@visulima/storage 1.0.9 → 1.0.10

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.
Files changed (143) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/adapter/nuxt/module.d.ts +8 -8
  3. package/dist/ai/ai-sdk/index.d.ts +51 -59
  4. package/dist/ai/claude/index.d.ts +104 -119
  5. package/dist/ai/openai/index.d.ts +86 -99
  6. package/dist/ai/tanstack/index.d.ts +53 -61
  7. package/dist/handler/http/fetch/index.d.ts +201 -201
  8. package/dist/handler/http/hono/index.d.ts +59 -59
  9. package/dist/handler/http/nextjs/index.d.ts +54 -54
  10. package/dist/handler/http/node/index.d.ts +233 -246
  11. package/dist/handler/http/solid-start/index.d.ts +54 -54
  12. package/dist/index.d.ts +70 -70
  13. package/dist/index.js +1 -1
  14. package/dist/packem_shared/{AwsLightStorage-BK-WPL0h.js → AwsLightStorage-EsqkAtU5.js} +1 -1
  15. package/dist/packem_shared/{AzureStorage-1UvDIQZd.js → AzureStorage-DL-U7qFG.js} +1 -1
  16. package/dist/packem_shared/BoxMetaStorage-CHWrhgg2.js +1 -0
  17. package/dist/packem_shared/{BoxStorage-DbGqBLux.js → BoxStorage-B8_oCz27.js} +1 -1
  18. package/dist/packem_shared/BunS3MetaStorage-CHWrhgg2.js +1 -0
  19. package/dist/packem_shared/{BunS3Storage-DNvimm9e.js → BunS3Storage-_PVXu_na.js} +1 -1
  20. package/dist/packem_shared/BunnyMetaStorage-CHWrhgg2.js +1 -0
  21. package/dist/packem_shared/{BunnyStorage-C7d0opLL.js → BunnyStorage-BsoWjScH.js} +1 -1
  22. package/dist/packem_shared/CloudinaryMetaStorage-BI9YXcwU.js +1 -0
  23. package/dist/packem_shared/{CloudinaryStorage-Dc3XA2lP.js → CloudinaryStorage-BNwiLF9V.js} +1 -1
  24. package/dist/packem_shared/{DiskStorage-CI07TVNu.js → DiskStorage-D-NtQDms.js} +1 -1
  25. package/dist/packem_shared/{DiskStorageWithChecksum-vFCubS6K.js → DiskStorageWithChecksum-UnCtyEvs.js} +1 -1
  26. package/dist/packem_shared/DropboxMetaStorage-CHWrhgg2.js +1 -0
  27. package/dist/packem_shared/{DropboxStorage-CY9Ggu3m.js → DropboxStorage-BS9kj0nH.js} +1 -1
  28. package/dist/packem_shared/FirebaseMetaStorage-BI9YXcwU.js +1 -0
  29. package/dist/packem_shared/{FirebaseStorage-D6O9CJXN.js → FirebaseStorage-DNquii2p.js} +1 -1
  30. package/dist/packem_shared/FtpMetaStorage-CHWrhgg2.js +1 -0
  31. package/dist/packem_shared/{FtpStorage-DbEjbq8z.js → FtpStorage-Bd004--s.js} +1 -1
  32. package/dist/packem_shared/{GCSMetaStorage-DT8K6zdm.js → GCSMetaStorage-Bf4qDFB1.js} +1 -1
  33. package/dist/packem_shared/{GCStorage-6BHkFlEs.js → GCStorage-ChqEpgqR.js} +1 -1
  34. package/dist/packem_shared/GoogleDriveMetaStorage-xlHfKwmR.js +1 -0
  35. package/dist/packem_shared/{GoogleDriveStorage-Bklsz7Bh.js → GoogleDriveStorage-v1glykjd.js} +1 -1
  36. package/dist/packem_shared/{LocalMetaStorage-BhicZnNl.js → LocalMetaStorage-YWPBYEe7.js} +1 -1
  37. package/dist/packem_shared/NetlifyBlobMetaStorage-BI9YXcwU.js +1 -0
  38. package/dist/packem_shared/{NetlifyBlobStorage-CkpCCoN1.js → NetlifyBlobStorage-BPyEWSnx.js} +1 -1
  39. package/dist/packem_shared/OneDriveMetaStorage-xlHfKwmR.js +1 -0
  40. package/dist/packem_shared/{OneDriveStorage-CP6MvGAa.js → OneDriveStorage-BJ3Kzxc5.js} +1 -1
  41. package/dist/packem_shared/PocketBaseMetaStorage-DnrxOQhO.js +1 -0
  42. package/dist/packem_shared/{PocketBaseStorage-2qhbI2PW.js → PocketBaseStorage-DqKHbbvn.js} +1 -1
  43. package/dist/packem_shared/{S3Storage-YGeNk3Tt.js → S3Storage-BiI2k6d1.js} +1 -1
  44. package/dist/packem_shared/SftpMetaStorage-CHWrhgg2.js +1 -0
  45. package/dist/packem_shared/{SftpStorage-2Hz396Xr.js → SftpStorage-w8XdtZtw.js} +1 -1
  46. package/dist/packem_shared/SharePointMetaStorage-CHWrhgg2.js +1 -0
  47. package/dist/packem_shared/{SharePointStorage-CrX2Pk6C.js → SharePointStorage-DpDpI7Ln.js} +1 -1
  48. package/dist/packem_shared/SupabaseMetaStorage-xlHfKwmR.js +1 -0
  49. package/dist/packem_shared/{SupabaseStorage-Dc_DBX29.js → SupabaseStorage-B_ugUCs7.js} +1 -1
  50. package/dist/packem_shared/UploadThingMetaStorage-BI9YXcwU.js +1 -0
  51. package/dist/packem_shared/{UploadThingStorage-BChykYSe.js → UploadThingStorage-_H45IVqX.js} +1 -1
  52. package/dist/packem_shared/VercelBlobMetaStorage-CHWrhgg2.js +1 -0
  53. package/dist/packem_shared/{VercelBlobStorage-CsRyPfw3.js → VercelBlobStorage-U1YMKeHs.js} +1 -1
  54. package/dist/packem_shared/{approval.d-CMAYH9GF.d.ts → approval.d-C-d-t94D.d.ts} +6 -6
  55. package/dist/packem_shared/disk-storage-BwPk2IRa.js +1 -0
  56. package/dist/packem_shared/disk-storage-with-checksum.d-CQucFacO.d.ts +146 -0
  57. package/dist/packem_shared/{executors.d-BZP2rWo3.d.ts → executors.d-DeDH3Ilt.d.ts} +2 -2
  58. package/dist/packem_shared/files.d-D8H_ge9Y.d.ts +655 -0
  59. package/dist/packem_shared/{gcs-meta-storage-B7BnctnV.js → gcs-meta-storage-DQGu_cHq.js} +1 -1
  60. package/dist/packem_shared/local-meta-storage-DJDcuxf1.js +11 -0
  61. package/dist/packem_shared/{local-meta-storage.d-D9PBfkn6.d.ts → local-meta-storage.d-DuTEzyii.d.ts} +7 -7
  62. package/dist/packem_shared/media-transformer.d-CvMFjINm.d.ts +331 -0
  63. package/dist/packem_shared/{memory-storage.d-4EU1cMt1.d.ts → memory-storage.d-BRdTiY8y.d.ts} +32 -40
  64. package/dist/packem_shared/{s3-base-storage-BoTyhuzO.js → s3-base-storage-CMUui93V.js} +1 -1
  65. package/dist/packem_shared/{s3-base-storage.d-BQgP5B-t.d.ts → s3-base-storage.d-Cg7m4FuH.d.ts} +64 -70
  66. package/dist/packem_shared/storage.d-DIav_lF1.d.ts +1163 -0
  67. package/dist/packem_shared/tus-base.d-BiEg5t4t.d.ts +102 -0
  68. package/dist/packem_shared/{types.d-CrUWY4On.d.ts → types.d-CAAzKiI6.d.ts} +134 -134
  69. package/dist/packem_shared/types.d-DgHhkCAl.d.ts +104 -0
  70. package/dist/packem_shared/{types.d-CggTCgXr.d.ts → types.d-jAs_Rp_v.d.ts} +3 -3
  71. package/dist/storage/aws/clients/index.d.ts +388 -388
  72. package/dist/storage/aws/index.d.ts +109 -113
  73. package/dist/storage/aws/index.js +1 -1
  74. package/dist/storage/aws-light/index.d.ts +63 -67
  75. package/dist/storage/aws-light/index.js +1 -1
  76. package/dist/storage/azure/index.d.ts +133 -139
  77. package/dist/storage/azure/index.js +1 -1
  78. package/dist/storage/box/index.d.ts +88 -92
  79. package/dist/storage/box/index.js +1 -1
  80. package/dist/storage/bun-s3/index.d.ts +70 -76
  81. package/dist/storage/bun-s3/index.js +1 -1
  82. package/dist/storage/bunny/index.d.ts +51 -55
  83. package/dist/storage/bunny/index.js +1 -1
  84. package/dist/storage/cloudinary/index.d.ts +53 -59
  85. package/dist/storage/cloudinary/index.js +1 -1
  86. package/dist/storage/dropbox/index.d.ts +58 -62
  87. package/dist/storage/dropbox/index.js +1 -1
  88. package/dist/storage/firebase/index.d.ts +73 -79
  89. package/dist/storage/firebase/index.js +1 -1
  90. package/dist/storage/ftp/index.d.ts +37 -43
  91. package/dist/storage/ftp/index.js +1 -1
  92. package/dist/storage/gcs/index.d.ts +89 -95
  93. package/dist/storage/gcs/index.js +1 -1
  94. package/dist/storage/google-drive/index.d.ts +68 -72
  95. package/dist/storage/google-drive/index.js +1 -1
  96. package/dist/storage/local/index.d.ts +3 -3
  97. package/dist/storage/local/index.js +1 -1
  98. package/dist/storage/memory/index.d.ts +2 -2
  99. package/dist/storage/netlify-blob/index.d.ts +85 -93
  100. package/dist/storage/netlify-blob/index.js +1 -1
  101. package/dist/storage/onedrive/index.d.ts +43 -53
  102. package/dist/storage/onedrive/index.js +1 -1
  103. package/dist/storage/pocketbase/index.d.ts +66 -72
  104. package/dist/storage/pocketbase/index.js +1 -1
  105. package/dist/storage/sftp/index.d.ts +39 -45
  106. package/dist/storage/sftp/index.js +1 -1
  107. package/dist/storage/sharepoint/index.d.ts +95 -95
  108. package/dist/storage/sharepoint/index.js +1 -1
  109. package/dist/storage/supabase/index.d.ts +49 -55
  110. package/dist/storage/supabase/index.js +1 -1
  111. package/dist/storage/uploadthing/index.d.ts +33 -37
  112. package/dist/storage/uploadthing/index.js +1 -1
  113. package/dist/storage/vercel-blob/index.d.ts +109 -115
  114. package/dist/storage/vercel-blob/index.js +1 -1
  115. package/dist/transformer/audio-transformer.d.ts +96 -96
  116. package/dist/transformer/image-transformer.d.ts +422 -422
  117. package/dist/transformer/index.d.ts +34 -34
  118. package/dist/transformer/video-transformer.d.ts +111 -111
  119. package/package.json +1 -1
  120. package/dist/packem_shared/BoxMetaStorage-BSn6Qfnf.js +0 -1
  121. package/dist/packem_shared/BunS3MetaStorage-BSn6Qfnf.js +0 -1
  122. package/dist/packem_shared/BunnyMetaStorage-BSn6Qfnf.js +0 -1
  123. package/dist/packem_shared/CloudinaryMetaStorage-DPVnmNe5.js +0 -1
  124. package/dist/packem_shared/DropboxMetaStorage-BSn6Qfnf.js +0 -1
  125. package/dist/packem_shared/FirebaseMetaStorage-DPVnmNe5.js +0 -1
  126. package/dist/packem_shared/FtpMetaStorage-BSn6Qfnf.js +0 -1
  127. package/dist/packem_shared/GoogleDriveMetaStorage-Cbwa1CHV.js +0 -1
  128. package/dist/packem_shared/NetlifyBlobMetaStorage-DPVnmNe5.js +0 -1
  129. package/dist/packem_shared/OneDriveMetaStorage-Cbwa1CHV.js +0 -1
  130. package/dist/packem_shared/PocketBaseMetaStorage-DOTLwVE7.js +0 -1
  131. package/dist/packem_shared/SftpMetaStorage-BSn6Qfnf.js +0 -1
  132. package/dist/packem_shared/SharePointMetaStorage-BSn6Qfnf.js +0 -1
  133. package/dist/packem_shared/SupabaseMetaStorage-Cbwa1CHV.js +0 -1
  134. package/dist/packem_shared/UploadThingMetaStorage-DPVnmNe5.js +0 -1
  135. package/dist/packem_shared/VercelBlobMetaStorage-BSn6Qfnf.js +0 -1
  136. package/dist/packem_shared/disk-storage-CsQcYW3s.js +0 -1
  137. package/dist/packem_shared/disk-storage-with-checksum.d-B-VGEsfl.d.ts +0 -156
  138. package/dist/packem_shared/files.d-CH0iLBNC.d.ts +0 -655
  139. package/dist/packem_shared/local-meta-storage-iuJnu90B.js +0 -11
  140. package/dist/packem_shared/media-transformer.d-Quf4ai47.d.ts +0 -331
  141. package/dist/packem_shared/storage.d-CEM1upWM.d.ts +0 -1176
  142. package/dist/packem_shared/tus-base.d-DLzKE54M.d.ts +0 -106
  143. package/dist/packem_shared/types.d-Bon9GVVe.d.ts +0 -104
@@ -1,69 +1,69 @@
1
1
  import { APIEvent } from '@solidjs/start/server';
2
- import { U as UploadFile } from "../../../packem_shared/storage.d-CEM1upWM.js";
2
+ import { U as UploadFile } from "../../../packem_shared/storage.d-DIav_lF1.js";
3
3
  import 'node:stream';
4
- import { U as UploadOptions } from "../../../packem_shared/types.d-CggTCgXr.js";
4
+ import { U as UploadOptions } from "../../../packem_shared/types.d-jAs_Rp_v.js";
5
5
  import 'node:crypto';
6
6
  import 'node:http';
7
7
  import 'lru-cache';
8
8
  import 'node:events';
9
9
  import '@visulima/pagination';
10
- import "../../../packem_shared/media-transformer.d-Quf4ai47.js";
11
- import "../../../packem_shared/types.d-CrUWY4On.js";
10
+ import "../../../packem_shared/media-transformer.d-CvMFjINm.js";
11
+ import "../../../packem_shared/types.d-CAAzKiI6.js";
12
12
  /**
13
- * Configuration for SolidStart handler.
14
- */
13
+ * Configuration for SolidStart handler.
14
+ */
15
15
  interface SolidStartHandlerConfig<TFile extends UploadFile> extends UploadOptions<TFile> {
16
16
  /** Handler type to use */
17
17
  type: "multipart" | "rest" | "tus";
18
18
  }
