@strapi/provider-upload-aws-s3 0.0.0-next.f0a0bc26f5ef0693aaea2a616bc6b816cfee54b6 → 0.0.0-next.f0f36e3df4b18f167036dcbca529dcb933bf4e1d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="node" />
3
+ /// <reference types="node" />
3
4
  import type { ReadStream } from 'node:fs';
4
5
  import { DeleteObjectCommandOutput, CompleteMultipartUploadCommandOutput, AbortMultipartUploadCommandOutput, S3ClientConfig, ObjectCannedACL } from '@aws-sdk/client-s3';
5
6
  import type { AwsCredentialIdentity } from '@aws-sdk/types';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE1C,OAAO,EAIL,yBAAyB,EAEzB,oCAAoC,EACpC,iCAAiC,EACjC,cAAc,EACd,eAAe,EAChB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAK5D,MAAM,WAAW,IAAI;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,CAA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SAAQ,cAAc;IAEpD,WAAW,CAAC,EAAE,qBAAqB,CAAC,aAAa,CAAC,CAAC;IACnD,eAAe,CAAC,EAAE,qBAAqB,CAAC,iBAAiB,CAAC,CAAC;IAE3D,WAAW,CAAC,EAAE,qBAAqB,CAAC;IACpC,MAAM,CAAC,EAAE,SAAS,CAAC;IACnB,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CAClB;AAED,MAAM,MAAM,WAAW,GAAG,CAAC,cAAc,GAAG;IAAE,SAAS,EAAE,cAAc,CAAA;CAAE,CAAC,GAAG;IAC3E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CAClB,CAAC;;+DA0B2D,WAAW;;2BAwCzC,IAAI,gBAAgB,GAAG,GAAG,QAAQ;YAAE,GAAG,EAAE,MAAM,CAAA;SAAE,CAAC;2BAsBxD,IAAI;qBAGV,IAAI;qBAGJ,IAAI,sBAAsB,QAAQ,yBAAyB,CAAC;;;AArE/E,wBA+EE"}
