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

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 (173) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +2 -2
  3. package/dist/adapter/nuxt/module.d.ts +4 -4
  4. package/dist/adapter/nuxt/node_modules/.bin/nuxi +2 -2
  5. package/dist/adapter/nuxt/node_modules/.bin/nuxt +2 -2
  6. package/dist/ai/ai-sdk/index.d.ts +3 -3
  7. package/dist/ai/claude/index.d.ts +2 -2
  8. package/dist/ai/openai/index.d.ts +3 -3
  9. package/dist/ai/tanstack/index.d.ts +2 -2
  10. package/dist/handler/http/fetch/index.d.ts +7 -7
  11. package/dist/handler/http/fetch/index.js +1 -1
  12. package/dist/handler/http/hono/index.d.ts +4 -4
  13. package/dist/handler/http/hono/index.js +1 -1
  14. package/dist/handler/http/nextjs/index.d.ts +4 -4
  15. package/dist/handler/http/nextjs/index.js +1 -1
  16. package/dist/handler/http/node/index.d.ts +7 -7
  17. package/dist/handler/http/node/index.js +1 -1
  18. package/dist/handler/http/solid-start/index.d.ts +4 -4
  19. package/dist/handler/http/solid-start/index.js +1 -1
  20. package/dist/index.d.ts +6 -5
  21. package/dist/index.js +1 -1
  22. package/dist/packem_shared/{AwsLightStorage-DbQrK9m7.js → AwsLightStorage-B1jNF7sv.js} +1 -1
  23. package/dist/packem_shared/AzureStorage-B4E6VLn5.js +1 -0
  24. package/dist/packem_shared/{BoxMetaStorage-DLdXbZaV.js → BoxMetaStorage-nESVquA1.js} +1 -1
  25. package/dist/packem_shared/BoxStorage-CHYDrcxw.js +1 -0
  26. package/dist/packem_shared/{BunS3MetaStorage-Bv_CTTMz.js → BunS3MetaStorage-BkZx5q4w.js} +1 -1
  27. package/dist/packem_shared/BunS3Storage-BopE7kmX.js +1 -0
  28. package/dist/packem_shared/{BunnyMetaStorage-DNMTSeoN.js → BunnyMetaStorage-bB8NXGUI.js} +1 -1
  29. package/dist/packem_shared/BunnyStorage-C3IBxJqr.js +1 -0
  30. package/dist/packem_shared/{CloudinaryMetaStorage-DEBk5eQy.js → CloudinaryMetaStorage-BzibHydK.js} +1 -1
  31. package/dist/packem_shared/CloudinaryStorage-Cj00ZXWV.js +1 -0
  32. package/dist/packem_shared/DiskStorage-BrAb28Je.js +1 -0
  33. package/dist/packem_shared/DiskStorageWithChecksum-BX85CHJ6.js +1 -0
  34. package/dist/packem_shared/{DropboxMetaStorage-C6vj1QDA.js → DropboxMetaStorage-Bfm5bblb.js} +1 -1
  35. package/dist/packem_shared/DropboxStorage-Btz9h9Mj.js +1 -0
  36. package/dist/packem_shared/Files-tnc_buzM.js +1 -0
  37. package/dist/packem_shared/{FirebaseMetaStorage-CzyOim-J.js → FirebaseMetaStorage-CshnJMb0.js} +1 -1
  38. package/dist/packem_shared/FirebaseStorage-Y9P6Dx8I.js +2 -0
  39. package/dist/packem_shared/{FtpMetaStorage-1Njy0DpU.js → FtpMetaStorage-CoyWJafY.js} +1 -1
  40. package/dist/packem_shared/FtpStorage-DCKPMX0z.js +1 -0
  41. package/dist/packem_shared/{GCSMetaStorage-DFIjFmn-.js → GCSMetaStorage-CfZj52hQ.js} +1 -1
  42. package/dist/packem_shared/GCStorage-hfL1u2KQ.js +1 -0
  43. package/dist/packem_shared/{GoogleDriveMetaStorage-WGuUZPyx.js → GoogleDriveMetaStorage-CBSdEQr6.js} +1 -1
  44. package/dist/packem_shared/GoogleDriveStorage-C7iuV7qb.js +1 -0
  45. package/dist/packem_shared/{LocalMetaStorage-QMKL7McF.js → LocalMetaStorage-DSwsmdt7.js} +1 -1
  46. package/dist/packem_shared/MemoryMetaStorage-DEzfBNgL.js +1 -0
  47. package/dist/packem_shared/{Multipart-DkH4QwNs.js → Multipart-kQ5wJQaV.js} +1 -1
  48. package/dist/packem_shared/{Multipart-C6Mw7V9W.js → Multipart-qaEOWKz1.js} +1 -1
  49. package/dist/packem_shared/{NetlifyBlobMetaStorage-ClIFdTkT.js → NetlifyBlobMetaStorage-CqluIgV0.js} +1 -1
  50. package/dist/packem_shared/NetlifyBlobStorage-CkMw9Uyv.js +1 -0
  51. package/dist/packem_shared/{OneDriveMetaStorage-DS4f83X2.js → OneDriveMetaStorage-DPTNMpeq.js} +1 -1
  52. package/dist/packem_shared/OneDriveStorage-CEGYb6OC.js +1 -0
  53. package/dist/packem_shared/{PocketBaseMetaStorage-B6utPncj.js → PocketBaseMetaStorage-CemTT_01.js} +1 -1
  54. package/dist/packem_shared/PocketBaseStorage-BZNzWj09.js +1 -0
  55. package/dist/packem_shared/{Rest-DY1neM_3.js → Rest-BAcUFAgk.js} +1 -1
  56. package/dist/packem_shared/{Rest-DWrS4Z_j.js → Rest-DukkeDZe.js} +1 -1
  57. package/dist/packem_shared/S3Storage-7hG3izjU.js +1 -0
  58. package/dist/packem_shared/{SftpMetaStorage-DYqXwCdM.js → SftpMetaStorage-Cs8b7uBO.js} +1 -1
  59. package/dist/packem_shared/SftpStorage-DnigT9GT.js +1 -0
  60. package/dist/packem_shared/{SharePointMetaStorage-DVM5-X6g.js → SharePointMetaStorage-DTVKAx6f.js} +1 -1
  61. package/dist/packem_shared/{SharePointStorage-r934t5HX.js → SharePointStorage-D1cWu-14.js} +1 -1
  62. package/dist/packem_shared/{SupabaseMetaStorage-ivXoYVUu.js → SupabaseMetaStorage-D_fGv0d6.js} +1 -1
  63. package/dist/packem_shared/SupabaseStorage-DbIUa6NZ.js +1 -0
  64. package/dist/packem_shared/{Tus-d2hPK5nV.js → Tus-BYTcw17H.js} +1 -1
  65. package/dist/packem_shared/{Tus-BMd67Cnb.js → Tus-BrP4RFTg.js} +1 -1
  66. package/dist/packem_shared/{UploadThingMetaStorage-BvKNzgm7.js → UploadThingMetaStorage-CAQ1uTfv.js} +1 -1
  67. package/dist/packem_shared/UploadThingStorage-B1qw1GrM.js +1 -0
  68. package/dist/packem_shared/{VercelBlobMetaStorage-CwaqWucZ.js → VercelBlobMetaStorage-DY4zAB6M.js} +1 -1
  69. package/dist/packem_shared/VercelBlobStorage-u6xmp8ox.js +1 -0
  70. package/dist/packem_shared/{base-handler-core-Cwd9uq_E.js → base-handler-core-Ccvdhx-k.js} +1 -1
  71. package/dist/packem_shared/{base-handler-fetch-_BD4V1W2.js → base-handler-fetch-DzbThEWy.js} +1 -1
  72. package/dist/packem_shared/{base-handler-node-BDNRnVIc.js → base-handler-node-CmCpLlBt.js} +1 -1
  73. package/dist/packem_shared/default-BrhEhSqN.js +1 -0
  74. package/dist/packem_shared/{defaultCloudStorageFileNameValidation-hWLdEgOD.js → defaultCloudStorageFileNameValidation-DwDn0XB5.js} +1 -1
  75. package/dist/packem_shared/disk-storage-fWizVrge.js +1 -0
  76. package/dist/packem_shared/{disk-storage-with-checksum.d-Dm4agCey.d.ts → disk-storage-with-checksum.d-aYBmkg45.d.ts} +8 -2
  77. package/dist/packem_shared/{executors.d-Cut3Gstb.d.ts → executors.d-WGJGPSZs.d.ts} +1 -1
  78. package/dist/packem_shared/{gcs-meta-storage-Bwts-MUe.js → gcs-meta-storage-COq32th7.js} +1 -1
  79. package/dist/packem_shared/get-file-status-DLS18Zvd.js +1 -0
  80. package/dist/packem_shared/index.d-CYdFIB-w.d.ts +455 -0
  81. package/dist/packem_shared/isRetryableError-CBZ65V6T.js +1 -0
  82. package/dist/packem_shared/local-meta-storage-Dr891Iy7.js +1 -0
  83. package/dist/packem_shared/{local-meta-storage.d-qZQI1JUe.d.ts → local-meta-storage.d-CuvN-KQ3.d.ts} +1 -1
  84. package/dist/packem_shared/{media-transformer.d-lQ_RUjb5.d.ts → media-transformer.d-DfU7VbFl.d.ts} +2 -2
  85. package/dist/packem_shared/memory-storage.d-DRbE0WMO.d.ts +101 -0
  86. package/dist/packem_shared/part-match-D_NwyoF3.js +1 -0
  87. package/dist/packem_shared/{path-D7rMc9nq-B718mbm6.js → path-D7rMc9nq-CPbxyMDy.js} +1 -1
  88. package/dist/packem_shared/{rest-base-C-a7pXUc.js → rest-base-xrnOBxS9.js} +1 -1
  89. package/dist/packem_shared/s3-base-storage-CqAyWHR6.js +1 -0
  90. package/dist/packem_shared/{s3-base-storage.d-CDIOMTpp.d.ts → s3-base-storage.d-BrHiKWFw.d.ts} +9 -2
  91. package/dist/packem_shared/storage-uhIhcN-O.js +1 -0
  92. package/dist/packem_shared/{storage.d-BoJgdi1n.d.ts → storage.d-X6TimMHY.d.ts} +23 -1
  93. package/dist/packem_shared/{tus-base.d-C28C_AY9.d.ts → tus-base.d-Ds7xYAJC.d.ts} +3 -3
  94. package/dist/packem_shared/{types.d-CPxJpoPH.d.ts → types.d-B72PbsLY.d.ts} +2 -2
  95. package/dist/packem_shared/{types.d-DCPQvHDI.d.ts → types.d-C4QumoP1.d.ts} +2 -2
  96. package/dist/packem_shared/{types.d-C0MDnUYc.d.ts → types.d-a1grKnaX.d.ts} +1 -1
  97. package/dist/storage/aws/index.d.ts +9 -3
  98. package/dist/storage/aws/index.js +1 -1
  99. package/dist/storage/aws-light/index.d.ts +2 -2
  100. package/dist/storage/aws-light/index.js +1 -1
  101. package/dist/storage/azure/index.d.ts +1 -1
  102. package/dist/storage/azure/index.js +1 -1
  103. package/dist/storage/box/index.d.ts +2 -2
  104. package/dist/storage/box/index.js +1 -1
  105. package/dist/storage/bun-s3/index.d.ts +2 -2
  106. package/dist/storage/bun-s3/index.js +1 -1
  107. package/dist/storage/bunny/index.d.ts +2 -2
  108. package/dist/storage/bunny/index.js +1 -1
  109. package/dist/storage/cloudinary/index.d.ts +2 -2
  110. package/dist/storage/cloudinary/index.js +1 -1
  111. package/dist/storage/dropbox/index.d.ts +2 -2
  112. package/dist/storage/dropbox/index.js +1 -1
  113. package/dist/storage/firebase/index.d.ts +2 -2
  114. package/dist/storage/firebase/index.js +1 -1
  115. package/dist/storage/ftp/index.d.ts +2 -2
  116. package/dist/storage/ftp/index.js +1 -1
  117. package/dist/storage/gcs/index.d.ts +1 -1
  118. package/dist/storage/gcs/index.js +1 -1
  119. package/dist/storage/google-drive/index.d.ts +2 -2
  120. package/dist/storage/google-drive/index.js +1 -1
  121. package/dist/storage/local/index.d.ts +3 -3
  122. package/dist/storage/local/index.js +1 -1
  123. package/dist/storage/memory/index.d.ts +6 -0
  124. package/dist/storage/memory/index.js +1 -0
  125. package/dist/storage/netlify-blob/index.d.ts +2 -2
  126. package/dist/storage/netlify-blob/index.js +1 -1
  127. package/dist/storage/onedrive/index.d.ts +4 -4
  128. package/dist/storage/onedrive/index.js +1 -1
  129. package/dist/storage/pocketbase/index.d.ts +2 -2
  130. package/dist/storage/pocketbase/index.js +1 -1
  131. package/dist/storage/sftp/index.d.ts +2 -2
  132. package/dist/storage/sftp/index.js +1 -1
  133. package/dist/storage/sharepoint/index.d.ts +3 -3
  134. package/dist/storage/sharepoint/index.js +1 -1
  135. package/dist/storage/supabase/index.d.ts +2 -2
  136. package/dist/storage/supabase/index.js +1 -1
  137. package/dist/storage/uploadthing/index.d.ts +2 -2
  138. package/dist/storage/uploadthing/index.js +1 -1
  139. package/dist/storage/vercel-blob/index.d.ts +2 -2
  140. package/dist/storage/vercel-blob/index.js +1 -1
  141. package/dist/transformer/audio-transformer.d.ts +2 -2
  142. package/dist/transformer/image-transformer.d.ts +2 -2
  143. package/dist/transformer/index.d.ts +3 -3
  144. package/dist/transformer/video-transformer.d.ts +2 -2
  145. package/package.json +6 -2
  146. package/dist/packem_shared/AzureStorage-Cmr0nPDq.js +0 -1
  147. package/dist/packem_shared/BoxStorage-DYzAYPIr.js +0 -1
  148. package/dist/packem_shared/BunS3Storage-BvaFeKeu.js +0 -1
  149. package/dist/packem_shared/BunnyStorage-DsQndiy5.js +0 -1
  150. package/dist/packem_shared/CloudinaryStorage-DiK0T7N7.js +0 -1
  151. package/dist/packem_shared/DiskStorage-RvZNMWe7.js +0 -1
  152. package/dist/packem_shared/DiskStorageWithChecksum-eGOV3leX.js +0 -1
  153. package/dist/packem_shared/DropboxStorage-Dfd78aJL.js +0 -1
  154. package/dist/packem_shared/Files-CtggibJ-.js +0 -1
  155. package/dist/packem_shared/FirebaseStorage-C-FwZOYA.js +0 -2
  156. package/dist/packem_shared/FtpStorage-DzaP89bG.js +0 -1
  157. package/dist/packem_shared/GCStorage-1vA3xkFO.js +0 -1
  158. package/dist/packem_shared/GoogleDriveStorage-D_RaKV_j.js +0 -1
  159. package/dist/packem_shared/NetlifyBlobStorage-C-IkXF0_.js +0 -1
  160. package/dist/packem_shared/OneDriveStorage-C7rqK2Wp.js +0 -1
  161. package/dist/packem_shared/PocketBaseStorage-Cdgr5w88.js +0 -1
  162. package/dist/packem_shared/S3Storage-Dn3l4WkO.js +0 -1
  163. package/dist/packem_shared/SftpStorage-CBW6MBLV.js +0 -1
  164. package/dist/packem_shared/SupabaseStorage-DMRhLPNo.js +0 -1
  165. package/dist/packem_shared/UploadThingStorage-BjF_gRMY.js +0 -1
  166. package/dist/packem_shared/VercelBlobStorage-Dx2jywjl.js +0 -1
  167. package/dist/packem_shared/disk-storage-Bmvawf-b.js +0 -1
  168. package/dist/packem_shared/index.d-DSZjPbvW.d.ts +0 -230
  169. package/dist/packem_shared/isRetryableError-BhizNeAz.js +0 -1
  170. package/dist/packem_shared/local-meta-storage-Bi0mK6gD.js +0 -1
  171. package/dist/packem_shared/part-match-B5fLLmFw.js +0 -1
  172. package/dist/packem_shared/s3-base-storage-Ek1HinGR.js +0 -1
  173. package/dist/packem_shared/storage-B-NDsI-o.js +0 -1