19
19
  /**
20
- * SolidStart API route handler that automatically handles the correct HTTP methods for each handler type.
21
- * @example
22
- * ```ts
23
- * // app/routes/api/upload/multipart.ts
24
- * import { DiskStorage } from "@visulima/storage";
25
- * import { createSolidStartHandler } from "@visulima/storage/handler/http/solid-start";
26
- *
27
- * const storage = new DiskStorage({ directory: "./uploads" });
28
- * const handler = createSolidStartHandler({ storage, type: "multipart" });
29
- *
30
- * export const POST = handler;
31
- * export const DELETE = handler;
32
- * export const GET = handler;
33
- * export const OPTIONS = handler;
34
- * ```
35
- * @example
36
- * ```ts
37
- * // app/routes/api/upload/rest.ts
38
- * import { DiskStorage } from "@visulima/storage";
39
- * import { createSolidStartHandler } from "@visulima/storage/handler/http/solid-start";
40
- *
41
- * const storage = new DiskStorage({ directory: "./uploads" });
42
- * const handler = createSolidStartHandler({ storage, type: "rest" });
43
- *
44
- * export const POST = handler;
45
- * export const PUT = handler;
46
- * export const PATCH = handler;
47
- * export const GET = handler;
48
- * export const HEAD = handler;
49
- * export const DELETE = handler;
50
- * export const OPTIONS = handler;
51
- * ```
52
- * @example
53
- * ```ts
54
- * // app/routes/api/upload/tus.ts
55
- * import { DiskStorage } from "@visulima/storage";
56
- * import { createSolidStartHandler } from "@visulima/storage/handler/http/solid-start";
57
- *
58
- * const storage = new DiskStorage({ directory: "./uploads" });
59
- * const handler = createSolidStartHandler({ storage, type: "tus" });
60
- *
61
- * export const POST = handler;
62
- * export const PATCH = handler;
63
- * export const HEAD = handler;
64
- * export const DELETE = handler;
65
- * export const OPTIONS = handler;
66
- * ```
67
- */
20
+ * SolidStart API route handler that automatically handles the correct HTTP methods for each handler type.
21
+ * @example
22
+ * ```ts
23
+ * // app/routes/api/upload/multipart.ts
24
+ * import { DiskStorage } from "@visulima/storage";
25
+ * import { createSolidStartHandler } from "@visulima/storage/handler/http/solid-start";
26
+ *
27
+ * const storage = new DiskStorage({ directory: "./uploads" });
28
+ * const handler = createSolidStartHandler({ storage, type: "multipart" });
29
+ *
30
+ * export const POST = handler;
31
+ * export const DELETE = handler;
32
+ * export const GET = handler;
33
+ * export const OPTIONS = handler;
34
+ * ```
35
+ * @example
36
+ * ```ts
37
+ * // app/routes/api/upload/rest.ts
38
+ * import { DiskStorage } from "@visulima/storage";
39
+ * import { createSolidStartHandler } from "@visulima/storage/handler/http/solid-start";
40
+ *
41
+ * const storage = new DiskStorage({ directory: "./uploads" });
42
+ * const handler = createSolidStartHandler({ storage, type: "rest" });
43
+ *
44
+ * export const POST = handler;
45
+ * export const PUT = handler;
46
+ * export const PATCH = handler;
47
+ * export const GET = handler;
48
+ * export const HEAD = handler;
49
+ * export const DELETE = handler;
50
+ * export const OPTIONS = handler;
51
+ * ```
52
+ * @example
53
+ * ```ts
54
+ * // app/routes/api/upload/tus.ts
55
+ * import { DiskStorage } from "@visulima/storage";
56
+ * import { createSolidStartHandler } from "@visulima/storage/handler/http/solid-start";
57
+ *
58
+ * const storage = new DiskStorage({ directory: "./uploads" });
59
+ * const handler = createSolidStartHandler({ storage, type: "tus" });
60
+ *
61
+ * export const POST = handler;
62
+ * export const PATCH = handler;
63
+ * export const HEAD = handler;
64
+ * export const DELETE = handler;
65
+ * export const OPTIONS = handler;
66
+ * ```
67
+ */
68
68
  declare const createSolidStartHandler: <TFile extends UploadFile>(config: SolidStartHandlerConfig<TFile>) => ((event: APIEvent) => Promise<Response>);
69
69
  export { SolidStartHandlerConfig, createSolidStartHandler };
package/dist/index.d.ts CHANGED
@@ -1,106 +1,106 @@
1
- import { F as Files, S as SyncOptions, a as SyncResult, T as TransferOptions, b as TransferResult } from "./packem_shared/files.d-CH0iLBNC.js";
2
- export { type B as BulkDeleteResult, type c as BulkDownloadOptions, type d as BulkDownloadResult, type e as BulkError, type f as BulkExistsResult, type g as BulkHeadResult, type h as BulkMoveItem, type i as BulkMoveResult, type j as BulkOptions, type k as BulkUploadItem, type l as BulkUploadOptions, type m as BulkUploadResult, type D as DownloadOptions, type n as DownloadRange, type o as DownloadResult, type p as DownloadStreamResult, type q as FileBody, type r as FileObject, type s as FilesHooks, type t as FilesOptions, type H as HookActionType, type u as HookEvent, type L as ListAllOptions, type v as ListDirectoryResult, type w as ListOptions, type M as MultipartOptions, type x as SignedReadUrlOptions, type y as SignedUploadUrlOptions, type z as StorageCapabilities, type A as SyncProgress, type C as TransferProgress, U as UploadControl, type E as UploadControlState, type G as UploadControlToken, type I as UploadOptions, type J as UploadProgress, type K as UploadProgressCallback } from "./packem_shared/files.d-CH0iLBNC.js";
3
- import { n as Metrics } from "./packem_shared/storage.d-CEM1upWM.js";
4
- export { B as AbstractBaseStorage, type l as BaseStorageOptions, type o as BatchOperationResponse, type p as BatchOperationResult, type D as DiskStorageOptions, type j as DiskStorageWithChecksumOptions, i as ERRORS, q as ErrorMap, type r as ExpirationOptions, F as File, type d as FileInit, type e as FilePart, type f as FileQuery, type s as Header, type t as Headers, type H as HttpError, type u as HttpErrorBody, type I as IncomingMessageWithBody, type L as LocalMetaStorageOptions, M as MetaStorage, type k as MetaStorageOptions, v as Metadata, type w as OnComplete, type x as OnCreate, type y as OnDelete, type z as OnError, type A as OnUpdate, type P as PurgeList, type G as RangeChecksum, type J as RangeHasher, type K as ResponseBody, type h as ResponseBodyType, type N as ResponseTuple, type R as RetryConfig, a as UploadError, type b as UploadEventType, type U as UploadFile, type m as UploadResponse, type V as Validation, type Q as ValidationError, type S as ValidatorConfig, c as createRetryWrapper, T as defaultCloudStorageFileNameValidation, W as defaultFilesystemFileNameValidation, X as extractHttpStatus, Y as isRetryableError, Z as isUploadError, _ as mapStatusToErrorCode, $ as retry, a0 as throwErrorCode, a1 as wrapStorageError } from "./packem_shared/storage.d-CEM1upWM.js";
1
+ import { F as Files, S as SyncOptions, a as SyncResult, T as TransferOptions, b as TransferResult } from "./packem_shared/files.d-D8H_ge9Y.js";
2
+ export { type B as BulkDeleteResult, type c as BulkDownloadOptions, type d as BulkDownloadResult, type e as BulkError, type f as BulkExistsResult, type g as BulkHeadResult, type h as BulkMoveItem, type i as BulkMoveResult, type j as BulkOptions, type k as BulkUploadItem, type l as BulkUploadOptions, type m as BulkUploadResult, type D as DownloadOptions, type n as DownloadRange, type o as DownloadResult, type p as DownloadStreamResult, type q as FileBody, type r as FileObject, type s as FilesHooks, type t as FilesOptions, type H as HookActionType, type u as HookEvent, type L as ListAllOptions, type v as ListDirectoryResult, type w as ListOptions, type M as MultipartOptions, type x as SignedReadUrlOptions, type y as SignedUploadUrlOptions, type z as StorageCapabilities, type A as SyncProgress, type C as TransferProgress, U as UploadControl, type E as UploadControlState, type G as UploadControlToken, type I as UploadOptions, type J as UploadProgress, type K as UploadProgressCallback } from "./packem_shared/files.d-D8H_ge9Y.js";
3
+ import { n as Metrics } from "./packem_shared/storage.d-DIav_lF1.js";
4
+ export { B as AbstractBaseStorage, type l as BaseStorageOptions, type o as BatchOperationResponse, type p as BatchOperationResult, type D as DiskStorageOptions, type j as DiskStorageWithChecksumOptions, i as ERRORS, q as ErrorMap, type r as ExpirationOptions, F as File, type d as FileInit, type e as FilePart, type f as FileQuery, type s as Header, type t as Headers, type H as HttpError, type u as HttpErrorBody, type I as IncomingMessageWithBody, type L as LocalMetaStorageOptions, M as MetaStorage, type k as MetaStorageOptions, v as Metadata, type w as OnComplete, type x as OnCreate, type y as OnDelete, type z as OnError, type A as OnUpdate, type P as PurgeList, type G as RangeChecksum, type J as RangeHasher, type K as ResponseBody, type h as ResponseBodyType, type N as ResponseTuple, type R as RetryConfig, a as UploadError, type b as UploadEventType, type U as UploadFile, type m as UploadResponse, type V as Validation, type Q as ValidationError, type S as ValidatorConfig, c as createRetryWrapper, T as defaultCloudStorageFileNameValidation, W as defaultFilesystemFileNameValidation, X as extractHttpStatus, Y as isRetryableError, Z as isUploadError, _ as mapStatusToErrorCode, $ as retry, a0 as throwErrorCode, a1 as wrapStorageError } from "./packem_shared/storage.d-DIav_lF1.js";
5
5
  import { Meter } from '@opentelemetry/api';
6
- export { D as DiskStorage, a as DiskStorageWithChecksum } from "./packem_shared/disk-storage-with-checksum.d-B-VGEsfl.js";
7
- export { L as LocalMetaStorage } from "./packem_shared/local-meta-storage.d-D9PBfkn6.js";
8
- export { M as MemoryMetaStorage, a as MemoryStorage, type b as MemoryStorageOptions } from "./packem_shared/memory-storage.d-4EU1cMt1.js";
6
+ export { D as DiskStorage, a as DiskStorageWithChecksum } from "./packem_shared/disk-storage-with-checksum.d-CQucFacO.js";
7
+ export { L as LocalMetaStorage } from "./packem_shared/local-meta-storage.d-DuTEzyii.js";
8
+ export { M as MemoryMetaStorage, a as MemoryStorage, type b as MemoryStorageOptions } from "./packem_shared/memory-storage.d-BRdTiY8y.js";
9
9
  export { type AnyWebReadableByteStreamWithFileType, type AnyWebReadableStream, type Detector, type FileTypeOptions, type FileTypeParser, type FileTypeResult, type StreamOptions, type TokenizerPositionError, fileTypeFromBlob, fileTypeFromBuffer, fileTypeFromTokenizer, supportedExtensions, supportedMimeTypes } from 'file-type';
10
10
  import 'node:stream';
11
11
  import 'node:crypto';
12
12
  import 'node:http';
13
13
  import 'lru-cache';
14
14
  /**
15
- * Streams every object from `source` to `destination` for cross-provider migration.
16
- * Built entirely on the public {@link Files} surface — no adapter implements anything new.
17
- *
18
- * Each object is downloaded and re-uploaded with bounded concurrency. By default missing
19
- * destination keys are uploaded and existing keys are skipped — pass `overwrite: true` to force
20
- * re-upload. Body, content type, and user metadata travel; `etag`/`lastModified` are
21
- * destination-assigned.
22
- *
23
- * Like the other bulk methods, `transfer` doesn't throw on partial failure: results come back as
24
- * `{ transferred, skipped, errors? }`.
25
- * @example
26
- * ```ts
27
- * const from = new Files({ adapter: new S3Storage({ bucket: "old", ... }) });
28
- * const to = new Files({ adapter: new GCSStorage({ bucket: "new", ... }) });
29
- *
30
- * const { transferred, skipped, errors } = await transfer(from, to, {
31
- * prefix: "uploads/",
32
- * onProgress: ({ done, key, status }) => console.log(done, key, status),
33
- * });
34
- * ```
35
- */
15
+ * Streams every object from `source` to `destination` for cross-provider migration.
16
+ * Built entirely on the public {@link Files} surface — no adapter implements anything new.
17
+ *
18
+ * Each object is downloaded and re-uploaded with bounded concurrency. By default missing
19
+ * destination keys are uploaded and existing keys are skipped — pass `overwrite: true` to force
20
+ * re-upload. Body, content type, and user metadata travel; `etag`/`lastModified` are
21
+ * destination-assigned.
22
+ *
23
+ * Like the other bulk methods, `transfer` doesn't throw on partial failure: results come back as
24
+ * `{ transferred, skipped, errors? }`.
25
+ * @example
26
+ * ```ts
27
+ * const from = new Files({ adapter: new S3Storage({ bucket: "old", ... }) });
28
+ * const to = new Files({ adapter: new GCSStorage({ bucket: "new", ... }) });
29
+ *
30
+ * const { transferred, skipped, errors } = await transfer(from, to, {
31
+ * prefix: "uploads/",
32
+ * onProgress: ({ done, key, status }) => console.log(done, key, status),
33
+ * });
34
+ * ```
35
+ */
36
36
  declare const transfer: (source: Files, destination: Files, options?: TransferOptions) => Promise<TransferResult>;
37
37
  /**
38
- * Incremental, optionally-pruning mirror from `source` to `destination`. Built entirely on the
39
- * public {@link Files} surface — no adapter implements anything new.
40
- *
41
- * Each source object is compared against its destination counterpart (by size, then etag, then
42
- * modification time) and only copied when missing or differing; matching objects are skipped. With
43
- * `prune: true`, destination keys absent from the source are deleted afterwards (full mirror).
44
- * Pass `dryRun: true` to compute the plan without writing.
45
- *
46
- * Like the other bulk methods, `sync` doesn't throw on partial failure: results come back as
47
- * `{ uploaded, updated, unchanged, deleted, errors? }`.
48
- * @example
49
- * ```ts
50
- * const from = new Files({ adapter: new S3Storage({ bucket: "primary", ... }) });
51
- * const to = new Files({ adapter: new GCSStorage({ bucket: "mirror", ... }) });
52
- *
53
- * // Preview first…
54
- * const plan = await sync(from, to, { prefix: "assets/", prune: true, dryRun: true });
55
- * // …then apply.
56
- * const result = await sync(from, to, { prefix: "assets/", prune: true });
57
- * ```
58
- */
38
+ * Incremental, optionally-pruning mirror from `source` to `destination`. Built entirely on the
39
+ * public {@link Files} surface — no adapter implements anything new.
40
+ *
41
+ * Each source object is compared against its destination counterpart (by size, then etag, then
42
+ * modification time) and only copied when missing or differing; matching objects are skipped. With
43
+ * `prune: true`, destination keys absent from the source are deleted afterwards (full mirror).
44
+ * Pass `dryRun: true` to compute the plan without writing.
45
+ *
46
+ * Like the other bulk methods, `sync` doesn't throw on partial failure: results come back as
47
+ * `{ uploaded, updated, unchanged, deleted, errors? }`.
48
+ * @example
49
+ * ```ts
50
+ * const from = new Files({ adapter: new S3Storage({ bucket: "primary", ... }) });
51
+ * const to = new Files({ adapter: new GCSStorage({ bucket: "mirror", ... }) });
52
+ *
53
+ * // Preview first…
54
+ * const plan = await sync(from, to, { prefix: "assets/", prune: true, dryRun: true });
55
+ * // …then apply.
56
+ * const result = await sync(from, to, { prefix: "assets/", prune: true });
57
+ * ```
58
+ */
59
59
  declare const sync: (source: Files, destination: Files, options?: SyncOptions) => Promise<SyncResult>;
60
60
  /**
61
- * Wait for storage to be ready before handling requests.
62
- * This ensures storage initialization (e.g., AWS S3, GCS) completes before processing uploads.
63
- * @param storage Storage instance with isReady property
64
- * @param timeoutMs Maximum time to wait in milliseconds (default: 5000)
65
- * @throws Error if storage doesn't become ready within timeout
66
- */
61
+ * Wait for storage to be ready before handling requests.
62
+ * This ensures storage initialization (e.g., AWS S3, GCS) completes before processing uploads.
63
+ * @param storage Storage instance with isReady property
64
+ * @param timeoutMs Maximum time to wait in milliseconds (default: 5000)
65
+ * @throws Error if storage doesn't become ready within timeout
66
+ */
67
67
  declare const waitForStorage: (storage: {
68
68
  isReady: boolean;
69
69
  }, timeoutMs?: number) => Promise<void>;
70
70
  /**
71
- * No-op metrics that does nothing.
72
- * Used as a default when metrics are not provided.
73
- */
71
+ * No-op metrics that does nothing.
72
+ * Used as a default when metrics are not provided.
73
+ */
74
74
  declare class NoOpMetrics implements Metrics {
75
75
  increment(_name: string, _value?: number, _attributes?: Record<string, string | number>): void;
76
76
  timing(_name: string, _duration: number, _attributes?: Record<string, string | number>): void;
77
77
  gauge(_name: string, _value: number, _attributes?: Record<string, string | number>): void;
78
78
  }