package/dist/index.js CHANGED
@@ -1,147 +1,116 @@
1
- "use strict";
2
- const fp = require("lodash/fp");
3
- const clientS3 = require("@aws-sdk/client-s3");
4
- const s3RequestPresigner = require("@aws-sdk/s3-request-presigner");
5
- const libStorage = require("@aws-sdk/lib-storage");
6
- const ENDPOINT_PATTERN = /^(.+\.)?s3[.-]([a-z0-9-]+)\./;
7
- function isUrlFromBucket(fileUrl, bucketName, baseUrl = "") {
8
- const url = new URL(fileUrl);
9
- if (baseUrl) {
10
- return false;
11
- }
12
- const { bucket } = getBucketFromAwsUrl(fileUrl);
13
- if (bucket) {
14
- return bucket === bucketName;
15
- }
16
- return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);
17
- }
18
- function getBucketFromAwsUrl(fileUrl) {
19
- const url = new URL(fileUrl);
20
- if (url.protocol === "s3:") {
21
- const bucket = url.host;
22
- if (!bucket) {
23
- return { err: `Invalid S3 url: no bucket: ${url}` };
24
- }
25
- return { bucket };
26
- }
27
- if (!url.host) {
28
- return { err: `Invalid S3 url: no hostname: ${url}` };
29
- }
30
- const matches = url.host.match(ENDPOINT_PATTERN);
31
- if (!matches) {
32
- return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };
33
- }
34
- const prefix = matches[1];
35
- if (!prefix) {
36
- if (url.pathname === "/") {
37
- return { bucket: null };
38
- }
39
- const index2 = url.pathname.indexOf("/", 1);
40
- if (index2 === -1) {
41
- return { bucket: url.pathname.substring(1) };
42
- }
43
- if (index2 === url.pathname.length - 1) {
44
- return { bucket: url.pathname.substring(1, index2) };
1
+ 'use strict';
2
+
3
+ var fp = require('lodash/fp');
4
+ var clientS3 = require('@aws-sdk/client-s3');
5
+ var s3RequestPresigner = require('@aws-sdk/s3-request-presigner');
6
+ var libStorage = require('@aws-sdk/lib-storage');
7
+ var utils = require('./utils.js');
8
+
9
+ const assertUrlProtocol = (url)=>{
10
+ // Regex to test protocol like "http://", "https://"
11
+ return /^\w*:\/\//.test(url);
12
+ };
13
+ const getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options })=>{
14
+ if (Object.keys(legacyS3Options).length > 0) {
15
+ process.emitWarning("S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.");
45
16
  }
46
- return { bucket: url.pathname.substring(1, index2) };
47
- }
48
- return { bucket: prefix.substring(0, prefix.length - 1) };
49
- }
50
- const extractCredentials = (options) => {
51
- if (options.s3Options?.credentials) {
52
- return {
53
- accessKeyId: options.s3Options.credentials.accessKeyId,
54
- secretAccessKey: options.s3Options.credentials.secretAccessKey
17
+ const credentials = utils.extractCredentials({
18
+ s3Options,
19
+ ...legacyS3Options
20
+ });
21
+ const config = {
22
+ ...s3Options,
23
+ ...legacyS3Options,
24
+ ...credentials ? {
25
+ credentials
26
+ } : {}
55
27
  };
56
- }
57
- return null;
58
- };
59
- const assertUrlProtocol = (url) => {
60
- return /^\w*:\/\//.test(url);
28
+ config.params.ACL = fp.getOr(clientS3.ObjectCannedACL.public_read, [
29
+ 'params',
30
+ 'ACL'
31
+ ], config);
32
+ return config;
61
33
  };
62
- const getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }) => {
63
- if (Object.keys(legacyS3Options).length > 0) {
64
- process.emitWarning(
65
- "S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property."
66
- );
67
- }
68
- const credentials = extractCredentials({ s3Options, ...legacyS3Options });
69
- const config = {
70
- ...s3Options,
71
- ...legacyS3Options,
72
- ...credentials ? { credentials } : {}
73
- };
74
- config.params.ACL = fp.getOr(clientS3.ObjectCannedACL.public_read, ["params", "ACL"], config);
75
- return config;
76
- };
77
- const index = {
78
- init({ baseUrl, rootPath, s3Options, ...legacyS3Options }) {
79
- const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });
80
- const s3Client = new clientS3.S3Client(config);
81
- const filePrefix = rootPath ? `${rootPath.replace(/\/+$/, "")}/` : "";
82
- const getFileKey = (file) => {
83
- const path = file.path ? `${file.path}/` : "";
84
- return `${filePrefix}${path}${file.hash}${file.ext}`;
85
- };
86
- const upload = async (file, customParams = {}) => {
87
- const fileKey = getFileKey(file);
88
- const uploadObj = new libStorage.Upload({
89
- client: s3Client,
90
- params: {
91
- Bucket: config.params.Bucket,
92
- Key: fileKey,
93
- Body: file.stream || Buffer.from(file.buffer, "binary"),
94
- ACL: config.params.ACL,
95
- ContentType: file.mime,
96
- ...customParams
97
- }
98
- });
99
- const upload2 = await uploadObj.done();
100
- if (assertUrlProtocol(upload2.Location)) {
101
- file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload2.Location;
102
- } else {
103
- file.url = `https://${upload2.Location}`;
104
- }
105
- };
106
- return {
107
- isPrivate() {
108
- return config.params.ACL === "private";
109
- },
110
- async getSignedUrl(file, customParams) {
111
- if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {
112
- return { url: file.url };
113
- }
114
- const fileKey = getFileKey(file);
115
- const url = await s3RequestPresigner.getSignedUrl(
116
- // @ts-expect-error - TODO fix client type
117
- s3Client,
118
- new clientS3.GetObjectCommand({
119
- Bucket: config.params.Bucket,
120
- Key: fileKey,
121
- ...customParams
122
- }),
123
- {
124
- expiresIn: fp.getOr(15 * 60, ["params", "signedUrlExpires"], config)
125
- }
126
- );
127
- return { url };
128
- },
129
- uploadStream(file, customParams = {}) {
130
- return upload(file, customParams);
131
- },
132
- upload(file, customParams = {}) {
133
- return upload(file, customParams);
134
- },
135
- delete(file, customParams = {}) {
136
- const command = new clientS3.DeleteObjectCommand({
137
- Bucket: config.params.Bucket,
138
- Key: getFileKey(file),
139
- ...customParams
34
+ var index = {
35
+ init ({ baseUrl, rootPath, s3Options, ...legacyS3Options }) {
36
+ // TODO V5 change config structure to avoid having to do this
37
+ const config = getConfig({
38
+ baseUrl,
39
+ rootPath,
40
+ s3Options,
41
+ ...legacyS3Options
140
42
  });
141
- return s3Client.send(command);
142
- }
143
- };
144
- }
43
+ const s3Client = new clientS3.S3Client(config);
44
+ const filePrefix = rootPath ? `${rootPath.replace(/\/+$/, '')}/` : '';
45
+ const getFileKey = (file)=>{
46
+ const path = file.path ? `${file.path}/` : '';
47
+ return `${filePrefix}${path}${file.hash}${file.ext}`;
48
+ };
49
+ const upload = async (file, customParams = {})=>{
50
+ const fileKey = getFileKey(file);
51
+ const uploadObj = new libStorage.Upload({
52
+ client: s3Client,
53
+ params: {
54
+ Bucket: config.params.Bucket,
55
+ Key: fileKey,
56
+ Body: file.stream || Buffer.from(file.buffer, 'binary'),
57
+ ACL: config.params.ACL,
58
+ ContentType: file.mime,
59
+ ...customParams
60
+ }
61
+ });
62
+ const upload = await uploadObj.done();
63
+ if (assertUrlProtocol(upload.Location)) {
64
+ file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;
65
+ } else {
66
+ // Default protocol to https protocol
67
+ file.url = `https://${upload.Location}`;
68
+ }
69
+ };
70
+ return {
71
+ isPrivate () {
72
+ return config.params.ACL === 'private';
73
+ },
74
+ async getSignedUrl (file, customParams) {
75
+ // Do not sign the url if it does not come from the same bucket.
76
+ if (!utils.isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {
77
+ return {
78
+ url: file.url
79
+ };
80
+ }
81
+ const fileKey = getFileKey(file);
82
+ const url = await s3RequestPresigner.getSignedUrl(// @ts-expect-error - TODO fix client type
83
+ s3Client, new clientS3.GetObjectCommand({
84
+ Bucket: config.params.Bucket,
85
+ Key: fileKey,
86
+ ...customParams
87
+ }), {
88
+ expiresIn: fp.getOr(15 * 60, [
89
+ 'params',
90
+ 'signedUrlExpires'
91
+ ], config)
92
+ });
93
+ return {
94
+ url
95
+ };
96
+ },
97
+ uploadStream (file, customParams = {}) {
98
+ return upload(file, customParams);
99
+ },
100
+ upload (file, customParams = {}) {
101
+ return upload(file, customParams);
102
+ },
103
+ delete (file, customParams = {}) {
104
+ const command = new clientS3.DeleteObjectCommand({
105
+ Bucket: config.params.Bucket,
106
+ Key: getFileKey(file),
107
+ ...customParams
108
+ });
109
+ return s3Client.send(command);
110
+ }
111
+ };
112
+ }
145
113
  };
114
+
146
115
  module.exports = index;
147
116
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/utils.ts","../src/index.ts"],"sourcesContent":["import type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport type { InitOptions } from '.';\n\nconst ENDPOINT_PATTERN = /^(.+\\.)?s3[.-]([a-z0-9-]+)\\./;\n\ninterface BucketInfo {\n bucket?: string | null;\n err?: string;\n}\n\nexport function isUrlFromBucket(fileUrl: string, bucketName: string, baseUrl = ''): boolean {\n const url = new URL(fileUrl);\n\n // Check if the file URL is using a base URL (e.g. a CDN).\n // In this case do not sign the URL.\n if (baseUrl) {\n return false;\n }\n\n const { bucket } = getBucketFromAwsUrl(fileUrl);\n\n if (bucket) {\n return bucket === bucketName;\n }\n\n // File URL might be of an S3-compatible provider. (or an invalid URL)\n // In this case, check if the bucket name appears in the URL host or path.\n // e.g. https://minio.example.com/bucket-name/object-key\n // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png\n return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);\n}\n\n/**\n * Parse the bucket name from a URL.\n * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html\n *\n * @param {string} fileUrl - the URL to parse\n * @returns {object} result\n * @returns {string} result.bucket - the bucket name\n * @returns {string} result.err - if any\n */\nfunction getBucketFromAwsUrl(fileUrl: string): BucketInfo {\n const url = new URL(fileUrl);\n\n // S3://<bucket-name>/<key>\n if (url.protocol === 's3:') {\n const bucket = url.host;\n\n if (!bucket) {\n return { err: `Invalid S3 url: no bucket: ${url}` };\n }\n return { bucket };\n }\n\n if (!url.host) {\n return { err: `Invalid S3 url: no hostname: ${url}` };\n }\n\n const matches = url.host.match(ENDPOINT_PATTERN);\n if (!matches) {\n return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };\n }\n\n const prefix = matches[1];\n // https://s3.amazonaws.com/<bucket-name>\n if (!prefix) {\n if (url.pathname === '/') {\n return { bucket: null };\n }\n\n const index = url.pathname.indexOf('/', 1);\n\n // https://s3.amazonaws.com/<bucket-name>\n if (index === -1) {\n return { bucket: url.pathname.substring(1) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/\n if (index === url.pathname.length - 1) {\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/key\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://<bucket-name>.s3.amazonaws.com/\n return { bucket: prefix.substring(0, prefix.length - 1) };\n}\n\nexport const extractCredentials = (options: InitOptions): AwsCredentialIdentity | null => {\n if (options.s3Options?.credentials) {\n return {\n accessKeyId: options.s3Options.credentials.accessKeyId,\n secretAccessKey: options.s3Options.credentials.secretAccessKey,\n };\n }\n return null;\n};\n","import type { ReadStream } from 'node:fs';\nimport { getOr } from 'lodash/fp';\nimport {\n S3Client,\n GetObjectCommand,\n DeleteObjectCommand,\n DeleteObjectCommandOutput,\n PutObjectCommandInput,\n CompleteMultipartUploadCommandOutput,\n AbortMultipartUploadCommandOutput,\n S3ClientConfig,\n ObjectCannedACL,\n} from '@aws-sdk/client-s3';\nimport type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { extractCredentials, isUrlFromBucket } from './utils';\n\nexport interface File {\n name: string;\n alternativeText?: string;\n caption?: string;\n width?: number;\n height?: number;\n formats?: Record<string, unknown>;\n hash: string;\n ext?: string;\n mime: string;\n size: number;\n sizeInBytes: number;\n url: string;\n previewUrl?: string;\n path?: string;\n provider?: string;\n provider_metadata?: Record<string, unknown>;\n stream?: ReadStream;\n buffer?: Buffer;\n}\n\nexport type UploadCommandOutput = (\n | CompleteMultipartUploadCommandOutput\n | AbortMultipartUploadCommandOutput\n) & {\n Location: string;\n};\n\nexport interface AWSParams {\n Bucket: string; // making it required\n ACL?: ObjectCannedACL;\n signedUrlExpires?: number;\n}\n\nexport interface DefaultOptions extends S3ClientConfig {\n // TODO Remove this in V5\n accessKeyId?: AwsCredentialIdentity['accessKeyId'];\n secretAccessKey?: AwsCredentialIdentity['secretAccessKey'];\n // Keep this for V5\n credentials?: AwsCredentialIdentity;\n params?: AWSParams;\n [k: string]: any;\n}\n\nexport type InitOptions = (DefaultOptions | { s3Options: DefaultOptions }) & {\n baseUrl?: string;\n rootPath?: string;\n [k: string]: any;\n};\n\nconst assertUrlProtocol = (url: string) => {\n // Regex to test protocol like \"http://\", \"https://\"\n return /^\\w*:\\/\\//.test(url);\n};\n\nconst getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) => {\n if (Object.keys(legacyS3Options).length > 0) {\n process.emitWarning(\n \"S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.\"\n );\n }\n const credentials = extractCredentials({ s3Options, ...legacyS3Options });\n const config = {\n ...s3Options,\n ...legacyS3Options,\n ...(credentials ? { credentials } : {}),\n };\n\n config.params.ACL = getOr(ObjectCannedACL.public_read, ['params', 'ACL'], config);\n\n return config;\n};\n\nexport default {\n init({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) {\n // TODO V5 change config structure to avoid having to do this\n const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });\n const s3Client = new S3Client(config);\n const filePrefix = rootPath ? `${rootPath.replace(/\\/+$/, '')}/` : '';\n\n const getFileKey = (file: File) => {\n const path = file.path ? `${file.path}/` : '';\n return `${filePrefix}${path}${file.hash}${file.ext}`;\n };\n\n const upload = async (file: File, customParams: Partial<PutObjectCommandInput> = {}) => {\n const fileKey = getFileKey(file);\n const uploadObj = new Upload({\n client: s3Client,\n params: {\n Bucket: config.params.Bucket,\n Key: fileKey,\n Body: file.stream || Buffer.from(file.buffer as any, 'binary'),\n ACL: config.params.ACL,\n ContentType: file.mime,\n ...customParams,\n },\n });\n\n const upload = (await uploadObj.done()) as UploadCommandOutput;\n\n if (assertUrlProtocol(upload.Location)) {\n file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;\n } else {\n // Default protocol to https protocol\n file.url = `https://${upload.Location}`;\n }\n };\n\n return {\n isPrivate() {\n return config.params.ACL === 'private';\n },\n\n async getSignedUrl(file: File, customParams: any): Promise<{ url: string }> {\n // Do not sign the url if it does not come from the same bucket.\n if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {\n return { url: file.url };\n }\n const fileKey = getFileKey(file);\n\n const url = await getSignedUrl(\n // @ts-expect-error - TODO fix client type\n s3Client,\n new GetObjectCommand({\n Bucket: config.params.Bucket,\n Key: fileKey,\n ...customParams,\n }),\n {\n expiresIn: getOr(15 * 60, ['params', 'signedUrlExpires'], config),\n }\n );\n\n return { url };\n },\n uploadStream(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n upload(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n delete(file: File, customParams = {}): Promise<DeleteObjectCommandOutput> {\n const command = new DeleteObjectCommand({\n Bucket: config.params.Bucket,\n Key: getFileKey(file),\n ...customParams,\n });\n return s3Client.send(command);\n },\n };\n },\n};\n"],"names":["index","getOr","ObjectCannedACL","S3Client","Upload","upload","getSignedUrl","GetObjectCommand","DeleteObjectCommand"],"mappings":";;;;;AAGA,MAAM,mBAAmB;AAOlB,SAAS,gBAAgB,SAAiB,YAAoB,UAAU,IAAa;AACpF,QAAA,MAAM,IAAI,IAAI,OAAO;AAI3B,MAAI,SAAS;AACJ,WAAA;AAAA,EACT;AAEA,QAAM,EAAE,OAAA,IAAW,oBAAoB,OAAO;AAE9C,MAAI,QAAQ;AACV,WAAO,WAAW;AAAA,EACpB;AAMA,SAAO,IAAI,KAAK,WAAW,GAAG,UAAU,GAAG,KAAK,IAAI,SAAS,SAAS,IAAI,UAAU,GAAG;AACzF;AAWA,SAAS,oBAAoB,SAA6B;AAClD,QAAA,MAAM,IAAI,IAAI,OAAO;AAGvB,MAAA,IAAI,aAAa,OAAO;AAC1B,UAAM,SAAS,IAAI;AAEnB,QAAI,CAAC,QAAQ;AACX,aAAO,EAAE,KAAK,8BAA8B,GAAG,GAAG;AAAA,IACpD;AACA,WAAO,EAAE,OAAO;AAAA,EAClB;AAEI,MAAA,CAAC,IAAI,MAAM;AACb,WAAO,EAAE,KAAK,gCAAgC,GAAG,GAAG;AAAA,EACtD;AAEA,QAAM,UAAU,IAAI,KAAK,MAAM,gBAAgB;AAC/C,MAAI,CAAC,SAAS;AACZ,WAAO,EAAE,KAAK,uEAAuE,GAAG,GAAG;AAAA,EAC7F;AAEM,QAAA,SAAS,QAAQ,CAAC;AAExB,MAAI,CAAC,QAAQ;AACP,QAAA,IAAI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,OAAO;AAAA,YACtB,KAAK;AAAA,YACL,GAAG;AAAA,UAAA,CACJ;AAAA,UACD;AAAA,YACE,WAAWN,SAAM,KAAK,IAAI,CAAC,UAAU,kBAAkB,GAAG,MAAM;AAAA,UAClE;AAAA,QAAA;AAGF,eAAO,EAAE,IAAI;AAAA,MACf;AAAA,MACA,aAAa,MAAY,eAAe,IAAI;AACnC,eAAA,OAAO,MAAM,YAAY;AAAA,MAClC;AAAA,MACA,OAAO,MAAY,eAAe,IAAI;AAC7B,eAAA,OAAO,MAAM,YAAY;AAAA,MAClC;AAAA,MACA,OAAO,MAAY,eAAe,IAAwC;AAClE,cAAA,UAAU,IAAIO,6BAAoB;AAAA,UACtC,QAAQ,OAAO,OAAO;AAAA,UACtB,KAAK,WAAW,IAAI;AAAA,UACpB,GAAG;AAAA,QAAA,CACJ;AACM,eAAA,SAAS,KAAK,OAAO;AAAA,MAC9B;AAAA,IAAA;AAAA,EAEJ;AACF;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import type { ReadStream } from 'node:fs';\nimport { getOr } from 'lodash/fp';\nimport {\n S3Client,\n GetObjectCommand,\n DeleteObjectCommand,\n DeleteObjectCommandOutput,\n PutObjectCommandInput,\n CompleteMultipartUploadCommandOutput,\n AbortMultipartUploadCommandOutput,\n S3ClientConfig,\n ObjectCannedACL,\n} from '@aws-sdk/client-s3';\nimport type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { extractCredentials, isUrlFromBucket } from './utils';\n\nexport interface File {\n name: string;\n alternativeText?: string;\n caption?: string;\n width?: number;\n height?: number;\n formats?: Record<string, unknown>;\n hash: string;\n ext?: string;\n mime: string;\n size: number;\n sizeInBytes: number;\n url: string;\n previewUrl?: string;\n path?: string;\n provider?: string;\n provider_metadata?: Record<string, unknown>;\n stream?: ReadStream;\n buffer?: Buffer;\n}\n\nexport type UploadCommandOutput = (\n | CompleteMultipartUploadCommandOutput\n | AbortMultipartUploadCommandOutput\n) & {\n Location: string;\n};\n\nexport interface AWSParams {\n Bucket: string; // making it required\n ACL?: ObjectCannedACL;\n signedUrlExpires?: number;\n}\n\nexport interface DefaultOptions extends S3ClientConfig {\n // TODO Remove this in V5\n accessKeyId?: AwsCredentialIdentity['accessKeyId'];\n secretAccessKey?: AwsCredentialIdentity['secretAccessKey'];\n // Keep this for V5\n credentials?: AwsCredentialIdentity;\n params?: AWSParams;\n [k: string]: any;\n}\n\nexport type InitOptions = (DefaultOptions | { s3Options: DefaultOptions }) & {\n baseUrl?: string;\n rootPath?: string;\n [k: string]: any;\n};\n\nconst assertUrlProtocol = (url: string) => {\n // Regex to test protocol like \"http://\", \"https://\"\n return /^\\w*:\\/\\//.test(url);\n};\n\nconst getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) => {\n if (Object.keys(legacyS3Options).length > 0) {\n process.emitWarning(\n \"S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.\"\n );\n }\n const credentials = extractCredentials({ s3Options, ...legacyS3Options });\n const config = {\n ...s3Options,\n ...legacyS3Options,\n ...(credentials ? { credentials } : {}),\n };\n\n config.params.ACL = getOr(ObjectCannedACL.public_read, ['params', 'ACL'], config);\n\n return config;\n};\n\nexport default {\n init({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) {\n // TODO V5 change config structure to avoid having to do this\n const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });\n const s3Client = new S3Client(config);\n const filePrefix = rootPath ? `${rootPath.replace(/\\/+$/, '')}/` : '';\n\n const getFileKey = (file: File) => {\n const path = file.path ? `${file.path}/` : '';\n return `${filePrefix}${path}${file.hash}${file.ext}`;\n };\n\n const upload = async (file: File, customParams: Partial<PutObjectCommandInput> = {}) => {\n const fileKey = getFileKey(file);\n const uploadObj = new Upload({\n client: s3Client,\n params: {\n Bucket: config.params.Bucket,\n Key: fileKey,\n Body: file.stream || Buffer.from(file.buffer as any, 'binary'),\n ACL: config.params.ACL,\n ContentType: file.mime,\n ...customParams,\n },\n });\n\n const upload = (await uploadObj.done()) as UploadCommandOutput;\n\n if (assertUrlProtocol(upload.Location)) {\n file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;\n } else {\n // Default protocol to https protocol\n file.url = `https://${upload.Location}`;\n }\n };\n\n return {\n isPrivate() {\n return config.params.ACL === 'private';\n },\n\n async getSignedUrl(file: File, customParams: any): Promise<{ url: string }> {\n // Do not sign the url if it does not come from the same bucket.\n if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {\n return { url: file.url };\n }\n const fileKey = getFileKey(file);\n\n const url = await getSignedUrl(\n // @ts-expect-error - TODO fix client type\n s3Client,\n new GetObjectCommand({\n Bucket: config.params.Bucket,\n Key: fileKey,\n ...customParams,\n }),\n {\n expiresIn: getOr(15 * 60, ['params', 'signedUrlExpires'], config),\n }\n );\n\n return { url };\n },\n uploadStream(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n upload(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n delete(file: File, customParams = {}): Promise<DeleteObjectCommandOutput> {\n const command = new DeleteObjectCommand({\n Bucket: config.params.Bucket,\n Key: getFileKey(file),\n ...customParams,\n });\n return s3Client.send(command);\n },\n };\n },\n};\n"],"names":["assertUrlProtocol","url","test","getConfig","baseUrl","rootPath","s3Options","legacyS3Options","Object","keys","length","process","emitWarning","credentials","extractCredentials","config","params","ACL","getOr","ObjectCannedACL","public_read","init","s3Client","S3Client","filePrefix","replace","getFileKey","file","path","hash","ext","upload","customParams","fileKey","uploadObj","Upload","client","Bucket","Key","Body","stream","Buffer","from","buffer","ContentType","mime","done","Location","isPrivate","getSignedUrl","isUrlFromBucket","GetObjectCommand","expiresIn","uploadStream","delete","command","DeleteObjectCommand","send"],"mappings":";;;;;;;;AAoEA,MAAMA,oBAAoB,CAACC,GAAAA,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EK,YAAe,GAAA,EAAE,EAAA;gBAClC,MAAMuB,OAAAA,GAAU,IAAIC,4BAAoB,CAAA;oBACtCnB,MAAQtB,EAAAA,MAAAA,CAAOC,MAAM,CAACqB,MAAM;AAC5BC,oBAAAA,GAAAA,EAAKZ,UAAWC,CAAAA,IAAAA,CAAAA;AAChB,oBAAA,GAAGK;AACL,iBAAA,CAAA;gBACA,OAAOV,QAAAA,CAASmC,IAAI,CAACF,OAAAA,CAAAA;AACvB;AACF,SAAA;AACF;AACF,CAAE;;;;"}
package/dist/index.mjs CHANGED
@@ -1,148 +1,114 @@
1
- import { getOr } from "lodash/fp";
2
- import { S3Client, GetObjectCommand, DeleteObjectCommand, ObjectCannedACL } from "@aws-sdk/client-s3";
3
- import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
4
- import { Upload } from "@aws-sdk/lib-storage";
5
- const ENDPOINT_PATTERN = /^(.+\.)?s3[.-]([a-z0-9-]+)\./;
6
- function isUrlFromBucket(fileUrl, bucketName, baseUrl = "") {
7
- const url = new URL(fileUrl);
8
- if (baseUrl) {
9
- return false;
10
- }
11
- const { bucket } = getBucketFromAwsUrl(fileUrl);
12
- if (bucket) {
13
- return bucket === bucketName;
14
- }
15
- return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);
16
- }
17
- function getBucketFromAwsUrl(fileUrl) {
18
- const url = new URL(fileUrl);
19
- if (url.protocol === "s3:") {
20
- const bucket = url.host;
21
- if (!bucket) {
22
- return { err: `Invalid S3 url: no bucket: ${url}` };
23
- }
24
- return { bucket };
25
- }
26
- if (!url.host) {
27
- return { err: `Invalid S3 url: no hostname: ${url}` };
28
- }
29
- const matches = url.host.match(ENDPOINT_PATTERN);
30
- if (!matches) {
31
- return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };
32
- }
33
- const prefix = matches[1];
34
- if (!prefix) {
35
- if (url.pathname === "/") {
36
- return { bucket: null };
37
- }
38
- const index2 = url.pathname.indexOf("/", 1);
39
- if (index2 === -1) {
40
- return { bucket: url.pathname.substring(1) };
41
- }
42
- if (index2 === url.pathname.length - 1) {
43
- return { bucket: url.pathname.substring(1, index2) };
1
+ import { getOr } from 'lodash/fp';
2
+ import { S3Client, GetObjectCommand, DeleteObjectCommand, ObjectCannedACL } from '@aws-sdk/client-s3';
3
+ import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
4
+ import { Upload } from '@aws-sdk/lib-storage';
5
+ import { isUrlFromBucket, extractCredentials } from './utils.mjs';
6
+
7
+ const assertUrlProtocol = (url)=>{
8
+ // Regex to test protocol like "http://", "https://"
9
+ return /^\w*:\/\//.test(url);
10
+ };
11
+ const getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options })=>{
12
+ if (Object.keys(legacyS3Options).length > 0) {
13
+ process.emitWarning("S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.");
44
14
  }
45
- return { bucket: url.pathname.substring(1, index2) };
46
- }
47
- return { bucket: prefix.substring(0, prefix.length - 1) };
48
- }
49
- const extractCredentials = (options) => {
50
- if (options.s3Options?.credentials) {
51
- return {
52
- accessKeyId: options.s3Options.credentials.accessKeyId,
53
- secretAccessKey: options.s3Options.credentials.secretAccessKey
15
+ const credentials = extractCredentials({
16
+ s3Options,
17
+ ...legacyS3Options
18
+ });
19
+ const config = {
20
+ ...s3Options,
21
+ ...legacyS3Options,
22
+ ...credentials ? {
23
+ credentials
24
+ } : {}
54
25
  };
55
- }
56
- return null;
57
- };
58
- const assertUrlProtocol = (url) => {
59
- return /^\w*:\/\//.test(url);
60
- };
61
- const getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }) => {
62
- if (Object.keys(legacyS3Options).length > 0) {
63
- process.emitWarning(
64
- "S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property."
65
- );
66
- }
67
- const credentials = extractCredentials({ s3Options, ...legacyS3Options });
68
- const config = {
69
- ...s3Options,
70
- ...legacyS3Options,
71
- ...credentials ? { credentials } : {}
72
- };
73
- config.params.ACL = getOr(ObjectCannedACL.public_read, ["params", "ACL"], config);
74
- return config;
26
+ config.params.ACL = getOr(ObjectCannedACL.public_read, [
27
+ 'params',
28
+ 'ACL'
29
+ ], config);
30
+ return config;
75
31
  };
