@visulima/storage 1.0.0-alpha.32 → 1.0.0-alpha.34

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 (182) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +1 -1
  3. package/dist/adapter/nuxt/module.d.ts +4 -4
  4. package/dist/adapter/nuxt/node_modules/.bin/nuxi +2 -2
  5. package/dist/adapter/nuxt/node_modules/.bin/nuxt +2 -2
  6. package/dist/ai/ai-sdk/index.d.ts +3 -3
  7. package/dist/ai/ai-sdk/index.js +1 -1
  8. package/dist/ai/claude/index.d.ts +2 -2
  9. package/dist/ai/claude/index.js +1 -1
  10. package/dist/ai/openai/index.d.ts +3 -3
  11. package/dist/ai/openai/index.js +1 -1
  12. package/dist/ai/tanstack/index.d.ts +2 -2
  13. package/dist/ai/tanstack/index.js +1 -1
  14. package/dist/handler/http/fetch/index.d.ts +7 -7
  15. package/dist/handler/http/fetch/index.js +1 -1
  16. package/dist/handler/http/hono/index.d.ts +4 -4
  17. package/dist/handler/http/hono/index.js +1 -1
  18. package/dist/handler/http/nextjs/index.d.ts +4 -4
  19. package/dist/handler/http/nextjs/index.js +1 -1
  20. package/dist/handler/http/node/index.d.ts +7 -7
  21. package/dist/handler/http/node/index.js +1 -1
  22. package/dist/handler/http/solid-start/index.d.ts +4 -4
  23. package/dist/handler/http/solid-start/index.js +1 -1
  24. package/dist/index.d.ts +6 -6
  25. package/dist/index.js +1 -1
  26. package/dist/packem_shared/{AwsLightMetaStorage-B-iQbToR.js → AwsLightMetaStorage-Cj7ym1qI.js} +1 -1
  27. package/dist/packem_shared/{AwsLightStorage-B1jNF7sv.js → AwsLightStorage-CWBRVcn5.js} +1 -1
  28. package/dist/packem_shared/AzureSMetaStorage-YCj-X8a1.js +1 -0
  29. package/dist/packem_shared/AzureStorage-nhAojuEU.js +1 -0
  30. package/dist/packem_shared/{BoxMetaStorage-nESVquA1.js → BoxMetaStorage-XMZn5yvp.js} +1 -1
  31. package/dist/packem_shared/{BoxStorage-CHYDrcxw.js → BoxStorage-C3--16du.js} +1 -1
  32. package/dist/packem_shared/{BunS3MetaStorage-BkZx5q4w.js → BunS3MetaStorage-DomG8mVK.js} +1 -1
  33. package/dist/packem_shared/BunS3Storage-0oYNi2Os.js +1 -0
  34. package/dist/packem_shared/{BunnyMetaStorage-bB8NXGUI.js → BunnyMetaStorage-luemw1pL.js} +1 -1
  35. package/dist/packem_shared/BunnyStorage-CIkpp1Rc.js +1 -0
  36. package/dist/packem_shared/{CloudinaryMetaStorage-BzibHydK.js → CloudinaryMetaStorage-DpxjshXZ.js} +1 -1
  37. package/dist/packem_shared/{CloudinaryStorage-Cj00ZXWV.js → CloudinaryStorage-9Y1Gq0gr.js} +1 -1
  38. package/dist/packem_shared/DiskStorage-BkP8c0MY.js +1 -0
  39. package/dist/packem_shared/{DiskStorageWithChecksum-BX85CHJ6.js → DiskStorageWithChecksum-CUXj5mE9.js} +1 -1
  40. package/dist/packem_shared/{DropboxMetaStorage-Bfm5bblb.js → DropboxMetaStorage-h0eTJuk5.js} +1 -1
  41. package/dist/packem_shared/{DropboxStorage-Btz9h9Mj.js → DropboxStorage-CuA9MkpH.js} +1 -1
  42. package/dist/packem_shared/ERRORS-vMSqlI69.js +1 -0
  43. package/dist/packem_shared/{FirebaseMetaStorage-CshnJMb0.js → FirebaseMetaStorage-CCBnEE8_.js} +1 -1
  44. package/dist/packem_shared/FirebaseStorage-DUskfjh_.js +2 -0
  45. package/dist/packem_shared/{FtpMetaStorage-CoyWJafY.js → FtpMetaStorage-DxHcXk9x.js} +1 -1
  46. package/dist/packem_shared/FtpStorage-DMpDY7oG.js +1 -0
  47. package/dist/packem_shared/{GCSMetaStorage-CfZj52hQ.js → GCSMetaStorage-DCBR02C7.js} +1 -1
  48. package/dist/packem_shared/GCStorage-RCw58CoD.js +1 -0
  49. package/dist/packem_shared/{GoogleDriveMetaStorage-CBSdEQr6.js → GoogleDriveMetaStorage-koEiYfFw.js} +1 -1
  50. package/dist/packem_shared/GoogleDriveStorage-DNlVE5Uo.js +1 -0
  51. package/dist/packem_shared/LocalMetaStorage-BKC34woF.js +1 -0
  52. package/dist/packem_shared/MemoryStorage-CgEFb9yw.js +1 -0
  53. package/dist/packem_shared/{Multipart-qaEOWKz1.js → Multipart-D2eF0kMq.js} +1 -1
  54. package/dist/packem_shared/{Multipart-kQ5wJQaV.js → Multipart-mlcj2Wm8.js} +1 -1
  55. package/dist/packem_shared/{NetlifyBlobMetaStorage-CqluIgV0.js → NetlifyBlobMetaStorage-DLJLr0fD.js} +1 -1
  56. package/dist/packem_shared/{NetlifyBlobStorage-CkMw9Uyv.js → NetlifyBlobStorage-DqeW_OGE.js} +1 -1
  57. package/dist/packem_shared/{OneDriveMetaStorage-DPTNMpeq.js → OneDriveMetaStorage-Cuw5g3cr.js} +1 -1
  58. package/dist/packem_shared/OneDriveStorage-D41BZtkz.js +1 -0
  59. package/dist/packem_shared/{PocketBaseMetaStorage-CemTT_01.js → PocketBaseMetaStorage-BkzeMDP0.js} +1 -1
  60. package/dist/packem_shared/{PocketBaseStorage-BZNzWj09.js → PocketBaseStorage-CdvEL3YX.js} +1 -1
  61. package/dist/packem_shared/{Rest-BAcUFAgk.js → Rest-08Oi3-WZ.js} +1 -1
  62. package/dist/packem_shared/{Rest-DukkeDZe.js → Rest-BpyZYW-e.js} +1 -1
  63. package/dist/packem_shared/S3Storage-adY1XLfH.js +1 -0
  64. package/dist/packem_shared/{SftpMetaStorage-Cs8b7uBO.js → SftpMetaStorage-DN00oxqH.js} +1 -1
  65. package/dist/packem_shared/SftpStorage-CDKtnw6a.js +1 -0
  66. package/dist/packem_shared/{SharePointMetaStorage-DTVKAx6f.js → SharePointMetaStorage-WkQcni-I.js} +1 -1
  67. package/dist/packem_shared/{SharePointStorage-D1cWu-14.js → SharePointStorage-CZkO7FSl.js} +1 -1
  68. package/dist/packem_shared/{SupabaseMetaStorage-D_fGv0d6.js → SupabaseMetaStorage-FaEVpmT5.js} +1 -1
  69. package/dist/packem_shared/SupabaseStorage-O29RNXWx.js +1 -0
  70. package/dist/packem_shared/{Tus-BYTcw17H.js → Tus-B7k9LUeY.js} +1 -1
  71. package/dist/packem_shared/{Tus-BrP4RFTg.js → Tus-BZT2Jhl5.js} +1 -1
  72. package/dist/packem_shared/UploadControl-jgusdgDN.js +1 -0
  73. package/dist/packem_shared/{UploadThingMetaStorage-CAQ1uTfv.js → UploadThingMetaStorage-CdDfhiyy.js} +1 -1
  74. package/dist/packem_shared/UploadThingStorage-ByryGerX.js +1 -0
  75. package/dist/packem_shared/{VercelBlobMetaStorage-DY4zAB6M.js → VercelBlobMetaStorage-CC1zy35k.js} +1 -1
  76. package/dist/packem_shared/{VercelBlobStorage-u6xmp8ox.js → VercelBlobStorage-C4QUjBfu.js} +1 -1
  77. package/dist/packem_shared/{agentsListFiles-R-CnGKc4.js → agentsListFiles-Bl2TOnMy.js} +1 -1
  78. package/dist/packem_shared/aws-light-meta-storage-CXIZfLXR.js +4 -0
  79. package/dist/packem_shared/{azure-meta-storage-C4SrMtT2.js → azure-meta-storage-B-D-tBVw.js} +1 -1
  80. package/dist/packem_shared/{base-handler-core-Ccvdhx-k.js → base-handler-core-ty4J6Ji6.js} +1 -1
  81. package/dist/packem_shared/{base-handler-fetch-DzbThEWy.js → base-handler-fetch-BAjJyP84.js} +1 -1
  82. package/dist/packem_shared/{base-handler-node-CmCpLlBt.js → base-handler-node-BCqhH22o.js} +1 -1
  83. package/dist/packem_shared/{claudeListFiles-DAezbKEi.js → claudeListFiles-yLqM5iFS.js} +1 -1
  84. package/dist/packem_shared/{createResponsesFileTools-BCep-qdO.js → createResponsesFileTools-DFFHq35s.js} +1 -1
  85. package/dist/packem_shared/{defaultCloudStorageFileNameValidation-DwDn0XB5.js → defaultCloudStorageFileNameValidation-DSAf6C4S.js} +1 -1
  86. package/dist/packem_shared/detect-file-type-DRWGvQW4.js +1 -0
  87. package/dist/packem_shared/disk-storage-DJ2Nic2v.js +1 -0
  88. package/dist/packem_shared/{disk-storage-with-checksum.d-aYBmkg45.d.ts → disk-storage-with-checksum.d-BT_ll5b8.d.ts} +1 -1
  89. package/dist/packem_shared/executors-MzQbS9FT.js +1 -0
  90. package/dist/packem_shared/{executors.d-WGJGPSZs.d.ts → executors.d-D8esmhum.d.ts} +1 -1
  91. package/dist/packem_shared/{gcs-meta-storage-COq32th7.js → gcs-meta-storage-BXcsC7xV.js} +1 -1
  92. package/dist/packem_shared/{index.d-CYdFIB-w.d.ts → index.d-DB1VD8RP.d.ts} +229 -12
  93. package/dist/packem_shared/{listFiles-BtP6VnUp.js → listFiles-BNGQbV_d.js} +1 -1
  94. package/dist/packem_shared/{listFiles-B6VF05d-.js → listFiles-BdBngq3i.js} +1 -1
  95. package/dist/packem_shared/local-meta-storage-tayO1ARY.js +1 -0
  96. package/dist/packem_shared/{local-meta-storage.d-CuvN-KQ3.d.ts → local-meta-storage.d-DUuLtPik.d.ts} +1 -1
  97. package/dist/packem_shared/{media-transformer.d-DfU7VbFl.d.ts → media-transformer.d-B9dfBdoV.d.ts} +2 -2
  98. package/dist/packem_shared/{memory-storage.d-DRbE0WMO.d.ts → memory-storage.d-BpxSYO-D.d.ts} +1 -1
  99. package/dist/packem_shared/{path-D7rMc9nq-CPbxyMDy.js → path-D7rMc9nq-B718mbm6.js} +1 -1
  100. package/dist/packem_shared/{rest-base-xrnOBxS9.js → rest-base-BG0e-6E0.js} +1 -1
  101. package/dist/packem_shared/s3-base-storage-FiC4s91g.js +1 -0
  102. package/dist/packem_shared/{s3-base-storage.d-BrHiKWFw.d.ts → s3-base-storage.d-CoYAf_hG.d.ts} +21 -1
  103. package/dist/packem_shared/storage-CI88PmRw.js +1 -0
  104. package/dist/packem_shared/{storage.d-X6TimMHY.d.ts → storage.d-C6HtvSoY.d.ts} +43 -1
  105. package/dist/packem_shared/{tus-base.d-Ds7xYAJC.d.ts → tus-base.d-Dv25OXL0.d.ts} +3 -3
  106. package/dist/packem_shared/{types.d-a1grKnaX.d.ts → types.d-Cd2-3e-F.d.ts} +1 -1
  107. package/dist/packem_shared/{types.d-B72PbsLY.d.ts → types.d-CmBrgo0d.d.ts} +2 -2
  108. package/dist/packem_shared/{types.d-C4QumoP1.d.ts → types.d-CmT_ubPu.d.ts} +2 -2
  109. package/dist/storage/aws/index.d.ts +7 -2
  110. package/dist/storage/aws/index.js +1 -1
  111. package/dist/storage/aws-light/index.d.ts +7 -2
  112. package/dist/storage/aws-light/index.js +1 -1
  113. package/dist/storage/azure/index.d.ts +26 -7
  114. package/dist/storage/azure/index.js +1 -1
  115. package/dist/storage/box/index.d.ts +2 -2
  116. package/dist/storage/box/index.js +1 -1
  117. package/dist/storage/bun-s3/index.d.ts +2 -2
  118. package/dist/storage/bun-s3/index.js +1 -1
  119. package/dist/storage/bunny/index.d.ts +2 -2
  120. package/dist/storage/bunny/index.js +1 -1
  121. package/dist/storage/cloudinary/index.d.ts +2 -2
  122. package/dist/storage/cloudinary/index.js +1 -1
  123. package/dist/storage/dropbox/index.d.ts +2 -2
  124. package/dist/storage/dropbox/index.js +1 -1
  125. package/dist/storage/firebase/index.d.ts +2 -2
  126. package/dist/storage/firebase/index.js +1 -1
  127. package/dist/storage/ftp/index.d.ts +9 -3
  128. package/dist/storage/ftp/index.js +1 -1
  129. package/dist/storage/gcs/index.d.ts +15 -1
  130. package/dist/storage/gcs/index.js +1 -1
  131. package/dist/storage/google-drive/index.d.ts +2 -2
  132. package/dist/storage/google-drive/index.js +1 -1
  133. package/dist/storage/local/index.d.ts +3 -3
  134. package/dist/storage/local/index.js +1 -1
  135. package/dist/storage/memory/index.d.ts +2 -2
  136. package/dist/storage/memory/index.js +1 -1
  137. package/dist/storage/netlify-blob/index.d.ts +2 -2
  138. package/dist/storage/netlify-blob/index.js +1 -1
  139. package/dist/storage/onedrive/index.d.ts +4 -4
  140. package/dist/storage/onedrive/index.js +1 -1
  141. package/dist/storage/pocketbase/index.d.ts +2 -2
  142. package/dist/storage/pocketbase/index.js +1 -1
  143. package/dist/storage/sftp/index.d.ts +9 -3
  144. package/dist/storage/sftp/index.js +1 -1
  145. package/dist/storage/sharepoint/index.d.ts +3 -3
  146. package/dist/storage/sharepoint/index.js +1 -1
  147. package/dist/storage/supabase/index.d.ts +3 -3
  148. package/dist/storage/supabase/index.js +1 -1
  149. package/dist/storage/uploadthing/index.d.ts +2 -2
  150. package/dist/storage/uploadthing/index.js +1 -1
  151. package/dist/storage/vercel-blob/index.d.ts +2 -2
  152. package/dist/storage/vercel-blob/index.js +1 -1
  153. package/dist/transformer/audio-transformer.d.ts +2 -2
  154. package/dist/transformer/image-transformer.d.ts +2 -2
  155. package/dist/transformer/index.d.ts +3 -3
  156. package/dist/transformer/video-transformer.d.ts +2 -2
  157. package/package.json +2 -2
  158. package/dist/packem_shared/AzureSMetaStorage-CR-lfQNQ.js +0 -1
  159. package/dist/packem_shared/AzureStorage-B4E6VLn5.js +0 -1
  160. package/dist/packem_shared/BunS3Storage-BopE7kmX.js +0 -1
  161. package/dist/packem_shared/BunnyStorage-C3IBxJqr.js +0 -1
  162. package/dist/packem_shared/DiskStorage-BrAb28Je.js +0 -1
  163. package/dist/packem_shared/ERRORS-CyOuSMLY.js +0 -1
  164. package/dist/packem_shared/Files-tnc_buzM.js +0 -1
  165. package/dist/packem_shared/FirebaseStorage-Y9P6Dx8I.js +0 -2
  166. package/dist/packem_shared/FtpStorage-DCKPMX0z.js +0 -1
  167. package/dist/packem_shared/GCStorage-hfL1u2KQ.js +0 -1
  168. package/dist/packem_shared/GoogleDriveStorage-C7iuV7qb.js +0 -1
  169. package/dist/packem_shared/LocalMetaStorage-DSwsmdt7.js +0 -1
  170. package/dist/packem_shared/OneDriveStorage-CEGYb6OC.js +0 -1
  171. package/dist/packem_shared/S3Storage-7hG3izjU.js +0 -1
  172. package/dist/packem_shared/SftpStorage-DnigT9GT.js +0 -1
  173. package/dist/packem_shared/SupabaseStorage-DbIUa6NZ.js +0 -1
  174. package/dist/packem_shared/UploadThingStorage-B1qw1GrM.js +0 -1
  175. package/dist/packem_shared/aws-light-meta-storage-CstQBYXG.js +0 -4
  176. package/dist/packem_shared/default-BrhEhSqN.js +0 -1
  177. package/dist/packem_shared/detect-file-type-5JhzC9RU.js +0 -1
  178. package/dist/packem_shared/disk-storage-fWizVrge.js +0 -1
  179. package/dist/packem_shared/executors-DG6hGtvm.js +0 -1
  180. package/dist/packem_shared/local-meta-storage-Dr891Iy7.js +0 -1
  181. package/dist/packem_shared/s3-base-storage-CqAyWHR6.js +0 -1
  182. package/dist/packem_shared/storage-uhIhcN-O.js +0 -1
