@visulima/storage 1.0.0-alpha.25 → 1.0.0-alpha.27

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 (194) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE.md +0 -1104
  3. package/README.md +79 -466
  4. package/dist/adapter/nuxt/module.d.ts +4 -4
  5. package/dist/adapter/nuxt/node_modules/.bin/nuxi +22 -0
  6. package/dist/adapter/nuxt/node_modules/.bin/nuxt +22 -0
  7. package/dist/ai/ai-sdk/index.d.ts +113 -0
  8. package/dist/ai/ai-sdk/index.js +1 -0
  9. package/dist/ai/claude/index.d.ts +177 -0
  10. package/dist/ai/claude/index.js +1 -0
  11. package/dist/ai/openai/index.d.ts +205 -0
  12. package/dist/ai/openai/index.js +1 -0
  13. package/dist/ai/tanstack/index.d.ts +115 -0
  14. package/dist/ai/tanstack/index.js +1 -0
  15. package/dist/handler/http/fetch/index.d.ts +13 -7
  16. package/dist/handler/http/fetch/index.js +1 -1
  17. package/dist/handler/http/hono/index.d.ts +5 -1412
  18. package/dist/handler/http/hono/index.js +1 -1
  19. package/dist/handler/http/nextjs/index.d.ts +4 -4
  20. package/dist/handler/http/nextjs/index.js +1 -1
  21. package/dist/handler/http/node/index.d.ts +7 -7
  22. package/dist/handler/http/node/index.js +1 -1
  23. package/dist/handler/http/solid-start/index.d.ts +4 -4
  24. package/dist/handler/http/solid-start/index.js +1 -1
  25. package/dist/index.d.ts +6 -324
  26. package/dist/index.js +1 -1
  27. package/dist/packem_shared/{AwsLightFile-BTLiRxXj.js → AwsLightFile-BSqjc_rD.js} +1 -1
  28. package/dist/packem_shared/{AwsLightStorage-CA9cdfJ6.js → AwsLightStorage-SH7j-myh.js} +1 -1
  29. package/dist/packem_shared/{AzureFile-BKHru1zB.js → AzureFile-Dgj2Tef4.js} +1 -1
  30. package/dist/packem_shared/{AzureSMetaStorage-BqA4jUDJ.js → AzureSMetaStorage-DV2tNjKh.js} +1 -1
  31. package/dist/packem_shared/AzureStorage-BVYMFEBP.js +1 -0
  32. package/dist/packem_shared/BaseTransformer-Fpcuz4kj.js +1 -0
  33. package/dist/packem_shared/BoxFile-Be0S4N1L.js +1 -0
  34. package/dist/packem_shared/BoxMetaStorage-BUe5Qmqe.js +1 -0
  35. package/dist/packem_shared/BoxStorage-CgC81_So.js +1 -0
  36. package/dist/packem_shared/BunnyFile-Dotl-lO9.js +1 -0
  37. package/dist/packem_shared/BunnyMetaStorage-D0mT6veJ.js +1 -0
  38. package/dist/packem_shared/BunnyStorage-Bl4usdVT.js +1 -0
  39. package/dist/packem_shared/DiskStorage-B5uIDVXr.js +1 -0
  40. package/dist/packem_shared/DiskStorageWithChecksum-CbXWpSOr.js +1 -0
  41. package/dist/packem_shared/DropboxFile-BGVG2kXM.js +1 -0
  42. package/dist/packem_shared/DropboxMetaStorage-CICuUZ1n.js +1 -0
  43. package/dist/packem_shared/DropboxStorage-CPjhDN5B.js +1 -0
  44. package/dist/packem_shared/ERRORS-CyOuSMLY.js +1 -0
  45. package/dist/packem_shared/File-BhfUgJjs.js +1 -0
  46. package/dist/packem_shared/Files-B7hlJcB4.js +1 -0
  47. package/dist/packem_shared/{GCSFile-CHjX_fJk.js → GCSFile-CDQ6IWAz.js} +1 -1
  48. package/dist/packem_shared/{GCSMetaStorage-BQkYQUDn.js → GCSMetaStorage-CqP9ifYB.js} +1 -1
  49. package/dist/packem_shared/GCStorage-XSBKVx90.js +1 -0
  50. package/dist/packem_shared/GoogleDriveFile-D0aGfGbL.js +1 -0
  51. package/dist/packem_shared/GoogleDriveMetaStorage-rghGy3Fa.js +1 -0
  52. package/dist/packem_shared/GoogleDriveStorage-DuB6glUk.js +1 -0
  53. package/dist/packem_shared/LocalMetaStorage-B5uh1snG.js +1 -0
  54. package/dist/packem_shared/MediaTransformer-D-1c9Q_k.js +1 -0
  55. package/dist/packem_shared/Multipart-7FSSy2n1.js +1 -0
  56. package/dist/packem_shared/Multipart-DACQFsrn.js +1 -0
  57. package/dist/packem_shared/{NetlifyBlobFile-CpzkMKng.js → NetlifyBlobFile-PMZLJ8AC.js} +1 -1
  58. package/dist/packem_shared/NetlifyBlobMetaStorage-BcRFPky8.js +1 -0
  59. package/dist/packem_shared/NetlifyBlobStorage-C4qkJv1R.js +1 -0
  60. package/dist/packem_shared/OneDriveFile-XbVVKIJh.js +1 -0
  61. package/dist/packem_shared/OneDriveMetaStorage-B_BkGLzW.js +1 -0
  62. package/dist/packem_shared/OneDriveStorage-Cu0cGcrh.js +1 -0
  63. package/dist/packem_shared/Rest-5NwM1xYj.js +1 -0
  64. package/dist/packem_shared/{Rest-CYEBbtCD.js → Rest-y8Vz2Rt0.js} +1 -1
  65. package/dist/packem_shared/{S3File-Du6wP0Sz.js → S3File-BfmCOET4.js} +1 -1
  66. package/dist/packem_shared/S3Storage-D8dopWoO.js +1 -0
  67. package/dist/packem_shared/SupabaseFile-DZ1iv9gM.js +1 -0
  68. package/dist/packem_shared/SupabaseMetaStorage-BR1UGqnj.js +1 -0
  69. package/dist/packem_shared/SupabaseStorage-CCtMTiN5.js +1 -0
  70. package/dist/packem_shared/{Tus-CUBCkuPE.js → Tus-BCVAbJIi.js} +1 -1
  71. package/dist/packem_shared/Tus-CJMcygk7.js +1 -0
  72. package/dist/packem_shared/UploadThingFile-BpG9mE8K.js +1 -0
  73. package/dist/packem_shared/UploadThingMetaStorage-DyGNyaAq.js +1 -0
  74. package/dist/packem_shared/UploadThingStorage-B_fNzNFO.js +1 -0
  75. package/dist/packem_shared/{VercelBlobFile-CL9MjKcY.js → VercelBlobFile-Cni_1qwD.js} +1 -1
  76. package/dist/packem_shared/{VercelBlobMetaStorage-BsOTx-Su.js → VercelBlobMetaStorage-Do9ZoKrl.js} +1 -1
  77. package/dist/packem_shared/VercelBlobStorage-D5zy4PPQ.js +1 -0
  78. package/dist/packem_shared/agentsListFiles-R-CnGKc4.js +1 -0
  79. package/dist/packem_shared/akamai-BYS9pP8S.js +1 -0
  80. package/dist/packem_shared/approval-BBeX3o4E.js +1 -0
  81. package/dist/packem_shared/approval.d-CMAYH9GF.d.ts +75 -0
  82. package/dist/packem_shared/backblaze-CvdtCvJL.js +1 -0
  83. package/dist/packem_shared/base-handler-core-BfwZ1RS1.js +1 -0
  84. package/dist/packem_shared/base-handler-fetch-CLxqXTQf.js +1 -0
  85. package/dist/packem_shared/base-handler-node-DBZjcqsp.js +1 -0
  86. package/dist/packem_shared/claudeListFiles-DAezbKEi.js +1 -0
  87. package/dist/packem_shared/cloudflare-Bm_Pg6yx.js +1 -0
  88. package/dist/packem_shared/createResponsesFileTools-BCep-qdO.js +1 -0
  89. package/dist/packem_shared/defaultCloudStorageFileNameValidation-6URTv-Mp.js +1 -0
  90. package/dist/packem_shared/detect-file-type-5JhzC9RU.js +1 -0
  91. package/dist/packem_shared/digitalOcean-Lj1NfDzc.js +1 -0
  92. package/dist/packem_shared/disk-storage-CbSSPnOf.js +5 -0
  93. package/dist/packem_shared/{disk-storage-with-checksum.d-B5D9I_CA.d.ts → disk-storage-with-checksum.d-BQMXA4Wl.d.ts} +6 -4
  94. package/dist/packem_shared/executors-DG6hGtvm.js +1 -0
  95. package/dist/packem_shared/executors.d-UtkeCbk1.d.ts +65 -0
  96. package/dist/packem_shared/{gcs-meta-storage-CNiEWerS.js → gcs-meta-storage-XB-UPJn6.js} +1 -1
  97. package/dist/packem_shared/hetzner-DDxE7Gy7.js +1 -0
  98. package/dist/packem_shared/index.d-DotjipuX.d.ts +89 -0
  99. package/dist/packem_shared/isRetryableError-B6ZS_-5I.js +1 -0
  100. package/dist/packem_shared/listFiles-B6VF05d-.js +1 -0
  101. package/dist/packem_shared/listFiles-BtP6VnUp.js +1 -0
  102. package/dist/packem_shared/{local-meta-storage-Bkwqi_gi.js → local-meta-storage-CT1audnK.js} +1 -1
  103. package/dist/packem_shared/{local-meta-storage.d-rO44cnQ5.d.ts → local-meta-storage.d-B5R1nswK.d.ts} +2 -1
  104. package/dist/packem_shared/{media-transformer.d-BXjTN5Qv.d.ts → media-transformer.d-DK7NJncf.d.ts} +2 -2
  105. package/dist/packem_shared/minio-T_Z3iEy7.js +1 -0
  106. package/dist/packem_shared/multipart-base-BxckfvQf.js +1 -0
  107. package/dist/packem_shared/oauth-refresh-Dg2ybc6_.js +1 -0
  108. package/dist/packem_shared/part-match-B5fLLmFw.js +1 -0
  109. package/dist/packem_shared/rest-base-CCv78k7h.js +1 -0
  110. package/dist/packem_shared/s3-base-storage-f_EyFAAt.js +1 -0
  111. package/dist/packem_shared/{s3-base-storage.d-Ccatb1dO.d.ts → s3-base-storage.d-BROGYJ4F.d.ts} +1 -1
  112. package/dist/packem_shared/storage-CoyB2O-Y.js +1 -0
  113. package/dist/packem_shared/{storage.d-sc8gn16g.d.ts → storage.d-Cr6f2lac.d.ts} +118 -17
  114. package/dist/packem_shared/storj-CVA9mM-7.js +1 -0
  115. package/dist/packem_shared/tigris-wmhjfsH2.js +1 -0
  116. package/dist/packem_shared/{tus-base.d-BX3mSWL6.d.ts → tus-base.d-4-ZfDQwl.d.ts} +3 -3
  117. package/dist/packem_shared/{types.d-Cor8FV54.d.ts → types.d-BgCmSE94.d.ts} +2 -2
  118. package/dist/packem_shared/{types.d-b0WcdT0x.d.ts → types.d-C8eSxqX9.d.ts} +14 -2
  119. package/dist/packem_shared/wasabi-JQzxdrFy.js +1 -0
  120. package/dist/storage/aws/clients/index.d.ts +90 -15
  121. package/dist/storage/aws/clients/index.js +1 -1
  122. package/dist/storage/aws/index.d.ts +16 -15
  123. package/dist/storage/aws/index.js +1 -1
  124. package/dist/storage/aws-light/index.d.ts +5 -3
  125. package/dist/storage/aws-light/index.js +1 -1
  126. package/dist/storage/azure/index.d.ts +4 -10277
  127. package/dist/storage/azure/index.js +1 -1
  128. package/dist/storage/box/index.d.ts +186 -0
  129. package/dist/storage/box/index.js +1 -0
  130. package/dist/storage/bunny/index.d.ts +116 -0
  131. package/dist/storage/bunny/index.js +1 -0
  132. package/dist/storage/dropbox/index.d.ts +129 -0
  133. package/dist/storage/dropbox/index.js +1 -0
  134. package/dist/storage/gcs/index.d.ts +6 -3941
  135. package/dist/storage/gcs/index.js +1 -1
  136. package/dist/storage/google-drive/index.d.ts +145 -0
  137. package/dist/storage/google-drive/index.js +1 -0
  138. package/dist/storage/local/index.d.ts +3 -3
  139. package/dist/storage/local/index.js +1 -1
  140. package/dist/storage/netlify-blob/index.d.ts +4 -2
  141. package/dist/storage/netlify-blob/index.js +1 -1
  142. package/dist/storage/onedrive/index.d.ts +192 -0
  143. package/dist/storage/onedrive/index.js +1 -0
  144. package/dist/storage/supabase/index.d.ts +111 -0
  145. package/dist/storage/supabase/index.js +1 -0
  146. package/dist/storage/uploadthing/index.d.ts +91 -0
  147. package/dist/storage/uploadthing/index.js +1 -0
  148. package/dist/storage/vercel-blob/index.d.ts +17 -2
  149. package/dist/storage/vercel-blob/index.js +1 -1
  150. package/dist/transformer/audio-transformer.d.ts +2 -2
  151. package/dist/transformer/audio-transformer.js +1 -1
  152. package/dist/transformer/image-transformer.d.ts +6 -2
  153. package/dist/transformer/image-transformer.js +1 -1
  154. package/dist/transformer/index.d.ts +3 -3
  155. package/dist/transformer/index.js +1 -1
  156. package/dist/transformer/video-transformer.d.ts +2 -2
  157. package/dist/transformer/video-transformer.js +1 -1
  158. package/package.json +99 -3
  159. package/dist/packem_shared/AzureStorage-BKUjCymW.js +0 -1
  160. package/dist/packem_shared/BaseTransformer-D68eLyz1.js +0 -1
  161. package/dist/packem_shared/DiskStorage-DNjpDMX9.js +0 -1
  162. package/dist/packem_shared/DiskStorageWithChecksum-Bb6JX_tC.js +0 -1
  163. package/dist/packem_shared/ERRORS-B9jkvKwx.js +0 -1
  164. package/dist/packem_shared/File-alcSNpLq.js +0 -1
  165. package/dist/packem_shared/GCStorage-C8hxSNLM.js +0 -1
  166. package/dist/packem_shared/LocalMetaStorage-BWuFvWn4.js +0 -1
  167. package/dist/packem_shared/MediaTransformer-2C8MJeAg.js +0 -1
  168. package/dist/packem_shared/Multipart-Bd9YFFn0.js +0 -1
  169. package/dist/packem_shared/Multipart-D5bcEvga.js +0 -1
  170. package/dist/packem_shared/NetlifyBlobMetaStorage-dD0oBLom.js +0 -1
  171. package/dist/packem_shared/NetlifyBlobStorage-ByTwCN-h.js +0 -1
  172. package/dist/packem_shared/Rest-DoonVU7B.js +0 -1
  173. package/dist/packem_shared/S3Client.d-CZ62Jztg.d.ts +0 -20357
  174. package/dist/packem_shared/S3Storage-Fx6-OSc-.js +0 -1
  175. package/dist/packem_shared/Tus-Bd_2Ki2G.js +0 -1
  176. package/dist/packem_shared/VercelBlobStorage-kNkk5Cn4.js +0 -1
  177. package/dist/packem_shared/backblaze-DEflv87m.js +0 -1
  178. package/dist/packem_shared/base-handler-core-DaggCVsq.js +0 -1
  179. package/dist/packem_shared/base-handler-fetch-DnarP64X.js +0 -1
  180. package/dist/packem_shared/base-handler-node-BTes6sql.js +0 -1
  181. package/dist/packem_shared/cloudflare-DLAeQvgD.js +0 -1
  182. package/dist/packem_shared/defaultCloudStorageFileNameValidation-yiM9GxHr.js +0 -1
  183. package/dist/packem_shared/digitalOcean-nhZUds87.js +0 -1
  184. package/dist/packem_shared/disk-storage-BvdK4bqF.js +0 -5
  185. package/dist/packem_shared/isRetryableError-DQNSZiBc.js +0 -1
  186. package/dist/packem_shared/minio-BWwgGXeE.js +0 -1
  187. package/dist/packem_shared/multipart-base-C6OjBwMS.js +0 -1
  188. package/dist/packem_shared/part-match-DqD5U7An.js +0 -1
  189. package/dist/packem_shared/rest-base-B2Dv7esY.js +0 -1
  190. package/dist/packem_shared/s3-base-storage-xHZNtsGe.js +0 -1
  191. package/dist/packem_shared/storage-m_Cxgiih.js +0 -1
  192. package/dist/packem_shared/tigris-DZoyrMNd.js +0 -1
  193. package/dist/packem_shared/validator-DK41xp8N.js +0 -1
  194. package/dist/packem_shared/wasabi-Dmce4x9s.js +0 -1
