@visulima/storage 1.0.9 → 1.0.10

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 (143) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/adapter/nuxt/module.d.ts +8 -8
  3. package/dist/ai/ai-sdk/index.d.ts +51 -59
  4. package/dist/ai/claude/index.d.ts +104 -119
  5. package/dist/ai/openai/index.d.ts +86 -99
  6. package/dist/ai/tanstack/index.d.ts +53 -61
  7. package/dist/handler/http/fetch/index.d.ts +201 -201
  8. package/dist/handler/http/hono/index.d.ts +59 -59
  9. package/dist/handler/http/nextjs/index.d.ts +54 -54
  10. package/dist/handler/http/node/index.d.ts +233 -246
  11. package/dist/handler/http/solid-start/index.d.ts +54 -54
  12. package/dist/index.d.ts +70 -70
  13. package/dist/index.js +1 -1
  14. package/dist/packem_shared/{AwsLightStorage-BK-WPL0h.js → AwsLightStorage-EsqkAtU5.js} +1 -1
  15. package/dist/packem_shared/{AzureStorage-1UvDIQZd.js → AzureStorage-DL-U7qFG.js} +1 -1
  16. package/dist/packem_shared/BoxMetaStorage-CHWrhgg2.js +1 -0
  17. package/dist/packem_shared/{BoxStorage-DbGqBLux.js → BoxStorage-B8_oCz27.js} +1 -1
  18. package/dist/packem_shared/BunS3MetaStorage-CHWrhgg2.js +1 -0
  19. package/dist/packem_shared/{BunS3Storage-DNvimm9e.js → BunS3Storage-_PVXu_na.js} +1 -1
  20. package/dist/packem_shared/BunnyMetaStorage-CHWrhgg2.js +1 -0
  21. package/dist/packem_shared/{BunnyStorage-C7d0opLL.js → BunnyStorage-BsoWjScH.js} +1 -1
  22. package/dist/packem_shared/CloudinaryMetaStorage-BI9YXcwU.js +1 -0
  23. package/dist/packem_shared/{CloudinaryStorage-Dc3XA2lP.js → CloudinaryStorage-BNwiLF9V.js} +1 -1
  24. package/dist/packem_shared/{DiskStorage-CI07TVNu.js → DiskStorage-D-NtQDms.js} +1 -1
  25. package/dist/packem_shared/{DiskStorageWithChecksum-vFCubS6K.js → DiskStorageWithChecksum-UnCtyEvs.js} +1 -1
  26. package/dist/packem_shared/DropboxMetaStorage-CHWrhgg2.js +1 -0
  27. package/dist/packem_shared/{DropboxStorage-CY9Ggu3m.js → DropboxStorage-BS9kj0nH.js} +1 -1
  28. package/dist/packem_shared/FirebaseMetaStorage-BI9YXcwU.js +1 -0
  29. package/dist/packem_shared/{FirebaseStorage-D6O9CJXN.js → FirebaseStorage-DNquii2p.js} +1 -1
  30. package/dist/packem_shared/FtpMetaStorage-CHWrhgg2.js +1 -0
  31. package/dist/packem_shared/{FtpStorage-DbEjbq8z.js → FtpStorage-Bd004--s.js} +1 -1
  32. package/dist/packem_shared/{GCSMetaStorage-DT8K6zdm.js → GCSMetaStorage-Bf4qDFB1.js} +1 -1
  33. package/dist/packem_shared/{GCStorage-6BHkFlEs.js → GCStorage-ChqEpgqR.js} +1 -1
  34. package/dist/packem_shared/GoogleDriveMetaStorage-xlHfKwmR.js +1 -0
  35. package/dist/packem_shared/{GoogleDriveStorage-Bklsz7Bh.js → GoogleDriveStorage-v1glykjd.js} +1 -1
  36. package/dist/packem_shared/{LocalMetaStorage-BhicZnNl.js → LocalMetaStorage-YWPBYEe7.js} +1 -1
  37. package/dist/packem_shared/NetlifyBlobMetaStorage-BI9YXcwU.js +1 -0
  38. package/dist/packem_shared/{NetlifyBlobStorage-CkpCCoN1.js → NetlifyBlobStorage-BPyEWSnx.js} +1 -1
  39. package/dist/packem_shared/OneDriveMetaStorage-xlHfKwmR.js +1 -0
  40. package/dist/packem_shared/{OneDriveStorage-CP6MvGAa.js → OneDriveStorage-BJ3Kzxc5.js} +1 -1
  41. package/dist/packem_shared/PocketBaseMetaStorage-DnrxOQhO.js +1 -0
  42. package/dist/packem_shared/{PocketBaseStorage-2qhbI2PW.js → PocketBaseStorage-DqKHbbvn.js} +1 -1
  43. package/dist/packem_shared/{S3Storage-YGeNk3Tt.js → S3Storage-BiI2k6d1.js} +1 -1
  44. package/dist/packem_shared/SftpMetaStorage-CHWrhgg2.js +1 -0
  45. package/dist/packem_shared/{SftpStorage-2Hz396Xr.js → SftpStorage-w8XdtZtw.js} +1 -1
  46. package/dist/packem_shared/SharePointMetaStorage-CHWrhgg2.js +1 -0
  47. package/dist/packem_shared/{SharePointStorage-CrX2Pk6C.js → SharePointStorage-DpDpI7Ln.js} +1 -1
  48. package/dist/packem_shared/SupabaseMetaStorage-xlHfKwmR.js +1 -0
  49. package/dist/packem_shared/{SupabaseStorage-Dc_DBX29.js → SupabaseStorage-B_ugUCs7.js} +1 -1
  50. package/dist/packem_shared/UploadThingMetaStorage-BI9YXcwU.js +1 -0
  51. package/dist/packem_shared/{UploadThingStorage-BChykYSe.js → UploadThingStorage-_H45IVqX.js} +1 -1
  52. package/dist/packem_shared/VercelBlobMetaStorage-CHWrhgg2.js +1 -0
  53. package/dist/packem_shared/{VercelBlobStorage-CsRyPfw3.js → VercelBlobStorage-U1YMKeHs.js} +1 -1
  54. package/dist/packem_shared/{approval.d-CMAYH9GF.d.ts → approval.d-C-d-t94D.d.ts} +6 -6
  55. package/dist/packem_shared/disk-storage-BwPk2IRa.js +1 -0
  56. package/dist/packem_shared/disk-storage-with-checksum.d-CQucFacO.d.ts +146 -0
  57. package/dist/packem_shared/{executors.d-BZP2rWo3.d.ts → executors.d-DeDH3Ilt.d.ts} +2 -2
  58. package/dist/packem_shared/files.d-D8H_ge9Y.d.ts +655 -0
  59. package/dist/packem_shared/{gcs-meta-storage-B7BnctnV.js → gcs-meta-storage-DQGu_cHq.js} +1 -1
  60. package/dist/packem_shared/local-meta-storage-DJDcuxf1.js +11 -0
  61. package/dist/packem_shared/{local-meta-storage.d-D9PBfkn6.d.ts → local-meta-storage.d-DuTEzyii.d.ts} +7 -7
  62. package/dist/packem_shared/media-transformer.d-CvMFjINm.d.ts +331 -0
  63. package/dist/packem_shared/{memory-storage.d-4EU1cMt1.d.ts → memory-storage.d-BRdTiY8y.d.ts} +32 -40
  64. package/dist/packem_shared/{s3-base-storage-BoTyhuzO.js → s3-base-storage-CMUui93V.js} +1 -1
  65. package/dist/packem_shared/{s3-base-storage.d-BQgP5B-t.d.ts → s3-base-storage.d-Cg7m4FuH.d.ts} +64 -70
  66. package/dist/packem_shared/storage.d-DIav_lF1.d.ts +1163 -0
  67. package/dist/packem_shared/tus-base.d-BiEg5t4t.d.ts +102 -0
  68. package/dist/packem_shared/{types.d-CrUWY4On.d.ts → types.d-CAAzKiI6.d.ts} +134 -134
  69. package/dist/packem_shared/types.d-DgHhkCAl.d.ts +104 -0
  70. package/dist/packem_shared/{types.d-CggTCgXr.d.ts → types.d-jAs_Rp_v.d.ts} +3 -3
  71. package/dist/storage/aws/clients/index.d.ts +388 -388
  72. package/dist/storage/aws/index.d.ts +109 -113
  73. package/dist/storage/aws/index.js +1 -1
  74. package/dist/storage/aws-light/index.d.ts +63 -67
  75. package/dist/storage/aws-light/index.js +1 -1
  76. package/dist/storage/azure/index.d.ts +133 -139
  77. package/dist/storage/azure/index.js +1 -1
  78. package/dist/storage/box/index.d.ts +88 -92
  79. package/dist/storage/box/index.js +1 -1
  80. package/dist/storage/bun-s3/index.d.ts +70 -76
  81. package/dist/storage/bun-s3/index.js +1 -1
  82. package/dist/storage/bunny/index.d.ts +51 -55
  83. package/dist/storage/bunny/index.js +1 -1
  84. package/dist/storage/cloudinary/index.d.ts +53 -59
  85. package/dist/storage/cloudinary/index.js +1 -1
  86. package/dist/storage/dropbox/index.d.ts +58 -62
  87. package/dist/storage/dropbox/index.js +1 -1
  88. package/dist/storage/firebase/index.d.ts +73 -79
  89. package/dist/storage/firebase/index.js +1 -1
  90. package/dist/storage/ftp/index.d.ts +37 -43
  91. package/dist/storage/ftp/index.js +1 -1
  92. package/dist/storage/gcs/index.d.ts +89 -95
  93. package/dist/storage/gcs/index.js +1 -1
  94. package/dist/storage/google-drive/index.d.ts +68 -72
  95. package/dist/storage/google-drive/index.js +1 -1
  96. package/dist/storage/local/index.d.ts +3 -3
  97. package/dist/storage/local/index.js +1 -1
  98. package/dist/storage/memory/index.d.ts +2 -2
  99. package/dist/storage/netlify-blob/index.d.ts +85 -93
  100. package/dist/storage/netlify-blob/index.js +1 -1
  101. package/dist/storage/onedrive/index.d.ts +43 -53
  102. package/dist/storage/onedrive/index.js +1 -1
  103. package/dist/storage/pocketbase/index.d.ts +66 -72
  104. package/dist/storage/pocketbase/index.js +1 -1
  105. package/dist/storage/sftp/index.d.ts +39 -45
  106. package/dist/storage/sftp/index.js +1 -1
  107. package/dist/storage/sharepoint/index.d.ts +95 -95
  108. package/dist/storage/sharepoint/index.js +1 -1
  109. package/dist/storage/supabase/index.d.ts +49 -55
  110. package/dist/storage/supabase/index.js +1 -1
  111. package/dist/storage/uploadthing/index.d.ts +33 -37
  112. package/dist/storage/uploadthing/index.js +1 -1
  113. package/dist/storage/vercel-blob/index.d.ts +109 -115
  114. package/dist/storage/vercel-blob/index.js +1 -1
  115. package/dist/transformer/audio-transformer.d.ts +96 -96
  116. package/dist/transformer/image-transformer.d.ts +422 -422
  117. package/dist/transformer/index.d.ts +34 -34
  118. package/dist/transformer/video-transformer.d.ts +111 -111
  119. package/package.json +1 -1
  120. package/dist/packem_shared/BoxMetaStorage-BSn6Qfnf.js +0 -1
  121. package/dist/packem_shared/BunS3MetaStorage-BSn6Qfnf.js +0 -1
  122. package/dist/packem_shared/BunnyMetaStorage-BSn6Qfnf.js +0 -1
  123. package/dist/packem_shared/CloudinaryMetaStorage-DPVnmNe5.js +0 -1
  124. package/dist/packem_shared/DropboxMetaStorage-BSn6Qfnf.js +0 -1
  125. package/dist/packem_shared/FirebaseMetaStorage-DPVnmNe5.js +0 -1
  126. package/dist/packem_shared/FtpMetaStorage-BSn6Qfnf.js +0 -1
  127. package/dist/packem_shared/GoogleDriveMetaStorage-Cbwa1CHV.js +0 -1
  128. package/dist/packem_shared/NetlifyBlobMetaStorage-DPVnmNe5.js +0 -1
  129. package/dist/packem_shared/OneDriveMetaStorage-Cbwa1CHV.js +0 -1
  130. package/dist/packem_shared/PocketBaseMetaStorage-DOTLwVE7.js +0 -1
  131. package/dist/packem_shared/SftpMetaStorage-BSn6Qfnf.js +0 -1
  132. package/dist/packem_shared/SharePointMetaStorage-BSn6Qfnf.js +0 -1
  133. package/dist/packem_shared/SupabaseMetaStorage-Cbwa1CHV.js +0 -1
  134. package/dist/packem_shared/UploadThingMetaStorage-DPVnmNe5.js +0 -1
  135. package/dist/packem_shared/VercelBlobMetaStorage-BSn6Qfnf.js +0 -1
  136. package/dist/packem_shared/disk-storage-CsQcYW3s.js +0 -1
  137. package/dist/packem_shared/disk-storage-with-checksum.d-B-VGEsfl.d.ts +0 -156
  138. package/dist/packem_shared/files.d-CH0iLBNC.d.ts +0 -655
  139. package/dist/packem_shared/local-meta-storage-iuJnu90B.js +0 -11
  140. package/dist/packem_shared/media-transformer.d-Quf4ai47.d.ts +0 -331
  141. package/dist/packem_shared/storage.d-CEM1upWM.d.ts +0 -1176
  142. package/dist/packem_shared/tus-base.d-DLzKE54M.d.ts +0 -106
  143. package/dist/packem_shared/types.d-Bon9GVVe.d.ts +0 -104