@@ -1 +1 @@
1
- var I=Object.defineProperty;var h=(i,e)=>I(i,"name",{value:e,configurable:!0});import{throwErrorCode as c,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import u,{buildGraphClient as g}from"./OneDriveStorage-CEGYb6OC.js";import{B as v}from"./storage-uhIhcN-O.js";import E from"./SharePointMetaStorage-DTVKAx6f.js";var m=Object.defineProperty,l=h((i,e)=>m(i,"name",{value:e,configurable:!0}),"d");const p=l(i=>{if(!i)return;const e=i.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},"webUrlLeaf"),S=l(i=>{let e;try{e=new URL(i)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${i}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}},"parseSiteUrl");class C extends v{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 o=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,a=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,n=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(o&&a&&n)return{clientId:a,clientSecret:n,tenantId:o}})();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=g(this.oneDriveAuth),this.meta=e.metaStorage??new E(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:o,sitePath:a,siteUrl:n,...s}=this.genericConfig;return new u({...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 o=await this.client.api(`/sites/${t}/drives`).get(),a=e.documentLibrary.toLowerCase(),n=(o.value??[]).find(s=>s.name===e.documentLibrary)??(o.value??[]).find(s=>s.name?.toLowerCase()===a||p(s.webUrl)?.toLowerCase()===a);return n?n.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}=S(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 o=r==="/"?"":r.replace(/^\/+/,""),a=o?`/sites/${t}:/${o}`:`/sites/${t}`;let n;try{n=await this.client.api(a).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 n?.id?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{C as default};
1
+ var I=Object.defineProperty;var h=(i,e)=>I(i,"name",{value:e,configurable:!0});import{throwErrorCode as c,ERRORS as d}from"./ERRORS-vMSqlI69.js";import u,{buildGraphClient as g}from"./OneDriveStorage-D41BZtkz.js";import{B as v}from"./storage-CI88PmRw.js";import E from"./SharePointMetaStorage-WkQcni-I.js";var m=Object.defineProperty,l=h((i,e)=>m(i,"name",{value:e,configurable:!0}),"d");const p=l(i=>{if(!i)return;const e=i.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},"webUrlLeaf"),S=l(i=>{let e;try{e=new URL(i)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${i}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}},"parseSiteUrl");class C extends v{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 o=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,a=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,n=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(o&&a&&n)return{clientId:a,clientSecret:n,tenantId:o}})();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=g(this.oneDriveAuth),this.meta=e.metaStorage??new E(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:o,sitePath:a,siteUrl:n,...s}=this.genericConfig;return new u({...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 o=await this.client.api(`/sites/${t}/drives`).get(),a=e.documentLibrary.toLowerCase(),n=(o.value??[]).find(s=>s.name===e.documentLibrary)??(o.value??[]).find(s=>s.name?.toLowerCase()===a||p(s.webUrl)?.toLowerCase()===a);return n?n.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}=S(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 o=r==="/"?"":r.replace(/^\/+/,""),a=o?`/sites/${t}:/${o}`:`/sites/${t}`;let n;try{n=await this.client.api(a).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 n?.id?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{C as default};
@@ -1 +1 @@
1
- var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-Dr891Iy7.js";var o=Object.defineProperty,u=a((t,e)=>o(t,"name",{value:e,configurable:!0}),"t");class i extends s{static{a(this,"p")}static{u(this,"SupabaseMetaStorage")}constructor(e){super(e)}}export{i as default};
1
+ var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-tayO1ARY.js";var o=Object.defineProperty,u=a((t,e)=>o(t,"name",{value:e,configurable:!0}),"t");class i extends s{static{a(this,"p")}static{u(this,"SupabaseMetaStorage")}constructor(e){super(e)}}export{i as default};
@@ -0,0 +1 @@
1
+ var g=Object.defineProperty;var d=(o,t)=>g(o,"name",{value:t,configurable:!0});import{StorageClient as w}from"@supabase/storage-js";import{throwErrorCode as u,ERRORS as h}from"./ERRORS-vMSqlI69.js";import{B as y}from"./storage-CI88PmRw.js";import c from"./SupabaseFile-DZ1iv9gM.js";import b from"./SupabaseMetaStorage-FaEVpmT5.js";import{o as l}from"./get-file-status-DLS18Zvd.js";import{u as E}from"./update-size-DANV7aa2.js";import{r as S}from"./part-match-D_NwyoF3.js";import{o as k}from"./has-content-Bx2p8Okx.js";var U=Object.defineProperty,p=d((o,t)=>U(o,"name",{value:t,configurable:!0}),"p");const f=3600*24*7,O=p(o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const t=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=t?.[1]??t?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},"parseDownloadOption"),C=p(async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream");class I extends y{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(t){if(super(t),this.bucket=t.bucket,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,f),t.client)this.storageClient=t.client;else{const a=t.url??process.env.SUPABASE_URL,e=t.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(!e)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 w(i,{apikey:e,Authorization:`Bearer ${e}`},t.fetch)}this.meta=t.metaStorage??new b(t.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucket,e.path=e.name,await this.validate(e);try{const i=await this.getMeta(e.id);if(i.bytesWritten>=0)return i}catch{}return e.bytesWritten=0,e.status=l(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&E(e,t.size),!S(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(k(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await C(t.body),n=e.path??e.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,r,{contentType:e.contentType,upsert:!0}));if(m)throw m;e.bytesWritten=r.length,e.size=r.length,e.path=s?.path??n,e.ETag=s?.id}return e.status=l(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,i)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const i=e?.path??e?.name??t,{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 e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.bucket,id:t,name:t,path:i,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}const{data:i,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(e));return r?!1:!!i})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,i;try{i=await this.checkIfExpired(await this.getMeta(t)),e=i.path??i.name??t}catch{}const{data:r,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(e));if(n||!r)throw n??new Error(`Supabase: object not found at "${e}"`);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:t,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt,name:i?.name??e,originalName:i?.originalName??e,size:i?.size??s.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t,r=a,{error:n}=await this.runOperation(e,()=>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(t,a,e){return this.instrumentOperation("move",async()=>{const i=(await this.getMetaSafe(t))?.path??t,{error:r}=await this.runOperation(e,()=>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(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const{data:e,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:t}));if(i)throw i;return(e??[]).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:t})}async getReadUrl(t,a){const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{data:i,error:r}=await this.storageClient.from(this.bucket).createSignedUrl(t,e,{download:O(a?.responseContentDisposition)});return r||!i?u(h.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUrl failed"):i.signedUrl}async getUploadUrl(t,a){if(a?.contentType!==void 0||a?.contentLength!==void 0)return u(h.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:e,error:i}=await this.storageClient.from(this.bucket).createSignedUploadUrl(t);return i||!e?u(h.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUploadUrl failed"):e.signedUrl}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=p(t=>this.deleteMeta(t.id),"internalOnComplete")}export{I as default};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var g=(i,e)=>E(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{B as w}from"./storage-uhIhcN-O.js";import{O as B}from"./base-handler-fetch-DzbThEWy.js";import{TusBase as H,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as k}from"./TUS_RESUMABLE-B7KtPVeC.js";var R=Object.defineProperty,b=g((i,e)=>R(i,"name",{value:e,configurable:!0}),"g");const l=b(i=>{let e;try{const t=new URL(i).pathname.split("/").filter(Boolean);e=t[t.length-1]||void 0}catch{return}if(e){try{w.assertSafeId(e)}catch{throw a(400,`Invalid file id: "${e}"`)}return e}},"getIdFromRequestUrl");class T extends B{static{g(this,"Tus")}static{b(this,"Tus")}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 H{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",O),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})}async options(){return this.tusBase.handleOptions(T.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,u=e.headers.get("content-type")||"",n=e.headers.get("content-length"),h=n?Number.parseInt(n,10):0,c=e.url,p=e.body;return this.tusBase.handlePost(s,r,o,d,c,p,h,u)}async patch(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(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),u=e.headers.get("upload-length")||void 0,n=e.headers.get("upload-metadata")||void 0,h=e.headers.get("content-length"),c=h?Number.parseInt(h,10):0,p=e.headers.get("upload-checksum")||void 0,{checksum:U,checksumAlgorithm:F}=this.tusBase.extractChecksum(p),v=e.url,y=e.body;try{return this.tusBase.handlePatch(s,d,u,n,U,F,v,y,c)}catch(m){const f=m;throw f.UploadErrorCode==="GONE"||f.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):m}}async head(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(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=l(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=l(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{O as TUS_RESUMABLE,k as TUS_VERSION,T as Tus};
1
+ var E=Object.defineProperty;var g=(i,e)=>E(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{B as w}from"./storage-CI88PmRw.js";import{O as B}from"./base-handler-fetch-BAjJyP84.js";import{TusBase as H,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as k}from"./TUS_RESUMABLE-B7KtPVeC.js";var R=Object.defineProperty,b=g((i,e)=>R(i,"name",{value:e,configurable:!0}),"g");const l=b(i=>{let e;try{const t=new URL(i).pathname.split("/").filter(Boolean);e=t[t.length-1]||void 0}catch{return}if(e){try{w.assertSafeId(e)}catch{throw a(400,`Invalid file id: "${e}"`)}return e}},"getIdFromRequestUrl");class T extends B{static{g(this,"Tus")}static{b(this,"Tus")}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 H{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",O),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})}async options(){return this.tusBase.handleOptions(T.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,u=e.headers.get("content-type")||"",n=e.headers.get("content-length"),h=n?Number.parseInt(n,10):0,c=e.url,p=e.body;return this.tusBase.handlePost(s,r,o,d,c,p,h,u)}async patch(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(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),u=e.headers.get("upload-length")||void 0,n=e.headers.get("upload-metadata")||void 0,h=e.headers.get("content-length"),c=h?Number.parseInt(h,10):0,p=e.headers.get("upload-checksum")||void 0,{checksum:U,checksumAlgorithm:F}=this.tusBase.extractChecksum(p),v=e.url,y=e.body;try{return this.tusBase.handlePatch(s,d,u,n,U,F,v,y,c)}catch(m){const f=m;throw f.UploadErrorCode==="GONE"||f.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):m}}async head(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(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=l(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=l(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{O as TUS_RESUMABLE,k as TUS_VERSION,T as Tus};
@@ -1 +1 @@
1
- var U=Object.defineProperty;var p=(h,e)=>U(h,"name",{value:e,configurable:!0});import{format as F}from"node:url";import{n as d}from"./headers-DC2MEOrK.js";import{a,b as m,g as n,c as T}from"./base-handler-core-Ccvdhx-k.js";import{F as E}from"./base-handler-node-CmCpLlBt.js";import{TusBase as y,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as w}from"./TUS_RESUMABLE-B7KtPVeC.js";var B=Object.defineProperty,H=p((h,e)=>B(h,"name",{value:e,configurable:!0}),"h");class g extends E{static{p(this,"Tus")}static{H(this,"Tus")}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 y{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(g.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")||"",l=Number.parseInt(a(e,"content-length")||"0",10),u=e.originalUrl||e.url||"",c=m(e);return this.tusBase.handlePost(t,s,r,o,u,c,l,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")),l=a(e,"upload-checksum"),{checksum:u,checksumAlgorithm:c}=this.tusBase.extractChecksum(l),b=e.originalUrl||e.url||"",f=m(e);return this.tusBase.handlePatch(t,s,r,o,u,c,b,f,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":O},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=F({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:T({url:e})+i}}export{O as TUS_RESUMABLE,w as TUS_VERSION,g as Tus};
1
+ var U=Object.defineProperty;var p=(h,e)=>U(h,"name",{value:e,configurable:!0});import{format as F}from"node:url";import{n as d}from"./headers-DC2MEOrK.js";import{a,b as m,g as n,c as T}from"./base-handler-core-ty4J6Ji6.js";import{F as E}from"./base-handler-node-BCqhH22o.js";import{TusBase as y,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as w}from"./TUS_RESUMABLE-B7KtPVeC.js";var B=Object.defineProperty,H=p((h,e)=>B(h,"name",{value:e,configurable:!0}),"h");class g extends E{static{p(this,"Tus")}static{H(this,"Tus")}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 y{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(g.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")||"",l=Number.parseInt(a(e,"content-length")||"0",10),u=e.originalUrl||e.url||"",c=m(e);return this.tusBase.handlePost(t,s,r,o,u,c,l,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")),l=a(e,"upload-checksum"),{checksum:u,checksumAlgorithm:c}=this.tusBase.extractChecksum(l),b=e.originalUrl||e.url||"",f=m(e);return this.tusBase.handlePatch(t,s,r,o,u,c,b,f,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":O},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=F({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:T({url:e})+i}}export{O as TUS_RESUMABLE,w as TUS_VERSION,g as Tus};
@@ -0,0 +1 @@
1
+ var V=Object.defineProperty;var C=(s,t)=>V(s,"name",{value:t,configurable:!0});import{PassThrough as J,Readable as R}from"node:stream";import{B as P}from"./storage-CI88PmRw.js";import{throwErrorCode as W,ERRORS as K}from"./ERRORS-vMSqlI69.js";var Y=Object.defineProperty,m=C((s,t)=>Y(s,"name",{value:t,configurable:!0}),"y");class ${static{C(this,"UploadControl")}static{m(this,"UploadControl")}key;controller=new AbortController;internalState="idle";loadedBytes;startPaused=!1;boundStream;constructor(t){this.loadedBytes=t?.loaded??0,this.key=t?.key}static from(t){const e=typeof t=="string"?JSON.parse(t):t;return new $({key:e.key,loaded:e.loaded})}get signal(){return this.controller.signal}get state(){return this.internalState}get loaded(){return this.loadedBytes}pause(){(this.internalState==="uploading"||this.internalState==="idle")&&(this.internalState="paused",this.startPaused=!0,this.boundStream?.pause())}resume(){this.internalState==="paused"&&(this.internalState="uploading",this.startPaused=!1,this.boundStream?.resume())}abort(t){this.internalState!=="completed"&&this.internalState!=="aborted"&&(this.internalState="aborted",this.controller.abort(t))}serialize(){return{key:this.key,loaded:this.loadedBytes,version:1}}_bind(t,e){this.boundStream=t,this.key??=e,this.internalState!=="aborted"&&(this.internalState=this.startPaused?"paused":"uploading"),this.startPaused&&t.pause()}_progress(t){this.loadedBytes=t}_complete(){this.internalState!=="aborted"&&(this.internalState="completed"),this.boundStream=void 0}}const U=8,q=m(s=>typeof s=="object"&&s!==null&&typeof s.getReader=="function","isWebReadableStream"),G=m(s=>typeof s=="object"&&s!==null&&typeof s.pipe=="function"&&typeof s.read=="function","isNodeReadable"),Q=m(async(s,t)=>{if(typeof s=="string"){const e=Buffer.from(s);return{size:e.byteLength,stream:R.from(e)}}if(Buffer.isBuffer(s))return{size:s.byteLength,stream:R.from(s)};if(s instanceof Uint8Array){const e=Buffer.from(s.buffer,s.byteOffset,s.byteLength);return{size:e.byteLength,stream:R.from(e)}}if(s instanceof ArrayBuffer){const e=Buffer.from(s);return{size:e.byteLength,stream:R.from(e)}}if(ArrayBuffer.isView(s)){const e=s,r=Buffer.from(e.buffer,e.byteOffset,e.byteLength);return{size:r.byteLength,stream:R.from(r)}}if(typeof Blob<"u"&&s instanceof Blob)return{size:s.size,stream:R.fromWeb(s.stream())};if(q(s))return{size:t,stream:R.fromWeb(s)};if(G(s))return{size:t,stream:s};throw new TypeError(`Unsupported body type: ${Object.prototype.toString.call(s)}`)},"normalizeBody"),I=m((s,t)=>({contentType:s.contentType??"application/octet-stream",etag:s.ETag,key:s.name||s.id||t||"",lastModified:s.modifiedAt??s.createdAt,metadata:s.metadata,size:typeof s.size=="number"?s.size:void 0}),"toFileObject"),j=m((s,t)=>{s.split("/").some(e=>e==="."||e==="..")&&W(K.INVALID_FILE_NAME,`${K.INVALID_FILE_NAME}: ${t} must not contain "." or ".." path segments: "${s}"`)},"assertNoRelativeSegments"),X=m(s=>{if(!s)return"";const t=s.split("/").filter(e=>e.length>0).join("/");return j(t,"prefix"),t},"normalizePrefix"),Z=m((s,t)=>{if(!t&&!s.signal&&s.timeout===void 0&&s.retries===void 0)return;const e={...s};return t&&(t.signal!==void 0&&(e.signal=t.signal),t.timeout!==void 0&&(e.timeout=t.timeout),t.retries!==void 0&&(e.retries=t.retries)),s.signal&&t?.signal&&(e.signal=AbortSignal.any([s.signal,t.signal])),e},"mergeOperationOptions"),D=m(async(s,t,e)=>{const r=Array.from({length:s.length});let n=0,o=!1;const u=m(async()=>{for(;n<s.length;){if(o||e.signal?.aborted)return;const a=n;n+=1;try{const i=await t(s[a],a);r[a]={status:"fulfilled",value:i}}catch(i){r[a]={reason:i,status:"rejected"},e.stopOnError&&(o=!0)}}},"worker"),c=Math.max(1,Math.min(e.concurrency,s.length)),l=Array.from({length:c},()=>u());return await Promise.all(l),r},"runConcurrent"),b=m((s,t)=>t instanceof Error?{error:t,key:s}:{error:new Error(typeof t=="string"?t:"Unknown error",{cause:t}),key:s},"toBulkError"),_=m((s,t)=>{if(s)try{s(t)}catch{}},"safeInvoke");class F{static{C(this,"Files")}static{m(this,"Files")}adapter;defaults;hooks;prefix;readonlyMode;constructor(t){this.adapter=t.adapter,this.defaults=t.defaults??{},this.hooks=t.hooks??{},this.prefix=X(t.prefix??""),this.readonlyMode=t.readonly??!1}get capabilities(){return{cacheControl:this.adapter.supportsCacheControl,metadata:this.adapter.supportsMetadata,range:this.adapter.supportsRange,readonly:this.readonlyMode}}readonly(){return new F({adapter:this.adapter,defaults:this.defaults,hooks:this.hooks,prefix:this.prefix,readonly:!0})}assertWritable(){this.readonlyMode&&W(K.READ_ONLY,"This Files instance is read-only")}get raw(){return this.adapter.raw}resolveKey(t){const e=t.replace(/^\/+/u,"");return j(e,"key"),this.prefix?`${this.prefix}/${e}`:t}stripPrefix(t){const e=t.startsWith("/")?t.slice(1):t;if(!this.prefix)return e;const r=`${this.prefix}/`;return e.startsWith(r)?e.slice(r.length):null}mergeOptions(t,e){const r=Z(this.defaults,t);if(!e||!this.hooks.onRetry)return r;const n=r?.retries,o=typeof n=="number"?{maxRetries:n}:{...n},u=o.onRetry,c=this.hooks.onRetry;return o.onRetry=(l,a)=>{if(u)try{u(l,a)}catch{}try{const i=typeof a=="string"?a:"Unknown error",d=a instanceof Error?a:new Error(i,{cause:a});c({...e,attempt:l,error:d})}catch{}},{...r,retries:o}}emitAction(t,e){if(this.hooks.onAction)try{this.hooks.onAction({type:t,...e})}catch{}}emitError(t,e,r){if(this.hooks.onError)try{this.hooks.onError({error:r,type:t,...e})}catch{}}async withHooks(t,e,r){const n=Date.now();try{const o=await r();return this.emitAction(t,{...e,durationMs:Date.now()-n}),o}catch(o){const u=typeof o=="string"?o:"Unknown error",c=o instanceof Error?o:new Error(u,{cause:o});throw this.emitError(t,{...e,durationMs:Date.now()-n},c),c}}async upload(t,e,r){return Array.isArray(t)?this.uploadMany(t,e):this.uploadOne(t,e,r)}async uploadOne(t,e,r){this.assertWritable(),r?.metadata&&Object.keys(r.metadata).length>0&&!this.adapter.supportsMetadata&&W(K.METHOD_NOT_ALLOWED,`Adapter ${this.adapter.constructor.name} does not persist custom metadata`);const n=r?.control;return this.withHooks("upload",{key:t},async()=>{const o=this.resolveKey(t);P.assertSafeId(o);const{size:u,stream:c}=await Q(e,r?.size),l=r?.size??u,a={...r?.metadata??{},name:o,...r?.contentType?{type:r.contentType}:{},...l===void 0?{}:{size:l}},i=n?{...r,signal:r?.signal?AbortSignal.any([r.signal,n.signal]):n.signal}:r,d=this.mergeOptions(i,{key:t,type:"upload"}),p=r?.multipart;n?._bind(c,t);const y=await this.adapter.create({contentType:r?.contentType,id:o,metadata:a,originalName:o,size:l,storageClass:r?.storageClass},d),f=this.adapter.reportsUploadProgress,h=r?.onProgress,S=!!h||!!n;let w=c;if(S&&!f){let N=0;const M=new J;l!==void 0&&h&&_(h,{loaded:0,total:l}),c.on("data",T=>{const O=typeof T=="string"?Buffer.byteLength(T):T.byteLength;N+=O,n?._progress(N),h&&_(h,{loaded:N,total:l})}),c.pipe(M),w=M}const E={body:w,contentLength:l,id:y.id,start:0,...p!==void 0&&{multipart:p},...f&&h&&{onProgress:h}},k=await this.adapter.write(E,d);n?._complete();const A=I(k,o),g=this.stripPrefix(A.key);return g!==null&&(A.key=g),A})}async uploadMany(t,e){this.assertWritable();const{concurrency:r=U,multipart:n,onProgress:o,stopOnError:u=!1,...c}=e??{},l=await D(t,async({body:d,key:p,...y})=>{const f=y.onProgress??(o?h=>{o({...h,key:p})}:void 0);return this.uploadOne(p,d,{...c,multipart:n,...y,...f&&{onProgress:f}})},{concurrency:r,signal:c.signal,stopOnError:u}),a=[],i=[];for(const[d,p]of l.entries()){const y=t[d];if(!p){i.push(b(y.key,new Error("Operation skipped (stopOnError)")));continue}p.status==="fulfilled"?a.push(p.value):i.push(b(y.key,p.reason))}return i.length>0?{errors:i,uploaded:a}:{uploaded:a}}async download(t,e){return Array.isArray(t)?this.downloadMany(t,e):this.downloadOne(t,e)}assertRangeSupported(t){if(t){if(!Number.isFinite(t.start)||t.start<0)throw new TypeError(`Invalid range.start: ${String(t.start)}`);if(t.end!==void 0&&(!Number.isFinite(t.end)||t.end<t.start))throw new TypeError(`Invalid range.end: ${String(t.end)}`);if(!this.adapter.supportsRange)throw new Error(`Adapter ${this.adapter.constructor.name} does not support range downloads`)}}async downloadOne(t,e){return this.withHooks("download",{key:t},async()=>{const r=this.resolveKey(t);P.assertSafeId(r),this.assertRangeSupported(e?.range);const n=this.mergeOptions(e,{key:t,type:"download"})??{},o=e?.range?{...n,range:e.range}:n,u=await this.adapter.get({id:r},o);return{body:u.content,contentType:u.contentType??"application/octet-stream",etag:u.ETag,key:t,lastModified:u.modifiedAt,metadata:u.metadata,size:typeof u.size=="number"?u.size:void 0}})}async downloadMany(t,e){const{concurrency:r=U,range:n,stopOnError:o=!1,...u}=e??{},c=await D(t,async i=>this.downloadOne(i,n?{...u,range:n}:u),{concurrency:r,signal:u.signal,stopOnError:o}),l=[],a=[];for(const[i,d]of c.entries()){const p=t[i];if(!d){a.push(b(p,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?l.push(d.value):a.push(b(p,d.reason))}return a.length>0?{downloaded:l,errors:a}:{downloaded:l}}async head(t,e){return Array.isArray(t)?this.headMany(t,e):this.headOne(t,e)}async headOne(t,e){return this.withHooks("head",{key:t},async()=>{const r=this.resolveKey(t);P.assertSafeId(r);const n=await this.adapter.getMeta(r,this.mergeOptions(e,{key:t,type:"head"})),o=I(n,r);return o.key=t,o})}async headMany(t,e){const{concurrency:r=U,stopOnError:n=!1,...o}=e??{},u=await D(t,async a=>this.headOne(a,o),{concurrency:r,signal:o.signal,stopOnError:n}),c=[],l=[];for(const[a,i]of u.entries()){const d=t[a];if(!i){l.push(b(d,new Error("Operation skipped (stopOnError)")));continue}i.status==="fulfilled"?c.push(i.value):l.push(b(d,i.reason))}return l.length>0?{errors:l,files:c}:{files:c}}async exists(t,e){return Array.isArray(t)?this.existsMany(t,e):this.existsOne(t,e)}async existsOne(t,e){return this.withHooks("exists",{key:t},async()=>{const r=this.resolveKey(t);return P.assertSafeId(r),this.adapter.exists({id:r},this.mergeOptions(e,{key:t,type:"exists"}))})}async existsMany(t,e){const{concurrency:r=U,stopOnError:n=!1,...o}=e??{},u=await D(t,async i=>this.existsOne(i,o),{concurrency:r,signal:o.signal,stopOnError:n}),c=[],l=[],a=[];for(const[i,d]of u.entries()){const p=t[i];if(!d){a.push(b(p,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?d.value?c.push(p):l.push(p):a.push(b(p,d.reason))}return a.length>0?{errors:a,existing:c,missing:l}:{existing:c,missing:l}}async delete(t,e){if(this.assertWritable(),Array.isArray(t))return this.deleteMany(t,e);await this.deleteOne(t,e)}async deleteOne(t,e){await this.withHooks("delete",{key:t},async()=>{const r=this.resolveKey(t);P.assertSafeId(r),await this.adapter.delete({id:r},this.mergeOptions(e,{key:t,type:"delete"}))})}async deleteMany(t,e){const{concurrency:r=U,stopOnError:n=!1,...o}=e??{},u=this.mergeOptions(o,{keys:t,type:"delete"});if(!n&&typeof this.adapter.deleteBatch=="function"){const i=[],d=[],p=[];for(const y of t)try{const f=this.resolveKey(y);P.assertSafeId(f),i.push(y),d.push(f)}catch(f){p.push(b(y,f))}return this.withHooks("delete",{keys:i},async()=>{const y=d.length>0?await this.adapter.deleteBatch(d,u):{failed:[],successful:[]},f=new Map(d.map((w,E)=>[w,E])),h=y.successful.map(w=>this.stripPrefix(w.id)??w.id),S=[...p,...y.failed.map(({error:w,id:E})=>{const k=f.get(E),A=k===void 0?E:i[k];return b(A,new Error(w))})];return S.length>0?{deleted:h,errors:S}:{deleted:h}})}const c=await D(t,async i=>this.deleteOne(i,o),{concurrency:r,signal:o.signal,stopOnError:n}),l=[],a=[];for(const[i,d]of c.entries()){const p=t[i];if(!d){a.push(b(p,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?l.push(p):a.push(b(p,d.reason))}return a.length>0?{deleted:l,errors:a}:{deleted:l}}async copy(t,e,r){return this.assertWritable(),this.withHooks("copy",{from:t,to:e},async()=>{const n=this.resolveKey(t),o=this.resolveKey(e);P.assertSafeId(n),P.assertSafeId(o);const u=await this.adapter.copy(n,o,{...this.mergeOptions(r,{from:t,to:e,type:"copy"}),storageClass:r?.storageClass}),c=I(u,o);return c.key=e,c})}async move(t,e,r){return this.assertWritable(),Array.isArray(t)?this.moveMany(t,e):this.moveOne(t,e,r)}async moveOne(t,e,r){return this.withHooks("move",{from:t,to:e},async()=>{const n=this.resolveKey(t);if(P.assertSafeId(n),t===e){const a=await this.adapter.getMeta(n,this.mergeOptions(r,{from:t,to:e,type:"move"})),i=I(a,n);return i.key=t,i}const o=this.resolveKey(e);P.assertSafeId(o);const u={...this.mergeOptions(r,{from:t,to:e,type:"move"}),...r?.storageClass!==void 0&&{storageClass:r.storageClass}},c=await this.adapter.move(n,o,u),l=I(c,o);return l.key=e,l})}async moveMany(t,e){const{concurrency:r=U,stopOnError:n=!1,...o}=e??{},u=await D(t,async({from:a,to:i})=>this.moveOne(a,i,o),{concurrency:r,signal:o.signal,stopOnError:n}),c=[],l=[];for(const[a,i]of u.entries()){const d=t[a];if(!i){l.push(b(d.from,new Error("Operation skipped (stopOnError)")));continue}i.status==="fulfilled"?c.push(i.value):l.push(b(d.from,i.reason))}return l.length>0?{errors:l,moved:c}:{moved:c}}async list(t={}){return this.withHooks("list",{},async()=>{const{delimiter:e,limit:r,prefix:n,...o}=t;if(e!==void 0&&this.adapter.supportsDelimiter)return this.listDirectoryNative(e,n,r,o);const u=await this.adapter.list(r??1e3,this.mergeOptions(o,{type:"list"})),c=[];for(const p of u){const y=I(p),f=this.stripPrefix(y.key);f!==null&&(y.key=f,c.push(y))}const l=n?c.filter(p=>p.key.startsWith(n)):c;if(e===void 0)return l;const a=n??"",i=[],d=new Set;for(const p of l){const y=p.key.slice(a.length),f=y.indexOf(e);f===-1?i.push(p):d.add(a+y.slice(0,f+e.length))}return{files:i,prefixes:[...d].toSorted()}})}async listDirectoryNative(t,e,r,n){const o=[this.prefix,e].filter(Boolean).join("/"),{files:u,prefixes:c}=await this.adapter.listDirectory({delimiter:t,...r!==void 0&&{limit:r},...o&&{prefix:o},...this.mergeOptions(n,{type:"list"})}),l=[];for(const i of u){const d=I(i),p=this.stripPrefix(d.key);p!==null&&(d.key=p,l.push(d))}const a=[];for(const i of c){const d=this.stripPrefix(i);d!==null&&a.push(d)}return{files:l,prefixes:a.toSorted()}}async*listAll(t={}){const{limit:e,prefix:r,...n}=t,o=Math.max(1,e??1e3),u=Date.now(),c=new Set;let l;try{for(;;){const a=await this.adapter.list(o,this.mergeOptions(n,{type:"listAll"}));let i=0;for(const d of a){const p=I(d),y=this.stripPrefix(p.key);y!==null&&(p.key=y,!(r&&!p.key.startsWith(r))&&(c.has(p.key)||(c.add(p.key),i+=1,yield p)))}if(i===0||a.length<o)break}}catch(a){const i=typeof a=="string"?a:"Unknown error";throw l=a instanceof Error?a:new Error(i,{cause:a}),l}finally{const a=Date.now()-u;l?this.emitError("listAll",{durationMs:a},l):this.emitAction("listAll",{durationMs:a})}}async url(t,e){return this.withHooks("url",{key:t},async()=>{const r=this.resolveKey(t);return P.assertSafeId(r),this.adapter.getReadUrl(r,{...this.mergeOptions(e,{key:t,type:"url"}),...e})})}async signedUploadUrl(t,e){return this.assertWritable(),this.withHooks("signedUploadUrl",{key:t},async()=>{const r=this.resolveKey(t);return P.assertSafeId(r),this.adapter.getUploadUrl(r,{...this.mergeOptions(e,{key:t,type:"signedUploadUrl"}),...e})})}}const ot=m(async(s,t,e={})=>{const{concurrency:r=U,limit:n,onProgress:o,overwrite:u=!1,prefix:c,signal:l,stopOnError:a=!1,transformKey:i}=e,d=[],p=[],y=[];let f=!1,h=0;const S=m(g=>{if(o)try{o(g)}catch{}},"emit"),w=s.listAll({...c!==void 0&&{prefix:c},...n!==void 0&&{limit:n}}),E=m(async g=>{if(f||l?.aborted)return;const N=i?i(g):g;try{if(!u&&await t.exists(N,{signal:l})){p.push(g),h+=1,S({done:h,key:g,status:"skipped"});return}const M=await s.download(g,{signal:l});await t.upload(N,M.body,{...M.contentType&&{contentType:M.contentType},...M.metadata&&{metadata:M.metadata},signal:l}),d.push(g),h+=1,S({done:h,key:g,status:"transferred"})}catch(M){const T=b(g,M);if(y.push(T),h+=1,S({done:h,error:T.error,key:g,status:"errored"}),a)throw f=!0,T.error}},"transferOne");if(a){try{for await(const g of w){if(f||l?.aborted)break;try{await E(g.key)}catch{break}}}finally{await w.return?.()}return y.length>0?{errors:y,skipped:p,transferred:d}:{skipped:p,transferred:d}}const k=Math.max(1,r),A=m(async()=>{for(;!f&&!l?.aborted;){const g=await w.next();if(g.done)return;await E(g.value.key)}},"worker");try{await Promise.all(Array.from({length:k},()=>A()))}finally{await w.return?.()}return y.length>0?{errors:y,skipped:p,transferred:d}:{skipped:p,transferred:d}},"transfer"),tt=m((s,t)=>{if(typeof s.size=="number"&&typeof t.size=="number"&&s.size!==t.size)return!1;if(s.etag&&t.etag)return s.etag===t.etag;if(typeof s.size=="number"&&typeof t.size=="number")return!0;const e=s.lastModified===void 0?void 0:Number(new Date(s.lastModified)),r=t.lastModified===void 0?void 0:Number(new Date(t.lastModified));return e!==void 0&&r!==void 0&&!Number.isNaN(e)&&!Number.isNaN(r)?e<=r:!0},"objectsMatch"),it=m(async(s,t,e={})=>{const{concurrency:r=U,dryRun:n=!1,limit:o,onProgress:u,prefix:c,prune:l=!1,signal:a,stopOnError:i=!1,transformKey:d}=e,p=[],y=[],f=[],h=[],S=[],w=new Set;let E=!1,k=0;const A=m(O=>{if(u)try{u(O)}catch{}},"emit"),g=s.listAll({...c!==void 0&&{prefix:c},...o!==void 0&&{limit:o}}),N=m(async O=>{if(E||a?.aborted)return;const x=O.key,L=d?d(x):x;w.add(L);try{let v;try{v=await t.head(L,{signal:a})}catch{v=void 0}if(v){let z=O;if(O.size===void 0&&O.etag===void 0)try{z=await s.head(x,{signal:a})}catch{}if(tt(z,v)){f.push(x),k+=1,A({done:k,key:x,status:"unchanged"});return}}const B=v!==void 0;if(!n){const z=await s.download(x,{signal:a});await t.upload(L,z.body,{...z.contentType&&{contentType:z.contentType},...z.metadata&&{metadata:z.metadata},signal:a})}B?y.push(x):p.push(x),k+=1,A({done:k,key:x,status:B?"updated":"uploaded"})}catch(v){const B=b(x,v);if(S.push(B),k+=1,A({done:k,error:B.error,key:x,status:"errored"}),i)throw E=!0,B.error}},"syncOne"),M=Math.max(1,r),T=m(async()=>{for(;!E&&!a?.aborted;){const O=await g.next();if(O.done)return;await N(O.value)}},"worker");try{await Promise.all(Array.from({length:M},()=>T()))}finally{await g.return?.()}if(l&&!E&&!a?.aborted){const O=[],x=t.listAll({...c!==void 0&&{prefix:c},...o!==void 0&&{limit:o}});try{for await(const v of x)w.has(v.key)||O.push(v.key)}finally{await x.return?.()}const L=await D(O,async v=>(n||await t.delete(v,{signal:a}),v),{concurrency:M,signal:a,stopOnError:i});for(const[v,B]of L.entries()){const z=O[v];if(B)if(B.status==="fulfilled")h.push(z),k+=1,A({done:k,key:z,status:"deleted"});else{const H=b(z,B.reason);S.push(H),k+=1,A({done:k,error:H.error,key:z,status:"errored"})}}}return S.length>0?{deleted:h,errors:S,unchanged:f,updated:y,uploaded:p}:{deleted:h,unchanged:f,updated:y,uploaded:p}},"sync");export{F as Files,$ as UploadControl,F as default,it as sync,ot as transfer};
@@ -1 +1 @@
1
- var t=Object.defineProperty;var r=(a,e)=>t(a,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-Dr891Iy7.js";var s=Object.defineProperty,c=r((a,e)=>s(a,"name",{value:e,configurable:!0}),"a");class u extends o{static{r(this,"r")}static{c(this,"UploadThingMetaStorage")}constructor(e){super(e)}}export{u as default};
1
+ var t=Object.defineProperty;var r=(a,e)=>t(a,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-tayO1ARY.js";var s=Object.defineProperty,c=r((a,e)=>s(a,"name",{value:e,configurable:!0}),"a");class u extends o{static{r(this,"r")}static{c(this,"UploadThingMetaStorage")}constructor(e){super(e)}}export{u as default};
@@ -0,0 +1 @@
1
+ var T=Object.defineProperty;var l=(r,t)=>T(r,"name",{value:t,configurable:!0});import{UTApi as U,UTFile as h}from"uploadthing/server";import{throwErrorCode as m,ERRORS as f}from"./ERRORS-vMSqlI69.js";import{B as I}from"./storage-CI88PmRw.js";import d from"./UploadThingFile-BpG9mE8K.js";import O from"./UploadThingMetaStorage-CdDfhiyy.js";import{o as y}from"./get-file-status-DLS18Zvd.js";import{u as E}from"./update-size-DANV7aa2.js";import{r as k}from"./part-match-D_NwyoF3.js";import{o as v}from"./has-content-Bx2p8Okx.js";var b=Object.defineProperty,u=l((r,t)=>b(r,"name",{value:t,configurable:!0}),"c");const w=3600*24*7,x=u(r=>{let t;try{t=typeof atob=="function"?atob(r):Buffer.from(r,"base64").toString("utf8")}catch(e){throw new Error(`UploadThing: token is not valid base64: ${e.message}`)}let a;try{a=JSON.parse(t)}catch(e){throw new Error(`UploadThing: token does not decode to JSON: ${e.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},"decodeToken"),N=u(async r=>{const t=[];for await(const a of r)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream"),g=u(r=>{const t=r.lastIndexOf("/");return t===-1?r:r.slice(t+1)},"basename");class B extends I{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(t){super(t);const a=t.token??process.env.UPLOADTHING_TOKEN;if(t.client)this.utapi=t.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new U({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=x(a).appId,this.acl=t.acl??"public-read",this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w),this.meta=t.metaStorage??new O(t.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new d(t);e.name=this.namingFunction(e),e.customId=e.name,await this.validate(e);try{const i=await this.getMeta(e.id);if(i.bytesWritten>=0)return i}catch{}return e.bytesWritten=0,e.status=y(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&E(e,t.size),!k(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(v(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await N(t.body),p=new Blob([new Uint8Array(n)],{type:e.contentType}),o=new h([p],g(e.name||e.id),{customId:e.name||e.id,type:e.contentType}),s=await this.runOperation(a,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const{data:c}=s;e.bytesWritten=n.length,e.size=n.length,e.ufsKey=c.key,e.url=c.ufsUrl??c.url,e.ETag=c.fileHash,e.fileHash=c.fileHash}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,i)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const i=e?.customId??e?.name??t;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:t}),{customId:i,id:t,name:t,status:"deleted"})})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e,i=t;try{e=await this.checkIfExpired(await this.getMeta(t)),i=e.customId??e.name??t}catch{}const n=await this.resolveFetchUrl(i,a),p=await this.runOperation(a,()=>fetch(n));if(!p.ok)throw new Error(`UploadThing: fetch failed: ${p.status} ${p.statusText} for ${i}`);const o=Buffer.from(await p.arrayBuffer());return{content:o,contentType:e?.contentType??p.headers.get("content-type")??"application/octet-stream",ETag:e?.ETag??p.headers.get("etag")??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt,name:e?.name??i,originalName:e?.originalName??i,size:e?.size??o.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:t},e),n=new Blob([new Uint8Array(i.content)],{type:i.contentType}),p=new h([n],g(a),{customId:a,type:i.contentType}),o=await this.runOperation(e,()=>this.utapi.uploadFiles(p,{acl:this.acl}));if(o.error)throw new Error(o.error.message);const s=new d({contentType:i.contentType,metadata:{},originalName:a});return s.id=a,s.name=a,s.customId=a,s.size=typeof i.size=="string"?Number(i.size):i.size,s.ufsKey=o.data.key,s.url=o.data.ufsUrl??o.data.url,s.ETag=o.data.fileHash,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e);return await this.delete({id:t},e),i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:t}))).files.map(e=>{const i=e.customId??e.key,n=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return n.id=i,n.name=i,n.customId=e.customId??void 0,n.ufsKey=e.key,n.size=e.size,n.modifiedAt=e.uploadedAt?new Date(e.uploadedAt).toISOString():void 0,n}),{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return m(f.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(t)}`;const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,w),{ufsUrl:i}=await this.utapi.generateSignedURL(t,{expiresIn:e,keyType:"customId"});return i}async getUploadUrl(t,a){return m(f.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(t,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const{ufsUrl:e}=await this.runOperation(a,()=>this.utapi.generateSignedURL(t,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return e}internalOnComplete=u(t=>this.deleteMeta(t.id),"internalOnComplete")}export{B as default};
@@ -1 +1 @@
1
- var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-Dr891Iy7.js";var s=Object.defineProperty,c=t((r,e)=>s(r,"name",{value:e,configurable:!0}),"e");class i extends o{static{t(this,"l")}static{c(this,"VercelBlobMetaStorage")}constructor(e){super(e)}}export{i as default};
1
+ var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-tayO1ARY.js";var s=Object.defineProperty,c=t((r,e)=>s(r,"name",{value:e,configurable:!0}),"e");class i extends o{static{t(this,"l")}static{c(this,"VercelBlobMetaStorage")}constructor(e){super(e)}}export{i as default};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var u=(c,e)=>E(c,"name",{value:e,configurable:!0});import{put as d,list as m,del as h,copy as p}from"@vercel/blob";import{a as g}from"./detect-file-type-5JhzC9RU.js";import{B as v,t as T}from"./storage-uhIhcN-O.js";import{v as b}from"./local-meta-storage-Dr891Iy7.js";import f from"./VercelBlobFile-Cni_1qwD.js";import{o as w}from"./get-file-status-DLS18Zvd.js";import{u as B}from"./update-size-DANV7aa2.js";import{r as _}from"./part-match-D_NwyoF3.js";import{o as k}from"./has-content-Bx2p8Okx.js";var I=Object.defineProperty,C=u((c,e)=>I(c,"name",{value:e,configurable:!0}),"p");class y extends v{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:p,credentials:this.credentials,del:h,list:m,put:d}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=y.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:i,metaStorageConfig:t}=e;this.meta=i||new b(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const i=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,r=t?.startsWith("store_")?t.slice(6):t;if(i&&r)return{oidcToken:i,storeId:r};if(i||r)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${i?"set":"missing"}, storeId=${r?"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,i){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?T(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const r=new f(t);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);if(a.bytesWritten>=0)return a}catch{}return r.bytesWritten=0,r.status=w(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&B(t,e.size),!_(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(k(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],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 g(s);o?.mime&&(t.contentType=o.mime)}catch{}const O=new Blob([s],{type:t.contentType}),l=await this.runOperation(i,()=>d(t.name,O,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=l.url,t.pathname=l.pathname,t.downloadUrl=l.downloadUrl,t.bytesWritten=s.length}return t.status=w(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:r}=t;t.status="deleted";try{await this.runOperation(i,()=>h(r,{...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},i){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:r}=t;return(await this.runOperation(i,()=>fetch(r,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},i){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:r}=t,a=await this.runOperation(i,()=>fetch(r)),n=Buffer.from(await this.runOperation(i,()=>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,i,t){return this.instrumentOperation("copy",async()=>{const r=await this.getMeta(e);if(!r.url)throw new Error("Source file URL not found");const a=r.url,n=await this.runOperation(t,()=>p(a,i,{access:"public",...this.credentials}));return{...r,id:i,name:i,pathname:n.pathname,url:n.url}})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const r=await this.copy(e,i,t);return await this.delete({id:e},t),r})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>(await this.runOperation(i,()=>m({limit:e,...this.credentials}))).blobs.map(t=>{const r=new f({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return r.createdAt=t.uploadedAt?.toISOString(),r.id=t.pathname,r.modifiedAt=t.uploadedAt?.toISOString(),r.name=t.pathname,r.pathname=t.pathname,r.size=t.size,r.url=t.url,r.downloadUrl=t.downloadUrl,r}),{limit:e})}internalOnComplete=C(e=>this.deleteMeta(e.id),"internalOnComplete");shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{y as default};
1
+ var E=Object.defineProperty;var u=(c,e)=>E(c,"name",{value:e,configurable:!0});import{put as d,list as m,del as h,copy as p}from"@vercel/blob";import{a as g}from"./detect-file-type-DRWGvQW4.js";import{B as v,t as T}from"./storage-CI88PmRw.js";import{v as b}from"./local-meta-storage-tayO1ARY.js";import f from"./VercelBlobFile-Cni_1qwD.js";import{o as w}from"./get-file-status-DLS18Zvd.js";import{u as B}from"./update-size-DANV7aa2.js";import{r as _}from"./part-match-D_NwyoF3.js";import{o as k}from"./has-content-Bx2p8Okx.js";var I=Object.defineProperty,C=u((c,e)=>I(c,"name",{value:e,configurable:!0}),"p");class y extends v{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:p,credentials:this.credentials,del:h,list:m,put:d}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=y.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:i,metaStorageConfig:t}=e;this.meta=i||new b(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const i=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,r=t?.startsWith("store_")?t.slice(6):t;if(i&&r)return{oidcToken:i,storeId:r};if(i||r)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${i?"set":"missing"}, storeId=${r?"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,i){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?T(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const r=new f(t);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);if(a.bytesWritten>=0)return a}catch{}return r.bytesWritten=0,r.status=w(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&B(t,e.size),!_(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(k(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],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 g(s);o?.mime&&(t.contentType=o.mime)}catch{}const O=new Blob([s],{type:t.contentType}),l=await this.runOperation(i,()=>d(t.name,O,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=l.url,t.pathname=l.pathname,t.downloadUrl=l.downloadUrl,t.bytesWritten=s.length}return t.status=w(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:r}=t;t.status="deleted";try{await this.runOperation(i,()=>h(r,{...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},i){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:r}=t;return(await this.runOperation(i,()=>fetch(r,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},i){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:r}=t,a=await this.runOperation(i,()=>fetch(r)),n=Buffer.from(await this.runOperation(i,()=>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,i,t){return this.instrumentOperation("copy",async()=>{const r=await this.getMeta(e);if(!r.url)throw new Error("Source file URL not found");const a=r.url,n=await this.runOperation(t,()=>p(a,i,{access:"public",...this.credentials}));return{...r,id:i,name:i,pathname:n.pathname,url:n.url}})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const r=await this.copy(e,i,t);return await this.delete({id:e},t),r})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>(await this.runOperation(i,()=>m({limit:e,...this.credentials}))).blobs.map(t=>{const r=new f({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return r.createdAt=t.uploadedAt?.toISOString(),r.id=t.pathname,r.modifiedAt=t.uploadedAt?.toISOString(),r.name=t.pathname,r.pathname=t.pathname,r.size=t.size,r.url=t.url,r.downloadUrl=t.downloadUrl,r}),{limit:e})}internalOnComplete=C(e=>this.deleteMeta(e.id),"internalOnComplete");shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{y as default};
@@ -1 +1 @@
1
- var g=Object.defineProperty;var d=(e,t)=>g(e,"name",{value:t,configurable:!0});import{tool as r}from"@openai/agents";import{r as U}from"./approval-BBeX3o4E.js";import{T as i,e as o,W as m}from"./executors-DG6hGtvm.js";var x=Object.defineProperty,l=d((e,t)=>x(e,"name",{value:t,configurable:!0}),"o");const v=l(e=>r({description:i.listFiles.description,execute:l(t=>o.listFiles(e,t),"execute"),name:"listFiles",parameters:i.listFiles.input}),"agentsListFiles"),A=l(e=>r({description:i.getFileMetadata.description,execute:l(t=>o.getFileMetadata(e,t),"execute"),name:"getFileMetadata",parameters:i.getFileMetadata.input}),"agentsGetFileMetadata"),f=l(e=>r({description:i.downloadFile.description,execute:l(t=>o.downloadFile(e,t),"execute"),name:"downloadFile",parameters:i.downloadFile.input}),"agentsDownloadFile"),y=l(e=>r({description:i.getFileUrl.description,execute:l(t=>o.getFileUrl(e,t),"execute"),name:"getFileUrl",parameters:i.getFileUrl.input}),"agentsGetFileUrl"),O=l((e,{needsApproval:t=!0}={})=>r({description:i.uploadFile.description,execute:l(a=>o.uploadFile(e,a),"execute"),name:"uploadFile",needsApproval:t,parameters:i.uploadFile.input}),"agentsUploadFile"),M=l((e,{needsApproval:t=!0}={})=>r({description:i.deleteFile.description,execute:l(a=>o.deleteFile(e,a),"execute"),name:"deleteFile",needsApproval:t,parameters:i.deleteFile.input}),"agentsDeleteFile"),w=l((e,{needsApproval:t=!0}={})=>r({description:i.copyFile.description,execute:l(a=>o.copyFile(e,a),"execute"),name:"copyFile",needsApproval:t,parameters:i.copyFile.input}),"agentsCopyFile"),T=l((e,{needsApproval:t=!0}={})=>r({description:i.signUploadUrl.description,execute:l(a=>o.signUploadUrl(e,a),"execute"),name:"signUploadUrl",needsApproval:t,parameters:i.signUploadUrl.input}),"agentsSignUploadUrl");function b({files:e,overrides:t,readOnly:a=!1,requireApproval:u=!0}){const p=l(s=>({needsApproval:U(s,u)}),"approval"),n={copyFile:w(e,p("copyFile")),deleteFile:M(e,p("deleteFile")),downloadFile:f(e),getFileMetadata:A(e),getFileUrl:y(e),listFiles:v(e),signUploadUrl:T(e,p("signUploadUrl")),uploadFile:O(e,p("uploadFile"))};if(t){for(const[s,F]of Object.entries(t))if(s in n&&F){const c=s;Object.assign(n,{[c]:{...n[c],...F}})}}return a?Object.fromEntries(Object.entries(n).filter(([s])=>!m.has(s))):n}d(b,"createAgentsFileTools");l(b,"createAgentsFileTools");export{w as agentsCopyFile,M as agentsDeleteFile,f as agentsDownloadFile,A as agentsGetFileMetadata,y as agentsGetFileUrl,v as agentsListFiles,T as agentsSignUploadUrl,O as agentsUploadFile,b as createAgentsFileTools};
1
+ var g=Object.defineProperty;var d=(e,t)=>g(e,"name",{value:t,configurable:!0});import{tool as r}from"@openai/agents";import{r as U}from"./approval-BBeX3o4E.js";import{T as i,e as o,W as m}from"./executors-MzQbS9FT.js";var x=Object.defineProperty,l=d((e,t)=>x(e,"name",{value:t,configurable:!0}),"o");const v=l(e=>r({description:i.listFiles.description,execute:l(t=>o.listFiles(e,t),"execute"),name:"listFiles",parameters:i.listFiles.input}),"agentsListFiles"),A=l(e=>r({description:i.getFileMetadata.description,execute:l(t=>o.getFileMetadata(e,t),"execute"),name:"getFileMetadata",parameters:i.getFileMetadata.input}),"agentsGetFileMetadata"),f=l(e=>r({description:i.downloadFile.description,execute:l(t=>o.downloadFile(e,t),"execute"),name:"downloadFile",parameters:i.downloadFile.input}),"agentsDownloadFile"),y=l(e=>r({description:i.getFileUrl.description,execute:l(t=>o.getFileUrl(e,t),"execute"),name:"getFileUrl",parameters:i.getFileUrl.input}),"agentsGetFileUrl"),O=l((e,{needsApproval:t=!0}={})=>r({description:i.uploadFile.description,execute:l(a=>o.uploadFile(e,a),"execute"),name:"uploadFile",needsApproval:t,parameters:i.uploadFile.input}),"agentsUploadFile"),M=l((e,{needsApproval:t=!0}={})=>r({description:i.deleteFile.description,execute:l(a=>o.deleteFile(e,a),"execute"),name:"deleteFile",needsApproval:t,parameters:i.deleteFile.input}),"agentsDeleteFile"),w=l((e,{needsApproval:t=!0}={})=>r({description:i.copyFile.description,execute:l(a=>o.copyFile(e,a),"execute"),name:"copyFile",needsApproval:t,parameters:i.copyFile.input}),"agentsCopyFile"),T=l((e,{needsApproval:t=!0}={})=>r({description:i.signUploadUrl.description,execute:l(a=>o.signUploadUrl(e,a),"execute"),name:"signUploadUrl",needsApproval:t,parameters:i.signUploadUrl.input}),"agentsSignUploadUrl");function b({files:e,overrides:t,readOnly:a=!1,requireApproval:u=!0}){const p=l(s=>({needsApproval:U(s,u)}),"approval"),n={copyFile:w(e,p("copyFile")),deleteFile:M(e,p("deleteFile")),downloadFile:f(e),getFileMetadata:A(e),getFileUrl:y(e),listFiles:v(e),signUploadUrl:T(e,p("signUploadUrl")),uploadFile:O(e,p("uploadFile"))};if(t){for(const[s,F]of Object.entries(t))if(s in n&&F){const c=s;Object.assign(n,{[c]:{...n[c],...F}})}}return a?Object.fromEntries(Object.entries(n).filter(([s])=>!m.has(s))):n}d(b,"createAgentsFileTools");l(b,"createAgentsFileTools");export{w as agentsCopyFile,M as agentsDeleteFile,f as agentsDownloadFile,A as agentsGetFileMetadata,y as agentsGetFileUrl,v as agentsListFiles,T as agentsSignUploadUrl,O as agentsUploadFile,b as createAgentsFileTools};
@@ -0,0 +1,4 @@
1
+ var b=Object.defineProperty;var p=(h,t)=>b(h,"name",{value:t,configurable:!0});import C from"./MetaStorage-Y4m1dWgd.js";import{parseMetadata as x,stringifyMetadata as T}from"./Metadata-B6Ir0KO7.js";import{Readable as w}from"node:stream";import{AwsClient as k}from"aws4fetch";import{o as E}from"./is-expired-1JuZjDtb.js";var U=Object.defineProperty,y=p((h,t)=>U(h,"name",{value:t,configurable:!0}),"f");const m=y(h=>{const t={},o=h.replaceAll(/<\?xml[^>]*\?>/g,"").replaceAll(/xmlns[^=]*="[^"]*"/g,""),a=/<([^>]+)>([^<]*)<\/\1>/g,e=[...o.matchAll(a)];for(const i of e){const[,r,c]=i;r&&c?.trim()&&(t[r]?(Array.isArray(t[r])||(t[r]=[t[r]]),t[r].push(c.trim())):t[r]=c.trim())}const s=/<([^>]+)>([\s\S]*?)<\/\1>/g;let n;for(;(n=s.exec(o))!==null;){const[,i,r]=n;if(i&&r?.includes("<")){const c=m(r);Object.keys(c).length>0&&(t[i]=c)}}return t},"parseXml");class ${static{p(this,"x")}static{y(this,"AwsLightApiAdapter")}aws;bucket;endpoint;constructor(t){this.bucket=t.bucket,this.endpoint=t.endpoint||`https://${t.bucket}.s3.${t.region}.amazonaws.com`,this.aws=new k({accessKeyId:t.accessKeyId,region:t.region,secretAccessKey:t.secretAccessKey,service:t.service||"s3",sessionToken:t.sessionToken})}async createMultipartUpload(t,o){const a={uploads:""},e={};if(t.ContentType&&(e["Content-Type"]=t.ContentType),t.ACL&&(e["x-amz-acl"]=t.ACL),t.Metadata)for(const[d,l]of Object.entries(t.Metadata))e[`x-amz-meta-${d}`]=l;const s=this.buildUrl(t.Key,a),n=await this.aws.fetch(s,{headers:e,method:"POST",signal:o?.signal}),i=await n.text();if(!n.ok)throw new Error(`Failed to create multipart upload: ${n.status} ${i}`);const r=m(i),c=r.UploadId||r.InitiateMultipartUploadResult?.UploadId;if(!c){const d=new Error("Failed to parse UploadId from response");throw d.retryable=!1,d}return{UploadId:c}}async uploadPart(t,o){const a={partNumber:String(t.PartNumber),uploadId:t.UploadId},e={};t.ContentLength&&(e["Content-Length"]=String(t.ContentLength)),t.ContentMD5&&(e["Content-MD5"]=t.ContentMD5);const s=t.Body instanceof w?w.toWeb(t.Body):t.Body,n=this.buildUrl(t.Key,a),i=await this.aws.fetch(n,{body:s,headers:e,method:"PUT",signal:o?.signal});if(!i.ok){const c=await i.text();throw new Error(`Failed to upload part: ${i.status} ${c}`)}const r=i.headers.get("ETag");if(!r)throw new Error("Failed to get ETag from response");return{ETag:r.replaceAll(/(^"|"$)/g,"")}}async completeMultipartUpload(t,o){const a={uploadId:t.UploadId},e=`<?xml version="1.0" encoding="UTF-8"?>
2
+ <CompleteMultipartUpload xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
3
+ ${t.Parts.map(({ETag:l,PartNumber:u})=>`<Part><PartNumber>${u}</PartNumber><ETag>"${l}"</ETag></Part>`).join("")}
4
+ </CompleteMultipartUpload>`,s=this.buildUrl(t.Key,a),n=await this.aws.fetch(s,{body:e,headers:{"Content-Type":"application/xml"},method:"POST",signal:o?.signal}),i=await n.text();if(!n.ok)throw new Error(`Failed to complete multipart upload: ${n.status} ${i}`);const r=m(i),c=r.CompleteMultipartUploadResult||r,d=c.Location||`${this.endpoint}/${t.Key}`;return{ETag:c.ETag?.replaceAll(/(^"|"$)/g,""),Location:d}}async abortMultipartUpload(t,o){const a={uploadId:t.UploadId},e=this.buildUrl(t.Key,a),s=await this.aws.fetch(e,{method:"DELETE",signal:o?.signal});if(!s.ok){const n=await s.text();throw new Error(`Failed to abort multipart upload: ${s.status} ${n}`)}}async listParts(t,o){const a={uploadId:t.UploadId},e=this.buildUrl(t.Key,a),s=await this.aws.fetch(e,{method:"GET",signal:o?.signal}),n=await s.text();if(!s.ok)throw new Error(`Failed to list parts: ${s.status} ${n}`);const i=m(n),r=i.ListPartsResult||i;let c=[];return r.Part&&(c=Array.isArray(r.Part)?r.Part:[r.Part]),{Parts:c.map(d=>({ETag:d.ETag?.replaceAll(/(^"|"$)/g,""),PartNumber:Number(d.PartNumber)||0,Size:d.Size?Number(d.Size):void 0}))}}async getObject(t,o){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"GET",signal:o?.signal});if(!e.ok){const u=await e.text();throw new Error(`Failed to get object: ${e.status} ${u}`)}const s=e.headers.get("Content-Length"),n=e.headers.get("Content-Type"),i=e.headers.get("ETag"),r=e.headers.get("Expires"),c=e.headers.get("Last-Modified"),d={};for(const[u,g]of e.headers.entries())if(u.toLowerCase().startsWith("x-amz-meta-")){const f=u.toLowerCase().replace("x-amz-meta-","");d[f]=g}const{body:l}=e;return{Body:l?this.streamToReadable(l):void 0,ContentLength:s?Number(s):void 0,ContentType:n||void 0,ETag:i?.replaceAll(/(^"|"$)/g,"")||void 0,Expires:r?new Date(r):void 0,LastModified:c?new Date(c):void 0,Metadata:Object.keys(d).length>0?d:void 0}}async headObject(t,o){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"HEAD",signal:o?.signal});if(!e.ok){const l=await e.text();throw new Error(`Failed to head object: ${e.status} ${l}`)}const s=e.headers.get("Content-Length"),n=e.headers.get("Content-Type"),i=e.headers.get("ETag"),r=e.headers.get("Expires"),c=e.headers.get("Last-Modified"),d={};for(const[l,u]of e.headers.entries())if(l.toLowerCase().startsWith("x-amz-meta-")){const g=l.toLowerCase().replace("x-amz-meta-","");d[g]=u}return{ContentLength:s?Number(s):void 0,ContentType:n||void 0,ETag:i?.replaceAll(/(^"|"$)/g,"")||void 0,Expires:r?new Date(r):void 0,LastModified:c?new Date(c):void 0,Metadata:Object.keys(d).length>0?d:void 0}}async deleteObject(t,o){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"DELETE",signal:o?.signal});if(!e.ok){const s=await e.text();throw new Error(`Failed to delete object: ${e.status} ${s}`)}}async copyObject(t,o){const a={"x-amz-copy-source":t.CopySource};t.StorageClass&&(a["x-amz-storage-class"]=t.StorageClass);let e=this.buildUrl(t.Key);t.Bucket!==this.bucket&&(e=e.replace(this.bucket,t.Bucket));const s=await this.aws.fetch(e,{headers:a,method:"PUT",signal:o?.signal});if(!s.ok){const n=await s.text();throw new Error(`Failed to copy object: ${s.status} ${n}`)}}async listObjectsV2(t,o){const a={"list-type":"2"};t.MaxKeys&&(a["max-keys"]=String(t.MaxKeys)),t.ContinuationToken&&(a["continuation-token"]=t.ContinuationToken),t.Delimiter!==void 0&&(a.delimiter=t.Delimiter),t.Prefix!==void 0&&(a.prefix=t.Prefix);const e=this.buildUrl("",a),s=await this.aws.fetch(e,{method:"GET",signal:o?.signal}),n=await s.text();if(!s.ok)throw new Error(`Failed to list objects: ${s.status} ${n}`);const i=m(n),r=i.ListBucketResult||i,c=r.Contents||(Array.isArray(r.Contents)?r.Contents:[]),d=[];for(const l of n.matchAll(/<CommonPrefixes>\s*<Prefix>([^<]*)<\/Prefix>\s*<\/CommonPrefixes>/g))d.push({Prefix:l[1]});return{CommonPrefixes:d,Contents:Array.isArray(c)?c.map(l=>({Key:l.Key,LastModified:l.LastModified?new Date(String(l.LastModified)):void 0})):[],IsTruncated:r.IsTruncated==="true"||r.IsTruncated===!0,NextContinuationToken:r.NextContinuationToken}}async getPresignedUrl(t){const o={partNumber:String(t.PartNumber),uploadId:t.UploadId,"X-Amz-Expires":String(t.expiresIn)};return this.buildUrl(t.Key,o)}async putObject(t){const o=this.buildUrl(t.Key),a={};if(t.ContentType&&(a["Content-Type"]=t.ContentType),t.ContentLength!==void 0&&(a["Content-Length"]=String(t.ContentLength)),t.Metadata)for(const[n,i]of Object.entries(t.Metadata))a[`x-amz-meta-${n}`]=i;let e;t.Body===void 0?e=void 0:t.Body instanceof Uint8Array?e=new Uint8Array(t.Body):t.Body instanceof ReadableStream?e=t.Body:e=void 0;const s=await this.aws.fetch(o,{body:e,headers:a,method:"PUT"});if(!s.ok){const n=await s.text();throw new Error(`Failed to put object: ${s.status} ${n}`)}}async checkBucketAccess(t){const o=this.buildUrl(""),a=await this.aws.fetch(o,{method:"HEAD"});if(!a.ok&&a.status!==404){const e=await a.text();throw new Error(`Failed to access bucket: ${a.status} ${e}`)}}buildUrl(t,o){const a=new URL(t,this.endpoint);if(o)for(const[e,s]of Object.entries(o))a.searchParams.set(e,s);return a.toString()}streamToReadable(t){return w.fromWeb(t)}}var v=Object.defineProperty,A=p((h,t)=>v(h,"name",{value:t,configurable:!0}),"n");class S extends C{static{p(this,"l")}constructor(t){super(t),this.config=t;const o=t.bucket||process.env.S3_BUCKET||process.env.AWS_S3_BUCKET;if(!o)throw new Error("S3 bucket is not defined");this.bucket=o,this.adapter=new $({accessKeyId:t.accessKeyId,bucket:o,endpoint:t.endpoint,region:t.region,secretAccessKey:t.secretAccessKey,service:t.service,sessionToken:t.sessionToken}),this.adapter.checkBucketAccess({Bucket:o}).catch(a=>{throw a})}config;static{A(this,"AwsLightMetaStorage")}adapter;bucket;async get(t){const o=this.getMetaName(t),{Expires:a,Metadata:e}=await this.adapter.headObject({Bucket:this.bucket,Key:o});if(a&&E({expiredAt:a}))throw await this.delete(o),new Error(`Metafile ${t} not found`);if(e?.metadata!==void 0){const s=JSON.parse(decodeURIComponent(e.metadata));return s.metadata&&typeof s.metadata=="string"&&(s.metadata=x(s.metadata)),s}throw new Error(`Metafile ${t} not found`)}async touch(t,o){return this.save(t,o)}async delete(t){await this.adapter.deleteObject({Bucket:this.bucket,Key:this.getMetaName(t)})}async save(t,o){const a={...o};a.metadata&&(a.metadata=T(o.metadata));const e=encodeURIComponent(JSON.stringify(a));return await this.adapter.putObject({Bucket:this.bucket,ContentLength:0,ContentType:"application/json",Key:this.getMetaName(t),Metadata:{metadata:e}}),o}}export{S as l,$ as x};
@@ -1 +1 @@
1
- var u=Object.defineProperty;var l=(t,e)=>u(t,"name",{value:e,configurable:!0});import{throwErrorCode as d,ERRORS as p}from"./ERRORS-CyOuSMLY.js";import m from"./MetaStorage-Y4m1dWgd.js";import{parseMetadata as g,stringifyMetadata as y}from"./Metadata-B6Ir0KO7.js";import{BlobSASPermissions as f,SASProtocol as h,BlobServiceClient as c,StorageSharedKeyCredential as w}from"@azure/storage-blob";var A=Object.defineProperty,s=l((t,e)=>A(t,"name",{value:e,configurable:!0}),"a");const D=s((t,e)=>{const n=e.startsWith("?")?e.slice(1):e;return t.includes("?")?`${t}&${n}`:`${t}?${n}`},"appendSasToken"),S=300*1e3,O=s(t=>{const e={};for(const n of t.split(";")){const r=n.indexOf("=");r>0&&(e[n.slice(0,r).trim()]=n.slice(r+1).trim())}return e},"parseConnectionString"),v=s((t,e)=>t||(e?`https://${e}.blob.core.windows.net`:void 0),"resolveEndpoint"),C=s(t=>{const e=t.connectionString||process.env.AZURE_STORAGE_CONNECTION_STRING||void 0;if(e){const a=c.fromConnectionString(e);return O(e).AccountKey?{client:a,signer:{kind:"sharedKey"}}:{client:a}}const n=t.accountKey||process.env.AZURE_STORAGE_ACCOUNT_KEY||void 0,r=t.accountName||process.env.AZURE_STORAGE_ACCOUNT||void 0,i=v(t.endpoint,r);if(n){if(!r)throw new Error("Missing required parameter: Azure blob storage account name.");const a=new w(r,n);return{client:new c(i,a),signer:{kind:"sharedKey"}}}if(t.credential){if(!i)throw new Error("Missing required parameter: Azure blob storage account name or endpoint.");const a=new c(i,t.credential);return t.useUserDelegationSas===!1?{client:a}:{client:a,signer:{client:a,kind:"userDelegation"}}}const o=t.sasToken||process.env.AZURE_STORAGE_SAS_TOKEN||void 0;if(o){if(!i)throw new Error("Missing required parameter: Azure blob storage account name or endpoint.");const a=o.startsWith("?")?"":"?";return{client:new c(`${i}${a}${o}`),sasToken:o}}if(!i)throw new Error("Missing required Azure credentials: provide a connectionString, accountKey + accountName, a credential, a sasToken, or an accountName/endpoint for anonymous access.");return{anonymous:!0,client:new c(i)}},"createAzureClient"),E=s(async(t,e,n)=>{if(t.cachedKey&&t.cachedKey.expiresOn.getTime()>n.getTime())return t.cachedKey.key;if(t.pendingKey&&t.pendingKey.expiresOn.getTime()>n.getTime())return t.pendingKey.promise;const r=new Date(n.getTime()+S),i=t.client.getUserDelegationKey(e,r),o={expiresOn:r,promise:i};t.pendingKey=o;try{const a=await i;return t.cachedKey={expiresOn:r,key:a},a}finally{t.pendingKey===o&&(t.pendingKey=void 0)}},"resolveUserDelegationKey"),x=s(async(t,e,n)=>{const r=new Date(Date.now()-6e4),i=new Date(Date.now()+n.expiresIn*1e3),o={expiresOn:i,permissions:f.parse(n.permissions),protocol:h.Https,startsOn:r,...n.contentDisposition&&{contentDisposition:n.contentDisposition},...n.contentType&&{contentType:n.contentType}};if(e.kind==="sharedKey")return t.generateSasUrl(o);const a=await E(e,r,i);return t.generateUserDelegationSasUrl(o,a)},"buildAzureSasUrl");var T=Object.defineProperty,N=l((t,e)=>T(t,"name",{value:e,configurable:!0}),"o");class M extends m{static{l(this,"b")}constructor(e){super(e),this.config=e;const{client:n,...r}=e;if(this.client=n===void 0?C(r).client:n,!(r.containerName||process.env.AZURE_STORAGE_CONTAINER))throw new Error("Missing required parameter: Azure container name.");this.containerClient=this.client.getContainerClient(r.containerName)}config;static{N(this,"AzureMetaStorage")}client;containerClient;async get(e){const n=this.containerClient.getAppendBlobClient(this.getMetaName(e));let r;try{r=await n.getProperties()}catch{throw d(p.UNKNOWN_ERROR)}if(!r.metadata)throw d(p.FILE_NOT_FOUND);const i=r.metadata;return i.metadata&&typeof i.metadata=="string"&&(i.metadata=g(i.metadata)),i}async touch(e,n){return this.save(e,n)}async delete(e){await this.containerClient.getBlockBlobClient(this.getMetaName(e)).deleteIfExists()}async save(e,n){const r={...n};return r.metadata&&(r.metadata=y(n.metadata)),await this.containerClient.getAppendBlobClient(this.getMetaName(e)).setMetadata(r,{}),n}async list(){const e=[],n=this.containerClient.listBlobsFlat({prefix:this.prefix});for await(const r of n)e.push(r);return e.filter(r=>r.name.endsWith(this.suffix)).map(r=>({createdAt:r.properties.createdOn,id:this.getIdFromMetaName(r.name)}))}}export{x as a,M as b,C as c,D as d};
1
+ var u=Object.defineProperty;var l=(t,e)=>u(t,"name",{value:e,configurable:!0});import{throwErrorCode as d,ERRORS as p}from"./ERRORS-vMSqlI69.js";import m from"./MetaStorage-Y4m1dWgd.js";import{parseMetadata as g,stringifyMetadata as y}from"./Metadata-B6Ir0KO7.js";import{BlobSASPermissions as f,SASProtocol as h,BlobServiceClient as c,StorageSharedKeyCredential as w}from"@azure/storage-blob";var A=Object.defineProperty,s=l((t,e)=>A(t,"name",{value:e,configurable:!0}),"a");const D=s((t,e)=>{const n=e.startsWith("?")?e.slice(1):e;return t.includes("?")?`${t}&${n}`:`${t}?${n}`},"appendSasToken"),S=300*1e3,O=s(t=>{const e={};for(const n of t.split(";")){const r=n.indexOf("=");r>0&&(e[n.slice(0,r).trim()]=n.slice(r+1).trim())}return e},"parseConnectionString"),v=s((t,e)=>t||(e?`https://${e}.blob.core.windows.net`:void 0),"resolveEndpoint"),C=s(t=>{const e=t.connectionString||process.env.AZURE_STORAGE_CONNECTION_STRING||void 0;if(e){const a=c.fromConnectionString(e);return O(e).AccountKey?{client:a,signer:{kind:"sharedKey"}}:{client:a}}const n=t.accountKey||process.env.AZURE_STORAGE_ACCOUNT_KEY||void 0,r=t.accountName||process.env.AZURE_STORAGE_ACCOUNT||void 0,i=v(t.endpoint,r);if(n){if(!r)throw new Error("Missing required parameter: Azure blob storage account name.");const a=new w(r,n);return{client:new c(i,a),signer:{kind:"sharedKey"}}}if(t.credential){if(!i)throw new Error("Missing required parameter: Azure blob storage account name or endpoint.");const a=new c(i,t.credential);return t.useUserDelegationSas===!1?{client:a}:{client:a,signer:{client:a,kind:"userDelegation"}}}const o=t.sasToken||process.env.AZURE_STORAGE_SAS_TOKEN||void 0;if(o){if(!i)throw new Error("Missing required parameter: Azure blob storage account name or endpoint.");const a=o.startsWith("?")?"":"?";return{client:new c(`${i}${a}${o}`),sasToken:o}}if(!i)throw new Error("Missing required Azure credentials: provide a connectionString, accountKey + accountName, a credential, a sasToken, or an accountName/endpoint for anonymous access.");return{anonymous:!0,client:new c(i)}},"createAzureClient"),E=s(async(t,e,n)=>{if(t.cachedKey&&t.cachedKey.expiresOn.getTime()>n.getTime())return t.cachedKey.key;if(t.pendingKey&&t.pendingKey.expiresOn.getTime()>n.getTime())return t.pendingKey.promise;const r=new Date(n.getTime()+S),i=t.client.getUserDelegationKey(e,r),o={expiresOn:r,promise:i};t.pendingKey=o;try{const a=await i;return t.cachedKey={expiresOn:r,key:a},a}finally{t.pendingKey===o&&(t.pendingKey=void 0)}},"resolveUserDelegationKey"),x=s(async(t,e,n)=>{const r=new Date(Date.now()-6e4),i=new Date(Date.now()+n.expiresIn*1e3),o={expiresOn:i,permissions:f.parse(n.permissions),protocol:h.Https,startsOn:r,...n.contentDisposition&&{contentDisposition:n.contentDisposition},...n.contentType&&{contentType:n.contentType}};if(e.kind==="sharedKey")return t.generateSasUrl(o);const a=await E(e,r,i);return t.generateUserDelegationSasUrl(o,a)},"buildAzureSasUrl");var T=Object.defineProperty,N=l((t,e)=>T(t,"name",{value:e,configurable:!0}),"o");class M extends m{static{l(this,"b")}constructor(e){super(e),this.config=e;const{client:n,...r}=e;if(this.client=n===void 0?C(r).client:n,!(r.containerName||process.env.AZURE_STORAGE_CONTAINER))throw new Error("Missing required parameter: Azure container name.");this.containerClient=this.client.getContainerClient(r.containerName)}config;static{N(this,"AzureMetaStorage")}client;containerClient;async get(e){const n=this.containerClient.getAppendBlobClient(this.getMetaName(e));let r;try{r=await n.getProperties()}catch{throw d(p.UNKNOWN_ERROR)}if(!r.metadata)throw d(p.FILE_NOT_FOUND);const i=r.metadata;return i.metadata&&typeof i.metadata=="string"&&(i.metadata=g(i.metadata)),i}async touch(e,n){return this.save(e,n)}async delete(e){await this.containerClient.getBlockBlobClient(this.getMetaName(e)).deleteIfExists()}async save(e,n){const r={...n};return r.metadata&&(r.metadata=y(n.metadata)),await this.containerClient.getAppendBlobClient(this.getMetaName(e)).setMetadata(r,{}),n}async list(){const e=[],n=this.containerClient.listBlobsFlat({prefix:this.prefix});for await(const r of n)e.push(r);return e.filter(r=>r.name.endsWith(this.suffix)).map(r=>({createdAt:r.properties.createdOn,id:this.getIdFromMetaName(r.name)}))}}export{x as a,M as b,C as c,D as d};
@@ -1 +1 @@
1
- var b=Object.defineProperty;var u=(r,e)=>b(r,"name",{value:e,configurable:!0});import{EventEmitter as y}from"node:events";import{format as w}from"node:url";import R from"mime";import{ErrorMap as E}from"./ERRORS-CyOuSMLY.js";import{H as v}from"./headers-DC2MEOrK.js";import{Readable as p}from"node:stream";import U,{hasBody as I}from"type-is";import{B as h}from"./storage-uhIhcN-O.js";var H=Object.defineProperty,L=u((r,e)=>H(r,"name",{value:e,configurable:!0}),"a");const $=L(r=>r.at(-1),"getLastOne");var B=Object.defineProperty,i=u((r,e)=>B(r,"name",{value:e,configurable:!0}),"n");const N=i(r=>{let e="",t="";const s=c(r,"forwarded");return s&&s.split(";").forEach(a=>{const[n,o]=a.split("=");n==="proto"&&(e=o),n==="host"&&(t=o)}),{host:t,proto:e}},"extractForwarded"),x=i((r,e="utf8",t)=>new Promise((s,a)=>{const n=[];let o=0;r.on("data",l=>{const d=Buffer.isBuffer(l)?l:Buffer.from(l,e);if(o+=d.length,t!==void 0&&o>t){a(new Error("Request body length limit exceeded")),r.destroy();return}n.push(d)}),r.once("end",()=>{s(Buffer.concat(n).toString(e))}),r.once("error",a)}),"readBody"),c=i((r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const a=Array.isArray(s)?s:s.split(",");return $(a).trim()},"getHeader");i(async(r,e=16777216)=>{if(!U(r,["json"]))return{};if(r.body)return{...r.body};if(I(r)){const s=Number.parseInt(c(r,"content-length"),10);if(!Number.isNaN(s)&&s>e)throw new Error("body length limit")}const t=await x(r,"utf8",e);return{...JSON.parse(t)}},"getMetadata");const P=i((r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},"appendHeader"),V=i((r,e={})=>{const t=Object.keys(e);t.length>0&&P(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{if(["link","location"].includes(s.toLowerCase())){const a=encodeURI(e[s].toString()).replaceAll("#","%23");r.setHeader(s,a)}else r.setHeader(s,e[s])})},"setHeaders"),q=i(r=>c(r,"host")||c(r,"x-forwarded-host"),"extractHost"),F=i(r=>c(r,"x-forwarded-proto").toLowerCase(),"extractProto"),T=i(r=>{let{host:e,proto:t}=N(r);return e||=q(r),t||=F(r),e?t?`${t}://${e}`:`//${e}`:""},"getBaseUrl"),S=i(r=>{let e=(r.originalUrl||r.url||"").split("?")[0];if(!e)throw new TypeError("Invalid request URL");return e.startsWith("/")||(e=`/${e}`),e.startsWith("http")&&(e=new URL(e).pathname),e},"getRealPath"),O=/^[\da-z]{4,}(?:-[\da-z]{4,}){2,}$/i,X=i(r=>{const e=S(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let a=e.length-1;a>=0;a-=1){const n=e[a];if(!n)continue;const o=n.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(o.toLowerCase())&&O.test(o))return h.assertSafeId(o),o}const t=e[e.length-1];if(!t)throw new Error("Invalid request URL");const s=t.replace(/\.[^/.]+$/,"");if(["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(s.toLowerCase()))throw new Error("Invalid request URL");if(s.length<8)throw new Error("Invalid request URL");if(e.length>1)return h.assertSafeId(s),s;throw new Error("Invalid request URL")},"getIdFromRequest"),Y=i(r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?p.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?p.from(Buffer.from(r.body)):r instanceof p?r:p.from(new Uint8Array(0)),"getRequestStream");var j=Object.defineProperty,C=u((r,e)=>j(r,"name",{value:e,configurable:!0}),"r");const Z=C((r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},"pick");var k=Object.defineProperty,m=u((r,e)=>k(r,"name",{value:e,configurable:!0}),"d");class _ extends y{static{u(this,"E")}static{m(this,"BaseHandlerCore")}responseType="json";storage;mediaTransformer;disableTerminationForFinishedUploads;logger;get loggerInstance(){return this.logger}internalErrorResponses={};get errorResponses(){return this.internalErrorResponses}constructor({disableTerminationForFinishedUploads:e,mediaTransformer:t,storage:s}){super(),this.storage=s,this.mediaTransformer=t,this.disableTerminationForFinishedUploads=e,this.logger=this.storage?.logger,this.assembleErrors()}set errorResponses(e){this.assembleErrors(e)}assembleErrors=m((e={})=>{this.internalErrorResponses={...E,...this.internalErrorResponses,...this.storage.errorResponses,...e}},"assembleErrors");parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const a=s[0]?.trim();if(!a)return;const n=a.split("-");if(n.length!==2)return;const[o,l]=n;let d,f;if(o&&l)d=Number.parseInt(o,10),f=Number.parseInt(l,10);else if(o&&!l)d=Number.parseInt(o,10),f=t-1;else if(!o&&l){const g=Number.parseInt(l,10);d=Math.max(0,t-g),f=t-1}else return;if(!(Number.isNaN(d)||Number.isNaN(f)||d>=t||f>=t||d>f))return{end:f,start:d}}buildFileUrlFromString(e,t){const s=new URL(e,"http://localhost"),{pathname:a}=s,n=Object.fromEntries(s.searchParams.entries()),o=w({pathname:`${a}/${t.id}`,query:n});return`${this.storage.config.useRelativeLocation?"":T({url:e})}${o}.${R.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return v.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{_ as E,Z as T,c as a,Y as b,T as c,S as d,X as g,x as r,V as s,O as u};
1
+ var b=Object.defineProperty;var u=(r,e)=>b(r,"name",{value:e,configurable:!0});import{EventEmitter as y}from"node:events";import{format as w}from"node:url";import R from"mime";import{ErrorMap as E}from"./ERRORS-vMSqlI69.js";import{H as v}from"./headers-DC2MEOrK.js";import{Readable as p}from"node:stream";import U,{hasBody as I}from"type-is";import{B as h}from"./storage-CI88PmRw.js";var H=Object.defineProperty,L=u((r,e)=>H(r,"name",{value:e,configurable:!0}),"a");const $=L(r=>r.at(-1),"getLastOne");var B=Object.defineProperty,i=u((r,e)=>B(r,"name",{value:e,configurable:!0}),"n");const N=i(r=>{let e="",t="";const s=c(r,"forwarded");return s&&s.split(";").forEach(a=>{const[n,o]=a.split("=");n==="proto"&&(e=o),n==="host"&&(t=o)}),{host:t,proto:e}},"extractForwarded"),x=i((r,e="utf8",t)=>new Promise((s,a)=>{const n=[];let o=0;r.on("data",l=>{const d=Buffer.isBuffer(l)?l:Buffer.from(l,e);if(o+=d.length,t!==void 0&&o>t){a(new Error("Request body length limit exceeded")),r.destroy();return}n.push(d)}),r.once("end",()=>{s(Buffer.concat(n).toString(e))}),r.once("error",a)}),"readBody"),c=i((r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const a=Array.isArray(s)?s:s.split(",");return $(a).trim()},"getHeader");i(async(r,e=16777216)=>{if(!U(r,["json"]))return{};if(r.body)return{...r.body};if(I(r)){const s=Number.parseInt(c(r,"content-length"),10);if(!Number.isNaN(s)&&s>e)throw new Error("body length limit")}const t=await x(r,"utf8",e);return{...JSON.parse(t)}},"getMetadata");const P=i((r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},"appendHeader"),V=i((r,e={})=>{const t=Object.keys(e);t.length>0&&P(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{if(["link","location"].includes(s.toLowerCase())){const a=encodeURI(e[s].toString()).replaceAll("#","%23");r.setHeader(s,a)}else r.setHeader(s,e[s])})},"setHeaders"),q=i(r=>c(r,"host")||c(r,"x-forwarded-host"),"extractHost"),F=i(r=>c(r,"x-forwarded-proto").toLowerCase(),"extractProto"),T=i(r=>{let{host:e,proto:t}=N(r);return e||=q(r),t||=F(r),e?t?`${t}://${e}`:`//${e}`:""},"getBaseUrl"),S=i(r=>{let e=(r.originalUrl||r.url||"").split("?")[0];if(!e)throw new TypeError("Invalid request URL");return e.startsWith("/")||(e=`/${e}`),e.startsWith("http")&&(e=new URL(e).pathname),e},"getRealPath"),O=/^[\da-z]{4,}(?:-[\da-z]{4,}){2,}$/i,X=i(r=>{const e=S(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let a=e.length-1;a>=0;a-=1){const n=e[a];if(!n)continue;const o=n.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(o.toLowerCase())&&O.test(o))return h.assertSafeId(o),o}const t=e[e.length-1];if(!t)throw new Error("Invalid request URL");const s=t.replace(/\.[^/.]+$/,"");if(["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(s.toLowerCase()))throw new Error("Invalid request URL");if(s.length<8)throw new Error("Invalid request URL");if(e.length>1)return h.assertSafeId(s),s;throw new Error("Invalid request URL")},"getIdFromRequest"),Y=i(r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?p.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?p.from(Buffer.from(r.body)):r instanceof p?r:p.from(new Uint8Array(0)),"getRequestStream");var j=Object.defineProperty,C=u((r,e)=>j(r,"name",{value:e,configurable:!0}),"r");const Z=C((r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},"pick");var k=Object.defineProperty,m=u((r,e)=>k(r,"name",{value:e,configurable:!0}),"d");class _ extends y{static{u(this,"E")}static{m(this,"BaseHandlerCore")}responseType="json";storage;mediaTransformer;disableTerminationForFinishedUploads;logger;get loggerInstance(){return this.logger}internalErrorResponses={};get errorResponses(){return this.internalErrorResponses}constructor({disableTerminationForFinishedUploads:e,mediaTransformer:t,storage:s}){super(),this.storage=s,this.mediaTransformer=t,this.disableTerminationForFinishedUploads=e,this.logger=this.storage?.logger,this.assembleErrors()}set errorResponses(e){this.assembleErrors(e)}assembleErrors=m((e={})=>{this.internalErrorResponses={...E,...this.internalErrorResponses,...this.storage.errorResponses,...e}},"assembleErrors");parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const a=s[0]?.trim();if(!a)return;const n=a.split("-");if(n.length!==2)return;const[o,l]=n;let d,f;if(o&&l)d=Number.parseInt(o,10),f=Number.parseInt(l,10);else if(o&&!l)d=Number.parseInt(o,10),f=t-1;else if(!o&&l){const g=Number.parseInt(l,10);d=Math.max(0,t-g),f=t-1}else return;if(!(Number.isNaN(d)||Number.isNaN(f)||d>=t||f>=t||d>f))return{end:f,start:d}}buildFileUrlFromString(e,t){const s=new URL(e,"http://localhost"),{pathname:a}=s,n=Object.fromEntries(s.searchParams.entries()),o=w({pathname:`${a}/${t.id}`,query:n});return`${this.storage.config.useRelativeLocation?"":T({url:e})}${o}.${R.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return v.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{_ as E,Z as T,c as a,Y as b,T as c,S as d,X as g,x as r,V as s,O as u};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var u=(h,t)=>E(h,"name",{value:t,configurable:!0});import{H as m,h as b}from"./headers-DC2MEOrK.js";import{ERRORS as g,isUploadError as R}from"./ERRORS-CyOuSMLY.js";import{E as v,T as O}from"./base-handler-core-Ccvdhx-k.js";import{i as H}from"./storage-uhIhcN-O.js";import{waitForStorage as w}from"./waitForStorage-ChSBLhLc.js";var T=Object.defineProperty,x=u((h,t)=>T(h,"name",{value:t,configurable:!0}),"m");class z extends v{static{u(this,"O")}static{x(this,"BaseHandlerFetch")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(t){super(t),this.compose()}get handlers(){return this.registeredHandlers}async fetch(t){this.logger?.debug("[fetch request]: %s %s",t.method,t.url);const e=this.registeredHandlers.get(t.method||"GET");if(!e)return this.createErrorResponse({UploadErrorCode:g.METHOD_NOT_ALLOWED});try{await w(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:g.STORAGE_ERROR})}try{const r=await e.call(this,t);return this.handleFetchResponse(t,r)}catch(r){const s=r instanceof Error?r:new Error(String(r)),o={...O(s,["name",...Object.getOwnPropertyNames(s)]),request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}};return this.listenerCount("error")>0&&this.emit("error",o),this.logger?.error("[fetch error]: %O",o),this.createErrorResponse(s)}}async handleFetchResponse(t,e){if(t.method==="HEAD"||t.method==="OPTIONS"){const{headers:n,statusCode:d}=e;return new Response(void 0,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}if(t.method==="GET"){const{headers:n,statusCode:d}=e;let c="";return e.content!==void 0?c=new Uint8Array(e.content):typeof e=="object"&&"data"in e&&(c=JSON.stringify(e.data)),new Response(c,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}const{headers:r,statusCode:s,...o}=e;if(o.status!==void 0&&this.listenerCount(o.status)>0&&this.emit(o.status,{...o,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),o.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(o,n)}catch(p){throw this.logger?.error("[onComplete error]: %O",p),p}const{headers:d,statusCode:c,...f}=n,{content:j,stream:S,...C}=f;return this.createResponse({body:C,headers:d||r,statusCode:c||s||200})}const y={...r,...e.headers},a=this.convertHeaders({...y,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control",...o.hash===void 0?{}:{[`X-Range-${o.hash?.algorithm.toUpperCase()}`]:o.hash?.value}}),l=e.headers||{};l.Location&&!a.location&&!a.Location?a.location=String(l.Location):l.location&&!a.location&&!a.Location?a.location=String(l.location):r.Location&&!a.location&&!a.Location?a.location=String(r.Location):r.location&&!a.location&&!a.Location&&(a.location=String(r.location));let i;return s>=200&&s<300&&(i=Object.keys(o).length>0?{...o}:{},"content"in i&&delete i.content,"stream"in i&&delete i.stream,Object.keys(i).length===0&&(i={})),this.createResponse({body:i,headers:a,statusCode:s||200})}convertHeaders(t){const e={};for(const[r,s]of Object.entries(t))e[r]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:r={},statusCode:s}=t;let o;return s===204?o=null:typeof e=="string"?o=e:e instanceof Buffer?o=new Uint8Array(e):e&&typeof e=="object"?(o=JSON.stringify(e),r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(o="{}",r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(o,{headers:this.convertHeaders(r),status:s})}async createErrorResponse(t){let e;R(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!H(t)&&!b.isHttpError(t)?e=this.storage.normalizeError(t):e={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(e);let r;return e.body?typeof e.body=="object"&&e.body!==null?r={body:e.body,headers:e.headers,statusCode:e.statusCode}:r={body:{error:{code:e.code||e.name||"Error",message:e.body||e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500}:r={body:{error:{code:e.code||e.name||"Error",message:e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500},this.createResponse(r)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{z as O};
1
+ var E=Object.defineProperty;var u=(h,t)=>E(h,"name",{value:t,configurable:!0});import{H as m,h as b}from"./headers-DC2MEOrK.js";import{ERRORS as g,isUploadError as R}from"./ERRORS-vMSqlI69.js";import{E as v,T as O}from"./base-handler-core-ty4J6Ji6.js";import{i as H}from"./storage-CI88PmRw.js";import{waitForStorage as w}from"./waitForStorage-ChSBLhLc.js";var T=Object.defineProperty,x=u((h,t)=>T(h,"name",{value:t,configurable:!0}),"m");class z extends v{static{u(this,"O")}static{x(this,"BaseHandlerFetch")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(t){super(t),this.compose()}get handlers(){return this.registeredHandlers}async fetch(t){this.logger?.debug("[fetch request]: %s %s",t.method,t.url);const e=this.registeredHandlers.get(t.method||"GET");if(!e)return this.createErrorResponse({UploadErrorCode:g.METHOD_NOT_ALLOWED});try{await w(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:g.STORAGE_ERROR})}try{const r=await e.call(this,t);return this.handleFetchResponse(t,r)}catch(r){const s=r instanceof Error?r:new Error(String(r)),o={...O(s,["name",...Object.getOwnPropertyNames(s)]),request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}};return this.listenerCount("error")>0&&this.emit("error",o),this.logger?.error("[fetch error]: %O",o),this.createErrorResponse(s)}}async handleFetchResponse(t,e){if(t.method==="HEAD"||t.method==="OPTIONS"){const{headers:n,statusCode:d}=e;return new Response(void 0,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}if(t.method==="GET"){const{headers:n,statusCode:d}=e;let c="";return e.content!==void 0?c=new Uint8Array(e.content):typeof e=="object"&&"data"in e&&(c=JSON.stringify(e.data)),new Response(c,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}const{headers:r,statusCode:s,...o}=e;if(o.status!==void 0&&this.listenerCount(o.status)>0&&this.emit(o.status,{...o,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),o.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(o,n)}catch(p){throw this.logger?.error("[onComplete error]: %O",p),p}const{headers:d,statusCode:c,...f}=n,{content:j,stream:S,...C}=f;return this.createResponse({body:C,headers:d||r,statusCode:c||s||200})}const y={...r,...e.headers},a=this.convertHeaders({...y,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control",...o.hash===void 0?{}:{[`X-Range-${o.hash?.algorithm.toUpperCase()}`]:o.hash?.value}}),l=e.headers||{};l.Location&&!a.location&&!a.Location?a.location=String(l.Location):l.location&&!a.location&&!a.Location?a.location=String(l.location):r.Location&&!a.location&&!a.Location?a.location=String(r.Location):r.location&&!a.location&&!a.Location&&(a.location=String(r.location));let i;return s>=200&&s<300&&(i=Object.keys(o).length>0?{...o}:{},"content"in i&&delete i.content,"stream"in i&&delete i.stream,Object.keys(i).length===0&&(i={})),this.createResponse({body:i,headers:a,statusCode:s||200})}convertHeaders(t){const e={};for(const[r,s]of Object.entries(t))e[r]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:r={},statusCode:s}=t;let o;return s===204?o=null:typeof e=="string"?o=e:e instanceof Buffer?o=new Uint8Array(e):e&&typeof e=="object"?(o=JSON.stringify(e),r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(o="{}",r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(o,{headers:this.convertHeaders(r),status:s})}async createErrorResponse(t){let e;R(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!H(t)&&!b.isHttpError(t)?e=this.storage.normalizeError(t):e={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(e);let r;return e.body?typeof e.body=="object"&&e.body!==null?r={body:e.body,headers:e.headers,statusCode:e.statusCode}:r={body:{error:{code:e.code||e.name||"Error",message:e.body||e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500}:r={body:{error:{code:e.code||e.name||"Error",message:e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500},this.createResponse(r)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{z as O};
@@ -1 +1 @@
1
- var M=Object.defineProperty;var C=(i,e)=>M(i,"name",{value:e,configurable:!0});import{paginate as P}from"@visulima/pagination";import{H as T,h as z,n as y}from"./headers-DC2MEOrK.js";import O from"mime";import{isUploadError as $,ERRORS as m}from"./ERRORS-CyOuSMLY.js";import{match as k}from"path-to-regexp";import{T as S,E as q,s as A,d as U,u as x}from"./base-handler-core-Ccvdhx-k.js";import{i as D}from"./storage-uhIhcN-O.js";import{waitForStorage as _}from"./waitForStorage-ChSBLhLc.js";import{PassThrough as I}from"node:stream";import{e as H}from"./response-builder-Wdo_fvcF.js";var X=Object.defineProperty,G=C((i,e)=>X(i,"name",{value:e,configurable:!0}),"n");const W=k(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),L=G(i=>{const e=W(i);if(!e)return;const{params:t}=e;if(!t.uuid)return;const r={uuid:t.uuid};return t.metadata!==void 0&&(r.metadata=t.metadata),t.path!==void 0&&(r.path=t.path),t.ext!==void 0&&(r.ext=t.ext),{params:r,path:e.path}},"filePathUrlMatcher");var B=Object.defineProperty,v=C((i,e)=>B(i,"name",{value:e,configurable:!0}),"a");const J=v((i,e,t)=>{let r=0,a=0;const o=t-e+1;return new I({highWaterMark:Math.min(64*1024,o),transform(n,h,s){const l=n.length,d=r,p=d+l-1;if(r+=l,p<e){s();return}if(d>t){this.end(),s();return}const u=Math.max(0,e-d),f=Math.min(l,t-d+1);if(u<f){const b=n.subarray(u,f);a+=b.length,this.push(b)||i.pause()}a>=o&&(this.end(),i.destroy()),s()}})},"createRangeLimitedStream"),V=v((i,e,t)=>{let r=!1;const a=v(()=>{r||(r=!0,i.destroy())},"cleanup");e.on("drain",()=>{i.resume()}),e.on("close",a),e.on("finish",a),e.on("error",a),i.on("end",()=>{e.end()}),i.on("error",async o=>{r||(await t(e,o),a())}),i.on("data",o=>{e.write(o)||i.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",a)},"pipeWithBackpressure");v((i,e,t={})=>({headers:t,size:e,stream:i}),"createStreamResponse");var K=Object.defineProperty,w=C((i,e)=>K(i,"name",{value:e,configurable:!0}),"u");const Q=w((i,e,t)=>{const{headers:r,statusCode:a}=i;e(t,{headers:r,statusCode:a})},"handleHeadOptionsRequest"),Y=w((i,e,t,r,a,o,n)=>{e.body=i?.data===void 0?i:i.data;const{headers:h,statusCode:s}=i,l=i;if(l.stream)if(typeof r=="function")r();else{const d=n(e.headers.range,l.size||0);o(t,l.stream,{headers:h,range:d||void 0,size:l.size,statusCode:s})}else{let d="";i.content!==void 0?d=i.content:typeof i=="object"&&"data"in i&&(d=i.data),typeof r=="function"?r():a(t,{body:d,headers:h,statusCode:s})}},"handleGetRequest"),Z=w(async(i,e,t,r,a,o,n)=>{const{headers:h,statusCode:s,...l}=i;if(typeof r=="function")e._body=!0,e.body=l,r();else{const d=i,p=d.headers?{...d.headers}:{};d.headers===void 0&&(d.headers={}),d.statusCode===void 0&&(d.statusCode=200);try{const u=a.onComplete(l,d,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(d.headers||{}).length===0&&Object.keys(p).length>0?d.headers=p:d.headers&&Object.keys(p).length>0&&(d.headers={...p,...d.headers}),n(e,t,d)}},"handleCompletedUpload"),ee=w((i,e,t,r)=>{const{headers:a,statusCode:o,...n}=i,h=a||{},s=h["X-Chunked-Upload"]==="true"||h["x-chunked-upload"]==="true";let l;const d={...H(h),...a?H(a):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};s&&(l=JSON.stringify(n),!d["Content-Type"]&&!d["content-type"]&&(d["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(l=""),r(t,{body:l,headers:d,statusCode:o||200})},"handlePartialUpload"),te=w(async(i,e,t,r,a,o,n)=>{const h=i instanceof Error?i:new Error(String(i)),s={...S(h,["name",...Object.getOwnPropertyNames(h)]),request:S(e,["headers","method","url"])};r("error")>0&&t("error",s),a?.error&&a.error("[error]: %O",s),await o(n,h)},"handleUploadError");var re=Object.defineProperty,R=C((i,e)=>re(i,"name",{value:e,configurable:!0}),"C");const g="Content-Type";class N extends q{static{C(this,"F")}static{R(this,"BaseHandlerNode")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=R(async(e,t)=>this.upload(e,t),"handle");upload=R(async(e,t,r)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const a=this.registeredHandlers.get(e.method);if(!a){await this.sendError(t,{UploadErrorCode:m.METHOD_NOT_ALLOWED});return}try{await _(this.storage)}catch{await this.sendError(t,{UploadErrorCode:m.STORAGE_ERROR});return}try{const o=await a.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))Q(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&Y(n,e,t,r,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:h,...s}=o;this.logger?.debug("[%s]: %s: %d/%d",s.status,s.name,s.bytesWritten,s.size),s.status!==void 0&&this.listenerCount(s.status)>0&&this.emit(s.status,{...s,request:S(e,["headers","method","url"])}),s.status==="completed"?await Z(o,e,t,r,this.storage,this.logger,(l,d,p)=>{this.finish(l,d,p)}):ee(o,e,t,(l,d)=>{this.send(l,{body:d.body,headers:d.headers,statusCode:d.statusCode})})}}catch(o){await te(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}},"upload");send(e,{body:t="",headers:r={},statusCode:a=200}){let o;const n={...r};if(typeof t=="string"){if(o=t,n[g]===void 0)n[g]=T.createContentType({mediaType:"text/plain"});else{const h=Array.isArray(n[g])?n[g].join(", "):String(n[g]);n[g]=T.ensureCharset(h)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[g]||(n[g]=T.createContentType({charset:"utf8",mediaType:"application/json"})));A(e,n),e.statusCode=a,e.end(o)}async sendError(e,t){let r;$(t)?r=this.internalErrorResponses[t.UploadErrorCode]:!D(t)&&!z.isHttpError(t)?r=this.storage.normalizeError(t):r={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(r);let a;r.body?typeof r.body=="object"&&r.body!==null?a={body:r.body,headers:r.headers,statusCode:r.statusCode}:a={body:{error:{code:r.code||r.name||"Error",message:r.body||r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500}:a={body:{error:{code:r.code||r.name||"Error",message:r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500},this.send(e,a)}sendStream(e,t,{headers:r={},range:a,size:o,statusCode:n=200}){A(e,r),e.statusCode=n;let h=t;a&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${a.start}-${a.end}/${o}`),e.setHeader("Content-Length",a.end-a.start+1),e.setHeader("Accept-Ranges","bytes"),h=J(t,a.start,a.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),V(h,e,(s,l)=>this.sendError(s,l))}finish(e,t,r){const a="id"in r&&"headers"in r&&!("body"in r);let o,n,h;if(a){const s=r,l=s.headers||{},d=s.statusCode||200,{headers:p,statusCode:u,...f}=s;o=f,n={...l},h=d}else{const s=r;o=s.body,n=s.headers||{},h=s.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:s,contentType:l}=o;o=s,n={...n,"Content-Type":l}}this.send(t,{body:o||r,headers:n,statusCode:h})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||N.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const r=L(U(e));if(r?.params.uuid){const{ext:a,metadata:o,uuid:n}=r.params,h=a?n.replace(new RegExp(String.raw`\.${a}$`),""):n;if(o==="metadata"&&U(e).endsWith("/metadata"))try{const s=await this.storage.getMeta(h);return{...s,content:JSON.stringify(s),headers:{"Content-Type":T.createContentType({charset:"utf8",mediaType:"application/json"}),...s.expiredAt===void 0?{}:{"X-Upload-Expires":s.expiredAt.toString()},...s.modifiedAt===void 0?{}:{"Last-Modified":s.modifiedAt.toString()}},statusCode:200}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File metadata not found"):s}if(!x.test(h))return this.list(e,t);try{const s=new URL(e.url||"","http://localhost"),l=Object.fromEntries(s.searchParams.entries());if(Object.keys(l).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const c=await this.mediaTransformer.handle(h,l);return{content:c.buffer,headers:{"Content-Length":String(c.size),"Content-Type":`${c.mediaType}/${c.format}`,"X-Media-Type":c.mediaType,"X-Original-Format":c.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":c.format,...c.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":c.originalFile.expiredAt.toString()},...c.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":c.originalFile.modifiedAt.toString()},...c.originalFile?.ETag===void 0?{}:{ETag:c.originalFile.ETag}},statusCode:200}}catch(c){if(c.name==="ValidationError")throw y(400,c.message);this.logger?.warn(`Media transformation failed: ${c.message}`)}const d=await this.storage.getMeta(h);if((e.headers.range||d.size&&d.size>1024*1024)&&this.storage.getStream)try{const c=await this.storage.getStream({id:h});let E=c.headers?.["Content-Type"]||d.contentType;return E.includes("image")&&typeof a=="string"&&(E=O.getType(a)||E),{headers:{...c.headers,"Accept-Ranges":"bytes","Content-Type":E},size:c.size,statusCode:200,stream:c.stream,...d,contentType:E}}catch(c){this.logger?.warn(`Streaming failed, falling back to buffer: ${c}`)}const p=await this.storage.get({id:h});let{contentType:u}=p;u.includes("image")&&typeof a=="string"&&(u=O.getType(a)||u);const{ETag:f,expiredAt:b,modifiedAt:F,size:j}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(j),"Content-Type":u,...b===void 0?{}:{"X-Upload-Expires":b.toString()},...F===void 0?{}:{"Last-Modified":F.toString()},...f===void 0?{}:{ETag:f}},statusCode:200,...p,contentType:u}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File not found"):s}}return this.list(e,t)}async list(e,t){const r=new URL(e.url||"","http://localhost"),a=r.searchParams.get("limit"),o=r.searchParams.get("page"),n=await this.storage.list(Number(a||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&a!==void 0?{data:P(Number(o),Number(a),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const r=L(U(e));if(!r?.params.uuid||!x.test(r.params.uuid))throw y(404,"File not found");const{ext:a,uuid:o}=r.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,y(501,"Streaming download not supported"));return}const h=await this.storage.getStream({id:o});let s=h.headers?.["Content-Type"]||n.contentType;s.includes("image")&&typeof a=="string"&&(s=O.getType(a)||s);const l=this.parseRangeHeader(e.headers.range,h.size||0),d={...h.headers,"Accept-Ranges":"bytes","Content-Disposition":T.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":s};this.sendStream(t,h.stream,{headers:d,range:l||void 0,size:h.size,statusCode:l?206:200})}catch(n){const h=n;if(h.UploadErrorCode===m.FILE_NOT_FOUND||h.UploadErrorCode===m.GONE){await this.sendError(t,y(404,"File not found"));return}await this.sendError(t,n)}}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw y(404,"File not found")}}export{N as F};
1
+ var M=Object.defineProperty;var C=(i,e)=>M(i,"name",{value:e,configurable:!0});import{paginate as P}from"@visulima/pagination";import{H as T,h as z,n as y}from"./headers-DC2MEOrK.js";import O from"mime";import{isUploadError as $,ERRORS as m}from"./ERRORS-vMSqlI69.js";import{match as k}from"path-to-regexp";import{T as S,E as q,s as A,d as U,u as x}from"./base-handler-core-ty4J6Ji6.js";import{i as D}from"./storage-CI88PmRw.js";import{waitForStorage as _}from"./waitForStorage-ChSBLhLc.js";import{PassThrough as I}from"node:stream";import{e as H}from"./response-builder-Wdo_fvcF.js";var X=Object.defineProperty,G=C((i,e)=>X(i,"name",{value:e,configurable:!0}),"n");const W=k(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),L=G(i=>{const e=W(i);if(!e)return;const{params:t}=e;if(!t.uuid)return;const r={uuid:t.uuid};return t.metadata!==void 0&&(r.metadata=t.metadata),t.path!==void 0&&(r.path=t.path),t.ext!==void 0&&(r.ext=t.ext),{params:r,path:e.path}},"filePathUrlMatcher");var B=Object.defineProperty,v=C((i,e)=>B(i,"name",{value:e,configurable:!0}),"a");const J=v((i,e,t)=>{let r=0,a=0;const o=t-e+1;return new I({highWaterMark:Math.min(64*1024,o),transform(n,h,s){const l=n.length,d=r,p=d+l-1;if(r+=l,p<e){s();return}if(d>t){this.end(),s();return}const u=Math.max(0,e-d),f=Math.min(l,t-d+1);if(u<f){const b=n.subarray(u,f);a+=b.length,this.push(b)||i.pause()}a>=o&&(this.end(),i.destroy()),s()}})},"createRangeLimitedStream"),V=v((i,e,t)=>{let r=!1;const a=v(()=>{r||(r=!0,i.destroy())},"cleanup");e.on("drain",()=>{i.resume()}),e.on("close",a),e.on("finish",a),e.on("error",a),i.on("end",()=>{e.end()}),i.on("error",async o=>{r||(await t(e,o),a())}),i.on("data",o=>{e.write(o)||i.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",a)},"pipeWithBackpressure");v((i,e,t={})=>({headers:t,size:e,stream:i}),"createStreamResponse");var K=Object.defineProperty,w=C((i,e)=>K(i,"name",{value:e,configurable:!0}),"u");const Q=w((i,e,t)=>{const{headers:r,statusCode:a}=i;e(t,{headers:r,statusCode:a})},"handleHeadOptionsRequest"),Y=w((i,e,t,r,a,o,n)=>{e.body=i?.data===void 0?i:i.data;const{headers:h,statusCode:s}=i,l=i;if(l.stream)if(typeof r=="function")r();else{const d=n(e.headers.range,l.size||0);o(t,l.stream,{headers:h,range:d||void 0,size:l.size,statusCode:s})}else{let d="";i.content!==void 0?d=i.content:typeof i=="object"&&"data"in i&&(d=i.data),typeof r=="function"?r():a(t,{body:d,headers:h,statusCode:s})}},"handleGetRequest"),Z=w(async(i,e,t,r,a,o,n)=>{const{headers:h,statusCode:s,...l}=i;if(typeof r=="function")e._body=!0,e.body=l,r();else{const d=i,p=d.headers?{...d.headers}:{};d.headers===void 0&&(d.headers={}),d.statusCode===void 0&&(d.statusCode=200);try{const u=a.onComplete(l,d,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(d.headers||{}).length===0&&Object.keys(p).length>0?d.headers=p:d.headers&&Object.keys(p).length>0&&(d.headers={...p,...d.headers}),n(e,t,d)}},"handleCompletedUpload"),ee=w((i,e,t,r)=>{const{headers:a,statusCode:o,...n}=i,h=a||{},s=h["X-Chunked-Upload"]==="true"||h["x-chunked-upload"]==="true";let l;const d={...H(h),...a?H(a):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};s&&(l=JSON.stringify(n),!d["Content-Type"]&&!d["content-type"]&&(d["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(l=""),r(t,{body:l,headers:d,statusCode:o||200})},"handlePartialUpload"),te=w(async(i,e,t,r,a,o,n)=>{const h=i instanceof Error?i:new Error(String(i)),s={...S(h,["name",...Object.getOwnPropertyNames(h)]),request:S(e,["headers","method","url"])};r("error")>0&&t("error",s),a?.error&&a.error("[error]: %O",s),await o(n,h)},"handleUploadError");var re=Object.defineProperty,R=C((i,e)=>re(i,"name",{value:e,configurable:!0}),"C");const g="Content-Type";class N extends q{static{C(this,"F")}static{R(this,"BaseHandlerNode")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=R(async(e,t)=>this.upload(e,t),"handle");upload=R(async(e,t,r)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const a=this.registeredHandlers.get(e.method);if(!a){await this.sendError(t,{UploadErrorCode:m.METHOD_NOT_ALLOWED});return}try{await _(this.storage)}catch{await this.sendError(t,{UploadErrorCode:m.STORAGE_ERROR});return}try{const o=await a.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))Q(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&Y(n,e,t,r,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:h,...s}=o;this.logger?.debug("[%s]: %s: %d/%d",s.status,s.name,s.bytesWritten,s.size),s.status!==void 0&&this.listenerCount(s.status)>0&&this.emit(s.status,{...s,request:S(e,["headers","method","url"])}),s.status==="completed"?await Z(o,e,t,r,this.storage,this.logger,(l,d,p)=>{this.finish(l,d,p)}):ee(o,e,t,(l,d)=>{this.send(l,{body:d.body,headers:d.headers,statusCode:d.statusCode})})}}catch(o){await te(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}},"upload");send(e,{body:t="",headers:r={},statusCode:a=200}){let o;const n={...r};if(typeof t=="string"){if(o=t,n[g]===void 0)n[g]=T.createContentType({mediaType:"text/plain"});else{const h=Array.isArray(n[g])?n[g].join(", "):String(n[g]);n[g]=T.ensureCharset(h)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[g]||(n[g]=T.createContentType({charset:"utf8",mediaType:"application/json"})));A(e,n),e.statusCode=a,e.end(o)}async sendError(e,t){let r;$(t)?r=this.internalErrorResponses[t.UploadErrorCode]:!D(t)&&!z.isHttpError(t)?r=this.storage.normalizeError(t):r={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(r);let a;r.body?typeof r.body=="object"&&r.body!==null?a={body:r.body,headers:r.headers,statusCode:r.statusCode}:a={body:{error:{code:r.code||r.name||"Error",message:r.body||r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500}:a={body:{error:{code:r.code||r.name||"Error",message:r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500},this.send(e,a)}sendStream(e,t,{headers:r={},range:a,size:o,statusCode:n=200}){A(e,r),e.statusCode=n;let h=t;a&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${a.start}-${a.end}/${o}`),e.setHeader("Content-Length",a.end-a.start+1),e.setHeader("Accept-Ranges","bytes"),h=J(t,a.start,a.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),V(h,e,(s,l)=>this.sendError(s,l))}finish(e,t,r){const a="id"in r&&"headers"in r&&!("body"in r);let o,n,h;if(a){const s=r,l=s.headers||{},d=s.statusCode||200,{headers:p,statusCode:u,...f}=s;o=f,n={...l},h=d}else{const s=r;o=s.body,n=s.headers||{},h=s.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:s,contentType:l}=o;o=s,n={...n,"Content-Type":l}}this.send(t,{body:o||r,headers:n,statusCode:h})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||N.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const r=L(U(e));if(r?.params.uuid){const{ext:a,metadata:o,uuid:n}=r.params,h=a?n.replace(new RegExp(String.raw`\.${a}$`),""):n;if(o==="metadata"&&U(e).endsWith("/metadata"))try{const s=await this.storage.getMeta(h);return{...s,content:JSON.stringify(s),headers:{"Content-Type":T.createContentType({charset:"utf8",mediaType:"application/json"}),...s.expiredAt===void 0?{}:{"X-Upload-Expires":s.expiredAt.toString()},...s.modifiedAt===void 0?{}:{"Last-Modified":s.modifiedAt.toString()}},statusCode:200}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File metadata not found"):s}if(!x.test(h))return this.list(e,t);try{const s=new URL(e.url||"","http://localhost"),l=Object.fromEntries(s.searchParams.entries());if(Object.keys(l).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const c=await this.mediaTransformer.handle(h,l);return{content:c.buffer,headers:{"Content-Length":String(c.size),"Content-Type":`${c.mediaType}/${c.format}`,"X-Media-Type":c.mediaType,"X-Original-Format":c.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":c.format,...c.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":c.originalFile.expiredAt.toString()},...c.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":c.originalFile.modifiedAt.toString()},...c.originalFile?.ETag===void 0?{}:{ETag:c.originalFile.ETag}},statusCode:200}}catch(c){if(c.name==="ValidationError")throw y(400,c.message);this.logger?.warn(`Media transformation failed: ${c.message}`)}const d=await this.storage.getMeta(h);if((e.headers.range||d.size&&d.size>1024*1024)&&this.storage.getStream)try{const c=await this.storage.getStream({id:h});let E=c.headers?.["Content-Type"]||d.contentType;return E.includes("image")&&typeof a=="string"&&(E=O.getType(a)||E),{headers:{...c.headers,"Accept-Ranges":"bytes","Content-Type":E},size:c.size,statusCode:200,stream:c.stream,...d,contentType:E}}catch(c){this.logger?.warn(`Streaming failed, falling back to buffer: ${c}`)}const p=await this.storage.get({id:h});let{contentType:u}=p;u.includes("image")&&typeof a=="string"&&(u=O.getType(a)||u);const{ETag:f,expiredAt:b,modifiedAt:F,size:j}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(j),"Content-Type":u,...b===void 0?{}:{"X-Upload-Expires":b.toString()},...F===void 0?{}:{"Last-Modified":F.toString()},...f===void 0?{}:{ETag:f}},statusCode:200,...p,contentType:u}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File not found"):s}}return this.list(e,t)}async list(e,t){const r=new URL(e.url||"","http://localhost"),a=r.searchParams.get("limit"),o=r.searchParams.get("page"),n=await this.storage.list(Number(a||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&a!==void 0?{data:P(Number(o),Number(a),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const r=L(U(e));if(!r?.params.uuid||!x.test(r.params.uuid))throw y(404,"File not found");const{ext:a,uuid:o}=r.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,y(501,"Streaming download not supported"));return}const h=await this.storage.getStream({id:o});let s=h.headers?.["Content-Type"]||n.contentType;s.includes("image")&&typeof a=="string"&&(s=O.getType(a)||s);const l=this.parseRangeHeader(e.headers.range,h.size||0),d={...h.headers,"Accept-Ranges":"bytes","Content-Disposition":T.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":s};this.sendStream(t,h.stream,{headers:d,range:l||void 0,size:h.size,statusCode:l?206:200})}catch(n){const h=n;if(h.UploadErrorCode===m.FILE_NOT_FOUND||h.UploadErrorCode===m.GONE){await this.sendError(t,y(404,"File not found"));return}await this.sendError(t,n)}}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw y(404,"File not found")}}export{N as F};
@@ -1 +1 @@
1
- var F=Object.defineProperty;var r=(e,t)=>F(e,"name",{value:t,configurable:!0});import{tool as n}from"@anthropic-ai/claude-agent-sdk";import{T as i,e as o}from"./executors-DG6hGtvm.js";var c=Object.defineProperty,l=r((e,t)=>c(e,"name",{value:t,configurable:!0}),"o");const s={readOnlyHint:!0},p={destructiveHint:!0,readOnlyHint:!1},u={destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1},U=l(e=>({content:[{text:typeof e=="string"?e:JSON.stringify(e),type:"text"}]}),"okResult"),g=l(e=>({content:[{text:e instanceof Error?e.message:String(e),type:"text"}],isError:!0}),"errorResult"),d=l(e=>async t=>{try{return U(await e(t))}catch(a){return g(a)}},"wrap"),w=l(e=>n("listFiles",i.listFiles.description,i.listFiles.input.shape,d(t=>o.listFiles(e,t)),{annotations:s}),"claudeListFiles"),m=l(e=>n("getFileMetadata",i.getFileMetadata.description,i.getFileMetadata.input.shape,d(t=>o.getFileMetadata(e,t)),{annotations:s}),"claudeGetFileMetadata"),H=l(e=>n("downloadFile",i.downloadFile.description,i.downloadFile.input.shape,d(t=>o.downloadFile(e,t)),{annotations:s}),"claudeDownloadFile"),M=l(e=>n("getFileUrl",i.getFileUrl.description,i.getFileUrl.input.shape,d(t=>o.getFileUrl(e,t)),{annotations:s}),"claudeGetFileUrl"),O=l((e,{annotations:t=p}={})=>n("uploadFile",i.uploadFile.description,i.uploadFile.input.shape,d(a=>o.uploadFile(e,a)),{annotations:t}),"claudeUploadFile"),x=l((e,{annotations:t=p}={})=>n("deleteFile",i.deleteFile.description,i.deleteFile.input.shape,d(a=>o.deleteFile(e,a)),{annotations:t}),"claudeDeleteFile"),S=l((e,{annotations:t=u}={})=>n("copyFile",i.copyFile.description,i.copyFile.input.shape,d(a=>o.copyFile(e,a)),{annotations:t}),"claudeCopyFile"),v=l((e,{annotations:t=u}={})=>n("signUploadUrl",i.signUploadUrl.description,i.signUploadUrl.input.shape,d(a=>o.signUploadUrl(e,a)),{annotations:t}),"claudeSignUploadUrl");export{S as claudeCopyFile,x as claudeDeleteFile,H as claudeDownloadFile,m as claudeGetFileMetadata,M as claudeGetFileUrl,w as claudeListFiles,v as claudeSignUploadUrl,O as claudeUploadFile};
1
+ var F=Object.defineProperty;var r=(e,t)=>F(e,"name",{value:t,configurable:!0});import{tool as n}from"@anthropic-ai/claude-agent-sdk";import{T as i,e as o}from"./executors-MzQbS9FT.js";var c=Object.defineProperty,l=r((e,t)=>c(e,"name",{value:t,configurable:!0}),"o");const s={readOnlyHint:!0},p={destructiveHint:!0,readOnlyHint:!1},u={destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1},U=l(e=>({content:[{text:typeof e=="string"?e:JSON.stringify(e),type:"text"}]}),"okResult"),g=l(e=>({content:[{text:e instanceof Error?e.message:String(e),type:"text"}],isError:!0}),"errorResult"),d=l(e=>async t=>{try{return U(await e(t))}catch(a){return g(a)}},"wrap"),w=l(e=>n("listFiles",i.listFiles.description,i.listFiles.input.shape,d(t=>o.listFiles(e,t)),{annotations:s}),"claudeListFiles"),m=l(e=>n("getFileMetadata",i.getFileMetadata.description,i.getFileMetadata.input.shape,d(t=>o.getFileMetadata(e,t)),{annotations:s}),"claudeGetFileMetadata"),H=l(e=>n("downloadFile",i.downloadFile.description,i.downloadFile.input.shape,d(t=>o.downloadFile(e,t)),{annotations:s}),"claudeDownloadFile"),M=l(e=>n("getFileUrl",i.getFileUrl.description,i.getFileUrl.input.shape,d(t=>o.getFileUrl(e,t)),{annotations:s}),"claudeGetFileUrl"),O=l((e,{annotations:t=p}={})=>n("uploadFile",i.uploadFile.description,i.uploadFile.input.shape,d(a=>o.uploadFile(e,a)),{annotations:t}),"claudeUploadFile"),x=l((e,{annotations:t=p}={})=>n("deleteFile",i.deleteFile.description,i.deleteFile.input.shape,d(a=>o.deleteFile(e,a)),{annotations:t}),"claudeDeleteFile"),S=l((e,{annotations:t=u}={})=>n("copyFile",i.copyFile.description,i.copyFile.input.shape,d(a=>o.copyFile(e,a)),{annotations:t}),"claudeCopyFile"),v=l((e,{annotations:t=u}={})=>n("signUploadUrl",i.signUploadUrl.description,i.signUploadUrl.input.shape,d(a=>o.signUploadUrl(e,a)),{annotations:t}),"claudeSignUploadUrl");export{S as claudeCopyFile,x as claudeDeleteFile,H as claudeDownloadFile,m as claudeGetFileMetadata,M as claudeGetFileUrl,w as claudeListFiles,v as claudeSignUploadUrl,O as claudeUploadFile};
@@ -1 +1 @@
1
- var v=Object.defineProperty;var d=(e,r)=>v(e,"name",{value:r,configurable:!0});import{r as O}from"./approval-BBeX3o4E.js";import{T as F,W as y,e as o}from"./executors-DG6hGtvm.js";import*as k from"zod";var S=Object.defineProperty,h=d((e,r)=>S(e,"name",{value:r,configurable:!0}),"e");const U=h(e=>{const r=k.toJSONSchema(e),{$schema:u,...t}=r;return t},"toOpenAiJsonSchema");var A=Object.defineProperty,i=d((e,r)=>A(e,"name",{value:r,configurable:!0}),"a");const T=["listFiles","getFileMetadata","downloadFile","getFileUrl","uploadFile","deleteFile","copyFile","signUploadUrl"],f=i(e=>y.has(e),"isWriteTool"),_=i(async(e,r,u)=>{const t=F[r].input.safeParse(u);if(!t.success)return{issues:t.error.issues,ok:!1};switch(r){case"copyFile":return{ok:!0,output:await o.copyFile(e,t.data)};case"deleteFile":return{ok:!0,output:await o.deleteFile(e,t.data)};case"downloadFile":return{ok:!0,output:await o.downloadFile(e,t.data)};case"getFileMetadata":return{ok:!0,output:await o.getFileMetadata(e,t.data)};case"getFileUrl":return{ok:!0,output:await o.getFileUrl(e,t.data)};case"listFiles":return{ok:!0,output:await o.listFiles(e,t.data)};case"signUploadUrl":return{ok:!0,output:await o.signUploadUrl(e,t.data)};case"uploadFile":return{ok:!0,output:await o.uploadFile(e,t.data)};default:{const c=r;throw new Error(`Unhandled tool: ${String(c)}`)}}},"dispatch"),N=i(({files:e,overrides:r,readOnly:u=!1,requireApproval:t=!0})=>{const c=T.filter(a=>!(u&&f(a))),m=i(a=>f(a)?O(a,t):!1,"approvalFor"),g=c.map(a=>{const s=F[a],l=r?.[a];return{description:l?.description??s.description,name:a,parameters:U(s.input),strict:l?.strict??!1,type:"function"}}),w=new Set(c);return{definitions:g,execute:i(async a=>{const s=i(n=>({call_id:a.call_id,output:typeof n=="string"?n:JSON.stringify(n),type:"function_call_output"}),"wrap");if(!w.has(a.name))return s({error:`Unknown tool: ${a.name}`});let l;try{l=JSON.parse(a.arguments)}catch(n){return s({error:`Invalid JSON in arguments: ${n.message}`})}const p=await _(e,a.name,l);return p.ok?s(p.output):s({error:"Argument validation failed",issues:p.issues})},"execute"),needsApproval:m}},"createResponsesFileTools");export{N as createResponsesFileTools};
1
+ var v=Object.defineProperty;var d=(e,r)=>v(e,"name",{value:r,configurable:!0});import{r as O}from"./approval-BBeX3o4E.js";import{T as F,W as y,e as o}from"./executors-MzQbS9FT.js";import*as k from"zod";var S=Object.defineProperty,h=d((e,r)=>S(e,"name",{value:r,configurable:!0}),"e");const U=h(e=>{const r=k.toJSONSchema(e),{$schema:u,...t}=r;return t},"toOpenAiJsonSchema");var A=Object.defineProperty,i=d((e,r)=>A(e,"name",{value:r,configurable:!0}),"a");const T=["listFiles","getFileMetadata","downloadFile","getFileUrl","uploadFile","deleteFile","copyFile","signUploadUrl"],f=i(e=>y.has(e),"isWriteTool"),_=i(async(e,r,u)=>{const t=F[r].input.safeParse(u);if(!t.success)return{issues:t.error.issues,ok:!1};switch(r){case"copyFile":return{ok:!0,output:await o.copyFile(e,t.data)};case"deleteFile":return{ok:!0,output:await o.deleteFile(e,t.data)};case"downloadFile":return{ok:!0,output:await o.downloadFile(e,t.data)};case"getFileMetadata":return{ok:!0,output:await o.getFileMetadata(e,t.data)};case"getFileUrl":return{ok:!0,output:await o.getFileUrl(e,t.data)};case"listFiles":return{ok:!0,output:await o.listFiles(e,t.data)};case"signUploadUrl":return{ok:!0,output:await o.signUploadUrl(e,t.data)};case"uploadFile":return{ok:!0,output:await o.uploadFile(e,t.data)};default:{const c=r;throw new Error(`Unhandled tool: ${String(c)}`)}}},"dispatch"),N=i(({files:e,overrides:r,readOnly:u=!1,requireApproval:t=!0})=>{const c=T.filter(a=>!(u&&f(a))),m=i(a=>f(a)?O(a,t):!1,"approvalFor"),g=c.map(a=>{const s=F[a],l=r?.[a];return{description:l?.description??s.description,name:a,parameters:U(s.input),strict:l?.strict??!1,type:"function"}}),w=new Set(c);return{definitions:g,execute:i(async a=>{const s=i(n=>({call_id:a.call_id,output:typeof n=="string"?n:JSON.stringify(n),type:"function_call_output"}),"wrap");if(!w.has(a.name))return s({error:`Unknown tool: ${a.name}`});let l;try{l=JSON.parse(a.arguments)}catch(n){return s({error:`Invalid JSON in arguments: ${n.message}`})}const p=await _(e,a.name,l);return p.ok?s(p.output):s({error:"Argument validation failed",issues:p.issues})},"execute"),needsApproval:m}},"createResponsesFileTools");export{N as createResponsesFileTools};
@@ -1 +1 @@
1
- import"node:stream";import"node:timers";import"node:util";import{B as u,d as F,a as g}from"./storage-uhIhcN-O.js";import"./path-D7rMc9nq-CPbxyMDy.js";import"type-is";import"./NoOpMetrics-Dky06sf1.js";import"./cache-qV_5Umeq.js";import"./ERRORS-CyOuSMLY.js";import"./isRetryableError-CBZ65V6T.js";import"./is-expired-1JuZjDtb.js";export{u as BaseStorage,F as defaultCloudStorageFileNameValidation,g as defaultFilesystemFileNameValidation};
1
+ import"node:stream";import"node:timers";import"node:util";import{B as u,d as F,a as g}from"./storage-CI88PmRw.js";import"./path-D7rMc9nq-B718mbm6.js";import"type-is";import"./NoOpMetrics-Dky06sf1.js";import"./cache-qV_5Umeq.js";import"./ERRORS-vMSqlI69.js";import"./isRetryableError-CBZ65V6T.js";import"./is-expired-1JuZjDtb.js";export{u as BaseStorage,F as defaultCloudStorageFileNameValidation,g as defaultFilesystemFileNameValidation};
@@ -0,0 +1 @@
1
+ var F=Object.defineProperty;var h=(r,o)=>F(r,"name",{value:o,configurable:!0});import{PassThrough as w,Transform as P}from"node:stream";import{fileTypeFromBuffer as f}from"file-type";var g=Object.defineProperty,d=h((r,o)=>g(r,"name",{value:o,configurable:!0}),"u");const S=d(async r=>{try{return await f(r)}catch{return}},"detectFileTypeFromBuffer"),j=d(async(r,o)=>{const p=o?.sampleSize??4100;let m;const s=[];let u=0,a=!1,i;const n=new w({highWaterMark:0}),c=new P({objectMode:!1,transform(e,t,y){if(!a&&(s.push(e),u+=e.length,u>=p)){a=!0;const T=Buffer.concat(s);i=f(T).then(l=>(m=l,l)).catch(()=>{})}y(void 0,e)},flush(e){!a&&s.length>0&&(a=!0,i=f(Buffer.concat(s)).then(t=>(m=t,t)).catch(()=>{})),e()}});return r.pipe(c).pipe(n),r.on("error",e=>{c.destroy(e),n.destroy(e)}),c.on("error",e=>{n.destroyed||n.destroy(e)}),await Promise.race([new Promise(e=>{if(a){e();return}const t=setTimeout(e,10);c.once("data",()=>{clearTimeout(t),e()}),c.once("end",()=>{clearTimeout(t),e()})}),new Promise(e=>{setTimeout(e,10)})]),i&&await Promise.race([i.then(()=>{}),new Promise(e=>{setTimeout(e,150)})]).catch(()=>{}),{fileType:m,stream:n}},"detectFileTypeFromStream");export{S as a,j as d};
@@ -0,0 +1 @@
1
+ var mt=Object.defineProperty;var d=(e,t)=>mt(e,"name",{value:t,configurable:!0});import{createReadStream as ht,createWriteStream as dt}from"node:fs";import{truncate as yt,stat as U,copyFile as B}from"node:fs/promises";import{Transform as X,PassThrough as ft,pipeline as gt}from"node:stream";import{f as C,l as pt,w as q,U as v,_ as wt,i as bt,v as vt,E as Et,y as V}from"./local-meta-storage-tayO1ARY.js";import{createRequire as _}from"node:module";import{K as b,C as P,M as Y,L as $t,Q as St,O as Ot}from"./path-D7rMc9nq-B718mbm6.js";import{S as Tt}from"./index-B4ETk0Lu.js";import{d as Ft}from"./detect-file-type-DRWGvQW4.js";import{throwErrorCode as w,ERRORS as y,isUploadError as kt}from"./ERRORS-vMSqlI69.js";import{createHash as Nt}from"node:crypto";import{B as Pt,a as Dt,t as It}from"./storage-CI88PmRw.js";import Mt from"./File-BhfUgJjs.js";import{o as Q}from"./get-file-status-DLS18Zvd.js";import{u as _t}from"./update-size-DANV7aa2.js";import{r as Rt}from"./part-match-D_NwyoF3.js";import{o as xt}from"./has-content-Bx2p8Okx.js";var Lt=Object.defineProperty,jt=d((e,t)=>Lt(e,"name",{value:t,configurable:!0}),"i$4"),At=Object.defineProperty,G=jt((e,t)=>At(e,"name",{value:t,configurable:!0}),"t");const Ct=_(import.meta.url),F=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,zt=G(e=>{if(typeof F<"u"&&F.versions&&F.versions.node){const[t,r]=F.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return F.getBuiltinModule(e)}return Ct(e)},"__cjs_getBuiltinModule"),{lstat:Wt,writeFile:Ut}=zt("node:fs/promises");var Bt=Object.defineProperty,Vt=G((e,t)=>Bt(e,"name",{value:t,configurable:!0}),"o");const A=Vt(async e=>{C(e);try{const t=await Wt(e);if(!t.isFile())throw new Error(`Ensure path exists, expected 'file', got '${String(pt(t))}'`)}catch(t){if(t.code==="ENOENT"){await q(b(v(e))),await Ut(e,new Uint8Array);return}throw t}},"ensureFile");var Qt=Object.defineProperty,J=d((e,t)=>Qt(e,"name",{value:t,configurable:!0}),"t$1"),Ht=Object.defineProperty,Z=J((e,t)=>Ht(e,"name",{value:t,configurable:!0}),"t"),Kt=Object.defineProperty,Xt=Z((e,t)=>Kt(e,"name",{value:t,configurable:!0}),"t");let H=class extends Error{static{d(this,"l")}static{J(this,"c")}static{Z(this,"i")}static{Xt(this,"WalkError")}root;constructor(t,r){super(`${t instanceof Error?t.message:String(t)} for path "${r}"`),this.cause=t,this.root=r}get name(){return"WalkError"}set name(t){throw new Error("Cannot overwrite name of WalkError")}};var qt=Object.defineProperty,Yt=d((e,t)=>qt(e,"name",{value:t,configurable:!0}),"l$1"),Gt=Object.defineProperty,tt=Yt((e,t)=>Gt(e,"name",{value:t,configurable:!0}),"c"),Jt=Object.defineProperty,Zt=tt((e,t)=>Jt(e,"name",{value:t,configurable:!0}),"g");const K=Zt(e=>{const t=e.replace(/[$()+\\^]/g,String.raw`\$&`).replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,String.raw`\.`).replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");try{return new RegExp(`^${t}$`)}catch(r){throw new Error(`Invalid glob pattern: ${e}`,{cause:r})}},"globToRegExp");var te=Object.defineProperty,ee=tt((e,t)=>te(e,"name",{value:t,configurable:!0}),"t");const I=ee((e,t,r,i)=>{if(Array.isArray(t)&&t.length>0&&!t.some(a=>e.endsWith(a)))return!1;const o=e.includes("\\")?e.replaceAll("\\","/"):e;return r&&!r.some(a=>a.test(o))?!1:!i?.some(a=>a.test(o))},"walkInclude");var re=Object.defineProperty,et=d((e,t)=>re(e,"name",{value:t,configurable:!0}),"f$1"),ie=Object.defineProperty,z=et((e,t)=>ie(e,"name",{value:t,configurable:!0}),"y");const ae=_(import.meta.url),k=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,se=z(e=>{if(typeof k<"u"&&k.versions&&k.versions.node){const[t,r]=k.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return k.getBuiltinModule(e)}return ae(e)},"__cjs_getBuiltinModule"),{readdir:ne,realpath:oe,stat:ce}=se("node:fs/promises");var le=Object.defineProperty,p=z((e,t)=>le(e,"name",{value:t,configurable:!0}),"r");const ue=p(async e=>{const t=$t(e),r=St(t),i=await ce(t);return{isDirectory:p(()=>i.isDirectory(),"isDirectory"),isFile:p(()=>i.isFile(),"isFile"),isSymbolicLink:p(()=>i.isSymbolicLink(),"isSymbolicLink"),name:r,path:t}},"_createWalkEntry");async function*D(e,{extensions:t,followSymlinks:r=!1,includeDirs:i=!0,includeFiles:o=!0,includeSymlinks:a=!0,match:s,maxDepth:u=Number.POSITIVE_INFINITY,skip:l}={}){if(C(e),u<0)return;const m=s?s.map(c=>typeof c=="string"?K(c):c):void 0,h=l?l.map(c=>typeof c=="string"?K(c):c):void 0;if(e=P(v(e)),i&&I(e,t,m,h)&&(yield await ue(e)),!(u<1||!I(e,void 0,void 0,h)))try{const c=await ne(e,{withFileTypes:!0});for(const n of c){let g=Y(e,n.name);if(n.isSymbolicLink())if(r)g=await oe(g);else if(a&&I(g,t,m,h)){yield{isDirectory:p(()=>n.isDirectory(),"isDirectory"),isFile:p(()=>n.isFile(),"isFile"),isSymbolicLink:p(()=>n.isSymbolicLink(),"isSymbolicLink"),name:n.name,path:g};continue}else continue;n.isDirectory()?yield*D(g,{extensions:t,followSymlinks:r,includeDirs:i,includeFiles:o,includeSymlinks:a,match:m,maxDepth:u-1,skip:h}):n.isFile()&&o&&I(g,t,m,h)&&(yield{isDirectory:p(()=>n.isDirectory(),"isDirectory"),isFile:p(()=>n.isFile(),"isFile"),isSymbolicLink:p(()=>n.isSymbolicLink(),"isSymbolicLink"),name:n.name,path:g})}}catch(c){throw c instanceof H?c:new H(c,e)}}d(D,"p$2");et(D,"D");z(D,"g");p(D,"walk");var me=Object.defineProperty,rt=d((e,t)=>me(e,"name",{value:t,configurable:!0}),"t"),he=Object.defineProperty,W=rt((e,t)=>he(e,"name",{value:t,configurable:!0}),"t");const de=_(import.meta.url),N=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ye=W(e=>{if(typeof N<"u"&&N.versions&&N.versions.node){const[t,r]=N.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return N.getBuiltinModule(e)}return de(e)},"__cjs_getBuiltinModule"),{accessSync:fe}=ye("node:fs");var ge=Object.defineProperty,pe=W((e,t)=>ge(e,"name",{value:t,configurable:!0}),"o");function R(e,t=wt){C(e),e=v(e);try{return fe(e,t),!0}catch{return!1}}d(R,"i$1");rt(R,"d");W(R,"m");pe(R,"isAccessibleSync");var we=Object.defineProperty,it=d((e,t)=>we(e,"name",{value:t,configurable:!0}),"v"),be=Object.defineProperty,T=it((e,t)=>be(e,"name",{value:t,configurable:!0}),"i");const ve=_(import.meta.url),S=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,at=T(e=>{if(typeof S<"u"&&S.versions&&S.versions.node){const[t,r]=S.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return S.getBuiltinModule(e)}return ve(e)},"__cjs_getBuiltinModule"),{cwd:x}=S,{mkdir:Ee,rename:$e,copyFile:Se,unlink:Oe}=at("node:fs/promises"),{mkdirSync:Te,renameSync:Fe,copyFileSync:ke,unlinkSync:Ne}=at("node:fs");var Pe=Object.defineProperty,st=T((e,t)=>Pe(e,"name",{value:t,configurable:!0}),"o");class De extends Error{static{d(this,"V")}static{it(this,"O")}static{T(this,"a")}static{st(this,"SameDirectoryError")}constructor(t,r){super(`Source directory "${b(t)}" does not match destination directory "${b(r)}"`),this.name="SameDirectoryError"}}const nt=st((e,t)=>{if(!e||!t)throw new Error("Source and destination paths must not be empty");if(b(e)!==b(t))throw new De(e,t)},"validateSameDirectory");var Ie=Object.defineProperty,Me=T((e,t)=>Ie(e,"name",{value:t,configurable:!0}),"m$1");const ot=Me(async(e,t,{cwd:r,directoryMode:i,overwrite:o,validateDirectory:a})=>{if(r&&(e=P(r,e),t=P(r,t)),a&&nt(e,t),!o&&await bt(t))throw new Error(`The destination file exists: ${t}`);await Ee(b(t),{mode:i,recursive:!0});try{await $e(e,t)}catch(s){if(s.code==="EXDEV")await Se(e,t),await Oe(e);else throw s}},"internalMoveFile");var _e=Object.defineProperty,Re=T((e,t)=>_e(e,"name",{value:t,configurable:!0}),"m");const ct=Re((e,t,{cwd:r,directoryMode:i,overwrite:o,validateDirectory:a})=>{if(r&&(e=P(r,e),t=P(r,t)),a&&nt(e,t),!o&&R(t))throw new Error(`The destination file exists: ${t}`);Te(b(t),{mode:i,recursive:!0});try{Fe(e,t)}catch(s){if(s.code==="EXDEV")ke(e,t),Ne(e);else throw s}},"internalMoveFileSync");var xe=Object.defineProperty,L=T((e,t)=>xe(e,"name",{value:t,configurable:!0}),"i");const Le=L(async(e,t,r={})=>{const i={overwrite:!0,validateDirectory:!1,...r,cwd:r.cwd?v(r.cwd):x()};await ot(e,t,i)},"move");L((e,t,r)=>{const i={overwrite:!0,validateDirectory:!1,...r};i.cwd=i.cwd?v(i.cwd):x(),ct(e,t,i)},"moveSync");L(async(e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?v(i.cwd):x(),await ot(e,t,i)},"rename");L((e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?v(i.cwd):x(),ct(e,t,i)},"renameSync");var je=Object.defineProperty,lt=d((e,t)=>je(e,"name",{value:t,configurable:!0}),"r");class Ae extends X{static{d(this,"StreamChecksum")}constructor(t,r,i="base64"){super(),this.checksum=t,this.algorithm=r,this.encoding=i,this.hash=Nt(r)}checksum;algorithm;encoding;static{lt(this,"StreamChecksum")}length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(t,r,i){this.push(t),this.hash.update(t),this.length+=t.length,i()}_flush(t){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?t(new Error("Checksum mismatch")):t()}}const Ce=lt((e,t,r="base64")=>t?new Ae(e,t,r):new ft,"streamChecksum");var ze=Object.defineProperty,We=d((e,t)=>ze(e,"name",{value:t,configurable:!0}),"o");class Ue extends X{static{d(this,"m")}constructor(t=Number.POSITIVE_INFINITY){super(),this.limit=t}limit;static{We(this,"StreamLength")}length=0;_transform(t,r,i){const o=this.length+t.length;this.limit>=o?(this.push(t),this.length=o,i()):i(new Error("Stream length limit exceeded"))}}var Be=Object.defineProperty,M=d((e,t)=>Be(e,"name",{value:t,configurable:!0}),"F");class O extends Pt{static name="disk";checksumTypes=["md5","sha1"];supportsRange=!0;get raw(){return{directory:this.directory}}directory;meta;constructor(t){const r={...t,fileNameValidation:t.fileNameValidation??Dt};if(super(r),this.directory=r.directory,r.metaStorage)this.meta=r.metaStorage;else{const i={...r,...r.metaStorageConfig,logger:this.logger};this.meta=new vt(i)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}normalizeError(t){return super.normalizeError(t)}async create(t){return this.instrumentOperation("create",async()=>{const r={...t};if(t.ttl){const a=typeof t.ttl=="string"?It(t.ttl):t.ttl;a!==void 0&&(r.expiredAt=Date.now()+a)}r.size!==void 0&&Number(r.size)<0&&w(y.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const i=new Mt(r);try{const a=await this.getMeta(i.id);if(a.status==="completed")return a}catch{}i.name=this.namingFunction(i),(i.size===void 0||Number.isNaN(i.size))&&(i.size===void 0||(i.size=this.maxUploadSize)),await this.validate(i);const o=this.getFilePath(i.name);try{await A(o),i.bytesWritten=0}catch(a){const s=this.normalizeError(a instanceof Error?a:new Error(String(a)));await this.onError(s),w(y.FILE_ERROR,s.message)}return i.status=Q(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(t){return this.instrumentOperation("write",async()=>{let r;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?r=t:(r=await this.getMeta(t.id),await this.checkIfExpired(r)),r.status==="completed")return r;if(t.size!==void 0&&_t(r,t.size),!Rt(t,r))return w(y.FILE_CONFLICT);const i=this.getFilePath(r.name),o=await this.lock(i);try{const a=t.start||0;if(await A(i),r.bytesWritten===0&&(r.bytesWritten=a),xt(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return w(y.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(r.bytesWritten===0||Number.isNaN(r.bytesWritten))&&(!r.contentType||r.contentType==="application/octet-stream"))try{const{fileType:c,stream:n}=await Ft(t.body);c?.mime&&(r.contentType=c.mime),t.body=n}catch{}const s=t.signal,u={...r,...t,body:t.body};s&&(u.signal=s);const[l,m]=await this.lazyWrite(u);if(m)return await yt(i,r.bytesWritten),w(m);const h=a+(t.contentLength||0);r.bytesWritten=Math.max(r.bytesWritten||0,h),r.bytesWritten=Math.max(r.bytesWritten||0,l),r.status=Q(r),await this.saveMeta(r)}else await A(i),r.bytesWritten=0;return r}catch(a){if(kt(a))throw a;const s=this.normalizeError(a instanceof Error?a:new Error(String(a)));return await this.onError(s),w(y.FILE_ERROR,(typeof s.message=="string"?s.message:String(a))||String(a))}finally{await this.unlock(i,o)}})}async get({id:t},r){return this.instrumentOperation("get",async()=>{const i=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:o,contentType:a,expiredAt:s,metadata:u,modifiedAt:l,name:m,originalName:h,size:c}=i;let n;try{n=await Et(this.getFilePath(m),{buffer:!0})}catch(f){const $=f;if($.code==="ENOENT"||$.code==="EPERM"){const j=this.normalizeError(f instanceof Error?f:new Error($.message||String(f)));return await this.onError(j),w(y.FILE_NOT_FOUND,(typeof j.message=="string"?j.message:String(f))||String(f))}const ut=this.normalizeError(f instanceof Error?f:new Error(String(f)));throw await this.onError(ut),f}const g=Tt(n),E=r?.range;if(E){const f=Math.max(0,E.start),$=E.end===void 0?n.length-1:Math.min(n.length-1,E.end);if(f>$||f>=n.length)return w(y.BAD_REQUEST,`Invalid range ${f}-${E.end??""}`);n=n.subarray(f,$+1)}return{content:n,contentType:a,ETag:g,expiredAt:s,id:t,metadata:u,modifiedAt:l,name:m,originalName:h,size:E?n.length:c||o}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{const r=await this.getMeta(t),i=this.getFilePath(r.name);return await U(i),!0}catch{return!1}})}async getStream({id:t}){return this.instrumentOperation("getStream",async()=>{try{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:i,contentType:o,expiredAt:a,modifiedAt:s,name:u,size:l}=r,m=ht(this.getFilePath(u));return{headers:{"Content-Length":String(l||i),"Content-Type":o,...a&&{"X-Upload-Expires":a.toString()},...s&&{"Last-Modified":s.toString()}},size:l||i,stream:m}}catch(r){const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));throw await this.onError(i),w(y.FILE_NOT_FOUND,(typeof i.message=="string"?i.message:String(r))||String(r))}})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const r=await this.getMeta(t);await V(this.getFilePath(r.name)),await this.deleteMeta(t);const i={...r,status:"deleted"};return await this.onDelete(i),i})}async copy(t,r){return this.instrumentOperation("copy",async()=>{O.assertSafeId(t),O.assertSafeId(r);const i=await this.getMeta(t);return await B(this.getFilePath(i.name),this.getFilePath(r)),{...i,name:r}})}async move(t,r){return this.instrumentOperation("move",async()=>{O.assertSafeId(t),O.assertSafeId(r);const i=await this.getMeta(t),o=this.getFilePath(i.name),a=this.getFilePath(r);try{await Le(o,a)}catch(s){if(s?.code==="EXDEV")await B(o,a),await V(o);else{const u=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(u),s}}return{...i,id:i.id,name:r}})}async list(){return this.instrumentOperation("list",async()=>{const t={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},r=[],{directory:i}=this,o=M(s=>s.replaceAll("\\","/"),"toPosix"),a=o(i);for await(const s of D(i,t)){const{suffix:u}=this.meta,{path:l}=s;if(!l.includes(u)){const{birthtime:m,ctime:h,mtime:c}=await U(l),n=o(l),g=n.startsWith(a)?n.slice(a.length):n;r.push({createdAt:m||h,id:g,modifiedAt:c})}}return r})}getFilePath(t){return O.assertSafeId(t),Ot(t)&&w(y.INVALID_FILE_NAME,`Invalid file id: "${t}"`),Y(this.directory,t)}lazyWrite(t){return new Promise((r,i)=>{const o=dt(this.getFilePath(t.name),{flags:"r+",start:t.start}),a=new Ue(t.contentLength||t.size-t.start),s=Ce(t.checksum,t.checksumAlgorithm),u=!t.checksum,{signal:l}=t,m=M(()=>{o.close(),a.destroy(),s.destroy()},"cleanupStreams"),h=M(n=>{m(),r([Number.NaN,n])},"failWithCode");if(a.on("error",()=>{h(y.FILE_CONFLICT)}),s.on("error",()=>{h(y.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{h(u?void 0:y.REQUEST_ABORTED)}),t.body.on("error",n=>{m(),i(n)}),l?.aborted){h(u?void 0:y.REQUEST_ABORTED);return}let c;l&&(c=M(()=>{m(),o.destroy(),a.destroy(),s.destroy(),t.body.destroy(),r([Number.NaN,u?void 0:y.REQUEST_ABORTED])},"onAbort"),l.addEventListener("abort",c,{once:!0})),gt(t.body,a,s,o,n=>{if(l&&c&&l.removeEventListener("abort",c),n){if(m(),l?.aborted){r([Number.NaN,u?void 0:y.REQUEST_ABORTED]);return}r([Number.NaN,y.FILE_ERROR]);return}r([t.start+o.bytesWritten])})})}async accessCheck(){await q(this.directory)}}export{Ue as m,O as p,Ce as s,A as y};
@@ -1,4 +1,4 @@
1
- import { F as File, M as MetaStorage, D as DiskStorageOptions, H as HttpError, e as FileInit, f as FilePart, g as FileQuery, O as OperationOptions, a as FileReturn, E as ERRORS, B as BaseStorage, j as DiskStorageWithChecksumOptions } from "./storage.d-X6TimMHY.js";
1
+ import { F as File, M as MetaStorage, D as DiskStorageOptions, H as HttpError, b as FileInit, d as FilePart, e as FileQuery, O as OperationOptions, a as FileReturn, E as ERRORS, B as BaseStorage, h as DiskStorageWithChecksumOptions } from "./storage.d-C6HtvSoY.js";
2
2
  import { Readable } from 'node:stream';
3
3
  /**
4
4
  * Local disk-based storage implementation.
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var y=(t,n)=>u(t,"name",{value:n,configurable:!0});import*as e from"zod";const m=1024*1024,p=10*1024*1024,f=e.object({limit:e.int().positive().max(1e3).optional().meta({description:"Maximum number of items to return"}),prefix:e.string().trim().optional().meta({description:"Only return keys that start with this prefix"})}),g=e.object({key:e.string().trim().meta({description:"The object key to inspect"})}),b=e.object({binary:e.boolean().optional().meta({description:"When true, returns base64-encoded bytes instead of UTF-8 text"}),key:e.string().trim().meta({description:"The object key to download"}),maxBytes:e.int().positive().max(p).optional().meta({description:`Reject downloads larger than this byte count (default ${m}, maximum ${p}). Verified via head() before transferring.`})}),h=e.object({expiresIn:e.int().positive().optional().meta({description:"Override the adapter default URL expiry in seconds. Ignored by permanent-CDN adapters."}),key:e.string().trim().meta({description:"The object key to build a URL for"}),responseContentDisposition:e.string().trim().optional().meta({description:`Force a Content-Disposition header on the response (e.g. 'attachment; filename="f.txt"'). Strongly recommended for user-uploaded content to prevent inline rendering of HTML/SVG.`})}),F=e.object({content:e.string().meta({description:'File body. Treated as UTF-8 text unless encoding is "base64".'}),contentType:e.string().trim().optional().meta({description:"MIME type recorded with the object"}),encoding:e.enum(["text","base64"]).optional().meta({description:"How to interpret content (default: text)"}),key:e.string().trim().meta({description:"Destination object key"}),metadata:e.record(e.string().trim(),e.string()).optional().meta({description:"Custom string metadata to attach to the object"})}),k=e.object({key:e.string().trim().meta({description:"Object key to delete"})}),w=e.object({from:e.string().trim().meta({description:"Source object key"}),to:e.string().trim().meta({description:"Destination object key"})}),x=e.object({contentType:e.string().trim().optional().meta({description:"Content-Type that the upload must declare"}),expiresIn:e.int().positive().meta({description:"Lifetime of the presigned URL in seconds"}),key:e.string().trim().meta({description:"Destination object key"})}),S={copyFile:{description:"Copy a file to a new key within the configured bucket. The source remains intact.",input:w},deleteFile:{description:"Permanently delete a file from the configured bucket.",input:k},downloadFile:{description:"Download a file and return its contents. Returns UTF-8 text by default; set binary=true to receive base64-encoded bytes. Files larger than maxBytes are rejected before transfer.",input:b},getFileMetadata:{description:"Fetch metadata for a single file (size, content type, etag, custom metadata) without transferring its body.",input:g},getFileUrl:{description:"Return a signed, time-limited URL the caller can use to fetch a file. Adapters that don't support presigning will throw MethodNotAllowed.",input:h},listFiles:{description:"List files in the configured bucket, optionally filtered by key prefix.",input:f},signUploadUrl:{description:"Issue a presigned URL that lets a client upload directly to the configured bucket. Approval-gated by default — the URL grants upload permission until it expires.",input:x},uploadFile:{description:'Upload a file to the configured bucket. Pass content as UTF-8 text by default, or as base64 with encoding="base64" for binary payloads.',input:F}},T=["uploadFile","deleteFile","copyFile","signUploadUrl"],j=new Set(T);var U=Object.defineProperty,s=y((t,n)=>U(t,"name",{value:n,configurable:!0}),"r");const l=s(t=>{if(t!==void 0)return t instanceof Date?t.toISOString():typeof t=="number"?new Date(t).toISOString():t},"serializeLastModified"),I={copyFile:s(async(t,{from:n,to:i})=>{const o=await t.copy(n,i);return{copied:!0,etag:o.etag,from:n,key:o.key,to:i}},"copyFile"),deleteFile:s(async(t,{key:n})=>(await t.delete(n),{deleted:!0,key:n}),"deleteFile"),downloadFile:s(async(t,{binary:n,key:i,maxBytes:o})=>{const r=o??m;if(r>p)throw new RangeError(`downloadFile refused: maxBytes (${r}) exceeds the maximum of ${p}. Use getFileUrl to delegate larger downloads to the client.`);const c=await t.head(i);if(typeof c.size=="number"&&c.size>r)throw new RangeError(`downloadFile refused: "${i}" is ${c.size} bytes which exceeds the maxBytes limit of ${r}. Use getFileUrl to delegate to the client, or raise maxBytes.`);const a=await t.download(i);if(a.body.byteLength>r)throw new RangeError(`downloadFile refused: "${i}" returned ${a.body.byteLength} bytes which exceeds the maxBytes limit of ${r}. Use getFileUrl instead.`);return n?{content:a.body.toString("base64"),contentType:a.contentType,encoding:"base64",key:a.key,...typeof a.size=="number"?{size:a.size}:{}}:{content:a.body.toString("utf8"),contentType:a.contentType,encoding:"text",key:a.key,...typeof a.size=="number"?{size:a.size}:{}}},"downloadFile"),getFileMetadata:s(async(t,{key:n})=>{const i=await t.head(n);return{contentType:i.contentType,...i.etag?{etag:i.etag}:{},key:i.key,...l(i.lastModified)?{lastModified:l(i.lastModified)}:{},...i.metadata?{metadata:i.metadata}:{},...typeof i.size=="number"?{size:i.size}:{}}},"getFileMetadata"),getFileUrl:s(async(t,{expiresIn:n,key:i,responseContentDisposition:o})=>{const r=await t.url(i,{expiresIn:n,responseContentDisposition:o});return{key:i,url:r}},"getFileUrl"),listFiles:s(async(t,{limit:n,prefix:i})=>({items:(await t.list({limit:n,prefix:i})).map(o=>({contentType:o.contentType,...o.etag?{etag:o.etag}:{},key:o.key,...l(o.lastModified)?{lastModified:l(o.lastModified)}:{},...typeof o.size=="number"?{size:o.size}:{}}))}),"listFiles"),signUploadUrl:s(async(t,{contentType:n,expiresIn:i,key:o})=>{const r=await t.signedUploadUrl(o,{contentType:n,expiresIn:i});return{key:o,url:r}},"signUploadUrl"),uploadFile:s(async(t,{content:n,contentType:i,encoding:o,key:r,metadata:c})=>{const a=o==="base64"?Buffer.from(n,"base64"):Buffer.from(n,"utf8"),d=await t.upload(r,a,{contentType:i,metadata:c});return{contentType:d.contentType,...d.etag?{etag:d.etag}:{},key:d.key,...l(d.lastModified)?{lastModified:l(d.lastModified)}:{},...typeof d.size=="number"?{size:d.size}:{}}},"uploadFile")};export{S as T,j as W,I as e};
@@ -1,4 +1,4 @@
1
- import { F as Files } from "./index.d-CYdFIB-w.js";
1
+ import { F as Files } from "./index.d-DB1VD8RP.js";
2
2
  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";
3
3
  interface CopyFileResult {
4
4
  copied: true;
@@ -1 +1 @@
1
- var g=Object.defineProperty;var o=(s,t)=>g(s,"name",{value:t,configurable:!0});import{randomUUID as y}from"node:crypto";import{request as f}from"gaxios";import{GoogleAuth as C}from"google-auth-library";import v from"./MetaStorage-Y4m1dWgd.js";import{stringifyMetadata as R,parseMetadata as E}from"./Metadata-B6Ir0KO7.js";import n from"./GCSConfig-BQ0OpVhe.js";import{o as $}from"./has-content-Bx2p8Okx.js";var I="@visulima/storage",P="1.0.0-alpha.31";const i={name:I,version:P};var A=Object.defineProperty,u=o((s,t)=>A(s,"name",{value:t,configurable:!0}),"n");const T=u(s=>{const t=s.match(/(\d+)-(\d+)/),e=t?.[2]?+t[2]:0;return e>0?e+1:0},"getRangeEnd"),G=u(s=>{if($(s)){const t=s.contentLength?s.start+s.contentLength-1:"*";return`bytes ${s.start}-${t}/${s.size??"*"}`}return`bytes */${s.size??"*"}`},"buildContentRange"),U=u(s=>{if(s.response!==void 0){const{response:t}=s;return t?.data?.error?.errors?.map(({reason:e=""})=>e==="rateLimitExceeded"||e==="userRateLimitExceeded"?!0:!!(e&&e.includes("EAI_AGAIN"))).includes(!0)}return!1},"shouldRetry"),w={retry:3,shouldRetry:U,statusCodesToRetry:[[408,429,500,502,503,504],[100,199],[429],[500,599]]};var b=Object.defineProperty,j=o((s,t)=>b(s,"name",{value:t,configurable:!0}),"p");class N extends v{static{o(this,"E")}constructor(t){super(t),this.config=t;const{authClient:e,...a}=t,r=a.bucket||process.env.GCS_BUCKET;if(e===void 0){if(!r)throw new Error("GCS bucket is not defined");if(!a.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");a.scopes||=n.authScopes,this.authClient=new C(a)}else this.authClient=e;this.storageBaseURI=`${a.storageAPI||n.storageAPI}/${r}/o`,this.uploadBaseURI=`${a.uploadAPI||n.uploadAPI}/${r}/o`;const h=["storage.googleapis.com"],d=new URL(this.storageBaseURI).hostname;this.isCustomEndpoint=!h.includes(d);const{retryOptions:m,useAuthWithCustomEndpoint:p,userProject:l}=t;this.userProject=l,this.useAuthWithCustomEndpoint=p||!1,this.retryOptions={...w,...m},e===void 0&&this.accessCheck().catch(c=>{throw c.code==="404"?new Error(`Bucket ${r} does not exist`):c})}config;static{j(this,"GCSMetaStorage")}authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;async save(t,e){const a={...e};return a.metadata&&(a.metadata=R(e.metadata)),await this.makeRequest({body:JSON.stringify(a),headers:{"Content-Type":"application/json; charset=utf-8"},method:"POST",params:{name:encodeURIComponent(this.getMetaName(t)),uploadType:"media"},url:this.uploadBaseURI}),e}async delete(t){const e=this.getMetaPath(t);await this.makeRequest({method:"DELETE",url:e})}async get(t){const e=this.getMetaPath(t),{data:a}=await this.makeRequest({params:{alt:"media"},url:e});return a.metadata&&typeof a.metadata=="string"&&(a.metadata=E(a.metadata)),a}async touch(t,e){return this.save(t,e)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}getMetaPath(t){return`${this.storageBaseURI}/${this.getMetaName(t)}`}async makeRequest(t){return typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":")),t={...t,headers:{"User-Agent":`${i.name}/${i.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${i.version} gccl-invocation-id/${y()}`},params:{...this.userProject===void 0?{}:{userProject:this.userProject}},retry:!0,retryConfig:this.retryOptions,timeout:6e4},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?f(t):this.authClient.request(t)}}export{N as E,G as b,i as d,T as g,w as r};
1
+ var g=Object.defineProperty;var o=(s,t)=>g(s,"name",{value:t,configurable:!0});import{randomUUID as y}from"node:crypto";import{request as f}from"gaxios";import{GoogleAuth as C}from"google-auth-library";import v from"./MetaStorage-Y4m1dWgd.js";import{stringifyMetadata as R,parseMetadata as E}from"./Metadata-B6Ir0KO7.js";import n from"./GCSConfig-BQ0OpVhe.js";import{o as $}from"./has-content-Bx2p8Okx.js";var I="@visulima/storage",P="1.0.0-alpha.33";const i={name:I,version:P};var A=Object.defineProperty,u=o((s,t)=>A(s,"name",{value:t,configurable:!0}),"n");const T=u(s=>{const t=s.match(/(\d+)-(\d+)/),e=t?.[2]?+t[2]:0;return e>0?e+1:0},"getRangeEnd"),G=u(s=>{if($(s)){const t=s.contentLength?s.start+s.contentLength-1:"*";return`bytes ${s.start}-${t}/${s.size??"*"}`}return`bytes */${s.size??"*"}`},"buildContentRange"),U=u(s=>{if(s.response!==void 0){const{response:t}=s;return t?.data?.error?.errors?.map(({reason:e=""})=>e==="rateLimitExceeded"||e==="userRateLimitExceeded"?!0:!!(e&&e.includes("EAI_AGAIN"))).includes(!0)}return!1},"shouldRetry"),w={retry:3,shouldRetry:U,statusCodesToRetry:[[408,429,500,502,503,504],[100,199],[429],[500,599]]};var b=Object.defineProperty,j=o((s,t)=>b(s,"name",{value:t,configurable:!0}),"p");class N extends v{static{o(this,"E")}constructor(t){super(t),this.config=t;const{authClient:e,...a}=t,r=a.bucket||process.env.GCS_BUCKET;if(e===void 0){if(!r)throw new Error("GCS bucket is not defined");if(!a.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");a.scopes||=n.authScopes,this.authClient=new C(a)}else this.authClient=e;this.storageBaseURI=`${a.storageAPI||n.storageAPI}/${r}/o`,this.uploadBaseURI=`${a.uploadAPI||n.uploadAPI}/${r}/o`;const h=["storage.googleapis.com"],d=new URL(this.storageBaseURI).hostname;this.isCustomEndpoint=!h.includes(d);const{retryOptions:m,useAuthWithCustomEndpoint:p,userProject:l}=t;this.userProject=l,this.useAuthWithCustomEndpoint=p||!1,this.retryOptions={...w,...m},e===void 0&&this.accessCheck().catch(c=>{throw c.code==="404"?new Error(`Bucket ${r} does not exist`):c})}config;static{j(this,"GCSMetaStorage")}authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;async save(t,e){const a={...e};return a.metadata&&(a.metadata=R(e.metadata)),await this.makeRequest({body:JSON.stringify(a),headers:{"Content-Type":"application/json; charset=utf-8"},method:"POST",params:{name:encodeURIComponent(this.getMetaName(t)),uploadType:"media"},url:this.uploadBaseURI}),e}async delete(t){const e=this.getMetaPath(t);await this.makeRequest({method:"DELETE",url:e})}async get(t){const e=this.getMetaPath(t),{data:a}=await this.makeRequest({params:{alt:"media"},url:e});return a.metadata&&typeof a.metadata=="string"&&(a.metadata=E(a.metadata)),a}async touch(t,e){return this.save(t,e)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}getMetaPath(t){return`${this.storageBaseURI}/${this.getMetaName(t)}`}async makeRequest(t){return typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":")),t={...t,headers:{"User-Agent":`${i.name}/${i.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${i.version} gccl-invocation-id/${y()}`},params:{...this.userProject===void 0?{}:{userProject:this.userProject}},retry:!0,retryConfig:this.retryOptions,timeout:6e4},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?f(t):this.authClient.request(t)}}export{N as E,G as b,i as d,T as g,w as r};