76
- const index = {
77
- init({ baseUrl, rootPath, s3Options, ...legacyS3Options }) {
78
- const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });
79
- const s3Client = new S3Client(config);
80
- const filePrefix = rootPath ? `${rootPath.replace(/\/+$/, "")}/` : "";
81
- const getFileKey = (file) => {
82
- const path = file.path ? `${file.path}/` : "";
83
- return `${filePrefix}${path}${file.hash}${file.ext}`;
84
- };
85
- const upload = async (file, customParams = {}) => {
86
- const fileKey = getFileKey(file);
87
- const uploadObj = new Upload({
88
- client: s3Client,
89
- params: {
90
- Bucket: config.params.Bucket,
91
- Key: fileKey,
92
- Body: file.stream || Buffer.from(file.buffer, "binary"),
93
- ACL: config.params.ACL,
94
- ContentType: file.mime,
95
- ...customParams
96
- }
97
- });
98
- const upload2 = await uploadObj.done();
99
- if (assertUrlProtocol(upload2.Location)) {
100
- file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload2.Location;
101
- } else {
102
- file.url = `https://${upload2.Location}`;
103
- }
104
- };
105
- return {
106
- isPrivate() {
107
- return config.params.ACL === "private";
108
- },
109
- async getSignedUrl(file, customParams) {
110
- if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {
111
- return { url: file.url };
112
- }
113
- const fileKey = getFileKey(file);
114
- const url = await getSignedUrl(
115
- // @ts-expect-error - TODO fix client type
116
- s3Client,
117
- new GetObjectCommand({
118
- Bucket: config.params.Bucket,
119
- Key: fileKey,
120
- ...customParams
121
- }),
122
- {
123
- expiresIn: getOr(15 * 60, ["params", "signedUrlExpires"], config)
124
- }
125
- );
126
- return { url };
127
- },
128
- uploadStream(file, customParams = {}) {
129
- return upload(file, customParams);
130
- },
131
- upload(file, customParams = {}) {
132
- return upload(file, customParams);
133
- },
134
- delete(file, customParams = {}) {
135
- const command = new DeleteObjectCommand({
136
- Bucket: config.params.Bucket,
137
- Key: getFileKey(file),
138
- ...customParams
32
+ var index = {
33
+ init ({ baseUrl, rootPath, s3Options, ...legacyS3Options }) {
34
+ // TODO V5 change config structure to avoid having to do this
35
+ const config = getConfig({
36
+ baseUrl,
37
+ rootPath,
38
+ s3Options,
39
+ ...legacyS3Options
139
40
  });
140
- return s3Client.send(command);
141
- }
142
- };
143
- }
144
- };
145
- export {
146
- index as default
41
+ const s3Client = new S3Client(config);
42
+ const filePrefix = rootPath ? `${rootPath.replace(/\/+$/, '')}/` : '';
43
+ const getFileKey = (file)=>{
44
+ const path = file.path ? `${file.path}/` : '';
45
+ return `${filePrefix}${path}${file.hash}${file.ext}`;
46
+ };
47
+ const upload = async (file, customParams = {})=>{
48
+ const fileKey = getFileKey(file);
49
+ const uploadObj = new Upload({
50
+ client: s3Client,
51
+ params: {
52
+ Bucket: config.params.Bucket,
53
+ Key: fileKey,
54
+ Body: file.stream || Buffer.from(file.buffer, 'binary'),
55
+ ACL: config.params.ACL,
56
+ ContentType: file.mime,
57
+ ...customParams
58
+ }
59
+ });
60
+ const upload = await uploadObj.done();
61
+ if (assertUrlProtocol(upload.Location)) {
62
+ file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;
63
+ } else {
64
+ // Default protocol to https protocol
65
+ file.url = `https://${upload.Location}`;
66
+ }
67
+ };
68
+ return {
69
+ isPrivate () {
70
+ return config.params.ACL === 'private';
71
+ },
72
+ async getSignedUrl (file, customParams) {
73
+ // Do not sign the url if it does not come from the same bucket.
74
+ if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {
75
+ return {
76
+ url: file.url
77
+ };
78
+ }
79
+ const fileKey = getFileKey(file);
80
+ const url = await getSignedUrl(// @ts-expect-error - TODO fix client type
81
+ s3Client, new GetObjectCommand({
82
+ Bucket: config.params.Bucket,
83
+ Key: fileKey,
84
+ ...customParams
85
+ }), {
86
+ expiresIn: getOr(15 * 60, [
87
+ 'params',
88
+ 'signedUrlExpires'
89
+ ], config)
90
+ });
91
+ return {
92
+ url
93
+ };
94
+ },
95
+ uploadStream (file, customParams = {}) {
96
+ return upload(file, customParams);
97
+ },
98
+ upload (file, customParams = {}) {
99
+ return upload(file, customParams);
100
+ },
101
+ delete (file, customParams = {}) {
102
+ const command = new DeleteObjectCommand({
103
+ Bucket: config.params.Bucket,
104
+ Key: getFileKey(file),
105
+ ...customParams
106
+ });
107
+ return s3Client.send(command);
108
+ }
109
+ };
110
+ }
147
111
  };
112
+
113
+ export { index as default };
148
114
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/utils.ts","../src/index.ts"],"sourcesContent":["import type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport type { InitOptions } from '.';\n\nconst ENDPOINT_PATTERN = /^(.+\\.)?s3[.-]([a-z0-9-]+)\\./;\n\ninterface BucketInfo {\n bucket?: string | null;\n err?: string;\n}\n\nexport function isUrlFromBucket(fileUrl: string, bucketName: string, baseUrl = ''): boolean {\n const url = new URL(fileUrl);\n\n // Check if the file URL is using a base URL (e.g. a CDN).\n // In this case do not sign the URL.\n if (baseUrl) {\n return false;\n }\n\n const { bucket } = getBucketFromAwsUrl(fileUrl);\n\n if (bucket) {\n return bucket === bucketName;\n }\n\n // File URL might be of an S3-compatible provider. (or an invalid URL)\n // In this case, check if the bucket name appears in the URL host or path.\n // e.g. https://minio.example.com/bucket-name/object-key\n // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png\n return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);\n}\n\n/**\n * Parse the bucket name from a URL.\n * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html\n *\n * @param {string} fileUrl - the URL to parse\n * @returns {object} result\n * @returns {string} result.bucket - the bucket name\n * @returns {string} result.err - if any\n */\nfunction getBucketFromAwsUrl(fileUrl: string): BucketInfo {\n const url = new URL(fileUrl);\n\n // S3://<bucket-name>/<key>\n if (url.protocol === 's3:') {\n const bucket = url.host;\n\n if (!bucket) {\n return { err: `Invalid S3 url: no bucket: ${url}` };\n }\n return { bucket };\n }\n\n if (!url.host) {\n return { err: `Invalid S3 url: no hostname: ${url}` };\n }\n\n const matches = url.host.match(ENDPOINT_PATTERN);\n if (!matches) {\n return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };\n }\n\n const prefix = matches[1];\n // https://s3.amazonaws.com/<bucket-name>\n if (!prefix) {\n if (url.pathname === '/') {\n return { bucket: null };\n }\n\n const index = url.pathname.indexOf('/', 1);\n\n // https://s3.amazonaws.com/<bucket-name>\n if (index === -1) {\n return { bucket: url.pathname.substring(1) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/\n if (index === url.pathname.length - 1) {\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/key\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://<bucket-name>.s3.amazonaws.com/\n return { bucket: prefix.substring(0, prefix.length - 1) };\n}\n\nexport const extractCredentials = (options: InitOptions): AwsCredentialIdentity | null => {\n if (options.s3Options?.credentials) {\n return {\n accessKeyId: options.s3Options.credentials.accessKeyId,\n secretAccessKey: options.s3Options.credentials.secretAccessKey,\n };\n }\n return null;\n};\n","import type { ReadStream } from 'node:fs';\nimport { getOr } from 'lodash/fp';\nimport {\n S3Client,\n GetObjectCommand,\n DeleteObjectCommand,\n DeleteObjectCommandOutput,\n PutObjectCommandInput,\n CompleteMultipartUploadCommandOutput,\n AbortMultipartUploadCommandOutput,\n S3ClientConfig,\n ObjectCannedACL,\n} from '@aws-sdk/client-s3';\nimport type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { extractCredentials, isUrlFromBucket } from './utils';\n\nexport interface File {\n name: string;\n alternativeText?: string;\n caption?: string;\n width?: number;\n height?: number;\n formats?: Record<string, unknown>;\n hash: string;\n ext?: string;\n mime: string;\n size: number;\n sizeInBytes: number;\n url: string;\n previewUrl?: string;\n path?: string;\n provider?: string;\n provider_metadata?: Record<string, unknown>;\n stream?: ReadStream;\n buffer?: Buffer;\n}\n\nexport type UploadCommandOutput = (\n | CompleteMultipartUploadCommandOutput\n | AbortMultipartUploadCommandOutput\n) & {\n Location: string;\n};\n\nexport interface AWSParams {\n Bucket: string; // making it required\n ACL?: ObjectCannedACL;\n signedUrlExpires?: number;\n}\n\nexport interface DefaultOptions extends S3ClientConfig {\n // TODO Remove this in V5\n accessKeyId?: AwsCredentialIdentity['accessKeyId'];\n secretAccessKey?: AwsCredentialIdentity['secretAccessKey'];\n // Keep this for V5\n credentials?: AwsCredentialIdentity;\n params?: AWSParams;\n [k: string]: any;\n}\n\nexport type InitOptions = (DefaultOptions | { s3Options: DefaultOptions }) & {\n baseUrl?: string;\n rootPath?: string;\n [k: string]: any;\n};\n\nconst assertUrlProtocol = (url: string) => {\n // Regex to test protocol like \"http://\", \"https://\"\n return /^\\w*:\\/\\//.test(url);\n};\n\nconst getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) => {\n if (Object.keys(legacyS3Options).length > 0) {\n process.emitWarning(\n \"S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.\"\n );\n }\n const credentials = extractCredentials({ s3Options, ...legacyS3Options });\n const config = {\n ...s3Options,\n ...legacyS3Options,\n ...(credentials ? { credentials } : {}),\n };\n\n config.params.ACL = getOr(ObjectCannedACL.public_read, ['params', 'ACL'], config);\n\n return config;\n};\n\nexport default {\n init({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) {\n // TODO V5 change config structure to avoid having to do this\n const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });\n const s3Client = new S3Client(config);\n const filePrefix = rootPath ? `${rootPath.replace(/\\/+$/, '')}/` : '';\n\n const getFileKey = (file: File) => {\n const path = file.path ? `${file.path}/` : '';\n return `${filePrefix}${path}${file.hash}${file.ext}`;\n };\n\n const upload = async (file: File, customParams: Partial<PutObjectCommandInput> = {}) => {\n const fileKey = getFileKey(file);\n const uploadObj = new Upload({\n client: s3Client,\n params: {\n Bucket: config.params.Bucket,\n Key: fileKey,\n Body: file.stream || Buffer.from(file.buffer as any, 'binary'),\n ACL: config.params.ACL,\n ContentType: file.mime,\n ...customParams,\n },\n });\n\n const upload = (await uploadObj.done()) as UploadCommandOutput;\n\n if (assertUrlProtocol(upload.Location)) {\n file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;\n } else {\n // Default protocol to https protocol\n file.url = `https://${upload.Location}`;\n }\n };\n\n return {\n isPrivate() {\n return config.params.ACL === 'private';\n },\n\n async getSignedUrl(file: File, customParams: any): Promise<{ url: string }> {\n // Do not sign the url if it does not come from the same bucket.\n if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {\n return { url: file.url };\n }\n const fileKey = getFileKey(file);\n\n const url = await getSignedUrl(\n // @ts-expect-error - TODO fix client type\n s3Client,\n new GetObjectCommand({\n Bucket: config.params.Bucket,\n Key: fileKey,\n ...customParams,\n }),\n {\n expiresIn: getOr(15 * 60, ['params', 'signedUrlExpires'], config),\n }\n );\n\n return { url };\n },\n uploadStream(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n upload(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n delete(file: File, customParams = {}): Promise<DeleteObjectCommandOutput> {\n const command = new DeleteObjectCommand({\n Bucket: config.params.Bucket,\n Key: getFileKey(file),\n ...customParams,\n });\n return s3Client.send(command);\n },\n };\n },\n};\n"],"names":["index","upload"],"mappings":";;;;AAGA,MAAM,mBAAmB;AAOlB,SAAS,gBAAgB,SAAiB,YAAoB,UAAU,IAAa;AACpF,QAA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;AAAA,UACpB,GAAG;AAAA,QAAA,CACJ;AACM,eAAA,SAAS,KAAK,OAAO;AAAA,MAC9B;AAAA,IAAA;AAAA,EAEJ;AACF;"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":["import type { ReadStream } from 'node:fs';\nimport { getOr } from 'lodash/fp';\nimport {\n S3Client,\n GetObjectCommand,\n DeleteObjectCommand,\n DeleteObjectCommandOutput,\n PutObjectCommandInput,\n CompleteMultipartUploadCommandOutput,\n AbortMultipartUploadCommandOutput,\n S3ClientConfig,\n ObjectCannedACL,\n} from '@aws-sdk/client-s3';\nimport type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { extractCredentials, isUrlFromBucket } from './utils';\n\nexport interface File {\n name: string;\n alternativeText?: string;\n caption?: string;\n width?: number;\n height?: number;\n formats?: Record<string, unknown>;\n hash: string;\n ext?: string;\n mime: string;\n size: number;\n sizeInBytes: number;\n url: string;\n previewUrl?: string;\n path?: string;\n provider?: string;\n provider_metadata?: Record<string, unknown>;\n stream?: ReadStream;\n buffer?: Buffer;\n}\n\nexport type UploadCommandOutput = (\n | CompleteMultipartUploadCommandOutput\n | AbortMultipartUploadCommandOutput\n) & {\n Location: string;\n};\n\nexport interface AWSParams {\n Bucket: string; // making it required\n ACL?: ObjectCannedACL;\n signedUrlExpires?: number;\n}\n\nexport interface DefaultOptions extends S3ClientConfig {\n // TODO Remove this in V5\n accessKeyId?: AwsCredentialIdentity['accessKeyId'];\n secretAccessKey?: AwsCredentialIdentity['secretAccessKey'];\n // Keep this for V5\n credentials?: AwsCredentialIdentity;\n params?: AWSParams;\n [k: string]: any;\n}\n\nexport type InitOptions = (DefaultOptions | { s3Options: DefaultOptions }) & {\n baseUrl?: string;\n rootPath?: string;\n [k: string]: any;\n};\n\nconst assertUrlProtocol = (url: string) => {\n // Regex to test protocol like \"http://\", \"https://\"\n return /^\\w*:\\/\\//.test(url);\n};\n\nconst getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) => {\n if (Object.keys(legacyS3Options).length > 0) {\n process.emitWarning(\n \"S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.\"\n );\n }\n const credentials = extractCredentials({ s3Options, ...legacyS3Options });\n const config = {\n ...s3Options,\n ...legacyS3Options,\n ...(credentials ? { credentials } : {}),\n };\n\n config.params.ACL = getOr(ObjectCannedACL.public_read, ['params', 'ACL'], config);\n\n return config;\n};\n\nexport default {\n init({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) {\n // TODO V5 change config structure to avoid having to do this\n const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });\n const s3Client = new S3Client(config);\n const filePrefix = rootPath ? `${rootPath.replace(/\\/+$/, '')}/` : '';\n\n const getFileKey = (file: File) => {\n const path = file.path ? `${file.path}/` : '';\n return `${filePrefix}${path}${file.hash}${file.ext}`;\n };\n\n const upload = async (file: File, customParams: Partial<PutObjectCommandInput> = {}) => {\n const fileKey = getFileKey(file);\n const uploadObj = new Upload({\n client: s3Client,\n params: {\n Bucket: config.params.Bucket,\n Key: fileKey,\n Body: file.stream || Buffer.from(file.buffer as any, 'binary'),\n ACL: config.params.ACL,\n ContentType: file.mime,\n ...customParams,\n },\n });\n\n const upload = (await uploadObj.done()) as UploadCommandOutput;\n\n if (assertUrlProtocol(upload.Location)) {\n file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;\n } else {\n // Default protocol to https protocol\n file.url = `https://${upload.Location}`;\n }\n };\n\n return {\n isPrivate() {\n return config.params.ACL === 'private';\n },\n\n async getSignedUrl(file: File, customParams: any): Promise<{ url: string }> {\n // Do not sign the url if it does not come from the same bucket.\n if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {\n return { url: file.url };\n }\n const fileKey = getFileKey(file);\n\n const url = await getSignedUrl(\n // @ts-expect-error - TODO fix client type\n s3Client,\n new GetObjectCommand({\n Bucket: config.params.Bucket,\n Key: fileKey,\n ...customParams,\n }),\n {\n expiresIn: getOr(15 * 60, ['params', 'signedUrlExpires'], config),\n }\n );\n\n return { url };\n },\n uploadStream(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n upload(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n delete(file: File, customParams = {}): Promise<DeleteObjectCommandOutput> {\n const command = new DeleteObjectCommand({\n Bucket: config.params.Bucket,\n Key: getFileKey(file),\n ...customParams,\n });\n return s3Client.send(command);\n },\n };\n },\n};\n"],"names":["assertUrlProtocol","url","test","getConfig","baseUrl","rootPath","s3Options","legacyS3Options","Object","keys","length","process","emitWarning","credentials","extractCredentials","config","params","ACL","getOr","ObjectCannedACL","public_read","init","s3Client","S3Client","filePrefix","replace","getFileKey","file","path","hash","ext","upload","customParams","fileKey","uploadObj","Upload","client","Bucket","Key","Body","stream","Buffer","from","buffer","ContentType","mime","done","Location","isPrivate","getSignedUrl","isUrlFromBucket","GetObjectCommand","expiresIn","uploadStream","delete","command","DeleteObjectCommand","send"],"mappings":";;;;;;AAoEA,MAAMA,oBAAoB,CAACC,GAAAA,GAAAA;;IAEzB,OAAO,WAAA,CAAYC,IAAI,CAACD,GAAAA,CAAAA;AAC1B,CAAA;AAEA,MAAME,SAAAA,GAAY,CAAC,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,SAAS,EAAE,GAAGC,eAA8B,EAAA,GAAA;AAClF,IAAA,IAAIC,OAAOC,IAAI,CAACF,eAAiBG,CAAAA,CAAAA,MAAM,GAAG,CAAG,EAAA;AAC3CC,QAAAA,OAAAA,CAAQC,WAAW,CACjB,2LAAA,CAAA;AAEJ;AACA,IAAA,MAAMC,cAAcC,kBAAmB,CAAA;AAAER,QAAAA,SAAAA;AAAW,QAAA,GAAGC;AAAgB,KAAA,CAAA;AACvE,IAAA,MAAMQ,MAAS,GAAA;AACb,QAAA,GAAGT,SAAS;AAC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 const url = new URL(fileUrl);
6
+ // Check if the file URL is using a base URL (e.g. a CDN).
7
+ // In this case do not sign the URL.
8
+ if (baseUrl) {
9
+ return false;
10
+ }
11
+ const { bucket } = getBucketFromAwsUrl(fileUrl);
12
+ if (bucket) {
13
+ return bucket === bucketName;
14
+ }
15
+ // File URL might be of an S3-compatible provider. (or an invalid URL)
16
+ // In this case, check if the bucket name appears in the URL host or path.
17
+ // e.g. https://minio.example.com/bucket-name/object-key
18
+ // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png
19
+ return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);
20
+ }
21
+ /**
22
+ * Parse the bucket name from a URL.
23
+ * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html
24
+ *
25
+ * @param {string} fileUrl - the URL to parse
26
+ * @returns {object} result
27
+ * @returns {string} result.bucket - the bucket name
28
+ * @returns {string} result.err - if any
29
+ */ function getBucketFromAwsUrl(fileUrl) {
30
+ const url = new URL(fileUrl);
31
+ // S3://<bucket-name>/<key>
32
+ if (url.protocol === 's3:') {
33
+ const bucket = url.host;
34
+ if (!bucket) {
35
+ return {
36
+ err: `Invalid S3 url: no bucket: ${url}`
37
+ };
38
+ }
39
+ return {
40
+ bucket
41
+ };
42
+ }
43
+ if (!url.host) {
44
+ return {
45
+ err: `Invalid S3 url: no hostname: ${url}`
46
+ };
47
+ }
48
+ const matches = url.host.match(ENDPOINT_PATTERN);
49
+ if (!matches) {
50
+ return {
51
+ err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}`
52
+ };
53
+ }
54
+ const prefix = matches[1];
55
+ // https://s3.amazonaws.com/<bucket-name>
56
+ if (!prefix) {
57
+ if (url.pathname === '/') {
58
+ return {
59
+ bucket: null
60
+ };
61
+ }
62
+ const index = url.pathname.indexOf('/', 1);
63
+ // https://s3.amazonaws.com/<bucket-name>
64
+ if (index === -1) {
65
+ return {
66
+ bucket: url.pathname.substring(1)
67
+ };
68
+ }
69
+ // https://s3.amazonaws.com/<bucket-name>/
70
+ if (index === url.pathname.length - 1) {
71
+ return {
72
+ bucket: url.pathname.substring(1, index)
73
+ };
74
+ }
75
+ // https://s3.amazonaws.com/<bucket-name>/key
76
+ return {
77
+ bucket: url.pathname.substring(1, index)
78
+ };
79
+ }
80
+ // https://<bucket-name>.s3.amazonaws.com/
81
+ return {
82
+ bucket: prefix.substring(0, prefix.length - 1)
83
+ };
84
+ }
85
+ const extractCredentials = (options)=>{
86
+ if (options.s3Options?.credentials) {
87
+ return {
88
+ accessKeyId: options.s3Options.credentials.accessKeyId,
89
+ secretAccessKey: options.s3Options.credentials.secretAccessKey
90
+ };
91
+ }
92
+ return null;
93
+ };
94
+
95
+ exports.extractCredentials = extractCredentials;
96
+ exports.isUrlFromBucket = isUrlFromBucket;
97
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sources":["../src/utils.ts"],"sourcesContent":["import type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport type { InitOptions } from '.';\n\nconst ENDPOINT_PATTERN = /^(.+\\.)?s3[.-]([a-z0-9-]+)\\./;\n\ninterface BucketInfo {\n bucket?: string | null;\n err?: string;\n}\n\nexport function isUrlFromBucket(fileUrl: string, bucketName: string, baseUrl = ''): boolean {\n const url = new URL(fileUrl);\n\n // Check if the file URL is using a base URL (e.g. a CDN).\n // In this case do not sign the URL.\n if (baseUrl) {\n return false;\n }\n\n const { bucket } = getBucketFromAwsUrl(fileUrl);\n\n if (bucket) {\n return bucket === bucketName;\n }\n\n // File URL might be of an S3-compatible provider. (or an invalid URL)\n // In this case, check if the bucket name appears in the URL host or path.\n // e.g. https://minio.example.com/bucket-name/object-key\n // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png\n return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);\n}\n\n/**\n * Parse the bucket name from a URL.\n * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html\n *\n * @param {string} fileUrl - the URL to parse\n * @returns {object} result\n * @returns {string} result.bucket - the bucket name\n * @returns {string} result.err - if any\n */\nfunction getBucketFromAwsUrl(fileUrl: string): BucketInfo {\n const url = new URL(fileUrl);\n\n // S3://<bucket-name>/<key>\n if (url.protocol === 's3:') {\n const bucket = url.host;\n\n if (!bucket) {\n return { err: `Invalid S3 url: no bucket: ${url}` };\n }\n return { bucket };\n }\n\n if (!url.host) {\n return { err: `Invalid S3 url: no hostname: ${url}` };\n }\n\n const matches = url.host.match(ENDPOINT_PATTERN);\n if (!matches) {\n return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };\n }\n\n const prefix = matches[1];\n // https://s3.amazonaws.com/<bucket-name>\n if (!prefix) {\n if (url.pathname === '/') {\n return { bucket: null };\n }\n\n const index = url.pathname.indexOf('/', 1);\n\n // https://s3.amazonaws.com/<bucket-name>\n if (index === -1) {\n return { bucket: url.pathname.substring(1) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/\n if (index === url.pathname.length - 1) {\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/key\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://<bucket-name>.s3.amazonaws.com/\n return { bucket: prefix.substring(0, prefix.length - 1) };\n}\n\nexport const extractCredentials = (options: InitOptions): AwsCredentialIdentity | null => {\n if (options.s3Options?.credentials) {\n return {\n accessKeyId: options.s3Options.credentials.accessKeyId,\n secretAccessKey: options.s3Options.credentials.secretAccessKey,\n };\n }\n return null;\n};\n"],"names":["ENDPOINT_PATTERN","isUrlFromBucket","fileUrl","bucketName","baseUrl","url","URL","bucket","getBucketFromAwsUrl","host","startsWith","pathname","includes","protocol","err","matches","match","prefix","index","indexOf","substring","length","extractCredentials","options","s3Options","credentials","accessKeyId","secretAccessKey"],"mappings":";;AAGA,MAAMA,gBAAmB,GAAA,8BAAA;AAOlB,SAASC,eAAgB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ENDPOINT_PATTERN = /^(.+\.)?s3[.-]([a-z0-9-]+)\./;
2
+ function isUrlFromBucket(fileUrl, bucketName, baseUrl = '') {
3
+ const url = new URL(fileUrl);
4
+ // Check if the file URL is using a base URL (e.g. a CDN).
5
+ // In this case do not sign the URL.
6
+ if (baseUrl) {
7
+ return false;
8
+ }
9
+ const { bucket } = getBucketFromAwsUrl(fileUrl);
10
+ if (bucket) {
11
+ return bucket === bucketName;
12
+ }
13
+ // File URL might be of an S3-compatible provider. (or an invalid URL)
14
+ // In this case, check if the bucket name appears in the URL host or path.
15
+ // e.g. https://minio.example.com/bucket-name/object-key
16
+ // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png
17
+ return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);
18
+ }
19
+ /**
20
+ * Parse the bucket name from a URL.
21
+ * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html
22
+ *
23
+ * @param {string} fileUrl - the URL to parse
24
+ * @returns {object} result
25
+ * @returns {string} result.bucket - the bucket name
26
+ * @returns {string} result.err - if any
27
+ */ function getBucketFromAwsUrl(fileUrl) {
28
+ const url = new URL(fileUrl);
29
+ // S3://<bucket-name>/<key>
30
+ if (url.protocol === 's3:') {
31
+ const bucket = url.host;
32
+ if (!bucket) {
33
+ return {
34
+ err: `Invalid S3 url: no bucket: ${url}`
35
+ };
36
+ }
37
+ return {
38
+ bucket
39
+ };
40
+ }
41
+ if (!url.host) {
42
+ return {
43
+ err: `Invalid S3 url: no hostname: ${url}`
44
+ };
45
+ }
46
+ const matches = url.host.match(ENDPOINT_PATTERN);
47
+ if (!matches) {
48
+ return {
49
+ err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}`
50
+ };
51
+ }
52
+ const prefix = matches[1];
53
+ // https://s3.amazonaws.com/<bucket-name>
54
+ if (!prefix) {
55
+ if (url.pathname === '/') {
56
+ return {
57
+ bucket: null
58
+ };
59
+ }
60
+ const index = url.pathname.indexOf('/', 1);
61
+ // https://s3.amazonaws.com/<bucket-name>
62
+ if (index === -1) {
63
+ return {
64
+ bucket: url.pathname.substring(1)
65
+ };
66
+ }
67
+ // https://s3.amazonaws.com/<bucket-name>/
68
+ if (index === url.pathname.length - 1) {
69
+ return {
70
+ bucket: url.pathname.substring(1, index)
71
+ };
72
+ }
73
+ // https://s3.amazonaws.com/<bucket-name>/key
74
+ return {
75
+ bucket: url.pathname.substring(1, index)
76
+ };
77
+ }
78
+ // https://<bucket-name>.s3.amazonaws.com/
79
+ return {
80
+ bucket: prefix.substring(0, prefix.length - 1)
81
+ };
82
+ }
83
+ const extractCredentials = (options)=>{
84
+ if (options.s3Options?.credentials) {
85
+ return {
86
+ accessKeyId: options.s3Options.credentials.accessKeyId,
87
+ secretAccessKey: options.s3Options.credentials.secretAccessKey
88
+ };
89
+ }
90
+ return null;
91
+ };
92
+
93
+ export { extractCredentials, isUrlFromBucket };
94
+ //# sourceMappingURL=utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","sources":["../src/utils.ts"],"sourcesContent":["import type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport type { InitOptions } from '.';\n\nconst ENDPOINT_PATTERN = /^(.+\\.)?s3[.-]([a-z0-9-]+)\\./;\n\ninterface BucketInfo {\n bucket?: string | null;\n err?: string;\n}\n\nexport function isUrlFromBucket(fileUrl: string, bucketName: string, baseUrl = ''): boolean {\n const url = new URL(fileUrl);\n\n // Check if the file URL is using a base URL (e.g. a CDN).\n // In this case do not sign the URL.\n if (baseUrl) {\n return false;\n }\n\n const { bucket } = getBucketFromAwsUrl(fileUrl);\n\n if (bucket) {\n return bucket === bucketName;\n }\n\n // File URL might be of an S3-compatible provider. (or an invalid URL)\n // In this case, check if the bucket name appears in the URL host or path.\n // e.g. https://minio.example.com/bucket-name/object-key\n // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png\n return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);\n}\n\n/**\n * Parse the bucket name from a URL.\n * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html\n *\n * @param {string} fileUrl - the URL to parse\n * @returns {object} result\n * @returns {string} result.bucket - the bucket name\n * @returns {string} result.err - if any\n */\nfunction getBucketFromAwsUrl(fileUrl: string): BucketInfo {\n const url = new URL(fileUrl);\n\n // S3://<bucket-name>/<key>\n if (url.protocol === 's3:') {\n const bucket = url.host;\n\n if (!bucket) {\n return { err: `Invalid S3 url: no bucket: ${url}` };\n }\n return { bucket };\n }\n\n if (!url.host) {\n return { err: `Invalid S3 url: no hostname: ${url}` };\n }\n\n const matches = url.host.match(ENDPOINT_PATTERN);\n if (!matches) {\n return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };\n }\n\n const prefix = matches[1];\n // https://s3.amazonaws.com/<bucket-name>\n if (!prefix) {\n if (url.pathname === '/') {\n return { bucket: null };\n }\n\n const index = url.pathname.indexOf('/', 1);\n\n // https://s3.amazonaws.com/<bucket-name>\n if (index === -1) {\n return { bucket: url.pathname.substring(1) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/\n if (index === url.pathname.length - 1) {\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/key\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://<bucket-name>.s3.amazonaws.com/\n return { bucket: prefix.substring(0, prefix.length - 1) };\n}\n\nexport const extractCredentials = (options: InitOptions): AwsCredentialIdentity | null => {\n if (options.s3Options?.credentials) {\n return {\n accessKeyId: options.s3Options.credentials.accessKeyId,\n secretAccessKey: options.s3Options.credentials.secretAccessKey,\n };\n }\n return null;\n};\n"],"names":["ENDPOINT_PATTERN","isUrlFromBucket","fileUrl","bucketName","baseUrl","url","URL","bucket","getBucketFromAwsUrl","host","startsWith","pathname","includes","protocol","err","matches","match","prefix","index","indexOf","substring","length","extractCredentials","options","s3Options","credentials","accessKeyId","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A,OAAO,IAAA;AACT;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@strapi/provider-upload-aws-s3",
3
- "version": "0.0.0-next.f0a0bc26f5ef0693aaea2a616bc6b816cfee54b6",
3
+ "version": "0.0.0-next.f0f36e3df4b18f167036dcbca529dcb933bf4e1d",
4
4
  "description": "AWS S3 provider for strapi upload",