@@ -1 +1 @@
1
- import{createReadStream as l,createWriteStream as y}from"node:fs";import{truncate as g}from"node:fs/promises";import{Transform as f,pipeline as w}from"node:stream";import{l as b,d as E}from"./local-meta-storage-iuJnu90B.js";import{d as F}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as c,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{F as C,n as T,s as W}from"./disk-storage-CsQcYW3s.js";import{LRUCache as N}from"lru-cache";import{createHash as S}from"node:crypto";import{t as R}from"./update-size-DuNuLyxj.js";import{i as x}from"./part-match-D-9dGX42.js";import{e as M}from"./has-content-50BsqrWw.js";import{t as _}from"./get-file-status-y3wTtDQs.js";class k extends f{constructor(t,e){super(),this.path=e,this.hashes=t,this.hash=this.hashes.get(e)||S(this.hashes.algorithm),this.hashCopy=this.hash.copy()}path;hash;hashCopy;hashes;reset(){this.hashes.set(this.path,this.hashCopy)}digest(t="hex"){return this.hash.copy().digest(t)}_transform(t,e,s){this.push(t),this.hash.update(t),s()}_flush(t){t()}}class I extends N{constructor(t="sha1",e){super({ttl:1e3,ttlAutopurge:!0,...e}),this.algorithm=t}algorithm;hex(t){return this.get(t)?.copy().digest("hex")||""}base64(t){return this.get(t)?.copy().digest("base64")||""}async init(t,e=0){return this.get(t)?.copy()||this.updateFromFs(t,e)}digester(t){return new k(this,t)}async updateFromFs(t,e=0,s){const r=await this.fromFs(t,e,s);return this.set(t,r),r}fromFs(t,e=0,s){return new Promise((r,i)=>{const a=this.digester(t);s!==void 0&&(a.hash=s),l(t,{start:e}).on("error",i).on("end",()=>{r(a.hash)}).pipe(a).resume()})}}class j extends C{hashes;constructor(t){super(t),this.hashes=new I(t?.checksum==="sha1"?"sha1":"md5")}async delete({id:t}){try{const e=await this.getMeta(t),s=this.getFilePath(e.name);this.hashes.delete(s),await b(s),await this.deleteMeta(t);const r={...e,status:"deleted"};return await this.onDelete(r),r}catch(e){this.logger?.error("[error]: Could not delete file: %O",e);const s=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(s)}return{id:t}}async write(t){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&&R(e,t.size),!x(t,e))return c(h.FILE_CONFLICT);const s=this.getFilePath(e.name);try{const r=t.start||0;if(await E(s),(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(e.bytesWritten=r),await this.hashes.init(s),M(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return c(h.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:o,stream:n}=await F(t.body);o?.mime&&(e.contentType=o.mime),t.body=n}catch{}const[i,a]=await this.lazyWrite({...t,...e});if(a)return await g(s,e.bytesWritten),c(a);typeof i!="number"&&await this.hashes.updateFromFs(s,e.bytesWritten),e.bytesWritten=i}return e.status=_(e),e.hash={algorithm:this.hashes.algorithm,value:this.hashes.hex(s)},e.status==="completed"&&this.hashes.delete(s),await this.saveMeta(e),e}catch(r){await this.hashes.updateFromFs(s,e.bytesWritten);const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));return await this.onError(i),c(h.FILE_ERROR,(typeof i.message=="string"?i.message:String(r))||String(r))}}lazyWrite(t){return new Promise((e,s)=>{const r=this.getFilePath(t.name),i=y(r,{flags:"r+",start:t.start}),a=new T(t.contentLength||Number(t.size)-t.start),o=W(t.checksum,t.checksumAlgorithm),n=this.hashes.digester(r),d=!t.checksum,u=m=>{n.reset(),i.close(),e([Number.NaN,m])};a.on("error",()=>{u(h.FILE_CONFLICT)}),o.on("error",()=>{u(h.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{u(d?void 0:h.REQUEST_ABORTED)}),w(t.body,a,o,n,i,m=>{if(m){n.reset(),s(m);return}e([t.start+i.bytesWritten])})})}}export{j as default};
1
+ import{createReadStream as l,createWriteStream as y}from"node:fs";import{truncate as g}from"node:fs/promises";import{Transform as f,pipeline as w}from"node:stream";import{u as b,h as E}from"./local-meta-storage-DJDcuxf1.js";import{d as F}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as c,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{F as C,n as T,s as W}from"./disk-storage-BwPk2IRa.js";import{LRUCache as N}from"lru-cache";import{createHash as S}from"node:crypto";import{t as R}from"./update-size-DuNuLyxj.js";import{i as x}from"./part-match-D-9dGX42.js";import{e as M}from"./has-content-50BsqrWw.js";import{t as _}from"./get-file-status-y3wTtDQs.js";class k extends f{constructor(t,e){super(),this.path=e,this.hashes=t,this.hash=this.hashes.get(e)||S(this.hashes.algorithm),this.hashCopy=this.hash.copy()}path;hash;hashCopy;hashes;reset(){this.hashes.set(this.path,this.hashCopy)}digest(t="hex"){return this.hash.copy().digest(t)}_transform(t,e,s){this.push(t),this.hash.update(t),s()}_flush(t){t()}}class I extends N{constructor(t="sha1",e){super({ttl:1e3,ttlAutopurge:!0,...e}),this.algorithm=t}algorithm;hex(t){return this.get(t)?.copy().digest("hex")||""}base64(t){return this.get(t)?.copy().digest("base64")||""}async init(t,e=0){return this.get(t)?.copy()||this.updateFromFs(t,e)}digester(t){return new k(this,t)}async updateFromFs(t,e=0,s){const r=await this.fromFs(t,e,s);return this.set(t,r),r}fromFs(t,e=0,s){return new Promise((r,i)=>{const a=this.digester(t);s!==void 0&&(a.hash=s),l(t,{start:e}).on("error",i).on("end",()=>{r(a.hash)}).pipe(a).resume()})}}class j extends C{hashes;constructor(t){super(t),this.hashes=new I(t?.checksum==="sha1"?"sha1":"md5")}async delete({id:t}){try{const e=await this.getMeta(t),s=this.getFilePath(e.name);this.hashes.delete(s),await b(s),await this.deleteMeta(t);const r={...e,status:"deleted"};return await this.onDelete(r),r}catch(e){this.logger?.error("[error]: Could not delete file: %O",e);const s=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(s)}return{id:t}}async write(t){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&&R(e,t.size),!x(t,e))return c(h.FILE_CONFLICT);const s=this.getFilePath(e.name);try{const r=t.start||0;if(await E(s),(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(e.bytesWritten=r),await this.hashes.init(s),M(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return c(h.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:o,stream:n}=await F(t.body);o?.mime&&(e.contentType=o.mime),t.body=n}catch{}const[i,a]=await this.lazyWrite({...t,...e});if(a)return await g(s,e.bytesWritten),c(a);typeof i!="number"&&await this.hashes.updateFromFs(s,e.bytesWritten),e.bytesWritten=i}return e.status=_(e),e.hash={algorithm:this.hashes.algorithm,value:this.hashes.hex(s)},e.status==="completed"&&this.hashes.delete(s),await this.saveMeta(e),e}catch(r){await this.hashes.updateFromFs(s,e.bytesWritten);const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));return await this.onError(i),c(h.FILE_ERROR,(typeof i.message=="string"?i.message:String(r))||String(r))}}lazyWrite(t){return new Promise((e,s)=>{const r=this.getFilePath(t.name),i=y(r,{flags:"r+",start:t.start}),a=new T(t.contentLength||Number(t.size)-t.start),o=W(t.checksum,t.checksumAlgorithm),n=this.hashes.digester(r),d=!t.checksum,u=m=>{n.reset(),i.close(),e([Number.NaN,m])};a.on("error",()=>{u(h.FILE_CONFLICT)}),o.on("error",()=>{u(h.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{u(d?void 0:h.REQUEST_ABORTED)}),w(t.body,a,o,n,i,m=>{if(m){n.reset(),s(m);return}e([t.start+i.bytesWritten])})})}}export{j as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{DropboxResponseError as _,DropboxAuth as u,Dropbox as d}from"dropbox";import{throwErrorCode as m,ERRORS as y}from"./ERRORS-BIBxE2oR.js";import{c as E}from"./oauth-refresh-EdGzlcOZ.js";import{B as v}from"./storage-0j5nCAUp.js";import l from"./DropboxFile-BFb7eOzy.js";import A from"./DropboxMetaStorage-BSn6Qfnf.js";import{t as g}from"./get-file-status-y3wTtDQs.js";import{t as D}from"./update-size-DuNuLyxj.js";import{i as S}from"./part-match-D-9dGX42.js";import{e as x}from"./has-content-50BsqrWw.js";const w=14400,B=150*1024*1024,p=8*1024*1024,k=(r,t)=>{r.auth.setAccessToken(t)},R=r=>r.auth.getAccessToken(),T=r=>{let t=0,n=r.length;for(;t<n&&r[t]==="/";)t+=1;for(;n>t&&r[n-1]==="/";)n-=1;return t===0&&n===r.length?r:r.slice(t,n)},H=async r=>{const t=[];for await(const n of r)t.push(Buffer.from(n));return Buffer.concat(t)},O=r=>r.includes("?dl=0")?r.replace("?dl=0","?dl=1"):r.includes("?dl=")?r:r+(r.includes("?")?"&dl=1":"?dl=1"),b=(r,t)=>(k(r,t),{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(t)}),U=(r,t)=>{const n=async()=>{const e=await t();return k(r,e),e};return{async ensureAccessToken(){await n()},getAccessToken:n}},P=(r,t)=>{const n=E({buildBody:()=>new URLSearchParams({client_id:t.appKey,grant_type:"refresh_token",refresh_token:t.refreshToken,...t.appSecret&&{client_secret:t.appSecret}}),onRefresh:e=>{k(r,e)},provider:"Dropbox",tokenUrl:"https://api.dropboxapi.com/oauth2/token"});return{async ensureAccessToken(){await n.getAccessToken()},getAccessToken:()=>n.getAccessToken()}},C=r=>{if(r.client){const i=r.client;return{authHandle:{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(R(i))},client:i}}const t=r.accessToken,n=r.refreshToken!==void 0||r.appKey!==void 0||r.appSecret!==void 0;if(t!==void 0&&n)throw new Error("Dropbox storage: pass exactly one of `accessToken` or `refreshToken` (with `appKey`).");if(t!==void 0){const i=new u({accessToken:typeof t=="string"?t:void 0}),s=new d({auth:i});return{authHandle:typeof t=="function"?U(s,t):b(s,t),client:s}}if(n){if(!r.refreshToken||!r.appKey)throw new Error("Dropbox storage: refresh-token auth requires both `refreshToken` and `appKey`.");const i=new u({}),s=new d({auth:i});return{authHandle:P(s,{appKey:r.appKey,...r.appSecret&&{appSecret:r.appSecret},refreshToken:r.refreshToken}),client:s}}const e=process.env.DROPBOX_ACCESS_TOKEN;if(e){const i=new u({accessToken:e}),s=new d({auth:i});return{authHandle:b(s,e),client:s}}const o=process.env.DROPBOX_REFRESH_TOKEN,a=process.env.DROPBOX_APP_KEY;if(o&&a){const i=process.env.DROPBOX_APP_SECRET,s=new u({}),h=new d({auth:s});return{authHandle:P(h,{appKey:a,...i&&{appSecret:i},refreshToken:o}),client:h}}throw new Error("Dropbox storage: missing auth. Pass `client`, `accessToken`, or `refreshToken` + `appKey`. Env fallbacks: DROPBOX_ACCESS_TOKEN, or DROPBOX_REFRESH_TOKEN + DROPBOX_APP_KEY (+ DROPBOX_APP_SECRET).")};class q extends v{static name="dropbox";checksumTypes=[];meta;authHandle;client;defaultUrlExpiresIn;publicByDefault;rootFolderPath;constructor(t){super(t),this.rootFolderPath=T(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w);const n=C(t);this.client=n.client,this.authHandle=n.authHandle,this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,n){return this.instrumentOperation("create",async()=>{const e=new l(t);e.name=this.namingFunction(e),e.path=this.keyToPath(e.name),await this.validate(e);try{const o=await this.getMeta(e.id);if(o.bytesWritten>=0)return o}catch{}return e.bytesWritten=0,e.status=g(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,n){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&&D(e,t.size),!S(t,e))throw new Error("File part does not match");const o=await this.lock(t.id);try{if(x(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await H(t.body),i=e.path??this.keyToPath(e.name||e.id);await this.authHandle.ensureAccessToken();const s=a.byteLength<=B?await this.uploadSimple(i,a,n):await this.uploadSession(i,a,n);e.bytesWritten=a.length,e.size=a.length,e.path=s.path_display??i,e.rev=s.rev,e.ETag=s.rev}return e.status=g(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,o)}})}async delete({id:t},n){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const o=e?.path??this.keyToPath(e?.name??t);await this.authHandle.ensureAccessToken();try{await this.runOperation(n,()=>this.client.filesDeleteV2({path:o}))}catch(a){if(!L(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new l({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,path:o,status:"deleted"})})}async get({id:t},n){return this.instrumentOperation("get",async()=>{let e,o=this.keyToPath(t);try{e=await this.checkIfExpired(await this.getMeta(t)),o=e.path??this.keyToPath(e.name??t)}catch{}await this.authHandle.ensureAccessToken();const a=(await this.runOperation(n,()=>this.client.filesDownload({path:o}))).result;let i;if(a.fileBinary instanceof Uint8Array)i=Buffer.from(a.fileBinary.buffer,a.fileBinary.byteOffset,a.fileBinary.byteLength);else if(a.fileBlob instanceof Blob)i=Buffer.from(await a.fileBlob.arrayBuffer());else throw new TypeError("Dropbox: unexpected download response shape — neither fileBinary nor fileBlob present");return{content:i,contentType:e?.contentType??"application/octet-stream",ETag:e?.ETag??a.rev,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.server_modified,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??i.length}})}async copy(t,n,e){return this.instrumentOperation("copy",async()=>{const o=this.keyToPath(t),a=this.keyToPath(n);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesCopyV2({from_path:o,to_path:a}));const i=new l({contentType:"application/octet-stream",metadata:{},originalName:n});return i.id=n,i.name=n,i.path=a,i})}async move(t,n,e){return this.instrumentOperation("move",async()=>{const o=this.keyToPath(t),a=this.keyToPath(n);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesMoveV2({from_path:o,to_path:a}));const i=new l({contentType:"application/octet-stream",metadata:{},originalName:n});i.id=n,i.name=n,i.path=a;try{await this.deleteMeta(t)}catch{}return i})}async list(t=1e3,n){return this.instrumentOperation("list",async()=>{await this.authHandle.ensureAccessToken();const e=await this.runOperation(n,()=>this.client.filesListFolder({limit:t,path:this.rootFolderPath?`/${this.rootFolderPath}`:"",recursive:!0})),{result:o}=e,a=[];for(const i of o.entries){if(i[".tag"]!=="file")continue;const s=i,h=s.path_display??s.path_lower??`/${s.name}`,f=this.pathToKey(h);if(!f)continue;const c=new l({contentType:"application/octet-stream",metadata:{},originalName:s.name});c.id=f,c.name=f,c.path=h,c.size=s.size,c.rev=s.rev,c.ETag=s.rev,c.modifiedAt=s.server_modified,a.push(c)}return a},{limit:t})}async getReadUrl(t,n){if(n?.responseContentDisposition!==void 0||n?.responseContentType!==void 0)return m(y.METHOD_NOT_ALLOWED,"Dropbox: `responseContentDisposition`/`responseContentType` are not supported — Dropbox temporary links have no Content-Disposition/Content-Type override.");const e=n?.expiresIn??this.defaultUrlExpiresIn;return e>w?m(y.METHOD_NOT_ALLOWED,`Dropbox: \`expiresIn\` of ${e}s exceeds the ${w}s (4h) maximum. Use \`publicByDefault: true\` for a permanent shared link.`):(await this.authHandle.ensureAccessToken(),this.publicByDefault?await this.createPublicSharedLink(t):(await this.client.filesGetTemporaryLink({path:this.keyToPath(t)})).result.link)}async getUploadUrl(t,n){return m(y.METHOD_NOT_ALLOWED,"Dropbox: presigned upload URLs use POST with a raw body, which doesn't fit the PUT-style upload-url contract. Use `write()` or `storage.raw.filesGetTemporaryUploadLink(...)` directly.")}keyToPath(t){const n=T(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),n&&e.push(n),e.length===0?"":`/${e.join("/")}`}pathToKey(t){const n=T(t);if(!this.rootFolderPath)return n;if(n===this.rootFolderPath)return"";const e=`${this.rootFolderPath}/`;return n.startsWith(e)?n.slice(e.length):n}async uploadSimple(t,n,e){return(await this.runOperation(e,()=>this.client.filesUpload({contents:n,mode:{".tag":"overwrite"},mute:!0,path:t}))).result}async uploadSession(t,n,e){const o=n.byteLength;let a=0;const i=(await this.runOperation(e,()=>this.client.filesUploadSessionStart({close:!1,contents:n.subarray(a,Math.min(a+p,o))}))).result.session_id;for(a=Math.min(a+p,o);o-a>p;){const h=n.subarray(a,a+p);await this.runOperation(e,()=>this.client.filesUploadSessionAppendV2({close:!1,contents:h,cursor:{offset:a,session_id:i}})),a+=p}const s=n.subarray(a,o);return(await this.runOperation(e,()=>this.client.filesUploadSessionFinish({commit:{mode:{".tag":"overwrite"},mute:!0,path:t},contents:s,cursor:{offset:a,session_id:i}}))).result}async createPublicSharedLink(t){try{const n=await this.client.sharingCreateSharedLinkWithSettings({path:this.keyToPath(t),settings:{requested_visibility:{".tag":"public"}}});return O(n.result.url)}catch(n){if(n instanceof _){const e=n.error?.shared_link_already_exists?.metadata?.url;if(typeof e=="string"&&e.length>0)return O(e)}throw n}}internalOnComplete=t=>this.deleteMeta(t.id)}const L=r=>{if(!(r instanceof _))return!1;if(r.status===404)return!0;const t=[],n=(e,o)=>{if(o>6||e===null||typeof e!="object")return;const a=e,i=a[".tag"];typeof i=="string"&&t.push(i);for(const s of Object.values(a))s&&typeof s=="object"&&n(s,o+1)};return n(r.error,0),t.includes("not_found")||t.includes("not_file")||t.includes("not_folder")};export{q as default};
1
+ import{DropboxResponseError as _,DropboxAuth as u,Dropbox as d}from"dropbox";import{throwErrorCode as m,ERRORS as y}from"./ERRORS-BIBxE2oR.js";import{c as E}from"./oauth-refresh-EdGzlcOZ.js";import{B as v}from"./storage-0j5nCAUp.js";import l from"./DropboxFile-BFb7eOzy.js";import A from"./DropboxMetaStorage-CHWrhgg2.js";import{t as g}from"./get-file-status-y3wTtDQs.js";import{t as D}from"./update-size-DuNuLyxj.js";import{i as S}from"./part-match-D-9dGX42.js";import{e as x}from"./has-content-50BsqrWw.js";const w=14400,B=150*1024*1024,p=8*1024*1024,k=(r,t)=>{r.auth.setAccessToken(t)},R=r=>r.auth.getAccessToken(),T=r=>{let t=0,n=r.length;for(;t<n&&r[t]==="/";)t+=1;for(;n>t&&r[n-1]==="/";)n-=1;return t===0&&n===r.length?r:r.slice(t,n)},H=async r=>{const t=[];for await(const n of r)t.push(Buffer.from(n));return Buffer.concat(t)},O=r=>r.includes("?dl=0")?r.replace("?dl=0","?dl=1"):r.includes("?dl=")?r:r+(r.includes("?")?"&dl=1":"?dl=1"),b=(r,t)=>(k(r,t),{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(t)}),U=(r,t)=>{const n=async()=>{const e=await t();return k(r,e),e};return{async ensureAccessToken(){await n()},getAccessToken:n}},P=(r,t)=>{const n=E({buildBody:()=>new URLSearchParams({client_id:t.appKey,grant_type:"refresh_token",refresh_token:t.refreshToken,...t.appSecret&&{client_secret:t.appSecret}}),onRefresh:e=>{k(r,e)},provider:"Dropbox",tokenUrl:"https://api.dropboxapi.com/oauth2/token"});return{async ensureAccessToken(){await n.getAccessToken()},getAccessToken:()=>n.getAccessToken()}},C=r=>{if(r.client){const i=r.client;return{authHandle:{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(R(i))},client:i}}const t=r.accessToken,n=r.refreshToken!==void 0||r.appKey!==void 0||r.appSecret!==void 0;if(t!==void 0&&n)throw new Error("Dropbox storage: pass exactly one of `accessToken` or `refreshToken` (with `appKey`).");if(t!==void 0){const i=new u({accessToken:typeof t=="string"?t:void 0}),s=new d({auth:i});return{authHandle:typeof t=="function"?U(s,t):b(s,t),client:s}}if(n){if(!r.refreshToken||!r.appKey)throw new Error("Dropbox storage: refresh-token auth requires both `refreshToken` and `appKey`.");const i=new u({}),s=new d({auth:i});return{authHandle:P(s,{appKey:r.appKey,...r.appSecret&&{appSecret:r.appSecret},refreshToken:r.refreshToken}),client:s}}const e=process.env.DROPBOX_ACCESS_TOKEN;if(e){const i=new u({accessToken:e}),s=new d({auth:i});return{authHandle:b(s,e),client:s}}const o=process.env.DROPBOX_REFRESH_TOKEN,a=process.env.DROPBOX_APP_KEY;if(o&&a){const i=process.env.DROPBOX_APP_SECRET,s=new u({}),h=new d({auth:s});return{authHandle:P(h,{appKey:a,...i&&{appSecret:i},refreshToken:o}),client:h}}throw new Error("Dropbox storage: missing auth. Pass `client`, `accessToken`, or `refreshToken` + `appKey`. Env fallbacks: DROPBOX_ACCESS_TOKEN, or DROPBOX_REFRESH_TOKEN + DROPBOX_APP_KEY (+ DROPBOX_APP_SECRET).")};class q extends v{static name="dropbox";checksumTypes=[];meta;authHandle;client;defaultUrlExpiresIn;publicByDefault;rootFolderPath;constructor(t){super(t),this.rootFolderPath=T(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w);const n=C(t);this.client=n.client,this.authHandle=n.authHandle,this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,n){return this.instrumentOperation("create",async()=>{const e=new l(t);e.name=this.namingFunction(e),e.path=this.keyToPath(e.name),await this.validate(e);try{const o=await this.getMeta(e.id);if(o.bytesWritten>=0)return o}catch{}return e.bytesWritten=0,e.status=g(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,n){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&&D(e,t.size),!S(t,e))throw new Error("File part does not match");const o=await this.lock(t.id);try{if(x(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await H(t.body),i=e.path??this.keyToPath(e.name||e.id);await this.authHandle.ensureAccessToken();const s=a.byteLength<=B?await this.uploadSimple(i,a,n):await this.uploadSession(i,a,n);e.bytesWritten=a.length,e.size=a.length,e.path=s.path_display??i,e.rev=s.rev,e.ETag=s.rev}return e.status=g(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,o)}})}async delete({id:t},n){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const o=e?.path??this.keyToPath(e?.name??t);await this.authHandle.ensureAccessToken();try{await this.runOperation(n,()=>this.client.filesDeleteV2({path:o}))}catch(a){if(!L(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new l({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,path:o,status:"deleted"})})}async get({id:t},n){return this.instrumentOperation("get",async()=>{let e,o=this.keyToPath(t);try{e=await this.checkIfExpired(await this.getMeta(t)),o=e.path??this.keyToPath(e.name??t)}catch{}await this.authHandle.ensureAccessToken();const a=(await this.runOperation(n,()=>this.client.filesDownload({path:o}))).result;let i;if(a.fileBinary instanceof Uint8Array)i=Buffer.from(a.fileBinary.buffer,a.fileBinary.byteOffset,a.fileBinary.byteLength);else if(a.fileBlob instanceof Blob)i=Buffer.from(await a.fileBlob.arrayBuffer());else throw new TypeError("Dropbox: unexpected download response shape — neither fileBinary nor fileBlob present");return{content:i,contentType:e?.contentType??"application/octet-stream",ETag:e?.ETag??a.rev,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.server_modified,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??i.length}})}async copy(t,n,e){return this.instrumentOperation("copy",async()=>{const o=this.keyToPath(t),a=this.keyToPath(n);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesCopyV2({from_path:o,to_path:a}));const i=new l({contentType:"application/octet-stream",metadata:{},originalName:n});return i.id=n,i.name=n,i.path=a,i})}async move(t,n,e){return this.instrumentOperation("move",async()=>{const o=this.keyToPath(t),a=this.keyToPath(n);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesMoveV2({from_path:o,to_path:a}));const i=new l({contentType:"application/octet-stream",metadata:{},originalName:n});i.id=n,i.name=n,i.path=a;try{await this.deleteMeta(t)}catch{}return i})}async list(t=1e3,n){return this.instrumentOperation("list",async()=>{await this.authHandle.ensureAccessToken();const e=await this.runOperation(n,()=>this.client.filesListFolder({limit:t,path:this.rootFolderPath?`/${this.rootFolderPath}`:"",recursive:!0})),{result:o}=e,a=[];for(const i of o.entries){if(i[".tag"]!=="file")continue;const s=i,h=s.path_display??s.path_lower??`/${s.name}`,f=this.pathToKey(h);if(!f)continue;const c=new l({contentType:"application/octet-stream",metadata:{},originalName:s.name});c.id=f,c.name=f,c.path=h,c.size=s.size,c.rev=s.rev,c.ETag=s.rev,c.modifiedAt=s.server_modified,a.push(c)}return a},{limit:t})}async getReadUrl(t,n){if(n?.responseContentDisposition!==void 0||n?.responseContentType!==void 0)return m(y.METHOD_NOT_ALLOWED,"Dropbox: `responseContentDisposition`/`responseContentType` are not supported — Dropbox temporary links have no Content-Disposition/Content-Type override.");const e=n?.expiresIn??this.defaultUrlExpiresIn;return e>w?m(y.METHOD_NOT_ALLOWED,`Dropbox: \`expiresIn\` of ${e}s exceeds the ${w}s (4h) maximum. Use \`publicByDefault: true\` for a permanent shared link.`):(await this.authHandle.ensureAccessToken(),this.publicByDefault?await this.createPublicSharedLink(t):(await this.client.filesGetTemporaryLink({path:this.keyToPath(t)})).result.link)}async getUploadUrl(t,n){return m(y.METHOD_NOT_ALLOWED,"Dropbox: presigned upload URLs use POST with a raw body, which doesn't fit the PUT-style upload-url contract. Use `write()` or `storage.raw.filesGetTemporaryUploadLink(...)` directly.")}keyToPath(t){const n=T(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),n&&e.push(n),e.length===0?"":`/${e.join("/")}`}pathToKey(t){const n=T(t);if(!this.rootFolderPath)return n;if(n===this.rootFolderPath)return"";const e=`${this.rootFolderPath}/`;return n.startsWith(e)?n.slice(e.length):n}async uploadSimple(t,n,e){return(await this.runOperation(e,()=>this.client.filesUpload({contents:n,mode:{".tag":"overwrite"},mute:!0,path:t}))).result}async uploadSession(t,n,e){const o=n.byteLength;let a=0;const i=(await this.runOperation(e,()=>this.client.filesUploadSessionStart({close:!1,contents:n.subarray(a,Math.min(a+p,o))}))).result.session_id;for(a=Math.min(a+p,o);o-a>p;){const h=n.subarray(a,a+p);await this.runOperation(e,()=>this.client.filesUploadSessionAppendV2({close:!1,contents:h,cursor:{offset:a,session_id:i}})),a+=p}const s=n.subarray(a,o);return(await this.runOperation(e,()=>this.client.filesUploadSessionFinish({commit:{mode:{".tag":"overwrite"},mute:!0,path:t},contents:s,cursor:{offset:a,session_id:i}}))).result}async createPublicSharedLink(t){try{const n=await this.client.sharingCreateSharedLinkWithSettings({path:this.keyToPath(t),settings:{requested_visibility:{".tag":"public"}}});return O(n.result.url)}catch(n){if(n instanceof _){const e=n.error?.shared_link_already_exists?.metadata?.url;if(typeof e=="string"&&e.length>0)return O(e)}throw n}}internalOnComplete=t=>this.deleteMeta(t.id)}const L=r=>{if(!(r instanceof _))return!1;if(r.status===404)return!0;const t=[],n=(e,o)=>{if(o>6||e===null||typeof e!="object")return;const a=e,i=a[".tag"];typeof i=="string"&&t.push(i);for(const s of Object.values(a))s&&typeof s=="object"&&n(s,o+1)};return n(r.error,0),t.includes("not_found")||t.includes("not_file")||t.includes("not_folder")};export{q as default};
@@ -0,0 +1 @@
1
+ import{y as s}from"./local-meta-storage-DJDcuxf1.js";class o extends s{constructor(r){super(r)}}export{o as default};
@@ -1,2 +1,2 @@
1
- import{readFileSync as y}from"node:fs";import{getApps as g,getApp as m,initializeApp as E,cert as w}from"firebase-admin/app";import{getStorage as b}from"firebase-admin/storage";import{throwErrorCode as u,ERRORS as l}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import c from"./FirebaseFile-BLaBxa2A.js";import T from"./FirebaseMetaStorage-DPVnmNe5.js";import{t as d}from"./get-file-status-y3wTtDQs.js";import{t as k}from"./update-size-DuNuLyxj.js";import{i as A}from"./part-match-D-9dGX42.js";import{e as I}from"./has-content-50BsqrWw.js";const v=3600,S=async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},U=o=>typeof o=="object"&&o!==null&&typeof o.file=="function"&&typeof o.getFiles=="function";class f extends O{static name="firebase";checksumTypes=[];meta;bucket;bucketName;defaultUrlExpiresIn;publicBaseUrl;constructor(t){if(super(t),this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??v,this.publicBaseUrl=t.publicBaseUrl?.replace(/\/+$/,""),t.app&&U(t.app))this.bucket=t.app,this.bucketName=t.app.name??"";else{const a=t.bucket??process.env.FIREBASE_STORAGE_BUCKET;if(!a)throw new Error("Firebase storage: `bucket` is required (or set FIREBASE_STORAGE_BUCKET).");this.bucketName=a;const e=t.app??f.resolveApp(t,a);this.bucket=b(e).bucket(a)}this.meta=t.metaStorage??new T(t.metaStorageConfig),this.isReady=!0}get raw(){return this.bucket}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucketName,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=d(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&&k(e,t.size),!A(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(I(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await S(t.body),s=e.path??e.name;await this.runOperation(a,()=>this.bucket.file(s).save(n,{contentType:e.contentType,resumable:!1})),e.bytesWritten=n.length,e.size=n.length,e.path=s}return e.status=d(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;return await this.runOperation(a,()=>this.bucket.file(i).delete({ignoreNotFound:!0})),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.bucketName,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{}try{const[i]=await this.runOperation(a,()=>this.bucket.file(e).exists());return i}catch{return!1}})}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 n=this.bucket.file(e),[s]=await this.runOperation(a,()=>n.download());let r={};try{[r]=await this.runOperation(a,()=>n.getMetadata())}catch{}return{content:s,contentType:i?.contentType??r.contentType??"application/octet-stream",ETag:i?.ETag??r.etag,expiredAt:i?.expiredAt,id:t,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt??r.updated,name:i?.name??e,originalName:i?.originalName??e,size:i?.size??(r.size===void 0?s.length:Number(r.size))}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(i).copy(this.bucket.file(a)));const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return n.id=a,n.name=a,n.path=a,n.bucket=this.bucketName,n})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(i).move(a));const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucketName;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const[e]=await this.runOperation(a,()=>this.bucket.getFiles({maxResults:t}));return(e??[]).map(i=>{const n=new c({contentType:"application/octet-stream",metadata:{},originalName:i.name});return n.id=i.name,n.name=i.name,n.path=i.name,n.bucket=this.bucketName,n})},{limit:t})}async getReadUrl(t,a){if(this.publicBaseUrl)return a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0?u(l.BAD_REQUEST,"Firebase: `responseContentDisposition`/`responseContentType` are not supported when `publicBaseUrl` is configured — a static public URL has no signature in which to bind the override."):`${this.publicBaseUrl}/${t}`;const e=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(t).getSignedUrl({action:"read",expires:Date.now()+e*1e3,...a?.responseContentDisposition!==void 0&&{responseDisposition:a.responseContentDisposition},...a?.responseContentType!==void 0&&{responseType:a.responseContentType}});return i}catch(i){return u(l.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}async getUploadUrl(t,a){if(a?.contentLength!==void 0)return u(l.BAD_REQUEST,"Firebase: `contentLength` is not supported for upload URLs. A GCS signed PUT has no content-length-range policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the URL.");const e=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(t).getSignedUrl({action:"write",contentType:a?.contentType,expires:Date.now()+e*1e3});return i}catch(i){return u(l.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}static resolveApp(t,a){const{appName:e}=t,i=g();if(e?i.find(p=>p.name===e):i[0])return e?m(e):m();const n=t.projectId??process.env.FIREBASE_PROJECT_ID??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT;let s=t.credentials?.clientEmail??process.env.FIREBASE_CLIENT_EMAIL,r=t.credentials?.privateKey??process.env.FIREBASE_PRIVATE_KEY;const h=t.serviceAccountPath??process.env.GOOGLE_APPLICATION_CREDENTIALS;if((!s||!r)&&h){const p=JSON.parse(y(h,"utf8"));s??=p.client_email,r??=p.private_key}if(!s||!r)throw new Error("Firebase storage: service-account credentials are required. Provide `credentials` ({ clientEmail, privateKey }), `serviceAccountPath`, or set FIREBASE_CLIENT_EMAIL / FIREBASE_PRIVATE_KEY / GOOGLE_APPLICATION_CREDENTIALS.");return E({credential:w({clientEmail:s,privateKey:r.replaceAll(String.raw`\n`,`
1
+ import{readFileSync as y}from"node:fs";import{getApps as g,getApp as m,initializeApp as E,cert as w}from"firebase-admin/app";import{getStorage as b}from"firebase-admin/storage";import{throwErrorCode as u,ERRORS as l}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import c from"./FirebaseFile-BLaBxa2A.js";import T from"./FirebaseMetaStorage-BI9YXcwU.js";import{t as d}from"./get-file-status-y3wTtDQs.js";import{t as k}from"./update-size-DuNuLyxj.js";import{i as A}from"./part-match-D-9dGX42.js";import{e as I}from"./has-content-50BsqrWw.js";const v=3600,S=async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},U=o=>typeof o=="object"&&o!==null&&typeof o.file=="function"&&typeof o.getFiles=="function";class f extends O{static name="firebase";checksumTypes=[];meta;bucket;bucketName;defaultUrlExpiresIn;publicBaseUrl;constructor(t){if(super(t),this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??v,this.publicBaseUrl=t.publicBaseUrl?.replace(/\/+$/,""),t.app&&U(t.app))this.bucket=t.app,this.bucketName=t.app.name??"";else{const a=t.bucket??process.env.FIREBASE_STORAGE_BUCKET;if(!a)throw new Error("Firebase storage: `bucket` is required (or set FIREBASE_STORAGE_BUCKET).");this.bucketName=a;const e=t.app??f.resolveApp(t,a);this.bucket=b(e).bucket(a)}this.meta=t.metaStorage??new T(t.metaStorageConfig),this.isReady=!0}get raw(){return this.bucket}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucketName,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=d(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&&k(e,t.size),!A(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(I(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await S(t.body),s=e.path??e.name;await this.runOperation(a,()=>this.bucket.file(s).save(n,{contentType:e.contentType,resumable:!1})),e.bytesWritten=n.length,e.size=n.length,e.path=s}return e.status=d(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;return await this.runOperation(a,()=>this.bucket.file(i).delete({ignoreNotFound:!0})),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.bucketName,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{}try{const[i]=await this.runOperation(a,()=>this.bucket.file(e).exists());return i}catch{return!1}})}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 n=this.bucket.file(e),[s]=await this.runOperation(a,()=>n.download());let r={};try{[r]=await this.runOperation(a,()=>n.getMetadata())}catch{}return{content:s,contentType:i?.contentType??r.contentType??"application/octet-stream",ETag:i?.ETag??r.etag,expiredAt:i?.expiredAt,id:t,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt??r.updated,name:i?.name??e,originalName:i?.originalName??e,size:i?.size??(r.size===void 0?s.length:Number(r.size))}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(i).copy(this.bucket.file(a)));const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return n.id=a,n.name=a,n.path=a,n.bucket=this.bucketName,n})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(i).move(a));const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucketName;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const[e]=await this.runOperation(a,()=>this.bucket.getFiles({maxResults:t}));return(e??[]).map(i=>{const n=new c({contentType:"application/octet-stream",metadata:{},originalName:i.name});return n.id=i.name,n.name=i.name,n.path=i.name,n.bucket=this.bucketName,n})},{limit:t})}async getReadUrl(t,a){if(this.publicBaseUrl)return a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0?u(l.BAD_REQUEST,"Firebase: `responseContentDisposition`/`responseContentType` are not supported when `publicBaseUrl` is configured — a static public URL has no signature in which to bind the override."):`${this.publicBaseUrl}/${t}`;const e=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(t).getSignedUrl({action:"read",expires:Date.now()+e*1e3,...a?.responseContentDisposition!==void 0&&{responseDisposition:a.responseContentDisposition},...a?.responseContentType!==void 0&&{responseType:a.responseContentType}});return i}catch(i){return u(l.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}async getUploadUrl(t,a){if(a?.contentLength!==void 0)return u(l.BAD_REQUEST,"Firebase: `contentLength` is not supported for upload URLs. A GCS signed PUT has no content-length-range policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the URL.");const e=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(t).getSignedUrl({action:"write",contentType:a?.contentType,expires:Date.now()+e*1e3});return i}catch(i){return u(l.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}static resolveApp(t,a){const{appName:e}=t,i=g();if(e?i.find(p=>p.name===e):i[0])return e?m(e):m();const n=t.projectId??process.env.FIREBASE_PROJECT_ID??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT;let s=t.credentials?.clientEmail??process.env.FIREBASE_CLIENT_EMAIL,r=t.credentials?.privateKey??process.env.FIREBASE_PRIVATE_KEY;const h=t.serviceAccountPath??process.env.GOOGLE_APPLICATION_CREDENTIALS;if((!s||!r)&&h){const p=JSON.parse(y(h,"utf8"));s??=p.client_email,r??=p.private_key}if(!s||!r)throw new Error("Firebase storage: service-account credentials are required. Provide `credentials` ({ clientEmail, privateKey }), `serviceAccountPath`, or set FIREBASE_CLIENT_EMAIL / FIREBASE_PRIVATE_KEY / GOOGLE_APPLICATION_CREDENTIALS.");return E({credential:w({clientEmail:s,privateKey:r.replaceAll(String.raw`\n`,`
2
2
  `),projectId:n}),projectId:n,storageBucket:a},e)}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=t=>this.deleteMeta(t.id)}export{f as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{Readable as y,Writable as E}from"node:stream";import{Client as F}from"basic-ftp";import{F as T}from"./index-nZWCQrSe.js";import{throwErrorCode as u,ERRORS as m}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import k from"./FtpFile-ClWDYnt2.js";import b from"./FtpMetaStorage-BSn6Qfnf.js";import{r as l,t as v,e as M}from"./posix-dirname-CfpH5wZi.js";import{t as P}from"./get-file-status-y3wTtDQs.js";import{t as A}from"./update-size-DuNuLyxj.js";import{i as R}from"./part-match-D-9dGX42.js";import{e as D}from"./has-content-50BsqrWw.js";const d=h=>{const a=h?.code;if(a===550||a===450||a===553)return!0;const e=h instanceof Error?h.message:String(h);return/no such file|not exist|cannot find|file unavailable/i.test(e)},f=h=>{if(h instanceof Error&&h.name==="AbortError")return h;const a=new Error(h instanceof Error&&h.message?h.message:"The operation was aborted",{cause:h});return a.name="AbortError",a},g=async(h,a,e)=>{const t=[],n=new E({write(i,r,s){t.push(Buffer.from(i)),s()}});return await h.downloadTo(n,a,e&&e>0?e:void 0),Buffer.concat(t)};class H extends O{static name="ftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=l(a.rootFolderPath??""),this.meta=a.metaStorage??new b(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new k(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const n=await this.getMeta(t.id);if(n.status==="completed")return n}catch{}return t.bytesWritten=0,t.status=P(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&A(t,a.size),!R(a,t))return u(m.FILE_CONFLICT);const n=await this.lock(a.id);try{if(D(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return u(m.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return u(m.METHOD_NOT_ALLOWED,"FTP storage does not support chunked or resumable uploads; send the file in a single request.");const i=await v(a.body),r=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{await this.ensureRemoteDirectory(o,r),await o.uploadFrom(y.from(i),r)})),t.bytesWritten=i.length,t.size=i.length,t.path=r,t.ETag=T(i)}return t.status=P(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,n)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),n=t.path??this.keyToPath(t.name||a),{range:i}=e??{},r=await this.runOperation(e,s=>this.run(s,async o=>{try{const c=await g(o,n,i?.start);return i?.end!==void 0?c.subarray(0,i.end-i.start+1):c}catch(c){if(d(c))return u(m.FILE_NOT_FOUND);throw c}}));return{content:r,contentType:t.contentType,ETag:t.ETag??T(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:i?r.length:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),n=t.path??this.keyToPath(t.name||a);await this.runOperation(e,r=>this.run(r,async s=>{try{await s.remove(n)}catch(o){if(!d(o))throw o}})),await this.deleteMeta(a);const i={...t,status:"deleted"};return await this.onDelete(i),i})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(a),i=n.path??this.keyToPath(n.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{const p=await g(c,i);await this.ensureRemoteDirectory(c,r),await c.uploadFrom(y.from(p),r)}));const s={...n,id:e,name:e,path:r};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const n=await this.getMeta(a),i=n.path??this.keyToPath(n.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{try{await this.ensureRemoteDirectory(c,r),await c.rename(i,r)}catch(p){try{const w=await g(c,i);await this.ensureRemoteDirectory(c,r),await c.uploadFrom(y.from(w),r),await c.remove(i)}catch(w){throw new AggregateError([p,w],`FTP move failed: rename and copy+delete fallback both failed for "${i}" → "${r}"`)}}}));const s={...n,id:e,name:e,path:r};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,n=>this.run(n,async i=>{const r=[];return await this.walkList(i,t,r),r}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const n=t.path??this.keyToPath(t.name||a);return this.runOperation(e,i=>this.run(i,async r=>{try{return await r.size(n),!0}catch(s){if(d(s))return!1;throw s}}))})}async walkList(a,e,t){let n;try{n=await a.list(e||".")}catch(i){if(d(i))return;throw i}for(const i of n){const r=e?`${e}/${i.name}`:i.name;if(i.isDirectory){await this.walkList(a,r,t);continue}if(!i.isFile)continue;const s=this.pathToKey(r);if(!s)continue;const o=new k({contentType:"application/octet-stream",metadata:{},originalName:i.name});o.id=s,o.name=s,o.path=r,o.size=i.size,i.modifiedAt&&(o.modifiedAt=i.modifiedAt.toISOString()),t.push(o)}}async run(a,e){const t=new F;if(a?.aborted)throw f(a.reason);const n=()=>{t.close()};a?.addEventListener("abort",n,{once:!0});try{if(await t.access(this.connection),a?.aborted)throw f(a.reason);return await e(t)}catch(i){throw a?.aborted?f(i):i}finally{a?.removeEventListener("abort",n),t.close()}}async ensureRemoteDirectory(a,e){const t=M(e);t&&(await a.ensureDir(t),await a.cd("/"))}keyToPath(a){const e=l(a);e&&O.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":`/${t.join("/")}`}pathToKey(a){const e=l(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{H as default};
1
+ import{Readable as y,Writable as E}from"node:stream";import{Client as F}from"basic-ftp";import{F as T}from"./index-nZWCQrSe.js";import{throwErrorCode as u,ERRORS as m}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import k from"./FtpFile-ClWDYnt2.js";import b from"./FtpMetaStorage-CHWrhgg2.js";import{r as l,t as v,e as M}from"./posix-dirname-CfpH5wZi.js";import{t as P}from"./get-file-status-y3wTtDQs.js";import{t as A}from"./update-size-DuNuLyxj.js";import{i as R}from"./part-match-D-9dGX42.js";import{e as D}from"./has-content-50BsqrWw.js";const d=h=>{const a=h?.code;if(a===550||a===450||a===553)return!0;const e=h instanceof Error?h.message:String(h);return/no such file|not exist|cannot find|file unavailable/i.test(e)},f=h=>{if(h instanceof Error&&h.name==="AbortError")return h;const a=new Error(h instanceof Error&&h.message?h.message:"The operation was aborted",{cause:h});return a.name="AbortError",a},g=async(h,a,e)=>{const t=[],n=new E({write(i,r,s){t.push(Buffer.from(i)),s()}});return await h.downloadTo(n,a,e&&e>0?e:void 0),Buffer.concat(t)};class H extends O{static name="ftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=l(a.rootFolderPath??""),this.meta=a.metaStorage??new b(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new k(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const n=await this.getMeta(t.id);if(n.status==="completed")return n}catch{}return t.bytesWritten=0,t.status=P(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&A(t,a.size),!R(a,t))return u(m.FILE_CONFLICT);const n=await this.lock(a.id);try{if(D(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return u(m.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return u(m.METHOD_NOT_ALLOWED,"FTP storage does not support chunked or resumable uploads; send the file in a single request.");const i=await v(a.body),r=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{await this.ensureRemoteDirectory(o,r),await o.uploadFrom(y.from(i),r)})),t.bytesWritten=i.length,t.size=i.length,t.path=r,t.ETag=T(i)}return t.status=P(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,n)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),n=t.path??this.keyToPath(t.name||a),{range:i}=e??{},r=await this.runOperation(e,s=>this.run(s,async o=>{try{const c=await g(o,n,i?.start);return i?.end!==void 0?c.subarray(0,i.end-i.start+1):c}catch(c){if(d(c))return u(m.FILE_NOT_FOUND);throw c}}));return{content:r,contentType:t.contentType,ETag:t.ETag??T(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:i?r.length:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),n=t.path??this.keyToPath(t.name||a);await this.runOperation(e,r=>this.run(r,async s=>{try{await s.remove(n)}catch(o){if(!d(o))throw o}})),await this.deleteMeta(a);const i={...t,status:"deleted"};return await this.onDelete(i),i})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(a),i=n.path??this.keyToPath(n.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{const p=await g(c,i);await this.ensureRemoteDirectory(c,r),await c.uploadFrom(y.from(p),r)}));const s={...n,id:e,name:e,path:r};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const n=await this.getMeta(a),i=n.path??this.keyToPath(n.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{try{await this.ensureRemoteDirectory(c,r),await c.rename(i,r)}catch(p){try{const w=await g(c,i);await this.ensureRemoteDirectory(c,r),await c.uploadFrom(y.from(w),r),await c.remove(i)}catch(w){throw new AggregateError([p,w],`FTP move failed: rename and copy+delete fallback both failed for "${i}" → "${r}"`)}}}));const s={...n,id:e,name:e,path:r};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,n=>this.run(n,async i=>{const r=[];return await this.walkList(i,t,r),r}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const n=t.path??this.keyToPath(t.name||a);return this.runOperation(e,i=>this.run(i,async r=>{try{return await r.size(n),!0}catch(s){if(d(s))return!1;throw s}}))})}async walkList(a,e,t){let n;try{n=await a.list(e||".")}catch(i){if(d(i))return;throw i}for(const i of n){const r=e?`${e}/${i.name}`:i.name;if(i.isDirectory){await this.walkList(a,r,t);continue}if(!i.isFile)continue;const s=this.pathToKey(r);if(!s)continue;const o=new k({contentType:"application/octet-stream",metadata:{},originalName:i.name});o.id=s,o.name=s,o.path=r,o.size=i.size,i.modifiedAt&&(o.modifiedAt=i.modifiedAt.toISOString()),t.push(o)}}async run(a,e){const t=new F;if(a?.aborted)throw f(a.reason);const n=()=>{t.close()};a?.addEventListener("abort",n,{once:!0});try{if(await t.access(this.connection),a?.aborted)throw f(a.reason);return await e(t)}catch(i){throw a?.aborted?f(i):i}finally{a?.removeEventListener("abort",n),t.close()}}async ensureRemoteDirectory(a,e){const t=M(e);t&&(await a.ensureDir(t),await a.cd("/"))}keyToPath(a){const e=l(a);e&&O.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":`/${t.join("/")}`}pathToKey(a){const e=l(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{H as default};
@@ -1 +1 @@
1
- import"node:crypto";import"gaxios";import"google-auth-library";import{v as f}from"./gcs-meta-storage-B7BnctnV.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-B7CcBueg.js";import"./GCSConfig-BQ0OpVhe.js";export{f as default};
1
+ import"node:crypto";import"gaxios";import"google-auth-library";import{v as f}from"./gcs-meta-storage-DQGu_cHq.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-B7CcBueg.js";import"./GCSConfig-BQ0OpVhe.js";export{f as default};
@@ -1 +1 @@
1
- import{randomUUID as g}from"node:crypto";import{request as f}from"gaxios";import{GoogleAuth as y}from"google-auth-library";import{r as w,v as R,g as C,m,b}from"./gcs-meta-storage-B7BnctnV.js";import{d as E}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as k,ERRORS as U}from"./ERRORS-BIBxE2oR.js";import{B as I,c as S}from"./storage-0j5nCAUp.js";import{y as T}from"./local-meta-storage-iuJnu90B.js";import d from"./GCSConfig-BQ0OpVhe.js";import x from"./GCSFile-Cero7qZN.js";import{i as O}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";import{t as A}from"./get-file-status-y3wTtDQs.js";class B extends Error{constructor(t,s,e){super(t),this.code=s,this.config=e}code;config;name="FetchError"}const $=l=>l>=200&&l<300||l===308||l===499;class p extends I{static name="gcs";checksumTypes=["md5","crc32c"];supportsDelimiter=!0;get raw(){return this.authClient}meta;bucket;authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;constructor(t){super(t);const s=t.bucket||process.env.GCS_BUCKET;if(!s)throw new Error("GCS bucket is not defined");if(!t.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");this.bucket=s,this.storageBaseURI=`${t.storageAPI||d.storageAPI}/${this.bucket}/o`,this.uploadBaseURI=`${t.uploadAPI||d.uploadAPI}/${this.bucket}/o`,this.isCustomEndpoint=new URL(this.storageBaseURI).hostname!=="storage.googleapis.com";const{retryOptions:e,useAuthWithCustomEndpoint:r,userProject:i}=t;this.userProject=i,this.useAuthWithCustomEndpoint=r||!1,this.retryOptions={...w,...e},t.scopes||=d.authScopes,this.authClient=new y(t);const{bucket:n,metaStorage:c,metaStorageConfig:o,projectId:a}=t;if(c)this.meta=c;else{let u={...t,...o,logger:this.logger};"directory"in u?(this.logger?.debug("Using local meta storage"),this.meta=new T(u)):(n===u.bucket&&a===u.projectId&&(u={...u,authClient:this.authClient}),this.meta=new R(u))}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(u=>{this.logger?.error("Storage access check failed: %O",u)})}normalizeError(t){if(t.config){const s=+t.code||500;return{code:`GCS${s}`,message:t.message,name:t.name,retryable:s>=499,statusCode:s}}return{code:"GenericUploadError",message:`[${this.constructor.name}] ${t.message}`,name:t.name,statusCode:500}}async create(t,s){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const a=typeof t.ttl=="string"?S(t.ttl):t.ttl;a!==void 0&&(e.expiredAt=Date.now()+a)}const r=new x(e);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);return a.bytesWritten=await this.internalWrite(a,s),a}catch{}const i={"Content-Type":"application/json; charset=utf-8","X-Goog-Upload-Command":"start","X-Goog-Upload-Protocol":"resumable","X-Upload-Content-Length":r.size.toString(),"X-Upload-Content-Type":r.contentType},n={body:JSON.stringify({metadata:r.metadata}),headers:i,method:"POST",params:{name:r.name,size:r.size,uploadType:"resumable"},url:this.uploadBaseURI},c=await this.makeRequest(n,s);if(c.status!==200)throw new Error("Expected 200 response from GCS");const o=c.headers.get("X-Goog-Upload-Status")||c.headers.get("x-goog-upload-status");if(o!=="active")throw new Error(`X-Goog-Upload-Status response header expected 'active' got: ${o}`);return r.uri=c.headers.get("location"),this.config.clientDirectUpload?(r.GCSUploadURI=r.uri,this.logger?.debug("send uploadURI to client: %s",r.GCSUploadURI),r.status="created",r):(r.bytesWritten=0,await this.saveMeta(r),r.status="created",await this.onCreate(r),r)})}async write(t,s){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(!O(t,e))return k(U.FILE_CONFLICT);const r=await this.lock(t.id);try{if(v(t)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:i,stream:n}=await E(t.body);i?.mime&&(e.contentType=i.mime),t.body=n}catch{}e.bytesWritten=await this.internalWrite({...e,...t},s),e.status=A(e),e.status==="completed"&&(e.uri=`${this.storageBaseURI}/${e.name}`,await this.internalOnComplete(e))}finally{await this.unlock(t.id,r)}return e})}async delete({id:t},s){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);if(!e.uri)throw new Error(`File ${t} does not have a valid URI`);e.status="deleted",await this.makeRequest({method:"DELETE",url:e.uri,validateStatus:$},s),await this.deleteMeta(e.id);const r={...e};return await this.onDelete(r),r})}async copy(t,s,e){return this.instrumentOperation("copy",async()=>{const r=new URL(`/${this.bucket}/${t}`,"file://"),i=new URL(encodeURI(s),r).pathname,[,n,...c]=i.split("/"),o=c.join("/"),a=`${this.storageBaseURI}/${t}/rewriteTo/b/${n}/o/${o}`;let u={};const h={body:"",headers:{"Content-Type":"application/json"},method:"POST",url:a};do h.body=u.rewriteToken?JSON.stringify({rewriteToken:u.rewriteToken}):"",u=(await this.makeRequest(h,e)).data||{};while(u.rewriteToken);return await this.getMeta(s)})}async move(t,s,e){return this.instrumentOperation("move",async()=>{const r=await this.copy(t,s,e),i=`${this.storageBaseURI}/${t}`;return await this.makeRequest({method:"DELETE",url:i},e),r})}async get({id:t},s){return this.instrumentOperation("get",async()=>{const{data:e}=await this.makeRequest({params:{alt:"json"},url:`${this.storageBaseURI}/${t}`},s);if(await this.checkIfExpired({expiredAt:e.timeDeleted}),!e.uri)throw new Error("File URI not found");const r=(await this.makeRequest({params:{alt:"media"},url:e.uri},s)).data;let i;if(typeof r=="string")i=Buffer.from(r,"utf8");else if(r&&typeof r=="object"&&"data"in r){const n=r.data;i=Buffer.from(n)}else i=Buffer.from(r);return{...e,content:i}})}async exists({id:t},s){return this.instrumentOperation("exists",async()=>{try{return await this.getMeta(t),await this.makeRequest({method:"HEAD",url:`${this.storageBaseURI}/${t}`},s),!0}catch{return!1}})}async list(t=1e3,s){return this.instrumentOperation("list",async()=>{const e=[],r=Math.min(t,1e3);let i=!0,n={params:{maxResults:r},url:this.storageBaseURI};for(;i&&e.length<t;)try{const{data:c}=await this.makeRequest(n,s);for(const{name:o,timeCreated:a,updated:u}of c?.items||[]){if(e.length>=t)break;e.push({createdAt:a,id:o,modifiedAt:u})}i=c?.nextPageToken!==void 0,i&&e.length<t&&(n={...n,params:{...n.params,maxResults:Math.min(r,t-e.length),pageToken:c.nextPageToken}})}catch(c){const o=this.normalizeError(c instanceof Error?c:new Error(String(c)));throw await this.onError(o),c}return e},{limit:t})}async listDirectory(t){return this.instrumentOperation("listDirectory",async()=>{const s=t?.limit??1e3,e=Math.min(s,1e3),r=[],i=new Set;let n=!0,c={params:{delimiter:t?.delimiter,maxResults:e,...t?.prefix!==void 0&&{prefix:t.prefix}},url:this.storageBaseURI};for(;n&&r.length<s;)try{const{data:o}=await this.makeRequest(c,t);for(const a of o?.prefixes||[])i.add(a);for(const{name:a,timeCreated:u,updated:h}of o?.items||[]){if(r.length>=s)break;r.push({createdAt:u,id:a,modifiedAt:h})}n=o?.nextPageToken!==void 0,n&&r.length<s&&(c={...c,params:{...c.params,maxResults:Math.min(e,s-r.length),pageToken:o.nextPageToken}})}catch(o){const a=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(a),o}return{files:r,prefixes:[...i]}},{limit:t?.limit??1e3})}async internalWrite(t,s){const{body:e,bytesWritten:r,size:i,uri:n=""}=t,c=b(t),o={method:"PUT"};if(e?.on){const a=new AbortController;e.on("aborted",()=>{a.abort()}),o.body=e,o.signal=a.signal,o.retry=!1}o.headers={Accept:"application/json","Content-Range":c,...i===r?{"X-Goog-Upload-Command":"upload, finalize"}:{}};try{const a=await this.makeRequest({url:n,...o},s);if(a.status===308){const u=a.headers.get("range");return u?C(u):0}if(a.status===200)return this.logger?.debug("uploaded %O",a.data),i;throw new B(String(a.data),`GCS${a.status}`,{uri:n})}catch(a){this.logger?.error(n,a);const u=this.normalizeError(a instanceof Error?a:new Error(String(a)));throw await this.onError(u),a}}internalOnComplete=t=>this.deleteMeta(t.id);static buildCallSignal(t,s){const e=[];if(s&&e.push(s),t?.signal&&e.push(t.signal),e.length!==0)return e.length===1?e[0]:AbortSignal.any(e)}async makeRequest(t,s){typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":"));const e=p.buildCallSignal(s,t.signal);let r=this.retryOptions;if(s?.retries!==void 0){const n=typeof s.retries=="number"?s.retries:s.retries.maxRetries;typeof n=="number"&&(r={...this.retryOptions,retry:n})}const i=typeof s?.timeout=="number"&&s.timeout>0?s.timeout:6e4;return t={...t,headers:{"User-Agent":`${m.name}/${m.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${m.version} gccl-invocation-id/${g()}`,...t.headers},params:{...this.userProject===void 0?{}:{userProject:this.userProject},...t.params},retry:t.retry===!1?!1:s?.retries!==0,retryConfig:r,timeout:i,...e?{signal:e}:{}},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?f(t):this.authClient.request(t)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}}export{p as default};
1
+ import{randomUUID as g}from"node:crypto";import{request as f}from"gaxios";import{GoogleAuth as y}from"google-auth-library";import{r as w,v as R,g as C,m,b}from"./gcs-meta-storage-DQGu_cHq.js";import{d as E}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as k,ERRORS as U}from"./ERRORS-BIBxE2oR.js";import{B as I,c as S}from"./storage-0j5nCAUp.js";import{y as T}from"./local-meta-storage-DJDcuxf1.js";import d from"./GCSConfig-BQ0OpVhe.js";import x from"./GCSFile-Cero7qZN.js";import{i as O}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";import{t as A}from"./get-file-status-y3wTtDQs.js";class B extends Error{constructor(t,s,e){super(t),this.code=s,this.config=e}code;config;name="FetchError"}const $=l=>l>=200&&l<300||l===308||l===499;class p extends I{static name="gcs";checksumTypes=["md5","crc32c"];supportsDelimiter=!0;get raw(){return this.authClient}meta;bucket;authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;constructor(t){super(t);const s=t.bucket||process.env.GCS_BUCKET;if(!s)throw new Error("GCS bucket is not defined");if(!t.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");this.bucket=s,this.storageBaseURI=`${t.storageAPI||d.storageAPI}/${this.bucket}/o`,this.uploadBaseURI=`${t.uploadAPI||d.uploadAPI}/${this.bucket}/o`,this.isCustomEndpoint=new URL(this.storageBaseURI).hostname!=="storage.googleapis.com";const{retryOptions:e,useAuthWithCustomEndpoint:r,userProject:i}=t;this.userProject=i,this.useAuthWithCustomEndpoint=r||!1,this.retryOptions={...w,...e},t.scopes||=d.authScopes,this.authClient=new y(t);const{bucket:n,metaStorage:c,metaStorageConfig:o,projectId:a}=t;if(c)this.meta=c;else{let u={...t,...o,logger:this.logger};"directory"in u?(this.logger?.debug("Using local meta storage"),this.meta=new T(u)):(n===u.bucket&&a===u.projectId&&(u={...u,authClient:this.authClient}),this.meta=new R(u))}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(u=>{this.logger?.error("Storage access check failed: %O",u)})}normalizeError(t){if(t.config){const s=+t.code||500;return{code:`GCS${s}`,message:t.message,name:t.name,retryable:s>=499,statusCode:s}}return{code:"GenericUploadError",message:`[${this.constructor.name}] ${t.message}`,name:t.name,statusCode:500}}async create(t,s){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const a=typeof t.ttl=="string"?S(t.ttl):t.ttl;a!==void 0&&(e.expiredAt=Date.now()+a)}const r=new x(e);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);return a.bytesWritten=await this.internalWrite(a,s),a}catch{}const i={"Content-Type":"application/json; charset=utf-8","X-Goog-Upload-Command":"start","X-Goog-Upload-Protocol":"resumable","X-Upload-Content-Length":r.size.toString(),"X-Upload-Content-Type":r.contentType},n={body:JSON.stringify({metadata:r.metadata}),headers:i,method:"POST",params:{name:r.name,size:r.size,uploadType:"resumable"},url:this.uploadBaseURI},c=await this.makeRequest(n,s);if(c.status!==200)throw new Error("Expected 200 response from GCS");const o=c.headers.get("X-Goog-Upload-Status")||c.headers.get("x-goog-upload-status");if(o!=="active")throw new Error(`X-Goog-Upload-Status response header expected 'active' got: ${o}`);return r.uri=c.headers.get("location"),this.config.clientDirectUpload?(r.GCSUploadURI=r.uri,this.logger?.debug("send uploadURI to client: %s",r.GCSUploadURI),r.status="created",r):(r.bytesWritten=0,await this.saveMeta(r),r.status="created",await this.onCreate(r),r)})}async write(t,s){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(!O(t,e))return k(U.FILE_CONFLICT);const r=await this.lock(t.id);try{if(v(t)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:i,stream:n}=await E(t.body);i?.mime&&(e.contentType=i.mime),t.body=n}catch{}e.bytesWritten=await this.internalWrite({...e,...t},s),e.status=A(e),e.status==="completed"&&(e.uri=`${this.storageBaseURI}/${e.name}`,await this.internalOnComplete(e))}finally{await this.unlock(t.id,r)}return e})}async delete({id:t},s){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);if(!e.uri)throw new Error(`File ${t} does not have a valid URI`);e.status="deleted",await this.makeRequest({method:"DELETE",url:e.uri,validateStatus:$},s),await this.deleteMeta(e.id);const r={...e};return await this.onDelete(r),r})}async copy(t,s,e){return this.instrumentOperation("copy",async()=>{const r=new URL(`/${this.bucket}/${t}`,"file://"),i=new URL(encodeURI(s),r).pathname,[,n,...c]=i.split("/"),o=c.join("/"),a=`${this.storageBaseURI}/${t}/rewriteTo/b/${n}/o/${o}`;let u={};const h={body:"",headers:{"Content-Type":"application/json"},method:"POST",url:a};do h.body=u.rewriteToken?JSON.stringify({rewriteToken:u.rewriteToken}):"",u=(await this.makeRequest(h,e)).data||{};while(u.rewriteToken);return await this.getMeta(s)})}async move(t,s,e){return this.instrumentOperation("move",async()=>{const r=await this.copy(t,s,e),i=`${this.storageBaseURI}/${t}`;return await this.makeRequest({method:"DELETE",url:i},e),r})}async get({id:t},s){return this.instrumentOperation("get",async()=>{const{data:e}=await this.makeRequest({params:{alt:"json"},url:`${this.storageBaseURI}/${t}`},s);if(await this.checkIfExpired({expiredAt:e.timeDeleted}),!e.uri)throw new Error("File URI not found");const r=(await this.makeRequest({params:{alt:"media"},url:e.uri},s)).data;let i;if(typeof r=="string")i=Buffer.from(r,"utf8");else if(r&&typeof r=="object"&&"data"in r){const n=r.data;i=Buffer.from(n)}else i=Buffer.from(r);return{...e,content:i}})}async exists({id:t},s){return this.instrumentOperation("exists",async()=>{try{return await this.getMeta(t),await this.makeRequest({method:"HEAD",url:`${this.storageBaseURI}/${t}`},s),!0}catch{return!1}})}async list(t=1e3,s){return this.instrumentOperation("list",async()=>{const e=[],r=Math.min(t,1e3);let i=!0,n={params:{maxResults:r},url:this.storageBaseURI};for(;i&&e.length<t;)try{const{data:c}=await this.makeRequest(n,s);for(const{name:o,timeCreated:a,updated:u}of c?.items||[]){if(e.length>=t)break;e.push({createdAt:a,id:o,modifiedAt:u})}i=c?.nextPageToken!==void 0,i&&e.length<t&&(n={...n,params:{...n.params,maxResults:Math.min(r,t-e.length),pageToken:c.nextPageToken}})}catch(c){const o=this.normalizeError(c instanceof Error?c:new Error(String(c)));throw await this.onError(o),c}return e},{limit:t})}async listDirectory(t){return this.instrumentOperation("listDirectory",async()=>{const s=t?.limit??1e3,e=Math.min(s,1e3),r=[],i=new Set;let n=!0,c={params:{delimiter:t?.delimiter,maxResults:e,...t?.prefix!==void 0&&{prefix:t.prefix}},url:this.storageBaseURI};for(;n&&r.length<s;)try{const{data:o}=await this.makeRequest(c,t);for(const a of o?.prefixes||[])i.add(a);for(const{name:a,timeCreated:u,updated:h}of o?.items||[]){if(r.length>=s)break;r.push({createdAt:u,id:a,modifiedAt:h})}n=o?.nextPageToken!==void 0,n&&r.length<s&&(c={...c,params:{...c.params,maxResults:Math.min(e,s-r.length),pageToken:o.nextPageToken}})}catch(o){const a=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(a),o}return{files:r,prefixes:[...i]}},{limit:t?.limit??1e3})}async internalWrite(t,s){const{body:e,bytesWritten:r,size:i,uri:n=""}=t,c=b(t),o={method:"PUT"};if(e?.on){const a=new AbortController;e.on("aborted",()=>{a.abort()}),o.body=e,o.signal=a.signal,o.retry=!1}o.headers={Accept:"application/json","Content-Range":c,...i===r?{"X-Goog-Upload-Command":"upload, finalize"}:{}};try{const a=await this.makeRequest({url:n,...o},s);if(a.status===308){const u=a.headers.get("range");return u?C(u):0}if(a.status===200)return this.logger?.debug("uploaded %O",a.data),i;throw new B(String(a.data),`GCS${a.status}`,{uri:n})}catch(a){this.logger?.error(n,a);const u=this.normalizeError(a instanceof Error?a:new Error(String(a)));throw await this.onError(u),a}}internalOnComplete=t=>this.deleteMeta(t.id);static buildCallSignal(t,s){const e=[];if(s&&e.push(s),t?.signal&&e.push(t.signal),e.length!==0)return e.length===1?e[0]:AbortSignal.any(e)}async makeRequest(t,s){typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":"));const e=p.buildCallSignal(s,t.signal);let r=this.retryOptions;if(s?.retries!==void 0){const n=typeof s.retries=="number"?s.retries:s.retries.maxRetries;typeof n=="number"&&(r={...this.retryOptions,retry:n})}const i=typeof s?.timeout=="number"&&s.timeout>0?s.timeout:6e4;return t={...t,headers:{"User-Agent":`${m.name}/${m.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${m.version} gccl-invocation-id/${g()}`,...t.headers},params:{...this.userProject===void 0?{}:{userProject:this.userProject},...t.params},retry:t.retry===!1?!1:s?.retries!==0,retryConfig:r,timeout:i,...e?{signal:e}:{}},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?f(t):this.authClient.request(t)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}}export{p as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(t){super(t)}}export{o as default};
@@ -1 +1 @@
1
- import{Readable as D}from"node:stream";import{drive as C}from"@googleapis/drive";import{JWT as g,GoogleAuth as T,OAuth2Client as b}from"google-auth-library";import{throwErrorCode as u,ERRORS as p,wrapStorageError as E}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-0j5nCAUp.js";import m from"./GoogleDriveFile-DHpLhzg9.js";import F from"./GoogleDriveMetaStorage-Cbwa1CHV.js";import{t as I}from"./get-file-status-y3wTtDQs.js";import{t as _}from"./update-size-DuNuLyxj.js";import{i as L}from"./part-match-D-9dGX42.js";import{e as G}from"./has-content-50BsqrWw.js";const f="https://www.googleapis.com/auth/drive",A=1024,h="fsdkKey",y="fsdkContentType",O="id, name, size, mimeType, md5Checksum, modifiedTime, appProperties",v=r=>{const e=r.lastIndexOf("/");return e===-1?r:r.slice(e+1)},w=r=>r.replaceAll("\\","\\\\").replaceAll("'",String.raw`\'`);class R{#t;#e=new Map;constructor(e){this.#t=Math.max(1,e)}delete(e){this.#e.delete(e)}get(e){const i=this.#e.get(e);if(i!==void 0)return this.#e.delete(e),this.#e.set(e,i),i}set(e,i){if(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,i),this.#e.size>this.#t){const t=this.#e.keys().next().value;t!==void 0&&this.#e.delete(t)}}}const P=r=>{const e=r.subject??process.env.GOOGLE_DRIVE_SUBJECT;if(r.credentials)return new g({email:r.credentials.client_email,key:r.credentials.private_key,scopes:[f],...e&&{subject:e}});if(r.keyFilename)return new T({keyFile:r.keyFilename,scopes:[f],...e&&{clientOptions:{subject:e}}});if(r.oauth){const s=new b({clientId:r.oauth.clientId,clientSecret:r.oauth.clientSecret});return s.setCredentials({refresh_token:r.oauth.refreshToken}),s}const i=process.env.GOOGLE_DRIVE_CLIENT_EMAIL,t=process.env.GOOGLE_DRIVE_PRIVATE_KEY;if(i&&t)return new g({email:i,key:t,scopes:[f],...e&&{subject:e}});const o=process.env.GOOGLE_DRIVE_KEY_FILE;if(o)return new T({keyFile:o,scopes:[f],...e&&{clientOptions:{subject:e}}})},B=async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},U=r=>{if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(Buffer.isBuffer(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof r=="string")return new TextEncoder().encode(r);throw new Error("Google Drive: unexpected response payload shape")};class H extends k{static name="google-drive";checksumTypes=[];meta;authForTokens;driveClient;fileIdCache;publicByDefault;rootFolderId;sharedDriveParams;constructor(e){if(super(e),e.client)this.driveClient=e.client,this.authForTokens=void 0;else{const t=P(e);if(!t)throw new Error("Google Drive storage: missing auth. Pass `client`, `credentials`, `keyFilename`, or `oauth`. Env fallbacks: GOOGLE_DRIVE_CLIENT_EMAIL + GOOGLE_DRIVE_PRIVATE_KEY, or GOOGLE_DRIVE_KEY_FILE.");this.authForTokens=t,this.driveClient=C({auth:t,version:"v3"})}const i=e.driveId??process.env.GOOGLE_DRIVE_ID;this.rootFolderId=e.rootFolderId??process.env.GOOGLE_DRIVE_ROOT_FOLDER_ID??i??"root",this.publicByDefault=e.publicByDefault??!1,this.fileIdCache=new R(e.fileIdCacheSize??A),this.sharedDriveParams={includeItemsFromAllDrives:!0,supportsAllDrives:!0,...i&&{corpora:"drive",driveId:i}},this.meta=e.metaStorage??new F(e.metaStorageConfig),this.isReady=!0}get raw(){return this.driveClient}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new m(e);t.name=this.namingFunction(t),await this.validate(t);try{const o=await this.getMeta(t.id);if(o.bytesWritten>=0)return o}catch{}return t.bytesWritten=0,t.status=I(t),await this.saveMeta(t),await this.onCreate(t),t})}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&&_(t,e.size),!L(e,t))throw new Error("File part does not match");const o=await this.lock(e.id);try{if(G(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const s=await B(e.body),n=t.name||t.id,a={[y]:t.contentType,[h]:n},l=await this.runOperation(i,()=>this.driveClient.files.create({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum, modifiedTime",media:{body:D.from(s),mimeType:t.contentType},requestBody:{appProperties:a,mimeType:t.contentType,name:v(n),parents:[this.rootFolderId]}})),{data:d}=l,c=d.id??void 0;c&&(this.fileIdCache.set(n,c),this.publicByDefault&&await this.runOperation(i,()=>this.driveClient.permissions.create({...this.sharedDriveParams,fileId:c,requestBody:{role:"reader",type:"anyone"}}))),t.bytesWritten=s.length,t.size=s.length,t.driveFileId=c,t.mimeType=d.mimeType??t.contentType,t.ETag=d.md5Checksum??void 0}return t.status=I(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,o)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;const o=e;try{t=await this.getMeta(e)}catch{}try{const s=t?.driveFileId??await this.resolveFileId(o,i);await this.runOperation(i,()=>this.driveClient.files.delete({...this.sharedDriveParams,fileId:s})),this.fileIdCache.delete(o)}catch(s){if(!z(s))throw s;this.fileIdCache.delete(o)}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new m({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,status:"deleted"})})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,o;try{t=await this.checkIfExpired(await this.getMeta(e)),o=t.driveFileId??await this.resolveFileId(t.name??e,i)}catch{o=await this.resolveFileId(e,i)}const[s,n]=await Promise.all([this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,fields:O,fileId:o})),this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,alt:"media",fileId:o},{responseType:"arraybuffer"}))]),{data:a}=s,l=U(n.data),d=Buffer.from(l.buffer,l.byteOffset,l.byteLength),c=a.appProperties??{};return{content:d,contentType:t?.contentType??c[y]??a.mimeType??"application/octet-stream",ETag:t?.ETag??a.md5Checksum??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??a.modifiedTime??void 0,name:t?.name??a.name??e,originalName:t?.originalName??a.name??e,size:t?.size??Number(a.size??d.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const o=await this.resolveFileId(e,t),s=await this.runOperation(t,()=>this.driveClient.files.copy({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum",fileId:o,requestBody:{appProperties:{[h]:i},name:v(i),parents:[this.rootFolderId]}})),n=s.data.id??void 0;n&&this.fileIdCache.set(i,n);const a=new m({contentType:s.data.mimeType??"application/octet-stream",metadata:{},originalName:i});return a.id=i,a.name=i,a.driveFileId=n,a.mimeType=s.data.mimeType??void 0,a.ETag=s.data.md5Checksum??void 0,a.size=Number(s.data.size??0),a})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const o=await this.copy(e,i,t);return await this.delete({id:e},t),o})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{const t=`'${w(this.rootFolderId)}' in parents and trashed=false`,o=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:`nextPageToken, files(${O})`,pageSize:e,q:t}))).data.files??[],s=[];for(const n of o){const a=n.appProperties??{},l=a[h];if(!l)continue;n.id&&this.fileIdCache.set(l,n.id);const d=new m({contentType:a[y]??n.mimeType??"application/octet-stream",metadata:{},originalName:n.name??l});d.id=l,d.name=l,d.driveFileId=n.id??void 0,d.mimeType=n.mimeType??void 0,d.size=Number(n.size??0),d.modifiedAt=n.modifiedTime??void 0,d.ETag=n.md5Checksum??void 0,s.push(d)}return s},{limit:e})}async getReadUrl(e,i){return i?.responseContentDisposition!==void 0||i?.responseContentType!==void 0?u(p.METHOD_NOT_ALLOWED,"Google Drive: `responseContentDisposition`/`responseContentType` are not supported — Drive's webContentLink has no Content-Disposition/Content-Type override."):this.publicByDefault?`https://drive.google.com/uc?export=download&id=${await this.resolveFileId(e)}`:u(p.METHOD_NOT_ALLOWED,"Google Drive: getReadUrl() requires the adapter to be constructed with `publicByDefault: true`. Drive has no signed URL primitive — use get() for private files.")}async getUploadUrl(e,i){if(i?.contentLength!==void 0)return u(p.BAD_REQUEST,"Google Drive: `contentLength` is not supported for upload URLs. A Drive resumable upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");if(!this.authForTokens)return u(p.METHOD_NOT_ALLOWED,"Google Drive: getUploadUrl() requires `credentials`, `keyFilename`, or `oauth` — not the pre-built `client` escape hatch.");const t=await this.authForTokens.getAccessToken(),o=typeof t=="string"?t:t?.token;if(!o)throw new Error("Google Drive: failed to mint access token for resumable upload session");const s={Authorization:`Bearer ${o}`,"Content-Type":"application/json; charset=UTF-8"};i?.contentType&&(s["X-Upload-Content-Type"]=i.contentType);const n={appProperties:{[h]:e},name:v(e),parents:[this.rootFolderId]},a=await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",{body:JSON.stringify(n),headers:s,method:"POST"});if(!a.ok){const d=await a.text().catch(()=>"");throw E(new Error(`${a.statusText} ${d}`.trim()||a.statusText),{adapter:"Google Drive",operation:"resumable upload session",status:a.status})}const l=a.headers.get("location")??a.headers.get("Location");if(!l)throw E(new Error("response missing Location header"),{adapter:"Google Drive",code:p.STORAGE_ERROR,operation:"resumable upload session"});return l}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const o=`appProperties has { key='${h}' and value='${w(e)}' } and '${w(this.rootFolderId)}' in parents and trashed=false`,s=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:"files(id)",pageSize:2,q:o}))).data.files??[];if(s.length===0)throw new Error(`Google Drive: not found: ${e}`);if(s.length>1)throw new Error(`Google Drive: multiple files share virtual key '${e}'. Resolve via storage.raw.`);const n=s[0]?.id;if(!n)throw new Error(`Google Drive: list returned no fileId for ${e}`);return this.fileIdCache.set(e,n),n}internalOnComplete=e=>this.deleteMeta(e.id)}const z=r=>{if(r===null||typeof r!="object")return!1;const e=r;return typeof e.code=="number"&&e.code===404||typeof e.status=="number"&&e.status===404?!0:typeof e.response?.status=="number"&&e.response.status===404};export{H as default};
1
+ import{Readable as D}from"node:stream";import{drive as C}from"@googleapis/drive";import{JWT as g,GoogleAuth as T,OAuth2Client as b}from"google-auth-library";import{throwErrorCode as u,ERRORS as p,wrapStorageError as E}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-0j5nCAUp.js";import m from"./GoogleDriveFile-DHpLhzg9.js";import F from"./GoogleDriveMetaStorage-xlHfKwmR.js";import{t as I}from"./get-file-status-y3wTtDQs.js";import{t as _}from"./update-size-DuNuLyxj.js";import{i as L}from"./part-match-D-9dGX42.js";import{e as G}from"./has-content-50BsqrWw.js";const f="https://www.googleapis.com/auth/drive",A=1024,h="fsdkKey",y="fsdkContentType",O="id, name, size, mimeType, md5Checksum, modifiedTime, appProperties",v=r=>{const e=r.lastIndexOf("/");return e===-1?r:r.slice(e+1)},w=r=>r.replaceAll("\\","\\\\").replaceAll("'",String.raw`\'`);class R{#t;#e=new Map;constructor(e){this.#t=Math.max(1,e)}delete(e){this.#e.delete(e)}get(e){const i=this.#e.get(e);if(i!==void 0)return this.#e.delete(e),this.#e.set(e,i),i}set(e,i){if(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,i),this.#e.size>this.#t){const t=this.#e.keys().next().value;t!==void 0&&this.#e.delete(t)}}}const P=r=>{const e=r.subject??process.env.GOOGLE_DRIVE_SUBJECT;if(r.credentials)return new g({email:r.credentials.client_email,key:r.credentials.private_key,scopes:[f],...e&&{subject:e}});if(r.keyFilename)return new T({keyFile:r.keyFilename,scopes:[f],...e&&{clientOptions:{subject:e}}});if(r.oauth){const s=new b({clientId:r.oauth.clientId,clientSecret:r.oauth.clientSecret});return s.setCredentials({refresh_token:r.oauth.refreshToken}),s}const i=process.env.GOOGLE_DRIVE_CLIENT_EMAIL,t=process.env.GOOGLE_DRIVE_PRIVATE_KEY;if(i&&t)return new g({email:i,key:t,scopes:[f],...e&&{subject:e}});const o=process.env.GOOGLE_DRIVE_KEY_FILE;if(o)return new T({keyFile:o,scopes:[f],...e&&{clientOptions:{subject:e}}})},B=async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},U=r=>{if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(Buffer.isBuffer(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof r=="string")return new TextEncoder().encode(r);throw new Error("Google Drive: unexpected response payload shape")};class H extends k{static name="google-drive";checksumTypes=[];meta;authForTokens;driveClient;fileIdCache;publicByDefault;rootFolderId;sharedDriveParams;constructor(e){if(super(e),e.client)this.driveClient=e.client,this.authForTokens=void 0;else{const t=P(e);if(!t)throw new Error("Google Drive storage: missing auth. Pass `client`, `credentials`, `keyFilename`, or `oauth`. Env fallbacks: GOOGLE_DRIVE_CLIENT_EMAIL + GOOGLE_DRIVE_PRIVATE_KEY, or GOOGLE_DRIVE_KEY_FILE.");this.authForTokens=t,this.driveClient=C({auth:t,version:"v3"})}const i=e.driveId??process.env.GOOGLE_DRIVE_ID;this.rootFolderId=e.rootFolderId??process.env.GOOGLE_DRIVE_ROOT_FOLDER_ID??i??"root",this.publicByDefault=e.publicByDefault??!1,this.fileIdCache=new R(e.fileIdCacheSize??A),this.sharedDriveParams={includeItemsFromAllDrives:!0,supportsAllDrives:!0,...i&&{corpora:"drive",driveId:i}},this.meta=e.metaStorage??new F(e.metaStorageConfig),this.isReady=!0}get raw(){return this.driveClient}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new m(e);t.name=this.namingFunction(t),await this.validate(t);try{const o=await this.getMeta(t.id);if(o.bytesWritten>=0)return o}catch{}return t.bytesWritten=0,t.status=I(t),await this.saveMeta(t),await this.onCreate(t),t})}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&&_(t,e.size),!L(e,t))throw new Error("File part does not match");const o=await this.lock(e.id);try{if(G(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const s=await B(e.body),n=t.name||t.id,a={[y]:t.contentType,[h]:n},l=await this.runOperation(i,()=>this.driveClient.files.create({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum, modifiedTime",media:{body:D.from(s),mimeType:t.contentType},requestBody:{appProperties:a,mimeType:t.contentType,name:v(n),parents:[this.rootFolderId]}})),{data:d}=l,c=d.id??void 0;c&&(this.fileIdCache.set(n,c),this.publicByDefault&&await this.runOperation(i,()=>this.driveClient.permissions.create({...this.sharedDriveParams,fileId:c,requestBody:{role:"reader",type:"anyone"}}))),t.bytesWritten=s.length,t.size=s.length,t.driveFileId=c,t.mimeType=d.mimeType??t.contentType,t.ETag=d.md5Checksum??void 0}return t.status=I(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,o)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;const o=e;try{t=await this.getMeta(e)}catch{}try{const s=t?.driveFileId??await this.resolveFileId(o,i);await this.runOperation(i,()=>this.driveClient.files.delete({...this.sharedDriveParams,fileId:s})),this.fileIdCache.delete(o)}catch(s){if(!z(s))throw s;this.fileIdCache.delete(o)}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new m({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,status:"deleted"})})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,o;try{t=await this.checkIfExpired(await this.getMeta(e)),o=t.driveFileId??await this.resolveFileId(t.name??e,i)}catch{o=await this.resolveFileId(e,i)}const[s,n]=await Promise.all([this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,fields:O,fileId:o})),this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,alt:"media",fileId:o},{responseType:"arraybuffer"}))]),{data:a}=s,l=U(n.data),d=Buffer.from(l.buffer,l.byteOffset,l.byteLength),c=a.appProperties??{};return{content:d,contentType:t?.contentType??c[y]??a.mimeType??"application/octet-stream",ETag:t?.ETag??a.md5Checksum??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??a.modifiedTime??void 0,name:t?.name??a.name??e,originalName:t?.originalName??a.name??e,size:t?.size??Number(a.size??d.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const o=await this.resolveFileId(e,t),s=await this.runOperation(t,()=>this.driveClient.files.copy({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum",fileId:o,requestBody:{appProperties:{[h]:i},name:v(i),parents:[this.rootFolderId]}})),n=s.data.id??void 0;n&&this.fileIdCache.set(i,n);const a=new m({contentType:s.data.mimeType??"application/octet-stream",metadata:{},originalName:i});return a.id=i,a.name=i,a.driveFileId=n,a.mimeType=s.data.mimeType??void 0,a.ETag=s.data.md5Checksum??void 0,a.size=Number(s.data.size??0),a})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const o=await this.copy(e,i,t);return await this.delete({id:e},t),o})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{const t=`'${w(this.rootFolderId)}' in parents and trashed=false`,o=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:`nextPageToken, files(${O})`,pageSize:e,q:t}))).data.files??[],s=[];for(const n of o){const a=n.appProperties??{},l=a[h];if(!l)continue;n.id&&this.fileIdCache.set(l,n.id);const d=new m({contentType:a[y]??n.mimeType??"application/octet-stream",metadata:{},originalName:n.name??l});d.id=l,d.name=l,d.driveFileId=n.id??void 0,d.mimeType=n.mimeType??void 0,d.size=Number(n.size??0),d.modifiedAt=n.modifiedTime??void 0,d.ETag=n.md5Checksum??void 0,s.push(d)}return s},{limit:e})}async getReadUrl(e,i){return i?.responseContentDisposition!==void 0||i?.responseContentType!==void 0?u(p.METHOD_NOT_ALLOWED,"Google Drive: `responseContentDisposition`/`responseContentType` are not supported — Drive's webContentLink has no Content-Disposition/Content-Type override."):this.publicByDefault?`https://drive.google.com/uc?export=download&id=${await this.resolveFileId(e)}`:u(p.METHOD_NOT_ALLOWED,"Google Drive: getReadUrl() requires the adapter to be constructed with `publicByDefault: true`. Drive has no signed URL primitive — use get() for private files.")}async getUploadUrl(e,i){if(i?.contentLength!==void 0)return u(p.BAD_REQUEST,"Google Drive: `contentLength` is not supported for upload URLs. A Drive resumable upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");if(!this.authForTokens)return u(p.METHOD_NOT_ALLOWED,"Google Drive: getUploadUrl() requires `credentials`, `keyFilename`, or `oauth` — not the pre-built `client` escape hatch.");const t=await this.authForTokens.getAccessToken(),o=typeof t=="string"?t:t?.token;if(!o)throw new Error("Google Drive: failed to mint access token for resumable upload session");const s={Authorization:`Bearer ${o}`,"Content-Type":"application/json; charset=UTF-8"};i?.contentType&&(s["X-Upload-Content-Type"]=i.contentType);const n={appProperties:{[h]:e},name:v(e),parents:[this.rootFolderId]},a=await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",{body:JSON.stringify(n),headers:s,method:"POST"});if(!a.ok){const d=await a.text().catch(()=>"");throw E(new Error(`${a.statusText} ${d}`.trim()||a.statusText),{adapter:"Google Drive",operation:"resumable upload session",status:a.status})}const l=a.headers.get("location")??a.headers.get("Location");if(!l)throw E(new Error("response missing Location header"),{adapter:"Google Drive",code:p.STORAGE_ERROR,operation:"resumable upload session"});return l}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const o=`appProperties has { key='${h}' and value='${w(e)}' } and '${w(this.rootFolderId)}' in parents and trashed=false`,s=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:"files(id)",pageSize:2,q:o}))).data.files??[];if(s.length===0)throw new Error(`Google Drive: not found: ${e}`);if(s.length>1)throw new Error(`Google Drive: multiple files share virtual key '${e}'. Resolve via storage.raw.`);const n=s[0]?.id;if(!n)throw new Error(`Google Drive: list returned no fileId for ${e}`);return this.fileIdCache.set(e,n),n}internalOnComplete=e=>this.deleteMeta(e.id)}const z=r=>{if(r===null||typeof r!="object")return!1;const e=r;return typeof e.code=="number"&&e.code===404||typeof e.status=="number"&&e.status===404?!0:typeof e.response?.status=="number"&&e.response.status===404};export{H as default};
@@ -1 +1 @@
1
- import"node:fs/promises";import"node:os";import{y as f}from"./local-meta-storage-iuJnu90B.js";import"./path-0oTTdkvl-DvWvbDbh.js";import"./ERRORS-BIBxE2oR.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-B7CcBueg.js";export{f as default};
1
+ import"node:fs/promises";import"node:os";import{y as f}from"./local-meta-storage-DJDcuxf1.js";import"./path-0oTTdkvl-DvWvbDbh.js";import"./ERRORS-BIBxE2oR.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-B7CcBueg.js";export{f as default};
@@ -0,0 +1 @@
1
+ import{y as s}from"./local-meta-storage-DJDcuxf1.js";class o extends s{constructor(r){super(r)}}export{o as default};
@@ -1 +1 @@
1
- import{getStore as u}from"@netlify/blobs";import{a as p}from"./detect-file-type-BA7UBLKA.js";import{B as y,c as h,e as d}from"./storage-0j5nCAUp.js";import{y as w}from"./local-meta-storage-iuJnu90B.js";import f from"./NetlifyBlobFile-DoFhkzaH.js";import{t as m}from"./get-file-status-y3wTtDQs.js";import{t as g}from"./update-size-DuNuLyxj.js";import{i as b}from"./part-match-D-9dGX42.js";import{e as O}from"./has-content-50BsqrWw.js";class C extends y{static name="netlify-blob";checksumTypes=["md5"];get raw(){return this.store}meta;storeName;siteID;token;store;resolvedRetryConfig;constructor(e){super(e),this.storeName=e.storeName||"default",this.siteID=e.siteID||process.env.NETLIFY_SITE_ID,this.token=e.token||process.env.NETLIFY_TOKEN,this.store=u({name:this.storeName,...this.siteID&&{siteID:this.siteID},...this.token&&{token:this.token}});const n={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:r=>{if(r instanceof Error){const i=r.code;if(i==="ECONNRESET"||i==="ETIMEDOUT"||i==="ENOTFOUND"||i==="ECONNREFUSED")return!0}const s=r;return!!(s.status&&[408,429,500,502,503,504].includes(s.status))},...e.retryConfig};this.resolvedRetryConfig=n;const{metaStorage:t,metaStorageConfig:a}=e;this.meta=t||new w(a),this.isReady=!0}getRetryConfig(){return this.resolvedRetryConfig}async create(e,n){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const r=typeof e.ttl=="string"?h(e.ttl):e.ttl;t.expiredAt=r===void 0?void 0:Date.now()+r}const a=new f(t);a.name=this.namingFunction(a),await this.validate(a);try{const r=await this.getMeta(a.id);if(r.bytesWritten>=0)return r}catch{}return a.bytesWritten=0,a.status=m(a),await this.saveMeta(a),await this.onCreate(a),a})}async write(e,n){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&&g(t,e.size),!b(e,t))throw new Error("File part does not match");const a=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=[],s=e.body;for await(const o of s)r.push(Buffer.from(o));const i=Buffer.concat(r);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await p(i);o?.mime&&(t.contentType=o.mime)}catch{}await this.runOperation(n,()=>this.store.set(t.name,i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),{metadata:{...t.metadata,contentType:t.contentType}})),t.pathname=t.name,t.url=this.getBlobUrl(t.name),t.bytesWritten=i.length}return t.status=m(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,a)}})}async delete({id:e},n){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.pathname)throw new Error(`File ${e} does not have a valid pathname`);t.status="deleted";try{await this.runOperation(n,()=>this.store.delete(t.pathname))}catch(r){this.logger?.error("Failed to delete blob from Netlify Blob:",r);const s=this.normalizeError(r instanceof Error?r:new Error(String(r)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},n){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);return!t.pathname||t.pathname.length<=0?!1:await this.runOperation(n,()=>this.store.get(t.pathname,{type:"blob"}))!=null}catch{return!1}})}async get({id:e},n){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.pathname||t.pathname.length<=0)throw new Error("File pathname not found");const a=await this.runOperation(n,()=>this.store.get(t.pathname,{type:"blob"}));if(!a)throw new Error("File not found in Netlify Blob");let r;if(typeof a=="string")r=Buffer.from(a,"utf8").buffer;else if(a&&typeof a=="object"&&"arrayBuffer"in a&&typeof a.arrayBuffer=="function")r=await this.runOperation(n,()=>a.arrayBuffer());else throw new Error("Invalid blob type returned from Netlify Blob");const s=Buffer.from(r);let i=null;try{i=await this.store.getMetadata?.(t.pathname)??null}catch{}return{content:s,contentType:i?.contentType||t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:{...t.metadata,...i?.metadata},modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||s.length}})}async copy(e,n,t){return this.instrumentOperation("copy",async()=>{const a=await this.getMeta(e);if(!a.pathname)throw new Error("Source file pathname not found");const r=await this.runOperation(t,()=>this.store.get(a.pathname,{type:"blob"}));if(!r)throw new Error("Source file not found in Netlify Blob");let s=null;try{const l=this.store;l.getMetadata&&a.pathname&&(s=await l.getMetadata(a.pathname))}catch{}let i;if(typeof r=="string")i=Buffer.from(r,"utf8").buffer;else if(r&&typeof r=="object"&&"arrayBuffer"in r){const l=r;i=await this.runOperation(t,()=>l.arrayBuffer())}else throw new Error("Invalid blob type returned from Netlify Blob");const o=Buffer.from(i);await this.runOperation(t,()=>this.store.set(n,o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength),{metadata:s||{contentType:a.contentType,...a.metadata}}));const c={...a,id:n,name:n,pathname:n,url:this.getBlobUrl(n)};return await this.saveMeta(c),c})}async move(e,n,t){return this.instrumentOperation("move",async()=>{const a=await this.copy(e,n,t);return await this.delete({id:e},t),a})}async update({id:e},n,t){return this.instrumentOperation("update",async()=>{const a=await this.getMeta(e),r={...n};if("ttl"in r&&r.ttl!==void 0){const i=r.ttl,o=typeof i=="string"?h(i):i;o!==void 0&&(r.expiredAt=Date.now()+o),delete r.ttl}d(a,r),await this.saveMeta(a);const s={...a,status:"updated"};return await this.onUpdate(s),s})}async list(e=1e3,n){return this.instrumentOperation("list",async()=>{const t=await this.runOperation(n,()=>this.store.list()),a=[];for await(const r of t.blobs){let s=null;try{s=await this.store.getMetadata?.(r.key)??null}catch{}const i=new f({contentType:s?.contentType||"application/octet-stream",metadata:s?.metadata||{},originalName:r.key}),o=r;if(i.createdAt=o.createdAt?.toISOString(),i.id=r.key,i.modifiedAt=o.updatedAt?.toISOString(),i.name=r.key,i.pathname=r.key,i.size=o.size,i.url=this.getBlobUrl(r.key),a.push(i),a.length>=e)break}return a},{limit:e})}internalOnComplete=e=>this.deleteMeta(e.id);getBlobUrl(e){return`/api/blobs/${this.storeName}/${e}`}}export{C as default};
1
+ import{getStore as u}from"@netlify/blobs";import{a as p}from"./detect-file-type-BA7UBLKA.js";import{B as y,c as h,e as d}from"./storage-0j5nCAUp.js";import{y as w}from"./local-meta-storage-DJDcuxf1.js";import f from"./NetlifyBlobFile-DoFhkzaH.js";import{t as m}from"./get-file-status-y3wTtDQs.js";import{t as g}from"./update-size-DuNuLyxj.js";import{i as b}from"./part-match-D-9dGX42.js";import{e as O}from"./has-content-50BsqrWw.js";class C extends y{static name="netlify-blob";checksumTypes=["md5"];get raw(){return this.store}meta;storeName;siteID;token;store;resolvedRetryConfig;constructor(e){super(e),this.storeName=e.storeName||"default",this.siteID=e.siteID||process.env.NETLIFY_SITE_ID,this.token=e.token||process.env.NETLIFY_TOKEN,this.store=u({name:this.storeName,...this.siteID&&{siteID:this.siteID},...this.token&&{token:this.token}});const n={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:r=>{if(r instanceof Error){const i=r.code;if(i==="ECONNRESET"||i==="ETIMEDOUT"||i==="ENOTFOUND"||i==="ECONNREFUSED")return!0}const s=r;return!!(s.status&&[408,429,500,502,503,504].includes(s.status))},...e.retryConfig};this.resolvedRetryConfig=n;const{metaStorage:t,metaStorageConfig:a}=e;this.meta=t||new w(a),this.isReady=!0}getRetryConfig(){return this.resolvedRetryConfig}async create(e,n){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const r=typeof e.ttl=="string"?h(e.ttl):e.ttl;t.expiredAt=r===void 0?void 0:Date.now()+r}const a=new f(t);a.name=this.namingFunction(a),await this.validate(a);try{const r=await this.getMeta(a.id);if(r.bytesWritten>=0)return r}catch{}return a.bytesWritten=0,a.status=m(a),await this.saveMeta(a),await this.onCreate(a),a})}async write(e,n){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&&g(t,e.size),!b(e,t))throw new Error("File part does not match");const a=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=[],s=e.body;for await(const o of s)r.push(Buffer.from(o));const i=Buffer.concat(r);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await p(i);o?.mime&&(t.contentType=o.mime)}catch{}await this.runOperation(n,()=>this.store.set(t.name,i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),{metadata:{...t.metadata,contentType:t.contentType}})),t.pathname=t.name,t.url=this.getBlobUrl(t.name),t.bytesWritten=i.length}return t.status=m(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,a)}})}async delete({id:e},n){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.pathname)throw new Error(`File ${e} does not have a valid pathname`);t.status="deleted";try{await this.runOperation(n,()=>this.store.delete(t.pathname))}catch(r){this.logger?.error("Failed to delete blob from Netlify Blob:",r);const s=this.normalizeError(r instanceof Error?r:new Error(String(r)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},n){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);return!t.pathname||t.pathname.length<=0?!1:await this.runOperation(n,()=>this.store.get(t.pathname,{type:"blob"}))!=null}catch{return!1}})}async get({id:e},n){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.pathname||t.pathname.length<=0)throw new Error("File pathname not found");const a=await this.runOperation(n,()=>this.store.get(t.pathname,{type:"blob"}));if(!a)throw new Error("File not found in Netlify Blob");let r;if(typeof a=="string")r=Buffer.from(a,"utf8").buffer;else if(a&&typeof a=="object"&&"arrayBuffer"in a&&typeof a.arrayBuffer=="function")r=await this.runOperation(n,()=>a.arrayBuffer());else throw new Error("Invalid blob type returned from Netlify Blob");const s=Buffer.from(r);let i=null;try{i=await this.store.getMetadata?.(t.pathname)??null}catch{}return{content:s,contentType:i?.contentType||t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:{...t.metadata,...i?.metadata},modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||s.length}})}async copy(e,n,t){return this.instrumentOperation("copy",async()=>{const a=await this.getMeta(e);if(!a.pathname)throw new Error("Source file pathname not found");const r=await this.runOperation(t,()=>this.store.get(a.pathname,{type:"blob"}));if(!r)throw new Error("Source file not found in Netlify Blob");let s=null;try{const l=this.store;l.getMetadata&&a.pathname&&(s=await l.getMetadata(a.pathname))}catch{}let i;if(typeof r=="string")i=Buffer.from(r,"utf8").buffer;else if(r&&typeof r=="object"&&"arrayBuffer"in r){const l=r;i=await this.runOperation(t,()=>l.arrayBuffer())}else throw new Error("Invalid blob type returned from Netlify Blob");const o=Buffer.from(i);await this.runOperation(t,()=>this.store.set(n,o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength),{metadata:s||{contentType:a.contentType,...a.metadata}}));const c={...a,id:n,name:n,pathname:n,url:this.getBlobUrl(n)};return await this.saveMeta(c),c})}async move(e,n,t){return this.instrumentOperation("move",async()=>{const a=await this.copy(e,n,t);return await this.delete({id:e},t),a})}async update({id:e},n,t){return this.instrumentOperation("update",async()=>{const a=await this.getMeta(e),r={...n};if("ttl"in r&&r.ttl!==void 0){const i=r.ttl,o=typeof i=="string"?h(i):i;o!==void 0&&(r.expiredAt=Date.now()+o),delete r.ttl}d(a,r),await this.saveMeta(a);const s={...a,status:"updated"};return await this.onUpdate(s),s})}async list(e=1e3,n){return this.instrumentOperation("list",async()=>{const t=await this.runOperation(n,()=>this.store.list()),a=[];for await(const r of t.blobs){let s=null;try{s=await this.store.getMetadata?.(r.key)??null}catch{}const i=new f({contentType:s?.contentType||"application/octet-stream",metadata:s?.metadata||{},originalName:r.key}),o=r;if(i.createdAt=o.createdAt?.toISOString(),i.id=r.key,i.modifiedAt=o.updatedAt?.toISOString(),i.name=r.key,i.pathname=r.key,i.size=o.size,i.url=this.getBlobUrl(r.key),a.push(i),a.length>=e)break}return a},{limit:e})}internalOnComplete=e=>this.deleteMeta(e.id);getBlobUrl(e){return`/api/blobs/${this.storeName}/${e}`}}export{C as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(t){super(t)}}export{o as default};
@@ -1 +1 @@
1
- import{ResponseType as g,Client as U,GraphError as b}from"@microsoft/microsoft-graph-client";import{wrapStorageError as p,ERRORS as m,throwErrorCode as E}from"./ERRORS-BIBxE2oR.js";import{c as D}from"./oauth-refresh-EdGzlcOZ.js";import{B as _}from"./storage-0j5nCAUp.js";import u from"./OneDriveFile-CNNJYI43.js";import A from"./OneDriveMetaStorage-Cbwa1CHV.js";import{t as T}from"./get-file-status-y3wTtDQs.js";import{t as N}from"./update-size-DuNuLyxj.js";import{i as S}from"./part-match-D-9dGX42.js";import{e as L}from"./has-content-50BsqrWw.js";const P="https://graph.microsoft.com/.default",M=250*1024*1024,F=16*320*1024,B=1e3,d=o=>{let t=0,i=o.length;for(;t<i&&o[t]==="/";)t+=1;for(;i>t&&o[i-1]==="/";)i-=1;return t===0&&i===o.length?o:o.slice(t,i)},w=(o,t)=>{if(d(o).split("/").filter(Boolean).some(i=>i==="."||i===".."))throw new Error(`OneDrive storage: ${t} must not contain "." or ".." path segments.`)},y=o=>o.split("/").map(t=>encodeURIComponent(t)).join("/"),x=async o=>{const t=[];for await(const i of o)t.push(Buffer.from(i));return Buffer.concat(t)},I=o=>({getAccessToken:()=>Promise.resolve(o)}),$=o=>({getAccessToken:async()=>o()}),O=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,client_secret:o.clientSecret,grant_type:"client_credentials",scope:P}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId)}/oauth2/v2.0/token`}),v=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,grant_type:"refresh_token",refresh_token:o.refreshToken,scope:P,...o.clientSecret&&{client_secret:o.clientSecret}}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId??"common")}/oauth2/v2.0/token`}),V=o=>({getAccessToken:()=>o.getAccessToken()}),C=o=>{if(o.client)return o.client;const t=o.accessToken!==void 0,i=o.clientCredentials!==void 0,e=o.oauth!==void 0;if([t,i,e].filter(Boolean).length>1)throw new Error("OneDrive storage: pass exactly one of `accessToken`, `clientCredentials`, or `oauth`.");let n;if(o.accessToken!==void 0?n=typeof o.accessToken=="function"?$(o.accessToken):I(o.accessToken):o.clientCredentials?n=O(o.clientCredentials):o.oauth&&(n=v({clientId:o.oauth.clientId,refreshToken:o.oauth.refreshToken,...o.oauth.clientSecret&&{clientSecret:o.oauth.clientSecret},...o.oauth.tenantId&&{tenantId:o.oauth.tenantId}})),!n){const a=process.env.ONEDRIVE_ACCESS_TOKEN;if(a)n=I(a);else{const r=process.env.ONEDRIVE_CLIENT_ID,s=process.env.ONEDRIVE_CLIENT_SECRET,c=process.env.ONEDRIVE_TENANT_ID,h=process.env.ONEDRIVE_REFRESH_TOKEN;h&&r?n=v({clientId:r,refreshToken:h,...s&&{clientSecret:s},...c&&{tenantId:c}}):r&&s&&c&&(n=O({clientId:r,clientSecret:s,tenantId:c}))}}if(!n)throw new Error("OneDrive storage: missing auth. Pass `client`, `accessToken`, `clientCredentials`, or `oauth`. Env fallbacks: ONEDRIVE_ACCESS_TOKEN; or ONEDRIVE_REFRESH_TOKEN + ONEDRIVE_CLIENT_ID (+ optional ONEDRIVE_CLIENT_SECRET, ONEDRIVE_TENANT_ID); or ONEDRIVE_CLIENT_ID + ONEDRIVE_CLIENT_SECRET + ONEDRIVE_TENANT_ID.");return U.initWithMiddleware({authProvider:V(n)})},z=o=>{if(o instanceof b)return o.statusCode===404||o.code==="itemNotFound";if(o&&typeof o=="object"){const t=o;return t.statusCode===404||t.status===404||t.code==="itemNotFound"}return!1};class Z extends _{static name="onedrive";checksumTypes=[];meta;basePath;client;copyTimeoutMs;publicByDefault;rootFolderPath;constructor(t){if(super(t),[t.driveId,t.siteId,t.userId].filter(i=>i!==void 0).length>1)throw new Error("OneDrive storage: pass at most one of `driveId`, `siteId`, or `userId`.");if(t.driveId)this.basePath=`/drives/${encodeURIComponent(t.driveId)}`;else if(t.siteId)this.basePath=`/sites/${encodeURIComponent(t.siteId)}/drive`;else if(t.userId)this.basePath=`/users/${encodeURIComponent(t.userId)}/drive`;else{if(t.clientCredentials)throw new Error("OneDrive storage: `clientCredentials` (app-only) auth requires `driveId`, `siteId`, or `userId`.");this.basePath="/me/drive"}w(t.rootFolderPath??"","rootFolderPath"),this.rootFolderPath=d(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.copyTimeoutMs=t.copyTimeoutMs??6e4,this.client=C(t),this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,i){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),await this.validate(e);try{const n=await this.getMeta(e.id);if(n.bytesWritten>=0)return n}catch{}return e.bytesWritten=0,e.status=T(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,i){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&&N(e,t.size),!S(t,e))throw new Error("File part does not match");const n=await this.lock(t.id);try{if(L(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await x(t.body),r=e.name||e.id,s=a.byteLength<=M?await this.uploadSimple(r,a,e.contentType,i):await this.uploadSession(r,a,e.contentType,i);e.bytesWritten=a.length,e.size=a.length,e.driveItemId=s.id,e.webUrl=s.webUrl,e.eTag=s.eTag,e.ETag=s.eTag}return e.status=T(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,n)}})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const n=e?.name??t;try{await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).delete())}catch(a){if(!z(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,status:"deleted"})})}async get({id:t},i){return this.instrumentOperation("get",async()=>{let e,n=t;try{e=await this.checkIfExpired(await this.getMeta(t)),n=e.name??t}catch{}const a=await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).get()),r=await this.runOperation(i,()=>this.client.api(this.itemActionPath(n,"content")).responseType(g.ARRAYBUFFER).get()),s=Buffer.from(r);return{content:s,contentType:e?.contentType??a.file?.mimeType??"application/octet-stream",ETag:e?.ETag??a.eTag,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.lastModifiedDateTime,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??s.length}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const n=this.parentReferencePath(i),a={name:R(i),parentReference:{path:n}},r=await this.runOperation(e,()=>this.client.api(this.itemActionPath(t,"copy")).responseType(g.RAW).post(a));if(r.status!==202){const f=await r.text().catch(()=>"");throw p(new Error(f||r.statusText),{adapter:"OneDrive",operation:"copy",status:r.status})}const s=r.headers.get("Location");if(!s)throw p(new Error("response missing Location monitor URL"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});const c=await this.pollCopyMonitor(s,e),h=new u({contentType:"application/octet-stream",metadata:{},originalName:i});return h.id=i,h.name=i,h.driveItemId=c,h})}async move(t,i,e){return this.instrumentOperation("move",async()=>{const n=this.parentReferencePath(i),a=R(i),r=await this.runOperation(e,()=>this.client.api(this.itemApiPath(t)).patch({name:a,parentReference:{path:n}})),s=new u({contentType:"application/octet-stream",metadata:{},originalName:i});s.id=i,s.name=i,s.driveItemId=r.id,s.webUrl=r.webUrl,s.eTag=r.eTag,s.ETag=r.eTag;try{await this.deleteMeta(t)}catch{}return s})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const e=[];let n=`${this.folderListChildrenPath()}?$top=${Math.min(t,1e3)}`;for(;n&&e.length<t;){const a=await this.runOperation(i,()=>this.client.api(n).get());for(const r of a.value){if(!r.file)continue;const s=this.itemPathToKey(r);if(!s)continue;const c=new u({contentType:r.file.mimeType??"application/octet-stream",metadata:{},originalName:r.name});if(c.id=s,c.name=s,c.driveItemId=r.id,c.webUrl=r.webUrl,c.eTag=r.eTag,c.ETag=r.eTag,c.size=r.size??0,c.modifiedAt=r.lastModifiedDateTime,e.push(c),e.length>=t)break}n=a["@odata.nextLink"]??null}return e},{limit:t})}async getReadUrl(t,i){if(i?.responseContentDisposition||i?.responseContentType)return E(m.METHOD_NOT_ALLOWED,"OneDrive: `responseContentDisposition` / `responseContentType` are not supported — Graph download URLs have no overrides.");if(this.publicByDefault){const n=(await this.client.api(this.itemActionPath(t,"createLink")).post({scope:"anonymous",type:"view"})).link?.webUrl;if(!n)throw new Error("OneDrive: createLink response missing webUrl");return n}const e=(await this.client.api(this.itemApiPath(t)).select("@microsoft.graph.downloadUrl").get())["@microsoft.graph.downloadUrl"];if(!e)throw new Error("OneDrive: item has no `@microsoft.graph.downloadUrl` — it may be a folder or have no content.");return e}async getUploadUrl(t,i){if(i?.contentLength!==void 0)return E(m.BAD_REQUEST,"OneDrive: `contentLength` is not supported for upload URLs. A Graph upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");const e=await this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...i?.contentType&&{file:{mimeType:i.contentType}}}});if(!e.uploadUrl)throw p(new Error("createUploadSession response missing uploadUrl"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"getUploadUrl"});return e.uploadUrl}keyParts(t){w(t,"key");const i=d(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),i&&e.push(i),e}itemApiPath(t){const i=this.keyParts(t);return i.length===0?`${this.basePath}/root`:`${this.basePath}/root:/${y(i.join("/"))}`}itemActionPath(t,i){const e=this.keyParts(t);return e.length===0?`${this.basePath}/root/${i}`:`${this.basePath}/root:/${y(e.join("/"))}:/${i}`}folderListChildrenPath(){return this.itemActionPath("","children")}parentReferencePath(t){w(t,"key");const i=d(t),e=[];this.rootFolderPath&&e.push(this.rootFolderPath);const n=i.lastIndexOf("/");if(n!==-1){const a=i.slice(0,n);a&&e.push(a)}return e.length===0?"/drive/root:":`/drive/root:/${y(e.join("/"))}`}itemPathToKey(t){const i=t.parentReference?.path??"",e="/root:",n=i.indexOf(e);let a=n===-1?"":i.slice(n+e.length);a=d(decodeURIComponent(a));const r=this.rootFolderPath&&a.startsWith(this.rootFolderPath)?a.slice(this.rootFolderPath.length):a,s=d(r);return s?`${s}/${t.name}`:t.name}async uploadSimple(t,i,e,n){return await this.runOperation(n,()=>this.client.api(`${this.itemActionPath(t,"content")}?@microsoft.graph.conflictBehavior=replace`).header("Content-Type",e??"application/octet-stream").put(i))}async uploadSession(t,i,e,n){const a=await this.runOperation(n,()=>this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...e&&{file:{mimeType:e}}}})),r=i.byteLength;let s=0,c;for(;s<r;){const h=Math.min(s+F,r),f=i.subarray(s,h),l=await this.runOperation(n,()=>fetch(a.uploadUrl,{body:new Uint8Array(f),headers:{"Content-Length":String(f.byteLength),"Content-Range":`bytes ${s}-${h-1}/${r}`},method:"PUT"}));if(l.status===200||l.status===201)c=await l.json();else if(l.status!==202){const k=await l.text().catch(()=>"");throw p(new Error(k||l.statusText),{adapter:"OneDrive",operation:"upload-session chunk",status:l.status})}s=h}if(!c)throw p(new Error("upload-session terminated without a final DriveItem response"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"write"});return c}async pollCopyMonitor(t,i){const e=Date.now()+this.copyTimeoutMs;for(;;){const n=await this.runOperation(i,()=>fetch(t));if(!n.ok)throw p(new Error(n.statusText),{adapter:"OneDrive",operation:"copy monitor",status:n.status});const a=await n.json();if(a.status==="completed")return a.resourceId;if(a.status==="failed")throw p(new Error(a.error?.message??"unknown error"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});if(Date.now()>=e)throw new Error(`OneDrive: copy timed out after ${this.copyTimeoutMs}ms (status: ${a.status??"unknown"})`);await new Promise(r=>{setTimeout(r,B)})}}internalOnComplete=t=>this.deleteMeta(t.id)}const R=o=>{const t=d(o),i=t.lastIndexOf("/");return i===-1?t:t.slice(i+1)},tt=o=>C(o);export{tt as buildGraphClient,Z as default};
1
+ import{ResponseType as g,Client as U,GraphError as b}from"@microsoft/microsoft-graph-client";import{wrapStorageError as p,ERRORS as m,throwErrorCode as E}from"./ERRORS-BIBxE2oR.js";import{c as D}from"./oauth-refresh-EdGzlcOZ.js";import{B as _}from"./storage-0j5nCAUp.js";import u from"./OneDriveFile-CNNJYI43.js";import A from"./OneDriveMetaStorage-xlHfKwmR.js";import{t as T}from"./get-file-status-y3wTtDQs.js";import{t as N}from"./update-size-DuNuLyxj.js";import{i as S}from"./part-match-D-9dGX42.js";import{e as L}from"./has-content-50BsqrWw.js";const P="https://graph.microsoft.com/.default",M=250*1024*1024,F=16*320*1024,B=1e3,d=o=>{let t=0,i=o.length;for(;t<i&&o[t]==="/";)t+=1;for(;i>t&&o[i-1]==="/";)i-=1;return t===0&&i===o.length?o:o.slice(t,i)},w=(o,t)=>{if(d(o).split("/").filter(Boolean).some(i=>i==="."||i===".."))throw new Error(`OneDrive storage: ${t} must not contain "." or ".." path segments.`)},y=o=>o.split("/").map(t=>encodeURIComponent(t)).join("/"),x=async o=>{const t=[];for await(const i of o)t.push(Buffer.from(i));return Buffer.concat(t)},I=o=>({getAccessToken:()=>Promise.resolve(o)}),$=o=>({getAccessToken:async()=>o()}),O=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,client_secret:o.clientSecret,grant_type:"client_credentials",scope:P}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId)}/oauth2/v2.0/token`}),v=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,grant_type:"refresh_token",refresh_token:o.refreshToken,scope:P,...o.clientSecret&&{client_secret:o.clientSecret}}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId??"common")}/oauth2/v2.0/token`}),V=o=>({getAccessToken:()=>o.getAccessToken()}),C=o=>{if(o.client)return o.client;const t=o.accessToken!==void 0,i=o.clientCredentials!==void 0,e=o.oauth!==void 0;if([t,i,e].filter(Boolean).length>1)throw new Error("OneDrive storage: pass exactly one of `accessToken`, `clientCredentials`, or `oauth`.");let n;if(o.accessToken!==void 0?n=typeof o.accessToken=="function"?$(o.accessToken):I(o.accessToken):o.clientCredentials?n=O(o.clientCredentials):o.oauth&&(n=v({clientId:o.oauth.clientId,refreshToken:o.oauth.refreshToken,...o.oauth.clientSecret&&{clientSecret:o.oauth.clientSecret},...o.oauth.tenantId&&{tenantId:o.oauth.tenantId}})),!n){const a=process.env.ONEDRIVE_ACCESS_TOKEN;if(a)n=I(a);else{const r=process.env.ONEDRIVE_CLIENT_ID,s=process.env.ONEDRIVE_CLIENT_SECRET,c=process.env.ONEDRIVE_TENANT_ID,h=process.env.ONEDRIVE_REFRESH_TOKEN;h&&r?n=v({clientId:r,refreshToken:h,...s&&{clientSecret:s},...c&&{tenantId:c}}):r&&s&&c&&(n=O({clientId:r,clientSecret:s,tenantId:c}))}}if(!n)throw new Error("OneDrive storage: missing auth. Pass `client`, `accessToken`, `clientCredentials`, or `oauth`. Env fallbacks: ONEDRIVE_ACCESS_TOKEN; or ONEDRIVE_REFRESH_TOKEN + ONEDRIVE_CLIENT_ID (+ optional ONEDRIVE_CLIENT_SECRET, ONEDRIVE_TENANT_ID); or ONEDRIVE_CLIENT_ID + ONEDRIVE_CLIENT_SECRET + ONEDRIVE_TENANT_ID.");return U.initWithMiddleware({authProvider:V(n)})},z=o=>{if(o instanceof b)return o.statusCode===404||o.code==="itemNotFound";if(o&&typeof o=="object"){const t=o;return t.statusCode===404||t.status===404||t.code==="itemNotFound"}return!1};class Z extends _{static name="onedrive";checksumTypes=[];meta;basePath;client;copyTimeoutMs;publicByDefault;rootFolderPath;constructor(t){if(super(t),[t.driveId,t.siteId,t.userId].filter(i=>i!==void 0).length>1)throw new Error("OneDrive storage: pass at most one of `driveId`, `siteId`, or `userId`.");if(t.driveId)this.basePath=`/drives/${encodeURIComponent(t.driveId)}`;else if(t.siteId)this.basePath=`/sites/${encodeURIComponent(t.siteId)}/drive`;else if(t.userId)this.basePath=`/users/${encodeURIComponent(t.userId)}/drive`;else{if(t.clientCredentials)throw new Error("OneDrive storage: `clientCredentials` (app-only) auth requires `driveId`, `siteId`, or `userId`.");this.basePath="/me/drive"}w(t.rootFolderPath??"","rootFolderPath"),this.rootFolderPath=d(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.copyTimeoutMs=t.copyTimeoutMs??6e4,this.client=C(t),this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,i){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),await this.validate(e);try{const n=await this.getMeta(e.id);if(n.bytesWritten>=0)return n}catch{}return e.bytesWritten=0,e.status=T(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,i){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&&N(e,t.size),!S(t,e))throw new Error("File part does not match");const n=await this.lock(t.id);try{if(L(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await x(t.body),r=e.name||e.id,s=a.byteLength<=M?await this.uploadSimple(r,a,e.contentType,i):await this.uploadSession(r,a,e.contentType,i);e.bytesWritten=a.length,e.size=a.length,e.driveItemId=s.id,e.webUrl=s.webUrl,e.eTag=s.eTag,e.ETag=s.eTag}return e.status=T(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,n)}})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const n=e?.name??t;try{await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).delete())}catch(a){if(!z(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,status:"deleted"})})}async get({id:t},i){return this.instrumentOperation("get",async()=>{let e,n=t;try{e=await this.checkIfExpired(await this.getMeta(t)),n=e.name??t}catch{}const a=await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).get()),r=await this.runOperation(i,()=>this.client.api(this.itemActionPath(n,"content")).responseType(g.ARRAYBUFFER).get()),s=Buffer.from(r);return{content:s,contentType:e?.contentType??a.file?.mimeType??"application/octet-stream",ETag:e?.ETag??a.eTag,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.lastModifiedDateTime,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??s.length}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const n=this.parentReferencePath(i),a={name:R(i),parentReference:{path:n}},r=await this.runOperation(e,()=>this.client.api(this.itemActionPath(t,"copy")).responseType(g.RAW).post(a));if(r.status!==202){const f=await r.text().catch(()=>"");throw p(new Error(f||r.statusText),{adapter:"OneDrive",operation:"copy",status:r.status})}const s=r.headers.get("Location");if(!s)throw p(new Error("response missing Location monitor URL"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});const c=await this.pollCopyMonitor(s,e),h=new u({contentType:"application/octet-stream",metadata:{},originalName:i});return h.id=i,h.name=i,h.driveItemId=c,h})}async move(t,i,e){return this.instrumentOperation("move",async()=>{const n=this.parentReferencePath(i),a=R(i),r=await this.runOperation(e,()=>this.client.api(this.itemApiPath(t)).patch({name:a,parentReference:{path:n}})),s=new u({contentType:"application/octet-stream",metadata:{},originalName:i});s.id=i,s.name=i,s.driveItemId=r.id,s.webUrl=r.webUrl,s.eTag=r.eTag,s.ETag=r.eTag;try{await this.deleteMeta(t)}catch{}return s})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const e=[];let n=`${this.folderListChildrenPath()}?$top=${Math.min(t,1e3)}`;for(;n&&e.length<t;){const a=await this.runOperation(i,()=>this.client.api(n).get());for(const r of a.value){if(!r.file)continue;const s=this.itemPathToKey(r);if(!s)continue;const c=new u({contentType:r.file.mimeType??"application/octet-stream",metadata:{},originalName:r.name});if(c.id=s,c.name=s,c.driveItemId=r.id,c.webUrl=r.webUrl,c.eTag=r.eTag,c.ETag=r.eTag,c.size=r.size??0,c.modifiedAt=r.lastModifiedDateTime,e.push(c),e.length>=t)break}n=a["@odata.nextLink"]??null}return e},{limit:t})}async getReadUrl(t,i){if(i?.responseContentDisposition||i?.responseContentType)return E(m.METHOD_NOT_ALLOWED,"OneDrive: `responseContentDisposition` / `responseContentType` are not supported — Graph download URLs have no overrides.");if(this.publicByDefault){const n=(await this.client.api(this.itemActionPath(t,"createLink")).post({scope:"anonymous",type:"view"})).link?.webUrl;if(!n)throw new Error("OneDrive: createLink response missing webUrl");return n}const e=(await this.client.api(this.itemApiPath(t)).select("@microsoft.graph.downloadUrl").get())["@microsoft.graph.downloadUrl"];if(!e)throw new Error("OneDrive: item has no `@microsoft.graph.downloadUrl` — it may be a folder or have no content.");return e}async getUploadUrl(t,i){if(i?.contentLength!==void 0)return E(m.BAD_REQUEST,"OneDrive: `contentLength` is not supported for upload URLs. A Graph upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");const e=await this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...i?.contentType&&{file:{mimeType:i.contentType}}}});if(!e.uploadUrl)throw p(new Error("createUploadSession response missing uploadUrl"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"getUploadUrl"});return e.uploadUrl}keyParts(t){w(t,"key");const i=d(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),i&&e.push(i),e}itemApiPath(t){const i=this.keyParts(t);return i.length===0?`${this.basePath}/root`:`${this.basePath}/root:/${y(i.join("/"))}`}itemActionPath(t,i){const e=this.keyParts(t);return e.length===0?`${this.basePath}/root/${i}`:`${this.basePath}/root:/${y(e.join("/"))}:/${i}`}folderListChildrenPath(){return this.itemActionPath("","children")}parentReferencePath(t){w(t,"key");const i=d(t),e=[];this.rootFolderPath&&e.push(this.rootFolderPath);const n=i.lastIndexOf("/");if(n!==-1){const a=i.slice(0,n);a&&e.push(a)}return e.length===0?"/drive/root:":`/drive/root:/${y(e.join("/"))}`}itemPathToKey(t){const i=t.parentReference?.path??"",e="/root:",n=i.indexOf(e);let a=n===-1?"":i.slice(n+e.length);a=d(decodeURIComponent(a));const r=this.rootFolderPath&&a.startsWith(this.rootFolderPath)?a.slice(this.rootFolderPath.length):a,s=d(r);return s?`${s}/${t.name}`:t.name}async uploadSimple(t,i,e,n){return await this.runOperation(n,()=>this.client.api(`${this.itemActionPath(t,"content")}?@microsoft.graph.conflictBehavior=replace`).header("Content-Type",e??"application/octet-stream").put(i))}async uploadSession(t,i,e,n){const a=await this.runOperation(n,()=>this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...e&&{file:{mimeType:e}}}})),r=i.byteLength;let s=0,c;for(;s<r;){const h=Math.min(s+F,r),f=i.subarray(s,h),l=await this.runOperation(n,()=>fetch(a.uploadUrl,{body:new Uint8Array(f),headers:{"Content-Length":String(f.byteLength),"Content-Range":`bytes ${s}-${h-1}/${r}`},method:"PUT"}));if(l.status===200||l.status===201)c=await l.json();else if(l.status!==202){const k=await l.text().catch(()=>"");throw p(new Error(k||l.statusText),{adapter:"OneDrive",operation:"upload-session chunk",status:l.status})}s=h}if(!c)throw p(new Error("upload-session terminated without a final DriveItem response"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"write"});return c}async pollCopyMonitor(t,i){const e=Date.now()+this.copyTimeoutMs;for(;;){const n=await this.runOperation(i,()=>fetch(t));if(!n.ok)throw p(new Error(n.statusText),{adapter:"OneDrive",operation:"copy monitor",status:n.status});const a=await n.json();if(a.status==="completed")return a.resourceId;if(a.status==="failed")throw p(new Error(a.error?.message??"unknown error"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});if(Date.now()>=e)throw new Error(`OneDrive: copy timed out after ${this.copyTimeoutMs}ms (status: ${a.status??"unknown"})`);await new Promise(r=>{setTimeout(r,B)})}}internalOnComplete=t=>this.deleteMeta(t.id)}const R=o=>{const t=d(o),i=t.lastIndexOf("/");return i===-1?t:t.slice(i+1)},tt=o=>C(o);export{tt as buildGraphClient,Z as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class e extends r{constructor(o){super(o)}}export{e as default};
@@ -1 +1 @@
1
- import g,{ClientResponseError as O}from"pocketbase";import{throwErrorCode as p,ERRORS as m}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-0j5nCAUp.js";import u from"./PocketBaseFile-DpJpxl3e.js";import A from"./PocketBaseMetaStorage-DOTLwVE7.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as E}from"./update-size-DuNuLyxj.js";import{i as T}from"./part-match-D-9dGX42.js";import{e as B}from"./has-content-50BsqrWw.js";const N=async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},d=o=>(o instanceof O||!!o&&typeof o=="object")&&o.status===404,f=(o,t,a,e)=>{const i=o.files.getURL??o.files.getUrl;return i?i(t,a,e):p(m.METHOD_NOT_ALLOWED,"PocketBase: client has no files.getURL()")};class P extends k{static name="pocketbase";checksumTypes=[];meta;client;collectionName;defaultUrlExpiresIn;fileField;keyField;publicBaseUrl;ensureAuth;constructor(t){if(super(t),!t.collection)throw new Error("PocketBase storage: `collection` is required.");if(this.collectionName=t.collection,this.keyField=t.keyField??"key",this.fileField=t.fileField??"file",this.publicBaseUrl=t.publicBaseUrl,this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??3600,t.client)this.client=t.client,this.ensureAuth=async()=>{};else{const a=t.url??process.env.POCKETBASE_URL;if(!a)throw new Error("PocketBase storage: `url` is required (or set POCKETBASE_URL).");const e=new g(a);this.client=e;const i=t.authToken??process.env.POCKETBASE_AUTH_TOKEN,n=t.adminEmail??process.env.POCKETBASE_ADMIN_EMAIL,s=t.adminPassword??process.env.POCKETBASE_ADMIN_PASSWORD;i?(e.authStore.save(i,null),this.ensureAuth=async()=>{}):n&&s?this.ensureAuth=async()=>{e.authStore.isValid||await e.collection("_superusers").authWithPassword(n,s)}:this.ensureAuth=async()=>{}}this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),e.bucket=this.collectionName,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=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),!T(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(B(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await N(t.body),s=e.path??e.name;await this.putRecord(s,n,e.contentType,a),e.bytesWritten=n.length,e.size=n.length,e.path=s}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?.path??e?.name??t;await this.ensureAuth();try{const n=await this.findRecord(i,a);await this.runOperation(a,()=>this.client.collection(this.collectionName).delete(n.id))}catch(n){if(!d(n))throw n}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.collectionName,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{}await this.ensureAuth();try{return await this.findRecord(e,a),!0}catch(i){if(d(i))return!1;throw 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{}await this.ensureAuth();const n=await this.findRecord(e,a),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(a,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${e}"`);const l=Buffer.from(await c.arrayBuffer());return{content:l,contentType:i?.contentType??c.headers.get("content-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??l.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();const n=await this.findRecord(i,e),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(e,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${i}"`);const l=Buffer.from(await c.arrayBuffer()),w=c.headers.get("content-type")??"application/octet-stream";await this.putRecord(a,l,w,e);const h=new u({contentType:w,metadata:{},originalName:a});return h.id=a,h.name=a,h.path=a,h.bucket=this.collectionName,h.size=l.length,h})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e),n=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();try{const s=await this.findRecord(n,e);await this.runOperation(e,()=>this.client.collection(this.collectionName).delete(s.id))}catch(s){if(!d(s))throw s}try{await this.deleteMeta(t)}catch{}return i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{await this.ensureAuth();const{items:e}=await this.runOperation(a,()=>this.client.collection(this.collectionName).getList(1,t));return(e??[]).map(i=>{const n=String(i[this.keyField]??i.id),s=String(i[this.fileField]??""),r=new u({contentType:"application/octet-stream",metadata:{},originalName:n});return r.id=n,r.name=n,r.path=n,r.bucket=this.collectionName,r.ETag=s||void 0,r.createdAt=typeof i.created=="string"?i.created:void 0,r.modifiedAt=typeof i.updated=="string"?i.updated:void 0,r})},{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return p(m.METHOD_NOT_ALLOWED,"PocketBase: `responseContentDisposition`/`responseContentType` are not supported — PocketBase file URLs have no Content-Disposition/Content-Type override.");if(this.publicBaseUrl)return`${this.publicBaseUrl.replace(/\/+$/,"")}/${t}`;await this.ensureAuth();let e=t;const i=await this.getMetaSafe(t);i?.path&&(e=i.path);const n=await this.findRecord(e),s=String(n[this.fileField]??""),r=await this.client.files.getToken();return f(this.client,n,s,{token:r})}async findRecord(t,a){const e=this.client.filter(`${this.keyField} = {:k}`,{k:t});return this.runOperation(a,()=>this.client.collection(this.collectionName).getFirstListItem(e))}async putRecord(t,a,e,i){await this.ensureAuth();const n=new FormData;n.append(this.keyField,t),n.append(this.fileField,new Blob([new Uint8Array(a)],{type:e}),t);try{const s=await this.findRecord(t,i);await this.runOperation(i,()=>this.client.collection(this.collectionName).update(s.id,n))}catch(s){if(!d(s))throw s;await this.runOperation(i,()=>this.client.collection(this.collectionName).create(n))}}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=t=>this.deleteMeta(t.id)}export{P as default};
1
+ import g,{ClientResponseError as O}from"pocketbase";import{throwErrorCode as p,ERRORS as m}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-0j5nCAUp.js";import u from"./PocketBaseFile-DpJpxl3e.js";import A from"./PocketBaseMetaStorage-DnrxOQhO.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as E}from"./update-size-DuNuLyxj.js";import{i as T}from"./part-match-D-9dGX42.js";import{e as B}from"./has-content-50BsqrWw.js";const N=async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},d=o=>(o instanceof O||!!o&&typeof o=="object")&&o.status===404,f=(o,t,a,e)=>{const i=o.files.getURL??o.files.getUrl;return i?i(t,a,e):p(m.METHOD_NOT_ALLOWED,"PocketBase: client has no files.getURL()")};class P extends k{static name="pocketbase";checksumTypes=[];meta;client;collectionName;defaultUrlExpiresIn;fileField;keyField;publicBaseUrl;ensureAuth;constructor(t){if(super(t),!t.collection)throw new Error("PocketBase storage: `collection` is required.");if(this.collectionName=t.collection,this.keyField=t.keyField??"key",this.fileField=t.fileField??"file",this.publicBaseUrl=t.publicBaseUrl,this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??3600,t.client)this.client=t.client,this.ensureAuth=async()=>{};else{const a=t.url??process.env.POCKETBASE_URL;if(!a)throw new Error("PocketBase storage: `url` is required (or set POCKETBASE_URL).");const e=new g(a);this.client=e;const i=t.authToken??process.env.POCKETBASE_AUTH_TOKEN,n=t.adminEmail??process.env.POCKETBASE_ADMIN_EMAIL,s=t.adminPassword??process.env.POCKETBASE_ADMIN_PASSWORD;i?(e.authStore.save(i,null),this.ensureAuth=async()=>{}):n&&s?this.ensureAuth=async()=>{e.authStore.isValid||await e.collection("_superusers").authWithPassword(n,s)}:this.ensureAuth=async()=>{}}this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),e.bucket=this.collectionName,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=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),!T(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(B(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await N(t.body),s=e.path??e.name;await this.putRecord(s,n,e.contentType,a),e.bytesWritten=n.length,e.size=n.length,e.path=s}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?.path??e?.name??t;await this.ensureAuth();try{const n=await this.findRecord(i,a);await this.runOperation(a,()=>this.client.collection(this.collectionName).delete(n.id))}catch(n){if(!d(n))throw n}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.collectionName,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{}await this.ensureAuth();try{return await this.findRecord(e,a),!0}catch(i){if(d(i))return!1;throw 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{}await this.ensureAuth();const n=await this.findRecord(e,a),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(a,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${e}"`);const l=Buffer.from(await c.arrayBuffer());return{content:l,contentType:i?.contentType??c.headers.get("content-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??l.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();const n=await this.findRecord(i,e),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(e,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${i}"`);const l=Buffer.from(await c.arrayBuffer()),w=c.headers.get("content-type")??"application/octet-stream";await this.putRecord(a,l,w,e);const h=new u({contentType:w,metadata:{},originalName:a});return h.id=a,h.name=a,h.path=a,h.bucket=this.collectionName,h.size=l.length,h})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e),n=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();try{const s=await this.findRecord(n,e);await this.runOperation(e,()=>this.client.collection(this.collectionName).delete(s.id))}catch(s){if(!d(s))throw s}try{await this.deleteMeta(t)}catch{}return i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{await this.ensureAuth();const{items:e}=await this.runOperation(a,()=>this.client.collection(this.collectionName).getList(1,t));return(e??[]).map(i=>{const n=String(i[this.keyField]??i.id),s=String(i[this.fileField]??""),r=new u({contentType:"application/octet-stream",metadata:{},originalName:n});return r.id=n,r.name=n,r.path=n,r.bucket=this.collectionName,r.ETag=s||void 0,r.createdAt=typeof i.created=="string"?i.created:void 0,r.modifiedAt=typeof i.updated=="string"?i.updated:void 0,r})},{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return p(m.METHOD_NOT_ALLOWED,"PocketBase: `responseContentDisposition`/`responseContentType` are not supported — PocketBase file URLs have no Content-Disposition/Content-Type override.");if(this.publicBaseUrl)return`${this.publicBaseUrl.replace(/\/+$/,"")}/${t}`;await this.ensureAuth();let e=t;const i=await this.getMetaSafe(t);i?.path&&(e=i.path);const n=await this.findRecord(e),s=String(n[this.fileField]??""),r=await this.client.files.getToken();return f(this.client,n,s,{token:r})}async findRecord(t,a){const e=this.client.filter(`${this.keyField} = {:k}`,{k:t});return this.runOperation(a,()=>this.client.collection(this.collectionName).getFirstListItem(e))}async putRecord(t,a,e,i){await this.ensureAuth();const n=new FormData;n.append(this.keyField,t),n.append(this.fileField,new Blob([new Uint8Array(a)],{type:e}),t);try{const s=await this.findRecord(t,i);await this.runOperation(i,()=>this.client.collection(this.collectionName).update(s.id,n))}catch(s){if(!d(s))throw s;await this.runOperation(i,()=>this.client.collection(this.collectionName).create(n))}}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=t=>this.deleteMeta(t.id)}export{P as default};
@@ -1 +1 @@
1
- import{CreateMultipartUploadCommand as f,UploadPartCommand as g,CompleteMultipartUploadCommand as w,AbortMultipartUploadCommand as k,ListPartsCommand as B,GetObjectCommand as C,HeadObjectCommand as b,DeleteObjectCommand as S,CopyObjectCommand as T,ListObjectsV2Command as E,waitUntilBucketExists as x,S3Client as U,PutObjectCommand as K}from"@aws-sdk/client-s3";import{fromIni as L}from"@aws-sdk/credential-providers";import{getSignedUrl as m}from"@aws-sdk/s3-request-presigner";import{S as P,b as I}from"./s3-base-storage-BoTyhuzO.js";import{Readable as u}from"node:stream";import{ReadableStream as y}from"node:stream/web";import M from"./S3File-CpZrubaV.js";import A from"./S3MetaStorage-CMonflzp.js";const r=p=>p?.signal?{abortSignal:p.signal}:void 0;class O{constructor(e,t){this.client=e}client;async createMultipartUpload(e,t){const a=new f({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),n=await this.client.send(a,r(t));if(!n.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:n.UploadId}}async uploadPart(e,t){const a=e.Body instanceof y?u.fromWeb(e.Body):e.Body,n=new g({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),o=await this.client.send(n,r(t));if(!o.ETag)throw new Error("Failed to upload part");return{ETag:o.ETag}}async completeMultipartUpload(e,t){const a=new w({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:o,PartNumber:i})=>({ETag:o,PartNumber:i}))},UploadId:e.UploadId}),n=await this.client.send(a,r(t));if(!n.Location)throw new Error("Failed to complete multipart upload");return{ETag:n.ETag,Location:n.Location}}async abortMultipartUpload(e,t){const a=new k({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a,r(t))}async listParts(e,t){const a=new B({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),n=await this.client.send(a,r(t)),o=[];if(n.Parts)for(const i of n.Parts)i.ETag&&i.PartNumber&&o.push({ETag:i.ETag,PartNumber:i.PartNumber,Size:i.Size});return{Parts:o.length>0?o:void 0}}async getObject(e,t){const a=new C({Bucket:e.Bucket,Key:e.Key,...e.Range!==void 0&&{Range:e.Range}}),n=await this.client.send(a,r(t));let o;if(n.Body){const i=n.Body;i instanceof u||typeof i=="object"&&"transform"in i&&i instanceof y?o=i:o=u.from(i)}return{Body:o,ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified,Metadata:n.Metadata}}async headObject(e,t){const a=new b({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,r(t));return{ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified}}async deleteObject(e,t){const a=new S({Bucket:e.Bucket,Key:e.Key});await this.client.send(a,r(t))}async copyObject(e,t){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const n=new T(a);await this.client.send(n,r(t))}async listObjectsV2(e,t){const a=new E({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,Delimiter:e.Delimiter,MaxKeys:e.MaxKeys,Prefix:e.Prefix}),n=await this.client.send(a,r(t));return{CommonPrefixes:n.CommonPrefixes?.map(o=>({Prefix:o.Prefix})),Contents:n.Contents?.map(o=>({Key:o.Key,LastModified:o.LastModified})),IsTruncated:n.IsTruncated,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(e){const t=new g({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return m(this.client,t,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await x({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}class _ extends P{static name="s3";s3Api;rawClient;constructor(e){const{bucket:t=process.env.S3_BUCKET,region:a=process.env.S3_REGION}=e;if(!t)throw new Error("S3 bucket is not defined");if(!a)throw new Error("S3 region is not defined");e.region=a;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=L({configFilepath:n}));const o=new U(e);super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:c=>{const s=c;if(s.$metadata){const d=s.$metadata.httpStatusCode;if(d&&[408,429,500,502,503,504].includes(d)||s.$fault==="server")return!0}return s.retryable??!1}}}),this.s3Api=new O(o,t),this.rawClient=o;const{metaStorage:i,metaStorageConfig:l}=e;if(!i){const c={...e,...l,logger:this.logger};"directory"in c||(this.meta=new A(c))}this.config.clientDirectUpload&&(this.onCreate=async()=>{})}normalizeError(e){return e.$metadata?{code:e.Code||e.name,message:e.message,name:e.name,statusCode:e.$metadata.httpStatusCode||500}:super.normalizeError(e)}async update({id:e},t){if(this.config.clientDirectUpload){const a=await this.getMeta(e);return this.buildPresigned({...a,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),n=I(t?.range),{Body:o,ContentLength:i,ContentType:l,ETag:c,Expires:s,LastModified:d}=await this.runOperation(t,h=>a.getObject({Bucket:this.bucket,Key:e,...n!==void 0&&{Range:n}},{signal:h}));return await this.checkIfExpired({expiredAt:s}),{headers:{"Content-Length":i?.toString()??"0","Content-Type":l,...c&&{ETag:c},...s&&{"X-Upload-Expires":s.toString()},...d&&{"Last-Modified":d.toString()}},size:Number(i),stream:o}})}get raw(){return this.rawClient}async getReadUrl(e,t){const a=new C({Bucket:this.bucket,Key:e,...t?.responseContentDisposition&&{ResponseContentDisposition:t.responseContentDisposition},...t?.responseContentType&&{ResponseContentType:t.responseContentType}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}async getUploadUrl(e,t){const a=new K({Bucket:this.bucket,Key:e,...t?.contentType&&{ContentType:t.contentType},...t?.contentLength!==void 0&&{ContentLength:t.contentLength}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}getS3Api(){return this.s3Api}getFileClass(){return M}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{_ as default};
1
+ import{CreateMultipartUploadCommand as f,UploadPartCommand as g,CompleteMultipartUploadCommand as w,AbortMultipartUploadCommand as k,ListPartsCommand as B,GetObjectCommand as C,HeadObjectCommand as b,DeleteObjectCommand as S,CopyObjectCommand as T,ListObjectsV2Command as E,waitUntilBucketExists as x,S3Client as U,PutObjectCommand as K}from"@aws-sdk/client-s3";import{fromIni as L}from"@aws-sdk/credential-providers";import{getSignedUrl as m}from"@aws-sdk/s3-request-presigner";import{S as P,b as I}from"./s3-base-storage-CMUui93V.js";import{Readable as u}from"node:stream";import{ReadableStream as y}from"node:stream/web";import M from"./S3File-CpZrubaV.js";import A from"./S3MetaStorage-CMonflzp.js";const r=p=>p?.signal?{abortSignal:p.signal}:void 0;class O{constructor(e,t){this.client=e}client;async createMultipartUpload(e,t){const a=new f({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),n=await this.client.send(a,r(t));if(!n.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:n.UploadId}}async uploadPart(e,t){const a=e.Body instanceof y?u.fromWeb(e.Body):e.Body,n=new g({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),o=await this.client.send(n,r(t));if(!o.ETag)throw new Error("Failed to upload part");return{ETag:o.ETag}}async completeMultipartUpload(e,t){const a=new w({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:o,PartNumber:i})=>({ETag:o,PartNumber:i}))},UploadId:e.UploadId}),n=await this.client.send(a,r(t));if(!n.Location)throw new Error("Failed to complete multipart upload");return{ETag:n.ETag,Location:n.Location}}async abortMultipartUpload(e,t){const a=new k({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a,r(t))}async listParts(e,t){const a=new B({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),n=await this.client.send(a,r(t)),o=[];if(n.Parts)for(const i of n.Parts)i.ETag&&i.PartNumber&&o.push({ETag:i.ETag,PartNumber:i.PartNumber,Size:i.Size});return{Parts:o.length>0?o:void 0}}async getObject(e,t){const a=new C({Bucket:e.Bucket,Key:e.Key,...e.Range!==void 0&&{Range:e.Range}}),n=await this.client.send(a,r(t));let o;if(n.Body){const i=n.Body;i instanceof u||typeof i=="object"&&"transform"in i&&i instanceof y?o=i:o=u.from(i)}return{Body:o,ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified,Metadata:n.Metadata}}async headObject(e,t){const a=new b({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,r(t));return{ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified}}async deleteObject(e,t){const a=new S({Bucket:e.Bucket,Key:e.Key});await this.client.send(a,r(t))}async copyObject(e,t){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const n=new T(a);await this.client.send(n,r(t))}async listObjectsV2(e,t){const a=new E({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,Delimiter:e.Delimiter,MaxKeys:e.MaxKeys,Prefix:e.Prefix}),n=await this.client.send(a,r(t));return{CommonPrefixes:n.CommonPrefixes?.map(o=>({Prefix:o.Prefix})),Contents:n.Contents?.map(o=>({Key:o.Key,LastModified:o.LastModified})),IsTruncated:n.IsTruncated,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(e){const t=new g({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return m(this.client,t,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await x({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}class _ extends P{static name="s3";s3Api;rawClient;constructor(e){const{bucket:t=process.env.S3_BUCKET,region:a=process.env.S3_REGION}=e;if(!t)throw new Error("S3 bucket is not defined");if(!a)throw new Error("S3 region is not defined");e.region=a;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=L({configFilepath:n}));const o=new U(e);super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:c=>{const s=c;if(s.$metadata){const d=s.$metadata.httpStatusCode;if(d&&[408,429,500,502,503,504].includes(d)||s.$fault==="server")return!0}return s.retryable??!1}}}),this.s3Api=new O(o,t),this.rawClient=o;const{metaStorage:i,metaStorageConfig:l}=e;if(!i){const c={...e,...l,logger:this.logger};"directory"in c||(this.meta=new A(c))}this.config.clientDirectUpload&&(this.onCreate=async()=>{})}normalizeError(e){return e.$metadata?{code:e.Code||e.name,message:e.message,name:e.name,statusCode:e.$metadata.httpStatusCode||500}:super.normalizeError(e)}async update({id:e},t){if(this.config.clientDirectUpload){const a=await this.getMeta(e);return this.buildPresigned({...a,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),n=I(t?.range),{Body:o,ContentLength:i,ContentType:l,ETag:c,Expires:s,LastModified:d}=await this.runOperation(t,h=>a.getObject({Bucket:this.bucket,Key:e,...n!==void 0&&{Range:n}},{signal:h}));return await this.checkIfExpired({expiredAt:s}),{headers:{"Content-Length":i?.toString()??"0","Content-Type":l,...c&&{ETag:c},...s&&{"X-Upload-Expires":s.toString()},...d&&{"Last-Modified":d.toString()}},size:Number(i),stream:o}})}get raw(){return this.rawClient}async getReadUrl(e,t){const a=new C({Bucket:this.bucket,Key:e,...t?.responseContentDisposition&&{ResponseContentDisposition:t.responseContentDisposition},...t?.responseContentType&&{ResponseContentType:t.responseContentType}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}async getUploadUrl(e,t){const a=new K({Bucket:this.bucket,Key:e,...t?.contentType&&{ContentType:t.contentType},...t?.contentLength!==void 0&&{ContentLength:t.contentLength}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}getS3Api(){return this.s3Api}getFileClass(){return M}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{_ as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{F as T}from"./index-nZWCQrSe.js";import P from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import k from"./SftpFile-ClWDYnt2.js";import F from"./SftpMetaStorage-BSn6Qfnf.js";import{r as y,t as b,e as l}from"./posix-dirname-CfpH5wZi.js";import{t as E}from"./get-file-status-y3wTtDQs.js";import{t as M}from"./update-size-DuNuLyxj.js";import{i as v}from"./part-match-D-9dGX42.js";import{e as S}from"./has-content-50BsqrWw.js";const f=c=>{const a=c?.code,e=c instanceof Error?c.message:String(c);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},g=c=>{if(c instanceof Error&&c.name==="AbortError")return c;const a=new Error(c instanceof Error&&c.message?c.message:"The operation was aborted",{cause:c});return a.name="AbortError",a};class U extends O{static name="sftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=y(a.rootFolderPath??""),this.meta=a.metaStorage??new F(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new k(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const i=await this.getMeta(t.id);if(i.status==="completed")return i}catch{}return t.bytesWritten=0,t.status=E(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&M(t,a.size),!v(a,t))return d(p.FILE_CONFLICT);const i=await this.lock(a.id);try{if(S(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return d(p.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return d(p.METHOD_NOT_ALLOWED,"SFTP storage does not support chunked or resumable uploads; send the file in a single request.");const n=await b(a.body),r=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{const h=l(r);h&&await o.mkdir(h,!0),await o.put(n,r)})),t.bytesWritten=n.length,t.size=n.length,t.path=r,t.ETag=T(n)}return t.status=E(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,i)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),i=t.path??this.keyToPath(t.name||a),{range:n}=e??{},r=await this.runOperation(e,s=>this.run(s,async o=>{try{const h=n?{readStreamOptions:{start:n.start,...n.end===void 0?{}:{end:n.end}}}:void 0;return await o.get(i,void 0,h)}catch(h){if(f(h))return d(p.FILE_NOT_FOUND);throw h}}));return{content:r,contentType:t.contentType,ETag:t.ETag??T(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:n?r.length:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),i=t.path??this.keyToPath(t.name||a);await this.runOperation(e,r=>this.run(r,async s=>{try{await s.delete(i)}catch(o){if(!f(o))throw o}})),await this.deleteMeta(a);const n={...t,status:"deleted"};return await this.onDelete(n),n})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=await h.get(n),m=l(r);m&&await h.mkdir(m,!0),await h.put(u,r)}));const s={...i,id:e,name:e,path:r};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=l(r);u&&await h.mkdir(u,!0);try{await h.rename(n,r)}catch(m){try{const w=await h.get(n);await h.put(w,r),await h.delete(n)}catch(w){throw new AggregateError([m,w],`SFTP move failed: rename and copy+delete fallback both failed for "${n}" → "${r}"`)}}}));const s={...i,id:e,name:e,path:r};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,i=>this.run(i,async n=>{const r=[];return await this.walkList(n,t,r),r}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const i=t.path??this.keyToPath(t.name||a);return this.runOperation(e,n=>this.run(n,async r=>{const s=await r.exists(i);return s==="-"||s==="l"}))})}async walkList(a,e,t){let i;try{i=await a.list(e||".")}catch(n){if(f(n))return;throw n}for(const n of i){const r=e?`${e}/${n.name}`:n.name;if(n.type==="d"){await this.walkList(a,r,t);continue}if(n.type!=="-")continue;const s=this.pathToKey(r);if(!s)continue;const o=new k({contentType:"application/octet-stream",metadata:{},originalName:n.name});o.id=s,o.name=s,o.path=r,o.size=n.size,o.modifiedAt=new Date(n.modifyTime).toISOString(),t.push(o)}}async run(a,e){const t=new P;if(a?.aborted)throw g(a.reason);const i=()=>{t.end()};a?.addEventListener("abort",i,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(n){throw a?.aborted?g(n):n}finally{a?.removeEventListener("abort",i),await t.end()}}keyToPath(a){const e=y(a);e&&O.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":this.rootFolderPath.startsWith("/")?`/${t.join("/")}`:t.join("/")}pathToKey(a){const e=y(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{U as default};
1
+ import{F as T}from"./index-nZWCQrSe.js";import P from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import k from"./SftpFile-ClWDYnt2.js";import F from"./SftpMetaStorage-CHWrhgg2.js";import{r as y,t as b,e as l}from"./posix-dirname-CfpH5wZi.js";import{t as E}from"./get-file-status-y3wTtDQs.js";import{t as M}from"./update-size-DuNuLyxj.js";import{i as v}from"./part-match-D-9dGX42.js";import{e as S}from"./has-content-50BsqrWw.js";const f=c=>{const a=c?.code,e=c instanceof Error?c.message:String(c);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},g=c=>{if(c instanceof Error&&c.name==="AbortError")return c;const a=new Error(c instanceof Error&&c.message?c.message:"The operation was aborted",{cause:c});return a.name="AbortError",a};class U extends O{static name="sftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=y(a.rootFolderPath??""),this.meta=a.metaStorage??new F(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new k(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const i=await this.getMeta(t.id);if(i.status==="completed")return i}catch{}return t.bytesWritten=0,t.status=E(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&M(t,a.size),!v(a,t))return d(p.FILE_CONFLICT);const i=await this.lock(a.id);try{if(S(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return d(p.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return d(p.METHOD_NOT_ALLOWED,"SFTP storage does not support chunked or resumable uploads; send the file in a single request.");const n=await b(a.body),r=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{const h=l(r);h&&await o.mkdir(h,!0),await o.put(n,r)})),t.bytesWritten=n.length,t.size=n.length,t.path=r,t.ETag=T(n)}return t.status=E(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,i)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),i=t.path??this.keyToPath(t.name||a),{range:n}=e??{},r=await this.runOperation(e,s=>this.run(s,async o=>{try{const h=n?{readStreamOptions:{start:n.start,...n.end===void 0?{}:{end:n.end}}}:void 0;return await o.get(i,void 0,h)}catch(h){if(f(h))return d(p.FILE_NOT_FOUND);throw h}}));return{content:r,contentType:t.contentType,ETag:t.ETag??T(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:n?r.length:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),i=t.path??this.keyToPath(t.name||a);await this.runOperation(e,r=>this.run(r,async s=>{try{await s.delete(i)}catch(o){if(!f(o))throw o}})),await this.deleteMeta(a);const n={...t,status:"deleted"};return await this.onDelete(n),n})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=await h.get(n),m=l(r);m&&await h.mkdir(m,!0),await h.put(u,r)}));const s={...i,id:e,name:e,path:r};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=l(r);u&&await h.mkdir(u,!0);try{await h.rename(n,r)}catch(m){try{const w=await h.get(n);await h.put(w,r),await h.delete(n)}catch(w){throw new AggregateError([m,w],`SFTP move failed: rename and copy+delete fallback both failed for "${n}" → "${r}"`)}}}));const s={...i,id:e,name:e,path:r};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,i=>this.run(i,async n=>{const r=[];return await this.walkList(n,t,r),r}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const i=t.path??this.keyToPath(t.name||a);return this.runOperation(e,n=>this.run(n,async r=>{const s=await r.exists(i);return s==="-"||s==="l"}))})}async walkList(a,e,t){let i;try{i=await a.list(e||".")}catch(n){if(f(n))return;throw n}for(const n of i){const r=e?`${e}/${n.name}`:n.name;if(n.type==="d"){await this.walkList(a,r,t);continue}if(n.type!=="-")continue;const s=this.pathToKey(r);if(!s)continue;const o=new k({contentType:"application/octet-stream",metadata:{},originalName:n.name});o.id=s,o.name=s,o.path=r,o.size=n.size,o.modifiedAt=new Date(n.modifyTime).toISOString(),t.push(o)}}async run(a,e){const t=new P;if(a?.aborted)throw g(a.reason);const i=()=>{t.end()};a?.addEventListener("abort",i,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(n){throw a?.aborted?g(n):n}finally{a?.removeEventListener("abort",i),await t.end()}}keyToPath(a){const e=y(a);e&&O.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":this.rootFolderPath.startsWith("/")?`/${t.join("/")}`:t.join("/")}pathToKey(a){const e=y(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{U as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{throwErrorCode as c,ERRORS as d}from"./ERRORS-BIBxE2oR.js";import h,{buildGraphClient as l}from"./OneDriveStorage-CP6MvGAa.js";import{B as I}from"./storage-0j5nCAUp.js";import u from"./SharePointMetaStorage-BSn6Qfnf.js";const g=a=>{if(!a)return;const e=a.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},v=a=>{let e;try{e=new URL(a)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${a}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}};class T extends I{static name="sharepoint";checksumTypes=[];meta;client;inner;innerPromise;oneDriveAuth;resolvedConfig;constructor(e){super(e);const t=e.accessToken??process.env.SHAREPOINT_ACCESS_TOKEN??process.env.ONEDRIVE_ACCESS_TOKEN,r=e.clientCredentials??(()=>{const n=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,o=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,i=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(n&&o&&i)return{clientId:o,clientSecret:i,tenantId:n}})();this.oneDriveAuth={...e.client&&{client:e.client},...t!==void 0&&{accessToken:t},...r&&{clientCredentials:r},...e.oauth&&{oauth:e.oauth}},this.resolvedConfig={...e,...e.driveId??process.env.SHAREPOINT_DRIVE_ID?{driveId:e.driveId??process.env.SHAREPOINT_DRIVE_ID}:{},...e.siteId??process.env.SHAREPOINT_SITE_ID?{siteId:e.siteId??process.env.SHAREPOINT_SITE_ID}:{},...e.siteUrl??process.env.SHAREPOINT_SITE_URL?{siteUrl:e.siteUrl??process.env.SHAREPOINT_SITE_URL}:{},...e.hostname??process.env.SHAREPOINT_HOSTNAME?{hostname:e.hostname??process.env.SHAREPOINT_HOSTNAME}:{}},this.client=l(this.oneDriveAuth),this.meta=e.metaStorage??new u(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,t){return(await this.getInner()).create(e,t)}async write(e,t){return(await this.getInner()).write(e,t)}async delete(e,t){return(await this.getInner()).delete(e,t)}async get(e,t){return(await this.getInner()).get(e,t)}async copy(e,t,r){return(await this.getInner()).copy(e,t,r)}async move(e,t,r){return(await this.getInner()).move(e,t,r)}async exists(e,t){return(await this.getInner()).exists(e)}async list(e=1e3,t){return(await this.getInner()).list(e,t)}async update(e,t,r){return(await this.getInner()).update(e,t)}async getStream(e,t){return(await this.getInner()).getStream(e)}async getReadUrl(e,t){return(await this.getInner()).getReadUrl(e,t)}async getUploadUrl(e,t){return(await this.getInner()).getUploadUrl(e,t)}async getInner(){return this.inner?this.inner:(this.innerPromise??=this.buildInner(),this.inner=await this.innerPromise,this.inner)}async buildInner(){const e=await this.resolveDriveId(),{documentLibrary:t,hostname:r,siteId:n,sitePath:o,siteUrl:i,...s}=this.genericConfig;return new h({...s,...this.oneDriveAuth,driveId:e,...this.resolvedConfig.copyTimeoutMs!==void 0&&{copyTimeoutMs:this.resolvedConfig.copyTimeoutMs},...this.resolvedConfig.metaStorageConfig&&{metaStorageConfig:this.resolvedConfig.metaStorageConfig},metaStorage:this.meta,...this.resolvedConfig.publicByDefault!==void 0&&{publicByDefault:this.resolvedConfig.publicByDefault},...this.resolvedConfig.rootFolderPath!==void 0&&{rootFolderPath:this.resolvedConfig.rootFolderPath}})}async resolveDriveId(){const e=this.resolvedConfig;if(e.driveId)return e.driveId;const t=await this.resolveSiteId();if(e.documentLibrary){const n=await this.client.api(`/sites/${t}/drives`).get(),o=e.documentLibrary.toLowerCase(),i=(n.value??[]).find(s=>s.name===e.documentLibrary)??(n.value??[]).find(s=>s.name?.toLowerCase()===o||g(s.webUrl)?.toLowerCase()===o);return i?i.id:c(d.FILE_NOT_FOUND,`SharePoint storage: document library "${e.documentLibrary}" not found in site "${t}".`)}const r=await this.client.api(`/sites/${t}/drive`).get();return r?.id?r.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site "${t}" has no default drive.`)}async resolveSiteId(){const e=this.resolvedConfig;if(e.siteId)return e.siteId;let t,r;if(e.siteUrl?{hostname:t,sitePath:r}=v(e.siteUrl):e.hostname&&(t=e.hostname,r=e.sitePath??"/"),!t||!r)return c(d.BAD_REQUEST,"SharePoint storage: missing site targeting. Provide `driveId`, `siteId`, `siteUrl`, or `hostname` (+ `sitePath`).");const n=r==="/"?"":r.replace(/^\/+/,""),o=n?`/sites/${t}:/${n}`:`/sites/${t}`;let i;try{i=await this.client.api(o).get()}catch(s){return c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}" (${s instanceof Error?s.message:String(s)}).`)}return i?.id?i.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{T as default};
1
+ import{throwErrorCode as c,ERRORS as d}from"./ERRORS-BIBxE2oR.js";import h,{buildGraphClient as l}from"./OneDriveStorage-BJ3Kzxc5.js";import{B as I}from"./storage-0j5nCAUp.js";import u from"./SharePointMetaStorage-CHWrhgg2.js";const g=a=>{if(!a)return;const e=a.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},v=a=>{let e;try{e=new URL(a)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${a}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}};class T extends I{static name="sharepoint";checksumTypes=[];meta;client;inner;innerPromise;oneDriveAuth;resolvedConfig;constructor(e){super(e);const t=e.accessToken??process.env.SHAREPOINT_ACCESS_TOKEN??process.env.ONEDRIVE_ACCESS_TOKEN,r=e.clientCredentials??(()=>{const n=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,o=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,i=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(n&&o&&i)return{clientId:o,clientSecret:i,tenantId:n}})();this.oneDriveAuth={...e.client&&{client:e.client},...t!==void 0&&{accessToken:t},...r&&{clientCredentials:r},...e.oauth&&{oauth:e.oauth}},this.resolvedConfig={...e,...e.driveId??process.env.SHAREPOINT_DRIVE_ID?{driveId:e.driveId??process.env.SHAREPOINT_DRIVE_ID}:{},...e.siteId??process.env.SHAREPOINT_SITE_ID?{siteId:e.siteId??process.env.SHAREPOINT_SITE_ID}:{},...e.siteUrl??process.env.SHAREPOINT_SITE_URL?{siteUrl:e.siteUrl??process.env.SHAREPOINT_SITE_URL}:{},...e.hostname??process.env.SHAREPOINT_HOSTNAME?{hostname:e.hostname??process.env.SHAREPOINT_HOSTNAME}:{}},this.client=l(this.oneDriveAuth),this.meta=e.metaStorage??new u(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,t){return(await this.getInner()).create(e,t)}async write(e,t){return(await this.getInner()).write(e,t)}async delete(e,t){return(await this.getInner()).delete(e,t)}async get(e,t){return(await this.getInner()).get(e,t)}async copy(e,t,r){return(await this.getInner()).copy(e,t,r)}async move(e,t,r){return(await this.getInner()).move(e,t,r)}async exists(e,t){return(await this.getInner()).exists(e)}async list(e=1e3,t){return(await this.getInner()).list(e,t)}async update(e,t,r){return(await this.getInner()).update(e,t)}async getStream(e,t){return(await this.getInner()).getStream(e)}async getReadUrl(e,t){return(await this.getInner()).getReadUrl(e,t)}async getUploadUrl(e,t){return(await this.getInner()).getUploadUrl(e,t)}async getInner(){return this.inner?this.inner:(this.innerPromise??=this.buildInner(),this.inner=await this.innerPromise,this.inner)}async buildInner(){const e=await this.resolveDriveId(),{documentLibrary:t,hostname:r,siteId:n,sitePath:o,siteUrl:i,...s}=this.genericConfig;return new h({...s,...this.oneDriveAuth,driveId:e,...this.resolvedConfig.copyTimeoutMs!==void 0&&{copyTimeoutMs:this.resolvedConfig.copyTimeoutMs},...this.resolvedConfig.metaStorageConfig&&{metaStorageConfig:this.resolvedConfig.metaStorageConfig},metaStorage:this.meta,...this.resolvedConfig.publicByDefault!==void 0&&{publicByDefault:this.resolvedConfig.publicByDefault},...this.resolvedConfig.rootFolderPath!==void 0&&{rootFolderPath:this.resolvedConfig.rootFolderPath}})}async resolveDriveId(){const e=this.resolvedConfig;if(e.driveId)return e.driveId;const t=await this.resolveSiteId();if(e.documentLibrary){const n=await this.client.api(`/sites/${t}/drives`).get(),o=e.documentLibrary.toLowerCase(),i=(n.value??[]).find(s=>s.name===e.documentLibrary)??(n.value??[]).find(s=>s.name?.toLowerCase()===o||g(s.webUrl)?.toLowerCase()===o);return i?i.id:c(d.FILE_NOT_FOUND,`SharePoint storage: document library "${e.documentLibrary}" not found in site "${t}".`)}const r=await this.client.api(`/sites/${t}/drive`).get();return r?.id?r.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site "${t}" has no default drive.`)}async resolveSiteId(){const e=this.resolvedConfig;if(e.siteId)return e.siteId;let t,r;if(e.siteUrl?{hostname:t,sitePath:r}=v(e.siteUrl):e.hostname&&(t=e.hostname,r=e.sitePath??"/"),!t||!r)return c(d.BAD_REQUEST,"SharePoint storage: missing site targeting. Provide `driveId`, `siteId`, `siteUrl`, or `hostname` (+ `sitePath`).");const n=r==="/"?"":r.replace(/^\/+/,""),o=n?`/sites/${t}:/${n}`:`/sites/${t}`;let i;try{i=await this.client.api(o).get()}catch(s){return c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}" (${s instanceof Error?s.message:String(s)}).`)}return i?.id?i.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{T as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-DJDcuxf1.js";class o extends r{constructor(t){super(t)}}export{o as default};