79
79
  /**
80
- * OpenTelemetry-based metrics implementation.
81
- */
80
+ * OpenTelemetry-based metrics implementation.
81
+ */
82
82
  declare class OpenTelemetryMetrics implements Metrics {
83
83
  private readonly meter;
84
84
  private readonly counters;
85
85
  private readonly histograms;
86
86
  private readonly gauges;
87
87
  /**
88
- * Creates a new OpenTelemetryMetrics instance.
89
- * @param meter OpenTelemetry Meter instance. If not provided, uses the default meter.
90
- * @throws {Error} If \@opentelemetry/api is not installed
91
- */
88
+ * Creates a new OpenTelemetryMetrics instance.
89
+ * @param meter OpenTelemetry Meter instance. If not provided, uses the default meter.
90
+ * @throws {Error} If \@opentelemetry/api is not installed
91
+ */
92
92
  constructor(meter?: Meter);
93
93
  /**
94
- * Increment a counter metric.
95
- */
94
+ * Increment a counter metric.
95
+ */
96
96
  increment(name: string, value?: number, attributes?: Record<string, string | number>): void;
97
97
  /**
98
- * Record a duration/timing metric in milliseconds.
99
- */
98
+ * Record a duration/timing metric in milliseconds.
99
+ */
100
100
  timing(name: string, duration: number, attributes?: Record<string, string | number>): void;
101
101
  /**
102
- * Set a gauge metric value.
103
- */
102
+ * Set a gauge metric value.
103
+ */
104
104
  gauge(name: string, value: number, attributes?: Record<string, string | number>): void;
105
105
  }
106
106
  export { Files, type Metrics, NoOpMetrics, OpenTelemetryMetrics, type SyncOptions, type SyncResult, type TransferOptions, type TransferResult, sync, transfer, waitForStorage };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{waitForStorage as o}from"./packem_shared/waitForStorage-ByQmG4xF.js";import{F as a}from"./packem_shared/disk-storage-CsQcYW3s.js";import{default as f}from"./packem_shared/DiskStorageWithChecksum-vFCubS6K.js";import{y as m}from"./packem_shared/local-meta-storage-iuJnu90B.js";import{default as i}from"./packem_shared/MemoryMetaStorage-Ksgh9pe7.js";import{default as x}from"./packem_shared/MemoryStorage-9gbWd09l.js";import{default as y}from"./packem_shared/MetaStorage-DPEUyWgN.js";import{B as g,d as F,a as M}from"./packem_shared/storage-0j5nCAUp.js";import{ERRORS as E,ErrorMap as c,UploadError as T,extractHttpStatus as C,isUploadError as R,mapStatusToErrorCode as k,throwErrorCode as B,wrapStorageError as b}from"./packem_shared/ERRORS-BIBxE2oR.js";import{createRetryWrapper as w,isRetryableError as N,retry as O}from"./packem_shared/createRetryWrapper-CxgiV_hH.js";import{fileTypeFromBlob as D,fileTypeFromBuffer as V,fileTypeFromTokenizer as W,supportedExtensions as z,supportedMimeTypes as A}from"file-type";import{default as L}from"./packem_shared/File-W8aOo15X.js";import{default as q}from"./packem_shared/NoOpMetrics-BLo6u4NY.js";import{default as G}from"./packem_shared/OpenTelemetryMetrics-DJDQsNKp.js";import{Files as J}from"./packem_shared/Files-CpIcMjP0.js";import{Metadata as P}from"./packem_shared/Metadata-B7CcBueg.js";import{UploadControl as X}from"./packem_shared/UploadControl-DZJhI9Wh.js";import{sync as Z,transfer as _}from"./packem_shared/sync-DhR3536K.js";export{g as AbstractBaseStorage,a as DiskStorage,f as DiskStorageWithChecksum,E as ERRORS,c as ErrorMap,L as File,J as Files,m as LocalMetaStorage,i as MemoryMetaStorage,x as MemoryStorage,y as MetaStorage,P as Metadata,q as NoOpMetrics,G as OpenTelemetryMetrics,X as UploadControl,T as UploadError,w as createRetryWrapper,F as defaultCloudStorageFileNameValidation,M as defaultFilesystemFileNameValidation,C as extractHttpStatus,D as fileTypeFromBlob,V as fileTypeFromBuffer,W as fileTypeFromTokenizer,N as isRetryableError,R as isUploadError,k as mapStatusToErrorCode,O as retry,z as supportedExtensions,A as supportedMimeTypes,Z as sync,B as throwErrorCode,_ as transfer,o as waitForStorage,b as wrapStorageError};