5
5
  "keywords": [
6
6
  "upload",
@@ -37,12 +37,14 @@
37
37
  "dist/"
38
38
  ],
39
39
  "scripts": {
40
- "build": "pack-up build",
40
+ "build": "run -T npm-run-all clean --parallel build:code build:types",
41
+ "build:code": "run -T rollup -c",
42
+ "build:types": "run -T tsc -p tsconfig.build.json --emitDeclarationOnly",
41
43
  "clean": "run -T rimraf ./dist",
42
44
  "lint": "run -T eslint .",
43
45
  "test:unit": "run -T jest",
44
46
  "test:unit:watch": "run -T jest --watch",
45
- "watch": "pack-up watch"
47
+ "watch": "run -T rollup -c -w"
46
48
  },
47
49
  "dependencies": {
48
50
  "@aws-sdk/client-s3": "3.600.0",
@@ -52,14 +54,12 @@
52
54
  "lodash": "4.17.21"
53
55
  },
54
56
  "devDependencies": {
55
- "@strapi/pack-up": "5.0.0",
56
57
  "@types/jest": "29.5.2",
57
- "eslint-config-custom": "0.0.0-next.f0a0bc26f5ef0693aaea2a616bc6b816cfee54b6",
58
- "tsconfig": "0.0.0-next.f0a0bc26f5ef0693aaea2a616bc6b816cfee54b6"
58
+ "eslint-config-custom": "0.0.0-next.f0f36e3df4b18f167036dcbca529dcb933bf4e1d",
59
+ "tsconfig": "0.0.0-next.f0f36e3df4b18f167036dcbca529dcb933bf4e1d"
59
60
  },
60
61
  "engines": {
61
- "node": ">=18.0.0 <=22.x.x",
62
+ "node": ">=20.0.0 <=24.x.x",
62
63
  "npm": ">=6.0.0"
63
- },
64
- "gitHead": "f0a0bc26f5ef0693aaea2a616bc6b816cfee54b6"
64
+ }
65
65
  }