@@ -1 +0,0 @@
1
- var h=Object.defineProperty;var u=(i,e)=>h(i,"name",{value:e,configurable:!0});import{Readable as p}from"node:stream";import{CreateMultipartUploadCommand as C,UploadPartCommand as g,CompleteMultipartUploadCommand as f,AbortMultipartUploadCommand as k,ListPartsCommand as w,GetObjectCommand as b,HeadObjectCommand as B,DeleteObjectCommand as S,CopyObjectCommand as E,ListObjectsV2Command as T,waitUntilBucketExists as U,S3Client as K}from"@aws-sdk/client-s3";import{fromIni as x}from"@aws-sdk/credential-providers";import{S as L}from"./s3-base-storage-xHZNtsGe.js";import{ReadableStream as y}from"node:stream/web";import{getSignedUrl as M}from"@aws-sdk/s3-request-presigner";import P from"./S3File-Du6wP0Sz.js";import I from"./S3MetaStorage-vcriiosn.js";var A=Object.defineProperty,O=u((i,e)=>A(i,"name",{value:e,configurable:!0}),"s");class j{static{u(this,"T")}constructor(e,a){this.client=e}client;static{O(this,"S3ClientAdapter")}async createMultipartUpload(e){const a=new C({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),t=await this.client.send(a);if(!t.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:t.UploadId}}async uploadPart(e){const a=e.Body instanceof y?p.fromWeb(e.Body):e.Body,t=new g({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),n=await this.client.send(t);if(!n.ETag)throw new Error("Failed to upload part");return{ETag:n.ETag}}async completeMultipartUpload(e){const a=new f({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:n,PartNumber:o})=>({ETag:n,PartNumber:o}))},UploadId:e.UploadId}),t=await this.client.send(a);if(!t.Location)throw new Error("Failed to complete multipart upload");return{ETag:t.ETag,Location:t.Location}}async abortMultipartUpload(e){const a=new k({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a)}async listParts(e){const a=new w({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),t=await this.client.send(a),n=[];if(t.Parts)for(const o of t.Parts)o.ETag&&o.PartNumber&&n.push({ETag:o.ETag,PartNumber:o.PartNumber,Size:o.Size});return{Parts:n.length>0?n:void 0}}async getObject(e){const a=new b({Bucket:e.Bucket,Key:e.Key}),t=await this.client.send(a);let n;if(t.Body){const o=t.Body;o instanceof p||typeof o=="object"&&"transform"in o&&o instanceof y?n=o:n=p.from(o)}return{Body:n,ContentLength:t.ContentLength,ContentType:t.ContentType,ETag:t.ETag,Expires:t.Expires,LastModified:t.LastModified,Metadata:t.Metadata}}async headObject(e){const a=new B({Bucket:e.Bucket,Key:e.Key}),t=await this.client.send(a);return{ContentLength:t.ContentLength,ContentType:t.ContentType,ETag:t.ETag,Expires:t.Expires,LastModified:t.LastModified}}async deleteObject(e){const a=new S({Bucket:e.Bucket,Key:e.Key});await this.client.send(a)}async copyObject(e){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const t=new E(a);await this.client.send(t)}async listObjectsV2(e){const a=new T({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,MaxKeys:e.MaxKeys}),t=await this.client.send(a);return{Contents:t.Contents?.map(n=>({Key:n.Key,LastModified:n.LastModified})),IsTruncated:t.IsTruncated,NextContinuationToken:t.NextContinuationToken}}async getPresignedUrl(e){const a=new g({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return M(this.client,a,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await U({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}var N=Object.defineProperty,v=u((i,e)=>N(i,"name",{value:e,configurable:!0}),"u");class H extends L{static name="s3";s3Api;constructor(e){const{bucket:a=process.env.S3_BUCKET,region:t=process.env.S3_REGION}=e;if(!a)throw new Error("S3 bucket is not defined");if(!t)throw new Error("S3 region is not defined");e.region=t;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=x({configFilepath:n}));const o=new K(e);super({bucket:a,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:v(s=>{const r=s;if(r.$metadata){const l=r.$metadata.httpStatusCode;if(l&&[408,429,500,502,503,504].includes(l)||r.$fault==="server")return!0}return r.retryable??!1},"shouldRetry")}}),this.s3Api=new j(o,a);const{metaStorage:d,metaStorageConfig:c}=e;if(!d){const s={...e,...c,logger:this.logger};"directory"in s||(this.meta=new I(s))}this.config.clientDirectUpload&&(this.onCreate=async()=>{})}normalizeError(e){return e.$metadata?{code:e.Code||e.name,message:e.message,name:e.name,statusCode:e.$metadata.httpStatusCode||500}:super.normalizeError(e)}async update({id:e},a){if(this.config.clientDirectUpload){const t=await this.getMeta(e);return this.buildPresigned({...t,...a})}return super.update({id:e},a)}async getStream({id:e}){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),{Body:t,ContentLength:n,ContentType:o,ETag:d,Expires:c,LastModified:s}=await this.retry(()=>a.getObject({Bucket:this.bucket,Key:e}));await this.checkIfExpired({expiredAt:c});const r=t,l=new p({read(){r.on("data",m=>{this.push(m)}),r.on("end",()=>{this.push(null)}),r.on("error",m=>{this.destroy(m)})}});return{headers:{"Content-Length":n?.toString()??"0","Content-Type":o,...d&&{ETag:d},...c&&{"X-Upload-Expires":c.toString()},...s&&{"Last-Modified":s.toString()}},size:Number(n),stream:l}})}getS3Api(){return this.s3Api}getFileClass(){return P}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{H as default};
@@ -1 +0,0 @@
1
- var y=Object.defineProperty;var g=(i,e)=>y(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{O as B}from"./base-handler-fetch-DnarP64X.js";import{TusBase as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_RESUMABLE as L,TUS_VERSION as P}from"./TUS_RESUMABLE-B7KtPVeC.js";var w=Object.defineProperty,f=g((i,e)=>w(i,"name",{value:e,configurable:!0}),"g");const l=f(i=>{try{const e=new URL(i).pathname.split("/").filter(Boolean);return e[e.length-1]||void 0}catch{return}},"getIdFromRequestUrl");class T extends B{static{g(this,"Tus")}static{f(this,"Tus")}static methods=["delete","download","get","head","options","patch","post"];tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const r=this;this.tusBase=new class extends O{get storage(){return r.storage}get disableTerminationForFinishedUploads(){return r.disableTerminationForFinishedUploads??!1}buildFileUrl(t,s){return r.buildFileUrlForTus(t,s)}}}async options(){return this.tusBase.handleOptions(T.methods)}async post(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=e.headers.get("upload-length")||void 0,s=e.headers.get("upload-defer-length")||void 0,o=e.headers.get("upload-concat")||void 0,d=e.headers.get("upload-metadata")||void 0,u=e.headers.get("content-type")||"",n=e.headers.get("content-length"),h=n?Number.parseInt(n,10):0,c=e.url,p=e.body;return this.tusBase.handlePost(t,s,o,d,c,p,h,u)}async patch(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=l(e.url);if(!t)throw a(404,"File not found");const s=e.headers.get("upload-offset");if(!s)throw a(412,"Missing Upload-Offset header");const o=e.headers.get("content-type");if(!o)throw a(412,"Content-Type header required");if(o!=="application/offset+octet-stream")throw a(415,"Unsupported Media Type");const d=Number.parseInt(s,10),u=e.headers.get("upload-length")||void 0,n=e.headers.get("upload-metadata")||void 0,h=e.headers.get("content-length"),c=h?Number.parseInt(h,10):0,p=e.headers.get("upload-checksum")||void 0,{checksum:U,checksumAlgorithm:F}=this.tusBase.extractChecksum(p),v=e.url,E=e.body;try{return this.tusBase.handlePatch(t,d,u,n,U,F,v,E,c)}catch(m){const b=m;throw b.UploadErrorCode==="GONE"||b.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):m}}async head(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=l(e.url);if(!t)throw a(404,"File not found");try{return this.tusBase.handleHead(t)}catch(s){const o=s;throw o.UploadErrorCode==="GONE"||o.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):s}}async get(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=l(e.url);if(!t)throw a(404,"File not found");try{return this.tusBase.handleGet(t)}catch(s){throw s.UploadErrorCode==="GONE"?a(410,"Upload expired"):s}}async delete(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=l(e.url);if(!t)throw a(404,"File not found");try{return this.tusBase.handleDelete(t)}catch(s){throw s.code==="ENOENT"?a(404,"File not found"):s}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForTus(e,r){const t=new URL(e),{pathname:s,search:o}=t,d=`${s}/${r.id}${o}`;return this.storage.config.useRelativeLocation?d:t.origin+d}}export{L as TUS_RESUMABLE,P as TUS_VERSION,T as Tus};
@@ -1 +0,0 @@
1
- var p=Object.defineProperty;var l=(n,e)=>p(n,"name",{value:e,configurable:!0});import{put as h,del as d,copy as f,list as w}from"@vercel/blob";import{o as c,r as y,a as g}from"./part-match-DqD5U7An.js";import{B as E,t as O}from"./storage-m_Cxgiih.js";import{O as b}from"./local-meta-storage-Bkwqi_gi.js";import m from"./VercelBlobFile-CL9MjKcY.js";import{u as v}from"./update-size-DANV7aa2.js";import{o as B}from"./has-content-Bx2p8Okx.js";var T=Object.defineProperty,k=l((n,e)=>T(n,"name",{value:e,configurable:!0}),"l");class z extends E{static name="vercel-blob";checksumTypes=["md5"];meta;token;multipart;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;const{metaStorage:t,metaStorageConfig:a}=e;this.meta=t||new b(a),this.isReady=!0}async create(e){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const i=typeof e.ttl=="string"?O(e.ttl):e.ttl;t.expiredAt=i===void 0?void 0:Date.now()+i}const a=new m(t);a.name=this.namingFunction(a),await this.validate(a);try{const i=await this.getMeta(a.id);if(i.bytesWritten>=0)return i}catch{}return a.bytesWritten=0,a.status=c(a),await this.saveMeta(a),await this.onCreate(a),a})}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&&v(t,e.size),!y(e,t))throw new Error("File part does not match");await this.lock(e.id);try{if(B(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],i=e.body;for await(const o of i)a.push(Buffer.from(o));const r=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await g(r);o?.mime&&(t.contentType=o.mime)}catch{}const u=new Blob([r],{type:t.contentType}),s=await h(t.name,u,{access:"public",multipart:this.shouldUseMultipart(t)});t.url=s.url,t.pathname=s.pathname,t.downloadUrl=s.downloadUrl,t.bytesWritten=r.length}return t.status=c(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id)}})}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 d(t.url,{token:this.token})}catch(i){this.logger?.error("Failed to delete blob from Vercel Blob:",i);const r=this.normalizeError(i instanceof Error?i:new Error(String(i)));await this.onError(r)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}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 a=await fetch(t.url),i=Buffer.from(await a.arrayBuffer());return{content:i,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||i.length}})}async copy(e,t){return this.instrumentOperation("copy",async()=>{const a=await this.getMeta(e);if(!a.url)throw new Error("Source file URL not found");const i=await f(a.url,t,{access:"public"});return{...a,id:t,name:t,pathname:i.pathname,url:i.url}})}async move(e,t){return this.instrumentOperation("move",async()=>{const a=await this.copy(e,t);return await this.delete({id:e}),a})}async list(e=1e3){return this.instrumentOperation("list",async()=>(await w({limit:e})).blobs.map(t=>{const a=new m({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return a.createdAt=t.uploadedAt?.toISOString(),a.id=t.pathname,a.modifiedAt=t.uploadedAt?.toISOString(),a.name=t.pathname,a.pathname=t.pathname,a.size=t.size,a.url=t.url,a.downloadUrl=t.downloadUrl,a}),{limit:e})}internalOnComplete=k(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{z as default};
@@ -1 +0,0 @@
1
- var a=Object.defineProperty;var n=(r,e)=>a(r,"name",{value:e,configurable:!0});var o=Object.defineProperty,p=n((r,e)=>o(r,"name",{value:e,configurable:!0}),"n");const i=p(r=>{const{applicationKey:e,applicationKeyId:c,region:s}=r??{applicationKey:process.env.AWS_SECRET_ACCESS_KEY||process.env.B2_APP_KEY||process.env.BACKBLAZE_APP_KEY,applicationKeyId:process.env.AWS_ACCESS_KEY_ID||process.env.B2_APP_KEY_ID||process.env.BACKBLAZE_APP_KEY_ID,region:process.env.AWS_REGION||process.env.B2_REGION||process.env.BACKBLAZE_REGION};if(!s||!c||!e)throw new Error("Missing required parameters for Backblaze B2 client.");return{credentials:{accessKeyId:c,secretAccessKey:e},endpoint:`https://s3.${s}.backblazeb2.com`,region:s}},"backblaze");export{i as backblaze,i as default};
@@ -1 +0,0 @@
1
- var g=Object.defineProperty;var c=(r,e)=>g(r,"name",{value:e,configurable:!0});import{EventEmitter as b}from"node:events";import{format as y}from"node:url";import w from"mime";import{ErrorMap as E}from"./ERRORS-B9jkvKwx.js";import{H as R}from"./headers-DC2MEOrK.js";import{Readable as h}from"node:stream";import v,{hasBody as U}from"type-is";var H=Object.defineProperty,I=c((r,e)=>H(r,"name",{value:e,configurable:!0}),"a");const L=I(r=>r.at(-1),"getLastOne");var N=Object.defineProperty,i=c((r,e)=>N(r,"name",{value:e,configurable:!0}),"n");const x=i(r=>{let e="",t="";const s=f(r,"forwarded");return s&&s.split(";").forEach(n=>{const[a,o]=n.split("=");a==="proto"&&(e=o),a==="host"&&(t=o)}),{host:t,proto:e}},"extractForwarded"),P=i((r,e="utf8",t)=>new Promise((s,n)=>{let a="";r.setEncoding(e),r.on("data",o=>{if(t&&a.length+o.length>t){n(new Error("Request body length limit exceeded"));return}a+=o}),r.once("end",()=>{s(a)})}),"readBody"),f=i((r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const n=Array.isArray(s)?s:s.split(",");return L(n).trim()},"getHeader");i(async(r,e=16777216)=>{if(!v(r,["json"]))return{};if(r.body)return{...r.body};if(U(r)){const s=Number.parseInt(f(r,"content-length"),10);if(!Number.isNaN(s)&&s>e)throw new Error("body length limit")}const t=await P(r,"utf8",e);return{...JSON.parse(t)}},"getMetadata");const $=i((r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},"appendHeader"),G=i((r,e={})=>{const t=Object.keys(e);t.length>0&&$(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{["link","location"].includes(s.toLowerCase())?r.setHeader(s,encodeURI(e[s].toString())):r.setHeader(s,e[s])})},"setHeaders"),q=i(r=>f(r,"host")||f(r,"x-forwarded-host"),"extractHost"),F=i(r=>f(r,"x-forwarded-proto").toLowerCase(),"extractProto"),T=i(r=>{let{host:e,proto:t}=x(r);return e||=q(r),t||=F(r),e?t?`${t}://${e}`:`//${e}`:""},"getBaseUrl"),B=i(r=>{let e=(r.originalUrl||r.url||"").split("?")[0];if(!e)throw new TypeError("Invalid request URL");return e.startsWith("/")||(e=`/${e}`),e.startsWith("http")&&(e=new URL(e).pathname),e},"getRealPath"),O=/(?:[\dA-Z]+-){2}[\dA-Z]+/i,K=i(r=>{const e=B(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(!a)continue;const o=a.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(o.toLowerCase())&&O.test(o))return o}const t=e[e.length-1];if(!t)throw new Error("Invalid request URL");const s=t.replace(/\.[^/.]+$/,"");if(["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(s.toLowerCase()))throw new Error("Invalid request URL");if(s.length<8)throw new Error("Invalid request URL");if(e.length>1)return s;throw new Error("Invalid request URL")},"getIdFromRequest"),Q=i(r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?h.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?h.from(Buffer.from(r.body)):r instanceof h?r:h.from(new Uint8Array(0)),"getRequestStream");var j=Object.defineProperty,C=c((r,e)=>j(r,"name",{value:e,configurable:!0}),"r");const V=C((r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},"pick");var A=Object.defineProperty,p=c((r,e)=>A(r,"name",{value:e,configurable:!0}),"d");class X extends b{static{c(this,"E")}static{p(this,"BaseHandlerCore")}responseType="json";storage;mediaTransformer;disableTerminationForFinishedUploads;logger;get loggerInstance(){return this.logger}internalErrorResponses={};get errorResponses(){return this.internalErrorResponses}constructor({disableTerminationForFinishedUploads:e,mediaTransformer:t,storage:s}){super(),this.storage=s,this.mediaTransformer=t,this.disableTerminationForFinishedUploads=e,this.logger=this.storage?.logger,this.assembleErrors()}set errorResponses(e){this.assembleErrors(e)}assembleErrors=p((e={})=>{this.internalErrorResponses={...E,...this.internalErrorResponses,...this.storage.errorResponses,...e}},"assembleErrors");parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const n=s[0]?.trim();if(!n)return;const a=n.split("-");if(a.length!==2)return;const[o,u]=a;let d,l;if(o&&u)d=Number.parseInt(o,10),l=Number.parseInt(u,10);else if(o&&!u)d=Number.parseInt(o,10),l=t-1;else if(!o&&u){const m=Number.parseInt(u,10);d=Math.max(0,t-m),l=t-1}else return;if(!(Number.isNaN(d)||Number.isNaN(l)||d>=t||l>=t||d>l))return{end:l,start:d}}buildFileUrlFromString(e,t){const s=new URL(e,"http://localhost"),{pathname:n}=s,a=Object.fromEntries(s.searchParams.entries()),o=y({pathname:`${n}/${t.id}`,query:a});return`${this.storage.config.useRelativeLocation?"":T({url:e})}${o}.${w.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return R.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{X as E,V as T,f as a,Q as b,T as c,B as d,K as g,P as r,G as s,O as u};
@@ -1 +0,0 @@
1
- var E=Object.defineProperty;var u=(h,t)=>E(h,"name",{value:t,configurable:!0});import{H as m,h as b}from"./headers-DC2MEOrK.js";import{ERRORS as g,isUploadError as R}from"./ERRORS-B9jkvKwx.js";import{E as v,T as O}from"./base-handler-core-DaggCVsq.js";import{i as H}from"./validator-DK41xp8N.js";import{waitForStorage as w}from"./waitForStorage-ChSBLhLc.js";var T=Object.defineProperty,x=u((h,t)=>T(h,"name",{value:t,configurable:!0}),"m");class z extends v{static{u(this,"O")}static{x(this,"BaseHandlerFetch")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(t){super(t),this.compose()}get handlers(){return this.registeredHandlers}async fetch(t){this.logger?.debug("[fetch request]: %s %s",t.method,t.url);const e=this.registeredHandlers.get(t.method||"GET");if(!e)return this.createErrorResponse({UploadErrorCode:g.METHOD_NOT_ALLOWED});try{await w(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:g.STORAGE_ERROR})}try{const r=await e.call(this,t);return this.handleFetchResponse(t,r)}catch(r){const s=r instanceof Error?r:new Error(String(r)),o={...O(s,["name",...Object.getOwnPropertyNames(s)]),request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}};return this.listenerCount("error")>0&&this.emit("error",o),this.logger?.error("[fetch error]: %O",o),this.createErrorResponse(s)}}async handleFetchResponse(t,e){if(t.method==="HEAD"||t.method==="OPTIONS"){const{headers:n,statusCode:d}=e;return new Response(void 0,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}if(t.method==="GET"){const{headers:n,statusCode:d}=e;let c="";return e.content!==void 0?c=new Uint8Array(e.content):typeof e=="object"&&"data"in e&&(c=JSON.stringify(e.data)),new Response(c,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}const{headers:r,statusCode:s,...o}=e;if(o.status!==void 0&&this.listenerCount(o.status)>0&&this.emit(o.status,{...o,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),o.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(o,n)}catch(p){throw this.logger?.error("[onComplete error]: %O",p),p}const{headers:d,statusCode:c,...f}=n,{content:j,stream:S,...C}=f;return this.createResponse({body:C,headers:d||r,statusCode:c||s||200})}const y={...r,...e.headers},a=this.convertHeaders({...y,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control",...o.hash===void 0?{}:{[`X-Range-${o.hash?.algorithm.toUpperCase()}`]:o.hash?.value}}),l=e.headers||{};l.Location&&!a.location&&!a.Location?a.location=String(l.Location):l.location&&!a.location&&!a.Location?a.location=String(l.location):r.Location&&!a.location&&!a.Location?a.location=String(r.Location):r.location&&!a.location&&!a.Location&&(a.location=String(r.location));let i;return s>=200&&s<300&&(i=Object.keys(o).length>0?{...o}:{},"content"in i&&delete i.content,"stream"in i&&delete i.stream,Object.keys(i).length===0&&(i={})),this.createResponse({body:i,headers:a,statusCode:s||200})}convertHeaders(t){const e={};for(const[r,s]of Object.entries(t))e[r]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:r={},statusCode:s}=t;let o;return s===204?o=null:typeof e=="string"?o=e:e instanceof Buffer?o=new Uint8Array(e):e&&typeof e=="object"?(o=JSON.stringify(e),r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(o="{}",r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(o,{headers:this.convertHeaders(r),status:s})}async createErrorResponse(t){let e;R(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!H(t)&&!b.isHttpError(t)?e=this.storage.normalizeError(t):e={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(e);let r;return e.body?typeof e.body=="object"&&e.body!==null?r={body:e.body,headers:e.headers,statusCode:e.statusCode}:r={body:{error:{code:e.code||e.name||"Error",message:e.body||e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500}:r={body:{error:{code:e.code||e.name||"Error",message:e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500},this.createResponse(r)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{z as O};
@@ -1 +0,0 @@
1
- var M=Object.defineProperty;var C=(i,e)=>M(i,"name",{value:e,configurable:!0});import{paginate as P}from"@visulima/pagination";import{H as T,h as z,n as y}from"./headers-DC2MEOrK.js";import O from"mime";import{isUploadError as $,ERRORS as m}from"./ERRORS-B9jkvKwx.js";import{match as k}from"path-to-regexp";import{T as S,E as q,s as A,d as U,u as x}from"./base-handler-core-DaggCVsq.js";import{i as D}from"./validator-DK41xp8N.js";import{waitForStorage as _}from"./waitForStorage-ChSBLhLc.js";import{PassThrough as I}from"node:stream";import{e as H}from"./response-builder-Wdo_fvcF.js";var X=Object.defineProperty,G=C((i,e)=>X(i,"name",{value:e,configurable:!0}),"n");const W=k(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),L=G(i=>{const e=W(i);if(!e)return;const{params:t}=e;if(!t.uuid)return;const r={uuid:t.uuid};return t.metadata!==void 0&&(r.metadata=t.metadata),t.path!==void 0&&(r.path=t.path),t.ext!==void 0&&(r.ext=t.ext),{params:r,path:e.path}},"filePathUrlMatcher");var B=Object.defineProperty,v=C((i,e)=>B(i,"name",{value:e,configurable:!0}),"a");const J=v((i,e,t)=>{let r=0,a=0;const o=t-e+1;return new I({highWaterMark:Math.min(64*1024,o),transform(n,h,s){const l=n.length,d=r,p=d+l-1;if(r+=l,p<e){s();return}if(d>t){this.end(),s();return}const u=Math.max(0,e-d),f=Math.min(l,t-d+1);if(u<f){const b=n.subarray(u,f);a+=b.length,this.push(b)||i.pause()}a>=o&&(this.end(),i.destroy()),s()}})},"createRangeLimitedStream"),V=v((i,e,t)=>{let r=!1;const a=v(()=>{r||(r=!0,i.destroy())},"cleanup");e.on("drain",()=>{i.resume()}),e.on("close",a),e.on("finish",a),e.on("error",a),i.on("end",()=>{e.end()}),i.on("error",async o=>{r||(await t(e,o),a())}),i.on("data",o=>{e.write(o)||i.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",a)},"pipeWithBackpressure");v((i,e,t={})=>({headers:t,size:e,stream:i}),"createStreamResponse");var K=Object.defineProperty,w=C((i,e)=>K(i,"name",{value:e,configurable:!0}),"u");const Q=w((i,e,t)=>{const{headers:r,statusCode:a}=i;e(t,{headers:r,statusCode:a})},"handleHeadOptionsRequest"),Y=w((i,e,t,r,a,o,n)=>{e.body=i?.data===void 0?i:i.data;const{headers:h,statusCode:s}=i,l=i;if(l.stream)if(typeof r=="function")r();else{const d=n(e.headers.range,l.size||0);o(t,l.stream,{headers:h,range:d||void 0,size:l.size,statusCode:s})}else{let d="";i.content!==void 0?d=i.content:typeof i=="object"&&"data"in i&&(d=i.data),typeof r=="function"?r():a(t,{body:d,headers:h,statusCode:s})}},"handleGetRequest"),Z=w(async(i,e,t,r,a,o,n)=>{const{headers:h,statusCode:s,...l}=i;if(typeof r=="function")e._body=!0,e.body=l,r();else{const d=i,p=d.headers?{...d.headers}:{};d.headers===void 0&&(d.headers={}),d.statusCode===void 0&&(d.statusCode=200);try{const u=a.onComplete(l,d,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(d.headers||{}).length===0&&Object.keys(p).length>0?d.headers=p:d.headers&&Object.keys(p).length>0&&(d.headers={...p,...d.headers}),n(e,t,d)}},"handleCompletedUpload"),ee=w((i,e,t,r)=>{const{headers:a,statusCode:o,...n}=i,h=a||{},s=h["X-Chunked-Upload"]==="true"||h["x-chunked-upload"]==="true";let l;const d={...H(h),...a?H(a):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};s&&(l=JSON.stringify(n),!d["Content-Type"]&&!d["content-type"]&&(d["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(l=""),r(t,{body:l,headers:d,statusCode:o||200})},"handlePartialUpload"),te=w(async(i,e,t,r,a,o,n)=>{const h=i instanceof Error?i:new Error(String(i)),s={...S(h,["name",...Object.getOwnPropertyNames(h)]),request:S(e,["headers","method","url"])};r("error")>0&&t("error",s),a?.error&&a.error("[error]: %O",s),await o(n,h)},"handleUploadError");var re=Object.defineProperty,R=C((i,e)=>re(i,"name",{value:e,configurable:!0}),"C");const g="Content-Type";class N extends q{static{C(this,"F")}static{R(this,"BaseHandlerNode")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=R(async(e,t)=>this.upload(e,t),"handle");upload=R(async(e,t,r)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const a=this.registeredHandlers.get(e.method);if(!a){await this.sendError(t,{UploadErrorCode:m.METHOD_NOT_ALLOWED});return}try{await _(this.storage)}catch{await this.sendError(t,{UploadErrorCode:m.STORAGE_ERROR});return}try{const o=await a.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))Q(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&Y(n,e,t,r,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:h,...s}=o;this.logger?.debug("[%s]: %s: %d/%d",s.status,s.name,s.bytesWritten,s.size),s.status!==void 0&&this.listenerCount(s.status)>0&&this.emit(s.status,{...s,request:S(e,["headers","method","url"])}),s.status==="completed"?await Z(o,e,t,r,this.storage,this.logger,(l,d,p)=>{this.finish(l,d,p)}):ee(o,e,t,(l,d)=>{this.send(l,{body:d.body,headers:d.headers,statusCode:d.statusCode})})}}catch(o){await te(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}},"upload");send(e,{body:t="",headers:r={},statusCode:a=200}){let o;const n={...r};if(typeof t=="string"){if(o=t,n[g]===void 0)n[g]=T.createContentType({mediaType:"text/plain"});else{const h=Array.isArray(n[g])?n[g].join(", "):String(n[g]);n[g]=T.ensureCharset(h)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[g]||(n[g]=T.createContentType({charset:"utf8",mediaType:"application/json"})));A(e,n),e.statusCode=a,e.end(o)}async sendError(e,t){let r;$(t)?r=this.internalErrorResponses[t.UploadErrorCode]:!D(t)&&!z.isHttpError(t)?r=this.storage.normalizeError(t):r={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(r);let a;r.body?typeof r.body=="object"&&r.body!==null?a={body:r.body,headers:r.headers,statusCode:r.statusCode}:a={body:{error:{code:r.code||r.name||"Error",message:r.body||r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500}:a={body:{error:{code:r.code||r.name||"Error",message:r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500},this.send(e,a)}sendStream(e,t,{headers:r={},range:a,size:o,statusCode:n=200}){A(e,r),e.statusCode=n;let h=t;a&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${a.start}-${a.end}/${o}`),e.setHeader("Content-Length",a.end-a.start+1),e.setHeader("Accept-Ranges","bytes"),h=J(t,a.start,a.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),V(h,e,(s,l)=>this.sendError(s,l))}finish(e,t,r){const a="id"in r&&"headers"in r&&!("body"in r);let o,n,h;if(a){const s=r,l=s.headers||{},d=s.statusCode||200,{headers:p,statusCode:u,...f}=s;o=f,n={...l},h=d}else{const s=r;o=s.body,n=s.headers||{},h=s.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:s,contentType:l}=o;o=s,n={...n,"Content-Type":l}}this.send(t,{body:o||r,headers:n,statusCode:h})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||N.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const r=L(U(e));if(r?.params.uuid){const{ext:a,metadata:o,uuid:n}=r.params,h=a?n.replace(new RegExp(String.raw`\.${a}$`),""):n;if(o==="metadata"&&U(e).endsWith("/metadata"))try{const s=await this.storage.getMeta(h);return{...s,content:JSON.stringify(s),headers:{"Content-Type":T.createContentType({charset:"utf8",mediaType:"application/json"}),...s.expiredAt===void 0?{}:{"X-Upload-Expires":s.expiredAt.toString()},...s.modifiedAt===void 0?{}:{"Last-Modified":s.modifiedAt.toString()}},statusCode:200}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File metadata not found"):s}if(!x.test(h))return this.list(e,t);try{const s=new URL(e.url||"","http://localhost"),l=Object.fromEntries(s.searchParams.entries());if(Object.keys(l).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const c=await this.mediaTransformer.handle(h,l);return{content:c.buffer,headers:{"Content-Length":String(c.size),"Content-Type":`${c.mediaType}/${c.format}`,"X-Media-Type":c.mediaType,"X-Original-Format":c.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":c.format,...c.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":c.originalFile.expiredAt.toString()},...c.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":c.originalFile.modifiedAt.toString()},...c.originalFile?.ETag===void 0?{}:{ETag:c.originalFile.ETag}},statusCode:200}}catch(c){if(c.name==="ValidationError")throw y(400,c.message);this.logger?.warn(`Media transformation failed: ${c.message}`)}const d=await this.storage.getMeta(h);if((e.headers.range||d.size&&d.size>1024*1024)&&this.storage.getStream)try{const c=await this.storage.getStream({id:h});let E=c.headers?.["Content-Type"]||d.contentType;return E.includes("image")&&typeof a=="string"&&(E=O.getType(a)||E),{headers:{...c.headers,"Accept-Ranges":"bytes","Content-Type":E},size:c.size,statusCode:200,stream:c.stream,...d,contentType:E}}catch(c){this.logger?.warn(`Streaming failed, falling back to buffer: ${c}`)}const p=await this.storage.get({id:h});let{contentType:u}=p;u.includes("image")&&typeof a=="string"&&(u=O.getType(a)||u);const{ETag:f,expiredAt:b,modifiedAt:F,size:j}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(j),"Content-Type":u,...b===void 0?{}:{"X-Upload-Expires":b.toString()},...F===void 0?{}:{"Last-Modified":F.toString()},...f===void 0?{}:{ETag:f}},statusCode:200,...p,contentType:u}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File not found"):s}}return this.list(e,t)}async list(e,t){const r=new URL(e.url||"","http://localhost"),a=r.searchParams.get("limit"),o=r.searchParams.get("page"),n=await this.storage.list(Number(a||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&a!==void 0?{data:P(Number(o),Number(a),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const r=L(U(e));if(!r?.params.uuid||!x.test(r.params.uuid))throw y(404,"File not found");const{ext:a,uuid:o}=r.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,y(501,"Streaming download not supported"));return}const h=await this.storage.getStream({id:o});let s=h.headers?.["Content-Type"]||n.contentType;s.includes("image")&&typeof a=="string"&&(s=O.getType(a)||s);const l=this.parseRangeHeader(e.headers.range,h.size||0),d={...h.headers,"Accept-Ranges":"bytes","Content-Disposition":T.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":s};this.sendStream(t,h.stream,{headers:d,range:l||void 0,size:h.size,statusCode:l?206:200})}catch(n){const h=n;if(h.UploadErrorCode===m.FILE_NOT_FOUND||h.UploadErrorCode===m.GONE){await this.sendError(t,y(404,"File not found"));return}await this.sendError(t,n)}}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw y(404,"File not found")}}export{N as F};
@@ -1 +0,0 @@
1
- var C=Object.defineProperty;var n=(s,e)=>C(s,"name",{value:e,configurable:!0});var t=Object.defineProperty,E=n((s,e)=>t(s,"name",{value:e,configurable:!0}),"C");const _=E(s=>{const{accessKeyId:e,accountId:c,jurisdiction:r,secretAccessKey:o}=s??{accessKeyId:process.env.AWS_ACCESS_KEY_ID||process.env.CLOUDFLARE_ACCESS_KEY_ID||process.env.CLOUDFLARE_ACCESS_KEY,accountId:process.env.CLOUDFLARE_ACCOUNT_ID,jurisdiction:process.env.CLOUDFLARE_JURISDICTION||process.env.CLOUDFLARE_R2_JURISDICTION,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||process.env.CLOUDFLARE_SECRET_ACCESS_KEY||process.env.CLOUDFLARE_SECRET_KEY};if(!c||!e||!o)throw new Error("Missing required parameters for Cloudflare R2 client.");return{credentials:{accessKeyId:e,secretAccessKey:o},endpoint:`https://${c}.${r?`${r}.`:""}r2.cloudflarestorage.com`,region:"auto"}},"cloudflare");export{_ as cloudflare,_ as default};
@@ -1 +0,0 @@
1
- import"node:stream";import"node:timers";import"node:util";import{B as u,d as F,a as g}from"./storage-m_Cxgiih.js";import"./path-D7rMc9nq-B718mbm6.js";import"type-is";import"./NoOpMetrics-Dky06sf1.js";import"./cache-qV_5Umeq.js";import"./ERRORS-B9jkvKwx.js";import"./validator-DK41xp8N.js";import"./is-expired-1JuZjDtb.js";export{u as BaseStorage,F as defaultCloudStorageFileNameValidation,g as defaultFilesystemFileNameValidation};
@@ -1 +0,0 @@
1
- var t=Object.defineProperty;var n=(r,e)=>t(r,"name",{value:e,configurable:!0});var a=Object.defineProperty,o=n((r,e)=>a(r,"name",{value:e,configurable:!0}),"n");const S=o(r=>{const{key:e,region:s,secret:c}=r??{key:process.env.AWS_ACCESS_KEY_ID||process.env.SPACES_KEY,region:process.env.AWS_REGION||process.env.SPACES_REGION,secret:process.env.AWS_SECRET_ACCESS_KEY||process.env.SPACES_SECRET};if(!s||!e||!c)throw new Error("Missing required parameters for DigitalOcean Spaces client.");return{credentials:{accessKeyId:e,secretAccessKey:c},endpoint:`https://${s}.digitaloceanspaces.com`,forcePathStyle:!1,region:"us-east-1"}},"digitalOcean");export{S as default};
@@ -1,5 +0,0 @@
1
- var le=Object.defineProperty;var m=(t,e)=>le(t,"name",{value:e,configurable:!0});import{createReadStream as ue,createWriteStream as me}from"node:fs";import{truncate as he,stat as I,copyFile as C}from"node:fs/promises";import{Transform as H,PassThrough as de,pipeline as ye}from"node:stream";import{f as x,l as fe,w as K,U as b,_ as ge,i as pe,O as we,B as be,y as W}from"./local-meta-storage-Bkwqi_gi.js";import{createRequire as P}from"node:module";import{K as w,C as T,M as Q,L as ve,Q as Ee,O as $e}from"./path-D7rMc9nq-B718mbm6.js";import{g as Se}from"./_commonjsHelpers-D6W6KoPK.js";import Oe from"crypto";import Te from"fs";import{o as A,r as ke,d as Fe}from"./part-match-DqD5U7An.js";import{throwErrorCode as p,ERRORS as f,isUploadError as Pe}from"./ERRORS-B9jkvKwx.js";import{createHash as Ne}from"node:crypto";import{B as De,a as _e,t as je}from"./storage-m_Cxgiih.js";import Me from"./File-alcSNpLq.js";import{u as Re}from"./update-size-DANV7aa2.js";import{o as xe}from"./has-content-Bx2p8Okx.js";var Le=Object.defineProperty,ze=m((t,e)=>Le(t,"name",{value:e,configurable:!0}),"i$4"),Ie=Object.defineProperty,X=ze((t,e)=>Ie(t,"name",{value:e,configurable:!0}),"t");const Ce=P(import.meta.url),$=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,We=X(t=>{if(typeof $<"u"&&$.versions&&$.versions.node){const[e,r]=$.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return $.getBuiltinModule(t)}return Ce(t)},"__cjs_getBuiltinModule"),{lstat:Ae,writeFile:Be}=We("node:fs/promises");var Ue=Object.defineProperty,qe=X((t,e)=>Ue(t,"name",{value:e,configurable:!0}),"o");const M=qe(async t=>{x(t);try{const e=await Ae(t);if(!e.isFile())throw new Error(`Ensure path exists, expected 'file', got '${String(fe(e))}'`)}catch(e){if(e.code==="ENOENT"){await K(w(b(t))),await Be(t,new Uint8Array);return}throw e}},"ensureFile");var Ve=Object.defineProperty,Y=m((t,e)=>Ve(t,"name",{value:e,configurable:!0}),"t$2"),He=Object.defineProperty,G=Y((t,e)=>He(t,"name",{value:e,configurable:!0}),"t"),Ke=Object.defineProperty,Qe=G((t,e)=>Ke(t,"name",{value:e,configurable:!0}),"t");let B=class extends Error{static{m(this,"l")}static{Y(this,"c")}static{G(this,"i")}static{Qe(this,"WalkError")}root;constructor(e,r){super(`${e instanceof Error?e.message:String(e)} for path "${r}"`),this.cause=e,this.root=r}get name(){return"WalkError"}set name(e){throw new Error("Cannot overwrite name of WalkError")}};var Xe=Object.defineProperty,Ye=m((t,e)=>Xe(t,"name",{value:e,configurable:!0}),"n"),Ge=Object.defineProperty,J=Ye((t,e)=>Ge(t,"name",{value:e,configurable:!0}),"t"),Je=Object.defineProperty,Ze=J((t,e)=>Je(t,"name",{value:e,configurable:!0}),"g");const U=Ze(t=>{const e=t.replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,String.raw`\.`).replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");return new RegExp(`^${e}$`)},"globToRegExp");var et=Object.defineProperty,tt=J((t,e)=>et(t,"name",{value:e,configurable:!0}),"n");const F=tt((t,e,r,i)=>Array.isArray(e)&&e.length>0&&!e.some(s=>t.endsWith(s))||r&&!r.some(s=>s.test(t))?!1:!i?.some(s=>s.test(t)),"walkInclude");var rt=Object.defineProperty,Z=m((t,e)=>rt(t,"name",{value:e,configurable:!0}),"u$1"),it=Object.defineProperty,L=Z((t,e)=>it(t,"name",{value:e,configurable:!0}),"y");const at=P(import.meta.url),S=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,st=L(t=>{if(typeof S<"u"&&S.versions&&S.versions.node){const[e,r]=S.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return S.getBuiltinModule(t)}return at(t)},"__cjs_getBuiltinModule"),{readdir:nt,realpath:ot,stat:ct}=st("node:fs/promises");var lt=Object.defineProperty,g=L((t,e)=>lt(t,"name",{value:e,configurable:!0}),"r");const ut=g(async t=>{const e=ve(t),r=Ee(e),i=await ct(e);return{isDirectory:g(()=>i.isDirectory(),"isDirectory"),isFile:g(()=>i.isFile(),"isFile"),isSymbolicLink:g(()=>i.isSymbolicLink(),"isSymbolicLink"),name:r,path:e}},"_createWalkEntry");async function*k(t,{extensions:e,followSymlinks:r=!1,includeDirs:i=!0,includeFiles:s=!0,includeSymlinks:n=!0,match:o,maxDepth:h=Number.POSITIVE_INFINITY,skip:d}={}){if(x(t),h<0)return;const a=o?o.map(c=>typeof c=="string"?U(c):c):void 0,l=d?d.map(c=>typeof c=="string"?U(c):c):void 0;if(t=T(b(t)),i&&F(t,e,a,l)&&(yield await ut(t)),!(h<1||!F(t,void 0,void 0,l)))try{const c=await nt(t,{withFileTypes:!0});for(const u of c){let y=Q(t,u.name);if(u.isSymbolicLink())if(r)y=await ot(y);else if(n&&F(y,e,a,l)){yield{isDirectory:g(()=>u.isDirectory(),"isDirectory"),isFile:g(()=>u.isFile(),"isFile"),isSymbolicLink:g(()=>u.isSymbolicLink(),"isSymbolicLink"),name:u.name,path:y};continue}else continue;u.isDirectory()?yield*k(y,{extensions:e,followSymlinks:r,includeDirs:i,includeFiles:s,includeSymlinks:n,match:a,maxDepth:h-1,skip:l}):u.isFile()&&s&&F(y,e,a,l)&&(yield{isDirectory:g(()=>u.isDirectory(),"isDirectory"),isFile:g(()=>u.isFile(),"isFile"),isSymbolicLink:g(()=>u.isSymbolicLink(),"isSymbolicLink"),name:u.name,path:y})}}catch(c){throw c instanceof B?c:new B(c,t)}}m(k,"f$1");Z(k,"D");L(k,"g");g(k,"walk");var mt=Object.defineProperty,ee=m((t,e)=>mt(t,"name",{value:e,configurable:!0}),"t"),ht=Object.defineProperty,z=ee((t,e)=>ht(t,"name",{value:e,configurable:!0}),"t");const dt=P(import.meta.url),O=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,yt=z(t=>{if(typeof O<"u"&&O.versions&&O.versions.node){const[e,r]=O.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return O.getBuiltinModule(t)}return dt(t)},"__cjs_getBuiltinModule"),{accessSync:ft}=yt("node:fs");var gt=Object.defineProperty,pt=z((t,e)=>gt(t,"name",{value:e,configurable:!0}),"o");function N(t,e=ge){x(t),t=b(t);try{return ft(t,e),!0}catch{return!1}}m(N,"i$1");ee(N,"d");z(N,"m");pt(N,"isAccessibleSync");var wt=Object.defineProperty,te=m((t,e)=>wt(t,"name",{value:e,configurable:!0}),"v"),bt=Object.defineProperty,E=te((t,e)=>bt(t,"name",{value:e,configurable:!0}),"i");const vt=P(import.meta.url),v=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,re=E(t=>{if(typeof v<"u"&&v.versions&&v.versions.node){const[e,r]=v.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return v.getBuiltinModule(t)}return vt(t)},"__cjs_getBuiltinModule"),{cwd:D}=v,{mkdir:Et,rename:$t,copyFile:St,unlink:Ot}=re("node:fs/promises"),{mkdirSync:Tt,renameSync:kt,copyFileSync:Ft,unlinkSync:Pt}=re("node:fs");var Nt=Object.defineProperty,ie=E((t,e)=>Nt(t,"name",{value:e,configurable:!0}),"o");class Dt extends Error{static{m(this,"V")}static{te(this,"O")}static{E(this,"a")}static{ie(this,"SameDirectoryError")}constructor(e,r){super(`Source directory "${w(e)}" does not match destination directory "${w(r)}"`),this.name="SameDirectoryError"}}const ae=ie((t,e)=>{if(!t||!e)throw new Error("Source and destination paths must not be empty");if(w(t)!==w(e))throw new Dt(t,e)},"validateSameDirectory");var _t=Object.defineProperty,jt=E((t,e)=>_t(t,"name",{value:e,configurable:!0}),"m$1");const se=jt(async(t,e,{cwd:r,directoryMode:i,overwrite:s,validateDirectory:n})=>{if(r&&(t=T(r,t),e=T(r,e)),n&&ae(t,e),!s&&await pe(e))throw new Error(`The destination file exists: ${e}`);await Et(w(e),{mode:i,recursive:!0});try{await $t(t,e)}catch(o){if(o.code==="EXDEV")await St(t,e),await Ot(t);else throw o}},"internalMoveFile");var Mt=Object.defineProperty,Rt=E((t,e)=>Mt(t,"name",{value:e,configurable:!0}),"m");const ne=Rt((t,e,{cwd:r,directoryMode:i,overwrite:s,validateDirectory:n})=>{if(r&&(t=T(r,t),e=T(r,e)),n&&ae(t,e),!s&&N(e))throw new Error(`The destination file exists: ${e}`);Tt(w(e),{mode:i,recursive:!0});try{kt(t,e)}catch(o){if(o.code==="EXDEV")Ft(t,e),Pt(t);else throw o}},"internalMoveFileSync");var xt=Object.defineProperty,_=E((t,e)=>xt(t,"name",{value:e,configurable:!0}),"i");const Lt=_(async(t,e,r={})=>{const i={overwrite:!0,validateDirectory:!1,...r,cwd:r.cwd?b(r.cwd):D()};await se(t,e,i)},"move");_((t,e,r)=>{const i={overwrite:!0,validateDirectory:!1,...r};i.cwd=i.cwd?b(i.cwd):D(),ne(t,e,i)},"moveSync");_(async(t,e,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):D(),await se(t,e,i)},"rename");_((t,e,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):D(),ne(t,e,i)},"renameSync");var R,q;function zt(){if(q)return R;q=1;var t=Object.defineProperty,e=m((a,l)=>t(a,"name",{value:l,configurable:!0}),"i");/*!
2
- * etag
3
- * Copyright(c) 2014-2016 Douglas Christopher Wilson
4
- * MIT Licensed
5
- */R=o;var r=Oe,i=Te.Stats,s=Object.prototype.toString;function n(a){if(a.length===0)return'"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"';var l=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)+"-"+l+'"'}m(n,"entitytag"),e(n,"entitytag");function o(a,l){if(a==null)throw new TypeError("argument entity is required");var c=h(a),u=l&&typeof l.weak=="boolean"?l.weak:c;if(!c&&typeof a!="string"&&!Buffer.isBuffer(a))throw new TypeError("argument entity must be string, Buffer, or fs.Stats");var y=c?d(a):n(a);return u?"W/"+y:y}m(o,"etag"),e(o,"etag");function h(a){return typeof i=="function"&&a instanceof i?!0:a&&typeof a=="object"&&"ctime"in a&&s.call(a.ctime)==="[object Date]"&&"mtime"in a&&s.call(a.mtime)==="[object Date]"&&"ino"in a&&typeof a.ino=="number"&&"size"in a&&typeof a.size=="number"}m(h,"isstats"),e(h,"isstats");function d(a){var l=a.mtime.getTime().toString(16),c=a.size.toString(16);return'"'+c+"-"+l+'"'}return m(d,"stattag"),e(d,"stattag"),R}m(zt,"requireEtag");var It=zt();const Ct=Se(It);var Wt=Object.defineProperty,oe=m((t,e)=>Wt(t,"name",{value:e,configurable:!0}),"r");class At extends H{static{m(this,"StreamChecksum")}constructor(e,r,i="base64"){super(),this.checksum=e,this.algorithm=r,this.encoding=i,this.hash=Ne(r)}checksum;algorithm;encoding;static{oe(this,"StreamChecksum")}length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(e,r,i){this.push(e),this.hash.update(e),this.length+=e.length,i()}_flush(e){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?e(new Error("Checksum mismatch")):e()}}const Bt=oe((t,e,r="base64")=>e?new At(t,e,r):new de,"streamChecksum");var Ut=Object.defineProperty,qt=m((t,e)=>Ut(t,"name",{value:e,configurable:!0}),"o");class Vt extends H{static{m(this,"m")}constructor(e=Number.POSITIVE_INFINITY){super(),this.limit=e}limit;static{qt(this,"StreamLength")}length=0;_transform(e,r,i){const s=this.length+e.length;this.limit>=s?(this.push(e),this.length=s,i()):i(new Error("Stream length limit exceeded"))}}var Ht=Object.defineProperty,V=m((t,e)=>Ht(t,"name",{value:e,configurable:!0}),"p");class mr extends De{static name="disk";checksumTypes=["md5","sha1"];directory;meta;constructor(e){if(super(e),this.directory=e.directory,e.metaStorage)this.meta=e.metaStorage;else{const r={...e,...e.metaStorageConfig,logger:this.logger};this.meta=new we(r)}e.fileNameValidation||(e.fileNameValidation=_e),this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(r=>{this.logger?.error("Storage access check failed: %O",r)})}normalizeError(e){return super.normalizeError(e)}async create(e){return this.instrumentOperation("create",async()=>{const r={...e};if(e.ttl){const n=typeof e.ttl=="string"?je(e.ttl):e.ttl;n!==void 0&&(r.expiredAt=Date.now()+n)}r.size!==void 0&&Number(r.size)<0&&p(f.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const i=new Me(r);try{const n=await this.getMeta(i.id);if(n.status==="completed")return n}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 s=this.getFilePath(i.name);try{await M(s),i.bytesWritten=0}catch(n){const o=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(o),p(f.FILE_ERROR,o.message)}return i.status=A(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(e){return this.instrumentOperation("write",async()=>{let r;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?r=e:(r=await this.getMeta(e.id),await this.checkIfExpired(r)),r.status==="completed")return r;if(e.size!==void 0&&Re(r,e.size),!ke(e,r))return p(f.FILE_CONFLICT);const i=this.getFilePath(r.name);await this.lock(i);try{const s=e.start||0;if(await M(i),r.bytesWritten===0&&(r.bytesWritten=s),xe(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))return p(f.UNSUPPORTED_CHECKSUM_ALGORITHM);if((e.start===0||e.start===void 0)&&(r.bytesWritten===0||Number.isNaN(r.bytesWritten))&&(!r.contentType||r.contentType==="application/octet-stream"))try{const{fileType:l,stream:c}=await Fe(e.body);l?.mime&&(r.contentType=l.mime),e.body=c}catch{}const n=e.signal,o={...r,...e,body:e.body};n&&(o.signal=n);const[h,d]=await this.lazyWrite(o);if(d)return await he(i,r.bytesWritten),p(d);const a=s+(e.contentLength||0);r.bytesWritten=Math.max(r.bytesWritten||0,a),r.bytesWritten=Math.max(r.bytesWritten||0,h),r.status=A(r),await this.saveMeta(r)}else await M(i),r.bytesWritten=0;return r}catch(s){if(Pe(s))throw s;const n=this.normalizeError(s instanceof Error?s:new Error(String(s)));return await this.onError(n),p(f.FILE_ERROR,(typeof n.message=="string"?n.message:String(s))||String(s))}finally{await this.unlock(i)}})}async get({id:e}){return this.instrumentOperation("get",async()=>{const r=await this.checkIfExpired(await this.meta.get(e)),{bytesWritten:i,contentType:s,expiredAt:n,metadata:o,modifiedAt:h,name:d,originalName:a,size:l}=r;let c;try{c=await be(this.getFilePath(d),{buffer:!0})}catch(u){const y=u;if(y.code==="ENOENT"||y.code==="EPERM"){const j=this.normalizeError(u instanceof Error?u:new Error(y.message||String(u)));return await this.onError(j),p(f.FILE_NOT_FOUND,(typeof j.message=="string"?j.message:String(u))||String(u))}const ce=this.normalizeError(u instanceof Error?u:new Error(String(u)));throw await this.onError(ce),u}return{content:c,contentType:s,ETag:Ct(c),expiredAt:n,id:e,metadata:o,modifiedAt:h,name:d,originalName:a,size:l||i}})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const r=await this.getMeta(e),i=this.getFilePath(r.name);return await I(i),!0}catch{return!1}})}async getStream({id:e}){return this.instrumentOperation("getStream",async()=>{try{const r=await this.checkIfExpired(await this.meta.get(e)),{bytesWritten:i,contentType:s,expiredAt:n,modifiedAt:o,name:h,size:d}=r,a=ue(this.getFilePath(h));return{headers:{"Content-Length":String(d||i),"Content-Type":s,...n&&{"X-Upload-Expires":n.toString()},...o&&{"Last-Modified":o.toString()}},size:d||i,stream:a}}catch(r){const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));throw await this.onError(i),p(f.FILE_NOT_FOUND,(typeof i.message=="string"?i.message:String(r))||String(r))}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{const r=await this.getMeta(e);await W(this.getFilePath(r.name)),await this.deleteMeta(e);const i={...r,status:"deleted"};return await this.onDelete(i),i})}async copy(e,r){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(e);return await C(this.getFilePath(i.name),this.getFilePath(r)),{...i,name:r}})}async move(e,r){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(e),s=this.getFilePath(i.name),n=this.getFilePath(r);try{await Lt(s,n)}catch(o){if(o?.code==="EXDEV")await C(s,n),await W(s);else{const h=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(h),o}}return{...i,id:i.id,name:r}})}async list(){return this.instrumentOperation("list",async()=>{const e={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},r=[],{directory:i}=this;for await(const s of k(i,e)){const{suffix:n}=this.meta,{path:o}=s;if(!o.includes(n)){const{birthtime:h,ctime:d,mtime:a}=await I(o);r.push({createdAt:h||d,id:o.replace(i,""),modifiedAt:a})}}return r})}getFilePath(e){return $e(e)?e:Q(this.directory,e)}lazyWrite(e){return new Promise((r,i)=>{const s=me(this.getFilePath(e.name),{flags:"r+",start:e.start}),n=new Vt(e.contentLength||e.size-e.start),o=Bt(e.checksum,e.checksumAlgorithm),h=!e.checksum,{signal:d}=e,a=V(()=>{s.close(),n.destroy(),o.destroy()},"cleanupStreams"),l=V(c=>{a(),r([Number.NaN,c])},"failWithCode");if(n.on("error",()=>{l(f.FILE_CONFLICT)}),o.on("error",()=>{l(f.CHECKSUM_MISMATCH)}),e.body.on("aborted",()=>{l(h?void 0:f.REQUEST_ABORTED)}),e.body.on("error",c=>{a(),i(c)}),d?.aborted){l(h?void 0:f.REQUEST_ABORTED);return}d&&d.addEventListener("abort",()=>{a(),s.destroy(),n.destroy(),o.destroy(),e.body.destroy(),r([Number.NaN,h?void 0:f.REQUEST_ABORTED])}),ye(e.body,n,o,s,c=>{if(c){if(a(),d?.aborted){r([Number.NaN,h?void 0:f.REQUEST_ABORTED]);return}r([Number.NaN,f.FILE_ERROR]);return}r([e.start+s.bytesWritten])})})}async accessCheck(){await K(this.directory)}}export{Vt as m,mr as q,Bt 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(()=>!0,"shouldRetry")},p=i((e,t,a,o)=>{const r=t*a**e;return Math.min(r,o)},"calculateExponentialBackoff"),D=i(e=>new Promise(t=>{setTimeout(t,e)}),"sleep"),C=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"),h=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)||C(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=>h(t,e),"createRetryWrapper");export{N as createRetryWrapper,C as isRetryableError,h as retry};
@@ -1 +0,0 @@
1
- var t=Object.defineProperty;var o=(s,e)=>t(s,"name",{value:e,configurable:!0});var E=Object.defineProperty,I=o((s,e)=>E(s,"name",{value:e,configurable:!0}),"t");const i=I(s=>{const{accessKeyId:e,endpoint:r,region:c,secretAccessKey:n}=s??{accessKeyId:process.env.AWS_ACCESS_KEY_ID||process.env.MINIO_ACCESS_KEY_ID||process.env.MINIO_ACCESS_KEY,endpoint:process.env.AWS_ENDPOINT||process.env.MINIO_ENDPOINT,region:process.env.AWS_REGION||process.env.MINIO_REGION,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||process.env.MINIO_SECRET_ACCESS_KEY||process.env.MINIO_SECRET_KEY};if(!c||!e||!n||!r)throw new Error("Missing required parameters for Minio client.");return{credentials:{accessKeyId:e,secretAccessKey:n},endpoint:r,forcePathStyle:!0,region:c}},"minio");export{i as default};
@@ -1 +0,0 @@
1
- var u=Object.defineProperty;var d=(s,t)=>u(s,"name",{value:t,configurable:!0});import{n as g}from"./headers-DC2MEOrK.js";var p=Object.defineProperty,b=d((s,t)=>p(s,"name",{value:t,configurable:!0}),"l");class f{static{d(this,"F")}static{b(this,"MultipartBase")}async handlePost(t,i,m){const r={contentType:t.mediaType||"application/octet-stream",metadata:{},originalName:t.filename,size:t.size};for(const e of i)if(!e.isFile&&e.name){let n={};if(e.name==="metadata"&&e.text)try{n=JSON.parse(e.text)}catch{}else e.name&&(n={[e.name]:e.text});Object.assign(r.metadata,n)}const l=await this.storage.create(r),c=this.createStreamFromBytes(t.bytes);await this.storage.write({body:c,contentLength:t.size,id:l.id,start:0});const o=await this.storage.write({body:this.createEmptyStream(),contentLength:0,id:l.id,start:t.size});let a=o;if(Object.keys(r.metadata).length>0){const e={...o.metadata,...r.metadata};a={...await this.storage.update({id:o.id},{metadata:e}),status:o.status}}const h=this.buildFileUrl(m,a);return{...a,headers:{Location:h,...a.expiredAt===void 0?{}:{"X-Upload-Expires":a.expiredAt.toString()},...a.ETag===void 0?{}:{ETag:a.ETag}},statusCode:200}}async handleDelete(t){const i=await this.storage.delete({id:t});if(i.status===void 0)throw g(404,"File not found");return{...i,headers:{},statusCode:204}}get storage(){throw new Error("storage must be implemented")}buildFileUrl(t,i){throw new Error("buildFileUrl must be implemented")}}export{f as F};
@@ -1 +0,0 @@
1
- var v=Object.defineProperty;var i=(e,t)=>v(e,"name",{value:t,configurable:!0});import{PassThrough as z,Transform as F}from"node:stream";import{fileTypeFromBuffer as l}from"file-type";var g=Object.defineProperty,p=i((e,t)=>g(e,"name",{value:t,configurable:!0}),"f");const O=p(async e=>{try{return await l(e)}catch{return}},"detectFileTypeFromBuffer"),W=p(async(e,t)=>{const y=t?.sampleSize??4100;let u;const f=[];let s=0,n=!1,c;const o=new z({highWaterMark:0}),a=new F({objectMode:!1,transform(r,m,T){if(!n&&(f.push(r),s+=r.length,s>=y||s>0)){n=!0;const h=Buffer.concat(f);c=l(h).then(d=>(u=d,d)).catch(()=>{})}T(void 0,r)}});return e.pipe(a).pipe(o),e.on("error",r=>{a.destroy(r),o.destroy(r)}),a.on("error",r=>{o.destroyed||o.destroy(r)}),await Promise.race([new Promise(r=>{if(n){r();return}const m=setTimeout(r,10);a.once("data",()=>{clearTimeout(m),r()}),a.once("end",()=>{clearTimeout(m),r()})}),new Promise(r=>{setTimeout(r,10)})]),c&&await Promise.race([c.then(()=>{}),new Promise(r=>{setTimeout(r,150)})]).catch(()=>{}),{fileType:u,stream:o}},"detectFileTypeFromStream");var P=Object.defineProperty,b=i((e,t)=>P(e,"name",{value:t,configurable:!0}),"t");const k=b(e=>e.bytesWritten===e.size?"completed":e.createdAt?"part":"created","getFileStatus");var w=Object.defineProperty,j=i((e,t)=>w(e,"name",{value:t,configurable:!0}),"i");const x=j((e,t)=>e.size!==void 0&&t.size!==void 0&&e.size>0&&t.size>0&&e.size>t.size?!1:t.size===void 0?!0:(e.start||0)+(e.contentLength||0)<=t.size,"partMatch");export{O as a,W as d,k as o,x as r};
@@ -1 +0,0 @@
1
- var A=Object.defineProperty;var y=(s,t)=>A(s,"name",{value:t,configurable:!0});import{n as d}from"./headers-DC2MEOrK.js";import{hasBody as E}from"type-is";import{a as h}from"./base-handler-core-DaggCVsq.js";import{ERRORS as X}from"./ERRORS-B9jkvKwx.js";import{b,a as z,c as v,d as T}from"./response-builder-Wdo_fvcF.js";var D=Object.defineProperty,f=y((s,t)=>D(s,"name",{value:t,configurable:!0}),"a$1");const L=f((s,t={})=>{const e=h(s,"x-file-metadata",!0);if(!e)return t;try{return{...t,...JSON.parse(e)}}catch{return t}},"parseMetadata"),P=f(s=>{if(!s)return;const t=2e3,e=s.length>t?s.slice(0,Math.max(0,t)):s,r=e.toLowerCase().indexOf("filename");if(r===-1)return;let a=r+8;for(;a<e.length&&(e[a]==="*"||e[a]===" "||e[a]===" ");)a++;if(a>=e.length||e[a]!=="=")return;for(a++;a<e.length&&(e[a]===" "||e[a]===" ");)a++;if(a>=e.length)return;let o=a,n;const i=e[a];return i==='"'||i==="'"?(o=a+1,n=e.indexOf(i,o),n===-1&&(n=e.indexOf(";",o),n===-1&&(n=e.length))):(n=e.indexOf(";",o),n===-1&&(n=e.length)),o>=n?void 0:e.substring(o,n).trim()||void 0},"parseContentDispositionValue"),I=f(s=>{const t=h(s,"content-disposition",!0);return P(t)},"parseContentDisposition"),R=f(s=>{const t=h(s,"x-chunked-upload",!0)==="true",e=h(s,"x-chunk-offset",!0),r=h(s,"x-total-size",!0),a={isChunkedUpload:t};if(e){const o=Number.parseInt(e,10);!Number.isNaN(o)&&o>=0&&(a.chunkOffset=o)}if(r){const o=Number.parseInt(r,10);!Number.isNaN(o)&&o>0&&(a.totalSize=o)}return a},"parseChunkHeaders"),Z=f((s,t=!1)=>{const e=h(s,"x-chunked-upload",!0)==="true";if(!(t&&e)){if(!E(s))throw d(400,"Request body is required");if(Number.parseInt(h(s,"content-length")||"0",10)===0&&!e)throw d(400,"Content-Length is required and must be greater than 0")}},"validateRequestBody"),ee=f((s,t=!1,e)=>{const r=h(s,"x-chunked-upload",!0)==="true",a=Number.parseInt(h(s,"content-length")||"0",10);if(!t&&!r&&a===0)throw d(400,"Content-Length is required and must be greater than 0");if(e!==void 0&&a>e)throw d(413,`File size exceeds maximum allowed size of ${e} bytes`);return a},"validateContentLength"),te=f((s,t,e="application/octet-stream")=>{const r=I(s),a=L(s),{isChunkedUpload:o,totalSize:n}=R(s),i=o&&n?n:t;return o&&n&&(a._chunkedUpload=!0,a._chunks=[],a._totalSize=n),{contentType:e,metadata:a,originalName:r,size:i}},"extractFileInit");f((s,t,e)=>{if(Number.isNaN(s)||s<0)throw d(400,"X-Chunk-Offset must be a valid non-negative number");if(s+t>e)throw d(400,`Chunk exceeds file size. Offset: ${s}, Size: ${t}, Total: ${e}`)},"validateChunk");f((s,t="application/octet-stream")=>h(s,"content-type")||t,"getContentType");var W=Object.defineProperty,g=y((s,t)=>W(s,"name",{value:t,configurable:!0}),"a");const N=g((s,t)=>{if(s.length===0)return!1;const e=[...s].toSorted((o,n)=>o.offset-n.offset),r=e[0];if(r?.offset!==0)return!1;let a=r.length;for(let o=1;o<e.length;o+=1){const n=e[o];if(n){if(n.offset>a)return!1;a=Math.max(a,n.offset+n.length)}}return a>=t},"isUploadComplete"),H=g((s,t,e,r)=>{if(Number.isNaN(s)||s<0)throw new Error("Chunk offset must be a valid non-negative number");if(t<=0)throw new Error("Chunk length must be greater than 0");if(r!==void 0&&t>r)throw new Error(`Chunk size exceeds maximum allowed size of ${r} bytes`);if(s+t>e)throw new Error(`Chunk exceeds file size. Offset: ${s}, Size: ${t}, Total: ${e}`)},"validateChunk"),B=g((s,t)=>{const e=s.find(r=>r.offset===t.offset&&r.length===t.length);return e?t.checksum&&e.checksum!==t.checksum?s.map(r=>r.offset===t.offset?{...r,checksum:t.checksum}:r):s:[...s,t]},"trackChunk"),j=g((s,t)=>{if(s.length===0||t===0)return{bytesWritten:0,percentage:0};const e=[...s].toSorted((n,i)=>n.offset-i.offset);let r=0,a=0;for(const n of e){const i=n.offset+n.length;n.offset<=a?r=Math.max(r,i):r+=n.length,a=Math.max(a,i)}r=Math.min(r,t);const o=t>0?r/t*100:0;return{bytesWritten:r,percentage:o}},"calculateUploadProgress");g(s=>{const t=s.metadata||{};if(t._chunkedUpload===!0&&Array.isArray(t._chunks)){const e=typeof t._totalSize=="number"?t._totalSize:s.size||0;return j(t._chunks,e).bytesWritten}return s.bytesWritten||0},"getBytesWritten");const F=g(s=>(s.metadata||{})._chunkedUpload===!0,"isChunkedUpload"),U=g(s=>{const t=s.metadata||{};if(t._chunkedUpload===!0&&typeof t._totalSize=="number")return t._totalSize},"getTotalSize");var q=Object.defineProperty,$=y((s,t)=>q(s,"name",{value:t,configurable:!0}),"U");class se{static{y(this,"A")}static{$(this,"RestBase")}async deleteSingle(t){const e=await this.storage.delete({id:t});if(e.status===void 0)throw d(404,"File not found");return{...e,headers:{},statusCode:204}}async handlePost(t,e,r,a,o){if(e&&t.size!==void 0){const c=typeof t.size=="number"?t.size:Number.parseInt(String(t.size),10);if(c>0&&c>this.storage.maxUploadSize)throw d(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`)}const n=await this.storage.create(t);if(e){const c=this.buildFileUrl(r,n);return b(n,{...z(n,c),"X-Chunked-Upload":"true","X-Upload-ID":n.id},201)}const i=await this.storage.write({body:a,contentLength:o,id:n.id,start:0}),l=this.buildFileUrl(r,i);return b(i,z(i,l),201)}async handlePut(t,e,r,a,o,n){let i,l=!1;try{await this.storage.getMeta(t),l=!0,n&&await this.storage.update({id:t},{metadata:n}),i=await this.storage.write({body:a,contentLength:o,id:t,start:0})}catch(m){const S=m;if(S.UploadErrorCode===X.FILE_NOT_FOUND||S.code==="ENOENT")try{const C=await this.storage.create(e);i=await this.storage.write({body:a,contentLength:o,id:C.id,start:0})}catch(C){throw C}else throw m}const c=this.buildFileUrl(r,i);return b(i,z(i,c),l?200:201)}async handlePatch(t,e,r,a,o,n){let i=await this.storage.getMeta(t);const l=i.metadata||{},c=F(i);if(c){const u=U(i);u&&i.size!==u&&(i={...i,size:u})}const m=typeof l._totalSize=="number"?l._totalSize:i.size||0;if(!c)throw d(400,"File is not a chunked upload. Use POST or PUT for full file uploads.");const S=100*1024*1024;try{H(e,r,m,S)}catch(u){throw u instanceof Error&&u.message.includes("exceeds maximum")?d(413,u.message):d(400,u instanceof Error?u.message:String(u))}if(i.status==="completed"){const u=this.buildFileUrl(o,i);return b(i,{...z(i,u),"X-Upload-Complete":"true"},200)}const C=Array.isArray(l._chunks)?l._chunks:[],x=B(C,{checksum:a,length:r,offset:e}),O={...l,_chunks:x};await this.storage.update({id:t},{metadata:O});let p=await this.storage.write({body:n,contentLength:r,id:t,start:e}),k=p.bytesWritten>=m;c&&(k=N(x,m),p.status==="completed"&&!k&&(await this.storage.update({id:t},{status:"part"}),p={...p,status:"part"}));const w=k&&p.bytesWritten!==m?{...p,bytesWritten:m}:p,_=this.buildFileUrl(o,w),M={...z(w,_),...v(w,k),"x-upload-offset":String(w.bytesWritten||0)};return b(w,M,k?200:202)}async handleHead(t){let e=await this.storage.getMeta(t);const r=F(e);if(r){const o=U(e);o&&e.size!==o&&(e={...e,size:o})}const a={...T(e)};if(r){const o=e.metadata||{},n=U(e)||e.size||0,i=Array.isArray(o._chunks)?o._chunks:[],l=N(i,n);Object.assign(a,v(e,l))}return b(e,a,200)}handleOptions(t,e){return{headers:{"Access-Control-Allow-Headers":"Authorization, Content-Type, Content-Length, Content-Disposition, X-File-Metadata, X-Chunked-Upload, X-Total-Size, X-Chunk-Offset, X-Chunk-Checksum","Access-Control-Allow-Methods":t.map(r=>r.toUpperCase()).join(", "),"Access-Control-Max-Age":86400,"X-Max-Upload-Size":String(e)},statusCode:204}}async deleteBatch(t){const e=await this.storage.deleteBatch(t);if(e.successfulCount===0&&e.failedCount>0){const r=e.failed.map(a=>a.id).join(", ");throw d(404,`Failed to delete files: ${r}`)}return{data:e.successful,headers:e.failedCount>0?{"X-Delete-Errors":JSON.stringify(e.failed),"X-Delete-Failed":String(e.failedCount),"X-Delete-Successful":String(e.successfulCount)}:{"X-Delete-Successful":String(e.successfulCount)},statusCode:e.successfulCount===t.length?204:207}}get storage(){throw new Error("storage must be implemented")}buildFileUrl(t,e){throw new Error("buildFileUrl must be implemented")}}export{se as A,ee as a,R as b,P as c,te as e,I as p,Z as v};
@@ -1 +0,0 @@
1
- var U=Object.defineProperty;var d=(o,t)=>U(o,"name",{value:t,configurable:!0});import{Readable as y}from"node:stream";import{z as E,B as M,$ as C,t as O}from"./storage-m_Cxgiih.js";import{r as A,d as T,o as f}from"./part-match-DqD5U7An.js";import{throwErrorCode as p,ERRORS as m}from"./ERRORS-B9jkvKwx.js";import{createRetryWrapper as I}from"./isRetryableError-DQNSZiBc.js";import{O as b}from"./local-meta-storage-Bkwqi_gi.js";import{u as z}from"./update-size-DANV7aa2.js";import{o as R}from"./has-content-Bx2p8Okx.js";import{o as x}from"./is-expired-1JuZjDtb.js";var B=Object.defineProperty,v=d((o,t)=>B(o,"name",{value:t,configurable:!0}),"o$1");const L=v((o,t)=>{const e={};return Object.keys(o).forEach(r=>{e[r]=t(o[r])}),e},"mapValues");var N=Object.defineProperty,$=d((o,t)=>N(o,"name",{value:t,configurable:!0}),"t");const K=$(o=>o===Number(o)?o:(E(o)??0)/1e3,"toSeconds");var j=Object.defineProperty,g=d((o,t)=>j(o,"name",{value:t,configurable:!0}),"u");const D=5*1024*1024,F=16*1024*1024;class Z extends M{static{d(this,"S3BaseStorage")}static{g(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"?C(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:g(s=>{const a=s;return a.statusCode&&[408,429,500,502,503,504].includes(a.statusCode)?!0:a.retryable??!1},"shouldRetry"),...t.retryConfig};this.retry=I(e);const{metaStorage:r,metaStorageConfig:n}=t;if(r)this.meta=r;else{const s={...t,...n,logger:this.logger};"directory"in s?(this.logger?.debug("Using local meta storage"),this.meta=new b(s)):this.meta=new b(s)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(s=>{this.logger?.error("Storage access check failed: %O",s)})}async create(t){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const i=typeof t.ttl=="string"?O(t.ttl):t.ttl;i!==void 0&&(e.expiredAt=Date.now()+i)}const r=new(this.getFileClass())(e);r.name=this.namingFunction(r),await this.validate(r);try{const i=await this.getMeta(r.id);if(i.bytesWritten>=0)return i}catch{}const n=this.getS3Api();let s;try{s=await this.retry(()=>n.createMultipartUpload({ACL:this.getAcl(),Bucket:this.bucket,ContentType:r.contentType,Key:r.name,Metadata:L({originalName:r.originalName,...r.metadata},i=>encodeURI(String(i)))}))}catch{return p(m.FILE_ERROR,"s3 create upload error")}const{UploadId:a}=s||{};return a?(r.UploadId=a,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),!A(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(r=>r.Size||0).reduce((r,n)=>r+n,0),await this.lock(t.id);try{if(R(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 y?t.body:y.fromWeb(t.body),{fileType:c,stream:u}=await T(l);c?.mime&&(e.contentType=c.mime),t.body=u}catch{}if(e.Parts.length>this.MAX_PARTS)throw new Error(`Exceeded ${this.MAX_PARTS} as part of the upload to ${this.bucket}.`);const r=e.Parts.length+1,n=this.getS3Api(),s=e.UploadId;if(!s)throw new Error("UploadId is required");const{ETag:a}=await this.retry(()=>n.uploadPart({Body:t.body,Bucket:this.bucket,ContentLength:t.contentLength||0,Key:e.name,PartNumber:r,UploadId:s,...t.checksumAlgorithm==="md5"?{ContentMD5:t.checksum}:{}})),i={ETag:a,PartNumber:r,Size:t.contentLength};e.Parts=[...e.Parts,i],e.bytesWritten+=t.contentLength||0}if(this.cache.set(e.id,e),e.status=f(e),e.status==="completed"){const[r]=await this.internalOnComplete(e);delete e.Parts,e.uri=r.Location,e.ETag=r.ETag}}finally{await this.unlock(t.id)}return e})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await Promise.all([this.deleteMeta(e.id),this.retry(()=>this.abortMultipartUpload(e))]);const r={...e};return await this.onDelete(r),r})}async copy(t,e,r){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(t),s=`${this.bucket}/${t}`;let a=this.bucket,i=e;if(e.startsWith("/")){const[,c,...u]=e.split("/");a=c||this.bucket,i=u.join("/")}const l=this.getS3Api();return await this.retry(()=>l.copyObject({Bucket:a,CopySource:s,Key:i,...r?.storageClass&&{StorageClass:r.storageClass}})),{...n,id:i,name:i}})}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();let r={Bucket:this.bucket,MaxKeys:t};const n=[];let s=!0;for(;s;)try{const a=await this.retry(()=>e.listObjectsV2(r));for(const{Key:i,LastModified:l}of a?.Contents||[])if(i!==void 0){const{Expires:c}=await this.retry(()=>e.headObject({Bucket:this.bucket,Key:i}));c&&x({expiredAt:c})?await this.delete({id:i}):n.push({id:i,...l&&{createdAt:l}})}s=a.IsTruncated||!1,s&&a.NextContinuationToken&&(r={...r,ContinuationToken:a.NextContinuationToken})}catch(a){const i=this.normalizeError(a instanceof Error?a:new Error(String(a)));throw await this.onError(i),a}return n},{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:n,ContentType:s,ETag:a,Expires:i,LastModified:l,Metadata:c}=await this.retry(()=>e.getObject({Bucket:this.bucket,Key:t}));await this.checkIfExpired({expiredAt:i});const u=[];if(r)if(r instanceof y)for await(const h of r)u.push(h instanceof Uint8Array?h:new Uint8Array(h));else{const h=r.getReader();for(;;){const{done:k,value:P}=await h.read();if(k)break;u.push(P)}}const{originalName:w,...S}=c||{};return{content:Buffer.concat(u),contentType:s,ETag:a,expiredAt:i,id:t,metadata:S,modifiedAt:l,name:t,originalName:w||t,size:Number(n)}})}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,n)=>r+n,0),t.status=f(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,n=[],s=Math.trunc(K(this.config.expiration?.maxAge||"6hrs")),a=this.getS3Api();for(let i=0;i<r;i++)n.push(a.getPresignedUrl({Bucket:this.bucket,expiresIn:s,Key:t.name,PartNumber:i+1,UploadId:e}));return Promise.all(n)}async getParts(t){const e=this.getS3Api(),r=t.UploadId;if(!r)throw new Error("UploadId is required");const{Parts:n=[]}=await this.retry(()=>e.listParts({Bucket:this.bucket,Key:t.name,UploadId:r}));return n}completeMultipartUpload(t){const e=this.getS3Api(),r=t.UploadId;if(!r)throw new Error("UploadId is required");const n=t.Parts?.map(({ETag:s,PartNumber:a})=>{if(!s||!a)throw new Error("ETag and PartNumber are required");return{ETag:s,PartNumber:a}})||[];return this.retry(()=>e.completeMultipartUpload({Bucket:this.bucket,Key:t.name,Parts:n,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=g(async t=>{const[e]=await Promise.all([this.completeMultipartUpload(t),this.deleteMeta(t.id)]);return[e,t]},"internalOnComplete")}export{Z as S};
@@ -1 +0,0 @@
1
- var Z=Object.defineProperty;var y=(t,e)=>Z(t,"name",{value:e,configurable:!0});import{Readable as q}from"node:stream";import{setInterval as W}from"node:timers";import{inspect as X}from"node:util";import{L as H,O as j}from"./path-D7rMc9nq-B718mbm6.js";import J from"type-is";import Q from"./NoOpMetrics-Dky06sf1.js";import{N as ee}from"./cache-qV_5Umeq.js";import{ErrorMap as T,throwErrorCode as M,ERRORS as N}from"./ERRORS-B9jkvKwx.js";import{LRUCache as te}from"lru-cache";import{V as re}from"./validator-DK41xp8N.js";import{o as oe}from"./is-expired-1JuZjDtb.js";var se=Object.defineProperty,ae=y((t,e)=>se(t,"name",{value:e,configurable:!0}),"y$2"),ie=Object.defineProperty,ne=ae((t,e)=>ie(t,"name",{value:e,configurable:!0}),"y"),ce=Object.defineProperty,O=ne((t,e)=>ce(t,"name",{value:e,configurable:!0}),"i");const le=/^(?<value>-?\d+(?:[.,]\d+)*) *(?<type>[a-z]+)?$/i,ue=/^KIBI/,me=/^MIBI/,ge=/^GIBI/,pe=/^TEBI/,he=/^PEBI/,de=/^EXBI/,fe=/^ZEBI/,ye=/^YIBI/,be=/^(.)IB$/,U={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"}]},we=O((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"),_=O(t=>{switch(t){case 2:return 1024;case 10:return 1e3;default:throw new Error("Unsupported base.")}},"fromBase"),D=O((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=le.exec(t)?.groups;if(!o)return Number.NaN;const i=we(o.value,r.locale),a=(o.type??"Bytes").toUpperCase().replace(ue,"KILO").replace(me,"MEGA").replace(ge,"GIGA").replace(pe,"TERA").replace(he,"PETA").replace(de,"EXA").replace(fe,"ZETTA").replace(ye,"YOTTA").replace(be,"$1B"),n=U[r.units].findIndex(c=>c.short[0].toUpperCase()===a[0]),l=_(r.base);return i*l**n},"parseBytes");O((t,e)=>{if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("Bytesize is not a number.");const{base:r,decimals:o,locale:i,long:a,unit:n,units:l,...c}={base:2,decimals:0,locale:"en-US",long:!1,units:"metric",...e},s=_(r),m=Math.abs(t),u=e?.space??!0?" ":"",g=U[l],p=g.findIndex(w=>w.short===n);if(t===0){const w=Math.min(0,Math.max(p,g.length-1));return"0"+u+g[w][a?"long":"short"]}const f=p===-1?Math.min(Math.floor(Math.log(m)/Math.log(s)),g.length-1):p,$=g[f][a?"long":"short"],x=t/s**f,v=o<0?void 0:o;return new Intl.NumberFormat(i,{maximumFractionDigits:v,minimumFractionDigits:v,...c}).format(x)+u+$},"formatBytes");var ve=Object.defineProperty,Ee=y((t,e)=>ve(t,"name",{value:e,configurable:!0}),"u$1"),$e=Object.defineProperty,xe=Ee((t,e)=>$e(t,"name",{value:e,configurable:!0}),"v"),Me=Object.defineProperty,Ne=xe((t,e)=>Me(t,"name",{value:e,configurable:!0}),"D");const Se=Ne((t,e,r,o,i,a,n,l,c,s,m,u,g,p)=>{const f={d:o,h:i,m:a,mo:e,ms:l,s:n,w:r,y:t};return c!==void 0&&(f.future=c),s!==void 0&&(f.past=s),m!==void 0&&(f.decimal=m),u!==void 0&&(f.unitMap=u),g!==void 0&&(f.groupSeparator=g),p!==void 0&&(f.placeholderSeparator=p),f},"createDurationLanguage"),k={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"},Be=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",".",k,",","_");var Oe=Object.defineProperty,Te=y((t,e)=>Oe(t,"name",{value:e,configurable:!0}),"o$1"),Pe=Object.defineProperty,Ce=Te((t,e)=>Pe(t,"name",{value:e,configurable:!0}),"o"),Ae=Object.defineProperty,Ie=Ce((t,e)=>Ae(t,"name",{value:e,configurable:!0}),"o");const ze=Ie(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 De=Object.defineProperty,Fe=y((t,e)=>De(t,"name",{value:e,configurable:!0}),"w"),je=Object.defineProperty,Ue=Fe((t,e)=>je(t,"name",{value:e,configurable:!0}),"S"),_e=Object.defineProperty,ke=Ue((t,e)=>_e(t,"name",{value:e,configurable:!0}),"h");const F={d:864e5,h:36e5,m:6e4,mo:2629746e3,ms:1,s:1e3,w:6048e5,y:31556952e3},S=/[-/\\^$*+?.()|[\]{}]/g,Re=/^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/i,Le=/^(?:(\d+):)?(?:(\d+):)?(\d+)$/,Ge=/^[+-]?\d+(?:\.\d+)?$/,Ve=/^[-+]/,Ye=ke((t,e)=>{if(typeof t!="string"||t.length===0)return;const{defaultUnit:r="ms",language:o=Be}=e??{};ze(o);const i=o.decimal??".",a=o.groupSeparator??",",n=o.placeholderSeparator??"_",l=i.replaceAll(S,String.raw`\$&`),c=a.replaceAll(S,String.raw`\$&`),s=n.replaceAll(S,String.raw`\$&`),m=o.unitMap??k;let u=t.replaceAll(new RegExp(String.raw`(\d)[${s}${c}](\d)`,"g"),"$1$2");if(i!=="."&&(u=u.replace(l,".")),Ge.test(t)){const h=Number.parseFloat(u.trim());if(!Number.isNaN(h)){const d=m[r];if(d!==void 0)return h*F[d]}return}const g=Re.exec(t);if(g){const h=Number.parseInt(g[1]??"0",10),d=Number.parseInt(g[2]??"0",10),E=Number.parseInt(g[3]??"0",10);return h*36e5+d*6e4+E*1e3}const p=Le.exec(t);if(p){let h=0,d=0;p[2]!==void 0?(h=Number.parseInt(p[1]??"0",10),d=Number.parseInt(p[2],10)):p[1]!==void 0&&(d=Number.parseInt(p[1],10));const E=Number.parseInt(p[3]??"0",10);return h*36e5+d*6e4+E*1e3}const f=Object.keys(m).toSorted((h,d)=>d.length-h.length).map(h=>h.replaceAll(S,String.raw`\$&`)).join("|"),$=new RegExp(String.raw`(-?\d*\.?\d+)\s*(${f})`,"gi");let x=0,v,w=!1,C=-1,A=0;for($.lastIndex=0;(v=$.exec(u))!==null;){w||(C=v.index),w=!0;const h=v[1],d=v[2];if(!h||!d)continue;const E=h.trim(),V=E.startsWith("-")?-1:1,Y=E.replace(Ve,""),I=Number.parseFloat(Y),z=m[d.toLowerCase()];if(z===void 0)continue;const K=F[z];if(Number.isNaN(I))return;x+=V*I*K,A=$.lastIndex}const L=u.slice(0,C).trim(),G=u.slice(A).trim();if(!(w&&(L.length>0||G.length>0))&&w)return x},"parseDuration");var Ke=Object.defineProperty,Ze=y((t,e)=>Ke(t,"name",{value:e,configurable:!0}),"e");const B=Ze(t=>{if(t===Number(t))return t;if(!t)return;const e=Ye(t);if(e!==void 0)return e},"toMilliseconds");var qe=Object.defineProperty,We=y((t,e)=>qe(t,"name",{value:e,configurable:!0}),"r");class Xe extends te{static{y(this,"o")}static{We(this,"Locker")}constructor(e){super({ttl:1e3,ttlAutopurge:!0,...e})}lock(e){if(this.get(e))throw new Error(`${e} is locked`);return this.set(e,e),e}unlock(e){this.delete(e)}}var He=Object.defineProperty,P=y((t,e)=>He(t,"name",{value:e,configurable:!0}),"i");const Je=P(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=P((t,e)=>{const r={...t};return Object.keys(e).forEach(o=>{const i=e[o];if(i!==null&&typeof i=="object"&&!Array.isArray(i)){const a=r[o],n=a&&typeof a=="object"&&!Array.isArray(a)?a:{};r[o]=R(n,i)}else r[o]=i}),r},"deepMerge"),Qe=P((t,e)=>{const r=R(t,e);Object.assign(t,r),t.originalName=Je(t.metadata)||t.originalName},"updateMetadata");var et=Object.defineProperty,b=y((t,e)=>et(t,"name",{value:e,configurable:!0}),"g");const tt={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:{}},rt=b(t=>!t||t.length<3||t.length>255||j(t)?!1:!(t.toUpperCase().includes("../")||t.includes("\0")),"defaultCloudStorageFileNameValidation"),dt=b(t=>{if(!t||t.length<3||t.length>255||j(t))return!1;const e=t.toUpperCase();return!['"',"*",":","<",">","?","\\","|","../","\0"].some(r=>e.includes(r))},"defaultFilesystemFileNameValidation");class ft{static{y(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 re;assetFolder=void 0;concurrency;constructor(e){const r={...tt,...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"?D(r.maxUploadSize):r.maxUploadSize,this.maxMetadataSize=typeof r.maxMetadataSize=="string"?D(r.maxMetadataSize):r.maxMetadataSize,this.expiration=r.expiration,this.genericConfig=r,r.assetFolder!==void 0&&(this.assetFolder=H(r.assetFolder)),this.locker=new Xe({max:1e3,ttl:3e4,ttlAutopurge:!0}),this.cache=r.cache??new ee,this.logger=r.logger,this.metrics=r.metrics??new Q,this.logger?.debug(`${this.constructor.name} config: ${X({...e,logger:this.logger.constructor})}`);const o=B(r.expiration?.purgeInterval);o&&this.startAutoPurge(o);const i={isValid(c){if(c.size===void 0)return!0;const s=c.size;if(s==null)return!1;const m=typeof s=="number"?s:Number(s);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:T.RequestEntityTooLarge,value:this.maxUploadSize},a={isValid(c){return!!J.is(c.contentType,this.value)},response:T.UnsupportedMediaType,value:r.allowMIME},n=r.fileNameValidation??rt,l={isValid(c){return n(c.name)},response:T.InvalidFileName};this.validation.add({filename:l,mime:a,size:i}),this.validation.add({...r.validation})}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 this.updateTimestamps(e),this.cache.set(e.id,e),this.meta.save(e.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),M(N.FILE_NOT_FOUND)}}async checkIfExpired(e){return oe(e)?(this.delete(e).catch(()=>{}),this.deleteMeta(e.id).catch(()=>{}),M(N.GONE)):e}async purge(e){return this.instrumentOperation("purge",async()=>{const r=B(e||this.expiration?.maxAge),o={items:[],maxAgeMs:r};if(r){const i=Date.now()-r,a=(await this.list()).filter(n=>Number(new Date(this.expiration?.rolling&&n.modifiedAt||n.createdAt))<i);for await(const{id:n,...l}of a)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=q.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),i={...r};if("ttl"in i&&i.ttl!==void 0){const n=i.ttl,l=typeof n=="string"?B(n):n;l!==void 0&&(i.expiredAt=Date.now()+l),delete i.ttl}Qe(o,i),await this.saveMeta(o);const a={...o,status:"updated"};return await this.onUpdate(a),a})}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 i=[],a=[],n=e.map(async s=>{try{return{file:await this.delete({id:s}),id:s,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:s,success:!1}}}),l=await Promise.allSettled(n);for(const s of l)s.status==="fulfilled"?s.value.success?i.push(s.value.file):a.push({error:s.value.error,id:s.value.id}):a.push({error:s.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",i.length,{storage:o}),this.metrics.gauge("storage.operations.batch.delete.failed_count",a.length,{storage:o}),{failed:a,failedCount:a.length,successful:i,successfulCount:i.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 i=[],a=[],n=e.map(async({destination:s,options:m,source:u})=>{try{return{file:await this.copy(u,s,m),id:s,success:!0}}catch(g){const p=g instanceof Error?g.message:"Copy failed";return this.metrics.increment("storage.operations.copy.error.count",1,{error:p,storage:o}),{error:p,id:s,success:!1}}}),l=await Promise.allSettled(n);for(const s of l)s.status==="fulfilled"?s.value.success&&s.value.file?i.push(s.value.file):a.push({error:s.value.error||"Copy failed",id:s.value.id}):a.push({error:s.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",i.length,{storage:o}),this.metrics.gauge("storage.operations.batch.copy.failed_count",a.length,{storage:o}),{failed:a,failedCount:a.length,successful:i,successfulCount:i.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 i=[],a=[],n=e.map(async({destination:s,source:m})=>{try{return{file:await this.move(m,s),id:s,success:!0}}catch(u){const g=u instanceof Error?u.message:"Move failed";return this.metrics.increment("storage.operations.move.error.count",1,{error:g,storage:o}),{error:g,id:s,success:!1}}}),l=await Promise.allSettled(n);for(const s of l)s.status==="fulfilled"?s.value.success&&s.value.file?i.push(s.value.file):a.push({error:s.value.error||"Move failed",id:s.value.id}):a.push({error:s.reason?.message||"Move failed",id:s.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",i.length,{storage:o}),this.metrics.gauge("storage.operations.batch.move.failed_count",a.length,{storage:o}),{failed:a,failedCount:a.length,successful:i,successfulCount:i.length}}async lock(e){const r=[...this.locker.keys()];return r.includes(e)?M(N.FILE_LOCKED):this.config.concurrency&&typeof this.config.concurrency=="number"&&this.config.concurrency<r.length?M(N.STORAGE_BUSY):(this.locker.set(e,e),e)}async unlock(e){this.locker.unlock(e)}isUnsupportedChecksum(e=""){return!!e&&!this.checksumTypes.includes(e)}startAutoPurge(e){if(e>=2147483647)throw new Error("“purgeInterval” must be less than 2147483647 ms");W(()=>{this.purge().catch(r=>this.logger?.error(r))},e)}updateTimestamps(e){e.createdAt??=new Date().toISOString();const r=B(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 i=Date.now(),a={storage:this.constructor.name.toLowerCase().replace("storage",""),...o};try{this.metrics.increment(`storage.operations.${e}.count`,1,a);const n=await r(),l=Date.now()-i;return this.metrics.timing(`storage.operations.${e}.duration`,l,a),n&&typeof n=="object"&&"size"in n&&typeof n.size=="number"&&this.metrics.gauge("storage.files.size",n.size,{...a,operation:e}),n}catch(n){const l=Date.now()-i,c=n instanceof Error?n.message:"Unknown error";throw this.metrics.timing(`storage.operations.${e}.duration`,l,{...a,error:"true"}),this.metrics.increment(`storage.operations.${e}.error.count`,1,{...a,error:c}),n}}}export{D as $,ft as B,dt as a,rt as d,B as t,Qe as u,Ye as z};
@@ -1 +0,0 @@
1
- var n=Object.defineProperty;var c=(s,e)=>n(s,"name",{value:e,configurable:!0});var o=Object.defineProperty,S=c((s,e)=>o(s,"name",{value:e,configurable:!0}),"t");const a=S(s=>{const{accessKeyId:e,endpoint:t,secretAccessKey:r}=s??{accessKeyId:process.env.AWS_ACCESS_KEY_ID||process.env.TIGRIS_ACCESS_KEY_ID||process.env.TIGRIS_ACCESS_KEY,endpoint:process.env.TIGRIS_ENDPOINT,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||process.env.TIGRIS_SECRET_ACCESS_KEY||process.env.TIGRIS_SECRET_KEY};if(!e||!r)throw new Error("Missing required parameters for Tigris client.");return{credentials:{accessKeyId:e,secretAccessKey:r},endpoint:t??"https://t3.storage.dev",forcePathStyle:!1,region:"auto"}},"tigris");export{a as default};
@@ -1 +0,0 @@
1
- var p=Object.defineProperty;var e=(r,t)=>p(r,"name",{value:t,configurable:!0});import{ErrorMap as d}from"./ERRORS-B9jkvKwx.js";var u=Object.defineProperty,y=e((r,t)=>u(r,"name",{value:t,configurable:!0}),"t");let V=class extends Error{static{e(this,"d")}static{y(this,"ValidationError")}code;statusCode;body;headers;name="ValidationError";constructor(t,a,i,s){const n=typeof i=="string"?i:i?.message||"Validation error";super(n),this.code=t,this.statusCode=a,this.body=i,this.headers=s}};var v=Object.defineProperty,o=e((r,t)=>v(r,"name",{value:t,configurable:!0}),"e");const E=o(r=>r&&r[0].toUpperCase()+r.slice(1),"capitalize"),b=o(r=>{if(!Array.isArray(r))return r;const[t,a,i]=r;return{body:a,headers:i,statusCode:t}},"toResponse");class x{static{e(this,"Validator")}constructor(t="ValidationError"){this.prefix=t}prefix;static{o(this,"Validator")}validators={};add(t){Object.entries(t).forEach(([a,i])=>{const s=`${this.prefix}${E(a)}`;if(this.validators[s]={...this.validators[s],...i},typeof this.validators[s].isValid!="function")throw new TypeError('Validation config "isValid" is missing, or it is not a function!')})}async verify(t){for(const[a,i]of Object.entries(this.validators))if(!await i.isValid(t)){const s=i.response||(a in d?d[a]:d.UnknownError),n=b(s),{body:c,headers:l,message:f,statusCode:h}=n;throw new V(a,h,c||f,l)}}}const C=o(r=>r.name==="ValidationError","isValidationError");export{x as V,V as d,C as i};
@@ -1 +0,0 @@
1
- var o=Object.defineProperty;var n=(s,e)=>o(s,"name",{value:e,configurable:!0});var A=Object.defineProperty,S=n((s,e)=>A(s,"name",{value:e,configurable:!0}),"n");const E=S(s=>{const{accessKeyId:e,region:r,secretAccessKey:c}=s??{accessKeyId:process.env.AWS_ACCESS_KEY_ID||process.env.WASABI_ACCESS_KEY_ID||process.env.WASABI_ACCESS_KEY,region:process.env.AWS_REGION||process.env.WASABI_REGION,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||process.env.WASABI_SECRET_ACCESS_KEY||process.env.WASABI_SECRET_KEY};if(!r||!e||!c)throw new Error("Missing required parameters for Wasabi client.");return{apiVersion:"2006-03-01",credentials:{accessKeyId:e,secretAccessKey:c},endpoint:`https://s3.${r}.wasabisys.com`,region:r}},"wasabi");export{E as default};