@visulima/storage 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (360) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE.md +130 -1
  3. package/dist/adapter/nuxt/module.d.ts +5 -5
  4. package/dist/adapter/nuxt/module.js +1 -1
  5. package/dist/ai/ai-sdk/index.d.ts +7 -7
  6. package/dist/ai/ai-sdk/index.js +1 -1
  7. package/dist/ai/claude/index.d.ts +5 -5
  8. package/dist/ai/claude/index.js +1 -1
  9. package/dist/ai/openai/index.d.ts +13 -5
  10. package/dist/ai/openai/index.js +1 -1
  11. package/dist/ai/tanstack/index.d.ts +6 -6
  12. package/dist/ai/tanstack/index.js +1 -1
  13. package/dist/handler/http/fetch/index.d.ts +8 -8
  14. package/dist/handler/http/fetch/index.js +1 -1
  15. package/dist/handler/http/hono/index.d.ts +7 -7
  16. package/dist/handler/http/hono/index.js +1 -1
  17. package/dist/handler/http/nextjs/index.d.ts +7 -7
  18. package/dist/handler/http/nextjs/index.js +1 -1
  19. package/dist/handler/http/node/index.d.ts +7 -7
  20. package/dist/handler/http/node/index.js +1 -1
  21. package/dist/handler/http/solid-start/index.d.ts +7 -7
  22. package/dist/handler/http/solid-start/index.js +1 -1
  23. package/dist/index.d.ts +8 -8
  24. package/dist/index.js +1 -1
  25. package/dist/openapi/index.js +1 -1
  26. package/dist/packem_shared/AbstractBaseStorage-CcIPoAES.js +1 -0
  27. package/dist/packem_shared/AwsLightFile-CqeZ6M7o.js +1 -0
  28. package/dist/packem_shared/AwsLightMetaStorage-Cb4xIpax.js +1 -0
  29. package/dist/packem_shared/AwsLightStorage-Bhg6C3fo.js +1 -0
  30. package/dist/packem_shared/AzureFile-DoUVXQMI.js +1 -0
  31. package/dist/packem_shared/AzureSMetaStorage-ByKDwgWo.js +1 -0
  32. package/dist/packem_shared/AzureStorage-BzYWVRnX.js +1 -0
  33. package/dist/packem_shared/BaseTransformer-ByIAKnn8.js +1 -0
  34. package/dist/packem_shared/BoxFile-CKKRYACc.js +1 -0
  35. package/dist/packem_shared/BoxMetaStorage-BI-G6aeO.js +1 -0
  36. package/dist/packem_shared/BoxStorage-Bmzt-OTx.js +1 -0
  37. package/dist/packem_shared/BunS3File-B2rczbY_.js +1 -0
  38. package/dist/packem_shared/BunS3MetaStorage-BI-G6aeO.js +1 -0
  39. package/dist/packem_shared/{BunS3Storage-B_roVJ29.js → BunS3Storage-uJ-u5wpg.js} +1 -1
  40. package/dist/packem_shared/BunnyFile-CBJdpNcB.js +1 -0
  41. package/dist/packem_shared/BunnyMetaStorage-BI-G6aeO.js +1 -0
  42. package/dist/packem_shared/BunnyStorage-9fw8VeuO.js +1 -0
  43. package/dist/packem_shared/CloudinaryFile-Dl8cnbJo.js +1 -0
  44. package/dist/packem_shared/CloudinaryMetaStorage-CYWznm7F.js +1 -0
  45. package/dist/packem_shared/CloudinaryStorage-CRVFUrEK.js +1 -0
  46. package/dist/packem_shared/DiskStorage-Wm6PC8Rc.js +1 -0
  47. package/dist/packem_shared/DiskStorageWithChecksum-CyhRDK5M.js +1 -0
  48. package/dist/packem_shared/DropboxFile-BUSubTWW.js +1 -0
  49. package/dist/packem_shared/DropboxMetaStorage-BYbJBJXr.js +1 -0
  50. package/dist/packem_shared/DropboxStorage-ZfgP7IMo.js +1 -0
  51. package/dist/packem_shared/{ERRORS-BIBxE2oR.js → ERRORS-olUcTqo2.js} +1 -1
  52. package/dist/packem_shared/File-DLAa0hBv.js +1 -0
  53. package/dist/packem_shared/Files-NF7wRh5C.js +1 -0
  54. package/dist/packem_shared/FirebaseFile-Dl8cnbJo.js +1 -0
  55. package/dist/packem_shared/FirebaseMetaStorage-DX1-58UY.js +1 -0
  56. package/dist/packem_shared/FirebaseStorage-D8NgHiZh.js +2 -0
  57. package/dist/packem_shared/FtpFile-H8EmE3S_.js +1 -0
  58. package/dist/packem_shared/FtpMetaStorage-BI-G6aeO.js +1 -0
  59. package/dist/packem_shared/FtpStorage-BjBdLfTV.js +1 -0
  60. package/dist/packem_shared/GCSFile-mFuZfcTW.js +1 -0
  61. package/dist/packem_shared/GCSMetaStorage-Dm8m-iJT.js +1 -0
  62. package/dist/packem_shared/GCStorage-BWV6QQqd.js +1 -0
  63. package/dist/packem_shared/GoogleDriveFile-fDYE1aaN.js +1 -0
  64. package/dist/packem_shared/GoogleDriveMetaStorage-CEleJNZZ.js +1 -0
  65. package/dist/packem_shared/{GoogleDriveStorage-Du7uBhSm.js → GoogleDriveStorage-CS9nWKP5.js} +1 -1
  66. package/dist/packem_shared/LocalMetaStorage-EnWCLyKq.js +1 -0
  67. package/dist/packem_shared/MediaTransformer-GqBUkOvz.js +1 -0
  68. package/dist/packem_shared/MemoryMetaStorage-DdAIGIVO.js +1 -0
  69. package/dist/packem_shared/{MemoryStorage-ChKyI6OY.js → MemoryStorage-CJw7SAlG.js} +1 -1
  70. package/dist/packem_shared/Metadata-BeQVDFer.js +1 -0
  71. package/dist/packem_shared/{Multipart-V64Bg5dt.js → Multipart-C3ve9Z0D.js} +1 -1
  72. package/dist/packem_shared/Multipart-PlMON60C.js +1 -0
  73. package/dist/packem_shared/NetlifyBlobFile-Br5HPqlC.js +1 -0
  74. package/dist/packem_shared/NetlifyBlobMetaStorage-DD5mbms5.js +1 -0
  75. package/dist/packem_shared/NetlifyBlobStorage-DVpJgN3v.js +1 -0
  76. package/dist/packem_shared/NoOpMetrics-CWqe9gwp.js +1 -0
  77. package/dist/packem_shared/OneDriveFile-Ccv5bkno.js +1 -0
  78. package/dist/packem_shared/OneDriveMetaStorage-D0GzJ0FC.js +1 -0
  79. package/dist/packem_shared/OneDriveStorage-CTYdWnnf.js +1 -0
  80. package/dist/packem_shared/OpenTelemetryMetrics-opDTaCRp.js +1 -0
  81. package/dist/packem_shared/PocketBaseFile-Dl8cnbJo.js +1 -0
  82. package/dist/packem_shared/PocketBaseMetaStorage-DgKNhi2j.js +1 -0
  83. package/dist/packem_shared/PocketBaseStorage-CHQVk7lR.js +1 -0
  84. package/dist/packem_shared/Rest-DQRxx8yQ.js +1 -0
  85. package/dist/packem_shared/Rest-DYXzbF-Q.js +1 -0
  86. package/dist/packem_shared/S3File-CyL0Q6Nx.js +1 -0
  87. package/dist/packem_shared/S3MetaStorage-DszTVQMa.js +1 -0
  88. package/dist/packem_shared/S3Storage-Bdns7a3N.js +1 -0
  89. package/dist/packem_shared/SftpFile-H8EmE3S_.js +1 -0
  90. package/dist/packem_shared/SftpMetaStorage-BI-G6aeO.js +1 -0
  91. package/dist/packem_shared/SftpStorage-D08to8f6.js +1 -0
  92. package/dist/packem_shared/SharePointFile-BWfd3Rel.js +1 -0
  93. package/dist/packem_shared/SharePointMetaStorage-BI-G6aeO.js +1 -0
  94. package/dist/packem_shared/{SharePointStorage-Dtnt5-wk.js → SharePointStorage-PtgEmyCY.js} +1 -1
  95. package/dist/packem_shared/SupabaseFile-CI0eFAyo.js +1 -0
  96. package/dist/packem_shared/SupabaseMetaStorage-CRw0xTXk.js +1 -0
  97. package/dist/packem_shared/SupabaseStorage-DJe4YZJD.js +1 -0
  98. package/dist/packem_shared/TUS_RESUMABLE-Dsxqcx-u.js +1 -0
  99. package/dist/packem_shared/{Tus-CJBgnJrn.js → Tus-C800fRBi.js} +1 -1
  100. package/dist/packem_shared/Tus-Vttn79I2.js +1 -0
  101. package/dist/packem_shared/UploadThingFile-DP4kNmpS.js +1 -0
  102. package/dist/packem_shared/UploadThingMetaStorage-CYWznm7F.js +1 -0
  103. package/dist/packem_shared/UploadThingStorage-S3iYzJ8Z.js +1 -0
  104. package/dist/packem_shared/ValidationError-SzFFFHiN.js +1 -0
  105. package/dist/packem_shared/VercelBlobFile-Censq2sD.js +1 -0
  106. package/dist/packem_shared/VercelBlobMetaStorage-DgKNhi2j.js +1 -0
  107. package/dist/packem_shared/VercelBlobStorage-D1eytZwU.js +1 -0
  108. package/dist/packem_shared/_commonjsHelpers-CqkleIqs.js +1 -0
  109. package/dist/packem_shared/agentsCopyFile-BMTcfVHg.js +1 -0
  110. package/dist/packem_shared/akamai-BPAk4688.js +1 -0
  111. package/dist/packem_shared/alibaba-CPhhkaQs.js +1 -0
  112. package/dist/packem_shared/approval-DcuhtQKs.js +1 -0
  113. package/dist/packem_shared/aws-light-meta-storage-CgGLgB8g.js +4 -0
  114. package/dist/packem_shared/azure-meta-storage-DmBO5MmP.js +1 -0
  115. package/dist/packem_shared/backblaze-CjeWkpeg.js +1 -0
  116. package/dist/packem_shared/base-handler-core-BvNgdV-9.js +1 -0
  117. package/dist/packem_shared/base-handler-fetch-DDSPIzWT.js +1 -0
  118. package/dist/packem_shared/base-handler-node-C83nCFpv.js +1 -0
  119. package/dist/packem_shared/claudeCopyFile-CMKFZHFh.js +1 -0
  120. package/dist/packem_shared/cloudflare-CijqmNaq.js +1 -0
  121. package/dist/packem_shared/copyFile-B7PNh9O7.js +1 -0
  122. package/dist/packem_shared/copyFile-Q5eYZIU5.js +1 -0
  123. package/dist/packem_shared/createResponsesFileTools-SU-K9JG4.js +1 -0
  124. package/dist/packem_shared/createRetryWrapper-BM8PL0cI.js +1 -0
  125. package/dist/packem_shared/detect-file-type-go3r-MOD.js +1 -0
  126. package/dist/packem_shared/digitalOcean-BE_d_CcF.js +1 -0
  127. package/dist/packem_shared/disk-storage-DEOi12bM.js +1 -0
  128. package/dist/packem_shared/{executors-BDzMjc4y.js → executors-DgKT6b1T.js} +1 -1
  129. package/dist/packem_shared/{executors.d-B9dIy3NT.d.ts → executors.d-HWHR3Ids.d.ts} +1 -6
  130. package/dist/packem_shared/exoscale-BzXbsZ3A.js +1 -0
  131. package/dist/packem_shared/{filebase-CsFYJIwB.js → filebase-pfolz904.js} +1 -1
  132. package/dist/packem_shared/{files.d-CmSZi3M0.d.ts → files.d-DuIceNg2.d.ts} +1 -1
  133. package/dist/packem_shared/gcs-meta-storage-A5uvIda3.js +1 -0
  134. package/dist/packem_shared/{get-file-status-y3wTtDQs.js → get-file-status-B8WmWzcM.js} +1 -1
  135. package/dist/packem_shared/getFormatFromContentType-BAVdaQ0o.js +1 -0
  136. package/dist/packem_shared/has-content-96mmyLn2.js +1 -0
  137. package/dist/packem_shared/headers-erjZrwbT.js +26 -0
  138. package/dist/packem_shared/hetzner-CaLW6ANw.js +1 -0
  139. package/dist/packem_shared/{ibmCos-j-3TfJ5p.js → ibmCos-Dbcs7XEJ.js} +1 -1
  140. package/dist/packem_shared/idriveE2-BiiGl7tr.js +1 -0
  141. package/dist/packem_shared/index-DKzU1HON.js +5 -0
  142. package/dist/packem_shared/internal-Zb__DDsV.js +1 -0
  143. package/dist/packem_shared/is-expired-CZlgTFFz.js +1 -0
  144. package/dist/packem_shared/local-meta-storage-Ca6WrUmN.js +1 -0
  145. package/dist/packem_shared/{local-meta-storage.d-cRTXr1kb.d.ts → local-meta-storage.d-CYWYyCUo.d.ts} +1 -2
  146. package/dist/packem_shared/{media-transformer.d-C8tn4J2Z.d.ts → media-transformer.d-Co37isNg.d.ts} +2 -2
  147. package/dist/packem_shared/minio-CC_RGR-q.js +1 -0
  148. package/dist/packem_shared/multipart-base-0AXqLN-B.js +1 -0
  149. package/dist/packem_shared/oauth-refresh-Cf1z47zf.js +1 -0
  150. package/dist/packem_shared/{oracleCloud-DslqNpn6.js → oracleCloud-eAWm6voZ.js} +1 -1
  151. package/dist/packem_shared/{ovhCloud-CMHE6uLV.js → ovhCloud-D00DprwO.js} +1 -1
  152. package/dist/packem_shared/part-match-Cb6xL9eN.js +1 -0
  153. package/dist/packem_shared/path-CxEa27Rz-DSh0_A5o.js +1 -0
  154. package/dist/packem_shared/posix-dirname-CSjB98Q5.js +1 -0
  155. package/dist/packem_shared/response-builder-tJ84C7n4.js +1 -0
  156. package/dist/packem_shared/rest-base-CzhSrUnH.js +1 -0
  157. package/dist/packem_shared/{restOpenApiSpec-Csv513qf.js → restOpenApiSpec-BNBrZFuE.js} +1 -1
  158. package/dist/packem_shared/s3-base-storage-DuHVKzSw.js +1 -0
  159. package/dist/packem_shared/{s3-base-storage.d-ks99NSs-.d.ts → s3-base-storage.d-BmuspwCF.d.ts} +1 -1
  160. package/dist/packem_shared/scaleway-Dms2IqTd.js +1 -0
  161. package/dist/packem_shared/{sharedErrorSchemaObject-YN65aAKj.js → sharedErrorSchemaObject-GTCM7U0s.js} +1 -1
  162. package/dist/packem_shared/{storage-DR7qdwBN.js → storage-uypoNkqu.js} +1 -1
  163. package/dist/packem_shared/{storage.d-DwdJrArF.d.ts → storage.d-C9EdfTf1.d.ts} +1 -1
  164. package/dist/packem_shared/storj-DzEePQoh.js +1 -0
  165. package/dist/packem_shared/sync-ClnPrYjk.js +1 -0
  166. package/dist/packem_shared/tencent-7P8z8AwE.js +1 -0
  167. package/dist/packem_shared/tigris-DlNWhmsM.js +1 -0
  168. package/dist/packem_shared/{transformOpenApiSpec-CIEAgpBD.js → transformOpenApiSpec-Bcnw9LVy.js} +1 -1
  169. package/dist/packem_shared/{tus-base.d-BKBoJVy0.d.ts → tus-base.d-Dgnbivbj.d.ts} +3 -8
  170. package/dist/packem_shared/{tusOpenApiSpec-D96B03t5.js → tusOpenApiSpec-BU8nhLH2.js} +1 -1
  171. package/dist/packem_shared/{types.d-BEUv414z.d.ts → types.d-D1TIRqKW.d.ts} +1 -1
  172. package/dist/packem_shared/{types.d-D7Zlz5RE.d.ts → types.d-D6Jkz0Sp.d.ts} +2 -2
  173. package/dist/packem_shared/{types.d-B1_xZIhu.d.ts → types.d-ZrDWKyVi.d.ts} +1 -2
  174. package/dist/packem_shared/update-size-Dxc1hvbI.js +1 -0
  175. package/dist/packem_shared/vultr-Crvmg314.js +1 -0
  176. package/dist/packem_shared/waitForStorage-afkqWeuz.js +1 -0
  177. package/dist/packem_shared/wasabi-CyCMxoUT.js +1 -0
  178. package/dist/packem_shared/{xhrOpenApiSpec-DQR4h6M8.js → xhrOpenApiSpec-xDSkxm2d.js} +1 -1
  179. package/dist/packem_shared/yandex-D1HwCz7g.js +1 -0
  180. package/dist/storage/aws/clients/index.js +1 -1
  181. package/dist/storage/aws/index.d.ts +3 -3
  182. package/dist/storage/aws/index.js +1 -1
  183. package/dist/storage/aws-light/index.d.ts +2 -2
  184. package/dist/storage/aws-light/index.js +1 -1
  185. package/dist/storage/azure/index.d.ts +2 -2
  186. package/dist/storage/azure/index.js +1 -1
  187. package/dist/storage/box/index.d.ts +3 -3
  188. package/dist/storage/box/index.js +1 -1
  189. package/dist/storage/bun-s3/index.d.ts +2 -2
  190. package/dist/storage/bun-s3/index.js +1 -1
  191. package/dist/storage/bunny/index.d.ts +3 -3
  192. package/dist/storage/bunny/index.js +1 -1
  193. package/dist/storage/cloudinary/index.d.ts +3 -3
  194. package/dist/storage/cloudinary/index.js +1 -1
  195. package/dist/storage/dropbox/index.d.ts +3 -3
  196. package/dist/storage/dropbox/index.js +1 -1
  197. package/dist/storage/firebase/index.d.ts +2 -2
  198. package/dist/storage/firebase/index.js +1 -1
  199. package/dist/storage/ftp/index.d.ts +3 -3
  200. package/dist/storage/ftp/index.js +1 -1
  201. package/dist/storage/gcs/index.d.ts +2 -2
  202. package/dist/storage/gcs/index.js +1 -1
  203. package/dist/storage/google-drive/index.d.ts +3 -3
  204. package/dist/storage/google-drive/index.js +1 -1
  205. package/dist/storage/local/index.d.ts +148 -4
  206. package/dist/storage/local/index.js +1 -1
  207. package/dist/storage/memory/index.d.ts +93 -3
  208. package/dist/storage/memory/index.js +1 -1
  209. package/dist/storage/netlify-blob/index.d.ts +3 -3
  210. package/dist/storage/netlify-blob/index.js +1 -1
  211. package/dist/storage/onedrive/index.d.ts +4 -4
  212. package/dist/storage/onedrive/index.js +1 -1
  213. package/dist/storage/pocketbase/index.d.ts +2 -2
  214. package/dist/storage/pocketbase/index.js +1 -1
  215. package/dist/storage/sftp/index.d.ts +3 -3
  216. package/dist/storage/sftp/index.js +1 -1
  217. package/dist/storage/sharepoint/index.d.ts +3 -3
  218. package/dist/storage/sharepoint/index.js +1 -1
  219. package/dist/storage/supabase/index.d.ts +3 -3
  220. package/dist/storage/supabase/index.js +1 -1
  221. package/dist/storage/uploadthing/index.d.ts +2 -2
  222. package/dist/storage/uploadthing/index.js +1 -1
  223. package/dist/storage/vercel-blob/index.d.ts +3 -3
  224. package/dist/storage/vercel-blob/index.js +1 -1
  225. package/dist/transformer/audio-transformer.d.ts +2 -2
  226. package/dist/transformer/audio-transformer.js +1 -1
  227. package/dist/transformer/image-transformer.d.ts +2 -2
  228. package/dist/transformer/image-transformer.js +1 -1
  229. package/dist/transformer/index.d.ts +3 -3
  230. package/dist/transformer/index.js +1 -1
  231. package/dist/transformer/video-transformer.d.ts +2 -2
  232. package/dist/transformer/video-transformer.js +1 -1
  233. package/package.json +19 -18
  234. package/dist/packem_shared/AbstractBaseStorage-CLsYmMZg.js +0 -1
  235. package/dist/packem_shared/AwsLightFile-CpZrubaV.js +0 -1
  236. package/dist/packem_shared/AwsLightMetaStorage-DPqJ9LTr.js +0 -1
  237. package/dist/packem_shared/AwsLightStorage-DGSPFUqr.js +0 -1
  238. package/dist/packem_shared/AzureFile-DFSaVe25.js +0 -1
  239. package/dist/packem_shared/AzureSMetaStorage-ByzM6Aix.js +0 -1
  240. package/dist/packem_shared/AzureStorage-DvKk_hhz.js +0 -1
  241. package/dist/packem_shared/BaseTransformer-Buw5lX_3.js +0 -1
  242. package/dist/packem_shared/BoxFile-CseIoPW1.js +0 -1
  243. package/dist/packem_shared/BoxMetaStorage-CJsyeQ63.js +0 -1
  244. package/dist/packem_shared/BoxStorage-CmM95wi2.js +0 -1
  245. package/dist/packem_shared/BunS3File-BcYmsz1n.js +0 -1
  246. package/dist/packem_shared/BunS3MetaStorage-CJsyeQ63.js +0 -1
  247. package/dist/packem_shared/BunnyFile-BgEOlcYI.js +0 -1
  248. package/dist/packem_shared/BunnyMetaStorage-CJsyeQ63.js +0 -1
  249. package/dist/packem_shared/BunnyStorage-eZ1QDVaY.js +0 -1
  250. package/dist/packem_shared/CloudinaryFile-Bo5B-vM1.js +0 -1
  251. package/dist/packem_shared/CloudinaryMetaStorage-Bv_YCZ0Q.js +0 -1
  252. package/dist/packem_shared/CloudinaryStorage-CpH2f0Fv.js +0 -1
  253. package/dist/packem_shared/DiskStorage-DzjjqCzo.js +0 -1
  254. package/dist/packem_shared/DiskStorageWithChecksum-MZkDEyts.js +0 -1
  255. package/dist/packem_shared/DropboxFile-BFb7eOzy.js +0 -1
  256. package/dist/packem_shared/DropboxMetaStorage-CJsyeQ63.js +0 -1
  257. package/dist/packem_shared/DropboxStorage-BB9NoWK2.js +0 -1
  258. package/dist/packem_shared/File-W8aOo15X.js +0 -1
  259. package/dist/packem_shared/Files-DyMJ9FPN.js +0 -1
  260. package/dist/packem_shared/FirebaseFile-BLaBxa2A.js +0 -1
  261. package/dist/packem_shared/FirebaseMetaStorage-Bv_YCZ0Q.js +0 -1
  262. package/dist/packem_shared/FirebaseStorage-BgbxzYNC.js +0 -2
  263. package/dist/packem_shared/FtpFile-ClWDYnt2.js +0 -1
  264. package/dist/packem_shared/FtpMetaStorage-CJsyeQ63.js +0 -1
  265. package/dist/packem_shared/FtpStorage-CNqXDz7P.js +0 -1
  266. package/dist/packem_shared/GCSFile-Cero7qZN.js +0 -1
  267. package/dist/packem_shared/GCSMetaStorage-Cm_XzR0C.js +0 -1
  268. package/dist/packem_shared/GCStorage-DcvsI7eu.js +0 -1
  269. package/dist/packem_shared/GoogleDriveFile-DHpLhzg9.js +0 -1
  270. package/dist/packem_shared/GoogleDriveMetaStorage-B0gLF7Io.js +0 -1
  271. package/dist/packem_shared/LocalMetaStorage-CcGfFG39.js +0 -1
  272. package/dist/packem_shared/MediaTransformer-D2kUsklW.js +0 -1
  273. package/dist/packem_shared/MemoryMetaStorage-Ksgh9pe7.js +0 -1
  274. package/dist/packem_shared/Metadata-B7CcBueg.js +0 -1
  275. package/dist/packem_shared/Multipart-C35TR2qL.js +0 -1
  276. package/dist/packem_shared/NetlifyBlobFile-DoFhkzaH.js +0 -1
  277. package/dist/packem_shared/NetlifyBlobMetaStorage-Bv_YCZ0Q.js +0 -1
  278. package/dist/packem_shared/NetlifyBlobStorage-CZsr_0DF.js +0 -1
  279. package/dist/packem_shared/NoOpMetrics-BLo6u4NY.js +0 -1
  280. package/dist/packem_shared/OneDriveFile-CNNJYI43.js +0 -1
  281. package/dist/packem_shared/OneDriveMetaStorage-B0gLF7Io.js +0 -1
  282. package/dist/packem_shared/OneDriveStorage-B8qFgMq1.js +0 -1
  283. package/dist/packem_shared/OpenTelemetryMetrics-DJDQsNKp.js +0 -1
  284. package/dist/packem_shared/PocketBaseFile-DpJpxl3e.js +0 -1
  285. package/dist/packem_shared/PocketBaseMetaStorage-Cm3v8g1-.js +0 -1
  286. package/dist/packem_shared/PocketBaseStorage-D2vMN-oY.js +0 -1
  287. package/dist/packem_shared/Rest-BrEMYgxZ.js +0 -1
  288. package/dist/packem_shared/Rest-aPVP2ww1.js +0 -1
  289. package/dist/packem_shared/S3File-CpZrubaV.js +0 -1
  290. package/dist/packem_shared/S3MetaStorage-CMonflzp.js +0 -1
  291. package/dist/packem_shared/S3Storage-CTe_BMDl.js +0 -1
  292. package/dist/packem_shared/SftpFile-ClWDYnt2.js +0 -1
  293. package/dist/packem_shared/SftpMetaStorage-CJsyeQ63.js +0 -1
  294. package/dist/packem_shared/SftpStorage-BKeAzuej.js +0 -1
  295. package/dist/packem_shared/SharePointFile-Blz9FS4h.js +0 -1
  296. package/dist/packem_shared/SharePointMetaStorage-CJsyeQ63.js +0 -1
  297. package/dist/packem_shared/SupabaseFile-Bo5B-vM1.js +0 -1
  298. package/dist/packem_shared/SupabaseMetaStorage-B0gLF7Io.js +0 -1
  299. package/dist/packem_shared/SupabaseStorage-CmGQjqXf.js +0 -1
  300. package/dist/packem_shared/TUS_RESUMABLE-CyTSRvPU.js +0 -1
  301. package/dist/packem_shared/Tus-D9c7KDnl.js +0 -1
  302. package/dist/packem_shared/UploadThingFile-BTFMpcIA.js +0 -1
  303. package/dist/packem_shared/UploadThingMetaStorage-Bv_YCZ0Q.js +0 -1
  304. package/dist/packem_shared/UploadThingStorage-DZ4zNvDH.js +0 -1
  305. package/dist/packem_shared/ValidationError-3B06DFyE.js +0 -1
  306. package/dist/packem_shared/VercelBlobFile-CVQwKlZk.js +0 -1
  307. package/dist/packem_shared/VercelBlobMetaStorage-CJsyeQ63.js +0 -1
  308. package/dist/packem_shared/VercelBlobStorage-DDNEofR3.js +0 -1
  309. package/dist/packem_shared/_commonjsHelpers-CWAkuNXM.js +0 -1
  310. package/dist/packem_shared/agentsCopyFile-Dl5iffdH.js +0 -1
  311. package/dist/packem_shared/akamai-DthkaFul.js +0 -1
  312. package/dist/packem_shared/alibaba-BEi25O1g.js +0 -1
  313. package/dist/packem_shared/approval-fVHwBp7u.js +0 -1
  314. package/dist/packem_shared/aws-light-meta-storage-DGrn72VJ.js +0 -4
  315. package/dist/packem_shared/azure-meta-storage-ClbEsfI4.js +0 -1
  316. package/dist/packem_shared/backblaze-m1N5NZ9q.js +0 -1
  317. package/dist/packem_shared/base-handler-core-BJP9jHCE.js +0 -1
  318. package/dist/packem_shared/base-handler-fetch-yrYrukwL.js +0 -1
  319. package/dist/packem_shared/base-handler-node-C8P9rkaH.js +0 -1
  320. package/dist/packem_shared/claudeCopyFile-BX9O4ORk.js +0 -1
  321. package/dist/packem_shared/cloudflare-CdUTErlo.js +0 -1
  322. package/dist/packem_shared/copyFile-49FtxXcm.js +0 -1
  323. package/dist/packem_shared/copyFile-BUPezT_c.js +0 -1
  324. package/dist/packem_shared/createResponsesFileTools-6Tvt2PNr.js +0 -1
  325. package/dist/packem_shared/createRetryWrapper-DgmeHPNF.js +0 -1
  326. package/dist/packem_shared/detect-file-type-BA7UBLKA.js +0 -1
  327. package/dist/packem_shared/digitalOcean-B2uB6pgz.js +0 -1
  328. package/dist/packem_shared/disk-storage-DqnnFQAQ.js +0 -1
  329. package/dist/packem_shared/disk-storage-with-checksum.d-Dgwyza8a.d.ts +0 -146
  330. package/dist/packem_shared/exoscale-BDa1Gjth.js +0 -1
  331. package/dist/packem_shared/gcs-meta-storage-Bu2upyHK.js +0 -1
  332. package/dist/packem_shared/getFormatFromContentType-DCTTPQHm.js +0 -1
  333. package/dist/packem_shared/has-content-50BsqrWw.js +0 -1
  334. package/dist/packem_shared/headers-BAiAKekR.js +0 -26
  335. package/dist/packem_shared/hetzner-BGGFiRGD.js +0 -1
  336. package/dist/packem_shared/idriveE2-C6pQ5pQ0.js +0 -1
  337. package/dist/packem_shared/index-nZWCQrSe.js +0 -5
  338. package/dist/packem_shared/internal-D_cZIFwI.js +0 -1
  339. package/dist/packem_shared/is-expired-CBEk6XBi.js +0 -1
  340. package/dist/packem_shared/local-meta-storage-BELb1YwO.js +0 -11
  341. package/dist/packem_shared/memory-storage.d-BNZvDG1b.d.ts +0 -93
  342. package/dist/packem_shared/minio-NKquuBfS.js +0 -1
  343. package/dist/packem_shared/multipart-base-BOzY19lb.js +0 -1
  344. package/dist/packem_shared/oauth-refresh-EdGzlcOZ.js +0 -1
  345. package/dist/packem_shared/part-match-D-9dGX42.js +0 -1
  346. package/dist/packem_shared/path-C-OWflAo-_mqb5p5d.js +0 -1
  347. package/dist/packem_shared/posix-dirname-CfpH5wZi.js +0 -1
  348. package/dist/packem_shared/response-builder-CbSA8qPa.js +0 -1
  349. package/dist/packem_shared/rest-base-BQ_dhWyV.js +0 -1
  350. package/dist/packem_shared/s3-base-storage-CX94H-Za.js +0 -1
  351. package/dist/packem_shared/scaleway-U1In3v70.js +0 -1
  352. package/dist/packem_shared/storj-Cb59q9kF.js +0 -1
  353. package/dist/packem_shared/sync-DhR3536K.js +0 -1
  354. package/dist/packem_shared/tencent-Q1y2GENc.js +0 -1
  355. package/dist/packem_shared/tigris-BELKoyyp.js +0 -1
  356. package/dist/packem_shared/update-size-DuNuLyxj.js +0 -1
  357. package/dist/packem_shared/vultr-B491cQ4e.js +0 -1
  358. package/dist/packem_shared/waitForStorage-ByQmG4xF.js +0 -1
  359. package/dist/packem_shared/wasabi-DFrwIoab.js +0 -1
  360. package/dist/packem_shared/yandex-CwzHuEKP.js +0 -1
