@visulima/storage 1.0.0-alpha.28 → 1.0.0-alpha.29

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 (190) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +2 -2
  3. package/dist/adapter/nuxt/module.d.ts +4 -4
  4. package/dist/adapter/nuxt/node_modules/.bin/nuxi +2 -2
  5. package/dist/adapter/nuxt/node_modules/.bin/nuxt +2 -2
  6. package/dist/ai/ai-sdk/index.d.ts +3 -3
  7. package/dist/ai/claude/index.d.ts +2 -2
  8. package/dist/ai/openai/index.d.ts +3 -3
  9. package/dist/ai/tanstack/index.d.ts +2 -2
  10. package/dist/handler/http/fetch/index.d.ts +7 -7
  11. package/dist/handler/http/fetch/index.js +1 -1
  12. package/dist/handler/http/hono/index.d.ts +4 -4
  13. package/dist/handler/http/hono/index.js +1 -1
  14. package/dist/handler/http/nextjs/index.d.ts +4 -4
  15. package/dist/handler/http/nextjs/index.js +1 -1
  16. package/dist/handler/http/node/index.d.ts +7 -7
  17. package/dist/handler/http/node/index.js +1 -1
  18. package/dist/handler/http/solid-start/index.d.ts +4 -4
  19. package/dist/handler/http/solid-start/index.js +1 -1
  20. package/dist/index.d.ts +5 -5
  21. package/dist/index.js +1 -1
  22. package/dist/packem_shared/{AwsLightMetaStorage-DHz1nf_H.js → AwsLightMetaStorage-B-iQbToR.js} +1 -1
  23. package/dist/packem_shared/AwsLightStorage-w21RxjUm.js +1 -0
  24. package/dist/packem_shared/AzureSMetaStorage-CR-lfQNQ.js +1 -0
  25. package/dist/packem_shared/AzureStorage-2kl7JDXs.js +1 -0
  26. package/dist/packem_shared/BoxMetaStorage-DLdXbZaV.js +1 -0
  27. package/dist/packem_shared/BoxStorage-BUeEJoGL.js +1 -0
  28. package/dist/packem_shared/BunS3File-D-SRiyrm.js +1 -0
  29. package/dist/packem_shared/BunS3MetaStorage-Bv_CTTMz.js +1 -0
  30. package/dist/packem_shared/BunS3Storage-WM3rF6Fw.js +1 -0
  31. package/dist/packem_shared/BunnyMetaStorage-DNMTSeoN.js +1 -0
  32. package/dist/packem_shared/BunnyStorage-D3s2fRB3.js +1 -0
  33. package/dist/packem_shared/CloudinaryFile-B5-m33eS.js +1 -0
  34. package/dist/packem_shared/CloudinaryMetaStorage-DEBk5eQy.js +1 -0
  35. package/dist/packem_shared/CloudinaryStorage-BBE2-aVz.js +1 -0
  36. package/dist/packem_shared/DiskStorage-DL0GiG6k.js +1 -0
  37. package/dist/packem_shared/{DiskStorageWithChecksum-CbXWpSOr.js → DiskStorageWithChecksum-BvUTn7O-.js} +1 -1
  38. package/dist/packem_shared/{DropboxMetaStorage-CICuUZ1n.js → DropboxMetaStorage-C6vj1QDA.js} +1 -1
  39. package/dist/packem_shared/DropboxStorage-BL3OIdE_.js +1 -0
  40. package/dist/packem_shared/{Files-BhvjnhTE.js → Files-CJh9_N-9.js} +1 -1
  41. package/dist/packem_shared/FirebaseFile-JEu3plMP.js +1 -0
  42. package/dist/packem_shared/FirebaseMetaStorage-CzyOim-J.js +1 -0
  43. package/dist/packem_shared/FirebaseStorage-lXMXy3Pm.js +2 -0
  44. package/dist/packem_shared/FtpFile-B8jaICTB.js +1 -0
  45. package/dist/packem_shared/FtpMetaStorage-1Njy0DpU.js +1 -0
  46. package/dist/packem_shared/FtpStorage-Dw94efNW.js +1 -0
  47. package/dist/packem_shared/{GCSMetaStorage-Cm_Pse62.js → GCSMetaStorage-DvRxZhmq.js} +1 -1
  48. package/dist/packem_shared/GCStorage-U4f4WsWC.js +1 -0
  49. package/dist/packem_shared/{GoogleDriveMetaStorage-rghGy3Fa.js → GoogleDriveMetaStorage-WGuUZPyx.js} +1 -1
  50. package/dist/packem_shared/GoogleDriveStorage-C0NhBBWH.js +1 -0
  51. package/dist/packem_shared/{LocalMetaStorage-B5uh1snG.js → LocalMetaStorage-QMKL7McF.js} +1 -1
  52. package/dist/packem_shared/{Multipart-7FSSy2n1.js → Multipart-CIFfQksD.js} +1 -1
  53. package/dist/packem_shared/{Multipart-DACQFsrn.js → Multipart-D9WIud9R.js} +1 -1
  54. package/dist/packem_shared/NetlifyBlobMetaStorage-ClIFdTkT.js +1 -0
  55. package/dist/packem_shared/NetlifyBlobStorage-CO89TGvF.js +1 -0
  56. package/dist/packem_shared/OneDriveMetaStorage-DS4f83X2.js +1 -0
  57. package/dist/packem_shared/OneDriveStorage-jAN46vRm.js +1 -0
  58. package/dist/packem_shared/PocketBaseFile-CkAiSBb0.js +1 -0
  59. package/dist/packem_shared/PocketBaseMetaStorage-B6utPncj.js +1 -0
  60. package/dist/packem_shared/PocketBaseStorage-DpOjOKAt.js +1 -0
  61. package/dist/packem_shared/{Rest-5NwM1xYj.js → Rest-BuD3ySAg.js} +1 -1
  62. package/dist/packem_shared/{Rest-y8Vz2Rt0.js → Rest-URrQ5FYM.js} +1 -1
  63. package/dist/packem_shared/S3Storage-n1ohEZj4.js +1 -0
  64. package/dist/packem_shared/SftpFile-CQCxZNVq.js +1 -0
  65. package/dist/packem_shared/SftpMetaStorage-DYqXwCdM.js +1 -0
  66. package/dist/packem_shared/SftpStorage-Ban-WN8v.js +1 -0
  67. package/dist/packem_shared/SharePointFile-BA6X9Sxr.js +1 -0
  68. package/dist/packem_shared/SharePointMetaStorage-DVM5-X6g.js +1 -0
  69. package/dist/packem_shared/SharePointStorage-BY90zh1c.js +1 -0
  70. package/dist/packem_shared/SupabaseMetaStorage-ivXoYVUu.js +1 -0
  71. package/dist/packem_shared/SupabaseStorage-pNbHAE1Y.js +1 -0
  72. package/dist/packem_shared/{Tus-CJMcygk7.js → Tus-Fp_hx5ug.js} +1 -1
  73. package/dist/packem_shared/{Tus-BCVAbJIi.js → Tus-TNG9HAY8.js} +1 -1
  74. package/dist/packem_shared/UploadThingMetaStorage-BvKNzgm7.js +1 -0
  75. package/dist/packem_shared/UploadThingStorage-BcmIE2dI.js +1 -0
  76. package/dist/packem_shared/{VercelBlobMetaStorage-Do9ZoKrl.js → VercelBlobMetaStorage-CwaqWucZ.js} +1 -1
  77. package/dist/packem_shared/VercelBlobStorage-C89IUiQ1.js +1 -0
  78. package/dist/packem_shared/alibaba-BJQ6ijoK.js +1 -0
  79. package/dist/packem_shared/aws-light-meta-storage-CstQBYXG.js +4 -0
  80. package/dist/packem_shared/azure-meta-storage-C4SrMtT2.js +1 -0
  81. package/dist/packem_shared/{base-handler-core-BfwZ1RS1.js → base-handler-core-BYDQditz.js} +1 -1
  82. package/dist/packem_shared/{base-handler-fetch-CLxqXTQf.js → base-handler-fetch-DWzsPkmV.js} +1 -1
  83. package/dist/packem_shared/{base-handler-node-DBZjcqsp.js → base-handler-node-Dety2rQB.js} +1 -1
  84. package/dist/packem_shared/defaultCloudStorageFileNameValidation-shIZX_7L.js +1 -0
  85. package/dist/packem_shared/disk-storage-CKAJvhcj.js +1 -0
  86. package/dist/packem_shared/{disk-storage-with-checksum.d-8gCPEZZC.d.ts → disk-storage-with-checksum.d-mHcg2uLw.d.ts} +1 -1
  87. package/dist/packem_shared/{executors.d-DgroC6pk.d.ts → executors.d-X4hz3zfu.d.ts} +1 -1
  88. package/dist/packem_shared/exoscale-O0HzxoDz.js +1 -0
  89. package/dist/packem_shared/filebase-D-urO4Ob.js +1 -0
  90. package/dist/packem_shared/{gcs-meta-storage-DibQBpU8.js → gcs-meta-storage-Br_I-m9X.js} +1 -1
  91. package/dist/packem_shared/ibmCos-Rx_yku4H.js +1 -0
  92. package/dist/packem_shared/idriveE2-BFhw0Vwy.js +1 -0
  93. package/dist/packem_shared/index-B4ETk0Lu.js +5 -0
  94. package/dist/packem_shared/{index.d-CKaAalRr.d.ts → index.d-C4Fivh4I.d.ts} +1 -1
  95. package/dist/packem_shared/isRetryableError-BhizNeAz.js +1 -0
  96. package/dist/packem_shared/{local-meta-storage-CT1audnK.js → local-meta-storage-Bi0mK6gD.js} +1 -1
  97. package/dist/packem_shared/{local-meta-storage.d-KWaPZTSN.d.ts → local-meta-storage.d-B11vHYNm.d.ts} +1 -1
  98. package/dist/packem_shared/{media-transformer.d-Dt9W_its.d.ts → media-transformer.d-j1W9HAXw.d.ts} +2 -2
  99. package/dist/packem_shared/oracleCloud-D5T9s4JV.js +1 -0
  100. package/dist/packem_shared/ovhCloud-DCwef2fe.js +1 -0
  101. package/dist/packem_shared/posix-dirname-CiHXPPnw.js +1 -0
  102. package/dist/packem_shared/{rest-base-CCv78k7h.js → rest-base-DI7xFXr5.js} +1 -1
  103. package/dist/packem_shared/s3-base-storage-Dbexfg7p.js +1 -0
  104. package/dist/packem_shared/{s3-base-storage.d-DTxJKx3M.d.ts → s3-base-storage.d-V3N2nKCt.d.ts} +31 -22
  105. package/dist/packem_shared/scaleway-ygRXOss9.js +1 -0
  106. package/dist/packem_shared/storage-Dh0tJh7j.js +1 -0
  107. package/dist/packem_shared/{storage.d-D9YA4MRs.d.ts → storage.d-RteRC-cG.d.ts} +131 -65
  108. package/dist/packem_shared/tencent-CAcAGaIW.js +1 -0
  109. package/dist/packem_shared/{tus-base.d-BeCT7hH6.d.ts → tus-base.d-wZsb3umJ.d.ts} +3 -3
  110. package/dist/packem_shared/{types.d-P2Kxr4cB.d.ts → types.d-B5qPfCr5.d.ts} +2 -2
  111. package/dist/packem_shared/types.d-ChNXbbHG.d.ts +104 -0
  112. package/dist/packem_shared/{types.d-CBvMCJmv.d.ts → types.d-DzPvh74p.d.ts} +2 -2
  113. package/dist/packem_shared/vultr-lK9L-sFk.js +1 -0
  114. package/dist/packem_shared/yandex-ZwvE77v4.js +1 -0
  115. package/dist/storage/aws/clients/index.d.ts +372 -1
  116. package/dist/storage/aws/clients/index.js +1 -1
  117. package/dist/storage/aws/index.d.ts +13 -13
  118. package/dist/storage/aws/index.js +1 -1
  119. package/dist/storage/aws-light/index.d.ts +13 -13
  120. package/dist/storage/aws-light/index.js +1 -1
  121. package/dist/storage/azure/index.d.ts +82 -14
  122. package/dist/storage/azure/index.js +1 -1
  123. package/dist/storage/box/index.d.ts +12 -9
  124. package/dist/storage/box/index.js +1 -1
  125. package/dist/storage/bun-s3/index.d.ts +200 -0
  126. package/dist/storage/bun-s3/index.js +1 -0
  127. package/dist/storage/bunny/index.d.ts +12 -9
  128. package/dist/storage/bunny/index.js +1 -1
  129. package/dist/storage/cloudinary/index.d.ts +121 -0
  130. package/dist/storage/cloudinary/index.js +1 -0
  131. package/dist/storage/dropbox/index.d.ts +12 -9
  132. package/dist/storage/dropbox/index.js +1 -1
  133. package/dist/storage/firebase/index.d.ts +192 -0
  134. package/dist/storage/firebase/index.js +1 -0
  135. package/dist/storage/ftp/index.d.ts +85 -0
  136. package/dist/storage/ftp/index.js +1 -0
  137. package/dist/storage/gcs/index.d.ts +19 -10
  138. package/dist/storage/gcs/index.js +1 -1
  139. package/dist/storage/google-drive/index.d.ts +12 -9
  140. package/dist/storage/google-drive/index.js +1 -1
  141. package/dist/storage/local/index.d.ts +3 -3
  142. package/dist/storage/local/index.js +1 -1
  143. package/dist/storage/netlify-blob/index.d.ts +15 -12
  144. package/dist/storage/netlify-blob/index.js +1 -1
  145. package/dist/storage/onedrive/index.d.ts +22 -111
  146. package/dist/storage/onedrive/index.js +1 -1
  147. package/dist/storage/pocketbase/index.d.ts +172 -0
  148. package/dist/storage/pocketbase/index.js +1 -0
  149. package/dist/storage/sftp/index.d.ts +86 -0
  150. package/dist/storage/sftp/index.js +1 -0
  151. package/dist/storage/sharepoint/index.d.ts +180 -0
  152. package/dist/storage/sharepoint/index.js +1 -0
  153. package/dist/storage/supabase/index.d.ts +14 -10
  154. package/dist/storage/supabase/index.js +1 -1
  155. package/dist/storage/uploadthing/index.d.ts +13 -9
  156. package/dist/storage/uploadthing/index.js +1 -1
  157. package/dist/storage/vercel-blob/index.d.ts +13 -10
  158. package/dist/storage/vercel-blob/index.js +1 -1
  159. package/dist/transformer/audio-transformer.d.ts +2 -2
  160. package/dist/transformer/image-transformer.d.ts +2 -2
  161. package/dist/transformer/index.d.ts +3 -3
  162. package/dist/transformer/video-transformer.d.ts +2 -2
  163. package/package.json +55 -3
  164. package/dist/packem_shared/AwsLightStorage-SH7j-myh.js +0 -1
  165. package/dist/packem_shared/AzureSMetaStorage-DV2tNjKh.js +0 -1
  166. package/dist/packem_shared/AzureStorage-BVYMFEBP.js +0 -1
  167. package/dist/packem_shared/BoxMetaStorage-BUe5Qmqe.js +0 -1
  168. package/dist/packem_shared/BoxStorage-CgC81_So.js +0 -1
  169. package/dist/packem_shared/BunnyMetaStorage-D0mT6veJ.js +0 -1
  170. package/dist/packem_shared/BunnyStorage-Bl4usdVT.js +0 -1
  171. package/dist/packem_shared/DiskStorage-B5uIDVXr.js +0 -1
  172. package/dist/packem_shared/DropboxStorage-CPjhDN5B.js +0 -1
  173. package/dist/packem_shared/GCStorage-CNCPTaGF.js +0 -1
  174. package/dist/packem_shared/GoogleDriveStorage-DuB6glUk.js +0 -1
  175. package/dist/packem_shared/NetlifyBlobMetaStorage-BcRFPky8.js +0 -1
  176. package/dist/packem_shared/NetlifyBlobStorage-C4qkJv1R.js +0 -1
  177. package/dist/packem_shared/OneDriveMetaStorage-B_BkGLzW.js +0 -1
  178. package/dist/packem_shared/OneDriveStorage-Cu0cGcrh.js +0 -1
  179. package/dist/packem_shared/S3Storage-D8dopWoO.js +0 -1
  180. package/dist/packem_shared/SupabaseMetaStorage-BR1UGqnj.js +0 -1
  181. package/dist/packem_shared/SupabaseStorage-CCtMTiN5.js +0 -1
  182. package/dist/packem_shared/UploadThingMetaStorage-DyGNyaAq.js +0 -1
  183. package/dist/packem_shared/UploadThingStorage-B_fNzNFO.js +0 -1
  184. package/dist/packem_shared/VercelBlobStorage-D5zy4PPQ.js +0 -1
  185. package/dist/packem_shared/aws-light-meta-storage-TPyQwLvk.js +0 -4
  186. package/dist/packem_shared/defaultCloudStorageFileNameValidation-6URTv-Mp.js +0 -1
  187. package/dist/packem_shared/disk-storage-CbSSPnOf.js +0 -5
  188. package/dist/packem_shared/isRetryableError-B6ZS_-5I.js +0 -1
  189. package/dist/packem_shared/s3-base-storage-f_EyFAAt.js +0 -1
  190. package/dist/packem_shared/storage-CoyB2O-Y.js +0 -1
