@visulima/storage 1.0.9 → 1.0.11

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 (174) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/adapter/nuxt/module.d.ts +9 -8
  3. package/dist/ai/ai-sdk/index.d.ts +52 -59
  4. package/dist/ai/claude/index.d.ts +105 -119
  5. package/dist/ai/openai/index.d.ts +87 -99
  6. package/dist/ai/tanstack/index.d.ts +54 -61
  7. package/dist/handler/http/fetch/index.d.ts +202 -201
  8. package/dist/handler/http/fetch/index.js +1 -1
  9. package/dist/handler/http/hono/index.d.ts +60 -59
  10. package/dist/handler/http/hono/index.js +1 -1
  11. package/dist/handler/http/nextjs/index.d.ts +55 -54
  12. package/dist/handler/http/nextjs/index.js +1 -1
  13. package/dist/handler/http/node/index.d.ts +234 -246
  14. package/dist/handler/http/node/index.js +1 -1
  15. package/dist/handler/http/solid-start/index.d.ts +55 -54
  16. package/dist/handler/http/solid-start/index.js +1 -1
  17. package/dist/index.d.ts +71 -70
  18. package/dist/index.js +1 -1
  19. package/dist/packem_shared/{AbstractBaseStorage-CiPEMcuo.js → AbstractBaseStorage-CLsYmMZg.js} +1 -1
  20. package/dist/packem_shared/AwsLightStorage-DGSPFUqr.js +1 -0
  21. package/dist/packem_shared/AzureStorage-DvKk_hhz.js +1 -0
  22. package/dist/packem_shared/BoxMetaStorage-CJsyeQ63.js +1 -0
  23. package/dist/packem_shared/{BoxStorage-DbGqBLux.js → BoxStorage-CmM95wi2.js} +1 -1
  24. package/dist/packem_shared/BunS3MetaStorage-CJsyeQ63.js +1 -0
  25. package/dist/packem_shared/{BunS3Storage-DNvimm9e.js → BunS3Storage-B_roVJ29.js} +1 -1
  26. package/dist/packem_shared/BunnyMetaStorage-CJsyeQ63.js +1 -0
  27. package/dist/packem_shared/{BunnyStorage-C7d0opLL.js → BunnyStorage-eZ1QDVaY.js} +1 -1
  28. package/dist/packem_shared/CloudinaryMetaStorage-Bv_YCZ0Q.js +1 -0
  29. package/dist/packem_shared/{CloudinaryStorage-Dc3XA2lP.js → CloudinaryStorage-CpH2f0Fv.js} +1 -1
  30. package/dist/packem_shared/DiskStorage-DzjjqCzo.js +1 -0
  31. package/dist/packem_shared/{DiskStorageWithChecksum-vFCubS6K.js → DiskStorageWithChecksum-MZkDEyts.js} +1 -1
  32. package/dist/packem_shared/DropboxMetaStorage-CJsyeQ63.js +1 -0
  33. package/dist/packem_shared/{DropboxStorage-CY9Ggu3m.js → DropboxStorage-BB9NoWK2.js} +1 -1
  34. package/dist/packem_shared/{Files-CpIcMjP0.js → Files-DyMJ9FPN.js} +1 -1
  35. package/dist/packem_shared/FirebaseMetaStorage-Bv_YCZ0Q.js +1 -0
  36. package/dist/packem_shared/{FirebaseStorage-D6O9CJXN.js → FirebaseStorage-BgbxzYNC.js} +1 -1
  37. package/dist/packem_shared/FtpMetaStorage-CJsyeQ63.js +1 -0
  38. package/dist/packem_shared/{FtpStorage-DbEjbq8z.js → FtpStorage-CNqXDz7P.js} +1 -1
  39. package/dist/packem_shared/{GCSMetaStorage-DT8K6zdm.js → GCSMetaStorage-gEhWlpfS.js} +1 -1
  40. package/dist/packem_shared/{GCStorage-6BHkFlEs.js → GCStorage-CRd5vjok.js} +1 -1
  41. package/dist/packem_shared/GoogleDriveMetaStorage-B0gLF7Io.js +1 -0
  42. package/dist/packem_shared/{GoogleDriveStorage-Bklsz7Bh.js → GoogleDriveStorage-Du7uBhSm.js} +1 -1
  43. package/dist/packem_shared/{LocalMetaStorage-BhicZnNl.js → LocalMetaStorage-CcGfFG39.js} +1 -1
  44. package/dist/packem_shared/{MemoryStorage-9gbWd09l.js → MemoryStorage-ChKyI6OY.js} +1 -1
  45. package/dist/packem_shared/{Multipart-D0ok6BBy.js → Multipart-C35TR2qL.js} +1 -1
  46. package/dist/packem_shared/{Multipart-CQjYqU--.js → Multipart-V64Bg5dt.js} +1 -1
  47. package/dist/packem_shared/NetlifyBlobMetaStorage-Bv_YCZ0Q.js +1 -0
  48. package/dist/packem_shared/NetlifyBlobStorage-CZsr_0DF.js +1 -0
  49. package/dist/packem_shared/OneDriveMetaStorage-B0gLF7Io.js +1 -0
  50. package/dist/packem_shared/{OneDriveStorage-CP6MvGAa.js → OneDriveStorage-B8qFgMq1.js} +1 -1
  51. package/dist/packem_shared/PocketBaseMetaStorage-Cm3v8g1-.js +1 -0
  52. package/dist/packem_shared/{PocketBaseStorage-2qhbI2PW.js → PocketBaseStorage-D2vMN-oY.js} +1 -1
  53. package/dist/packem_shared/{Rest-CI_BiZPv.js → Rest-B7g1sgkq.js} +1 -1
  54. package/dist/packem_shared/{Rest-DvfN4-kf.js → Rest-BrEMYgxZ.js} +1 -1
  55. package/dist/packem_shared/{S3Storage-YGeNk3Tt.js → S3Storage-CTe_BMDl.js} +1 -1
  56. package/dist/packem_shared/SftpMetaStorage-CJsyeQ63.js +1 -0
  57. package/dist/packem_shared/{SftpStorage-2Hz396Xr.js → SftpStorage-BKeAzuej.js} +1 -1
  58. package/dist/packem_shared/SharePointMetaStorage-CJsyeQ63.js +1 -0
  59. package/dist/packem_shared/{SharePointStorage-CrX2Pk6C.js → SharePointStorage-Dtnt5-wk.js} +1 -1
  60. package/dist/packem_shared/SupabaseMetaStorage-B0gLF7Io.js +1 -0
  61. package/dist/packem_shared/{SupabaseStorage-Dc_DBX29.js → SupabaseStorage-CmGQjqXf.js} +1 -1
  62. package/dist/packem_shared/{Tus-BlBZykIL.js → Tus-CJBgnJrn.js} +1 -1
  63. package/dist/packem_shared/{Tus-BBVt2ky3.js → Tus-D9c7KDnl.js} +1 -1
  64. package/dist/packem_shared/UploadThingMetaStorage-Bv_YCZ0Q.js +1 -0
  65. package/dist/packem_shared/{UploadThingStorage-BChykYSe.js → UploadThingStorage-DZ4zNvDH.js} +1 -1
  66. package/dist/packem_shared/VercelBlobMetaStorage-CJsyeQ63.js +1 -0
  67. package/dist/packem_shared/{VercelBlobStorage-CsRyPfw3.js → VercelBlobStorage-DDNEofR3.js} +1 -1
  68. package/dist/packem_shared/{approval.d-CMAYH9GF.d.ts → approval.d-C-d-t94D.d.ts} +6 -6
  69. package/dist/packem_shared/{base-handler-core-D-9Ku1h-.js → base-handler-core-BJP9jHCE.js} +1 -1
  70. package/dist/packem_shared/{base-handler-fetch-CfkNakv8.js → base-handler-fetch-yrYrukwL.js} +1 -1
  71. package/dist/packem_shared/base-handler-node-C8P9rkaH.js +1 -0
  72. package/dist/packem_shared/{createRetryWrapper-CxgiV_hH.js → createRetryWrapper-DgmeHPNF.js} +1 -1
  73. package/dist/packem_shared/disk-storage-DqnnFQAQ.js +1 -0
  74. package/dist/packem_shared/disk-storage-with-checksum.d-Dgwyza8a.d.ts +146 -0
  75. package/dist/packem_shared/{executors.d-BZP2rWo3.d.ts → executors.d-B9dIy3NT.d.ts} +3 -2
  76. package/dist/packem_shared/files.d-CmSZi3M0.d.ts +655 -0
  77. package/dist/packem_shared/gcs-meta-storage-C9F78Sqq.js +1 -0
  78. package/dist/packem_shared/local-meta-storage-BELb1YwO.js +11 -0
  79. package/dist/packem_shared/{local-meta-storage.d-D9PBfkn6.d.ts → local-meta-storage.d-cRTXr1kb.d.ts} +7 -7
  80. package/dist/packem_shared/media-transformer.d-C8tn4J2Z.d.ts +331 -0
  81. package/dist/packem_shared/{memory-storage.d-4EU1cMt1.d.ts → memory-storage.d-BNZvDG1b.d.ts} +32 -40
  82. package/dist/packem_shared/path-C-OWflAo-_mqb5p5d.js +1 -0
  83. package/dist/packem_shared/{rest-base-e0reNDE_.js → rest-base-BQ_dhWyV.js} +1 -1
  84. package/dist/packem_shared/s3-base-storage-CX94H-Za.js +1 -0
  85. package/dist/packem_shared/{s3-base-storage.d-BQgP5B-t.d.ts → s3-base-storage.d-ks99NSs-.d.ts} +64 -70
  86. package/dist/packem_shared/storage-DR7qdwBN.js +1 -0
  87. package/dist/packem_shared/storage.d-DwdJrArF.d.ts +1186 -0
  88. package/dist/packem_shared/tus-base.d-BKBoJVy0.d.ts +103 -0
  89. package/dist/packem_shared/types.d-B1_xZIhu.d.ts +104 -0
  90. package/dist/packem_shared/{types.d-CrUWY4On.d.ts → types.d-BEUv414z.d.ts} +134 -134
  91. package/dist/packem_shared/{types.d-CggTCgXr.d.ts → types.d-D7Zlz5RE.d.ts} +3 -3
  92. package/dist/storage/aws/clients/index.d.ts +388 -388
  93. package/dist/storage/aws/index.d.ts +110 -113
  94. package/dist/storage/aws/index.js +1 -1
  95. package/dist/storage/aws-light/index.d.ts +64 -67
  96. package/dist/storage/aws-light/index.js +1 -1
  97. package/dist/storage/azure/index.d.ts +134 -139
  98. package/dist/storage/azure/index.js +1 -1
  99. package/dist/storage/box/index.d.ts +89 -92
  100. package/dist/storage/box/index.js +1 -1
  101. package/dist/storage/bun-s3/index.d.ts +71 -76
  102. package/dist/storage/bun-s3/index.js +1 -1
  103. package/dist/storage/bunny/index.d.ts +52 -55
  104. package/dist/storage/bunny/index.js +1 -1
  105. package/dist/storage/cloudinary/index.d.ts +54 -59
  106. package/dist/storage/cloudinary/index.js +1 -1
  107. package/dist/storage/dropbox/index.d.ts +59 -62
  108. package/dist/storage/dropbox/index.js +1 -1
  109. package/dist/storage/firebase/index.d.ts +74 -79
  110. package/dist/storage/firebase/index.js +1 -1
  111. package/dist/storage/ftp/index.d.ts +38 -43
  112. package/dist/storage/ftp/index.js +1 -1
  113. package/dist/storage/gcs/index.d.ts +90 -95
  114. package/dist/storage/gcs/index.js +1 -1
  115. package/dist/storage/google-drive/index.d.ts +69 -72
  116. package/dist/storage/google-drive/index.js +1 -1
  117. package/dist/storage/local/index.d.ts +4 -3
  118. package/dist/storage/local/index.js +1 -1
  119. package/dist/storage/memory/index.d.ts +3 -2
  120. package/dist/storage/memory/index.js +1 -1
  121. package/dist/storage/netlify-blob/index.d.ts +86 -93
  122. package/dist/storage/netlify-blob/index.js +1 -1
  123. package/dist/storage/onedrive/index.d.ts +44 -53
  124. package/dist/storage/onedrive/index.js +1 -1
  125. package/dist/storage/pocketbase/index.d.ts +67 -72
  126. package/dist/storage/pocketbase/index.js +1 -1
  127. package/dist/storage/sftp/index.d.ts +40 -45
  128. package/dist/storage/sftp/index.js +1 -1
  129. package/dist/storage/sharepoint/index.d.ts +96 -95
  130. package/dist/storage/sharepoint/index.js +1 -1
  131. package/dist/storage/supabase/index.d.ts +50 -55
  132. package/dist/storage/supabase/index.js +1 -1
  133. package/dist/storage/uploadthing/index.d.ts +34 -37
  134. package/dist/storage/uploadthing/index.js +1 -1
  135. package/dist/storage/vercel-blob/index.d.ts +110 -115
  136. package/dist/storage/vercel-blob/index.js +1 -1
  137. package/dist/transformer/audio-transformer.d.ts +97 -96
  138. package/dist/transformer/image-transformer.d.ts +423 -422
  139. package/dist/transformer/index.d.ts +35 -34
  140. package/dist/transformer/video-transformer.d.ts +112 -111
  141. package/package.json +2 -2
  142. package/dist/packem_shared/AwsLightStorage-BK-WPL0h.js +0 -1
  143. package/dist/packem_shared/AzureStorage-1UvDIQZd.js +0 -1
  144. package/dist/packem_shared/BoxMetaStorage-BSn6Qfnf.js +0 -1
  145. package/dist/packem_shared/BunS3MetaStorage-BSn6Qfnf.js +0 -1
  146. package/dist/packem_shared/BunnyMetaStorage-BSn6Qfnf.js +0 -1
  147. package/dist/packem_shared/CloudinaryMetaStorage-DPVnmNe5.js +0 -1
  148. package/dist/packem_shared/DiskStorage-CI07TVNu.js +0 -1
  149. package/dist/packem_shared/DropboxMetaStorage-BSn6Qfnf.js +0 -1
  150. package/dist/packem_shared/FirebaseMetaStorage-DPVnmNe5.js +0 -1
  151. package/dist/packem_shared/FtpMetaStorage-BSn6Qfnf.js +0 -1
  152. package/dist/packem_shared/GoogleDriveMetaStorage-Cbwa1CHV.js +0 -1
  153. package/dist/packem_shared/NetlifyBlobMetaStorage-DPVnmNe5.js +0 -1
  154. package/dist/packem_shared/NetlifyBlobStorage-CkpCCoN1.js +0 -1
  155. package/dist/packem_shared/OneDriveMetaStorage-Cbwa1CHV.js +0 -1
  156. package/dist/packem_shared/PocketBaseMetaStorage-DOTLwVE7.js +0 -1
  157. package/dist/packem_shared/SftpMetaStorage-BSn6Qfnf.js +0 -1
  158. package/dist/packem_shared/SharePointMetaStorage-BSn6Qfnf.js +0 -1
  159. package/dist/packem_shared/SupabaseMetaStorage-Cbwa1CHV.js +0 -1
  160. package/dist/packem_shared/UploadThingMetaStorage-DPVnmNe5.js +0 -1
  161. package/dist/packem_shared/VercelBlobMetaStorage-BSn6Qfnf.js +0 -1
  162. package/dist/packem_shared/base-handler-node-BF1v1qDa.js +0 -1
  163. package/dist/packem_shared/disk-storage-CsQcYW3s.js +0 -1
  164. package/dist/packem_shared/disk-storage-with-checksum.d-B-VGEsfl.d.ts +0 -156
  165. package/dist/packem_shared/files.d-CH0iLBNC.d.ts +0 -655
  166. package/dist/packem_shared/gcs-meta-storage-B7BnctnV.js +0 -1
  167. package/dist/packem_shared/local-meta-storage-iuJnu90B.js +0 -11
  168. package/dist/packem_shared/media-transformer.d-Quf4ai47.d.ts +0 -331
  169. package/dist/packem_shared/path-0oTTdkvl-DvWvbDbh.js +0 -1
  170. package/dist/packem_shared/s3-base-storage-BoTyhuzO.js +0 -1
  171. package/dist/packem_shared/storage-0j5nCAUp.js +0 -1
  172. package/dist/packem_shared/storage.d-CEM1upWM.d.ts +0 -1176
  173. package/dist/packem_shared/tus-base.d-DLzKE54M.d.ts +0 -106
  174. package/dist/packem_shared/types.d-Bon9GVVe.d.ts +0 -104
