https://project.mdnd-it.cc/work_packages/94
This commit is contained in:
Donat committed 2025-08-23 04:25:28 +02:00
1 parent 725516ad6c
commit 19cfa031d0
25823 files changed
+1095586 -2801759

No files matched your search

+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+66
View File
@@ -0,0 +1,66 @@
# For maintainers only
Development of MinIO JS SDK require nodejs14+ and [npm7+](https://www.npmjs.org/).
## Responsibilities
Go through [Maintainer Responsibility Guide](https://gist.github.com/abperiasamy/f4d9b31d3186bbd26522).
## Setup your minio-js Github Repository
Clone [minio-js](https://github.com/minio/minio-js/) source repository locally.
```sh
$ git clone git@github.com:minio/minio-js
$ cd minio-js
```
### Install deps
```shell
$ npm install
```
### Testing
```shell
$ npm test
```
## Publishing new release
Edit `package.json` version and all other files to the latest version as shown below.
```sh
$ git grep 3.2.0 | cut -f1 -d: | xargs sed s/3.2.0/3.2.1/g -i
$ grep version package.json
"version": "3.2.1",
$ git commit -a -m "Bump to 3.2.1 release"
```
### Publish to NPM
Login to your npm account.
```sh
$ npm login
...
Logged in as minio on https://registry.npmjs.org/.
```
Build for release
```sh
$ npm run build
```
Publish the new release to npm repository.
```
$ npm publish
```
### Tag
Tag and sign your release commit, additionally this step requires you to have access to MinIO's trusted private key.
```
$ export GNUPGHOME=/media/${USER}/minio/trusted
$ git tag -s 3.2.1
$ git push
$ git push --tags
```
### Announce
Announce new release by adding release notes at https://github.com/minio/minio-js/releases from `trusted@minio.io` account. Release notes requires two sections `highlights` and `changelog`. Highlights is a bulleted list of salient features in this release and Changelog contains list of all commits since the last release.
To generate `changelog`
```sh
git log --no-color --pretty=format:'-%d %s (%cr) <%an>' <last_release_tag>..<latest_release_tag>
```
+275
View File
@@ -0,0 +1,275 @@
# MinIO JavaScript Library for Amazon S3 Compatible Cloud Storage [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io)
[![NPM](https://nodei.co/npm/minio.png)](https://nodei.co/npm/minio/)
The MinIO JavaScript Client SDK provides high level APIs to access any Amazon S3 compatible object storage server.
This guide will show you how to install the client SDK and execute an example JavaScript program.
For a complete list of APIs and examples, please take a look at the [JavaScript Client API Reference](https://min.io/docs/minio/linux/developers/javascript/API.html) documentation.
This document presumes you have a working [Node.js](http://nodejs.org/) development environment, LTS versions v16, v18 or v20.
## Download from NPM
```sh
npm install --save minio
```
## Download from Source
```sh
git clone https://github.com/minio/minio-js
cd minio-js
npm install
npm run build
npm install -g
```
## Using with TypeScript
`minio>7.1.0` is shipped with builtin type definition, `@types/minio` is no longer needed.
## Initialize MinIO Client
The following parameters are needed to connect to a MinIO object storage server:
| Parameter | Description |
| :---------- | :--------------------------------------------------------------------------- |
| `endPoint` | Hostname of the object storage service. |
| `port` | TCP/IP port number. Optional, defaults to `80` for HTTP and `443` for HTTPs. |
| `accessKey` | Access key (user ID) of an account in the S3 service. |
| `secretKey` | Secret key (password) of an account in the S3 service. |
| `useSSL` | Optional, set to 'true' to enable secure (HTTPS) access. |
```js
import * as Minio from 'minio'
const minioClient = new Minio.Client({
endPoint: 'play.min.io',
port: 9000,
useSSL: true,
accessKey: 'Q3AM3UQ867SPQQA43P2F',
secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG',
})
```
## Quick Start Example - File Uploader
This example connects to an object storage server, creates a bucket, and uploads a file to the bucket.
It uses the MinIO `play` server, a public MinIO cluster located at [https://play.min.io](https://play.min.io).
The `play` server runs the latest stable version of MinIO and may be used for testing and development.
The access credentials shown in this example are open to the public.
All data uploaded to `play` should be considered public and non-protected.
#### file-uploader.mjs
```js
import * as Minio from 'minio'
// Instantiate the MinIO client with the object store service
// endpoint and an authorized user's credentials
// play.min.io is the MinIO public test cluster
const minioClient = new Minio.Client({
endPoint: 'play.min.io',
port: 9000,
useSSL: true,
accessKey: 'Q3AM3UQ867SPQQA43P2F',
secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG',
})
// File to upload
const sourceFile = '/tmp/test-file.txt'
// Destination bucket
const bucket = 'js-test-bucket'
// Destination object name
const destinationObject = 'my-test-file.txt'
// Check if the bucket exists
// If it doesn't, create it
const exists = await minioClient.bucketExists(bucket)
if (exists) {
console.log('Bucket ' + bucket + ' exists.')
} else {
await minioClient.makeBucket(bucket, 'us-east-1')
console.log('Bucket ' + bucket + ' created in "us-east-1".')
}
// Set the object metadata
var metaData = {
'Content-Type': 'text/plain',
'X-Amz-Meta-Testing': 1234,
example: 5678,
}
// Upload the file with fPutObject
// If an object with the same name exists,
// it is updated with new data
await minioClient.fPutObject(bucket, destinationObject, sourceFile, metaData)
console.log('File ' + sourceFile + ' uploaded as object ' + destinationObject + ' in bucket ' + bucket)
```
#### Run the File Uploader
```sh
node file-uploader.mjs
Bucket js-test-bucket created successfully in "us-east-1".
File /tmp/test-file.txt uploaded successfully as my-test-file.txt to bucket js-test-bucket
```
Verify the object was created with [`mc`](https://min.io/docs/minio/linux/reference/minio-mc.html):
```
mc ls play/js-test-bucket
[2023-11-10 17:52:20 UTC] 20KiB STANDARD my-test-file.txt
```
## API Reference
The complete API Reference is available here:
- [MinIO JavaScript API Reference](https://min.io/docs/minio/linux/developers/javascript/API.html)
### Bucket Operations
- [`makeBucket`](https://min.io/docs/minio/linux/developers/javascript/API.html#makeBucket)
- [`listBuckets`](https://min.io/docs/minio/linux/developers/javascript/API.html#listBuckets)
- [`bucketExists`](https://min.io/docs/minio/linux/developers/javascript/API.html#bucketExists)
- [`removeBucket`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeBucket)
- [`listObjects`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjects)
- [`listObjectsV2`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjectsV2)
- [`listObjectsV2WithMetadata`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjectsV2WithMetadata) (Extension)
- [`listIncompleteUploads`](https://min.io/docs/minio/linux/developers/javascript/API.html#listIncompleteUploads)
- [`getBucketVersioning`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketVersioning)
- [`setBucketVersioning`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketVersioning)
- [`setBucketLifecycle`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketLifecycle)
- [`getBucketLifecycle`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketLifecycle)
- [`removeBucketLifecycle`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeBucketLifecycle)
- [`getObjectLockConfig`](https://min.io/docs/minio/linux/developers/javascript/API.html#getObjectLockConfig)
- [`setObjectLockConfig`](https://min.io/docs/minio/linux/developers/javascript/API.html#setObjectLockConfig)
### File Object Operations
- [`fPutObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#fPutObject)
- [`fGetObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#fGetObject)
### Object Operations
- [`getObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#getObject)
- [`putObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#putObject)
- [`copyObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#copyObject)
- [`statObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#statObject)
- [`removeObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeObject)
- [`removeObjects`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeObjects)
- [`removeIncompleteUpload`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeIncompleteUpload)
- [`selectObjectContent`](https://min.io/docs/minio/linux/developers/javascript/API.html#selectObjectContent)
### Presigned Operations
- [`presignedUrl`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedUrl)
- [`presignedGetObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedGetObject)
- [`presignedPutObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedPutObject)
- [`presignedPostPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedPostPolicy)
### Bucket Notification Operations
- [`getBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketNotification)
- [`setBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketNotification)
- [`removeAllBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeAllBucketNotification)
- [`listenBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#listenBucketNotification) (MinIO Extension)
### Bucket Policy Operations
- [`getBucketPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketPolicy)
- [`setBucketPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketPolicy)
## Examples
#### Bucket Operations
- [list-buckets.mjs](https://github.com/minio/minio-js/blob/master/examples/list-buckets.mjs)
- [list-objects.js](https://github.com/minio/minio-js/blob/master/examples/list-objects.js)
- [list-objects-v2.js](https://github.com/minio/minio-js/blob/master/examples/list-objects-v2.js)
- [list-objects-v2-with-metadata.js](https://github.com/minio/minio-js/blob/master/examples/list-objects-v2-with-metadata.js) (Extension)
- [bucket-exists.mjs](https://github.com/minio/minio-js/blob/master/examples/bucket-exists.mjs)
- [make-bucket.mjs](https://github.com/minio/minio-js/blob/master/examples/make-bucket.js)
- [remove-bucket.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket.mjs)
- [list-incomplete-uploads.js](https://github.com/minio/minio-js/blob/master/examples/list-incomplete-uploads.js)
- [get-bucket-versioning.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-versioning.js)
- [set-bucket-versioning.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-versioning.js)
- [set-bucket-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-tagging.js)
- [get-bucket-versioning.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-versioning.js)
- [set-bucket-versioning.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-versioning.js)
- [set-bucket-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-tagging.js)
- [get-bucket-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-tagging.mjs)
- [remove-bucket-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket-tagging.js)
- [set-bucket-lifecycle.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-lifecycle.mjs)
- [get-bucket-lifecycle.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-lifecycle.mjs)
- [remove-bucket-lifecycle.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket-lifecycle.mjs)
- [get-object-lock-config.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object-lock-config.mjs)
- [set-object-lock-config.mjs](https://github.com/minio/minio-js/blob/master/examples/set-object-lock-config.mjs)
- [set-bucket-replication.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-replication.mjs)
- [get-bucket-replication.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-replication.mjs)
- [remove-bucket-replication.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket-replication.mjs)
- [set-bucket-encryption.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-encryption.mjs)
- [get-bucket-encryption.mjs](https://github.com/minio/minio-js/blob/master/examples/get-bucket-encryption.mjs)
- [remove-bucket-encryption.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket-encryption.mjs)
#### File Object Operations
- [fput-object.mjs](https://github.com/minio/minio-js/blob/master/examples/fput-object.js)
- [fget-object.mjs](https://github.com/minio/minio-js/blob/master/examples/fget-object.mjs)
#### Object Operations
- [put-object.js](https://github.com/minio/minio-js/blob/master/examples/put-object.js)
- [get-object.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object.mjs)
- [copy-object.js](https://github.com/minio/minio-js/blob/master/examples/copy-object.js)
- [get-partialobject.mjs](https://github.com/minio/minio-js/blob/master/examples/get-partialobject.mjs)
- [remove-object.js](https://github.com/minio/minio-js/blob/master/examples/remove-object.js)
- [remove-incomplete-upload.js](https://github.com/minio/minio-js/blob/master/examples/remove-incomplete-upload.js)
- [stat-object.mjs](https://github.com/minio/minio-js/blob/master/examples/stat-object.mjs)
- [get-object-retention.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object-retention.mjs)
- [put-object-retention.mjs](https://github.com/minio/minio-js/blob/master/examples/put-object-retention.mjs)
- [put-object-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/put-object-tagging.js)
- [get-object-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object-tagging.mjs)
- [remove-object-tagging.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-object-tagging.js)
- [set-object-legal-hold.mjs](https://github.com/minio/minio-js/blob/master/examples/set-object-legalhold.mjs)
- [get-object-legal-hold.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object-legal-hold.mjs)
- [compose-object.mjs](https://github.com/minio/minio-js/blob/master/examples/compose-object.js)
- [select-object-content.mjs](https://github.com/minio/minio-js/blob/master/examples/select-object-content.mjs)
#### Presigned Operations
- [presigned-getobject.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-getobject.js)
- [presigned-putobject.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-putobject.js)
- [presigned-postpolicy.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-postpolicy.js)
#### Bucket Notification Operations
- [get-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/get-bucket-notification.js)
- [set-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/set-bucket-notification.js)
- [remove-all-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/remove-all-bucket-notification.js)
- [listen-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/minio/listen-bucket-notification.js) (MinIO Extension)
#### Bucket Policy Operations
- [get-bucket-policy.js](https://github.com/minio/minio-js/blob/master/examples/get-bucket-policy.js)
- [set-bucket-policy.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-policy.mjs)
## Custom Settings
- [setAccelerateEndPoint](https://github.com/minio/minio-js/blob/master/examples/set-accelerate-end-point.js)
## Explore Further
- [Complete Documentation](https://min.io/docs/minio/kubernetes/upstream/index.html)
- [MinIO JavaScript Client SDK API Reference](https://min.io/docs/minio/linux/developers/javascript/API.html)
## Contribute
- [Contributors Guide](https://github.com/minio/minio-js/blob/master/CONTRIBUTING.md)
![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/minio/minio-js/nodejs.yml)
+200
View File
@@ -0,0 +1,200 @@
# 适用于Amazon S3兼容云存储的Minio JavaScript Library [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io)
[![NPM](https://nodei.co/npm/minio.png)](https://nodei.co/npm/minio/)
MinIO JavaScript Client SDK提供简单的API来访问任何Amazon S3兼容的对象存储服务。
本快速入门指南将向您展示如何安装客户端SDK并执行示例JavaScript程序。有关API和示例的完整列表,请参阅[JavaScript客户端API参考](https://min.io/docs/minio/linux/developers/javascript/API.html/javascript-client-api-reference)文档。
本文假设你已经安装了[nodejs](http://nodejs.org/) 。
## 使用NPM下载
`minio>7.1.0` 拥有自带的类型定义,不再需要安装 `@types/minio`。
## 下载并安装源码
```sh
git clone https://github.com/minio/minio-js
cd minio-js
npm install
npm install -g
```
## 初使化Minio Client
你需要设置5个属性来链接Minio对象存储服务。
| 参数 | 描述 |
| :------- | :------------ |
| endPoint |对象存储服务的URL |
|port| TCP/IP端口号。可选值,如果是使用HTTP的话,默认值是`80`;如果使用HTTPS的话,默认值是`443`。|
| accessKey | Access key是唯一标识你的账户的用户ID。 |
| secretKey | Secret key是你账户的密码。 |
|useSSL |true代表使用HTTPS |
```js
import * as Minio from 'minio'
const minioClient = new Minio.Client({
endPoint: 'play.min.io',
port: 9000,
useSSL: true,
accessKey: 'Q3AM3UQ867SPQQA43P2F',
secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG'
});
```
## 示例-文件上传
本示例连接到一个对象存储服务,创建一个存储桶并上传一个文件到存储桶中。
我们在本示例中使用运行在 [https://play.min.io](https://play.min.io) 上的Minio服务,你可以用这个服务来开发和测试。示例中的访问凭据是公开的。
#### file-uploader.js
```js
import * as Minio from 'minio'
// Instantiate the minio client with the endpoint
// and access keys as shown below.
const minioClient = new Minio.Client({
endPoint: 'play.min.io',
port: 9000,
useSSL: true,
accessKey: 'Q3AM3UQ867SPQQA43P2F',
secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG'
});
// File that needs to be uploaded.
const file = '/tmp/photos-europe.tar'
// Make a bucket called europetrip.
minioClient.makeBucket('europetrip', 'us-east-1', function(err) {
if (err) return console.log(err)
console.log('Bucket created successfully in "us-east-1".')
const metaData = {
'Content-Type': 'application/octet-stream',
'X-Amz-Meta-Testing': 1234,
'example': 5678
}
// Using fPutObject API upload your file to the bucket europetrip.
minioClient.fPutObject('europetrip', 'photos-europe.tar', file, metaData, function(err, etag) {
if (err) return console.log(err)
console.log('File uploaded successfully.')
});
});
```
#### 运行file-uploader
```sh
node file-uploader.js
Bucket created successfully in "us-east-1".
mc ls play/europetrip/
[2016-05-25 23:49:50 PDT] 17MiB photos-europe.tar
```
## API文档
完整的API文档在这里。
* [完整API文档](https://min.io/docs/minio/linux/developers/javascript/API.html)
### API文档 : 操作存储桶
* [`makeBucket`](https://min.io/docs/minio/linux/developers/javascript/API.html#makeBucket)
* [`listBuckets`](https://min.io/docs/minio/linux/developers/javascript/API.html#listBuckets)
* [`bucketExists`](https://min.io/docs/minio/linux/developers/javascript/API.html#bucketExists)
* [`removeBucket`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeBucket)
* [`listObjects`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjects)
* [`listObjectsV2`](https://min.io/docs/minio/linux/developers/javascript/API.html#listObjectsV2)
* [`listIncompleteUploads`](https://min.io/docs/minio/linux/developers/javascript/API.html#listIncompleteUploads)
### API文档 : 操作文件对象
* [`fPutObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#fPutObject)
* [`fGetObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#fGetObject)
### API文档 : 操作对象
* [`getObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#getObject)
* [`putObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#putObject)
* [`copyObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#copyObject)
* [`statObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#statObject)
* [`removeObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeObject)
* [`removeIncompleteUpload`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeIncompleteUpload)
### API文档 : Presigned操作
* [`presignedGetObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedGetObject)
* [`presignedPutObject`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedPutObject)
* [`presignedPostPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#presignedPostPolicy)
### API文档 : 存储桶通知
* [`getBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketNotification)
* [`setBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketNotification)
* [`removeAllBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#removeAllBucketNotification)
* [`listenBucketNotification`](https://min.io/docs/minio/linux/developers/javascript/API.html#listenBucketNotification) (MinIO Extension)
### API文档 : 存储桶策略
* [`getBucketPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#getBucketPolicy)
* [`setBucketPolicy`](https://min.io/docs/minio/linux/developers/javascript/API.html#setBucketPolicy)
## 完整示例
#### 完整示例 : 操作存储桶
* [list-buckets.js](https://github.com/minio/minio-js/blob/master/examples/list-buckets.js)
* [list-objects.js](https://github.com/minio/minio-js/blob/master/examples/list-objects.js)
* [list-objects-v2.js](https://github.com/minio/minio-js/blob/master/examples/list-objects-v2.js)
* [bucket-exists.mjs](https://github.com/minio/minio-js/blob/master/examples/bucket-exists.mjs)
* [make-bucket.mjs](https://github.com/minio/minio-js/blob/master/examples/make-bucket.js)
* [remove-bucket.mjs](https://github.com/minio/minio-js/blob/master/examples/remove-bucket.mjs)
* [list-incomplete-uploads.js](https://github.com/minio/minio-js/blob/master/examples/list-incomplete-uploads.js)
#### 完整示例 : 操作文件对象
* [fput-object.mjs](https://github.com/minio/minio-js/blob/master/examples/fput-object.js)
* [fget-object.mjs](https://github.com/minio/minio-js/blob/master/examples/fget-object.mjs)
#### 完整示例 : 操作对象
* [put-object.js](https://github.com/minio/minio-js/blob/master/examples/put-object.js)
* [get-object.mjs](https://github.com/minio/minio-js/blob/master/examples/get-object.mjs)
* [copy-object.js](https://github.com/minio/minio-js/blob/master/examples/copy-object.js)
* [get-partialobject.mjs](https://github.com/minio/minio-js/blob/master/examples/get-partialobject.mjs)
* [remove-object.js](https://github.com/minio/minio-js/blob/master/examples/remove-object.js)
* [remove-incomplete-upload.js](https://github.com/minio/minio-js/blob/master/examples/remove-incomplete-upload.js)
* [stat-object.mjs](https://github.com/minio/minio-js/blob/master/examples/stat-object.mjs)
#### 完整示例 : Presigned操作
* [presigned-getobject.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-getobject.js)
* [presigned-putobject.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-putobject.js)
* [presigned-postpolicy.mjs](https://github.com/minio/minio-js/blob/master/examples/presigned-postpolicy.js)
#### 完整示例 : 存储桶通知
* [get-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/get-bucket-notification.js)
* [set-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/set-bucket-notification.js)
* [remove-all-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/remove-all-bucket-notification.js)
* [listen-bucket-notification.js](https://github.com/minio/minio-js/blob/master/examples/minio/listen-bucket-notification.js) (MinIO Extension)
#### 完整示例 : 存储桶策略
* [get-bucket-policy.js](https://github.com/minio/minio-js/blob/master/examples/get-bucket-policy.js)
* [set-bucket-policy.mjs](https://github.com/minio/minio-js/blob/master/examples/set-bucket-policy.mjs)
## 了解更多
* [完整文档]([https://docs.min.i](https://min.io/docs/minio/kubernetes/upstream/index.html)o)
* [MinIO JavaScript Client SDK API文档](https://min.io/docs/minio/linux/developers/javascript/API.html)
* [创建属于你的购物APP-完整示例](https://github.com/minio/minio-js-store-app)
## 贡献
[贡献者指南](https://github.com/minio/minio-js/blob/master/CONTRIBUTING.md)
[![Build Status](https://travis-ci.org/minio/minio-js.svg)](https://travis-ci.org/minio/minio-js)
[![Build status](https://ci.appveyor.com/api/projects/status/1d05e6nvxcelmrak?svg=true)](https://ci.appveyor.com/project/harshavardhana/minio-js)
@@ -0,0 +1,86 @@
/// <reference types="node" />
import * as http from 'node:http';
import { CredentialProvider } from "./CredentialProvider.mjs";
import { Credentials } from "./Credentials.mjs";
/**
* @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html
*/
type CredentialResponse = {
ErrorResponse?: {
Error?: {
Code?: string;
Message?: string;
};
};
AssumeRoleResponse: {
AssumeRoleResult: {
Credentials: {
AccessKeyId: string;
SecretAccessKey: string;
SessionToken: string;
Expiration: string;
};
};
};
};
export interface AssumeRoleProviderOptions {
stsEndpoint: string;
accessKey: string;
secretKey: string;
durationSeconds?: number;
sessionToken?: string;
policy?: string;
region?: string;
roleArn?: string;
roleSessionName?: string;
externalId?: string;
token?: string;
webIdentityToken?: string;
action?: string;
transportAgent?: http.Agent;
}
export declare class AssumeRoleProvider extends CredentialProvider {
private readonly stsEndpoint;
private readonly accessKey;
private readonly secretKey;
private readonly durationSeconds;
private readonly policy?;
private readonly region;
private readonly roleArn?;
private readonly roleSessionName?;
private readonly externalId?;
private readonly token?;
private readonly webIdentityToken?;
private readonly action;
private _credentials;
private readonly expirySeconds;
private accessExpiresAt;
private readonly transportAgent?;
private readonly transport;
constructor({
stsEndpoint,
accessKey,
secretKey,
durationSeconds,
sessionToken,
policy,
region,
roleArn,
roleSessionName,
externalId,
token,
webIdentityToken,
action,
transportAgent
}: AssumeRoleProviderOptions);
getRequestConfig(): {
requestOptions: http.RequestOptions;
requestData: string;
};
performRequest(): Promise<CredentialResponse>;
parseCredentials(respObj: CredentialResponse): Credentials;
refreshCredentials(): Promise<Credentials>;
getCredentials(): Promise<Credentials>;
isAboutToExpire(): boolean;
}
export default AssumeRoleProvider;
+183
View File
@@ -0,0 +1,183 @@
import * as http from "http";
import * as https from "https";
import { URL, URLSearchParams } from "url";
import { CredentialProvider } from "./CredentialProvider.mjs";
import { Credentials } from "./Credentials.mjs";
import { makeDateLong, parseXml, toSha256 } from "./internal/helper.mjs";
import { request } from "./internal/request.mjs";
import { readAsString } from "./internal/response.mjs";
import { signV4ByServiceName } from "./signing.mjs";
/**
* @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html
*/
const defaultExpirySeconds = 900;
export class AssumeRoleProvider extends CredentialProvider {
accessExpiresAt = '';
constructor({
stsEndpoint,
accessKey,
secretKey,
durationSeconds = defaultExpirySeconds,
sessionToken,
policy,
region = '',
roleArn,
roleSessionName,
externalId,
token,
webIdentityToken,
action = 'AssumeRole',
transportAgent = undefined
}) {
super({
accessKey,
secretKey,
sessionToken
});
this.stsEndpoint = new URL(stsEndpoint);
this.accessKey = accessKey;
this.secretKey = secretKey;
this.policy = policy;
this.region = region;
this.roleArn = roleArn;
this.roleSessionName = roleSessionName;
this.externalId = externalId;
this.token = token;
this.webIdentityToken = webIdentityToken;
this.action = action;
this.durationSeconds = parseInt(durationSeconds);
let expirySeconds = this.durationSeconds;
if (this.durationSeconds < defaultExpirySeconds) {
expirySeconds = defaultExpirySeconds;
}
this.expirySeconds = expirySeconds; // for calculating refresh of credentials.
// By default, nodejs uses a global agent if the 'agent' property
// is set to undefined. Otherwise, it's okay to assume the users
// know what they're doing if they specify a custom transport agent.
this.transportAgent = transportAgent;
const isHttp = this.stsEndpoint.protocol === 'http:';
this.transport = isHttp ? http : https;
/**
* Internal Tracking variables
*/
this._credentials = null;
}
getRequestConfig() {
const hostValue = this.stsEndpoint.hostname;
const portValue = this.stsEndpoint.port;
const qryParams = new URLSearchParams({
Action: this.action,
Version: '2011-06-15'
});
qryParams.set('DurationSeconds', this.expirySeconds.toString());
if (this.policy) {
qryParams.set('Policy', this.policy);
}
if (this.roleArn) {
qryParams.set('RoleArn', this.roleArn);
}
if (this.roleSessionName != null) {
qryParams.set('RoleSessionName', this.roleSessionName);
}
if (this.token != null) {
qryParams.set('Token', this.token);
}
if (this.webIdentityToken) {
qryParams.set('WebIdentityToken', this.webIdentityToken);
}
if (this.externalId) {
qryParams.set('ExternalId', this.externalId);
}
const urlParams = qryParams.toString();
const contentSha256 = toSha256(urlParams);
const date = new Date();
const requestOptions = {
hostname: hostValue,
port: portValue,
path: '/',
protocol: this.stsEndpoint.protocol,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'content-length': urlParams.length.toString(),
host: hostValue,
'x-amz-date': makeDateLong(date),
'x-amz-content-sha256': contentSha256
},
agent: this.transportAgent
};
requestOptions.headers.authorization = signV4ByServiceName(requestOptions, this.accessKey, this.secretKey, this.region, date, contentSha256, 'sts');
return {
requestOptions,
requestData: urlParams
};
}
async performRequest() {
const {
requestOptions,
requestData
} = this.getRequestConfig();
const res = await request(this.transport, requestOptions, requestData);
const body = await readAsString(res);
return parseXml(body);
}
parseCredentials(respObj) {
if (respObj.ErrorResponse) {
var _respObj$ErrorRespons, _respObj$ErrorRespons2, _respObj$ErrorRespons3, _respObj$ErrorRespons4;
throw new Error(`Unable to obtain credentials: ${(_respObj$ErrorRespons = respObj.ErrorResponse) === null || _respObj$ErrorRespons === void 0 ? void 0 : (_respObj$ErrorRespons2 = _respObj$ErrorRespons.Error) === null || _respObj$ErrorRespons2 === void 0 ? void 0 : _respObj$ErrorRespons2.Code} ${(_respObj$ErrorRespons3 = respObj.ErrorResponse) === null || _respObj$ErrorRespons3 === void 0 ? void 0 : (_respObj$ErrorRespons4 = _respObj$ErrorRespons3.Error) === null || _respObj$ErrorRespons4 === void 0 ? void 0 : _respObj$ErrorRespons4.Message}`, {
cause: respObj
});
}
const {
AssumeRoleResponse: {
AssumeRoleResult: {
Credentials: {
AccessKeyId: accessKey,
SecretAccessKey: secretKey,
SessionToken: sessionToken,
Expiration: expiresAt
}
}
}
} = respObj;
this.accessExpiresAt = expiresAt;
return new Credentials({
accessKey,
secretKey,
sessionToken
});
}
async refreshCredentials() {
try {
const assumeRoleCredentials = await this.performRequest();
this._credentials = this.parseCredentials(assumeRoleCredentials);
} catch (err) {
throw new Error(`Failed to get Credentials: ${err}`, {
cause: err
});
}
return this._credentials;
}
async getCredentials() {
if (this._credentials && !this.isAboutToExpire()) {
return this._credentials;
}
this._credentials = await this.refreshCredentials();
return this._credentials;
}
isAboutToExpire() {
const expiresAt = new Date(this.accessExpiresAt);
const provisionalExpiry = new Date(Date.now() + 1000 * 10); // check before 10 seconds.
return provisionalExpiry > expiresAt;
}
}
// deprecated default export, please use named exports.
// keep for backward compatibility.
// eslint-disable-next-line import/no-default-export
export default AssumeRoleProvider;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJodHRwIiwiaHR0cHMiLCJVUkwiLCJVUkxTZWFyY2hQYXJhbXMiLCJDcmVkZW50aWFsUHJvdmlkZXIiLCJDcmVkZW50aWFscyIsIm1ha2VEYXRlTG9uZyIsInBhcnNlWG1sIiwidG9TaGEyNTYiLCJyZXF1ZXN0IiwicmVhZEFzU3RyaW5nIiwic2lnblY0QnlTZXJ2aWNlTmFtZSIsImRlZmF1bHRFeHBpcnlTZWNvbmRzIiwiQXNzdW1lUm9sZVByb3ZpZGVyIiwiYWNjZXNzRXhwaXJlc0F0IiwiY29uc3RydWN0b3IiLCJzdHNFbmRwb2ludCIsImFjY2Vzc0tleSIsInNlY3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ZUFybixcbiAgICByb2xlU2Vzc2lvbk5hbWUsXG4gICAgZXh0ZXJuYWxJZCxcbiAgICB0b2tlbixcbiAgICB3ZWJJZGVudGl0eVRva2VuLFxuICAgIGFjdGlvbiA9ICdBc3N1bWVSb2xlJyxcbiAgICB0cmFuc3BvcnRBZ2VudCA9IHVuZGVmaW5lZCxcbiAgfTogQXNzdW1lUm9sZVByb3ZpZGVyT3B0aW9 Line truncated
@@ -0,0 +1,22 @@
import { Credentials } from "./Credentials.mjs";
export declare class CredentialProvider {
private credentials;
constructor({
accessKey,
secretKey,
sessionToken
}: {
accessKey: string;
secretKey: string;
sessionToken?: string;
});
getCredentials(): Promise<Credentials>;
setCredentials(credentials: Credentials): void;
setAccessKey(accessKey: string): void;
getAccessKey(): string;
setSecretKey(secretKey: string): void;
getSecretKey(): string;
setSessionToken(sessionToken: string): void;
getSessionToken(): string | undefined;
}
export default CredentialProvider;
+48
View File
@@ -0,0 +1,48 @@
import { Credentials } from "./Credentials.mjs";
export class CredentialProvider {
constructor({
accessKey,
secretKey,
sessionToken
}) {
this.credentials = new Credentials({
accessKey,
secretKey,
sessionToken
});
}
async getCredentials() {
return this.credentials.get();
}
setCredentials(credentials) {
if (credentials instanceof Credentials) {
this.credentials = credentials;
} else {
throw new Error('Unable to set Credentials. it should be an instance of Credentials class');
}
}
setAccessKey(accessKey) {
this.credentials.setAccessKey(accessKey);
}
getAccessKey() {
return this.credentials.getAccessKey();
}
setSecretKey(secretKey) {
this.credentials.setSecretKey(secretKey);
}
getSecretKey() {
return this.credentials.getSecretKey();
}
setSessionToken(sessionToken) {
this.credentials.setSessionToken(sessionToken);
}
getSessionToken() {
return this.credentials.getSessionToken();
}
}
// deprecated default export, please use named exports.
// keep for backward compatibility.
// eslint-disable-next-line import/no-default-export
export default CredentialProvider;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDcmVkZW50aWFscyIsIkNyZWRlbnRpYWxQcm92a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UEsRUFBRztJQUNiLE9BQU8sSUFBSSxDQUFDUixXQUFXLENBQUNRLFlBQVksQ0FBQyxDQUFDO0VBQ3hDO0VBRUFDLGVBQWVBLENBQUNWLFlBQW9CLEVBQUU7SUFDcEMsSUFBSSxDQUFDQyxXQUFXLENBQUNTLGVBQWUsQ0FBQ1YsWUFBWSxDQUFDO0VBQ2hEO0VBRUFXLGVBQWVBLENBQUEsRUFBRztJQUNoQixPQUFPLElBQUksQ0FBQ1YsV0FBVyxDQUFDVSxlQUFlLENBQUMsQ0FBQztFQUMzQztBQUNGOztBQUVBO0FBQ0E7QUFDQTtBQUNBLGVBQWVmLGtCQUFrQiJ9
+22
View File
@@ -0,0 +1,22 @@
export declare class Credentials {
accessKey: string;
secretKey: string;
sessionToken?: string;
constructor({
accessKey,
secretKey,
sessionToken
}: {
accessKey: string;
secretKey: string;
sessionToken?: string;
});
setAccessKey(accessKey: string): void;
getAccessKey(): string;
setSecretKey(secretKey: string): void;
getSecretKey(): string;
setSessionToken(sessionToken: string): void;
getSessionToken(): string | undefined;
get(): Credentials;
}
export default Credentials;
+38
View File
@@ -0,0 +1,38 @@
export class Credentials {
constructor({
accessKey,
secretKey,
sessionToken
}) {
this.accessKey = accessKey;
this.secretKey = secretKey;
this.sessionToken = sessionToken;
}
setAccessKey(accessKey) {
this.accessKey = accessKey;
}
getAccessKey() {
return this.accessKey;
}
setSecretKey(secretKey) {
this.secretKey = secretKey;
}
getSecretKey() {
return this.secretKey;
}
setSessionToken(sessionToken) {
this.sessionToken = sessionToken;
}
getSessionToken() {
return this.sessionToken;
}
get() {
return this;
}
}
// deprecated default export, please use named exports.
// keep for backward compatibility.
// eslint-disable-next-line import/no-default-export
export default Credentials;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDcmVkZW50aWFscyIsImNvbnN0cnVjdG9yIiwiYWNjZXNzS2V5Iiwic2VjcmV0S2V5Iiwic2Vzc2lvblRva2VuIi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N2QjtFQUVBTSxlQUFlQSxDQUFDTCxZQUFvQixFQUFFO0lBQ3BDLElBQUksQ0FBQ0EsWUFBWSxHQUFHQSxZQUFZO0VBQ2xDO0VBRUFNLGVBQWVBLENBQUEsRUFBRztJQUNoQixPQUFPLElBQUksQ0FBQ04sWUFBWTtFQUMxQjtFQUVBTyxHQUFHQSxDQUFBLEVBQWdCO0lBQ2pCLE9BQU8sSUFBSTtFQUNiO0FBQ0Y7O0FBRUE7QUFDQTtBQUNBO0FBQ0EsZUFBZVgsV0FBVyJ9
+27
View File
@@ -0,0 +1,27 @@
/// <reference types="node" />
import * as http from 'node:http';
import { CredentialProvider } from "./CredentialProvider.mjs";
import { Credentials } from "./Credentials.mjs";
export interface IamAwsProviderOptions {
customEndpoint?: string;
transportAgent?: http.Agent;
}
export declare class IamAwsProvider extends CredentialProvider {
private readonly customEndpoint?;
private _credentials;
private readonly transportAgent?;
private accessExpiresAt;
constructor({
customEndpoint,
transportAgent
}: IamAwsProviderOptions);
getCredentials(): Promise<Credentials>;
private fetchCredentials;
private fetchCredentialsUsingTokenFile;
private fetchImdsToken;
private getIamRoleNamedUrl;
private getIamRoleName;
private requestCredentials;
private isAboutToExpire;
}
export default IamAwsProvider;
+189
View File
@@ -0,0 +1,189 @@
import * as fs from "fs/promises";
import * as http from "http";
import * as https from "https";
import { URL, URLSearchParams } from "url";
import { CredentialProvider } from "./CredentialProvider.mjs";
import { Credentials } from "./Credentials.mjs";
import { parseXml } from "./internal/helper.mjs";
import { request } from "./internal/request.mjs";
import { readAsString } from "./internal/response.mjs";
export class IamAwsProvider extends CredentialProvider {
accessExpiresAt = '';
constructor({
customEndpoint = undefined,
transportAgent = undefined
}) {
super({
accessKey: '',
secretKey: ''
});
this.customEndpoint = customEndpoint;
this.transportAgent = transportAgent;
/**
* Internal Tracking variables
*/
this._credentials = null;
}
async getCredentials() {
if (!this._credentials || this.isAboutToExpire()) {
this._credentials = await this.fetchCredentials();
}
return this._credentials;
}
async fetchCredentials() {
try {
// check for IRSA (https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html)
const tokenFile = process.env.AWS_WEB_IDENTITY_TOKEN_FILE;
if (tokenFile) {
return await this.fetchCredentialsUsingTokenFile(tokenFile);
}
// try with IAM role for EC2 instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html)
let tokenHeader = 'Authorization';
let token = process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;
const relativeUri = process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI;
const fullUri = process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI;
let url;
if (relativeUri) {
url = new URL(relativeUri, 'http://169.254.170.2');
} else if (fullUri) {
url = new URL(fullUri);
} else {
token = await this.fetchImdsToken();
tokenHeader = 'X-aws-ec2-metadata-token';
url = await this.getIamRoleNamedUrl(token);
}
return this.requestCredentials(url, tokenHeader, token);
} catch (err) {
throw new Error(`Failed to get Credentials: ${err}`, {
cause: err
});
}
}
async fetchCredentialsUsingTokenFile(tokenFile) {
const token = await fs.readFile(tokenFile, {
encoding: 'utf8'
});
const region = process.env.AWS_REGION;
const stsEndpoint = new URL(region ? `https://sts.${region}.amazonaws.com` : 'https://sts.amazonaws.com');
const hostValue = stsEndpoint.hostname;
const portValue = stsEndpoint.port;
const qryParams = new URLSearchParams({
Action: 'AssumeRoleWithWebIdentity',
Version: '2011-06-15'
});
const roleArn = process.env.AWS_ROLE_ARN;
if (roleArn) {
qryParams.set('RoleArn', roleArn);
const roleSessionName = process.env.AWS_ROLE_SESSION_NAME;
qryParams.set('RoleSessionName', roleSessionName ? roleSessionName : Date.now().toString());
}
qryParams.set('WebIdentityToken', token);
qryParams.sort();
const requestOptions = {
hostname: hostValue,
port: portValue,
path: `${stsEndpoint.pathname}?${qryParams.toString()}`,
protocol: stsEndpoint.protocol,
method: 'POST',
headers: {},
agent: this.transportAgent
};
const transport = stsEndpoint.protocol === 'http:' ? http : https;
const res = await request(transport, requestOptions, null);
const body = await readAsString(res);
const assumeRoleResponse = parseXml(body);
const creds = assumeRoleResponse.AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult.Credentials;
this.accessExpiresAt = creds.Expiration;
return new Credentials({
accessKey: creds.AccessKeyId,
secretKey: creds.SecretAccessKey,
sessionToken: creds.SessionToken
});
}
async fetchImdsToken() {
const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254';
const url = new URL('/latest/api/token', endpoint);
const requestOptions = {
hostname: url.hostname,
port: url.port,
path: `${url.pathname}${url.search}`,
protocol: url.protocol,
method: 'PUT',
headers: {
'X-aws-ec2-metadata-token-ttl-seconds': '21600'
},
agent: this.transportAgent
};
const transport = url.protocol === 'http:' ? http : https;
const res = await request(transport, requestOptions, null);
return await readAsString(res);
}
async getIamRoleNamedUrl(token) {
const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254';
const url = new URL('latest/meta-data/iam/security-credentials/', endpoint);
const roleName = await this.getIamRoleName(url, token);
return new URL(`${url.pathname}/${encodeURIComponent(roleName)}`, url.origin);
}
async getIamRoleName(url, token) {
const requestOptions = {
hostname: url.hostname,
port: url.port,
path: `${url.pathname}${url.search}`,
protocol: url.protocol,
method: 'GET',
headers: {
'X-aws-ec2-metadata-token': token
},
agent: this.transportAgent
};
const transport = url.protocol === 'http:' ? http : https;
const res = await request(transport, requestOptions, null);
const body = await readAsString(res);
const roleNames = body.split(/\r\n|[\n\r\u2028\u2029]/);
if (roleNames.length === 0) {
throw new Error(`No IAM roles attached to EC2 service ${url}`);
}
return roleNames[0];
}
async requestCredentials(url, tokenHeader, token) {
const headers = {};
if (token) {
headers[tokenHeader] = token;
}
const requestOptions = {
hostname: url.hostname,
port: url.port,
path: `${url.pathname}${url.search}`,
protocol: url.protocol,
method: 'GET',
headers: headers,
agent: this.transportAgent
};
const transport = url.protocol === 'http:' ? http : https;
const res = await request(transport, requestOptions, null);
const body = await readAsString(res);
const ecsCredentials = JSON.parse(body);
if (!ecsCredentials.Code || ecsCredentials.Code != 'Success') {
throw new Error(`${url} failed with code ${ecsCredentials.Code} and message ${ecsCredentials.Message}`);
}
this.accessExpiresAt = ecsCredentials.Expiration;
return new Credentials({
accessKey: ecsCredentials.AccessKeyID,
secretKey: ecsCredentials.SecretAccessKey,
sessionToken: ecsCredentials.Token
});
}
isAboutToExpire() {
const expiresAt = new Date(this.accessExpiresAt);
const provisionalExpiry = new Date(Date.now() + 1000 * 10); // 10 seconds leeway
return provisionalExpiry > expiresAt;
}
}
// deprecated default export, please use named exports.
// keep for backward compatibility.
// eslint-disable-next-line import/no-default-export
export default IamAwsProvider;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmcyIsImh0dHAiLCJodHRwcyIsIlVSTCIsIlVSTFNlYXJjaFBhcmFtcyIsIkNyZWRlbnRpYWxQcm92aWRlciIsIkNyZWRlbnRpYWxzIiwicGFyc2VYbWwiLCJyZXF1ZXN0IiwicmVhZEFzU3RyaW5nIiwiSWFtQXdzUHJvdmlkZXIiLCJhY2Nlc3NFeHBpcmVzQXQiLCJjb25zdHJ1Y3RvciIsImN1c3RvbUVuZHBvaW50IiwidW5kZWZpbmVkIiwidHJhbnNwb3J0QWdlbnQiLCJhY2Nlc3NLZXkiLCJzZWNyZXRLZXkiLCJfY3JlZGVudGlhbHMiLCJnZXRDcmVkZW50aWFscyIsImlzQWJvdXRUb0V4cGlyZSIsImZldGNoQ3JlZGVudGlhbHMiLCJ0b2tlbkZpbGUiLCJwcm9jZXNzIiwiZW52IiwiQVdTX1dFQl9JREVOVElUWV9UT0tFTl9GSUxFIiwiZmV0Y2hDcmVkZW50aWFsc1VzaW5nVG9rZW5GaWxlIiwidG9rZW5IZWFkZXIiLCJ0b2tlbiIsIkFXU19DT05UQUlORVJfQVVUSE9SSVpBVElPTl9UT0tFTiIsInJlbGF0aXZlVXJpIiwiQVdTX0NPTlRBSU5FUl9DUkVERU5USUFMU19SR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ZWRlbnRpYWxzID0gbnVsbFxuICB9XG5cbiAgYXN5bmMgZ2V0Q3JlZGVudGlhbHMoKTogUHJvbWlzZTxDcmVkZW50aWFscz4ge1xuICAgIGlmICghdGhpcy5fY3JlZGVudGlhbHMgfHwgdGhpcy5pc0Fib3V0VG9FeHBpcmUoKSkge1xuICAgICAgdGhpcy5fY3JlZGVudGlhbHMgPSBhd2FpdCB0aGlzLmZldGNoQ3JlZGVudGlhbHMoKVxuICAgIH1cbiAgICByZXR1cm4gdGhpcy5fY3JlZGVudGlhbHNcbiAgfVxuXG4gIHByaXZhdGUgYXN5bmMgZmV0Y2hDcmVkZW50aWFscygpOiBQcm9taXNlPENyZWRlbnRpYWxzPiB7XG4gICAgdHJ5IHtcbiAgICAgIC8vIGNoZWNrIGZvciBJUlNBIChodHRwczovL2RvY3MuYXdzLmFtYXpvbi5jb20vZWtzL2xhdGVzdC91c2VyZ3VpZGUvaWFtLXJvbGVzLWZvci1zZXJ2aWNlLWFjY291bnRzLmh0bWwpXG4gICAgICBjb25zdCB0b2tlbkZpbGUgPSBwcm9jZXNzLmVudi5BV1NfV0VCX0lERU5USVRZX1RPS0VOX0ZJTEVcbiAgICAgIGlmICh0b2tlbkZpbGUpIHtcbiAgICAgICAgcmV0dXJuIGF3YWl0IHRoaXMuZmV0Y2hDcmVkZW50aWFsc1VzaW5nVG9rZW5GaWxlKHRva2VuRmlsZSlcbiAgICAgIH1cblxuICAgICAgLy8gdHJ5IHdpdGggSUFNIHJvbGUgZm9yIEVDMiBpbnN0YW5jZXMgKGh0dHBzOi8vZG9jcy5hd3MuYW1hem9uLmNvbS9BV1NFQzIvbGF0ZXN0L1VzZXJHdWlkZS9pYW0tcm9sZXMtZm9yLWFtYXpvbi1lYzIuaHRtbClcbiAgICAgIGxldCB0b2tlbkhlYWRlciA9ICdBdXRob3JpemF0aW9uJ1xuICAgICAgbGV0IHRva2V Line truncated
+82
View File
@@ -0,0 +1,82 @@
/// <reference lib="es2022.error" />
declare class ExtendableError extends Error {
constructor(message?: string, opt?: ErrorOptions);
}
/**
* AnonymousRequestError is generated for anonymous keys on specific
* APIs. NOTE: PresignedURL generation always requires access keys.
*/
export declare class AnonymousRequestError extends ExtendableError {}
/**
* InvalidArgumentError is generated for all invalid arguments.
*/
export declare class InvalidArgumentError extends ExtendableError {}
/**
* InvalidPortError is generated when a non integer value is provided
* for ports.
*/
export declare class InvalidPortError extends ExtendableError {}
/**
* InvalidEndpointError is generated when an invalid end point value is
* provided which does not follow domain standards.
*/
export declare class InvalidEndpointError extends ExtendableError {}
/**
* InvalidBucketNameError is generated when an invalid bucket name is
* provided which does not follow AWS S3 specifications.
* http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
*/
export declare class InvalidBucketNameError extends ExtendableError {}
/**
* InvalidObjectNameError is generated when an invalid object name is
* provided which does not follow AWS S3 specifications.
* http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
*/
export declare class InvalidObjectNameError extends ExtendableError {}
/**
* AccessKeyRequiredError generated by signature methods when access
* key is not found.
*/
export declare class AccessKeyRequiredError extends ExtendableError {}
/**
* SecretKeyRequiredError generated by signature methods when secret
* key is not found.
*/
export declare class SecretKeyRequiredError extends ExtendableError {}
/**
* ExpiresParamError generated when expires parameter value is not
* well within stipulated limits.
*/
export declare class ExpiresParamError extends ExtendableError {}
/**
* InvalidDateError generated when invalid date is found.
*/
export declare class InvalidDateError extends ExtendableError {}
/**
* InvalidPrefixError generated when object prefix provided is invalid
* or does not conform to AWS S3 object key restrictions.
*/
export declare class InvalidPrefixError extends ExtendableError {}
/**
* InvalidBucketPolicyError generated when the given bucket policy is invalid.
*/
export declare class InvalidBucketPolicyError extends ExtendableError {}
/**
* IncorrectSizeError generated when total data read mismatches with
* the input size.
*/
export declare class IncorrectSizeError extends ExtendableError {}
/**
* InvalidXMLError generated when an unknown XML is found.
*/
export declare class InvalidXMLError extends ExtendableError {}
/**
* S3Error is generated for errors returned from S3 server.
* see getErrorTransformer for details
*/
export declare class S3Error extends ExtendableError {
code?: string;
region?: string;
}
export declare class IsValidBucketNameError extends ExtendableError {}
export {};
+117
View File
@@ -0,0 +1,117 @@
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference lib="ES2022.Error" />
class ExtendableError extends Error {
constructor(message, opt) {
// error Option {cause?: unknown} is a 'nice to have',
// don't use it internally
super(message, opt);
// set error name, otherwise it's always 'Error'
this.name = this.constructor.name;
}
}
/**
* AnonymousRequestError is generated for anonymous keys on specific
* APIs. NOTE: PresignedURL generation always requires access keys.
*/
export class AnonymousRequestError extends ExtendableError {}
/**
* InvalidArgumentError is generated for all invalid arguments.
*/
export class InvalidArgumentError extends ExtendableError {}
/**
* InvalidPortError is generated when a non integer value is provided
* for ports.
*/
export class InvalidPortError extends ExtendableError {}
/**
* InvalidEndpointError is generated when an invalid end point value is
* provided which does not follow domain standards.
*/
export class InvalidEndpointError extends ExtendableError {}
/**
* InvalidBucketNameError is generated when an invalid bucket name is
* provided which does not follow AWS S3 specifications.
* http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
*/
export class InvalidBucketNameError extends ExtendableError {}
/**
* InvalidObjectNameError is generated when an invalid object name is
* provided which does not follow AWS S3 specifications.
* http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
*/
export class InvalidObjectNameError extends ExtendableError {}
/**
* AccessKeyRequiredError generated by signature methods when access
* key is not found.
*/
export class AccessKeyRequiredError extends ExtendableError {}
/**
* SecretKeyRequiredError generated by signature methods when secret
* key is not found.
*/
export class SecretKeyRequiredError extends ExtendableError {}
/**
* ExpiresParamError generated when expires parameter value is not
* well within stipulated limits.
*/
export class ExpiresParamError extends ExtendableError {}
/**
* InvalidDateError generated when invalid date is found.
*/
export class InvalidDateError extends ExtendableError {}
/**
* InvalidPrefixError generated when object prefix provided is invalid
* or does not conform to AWS S3 object key restrictions.
*/
export class InvalidPrefixError extends ExtendableError {}
/**
* InvalidBucketPolicyError generated when the given bucket policy is invalid.
*/
export class InvalidBucketPolicyError extends ExtendableError {}
/**
* IncorrectSizeError generated when total data read mismatches with
* the input size.
*/
export class IncorrectSizeError extends ExtendableError {}
/**
* InvalidXMLError generated when an unknown XML is found.
*/
export class InvalidXMLError extends ExtendableError {}
/**
* S3Error is generated for errors returned from S3 server.
* see getErrorTransformer for details
*/
export class S3Error extends ExtendableError {}
export class IsValidBucketNameError extends ExtendableError {}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFeHRlbmRhYmxlRXJyb3IiLCJFcnJvciIsImNvbnN0cnVjdG9yIiwibWVzc2FnZSIsIm9wdCIsIm5hbWUiLCJBbm9ueW1vdXNSZXF1ZXN0RXJyb3IiLCJJbnZhbGlkQXJndW1lbnRFcnJvciIsIkludmFsaWRQb3J0RXJyb3IiLCJJbnZhbGlkRW5kcG9pbnRFcnJvciIsIkludmFsaWRCdWNrZXROYW1lRXJyb3IiLCJJbnZhbGlkT2JqZWN0TmFtZUVycm9yIiwiQWNjZXNzS2V5UmVxdWlyZWRFcnJvciIsIlNlY3JldEtleVJlcXVpcmVkRXJyb3IiLCJFeHBpcmVzUGFyYW1FcnJvciIsIkludmFsaWREYXRlRXJyb3IiLCJJbnZhbGlkUHJlZml4RXJyb3IiLCJJbnZhbGlkQnVja2V0UG9saWN5RXJyb3IiLCJJbmNvcnJlY3RTaXplRXJyb3IiLCJJbnZhbGlkWE1MRXJyb3IiLCJTM0Vycm9yIiwiSXNWYWxpZEJ1Y2tldE5hbWVFcnJvciJ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yIGdlbmVyYXRlZCB3aGVuIHRoZSBnaXZlbiBidWNrZXQgcG9saWN5IGlzIGludmFsaWQuXG4 Line truncated
+156
View File
@@ -0,0 +1,156 @@
import type { Encryption, ObjectMetaData, RequestHeaders } from "./internal/type.mjs";
import { RETENTION_MODES } from "./internal/type.mjs";
export { ENCRYPTION_TYPES, LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./internal/type.mjs";
export declare const DEFAULT_REGION = "us-east-1";
export declare const PRESIGN_EXPIRY_DAYS_MAX: number;
export interface ICopySourceOptions {
Bucket: string;
Object: string;
/**
* Valid versionId
*/
VersionID?: string;
/**
* Etag to match
*/
MatchETag?: string;
/**
* Etag to exclude
*/
NoMatchETag?: string;
/**
* Modified Date of the object/part. UTC Date in string format
*/
MatchModifiedSince?: string | null;
/**
* Modified Date of the object/part to exclude UTC Date in string format
*/
MatchUnmodifiedSince?: string | null;
/**
* true or false Object range to match
*/
MatchRange?: boolean;
Start?: number;
End?: number;
Encryption?: Encryption;
}
export declare class CopySourceOptions {
readonly Bucket: string;
readonly Object: string;
readonly VersionID: string;
MatchETag: string;
private readonly NoMatchETag;
private readonly MatchModifiedSince;
private readonly MatchUnmodifiedSince;
readonly MatchRange: boolean;
readonly Start: number;
readonly End: number;
private readonly Encryption?;
constructor({
Bucket,
Object,
VersionID,
MatchETag,
NoMatchETag,
MatchModifiedSince,
MatchUnmodifiedSince,
MatchRange,
Start,
End,
Encryption
}: ICopySourceOptions);
validate(): boolean;
getHeaders(): RequestHeaders;
}
/**
* @deprecated use nodejs fs module
*/
export declare function removeDirAndFiles(dirPath: string, removeSelf?: boolean): void;
export interface ICopyDestinationOptions {
/**
* Bucket name
*/
Bucket: string;
/**
* Object Name for the destination (composed/copied) object defaults
*/
Object: string;
/**
* Encryption configuration defaults to {}
* @default {}
*/
Encryption?: Encryption;
UserMetadata?: ObjectMetaData;
/**
* query-string encoded string or Record<string, string> Object
*/
UserTags?: Record<string, string> | string;
LegalHold?: 'on' | 'off';
/**
* UTC Date String
*/
RetainUntilDate?: string;
Mode?: RETENTION_MODES;
MetadataDirective?: 'COPY' | 'REPLACE';
/**
* Extra headers for the target object
*/
Headers?: Record<string, string>;
}
export declare class CopyDestinationOptions {
readonly Bucket: string;
readonly Object: string;
private readonly Encryption?;
private readonly UserMetadata?;
private readonly UserTags?;
private readonly LegalHold?;
private readonly RetainUntilDate?;
private readonly Mode?;
private readonly MetadataDirective?;
private readonly Headers?;
constructor({
Bucket,
Object,
Encryption,
UserMetadata,
UserTags,
LegalHold,
RetainUntilDate,
Mode,
MetadataDirective,
Headers
}: ICopyDestinationOptions);
getHeaders(): RequestHeaders;
validate(): boolean;
}
/**
* maybe this should be a generic type for Records, leave it for later refactor
*/
export declare class SelectResults {
private records?;
private response?;
private stats?;
private progress?;
constructor({
records,
// parsed data as stream
response,
// original response stream
stats,
// stats as xml
progress
}: {
records?: unknown;
response?: unknown;
stats?: string;
progress?: unknown;
});
setStats(stats: string): void;
getStats(): string | undefined;
setProgress(progress: unknown): void;
getProgress(): unknown;
setResponse(response: unknown): void;
getResponse(): unknown;
setRecords(records: unknown): void;
getRecords(): unknown;
}
+218
View File
@@ -0,0 +1,218 @@
import * as fs from "fs";
import * as path from "path";
import * as querystring from 'query-string';
import * as errors from "./errors.mjs";
import { getEncryptionHeaders, isEmpty, isEmptyObject, isNumber, isObject, isString, isValidBucketName, isValidObjectName } from "./internal/helper.mjs";
import { RETENTION_MODES } from "./internal/type.mjs";
export { ENCRYPTION_TYPES, LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./internal/type.mjs";
export const DEFAULT_REGION = 'us-east-1';
export const PRESIGN_EXPIRY_DAYS_MAX = 24 * 60 * 60 * 7; // 7 days in seconds
export class CopySourceOptions {
constructor({
Bucket,
Object,
VersionID = '',
MatchETag = '',
NoMatchETag = '',
MatchModifiedSince = null,
MatchUnmodifiedSince = null,
MatchRange = false,
Start = 0,
End = 0,
Encryption = undefined
}) {
this.Bucket = Bucket;
this.Object = Object;
this.VersionID = VersionID;
this.MatchETag = MatchETag;
this.NoMatchETag = NoMatchETag;
this.MatchModifiedSince = MatchModifiedSince;
this.MatchUnmodifiedSince = MatchUnmodifiedSince;
this.MatchRange = MatchRange;
this.Start = Start;
this.End = End;
this.Encryption = Encryption;
}
validate() {
if (!isValidBucketName(this.Bucket)) {
throw new errors.InvalidBucketNameError('Invalid Source bucket name: ' + this.Bucket);
}
if (!isValidObjectName(this.Object)) {
throw new errors.InvalidObjectNameError(`Invalid Source object name: ${this.Object}`);
}
if (this.MatchRange && this.Start !== -1 && this.End !== -1 && this.Start > this.End || this.Start < 0) {
throw new errors.InvalidObjectNameError('Source start must be non-negative, and start must be at most end.');
} else if (this.MatchRange && !isNumber(this.Start) || !isNumber(this.End)) {
throw new errors.InvalidObjectNameError('MatchRange is specified. But Invalid Start and End values are specified.');
}
return true;
}
getHeaders() {
const headerOptions = {};
headerOptions['x-amz-copy-source'] = encodeURI(this.Bucket + '/' + this.Object);
if (!isEmpty(this.VersionID)) {
headerOptions['x-amz-copy-source'] = `${encodeURI(this.Bucket + '/' + this.Object)}?versionId=${this.VersionID}`;
}
if (!isEmpty(this.MatchETag)) {
headerOptions['x-amz-copy-source-if-match'] = this.MatchETag;
}
if (!isEmpty(this.NoMatchETag)) {
headerOptions['x-amz-copy-source-if-none-match'] = this.NoMatchETag;
}
if (!isEmpty(this.MatchModifiedSince)) {
headerOptions['x-amz-copy-source-if-modified-since'] = this.MatchModifiedSince;
}
if (!isEmpty(this.MatchUnmodifiedSince)) {
headerOptions['x-amz-copy-source-if-unmodified-since'] = this.MatchUnmodifiedSince;
}
return headerOptions;
}
}
/**
* @deprecated use nodejs fs module
*/
export function removeDirAndFiles(dirPath, removeSelf = true) {
if (removeSelf) {
return fs.rmSync(dirPath, {
recursive: true,
force: true
});
}
fs.readdirSync(dirPath).forEach(item => {
fs.rmSync(path.join(dirPath, item), {
recursive: true,
force: true
});
});
}
export class CopyDestinationOptions {
constructor({
Bucket,
Object,
Encryption,
UserMetadata,
UserTags,
LegalHold,
RetainUntilDate,
Mode,
MetadataDirective,
Headers
}) {
this.Bucket = Bucket;
this.Object = Object;
this.Encryption = Encryption ?? undefined; // null input will become undefined, easy for runtime assert
this.UserMetadata = UserMetadata;
this.UserTags = UserTags;
this.LegalHold = LegalHold;
this.Mode = Mode; // retention mode
this.RetainUntilDate = RetainUntilDate;
this.MetadataDirective = MetadataDirective;
this.Headers = Headers;
}
getHeaders() {
const replaceDirective = 'REPLACE';
const headerOptions = {};
const userTags = this.UserTags;
if (!isEmpty(userTags)) {
headerOptions['X-Amz-Tagging-Directive'] = replaceDirective;
headerOptions['X-Amz-Tagging'] = isObject(userTags) ? querystring.stringify(userTags) : isString(userTags) ? userTags : '';
}
if (this.Mode) {
headerOptions['X-Amz-Object-Lock-Mode'] = this.Mode; // GOVERNANCE or COMPLIANCE
}
if (this.RetainUntilDate) {
headerOptions['X-Amz-Object-Lock-Retain-Until-Date'] = this.RetainUntilDate; // needs to be UTC.
}
if (this.LegalHold) {
headerOptions['X-Amz-Object-Lock-Legal-Hold'] = this.LegalHold; // ON or OFF
}
if (this.UserMetadata) {
for (const [key, value] of Object.entries(this.UserMetadata)) {
headerOptions[`X-Amz-Meta-${key}`] = value.toString();
}
}
if (this.MetadataDirective) {
headerOptions[`X-Amz-Metadata-Directive`] = this.MetadataDirective;
}
if (this.Encryption) {
const encryptionHeaders = getEncryptionHeaders(this.Encryption);
for (const [key, value] of Object.entries(encryptionHeaders)) {
headerOptions[key] = value;
}
}
if (this.Headers) {
for (const [key, value] of Object.entries(this.Headers)) {
headerOptions[key] = value;
}
}
return headerOptions;
}
validate() {
if (!isValidBucketName(this.Bucket)) {
throw new errors.InvalidBucketNameError('Invalid Destination bucket name: ' + this.Bucket);
}
if (!isValidObjectName(this.Object)) {
throw new errors.InvalidObjectNameError(`Invalid Destination object name: ${this.Object}`);
}
if (!isEmpty(this.UserMetadata) && !isObject(this.UserMetadata)) {
throw new errors.InvalidObjectNameError(`Destination UserMetadata should be an object with key value pairs`);
}
if (!isEmpty(this.Mode) && ![RETENTION_MODES.GOVERNANCE, RETENTION_MODES.COMPLIANCE].includes(this.Mode)) {
throw new errors.InvalidObjectNameError(`Invalid Mode specified for destination object it should be one of [GOVERNANCE,COMPLIANCE]`);
}
if (this.Encryption !== undefined && isEmptyObject(this.Encryption)) {
throw new errors.InvalidObjectNameError(`Invalid Encryption configuration for destination object `);
}
return true;
}
}
/**
* maybe this should be a generic type for Records, leave it for later refactor
*/
export class SelectResults {
constructor({
records,
// parsed data as stream
response,
// original response stream
stats,
// stats as xml
progress // stats as xml
}) {
this.records = records;
this.response = response;
this.stats = stats;
this.progress = progress;
}
setStats(stats) {
this.stats = stats;
}
getStats() {
return this.stats;
}
setProgress(progress) {
this.progress = progress;
}
getProgress() {
return this.progress;
}
setResponse(response) {
this.response = response;
}
getResponse() {
return this.response;
}
setRecords(records) {
this.records = records;
}
getRecords() {
return this.records;
}
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmcyIsInBhdGgiLCJxdWVyeXN0cmluZyIsImVycm9ycyIsImdldEVuY3J5cHRpb25IZWFkZXJzIiwiaXNFbXB0eSIsImlzRW1wdHlPYmplY3QiLCJpc051bWJlciIsImlzT2JqZWN0IiwiaXNTdHJpbmciLCJpc1ZhbGlkQnVja2V0TmFtZSIsImlzVmFsaWRPYmplY3ROYW1lIiwiUkVURU5USU9OX01PREVTIiwiRU5DUllQVElPTl9UWVBFUyIsIkxFR0FMX0hPTERfU1RBVFVTIiwiUkVURU5USU9OX1ZBTElESVRZX1VOSVRTIiwiREVGQVVMVF9SRUdJT04iLCJQUkVTSUdOX0VYUElSWV9EQVlTX01BWCIsIkNvcHlTb3VyY2VPcHRpb25zIiwiY29uc3RydWN0b3IiLCJCdWNrZXQiLCJPYmplY3QiLCJWZXJzaW9uSUQiLCJNYXRjaEVUYWciLCJ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gPSBFbmRcbiAgICB0aGlzLkVuY3J5cHRpb24gPSBFbmNyeXB0aW9uXG4gIH1cblxuICB2YWxpZGF0ZSgpIHtcbiAgICBpZiAoIWlzVmFsaWRCdWNrZXROYW1lKHRoaXMuQnV Line truncated
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="node" />
/// <reference types="node" />
import * as fs from 'node:fs';
import * as stream from 'node:stream';
export { promises as fsp } from 'node:fs';
export declare const streamPromise: {
pipeline: typeof stream.pipeline.__promisify__;
};
export declare const fstat: typeof fs.fstat.__promisify__;
+14
View File
@@ -0,0 +1,14 @@
// promise helper for stdlib
import * as fs from "fs";
import * as stream from "stream";
import { promisify } from "util";
// TODO: use "node:fs/promise" directly after we stop testing on nodejs 12
export { promises as fsp } from 'node:fs';
export const streamPromise = {
// node:stream/promises Added in: v15.0.0
pipeline: promisify(stream.pipeline)
};
export const fstat = promisify(fs.fstat);
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmcyIsInN0cmVhbSIsInByb21pc2lmeSIsInByb21pc2VzIiwiZnNwIiwic3RyZWFtUHJvbWlzZSIsInBpcGVsaW5lIiwiZnN0YXQiXSwic291cmNlcyI6WyJhc3luYy50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvLyBwcm9taXNlIGhlbHBlciBmb3Igc3RkbGliXG5cbmltcG9ydCAqIGFzIGZzIGZyb20gJ25vZGU6ZnMnXG5pbXBvcnQgKiBhcyBzdHJlYW0gZnJvbSAnbm9kZTpzdHJlYW0nXG5pbXBvcnQgeyBwcm9taXNpZnkgfSBmcm9tICdub2RlOnV0aWwnXG5cbi8vIFRPRE86IHVzZSBcIm5vZGU6ZnMvcHJvbWlzZVwiIGRpcmVjdGx5IGFmdGVyIHdlIHN0b3AgdGVzdGluZyBvbiBub2RlanMgMTJcbmV4cG9ydCB7IHByb21pc2VzIGFzIGZzcCB9IGZyb20gJ25vZGU6ZnMnXG5leHBvcnQgY29uc3Qgc3RyZWFtUHJvbWlzZSA9IHtcbiAgLy8gbm9kZTpzdHJlYW0vcHJvbWlzZXMgQWRkZWQgaW46IHYxNS4wLjBcbiAgcGlwZWxpbmU6IHByb21pc2lmeShzdHJlYW0ucGlwZWxpbmUpLFxufVxuXG5leHBvcnQgY29uc3QgZnN0YXQgPSBwcm9taXNpZnkoZnMuZnN0YXQpXG4iXSwibWFwcGluZ3MiOiJBQUFBOztBQUVBLE9BQU8sS0FBS0EsRUFBRTtBQUNkLE9BQU8sS0FBS0MsTUFBTTtBQUNsQixTQUFTQyxTQUFTOztBQUVsQjtBQUNBLFNBQVNDLFFBQVEsSUFBSUMsR0FBRyxRQUFRLFNBQVM7QUFDekMsT0FBTyxNQUFNQyxhQUFhLEdBQUc7RUFDM0I7RUFDQUMsUUFBUSxFQUFFSixTQUFTLENBQUNELE1BQU0sQ0FBQ0ssUUFBUTtBQUNyQyxDQUFDO0FBRUQsT0FBTyxNQUFNQyxLQUFLLEdBQUdMLFNBQVMsQ0FBQ0YsRUFBRSxDQUFDTyxLQUFLLENBQUMifQ==
@@ -0,0 +1,15 @@
// wrapper an async function that support callback style API.
// It will preserve 'this'.
export function callbackify(fn) {
return function () {
const args = [...arguments];
const callback = args.pop();
// If the last argument is a function, assume it's the callback.
if (typeof callback === 'function') {
return fn.apply(this, args).then(result => callback(null, result), err => callback(err));
}
return fn.apply(this, arguments);
};
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjYWxsYmFja2lmeSIsImZuIiwiYXJncyIsImFyZ3VtZW50cyIsImNhbGxiYWNrIiwicG9wIiwiYXBwbHkiLCJ0aGVuIiwicmVzdWx0IiwiZXJyIl0sInNvdXJjZXMiOlsiY2FsbGJhY2tpZnkuanMiXSwic291cmNlc0NvbnRlbnQiOlsiLy8gd3JhcHBlciBhbiBhc3luYyBmdW5jdGlvbiB0aGF0IHN1cHBvcnQgY2FsbGJhY2sgc3R5bGUgQV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DQUFDSyxHQUFHLENBQ3ZCLENBQUM7SUFDSDtJQUVBLE9BQU9SLEVBQUUsQ0FBQ0ssS0FBSyxDQUFDLElBQUksRUFBRUgsU0FBUyxDQUFDO0VBQ2xDLENBQUM7QUFDSCJ9
+359
View File
@@ -0,0 +1,359 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import * as http from 'node:http';
import * as https from 'node:https';
import * as stream from 'node:stream';
import { CredentialProvider } from "../CredentialProvider.mjs";
import type { SelectResults } from "../helpers.mjs";
import { CopyDestinationOptions, CopySourceOptions, LEGAL_HOLD_STATUS } from "../helpers.mjs";
import type { PostPolicyResult } from "../minio.mjs";
import { CopyConditions } from "./copy-conditions.mjs";
import { Extensions } from "./extensions.mjs";
import { PostPolicy } from "./post-policy.mjs";
import type { Region } from "./s3-endpoints.mjs";
import type { Binary, BucketItemFromList, BucketItemStat, BucketStream, BucketVersioningConfiguration, CopyObjectResult, EncryptionConfig, GetObjectLegalHoldOptions, GetObjectOpts, GetObjectRetentionOpts, IncompleteUploadedBucketItem, IRequest, ItemBucketMetadata, LifecycleConfig, LifeCycleConfigParam, ListObjectQueryOpts, ObjectInfo, ObjectLockInfo, ObjectMetaData, ObjectRetentionInfo, PreSignRequestParams, PutObjectLegalHoldOptions, RemoveObjectsParam, RemoveObjectsResponse, ReplicationConfig, ReplicationConfigOpts, RequestHeaders, ResultCallback, Retention, SelectOptions, StatObjectOpts, Tag, TaggingOpts, Tags, Transport, UploadedObjectInfo } from "./type.mjs";
import type { ListMultipartResult, UploadedPart } from "./xml-parser.mjs";
declare const requestOptionProperties: readonly ["agent", "ca", "cert", "ciphers", "clientCertEngine", "crl", "dhparam", "ecdhCurve", "family", "honorCipherOrder", "key", "passphrase", "pfx", "rejectUnauthorized", "secureOptions", "secureProtocol", "servername", "sessionIdContext"];
export interface ClientOptions {
endPoint: string;
accessKey?: string;
secretKey?: string;
useSSL?: boolean;
port?: number;
region?: Region;
transport?: Transport;
sessionToken?: string;
partSize?: number;
pathStyle?: boolean;
credentialsProvider?: CredentialProvider;
s3AccelerateEndpoint?: string;
transportAgent?: http.Agent;
}
export type RequestOption = Partial<IRequest> & {
method: string;
bucketName?: string;
objectName?: string;
query?: string;
pathStyle?: boolean;
};
export type NoResultCallback = (error: unknown) => void;
export interface MakeBucketOpt {
ObjectLocking?: boolean;
}
export interface RemoveOptions {
versionId?: string;
governanceBypass?: boolean;
forceDelete?: boolean;
}
export declare class TypedClient {
protected transport: Transport;
protected host: string;
protected port: number;
protected protocol: string;
protected accessKey: string;
protected secretKey: string;
protected sessionToken?: string;
protected userAgent: string;
protected anonymous: boolean;
protected pathStyle: boolean;
protected regionMap: Record<string, string>;
region?: string;
protected credentialsProvider?: CredentialProvider;
partSize: number;
protected overRidePartSize?: boolean;
protected maximumPartSize: number;
protected maxObjectSize: number;
enableSHA256: boolean;
protected s3AccelerateEndpoint?: string;
protected reqOptions: Record<string, unknown>;
protected transportAgent: http.Agent;
private readonly clientExtensions;
constructor(params: ClientOptions);
/**
* Minio extensions that aren't necessary present for Amazon S3 compatible storage servers
*/
get extensions(): Extensions;
/**
* @param endPoint - valid S3 acceleration end point
*/
setS3TransferAccelerate(endPoint: string): void;
/**
* Sets the supported request options.
*/
setRequestOptions(options: Pick<https.RequestOptions, (typeof requestOptionProperties)[number]>): void;
/**
* This is s3 Specific and does not hold validity in any other Object storage.
*/
private getAccelerateEndPointIfSet;
/**
* Set application specific information.
* Generates User-Agent in the following style.
* MinIO (OS; ARCH) LIB/VER APP/VER
*/
setAppInfo(appName: string, appVersion: string): void;
/**
* returns options object that can be used with http.request()
* Takes care of constructing virtual-host-style or path-style hostname
*/
protected getRequestOptions(opts: RequestOption & {
region: string;
}): IRequest & {
host: string;
headers: Record<string, string>;
};
setCredentialsProvider(credentialsProvider: CredentialProvider): Promise<void>;
private checkAndRefreshCreds;
private logStream?;
/**
* log the request, response, error
*/
private logHTTP;
/**
* Enable tracing
*/
traceOn(stream?: stream.Writable): void;
/**
* Disable tracing
*/
traceOff(): void;
/**
* makeRequest is the primitive used by the apis for making S3 requests.
* payload can be empty string in case of no payload.
* statusCode is the expected statusCode. If response.statusCode does not match
* we parse the XML error and call the callback with the error message.
*
* A valid region is passed by the calls - listBuckets, makeBucket and getBucketRegion.
*
* @internal
*/
makeRequestAsync(options: RequestOption, payload?: Binary, expectedCodes?: number[], region?: string): Promise<http.IncomingMessage>;
/**
* new request with promise
*
* No need to drain response, response body is not valid
*/
makeRequestAsyncOmit(options: RequestOption, payload?: Binary, statusCodes?: number[], region?: string): Promise<Omit<http.IncomingMessage, 'on'>>;
/**
* makeRequestStream will be used directly instead of makeRequest in case the payload
* is available as a stream. for ex. putObject
*
* @internal
*/
makeRequestStreamAsync(options: RequestOption, body: stream.Readable | Binary, sha256sum: string, statusCodes: number[], region: string): Promise<http.IncomingMessage>;
/**
* gets the region of the bucket
*
* @param bucketName
*
* @internal
*/
protected getBucketRegionAsync(bucketName: string): Promise<string>;
/**
* makeRequest is the primitive used by the apis for making S3 requests.
* payload can be empty string in case of no payload.
* statusCode is the expected statusCode. If response.statusCode does not match
* we parse the XML error and call the callback with the error message.
* A valid region is passed by the calls - listBuckets, makeBucket and
* getBucketRegion.
*
* @deprecated use `makeRequestAsync` instead
*/
makeRequest(options: RequestOption, payload: Binary | undefined, expectedCodes: number[] | undefined, region: string | undefined, returnResponse: boolean, cb: (cb: unknown, result: http.IncomingMessage) => void): void;
/**
* makeRequestStream will be used directly instead of makeRequest in case the payload
* is available as a stream. for ex. putObject
*
* @deprecated use `makeRequestStreamAsync` instead
*/
makeRequestStream(options: RequestOption, stream: stream.Readable | Buffer, sha256sum: string, statusCodes: number[], region: string, returnResponse: boolean, cb: (cb: unknown, result: http.IncomingMessage) => void): void;
/**
* @deprecated use `getBucketRegionAsync` instead
*/
getBucketRegion(bucketName: string, cb: (err: unknown, region: string) => void): Promise<void>;
/**
* Creates the bucket `bucketName`.
*
*/
makeBucket(bucketName: string, region?: Region, makeOpts?: MakeBucketOpt): Promise<void>;
/**
* To check if a bucket already exists.
*/
bucketExists(bucketName: string): Promise<boolean>;
removeBucket(bucketName: string): Promise<void>;
/**
* @deprecated use promise style API
*/
removeBucket(bucketName: string, callback: NoResultCallback): void;
/**
* Callback is called with readable stream of the object content.
*/
getObject(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise<stream.Readable>;
/**
* Callback is called with readable stream of the partial object content.
* @param bucketName
* @param objectName
* @param offset
* @param length - length of the object that will be read in the stream (optional, if not specified we read the rest of the file from the offset)
* @param getOpts
*/
getPartialObject(bucketName: string, objectName: string, offset: number, length?: number, getOpts?: GetObjectOpts): Promise<stream.Readable>;
/**
* download object content to a file.
* This method will create a temp file named `${filename}.${base64(etag)}.part.minio` when downloading.
*
* @param bucketName - name of the bucket
* @param objectName - name of the object
* @param filePath - path to which the object data will be written to
* @param getOpts - Optional object get option
*/
fGetObject(bucketName: string, objectName: string, filePath: string, getOpts?: GetObjectOpts): Promise<void>;
/**
* Stat information of the object.
*/
statObject(bucketName: string, objectName: string, statOpts?: StatObjectOpts): Promise<BucketItemStat>;
removeObject(bucketName: string, objectName: string, removeOpts?: RemoveOptions): Promise<void>;
listIncompleteUploads(bucket: string, prefix: string, recursive: boolean): BucketStream<IncompleteUploadedBucketItem>;
/**
* Called by listIncompleteUploads to fetch a batch of incomplete uploads.
*/
listIncompleteUploadsQuery(bucketName: string, prefix: string, keyMarker: string, uploadIdMarker: string, delimiter: string): Promise<ListMultipartResult>;
/**
* Initiate a new multipart upload.
* @internal
*/
initiateNewMultipartUpload(bucketName: string, objectName: string, headers: RequestHeaders): Promise<string>;
/**
* Internal Method to abort a multipart upload request in case of any errors.
*
* @param bucketName - Bucket Name
* @param objectName - Object Name
* @param uploadId - id of a multipart upload to cancel during compose object sequence.
*/
abortMultipartUpload(bucketName: string, objectName: string, uploadId: string): Promise<void>;
findUploadId(bucketName: string, objectName: string): Promise<string | undefined>;
/**
* this call will aggregate the parts on the server into a single object.
*/
completeMultipartUpload(bucketName: string, objectName: string, uploadId: string, etags: {
part: number;
etag?: string;
}[]): Promise<{
etag: string;
versionId: string | null;
}>;
/**
* Get part-info of all parts of an incomplete upload specified by uploadId.
*/
protected listParts(bucketName: string, objectName: string, uploadId: string): Promise<UploadedPart[]>;
/**
* Called by listParts to fetch a batch of part-info
*/
private listPartsQuery;
listBuckets(): Promise<BucketItemFromList[]>;
/**
* Calculate part size given the object size. Part size will be atleast this.partSize
*/
calculatePartSize(size: number): number;
/**
* Uploads the object using contents from a file
*/
fPutObject(bucketName: string, objectName: string, filePath: string, metaData?: ObjectMetaData): Promise<UploadedObjectInfo>;
/**
* Uploading a stream, "Buffer" or "string".
* It's recommended to pass `size` argument with stream.
*/
putObject(bucketName: string, objectName: string, stream: stream.Readable | Buffer | string, size?: number, metaData?: ItemBucketMetadata): Promise<UploadedObjectInfo>;
/**
* method to upload buffer in one call
* @private
*/
private uploadBuffer;
/**
* upload stream with MultipartUpload
* @private
*/
private uploadStream;
removeBucketReplication(bucketName: string): Promise<void>;
removeBucketReplication(bucketName: string, callback: NoResultCallback): void;
setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): void;
setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): Promise<void>;
getBucketReplication(bucketName: string): void;
getBucketReplication(bucketName: string): Promise<ReplicationConfig>;
getObjectLegalHold(bucketName: string, objectName: string, getOpts?: GetObjectLegalHoldOptions, callback?: ResultCallback<LEGAL_HOLD_STATUS>): Promise<LEGAL_HOLD_STATUS>;
setObjectLegalHold(bucketName: string, objectName: string, setOpts?: PutObjectLegalHoldOptions): void;
/**
* Get Tags associated with a Bucket
*/
getBucketTagging(bucketName: string): Promise<Tag[]>;
/**
* Get the tags associated with a bucket OR an object
*/
getObjectTagging(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise<Tag[]>;
/**
* Set the policy on a bucket or an object prefix.
*/
setBucketPolicy(bucketName: string, policy: string): Promise<void>;
/**
* Get the policy on a bucket or an object prefix.
*/
getBucketPolicy(bucketName: string): Promise<string>;
putObjectRetention(bucketName: string, objectName: string, retentionOpts?: Retention): Promise<void>;
getObjectLockConfig(bucketName: string, callback: ResultCallback<ObjectLockInfo>): void;
getObjectLockConfig(bucketName: string): void;
getObjectLockConfig(bucketName: string): Promise<ObjectLockInfo>;
setObjectLockConfig(bucketName: string, lockConfigOpts: Omit<ObjectLockInfo, 'objectLockEnabled'>): void;
setObjectLockConfig(bucketName: string, lockConfigOpts: Omit<ObjectLockInfo, 'objectLockEnabled'>): Promise<void>;
getBucketVersioning(bucketName: string): Promise<BucketVersioningConfiguration>;
setBucketVersioning(bucketName: string, versionConfig: BucketVersioningConfiguration): Promise<void>;
private setTagging;
private removeTagging;
setBucketTagging(bucketName: string, tags: Tags): Promise<void>;
removeBucketTagging(bucketName: string): Promise<void>;
setObjectTagging(bucketName: string, objectName: string, tags: Tags, putOpts?: TaggingOpts): Promise<void>;
removeObjectTagging(bucketName: string, objectName: string, removeOpts: TaggingOpts): Promise<void>;
selectObjectContent(bucketName: string, objectName: string, selectOpts: SelectOptions): Promise<SelectResults | undefined>;
private applyBucketLifecycle;
removeBucketLifecycle(bucketName: string): Promise<void>;
setBucketLifecycle(bucketName: string, lifeCycleConfig: LifeCycleConfigParam): Promise<void>;
getBucketLifecycle(bucketName: string): Promise<LifecycleConfig | null>;
setBucketEncryption(bucketName: string, encryptionConfig?: EncryptionConfig): Promise<void>;
getBucketEncryption(bucketName: string): Promise<any>;
removeBucketEncryption(bucketName: string): Promise<void>;
getObjectRetention(bucketName: string, objectName: string, getOpts?: GetObjectRetentionOpts): Promise<ObjectRetentionInfo | null | undefined>;
removeObjects(bucketName: string, objectsList: RemoveObjectsParam): Promise<RemoveObjectsResponse[]>;
removeIncompleteUpload(bucketName: string, objectName: string): Promise<void>;
private copyObjectV1;
private copyObjectV2;
copyObject(source: CopySourceOptions, dest: CopyDestinationOptions): Promise<CopyObjectResult>;
copyObject(targetBucketName: string, targetObjectName: string, sourceBucketNameAndObjectName: string, conditions?: CopyConditions): Promise<CopyObjectResult>;
uploadPart(partConfig: {
bucketName: string;
objectName: string;
uploadID: string;
partNumber: number;
headers: RequestHeaders;
}, payload?: Binary): Promise<{
etag: string;
key: string;
part: number;
}>;
composeObject(destObjConfig: CopyDestinationOptions, sourceObjList: CopySourceOptions[]): Promise<boolean | {
etag: string;
versionId: string | null;
} | Promise<void> | CopyObjectResult>;
presignedUrl(method: string, bucketName: string, objectName: string, expires?: number | PreSignRequestParams | undefined, reqParams?: PreSignRequestParams | Date, requestDate?: Date): Promise<string>;
presignedGetObject(bucketName: string, objectName: string, expires?: number, respHeaders?: PreSignRequestParams | Date, requestDate?: Date): Promise<string>;
presignedPutObject(bucketName: string, objectName: string, expires?: number): Promise<string>;
newPostPolicy(): PostPolicy;
presignedPostPolicy(postPolicy: PostPolicy): Promise<PostPolicyResult>;
listObjectsQuery(bucketName: string, prefix?: string, marker?: string, listQueryOpts?: ListObjectQueryOpts): Promise<{
objects: ObjectInfo[];
isTruncated?: boolean | undefined;
nextMarker?: string | undefined;
versionIdMarker?: string | undefined;
}>;
listObjects(bucketName: string, prefix?: string, recursive?: boolean, listOpts?: ListObjectQueryOpts | undefined): BucketStream<ObjectInfo>;
}
export {};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,10 @@
export declare class CopyConditions {
modified: string;
unmodified: string;
matchETag: string;
matchETagExcept: string;
setModified(date: Date): void;
setUnmodified(date: Date): void;
setMatchETag(etag: string): void;
setMatchETagExcept(etag: string): void;
}
@@ -0,0 +1,25 @@
export class CopyConditions {
modified = '';
unmodified = '';
matchETag = '';
matchETagExcept = '';
setModified(date) {
if (!(date instanceof Date)) {
throw new TypeError('date must be of type Date');
}
this.modified = date.toUTCString();
}
setUnmodified(date) {
if (!(date instanceof Date)) {
throw new TypeError('date must be of type Date');
}
this.unmodified = date.toUTCString();
}
setMatchETag(etag) {
this.matchETag = etag;
}
setMatchETagExcept(etag) {
this.matchETagExcept = etag;
}
}
//# sourceMapping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BucketItemWithMetadata, BucketStream } from "./type.mjs";
export declare class Extensions {
private readonly client;
constructor(client: TypedClient);
/**
* List the objects in the bucket using S3 ListObjects V2 With Metadata
*
* @param bucketName - name of the bucket
* @param prefix - the prefix of the objects that should be listed (optional, default `''`)
* @param recursive - `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`)
* @param startAfter - Specifies the key to start after when listing objects in a bucket. (optional, default `''`)
* @returns stream emitting the objects in the bucket, the object is of the format:
*/
listObjectsV2WithMetadata(bucketName: string, prefix?: string, recursive?: boolean, startAfter?: string): BucketStream<BucketItemWithMetadata>;
private listObjectsV2WithMetadataGen;
private listObjectsV2WithMetadataQuery;
}
+114
View File
@@ -0,0 +1,114 @@
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as stream from "stream";
import * as errors from "../errors.mjs";
import { isBoolean, isString, isValidBucketName, isValidPrefix, uriEscape } from "./helper.mjs";
import { readAsString } from "./response.mjs";
import { parseListObjectsV2WithMetadata } from "./xml-parser.mjs";
export class Extensions {
constructor(client) {
this.client = client;
}
/**
* List the objects in the bucket using S3 ListObjects V2 With Metadata
*
* @param bucketName - name of the bucket
* @param prefix - the prefix of the objects that should be listed (optional, default `''`)
* @param recursive - `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`)
* @param startAfter - Specifies the key to start after when listing objects in a bucket. (optional, default `''`)
* @returns stream emitting the objects in the bucket, the object is of the format:
*/
listObjectsV2WithMetadata(bucketName, prefix, recursive, startAfter) {
if (prefix === undefined) {
prefix = '';
}
if (recursive === undefined) {
recursive = false;
}
if (startAfter === undefined) {
startAfter = '';
}
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!isValidPrefix(prefix)) {
throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`);
}
if (!isString(prefix)) {
throw new TypeError('prefix should be of type "string"');
}
if (!isBoolean(recursive)) {
throw new TypeError('recursive should be of type "boolean"');
}
if (!isString(startAfter)) {
throw new TypeError('startAfter should be of type "string"');
}
// if recursive is false set delimiter to '/'
const delimiter = recursive ? '' : '/';
return stream.Readable.from(this.listObjectsV2WithMetadataGen(bucketName, prefix, delimiter, startAfter), {
objectMode: true
});
}
async *listObjectsV2WithMetadataGen(bucketName, prefix, delimiter, startAfter) {
let ended = false;
let continuationToken = '';
do {
const result = await this.listObjectsV2WithMetadataQuery(bucketName, prefix, continuationToken, delimiter, startAfter);
ended = !result.isTruncated;
continuationToken = result.nextContinuationToken;
for (const obj of result.objects) {
yield obj;
}
} while (!ended);
}
async listObjectsV2WithMetadataQuery(bucketName, prefix, continuationToken, delimiter, startAfter) {
const queries = [];
// Call for listing objects v2 API
queries.push(`list-type=2`);
queries.push(`encoding-type=url`);
// escape every value in query string, except maxKeys
queries.push(`prefix=${uriEscape(prefix)}`);
queries.push(`delimiter=${uriEscape(delimiter)}`);
queries.push(`metadata=true`);
if (continuationToken) {
continuationToken = uriEscape(continuationToken);
queries.push(`continuation-token=${continuationToken}`);
}
// Set start-after
if (startAfter) {
startAfter = uriEscape(startAfter);
queries.push(`start-after=${startAfter}`);
}
queries.push(`max-keys=1000`);
queries.sort();
let query = '';
if (queries.length > 0) {
query = `${queries.join('&')}`;
}
const method = 'GET';
const res = await this.client.makeRequestAsync({
method,
bucketName,
query
});
return parseListObjectsV2WithMetadata(await readAsString(res));
}
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJzdHJlYW0iLCJlcnJvcnMiLC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vZiB0eXBlIFwiYm9vbGVhblwiJylcbiAgICB9XG4gICAgaWYgKCFpc1N0cmluZyhzdGFydEFmdGVyKSkge1xuICAgICAgdGhyb3cgbmV3IFR5cGVFcnJvcignc3RhcnRBZnRlciBzaG91bGQgYmUgb2YgdHlwZSBcInN0cmluZ1wiJylcbiAgICB9XG5cbiAgICAvLyBpZiByZWN1cnNpdmUgaXMgZmFsc2Ugc2V0IGRlbGltaXRlciB0byAnLydcbiAgICBjb25zdCBkZWxpbWl0ZXIgPSByZWN1cnNpdmUgPyAnJyA6ICcvJ1xuICAgIHJldHVybiBzdHJlYW0uUmVhZGFibGUuZnJvbSh0aGlzLmxpc3RPYmplY3RzVjJXaXRoTWV0YWRhdGFHZW4oYnVja2V0TmFtZSwgcHJlZml4LCBkZWxpbWl0ZXIsIHN0YXJ0QWZ0ZXIpLCB7XG4gICAgICBvYmplY3RNb2RlOiB0cnVlLFxuICAgIH0pXG4gIH1cblxuICBwcml2YXRlIGFzeW5jICpsaXN0T2JqZWN0c1YyV2l0aE1ldGFkYXRhR2VuKFxuICAgIGJ1Y2tldE5hbWU6IHN Line truncated
+173
View File
@@ -0,0 +1,173 @@
/// <reference types="node" />
/// <reference types="node" />
import * as stream from 'node:stream';
import _ from 'lodash';
import type { Binary, Encryption, ObjectMetaData, RequestHeaders, ResponseHeader } from "./type.mjs";
export declare function hashBinary(buf: Buffer, enableSHA256: boolean): {
md5sum: string;
sha256sum: string;
};
export declare function uriEscape(uriStr: string): string;
export declare function uriResourceEscape(string: string): string;
export declare function getScope(region: string, date: Date, serviceName?: string): string;
/**
* isAmazonEndpoint - true if endpoint is 's3.amazonaws.com' or 's3.cn-north-1.amazonaws.com.cn'
*/
export declare function isAmazonEndpoint(endpoint: string): boolean;
/**
* isVirtualHostStyle - verify if bucket name is support with virtual
* hosts. bucketNames with periods should be always treated as path
* style if the protocol is 'https:', this is due to SSL wildcard
* limitation. For all other buckets and Amazon S3 endpoint we will
* default to virtual host style.
*/
export declare function isVirtualHostStyle(endpoint: string, protocol: string, bucket: string, pathStyle: boolean): boolean;
export declare function isValidIP(ip: string): boolean;
/**
* @returns if endpoint is valid domain.
*/
export declare function isValidEndpoint(endpoint: string): boolean;
/**
* @returns if input host is a valid domain.
*/
export declare function isValidDomain(host: string): boolean;
/**
* Probes contentType using file extensions.
*
* @example
* ```
* // return 'image/png'
* probeContentType('file.png')
* ```
*/
export declare function probeContentType(path: string): string;
/**
* is input port valid.
*/
export declare function isValidPort(port: unknown): port is number;
export declare function isValidBucketName(bucket: unknown): boolean;
/**
* check if objectName is a valid object name
*/
export declare function isValidObjectName(objectName: unknown): boolean;
/**
* check if prefix is valid
*/
export declare function isValidPrefix(prefix: unknown): prefix is string;
/**
* check if typeof arg number
*/
export declare function isNumber(arg: unknown): arg is number;
export type AnyFunction = (...args: any[]) => any;
/**
* check if typeof arg function
*/
export declare function isFunction(arg: unknown): arg is AnyFunction;
/**
* check if typeof arg string
*/
export declare function isString(arg: unknown): arg is string;
/**
* check if typeof arg object
*/
export declare function isObject(arg: unknown): arg is object;
/**
* check if object is readable stream
*/
export declare function isReadableStream(arg: unknown): arg is stream.Readable;
/**
* check if arg is boolean
*/
export declare function isBoolean(arg: unknown): arg is boolean;
export declare function isEmpty(o: unknown): o is null | undefined;
export declare function isEmptyObject(o: Record<string, unknown>): boolean;
export declare function isDefined<T>(o: T): o is Exclude<T, null | undefined>;
/**
* check if arg is a valid date
*/
export declare function isValidDate(arg: unknown): arg is Date;
/**
* Create a Date string with format: 'YYYYMMDDTHHmmss' + Z
*/
export declare function makeDateLong(date?: Date): string;
/**
* Create a Date string with format: 'YYYYMMDD'
*/
export declare function makeDateShort(date?: Date): string;
/**
* pipesetup sets up pipe() from left to right os streams array
* pipesetup will also make sure that error emitted at any of the upstream Stream
* will be emitted at the last stream. This makes error handling simple
*/
export declare function pipesetup(...streams: [stream.Readable, ...stream.Duplex[], stream.Writable]): stream.Readable | stream.Duplex | stream.Writable;
/**
* return a Readable stream that emits data
*/
export declare function readableStream(data: unknown): stream.Readable;
/**
* Process metadata to insert appropriate value to `content-type` attribute
*/
export declare function insertContentType(metaData: ObjectMetaData, filePath: string): ObjectMetaData;
/**
* Function prepends metadata with the appropriate prefix if it is not already on
*/
export declare function prependXAMZMeta(metaData?: ObjectMetaData): RequestHeaders;
/**
* Checks if it is a valid header according to the AmazonS3 API
*/
export declare function isAmzHeader(key: string): boolean;
/**
* Checks if it is a supported Header
*/
export declare function isSupportedHeader(key: string): boolean;
/**
* Checks if it is a storage header
*/
export declare function isStorageClassHeader(key: string): boolean;
export declare function extractMetadata(headers: ResponseHeader): _.Dictionary<string>;
export declare function getVersionId(headers?: ResponseHeader): string | null;
export declare function getSourceVersionId(headers?: ResponseHeader): string | null;
export declare function sanitizeETag(etag?: string): string;
export declare function toMd5(payload: Binary): string;
export declare function toSha256(payload: Binary): string;
/**
* toArray returns a single element array with param being the element,
* if param is just a string, and returns 'param' back if it is an array
* So, it makes sure param is always an array
*/
export declare function toArray<T = unknown>(param: T | T[]): Array<T>;
export declare function sanitizeObjectKey(objectName: string): string;
export declare function sanitizeSize(size?: string): number | undefined;
export declare const PART_CONSTRAINTS: {
ABS_MIN_PART_SIZE: number;
MIN_PART_SIZE: number;
MAX_PARTS_COUNT: number;
MAX_PART_SIZE: number;
MAX_SINGLE_PUT_OBJECT_SIZE: number;
MAX_MULTIPART_PUT_OBJECT_SIZE: number;
};
/**
* Return Encryption headers
* @param encConfig
* @returns an object with key value pairs that can be used in headers.
*/
export declare function getEncryptionHeaders(encConfig: Encryption): RequestHeaders;
export declare function partsRequired(size: number): number;
/**
* calculateEvenSplits - computes splits for a source and returns
* start and end index slices. Splits happen evenly to be sure that no
* part is less than 5MiB, as that could fail the multipart request if
* it is not the last part.
*/
export declare function calculateEvenSplits<T extends {
Start?: number;
}>(size: number, objInfo: T): {
startIndex: number[];
objInfo: T;
endIndex: number[];
} | null;
export declare function parseXml(xml: string): any;
/**
* get content size of object content to upload
*/
export declare function getContentLength(s: stream.Readable | Buffer | string): Promise<number | null>;
+547
View File
@@ -0,0 +1,547 @@
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as crypto from "crypto";
import * as stream from "stream";
import { XMLParser } from 'fast-xml-parser';
import ipaddr from 'ipaddr.js';
import _ from 'lodash';
import * as mime from 'mime-types';
import { fsp, fstat } from "./async.mjs";
import { ENCRYPTION_TYPES } from "./type.mjs";
const MetaDataHeaderPrefix = 'x-amz-meta-';
export function hashBinary(buf, enableSHA256) {
let sha256sum = '';
if (enableSHA256) {
sha256sum = crypto.createHash('sha256').update(buf).digest('hex');
}
const md5sum = crypto.createHash('md5').update(buf).digest('base64');
return {
md5sum,
sha256sum
};
}
// S3 percent-encodes some extra non-standard characters in a URI . So comply with S3.
const encodeAsHex = c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`;
export function uriEscape(uriStr) {
return encodeURIComponent(uriStr).replace(/[!'()*]/g, encodeAsHex);
}
export function uriResourceEscape(string) {
return uriEscape(string).replace(/%2F/g, '/');
}
export function getScope(region, date, serviceName = 's3') {
return `${makeDateShort(date)}/${region}/${serviceName}/aws4_request`;
}
/**
* isAmazonEndpoint - true if endpoint is 's3.amazonaws.com' or 's3.cn-north-1.amazonaws.com.cn'
*/
export function isAmazonEndpoint(endpoint) {
return endpoint === 's3.amazonaws.com' || endpoint === 's3.cn-north-1.amazonaws.com.cn';
}
/**
* isVirtualHostStyle - verify if bucket name is support with virtual
* hosts. bucketNames with periods should be always treated as path
* style if the protocol is 'https:', this is due to SSL wildcard
* limitation. For all other buckets and Amazon S3 endpoint we will
* default to virtual host style.
*/
export function isVirtualHostStyle(endpoint, protocol, bucket, pathStyle) {
if (protocol === 'https:' && bucket.includes('.')) {
return false;
}
return isAmazonEndpoint(endpoint) || !pathStyle;
}
export function isValidIP(ip) {
return ipaddr.isValid(ip);
}
/**
* @returns if endpoint is valid domain.
*/
export function isValidEndpoint(endpoint) {
return isValidDomain(endpoint) || isValidIP(endpoint);
}
/**
* @returns if input host is a valid domain.
*/
export function isValidDomain(host) {
if (!isString(host)) {
return false;
}
// See RFC 1035, RFC 3696.
if (host.length === 0 || host.length > 255) {
return false;
}
// Host cannot start or end with a '-'
if (host[0] === '-' || host.slice(-1) === '-') {
return false;
}
// Host cannot start or end with a '_'
if (host[0] === '_' || host.slice(-1) === '_') {
return false;
}
// Host cannot start with a '.'
if (host[0] === '.') {
return false;
}
const nonAlphaNumerics = '`~!@#$%^&*()+={}[]|\\"\';:><?/';
// All non alphanumeric characters are invalid.
for (const char of nonAlphaNumerics) {
if (host.includes(char)) {
return false;
}
}
// No need to regexp match, since the list is non-exhaustive.
// We let it be valid and fail later.
return true;
}
/**
* Probes contentType using file extensions.
*
* @example
* ```
* // return 'image/png'
* probeContentType('file.png')
* ```
*/
export function probeContentType(path) {
let contentType = mime.lookup(path);
if (!contentType) {
contentType = 'application/octet-stream';
}
return contentType;
}
/**
* is input port valid.
*/
export function isValidPort(port) {
// Convert string port to number if needed
const portNum = typeof port === 'string' ? parseInt(port, 10) : port;
// verify if port is a valid number
if (!isNumber(portNum) || isNaN(portNum)) {
return false;
}
// port `0` is valid and special case
return 0 <= portNum && portNum <= 65535;
}
export function isValidBucketName(bucket) {
if (!isString(bucket)) {
return false;
}
// bucket length should be less than and no more than 63
// characters long.
if (bucket.length < 3 || bucket.length > 63) {
return false;
}
// bucket with successive periods is invalid.
if (bucket.includes('..')) {
return false;
}
// bucket cannot have ip address style.
if (/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/.test(bucket)) {
return false;
}
// bucket should begin with alphabet/number and end with alphabet/number,
// with alphabet/number/.- in the middle.
if (/^[a-z0-9][a-z0-9.-]+[a-z0-9]$/.test(bucket)) {
return true;
}
return false;
}
/**
* check if objectName is a valid object name
*/
export function isValidObjectName(objectName) {
if (!isValidPrefix(objectName)) {
return false;
}
return objectName.length !== 0;
}
/**
* check if prefix is valid
*/
export function isValidPrefix(prefix) {
if (!isString(prefix)) {
return false;
}
if (prefix.length > 1024) {
return false;
}
return true;
}
/**
* check if typeof arg number
*/
export function isNumber(arg) {
return typeof arg === 'number';
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
/**
* check if typeof arg function
*/
export function isFunction(arg) {
return typeof arg === 'function';
}
/**
* check if typeof arg string
*/
export function isString(arg) {
return typeof arg === 'string';
}
/**
* check if typeof arg object
*/
export function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
/**
* check if object is readable stream
*/
export function isReadableStream(arg) {
// eslint-disable-next-line @typescript-eslint/unbound-method
return isObject(arg) && isFunction(arg._read);
}
/**
* check if arg is boolean
*/
export function isBoolean(arg) {
return typeof arg === 'boolean';
}
export function isEmpty(o) {
return _.isEmpty(o);
}
export function isEmptyObject(o) {
return Object.values(o).filter(x => x !== undefined).length !== 0;
}
export function isDefined(o) {
return o !== null && o !== undefined;
}
/**
* check if arg is a valid date
*/
export function isValidDate(arg) {
// @ts-expect-error checknew Date(Math.NaN)
return arg instanceof Date && !isNaN(arg);
}
/**
* Create a Date string with format: 'YYYYMMDDTHHmmss' + Z
*/
export function makeDateLong(date) {
date = date || new Date();
// Gives format like: '2017-08-07T16:28:59.889Z'
const s = date.toISOString();
return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 13) + s.slice(14, 16) + s.slice(17, 19) + 'Z';
}
/**
* Create a Date string with format: 'YYYYMMDD'
*/
export function makeDateShort(date) {
date = date || new Date();
// Gives format like: '2017-08-07T16:28:59.889Z'
const s = date.toISOString();
return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 10);
}
/**
* pipesetup sets up pipe() from left to right os streams array
* pipesetup will also make sure that error emitted at any of the upstream Stream
* will be emitted at the last stream. This makes error handling simple
*/
export function pipesetup(...streams) {
// @ts-expect-error ts can't narrow this
return streams.reduce((src, dst) => {
src.on('error', err => dst.emit('error', err));
return src.pipe(dst);
});
}
/**
* return a Readable stream that emits data
*/
export function readableStream(data) {
const s = new stream.Readable();
s._read = () => {};
s.push(data);
s.push(null);
return s;
}
/**
* Process metadata to insert appropriate value to `content-type` attribute
*/
export function insertContentType(metaData, filePath) {
// check if content-type attribute present in metaData
for (const key in metaData) {
if (key.toLowerCase() === 'content-type') {
return metaData;
}
}
// if `content-type` attribute is not present in metadata, then infer it from the extension in filePath
return {
...metaData,
'content-type': probeContentType(filePath)
};
}
/**
* Function prepends metadata with the appropriate prefix if it is not already on
*/
export function prependXAMZMeta(metaData) {
if (!metaData) {
return {};
}
return _.mapKeys(metaData, (value, key) => {
if (isAmzHeader(key) || isSupportedHeader(key) || isStorageClassHeader(key)) {
return key;
}
return MetaDataHeaderPrefix + key;
});
}
/**
* Checks if it is a valid header according to the AmazonS3 API
*/
export function isAmzHeader(key) {
const temp = key.toLowerCase();
return temp.startsWith(MetaDataHeaderPrefix) || temp === 'x-amz-acl' || temp.startsWith('x-amz-server-side-encryption-') || temp === 'x-amz-server-side-encryption';
}
/**
* Checks if it is a supported Header
*/
export function isSupportedHeader(key) {
const supported_headers = ['content-type', 'cache-control', 'content-encoding', 'content-disposition', 'content-language', 'x-amz-website-redirect-location', 'if-none-match', 'if-match'];
return supported_headers.includes(key.toLowerCase());
}
/**
* Checks if it is a storage header
*/
export function isStorageClassHeader(key) {
return key.toLowerCase() === 'x-amz-storage-class';
}
export function extractMetadata(headers) {
return _.mapKeys(_.pickBy(headers, (value, key) => isSupportedHeader(key) || isStorageClassHeader(key) || isAmzHeader(key)), (value, key) => {
const lower = key.toLowerCase();
if (lower.startsWith(MetaDataHeaderPrefix)) {
return lower.slice(MetaDataHeaderPrefix.length);
}
return key;
});
}
export function getVersionId(headers = {}) {
return headers['x-amz-version-id'] || null;
}
export function getSourceVersionId(headers = {}) {
return headers['x-amz-copy-source-version-id'] || null;
}
export function sanitizeETag(etag = '') {
const replaceChars = {
'"': '',
'&quot;': '',
'&#34;': '',
'&QUOT;': '',
'&#x00022': ''
};
return etag.replace(/^("|&quot;|&#34;)|("|&quot;|&#34;)$/g, m => replaceChars[m]);
}
export function toMd5(payload) {
// use string from browser and buffer from nodejs
// browser support is tested only against minio server
return crypto.createHash('md5').update(Buffer.from(payload)).digest().toString('base64');
}
export function toSha256(payload) {
return crypto.createHash('sha256').update(payload).digest('hex');
}
/**
* toArray returns a single element array with param being the element,
* if param is just a string, and returns 'param' back if it is an array
* So, it makes sure param is always an array
*/
export function toArray(param) {
if (!Array.isArray(param)) {
return [param];
}
return param;
}
export function sanitizeObjectKey(objectName) {
// + symbol characters are not decoded as spaces in JS. so replace them first and decode to get the correct result.
const asStrName = (objectName ? objectName.toString() : '').replace(/\+/g, ' ');
return decodeURIComponent(asStrName);
}
export function sanitizeSize(size) {
return size ? Number.parseInt(size) : undefined;
}
export const PART_CONSTRAINTS = {
// absMinPartSize - absolute minimum part size (5 MiB)
ABS_MIN_PART_SIZE: 1024 * 1024 * 5,
// MIN_PART_SIZE - minimum part size 16MiB per object after which
MIN_PART_SIZE: 1024 * 1024 * 16,
// MAX_PARTS_COUNT - maximum number of parts for a single multipart session.
MAX_PARTS_COUNT: 10000,
// MAX_PART_SIZE - maximum part size 5GiB for a single multipart upload
// operation.
MAX_PART_SIZE: 1024 * 1024 * 1024 * 5,
// MAX_SINGLE_PUT_OBJECT_SIZE - maximum size 5GiB of object per PUT
// operation.
MAX_SINGLE_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 5,
// MAX_MULTIPART_PUT_OBJECT_SIZE - maximum size 5TiB of object for
// Multipart operation.
MAX_MULTIPART_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 1024 * 5
};
const GENERIC_SSE_HEADER = 'X-Amz-Server-Side-Encryption';
const ENCRYPTION_HEADERS = {
// sseGenericHeader is the AWS SSE header used for SSE-S3 and SSE-KMS.
sseGenericHeader: GENERIC_SSE_HEADER,
// sseKmsKeyID is the AWS SSE-KMS key id.
sseKmsKeyID: GENERIC_SSE_HEADER + '-Aws-Kms-Key-Id'
};
/**
* Return Encryption headers
* @param encConfig
* @returns an object with key value pairs that can be used in headers.
*/
export function getEncryptionHeaders(encConfig) {
const encType = encConfig.type;
if (!isEmpty(encType)) {
if (encType === ENCRYPTION_TYPES.SSEC) {
return {
[ENCRYPTION_HEADERS.sseGenericHeader]: 'AES256'
};
} else if (encType === ENCRYPTION_TYPES.KMS) {
return {
[ENCRYPTION_HEADERS.sseGenericHeader]: encConfig.SSEAlgorithm,
[ENCRYPTION_HEADERS.sseKmsKeyID]: encConfig.KMSMasterKeyID
};
}
}
return {};
}
export function partsRequired(size) {
const maxPartSize = PART_CONSTRAINTS.MAX_MULTIPART_PUT_OBJECT_SIZE / (PART_CONSTRAINTS.MAX_PARTS_COUNT - 1);
let requiredPartSize = size / maxPartSize;
if (size % maxPartSize > 0) {
requiredPartSize++;
}
requiredPartSize = Math.trunc(requiredPartSize);
return requiredPartSize;
}
/**
* calculateEvenSplits - computes splits for a source and returns
* start and end index slices. Splits happen evenly to be sure that no
* part is less than 5MiB, as that could fail the multipart request if
* it is not the last part.
*/
export function calculateEvenSplits(size, objInfo) {
if (size === 0) {
return null;
}
const reqParts = partsRequired(size);
const startIndexParts = [];
const endIndexParts = [];
let start = objInfo.Start;
if (isEmpty(start) || start === -1) {
start = 0;
}
const divisorValue = Math.trunc(size / reqParts);
const reminderValue = size % reqParts;
let nextStart = start;
for (let i = 0; i < reqParts; i++) {
let curPartSize = divisorValue;
if (i < reminderValue) {
curPartSize++;
}
const currentStart = nextStart;
const currentEnd = currentStart + curPartSize - 1;
nextStart = currentEnd + 1;
startIndexParts.push(currentStart);
endIndexParts.push(currentEnd);
}
return {
startIndex: startIndexParts,
endIndex: endIndexParts,
objInfo: objInfo
};
}
const fxp = new XMLParser({
numberParseOptions: {
eNotation: false,
hex: true,
leadingZeros: true
}
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function parseXml(xml) {
const result = fxp.parse(xml);
if (result.Error) {
throw result.Error;
}
return result;
}
/**
* get content size of object content to upload
*/
export async function getContentLength(s) {
// use length property of string | Buffer
if (typeof s === 'string' || Buffer.isBuffer(s)) {
return s.length;
}
// property of `fs.ReadStream`
const filePath = s.path;
if (filePath && typeof filePath === 'string') {
const stat = await fsp.lstat(filePath);
return stat.size;
}
// property of `fs.ReadStream`
const fd = s.fd;
if (fd && typeof fd === 'number') {
const stat = await fstat(fd);
return stat.size;
}
return null;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJzdHJlYW0iLCJYTUxQYXJzZXIiLCJpcGFkZHIiLCJfIiwibWltZSIsImZzcCIsImZzdGF0IiwiRU5DUllQVElPTl9UWVBFUyIsIk1ldGFEYXRhSGVhZGVyUHJlZml4IiwiaGFzaEJpbmFyeSIsImJ1ZiIsImVuYWJsZVNIQTI1NiIsInNoYTI1NnN1bSIsImNyZWF0ZUhhc2giLCJ1cGRhdGUiLCJkaWdlc3QiLCJtZDVzdW0iLCJlbmNvZGVBc0hleCIsImMiLCJjaGFyQ29kZUF0IiwidG9TdHJpbmciLCJ0b1VwcGVyQ2FzZSIsInVyaUVzY2FwZSIsInVyaVN0ciIsImVuY29kZVVSSUNvbXBvbmVudCIsInJlcGxhY2UiLCJ1cmlSZXNvdXJjZUVzY2FwZSIsInN0cmluZyIsImdldFNjb3BlIiwicmVnaW9uIiwiZGF0ZSIsInNlcnZpY2VOYW1lIiwibWFrZURhdGVTaG9ydCIsImlzQW1hem9uRW5kcG9pbnQiLCJlbmRwb2ludCIsImlzVmlydHVhbEhvc3RTdHlsZSIsInByb3RvY29sIiwiYnVja2V0IiwicGF0aFN0eWxlIiwiaW5jbHVkZXMiLCJpc1Zh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0lORCwgZWl0aGVyIGV4cHJlc3Mgb3IgaW1wbGllZC5cbiAqIFNlZSB0aGUgTGljZW5zZSBmb3IgdGhlIHNwZWNpZmljIGxhbmd1YWdlIGdvdmVybmluZyBwZXJtaXNzaW9ucyBhbmRcbiAqIGxpbWl0YXRpb25zIHVuZGVyIHRoZSBMaWNlbnNlLlxuICovXG5cbmltcG9ydCAqIGFzIGNyeXB0byBmcm9tICdub2RlOmNyeXB0bydcbmltcG9ydCAqIGFzIHN0cmVhbSBmcm9tICdub2RlOnN0cmVhbSdcblxuaW1wb3J0IHsgWE1MUGFyc2VyIH0gZnJvbSAnZmFzdC14bWwtcGFyc2VyJ1xuaW1wb3J0IGlwYWRkciBmcm9tICdpcGFkZHIuanMnXG5pbXBvcnQgXyBmcm9tICdsb2Rhc2gnXG5pbXBvcnQgKiBhcyBtaW1lIGZyb20gJ21pbWUtdHlwZXMnXG5cbmltcG9ydCB7IGZzcCwgZnN0YXQgfSBmcm9tICcuL2FzeW5jLnRzJ1xuaW1wb3J0IHR5cGUgeyBCaW5hcnksIEVuY3J5cHRpb24sIE9iamVjdE1ldGFEYXRhLCBSZXF1ZXN0SGVhZGVycywgUmVzcG9uc2VIZWFkZXIgfSBmcm9tICcuL3R5cGUudHMnXG5pbXBvcnQgeyBFTkNSWVBUSU9OX1RZUEVTIH0gZnJvbSAnLi90eXBlLnRzJ1xuXG5jb25zdCBNZXRhRGF0YUhlYWRlclByZWZpeCA9ICd4LWFtei1tZXRhLSdcblxuZXhwb3J0IGZ1bmN0aW9uIGhhc2hCaW5hcnkoYnVmOiBCdWZmZXIsIGVuYWJsZVNIQTI1NjogYm9vbGVhbikge1xuICBsZXQgc2hhMjU2c3VtID0gJydcbiAgaWYgKGVuYWJsZVNIQTI1Nikge1xuICAgIHNoYTI1NnN1bSA9IGNyeXB0by5jcmVhdGVIYXNoKCdzaGEyNTYnKS51cGRhdGUoYnV Line truncated
@@ -0,0 +1,11 @@
/**
* joinHostPort combines host and port into a network address of the
* form "host:port". If host contains a colon, as found in literal
* IPv6 addresses, then JoinHostPort returns "[host]:port".
*
* @param host
* @param port
* @returns Cleaned up host
* @internal
*/
export declare function joinHostPort(host: string, port?: number): string;
@@ -0,0 +1,23 @@
/**
* joinHostPort combines host and port into a network address of the
* form "host:port". If host contains a colon, as found in literal
* IPv6 addresses, then JoinHostPort returns "[host]:port".
*
* @param host
* @param port
* @returns Cleaned up host
* @internal
*/
export function joinHostPort(host, port) {
if (port === undefined) {
return host;
}
// We assume that host is a literal IPv6 address if host has
// colons.
if (host.includes(':')) {
return `[${host}]:${port.toString()}`;
}
return `${host}:${port.toString()}`;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJqb2luSG9zdFBvcnQiLCJob3N0IiwicG9ydCIsInVuZGVmaW5lZCIsImluY2x1ZGVzIiwidG9TdHJpbmciXSwic291cmNlcyI6WyJqb2luLWhvc3QtcG9ydC50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIGpvaW5Ib3N0UG9ydCBjb21iaW5lcyBob3N0IGFuZCBwb3J0IGludG8gYSBuZXR3b3JrIGFkZHJlc3Mgb2YgdGhlXG4gKiBmb3JtIFwiaG9zdDpwb3J0XCIuIElmIGhvc3QgY29udGFpbnMgYSBjb2xvbiwgYXMgZm91bmQgaW4gbGl0ZXJhbFxuICogSVB2NiBhZGRyZXNzZXMsIHRoZW4gSm9pbkhvc3RQb3J0IHJldHVybnMgXCJbaG9zdF06cG9ydFwiLlxuICpcbiAqIEBwYXJhbSBob3N0XG4gKiBAcGFyYW0gcG9ydFxuICogQHJldHVybnMgQ2xlYW5lZCB1cCBob3N0XG4gKiBAaW50ZXJuYWxcbiAqL1xuZXhwb3J0IGZ1bmN0aW9uIGpvaW5Ib3N0UG9ydChob3N0OiBzdHJpbmcsIHBvcnQ/OiBudW1iZXIpOiBzdHJpbmcge1xuICBpZiAocG9ydCA9PT0gdW5kZWZpbmVkKSB7XG4gICAgcmV0dXJuIGhvc3RcbiAgfVxuXG4gIC8vIFdlIGFzc3VtZSB0aGF0IGhvc3QgaXMgYSBsaXRlcmFsIElQdjYgYWRkcmVzcyBpZiBob3N0IGhhc1xuICAvLyBjb2xvbnMuXG4gIGlmIChob3N0LmluY2x1ZGVzKCc6JykpIHtcbiAgICByZXR1cm4gYFske2hvc3R9XToke3BvcnQudG9TdHJpbmcoKX1gXG4gIH1cblxuICByZXR1cm4gYCR7aG9zdH06JHtwb3J0LnRvU3RyaW5nKCl9YFxufVxuIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE9BQU8sU0FBU0EsWUFBWUEsQ0FBQ0MsSUFBWSxFQUFFQyxJQUFhLEVBQVU7RUFDaEUsSUFBSUEsSUFBSSxLQUFLQyxTQUFTLEVBQUU7SUFDdEIsT0FBT0YsSUFBSTtFQUNiOztFQUVBO0VBQ0E7RUFDQSxJQUFJQSxJQUFJLENBQUNHLFFBQVEsQ0FBQyxHQUFHLENBQUMsRUFBRTtJQUN0QixPQUFRLElBQUdILElBQUssS0FBSUMsSUFBSSxDQUFDRyxRQUFRLENBQUMsQ0FBRSxFQUFDO0VBQ3ZDO0VBRUEsT0FBUSxHQUFFSixJQUFLLElBQUdDLElBQUksQ0FBQ0csUUFBUSxDQUFDLENBQUUsRUFBQztBQUNyQyJ9
@@ -0,0 +1,17 @@
import type { ObjectMetaData } from "./type.mjs";
export declare class PostPolicy {
policy: {
conditions: (string | number)[][];
expiration?: string;
};
formData: Record<string, string>;
setExpires(date: Date): void;
setKey(objectName: string): void;
setKeyStartsWith(prefix: string): void;
setBucket(bucketName: string): void;
setContentType(type: string): void;
setContentTypeStartsWith(prefix: string): void;
setContentDisposition(value: string): void;
setContentLengthRange(min: number, max: number): void;
setUserMetaData(metaData: ObjectMetaData): void;
}
@@ -0,0 +1,98 @@
// Build PostPolicy object that can be signed by presignedPostPolicy
import * as errors from "../errors.mjs";
import { isObject, isValidBucketName, isValidObjectName, isValidPrefix } from "./helper.mjs";
export class PostPolicy {
policy = {
conditions: []
};
formData = {};
// set expiration date
setExpires(date) {
if (!date) {
throw new errors.InvalidDateError('Invalid date: cannot be null');
}
this.policy.expiration = date.toISOString();
}
// set object name
setKey(objectName) {
if (!isValidObjectName(objectName)) {
throw new errors.InvalidObjectNameError(`Invalid object name : ${objectName}`);
}
this.policy.conditions.push(['eq', '$key', objectName]);
this.formData.key = objectName;
}
// set object name prefix, i.e policy allows any keys with this prefix
setKeyStartsWith(prefix) {
if (!isValidPrefix(prefix)) {
throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`);
}
this.policy.conditions.push(['starts-with', '$key', prefix]);
this.formData.key = prefix;
}
// set bucket name
setBucket(bucketName) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError(`Invalid bucket name : ${bucketName}`);
}
this.policy.conditions.push(['eq', '$bucket', bucketName]);
this.formData.bucket = bucketName;
}
// set Content-Type
setContentType(type) {
if (!type) {
throw new Error('content-type cannot be null');
}
this.policy.conditions.push(['eq', '$Content-Type', type]);
this.formData['Content-Type'] = type;
}
// set Content-Type prefix, i.e image/ allows any image
setContentTypeStartsWith(prefix) {
if (!prefix) {
throw new Error('content-type cannot be null');
}
this.policy.conditions.push(['starts-with', '$Content-Type', prefix]);
this.formData['Content-Type'] = prefix;
}
// set Content-Disposition
setContentDisposition(value) {
if (!value) {
throw new Error('content-disposition cannot be null');
}
this.policy.conditions.push(['eq', '$Content-Disposition', value]);
this.formData['Content-Disposition'] = value;
}
// set minimum/maximum length of what Content-Length can be.
setContentLengthRange(min, max) {
if (min > max) {
throw new Error('min cannot be more than max');
}
if (min < 0) {
throw new Error('min should be > 0');
}
if (max < 0) {
throw new Error('max should be > 0');
}
this.policy.conditions.push(['content-length-range', min, max]);
}
// set user defined metadata
setUserMetaData(metaData) {
if (!isObject(metaData)) {
throw new TypeError('metadata should be of type "object"');
}
Object.entries(metaData).forEach(([key, value]) => {
const amzMetaDataKey = `x-amz-meta-${key}`;
this.policy.conditions.push(['eq', `$${amzMetaDataKey}`, value]);
this.formData[amzMetaDataKey] = value.toString();
});
}
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJlcnJvcnMiLCJpc09iamVjdCIsImlzVmFsaWRCdWNrZXROYW1lIiwiaXNWYWxpZE9iamVjdE5hbWUiLCJpc1ZhbGlkUHJlZml4IiwiUG9zdFBvbGljeSIsInBvbGljeSIsImNvbmRpdGlvbnMiLCJmb3JtRGF0YSIsInNldEV4cGlyZXMiLCJkYXRlIiwiSW52YWxpZERhdGVFcnJvciIsImV4cGlyYXRpb24iLCJ0b0lTT1N0cmluZyIsInNldEtleSIsIm9iamVjdE5hbWUiLCJJbnZhbGlkT2JqZWN0TmFtZUVycm9yIiwicHVzaCIsImtleSIsInNldEtleVN0YXJ0c1dpdGgiLCJwcmVmaXgiLCJJbnZhbGlkUHJlZml4RXJyb3IiLCJzZXRCdWNrZXQiLCJidWNrZXROYW1lIiwiSW52YWxpZEJ1Y2tldE5hbWVFcnJvciIsImJ1Y2tldCIsInNldENvbnRlbnRUeXBlIiwidHlwZSIsIkVycm9yIiwic2V0Q29udGVudFR5cGVTdGFydHNXaXRoIiwic2V0Q29udGVudERpc3Bvc2l0aW9uIiwidmFsdWUiLCJzZXRDb250ZW50TGVuZ3RoUmFuZ2UiLCJtaW4iLCJtYXgiLCJzZXRVc2VyTWV0YURhdGEiLCJtZXRhRGF0YSIsIlR5cGVFcnJvciIsIk9iamVjdCIsImVudHJpZXMiLCJmb3JFYWNoIiwiYW16TWV0YURhdGFLZXkiLCJ0b1N0cmluZyJdLCJzb3VyY2VzIjpbInBvc3QtcG9saWN5LnRzIl0sInNvdXJjZXNDb250ZW50IjpbIi8vIEJ1aWxkIFBvc3RQb2xpY3kgb2JqZWN0IHRoYXQgY2FuIGJlIHN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SYW5nZShtaW46IG51bWJlciwgbWF4OiBudW1iZXIpIHtcbiAgICBpZiAobWluID4gbWF4KSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ21pbiBjYW5ub3QgYmUgbW9yZSB0aGFuIG1heCcpXG4gICAgfVxuICAgIGlmIChtaW4gPCAwKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ21pbiBzaG91bGQgYmUgPiAwJylcbiAgICB9XG4gICAgaWYgKG1heCA8IDApIHtcbiAgICAgIHRocm93IG5ldyBFcnJvcignbWF4IHNob3VsZCBiZSA+IDAnKVxuICAgIH1cbiAgICB0aGlzLnBvbGljeS5jb25kaXRpb25zLnB1c2goWydjb250ZW50LWxlbmd0aC1yYW5nZScsIG1pbiwgbWF4XSlcbiAgfVxuXG4gIC8vIHNldCB1c2VyIGRlZmluZWQgbWV0YWRhdGFcbiAgc2V0VXNlck1ldGFEYXRhKG1ldGFEYXRhOiBPYmplY3RNZXRhRGF0YSkge1xuICAgIGlmICghaXNPYmplY3QobWV0YURhdGEpKSB7XG4gICAgICB0aHJvdyBuZXcgVHlwZUVycm9yKCdtZXRhZGF0YSBzaG91bGQgYmUgb2YgdHlwZSBcIm9iamVjdFwiJylcbiAgICB9XG4gICAgT2JqZWN0LmVudHJpZXMobWV Line truncated
+11
View File
@@ -0,0 +1,11 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import type * as http from 'node:http';
import type * as https from 'node:https';
import type * as stream from 'node:stream';
import type { Transport } from "./type.mjs";
export declare function request(transport: Transport, opt: https.RequestOptions, body?: Buffer | string | stream.Readable | null): Promise<http.IncomingMessage>;
export declare const retryHttpCodes: Record<string, boolean>;
export declare function requestWithRetry(transport: Transport, opt: https.RequestOptions, body?: Buffer | string | stream.Readable | null, maxRetries?: number): Promise<http.IncomingMessage>;
+75
View File
@@ -0,0 +1,75 @@
import { pipeline } from "stream";
import { promisify } from "util";
const pipelineAsync = promisify(pipeline);
export async function request(transport, opt, body = null) {
return new Promise((resolve, reject) => {
const requestObj = transport.request(opt, response => {
resolve(response);
});
requestObj.on('error', reject);
if (!body || Buffer.isBuffer(body) || typeof body === 'string') {
requestObj.end(body);
} else {
pipelineAsync(body, requestObj).catch(reject);
}
});
}
const MAX_RETRIES = 10;
const EXP_BACK_OFF_BASE_DELAY = 1000; // Base delay for exponential backoff
const ADDITIONAL_DELAY_FACTOR = 1.0; // to avoid synchronized retries
// Retryable error codes for HTTP ( ref: minio-go)
export const retryHttpCodes = {
408: true,
429: true,
499: true,
500: true,
502: true,
503: true,
504: true,
520: true
};
const isHttpRetryable = httpResCode => {
return retryHttpCodes[httpResCode] !== undefined;
};
const sleep = ms => {
return new Promise(resolve => setTimeout(resolve, ms));
};
const getExpBackOffDelay = retryCount => {
const backOffBy = EXP_BACK_OFF_BASE_DELAY * 2 ** retryCount;
const additionalDelay = Math.random() * backOffBy * ADDITIONAL_DELAY_FACTOR;
return backOffBy + additionalDelay;
};
export async function requestWithRetry(transport, opt, body = null, maxRetries = MAX_RETRIES) {
let attempt = 0;
let isRetryable = false;
while (attempt <= maxRetries) {
try {
const response = await request(transport, opt, body);
// Check if the HTTP status code is retryable
if (isHttpRetryable(response.statusCode)) {
isRetryable = true;
throw new Error(`Retryable HTTP status: ${response.statusCode}`); // trigger retry attempt with calculated delay
}
return response; // Success, return the raw response
} catch (err) {
if (isRetryable) {
attempt++;
isRetryable = false;
if (attempt > maxRetries) {
throw new Error(`Request failed after ${maxRetries} retries: ${err}`);
}
const delay = getExpBackOffDelay(attempt);
// eslint-disable-next-line no-console
console.warn(`${new Date().toLocaleString()} Retrying request (attempt ${attempt}/${maxRetries}) after ${delay}ms due to: ${err}`);
await sleep(delay);
} else {
throw err; // re-throw if any request, syntax errors
}
}
}
throw new Error(`${MAX_RETRIES} Retries exhausted, request failed.`);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJwaXBlbGluZSIsInByb21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YWNrT2ZmRGVsYXkoYXR0ZW1wdClcbiAgICAgICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIG5vLWNvbnNvbGVcbiAgICAgICAgY29uc29sZS53YXJuKFxuICAgICAgICAgIGAke25ldyBEYXRlKCkudG9Mb2NhbGVTdHJpbmcoKX0gUmV0cnlpbmcgcmVxdWVzdCAoYXR0ZW1wdCAke2F0dGVtcHR9LyR7bWF4UmV0cmllc30pIGFmdGVyICR7ZGVsYXl9bXMgZHVlIHRvOiAke2Vycn1gLFxuICAgICAgICApXG4gICAgICAgIGF3YWl0IHNsZWVwKGRlbGF5KVxuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdGhyb3cgZXJyIC8vIHJlLXRocm93IGlmIGFueSByZXF1ZXN0LCBzeW50YXggZXJyb3JzXG4gICAgICB9XG4gICAgfVxuICB9XG5cbiAgdGhyb3cgbmV3IEVycm9yKGAke01BWF9SRVRSSUVTfSBSZXRyaWVzIGV4aGF1c3RlZCwgcmVxdWVzdCBmYWl Line truncated
@@ -0,0 +1,8 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import type http from 'node:http';
import type stream from 'node:stream';
export declare function readAsBuffer(res: stream.Readable): Promise<Buffer>;
export declare function readAsString(res: http.IncomingMessage): Promise<string>;
export declare function drainResponse(res: stream.Readable): Promise<void>;
+16
View File
@@ -0,0 +1,16 @@
export async function readAsBuffer(res) {
return new Promise((resolve, reject) => {
const body = [];
res.on('data', chunk => body.push(chunk)).on('error', e => reject(e)).on('end', () => resolve(Buffer.concat(body)));
});
}
export async function readAsString(res) {
const body = await readAsBuffer(res);
return body.toString();
}
export async function drainResponse(res) {
return new Promise((resolve, reject) => {
res.on('data', () => {}).on('error', e => reject(e)).on('end', () => resolve());
});
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJyZWFkQXNCdWZmZXIiLCJyZXMiLCJQcm9taXNlIiwicmVzb2x2ZS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ENBQUMsQ0FDcEJBLEVBQUUsQ0FBQyxPQUFPLEVBQUdHLENBQUMsSUFBS0wsTUFBTSxDQUFDSyxDQUFDLENBQUMsQ0FBQyxDQUM3QkgsRUFBRSxDQUFDLEtBQUssRUFBRSxNQUFNSCxPQUFPLENBQUMsQ0FBQyxDQUFDO0VBQy9CLENBQUMsQ0FBQztBQUNKIn0=
@@ -0,0 +1,38 @@
declare const awsS3Endpoint: {
'af-south-1': string;
'ap-east-1': string;
'ap-south-1': string;
'ap-south-2': string;
'ap-southeast-1': string;
'ap-southeast-2': string;
'ap-southeast-3': string;
'ap-southeast-4': string;
'ap-southeast-5': string;
'ap-northeast-1': string;
'ap-northeast-2': string;
'ap-northeast-3': string;
'ca-central-1': string;
'ca-west-1': string;
'cn-north-1': string;
'eu-central-1': string;
'eu-central-2': string;
'eu-north-1': string;
'eu-south-1': string;
'eu-south-2': string;
'eu-west-1': string;
'eu-west-2': string;
'eu-west-3': string;
'il-central-1': string;
'me-central-1': string;
'me-south-1': string;
'sa-east-1': string;
'us-east-1': string;
'us-east-2': string;
'us-west-1': string;
'us-west-2': string;
'us-gov-east-1': string;
'us-gov-west-1': string;
};
export type Region = keyof typeof awsS3Endpoint | string;
export declare function getS3Endpoint(region: Region): string;
export {};
@@ -0,0 +1,68 @@
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015, 2016 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { isString } from "./helper.mjs";
// List of currently supported endpoints.
const awsS3Endpoint = {
'af-south-1': 's3.af-south-1.amazonaws.com',
'ap-east-1': 's3.ap-east-1.amazonaws.com',
'ap-south-1': 's3.ap-south-1.amazonaws.com',
'ap-south-2': 's3.ap-south-2.amazonaws.com',
'ap-southeast-1': 's3.ap-southeast-1.amazonaws.com',
'ap-southeast-2': 's3.ap-southeast-2.amazonaws.com',
'ap-southeast-3': 's3.ap-southeast-3.amazonaws.com',
'ap-southeast-4': 's3.ap-southeast-4.amazonaws.com',
'ap-southeast-5': 's3.ap-southeast-5.amazonaws.com',
'ap-northeast-1': 's3.ap-northeast-1.amazonaws.com',
'ap-northeast-2': 's3.ap-northeast-2.amazonaws.com',
'ap-northeast-3': 's3.ap-northeast-3.amazonaws.com',
'ca-central-1': 's3.ca-central-1.amazonaws.com',
'ca-west-1': 's3.ca-west-1.amazonaws.com',
'cn-north-1': 's3.cn-north-1.amazonaws.com.cn',
'eu-central-1': 's3.eu-central-1.amazonaws.com',
'eu-central-2': 's3.eu-central-2.amazonaws.com',
'eu-north-1': 's3.eu-north-1.amazonaws.com',
'eu-south-1': 's3.eu-south-1.amazonaws.com',
'eu-south-2': 's3.eu-south-2.amazonaws.com',
'eu-west-1': 's3.eu-west-1.amazonaws.com',
'eu-west-2': 's3.eu-west-2.amazonaws.com',
'eu-west-3': 's3.eu-west-3.amazonaws.com',
'il-central-1': 's3.il-central-1.amazonaws.com',
'me-central-1': 's3.me-central-1.amazonaws.com',
'me-south-1': 's3.me-south-1.amazonaws.com',
'sa-east-1': 's3.sa-east-1.amazonaws.com',
'us-east-1': 's3.us-east-1.amazonaws.com',
'us-east-2': 's3.us-east-2.amazonaws.com',
'us-west-1': 's3.us-west-1.amazonaws.com',
'us-west-2': 's3.us-west-2.amazonaws.com',
'us-gov-east-1': 's3.us-gov-east-1.amazonaws.com',
'us-gov-west-1': 's3.us-gov-west-1.amazonaws.com'
// Add new endpoints here.
};
// getS3Endpoint get relevant endpoint for the region.
export function getS3Endpoint(region) {
if (!isString(region)) {
throw new TypeError(`Invalid region: ${region}`);
}
const endpoint = awsS3Endpoint[region];
if (endpoint) {
return endpoint;
}
return 's3.amazonaws.com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2QkFBNkI7RUFDM0MsV0FBVyxFQUFFLDRCQUE0QjtFQUN6QyxZQUFZLEVBQUUsNkJBQTZCO0VBQzNDLFlBQVksRUFBRSw2QkFBNkI7RUFDM0MsZ0JBQWdCLEVBQUUsaUNBQWlDO0VBQ25ELGdCQUFnQixFQUFFLGlDQUFpQztFQUNuRCxnQkFBZ0IsRUFBRSxpQ0FBaUM7RUFDbkQsZ0JBQWdCLEVBQUUsaUNBQWlDO0VBQ25ELGdCQUFnQixFQUFFLGlDQUFpQztFQUNuRCxnQkFBZ0IsRUFBRSxpQ0FBaUM7RUFDbkQsZ0JBQWdCLEVBQUUsaUNBQWlDO0VBQ25ELGdCQUFnQixFQUFFLGlDQUFpQztFQUNuRCxjQUFjLEVBQUUsK0JBQStCO0VBQy9DLFdBQVcsRUFBRSw0QkFBNEI7RUFDekMsWUFBWSxFQUFFLGdDQUFnQztFQUM5QyxjQUFjLEVBQUUsK0JBQStCO0VBQy9DLGNBQWMsRUFBRSwrQkFBK0I7RUFDL0MsWUFBWSxFQUFFLDZCQUE2QjtFQUMzQyxZQUFZLEVBQUUsNkJBQTZCO0VBQzNDLFlBQVksRUFBRSw2QkFBNkI7RUFDM0MsV0FBVyxFQUFFLDRCQUE0QjtFQUN6QyxXQUFXLEV Line truncated
+447
View File
@@ -0,0 +1,447 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import type * as http from 'node:http';
import type { Readable as ReadableStream } from 'node:stream';
import type { CopyDestinationOptions, CopySourceOptions } from "../helpers.mjs";
import type { CopyConditions } from "./copy-conditions.mjs";
export type VersionIdentificator = {
versionId?: string;
};
export type GetObjectOpts = VersionIdentificator & {
SSECustomerAlgorithm?: string;
SSECustomerKey?: string;
SSECustomerKeyMD5?: string;
};
export type Binary = string | Buffer;
export type ResponseHeader = Record<string, string>;
export type ObjectMetaData = Record<string, string | number>;
export type RequestHeaders = Record<string, string | boolean | number | undefined>;
export type Encryption = {
type: ENCRYPTION_TYPES.SSEC;
} | {
type: ENCRYPTION_TYPES.KMS;
SSEAlgorithm?: string;
KMSMasterKeyID?: string;
};
export type EnabledOrDisabledStatus = 'Enabled' | 'Disabled';
export declare enum ENCRYPTION_TYPES {
/**
* SSEC represents server-side-encryption with customer provided keys
*/
SSEC = "SSE-C",
/**
* KMS represents server-side-encryption with managed keys
*/
KMS = "KMS",
}
export declare enum RETENTION_MODES {
GOVERNANCE = "GOVERNANCE",
COMPLIANCE = "COMPLIANCE",
}
export declare enum RETENTION_VALIDITY_UNITS {
DAYS = "Days",
YEARS = "Years",
}
export declare enum LEGAL_HOLD_STATUS {
ENABLED = "ON",
DISABLED = "OFF",
}
export type Transport = Pick<typeof http, 'request'>;
export interface IRequest {
protocol: string;
port?: number | string;
method: string;
path: string;
headers: RequestHeaders;
}
export type ICanonicalRequest = string;
export interface IncompleteUploadedBucketItem {
key: string;
uploadId: string;
size: number;
}
export interface MetadataItem {
Key: string;
Value: string;
}
export interface ItemBucketMetadataList {
Items: MetadataItem[];
}
export interface ItemBucketMetadata {
[key: string]: any;
}
export interface ItemBucketTags {
[key: string]: any;
}
export interface BucketItemFromList {
name: string;
creationDate: Date;
}
export interface BucketItemCopy {
etag: string;
lastModified: Date;
}
export type BucketItem = {
name: string;
size: number;
etag: string;
prefix?: never;
lastModified: Date;
} | {
name?: never;
etag?: never;
lastModified?: never;
prefix: string;
size: 0;
};
export type BucketItemWithMetadata = BucketItem & {
metadata?: ItemBucketMetadata | ItemBucketMetadataList;
tags?: ItemBucketTags;
};
export interface BucketStream<T> extends ReadableStream {
on(event: 'data', listener: (item: T) => void): this;
on(event: 'end' | 'pause' | 'readable' | 'resume' | 'close', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface BucketItemStat {
size: number;
etag: string;
lastModified: Date;
metaData: ItemBucketMetadata;
versionId?: string | null;
}
export type StatObjectOpts = {
versionId?: string;
};
export type ReplicationRuleStatus = {
Status: EnabledOrDisabledStatus;
};
export type Tag = {
Key: string;
Value: string;
};
export type Tags = Record<string, string>;
export type ReplicationRuleDestination = {
Bucket: string;
StorageClass: string;
};
export type ReplicationRuleAnd = {
Prefix: string;
Tags: Tag[];
};
export type ReplicationRuleFilter = {
Prefix: string;
And: ReplicationRuleAnd;
Tag: Tag;
};
export type ReplicaModifications = {
Status: ReplicationRuleStatus;
};
export type SourceSelectionCriteria = {
ReplicaModifications: ReplicaModifications;
};
export type ExistingObjectReplication = {
Status: ReplicationRuleStatus;
};
export type ReplicationRule = {
ID: string;
Status: ReplicationRuleStatus;
Priority: number;
DeleteMarkerReplication: ReplicationRuleStatus;
DeleteReplication: ReplicationRuleStatus;
Destination: ReplicationRuleDestination;
Filter: ReplicationRuleFilter;
SourceSelectionCriteria: SourceSelectionCriteria;
ExistingObjectReplication: ExistingObjectReplication;
};
export type ReplicationConfigOpts = {
role: string;
rules: ReplicationRule[];
};
export type ReplicationConfig = {
ReplicationConfiguration: ReplicationConfigOpts;
};
export type ResultCallback<T> = (error: Error | null, result: T) => void;
export type GetObjectLegalHoldOptions = {
versionId: string;
};
/**
* @deprecated keep for backward compatible, use `LEGAL_HOLD_STATUS` instead
*/
export type LegalHoldStatus = LEGAL_HOLD_STATUS;
export type PutObjectLegalHoldOptions = {
versionId?: string;
status: LEGAL_HOLD_STATUS;
};
export interface UploadedObjectInfo {
etag: string;
versionId: string | null;
}
export interface RetentionOptions {
versionId: string;
mode?: RETENTION_MODES;
retainUntilDate?: IsoDate;
governanceBypass?: boolean;
}
export type Retention = RetentionOptions | EmptyObject;
export type IsoDate = string;
export type EmptyObject = Record<string, never>;
export type ObjectLockInfo = {
objectLockEnabled: EnabledOrDisabledStatus;
mode: RETENTION_MODES;
unit: RETENTION_VALIDITY_UNITS;
validity: number;
} | EmptyObject;
export type ObjectLockConfigParam = {
ObjectLockEnabled?: 'Enabled' | undefined;
Rule?: {
DefaultRetention: {
Mode: RETENTION_MODES;
Days: number;
Years: number;
} | EmptyObject;
} | EmptyObject;
};
export type VersioningEnabled = 'Enabled';
export type VersioningSuspended = 'Suspended';
export type TaggingOpts = {
versionId: string;
};
export type PutTaggingParams = {
bucketName: string;
objectName?: string;
tags: Tags;
putOpts?: TaggingOpts;
};
export type RemoveTaggingParams = {
bucketName: string;
objectName?: string;
removeOpts?: TaggingOpts;
};
export type InputSerialization = {
CompressionType?: 'NONE' | 'GZIP' | 'BZIP2';
CSV?: {
AllowQuotedRecordDelimiter?: boolean;
Comments?: string;
FieldDelimiter?: string;
FileHeaderInfo?: 'NONE' | 'IGNORE' | 'USE';
QuoteCharacter?: string;
QuoteEscapeCharacter?: string;
RecordDelimiter?: string;
};
JSON?: {
Type: 'DOCUMENT' | 'LINES';
};
Parquet?: EmptyObject;
};
export type OutputSerialization = {
CSV?: {
FieldDelimiter?: string;
QuoteCharacter?: string;
QuoteEscapeCharacter?: string;
QuoteFields?: string;
RecordDelimiter?: string;
};
JSON?: {
RecordDelimiter?: string;
};
};
export type SelectProgress = {
Enabled: boolean;
};
export type ScanRange = {
Start: number;
End: number;
};
export type SelectOptions = {
expression: string;
expressionType?: string;
inputSerialization: InputSerialization;
outputSerialization: OutputSerialization;
requestProgress?: SelectProgress;
scanRange?: ScanRange;
};
export type Expiration = {
Date?: string;
Days: number;
DeleteMarker?: boolean;
DeleteAll?: boolean;
};
export type RuleFilterAnd = {
Prefix: string;
Tags: Tag[];
};
export type RuleFilter = {
And?: RuleFilterAnd;
Prefix: string;
Tag?: Tag[];
};
export type NoncurrentVersionExpiration = {
NoncurrentDays: number;
NewerNoncurrentVersions?: number;
};
export type NoncurrentVersionTransition = {
StorageClass: string;
NoncurrentDays?: number;
NewerNoncurrentVersions?: number;
};
export type Transition = {
Date?: string;
StorageClass: string;
Days: number;
};
export type AbortIncompleteMultipartUpload = {
DaysAfterInitiation: number;
};
export type LifecycleRule = {
AbortIncompleteMultipartUpload?: AbortIncompleteMultipartUpload;
ID: string;
Prefix?: string;
Status?: string;
Expiration?: Expiration;
Filter?: RuleFilter;
NoncurrentVersionExpiration?: NoncurrentVersionExpiration;
NoncurrentVersionTransition?: NoncurrentVersionTransition;
Transition?: Transition;
};
export type LifecycleConfig = {
Rule: LifecycleRule[];
};
export type LifeCycleConfigParam = LifecycleConfig | null | undefined | '';
export type ApplySSEByDefault = {
KmsMasterKeyID?: string;
SSEAlgorithm: string;
};
export type EncryptionRule = {
ApplyServerSideEncryptionByDefault?: ApplySSEByDefault;
};
export type EncryptionConfig = {
Rule: EncryptionRule[];
};
export type GetObjectRetentionOpts = {
versionId: string;
};
export type ObjectRetentionInfo = {
mode: RETENTION_MODES;
retainUntilDate: string;
};
export type RemoveObjectsEntry = {
name: string;
versionId?: string;
};
export type ObjectName = string;
export type RemoveObjectsParam = ObjectName[] | RemoveObjectsEntry[];
export type RemoveObjectsRequestEntry = {
Key: string;
VersionId?: string;
};
export type RemoveObjectsResponse = null | undefined | {
Error?: {
Code?: string;
Message?: string;
Key?: string;
VersionId?: string;
};
};
export type CopyObjectResultV1 = {
etag: string;
lastModified: string | Date;
};
export type CopyObjectResultV2 = {
Bucket?: string;
Key?: string;
LastModified: string | Date;
MetaData?: ResponseHeader;
VersionId?: string | null;
SourceVersionId?: string | null;
Etag?: string;
Size?: number;
};
export type CopyObjectResult = CopyObjectResultV1 | CopyObjectResultV2;
export type CopyObjectParams = [CopySourceOptions, CopyDestinationOptions] | [string, string, string, CopyConditions?];
export type ExcludedPrefix = {
Prefix: string;
};
export type BucketVersioningConfiguration = {
Status: VersioningEnabled | VersioningSuspended;
MFADelete?: string;
ExcludedPrefixes?: ExcludedPrefix[];
ExcludeFolders?: boolean;
};
export type UploadPartConfig = {
bucketName: string;
objectName: string;
uploadID: string;
partNumber: number;
headers: RequestHeaders;
sourceObj: string;
};
export type PreSignRequestParams = {
[key: string]: string;
};
/** List object api types **/
export type CommonPrefix = {
Prefix: string;
};
export type Owner = {
ID: string;
DisplayName: string;
};
export type Metadata = {
Items: MetadataItem[];
};
export type ObjectInfo = {
key?: string;
name?: string;
lastModified?: Date;
etag?: string;
owner?: Owner;
storageClass?: string;
userMetadata?: Metadata;
userTags?: string;
prefix?: string;
size?: number;
};
export type ListObjectQueryRes = {
isTruncated?: boolean;
nextMarker?: string;
versionIdMarker?: string;
objects?: ObjectInfo[];
};
export type ListObjectQueryOpts = {
Delimiter?: string;
MaxKeys?: number;
IncludeVersion?: boolean;
};
/** List object api types **/
export type ObjectVersionEntry = {
IsLatest?: string;
VersionId?: string;
};
export type ObjectRowEntry = ObjectVersionEntry & {
Key: string;
LastModified?: Date | undefined;
ETag?: string;
Size?: string;
Owner?: Owner;
StorageClass?: string;
};
export interface ListBucketResultV1 {
Name?: string;
Prefix?: string;
ContinuationToken?: string;
KeyCount?: string;
Marker?: string;
MaxKeys?: string;
Delimiter?: string;
IsTruncated?: boolean;
Contents?: ObjectRowEntry[];
NextKeyMarker?: string;
CommonPrefixes?: CommonPrefix[];
Version?: ObjectRowEntry[];
DeleteMarker?: ObjectRowEntry[];
VersionIdMarker?: string;
NextVersionIdMarker?: string;
}
+34
View File
@@ -0,0 +1,34 @@
// nodejs IncomingHttpHeaders is Record<string, string | string[]>, but it's actually this:
export let ENCRYPTION_TYPES = /*#__PURE__*/function (ENCRYPTION_TYPES) {
ENCRYPTION_TYPES["SSEC"] = "SSE-C";
ENCRYPTION_TYPES["KMS"] = "KMS";
return ENCRYPTION_TYPES;
}({});
export let RETENTION_MODES = /*#__PURE__*/function (RETENTION_MODES) {
RETENTION_MODES["GOVERNANCE"] = "GOVERNANCE";
RETENTION_MODES["COMPLIANCE"] = "COMPLIANCE";
return RETENTION_MODES;
}({});
export let RETENTION_VALIDITY_UNITS = /*#__PURE__*/function (RETENTION_VALIDITY_UNITS) {
RETENTION_VALIDITY_UNITS["DAYS"] = "Days";
RETENTION_VALIDITY_UNITS["YEARS"] = "Years";
return RETENTION_VALIDITY_UNITS;
}({});
export let LEGAL_HOLD_STATUS = /*#__PURE__*/function (LEGAL_HOLD_STATUS) {
LEGAL_HOLD_STATUS["ENABLED"] = "ON";
LEGAL_HOLD_STATUS["DISABLED"] = "OFF";
return LEGAL_HOLD_STATUS;
}({});
/* Replication Config types */
/* Replication Config types */
/**
* @deprecated keep for backward compatible, use `LEGAL_HOLD_STATUS` instead
*/
/** List object api types **/ // Common types
/** List object api types **/
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFTkNSWVBUSU9OX1RZUEVTIiwiUkVURU5USU9OX01PREVTIiwiUkVURU5USU9OX1ZBTElESVRZX1VOSVRTIiwiTEVHQUxfSE9MRF9TVEFUVVMiXSwic291cmNlcyI6WyJ0eXBlLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB0eXBlICogYXMgaHR0cCBmcm9tICdub2RlOmh0dHAnXG5pbXBvcnQgdHlwZSB7IFJlYWRhYmxlIGFzIFJlYWRhYmxlU3RyZWFtIH0gZnJvbSAnbm9kZTpzdHJlYW0nXG5cbmltcG9ydCB0eXBlIHsgQ29weURlc3RpbmF0aW9uT3B0aW9ucywgQ29weVNvdXJjZU9wdGlvbnMgfSBmcm9tICcuLi9oZWxwZXJzLnRzJ1xuaW1wb3J0IHR5cGUgeyBDb3B5Q29uZGl0aW9ucyB9IGZyb20gJy4vY29weS1jb25kaXRpb25zLnRzJ1xuXG5leHBvcnQgdHlwZSBWZXJzaW9uSWRlbnRpZmljYXRvciA9IHtcbiAgdmVyc2lvbklkPzogc3RyaW5nXG59XG5cbmV4cG9ydCB0eXBlIEdldE9iamVjdE9wdHMgPSBWZXJzaW9uSWRlbnRpZmljYXRvciAmIHtcbiAgU1NFQ3VzdG9tZXJBbGdvcml0aG0/OiBzdHJpbmdcbiAgU1NFQ3VzdG9tZXJLZXk/OiBzdHJpbmdcbiAgU1NFQ3VzdG9tZXJLZXlNRDU/OiBzdHJpbmdcbn1cblxuZXhwb3J0IHR5cGUgQmluYXJ5ID0gc3RyaW5nIHwgQnVmZmVyXG5cbi8vIG5vZGVqcyBJb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0ZW5lcjogKGl0ZW06IFQpID0+IHZvaWQpOiB0aGlzXG5cbiAgb24oZXZlbnQ6ICdlbmQnIHwgJ3BhdXNlJyB8ICdyZWFkYWJsZScgfCAncmVzdW1lJyB8ICdjbG9zZScsIGxpc3RlbmVyOiAoKSA9PiB2b2lkKTogdGhpc1xuXG4gIG9uKGV2ZW50OiAnZXJyb3InLCBsaXN0ZW5lcjogKGVycjogRXJyb3IpID0+IHZvaWQpOiB0aGlzXG5cbiAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIEB0eXBlc2NyaXB0LWVzbGludC9uby1leHBsaWNpdC1hbnlcbiAgb24oZXZlbnQ6IHN0cmluZyB8IHN5bWJvbCwgbGlzdGVuZXI6ICguLi5hcmdzOiBhbnlbXSkgPT4gdm9pZCk6IHRoaXNcbn1cblxuZXhwb3J0IGludGVyZmFjZSBCdWNrZXRJdGVtU3RhdCB7XG4gIHNpemU6IG51bWJlclxuICBldGFnOiBzdHJpbmdcbiAgbGFzdE1vZGlmaWVkOiBEYXRlXG4gIG1ldGFEYXRhOiBJdGVtQnVja2V0TWV0YWRhdGFcbiAgdmVyc2lvbklkPzogc3RyaW5nIHwgbnVsbFxufVxuXG5leHBvcnQgdHlwZSBTdGF0T2JqZWN0T3B0cyA9IHtcbiAgdmVyc2lvbklkPzogc3RyaW5nXG59XG5cbi8qIFJlcGxpY2F0aW9uIENvbmZpZyB0eXBlcyAqL1xuZXhwb3J0IHR5cGUgUmVwbGljYXRpb25SdWxlU3RhdHVzID0ge1x Line truncated
@@ -0,0 +1,90 @@
/// <reference types="node" />
/// <reference types="node" />
import type * as http from 'node:http';
import { SelectResults } from "../helpers.mjs";
import type { BucketItemFromList, BucketItemWithMetadata, CopyObjectResultV1, ObjectInfo, ObjectLockInfo, ReplicationConfig } from "./type.mjs";
export declare function parseBucketRegion(xml: string): string;
export declare function parseError(xml: string, headerInfo: Record<string, unknown>): Record<string, unknown>;
export declare function parseResponseError(response: http.IncomingMessage): Promise<Record<string, string>>;
/**
* parse XML response for list objects v2 with metadata in a bucket
*/
export declare function parseListObjectsV2WithMetadata(xml: string): {
objects: Array<BucketItemWithMetadata>;
isTruncated: boolean;
nextContinuationToken: string;
};
export type UploadedPart = {
part: number;
lastModified?: Date;
etag: string;
size: number;
};
export declare function parseListParts(xml: string): {
isTruncated: boolean;
marker: number;
parts: UploadedPart[];
};
export declare function parseListBucket(xml: string): BucketItemFromList[];
export declare function parseInitiateMultipart(xml: string): string;
export declare function parseReplicationConfig(xml: string): ReplicationConfig;
export declare function parseObjectLegalHoldConfig(xml: string): any;
export declare function parseTagging(xml: string): any;
export declare function parseCompleteMultipart(xml: string): {
location: any;
bucket: any;
key: any;
etag: any;
errCode?: undefined;
errMessage?: undefined;
} | {
errCode: any;
errMessage: any;
location?: undefined;
bucket?: undefined;
key?: undefined;
etag?: undefined;
} | undefined;
type UploadID = string;
export type ListMultipartResult = {
uploads: {
key: string;
uploadId: UploadID;
initiator?: {
id: string;
displayName: string;
};
owner?: {
id: string;
displayName: string;
};
storageClass: unknown;
initiated: Date;
}[];
prefixes: {
prefix: string;
}[];
isTruncated: boolean;
nextKeyMarker: string;
nextUploadIdMarker: string;
};
export declare function parseListMultipart(xml: string): ListMultipartResult;
export declare function parseObjectLockConfig(xml: string): ObjectLockInfo;
export declare function parseBucketVersioningConfig(xml: string): any;
export declare function parseSelectObjectContentResponse(res: Buffer): SelectResults | undefined;
export declare function parseLifecycleConfig(xml: string): any;
export declare function parseBucketEncryptionConfig(xml: string): any;
export declare function parseObjectRetentionConfig(xml: string): {
mode: any;
retainUntilDate: any;
};
export declare function removeObjectsParser(xml: string): any[];
export declare function parseCopyObject(xml: string): CopyObjectResultV1;
export declare function parseListObjects(xml: string): {
objects: ObjectInfo[];
isTruncated?: boolean | undefined;
nextMarker?: string | undefined;
versionIdMarker?: string | undefined;
};
export declare function uploadPartParser(xml: string): any;
export {};
+691
View File
@@ -0,0 +1,691 @@
import crc32 from 'buffer-crc32';
import { XMLParser } from 'fast-xml-parser';
import * as errors from "../errors.mjs";
import { SelectResults } from "../helpers.mjs";
import { isObject, parseXml, readableStream, sanitizeETag, sanitizeObjectKey, sanitizeSize, toArray } from "./helper.mjs";
import { readAsString } from "./response.mjs";
import { RETENTION_VALIDITY_UNITS } from "./type.mjs";
// parse XML response for bucket region
export function parseBucketRegion(xml) {
// return region information
return parseXml(xml).LocationConstraint;
}
const fxp = new XMLParser();
const fxpWithoutNumParser = new XMLParser({
// @ts-ignore
numberParseOptions: {
skipLike: /./
}
});
// Parse XML and return information as Javascript types
// parse error XML response
export function parseError(xml, headerInfo) {
let xmlErr = {};
const xmlObj = fxp.parse(xml);
if (xmlObj.Error) {
xmlErr = xmlObj.Error;
}
const e = new errors.S3Error();
Object.entries(xmlErr).forEach(([key, value]) => {
e[key.toLowerCase()] = value;
});
Object.entries(headerInfo).forEach(([key, value]) => {
e[key] = value;
});
return e;
}
// Generates an Error object depending on http statusCode and XML body
export async function parseResponseError(response) {
const statusCode = response.statusCode;
let code = '',
message = '';
if (statusCode === 301) {
code = 'MovedPermanently';
message = 'Moved Permanently';
} else if (statusCode === 307) {
code = 'TemporaryRedirect';
message = 'Are you using the correct endpoint URL?';
} else if (statusCode === 403) {
code = 'AccessDenied';
message = 'Valid and authorized credentials required';
} else if (statusCode === 404) {
code = 'NotFound';
message = 'Not Found';
} else if (statusCode === 405) {
code = 'MethodNotAllowed';
message = 'Method Not Allowed';
} else if (statusCode === 501) {
code = 'MethodNotAllowed';
message = 'Method Not Allowed';
} else if (statusCode === 503) {
code = 'SlowDown';
message = 'Please reduce your request rate.';
} else {
const hErrCode = response.headers['x-minio-error-code'];
const hErrDesc = response.headers['x-minio-error-desc'];
if (hErrCode && hErrDesc) {
code = hErrCode;
message = hErrDesc;
}
}
const headerInfo = {};
// A value created by S3 compatible server that uniquely identifies the request.
headerInfo.amzRequestid = response.headers['x-amz-request-id'];
// A special token that helps troubleshoot API replies and issues.
headerInfo.amzId2 = response.headers['x-amz-id-2'];
// Region where the bucket is located. This header is returned only
// in HEAD bucket and ListObjects response.
headerInfo.amzBucketRegion = response.headers['x-amz-bucket-region'];
const xmlString = await readAsString(response);
if (xmlString) {
throw parseError(xmlString, headerInfo);
}
// Message should be instantiated for each S3Errors.
const e = new errors.S3Error(message, {
cause: headerInfo
});
// S3 Error code.
e.code = code;
Object.entries(headerInfo).forEach(([key, value]) => {
// @ts-expect-error force set error properties
e[key] = value;
});
throw e;
}
/**
* parse XML response for list objects v2 with metadata in a bucket
*/
export function parseListObjectsV2WithMetadata(xml) {
const result = {
objects: [],
isTruncated: false,
nextContinuationToken: ''
};
let xmlobj = parseXml(xml);
if (!xmlobj.ListBucketResult) {
throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"');
}
xmlobj = xmlobj.ListBucketResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextContinuationToken) {
result.nextContinuationToken = xmlobj.NextContinuationToken;
}
if (xmlobj.Contents) {
toArray(xmlobj.Contents).forEach(content => {
const name = sanitizeObjectKey(content.Key);
const lastModified = new Date(content.LastModified);
const etag = sanitizeETag(content.ETag);
const size = content.Size;
let tags = {};
if (content.UserTags != null) {
toArray(content.UserTags.split('&')).forEach(tag => {
const [key, value] = tag.split('=');
tags[key] = value;
});
} else {
tags = {};
}
let metadata;
if (content.UserMetadata != null) {
metadata = toArray(content.UserMetadata)[0];
} else {
metadata = null;
}
result.objects.push({
name,
lastModified,
etag,
size,
metadata,
tags
});
});
}
if (xmlobj.CommonPrefixes) {
toArray(xmlobj.CommonPrefixes).forEach(commonPrefix => {
result.objects.push({
prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0]),
size: 0
});
});
}
return result;
}
// parse XML response for list parts of an in progress multipart upload
export function parseListParts(xml) {
let xmlobj = parseXml(xml);
const result = {
isTruncated: false,
parts: [],
marker: 0
};
if (!xmlobj.ListPartsResult) {
throw new errors.InvalidXMLError('Missing tag: "ListPartsResult"');
}
xmlobj = xmlobj.ListPartsResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextPartNumberMarker) {
result.marker = toArray(xmlobj.NextPartNumberMarker)[0] || '';
}
if (xmlobj.Part) {
toArray(xmlobj.Part).forEach(p => {
const part = parseInt(toArray(p.PartNumber)[0], 10);
const lastModified = new Date(p.LastModified);
const etag = p.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^&quot;/g, '').replace(/&quot;$/g, '').replace(/^&#34;/g, '').replace(/&#34;$/g, '');
result.parts.push({
part,
lastModified,
etag,
size: parseInt(p.Size, 10)
});
});
}
return result;
}
export function parseListBucket(xml) {
let result = [];
const listBucketResultParser = new XMLParser({
parseTagValue: true,
// Enable parsing of values
numberParseOptions: {
leadingZeros: false,
// Disable number parsing for values with leading zeros
hex: false,
// Disable hex number parsing - Invalid bucket name
skipLike: /^[0-9]+$/ // Skip number parsing if the value consists entirely of digits
},
tagValueProcessor: (tagName, tagValue = '') => {
// Ensure that the Name tag is always treated as a string
if (tagName === 'Name') {
return tagValue.toString();
}
return tagValue;
},
ignoreAttributes: false // Ensure that all attributes are parsed
});
const parsedXmlRes = listBucketResultParser.parse(xml);
if (!parsedXmlRes.ListAllMyBucketsResult) {
throw new errors.InvalidXMLError('Missing tag: "ListAllMyBucketsResult"');
}
const {
ListAllMyBucketsResult: {
Buckets = {}
} = {}
} = parsedXmlRes;
if (Buckets.Bucket) {
result = toArray(Buckets.Bucket).map((bucket = {}) => {
const {
Name: bucketName,
CreationDate
} = bucket;
const creationDate = new Date(CreationDate);
return {
name: bucketName,
creationDate
};
});
}
return result;
}
export function parseInitiateMultipart(xml) {
let xmlobj = parseXml(xml);
if (!xmlobj.InitiateMultipartUploadResult) {
throw new errors.InvalidXMLError('Missing tag: "InitiateMultipartUploadResult"');
}
xmlobj = xmlobj.InitiateMultipartUploadResult;
if (xmlobj.UploadId) {
return xmlobj.UploadId;
}
throw new errors.InvalidXMLError('Missing tag: "UploadId"');
}
export function parseReplicationConfig(xml) {
const xmlObj = parseXml(xml);
const {
Role,
Rule
} = xmlObj.ReplicationConfiguration;
return {
ReplicationConfiguration: {
role: Role,
rules: toArray(Rule)
}
};
}
export function parseObjectLegalHoldConfig(xml) {
const xmlObj = parseXml(xml);
return xmlObj.LegalHold;
}
export function parseTagging(xml) {
const xmlObj = parseXml(xml);
let result = [];
if (xmlObj.Tagging && xmlObj.Tagging.TagSet && xmlObj.Tagging.TagSet.Tag) {
const tagResult = xmlObj.Tagging.TagSet.Tag;
// if it is a single tag convert into an array so that the return value is always an array.
if (isObject(tagResult)) {
result.push(tagResult);
} else {
result = tagResult;
}
}
return result;
}
// parse XML response when a multipart upload is completed
export function parseCompleteMultipart(xml) {
const xmlobj = parseXml(xml).CompleteMultipartUploadResult;
if (xmlobj.Location) {
const location = toArray(xmlobj.Location)[0];
const bucket = toArray(xmlobj.Bucket)[0];
const key = xmlobj.Key;
const etag = xmlobj.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^&quot;/g, '').replace(/&quot;$/g, '').replace(/^&#34;/g, '').replace(/&#34;$/g, '');
return {
location,
bucket,
key,
etag
};
}
// Complete Multipart can return XML Error after a 200 OK response
if (xmlobj.Code && xmlobj.Message) {
const errCode = toArray(xmlobj.Code)[0];
const errMessage = toArray(xmlobj.Message)[0];
return {
errCode,
errMessage
};
}
}
// parse XML response for listing in-progress multipart uploads
export function parseListMultipart(xml) {
const result = {
prefixes: [],
uploads: [],
isTruncated: false,
nextKeyMarker: '',
nextUploadIdMarker: ''
};
let xmlobj = parseXml(xml);
if (!xmlobj.ListMultipartUploadsResult) {
throw new errors.InvalidXMLError('Missing tag: "ListMultipartUploadsResult"');
}
xmlobj = xmlobj.ListMultipartUploadsResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextKeyMarker) {
result.nextKeyMarker = xmlobj.NextKeyMarker;
}
if (xmlobj.NextUploadIdMarker) {
result.nextUploadIdMarker = xmlobj.nextUploadIdMarker || '';
}
if (xmlobj.CommonPrefixes) {
toArray(xmlobj.CommonPrefixes).forEach(prefix => {
// @ts-expect-error index check
result.prefixes.push({
prefix: sanitizeObjectKey(toArray(prefix.Prefix)[0])
});
});
}
if (xmlobj.Upload) {
toArray(xmlobj.Upload).forEach(upload => {
const uploadItem = {
key: upload.Key,
uploadId: upload.UploadId,
storageClass: upload.StorageClass,
initiated: new Date(upload.Initiated)
};
if (upload.Initiator) {
uploadItem.initiator = {
id: upload.Initiator.ID,
displayName: upload.Initiator.DisplayName
};
}
if (upload.Owner) {
uploadItem.owner = {
id: upload.Owner.ID,
displayName: upload.Owner.DisplayName
};
}
result.uploads.push(uploadItem);
});
}
return result;
}
export function parseObjectLockConfig(xml) {
const xmlObj = parseXml(xml);
let lockConfigResult = {};
if (xmlObj.ObjectLockConfiguration) {
lockConfigResult = {
objectLockEnabled: xmlObj.ObjectLockConfiguration.ObjectLockEnabled
};
let retentionResp;
if (xmlObj.ObjectLockConfiguration && xmlObj.ObjectLockConfiguration.Rule && xmlObj.ObjectLockConfiguration.Rule.DefaultRetention) {
retentionResp = xmlObj.ObjectLockConfiguration.Rule.DefaultRetention || {};
lockConfigResult.mode = retentionResp.Mode;
}
if (retentionResp) {
const isUnitYears = retentionResp.Years;
if (isUnitYears) {
lockConfigResult.validity = isUnitYears;
lockConfigResult.unit = RETENTION_VALIDITY_UNITS.YEARS;
} else {
lockConfigResult.validity = retentionResp.Days;
lockConfigResult.unit = RETENTION_VALIDITY_UNITS.DAYS;
}
}
}
return lockConfigResult;
}
export function parseBucketVersioningConfig(xml) {
const xmlObj = parseXml(xml);
return xmlObj.VersioningConfiguration;
}
// Used only in selectObjectContent API.
// extractHeaderType extracts the first half of the header message, the header type.
function extractHeaderType(stream) {
const headerNameLen = Buffer.from(stream.read(1)).readUInt8();
const headerNameWithSeparator = Buffer.from(stream.read(headerNameLen)).toString();
const splitBySeparator = (headerNameWithSeparator || '').split(':');
return splitBySeparator.length >= 1 ? splitBySeparator[1] : '';
}
function extractHeaderValue(stream) {
const bodyLen = Buffer.from(stream.read(2)).readUInt16BE();
return Buffer.from(stream.read(bodyLen)).toString();
}
export function parseSelectObjectContentResponse(res) {
const selectResults = new SelectResults({}); // will be returned
const responseStream = readableStream(res); // convert byte array to a readable responseStream
// @ts-ignore
while (responseStream._readableState.length) {
// Top level responseStream read tracker.
let msgCrcAccumulator; // accumulate from start of the message till the message crc start.
const totalByteLengthBuffer = Buffer.from(responseStream.read(4));
msgCrcAccumulator = crc32(totalByteLengthBuffer);
const headerBytesBuffer = Buffer.from(responseStream.read(4));
msgCrcAccumulator = crc32(headerBytesBuffer, msgCrcAccumulator);
const calculatedPreludeCrc = msgCrcAccumulator.readInt32BE(); // use it to check if any CRC mismatch in header itself.
const preludeCrcBuffer = Buffer.from(responseStream.read(4)); // read 4 bytes i.e 4+4 =8 + 4 = 12 ( prelude + prelude crc)
msgCrcAccumulator = crc32(preludeCrcBuffer, msgCrcAccumulator);
const totalMsgLength = totalByteLengthBuffer.readInt32BE();
const headerLength = headerBytesBuffer.readInt32BE();
const preludeCrcByteValue = preludeCrcBuffer.readInt32BE();
if (preludeCrcByteValue !== calculatedPreludeCrc) {
// Handle Header CRC mismatch Error
throw new Error(`Header Checksum Mismatch, Prelude CRC of ${preludeCrcByteValue} does not equal expected CRC of ${calculatedPreludeCrc}`);
}
const headers = {};
if (headerLength > 0) {
const headerBytes = Buffer.from(responseStream.read(headerLength));
msgCrcAccumulator = crc32(headerBytes, msgCrcAccumulator);
const headerReaderStream = readableStream(headerBytes);
// @ts-ignore
while (headerReaderStream._readableState.length) {
const headerTypeName = extractHeaderType(headerReaderStream);
headerReaderStream.read(1); // just read and ignore it.
if (headerTypeName) {
headers[headerTypeName] = extractHeaderValue(headerReaderStream);
}
}
}
let payloadStream;
const payLoadLength = totalMsgLength - headerLength - 16;
if (payLoadLength > 0) {
const payLoadBuffer = Buffer.from(responseStream.read(payLoadLength));
msgCrcAccumulator = crc32(payLoadBuffer, msgCrcAccumulator);
// read the checksum early and detect any mismatch so we can avoid unnecessary further processing.
const messageCrcByteValue = Buffer.from(responseStream.read(4)).readInt32BE();
const calculatedCrc = msgCrcAccumulator.readInt32BE();
// Handle message CRC Error
if (messageCrcByteValue !== calculatedCrc) {
throw new Error(`Message Checksum Mismatch, Message CRC of ${messageCrcByteValue} does not equal expected CRC of ${calculatedCrc}`);
}
payloadStream = readableStream(payLoadBuffer);
}
const messageType = headers['message-type'];
switch (messageType) {
case 'error':
{
const errorMessage = headers['error-code'] + ':"' + headers['error-message'] + '"';
throw new Error(errorMessage);
}
case 'event':
{
const contentType = headers['content-type'];
const eventType = headers['event-type'];
switch (eventType) {
case 'End':
{
selectResults.setResponse(res);
return selectResults;
}
case 'Records':
{
var _payloadStream;
const readData = (_payloadStream = payloadStream) === null || _payloadStream === void 0 ? void 0 : _payloadStream.read(payLoadLength);
selectResults.setRecords(readData);
break;
}
case 'Progress':
{
switch (contentType) {
case 'text/xml':
{
var _payloadStream2;
const progressData = (_payloadStream2 = payloadStream) === null || _payloadStream2 === void 0 ? void 0 : _payloadStream2.read(payLoadLength);
selectResults.setProgress(progressData.toString());
break;
}
default:
{
const errorMessage = `Unexpected content-type ${contentType} sent for event-type Progress`;
throw new Error(errorMessage);
}
}
}
break;
case 'Stats':
{
switch (contentType) {
case 'text/xml':
{
var _payloadStream3;
const statsData = (_payloadStream3 = payloadStream) === null || _payloadStream3 === void 0 ? void 0 : _payloadStream3.read(payLoadLength);
selectResults.setStats(statsData.toString());
break;
}
default:
{
const errorMessage = `Unexpected content-type ${contentType} sent for event-type Stats`;
throw new Error(errorMessage);
}
}
}
break;
default:
{
// Continuation message: Not sure if it is supported. did not find a reference or any message in response.
// It does not have a payload.
const warningMessage = `Un implemented event detected ${messageType}.`;
// eslint-disable-next-line no-console
console.warn(warningMessage);
}
}
}
}
}
}
export function parseLifecycleConfig(xml) {
const xmlObj = parseXml(xml);
return xmlObj.LifecycleConfiguration;
}
export function parseBucketEncryptionConfig(xml) {
return parseXml(xml);
}
export function parseObjectRetentionConfig(xml) {
const xmlObj = parseXml(xml);
const retentionConfig = xmlObj.Retention;
return {
mode: retentionConfig.Mode,
retainUntilDate: retentionConfig.RetainUntilDate
};
}
export function removeObjectsParser(xml) {
const xmlObj = parseXml(xml);
if (xmlObj.DeleteResult && xmlObj.DeleteResult.Error) {
// return errors as array always. as the response is object in case of single object passed in removeObjects
return toArray(xmlObj.DeleteResult.Error);
}
return [];
}
// parse XML response for copy object
export function parseCopyObject(xml) {
const result = {
etag: '',
lastModified: ''
};
let xmlobj = parseXml(xml);
if (!xmlobj.CopyObjectResult) {
throw new errors.InvalidXMLError('Missing tag: "CopyObjectResult"');
}
xmlobj = xmlobj.CopyObjectResult;
if (xmlobj.ETag) {
result.etag = xmlobj.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^&quot;/g, '').replace(/&quot;$/g, '').replace(/^&#34;/g, '').replace(/&#34;$/g, '');
}
if (xmlobj.LastModified) {
result.lastModified = new Date(xmlobj.LastModified);
}
return result;
}
const formatObjInfo = (content, opts = {}) => {
const {
Key,
LastModified,
ETag,
Size,
VersionId,
IsLatest
} = content;
if (!isObject(opts)) {
opts = {};
}
const name = sanitizeObjectKey(toArray(Key)[0] || '');
const lastModified = LastModified ? new Date(toArray(LastModified)[0] || '') : undefined;
const etag = sanitizeETag(toArray(ETag)[0] || '');
const size = sanitizeSize(Size || '');
return {
name,
lastModified,
etag,
size,
versionId: VersionId,
isLatest: IsLatest,
isDeleteMarker: opts.IsDeleteMarker ? opts.IsDeleteMarker : false
};
};
// parse XML response for list objects in a bucket
export function parseListObjects(xml) {
const result = {
objects: [],
isTruncated: false,
nextMarker: undefined,
versionIdMarker: undefined
};
let isTruncated = false;
let nextMarker, nextVersionKeyMarker;
const xmlobj = fxpWithoutNumParser.parse(xml);
const parseCommonPrefixesEntity = commonPrefixEntry => {
if (commonPrefixEntry) {
toArray(commonPrefixEntry).forEach(commonPrefix => {
result.objects.push({
prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0] || ''),
size: 0
});
});
}
};
const listBucketResult = xmlobj.ListBucketResult;
const listVersionsResult = xmlobj.ListVersionsResult;
if (listBucketResult) {
if (listBucketResult.IsTruncated) {
isTruncated = listBucketResult.IsTruncated;
}
if (listBucketResult.Contents) {
toArray(listBucketResult.Contents).forEach(content => {
const name = sanitizeObjectKey(toArray(content.Key)[0] || '');
const lastModified = new Date(toArray(content.LastModified)[0] || '');
const etag = sanitizeETag(toArray(content.ETag)[0] || '');
const size = sanitizeSize(content.Size || '');
result.objects.push({
name,
lastModified,
etag,
size
});
});
}
if (listBucketResult.Marker) {
nextMarker = listBucketResult.Marker;
} else if (isTruncated && result.objects.length > 0) {
var _result$objects;
nextMarker = (_result$objects = result.objects[result.objects.length - 1]) === null || _result$objects === void 0 ? void 0 : _result$objects.name;
}
if (listBucketResult.CommonPrefixes) {
parseCommonPrefixesEntity(listBucketResult.CommonPrefixes);
}
}
if (listVersionsResult) {
if (listVersionsResult.IsTruncated) {
isTruncated = listVersionsResult.IsTruncated;
}
if (listVersionsResult.Version) {
toArray(listVersionsResult.Version).forEach(content => {
result.objects.push(formatObjInfo(content));
});
}
if (listVersionsResult.DeleteMarker) {
toArray(listVersionsResult.DeleteMarker).forEach(content => {
result.objects.push(formatObjInfo(content, {
IsDeleteMarker: true
}));
});
}
if (listVersionsResult.NextKeyMarker) {
nextVersionKeyMarker = listVersionsResult.NextKeyMarker;
}
if (listVersionsResult.NextVersionIdMarker) {
result.versionIdMarker = listVersionsResult.NextVersionIdMarker;
}
if (listVersionsResult.CommonPrefixes) {
parseCommonPrefixesEntity(listVersionsResult.CommonPrefixes);
}
}
result.isTruncated = isTruncated;
if (isTruncated) {
result.nextMarker = nextVersionKeyMarker || nextMarker;
}
return result;
}
export function uploadPartParser(xml) {
const xmlObj = parseXml(xml);
const respEl = xmlObj.CopyPartResult;
return respEl;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJz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tldEVuY3J5cHRpb25Db25maWciLCJwYXJzZU9iamVjdFJldGVudGlvbkNvbmZpZyIsInJldGVudGlvbkNvbmZpZyIsIlJldGVudGlvbiIsInJldGFpblVudGlsRGF0ZSIsIlJldGFpblVudGlsRGF0ZSIsInJlbW92ZU9iamVjdHNQYXJzZXIiLCJEZWxldGVSZXN1bHQiLCJwYXJzZUNvcHlPYmplY3QiLCJDb3B5T2JqZWN0UmVzdWx0IiwiZm9ybWF0T2JqSW5mbyIsIm9wdHMiLCJWZXJzaW9uSWQiLCJJc0xhdGVzdCIsInVuZGVmaW5lZCIsInZlcnNpb25JZCIsImlzTGF0ZXN0IiwiaXNEZWxldGVNYXJrZXIiLCJJc0RlbGV0ZU1hcmtlciIsInBhcnNlTGlzdE9iamVjdHMiLCJuZXh0TWFya2VyIiwidmVyc2lvbklkTWFya2VyIiwibmV4dFZlcnNpb25LZXlNYXJrZXIiLCJwYXJzZUNvbW1vblByZWZpeGVzRW50aXR5IiwiY29tbW9uUHJlZml4RW50cnkiLCJsaXN0QnVja2V0UmVzdWx0IiwibGlzdFZlcnNpb25zUmVzdWx0IiwiTGlzdFZlcnNpb25zUmV Line truncated
+66
View File
@@ -0,0 +1,66 @@
// imported from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/93cfb0ec069731dcdfc31464788613f7cddb8192/types/minio/index.d.ts
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./helpers.mjs";
import type { ClientOptions, NoResultCallback, RemoveOptions } from "./internal/client.mjs";
import { TypedClient } from "./internal/client.mjs";
import { CopyConditions } from "./internal/copy-conditions.mjs";
import { PostPolicy } from "./internal/post-policy.mjs";
import type { BucketItem, BucketItemCopy, BucketItemFromList, BucketItemStat, BucketItemWithMetadata, BucketStream, EmptyObject, ExistingObjectReplication, GetObjectLegalHoldOptions, IncompleteUploadedBucketItem, InputSerialization, IsoDate, ItemBucketMetadata, ItemBucketMetadataList, LegalHoldStatus, LifecycleConfig, LifecycleRule, MetadataItem, ObjectLockInfo, OutputSerialization, PutObjectLegalHoldOptions, ReplicaModifications, ReplicationConfig, ReplicationConfigOpts, ReplicationRule, ReplicationRuleAnd, ReplicationRuleDestination, ReplicationRuleFilter, ReplicationRuleStatus, ResultCallback, Retention, RetentionOptions, ScanRange, SelectOptions, SelectProgress, SourceSelectionCriteria, Tag } from "./internal/type.mjs";
import type { NotificationConfig, NotificationEvent, NotificationPoller } from "./notification.mjs";
export * from "./errors.mjs";
export * from "./helpers.mjs";
export type { Region } from "./internal/s3-endpoints.mjs";
export type * from "./notification.mjs";
export * from "./notification.mjs";
export { CopyConditions, PostPolicy };
export type { MakeBucketOpt } from "./internal/client.mjs";
export type { BucketItem, BucketItemCopy, BucketItemFromList, BucketItemStat, BucketItemWithMetadata, BucketStream, ClientOptions, EmptyObject, ExistingObjectReplication, GetObjectLegalHoldOptions, IncompleteUploadedBucketItem, InputSerialization, IsoDate, ItemBucketMetadata, ItemBucketMetadataList, LegalHoldStatus, LifecycleConfig, LifecycleRule, MetadataItem, NoResultCallback, ObjectLockInfo, OutputSerialization, PutObjectLegalHoldOptions, RemoveOptions, ReplicaModifications, ReplicationConfig, ReplicationConfigOpts, ReplicationRule, ReplicationRuleAnd, ReplicationRuleDestination, ReplicationRuleFilter, ReplicationRuleStatus, Retention, RetentionOptions, ScanRange, SelectOptions, SelectProgress, SourceSelectionCriteria, Tag };
/**
* @deprecated keep for backward compatible, use `RETENTION_MODES` instead
*/
export type Mode = RETENTION_MODES;
/**
* @deprecated keep for backward compatible
*/
export type LockUnit = RETENTION_VALIDITY_UNITS;
export type VersioningConfig = Record<string | number | symbol, unknown>;
export type TagList = Record<string, string>;
export interface PostPolicyResult {
postURL: string;
formData: {
[key: string]: any;
};
}
export interface LockConfig {
mode: RETENTION_MODES;
unit: RETENTION_VALIDITY_UNITS;
validity: number;
}
export interface LegalHoldOptions {
versionId: string;
status: LEGAL_HOLD_STATUS;
}
export interface SourceObjectStats {
size: number;
metaData: string;
lastModicied: Date;
versionId: string;
etag: string;
}
// Exports from library
export class Client extends TypedClient {
listObjectsV2(bucketName: string, prefix?: string, recursive?: boolean, startAfter?: string): BucketStream<BucketItem>;
// Bucket Policy & Notification operations
getBucketNotification(bucketName: string, callback: ResultCallback<NotificationConfig>): void;
getBucketNotification(bucketName: string): Promise<NotificationConfig>;
setBucketNotification(bucketName: string, bucketNotificationConfig: NotificationConfig, callback: NoResultCallback): void;
setBucketNotification(bucketName: string, bucketNotificationConfig: NotificationConfig): Promise<void>;
removeAllBucketNotification(bucketName: string, callback: NoResultCallback): void;
removeAllBucketNotification(bucketName: string): Promise<void>;
listenBucketNotification(bucketName: string, prefix: string, suffix: string, events: NotificationEvent[]): NotificationPoller;
}
+308
View File
@@ -0,0 +1,308 @@
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as Stream from "stream";
import xml2js from 'xml2js';
import * as errors from "./errors.mjs";
import { callbackify } from "./internal/callbackify.mjs";
import { TypedClient } from "./internal/client.mjs";
import { CopyConditions } from "./internal/copy-conditions.mjs";
import { isBoolean, isFunction, isNumber, isObject, isString, isValidBucketName, isValidPrefix, pipesetup, uriEscape } from "./internal/helper.mjs";
import { PostPolicy } from "./internal/post-policy.mjs";
import { NotificationConfig, NotificationPoller } from "./notification.mjs";
import { promisify } from "./promisify.mjs";
import * as transformers from "./transformers.mjs";
export * from "./errors.mjs";
export * from "./helpers.mjs";
export * from "./notification.mjs";
export { CopyConditions, PostPolicy };
export class Client extends TypedClient {
//
// __Arguments__
// * `appName` _string_ - Application name.
// * `appVersion` _string_ - Application version.
// listObjectsV2Query - (List Objects V2) - List some or all (up to 1000) of the objects in a bucket.
//
// You can use the request parameters as selection criteria to return a subset of the objects in a bucket.
// request parameters :-
// * `bucketName` _string_: name of the bucket
// * `prefix` _string_: Limits the response to keys that begin with the specified prefix.
// * `continuation-token` _string_: Used to continue iterating over a set of objects.
// * `delimiter` _string_: A delimiter is a character you use to group keys.
// * `max-keys` _number_: Sets the maximum number of keys returned in the response body.
// * `start-after` _string_: Specifies the key to start after when listing objects in a bucket.
listObjectsV2Query(bucketName, prefix, continuationToken, delimiter, maxKeys, startAfter) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!isString(prefix)) {
throw new TypeError('prefix should be of type "string"');
}
if (!isString(continuationToken)) {
throw new TypeError('continuationToken should be of type "string"');
}
if (!isString(delimiter)) {
throw new TypeError('delimiter should be of type "string"');
}
if (!isNumber(maxKeys)) {
throw new TypeError('maxKeys should be of type "number"');
}
if (!isString(startAfter)) {
throw new TypeError('startAfter should be of type "string"');
}
var queries = [];
// Call for listing objects v2 API
queries.push(`list-type=2`);
queries.push(`encoding-type=url`);
// escape every value in query string, except maxKeys
queries.push(`prefix=${uriEscape(prefix)}`);
queries.push(`delimiter=${uriEscape(delimiter)}`);
if (continuationToken) {
continuationToken = uriEscape(continuationToken);
queries.push(`continuation-token=${continuationToken}`);
}
// Set start-after
if (startAfter) {
startAfter = uriEscape(startAfter);
queries.push(`start-after=${startAfter}`);
}
// no need to escape maxKeys
if (maxKeys) {
if (maxKeys >= 1000) {
maxKeys = 1000;
}
queries.push(`max-keys=${maxKeys}`);
}
queries.sort();
var query = '';
if (queries.length > 0) {
query = `${queries.join('&')}`;
}
var method = 'GET';
var transformer = transformers.getListObjectsV2Transformer();
this.makeRequest({
method,
bucketName,
query
}, '', [200], '', true, (e, response) => {
if (e) {
return transformer.emit('error', e);
}
pipesetup(response, transformer);
});
return transformer;
}
// List the objects in the bucket using S3 ListObjects V2
//
// __Arguments__
// * `bucketName` _string_: name of the bucket
// * `prefix` _string_: the prefix of the objects that should be listed (optional, default `''`)
// * `recursive` _bool_: `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`)
// * `startAfter` _string_: Specifies the key to start after when listing objects in a bucket. (optional, default `''`)
//
// __Return Value__
// * `stream` _Stream_: stream emitting the objects in the bucket, the object is of the format:
// * `obj.name` _string_: name of the object
// * `obj.prefix` _string_: name of the object prefix
// * `obj.size` _number_: size of the object
// * `obj.etag` _string_: etag of the object
// * `obj.lastModified` _Date_: modified time stamp
listObjectsV2(bucketName, prefix, recursive, startAfter) {
if (prefix === undefined) {
prefix = '';
}
if (recursive === undefined) {
recursive = false;
}
if (startAfter === undefined) {
startAfter = '';
}
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!isValidPrefix(prefix)) {
throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`);
}
if (!isString(prefix)) {
throw new TypeError('prefix should be of type "string"');
}
if (!isBoolean(recursive)) {
throw new TypeError('recursive should be of type "boolean"');
}
if (!isString(startAfter)) {
throw new TypeError('startAfter should be of type "string"');
}
// if recursive is false set delimiter to '/'
var delimiter = recursive ? '' : '/';
var continuationToken = '';
var objects = [];
var ended = false;
var readStream = Stream.Readable({
objectMode: true
});
readStream._read = () => {
// push one object per _read()
if (objects.length) {
readStream.push(objects.shift());
return;
}
if (ended) {
return readStream.push(null);
}
// if there are no objects to push do query for the next batch of objects
this.listObjectsV2Query(bucketName, prefix, continuationToken, delimiter, 1000, startAfter).on('error', e => readStream.emit('error', e)).on('data', result => {
if (result.isTruncated) {
continuationToken = result.nextContinuationToken;
} else {
ended = true;
}
objects = result.objects;
readStream._read();
});
};
return readStream;
}
// Remove all the notification configurations in the S3 provider
setBucketNotification(bucketName, config, cb) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!isObject(config)) {
throw new TypeError('notification config should be of type "Object"');
}
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"');
}
var method = 'PUT';
var query = 'notification';
var builder = new xml2js.Builder({
rootName: 'NotificationConfiguration',
renderOpts: {
pretty: false
},
headless: true
});
var payload = builder.buildObject(config);
this.makeRequest({
method,
bucketName,
query
}, payload, [200], '', false, cb);
}
removeAllBucketNotification(bucketName, cb) {
this.setBucketNotification(bucketName, new NotificationConfig(), cb);
}
// Return the list of notification configurations stored
// in the S3 provider
getBucketNotification(bucketName, cb) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!isFunction(cb)) {
throw new TypeError('callback should be of type "function"');
}
var method = 'GET';
var query = 'notification';
this.makeRequest({
method,
bucketName,
query
}, '', [200], '', true, (e, response) => {
if (e) {
return cb(e);
}
var transformer = transformers.getBucketNotificationTransformer();
var bucketNotification;
pipesetup(response, transformer).on('data', result => bucketNotification = result).on('error', e => cb(e)).on('end', () => cb(null, bucketNotification));
});
}
// Listens for bucket notifications. Returns an EventEmitter.
listenBucketNotification(bucketName, prefix, suffix, events) {
if (!isValidBucketName(bucketName)) {
throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`);
}
if (!isString(prefix)) {
throw new TypeError('prefix must be of type string');
}
if (!isString(suffix)) {
throw new TypeError('suffix must be of type string');
}
if (!Array.isArray(events)) {
throw new TypeError('events must be of type Array');
}
let listener = new NotificationPoller(this, bucketName, prefix, suffix, events);
listener.start();
return listener;
}
}
Client.prototype.getBucketNotification = promisify(Client.prototype.getBucketNotification);
Client.prototype.setBucketNotification = promisify(Client.prototype.setBucketNotification);
Client.prototype.removeAllBucketNotification = promisify(Client.prototype.removeAllBucketNotification);
// refactored API use promise internally
Client.prototype.makeBucket = callbackify(Client.prototype.makeBucket);
Client.prototype.bucketExists = callbackify(Client.prototype.bucketExists);
Client.prototype.removeBucket = callbackify(Client.prototype.removeBucket);
Client.prototype.listBuckets = callbackify(Client.prototype.listBuckets);
Client.prototype.getObject = callbackify(Client.prototype.getObject);
Client.prototype.fGetObject = callbackify(Client.prototype.fGetObject);
Client.prototype.getPartialObject = callbackify(Client.prototype.getPartialObject);
Client.prototype.statObject = callbackify(Client.prototype.statObject);
Client.prototype.putObjectRetention = callbackify(Client.prototype.putObjectRetention);
Client.prototype.putObject = callbackify(Client.prototype.putObject);
Client.prototype.fPutObject = callbackify(Client.prototype.fPutObject);
Client.prototype.removeObject = callbackify(Client.prototype.removeObject);
Client.prototype.removeBucketReplication = callbackify(Client.prototype.removeBucketReplication);
Client.prototype.setBucketReplication = callbackify(Client.prototype.setBucketReplication);
Client.prototype.getBucketReplication = callbackify(Client.prototype.getBucketReplication);
Client.prototype.getObjectLegalHold = callbackify(Client.prototype.getObjectLegalHold);
Client.prototype.setObjectLegalHold = callbackify(Client.prototype.setObjectLegalHold);
Client.prototype.setObjectLockConfig = callbackify(Client.prototype.setObjectLockConfig);
Client.prototype.getObjectLockConfig = callbackify(Client.prototype.getObjectLockConfig);
Client.prototype.getBucketPolicy = callbackify(Client.prototype.getBucketPolicy);
Client.prototype.setBucketPolicy = callbackify(Client.prototype.setBucketPolicy);
Client.prototype.getBucketTagging = callbackify(Client.prototype.getBucketTagging);
Client.prototype.getObjectTagging = callbackify(Client.prototype.getObjectTagging);
Client.prototype.setBucketTagging = callbackify(Client.prototype.setBucketTagging);
Client.prototype.removeBucketTagging = callbackify(Client.prototype.removeBucketTagging);
Client.prototype.setObjectTagging = callbackify(Client.prototype.setObjectTagging);
Client.prototype.removeObjectTagging = callbackify(Client.prototype.removeObjectTagging);
Client.prototype.getBucketVersioning = callbackify(Client.prototype.getBucketVersioning);
Client.prototype.setBucketVersioning = callbackify(Client.prototype.setBucketVersioning);
Client.prototype.selectObjectContent = callbackify(Client.prototype.selectObjectContent);
Client.prototype.setBucketLifecycle = callbackify(Client.prototype.setBucketLifecycle);
Client.prototype.getBucketLifecycle = callbackify(Client.prototype.getBucketLifecycle);
Client.prototype.removeBucketLifecycle = callbackify(Client.prototype.removeBucketLifecycle);
Client.prototype.setBucketEncryption = callbackify(Client.prototype.setBucketEncryption);
Client.prototype.getBucketEncryption = callbackify(Client.prototype.getBucketEncryption);
Client.prototype.removeBucketEncryption = callbackify(Client.prototype.removeBucketEncryption);
Client.prototype.getObjectRetention = callbackify(Client.prototype.getObjectRetention);
Client.prototype.removeObjects = callbackify(Client.prototype.removeObjects);
Client.prototype.removeIncompleteUpload = callbackify(Client.prototype.removeIncompleteUpload);
Client.prototype.copyObject = callbackify(Client.prototype.copyObject);
Client.prototype.composeObject = callbackify(Client.prototype.composeObject);
Client.prototype.presignedUrl = callbackify(Client.prototype.presignedUrl);
Client.prototype.presignedGetObject = callbackify(Client.prototype.presignedGetObject);
Client.prototype.presignedPutObject = callbackify(Client.prototype.presignedPutObject);
Client.prototype.presignedPostPolicy = callbackify(Client.prototype.presignedPostPolicy);
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJTdHJlYW0iLCJ4bWwyanMiLCJlcnJvcnMiLCJjYWxsYmFja2lmeSIsIlR5cGVkQ2xpZW50IiwiQ29weUNvbmRpdGlvbnMiLCJpc0Jvb2xlYW4iLCJpc0Z1bmN0aW9uIiwiaXNOdW1iZXIiLCJpc09iamVjdCIsImlzU3RyaW5nIiwiaXNWYWxpZEJ1Y2tldE5hbWUiLCJpc1ZhbGlkUHJlZml4IiwicGlwZXNldHVwIiwidXJpRXNjYXBlIiwiUG9zdFBvbGljeSIsIk5vdGlmaWNhdGlvbkNvbmZpZyIsIk5vdGlmaWNhdGlvblBvbGxlciIsInByb21pc2lmeSIsInRyYW5zZm9ybWVycyIsIkNsaWVudCIsImxpc3RPYmplY3RzVjJRdWVyeSIsImJ1Y2tldE5hbWUiLCJwcmVmaXgiLCJjb250aW51YXRpb25Ub2tlbiIsImRlbGltaXRlciIsIm1heEtleX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F9zdHJpbmdfIC0gQXBwbGljYXRpb24gdmVyc2lvbi5cblxuICAvLyBsaXN0T2JqZWN0c1YyUXVlcnkgLSAoTGlzdCBPYmplY3R Line truncated
+58
View File
@@ -0,0 +1,58 @@
import { EventEmitter } from 'eventemitter3';
import type { TypedClient } from "./internal/client.mjs";
type Event = unknown;
export declare class TargetConfig {
private Filter?;
private Event?;
private Id;
setId(id: unknown): void;
addEvent(newevent: Event): void;
addFilterSuffix(suffix: string): void;
addFilterPrefix(prefix: string): void;
}
export declare class TopicConfig extends TargetConfig {
private Topic;
constructor(arn: string);
}
export declare class QueueConfig extends TargetConfig {
private Queue;
constructor(arn: string);
}
export declare class CloudFunctionConfig extends TargetConfig {
private CloudFunction;
constructor(arn: string);
}
export declare class NotificationConfig {
private TopicConfiguration?;
private CloudFunctionConfiguration?;
private QueueConfiguration?;
add(target: TargetConfig): void;
}
export declare const buildARN: (partition: string, service: string, region: string, accountId: string, resource: string) => string;
export declare const ObjectCreatedAll = "s3:ObjectCreated:*";
export declare const ObjectCreatedPut = "s3:ObjectCreated:Put";
export declare const ObjectCreatedPost = "s3:ObjectCreated:Post";
export declare const ObjectCreatedCopy = "s3:ObjectCreated:Copy";
export declare const ObjectCreatedCompleteMultipartUpload = "s3:ObjectCreated:CompleteMultipartUpload";
export declare const ObjectRemovedAll = "s3:ObjectRemoved:*";
export declare const ObjectRemovedDelete = "s3:ObjectRemoved:Delete";
export declare const ObjectRemovedDeleteMarkerCreated = "s3:ObjectRemoved:DeleteMarkerCreated";
export declare const ObjectReducedRedundancyLostObject = "s3:ReducedRedundancyLostObject";
export type NotificationEvent = 's3:ObjectCreated:*' | 's3:ObjectCreated:Put' | 's3:ObjectCreated:Post' | 's3:ObjectCreated:Copy' | 's3:ObjectCreated:CompleteMultipartUpload' | 's3:ObjectRemoved:*' | 's3:ObjectRemoved:Delete' | 's3:ObjectRemoved:DeleteMarkerCreated' | 's3:ReducedRedundancyLostObject' | 's3:TestEvent' | 's3:ObjectRestore:Post' | 's3:ObjectRestore:Completed' | 's3:Replication:OperationFailedReplication' | 's3:Replication:OperationMissedThreshold' | 's3:Replication:OperationReplicatedAfterThreshold' | 's3:Replication:OperationNotTracked' | string;
export type NotificationRecord = unknown;
export declare class NotificationPoller extends EventEmitter<{
notification: (event: NotificationRecord) => void;
error: (error: unknown) => void;
}> {
private client;
private bucketName;
private prefix;
private suffix;
private events;
private ending;
constructor(client: TypedClient, bucketName: string, prefix: string, suffix: string, events: NotificationEvent[]);
start(): void;
stop(): void;
checkForChanges(): void;
}
export {};
+209
View File
@@ -0,0 +1,209 @@
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { EventEmitter } from 'eventemitter3';
import jsonLineParser from 'stream-json/jsonl/Parser.js';
import { DEFAULT_REGION } from "./helpers.mjs";
import { pipesetup, uriEscape } from "./internal/helper.mjs";
// TODO: type this
// Base class for three supported configs.
export class TargetConfig {
setId(id) {
this.Id = id;
}
addEvent(newevent) {
if (!this.Event) {
this.Event = [];
}
this.Event.push(newevent);
}
addFilterSuffix(suffix) {
if (!this.Filter) {
this.Filter = {
S3Key: {
FilterRule: []
}
};
}
this.Filter.S3Key.FilterRule.push({
Name: 'suffix',
Value: suffix
});
}
addFilterPrefix(prefix) {
if (!this.Filter) {
this.Filter = {
S3Key: {
FilterRule: []
}
};
}
this.Filter.S3Key.FilterRule.push({
Name: 'prefix',
Value: prefix
});
}
}
// 1. Topic (simple notification service)
export class TopicConfig extends TargetConfig {
constructor(arn) {
super();
this.Topic = arn;
}
}
// 2. Queue (simple queue service)
export class QueueConfig extends TargetConfig {
constructor(arn) {
super();
this.Queue = arn;
}
}
// 3. CloudFront (lambda function)
export class CloudFunctionConfig extends TargetConfig {
constructor(arn) {
super();
this.CloudFunction = arn;
}
}
// Notification config - array of target configs.
// Target configs can be
// 1. Topic (simple notification service)
// 2. Queue (simple queue service)
// 3. CloudFront (lambda function)
export class NotificationConfig {
add(target) {
let instance;
if (target instanceof TopicConfig) {
instance = this.TopicConfiguration ?? (this.TopicConfiguration = []);
}
if (target instanceof QueueConfig) {
instance = this.QueueConfiguration ?? (this.QueueConfiguration = []);
}
if (target instanceof CloudFunctionConfig) {
instance = this.CloudFunctionConfiguration ?? (this.CloudFunctionConfiguration = []);
}
if (instance) {
instance.push(target);
}
}
}
export const buildARN = (partition, service, region, accountId, resource) => {
return 'arn:' + partition + ':' + service + ':' + region + ':' + accountId + ':' + resource;
};
export const ObjectCreatedAll = 's3:ObjectCreated:*';
export const ObjectCreatedPut = 's3:ObjectCreated:Put';
export const ObjectCreatedPost = 's3:ObjectCreated:Post';
export const ObjectCreatedCopy = 's3:ObjectCreated:Copy';
export const ObjectCreatedCompleteMultipartUpload = 's3:ObjectCreated:CompleteMultipartUpload';
export const ObjectRemovedAll = 's3:ObjectRemoved:*';
export const ObjectRemovedDelete = 's3:ObjectRemoved:Delete';
export const ObjectRemovedDeleteMarkerCreated = 's3:ObjectRemoved:DeleteMarkerCreated';
export const ObjectReducedRedundancyLostObject = 's3:ReducedRedundancyLostObject';
// put string at least so auto-complete could work
// TODO: type this
// Poll for notifications, used in #listenBucketNotification.
// Listening constitutes repeatedly requesting s3 whether or not any
// changes have occurred.
export class NotificationPoller extends EventEmitter {
constructor(client, bucketName, prefix, suffix, events) {
super();
this.client = client;
this.bucketName = bucketName;
this.prefix = prefix;
this.suffix = suffix;
this.events = events;
this.ending = false;
}
// Starts the polling.
start() {
this.ending = false;
process.nextTick(() => {
this.checkForChanges();
});
}
// Stops the polling.
stop() {
this.ending = true;
}
checkForChanges() {
// Don't continue if we're looping again but are cancelled.
if (this.ending) {
return;
}
const method = 'GET';
const queries = [];
if (this.prefix) {
const prefix = uriEscape(this.prefix);
queries.push(`prefix=${prefix}`);
}
if (this.suffix) {
const suffix = uriEscape(this.suffix);
queries.push(`suffix=${suffix}`);
}
if (this.events) {
this.events.forEach(s3event => queries.push('events=' + uriEscape(s3event)));
}
queries.sort();
let query = '';
if (queries.length > 0) {
query = `${queries.join('&')}`;
}
const region = this.client.region || DEFAULT_REGION;
this.client.makeRequestAsync({
method,
bucketName: this.bucketName,
query
}, '', [200], region).then(response => {
const asm = jsonLineParser.make();
pipesetup(response, asm).on('data', data => {
// Data is flushed periodically (every 5 seconds), so we should
// handle it after flushing from the JSON parser.
let records = data.value.Records;
// If null (= no records), change to an empty array.
if (!records) {
records = [];
}
// Iterate over the notifications and emit them individually.
records.forEach(record => {
this.emit('notification', record);
});
// If we're done, stop.
if (this.ending) {
response === null || response === void 0 ? void 0 : response.destroy();
}
}).on('error', e => this.emit('error', e)).on('end', () => {
// Do it again, if we haven't cancelled yet.
process.nextTick(() => {
this.checkForChanges();
});
});
}, e => {
return this.emit('error', e);
});
}
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFdmVudEVtaXR0ZXIiLCJqc29uTGluZVBhcnNlciIsIkRFRkFVTFRfUkVHSU9OIiwicGlwZXNldHVwIiwidXJpRXNjYXBlIiwiVGFyZ2V0Q29uZmlnIiwic2V0SWQiLCJpZCIsIklkIiwiYWRkRXZlbnQiLCJuZXdldmVudCIsIkV2ZW50IiwicHVzaCIsImFkZEZpbHRlclN1ZmZpeCIsInN1ZmZpeCIsIkZpbHRlciIsIlMzS2V5IiwiRmlsdGVyUnVsZSIsIk5hbWUiLCJWYWx1ZSIsImFkZEZpbHRlclByZWZpeCIsInByZWZpeCIsIlRvcGljQ29uZmlnIiwiY29uc3RydWN0b3IiLCJhcm4iLCJUb3BpYyIsIlF1ZXVlQ29uZmlnIiwiUXVld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YXJnZXQgY29uZmlncy5cbi8vIFRhcmdldCBjb25maWdzIGNhbiBiZVxuLy8gMS4gVG9waWMgKHNpbXBsZSBub3RpZmljYXRpb24gc2VydmljZSlcbi8vIDIuIFF1ZXVlIChzaW1wbGUgcXVldWUgc2VydmljZSlcbi8vIDMuIENsb3VkRnJvbnQgKGxhbWJkYSBmdW5jdGlvbilcbmV4cG9ydCB Line truncated
+30
View File
@@ -0,0 +1,30 @@
// Returns a wrapper function that will promisify a given callback function.
// It will preserve 'this'.
export function promisify(fn) {
return function () {
// If the last argument is a function, assume its the callback.
let callback = arguments[arguments.length - 1];
// If the callback is given, don't promisify, just pass straight in.
if (typeof callback === 'function') {
return fn.apply(this, arguments);
}
// Otherwise, create a new set of arguments, and wrap
// it in a promise.
let args = [...arguments];
return new Promise((resolve, reject) => {
// Add the callback function.
args.push((err, value) => {
if (err) {
return reject(err);
}
resolve(value);
});
// Call the function with our special adaptor callback added.
fn.apply(this, args);
});
};
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJwcm9taXNpZnkiLCJmbiIsImNhbGxiYWNrIiwiYXJndW1lbnRzIiwibGVuZ3RoIiwiYXBwbHkiLCJhcmdzIiwiUHJvbWlzZSIsInJlc29sdmUiLCJyZWplY3QiLCJwdXNoIiwiZXJyIiwidmFsdWUiXSwic291cmNlcyI6WyJwcm9taXNpZnkuanMiXSwic291cmNlc0NvbnRlbnQiOlsiLy8gUmV0dXJucyBhIHdyYXBwZXIgZnVuY3Rpb24gdGhhdCB3aWxsIHByb21pc2lmeSBhIGdpdmVuIGNhbGxiYWNrIGZ1bmN0aW9uLlxuLy8gSXQgd2lsbCBwcmVzZXJ2ZSAndGhpcycuXG5leHBvcnQgZnVuY3Rpb24gcHJvbWlzaWZ5KGZuKSB7XG4gIHJldHVybiBmdW5jdGlvbiAoKSB7XG4gICAgLy8gSWYgdGhlIGxhc3QgYXJndW1lbnQgaXMgYSBmdW5jdG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xTQUFTLENBQUNDLE1BQU0sR0FBRyxDQUFDLENBQUM7O0lBRTlDO0lBQ0EsSUFBSSxPQUFPRixRQUFRLEtBQUssVUFBVSxFQUFFO01BQ2xDLE9BQU9ELEVBQUUsQ0FBQ0ksS0FBSyxDQUFDLElBQUksRUFBRUYsU0FBUyxDQUFDO0lBQ2xDOztJQUVBO0lBQ0E7SUFDQSxJQUFJRyxJQUFJLEdBQUcsQ0FBQyxHQUFHSCxTQUFTLENBQUM7SUFFekIsT0FBTyxJQUFJSSxPQUFPLENBQUMsQ0FBQ0MsT0FBTyxFQUFFQyxNQUFNLEtBQUs7TUFDdEM7TUFDQUgsSUFBSSxDQUFDSSxJQUFJLENBQUMsQ0FBQ0MsR0FBRyxFQUFFQyxLQUFLLEtBQUs7UUFDeEIsSUFBSUQsR0FBRyxFQUFFO1VBQ1AsT0FBT0YsTUFBTSxDQUFDRSxHQUFHLENBQUM7UUFDcEI7UUFFQUgsT0FBTyxDQUFDSSxLQUFLLENBQUM7TUFDaEIsQ0FBQyxDQUFDOztNQUVGO01BQ0FYLEVBQUUsQ0FBQ0ksS0FBSyxDQUFDLElBQUksRUFBRUMsSUFBSSxDQUFDO0lBQ3RCLENBQUMsQ0FBQztFQUNKLENBQUM7QUFDSCJ9
+5
View File
@@ -0,0 +1,5 @@
import type { IRequest } from "./internal/type.mjs";
export declare function postPresignSignatureV4(region: string, date: Date, secretKey: string, policyBase64: string): string;
export declare function signV4(request: IRequest, accessKey: string, secretKey: string, region: string, requestDate: Date, sha256sum: string, serviceName?: string): string;
export declare function signV4ByServiceName(request: IRequest, accessKey: string, secretKey: string, region: string, requestDate: Date, contentSha256: string, serviceName?: string): string;
export declare function presignSignatureV4(request: IRequest, accessKey: string, secretKey: string, sessionToken: string | undefined, region: string, requestDate: Date, expires: number | undefined): string;
+258
View File
@@ -0,0 +1,258 @@
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as crypto from "crypto";
import * as errors from "./errors.mjs";
import { PRESIGN_EXPIRY_DAYS_MAX } from "./helpers.mjs";
import { getScope, isNumber, isObject, isString, makeDateLong, makeDateShort, uriEscape } from "./internal/helper.mjs";
const signV4Algorithm = 'AWS4-HMAC-SHA256';
// getCanonicalRequest generate a canonical request of style.
//
// canonicalRequest =
// <HTTPMethod>\n
// <CanonicalURI>\n
// <CanonicalQueryString>\n
// <CanonicalHeaders>\n
// <SignedHeaders>\n
// <HashedPayload>
//
function getCanonicalRequest(method, path, headers, signedHeaders, hashedPayload) {
if (!isString(method)) {
throw new TypeError('method should be of type "string"');
}
if (!isString(path)) {
throw new TypeError('path should be of type "string"');
}
if (!isObject(headers)) {
throw new TypeError('headers should be of type "object"');
}
if (!Array.isArray(signedHeaders)) {
throw new TypeError('signedHeaders should be of type "array"');
}
if (!isString(hashedPayload)) {
throw new TypeError('hashedPayload should be of type "string"');
}
const headersArray = signedHeaders.reduce((acc, i) => {
// Trim spaces from the value (required by V4 spec)
const val = `${headers[i]}`.replace(/ +/g, ' ');
acc.push(`${i.toLowerCase()}:${val}`);
return acc;
}, []);
const requestResource = path.split('?')[0];
let requestQuery = path.split('?')[1];
if (!requestQuery) {
requestQuery = '';
}
if (requestQuery) {
requestQuery = requestQuery.split('&').sort().map(element => !element.includes('=') ? element + '=' : element).join('&');
}
return [method.toUpperCase(), requestResource, requestQuery, headersArray.join('\n') + '\n', signedHeaders.join(';').toLowerCase(), hashedPayload].join('\n');
}
// generate a credential string
function getCredential(accessKey, region, requestDate, serviceName = 's3') {
if (!isString(accessKey)) {
throw new TypeError('accessKey should be of type "string"');
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"');
}
if (!isObject(requestDate)) {
throw new TypeError('requestDate should be of type "object"');
}
return `${accessKey}/${getScope(region, requestDate, serviceName)}`;
}
// Returns signed headers array - alphabetically sorted
function getSignedHeaders(headers) {
if (!isObject(headers)) {
throw new TypeError('request should be of type "object"');
}
// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258
//
// User-Agent:
//
// This is ignored from signing because signing this causes problems with generating pre-signed URLs
// (that are executed by other agents) or when customers pass requests through proxies, which may
// modify the user-agent.
//
// Content-Length:
//
// This is ignored from signing because generating a pre-signed URL should not provide a content-length
// constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when
// sending regular requests (non-pre-signed), the signature contains a checksum of the body, which
// implicitly validates the payload length (since changing the number of bytes would change the checksum)
// and therefore this header is not valuable in the signature.
//
// Content-Type:
//
// Signing this header causes quite a number of problems in browser environments, where browsers
// like to modify and normalize the content-type header in different ways. There is more information
// on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic
// and reduces the possibility of future bugs
//
// Authorization:
//
// Is skipped for obvious reasons
const ignoredHeaders = ['authorization', 'content-length', 'content-type', 'user-agent'];
return Object.keys(headers).filter(header => !ignoredHeaders.includes(header)).sort();
}
// returns the key used for calculating signature
function getSigningKey(date, region, secretKey, serviceName = 's3') {
if (!isObject(date)) {
throw new TypeError('date should be of type "object"');
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"');
}
if (!isString(secretKey)) {
throw new TypeError('secretKey should be of type "string"');
}
const dateLine = makeDateShort(date);
const hmac1 = crypto.createHmac('sha256', 'AWS4' + secretKey).update(dateLine).digest(),
hmac2 = crypto.createHmac('sha256', hmac1).update(region).digest(),
hmac3 = crypto.createHmac('sha256', hmac2).update(serviceName).digest();
return crypto.createHmac('sha256', hmac3).update('aws4_request').digest();
}
// returns the string that needs to be signed
function getStringToSign(canonicalRequest, requestDate, region, serviceName = 's3') {
if (!isString(canonicalRequest)) {
throw new TypeError('canonicalRequest should be of type "string"');
}
if (!isObject(requestDate)) {
throw new TypeError('requestDate should be of type "object"');
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"');
}
const hash = crypto.createHash('sha256').update(canonicalRequest).digest('hex');
const scope = getScope(region, requestDate, serviceName);
const stringToSign = [signV4Algorithm, makeDateLong(requestDate), scope, hash];
return stringToSign.join('\n');
}
// calculate the signature of the POST policy
export function postPresignSignatureV4(region, date, secretKey, policyBase64) {
if (!isString(region)) {
throw new TypeError('region should be of type "string"');
}
if (!isObject(date)) {
throw new TypeError('date should be of type "object"');
}
if (!isString(secretKey)) {
throw new TypeError('secretKey should be of type "string"');
}
if (!isString(policyBase64)) {
throw new TypeError('policyBase64 should be of type "string"');
}
const signingKey = getSigningKey(date, region, secretKey);
return crypto.createHmac('sha256', signingKey).update(policyBase64).digest('hex').toLowerCase();
}
// Returns the authorization header
export function signV4(request, accessKey, secretKey, region, requestDate, sha256sum, serviceName = 's3') {
if (!isObject(request)) {
throw new TypeError('request should be of type "object"');
}
if (!isString(accessKey)) {
throw new TypeError('accessKey should be of type "string"');
}
if (!isString(secretKey)) {
throw new TypeError('secretKey should be of type "string"');
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"');
}
if (!accessKey) {
throw new errors.AccessKeyRequiredError('accessKey is required for signing');
}
if (!secretKey) {
throw new errors.SecretKeyRequiredError('secretKey is required for signing');
}
const signedHeaders = getSignedHeaders(request.headers);
const canonicalRequest = getCanonicalRequest(request.method, request.path, request.headers, signedHeaders, sha256sum);
const serviceIdentifier = serviceName || 's3';
const stringToSign = getStringToSign(canonicalRequest, requestDate, region, serviceIdentifier);
const signingKey = getSigningKey(requestDate, region, secretKey, serviceIdentifier);
const credential = getCredential(accessKey, region, requestDate, serviceIdentifier);
const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase();
return `${signV4Algorithm} Credential=${credential}, SignedHeaders=${signedHeaders.join(';').toLowerCase()}, Signature=${signature}`;
}
export function signV4ByServiceName(request, accessKey, secretKey, region, requestDate, contentSha256, serviceName = 's3') {
return signV4(request, accessKey, secretKey, region, requestDate, contentSha256, serviceName);
}
// returns a presigned URL string
export function presignSignatureV4(request, accessKey, secretKey, sessionToken, region, requestDate, expires) {
if (!isObject(request)) {
throw new TypeError('request should be of type "object"');
}
if (!isString(accessKey)) {
throw new TypeError('accessKey should be of type "string"');
}
if (!isString(secretKey)) {
throw new TypeError('secretKey should be of type "string"');
}
if (!isString(region)) {
throw new TypeError('region should be of type "string"');
}
if (!accessKey) {
throw new errors.AccessKeyRequiredError('accessKey is required for presigning');
}
if (!secretKey) {
throw new errors.SecretKeyRequiredError('secretKey is required for presigning');
}
if (expires && !isNumber(expires)) {
throw new TypeError('expires should be of type "number"');
}
if (expires && expires < 1) {
throw new errors.ExpiresParamError('expires param cannot be less than 1 seconds');
}
if (expires && expires > PRESIGN_EXPIRY_DAYS_MAX) {
throw new errors.ExpiresParamError('expires param cannot be greater than 7 days');
}
const iso8601Date = makeDateLong(requestDate);
const signedHeaders = getSignedHeaders(request.headers);
const credential = getCredential(accessKey, region, requestDate);
const hashedPayload = 'UNSIGNED-PAYLOAD';
const requestQuery = [];
requestQuery.push(`X-Amz-Algorithm=${signV4Algorithm}`);
requestQuery.push(`X-Amz-Credential=${uriEscape(credential)}`);
requestQuery.push(`X-Amz-Date=${iso8601Date}`);
requestQuery.push(`X-Amz-Expires=${expires}`);
requestQuery.push(`X-Amz-SignedHeaders=${uriEscape(signedHeaders.join(';').toLowerCase())}`);
if (sessionToken) {
requestQuery.push(`X-Amz-Security-Token=${uriEscape(sessionToken)}`);
}
const resource = request.path.split('?')[0];
let query = request.path.split('?')[1];
if (query) {
query = query + '&' + requestQuery.join('&');
} else {
query = requestQuery.join('&');
}
const path = resource + '?' + query;
const canonicalRequest = getCanonicalRequest(request.method, path, request.headers, signedHeaders, hashedPayload);
const stringToSign = getStringToSign(canonicalRequest, requestDate, region);
const signingKey = getSigningKey(requestDate, region, secretKey);
const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase();
return request.protocol + '//' + request.headers.host + path + `&X-Amz-Signature=${signature}`;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJlcnJvcnMiLCJQUkVTSUdOX0VYUElSWV9EQVlTX01BWCIsImdldFNjb3BlIiwiaXNOdW1iZXIiLCJpc09iamVjdCIsImlzU3RyaW5nIiwibWFrZURhdGVMb25nIiwibWFrZURhdGVTaG9ydCIsInVyaUVzY2FwZSIsInNpZ25WNEFsZ29yaXRobSIsImdldENhbm9uaWNhbFJlcXVlc3QiLCJtZXRob2QiLCJwYXRoIiwiaGVhZGVycyIsInNpZ25lZEhlYWRlcnMiLCJoYXNoZWRQYXlsb2FkIiwiVHlwZUVycm9yIiwiQXJyYXkiLCJpc0FycmF5IiwiaGVhZGVyc0FycmF5IiwicmVkdWNlIiwiYWNjIiwiaSIsInZhbCIsInJlcGxhY2UiLCJwdXNoIiwidG9Mb3dlckNhc2UiLCJyZXF1ZXN0UmVzb3VyY2UiLCJzcGxpdCIsInJlcXVlc3RRdWVyeSIsInNvcnQiLCJtYXAiLCJlbGVtZW50IiwiaW5jbHVkZXMiLCJqb2luIiwidG9VcHBlckNhc2UiLCJnZXRDcmVkZW50aWFsIiwiYWNjZXNzS2V5IiwicmVnaW9uIiwicmVxdWVzdERhdGUiLCJzZXJ2aWNlTmFtZSIsImdldFNpZ25lZEhlYWRlcnMiLCJpZ25vcmVkSGVhZGVycyIsIk9iamVjdCIsImtleXMiLCJmaWx0ZXIiLCJoZWFkZXIiLCJnZXRTaWduaW5nS2V5IiwiZGF0ZSIsInNlY3JldEtleSIsImRhdGVMaW5lIiwiaG1hYzEiLCJjcmVhdGVIbWFjIiwidXBkYXRlIiwiZGlnZXN0IiwiaG1hYzIiLCJobWFjMyIsImdldFN0cmluZ1RvU2lnbiIsImNhbm9uaWNhbFJlcX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nXCInKVxuICB9XG5cbiAgY29uc3QgaGVhZGVyc0FycmF5ID0gc2lnbmVkSGVhZGVycy5yZWR1Y2UoKGFjYywgaSkgPT4ge1xuICAgIC8vIFRyaW0gc3BhY2VzIGZyb20gdGhlIHZhbHVlIChyZXF1aXJlZCBieSBWNCBzcGVjKVxuICAgIGNvbnN0IHZhbCA9IGAke2hlYWRlcnNbaV19YC5yZXBsYWNlKC8gKy9nLCAnICcpXG4gICAgYWNjLnB1c2goYCR7aS50b0xvd2VyQ2FzZSgpfToke3ZhbH1gKVxuICAgIHJldHVybiBhY2NcbiAgfSwgW10gYXMgc3RyaW5nW10pXG5cbiAgY29uc3QgcmVxdWVzdFJlc291cmNlID0gcGF0aC5zcGxpdCgnPycpWzBdXG4gIGxldCByZXF1ZXN0UXVlcnkgPSBwYXRoLnNwbGl0KCc/JylbMV1cbiAgaWYgKCFyZXF1ZXN0UXVlcnkpIHtcbiAgICByZXF1ZXN0UXVlcnkgPSAnJ1xuICB9XG5cbiAgaWYgKHJlcXVlc3RRdWVyeSkge1xuICAgIHJlcXVlc3RRdWVyeSA9IHJlcXVlc3RRdWVyeVxuICAgICAgLnNwbGl0KCcmJylcbiAgICAgIC5zb3J0KClcbiAgICAgIC5tYXAoKGVsZW1lbnQpID0+ICghZWxlbWVudC5pbmNsdWRlcygnPScpID8gZWxlbWVudCArICc9JyA6IGVsZW1lbnQpKVxuICA Line truncated
+104
View File
@@ -0,0 +1,104 @@
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015, 2016 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as Crypto from "crypto";
import Through2 from 'through2';
import { isFunction } from "./internal/helper.mjs";
import * as xmlParsers from "./xml-parsers.mjs";
// getConcater returns a stream that concatenates the input and emits
// the concatenated output when 'end' has reached. If an optional
// parser function is passed upon reaching the 'end' of the stream,
// `parser(concatenated_data)` will be emitted.
export function getConcater(parser, emitError) {
var objectMode = false;
var bufs = [];
if (parser && !isFunction(parser)) {
throw new TypeError('parser should be of type "function"');
}
if (parser) {
objectMode = true;
}
return Through2({
objectMode
}, function (chunk, enc, cb) {
bufs.push(chunk);
cb();
}, function (cb) {
if (emitError) {
cb(parser(Buffer.concat(bufs).toString()));
// cb(e) would mean we have to emit 'end' by explicitly calling this.push(null)
this.push(null);
return;
}
if (bufs.length) {
if (parser) {
this.push(parser(Buffer.concat(bufs).toString()));
} else {
this.push(Buffer.concat(bufs));
}
}
cb();
});
}
// A through stream that calculates md5sum and sha256sum
export function getHashSummer(enableSHA256) {
var md5 = Crypto.createHash('md5');
var sha256 = Crypto.createHash('sha256');
return Through2.obj(function (chunk, enc, cb) {
if (enableSHA256) {
sha256.update(chunk);
} else {
md5.update(chunk);
}
cb();
}, function (cb) {
var md5sum = '';
var sha256sum = '';
if (enableSHA256) {
sha256sum = sha256.digest('hex');
} else {
md5sum = md5.digest('base64');
}
var hashData = {
md5sum,
sha256sum
};
this.push(hashData);
this.push(null);
cb();
});
}
// Following functions return a stream object that parses XML
// and emits suitable Javascript objects.
// Parses listObjects response.
export function getListObjectsV2Transformer() {
return getConcater(xmlParsers.parseListObjectsV2);
}
// Parses listObjects with metadata response.
export function getListObjectsV2WithMetadataTransformer() {
return getConcater(xmlParsers.parseListObjectsV2WithMetadata);
}
// Parses GET/SET BucketNotification response
export function getBucketNotificationTransformer() {
return getConcater(xmlParsers.parseBucketNotification);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDcnlwdG8iLCJUaHJvdWdoMiIsImlzRnVuY3Rpb24iLCJ4bWxQYXJzZXJzIiwiZ2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2NyaXB0IG9iamVjdHMuXG5cbi8vIFBhcnNlcyBsaXN0T2JqZWN0cyByZXNwb25zZS5cbmV4cG9ydCBmdW5jdGlvbiBnZXRMaXN0T2JqZWN0c1YyVHJhbnNmb3JtZXIoKSB7XG4gIHJldHVybiBnZXRDb25jYXRlcih4bWxQYXJzZXJzLnBhcnNlTGlzdE9iamVjdHNWMilcbn1cblxuLy8gUGFyc2VzIGxpc3RPYmplY3RzIHdpdGggbWV0YWRhdGEgcmVzcG9uc2UuXG5leHBvcnQgZnVuY3Rpb24gZ2V0TGlzdE9iamVjdHNWMldpdGhNZXRhZGF0YVRyYW5zZm9ybWVyKCkge1xuICByZXR1cm4gZ2V0Q29uY2F0ZXIoeG1sUGFyc2Vycy5wYXJzZUxpc3RPYmplY3RzVjJXaXRoTWV0YWRhdGEpXG59XG5cbi8vIFBhcnNlcyBHRVQvU0VUIEJ1Y2tldE5vdGlmaWNhdGlvbiByZXNwb25zZVxuZXhwb3J0IGZ1bmN0aW9uIGdldEJ1Y2tldE5vdGlmaWN Line truncated
+199
View File
@@ -0,0 +1,199 @@
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as errors from "./errors.mjs";
import { parseXml, sanitizeETag, sanitizeObjectKey, toArray } from "./internal/helper.mjs";
// parse XML response for bucket notification
export function parseBucketNotification(xml) {
var result = {
TopicConfiguration: [],
QueueConfiguration: [],
CloudFunctionConfiguration: []
};
// Parse the events list
var genEvents = function (events) {
var result = [];
if (events) {
toArray(events).forEach(s3event => {
result.push(s3event);
});
}
return result;
};
// Parse all filter rules
var genFilterRules = function (filters) {
var result = [];
if (filters) {
filters = toArray(filters);
if (filters[0].S3Key) {
filters[0].S3Key = toArray(filters[0].S3Key);
if (filters[0].S3Key[0].FilterRule) {
toArray(filters[0].S3Key[0].FilterRule).forEach(rule => {
var Name = toArray(rule.Name)[0];
var Value = toArray(rule.Value)[0];
result.push({
Name,
Value
});
});
}
}
}
return result;
};
var xmlobj = parseXml(xml);
xmlobj = xmlobj.NotificationConfiguration;
// Parse all topic configurations in the xml
if (xmlobj.TopicConfiguration) {
toArray(xmlobj.TopicConfiguration).forEach(config => {
var Id = toArray(config.Id)[0];
var Topic = toArray(config.Topic)[0];
var Event = genEvents(config.Event);
var Filter = genFilterRules(config.Filter);
result.TopicConfiguration.push({
Id,
Topic,
Event,
Filter
});
});
}
// Parse all topic configurations in the xml
if (xmlobj.QueueConfiguration) {
toArray(xmlobj.QueueConfiguration).forEach(config => {
var Id = toArray(config.Id)[0];
var Queue = toArray(config.Queue)[0];
var Event = genEvents(config.Event);
var Filter = genFilterRules(config.Filter);
result.QueueConfiguration.push({
Id,
Queue,
Event,
Filter
});
});
}
// Parse all QueueConfiguration arrays
if (xmlobj.CloudFunctionConfiguration) {
toArray(xmlobj.CloudFunctionConfiguration).forEach(config => {
var Id = toArray(config.Id)[0];
var CloudFunction = toArray(config.CloudFunction)[0];
var Event = genEvents(config.Event);
var Filter = genFilterRules(config.Filter);
result.CloudFunctionConfiguration.push({
Id,
CloudFunction,
Event,
Filter
});
});
}
return result;
}
// parse XML response for list objects v2 in a bucket
export function parseListObjectsV2(xml) {
var result = {
objects: [],
isTruncated: false
};
var xmlobj = parseXml(xml);
if (!xmlobj.ListBucketResult) {
throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"');
}
xmlobj = xmlobj.ListBucketResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextContinuationToken) {
result.nextContinuationToken = xmlobj.NextContinuationToken;
}
if (xmlobj.Contents) {
toArray(xmlobj.Contents).forEach(content => {
var name = sanitizeObjectKey(toArray(content.Key)[0]);
var lastModified = new Date(content.LastModified);
var etag = sanitizeETag(content.ETag);
var size = content.Size;
result.objects.push({
name,
lastModified,
etag,
size
});
});
}
if (xmlobj.CommonPrefixes) {
toArray(xmlobj.CommonPrefixes).forEach(commonPrefix => {
result.objects.push({
prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0]),
size: 0
});
});
}
return result;
}
// parse XML response for list objects v2 with metadata in a bucket
export function parseListObjectsV2WithMetadata(xml) {
var result = {
objects: [],
isTruncated: false
};
var xmlobj = parseXml(xml);
if (!xmlobj.ListBucketResult) {
throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"');
}
xmlobj = xmlobj.ListBucketResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextContinuationToken) {
result.nextContinuationToken = xmlobj.NextContinuationToken;
}
if (xmlobj.Contents) {
toArray(xmlobj.Contents).forEach(content => {
var name = sanitizeObjectKey(content.Key);
var lastModified = new Date(content.LastModified);
var etag = sanitizeETag(content.ETag);
var size = content.Size;
var metadata;
if (content.UserMetadata != null) {
metadata = toArray(content.UserMetadata)[0];
} else {
metadata = null;
}
result.objects.push({
name,
lastModified,
etag,
size,
metadata
});
});
}
if (xmlobj.CommonPrefixes) {
toArray(xmlobj.CommonPrefixes).forEach(commonPrefix => {
result.objects.push({
prefix: sanitizeObjectKey(toArray(commonPrefix.Prefix)[0]),
size: 0
});
});
}
return result;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJlcnJvcnMiLCJwYXJzZVhtbCIsInNhbml0aXplRVRhZyIsInNhbml0aXplT2JqZWN0S2V5IiwidG9BcnJheSIsInBhcnNlQnVja2V0Tm90aWZpY2F0aW9uIiwieG1sIiwicmVzdWx0IiwiVG9waWNDb25maWd1cmF0aW9uIiwiUXVldWVDb25maWd1cmF0aW9uIiwiQ2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yKVxuICAgICAgcmVzdWx0LlF1ZXVlQ29uZmlndXJhdGlvbi5wdXNoKHsgSWQsIFF1ZXVlLCBFdmVudCwgRmlsdGVyIH0pXG4gICAgfSlcbiAgfVxuICAvLyBQYXJzZSBhbGwgUXVldWVDb25maWd1cmF0aW9uIGFycmF5c1xuICBpZiAoeG1sb2JqLkNsb3VkRnVuY3Rpb25Db25maWd1cmF0aW9uKSB7XG4gICAgdG9BcnJheSh4bWxvYmouQ2xvdWRGdW5jdGlvbkNvbmZpZ3VyYXRpb24pLmZvckVhY2goKGNvbmZpZykgPT4ge1xuICAgICAgdmFyIElkID0gdG9BcnJheShjb25maWcuSWQpWzBdXG4gICAgICB2YXI Line truncated
@@ -0,0 +1,86 @@
/// <reference types="node" />
import * as http from 'node:http';
import { CredentialProvider } from "./CredentialProvider.js";
import { Credentials } from "./Credentials.js";
/**
* @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html
*/
type CredentialResponse = {
ErrorResponse?: {
Error?: {
Code?: string;
Message?: string;
};
};
AssumeRoleResponse: {
AssumeRoleResult: {
Credentials: {
AccessKeyId: string;
SecretAccessKey: string;
SessionToken: string;
Expiration: string;
};
};
};
};
export interface AssumeRoleProviderOptions {
stsEndpoint: string;
accessKey: string;
secretKey: string;
durationSeconds?: number;
sessionToken?: string;
policy?: string;
region?: string;
roleArn?: string;
roleSessionName?: string;
externalId?: string;
token?: string;
webIdentityToken?: string;
action?: string;
transportAgent?: http.Agent;
}
export declare class AssumeRoleProvider extends CredentialProvider {
private readonly stsEndpoint;
private readonly accessKey;
private readonly secretKey;
private readonly durationSeconds;
private readonly policy?;
private readonly region;
private readonly roleArn?;
private readonly roleSessionName?;
private readonly externalId?;
private readonly token?;
private readonly webIdentityToken?;
private readonly action;
private _credentials;
private readonly expirySeconds;
private accessExpiresAt;
private readonly transportAgent?;
private readonly transport;
constructor({
stsEndpoint,
accessKey,
secretKey,
durationSeconds,
sessionToken,
policy,
region,
roleArn,
roleSessionName,
externalId,
token,
webIdentityToken,
action,
transportAgent
}: AssumeRoleProviderOptions);
getRequestConfig(): {
requestOptions: http.RequestOptions;
requestData: string;
};
performRequest(): Promise<CredentialResponse>;
parseCredentials(respObj: CredentialResponse): Credentials;
refreshCredentials(): Promise<Credentials>;
getCredentials(): Promise<Credentials>;
isAboutToExpire(): boolean;
}
export default AssumeRoleProvider;
+191
View File
@@ -0,0 +1,191 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var http = _interopRequireWildcard(require("http"), true);
var https = _interopRequireWildcard(require("https"), true);
var _url = require("url");
var _CredentialProvider = require("./CredentialProvider.js");
var _Credentials = require("./Credentials.js");
var _helper = require("./internal/helper.js");
var _request = require("./internal/request.js");
var _response = require("./internal/response.js");
var _signing = require("./signing.js");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/**
* @see https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html
*/
const defaultExpirySeconds = 900;
class AssumeRoleProvider extends _CredentialProvider.CredentialProvider {
accessExpiresAt = '';
constructor({
stsEndpoint,
accessKey,
secretKey,
durationSeconds = defaultExpirySeconds,
sessionToken,
policy,
region = '',
roleArn,
roleSessionName,
externalId,
token,
webIdentityToken,
action = 'AssumeRole',
transportAgent = undefined
}) {
super({
accessKey,
secretKey,
sessionToken
});
this.stsEndpoint = new _url.URL(stsEndpoint);
this.accessKey = accessKey;
this.secretKey = secretKey;
this.policy = policy;
this.region = region;
this.roleArn = roleArn;
this.roleSessionName = roleSessionName;
this.externalId = externalId;
this.token = token;
this.webIdentityToken = webIdentityToken;
this.action = action;
this.durationSeconds = parseInt(durationSeconds);
let expirySeconds = this.durationSeconds;
if (this.durationSeconds < defaultExpirySeconds) {
expirySeconds = defaultExpirySeconds;
}
this.expirySeconds = expirySeconds; // for calculating refresh of credentials.
// By default, nodejs uses a global agent if the 'agent' property
// is set to undefined. Otherwise, it's okay to assume the users
// know what they're doing if they specify a custom transport agent.
this.transportAgent = transportAgent;
const isHttp = this.stsEndpoint.protocol === 'http:';
this.transport = isHttp ? http : https;
/**
* Internal Tracking variables
*/
this._credentials = null;
}
getRequestConfig() {
const hostValue = this.stsEndpoint.hostname;
const portValue = this.stsEndpoint.port;
const qryParams = new _url.URLSearchParams({
Action: this.action,
Version: '2011-06-15'
});
qryParams.set('DurationSeconds', this.expirySeconds.toString());
if (this.policy) {
qryParams.set('Policy', this.policy);
}
if (this.roleArn) {
qryParams.set('RoleArn', this.roleArn);
}
if (this.roleSessionName != null) {
qryParams.set('RoleSessionName', this.roleSessionName);
}
if (this.token != null) {
qryParams.set('Token', this.token);
}
if (this.webIdentityToken) {
qryParams.set('WebIdentityToken', this.webIdentityToken);
}
if (this.externalId) {
qryParams.set('ExternalId', this.externalId);
}
const urlParams = qryParams.toString();
const contentSha256 = (0, _helper.toSha256)(urlParams);
const date = new Date();
const requestOptions = {
hostname: hostValue,
port: portValue,
path: '/',
protocol: this.stsEndpoint.protocol,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'content-length': urlParams.length.toString(),
host: hostValue,
'x-amz-date': (0, _helper.makeDateLong)(date),
'x-amz-content-sha256': contentSha256
},
agent: this.transportAgent
};
requestOptions.headers.authorization = (0, _signing.signV4ByServiceName)(requestOptions, this.accessKey, this.secretKey, this.region, date, contentSha256, 'sts');
return {
requestOptions,
requestData: urlParams
};
}
async performRequest() {
const {
requestOptions,
requestData
} = this.getRequestConfig();
const res = await (0, _request.request)(this.transport, requestOptions, requestData);
const body = await (0, _response.readAsString)(res);
return (0, _helper.parseXml)(body);
}
parseCredentials(respObj) {
if (respObj.ErrorResponse) {
var _respObj$ErrorRespons, _respObj$ErrorRespons2, _respObj$ErrorRespons3, _respObj$ErrorRespons4;
throw new Error(`Unable to obtain credentials: ${(_respObj$ErrorRespons = respObj.ErrorResponse) === null || _respObj$ErrorRespons === void 0 ? void 0 : (_respObj$ErrorRespons2 = _respObj$ErrorRespons.Error) === null || _respObj$ErrorRespons2 === void 0 ? void 0 : _respObj$ErrorRespons2.Code} ${(_respObj$ErrorRespons3 = respObj.ErrorResponse) === null || _respObj$ErrorRespons3 === void 0 ? void 0 : (_respObj$ErrorRespons4 = _respObj$ErrorRespons3.Error) === null || _respObj$ErrorRespons4 === void 0 ? void 0 : _respObj$ErrorRespons4.Message}`, {
cause: respObj
});
}
const {
AssumeRoleResponse: {
AssumeRoleResult: {
Credentials: {
AccessKeyId: accessKey,
SecretAccessKey: secretKey,
SessionToken: sessionToken,
Expiration: expiresAt
}
}
}
} = respObj;
this.accessExpiresAt = expiresAt;
return new _Credentials.Credentials({
accessKey,
secretKey,
sessionToken
});
}
async refreshCredentials() {
try {
const assumeRoleCredentials = await this.performRequest();
this._credentials = this.parseCredentials(assumeRoleCredentials);
} catch (err) {
throw new Error(`Failed to get Credentials: ${err}`, {
cause: err
});
}
return this._credentials;
}
async getCredentials() {
if (this._credentials && !this.isAboutToExpire()) {
return this._credentials;
}
this._credentials = await this.refreshCredentials();
return this._credentials;
}
isAboutToExpire() {
const expiresAt = new Date(this.accessExpiresAt);
const provisionalExpiry = new Date(Date.now() + 1000 * 10); // check before 10 seconds.
return provisionalExpiry > expiresAt;
}
}
// deprecated default export, please use named exports.
// keep for backward compatibility.
// eslint-disable-next-line import/no-default-export
exports.AssumeRoleProvider = AssumeRoleProvider;
var _default = AssumeRoleProvider;
exports.default = _default;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJodHRwIiwiX2ludGVyb3BSZXF1aXJlV2lsZGNhcmQiLCJyZXF1aXJlIiwiaHR0cHMiLCJfdXJsIiwiX0NyZWRlbnRpYWxQcm92aWRlciIsIl9DcmVkZW50aWFscyIsIl9oZWxwZXIiLCJfcmVxdWVzdCIsIl9yZXNwb25zZSIsIl9zaWduaW5nIiwiX2dldFJlcXVpcmVXaWxkY2FyZENhY2hlIiwibm9kZUludGVyb3AiLCJXZWFrTWFwIiwiY2FjaGVCYWJlbEludGVyb3AiLCJjYWNoZU5vZGVJbnRlcm9wIiwib2JqIiwiX19lc01vZHVsZSIsImRlZmF1bHQiLCJjYWNoZSIsImhhcyIsImdldCIsIm5ld09iaiIsImhhc1Byb3BlcnR5RGVzY3JpcHRvciIsIk9iamVjdCIsImRlZmluZVByb3BlcnR5IiwiZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9yIiwia2V5IiwicHJvdG90eXBlIiwiaGFzT3duUHJvcGVydHkiLCJjYWxsIiwiZGVzYyIsInNldCIsImRlZmF1bHRFeHBpcnlTZWNvbmRzIiwiQXNzdW1lUm9sZVByb3ZpZGVyIiwiQ3JlZGVudGlhbFByb3ZpZGVyIiwiYWNjZXNzRXhwaXJlc0F0IiwiY29uc3RydWN0b3IiLCJzdHNFbmRwb2ludCIsImFjY2Vzc0tleSIsInNlY3JldEtleSIsImR1cmF0aW9uU2Vjb25kcyIsInNlc3Npb25Ub2tlbiIsInBvbGljeSIsInJlZ2lvbiIsInJvbGVBcm4iLCJyb2xlU2Vzc2lvbk5hbWUiLCJleHRlcm5hbElkIiwidG9rZW4iLCJ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yBDcmVkZW50aWFsUHJvdmlkZXIge1xuICBwcml2YXRlIHJlYWRvbmx5IHN0c0VuZHBvaW50OiBVUkxcbiAgcHJpdmF0ZSByZWFkb25seSBhY2Nlc3NLZXk6IHN0cmluZ1xuICBwcml2YXRlIHJlYWRvbmx5IHNlY3JldEtleTogc3RyaW5nXG4gIHByaXZhdGUgcmVhZG9ubHkgZHVyYXRpb25TZWNvbmRzOiBudW1iZXJcbiAgcHJpdmF0ZSByZWFkb25seSBwb2xpY3k/OiBzdHJpbmdcbiAgcHJpdmF0ZSByZWFkb25seSByZWdpb246IHN0cmluZ1xuICBwcml2YXRlIHJlYWRvbmx5IHJvbGVBcm4/OiBzdHJpbmdcbiAgcHJpdmF0ZSByZWFkb25seSByb2xlU2Vzc2lvbk5hbWU/OiBzdHJpbmdcbiAgcHJpdmF0ZSByZWFkb25seSBleHRlcm5hbElkPzogc3RyaW5nXG4gIHByaXZhdGUgcmVhZG9ubHkgdG9rZW4/OiBzdHJpbmdcbiAgcHJpdmF0ZSByZWFkb25seSB3ZWJJZGVudGl0eVRva2VuPzogc3RyaW5nXG4gIHByaXZhdGUgcmVhZG9ubHkgYWN0aW9uOiBzdHJpbmdcblxuICBwcml2YXRlIF9jcmVkZW50aWFsczogQ3JlZGVudGlhbHMgfCBudWxsXG4gIHByaXZhdGUgcmVhZG9ubHkgZXhwaXJ5U2Vjb25kczogbnVtYmVyXG4gIHByaXZhdGUgYWNjZXNzRXhwaXJlc0F0ID0gJydcbiAgcHJpdmF0ZSByZWF Line truncated
@@ -0,0 +1,22 @@
import { Credentials } from "./Credentials.js";
export declare class CredentialProvider {
private credentials;
constructor({
accessKey,
secretKey,
sessionToken
}: {
accessKey: string;
secretKey: string;
sessionToken?: string;
});
getCredentials(): Promise<Credentials>;
setCredentials(credentials: Credentials): void;
setAccessKey(accessKey: string): void;
getAccessKey(): string;
setSecretKey(secretKey: string): void;
getSecretKey(): string;
setSessionToken(sessionToken: string): void;
getSessionToken(): string | undefined;
}
export default CredentialProvider;
+55
View File
@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Credentials = require("./Credentials.js");
class CredentialProvider {
constructor({
accessKey,
secretKey,
sessionToken
}) {
this.credentials = new _Credentials.Credentials({
accessKey,
secretKey,
sessionToken
});
}
async getCredentials() {
return this.credentials.get();
}
setCredentials(credentials) {
if (credentials instanceof _Credentials.Credentials) {
this.credentials = credentials;
} else {
throw new Error('Unable to set Credentials. it should be an instance of Credentials class');
}
}
setAccessKey(accessKey) {
this.credentials.setAccessKey(accessKey);
}
getAccessKey() {
return this.credentials.getAccessKey();
}
setSecretKey(secretKey) {
this.credentials.setSecretKey(secretKey);
}
getSecretKey() {
return this.credentials.getSecretKey();
}
setSessionToken(sessionToken) {
this.credentials.setSessionToken(sessionToken);
}
getSessionToken() {
return this.credentials.getSessionToken();
}
}
// deprecated default export, please use named exports.
// keep for backward compatibility.
// eslint-disable-next-line import/no-default-export
exports.CredentialProvider = CredentialProvider;
var _default = CredentialProvider;
exports.default = _default;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfQ3JlZGVudGlhbHMiLCJyZXF1aXJlIiwiQ3JlZGVudGlhbFByb3ZpZGVyIiwiY29uc3RydWN0b3IiLCJhY2Nlc3NLZXkiLCJzZWNyZXRLZXkiLCJzZXNzaW9uVG9rZW4iLCJjcmVkZW50aWFscyIsIkNyZWRlbnRpYWxzIiwiZ2V0Q3JlZGVudGlhbHMiLCJnZXQiLCJzZXRDcmVkZW50aWFscyIsIkVycm9yIiwic2V0QWNjZXNzS2V5IiwiZ2V0QWNjZXNzS2V5Iiwic2V0U2VjcmV0S2V5IiwiZ2V0U2VjcmV0S2V5Iiwic2V0U2Vzc2lvblRva2VuIiwiZ2V0U2Vzc2lvblRva2VuIiwiZXhwb3J0cyIsIl9kZWZhdWx0IiwiZGVmYXVsdCJdLCJzb3VyY2VzIjpbIkNyZWRlbnRp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QUFDQTtBQUNBO0FBQUFDLE9BQUEsQ0FBQWpCLGtCQUFBLEdBQUFBLGtCQUFBO0FBQUEsSUFBQWtCLFFBQUEsR0FDZWxCLGtCQUFrQjtBQUFBaUIsT0FBQSxDQUFBRSxPQUFBLEdBQUFELFFBQUEifQ==
+22
View File
@@ -0,0 +1,22 @@
export declare class Credentials {
accessKey: string;
secretKey: string;
sessionToken?: string;
constructor({
accessKey,
secretKey,
sessionToken
}: {
accessKey: string;
secretKey: string;
sessionToken?: string;
});
setAccessKey(accessKey: string): void;
getAccessKey(): string;
setSecretKey(secretKey: string): void;
getSecretKey(): string;
setSessionToken(sessionToken: string): void;
getSessionToken(): string | undefined;
get(): Credentials;
}
export default Credentials;
+45
View File
@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
class Credentials {
constructor({
accessKey,
secretKey,
sessionToken
}) {
this.accessKey = accessKey;
this.secretKey = secretKey;
this.sessionToken = sessionToken;
}
setAccessKey(accessKey) {
this.accessKey = accessKey;
}
getAccessKey() {
return this.accessKey;
}
setSecretKey(secretKey) {
this.secretKey = secretKey;
}
getSecretKey() {
return this.secretKey;
}
setSessionToken(sessionToken) {
this.sessionToken = sessionToken;
}
getSessionToken() {
return this.sessionToken;
}
get() {
return this;
}
}
// deprecated default export, please use named exports.
// keep for backward compatibility.
// eslint-disable-next-line import/no-default-export
exports.Credentials = Credentials;
var _default = Credentials;
exports.default = _default;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDcmVkZW50aWFscyIsImNvbnN0cnVjdG9yIiwiYWNjZXNzS2V5Iiwic2VjcmV0S2V5Iiwic2Vzc2lvblRva2VuIiwic2V0QWNjZXNzS2V5IiwiZ2V0QWNjZXNzS2V5Iiwic2V0U2VjcmV0S2V5IiwiZ2V0U2VjcmV0S2V5Iiwic2V0U2Vzc2lvblRva2VuIiwiZ2V0U2Vzc2lvblRva2VuIiwiZ2V0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xlQUFlQSxDQUFBLEVBQUc7SUFDaEIsT0FBTyxJQUFJLENBQUNOLFlBQVk7RUFDMUI7RUFFQU8sR0FBR0EsQ0FBQSxFQUFnQjtJQUNqQixPQUFPLElBQUk7RUFDYjtBQUNGOztBQUVBO0FBQ0E7QUFDQTtBQUFBQyxPQUFBLENBQUFaLFdBQUEsR0FBQUEsV0FBQTtBQUFBLElBQUFhLFFBQUEsR0FDZWIsV0FBVztBQUFBWSxPQUFBLENBQUFFLE9BQUEsR0FBQUQsUUFBQSJ9
+27
View File
@@ -0,0 +1,27 @@
/// <reference types="node" />
import * as http from 'node:http';
import { CredentialProvider } from "./CredentialProvider.js";
import { Credentials } from "./Credentials.js";
export interface IamAwsProviderOptions {
customEndpoint?: string;
transportAgent?: http.Agent;
}
export declare class IamAwsProvider extends CredentialProvider {
private readonly customEndpoint?;
private _credentials;
private readonly transportAgent?;
private accessExpiresAt;
constructor({
customEndpoint,
transportAgent
}: IamAwsProviderOptions);
getCredentials(): Promise<Credentials>;
private fetchCredentials;
private fetchCredentialsUsingTokenFile;
private fetchImdsToken;
private getIamRoleNamedUrl;
private getIamRoleName;
private requestCredentials;
private isAboutToExpire;
}
export default IamAwsProvider;
+198
View File
@@ -0,0 +1,198 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var fs = _interopRequireWildcard(require("fs/promises"), true);
var http = _interopRequireWildcard(require("http"), true);
var https = _interopRequireWildcard(require("https"), true);
var _url = require("url");
var _CredentialProvider = require("./CredentialProvider.js");
var _Credentials = require("./Credentials.js");
var _helper = require("./internal/helper.js");
var _request = require("./internal/request.js");
var _response = require("./internal/response.js");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
class IamAwsProvider extends _CredentialProvider.CredentialProvider {
accessExpiresAt = '';
constructor({
customEndpoint = undefined,
transportAgent = undefined
}) {
super({
accessKey: '',
secretKey: ''
});
this.customEndpoint = customEndpoint;
this.transportAgent = transportAgent;
/**
* Internal Tracking variables
*/
this._credentials = null;
}
async getCredentials() {
if (!this._credentials || this.isAboutToExpire()) {
this._credentials = await this.fetchCredentials();
}
return this._credentials;
}
async fetchCredentials() {
try {
// check for IRSA (https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html)
const tokenFile = process.env.AWS_WEB_IDENTITY_TOKEN_FILE;
if (tokenFile) {
return await this.fetchCredentialsUsingTokenFile(tokenFile);
}
// try with IAM role for EC2 instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html)
let tokenHeader = 'Authorization';
let token = process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;
const relativeUri = process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI;
const fullUri = process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI;
let url;
if (relativeUri) {
url = new _url.URL(relativeUri, 'http://169.254.170.2');
} else if (fullUri) {
url = new _url.URL(fullUri);
} else {
token = await this.fetchImdsToken();
tokenHeader = 'X-aws-ec2-metadata-token';
url = await this.getIamRoleNamedUrl(token);
}
return this.requestCredentials(url, tokenHeader, token);
} catch (err) {
throw new Error(`Failed to get Credentials: ${err}`, {
cause: err
});
}
}
async fetchCredentialsUsingTokenFile(tokenFile) {
const token = await fs.readFile(tokenFile, {
encoding: 'utf8'
});
const region = process.env.AWS_REGION;
const stsEndpoint = new _url.URL(region ? `https://sts.${region}.amazonaws.com` : 'https://sts.amazonaws.com');
const hostValue = stsEndpoint.hostname;
const portValue = stsEndpoint.port;
const qryParams = new _url.URLSearchParams({
Action: 'AssumeRoleWithWebIdentity',
Version: '2011-06-15'
});
const roleArn = process.env.AWS_ROLE_ARN;
if (roleArn) {
qryParams.set('RoleArn', roleArn);
const roleSessionName = process.env.AWS_ROLE_SESSION_NAME;
qryParams.set('RoleSessionName', roleSessionName ? roleSessionName : Date.now().toString());
}
qryParams.set('WebIdentityToken', token);
qryParams.sort();
const requestOptions = {
hostname: hostValue,
port: portValue,
path: `${stsEndpoint.pathname}?${qryParams.toString()}`,
protocol: stsEndpoint.protocol,
method: 'POST',
headers: {},
agent: this.transportAgent
};
const transport = stsEndpoint.protocol === 'http:' ? http : https;
const res = await (0, _request.request)(transport, requestOptions, null);
const body = await (0, _response.readAsString)(res);
const assumeRoleResponse = (0, _helper.parseXml)(body);
const creds = assumeRoleResponse.AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult.Credentials;
this.accessExpiresAt = creds.Expiration;
return new _Credentials.Credentials({
accessKey: creds.AccessKeyId,
secretKey: creds.SecretAccessKey,
sessionToken: creds.SessionToken
});
}
async fetchImdsToken() {
const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254';
const url = new _url.URL('/latest/api/token', endpoint);
const requestOptions = {
hostname: url.hostname,
port: url.port,
path: `${url.pathname}${url.search}`,
protocol: url.protocol,
method: 'PUT',
headers: {
'X-aws-ec2-metadata-token-ttl-seconds': '21600'
},
agent: this.transportAgent
};
const transport = url.protocol === 'http:' ? http : https;
const res = await (0, _request.request)(transport, requestOptions, null);
return await (0, _response.readAsString)(res);
}
async getIamRoleNamedUrl(token) {
const endpoint = this.customEndpoint ? this.customEndpoint : 'http://169.254.169.254';
const url = new _url.URL('latest/meta-data/iam/security-credentials/', endpoint);
const roleName = await this.getIamRoleName(url, token);
return new _url.URL(`${url.pathname}/${encodeURIComponent(roleName)}`, url.origin);
}
async getIamRoleName(url, token) {
const requestOptions = {
hostname: url.hostname,
port: url.port,
path: `${url.pathname}${url.search}`,
protocol: url.protocol,
method: 'GET',
headers: {
'X-aws-ec2-metadata-token': token
},
agent: this.transportAgent
};
const transport = url.protocol === 'http:' ? http : https;
const res = await (0, _request.request)(transport, requestOptions, null);
const body = await (0, _response.readAsString)(res);
const roleNames = body.split(/\r\n|[\n\r\u2028\u2029]/);
if (roleNames.length === 0) {
throw new Error(`No IAM roles attached to EC2 service ${url}`);
}
return roleNames[0];
}
async requestCredentials(url, tokenHeader, token) {
const headers = {};
if (token) {
headers[tokenHeader] = token;
}
const requestOptions = {
hostname: url.hostname,
port: url.port,
path: `${url.pathname}${url.search}`,
protocol: url.protocol,
method: 'GET',
headers: headers,
agent: this.transportAgent
};
const transport = url.protocol === 'http:' ? http : https;
const res = await (0, _request.request)(transport, requestOptions, null);
const body = await (0, _response.readAsString)(res);
const ecsCredentials = JSON.parse(body);
if (!ecsCredentials.Code || ecsCredentials.Code != 'Success') {
throw new Error(`${url} failed with code ${ecsCredentials.Code} and message ${ecsCredentials.Message}`);
}
this.accessExpiresAt = ecsCredentials.Expiration;
return new _Credentials.Credentials({
accessKey: ecsCredentials.AccessKeyID,
secretKey: ecsCredentials.SecretAccessKey,
sessionToken: ecsCredentials.Token
});
}
isAboutToExpire() {
const expiresAt = new Date(this.accessExpiresAt);
const provisionalExpiry = new Date(Date.now() + 1000 * 10); // 10 seconds leeway
return provisionalExpiry > expiresAt;
}
}
// deprecated default export, please use named exports.
// keep for backward compatibility.
// eslint-disable-next-line import/no-default-export
exports.IamAwsProvider = IamAwsProvider;
var _default = IamAwsProvider;
exports.default = _default;
//# sourceMappingURL=data:application/json;charset=utf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BvaW50ID0gY3VzdG9tRW5kcG9pbnRcbiAgICB0aGlzLnRyYW5zcG9ydEFnZW50ID0gdHJhbnNwb3J0QWdlbnRcblxuICAgIC8qKlxuICAgICAqIEludGVybmFsIFRyYWNraW5nIHZhcmlhYmxlc1xuICAgICAqL1xuICAgIHRoaXMuX2NyZWRlbnRpYWxzID0gbnVsbFxuICB9XG5cbiAgYXN5bmMgZ2V0Q3JlZGVudGlhbHMoKTogUHJvbWlzZTxDcmVkZW50aWFscz4ge1xuICAgIGlmICghdGhpcy5fY3JlZGVudGlhbHMgfHwgdGhpcy5pc0Fib3V0VG9FeHBpcmUoKSkge1xuICAgICAgdGhpcy5fY3JlZGVudGlhbHMgPSBhd2FpdCB0aGlzLmZldGNoQ3JlZGVudGlhbHMoKVxuICAgIH1cbiAgICByZXR1cm4gdGhpcy5fY3JlZGVudGlhbHNcbiAgfVxuXG4gIHByaXZhdGUgYXN5bmMgZmV0Y2hDcmVkZW50aWFscygpOiBQcm9taXNlPENyZWRlbnRpYWxzPiB7XG4gICAgdHJ5IHtcbiAgICAgIC8vIGNoZWNrIGZvciBJUlNBIChodHRwczovL2RvY3MuYXdzLmFtYXpvbi5jb20vZWtzL2x Line truncated
+82
View File
@@ -0,0 +1,82 @@
/// <reference lib="es2022.error" />
declare class ExtendableError extends Error {
constructor(message?: string, opt?: ErrorOptions);
}
/**
* AnonymousRequestError is generated for anonymous keys on specific
* APIs. NOTE: PresignedURL generation always requires access keys.
*/
export declare class AnonymousRequestError extends ExtendableError {}
/**
* InvalidArgumentError is generated for all invalid arguments.
*/
export declare class InvalidArgumentError extends ExtendableError {}
/**
* InvalidPortError is generated when a non integer value is provided
* for ports.
*/
export declare class InvalidPortError extends ExtendableError {}
/**
* InvalidEndpointError is generated when an invalid end point value is
* provided which does not follow domain standards.
*/
export declare class InvalidEndpointError extends ExtendableError {}
/**
* InvalidBucketNameError is generated when an invalid bucket name is
* provided which does not follow AWS S3 specifications.
* http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
*/
export declare class InvalidBucketNameError extends ExtendableError {}
/**
* InvalidObjectNameError is generated when an invalid object name is
* provided which does not follow AWS S3 specifications.
* http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
*/
export declare class InvalidObjectNameError extends ExtendableError {}
/**
* AccessKeyRequiredError generated by signature methods when access
* key is not found.
*/
export declare class AccessKeyRequiredError extends ExtendableError {}
/**
* SecretKeyRequiredError generated by signature methods when secret
* key is not found.
*/
export declare class SecretKeyRequiredError extends ExtendableError {}
/**
* ExpiresParamError generated when expires parameter value is not
* well within stipulated limits.
*/
export declare class ExpiresParamError extends ExtendableError {}
/**
* InvalidDateError generated when invalid date is found.
*/
export declare class InvalidDateError extends ExtendableError {}
/**
* InvalidPrefixError generated when object prefix provided is invalid
* or does not conform to AWS S3 object key restrictions.
*/
export declare class InvalidPrefixError extends ExtendableError {}
/**
* InvalidBucketPolicyError generated when the given bucket policy is invalid.
*/
export declare class InvalidBucketPolicyError extends ExtendableError {}
/**
* IncorrectSizeError generated when total data read mismatches with
* the input size.
*/
export declare class IncorrectSizeError extends ExtendableError {}
/**
* InvalidXMLError generated when an unknown XML is found.
*/
export declare class InvalidXMLError extends ExtendableError {}
/**
* S3Error is generated for errors returned from S3 server.
* see getErrorTransformer for details
*/
export declare class S3Error extends ExtendableError {
code?: string;
region?: string;
}
export declare class IsValidBucketNameError extends ExtendableError {}
export {};
+138
View File
@@ -0,0 +1,138 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference lib="ES2022.Error" />
class ExtendableError extends Error {
constructor(message, opt) {
// error Option {cause?: unknown} is a 'nice to have',
// don't use it internally
super(message, opt);
// set error name, otherwise it's always 'Error'
this.name = this.constructor.name;
}
}
/**
* AnonymousRequestError is generated for anonymous keys on specific
* APIs. NOTE: PresignedURL generation always requires access keys.
*/
class AnonymousRequestError extends ExtendableError {}
/**
* InvalidArgumentError is generated for all invalid arguments.
*/
exports.AnonymousRequestError = AnonymousRequestError;
class InvalidArgumentError extends ExtendableError {}
/**
* InvalidPortError is generated when a non integer value is provided
* for ports.
*/
exports.InvalidArgumentError = InvalidArgumentError;
class InvalidPortError extends ExtendableError {}
/**
* InvalidEndpointError is generated when an invalid end point value is
* provided which does not follow domain standards.
*/
exports.InvalidPortError = InvalidPortError;
class InvalidEndpointError extends ExtendableError {}
/**
* InvalidBucketNameError is generated when an invalid bucket name is
* provided which does not follow AWS S3 specifications.
* http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
*/
exports.InvalidEndpointError = InvalidEndpointError;
class InvalidBucketNameError extends ExtendableError {}
/**
* InvalidObjectNameError is generated when an invalid object name is
* provided which does not follow AWS S3 specifications.
* http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
*/
exports.InvalidBucketNameError = InvalidBucketNameError;
class InvalidObjectNameError extends ExtendableError {}
/**
* AccessKeyRequiredError generated by signature methods when access
* key is not found.
*/
exports.InvalidObjectNameError = InvalidObjectNameError;
class AccessKeyRequiredError extends ExtendableError {}
/**
* SecretKeyRequiredError generated by signature methods when secret
* key is not found.
*/
exports.AccessKeyRequiredError = AccessKeyRequiredError;
class SecretKeyRequiredError extends ExtendableError {}
/**
* ExpiresParamError generated when expires parameter value is not
* well within stipulated limits.
*/
exports.SecretKeyRequiredError = SecretKeyRequiredError;
class ExpiresParamError extends ExtendableError {}
/**
* InvalidDateError generated when invalid date is found.
*/
exports.ExpiresParamError = ExpiresParamError;
class InvalidDateError extends ExtendableError {}
/**
* InvalidPrefixError generated when object prefix provided is invalid
* or does not conform to AWS S3 object key restrictions.
*/
exports.InvalidDateError = InvalidDateError;
class InvalidPrefixError extends ExtendableError {}
/**
* InvalidBucketPolicyError generated when the given bucket policy is invalid.
*/
exports.InvalidPrefixError = InvalidPrefixError;
class InvalidBucketPolicyError extends ExtendableError {}
/**
* IncorrectSizeError generated when total data read mismatches with
* the input size.
*/
exports.InvalidBucketPolicyError = InvalidBucketPolicyError;
class IncorrectSizeError extends ExtendableError {}
/**
* InvalidXMLError generated when an unknown XML is found.
*/
exports.IncorrectSizeError = IncorrectSizeError;
class InvalidXMLError extends ExtendableError {}
/**
* S3Error is generated for errors returned from S3 server.
* see getErrorTransformer for details
*/
exports.InvalidXMLError = InvalidXMLError;
class S3Error extends ExtendableError {}
exports.S3Error = S3Error;
class IsValidBucketNameError extends ExtendableError {}
exports.IsValidBucketNameError = IsValidBucketNameError;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFeHRlbmRhYmxlRXJyb3IiLCJFcnJvciIsImNvbnN0cnVjdG9yIiwibWVzc2FnZSIsIm9wdCIsIm5hbWUiLCJBbm9ueW1vdXNSZXF1ZXN0RXJyb3IiLCJleHBvcnRzIiwiSW52YWxpZEFyZ3VtZW50RXJyb3IiLCJJbnZhbGlkUG9ydEVycm9yIiwiSW52YWxpZEVuZHBvaW50RXJyb3IiLCJJbnZhbGlkQnVja2V0TmFtZUVycm9yIiwiSW52YWxpZE9iamVjdE5hbWVFcnJvciIsIkFjY2Vzc0tleVJlcXVpcmVkRXJyb3IiLCJTZWNyZXRLZXlSZXF1aXJlZEVycm9yIiwiRXhwaXJlc1BhcmFtRXJyb3IiLCJJbnZhbGlkRGF0ZUVycm9yIiwiSW52YWxpZFByZWZpeEVycm9yIiwiSW52YWxpZEJ1Y2tldFBvbGljeUVycm9yIiwiSW5jb3JyZWN0U2l6ZUVycm9yIiwiSW52YWxpZF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lbmRzIEV4dGVuZGFibGVFcnJvciB7fVxuXG4vKipcbiAqIEludmFsaWRCdWNrZXRQb2xpY3lFcnJvciBnZW5lcmF0ZWQgd2hlbiB0aGUgZ2l2ZW4gYnVja2V0IHBvbGljeSBpcyB Line truncated
+156
View File
@@ -0,0 +1,156 @@
import type { Encryption, ObjectMetaData, RequestHeaders } from "./internal/type.js";
import { RETENTION_MODES } from "./internal/type.js";
export { ENCRYPTION_TYPES, LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./internal/type.js";
export declare const DEFAULT_REGION = "us-east-1";
export declare const PRESIGN_EXPIRY_DAYS_MAX: number;
export interface ICopySourceOptions {
Bucket: string;
Object: string;
/**
* Valid versionId
*/
VersionID?: string;
/**
* Etag to match
*/
MatchETag?: string;
/**
* Etag to exclude
*/
NoMatchETag?: string;
/**
* Modified Date of the object/part. UTC Date in string format
*/
MatchModifiedSince?: string | null;
/**
* Modified Date of the object/part to exclude UTC Date in string format
*/
MatchUnmodifiedSince?: string | null;
/**
* true or false Object range to match
*/
MatchRange?: boolean;
Start?: number;
End?: number;
Encryption?: Encryption;
}
export declare class CopySourceOptions {
readonly Bucket: string;
readonly Object: string;
readonly VersionID: string;
MatchETag: string;
private readonly NoMatchETag;
private readonly MatchModifiedSince;
private readonly MatchUnmodifiedSince;
readonly MatchRange: boolean;
readonly Start: number;
readonly End: number;
private readonly Encryption?;
constructor({
Bucket,
Object,
VersionID,
MatchETag,
NoMatchETag,
MatchModifiedSince,
MatchUnmodifiedSince,
MatchRange,
Start,
End,
Encryption
}: ICopySourceOptions);
validate(): boolean;
getHeaders(): RequestHeaders;
}
/**
* @deprecated use nodejs fs module
*/
export declare function removeDirAndFiles(dirPath: string, removeSelf?: boolean): void;
export interface ICopyDestinationOptions {
/**
* Bucket name
*/
Bucket: string;
/**
* Object Name for the destination (composed/copied) object defaults
*/
Object: string;
/**
* Encryption configuration defaults to {}
* @default {}
*/
Encryption?: Encryption;
UserMetadata?: ObjectMetaData;
/**
* query-string encoded string or Record<string, string> Object
*/
UserTags?: Record<string, string> | string;
LegalHold?: 'on' | 'off';
/**
* UTC Date String
*/
RetainUntilDate?: string;
Mode?: RETENTION_MODES;
MetadataDirective?: 'COPY' | 'REPLACE';
/**
* Extra headers for the target object
*/
Headers?: Record<string, string>;
}
export declare class CopyDestinationOptions {
readonly Bucket: string;
readonly Object: string;
private readonly Encryption?;
private readonly UserMetadata?;
private readonly UserTags?;
private readonly LegalHold?;
private readonly RetainUntilDate?;
private readonly Mode?;
private readonly MetadataDirective?;
private readonly Headers?;
constructor({
Bucket,
Object,
Encryption,
UserMetadata,
UserTags,
LegalHold,
RetainUntilDate,
Mode,
MetadataDirective,
Headers
}: ICopyDestinationOptions);
getHeaders(): RequestHeaders;
validate(): boolean;
}
/**
* maybe this should be a generic type for Records, leave it for later refactor
*/
export declare class SelectResults {
private records?;
private response?;
private stats?;
private progress?;
constructor({
records,
// parsed data as stream
response,
// original response stream
stats,
// stats as xml
progress
}: {
records?: unknown;
response?: unknown;
stats?: string;
progress?: unknown;
});
setStats(stats: string): void;
getStats(): string | undefined;
setProgress(progress: unknown): void;
getProgress(): unknown;
setResponse(response: unknown): void;
getResponse(): unknown;
setRecords(records: unknown): void;
getRecords(): unknown;
}
+233
View File
@@ -0,0 +1,233 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.removeDirAndFiles = removeDirAndFiles;
var fs = _interopRequireWildcard(require("fs"), true);
var path = _interopRequireWildcard(require("path"), true);
var querystring = _interopRequireWildcard(require("query-string"), true);
var errors = _interopRequireWildcard(require("./errors.js"), true);
var _helper = require("./internal/helper.js");
var _type = require("./internal/type.js");
exports.RETENTION_MODES = _type.RETENTION_MODES;
exports.ENCRYPTION_TYPES = _type.ENCRYPTION_TYPES;
exports.LEGAL_HOLD_STATUS = _type.LEGAL_HOLD_STATUS;
exports.RETENTION_VALIDITY_UNITS = _type.RETENTION_VALIDITY_UNITS;
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const DEFAULT_REGION = 'us-east-1';
exports.DEFAULT_REGION = DEFAULT_REGION;
const PRESIGN_EXPIRY_DAYS_MAX = 24 * 60 * 60 * 7; // 7 days in seconds
exports.PRESIGN_EXPIRY_DAYS_MAX = PRESIGN_EXPIRY_DAYS_MAX;
class CopySourceOptions {
constructor({
Bucket,
Object,
VersionID = '',
MatchETag = '',
NoMatchETag = '',
MatchModifiedSince = null,
MatchUnmodifiedSince = null,
MatchRange = false,
Start = 0,
End = 0,
Encryption = undefined
}) {
this.Bucket = Bucket;
this.Object = Object;
this.VersionID = VersionID;
this.MatchETag = MatchETag;
this.NoMatchETag = NoMatchETag;
this.MatchModifiedSince = MatchModifiedSince;
this.MatchUnmodifiedSince = MatchUnmodifiedSince;
this.MatchRange = MatchRange;
this.Start = Start;
this.End = End;
this.Encryption = Encryption;
}
validate() {
if (!(0, _helper.isValidBucketName)(this.Bucket)) {
throw new errors.InvalidBucketNameError('Invalid Source bucket name: ' + this.Bucket);
}
if (!(0, _helper.isValidObjectName)(this.Object)) {
throw new errors.InvalidObjectNameError(`Invalid Source object name: ${this.Object}`);
}
if (this.MatchRange && this.Start !== -1 && this.End !== -1 && this.Start > this.End || this.Start < 0) {
throw new errors.InvalidObjectNameError('Source start must be non-negative, and start must be at most end.');
} else if (this.MatchRange && !(0, _helper.isNumber)(this.Start) || !(0, _helper.isNumber)(this.End)) {
throw new errors.InvalidObjectNameError('MatchRange is specified. But Invalid Start and End values are specified.');
}
return true;
}
getHeaders() {
const headerOptions = {};
headerOptions['x-amz-copy-source'] = encodeURI(this.Bucket + '/' + this.Object);
if (!(0, _helper.isEmpty)(this.VersionID)) {
headerOptions['x-amz-copy-source'] = `${encodeURI(this.Bucket + '/' + this.Object)}?versionId=${this.VersionID}`;
}
if (!(0, _helper.isEmpty)(this.MatchETag)) {
headerOptions['x-amz-copy-source-if-match'] = this.MatchETag;
}
if (!(0, _helper.isEmpty)(this.NoMatchETag)) {
headerOptions['x-amz-copy-source-if-none-match'] = this.NoMatchETag;
}
if (!(0, _helper.isEmpty)(this.MatchModifiedSince)) {
headerOptions['x-amz-copy-source-if-modified-since'] = this.MatchModifiedSince;
}
if (!(0, _helper.isEmpty)(this.MatchUnmodifiedSince)) {
headerOptions['x-amz-copy-source-if-unmodified-since'] = this.MatchUnmodifiedSince;
}
return headerOptions;
}
}
/**
* @deprecated use nodejs fs module
*/
exports.CopySourceOptions = CopySourceOptions;
function removeDirAndFiles(dirPath, removeSelf = true) {
if (removeSelf) {
return fs.rmSync(dirPath, {
recursive: true,
force: true
});
}
fs.readdirSync(dirPath).forEach(item => {
fs.rmSync(path.join(dirPath, item), {
recursive: true,
force: true
});
});
}
class CopyDestinationOptions {
constructor({
Bucket,
Object,
Encryption,
UserMetadata,
UserTags,
LegalHold,
RetainUntilDate,
Mode,
MetadataDirective,
Headers
}) {
this.Bucket = Bucket;
this.Object = Object;
this.Encryption = Encryption ?? undefined; // null input will become undefined, easy for runtime assert
this.UserMetadata = UserMetadata;
this.UserTags = UserTags;
this.LegalHold = LegalHold;
this.Mode = Mode; // retention mode
this.RetainUntilDate = RetainUntilDate;
this.MetadataDirective = MetadataDirective;
this.Headers = Headers;
}
getHeaders() {
const replaceDirective = 'REPLACE';
const headerOptions = {};
const userTags = this.UserTags;
if (!(0, _helper.isEmpty)(userTags)) {
headerOptions['X-Amz-Tagging-Directive'] = replaceDirective;
headerOptions['X-Amz-Tagging'] = (0, _helper.isObject)(userTags) ? querystring.stringify(userTags) : (0, _helper.isString)(userTags) ? userTags : '';
}
if (this.Mode) {
headerOptions['X-Amz-Object-Lock-Mode'] = this.Mode; // GOVERNANCE or COMPLIANCE
}
if (this.RetainUntilDate) {
headerOptions['X-Amz-Object-Lock-Retain-Until-Date'] = this.RetainUntilDate; // needs to be UTC.
}
if (this.LegalHold) {
headerOptions['X-Amz-Object-Lock-Legal-Hold'] = this.LegalHold; // ON or OFF
}
if (this.UserMetadata) {
for (const [key, value] of Object.entries(this.UserMetadata)) {
headerOptions[`X-Amz-Meta-${key}`] = value.toString();
}
}
if (this.MetadataDirective) {
headerOptions[`X-Amz-Metadata-Directive`] = this.MetadataDirective;
}
if (this.Encryption) {
const encryptionHeaders = (0, _helper.getEncryptionHeaders)(this.Encryption);
for (const [key, value] of Object.entries(encryptionHeaders)) {
headerOptions[key] = value;
}
}
if (this.Headers) {
for (const [key, value] of Object.entries(this.Headers)) {
headerOptions[key] = value;
}
}
return headerOptions;
}
validate() {
if (!(0, _helper.isValidBucketName)(this.Bucket)) {
throw new errors.InvalidBucketNameError('Invalid Destination bucket name: ' + this.Bucket);
}
if (!(0, _helper.isValidObjectName)(this.Object)) {
throw new errors.InvalidObjectNameError(`Invalid Destination object name: ${this.Object}`);
}
if (!(0, _helper.isEmpty)(this.UserMetadata) && !(0, _helper.isObject)(this.UserMetadata)) {
throw new errors.InvalidObjectNameError(`Destination UserMetadata should be an object with key value pairs`);
}
if (!(0, _helper.isEmpty)(this.Mode) && ![_type.RETENTION_MODES.GOVERNANCE, _type.RETENTION_MODES.COMPLIANCE].includes(this.Mode)) {
throw new errors.InvalidObjectNameError(`Invalid Mode specified for destination object it should be one of [GOVERNANCE,COMPLIANCE]`);
}
if (this.Encryption !== undefined && (0, _helper.isEmptyObject)(this.Encryption)) {
throw new errors.InvalidObjectNameError(`Invalid Encryption configuration for destination object `);
}
return true;
}
}
/**
* maybe this should be a generic type for Records, leave it for later refactor
*/
exports.CopyDestinationOptions = CopyDestinationOptions;
class SelectResults {
constructor({
records,
// parsed data as stream
response,
// original response stream
stats,
// stats as xml
progress // stats as xml
}) {
this.records = records;
this.response = response;
this.stats = stats;
this.progress = progress;
}
setStats(stats) {
this.stats = stats;
}
getStats() {
return this.stats;
}
setProgress(progress) {
this.progress = progress;
}
getProgress() {
return this.progress;
}
setResponse(response) {
this.response = response;
}
getResponse() {
return this.response;
}
setRecords(records) {
this.records = records;
}
getRecords() {
return this.records;
}
}
exports.SelectResults = SelectResults;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmcyIsIl9pbnRlcm9wUmVxdWlyZVdpbGRjYXJkIiwicmVxdWlyZSIsInBhdGgiLCJxdWVyeXN0cmluZyIsImVycm9ycyIsIl9oZWxwZXIiLCJfdHlwZSIsImV4cG9ydHMiLCJSRVRFTlRJT05fTU9ERVMiLCJFTkNSWVBUSU9OX1RZUEVTIiwiTEVHQUxfSE9MRF9TVEFUVVMiLCJSRVRFTlRJT05fVkFMSURJVFlfVU5JVFMiLCJfZ2V0UmVxdWlyZVdpbGRjYXJkQ2FjaGUiLCJub2RlSW50ZXJvcCIsIldlYWtNYXAiLCJjYWNoZUJhYmVsSW50ZXJvcCIsImNhY2hlTm9kZUludGVyb3AiLCJvYmoiLCJfX2VzTW9kdWxlIiwiZGVmYXVsdCIsImNhY2hlIiwiaGFzIiwiZ2V0IiwibmV3T2JqIiwiaGFzUHJvcGVydHlEZXNjcmlwdG9yIiwiT2JqZWN0IiwiZGVmaW5lUHJvcGVydHkiLCJnZXRPd25Qcm9wZX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iamVjdCA9IE9iamVjdFxuICAgIHRoaXMuVmVyc2lvbklEID0gVmVyc2lvbklEXG4gICAgdGhpcy5NYXR Line truncated
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="node" />
/// <reference types="node" />
import * as fs from 'node:fs';
import * as stream from 'node:stream';
export { promises as fsp } from 'node:fs';
export declare const streamPromise: {
pipeline: typeof stream.pipeline.__promisify__;
};
export declare const fstat: typeof fs.fstat.__promisify__;
+24
View File
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var fs = _interopRequireWildcard(require("fs"), true);
var stream = _interopRequireWildcard(require("stream"), true);
var _util = require("util");
var _nodeFs = require("fs");
exports.fsp = _nodeFs.promises;
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// promise helper for stdlib
// TODO: use "node:fs/promise" directly after we stop testing on nodejs 12
const streamPromise = {
// node:stream/promises Added in: v15.0.0
pipeline: (0, _util.promisify)(stream.pipeline)
};
exports.streamPromise = streamPromise;
const fstat = (0, _util.promisify)(fs.fstat);
exports.fstat = fstat;
//#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QUEsSUFBQUQsTUFBQSxDQUFBRSx3QkFBQSxXQUFBQyxHQUFBLElBQUFYLEdBQUEsUUFBQVcsR0FBQSxrQkFBQUgsTUFBQSxDQUFBSSxTQUFBLENBQUFDLGNBQUEsQ0FBQUMsSUFBQSxDQUFBZCxHQUFBLEVBQUFXLEdBQUEsU0FBQUksSUFBQSxHQUFBUixxQkFBQSxHQUFBQyxNQUFBLENBQUFFLHdCQUFBLENBQUFWLEdBQUEsRUFBQVcsR0FBQSxjQUFBSSxJQUFBLEtBQUFBLElBQUEsQ0FBQVYsR0FBQSxJQUFBVSxJQUFBLENBQUFDLEdBQUEsS0FBQVIsTUFBQSxDQUFBQyxjQUFBLENBQUFILE1BQUEsRUFBQUssR0FBQSxFQUFBSSxJQUFBLFlBQUFULE1BQUEsQ0FBQUssR0FBQSxJQUFBWCxHQUFBLENBQUFXLEdBQUEsU0FBQUwsTUFBQSxDQUFBSixPQUFBLEdBQUFGLEdBQUEsTUFBQUcsS0FBQSxJQUFBQSxLQUFBLENBQUFhLEdBQUEsQ0FBQWhCLEdBQUEsRUFBQU0sTUFBQSxZQUFBQSxNQUFBO0FBUHpDOztBQU1BOztBQUVPLE1BQU1XLGFBQWEsR0FBRztFQUMzQjtFQUNBQyxRQUFRLEVBQUUsSUFBQUMsZUFBUyxFQUFDOUIsTUFBTSxDQUFDNkIsUUFBUTtBQUNyQyxDQUFDO0FBQUExQixPQUFBLENBQUF5QixhQUFBLEdBQUFBLGFBQUE7QUFFTSxNQUFNRyxLQUFLLEdBQUcsSUFBQUQsZUFBUyxFQUFDakMsRUFBRSxDQUFDa0MsS0FBSyxDQUFDO0FBQUE1QixPQUFBLENBQUE0QixLQUFBLEdBQUFBLEtBQUEifQ==
@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.callbackify = callbackify;
// wrapper an async function that support callback style API.
// It will preserve 'this'.
function callbackify(fn) {
return function () {
const args = [...arguments];
const callback = args.pop();
// If the last argument is a function, assume it's the callback.
if (typeof callback === 'function') {
return fn.apply(this, args).then(result => callback(null, result), err => callback(err));
}
return fn.apply(this, arguments);
};
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjYWxsYmFja2lmeSIsImZuIiwiYXJncyIsImFyZ3VtZW50cyIsImNhbGxiYWNrIiwicG9wIiwiYXBwbHkiLCJ0aGVuIiwicmVzdWx0IiwiZXJyIl0sInNvdXJjZXMiOlsiY2FsbGJhY2tpZnkuanMiXSwic291cmNlc0NvbnRlbnQiOlsiLy8gd3JhcHBlciBhbiBhc3luYyBmdW5jdGlvbiB0aGF0IHN1cHBvcnQgY2FsbGJhY2sgc3R5bGUgQVBJLlxuLy8gSXQgd2lsbCBwcmVzZXJ2ZSAndGhpcycuXG5leHBvcnQgZnVuY3Rpb24gY2FsbGJhY2tpZnkoZm4pIHtcbiAgcmV0dXJuIGZ1bmN0aW9uICgpIHtcbiAgICBjb25zdCBhcmdzID0gWy4uLmFyZ3VtZW50c11cbiAgICBjb25zdCBjYWxsYmFjayA9IGFyZ3MucG9wKClcblxuICAgIC8vIElmIHRoZSBsYXN0IGFyZ3VtZW50IGlzIGEgZnVuY3Rpb24sIGFzc3VtZSBpdCdzIHRoZSBjYWxsYmFjay5cbiAgICBpZiAodHlwZW9mIGNhbGxiYWNrID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICByZXR1cm4gZm4uYXBwbHkodGhpcywgYXJncykudGhlbihcbiAgICAgICAgKHJlc3VsdCkgPT4gY2FsbGJhY2sobnVsbCwgcmVzdWx0KSxcbiAgICAgICAgKGVycikgPT4gY2FsbGJhY2soZXJyKSxcbiAgICAgIClcbiAgICB9XG5cbiAgICByZXR1cm4gZm4uYXBwbHkodGhpcywgYXJndW1lbnRzKVxuICB9XG59XG4iXSwibWFwcGluZ3MiOiI7Ozs7OztBQUFBO0FBQ0E7QUFDTyxTQUFTQSxXQUFXQSxDQUFDQyxFQUFFLEVBQUU7RUFDOUIsT0FBTyxZQUFZO0lBQ2pCLE1BQU1DLElBQUksR0FBRyxDQUFDLEdBQUdDLFNBQVMsQ0FBQztJQUMzQixNQUFNQyxRQUFRLEdBQUdGLElBQUksQ0FBQ0csR0FBRyxDQUFDLENBQUM7O0lBRTNCO0lBQ0EsSUFBSSxPQUFPRCxRQUFRLEtBQUssVUFBVSxFQUFFO01BQ2xDLE9BQU9ILEVBQUUsQ0FBQ0ssS0FBSyxDQUFDLElBQUksRUFBRUosSUFBSSxDQUFDLENBQUNLLElBQUksQ0FDN0JDLE1BQU0sSUFBS0osUUFBUSxDQUFDLElBQUksRUFBRUksTUFBTSxDQUFDLEVBQ2pDQyxHQUFHLElBQUtMLFFBQVEsQ0FBQ0ssR0FBRyxDQUN2QixDQUFDO0lBQ0g7SUFFQSxPQUFPUixFQUFFLENBQUNLLEtBQUssQ0FBQyxJQUFJLEVBQUVILFNBQVMsQ0FBQztFQUNsQyxDQUFDO0FBQ0gifQ==
+359
View File
@@ -0,0 +1,359 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import * as http from 'node:http';
import * as https from 'node:https';
import * as stream from 'node:stream';
import { CredentialProvider } from "../CredentialProvider.js";
import type { SelectResults } from "../helpers.js";
import { CopyDestinationOptions, CopySourceOptions, LEGAL_HOLD_STATUS } from "../helpers.js";
import type { PostPolicyResult } from "../minio.js";
import { CopyConditions } from "./copy-conditions.js";
import { Extensions } from "./extensions.js";
import { PostPolicy } from "./post-policy.js";
import type { Region } from "./s3-endpoints.js";
import type { Binary, BucketItemFromList, BucketItemStat, BucketStream, BucketVersioningConfiguration, CopyObjectResult, EncryptionConfig, GetObjectLegalHoldOptions, GetObjectOpts, GetObjectRetentionOpts, IncompleteUploadedBucketItem, IRequest, ItemBucketMetadata, LifecycleConfig, LifeCycleConfigParam, ListObjectQueryOpts, ObjectInfo, ObjectLockInfo, ObjectMetaData, ObjectRetentionInfo, PreSignRequestParams, PutObjectLegalHoldOptions, RemoveObjectsParam, RemoveObjectsResponse, ReplicationConfig, ReplicationConfigOpts, RequestHeaders, ResultCallback, Retention, SelectOptions, StatObjectOpts, Tag, TaggingOpts, Tags, Transport, UploadedObjectInfo } from "./type.js";
import type { ListMultipartResult, UploadedPart } from "./xml-parser.js";
declare const requestOptionProperties: readonly ["agent", "ca", "cert", "ciphers", "clientCertEngine", "crl", "dhparam", "ecdhCurve", "family", "honorCipherOrder", "key", "passphrase", "pfx", "rejectUnauthorized", "secureOptions", "secureProtocol", "servername", "sessionIdContext"];
export interface ClientOptions {
endPoint: string;
accessKey?: string;
secretKey?: string;
useSSL?: boolean;
port?: number;
region?: Region;
transport?: Transport;
sessionToken?: string;
partSize?: number;
pathStyle?: boolean;
credentialsProvider?: CredentialProvider;
s3AccelerateEndpoint?: string;
transportAgent?: http.Agent;
}
export type RequestOption = Partial<IRequest> & {
method: string;
bucketName?: string;
objectName?: string;
query?: string;
pathStyle?: boolean;
};
export type NoResultCallback = (error: unknown) => void;
export interface MakeBucketOpt {
ObjectLocking?: boolean;
}
export interface RemoveOptions {
versionId?: string;
governanceBypass?: boolean;
forceDelete?: boolean;
}
export declare class TypedClient {
protected transport: Transport;
protected host: string;
protected port: number;
protected protocol: string;
protected accessKey: string;
protected secretKey: string;
protected sessionToken?: string;
protected userAgent: string;
protected anonymous: boolean;
protected pathStyle: boolean;
protected regionMap: Record<string, string>;
region?: string;
protected credentialsProvider?: CredentialProvider;
partSize: number;
protected overRidePartSize?: boolean;
protected maximumPartSize: number;
protected maxObjectSize: number;
enableSHA256: boolean;
protected s3AccelerateEndpoint?: string;
protected reqOptions: Record<string, unknown>;
protected transportAgent: http.Agent;
private readonly clientExtensions;
constructor(params: ClientOptions);
/**
* Minio extensions that aren't necessary present for Amazon S3 compatible storage servers
*/
get extensions(): Extensions;
/**
* @param endPoint - valid S3 acceleration end point
*/
setS3TransferAccelerate(endPoint: string): void;
/**
* Sets the supported request options.
*/
setRequestOptions(options: Pick<https.RequestOptions, (typeof requestOptionProperties)[number]>): void;
/**
* This is s3 Specific and does not hold validity in any other Object storage.
*/
private getAccelerateEndPointIfSet;
/**
* Set application specific information.
* Generates User-Agent in the following style.
* MinIO (OS; ARCH) LIB/VER APP/VER
*/
setAppInfo(appName: string, appVersion: string): void;
/**
* returns options object that can be used with http.request()
* Takes care of constructing virtual-host-style or path-style hostname
*/
protected getRequestOptions(opts: RequestOption & {
region: string;
}): IRequest & {
host: string;
headers: Record<string, string>;
};
setCredentialsProvider(credentialsProvider: CredentialProvider): Promise<void>;
private checkAndRefreshCreds;
private logStream?;
/**
* log the request, response, error
*/
private logHTTP;
/**
* Enable tracing
*/
traceOn(stream?: stream.Writable): void;
/**
* Disable tracing
*/
traceOff(): void;
/**
* makeRequest is the primitive used by the apis for making S3 requests.
* payload can be empty string in case of no payload.
* statusCode is the expected statusCode. If response.statusCode does not match
* we parse the XML error and call the callback with the error message.
*
* A valid region is passed by the calls - listBuckets, makeBucket and getBucketRegion.
*
* @internal
*/
makeRequestAsync(options: RequestOption, payload?: Binary, expectedCodes?: number[], region?: string): Promise<http.IncomingMessage>;
/**
* new request with promise
*
* No need to drain response, response body is not valid
*/
makeRequestAsyncOmit(options: RequestOption, payload?: Binary, statusCodes?: number[], region?: string): Promise<Omit<http.IncomingMessage, 'on'>>;
/**
* makeRequestStream will be used directly instead of makeRequest in case the payload
* is available as a stream. for ex. putObject
*
* @internal
*/
makeRequestStreamAsync(options: RequestOption, body: stream.Readable | Binary, sha256sum: string, statusCodes: number[], region: string): Promise<http.IncomingMessage>;
/**
* gets the region of the bucket
*
* @param bucketName
*
* @internal
*/
protected getBucketRegionAsync(bucketName: string): Promise<string>;
/**
* makeRequest is the primitive used by the apis for making S3 requests.
* payload can be empty string in case of no payload.
* statusCode is the expected statusCode. If response.statusCode does not match
* we parse the XML error and call the callback with the error message.
* A valid region is passed by the calls - listBuckets, makeBucket and
* getBucketRegion.
*
* @deprecated use `makeRequestAsync` instead
*/
makeRequest(options: RequestOption, payload: Binary | undefined, expectedCodes: number[] | undefined, region: string | undefined, returnResponse: boolean, cb: (cb: unknown, result: http.IncomingMessage) => void): void;
/**
* makeRequestStream will be used directly instead of makeRequest in case the payload
* is available as a stream. for ex. putObject
*
* @deprecated use `makeRequestStreamAsync` instead
*/
makeRequestStream(options: RequestOption, stream: stream.Readable | Buffer, sha256sum: string, statusCodes: number[], region: string, returnResponse: boolean, cb: (cb: unknown, result: http.IncomingMessage) => void): void;
/**
* @deprecated use `getBucketRegionAsync` instead
*/
getBucketRegion(bucketName: string, cb: (err: unknown, region: string) => void): Promise<void>;
/**
* Creates the bucket `bucketName`.
*
*/
makeBucket(bucketName: string, region?: Region, makeOpts?: MakeBucketOpt): Promise<void>;
/**
* To check if a bucket already exists.
*/
bucketExists(bucketName: string): Promise<boolean>;
removeBucket(bucketName: string): Promise<void>;
/**
* @deprecated use promise style API
*/
removeBucket(bucketName: string, callback: NoResultCallback): void;
/**
* Callback is called with readable stream of the object content.
*/
getObject(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise<stream.Readable>;
/**
* Callback is called with readable stream of the partial object content.
* @param bucketName
* @param objectName
* @param offset
* @param length - length of the object that will be read in the stream (optional, if not specified we read the rest of the file from the offset)
* @param getOpts
*/
getPartialObject(bucketName: string, objectName: string, offset: number, length?: number, getOpts?: GetObjectOpts): Promise<stream.Readable>;
/**
* download object content to a file.
* This method will create a temp file named `${filename}.${base64(etag)}.part.minio` when downloading.
*
* @param bucketName - name of the bucket
* @param objectName - name of the object
* @param filePath - path to which the object data will be written to
* @param getOpts - Optional object get option
*/
fGetObject(bucketName: string, objectName: string, filePath: string, getOpts?: GetObjectOpts): Promise<void>;
/**
* Stat information of the object.
*/
statObject(bucketName: string, objectName: string, statOpts?: StatObjectOpts): Promise<BucketItemStat>;
removeObject(bucketName: string, objectName: string, removeOpts?: RemoveOptions): Promise<void>;
listIncompleteUploads(bucket: string, prefix: string, recursive: boolean): BucketStream<IncompleteUploadedBucketItem>;
/**
* Called by listIncompleteUploads to fetch a batch of incomplete uploads.
*/
listIncompleteUploadsQuery(bucketName: string, prefix: string, keyMarker: string, uploadIdMarker: string, delimiter: string): Promise<ListMultipartResult>;
/**
* Initiate a new multipart upload.
* @internal
*/
initiateNewMultipartUpload(bucketName: string, objectName: string, headers: RequestHeaders): Promise<string>;
/**
* Internal Method to abort a multipart upload request in case of any errors.
*
* @param bucketName - Bucket Name
* @param objectName - Object Name
* @param uploadId - id of a multipart upload to cancel during compose object sequence.
*/
abortMultipartUpload(bucketName: string, objectName: string, uploadId: string): Promise<void>;
findUploadId(bucketName: string, objectName: string): Promise<string | undefined>;
/**
* this call will aggregate the parts on the server into a single object.
*/
completeMultipartUpload(bucketName: string, objectName: string, uploadId: string, etags: {
part: number;
etag?: string;
}[]): Promise<{
etag: string;
versionId: string | null;
}>;
/**
* Get part-info of all parts of an incomplete upload specified by uploadId.
*/
protected listParts(bucketName: string, objectName: string, uploadId: string): Promise<UploadedPart[]>;
/**
* Called by listParts to fetch a batch of part-info
*/
private listPartsQuery;
listBuckets(): Promise<BucketItemFromList[]>;
/**
* Calculate part size given the object size. Part size will be atleast this.partSize
*/
calculatePartSize(size: number): number;
/**
* Uploads the object using contents from a file
*/
fPutObject(bucketName: string, objectName: string, filePath: string, metaData?: ObjectMetaData): Promise<UploadedObjectInfo>;
/**
* Uploading a stream, "Buffer" or "string".
* It's recommended to pass `size` argument with stream.
*/
putObject(bucketName: string, objectName: string, stream: stream.Readable | Buffer | string, size?: number, metaData?: ItemBucketMetadata): Promise<UploadedObjectInfo>;
/**
* method to upload buffer in one call
* @private
*/
private uploadBuffer;
/**
* upload stream with MultipartUpload
* @private
*/
private uploadStream;
removeBucketReplication(bucketName: string): Promise<void>;
removeBucketReplication(bucketName: string, callback: NoResultCallback): void;
setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): void;
setBucketReplication(bucketName: string, replicationConfig: ReplicationConfigOpts): Promise<void>;
getBucketReplication(bucketName: string): void;
getBucketReplication(bucketName: string): Promise<ReplicationConfig>;
getObjectLegalHold(bucketName: string, objectName: string, getOpts?: GetObjectLegalHoldOptions, callback?: ResultCallback<LEGAL_HOLD_STATUS>): Promise<LEGAL_HOLD_STATUS>;
setObjectLegalHold(bucketName: string, objectName: string, setOpts?: PutObjectLegalHoldOptions): void;
/**
* Get Tags associated with a Bucket
*/
getBucketTagging(bucketName: string): Promise<Tag[]>;
/**
* Get the tags associated with a bucket OR an object
*/
getObjectTagging(bucketName: string, objectName: string, getOpts?: GetObjectOpts): Promise<Tag[]>;
/**
* Set the policy on a bucket or an object prefix.
*/
setBucketPolicy(bucketName: string, policy: string): Promise<void>;
/**
* Get the policy on a bucket or an object prefix.
*/
getBucketPolicy(bucketName: string): Promise<string>;
putObjectRetention(bucketName: string, objectName: string, retentionOpts?: Retention): Promise<void>;
getObjectLockConfig(bucketName: string, callback: ResultCallback<ObjectLockInfo>): void;
getObjectLockConfig(bucketName: string): void;
getObjectLockConfig(bucketName: string): Promise<ObjectLockInfo>;
setObjectLockConfig(bucketName: string, lockConfigOpts: Omit<ObjectLockInfo, 'objectLockEnabled'>): void;
setObjectLockConfig(bucketName: string, lockConfigOpts: Omit<ObjectLockInfo, 'objectLockEnabled'>): Promise<void>;
getBucketVersioning(bucketName: string): Promise<BucketVersioningConfiguration>;
setBucketVersioning(bucketName: string, versionConfig: BucketVersioningConfiguration): Promise<void>;
private setTagging;
private removeTagging;
setBucketTagging(bucketName: string, tags: Tags): Promise<void>;
removeBucketTagging(bucketName: string): Promise<void>;
setObjectTagging(bucketName: string, objectName: string, tags: Tags, putOpts?: TaggingOpts): Promise<void>;
removeObjectTagging(bucketName: string, objectName: string, removeOpts: TaggingOpts): Promise<void>;
selectObjectContent(bucketName: string, objectName: string, selectOpts: SelectOptions): Promise<SelectResults | undefined>;
private applyBucketLifecycle;
removeBucketLifecycle(bucketName: string): Promise<void>;
setBucketLifecycle(bucketName: string, lifeCycleConfig: LifeCycleConfigParam): Promise<void>;
getBucketLifecycle(bucketName: string): Promise<LifecycleConfig | null>;
setBucketEncryption(bucketName: string, encryptionConfig?: EncryptionConfig): Promise<void>;
getBucketEncryption(bucketName: string): Promise<any>;
removeBucketEncryption(bucketName: string): Promise<void>;
getObjectRetention(bucketName: string, objectName: string, getOpts?: GetObjectRetentionOpts): Promise<ObjectRetentionInfo | null | undefined>;
removeObjects(bucketName: string, objectsList: RemoveObjectsParam): Promise<RemoveObjectsResponse[]>;
removeIncompleteUpload(bucketName: string, objectName: string): Promise<void>;
private copyObjectV1;
private copyObjectV2;
copyObject(source: CopySourceOptions, dest: CopyDestinationOptions): Promise<CopyObjectResult>;
copyObject(targetBucketName: string, targetObjectName: string, sourceBucketNameAndObjectName: string, conditions?: CopyConditions): Promise<CopyObjectResult>;
uploadPart(partConfig: {
bucketName: string;
objectName: string;
uploadID: string;
partNumber: number;
headers: RequestHeaders;
}, payload?: Binary): Promise<{
etag: string;
key: string;
part: number;
}>;
composeObject(destObjConfig: CopyDestinationOptions, sourceObjList: CopySourceOptions[]): Promise<boolean | {
etag: string;
versionId: string | null;
} | Promise<void> | CopyObjectResult>;
presignedUrl(method: string, bucketName: string, objectName: string, expires?: number | PreSignRequestParams | undefined, reqParams?: PreSignRequestParams | Date, requestDate?: Date): Promise<string>;
presignedGetObject(bucketName: string, objectName: string, expires?: number, respHeaders?: PreSignRequestParams | Date, requestDate?: Date): Promise<string>;
presignedPutObject(bucketName: string, objectName: string, expires?: number): Promise<string>;
newPostPolicy(): PostPolicy;
presignedPostPolicy(postPolicy: PostPolicy): Promise<PostPolicyResult>;
listObjectsQuery(bucketName: string, prefix?: string, marker?: string, listQueryOpts?: ListObjectQueryOpts): Promise<{
objects: ObjectInfo[];
isTruncated?: boolean | undefined;
nextMarker?: string | undefined;
versionIdMarker?: string | undefined;
}>;
listObjects(bucketName: string, prefix?: string, recursive?: boolean, listOpts?: ListObjectQueryOpts | undefined): BucketStream<ObjectInfo>;
}
export {};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,10 @@
export declare class CopyConditions {
modified: string;
unmodified: string;
matchETag: string;
matchETagExcept: string;
setModified(date: Date): void;
setUnmodified(date: Date): void;
setMatchETag(etag: string): void;
setMatchETagExcept(etag: string): void;
}
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
class CopyConditions {
modified = '';
unmodified = '';
matchETag = '';
matchETagExcept = '';
setModified(date) {
if (!(date instanceof Date)) {
throw new TypeError('date must be of type Date');
}
this.modified = date.toUTCString();
}
setUnmodified(date) {
if (!(date instanceof Date)) {
throw new TypeError('date must be of type Date');
}
this.unmodified = date.toUTCString();
}
setMatchETag(etag) {
this.matchETag = etag;
}
setMatchETagExcept(etag) {
this.matchETagExcept = etag;
}
}
exports.CopyConditions = CopyConditions;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDb3B5Q29uZGl0aW9ucyIsIm1vZGlmaWVkIiwidW5tb2RpZmllZCIsIm1hdGNoRVRhZyIsIm1hdGNoRVRhZ0V4Y2VwdCIsInNldE1vZGlmaWVkIiwiZGF0ZSIsIkRhdGUiLCJUeXBlRXJyb3IiLCJ0b1VUQ1N0cmluZyIsInNldFVubW9kaWZpZWQiLCJzZXRNYXRjaEVUYWciLCJldGFnIiwic2V0TWF0Y2hFVGFnRXhjZXB0IiwiZXhwb3J0cyJdLCJzb3VyY2VzIjpbImNvcHktY29uZGl0aW9ucy50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgY2xhc3MgQ29weUNvbmRpdGlvbnMge1xuICBwdWJsaWMgbW9kaWZpZWQgPSAnJ1xuICBwdWJsaWMgdW5tb2RpZmllZCA9ICcnXG4gIHB1YmxpYyBtYXRjaEVUYWcgPSAnJ1xuICBwdWJsaWMgbWF0Y2hFVGFnRXhjZXB0ID0gJydcblxuICBzZXRNb2RpZmllZChkYXRlOiBEYXRlKTogdm9pZCB7XG4gICAgaWYgKCEoZGF0ZSBpbnN0YW5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sRUFBUTtJQUM5QixJQUFJLEVBQUVBLElBQUksWUFBWUMsSUFBSSxDQUFDLEVBQUU7TUFDM0IsTUFBTSxJQUFJQyxTQUFTLENBQUMsMkJBQTJCLENBQUM7SUFDbEQ7SUFFQSxJQUFJLENBQUNOLFVBQVUsR0FBR0ksSUFBSSxDQUFDRyxXQUFXLENBQUMsQ0FBQztFQUN0QztFQUVBRSxZQUFZQSxDQUFDQyxJQUFZLEVBQVE7SUFDL0IsSUFBSSxDQUFDVCxTQUFTLEdBQUdTLElBQUk7RUFDdkI7RUFFQUMsa0JBQWtCQSxDQUFDRCxJQUFZLEVBQVE7SUFDckMsSUFBSSxDQUFDUixlQUFlLEdBQUdRLElBQUk7RUFDN0I7QUFDRjtBQUFDRSxPQUFBLENBQUFkLGNBQUEsR0FBQUEsY0FBQSJ9
@@ -0,0 +1,18 @@
import type { TypedClient } from "./client.js";
import type { BucketItemWithMetadata, BucketStream } from "./type.js";
export declare class Extensions {
private readonly client;
constructor(client: TypedClient);
/**
* List the objects in the bucket using S3 ListObjects V2 With Metadata
*
* @param bucketName - name of the bucket
* @param prefix - the prefix of the objects that should be listed (optional, default `''`)
* @param recursive - `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`)
* @param startAfter - Specifies the key to start after when listing objects in a bucket. (optional, default `''`)
* @returns stream emitting the objects in the bucket, the object is of the format:
*/
listObjectsV2WithMetadata(bucketName: string, prefix?: string, recursive?: boolean, startAfter?: string): BucketStream<BucketItemWithMetadata>;
private listObjectsV2WithMetadataGen;
private listObjectsV2WithMetadataQuery;
}
+122
View File
@@ -0,0 +1,122 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var stream = _interopRequireWildcard(require("stream"), true);
var errors = _interopRequireWildcard(require("../errors.js"), true);
var _helper = require("./helper.js");
var _response = require("./response.js");
var _xmlParser = require("./xml-parser.js");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2020 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class Extensions {
constructor(client) {
this.client = client;
}
/**
* List the objects in the bucket using S3 ListObjects V2 With Metadata
*
* @param bucketName - name of the bucket
* @param prefix - the prefix of the objects that should be listed (optional, default `''`)
* @param recursive - `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`)
* @param startAfter - Specifies the key to start after when listing objects in a bucket. (optional, default `''`)
* @returns stream emitting the objects in the bucket, the object is of the format:
*/
listObjectsV2WithMetadata(bucketName, prefix, recursive, startAfter) {
if (prefix === undefined) {
prefix = '';
}
if (recursive === undefined) {
recursive = false;
}
if (startAfter === undefined) {
startAfter = '';
}
if (!(0, _helper.isValidBucketName)(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!(0, _helper.isValidPrefix)(prefix)) {
throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`);
}
if (!(0, _helper.isString)(prefix)) {
throw new TypeError('prefix should be of type "string"');
}
if (!(0, _helper.isBoolean)(recursive)) {
throw new TypeError('recursive should be of type "boolean"');
}
if (!(0, _helper.isString)(startAfter)) {
throw new TypeError('startAfter should be of type "string"');
}
// if recursive is false set delimiter to '/'
const delimiter = recursive ? '' : '/';
return stream.Readable.from(this.listObjectsV2WithMetadataGen(bucketName, prefix, delimiter, startAfter), {
objectMode: true
});
}
async *listObjectsV2WithMetadataGen(bucketName, prefix, delimiter, startAfter) {
let ended = false;
let continuationToken = '';
do {
const result = await this.listObjectsV2WithMetadataQuery(bucketName, prefix, continuationToken, delimiter, startAfter);
ended = !result.isTruncated;
continuationToken = result.nextContinuationToken;
for (const obj of result.objects) {
yield obj;
}
} while (!ended);
}
async listObjectsV2WithMetadataQuery(bucketName, prefix, continuationToken, delimiter, startAfter) {
const queries = [];
// Call for listing objects v2 API
queries.push(`list-type=2`);
queries.push(`encoding-type=url`);
// escape every value in query string, except maxKeys
queries.push(`prefix=${(0, _helper.uriEscape)(prefix)}`);
queries.push(`delimiter=${(0, _helper.uriEscape)(delimiter)}`);
queries.push(`metadata=true`);
if (continuationToken) {
continuationToken = (0, _helper.uriEscape)(continuationToken);
queries.push(`continuation-token=${continuationToken}`);
}
// Set start-after
if (startAfter) {
startAfter = (0, _helper.uriEscape)(startAfter);
queries.push(`start-after=${startAfter}`);
}
queries.push(`max-keys=1000`);
queries.sort();
let query = '';
if (queries.length > 0) {
query = `${queries.join('&')}`;
}
const method = 'GET';
const res = await this.client.makeRequestAsync({
method,
bucketName,
query
});
return (0, _xmlParser.parseListObjectsV2WithMetadata)(await (0, _response.readAsString)(res));
}
}
exports.Extensions = Extensions;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2Z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ICAgICB0aHJvdyBuZXcgZXJyb3JzLkludmFsaWRCdWNrZXROYW1lRXJyb3IoJ0ludmFsaWQgYnVja2V0IG5hbWU6ICcgKyBidWNrZXROYW1lKVxuICAgIH1cbiAgICBpZiAoIWlzVmFsaWRQcmVmaXgocHJlZml4KSkge1xuICAgICAgdGhyb3cgbmV3IGVycm9ycy5JbnZhbGlkUHJlZml4RXJyb3IoYEludmFsaWQgcHJlZml4IDogJHtwcmVmaXh9YClcbiAgICB9XG4gICAgaWYgKCFpc1N0cmluZyhwcmVmaXgpKSB7XG4gICAgICB0aHJvdyBuZXcgVHlwZUVycm9yKCdwcmVmaXggc2hvdWxkIGJlIG9mIHR5cGUgXCJzdHJpbmdcIicpXG4gICAgfVxuICAgIGlmICghaXNCb29sZWFuKHJlY3Vyc2l2ZSkpIHtcbiAgICAgIHRocm93IG5ldyBUeXBlRXJyb3IoJ3JlY3Vyc2l2ZSBzaG91bGQgYmUgb2YgdHlwZSBcImJvb2xlYW5cIicpXG4gICAgfVxuICAgIGlmICghaXNTdHJpbmcoc3RhcnRBZnRlcikpIHtcbiAgICAgIHRocm93IG5ldyBUeXBlRXJyb3IoJ3N0YXJ0QWZ0ZXI Line truncated
+173
View File
@@ -0,0 +1,173 @@
/// <reference types="node" />
/// <reference types="node" />
import * as stream from 'node:stream';
import _ from 'lodash';
import type { Binary, Encryption, ObjectMetaData, RequestHeaders, ResponseHeader } from "./type.js";
export declare function hashBinary(buf: Buffer, enableSHA256: boolean): {
md5sum: string;
sha256sum: string;
};
export declare function uriEscape(uriStr: string): string;
export declare function uriResourceEscape(string: string): string;
export declare function getScope(region: string, date: Date, serviceName?: string): string;
/**
* isAmazonEndpoint - true if endpoint is 's3.amazonaws.com' or 's3.cn-north-1.amazonaws.com.cn'
*/
export declare function isAmazonEndpoint(endpoint: string): boolean;
/**
* isVirtualHostStyle - verify if bucket name is support with virtual
* hosts. bucketNames with periods should be always treated as path
* style if the protocol is 'https:', this is due to SSL wildcard
* limitation. For all other buckets and Amazon S3 endpoint we will
* default to virtual host style.
*/
export declare function isVirtualHostStyle(endpoint: string, protocol: string, bucket: string, pathStyle: boolean): boolean;
export declare function isValidIP(ip: string): boolean;
/**
* @returns if endpoint is valid domain.
*/
export declare function isValidEndpoint(endpoint: string): boolean;
/**
* @returns if input host is a valid domain.
*/
export declare function isValidDomain(host: string): boolean;
/**
* Probes contentType using file extensions.
*
* @example
* ```
* // return 'image/png'
* probeContentType('file.png')
* ```
*/
export declare function probeContentType(path: string): string;
/**
* is input port valid.
*/
export declare function isValidPort(port: unknown): port is number;
export declare function isValidBucketName(bucket: unknown): boolean;
/**
* check if objectName is a valid object name
*/
export declare function isValidObjectName(objectName: unknown): boolean;
/**
* check if prefix is valid
*/
export declare function isValidPrefix(prefix: unknown): prefix is string;
/**
* check if typeof arg number
*/
export declare function isNumber(arg: unknown): arg is number;
export type AnyFunction = (...args: any[]) => any;
/**
* check if typeof arg function
*/
export declare function isFunction(arg: unknown): arg is AnyFunction;
/**
* check if typeof arg string
*/
export declare function isString(arg: unknown): arg is string;
/**
* check if typeof arg object
*/
export declare function isObject(arg: unknown): arg is object;
/**
* check if object is readable stream
*/
export declare function isReadableStream(arg: unknown): arg is stream.Readable;
/**
* check if arg is boolean
*/
export declare function isBoolean(arg: unknown): arg is boolean;
export declare function isEmpty(o: unknown): o is null | undefined;
export declare function isEmptyObject(o: Record<string, unknown>): boolean;
export declare function isDefined<T>(o: T): o is Exclude<T, null | undefined>;
/**
* check if arg is a valid date
*/
export declare function isValidDate(arg: unknown): arg is Date;
/**
* Create a Date string with format: 'YYYYMMDDTHHmmss' + Z
*/
export declare function makeDateLong(date?: Date): string;
/**
* Create a Date string with format: 'YYYYMMDD'
*/
export declare function makeDateShort(date?: Date): string;
/**
* pipesetup sets up pipe() from left to right os streams array
* pipesetup will also make sure that error emitted at any of the upstream Stream
* will be emitted at the last stream. This makes error handling simple
*/
export declare function pipesetup(...streams: [stream.Readable, ...stream.Duplex[], stream.Writable]): stream.Readable | stream.Duplex | stream.Writable;
/**
* return a Readable stream that emits data
*/
export declare function readableStream(data: unknown): stream.Readable;
/**
* Process metadata to insert appropriate value to `content-type` attribute
*/
export declare function insertContentType(metaData: ObjectMetaData, filePath: string): ObjectMetaData;
/**
* Function prepends metadata with the appropriate prefix if it is not already on
*/
export declare function prependXAMZMeta(metaData?: ObjectMetaData): RequestHeaders;
/**
* Checks if it is a valid header according to the AmazonS3 API
*/
export declare function isAmzHeader(key: string): boolean;
/**
* Checks if it is a supported Header
*/
export declare function isSupportedHeader(key: string): boolean;
/**
* Checks if it is a storage header
*/
export declare function isStorageClassHeader(key: string): boolean;
export declare function extractMetadata(headers: ResponseHeader): _.Dictionary<string>;
export declare function getVersionId(headers?: ResponseHeader): string | null;
export declare function getSourceVersionId(headers?: ResponseHeader): string | null;
export declare function sanitizeETag(etag?: string): string;
export declare function toMd5(payload: Binary): string;
export declare function toSha256(payload: Binary): string;
/**
* toArray returns a single element array with param being the element,
* if param is just a string, and returns 'param' back if it is an array
* So, it makes sure param is always an array
*/
export declare function toArray<T = unknown>(param: T | T[]): Array<T>;
export declare function sanitizeObjectKey(objectName: string): string;
export declare function sanitizeSize(size?: string): number | undefined;
export declare const PART_CONSTRAINTS: {
ABS_MIN_PART_SIZE: number;
MIN_PART_SIZE: number;
MAX_PARTS_COUNT: number;
MAX_PART_SIZE: number;
MAX_SINGLE_PUT_OBJECT_SIZE: number;
MAX_MULTIPART_PUT_OBJECT_SIZE: number;
};
/**
* Return Encryption headers
* @param encConfig
* @returns an object with key value pairs that can be used in headers.
*/
export declare function getEncryptionHeaders(encConfig: Encryption): RequestHeaders;
export declare function partsRequired(size: number): number;
/**
* calculateEvenSplits - computes splits for a source and returns
* start and end index slices. Splits happen evenly to be sure that no
* part is less than 5MiB, as that could fail the multipart request if
* it is not the last part.
*/
export declare function calculateEvenSplits<T extends {
Start?: number;
}>(size: number, objInfo: T): {
startIndex: number[];
objInfo: T;
endIndex: number[];
} | null;
export declare function parseXml(xml: string): any;
/**
* get content size of object content to upload
*/
export declare function getContentLength(s: stream.Readable | Buffer | string): Promise<number | null>;
+602
View File
@@ -0,0 +1,602 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.calculateEvenSplits = calculateEvenSplits;
exports.extractMetadata = extractMetadata;
exports.getContentLength = getContentLength;
exports.getEncryptionHeaders = getEncryptionHeaders;
exports.getScope = getScope;
exports.getSourceVersionId = getSourceVersionId;
exports.getVersionId = getVersionId;
exports.hashBinary = hashBinary;
exports.insertContentType = insertContentType;
exports.isAmazonEndpoint = isAmazonEndpoint;
exports.isAmzHeader = isAmzHeader;
exports.isBoolean = isBoolean;
exports.isDefined = isDefined;
exports.isEmpty = isEmpty;
exports.isEmptyObject = isEmptyObject;
exports.isFunction = isFunction;
exports.isNumber = isNumber;
exports.isObject = isObject;
exports.isReadableStream = isReadableStream;
exports.isStorageClassHeader = isStorageClassHeader;
exports.isString = isString;
exports.isSupportedHeader = isSupportedHeader;
exports.isValidBucketName = isValidBucketName;
exports.isValidDate = isValidDate;
exports.isValidDomain = isValidDomain;
exports.isValidEndpoint = isValidEndpoint;
exports.isValidIP = isValidIP;
exports.isValidObjectName = isValidObjectName;
exports.isValidPort = isValidPort;
exports.isValidPrefix = isValidPrefix;
exports.isVirtualHostStyle = isVirtualHostStyle;
exports.makeDateLong = makeDateLong;
exports.makeDateShort = makeDateShort;
exports.parseXml = parseXml;
exports.partsRequired = partsRequired;
exports.pipesetup = pipesetup;
exports.prependXAMZMeta = prependXAMZMeta;
exports.probeContentType = probeContentType;
exports.readableStream = readableStream;
exports.sanitizeETag = sanitizeETag;
exports.sanitizeObjectKey = sanitizeObjectKey;
exports.sanitizeSize = sanitizeSize;
exports.toArray = toArray;
exports.toMd5 = toMd5;
exports.toSha256 = toSha256;
exports.uriEscape = uriEscape;
exports.uriResourceEscape = uriResourceEscape;
var crypto = _interopRequireWildcard(require("crypto"), true);
var stream = _interopRequireWildcard(require("stream"), true);
var _fastXmlParser = require("fast-xml-parser");
var _ipaddr = require("ipaddr.js");
var _lodash = require("lodash");
var mime = _interopRequireWildcard(require("mime-types"), true);
var _async = require("./async.js");
var _type = require("./type.js");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const MetaDataHeaderPrefix = 'x-amz-meta-';
function hashBinary(buf, enableSHA256) {
let sha256sum = '';
if (enableSHA256) {
sha256sum = crypto.createHash('sha256').update(buf).digest('hex');
}
const md5sum = crypto.createHash('md5').update(buf).digest('base64');
return {
md5sum,
sha256sum
};
}
// S3 percent-encodes some extra non-standard characters in a URI . So comply with S3.
const encodeAsHex = c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`;
function uriEscape(uriStr) {
return encodeURIComponent(uriStr).replace(/[!'()*]/g, encodeAsHex);
}
function uriResourceEscape(string) {
return uriEscape(string).replace(/%2F/g, '/');
}
function getScope(region, date, serviceName = 's3') {
return `${makeDateShort(date)}/${region}/${serviceName}/aws4_request`;
}
/**
* isAmazonEndpoint - true if endpoint is 's3.amazonaws.com' or 's3.cn-north-1.amazonaws.com.cn'
*/
function isAmazonEndpoint(endpoint) {
return endpoint === 's3.amazonaws.com' || endpoint === 's3.cn-north-1.amazonaws.com.cn';
}
/**
* isVirtualHostStyle - verify if bucket name is support with virtual
* hosts. bucketNames with periods should be always treated as path
* style if the protocol is 'https:', this is due to SSL wildcard
* limitation. For all other buckets and Amazon S3 endpoint we will
* default to virtual host style.
*/
function isVirtualHostStyle(endpoint, protocol, bucket, pathStyle) {
if (protocol === 'https:' && bucket.includes('.')) {
return false;
}
return isAmazonEndpoint(endpoint) || !pathStyle;
}
function isValidIP(ip) {
return _ipaddr.isValid(ip);
}
/**
* @returns if endpoint is valid domain.
*/
function isValidEndpoint(endpoint) {
return isValidDomain(endpoint) || isValidIP(endpoint);
}
/**
* @returns if input host is a valid domain.
*/
function isValidDomain(host) {
if (!isString(host)) {
return false;
}
// See RFC 1035, RFC 3696.
if (host.length === 0 || host.length > 255) {
return false;
}
// Host cannot start or end with a '-'
if (host[0] === '-' || host.slice(-1) === '-') {
return false;
}
// Host cannot start or end with a '_'
if (host[0] === '_' || host.slice(-1) === '_') {
return false;
}
// Host cannot start with a '.'
if (host[0] === '.') {
return false;
}
const nonAlphaNumerics = '`~!@#$%^&*()+={}[]|\\"\';:><?/';
// All non alphanumeric characters are invalid.
for (const char of nonAlphaNumerics) {
if (host.includes(char)) {
return false;
}
}
// No need to regexp match, since the list is non-exhaustive.
// We let it be valid and fail later.
return true;
}
/**
* Probes contentType using file extensions.
*
* @example
* ```
* // return 'image/png'
* probeContentType('file.png')
* ```
*/
function probeContentType(path) {
let contentType = mime.lookup(path);
if (!contentType) {
contentType = 'application/octet-stream';
}
return contentType;
}
/**
* is input port valid.
*/
function isValidPort(port) {
// Convert string port to number if needed
const portNum = typeof port === 'string' ? parseInt(port, 10) : port;
// verify if port is a valid number
if (!isNumber(portNum) || isNaN(portNum)) {
return false;
}
// port `0` is valid and special case
return 0 <= portNum && portNum <= 65535;
}
function isValidBucketName(bucket) {
if (!isString(bucket)) {
return false;
}
// bucket length should be less than and no more than 63
// characters long.
if (bucket.length < 3 || bucket.length > 63) {
return false;
}
// bucket with successive periods is invalid.
if (bucket.includes('..')) {
return false;
}
// bucket cannot have ip address style.
if (/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/.test(bucket)) {
return false;
}
// bucket should begin with alphabet/number and end with alphabet/number,
// with alphabet/number/.- in the middle.
if (/^[a-z0-9][a-z0-9.-]+[a-z0-9]$/.test(bucket)) {
return true;
}
return false;
}
/**
* check if objectName is a valid object name
*/
function isValidObjectName(objectName) {
if (!isValidPrefix(objectName)) {
return false;
}
return objectName.length !== 0;
}
/**
* check if prefix is valid
*/
function isValidPrefix(prefix) {
if (!isString(prefix)) {
return false;
}
if (prefix.length > 1024) {
return false;
}
return true;
}
/**
* check if typeof arg number
*/
function isNumber(arg) {
return typeof arg === 'number';
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
/**
* check if typeof arg function
*/
function isFunction(arg) {
return typeof arg === 'function';
}
/**
* check if typeof arg string
*/
function isString(arg) {
return typeof arg === 'string';
}
/**
* check if typeof arg object
*/
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
/**
* check if object is readable stream
*/
function isReadableStream(arg) {
// eslint-disable-next-line @typescript-eslint/unbound-method
return isObject(arg) && isFunction(arg._read);
}
/**
* check if arg is boolean
*/
function isBoolean(arg) {
return typeof arg === 'boolean';
}
function isEmpty(o) {
return _lodash.isEmpty(o);
}
function isEmptyObject(o) {
return Object.values(o).filter(x => x !== undefined).length !== 0;
}
function isDefined(o) {
return o !== null && o !== undefined;
}
/**
* check if arg is a valid date
*/
function isValidDate(arg) {
// @ts-expect-error checknew Date(Math.NaN)
return arg instanceof Date && !isNaN(arg);
}
/**
* Create a Date string with format: 'YYYYMMDDTHHmmss' + Z
*/
function makeDateLong(date) {
date = date || new Date();
// Gives format like: '2017-08-07T16:28:59.889Z'
const s = date.toISOString();
return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 13) + s.slice(14, 16) + s.slice(17, 19) + 'Z';
}
/**
* Create a Date string with format: 'YYYYMMDD'
*/
function makeDateShort(date) {
date = date || new Date();
// Gives format like: '2017-08-07T16:28:59.889Z'
const s = date.toISOString();
return s.slice(0, 4) + s.slice(5, 7) + s.slice(8, 10);
}
/**
* pipesetup sets up pipe() from left to right os streams array
* pipesetup will also make sure that error emitted at any of the upstream Stream
* will be emitted at the last stream. This makes error handling simple
*/
function pipesetup(...streams) {
// @ts-expect-error ts can't narrow this
return streams.reduce((src, dst) => {
src.on('error', err => dst.emit('error', err));
return src.pipe(dst);
});
}
/**
* return a Readable stream that emits data
*/
function readableStream(data) {
const s = new stream.Readable();
s._read = () => {};
s.push(data);
s.push(null);
return s;
}
/**
* Process metadata to insert appropriate value to `content-type` attribute
*/
function insertContentType(metaData, filePath) {
// check if content-type attribute present in metaData
for (const key in metaData) {
if (key.toLowerCase() === 'content-type') {
return metaData;
}
}
// if `content-type` attribute is not present in metadata, then infer it from the extension in filePath
return {
...metaData,
'content-type': probeContentType(filePath)
};
}
/**
* Function prepends metadata with the appropriate prefix if it is not already on
*/
function prependXAMZMeta(metaData) {
if (!metaData) {
return {};
}
return _lodash.mapKeys(metaData, (value, key) => {
if (isAmzHeader(key) || isSupportedHeader(key) || isStorageClassHeader(key)) {
return key;
}
return MetaDataHeaderPrefix + key;
});
}
/**
* Checks if it is a valid header according to the AmazonS3 API
*/
function isAmzHeader(key) {
const temp = key.toLowerCase();
return temp.startsWith(MetaDataHeaderPrefix) || temp === 'x-amz-acl' || temp.startsWith('x-amz-server-side-encryption-') || temp === 'x-amz-server-side-encryption';
}
/**
* Checks if it is a supported Header
*/
function isSupportedHeader(key) {
const supported_headers = ['content-type', 'cache-control', 'content-encoding', 'content-disposition', 'content-language', 'x-amz-website-redirect-location', 'if-none-match', 'if-match'];
return supported_headers.includes(key.toLowerCase());
}
/**
* Checks if it is a storage header
*/
function isStorageClassHeader(key) {
return key.toLowerCase() === 'x-amz-storage-class';
}
function extractMetadata(headers) {
return _lodash.mapKeys(_lodash.pickBy(headers, (value, key) => isSupportedHeader(key) || isStorageClassHeader(key) || isAmzHeader(key)), (value, key) => {
const lower = key.toLowerCase();
if (lower.startsWith(MetaDataHeaderPrefix)) {
return lower.slice(MetaDataHeaderPrefix.length);
}
return key;
});
}
function getVersionId(headers = {}) {
return headers['x-amz-version-id'] || null;
}
function getSourceVersionId(headers = {}) {
return headers['x-amz-copy-source-version-id'] || null;
}
function sanitizeETag(etag = '') {
const replaceChars = {
'"': '',
'&quot;': '',
'&#34;': '',
'&QUOT;': '',
'&#x00022': ''
};
return etag.replace(/^("|&quot;|&#34;)|("|&quot;|&#34;)$/g, m => replaceChars[m]);
}
function toMd5(payload) {
// use string from browser and buffer from nodejs
// browser support is tested only against minio server
return crypto.createHash('md5').update(Buffer.from(payload)).digest().toString('base64');
}
function toSha256(payload) {
return crypto.createHash('sha256').update(payload).digest('hex');
}
/**
* toArray returns a single element array with param being the element,
* if param is just a string, and returns 'param' back if it is an array
* So, it makes sure param is always an array
*/
function toArray(param) {
if (!Array.isArray(param)) {
return [param];
}
return param;
}
function sanitizeObjectKey(objectName) {
// + symbol characters are not decoded as spaces in JS. so replace them first and decode to get the correct result.
const asStrName = (objectName ? objectName.toString() : '').replace(/\+/g, ' ');
return decodeURIComponent(asStrName);
}
function sanitizeSize(size) {
return size ? Number.parseInt(size) : undefined;
}
const PART_CONSTRAINTS = {
// absMinPartSize - absolute minimum part size (5 MiB)
ABS_MIN_PART_SIZE: 1024 * 1024 * 5,
// MIN_PART_SIZE - minimum part size 16MiB per object after which
MIN_PART_SIZE: 1024 * 1024 * 16,
// MAX_PARTS_COUNT - maximum number of parts for a single multipart session.
MAX_PARTS_COUNT: 10000,
// MAX_PART_SIZE - maximum part size 5GiB for a single multipart upload
// operation.
MAX_PART_SIZE: 1024 * 1024 * 1024 * 5,
// MAX_SINGLE_PUT_OBJECT_SIZE - maximum size 5GiB of object per PUT
// operation.
MAX_SINGLE_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 5,
// MAX_MULTIPART_PUT_OBJECT_SIZE - maximum size 5TiB of object for
// Multipart operation.
MAX_MULTIPART_PUT_OBJECT_SIZE: 1024 * 1024 * 1024 * 1024 * 5
};
exports.PART_CONSTRAINTS = PART_CONSTRAINTS;
const GENERIC_SSE_HEADER = 'X-Amz-Server-Side-Encryption';
const ENCRYPTION_HEADERS = {
// sseGenericHeader is the AWS SSE header used for SSE-S3 and SSE-KMS.
sseGenericHeader: GENERIC_SSE_HEADER,
// sseKmsKeyID is the AWS SSE-KMS key id.
sseKmsKeyID: GENERIC_SSE_HEADER + '-Aws-Kms-Key-Id'
};
/**
* Return Encryption headers
* @param encConfig
* @returns an object with key value pairs that can be used in headers.
*/
function getEncryptionHeaders(encConfig) {
const encType = encConfig.type;
if (!isEmpty(encType)) {
if (encType === _type.ENCRYPTION_TYPES.SSEC) {
return {
[ENCRYPTION_HEADERS.sseGenericHeader]: 'AES256'
};
} else if (encType === _type.ENCRYPTION_TYPES.KMS) {
return {
[ENCRYPTION_HEADERS.sseGenericHeader]: encConfig.SSEAlgorithm,
[ENCRYPTION_HEADERS.sseKmsKeyID]: encConfig.KMSMasterKeyID
};
}
}
return {};
}
function partsRequired(size) {
const maxPartSize = PART_CONSTRAINTS.MAX_MULTIPART_PUT_OBJECT_SIZE / (PART_CONSTRAINTS.MAX_PARTS_COUNT - 1);
let requiredPartSize = size / maxPartSize;
if (size % maxPartSize > 0) {
requiredPartSize++;
}
requiredPartSize = Math.trunc(requiredPartSize);
return requiredPartSize;
}
/**
* calculateEvenSplits - computes splits for a source and returns
* start and end index slices. Splits happen evenly to be sure that no
* part is less than 5MiB, as that could fail the multipart request if
* it is not the last part.
*/
function calculateEvenSplits(size, objInfo) {
if (size === 0) {
return null;
}
const reqParts = partsRequired(size);
const startIndexParts = [];
const endIndexParts = [];
let start = objInfo.Start;
if (isEmpty(start) || start === -1) {
start = 0;
}
const divisorValue = Math.trunc(size / reqParts);
const reminderValue = size % reqParts;
let nextStart = start;
for (let i = 0; i < reqParts; i++) {
let curPartSize = divisorValue;
if (i < reminderValue) {
curPartSize++;
}
const currentStart = nextStart;
const currentEnd = currentStart + curPartSize - 1;
nextStart = currentEnd + 1;
startIndexParts.push(currentStart);
endIndexParts.push(currentEnd);
}
return {
startIndex: startIndexParts,
endIndex: endIndexParts,
objInfo: objInfo
};
}
const fxp = new _fastXmlParser.XMLParser({
numberParseOptions: {
eNotation: false,
hex: true,
leadingZeros: true
}
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function parseXml(xml) {
const result = fxp.parse(xml);
if (result.Error) {
throw result.Error;
}
return result;
}
/**
* get content size of object content to upload
*/
async function getContentLength(s) {
// use length property of string | Buffer
if (typeof s === 'string' || Buffer.isBuffer(s)) {
return s.length;
}
// property of `fs.ReadStream`
const filePath = s.path;
if (filePath && typeof filePath === 'string') {
const stat = await _async.fsp.lstat(filePath);
return stat.size;
}
// property of `fs.ReadStream`
const fd = s.fd;
if (fd && typeof fd === 'number') {
const stat = await (0, _async.fstat)(fd);
return stat.size;
}
return null;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJfaW50ZXJvcFJlcXVpcmVXaWxkY2FyZCIsInJlcXVpcmUiLCJzdHJlYW0iLCJfZmFzdFhtbFBhcnNlciIsIl9pcGFkZHIiLCJfbG9kYXNoIiwibWltZSIsIl9hc3luYyIsIl90eXBlIiwiX2dldFJlcXVpcmVXaWxkY2FyZENhY2hlIiwib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3Npb25zIGFuZFxuICogbGltaXRhdGlvbnMgdW5kZXIgdGhlIExpY2Vuc2UuXG4gKi9cblxuaW1wb3J0ICogYXMgY3J5cHRvIGZyb20gJ25vZGU6Y3J5cHRvJ1xuaW1wb3J0ICogYXMgc3RyZWFtIGZyb20gJ25vZGU6c3RyZWFtJ1xuXG5pbXBvcnQgeyBYTUxQYXJzZXIgfSBmcm9tICdmYXN0LXhtbC1wYXJzZXInXG5pbXBvcnQgaXBhZGRyIGZyb20gJ2lwYWRkci5qcydcbmltcG9ydCBfIGZyb20gJ2xvZGFzaCdcbmltcG9ydCAqIGFzIG1pbWUgZnJvbSAnbWltZS10eXBlcydcblxuaW1wb3J0IHsgZnNwLCBmc3RhdCB9IGZyb20gJy4vYXN5bmM Line truncated
@@ -0,0 +1,11 @@
/**
* joinHostPort combines host and port into a network address of the
* form "host:port". If host contains a colon, as found in literal
* IPv6 addresses, then JoinHostPort returns "[host]:port".
*
* @param host
* @param port
* @returns Cleaned up host
* @internal
*/
export declare function joinHostPort(host: string, port?: number): string;
@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.joinHostPort = joinHostPort;
/**
* joinHostPort combines host and port into a network address of the
* form "host:port". If host contains a colon, as found in literal
* IPv6 addresses, then JoinHostPort returns "[host]:port".
*
* @param host
* @param port
* @returns Cleaned up host
* @internal
*/
function joinHostPort(host, port) {
if (port === undefined) {
return host;
}
// We assume that host is a literal IPv6 address if host has
// colons.
if (host.includes(':')) {
return `[${host}]:${port.toString()}`;
}
return `${host}:${port.toString()}`;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJqb2luSG9zdFBvcnQiLCJob3N0IiwicG9ydCIsInVuZGVmaW5lZCIsImluY2x1ZGVzIiwidG9TdHJpbmciXSwic291cmNlcyI6WyJqb2luLWhvc3QtcG9ydC50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIGp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UFBSSxDQUFDRyxRQUFRLENBQUMsR0FBRyxDQUFDLEVBQUU7SUFDdEIsT0FBUSxJQUFHSCxJQUFLLEtBQUlDLElBQUksQ0FBQ0csUUFBUSxDQUFDLENBQUUsRUFBQztFQUN2QztFQUVBLE9BQVEsR0FBRUosSUFBSyxJQUFHQyxJQUFJLENBQUNHLFFBQVEsQ0FBQyxDQUFFLEVBQUM7QUFDckMifQ==
@@ -0,0 +1,17 @@
import type { ObjectMetaData } from "./type.js";
export declare class PostPolicy {
policy: {
conditions: (string | number)[][];
expiration?: string;
};
formData: Record<string, string>;
setExpires(date: Date): void;
setKey(objectName: string): void;
setKeyStartsWith(prefix: string): void;
setBucket(bucketName: string): void;
setContentType(type: string): void;
setContentTypeStartsWith(prefix: string): void;
setContentDisposition(value: string): void;
setContentLengthRange(min: number, max: number): void;
setUserMetaData(metaData: ObjectMetaData): void;
}
@@ -0,0 +1,107 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var errors = _interopRequireWildcard(require("../errors.js"), true);
var _helper = require("./helper.js");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// Build PostPolicy object that can be signed by presignedPostPolicy
class PostPolicy {
policy = {
conditions: []
};
formData = {};
// set expiration date
setExpires(date) {
if (!date) {
throw new errors.InvalidDateError('Invalid date: cannot be null');
}
this.policy.expiration = date.toISOString();
}
// set object name
setKey(objectName) {
if (!(0, _helper.isValidObjectName)(objectName)) {
throw new errors.InvalidObjectNameError(`Invalid object name : ${objectName}`);
}
this.policy.conditions.push(['eq', '$key', objectName]);
this.formData.key = objectName;
}
// set object name prefix, i.e policy allows any keys with this prefix
setKeyStartsWith(prefix) {
if (!(0, _helper.isValidPrefix)(prefix)) {
throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`);
}
this.policy.conditions.push(['starts-with', '$key', prefix]);
this.formData.key = prefix;
}
// set bucket name
setBucket(bucketName) {
if (!(0, _helper.isValidBucketName)(bucketName)) {
throw new errors.InvalidBucketNameError(`Invalid bucket name : ${bucketName}`);
}
this.policy.conditions.push(['eq', '$bucket', bucketName]);
this.formData.bucket = bucketName;
}
// set Content-Type
setContentType(type) {
if (!type) {
throw new Error('content-type cannot be null');
}
this.policy.conditions.push(['eq', '$Content-Type', type]);
this.formData['Content-Type'] = type;
}
// set Content-Type prefix, i.e image/ allows any image
setContentTypeStartsWith(prefix) {
if (!prefix) {
throw new Error('content-type cannot be null');
}
this.policy.conditions.push(['starts-with', '$Content-Type', prefix]);
this.formData['Content-Type'] = prefix;
}
// set Content-Disposition
setContentDisposition(value) {
if (!value) {
throw new Error('content-disposition cannot be null');
}
this.policy.conditions.push(['eq', '$Content-Disposition', value]);
this.formData['Content-Disposition'] = value;
}
// set minimum/maximum length of what Content-Length can be.
setContentLengthRange(min, max) {
if (min > max) {
throw new Error('min cannot be more than max');
}
if (min < 0) {
throw new Error('min should be > 0');
}
if (max < 0) {
throw new Error('max should be > 0');
}
this.policy.conditions.push(['content-length-range', min, max]);
}
// set user defined metadata
setUserMetaData(metaData) {
if (!(0, _helper.isObject)(metaData)) {
throw new TypeError('metadata should be of type "object"');
}
Object.entries(metaData).forEach(([key, value]) => {
const amzMetaDataKey = `x-amz-meta-${key}`;
this.policy.conditions.push(['eq', `$${amzMetaDataKey}`, value]);
this.formData[amzMetaDataKey] = value.toString();
});
}
}
exports.PostPolicy = PostPolicy;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJlcnJvcnMiLCJfaW50ZXJvcFJlcXVpcmVXaWxkY2FyZCIsInJlcXVpcmUiLCJfaGVscGVyIiwiX2dldFJlcXVpcmVXaWxkY2FyZENhY2hlIiwibm9kZUludGVyb3AiLCJXZWFrTWFwIiwiY2FjaGVCYWJlbEludGVyb3AiLCJjYWNoZU5vZGVJbnRlcm9wIiwib2JqIiwiX19lc01vZHVsZSIsImRlZmF1bHQiLCJjYWNoZSIsImhhcyIsImdldCIsIm5ld09iaiIsImhhc1Byb3BlcnR5RGVzY3JpcHRvciIsIk9iamVjdCIsImRlZmluZVByb3BlcnR5IiwiZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9yIiwia2V5IiwicHJvdG90eXBlIiwiaGFzT3duUHJvcGVydHkiLCJjYWxsIiwiZGVzYyIsInNldCIsIlBvc3RQb2xpY3kiLCJwb2xpY3kiLCJjb25kaXRpb25zIiwiZm9ybURhdGEiLCJzZXRFeHBpcmVzIiwiZGF0ZSIsIkludmFsaWREYXRlRXJyb3IiLCJleHBpcmF0aW9uIiwidG9JU09TdHJpbmciLCJzZXRLZXkiLCJvYmplY3ROYW1lIiwiaXNWYWxpZE9iamVjdE5hbWUiLCJJbnZhbGlkT2JqZWN0TmFtZUVycm9yIiwicHVzaCIsInNldEtleVN0YXJ0c1dpdGgiLCJwcmVmaXgiLCJpc1ZhbGlkUHJlZml4IiwiSW52YWxpZFByZWZpeEVycm9yIiwic2V0QnVja2V0IiwiYnVja2V0TmFtZSIsImlzVmFsaWRCdWNrZXROYW1lIiwiSW52YWxpZEJ1Y2tldE5hbWVFcnJv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Agc2V0Q29udGVudERpc3Bvc2l0aW9uKHZhbHVlOiBzdHJpbmcpIHtcbiAgICBpZiAoIXZhbHVlKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ2NvbnRlbnQtZGlzcG9zaXRpb24gY2Fubm90IGJlIG51bGwnKVxuICAgIH1cbiAgICB0aGlzLnBvbGljeS5jb25kaXRpb25zLnB1c2goWydlcScsICckQ29udGVudC1EaXNwb3NpdGlvbicsIHZhbHVlXSlcbiAgICB0aGlzLmZvcm1EYXRhWydDb250ZW50LURpc3Bvc2l0aW9uJ10gPSB2YWx1ZVxuICB9XG5cbiAgLy8gc2V0IG1pbmltdW0vbWF4aW11bSBsZW5ndGggb2Ygd2hhdCBDb250ZW50LUxlbmd0aCBjYW4gYmUuXG4gIHNldENvbnRlbnRMZW5ndGhSYW5nZShtaW46IG51bWJlciwgbWF4OiBudW1iZXIpIHtcbiAgICBpZiAobWluID4gbWF4KSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ21pbiBjYW5ub3QgYmUgbW9yZSB0aGFuIG1heCcpXG4gICAgfVxuICAgIGlmIChtaW4gPCAwKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ21pbiBzaG91bGQgYmUgPiAwJylcbiAgICB9XG4gICAgaWYgKG1heCA8IDApIHtcbiAgICAgIHRocm93IG5 Line truncated
+11
View File
@@ -0,0 +1,11 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import type * as http from 'node:http';
import type * as https from 'node:https';
import type * as stream from 'node:stream';
import type { Transport } from "./type.js";
export declare function request(transport: Transport, opt: https.RequestOptions, body?: Buffer | string | stream.Readable | null): Promise<http.IncomingMessage>;
export declare const retryHttpCodes: Record<string, boolean>;
export declare function requestWithRetry(transport: Transport, opt: https.RequestOptions, body?: Buffer | string | stream.Readable | null, maxRetries?: number): Promise<http.IncomingMessage>;
+83
View File
@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.request = request;
exports.requestWithRetry = requestWithRetry;
var _stream = require("stream");
var _util = require("util");
const pipelineAsync = (0, _util.promisify)(_stream.pipeline);
async function request(transport, opt, body = null) {
return new Promise((resolve, reject) => {
const requestObj = transport.request(opt, response => {
resolve(response);
});
requestObj.on('error', reject);
if (!body || Buffer.isBuffer(body) || typeof body === 'string') {
requestObj.end(body);
} else {
pipelineAsync(body, requestObj).catch(reject);
}
});
}
const MAX_RETRIES = 10;
const EXP_BACK_OFF_BASE_DELAY = 1000; // Base delay for exponential backoff
const ADDITIONAL_DELAY_FACTOR = 1.0; // to avoid synchronized retries
// Retryable error codes for HTTP ( ref: minio-go)
const retryHttpCodes = {
408: true,
429: true,
499: true,
500: true,
502: true,
503: true,
504: true,
520: true
};
exports.retryHttpCodes = retryHttpCodes;
const isHttpRetryable = httpResCode => {
return retryHttpCodes[httpResCode] !== undefined;
};
const sleep = ms => {
return new Promise(resolve => setTimeout(resolve, ms));
};
const getExpBackOffDelay = retryCount => {
const backOffBy = EXP_BACK_OFF_BASE_DELAY * 2 ** retryCount;
const additionalDelay = Math.random() * backOffBy * ADDITIONAL_DELAY_FACTOR;
return backOffBy + additionalDelay;
};
async function requestWithRetry(transport, opt, body = null, maxRetries = MAX_RETRIES) {
let attempt = 0;
let isRetryable = false;
while (attempt <= maxRetries) {
try {
const response = await request(transport, opt, body);
// Check if the HTTP status code is retryable
if (isHttpRetryable(response.statusCode)) {
isRetryable = true;
throw new Error(`Retryable HTTP status: ${response.statusCode}`); // trigger retry attempt with calculated delay
}
return response; // Success, return the raw response
} catch (err) {
if (isRetryable) {
attempt++;
isRetryable = false;
if (attempt > maxRetries) {
throw new Error(`Request failed after ${maxRetries} retries: ${err}`);
}
const delay = getExpBackOffDelay(attempt);
// eslint-disable-next-line no-console
console.warn(`${new Date().toLocaleString()} Retrying request (attempt ${attempt}/${maxRetries}) after ${delay}ms due to: ${err}`);
await sleep(delay);
} else {
throw err; // re-throw if any request, syntax errors
}
}
}
throw new Error(`${MAX_RETRIES} Retries exhausted, request failed.`);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfc3RyZWFtIiwicmVxdWlyZSIsIl91dGlsIiwicGlwZWxpbmVBc3luYyIsInByb21pc2lmeSIsInBpcGVsaW5lIiwicmVxdWVzdCIsInRyYW5zcG9ydCIsIm9wdCIsImJvZHkiLCJQcm9taXNlIiwicmVzb2x2ZSIsInJlamVjdCIsInJlcXVlc3RPYmoiLCJyZXNwb25zZSIsIm9uIiwiQnVmZmVyIiwiaXNCdWZmZXIiLCJlbmQiLCJjYXRjaCIsIk1BWF9SRVRSSUVTIiwiRVhQX0JBQ0tfT0ZGX0JBU0VfREVMQVkiLCJBRERJVElPTkFMX0RFTEFZX0ZBQ1RPUiIsInJldHJ5SHR0cENvZGVzIiwiZXhwb3J0cyIsImlzSHR0cFJldHJ5YWJsZSIsImh0dHBSZXNDb2RlIiwidW5kZWZpbmVkIiwic2xlZXAiLCJtcyIsInNldFRpbWVvdXQiLCJnZXRFeHBCYWNrT2ZmRGVsYXkiLCJyZXRyeUNvdW50IiwiYmFja09mZkJ5IiwiYWRkaXRpb25hbERlbGF5IiwiTWF0aCIsInJhbmRvbSIsInJlcXVlc3RXaXRoUmV0cnkiLCJtYXhSZXRyaWVzIiwiYXR0ZW1wdCIsImlzUmV0cnlhYmxlIiwic3RhdHVzQ29kZSIsIkVycm9yIiwiZXJyIiwiZGVsYXkiLCJjb25zb2xlIiwid2FybiIsIkRhdGUiLCJ0b0xvY2FsZVN0cmluZyJdLCJzb3VyY2VzIjpbInJlcXVlc3QudHMiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHR5cGUgKiBhcyBodHRwIGZyb20gJ25vZGU6aHR0cCdcbmltcG9ydCB0eXBlICogYXMgaHR0cHMgZnJvbSAnbm9kZTpodHRwcydcbmltcG9ydCB0eXBlICogYXMgc3RyZWFtIGZyb20gJ25vZGU6c3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gICAgICB0aHJvdyBuZXcgRXJyb3IoYFJlcXVlc3QgZmFpbGVkIGFmdGVyICR7bWF4UmV0cmllc30gcmV0cmllczogJHtlcnJ9YClcbiAgICAgICAgfVxuICAgICAgICBjb25zdCBkZWxheSA9IGdldEV4cEJhY2tPZmZEZWxheShhdHRlbXB0KVxuICAgICAgICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgbm8tY29uc29sZVxuICAgICAgICBjb25zb2xlLndhcm4oXG4gICAgICAgICAgYCR7bmV3IERhdGUoKS50b0xvY2FsZVN0cmluZygpfSBSZXRyeWluZyByZXF1ZXN0IChhdHRlbXB0ICR7YXR0ZW1wdH0vJHttYXhSZXRyaWVzfSkgYWZ0ZXIgJHtkZWxheX1tcyBkdWUgdG86ICR7ZXJyfWAsXG4gICAgICAgIClcbiAgICAgICAgYXdhaXQgc2xlZXAoZGVsYXkpXG4gICAgICB9IGVsc2Uge1xuICAgICAgICB0aHJvdyBlcnIgLy8gcmUtdGhyb3cgaWYgYW55IHJlcXVlc3QsIHN5bnRheCBlcnJvcnNcbiAgICAgIH1cbiAgICB9XG4gIH1cblxuICB0aHJvdyBuZXcgRXJyb3IoYCR7TUFYX1J Line truncated
@@ -0,0 +1,8 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import type http from 'node:http';
import type stream from 'node:stream';
export declare function readAsBuffer(res: stream.Readable): Promise<Buffer>;
export declare function readAsString(res: http.IncomingMessage): Promise<string>;
export declare function drainResponse(res: stream.Readable): Promise<void>;
+24
View File
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.drainResponse = drainResponse;
exports.readAsBuffer = readAsBuffer;
exports.readAsString = readAsString;
async function readAsBuffer(res) {
return new Promise((resolve, reject) => {
const body = [];
res.on('data', chunk => body.push(chunk)).on('error', e => reject(e)).on('end', () => resolve(Buffer.concat(body)));
});
}
async function readAsString(res) {
const body = await readAsBuffer(res);
return body.toString();
}
async function drainResponse(res) {
return new Promise((resolve, reject) => {
res.on('data', () => {}).on('error', e => reject(e)).on('end', () => resolve());
});
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJyZWFkQXNCdWZmZXIiLCJyZXMiLCJQcm9taXNlIiwicmVzb2x2ZSIsInJlamVjdCIsImJvZHkiLCJvbiIsImNodW5rIiwicHVzaCIsImUiLCJCdWZmZXIiLCJjb25jYXQiLCJyZWFkQXNTdHJpbmciLCJ0b1N0cmluZyIsImRyYWluUmVzcG9uc2UiXSwic291cmNlcyI6WyJyZXNwb25zZS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSBodHRwIGZyb20gJ25vZGU6aHR0cCdcbmltcG9ydCB0eXBlIHN0cmVhbSBmcm9tICdub2RlOnN0cmVhbSdcblxuZXhwb3J0IGFzeW5jIGZ1bmN0aW9uIHJlYWRBc0J1ZmZlcihyZXM6IHN0cmVhbS5SZWFkYWJsZSk6IFByb21pc2U8QnVmZmVyPiB7XG4gIHJldHVybiBuZXcgUHJvbWlzZSgocmVzb2x2ZSwgcmVqZWN0KSA9PiB7XG4gICAgY29uc3QgYm9keTogQnVmZmVyW10gPSBbXVxuICAgIHJlc1xuICAgICAgLm9uKCdkYXRhJywgKGNodW5rOiBCdWZmZXIpID0+IGJvZHkucHVzaChjaHVuaykpXG4gICAgICAub24oJ2Vycm9yJywgKGUpID0+IHJlamVjdChlKSlcbiAgICAgIC5vbignZW5kJywgKCkgPT4gcmVzb2x2ZShCdWZmZXIuY29uY2F0KGJvZHkpKSlcbiAgfSlcbn1cblxuZXhwb3J0IGFzeW5jIGZ1bmN0aW9uIHJlYWRBc1N0cmluZyhyZXM6IGh0dHAuSW5jb21pbmdNZXNzYWdlKTogUHJvbWlzZTxzdHJpbmc+IHtcbiAgY29uc3QgYm9keSA9IGF3YWl0IHJlYWRBc0J1ZmZlcihyZXMpXG4gIHJldHVybiBib2R5LnRvU3Ry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ENBQUNiLEdBQW9CLEVBQWlCO0VBQ3ZFLE9BQU8sSUFBSUMsT0FBTyxDQUFDLENBQUNDLE9BQU8sRUFBRUMsTUFBTSxLQUFLO0lBQ3RDSCxHQUFHLENBQ0FLLEVBQUUsQ0FBQyxNQUFNLEVBQUUsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUNwQkEsRUFBRSxDQUFDLE9BQU8sRUFBR0csQ0FBQyxJQUFLTCxNQUFNLENBQUNLLENBQUMsQ0FBQyxDQUFDLENBQzdCSCxFQUFFLENBQUMsS0FBSyxFQUFFLE1BQU1ILE9BQU8sQ0FBQyxDQUFDLENBQUM7RUFDL0IsQ0FBQyxDQUFDO0FBQ0oifQ==
@@ -0,0 +1,38 @@
declare const awsS3Endpoint: {
'af-south-1': string;
'ap-east-1': string;
'ap-south-1': string;
'ap-south-2': string;
'ap-southeast-1': string;
'ap-southeast-2': string;
'ap-southeast-3': string;
'ap-southeast-4': string;
'ap-southeast-5': string;
'ap-northeast-1': string;
'ap-northeast-2': string;
'ap-northeast-3': string;
'ca-central-1': string;
'ca-west-1': string;
'cn-north-1': string;
'eu-central-1': string;
'eu-central-2': string;
'eu-north-1': string;
'eu-south-1': string;
'eu-south-2': string;
'eu-west-1': string;
'eu-west-2': string;
'eu-west-3': string;
'il-central-1': string;
'me-central-1': string;
'me-south-1': string;
'sa-east-1': string;
'us-east-1': string;
'us-east-2': string;
'us-west-1': string;
'us-west-2': string;
'us-gov-east-1': string;
'us-gov-west-1': string;
};
export type Region = keyof typeof awsS3Endpoint | string;
export declare function getS3Endpoint(region: Region): string;
export {};
@@ -0,0 +1,73 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getS3Endpoint = getS3Endpoint;
var _helper = require("./helper.js");
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015, 2016 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// List of currently supported endpoints.
const awsS3Endpoint = {
'af-south-1': 's3.af-south-1.amazonaws.com',
'ap-east-1': 's3.ap-east-1.amazonaws.com',
'ap-south-1': 's3.ap-south-1.amazonaws.com',
'ap-south-2': 's3.ap-south-2.amazonaws.com',
'ap-southeast-1': 's3.ap-southeast-1.amazonaws.com',
'ap-southeast-2': 's3.ap-southeast-2.amazonaws.com',
'ap-southeast-3': 's3.ap-southeast-3.amazonaws.com',
'ap-southeast-4': 's3.ap-southeast-4.amazonaws.com',
'ap-southeast-5': 's3.ap-southeast-5.amazonaws.com',
'ap-northeast-1': 's3.ap-northeast-1.amazonaws.com',
'ap-northeast-2': 's3.ap-northeast-2.amazonaws.com',
'ap-northeast-3': 's3.ap-northeast-3.amazonaws.com',
'ca-central-1': 's3.ca-central-1.amazonaws.com',
'ca-west-1': 's3.ca-west-1.amazonaws.com',
'cn-north-1': 's3.cn-north-1.amazonaws.com.cn',
'eu-central-1': 's3.eu-central-1.amazonaws.com',
'eu-central-2': 's3.eu-central-2.amazonaws.com',
'eu-north-1': 's3.eu-north-1.amazonaws.com',
'eu-south-1': 's3.eu-south-1.amazonaws.com',
'eu-south-2': 's3.eu-south-2.amazonaws.com',
'eu-west-1': 's3.eu-west-1.amazonaws.com',
'eu-west-2': 's3.eu-west-2.amazonaws.com',
'eu-west-3': 's3.eu-west-3.amazonaws.com',
'il-central-1': 's3.il-central-1.amazonaws.com',
'me-central-1': 's3.me-central-1.amazonaws.com',
'me-south-1': 's3.me-south-1.amazonaws.com',
'sa-east-1': 's3.sa-east-1.amazonaws.com',
'us-east-1': 's3.us-east-1.amazonaws.com',
'us-east-2': 's3.us-east-2.amazonaws.com',
'us-west-1': 's3.us-west-1.amazonaws.com',
'us-west-2': 's3.us-west-2.amazonaws.com',
'us-gov-east-1': 's3.us-gov-east-1.amazonaws.com',
'us-gov-west-1': 's3.us-gov-west-1.amazonaws.com'
// Add new endpoints here.
};
// getS3Endpoint get relevant endpoint for the region.
function getS3Endpoint(region) {
if (!(0, _helper.isString)(region)) {
throw new TypeError(`Invalid region: ${region}`);
}
const endpoint = awsS3Endpoint[region];
if (endpoint) {
return endpoint;
}
return 's3.amazonaws.com';
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfaGVscGVyIiwicmVxdWlyZSIsImF3c1MzRW5kcG9pbnQiLCJnZXRTM0VuZHBvaW50IiwicmVnaW9uIiwiaXNTdHJpbmciLCJUeXBlRXJyb3IiLCJlbmRwb2ludCJdLCJzb3VyY2VzIjpbInMzLWVuZHBvaW50cy50cyJdLCJzb3VyY2VzQ29udGVudCI6WyIvKlxuICogTWluSU8gSmF2YXNjcmlwdCBMaWJyYXJ5IGZvciBBbWF6b24gUzMgQ29tcGF0aWJsZSBDbG91ZCBTdG9yYWdlLCAoQykgMjAxNSwgMjAxNiBNaW5JTywgSW5jLlxuICpcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBBcGFjaGUgTGljZW5zZSwgVmVyc2lvbiAyLjAgKHRoZSBcIkxpY2Vuc2VcIik7XG4gKiB5b3UgbWF5IG5vdCB1c2UgdGhpcyBmaWxlIGV4Y2VwdCBpbiBjb21wbGlhbmNlIHdpdGggdGhlIExpY2Vuc2UuXG4gKiBZb3UgbWF5IG9idGFpbiBhIGNvcHkgb2YgdGhlIExpY2Vuc2UgYXRcbiAqXG4gKiAgICAgaHR0cDovL3d3dy5hcGFjaGUub3JnL2xpY2Vuc2VzL0xJQ0VOU0UtMi4wXG4gKlxuICogVW5sZXNzIHJlcXVpcmVkIGJ5IGFwcGxpY2FibGUgbGF3IG9yIGFncmVlZCB0byBpbiB3cml0aW5nLCBzb2Z0d2FyZVxuICogZGlzdHJ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QpIHtcbiAgICByZXR1cm4gZW5kcG9pbnRcbiAgfVxuICByZXR1cm4gJ3MzLmFtYXpvbmF3cy5jb20nXG59XG4iXSwibWFwcGluZ3MiOiI7Ozs7OztBQWdCQSxJQUFBQSxPQUFBLEdBQUFDLE9BQUE7QUFoQkE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUlBO0FBQ0EsTUFBTUMsYUFBYSxHQUFHO0VBQ3BCLFlBQVksRUFBRSw2QkFBNkI7RUFDM0MsV0FBVyxFQUFFLDRCQUE0QjtFQUN6QyxZQUFZLEVBQUUsNkJBQTZCO0VBQzNDLFlBQVksRUFBRSw2QkFBNkI7RUFDM0MsZ0JBQWdCLEVBQUUsaUNBQWlDO0VBQ25ELGdCQUFnQixFQUFFLGlDQUFpQztFQUNuRCxnQkFBZ0IsRUFBRSxpQ0FBaUM7RUFDbkQsZ0JBQWdCLEVBQUUsaUNBQWlDO0VBQ25ELGdCQUFnQixFQUFFLGlDQUFpQztFQUNuRCxnQkFBZ0IsRUFBRSxpQ0FBaUM7RUFDbkQsZ0JBQWdCLEVBQUUsaUNBQWlDO0VBQ25ELGdCQUFnQixFQUFFLGlDQUFpQztFQUNuRCxjQUFjLEVBQUUsK0JBQStCO0VBQy9DLFdBQVcsRUFBRSw0QkFBNEI7RUFDekMsWUFBWSxFQUFFLGdDQUFnQztFQUM5QyxjQUFjLEVBQUUsK0JBQStCO0VBQy9DLGNBQWMsRUFBRSwrQkFBK0I7RUFDL0MsWUFBWSxFQUFFLDZCQUE2QjtFQUMzQyxZQUFZLEVBQUUsNkJBQTZCO0VBQzNDLFlBQVksRUFBRSw2QkFBNkI7RUFDM0MsV0F Line truncated
+447
View File
@@ -0,0 +1,447 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import type * as http from 'node:http';
import type { Readable as ReadableStream } from 'node:stream';
import type { CopyDestinationOptions, CopySourceOptions } from "../helpers.js";
import type { CopyConditions } from "./copy-conditions.js";
export type VersionIdentificator = {
versionId?: string;
};
export type GetObjectOpts = VersionIdentificator & {
SSECustomerAlgorithm?: string;
SSECustomerKey?: string;
SSECustomerKeyMD5?: string;
};
export type Binary = string | Buffer;
export type ResponseHeader = Record<string, string>;
export type ObjectMetaData = Record<string, string | number>;
export type RequestHeaders = Record<string, string | boolean | number | undefined>;
export type Encryption = {
type: ENCRYPTION_TYPES.SSEC;
} | {
type: ENCRYPTION_TYPES.KMS;
SSEAlgorithm?: string;
KMSMasterKeyID?: string;
};
export type EnabledOrDisabledStatus = 'Enabled' | 'Disabled';
export declare enum ENCRYPTION_TYPES {
/**
* SSEC represents server-side-encryption with customer provided keys
*/
SSEC = "SSE-C",
/**
* KMS represents server-side-encryption with managed keys
*/
KMS = "KMS",
}
export declare enum RETENTION_MODES {
GOVERNANCE = "GOVERNANCE",
COMPLIANCE = "COMPLIANCE",
}
export declare enum RETENTION_VALIDITY_UNITS {
DAYS = "Days",
YEARS = "Years",
}
export declare enum LEGAL_HOLD_STATUS {
ENABLED = "ON",
DISABLED = "OFF",
}
export type Transport = Pick<typeof http, 'request'>;
export interface IRequest {
protocol: string;
port?: number | string;
method: string;
path: string;
headers: RequestHeaders;
}
export type ICanonicalRequest = string;
export interface IncompleteUploadedBucketItem {
key: string;
uploadId: string;
size: number;
}
export interface MetadataItem {
Key: string;
Value: string;
}
export interface ItemBucketMetadataList {
Items: MetadataItem[];
}
export interface ItemBucketMetadata {
[key: string]: any;
}
export interface ItemBucketTags {
[key: string]: any;
}
export interface BucketItemFromList {
name: string;
creationDate: Date;
}
export interface BucketItemCopy {
etag: string;
lastModified: Date;
}
export type BucketItem = {
name: string;
size: number;
etag: string;
prefix?: never;
lastModified: Date;
} | {
name?: never;
etag?: never;
lastModified?: never;
prefix: string;
size: 0;
};
export type BucketItemWithMetadata = BucketItem & {
metadata?: ItemBucketMetadata | ItemBucketMetadataList;
tags?: ItemBucketTags;
};
export interface BucketStream<T> extends ReadableStream {
on(event: 'data', listener: (item: T) => void): this;
on(event: 'end' | 'pause' | 'readable' | 'resume' | 'close', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface BucketItemStat {
size: number;
etag: string;
lastModified: Date;
metaData: ItemBucketMetadata;
versionId?: string | null;
}
export type StatObjectOpts = {
versionId?: string;
};
export type ReplicationRuleStatus = {
Status: EnabledOrDisabledStatus;
};
export type Tag = {
Key: string;
Value: string;
};
export type Tags = Record<string, string>;
export type ReplicationRuleDestination = {
Bucket: string;
StorageClass: string;
};
export type ReplicationRuleAnd = {
Prefix: string;
Tags: Tag[];
};
export type ReplicationRuleFilter = {
Prefix: string;
And: ReplicationRuleAnd;
Tag: Tag;
};
export type ReplicaModifications = {
Status: ReplicationRuleStatus;
};
export type SourceSelectionCriteria = {
ReplicaModifications: ReplicaModifications;
};
export type ExistingObjectReplication = {
Status: ReplicationRuleStatus;
};
export type ReplicationRule = {
ID: string;
Status: ReplicationRuleStatus;
Priority: number;
DeleteMarkerReplication: ReplicationRuleStatus;
DeleteReplication: ReplicationRuleStatus;
Destination: ReplicationRuleDestination;
Filter: ReplicationRuleFilter;
SourceSelectionCriteria: SourceSelectionCriteria;
ExistingObjectReplication: ExistingObjectReplication;
};
export type ReplicationConfigOpts = {
role: string;
rules: ReplicationRule[];
};
export type ReplicationConfig = {
ReplicationConfiguration: ReplicationConfigOpts;
};
export type ResultCallback<T> = (error: Error | null, result: T) => void;
export type GetObjectLegalHoldOptions = {
versionId: string;
};
/**
* @deprecated keep for backward compatible, use `LEGAL_HOLD_STATUS` instead
*/
export type LegalHoldStatus = LEGAL_HOLD_STATUS;
export type PutObjectLegalHoldOptions = {
versionId?: string;
status: LEGAL_HOLD_STATUS;
};
export interface UploadedObjectInfo {
etag: string;
versionId: string | null;
}
export interface RetentionOptions {
versionId: string;
mode?: RETENTION_MODES;
retainUntilDate?: IsoDate;
governanceBypass?: boolean;
}
export type Retention = RetentionOptions | EmptyObject;
export type IsoDate = string;
export type EmptyObject = Record<string, never>;
export type ObjectLockInfo = {
objectLockEnabled: EnabledOrDisabledStatus;
mode: RETENTION_MODES;
unit: RETENTION_VALIDITY_UNITS;
validity: number;
} | EmptyObject;
export type ObjectLockConfigParam = {
ObjectLockEnabled?: 'Enabled' | undefined;
Rule?: {
DefaultRetention: {
Mode: RETENTION_MODES;
Days: number;
Years: number;
} | EmptyObject;
} | EmptyObject;
};
export type VersioningEnabled = 'Enabled';
export type VersioningSuspended = 'Suspended';
export type TaggingOpts = {
versionId: string;
};
export type PutTaggingParams = {
bucketName: string;
objectName?: string;
tags: Tags;
putOpts?: TaggingOpts;
};
export type RemoveTaggingParams = {
bucketName: string;
objectName?: string;
removeOpts?: TaggingOpts;
};
export type InputSerialization = {
CompressionType?: 'NONE' | 'GZIP' | 'BZIP2';
CSV?: {
AllowQuotedRecordDelimiter?: boolean;
Comments?: string;
FieldDelimiter?: string;
FileHeaderInfo?: 'NONE' | 'IGNORE' | 'USE';
QuoteCharacter?: string;
QuoteEscapeCharacter?: string;
RecordDelimiter?: string;
};
JSON?: {
Type: 'DOCUMENT' | 'LINES';
};
Parquet?: EmptyObject;
};
export type OutputSerialization = {
CSV?: {
FieldDelimiter?: string;
QuoteCharacter?: string;
QuoteEscapeCharacter?: string;
QuoteFields?: string;
RecordDelimiter?: string;
};
JSON?: {
RecordDelimiter?: string;
};
};
export type SelectProgress = {
Enabled: boolean;
};
export type ScanRange = {
Start: number;
End: number;
};
export type SelectOptions = {
expression: string;
expressionType?: string;
inputSerialization: InputSerialization;
outputSerialization: OutputSerialization;
requestProgress?: SelectProgress;
scanRange?: ScanRange;
};
export type Expiration = {
Date?: string;
Days: number;
DeleteMarker?: boolean;
DeleteAll?: boolean;
};
export type RuleFilterAnd = {
Prefix: string;
Tags: Tag[];
};
export type RuleFilter = {
And?: RuleFilterAnd;
Prefix: string;
Tag?: Tag[];
};
export type NoncurrentVersionExpiration = {
NoncurrentDays: number;
NewerNoncurrentVersions?: number;
};
export type NoncurrentVersionTransition = {
StorageClass: string;
NoncurrentDays?: number;
NewerNoncurrentVersions?: number;
};
export type Transition = {
Date?: string;
StorageClass: string;
Days: number;
};
export type AbortIncompleteMultipartUpload = {
DaysAfterInitiation: number;
};
export type LifecycleRule = {
AbortIncompleteMultipartUpload?: AbortIncompleteMultipartUpload;
ID: string;
Prefix?: string;
Status?: string;
Expiration?: Expiration;
Filter?: RuleFilter;
NoncurrentVersionExpiration?: NoncurrentVersionExpiration;
NoncurrentVersionTransition?: NoncurrentVersionTransition;
Transition?: Transition;
};
export type LifecycleConfig = {
Rule: LifecycleRule[];
};
export type LifeCycleConfigParam = LifecycleConfig | null | undefined | '';
export type ApplySSEByDefault = {
KmsMasterKeyID?: string;
SSEAlgorithm: string;
};
export type EncryptionRule = {
ApplyServerSideEncryptionByDefault?: ApplySSEByDefault;
};
export type EncryptionConfig = {
Rule: EncryptionRule[];
};
export type GetObjectRetentionOpts = {
versionId: string;
};
export type ObjectRetentionInfo = {
mode: RETENTION_MODES;
retainUntilDate: string;
};
export type RemoveObjectsEntry = {
name: string;
versionId?: string;
};
export type ObjectName = string;
export type RemoveObjectsParam = ObjectName[] | RemoveObjectsEntry[];
export type RemoveObjectsRequestEntry = {
Key: string;
VersionId?: string;
};
export type RemoveObjectsResponse = null | undefined | {
Error?: {
Code?: string;
Message?: string;
Key?: string;
VersionId?: string;
};
};
export type CopyObjectResultV1 = {
etag: string;
lastModified: string | Date;
};
export type CopyObjectResultV2 = {
Bucket?: string;
Key?: string;
LastModified: string | Date;
MetaData?: ResponseHeader;
VersionId?: string | null;
SourceVersionId?: string | null;
Etag?: string;
Size?: number;
};
export type CopyObjectResult = CopyObjectResultV1 | CopyObjectResultV2;
export type CopyObjectParams = [CopySourceOptions, CopyDestinationOptions] | [string, string, string, CopyConditions?];
export type ExcludedPrefix = {
Prefix: string;
};
export type BucketVersioningConfiguration = {
Status: VersioningEnabled | VersioningSuspended;
MFADelete?: string;
ExcludedPrefixes?: ExcludedPrefix[];
ExcludeFolders?: boolean;
};
export type UploadPartConfig = {
bucketName: string;
objectName: string;
uploadID: string;
partNumber: number;
headers: RequestHeaders;
sourceObj: string;
};
export type PreSignRequestParams = {
[key: string]: string;
};
/** List object api types **/
export type CommonPrefix = {
Prefix: string;
};
export type Owner = {
ID: string;
DisplayName: string;
};
export type Metadata = {
Items: MetadataItem[];
};
export type ObjectInfo = {
key?: string;
name?: string;
lastModified?: Date;
etag?: string;
owner?: Owner;
storageClass?: string;
userMetadata?: Metadata;
userTags?: string;
prefix?: string;
size?: number;
};
export type ListObjectQueryRes = {
isTruncated?: boolean;
nextMarker?: string;
versionIdMarker?: string;
objects?: ObjectInfo[];
};
export type ListObjectQueryOpts = {
Delimiter?: string;
MaxKeys?: number;
IncludeVersion?: boolean;
};
/** List object api types **/
export type ObjectVersionEntry = {
IsLatest?: string;
VersionId?: string;
};
export type ObjectRowEntry = ObjectVersionEntry & {
Key: string;
LastModified?: Date | undefined;
ETag?: string;
Size?: string;
Owner?: Owner;
StorageClass?: string;
};
export interface ListBucketResultV1 {
Name?: string;
Prefix?: string;
ContinuationToken?: string;
KeyCount?: string;
Marker?: string;
MaxKeys?: string;
Delimiter?: string;
IsTruncated?: boolean;
Contents?: ObjectRowEntry[];
NextKeyMarker?: string;
CommonPrefixes?: CommonPrefix[];
Version?: ObjectRowEntry[];
DeleteMarker?: ObjectRowEntry[];
VersionIdMarker?: string;
NextVersionIdMarker?: string;
}
+39
View File
@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// nodejs IncomingHttpHeaders is Record<string, string | string[]>, but it's actually this:
let ENCRYPTION_TYPES = /*#__PURE__*/function (ENCRYPTION_TYPES) {
ENCRYPTION_TYPES["SSEC"] = "SSE-C";
ENCRYPTION_TYPES["KMS"] = "KMS";
return ENCRYPTION_TYPES;
}({});
exports.ENCRYPTION_TYPES = ENCRYPTION_TYPES;
let RETENTION_MODES = /*#__PURE__*/function (RETENTION_MODES) {
RETENTION_MODES["GOVERNANCE"] = "GOVERNANCE";
RETENTION_MODES["COMPLIANCE"] = "COMPLIANCE";
return RETENTION_MODES;
}({});
exports.RETENTION_MODES = RETENTION_MODES;
let RETENTION_VALIDITY_UNITS = /*#__PURE__*/function (RETENTION_VALIDITY_UNITS) {
RETENTION_VALIDITY_UNITS["DAYS"] = "Days";
RETENTION_VALIDITY_UNITS["YEARS"] = "Years";
return RETENTION_VALIDITY_UNITS;
}({});
exports.RETENTION_VALIDITY_UNITS = RETENTION_VALIDITY_UNITS;
let LEGAL_HOLD_STATUS = /*#__PURE__*/function (LEGAL_HOLD_STATUS) {
LEGAL_HOLD_STATUS["ENABLED"] = "ON";
LEGAL_HOLD_STATUS["DISABLED"] = "OFF";
return LEGAL_HOLD_STATUS;
}({});
/* Replication Config types */
/* Replication Config types */
/**
* @deprecated keep for backward compatible, use `LEGAL_HOLD_STATUS` instead
*/
/** List object api types **/
// Common types
/** List object api types **/
exports.LEGAL_HOLD_STATUS = LEGAL_HOLD_STATUS;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJFTkNSWVBUSU9OX1RZUEVTIiwiZXhwb3J0cyIsIlJFVEVOVElPTl9NT0RFUyIsIlJFVEVOVElPTl9WQUxJRElUWV9VTklUUyIsIkxFR0FMX0hPTERfU1RBVFVTIl0sInNvdXJjZXMiOlsidHlwZS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgdHlwZSAqIGFzIGh0dHAgZnJvbSAnbm9kZTpodHRwJ1xuaW1wb3J0IHR5cGUgeyBSZWFkYWJsZSBhcyBSZWFkYWJsZVN0cmVhbSB9IGZyb20gJ25vZGU6c3RyZWFtJ1xuXG5pbXBvcnQgdHlwZSB7IENvcHlEZXN0aW5hdGlvbk9wdGlvbnMsIENvcHlTb3VyY2VPcHRpb25zIH0gZnJ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yB8IG51bGxcbn1cblxuZXhwb3J0IHR5cGUgU3RhdE9iamVjdE9wdHMgPSB7XG4gIHZlcnNpb25JZD86IHN0cmluZ1xufVxuXG4vKiBSZXBsaWNhdGlvbiBDb25maWcgdHlwZXMgKi9cbmV4cG9ydCB0eXBlIFJlcGxpY2F0aW9uUnVsZVN Line truncated
@@ -0,0 +1,90 @@
/// <reference types="node" />
/// <reference types="node" />
import type * as http from 'node:http';
import { SelectResults } from "../helpers.js";
import type { BucketItemFromList, BucketItemWithMetadata, CopyObjectResultV1, ObjectInfo, ObjectLockInfo, ReplicationConfig } from "./type.js";
export declare function parseBucketRegion(xml: string): string;
export declare function parseError(xml: string, headerInfo: Record<string, unknown>): Record<string, unknown>;
export declare function parseResponseError(response: http.IncomingMessage): Promise<Record<string, string>>;
/**
* parse XML response for list objects v2 with metadata in a bucket
*/
export declare function parseListObjectsV2WithMetadata(xml: string): {
objects: Array<BucketItemWithMetadata>;
isTruncated: boolean;
nextContinuationToken: string;
};
export type UploadedPart = {
part: number;
lastModified?: Date;
etag: string;
size: number;
};
export declare function parseListParts(xml: string): {
isTruncated: boolean;
marker: number;
parts: UploadedPart[];
};
export declare function parseListBucket(xml: string): BucketItemFromList[];
export declare function parseInitiateMultipart(xml: string): string;
export declare function parseReplicationConfig(xml: string): ReplicationConfig;
export declare function parseObjectLegalHoldConfig(xml: string): any;
export declare function parseTagging(xml: string): any;
export declare function parseCompleteMultipart(xml: string): {
location: any;
bucket: any;
key: any;
etag: any;
errCode?: undefined;
errMessage?: undefined;
} | {
errCode: any;
errMessage: any;
location?: undefined;
bucket?: undefined;
key?: undefined;
etag?: undefined;
} | undefined;
type UploadID = string;
export type ListMultipartResult = {
uploads: {
key: string;
uploadId: UploadID;
initiator?: {
id: string;
displayName: string;
};
owner?: {
id: string;
displayName: string;
};
storageClass: unknown;
initiated: Date;
}[];
prefixes: {
prefix: string;
}[];
isTruncated: boolean;
nextKeyMarker: string;
nextUploadIdMarker: string;
};
export declare function parseListMultipart(xml: string): ListMultipartResult;
export declare function parseObjectLockConfig(xml: string): ObjectLockInfo;
export declare function parseBucketVersioningConfig(xml: string): any;
export declare function parseSelectObjectContentResponse(res: Buffer): SelectResults | undefined;
export declare function parseLifecycleConfig(xml: string): any;
export declare function parseBucketEncryptionConfig(xml: string): any;
export declare function parseObjectRetentionConfig(xml: string): {
mode: any;
retainUntilDate: any;
};
export declare function removeObjectsParser(xml: string): any[];
export declare function parseCopyObject(xml: string): CopyObjectResultV1;
export declare function parseListObjects(xml: string): {
objects: ObjectInfo[];
isTruncated?: boolean | undefined;
nextMarker?: string | undefined;
versionIdMarker?: string | undefined;
};
export declare function uploadPartParser(xml: string): any;
export {};
+719
View File
@@ -0,0 +1,719 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseBucketEncryptionConfig = parseBucketEncryptionConfig;
exports.parseBucketRegion = parseBucketRegion;
exports.parseBucketVersioningConfig = parseBucketVersioningConfig;
exports.parseCompleteMultipart = parseCompleteMultipart;
exports.parseCopyObject = parseCopyObject;
exports.parseError = parseError;
exports.parseInitiateMultipart = parseInitiateMultipart;
exports.parseLifecycleConfig = parseLifecycleConfig;
exports.parseListBucket = parseListBucket;
exports.parseListMultipart = parseListMultipart;
exports.parseListObjects = parseListObjects;
exports.parseListObjectsV2WithMetadata = parseListObjectsV2WithMetadata;
exports.parseListParts = parseListParts;
exports.parseObjectLegalHoldConfig = parseObjectLegalHoldConfig;
exports.parseObjectLockConfig = parseObjectLockConfig;
exports.parseObjectRetentionConfig = parseObjectRetentionConfig;
exports.parseReplicationConfig = parseReplicationConfig;
exports.parseResponseError = parseResponseError;
exports.parseSelectObjectContentResponse = parseSelectObjectContentResponse;
exports.parseTagging = parseTagging;
exports.removeObjectsParser = removeObjectsParser;
exports.uploadPartParser = uploadPartParser;
var _bufferCrc = require("buffer-crc32");
var _fastXmlParser = require("fast-xml-parser");
var errors = _interopRequireWildcard(require("../errors.js"), true);
var _helpers = require("../helpers.js");
var _helper = require("./helper.js");
var _response = require("./response.js");
var _type = require("./type.js");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// parse XML response for bucket region
function parseBucketRegion(xml) {
// return region information
return (0, _helper.parseXml)(xml).LocationConstraint;
}
const fxp = new _fastXmlParser.XMLParser();
const fxpWithoutNumParser = new _fastXmlParser.XMLParser({
// @ts-ignore
numberParseOptions: {
skipLike: /./
}
});
// Parse XML and return information as Javascript types
// parse error XML response
function parseError(xml, headerInfo) {
let xmlErr = {};
const xmlObj = fxp.parse(xml);
if (xmlObj.Error) {
xmlErr = xmlObj.Error;
}
const e = new errors.S3Error();
Object.entries(xmlErr).forEach(([key, value]) => {
e[key.toLowerCase()] = value;
});
Object.entries(headerInfo).forEach(([key, value]) => {
e[key] = value;
});
return e;
}
// Generates an Error object depending on http statusCode and XML body
async function parseResponseError(response) {
const statusCode = response.statusCode;
let code = '',
message = '';
if (statusCode === 301) {
code = 'MovedPermanently';
message = 'Moved Permanently';
} else if (statusCode === 307) {
code = 'TemporaryRedirect';
message = 'Are you using the correct endpoint URL?';
} else if (statusCode === 403) {
code = 'AccessDenied';
message = 'Valid and authorized credentials required';
} else if (statusCode === 404) {
code = 'NotFound';
message = 'Not Found';
} else if (statusCode === 405) {
code = 'MethodNotAllowed';
message = 'Method Not Allowed';
} else if (statusCode === 501) {
code = 'MethodNotAllowed';
message = 'Method Not Allowed';
} else if (statusCode === 503) {
code = 'SlowDown';
message = 'Please reduce your request rate.';
} else {
const hErrCode = response.headers['x-minio-error-code'];
const hErrDesc = response.headers['x-minio-error-desc'];
if (hErrCode && hErrDesc) {
code = hErrCode;
message = hErrDesc;
}
}
const headerInfo = {};
// A value created by S3 compatible server that uniquely identifies the request.
headerInfo.amzRequestid = response.headers['x-amz-request-id'];
// A special token that helps troubleshoot API replies and issues.
headerInfo.amzId2 = response.headers['x-amz-id-2'];
// Region where the bucket is located. This header is returned only
// in HEAD bucket and ListObjects response.
headerInfo.amzBucketRegion = response.headers['x-amz-bucket-region'];
const xmlString = await (0, _response.readAsString)(response);
if (xmlString) {
throw parseError(xmlString, headerInfo);
}
// Message should be instantiated for each S3Errors.
const e = new errors.S3Error(message, {
cause: headerInfo
});
// S3 Error code.
e.code = code;
Object.entries(headerInfo).forEach(([key, value]) => {
// @ts-expect-error force set error properties
e[key] = value;
});
throw e;
}
/**
* parse XML response for list objects v2 with metadata in a bucket
*/
function parseListObjectsV2WithMetadata(xml) {
const result = {
objects: [],
isTruncated: false,
nextContinuationToken: ''
};
let xmlobj = (0, _helper.parseXml)(xml);
if (!xmlobj.ListBucketResult) {
throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"');
}
xmlobj = xmlobj.ListBucketResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextContinuationToken) {
result.nextContinuationToken = xmlobj.NextContinuationToken;
}
if (xmlobj.Contents) {
(0, _helper.toArray)(xmlobj.Contents).forEach(content => {
const name = (0, _helper.sanitizeObjectKey)(content.Key);
const lastModified = new Date(content.LastModified);
const etag = (0, _helper.sanitizeETag)(content.ETag);
const size = content.Size;
let tags = {};
if (content.UserTags != null) {
(0, _helper.toArray)(content.UserTags.split('&')).forEach(tag => {
const [key, value] = tag.split('=');
tags[key] = value;
});
} else {
tags = {};
}
let metadata;
if (content.UserMetadata != null) {
metadata = (0, _helper.toArray)(content.UserMetadata)[0];
} else {
metadata = null;
}
result.objects.push({
name,
lastModified,
etag,
size,
metadata,
tags
});
});
}
if (xmlobj.CommonPrefixes) {
(0, _helper.toArray)(xmlobj.CommonPrefixes).forEach(commonPrefix => {
result.objects.push({
prefix: (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(commonPrefix.Prefix)[0]),
size: 0
});
});
}
return result;
}
// parse XML response for list parts of an in progress multipart upload
function parseListParts(xml) {
let xmlobj = (0, _helper.parseXml)(xml);
const result = {
isTruncated: false,
parts: [],
marker: 0
};
if (!xmlobj.ListPartsResult) {
throw new errors.InvalidXMLError('Missing tag: "ListPartsResult"');
}
xmlobj = xmlobj.ListPartsResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextPartNumberMarker) {
result.marker = (0, _helper.toArray)(xmlobj.NextPartNumberMarker)[0] || '';
}
if (xmlobj.Part) {
(0, _helper.toArray)(xmlobj.Part).forEach(p => {
const part = parseInt((0, _helper.toArray)(p.PartNumber)[0], 10);
const lastModified = new Date(p.LastModified);
const etag = p.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^&quot;/g, '').replace(/&quot;$/g, '').replace(/^&#34;/g, '').replace(/&#34;$/g, '');
result.parts.push({
part,
lastModified,
etag,
size: parseInt(p.Size, 10)
});
});
}
return result;
}
function parseListBucket(xml) {
let result = [];
const listBucketResultParser = new _fastXmlParser.XMLParser({
parseTagValue: true,
// Enable parsing of values
numberParseOptions: {
leadingZeros: false,
// Disable number parsing for values with leading zeros
hex: false,
// Disable hex number parsing - Invalid bucket name
skipLike: /^[0-9]+$/ // Skip number parsing if the value consists entirely of digits
},
tagValueProcessor: (tagName, tagValue = '') => {
// Ensure that the Name tag is always treated as a string
if (tagName === 'Name') {
return tagValue.toString();
}
return tagValue;
},
ignoreAttributes: false // Ensure that all attributes are parsed
});
const parsedXmlRes = listBucketResultParser.parse(xml);
if (!parsedXmlRes.ListAllMyBucketsResult) {
throw new errors.InvalidXMLError('Missing tag: "ListAllMyBucketsResult"');
}
const {
ListAllMyBucketsResult: {
Buckets = {}
} = {}
} = parsedXmlRes;
if (Buckets.Bucket) {
result = (0, _helper.toArray)(Buckets.Bucket).map((bucket = {}) => {
const {
Name: bucketName,
CreationDate
} = bucket;
const creationDate = new Date(CreationDate);
return {
name: bucketName,
creationDate
};
});
}
return result;
}
function parseInitiateMultipart(xml) {
let xmlobj = (0, _helper.parseXml)(xml);
if (!xmlobj.InitiateMultipartUploadResult) {
throw new errors.InvalidXMLError('Missing tag: "InitiateMultipartUploadResult"');
}
xmlobj = xmlobj.InitiateMultipartUploadResult;
if (xmlobj.UploadId) {
return xmlobj.UploadId;
}
throw new errors.InvalidXMLError('Missing tag: "UploadId"');
}
function parseReplicationConfig(xml) {
const xmlObj = (0, _helper.parseXml)(xml);
const {
Role,
Rule
} = xmlObj.ReplicationConfiguration;
return {
ReplicationConfiguration: {
role: Role,
rules: (0, _helper.toArray)(Rule)
}
};
}
function parseObjectLegalHoldConfig(xml) {
const xmlObj = (0, _helper.parseXml)(xml);
return xmlObj.LegalHold;
}
function parseTagging(xml) {
const xmlObj = (0, _helper.parseXml)(xml);
let result = [];
if (xmlObj.Tagging && xmlObj.Tagging.TagSet && xmlObj.Tagging.TagSet.Tag) {
const tagResult = xmlObj.Tagging.TagSet.Tag;
// if it is a single tag convert into an array so that the return value is always an array.
if ((0, _helper.isObject)(tagResult)) {
result.push(tagResult);
} else {
result = tagResult;
}
}
return result;
}
// parse XML response when a multipart upload is completed
function parseCompleteMultipart(xml) {
const xmlobj = (0, _helper.parseXml)(xml).CompleteMultipartUploadResult;
if (xmlobj.Location) {
const location = (0, _helper.toArray)(xmlobj.Location)[0];
const bucket = (0, _helper.toArray)(xmlobj.Bucket)[0];
const key = xmlobj.Key;
const etag = xmlobj.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^&quot;/g, '').replace(/&quot;$/g, '').replace(/^&#34;/g, '').replace(/&#34;$/g, '');
return {
location,
bucket,
key,
etag
};
}
// Complete Multipart can return XML Error after a 200 OK response
if (xmlobj.Code && xmlobj.Message) {
const errCode = (0, _helper.toArray)(xmlobj.Code)[0];
const errMessage = (0, _helper.toArray)(xmlobj.Message)[0];
return {
errCode,
errMessage
};
}
}
// parse XML response for listing in-progress multipart uploads
function parseListMultipart(xml) {
const result = {
prefixes: [],
uploads: [],
isTruncated: false,
nextKeyMarker: '',
nextUploadIdMarker: ''
};
let xmlobj = (0, _helper.parseXml)(xml);
if (!xmlobj.ListMultipartUploadsResult) {
throw new errors.InvalidXMLError('Missing tag: "ListMultipartUploadsResult"');
}
xmlobj = xmlobj.ListMultipartUploadsResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextKeyMarker) {
result.nextKeyMarker = xmlobj.NextKeyMarker;
}
if (xmlobj.NextUploadIdMarker) {
result.nextUploadIdMarker = xmlobj.nextUploadIdMarker || '';
}
if (xmlobj.CommonPrefixes) {
(0, _helper.toArray)(xmlobj.CommonPrefixes).forEach(prefix => {
// @ts-expect-error index check
result.prefixes.push({
prefix: (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(prefix.Prefix)[0])
});
});
}
if (xmlobj.Upload) {
(0, _helper.toArray)(xmlobj.Upload).forEach(upload => {
const uploadItem = {
key: upload.Key,
uploadId: upload.UploadId,
storageClass: upload.StorageClass,
initiated: new Date(upload.Initiated)
};
if (upload.Initiator) {
uploadItem.initiator = {
id: upload.Initiator.ID,
displayName: upload.Initiator.DisplayName
};
}
if (upload.Owner) {
uploadItem.owner = {
id: upload.Owner.ID,
displayName: upload.Owner.DisplayName
};
}
result.uploads.push(uploadItem);
});
}
return result;
}
function parseObjectLockConfig(xml) {
const xmlObj = (0, _helper.parseXml)(xml);
let lockConfigResult = {};
if (xmlObj.ObjectLockConfiguration) {
lockConfigResult = {
objectLockEnabled: xmlObj.ObjectLockConfiguration.ObjectLockEnabled
};
let retentionResp;
if (xmlObj.ObjectLockConfiguration && xmlObj.ObjectLockConfiguration.Rule && xmlObj.ObjectLockConfiguration.Rule.DefaultRetention) {
retentionResp = xmlObj.ObjectLockConfiguration.Rule.DefaultRetention || {};
lockConfigResult.mode = retentionResp.Mode;
}
if (retentionResp) {
const isUnitYears = retentionResp.Years;
if (isUnitYears) {
lockConfigResult.validity = isUnitYears;
lockConfigResult.unit = _type.RETENTION_VALIDITY_UNITS.YEARS;
} else {
lockConfigResult.validity = retentionResp.Days;
lockConfigResult.unit = _type.RETENTION_VALIDITY_UNITS.DAYS;
}
}
}
return lockConfigResult;
}
function parseBucketVersioningConfig(xml) {
const xmlObj = (0, _helper.parseXml)(xml);
return xmlObj.VersioningConfiguration;
}
// Used only in selectObjectContent API.
// extractHeaderType extracts the first half of the header message, the header type.
function extractHeaderType(stream) {
const headerNameLen = Buffer.from(stream.read(1)).readUInt8();
const headerNameWithSeparator = Buffer.from(stream.read(headerNameLen)).toString();
const splitBySeparator = (headerNameWithSeparator || '').split(':');
return splitBySeparator.length >= 1 ? splitBySeparator[1] : '';
}
function extractHeaderValue(stream) {
const bodyLen = Buffer.from(stream.read(2)).readUInt16BE();
return Buffer.from(stream.read(bodyLen)).toString();
}
function parseSelectObjectContentResponse(res) {
const selectResults = new _helpers.SelectResults({}); // will be returned
const responseStream = (0, _helper.readableStream)(res); // convert byte array to a readable responseStream
// @ts-ignore
while (responseStream._readableState.length) {
// Top level responseStream read tracker.
let msgCrcAccumulator; // accumulate from start of the message till the message crc start.
const totalByteLengthBuffer = Buffer.from(responseStream.read(4));
msgCrcAccumulator = _bufferCrc(totalByteLengthBuffer);
const headerBytesBuffer = Buffer.from(responseStream.read(4));
msgCrcAccumulator = _bufferCrc(headerBytesBuffer, msgCrcAccumulator);
const calculatedPreludeCrc = msgCrcAccumulator.readInt32BE(); // use it to check if any CRC mismatch in header itself.
const preludeCrcBuffer = Buffer.from(responseStream.read(4)); // read 4 bytes i.e 4+4 =8 + 4 = 12 ( prelude + prelude crc)
msgCrcAccumulator = _bufferCrc(preludeCrcBuffer, msgCrcAccumulator);
const totalMsgLength = totalByteLengthBuffer.readInt32BE();
const headerLength = headerBytesBuffer.readInt32BE();
const preludeCrcByteValue = preludeCrcBuffer.readInt32BE();
if (preludeCrcByteValue !== calculatedPreludeCrc) {
// Handle Header CRC mismatch Error
throw new Error(`Header Checksum Mismatch, Prelude CRC of ${preludeCrcByteValue} does not equal expected CRC of ${calculatedPreludeCrc}`);
}
const headers = {};
if (headerLength > 0) {
const headerBytes = Buffer.from(responseStream.read(headerLength));
msgCrcAccumulator = _bufferCrc(headerBytes, msgCrcAccumulator);
const headerReaderStream = (0, _helper.readableStream)(headerBytes);
// @ts-ignore
while (headerReaderStream._readableState.length) {
const headerTypeName = extractHeaderType(headerReaderStream);
headerReaderStream.read(1); // just read and ignore it.
if (headerTypeName) {
headers[headerTypeName] = extractHeaderValue(headerReaderStream);
}
}
}
let payloadStream;
const payLoadLength = totalMsgLength - headerLength - 16;
if (payLoadLength > 0) {
const payLoadBuffer = Buffer.from(responseStream.read(payLoadLength));
msgCrcAccumulator = _bufferCrc(payLoadBuffer, msgCrcAccumulator);
// read the checksum early and detect any mismatch so we can avoid unnecessary further processing.
const messageCrcByteValue = Buffer.from(responseStream.read(4)).readInt32BE();
const calculatedCrc = msgCrcAccumulator.readInt32BE();
// Handle message CRC Error
if (messageCrcByteValue !== calculatedCrc) {
throw new Error(`Message Checksum Mismatch, Message CRC of ${messageCrcByteValue} does not equal expected CRC of ${calculatedCrc}`);
}
payloadStream = (0, _helper.readableStream)(payLoadBuffer);
}
const messageType = headers['message-type'];
switch (messageType) {
case 'error':
{
const errorMessage = headers['error-code'] + ':"' + headers['error-message'] + '"';
throw new Error(errorMessage);
}
case 'event':
{
const contentType = headers['content-type'];
const eventType = headers['event-type'];
switch (eventType) {
case 'End':
{
selectResults.setResponse(res);
return selectResults;
}
case 'Records':
{
var _payloadStream;
const readData = (_payloadStream = payloadStream) === null || _payloadStream === void 0 ? void 0 : _payloadStream.read(payLoadLength);
selectResults.setRecords(readData);
break;
}
case 'Progress':
{
switch (contentType) {
case 'text/xml':
{
var _payloadStream2;
const progressData = (_payloadStream2 = payloadStream) === null || _payloadStream2 === void 0 ? void 0 : _payloadStream2.read(payLoadLength);
selectResults.setProgress(progressData.toString());
break;
}
default:
{
const errorMessage = `Unexpected content-type ${contentType} sent for event-type Progress`;
throw new Error(errorMessage);
}
}
}
break;
case 'Stats':
{
switch (contentType) {
case 'text/xml':
{
var _payloadStream3;
const statsData = (_payloadStream3 = payloadStream) === null || _payloadStream3 === void 0 ? void 0 : _payloadStream3.read(payLoadLength);
selectResults.setStats(statsData.toString());
break;
}
default:
{
const errorMessage = `Unexpected content-type ${contentType} sent for event-type Stats`;
throw new Error(errorMessage);
}
}
}
break;
default:
{
// Continuation message: Not sure if it is supported. did not find a reference or any message in response.
// It does not have a payload.
const warningMessage = `Un implemented event detected ${messageType}.`;
// eslint-disable-next-line no-console
console.warn(warningMessage);
}
}
}
}
}
}
function parseLifecycleConfig(xml) {
const xmlObj = (0, _helper.parseXml)(xml);
return xmlObj.LifecycleConfiguration;
}
function parseBucketEncryptionConfig(xml) {
return (0, _helper.parseXml)(xml);
}
function parseObjectRetentionConfig(xml) {
const xmlObj = (0, _helper.parseXml)(xml);
const retentionConfig = xmlObj.Retention;
return {
mode: retentionConfig.Mode,
retainUntilDate: retentionConfig.RetainUntilDate
};
}
function removeObjectsParser(xml) {
const xmlObj = (0, _helper.parseXml)(xml);
if (xmlObj.DeleteResult && xmlObj.DeleteResult.Error) {
// return errors as array always. as the response is object in case of single object passed in removeObjects
return (0, _helper.toArray)(xmlObj.DeleteResult.Error);
}
return [];
}
// parse XML response for copy object
function parseCopyObject(xml) {
const result = {
etag: '',
lastModified: ''
};
let xmlobj = (0, _helper.parseXml)(xml);
if (!xmlobj.CopyObjectResult) {
throw new errors.InvalidXMLError('Missing tag: "CopyObjectResult"');
}
xmlobj = xmlobj.CopyObjectResult;
if (xmlobj.ETag) {
result.etag = xmlobj.ETag.replace(/^"/g, '').replace(/"$/g, '').replace(/^&quot;/g, '').replace(/&quot;$/g, '').replace(/^&#34;/g, '').replace(/&#34;$/g, '');
}
if (xmlobj.LastModified) {
result.lastModified = new Date(xmlobj.LastModified);
}
return result;
}
const formatObjInfo = (content, opts = {}) => {
const {
Key,
LastModified,
ETag,
Size,
VersionId,
IsLatest
} = content;
if (!(0, _helper.isObject)(opts)) {
opts = {};
}
const name = (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(Key)[0] || '');
const lastModified = LastModified ? new Date((0, _helper.toArray)(LastModified)[0] || '') : undefined;
const etag = (0, _helper.sanitizeETag)((0, _helper.toArray)(ETag)[0] || '');
const size = (0, _helper.sanitizeSize)(Size || '');
return {
name,
lastModified,
etag,
size,
versionId: VersionId,
isLatest: IsLatest,
isDeleteMarker: opts.IsDeleteMarker ? opts.IsDeleteMarker : false
};
};
// parse XML response for list objects in a bucket
function parseListObjects(xml) {
const result = {
objects: [],
isTruncated: false,
nextMarker: undefined,
versionIdMarker: undefined
};
let isTruncated = false;
let nextMarker, nextVersionKeyMarker;
const xmlobj = fxpWithoutNumParser.parse(xml);
const parseCommonPrefixesEntity = commonPrefixEntry => {
if (commonPrefixEntry) {
(0, _helper.toArray)(commonPrefixEntry).forEach(commonPrefix => {
result.objects.push({
prefix: (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(commonPrefix.Prefix)[0] || ''),
size: 0
});
});
}
};
const listBucketResult = xmlobj.ListBucketResult;
const listVersionsResult = xmlobj.ListVersionsResult;
if (listBucketResult) {
if (listBucketResult.IsTruncated) {
isTruncated = listBucketResult.IsTruncated;
}
if (listBucketResult.Contents) {
(0, _helper.toArray)(listBucketResult.Contents).forEach(content => {
const name = (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(content.Key)[0] || '');
const lastModified = new Date((0, _helper.toArray)(content.LastModified)[0] || '');
const etag = (0, _helper.sanitizeETag)((0, _helper.toArray)(content.ETag)[0] || '');
const size = (0, _helper.sanitizeSize)(content.Size || '');
result.objects.push({
name,
lastModified,
etag,
size
});
});
}
if (listBucketResult.Marker) {
nextMarker = listBucketResult.Marker;
} else if (isTruncated && result.objects.length > 0) {
var _result$objects;
nextMarker = (_result$objects = result.objects[result.objects.length - 1]) === null || _result$objects === void 0 ? void 0 : _result$objects.name;
}
if (listBucketResult.CommonPrefixes) {
parseCommonPrefixesEntity(listBucketResult.CommonPrefixes);
}
}
if (listVersionsResult) {
if (listVersionsResult.IsTruncated) {
isTruncated = listVersionsResult.IsTruncated;
}
if (listVersionsResult.Version) {
(0, _helper.toArray)(listVersionsResult.Version).forEach(content => {
result.objects.push(formatObjInfo(content));
});
}
if (listVersionsResult.DeleteMarker) {
(0, _helper.toArray)(listVersionsResult.DeleteMarker).forEach(content => {
result.objects.push(formatObjInfo(content, {
IsDeleteMarker: true
}));
});
}
if (listVersionsResult.NextKeyMarker) {
nextVersionKeyMarker = listVersionsResult.NextKeyMarker;
}
if (listVersionsResult.NextVersionIdMarker) {
result.versionIdMarker = listVersionsResult.NextVersionIdMarker;
}
if (listVersionsResult.CommonPrefixes) {
parseCommonPrefixesEntity(listVersionsResult.CommonPrefixes);
}
}
result.isTruncated = isTruncated;
if (isTruncated) {
result.nextMarker = nextVersionKeyMarker || nextMarker;
}
return result;
}
function uploadPartParser(xml) {
const xmlObj = (0, _helper.parseXml)(xml);
const respEl = xmlObj.CopyPartResult;
return respEl;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfYnVmZmVyQ3JjIiwicmVxdWlyZSIsIl9mYXN0WG1sUGFyc2VyIiwiZXJyb3JzIiwiX2ludGVyb3BSZXF1aXJlV2lsZGNhcmQ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1lc3NhZ2VUeXBlIiwiZXJyb3JNZXNzYWdlIiwiY29udGVudFR5cGUiLCJldmVudFR5cGUiLCJzZXRSZXNwb25zZSIsIl9wYXlsb2FkU3RyZWFtIiwicmVhZERhdGEiLCJzZXRSZWNvcmRzIiwiX3BheWxvYWRTdHJlYW0yIiwicHJvZ3Jlc3NEYXRhIiwic2V0UHJvZ3Jlc3MiLCJfcGF5bG9hZFN0cmVhbTMiLCJzdGF0c0RhdGEiLCJzZXRTdGF0cyIsIndhcm5pbmdNZXNzYWdlIiwiY29uc29sZSIsIndhcm4iLCJwYXJzZUxpZmVjeWNsZUNvbmZpZyIsIkxpZmVjeWNsZUNvbmZpZ3VyYXRpb24iLCJwYXJzZUJ1Y2tldEVuY3J5cHRpb25Db25maWciLCJwYXJzZU9iamVjdFJldGVudGlvbkNvbmZpZyIsInJldGVudGlvbkNvbmZpZyIsIlJldGVudGlvbiIsInJldGFpblVudGlsRGF0ZSIsIlJldGFpblVudGlsRGF0ZSIsInJlbW92ZU9 Line truncated
+66
View File
@@ -0,0 +1,66 @@
// imported from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/93cfb0ec069731dcdfc31464788613f7cddb8192/types/minio/index.d.ts
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { LEGAL_HOLD_STATUS, RETENTION_MODES, RETENTION_VALIDITY_UNITS } from "./helpers.js";
import type { ClientOptions, NoResultCallback, RemoveOptions } from "./internal/client.js";
import { TypedClient } from "./internal/client.js";
import { CopyConditions } from "./internal/copy-conditions.js";
import { PostPolicy } from "./internal/post-policy.js";
import type { BucketItem, BucketItemCopy, BucketItemFromList, BucketItemStat, BucketItemWithMetadata, BucketStream, EmptyObject, ExistingObjectReplication, GetObjectLegalHoldOptions, IncompleteUploadedBucketItem, InputSerialization, IsoDate, ItemBucketMetadata, ItemBucketMetadataList, LegalHoldStatus, LifecycleConfig, LifecycleRule, MetadataItem, ObjectLockInfo, OutputSerialization, PutObjectLegalHoldOptions, ReplicaModifications, ReplicationConfig, ReplicationConfigOpts, ReplicationRule, ReplicationRuleAnd, ReplicationRuleDestination, ReplicationRuleFilter, ReplicationRuleStatus, ResultCallback, Retention, RetentionOptions, ScanRange, SelectOptions, SelectProgress, SourceSelectionCriteria, Tag } from "./internal/type.js";
import type { NotificationConfig, NotificationEvent, NotificationPoller } from "./notification.js";
export * from "./errors.js";
export * from "./helpers.js";
export type { Region } from "./internal/s3-endpoints.js";
export type * from "./notification.js";
export * from "./notification.js";
export { CopyConditions, PostPolicy };
export type { MakeBucketOpt } from "./internal/client.js";
export type { BucketItem, BucketItemCopy, BucketItemFromList, BucketItemStat, BucketItemWithMetadata, BucketStream, ClientOptions, EmptyObject, ExistingObjectReplication, GetObjectLegalHoldOptions, IncompleteUploadedBucketItem, InputSerialization, IsoDate, ItemBucketMetadata, ItemBucketMetadataList, LegalHoldStatus, LifecycleConfig, LifecycleRule, MetadataItem, NoResultCallback, ObjectLockInfo, OutputSerialization, PutObjectLegalHoldOptions, RemoveOptions, ReplicaModifications, ReplicationConfig, ReplicationConfigOpts, ReplicationRule, ReplicationRuleAnd, ReplicationRuleDestination, ReplicationRuleFilter, ReplicationRuleStatus, Retention, RetentionOptions, ScanRange, SelectOptions, SelectProgress, SourceSelectionCriteria, Tag };
/**
* @deprecated keep for backward compatible, use `RETENTION_MODES` instead
*/
export type Mode = RETENTION_MODES;
/**
* @deprecated keep for backward compatible
*/
export type LockUnit = RETENTION_VALIDITY_UNITS;
export type VersioningConfig = Record<string | number | symbol, unknown>;
export type TagList = Record<string, string>;
export interface PostPolicyResult {
postURL: string;
formData: {
[key: string]: any;
};
}
export interface LockConfig {
mode: RETENTION_MODES;
unit: RETENTION_VALIDITY_UNITS;
validity: number;
}
export interface LegalHoldOptions {
versionId: string;
status: LEGAL_HOLD_STATUS;
}
export interface SourceObjectStats {
size: number;
metaData: string;
lastModicied: Date;
versionId: string;
etag: string;
}
// Exports from library
export class Client extends TypedClient {
listObjectsV2(bucketName: string, prefix?: string, recursive?: boolean, startAfter?: string): BucketStream<BucketItem>;
// Bucket Policy & Notification operations
getBucketNotification(bucketName: string, callback: ResultCallback<NotificationConfig>): void;
getBucketNotification(bucketName: string): Promise<NotificationConfig>;
setBucketNotification(bucketName: string, bucketNotificationConfig: NotificationConfig, callback: NoResultCallback): void;
setBucketNotification(bucketName: string, bucketNotificationConfig: NotificationConfig): Promise<void>;
removeAllBucketNotification(bucketName: string, callback: NoResultCallback): void;
removeAllBucketNotification(bucketName: string): Promise<void>;
listenBucketNotification(bucketName: string, prefix: string, suffix: string, events: NotificationEvent[]): NotificationPoller;
}
+338
View File
@@ -0,0 +1,338 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
Client: true,
CopyConditions: true,
PostPolicy: true
};
var Stream = _interopRequireWildcard(require("stream"), true);
var _xml2js = require("xml2js");
var errors = _interopRequireWildcard(require("./errors.js"), true);
Object.keys(errors).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === errors[key]) return;
exports[key] = errors[key];
});
var _callbackify = require("./internal/callbackify.js");
var _client = require("./internal/client.js");
var _copyConditions = require("./internal/copy-conditions.js");
exports.CopyConditions = _copyConditions.CopyConditions;
var _helper = require("./internal/helper.js");
var _postPolicy = require("./internal/post-policy.js");
exports.PostPolicy = _postPolicy.PostPolicy;
var _notification = require("./notification.js");
Object.keys(_notification).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _notification[key]) return;
exports[key] = _notification[key];
});
var _promisify = require("./promisify.js");
var transformers = _interopRequireWildcard(require("./transformers.js"), true);
var _helpers = require("./helpers.js");
Object.keys(_helpers).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _helpers[key]) return;
exports[key] = _helpers[key];
});
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class Client extends _client.TypedClient {
//
// __Arguments__
// * `appName` _string_ - Application name.
// * `appVersion` _string_ - Application version.
// listObjectsV2Query - (List Objects V2) - List some or all (up to 1000) of the objects in a bucket.
//
// You can use the request parameters as selection criteria to return a subset of the objects in a bucket.
// request parameters :-
// * `bucketName` _string_: name of the bucket
// * `prefix` _string_: Limits the response to keys that begin with the specified prefix.
// * `continuation-token` _string_: Used to continue iterating over a set of objects.
// * `delimiter` _string_: A delimiter is a character you use to group keys.
// * `max-keys` _number_: Sets the maximum number of keys returned in the response body.
// * `start-after` _string_: Specifies the key to start after when listing objects in a bucket.
listObjectsV2Query(bucketName, prefix, continuationToken, delimiter, maxKeys, startAfter) {
if (!(0, _helper.isValidBucketName)(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!(0, _helper.isString)(prefix)) {
throw new TypeError('prefix should be of type "string"');
}
if (!(0, _helper.isString)(continuationToken)) {
throw new TypeError('continuationToken should be of type "string"');
}
if (!(0, _helper.isString)(delimiter)) {
throw new TypeError('delimiter should be of type "string"');
}
if (!(0, _helper.isNumber)(maxKeys)) {
throw new TypeError('maxKeys should be of type "number"');
}
if (!(0, _helper.isString)(startAfter)) {
throw new TypeError('startAfter should be of type "string"');
}
var queries = [];
// Call for listing objects v2 API
queries.push(`list-type=2`);
queries.push(`encoding-type=url`);
// escape every value in query string, except maxKeys
queries.push(`prefix=${(0, _helper.uriEscape)(prefix)}`);
queries.push(`delimiter=${(0, _helper.uriEscape)(delimiter)}`);
if (continuationToken) {
continuationToken = (0, _helper.uriEscape)(continuationToken);
queries.push(`continuation-token=${continuationToken}`);
}
// Set start-after
if (startAfter) {
startAfter = (0, _helper.uriEscape)(startAfter);
queries.push(`start-after=${startAfter}`);
}
// no need to escape maxKeys
if (maxKeys) {
if (maxKeys >= 1000) {
maxKeys = 1000;
}
queries.push(`max-keys=${maxKeys}`);
}
queries.sort();
var query = '';
if (queries.length > 0) {
query = `${queries.join('&')}`;
}
var method = 'GET';
var transformer = transformers.getListObjectsV2Transformer();
this.makeRequest({
method,
bucketName,
query
}, '', [200], '', true, (e, response) => {
if (e) {
return transformer.emit('error', e);
}
(0, _helper.pipesetup)(response, transformer);
});
return transformer;
}
// List the objects in the bucket using S3 ListObjects V2
//
// __Arguments__
// * `bucketName` _string_: name of the bucket
// * `prefix` _string_: the prefix of the objects that should be listed (optional, default `''`)
// * `recursive` _bool_: `true` indicates recursive style listing and `false` indicates directory style listing delimited by '/'. (optional, default `false`)
// * `startAfter` _string_: Specifies the key to start after when listing objects in a bucket. (optional, default `''`)
//
// __Return Value__
// * `stream` _Stream_: stream emitting the objects in the bucket, the object is of the format:
// * `obj.name` _string_: name of the object
// * `obj.prefix` _string_: name of the object prefix
// * `obj.size` _number_: size of the object
// * `obj.etag` _string_: etag of the object
// * `obj.lastModified` _Date_: modified time stamp
listObjectsV2(bucketName, prefix, recursive, startAfter) {
if (prefix === undefined) {
prefix = '';
}
if (recursive === undefined) {
recursive = false;
}
if (startAfter === undefined) {
startAfter = '';
}
if (!(0, _helper.isValidBucketName)(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!(0, _helper.isValidPrefix)(prefix)) {
throw new errors.InvalidPrefixError(`Invalid prefix : ${prefix}`);
}
if (!(0, _helper.isString)(prefix)) {
throw new TypeError('prefix should be of type "string"');
}
if (!(0, _helper.isBoolean)(recursive)) {
throw new TypeError('recursive should be of type "boolean"');
}
if (!(0, _helper.isString)(startAfter)) {
throw new TypeError('startAfter should be of type "string"');
}
// if recursive is false set delimiter to '/'
var delimiter = recursive ? '' : '/';
var continuationToken = '';
var objects = [];
var ended = false;
var readStream = Stream.Readable({
objectMode: true
});
readStream._read = () => {
// push one object per _read()
if (objects.length) {
readStream.push(objects.shift());
return;
}
if (ended) {
return readStream.push(null);
}
// if there are no objects to push do query for the next batch of objects
this.listObjectsV2Query(bucketName, prefix, continuationToken, delimiter, 1000, startAfter).on('error', e => readStream.emit('error', e)).on('data', result => {
if (result.isTruncated) {
continuationToken = result.nextContinuationToken;
} else {
ended = true;
}
objects = result.objects;
readStream._read();
});
};
return readStream;
}
// Remove all the notification configurations in the S3 provider
setBucketNotification(bucketName, config, cb) {
if (!(0, _helper.isValidBucketName)(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!(0, _helper.isObject)(config)) {
throw new TypeError('notification config should be of type "Object"');
}
if (!(0, _helper.isFunction)(cb)) {
throw new TypeError('callback should be of type "function"');
}
var method = 'PUT';
var query = 'notification';
var builder = new _xml2js.Builder({
rootName: 'NotificationConfiguration',
renderOpts: {
pretty: false
},
headless: true
});
var payload = builder.buildObject(config);
this.makeRequest({
method,
bucketName,
query
}, payload, [200], '', false, cb);
}
removeAllBucketNotification(bucketName, cb) {
this.setBucketNotification(bucketName, new _notification.NotificationConfig(), cb);
}
// Return the list of notification configurations stored
// in the S3 provider
getBucketNotification(bucketName, cb) {
if (!(0, _helper.isValidBucketName)(bucketName)) {
throw new errors.InvalidBucketNameError('Invalid bucket name: ' + bucketName);
}
if (!(0, _helper.isFunction)(cb)) {
throw new TypeError('callback should be of type "function"');
}
var method = 'GET';
var query = 'notification';
this.makeRequest({
method,
bucketName,
query
}, '', [200], '', true, (e, response) => {
if (e) {
return cb(e);
}
var transformer = transformers.getBucketNotificationTransformer();
var bucketNotification;
(0, _helper.pipesetup)(response, transformer).on('data', result => bucketNotification = result).on('error', e => cb(e)).on('end', () => cb(null, bucketNotification));
});
}
// Listens for bucket notifications. Returns an EventEmitter.
listenBucketNotification(bucketName, prefix, suffix, events) {
if (!(0, _helper.isValidBucketName)(bucketName)) {
throw new errors.InvalidBucketNameError(`Invalid bucket name: ${bucketName}`);
}
if (!(0, _helper.isString)(prefix)) {
throw new TypeError('prefix must be of type string');
}
if (!(0, _helper.isString)(suffix)) {
throw new TypeError('suffix must be of type string');
}
if (!Array.isArray(events)) {
throw new TypeError('events must be of type Array');
}
let listener = new _notification.NotificationPoller(this, bucketName, prefix, suffix, events);
listener.start();
return listener;
}
}
exports.Client = Client;
Client.prototype.getBucketNotification = (0, _promisify.promisify)(Client.prototype.getBucketNotification);
Client.prototype.setBucketNotification = (0, _promisify.promisify)(Client.prototype.setBucketNotification);
Client.prototype.removeAllBucketNotification = (0, _promisify.promisify)(Client.prototype.removeAllBucketNotification);
// refactored API use promise internally
Client.prototype.makeBucket = (0, _callbackify.callbackify)(Client.prototype.makeBucket);
Client.prototype.bucketExists = (0, _callbackify.callbackify)(Client.prototype.bucketExists);
Client.prototype.removeBucket = (0, _callbackify.callbackify)(Client.prototype.removeBucket);
Client.prototype.listBuckets = (0, _callbackify.callbackify)(Client.prototype.listBuckets);
Client.prototype.getObject = (0, _callbackify.callbackify)(Client.prototype.getObject);
Client.prototype.fGetObject = (0, _callbackify.callbackify)(Client.prototype.fGetObject);
Client.prototype.getPartialObject = (0, _callbackify.callbackify)(Client.prototype.getPartialObject);
Client.prototype.statObject = (0, _callbackify.callbackify)(Client.prototype.statObject);
Client.prototype.putObjectRetention = (0, _callbackify.callbackify)(Client.prototype.putObjectRetention);
Client.prototype.putObject = (0, _callbackify.callbackify)(Client.prototype.putObject);
Client.prototype.fPutObject = (0, _callbackify.callbackify)(Client.prototype.fPutObject);
Client.prototype.removeObject = (0, _callbackify.callbackify)(Client.prototype.removeObject);
Client.prototype.removeBucketReplication = (0, _callbackify.callbackify)(Client.prototype.removeBucketReplication);
Client.prototype.setBucketReplication = (0, _callbackify.callbackify)(Client.prototype.setBucketReplication);
Client.prototype.getBucketReplication = (0, _callbackify.callbackify)(Client.prototype.getBucketReplication);
Client.prototype.getObjectLegalHold = (0, _callbackify.callbackify)(Client.prototype.getObjectLegalHold);
Client.prototype.setObjectLegalHold = (0, _callbackify.callbackify)(Client.prototype.setObjectLegalHold);
Client.prototype.setObjectLockConfig = (0, _callbackify.callbackify)(Client.prototype.setObjectLockConfig);
Client.prototype.getObjectLockConfig = (0, _callbackify.callbackify)(Client.prototype.getObjectLockConfig);
Client.prototype.getBucketPolicy = (0, _callbackify.callbackify)(Client.prototype.getBucketPolicy);
Client.prototype.setBucketPolicy = (0, _callbackify.callbackify)(Client.prototype.setBucketPolicy);
Client.prototype.getBucketTagging = (0, _callbackify.callbackify)(Client.prototype.getBucketTagging);
Client.prototype.getObjectTagging = (0, _callbackify.callbackify)(Client.prototype.getObjectTagging);
Client.prototype.setBucketTagging = (0, _callbackify.callbackify)(Client.prototype.setBucketTagging);
Client.prototype.removeBucketTagging = (0, _callbackify.callbackify)(Client.prototype.removeBucketTagging);
Client.prototype.setObjectTagging = (0, _callbackify.callbackify)(Client.prototype.setObjectTagging);
Client.prototype.removeObjectTagging = (0, _callbackify.callbackify)(Client.prototype.removeObjectTagging);
Client.prototype.getBucketVersioning = (0, _callbackify.callbackify)(Client.prototype.getBucketVersioning);
Client.prototype.setBucketVersioning = (0, _callbackify.callbackify)(Client.prototype.setBucketVersioning);
Client.prototype.selectObjectContent = (0, _callbackify.callbackify)(Client.prototype.selectObjectContent);
Client.prototype.setBucketLifecycle = (0, _callbackify.callbackify)(Client.prototype.setBucketLifecycle);
Client.prototype.getBucketLifecycle = (0, _callbackify.callbackify)(Client.prototype.getBucketLifecycle);
Client.prototype.removeBucketLifecycle = (0, _callbackify.callbackify)(Client.prototype.removeBucketLifecycle);
Client.prototype.setBucketEncryption = (0, _callbackify.callbackify)(Client.prototype.setBucketEncryption);
Client.prototype.getBucketEncryption = (0, _callbackify.callbackify)(Client.prototype.getBucketEncryption);
Client.prototype.removeBucketEncryption = (0, _callbackify.callbackify)(Client.prototype.removeBucketEncryption);
Client.prototype.getObjectRetention = (0, _callbackify.callbackify)(Client.prototype.getObjectRetention);
Client.prototype.removeObjects = (0, _callbackify.callbackify)(Client.prototype.removeObjects);
Client.prototype.removeIncompleteUpload = (0, _callbackify.callbackify)(Client.prototype.removeIncompleteUpload);
Client.prototype.copyObject = (0, _callbackify.callbackify)(Client.prototype.copyObject);
Client.prototype.composeObject = (0, _callbackify.callbackify)(Client.prototype.composeObject);
Client.prototype.presignedUrl = (0, _callbackify.callbackify)(Client.prototype.presignedUrl);
Client.prototype.presignedGetObject = (0, _callbackify.callbackify)(Client.prototype.presignedGetObject);
Client.prototype.presignedPutObject = (0, _callbackify.callbackify)(Client.prototype.presignedPutObject);
Client.prototype.presignedPostPolicy = (0, _callbackify.callbackify)(Client.prototype.presignedPostPolicy);
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJTdHJlYW0iLCJfaW50ZXJvcFJlcX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YWNraWZ5IH0gZnJvbSAnLi9pbnRlcm5hbC9jYWxsYmFja2lmeS5qcydcbmltcG9ydCB7IFR5cGVkQ2xpZW50IH0gZnJvbSAnLi9pbnRlcm5hbC9jbGllbnQudHMnXG5pbXBvcnQgeyBDb3B5Q29uZGl0aW9ucyB9IGZyb20gJy4vaW50ZXJuYWwvY29weS1jb25kaXRpb25zLnRzJ1xuaW1wb3J0IHtcbiAgaXNCb29sZWFuLFxuICBpc0Z1bmN0aW9uLFxuICBpc051bWJlcixcbiAgaXNPYmplY3QsXG4gIGlzU3RyaW5nLFxuICBpc1ZhbGlkQnVja2V0TmFtZSxcbiAgaXNWYWxpZFByZWZpeCxcbiAgcGlwZXNldHVwLFxuICB1cmlFc2NhcGUsXG59IGZyb20gJy4vaW50ZXJuYWwvaGVscGVyLnRzJ1xuaW1wb3J0IHsgUG9zdFBvbGljeSB9IGZyb20gJy4vaW50ZXJuYWwvcG9zdC1wb2xpY3kudHMnXG5pbXBvcnQgeyBOb3RpZmljYXRpb25Db25maWcsIE5vdGlmaWNhdGlvblBvbGxlciB9IGZyb20 Line truncated
+58
View File
@@ -0,0 +1,58 @@
import { EventEmitter } from 'eventemitter3';
import type { TypedClient } from "./internal/client.js";
type Event = unknown;
export declare class TargetConfig {
private Filter?;
private Event?;
private Id;
setId(id: unknown): void;
addEvent(newevent: Event): void;
addFilterSuffix(suffix: string): void;
addFilterPrefix(prefix: string): void;
}
export declare class TopicConfig extends TargetConfig {
private Topic;
constructor(arn: string);
}
export declare class QueueConfig extends TargetConfig {
private Queue;
constructor(arn: string);
}
export declare class CloudFunctionConfig extends TargetConfig {
private CloudFunction;
constructor(arn: string);
}
export declare class NotificationConfig {
private TopicConfiguration?;
private CloudFunctionConfiguration?;
private QueueConfiguration?;
add(target: TargetConfig): void;
}
export declare const buildARN: (partition: string, service: string, region: string, accountId: string, resource: string) => string;
export declare const ObjectCreatedAll = "s3:ObjectCreated:*";
export declare const ObjectCreatedPut = "s3:ObjectCreated:Put";
export declare const ObjectCreatedPost = "s3:ObjectCreated:Post";
export declare const ObjectCreatedCopy = "s3:ObjectCreated:Copy";
export declare const ObjectCreatedCompleteMultipartUpload = "s3:ObjectCreated:CompleteMultipartUpload";
export declare const ObjectRemovedAll = "s3:ObjectRemoved:*";
export declare const ObjectRemovedDelete = "s3:ObjectRemoved:Delete";
export declare const ObjectRemovedDeleteMarkerCreated = "s3:ObjectRemoved:DeleteMarkerCreated";
export declare const ObjectReducedRedundancyLostObject = "s3:ReducedRedundancyLostObject";
export type NotificationEvent = 's3:ObjectCreated:*' | 's3:ObjectCreated:Put' | 's3:ObjectCreated:Post' | 's3:ObjectCreated:Copy' | 's3:ObjectCreated:CompleteMultipartUpload' | 's3:ObjectRemoved:*' | 's3:ObjectRemoved:Delete' | 's3:ObjectRemoved:DeleteMarkerCreated' | 's3:ReducedRedundancyLostObject' | 's3:TestEvent' | 's3:ObjectRestore:Post' | 's3:ObjectRestore:Completed' | 's3:Replication:OperationFailedReplication' | 's3:Replication:OperationMissedThreshold' | 's3:Replication:OperationReplicatedAfterThreshold' | 's3:Replication:OperationNotTracked' | string;
export type NotificationRecord = unknown;
export declare class NotificationPoller extends EventEmitter<{
notification: (event: NotificationRecord) => void;
error: (error: unknown) => void;
}> {
private client;
private bucketName;
private prefix;
private suffix;
private events;
private ending;
constructor(client: TypedClient, bucketName: string, prefix: string, suffix: string, events: NotificationEvent[]);
start(): void;
stop(): void;
checkForChanges(): void;
}
export {};
+230
View File
@@ -0,0 +1,230 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _eventemitter = require("eventemitter3");
var _Parser = require("stream-json/jsonl/Parser.js");
var _helpers = require("./helpers.js");
var _helper = require("./internal/helper.js");
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO: type this
// Base class for three supported configs.
class TargetConfig {
setId(id) {
this.Id = id;
}
addEvent(newevent) {
if (!this.Event) {
this.Event = [];
}
this.Event.push(newevent);
}
addFilterSuffix(suffix) {
if (!this.Filter) {
this.Filter = {
S3Key: {
FilterRule: []
}
};
}
this.Filter.S3Key.FilterRule.push({
Name: 'suffix',
Value: suffix
});
}
addFilterPrefix(prefix) {
if (!this.Filter) {
this.Filter = {
S3Key: {
FilterRule: []
}
};
}
this.Filter.S3Key.FilterRule.push({
Name: 'prefix',
Value: prefix
});
}
}
// 1. Topic (simple notification service)
exports.TargetConfig = TargetConfig;
class TopicConfig extends TargetConfig {
constructor(arn) {
super();
this.Topic = arn;
}
}
// 2. Queue (simple queue service)
exports.TopicConfig = TopicConfig;
class QueueConfig extends TargetConfig {
constructor(arn) {
super();
this.Queue = arn;
}
}
// 3. CloudFront (lambda function)
exports.QueueConfig = QueueConfig;
class CloudFunctionConfig extends TargetConfig {
constructor(arn) {
super();
this.CloudFunction = arn;
}
}
// Notification config - array of target configs.
// Target configs can be
// 1. Topic (simple notification service)
// 2. Queue (simple queue service)
// 3. CloudFront (lambda function)
exports.CloudFunctionConfig = CloudFunctionConfig;
class NotificationConfig {
add(target) {
let instance;
if (target instanceof TopicConfig) {
instance = this.TopicConfiguration ?? (this.TopicConfiguration = []);
}
if (target instanceof QueueConfig) {
instance = this.QueueConfiguration ?? (this.QueueConfiguration = []);
}
if (target instanceof CloudFunctionConfig) {
instance = this.CloudFunctionConfiguration ?? (this.CloudFunctionConfiguration = []);
}
if (instance) {
instance.push(target);
}
}
}
exports.NotificationConfig = NotificationConfig;
const buildARN = (partition, service, region, accountId, resource) => {
return 'arn:' + partition + ':' + service + ':' + region + ':' + accountId + ':' + resource;
};
exports.buildARN = buildARN;
const ObjectCreatedAll = 's3:ObjectCreated:*';
exports.ObjectCreatedAll = ObjectCreatedAll;
const ObjectCreatedPut = 's3:ObjectCreated:Put';
exports.ObjectCreatedPut = ObjectCreatedPut;
const ObjectCreatedPost = 's3:ObjectCreated:Post';
exports.ObjectCreatedPost = ObjectCreatedPost;
const ObjectCreatedCopy = 's3:ObjectCreated:Copy';
exports.ObjectCreatedCopy = ObjectCreatedCopy;
const ObjectCreatedCompleteMultipartUpload = 's3:ObjectCreated:CompleteMultipartUpload';
exports.ObjectCreatedCompleteMultipartUpload = ObjectCreatedCompleteMultipartUpload;
const ObjectRemovedAll = 's3:ObjectRemoved:*';
exports.ObjectRemovedAll = ObjectRemovedAll;
const ObjectRemovedDelete = 's3:ObjectRemoved:Delete';
exports.ObjectRemovedDelete = ObjectRemovedDelete;
const ObjectRemovedDeleteMarkerCreated = 's3:ObjectRemoved:DeleteMarkerCreated';
exports.ObjectRemovedDeleteMarkerCreated = ObjectRemovedDeleteMarkerCreated;
const ObjectReducedRedundancyLostObject = 's3:ReducedRedundancyLostObject';
// put string at least so auto-complete could work
// TODO: type this
exports.ObjectReducedRedundancyLostObject = ObjectReducedRedundancyLostObject;
// Poll for notifications, used in #listenBucketNotification.
// Listening constitutes repeatedly requesting s3 whether or not any
// changes have occurred.
class NotificationPoller extends _eventemitter.EventEmitter {
constructor(client, bucketName, prefix, suffix, events) {
super();
this.client = client;
this.bucketName = bucketName;
this.prefix = prefix;
this.suffix = suffix;
this.events = events;
this.ending = false;
}
// Starts the polling.
start() {
this.ending = false;
process.nextTick(() => {
this.checkForChanges();
});
}
// Stops the polling.
stop() {
this.ending = true;
}
checkForChanges() {
// Don't continue if we're looping again but are cancelled.
if (this.ending) {
return;
}
const method = 'GET';
const queries = [];
if (this.prefix) {
const prefix = (0, _helper.uriEscape)(this.prefix);
queries.push(`prefix=${prefix}`);
}
if (this.suffix) {
const suffix = (0, _helper.uriEscape)(this.suffix);
queries.push(`suffix=${suffix}`);
}
if (this.events) {
this.events.forEach(s3event => queries.push('events=' + (0, _helper.uriEscape)(s3event)));
}
queries.sort();
let query = '';
if (queries.length > 0) {
query = `${queries.join('&')}`;
}
const region = this.client.region || _helpers.DEFAULT_REGION;
this.client.makeRequestAsync({
method,
bucketName: this.bucketName,
query
}, '', [200], region).then(response => {
const asm = _Parser.make();
(0, _helper.pipesetup)(response, asm).on('data', data => {
// Data is flushed periodically (every 5 seconds), so we should
// handle it after flushing from the JSON parser.
let records = data.value.Records;
// If null (= no records), change to an empty array.
if (!records) {
records = [];
}
// Iterate over the notifications and emit them individually.
records.forEach(record => {
this.emit('notification', record);
});
// If we're done, stop.
if (this.ending) {
response === null || response === void 0 ? void 0 : response.destroy();
}
}).on('error', e => this.emit('error', e)).on('end', () => {
// Do it again, if we haven't cancelled yet.
process.nextTick(() => {
this.checkForChanges();
});
});
}, e => {
return this.emit('error', e);
});
}
}
exports.NotificationPoller = NotificationPoller;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfZXZlbnRlbWl0dGVyIiwicmVxdWlyZSIsIl9QYXJzZXIiLCJfaGVscGVycyIsIl9oZWxwZXIiLCJUYXJnZXRDb25maWciLCJzZXRJZCIsImlkIiwiSWQiLCJhZGRFdmVudCIsIm5ld2V2ZW50IiwiRXZlbnQiLCJwdXNoIiwiYWRkRmlsdGVyU3VmZml4Iiwic3VmZml4IiwiRmlsdGVyIiwiUzNLZXkiLCJGaWx0ZXJSdWxlIiwiTmFtZSIsIlZhbHVlIiwiYWRkRmlsdGVyUHJlZml4IiwicHJlZml4IiwiZXhwb3J0cyIsIlRvcGljQ29uZmlnIiwiY29uc3RydWN0b3IiLCJhcm4iLCJUb3BpYyIsIlF1ZXVlQ29uZmlnIiwiUXVldWUiLCJDbG91ZEZ1bmN0aW9uQ29uZmlnIiwiQ2xvdWRGdW5jdGlvbiIsIk5vdGlmaWNhdGlvbkNvbmZpZyIsImFkZCIsInRhcmdldCIsImluc3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mlncyBjYW4gYmVcbi8vIDEuIFRvcGljIChzaW1wbGUgbm90aWZpY2F0aW9uIHNlcnZpY2UpXG4vLyAyLiBRdWV1ZSA Line truncated
+36
View File
@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.promisify = promisify;
// Returns a wrapper function that will promisify a given callback function.
// It will preserve 'this'.
function promisify(fn) {
return function () {
// If the last argument is a function, assume its the callback.
let callback = arguments[arguments.length - 1];
// If the callback is given, don't promisify, just pass straight in.
if (typeof callback === 'function') {
return fn.apply(this, arguments);
}
// Otherwise, create a new set of arguments, and wrap
// it in a promise.
let args = [...arguments];
return new Promise((resolve, reject) => {
// Add the callback function.
args.push((err, value) => {
if (err) {
return reject(err);
}
resolve(value);
});
// Call the function with our special adaptor callback added.
fn.apply(this, args);
});
};
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJwcm9taXNpZnkiLCJmbiIsImNhbGxiYWNrIiwiYXJndW1lbnRzIiwibGVuZ3RoIiwiYXBwbHkiLCJhcmdzIiwiUHJvbWlzZSIsInJlc29sdmUiLCJyZWplY3QiLCJwdXNoIiwiZXJyIiwidmFsdWUiXSwic291cmNlcyI6WyJwcm9taXNpZnkuanMiXSwic291cmNlc0NvbnRlbnQiOlsiLy8gUmV0dXJucyBhIHdyYXBwZXIgZnVuY3Rpb24gdGhhdCB3aWxsIHByb21pc2lmeSBhIGdpdmVuIGNhbGxiYWNrIGZ1bmN0aW9uLlxuLy8gSXQgd2lsbCBwcmVzZXJ2ZSAndGhpcycuXG5leHBvcnQgZnVuY3Rpb24gcHJvbWlzaWZ5KGZuKSB7XG4gIHJldHVybiBmdW5jdGlvbiAoKSB7XG4gICAgLy8gSWYgdGhlIGxhc3QgYXJndW1lbnQgaXMgYSBmdW5jdGlvbiwgYXNzdW1lIGl0cyB0aGUgY2FsbGJhY2suXG4gICAgbGV0IGNhbGxiYWNrID0gYXJndW1lbnR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FBUSxLQUFLLFVBQVUsRUFBRTtNQUNsQyxPQUFPRCxFQUFFLENBQUNJLEtBQUssQ0FBQyxJQUFJLEVBQUVGLFNBQVMsQ0FBQztJQUNsQzs7SUFFQTtJQUNBO0lBQ0EsSUFBSUcsSUFBSSxHQUFHLENBQUMsR0FBR0gsU0FBUyxDQUFDO0lBRXpCLE9BQU8sSUFBSUksT0FBTyxDQUFDLENBQUNDLE9BQU8sRUFBRUMsTUFBTSxLQUFLO01BQ3RDO01BQ0FILElBQUksQ0FBQ0ksSUFBSSxDQUFDLENBQUNDLEdBQUcsRUFBRUMsS0FBSyxLQUFLO1FBQ3hCLElBQUlELEdBQUcsRUFBRTtVQUNQLE9BQU9GLE1BQU0sQ0FBQ0UsR0FBRyxDQUFDO1FBQ3BCO1FBRUFILE9BQU8sQ0FBQ0ksS0FBSyxDQUFDO01BQ2hCLENBQUMsQ0FBQzs7TUFFRjtNQUNBWCxFQUFFLENBQUNJLEtBQUssQ0FBQyxJQUFJLEVBQUVDLElBQUksQ0FBQztJQUN0QixDQUFDLENBQUM7RUFDSixDQUFDO0FBQ0gifQ==
+5
View File
@@ -0,0 +1,5 @@
import type { IRequest } from "./internal/type.js";
export declare function postPresignSignatureV4(region: string, date: Date, secretKey: string, policyBase64: string): string;
export declare function signV4(request: IRequest, accessKey: string, secretKey: string, region: string, requestDate: Date, sha256sum: string, serviceName?: string): string;
export declare function signV4ByServiceName(request: IRequest, accessKey: string, secretKey: string, region: string, requestDate: Date, contentSha256: string, serviceName?: string): string;
export declare function presignSignatureV4(request: IRequest, accessKey: string, secretKey: string, sessionToken: string | undefined, region: string, requestDate: Date, expires: number | undefined): string;
+269
View File
@@ -0,0 +1,269 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.postPresignSignatureV4 = postPresignSignatureV4;
exports.presignSignatureV4 = presignSignatureV4;
exports.signV4 = signV4;
exports.signV4ByServiceName = signV4ByServiceName;
var crypto = _interopRequireWildcard(require("crypto"), true);
var errors = _interopRequireWildcard(require("./errors.js"), true);
var _helpers = require("./helpers.js");
var _helper = require("./internal/helper.js");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2016 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const signV4Algorithm = 'AWS4-HMAC-SHA256';
// getCanonicalRequest generate a canonical request of style.
//
// canonicalRequest =
// <HTTPMethod>\n
// <CanonicalURI>\n
// <CanonicalQueryString>\n
// <CanonicalHeaders>\n
// <SignedHeaders>\n
// <HashedPayload>
//
function getCanonicalRequest(method, path, headers, signedHeaders, hashedPayload) {
if (!(0, _helper.isString)(method)) {
throw new TypeError('method should be of type "string"');
}
if (!(0, _helper.isString)(path)) {
throw new TypeError('path should be of type "string"');
}
if (!(0, _helper.isObject)(headers)) {
throw new TypeError('headers should be of type "object"');
}
if (!Array.isArray(signedHeaders)) {
throw new TypeError('signedHeaders should be of type "array"');
}
if (!(0, _helper.isString)(hashedPayload)) {
throw new TypeError('hashedPayload should be of type "string"');
}
const headersArray = signedHeaders.reduce((acc, i) => {
// Trim spaces from the value (required by V4 spec)
const val = `${headers[i]}`.replace(/ +/g, ' ');
acc.push(`${i.toLowerCase()}:${val}`);
return acc;
}, []);
const requestResource = path.split('?')[0];
let requestQuery = path.split('?')[1];
if (!requestQuery) {
requestQuery = '';
}
if (requestQuery) {
requestQuery = requestQuery.split('&').sort().map(element => !element.includes('=') ? element + '=' : element).join('&');
}
return [method.toUpperCase(), requestResource, requestQuery, headersArray.join('\n') + '\n', signedHeaders.join(';').toLowerCase(), hashedPayload].join('\n');
}
// generate a credential string
function getCredential(accessKey, region, requestDate, serviceName = 's3') {
if (!(0, _helper.isString)(accessKey)) {
throw new TypeError('accessKey should be of type "string"');
}
if (!(0, _helper.isString)(region)) {
throw new TypeError('region should be of type "string"');
}
if (!(0, _helper.isObject)(requestDate)) {
throw new TypeError('requestDate should be of type "object"');
}
return `${accessKey}/${(0, _helper.getScope)(region, requestDate, serviceName)}`;
}
// Returns signed headers array - alphabetically sorted
function getSignedHeaders(headers) {
if (!(0, _helper.isObject)(headers)) {
throw new TypeError('request should be of type "object"');
}
// Excerpts from @lsegal - https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258
//
// User-Agent:
//
// This is ignored from signing because signing this causes problems with generating pre-signed URLs
// (that are executed by other agents) or when customers pass requests through proxies, which may
// modify the user-agent.
//
// Content-Length:
//
// This is ignored from signing because generating a pre-signed URL should not provide a content-length
// constraint, specifically when vending a S3 pre-signed PUT URL. The corollary to this is that when
// sending regular requests (non-pre-signed), the signature contains a checksum of the body, which
// implicitly validates the payload length (since changing the number of bytes would change the checksum)
// and therefore this header is not valuable in the signature.
//
// Content-Type:
//
// Signing this header causes quite a number of problems in browser environments, where browsers
// like to modify and normalize the content-type header in different ways. There is more information
// on this in https://github.com/aws/aws-sdk-js/issues/244. Avoiding this field simplifies logic
// and reduces the possibility of future bugs
//
// Authorization:
//
// Is skipped for obvious reasons
const ignoredHeaders = ['authorization', 'content-length', 'content-type', 'user-agent'];
return Object.keys(headers).filter(header => !ignoredHeaders.includes(header)).sort();
}
// returns the key used for calculating signature
function getSigningKey(date, region, secretKey, serviceName = 's3') {
if (!(0, _helper.isObject)(date)) {
throw new TypeError('date should be of type "object"');
}
if (!(0, _helper.isString)(region)) {
throw new TypeError('region should be of type "string"');
}
if (!(0, _helper.isString)(secretKey)) {
throw new TypeError('secretKey should be of type "string"');
}
const dateLine = (0, _helper.makeDateShort)(date);
const hmac1 = crypto.createHmac('sha256', 'AWS4' + secretKey).update(dateLine).digest(),
hmac2 = crypto.createHmac('sha256', hmac1).update(region).digest(),
hmac3 = crypto.createHmac('sha256', hmac2).update(serviceName).digest();
return crypto.createHmac('sha256', hmac3).update('aws4_request').digest();
}
// returns the string that needs to be signed
function getStringToSign(canonicalRequest, requestDate, region, serviceName = 's3') {
if (!(0, _helper.isString)(canonicalRequest)) {
throw new TypeError('canonicalRequest should be of type "string"');
}
if (!(0, _helper.isObject)(requestDate)) {
throw new TypeError('requestDate should be of type "object"');
}
if (!(0, _helper.isString)(region)) {
throw new TypeError('region should be of type "string"');
}
const hash = crypto.createHash('sha256').update(canonicalRequest).digest('hex');
const scope = (0, _helper.getScope)(region, requestDate, serviceName);
const stringToSign = [signV4Algorithm, (0, _helper.makeDateLong)(requestDate), scope, hash];
return stringToSign.join('\n');
}
// calculate the signature of the POST policy
function postPresignSignatureV4(region, date, secretKey, policyBase64) {
if (!(0, _helper.isString)(region)) {
throw new TypeError('region should be of type "string"');
}
if (!(0, _helper.isObject)(date)) {
throw new TypeError('date should be of type "object"');
}
if (!(0, _helper.isString)(secretKey)) {
throw new TypeError('secretKey should be of type "string"');
}
if (!(0, _helper.isString)(policyBase64)) {
throw new TypeError('policyBase64 should be of type "string"');
}
const signingKey = getSigningKey(date, region, secretKey);
return crypto.createHmac('sha256', signingKey).update(policyBase64).digest('hex').toLowerCase();
}
// Returns the authorization header
function signV4(request, accessKey, secretKey, region, requestDate, sha256sum, serviceName = 's3') {
if (!(0, _helper.isObject)(request)) {
throw new TypeError('request should be of type "object"');
}
if (!(0, _helper.isString)(accessKey)) {
throw new TypeError('accessKey should be of type "string"');
}
if (!(0, _helper.isString)(secretKey)) {
throw new TypeError('secretKey should be of type "string"');
}
if (!(0, _helper.isString)(region)) {
throw new TypeError('region should be of type "string"');
}
if (!accessKey) {
throw new errors.AccessKeyRequiredError('accessKey is required for signing');
}
if (!secretKey) {
throw new errors.SecretKeyRequiredError('secretKey is required for signing');
}
const signedHeaders = getSignedHeaders(request.headers);
const canonicalRequest = getCanonicalRequest(request.method, request.path, request.headers, signedHeaders, sha256sum);
const serviceIdentifier = serviceName || 's3';
const stringToSign = getStringToSign(canonicalRequest, requestDate, region, serviceIdentifier);
const signingKey = getSigningKey(requestDate, region, secretKey, serviceIdentifier);
const credential = getCredential(accessKey, region, requestDate, serviceIdentifier);
const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase();
return `${signV4Algorithm} Credential=${credential}, SignedHeaders=${signedHeaders.join(';').toLowerCase()}, Signature=${signature}`;
}
function signV4ByServiceName(request, accessKey, secretKey, region, requestDate, contentSha256, serviceName = 's3') {
return signV4(request, accessKey, secretKey, region, requestDate, contentSha256, serviceName);
}
// returns a presigned URL string
function presignSignatureV4(request, accessKey, secretKey, sessionToken, region, requestDate, expires) {
if (!(0, _helper.isObject)(request)) {
throw new TypeError('request should be of type "object"');
}
if (!(0, _helper.isString)(accessKey)) {
throw new TypeError('accessKey should be of type "string"');
}
if (!(0, _helper.isString)(secretKey)) {
throw new TypeError('secretKey should be of type "string"');
}
if (!(0, _helper.isString)(region)) {
throw new TypeError('region should be of type "string"');
}
if (!accessKey) {
throw new errors.AccessKeyRequiredError('accessKey is required for presigning');
}
if (!secretKey) {
throw new errors.SecretKeyRequiredError('secretKey is required for presigning');
}
if (expires && !(0, _helper.isNumber)(expires)) {
throw new TypeError('expires should be of type "number"');
}
if (expires && expires < 1) {
throw new errors.ExpiresParamError('expires param cannot be less than 1 seconds');
}
if (expires && expires > _helpers.PRESIGN_EXPIRY_DAYS_MAX) {
throw new errors.ExpiresParamError('expires param cannot be greater than 7 days');
}
const iso8601Date = (0, _helper.makeDateLong)(requestDate);
const signedHeaders = getSignedHeaders(request.headers);
const credential = getCredential(accessKey, region, requestDate);
const hashedPayload = 'UNSIGNED-PAYLOAD';
const requestQuery = [];
requestQuery.push(`X-Amz-Algorithm=${signV4Algorithm}`);
requestQuery.push(`X-Amz-Credential=${(0, _helper.uriEscape)(credential)}`);
requestQuery.push(`X-Amz-Date=${iso8601Date}`);
requestQuery.push(`X-Amz-Expires=${expires}`);
requestQuery.push(`X-Amz-SignedHeaders=${(0, _helper.uriEscape)(signedHeaders.join(';').toLowerCase())}`);
if (sessionToken) {
requestQuery.push(`X-Amz-Security-Token=${(0, _helper.uriEscape)(sessionToken)}`);
}
const resource = request.path.split('?')[0];
let query = request.path.split('?')[1];
if (query) {
query = query + '&' + requestQuery.join('&');
} else {
query = requestQuery.join('&');
}
const path = resource + '?' + query;
const canonicalRequest = getCanonicalRequest(request.method, path, request.headers, signedHeaders, hashedPayload);
const stringToSign = getStringToSign(canonicalRequest, requestDate, region);
const signingKey = getSigningKey(requestDate, region, secretKey);
const signature = crypto.createHmac('sha256', signingKey).update(stringToSign).digest('hex').toLowerCase();
return request.protocol + '//' + request.headers.host + path + `&X-Amz-Signature=${signature}`;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcnlwdG8iLCJfaW50ZXJvcFJlcXVpcmVXaWxkY2FyZCIsInJlcXVpcmUiLCJlcnJvcnMiLCJfaGVscGVycyIsIl9o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IG9mIHR5cGUgXCJhcnJheVwiJylcbiAgfVxuICBpZiAoIWlzU3RyaW5nKGhhc2hlZFBheWxvYWQpKSB7XG4gICAgdGhyb3cgbmV3IFR5cGVFcnJvcignaGFzaGVkUGF5bG9hZCBzaG91bGQgYmUgb2YgdHlwZSBcInN0cmluZ1wiJylcbiAgfVxuXG4gIGNvbnN0IGhlYWRlcnNBcnJheSA9IHNpZ25lZEhlYWRlcnMucmVkdWNlKChhY2MsIGkpID0+IHtcbiAgICAvLyBUcmltIHNwYWNlcyBmcm9tIHRoZSB2YWx1ZSAocmVxdWlyZWQgYnkgVjQgc3BlYylcbiAgICBjb25zdCB2YWwgPSBgJHtoZWFkZXJzW2ldfWAucmVwbGFjZSgvICsvZywgJyAnKVxuICAgIGFjYy5wdXNoKGAke2kudG9Mb3dlckNhc2UoKX06JHt2YWx9YClcbiAgICByZXR1cm4gYWNjXG4gIH0sIFt Line truncated
+115
View File
@@ -0,0 +1,115 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getBucketNotificationTransformer = getBucketNotificationTransformer;
exports.getConcater = getConcater;
exports.getHashSummer = getHashSummer;
exports.getListObjectsV2Transformer = getListObjectsV2Transformer;
exports.getListObjectsV2WithMetadataTransformer = getListObjectsV2WithMetadataTransformer;
var Crypto = _interopRequireWildcard(require("crypto"), true);
var _through = require("through2");
var _helper = require("./internal/helper.js");
var xmlParsers = _interopRequireWildcard(require("./xml-parsers.js"), true);
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015, 2016 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// getConcater returns a stream that concatenates the input and emits
// the concatenated output when 'end' has reached. If an optional
// parser function is passed upon reaching the 'end' of the stream,
// `parser(concatenated_data)` will be emitted.
function getConcater(parser, emitError) {
var objectMode = false;
var bufs = [];
if (parser && !(0, _helper.isFunction)(parser)) {
throw new TypeError('parser should be of type "function"');
}
if (parser) {
objectMode = true;
}
return _through({
objectMode
}, function (chunk, enc, cb) {
bufs.push(chunk);
cb();
}, function (cb) {
if (emitError) {
cb(parser(Buffer.concat(bufs).toString()));
// cb(e) would mean we have to emit 'end' by explicitly calling this.push(null)
this.push(null);
return;
}
if (bufs.length) {
if (parser) {
this.push(parser(Buffer.concat(bufs).toString()));
} else {
this.push(Buffer.concat(bufs));
}
}
cb();
});
}
// A through stream that calculates md5sum and sha256sum
function getHashSummer(enableSHA256) {
var md5 = Crypto.createHash('md5');
var sha256 = Crypto.createHash('sha256');
return _through.obj(function (chunk, enc, cb) {
if (enableSHA256) {
sha256.update(chunk);
} else {
md5.update(chunk);
}
cb();
}, function (cb) {
var md5sum = '';
var sha256sum = '';
if (enableSHA256) {
sha256sum = sha256.digest('hex');
} else {
md5sum = md5.digest('base64');
}
var hashData = {
md5sum,
sha256sum
};
this.push(hashData);
this.push(null);
cb();
});
}
// Following functions return a stream object that parses XML
// and emits suitable Javascript objects.
// Parses listObjects response.
function getListObjectsV2Transformer() {
return getConcater(xmlParsers.parseListObjectsV2);
}
// Parses listObjects with metadata response.
function getListObjectsV2WithMetadataTransformer() {
return getConcater(xmlParsers.parseListObjectsV2WithMetadata);
}
// Parses GET/SET BucketNotification response
function getBucketNotificationTransformer() {
return getConcater(xmlParsers.parseBucketNotification);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDcnlwdG8iLCJfaW50ZXJvcFJlcXVpcmVXaWxkY2FyZCIsInJlcXVpcmUiLCJfdGhyb3VnaCIsIl9oZWxwZXIiLCJ4bWxQYXJzZXJzIiwiX2dldFJlcXVpcmVXaWxkY2FyZENhY2hlIiwibm9kZUludGVyb3AiLCJXZWFrTWFwIiwiY2FjaGVCYWJlbEludGVyb3AiLCJjYWNoZU5vZGVJbnRlcm9wIiwib2JqIiwiX19lc01vZHVsZSIsImRlZmF1bHQiLCJjYWNoZSIsImhhcyIsImdldCIsIm5ld09iaiIsImhhc1Byb3BlcnR5RGVzY3JpcHRvciIsIk9iamVjdCIsImRlZmluZVByb3BlcnR5IiwiZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9yIiwia2V5IiwicHJvdG90eXBlIiwiaGFzT3duUHJvcGVydHkiLCJjYWxsIiwiZGVzYyIsInNldCIsImdldENvbmNhdGVyIiwicGFyc2VyIiwiZW1pdEVycm9yIiwib2JqZWN0TW9kZSIsImJ1ZnMiLCJpc0Z1bmN0aW9uIiwiVHlwZUVycm9yIiwiVGhyb3VnaDIiLCJjaHVuayIsImVuYyIsImNiIiwicHVzaCIsIkJ1ZmZlciIsImNvbmNhdCIsInRvU3RyaW5nIiwibGVuZ3RoIiwiZ2V0SGFza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HNoYTI1NiA9IENyeXB0by5jcmVhdGVIYXNoKCdzaGEyNTYnKVxuXG4gIHJldHVybiBUaHJvdWdoMi5vYmooXG4gICAgZnVuY3Rpb24gKGNodW5rLCBlbmMsIGNiKSB7XG4gICAgICBpZiAoZW5hYmxlU0hBMjU2KSB7XG4gICAgICAgIHNoYTI1Ni51cGRhdGUoY2h1bmspXG4gICAgICB9IGVsc2Uge1xuICAgICAgICBtZDUudXBkYXRlKGNodW5rKVxuICAgICAgfVxuICAgICAgY2IoKVxuICAgIH0sXG4gICAgZnVuY3Rpb24gKGNiKSB7XG4gICAgICB2YXIgbWQ1c3VtID0gJydcbiAgICAgIHZhciBzaGEyNTZzdW0gPSAnJ1xuICAgICAgaWYgKGVuYWJsZVNIQTI1Nikge1xuICAgICAgICBzaGEyNTZzdW0gPSBzaGEyNTYuZGlnZXN0KCdoZXgnKVxuICAgICAgfSBlbHNlIHtcbiAgICAgICAgbWQ1c3VtID0gbWQ1LmRpZ2VzdCgnYmFzZTY0JylcbiAgICAgIH1cbiAgICAgIHZhciBoYXNoRGF0YSA9IHsgbWQ1c3VtLCBzaGEyNTZzdW0gfVxuICAgICAgdGhpcy5wdXNoKGhhc2hEYXRhKVxuICAgICAgdGhpcy5wdXNoKG51bGwpXG4gICAgICBjYigpXG4gICAgfSxcbiAgKVxufVxuXG4vLyBGb2xsb3dpbmcgZnVuY3Rpb25zIHJldHVybiBhIHN0cmVhbSBvYmplY3QgdGhhdCBwYXJzZXMgWE1MXG4vLyBhbmQgZW1pdHMgc3VpdGFibGUgSmF2YXNjcmlwdCBvYmplY3RzLlxuXG4vLyBQYXJzZXMgbGlzdE9iamVjdHMgcmVzcG9uc2UuXG5leHBvcnQgZnVuY3Rpb24gZ2V0TGlzdE9iamVjdHNWMlR Line truncated
+208
View File
@@ -0,0 +1,208 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseBucketNotification = parseBucketNotification;
exports.parseListObjectsV2 = parseListObjectsV2;
exports.parseListObjectsV2WithMetadata = parseListObjectsV2WithMetadata;
var errors = _interopRequireWildcard(require("./errors.js"), true);
var _helper = require("./internal/helper.js");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
* MinIO Javascript Library for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// parse XML response for bucket notification
function parseBucketNotification(xml) {
var result = {
TopicConfiguration: [],
QueueConfiguration: [],
CloudFunctionConfiguration: []
};
// Parse the events list
var genEvents = function (events) {
var result = [];
if (events) {
(0, _helper.toArray)(events).forEach(s3event => {
result.push(s3event);
});
}
return result;
};
// Parse all filter rules
var genFilterRules = function (filters) {
var result = [];
if (filters) {
filters = (0, _helper.toArray)(filters);
if (filters[0].S3Key) {
filters[0].S3Key = (0, _helper.toArray)(filters[0].S3Key);
if (filters[0].S3Key[0].FilterRule) {
(0, _helper.toArray)(filters[0].S3Key[0].FilterRule).forEach(rule => {
var Name = (0, _helper.toArray)(rule.Name)[0];
var Value = (0, _helper.toArray)(rule.Value)[0];
result.push({
Name,
Value
});
});
}
}
}
return result;
};
var xmlobj = (0, _helper.parseXml)(xml);
xmlobj = xmlobj.NotificationConfiguration;
// Parse all topic configurations in the xml
if (xmlobj.TopicConfiguration) {
(0, _helper.toArray)(xmlobj.TopicConfiguration).forEach(config => {
var Id = (0, _helper.toArray)(config.Id)[0];
var Topic = (0, _helper.toArray)(config.Topic)[0];
var Event = genEvents(config.Event);
var Filter = genFilterRules(config.Filter);
result.TopicConfiguration.push({
Id,
Topic,
Event,
Filter
});
});
}
// Parse all topic configurations in the xml
if (xmlobj.QueueConfiguration) {
(0, _helper.toArray)(xmlobj.QueueConfiguration).forEach(config => {
var Id = (0, _helper.toArray)(config.Id)[0];
var Queue = (0, _helper.toArray)(config.Queue)[0];
var Event = genEvents(config.Event);
var Filter = genFilterRules(config.Filter);
result.QueueConfiguration.push({
Id,
Queue,
Event,
Filter
});
});
}
// Parse all QueueConfiguration arrays
if (xmlobj.CloudFunctionConfiguration) {
(0, _helper.toArray)(xmlobj.CloudFunctionConfiguration).forEach(config => {
var Id = (0, _helper.toArray)(config.Id)[0];
var CloudFunction = (0, _helper.toArray)(config.CloudFunction)[0];
var Event = genEvents(config.Event);
var Filter = genFilterRules(config.Filter);
result.CloudFunctionConfiguration.push({
Id,
CloudFunction,
Event,
Filter
});
});
}
return result;
}
// parse XML response for list objects v2 in a bucket
function parseListObjectsV2(xml) {
var result = {
objects: [],
isTruncated: false
};
var xmlobj = (0, _helper.parseXml)(xml);
if (!xmlobj.ListBucketResult) {
throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"');
}
xmlobj = xmlobj.ListBucketResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextContinuationToken) {
result.nextContinuationToken = xmlobj.NextContinuationToken;
}
if (xmlobj.Contents) {
(0, _helper.toArray)(xmlobj.Contents).forEach(content => {
var name = (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(content.Key)[0]);
var lastModified = new Date(content.LastModified);
var etag = (0, _helper.sanitizeETag)(content.ETag);
var size = content.Size;
result.objects.push({
name,
lastModified,
etag,
size
});
});
}
if (xmlobj.CommonPrefixes) {
(0, _helper.toArray)(xmlobj.CommonPrefixes).forEach(commonPrefix => {
result.objects.push({
prefix: (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(commonPrefix.Prefix)[0]),
size: 0
});
});
}
return result;
}
// parse XML response for list objects v2 with metadata in a bucket
function parseListObjectsV2WithMetadata(xml) {
var result = {
objects: [],
isTruncated: false
};
var xmlobj = (0, _helper.parseXml)(xml);
if (!xmlobj.ListBucketResult) {
throw new errors.InvalidXMLError('Missing tag: "ListBucketResult"');
}
xmlobj = xmlobj.ListBucketResult;
if (xmlobj.IsTruncated) {
result.isTruncated = xmlobj.IsTruncated;
}
if (xmlobj.NextContinuationToken) {
result.nextContinuationToken = xmlobj.NextContinuationToken;
}
if (xmlobj.Contents) {
(0, _helper.toArray)(xmlobj.Contents).forEach(content => {
var name = (0, _helper.sanitizeObjectKey)(content.Key);
var lastModified = new Date(content.LastModified);
var etag = (0, _helper.sanitizeETag)(content.ETag);
var size = content.Size;
var metadata;
if (content.UserMetadata != null) {
metadata = (0, _helper.toArray)(content.UserMetadata)[0];
} else {
metadata = null;
}
result.objects.push({
name,
lastModified,
etag,
size,
metadata
});
});
}
if (xmlobj.CommonPrefixes) {
(0, _helper.toArray)(xmlobj.CommonPrefixes).forEach(commonPrefix => {
result.objects.push({
prefix: (0, _helper.sanitizeObjectKey)((0, _helper.toArray)(commonPrefix.Prefix)[0]),
size: 0
});
});
}
return result;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9u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kV2ZW50KVxuICAgICAgdmFyIEZpbHRlciA9IGdlbkZpbHRlclJ1bGVzKGNvbmZpZy5GaWx0ZXIpXG4gICAgICByZXN1bHQuVG9waWNDb25maWd1cmF0aW9uLnB1c2goeyBJZCwgVG9waWMsIEV2ZW50LCBGaWx0ZXIgfSlcbiAgICB9KVxuICB9XG4gIC8vIFBhcnNlIGFsbCB0b3BpYyBjb25maWd1cmF0aW9ucyBpbiB0aGUgeG1sXG4gIGlmICh4bWxvYmouUXVldWVDb25maWd1cmF0aW9uKSB7XG4gICAgdG9BcnJheSh4bWxvYmouUXVldWVDb25maWd1cmF0aW9uKS5mb3JFYWNoKChjb25maWcpID0+IHtcbiAgICAgIHZhciBJZCA9IHRvQXJyYXkoY29uZmlnLklkKVswXVxuICAgICAgdmFyIFF1ZXVlID0gdG9BcnJheShjb25maWcuUXVldWUpWzBdXG4gICAgICB2YXIgRXZlbnQgPSBnZW5FdmVudHMoY29uZmlnLkV2ZW50KVxuICAgICAgdmF Line truncated
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../fast-xml-parser/src/cli/cli.js" "$@"
else
exec node "$basedir/../fast-xml-parser/src/cli/cli.js" "$@"
fi
+17
View File
@@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\fast-xml-parser\src\cli\cli.js" %*
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args
} else {
& "$basedir/node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args
} else {
& "node$exe" "$basedir/../fast-xml-parser/src/cli/cli.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret
@@ -0,0 +1,606 @@
<small>Note: If you find missing information about particular minor version, that version must have been changed without any functional change in this library.</small>
**4.5.2 / 2025-02-18**
- Fix null CDATA to comply with undefined behavior (#701) (By [Matthieu BOHEAS](https://github.com/Kelgors))
- Fix(performance): Update check for leaf node in saveTextToParentTag function in OrderedObjParser.js (#707) (By [...](https://github.com/tomingtoming))
- Fix: emit full JSON string from CLI when no output filename specified (#710) (By [Matt Benson](https://github.com/mbenson))
**4.5.1 / 2024-12-15**
- Fix empty tag key name for v5 (#697). no impact on v4
- Fixes entity parsing when used in strict mode (#699)
**4.5.0 / 2024-09-03**
- feat #666: ignoreAttributes support function, and array of string or regex (By [ArtemM](https://github.com/mav-rik))
**4.4.1 / 2024-07-28**
- v5 fix: maximum length limit to currency value
- fix #634: build attributes with oneListGroup and attributesGroupName (#653)(By [Andreas Naziris](https://github.com/a-rasin))
- fix: get oneListGroup to work as expected for array of strings (#662)(By [Andreas Naziris](https://github.com/a-rasin))
**4.4.0 / 2024-05-18**
- fix #654: parse attribute list correctly for self closing stop node.
- fix: validator bug when closing tag is not opened. (#647) (By [Ryosuke Fukatani](https://github.com/RyosukeFukatani))
- fix #581: typings; return type of `tagValueProcessor` & `attributeValueProcessor` (#582) (By [monholm]())
**4.3.6 / 2024-03-16**
- Add support for parsing HTML numeric entities (#645) (By [Jonas Schade ](https://github.com/DerZade))
**4.3.5 / 2024-02-24**
- code for v5 is added for experimental use
**4.3.4 / 2024-01-10**
- fix: Don't escape entities in CDATA sections (#633) (By [wackbyte](https://github.com/wackbyte))
**4.3.3 / 2024-01-10**
- Remove unnecessary regex
**4.3.2 / 2023-10-02**
- fix `jObj.hasOwnProperty` when give input is null (By [Arda TANRIKULU](https://github.com/ardatan))
**4.3.1 / 2023-09-24**
- revert back "Fix typings for builder and parser to make return type generic" to avoid failure of existing projects. Need to decide a common approach.
**4.3.0 / 2023-09-20**
- Fix stopNodes to work with removeNSPrefix (#607) (#608) (By [Craig Andrews]https://github.com/candrews))
- Fix #610 ignore properties set to Object.prototype
- Fix typings for builder and parser to make return type generic (By [Sarah Dayan](https://github.com/sarahdayan))
**4.2.7 / 2023-07-30**
- Fix: builder should set text node correctly when only textnode is present (#589) (By [qianqing](https://github.com/joneqian))
- Fix: Fix for null and undefined attributes when building xml (#585) (#598). A null or undefined value should be ignored. (By [Eugenio Ceschia](https://github.com/cecia234))
**4.2.6 / 2023-07-17**
- Fix: Remove trailing slash from jPath for self-closing tags (#595) (By [Maciej Radzikowski](https://github.com/m-radzikowski))
**4.2.5 / 2023-06-22**
- change code implementation
**4.2.4 / 2023-06-06**
- fix security bug
**4.2.3 / 2023-06-05**
- fix security bug
**4.2.2 / 2023-04-18**
- fix #562: fix unpaired tag when it comes in last of a nested tag. Also throw error when unpaired tag is used as closing tag
**4.2.1 / 2023-04-18**
- fix: jpath after unpaired tags
**4.2.0 / 2023-04-09**
- support `updateTag` parser property
**4.1.4 / 2023-04-08**
- update typings to let user create XMLBuilder instance without options (#556) (By [Patrick](https://github.com/omggga))
- fix: IsArray option isn't parsing tags with 0 as value correctly #490 (#557) (By [Aleksandr Murashkin](https://github.com/p-kuen))
- feature: support `oneListGroup` to group repeated children tags udder single group
**4.1.3 / 2023-02-26**
- fix #546: Support complex entity value
**4.1.2 / 2023-02-12**
- Security Fix
**4.1.1 / 2023-02-03**
- Fix #540: ignoreAttributes breaks unpairedTags
- Refactor XML builder code
**4.1.0 / 2023-02-02**
- Fix '<' or '>' in DTD comment throwing an error. (#533) (By [Adam Baker](https://github.com/Cwazywierdo))
- Set "eNotation" to 'true' as default
**4.0.15 / 2023-01-25**
- make "eNotation" optional
**4.0.14 / 2023-01-22**
- fixed: add missed typing "eNotation" to parse values
**4.0.13 / 2023-01-07**
- preserveorder formatting (By [mdeknowis](https://github.com/mdeknowis))
- support `transformAttributeName` (By [Erik Rothoff Andersson](https://github.com/erkie))
**4.0.12 / 2022-11-19**
- fix typescript
**4.0.11 / 2022-10-05**
- fix #501: parse for entities only once
**4.0.10 / 2022-09-14**
- fix broken links in demo site (By [Yannick Lang](https://github.com/layaxx))
- fix #491: tagValueProcessor type definition (By [Andrea Francesco Speziale](https://github.com/andreafspeziale))
- Add jsdocs for tagValueProcessor
**4.0.9 / 2022-07-10**
- fix #470: stop-tag can have self-closing tag with same name
- fix #472: stopNode can have any special tag inside
- Allow !ATTLIST and !NOTATION with DOCTYPE
- Add transformTagName option to transform tag names when parsing (#469) (By [Erik Rothoff Andersson](https://github.com/erkie))
**4.0.8 / 2022-05-28**
- Fix CDATA parsing returning empty string when value = 0 (#451) (By [ndelanou](https://github.com/ndelanou))
- Fix stopNodes when same tag appears inside node (#456) (By [patrickshipe](https://github.com/patrickshipe))
- fix #468: prettify own properties only
**4.0.7 / 2022-03-18**
- support CDATA even if tag order is not preserved
- support Comments even if tag order is not preserved
- fix #446: XMLbuilder should not indent XML declaration
**4.0.6 / 2022-03-08**
- fix: call tagValueProcessor only once for array items
- fix: missing changed for #437
**4.0.5 / 2022-03-06**
- fix #437: call tagValueProcessor from XML builder
**4.0.4 / 2022-03-03**
- fix #435: should skip unpaired and self-closing nodes when set as stopnodes
**4.0.3 / 2022-02-15**
- fix: ReferenceError when Bundled with Strict (#431) (By [Andreas Heissenberger](https://github.com/aheissenberger))
**4.0.2 / 2022-02-04**
- builder supports `suppressUnpairedNode`
- parser supports `ignoreDeclaration` and `ignorePiTags`
- fix: when comment is parsed as text value if given as `<!--> ...` #423
- builder supports decoding `&`
**4.0.1 / 2022-01-08**
- fix builder for pi tag
- fix: support suppressBooleanAttrs by builder
**4.0.0 / 2022-01-06**
- Generating different combined, parser only, builder only, validator only browser bundles
- Keeping cjs modules as they can be imported in cjs and esm modules both. Otherwise refer `esm` branch.
**4.0.0-beta.8 / 2021-12-13**
- call tagValueProcessor for stop nodes
**4.0.0-beta.7 / 2021-12-09**
- fix Validator bug when an attribute has no value but '=' only
- XML Builder should suppress unpaired tags by default.
- documents update for missing features
- refactoring to use Object.assign
- refactoring to remove repeated code
**4.0.0-beta.6 / 2021-12-05**
- Support PI Tags processing
- Support `suppressBooleanAttributes` by XML Builder for attributes with value `true`.
**4.0.0-beta.5 / 2021-12-04**
- fix: when a tag with name "attributes"
**4.0.0-beta.4 / 2021-12-02**
- Support HTML document parsing
- skip stop nodes parsing when building the XML from JS object
- Support external entites without DOCTYPE
- update dev dependency: strnum v1.0.5 to fix long number issue
**4.0.0-beta.3 / 2021-11-30**
- support global stopNodes expression like "*.stop"
- support self-closing and paired unpaired tags
- fix: CDATA should not be parsed.
- Fix typings for XMLBuilder (#396)(By [Anders Emil Salvesen](https://github.com/andersem))
- supports XML entities, HTML entities, DOCTYPE entities
**⚠️ 4.0.0-beta.2 / 2021-11-19**
- rename `attrMap` to `attibutes` in parser output when `preserveOrder:true`
- supports unpairedTags
**⚠️ 4.0.0-beta.1 / 2021-11-18**
- Parser returns an array now
- to make the structure common
- and to return root level detail
- renamed `cdataTagName` to `cdataPropName`
- Added `commentPropName`
- fix typings
**⚠️ 4.0.0-beta.0 / 2021-11-16**
- Name change of many configuration properties.
- `attrNodeName` to `attributesGroupName`
- `attrValueProcessor` to `attributeValueProcessor`
- `parseNodeValue` to `parseTagValue`
- `ignoreNameSpace` to `removeNSPrefix`
- `numParseOptions` to `numberParseOptions`
- spelling correction for `suppressEmptyNode`
- Name change of cli and browser bundle to **fxparser**
- `isArray` option is added to parse a tag into array
- `preserveOrder` option is added to render XML in such a way that the result js Object maintains the order of properties same as in XML.
- Processing behaviour of `tagValueProcessor` and `attributeValueProcessor` are changes with extra input parameters
- j2xparser is renamed to XMLBuilder.
- You need to build XML parser instance for given options first before parsing XML.
- fix #327, #336: throw error when extra text after XML content
- fix #330: attribute value can have '\n',
- fix #350: attrbiutes can be separated by '\n' from tagname
3.21.1 / 2021-10-31
- Correctly format JSON elements with a text prop but no attribute props ( By [haddadnj](https://github.com/haddadnj) )
3.21.0 / 2021-10-25
- feat: added option `rootNodeName` to set tag name for array input when converting js object to XML.
- feat: added option `alwaysCreateTextNode` to force text node creation (by: *@massimo-ua*)
- ⚠️ feat: Better error location for unclosed tags. (by *@Gei0r*)
- Some error messages would be changed when validating XML. Eg
- `{ InvalidXml: "Invalid '[ \"rootNode\"]' found." }` → `{InvalidTag: "Unclosed tag 'rootNode'."}`
- `{ InvalidTag: "Closing tag 'rootNode' is expected inplace of 'rootnode'." }` → `{ InvalidTag: "Expected closing tag 'rootNode' (opened in line 1) instead of closing tag 'rootnode'."}`
- ⚠️ feat: Column in error response when validating XML
```js
{
"code": "InvalidAttr",
"msg": "Attribute 'abc' is repeated.",
"line": 1,
"col": 22
}
```
3.20.1 / 2021-09-25
- update strnum package
3.20.0 / 2021-09-10
- Use strnum npm package to parse string to number
- breaking change: long number will be parsed to scientific notation.
3.19.0 / 2021-03-14
- License changed to MIT original
- Fix #321 : namespace tag parsing
3.18.0 / 2021-02-05
- Support RegEx and function in arrayMode option
- Fix #317 : validate nested PI tags
3.17.4 / 2020-06-07
- Refactor some code to support IE11
- Fix: `<tag >` space as attribute string
3.17.3 / 2020-05-23
- Fix: tag name separated by \n \t
- Fix: throw error for unclosed tags
3.17.2 / 2020-05-23
- Fixed an issue in processing doctype tag
- Fixed tagName where it should not have whitespace chars
3.17.1 / 2020-05-19
- Fixed an issue in checking opening tag
3.17.0 / 2020-05-18
- parser: fix '<' issue when it comes in aatr value
- parser: refactoring to remove dependency from regex
- validator: fix IE 11 issue for error messages
- updated dev dependencies
- separated benchmark module to sub-module
- breaking change: comments will not be removed from CDATA data
3.16.0 / 2020-01-12
- validaor: fix for ampersand characters (#215)
- refactoring to support unicode chars in tag name
- update typing for validator error
3.15.1 / 2019-12-09
- validaor: fix multiple roots are not allowed
3.15.0 / 2019-11-23
- validaor: improve error messaging
- validator: add line number in case of error
- validator: add more error scenarios to make it more descriptive
3.14.0 / 2019-10-25
- arrayMode for XML to JS obj parsing
3.13.0 / 2019-10-02
- pass tag/attr name to tag/attr value processor
- inbuilt optional validation with XML parser
3.12.21 / 2019-10-02
- Fix validator for unclosed XMLs
- move nimnjs dependency to dev dependency
- update dependencies
3.12.20 / 2019-08-16
- Revert: Fix #167: '>' in attribute value as it is causing high performance degrade.
3.12.19 / 2019-07-28
- Fix js to xml parser should work for date values. (broken: `tagValueProcessor` will receive the original value instead of string always) (breaking change)
3.12.18 / 2019-07-27
- remove configstore dependency
3.12.17 / 2019-07-14
- Fix #167: '>' in attribute value
3.12.16 / 2019-03-23
- Support a new option "stopNodes". (#150)
Accept the list of tags which are not required to be parsed. Instead, all the nested tag and data will be assigned as string.
- Don't show post-install message
3.12.12 / 2019-01-11
- fix : IE parseInt, parseFloat error
3.12.11 / 2018-12-24
- fix #132: "/" should not be parsed as boolean attr in case of self closing tags
3.12.9 / 2018-11-23
- fix #129 : validator should not fail when an atrribute name is 'length'
3.12.8 / 2018-11-22
- fix #128 : use 'attrValueProcessor' to process attribute value in json2xml parser
3.12.6 / 2018-11-10
- Fix #126: check for type
3.12.4 / 2018-09-12
- Fix: include tasks in npm package
3.12.3 / 2018-09-12
- Fix CLI issue raised in last PR
3.12.2 / 2018-09-11
- Fix formatting for JSON to XML output
- Migrate to webpack (PR merged)
- fix cli (PR merged)
3.12.0 / 2018-08-06
- Support hexadecimal values
- Support true number parsing
3.11.2 / 2018-07-23
- Update Demo for more options
- Update license information
- Update readme for formatting, users, and spelling mistakes
- Add missing typescript definition for j2xParser
- refactoring: change filenames
3.11.1 / 2018-06-05
- fix #93: read the text after self closing tag
3.11.0 / 2018-05-20
- return defaultOptions if there are not options in buildOptions function
- added localeRange declaration in parser.d.ts
- Added support of cyrillic characters in validator XML
- fixed bug in validator work when XML data with byte order marker
3.10.0 / 2018-05-13
- Added support of cyrillic characters in parsing XML to JSON
3.9.11 / 2018-05-09
- fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/80 fix nimn chars
- update package information
- fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/86: json 2 xml parser : property with null value should be parsed to self closing tag.
- update online demo
- revert zombiejs to old version to support old version of node
- update dependencies
3.3.10 / 2018-04-23
- fix #77 : parse even if closing tag has space before '>'
- include all css & js lib in demo app
- remove babel dependencies until needed
3.3.9 / 2018-04-18
- fix #74 : TS2314 TypeScript compiler error
3.3.8 / 2018-04-17
- fix #73 : IE doesn't support Object.assign
3.3.7 / 2018-04-14
- fix: use let insted of const in for loop of validator
- Merge pull request
https://github.com/NaturalIntelligence/fast-xml-parser/issues/71 from bb/master
first draft of typings for typescript
https://github.com/NaturalIntelligence/fast-xml-parser/issues/69
- Merge pull request
https://github.com/NaturalIntelligence/fast-xml-parser/issues/70 from bb/patch-1
fix some typos in readme
3.3.6 / 2018-03-21
- change arrow functions to full notation for IE compatibility
3.3.5 / 2018-03-15
- fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/67 : attrNodeName invalid behavior
- fix: remove decodeHTML char condition
3.3.4 / 2018-03-14
- remove dependency on "he" package
- refactor code to separate methods in separate files.
- draft code for transforming XML to json string. It is not officially documented due to performance issue.
3.3.0 / 2018-03-05
- use common default options for XML parsing for consistency. And add `parseToNimn` method.
- update nexttodo
- update README about XML to Nimn transformation and remove special notes about 3.x release
- update CONTRIBUTING.ms mentioning nexttodo
- add negative case for XML PIs
- validate xml processing instruction tags https://github.com/NaturalIntelligence/fast-xml-parser/issues/62
- nimndata: handle array with object
- nimndata: node with nested node and text node
- nimndata: handle attributes and text node
- nimndata: add options, handle array
- add xml to nimn data converter
- x2j: direct access property with tagname
- update changelog
- fix validator when single quote presents in value enclosed with double quotes or vice versa
- Revert "remove unneded nimnjs dependency, move opencollective to devDependencies and replace it
with more light opencollective-postinstall"
This reverts commit d47aa7181075d82db4fee97fd8ea32b056fe3f46.
- Merge pull request: https://github.com/NaturalIntelligence/fast-xml-parser/issues/63 from HaroldPutman/suppress-undefined
Keep undefined nodes out of the XML output : This is useful when you are deleting nodes from the JSON and rewriting XML.
3.2.4 / 2018-03-01
- fix #59 fix in validator when open quote presents in attribute value
- Create nexttodo.md
- exclude static from bitHound tests
- add package lock
3.2.3 / 2018-02-28
- Merge pull request from Delagen/master: fix namespaces can contain the same characters as xml names
3.2.2 / 2018-02-22
- fix: attribute xmlns should not be removed if ignoreNameSpace is false
- create CONTRIBUTING.md
3.2.1 / 2018-02-17
- fix: empty attribute should be parsed
3.2.0 / 2018-02-16
- Merge pull request : Dev to Master
- Update README and version
- j2x:add performance test
- j2x: Remove extra empty line before closing tag
- j2x: suppress empty nodes to self closing node if configured
- j2x: provide option to give indentation depth
- j2x: make optional formatting
- j2x: encodeHTMLchat
- j2x: handle cdata tag
- j2x: handle grouped attributes
- convert json to xml
- nested object
- array
- attributes
- text value
- small refactoring
- Merge pull request: Update cli.js to let user validate XML file or data
- Add option for rendering CDATA as separate property
3.0.1 / 2018-02-09
- fix CRLF: replace it with single space in attributes value only.
3.0.0 / 2018-02-08
- change online tool with new changes
- update info about new options
- separate tag value processing to separate function
- make HTML decoding optional
- give an option to allow boolean attributes
- change cli options as per v3
- Correct comparison table format on README
- update v3 information
- some performance improvement changes
- Make regex object local to the method and move some common methods to util
- Change parser to
- handle multiple instances of CDATA
- make triming of value optionals
- HTML decode attribute and text value
- refactor code to separate files
- Ignore newline chars without RE (in validator)
- validate for XML prolog
- Validate DOCTYPE without RE
- Update validator to return error response
- Update README to add detail about V3
- Separate xmlNode model class
- include vscode debug config
- fix for repeated object
- fix attribute regex for boolean attributes
- Fix validator for invalid attributes
2.9.4 / 2018-02-02
- Merge pull request: Decode HTML characters
- refactor source folder name
- ignore bundle / browser js to be published to npm
2.9.3 / 2018-01-26
- Merge pull request: Correctly remove CRLF line breaks
- Enable to parse attribute in online editor
- Fix testing demo app test
- Describe parsing options
- Add options for online demo
2.9.2 / 2018-01-18
- Remove check if tag starting with "XML"
- Fix: when there are spaces before / after CDATA
2.9.1 / 2018-01-16
- Fix: newline should be replaced with single space
- Fix: for single and multiline comments
- validate xml with CDATA
- Fix: the issue when there is no space between 2 attributes
- Fix: https://github.com/NaturalIntelligence/fast-xml-parser/issues/33: when there is newline char in attr val, it doesn't parse
- Merge pull request: fix ignoreNamespace
- fix: don't wrap attributes if only namespace attrs
- fix: use portfinder for run tests, update deps
- fix: don't treat namespaces as attributes when ignoreNamespace enabled
2.9.0 / 2018-01-10
- Rewrite the validator to handle large files.
Ignore DOCTYPE validation.
- Fix: When attribute value has equal sign
2.8.3 / 2017-12-15
- Fix: when a tag has value along with subtags
2.8.2 / 2017-12-04
- Fix value parsing for IE
2.8.1 / 2017-12-01
- fix: validator should return false instead of err when invalid XML
2.8.0 / 2017-11-29
- Add CLI option to ignore value conversion
- Fix variable name when filename is given on CLI
- Update CLI help text
- Merge pull request: xml2js: Accept standard input
- Test Node 8
- Update dependencies
- Bundle readToEnd
- Add ability to read from standard input
2.7.4 / 2017-09-22
- Merge pull request: Allow wrap attributes with subobject to compatible with other parsers output
2.7.3 / 2017-08-02
- fix: handle CDATA with regx
2.7.2 / 2017-07-30
- Change travis config for yarn caching
- fix validator: when tag property is same as array property
- Merge pull request: Failing test case in validator for valid SVG
2.7.1 / 2017-07-26
- Fix: Handle val 0
2.7.0 / 2017-07-25
- Fix test for arrayMode
- Merge pull request: Add arrayMode option to parse any nodes as arrays
2.6.0 / 2017-07-14
- code improvement
- Add unit tests for value conversion for attr
- Merge pull request: option of an attribute value conversion to a number (textAttrConversion) the same way as the textNodeConversion option does. Default value is false.
2.5.1 / 2017-07-01
- Fix XML element name pattern
- Fix XML element name pattern while parsing
- Fix validation for xml tag element
2.5.0 / 2017-06-25
- Improve Validator performance
- update attr matching regex
- Add perf tests
- Improve atrr regex to handle all cases
2.4.4 / 2017-06-08
- Bug fix: when an attribute has single or double quote in value
2.4.3 / 2017-06-05
- Bug fix: when multiple CDATA tags are given
- Merge pull request: add option "textNodeConversion"
- add option "textNodeConversion"
2.4.1 / 2017-04-14
- fix tests
- Bug fix: preserve initial space of node value
- Handle CDATA
2.3.1 / 2017-03-15
- Bug fix: when single self closing tag
- Merge pull request: fix .codeclimate.yml
- Update .codeclimate.yml - Fixed config so it does not error anymore.
- Update .codeclimate.yml
2.3.0 / 2017-02-26
- Code improvement
- add bithound config
- Update usage
- Update travis to generate bundle js before running tests
- 1.Browserify, 2. add more tests for validator
- Add validator
- Fix CLI default parameter bug
2.2.1 / 2017-02-05
- Bug fix: CLI default option
Loaded 100 of 25823 files, more files were not shown because too many files have changed in this diff. Show more