@od-oneapp/storage 2026.2.1501-canary.1

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,848 @@
1
+ import { t as VercelBlobProvider } from "./vercel-blob-HSvMatlk.mjs";
2
+ import { createRequire } from "node:module";
3
+
4
+ //#region ../shared/src/logs.tsx
5
+ /**
6
+ * @fileoverview Canonical logger for the OneApp platform.
7
+ *
8
+ * This module provides isomorphic logging functions that work in any environment
9
+ * (Browser, Node.js, Edge). Logs directly to console with runtime information.
10
+ *
11
+ * Preferred usage is to import from '@od-oneapp/shared/logs'.
12
+ */
13
+ /**
14
+ * Get runtime environment information.
15
+ *
16
+ * Detects the current runtime environment (browser, Node.js, edge, Bun) and returns
17
+ * detailed information about the environment type, version, and capabilities.
18
+ *
19
+ * @returns Runtime information object with type, version, and environment-specific details
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const runtime = getRuntimeInfo();
24
+ * // Returns: { type: 'node', version: '22.0.0', major: 22, minor: 0, isNode22Plus: true, isNextJs: true }
25
+ * // or: { type: 'browser', isNextJs: true }
26
+ * // or: { type: 'edge', variant: 'vercel' }
27
+ * ```
28
+ */
29
+ const getRuntimeInfo = () => {
30
+ if (typeof globalThis !== "undefined" && globalThis.EdgeRuntime) return {
31
+ type: "edge",
32
+ variant: "vercel"
33
+ };
34
+ if (typeof globalThis !== "undefined" && globalThis.caches && typeof globalThis.caches !== "undefined") return {
35
+ type: "edge",
36
+ variant: "cloudflare"
37
+ };
38
+ if (typeof process !== "undefined" && process.versions?.bun) return {
39
+ type: "bun",
40
+ version: process.versions.bun
41
+ };
42
+ if (typeof globalThis !== "undefined" && "window" in globalThis && typeof globalThis.window !== "undefined" && typeof globalThis.window?.document !== "undefined" && typeof globalThis.window?.navigator !== "undefined") return {
43
+ type: "browser",
44
+ isNextJs: Boolean(globalThis.window?.__NEXT_DATA__)
45
+ };
46
+ if (typeof process !== "undefined" && process.versions?.node) {
47
+ const nodeVersion = parseInt(process.versions.node.split(".")[0] ?? "0");
48
+ const nodeVersionMinor = parseInt(process.versions.node.split(".")[1] ?? "0");
49
+ if (nodeVersion < 22) console.warn(`[Observability] Node ${process.versions.node} detected. Node 22+ is required for optimal performance and latest features.`);
50
+ return {
51
+ type: "node",
52
+ version: process.versions.node,
53
+ major: nodeVersion,
54
+ minor: nodeVersionMinor,
55
+ isNode22Plus: nodeVersion >= 22,
56
+ isNextJs: Boolean(process.env.NEXT_RUNTIME) || Boolean(process.env.__NEXT_RUNTIME) || Boolean(process.env.NEXT_PUBLIC_VERCEL_ENV)
57
+ };
58
+ }
59
+ return { type: "unknown" };
60
+ };
61
+ const runtimeInfo = getRuntimeInfo();
62
+ /**
63
+ * Create a generic log function factory.
64
+ *
65
+ * Factory function that creates log functions for different levels (debug, info, warn, error).
66
+ * Logs directly to console with runtime information.
67
+ */
68
+ const createLogFunction = (level) => {
69
+ return (message, context) => {
70
+ let actualContext;
71
+ let errorObj;
72
+ if (context instanceof Error) errorObj = context;
73
+ else actualContext = context;
74
+ if (message instanceof Error) {
75
+ const combinedContext = {
76
+ ...actualContext,
77
+ ...errorObj ? { secondaryError: errorObj.message } : {}
78
+ };
79
+ const consoleMethod = console[level];
80
+ if (Object.keys(combinedContext).length > 0) consoleMethod(`[${runtimeInfo.type}]`, message, combinedContext);
81
+ else consoleMethod(`[${runtimeInfo.type}]`, message);
82
+ } else {
83
+ const finalError = errorObj;
84
+ const contextStr = actualContext ? JSON.stringify(actualContext) : "";
85
+ const logMessage = contextStr ? `${message} ${contextStr}` : message;
86
+ const consoleMethod = console[level];
87
+ if (finalError) consoleMethod(`[${runtimeInfo.type}]`, logMessage, finalError);
88
+ else consoleMethod(`[${runtimeInfo.type}]`, logMessage);
89
+ }
90
+ };
91
+ };
92
+ /**
93
+ * Log a debug message (isomorphic - works in any environment).
94
+ */
95
+ const logDebug = createLogFunction("debug");
96
+ /**
97
+ * Log an info message (isomorphic - works in any environment).
98
+ */
99
+ const logInfo = createLogFunction("info");
100
+ /**
101
+ * Log a warning message (isomorphic - works in any environment).
102
+ */
103
+ const logWarn = createLogFunction("warn");
104
+ /**
105
+ * Log an error message (isomorphic - works in any environment).
106
+ */
107
+ const logError = createLogFunction("error");
108
+
109
+ //#endregion
110
+ //#region providers/cloudflare-images.ts
111
+ /**
112
+ * @fileoverview Cloudflare Images storage provider
113
+ *
114
+ * Lazy shim around the monorepo integration package.
115
+ *
116
+ * Why:
117
+ * - `@integrations/*` packages are monorepo-private and may not be installed in extracted apps.
118
+ * - This avoids hard module resolution failures during bundling/build; the integration is only
119
+ * required if the provider is instantiated.
120
+ */
121
+ const require$1 = createRequire(import.meta.url);
122
+ function loadProvider$1() {
123
+ return require$1("@integrations/cloudflare/storage-provider/images").CloudflareImagesProvider;
124
+ }
125
+ const CloudflareImagesProvider = class CloudflareImagesProviderShim {
126
+ constructor(...args) {
127
+ return new (loadProvider$1())(...args);
128
+ }
129
+ };
130
+
131
+ //#endregion
132
+ //#region providers/cloudflare-r2.ts
133
+ /**
134
+ * @fileoverview Cloudflare R2 storage provider
135
+ *
136
+ * Lazy shim around the monorepo integration package.
137
+ *
138
+ * Why:
139
+ * - `@integrations/*` packages are monorepo-private and may not be installed in extracted apps.
140
+ * - This avoids hard module resolution failures during bundling/build; the integration is only
141
+ * required if the provider is instantiated.
142
+ */
143
+ const require = createRequire(import.meta.url);
144
+ function loadProvider() {
145
+ return require("@integrations/cloudflare/storage-provider/r2").CloudflareR2Provider;
146
+ }
147
+ const CloudflareR2Provider = class CloudflareR2ProviderShim {
148
+ constructor(...args) {
149
+ return new (loadProvider())(...args);
150
+ }
151
+ };
152
+
153
+ //#endregion
154
+ //#region src/constants.ts
155
+ /**
156
+ * @fileoverview Storage Package Constants
157
+ *
158
+ * Centralized constants for storage operations to avoid magic numbers
159
+ * and improve maintainability.
160
+ *
161
+ * Includes:
162
+ * - URL expiration times
163
+ * - File size limits
164
+ * - Multipart upload thresholds
165
+ * - Retry configuration
166
+ * - Rate limiting settings
167
+ *
168
+ * @module @od-oneapp/storage/constants
169
+ */
170
+ const STORAGE_CONSTANTS = {
171
+ DEFAULT_URL_EXPIRY_SECONDS: 3600,
172
+ PRODUCT_URL_EXPIRY_SECONDS: 3600,
173
+ UPLOAD_URL_EXPIRY_SECONDS: 1800,
174
+ ADMIN_URL_EXPIRY_SECONDS: 7200,
175
+ MULTIPART_THRESHOLD_BYTES: 100 * 1024 * 1024,
176
+ DEFAULT_PART_SIZE_BYTES: 5 * 1024 * 1024,
177
+ DEFAULT_MAX_PART_SIZE_BYTES: 25 * 1024 * 1024,
178
+ DEFAULT_QUEUE_SIZE: 4,
179
+ DEFAULT_BATCH_SIZE: 5,
180
+ MAX_BATCH_SIZE: 50,
181
+ DEFAULT_REQUEST_TIMEOUT_MS: 3e4,
182
+ DEFAULT_UPLOAD_TIMEOUT_MS: 3e5,
183
+ DEFAULT_DOWNLOAD_TIMEOUT_MS: 6e4,
184
+ DEFAULT_MAX_RETRIES: 3,
185
+ RETRY_BASE_DELAY_MS: 1e3,
186
+ MAX_KEY_LENGTH: 1024,
187
+ MAX_FILENAME_LENGTH: 255,
188
+ DEFAULT_RATE_LIMIT_REQUESTS: 100,
189
+ DEFAULT_RATE_LIMIT_WINDOW_MS: 60 * 1e3,
190
+ HEALTH_CHECK_KEY: "__health_check__"
191
+ };
192
+ /**
193
+ * File size thresholds for multipart upload decisions
194
+ */
195
+ const MULTIPART_THRESHOLDS = {
196
+ SMALL_FILE: 100 * 1024 * 1024,
197
+ MEDIUM_FILE: 1024 * 1024 * 1024,
198
+ LARGE_FILE: Infinity
199
+ };
200
+ /**
201
+ * Part sizes based on file size
202
+ */
203
+ const PART_SIZES = {
204
+ SMALL: 5 * 1024 * 1024,
205
+ MEDIUM: 10 * 1024 * 1024,
206
+ LARGE: 25 * 1024 * 1024
207
+ };
208
+ /**
209
+ * Default storage capabilities for providers that don't implement getCapabilities()
210
+ * Single source of truth for capability defaults
211
+ */
212
+ const DEFAULT_STORAGE_CAPABILITIES = {
213
+ multipart: false,
214
+ presignedUrls: false,
215
+ progressTracking: false,
216
+ abortSignal: false,
217
+ metadata: false,
218
+ customDomains: false,
219
+ edgeCompatible: false
220
+ };
221
+
222
+ //#endregion
223
+ //#region src/multi-storage.ts
224
+ /**
225
+ * @fileoverview Multi-storage provider manager
226
+ *
227
+ * Manages multiple storage providers with routing and fallback capabilities.
228
+ * Allows using different providers for different use cases or as backups.
229
+ *
230
+ * Features:
231
+ * - Provider routing based on key patterns
232
+ * - Fallback to default provider
233
+ * - Unified API across multiple providers
234
+ *
235
+ * @module @od-oneapp/storage/multi-storage
236
+ */
237
+ var MultiStorageManager = class {
238
+ providers = /* @__PURE__ */ new Map();
239
+ defaultProvider;
240
+ routing;
241
+ constructor(config) {
242
+ for (const [name, providerConfig] of Object.entries(config.providers)) this.providers.set(name, this.createProvider(providerConfig));
243
+ const firstProvider = Object.keys(config.providers)[0];
244
+ this.defaultProvider = config.defaultProvider ?? firstProvider ?? "";
245
+ if (!this.defaultProvider) throw new Error("No storage providers configured");
246
+ this.routing = config.routing;
247
+ }
248
+ createProvider(config) {
249
+ switch (config.provider) {
250
+ case "multi": throw new Error("Multi provider cannot be nested");
251
+ case "cloudflare-r2":
252
+ if (!config.cloudflareR2) throw new Error("Cloudflare R2 configuration is required");
253
+ if (Array.isArray(config.cloudflareR2)) {
254
+ if (config.cloudflareR2.length === 0) throw new Error("No R2 configurations provided");
255
+ const firstR2Config = config.cloudflareR2[0];
256
+ if (!firstR2Config) throw new Error("First R2 configuration is undefined");
257
+ return new CloudflareR2Provider(firstR2Config);
258
+ }
259
+ return new CloudflareR2Provider(config.cloudflareR2);
260
+ case "cloudflare-images":
261
+ if (!config.cloudflareImages) throw new Error("Cloudflare Images configuration is required");
262
+ return new CloudflareImagesProvider(config.cloudflareImages);
263
+ case "vercel-blob":
264
+ if (!config.vercelBlob?.token) throw new Error("Vercel Blob token is required");
265
+ return new VercelBlobProvider(config.vercelBlob.token);
266
+ default: throw new Error(`Unknown storage provider: ${config.provider}`);
267
+ }
268
+ }
269
+ getProviderForKey(key) {
270
+ if (this.routing) {
271
+ const extension = key.split(".").pop()?.toLowerCase();
272
+ if (this.routing.images && this.isImageFile(extension)) {
273
+ const provider = this.providers.get(this.routing.images);
274
+ if (provider) return {
275
+ provider,
276
+ providerName: this.routing.images
277
+ };
278
+ }
279
+ if (this.routing.documents && this.isDocumentFile(extension)) {
280
+ const provider = this.providers.get(this.routing.documents);
281
+ if (provider) return {
282
+ provider,
283
+ providerName: this.routing.documents
284
+ };
285
+ }
286
+ for (const [pattern, providerName] of Object.entries(this.routing)) if (pattern !== "images" && pattern !== "documents" && providerName) {
287
+ if (key.includes(pattern)) {
288
+ const provider = this.providers.get(providerName);
289
+ if (provider) return {
290
+ provider,
291
+ providerName
292
+ };
293
+ }
294
+ }
295
+ }
296
+ const provider = this.providers.get(this.defaultProvider);
297
+ if (!provider) throw new Error(`Default provider '${this.defaultProvider}' not found`);
298
+ return {
299
+ provider,
300
+ providerName: this.defaultProvider
301
+ };
302
+ }
303
+ isImageFile(extension) {
304
+ return extension ? [
305
+ "jpg",
306
+ "jpeg",
307
+ "png",
308
+ "gif",
309
+ "webp",
310
+ "avif",
311
+ "svg",
312
+ "ico"
313
+ ].includes(extension) : false;
314
+ }
315
+ isDocumentFile(extension) {
316
+ return extension ? [
317
+ "pdf",
318
+ "doc",
319
+ "docx",
320
+ "xls",
321
+ "xlsx",
322
+ "ppt",
323
+ "pptx",
324
+ "txt",
325
+ "csv"
326
+ ].includes(extension) : false;
327
+ }
328
+ getProvider(name) {
329
+ return this.providers.get(name);
330
+ }
331
+ async delete(key) {
332
+ const { provider } = this.getProviderForKey(key);
333
+ return provider.delete(key);
334
+ }
335
+ async download(key) {
336
+ const { provider } = this.getProviderForKey(key);
337
+ return provider.download(key);
338
+ }
339
+ async exists(key) {
340
+ const { provider } = this.getProviderForKey(key);
341
+ return provider.exists(key);
342
+ }
343
+ async getMetadata(key) {
344
+ const { provider } = this.getProviderForKey(key);
345
+ return provider.getMetadata(key);
346
+ }
347
+ async getUrl(key, options) {
348
+ const { provider } = this.getProviderForKey(key);
349
+ return provider.getUrl(key, options);
350
+ }
351
+ async list(options) {
352
+ if (options?.provider) {
353
+ const provider = this.providers.get(options.provider);
354
+ if (!provider) throw new Error(`Provider '${options.provider}' not found`);
355
+ return provider.list(options);
356
+ }
357
+ const allResults = [];
358
+ for (const provider of this.providers.values()) {
359
+ const results = await provider.list(options);
360
+ allResults.push(...results);
361
+ }
362
+ return allResults;
363
+ }
364
+ async upload(key, data, options) {
365
+ let provider;
366
+ if (options?.provider) {
367
+ const requestedProvider = this.providers.get(options.provider);
368
+ if (!requestedProvider) throw new Error(`Provider '${options.provider}' not found`);
369
+ provider = requestedProvider;
370
+ } else {
371
+ const { provider: routedProvider } = this.getProviderForKey(key);
372
+ provider = routedProvider;
373
+ }
374
+ return provider.upload(key, data, options);
375
+ }
376
+ async getCloudflareImagesProvider() {
377
+ for (const provider of this.providers.values()) if (provider instanceof CloudflareImagesProvider) return provider;
378
+ }
379
+ getProviderNames() {
380
+ return Array.from(this.providers.keys());
381
+ }
382
+ };
383
+
384
+ //#endregion
385
+ //#region src/multipart.ts
386
+ /**
387
+ * @fileoverview Unified Multipart Upload Manager
388
+ *
389
+ * Provides a consistent interface for multipart uploads across all storage providers.
390
+ * Handles provider-specific differences and provides retry logic, progress tracking,
391
+ * and error recovery.
392
+ *
393
+ * Features:
394
+ * - Automatic part size calculation
395
+ * - Concurrent part uploads
396
+ * - Progress tracking
397
+ * - Resume support
398
+ * - Error recovery
399
+ *
400
+ * @module @od-oneapp/storage/multipart
401
+ */
402
+ var MultipartUploadManager = class {
403
+ provider;
404
+ state = null;
405
+ abortController = null;
406
+ constructor(provider) {
407
+ this.provider = provider;
408
+ }
409
+ /**
410
+ * Check if provider supports multipart uploads
411
+ */
412
+ supportsMultipart() {
413
+ return (this.provider.getCapabilities?.())?.multipart ?? false;
414
+ }
415
+ /**
416
+ * Create a new multipart upload
417
+ *
418
+ * @param key - Storage key
419
+ * @param totalSize - Total file size in bytes
420
+ * @param options - Upload options
421
+ * @returns Upload state
422
+ */
423
+ async createUpload(key, totalSize, options = {}) {
424
+ if (!this.supportsMultipart()) throw new Error("Provider does not support multipart uploads");
425
+ if (this.state && !this.state.completed && !this.state.aborted) throw new Error("Upload already in progress. Abort current upload first.");
426
+ const partSize = this.calculatePartSize(totalSize, options.partSize);
427
+ const totalParts = Math.ceil(totalSize / partSize);
428
+ const uploadOptions = { onProgress: options.onProgress ? (progress) => {
429
+ options.onProgress?.({
430
+ key: progress.key,
431
+ loaded: progress.loaded,
432
+ total: progress.total,
433
+ part: progress.part ?? 0,
434
+ percentage: progress.percentage ?? 0
435
+ });
436
+ } : void 0 };
437
+ const result = await this.provider.createMultipartUpload?.(key, uploadOptions);
438
+ if (!result) throw new Error("Failed to create multipart upload");
439
+ this.state = {
440
+ uploadId: result.uploadId,
441
+ key: result.key,
442
+ provider: this.getProviderName(),
443
+ parts: Array.from({ length: totalParts }, (_, i) => ({
444
+ partNumber: i + 1,
445
+ size: i === totalParts - 1 ? totalSize - i * partSize : partSize,
446
+ uploaded: false
447
+ })),
448
+ totalSize,
449
+ uploadedSize: 0,
450
+ completed: false,
451
+ aborted: false
452
+ };
453
+ this.abortController = new AbortController();
454
+ return this.state;
455
+ }
456
+ /**
457
+ * Upload a part
458
+ *
459
+ * @param partNumber - Part number (1-based)
460
+ * @param data - Part data
461
+ * @param options - Upload options
462
+ * @returns Upload result
463
+ */
464
+ async uploadPart(partNumber, data, options = {}) {
465
+ if (!this.state) throw new Error("No active upload. Call createUpload first.");
466
+ if (this.state.completed || this.state.aborted) throw new Error("Upload is completed or aborted");
467
+ const part = this.state.parts.find((p) => p.partNumber === partNumber);
468
+ if (!part) throw new Error(`Part ${partNumber} not found`);
469
+ if (part.uploaded) throw new Error(`Part ${partNumber} already uploaded`);
470
+ if (this.abortController?.signal.aborted) throw new Error("Upload aborted");
471
+ try {
472
+ const result = await this.uploadPartWithRetry(partNumber, data, options);
473
+ part.etag = result.etag;
474
+ part.uploaded = true;
475
+ this.state.uploadedSize += part.size;
476
+ if (options.onProgress) options.onProgress({
477
+ key: this.state.key,
478
+ loaded: this.state.uploadedSize,
479
+ total: this.state.totalSize,
480
+ part: partNumber,
481
+ percentage: this.state.uploadedSize / this.state.totalSize * 100
482
+ });
483
+ return result;
484
+ } catch (error) {
485
+ this.state.error = error instanceof Error ? error.message : String(error);
486
+ throw error;
487
+ }
488
+ }
489
+ /**
490
+ * Complete the multipart upload
491
+ *
492
+ * @returns Final upload result
493
+ */
494
+ async completeUpload() {
495
+ if (!this.state) throw new Error("No active upload. Call createUpload first.");
496
+ if (this.state.completed) throw new Error("Upload already completed");
497
+ if (this.state.aborted) throw new Error("Upload was aborted");
498
+ const unuploadedParts = this.state.parts.filter((p) => !p.uploaded);
499
+ if (unuploadedParts.length > 0) throw new Error(`Upload incomplete: ${unuploadedParts.length} parts not uploaded`);
500
+ try {
501
+ const parts = this.state.parts.filter((p) => p.etag).map((p) => ({
502
+ partNumber: p.partNumber,
503
+ etag: p.etag ?? ""
504
+ })).filter((p) => p.etag !== "");
505
+ const result = await this.provider.completeMultipartUpload?.(this.state.uploadId, parts);
506
+ if (!result) throw new Error("Failed to complete multipart upload");
507
+ this.state.completed = true;
508
+ return {
509
+ ...result,
510
+ key: result.key ?? this.state.key,
511
+ uploadId: this.state.uploadId,
512
+ parts: this.state.parts.filter((p) => p.etag).map((p) => ({
513
+ partNumber: p.partNumber,
514
+ etag: p.etag ?? "",
515
+ size: p.size
516
+ })),
517
+ totalParts: this.state.parts.length
518
+ };
519
+ } catch (error) {
520
+ this.state.error = error instanceof Error ? error.message : String(error);
521
+ throw error;
522
+ }
523
+ }
524
+ /**
525
+ * Abort the multipart upload
526
+ */
527
+ async abortUpload() {
528
+ if (!this.state) return;
529
+ if (this.state.completed) return;
530
+ this.abortController?.abort();
531
+ this.state.aborted = true;
532
+ try {
533
+ await this.provider.abortMultipartUpload?.(this.state.uploadId);
534
+ } catch (error) {
535
+ logWarn("Failed to abort upload on provider", {
536
+ error: error instanceof Error ? error.message : String(error),
537
+ uploadId: this.state.uploadId,
538
+ key: this.state.key
539
+ });
540
+ }
541
+ this.state = null;
542
+ this.abortController = null;
543
+ }
544
+ /**
545
+ * Get current upload state
546
+ */
547
+ getState() {
548
+ return this.state;
549
+ }
550
+ /**
551
+ * Resume upload from state (for recovery)
552
+ *
553
+ * @param state - Previous upload state
554
+ */
555
+ async resumeUpload(state) {
556
+ if (this.state && !this.state.completed && !this.state.aborted) throw new Error("Upload already in progress");
557
+ this.state = { ...state };
558
+ this.abortController = new AbortController();
559
+ }
560
+ /**
561
+ * Upload file in chunks automatically
562
+ *
563
+ * @param key - Storage key
564
+ * @param data - File data
565
+ * @param options - Upload options
566
+ * @returns Upload result
567
+ */
568
+ async uploadFile(key, data, options = {}) {
569
+ const totalSize = data instanceof ArrayBuffer ? data.byteLength : data instanceof Buffer ? data.length : data.size;
570
+ await this.createUpload(key, totalSize, options);
571
+ const partSize = this.calculatePartSize(totalSize, options.partSize);
572
+ const totalParts = Math.ceil(totalSize / partSize);
573
+ for (let i = 0; i < totalParts; i++) {
574
+ const start = i * partSize;
575
+ const end = Math.min(start + partSize, totalSize);
576
+ const partData = data.slice(start, end);
577
+ await this.uploadPart(i + 1, partData, { onProgress: options.onProgress ? (progress) => {
578
+ options.onProgress?.({
579
+ key: progress.key,
580
+ loaded: progress.loaded,
581
+ total: progress.total,
582
+ part: progress.part ?? 0,
583
+ percentage: progress.percentage ?? 0
584
+ });
585
+ } : void 0 });
586
+ }
587
+ return await this.completeUpload();
588
+ }
589
+ async uploadPartWithRetry(partNumber, data, options, maxRetries = 3) {
590
+ let lastError = null;
591
+ for (let attempt = 1; attempt <= maxRetries; attempt++) try {
592
+ if (!this.state?.uploadId) throw new Error("Upload ID not initialized");
593
+ const result = await this.provider.uploadPart?.(this.state.uploadId, partNumber, data, {
594
+ ...options,
595
+ abortSignal: this.abortController?.signal
596
+ });
597
+ if (!result) throw new Error("Failed to upload part");
598
+ return {
599
+ etag: result.etag ?? "",
600
+ partNumber: result.partNumber ?? partNumber,
601
+ size: data instanceof ArrayBuffer ? data.byteLength : data instanceof Buffer ? data.length : data.size
602
+ };
603
+ } catch (error) {
604
+ lastError = error instanceof Error ? error : new Error(String(error));
605
+ if (this.abortController?.signal.aborted) throw lastError;
606
+ if (lastError.message.includes("validation") || lastError.message.includes("invalid")) throw lastError;
607
+ if (attempt < maxRetries) await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempt) * STORAGE_CONSTANTS.RETRY_BASE_DELAY_MS));
608
+ }
609
+ throw lastError ?? /* @__PURE__ */ new Error("Upload failed after retries");
610
+ }
611
+ calculatePartSize(totalSize, userPartSize) {
612
+ if (userPartSize) return Math.min(userPartSize, totalSize);
613
+ if (totalSize < MULTIPART_THRESHOLDS.SMALL_FILE) return PART_SIZES.SMALL;
614
+ else if (totalSize < MULTIPART_THRESHOLDS.MEDIUM_FILE) return PART_SIZES.MEDIUM;
615
+ else {
616
+ const minPartSize = Math.ceil(totalSize / 9999);
617
+ return Math.max(PART_SIZES.LARGE, minPartSize);
618
+ }
619
+ }
620
+ getProviderName() {
621
+ return this.provider.constructor.name;
622
+ }
623
+ };
624
+ /**
625
+ * Create a multipart upload manager for a provider
626
+ *
627
+ * @param provider - Storage provider
628
+ * @returns Multipart upload manager
629
+ */
630
+ function createMultipartUploadManager(provider) {
631
+ if (!hasMultipartSupport(provider)) throw new Error("The provided storage provider does not support multipart uploads");
632
+ return new MultipartUploadManager(provider);
633
+ }
634
+ /**
635
+ * Determines whether the given storage provider supports multipart uploads.
636
+ *
637
+ * @param provider - The storage provider to check
638
+ * @returns `true` if the provider supports multipart uploads, `false` otherwise.
639
+ */
640
+ function hasMultipartSupport(provider) {
641
+ return (provider.getCapabilities?.())?.multipart ?? false;
642
+ }
643
+ /**
644
+ * Selects an appropriate multipart upload part size for a file.
645
+ *
646
+ * If `userPartSize` is provided, it will be capped at the file size; otherwise the part size
647
+ * is chosen from configured thresholds for small, medium, or large files.
648
+ *
649
+ * @param fileSize - File size in bytes
650
+ * @param userPartSize - Optional user-specified part size in bytes; capped to `fileSize` when provided
651
+ * @returns The selected part size in bytes
652
+ */
653
+ function getOptimalPartSize(fileSize, userPartSize) {
654
+ if (userPartSize) return Math.min(userPartSize, fileSize);
655
+ if (fileSize < MULTIPART_THRESHOLDS.SMALL_FILE) return PART_SIZES.SMALL;
656
+ else if (fileSize < MULTIPART_THRESHOLDS.MEDIUM_FILE) return PART_SIZES.MEDIUM;
657
+ else {
658
+ const minPartSize = Math.ceil(fileSize / 9999);
659
+ return Math.max(PART_SIZES.LARGE, minPartSize);
660
+ }
661
+ }
662
+
663
+ //#endregion
664
+ //#region src/capabilities.ts
665
+ /**
666
+ * @fileoverview Storage Provider Capabilities Utilities
667
+ *
668
+ * Provides utilities for checking storage provider capabilities and feature support.
669
+ * Helps determine which features are available for each provider.
670
+ *
671
+ * @module @od-oneapp/storage/capabilities
672
+ */
673
+ /**
674
+ * Check if a storage provider has a specific capability
675
+ * @param provider - The storage provider to check
676
+ * @param capability - The capability to check for
677
+ * @returns True if the provider supports the capability
678
+ */
679
+ function hasCapability(provider, capability) {
680
+ return (provider.getCapabilities?.())?.[capability] ?? false;
681
+ }
682
+ /**
683
+ * Check if a storage provider supports multiple capabilities
684
+ * @param provider - The storage provider to check
685
+ * @param capabilities - Array of capabilities to check for
686
+ * @returns True if the provider supports all capabilities
687
+ */
688
+ function hasAllCapabilities(provider, capabilities) {
689
+ return capabilities.every((capability) => hasCapability(provider, capability));
690
+ }
691
+ /**
692
+ * Check if a storage provider supports any of the specified capabilities
693
+ * @param provider - The storage provider to check
694
+ * @param capabilities - Array of capabilities to check for
695
+ * @returns True if the provider supports at least one capability
696
+ */
697
+ function hasAnyCapability(provider, capabilities) {
698
+ return capabilities.some((capability) => hasCapability(provider, capability));
699
+ }
700
+ /**
701
+ * Get all capabilities supported by a storage provider
702
+ * @param provider - The storage provider to check
703
+ * @returns Object with all capabilities and their support status
704
+ */
705
+ function getProviderCapabilities(provider) {
706
+ return provider.getCapabilities?.() ?? { ...DEFAULT_STORAGE_CAPABILITIES };
707
+ }
708
+ /**
709
+ * Get a human-readable description of provider capabilities
710
+ * @param provider - The storage provider to describe
711
+ * @returns String describing the provider's capabilities
712
+ */
713
+ function describeProviderCapabilities(provider) {
714
+ const capabilities = getProviderCapabilities(provider);
715
+ const supportedFeatures = [];
716
+ const unsupportedFeatures = [];
717
+ if (capabilities.multipart) supportedFeatures.push("multipart uploads");
718
+ else unsupportedFeatures.push("multipart uploads");
719
+ if (capabilities.presignedUrls) supportedFeatures.push("presigned URLs");
720
+ else unsupportedFeatures.push("presigned URLs");
721
+ if (capabilities.progressTracking) supportedFeatures.push("progress tracking");
722
+ else unsupportedFeatures.push("progress tracking");
723
+ if (capabilities.abortSignal) supportedFeatures.push("abort signals");
724
+ else unsupportedFeatures.push("abort signals");
725
+ if (capabilities.metadata) supportedFeatures.push("metadata");
726
+ else unsupportedFeatures.push("metadata");
727
+ if (capabilities.customDomains) supportedFeatures.push("custom domains");
728
+ else unsupportedFeatures.push("custom domains");
729
+ if (capabilities.edgeCompatible) supportedFeatures.push("edge runtime");
730
+ else unsupportedFeatures.push("edge runtime");
731
+ let description = `Provider supports: ${supportedFeatures.join(", ")}`;
732
+ if (unsupportedFeatures.length > 0) description += `\nProvider does not support: ${unsupportedFeatures.join(", ")}`;
733
+ return description;
734
+ }
735
+ /**
736
+ * Validate that a provider supports the required capabilities for an operation
737
+ * @param provider - The storage provider to validate
738
+ * @param requiredCapabilities - Capabilities required for the operation
739
+ * @throws Error if provider doesn't support required capabilities
740
+ */
741
+ function validateProviderCapabilities(provider, requiredCapabilities) {
742
+ const missingCapabilities = requiredCapabilities.filter((capability) => !hasCapability(provider, capability));
743
+ if (missingCapabilities.length > 0) {
744
+ const providerName = provider.constructor.name;
745
+ throw new Error(`Provider ${providerName} does not support required capabilities: ${missingCapabilities.join(", ")}`);
746
+ }
747
+ }
748
+ /**
749
+ * Get the best provider for a specific use case based on capabilities
750
+ * @param providers - Array of storage providers to choose from
751
+ * @param requiredCapabilities - Capabilities required for the use case
752
+ * @returns The best provider or null if none meet the requirements
753
+ */
754
+ function getBestProvider(providers, requiredCapabilities) {
755
+ const suitableProviders = providers.filter((provider) => hasAllCapabilities(provider, requiredCapabilities));
756
+ if (suitableProviders.length === 0) return null;
757
+ const edgeCompatible = suitableProviders.filter((provider) => hasCapability(provider, "edgeCompatible"));
758
+ return edgeCompatible.length > 0 ? edgeCompatible[0] ?? null : suitableProviders[0] ?? null;
759
+ }
760
+ /**
761
+ * Builds a map from provider names to their reported storage capabilities.
762
+ *
763
+ * @param providers - Array of entries each containing a `name` (used as the map key) and a `provider` instance
764
+ * @returns A mapping from each provider name to its `StorageCapabilities`
765
+ */
766
+ function getCapabilityMatrix(providers) {
767
+ const matrix = {};
768
+ for (const { name, provider } of providers) matrix[name] = getProviderCapabilities(provider);
769
+ return matrix;
770
+ }
771
+ /**
772
+ * Evaluate a storage provider's suitability for a specific file and produce actionable recommendations and warnings.
773
+ *
774
+ * @param provider - The storage provider to evaluate
775
+ * @param fileSize - File size in bytes
776
+ * @param fileType - MIME type of the file
777
+ * @returns An object with `suitable` (`true` if there are no warnings, `false` otherwise), `recommendations` (suggested actions to improve handling), and `warnings` (issues that reduce suitability)
778
+ */
779
+ function checkProviderSuitability(provider, fileSize, fileType) {
780
+ const capabilities = getProviderCapabilities(provider);
781
+ const recommendations = [];
782
+ const warnings = [];
783
+ if (fileSize > MULTIPART_THRESHOLDS.SMALL_FILE) if (!capabilities.multipart) warnings.push("Large file detected but provider does not support multipart uploads");
784
+ else recommendations.push("Use multipart upload for this large file");
785
+ if (fileType.startsWith("image/")) {
786
+ if (capabilities.metadata) recommendations.push("Consider storing image metadata for better organization");
787
+ }
788
+ if (fileType.startsWith("video/")) {
789
+ if (!capabilities.multipart) warnings.push("Video files are typically large and benefit from multipart uploads");
790
+ }
791
+ if (fileType.startsWith("text/") && !capabilities.edgeCompatible) recommendations.push("Text files could be processed in edge runtime for better performance");
792
+ return {
793
+ suitable: warnings.length === 0,
794
+ recommendations,
795
+ warnings
796
+ };
797
+ }
798
+
799
+ //#endregion
800
+ //#region src/health-check.ts
801
+ /**
802
+ * Check the health of a storage provider
803
+ *
804
+ * @param provider - The storage provider to check
805
+ * @returns Health check result with status and latency
806
+ */
807
+ async function checkProviderHealth(provider) {
808
+ const startTime = Date.now();
809
+ try {
810
+ await provider.list({ limit: 1 });
811
+ const latencyMs = Date.now() - startTime;
812
+ const HEALTHY_THRESHOLD_MS = 1e3;
813
+ const DEGRADED_THRESHOLD_MS = 3e3;
814
+ let status;
815
+ if (latencyMs < HEALTHY_THRESHOLD_MS) status = "healthy";
816
+ else if (latencyMs < DEGRADED_THRESHOLD_MS) status = "degraded";
817
+ else status = "unhealthy";
818
+ return {
819
+ status,
820
+ latencyMs,
821
+ details: {
822
+ provider: provider.constructor.name,
823
+ threshold_healthy_ms: HEALTHY_THRESHOLD_MS,
824
+ threshold_degraded_ms: DEGRADED_THRESHOLD_MS
825
+ }
826
+ };
827
+ } catch (error) {
828
+ return {
829
+ status: "unhealthy",
830
+ latencyMs: Date.now() - startTime,
831
+ error: error instanceof Error ? error.message : String(error),
832
+ details: { provider: provider.constructor.name }
833
+ };
834
+ }
835
+ }
836
+ /**
837
+ * Perform a comprehensive health check on storage system
838
+ *
839
+ * @param provider - The storage provider to check
840
+ * @returns Detailed health check result
841
+ */
842
+ async function storageHealthCheck(provider) {
843
+ return checkProviderHealth(provider);
844
+ }
845
+
846
+ //#endregion
847
+ export { logWarn as S, DEFAULT_STORAGE_CAPABILITIES as _, getBestProvider as a, CloudflareImagesProvider as b, hasAllCapabilities as c, validateProviderCapabilities as d, MultipartUploadManager as f, MultiStorageManager as g, hasMultipartSupport as h, describeProviderCapabilities as i, hasAnyCapability as l, getOptimalPartSize as m, storageHealthCheck as n, getCapabilityMatrix as o, createMultipartUploadManager as p, checkProviderSuitability as r, getProviderCapabilities as s, checkProviderHealth as t, hasCapability as u, STORAGE_CONSTANTS as v, logError as x, CloudflareR2Provider as y };
848
+ //# sourceMappingURL=health-check-DbHmYLDb.mjs.map