@@ -1 +1 @@
1
- import{CreateMultipartUploadCommand as f,UploadPartCommand as g,CompleteMultipartUploadCommand as w,AbortMultipartUploadCommand as k,ListPartsCommand as B,GetObjectCommand as C,HeadObjectCommand as b,DeleteObjectCommand as S,CopyObjectCommand as T,ListObjectsV2Command as E,waitUntilBucketExists as x,S3Client as U,PutObjectCommand as K}from"@aws-sdk/client-s3";import{fromIni as L}from"@aws-sdk/credential-providers";import{getSignedUrl as m}from"@aws-sdk/s3-request-presigner";import{S as P,b as I}from"./s3-base-storage-BoTyhuzO.js";import{Readable as u}from"node:stream";import{ReadableStream as y}from"node:stream/web";import M from"./S3File-CpZrubaV.js";import A from"./S3MetaStorage-CMonflzp.js";const r=p=>p?.signal?{abortSignal:p.signal}:void 0;class O{constructor(e,t){this.client=e}client;async createMultipartUpload(e,t){const a=new f({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),n=await this.client.send(a,r(t));if(!n.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:n.UploadId}}async uploadPart(e,t){const a=e.Body instanceof y?u.fromWeb(e.Body):e.Body,n=new g({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),o=await this.client.send(n,r(t));if(!o.ETag)throw new Error("Failed to upload part");return{ETag:o.ETag}}async completeMultipartUpload(e,t){const a=new w({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:o,PartNumber:i})=>({ETag:o,PartNumber:i}))},UploadId:e.UploadId}),n=await this.client.send(a,r(t));if(!n.Location)throw new Error("Failed to complete multipart upload");return{ETag:n.ETag,Location:n.Location}}async abortMultipartUpload(e,t){const a=new k({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a,r(t))}async listParts(e,t){const a=new B({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),n=await this.client.send(a,r(t)),o=[];if(n.Parts)for(const i of n.Parts)i.ETag&&i.PartNumber&&o.push({ETag:i.ETag,PartNumber:i.PartNumber,Size:i.Size});return{Parts:o.length>0?o:void 0}}async getObject(e,t){const a=new C({Bucket:e.Bucket,Key:e.Key,...e.Range!==void 0&&{Range:e.Range}}),n=await this.client.send(a,r(t));let o;if(n.Body){const i=n.Body;i instanceof u||typeof i=="object"&&"transform"in i&&i instanceof y?o=i:o=u.from(i)}return{Body:o,ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified,Metadata:n.Metadata}}async headObject(e,t){const a=new b({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,r(t));return{ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified}}async deleteObject(e,t){const a=new S({Bucket:e.Bucket,Key:e.Key});await this.client.send(a,r(t))}async copyObject(e,t){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const n=new T(a);await this.client.send(n,r(t))}async listObjectsV2(e,t){const a=new E({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,Delimiter:e.Delimiter,MaxKeys:e.MaxKeys,Prefix:e.Prefix}),n=await this.client.send(a,r(t));return{CommonPrefixes:n.CommonPrefixes?.map(o=>({Prefix:o.Prefix})),Contents:n.Contents?.map(o=>({Key:o.Key,LastModified:o.LastModified})),IsTruncated:n.IsTruncated,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(e){const t=new g({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return m(this.client,t,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await x({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}class _ extends P{static name="s3";s3Api;rawClient;constructor(e){const{bucket:t=process.env.S3_BUCKET,region:a=process.env.S3_REGION}=e;if(!t)throw new Error("S3 bucket is not defined");if(!a)throw new Error("S3 region is not defined");e.region=a;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=L({configFilepath:n}));const o=new U(e);super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:c=>{const s=c;if(s.$metadata){const d=s.$metadata.httpStatusCode;if(d&&[408,429,500,502,503,504].includes(d)||s.$fault==="server")return!0}return s.retryable??!1}}}),this.s3Api=new O(o,t),this.rawClient=o;const{metaStorage:i,metaStorageConfig:l}=e;if(!i){const c={...e,...l,logger:this.logger};"directory"in c||(this.meta=new A(c))}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},t){if(this.config.clientDirectUpload){const a=await this.getMeta(e);return this.buildPresigned({...a,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),n=I(t?.range),{Body:o,ContentLength:i,ContentType:l,ETag:c,Expires:s,LastModified:d}=await this.runOperation(t,h=>a.getObject({Bucket:this.bucket,Key:e,...n!==void 0&&{Range:n}},{signal:h}));return await this.checkIfExpired({expiredAt:s}),{headers:{"Content-Length":i?.toString()??"0","Content-Type":l,...c&&{ETag:c},...s&&{"X-Upload-Expires":s.toString()},...d&&{"Last-Modified":d.toString()}},size:Number(i),stream:o}})}get raw(){return this.rawClient}async getReadUrl(e,t){const a=new C({Bucket:this.bucket,Key:e,...t?.responseContentDisposition&&{ResponseContentDisposition:t.responseContentDisposition},...t?.responseContentType&&{ResponseContentType:t.responseContentType}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}async getUploadUrl(e,t){const a=new K({Bucket:this.bucket,Key:e,...t?.contentType&&{ContentType:t.contentType},...t?.contentLength!==void 0&&{ContentLength:t.contentLength}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}getS3Api(){return this.s3Api}getFileClass(){return M}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{_ as default};
1
+ import{CreateMultipartUploadCommand as f,UploadPartCommand as g,CompleteMultipartUploadCommand as w,AbortMultipartUploadCommand as k,ListPartsCommand as B,GetObjectCommand as C,HeadObjectCommand as b,DeleteObjectCommand as S,CopyObjectCommand as T,ListObjectsV2Command as E,waitUntilBucketExists as x,S3Client as U,PutObjectCommand as K}from"@aws-sdk/client-s3";import{fromIni as L}from"@aws-sdk/credential-providers";import{getSignedUrl as m}from"@aws-sdk/s3-request-presigner";import{S as P,b as I}from"./s3-base-storage-CX94H-Za.js";import{Readable as u}from"node:stream";import{ReadableStream as y}from"node:stream/web";import M from"./S3File-CpZrubaV.js";import A from"./S3MetaStorage-CMonflzp.js";const r=p=>p?.signal?{abortSignal:p.signal}:void 0;class O{constructor(e,t){this.client=e}client;async createMultipartUpload(e,t){const a=new f({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),n=await this.client.send(a,r(t));if(!n.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:n.UploadId}}async uploadPart(e,t){const a=e.Body instanceof y?u.fromWeb(e.Body):e.Body,n=new g({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),o=await this.client.send(n,r(t));if(!o.ETag)throw new Error("Failed to upload part");return{ETag:o.ETag}}async completeMultipartUpload(e,t){const a=new w({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:o,PartNumber:i})=>({ETag:o,PartNumber:i}))},UploadId:e.UploadId}),n=await this.client.send(a,r(t));if(!n.Location)throw new Error("Failed to complete multipart upload");return{ETag:n.ETag,Location:n.Location}}async abortMultipartUpload(e,t){const a=new k({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a,r(t))}async listParts(e,t){const a=new B({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),n=await this.client.send(a,r(t)),o=[];if(n.Parts)for(const i of n.Parts)i.ETag&&i.PartNumber&&o.push({ETag:i.ETag,PartNumber:i.PartNumber,Size:i.Size});return{Parts:o.length>0?o:void 0}}async getObject(e,t){const a=new C({Bucket:e.Bucket,Key:e.Key,...e.Range!==void 0&&{Range:e.Range}}),n=await this.client.send(a,r(t));let o;if(n.Body){const i=n.Body;i instanceof u||typeof i=="object"&&"transform"in i&&i instanceof y?o=i:o=u.from(i)}return{Body:o,ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified,Metadata:n.Metadata}}async headObject(e,t){const a=new b({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,r(t));return{ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified}}async deleteObject(e,t){const a=new S({Bucket:e.Bucket,Key:e.Key});await this.client.send(a,r(t))}async copyObject(e,t){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const n=new T(a);await this.client.send(n,r(t))}async listObjectsV2(e,t){const a=new E({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,Delimiter:e.Delimiter,MaxKeys:e.MaxKeys,Prefix:e.Prefix}),n=await this.client.send(a,r(t));return{CommonPrefixes:n.CommonPrefixes?.map(o=>({Prefix:o.Prefix})),Contents:n.Contents?.map(o=>({Key:o.Key,LastModified:o.LastModified})),IsTruncated:n.IsTruncated,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(e){const t=new g({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return m(this.client,t,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await x({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}class _ extends P{static name="s3";s3Api;rawClient;constructor(e){const{bucket:t=process.env.S3_BUCKET,region:a=process.env.S3_REGION}=e;if(!t)throw new Error("S3 bucket is not defined");if(!a)throw new Error("S3 region is not defined");e.region=a;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=L({configFilepath:n}));const o=new U(e);super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:c=>{const s=c;if(s.$metadata){const d=s.$metadata.httpStatusCode;if(d&&[408,429,500,502,503,504].includes(d)||s.$fault==="server")return!0}return s.retryable===!0?!0:void 0}}}),this.s3Api=new O(o,t),this.rawClient=o;const{metaStorage:i,metaStorageConfig:l}=e;if(!i){const c={...e,...l,logger:this.logger};"directory"in c||(this.meta=new A(c))}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},t){if(this.config.clientDirectUpload){const a=await this.getMeta(e);return this.buildPresigned({...a,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),n=I(t?.range),{Body:o,ContentLength:i,ContentType:l,ETag:c,Expires:s,LastModified:d}=await this.runOperation(t,h=>a.getObject({Bucket:this.bucket,Key:e,...n!==void 0&&{Range:n}},{signal:h}));return await this.checkIfExpired({expiredAt:s}),{headers:{"Content-Length":i?.toString()??"0","Content-Type":l,...c&&{ETag:c},...s&&{"X-Upload-Expires":s.toString()},...d&&{"Last-Modified":d.toString()}},size:Number(i),stream:o}})}get raw(){return this.rawClient}async getReadUrl(e,t){const a=new C({Bucket:this.bucket,Key:e,...t?.responseContentDisposition&&{ResponseContentDisposition:t.responseContentDisposition},...t?.responseContentType&&{ResponseContentType:t.responseContentType}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}async getUploadUrl(e,t){const a=new K({Bucket:this.bucket,Key:e,...t?.contentType&&{ContentType:t.contentType},...t?.contentLength!==void 0&&{ContentLength:t.contentLength}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}getS3Api(){return this.s3Api}getFileClass(){return M}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{_ as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-BELb1YwO.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{F as T}from"./index-nZWCQrSe.js";import P from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import k from"./SftpFile-ClWDYnt2.js";import F from"./SftpMetaStorage-BSn6Qfnf.js";import{r as y,t as b,e as l}from"./posix-dirname-CfpH5wZi.js";import{t as E}from"./get-file-status-y3wTtDQs.js";import{t as M}from"./update-size-DuNuLyxj.js";import{i as v}from"./part-match-D-9dGX42.js";import{e as S}from"./has-content-50BsqrWw.js";const f=c=>{const a=c?.code,e=c instanceof Error?c.message:String(c);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},g=c=>{if(c instanceof Error&&c.name==="AbortError")return c;const a=new Error(c instanceof Error&&c.message?c.message:"The operation was aborted",{cause:c});return a.name="AbortError",a};class U extends O{static name="sftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=y(a.rootFolderPath??""),this.meta=a.metaStorage??new F(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new k(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const i=await this.getMeta(t.id);if(i.status==="completed")return i}catch{}return t.bytesWritten=0,t.status=E(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&M(t,a.size),!v(a,t))return d(p.FILE_CONFLICT);const i=await this.lock(a.id);try{if(S(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return d(p.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return d(p.METHOD_NOT_ALLOWED,"SFTP storage does not support chunked or resumable uploads; send the file in a single request.");const n=await b(a.body),r=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{const h=l(r);h&&await o.mkdir(h,!0),await o.put(n,r)})),t.bytesWritten=n.length,t.size=n.length,t.path=r,t.ETag=T(n)}return t.status=E(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,i)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),i=t.path??this.keyToPath(t.name||a),{range:n}=e??{},r=await this.runOperation(e,s=>this.run(s,async o=>{try{const h=n?{readStreamOptions:{start:n.start,...n.end===void 0?{}:{end:n.end}}}:void 0;return await o.get(i,void 0,h)}catch(h){if(f(h))return d(p.FILE_NOT_FOUND);throw h}}));return{content:r,contentType:t.contentType,ETag:t.ETag??T(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:n?r.length:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),i=t.path??this.keyToPath(t.name||a);await this.runOperation(e,r=>this.run(r,async s=>{try{await s.delete(i)}catch(o){if(!f(o))throw o}})),await this.deleteMeta(a);const n={...t,status:"deleted"};return await this.onDelete(n),n})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=await h.get(n),m=l(r);m&&await h.mkdir(m,!0),await h.put(u,r)}));const s={...i,id:e,name:e,path:r};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=l(r);u&&await h.mkdir(u,!0);try{await h.rename(n,r)}catch(m){try{const w=await h.get(n);await h.put(w,r),await h.delete(n)}catch(w){throw new AggregateError([m,w],`SFTP move failed: rename and copy+delete fallback both failed for "${n}" → "${r}"`)}}}));const s={...i,id:e,name:e,path:r};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,i=>this.run(i,async n=>{const r=[];return await this.walkList(n,t,r),r}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const i=t.path??this.keyToPath(t.name||a);return this.runOperation(e,n=>this.run(n,async r=>{const s=await r.exists(i);return s==="-"||s==="l"}))})}async walkList(a,e,t){let i;try{i=await a.list(e||".")}catch(n){if(f(n))return;throw n}for(const n of i){const r=e?`${e}/${n.name}`:n.name;if(n.type==="d"){await this.walkList(a,r,t);continue}if(n.type!=="-")continue;const s=this.pathToKey(r);if(!s)continue;const o=new k({contentType:"application/octet-stream",metadata:{},originalName:n.name});o.id=s,o.name=s,o.path=r,o.size=n.size,o.modifiedAt=new Date(n.modifyTime).toISOString(),t.push(o)}}async run(a,e){const t=new P;if(a?.aborted)throw g(a.reason);const i=()=>{t.end()};a?.addEventListener("abort",i,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(n){throw a?.aborted?g(n):n}finally{a?.removeEventListener("abort",i),await t.end()}}keyToPath(a){const e=y(a);e&&O.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":this.rootFolderPath.startsWith("/")?`/${t.join("/")}`:t.join("/")}pathToKey(a){const e=y(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{U as default};
1
+ import{F as T}from"./index-nZWCQrSe.js";import P from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-DR7qdwBN.js";import k from"./SftpFile-ClWDYnt2.js";import F from"./SftpMetaStorage-CJsyeQ63.js";import{r as y,t as b,e as l}from"./posix-dirname-CfpH5wZi.js";import{t as E}from"./get-file-status-y3wTtDQs.js";import{t as M}from"./update-size-DuNuLyxj.js";import{i as v}from"./part-match-D-9dGX42.js";import{e as S}from"./has-content-50BsqrWw.js";const f=c=>{const a=c?.code,e=c instanceof Error?c.message:String(c);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},g=c=>{if(c instanceof Error&&c.name==="AbortError")return c;const a=new Error(c instanceof Error&&c.message?c.message:"The operation was aborted",{cause:c});return a.name="AbortError",a};class U extends O{static name="sftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=y(a.rootFolderPath??""),this.meta=a.metaStorage??new F(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new k(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const i=await this.getMeta(t.id);if(i.status==="completed")return i}catch{}return t.bytesWritten=0,t.status=E(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&M(t,a.size),!v(a,t))return d(p.FILE_CONFLICT);const i=await this.lock(a.id);try{if(S(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return d(p.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return d(p.METHOD_NOT_ALLOWED,"SFTP storage does not support chunked or resumable uploads; send the file in a single request.");const n=await b(a.body),r=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{const h=l(r);h&&await o.mkdir(h,!0),await o.put(n,r)})),t.bytesWritten=n.length,t.size=n.length,t.path=r,t.ETag=T(n)}return t.status=E(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,i)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),i=t.path??this.keyToPath(t.name||a),{range:n}=e??{},r=await this.runOperation(e,s=>this.run(s,async o=>{try{const h=n?{readStreamOptions:{start:n.start,...n.end===void 0?{}:{end:n.end}}}:void 0;return await o.get(i,void 0,h)}catch(h){if(f(h))return d(p.FILE_NOT_FOUND);throw h}}));return{content:r,contentType:t.contentType,ETag:t.ETag??T(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:n?r.length:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),i=t.path??this.keyToPath(t.name||a);await this.runOperation(e,r=>this.run(r,async s=>{try{await s.delete(i)}catch(o){if(!f(o))throw o}})),await this.deleteMeta(a);const n={...t,status:"deleted"};return await this.onDelete(n),n})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=await h.get(n),m=l(r);m&&await h.mkdir(m,!0),await h.put(u,r)}));const s={...i,id:e,name:e,path:r};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=l(r);u&&await h.mkdir(u,!0);try{await h.rename(n,r)}catch(m){try{const w=await h.get(n);await h.put(w,r),await h.delete(n)}catch(w){throw new AggregateError([m,w],`SFTP move failed: rename and copy+delete fallback both failed for "${n}" → "${r}"`)}}}));const s={...i,id:e,name:e,path:r};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,i=>this.run(i,async n=>{const r=[];return await this.walkList(n,t,r),r}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const i=t.path??this.keyToPath(t.name||a);return this.runOperation(e,n=>this.run(n,async r=>{const s=await r.exists(i);return s==="-"||s==="l"}))})}async walkList(a,e,t){let i;try{i=await a.list(e||".")}catch(n){if(f(n))return;throw n}for(const n of i){const r=e?`${e}/${n.name}`:n.name;if(n.type==="d"){await this.walkList(a,r,t);continue}if(n.type!=="-")continue;const s=this.pathToKey(r);if(!s)continue;const o=new k({contentType:"application/octet-stream",metadata:{},originalName:n.name});o.id=s,o.name=s,o.path=r,o.size=n.size,o.modifiedAt=new Date(n.modifyTime).toISOString(),t.push(o)}}async run(a,e){const t=new P;if(a?.aborted)throw g(a.reason);const i=()=>{t.end()};a?.addEventListener("abort",i,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(n){throw a?.aborted?g(n):n}finally{a?.removeEventListener("abort",i),await t.end()}}keyToPath(a){const e=y(a);e&&O.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":this.rootFolderPath.startsWith("/")?`/${t.join("/")}`:t.join("/")}pathToKey(a){const e=y(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{U as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-BELb1YwO.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{throwErrorCode as c,ERRORS as d}from"./ERRORS-BIBxE2oR.js";import h,{buildGraphClient as l}from"./OneDriveStorage-CP6MvGAa.js";import{B as I}from"./storage-0j5nCAUp.js";import u from"./SharePointMetaStorage-BSn6Qfnf.js";const g=a=>{if(!a)return;const e=a.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},v=a=>{let e;try{e=new URL(a)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${a}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}};class T extends I{static name="sharepoint";checksumTypes=[];meta;client;inner;innerPromise;oneDriveAuth;resolvedConfig;constructor(e){super(e);const t=e.accessToken??process.env.SHAREPOINT_ACCESS_TOKEN??process.env.ONEDRIVE_ACCESS_TOKEN,r=e.clientCredentials??(()=>{const n=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,o=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,i=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(n&&o&&i)return{clientId:o,clientSecret:i,tenantId:n}})();this.oneDriveAuth={...e.client&&{client:e.client},...t!==void 0&&{accessToken:t},...r&&{clientCredentials:r},...e.oauth&&{oauth:e.oauth}},this.resolvedConfig={...e,...e.driveId??process.env.SHAREPOINT_DRIVE_ID?{driveId:e.driveId??process.env.SHAREPOINT_DRIVE_ID}:{},...e.siteId??process.env.SHAREPOINT_SITE_ID?{siteId:e.siteId??process.env.SHAREPOINT_SITE_ID}:{},...e.siteUrl??process.env.SHAREPOINT_SITE_URL?{siteUrl:e.siteUrl??process.env.SHAREPOINT_SITE_URL}:{},...e.hostname??process.env.SHAREPOINT_HOSTNAME?{hostname:e.hostname??process.env.SHAREPOINT_HOSTNAME}:{}},this.client=l(this.oneDriveAuth),this.meta=e.metaStorage??new u(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,t){return(await this.getInner()).create(e,t)}async write(e,t){return(await this.getInner()).write(e,t)}async delete(e,t){return(await this.getInner()).delete(e,t)}async get(e,t){return(await this.getInner()).get(e,t)}async copy(e,t,r){return(await this.getInner()).copy(e,t,r)}async move(e,t,r){return(await this.getInner()).move(e,t,r)}async exists(e,t){return(await this.getInner()).exists(e)}async list(e=1e3,t){return(await this.getInner()).list(e,t)}async update(e,t,r){return(await this.getInner()).update(e,t)}async getStream(e,t){return(await this.getInner()).getStream(e)}async getReadUrl(e,t){return(await this.getInner()).getReadUrl(e,t)}async getUploadUrl(e,t){return(await this.getInner()).getUploadUrl(e,t)}async getInner(){return this.inner?this.inner:(this.innerPromise??=this.buildInner(),this.inner=await this.innerPromise,this.inner)}async buildInner(){const e=await this.resolveDriveId(),{documentLibrary:t,hostname:r,siteId:n,sitePath:o,siteUrl:i,...s}=this.genericConfig;return new h({...s,...this.oneDriveAuth,driveId:e,...this.resolvedConfig.copyTimeoutMs!==void 0&&{copyTimeoutMs:this.resolvedConfig.copyTimeoutMs},...this.resolvedConfig.metaStorageConfig&&{metaStorageConfig:this.resolvedConfig.metaStorageConfig},metaStorage:this.meta,...this.resolvedConfig.publicByDefault!==void 0&&{publicByDefault:this.resolvedConfig.publicByDefault},...this.resolvedConfig.rootFolderPath!==void 0&&{rootFolderPath:this.resolvedConfig.rootFolderPath}})}async resolveDriveId(){const e=this.resolvedConfig;if(e.driveId)return e.driveId;const t=await this.resolveSiteId();if(e.documentLibrary){const n=await this.client.api(`/sites/${t}/drives`).get(),o=e.documentLibrary.toLowerCase(),i=(n.value??[]).find(s=>s.name===e.documentLibrary)??(n.value??[]).find(s=>s.name?.toLowerCase()===o||g(s.webUrl)?.toLowerCase()===o);return i?i.id:c(d.FILE_NOT_FOUND,`SharePoint storage: document library "${e.documentLibrary}" not found in site "${t}".`)}const r=await this.client.api(`/sites/${t}/drive`).get();return r?.id?r.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site "${t}" has no default drive.`)}async resolveSiteId(){const e=this.resolvedConfig;if(e.siteId)return e.siteId;let t,r;if(e.siteUrl?{hostname:t,sitePath:r}=v(e.siteUrl):e.hostname&&(t=e.hostname,r=e.sitePath??"/"),!t||!r)return c(d.BAD_REQUEST,"SharePoint storage: missing site targeting. Provide `driveId`, `siteId`, `siteUrl`, or `hostname` (+ `sitePath`).");const n=r==="/"?"":r.replace(/^\/+/,""),o=n?`/sites/${t}:/${n}`:`/sites/${t}`;let i;try{i=await this.client.api(o).get()}catch(s){return c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}" (${s instanceof Error?s.message:String(s)}).`)}return i?.id?i.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{T as default};
1
+ import{throwErrorCode as c,ERRORS as d}from"./ERRORS-BIBxE2oR.js";import h,{buildGraphClient as l}from"./OneDriveStorage-B8qFgMq1.js";import{B as I}from"./storage-DR7qdwBN.js";import u from"./SharePointMetaStorage-CJsyeQ63.js";const g=a=>{if(!a)return;const e=a.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},v=a=>{let e;try{e=new URL(a)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${a}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}};class T extends I{static name="sharepoint";checksumTypes=[];meta;client;inner;innerPromise;oneDriveAuth;resolvedConfig;constructor(e){super(e);const t=e.accessToken??process.env.SHAREPOINT_ACCESS_TOKEN??process.env.ONEDRIVE_ACCESS_TOKEN,r=e.clientCredentials??(()=>{const n=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,o=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,i=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(n&&o&&i)return{clientId:o,clientSecret:i,tenantId:n}})();this.oneDriveAuth={...e.client&&{client:e.client},...t!==void 0&&{accessToken:t},...r&&{clientCredentials:r},...e.oauth&&{oauth:e.oauth}},this.resolvedConfig={...e,...e.driveId??process.env.SHAREPOINT_DRIVE_ID?{driveId:e.driveId??process.env.SHAREPOINT_DRIVE_ID}:{},...e.siteId??process.env.SHAREPOINT_SITE_ID?{siteId:e.siteId??process.env.SHAREPOINT_SITE_ID}:{},...e.siteUrl??process.env.SHAREPOINT_SITE_URL?{siteUrl:e.siteUrl??process.env.SHAREPOINT_SITE_URL}:{},...e.hostname??process.env.SHAREPOINT_HOSTNAME?{hostname:e.hostname??process.env.SHAREPOINT_HOSTNAME}:{}},this.client=l(this.oneDriveAuth),this.meta=e.metaStorage??new u(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,t){return(await this.getInner()).create(e,t)}async write(e,t){return(await this.getInner()).write(e,t)}async delete(e,t){return(await this.getInner()).delete(e,t)}async get(e,t){return(await this.getInner()).get(e,t)}async copy(e,t,r){return(await this.getInner()).copy(e,t,r)}async move(e,t,r){return(await this.getInner()).move(e,t,r)}async exists(e,t){return(await this.getInner()).exists(e)}async list(e=1e3,t){return(await this.getInner()).list(e,t)}async update(e,t,r){return(await this.getInner()).update(e,t)}async getStream(e,t){return(await this.getInner()).getStream(e)}async getReadUrl(e,t){return(await this.getInner()).getReadUrl(e,t)}async getUploadUrl(e,t){return(await this.getInner()).getUploadUrl(e,t)}async getInner(){return this.inner?this.inner:(this.innerPromise??=this.buildInner(),this.inner=await this.innerPromise,this.inner)}async buildInner(){const e=await this.resolveDriveId(),{documentLibrary:t,hostname:r,siteId:n,sitePath:o,siteUrl:i,...s}=this.genericConfig;return new h({...s,...this.oneDriveAuth,driveId:e,...this.resolvedConfig.copyTimeoutMs!==void 0&&{copyTimeoutMs:this.resolvedConfig.copyTimeoutMs},...this.resolvedConfig.metaStorageConfig&&{metaStorageConfig:this.resolvedConfig.metaStorageConfig},metaStorage:this.meta,...this.resolvedConfig.publicByDefault!==void 0&&{publicByDefault:this.resolvedConfig.publicByDefault},...this.resolvedConfig.rootFolderPath!==void 0&&{rootFolderPath:this.resolvedConfig.rootFolderPath}})}async resolveDriveId(){const e=this.resolvedConfig;if(e.driveId)return e.driveId;const t=await this.resolveSiteId();if(e.documentLibrary){const n=await this.client.api(`/sites/${t}/drives`).get(),o=e.documentLibrary.toLowerCase(),i=(n.value??[]).find(s=>s.name===e.documentLibrary)??(n.value??[]).find(s=>s.name?.toLowerCase()===o||g(s.webUrl)?.toLowerCase()===o);return i?i.id:c(d.FILE_NOT_FOUND,`SharePoint storage: document library "${e.documentLibrary}" not found in site "${t}".`)}const r=await this.client.api(`/sites/${t}/drive`).get();return r?.id?r.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site "${t}" has no default drive.`)}async resolveSiteId(){const e=this.resolvedConfig;if(e.siteId)return e.siteId;let t,r;if(e.siteUrl?{hostname:t,sitePath:r}=v(e.siteUrl):e.hostname&&(t=e.hostname,r=e.sitePath??"/"),!t||!r)return c(d.BAD_REQUEST,"SharePoint storage: missing site targeting. Provide `driveId`, `siteId`, `siteUrl`, or `hostname` (+ `sitePath`).");const n=r==="/"?"":r.replace(/^\/+/,""),o=n?`/sites/${t}:/${n}`:`/sites/${t}`;let i;try{i=await this.client.api(o).get()}catch(s){return c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}" (${s instanceof Error?s.message:String(s)}).`)}return i?.id?i.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{T as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-BELb1YwO.js";class o extends r{constructor(t){super(t)}}export{o as default};
@@ -1 +1 @@
1
- import{StorageClient as l}from"@supabase/storage-js";import{throwErrorCode as h,ERRORS as u}from"./ERRORS-BIBxE2oR.js";import{B as f}from"./storage-0j5nCAUp.js";import c from"./SupabaseFile-Bo5B-vM1.js";import g from"./SupabaseMetaStorage-Cbwa1CHV.js";import{t as p}from"./get-file-status-y3wTtDQs.js";import{t as w}from"./update-size-DuNuLyxj.js";import{i as y}from"./part-match-D-9dGX42.js";import{e as b}from"./has-content-50BsqrWw.js";const d=3600*24*7,E=o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const e=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=e?.[1]??e?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},S=async o=>{const e=[];for await(const a of o)e.push(Buffer.from(a));return Buffer.concat(e)};class R extends f{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(e){if(super(e),this.bucket=e.bucket,this.defaultUrlExpiresIn=Math.min(e.defaultUrlExpiresIn??3600,d),e.client)this.storageClient=e.client;else{const a=e.url??process.env.SUPABASE_URL,t=e.serviceKey??process.env.SUPABASE_SERVICE_ROLE_KEY??process.env.SUPABASE_KEY;if(!a)throw new Error("Supabase storage: `url` is required (or set SUPABASE_URL).");if(!t)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const i=a.replace(/\/+$/,"")+(a.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new l(i,{apikey:t,Authorization:`Bearer ${t}`},e.fetch)}this.meta=e.metaStorage??new g(e.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new c(e);t.name=this.namingFunction(t),t.bucket=this.bucket,t.path=t.name,await this.validate(t);try{const i=await this.getMeta(t.id);if(i.bytesWritten>=0)return i}catch{}return t.bytesWritten=0,t.status=p(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&w(t,e.size),!y(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(b(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await S(e.body),n=t.path??t.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,r,{contentType:t.contentType,upsert:!0}));if(m)throw m;t.bytesWritten=r.length,t.size=r.length,t.path=s?.path??n,t.ETag=s?.id}return t.status=p(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const i=t?.path??t?.name??e,{error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).remove([i]));if(r&&r.message&&!/not.*found/i.test(r.message))throw r;return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:e}),{bucket:this.bucket,id:e,name:e,path:i,status:"deleted"})})}async exists({id:e},a){return this.instrumentOperation("exists",async()=>{let t=e;try{t=(await this.getMeta(e)).path??e}catch{}const{data:i,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(t));return r?!1:!!i})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t=e,i;try{i=await this.checkIfExpired(await this.getMeta(e)),t=i.path??i.name??e}catch{}const{data:r,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(t));if(n||!r)throw n??new Error(`Supabase: object not found at "${t}"`);const s=Buffer.from(await this.runOperation(a,()=>r.arrayBuffer()));return{content:s,contentType:i?.contentType??r.type??"application/octet-stream",ETag:i?.ETag,expiredAt:i?.expiredAt,id:e,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt,name:i?.name??t,originalName:i?.originalName??t,size:i?.size??s.length}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(e))?.path??e,r=a,{error:n}=await this.runOperation(t,()=>this.storageClient.from(this.bucket).copy(i,r));if(n)throw n;const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=r,s.bucket=this.bucket,s})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const i=(await this.getMetaSafe(e))?.path??e,{error:r}=await this.runOperation(t,()=>this.storageClient.from(this.bucket).move(i,a));if(r)throw r;const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucket;try{await this.deleteMeta(e)}catch{}return n})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>{const{data:t,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:e}));if(i)throw i;return(t??[]).map(r=>{const n=new c({contentType:r.metadata?.mimetype??"application/octet-stream",metadata:r.metadata??{},originalName:r.name});return n.id=r.name,n.name=r.name,n.path=r.name,n.bucket=this.bucket,n.size=typeof r.metadata?.size=="number"?r.metadata.size:void 0,n.createdAt=r.created_at??void 0,n.modifiedAt=r.updated_at??void 0,n.ETag=r.metadata?.eTag??r.id??void 0,n})},{limit:e})}async getReadUrl(e,a){const t=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,d),{data:i,error:r}=await this.storageClient.from(this.bucket).createSignedUrl(e,t,{download:E(a?.responseContentDisposition)});return r||!i?h(u.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUrl failed"):i.signedUrl}async getUploadUrl(e,a){if(a?.contentType!==void 0||a?.contentLength!==void 0)return h(u.BAD_REQUEST,"Supabase: `contentType`/`contentLength` are not supported for upload URLs. A Supabase signed upload URL does not bind the request Content-Type into the signature and cannot enforce a size limit; validate both at your application gateway/proxy before issuing the URL.");const{data:t,error:i}=await this.storageClient.from(this.bucket).createSignedUploadUrl(e);return i||!t?h(u.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUploadUrl failed"):t.signedUrl}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=e=>this.deleteMeta(e.id)}export{R as default};
1
+ import{StorageClient as l}from"@supabase/storage-js";import{throwErrorCode as h,ERRORS as u}from"./ERRORS-BIBxE2oR.js";import{B as f}from"./storage-DR7qdwBN.js";import c from"./SupabaseFile-Bo5B-vM1.js";import g from"./SupabaseMetaStorage-B0gLF7Io.js";import{t as p}from"./get-file-status-y3wTtDQs.js";import{t as w}from"./update-size-DuNuLyxj.js";import{i as y}from"./part-match-D-9dGX42.js";import{e as b}from"./has-content-50BsqrWw.js";const d=3600*24*7,E=o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const e=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=e?.[1]??e?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},S=async o=>{const e=[];for await(const a of o)e.push(Buffer.from(a));return Buffer.concat(e)};class R extends f{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(e){if(super(e),this.bucket=e.bucket,this.defaultUrlExpiresIn=Math.min(e.defaultUrlExpiresIn??3600,d),e.client)this.storageClient=e.client;else{const a=e.url??process.env.SUPABASE_URL,t=e.serviceKey??process.env.SUPABASE_SERVICE_ROLE_KEY??process.env.SUPABASE_KEY;if(!a)throw new Error("Supabase storage: `url` is required (or set SUPABASE_URL).");if(!t)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const i=a.replace(/\/+$/,"")+(a.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new l(i,{apikey:t,Authorization:`Bearer ${t}`},e.fetch)}this.meta=e.metaStorage??new g(e.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new c(e);t.name=this.namingFunction(t),t.bucket=this.bucket,t.path=t.name,await this.validate(t);try{const i=await this.getMeta(t.id);if(i.bytesWritten>=0)return i}catch{}return t.bytesWritten=0,t.status=p(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&w(t,e.size),!y(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(b(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await S(e.body),n=t.path??t.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,r,{contentType:t.contentType,upsert:!0}));if(m)throw m;t.bytesWritten=r.length,t.size=r.length,t.path=s?.path??n,t.ETag=s?.id}return t.status=p(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const i=t?.path??t?.name??e,{error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).remove([i]));if(r&&r.message&&!/not.*found/i.test(r.message))throw r;return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:e}),{bucket:this.bucket,id:e,name:e,path:i,status:"deleted"})})}async exists({id:e},a){return this.instrumentOperation("exists",async()=>{let t=e;try{t=(await this.getMeta(e)).path??e}catch{}const{data:i,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(t));return r?!1:!!i})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t=e,i;try{i=await this.checkIfExpired(await this.getMeta(e)),t=i.path??i.name??e}catch{}const{data:r,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(t));if(n||!r)throw n??new Error(`Supabase: object not found at "${t}"`);const s=Buffer.from(await this.runOperation(a,()=>r.arrayBuffer()));return{content:s,contentType:i?.contentType??r.type??"application/octet-stream",ETag:i?.ETag,expiredAt:i?.expiredAt,id:e,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt,name:i?.name??t,originalName:i?.originalName??t,size:i?.size??s.length}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(e))?.path??e,r=a,{error:n}=await this.runOperation(t,()=>this.storageClient.from(this.bucket).copy(i,r));if(n)throw n;const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=r,s.bucket=this.bucket,s})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const i=(await this.getMetaSafe(e))?.path??e,{error:r}=await this.runOperation(t,()=>this.storageClient.from(this.bucket).move(i,a));if(r)throw r;const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucket;try{await this.deleteMeta(e)}catch{}return n})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>{const{data:t,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:e}));if(i)throw i;return(t??[]).map(r=>{const n=new c({contentType:r.metadata?.mimetype??"application/octet-stream",metadata:r.metadata??{},originalName:r.name});return n.id=r.name,n.name=r.name,n.path=r.name,n.bucket=this.bucket,n.size=typeof r.metadata?.size=="number"?r.metadata.size:void 0,n.createdAt=r.created_at??void 0,n.modifiedAt=r.updated_at??void 0,n.ETag=r.metadata?.eTag??r.id??void 0,n})},{limit:e})}async getReadUrl(e,a){const t=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,d),{data:i,error:r}=await this.storageClient.from(this.bucket).createSignedUrl(e,t,{download:E(a?.responseContentDisposition)});return r||!i?h(u.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUrl failed"):i.signedUrl}async getUploadUrl(e,a){if(a?.contentType!==void 0||a?.contentLength!==void 0)return h(u.BAD_REQUEST,"Supabase: `contentType`/`contentLength` are not supported for upload URLs. A Supabase signed upload URL does not bind the request Content-Type into the signature and cannot enforce a size limit; validate both at your application gateway/proxy before issuing the URL.");const{data:t,error:i}=await this.storageClient.from(this.bucket).createSignedUploadUrl(e);return i||!t?h(u.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUploadUrl failed"):t.signedUrl}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=e=>this.deleteMeta(e.id)}export{R as default};
@@ -1 +1 @@
1
- import{format as b}from"node:url";import{n as d}from"./headers-BAiAKekR.js";import{b as a,a as c,g as n}from"./base-handler-core-D-9Ku1h-.js";import{T as f}from"./base-handler-node-BF1v1qDa.js";import{TusBase as U,TUS_RESUMABLE as T}from"./TUS_RESUMABLE-CyTSRvPU.js";import{TUS_VERSION as R}from"./TUS_RESUMABLE-CyTSRvPU.js";class p extends f{static methods=["delete","download","get","head","options","patch","post"];disableTerminationForFinishedUploads=!1;tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends U{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(p.methods)}async post(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));const t=e.headers["upload-length"],s=e.headers["upload-defer-length"],r=e.headers["upload-concat"],o=a(e,"upload-metadata",!0),i=a(e,"content-type")||"",h=Number.parseInt(a(e,"content-length")||"0",10),l=e.originalUrl||e.url||"",u=c(e);return this.tusBase.handlePost(t,s,r,o,l,u,h,i)}async patch(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);if(e.headers["upload-offset"]===void 0)throw d(412,"Missing Upload-Offset header");if(e.headers["content-type"]===void 0)throw d(412,"Content-Type header required");if(e.headers["content-type"]!=="application/offset+octet-stream")throw d(415,"Unsupported Media Type");const s=Number.parseInt(a(e,"upload-offset"),10),r=e.headers["upload-length"],o=a(e,"upload-metadata",!0),i=Number(a(e,"content-length")),h=a(e,"upload-checksum"),{checksum:l,checksumAlgorithm:u}=this.tusBase.extractChecksum(h),m=e.originalUrl||e.url||"",g=c(e);return this.tusBase.handlePatch(t,s,r,o,l,u,m,g,i)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async head(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleHead(t)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async get(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleGet(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.UploadErrorCode==="GONE"?d(410,"Upload expired"):t}}async delete(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleDelete(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.code==="ENOENT"?d(404,"File not found"):t}}send(e,{body:t="",headers:s={},statusCode:r=200}){const o={body:t,headers:{...s,"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","Tus-Resumable":T},statusCode:r||200};super.send(e,o)}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,t){const s=new URL(e,"http://localhost"),{pathname:r}=s,o=Object.fromEntries(s.searchParams.entries()),i=b({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:(/^https?:\/\//iu.test(e)?s.origin:"")+i}}export{T as TUS_RESUMABLE,R as TUS_VERSION,p as Tus};
1
+ import{format as b}from"node:url";import{n as d}from"./headers-BAiAKekR.js";import{b as a,a as c,g as n}from"./base-handler-core-BJP9jHCE.js";import{T as f}from"./base-handler-node-C8P9rkaH.js";import{TusBase as U,TUS_RESUMABLE as T}from"./TUS_RESUMABLE-CyTSRvPU.js";import{TUS_VERSION as R}from"./TUS_RESUMABLE-CyTSRvPU.js";class p extends f{static methods=["delete","download","get","head","options","patch","post"];disableTerminationForFinishedUploads=!1;tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends U{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(p.methods)}async post(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));const t=e.headers["upload-length"],s=e.headers["upload-defer-length"],r=e.headers["upload-concat"],o=a(e,"upload-metadata",!0),i=a(e,"content-type")||"",h=Number.parseInt(a(e,"content-length")||"0",10),l=e.originalUrl||e.url||"",u=c(e);return this.tusBase.handlePost(t,s,r,o,l,u,h,i)}async patch(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);if(e.headers["upload-offset"]===void 0)throw d(412,"Missing Upload-Offset header");if(e.headers["content-type"]===void 0)throw d(412,"Content-Type header required");if(e.headers["content-type"]!=="application/offset+octet-stream")throw d(415,"Unsupported Media Type");const s=Number.parseInt(a(e,"upload-offset"),10),r=e.headers["upload-length"],o=a(e,"upload-metadata",!0),i=Number(a(e,"content-length")),h=a(e,"upload-checksum"),{checksum:l,checksumAlgorithm:u}=this.tusBase.extractChecksum(h),m=e.originalUrl||e.url||"",g=c(e);return this.tusBase.handlePatch(t,s,r,o,l,u,m,g,i)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async head(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleHead(t)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async get(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleGet(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.UploadErrorCode==="GONE"?d(410,"Upload expired"):t}}async delete(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleDelete(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.code==="ENOENT"?d(404,"File not found"):t}}send(e,{body:t="",headers:s={},statusCode:r=200}){const o={body:t,headers:{...s,"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","Tus-Resumable":T},statusCode:r||200};super.send(e,o)}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,t){const s=new URL(e,"http://localhost"),{pathname:r}=s,o=Object.fromEntries(s.searchParams.entries()),i=b({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:(/^https?:\/\//iu.test(e)?s.origin:"")+i}}export{T as TUS_RESUMABLE,R as TUS_VERSION,p as Tus};
@@ -1 +1 @@
1
- import{n as a}from"./headers-BAiAKekR.js";import{B as y}from"./storage-0j5nCAUp.js";import{C as v}from"./base-handler-fetch-CfkNakv8.js";import{TusBase as E,TUS_RESUMABLE as w}from"./TUS_RESUMABLE-CyTSRvPU.js";import{TUS_VERSION as C}from"./TUS_RESUMABLE-CyTSRvPU.js";const h=f=>{let e;try{const t=new URL(f).pathname.split("/").filter(Boolean);e=t[t.length-1]||void 0}catch{return}if(e){try{y.assertSafeId(e)}catch{throw a(400,`Invalid file id: "${e}"`)}return e}};class m extends v{static methods=["delete","download","get","head","options","patch","post"];tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends E{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads??!1}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async fetch(e){const t=await super.fetch(e);if(t.headers.has("Tus-Resumable"))return t;const s=new Headers(t.headers);return s.set("Tus-Resumable",w),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})}async options(){return this.tusBase.handleOptions(m.methods)}async post(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=e.headers.get("upload-length")||void 0,r=e.headers.get("upload-defer-length")||void 0,o=e.headers.get("upload-concat")||void 0,d=e.headers.get("upload-metadata")||void 0,l=e.headers.get("content-type")||"",i=e.headers.get("content-length"),n=i?Number.parseInt(i,10):0,u=e.url,c=e.body;return this.tusBase.handlePost(s,r,o,d,u,c,n,l)}async patch(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(e.url);if(!s)throw a(404,"File not found");const r=e.headers.get("upload-offset");if(!r)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(r,10),l=e.headers.get("upload-length")||void 0,i=e.headers.get("upload-metadata")||void 0,n=e.headers.get("content-length"),u=n?Number.parseInt(n,10):0,c=e.headers.get("upload-checksum")||void 0,{checksum:b,checksumAlgorithm:T}=this.tusBase.extractChecksum(c),U=e.url,F=e.body;try{return this.tusBase.handlePatch(s,d,l,i,b,T,U,F,u)}catch(p){const g=p;throw g.UploadErrorCode==="GONE"||g.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):p}}async head(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleHead(s)}catch(r){const o=r;throw o.UploadErrorCode==="GONE"||o.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):r}}async get(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleGet(s)}catch(r){throw r.UploadErrorCode==="GONE"?a(410,"Upload expired"):r}}async delete(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleDelete(s)}catch(r){throw r.code==="ENOENT"?a(404,"File not found"):r}}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,t){const s=new URL(e),{pathname:r,search:o}=s,d=`${r}/${t.id}${o}`;return this.storage.config.useRelativeLocation?d:s.origin+d}}export{w as TUS_RESUMABLE,C as TUS_VERSION,m as Tus};
1
+ import{n as a}from"./headers-BAiAKekR.js";import{B as y}from"./storage-DR7qdwBN.js";import{C as v}from"./base-handler-fetch-yrYrukwL.js";import{TusBase as E,TUS_RESUMABLE as w}from"./TUS_RESUMABLE-CyTSRvPU.js";import{TUS_VERSION as C}from"./TUS_RESUMABLE-CyTSRvPU.js";const h=f=>{let e;try{const t=new URL(f).pathname.split("/").filter(Boolean);e=t[t.length-1]||void 0}catch{return}if(e){try{y.assertSafeId(e)}catch{throw a(400,`Invalid file id: "${e}"`)}return e}};class m extends v{static methods=["delete","download","get","head","options","patch","post"];tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends E{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads??!1}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async fetch(e){const t=await super.fetch(e);if(t.headers.has("Tus-Resumable"))return t;const s=new Headers(t.headers);return s.set("Tus-Resumable",w),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})}async options(){return this.tusBase.handleOptions(m.methods)}async post(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=e.headers.get("upload-length")||void 0,r=e.headers.get("upload-defer-length")||void 0,o=e.headers.get("upload-concat")||void 0,d=e.headers.get("upload-metadata")||void 0,l=e.headers.get("content-type")||"",i=e.headers.get("content-length"),n=i?Number.parseInt(i,10):0,u=e.url,c=e.body;return this.tusBase.handlePost(s,r,o,d,u,c,n,l)}async patch(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(e.url);if(!s)throw a(404,"File not found");const r=e.headers.get("upload-offset");if(!r)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(r,10),l=e.headers.get("upload-length")||void 0,i=e.headers.get("upload-metadata")||void 0,n=e.headers.get("content-length"),u=n?Number.parseInt(n,10):0,c=e.headers.get("upload-checksum")||void 0,{checksum:b,checksumAlgorithm:T}=this.tusBase.extractChecksum(c),U=e.url,F=e.body;try{return this.tusBase.handlePatch(s,d,l,i,b,T,U,F,u)}catch(p){const g=p;throw g.UploadErrorCode==="GONE"||g.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):p}}async head(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleHead(s)}catch(r){const o=r;throw o.UploadErrorCode==="GONE"||o.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):r}}async get(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleGet(s)}catch(r){throw r.UploadErrorCode==="GONE"?a(410,"Upload expired"):r}}async delete(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleDelete(s)}catch(r){throw r.code==="ENOENT"?a(404,"File not found"):r}}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,t){const s=new URL(e),{pathname:r,search:o}=s,d=`${r}/${t.id}${o}`;return this.storage.config.useRelativeLocation?d:s.origin+d}}export{w as TUS_RESUMABLE,C as TUS_VERSION,m as Tus};
@@ -0,0 +1 @@
1
+ import{y as s}from"./local-meta-storage-BELb1YwO.js";class o extends s{constructor(r){super(r)}}export{o as default};
@@ -1 +1 @@
1
- import{UTApi as w,UTFile as u}from"uploadthing/server";import{throwErrorCode as l,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as g}from"./storage-0j5nCAUp.js";import d from"./UploadThingFile-BTFMpcIA.js";import T from"./UploadThingMetaStorage-DPVnmNe5.js";import{t as m}from"./get-file-status-y3wTtDQs.js";import{t as U}from"./update-size-DuNuLyxj.js";import{i as I}from"./part-match-D-9dGX42.js";import{e as O}from"./has-content-50BsqrWw.js";const f=3600*24*7,E=p=>{let e;try{e=typeof atob=="function"?atob(p):Buffer.from(p,"base64").toString("utf8")}catch(t){throw new Error(`UploadThing: token is not valid base64: ${t.message}`)}let a;try{a=JSON.parse(e)}catch(t){throw new Error(`UploadThing: token does not decode to JSON: ${t.message}`)}if(!a||typeof a!="object"||typeof a.apiKey!="string"||typeof a.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return a},k=async p=>{const e=[];for await(const a of p)e.push(Buffer.from(a));return Buffer.concat(e)},y=p=>{const e=p.lastIndexOf("/");return e===-1?p:p.slice(e+1)};class S extends g{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(e){super(e);const a=e.token??process.env.UPLOADTHING_TOKEN;if(e.client)this.utapi=e.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new w({defaultKeyType:"customId",token:a})}if(!a)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=E(a).appId,this.acl=e.acl??"public-read",this.defaultUrlExpiresIn=Math.min(e.defaultUrlExpiresIn??3600,f),this.meta=e.metaStorage??new T(e.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new d(e);t.name=this.namingFunction(t),t.customId=t.name,await this.validate(t);try{const i=await this.getMeta(t.id);if(i.bytesWritten>=0)return i}catch{}return t.bytesWritten=0,t.status=m(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&U(t,e.size),!I(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await k(e.body),o=new Blob([new Uint8Array(n)],{type:t.contentType}),s=new u([o],y(t.name||t.id),{customId:t.name||t.id,type:t.contentType}),r=await this.runOperation(a,()=>this.utapi.uploadFiles(s,{acl:this.acl}));if(r.error)throw new Error(r.error.message);const{data:c}=r;t.bytesWritten=n.length,t.size=n.length,t.ufsKey=c.key,t.url=c.ufsUrl??c.url,t.ETag=c.fileHash,t.fileHash=c.fileHash}return t.status=m(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const i=t?.customId??t?.name??e;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:e}),{customId:i,id:e,name:e,status:"deleted"})})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t,i=e;try{t=await this.checkIfExpired(await this.getMeta(e)),i=t.customId??t.name??e}catch{}const n=await this.resolveFetchUrl(i,a),o=await this.runOperation(a,()=>fetch(n));if(!o.ok)throw new Error(`UploadThing: fetch failed: ${o.status} ${o.statusText} for ${i}`);const s=Buffer.from(await o.arrayBuffer());return{content:s,contentType:t?.contentType??o.headers.get("content-type")??"application/octet-stream",ETag:t?.ETag??o.headers.get("etag")??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt,name:t?.name??i,originalName:t?.originalName??i,size:t?.size??s.length}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:e},t),n=new Blob([new Uint8Array(i.content)],{type:i.contentType}),o=new u([n],y(a),{customId:a,type:i.contentType}),s=await this.runOperation(t,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const r=new d({contentType:i.contentType,metadata:{},originalName:a});return r.id=a,r.name=a,r.customId=a,r.size=typeof i.size=="string"?Number(i.size):i.size,r.ufsKey=s.data.key,r.url=s.data.ufsUrl??s.data.url,r.ETag=s.data.fileHash,r})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,a,t);return await this.delete({id:e},t),i})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:e}))).files.map(t=>{const i=t.customId??t.key,n=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return n.id=i,n.name=i,n.customId=t.customId??void 0,n.ufsKey=t.key,n.size=t.size,n.modifiedAt=t.uploadedAt?new Date(t.uploadedAt).toISOString():void 0,n}),{limit:e})}async getReadUrl(e,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return l(h.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition`/`responseContentType` are not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const t=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{ufsUrl:i}=await this.utapi.generateSignedURL(e,{expiresIn:t,keyType:"customId"});return i}async getUploadUrl(e,a){return l(h.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(e,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const{ufsUrl:t}=await this.runOperation(a,()=>this.utapi.generateSignedURL(e,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return t}internalOnComplete=e=>this.deleteMeta(e.id)}export{S as default};
1
+ import{UTApi as w,UTFile as u}from"uploadthing/server";import{throwErrorCode as l,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as g}from"./storage-DR7qdwBN.js";import d from"./UploadThingFile-BTFMpcIA.js";import T from"./UploadThingMetaStorage-Bv_YCZ0Q.js";import{t as m}from"./get-file-status-y3wTtDQs.js";import{t as U}from"./update-size-DuNuLyxj.js";import{i as I}from"./part-match-D-9dGX42.js";import{e as O}from"./has-content-50BsqrWw.js";const f=3600*24*7,E=p=>{let e;try{e=typeof atob=="function"?atob(p):Buffer.from(p,"base64").toString("utf8")}catch(t){throw new Error(`UploadThing: token is not valid base64: ${t.message}`)}let a;try{a=JSON.parse(e)}catch(t){throw new Error(`UploadThing: token does not decode to JSON: ${t.message}`)}if(!a||typeof a!="object"||typeof a.apiKey!="string"||typeof a.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return a},k=async p=>{const e=[];for await(const a of p)e.push(Buffer.from(a));return Buffer.concat(e)},y=p=>{const e=p.lastIndexOf("/");return e===-1?p:p.slice(e+1)};class S extends g{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(e){super(e);const a=e.token??process.env.UPLOADTHING_TOKEN;if(e.client)this.utapi=e.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new w({defaultKeyType:"customId",token:a})}if(!a)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=E(a).appId,this.acl=e.acl??"public-read",this.defaultUrlExpiresIn=Math.min(e.defaultUrlExpiresIn??3600,f),this.meta=e.metaStorage??new T(e.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new d(e);t.name=this.namingFunction(t),t.customId=t.name,await this.validate(t);try{const i=await this.getMeta(t.id);if(i.bytesWritten>=0)return i}catch{}return t.bytesWritten=0,t.status=m(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&U(t,e.size),!I(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await k(e.body),o=new Blob([new Uint8Array(n)],{type:t.contentType}),s=new u([o],y(t.name||t.id),{customId:t.name||t.id,type:t.contentType}),r=await this.runOperation(a,()=>this.utapi.uploadFiles(s,{acl:this.acl}));if(r.error)throw new Error(r.error.message);const{data:c}=r;t.bytesWritten=n.length,t.size=n.length,t.ufsKey=c.key,t.url=c.ufsUrl??c.url,t.ETag=c.fileHash,t.fileHash=c.fileHash}return t.status=m(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const i=t?.customId??t?.name??e;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:e}),{customId:i,id:e,name:e,status:"deleted"})})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t,i=e;try{t=await this.checkIfExpired(await this.getMeta(e)),i=t.customId??t.name??e}catch{}const n=await this.resolveFetchUrl(i,a),o=await this.runOperation(a,()=>fetch(n));if(!o.ok)throw new Error(`UploadThing: fetch failed: ${o.status} ${o.statusText} for ${i}`);const s=Buffer.from(await o.arrayBuffer());return{content:s,contentType:t?.contentType??o.headers.get("content-type")??"application/octet-stream",ETag:t?.ETag??o.headers.get("etag")??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt,name:t?.name??i,originalName:t?.originalName??i,size:t?.size??s.length}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:e},t),n=new Blob([new Uint8Array(i.content)],{type:i.contentType}),o=new u([n],y(a),{customId:a,type:i.contentType}),s=await this.runOperation(t,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const r=new d({contentType:i.contentType,metadata:{},originalName:a});return r.id=a,r.name=a,r.customId=a,r.size=typeof i.size=="string"?Number(i.size):i.size,r.ufsKey=s.data.key,r.url=s.data.ufsUrl??s.data.url,r.ETag=s.data.fileHash,r})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,a,t);return await this.delete({id:e},t),i})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:e}))).files.map(t=>{const i=t.customId??t.key,n=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return n.id=i,n.name=i,n.customId=t.customId??void 0,n.ufsKey=t.key,n.size=t.size,n.modifiedAt=t.uploadedAt?new Date(t.uploadedAt).toISOString():void 0,n}),{limit:e})}async getReadUrl(e,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return l(h.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition`/`responseContentType` are not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const t=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{ufsUrl:i}=await this.utapi.generateSignedURL(e,{expiresIn:t,keyType:"customId"});return i}async getUploadUrl(e,a){return l(h.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(e,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const{ufsUrl:t}=await this.runOperation(a,()=>this.utapi.generateSignedURL(e,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return t}internalOnComplete=e=>this.deleteMeta(e.id)}export{S as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-BELb1YwO.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{put as l,list as u,del as d,copy as h}from"@vercel/blob";import{a as y}from"./detect-file-type-BA7UBLKA.js";import{B as O,c as E}from"./storage-0j5nCAUp.js";import{y as g}from"./local-meta-storage-iuJnu90B.js";import m from"./VercelBlobFile-CVQwKlZk.js";import{t as p}from"./get-file-status-y3wTtDQs.js";import{t as T}from"./update-size-DuNuLyxj.js";import{i as b}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";class f extends O{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:h,credentials:this.credentials,del:d,list:u,put:l}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=f.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:r,metaStorageConfig:t}=e;this.meta=r||new g(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const r=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,i=t?.startsWith("store_")?t.slice(6):t;if(r&&i)return{oidcToken:r,storeId:i};if(r||i)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${r?"set":"missing"}, storeId=${i?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,r){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?E(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const i=new m(t);i.name=this.namingFunction(i),await this.validate(i);try{const a=await this.getMeta(i.id);if(a.bytesWritten>=0)return a}catch{}return i.bytesWritten=0,i.status=p(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(e,r){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&T(t,e.size),!b(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(v(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await y(s);o?.mime&&(t.contentType=o.mime)}catch{}const w=new Blob([s],{type:t.contentType}),c=await this.runOperation(r,()=>l(t.name,w,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=c.url,t.pathname=c.pathname,t.downloadUrl=c.downloadUrl,t.bytesWritten=s.length}return t.status=p(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},r){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`);const{url:i}=t;t.status="deleted";try{await this.runOperation(r,()=>d(i,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},r){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:i}=t;return(await this.runOperation(r,()=>fetch(i,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},r){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{url:i}=t,a=await this.runOperation(r,()=>fetch(i)),n=Buffer.from(await this.runOperation(r,()=>a.arrayBuffer()));return{content:n,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||n.length}})}async copy(e,r,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(e);if(!i.url)throw new Error("Source file URL not found");const a=i.url,n=await this.runOperation(t,()=>h(a,r,{access:"public",...this.credentials}));return{...i,id:r,name:r,pathname:n.pathname,url:n.url}})}async move(e,r,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,r,t);return await this.delete({id:e},t),i})}async list(e=1e3,r){return this.instrumentOperation("list",async()=>(await this.runOperation(r,()=>u({limit:e,...this.credentials}))).blobs.map(t=>{const i=new m({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return i.createdAt=t.uploadedAt?.toISOString(),i.id=t.pathname,i.modifiedAt=t.uploadedAt?.toISOString(),i.name=t.pathname,i.pathname=t.pathname,i.size=t.size,i.url=t.url,i.downloadUrl=t.downloadUrl,i}),{limit:e})}internalOnComplete=e=>this.deleteMeta(e.id);shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{f as default};
1
+ import{put as l,list as u,del as d,copy as h}from"@vercel/blob";import{a as y}from"./detect-file-type-BA7UBLKA.js";import{B as O,c as E}from"./storage-DR7qdwBN.js";import{y as g}from"./local-meta-storage-BELb1YwO.js";import m from"./VercelBlobFile-CVQwKlZk.js";import{t as p}from"./get-file-status-y3wTtDQs.js";import{t as T}from"./update-size-DuNuLyxj.js";import{i as b}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";class f extends O{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:h,credentials:this.credentials,del:d,list:u,put:l}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=f.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:r,metaStorageConfig:t}=e;this.meta=r||new g(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const r=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,i=t?.startsWith("store_")?t.slice(6):t;if(r&&i)return{oidcToken:r,storeId:i};if(r||i)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${r?"set":"missing"}, storeId=${i?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,r){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?E(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const i=new m(t);i.name=this.namingFunction(i),await this.validate(i);try{const a=await this.getMeta(i.id);if(a.bytesWritten>=0)return a}catch{}return i.bytesWritten=0,i.status=p(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(e,r){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&T(t,e.size),!b(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(v(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await y(s);o?.mime&&(t.contentType=o.mime)}catch{}const w=new Blob([s],{type:t.contentType}),c=await this.runOperation(r,()=>l(t.name,w,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=c.url,t.pathname=c.pathname,t.downloadUrl=c.downloadUrl,t.bytesWritten=s.length}return t.status=p(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},r){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`);const{url:i}=t;t.status="deleted";try{await this.runOperation(r,()=>d(i,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},r){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:i}=t;return(await this.runOperation(r,()=>fetch(i,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},r){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{url:i}=t,a=await this.runOperation(r,()=>fetch(i)),n=Buffer.from(await this.runOperation(r,()=>a.arrayBuffer()));return{content:n,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||n.length}})}async copy(e,r,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(e);if(!i.url)throw new Error("Source file URL not found");const a=i.url,n=await this.runOperation(t,()=>h(a,r,{access:"public",...this.credentials}));return{...i,id:r,name:r,pathname:n.pathname,url:n.url}})}async move(e,r,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,r,t);return await this.delete({id:e},t),i})}async list(e=1e3,r){return this.instrumentOperation("list",async()=>(await this.runOperation(r,()=>u({limit:e,...this.credentials}))).blobs.map(t=>{const i=new m({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return i.createdAt=t.uploadedAt?.toISOString(),i.id=t.pathname,i.modifiedAt=t.uploadedAt?.toISOString(),i.name=t.pathname,i.pathname=t.pathname,i.size=t.size,i.url=t.url,i.downloadUrl=t.downloadUrl,i}),{limit:e})}internalOnComplete=e=>this.deleteMeta(e.id);shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{f as default};
@@ -65,11 +65,11 @@ type DeleteFileInput = z.infer<typeof deleteFileInputSchema>;
65
65
  type CopyFileInput = z.infer<typeof copyFileInputSchema>;
66
66
  type SignUploadUrlInput = z.infer<typeof signUploadUrlInputSchema>;
67
67
  /**
68
- * Whether write operations require user approval.
69
- *
70
- * - `true` — all write tools need approval (default)
71
- * - `false` — no approval needed for any write tool
72
- * - object — per-tool override; unspecified write tools default to `true`
73
- */
68
+ * Whether write operations require user approval.
69
+ *
70
+ * - `true` — all write tools need approval (default)
71
+ * - `false` — no approval needed for any write tool
72
+ * - object — per-tool override; unspecified write tools default to `true`
73
+ */
74
74
  type ApprovalConfig = boolean | Partial<Record<FileWriteToolName, boolean>>;
75
75
  export { ApprovalConfig as A, CopyFileInput as C, DeleteFileInput as D, FileToolName as F, GetFileMetadataInput as G, ListFilesInput as L, SignUploadUrlInput as S, TOOL_SCHEMAS as T, UploadFileInput as U, DownloadFileInput as a, GetFileUrlInput as b, FileReadToolName as c, FileWriteToolName as d };
@@ -1 +1 @@
1
- import{EventEmitter as u}from"node:events";import{format as m}from"node:url";import g from"mime";import{ErrorMap as b}from"./ERRORS-BIBxE2oR.js";import{H as w}from"./headers-BAiAKekR.js";import{Readable as f}from"node:stream";import"type-is";import{B as h}from"./storage-0j5nCAUp.js";const C=(r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},R=r=>r.at(-1),y=r=>{let e="",t="";const s=c(r,"forwarded");return s&&s.split(";").forEach(o=>{const[i,n]=o.split("=");i==="proto"&&(e=n),i==="host"&&(t=n)}),{host:t,proto:e}},P=(r,e="utf8",t)=>new Promise((s,o)=>{const i=[];let n=0;r.on("data",d=>{const a=Buffer.isBuffer(d)?d:Buffer.from(d,e);if(n+=a.length,n>t){o(new Error("Request body length limit exceeded")),r.destroy();return}i.push(a)}),r.once("end",()=>{s(Buffer.concat(i).toString(e))}),r.once("error",o)}),c=(r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const o=Array.isArray(s)?s:s.split(",");return R(o).trim()},E=(r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},A=(r,e={})=>{const t=Object.keys(e);t.length>0&&E(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{if(["link","location"].includes(s.toLowerCase())){const o=encodeURI(e[s].toString()).replaceAll("#","%23");r.setHeader(s,o)}else r.setHeader(s,e[s])})},U=r=>c(r,"host")||c(r,"x-forwarded-host"),I=r=>c(r,"x-forwarded-proto").toLowerCase(),L=r=>{let{host:e,proto:t}=y(r);return e||=U(r),t||=I(r),e?t?`${t}://${e}`:`//${e}`:""},H=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},$=/^[\da-z]{4,}(?:-[\da-z]{4,}){2,}$/i,k=r=>{const e=H(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let o=e.length-1;o>=0;o-=1){const i=e[o];if(!i)continue;const n=i.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(n.toLowerCase())&&$.test(n))return h.assertSafeId(n),n}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 h.assertSafeId(s),s;throw new Error("Invalid request URL")},W=r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?f.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?f.from(Buffer.from(r.body)):r instanceof f?r:f.from(new Uint8Array(0));class j extends u{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=(e={})=>{this.internalErrorResponses={...b,...this.internalErrorResponses,...this.storage.errorResponses,...e}};parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const o=s[0]?.trim();if(!o)return;const i=o.split("-");if(i.length!==2)return;const[n,d]=i;let a,l;if(n&&d)a=Number.parseInt(n,10),l=Number.parseInt(d,10);else if(n&&!d)a=Number.parseInt(n,10),l=t-1;else if(!n&&d){const p=Number.parseInt(d,10);a=Math.max(0,t-p),l=t-1}else return;if(!(Number.isNaN(a)||Number.isNaN(l)||a>=t||l>=t||a>l))return{end:l,start:a}}buildFileUrlFromString(e,t,s){const o=new URL(e,"http://localhost"),{pathname:i}=o,n=Object.fromEntries(o.searchParams.entries()),d=m({pathname:`${i}/${t.id}`,query:n});let a="";return this.storage.config.useRelativeLocation||(/^https?:\/\//iu.test(e)?a=o.origin:s&&(a=L({headers:s}))),`${a}${d}.${g.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return w.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{W as a,c as b,j as c,C as d,H as e,k as g,P as r,A as s,$ as u};
1
+ import{EventEmitter as u}from"node:events";import{format as m}from"node:url";import g from"mime";import{ErrorMap as b}from"./ERRORS-BIBxE2oR.js";import{H as w}from"./headers-BAiAKekR.js";import{Readable as f}from"node:stream";import"type-is";import{B as h}from"./storage-DR7qdwBN.js";const C=(r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},R=r=>r.at(-1),y=r=>{let e="",t="";const s=c(r,"forwarded");return s&&s.split(";").forEach(o=>{const[i,n]=o.split("=");i==="proto"&&(e=n),i==="host"&&(t=n)}),{host:t,proto:e}},P=(r,e="utf8",t)=>new Promise((s,o)=>{const i=[];let n=0;r.on("data",d=>{const a=Buffer.isBuffer(d)?d:Buffer.from(d,e);if(n+=a.length,n>t){o(new Error("Request body length limit exceeded")),r.destroy();return}i.push(a)}),r.once("end",()=>{s(Buffer.concat(i).toString(e))}),r.once("error",o)}),c=(r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const o=Array.isArray(s)?s:s.split(",");return R(o).trim()},E=(r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},A=(r,e={})=>{const t=Object.keys(e);t.length>0&&E(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{if(["link","location"].includes(s.toLowerCase())){const o=encodeURI(e[s].toString()).replaceAll("#","%23");r.setHeader(s,o)}else r.setHeader(s,e[s])})},U=r=>c(r,"host")||c(r,"x-forwarded-host"),I=r=>c(r,"x-forwarded-proto").toLowerCase(),L=r=>{let{host:e,proto:t}=y(r);return e||=U(r),t||=I(r),e?t?`${t}://${e}`:`//${e}`:""},H=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},$=/^[\da-z]{4,}(?:-[\da-z]{4,}){2,}$/i,k=r=>{const e=H(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let o=e.length-1;o>=0;o-=1){const i=e[o];if(!i)continue;const n=i.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(n.toLowerCase())&&$.test(n))return h.assertSafeId(n),n}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 h.assertSafeId(s),s;throw new Error("Invalid request URL")},W=r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?f.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?f.from(Buffer.from(r.body)):r instanceof f?r:f.from(new Uint8Array(0));class j extends u{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=(e={})=>{this.internalErrorResponses={...b,...this.internalErrorResponses,...this.storage.errorResponses,...e}};parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const o=s[0]?.trim();if(!o)return;const i=o.split("-");if(i.length!==2)return;const[n,d]=i;let a,l;if(n&&d)a=Number.parseInt(n,10),l=Number.parseInt(d,10);else if(n&&!d)a=Number.parseInt(n,10),l=t-1;else if(!n&&d){const p=Number.parseInt(d,10);a=Math.max(0,t-p),l=t-1}else return;if(!(Number.isNaN(a)||Number.isNaN(l)||a>=t||l>=t||a>l))return{end:l,start:a}}buildFileUrlFromString(e,t,s){const o=new URL(e,"http://localhost"),{pathname:i}=o,n=Object.fromEntries(o.searchParams.entries()),d=m({pathname:`${i}/${t.id}`,query:n});let a="";return this.storage.config.useRelativeLocation||(/^https?:\/\//iu.test(e)?a=o.origin:s&&(a=L({headers:s}))),`${a}${d}.${g.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return w.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{W as a,c as b,j as c,C as d,H as e,k as g,P as r,A as s,$ as u};
@@ -1 +1 @@
1
- import{H as u,h as f}from"./headers-BAiAKekR.js";import{ERRORS as p,isUploadError as C}from"./ERRORS-BIBxE2oR.js";import{c as E,d as b}from"./base-handler-core-D-9Ku1h-.js";import{i as R}from"./storage-0j5nCAUp.js";import{waitForStorage as O}from"./waitForStorage-ByQmG4xF.js";class A extends E{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:p.METHOD_NOT_ALLOWED});try{await O(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:p.STORAGE_ERROR})}try{const o=await e.call(this,t);return this.handleFetchResponse(t,o)}catch(o){const s=o instanceof Error?o:new Error(String(o)),r={...b(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",r),this.logger?.error("[fetch error]: %O",r),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:o,statusCode:s,...r}=e;if(r.status!==void 0&&this.listenerCount(r.status)>0&&this.emit(r.status,{...r,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),r.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(r,n)}catch(l){throw this.logger?.error("[onComplete error]: %O",l),l}const{headers:d,statusCode:c,...g}=n,{content:H,stream:w,...y}=g;return this.createResponse({body:y,headers:d||o,statusCode:c||s||200})}const m={...o,...e.headers},a=this.convertHeaders({...m,"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",...r.hash===void 0?{}:{[`X-Range-${r.hash?.algorithm.toUpperCase()}`]:r.hash?.value}}),h=e.headers||{};h.Location&&!a.location&&!a.Location?a.location=String(h.Location):h.location&&!a.location&&!a.Location?a.location=String(h.location):o.Location&&!a.location&&!a.Location?a.location=String(o.Location):o.location&&!a.location&&!a.Location&&(a.location=String(o.location));let i;return s>=200&&s<300&&(i=Object.keys(r).length>0?{...r}:{},"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[o,s]of Object.entries(t))e[o]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:o={},statusCode:s}=t;let r;return s===204?r=null:typeof e=="string"?r=e:e instanceof Buffer?r=new Uint8Array(e):e&&typeof e=="object"?(r=JSON.stringify(e),o["Content-Type"]||(o["Content-Type"]=u.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(r="{}",o["Content-Type"]||(o["Content-Type"]=u.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(r,{headers:this.convertHeaders(o),status:s})}async createErrorResponse(t){let e;C(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!R(t)&&!f.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 o;return e.body?typeof e.body=="object"&&e.body!==null?o={body:e.body,headers:e.headers,statusCode:e.statusCode}:o={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}:o={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(o)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{A as C};
1
+ import{H as u,h as f}from"./headers-BAiAKekR.js";import{ERRORS as p,isUploadError as C}from"./ERRORS-BIBxE2oR.js";import{c as E,d as b}from"./base-handler-core-BJP9jHCE.js";import{i as R}from"./storage-DR7qdwBN.js";import{waitForStorage as O}from"./waitForStorage-ByQmG4xF.js";class A extends E{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:p.METHOD_NOT_ALLOWED});try{await O(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:p.STORAGE_ERROR})}try{const o=await e.call(this,t);return this.handleFetchResponse(t,o)}catch(o){const s=o instanceof Error?o:new Error(String(o)),r={...b(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",r),this.logger?.error("[fetch error]: %O",r),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:o,statusCode:s,...r}=e;if(r.status!==void 0&&this.listenerCount(r.status)>0&&this.emit(r.status,{...r,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),r.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(r,n)}catch(l){throw this.logger?.error("[onComplete error]: %O",l),l}const{headers:d,statusCode:c,...g}=n,{content:H,stream:w,...y}=g;return this.createResponse({body:y,headers:d||o,statusCode:c||s||200})}const m={...o,...e.headers},a=this.convertHeaders({...m,"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",...r.hash===void 0?{}:{[`X-Range-${r.hash?.algorithm.toUpperCase()}`]:r.hash?.value}}),h=e.headers||{};h.Location&&!a.location&&!a.Location?a.location=String(h.Location):h.location&&!a.location&&!a.Location?a.location=String(h.location):o.Location&&!a.location&&!a.Location?a.location=String(o.Location):o.location&&!a.location&&!a.Location&&(a.location=String(o.location));let i;return s>=200&&s<300&&(i=Object.keys(r).length>0?{...r}:{},"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[o,s]of Object.entries(t))e[o]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:o={},statusCode:s}=t;let r;return s===204?r=null:typeof e=="string"?r=e:e instanceof Buffer?r=new Uint8Array(e):e&&typeof e=="object"?(r=JSON.stringify(e),o["Content-Type"]||(o["Content-Type"]=u.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(r="{}",o["Content-Type"]||(o["Content-Type"]=u.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(r,{headers:this.convertHeaders(o),status:s})}async createErrorResponse(t){let e;C(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!R(t)&&!f.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 o;return e.body?typeof e.body=="object"&&e.body!==null?o={body:e.body,headers:e.headers,statusCode:e.statusCode}:o={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}:o={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(o)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{A as C};
@@ -0,0 +1 @@
1
+ import{paginate as N}from"@visulima/pagination";import{H as T,h as H,n as f}from"./headers-BAiAKekR.js";import w from"mime";import{ERRORS as g,isUploadError as L}from"./ERRORS-BIBxE2oR.js";import{match as z}from"path-to-regexp";import{d as S,c as M,s as U,e as O,u as F}from"./base-handler-core-BJP9jHCE.js";import{i as j}from"./storage-DR7qdwBN.js";import{waitForStorage as k}from"./waitForStorage-ByQmG4xF.js";import{PassThrough as $}from"node:stream";import{e as R}from"./response-builder-CbSA8qPa.js";const P=z(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),v=c=>{const e=P(c);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}},D=(c,e,t)=>{let r=0,s=0;const a=t-e+1,n=new $({highWaterMark:Math.min(64*1024,a),transform(i,o,h){const d=i.length,u=r,p=u+d-1;if(r+=d,p<e){h();return}if(u>t){this.end(),h();return}const y=Math.max(0,e-u),C=Math.min(d,t-u+1);if(y<C){const b=i.subarray(y,C);s+=b.length,this.push(b)||c.pause()}s>=a&&(this.end(),c.destroy()),h()}});return c.pipe(n),c.on("error",i=>{n.destroy(i)}),n},_=(c,e,t)=>{let r=!1;const s=()=>{r||(r=!0,c.destroy())};e.on("drain",()=>{c.resume()}),e.on("close",s),e.on("finish",s),e.on("error",s),c.on("end",()=>{e.end()}),c.on("error",async a=>{if(!r){if(e.headersSent||e.writableEnded){s(),e.destroy(a);return}try{await t(e,a)}catch{e.destroy(a)}finally{s()}}}),c.on("data",a=>{e.write(a)||c.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",s)},I=(c,e,t)=>{const{headers:r,statusCode:s}=c;e(t,{headers:r,statusCode:s})},X=(c,e,t,r,s,a,n)=>{e.body=c?.data===void 0?c:c.data;const{headers:i,statusCode:o}=c,h=c;if(h.stream)if(typeof r=="function")r();else{const d=n(e.headers.range,h.size||0);a(t,h.stream,{headers:i,range:d||void 0,size:h.size,statusCode:o})}else{let d="";c.content!==void 0?d=c.content:typeof c=="object"&&"data"in c&&(d=c.data),typeof r=="function"?r():s(t,{body:d,headers:i,statusCode:o})}},q=async(c,e,t,r,s,a,n)=>{const{headers:i,statusCode:o,...h}=c;if(typeof r=="function")e._body=!0,e.body=h,r();else{const d=c,u=d.headers?{...d.headers}:{};d.headers===void 0&&(d.headers={}),d.statusCode===void 0&&(d.statusCode=200);try{const p=s.onComplete(h,d,e);p instanceof Promise&&await p}catch(p){throw a?.error&&a.error("[onComplete error]: %O",p),p}Object.keys(d.headers||{}).length===0&&Object.keys(u).length>0?d.headers=u:d.headers&&Object.keys(u).length>0&&(d.headers={...u,...d.headers}),n(e,t,d)}},G=(c,e,t,r)=>{const{headers:s,statusCode:a,...n}=c,i=s||{},o=i["X-Chunked-Upload"]==="true"||i["x-chunked-upload"]==="true";let h;const d={...R(i),...s?R(s):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};o&&(h=JSON.stringify(n),!d["Content-Type"]&&!d["content-type"]&&(d["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(h=""),r(t,{body:h,headers:d,statusCode:a||200})},W=async(c,e,t,r,s,a,n)=>{const i=c instanceof Error?c:new Error(String(c)),o={...S(i,["name",...Object.getOwnPropertyNames(i)]),request:S(e,["headers","method","url"])};r("error")>0&&t("error",o),s?.error&&s.error("[error]: %O",o),await a(n,i)},m="Content-Type";class x extends M{static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=async(e,t)=>this.upload(e,t);upload=async(e,t,r)=>{e.on("error",a=>this.logger?.error("[request error]: %O",a)),this.logger?.debug("[request]: %s %s",e.method,e.url);const s=this.registeredHandlers.get(e.method);if(!s){await this.sendError(t,{UploadErrorCode:g.METHOD_NOT_ALLOWED});return}try{await k(this.storage)}catch{await this.sendError(t,{UploadErrorCode:g.STORAGE_ERROR});return}try{const a=await s.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))I(a,this.send.bind(this),t);else if(e.method==="GET"){const n=a;n&&X(n,e,t,r,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:i,...o}=a;this.logger?.debug("[%s]: %s: %d/%d",o.status,o.name,o.bytesWritten,o.size),o.status!==void 0&&this.listenerCount(o.status)>0&&this.emit(o.status,{...o,request:S(e,["headers","method","url"])}),o.status==="completed"?await q(a,e,t,r,this.storage,this.logger,(h,d,u)=>{this.finish(h,d,u)}):G(a,e,t,(h,d)=>{this.send(h,{body:d.body,headers:d.headers,statusCode:d.statusCode})})}}catch(a){await W(a,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}};send(e,{body:t="",headers:r={},statusCode:s=200}){let a;const n={...r};if(typeof t=="string"){if(a=t,n[m]===void 0)n[m]=T.createContentType({mediaType:"text/plain"});else{const i=Array.isArray(n[m])?n[m].join(", "):String(n[m]);n[m]=T.ensureCharset(i)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?a=t:(a=JSON.stringify(t),n[m]||(n[m]=T.createContentType({charset:"utf8",mediaType:"application/json"})));U(e,n),e.statusCode=s,e.end(a)}async sendError(e,t){let r;L(t)?r=this.internalErrorResponses[t.UploadErrorCode]:!j(t)&&!H.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 s;r.body?typeof r.body=="object"&&r.body!==null?s={body:r.body,headers:r.headers,statusCode:r.statusCode}:s={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}:s={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,s)}sendStream(e,t,{headers:r={},range:s,size:a,statusCode:n=200}){U(e,r),e.statusCode=n;let i=t;s&&a?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${s.start}-${s.end}/${a}`),e.setHeader("Content-Length",s.end-s.start+1),e.setHeader("Accept-Ranges","bytes"),i=D(t,s.start,s.end)):(a&&e.setHeader("Content-Length",a),e.setHeader("Accept-Ranges","bytes")),_(i,e,(o,h)=>this.sendError(o,h))}finish(e,t,r){const s="id"in r&&"headers"in r&&!("body"in r);let a,n,i;if(s){const o=r,h=o.headers||{},d=o.statusCode||200,{headers:u,statusCode:p,...y}=o;a=y,n={...h},i=d}else{const o=r;a=o.body,n=o.headers||{},i=o.statusCode||200}if(a&&typeof a=="object"&&a.content!==void 0){const{content:o,contentType:h}=a;a=o,n={...n,"Content-Type":h}}this.send(t,{body:a||r,headers:n,statusCode:i})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t,e.headers)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||x.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const r=v(O(e));if(r?.params.uuid){const{ext:s,metadata:a,uuid:n}=r.params,i=s?n.replace(new RegExp(String.raw`\.${s}$`),""):n;if(a==="metadata"&&O(e).endsWith("/metadata"))try{const o=await this.storage.getMeta(i);return{...o,content:JSON.stringify(o),headers:{"Content-Type":T.createContentType({charset:"utf8",mediaType:"application/json"}),...o.expiredAt===void 0?{}:{"X-Upload-Expires":o.expiredAt.toString()},...o.modifiedAt===void 0?{}:{"Last-Modified":o.modifiedAt.toString()}},statusCode:200}}catch(o){const h=o;throw h.UploadErrorCode===g.FILE_NOT_FOUND||h.UploadErrorCode===g.GONE?f(404,"File metadata not found"):o}if(!F.test(i))return this.list(e,t);try{const o=new URL(e.url||"","http://localhost"),h=Object.fromEntries(o.searchParams.entries());if(Object.keys(h).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const l=await this.mediaTransformer.handle(i,h);return{content:l.buffer,headers:{"Content-Length":String(l.size),"Content-Type":`${l.mediaType}/${l.format}`,"X-Media-Type":l.mediaType,"X-Original-Format":l.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":l.format,...l.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":l.originalFile.expiredAt.toString()},...l.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":l.originalFile.modifiedAt.toString()},...l.originalFile?.ETag===void 0?{}:{ETag:l.originalFile.ETag}},statusCode:200}}catch(l){if(l.name==="ValidationError")throw f(400,l.message);this.logger?.warn(`Media transformation failed: ${l.message}`)}const d=await this.storage.getMeta(i);if((e.headers.range||d.size&&d.size>1024*1024)&&this.storage.getStream)try{const l=await this.storage.getStream({id:i});let E=l.headers?.["Content-Type"]||d.contentType;return E.includes("image")&&typeof s=="string"&&(E=w.getType(s)||E),{headers:{...l.headers,"Accept-Ranges":"bytes","Content-Type":E},size:l.size,statusCode:200,stream:l.stream,...d,contentType:E}}catch(l){this.logger?.warn(`Streaming failed, falling back to buffer: ${l}`)}const u=await this.storage.get({id:i});let{contentType:p}=u;p.includes("image")&&typeof s=="string"&&(p=w.getType(s)||p);const{ETag:y,expiredAt:C,modifiedAt:b,size:A}=u;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(A),"Content-Type":p,...C===void 0?{}:{"X-Upload-Expires":C.toString()},...b===void 0?{}:{"Last-Modified":b.toString()},...y===void 0?{}:{ETag:y}},statusCode:200,...u,contentType:p}}catch(o){const h=o;throw h.UploadErrorCode===g.FILE_NOT_FOUND||h.UploadErrorCode===g.GONE?f(404,"File not found"):o}}return this.list(e,t)}async list(e,t){const r=new URL(e.url||"","http://localhost"),s=r.searchParams.get("limit"),a=r.searchParams.get("page"),n=await this.storage.list(Number(s||1e3));if(n.length===0)return{data:[],headers:{},statusCode:200};const i=Number(a),o=Number(s);return a!==null&&s!==null&&Number.isFinite(i)&&Number.isFinite(o)?{data:N(i,o,n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const r=v(O(e));if(!r?.params.uuid||!F.test(r.params.uuid))throw f(404,"File not found");const{ext:s,uuid:a}=r.params;try{const n=await this.storage.getMeta(a);if(!this.storage.getStream){await this.sendError(t,f(501,"Streaming download not supported"));return}const i=await this.storage.getStream({id:a});let o=i.headers?.["Content-Type"]||n.contentType;o.includes("image")&&typeof s=="string"&&(o=w.getType(s)||o);const h=this.parseRangeHeader(e.headers.range,i.size||0),d={...i.headers,"Accept-Ranges":"bytes","Content-Disposition":T.createContentDisposition({filename:n.originalName||a,type:"attachment"}),"Content-Type":o};this.sendStream(t,i.stream,{headers:d,range:h||void 0,size:i.size,statusCode:h?206:200})}catch(n){const i=n;if(i.UploadErrorCode===g.FILE_NOT_FOUND||i.UploadErrorCode===g.GONE){await this.sendError(t,f(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 f(404,"File not found")}}export{x as T};
@@ -1 +1 @@
1
- const l={backoffMultiplier:2,calculateDelay:void 0,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:()=>!1},m=(t,e,r,o)=>{const a=Math.min(e*r**t,o);return Math.floor(Math.random()*a)},R=t=>new Promise(e=>{setTimeout(e,t)}),b=(t,e=l.retryableStatusCodes)=>{if(t instanceof Error){const r=t.code,o=t.name;if(o==="AbortError"||r==="ABORT_ERR")return!1;if(r==="ECONNRESET"||r==="ETIMEDOUT"||r==="ENOTFOUND"||r==="ECONNREFUSED"||r==="EAI_AGAIN"||o==="NetworkError"||o==="TimeoutError")return!0;const a=t;if(a.$metadata){const n=a.$metadata.httpStatusCode;if(n&&e.includes(n)||a.$fault==="server")return!0}if(a.statusCode&&e.includes(a.statusCode))return!0;const{retryable:u}=a;return u===!0||typeof u=="string"&&u==="true"}return!1},D=async(t,e={})=>{const{backoffMultiplier:r=l.backoffMultiplier,calculateDelay:o=l.calculateDelay,initialDelay:a=l.initialDelay,maxDelay:u=l.maxDelay,maxRetries:n=l.maxRetries,onRetry:y,retryableStatusCodes:d=l.retryableStatusCodes,shouldRetry:E=l.shouldRetry}=e;let f;for(let s=0;s<=n;s+=1)try{return await t()}catch(i){if(f=i,s>=n)break;if(!(E(i)||b(i,d)))throw i;const c=o?o(s,i):m(s,a,r,u);if(y)try{y(s+1,i)}catch{}c!==void 0&&c>0&&await R(c)}throw f},h=(t={})=>e=>D(e,t);export{h as createRetryWrapper,b as isRetryableError,D as retry};
1
+ const i={backoffMultiplier:2,calculateDelay:void 0,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:()=>{}},m=(t,e,r,o)=>{const a=Math.min(e*r**t,o);return Math.floor(Math.random()*a)},R=t=>new Promise(e=>{setTimeout(e,t)}),b=(t,e=i.retryableStatusCodes)=>{if(t instanceof Error){const r=t.code,o=t.name;if(o==="AbortError"||r==="ABORT_ERR")return!1;if(r==="ECONNRESET"||r==="ETIMEDOUT"||r==="ENOTFOUND"||r==="ECONNREFUSED"||r==="EAI_AGAIN"||o==="NetworkError"||o==="TimeoutError")return!0;const a=t;if(a.$metadata){const n=a.$metadata.httpStatusCode;if(n&&e.includes(n)||a.$fault==="server")return!0}if(a.statusCode&&e.includes(a.statusCode))return!0;const{retryable:u}=a;return u===!0||typeof u=="string"&&u==="true"}return!1},D=async(t,e={})=>{const{backoffMultiplier:r=i.backoffMultiplier,calculateDelay:o=i.calculateDelay,initialDelay:a=i.initialDelay,maxDelay:u=i.maxDelay,maxRetries:n=i.maxRetries,onRetry:y,retryableStatusCodes:d=i.retryableStatusCodes,shouldRetry:E=i.shouldRetry}=e;let f;for(let l=0;l<=n;l+=1)try{return await t()}catch(s){if(f=s,l>=n)break;if(!(E(s)??b(s,d)))throw s;const c=o?o(l,s):m(l,a,r,u);if(y)try{y(l+1,s)}catch{}c!==void 0&&c>0&&await R(c)}throw f},h=(t={})=>e=>D(e,t);export{h as createRetryWrapper,b as isRetryableError,D as retry};
@@ -0,0 +1 @@
1
+ import{createReadStream as _,createWriteStream as C}from"node:fs";import{truncate as W,stat as S,open as L,copyFile as A}from"node:fs/promises";import{PassThrough as P,Transform as v,pipeline as U}from"node:stream";import{y as D,h as I,q as B,u as M,X as Q,j as V,d as H}from"./local-meta-storage-BELb1YwO.js";import{v as X,w as q}from"./path-C-OWflAo-_mqb5p5d.js";import{F as G}from"./index-nZWCQrSe.js";import{d as K}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as g,ERRORS as m,isUploadError as Y}from"./ERRORS-BIBxE2oR.js";import{createHash as j}from"node:crypto";import{B as J,a as Z,c as $}from"./storage-DR7qdwBN.js";import tt from"./File-W8aOo15X.js";import{t as k}from"./get-file-status-y3wTtDQs.js";import{t as et}from"./update-size-DuNuLyxj.js";import{i as rt}from"./part-match-D-9dGX42.js";import{e as it}from"./has-content-50BsqrWw.js";class st extends v{constructor(t,e,r="base64"){super(),this.checksum=t,this.algorithm=e,this.encoding=r,this.hash=j(e)}checksum;algorithm;encoding;length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(t,e,r){this.push(t),this.hash.update(t),this.length+=t.length,r()}_flush(t){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?t(new Error("Checksum mismatch")):t()}}const at=(b,t,e="base64")=>t?new st(b,t,e):new P;class nt extends v{constructor(t=Number.POSITIVE_INFINITY){super(),this.limit=t}limit;length=0;_transform(t,e,r){const a=this.length+t.length;this.limit>=a?(this.push(t),this.length=a,r()):r(new Error("Stream length limit exceeded"))}}class w extends J{static name="disk";checksumTypes=["md5","sha1"];supportsRange=!0;get raw(){return{directory:this.directory}}directory;meta;constructor(t){const e={...t,fileNameValidation:t.fileNameValidation??Z};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 D(r)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(r=>{this.logger?.error("Storage access check failed: %O",r)})}normalizeError(t){return super.normalizeError(t)}async create(t){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const i=typeof t.ttl=="string"?$(t.ttl):t.ttl;i!==void 0&&(e.expiredAt=Date.now()+i)}e.size!==void 0&&Number(e.size)<0&&g(m.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const r=new tt(e);try{const i=await this.getMeta(r.id);if(i.status==="completed")return i}catch{}r.name=this.namingFunction(r),(r.size===void 0||Number.isNaN(r.size))&&(r.size===void 0||(r.size=this.maxUploadSize)),await this.validate(r);const a=this.getFilePath(r.name);try{await I(a),r.bytesWritten=0}catch(i){const s=this.normalizeError(i instanceof Error?i:new Error(String(i)));await this.onError(s),g(m.FILE_ERROR,s.message)}return r.status=k(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(t){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&et(e,t.size),!rt(t,e))return g(m.FILE_CONFLICT);const r=this.getFilePath(e.name),a=await this.lock(r);try{const i=t.start||0;if(await I(r),e.bytesWritten===0&&(e.bytesWritten=i),it(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return g(m.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:c,stream:u}=await K(t.body);c?.mime&&(e.contentType=c.mime),t.body=u}catch{}const s=t.signal,o={...e,...t,body:t.body};s&&(o.signal=s);const[n,d]=await this.lazyWrite(o);if(d)return await W(r,e.bytesWritten),g(d);if(Number.isNaN(n)){const{size:c}=await S(r);e.bytesWritten=c}else{const c=i+(t.contentLength||0);e.bytesWritten=Math.max(e.bytesWritten||0,c),e.bytesWritten=Math.max(e.bytesWritten||0,n)}e.status=k(e),await this.saveMeta(e)}else await I(r),e.bytesWritten=0;return e}catch(i){if(Y(i))throw i;const s=this.normalizeError(i instanceof Error?i:new Error(String(i)));return await this.onError(s),g(m.FILE_ERROR,(typeof s.message=="string"?s.message:String(i))||String(i))}finally{await this.unlock(r,a)}})}async get({id:t},e){return this.instrumentOperation("get",async()=>{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:a,contentType:i,expiredAt:s,metadata:o,modifiedAt:n,name:d,originalName:c,size:u}=r,l=this.getFilePath(d),E=e?.range,N=async h=>{const y=h;if(y.code==="ENOENT"||y.code==="EPERM"){const p=this.normalizeError(h instanceof Error?h:new Error(y.message||String(h)));return await this.onError(p),g(m.FILE_NOT_FOUND,(typeof p.message=="string"?p.message:String(h))||String(h))}const f=this.normalizeError(h instanceof Error?h:new Error(String(h)));throw await this.onError(f),h};if(E){let h;try{h=await S(l)}catch(O){return N(O)}const y=h.size,f=Math.max(0,E.start),p=E.end===void 0?y-1:Math.min(y-1,E.end);if(f>p||f>=y)return g(m.BAD_REQUEST,`Invalid range ${f}-${E.end??""}`);const F=p-f+1,z=Buffer.allocUnsafe(F);let R;try{R=await L(l,"r"),await R.read(z,0,F,f)}catch(O){return N(O)}finally{await R?.close()}const x=`W/"${y.toString(16)}-${Math.trunc(h.mtimeMs).toString(16)}-${f}-${p}"`;return{content:z,contentType:i,ETag:x,expiredAt:s,id:t,metadata:o,modifiedAt:n,name:d,originalName:c,size:F}}let T;try{T=await B(l,{buffer:!0})}catch(h){return N(h)}return{content:T,contentType:i,ETag:G(T),expiredAt:s,id:t,metadata:o,modifiedAt:n,name:d,originalName:c,size:u||a}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{const e=await this.getMeta(t),r=this.getFilePath(e.name);return await S(r),!0}catch{return!1}})}async getStream({id:t}){return this.instrumentOperation("getStream",async()=>{try{const e=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:r,contentType:a,expiredAt:i,modifiedAt:s,name:o,size:n}=e,d=_(this.getFilePath(o));return{headers:{"Content-Length":String(n||r),"Content-Type":a,...i&&{"X-Upload-Expires":i.toString()},...s&&{"Last-Modified":s.toString()}},size:n||r,stream:d}}catch(e){const r=this.normalizeError(e instanceof Error?e:new Error(String(e)));throw await this.onError(r),g(m.FILE_NOT_FOUND,(typeof r.message=="string"?r.message:String(e))||String(e))}})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);await M(this.getFilePath(e.name)),await this.deleteMeta(t);const r={...e,status:"deleted"};return await this.onDelete(r),r})}async copy(t,e){return this.instrumentOperation("copy",async()=>{w.assertSafeId(t),w.assertSafeId(e);const r=await this.getMeta(t);return await A(this.getFilePath(r.name),this.getFilePath(e)),{...r,name:e}})}async move(t,e){return this.instrumentOperation("move",async()=>{w.assertSafeId(t),w.assertSafeId(e);const r=await this.getMeta(t),a=this.getFilePath(r.name),i=this.getFilePath(e);try{await Q(a,i)}catch(s){if(s?.code==="EXDEV")await A(a,i),await M(a);else{const o=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(o),s}}return{...r,id:r.id,name:e}})}async list(){return this.instrumentOperation("list",async()=>{const t={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},e=[],{directory:r}=this,a=s=>s.replaceAll("\\","/"),i=a(r);for await(const s of V(r,t)){const{suffix:o}=this.meta,{path:n}=s;if(!n.includes(o)){const{birthtime:d,ctime:c,mtime:u}=await S(n),l=a(n),E=l.startsWith(i)?l.slice(i.length):l;e.push({createdAt:d||c,id:E,modifiedAt:u})}}return e})}getFilePath(t){return w.assertSafeId(t),X(t)&&g(m.INVALID_FILE_NAME,`Invalid file id: "${t}"`),q(this.directory,t)}lazyWrite(t){return new Promise((e,r)=>{const a=C(this.getFilePath(t.name),{flags:"r+",start:t.start}),i=new nt(t.contentLength||t.size-t.start),s=at(t.checksum,t.checksumAlgorithm),o=!t.checksum,{signal:n}=t,d=()=>{a.close(),i.destroy(),s.destroy()},c=l=>{d(),e([Number.NaN,l])};if(i.on("error",()=>{c(m.FILE_CONFLICT)}),s.on("error",()=>{c(m.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{c(o?void 0:m.REQUEST_ABORTED)}),t.body.on("error",l=>{d(),r(l)}),n?.aborted){c(o?void 0:m.REQUEST_ABORTED);return}let u;n&&(u=()=>{d(),a.destroy(),i.destroy(),s.destroy(),t.body.destroy(),e([Number.NaN,o?void 0:m.REQUEST_ABORTED])},n.addEventListener("abort",u,{once:!0})),U(t.body,i,s,a,l=>{if(n&&u&&n.removeEventListener("abort",u),l){if(d(),n?.aborted){e([Number.NaN,o?void 0:m.REQUEST_ABORTED]);return}e([Number.NaN,m.FILE_ERROR]);return}e([t.start+a.bytesWritten])})})}async accessCheck(){await H(this.directory)}}export{nt as n,at as s,w};
@@ -0,0 +1,146 @@
1
+ import { F as File, M as MetaStorage, D as DiskStorageOptions, H as HttpError, d as FileInit, e as FilePart, f as FileQuery, O as OperationOptions, g as FileReturn, i as ERRORS, B as BaseStorage, j as DiskStorageWithChecksumOptions } from "./storage.d-DwdJrArF.js";
2
+ import { Readable } from 'node:stream';
3
+ /**
4
+ * Local disk-based storage implementation.
5
+ * @template TFile The file type used by this storage backend.
6
+ * @remarks
7
+ * ## Error Handling
8
+ * - Filesystem operations throw errors directly (no retry logic)
9
+ * - File not found errors are thrown immediately
10
+ * - Permission errors are propagated as-is
11
+ *
12
+ * ## Retry Behavior
13
+ * - No automatic retries (filesystem operations are typically immediate)
14
+ * - Errors are thrown directly for immediate feedback
15
+ *
16
+ * ## File Paths
17
+ * - Files are stored in the configured directory
18
+ * - Metadata files use the `.META` suffix by default
19
+ * - File paths are resolved relative to the storage directory
20
+ */
21
+ declare class DiskStorage<TFile extends File = File> extends BaseStorage<TFile> {
22
+ static override readonly name: string;
23
+ override checksumTypes: string[];
24
+ override readonly supportsRange: boolean;
25
+ override get raw(): {
26
+ directory: string;
27
+ };
28
+ directory: string;
29
+ meta: MetaStorage<TFile>;
30
+ constructor(config: DiskStorageOptions<TFile>);
31
+ /**
32
+ * Normalizes errors with disk storage context.
33
+ * @param error The error to normalize.
34
+ * @returns Normalized HTTP error.
35
+ */
36
+ override normalizeError(error: Error): HttpError;
37
+ /**
38
+ * Creates a new file upload and saves its metadata.
39
+ * @param fileInit File initialization configuration.
40
+ * @returns Promise resolving to the created file object.
41
+ * @throws {Error} If validation fails or file already exists and is completed.
42
+ * @remarks
43
+ * Supports TTL (time-to-live) option in fileInit.
44
+ * Creates the file on disk if it doesn't exist.
45
+ * Returns existing file if it's already completed.
46
+ */
47
+ create(fileInit: FileInit): Promise<TFile>;
48
+ /**
49
+ * Writes data to a file upload.
50
+ * @param part File part containing data to write, file query, or full file object.
51
+ * @returns Promise resolving to the updated file object.
52
+ * @throws {Error} If file is expired (ERRORS.GONE), locked (ERRORS.FILE_LOCKED), or conflicts occur (ERRORS.FILE_CONFLICT).
53
+ * @remarks
54
+ * Supports chunked uploads with start position.
55
+ * Automatically detects file type from stream on first chunk if contentType is not set.
56
+ * Validates checksum algorithms if provided.
57
+ * Uses file locking to prevent concurrent writes.
58
+ * Updates file status to "completed" when all bytes are written.
59
+ */
60
+ write(part: FilePart | FileQuery | TFile): Promise<TFile>;
61
+ /**
62
+ * Gets an uploaded file by ID.
63
+ * @param query File query containing the file ID to retrieve.
64
+ * @param query.id File ID to retrieve.
65
+ * @returns Promise resolving to the file data including content buffer.
66
+ * @throws {Error} If the file cannot be found (ERRORS.FILE_NOT_FOUND) or has expired (ERRORS.GONE).
67
+ * @remarks
68
+ * Loads the entire file content into memory as a Buffer.
69
+ * For large files, consider using getStream() instead.
70
+ * Includes ETag (MD5 hash) for content verification.
71
+ */
72
+ get({ id }: FileQuery, options?: OperationOptions & {
73
+ range?: {
74
+ end?: number;
75
+ start: number;
76
+ };
77
+ }): Promise<FileReturn>;
78
+ /**
79
+ * Checks if a file exists by verifying both metadata and the actual filesystem file.
80
+ * Returns true only if both the metadata and the file exist.
81
+ * @param query File query containing the file ID to check.
82
+ * @returns Promise resolving to true if both metadata and file exist, false otherwise.
83
+ */
84
+ override exists({ id }: FileQuery): Promise<boolean>;
85
+ /**
86
+ * Gets an uploaded file as a readable stream for efficient large file handling.
87
+ * @param query File query containing the file ID to stream.
88
+ * @param query.id File ID to stream.
89
+ * @returns Promise resolving to an object containing the stream, headers, and size.
90
+ * @throws {UploadError} If the file cannot be found (ERRORS.FILE_NOT_FOUND) or has expired (ERRORS.GONE).
91
+ * @remarks Creates a readable stream directly from the file system for efficient memory usage.
92
+ */
93
+ override getStream({ id }: FileQuery): Promise<{
94
+ headers?: Record<string, string>;
95
+ size?: number;
96
+ stream: Readable;
97
+ }>;
98
+ /**
99
+ * Deletes an upload and its metadata.
100
+ * @param query File query containing the file ID to delete.
101
+ * @param query.id File ID to delete.
102
+ * @returns Promise resolving to the deleted file object with status: "deleted".
103
+ * @throws {UploadError} If the file metadata cannot be found.
104
+ */
105
+ delete({ id }: FileQuery): Promise<TFile>;
106
+ /**
107
+ * Copies an upload file to a new location.
108
+ * @param name Source file name/ID.
109
+ * @param destination Destination file name/ID.
110
+ * @returns Promise resolving to the copied file object.
111
+ * @throws {UploadError} If the source file cannot be found.
112
+ */
113
+ copy(name: string, destination: string): Promise<TFile>;
114
+ /**
115
+ * Moves an upload file to a new location.
116
+ * @param name Source file name/ID.
117
+ * @param destination Destination file name/ID.
118
+ * @returns Promise resolving to the moved file object.
119
+ * @throws {Error} If the source file cannot be found.
120
+ */
121
+ move(name: string, destination: string): Promise<TFile>;
122
+ /**
123
+ * Retrieves a list of uploaded files.
124
+ * @returns Promise resolving to an array of file metadata objects.
125
+ * @remarks Walks the storage directory and returns all files, excluding metadata files.
126
+ */
127
+ override list(): Promise<TFile[]>;
128
+ /**
129
+ * Returns the absolute on-disk path for the uploaded file, always rooted at
130
+ * `this.directory`. Absolute inputs and `..` traversals are rejected.
131
+ */
132
+ protected getFilePath(filename: string): string;
133
+ protected lazyWrite(part: File & FilePart): Promise<[number, ERRORS?]>;
134
+ private accessCheck;
135
+ }
136
+ /**
137
+ * Additionally calculates checksum of the file/range.
138
+ */
139
+ declare class DiskStorageWithChecksum<TFile extends File = File> extends DiskStorage<TFile> {
140
+ private hashes;
141
+ constructor(config: DiskStorageWithChecksumOptions<TFile>);
142
+ override delete({ id }: FileQuery): Promise<TFile>;
143
+ override write(part: FilePart | FileQuery): Promise<TFile>;
144
+ protected override lazyWrite(part: File & FilePart): Promise<[number, ERRORS?]>;
145
+ }
146
+ export { DiskStorage as D, DiskStorageWithChecksum as a };
@@ -1,9 +1,10 @@
1
- import { F as Files } from "./files.d-CH0iLBNC.js";
1
+ import { F as Files } from "./files.d-CmSZi3M0.js";
2
2
  import 'node:stream';
3
+ import 'node:timers';
3
4
  import 'node:crypto';
4
5
  import 'node:http';
5
6
  import 'lru-cache';
6
- import { C as CopyFileInput, D as DeleteFileInput, a as DownloadFileInput, G as GetFileMetadataInput, b as GetFileUrlInput, L as ListFilesInput, S as SignUploadUrlInput, U as UploadFileInput } from "./approval.d-CMAYH9GF.js";
7
+ import { C as CopyFileInput, D as DeleteFileInput, a as DownloadFileInput, G as GetFileMetadataInput, b as GetFileUrlInput, L as ListFilesInput, S as SignUploadUrlInput, U as UploadFileInput } from "./approval.d-C-d-t94D.js";
7
8
  interface CopyFileResult {
8
9
  copied: true;
9
10
  etag: string | undefined;