@stacksjs/storage 0.70.87 → 0.70.90

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.
@@ -0,0 +1,471 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { basename } from "node:path";
3
+ import { normalizeExpiryToMilliseconds } from "../types";
4
+ import { sanitizePresignedDir, sanitizePresignedFilename } from "../path-sanitize";
5
+ import { signS3PresignedPost } from "../s3-presigned-post";
6
+ import process from "node:process";
7
+ const S3_MIN_PART_SIZE = 5242880, S3_MAX_PART_SIZE = 5368709120;
8
+ function clampPartSize(requested) {
9
+ if (!Number.isFinite(requested))
10
+ return S3_MIN_PART_SIZE;
11
+ return Math.max(S3_MIN_PART_SIZE, Math.min(Math.floor(requested), S3_MAX_PART_SIZE));
12
+ }
13
+
14
+ class ChunkBuffer {
15
+ chunks = [];
16
+ total = 0;
17
+ constructor(_partSize) {}
18
+ get length() {
19
+ return this.total;
20
+ }
21
+ push(c) {
22
+ this.chunks.push(c);
23
+ this.total += c.length;
24
+ }
25
+ take(n) {
26
+ const out = new Uint8Array(n);
27
+ let written = 0;
28
+ while (written < n && this.chunks.length > 0) {
29
+ const head = this.chunks[0], need = n - written;
30
+ if (head.length <= need) {
31
+ out.set(head, written);
32
+ written += head.length;
33
+ this.chunks.shift();
34
+ } else {
35
+ out.set(head.subarray(0, need), written);
36
+ this.chunks[0] = head.subarray(need);
37
+ written += need;
38
+ }
39
+ }
40
+ this.total -= n;
41
+ return out;
42
+ }
43
+ flush() {
44
+ const out = new Uint8Array(this.total);
45
+ let off = 0;
46
+ for (const c of this.chunks) {
47
+ out.set(c, off);
48
+ off += c.length;
49
+ }
50
+ this.chunks = [];
51
+ this.total = 0;
52
+ return out;
53
+ }
54
+ }
55
+ async function isSettled(p) {
56
+ const sentinel = Symbol("pending");
57
+ return await Promise.race([
58
+ p.then(() => "settled", () => "settled"),
59
+ Promise.resolve(sentinel)
60
+ ]) !== sentinel;
61
+ }
62
+
63
+ export class S3StorageAdapter {
64
+ _client;
65
+ _clientPromise = null;
66
+ bucket;
67
+ prefix;
68
+ region;
69
+ credentials;
70
+ constructor(client, config) {
71
+ this._client = client;
72
+ this.bucket = config.bucket || "";
73
+ this.prefix = config.prefix || "";
74
+ this.region = config.region || "us-east-1";
75
+ this.credentials = config.credentials;
76
+ if (!this.bucket)
77
+ throw Error("S3 bucket name is required");
78
+ }
79
+ async getClient() {
80
+ if (this._client)
81
+ return this._client;
82
+ if (!this._clientPromise)
83
+ this._clientPromise = import("@stacksjs/ts-cloud").then((cloud) => {
84
+ this._client = new cloud.S3Client(this.region);
85
+ return this._client;
86
+ });
87
+ return this._clientPromise;
88
+ }
89
+ resolveCredentials() {
90
+ if (this.credentials?.accessKeyId && this.credentials.secretAccessKey)
91
+ return this.credentials;
92
+ const accessKeyId = process.env.AWS_ACCESS_KEY_ID, secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY, sessionToken = process.env.AWS_SESSION_TOKEN;
93
+ if (!accessKeyId || !secretAccessKey)
94
+ throw Error("[storage/s3] presignedUploadPolicy requires AWS credentials \u2014 " + "pass them via S3DiskConfig.credentials or set AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY.");
95
+ return { accessKeyId, secretAccessKey, sessionToken };
96
+ }
97
+ prefixPath(path) {
98
+ if (!this.prefix)
99
+ return path;
100
+ return `${this.prefix}/${path}`.replace(/\/+/g, "/");
101
+ }
102
+ stripPrefix(path) {
103
+ if (!this.prefix)
104
+ return path;
105
+ const prefixWithSlash = `${this.prefix}/`;
106
+ return path.startsWith(prefixWithSlash) ? path.slice(prefixWithSlash.length) : path;
107
+ }
108
+ async contentsToBuffer(contents) {
109
+ if (typeof contents === "string")
110
+ return Buffer.from(contents, "utf8");
111
+ else if (contents instanceof Buffer)
112
+ return contents;
113
+ else if (contents instanceof Uint8Array)
114
+ return Buffer.from(contents);
115
+ else {
116
+ if (typeof contents.getReader !== "function")
117
+ throw TypeError("[storage/s3] contents must be a web-standard ReadableStream (with .getReader()), not a Node stream.Readable. Convert via Readable.toWeb(nodeStream) before passing.");
118
+ const reader = contents.getReader(), chunks = [];
119
+ while (!0) {
120
+ const { done, value } = await reader.read();
121
+ if (done)
122
+ break;
123
+ if (value)
124
+ chunks.push(value);
125
+ }
126
+ return Buffer.concat(chunks.map((c) => Buffer.from(c)));
127
+ }
128
+ }
129
+ async write(path, contents) {
130
+ const key = this.prefixPath(path), body = await this.contentsToBuffer(contents), contentType = this.detectMimeType(path);
131
+ await (await this.getClient()).putObject({
132
+ bucket: this.bucket,
133
+ key,
134
+ body,
135
+ contentType
136
+ });
137
+ return {
138
+ path,
139
+ size: body.length,
140
+ contentType,
141
+ lastModified: Date.now()
142
+ };
143
+ }
144
+ async read(path) {
145
+ const key = this.prefixPath(path), response = await (await this.getClient()).getObject(this.bucket, key);
146
+ if (!response)
147
+ throw Error(`Failed to read file: ${path}`);
148
+ return Buffer.from(response);
149
+ }
150
+ async getStream(path, _options) {
151
+ const key = this.prefixPath(path), buf = await (await this.getClient()).getObjectBuffer(this.bucket, key);
152
+ if (!buf)
153
+ throw Error(`Failed to read file: ${path}`);
154
+ const bytes = new Uint8Array(buf);
155
+ return new ReadableStream({
156
+ start(controller) {
157
+ controller.enqueue(bytes);
158
+ controller.close();
159
+ }
160
+ });
161
+ }
162
+ async putStream(path, stream, options) {
163
+ const key = this.prefixPath(path), contentType = options?.contentType ?? this.detectMimeType(path), partSize = clampPartSize(options?.partSize ?? 5242880), concurrency = Math.max(1, Math.min(options?.concurrency ?? 4, 100)), maxRetries = Math.max(0, options?.maxRetries ?? 3), signal = options?.signal, reader = stream.getReader();
164
+ let firstChunk = null, firstDone = !1;
165
+ {
166
+ const buf = new ChunkBuffer(partSize);
167
+ while (!firstDone && buf.length < partSize) {
168
+ if (signal?.aborted) {
169
+ try {
170
+ reader.releaseLock();
171
+ } catch {}
172
+ throw Error("aborted");
173
+ }
174
+ const { value, done } = await reader.read();
175
+ if (done) {
176
+ firstDone = !0;
177
+ break;
178
+ }
179
+ if (value)
180
+ buf.push(value);
181
+ }
182
+ firstChunk = buf.flush();
183
+ }
184
+ if (firstDone) {
185
+ try {
186
+ reader.releaseLock();
187
+ } catch {}
188
+ await (await this.getClient()).putObject({
189
+ bucket: this.bucket,
190
+ key,
191
+ body: Buffer.from(firstChunk),
192
+ contentType
193
+ });
194
+ return { path, size: firstChunk.length, contentType, lastModified: Date.now() };
195
+ }
196
+ const { UploadId: uploadId } = await (await this.getClient()).createMultipartUpload(this.bucket, key, { contentType }), completedParts = [];
197
+ let totalBytes = 0, partNumber = 1;
198
+ const inflight = [], uploadOne = async (body, n) => {
199
+ let attempt = 0;
200
+ while (!0) {
201
+ if (signal?.aborted)
202
+ throw Error("aborted");
203
+ try {
204
+ const { ETag } = await (await this.getClient()).uploadPart(this.bucket, key, uploadId, n, Buffer.from(body));
205
+ completedParts.push({ PartNumber: n, ETag });
206
+ totalBytes += body.length;
207
+ return;
208
+ } catch (err) {
209
+ if (attempt >= maxRetries)
210
+ throw err;
211
+ attempt += 1;
212
+ }
213
+ }
214
+ };
215
+ try {
216
+ inflight.push(uploadOne(firstChunk, partNumber++));
217
+ firstChunk = null;
218
+ const buf = new ChunkBuffer(partSize);
219
+ while (!0) {
220
+ if (signal?.aborted)
221
+ throw Error("aborted");
222
+ const { value, done } = await reader.read();
223
+ if (done)
224
+ break;
225
+ if (value)
226
+ buf.push(value);
227
+ while (buf.length >= partSize) {
228
+ const part = buf.take(partSize);
229
+ if (inflight.length >= concurrency) {
230
+ await Promise.race(inflight.map((p, i) => p.then(() => i)));
231
+ for (let i = inflight.length - 1;i >= 0; i--)
232
+ if (await isSettled(inflight[i]))
233
+ inflight.splice(i, 1);
234
+ }
235
+ inflight.push(uploadOne(part, partNumber++));
236
+ }
237
+ }
238
+ try {
239
+ reader.releaseLock();
240
+ } catch {}
241
+ const tail = buf.flush();
242
+ if (tail.length > 0)
243
+ inflight.push(uploadOne(tail, partNumber++));
244
+ await Promise.all(inflight);
245
+ completedParts.sort((a, b) => a.PartNumber - b.PartNumber);
246
+ await (await this.getClient()).completeMultipartUpload(this.bucket, key, uploadId, completedParts);
247
+ return { path, size: totalBytes, contentType, lastModified: Date.now() };
248
+ } catch (err) {
249
+ try {
250
+ await (await this.getClient()).abortMultipartUpload(this.bucket, key, uploadId);
251
+ } catch {}
252
+ throw err;
253
+ }
254
+ }
255
+ async readToString(path) {
256
+ const key = this.prefixPath(path), response = await (await this.getClient()).getObject(this.bucket, key);
257
+ if (!response)
258
+ throw Error(`Failed to read file: ${path}`);
259
+ return response;
260
+ }
261
+ async readToBuffer(path) {
262
+ return await this.read(path);
263
+ }
264
+ async readToUint8Array(path) {
265
+ const buffer = await this.readToBuffer(path);
266
+ return new Uint8Array(buffer);
267
+ }
268
+ async deleteFile(path) {
269
+ const key = this.prefixPath(path);
270
+ await (await this.getClient()).deleteObject(this.bucket, key);
271
+ }
272
+ async deleteDirectory(path) {
273
+ const prefix = this.prefixPath(path), normalizedPrefix = prefix.endsWith("/") ? prefix : `${prefix}/`, keys = (await (await this.getClient()).listAllObjects({ bucket: this.bucket, prefix: normalizedPrefix })).map((obj) => obj.Key).filter((k) => typeof k === "string");
274
+ if (keys.length === 0)
275
+ return;
276
+ await (await this.getClient()).deleteObjects(this.bucket, keys);
277
+ }
278
+ async createDirectory(_path) {}
279
+ async moveFile(from, to) {
280
+ await this.copyFile(from, to);
281
+ await this.deleteFile(from);
282
+ }
283
+ async copyFile(from, to) {
284
+ const fromKey = this.prefixPath(from), toKey = this.prefixPath(to);
285
+ await (await this.getClient()).copyObject({
286
+ sourceBucket: this.bucket,
287
+ sourceKey: fromKey,
288
+ destinationBucket: this.bucket,
289
+ destinationKey: toKey
290
+ });
291
+ }
292
+ async stat(path) {
293
+ const key = this.prefixPath(path), result = await (await this.getClient()).headObject(this.bucket, key);
294
+ if (!result)
295
+ throw Error(`File not found: ${path}`);
296
+ return {
297
+ path,
298
+ type: "file",
299
+ visibility: "private",
300
+ size: result.ContentLength || 0,
301
+ lastModified: result.LastModified ? new Date(result.LastModified).getTime() : Date.now(),
302
+ mimeType: result.ContentType
303
+ };
304
+ }
305
+ list(path, options = {}) {
306
+ return this.createAsyncIterator(path, options.deep || !1);
307
+ }
308
+ async* createAsyncIterator(path, deep) {
309
+ const prefix = this.prefixPath(path), normalizedPrefix = prefix ? `${prefix}/` : void 0;
310
+ if (deep) {
311
+ const objects = await (await this.getClient()).listAllObjects({ bucket: this.bucket, prefix: normalizedPrefix });
312
+ for (const obj of objects)
313
+ yield {
314
+ path: this.stripPrefix(obj.Key),
315
+ type: "file"
316
+ };
317
+ } else {
318
+ let continuationToken;
319
+ do {
320
+ const result = await (await this.getClient()).listObjects({
321
+ bucket: this.bucket,
322
+ prefix: normalizedPrefix,
323
+ continuationToken
324
+ });
325
+ for (const obj of result.objects || [])
326
+ yield {
327
+ path: this.stripPrefix(obj.Key),
328
+ type: "file"
329
+ };
330
+ continuationToken = result.nextContinuationToken;
331
+ } while (continuationToken);
332
+ }
333
+ }
334
+ async changeVisibility(path, vis) {
335
+ const key = this.prefixPath(path), acl = vis === "public" ? "public-read" : "private";
336
+ await (await this.getClient()).putObjectAcl(this.bucket, key, acl);
337
+ }
338
+ async visibility(path) {
339
+ const key = this.prefixPath(path);
340
+ return ((await (await this.getClient()).getObjectAcl(this.bucket, key))?.Grants ?? []).some((g) => g.Grantee?.URI === "http://acs.amazonaws.com/groups/global/AllUsers" && (g.Permission === "READ" || g.Permission === "FULL_CONTROL")) ? "public" : "private";
341
+ }
342
+ async fileExists(path) {
343
+ const key = this.prefixPath(path);
344
+ try {
345
+ return !!await (await this.getClient()).headObject(this.bucket, key);
346
+ } catch (error) {
347
+ if (!error.message?.includes("404") && !error.message?.includes("NoSuchKey") && !error.message?.includes("NotFound"))
348
+ console.debug(`[s3] Unexpected error checking file existence for ${path}: ${error.message}`);
349
+ return !1;
350
+ }
351
+ }
352
+ async directoryExists(path) {
353
+ const prefix = this.prefixPath(path);
354
+ return ((await (await this.getClient()).listObjects({
355
+ bucket: this.bucket,
356
+ prefix: `${prefix}/`,
357
+ maxKeys: 1
358
+ })).objects || []).length > 0;
359
+ }
360
+ async publicUrl(path, options = {}) {
361
+ const key = this.prefixPath(path);
362
+ return `${options.domain || `https://${this.bucket}.s3.${this.region}.amazonaws.com`}/${key}`;
363
+ }
364
+ async temporaryUrl(path, options) {
365
+ const key = this.prefixPath(path), expiresIn = Math.floor(normalizeExpiryToMilliseconds(options.expiresIn) / 1000), MIN_EXPIRY = 60, MAX_EXPIRY = 604800;
366
+ if (!Number.isFinite(expiresIn) || expiresIn < MIN_EXPIRY || expiresIn > MAX_EXPIRY)
367
+ throw RangeError(`[storage/s3] temporaryUrl expiresIn must be between 60s and 7 days (got ${expiresIn}s)`);
368
+ return await (await this.getClient()).getSignedUrl({
369
+ bucket: this.bucket,
370
+ key,
371
+ expiresIn,
372
+ operation: "getObject"
373
+ });
374
+ }
375
+ async signedUrl(path, options) {
376
+ return this.temporaryUrl(path, { expiresIn: options.expiresIn });
377
+ }
378
+ async presignedUploadUrl(options) {
379
+ if (!options.contentType)
380
+ throw Error("[storage/s3] presignedUploadUrl requires `contentType` \u2014 S3 signs against the exact header.");
381
+ const expiresIn = Math.floor(options.expiresIn), MIN_EXPIRY = 60, MAX_EXPIRY = 604800;
382
+ if (!Number.isFinite(expiresIn) || expiresIn < MIN_EXPIRY || expiresIn > MAX_EXPIRY)
383
+ throw RangeError(`[storage/s3] presignedUploadUrl expiresIn must be between 60s and 7 days (got ${expiresIn}s)`);
384
+ const safeDir = sanitizePresignedDir(options.dir), safeFilename = options.filename !== void 0 ? sanitizePresignedFilename(options.filename) : `${crypto.randomUUID().replace(/-/g, "")}${this.extensionForContentType(options.contentType)}`, path = safeDir ? `${safeDir}/${safeFilename}` : safeFilename, key = this.prefixPath(path);
385
+ return {
386
+ url: await (await this.getClient()).getSignedUrl({
387
+ bucket: this.bucket,
388
+ key,
389
+ expiresIn,
390
+ operation: "putObject"
391
+ }),
392
+ path,
393
+ key,
394
+ contentType: options.contentType,
395
+ maxBytes: options.maxBytes
396
+ };
397
+ }
398
+ async presignedUploadPolicy(options) {
399
+ const credentials = this.resolveCredentials(), scopedKey = typeof options.key === "string" ? this.prefixPath(options.key) : { startsWith: this.prefixPath(options.key.startsWith) };
400
+ return signS3PresignedPost({
401
+ bucket: this.bucket,
402
+ region: this.region,
403
+ credentials,
404
+ key: scopedKey,
405
+ contentType: options.contentType,
406
+ contentLengthRange: options.contentLengthRange,
407
+ acl: options.acl,
408
+ expiresIn: options.expiresIn,
409
+ fields: options.fields
410
+ });
411
+ }
412
+ extensionForContentType(contentType) {
413
+ const mime = contentType.toLowerCase().split(";")[0]?.trim() ?? "";
414
+ return {
415
+ "image/jpeg": ".jpg",
416
+ "image/jpg": ".jpg",
417
+ "image/png": ".png",
418
+ "image/webp": ".webp",
419
+ "image/gif": ".gif",
420
+ "image/avif": ".avif",
421
+ "image/svg+xml": ".svg",
422
+ "application/pdf": ".pdf",
423
+ "application/json": ".json",
424
+ "application/zip": ".zip",
425
+ "text/plain": ".txt",
426
+ "text/csv": ".csv",
427
+ "video/mp4": ".mp4",
428
+ "video/webm": ".webm",
429
+ "audio/mpeg": ".mp3",
430
+ "audio/wav": ".wav"
431
+ }[mime] ?? "";
432
+ }
433
+ async checksum(path, options = {}) {
434
+ const algorithm = options.algorithm || "sha256", content = await this.readToUint8Array(path), hasher = new Bun.CryptoHasher(algorithm);
435
+ hasher.update(content);
436
+ return hasher.digest("hex");
437
+ }
438
+ async mimeType(path, _options = {}) {
439
+ return (await this.stat(path)).mimeType || this.detectMimeType(path);
440
+ }
441
+ detectMimeType(path) {
442
+ const ext = basename(path).split(".").pop()?.toLowerCase();
443
+ return {
444
+ txt: "text/plain",
445
+ html: "text/html",
446
+ css: "text/css",
447
+ js: "application/javascript",
448
+ json: "application/json",
449
+ xml: "application/xml",
450
+ pdf: "application/pdf",
451
+ zip: "application/zip",
452
+ jpg: "image/jpeg",
453
+ jpeg: "image/jpeg",
454
+ png: "image/png",
455
+ gif: "image/gif",
456
+ svg: "image/svg+xml",
457
+ mp4: "video/mp4",
458
+ mp3: "audio/mpeg",
459
+ wav: "audio/wav"
460
+ }[ext || ""] || "application/octet-stream";
461
+ }
462
+ async lastModified(path) {
463
+ return (await this.stat(path)).lastModified;
464
+ }
465
+ async fileSize(path) {
466
+ return (await this.stat(path)).size;
467
+ }
468
+ }
469
+ export function createS3Storage(client, config) {
470
+ return new S3StorageAdapter(client, config);
471
+ }
@@ -0,0 +1,142 @@
1
+ const DEFAULT_SCOPE_PATTERN = /^[a-z0-9_-]+$/i;
2
+
3
+ export class ScopedStorageAdapter {
4
+ inner;
5
+ scope;
6
+ scopeWithSlash;
7
+ constructor(inner, options) {
8
+ const pattern = options.scopePattern ?? DEFAULT_SCOPE_PATTERN, cleaned = String(options.scope).replace(/^\/+|\/+$/g, "");
9
+ if (!cleaned)
10
+ throw Error("[storage/scoped] scope is required");
11
+ if (!pattern.test(cleaned))
12
+ throw Error(`[storage/scoped] scope '${cleaned}' contains disallowed characters`);
13
+ if (cleaned.includes("..") || cleaned.includes("/"))
14
+ throw Error(`[storage/scoped] scope '${cleaned}' cannot contain path separators or traversal`);
15
+ this.inner = inner;
16
+ this.scope = cleaned;
17
+ this.scopeWithSlash = `${cleaned}/`;
18
+ }
19
+ scopePath(path) {
20
+ if (typeof path !== "string")
21
+ throw Error("[storage/scoped] path must be a string");
22
+ if (path.length === 0)
23
+ return this.scope;
24
+ if (path.includes("\x00"))
25
+ throw Error("[storage/scoped] path contains a null byte");
26
+ if (path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path))
27
+ throw Error(`[storage/scoped] path '${path}' is absolute \u2014 refusing to escape scope`);
28
+ if (path.split(/[/\\]/).some((s) => s === ".."))
29
+ throw Error(`[storage/scoped] path '${path}' contains a '..' segment \u2014 refusing to escape scope`);
30
+ return `${this.scope}/${path.replace(/^\/+/, "")}`;
31
+ }
32
+ unscopePath(path) {
33
+ if (path === this.scope)
34
+ return "";
35
+ if (path.startsWith(this.scopeWithSlash))
36
+ return path.slice(this.scopeWithSlash.length);
37
+ return path;
38
+ }
39
+ async write(path, contents) {
40
+ const result = await this.inner.write(this.scopePath(path), contents);
41
+ return { ...result, path: this.unscopePath(result.path) };
42
+ }
43
+ async read(path) {
44
+ return this.inner.read(this.scopePath(path));
45
+ }
46
+ async readToString(path) {
47
+ return this.inner.readToString(this.scopePath(path));
48
+ }
49
+ async readToBuffer(path) {
50
+ return this.inner.readToBuffer(this.scopePath(path));
51
+ }
52
+ async readToUint8Array(path) {
53
+ return this.inner.readToUint8Array(this.scopePath(path));
54
+ }
55
+ async deleteFile(path) {
56
+ return this.inner.deleteFile(this.scopePath(path));
57
+ }
58
+ async deleteDirectory(path) {
59
+ return this.inner.deleteDirectory(this.scopePath(path));
60
+ }
61
+ async createDirectory(path) {
62
+ return this.inner.createDirectory(this.scopePath(path));
63
+ }
64
+ async moveFile(from, to) {
65
+ return this.inner.moveFile(this.scopePath(from), this.scopePath(to));
66
+ }
67
+ async copyFile(from, to) {
68
+ return this.inner.copyFile(this.scopePath(from), this.scopePath(to));
69
+ }
70
+ async stat(path) {
71
+ const entry = await this.inner.stat(this.scopePath(path));
72
+ return { ...entry, path: this.unscopePath(entry.path) };
73
+ }
74
+ list(path, options) {
75
+ const inner = this.inner.list(this.scopePath(path), options), unscope = this.unscopePath.bind(this);
76
+ return async function* () {
77
+ for await (const entry of inner)
78
+ yield { ...entry, path: unscope(entry.path) };
79
+ }();
80
+ }
81
+ async changeVisibility(path, visibility) {
82
+ return this.inner.changeVisibility(this.scopePath(path), visibility);
83
+ }
84
+ async visibility(path) {
85
+ return this.inner.visibility(this.scopePath(path));
86
+ }
87
+ async fileExists(path) {
88
+ return this.inner.fileExists(this.scopePath(path));
89
+ }
90
+ async directoryExists(path) {
91
+ return this.inner.directoryExists(this.scopePath(path));
92
+ }
93
+ async publicUrl(path, options) {
94
+ return this.inner.publicUrl(this.scopePath(path), options);
95
+ }
96
+ async temporaryUrl(path, options) {
97
+ return this.inner.temporaryUrl(this.scopePath(path), options);
98
+ }
99
+ async signedUrl(path, options) {
100
+ if (typeof this.inner.signedUrl !== "function")
101
+ throw Error("[storage/scoped] wrapped adapter does not support signedUrl");
102
+ return this.inner.signedUrl(this.scopePath(path), options);
103
+ }
104
+ async presignedUploadUrl(options) {
105
+ if (typeof this.inner.presignedUploadUrl !== "function")
106
+ throw Error("[storage/scoped] wrapped adapter does not support presignedUploadUrl");
107
+ const scopedDir = options.dir ? `${this.scope}/${options.dir.replace(/^\/+/, "")}` : this.scope, result = await this.inner.presignedUploadUrl({ ...options, dir: scopedDir });
108
+ return { ...result, path: this.unscopePath(result.path), key: this.unscopePath(result.key) };
109
+ }
110
+ async presignedUploadPolicy(options) {
111
+ if (typeof this.inner.presignedUploadPolicy !== "function")
112
+ throw Error("[storage/scoped] wrapped adapter does not support presignedUploadPolicy");
113
+ const scopedKey = typeof options.key === "string" ? this.scopePath(options.key) : { startsWith: this.scopePath(options.key.startsWith) }, result = await this.inner.presignedUploadPolicy({ ...options, key: scopedKey });
114
+ return { ...result, key: this.unscopePath(result.key) };
115
+ }
116
+ async getStream(path, options) {
117
+ if (typeof this.inner.getStream !== "function")
118
+ throw Error("[storage/scoped] wrapped adapter does not support getStream");
119
+ return this.inner.getStream(this.scopePath(path), options);
120
+ }
121
+ async putStream(path, stream, options) {
122
+ if (typeof this.inner.putStream !== "function")
123
+ throw Error("[storage/scoped] wrapped adapter does not support putStream");
124
+ const result = await this.inner.putStream(this.scopePath(path), stream, options);
125
+ return { ...result, path: this.unscopePath(result.path) };
126
+ }
127
+ async checksum(path, options) {
128
+ return this.inner.checksum(this.scopePath(path), options);
129
+ }
130
+ async mimeType(path, options) {
131
+ return this.inner.mimeType(this.scopePath(path), options);
132
+ }
133
+ async lastModified(path) {
134
+ return this.inner.lastModified(this.scopePath(path));
135
+ }
136
+ async fileSize(path) {
137
+ return this.inner.fileSize(this.scopePath(path));
138
+ }
139
+ }
140
+ export function scoped(inner, options) {
141
+ return new ScopedStorageAdapter(inner, options);
142
+ }
package/dist/copy.js ADDED
@@ -0,0 +1,30 @@
1
+ import { contains } from "@stacksjs/arrays";
2
+ import { join } from "@stacksjs/path";
3
+ import { fs } from "./fs";
4
+ export function copy(src, dest, exclude = []) {
5
+ if (Array.isArray(src))
6
+ src.forEach((file) => {
7
+ copy(file, dest, exclude);
8
+ });
9
+ else if (fs.statSync(src).isDirectory())
10
+ copyFolder(src, dest, exclude);
11
+ else
12
+ copyFile(src, dest);
13
+ }
14
+ export function copyFile(src, dest) {
15
+ fs.copyFileSync(src, dest);
16
+ }
17
+ export function copyFolder(src, dest, exclude = []) {
18
+ if (!fs.existsSync(dest))
19
+ fs.mkdirSync(dest, { recursive: !0 });
20
+ if (fs.existsSync(src))
21
+ fs.readdirSync(src).forEach((file) => {
22
+ if (!contains(join(src, file), exclude)) {
23
+ const srcPath = join(src, file), destPath = join(dest, file);
24
+ if (fs.statSync(srcPath).isDirectory())
25
+ copyFolder(srcPath, destPath, exclude);
26
+ else
27
+ fs.copyFileSync(srcPath, destPath);
28
+ }
29
+ });
30
+ }