1
+ import{waitForStorage as o}from"./packem_shared/waitForStorage-ByQmG4xF.js";import{F as a}from"./packem_shared/disk-storage-BwPk2IRa.js";import{default as f}from"./packem_shared/DiskStorageWithChecksum-UnCtyEvs.js";import{y as m}from"./packem_shared/local-meta-storage-DJDcuxf1.js";import{default as i}from"./packem_shared/MemoryMetaStorage-Ksgh9pe7.js";import{default as x}from"./packem_shared/MemoryStorage-9gbWd09l.js";import{default as y}from"./packem_shared/MetaStorage-DPEUyWgN.js";import{B as g,d as F,a as M}from"./packem_shared/storage-0j5nCAUp.js";import{ERRORS as E,ErrorMap as c,UploadError as T,extractHttpStatus as C,isUploadError as R,mapStatusToErrorCode as k,throwErrorCode as B,wrapStorageError as b}from"./packem_shared/ERRORS-BIBxE2oR.js";import{createRetryWrapper as w,isRetryableError as N,retry as O}from"./packem_shared/createRetryWrapper-CxgiV_hH.js";import{fileTypeFromBlob as D,fileTypeFromBuffer as V,fileTypeFromTokenizer as W,supportedExtensions as z,supportedMimeTypes as A}from"file-type";import{default as L}from"./packem_shared/File-W8aOo15X.js";import{default as q}from"./packem_shared/NoOpMetrics-BLo6u4NY.js";import{default as G}from"./packem_shared/OpenTelemetryMetrics-DJDQsNKp.js";import{Files as J}from"./packem_shared/Files-CpIcMjP0.js";import{Metadata as P}from"./packem_shared/Metadata-B7CcBueg.js";import{UploadControl as X}from"./packem_shared/UploadControl-DZJhI9Wh.js";import{sync as Z,transfer as _}from"./packem_shared/sync-DhR3536K.js";export{g as AbstractBaseStorage,a as DiskStorage,f as DiskStorageWithChecksum,E as ERRORS,c as ErrorMap,L as File,J as Files,m as LocalMetaStorage,i as MemoryMetaStorage,x as MemoryStorage,y as MetaStorage,P as Metadata,q as NoOpMetrics,G as OpenTelemetryMetrics,X as UploadControl,T as UploadError,w as createRetryWrapper,F as defaultCloudStorageFileNameValidation,M as defaultFilesystemFileNameValidation,C as extractHttpStatus,D as fileTypeFromBlob,V as fileTypeFromBuffer,W as fileTypeFromTokenizer,N as isRetryableError,R as isUploadError,k as mapStatusToErrorCode,O as retry,z as supportedExtensions,A as supportedMimeTypes,Z as sync,B as throwErrorCode,_ as transfer,o as waitForStorage,b as wrapStorageError};
@@ -1 +1 @@
1
- import{Readable as u}from"node:stream";import{S as m}from"./s3-base-storage-BoTyhuzO.js";import{b as h,p as l}from"./aws-light-meta-storage-DGrn72VJ.js";import f from"./AwsLightFile-CpZrubaV.js";class b extends m{static name="aws-light";s3Api;constructor(e){const{bucket:t=process.env.S3_BUCKET||process.env.AWS_S3_BUCKET,region:r}=e;if(!t)throw new Error("S3 bucket is not defined");if(!r)throw new Error("S3 region is not defined");if(!e.accessKeyId)throw new Error("accessKeyId is required");if(!e.secretAccessKey)throw new Error("secretAccessKey is required");super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:n=>{const s=n;return s.statusCode&&[408,429,500,502,503,504].includes(s.statusCode)?!0:s.retryable??!1}}}),this.s3Api=new h({accessKeyId:e.accessKeyId,bucket:t,endpoint:e.endpoint,region:r,secretAccessKey:e.secretAccessKey,service:e.service,sessionToken:e.sessionToken});const{metaStorage:i,metaStorageConfig:a}=e;if(!i){const n={...e,...a,logger:this.logger};this.meta=new l(n)}}normalizeError(e){const t=e;return t.statusCode||t.code?{code:t.code||t.name,message:t.message,name:t.name,statusCode:t.statusCode||500}:super.normalizeError(e)}async update({id:e},t){if(this.config.clientDirectUpload){const r=await this.getMeta(e);return this.buildPresigned({...r,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const r=this.getS3Api(),{Body:i,ContentLength:a,ContentType:n,ETag:s,Expires:c,LastModified:g}=await this.runOperation(t,o=>r.getObject({Bucket:this.bucket,Key:e},{signal:o}));await this.checkIfExpired({expiredAt:c});const d=i instanceof ReadableStream?u.fromWeb(i):i,p=new u({read(){d.on("data",o=>{this.push(o)}),d.on("end",()=>{this.push(null)}),d.on("error",o=>{this.destroy(o)})}});return{headers:{"Content-Length":a?.toString()??"0","Content-Type":n,...s&&{ETag:s},...c&&{"X-Upload-Expires":c.toString()},...g&&{"Last-Modified":g.toString()}},size:Number(a),stream:p}})}get raw(){return this.s3Api.aws}getS3Api(){return this.s3Api}getFileClass(){return f}getAcl(){}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{b as default};
1
+ import{Readable as u}from"node:stream";import{S as m}from"./s3-base-storage-CMUui93V.js";import{b as h,p as l}from"./aws-light-meta-storage-DGrn72VJ.js";import f from"./AwsLightFile-CpZrubaV.js";class b extends m{static name="aws-light";s3Api;constructor(e){const{bucket:t=process.env.S3_BUCKET||process.env.AWS_S3_BUCKET,region:r}=e;if(!t)throw new Error("S3 bucket is not defined");if(!r)throw new Error("S3 region is not defined");if(!e.accessKeyId)throw new Error("accessKeyId is required");if(!e.secretAccessKey)throw new Error("secretAccessKey is required");super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:n=>{const s=n;return s.statusCode&&[408,429,500,502,503,504].includes(s.statusCode)?!0:s.retryable??!1}}}),this.s3Api=new h({accessKeyId:e.accessKeyId,bucket:t,endpoint:e.endpoint,region:r,secretAccessKey:e.secretAccessKey,service:e.service,sessionToken:e.sessionToken});const{metaStorage:i,metaStorageConfig:a}=e;if(!i){const n={...e,...a,logger:this.logger};this.meta=new l(n)}}normalizeError(e){const t=e;return t.statusCode||t.code?{code:t.code||t.name,message:t.message,name:t.name,statusCode:t.statusCode||500}:super.normalizeError(e)}async update({id:e},t){if(this.config.clientDirectUpload){const r=await this.getMeta(e);return this.buildPresigned({...r,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const r=this.getS3Api(),{Body:i,ContentLength:a,ContentType:n,ETag:s,Expires:c,LastModified:g}=await this.runOperation(t,o=>r.getObject({Bucket:this.bucket,Key:e},{signal:o}));await this.checkIfExpired({expiredAt:c});const d=i instanceof ReadableStream?u.fromWeb(i):i,p=new u({read(){d.on("data",o=>{this.push(o)}),d.on("end",()=>{this.push(null)}),d.on("error",o=>{this.destroy(o)})}});return{headers:{"Content-Length":a?.toString()??"0","Content-Type":n,...s&&{ETag:s},...c&&{"X-Upload-Expires":c.toString()},...g&&{"Last-Modified":g.toString()}},size:Number(a),stream:p}})}get raw(){return this.s3Api.aws}getS3Api(){return this.s3Api}getFileClass(){return f}getAcl(){}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{b as default};
@@ -1 +1 @@
1
- import{W as f}from"./path-0oTTdkvl-DvWvbDbh.js";import{d as b}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as u,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as C,c as w}from"./storage-0j5nCAUp.js";import{y as T}from"./local-meta-storage-iuJnu90B.js";import{a as O,c as S,b as m,d as y}from"./azure-meta-storage-ClbEsfI4.js";import k from"./AzureFile-DFSaVe25.js";import{i as E}from"./part-match-D-9dGX42.js";import{e as B}from"./has-content-50BsqrWw.js";import{t as F}from"./get-file-status-y3wTtDQs.js";class z extends C{static name="azure";checksumTypes=["md5"];get raw(){return this.client}meta;client;containerClient;root;resolvedRetryConfig;signer;sasToken;anonymous;constructor(t){if(super(t),!t.containerName)throw new Error("Missing required parameter: Azure container name.");const{anonymous:r,client:e,sasToken:n,signer:s}=O(t);this.client=e,this.signer=s,this.sasToken=n,this.anonymous=r,this.containerClient=this.client.getContainerClient(t.containerName),this.root=t.root?f(t.root).replace(/^\//,""):"";const o={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:i=>{const a=i;if(a.statusCode&&[408,429,500,502,503,504].includes(a.statusCode))return!0;if(i instanceof Error){const l=a.code;if(l==="ECONNRESET"||l==="ETIMEDOUT"||l==="ENOTFOUND"||l==="ECONNREFUSED")return!0}return!1},...t.retryConfig};if(this.resolvedRetryConfig=o,t.metaStorage)this.meta=t.metaStorage;else{let i={...t,...t.metaStorageConfig,logger:this.logger};if("directory"in i)this.logger?.debug("Using local meta storage"),this.meta=new T(i);else{const a=t.metaStorageConfig;a&&["accountKey","accountName","connectionString","credential","endpoint","sasToken"].some(l=>l in a)||(i={...i,client:this.client}),this.meta=new S(i)}}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}getRetryConfig(){return this.resolvedRetryConfig}async create(t,r){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const a=typeof t.ttl=="string"?w(t.ttl):t.ttl;a!==void 0&&(e.expiredAt=Date.now()+a)}const n=new k(e);n.name=this.namingFunction(n),await this.validate(n);try{const a=await this.getMeta(n.id);if(a.bytesWritten>=0)return a}catch{}const s=this.containerClient.getBlockBlobClient(this.getFullPath(n.name)),o={};for(const[a,l]of Object.entries(n.metadata||{}))o[a]=JSON.stringify(l);const i=await this.runOperation(r,a=>s.uploadData(Buffer.from(""),{abortSignal:a,blobHTTPHeaders:{blobContentType:n.contentType},metadata:{name:n.name,originalName:n.originalName,...o}}));return i.requestId===void 0?u(h.FILE_ERROR,"azure create upload error"):(n.requestId=i.requestId,n.uri=i._response.headers.get("location"),n.bytesWritten=0,await this.saveMeta(n),n.status="created",await this.onCreate(n),n)})}async delete({id:t},r){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await this.runOperation(r,s=>this.containerClient.getBlockBlobClient(this.getFullPath(e.name)).deleteIfExists({abortSignal:s})),await this.deleteMeta(e.id);const n={...e};return await this.onDelete(n),n})}async deleteBatch(t,r){if(t.length===0)return{failed:[],failedCount:0,successful:[],successfulCount:0};const e=256;try{const n=this.client.getBlobBatchClient(),s=[],o=[];for(let i=0;i<t.length;i+=e){const a=t.slice(i,i+e),l=a.map(c=>this.containerClient.getBlockBlobClient(this.getFullPath(c))),d=await this.runOperation(r,c=>n.deleteBlobs(l,{abortSignal:c}));for(const[c,p]of d.subResponses.entries()){const g=a[c];p.status===202||p.status===404?s.push({id:g,name:g,status:"deleted"}):o.push({error:p.errorCode??`HTTP ${p.status}`,id:g})}}return await Promise.all(s.map(async i=>{try{await this.deleteMeta(i.id),await this.onDelete(i)}catch{}})),{failed:o,failedCount:o.length,successful:s,successfulCount:s.length}}catch(n){return this.logger?.warn(`Azure Blob Batch delete unavailable, falling back to per-key delete: ${n instanceof Error?n.message:String(n)}`),super.deleteBatch(t,r)}}async move(t,r,e){return this.instrumentOperation("move",async()=>{const n=await this.copy(t,r,e),s=this.getFullPath(t);return await this.runOperation(e,o=>this.containerClient.getBlockBlobClient(s).deleteIfExists({abortSignal:o})),n})}async write(t,r){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(!E(t,e))return u(h.FILE_CONFLICT);const n=await this.lock(t.id);try{if(B(t)){if((e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:a,stream:l}=await b(t.body);a?.mime&&(e.contentType=a.mime),t.body=l}catch{}const s=this.containerClient.getBlockBlobClient(this.getFullPath(e.name)),o=new AbortController;t.body.on("error",()=>{o.abort()});const i=await this.runOperation(r,a=>{const l=a?AbortSignal.any([o.signal,a]):o.signal;return s.uploadStream(t.body,void 0,void 0,{abortSignal:l,blobHTTPHeaders:{blobContentType:e.contentType??"application/octet-stream"},metadata:e.metadata})},{replayable:!1});if(i.requestId===void 0)return u(h.FILE_ERROR,"azure write upload error");e.requestId=i.requestId,e.bytesWritten+=t.contentLength||0,e.status=F(e),e.status==="completed"&&(e.uri=i._response.headers.get("location"),await this.deleteMeta(e.id))}}finally{await this.unlock(t.id,n)}return e})}async get({id:t},r){return this.instrumentOperation("get",async()=>{const e=this.containerClient.getBlockBlobClient(this.getFullPath(t));if(!await this.runOperation(r,c=>e.exists({abortSignal:c})))try{return await this.getMeta(t),u(h.GONE)}catch{return u(h.FILE_NOT_FOUND)}const n=await this.runOperation(r,c=>e.getProperties({abortSignal:c})),{contentLength:s,contentType:o,etag:i,expiresOn:a,lastModified:l,metadata:d}=n;return{content:await this.runOperation(r,c=>e.downloadToBuffer(0,void 0,{abortSignal:c})),contentType:o,ETag:i,expiredAt:a,id:t,metadata:d||{},modifiedAt:l,name:d?.name||t,originalName:d?.originalName||"",size:s}})}async exists({id:t},r){return this.instrumentOperation("exists",async()=>{try{await this.getMeta(t);const e=this.containerClient.getBlockBlobClient(this.getFullPath(t));return await this.runOperation(r,n=>e.exists({abortSignal:n}))}catch{return!1}})}async copy(t,r,e){return this.instrumentOperation("copy",async()=>{const n=this.containerClient.getBlockBlobClient(this.getFullPath(t));if(!await this.runOperation(e,a=>n.exists({abortSignal:a})))try{return await this.getMeta(t),u(h.GONE)}catch{return u(h.FILE_NOT_FOUND)}const s=this.containerClient.getBlockBlobClient(this.getFullPath(r));let o=n.url;this.signer?.kind==="userDelegation"?o=await m(this.containerClient.getBlobClient(this.getFullPath(t)),this.signer,{expiresIn:300,permissions:"r"}):this.sasToken&&(o=y(n.url,this.sasToken));const i=await this.runOperation(e,a=>s.beginCopyFromURL(o,{abortSignal:a}));return await this.runOperation(e,()=>i.pollUntilDone()),{...await this.getMeta(t),id:r,name:r}})}async list(t=1e3,r){return this.instrumentOperation("list",async()=>{const e=[];let n=!0,s;for(;n&&e.length<t;)try{const o=Math.min(t-e.length,1e3),i=(await this.runOperation(r,a=>this.containerClient.listBlobsFlat({abortSignal:a,includeMetadata:!0,prefix:this.root}).byPage({continuationToken:s,maxPageSize:o}).next())).value;if(i!==void 0&&"segment"in i){for(const a of i.segment.blobItems)if(!a.deleted&&(e.push({createdAt:a.properties.createdOn,id:a.name,modifiedAt:a.properties.lastModified}),e.length>=t))break}n=i?.continuationToken!==void 0,n&&(s=i.continuationToken)}catch(o){const i=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(i),o}return e},{limit:t})}async getReadUrl(t,r){const e=this.containerClient.getBlobClient(this.getFullPath(t));return this.signer?m(e,this.signer,{expiresIn:r?.expiresIn??3600,permissions:"r",...r?.responseContentDisposition&&{contentDisposition:r.responseContentDisposition},...r?.responseContentType&&{contentType:r.responseContentType}}):r?.responseContentDisposition!==void 0||r?.responseContentType!==void 0?u(h.BAD_REQUEST,"azure: `responseContentDisposition`/`responseContentType` require a freshly minted SAS (construct with a shared key or Microsoft Entra credential). A pre-issued `sasToken` or anonymous public-container URL has no signature in which to bind the override, so it cannot be enforced."):this.sasToken?y(e.url,this.sasToken):this.anonymous?e.url:u(h.METHOD_NOT_ALLOWED,"azure: cannot produce a read URL without a shared key, Microsoft Entra credential, or SAS token. Construct the adapter with accountKey + accountName, a connectionString containing an account key, a credential + accountName, or a sasToken.")}async getUploadUrl(t,r){if(r?.contentType!==void 0||r?.contentLength!==void 0)return u(h.BAD_REQUEST,"azure: `contentType`/`contentLength` are not supported for upload URLs. An Azure SAS does not bind the request Content-Type into the signature and cannot enforce a size limit; validate both at your application gateway/proxy before issuing the SAS, or omit them and accept the unbounded PUT.");const e=this.containerClient.getBlobClient(this.getFullPath(t));return this.signer?m(e,this.signer,{expiresIn:r?.expiresIn??3600,permissions:"cw"}):this.sasToken?y(e.url,this.sasToken):u(h.METHOD_NOT_ALLOWED,"azure: cannot produce an upload URL without a shared key, Microsoft Entra credential, or SAS token. Anonymous (public-container) access is read-only.")}getFullPath(t){return this.assetFolder!==void 0?`${this.assetFolder}/${t}`:t}async accessCheck(){await this.runOperation(void 0,t=>this.containerClient.getProperties({abortSignal:t}))}}export{z as default};
1
+ import{W as f}from"./path-0oTTdkvl-DvWvbDbh.js";import{d as b}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as u,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as C,c as w}from"./storage-0j5nCAUp.js";import{y as T}from"./local-meta-storage-DJDcuxf1.js";import{a as O,c as S,b as m,d as y}from"./azure-meta-storage-ClbEsfI4.js";import k from"./AzureFile-DFSaVe25.js";import{i as E}from"./part-match-D-9dGX42.js";import{e as B}from"./has-content-50BsqrWw.js";import{t as F}from"./get-file-status-y3wTtDQs.js";class z extends C{static name="azure";checksumTypes=["md5"];get raw(){return this.client}meta;client;containerClient;root;resolvedRetryConfig;signer;sasToken;anonymous;constructor(t){if(super(t),!t.containerName)throw new Error("Missing required parameter: Azure container name.");const{anonymous:r,client:e,sasToken:n,signer:s}=O(t);this.client=e,this.signer=s,this.sasToken=n,this.anonymous=r,this.containerClient=this.client.getContainerClient(t.containerName),this.root=t.root?f(t.root).replace(/^\//,""):"";const o={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:i=>{const a=i;if(a.statusCode&&[408,429,500,502,503,504].includes(a.statusCode))return!0;if(i instanceof Error){const l=a.code;if(l==="ECONNRESET"||l==="ETIMEDOUT"||l==="ENOTFOUND"||l==="ECONNREFUSED")return!0}return!1},...t.retryConfig};if(this.resolvedRetryConfig=o,t.metaStorage)this.meta=t.metaStorage;else{let i={...t,...t.metaStorageConfig,logger:this.logger};if("directory"in i)this.logger?.debug("Using local meta storage"),this.meta=new T(i);else{const a=t.metaStorageConfig;a&&["accountKey","accountName","connectionString","credential","endpoint","sasToken"].some(l=>l in a)||(i={...i,client:this.client}),this.meta=new S(i)}}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}getRetryConfig(){return this.resolvedRetryConfig}async create(t,r){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const a=typeof t.ttl=="string"?w(t.ttl):t.ttl;a!==void 0&&(e.expiredAt=Date.now()+a)}const n=new k(e);n.name=this.namingFunction(n),await this.validate(n);try{const a=await this.getMeta(n.id);if(a.bytesWritten>=0)return a}catch{}const s=this.containerClient.getBlockBlobClient(this.getFullPath(n.name)),o={};for(const[a,l]of Object.entries(n.metadata||{}))o[a]=JSON.stringify(l);const i=await this.runOperation(r,a=>s.uploadData(Buffer.from(""),{abortSignal:a,blobHTTPHeaders:{blobContentType:n.contentType},metadata:{name:n.name,originalName:n.originalName,...o}}));return i.requestId===void 0?u(h.FILE_ERROR,"azure create upload error"):(n.requestId=i.requestId,n.uri=i._response.headers.get("location"),n.bytesWritten=0,await this.saveMeta(n),n.status="created",await this.onCreate(n),n)})}async delete({id:t},r){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await this.runOperation(r,s=>this.containerClient.getBlockBlobClient(this.getFullPath(e.name)).deleteIfExists({abortSignal:s})),await this.deleteMeta(e.id);const n={...e};return await this.onDelete(n),n})}async deleteBatch(t,r){if(t.length===0)return{failed:[],failedCount:0,successful:[],successfulCount:0};const e=256;try{const n=this.client.getBlobBatchClient(),s=[],o=[];for(let i=0;i<t.length;i+=e){const a=t.slice(i,i+e),l=a.map(c=>this.containerClient.getBlockBlobClient(this.getFullPath(c))),d=await this.runOperation(r,c=>n.deleteBlobs(l,{abortSignal:c}));for(const[c,p]of d.subResponses.entries()){const g=a[c];p.status===202||p.status===404?s.push({id:g,name:g,status:"deleted"}):o.push({error:p.errorCode??`HTTP ${p.status}`,id:g})}}return await Promise.all(s.map(async i=>{try{await this.deleteMeta(i.id),await this.onDelete(i)}catch{}})),{failed:o,failedCount:o.length,successful:s,successfulCount:s.length}}catch(n){return this.logger?.warn(`Azure Blob Batch delete unavailable, falling back to per-key delete: ${n instanceof Error?n.message:String(n)}`),super.deleteBatch(t,r)}}async move(t,r,e){return this.instrumentOperation("move",async()=>{const n=await this.copy(t,r,e),s=this.getFullPath(t);return await this.runOperation(e,o=>this.containerClient.getBlockBlobClient(s).deleteIfExists({abortSignal:o})),n})}async write(t,r){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(!E(t,e))return u(h.FILE_CONFLICT);const n=await this.lock(t.id);try{if(B(t)){if((e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:a,stream:l}=await b(t.body);a?.mime&&(e.contentType=a.mime),t.body=l}catch{}const s=this.containerClient.getBlockBlobClient(this.getFullPath(e.name)),o=new AbortController;t.body.on("error",()=>{o.abort()});const i=await this.runOperation(r,a=>{const l=a?AbortSignal.any([o.signal,a]):o.signal;return s.uploadStream(t.body,void 0,void 0,{abortSignal:l,blobHTTPHeaders:{blobContentType:e.contentType??"application/octet-stream"},metadata:e.metadata})},{replayable:!1});if(i.requestId===void 0)return u(h.FILE_ERROR,"azure write upload error");e.requestId=i.requestId,e.bytesWritten+=t.contentLength||0,e.status=F(e),e.status==="completed"&&(e.uri=i._response.headers.get("location"),await this.deleteMeta(e.id))}}finally{await this.unlock(t.id,n)}return e})}async get({id:t},r){return this.instrumentOperation("get",async()=>{const e=this.containerClient.getBlockBlobClient(this.getFullPath(t));if(!await this.runOperation(r,c=>e.exists({abortSignal:c})))try{return await this.getMeta(t),u(h.GONE)}catch{return u(h.FILE_NOT_FOUND)}const n=await this.runOperation(r,c=>e.getProperties({abortSignal:c})),{contentLength:s,contentType:o,etag:i,expiresOn:a,lastModified:l,metadata:d}=n;return{content:await this.runOperation(r,c=>e.downloadToBuffer(0,void 0,{abortSignal:c})),contentType:o,ETag:i,expiredAt:a,id:t,metadata:d||{},modifiedAt:l,name:d?.name||t,originalName:d?.originalName||"",size:s}})}async exists({id:t},r){return this.instrumentOperation("exists",async()=>{try{await this.getMeta(t);const e=this.containerClient.getBlockBlobClient(this.getFullPath(t));return await this.runOperation(r,n=>e.exists({abortSignal:n}))}catch{return!1}})}async copy(t,r,e){return this.instrumentOperation("copy",async()=>{const n=this.containerClient.getBlockBlobClient(this.getFullPath(t));if(!await this.runOperation(e,a=>n.exists({abortSignal:a})))try{return await this.getMeta(t),u(h.GONE)}catch{return u(h.FILE_NOT_FOUND)}const s=this.containerClient.getBlockBlobClient(this.getFullPath(r));let o=n.url;this.signer?.kind==="userDelegation"?o=await m(this.containerClient.getBlobClient(this.getFullPath(t)),this.signer,{expiresIn:300,permissions:"r"}):this.sasToken&&(o=y(n.url,this.sasToken));const i=await this.runOperation(e,a=>s.beginCopyFromURL(o,{abortSignal:a}));return await this.runOperation(e,()=>i.pollUntilDone()),{...await this.getMeta(t),id:r,name:r}})}async list(t=1e3,r){return this.instrumentOperation("list",async()=>{const e=[];let n=!0,s;for(;n&&e.length<t;)try{const o=Math.min(t-e.length,1e3),i=(await this.runOperation(r,a=>this.containerClient.listBlobsFlat({abortSignal:a,includeMetadata:!0,prefix:this.root}).byPage({continuationToken:s,maxPageSize:o}).next())).value;if(i!==void 0&&"segment"in i){for(const a of i.segment.blobItems)if(!a.deleted&&(e.push({createdAt:a.properties.createdOn,id:a.name,modifiedAt:a.properties.lastModified}),e.length>=t))break}n=i?.continuationToken!==void 0,n&&(s=i.continuationToken)}catch(o){const i=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(i),o}return e},{limit:t})}async getReadUrl(t,r){const e=this.containerClient.getBlobClient(this.getFullPath(t));return this.signer?m(e,this.signer,{expiresIn:r?.expiresIn??3600,permissions:"r",...r?.responseContentDisposition&&{contentDisposition:r.responseContentDisposition},...r?.responseContentType&&{contentType:r.responseContentType}}):r?.responseContentDisposition!==void 0||r?.responseContentType!==void 0?u(h.BAD_REQUEST,"azure: `responseContentDisposition`/`responseContentType` require a freshly minted SAS (construct with a shared key or Microsoft Entra credential). A pre-issued `sasToken` or anonymous public-container URL has no signature in which to bind the override, so it cannot be enforced."):this.sasToken?y(e.url,this.sasToken):this.anonymous?e.url:u(h.METHOD_NOT_ALLOWED,"azure: cannot produce a read URL without a shared key, Microsoft Entra credential, or SAS token. Construct the adapter with accountKey + accountName, a connectionString containing an account key, a credential + accountName, or a sasToken.")}async getUploadUrl(t,r){if(r?.contentType!==void 0||r?.contentLength!==void 0)return u(h.BAD_REQUEST,"azure: `contentType`/`contentLength` are not supported for upload URLs. An Azure SAS does not bind the request Content-Type into the signature and cannot enforce a size limit; validate both at your application gateway/proxy before issuing the SAS, or omit them and accept the unbounded PUT.");const e=this.containerClient.getBlobClient(this.getFullPath(t));return this.signer?m(e,this.signer,{expiresIn:r?.expiresIn??3600,permissions:"cw"}):this.sasToken?y(e.url,this.sasToken):u(h.METHOD_NOT_ALLOWED,"azure: cannot produce an upload URL without a shared key, Microsoft Entra credential, or SAS token. Anonymous (public-container) access is read-only.")}getFullPath(t){return this.assetFolder!==void 0?`${this.assetFolder}/${t}`:t}async accessCheck(){await this.runOperation(void 0,t=>this.containerClient.getProperties({abortSignal:t}))}}export{z as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{Readable as x}from"node:stream";import{BoxDeveloperTokenAuth as I,BoxClient as u,OAuthConfig as E,BoxOAuth as O,CcgConfig as T,BoxCcgAuth as b,BoxJwtAuth as U,JwtConfig as F}from"box-typescript-sdk-gen";import{throwErrorCode as C,ERRORS as B}from"./ERRORS-BIBxE2oR.js";import{B as L}from"./storage-0j5nCAUp.js";import p from"./BoxFile-CseIoPW1.js";import S from"./BoxMetaStorage-BSn6Qfnf.js";import{t as v}from"./get-file-status-y3wTtDQs.js";import{t as D}from"./update-size-DuNuLyxj.js";import{i as H}from"./part-match-D-9dGX42.js";import{e as R}from"./has-content-50BsqrWw.js";const _="0",A=50*1024*1024,w={ensureReady:()=>Promise.resolve()},M=a=>{let e=0,i=a.length;for(;e<i&&a[e]==="/";)e+=1;for(;i>e&&a[i-1]==="/";)i-=1;return e===0&&i===a.length?a:a.slice(e,i)},m=a=>{const e=M(a);if(!e)throw new Error("Box: key must not be empty");const i=e.split("/").filter(r=>r.length>0),t=i.pop()??"";if(!t)throw new Error(`Box: key "${a}" has no file name segment`);return{leaf:t,parents:i}},N=async a=>{const e=[];for await(const i of a)e.push(Buffer.from(i));return Buffer.concat(e)},g=a=>x.from(a),j=a=>"configJsonString"in a?F.fromConfigJsonString(a.configJsonString):F.fromConfigFile(a.configFilePath),z=a=>[a.developerToken,a.oauth,a.ccg,a.jwt].filter(e=>e!==void 0).length,P=a=>{if(a.client)return{authHandle:w,client:a.client};if(z(a)>1)throw new Error("Box storage: pass exactly one of `developerToken`, `oauth`, `ccg`, or `jwt`.");if(a.developerToken!==void 0){const i=new I({token:a.developerToken});return{authHandle:w,client:new u({auth:i})}}if(a.oauth){const{clientId:i,clientSecret:t,refreshToken:r}=a.oauth,s=new E({clientId:i,clientSecret:t}),n=new O({config:s});let l;const o=async()=>{await n.tokenStorage.store({accessToken:"",refreshToken:r})};return{authHandle:{ensureReady:()=>(l||(l=o()),l)},client:new u({auth:n})}}if(a.ccg){const{clientId:i,clientSecret:t,enterpriseId:r,userId:s}=a.ccg;if(!r&&!s)throw new Error("Box storage: `ccg` auth requires either `enterpriseId` or `userId`.");const n=new T({clientId:i,clientSecret:t,...r!==void 0&&{enterpriseId:r},...s!==void 0&&{userId:s}}),l=new b({config:n});return{authHandle:w,client:new u({auth:l})}}if(a.jwt){const i=j(a.jwt),t=new U({config:i});return{authHandle:w,client:new u({auth:t})}}const e=process.env.BOX_DEVELOPER_TOKEN;if(e){const i=new I({token:e});return{authHandle:w,client:new u({auth:i})}}throw new Error("Box storage: missing auth. Pass `client`, `developerToken`, `oauth`, `ccg`, or `jwt`. Env fallback: BOX_DEVELOPER_TOKEN.")},J=a=>{if(a&&typeof a=="object"){const e=a,i=e.responseInfo?.code??e.responseInfo?.body?.code;return e.responseInfo?.statusCode===404||i==="not_found"||i==="file_not_found"||i==="folder_not_found"||i==="trashed"}return!1},k=a=>{if(a&&typeof a=="object"){const e=a,i=e.responseInfo?.code??e.responseInfo?.body?.code;return e.responseInfo?.statusCode===409||i==="item_name_in_use"||i==="conflict"}return!1};class ee extends L{static name="box";checksumTypes=[];meta;authHandle;client;fileIdCache;folderIdCache;publicByDefault;rootFolderId;constructor(e){super(e),this.rootFolderId=e.rootFolderId??_,this.publicByDefault=e.publicByDefault??!1;const i=P(e);this.client=i.client,this.authHandle=i.authHandle,this.folderIdCache=new Map,this.fileIdCache=new Map,this.meta=e.metaStorage??new S(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new p(e);t.name=this.namingFunction(t),await this.validate(t);try{const r=await this.getMeta(t.id);if(r.bytesWritten>=0)return r}catch{}return t.bytesWritten=0,t.status=v(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&D(t,e.size),!H(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(R(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");await this.authHandle.ensureReady();const s=await N(e.body),n=t.name||t.id,{leaf:l,parents:o}=m(n),d=await this.resolveFolderId(o,{create:!0},i),c=await this.resolveExistingFileForUpload(n,d,l,i),h=await this.performUpload(c,d,l,s,i);h.id&&(this.fileIdCache.set(n,h.id),this.publicByDefault&&await this.ensureSharedLink(h.id,i)),t.bytesWritten=s.length,t.size=s.length,t.boxFileId=h.id,t.eTag=h.etag??void 0,t.ETag=h.etag??void 0}return t.status=v(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const r=t?.name??e;await this.authHandle.ensureReady();try{const s=t?.boxFileId??await this.resolveFileId(r,i);await this.runOperation(i,()=>this.client.files.deleteFileById(s)),this.fileIdCache.delete(r)}catch(s){if(!J(s))throw s}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new p({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,status:"deleted"})})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,r=e;try{t=await this.checkIfExpired(await this.getMeta(e)),r=t.name??e}catch{}await this.authHandle.ensureReady();const s=t?.boxFileId??await this.resolveFileId(r,i),n=await this.runOperation(i,()=>this.client.files.getFileById(s)),l=await this.runOperation(i,()=>this.client.downloads.getDownloadFileUrl(s)),o=await this.runOperation(i,()=>fetch(l));if(!o.ok)throw new Error(`Box: download fetch failed (${o.status})`);const d=await this.runOperation(i,()=>o.arrayBuffer()),c=Buffer.from(d);return{content:c,contentType:t?.contentType??"application/octet-stream",ETag:t?.ETag??n.etag??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??n.modifiedAt??n.contentModifiedAt??void 0,name:t?.name??n.name??r,originalName:t?.originalName??n.name??r,size:t?.size??n.size??c.length}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{await this.authHandle.ensureReady();const r=await this.resolveFileId(e,t),{leaf:s,parents:n}=m(i),l=await this.resolveFolderId(n,{create:!0},t),o=await this.runOperation(t,()=>this.client.files.copyFile(r,{name:s,parent:{id:l}}));o.id&&this.fileIdCache.set(i,o.id);const d=new p({contentType:"application/octet-stream",metadata:{},originalName:i});return d.id=i,d.name=i,d.boxFileId=o.id,d.eTag=o.etag??void 0,d.ETag=o.etag??void 0,d})}async move(e,i,t){return this.instrumentOperation("move",async()=>{await this.authHandle.ensureReady();const r=await this.resolveFileId(e,t),{leaf:s,parents:n}=m(i),l=await this.resolveFolderId(n,{create:!0},t),o=await this.runOperation(t,()=>this.client.files.updateFileById(r,{requestBody:{name:s,parent:{id:l}}}));this.fileIdCache.delete(e),o.id&&this.fileIdCache.set(i,o.id);const d=new p({contentType:"application/octet-stream",metadata:{},originalName:i});d.id=i,d.name=i,d.boxFileId=o.id,d.eTag=o.etag??void 0,d.ETag=o.etag??void 0;try{await this.deleteMeta(e)}catch{}return d})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{await this.authHandle.ensureReady();const t=[];let r=0;const s=Math.min(e,1e3);for(;t.length<e;){const n=(await this.runOperation(i,()=>this.client.folders.getFolderItems(this.rootFolderId,{queryParams:{fields:["id","name","size","modified_at","etag","type"],limit:s,offset:r}}))).entries??[];for(const l of n){const o=l;if(o.type!=="file"||!o.id||!o.name)continue;this.fileIdCache.set(o.name,o.id);const d=new p({contentType:"application/octet-stream",metadata:{},originalName:o.name});if(d.id=o.name,d.name=o.name,d.boxFileId=o.id,d.eTag=o.etag??void 0,d.ETag=o.etag??void 0,d.size=o.size??0,d.modifiedAt=o.modifiedAt??o.contentModifiedAt??void 0,t.push(d),t.length>=e)break}if(n.length<s)break;r+=n.length}return t},{limit:e})}async getReadUrl(e,i){if(i?.responseContentDisposition||i?.responseContentType)return C(B.METHOD_NOT_ALLOWED,"Box: `responseContentDisposition` / `responseContentType` are not supported — Box download URLs and shared-link URLs have no overrides.");await this.authHandle.ensureReady();const t=await this.resolveFileId(e);return this.publicByDefault?this.ensureSharedLink(t):this.client.downloads.getDownloadFileUrl(t)}async getUploadUrl(e,i){return C(B.METHOD_NOT_ALLOWED,"Box: `getUploadUrl` is not supported. Box uploads require a multipart POST with an `attributes` JSON part and a file bytes part; this doesn't fit the PUT-style upload-url contract. Use `write()` server-side, or the Box UI Elements / Box Content Uploader for browser flows.")}async findChildByName(e,i,t){let r=0;const s=1e3;for(;;){const n=(await this.runOperation(t,()=>this.client.folders.getFolderItems(e,{queryParams:{fields:["id","name","type"],limit:s,offset:r}}))).entries??[];for(const l of n){const o=l;if(o.name===i&&o.id&&o.type)return{id:o.id,type:o.type}}if(n.length<s)return;r+=n.length}}folderCacheKey(e){return e.join("/")}async resolveFolderId(e,i,t){if(e.length===0)return this.rootFolderId;const r=this.folderCacheKey(e),s=this.folderIdCache.get(r);if(s)return s;let n=this.rootFolderId;const l=[];for(const o of e){l.push(o);const d=this.folderCacheKey(l),c=this.folderIdCache.get(d);if(c){n=c;continue}const h=await this.findChildByName(n,o,t);if(h&&h.type==="folder"){n=h.id,this.folderIdCache.set(d,n);continue}if(h&&h.type!=="folder")throw new Error(`Box: path segment "${o}" exists but is not a folder`);if(!i.create)throw new Error(`Box: folder "${l.join("/")}" not found`);try{const f=await this.runOperation(t,()=>this.client.folders.createFolder({name:o,parent:{id:n}}));if(!f.id)throw new Error(`Box: createFolder did not return an id for "${o}"`);n=f.id,this.folderIdCache.set(d,n)}catch(f){if(k(f)){const y=await this.findChildByName(n,o,t);if(y&&y.type==="folder"){n=y.id,this.folderIdCache.set(d,n);continue}}throw f}}return this.folderIdCache.set(r,n),n}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const{leaf:r,parents:s}=m(e),n=await this.resolveFolderId(s,{create:!1},i),l=await this.findChildByName(n,r,i);if(!l||l.type!=="file")throw new Error(`Box: file "${e}" not found`);return this.fileIdCache.set(e,l.id),l.id}async resolveExistingFileForUpload(e,i,t,r){const s=this.fileIdCache.get(e);if(s)return s;const n=await this.findChildByName(i,t,r);if(n){if(n.type==="file")return this.fileIdCache.set(e,n.id),n.id;throw new Error(`Box: "${e}" already exists as a non-file (${n.type})`)}}async performUpload(e,i,t,r,s){if(r.byteLength>A)return await this.runOperation(s,()=>this.client.chunkedUploads.uploadBigFile(g(r),t,r.byteLength,i));if(e){const l=((await this.runOperation(s,()=>this.client.uploads.uploadFileVersion(e,{attributes:{name:t},file:g(r)}))).entries??[])[0];if(!l)throw new Error("Box: uploadFileVersion returned no file");return l}const n=((await this.runOperation(s,()=>this.client.uploads.uploadFile({attributes:{name:t,parent:{id:i}},file:g(r)}))).entries??[])[0];if(!n)throw new Error("Box: uploadFile returned no file");return n}async ensureSharedLink(e,i){try{const t=(await this.runOperation(i,()=>this.client.sharedLinksFiles.addShareLinkToFile(e,{sharedLink:{access:"open"}},{fields:"shared_link"}))).sharedLink;return(t?.downloadUrl??t?.url)||this.fetchSharedLinkUrl(e,i)}catch(t){if(k(t))return this.fetchSharedLinkUrl(e,i);throw t}}async fetchSharedLinkUrl(e,i){const t=(await this.runOperation(i,()=>this.client.sharedLinksFiles.getSharedLinkForFile(e,{fields:"shared_link"}))).sharedLink,r=t?.downloadUrl??t?.url;if(!r)throw new Error("Box: file has no shared link. Call write() with publicByDefault: true, or addShareLinkToFile via storage.raw.");return r}internalOnComplete=e=>this.deleteMeta(e.id)}export{ee as default};
1
+ import{Readable as x}from"node:stream";import{BoxDeveloperTokenAuth as I,BoxClient as u,OAuthConfig as E,BoxOAuth as O,CcgConfig as T,BoxCcgAuth as b,BoxJwtAuth as U,JwtConfig as F}from"box-typescript-sdk-gen";import{throwErrorCode as C,ERRORS as B}from"./ERRORS-BIBxE2oR.js";import{B as L}from"./storage-0j5nCAUp.js";import p from"./BoxFile-CseIoPW1.js";import S from"./BoxMetaStorage-CHWrhgg2.js";import{t as v}from"./get-file-status-y3wTtDQs.js";import{t as D}from"./update-size-DuNuLyxj.js";import{i as H}from"./part-match-D-9dGX42.js";import{e as R}from"./has-content-50BsqrWw.js";const _="0",A=50*1024*1024,w={ensureReady:()=>Promise.resolve()},M=a=>{let e=0,i=a.length;for(;e<i&&a[e]==="/";)e+=1;for(;i>e&&a[i-1]==="/";)i-=1;return e===0&&i===a.length?a:a.slice(e,i)},m=a=>{const e=M(a);if(!e)throw new Error("Box: key must not be empty");const i=e.split("/").filter(r=>r.length>0),t=i.pop()??"";if(!t)throw new Error(`Box: key "${a}" has no file name segment`);return{leaf:t,parents:i}},N=async a=>{const e=[];for await(const i of a)e.push(Buffer.from(i));return Buffer.concat(e)},g=a=>x.from(a),j=a=>"configJsonString"in a?F.fromConfigJsonString(a.configJsonString):F.fromConfigFile(a.configFilePath),z=a=>[a.developerToken,a.oauth,a.ccg,a.jwt].filter(e=>e!==void 0).length,P=a=>{if(a.client)return{authHandle:w,client:a.client};if(z(a)>1)throw new Error("Box storage: pass exactly one of `developerToken`, `oauth`, `ccg`, or `jwt`.");if(a.developerToken!==void 0){const i=new I({token:a.developerToken});return{authHandle:w,client:new u({auth:i})}}if(a.oauth){const{clientId:i,clientSecret:t,refreshToken:r}=a.oauth,s=new E({clientId:i,clientSecret:t}),n=new O({config:s});let l;const o=async()=>{await n.tokenStorage.store({accessToken:"",refreshToken:r})};return{authHandle:{ensureReady:()=>(l||(l=o()),l)},client:new u({auth:n})}}if(a.ccg){const{clientId:i,clientSecret:t,enterpriseId:r,userId:s}=a.ccg;if(!r&&!s)throw new Error("Box storage: `ccg` auth requires either `enterpriseId` or `userId`.");const n=new T({clientId:i,clientSecret:t,...r!==void 0&&{enterpriseId:r},...s!==void 0&&{userId:s}}),l=new b({config:n});return{authHandle:w,client:new u({auth:l})}}if(a.jwt){const i=j(a.jwt),t=new U({config:i});return{authHandle:w,client:new u({auth:t})}}const e=process.env.BOX_DEVELOPER_TOKEN;if(e){const i=new I({token:e});return{authHandle:w,client:new u({auth:i})}}throw new Error("Box storage: missing auth. Pass `client`, `developerToken`, `oauth`, `ccg`, or `jwt`. Env fallback: BOX_DEVELOPER_TOKEN.")},J=a=>{if(a&&typeof a=="object"){const e=a,i=e.responseInfo?.code??e.responseInfo?.body?.code;return e.responseInfo?.statusCode===404||i==="not_found"||i==="file_not_found"||i==="folder_not_found"||i==="trashed"}return!1},k=a=>{if(a&&typeof a=="object"){const e=a,i=e.responseInfo?.code??e.responseInfo?.body?.code;return e.responseInfo?.statusCode===409||i==="item_name_in_use"||i==="conflict"}return!1};class ee extends L{static name="box";checksumTypes=[];meta;authHandle;client;fileIdCache;folderIdCache;publicByDefault;rootFolderId;constructor(e){super(e),this.rootFolderId=e.rootFolderId??_,this.publicByDefault=e.publicByDefault??!1;const i=P(e);this.client=i.client,this.authHandle=i.authHandle,this.folderIdCache=new Map,this.fileIdCache=new Map,this.meta=e.metaStorage??new S(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new p(e);t.name=this.namingFunction(t),await this.validate(t);try{const r=await this.getMeta(t.id);if(r.bytesWritten>=0)return r}catch{}return t.bytesWritten=0,t.status=v(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&D(t,e.size),!H(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(R(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");await this.authHandle.ensureReady();const s=await N(e.body),n=t.name||t.id,{leaf:l,parents:o}=m(n),d=await this.resolveFolderId(o,{create:!0},i),c=await this.resolveExistingFileForUpload(n,d,l,i),h=await this.performUpload(c,d,l,s,i);h.id&&(this.fileIdCache.set(n,h.id),this.publicByDefault&&await this.ensureSharedLink(h.id,i)),t.bytesWritten=s.length,t.size=s.length,t.boxFileId=h.id,t.eTag=h.etag??void 0,t.ETag=h.etag??void 0}return t.status=v(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const r=t?.name??e;await this.authHandle.ensureReady();try{const s=t?.boxFileId??await this.resolveFileId(r,i);await this.runOperation(i,()=>this.client.files.deleteFileById(s)),this.fileIdCache.delete(r)}catch(s){if(!J(s))throw s}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new p({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,status:"deleted"})})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,r=e;try{t=await this.checkIfExpired(await this.getMeta(e)),r=t.name??e}catch{}await this.authHandle.ensureReady();const s=t?.boxFileId??await this.resolveFileId(r,i),n=await this.runOperation(i,()=>this.client.files.getFileById(s)),l=await this.runOperation(i,()=>this.client.downloads.getDownloadFileUrl(s)),o=await this.runOperation(i,()=>fetch(l));if(!o.ok)throw new Error(`Box: download fetch failed (${o.status})`);const d=await this.runOperation(i,()=>o.arrayBuffer()),c=Buffer.from(d);return{content:c,contentType:t?.contentType??"application/octet-stream",ETag:t?.ETag??n.etag??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??n.modifiedAt??n.contentModifiedAt??void 0,name:t?.name??n.name??r,originalName:t?.originalName??n.name??r,size:t?.size??n.size??c.length}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{await this.authHandle.ensureReady();const r=await this.resolveFileId(e,t),{leaf:s,parents:n}=m(i),l=await this.resolveFolderId(n,{create:!0},t),o=await this.runOperation(t,()=>this.client.files.copyFile(r,{name:s,parent:{id:l}}));o.id&&this.fileIdCache.set(i,o.id);const d=new p({contentType:"application/octet-stream",metadata:{},originalName:i});return d.id=i,d.name=i,d.boxFileId=o.id,d.eTag=o.etag??void 0,d.ETag=o.etag??void 0,d})}async move(e,i,t){return this.instrumentOperation("move",async()=>{await this.authHandle.ensureReady();const r=await this.resolveFileId(e,t),{leaf:s,parents:n}=m(i),l=await this.resolveFolderId(n,{create:!0},t),o=await this.runOperation(t,()=>this.client.files.updateFileById(r,{requestBody:{name:s,parent:{id:l}}}));this.fileIdCache.delete(e),o.id&&this.fileIdCache.set(i,o.id);const d=new p({contentType:"application/octet-stream",metadata:{},originalName:i});d.id=i,d.name=i,d.boxFileId=o.id,d.eTag=o.etag??void 0,d.ETag=o.etag??void 0;try{await this.deleteMeta(e)}catch{}return d})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{await this.authHandle.ensureReady();const t=[];let r=0;const s=Math.min(e,1e3);for(;t.length<e;){const n=(await this.runOperation(i,()=>this.client.folders.getFolderItems(this.rootFolderId,{queryParams:{fields:["id","name","size","modified_at","etag","type"],limit:s,offset:r}}))).entries??[];for(const l of n){const o=l;if(o.type!=="file"||!o.id||!o.name)continue;this.fileIdCache.set(o.name,o.id);const d=new p({contentType:"application/octet-stream",metadata:{},originalName:o.name});if(d.id=o.name,d.name=o.name,d.boxFileId=o.id,d.eTag=o.etag??void 0,d.ETag=o.etag??void 0,d.size=o.size??0,d.modifiedAt=o.modifiedAt??o.contentModifiedAt??void 0,t.push(d),t.length>=e)break}if(n.length<s)break;r+=n.length}return t},{limit:e})}async getReadUrl(e,i){if(i?.responseContentDisposition||i?.responseContentType)return C(B.METHOD_NOT_ALLOWED,"Box: `responseContentDisposition` / `responseContentType` are not supported — Box download URLs and shared-link URLs have no overrides.");await this.authHandle.ensureReady();const t=await this.resolveFileId(e);return this.publicByDefault?this.ensureSharedLink(t):this.client.downloads.getDownloadFileUrl(t)}async getUploadUrl(e,i){return C(B.METHOD_NOT_ALLOWED,"Box: `getUploadUrl` is not supported. Box uploads require a multipart POST with an `attributes` JSON part and a file bytes part; this doesn't fit the PUT-style upload-url contract. Use `write()` server-side, or the Box UI Elements / Box Content Uploader for browser flows.")}async findChildByName(e,i,t){let r=0;const s=1e3;for(;;){const n=(await this.runOperation(t,()=>this.client.folders.getFolderItems(e,{queryParams:{fields:["id","name","type"],limit:s,offset:r}}))).entries??[];for(const l of n){const o=l;if(o.name===i&&o.id&&o.type)return{id:o.id,type:o.type}}if(n.length<s)return;r+=n.length}}folderCacheKey(e){return e.join("/")}async resolveFolderId(e,i,t){if(e.length===0)return this.rootFolderId;const r=this.folderCacheKey(e),s=this.folderIdCache.get(r);if(s)return s;let n=this.rootFolderId;const l=[];for(const o of e){l.push(o);const d=this.folderCacheKey(l),c=this.folderIdCache.get(d);if(c){n=c;continue}const h=await this.findChildByName(n,o,t);if(h&&h.type==="folder"){n=h.id,this.folderIdCache.set(d,n);continue}if(h&&h.type!=="folder")throw new Error(`Box: path segment "${o}" exists but is not a folder`);if(!i.create)throw new Error(`Box: folder "${l.join("/")}" not found`);try{const f=await this.runOperation(t,()=>this.client.folders.createFolder({name:o,parent:{id:n}}));if(!f.id)throw new Error(`Box: createFolder did not return an id for "${o}"`);n=f.id,this.folderIdCache.set(d,n)}catch(f){if(k(f)){const y=await this.findChildByName(n,o,t);if(y&&y.type==="folder"){n=y.id,this.folderIdCache.set(d,n);continue}}throw f}}return this.folderIdCache.set(r,n),n}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const{leaf:r,parents:s}=m(e),n=await this.resolveFolderId(s,{create:!1},i),l=await this.findChildByName(n,r,i);if(!l||l.type!=="file")throw new Error(`Box: file "${e}" not found`);return this.fileIdCache.set(e,l.id),l.id}async resolveExistingFileForUpload(e,i,t,r){const s=this.fileIdCache.get(e);if(s)return s;const n=await this.findChildByName(i,t,r);if(n){if(n.type==="file")return this.fileIdCache.set(e,n.id),n.id;throw new Error(`Box: "${e}" already exists as a non-file (${n.type})`)}}async performUpload(e,i,t,r,s){if(r.byteLength>A)return await this.runOperation(s,()=>this.client.chunkedUploads.uploadBigFile(g(r),t,r.byteLength,i));if(e){const l=((await this.runOperation(s,()=>this.client.uploads.uploadFileVersion(e,{attributes:{name:t},file:g(r)}))).entries??[])[0];if(!l)throw new Error("Box: uploadFileVersion returned no file");return l}const n=((await this.runOperation(s,()=>this.client.uploads.uploadFile({attributes:{name:t,parent:{id:i}},file:g(r)}))).entries??[])[0];if(!n)throw new Error("Box: uploadFile returned no file");return n}async ensureSharedLink(e,i){try{const t=(await this.runOperation(i,()=>this.client.sharedLinksFiles.addShareLinkToFile(e,{sharedLink:{access:"open"}},{fields:"shared_link"}))).sharedLink;return(t?.downloadUrl??t?.url)||this.fetchSharedLinkUrl(e,i)}catch(t){if(k(t))return this.fetchSharedLinkUrl(e,i);throw t}}async fetchSharedLinkUrl(e,i){const t=(await this.runOperation(i,()=>this.client.sharedLinksFiles.getSharedLinkForFile(e,{fields:"shared_link"}))).sharedLink,r=t?.downloadUrl??t?.url;if(!r)throw new Error("Box: file has no shared link. Call write() with publicByDefault: true, or addShareLinkToFile via storage.raw.");return r}internalOnComplete=e=>this.deleteMeta(e.id)}export{ee as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{Readable as w}from"node:stream";import{throwErrorCode as S,ERRORS as T,wrapStorageError as l}from"./ERRORS-BIBxE2oR.js";import{B as b}from"./storage-0j5nCAUp.js";import d from"./BunS3File-BcYmsz1n.js";import E from"./BunS3MetaStorage-BSn6Qfnf.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as O}from"./update-size-DuNuLyxj.js";import{i as I}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";const c=s=>s.replace(/^\/+/u,""),C=async s=>{const e=[];for await(const i of s)e.push(Buffer.from(i));return Buffer.concat(e)},k=s=>{const e=s?.code;return typeof e=="string"&&/nosuchkey|notfound/iu.test(e)},p=(s,e)=>{const i=s?.code,t=typeof i=="string"?i:"";return/nosuchkey|notfound/iu.test(t)?l(s,{adapter:"Bun S3",operation:e,status:404}):/accessdenied|forbidden|ERR_S3_INVALID_SIGNATURE|ERR_S3_MISSING_CREDENTIALS/iu.test(t)?l(s,{adapter:"Bun S3",operation:e,status:403}):l(s,{adapter:"Bun S3",operation:e})},z=s=>{if(s.client)return s.client;const e=globalThis.Bun;if(!e?.S3Client)throw new Error("BunS3Storage requires the Bun runtime (Bun.S3Client). Run this under Bun, or pass a pre-built `client` instance. For Node/edge runtimes use the `aws` or `aws-light` provider instead.");return new e.S3Client({accessKeyId:s.accessKeyId,acl:s.acl,bucket:s.bucket,endpoint:s.endpoint,region:s.region,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,virtualHostedStyle:s.virtualHostedStyle})};class L extends b{static name="bun-s3";meta;client;constructor(e){super(e),this.client=z(e),this.meta=e.metaStorage??new E(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new d(e);t.name=this.namingFunction(t),t.bunS3Key=c(t.name),await this.validate(t);try{const n=await this.getMeta(t.id);if(n.bytesWritten>=0)return n}catch{}return t.bytesWritten=0,t.status=y(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&O(t,e.size),!I(e,t))throw new Error("File part does not match");const n=await this.lock(e.id);try{if(v(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await C(e.body),a=c(t.name||t.id);try{await this.runOperation(i,()=>this.client.write(a,r,{type:t.contentType}))}catch(o){throw p(o,"upload")}t.bytesWritten=r.length,t.size=r.length,t.bunS3Key=a}return t.status=y(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,n)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const n=t?.bunS3Key??c(t?.name??e);try{await this.runOperation(i,()=>this.client.delete(n))}catch(a){if(!k(a))throw p(a,"delete")}if(t)return t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t;const r=new d({contentType:"application/octet-stream",metadata:{},originalName:e});return r.id=e,r.name=e,r.bunS3Key=n,r.status="deleted",r})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,n;try{t=await this.checkIfExpired(await this.getMeta(e)),n=t.bunS3Key??c(t.name??e)}catch{n=c(e)}const r=this.client.file(n);let a,o;try{t||(o=await this.runOperation(i,()=>r.stat())),a=Buffer.from(await this.runOperation(i,()=>r.arrayBuffer()))}catch(u){throw p(u,"get")}return{content:a,contentType:t?.contentType??o?.type??"application/octet-stream",ETag:t?.ETag??o?.etag??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??o?.lastModified?.toISOString(),name:t?.name??n,originalName:t?.originalName??n,size:t?.size??o?.size??a.length}})}async getStream({id:e},i){return this.instrumentOperation("getStream",async()=>{let t,n;try{t=await this.checkIfExpired(await this.getMeta(e)),n=t.bunS3Key??c(t.name??e)}catch{n=c(e)}const r=this.client.file(n);let a,o;try{a=await this.runOperation(i,()=>r.stat()),o=r.stream()}catch(f){throw p(f,"getStream")}const u=t?.size??a.size,g=t?.contentType??a.type??"application/octet-stream",h=t?.ETag??a.etag,m=t?.modifiedAt??a.lastModified?.toISOString();return{headers:{"Content-Length":String(u??0),"Content-Type":g,...h&&{ETag:h},...m&&{"Last-Modified":String(m)}},size:typeof u=="number"?u:void 0,stream:w.fromWeb(o)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const n=await this.get({id:e},t),r=c(i);try{await this.runOperation(t,()=>this.client.write(r,n.content,{type:n.contentType}))}catch(o){throw p(o,"copy")}const a=new d({contentType:n.contentType,metadata:{},originalName:i});return a.id=i,a.name=i,a.bunS3Key=r,a.size=typeof n.size=="string"?Number(n.size):n.size??n.content.length,a.ETag=n.ETag,a.bunS3ETag=n.ETag,a})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const n=await this.copy(e,i,t);return await this.delete({id:e},t),n})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{let t;try{t=await this.runOperation(i,()=>this.client.list({maxKeys:e}))}catch(n){throw p(n,"list")}return(t.contents??[]).filter(n=>!!n.key).slice(0,e).map(n=>{const r=c(n.key),a=new d({contentType:"application/octet-stream",metadata:{},originalName:r});return a.id=r,a.name=r,a.bunS3Key=r,a.size=n.size,a.ETag=n.eTag??void 0,a.bunS3ETag=n.eTag??void 0,a.modifiedAt=n.lastModified?new Date(n.lastModified).toISOString():void 0,a})},{limit:e})}async getReadUrl(e,i){return this.client.file(c(e)).presign({...i?.responseContentDisposition&&{contentDisposition:i.responseContentDisposition},...i?.expiresIn!==void 0&&{expiresIn:i.expiresIn},method:"GET",...i?.responseContentType&&{type:i.responseContentType}})}async getUploadUrl(e,i){return i?.contentLength!==void 0?S(T.BAD_REQUEST,"bun-s3: `contentLength` is not supported for upload URLs. A Bun presigned PUT has no content-length-range policy, so the cap would not bind; enforce size limits at your application gateway/proxy, or use a presigned POST form."):this.client.presign(c(e),{...i?.expiresIn!==void 0&&{expiresIn:i.expiresIn},method:"PUT",...i?.contentType&&{type:i.contentType}})}internalOnComplete=e=>this.deleteMeta(e.id)}export{L as default};
1
+ import{Readable as w}from"node:stream";import{throwErrorCode as S,ERRORS as T,wrapStorageError as l}from"./ERRORS-BIBxE2oR.js";import{B as b}from"./storage-0j5nCAUp.js";import d from"./BunS3File-BcYmsz1n.js";import E from"./BunS3MetaStorage-CHWrhgg2.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as O}from"./update-size-DuNuLyxj.js";import{i as I}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";const c=s=>s.replace(/^\/+/u,""),C=async s=>{const e=[];for await(const i of s)e.push(Buffer.from(i));return Buffer.concat(e)},k=s=>{const e=s?.code;return typeof e=="string"&&/nosuchkey|notfound/iu.test(e)},p=(s,e)=>{const i=s?.code,t=typeof i=="string"?i:"";return/nosuchkey|notfound/iu.test(t)?l(s,{adapter:"Bun S3",operation:e,status:404}):/accessdenied|forbidden|ERR_S3_INVALID_SIGNATURE|ERR_S3_MISSING_CREDENTIALS/iu.test(t)?l(s,{adapter:"Bun S3",operation:e,status:403}):l(s,{adapter:"Bun S3",operation:e})},z=s=>{if(s.client)return s.client;const e=globalThis.Bun;if(!e?.S3Client)throw new Error("BunS3Storage requires the Bun runtime (Bun.S3Client). Run this under Bun, or pass a pre-built `client` instance. For Node/edge runtimes use the `aws` or `aws-light` provider instead.");return new e.S3Client({accessKeyId:s.accessKeyId,acl:s.acl,bucket:s.bucket,endpoint:s.endpoint,region:s.region,secretAccessKey:s.secretAccessKey,sessionToken:s.sessionToken,virtualHostedStyle:s.virtualHostedStyle})};class L extends b{static name="bun-s3";meta;client;constructor(e){super(e),this.client=z(e),this.meta=e.metaStorage??new E(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new d(e);t.name=this.namingFunction(t),t.bunS3Key=c(t.name),await this.validate(t);try{const n=await this.getMeta(t.id);if(n.bytesWritten>=0)return n}catch{}return t.bytesWritten=0,t.status=y(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&O(t,e.size),!I(e,t))throw new Error("File part does not match");const n=await this.lock(e.id);try{if(v(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await C(e.body),a=c(t.name||t.id);try{await this.runOperation(i,()=>this.client.write(a,r,{type:t.contentType}))}catch(o){throw p(o,"upload")}t.bytesWritten=r.length,t.size=r.length,t.bunS3Key=a}return t.status=y(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,n)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const n=t?.bunS3Key??c(t?.name??e);try{await this.runOperation(i,()=>this.client.delete(n))}catch(a){if(!k(a))throw p(a,"delete")}if(t)return t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t;const r=new d({contentType:"application/octet-stream",metadata:{},originalName:e});return r.id=e,r.name=e,r.bunS3Key=n,r.status="deleted",r})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,n;try{t=await this.checkIfExpired(await this.getMeta(e)),n=t.bunS3Key??c(t.name??e)}catch{n=c(e)}const r=this.client.file(n);let a,o;try{t||(o=await this.runOperation(i,()=>r.stat())),a=Buffer.from(await this.runOperation(i,()=>r.arrayBuffer()))}catch(u){throw p(u,"get")}return{content:a,contentType:t?.contentType??o?.type??"application/octet-stream",ETag:t?.ETag??o?.etag??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??o?.lastModified?.toISOString(),name:t?.name??n,originalName:t?.originalName??n,size:t?.size??o?.size??a.length}})}async getStream({id:e},i){return this.instrumentOperation("getStream",async()=>{let t,n;try{t=await this.checkIfExpired(await this.getMeta(e)),n=t.bunS3Key??c(t.name??e)}catch{n=c(e)}const r=this.client.file(n);let a,o;try{a=await this.runOperation(i,()=>r.stat()),o=r.stream()}catch(f){throw p(f,"getStream")}const u=t?.size??a.size,g=t?.contentType??a.type??"application/octet-stream",h=t?.ETag??a.etag,m=t?.modifiedAt??a.lastModified?.toISOString();return{headers:{"Content-Length":String(u??0),"Content-Type":g,...h&&{ETag:h},...m&&{"Last-Modified":String(m)}},size:typeof u=="number"?u:void 0,stream:w.fromWeb(o)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const n=await this.get({id:e},t),r=c(i);try{await this.runOperation(t,()=>this.client.write(r,n.content,{type:n.contentType}))}catch(o){throw p(o,"copy")}const a=new d({contentType:n.contentType,metadata:{},originalName:i});return a.id=i,a.name=i,a.bunS3Key=r,a.size=typeof n.size=="string"?Number(n.size):n.size??n.content.length,a.ETag=n.ETag,a.bunS3ETag=n.ETag,a})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const n=await this.copy(e,i,t);return await this.delete({id:e},t),n})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{let t;try{t=await this.runOperation(i,()=>this.client.list({maxKeys:e}))}catch(n){throw p(n,"list")}return(t.contents??[]).filter(n=>!!n.key).slice(0,e).map(n=>{const r=c(n.key),a=new d({contentType:"application/octet-stream",metadata:{},originalName:r});return a.id=r,a.name=r,a.bunS3Key=r,a.size=n.size,a.ETag=n.eTag??void 0,a.bunS3ETag=n.eTag??void 0,a.modifiedAt=n.lastModified?new Date(n.lastModified).toISOString():void 0,a})},{limit:e})}async getReadUrl(e,i){return this.client.file(c(e)).presign({...i?.responseContentDisposition&&{contentDisposition:i.responseContentDisposition},...i?.expiresIn!==void 0&&{expiresIn:i.expiresIn},method:"GET",...i?.responseContentType&&{type:i.responseContentType}})}async getUploadUrl(e,i){return i?.contentLength!==void 0?S(T.BAD_REQUEST,"bun-s3: `contentLength` is not supported for upload URLs. A Bun presigned PUT has no content-length-range policy, so the cap would not bind; enforce size limits at your application gateway/proxy, or use a presigned POST form."):this.client.presign(c(e),{...i?.expiresIn!==void 0&&{expiresIn:i.expiresIn},method:"PUT",...i?.contentType&&{type:i.contentType}})}internalOnComplete=e=>this.deleteMeta(e.id)}export{L as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import*as c from"@bunny.net/storage-sdk";import{throwErrorCode as d,ERRORS as y,wrapStorageError as l}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import m from"./BunnyFile-BgEOlcYI.js";import T from"./BunnyMetaStorage-BSn6Qfnf.js";import{t as w}from"./get-file-status-y3wTtDQs.js";import{t as N}from"./update-size-DuNuLyxj.js";import{i as A}from"./part-match-D-9dGX42.js";import{e as _}from"./has-content-50BsqrWw.js";const f=new Set(Object.values(c.regions.StorageRegion)),h=r=>`/${r.replace(/^\/+/u,"")}`,g=r=>r.replace(/^\/+/u,""),B=(r,t)=>{const n=r.replace(/\/+$/u,""),e=t.replace(/^\/+/u,"");return`${n}/${e}`},b=async r=>{const t=[];for await(const n of r)t.push(Buffer.from(n));return Buffer.concat(t)},E=r=>new ReadableStream({start(t){t.enqueue(new Uint8Array(r)),t.close()}}),R=r=>{if(r){if(!f.has(r))throw new Error(`Bunny Storage: unsupported region "${r}". Pass one of ${[...f].join(", ")}.`);return r}},C=r=>{if(r.client)return r.client;const t=r.zone??process.env.BUNNY_STORAGE_ZONE??process.env.STORAGE_ZONE,n=r.accessKey??process.env.BUNNY_STORAGE_ACCESS_KEY??process.env.BUNNY_ACCESS_KEY??process.env.STORAGE_ACCESS_KEY,e=R(r.region??process.env.BUNNY_STORAGE_REGION??process.env.STORAGE_REGION);if(!t||!n||!e)throw new Error("Bunny Storage: missing credentials. Pass `zone` + `accessKey` + `region`, or set BUNNY_STORAGE_ZONE / BUNNY_STORAGE_ACCESS_KEY / BUNNY_STORAGE_REGION (SDK aliases: STORAGE_ZONE / STORAGE_ACCESS_KEY / STORAGE_REGION).");return c.zone.connect_with_accesskey(e,t,n)},U=async r=>Buffer.from(await new Response(r).arrayBuffer()),p=(r,t)=>{const n=r?.message,e=typeof n=="string"?n:"";return/^file not found/iu.test(e)?l(r,{adapter:"Bunny Storage",operation:t,status:404}):/^unauthorized access/iu.test(e)?l(r,{adapter:"Bunny Storage",operation:t,status:401}):/^unable to upload file/iu.test(e)?l(r,{adapter:"Bunny Storage",operation:t,status:400}):l(r,{adapter:"Bunny Storage",operation:t})};class M extends O{static name="bunny";checksumTypes=["SHA256"];meta;client;publicBaseUrl;zoneName;constructor(t){super(t),this.client=C(t),this.zoneName=c.zone.name(this.client),this.publicBaseUrl=t.publicBaseUrl,this.meta=t.metaStorage??new T(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}get zone(){return this.zoneName}async create(t,n){return this.instrumentOperation("create",async()=>{const e=new m(t);e.name=this.namingFunction(e),e.bunnyPath=h(e.name),await this.validate(e);try{const a=await this.getMeta(e.id);if(a.bytesWritten>=0)return a}catch{}return e.bytesWritten=0,e.status=w(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,n){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&N(e,t.size),!A(t,e))throw new Error("File part does not match");const a=await this.lock(t.id);try{if(_(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await b(t.body),o=h(e.name||e.id);try{await this.runOperation(n,()=>c.file.upload(this.client,o,E(i),{contentType:e.contentType,...t.checksum&&t.checksumAlgorithm==="sha256"&&{sha256Checksum:t.checksum}}))}catch(s){throw p(s,"upload")}e.bytesWritten=i.length,e.size=i.length,e.bunnyPath=o}return e.status=w(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,a)}})}async delete({id:t},n){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const a=e?.bunnyPath??h(e?.name??t);try{await this.runOperation(n,()=>c.file.remove(this.client,a))}catch(o){throw p(o,"delete")}if(e)return e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e;const i=new m({contentType:"application/octet-stream",metadata:{},originalName:t});return i.id=t,i.name=t,i.bunnyPath=a,i.status="deleted",i})}async get({id:t},n){return this.instrumentOperation("get",async()=>{let e,a;try{e=await this.checkIfExpired(await this.getMeta(t)),a=e.bunnyPath??h(e.name??t)}catch{a=h(t)}let i;try{i=await this.runOperation(n,()=>c.file.get(this.client,a))}catch(s){throw p(s,"get")}let o;try{const s=await this.runOperation(n,()=>i.data());o=await U(s.stream)}catch(s){throw p(s,"download")}return{content:o,contentType:e?.contentType??i.contentType??"application/octet-stream",ETag:e?.ETag??i.checksum??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??i.lastChanged?.toISOString(),name:e?.name??g(a),originalName:e?.originalName??g(a),size:e?.size??i.length??o.length}})}async copy(t,n,e){return this.instrumentOperation("copy",async()=>{const a=await this.get({id:t},e),i=h(n),o=a.content,s=typeof a.size=="string"?Number(a.size):a.size??o.length;try{await this.runOperation(e,()=>c.file.upload(this.client,i,E(o),{contentType:a.contentType}))}catch(S){throw p(S,"copy")}const u=new m({contentType:a.contentType,metadata:{},originalName:n});return u.id=n,u.name=n,u.bunnyPath=i,u.size=s,u.ETag=a.ETag,u.bunnyChecksum=a.ETag,u})}async move(t,n,e){return this.instrumentOperation("move",async()=>{const a=await this.copy(t,n,e);return await this.delete({id:t},e),a})}async list(t=1e3,n){return this.instrumentOperation("list",async()=>{let e;try{e=await this.runOperation(n,()=>c.file.list(this.client,"/"))}catch(a){throw p(a,"list")}return e.filter(a=>!a.isDirectory).slice(0,t).map(a=>{const i=a.path.endsWith(a.objectName)||!a.objectName?a.path:`${a.path.replace(/\/+$/u,"")}/${a.objectName}`,o=g(i),s=new m({contentType:a.contentType||"application/octet-stream",metadata:{},originalName:o});return s.id=o,s.name=o,s.bunnyPath=h(o),s.bunnyChecksum=a.checksum??void 0,s.ETag=a.checksum??void 0,s.size=a.length,s.modifiedAt=a.lastChanged?.toISOString(),s})},{limit:t})}async getReadUrl(t,n){return n?.responseContentDisposition!==void 0||n?.responseContentType!==void 0?d(y.METHOD_NOT_ALLOWED,"Bunny Storage: `responseContentDisposition`/`responseContentType` are not supported — no override exists on Bunny Storage / Pull Zone URLs."):this.publicBaseUrl?B(this.publicBaseUrl,t):d(y.METHOD_NOT_ALLOWED,"Bunny Storage: `getReadUrl` requires `publicBaseUrl` (for example a Bunny Pull Zone or custom CDN hostname). The Storage API URL itself requires an AccessKey header and cannot be handed out as a public URL.")}async getUploadUrl(t,n){return d(y.METHOD_NOT_ALLOWED,"Bunny Storage: presigned PUT URLs are not supported — writes go through the Storage API with an AccessKey header. Upload server-side via the SDK or proxy through your application.")}internalOnComplete=t=>this.deleteMeta(t.id)}export{M as default};
1
+ import*as c from"@bunny.net/storage-sdk";import{throwErrorCode as d,ERRORS as y,wrapStorageError as l}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import m from"./BunnyFile-BgEOlcYI.js";import T from"./BunnyMetaStorage-CHWrhgg2.js";import{t as w}from"./get-file-status-y3wTtDQs.js";import{t as N}from"./update-size-DuNuLyxj.js";import{i as A}from"./part-match-D-9dGX42.js";import{e as _}from"./has-content-50BsqrWw.js";const f=new Set(Object.values(c.regions.StorageRegion)),h=r=>`/${r.replace(/^\/+/u,"")}`,g=r=>r.replace(/^\/+/u,""),B=(r,t)=>{const n=r.replace(/\/+$/u,""),e=t.replace(/^\/+/u,"");return`${n}/${e}`},b=async r=>{const t=[];for await(const n of r)t.push(Buffer.from(n));return Buffer.concat(t)},E=r=>new ReadableStream({start(t){t.enqueue(new Uint8Array(r)),t.close()}}),R=r=>{if(r){if(!f.has(r))throw new Error(`Bunny Storage: unsupported region "${r}". Pass one of ${[...f].join(", ")}.`);return r}},C=r=>{if(r.client)return r.client;const t=r.zone??process.env.BUNNY_STORAGE_ZONE??process.env.STORAGE_ZONE,n=r.accessKey??process.env.BUNNY_STORAGE_ACCESS_KEY??process.env.BUNNY_ACCESS_KEY??process.env.STORAGE_ACCESS_KEY,e=R(r.region??process.env.BUNNY_STORAGE_REGION??process.env.STORAGE_REGION);if(!t||!n||!e)throw new Error("Bunny Storage: missing credentials. Pass `zone` + `accessKey` + `region`, or set BUNNY_STORAGE_ZONE / BUNNY_STORAGE_ACCESS_KEY / BUNNY_STORAGE_REGION (SDK aliases: STORAGE_ZONE / STORAGE_ACCESS_KEY / STORAGE_REGION).");return c.zone.connect_with_accesskey(e,t,n)},U=async r=>Buffer.from(await new Response(r).arrayBuffer()),p=(r,t)=>{const n=r?.message,e=typeof n=="string"?n:"";return/^file not found/iu.test(e)?l(r,{adapter:"Bunny Storage",operation:t,status:404}):/^unauthorized access/iu.test(e)?l(r,{adapter:"Bunny Storage",operation:t,status:401}):/^unable to upload file/iu.test(e)?l(r,{adapter:"Bunny Storage",operation:t,status:400}):l(r,{adapter:"Bunny Storage",operation:t})};class M extends O{static name="bunny";checksumTypes=["SHA256"];meta;client;publicBaseUrl;zoneName;constructor(t){super(t),this.client=C(t),this.zoneName=c.zone.name(this.client),this.publicBaseUrl=t.publicBaseUrl,this.meta=t.metaStorage??new T(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}get zone(){return this.zoneName}async create(t,n){return this.instrumentOperation("create",async()=>{const e=new m(t);e.name=this.namingFunction(e),e.bunnyPath=h(e.name),await this.validate(e);try{const a=await this.getMeta(e.id);if(a.bytesWritten>=0)return a}catch{}return e.bytesWritten=0,e.status=w(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,n){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&N(e,t.size),!A(t,e))throw new Error("File part does not match");const a=await this.lock(t.id);try{if(_(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await b(t.body),o=h(e.name||e.id);try{await this.runOperation(n,()=>c.file.upload(this.client,o,E(i),{contentType:e.contentType,...t.checksum&&t.checksumAlgorithm==="sha256"&&{sha256Checksum:t.checksum}}))}catch(s){throw p(s,"upload")}e.bytesWritten=i.length,e.size=i.length,e.bunnyPath=o}return e.status=w(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,a)}})}async delete({id:t},n){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const a=e?.bunnyPath??h(e?.name??t);try{await this.runOperation(n,()=>c.file.remove(this.client,a))}catch(o){throw p(o,"delete")}if(e)return e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e;const i=new m({contentType:"application/octet-stream",metadata:{},originalName:t});return i.id=t,i.name=t,i.bunnyPath=a,i.status="deleted",i})}async get({id:t},n){return this.instrumentOperation("get",async()=>{let e,a;try{e=await this.checkIfExpired(await this.getMeta(t)),a=e.bunnyPath??h(e.name??t)}catch{a=h(t)}let i;try{i=await this.runOperation(n,()=>c.file.get(this.client,a))}catch(s){throw p(s,"get")}let o;try{const s=await this.runOperation(n,()=>i.data());o=await U(s.stream)}catch(s){throw p(s,"download")}return{content:o,contentType:e?.contentType??i.contentType??"application/octet-stream",ETag:e?.ETag??i.checksum??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??i.lastChanged?.toISOString(),name:e?.name??g(a),originalName:e?.originalName??g(a),size:e?.size??i.length??o.length}})}async copy(t,n,e){return this.instrumentOperation("copy",async()=>{const a=await this.get({id:t},e),i=h(n),o=a.content,s=typeof a.size=="string"?Number(a.size):a.size??o.length;try{await this.runOperation(e,()=>c.file.upload(this.client,i,E(o),{contentType:a.contentType}))}catch(S){throw p(S,"copy")}const u=new m({contentType:a.contentType,metadata:{},originalName:n});return u.id=n,u.name=n,u.bunnyPath=i,u.size=s,u.ETag=a.ETag,u.bunnyChecksum=a.ETag,u})}async move(t,n,e){return this.instrumentOperation("move",async()=>{const a=await this.copy(t,n,e);return await this.delete({id:t},e),a})}async list(t=1e3,n){return this.instrumentOperation("list",async()=>{let e;try{e=await this.runOperation(n,()=>c.file.list(this.client,"/"))}catch(a){throw p(a,"list")}return e.filter(a=>!a.isDirectory).slice(0,t).map(a=>{const i=a.path.endsWith(a.objectName)||!a.objectName?a.path:`${a.path.replace(/\/+$/u,"")}/${a.objectName}`,o=g(i),s=new m({contentType:a.contentType||"application/octet-stream",metadata:{},originalName:o});return s.id=o,s.name=o,s.bunnyPath=h(o),s.bunnyChecksum=a.checksum??void 0,s.ETag=a.checksum??void 0,s.size=a.length,s.modifiedAt=a.lastChanged?.toISOString(),s})},{limit:t})}async getReadUrl(t,n){return n?.responseContentDisposition!==void 0||n?.responseContentType!==void 0?d(y.METHOD_NOT_ALLOWED,"Bunny Storage: `responseContentDisposition`/`responseContentType` are not supported — no override exists on Bunny Storage / Pull Zone URLs."):this.publicBaseUrl?B(this.publicBaseUrl,t):d(y.METHOD_NOT_ALLOWED,"Bunny Storage: `getReadUrl` requires `publicBaseUrl` (for example a Bunny Pull Zone or custom CDN hostname). The Storage API URL itself requires an AccessKey header and cannot be handed out as a public URL.")}async getUploadUrl(t,n){return d(y.METHOD_NOT_ALLOWED,"Bunny Storage: presigned PUT URLs are not supported — writes go through the Storage API with an AccessKey header. Upload server-side via the SDK or proxy through your application.")}internalOnComplete=t=>this.deleteMeta(t.id)}export{M as default};
@@ -0,0 +1 @@
1
+ import{y as s}from"./local-meta-storage-DJDcuxf1.js";class o extends s{constructor(r){super(r)}}export{o as default};
@@ -1 +1 @@
1
- import{v2 as p}from"cloudinary";import{throwErrorCode as u,ERRORS as l}from"./ERRORS-BIBxE2oR.js";import{B as d}from"./storage-0j5nCAUp.js";import c from"./CloudinaryFile-Bo5B-vM1.js";import h from"./CloudinaryMetaStorage-DPVnmNe5.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as m}from"./update-size-DuNuLyxj.js";import{i as f}from"./part-match-D-9dGX42.js";import{e as w}from"./has-content-50BsqrWw.js";const v=async o=>{const e=[];for await(const a of o)e.push(Buffer.from(a));return Buffer.concat(e)},_=o=>{if(!o)return{};const e=o.match(/^cloudinary:\/\/([^:]+):([^@]+)@(.+)$/);return e?{apiKey:e[1],apiSecret:e[2],cloudName:e[3]}:{}};class M extends d{static name="cloudinary";checksumTypes=[];meta;client;defaultUrlExpiresIn;deliveryType;resourceType;secure;constructor(e){if(super(e),this.resourceType=e.resourceType??"raw",this.deliveryType=e.type??"upload",this.secure=e.secure??!0,this.defaultUrlExpiresIn=e.defaultUrlExpiresIn??3600,e.client)this.client=e.client;else{const a=_(process.env.CLOUDINARY_URL),t=e.cloudName??process.env.CLOUDINARY_CLOUD_NAME??a.cloudName,r=e.apiKey??process.env.CLOUDINARY_API_KEY??a.apiKey,i=e.apiSecret??process.env.CLOUDINARY_API_SECRET??a.apiSecret;if(!t)throw new Error("Cloudinary storage: `cloudName` is required (or set CLOUDINARY_CLOUD_NAME / CLOUDINARY_URL).");p.config({api_key:r,api_secret:i,cloud_name:t,secure:this.secure}),this.client=p}this.meta=e.metaStorage??new h(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new c(e);t.name=this.namingFunction(t),t.path=t.name,await this.validate(t);try{const r=await this.getMeta(t.id);if(r.bytesWritten>=0)return r}catch{}return t.bytesWritten=0,t.status=y(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&m(t,e.size),!f(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(w(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await v(e.body),s=t.path??t.name,n=await this.runOperation(a,()=>this.uploadBuffer(s,i));t.bytesWritten=i.length,t.size=i.length,t.path=n.public_id??s,t.publicUrl=n.secure_url??n.url,t.ETag=n.version===void 0?void 0:String(n.version)}return t.status=y(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const r=t?.path??t?.name??e;return await this.runOperation(a,()=>this.client.uploader.destroy(r,{invalidate:!0,resource_type:this.resourceType,type:this.deliveryType})),t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,path:r,status:"deleted"})})}async exists({id:e},a){return this.instrumentOperation("exists",async()=>{let t=e;try{t=(await this.getMeta(e)).path??e}catch{}try{return await this.runOperation(a,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),!0}catch{return!1}})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t=e,r;try{r=await this.checkIfExpired(await this.getMeta(e)),t=r.path??r.name??e}catch{}const i=await this.runOperation(a,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),s=await this.runOperation(a,()=>fetch(this.client.url(t,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType})));if(!s.ok)throw new Error(`Cloudinary: object not found at "${t}"`);const n=Buffer.from(await s.arrayBuffer());return{content:n,contentType:r?.contentType??(i.resource_type&&i.format?`${i.resource_type}/${i.format}`:void 0)??"application/octet-stream",ETag:r?.ETag??(i.version===void 0?void 0:String(i.version)),expiredAt:r?.expiredAt,id:e,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??t,originalName:r?.originalName??t,size:r?.size??(typeof i.bytes=="number"?i.bytes:n.length)}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(e))?.path??e,i=this.client.url(r,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType});await this.runOperation(t,()=>this.client.uploader.upload(i,{overwrite:!0,public_id:a,resource_type:this.resourceType,type:this.deliveryType}));const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=a,s})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(e))?.path??e;await this.runOperation(t,()=>this.client.uploader.rename(r,a,{resource_type:this.resourceType}));const i=new c({contentType:"application/octet-stream",metadata:{},originalName:a});i.id=a,i.name=a,i.path=a;try{await this.deleteMeta(e)}catch{}return i})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>{const{resources:t}=await this.runOperation(a,()=>this.client.api.resources({max_results:e,resource_type:this.resourceType,type:this.deliveryType}));return(t??[]).map(r=>{const i=new c({contentType:r.resource_type&&r.format?`${r.resource_type}/${r.format}`:"application/octet-stream",metadata:{},originalName:r.public_id});return i.id=r.public_id,i.name=r.public_id,i.path=r.public_id,i.size=typeof r.bytes=="number"?r.bytes:void 0,i.createdAt=r.created_at??void 0,i.ETag=r.version===void 0?void 0:String(r.version),i})},{limit:e})}async getReadUrl(e,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return u(l.BAD_REQUEST,"cloudinary: `responseContentDisposition`/`responseContentType` are not supported. A public delivery URL has no signature in which to bind the override, and Cloudinary's signed download URL cannot pin an arbitrary Content-Disposition/Content-Type; set the disposition via a Cloudinary delivery transformation instead.");if(this.deliveryType==="upload")return this.client.url(e,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType});const t=a?.expiresIn??this.defaultUrlExpiresIn,r=e.lastIndexOf("."),i=r>0?e.slice(r+1):"";try{return this.client.utils.private_download_url(e,i,{expires_at:Math.floor(Date.now()/1e3)+t,resource_type:this.resourceType,type:this.deliveryType})}catch(s){return u(l.METHOD_NOT_ALLOWED,s instanceof Error?s.message:"Cloudinary: private_download_url failed")}}uploadBuffer(e,a){return new Promise((t,r)=>{this.client.uploader.upload_stream({overwrite:!0,public_id:e,resource_type:this.resourceType,type:this.deliveryType},(i,s)=>{if(i||!s){r(i instanceof Error?i:new Error(i?.message??"Cloudinary: upload failed"));return}t(s)}).end(a)})}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=e=>this.deleteMeta(e.id)}export{M as default};
1
+ import{v2 as p}from"cloudinary";import{throwErrorCode as u,ERRORS as l}from"./ERRORS-BIBxE2oR.js";import{B as d}from"./storage-0j5nCAUp.js";import c from"./CloudinaryFile-Bo5B-vM1.js";import h from"./CloudinaryMetaStorage-BI9YXcwU.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as m}from"./update-size-DuNuLyxj.js";import{i as f}from"./part-match-D-9dGX42.js";import{e as w}from"./has-content-50BsqrWw.js";const v=async o=>{const e=[];for await(const a of o)e.push(Buffer.from(a));return Buffer.concat(e)},_=o=>{if(!o)return{};const e=o.match(/^cloudinary:\/\/([^:]+):([^@]+)@(.+)$/);return e?{apiKey:e[1],apiSecret:e[2],cloudName:e[3]}:{}};class M extends d{static name="cloudinary";checksumTypes=[];meta;client;defaultUrlExpiresIn;deliveryType;resourceType;secure;constructor(e){if(super(e),this.resourceType=e.resourceType??"raw",this.deliveryType=e.type??"upload",this.secure=e.secure??!0,this.defaultUrlExpiresIn=e.defaultUrlExpiresIn??3600,e.client)this.client=e.client;else{const a=_(process.env.CLOUDINARY_URL),t=e.cloudName??process.env.CLOUDINARY_CLOUD_NAME??a.cloudName,r=e.apiKey??process.env.CLOUDINARY_API_KEY??a.apiKey,i=e.apiSecret??process.env.CLOUDINARY_API_SECRET??a.apiSecret;if(!t)throw new Error("Cloudinary storage: `cloudName` is required (or set CLOUDINARY_CLOUD_NAME / CLOUDINARY_URL).");p.config({api_key:r,api_secret:i,cloud_name:t,secure:this.secure}),this.client=p}this.meta=e.metaStorage??new h(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new c(e);t.name=this.namingFunction(t),t.path=t.name,await this.validate(t);try{const r=await this.getMeta(t.id);if(r.bytesWritten>=0)return r}catch{}return t.bytesWritten=0,t.status=y(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&m(t,e.size),!f(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(w(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await v(e.body),s=t.path??t.name,n=await this.runOperation(a,()=>this.uploadBuffer(s,i));t.bytesWritten=i.length,t.size=i.length,t.path=n.public_id??s,t.publicUrl=n.secure_url??n.url,t.ETag=n.version===void 0?void 0:String(n.version)}return t.status=y(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const r=t?.path??t?.name??e;return await this.runOperation(a,()=>this.client.uploader.destroy(r,{invalidate:!0,resource_type:this.resourceType,type:this.deliveryType})),t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,path:r,status:"deleted"})})}async exists({id:e},a){return this.instrumentOperation("exists",async()=>{let t=e;try{t=(await this.getMeta(e)).path??e}catch{}try{return await this.runOperation(a,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),!0}catch{return!1}})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t=e,r;try{r=await this.checkIfExpired(await this.getMeta(e)),t=r.path??r.name??e}catch{}const i=await this.runOperation(a,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),s=await this.runOperation(a,()=>fetch(this.client.url(t,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType})));if(!s.ok)throw new Error(`Cloudinary: object not found at "${t}"`);const n=Buffer.from(await s.arrayBuffer());return{content:n,contentType:r?.contentType??(i.resource_type&&i.format?`${i.resource_type}/${i.format}`:void 0)??"application/octet-stream",ETag:r?.ETag??(i.version===void 0?void 0:String(i.version)),expiredAt:r?.expiredAt,id:e,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??t,originalName:r?.originalName??t,size:r?.size??(typeof i.bytes=="number"?i.bytes:n.length)}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(e))?.path??e,i=this.client.url(r,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType});await this.runOperation(t,()=>this.client.uploader.upload(i,{overwrite:!0,public_id:a,resource_type:this.resourceType,type:this.deliveryType}));const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=a,s})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(e))?.path??e;await this.runOperation(t,()=>this.client.uploader.rename(r,a,{resource_type:this.resourceType}));const i=new c({contentType:"application/octet-stream",metadata:{},originalName:a});i.id=a,i.name=a,i.path=a;try{await this.deleteMeta(e)}catch{}return i})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>{const{resources:t}=await this.runOperation(a,()=>this.client.api.resources({max_results:e,resource_type:this.resourceType,type:this.deliveryType}));return(t??[]).map(r=>{const i=new c({contentType:r.resource_type&&r.format?`${r.resource_type}/${r.format}`:"application/octet-stream",metadata:{},originalName:r.public_id});return i.id=r.public_id,i.name=r.public_id,i.path=r.public_id,i.size=typeof r.bytes=="number"?r.bytes:void 0,i.createdAt=r.created_at??void 0,i.ETag=r.version===void 0?void 0:String(r.version),i})},{limit:e})}async getReadUrl(e,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return u(l.BAD_REQUEST,"cloudinary: `responseContentDisposition`/`responseContentType` are not supported. A public delivery URL has no signature in which to bind the override, and Cloudinary's signed download URL cannot pin an arbitrary Content-Disposition/Content-Type; set the disposition via a Cloudinary delivery transformation instead.");if(this.deliveryType==="upload")return this.client.url(e,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType});const t=a?.expiresIn??this.defaultUrlExpiresIn,r=e.lastIndexOf("."),i=r>0?e.slice(r+1):"";try{return this.client.utils.private_download_url(e,i,{expires_at:Math.floor(Date.now()/1e3)+t,resource_type:this.resourceType,type:this.deliveryType})}catch(s){return u(l.METHOD_NOT_ALLOWED,s instanceof Error?s.message:"Cloudinary: private_download_url failed")}}uploadBuffer(e,a){return new Promise((t,r)=>{this.client.uploader.upload_stream({overwrite:!0,public_id:e,resource_type:this.resourceType,type:this.deliveryType},(i,s)=>{if(i||!s){r(i instanceof Error?i:new Error(i?.message??"Cloudinary: upload failed"));return}t(s)}).end(a)})}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=e=>this.deleteMeta(e.id)}export{M as default};
@@ -1 +1 @@
1
- import"node:fs";import"node:fs/promises";import"node:stream";import"./local-meta-storage-iuJnu90B.js";import"./path-0oTTdkvl-DvWvbDbh.js";import"./index-nZWCQrSe.js";import"./detect-file-type-BA7UBLKA.js";import"./ERRORS-BIBxE2oR.js";import{F as c}from"./disk-storage-CsQcYW3s.js";import"./storage-0j5nCAUp.js";import"./File-W8aOo15X.js";import"./get-file-status-y3wTtDQs.js";import"./update-size-DuNuLyxj.js";import"./part-match-D-9dGX42.js";import"./has-content-50BsqrWw.js";export{c as default};
1
+ import"node:fs";import"node:fs/promises";import"node:stream";import"./local-meta-storage-DJDcuxf1.js";import"./path-0oTTdkvl-DvWvbDbh.js";import"./index-nZWCQrSe.js";import"./detect-file-type-BA7UBLKA.js";import"./ERRORS-BIBxE2oR.js";import{F as c}from"./disk-storage-BwPk2IRa.js";import"./storage-0j5nCAUp.js";import"./File-W8aOo15X.js";import"./get-file-status-y3wTtDQs.js";import"./update-size-DuNuLyxj.js";import"./part-match-D-9dGX42.js";import"./has-content-50BsqrWw.js";export{c as default};