@@ -1 +0,0 @@
1
- var f=Object.defineProperty;var h=(n,e)=>f(n,"name",{value:e,configurable:!0});import{StorageClient as g}from"@supabase/storage-js";import{throwErrorCode as u,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import{B as w}from"./storage-CoyB2O-Y.js";import o from"./SupabaseFile-DZ1iv9gM.js";import y from"./SupabaseMetaStorage-BR1UGqnj.js";import{o as p,r as b}from"./part-match-B5fLLmFw.js";import{u as E}from"./update-size-DANV7aa2.js";import{o as k}from"./has-content-Bx2p8Okx.js";var S=Object.defineProperty,c=h((n,e)=>S(n,"name",{value:e,configurable:!0}),"u");const l=3600*24*7,U=c(n=>{if(!n||!/^attachment(\s*;|\s*$)/i.test(n.trim()))return;const e=n.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),t=e?.[1]??e?.[2];if(!t)return!0;try{return decodeURIComponent(t.trim())}catch{return t.trim()}},"parseDownloadOption"),C=c(async n=>{const e=[];for await(const t of n)e.push(Buffer.from(t));return Buffer.concat(e)},"collectStream");class I extends w{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(e){if(super(e),this.bucket=e.bucket,this.defaultUrlExpiresIn=Math.min(e.defaultUrlExpiresIn??3600,l),e.client)this.storageClient=e.client;else{const t=e.url??process.env.SUPABASE_URL,r=e.serviceKey??process.env.SUPABASE_SERVICE_ROLE_KEY??process.env.SUPABASE_KEY;if(!t)throw new Error("Supabase storage: `url` is required (or set SUPABASE_URL).");if(!r)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const a=t.replace(/\/+$/,"")+(t.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new g(a,{apikey:r,Authorization:`Bearer ${r}`},e.fetch)}this.meta=e.metaStorage??new y(e.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(e){return this.instrumentOperation("create",async()=>{const t=new o(e);t.name=this.namingFunction(t),t.bucket=this.bucket,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=p(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e){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&&E(t,e.size),!b(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(k(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await C(e.body),i=t.path??t.name,{data:s,error:m}=await this.storageClient.from(this.bucket).upload(i,a,{contentType:t.contentType,upsert:!0});if(m)throw m;t.bytesWritten=a.length,t.size=a.length,t.path=s?.path??i,t.ETag=s?.id}return t.status=p(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const r=t?.path??t?.name??e,{error:a}=await this.storageClient.from(this.bucket).remove([r]);if(a&&a.message&&!/not.*found/i.test(a.message))throw a;return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new o({contentType:"application/octet-stream",metadata:{},originalName:e}),{bucket:this.bucket,id:e,name:e,path:r,status:"deleted"})})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{let t=e;try{t=(await this.getMeta(e)).path??e}catch{}const{data:r,error:a}=await this.storageClient.from(this.bucket).exists(t);return a?!1:!!r})}async get({id:e}){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{data:a,error:i}=await this.storageClient.from(this.bucket).download(t);if(i||!a)throw i??new Error(`Supabase: object not found at "${t}"`);const s=Buffer.from(await a.arrayBuffer());return{content:s,contentType:r?.contentType??a.type??"application/octet-stream",ETag:r?.ETag,expiredAt:r?.expiredAt,id:e,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??t,originalName:r?.originalName??t,size:r?.size??s.length}})}async copy(e,t){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(e))?.path??e,a=t,{error:i}=await this.storageClient.from(this.bucket).copy(r,a);if(i)throw i;const s=new o({contentType:"application/octet-stream",metadata:{},originalName:t});return s.id=t,s.name=t,s.path=a,s.bucket=this.bucket,s})}async move(e,t){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(e))?.path??e,{error:a}=await this.storageClient.from(this.bucket).move(r,t);if(a)throw a;const i=new o({contentType:"application/octet-stream",metadata:{},originalName:t});i.id=t,i.name=t,i.path=t,i.bucket=this.bucket;try{await this.deleteMeta(e)}catch{}return i})}async list(e=1e3){return this.instrumentOperation("list",async()=>{const{data:t,error:r}=await this.storageClient.from(this.bucket).list("",{limit:e});if(r)throw r;return(t??[]).map(a=>{const i=new o({contentType:a.metadata?.mimetype??"application/octet-stream",metadata:a.metadata??{},originalName:a.name});return i.id=a.name,i.name=a.name,i.path=a.name,i.bucket=this.bucket,i.size=typeof a.metadata?.size=="number"?a.metadata.size:void 0,i.createdAt=a.created_at??void 0,i.modifiedAt=a.updated_at??void 0,i.ETag=a.metadata?.eTag??a.id??void 0,i})},{limit:e})}async getReadUrl(e,t){const r=Math.min(t?.expiresIn??this.defaultUrlExpiresIn,l),{data:a,error:i}=await this.storageClient.from(this.bucket).createSignedUrl(e,r,{download:U(t?.responseContentDisposition)});return i||!a?u(d.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUrl failed"):a.signedUrl}async getUploadUrl(e,t){const{data:r,error:a}=await this.storageClient.from(this.bucket).createSignedUploadUrl(e);return a||!r?u(d.METHOD_NOT_ALLOWED,a?.message??"Supabase: createSignedUploadUrl failed"):r.signedUrl}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=c(e=>this.deleteMeta(e.id),"internalOnComplete")}export{I as default};
@@ -1 +0,0 @@
1
- var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-CT1audnK.js";var s=Object.defineProperty,c=t((r,e)=>s(r,"name",{value:e,configurable:!0}),"a");class u extends o{static{t(this,"r")}static{c(this,"UploadThingMetaStorage")}constructor(e){super(e)}}export{u as default};
@@ -1 +0,0 @@
1
- var g=Object.defineProperty;var l=(n,t)=>g(n,"name",{value:t,configurable:!0});import{UTApi as T,UTFile as u}from"uploadthing/server";import{throwErrorCode as h,ERRORS as m}from"./ERRORS-CyOuSMLY.js";import{B as U}from"./storage-CoyB2O-Y.js";import p from"./UploadThingFile-BpG9mE8K.js";import I from"./UploadThingMetaStorage-DyGNyaAq.js";import{o as f,r as E}from"./part-match-B5fLLmFw.js";import{u as O}from"./update-size-DANV7aa2.js";import{o as k}from"./has-content-Bx2p8Okx.js";var b=Object.defineProperty,d=l((n,t)=>b(n,"name",{value:t,configurable:!0}),"p");const y=3600*24*7,v=d(n=>{let t;try{t=typeof atob=="function"?atob(n):Buffer.from(n,"base64").toString("utf8")}catch(a){throw new Error(`UploadThing: token is not valid base64: ${a.message}`)}let e;try{e=JSON.parse(t)}catch(a){throw new Error(`UploadThing: token does not decode to JSON: ${a.message}`)}if(!e||typeof e!="object"||typeof e.apiKey!="string"||typeof e.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return e},"decodeToken"),x=d(async n=>{const t=[];for await(const e of n)t.push(Buffer.from(e));return Buffer.concat(t)},"collectStream"),w=d(n=>{const t=n.lastIndexOf("/");return t===-1?n:n.slice(t+1)},"basename");class L extends U{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(t){super(t);const e=t.token??process.env.UPLOADTHING_TOKEN;if(t.client)this.utapi=t.client;else{if(!e)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new T({defaultKeyType:"customId",token:e})}if(!e)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=v(e).appId,this.acl=t.acl??"public-read",this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,y),this.meta=t.metaStorage??new I(t.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(t){return this.instrumentOperation("create",async()=>{const e=new p(t);e.name=this.namingFunction(e),e.customId=e.name,await this.validate(e);try{const a=await this.getMeta(e.id);if(a.bytesWritten>=0)return a}catch{}return e.bytesWritten=0,e.status=f(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t){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&&O(e,t.size),!E(t,e))throw new Error("File part does not match");const a=await this.lock(t.id);try{if(k(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await x(t.body),o=new Blob([new Uint8Array(i)],{type:e.contentType}),s=new u([o],w(e.name||e.id),{customId:e.name||e.id,type:e.contentType}),r=await this.utapi.uploadFiles(s,{acl:this.acl});if(r.error)throw new Error(r.error.message);const{data:c}=r;e.bytesWritten=i.length,e.size=i.length,e.ufsKey=c.key,e.url=c.ufsUrl??c.url,e.ETag=c.fileHash,e.fileHash=c.fileHash}return e.status=f(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,a)}})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const a=e?.customId??e?.name??t;return await this.utapi.deleteFiles(a),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new p({contentType:"application/octet-stream",metadata:{},originalName:t}),{customId:a,id:t,name:t,status:"deleted"})})}async get({id:t}){return this.instrumentOperation("get",async()=>{let e,a=t;try{e=await this.checkIfExpired(await this.getMeta(t)),a=e.customId??e.name??t}catch{}const i=await this.resolveFetchUrl(a),o=await fetch(i);if(!o.ok)throw new Error(`UploadThing: fetch failed: ${o.status} ${o.statusText} for ${a}`);const s=Buffer.from(await o.arrayBuffer());return{content:s,contentType:e?.contentType??o.headers.get("content-type")??"application/octet-stream",ETag:e?.ETag??o.headers.get("etag")??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt,name:e?.name??a,originalName:e?.originalName??a,size:e?.size??s.length}})}async copy(t,e){return this.instrumentOperation("copy",async()=>{const a=await this.get({id:t}),i=new Blob([new Uint8Array(a.content)],{type:a.contentType}),o=new u([i],w(e),{customId:e,type:a.contentType}),s=await this.utapi.uploadFiles(o,{acl:this.acl});if(s.error)throw new Error(s.error.message);const r=new p({contentType:a.contentType,metadata:{},originalName:e});return r.id=e,r.name=e,r.customId=e,r.size=typeof a.size=="string"?Number(a.size):a.size,r.ufsKey=s.data.key,r.url=s.data.ufsUrl??s.data.url,r.ETag=s.data.fileHash,r})}async move(t,e){return this.instrumentOperation("move",async()=>{const a=await this.copy(t,e);return await this.delete({id:t}),a})}async list(t=1e3){return this.instrumentOperation("list",async()=>(await this.utapi.listFiles({limit:t})).files.map(e=>{const a=e.customId??e.key,i=new p({contentType:"application/octet-stream",metadata:{},originalName:a});return i.id=a,i.name=a,i.customId=e.customId??void 0,i.ufsKey=e.key,i.size=e.size,i.modifiedAt=e.uploadedAt?new Date(e.uploadedAt).toISOString():void 0,i}),{limit:t})}async getReadUrl(t,e){if(e?.responseContentDisposition)return h(m.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition` is not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const a=Math.min(e?.expiresIn??this.defaultUrlExpiresIn,y),{ufsUrl:i}=await this.utapi.generateSignedURL(t,{expiresIn:a,keyType:"customId"});return i}async getUploadUrl(t,e){return h(m.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(t){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const{ufsUrl:e}=await this.utapi.generateSignedURL(t,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"});return e}internalOnComplete=d(t=>this.deleteMeta(t.id),"internalOnComplete")}export{L as default};
@@ -1 +0,0 @@
1
- var y=Object.defineProperty;var l=(r,e)=>y(r,"name",{value:e,configurable:!0});import{put as m,list as u,del as p,copy as h}from"@vercel/blob";import{a as g}from"./detect-file-type-5JhzC9RU.js";import{B as E,t as b}from"./storage-CoyB2O-Y.js";import{v as O}from"./local-meta-storage-CT1audnK.js";import d from"./VercelBlobFile-Cni_1qwD.js";import{o as f,r as v}from"./part-match-B5fLLmFw.js";import{u as k}from"./update-size-DANV7aa2.js";import{o as B}from"./has-content-Bx2p8Okx.js";var T=Object.defineProperty,A=l((r,e)=>T(r,"name",{value:e,configurable:!0}),"c");class C extends E{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:h,del:p,list:u,put:m,token:this.token}}meta;token;multipart;access;constructor(e){if(super(e),this.token=e.token||process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN||"",!this.token)throw new Error("Vercel Blob token is required. Set BLOB_READ_WRITE_TOKEN or VERCEL_BLOB_TOKEN environment variable, or provide token in config.");this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:t,metaStorageConfig:i}=e;this.meta=t||new O(i),this.isReady=!0}async create(e){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?b(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const i=new d(t);i.name=this.namingFunction(i),await this.validate(i);try{const a=await this.getMeta(i.id);if(a.bytesWritten>=0)return a}catch{}return i.bytesWritten=0,i.status=f(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(e){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),!v(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(B(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],o=e.body;for await(const n of o)a.push(Buffer.from(n));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const n=await g(s);n?.mime&&(t.contentType=n.mime)}catch{}const w=new Blob([s],{type:t.contentType}),c=await m(t.name,w,{access:this.access,multipart:this.shouldUseMultipart(t)});t.url=c.url,t.pathname=c.pathname,t.downloadUrl=c.downloadUrl,t.bytesWritten=s.length}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}){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);t.status="deleted";try{await p(t.url,{token:this.token})}catch(a){this.logger?.error("Failed to delete blob from Vercel Blob:",a);const o=this.normalizeError(a instanceof Error?a:new Error(String(a)));await this.onError(o)}await this.deleteMeta(t.id);const i={...t};return await this.onDelete(i),i})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);return!t.url||t.url.length===0?!1:(await fetch(t.url,{method:"HEAD"})).ok}catch{return!1}})}async get({id:e}){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.url||t.url.length===0)throw new Error("File URL not found");const i=await fetch(t.url),a=Buffer.from(await i.arrayBuffer());return{content:a,contentType:t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||a.length}})}async copy(e,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(e);if(!i.url)throw new Error("Source file URL not found");const a=await h(i.url,t,{access:"public"});return{...i,id:t,name:t,pathname:a.pathname,url:a.url}})}async move(e,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,t);return await this.delete({id:e}),i})}async list(e=1e3){return this.instrumentOperation("list",async()=>(await u({limit:e})).blobs.map(t=>{const i=new d({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return i.createdAt=t.uploadedAt?.toISOString(),i.id=t.pathname,i.modifiedAt=t.uploadedAt?.toISOString(),i.name=t.pathname,i.pathname=t.pathname,i.size=t.size,i.url=t.url,i.downloadUrl=t.downloadUrl,i}),{limit:e})}internalOnComplete=A(e=>this.deleteMeta(e.id),"internalOnComplete");shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{C as default};
@@ -1,4 +0,0 @@
1
- var f=Object.defineProperty;var u=(l,t)=>f(l,"name",{value:t,configurable:!0});import b from"./MetaStorage-Y4m1dWgd.js";import{parseMetadata as T,stringifyMetadata as k}from"./Metadata-B6Ir0KO7.js";import{Readable as w}from"node:stream";import{AwsClient as C}from"aws4fetch";import{o as E}from"./is-expired-1JuZjDtb.js";var x=Object.defineProperty,y=u((l,t)=>x(l,"name",{value:t,configurable:!0}),"p");const p=y(l=>{const t={},a=l.replaceAll(/<\?xml[^>]*\?>/g,"").replaceAll(/xmlns[^=]*="[^"]*"/g,""),e=/<([^>]+)>([^<]*)<\/\1>/g,o=[...a.matchAll(e)];for(const r of o){const[,n,i]=r;n&&i?.trim()&&(t[n]?(Array.isArray(t[n])||(t[n]=[t[n]]),t[n].push(i.trim())):t[n]=i.trim())}const s=/<([^>]+)>([\s\S]*?)<\/\1>/g;let c;for(;(c=s.exec(a))!==null;){const[,r,n]=c;if(r&&n?.includes("<")){const i=p(n);Object.keys(i).length>0&&(t[r]=i)}}return t},"parseXml");class U{static{u(this,"w")}static{y(this,"AwsLightApiAdapter")}aws;bucket;endpoint;constructor(t){this.bucket=t.bucket,this.endpoint=t.endpoint||`https://${t.bucket}.s3.${t.region}.amazonaws.com`,this.aws=new C({accessKeyId:t.accessKeyId,region:t.region,secretAccessKey:t.secretAccessKey,service:t.service||"s3",sessionToken:t.sessionToken})}async createMultipartUpload(t){const a={uploads:""},e={};if(t.ContentType&&(e["Content-Type"]=t.ContentType),t.ACL&&(e["x-amz-acl"]=t.ACL),t.Metadata)for(const[i,d]of Object.entries(t.Metadata))e[`x-amz-meta-${i}`]=d;const o=this.buildUrl(t.Key,a),s=await this.aws.fetch(o,{headers:e,method:"POST"}),c=await s.text();if(!s.ok)throw new Error(`Failed to create multipart upload: ${s.status} ${c}`);const r=p(c),n=r.UploadId||r.InitiateMultipartUploadResult?.UploadId;if(!n){const i=new Error("Failed to parse UploadId from response");throw i.retryable=!1,i}return{UploadId:n}}async uploadPart(t){const a={partNumber:String(t.PartNumber),uploadId:t.UploadId},e={};t.ContentLength&&(e["Content-Length"]=String(t.ContentLength)),t.ContentMD5&&(e["Content-MD5"]=t.ContentMD5);const o=t.Body instanceof w?w.toWeb(t.Body):t.Body,s=this.buildUrl(t.Key,a),c=await this.aws.fetch(s,{body:o,headers:e,method:"PUT"});if(!c.ok){const n=await c.text();throw new Error(`Failed to upload part: ${c.status} ${n}`)}const r=c.headers.get("ETag");if(!r)throw new Error("Failed to get ETag from response");return{ETag:r.replaceAll(/(^"|"$)/g,"")}}async completeMultipartUpload(t){const a={uploadId:t.UploadId},e=`<?xml version="1.0" encoding="UTF-8"?>
2
- <CompleteMultipartUpload xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
3
- ${t.Parts.map(({ETag:d,PartNumber:h})=>`<Part><PartNumber>${h}</PartNumber><ETag>"${d}"</ETag></Part>`).join("")}
4
- </CompleteMultipartUpload>`,o=this.buildUrl(t.Key,a),s=await this.aws.fetch(o,{body:e,headers:{"Content-Type":"application/xml"},method:"POST"}),c=await s.text();if(!s.ok)throw new Error(`Failed to complete multipart upload: ${s.status} ${c}`);const r=p(c),n=r.CompleteMultipartUploadResult||r,i=n.Location||`${this.endpoint}/${t.Key}`;return{ETag:n.ETag?.replaceAll(/(^"|"$)/g,""),Location:i}}async abortMultipartUpload(t){const a={uploadId:t.UploadId},e=this.buildUrl(t.Key,a),o=await this.aws.fetch(e,{method:"DELETE"});if(!o.ok){const s=await o.text();throw new Error(`Failed to abort multipart upload: ${o.status} ${s}`)}}async listParts(t){const a={uploadId:t.UploadId},e=this.buildUrl(t.Key,a),o=await this.aws.fetch(e,{method:"GET"}),s=await o.text();if(!o.ok)throw new Error(`Failed to list parts: ${o.status} ${s}`);const c=p(s),r=c.ListPartsResult||c;let n=[];return r.Part&&(n=Array.isArray(r.Part)?r.Part:[r.Part]),{Parts:n.map(i=>({ETag:i.ETag?.replaceAll(/(^"|"$)/g,""),PartNumber:Number(i.PartNumber)||0,Size:i.Size?Number(i.Size):void 0}))}}async getObject(t){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"GET"});if(!e.ok){const h=await e.text();throw new Error(`Failed to get object: ${e.status} ${h}`)}const o=e.headers.get("Content-Length"),s=e.headers.get("Content-Type"),c=e.headers.get("ETag"),r=e.headers.get("Expires"),n=e.headers.get("Last-Modified"),i={};for(const[h,m]of e.headers.entries())if(h.toLowerCase().startsWith("x-amz-meta-")){const g=h.toLowerCase().replace("x-amz-meta-","");i[g]=m}const{body:d}=e;return{Body:d?this.streamToReadable(d):void 0,ContentLength:o?Number(o):void 0,ContentType:s||void 0,ETag:c?.replaceAll(/(^"|"$)/g,"")||void 0,Expires:r?new Date(r):void 0,LastModified:n?new Date(n):void 0,Metadata:Object.keys(i).length>0?i:void 0}}async headObject(t){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"HEAD"});if(!e.ok){const d=await e.text();throw new Error(`Failed to head object: ${e.status} ${d}`)}const o=e.headers.get("Content-Length"),s=e.headers.get("Content-Type"),c=e.headers.get("ETag"),r=e.headers.get("Expires"),n=e.headers.get("Last-Modified"),i={};for(const[d,h]of e.headers.entries())if(d.toLowerCase().startsWith("x-amz-meta-")){const m=d.toLowerCase().replace("x-amz-meta-","");i[m]=h}return{ContentLength:o?Number(o):void 0,ContentType:s||void 0,ETag:c?.replaceAll(/(^"|"$)/g,"")||void 0,Expires:r?new Date(r):void 0,LastModified:n?new Date(n):void 0,Metadata:Object.keys(i).length>0?i:void 0}}async deleteObject(t){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"DELETE"});if(!e.ok){const o=await e.text();throw new Error(`Failed to delete object: ${e.status} ${o}`)}}async copyObject(t){const a={"x-amz-copy-source":t.CopySource};t.StorageClass&&(a["x-amz-storage-class"]=t.StorageClass);let e=this.buildUrl(t.Key);t.Bucket!==this.bucket&&(e=e.replace(this.bucket,t.Bucket));const o=await this.aws.fetch(e,{headers:a,method:"PUT"});if(!o.ok){const s=await o.text();throw new Error(`Failed to copy object: ${o.status} ${s}`)}}async listObjectsV2(t){const a={"list-type":"2"};t.MaxKeys&&(a["max-keys"]=String(t.MaxKeys)),t.ContinuationToken&&(a["continuation-token"]=t.ContinuationToken);const e=this.buildUrl("",a),o=await this.aws.fetch(e,{method:"GET"}),s=await o.text();if(!o.ok)throw new Error(`Failed to list objects: ${o.status} ${s}`);const c=p(s),r=c.ListBucketResult||c,n=r.Contents||(Array.isArray(r.Contents)?r.Contents:[]);return{Contents:Array.isArray(n)?n.map(i=>({Key:i.Key,LastModified:i.LastModified?new Date(String(i.LastModified)):void 0})):[],IsTruncated:r.IsTruncated==="true"||r.IsTruncated===!0,NextContinuationToken:r.NextContinuationToken}}async getPresignedUrl(t){const a={partNumber:String(t.PartNumber),uploadId:t.UploadId,"X-Amz-Expires":String(t.expiresIn)};return this.buildUrl(t.Key,a)}async putObject(t){const a=this.buildUrl(t.Key),e={};if(t.ContentType&&(e["Content-Type"]=t.ContentType),t.ContentLength!==void 0&&(e["Content-Length"]=String(t.ContentLength)),t.Metadata)for(const[c,r]of Object.entries(t.Metadata))e[`x-amz-meta-${c}`]=r;let o;t.Body===void 0?o=void 0:t.Body instanceof Uint8Array?o=new Uint8Array(t.Body):t.Body instanceof ReadableStream?o=t.Body:o=void 0;const s=await this.aws.fetch(a,{body:o,headers:e,method:"PUT"});if(!s.ok){const c=await s.text();throw new Error(`Failed to put object: ${s.status} ${c}`)}}async checkBucketAccess(t){const a=this.buildUrl(""),e=await this.aws.fetch(a,{method:"HEAD"});if(!e.ok&&e.status!==404){const o=await e.text();throw new Error(`Failed to access bucket: ${e.status} ${o}`)}}buildUrl(t,a){const e=new URL(t,this.endpoint);if(a)for(const[o,s]of Object.entries(a))e.searchParams.set(o,s);return e.toString()}streamToReadable(t){return w.fromWeb(t)}}var $=Object.defineProperty,A=u((l,t)=>$(l,"name",{value:t,configurable:!0}),"n");class I extends b{static{u(this,"l")}constructor(t){super(t),this.config=t;const a=t.bucket||process.env.S3_BUCKET||process.env.AWS_S3_BUCKET;if(!a)throw new Error("S3 bucket is not defined");this.bucket=a,this.adapter=new U({accessKeyId:t.accessKeyId,bucket:a,endpoint:t.endpoint,region:t.region,secretAccessKey:t.secretAccessKey,service:t.service,sessionToken:t.sessionToken}),this.adapter.checkBucketAccess({Bucket:a}).catch(e=>{throw e})}config;static{A(this,"AwsLightMetaStorage")}adapter;bucket;async get(t){const a=this.getMetaName(t),{Expires:e,Metadata:o}=await this.adapter.headObject({Bucket:this.bucket,Key:a});if(e&&E({expiredAt:e}))throw await this.delete(a),new Error(`Metafile ${t} not found`);if(o?.metadata!==void 0){const s=JSON.parse(decodeURIComponent(o.metadata));return s.metadata&&typeof s.metadata=="string"&&(s.metadata=T(s.metadata)),s}throw new Error(`Metafile ${t} not found`)}async touch(t,a){return this.save(t,a)}async delete(t){await this.adapter.deleteObject({Bucket:this.bucket,Key:this.getMetaName(t)})}async save(t,a){const e={...a};e.metadata&&(e.metadata=k(a.metadata));const o=encodeURIComponent(JSON.stringify(e));return await this.adapter.putObject({Bucket:this.bucket,ContentLength:0,ContentType:"application/json",Key:this.getMetaName(t),Metadata:{metadata:o}}),a}}export{I as l,U as w};
@@ -1 +0,0 @@
1
- import"node:stream";import"node:timers";import"node:util";import{B as f,d as u,a as F}from"./storage-CoyB2O-Y.js";import"./path-D7rMc9nq-B718mbm6.js";import"type-is";import"./NoOpMetrics-Dky06sf1.js";import"./cache-qV_5Umeq.js";import"./ERRORS-CyOuSMLY.js";import"./is-expired-1JuZjDtb.js";export{f as BaseStorage,u as defaultCloudStorageFileNameValidation,F as defaultFilesystemFileNameValidation};
@@ -1,5 +0,0 @@
1
- var ut=Object.defineProperty;var d=(e,t)=>ut(e,"name",{value:t,configurable:!0});import{createReadStream as mt,createWriteStream as dt}from"node:fs";import{truncate as ht,stat as z,copyFile as A}from"node:fs/promises";import{Transform as K,PassThrough as yt,pipeline as ft}from"node:stream";import{f as R,l as gt,w as Q,U as b,_ as pt,i as wt,v as bt,B as vt,y as W}from"./local-meta-storage-CT1audnK.js";import{createRequire as P}from"node:module";import{K as w,C as k,M as X,L as Et,Q as St,O as $t}from"./path-D7rMc9nq-B718mbm6.js";import{g as Ot}from"./_commonjsHelpers-D6W6KoPK.js";import Tt from"crypto";import kt from"fs";import{d as Ft}from"./detect-file-type-5JhzC9RU.js";import{throwErrorCode as p,ERRORS as y,isUploadError as Nt}from"./ERRORS-CyOuSMLY.js";import{createHash as Pt}from"node:crypto";import{B as Dt,a as _t,t as jt}from"./storage-CoyB2O-Y.js";import It from"./File-BhfUgJjs.js";import{o as B,r as Mt}from"./part-match-B5fLLmFw.js";import{u as xt}from"./update-size-DANV7aa2.js";import{o as Rt}from"./has-content-Bx2p8Okx.js";var Lt=Object.defineProperty,Ct=d((e,t)=>Lt(e,"name",{value:t,configurable:!0}),"i$4"),zt=Object.defineProperty,Y=Ct((e,t)=>zt(e,"name",{value:t,configurable:!0}),"t");const At=P(import.meta.url),$=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Wt=Y(e=>{if(typeof $<"u"&&$.versions&&$.versions.node){const[t,r]=$.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return $.getBuiltinModule(e)}return At(e)},"__cjs_getBuiltinModule"),{lstat:Bt,writeFile:Ut}=Wt("node:fs/promises");var Vt=Object.defineProperty,qt=Y((e,t)=>Vt(e,"name",{value:t,configurable:!0}),"o");const M=qt(async e=>{R(e);try{const t=await Bt(e);if(!t.isFile())throw new Error(`Ensure path exists, expected 'file', got '${String(gt(t))}'`)}catch(t){if(t.code==="ENOENT"){await Q(w(b(e))),await Ut(e,new Uint8Array);return}throw t}},"ensureFile");var Ht=Object.defineProperty,G=d((e,t)=>Ht(e,"name",{value:t,configurable:!0}),"t$2"),Kt=Object.defineProperty,J=G((e,t)=>Kt(e,"name",{value:t,configurable:!0}),"t"),Qt=Object.defineProperty,Xt=J((e,t)=>Qt(e,"name",{value:t,configurable:!0}),"t");let U=class extends Error{static{d(this,"l")}static{G(this,"c")}static{J(this,"i")}static{Xt(this,"WalkError")}root;constructor(t,r){super(`${t instanceof Error?t.message:String(t)} for path "${r}"`),this.cause=t,this.root=r}get name(){return"WalkError"}set name(t){throw new Error("Cannot overwrite name of WalkError")}};var Yt=Object.defineProperty,Gt=d((e,t)=>Yt(e,"name",{value:t,configurable:!0}),"n"),Jt=Object.defineProperty,Z=Gt((e,t)=>Jt(e,"name",{value:t,configurable:!0}),"t"),Zt=Object.defineProperty,te=Z((e,t)=>Zt(e,"name",{value:t,configurable:!0}),"g");const V=te(e=>{const t=e.replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,String.raw`\.`).replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");return new RegExp(`^${t}$`)},"globToRegExp");var ee=Object.defineProperty,re=Z((e,t)=>ee(e,"name",{value:t,configurable:!0}),"n");const N=re((e,t,r,i)=>Array.isArray(t)&&t.length>0&&!t.some(o=>e.endsWith(o))||r&&!r.some(o=>o.test(e))?!1:!i?.some(o=>o.test(e)),"walkInclude");var ie=Object.defineProperty,tt=d((e,t)=>ie(e,"name",{value:t,configurable:!0}),"u$1"),ae=Object.defineProperty,L=tt((e,t)=>ae(e,"name",{value:t,configurable:!0}),"y");const se=P(import.meta.url),O=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ne=L(e=>{if(typeof O<"u"&&O.versions&&O.versions.node){const[t,r]=O.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return O.getBuiltinModule(e)}return se(e)},"__cjs_getBuiltinModule"),{readdir:oe,realpath:ce,stat:le}=ne("node:fs/promises");var ue=Object.defineProperty,g=L((e,t)=>ue(e,"name",{value:t,configurable:!0}),"r");const me=g(async e=>{const t=Et(e),r=St(t),i=await le(t);return{isDirectory:g(()=>i.isDirectory(),"isDirectory"),isFile:g(()=>i.isFile(),"isFile"),isSymbolicLink:g(()=>i.isSymbolicLink(),"isSymbolicLink"),name:r,path:t}},"_createWalkEntry");async function*F(e,{extensions:t,followSymlinks:r=!1,includeDirs:i=!0,includeFiles:o=!0,includeSymlinks:s=!0,match:n,maxDepth:m=Number.POSITIVE_INFINITY,skip:h}={}){if(R(e),m<0)return;const a=n?n.map(c=>typeof c=="string"?V(c):c):void 0,u=h?h.map(c=>typeof c=="string"?V(c):c):void 0;if(e=k(b(e)),i&&N(e,t,a,u)&&(yield await me(e)),!(m<1||!N(e,void 0,void 0,u)))try{const c=await oe(e,{withFileTypes:!0});for(const l of c){let f=X(e,l.name);if(l.isSymbolicLink())if(r)f=await ce(f);else if(s&&N(f,t,a,u)){yield{isDirectory:g(()=>l.isDirectory(),"isDirectory"),isFile:g(()=>l.isFile(),"isFile"),isSymbolicLink:g(()=>l.isSymbolicLink(),"isSymbolicLink"),name:l.name,path:f};continue}else continue;l.isDirectory()?yield*F(f,{extensions:t,followSymlinks:r,includeDirs:i,includeFiles:o,includeSymlinks:s,match:a,maxDepth:m-1,skip:u}):l.isFile()&&o&&N(f,t,a,u)&&(yield{isDirectory:g(()=>l.isDirectory(),"isDirectory"),isFile:g(()=>l.isFile(),"isFile"),isSymbolicLink:g(()=>l.isSymbolicLink(),"isSymbolicLink"),name:l.name,path:f})}}catch(c){throw c instanceof U?c:new U(c,e)}}d(F,"f$2");tt(F,"D");L(F,"g");g(F,"walk");var de=Object.defineProperty,et=d((e,t)=>de(e,"name",{value:t,configurable:!0}),"t"),he=Object.defineProperty,C=et((e,t)=>he(e,"name",{value:t,configurable:!0}),"t");const ye=P(import.meta.url),T=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,fe=C(e=>{if(typeof T<"u"&&T.versions&&T.versions.node){const[t,r]=T.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return T.getBuiltinModule(e)}return ye(e)},"__cjs_getBuiltinModule"),{accessSync:ge}=fe("node:fs");var pe=Object.defineProperty,we=C((e,t)=>pe(e,"name",{value:t,configurable:!0}),"o");function D(e,t=pt){R(e),e=b(e);try{return ge(e,t),!0}catch{return!1}}d(D,"i$1");et(D,"d");C(D,"m");we(D,"isAccessibleSync");var be=Object.defineProperty,rt=d((e,t)=>be(e,"name",{value:t,configurable:!0}),"v"),ve=Object.defineProperty,S=rt((e,t)=>ve(e,"name",{value:t,configurable:!0}),"i");const Ee=P(import.meta.url),v=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,it=S(e=>{if(typeof v<"u"&&v.versions&&v.versions.node){const[t,r]=v.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return v.getBuiltinModule(e)}return Ee(e)},"__cjs_getBuiltinModule"),{cwd:_}=v,{mkdir:Se,rename:$e,copyFile:Oe,unlink:Te}=it("node:fs/promises"),{mkdirSync:ke,renameSync:Fe,copyFileSync:Ne,unlinkSync:Pe}=it("node:fs");var De=Object.defineProperty,at=S((e,t)=>De(e,"name",{value:t,configurable:!0}),"o");class _e extends Error{static{d(this,"V")}static{rt(this,"O")}static{S(this,"a")}static{at(this,"SameDirectoryError")}constructor(t,r){super(`Source directory "${w(t)}" does not match destination directory "${w(r)}"`),this.name="SameDirectoryError"}}const st=at((e,t)=>{if(!e||!t)throw new Error("Source and destination paths must not be empty");if(w(e)!==w(t))throw new _e(e,t)},"validateSameDirectory");var je=Object.defineProperty,Ie=S((e,t)=>je(e,"name",{value:t,configurable:!0}),"m$1");const nt=Ie(async(e,t,{cwd:r,directoryMode:i,overwrite:o,validateDirectory:s})=>{if(r&&(e=k(r,e),t=k(r,t)),s&&st(e,t),!o&&await wt(t))throw new Error(`The destination file exists: ${t}`);await Se(w(t),{mode:i,recursive:!0});try{await $e(e,t)}catch(n){if(n.code==="EXDEV")await Oe(e,t),await Te(e);else throw n}},"internalMoveFile");var Me=Object.defineProperty,xe=S((e,t)=>Me(e,"name",{value:t,configurable:!0}),"m");const ot=xe((e,t,{cwd:r,directoryMode:i,overwrite:o,validateDirectory:s})=>{if(r&&(e=k(r,e),t=k(r,t)),s&&st(e,t),!o&&D(t))throw new Error(`The destination file exists: ${t}`);ke(w(t),{mode:i,recursive:!0});try{Fe(e,t)}catch(n){if(n.code==="EXDEV")Ne(e,t),Pe(e);else throw n}},"internalMoveFileSync");var Re=Object.defineProperty,j=S((e,t)=>Re(e,"name",{value:t,configurable:!0}),"i");const Le=j(async(e,t,r={})=>{const i={overwrite:!0,validateDirectory:!1,...r,cwd:r.cwd?b(r.cwd):_()};await nt(e,t,i)},"move");j((e,t,r)=>{const i={overwrite:!0,validateDirectory:!1,...r};i.cwd=i.cwd?b(i.cwd):_(),ot(e,t,i)},"moveSync");j(async(e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):_(),await nt(e,t,i)},"rename");j((e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):_(),ot(e,t,i)},"renameSync");var x,q;function Ce(){if(q)return x;q=1;var e=Object.defineProperty,t=d((a,u)=>e(a,"name",{value:u,configurable:!0}),"i");/*!
2
- * etag
3
- * Copyright(c) 2014-2016 Douglas Christopher Wilson
4
- * MIT Licensed
5
- */x=n;var r=Tt,i=kt.Stats,o=Object.prototype.toString;function s(a){if(a.length===0)return'"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"';var u=r.createHash("sha1").update(a,"utf8").digest("base64").substring(0,27),c=typeof a=="string"?Buffer.byteLength(a,"utf8"):a.length;return'"'+c.toString(16)+"-"+u+'"'}d(s,"entitytag"),t(s,"entitytag");function n(a,u){if(a==null)throw new TypeError("argument entity is required");var c=m(a),l=u&&typeof u.weak=="boolean"?u.weak:c;if(!c&&typeof a!="string"&&!Buffer.isBuffer(a))throw new TypeError("argument entity must be string, Buffer, or fs.Stats");var f=c?h(a):s(a);return l?"W/"+f:f}d(n,"etag"),t(n,"etag");function m(a){return typeof i=="function"&&a instanceof i?!0:a&&typeof a=="object"&&"ctime"in a&&o.call(a.ctime)==="[object Date]"&&"mtime"in a&&o.call(a.mtime)==="[object Date]"&&"ino"in a&&typeof a.ino=="number"&&"size"in a&&typeof a.size=="number"}d(m,"isstats"),t(m,"isstats");function h(a){var u=a.mtime.getTime().toString(16),c=a.size.toString(16);return'"'+c+"-"+u+'"'}return d(h,"stattag"),t(h,"stattag"),x}d(Ce,"requireEtag");var ze=Ce();const Ae=Ot(ze);var We=Object.defineProperty,ct=d((e,t)=>We(e,"name",{value:t,configurable:!0}),"r");class Be extends K{static{d(this,"StreamChecksum")}constructor(t,r,i="base64"){super(),this.checksum=t,this.algorithm=r,this.encoding=i,this.hash=Pt(r)}checksum;algorithm;encoding;static{ct(this,"StreamChecksum")}length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(t,r,i){this.push(t),this.hash.update(t),this.length+=t.length,i()}_flush(t){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?t(new Error("Checksum mismatch")):t()}}const Ue=ct((e,t,r="base64")=>t?new Be(e,t,r):new yt,"streamChecksum");var Ve=Object.defineProperty,qe=d((e,t)=>Ve(e,"name",{value:t,configurable:!0}),"o");class He extends K{static{d(this,"m")}constructor(t=Number.POSITIVE_INFINITY){super(),this.limit=t}limit;static{qe(this,"StreamLength")}length=0;_transform(t,r,i){const o=this.length+t.length;this.limit>=o?(this.push(t),this.length=o,i()):i(new Error("Stream length limit exceeded"))}}var Ke=Object.defineProperty,H=d((e,t)=>Ke(e,"name",{value:t,configurable:!0}),"E");class E extends Dt{static name="disk";checksumTypes=["md5","sha1"];get raw(){return{directory:this.directory}}directory;meta;constructor(t){const r={...t,fileNameValidation:t.fileNameValidation??_t};if(super(r),this.directory=r.directory,r.metaStorage)this.meta=r.metaStorage;else{const i={...r,...r.metaStorageConfig,logger:this.logger};this.meta=new bt(i)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}normalizeError(t){return super.normalizeError(t)}async create(t){return this.instrumentOperation("create",async()=>{const r={...t};if(t.ttl){const s=typeof t.ttl=="string"?jt(t.ttl):t.ttl;s!==void 0&&(r.expiredAt=Date.now()+s)}r.size!==void 0&&Number(r.size)<0&&p(y.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const i=new It(r);try{const s=await this.getMeta(i.id);if(s.status==="completed")return s}catch{}i.name=this.namingFunction(i),(i.size===void 0||Number.isNaN(i.size))&&(i.size===void 0||(i.size=this.maxUploadSize)),await this.validate(i);const o=this.getFilePath(i.name);try{await M(o),i.bytesWritten=0}catch(s){const n=this.normalizeError(s instanceof Error?s:new Error(String(s)));await this.onError(n),p(y.FILE_ERROR,n.message)}return i.status=B(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(t){return this.instrumentOperation("write",async()=>{let r;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?r=t:(r=await this.getMeta(t.id),await this.checkIfExpired(r)),r.status==="completed")return r;if(t.size!==void 0&&xt(r,t.size),!Mt(t,r))return p(y.FILE_CONFLICT);const i=this.getFilePath(r.name),o=await this.lock(i);try{const s=t.start||0;if(await M(i),r.bytesWritten===0&&(r.bytesWritten=s),Rt(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return p(y.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(r.bytesWritten===0||Number.isNaN(r.bytesWritten))&&(!r.contentType||r.contentType==="application/octet-stream"))try{const{fileType:c,stream:l}=await Ft(t.body);c?.mime&&(r.contentType=c.mime),t.body=l}catch{}const n=t.signal,m={...r,...t,body:t.body};n&&(m.signal=n);const[h,a]=await this.lazyWrite(m);if(a)return await ht(i,r.bytesWritten),p(a);const u=s+(t.contentLength||0);r.bytesWritten=Math.max(r.bytesWritten||0,u),r.bytesWritten=Math.max(r.bytesWritten||0,h),r.status=B(r),await this.saveMeta(r)}else await M(i),r.bytesWritten=0;return r}catch(s){if(Nt(s))throw s;const n=this.normalizeError(s instanceof Error?s:new Error(String(s)));return await this.onError(n),p(y.FILE_ERROR,(typeof n.message=="string"?n.message:String(s))||String(s))}finally{await this.unlock(i,o)}})}async get({id:t}){return this.instrumentOperation("get",async()=>{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:i,contentType:o,expiredAt:s,metadata:n,modifiedAt:m,name:h,originalName:a,size:u}=r;let c;try{c=await vt(this.getFilePath(h),{buffer:!0})}catch(l){const f=l;if(f.code==="ENOENT"||f.code==="EPERM"){const I=this.normalizeError(l instanceof Error?l:new Error(f.message||String(l)));return await this.onError(I),p(y.FILE_NOT_FOUND,(typeof I.message=="string"?I.message:String(l))||String(l))}const lt=this.normalizeError(l instanceof Error?l:new Error(String(l)));throw await this.onError(lt),l}return{content:c,contentType:o,ETag:Ae(c),expiredAt:s,id:t,metadata:n,modifiedAt:m,name:h,originalName:a,size:u||i}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{const r=await this.getMeta(t),i=this.getFilePath(r.name);return await z(i),!0}catch{return!1}})}async getStream({id:t}){return this.instrumentOperation("getStream",async()=>{try{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:i,contentType:o,expiredAt:s,modifiedAt:n,name:m,size:h}=r,a=mt(this.getFilePath(m));return{headers:{"Content-Length":String(h||i),"Content-Type":o,...s&&{"X-Upload-Expires":s.toString()},...n&&{"Last-Modified":n.toString()}},size:h||i,stream:a}}catch(r){const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));throw await this.onError(i),p(y.FILE_NOT_FOUND,(typeof i.message=="string"?i.message:String(r))||String(r))}})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const r=await this.getMeta(t);await W(this.getFilePath(r.name)),await this.deleteMeta(t);const i={...r,status:"deleted"};return await this.onDelete(i),i})}async copy(t,r){return this.instrumentOperation("copy",async()=>{E.assertSafeId(t),E.assertSafeId(r);const i=await this.getMeta(t);return await A(this.getFilePath(i.name),this.getFilePath(r)),{...i,name:r}})}async move(t,r){return this.instrumentOperation("move",async()=>{E.assertSafeId(t),E.assertSafeId(r);const i=await this.getMeta(t),o=this.getFilePath(i.name),s=this.getFilePath(r);try{await Le(o,s)}catch(n){if(n?.code==="EXDEV")await A(o,s),await W(o);else{const m=this.normalizeError(n instanceof Error?n:new Error(String(n)));throw await this.onError(m),n}}return{...i,id:i.id,name:r}})}async list(){return this.instrumentOperation("list",async()=>{const t={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},r=[],{directory:i}=this;for await(const o of F(i,t)){const{suffix:s}=this.meta,{path:n}=o;if(!n.includes(s)){const{birthtime:m,ctime:h,mtime:a}=await z(n);r.push({createdAt:m||h,id:n.replace(i,""),modifiedAt:a})}}return r})}getFilePath(t){return E.assertSafeId(t),$t(t)&&p(y.INVALID_FILE_NAME,`Invalid file id: "${t}"`),X(this.directory,t)}lazyWrite(t){return new Promise((r,i)=>{const o=dt(this.getFilePath(t.name),{flags:"r+",start:t.start}),s=new He(t.contentLength||t.size-t.start),n=Ue(t.checksum,t.checksumAlgorithm),m=!t.checksum,{signal:h}=t,a=H(()=>{o.close(),s.destroy(),n.destroy()},"cleanupStreams"),u=H(c=>{a(),r([Number.NaN,c])},"failWithCode");if(s.on("error",()=>{u(y.FILE_CONFLICT)}),n.on("error",()=>{u(y.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{u(m?void 0:y.REQUEST_ABORTED)}),t.body.on("error",c=>{a(),i(c)}),h?.aborted){u(m?void 0:y.REQUEST_ABORTED);return}h&&h.addEventListener("abort",()=>{a(),o.destroy(),s.destroy(),n.destroy(),t.body.destroy(),r([Number.NaN,m?void 0:y.REQUEST_ABORTED])}),ft(t.body,s,n,o,c=>{if(c){if(a(),h?.aborted){r([Number.NaN,m?void 0:y.REQUEST_ABORTED]);return}r([Number.NaN,y.FILE_ERROR]);return}r([t.start+o.bytesWritten])})})}async accessCheck(){await Q(this.directory)}}export{E as f,He as m,Ue as s,M as y};
@@ -1 +0,0 @@
1
- var b=Object.defineProperty;var d=(e,t)=>b(e,"name",{value:t,configurable:!0});var R=Object.defineProperty,i=d((e,t)=>R(e,"name",{value:t,configurable:!0}),"o");const l={backoffMultiplier:2,calculateDelay:void 0,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:i(()=>!1,"shouldRetry")},p=i((e,t,a,o)=>{const r=Math.min(t*a**e,o);return Math.floor(Math.random()*r)},"calculateExponentialBackoff"),D=i(e=>new Promise(t=>{setTimeout(t,e)}),"sleep"),h=i((e,t=l.retryableStatusCodes)=>{if(e instanceof Error){const a=e.code,o=e.name;if(a==="ECONNRESET"||a==="ETIMEDOUT"||a==="ENOTFOUND"||a==="ECONNREFUSED"||a==="EAI_AGAIN"||o==="NetworkError"||o==="TimeoutError")return!0;const r=e;if(r.$metadata){const u=r.$metadata.httpStatusCode;if(u&&t.includes(u)||r.$fault==="server")return!0}if(r.statusCode&&t.includes(r.statusCode))return!0;const{retryable:s}=r;return s===!0||typeof s=="string"&&s==="true"}return!1},"isRetryableError"),C=i(async(e,t={})=>{const{backoffMultiplier:a=l.backoffMultiplier,calculateDelay:o=l.calculateDelay,initialDelay:r=l.initialDelay,maxDelay:s=l.maxDelay,maxRetries:u=l.maxRetries,retryableStatusCodes:m=l.retryableStatusCodes,shouldRetry:E=l.shouldRetry}=t;let f;for(let n=0;n<=u;n+=1)try{return await e()}catch(c){if(f=c,n>=u)break;if(!(E(c)||h(c,m)))throw c;const y=o?o(n,c):p(n,r,a,s);y!==void 0&&y>0&&await D(y)}throw f},"retry"),N=i((e={})=>t=>C(t,e),"createRetryWrapper");export{N as createRetryWrapper,h as isRetryableError,C as retry};
@@ -1 +0,0 @@
1
- var E=Object.defineProperty;var d=(o,t)=>E(o,"name",{value:t,configurable:!0});import{Readable as g}from"node:stream";import{z as M,B as C,$ as T,t as A}from"./storage-CoyB2O-Y.js";import{d as I}from"./detect-file-type-5JhzC9RU.js";import{throwErrorCode as p,ERRORS as m}from"./ERRORS-CyOuSMLY.js";import{createRetryWrapper as O}from"./isRetryableError-B6ZS_-5I.js";import{v as w}from"./local-meta-storage-CT1audnK.js";import{u as z}from"./update-size-DANV7aa2.js";import{r as R,o as S}from"./part-match-B5fLLmFw.js";import{o as x}from"./has-content-Bx2p8Okx.js";var v=Object.defineProperty,B=d((o,t)=>v(o,"name",{value:t,configurable:!0}),"o$1");const L=B((o,t)=>{const e={};return Object.keys(o).forEach(r=>{e[r]=t(o[r])}),e},"mapValues");var N=Object.defineProperty,K=d((o,t)=>N(o,"name",{value:t,configurable:!0}),"t");const $=K(o=>o===Number(o)?o:(M(o)??0)/1e3,"toSeconds");var j=Object.defineProperty,f=d((o,t)=>j(o,"name",{value:t,configurable:!0}),"u");const D=5*1024*1024,F=16*1024*1024;class b extends C{static{d(this,"S3BaseStorage")}static{f(this,"S3BaseStorage")}checksumTypes=["md5","crc32","crc32c","sha1","sha256"];bucket;meta;MAX_PARTS=1e4;partSize;retry;constructor(t){if(super(t),this.bucket=t.bucket,this.partSize=typeof t.partSize=="string"?T(t.partSize):t.partSize||F,this.partSize<D)throw new Error("Minimum allowed partSize value is 5MB");const e={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:f(i=>{const n=i;return n.statusCode&&[408,429,500,502,503,504].includes(n.statusCode)?!0:n.retryable??!1},"shouldRetry"),...t.retryConfig};this.retry=O(e);const{metaStorage:r,metaStorageConfig:a}=t;if(r)this.meta=r;else{const i={...t,...a,logger:this.logger};"directory"in i?(this.logger?.debug("Using local meta storage"),this.meta=new w(i)):this.meta=new w(i)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}async create(t){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const s=typeof t.ttl=="string"?A(t.ttl):t.ttl;s!==void 0&&(e.expiredAt=Date.now()+s)}const r=new(this.getFileClass())(e);r.name=this.namingFunction(r),await this.validate(r);try{const s=await this.getMeta(r.id);if(s.bytesWritten>=0)return s}catch{}const a=this.getS3Api();let i;try{i=await this.retry(()=>a.createMultipartUpload({ACL:this.getAcl(),Bucket:this.bucket,ContentType:r.contentType,Key:r.name,Metadata:L({originalName:r.originalName,...r.metadata},s=>encodeURI(String(s)))}))}catch{return p(m.FILE_ERROR,"s3 create upload error")}const{UploadId:n}=i||{};return n?(r.UploadId=n,r.bytesWritten=0,this.config.clientDirectUpload&&(r.partSize??=this.partSize),await this.saveMeta(r),r.status="created",await this.onCreate(r),this.config.clientDirectUpload?this.buildPresigned(r):r):p(m.FILE_ERROR,"s3 create upload error")})}async write(t){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(typeof t.size=="number"&&t.size>0&&z(e,t.size),!R(t,e))return p(m.FILE_CONFLICT);if(this.config.clientDirectUpload)return this.buildPresigned(e);e.Parts??=await this.getParts(e),e.bytesWritten=e.Parts.map(a=>a.Size||0).reduce((a,i)=>a+i,0);const r=await this.lock(t.id);try{if(x(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return p(m.UNSUPPORTED_CHECKSUM_ALGORITHM);if(e.Parts.length===0&&(!e.contentType||e.contentType==="application/octet-stream"))try{const l=t.body instanceof g?t.body:g.fromWeb(t.body),{fileType:h,stream:y}=await I(l);h?.mime&&(e.contentType=h.mime),t.body=y}catch{}if(e.Parts.length>this.MAX_PARTS)throw new Error(`Exceeded ${this.MAX_PARTS} as part of the upload to ${this.bucket}.`);const a=e.Parts.length+1,i=this.getS3Api(),n=e.UploadId;if(!n)throw new Error("UploadId is required");const{ETag:s}=await this.retry(()=>i.uploadPart({Body:t.body,Bucket:this.bucket,ContentLength:t.contentLength||0,Key:e.name,PartNumber:a,UploadId:n,...t.checksumAlgorithm==="md5"?{ContentMD5:t.checksum}:{}})),c={ETag:s,PartNumber:a,Size:t.contentLength};e.Parts=[...e.Parts,c],e.bytesWritten+=t.contentLength||0}if(this.cache.set(e.id,e),e.status=S(e),e.status==="completed"){const[a]=await this.internalOnComplete(e);delete e.Parts,e.uri=a.Location,e.ETag=a.ETag}}finally{await this.unlock(t.id,r)}return e})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await this.retry(()=>this.abortMultipartUpload(e)),await this.deleteMeta(e.id);const r={...e};return await this.onDelete(r),r})}async copy(t,e,r){return this.instrumentOperation("copy",async()=>{b.assertSafeId(t),b.assertSafeId(e);const a=await this.getMeta(t),i=`${this.bucket}/${t}`,n=this.bucket,s=e,c=this.getS3Api();return await this.retry(()=>c.copyObject({Bucket:n,CopySource:i,Key:s,...r?.storageClass&&{StorageClass:r.storageClass}})),{...a,id:s,name:s}})}async move(t,e){return this.instrumentOperation("move",async()=>{await this.copy(t,e);const r=this.getS3Api();return await this.retry(()=>r.deleteObject({Bucket:this.bucket,Key:t})),await this.getMeta(e)})}async list(t=1e3){return this.instrumentOperation("list",async()=>{const e=this.getS3Api(),r=Math.min(t,1e3);let a={Bucket:this.bucket,MaxKeys:r};const i=[];let n=!0;for(;n&&i.length<t;)try{const s=await this.retry(()=>e.listObjectsV2(a));for(const{Key:c,LastModified:l}of s?.Contents||[]){if(i.length>=t)break;c!==void 0&&i.push({id:c,...l&&{createdAt:l}})}n=s.IsTruncated||!1,n&&s.NextContinuationToken&&i.length<t&&(a={...a,ContinuationToken:s.NextContinuationToken,MaxKeys:Math.min(r,t-i.length)})}catch(s){const c=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(c),s}return i},{limit:t})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{await this.getMeta(t);const e=this.getS3Api();return await this.retry(()=>e.headObject({Bucket:this.bucket,Key:t})),!0}catch{return!1}})}async get({id:t}){return this.instrumentOperation("get",async()=>{const e=this.getS3Api(),{Body:r,ContentLength:a,ContentType:i,ETag:n,Expires:s,LastModified:c,Metadata:l}=await this.retry(()=>e.getObject({Bucket:this.bucket,Key:t}));await this.checkIfExpired({expiredAt:s});const h=[];if(r)if(r instanceof g)for await(const u of r)h.push(u instanceof Uint8Array?u:new Uint8Array(u));else{const u=r.getReader();for(;;){const{done:P,value:U}=await u.read();if(P)break;h.push(U)}}const{originalName:y,...k}=l||{};return{content:Buffer.concat(h),contentType:i,ETag:n,expiredAt:s,id:t,metadata:k,modifiedAt:c,name:t,originalName:y||t,size:Number(a)}})}async buildPresigned(t){const e=t;if(e.Parts?.length||(e.Parts=await this.getParts(t)),e.bytesWritten=e.Parts.map(r=>r.Size||0).reduce((r,a)=>r+a,0),t.status=S(e),e.partsUrls?.length||(e.partsUrls=await this.getPartsPresignedUrls(t)),t.status==="completed"){const[r]=await this.internalOnComplete(t);return delete e.Parts,e.uri=r.Location,t}return t}async getPartsPresignedUrls(t){t.partSize??=this.partSize;const e=t.UploadId;if(!e)throw new Error("UploadId is required for getting presigned URLs");const r=Math.trunc(t.size/this.partSize)+1,a=[],i=Math.trunc($(this.config.expiration?.maxAge||"6hrs")),n=this.getS3Api();for(let s=0;s<r;s++)a.push(n.getPresignedUrl({Bucket:this.bucket,expiresIn:i,Key:t.name,PartNumber:s+1,UploadId:e}));return Promise.all(a)}async getParts(t){const e=this.getS3Api(),r=t.UploadId;if(!r)throw new Error("UploadId is required");const{Parts:a=[]}=await this.retry(()=>e.listParts({Bucket:this.bucket,Key:t.name,UploadId:r}));return a}completeMultipartUpload(t){const e=this.getS3Api(),r=t.UploadId;if(!r)throw new Error("UploadId is required");const a=t.Parts?.map(({ETag:i,PartNumber:n})=>{if(!i||!n)throw new Error("ETag and PartNumber are required");return{ETag:i,PartNumber:n}})||[];return this.retry(()=>e.completeMultipartUpload({Bucket:this.bucket,Key:t.name,Parts:a,UploadId:r}))}async abortMultipartUpload(t){if(t.status!=="completed")try{const e=this.getS3Api(),r=t.UploadId;if(!r)return;await this.retry(()=>e.abortMultipartUpload({Bucket:this.bucket,Key:t.name,UploadId:r}))}catch(e){this.logger?.error("abortMultipartUploadError: ",e);const r=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(r)}}internalOnComplete=f(async t=>{const[e]=await Promise.all([this.completeMultipartUpload(t),this.deleteMeta(t.id)]);return[e,t]},"internalOnComplete")}export{b as S};
@@ -1 +0,0 @@
1
- var H=Object.defineProperty;var h=(t,e)=>H(t,"name",{value:e,configurable:!0});import{Readable as X}from"node:stream";import{setInterval as J}from"node:timers";import{inspect as Q}from"node:util";import{L as ee,O as I}from"./path-D7rMc9nq-B718mbm6.js";import te from"type-is";import re from"./NoOpMetrics-Dky06sf1.js";import{N as oe}from"./cache-qV_5Umeq.js";import{ErrorMap as M,throwErrorCode as E,ERRORS as $}from"./ERRORS-CyOuSMLY.js";import{randomUUID as se}from"node:crypto";import{LRUCache as ae}from"lru-cache";import{o as ie}from"./is-expired-1JuZjDtb.js";var ne=Object.defineProperty,ce=h((t,e)=>ne(t,"name",{value:e,configurable:!0}),"y$3"),le=Object.defineProperty,ue=ce((t,e)=>le(t,"name",{value:e,configurable:!0}),"y"),me=Object.defineProperty,S=ue((t,e)=>me(t,"name",{value:e,configurable:!0}),"i");const de=/^(?<value>-?\d+(?:[.,]\d+)*) *(?<type>[a-z]+)?$/i,ge=/^KIBI/,he=/^MIBI/,pe=/^GIBI/,fe=/^TEBI/,ye=/^PEBI/,be=/^EXBI/,we=/^ZEBI/,ve=/^YIBI/,Ee=/^(.)IB$/,_={iec:[{long:"Bytes",short:"B"},{long:"Kibibytes",short:"KiB"},{long:"Mebibytes",short:"MiB"},{long:"Gibibytes",short:"GiB"},{long:"Tebibytes",short:"TiB"},{long:"Pebibytes",short:"PiB"},{long:"Exbibytes",short:"EiB"},{long:"Zebibytes",short:"ZiB"},{long:"Yobibytes",short:"YiB"}],iec_octet:[{long:"Octets",short:"o"},{long:"Kibioctets",short:"Kio"},{long:"Mebioctets",short:"Mio"},{long:"Gibioctets",short:"Gio"},{long:"Tebioctets",short:"Tio"},{long:"Pebioctets",short:"Pio"},{long:"Exbioctets",short:"Eio"},{long:"Zebioctets",short:"Zio"},{long:"Yobioctets",short:"Yio"}],metric:[{long:"Bytes",short:"Bytes"},{long:"Kilobytes",short:"KB"},{long:"Megabytes",short:"MB"},{long:"Gigabytes",short:"GB"},{long:"Terabytes",short:"TB"},{long:"Petabytes",short:"PB"},{long:"Exabytes",short:"EB"},{long:"Zettabytes",short:"ZB"},{long:"Yottabytes",short:"YB"}],metric_octet:[{long:"Octets",short:"o"},{long:"Kilo-octets",short:"ko"},{long:"Mega-octets",short:"Mo"},{long:"Giga-octets",short:"Go"},{long:"Tera-octets",short:"To"},{long:"Peta-octets",short:"Po"},{long:"Exa-octets",short:"Eo"},{long:"Zetta-octets",short:"Zo"},{long:"Yotta-octets",short:"Yo"}]},$e=S((t,e)=>{const r=new Intl.NumberFormat(e).format(11111).replaceAll(new RegExp("\\p{Number}","gu"),""),o=new Intl.NumberFormat(e).format(1.1).replaceAll(new RegExp("\\p{Number}","gu"),"");return Number.parseFloat(t.replaceAll(new RegExp(`\\${r}`,"g"),"").replace(new RegExp(`\\${o}`),"."))},"parseLocalizedNumber"),F=S(t=>{switch(t){case 2:return 1024;case 10:return 1e3;default:throw new Error("Unsupported base.")}},"fromBase"),j=S((t,e)=>{const r={base:2,locale:"en-US",units:"metric",...e};if(typeof t!="string"||t.length===0)throw new TypeError("Value is not a string or is empty.");if(t.length>100)throw new TypeError("Value exceeds the maximum length of 100 characters.");const o=de.exec(t)?.groups;if(!o)return Number.NaN;const s=$e(o.value,r.locale),i=(o.type??"Bytes").toUpperCase().replace(ge,"KILO").replace(he,"MEGA").replace(pe,"GIGA").replace(fe,"TERA").replace(ye,"PETA").replace(be,"EXA").replace(we,"ZETTA").replace(ve,"YOTTA").replace(Ee,"$1B"),n=_[r.units].findIndex(c=>c.short[0].toUpperCase()===i[0]),l=F(r.base);return s*l**n},"parseBytes");S((t,e)=>{if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("Bytesize is not a number.");const{base:r,decimals:o,locale:s,long:i,unit:n,units:l,...c}={base:2,decimals:0,locale:"en-US",long:!1,units:"metric",...e},a=F(r),m=Math.abs(t),u=e?.space??!0?" ":"",d=_[l],g=d.findIndex(w=>w.short===n);if(t===0){const w=Math.min(0,Math.max(g,d.length-1));return"0"+u+d[w][i?"long":"short"]}const y=g===-1?Math.min(Math.floor(Math.log(m)/Math.log(a)),d.length-1):g,N=d[y][i?"long":"short"],O=t/a**y,v=o<0?void 0:o;return new Intl.NumberFormat(s,{maximumFractionDigits:v,minimumFractionDigits:v,...c}).format(O)+u+N},"formatBytes");var xe=Object.defineProperty,Me=h((t,e)=>xe(t,"name",{value:e,configurable:!0}),"u$3"),Ne=Object.defineProperty,Oe=Me((t,e)=>Ne(t,"name",{value:e,configurable:!0}),"v"),Ae=Object.defineProperty,Te=Oe((t,e)=>Ae(t,"name",{value:e,configurable:!0}),"D");const Se=Te((t,e,r,o,s,i,n,l,c,a,m,u,d,g)=>{const y={d:o,h:s,m:i,mo:e,ms:l,s:n,w:r,y:t};return c!==void 0&&(y.future=c),a!==void 0&&(y.past=a),m!==void 0&&(y.decimal=m),u!==void 0&&(y.unitMap=u),d!==void 0&&(y.groupSeparator=d),g!==void 0&&(y.placeholderSeparator=g),y},"createDurationLanguage"),L={d:"d",day:"d",days:"d",h:"h",hour:"h",hours:"h",hr:"h",hrs:"h",m:"m",millisecond:"ms",milliseconds:"ms",min:"m",mins:"m",minute:"m",minutes:"m",mo:"mo",month:"mo",months:"mo",ms:"ms",s:"s",sec:"s",second:"s",seconds:"s",secs:"s",w:"w",week:"w",weeks:"w",y:"y",year:"y",years:"y",yr:"y",yrs:"y"},Ce=Se(t=>`year${t===1?"":"s"}`,t=>`month${t===1?"":"s"}`,t=>`week${t===1?"":"s"}`,t=>`day${t===1?"":"s"}`,t=>`hour${t===1?"":"s"}`,t=>`minute${t===1?"":"s"}`,t=>`second${t===1?"":"s"}`,t=>`millisecond${t===1?"":"s"}`,"in %s","%s ago",".",L,",","_");var Ie=Object.defineProperty,Be=h((t,e)=>Ie(t,"name",{value:e,configurable:!0}),"o"),Pe=Object.defineProperty,De=Be((t,e)=>Pe(t,"name",{value:e,configurable:!0}),"o"),Ue=Object.defineProperty,ze=De((t,e)=>Ue(t,"name",{value:e,configurable:!0}),"o");const je=ze(t=>{const e=["y","mo","w","d","h","m","s","ms","future","past"];for(const o of e)if(!Object.hasOwn(t,o))throw new TypeError(`Missing required property: ${o}`);if(typeof t.future!="string"||typeof t.past!="string")throw new TypeError("Properties future and past must be of type string");const r=["y","mo","w","d","h","m","s","ms"];for(const o of r)if(typeof t[o]!="string"&&typeof t[o]!="function")throw new TypeError(`Property ${o} must be of type string or function`);if(t.decimal&&typeof t.decimal!="string")throw new TypeError("Property decimal must be of type string");if(t.delimiter&&typeof t.delimiter!="string")throw new TypeError("Property delimiter must be of type string");if(t._digitReplacements&&!Array.isArray(t._digitReplacements))throw new TypeError("Property _digitReplacements must be an array");if(t._numberFirst&&typeof t._numberFirst!="boolean")throw new TypeError("Property _numberFirst must be of type boolean");if(t.unitMap&&typeof t.unitMap!="object")throw new TypeError("Property unitMap must be an object");if(t.unitMap&&Object.values(t.unitMap).some(o=>typeof o!="string"))throw new TypeError("All values in unitMap must be of type string")},"validateDurationLanguage");var ke=Object.defineProperty,_e=h((t,e)=>ke(t,"name",{value:e,configurable:!0}),"w$1"),Fe=Object.defineProperty,Le=_e((t,e)=>Fe(t,"name",{value:e,configurable:!0}),"S"),Re=Object.defineProperty,Ve=Le((t,e)=>Re(t,"name",{value:e,configurable:!0}),"h");const k={d:864e5,h:36e5,m:6e4,mo:2629746e3,ms:1,s:1e3,w:6048e5,y:31556952e3},A=/[-/\\^$*+?.()|[\]{}]/g,Ge=/^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/i,Ye=/^(?:(\d+):)?(?:(\d+):)?(\d+)$/,Ze=/^[+-]?\d+(?:\.\d+)?$/,Ke=/^[-+]/,We=Ve((t,e)=>{if(typeof t!="string"||t.length===0)return;const{defaultUnit:r="ms",language:o=Ce}=e??{};je(o);const s=o.decimal??".",i=o.groupSeparator??",",n=o.placeholderSeparator??"_",l=s.replaceAll(A,String.raw`\$&`),c=i.replaceAll(A,String.raw`\$&`),a=n.replaceAll(A,String.raw`\$&`),m=o.unitMap??L;let u=t.replaceAll(new RegExp(String.raw`(\d)[${a}${c}](\d)`,"g"),"$1$2");if(s!=="."&&(u=u.replace(l,".")),Ze.test(t)){const p=Number.parseFloat(u.trim());if(!Number.isNaN(p)){const f=m[r];if(f!==void 0)return p*k[f]}return}const d=Ge.exec(t);if(d){const p=Number.parseInt(d[1]??"0",10),f=Number.parseInt(d[2]??"0",10),x=Number.parseInt(d[3]??"0",10);return p*36e5+f*6e4+x*1e3}const g=Ye.exec(t);if(g){let p=0,f=0;g[2]!==void 0?(p=Number.parseInt(g[1]??"0",10),f=Number.parseInt(g[2],10)):g[1]!==void 0&&(f=Number.parseInt(g[1],10));const x=Number.parseInt(g[3]??"0",10);return p*36e5+f*6e4+x*1e3}const y=Object.keys(m).toSorted((p,f)=>f.length-p.length).map(p=>p.replaceAll(A,String.raw`\$&`)).join("|"),N=new RegExp(String.raw`(-?\d*\.?\d+)\s*(${y})`,"gi");let O=0,v,w=!1,P=-1,D=0;for(N.lastIndex=0;(v=N.exec(u))!==null;){w||(P=v.index),w=!0;const p=v[1],f=v[2];if(!p||!f)continue;const x=p.trim(),K=x.startsWith("-")?-1:1,W=x.replace(Ke,""),U=Number.parseFloat(W),z=m[f.toLowerCase()];if(z===void 0)continue;const q=k[z];if(Number.isNaN(U))return;O+=K*U*q,D=N.lastIndex}const Y=u.slice(0,P).trim(),Z=u.slice(D).trim();if(!(w&&(Y.length>0||Z.length>0))&&w)return O},"parseDuration");var qe=Object.defineProperty,He=h((t,e)=>qe(t,"name",{value:e,configurable:!0}),"n$1");let Xe=class extends ae{static{h(this,"u")}static{He(this,"Locker")}constructor(e){super({ttl:3e4,ttlAutopurge:!0,...e})}lock(e){if(this.get(e)!==void 0)throw new Error(`${e} is locked`);const r=se();return this.set(e,r),r}unlock(e,r){return this.get(e)!==r?!1:this.delete(e)}};var Je=Object.defineProperty,Qe=h((t,e)=>Je(t,"name",{value:e,configurable:!0}),"e$1");const T=Qe(t=>{if(t===Number(t))return t;if(!t)return;const e=We(t);if(e!==void 0)return e},"toMilliseconds");var et=Object.defineProperty,tt=h((t,e)=>et(t,"name",{value:e,configurable:!0}),"t");let rt=class extends Error{static{h(this,"d")}static{tt(this,"ValidationError")}code;statusCode;body;headers;name="ValidationError";constructor(e,r,o,s){const i=typeof o=="string"?o:o?.message||"Validation error";super(i),this.code=e,this.statusCode=r,this.body=o,this.headers=s}};var ot=Object.defineProperty,C=h((t,e)=>ot(t,"name",{value:e,configurable:!0}),"e");const st=C(t=>t&&t[0].toUpperCase()+t.slice(1),"capitalize"),at=C(t=>{if(!Array.isArray(t))return t;const[e,r,o]=t;return{body:r,headers:o,statusCode:e}},"toResponse");class it{static{h(this,"Validator")}constructor(e="ValidationError"){this.prefix=e}prefix;static{C(this,"Validator")}validators={};add(e){Object.entries(e).forEach(([r,o])=>{const s=`${this.prefix}${st(r)}`;if(this.validators[s]={...this.validators[s],...o},typeof this.validators[s].isValid!="function")throw new TypeError('Validation config "isValid" is missing, or it is not a function!')})}async verify(e){for(const[r,o]of Object.entries(this.validators))if(!await o.isValid(e)){const s=o.response||(r in M?M[r]:M.UnknownError),i=at(s),{body:n,headers:l,message:c,statusCode:a}=i;throw new rt(r,a,n||c,l)}}}const Tt=C(t=>t.name==="ValidationError","isValidationError");var nt=Object.defineProperty,B=h((t,e)=>nt(t,"name",{value:e,configurable:!0}),"i");const ct=B(t=>{if(typeof t.name=="string")return t.name;if(typeof t.title=="string")return t.title;if(typeof t.originalName=="string")return t.originalName;if(typeof t.filename=="string")return t.filename},"extractOriginalName"),R=B((t,e)=>{const r={...t};return Object.keys(e).forEach(o=>{const s=e[o];if(s!==null&&typeof s=="object"&&!Array.isArray(s)){const i=r[o],n=i&&typeof i=="object"&&!Array.isArray(i)?i:{};r[o]=R(n,s)}else r[o]=s}),r},"deepMerge"),lt=B((t,e)=>{const r=R(t,e);Object.assign(t,r),t.originalName=ct(t.metadata)||t.originalName},"updateMetadata");var ut=Object.defineProperty,b=h((t,e)=>ut(t,"name",{value:e,configurable:!0}),"g");const mt=/(secret|password|passwd|pwd|token|api[_-]?key|credential|authorization|sas|signature|sessiontoken|connectionstring)/i,V=b(t=>{const e={};for(const[r,o]of Object.entries(t))typeof o=="string"&&mt.test(r)?e[r]="[REDACTED]":o&&typeof o=="object"&&!Array.isArray(o)&&o.constructor===Object?e[r]=V(o):e[r]=o;return e},"redactSecrets"),dt={allowMIME:["*/*"],filename:b(({id:t})=>t,"filename"),maxMetadataSize:"8MB",maxUploadSize:"5TB",onComplete:b(()=>{},"onComplete"),onCreate:b(()=>{},"onCreate"),onDelete:b(()=>{},"onDelete"),onError:b(()=>{},"onError"),onUpdate:b(()=>{},"onUpdate"),useRelativeLocation:!1,validation:{}},gt=b(t=>!t||t.length<3||t.length>255||I(t)?!1:!(t.toUpperCase().includes("../")||t.includes("\0")),"defaultCloudStorageFileNameValidation"),St=b(t=>{if(!t||t.length<3||t.length>255||I(t))return!1;const e=t.toUpperCase();return!['"',"*",":","<",">","?","\\","|","../","\0"].some(r=>e.includes(r))},"defaultFilesystemFileNameValidation");class G{static{h(this,"BaseStorage")}static{b(this,"BaseStorage")}onCreate;onUpdate;onComplete;onDelete;onError;isReady=!0;errorResponses={};cache;logger;metrics;genericConfig;maxMetadataSize;checksumTypes=[];maxUploadSize;expiration;locker;namingFunction;validation=new it;assetFolder=void 0;concurrency;constructor(e){const r={...dt,...e};this.onCreate=r.onCreate,this.onUpdate=r.onUpdate,this.onComplete=r.onComplete,this.onDelete=r.onDelete,this.onError=r.onError,this.namingFunction=r.filename,this.maxUploadSize=typeof r.maxUploadSize=="string"?j(r.maxUploadSize):r.maxUploadSize,this.maxMetadataSize=typeof r.maxMetadataSize=="string"?j(r.maxMetadataSize):r.maxMetadataSize,this.expiration=r.expiration,this.genericConfig=r,r.assetFolder!==void 0&&(this.assetFolder=ee(r.assetFolder)),this.locker=new Xe({max:1e3,ttl:3e4,ttlAutopurge:!0}),this.cache=r.cache??new oe,this.logger=r.logger,this.metrics=r.metrics??new re,this.logger?.debug(`${this.constructor.name} config: ${Q(V({...e,logger:this.logger.constructor}))}`);const o=T(r.expiration?.purgeInterval);o&&this.startAutoPurge(o);const s={isValid(c){if(c.size===void 0)return!0;const a=c.size;if(a==null)return!1;const m=typeof a=="number"?a:Number(a);if(Number.isNaN(m)||m<0)return!1;const u=typeof this.value=="number"?this.value:Number(this.value);return!Number.isNaN(u)&&m<=u},response:M.RequestEntityTooLarge,value:this.maxUploadSize},i={isValid(c){return!!te.is(c.contentType,this.value)},response:M.UnsupportedMediaType,value:r.allowMIME},n=r.fileNameValidation??gt,l={isValid(c){return n(c.name)},response:M.InvalidFileName};this.validation.add({filename:l,mime:i,size:s}),this.validation.add({...r.validation})}get raw(){}async getReadUrl(e,r){return E($.METHOD_NOT_ALLOWED,`${this.constructor.name} does not implement getReadUrl()`)}async getUploadUrl(e,r){return E($.METHOD_NOT_ALLOWED,`${this.constructor.name} does not implement getUploadUrl()`)}get tusExtension(){const e=["creation","creation-with-upload","termination","checksum","creation-defer-length","concatenation"];return this.expiration&&e.push("expiration"),e}async validate(e){await this.validation.verify(e)}async exists(e){return this.instrumentOperation("exists",async()=>{try{return await this.getMeta(e.id),!0}catch{return!1}})}normalizeError(e){const r={code:e.name,message:e.message,name:e.name,statusCode:500};return{...r,message:`[${this.constructor.name}] ${r.message}`}}get config(){return this.genericConfig}async saveMeta(e){return G.assertSafeId(e.id),this.updateTimestamps(e),this.cache.set(e.id,e),this.meta.save(e.id,e)}static assertSafeId(e){(!e||typeof e!="string"||e.includes("\0")||e.includes("../")||e.includes("..\\")||e===".."||e.startsWith("../")||e.startsWith("..\\")||I(e)||/^[A-Z]:[/\\]/i.test(e))&&E($.INVALID_FILE_NAME,`Invalid file id: "${e}"`)}async deleteMeta(e){return this.cache.delete(e),this.meta.delete(e)}async getMeta(e){try{const r=await this.meta.get(e);return this.cache.set(r.id,r),{...r}}catch(r){const o=this.normalizeError(r instanceof Error?r:new Error(String(r)));return await this.onError(o),E($.FILE_NOT_FOUND)}}async checkIfExpired(e){return ie(e)?(this.delete(e).catch(()=>{}),this.deleteMeta(e.id).catch(()=>{}),E($.GONE)):e}async purge(e){return this.instrumentOperation("purge",async()=>{const r=T(e||this.expiration?.maxAge),o={items:[],maxAgeMs:r};if(r){const s=Date.now()-r,i=(await this.list()).filter(n=>Number(new Date(this.expiration?.rolling&&n.modifiedAt||n.createdAt))<s);for await(const{id:n,...l}of i)try{const c=await this.delete({id:n});o.items.push({...c,...l})}catch(c){this.logger?.warn(`Failed to delete file ${n} during purge: ${c instanceof Error?c.message:String(c)}`)}o.items.length>0&&(this.logger?.info(`Purge: removed ${o.items.length} uploads`),this.metrics.gauge("storage.operations.purge.items_count",o.items.length,{storage:this.constructor.name.toLowerCase().replace("storage","")}))}return o})}async getStream({id:e}){return this.instrumentOperation("getStream",async()=>{const r=await this.get({id:e}),o=X.from(r.content);return{headers:{"Content-Length":String(r.size),"Content-Type":r.contentType,...r.ETag&&{ETag:r.ETag},...r.modifiedAt&&{"Last-Modified":r.modifiedAt.toString()}},size:typeof r.size=="number"?r.size:void 0,stream:o}})}async list(e=1e3){return this.instrumentOperation("list",async()=>{throw new Error("Not implemented")})}async update({id:e},r){return this.instrumentOperation("update",async()=>{const o=await this.getMeta(e),s={...r};if("ttl"in s&&s.ttl!==void 0){const n=s.ttl,l=typeof n=="string"?T(n):n;l!==void 0&&(s.expiredAt=Date.now()+l),delete s.ttl}lt(o,s),await this.saveMeta(o);const i={...o,status:"updated"};return await this.onUpdate(i),i})}async deleteBatch(e){const r=Date.now(),o=this.constructor.name.toLowerCase().replace("storage","");this.metrics.increment("storage.operations.batch.delete.count",1,{batch_size:e.length,storage:o});const s=[],i=[],n=e.map(async a=>{try{return{file:await this.delete({id:a}),id:a,success:!0}}catch(m){const u=m instanceof Error?m.message:"Delete failed";return this.metrics.increment("storage.operations.delete.error.count",1,{error:u,storage:o}),{error:u,id:a,success:!1}}}),l=await Promise.allSettled(n);for(const a of l)a.status==="fulfilled"?a.value.success?s.push(a.value.file):i.push({error:a.value.error,id:a.value.id}):i.push({error:a.reason?.message||"Delete failed",id:""});const c=Date.now()-r;return this.metrics.timing("storage.operations.batch.delete.duration",c,{batch_size:e.length,storage:o}),this.metrics.gauge("storage.operations.batch.delete.success_count",s.length,{storage:o}),this.metrics.gauge("storage.operations.batch.delete.failed_count",i.length,{storage:o}),{failed:i,failedCount:i.length,successful:s,successfulCount:s.length}}async copyBatch(e){const r=Date.now(),o=this.constructor.name.toLowerCase().replace("storage","");this.metrics.increment("storage.operations.batch.copy.count",1,{batch_size:e.length,storage:o});const s=[],i=[],n=e.map(async({destination:a,options:m,source:u})=>{try{return{file:await this.copy(u,a,m),id:a,success:!0}}catch(d){const g=d instanceof Error?d.message:"Copy failed";return this.metrics.increment("storage.operations.copy.error.count",1,{error:g,storage:o}),{error:g,id:a,success:!1}}}),l=await Promise.allSettled(n);for(const a of l)a.status==="fulfilled"?a.value.success&&a.value.file?s.push(a.value.file):i.push({error:a.value.error||"Copy failed",id:a.value.id}):i.push({error:a.reason?.message||"Copy failed",id:""});const c=Date.now()-r;return this.metrics.timing("storage.operations.batch.copy.duration",c,{batch_size:e.length,storage:o}),this.metrics.gauge("storage.operations.batch.copy.success_count",s.length,{storage:o}),this.metrics.gauge("storage.operations.batch.copy.failed_count",i.length,{storage:o}),{failed:i,failedCount:i.length,successful:s,successfulCount:s.length}}async moveBatch(e){const r=Date.now(),o=this.constructor.name.toLowerCase().replace("storage","");this.metrics.increment("storage.operations.batch.move.count",1,{batch_size:e.length,storage:o});const s=[],i=[],n=e.map(async({destination:a,source:m})=>{try{return{file:await this.move(m,a),id:a,success:!0}}catch(u){const d=u instanceof Error?u.message:"Move failed";return this.metrics.increment("storage.operations.move.error.count",1,{error:d,storage:o}),{error:d,id:a,success:!1}}}),l=await Promise.allSettled(n);for(const a of l)a.status==="fulfilled"?a.value.success&&a.value.file?s.push(a.value.file):i.push({error:a.value.error||"Move failed",id:a.value.id}):i.push({error:a.reason?.message||"Move failed",id:a.reason?.id||""});const c=Date.now()-r;return this.metrics.timing("storage.operations.batch.move.duration",c,{batch_size:e.length,storage:o}),this.metrics.gauge("storage.operations.batch.move.success_count",s.length,{storage:o}),this.metrics.gauge("storage.operations.batch.move.failed_count",i.length,{storage:o}),{failed:i,failedCount:i.length,successful:s,successfulCount:s.length}}async lock(e){const r=[...this.locker.keys()];return r.includes(e)?E($.FILE_LOCKED):this.config.concurrency&&typeof this.config.concurrency=="number"&&this.config.concurrency<r.length?E($.STORAGE_BUSY):this.locker.lock(e)}async unlock(e,r){if(r===void 0){this.locker.delete(e);return}this.locker.unlock(e,r)}async withLock(e,r){const o=await this.lock(e);try{return await r()}finally{await this.unlock(e,o)}}isUnsupportedChecksum(e=""){return!!e&&!this.checksumTypes.includes(e)}startAutoPurge(e){if(e>=2147483647)throw new Error("“purgeInterval” must be less than 2147483647 ms");J(()=>{this.purge().catch(r=>this.logger?.error(r))},e)}updateTimestamps(e){e.createdAt??=new Date().toISOString();const r=T(this.expiration?.maxAge);return r&&!e.expiredAt&&(e.expiredAt=this.expiration?.rolling?Date.now()+r:+new Date(e.createdAt)+r),e}async instrumentOperation(e,r,o){const s=Date.now(),i={storage:this.constructor.name.toLowerCase().replace("storage",""),...o};try{this.metrics.increment(`storage.operations.${e}.count`,1,i);const n=await r(),l=Date.now()-s;return this.metrics.timing(`storage.operations.${e}.duration`,l,i),n&&typeof n=="object"&&"size"in n&&typeof n.size=="number"&&this.metrics.gauge("storage.files.size",n.size,{...i,operation:e}),n}catch(n){const l=Date.now()-s,c=n instanceof Error?n.message:"Unknown error";throw this.metrics.timing(`storage.operations.${e}.duration`,l,{...i,error:"true"}),this.metrics.increment(`storage.operations.${e}.error.count`,1,{...i,error:c}),n}}}export{j as $,G as B,St as a,rt as b,gt as d,Tt as i,T as t,lt as u,We as z};