@@ -0,0 +1 @@
1
+ import f from"./AzureFile-DoUVXQMI.js";import{c as b,A as C,b as m,a as y}from"./azure-meta-storage-DmBO5MmP.js";import{G as w}from"./path-CxEa27Rz-DSh0_A5o.js";import{a as T}from"./detect-file-type-go3r-MOD.js";import{throwErrorCode as u,ERRORS as h}from"./ERRORS-olUcTqo2.js";import{B as S,t as O}from"./storage-uypoNkqu.js";import{L as k}from"./local-meta-storage-Ca6WrUmN.js";import{p as E}from"./part-match-Cb6xL9eN.js";import{h as B}from"./has-content-96mmyLn2.js";import{g as F}from"./get-file-status-B8WmWzcM.js";class U extends S{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:i,client:e,sasToken:n,signer:l}=b(t);this.client=e,this.signer=l,this.sasToken=n,this.anonymous=i,this.containerClient=this.client.getContainerClient(t.containerName),this.root=t.root?w(t.root).replace(/^\//,""):"";const s={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:r=>{const a=r;if(a.statusCode&&[408,429,500,502,503,504].includes(a.statusCode))return!0;if(r instanceof Error){const o=a.code;if(o==="ECONNRESET"||o==="ETIMEDOUT"||o==="ENOTFOUND"||o==="ECONNREFUSED")return!0}},...t.retryConfig};if(this.resolvedRetryConfig=s,t.metaStorage)this.meta=t.metaStorage;else{let r={...t,...t.metaStorageConfig,logger:this.logger};if("directory"in r)this.logger?.debug("Using local meta storage"),this.meta=new k(r);else{const o=t.metaStorageConfig;o&&["accountKey","accountName","connectionString","credential","endpoint","sasToken"].some(c=>c in o)||(r={...r,client:this.client}),this.meta=new C(r)}}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(r=>{this.logger?.error("Storage access check failed: %O",r)})}getRetryConfig(){return this.resolvedRetryConfig}async create(t,i){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const a=typeof t.ttl=="string"?O(t.ttl):t.ttl;a!==void 0&&(e.expiredAt=Date.now()+a)}const n=new f(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 l=this.containerClient.getBlockBlobClient(this.getFullPath(n.name)),s={};for(const[a,o]of Object.entries(n.metadata||{}))s[a]=JSON.stringify(o);const r=await this.runOperation(i,a=>l.uploadData(Buffer.from(""),{abortSignal:a,blobHTTPHeaders:{blobContentType:n.contentType},metadata:{name:n.name,originalName:n.originalName,...s}}));return r.requestId===void 0?u(h.FILE_ERROR,"azure create upload error"):(n.requestId=r.requestId,n.uri=r._response.headers.get("location"),n.bytesWritten=0,await this.saveMeta(n),n.status="created",await this.onCreate(n),n)})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await this.runOperation(i,l=>this.containerClient.getBlockBlobClient(this.getFullPath(e.name)).deleteIfExists({abortSignal:l})),await this.deleteMeta(e.id);const n={...e};return await this.onDelete(n),n})}async deleteBatch(t,i){if(t.length===0)return{failed:[],failedCount:0,successful:[],successfulCount:0};const e=256;try{const n=this.client.getBlobBatchClient(),l=[],s=[];for(let r=0;r<t.length;r+=e){const a=t.slice(r,r+e),o=a.map(c=>this.containerClient.getBlockBlobClient(this.getFullPath(c))),g=await this.runOperation(i,c=>n.deleteBlobs(o,{abortSignal:c}));for(const[c,d]of g.subResponses.entries()){const p=a[c];d.status===202||d.status===404?l.push({id:p,name:p,status:"deleted"}):s.push({error:d.errorCode??`HTTP ${d.status}`,id:p})}}return await Promise.all(l.map(async r=>{try{await this.deleteMeta(r.id),await this.onDelete(r)}catch{}})),{failed:s,failedCount:s.length,successful:l,successfulCount:l.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,i)}}async move(t,i,e){return this.instrumentOperation("move",async()=>{const n=await this.copy(t,i,e),l=this.getFullPath(t);return await this.runOperation(e,s=>this.containerClient.getBlockBlobClient(l).deleteIfExists({abortSignal:s})),n})}async write(t,i){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:o}=await T(t.body);a?.mime&&(e.contentType=a.mime),t.body=o}catch{}const l=this.containerClient.getBlockBlobClient(this.getFullPath(e.name)),s=new AbortController;t.body.on("error",()=>{s.abort()});const r=await this.runOperation(i,a=>{const o=a?AbortSignal.any([s.signal,a]):s.signal;return l.uploadStream(t.body,void 0,void 0,{abortSignal:o,blobHTTPHeaders:{blobContentType:e.contentType??"application/octet-stream"},metadata:e.metadata})},{replayable:!1});if(r.requestId===void 0)return u(h.FILE_ERROR,"azure write upload error");e.requestId=r.requestId,e.bytesWritten+=t.contentLength||0,e.status=F(e),e.status==="completed"&&(e.uri=r._response.headers.get("location"),await this.deleteMeta(e.id))}}finally{await this.unlock(t.id,n)}return e})}async get({id:t},i){return this.instrumentOperation("get",async()=>{const e=this.containerClient.getBlockBlobClient(this.getFullPath(t));if(!await this.runOperation(i,d=>e.exists({abortSignal:d})))try{return await this.getMeta(t),u(h.GONE)}catch{return u(h.FILE_NOT_FOUND)}const l=await this.runOperation(i,d=>e.getProperties({abortSignal:d})),{contentLength:s,contentType:r,etag:a,expiresOn:o,lastModified:g,metadata:c}=l;return{content:await this.runOperation(i,d=>e.downloadToBuffer(0,void 0,{abortSignal:d})),contentType:r,ETag:a,expiredAt:o,id:t,metadata:c||{},modifiedAt:g,name:c?.name||t,originalName:c?.originalName||"",size:s}})}async exists({id:t},i){return this.instrumentOperation("exists",async()=>{try{await this.getMeta(t);const e=this.containerClient.getBlockBlobClient(this.getFullPath(t));return await this.runOperation(i,l=>e.exists({abortSignal:l}))}catch{return!1}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const n=this.containerClient.getBlockBlobClient(this.getFullPath(t));if(!await this.runOperation(e,g=>n.exists({abortSignal:g})))try{return await this.getMeta(t),u(h.GONE)}catch{return u(h.FILE_NOT_FOUND)}const s=this.containerClient.getBlockBlobClient(this.getFullPath(i));let r=n.url;this.signer?.kind==="userDelegation"?r=await m(this.containerClient.getBlobClient(this.getFullPath(t)),this.signer,{expiresIn:300,permissions:"r"}):this.sasToken&&(r=y(n.url,this.sasToken));const a=await this.runOperation(e,g=>s.beginCopyFromURL(r,{abortSignal:g}));return await this.runOperation(e,()=>a.pollUntilDone()),{...await this.getMeta(t),id:i,name:i}})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const e=[];let n=!0,l;for(;n&&e.length<t;)try{const s=Math.min(t-e.length,1e3),a=(await this.runOperation(i,o=>this.containerClient.listBlobsFlat({abortSignal:o,includeMetadata:!0,prefix:this.root}).byPage({continuationToken:l,maxPageSize:s}).next())).value;if(a!==void 0&&"segment"in a){for(const o of a.segment.blobItems)if(!o.deleted&&(e.push({createdAt:o.properties.createdOn,id:o.name,modifiedAt:o.properties.lastModified}),e.length>=t))break}n=a?.continuationToken!==void 0,n&&(l=a.continuationToken)}catch(s){const r=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(r),s}return e},{limit:t})}async getReadUrl(t,i){const e=this.containerClient.getBlobClient(this.getFullPath(t));return this.signer?m(e,this.signer,{expiresIn:i?.expiresIn??3600,permissions:"r",...i?.responseContentDisposition&&{contentDisposition:i.responseContentDisposition},...i?.responseContentType&&{contentType:i.responseContentType}}):i?.responseContentDisposition!==void 0||i?.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,i){if(i?.contentType!==void 0||i?.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:i?.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{U as default};
@@ -0,0 +1 @@
1
+ import{Readable as o}from"node:stream";import s from"mime";import{N as n}from"./cache-Cw3QjoVN.js";class m{constructor(e,r,t){this.storage=e,this.config=r,this.logger=t,this.cache=r.cache??new n}storage;config;logger;cache;async transformStream(e,r){const t=await this.transform(e,r);if(t&&"buffer"in t){const{buffer:a}=t;return{headers:{"Content-Length":a.length.toString(),"Content-Type":this.getContentTypeFromResult(t)},size:a.length,stream:o.from(a)}}throw new Error("Streaming transformation not supported for this transformer")}clearCache(e){if(!e){this.cache?.clear?.();return}if(!this.cache)return;if(typeof this.cache.keys!="function"){this.logger?.warn?.("clearCache(fileId) cannot scope its invalidation because the cache does not implement keys(); falling back to full clear()"),this.cache.clear?.();return}const r=`${e}:`;for(const t of this.cache.keys())typeof t=="string"&&(t===e||t.startsWith(r))&&this.cache.delete(t)}getCacheStats(){return{maxSize:-1,size:this.cache?.size??0}}getContentTypeFromResult(e){if(e?.format){const r=s.getType(e.format);if(r)return r}return"application/octet-stream"}}export{m as default};
@@ -0,0 +1 @@
1
+ import e from"./File-DLAa0hBv.js";class o extends e{boxFileId;eTag;publicUrl}export{o as default};
@@ -0,0 +1 @@
1
+ import{L as a}from"./local-meta-storage-Ca6WrUmN.js";class r extends a{constructor(t){super(t)}}export{r as default};
@@ -0,0 +1 @@
1
+ import f from"./BoxFile-CKKRYACc.js";import x from"./BoxMetaStorage-BI-G6aeO.js";import{Readable as E}from"node:stream";import{BoxDeveloperTokenAuth as I,BoxClient as w,OAuthConfig as T,BoxOAuth as O,CcgConfig as b,BoxCcgAuth as L,BoxJwtAuth as S,JwtConfig as F}from"box-typescript-sdk-gen";import{throwErrorCode as B,ERRORS as C}from"./ERRORS-olUcTqo2.js";import{B as _}from"./storage-uypoNkqu.js";import{g as v}from"./get-file-status-B8WmWzcM.js";import{u as U}from"./update-size-Dxc1hvbI.js";import{p as D}from"./part-match-Cb6xL9eN.js";import{h as A}from"./has-content-96mmyLn2.js";const R="0",M=50*1024*1024,p={ensureReady:()=>Promise.resolve()},H=o=>{let e=0,i=o.length;for(;e<i&&o[e]==="/";)e+=1;for(;i>e&&o[i-1]==="/";)i-=1;return e===0&&i===o.length?o:o.slice(e,i)},m=o=>{const e=H(o);if(!e)throw new Error("Box: key must not be empty");const i=e.split("/").filter(n=>n.length>0),t=i.pop()??"";if(!t)throw new Error(`Box: key "${o}" has no file name segment`);return{leaf:t,parents:i}},N=async o=>{const e=[];for await(const i of o)e.push(Buffer.from(i));return Buffer.concat(e)},g=o=>E.from(o),P=o=>"configJsonString"in o?F.fromConfigJsonString(o.configJsonString):F.fromConfigFile(o.configFilePath),j=o=>[o.developerToken,o.oauth,o.ccg,o.jwt].filter(e=>e!==void 0).length,z=o=>{if(o.client)return{authHandle:p,client:o.client};if(j(o)>1)throw new Error("Box storage: pass exactly one of `developerToken`, `oauth`, `ccg`, or `jwt`.");if(o.developerToken!==void 0){const i=new I({token:o.developerToken});return{authHandle:p,client:new w({auth:i})}}if(o.oauth){const{clientId:i,clientSecret:t,refreshToken:n}=o.oauth,a=new T({clientId:i,clientSecret:t}),s=new O({config:a});let l;const d=async()=>{await s.tokenStorage.store({accessToken:"",refreshToken:n})};return{authHandle:{ensureReady:()=>(l||(l=d()),l)},client:new w({auth:s})}}if(o.ccg){const{clientId:i,clientSecret:t,enterpriseId:n,userId:a}=o.ccg;if(!n&&!a)throw new Error("Box storage: `ccg` auth requires either `enterpriseId` or `userId`.");const s=new b({clientId:i,clientSecret:t,...n!==void 0&&{enterpriseId:n},...a!==void 0&&{userId:a}}),l=new L({config:s});return{authHandle:p,client:new w({auth:l})}}if(o.jwt){const i=P(o.jwt),t=new S({config:i});return{authHandle:p,client:new w({auth:t})}}const e=process.env.BOX_DEVELOPER_TOKEN;if(e){const i=new I({token:e});return{authHandle:p,client:new w({auth:i})}}throw new Error("Box storage: missing auth. Pass `client`, `developerToken`, `oauth`, `ccg`, or `jwt`. Env fallback: BOX_DEVELOPER_TOKEN.")},K=o=>{if(o&&typeof o=="object"){const e=o,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=o=>{if(o&&typeof o=="object"){const e=o,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 _{static name="box";checksumTypes=[];meta;authHandle;client;fileIdCache;folderIdCache;publicByDefault;rootFolderId;constructor(e){super(e),this.rootFolderId=e.rootFolderId??R,this.publicByDefault=e.publicByDefault??!1;const i=z(e);this.client=i.client,this.authHandle=i.authHandle,this.folderIdCache=new Map,this.fileIdCache=new Map,this.meta=e.metaStorage??new x(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new f(e);t.name=this.namingFunction(t),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=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&&U(t,e.size),!D(e,t))throw new Error("File part does not match");const n=await this.lock(e.id);try{if(A(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");await this.authHandle.ensureReady();const a=await N(e.body),s=t.name||t.id,{leaf:l,parents:d}=m(s),r=await this.resolveFolderId(d,{create:!0},i),c=await this.resolveExistingFileForUpload(s,r,l,i),h=await this.performUpload(c,r,l,a,i);h.id&&(this.fileIdCache.set(s,h.id),this.publicByDefault&&await this.ensureSharedLink(h.id,i)),t.bytesWritten=a.length,t.size=a.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,n)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const n=t?.name??e;await this.authHandle.ensureReady();try{const a=t?.boxFileId??await this.resolveFileId(n,i);await this.runOperation(i,()=>this.client.files.deleteFileById(a)),this.fileIdCache.delete(n)}catch(a){if(!K(a))throw a}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new f({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,n=e;try{t=await this.checkIfExpired(await this.getMeta(e)),n=t.name??e}catch{}await this.authHandle.ensureReady();const a=t?.boxFileId??await this.resolveFileId(n,i),s=await this.runOperation(i,()=>this.client.files.getFileById(a)),l=await this.runOperation(i,()=>this.client.downloads.getDownloadFileUrl(a)),d=await this.runOperation(i,()=>fetch(l));if(!d.ok)throw new Error(`Box: download fetch failed (${d.status})`);const r=await this.runOperation(i,()=>d.arrayBuffer()),c=Buffer.from(r);return{content:c,contentType:t?.contentType??"application/octet-stream",ETag:t?.ETag??s.etag??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??s.modifiedAt??s.contentModifiedAt??void 0,name:t?.name??s.name??n,originalName:t?.originalName??s.name??n,size:t?.size??s.size??c.length}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{await this.authHandle.ensureReady();const n=await this.resolveFileId(e,t),{leaf:a,parents:s}=m(i),l=await this.resolveFolderId(s,{create:!0},t),d=await this.runOperation(t,()=>this.client.files.copyFile(n,{name:a,parent:{id:l}}));d.id&&this.fileIdCache.set(i,d.id);const r=new f({contentType:"application/octet-stream",metadata:{},originalName:i});return r.id=i,r.name=i,r.boxFileId=d.id,r.eTag=d.etag??void 0,r.ETag=d.etag??void 0,r})}async move(e,i,t){return this.instrumentOperation("move",async()=>{await this.authHandle.ensureReady();const n=await this.resolveFileId(e,t),{leaf:a,parents:s}=m(i),l=await this.resolveFolderId(s,{create:!0},t),d=await this.runOperation(t,()=>this.client.files.updateFileById(n,{requestBody:{name:a,parent:{id:l}}}));this.fileIdCache.delete(e),d.id&&this.fileIdCache.set(i,d.id);const r=new f({contentType:"application/octet-stream",metadata:{},originalName:i});r.id=i,r.name=i,r.boxFileId=d.id,r.eTag=d.etag??void 0,r.ETag=d.etag??void 0;try{await this.deleteMeta(e)}catch{}return r})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{await this.authHandle.ensureReady();const t=[];let n=0;const a=Math.min(e,1e3);for(;t.length<e;){const l=(await this.runOperation(i,()=>this.client.folders.getFolderItems(this.rootFolderId,{queryParams:{fields:["id","name","size","modified_at","etag","type"],limit:a,offset:n}}))).entries??[];for(const d of l){const r=d;if(r.type!=="file"||!r.id||!r.name)continue;this.fileIdCache.set(r.name,r.id);const c=new f({contentType:"application/octet-stream",metadata:{},originalName:r.name});if(c.id=r.name,c.name=r.name,c.boxFileId=r.id,c.eTag=r.etag??void 0,c.ETag=r.etag??void 0,c.size=r.size??0,c.modifiedAt=r.modifiedAt??r.contentModifiedAt??void 0,t.push(c),t.length>=e)break}if(l.length<a)break;n+=l.length}return t},{limit:e})}async getReadUrl(e,i){if(i?.responseContentDisposition||i?.responseContentType)return B(C.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 B(C.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 n=0;const a=1e3;for(;;){const l=(await this.runOperation(t,()=>this.client.folders.getFolderItems(e,{queryParams:{fields:["id","name","type"],limit:a,offset:n}}))).entries??[];for(const d of l){const r=d;if(r.name===i&&r.id&&r.type)return{id:r.id,type:r.type}}if(l.length<a)return;n+=l.length}}folderCacheKey(e){return e.join("/")}async resolveFolderId(e,i,t){if(e.length===0)return this.rootFolderId;const n=this.folderCacheKey(e),a=this.folderIdCache.get(n);if(a)return a;let s=this.rootFolderId;const l=[];for(const d of e){l.push(d);const r=this.folderCacheKey(l),c=this.folderIdCache.get(r);if(c){s=c;continue}const h=await this.findChildByName(s,d,t);if(h&&h.type==="folder"){s=h.id,this.folderIdCache.set(r,s);continue}if(h&&h.type!=="folder")throw new Error(`Box: path segment "${d}" exists but is not a folder`);if(!i.create)throw new Error(`Box: folder "${l.join("/")}" not found`);try{const u=await this.runOperation(t,()=>this.client.folders.createFolder({name:d,parent:{id:s}}));if(!u.id)throw new Error(`Box: createFolder did not return an id for "${d}"`);s=u.id,this.folderIdCache.set(r,s)}catch(u){if(k(u)){const y=await this.findChildByName(s,d,t);if(y&&y.type==="folder"){s=y.id,this.folderIdCache.set(r,s);continue}}throw u}}return this.folderIdCache.set(n,s),s}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const{leaf:n,parents:a}=m(e),s=await this.resolveFolderId(a,{create:!1},i),l=await this.findChildByName(s,n,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,n){const a=this.fileIdCache.get(e);if(a)return a;const s=await this.findChildByName(i,t,n);if(s){if(s.type==="file")return this.fileIdCache.set(e,s.id),s.id;throw new Error(`Box: "${e}" already exists as a non-file (${s.type})`)}}async performUpload(e,i,t,n,a){if(n.byteLength>M)return await this.runOperation(a,()=>this.client.chunkedUploads.uploadBigFile(g(n),t,n.byteLength,i));if(e){const r=((await this.runOperation(a,()=>this.client.uploads.uploadFileVersion(e,{attributes:{name:t},file:g(n)}))).entries??[])[0];if(!r)throw new Error("Box: uploadFileVersion returned no file");return r}const l=((await this.runOperation(a,()=>this.client.uploads.uploadFile({attributes:{name:t,parent:{id:i}},file:g(n)}))).entries??[])[0];if(!l)throw new Error("Box: uploadFile returned no file");return l}async ensureSharedLink(e,i){try{const n=(await this.runOperation(i,()=>this.client.sharedLinksFiles.addShareLinkToFile(e,{sharedLink:{access:"open"}},{fields:"shared_link"}))).sharedLink,a=n?.downloadUrl??n?.url;return a||this.fetchSharedLinkUrl(e,i)}catch(t){if(k(t))return this.fetchSharedLinkUrl(e,i);throw t}}async fetchSharedLinkUrl(e,i){const n=(await this.runOperation(i,()=>this.client.sharedLinksFiles.getSharedLinkForFile(e,{fields:"shared_link"}))).sharedLink,a=n?.downloadUrl??n?.url;if(!a)throw new Error("Box: file has no shared link. Call write() with publicByDefault: true, or addShareLinkToFile via storage.raw.");return a}internalOnComplete=e=>this.deleteMeta(e.id)}export{ee as default};
@@ -0,0 +1 @@
1
+ import e from"./File-DLAa0hBv.js";class n extends e{bunS3ETag;bunS3Key}export{n as default};
@@ -0,0 +1 @@
1
+ import{L as a}from"./local-meta-storage-Ca6WrUmN.js";class r extends a{constructor(t){super(t)}}export{r 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-DR7qdwBN.js";import d from"./BunS3File-BcYmsz1n.js";import E from"./BunS3MetaStorage-CJsyeQ63.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 h from"./BunS3File-B2rczbY_.js";import w from"./BunS3MetaStorage-BI-G6aeO.js";import{Readable as S}from"node:stream";import{throwErrorCode as T,ERRORS as b,wrapStorageError as d}from"./ERRORS-olUcTqo2.js";import{B as E}from"./storage-uypoNkqu.js";import{g as m}from"./get-file-status-B8WmWzcM.js";import{u as k}from"./update-size-Dxc1hvbI.js";import{p as B}from"./part-match-Cb6xL9eN.js";import{h as O}from"./has-content-96mmyLn2.js";const c=s=>s.replace(/^\/+/u,""),I=async s=>{const e=[];for await(const i of s)e.push(Buffer.from(i));return Buffer.concat(e)},v=s=>{const e=s?.code;return typeof e=="string"&&/nosuchkey|notfound/iu.test(e)},u=(s,e)=>{const i=s?.code,t=typeof i=="string"?i:"";return/nosuchkey|notfound/iu.test(t)?d(s,{adapter:"Bun S3",operation:e,status:404}):/accessdenied|forbidden|ERR_S3_INVALID_SIGNATURE|ERR_S3_MISSING_CREDENTIALS/iu.test(t)?d(s,{adapter:"Bun S3",operation:e,status:403}):d(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 _ extends E{static name="bun-s3";meta;client;constructor(e){super(e),this.client=z(e),this.meta=e.metaStorage??new w(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new h(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=m(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&&k(t,e.size),!B(e,t))throw new Error("File part does not match");const n=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await I(e.body),a=c(t.name||t.id);try{await this.runOperation(i,()=>this.client.write(a,r,{type:t.contentType}))}catch(o){throw u(o,"upload")}t.bytesWritten=r.length,t.size=r.length,t.bunS3Key=a}return t.status=m(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(!v(a))throw u(a,"delete")}if(t)return t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t;const r=new h({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(l){throw u(l,"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(g){throw u(g,"getStream")}const l=t?.size??a.size,f=t?.contentType??a.type??"application/octet-stream",p=t?.ETag??a.etag,y=t?.modifiedAt??a.lastModified?.toISOString();return{headers:{"Content-Length":String(l??0),"Content-Type":f,...p&&{ETag:p},...y&&{"Last-Modified":String(y)}},size:typeof l=="number"?l:void 0,stream:S.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 u(o,"copy")}const a=new h({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 u(n,"list")}return(t.contents??[]).filter(n=>!!n.key).slice(0,e).map(n=>{const r=c(n.key),a=new h({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?T(b.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{_ as default};
@@ -0,0 +1 @@
1
+ import e from"./File-DLAa0hBv.js";class t extends e{bunnyChecksum;bunnyPath}export{t as default};
@@ -0,0 +1 @@
1
+ import{L as a}from"./local-meta-storage-Ca6WrUmN.js";class r extends a{constructor(t){super(t)}}export{r as default};
@@ -0,0 +1 @@
1
+ import m from"./BunnyFile-CBJdpNcB.js";import O from"./BunnyMetaStorage-BI-G6aeO.js";import*as c from"@bunny.net/storage-sdk";import{throwErrorCode as y,ERRORS as d,wrapStorageError as p}from"./ERRORS-olUcTqo2.js";import{B as T}from"./storage-uypoNkqu.js";import{g as f}from"./get-file-status-B8WmWzcM.js";import{u as B}from"./update-size-Dxc1hvbI.js";import{p as N}from"./part-match-Cb6xL9eN.js";import{h as _}from"./has-content-96mmyLn2.js";const w=new Set(Object.values(c.regions.StorageRegion)),h=s=>`/${s.replace(/^\/+/u,"")}`,g=s=>s.replace(/^\/+/u,""),b=(s,t)=>{const a=s.replace(/\/+$/u,""),e=t.replace(/^\/+/u,"");return`${a}/${e}`},A=async s=>{const t=[];for await(const a of s)t.push(Buffer.from(a));return Buffer.concat(t)},S=s=>new ReadableStream({start(a){a.enqueue(new Uint8Array(s)),a.close()}}),R=s=>{if(s){if(!w.has(s))throw new Error(`Bunny Storage: unsupported region "${s}". Pass one of ${[...w].join(", ")}.`);return s}},C=s=>{if(s.client)return s.client;const t=s.zone??process.env.BUNNY_STORAGE_ZONE??process.env.STORAGE_ZONE,a=s.accessKey??process.env.BUNNY_STORAGE_ACCESS_KEY??process.env.BUNNY_ACCESS_KEY??process.env.STORAGE_ACCESS_KEY,e=R(s.region??process.env.BUNNY_STORAGE_REGION??process.env.STORAGE_REGION);if(!t||!a||!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,a)},U=async s=>Buffer.from(await new Response(s).arrayBuffer()),l=(s,t)=>{const a=s?.message,e=typeof a=="string"?a:"";return/^file not found/iu.test(e)?p(s,{adapter:"Bunny Storage",operation:t,status:404}):/^unauthorized access/iu.test(e)?p(s,{adapter:"Bunny Storage",operation:t,status:401}):/^unable to upload file/iu.test(e)?p(s,{adapter:"Bunny Storage",operation:t,status:400}):p(s,{adapter:"Bunny Storage",operation:t})};class I extends T{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 O(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}get zone(){return this.zoneName}async create(t,a){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 n=await this.getMeta(e.id);if(n.bytesWritten>=0)return n}catch{}return e.bytesWritten=0,e.status=f(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){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&&B(e,t.size),!N(t,e))throw new Error("File part does not match");const n=await this.lock(t.id);try{if(_(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await A(t.body),o=h(e.name||e.id);try{await this.runOperation(a,()=>c.file.upload(this.client,o,S(r),{contentType:e.contentType,...t.checksum&&t.checksumAlgorithm==="sha256"&&{sha256Checksum:t.checksum}}))}catch(i){throw l(i,"upload")}e.bytesWritten=r.length,e.size=r.length,e.bunnyPath=o}return e.status=f(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,n)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const n=e?.bunnyPath??h(e?.name??t);try{await this.runOperation(a,()=>c.file.remove(this.client,n))}catch(o){throw l(o,"delete")}if(e)return e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e;const r=new m({contentType:"application/octet-stream",metadata:{},originalName:t});return r.id=t,r.name=t,r.bunnyPath=n,r.status="deleted",r})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e,n;try{e=await this.checkIfExpired(await this.getMeta(t)),n=e.bunnyPath??h(e.name??t)}catch{n=h(t)}let r;try{r=await this.runOperation(a,()=>c.file.get(this.client,n))}catch(i){throw l(i,"get")}let o;try{const i=await this.runOperation(a,()=>r.data());o=await U(i.stream)}catch(i){throw l(i,"download")}return{content:o,contentType:e?.contentType??r.contentType??"application/octet-stream",ETag:e?.ETag??r.checksum??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??r.lastChanged?.toISOString(),name:e?.name??g(n),originalName:e?.originalName??g(n),size:e?.size??r.length??o.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const n=await this.get({id:t},e),r=h(a),o=n.content,i=typeof n.size=="string"?Number(n.size):n.size??o.length;try{await this.runOperation(e,()=>c.file.upload(this.client,r,S(o),{contentType:n.contentType}))}catch(E){throw l(E,"copy")}const u=new m({contentType:n.contentType,metadata:{},originalName:a});return u.id=a,u.name=a,u.bunnyPath=r,u.size=i,u.ETag=n.ETag,u.bunnyChecksum=n.ETag,u})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const n=await this.copy(t,a,e);return await this.delete({id:t},e),n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{let e;try{e=await this.runOperation(a,()=>c.file.list(this.client,"/"))}catch(n){throw l(n,"list")}return e.filter(n=>!n.isDirectory).slice(0,t).map(n=>{const r=n.path.endsWith(n.objectName)||!n.objectName?n.path:`${n.path.replace(/\/+$/u,"")}/${n.objectName}`,o=g(r),i=new m({contentType:n.contentType||"application/octet-stream",metadata:{},originalName:o});return i.id=o,i.name=o,i.bunnyPath=h(o),i.bunnyChecksum=n.checksum??void 0,i.ETag=n.checksum??void 0,i.size=n.length,i.modifiedAt=n.lastChanged?.toISOString(),i})},{limit:t})}async getReadUrl(t,a){return a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0?y(d.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):y(d.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,a){return y(d.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{I as default};
@@ -0,0 +1 @@
1
+ import e from"./File-DLAa0hBv.js";class a extends e{bucket;path;publicUrl}export{a as default};
@@ -0,0 +1 @@
1
+ import{L as t}from"./local-meta-storage-Ca6WrUmN.js";class r extends t{constructor(a){super(a)}}export{r as default};
@@ -0,0 +1 @@
1
+ import c from"./CloudinaryFile-Dl8cnbJo.js";import y from"./CloudinaryMetaStorage-CYWznm7F.js";import{v2 as u}from"cloudinary";import{throwErrorCode as p,ERRORS as l}from"./ERRORS-olUcTqo2.js";import{B as d}from"./storage-uypoNkqu.js";import{g as h}from"./get-file-status-B8WmWzcM.js";import{u as m}from"./update-size-Dxc1hvbI.js";import{p as f}from"./part-match-Cb6xL9eN.js";import{h as w}from"./has-content-96mmyLn2.js";const v=async o=>{const e=[];for await(const i of o)e.push(Buffer.from(i));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 N 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 i=_(process.env.CLOUDINARY_URL),t=e.cloudName??process.env.CLOUDINARY_CLOUD_NAME??i.cloudName,r=e.apiKey??process.env.CLOUDINARY_API_KEY??i.apiKey,a=e.apiSecret??process.env.CLOUDINARY_API_SECRET??i.apiSecret;if(!t)throw new Error("Cloudinary storage: `cloudName` is required (or set CLOUDINARY_CLOUD_NAME / CLOUDINARY_URL).");u.config({api_key:r,api_secret:a,cloud_name:t,secure:this.secure}),this.client=u}this.meta=e.metaStorage??new y(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,i){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=h(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&&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 a=await v(e.body),s=t.path??t.name,n=await this.runOperation(i,()=>this.uploadBuffer(s,a));t.bytesWritten=a.length,t.size=a.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=h(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?.path??t?.name??e;return await this.runOperation(i,()=>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},i){return this.instrumentOperation("exists",async()=>{let t=e;try{t=(await this.getMeta(e)).path??e}catch{}try{return await this.runOperation(i,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),!0}catch{return!1}})}async get({id:e},i){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 a=await this.runOperation(i,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),s=await this.runOperation(i,()=>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??(a.resource_type&&a.format?`${a.resource_type}/${a.format}`:void 0)??"application/octet-stream",ETag:r?.ETag??(a.version===void 0?void 0:String(a.version)),expiredAt:r?.expiredAt,id:e,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??t,originalName:r?.originalName??t,size:r?.size??(typeof a.bytes=="number"?a.bytes:n.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const a=(await this.getMetaSafe(e))?.path??e,s=this.client.url(a,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType});await this.runOperation(t,()=>this.client.uploader.upload(s,{overwrite:!0,public_id:i,resource_type:this.resourceType,type:this.deliveryType}));const n=new c({contentType:"application/octet-stream",metadata:{},originalName:i});return n.id=i,n.name=i,n.path=i,n})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const a=(await this.getMetaSafe(e))?.path??e;await this.runOperation(t,()=>this.client.uploader.rename(a,i,{resource_type:this.resourceType}));const s=new c({contentType:"application/octet-stream",metadata:{},originalName:i});s.id=i,s.name=i,s.path=i;try{await this.deleteMeta(e)}catch{}return s})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{const{resources:t}=await this.runOperation(i,()=>this.client.api.resources({max_results:e,resource_type:this.resourceType,type:this.deliveryType}));return(t??[]).map(r=>{const a=new c({contentType:r.resource_type&&r.format?`${r.resource_type}/${r.format}`:"application/octet-stream",metadata:{},originalName:r.public_id});return a.id=r.public_id,a.name=r.public_id,a.path=r.public_id,a.size=typeof r.bytes=="number"?r.bytes:void 0,a.createdAt=r.created_at??void 0,a.ETag=r.version===void 0?void 0:String(r.version),a})},{limit:e})}async getReadUrl(e,i){if(i?.responseContentDisposition!==void 0||i?.responseContentType!==void 0)return p(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=i?.expiresIn??this.defaultUrlExpiresIn,r=e.lastIndexOf("."),a=r>0?e.slice(r+1):"";try{return this.client.utils.private_download_url(e,a,{expires_at:Math.floor(Date.now()/1e3)+t,resource_type:this.resourceType,type:this.deliveryType})}catch(s){return p(l.METHOD_NOT_ALLOWED,s instanceof Error?s.message:"Cloudinary: private_download_url failed")}}uploadBuffer(e,i){return new Promise((t,r)=>{this.client.uploader.upload_stream({overwrite:!0,public_id:e,resource_type:this.resourceType,type:this.deliveryType},(s,n)=>{if(s||!n){r(s instanceof Error?s:new Error(s?.message??"Cloudinary: upload failed"));return}t(n)}).end(i)})}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=e=>this.deleteMeta(e.id)}export{N as default};
@@ -0,0 +1 @@
1
+ import"./local-meta-storage-Ca6WrUmN.js";import"./path-CxEa27Rz-DSh0_A5o.js";import"./index-DKzU1HON.js";import"./detect-file-type-go3r-MOD.js";import"./ERRORS-olUcTqo2.js";import{D as x}from"./disk-storage-DEOi12bM.js";import"./storage-uypoNkqu.js";import"./File-DLAa0hBv.js";import"./get-file-status-B8WmWzcM.js";import"./update-size-Dxc1hvbI.js";import"./part-match-Cb6xL9eN.js";import"./has-content-96mmyLn2.js";export{x as default};
@@ -0,0 +1 @@
1
+ import{D as g,F as f,S as y,s as p}from"./disk-storage-DEOi12bM.js";import{createReadStream as w,createWriteStream as C}from"node:fs";import{truncate as F}from"node:fs/promises";import{Transform as b,pipeline as E}from"node:stream";import{p as S}from"./local-meta-storage-Ca6WrUmN.js";import{a as k}from"./detect-file-type-go3r-MOD.js";import{throwErrorCode as c,ERRORS as o}from"./ERRORS-olUcTqo2.js";import{LRUCache as W}from"lru-cache";import{createHash as R}from"node:crypto";import{u as T}from"./update-size-Dxc1hvbI.js";import{p as N}from"./part-match-Cb6xL9eN.js";import{h as M}from"./has-content-96mmyLn2.js";import{g as _}from"./get-file-status-B8WmWzcM.js";class x extends b{constructor(t,e){super(),this.path=e,this.hashes=t,this.hash=this.hashes.get(e)||R(this.hashes.algorithm),this.hashCopy=this.hash.copy()}path;hash;hashCopy;hashes;reset(){this.hashes.set(this.path,this.hashCopy)}digest(t="hex"){return this.hash.copy().digest(t)}_transform(t,e,s){this.push(t),this.hash.update(t),s()}_flush(t){t()}}class L extends W{constructor(t="sha1",e){super({ttl:1e3,ttlAutopurge:!0,...e}),this.algorithm=t}algorithm;hex(t){return this.get(t)?.copy().digest("hex")||""}base64(t){return this.get(t)?.copy().digest("base64")||""}async init(t,e=0){return this.get(t)?.copy()||this.updateFromFs(t,e)}digester(t){return new x(this,t)}async updateFromFs(t,e=0,s){const r=await this.fromFs(t,e,s);return this.set(t,r),r}fromFs(t,e=0,s){return new Promise((r,i)=>{const h=this.digester(t);s!==void 0&&(h.hash=s),w(t,{start:e}).on("error",i).on("end",()=>{r(h.hash)}).pipe(h).resume()})}}class j extends g{hashes;constructor(t){super(t),this.hashes=new L(t?.checksum==="sha1"?"sha1":"md5")}async delete({id:t}){try{const e=await this.getMeta(t),s=this.getFilePath(e.name);this.hashes.delete(s),await S(s),await this.deleteMeta(t);const r={...e,status:"deleted"};return await this.onDelete(r),r}catch(e){this.logger?.error("[error]: Could not delete file: %O",e);const s=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(s)}return{id:t}}async write(t){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&&T(e,t.size),!N(t,e))return c(o.FILE_CONFLICT);const s=this.getFilePath(e.name);try{const r=t.start||0;if(await f(s),(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(e.bytesWritten=r),await this.hashes.init(s),M(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return c(o.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:a,stream:u}=await k(t.body);a?.mime&&(e.contentType=a.mime),t.body=u}catch{}const[h,n]=await this.lazyWrite({...t,...e});if(n)return await F(s,e.bytesWritten),c(n);typeof h!="number"&&await this.hashes.updateFromFs(s,e.bytesWritten),e.bytesWritten=h}return e.status=_(e),e.hash={algorithm:this.hashes.algorithm,value:this.hashes.hex(s)},e.status==="completed"&&this.hashes.delete(s),await this.saveMeta(e),e}catch(r){await this.hashes.updateFromFs(s,e.bytesWritten);const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));return await this.onError(i),c(o.FILE_ERROR,(typeof i.message=="string"?i.message:String(r))||String(r))}}lazyWrite(t){return new Promise((e,s)=>{const r=this.getFilePath(t.name),i=C(r,{flags:"r+",start:t.start}),h=new y(t.contentLength||Number(t.size)-t.start),n=p(t.checksum,t.checksumAlgorithm),a=this.hashes.digester(r),u=!t.checksum,d=m=>{a.reset(),i.close(),e([Number.NaN,m])};h.on("error",()=>{d(o.FILE_CONFLICT)}),n.on("error",()=>{d(o.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{d(u?void 0:o.REQUEST_ABORTED)}),E(t.body,h,n,a,i,m=>{if(m){a.reset(),s(m);return}e([t.start+i.bytesWritten])})})}}export{j as default};
@@ -0,0 +1 @@
1
+ import e from"./File-DLAa0hBv.js";class o extends e{path;publicUrl;rev}export{o as default};
@@ -0,0 +1 @@
1
+ import{L as t}from"./local-meta-storage-Ca6WrUmN.js";class r extends t{constructor(o){super(o)}}export{r as default};
@@ -0,0 +1 @@
1
+ import u from"./DropboxFile-BUSubTWW.js";import v from"./DropboxMetaStorage-BYbJBJXr.js";import{DropboxResponseError as A,DropboxAuth as f,Dropbox as d}from"dropbox";import{throwErrorCode as y,ERRORS as w}from"./ERRORS-olUcTqo2.js";import{c as E}from"./oauth-refresh-Cf1z47zf.js";import{B as S}from"./storage-uypoNkqu.js";import{g as O}from"./get-file-status-B8WmWzcM.js";import{u as D}from"./update-size-Dxc1hvbI.js";import{p as x}from"./part-match-Cb6xL9eN.js";import{h as B}from"./has-content-96mmyLn2.js";const T=14400,R=150*1024*1024,p=8*1024*1024,g=(r,t)=>{r.auth.setAccessToken(t)},U=r=>r.auth.getAccessToken(),k=r=>{let t=0,s=r.length;for(;t<s&&r[t]==="/";)t+=1;for(;s>t&&r[s-1]==="/";)s-=1;return t===0&&s===r.length?r:r.slice(t,s)},C=async r=>{const t=[];for await(const s of r)t.push(Buffer.from(s));return Buffer.concat(t)},_=r=>r.includes("?dl=0")?r.replace("?dl=0","?dl=1"):r.includes("?dl=")?r:r+(r.includes("?")?"&dl=1":"?dl=1"),b=(r,t)=>(g(r,t),{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(t)}),L=(r,t)=>{const s=async()=>{const e=await t();return g(r,e),e};return{async ensureAccessToken(){await s()},getAccessToken:s}},P=(r,t)=>{const s=E({buildBody:()=>new URLSearchParams({client_id:t.appKey,grant_type:"refresh_token",refresh_token:t.refreshToken,...t.appSecret&&{client_secret:t.appSecret}}),onRefresh:e=>{g(r,e)},provider:"Dropbox",tokenUrl:"https://api.dropboxapi.com/oauth2/token"});return{async ensureAccessToken(){await s.getAccessToken()},getAccessToken:()=>s.getAccessToken()}},H=r=>{if(r.client){const n=r.client;return{authHandle:{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(U(n))},client:n}}const t=r.accessToken,s=r.refreshToken!==void 0||r.appKey!==void 0||r.appSecret!==void 0;if(t!==void 0&&s)throw new Error("Dropbox storage: pass exactly one of `accessToken` or `refreshToken` (with `appKey`).");if(t!==void 0){const n=new f({accessToken:typeof t=="string"?t:void 0}),i=new d({auth:n});return{authHandle:typeof t=="function"?L(i,t):b(i,t),client:i}}if(s){if(!r.refreshToken||!r.appKey)throw new Error("Dropbox storage: refresh-token auth requires both `refreshToken` and `appKey`.");const n=new f({}),i=new d({auth:n});return{authHandle:P(i,{appKey:r.appKey,...r.appSecret&&{appSecret:r.appSecret},refreshToken:r.refreshToken}),client:i}}const e=process.env.DROPBOX_ACCESS_TOKEN;if(e){const n=new f({accessToken:e}),i=new d({auth:n});return{authHandle:b(i,e),client:i}}const o=process.env.DROPBOX_REFRESH_TOKEN,a=process.env.DROPBOX_APP_KEY;if(o&&a){const n=process.env.DROPBOX_APP_SECRET,i=new f({}),c=new d({auth:i});return{authHandle:P(c,{appKey:a,...n&&{appSecret:n},refreshToken:o}),client:c}}throw new Error("Dropbox storage: missing auth. Pass `client`, `accessToken`, or `refreshToken` + `appKey`. Env fallbacks: DROPBOX_ACCESS_TOKEN, or DROPBOX_REFRESH_TOKEN + DROPBOX_APP_KEY (+ DROPBOX_APP_SECRET).")};class V extends S{static name="dropbox";checksumTypes=[];meta;authHandle;client;defaultUrlExpiresIn;publicByDefault;rootFolderPath;constructor(t){super(t),this.rootFolderPath=k(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,T);const s=H(t);this.client=s.client,this.authHandle=s.authHandle,this.meta=t.metaStorage??new v(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,s){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),e.path=this.keyToPath(e.name),await this.validate(e);try{const o=await this.getMeta(e.id);if(o.bytesWritten>=0)return o}catch{}return e.bytesWritten=0,e.status=O(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,s){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&&D(e,t.size),!x(t,e))throw new Error("File part does not match");const o=await this.lock(t.id);try{if(B(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await C(t.body),n=e.path??this.keyToPath(e.name||e.id);await this.authHandle.ensureAccessToken();const i=a.byteLength<=R?await this.uploadSimple(n,a,s):await this.uploadSession(n,a,s);e.bytesWritten=a.length,e.size=a.length,e.path=i.path_display??n,e.rev=i.rev,e.ETag=i.rev}return e.status=O(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,o)}})}async delete({id:t},s){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const o=e?.path??this.keyToPath(e?.name??t);await this.authHandle.ensureAccessToken();try{await this.runOperation(s,()=>this.client.filesDeleteV2({path:o}))}catch(a){if(!M(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,path:o,status:"deleted"})})}async get({id:t},s){return this.instrumentOperation("get",async()=>{let e,o=this.keyToPath(t);try{e=await this.checkIfExpired(await this.getMeta(t)),o=e.path??this.keyToPath(e.name??t)}catch{}await this.authHandle.ensureAccessToken();const n=(await this.runOperation(s,()=>this.client.filesDownload({path:o}))).result;let i;if(n.fileBinary instanceof Uint8Array)i=Buffer.from(n.fileBinary.buffer,n.fileBinary.byteOffset,n.fileBinary.byteLength);else if(n.fileBlob instanceof Blob)i=Buffer.from(await n.fileBlob.arrayBuffer());else throw new TypeError("Dropbox: unexpected download response shape — neither fileBinary nor fileBlob present");return{content:i,contentType:e?.contentType??"application/octet-stream",ETag:e?.ETag??n.rev,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??n.server_modified,name:e?.name??n.name,originalName:e?.originalName??n.name,size:e?.size??n.size??i.length}})}async copy(t,s,e){return this.instrumentOperation("copy",async()=>{const o=this.keyToPath(t),a=this.keyToPath(s);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesCopyV2({from_path:o,to_path:a}));const n=new u({contentType:"application/octet-stream",metadata:{},originalName:s});return n.id=s,n.name=s,n.path=a,n})}async move(t,s,e){return this.instrumentOperation("move",async()=>{const o=this.keyToPath(t),a=this.keyToPath(s);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesMoveV2({from_path:o,to_path:a}));const n=new u({contentType:"application/octet-stream",metadata:{},originalName:s});n.id=s,n.name=s,n.path=a;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,s){return this.instrumentOperation("list",async()=>{await this.authHandle.ensureAccessToken();const e=await this.runOperation(s,()=>this.client.filesListFolder({limit:t,path:this.rootFolderPath?`/${this.rootFolderPath}`:"",recursive:!0})),{result:o}=e,a=[];for(const n of o.entries){if(n[".tag"]!=="file")continue;const c=n,m=c.path_display??c.path_lower??`/${c.name}`,l=this.pathToKey(m);if(!l)continue;const h=new u({contentType:"application/octet-stream",metadata:{},originalName:c.name});h.id=l,h.name=l,h.path=m,h.size=c.size,h.rev=c.rev,h.ETag=c.rev,h.modifiedAt=c.server_modified,a.push(h)}return a},{limit:t})}async getReadUrl(t,s){if(s?.responseContentDisposition!==void 0||s?.responseContentType!==void 0)return y(w.METHOD_NOT_ALLOWED,"Dropbox: `responseContentDisposition`/`responseContentType` are not supported — Dropbox temporary links have no Content-Disposition/Content-Type override.");const e=s?.expiresIn??this.defaultUrlExpiresIn;return e>T?y(w.METHOD_NOT_ALLOWED,`Dropbox: \`expiresIn\` of ${e}s exceeds the ${T}s (4h) maximum. Use \`publicByDefault: true\` for a permanent shared link.`):(await this.authHandle.ensureAccessToken(),this.publicByDefault?await this.createPublicSharedLink(t):(await this.client.filesGetTemporaryLink({path:this.keyToPath(t)})).result.link)}async getUploadUrl(t,s){return y(w.METHOD_NOT_ALLOWED,"Dropbox: presigned upload URLs use POST with a raw body, which doesn't fit the PUT-style upload-url contract. Use `write()` or `storage.raw.filesGetTemporaryUploadLink(...)` directly.")}keyToPath(t){const s=k(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),s&&e.push(s),e.length===0?"":`/${e.join("/")}`}pathToKey(t){const s=k(t);if(!this.rootFolderPath)return s;if(s===this.rootFolderPath)return"";const e=`${this.rootFolderPath}/`;return s.startsWith(e)?s.slice(e.length):s}async uploadSimple(t,s,e){return(await this.runOperation(e,()=>this.client.filesUpload({contents:s,mode:{".tag":"overwrite"},mute:!0,path:t}))).result}async uploadSession(t,s,e){const o=s.byteLength;let a=0;const i=(await this.runOperation(e,()=>this.client.filesUploadSessionStart({close:!1,contents:s.subarray(a,Math.min(a+p,o))}))).result.session_id;for(a=Math.min(a+p,o);o-a>p;){const l=s.subarray(a,a+p);await this.runOperation(e,()=>this.client.filesUploadSessionAppendV2({close:!1,contents:l,cursor:{offset:a,session_id:i}})),a+=p}const c=s.subarray(a,o);return(await this.runOperation(e,()=>this.client.filesUploadSessionFinish({commit:{mode:{".tag":"overwrite"},mute:!0,path:t},contents:c,cursor:{offset:a,session_id:i}}))).result}async createPublicSharedLink(t){try{const s=await this.client.sharingCreateSharedLinkWithSettings({path:this.keyToPath(t),settings:{requested_visibility:{".tag":"public"}}});return _(s.result.url)}catch(s){if(s instanceof A){const e=s.error?.shared_link_already_exists?.metadata?.url;if(typeof e=="string"&&e.length>0)return _(e)}throw s}}internalOnComplete=t=>this.deleteMeta(t.id)}const M=r=>{if(!(r instanceof A))return!1;if(r.status===404)return!0;const t=[],s=(e,o)=>{if(o>6||e===null||typeof e!="object")return;const a=e,n=a[".tag"];typeof n=="string"&&t.push(n);for(const i of Object.values(a))i&&typeof i=="object"&&s(i,o+1)};return s(r.error,0),t.includes("not_found")||t.includes("not_file")||t.includes("not_folder")};export{V as default};
@@ -1 +1 @@
1
- var i=(e=>(e.BAD_REQUEST="BadRequest",e.CHECKSUM_MISMATCH="ChecksumMismatch",e.FILE_CONFLICT="FileConflict",e.FILE_ERROR="FileError",e.FILE_LOCKED="FileLocked",e.FILE_NOT_ALLOWED="FileNotAllowed",e.FILE_NOT_FOUND="FileNotFound",e.FORBIDDEN="Forbidden",e.GONE="Gone",e.INVALID_FILE_NAME="InvalidFileName",e.INVALID_FILE_SIZE="InvalidFileSize",e.INVALID_RANGE="InvalidRange",e.INVALID_TYPE="Invalidtype",e.METHOD_NOT_ALLOWED="MethodNotAllowed",e.READ_ONLY="ReadOnly",e.REQUEST_ABORTED="RequestAborted",e.REQUEST_ENTITY_TOO_LARGE="RequestEntityTooLarge",e.STORAGE_BUSY="StorageBusy",e.STORAGE_ERROR="StorageError",e.TOO_MANY_REQUESTS="TooManyRequests",e.UNKNOWN_ERROR="UnknownError",e.UNPROCESSABLE_ENTITY="UnprocessableEntity",e.UNSUPPORTED_CHECKSUM_ALGORITHM="UnsupportedChecksumAlgorithm",e.UNSUPPORTED_MEDIA_TYPE="UnsupportedMediaType",e))(i||{});const a=(()=>{const e={BadRequest:[400,"Bad request"],ChecksumMismatch:[460,"Checksum mismatch"],FileConflict:[409,"File conflict"],FileError:[500,"Something went wrong writing the file"],FileLocked:[423,"File locked"],FileNotAllowed:[403,"File not allowed"],FileNotFound:[404,"Not found"],Forbidden:[403,"Authenticated user is not allowed access"],Gone:[410,"The file for this url no longer exists"],InvalidFileName:[400,"Invalid file name or it cannot be retrieved"],InvalidFileSize:[400,"File size cannot be retrieved"],InvalidRange:[400,"Invalid or missing content-range header"],Invalidtype:[400,'Invalid or missing "content-type" header'],MethodNotAllowed:[405,"Method not allowed"],ReadOnly:[403,"Storage instance is read-only"],RequestAborted:[499,"Request aborted"],RequestEntityTooLarge:[413,"Request entity too large"],StorageBusy:[503,"Storage is busy"],StorageError:[503,"Storage error"],TooManyRequests:[429,"Too many requests"],UnknownError:[500,"Something went wrong"],UnprocessableEntity:[422,"Validation failed"],UnsupportedChecksumAlgorithm:[400,"Unsupported checksum algorithm"],UnsupportedMediaType:[415,"Unsupported media type"]},o={};return Object.keys(e).forEach(r=>{const[t,n]=e[r];o[r]={code:r,message:n,statusCode:t}}),o})();class d extends Error{name="UploadError";UploadErrorCode="UnknownError";detail;constructor(o="UnknownError",r,t){super(r||o),this.name="UploadError",this.detail=t,Object.values(i).includes(o)&&(this.UploadErrorCode=o)}}const u=e=>!!e.UploadErrorCode,E=e=>{if(!e||typeof e!="object")return;const o=e;if(typeof o.status=="number")return o.status;if(typeof o.statusCode=="number")return o.statusCode;if(typeof o.code=="number")return o.code;const r=o.response;if(typeof r?.status=="number")return r.status;if(typeof r?.statusCode=="number")return r.statusCode},c=e=>{if(e===void 0)return"StorageError";switch(e){case 400:return"BadRequest";case 401:case 403:return"Forbidden";case 404:return"FileNotFound";case 405:return"MethodNotAllowed";case 409:return"FileConflict";case 410:return"Gone";case 413:return"RequestEntityTooLarge";case 415:return"UnsupportedMediaType";case 422:return"UnprocessableEntity";case 423:return"FileLocked";case 429:return"TooManyRequests";case 503:return"StorageBusy";default:return e>=500&&e<600?"StorageError":e>=400&&e<500?"BadRequest":"UnknownError"}},p=(e,o,r,t)=>{const n=`${e}: ${o} failed`;return r?`${n} — ${r}`:t!==void 0?`${n} (HTTP ${t})`:n},R=(e,o)=>{if(u(e))return e;const r=o.status??E(e),t=o.code??c(r),n=e?.message,s=typeof n=="string"&&n.length>0?n:void 0,l=o.message??p(o.adapter,o.operation,s,r);return new d(t,l,e)},y=(e,o)=>{const r=e;let t;r&&typeof r=="string"&&r in a&&(t=a[r]);const n=o||(t?.body&&typeof t.body=="object"&&"message"in t.body?t.body.message:void 0)||t?.message||"UnknownError",s=new d(r,n);throw s.UploadErrorCode=r,typeof o=="string"&&(s.detail=o),s};export{i as ERRORS,a as ErrorMap,d as UploadError,E as extractHttpStatus,u as isUploadError,c as mapStatusToErrorCode,y as throwErrorCode,R as wrapStorageError};
1
+ var i=(e=>(e.BAD_REQUEST="BadRequest",e.CHECKSUM_MISMATCH="ChecksumMismatch",e.FILE_CONFLICT="FileConflict",e.FILE_ERROR="FileError",e.FILE_LOCKED="FileLocked",e.FILE_NOT_ALLOWED="FileNotAllowed",e.FILE_NOT_FOUND="FileNotFound",e.FORBIDDEN="Forbidden",e.GONE="Gone",e.INVALID_FILE_NAME="InvalidFileName",e.INVALID_FILE_SIZE="InvalidFileSize",e.INVALID_RANGE="InvalidRange",e.INVALID_TYPE="Invalidtype",e.METHOD_NOT_ALLOWED="MethodNotAllowed",e.READ_ONLY="ReadOnly",e.REQUEST_ABORTED="RequestAborted",e.REQUEST_ENTITY_TOO_LARGE="RequestEntityTooLarge",e.STORAGE_BUSY="StorageBusy",e.STORAGE_ERROR="StorageError",e.TOO_MANY_REQUESTS="TooManyRequests",e.UNKNOWN_ERROR="UnknownError",e.UNPROCESSABLE_ENTITY="UnprocessableEntity",e.UNSUPPORTED_CHECKSUM_ALGORITHM="UnsupportedChecksumAlgorithm",e.UNSUPPORTED_MEDIA_TYPE="UnsupportedMediaType",e))(i||{});const a=(()=>{const e={BadRequest:[400,"Bad request"],ChecksumMismatch:[460,"Checksum mismatch"],FileConflict:[409,"File conflict"],FileError:[500,"Something went wrong writing the file"],FileLocked:[423,"File locked"],FileNotAllowed:[403,"File not allowed"],FileNotFound:[404,"Not found"],Forbidden:[403,"Authenticated user is not allowed access"],Gone:[410,"The file for this url no longer exists"],InvalidFileName:[400,"Invalid file name or it cannot be retrieved"],InvalidFileSize:[400,"File size cannot be retrieved"],InvalidRange:[400,"Invalid or missing content-range header"],Invalidtype:[400,'Invalid or missing "content-type" header'],MethodNotAllowed:[405,"Method not allowed"],ReadOnly:[403,"Storage instance is read-only"],RequestAborted:[499,"Request aborted"],RequestEntityTooLarge:[413,"Request entity too large"],StorageBusy:[503,"Storage is busy"],StorageError:[503,"Storage error"],TooManyRequests:[429,"Too many requests"],UnknownError:[500,"Something went wrong"],UnprocessableEntity:[422,"Validation failed"],UnsupportedChecksumAlgorithm:[400,"Unsupported checksum algorithm"],UnsupportedMediaType:[415,"Unsupported media type"]},r={};return Object.keys(e).forEach(t=>{const[o,n]=e[t];r[t]={code:t,message:n,statusCode:o}}),r})();class d extends Error{name="UploadError";UploadErrorCode="UnknownError";detail;constructor(r="UnknownError",t,o){super(t||r),this.name="UploadError",this.detail=o,Object.values(i).includes(r)&&(this.UploadErrorCode=r)}}const l=e=>!!e.UploadErrorCode,c=e=>{if(!e||typeof e!="object")return;const r=e;if(typeof r.status=="number")return r.status;if(typeof r.statusCode=="number")return r.statusCode;if(typeof r.code=="number")return r.code;const t=r.response;if(typeof t?.status=="number")return t.status;if(typeof t?.statusCode=="number")return t.statusCode},p=e=>{if(e===void 0)return"StorageError";switch(e){case 400:return"BadRequest";case 401:case 403:return"Forbidden";case 404:return"FileNotFound";case 405:return"MethodNotAllowed";case 409:return"FileConflict";case 410:return"Gone";case 413:return"RequestEntityTooLarge";case 415:return"UnsupportedMediaType";case 422:return"UnprocessableEntity";case 423:return"FileLocked";case 429:return"TooManyRequests";case 503:return"StorageBusy";default:return e>=500&&e<600?"StorageError":e>=400&&e<500?"BadRequest":"UnknownError"}},E=(e,r,t,o)=>{const n=`${e}: ${r} failed`;return t?`${n} — ${t}`:o!==void 0?`${n} (HTTP ${o})`:n},g=(e,r)=>{if(l(e))return e;const t=r.status??c(e),o=r.code??p(t),n=e?.message,s=typeof n=="string"&&n.length>0?n:void 0,u=r.message??E(r.adapter,r.operation,s,t);return new d(o,u,e)},y=(e,r)=>{const t=e;let o;t&&typeof t=="string"&&t in a&&(o=a[t]);const n=r||(o?.body&&typeof o.body=="object"&&"message"in o.body?o.body.message:void 0)||o?.message||"UnknownError",s=new d(t,n);throw s.UploadErrorCode=t,typeof r=="string"&&(s.detail=r),s};export{i as ERRORS,a as ErrorMap,d as UploadError,c as extractHttpStatus,l as isUploadError,p as mapStatusToErrorCode,y as throwErrorCode,g as wrapStorageError};
@@ -0,0 +1 @@
1
+ import l from"@sindresorhus/fnv1a";import{nanoid as a}from"nanoid";const y=i=>l(i,{size:64}).toString(16),g=i=>{if(typeof i.mimeType=="string")return i.mimeType;if(typeof i.type=="string")return i.type;if(typeof i.filetype=="string")return i.filetype},d=i=>{if(typeof i.name=="string")return i.name;if(typeof i.title=="string")return i.title;if(typeof i.originalName=="string")return i.originalName;if(typeof i.filename=="string")return i.filename},m=i=>{const{metadata:r,originalName:n,size:o}=i,e=String(r.lastModified??Date.now());return[n,o,e].filter(Boolean).map(String).map(s=>y(s)).join("-")};class h{bytesWritten=Number.NaN;contentType;originalName;id;metadata;name="";size;status;expiredAt;createdAt;modifiedAt;hash;content;ETag;constructor({contentType:r,expiredAt:n,id:o,metadata:e,originalName:s,size:f}){this.metadata=e;let t=o||void 0,p=s||d(e);p||(t??=a(),p=t),t!==void 0&&(this.id=t),this.originalName=p,this.contentType=r||g(e)||"application/octet-stream",this.expiredAt=n,typeof f=="string"||typeof f=="number"?this.size=Number(f):(typeof e.size=="string"||typeof e.size=="number")&&(this.size=Number(e.size)),typeof this.size=="number"&&this.size<=0&&(this.size=void 0),this.id||=m(this)}}export{h as default};
@@ -0,0 +1 @@
1
+ import{PassThrough as I}from"node:stream";import{B as y}from"./storage-uypoNkqu.js";import{throwErrorCode as C,ERRORS as R}from"./ERRORS-olUcTqo2.js";import{n as H,a as L,m as N,b as W,s as T,t as v,D as x,r as E,c as f}from"./internal-Zb__DDsV.js";class U{adapter;defaults;hooks;prefix;readonlyMode;constructor(e){this.adapter=e.adapter,this.defaults=e.defaults??{},this.hooks=e.hooks??{},this.prefix=H(e.prefix??""),this.readonlyMode=e.readonly??!1}get capabilities(){return{cacheControl:this.adapter.supportsCacheControl,metadata:this.adapter.supportsMetadata,range:this.adapter.supportsRange,readonly:this.readonlyMode}}readonly(){return new U({adapter:this.adapter,defaults:this.defaults,hooks:this.hooks,prefix:this.prefix,readonly:!0})}assertWritable(){this.readonlyMode&&C(R.READ_ONLY,"This Files instance is read-only")}get raw(){return this.adapter.raw}resolveKey(e){const t=e.replace(/^\/+/u,"");return L(t,"key"),this.prefix?`${this.prefix}/${t}`:t}stripPrefix(e){const t=e.startsWith("/")?e.slice(1):e;if(!this.prefix)return t;const s=`${this.prefix}/`;return t.startsWith(s)?t.slice(s.length):null}mergeOptions(e,t){const s=N(this.defaults,e);if(!t||!this.hooks.onRetry)return s;const i=s?.retries,r=typeof i=="number"?{maxRetries:i}:{...i},h=r.onRetry,l=this.hooks.onRetry;return r.onRetry=(a,n)=>{if(h)try{h(a,n)}catch{}try{const o=typeof n=="string"?n:"Unknown error",c=n instanceof Error?n:new Error(o,{cause:n});l({...t,attempt:a,error:c})}catch{}},{...s,retries:r}}emitAction(e,t){if(this.hooks.onAction)try{this.hooks.onAction({type:e,...t})}catch{}}emitError(e,t,s){if(this.hooks.onError)try{this.hooks.onError({error:s,type:e,...t})}catch{}}async withHooks(e,t,s){const i=Date.now();try{const r=await s();return this.emitAction(e,{...t,durationMs:Date.now()-i}),r}catch(r){const h=typeof r=="string"?r:"Unknown error",l=r instanceof Error?r:new Error(h,{cause:r});throw this.emitError(e,{...t,durationMs:Date.now()-i},l),l}}async upload(e,t,s){return Array.isArray(e)?this.uploadMany(e,t):this.uploadOne(e,t,s)}async uploadOne(e,t,s){this.assertWritable(),s?.metadata&&Object.keys(s.metadata).length>0&&!this.adapter.supportsMetadata&&C(R.METHOD_NOT_ALLOWED,`Adapter ${this.adapter.constructor.name} does not persist custom metadata`);const i=s?.control;return this.withHooks("upload",{key:e},async()=>{const r=this.resolveKey(e);y.assertSafeId(r);const{size:h,stream:l}=await W(t,s?.size),a=s?.size??h,o={...s?.metadata??{},name:r,...s?.contentType?{type:s.contentType}:{},...a===void 0?{}:{size:a}},c=i?{...s,signal:s?.signal?AbortSignal.any([s.signal,i.signal]):i.signal}:s,d=this.mergeOptions(c,{key:e,type:"upload"}),p=s?.multipart;i?._bind(l,e);const u=await this.adapter.create({contentType:s?.contentType,id:r,metadata:o,originalName:r,size:a,storageClass:s?.storageClass},d),O=this.adapter.reportsUploadProgress,g=s?.onProgress,m=!!g||!!i;let w=l;if(m&&!O){let A=0;const z=new I;a!==void 0&&g&&T(g,{loaded:0,total:a}),l.on("data",M=>{const D=typeof M=="string"?Buffer.byteLength(M):M.byteLength;A+=D,i?._progress(A),g&&T(g,{loaded:A,total:a})}),l.pipe(z),w=z}const S={body:w,contentLength:a,id:u.id,start:0,...s?.checksum!==void 0&&{checksum:s.checksum},...s?.checksumAlgorithm!==void 0&&{checksumAlgorithm:s.checksumAlgorithm},...p!==void 0&&{multipart:p},...O&&g&&{onProgress:g}},b=await this.adapter.write(S,d);i?._complete();const k=v(b,r),P=this.stripPrefix(k.key);return P!==null&&(k.key=P),k})}async uploadMany(e,t){this.assertWritable();const{concurrency:s=x,multipart:i,onProgress:r,stopOnError:h=!1,...l}=t??{},a=await E(e,async({body:c,key:d,...p})=>{const u=p.onProgress??(r?O=>{r({...O,key:d})}:void 0);return this.uploadOne(d,c,{...l,multipart:i,...p,...u&&{onProgress:u}})},{concurrency:s,signal:l.signal,stopOnError:h}),n=[],o=[];for(const[c,d]of a.entries()){const p=e[c];if(!d){o.push(f(p.key,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?n.push(d.value):o.push(f(p.key,d.reason))}return o.length>0?{errors:o,uploaded:n}:{uploaded:n}}async download(e,t){return Array.isArray(e)?this.downloadMany(e,t):this.downloadOne(e,t)}assertRangeSupported(e){if(e){if(!Number.isFinite(e.start)||e.start<0)throw new TypeError(`Invalid range.start: ${String(e.start)}`);if(e.end!==void 0&&(!Number.isFinite(e.end)||e.end<e.start))throw new TypeError(`Invalid range.end: ${String(e.end)}`);if(!this.adapter.supportsRange)throw new Error(`Adapter ${this.adapter.constructor.name} does not support range downloads`)}}async downloadOne(e,t){return this.withHooks("download",{key:e},async()=>{const s=this.resolveKey(e);y.assertSafeId(s),this.assertRangeSupported(t?.range);const i=this.mergeOptions(t,{key:e,type:"download"})??{},r=t?.range?{...i,range:t.range}:i,h=await this.adapter.get({id:s},r);return{body:h.content,contentType:h.contentType??"application/octet-stream",etag:h.ETag,key:e,lastModified:h.modifiedAt,metadata:h.metadata,size:typeof h.size=="number"?h.size:void 0}})}async downloadMany(e,t){const{concurrency:s=x,range:i,stopOnError:r=!1,...h}=t??{},l=await E(e,async o=>this.downloadOne(o,i?{...h,range:i}:h),{concurrency:s,signal:h.signal,stopOnError:r}),a=[],n=[];for(const[o,c]of l.entries()){const d=e[o];if(!c){n.push(f(d,new Error("Operation skipped (stopOnError)")));continue}c.status==="fulfilled"?a.push(c.value):n.push(f(d,c.reason))}return n.length>0?{downloaded:a,errors:n}:{downloaded:a}}async downloadStream(e,t){return this.withHooks("download",{key:e},async()=>{const s=this.resolveKey(e);y.assertSafeId(s);const i=this.mergeOptions(t,{key:e,type:"download"}),{headers:r,size:h,stream:l}=await this.adapter.getStream({id:s},i),a=c=>r?Object.entries(r).find(([p])=>p.toLowerCase()===c.toLowerCase())?.[1]:void 0,n=a("Content-Length"),o=h??(n===void 0?void 0:Number(n));return{body:l,contentType:a("Content-Type")??"application/octet-stream",etag:a("ETag"),key:e,lastModified:a("Last-Modified"),size:typeof o=="number"&&Number.isFinite(o)?o:void 0}})}async head(e,t){return Array.isArray(e)?this.headMany(e,t):this.headOne(e,t)}async headOne(e,t){return this.withHooks("head",{key:e},async()=>{const s=this.resolveKey(e);y.assertSafeId(s);const i=await this.adapter.getMeta(s,this.mergeOptions(t,{key:e,type:"head"})),r=v(i,s);return r.key=e,r})}async headMany(e,t){const{concurrency:s=x,stopOnError:i=!1,...r}=t??{},h=await E(e,async n=>this.headOne(n,r),{concurrency:s,signal:r.signal,stopOnError:i}),l=[],a=[];for(const[n,o]of h.entries()){const c=e[n];if(!o){a.push(f(c,new Error("Operation skipped (stopOnError)")));continue}o.status==="fulfilled"?l.push(o.value):a.push(f(c,o.reason))}return a.length>0?{errors:a,files:l}:{files:l}}async exists(e,t){return Array.isArray(e)?this.existsMany(e,t):this.existsOne(e,t)}async existsOne(e,t){return this.withHooks("exists",{key:e},async()=>{const s=this.resolveKey(e);return y.assertSafeId(s),this.adapter.exists({id:s},this.mergeOptions(t,{key:e,type:"exists"}))})}async existsMany(e,t){const{concurrency:s=x,stopOnError:i=!1,...r}=t??{},h=await E(e,async o=>this.existsOne(o,r),{concurrency:s,signal:r.signal,stopOnError:i}),l=[],a=[],n=[];for(const[o,c]of h.entries()){const d=e[o];if(!c){n.push(f(d,new Error("Operation skipped (stopOnError)")));continue}c.status==="fulfilled"?c.value?l.push(d):a.push(d):n.push(f(d,c.reason))}return n.length>0?{errors:n,existing:l,missing:a}:{existing:l,missing:a}}async delete(e,t){if(this.assertWritable(),Array.isArray(e))return this.deleteMany(e,t);await this.deleteOne(e,t)}async deleteOne(e,t){await this.withHooks("delete",{key:e},async()=>{const s=this.resolveKey(e);y.assertSafeId(s),await this.adapter.delete({id:s},this.mergeOptions(t,{key:e,type:"delete"}))})}async deleteMany(e,t){const{concurrency:s=x,stopOnError:i=!1,...r}=t??{},h=this.mergeOptions(r,{keys:e,type:"delete"});if(!i&&typeof this.adapter.deleteBatch=="function"){const o=[],c=[],d=[];for(const p of e)try{const u=this.resolveKey(p);y.assertSafeId(u),o.push(p),c.push(u)}catch(u){d.push(f(p,u))}return this.withHooks("delete",{keys:o},async()=>{const p=c.length>0?await this.adapter.deleteBatch(c,h):{failed:[],successful:[]},u=new Map(c.map((m,w)=>[m,w])),O=p.successful.map(m=>this.stripPrefix(m.id)??m.id),g=[...d,...p.failed.map(({error:m,id:w})=>{const S=u.get(w),b=S===void 0?w:o[S];return f(b,new Error(m))})];return g.length>0?{deleted:O,errors:g}:{deleted:O}})}const l=await E(e,async o=>this.deleteOne(o,r),{concurrency:s,signal:r.signal,stopOnError:i}),a=[],n=[];for(const[o,c]of l.entries()){const d=e[o];if(!c){n.push(f(d,new Error("Operation skipped (stopOnError)")));continue}c.status==="fulfilled"?a.push(d):n.push(f(d,c.reason))}return n.length>0?{deleted:a,errors:n}:{deleted:a}}async copy(e,t,s){return this.assertWritable(),this.withHooks("copy",{from:e,to:t},async()=>{const i=this.resolveKey(e),r=this.resolveKey(t);y.assertSafeId(i),y.assertSafeId(r);const h=await this.adapter.copy(i,r,{...this.mergeOptions(s,{from:e,to:t,type:"copy"}),storageClass:s?.storageClass}),l=v(h,r);return l.key=t,l})}async move(e,t,s){return this.assertWritable(),Array.isArray(e)?this.moveMany(e,t):this.moveOne(e,t,s)}async moveOne(e,t,s){return this.withHooks("move",{from:e,to:t},async()=>{const i=this.resolveKey(e);if(y.assertSafeId(i),e===t){const n=await this.adapter.getMeta(i,this.mergeOptions(s,{from:e,to:t,type:"move"})),o=v(n,i);return o.key=e,o}const r=this.resolveKey(t);y.assertSafeId(r);const h={...this.mergeOptions(s,{from:e,to:t,type:"move"}),...s?.storageClass!==void 0&&{storageClass:s.storageClass}},l=await this.adapter.move(i,r,h),a=v(l,r);return a.key=t,a})}async moveMany(e,t){const{concurrency:s=x,stopOnError:i=!1,...r}=t??{},h=await E(e,async({from:n,to:o})=>this.moveOne(n,o,r),{concurrency:s,signal:r.signal,stopOnError:i}),l=[],a=[];for(const[n,o]of h.entries()){const c=e[n];if(!o){a.push(f(c.from,new Error("Operation skipped (stopOnError)")));continue}o.status==="fulfilled"?l.push(o.value):a.push(f(c.from,o.reason))}return a.length>0?{errors:a,moved:l}:{moved:l}}async list(e={}){return this.withHooks("list",{},async()=>{const{delimiter:t,limit:s,prefix:i,...r}=e;if(t!==void 0&&this.adapter.supportsDelimiter)return this.listDirectoryNative(t,i,s,r);const h=await this.adapter.list(s??1e3,this.mergeOptions(r,{type:"list"})),l=[];for(const d of h){const p=v(d),u=this.stripPrefix(p.key);u!==null&&(p.key=u,l.push(p))}const a=i?l.filter(d=>d.key.startsWith(i)):l;if(t===void 0)return a;const n=i??"",o=[],c=new Set;for(const d of a){const p=d.key.slice(n.length),u=p.indexOf(t);u===-1?o.push(d):c.add(n+p.slice(0,u+t.length))}return{files:o,prefixes:[...c].toSorted()}})}async listDirectoryNative(e,t,s,i){const r=[this.prefix,t].filter(Boolean).join("/"),{files:h,prefixes:l}=await this.adapter.listDirectory({delimiter:e,...s!==void 0&&{limit:s},...r&&{prefix:r},...this.mergeOptions(i,{type:"list"})}),a=[];for(const o of h){const c=v(o),d=this.stripPrefix(c.key);d!==null&&(c.key=d,a.push(c))}const n=[];for(const o of l){const c=this.stripPrefix(o);c!==null&&n.push(c)}return{files:a,prefixes:n.toSorted()}}async*listAll(e={}){const{limit:t,prefix:s,...i}=e,r=Math.max(1,t??1e3),h=Date.now(),l=new Set;let a;try{for(;;){const n=await this.adapter.list(r,this.mergeOptions(i,{type:"listAll"}));let o=0;for(const c of n){const d=v(c),p=this.stripPrefix(d.key);p!==null&&(d.key=p,!(s&&!d.key.startsWith(s))&&(l.has(d.key)||(l.add(d.key),o+=1,yield d)))}if(o===0||n.length<r)break}}catch(n){const o=typeof n=="string"?n:"Unknown error";throw a=n instanceof Error?n:new Error(o,{cause:n}),a}finally{const n=Date.now()-h;a?this.emitError("listAll",{durationMs:n},a):this.emitAction("listAll",{durationMs:n})}}async url(e,t){return this.withHooks("url",{key:e},async()=>{const s=this.resolveKey(e);return y.assertSafeId(s),this.adapter.getReadUrl(s,{...this.mergeOptions(t,{key:e,type:"url"}),...t})})}async signedUploadUrl(e,t){return this.assertWritable(),this.withHooks("signedUploadUrl",{key:e},async()=>{const s=this.resolveKey(e);return y.assertSafeId(s),this.adapter.getUploadUrl(s,{...this.mergeOptions(t,{key:e,type:"signedUploadUrl"}),...t})})}}export{U as Files};
@@ -0,0 +1 @@
1
+ import e from"./File-DLAa0hBv.js";class a extends e{bucket;path;publicUrl}export{a as default};
@@ -0,0 +1 @@
1
+ import{L as a}from"./local-meta-storage-Ca6WrUmN.js";class o extends a{constructor(e){super(e)}}export{o as default};
@@ -0,0 +1,2 @@
1
+ import c from"./FirebaseFile-Dl8cnbJo.js";import E from"./FirebaseMetaStorage-DX1-58UY.js";import{readFileSync as b}from"node:fs";import{getApps as w,getApp as d,initializeApp as g,cert as k}from"firebase-admin/app";import{getStorage as T}from"firebase-admin/storage";import{throwErrorCode as l,ERRORS as h}from"./ERRORS-olUcTqo2.js";import{B as O}from"./storage-uypoNkqu.js";import{g as f}from"./get-file-status-B8WmWzcM.js";import{u as A}from"./update-size-Dxc1hvbI.js";import{p as I}from"./part-match-Cb6xL9eN.js";import{h as S}from"./has-content-96mmyLn2.js";const v=3600,U=async o=>{const e=[];for await(const a of o)e.push(Buffer.from(a));return Buffer.concat(e)},_=o=>typeof o=="object"&&o!==null&&typeof o.file=="function"&&typeof o.getFiles=="function";class y extends O{static name="firebase";checksumTypes=[];meta;bucket;bucketName;defaultUrlExpiresIn;publicBaseUrl;constructor(e){if(super(e),this.defaultUrlExpiresIn=e.defaultUrlExpiresIn??v,this.publicBaseUrl=e.publicBaseUrl?.replace(/\/+$/,""),e.app&&_(e.app))this.bucket=e.app,this.bucketName=e.app.name??"";else{const a=e.bucket??process.env.FIREBASE_STORAGE_BUCKET;if(!a)throw new Error("Firebase storage: `bucket` is required (or set FIREBASE_STORAGE_BUCKET).");this.bucketName=a;const t=e.app??y.resolveApp(e,a);this.bucket=T(t).bucket(a)}this.meta=e.metaStorage??new E(e.metaStorageConfig),this.isReady=!0}get raw(){return this.bucket}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new c(e);t.name=this.namingFunction(t),t.bucket=this.bucketName,t.path=t.name,await this.validate(t);try{const i=await this.getMeta(t.id);if(i.bytesWritten>=0)return i}catch{}return t.bytesWritten=0,t.status=f(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&&A(t,e.size),!I(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(S(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const s=await U(e.body),r=t.path??t.name;await this.runOperation(a,()=>this.bucket.file(r).save(s,{contentType:t.contentType,resumable:!1})),t.bytesWritten=s.length,t.size=s.length,t.path=r}return t.status=f(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const i=t?.path??t?.name??e;return await this.runOperation(a,()=>this.bucket.file(i).delete({ignoreNotFound:!0})),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}),{bucket:this.bucketName,id:e,name:e,path:i,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{const[i]=await this.runOperation(a,()=>this.bucket.file(t).exists());return i}catch{return!1}})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t=e,i;try{i=await this.checkIfExpired(await this.getMeta(e)),t=i.path??i.name??e}catch{}const s=this.bucket.file(t),[r]=await this.runOperation(a,()=>s.download());let n={};try{[n]=await this.runOperation(a,()=>s.getMetadata())}catch{}return{content:r,contentType:i?.contentType??n.contentType??"application/octet-stream",ETag:i?.ETag??n.etag,expiredAt:i?.expiredAt,id:e,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt??n.updated,name:i?.name??t,originalName:i?.originalName??t,size:i?.size??(n.size===void 0?r.length:Number(n.size))}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const s=(await this.getMetaSafe(e))?.path??e;await this.runOperation(t,()=>this.bucket.file(s).copy(this.bucket.file(a)));const r=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return r.id=a,r.name=a,r.path=a,r.bucket=this.bucketName,r})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const s=(await this.getMetaSafe(e))?.path??e;await this.runOperation(t,()=>this.bucket.file(s).move(a));const r=new c({contentType:"application/octet-stream",metadata:{},originalName:a});r.id=a,r.name=a,r.path=a,r.bucket=this.bucketName;try{await this.deleteMeta(e)}catch{}return r})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>{const[t]=await this.runOperation(a,()=>this.bucket.getFiles({maxResults:e}));return(t??[]).map(i=>{const s=new c({contentType:"application/octet-stream",metadata:{},originalName:i.name});return s.id=i.name,s.name=i.name,s.path=i.name,s.bucket=this.bucketName,s})},{limit:e})}async getReadUrl(e,a){if(this.publicBaseUrl)return a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0?l(h.BAD_REQUEST,"Firebase: `responseContentDisposition`/`responseContentType` are not supported when `publicBaseUrl` is configured — a static public URL has no signature in which to bind the override."):`${this.publicBaseUrl}/${e}`;const t=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(e).getSignedUrl({action:"read",expires:Date.now()+t*1e3,...a?.responseContentDisposition!==void 0&&{responseDisposition:a.responseContentDisposition},...a?.responseContentType!==void 0&&{responseType:a.responseContentType}});return i}catch(i){return l(h.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}async getUploadUrl(e,a){if(a?.contentLength!==void 0)return l(h.BAD_REQUEST,"Firebase: `contentLength` is not supported for upload URLs. A GCS signed PUT has no content-length-range policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the URL.");const t=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(e).getSignedUrl({action:"write",contentType:a?.contentType,expires:Date.now()+t*1e3});return i}catch(i){return l(h.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}static resolveApp(e,a){const{appName:t}=e,i=w();if(t?i.find(u=>u.name===t):i[0])return t?d(t):d();const r=e.projectId??process.env.FIREBASE_PROJECT_ID??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT;let n=e.credentials?.clientEmail??process.env.FIREBASE_CLIENT_EMAIL,p=e.credentials?.privateKey??process.env.FIREBASE_PRIVATE_KEY;const m=e.serviceAccountPath??process.env.GOOGLE_APPLICATION_CREDENTIALS;if((!n||!p)&&m){const u=JSON.parse(b(m,"utf8"));n??=u.client_email,p??=u.private_key}if(!n||!p)throw new Error("Firebase storage: service-account credentials are required. Provide `credentials` ({ clientEmail, privateKey }), `serviceAccountPath`, or set FIREBASE_CLIENT_EMAIL / FIREBASE_PRIVATE_KEY / GOOGLE_APPLICATION_CREDENTIALS.");return g({credential:k({clientEmail:n,privateKey:p.replaceAll(String.raw`\n`,`
2
+ `),projectId:r}),projectId:r,storageBucket:a},t)}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=e=>this.deleteMeta(e.id)}export{y as default};
@@ -0,0 +1 @@
1
+ import e from"./File-DLAa0hBv.js";class l extends e{path}export{l as default};
@@ -0,0 +1 @@
1
+ import{L as a}from"./local-meta-storage-Ca6WrUmN.js";class r extends a{constructor(t){super(t)}}export{r as default};
@@ -0,0 +1 @@
1
+ import T from"./FtpFile-H8EmE3S_.js";import b from"./FtpMetaStorage-BI-G6aeO.js";import{Readable as p,Writable as E}from"node:stream";import{Client as O}from"basic-ftp";import{e as F}from"./index-DKzU1HON.js";import{throwErrorCode as u,ERRORS as m}from"./ERRORS-olUcTqo2.js";import{B as k}from"./storage-uypoNkqu.js";import{t as w,c as v,p as M}from"./posix-dirname-CSjB98Q5.js";import{g as P}from"./get-file-status-B8WmWzcM.js";import{u as S}from"./update-size-Dxc1hvbI.js";import{p as A}from"./part-match-Cb6xL9eN.js";import{h as D}from"./has-content-96mmyLn2.js";const f=c=>{const e=c?.code;if(e===550||e===450||e===553)return!0;const a=c instanceof Error?c.message:String(c);return/no such file|not exist|cannot find|file unavailable/i.test(a)},y=c=>{if(c instanceof Error&&c.name==="AbortError")return c;const e=new Error(c instanceof Error&&c.message?c.message:"The operation was aborted",{cause:c});return e.name="AbortError",e},g=async(c,e,a)=>{const t=[],o=new E({write(r,i,n){t.push(Buffer.from(r)),n()}});return await c.downloadTo(o,e,a&&a>0?a:void 0),Buffer.concat(t)};class H extends k{static name="ftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(e){super(e),this.connection=e.connection,this.rootFolderPath=w(e.rootFolderPath??""),this.meta=e.metaStorage??new b(e.metaStorageConfig),this.isReady=!0}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new T(e);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const o=await this.getMeta(t.id);if(o.status==="completed")return o}catch{}return t.bytesWritten=0,t.status=P(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&&S(t,e.size),!A(e,t))return u(m.FILE_CONFLICT);const o=await this.lock(e.id);try{if(D(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))return u(m.UNSUPPORTED_CHECKSUM_ALGORITHM);if(e.start>0)return u(m.METHOD_NOT_ALLOWED,"FTP storage does not support chunked or resumable uploads; send the file in a single request.");const r=await v(e.body),i=t.path??this.keyToPath(t.name||t.id);await this.runOperation(a,n=>this.run(n,async s=>{await this.ensureRemoteDirectory(s,i),await s.uploadFrom(p.from(r),i)})),t.bytesWritten=r.length,t.size=r.length,t.path=i,t.ETag=F(r)}return t.status=P(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,o)}})}async get({id:e},a){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e)),o=t.path??this.keyToPath(t.name||e),{range:r}=a??{},i=await this.runOperation(a,n=>this.run(n,async s=>{try{const h=await g(s,o,r?.start);return r?.end!==void 0?h.subarray(0,r.end-r.start+1):h}catch(h){if(f(h))return u(m.FILE_NOT_FOUND);throw h}}));return{content:i,contentType:t.contentType,ETag:t.ETag??F(i),expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:r?i.length:t.size??i.length}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e),o=t.path??this.keyToPath(t.name||e);await this.runOperation(a,i=>this.run(i,async n=>{try{await n.remove(o)}catch(s){if(!f(s))throw s}})),await this.deleteMeta(e);const r={...t,status:"deleted"};return await this.onDelete(r),r})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const o=await this.getMeta(e),r=o.path??this.keyToPath(o.name||e),i=this.keyToPath(a);await this.runOperation(t,s=>this.run(s,async h=>{const d=await g(h,r);await this.ensureRemoteDirectory(h,i),await h.uploadFrom(p.from(d),i)}));const n={...o,id:a,name:a,path:i};return await this.saveMeta(n),n})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const o=await this.getMeta(e),r=o.path??this.keyToPath(o.name||e),i=this.keyToPath(a);await this.runOperation(t,s=>this.run(s,async h=>{try{await this.ensureRemoteDirectory(h,i),await h.rename(r,i)}catch(d){try{const l=await g(h,r);await this.ensureRemoteDirectory(h,i),await h.uploadFrom(p.from(l),i),await h.remove(r)}catch(l){throw new AggregateError([d,l],`FTP move failed: rename and copy+delete fallback both failed for "${r}" → "${i}"`)}}}));const n={...o,id:a,name:a,path:i};await this.saveMeta(n);try{await this.deleteMeta(e)}catch{}return n})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(a,o=>this.run(o,async r=>{const i=[];return await this.walkList(r,t,i),i}))})}async exists({id:e},a){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(e)}catch{return!1}const o=t.path??this.keyToPath(t.name||e);return this.runOperation(a,r=>this.run(r,async i=>{try{return await i.size(o),!0}catch(n){if(f(n))return!1;throw n}}))})}async walkList(e,a,t){let o;try{o=await e.list(a||".")}catch(r){if(f(r))return;throw r}for(const r of o){const i=a?`${a}/${r.name}`:r.name;if(r.isDirectory){await this.walkList(e,i,t);continue}if(!r.isFile)continue;const n=this.pathToKey(i);if(!n)continue;const s=new T({contentType:"application/octet-stream",metadata:{},originalName:r.name});s.id=n,s.name=n,s.path=i,s.size=r.size,r.modifiedAt&&(s.modifiedAt=r.modifiedAt.toISOString()),t.push(s)}}async run(e,a){const t=new O;if(e?.aborted)throw y(e.reason);const o=()=>{t.close()};e?.addEventListener("abort",o,{once:!0});try{if(await t.access(this.connection),e?.aborted)throw y(e.reason);return await a(t)}catch(r){throw e?.aborted?y(r):r}finally{e?.removeEventListener("abort",o),t.close()}}async ensureRemoteDirectory(e,a){const t=M(a);t&&(await e.ensureDir(t),await e.cd("/"))}keyToPath(e){const a=w(e);a&&k.assertSafeId(a);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),a&&t.push(a),t.length===0?"":`/${t.join("/")}`}pathToKey(e){const a=w(e);if(!this.rootFolderPath)return a;if(a===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return a.startsWith(t)?a.slice(t.length):a}}export{H as default};
@@ -0,0 +1 @@
1
+ import e from"./File-DLAa0hBv.js";class i extends e{GCSUploadURI;uri}export{i as default};
@@ -0,0 +1 @@
1
+ import{G as i}from"./gcs-meta-storage-A5uvIda3.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-BeQVDFer.js";import"./GCSConfig-BQ0OpVhe.js";export{i as default};
@@ -0,0 +1 @@
1
+ import m from"./GCSConfig-BQ0OpVhe.js";import f from"./GCSFile-mFuZfcTW.js";import{r as y,G as w,b as C,g as R,p as d}from"./gcs-meta-storage-A5uvIda3.js";import{randomUUID as b}from"node:crypto";import{request as E}from"gaxios";import{GoogleAuth as k}from"google-auth-library";import{a as U}from"./detect-file-type-go3r-MOD.js";import{throwErrorCode as S,ERRORS as I}from"./ERRORS-olUcTqo2.js";import{B as x,t as T}from"./storage-uypoNkqu.js";import{L as $}from"./local-meta-storage-Ca6WrUmN.js";import{p as v}from"./part-match-Cb6xL9eN.js";import{h as A}from"./has-content-96mmyLn2.js";import{g as O}from"./get-file-status-B8WmWzcM.js";class B extends Error{constructor(t,s,e){super(t),this.code=s,this.config=e}code;config;name="FetchError"}const P=h=>h>=200&&h<300||h===308||h===499;class g extends x{static name="gcs";checksumTypes=["md5","crc32c"];supportsDelimiter=!0;get raw(){return this.authClient}meta;bucket;authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;constructor(t){super(t);const s=t.bucket||process.env.GCS_BUCKET;if(!s)throw new Error("GCS bucket is not defined");if(!t.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");this.bucket=s,this.storageBaseURI=`${t.storageAPI||m.storageAPI}/${this.bucket}/o`,this.uploadBaseURI=`${t.uploadAPI||m.uploadAPI}/${this.bucket}/o`,this.isCustomEndpoint=new URL(this.storageBaseURI).hostname!=="storage.googleapis.com";const{retryOptions:e,useAuthWithCustomEndpoint:r,userProject:i}=t;this.userProject=i,this.useAuthWithCustomEndpoint=r||!1,this.retryOptions={...y,...e},t.scopes||=m.authScopes,this.authClient=new k(t);const{bucket:o,metaStorage:n,metaStorageConfig:c,projectId:a}=t;if(n)this.meta=n;else{let u={...t,...c,logger:this.logger};"directory"in u?(this.logger?.debug("Using local meta storage"),this.meta=new $(u)):(o===u.bucket&&a===u.projectId&&(u={...u,authClient:this.authClient}),this.meta=new w(u))}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(u=>{this.logger?.error("Storage access check failed: %O",u)})}normalizeError(t){if(t.config){const s=+t.code||500;return{code:`GCS${s}`,message:t.message,name:t.name,retryable:s>=499,statusCode:s}}return{code:"GenericUploadError",message:`[${this.constructor.name}] ${t.message}`,name:t.name,statusCode:500}}async create(t,s){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const a=typeof t.ttl=="string"?T(t.ttl):t.ttl;a!==void 0&&(e.expiredAt=Date.now()+a)}const r=new f(e);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);return a.bytesWritten=await this.internalWrite(a,s),a}catch{}const i={"Content-Type":"application/json; charset=utf-8","X-Goog-Upload-Command":"start","X-Goog-Upload-Protocol":"resumable","X-Upload-Content-Length":r.size.toString(),"X-Upload-Content-Type":r.contentType},o={body:JSON.stringify({metadata:r.metadata}),headers:i,method:"POST",params:{name:r.name,size:r.size,uploadType:"resumable"},url:this.uploadBaseURI},n=await this.makeRequest(o,s);if(n.status!==200)throw new Error("Expected 200 response from GCS");const c=n.headers.get("X-Goog-Upload-Status")||n.headers.get("x-goog-upload-status");if(c!=="active")throw new Error(`X-Goog-Upload-Status response header expected 'active' got: ${c}`);return r.uri=n.headers.get("location"),this.config.clientDirectUpload?(r.GCSUploadURI=r.uri,this.logger?.debug("send uploadURI to client: %s",r.GCSUploadURI),r.status="created",r):(r.bytesWritten=0,await this.saveMeta(r),r.status="created",await this.onCreate(r),r)})}async write(t,s){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(!v(t,e))return S(I.FILE_CONFLICT);const r=await this.lock(t.id);try{if(A(t)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:i,stream:o}=await U(t.body);i?.mime&&(e.contentType=i.mime),t.body=o}catch{}e.bytesWritten=await this.internalWrite({...e,...t},s),e.status=O(e),e.status==="completed"&&(e.uri=`${this.storageBaseURI}/${e.name}`,await this.internalOnComplete(e))}finally{await this.unlock(t.id,r)}return e})}async delete({id:t},s){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);if(!e.uri)throw new Error(`File ${t} does not have a valid URI`);e.status="deleted",await this.makeRequest({method:"DELETE",url:e.uri,validateStatus:P},s),await this.deleteMeta(e.id);const r={...e};return await this.onDelete(r),r})}async copy(t,s,e){return this.instrumentOperation("copy",async()=>{const r=new URL(`/${this.bucket}/${t}`,"file://"),o=new URL(encodeURI(s),r).pathname,[,n,...c]=o.split("/"),a=c.join("/"),u=`${this.storageBaseURI}/${t}/rewriteTo/b/${n}/o/${a}`;let l={};const p={body:"",headers:{"Content-Type":"application/json"},method:"POST",url:u};do p.body=l.rewriteToken?JSON.stringify({rewriteToken:l.rewriteToken}):"",l=(await this.makeRequest(p,e)).data||{};while(l.rewriteToken);return await this.getMeta(s)})}async move(t,s,e){return this.instrumentOperation("move",async()=>{const r=await this.copy(t,s,e),i=`${this.storageBaseURI}/${t}`;return await this.makeRequest({method:"DELETE",url:i},e),r})}async get({id:t},s){return this.instrumentOperation("get",async()=>{const{data:e}=await this.makeRequest({params:{alt:"json"},url:`${this.storageBaseURI}/${t}`},s);if(await this.checkIfExpired({expiredAt:e.timeDeleted}),!e.uri)throw new Error("File URI not found");const i=(await this.makeRequest({params:{alt:"media"},url:e.uri},s)).data;let o;if(typeof i=="string")o=Buffer.from(i,"utf8");else if(i&&typeof i=="object"&&"data"in i){const n=i.data;o=Buffer.from(n)}else o=Buffer.from(i);return{...e,content:o}})}async exists({id:t},s){return this.instrumentOperation("exists",async()=>{try{return await this.getMeta(t),await this.makeRequest({method:"HEAD",url:`${this.storageBaseURI}/${t}`},s),!0}catch(e){const r=e;return(r.status||r.response?.status)===404,!1}})}async list(t=1e3,s){return this.instrumentOperation("list",async()=>{const e=[],r=Math.min(t,1e3);let i=!0,o={params:{maxResults:r},url:this.storageBaseURI};for(;i&&e.length<t;)try{const{data:n}=await this.makeRequest(o,s);for(const{name:c,timeCreated:a,updated:u}of n?.items||[]){if(e.length>=t)break;e.push({createdAt:a,id:c,modifiedAt:u})}i=n?.nextPageToken!==void 0,i&&e.length<t&&(o={...o,params:{...o.params,maxResults:Math.min(r,t-e.length),pageToken:n.nextPageToken}})}catch(n){const c=this.normalizeError(n instanceof Error?n:new Error(String(n)));throw await this.onError(c),n}return e},{limit:t})}async listDirectory(t){return this.instrumentOperation("listDirectory",async()=>{const s=t?.limit??1e3,e=Math.min(s,1e3),r=[],i=new Set;let o=!0,n={params:{delimiter:t?.delimiter,maxResults:e,...t?.prefix!==void 0&&{prefix:t.prefix}},url:this.storageBaseURI};for(;o&&r.length<s;)try{const{data:c}=await this.makeRequest(n,t);for(const a of c?.prefixes||[])i.add(a);for(const{name:a,timeCreated:u,updated:l}of c?.items||[]){if(r.length>=s)break;r.push({createdAt:u,id:a,modifiedAt:l})}o=c?.nextPageToken!==void 0,o&&r.length<s&&(n={...n,params:{...n.params,maxResults:Math.min(e,s-r.length),pageToken:c.nextPageToken}})}catch(c){const a=this.normalizeError(c instanceof Error?c:new Error(String(c)));throw await this.onError(a),c}return{files:r,prefixes:[...i]}},{limit:t?.limit??1e3})}async internalWrite(t,s){const{body:e,bytesWritten:r,size:i,uri:o=""}=t,n=C(t),c={method:"PUT"};if(e?.on){const a=new AbortController;e.on("aborted",()=>{a.abort()}),c.body=e,c.signal=a.signal,c.retry=!1}c.headers={Accept:"application/json","Content-Range":n,...i===r?{"X-Goog-Upload-Command":"upload, finalize"}:{}};try{const a=await this.makeRequest({url:o,...c},s);if(a.status===308){const u=a.headers.get("range");return u?R(u):0}if(a.status===200)return this.logger?.debug("uploaded %O",a.data),i;throw new B(String(a.data),`GCS${a.status}`,{uri:o})}catch(a){this.logger?.error(o,a);const u=this.normalizeError(a instanceof Error?a:new Error(String(a)));throw await this.onError(u),a}}internalOnComplete=t=>this.deleteMeta(t.id);static buildCallSignal(t,s){const e=[];if(s&&e.push(s),t?.signal&&e.push(t.signal),e.length!==0)return e.length===1?e[0]:AbortSignal.any(e)}async makeRequest(t,s){typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":"));const e=g.buildCallSignal(s,t.signal);let r=this.retryOptions;if(s?.retries!==void 0){const o=typeof s.retries=="number"?s.retries:s.retries.maxRetries;typeof o=="number"&&(r={...this.retryOptions,retry:o})}const i=typeof s?.timeout=="number"&&s.timeout>0?s.timeout:6e4;return t={...t,headers:{"User-Agent":`${d.name}/${d.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${d.version} gccl-invocation-id/${b()}`,...t.headers},params:{...this.userProject===void 0?{}:{userProject:this.userProject},...t.params},retry:t.retry===!1?!1:s?.retries!==0,retryConfig:r,timeout:i,...e?{signal:e}:{}},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?E(t):this.authClient.request(t)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}}export{g as default};
@@ -0,0 +1 @@
1
+ import e from"./File-DLAa0hBv.js";class r extends e{driveFileId;mimeType;publicUrl}export{r as default};
@@ -0,0 +1 @@
1
+ import{L as o}from"./local-meta-storage-Ca6WrUmN.js";class r extends o{constructor(e){super(e)}}export{r as default};
@@ -1 +1 @@
1
- import{Readable as D}from"node:stream";import{drive as C}from"@googleapis/drive";import{JWT as g,GoogleAuth as T,OAuth2Client as b}from"google-auth-library";import{throwErrorCode as u,ERRORS as p,wrapStorageError as E}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-DR7qdwBN.js";import m from"./GoogleDriveFile-DHpLhzg9.js";import F from"./GoogleDriveMetaStorage-B0gLF7Io.js";import{t as I}from"./get-file-status-y3wTtDQs.js";import{t as _}from"./update-size-DuNuLyxj.js";import{i as L}from"./part-match-D-9dGX42.js";import{e as G}from"./has-content-50BsqrWw.js";const f="https://www.googleapis.com/auth/drive",A=1024,h="fsdkKey",y="fsdkContentType",O="id, name, size, mimeType, md5Checksum, modifiedTime, appProperties",v=r=>{const e=r.lastIndexOf("/");return e===-1?r:r.slice(e+1)},w=r=>r.replaceAll("\\","\\\\").replaceAll("'",String.raw`\'`);class R{#t;#e=new Map;constructor(e){this.#t=Math.max(1,e)}delete(e){this.#e.delete(e)}get(e){const i=this.#e.get(e);if(i!==void 0)return this.#e.delete(e),this.#e.set(e,i),i}set(e,i){if(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,i),this.#e.size>this.#t){const t=this.#e.keys().next().value;t!==void 0&&this.#e.delete(t)}}}const P=r=>{const e=r.subject??process.env.GOOGLE_DRIVE_SUBJECT;if(r.credentials)return new g({email:r.credentials.client_email,key:r.credentials.private_key,scopes:[f],...e&&{subject:e}});if(r.keyFilename)return new T({keyFile:r.keyFilename,scopes:[f],...e&&{clientOptions:{subject:e}}});if(r.oauth){const s=new b({clientId:r.oauth.clientId,clientSecret:r.oauth.clientSecret});return s.setCredentials({refresh_token:r.oauth.refreshToken}),s}const i=process.env.GOOGLE_DRIVE_CLIENT_EMAIL,t=process.env.GOOGLE_DRIVE_PRIVATE_KEY;if(i&&t)return new g({email:i,key:t,scopes:[f],...e&&{subject:e}});const o=process.env.GOOGLE_DRIVE_KEY_FILE;if(o)return new T({keyFile:o,scopes:[f],...e&&{clientOptions:{subject:e}}})},B=async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},U=r=>{if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(Buffer.isBuffer(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof r=="string")return new TextEncoder().encode(r);throw new Error("Google Drive: unexpected response payload shape")};class H extends k{static name="google-drive";checksumTypes=[];meta;authForTokens;driveClient;fileIdCache;publicByDefault;rootFolderId;sharedDriveParams;constructor(e){if(super(e),e.client)this.driveClient=e.client,this.authForTokens=void 0;else{const t=P(e);if(!t)throw new Error("Google Drive storage: missing auth. Pass `client`, `credentials`, `keyFilename`, or `oauth`. Env fallbacks: GOOGLE_DRIVE_CLIENT_EMAIL + GOOGLE_DRIVE_PRIVATE_KEY, or GOOGLE_DRIVE_KEY_FILE.");this.authForTokens=t,this.driveClient=C({auth:t,version:"v3"})}const i=e.driveId??process.env.GOOGLE_DRIVE_ID;this.rootFolderId=e.rootFolderId??process.env.GOOGLE_DRIVE_ROOT_FOLDER_ID??i??"root",this.publicByDefault=e.publicByDefault??!1,this.fileIdCache=new R(e.fileIdCacheSize??A),this.sharedDriveParams={includeItemsFromAllDrives:!0,supportsAllDrives:!0,...i&&{corpora:"drive",driveId:i}},this.meta=e.metaStorage??new F(e.metaStorageConfig),this.isReady=!0}get raw(){return this.driveClient}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new m(e);t.name=this.namingFunction(t),await this.validate(t);try{const o=await this.getMeta(t.id);if(o.bytesWritten>=0)return o}catch{}return t.bytesWritten=0,t.status=I(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&&_(t,e.size),!L(e,t))throw new Error("File part does not match");const o=await this.lock(e.id);try{if(G(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const s=await B(e.body),n=t.name||t.id,a={[y]:t.contentType,[h]:n},l=await this.runOperation(i,()=>this.driveClient.files.create({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum, modifiedTime",media:{body:D.from(s),mimeType:t.contentType},requestBody:{appProperties:a,mimeType:t.contentType,name:v(n),parents:[this.rootFolderId]}})),{data:d}=l,c=d.id??void 0;c&&(this.fileIdCache.set(n,c),this.publicByDefault&&await this.runOperation(i,()=>this.driveClient.permissions.create({...this.sharedDriveParams,fileId:c,requestBody:{role:"reader",type:"anyone"}}))),t.bytesWritten=s.length,t.size=s.length,t.driveFileId=c,t.mimeType=d.mimeType??t.contentType,t.ETag=d.md5Checksum??void 0}return t.status=I(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,o)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;const o=e;try{t=await this.getMeta(e)}catch{}try{const s=t?.driveFileId??await this.resolveFileId(o,i);await this.runOperation(i,()=>this.driveClient.files.delete({...this.sharedDriveParams,fileId:s})),this.fileIdCache.delete(o)}catch(s){if(!z(s))throw s;this.fileIdCache.delete(o)}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new m({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,o;try{t=await this.checkIfExpired(await this.getMeta(e)),o=t.driveFileId??await this.resolveFileId(t.name??e,i)}catch{o=await this.resolveFileId(e,i)}const[s,n]=await Promise.all([this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,fields:O,fileId:o})),this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,alt:"media",fileId:o},{responseType:"arraybuffer"}))]),{data:a}=s,l=U(n.data),d=Buffer.from(l.buffer,l.byteOffset,l.byteLength),c=a.appProperties??{};return{content:d,contentType:t?.contentType??c[y]??a.mimeType??"application/octet-stream",ETag:t?.ETag??a.md5Checksum??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??a.modifiedTime??void 0,name:t?.name??a.name??e,originalName:t?.originalName??a.name??e,size:t?.size??Number(a.size??d.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const o=await this.resolveFileId(e,t),s=await this.runOperation(t,()=>this.driveClient.files.copy({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum",fileId:o,requestBody:{appProperties:{[h]:i},name:v(i),parents:[this.rootFolderId]}})),n=s.data.id??void 0;n&&this.fileIdCache.set(i,n);const a=new m({contentType:s.data.mimeType??"application/octet-stream",metadata:{},originalName:i});return a.id=i,a.name=i,a.driveFileId=n,a.mimeType=s.data.mimeType??void 0,a.ETag=s.data.md5Checksum??void 0,a.size=Number(s.data.size??0),a})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const o=await this.copy(e,i,t);return await this.delete({id:e},t),o})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{const t=`'${w(this.rootFolderId)}' in parents and trashed=false`,o=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:`nextPageToken, files(${O})`,pageSize:e,q:t}))).data.files??[],s=[];for(const n of o){const a=n.appProperties??{},l=a[h];if(!l)continue;n.id&&this.fileIdCache.set(l,n.id);const d=new m({contentType:a[y]??n.mimeType??"application/octet-stream",metadata:{},originalName:n.name??l});d.id=l,d.name=l,d.driveFileId=n.id??void 0,d.mimeType=n.mimeType??void 0,d.size=Number(n.size??0),d.modifiedAt=n.modifiedTime??void 0,d.ETag=n.md5Checksum??void 0,s.push(d)}return s},{limit:e})}async getReadUrl(e,i){return i?.responseContentDisposition!==void 0||i?.responseContentType!==void 0?u(p.METHOD_NOT_ALLOWED,"Google Drive: `responseContentDisposition`/`responseContentType` are not supported — Drive's webContentLink has no Content-Disposition/Content-Type override."):this.publicByDefault?`https://drive.google.com/uc?export=download&id=${await this.resolveFileId(e)}`:u(p.METHOD_NOT_ALLOWED,"Google Drive: getReadUrl() requires the adapter to be constructed with `publicByDefault: true`. Drive has no signed URL primitive — use get() for private files.")}async getUploadUrl(e,i){if(i?.contentLength!==void 0)return u(p.BAD_REQUEST,"Google Drive: `contentLength` is not supported for upload URLs. A Drive resumable upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");if(!this.authForTokens)return u(p.METHOD_NOT_ALLOWED,"Google Drive: getUploadUrl() requires `credentials`, `keyFilename`, or `oauth` — not the pre-built `client` escape hatch.");const t=await this.authForTokens.getAccessToken(),o=typeof t=="string"?t:t?.token;if(!o)throw new Error("Google Drive: failed to mint access token for resumable upload session");const s={Authorization:`Bearer ${o}`,"Content-Type":"application/json; charset=UTF-8"};i?.contentType&&(s["X-Upload-Content-Type"]=i.contentType);const n={appProperties:{[h]:e},name:v(e),parents:[this.rootFolderId]},a=await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",{body:JSON.stringify(n),headers:s,method:"POST"});if(!a.ok){const d=await a.text().catch(()=>"");throw E(new Error(`${a.statusText} ${d}`.trim()||a.statusText),{adapter:"Google Drive",operation:"resumable upload session",status:a.status})}const l=a.headers.get("location")??a.headers.get("Location");if(!l)throw E(new Error("response missing Location header"),{adapter:"Google Drive",code:p.STORAGE_ERROR,operation:"resumable upload session"});return l}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const o=`appProperties has { key='${h}' and value='${w(e)}' } and '${w(this.rootFolderId)}' in parents and trashed=false`,s=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:"files(id)",pageSize:2,q:o}))).data.files??[];if(s.length===0)throw new Error(`Google Drive: not found: ${e}`);if(s.length>1)throw new Error(`Google Drive: multiple files share virtual key '${e}'. Resolve via storage.raw.`);const n=s[0]?.id;if(!n)throw new Error(`Google Drive: list returned no fileId for ${e}`);return this.fileIdCache.set(e,n),n}internalOnComplete=e=>this.deleteMeta(e.id)}const z=r=>{if(r===null||typeof r!="object")return!1;const e=r;return typeof e.code=="number"&&e.code===404||typeof e.status=="number"&&e.status===404?!0:typeof e.response?.status=="number"&&e.response.status===404};export{H as default};
1
+ import p from"./GoogleDriveFile-fDYE1aaN.js";import D from"./GoogleDriveMetaStorage-CEleJNZZ.js";import{Readable as C}from"node:stream";import{drive as b}from"@googleapis/drive";import{JWT as g,GoogleAuth as E,OAuth2Client as _}from"google-auth-library";import{throwErrorCode as m,ERRORS as h,wrapStorageError as T}from"./ERRORS-olUcTqo2.js";import{B as F}from"./storage-uypoNkqu.js";import{g as I}from"./get-file-status-B8WmWzcM.js";import{u as k}from"./update-size-Dxc1hvbI.js";import{p as L}from"./part-match-Cb6xL9eN.js";import{h as R}from"./has-content-96mmyLn2.js";const f="https://www.googleapis.com/auth/drive",G=1024,u="fsdkKey",y="fsdkContentType",O="id, name, size, mimeType, md5Checksum, modifiedTime, appProperties",v=r=>{const e=r.lastIndexOf("/");return e===-1?r:r.slice(e+1)},w=r=>r.replaceAll("\\","\\\\").replaceAll("'",String.raw`\'`);class A{#t;#e=new Map;constructor(e){this.#t=Math.max(1,e)}delete(e){this.#e.delete(e)}get(e){const i=this.#e.get(e);if(i!==void 0)return this.#e.delete(e),this.#e.set(e,i),i}set(e,i){if(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,i),this.#e.size>this.#t){const t=this.#e.keys().next().value;t!==void 0&&this.#e.delete(t)}}}const P=r=>{const e=r.subject??process.env.GOOGLE_DRIVE_SUBJECT;if(r.credentials)return new g({email:r.credentials.client_email,key:r.credentials.private_key,scopes:[f],...e&&{subject:e}});if(r.keyFilename)return new E({keyFile:r.keyFilename,scopes:[f],...e&&{clientOptions:{subject:e}}});if(r.oauth){const n=new _({clientId:r.oauth.clientId,clientSecret:r.oauth.clientSecret});return n.setCredentials({refresh_token:r.oauth.refreshToken}),n}const i=process.env.GOOGLE_DRIVE_CLIENT_EMAIL,t=process.env.GOOGLE_DRIVE_PRIVATE_KEY;if(i&&t)return new g({email:i,key:t,scopes:[f],...e&&{subject:e}});const o=process.env.GOOGLE_DRIVE_KEY_FILE;if(o)return new E({keyFile:o,scopes:[f],...e&&{clientOptions:{subject:e}}})},S=async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},U=r=>{if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(Buffer.isBuffer(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof r=="string")return new TextEncoder().encode(r);throw new Error("Google Drive: unexpected response payload shape")};class H extends F{static name="google-drive";checksumTypes=[];meta;authForTokens;driveClient;fileIdCache;publicByDefault;rootFolderId;sharedDriveParams;constructor(e){if(super(e),e.client)this.driveClient=e.client,this.authForTokens=void 0;else{const t=P(e);if(!t)throw new Error("Google Drive storage: missing auth. Pass `client`, `credentials`, `keyFilename`, or `oauth`. Env fallbacks: GOOGLE_DRIVE_CLIENT_EMAIL + GOOGLE_DRIVE_PRIVATE_KEY, or GOOGLE_DRIVE_KEY_FILE.");this.authForTokens=t,this.driveClient=b({auth:t,version:"v3"})}const i=e.driveId??process.env.GOOGLE_DRIVE_ID;this.rootFolderId=e.rootFolderId??process.env.GOOGLE_DRIVE_ROOT_FOLDER_ID??i??"root",this.publicByDefault=e.publicByDefault??!1,this.fileIdCache=new A(e.fileIdCacheSize??G),this.sharedDriveParams={includeItemsFromAllDrives:!0,supportsAllDrives:!0,...i&&{corpora:"drive",driveId:i}},this.meta=e.metaStorage??new D(e.metaStorageConfig),this.isReady=!0}get raw(){return this.driveClient}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 o=await this.getMeta(t.id);if(o.bytesWritten>=0)return o}catch{}return t.bytesWritten=0,t.status=I(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&&k(t,e.size),!L(e,t))throw new Error("File part does not match");const o=await this.lock(e.id);try{if(R(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await S(e.body),a=t.name||t.id,s={[y]:t.contentType,[u]:a},c=await this.runOperation(i,()=>this.driveClient.files.create({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum, modifiedTime",media:{body:C.from(n),mimeType:t.contentType},requestBody:{appProperties:s,mimeType:t.contentType,name:v(a),parents:[this.rootFolderId]}})),{data:d}=c,l=d.id??void 0;l&&(this.fileIdCache.set(a,l),this.publicByDefault&&await this.runOperation(i,()=>this.driveClient.permissions.create({...this.sharedDriveParams,fileId:l,requestBody:{role:"reader",type:"anyone"}}))),t.bytesWritten=n.length,t.size=n.length,t.driveFileId=l,t.mimeType=d.mimeType??t.contentType,t.ETag=d.md5Checksum??void 0}return t.status=I(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,o)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;const o=e;try{t=await this.getMeta(e)}catch{}try{const n=t?.driveFileId??await this.resolveFileId(o,i);await this.runOperation(i,()=>this.driveClient.files.delete({...this.sharedDriveParams,fileId:n})),this.fileIdCache.delete(o)}catch(n){if(!B(n))throw n;this.fileIdCache.delete(o)}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,o;try{t=await this.checkIfExpired(await this.getMeta(e)),o=t.driveFileId??await this.resolveFileId(t.name??e,i)}catch{o=await this.resolveFileId(e,i)}const[n,a]=await Promise.all([this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,fields:O,fileId:o})),this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,alt:"media",fileId:o},{responseType:"arraybuffer"}))]),{data:s}=n,c=U(a.data),d=Buffer.from(c.buffer,c.byteOffset,c.byteLength),l=s.appProperties??{};return{content:d,contentType:t?.contentType??l[y]??s.mimeType??"application/octet-stream",ETag:t?.ETag??s.md5Checksum??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??s.modifiedTime??void 0,name:t?.name??s.name??e,originalName:t?.originalName??s.name??e,size:t?.size??Number(s.size??d.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const o=await this.resolveFileId(e,t),n=await this.runOperation(t,()=>this.driveClient.files.copy({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum",fileId:o,requestBody:{appProperties:{[u]:i},name:v(i),parents:[this.rootFolderId]}})),a=n.data.id??void 0;a&&this.fileIdCache.set(i,a);const s=new p({contentType:n.data.mimeType??"application/octet-stream",metadata:{},originalName:i});return s.id=i,s.name=i,s.driveFileId=a,s.mimeType=n.data.mimeType??void 0,s.ETag=n.data.md5Checksum??void 0,s.size=Number(n.data.size??0),s})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const o=await this.copy(e,i,t);return await this.delete({id:e},t),o})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{const t=`'${w(this.rootFolderId)}' in parents and trashed=false`,n=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:`nextPageToken, files(${O})`,pageSize:e,q:t}))).data.files??[],a=[];for(const s of n){const c=s.appProperties??{},d=c[u];if(!d)continue;s.id&&this.fileIdCache.set(d,s.id);const l=new p({contentType:c[y]??s.mimeType??"application/octet-stream",metadata:{},originalName:s.name??d});l.id=d,l.name=d,l.driveFileId=s.id??void 0,l.mimeType=s.mimeType??void 0,l.size=Number(s.size??0),l.modifiedAt=s.modifiedTime??void 0,l.ETag=s.md5Checksum??void 0,a.push(l)}return a},{limit:e})}async getReadUrl(e,i){return i?.responseContentDisposition!==void 0||i?.responseContentType!==void 0?m(h.METHOD_NOT_ALLOWED,"Google Drive: `responseContentDisposition`/`responseContentType` are not supported — Drive's webContentLink has no Content-Disposition/Content-Type override."):this.publicByDefault?`https://drive.google.com/uc?export=download&id=${await this.resolveFileId(e)}`:m(h.METHOD_NOT_ALLOWED,"Google Drive: getReadUrl() requires the adapter to be constructed with `publicByDefault: true`. Drive has no signed URL primitive — use get() for private files.")}async getUploadUrl(e,i){if(i?.contentLength!==void 0)return m(h.BAD_REQUEST,"Google Drive: `contentLength` is not supported for upload URLs. A Drive resumable upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");if(!this.authForTokens)return m(h.METHOD_NOT_ALLOWED,"Google Drive: getUploadUrl() requires `credentials`, `keyFilename`, or `oauth` — not the pre-built `client` escape hatch.");const t=await this.authForTokens.getAccessToken(),o=typeof t=="string"?t:t?.token;if(!o)throw new Error("Google Drive: failed to mint access token for resumable upload session");const n={Authorization:`Bearer ${o}`,"Content-Type":"application/json; charset=UTF-8"};i?.contentType&&(n["X-Upload-Content-Type"]=i.contentType);const a={appProperties:{[u]:e},name:v(e),parents:[this.rootFolderId]},s=await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",{body:JSON.stringify(a),headers:n,method:"POST"});if(!s.ok){const d=await s.text().catch(()=>"");throw T(new Error(`${s.statusText} ${d}`.trim()||s.statusText),{adapter:"Google Drive",operation:"resumable upload session",status:s.status})}const c=s.headers.get("location")??s.headers.get("Location");if(!c)throw T(new Error("response missing Location header"),{adapter:"Google Drive",code:h.STORAGE_ERROR,operation:"resumable upload session"});return c}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const o=`appProperties has { key='${u}' and value='${w(e)}' } and '${w(this.rootFolderId)}' in parents and trashed=false`,a=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:"files(id)",pageSize:2,q:o}))).data.files??[];if(a.length===0)throw new Error(`Google Drive: not found: ${e}`);if(a.length>1)throw new Error(`Google Drive: multiple files share virtual key '${e}'. Resolve via storage.raw.`);const s=a[0]?.id;if(!s)throw new Error(`Google Drive: list returned no fileId for ${e}`);return this.fileIdCache.set(e,s),s}internalOnComplete=e=>this.deleteMeta(e.id)}const B=r=>{if(r===null||typeof r!="object")return!1;const e=r;return typeof e.code=="number"&&e.code===404||typeof e.status=="number"&&e.status===404?!0:typeof e.response?.status=="number"&&e.response.status===404};export{H as default};
@@ -0,0 +1 @@
1
+ import{L as a}from"./local-meta-storage-Ca6WrUmN.js";import"./path-CxEa27Rz-DSh0_A5o.js";import"./ERRORS-olUcTqo2.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-BeQVDFer.js";export{a as default};
@@ -0,0 +1 @@
1
+ import{createHash as l}from"node:crypto";import{Readable as m}from"node:stream";import d from"mime";import{N as c}from"./cache-Cw3QjoVN.js";import{isKnownContentType as g}from"./getFormatFromContentType-BAVdaQ0o.js";import s from"./ValidationError-SzFFFHiN.js";class R{constructor(t,e={}){if(this.storage=t,this.logger=e.logger||this.storage.logger,this.config={audioBitrate:128e3,audioCodec:"aac",cache:e.cache??new c,cacheTtl:3600,maxAudioSize:100*1024*1024,maxImageSize:10*1024*1024,maxVideoSize:500*1024*1024,saveTransformedFiles:!1,supportedAudioFormats:[],supportedImageFormats:[],supportedVideoFormats:[],videoBitrate:2e6,videoCodec:"avc",...e},e.ImageTransformer&&((!Array.isArray(this.config.supportedImageFormats)||this.config.supportedImageFormats.length===0)&&(this.config.supportedImageFormats=["jpeg","png","webp","avif","tiff","gif","svg"]),this.imageTransformer=new e.ImageTransformer(this.storage,{cache:this.config.cache,cacheTtl:this.config.cacheTtl,logger:this.logger,maxImageSize:this.config.maxImageSize,supportedFormats:this.config.supportedImageFormats})),e.VideoTransformer&&((!Array.isArray(this.config.supportedVideoFormats)||this.config.supportedVideoFormats.length===0)&&(this.config.supportedVideoFormats=["mp4","webm","mkv","avi","mov","flv","wmv"]),this.videoTransformer=new e.VideoTransformer(this.storage,{cache:this.config.cache,cacheTtl:this.config.cacheTtl,defaultBitrate:this.config.videoBitrate,defaultCodec:this.config.videoCodec,logger:this.logger,maxVideoSize:this.config.maxVideoSize,supportedFormats:this.config.supportedVideoFormats})),e.AudioTransformer&&((!Array.isArray(this.config.supportedAudioFormats)||this.config.supportedAudioFormats.length===0)&&(this.config.supportedAudioFormats=["mp3","wav","ogg","aac","flac","m4a","wma","aiff"]),this.audioTransformer=new e.AudioTransformer(this.storage,{cache:this.config.cache,cacheTtl:this.config.cacheTtl,defaultBitrate:this.config.audioBitrate,defaultCodec:this.config.audioCodec,logger:this.logger,maxAudioSize:this.config.maxAudioSize,supportedFormats:this.config.supportedAudioFormats})),e.AudioTransformer===void 0&&e.ImageTransformer===void 0&&e.VideoTransformer===void 0)throw new Error("MediaTransformer initialization failed: No transformers are configured. At least one transformer (AudioTransformer, ImageTransformer, or VideoTransformer) must be provided in the configuration to enable media processing functionality.")}storage;imageTransformer;videoTransformer;audioTransformer;config;logger;supportedFormats(){return[...this.config.supportedAudioFormats,...this.config.supportedImageFormats,...this.config.supportedVideoFormats]}async handle(t,e){const i=this.parseQuery(e),o={id:t},a=await this.storage.get(o),r=this.detectMediaType(a.contentType);if(this.validateQueryParameters(i,r),this.config.saveTransformedFiles&&this.hasTransformations(i)){const h=this.generateTransformedFileId(t,i,r);try{const f=await this.storage.get({id:h});return this.logger?.debug?.(`Serving cached transformed file: ${h}`),this.createMediaTransformResult(f,r,a)}catch{this.logger?.debug?.(`Transformed file not found, processing: ${h}`)}}let n;switch(r){case"audio":{if(!this.audioTransformer)throw new Error("Audio transformer not available. Please install audio transformation dependencies or provide an audio transformer instance.");n=await this.handleAudioTransformation(t,i);break}case"image":{if(!this.imageTransformer)throw new Error("Image transformer not available. Please install image transformation dependencies or provide an image transformer instance.");n=await this.handleImageTransformation(t,i);break}case"video":{if(!this.videoTransformer)throw new Error("Video transformer not available. Please install video transformation dependencies or provide a video transformer instance.");n=await this.handleVideoTransformation(t,i);break}default:throw new Error(`Unsupported media type: ${a.contentType}`)}return this.config.saveTransformedFiles&&this.hasTransformations(i)&&await this.saveTransformedFile(n,t,i,r),n}async fetch(t,e){const i=new URLSearchParams(e);return this.handle(t,i)}clearCache(t){this.imageTransformer?.clearCache(t),this.videoTransformer?.clearCache(t),this.audioTransformer?.clearCache(t)}async clearSavedTransformedFiles(){if(this.config.saveTransformedFiles)try{this.logger?.warn?.("clearSavedTransformedFiles requires custom storage implementation to find and delete transformed files")}catch(t){this.logger?.error?.(`Failed to clear saved transformed files: ${t}`)}}async clearSavedTransformedFilesForFile(t){if(this.config.saveTransformedFiles)try{this.logger?.warn?.("clearSavedTransformedFilesForFile requires custom storage implementation")}catch(e){this.logger?.error?.(`Failed to clear saved transformed files for ${t}: ${e}`)}}getCacheStats(){const t={audio:this.audioTransformer?.getCacheStats(),image:this.imageTransformer?.getCacheStats(),video:this.videoTransformer?.getCacheStats()};return t.image===void 0&&delete t.image,t.video===void 0&&delete t.video,t.audio===void 0&&delete t.audio,t}validateQueryParameters(t,e){switch(e){case"audio":{this.validateAudioQueryParameters(t);break}case"image":{this.validateImageQueryParameters(t);break}case"video":{this.validateVideoQueryParameters(t);break}}}validateImageQueryParameters(t){const e=new Set(["alphaQuality","angle","background","bandbool","blur","boolean","brightness","channel","clahe","colourspace","compressionLevel","convolve","cropHeight","cropWidth","delay","dilate","effort","erode","extractChannel","fastShrinkOnLoad","fit","flatten","flip","flop","format","frameRate","gamma","grayscale","greyscale","height","hue","joinChannel","kernel","left","lightness","linear","loop","maxSlope","median","modulate","negate","normalise","normalize","position","quality","recombine","saturation","sharpen","threshold","tint","top","unflatten","width","withoutEnlargement","withoutReduction"]),i=new Set(["bitrate","codec","frameRate","keyFrameInterval","numberOfChannels","sampleRate"]),o=[];for(const n of i)t[n]!==void 0&&o.push(n);if(o.length>0){const n=[...o].toSorted();throw new s(`Invalid query parameters for image transformation: ${n.join(", ")}. Images support: ${[...e].toSorted().join(", ")}. Video/audio parameters (${n.join(", ")}) are not supported for images.`,"INVALID_PARAMS_FOR_IMAGE","image",n,[...e].toSorted())}if(t.fit&&!["contain","cover","fill","inside","outside"].includes(t.fit))throw new s(`Invalid fit value: "${t.fit}". Supported values: "cover", "contain", "fill", "inside", "outside"`,"INVALID_FIT_VALUE","image",["fit"],["cover","contain","fill","inside","outside"]);if(t.format&&!["avif","gif","jpeg","png","tiff","webp"].includes(t.format))throw new s(`Invalid format for image: "${t.format}". Supported formats: jpeg, png, webp, avif, tiff, gif`,"INVALID_FORMAT","image",["format"],["jpeg","png","webp","avif","tiff","gif"]);const a=["left","top","cropWidth","cropHeight"],r=a.filter(n=>t[n]!==void 0);if(r.length>0&&r.length!==a.length)throw new s(`Incomplete crop parameters: ${r.join(", ")}. All crop parameters must be provided: left, top, cropWidth, cropHeight`,"INCOMPLETE_CROP_PARAMS","image",r,a)}validateVideoQueryParameters(t){const e=new Set(["angle","background","bitrate","codec","cropHeight","cropWidth","fit","format","frameRate","height","keyFrameInterval","left","position","quality","top","width","withoutEnlargement","withoutReduction"]),i=new Set(["numberOfChannels","sampleRate"]),o=[];for(const n of i)t[n]!==void 0&&o.push(n);if(o.length>0){const n=[...o].toSorted();throw new s(`Invalid query parameters for video transformation: ${n.join(", ")}. Videos support: ${[...e].toSorted().join(", ")}. Audio-only parameters (${n.join(", ")}) are not supported for videos.`,"INVALID_PARAMS_FOR_VIDEO","video",n,[...e].toSorted())}if(t.fit&&!["contain","cover","fill","inside","outside"].includes(t.fit))throw new s(`Invalid fit value: "${t.fit}". Supported values: "cover", "contain", "fill", "inside", "outside"`,"INVALID_FIT_VALUE","video",["fit"],["cover","contain","fill","inside","outside"]);if(t.codec&&!["av1","avc","hevc","vp8","vp9"].includes(t.codec))throw new s(`Invalid codec for video: "${t.codec}". Supported codecs: avc, hevc, vp8, vp9, av1`,"INVALID_VIDEO_CODEC","video",["codec"],["avc","hevc","vp8","vp9","av1"]);if(t.format&&!["mkv","mp4","ogg","webm"].includes(t.format))throw new s(`Invalid format for video: "${t.format}". Supported formats: mp4, webm, mkv, ogg`,"INVALID_VIDEO_FORMAT","video",["format"],["mp4","webm","mkv","ogg"]);const a=["left","top","cropWidth","cropHeight"],r=a.filter(n=>t[n]!==void 0);if(r.length>0&&r.length!==a.length)throw new s(`Incomplete crop parameters: ${r.join(", ")}. All crop parameters must be provided: left, top, cropWidth, cropHeight`,"INCOMPLETE_CROP_PARAMS","video",r,a);if(t.width!==void 0&&(typeof t.width!="number"||t.width<=0))throw new s(`Invalid width: ${t.width}. Must be a positive number.`,"INVALID_WIDTH","video",["width"],[]);if(t.height!==void 0&&(typeof t.height!="number"||t.height<=0))throw new s(`Invalid height: ${t.height}. Must be a positive number.`,"INVALID_HEIGHT","video",["height"],[]);if(t.bitrate!==void 0&&(typeof t.bitrate!="number"||t.bitrate<=0))throw new s(`Invalid bitrate: ${t.bitrate}. Must be a positive number.`,"INVALID_BITRATE","video",["bitrate"],[]);if(t.frameRate!==void 0&&(typeof t.frameRate!="number"||t.frameRate<=0))throw new s(`Invalid frameRate: ${t.frameRate}. Must be a positive number.`,"INVALID_FRAME_RATE","video",["frameRate"],[]);if(t.keyFrameInterval!==void 0&&(typeof t.keyFrameInterval!="number"||t.keyFrameInterval<=0))throw new s(`Invalid keyFrameInterval: ${t.keyFrameInterval}. Must be a positive number.`,"INVALID_KEY_FRAME_INTERVAL","video",["keyFrameInterval"],[])}generateTransformedFileId(t,e,i){const o=Object.keys(e).filter(n=>e[n]!==void 0).toSorted().map(n=>`${n}:${e[n]}`).join("|"),a=`${t}|${i}|${o}`,r=l("sha256").update(a).digest("hex").slice(0,32);return`${t}_transformed_${r}`}hasTransformations(t){return this.hasImageTransformations(t)||this.hasVideoTransformations(t)||this.hasAudioTransformations(t)}createMediaTransformResult(t,e,i){const o={buffer:t.content,format:this.getFormatFromContentType(t.contentType||""),mediaType:e,originalFile:i,size:t.content.length};switch(e){case"audio":return{...o,bitrate:t.bitrate,duration:t.duration,mediaType:"audio",numberOfChannels:t.numberOfChannels,sampleRate:t.sampleRate};case"image":return{...o,height:t.height,mediaType:"image",width:t.width};case"video":return{...o,bitrate:t.bitrate,duration:t.duration,height:t.height,mediaType:"video",width:t.width};default:return o}}getFormatFromContentType(t){return t?d.getExtension(t)||"application/octet-stream":""}async saveTransformedFile(t,e,i,o){try{const a=this.generateTransformedFileId(e,i,o),r={format:t.format,mediaType:o,originalFileId:e,size:t.size,transformation:i,transformedAt:new Date().toISOString()};o==="image"&&t.width&&t.height?(r.width=t.width,r.height=t.height):o==="video"&&t.width&&t.height?(r.width=t.width,r.height=t.height,r.duration=t.duration,r.bitrate=t.bitrate):o==="audio"&&(r.duration=t.duration,r.numberOfChannels=t.numberOfChannels,r.sampleRate=t.sampleRate,r.bitrate=t.bitrate);const n=await this.storage.create({contentType:d.getType(t.format)??void 0,id:a,metadata:r,originalName:`${a}.${t.format}`,size:t.size});await this.storage.write({body:m.from(t.buffer),contentLength:t.size,id:n.id,start:0}),this.logger?.debug?.(`Saved transformed file: ${a}`)}catch(a){this.logger?.error?.(`Failed to save transformed file: ${a}`)}}validateAudioQueryParameters(t){const e=new Set(["bitrate","codec","format","numberOfChannels","quality","sampleRate"]),i=new Set(["angle","background","cropHeight","cropWidth","fit","frameRate","height","keyFrameInterval","left","position","top","width","withoutEnlargement","withoutReduction"]),o=[];for(const a of i)t[a]!==void 0&&o.push(a);if(o.length>0){const a=[...o].toSorted();throw new s(`Invalid query parameters for audio transformation: ${a.join(", ")}. Audio supports: ${[...e].toSorted().join(", ")}. Video-only parameters (${a.join(", ")}) are not supported for audio.`,"INVALID_PARAMS_FOR_AUDIO","audio",a,[...e].toSorted())}if(t.codec&&!["aac","flac","mp3","opus","vorbis"].includes(t.codec))throw new s(`Invalid codec for audio: "${t.codec}". Supported codecs: aac, opus, mp3, vorbis, flac`,"INVALID_AUDIO_CODEC","audio",["codec"],["aac","opus","mp3","vorbis","flac"]);if(t.format&&!["aac","flac","mp3","ogg","wav"].includes(t.format))throw new s(`Invalid format for audio: "${t.format}". Supported formats: mp3, wav, ogg, aac, flac`,"INVALID_AUDIO_FORMAT","audio",["format"],["mp3","wav","ogg","aac","flac"]);if(t.bitrate!==void 0&&(typeof t.bitrate!="number"||t.bitrate<=0))throw new s(`Invalid bitrate: ${t.bitrate}. Must be a positive number.`,"INVALID_BITRATE","audio",["bitrate"],[]);if(t.numberOfChannels!==void 0&&(typeof t.numberOfChannels!="number"||t.numberOfChannels<=0||t.numberOfChannels>8))throw new s(`Invalid numberOfChannels: ${t.numberOfChannels}. Must be a number between 1 and 8.`,"INVALID_CHANNEL_COUNT","audio",["numberOfChannels"],["1","2","3","4","5","6","7","8"]);if(t.sampleRate!==void 0){const a=[8e3,11025,16e3,22050,32e3,44100,48e3,88200,96e3,192e3];if(typeof t.sampleRate!="number"||!a.includes(t.sampleRate))throw new s(`Invalid sampleRate: ${t.sampleRate}. Supported sample rates: ${a.join(", ")}`,"INVALID_SAMPLE_RATE","audio",["sampleRate"],a.map(String))}}async handleImageTransformation(t,e){const i=[];this.hasImageTransformations(e)&&((e.width||e.height||e.fit)&&i.push({options:{fit:e.fit,height:e.height,position:e.position,width:e.width,withoutEnlargement:e.withoutEnlargement,withoutReduction:e.withoutReduction},type:"resize"}),e.left!==void 0&&e.top!==void 0&&e.cropWidth&&e.cropHeight&&i.push({options:{height:e.cropHeight,left:e.left,top:e.top,width:e.cropWidth},type:"crop"}),e.angle&&i.push({options:{angle:e.angle,background:e.background},type:"rotate"}),e.format?i.push({options:{format:e.format,quality:e.quality},type:"format"}):e.quality&&i.push({options:{quality:e.quality},type:"quality"}));const o=i.length>0?await this.imageTransformer.transform(t,i):await this.imageTransformer.transform(t,[]);return this.convertImageResult(o)}async handleVideoTransformation(t,e){const i=[];this.hasVideoTransformations(e)&&((e.width||e.height||e.fit)&&i.push({options:{fit:e.fit,height:e.height,position:e.position,width:e.width,withoutEnlargement:e.withoutEnlargement,withoutReduction:e.withoutReduction},type:"resize"}),e.left!==void 0&&e.top!==void 0&&e.cropWidth&&e.cropHeight&&i.push({options:{height:Number(e.cropHeight),left:e.left,top:e.top,width:e.cropWidth},type:"crop"}),e.angle&&i.push({options:{angle:e.angle,background:e.background},type:"rotate"}),(e.codec||e.bitrate)&&i.push({options:{bitrate:e.bitrate||e.quality,codec:e.codec,frameRate:e.frameRate,keyFrameInterval:e.keyFrameInterval},type:"codec"}),e.format&&i.push({options:{format:e.format},type:"format"}));const o=i.length>0?await this.videoTransformer.transform(t,i):await this.videoTransformer.transform(t,[]);return this.convertVideoResult(o)}async handleAudioTransformation(t,e){const i=[];this.hasAudioTransformations(e)&&(e.sampleRate&&i.push({options:{sampleRate:e.sampleRate},type:"resample"}),e.numberOfChannels&&i.push({options:{numberOfChannels:e.numberOfChannels},type:"channels"}),(e.codec||e.bitrate)&&i.push({options:{bitrate:e.bitrate||e.quality,codec:e.codec},type:"codec"}),e.format&&i.push({options:{format:e.format},type:"format"}));const o=i.length>0?await this.audioTransformer.transform(t,i):await this.audioTransformer.transform(t,[]);return this.convertAudioResult(o)}parseQuery(t){if(typeof t=="string")return this.parseURLSearchParams(new URLSearchParams(t));if(t instanceof URLSearchParams)return this.parseURLSearchParams(t);const e=t;return t.left&&(e.left=Number.parseInt(t.left,10)),t.top&&(e.top=Number.parseInt(t.top,10)),t.cropWidth&&(e.cropWidth=Number.parseInt(t.cropWidth,10)),t.cropHeight&&(e.cropHeight=Number.parseInt(t.cropHeight,10)),t.angle&&(e.angle=Number.parseInt(t.angle,10)),t.quality&&(e.quality=Number.parseInt(t.quality,10)),t.width&&(e.width=Number.parseInt(t.width,10)),t.height&&(e.height=Number.parseInt(t.height,10)),t.bitrate&&(e.bitrate=Number.parseInt(t.bitrate,10)),t.frameRate&&(e.frameRate=Number.parseInt(t.frameRate,10)),t.keyFrameInterval&&(e.keyFrameInterval=Number.parseInt(t.keyFrameInterval,10)),t.numberOfChannels&&(e.numberOfChannels=Number.parseInt(t.numberOfChannels,10)),t.sampleRate&&(e.sampleRate=Number.parseInt(t.sampleRate,10)),e}parseBooleanParameter(t){if(t!==null)return t==="true"||t==="1"}parseURLSearchParams(t){const e={};if(t.has("format")&&(e.format=t.get("format")??void 0),t.has("quality")&&(e.quality=t.get("quality")?Number.parseInt(t.get("quality"),10):void 0),t.has("width")&&(e.width=t.get("width")?Number.parseInt(t.get("width"),10):void 0),t.has("height")&&(e.height=t.get("height")?Number.parseInt(t.get("height"),10):void 0),t.has("fit")){const i=t.get("fit");i&&["contain","cover","fill","inside","outside"].includes(i)&&(e.fit=i)}if(t.has("position")&&(e.position=t.get("position")??void 0),t.has("withoutEnlargement")){const i=t.get("withoutEnlargement");e.withoutEnlargement=i==="true"?!0:void 0}if(t.has("withoutReduction")){const i=t.get("withoutReduction");e.withoutReduction=i==="true"?!0:void 0}if(t.has("left")&&(e.left=t.get("left")?Number.parseInt(t.get("left"),10):void 0),t.has("top")&&(e.top=t.get("top")?Number.parseInt(t.get("top"),10):void 0),t.has("cropWidth")&&(e.cropWidth=t.get("cropWidth")?Number.parseInt(t.get("cropWidth"),10):void 0),t.has("cropHeight")&&(e.cropHeight=t.get("cropHeight")?Number.parseInt(t.get("cropHeight"),10):void 0),t.has("angle")){const i=t.get("angle")?Number.parseInt(t.get("angle"),10):void 0;i!==void 0&&(e.angle=i)}if(t.has("background")&&(e.background=t.get("background")??void 0),t.has("blur")&&(e.blur=this.parseBooleanParameter(t.get("blur"))),t.has("sharpen")&&(e.sharpen=this.parseBooleanParameter(t.get("sharpen"))),t.has("median")&&(e.median=t.get("median")?Number.parseInt(t.get("median"),10):void 0),t.has("clahe")&&(e.clahe=this.parseBooleanParameter(t.get("clahe"))),t.has("threshold")&&(e.threshold=t.get("threshold")?Number.parseInt(t.get("threshold"),10):void 0),t.has("gamma")&&(e.gamma=this.parseBooleanParameter(t.get("gamma"))),t.has("negate")&&(e.negate=this.parseBooleanParameter(t.get("negate"))),(t.has("normalise")||t.has("normalize"))&&(e.normalise=this.parseBooleanParameter(t.get("normalise"))||this.parseBooleanParameter(t.get("normalize"))),t.has("flatten")&&(e.flatten=this.parseBooleanParameter(t.get("flatten"))),t.has("unflatten")&&(e.unflatten=this.parseBooleanParameter(t.get("unflatten"))),t.has("flip")&&(e.flip=this.parseBooleanParameter(t.get("flip"))),t.has("flop")&&(e.flop=this.parseBooleanParameter(t.get("flop"))),t.has("affine")&&(e.affine=this.parseBooleanParameter(t.get("affine"))),t.has("dilate")&&(e.dilate=this.parseBooleanParameter(t.get("dilate"))),t.has("erode")&&(e.erode=this.parseBooleanParameter(t.get("erode"))),t.has("pipelineColourspace")&&(e.pipelineColourspace=this.parseBooleanParameter(t.get("pipelineColourspace"))),t.has("toColourspace")&&(e.toColourspace=this.parseBooleanParameter(t.get("toColourspace"))),t.has("removeAlpha")&&(e.removeAlpha=this.parseBooleanParameter(t.get("removeAlpha"))),t.has("ensureAlpha")&&(e.ensureAlpha=this.parseBooleanParameter(t.get("ensureAlpha"))),(t.has("greyscale")||t.has("grayscale"))&&(e.greyscale=this.parseBooleanParameter(t.get("greyscale"))||this.parseBooleanParameter(t.get("grayscale"))),t.has("modulate")&&(e.modulate=this.parseBooleanParameter(t.get("modulate"))),t.has("tint")&&(e.tint=this.parseBooleanParameter(t.get("tint"))),t.has("brightness")&&(e.brightness=t.get("brightness")?Number.parseFloat(t.get("brightness")):void 0),t.has("saturation")&&(e.saturation=t.get("saturation")?Number.parseFloat(t.get("saturation")):void 0),t.has("hue")&&(e.hue=t.get("hue")?Number.parseInt(t.get("hue"),10):void 0),t.has("lightness")&&(e.lightness=t.get("lightness")?Number.parseInt(t.get("lightness"),10):void 0),t.has("kernel")&&(e.kernel=t.get("kernel")??void 0),t.has("fastShrinkOnLoad")&&(e.fastShrinkOnLoad=t.get("fastShrinkOnLoad")==="true"),t.has("codec")){const i=t.get("codec");i&&["avc","hevc","vp8","vp9","av1","aac","opus","mp3","vorbis","flac"].includes(i)&&(e.codec=i)}return t.has("bitrate")&&(e.bitrate=t.get("bitrate")?Number.parseInt(t.get("bitrate"),10):void 0),t.has("frameRate")&&(e.frameRate=t.get("frameRate")?Number.parseInt(t.get("frameRate"),10):void 0),t.has("keyFrameInterval")&&(e.keyFrameInterval=t.get("keyFrameInterval")?Number.parseInt(t.get("keyFrameInterval"),10):void 0),t.has("numberOfChannels")&&(e.numberOfChannels=t.get("numberOfChannels")?Number.parseInt(t.get("numberOfChannels"),10):void 0),t.has("sampleRate")&&(e.sampleRate=t.get("sampleRate")?Number.parseInt(t.get("sampleRate"),10):void 0),e}detectMediaType(t){if(!t)throw new Error("Cannot detect media type: no content type provided");if(!g(t))throw new Error(`Unknown or invalid content type: ${t}`);if(t.startsWith("image/"))return"image";if(t.startsWith("video/"))return"video";if(t.startsWith("audio/"))return"audio";throw new Error(`Unsupported media type for content type: ${t}`)}hasImageTransformations(t){return!!(t.width||t.height||t.fit||t.position||t.withoutEnlargement||t.withoutReduction||t.left!==void 0||t.top!==void 0||t.cropWidth||t.cropHeight||t.angle!==void 0||t.background||t.blur||t.sharpen||t.median||t.clahe||t.threshold!==void 0||t.gamma||t.negate||t.normalise||t.flatten||t.unflatten||t.flip||t.flop||t.greyscale||t.modulate||t.tint||t.brightness!==void 0||t.saturation!==void 0||t.hue!==void 0||t.lightness!==void 0||t.kernel||t.fastShrinkOnLoad||t.affine||t.dilate||t.erode||t.pipelineColourspace||t.toColourspace||t.removeAlpha||t.ensureAlpha||t.format||t.quality)}hasVideoTransformations(t){return!!(t.width||t.height||t.fit||t.position||t.withoutEnlargement||t.withoutReduction||t.left!==void 0||t.top!==void 0||t.cropWidth||t.cropHeight||t.angle||t.background||t.codec||t.bitrate||t.frameRate||t.keyFrameInterval||t.format||t.quality)}hasAudioTransformations(t){return!!(t.sampleRate||t.numberOfChannels||t.codec||t.bitrate||t.format||t.quality)}convertImageResult(t){return{buffer:t.buffer,format:t.format,height:t.height,mediaType:"image",originalFile:t.originalFile,size:t.size,width:t.width}}convertVideoResult(t){return{bitrate:t.bitrate,buffer:t.buffer,duration:t.duration,format:t.format,height:t.height,mediaType:"video",originalFile:t.originalFile,size:t.size,width:t.width}}convertAudioResult(t){return{bitrate:t.bitrate,buffer:t.buffer,duration:t.duration,format:t.format,mediaType:"audio",numberOfChannels:t.numberOfChannels,originalFile:t.originalFile,sampleRate:t.sampleRate,size:t.size}}}export{R as default};
@@ -0,0 +1 @@
1
+ import r from"./MetaStorage-DPEUyWgN.js";class a extends r{store;constructor(e){super(e),this.store=e?.store??new Map}async save(e,t){return this.store.set(e,{...t}),{...t}}async get(e){const t=this.store.get(e);if(!t)throw new Error(`Meta not found for id: ${e}`);return{...t}}async delete(e){this.store.delete(e)}async touch(e,t){return this.save(e,t)}clear(){this.store.clear()}}export{a as default};
@@ -1 +1 @@
1
- import{Readable as w}from"node:stream";import{F as p}from"./index-nZWCQrSe.js";import{throwErrorCode as f,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as c}from"./storage-DR7qdwBN.js";import T from"./MemoryMetaStorage-Ksgh9pe7.js";import l from"./File-W8aOo15X.js";import{t as u}from"./get-file-status-y3wTtDQs.js";import{e as b}from"./has-content-50BsqrWw.js";import{t as A}from"./update-size-DuNuLyxj.js";class F extends c{static name="memory";checksumTypes=["md5"];supportsRange=!0;meta;store;constructor(e={}){if(super(e),this.store=new Map,this.meta=e.metaStorage??new T({...e.metaStorageConfig,logger:this.logger}),e.initial)for(const[s,t]of Object.entries(e.initial)){c.assertSafeId(s);const a=Buffer.from(t),r=new Date().toISOString(),n=p(a);this.store.set(s,{bytes:a,contentType:"application/octet-stream",createdAt:r,eTag:n,metadata:{},modifiedAt:r});const i=new l({contentType:"application/octet-stream",id:s,metadata:{name:s,size:a.length},originalName:s,size:a.length});i.name=s,i.bytesWritten=a.length,i.ETag=n,i.createdAt=r,i.modifiedAt=r,i.status=u(i),this.meta.save(s,i).catch(()=>{})}}get raw(){return this.store}async create(e,s){return this.instrumentOperation("create",async()=>{const t=new l(e);return t.name=this.namingFunction(t),c.assertSafeId(t.name),await this.validate(t),t.bytesWritten=0,t.status=u(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,s){return this.instrumentOperation("write",async()=>{const t=await this.getMeta(e.id);if(!b(e))return t;const{body:a,start:r}=e,n=[];for await(const o of a)Buffer.isBuffer(o)?n.push(o):typeof o=="string"?n.push(Buffer.from(o)):ArrayBuffer.isView(o)?n.push(Buffer.from(o.buffer,o.byteOffset,o.byteLength)):n.push(Buffer.from(o));const i=Buffer.concat(n),m=this.store.get(t.name)?.bytes,d=r===0||!m?i:Buffer.concat([m.subarray(0,r),i]),y=new Date().toISOString(),g={bytes:d,contentType:t.contentType,createdAt:this.store.get(t.name)?.createdAt??y,eTag:p(d),metadata:{...t.metadata},modifiedAt:y};return this.store.set(t.name,g),t.bytesWritten=d.length,t.ETag=g.eTag,t.modifiedAt=g.modifiedAt,A(t,d.length),t.status=u(t),await this.saveMeta(t),t.status==="completed"&&await this.onComplete(t,{}),t})}async get({id:e},s){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);if(i>m||i>=a.bytes.length)return f(h.BAD_REQUEST,`Invalid range ${i}-${n.end??""}`);r=a.bytes.subarray(i,m+1)}return{content:r,contentType:a.contentType,ETag:a.eTag,expiredAt:t.expiredAt,id:e,metadata:{...a.metadata},modifiedAt:a.modifiedAt,name:t.name,originalName:t.originalName,size:r.length}})}async getStream({id:e},s){return this.instrumentOperation("getStream",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);r=a.bytes.subarray(i,m+1)}return{headers:{"Content-Length":String(r.length),"Content-Type":a.contentType,ETag:a.eTag,"Last-Modified":a.modifiedAt},size:r.length,stream:w.from(r)}})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const s=await this.meta.get(e);return this.store.has(s.name)}catch{return!1}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{const s=await this.getMeta(e);this.store.delete(s.name),await this.deleteMeta(e);const t={...s,status:"deleted"};return await this.onDelete(t),t})}async copy(e,s){return this.instrumentOperation("copy",async()=>{c.assertSafeId(e),c.assertSafeId(s);const t=await this.getMeta(e),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);const r=new Date().toISOString();this.store.set(s,{...a,bytes:Buffer.from(a.bytes),metadata:{...a.metadata},modifiedAt:r});const n={...t,ETag:a.eTag,id:s,modifiedAt:r,name:s};return await this.saveMeta(n),n})}async move(e,s){return this.instrumentOperation("move",async()=>{if(e===s)return this.getMeta(e);const t=await this.copy(e,s);return await this.delete({id:e}),t})}async list(){return this.instrumentOperation("list",async()=>{const e=[];for(const[s,t]of this.store)e.push({contentType:t.contentType,createdAt:t.createdAt,ETag:t.eTag,id:s,metadata:{...t.metadata},modifiedAt:t.modifiedAt,name:s,size:t.bytes.length});return e})}async getReadUrl(e){return c.assertSafeId(e),`memory://${e}`}async getUploadUrl(e){return c.assertSafeId(e),`memory://${e}`}}export{F as default};
1
+ import w from"./MemoryMetaStorage-DdAIGIVO.js";import{Readable as T}from"node:stream";import{e as l}from"./index-DKzU1HON.js";import{throwErrorCode as d,ERRORS as h}from"./ERRORS-olUcTqo2.js";import{B as c}from"./storage-uypoNkqu.js";import p from"./File-DLAa0hBv.js";import{g as y}from"./get-file-status-B8WmWzcM.js";import{h as b}from"./has-content-96mmyLn2.js";import{u as S}from"./update-size-Dxc1hvbI.js";class _ extends c{static name="memory";checksumTypes=["md5"];supportsRange=!0;meta;store;constructor(e={}){if(super(e),this.store=new Map,this.meta=e.metaStorage??new w({...e.metaStorageConfig,logger:this.logger}),e.initial)for(const[s,t]of Object.entries(e.initial)){c.assertSafeId(s);const a=Buffer.from(t),r=new Date().toISOString(),n=l(a);this.store.set(s,{bytes:a,contentType:"application/octet-stream",createdAt:r,eTag:n,metadata:{},modifiedAt:r});const i=new p({contentType:"application/octet-stream",id:s,metadata:{name:s,size:a.length},originalName:s,size:a.length});i.name=s,i.bytesWritten=a.length,i.ETag=n,i.createdAt=r,i.modifiedAt=r,i.status=y(i),this.meta.save(s,i).catch(()=>{})}}get raw(){return this.store}async create(e,s){return this.instrumentOperation("create",async()=>{const t=new p(e);return t.name=this.namingFunction(t),c.assertSafeId(t.name),await this.validate(t),t.bytesWritten=0,t.status=y(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,s){return this.instrumentOperation("write",async()=>{const t=await this.getMeta(e.id);if(!b(e))return t;const{body:a,start:r}=e,n=[];for await(const o of a)Buffer.isBuffer(o)?n.push(o):typeof o=="string"?n.push(Buffer.from(o)):ArrayBuffer.isView(o)?n.push(Buffer.from(o.buffer,o.byteOffset,o.byteLength)):n.push(Buffer.from(o));const i=Buffer.concat(n),m=this.store.get(t.name)?.bytes,f=r===0||!m?i:Buffer.concat([m.subarray(0,r),i]),u=new Date().toISOString(),g={bytes:f,contentType:t.contentType,createdAt:this.store.get(t.name)?.createdAt??u,eTag:l(f),metadata:{...t.metadata},modifiedAt:u};return this.store.set(t.name,g),t.bytesWritten=f.length,t.ETag=g.eTag,t.modifiedAt=g.modifiedAt,S(t,f.length),t.status=y(t),await this.saveMeta(t),t.status==="completed"&&await this.onComplete(t,{}),t})}async get({id:e},s){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return d(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);if(i>m||i>=a.bytes.length)return d(h.BAD_REQUEST,`Invalid range ${i}-${n.end??""}`);r=a.bytes.subarray(i,m+1)}return{content:r,contentType:a.contentType,ETag:a.eTag,expiredAt:t.expiredAt,id:e,metadata:{...a.metadata},modifiedAt:a.modifiedAt,name:t.name,originalName:t.originalName,size:r.length}})}async getStream({id:e},s){return this.instrumentOperation("getStream",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return d(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);r=a.bytes.subarray(i,m+1)}return{headers:{"Content-Length":String(r.length),"Content-Type":a.contentType,ETag:a.eTag,"Last-Modified":a.modifiedAt},size:r.length,stream:T.from(r)}})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const s=await this.meta.get(e);return this.store.has(s.name)}catch{return!1}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{const s=await this.getMeta(e);this.store.delete(s.name),await this.deleteMeta(e);const t={...s,status:"deleted"};return await this.onDelete(t),t})}async copy(e,s){return this.instrumentOperation("copy",async()=>{c.assertSafeId(e),c.assertSafeId(s);const t=await this.getMeta(e),a=this.store.get(t.name);if(!a)return d(h.FILE_NOT_FOUND);const r=new Date().toISOString();this.store.set(s,{...a,bytes:Buffer.from(a.bytes),metadata:{...a.metadata},modifiedAt:r});const n={...t,ETag:a.eTag,id:s,modifiedAt:r,name:s};return await this.saveMeta(n),n})}async move(e,s){return this.instrumentOperation("move",async()=>{if(e===s)return this.getMeta(e);const t=await this.copy(e,s);return await this.delete({id:e}),t})}async list(){return this.instrumentOperation("list",async()=>{const e=[];for(const[s,t]of this.store)e.push({contentType:t.contentType,createdAt:t.createdAt,ETag:t.eTag,id:s,metadata:{...t.metadata},modifiedAt:t.modifiedAt,name:s,size:t.bytes.length});return e})}async getReadUrl(e){return c.assertSafeId(e),`memory://${e}`}async getUploadUrl(e){return c.assertSafeId(e),`memory://${e}`}}export{_ as default};
@@ -0,0 +1 @@
1
+ const f=" ".codePointAt(0)??32,l=",".codePointAt(0)??44,c=/^[\d+/A-Z]*={0,2}$/i,d=t=>{if(typeof t!="string")return!1;const e=Number.parseFloat(t);return!Number.isNaN(e)&&Number.isFinite(e)};class g{psize;pname;pfiletype;ptype;pmimeType;pcontentType;ptitle;pfilename;poriginalName;plastModified}const p=t=>{if(t.length===0)return!1;for(let e=0;e<t.length;e+=1){const r=t.codePointAt(e);if(r>127||r===f||r===l)return!1}return!0},u=t=>t.length%4!==0?!1:c.test(t),m=t=>Object.entries(t).map(([e,r])=>{if(r==null)return e;const i=typeof r=="object"?JSON.stringify(r):String(r),o=Buffer.from(i,"utf8").toString("base64");return`${e} ${o}`}).join(","),h=t=>{const e={};if(!t||t.trim().length===0)throw new Error("Metadata string is not valid");for(const r of t.split(",")){const i=r.split(" "),[o,a]=i;if((i.length===1||i.length===2)&&p(o)&&(i.length===1||u(a))&&!(o in e)){let n="";i.length===1?n=void 0:a&&(n=Buffer.from(a,"base64").toString("utf8"));let s=n;if(n!==void 0)try{s=JSON.parse(n)}catch{n==="true"?s=!0:n==="false"?s=!1:d(n)&&(s=Number(n))}e[o]=s}else throw new Error("Metadata string is not valid")}return e};export{g as Metadata,h as parseMetadata,m as stringifyMetadata,p as validateKey,u as validateValue};
@@ -1 +1 @@
1
- import{Readable as a}from"node:stream";import{parseMultipartRequest as m,MaxFileSizeExceededError as h,MultipartParseError as c}from"@remix-run/multipart-parser";import{n as i}from"./headers-BAiAKekR.js";import{b as u,B as f}from"./storage-DR7qdwBN.js";import{C as p}from"./base-handler-fetch-yrYrukwL.js";import{p as g}from"./multipart-base-BOzY19lb.js";const x=/^multipart\/.+|application\/x-www-form-urlencoded$/i,S=d=>{let t;try{const r=new URL(d).pathname.split("/").filter(Boolean);t=r[r.length-1]||void 0}catch{return}if(t){try{f.assertSafeId(t)}catch{throw i(400,`Invalid file id: "${t}"`)}return t}};class n extends p{static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const r=this;this.multipartBase=new class extends g{get storage(){return r.storage}get maxFileSize(){return r.maxFileSize}get maxHeaderSize(){return r.maxHeaderSize}buildFileUrl(e,s){return r.buildFileUrl({url:e},s)}createStreamFromBytes(e){return e instanceof Uint8Array?a.from(Buffer.from(e)):e instanceof ArrayBuffer?a.from(Buffer.from(e)):a.from(new Uint8Array(0))}createEmptyStream(){return a.from(new Uint8Array(0))}}}async post(t){const r=t.headers.get("content-type")||"";if(!x.test(r.split(";")[0]||""))throw i(400,"Invalid content-type");try{const e=[];for await(const o of m(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(o);const s=e.find(o=>o.isFile);if(!s)throw i(400,"No file found in multipart request");const l=t.url;return this.multipartBase.handlePost(s,e,l)}catch(e){throw e instanceof h?i(413,"File size limit exceeded"):e instanceof c?i(400,"Invalid multipart request"):e instanceof u&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){const r=S(t.url);if(!r)throw i(404,"File not found");try{return this.multipartBase.handleDelete(r)}catch(e){throw e.code==="ENOENT"?i(404,"File not found"):e}}async options(t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||n.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(t){throw i(500,"GET requests should be handled via fetch() method")}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{n as default};
1
+ import{Readable as a}from"node:stream";import{parseMultipartRequest as h,MaxFileSizeExceededError as c,MultipartParseError as m}from"@remix-run/multipart-parser";import{c as i}from"./headers-erjZrwbT.js";import{V as u,B as f}from"./storage-uypoNkqu.js";import{B as p}from"./base-handler-fetch-DDSPIzWT.js";import{M as g}from"./multipart-base-0AXqLN-B.js";const x=/^multipart\/.+|application\/x-www-form-urlencoded$/i,S=d=>{let t;try{const e=new URL(d).pathname.split("/").filter(Boolean);t=e[e.length-1]||void 0}catch{return}if(t){try{f.assertSafeId(t)}catch{throw i(400,`Invalid file id: "${t}"`)}return t}};class n extends p{static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const r=this;this.multipartBase=new class extends g{get storage(){return r.storage}get maxFileSize(){return r.maxFileSize}get maxHeaderSize(){return r.maxHeaderSize}buildFileUrl(e,s){return r.buildFileUrl({url:e},s)}createStreamFromBytes(e){return e instanceof Uint8Array?a.from(Buffer.from(e)):e instanceof ArrayBuffer?a.from(Buffer.from(e)):a.from(new Uint8Array(0))}createEmptyStream(){return a.from(new Uint8Array(0))}}}async post(t){const r=t.headers.get("content-type")||"";if(!x.test(r.split(";")[0]||""))throw i(400,"Invalid content-type");try{const e=[];for await(const o of h(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(o);const s=e.find(o=>o.isFile);if(!s)throw i(400,"No file found in multipart request");const l=t.url;return this.multipartBase.handlePost(s,e,l)}catch(e){throw e instanceof c?i(413,"File size limit exceeded"):e instanceof m?i(400,"Invalid multipart request"):e instanceof u&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){const r=S(t.url);if(!r)throw i(404,"File not found");try{return this.multipartBase.handleDelete(r)}catch(e){throw e.code==="ENOENT"?i(404,"File not found"):e}}async options(t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||n.methods).map(e=>e.toUpperCase()).join(", ")},statusCode:204}}async get(t){throw i(500,"GET requests should be handled via fetch() method")}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{n as default};