@@ -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-B-NDsI-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 x=Object.defineProperty,i=u((r,e)=>x(r,"name",{value:e,configurable:!0}),"n");const B=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"),N=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 N(r,"utf8",e);return{...JSON.parse(t)}},"getMetadata");const q=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&&q(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"),F=i(r=>c(r,"host")||c(r,"x-forwarded-host"),"extractHost"),P=i(r=>c(r,"x-forwarded-proto").toLowerCase(),"extractProto"),T=i(r=>{let{host:e,proto:t}=B(r);return e||=F(r),t||=P(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,N 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-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 +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-Cwd9uq_E.js";import{i as H}from"./storage-B-NDsI-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-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 +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-Cwd9uq_E.js";import{i as D}from"./storage-B-NDsI-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-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};
@@ -0,0 +1 @@
1
+ import{Readable as w}from"node:stream";import{S as p}from"./index-B4ETk0Lu.js";import{throwErrorCode as f,ERRORS as h}from"./ERRORS-CyOuSMLY.js";import{B as c}from"./storage-uhIhcN-O.js";import b from"./MemoryMetaStorage-DEzfBNgL.js";import l from"./File-BhfUgJjs.js";import{o as u}from"./get-file-status-DLS18Zvd.js";import{o as T}from"./has-content-Bx2p8Okx.js";import{u as A}from"./update-size-DANV7aa2.js";class F extends c{static name="memory";checksumTypes=["md5"];supportsRange=!0;meta;store;constructor(e={}){if(super(e),this.store=new Map,this.meta=e.metaStorage??new b({...e.metaStorageConfig,logger:this.logger}),e.initial)for(const[s,t]of Object.entries(e.initial)){c.assertSafeId(s);const a=Buffer.from(t),r=new Date().toISOString(),n=p(a);this.store.set(s,{bytes:a,contentType:"application/octet-stream",createdAt:r,eTag:n,metadata:{},modifiedAt:r});const i=new l({contentType:"application/octet-stream",id:s,metadata:{name:s,size:a.length},originalName:s,size:a.length});i.name=s,i.bytesWritten=a.length,i.ETag=n,i.createdAt=r,i.modifiedAt=r,i.status=u(i),this.meta.save(s,i).catch(()=>{})}}get raw(){return this.store}async create(e,s){return this.instrumentOperation("create",async()=>{const t=new l(e);return t.name=this.namingFunction(t),c.assertSafeId(t.name),await this.validate(t),t.bytesWritten=0,t.status=u(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,s){return this.instrumentOperation("write",async()=>{const t=await this.getMeta(e.id);if(!T(e))return t;const{body:a,start:r=0}=e,n=[];for await(const o of a)Buffer.isBuffer(o)?n.push(o):typeof o=="string"?n.push(Buffer.from(o)):ArrayBuffer.isView(o)?n.push(Buffer.from(o.buffer,o.byteOffset,o.byteLength)):n.push(Buffer.from(o));const i=Buffer.concat(n),m=this.store.get(t.name)?.bytes;let d;r===0||!m?d=i:d=Buffer.concat([m.subarray(0,r),i]);const y=new Date().toISOString(),g={bytes:d,contentType:t.contentType,createdAt:this.store.get(t.name)?.createdAt??y,eTag:p(d),metadata:{...t.metadata},modifiedAt:y};return this.store.set(t.name,g),t.bytesWritten=d.length,t.ETag=g.eTag,t.modifiedAt=g.modifiedAt,A(t,d.length),t.status=u(t),await this.saveMeta(t),t.status==="completed"&&await this.onComplete(t,{}),t})}async get({id:e},s){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);if(i>m||i>=a.bytes.length)return f(h.BAD_REQUEST,`Invalid range ${i}-${n.end??""}`);r=a.bytes.subarray(i,m+1)}return{content:r,contentType:a.contentType,ETag:a.eTag,expiredAt:t.expiredAt,id:e,metadata:{...a.metadata},modifiedAt:a.modifiedAt,name:t.name,originalName:t.originalName,size:r.length}})}async getStream({id:e},s){return this.instrumentOperation("getStream",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);r=a.bytes.subarray(i,m+1)}return{headers:{"Content-Length":String(r.length),"Content-Type":a.contentType,ETag:a.eTag,"Last-Modified":a.modifiedAt},size:r.length,stream:w.from(r)}})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const s=await this.meta.get(e);return this.store.has(s.name)}catch{return!1}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{const s=await this.getMeta(e);this.store.delete(s.name),await this.deleteMeta(e);const t={...s,status:"deleted"};return await this.onDelete(t),t})}async copy(e,s){return this.instrumentOperation("copy",async()=>{c.assertSafeId(e),c.assertSafeId(s);const t=await this.getMeta(e),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);const r=new Date().toISOString();this.store.set(s,{...a,bytes:Buffer.from(a.bytes),metadata:{...a.metadata},modifiedAt:r});const n={...t,ETag:a.eTag,id:s,name:s,modifiedAt:r};return await this.saveMeta(n),n})}async move(e,s){return this.instrumentOperation("move",async()=>{if(e===s)return this.getMeta(e);const t=await this.copy(e,s);return await this.delete({id:e}),t})}async list(){return this.instrumentOperation("list",async()=>{const e=[];for(const[s,t]of this.store)e.push({contentType:t.contentType,createdAt:t.createdAt,ETag:t.eTag,id:s,metadata:{...t.metadata},modifiedAt:t.modifiedAt,name:s,size:t.bytes.length});return e})}async getReadUrl(e){return c.assertSafeId(e),`memory://${e}`}async getUploadUrl(e){return c.assertSafeId(e),`memory://${e}`}}export{F as default};
@@ -1 +1 @@
1
- import"node:stream";import"node:timers";import"node:util";import{B as u,d as F,a as g}from"./storage-B-NDsI-o.js";import"./path-D7rMc9nq-B718mbm6.js";import"type-is";import"./NoOpMetrics-Dky06sf1.js";import"./cache-qV_5Umeq.js";import"./ERRORS-CyOuSMLY.js";import"./isRetryableError-BhizNeAz.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-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};
@@ -0,0 +1 @@
1
+ var ut=Object.defineProperty;var h=(e,t)=>ut(e,"name",{value:t,configurable:!0});import{createReadStream as mt,createWriteStream as dt}from"node:fs";import{truncate as ht,stat as B,copyFile as U}from"node:fs/promises";import{Transform as q,PassThrough as yt,pipeline as ft}from"node:stream";import{f as C,l as gt,w as K,V as b,P as v,L as P,_ as pt,B as wt,X as bt,a as vt,i as Et,v as $t,b as St,y as V}from"./local-meta-storage-Dr891Iy7.js";import{createRequire as M}from"node:module";import{O as Ot,M as Tt}from"./path-D7rMc9nq-CPbxyMDy.js";import{S as Ft}from"./index-B4ETk0Lu.js";import{d as kt}from"./detect-file-type-5JhzC9RU.js";import{throwErrorCode as w,ERRORS as y,isUploadError as Nt}from"./ERRORS-CyOuSMLY.js";import{createHash as Pt}from"node:crypto";import{B as Dt,a as _t,t as Mt}from"./storage-uhIhcN-O.js";import It from"./File-BhfUgJjs.js";import{o as X}from"./get-file-status-DLS18Zvd.js";import{u as Rt}from"./update-size-DANV7aa2.js";import{r as xt}from"./part-match-D_NwyoF3.js";import{o as Lt}from"./has-content-Bx2p8Okx.js";var jt=Object.defineProperty,At=h((e,t)=>jt(e,"name",{value:t,configurable:!0}),"i$4"),Ct=Object.defineProperty,Y=At((e,t)=>Ct(e,"name",{value:t,configurable:!0}),"t");const zt=M(import.meta.url),F=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Wt=Y(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 zt(e)},"__cjs_getBuiltinModule"),{lstat:Bt,writeFile:Ut}=Wt("node:fs/promises");var Vt=Object.defineProperty,Xt=Y((e,t)=>Vt(e,"name",{value:t,configurable:!0}),"o");const j=Xt(async e=>{C(e);try{const t=await Bt(e);if(!t.isFile())throw new Error(`Ensure path exists, expected 'file', got '${String(gt(t))}'`)}catch(t){if(t.code==="ENOENT"){await K(b(v(e))),await Ut(e,new Uint8Array);return}throw t}},"ensureFile");var Qt=Object.defineProperty,G=h((e,t)=>Qt(e,"name",{value:t,configurable:!0}),"t$1"),Ht=Object.defineProperty,J=G((e,t)=>Ht(e,"name",{value:t,configurable:!0}),"t"),qt=Object.defineProperty,Kt=J((e,t)=>qt(e,"name",{value:t,configurable:!0}),"t");let Q=class extends Error{static{h(this,"l")}static{G(this,"c")}static{J(this,"i")}static{Kt(this,"WalkError")}root;constructor(t,r){super(`${t instanceof Error?t.message:String(t)} for path "${r}"`),this.cause=t,this.root=r}get name(){return"WalkError"}set name(t){throw new Error("Cannot overwrite name of WalkError")}};var Yt=Object.defineProperty,Gt=h((e,t)=>Yt(e,"name",{value:t,configurable:!0}),"l$1"),Jt=Object.defineProperty,Z=Gt((e,t)=>Jt(e,"name",{value:t,configurable:!0}),"t"),Zt=Object.defineProperty,te=Z((e,t)=>Zt(e,"name",{value:t,configurable:!0}),"g");const H=te(e=>{const t=e.replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,String.raw`\.`).replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");return new RegExp(`^${t}$`)},"globToRegExp");var ee=Object.defineProperty,re=Z((e,t)=>ee(e,"name",{value:t,configurable:!0}),"t");const _=re((e,t,r,i)=>{if(Array.isArray(t)&&t.length>0&&!t.some(a=>e.endsWith(a)))return!1;const n=e.includes("\\")?e.replaceAll("\\","/"):e;return r&&!r.some(a=>a.test(n))?!1:!i?.some(a=>a.test(n))},"walkInclude");var ie=Object.defineProperty,tt=h((e,t)=>ie(e,"name",{value:t,configurable:!0}),"f$1"),ae=Object.defineProperty,z=tt((e,t)=>ae(e,"name",{value:t,configurable:!0}),"y");const se=M(import.meta.url),k=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ne=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 se(e)},"__cjs_getBuiltinModule"),{readdir:oe,realpath:ce,stat:le}=ne("node:fs/promises");var ue=Object.defineProperty,p=z((e,t)=>ue(e,"name",{value:t,configurable:!0}),"r");const me=p(async e=>{const t=wt(e),r=bt(t),i=await le(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:n=!0,includeSymlinks:a=!0,match:s,maxDepth:l=Number.POSITIVE_INFINITY,skip:m}={}){if(C(e),l<0)return;const u=s?s.map(c=>typeof c=="string"?H(c):c):void 0,d=m?m.map(c=>typeof c=="string"?H(c):c):void 0;if(e=P(v(e)),i&&_(e,t,u,d)&&(yield await me(e)),!(l<1||!_(e,void 0,void 0,d)))try{const c=await oe(e,{withFileTypes:!0});for(const o of c){let g=pt(e,o.name);if(o.isSymbolicLink())if(r)g=await ce(g);else if(a&&_(g,t,u,d)){yield{isDirectory:p(()=>o.isDirectory(),"isDirectory"),isFile:p(()=>o.isFile(),"isFile"),isSymbolicLink:p(()=>o.isSymbolicLink(),"isSymbolicLink"),name:o.name,path:g};continue}else continue;o.isDirectory()?yield*D(g,{extensions:t,followSymlinks:r,includeDirs:i,includeFiles:n,includeSymlinks:a,match:u,maxDepth:l-1,skip:d}):o.isFile()&&n&&_(g,t,u,d)&&(yield{isDirectory:p(()=>o.isDirectory(),"isDirectory"),isFile:p(()=>o.isFile(),"isFile"),isSymbolicLink:p(()=>o.isSymbolicLink(),"isSymbolicLink"),name:o.name,path:g})}}catch(c){throw c instanceof Q?c:new Q(c,e)}}h(D,"p$2");tt(D,"D");z(D,"g");p(D,"walk");var de=Object.defineProperty,et=h((e,t)=>de(e,"name",{value:t,configurable:!0}),"t"),he=Object.defineProperty,W=et((e,t)=>he(e,"name",{value:t,configurable:!0}),"t");const ye=M(import.meta.url),N=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,fe=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 ye(e)},"__cjs_getBuiltinModule"),{accessSync:ge}=fe("node:fs");var pe=Object.defineProperty,we=W((e,t)=>pe(e,"name",{value:t,configurable:!0}),"o");function I(e,t=vt){C(e),e=v(e);try{return ge(e,t),!0}catch{return!1}}h(I,"i$1");et(I,"d");W(I,"m");we(I,"isAccessibleSync");var be=Object.defineProperty,rt=h((e,t)=>be(e,"name",{value:t,configurable:!0}),"v"),ve=Object.defineProperty,T=rt((e,t)=>ve(e,"name",{value:t,configurable:!0}),"i");const Ee=M(import.meta.url),S=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,it=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 Ee(e)},"__cjs_getBuiltinModule"),{cwd:R}=S,{mkdir:$e,rename:Se,copyFile:Oe,unlink:Te}=it("node:fs/promises"),{mkdirSync:Fe,renameSync:ke,copyFileSync:Ne,unlinkSync:Pe}=it("node:fs");var De=Object.defineProperty,at=T((e,t)=>De(e,"name",{value:t,configurable:!0}),"o");class _e extends Error{static{h(this,"V")}static{rt(this,"O")}static{T(this,"a")}static{at(this,"SameDirectoryError")}constructor(t,r){super(`Source directory "${b(t)}" does not match destination directory "${b(r)}"`),this.name="SameDirectoryError"}}const st=at((e,t)=>{if(!e||!t)throw new Error("Source and destination paths must not be empty");if(b(e)!==b(t))throw new _e(e,t)},"validateSameDirectory");var Me=Object.defineProperty,Ie=T((e,t)=>Me(e,"name",{value:t,configurable:!0}),"m$1");const nt=Ie(async(e,t,{cwd:r,directoryMode:i,overwrite:n,validateDirectory:a})=>{if(r&&(e=P(r,e),t=P(r,t)),a&&st(e,t),!n&&await Et(t))throw new Error(`The destination file exists: ${t}`);await $e(b(t),{mode:i,recursive:!0});try{await Se(e,t)}catch(s){if(s.code==="EXDEV")await Oe(e,t),await Te(e);else throw s}},"internalMoveFile");var Re=Object.defineProperty,xe=T((e,t)=>Re(e,"name",{value:t,configurable:!0}),"m");const ot=xe((e,t,{cwd:r,directoryMode:i,overwrite:n,validateDirectory:a})=>{if(r&&(e=P(r,e),t=P(r,t)),a&&st(e,t),!n&&I(t))throw new Error(`The destination file exists: ${t}`);Fe(b(t),{mode:i,recursive:!0});try{ke(e,t)}catch(s){if(s.code==="EXDEV")Ne(e,t),Pe(e);else throw s}},"internalMoveFileSync");var Le=Object.defineProperty,x=T((e,t)=>Le(e,"name",{value:t,configurable:!0}),"i");const je=x(async(e,t,r={})=>{const i={overwrite:!0,validateDirectory:!1,...r,cwd:r.cwd?v(r.cwd):R()};await nt(e,t,i)},"move");x((e,t,r)=>{const i={overwrite:!0,validateDirectory:!1,...r};i.cwd=i.cwd?v(i.cwd):R(),ot(e,t,i)},"moveSync");x(async(e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?v(i.cwd):R(),await nt(e,t,i)},"rename");x((e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?v(i.cwd):R(),ot(e,t,i)},"renameSync");var Ae=Object.defineProperty,ct=h((e,t)=>Ae(e,"name",{value:t,configurable:!0}),"r");class Ce extends q{static{h(this,"StreamChecksum")}constructor(t,r,i="base64"){super(),this.checksum=t,this.algorithm=r,this.encoding=i,this.hash=Pt(r)}checksum;algorithm;encoding;static{ct(this,"StreamChecksum")}length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(t,r,i){this.push(t),this.hash.update(t),this.length+=t.length,i()}_flush(t){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?t(new Error("Checksum mismatch")):t()}}const ze=ct((e,t,r="base64")=>t?new Ce(e,t,r):new yt,"streamChecksum");var We=Object.defineProperty,Be=h((e,t)=>We(e,"name",{value:t,configurable:!0}),"o");class Ue extends q{static{h(this,"m")}constructor(t=Number.POSITIVE_INFINITY){super(),this.limit=t}limit;static{Be(this,"StreamLength")}length=0;_transform(t,r,i){const n=this.length+t.length;this.limit>=n?(this.push(t),this.length=n,i()):i(new Error("Stream length limit exceeded"))}}var Ve=Object.defineProperty,A=h((e,t)=>Ve(e,"name",{value:t,configurable:!0}),"F");class O extends Dt{static name="disk";checksumTypes=["md5","sha1"];supportsRange=!0;get raw(){return{directory:this.directory}}directory;meta;constructor(t){const r={...t,fileNameValidation:t.fileNameValidation??_t};if(super(r),this.directory=r.directory,r.metaStorage)this.meta=r.metaStorage;else{const i={...r,...r.metaStorageConfig,logger:this.logger};this.meta=new $t(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"?Mt(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 It(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 n=this.getFilePath(i.name);try{await j(n),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=X(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&&Rt(r,t.size),!xt(t,r))return w(y.FILE_CONFLICT);const i=this.getFilePath(r.name),n=await this.lock(i);try{const a=t.start||0;if(await j(i),r.bytesWritten===0&&(r.bytesWritten=a),Lt(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:o}=await kt(t.body);c?.mime&&(r.contentType=c.mime),t.body=o}catch{}const s=t.signal,l={...r,...t,body:t.body};s&&(l.signal=s);const[m,u]=await this.lazyWrite(l);if(u)return await ht(i,r.bytesWritten),w(u);const d=a+(t.contentLength||0);r.bytesWritten=Math.max(r.bytesWritten||0,d),r.bytesWritten=Math.max(r.bytesWritten||0,m),r.status=X(r),await this.saveMeta(r)}else await j(i),r.bytesWritten=0;return r}catch(a){if(Nt(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,n)}})}async get({id:t},r){return this.instrumentOperation("get",async()=>{const i=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:n,contentType:a,expiredAt:s,metadata:l,modifiedAt:m,name:u,originalName:d,size:c}=i;let o;try{o=await St(this.getFilePath(u),{buffer:!0})}catch(f){const $=f;if($.code==="ENOENT"||$.code==="EPERM"){const L=this.normalizeError(f instanceof Error?f:new Error($.message||String(f)));return await this.onError(L),w(y.FILE_NOT_FOUND,(typeof L.message=="string"?L.message:String(f))||String(f))}const lt=this.normalizeError(f instanceof Error?f:new Error(String(f)));throw await this.onError(lt),f}const g=Ft(o),E=r?.range;if(E){const f=Math.max(0,E.start),$=E.end===void 0?o.length-1:Math.min(o.length-1,E.end);if(f>$||f>=o.length)return w(y.BAD_REQUEST,`Invalid range ${f}-${E.end??""}`);o=o.subarray(f,$+1)}return{content:o,contentType:a,ETag:g,expiredAt:s,id:t,metadata:l,modifiedAt:m,name:u,originalName:d,size:E?o.length:c||n}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{const r=await this.getMeta(t),i=this.getFilePath(r.name);return await B(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:n,expiredAt:a,modifiedAt:s,name:l,size:m}=r,u=mt(this.getFilePath(l));return{headers:{"Content-Length":String(m||i),"Content-Type":n,...a&&{"X-Upload-Expires":a.toString()},...s&&{"Last-Modified":s.toString()}},size:m||i,stream:u}}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 U(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),n=this.getFilePath(i.name),a=this.getFilePath(r);try{await je(n,a)}catch(s){if(s?.code==="EXDEV")await U(n,a),await V(n);else{const l=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(l),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,n=A(s=>s.replaceAll("\\","/"),"toPosix"),a=n(i);for await(const s of D(i,t)){const{suffix:l}=this.meta,{path:m}=s;if(!m.includes(l)){const{birthtime:u,ctime:d,mtime:c}=await B(m),o=n(m),g=o.startsWith(a)?o.slice(a.length):o;r.push({createdAt:u||d,id:g,modifiedAt:c})}}return r})}getFilePath(t){return O.assertSafeId(t),Ot(t)&&w(y.INVALID_FILE_NAME,`Invalid file id: "${t}"`),Tt(this.directory,t)}lazyWrite(t){return new Promise((r,i)=>{const n=dt(this.getFilePath(t.name),{flags:"r+",start:t.start}),a=new Ue(t.contentLength||t.size-t.start),s=ze(t.checksum,t.checksumAlgorithm),l=!t.checksum,{signal:m}=t,u=A(()=>{n.close(),a.destroy(),s.destroy()},"cleanupStreams"),d=A(c=>{u(),r([Number.NaN,c])},"failWithCode");if(a.on("error",()=>{d(y.FILE_CONFLICT)}),s.on("error",()=>{d(y.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{d(l?void 0:y.REQUEST_ABORTED)}),t.body.on("error",c=>{u(),i(c)}),m?.aborted){d(l?void 0:y.REQUEST_ABORTED);return}m&&m.addEventListener("abort",()=>{u(),n.destroy(),a.destroy(),s.destroy(),t.body.destroy(),r([Number.NaN,l?void 0:y.REQUEST_ABORTED])}),ft(t.body,a,s,n,c=>{if(c){if(u(),m?.aborted){r([Number.NaN,l?void 0:y.REQUEST_ABORTED]);return}r([Number.NaN,y.FILE_ERROR]);return}r([t.start+n.bytesWritten])})})}async accessCheck(){await K(this.directory)}}export{Ue as m,O as p,ze as s,j 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, a as FileReturn, E as ERRORS, B as BaseStorage, h as DiskStorageWithChecksumOptions } from "./storage.d-BoJgdi1n.js";
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";
2
2
  import { Readable } from 'node:stream';
3
3
  /**
4
4
  * Local disk-based storage implementation.
@@ -21,6 +21,7 @@ import { Readable } from 'node:stream';
21
21
  declare class DiskStorage<TFile extends File = File> extends BaseStorage<TFile> {
22
22
  static override readonly name: string;
23
23
  override checksumTypes: string[];
24
+ override readonly supportsRange: boolean;
24
25
  override get raw(): {
25
26
  directory: string;
26
27
  };
@@ -70,7 +71,12 @@ declare class DiskStorage<TFile extends File = File> extends BaseStorage<TFile>
70
71
  */
71
72
  get({
72
73
  id
73
- }: FileQuery): Promise<FileReturn>;
74
+ }: FileQuery, options?: OperationOptions & {
75
+ range?: {
76
+ end?: number;
77
+ start: number;
78
+ };
79
+ }): Promise<FileReturn>;
74
80
  /**
75
81
  * Checks if a file exists by verifying both metadata and the actual filesystem file.
76
82
  * Returns true only if both the metadata and the file exist.
@@ -1,4 +1,4 @@
1
- import { F as Files } from "./index.d-DSZjPbvW.js";
1
+ import { F as Files } from "./index.d-CYdFIB-w.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.30";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.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};
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var r=(e,t)=>a(e,"name",{value:t,configurable:!0});var c=Object.defineProperty,o=r((e,t)=>c(e,"name",{value:t,configurable:!0}),"t");const n=o(e=>e.bytesWritten===e.size?"completed":e.createdAt?"part":"created","getFileStatus");export{n as o};