@visulima/storage 1.0.0-alpha.30 → 1.0.0-alpha.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -0
- package/README.md +2 -2
- package/dist/adapter/nuxt/module.d.ts +4 -4
- package/dist/adapter/nuxt/node_modules/.bin/nuxi +2 -2
- package/dist/adapter/nuxt/node_modules/.bin/nuxt +2 -2
- package/dist/ai/ai-sdk/index.d.ts +3 -3
- package/dist/ai/claude/index.d.ts +2 -2
- package/dist/ai/openai/index.d.ts +3 -3
- package/dist/ai/tanstack/index.d.ts +2 -2
- package/dist/handler/http/fetch/index.d.ts +7 -7
- package/dist/handler/http/fetch/index.js +1 -1
- package/dist/handler/http/hono/index.d.ts +4 -4
- package/dist/handler/http/hono/index.js +1 -1
- package/dist/handler/http/nextjs/index.d.ts +4 -4
- package/dist/handler/http/nextjs/index.js +1 -1
- package/dist/handler/http/node/index.d.ts +7 -7
- package/dist/handler/http/node/index.js +1 -1
- package/dist/handler/http/solid-start/index.d.ts +4 -4
- package/dist/handler/http/solid-start/index.js +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +1 -1
- package/dist/packem_shared/{AwsLightStorage-w21RxjUm.js → AwsLightStorage-B1jNF7sv.js} +1 -1
- package/dist/packem_shared/AzureStorage-B4E6VLn5.js +1 -0
- package/dist/packem_shared/{BoxMetaStorage-DLdXbZaV.js → BoxMetaStorage-nESVquA1.js} +1 -1
- package/dist/packem_shared/BoxStorage-CHYDrcxw.js +1 -0
- package/dist/packem_shared/{BunS3MetaStorage-Bv_CTTMz.js → BunS3MetaStorage-BkZx5q4w.js} +1 -1
- package/dist/packem_shared/BunS3Storage-BopE7kmX.js +1 -0
- package/dist/packem_shared/{BunnyMetaStorage-DNMTSeoN.js → BunnyMetaStorage-bB8NXGUI.js} +1 -1
- package/dist/packem_shared/BunnyStorage-C3IBxJqr.js +1 -0
- package/dist/packem_shared/{CloudinaryMetaStorage-DEBk5eQy.js → CloudinaryMetaStorage-BzibHydK.js} +1 -1
- package/dist/packem_shared/CloudinaryStorage-Cj00ZXWV.js +1 -0
- package/dist/packem_shared/DiskStorage-BrAb28Je.js +1 -0
- package/dist/packem_shared/DiskStorageWithChecksum-BX85CHJ6.js +1 -0
- package/dist/packem_shared/{DropboxMetaStorage-C6vj1QDA.js → DropboxMetaStorage-Bfm5bblb.js} +1 -1
- package/dist/packem_shared/DropboxStorage-Btz9h9Mj.js +1 -0
- package/dist/packem_shared/Files-tnc_buzM.js +1 -0
- package/dist/packem_shared/{FirebaseMetaStorage-CzyOim-J.js → FirebaseMetaStorage-CshnJMb0.js} +1 -1
- package/dist/packem_shared/FirebaseStorage-Y9P6Dx8I.js +2 -0
- package/dist/packem_shared/{FtpMetaStorage-1Njy0DpU.js → FtpMetaStorage-CoyWJafY.js} +1 -1
- package/dist/packem_shared/FtpStorage-DCKPMX0z.js +1 -0
- package/dist/packem_shared/{GCSMetaStorage-udgXA5ia.js → GCSMetaStorage-CfZj52hQ.js} +1 -1
- package/dist/packem_shared/GCStorage-hfL1u2KQ.js +1 -0
- package/dist/packem_shared/{GoogleDriveMetaStorage-WGuUZPyx.js → GoogleDriveMetaStorage-CBSdEQr6.js} +1 -1
- package/dist/packem_shared/GoogleDriveStorage-C7iuV7qb.js +1 -0
- package/dist/packem_shared/{LocalMetaStorage-QMKL7McF.js → LocalMetaStorage-DSwsmdt7.js} +1 -1
- package/dist/packem_shared/MemoryMetaStorage-DEzfBNgL.js +1 -0
- package/dist/packem_shared/{Multipart-CIFfQksD.js → Multipart-kQ5wJQaV.js} +1 -1
- package/dist/packem_shared/{Multipart-D9WIud9R.js → Multipart-qaEOWKz1.js} +1 -1
- package/dist/packem_shared/{NetlifyBlobMetaStorage-ClIFdTkT.js → NetlifyBlobMetaStorage-CqluIgV0.js} +1 -1
- package/dist/packem_shared/NetlifyBlobStorage-CkMw9Uyv.js +1 -0
- package/dist/packem_shared/{OneDriveMetaStorage-DS4f83X2.js → OneDriveMetaStorage-DPTNMpeq.js} +1 -1
- package/dist/packem_shared/OneDriveStorage-CEGYb6OC.js +1 -0
- package/dist/packem_shared/{PocketBaseMetaStorage-B6utPncj.js → PocketBaseMetaStorage-CemTT_01.js} +1 -1
- package/dist/packem_shared/PocketBaseStorage-BZNzWj09.js +1 -0
- package/dist/packem_shared/{Rest-URrQ5FYM.js → Rest-BAcUFAgk.js} +1 -1
- package/dist/packem_shared/{Rest-BuD3ySAg.js → Rest-DukkeDZe.js} +1 -1
- package/dist/packem_shared/S3Storage-7hG3izjU.js +1 -0
- package/dist/packem_shared/{SftpMetaStorage-DYqXwCdM.js → SftpMetaStorage-Cs8b7uBO.js} +1 -1
- package/dist/packem_shared/SftpStorage-DnigT9GT.js +1 -0
- package/dist/packem_shared/{SharePointMetaStorage-DVM5-X6g.js → SharePointMetaStorage-DTVKAx6f.js} +1 -1
- package/dist/packem_shared/{SharePointStorage-BY90zh1c.js → SharePointStorage-D1cWu-14.js} +1 -1
- package/dist/packem_shared/{SupabaseMetaStorage-ivXoYVUu.js → SupabaseMetaStorage-D_fGv0d6.js} +1 -1
- package/dist/packem_shared/SupabaseStorage-DbIUa6NZ.js +1 -0
- package/dist/packem_shared/{Tus-Fp_hx5ug.js → Tus-BYTcw17H.js} +1 -1
- package/dist/packem_shared/{Tus-TNG9HAY8.js → Tus-BrP4RFTg.js} +1 -1
- package/dist/packem_shared/{UploadThingMetaStorage-BvKNzgm7.js → UploadThingMetaStorage-CAQ1uTfv.js} +1 -1
- package/dist/packem_shared/UploadThingStorage-B1qw1GrM.js +1 -0
- package/dist/packem_shared/{VercelBlobMetaStorage-CwaqWucZ.js → VercelBlobMetaStorage-DY4zAB6M.js} +1 -1
- package/dist/packem_shared/VercelBlobStorage-u6xmp8ox.js +1 -0
- package/dist/packem_shared/{base-handler-core-BYDQditz.js → base-handler-core-Ccvdhx-k.js} +1 -1
- package/dist/packem_shared/{base-handler-fetch-DWzsPkmV.js → base-handler-fetch-DzbThEWy.js} +1 -1
- package/dist/packem_shared/{base-handler-node-Dety2rQB.js → base-handler-node-CmCpLlBt.js} +1 -1
- package/dist/packem_shared/default-BrhEhSqN.js +1 -0
- package/dist/packem_shared/{defaultCloudStorageFileNameValidation-shIZX_7L.js → defaultCloudStorageFileNameValidation-DwDn0XB5.js} +1 -1
- package/dist/packem_shared/disk-storage-fWizVrge.js +1 -0
- package/dist/packem_shared/{disk-storage-with-checksum.d-mHcg2uLw.d.ts → disk-storage-with-checksum.d-aYBmkg45.d.ts} +8 -2
- package/dist/packem_shared/{executors.d-X4hz3zfu.d.ts → executors.d-WGJGPSZs.d.ts} +1 -1
- package/dist/packem_shared/{gcs-meta-storage-mZiqlX-9.js → gcs-meta-storage-COq32th7.js} +1 -1
- package/dist/packem_shared/get-file-status-DLS18Zvd.js +1 -0
- package/dist/packem_shared/index.d-CYdFIB-w.d.ts +455 -0
- package/dist/packem_shared/isRetryableError-CBZ65V6T.js +1 -0
- package/dist/packem_shared/local-meta-storage-Dr891Iy7.js +1 -0
- package/dist/packem_shared/{local-meta-storage.d-B11vHYNm.d.ts → local-meta-storage.d-CuvN-KQ3.d.ts} +1 -1
- package/dist/packem_shared/{media-transformer.d-C3QvECD7.d.ts → media-transformer.d-DfU7VbFl.d.ts} +2 -2
- package/dist/packem_shared/memory-storage.d-DRbE0WMO.d.ts +101 -0
- package/dist/packem_shared/part-match-D_NwyoF3.js +1 -0
- package/dist/packem_shared/{path-D7rMc9nq-B718mbm6.js → path-D7rMc9nq-CPbxyMDy.js} +1 -1
- package/dist/packem_shared/{rest-base-DI7xFXr5.js → rest-base-xrnOBxS9.js} +1 -1
- package/dist/packem_shared/s3-base-storage-CqAyWHR6.js +1 -0
- package/dist/packem_shared/{s3-base-storage.d-V3N2nKCt.d.ts → s3-base-storage.d-BrHiKWFw.d.ts} +9 -2
- package/dist/packem_shared/storage-uhIhcN-O.js +1 -0
- package/dist/packem_shared/{storage.d-RteRC-cG.d.ts → storage.d-X6TimMHY.d.ts} +42 -15
- package/dist/packem_shared/{tus-base.d-CygntIPM.d.ts → tus-base.d-Ds7xYAJC.d.ts} +3 -3
- package/dist/packem_shared/{types.d-cI_cMxcZ.d.ts → types.d-B72PbsLY.d.ts} +2 -2
- package/dist/packem_shared/{types.d-DxonY4XS.d.ts → types.d-C4QumoP1.d.ts} +2 -2
- package/dist/packem_shared/{types.d-ChNXbbHG.d.ts → types.d-a1grKnaX.d.ts} +1 -1
- package/dist/storage/aws/index.d.ts +9 -3
- package/dist/storage/aws/index.js +1 -1
- package/dist/storage/aws-light/index.d.ts +2 -2
- package/dist/storage/aws-light/index.js +1 -1
- package/dist/storage/azure/index.d.ts +1 -1
- package/dist/storage/azure/index.js +1 -1
- package/dist/storage/box/index.d.ts +2 -2
- package/dist/storage/box/index.js +1 -1
- package/dist/storage/bun-s3/index.d.ts +2 -2
- package/dist/storage/bun-s3/index.js +1 -1
- package/dist/storage/bunny/index.d.ts +2 -2
- package/dist/storage/bunny/index.js +1 -1
- package/dist/storage/cloudinary/index.d.ts +2 -2
- package/dist/storage/cloudinary/index.js +1 -1
- package/dist/storage/dropbox/index.d.ts +2 -2
- package/dist/storage/dropbox/index.js +1 -1
- package/dist/storage/firebase/index.d.ts +2 -2
- package/dist/storage/firebase/index.js +1 -1
- package/dist/storage/ftp/index.d.ts +2 -2
- package/dist/storage/ftp/index.js +1 -1
- package/dist/storage/gcs/index.d.ts +1 -1
- package/dist/storage/gcs/index.js +1 -1
- package/dist/storage/google-drive/index.d.ts +2 -2
- package/dist/storage/google-drive/index.js +1 -1
- package/dist/storage/local/index.d.ts +3 -3
- package/dist/storage/local/index.js +1 -1
- package/dist/storage/memory/index.d.ts +6 -0
- package/dist/storage/memory/index.js +1 -0
- package/dist/storage/netlify-blob/index.d.ts +2 -2
- package/dist/storage/netlify-blob/index.js +1 -1
- package/dist/storage/onedrive/index.d.ts +4 -4
- package/dist/storage/onedrive/index.js +1 -1
- package/dist/storage/pocketbase/index.d.ts +2 -2
- package/dist/storage/pocketbase/index.js +1 -1
- package/dist/storage/sftp/index.d.ts +2 -2
- package/dist/storage/sftp/index.js +1 -1
- package/dist/storage/sharepoint/index.d.ts +3 -3
- package/dist/storage/sharepoint/index.js +1 -1
- package/dist/storage/supabase/index.d.ts +2 -2
- package/dist/storage/supabase/index.js +1 -1
- package/dist/storage/uploadthing/index.d.ts +2 -2
- package/dist/storage/uploadthing/index.js +1 -1
- package/dist/storage/vercel-blob/index.d.ts +2 -2
- package/dist/storage/vercel-blob/index.js +1 -1
- package/dist/transformer/audio-transformer.d.ts +2 -2
- package/dist/transformer/image-transformer.d.ts +2 -2
- package/dist/transformer/index.d.ts +3 -3
- package/dist/transformer/video-transformer.d.ts +2 -2
- package/package.json +6 -2
- package/dist/packem_shared/AzureStorage-2kl7JDXs.js +0 -1
- package/dist/packem_shared/BoxStorage-BUeEJoGL.js +0 -1
- package/dist/packem_shared/BunS3Storage-WM3rF6Fw.js +0 -1
- package/dist/packem_shared/BunnyStorage-D3s2fRB3.js +0 -1
- package/dist/packem_shared/CloudinaryStorage-BBE2-aVz.js +0 -1
- package/dist/packem_shared/DiskStorage-DL0GiG6k.js +0 -1
- package/dist/packem_shared/DiskStorageWithChecksum-BvUTn7O-.js +0 -1
- package/dist/packem_shared/DropboxStorage-BL3OIdE_.js +0 -1
- package/dist/packem_shared/Files-CJh9_N-9.js +0 -1
- package/dist/packem_shared/FirebaseStorage-lXMXy3Pm.js +0 -2
- package/dist/packem_shared/FtpStorage-Dw94efNW.js +0 -1
- package/dist/packem_shared/GCStorage-ChY6uJuO.js +0 -1
- package/dist/packem_shared/GoogleDriveStorage-C0NhBBWH.js +0 -1
- package/dist/packem_shared/NetlifyBlobStorage-CO89TGvF.js +0 -1
- package/dist/packem_shared/OneDriveStorage-jAN46vRm.js +0 -1
- package/dist/packem_shared/PocketBaseStorage-DpOjOKAt.js +0 -1
- package/dist/packem_shared/S3Storage-n1ohEZj4.js +0 -1
- package/dist/packem_shared/SftpStorage-Ban-WN8v.js +0 -1
- package/dist/packem_shared/SupabaseStorage-pNbHAE1Y.js +0 -1
- package/dist/packem_shared/UploadThingStorage-BcmIE2dI.js +0 -1
- package/dist/packem_shared/VercelBlobStorage-s260zfFo.js +0 -1
- package/dist/packem_shared/disk-storage-CKAJvhcj.js +0 -1
- package/dist/packem_shared/index.d-C4Fivh4I.d.ts +0 -94
- package/dist/packem_shared/isRetryableError-BhizNeAz.js +0 -1
- package/dist/packem_shared/local-meta-storage-Bi0mK6gD.js +0 -1
- package/dist/packem_shared/part-match-B5fLLmFw.js +0 -1
- package/dist/packem_shared/s3-base-storage-Dbexfg7p.js +0 -1
- package/dist/packem_shared/storage-Dh0tJh7j.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var K=Object.defineProperty;var T=(s,t)=>K(s,"name",{value:t,configurable:!0});import{PassThrough as R,Readable as A}from"node:stream";import{B as O}from"./storage-uhIhcN-O.js";var H=Object.defineProperty,k=T((s,t)=>H(s,"name",{value:t,configurable:!0}),"h");const z=8,L=k(s=>typeof s=="object"&&s!==null&&typeof s.getReader=="function","isWebReadableStream"),C=k(s=>typeof s=="object"&&s!==null&&typeof s.pipe=="function"&&typeof s.read=="function","isNodeReadable"),j=k(async(s,t)=>{if(typeof s=="string"){const e=Buffer.from(s);return{size:e.byteLength,stream:A.from(e)}}if(Buffer.isBuffer(s))return{size:s.byteLength,stream:A.from(s)};if(s instanceof Uint8Array){const e=Buffer.from(s.buffer,s.byteOffset,s.byteLength);return{size:e.byteLength,stream:A.from(e)}}if(s instanceof ArrayBuffer){const e=Buffer.from(s);return{size:e.byteLength,stream:A.from(e)}}if(ArrayBuffer.isView(s)){const e=s,r=Buffer.from(e.buffer,e.byteOffset,e.byteLength);return{size:r.byteLength,stream:A.from(r)}}if(typeof Blob<"u"&&s instanceof Blob)return{size:s.size,stream:A.fromWeb(s.stream())};if(L(s))return{size:t,stream:A.fromWeb(s)};if(C(s))return{size:t,stream:s};throw new TypeError(`Unsupported body type: ${Object.prototype.toString.call(s)}`)},"normalizeBody"),M=k((s,t)=>({contentType:s.contentType??"application/octet-stream",etag:s.ETag,key:s.name||s.id||t||"",lastModified:s.modifiedAt??s.createdAt,metadata:s.metadata,size:typeof s.size=="number"?s.size:void 0}),"toFileObject"),F=k(s=>s?s.split("/").filter(t=>t.length>0).join("/"):"","normalizePrefix"),W=k((s,t)=>{if(!t&&!s.signal&&s.timeout===void 0&&s.retries===void 0)return;const e={...s};return t&&(t.signal!==void 0&&(e.signal=t.signal),t.timeout!==void 0&&(e.timeout=t.timeout),t.retries!==void 0&&(e.retries=t.retries)),s.signal&&t?.signal&&(e.signal=AbortSignal.any([s.signal,t.signal])),e},"mergeOperationOptions"),P=k(async(s,t,e)=>{const r=Array.from({length:s.length});let n=0,a=!1;const l=k(async()=>{for(;n<s.length;){if(a||e.signal?.aborted)return;const o=n;n+=1;try{const i=await t(s[o],o);r[o]={status:"fulfilled",value:i}}catch(i){r[o]={reason:i,status:"rejected"},e.stopOnError&&(a=!0)}}},"worker"),p=Math.max(1,Math.min(e.concurrency,s.length)),c=Array.from({length:p},()=>l());return await Promise.all(c),r},"runConcurrent"),w=k((s,t)=>t instanceof Error?{error:t,key:s}:{error:new Error(typeof t=="string"?t:"Unknown error",{cause:t}),key:s},"toBulkError"),I=k((s,t)=>{if(s)try{s(t)}catch{}},"safeInvoke");class V{static{T(this,"Files")}static{k(this,"Files")}adapter;defaults;hooks;prefix;constructor(t){this.adapter=t.adapter,this.defaults=t.defaults??{},this.hooks=t.hooks??{},this.prefix=F(t.prefix??"")}get raw(){return this.adapter.raw}resolveKey(t){return this.prefix?`${this.prefix}/${t}`:t}stripPrefix(t){const e=t.startsWith("/")?t.slice(1):t;if(!this.prefix)return e;const r=`${this.prefix}/`;return e.startsWith(r)?e.slice(r.length):null}mergeOptions(t,e){const r=W(this.defaults,t);if(!e||!this.hooks.onRetry)return r;const n=r?.retries,a=typeof n=="number"?{maxRetries:n}:{...n??{}},l=a.onRetry,p=this.hooks.onRetry;return a.onRetry=(c,o)=>{if(l)try{l(c,o)}catch{}try{const i=o instanceof Error?o:new Error(typeof o=="string"?o:"Unknown error",{cause:o});p({...e,attempt:c,error:i})}catch{}},{...r??{},retries:a}}emitAction(t,e){if(this.hooks.onAction)try{this.hooks.onAction({type:t,...e})}catch{}}emitError(t,e,r){if(this.hooks.onError)try{this.hooks.onError({error:r,type:t,...e})}catch{}}async withHooks(t,e,r){const n=Date.now();try{const a=await r();return this.emitAction(t,{...e,durationMs:Date.now()-n}),a}catch(a){const l=a instanceof Error?a:new Error(typeof a=="string"?a:"Unknown error",{cause:a});throw this.emitError(t,{...e,durationMs:Date.now()-n},l),l}}async upload(t,e,r){return Array.isArray(t)?this.uploadMany(t,e):this.uploadOne(t,e,r)}async uploadOne(t,e,r){return this.withHooks("upload",{key:t},async()=>{const n=this.resolveKey(t);O.assertSafeId(n);const{size:a,stream:l}=await j(e,r?.size),p=r?.size??a,c={...r?.metadata??{},name:n,...r?.contentType?{type:r.contentType}:{},...p===void 0?{}:{size:p}},o=this.mergeOptions(r,{key:t,type:"upload"}),i=r?.multipart,y=await this.adapter.create({contentType:r?.contentType,id:n,metadata:c,originalName:n,size:p,storageClass:r?.storageClass},o),d=this.adapter.reportsUploadProgress,f=!!r?.onProgress;let h=l;if(f&&!d){const x=r?.onProgress;let S=0;const u=new R;p!==void 0&&I(x,{loaded:0,total:p}),l.on("data",B=>{const E=typeof B=="string"?Buffer.byteLength(B):B.byteLength;S+=E,I(x,{loaded:S,total:p})}),l.pipe(u),h=u}const g={body:h,contentLength:p,id:y.id,start:0,...i!==void 0&&{multipart:i},...d&&f&&{onProgress:r?.onProgress}},b=await this.adapter.write(g,o),m=M(b,n),v=this.stripPrefix(m.key);return v!==null&&(m.key=v),m})}async uploadMany(t,e){const{concurrency:r=z,multipart:n,onProgress:a,stopOnError:l=!1,...p}=e??{},c=await P(t,async({body:y,key:d,...f})=>{const h=f.onProgress??(a?g=>a({...g,key:d}):void 0);return this.uploadOne(d,y,{...p,multipart:n,...f,...h&&{onProgress:h}})},{concurrency:r,signal:p.signal,stopOnError:l}),o=[],i=[];for(const[y,d]of c.entries()){const f=t[y];if(!d){i.push(w(f.key,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?o.push(d.value):i.push(w(f.key,d.reason))}return i.length>0?{errors:i,uploaded:o}:{uploaded:o}}async download(t,e){return Array.isArray(t)?this.downloadMany(t,e):this.downloadOne(t,e)}assertRangeSupported(t){if(t){if(!Number.isFinite(t.start)||t.start<0)throw new TypeError(`Invalid range.start: ${String(t.start)}`);if(t.end!==void 0&&(!Number.isFinite(t.end)||t.end<t.start))throw new TypeError(`Invalid range.end: ${String(t.end)}`);if(!this.adapter.supportsRange)throw new Error(`Adapter ${this.adapter.constructor.name} does not support range downloads`)}}async downloadOne(t,e){return this.withHooks("download",{key:t},async()=>{const r=this.resolveKey(t);O.assertSafeId(r),this.assertRangeSupported(e?.range);const n=this.mergeOptions(e,{key:t,type:"download"})??{},a=e?.range?{...n,range:e.range}:n,l=await this.adapter.get({id:r},a);return{body:l.content,contentType:l.contentType??"application/octet-stream",etag:l.ETag,key:t,lastModified:l.modifiedAt,metadata:l.metadata,size:typeof l.size=="number"?l.size:void 0}})}async downloadMany(t,e){const{concurrency:r=z,range:n,stopOnError:a=!1,...l}=e??{},p=await P(t,async i=>this.downloadOne(i,n?{...l,range:n}:l),{concurrency:r,signal:l.signal,stopOnError:a}),c=[],o=[];for(const[i,y]of p.entries()){const d=t[i];if(!y){o.push(w(d,new Error("Operation skipped (stopOnError)")));continue}y.status==="fulfilled"?c.push(y.value):o.push(w(d,y.reason))}return o.length>0?{downloaded:c,errors:o}:{downloaded:c}}async head(t,e){return Array.isArray(t)?this.headMany(t,e):this.headOne(t,e)}async headOne(t,e){return this.withHooks("head",{key:t},async()=>{const r=this.resolveKey(t);O.assertSafeId(r);const n=await this.adapter.getMeta(r,this.mergeOptions(e,{key:t,type:"head"})),a=M(n,r);return a.key=t,a})}async headMany(t,e){const{concurrency:r=z,stopOnError:n=!1,...a}=e??{},l=await P(t,async o=>this.headOne(o,a),{concurrency:r,signal:a.signal,stopOnError:n}),p=[],c=[];for(const[o,i]of l.entries()){const y=t[o];if(!i){c.push(w(y,new Error("Operation skipped (stopOnError)")));continue}i.status==="fulfilled"?p.push(i.value):c.push(w(y,i.reason))}return c.length>0?{errors:c,files:p}:{files:p}}async exists(t,e){return Array.isArray(t)?this.existsMany(t,e):this.existsOne(t,e)}async existsOne(t,e){return this.withHooks("exists",{key:t},async()=>{const r=this.resolveKey(t);return O.assertSafeId(r),this.adapter.exists({id:r},this.mergeOptions(e,{key:t,type:"exists"}))})}async existsMany(t,e){const{concurrency:r=z,stopOnError:n=!1,...a}=e??{},l=await P(t,async i=>this.existsOne(i,a),{concurrency:r,signal:a.signal,stopOnError:n}),p=[],c=[],o=[];for(const[i,y]of l.entries()){const d=t[i];if(!y){o.push(w(d,new Error("Operation skipped (stopOnError)")));continue}y.status==="fulfilled"?y.value?p.push(d):c.push(d):o.push(w(d,y.reason))}return o.length>0?{errors:o,existing:p,missing:c}:{existing:p,missing:c}}async delete(t,e){if(Array.isArray(t))return this.deleteMany(t,e);await this.deleteOne(t,e)}async deleteOne(t,e){await this.withHooks("delete",{key:t},async()=>{const r=this.resolveKey(t);O.assertSafeId(r),await this.adapter.delete({id:r},this.mergeOptions(e,{key:t,type:"delete"}))})}async deleteMany(t,e){const{concurrency:r=z,stopOnError:n=!1,...a}=e??{},l=this.mergeOptions(a,{keys:t,type:"delete"});if(!n&&typeof this.adapter.deleteBatch=="function"){const i=[],y=[],d=[];for(const f of t){const h=this.resolveKey(f);try{O.assertSafeId(h),i.push(f),y.push(h)}catch(g){d.push(w(f,g))}}return this.withHooks("delete",{keys:i},async()=>{const f=y.length>0?await this.adapter.deleteBatch(y,l):{failed:[],successful:[]},h=new Map(y.map((m,v)=>[m,v])),g=f.successful.map(m=>this.stripPrefix(m.id)??m.id),b=[...d,...f.failed.map(({error:m,id:v})=>{const x=h.get(v),S=x===void 0?v:i[x];return w(S,new Error(m))})];return b.length>0?{deleted:g,errors:b}:{deleted:g}})}const p=await P(t,async i=>this.deleteOne(i,a),{concurrency:r,signal:a.signal,stopOnError:n}),c=[],o=[];for(const[i,y]of p.entries()){const d=t[i];if(!y){o.push(w(d,new Error("Operation skipped (stopOnError)")));continue}y.status==="fulfilled"?c.push(d):o.push(w(d,y.reason))}return o.length>0?{deleted:c,errors:o}:{deleted:c}}async copy(t,e,r){return this.withHooks("copy",{from:t,to:e},async()=>{const n=this.resolveKey(t),a=this.resolveKey(e);O.assertSafeId(n),O.assertSafeId(a);const l=await this.adapter.copy(n,a,{...this.mergeOptions(r,{from:t,to:e,type:"copy"}),storageClass:r?.storageClass}),p=M(l,a);return p.key=e,p})}async move(t,e,r){return Array.isArray(t)?this.moveMany(t,e):this.moveOne(t,e,r)}async moveOne(t,e,r){return this.withHooks("move",{from:t,to:e},async()=>{const n=this.resolveKey(t);if(O.assertSafeId(n),t===e){const o=await this.adapter.getMeta(n,this.mergeOptions(r,{from:t,to:e,type:"move"})),i=M(o,n);return i.key=t,i}const a=this.resolveKey(e);O.assertSafeId(a);const l={...this.mergeOptions(r,{from:t,to:e,type:"move"}),...r?.storageClass!==void 0&&{storageClass:r.storageClass}},p=await this.adapter.move(n,a,l),c=M(p,a);return c.key=e,c})}async moveMany(t,e){const{concurrency:r=z,stopOnError:n=!1,...a}=e??{},l=await P(t,async({from:o,to:i})=>this.moveOne(o,i,a),{concurrency:r,signal:a.signal,stopOnError:n}),p=[],c=[];for(const[o,i]of l.entries()){const y=t[o];if(!i){c.push(w(y.from,new Error("Operation skipped (stopOnError)")));continue}i.status==="fulfilled"?p.push(i.value):c.push(w(y.from,i.reason))}return c.length>0?{errors:c,moved:p}:{moved:p}}async list(t={}){return this.withHooks("list",{},async()=>{const{limit:e,prefix:r,...n}=t,a=await this.adapter.list(e??1e3,this.mergeOptions(n,{type:"list"})),l=[];for(const p of a){const c=M(p),o=this.stripPrefix(c.key);o!==null&&(c.key=o,l.push(c))}return r?l.filter(p=>p.key.startsWith(r)):l})}async*listAll(t={}){const{limit:e,prefix:r,...n}=t,a=Math.max(1,e??1e3),l=Date.now(),p=new Set;let c;try{for(;;){const o=await this.adapter.list(a,this.mergeOptions(n,{type:"listAll"}));let i=0;for(const y of o){const d=M(y),f=this.stripPrefix(d.key);f!==null&&(d.key=f,!(r&&!d.key.startsWith(r))&&(p.has(d.key)||(p.add(d.key),i+=1,yield d)))}if(i===0||o.length<a)break}}catch(o){throw c=o instanceof Error?o:new Error(typeof o=="string"?o:"Unknown error",{cause:o}),c}finally{const o=Date.now()-l;c?this.emitError("listAll",{durationMs:o},c):this.emitAction("listAll",{durationMs:o})}}async url(t,e){return this.withHooks("url",{key:t},async()=>{const r=this.resolveKey(t);return O.assertSafeId(r),this.adapter.getReadUrl(r,{...this.mergeOptions(e,{key:t,type:"url"}),...e})})}async signedUploadUrl(t,e){return this.withHooks("signedUploadUrl",{key:t},async()=>{const r=this.resolveKey(t);return O.assertSafeId(r),this.adapter.getUploadUrl(r,{...this.mergeOptions(e,{key:t,type:"signedUploadUrl"}),...e})})}}const q=k(async(s,t,e={})=>{const{concurrency:r=z,limit:n,onProgress:a,overwrite:l=!1,prefix:p,signal:c,stopOnError:o=!1,transformKey:i}=e,y=[],d=[],f=[];let h=!1,g=0;const b=k(u=>{if(a)try{a(u)}catch{}},"emit"),m=s.listAll({...p!==void 0&&{prefix:p},...n!==void 0&&{limit:n}}),v=k(async u=>{if(h||c?.aborted)return;const B=i?i(u):u;try{if(!l&&await t.exists(B,{signal:c})){d.push(u),g+=1,b({done:g,key:u,status:"skipped"});return}const E=await s.download(u,{signal:c});await t.upload(B,E.body,{...E.contentType&&{contentType:E.contentType},...E.metadata&&{metadata:E.metadata},signal:c}),y.push(u),g+=1,b({done:g,key:u,status:"transferred"})}catch(E){const U=w(u,E);if(f.push(U),g+=1,b({done:g,error:U.error,key:u,status:"errored"}),o)throw h=!0,U.error}},"transferOne");if(o){try{for await(const u of m){if(h||c?.aborted)break;try{await v(u.key)}catch{break}}}finally{await m.return?.()}return f.length>0?{errors:f,skipped:d,transferred:y}:{skipped:d,transferred:y}}const x=Math.max(1,r),S=k(async()=>{for(;!h&&!c?.aborted;){const u=await m.next();if(u.done)return;await v(u.value.key)}},"worker");try{await Promise.all(Array.from({length:x},()=>S()))}finally{await m.return?.()}return f.length>0?{errors:f,skipped:d,transferred:y}:{skipped:d,transferred:y}},"transfer");export{V as Files,V as default,q as transfer};
|
package/dist/packem_shared/{FirebaseMetaStorage-CzyOim-J.js → FirebaseMetaStorage-CshnJMb0.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=Object.defineProperty;var r=(a,e)=>t(a,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-
|
|
1
|
+
var t=Object.defineProperty;var r=(a,e)=>t(a,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-Dr891Iy7.js";var o=Object.defineProperty,i=r((a,e)=>o(a,"name",{value:e,configurable:!0}),"a");class n extends s{static{r(this,"i")}static{i(this,"FirebaseMetaStorage")}constructor(e){super(e)}}export{n as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var g=Object.defineProperty;var m=(s,t)=>g(s,"name",{value:t,configurable:!0});import{readFileSync as w}from"node:fs";import{getApps as b,getApp as h,initializeApp as O,cert as k}from"firebase-admin/app";import{getStorage as A}from"firebase-admin/storage";import{throwErrorCode as d,ERRORS as f}from"./ERRORS-CyOuSMLY.js";import{B as T}from"./storage-uhIhcN-O.js";import o from"./FirebaseFile-JEu3plMP.js";import I from"./FirebaseMetaStorage-CshnJMb0.js";import{o as y}from"./get-file-status-DLS18Zvd.js";import{u as v}from"./update-size-DANV7aa2.js";import{r as S}from"./part-match-D_NwyoF3.js";import{o as _}from"./has-content-Bx2p8Okx.js";var N=Object.defineProperty,u=m((s,t)=>N(s,"name",{value:t,configurable:!0}),"l");const U=3600,R=u(async s=>{const t=[];for await(const i of s)t.push(Buffer.from(i));return Buffer.concat(t)},"collectStream"),B=u(s=>typeof s=="object"&&s!==null&&typeof s.file=="function"&&typeof s.getFiles=="function","isBucket");class E extends T{static name="firebase";checksumTypes=[];meta;bucket;bucketName;defaultUrlExpiresIn;publicBaseUrl;constructor(t){if(super(t),this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??U,this.publicBaseUrl=t.publicBaseUrl?.replace(/\/+$/,""),t.app&&B(t.app))this.bucket=t.app,this.bucketName=t.app.name??"";else{const i=t.bucket??process.env.FIREBASE_STORAGE_BUCKET;if(!i)throw new Error("Firebase storage: `bucket` is required (or set FIREBASE_STORAGE_BUCKET).");this.bucketName=i;const e=t.app??E.resolveApp(t,i);this.bucket=A(e).bucket(i)}this.meta=t.metaStorage??new I(t.metaStorageConfig),this.isReady=!0}get raw(){return this.bucket}async create(t,i){return this.instrumentOperation("create",async()=>{const e=new o(t);e.name=this.namingFunction(e),e.bucket=this.bucketName,e.path=e.name,await this.validate(e);try{const a=await this.getMeta(e.id);if(a.bytesWritten>=0)return a}catch{}return e.bytesWritten=0,e.status=y(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&&v(e,t.size),!S(t,e))throw new Error("File part does not match");const a=await this.lock(t.id);try{if(_(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await R(t.body),c=e.path??e.name;await this.runOperation(i,()=>this.bucket.file(c).save(r,{contentType:e.contentType,resumable:!1})),e.bytesWritten=r.length,e.size=r.length,e.path=c}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,a)}})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const a=e?.path??e?.name??t;return await this.runOperation(i,()=>this.bucket.file(a).delete({ignoreNotFound:!0})),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new o({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.bucketName,id:t,name:t,path:a,status:"deleted"})})}async exists({id:t},i){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}try{const[a]=await this.runOperation(i,()=>this.bucket.file(e).exists());return a}catch{return!1}})}async get({id:t},i){return this.instrumentOperation("get",async()=>{let e=t,a;try{a=await this.checkIfExpired(await this.getMeta(t)),e=a.path??a.name??t}catch{}const r=this.bucket.file(e),[c]=await this.runOperation(i,()=>r.download());let n={};try{[n]=await this.runOperation(i,()=>r.getMetadata())}catch{}return{content:c,contentType:a?.contentType??n.contentType??"application/octet-stream",ETag:a?.ETag??n.etag,expiredAt:a?.expiredAt,id:t,metadata:a?.metadata??{},modifiedAt:a?.modifiedAt??n.updated,name:a?.name??e,originalName:a?.originalName??e,size:a?.size??(n.size===void 0?c.length:Number(n.size))}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const a=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(a).copy(this.bucket.file(i)));const r=new o({contentType:"application/octet-stream",metadata:{},originalName:i});return r.id=i,r.name=i,r.path=i,r.bucket=this.bucketName,r})}async move(t,i,e){return this.instrumentOperation("move",async()=>{const a=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(a).move(i));const r=new o({contentType:"application/octet-stream",metadata:{},originalName:i});r.id=i,r.name=i,r.path=i,r.bucket=this.bucketName;try{await this.deleteMeta(t)}catch{}return r})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const[e]=await this.runOperation(i,()=>this.bucket.getFiles({maxResults:t}));return(e??[]).map(a=>{const r=new o({contentType:"application/octet-stream",metadata:{},originalName:a.name});return r.id=a.name,r.name=a.name,r.path=a.name,r.bucket=this.bucketName,r})},{limit:t})}async getReadUrl(t,i){if(this.publicBaseUrl)return`${this.publicBaseUrl}/${t}`;const e=i?.expiresIn??this.defaultUrlExpiresIn;try{const[a]=await this.bucket.file(t).getSignedUrl({action:"read",expires:Date.now()+e*1e3});return a}catch(a){return d(f.METHOD_NOT_ALLOWED,a instanceof Error?a.message:"Firebase: getSignedUrl failed")}}async getUploadUrl(t,i){const e=i?.expiresIn??this.defaultUrlExpiresIn;try{const[a]=await this.bucket.file(t).getSignedUrl({action:"write",contentType:i?.contentType,expires:Date.now()+e*1e3});return a}catch(a){return d(f.METHOD_NOT_ALLOWED,a instanceof Error?a.message:"Firebase: getSignedUrl failed")}}static resolveApp(t,i){const{appName:e}=t,a=b();if(e?a.find(p=>p.name===e):a[0])return e?h(e):h();const r=t.projectId??process.env.FIREBASE_PROJECT_ID??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT;let c=t.credentials?.clientEmail??process.env.FIREBASE_CLIENT_EMAIL,n=t.credentials?.privateKey??process.env.FIREBASE_PRIVATE_KEY;const l=t.serviceAccountPath??process.env.GOOGLE_APPLICATION_CREDENTIALS;if((!c||!n)&&l){const p=JSON.parse(w(l,"utf8"));c??=p.client_email,n??=p.private_key}if(!c||!n)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 O({credential:k({clientEmail:c,privateKey:n.replaceAll(String.raw`\n`,`
|
|
2
|
+
`),projectId:r}),projectId:r,storageBucket:i},e)}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=u(t=>this.deleteMeta(t.id),"internalOnComplete")}export{E as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-Dr891Iy7.js";var o=Object.defineProperty,c=a((t,e)=>o(t,"name",{value:e,configurable:!0}),"e");class i extends s{static{a(this,"p")}static{c(this,"FtpMetaStorage")}constructor(e){super(e)}}export{i as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var F=Object.defineProperty;var O=(o,a)=>F(o,"name",{value:a,configurable:!0});import{Readable as w,Writable as v}from"node:stream";import{Client as M}from"basic-ftp";import{S as k}from"./index-B4ETk0Lu.js";import{throwErrorCode as u,ERRORS as m}from"./ERRORS-CyOuSMLY.js";import{B as E}from"./storage-uhIhcN-O.js";import P from"./FtpFile-B8jaICTB.js";import A from"./FtpMetaStorage-CoyWJafY.js";import{i as y,n as $,o as D}from"./posix-dirname-CiHXPPnw.js";import{o as b}from"./get-file-status-DLS18Zvd.js";import{u as R}from"./update-size-DANV7aa2.js";import{r as L}from"./part-match-D_NwyoF3.js";import{o as S}from"./has-content-Bx2p8Okx.js";var x=Object.defineProperty,p=O((o,a)=>x(o,"name",{value:a,configurable:!0}),"u");const d=p(o=>{const a=o?.code;if(a===550||a===450||a===553)return!0;const e=o instanceof Error?o.message:String(o);return/no such file|not exist|cannot find|file unavailable/i.test(e)},"isNotFoundError"),g=p(o=>{if(o instanceof Error&&o.name==="AbortError")return o;const a=new Error(o instanceof Error&&o.message?o.message:"The operation was aborted",{cause:o});return a.name="AbortError",a},"toAbortError"),T=p(async(o,a)=>{const e=[],t=new v({write(n,r,i){e.push(Buffer.from(n)),i()}});return await o.downloadTo(t,a),Buffer.concat(e)},"downloadToBuffer");class J extends E{static name="ftp";checksumTypes=[];meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=y(a.rootFolderPath??""),this.meta=a.metaStorage??new A(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new P(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=b(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&&R(t,a.size),!L(a,t))return u(m.FILE_CONFLICT);const n=await this.lock(a.id);try{if(S(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 r=await $(a.body),i=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,c=>this.run(c,async s=>{await this.ensureRemoteDirectory(s,i),await s.uploadFrom(w.from(r),i)})),t.bytesWritten=r.length,t.size=r.length,t.path=i,t.ETag=k(r)}return t.status=b(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),r=await this.runOperation(e,i=>this.run(i,async c=>{try{return await T(c,n)}catch(s){if(d(s))return u(m.FILE_NOT_FOUND);throw s}}));return{content:r,contentType:t.contentType,ETag:t.ETag??k(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size: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,i=>this.run(i,async c=>{try{await c.remove(n)}catch(s){if(!d(s))throw s}})),await this.deleteMeta(a);const r={...t,status:"deleted"};return await this.onDelete(r),r})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async h=>{const f=await T(h,r);await this.ensureRemoteDirectory(h,i),await h.uploadFrom(w.from(f),i)}));const c={...n,id:e,name:e,path:i};return await this.saveMeta(c),c})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async h=>{try{await this.ensureRemoteDirectory(h,i),await h.rename(r,i)}catch(f){try{const l=await T(h,r);await this.ensureRemoteDirectory(h,i),await h.uploadFrom(w.from(l),i),await h.remove(r)}catch(l){throw new AggregateError([f,l],`FTP move failed: rename and copy+delete fallback both failed for "${r}" → "${i}"`)}}}));const c={...n,id:e,name:e,path:i};await this.saveMeta(c);try{await this.deleteMeta(a)}catch{}return c})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,n=>this.run(n,async r=>{const i=[];return await this.walkList(r,t,i),i}))})}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,r=>this.run(r,async i=>{try{return await i.size(n),!0}catch(c){if(d(c))return!1;throw c}}))})}async walkList(a,e,t){let n;try{n=await a.list(e||".")}catch(r){if(d(r))return;throw r}for(const r of n){const i=e?`${e}/${r.name}`:r.name;if(r.isDirectory){await this.walkList(a,i,t);continue}if(!r.isFile)continue;const c=this.pathToKey(i);if(!c)continue;const s=new P({contentType:"application/octet-stream",metadata:{},originalName:r.name});s.id=c,s.name=c,s.path=i,s.size=r.size,r.modifiedAt&&(s.modifiedAt=r.modifiedAt.toISOString()),t.push(s)}}async run(a,e){const t=new M;if(a?.aborted)throw g(a.reason);const n=p(()=>{t.close()},"onAbort");a?.addEventListener("abort",n,{once:!0});try{if(await t.access(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(r){throw a?.aborted?g(r):r}finally{a?.removeEventListener("abort",n),t.close()}}async ensureRemoteDirectory(a,e){const t=D(e);t&&(await a.ensureDir(t),await a.cd("/"))}keyToPath(a){const e=y(a);e&&E.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":`/${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{J as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"node:crypto";import"gaxios";import"google-auth-library";import{E as f}from"./gcs-meta-storage-
|
|
1
|
+
import"node:crypto";import"gaxios";import"google-auth-library";import{E as f}from"./gcs-meta-storage-COq32th7.js";import"./MetaStorage-Y4m1dWgd.js";import"./Metadata-B6Ir0KO7.js";import"./GCSConfig-BQ0OpVhe.js";export{f as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var y=Object.defineProperty;var h=(l,t)=>y(l,"name",{value:t,configurable:!0});import{randomUUID as w}from"node:crypto";import{request as b}from"gaxios";import{GoogleAuth as C}from"google-auth-library";import{r as R,E,b as U,g as k,d}from"./gcs-meta-storage-COq32th7.js";import{d as $}from"./detect-file-type-5JhzC9RU.js";import{throwErrorCode as I,ERRORS as S}from"./ERRORS-CyOuSMLY.js";import{B as v,t as O}from"./storage-uhIhcN-O.js";import{v as T}from"./local-meta-storage-Dr891Iy7.js";import m from"./GCSConfig-BQ0OpVhe.js";import B from"./GCSFile-CDQ6IWAz.js";import{r as A}from"./part-match-D_NwyoF3.js";import{o as j}from"./has-content-Bx2p8Okx.js";import{o as x}from"./get-file-status-DLS18Zvd.js";var P=Object.defineProperty,G=h((l,t)=>P(l,"name",{value:t,configurable:!0}),"e");class q extends Error{static{h(this,"o")}constructor(t,a,e){super(t),this.code=a,this.config=e}code;config;static{G(this,"FetchError")}name="FetchError"}var W=Object.defineProperty,g=h((l,t)=>W(l,"name",{value:t,configurable:!0}),"m");const M=g(l=>l>=200&&l<300||l===308||l===499,"validateStatus");class f extends v{static name="gcs";checksumTypes=["md5","crc32c"];get raw(){return this.authClient}meta;bucket;authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;constructor(t){super(t);const a=t.bucket||process.env.GCS_BUCKET;if(!a)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=a,this.storageBaseURI=`${t.storageAPI||m.storageAPI}/${this.bucket}/o`,this.uploadBaseURI=`${t.uploadAPI||m.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={...R,...e},t.scopes||=m.authScopes,this.authClient=new C(t);const{bucket:o,metaStorage:c,metaStorageConfig:u,projectId:s}=t;if(c)this.meta=c;else{let n={...t,...u,logger:this.logger};"directory"in n?(this.logger?.debug("Using local meta storage"),this.meta=new T(n)):(o===n.bucket&&s===n.projectId&&(n={...n,authClient:this.authClient}),this.meta=new E(n))}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(n=>{this.logger?.error("Storage access check failed: %O",n)})}normalizeError(t){if(t.config){const a=+t.code||500;return{code:`GCS${a}`,message:t.message,name:t.name,retryable:a>=499,statusCode:a}}return{code:"GenericUploadError",message:`[${this.constructor.name}] ${t.message}`,name:t.name,statusCode:500}}async create(t,a){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const s=typeof t.ttl=="string"?O(t.ttl):t.ttl;s!==void 0&&(e.expiredAt=Date.now()+s)}const r=new B(e);r.name=this.namingFunction(r),await this.validate(r);try{const s=await this.getMeta(r.id);return s.bytesWritten=await this.internalWrite(s,a),s}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},o={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(o,a);if(c.status!==200)throw new Error("Expected 200 response from GCS");const u=c.headers.get("X-Goog-Upload-Status")||c.headers.get("x-goog-upload-status");if(u!=="active")throw new Error(`X-Goog-Upload-Status response header expected 'active' got: ${u}`);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,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(!A(t,e))return I(S.FILE_CONFLICT);const r=await this.lock(t.id);try{if(j(t)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:i,stream:o}=await $(t.body);i?.mime&&(e.contentType=i.mime),t.body=o}catch{}e.bytesWritten=await this.internalWrite({...e,...t},a),e.status=x(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},a){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:M},a),await this.deleteMeta(e.id);const r={...e};return await this.onDelete(r),r})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const r=new URL(`/${this.bucket}/${t}`,"file://"),i=new URL(encodeURI(a),r).pathname,[,o,...c]=i.split("/"),u=c.join("/"),s=`${this.storageBaseURI}/${t}/rewriteTo/b/${o}/o/${u}`;let n={};const p={body:"",headers:{"Content-Type":"application/json"},method:"POST",url:s};do p.body=n.rewriteToken?JSON.stringify({rewriteToken:n.rewriteToken}):"",n=(await this.makeRequest(p,e)).data||{};while(n.rewriteToken);return await this.getMeta(a)})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const r=await this.copy(t,a,e),i=`${this.storageBaseURI}/${t}`;return await this.makeRequest({method:"DELETE",url:i},e),r})}async get({id:t},a){return this.instrumentOperation("get",async()=>{const{data:e}=await this.makeRequest({params:{alt:"json"},url:`${this.storageBaseURI}/${t}`},a);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},a)).data;let i;if(typeof r=="string")i=Buffer.from(r,"utf8");else if(r&&typeof r=="object"&&"data"in r){const o=r.data;i=Buffer.from(o)}else i=Buffer.from(r);return{...e,content:i}})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{try{return await this.getMeta(t),await this.makeRequest({method:"HEAD",url:`${this.storageBaseURI}/${t}`},a),!0}catch{return!1}})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const e=[],r=Math.min(t,1e3);let i=!0,o={params:{maxResults:r},url:this.storageBaseURI};for(;i&&e.length<t;)try{const{data:c}=await this.makeRequest(o,a);for(const{name:u,timeCreated:s,updated:n}of c?.items||[]){if(e.length>=t)break;e.push({createdAt:s,id:u,modifiedAt:n})}i=c?.nextPageToken!==void 0,i&&e.length<t&&(o={...o,params:{...o.params,maxResults:Math.min(r,t-e.length),pageToken:c.nextPageToken}})}catch(c){const u=this.normalizeError(c instanceof Error?c:new Error(String(c)));throw await this.onError(u),c}return e},{limit:t})}async internalWrite(t,a){const{body:e,bytesWritten:r,size:i,uri:o=""}=t,c=U(t),u={method:"PUT"};if(e?.on){const s=new AbortController;e.on("aborted",()=>{s.abort()}),u.body=e,u.signal=s.signal,u.retry=!1}u.headers={Accept:"application/json","Content-Range":c,...i===r?{"X-Goog-Upload-Command":"upload, finalize"}:{}};try{const s=await this.makeRequest({url:o,...u},a);if(s.status===308){const n=s.headers.get("range");return n?k(n):0}if(s.status===200)return this.logger?.debug("uploaded %O",s.data),i;throw new q(String(s.data),`GCS${s.status}`,{uri:o})}catch(s){this.logger?.error(o,s);const n=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(n),s}}internalOnComplete=g(t=>this.deleteMeta(t.id),"internalOnComplete");static buildCallSignal(t,a){const e=[];if(a&&e.push(a),t?.signal&&e.push(t.signal),e.length!==0)return e.length===1?e[0]:AbortSignal.any(e)}async makeRequest(t,a){typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":"));const e=f.buildCallSignal(a,t.signal);let r=this.retryOptions;if(a?.retries!==void 0){const o=typeof a.retries=="number"?a.retries:a.retries.maxRetries;typeof o=="number"&&(r={...this.retryOptions,retry:o})}const i=typeof a?.timeout=="number"&&a.timeout>0?a.timeout:6e4;return t={...t,headers:{"User-Agent":`${d.name}/${d.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${d.version} gccl-invocation-id/${w()}`,...t.headers},params:{...this.userProject===void 0?{}:{userProject:this.userProject},...t.params},retry:t.retry===!1?!1:a?.retries!==0,retryConfig:r,timeout:i,...e?{signal:e}:{}},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?b(t):this.authClient.request(t)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}}export{f as default};
|
package/dist/packem_shared/{GoogleDriveMetaStorage-WGuUZPyx.js → GoogleDriveMetaStorage-CBSdEQr6.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-
|
|
1
|
+
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-Dr891Iy7.js";var s=Object.defineProperty,c=t((r,e)=>s(r,"name",{value:e,configurable:!0}),"t");class u extends o{static{t(this,"l")}static{c(this,"GoogleDriveMetaStorage")}constructor(e){super(e)}}export{u as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var C=Object.defineProperty;var y=(r,e)=>C(r,"name",{value:e,configurable:!0});import{Readable as k}from"node:stream";import{drive as F}from"@googleapis/drive";import{JWT as T,GoogleAuth as E,OAuth2Client as _}from"google-auth-library";import{throwErrorCode as v,ERRORS as u,wrapStorageError as I}from"./ERRORS-CyOuSMLY.js";import{B as L}from"./storage-uhIhcN-O.js";import m from"./GoogleDriveFile-D0aGfGbL.js";import G from"./GoogleDriveMetaStorage-CBSdEQr6.js";import{o as O}from"./get-file-status-DLS18Zvd.js";import{u as A}from"./update-size-DANV7aa2.js";import{r as R}from"./part-match-D_NwyoF3.js";import{o as P}from"./has-content-Bx2p8Okx.js";var B=Object.defineProperty,c=y((r,e)=>B(r,"name",{value:e,configurable:!0}),"u");const f="https://www.googleapis.com/auth/drive",U=1024,p="fsdkKey",w="fsdkContentType",D="id, name, size, mimeType, md5Checksum, modifiedTime, appProperties",g=c(r=>{const e=r.lastIndexOf("/");return e===-1?r:r.slice(e+1)},"basename"),b=c(r=>r.replaceAll("\\","\\\\").replaceAll("'",String.raw`\'`),"escapeQueryValue");class z{static{y(this,"S")}static{c(this,"LRU")}#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 S=c(r=>{const e=r.subject??process.env.GOOGLE_DRIVE_SUBJECT;if(r.credentials)return new T({email:r.credentials.client_email,key:r.credentials.private_key,scopes:[f],...e&&{subject:e}});if(r.keyFilename)return new E({keyFile:r.keyFilename,scopes:[f],...e&&{clientOptions:{subject:e}}});if(r.oauth){const a=new _({clientId:r.oauth.clientId,clientSecret:r.oauth.clientSecret});return a.setCredentials({refresh_token:r.oauth.refreshToken}),a}const i=process.env.GOOGLE_DRIVE_CLIENT_EMAIL,t=process.env.GOOGLE_DRIVE_PRIVATE_KEY;if(i&&t)return new T({email:i,key:t,scopes:[f],...e&&{subject:e}});const o=process.env.GOOGLE_DRIVE_KEY_FILE;if(o)return new E({keyFile:o,scopes:[f],...e&&{clientOptions:{subject:e}}})},"buildAuth"),x=c(async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},"collectStream"),M=c(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")},"toUint8");class ee extends L{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=S(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=F({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 z(e.fileIdCacheSize??U),this.sharedDriveParams={includeItemsFromAllDrives:!0,supportsAllDrives:!0,...i&&{corpora:"drive",driveId:i}},this.meta=e.metaStorage??new G(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=O(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&&A(t,e.size),!R(e,t))throw new Error("File part does not match");const o=await this.lock(e.id);try{if(P(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await x(e.body),n=t.name||t.id,s={[w]:t.contentType,[p]:n},l=await this.runOperation(i,()=>this.driveClient.files.create({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum, modifiedTime",media:{body:k.from(a),mimeType:t.contentType},requestBody:{appProperties:s,mimeType:t.contentType,name:g(n),parents:[this.rootFolderId]}})),{data:d}=l,h=d.id??void 0;h&&(this.fileIdCache.set(n,h),this.publicByDefault&&await this.runOperation(i,()=>this.driveClient.permissions.create({...this.sharedDriveParams,fileId:h,requestBody:{role:"reader",type:"anyone"}}))),t.bytesWritten=a.length,t.size=a.length,t.driveFileId=h,t.mimeType=d.mimeType??t.contentType,t.ETag=d.md5Checksum??void 0}return t.status=O(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 a=t?.driveFileId??await this.resolveFileId(o,i);await this.runOperation(i,()=>this.driveClient.files.delete({...this.sharedDriveParams,fileId:a})),this.fileIdCache.delete(o)}catch(a){if(!N(a))throw a;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[a,n]=await Promise.all([this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,fields:D,fileId:o})),this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,alt:"media",fileId:o},{responseType:"arraybuffer"}))]),{data:s}=a,l=M(n.data),d=Buffer.from(l.buffer,l.byteOffset,l.byteLength),h=s.appProperties??{};return{content:d,contentType:t?.contentType??h[w]??s.mimeType??"application/octet-stream",ETag:t?.ETag??s.md5Checksum??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??s.modifiedTime??void 0,name:t?.name??s.name??e,originalName:t?.originalName??s.name??e,size:t?.size??Number(s.size??d.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const o=await this.resolveFileId(e,t),a=await this.runOperation(t,()=>this.driveClient.files.copy({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum",fileId:o,requestBody:{appProperties:{[p]:i},name:g(i),parents:[this.rootFolderId]}})),n=a.data.id??void 0;n&&this.fileIdCache.set(i,n);const s=new m({contentType:a.data.mimeType??"application/octet-stream",metadata:{},originalName:i});return s.id=i,s.name=i,s.driveFileId=n,s.mimeType=a.data.mimeType??void 0,s.ETag=a.data.md5Checksum??void 0,s.size=Number(a.data.size??0),s})}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=`'${b(this.rootFolderId)}' in parents and trashed=false`,o=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:`nextPageToken, files(${D})`,pageSize:e,q:t}))).data.files??[],a=[];for(const n of o){const s=n.appProperties??{},l=s[p];if(!l)continue;n.id&&this.fileIdCache.set(l,n.id);const d=new m({contentType:s[w]??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,a.push(d)}return a},{limit:e})}async getReadUrl(e,i){return i?.responseContentDisposition?v(u.METHOD_NOT_ALLOWED,"Google Drive: `responseContentDisposition` is not supported — Drive's webContentLink has no Content-Disposition override."):this.publicByDefault?`https://drive.google.com/uc?export=download&id=${await this.resolveFileId(e)}`:v(u.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(!this.authForTokens)return v(u.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 a={Authorization:`Bearer ${o}`,"Content-Type":"application/json; charset=UTF-8"};i?.contentType&&(a["X-Upload-Content-Type"]=i.contentType),i?.contentLength!==void 0&&(a["X-Upload-Content-Length"]=String(i.contentLength));const n={appProperties:{[p]:e},name:g(e),parents:[this.rootFolderId]},s=await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",{body:JSON.stringify(n),headers:a,method:"POST"});if(!s.ok){const d=await s.text().catch(()=>"");throw I(new Error(`${s.statusText} ${d}`.trim()||s.statusText),{adapter:"Google Drive",operation:"resumable upload session",status:s.status})}const l=s.headers.get("location")??s.headers.get("Location");if(!l)throw I(new Error("response missing Location header"),{adapter:"Google Drive",code:u.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='${p}' and value='${b(e)}' } and trashed=false`,a=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:"files(id)",pageSize:2,q:o}))).data.files??[];if(a.length===0)throw new Error(`Google Drive: not found: ${e}`);if(a.length>1)throw new Error(`Google Drive: multiple files share virtual key '${e}'. Resolve via storage.raw.`);const n=a[0]?.id;if(!n)throw new Error(`Google Drive: list returned no fileId for ${e}`);return this.fileIdCache.set(e,n),n}internalOnComplete=c(e=>this.deleteMeta(e.id),"internalOnComplete")}const N=c(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},"isNotFoundError");export{ee as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"node:fs/promises";import"node:os";import{v as f}from"./local-meta-storage-
|
|
1
|
+
import"node:fs/promises";import"node:os";import{v as f}from"./local-meta-storage-Dr891Iy7.js";import"./path-D7rMc9nq-CPbxyMDy.js";import"./ERRORS-CyOuSMLY.js";import"./MetaStorage-Y4m1dWgd.js";import"./Metadata-B6Ir0KO7.js";export{f as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var o=Object.defineProperty;var s=(r,e)=>o(r,"name",{value:e,configurable:!0});import a from"./MetaStorage-Y4m1dWgd.js";var n=Object.defineProperty,c=s((r,e)=>n(r,"name",{value:e,configurable:!0}),"o");class h extends a{static{s(this,"a")}static{c(this,"MemoryMetaStorage")}store;constructor(e){super(e),this.store=e?.store??new Map}async save(e,t){return this.store.set(e,{...t}),{...t}}async get(e){const t=this.store.get(e);if(!t)throw new Error(`Meta not found for id: ${e}`);return{...t}}async delete(e){this.store.delete(e)}async touch(e,t){return this.save(e,t)}clear(){this.store.clear()}}export{h as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var l=Object.defineProperty;var d=(s,t)=>l(s,"name",{value:t,configurable:!0});import{Readable as a}from"node:stream";import{parseMultipartRequest as m,MaxFileSizeExceededError as u,MultipartParseError as f}from"@remix-run/multipart-parser/node";import{n as i}from"./headers-DC2MEOrK.js";import{g as h}from"./base-handler-core-
|
|
1
|
+
var l=Object.defineProperty;var d=(s,t)=>l(s,"name",{value:t,configurable:!0});import{Readable as a}from"node:stream";import{parseMultipartRequest as m,MaxFileSizeExceededError as u,MultipartParseError as f}from"@remix-run/multipart-parser/node";import{n as i}from"./headers-DC2MEOrK.js";import{g as h}from"./base-handler-core-Ccvdhx-k.js";import{b as c}from"./storage-uhIhcN-O.js";import{F as p}from"./base-handler-node-CmCpLlBt.js";import{F as g}from"./multipart-base-BxckfvQf.js";var x=Object.defineProperty,F=d((s,t)=>x(s,"name",{value:t,configurable:!0}),"d");const S=/^multipart\/.+|application\/x-www-form-urlencoded$/i;class O extends p{static{d(this,"x")}static{F(this,"Multipart")}static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const e=this;this.multipartBase=new class extends g{get storage(){return e.storage}get maxFileSize(){return e.maxFileSize}get maxHeaderSize(){return e.maxHeaderSize}buildFileUrl(r,o){return e.buildFileUrl({url:r},o)}createStreamFromBytes(r){return r instanceof Uint8Array||Buffer.isBuffer(r)?a.from(Buffer.from(r)):typeof r=="number"?a.from(Buffer.alloc(0)):a.from(Buffer.from(String(r)))}createEmptyStream(){return a.from(new Uint8Array(0))}}}async post(t){if(!S.test(t.headers["content-type"]?.split(";")[0]??""))throw i(400,"Invalid content-type");try{const e=[];for await(const n of m(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(n);const r=e.find(n=>n.isFile);if(!r)throw i(400,"No file found in multipart request");const o=t.originalUrl||t.url||"";return this.multipartBase.handlePost(r,e,o)}catch(e){throw e instanceof u?i(413,"File size limit exceeded"):e instanceof f?i(400,"Invalid multipart request"):e instanceof c&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){try{const e=h(t);return this.multipartBase.handleDelete(e)}catch(e){throw this.checkForUndefinedIdOrPath(e),e.code==="ENOENT"?i(404,"File not found"):e}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{O as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var u=Object.defineProperty;var l=(s,t)=>u(s,"name",{value:t,configurable:!0});import{Readable as o}from"node:stream";import{parseMultipartRequest as c,MaxFileSizeExceededError as f,MultipartParseError as p}from"@remix-run/multipart-parser";import{n as i}from"./headers-DC2MEOrK.js";import{b as g,B as x}from"./storage-
|
|
1
|
+
var u=Object.defineProperty;var l=(s,t)=>u(s,"name",{value:t,configurable:!0});import{Readable as o}from"node:stream";import{parseMultipartRequest as c,MaxFileSizeExceededError as f,MultipartParseError as p}from"@remix-run/multipart-parser";import{n as i}from"./headers-DC2MEOrK.js";import{b as g,B as x}from"./storage-uhIhcN-O.js";import{O as S}from"./base-handler-fetch-DzbThEWy.js";import{F as y}from"./multipart-base-BxckfvQf.js";var w=Object.defineProperty,d=l((s,t)=>w(s,"name",{value:t,configurable:!0}),"l");const z=/^multipart\/.+|application\/x-www-form-urlencoded$/i,F=d(s=>{let t;try{const r=new URL(s).pathname.split("/").filter(Boolean);t=r[r.length-1]||void 0}catch{return}if(t){try{x.assertSafeId(t)}catch{throw i(400,`Invalid file id: "${t}"`)}return t}},"getIdFromRequestUrl");class m extends S{static{l(this,"d")}static{d(this,"Multipart")}static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const r=this;this.multipartBase=new class extends y{get storage(){return r.storage}get maxFileSize(){return r.maxFileSize}get maxHeaderSize(){return r.maxHeaderSize}buildFileUrl(e,a){return r.buildFileUrl({url:e},a)}createStreamFromBytes(e){return e instanceof Uint8Array?o.from(Buffer.from(e)):e instanceof ArrayBuffer?o.from(Buffer.from(e)):o.from(new Uint8Array(0))}createEmptyStream(){return o.from(new Uint8Array(0))}}}async post(t){const r=t.headers.get("content-type")||"";if(!z.test(r.split(";")[0]||""))throw i(400,"Invalid content-type");try{const e=[];for await(const n of c(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(n);const a=e.find(n=>n.isFile);if(!a)throw i(400,"No file found in multipart request");const h=t.url;return this.multipartBase.handlePost(a,e,h)}catch(e){throw e instanceof f?i(413,"File size limit exceeded"):e instanceof p?i(400,"Invalid multipart request"):e instanceof g&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){const r=F(t.url);if(!r)throw i(404,"File not found");try{return this.multipartBase.handleDelete(r)}catch(e){throw e.code==="ENOENT"?i(404,"File not found"):e}}async options(t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||m.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(t){throw i(500,"GET requests should be handled via fetch() method")}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{m as default};
|
package/dist/packem_shared/{NetlifyBlobMetaStorage-ClIFdTkT.js → NetlifyBlobMetaStorage-CqluIgV0.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-Dr891Iy7.js";var s=Object.defineProperty,l=a((t,e)=>s(t,"name",{value:e,configurable:!0}),"a");class u extends o{static{a(this,"l")}static{l(this,"NetlifyBlobMetaStorage")}constructor(e){super(e)}}export{u as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var d=Object.defineProperty;var f=(l,e)=>d(l,"name",{value:e,configurable:!0});import{getStore as w}from"@netlify/blobs";import{a as g}from"./detect-file-type-5JhzC9RU.js";import{B as b,t as u,u as O}from"./storage-uhIhcN-O.js";import{v as E}from"./local-meta-storage-Dr891Iy7.js";import m from"./NetlifyBlobFile-PMZLJ8AC.js";import{o as p}from"./get-file-status-DLS18Zvd.js";import{u as v}from"./update-size-DANV7aa2.js";import{r as N}from"./part-match-D_NwyoF3.js";import{o as T}from"./has-content-Bx2p8Okx.js";var k=Object.defineProperty,y=f((l,e)=>k(l,"name",{value:e,configurable:!0}),"u");class U extends b{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=w({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:y(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))},"shouldRetry"),...e.retryConfig};this.resolvedRetryConfig=n;const{metaStorage:t,metaStorageConfig:a}=e;this.meta=t||new E(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"?u(e.ttl):e.ttl;t.expiredAt=r===void 0?void 0:Date.now()+r}const a=new m(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=p(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&&v(t,e.size),!N(e,t))throw new Error("File part does not match");const a=await this.lock(e.id);try{if(T(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 g(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=p(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 c=this.store;c.getMetadata&&a.pathname&&(s=await c.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 c=r;i=await this.runOperation(t,()=>c.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 h={...a,id:n,name:n,pathname:n,url:this.getBlobUrl(n)};return await this.saveMeta(h),h})}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"?u(i):i;o!==void 0&&(r.expiredAt=Date.now()+o),delete r.ttl}O(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 m({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=y(e=>this.deleteMeta(e.id),"internalOnComplete");getBlobUrl(e){return`/api/blobs/${this.storeName}/${e}`}}export{U as default};
|
package/dist/packem_shared/{OneDriveMetaStorage-DS4f83X2.js → OneDriveMetaStorage-DPTNMpeq.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-
|
|
1
|
+
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-Dr891Iy7.js";var o=Object.defineProperty,i=t((r,e)=>o(r,"name",{value:e,configurable:!0}),"t");class u extends s{static{t(this,"i")}static{i(this,"OneDriveMetaStorage")}constructor(e){super(e)}}export{u as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var k=Object.defineProperty;var T=(n,t)=>k(n,"name",{value:t,configurable:!0});import{ResponseType as g,Client as A,GraphError as U}from"@microsoft/microsoft-graph-client";import{wrapStorageError as d,ERRORS as m,throwErrorCode as _}from"./ERRORS-CyOuSMLY.js";import{c as C}from"./oauth-refresh-Dg2ybc6_.js";import{B as N}from"./storage-uhIhcN-O.js";import f from"./OneDriveFile-XbVVKIJh.js";import S from"./OneDriveMetaStorage-DPTNMpeq.js";import{o as E}from"./get-file-status-DLS18Zvd.js";import{u as $}from"./update-size-DANV7aa2.js";import{r as L}from"./part-match-D_NwyoF3.js";import{o as M}from"./has-content-Bx2p8Okx.js";var B=Object.defineProperty,h=T((n,t)=>B(n,"name",{value:t,configurable:!0}),"l");const P="https://graph.microsoft.com/.default",F=250*1024*1024,x=16*320*1024,V=1e3,u=h(n=>{let t=0,o=n.length;for(;t<o&&n[t]==="/";)t+=1;for(;o>t&&n[o-1]==="/";)o-=1;return t===0&&o===n.length?n:n.slice(t,o)},"trimSlashes"),y=h(n=>n.split("/").map(t=>encodeURIComponent(t)).join("/"),"encodePathSegments"),j=h(async n=>{const t=[];for await(const o of n)t.push(Buffer.from(o));return Buffer.concat(t)},"collectStream"),I=h(n=>({getAccessToken:h(()=>Promise.resolve(n),"getAccessToken")}),"createStaticAccessTokenAuth"),z=h(n=>({getAccessToken:h(async()=>n(),"ensure")}),"createCallableAccessTokenAuth"),O=h(n=>C({buildBody:h(()=>new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials",scope:P}),"buildBody"),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(n.tenantId)}/oauth2/v2.0/token`}),"createClientCredentialsAuth"),v=h(n=>C({buildBody:h(()=>new URLSearchParams({client_id:n.clientId,grant_type:"refresh_token",refresh_token:n.refreshToken,scope:P,...n.clientSecret&&{client_secret:n.clientSecret}}),"buildBody"),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(n.tenantId??"common")}/oauth2/v2.0/token`}),"createRefreshTokenAuth"),G=h(n=>({getAccessToken:h(()=>n.getAccessToken(),"getAccessToken")}),"makeAuthProvider"),D=h(n=>{if(n.client)return n.client;const t=n.accessToken!==void 0,o=n.clientCredentials!==void 0,e=n.oauth!==void 0;if([t,o,e].filter(Boolean).length>1)throw new Error("OneDrive storage: pass exactly one of `accessToken`, `clientCredentials`, or `oauth`.");let r;if(n.accessToken!==void 0?r=typeof n.accessToken=="function"?z(n.accessToken):I(n.accessToken):n.clientCredentials?r=O(n.clientCredentials):n.oauth&&(r=v({clientId:n.oauth.clientId,refreshToken:n.oauth.refreshToken,...n.oauth.clientSecret&&{clientSecret:n.oauth.clientSecret},...n.oauth.tenantId&&{tenantId:n.oauth.tenantId}})),!r){const a=process.env.ONEDRIVE_ACCESS_TOKEN;if(a)r=I(a);else{const i=process.env.ONEDRIVE_CLIENT_ID,s=process.env.ONEDRIVE_CLIENT_SECRET,c=process.env.ONEDRIVE_TENANT_ID,l=process.env.ONEDRIVE_REFRESH_TOKEN;l&&i?r=v({clientId:i,refreshToken:l,...s&&{clientSecret:s},...c&&{tenantId:c}}):i&&s&&c&&(r=O({clientId:i,clientSecret:s,tenantId:c}))}}if(!r)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 A.initWithMiddleware({authProvider:G(r)})},"resolveAuth"),W=h(n=>{if(n instanceof U)return n.statusCode===404||n.code==="itemNotFound";if(n&&typeof n=="object"){const t=n;return t.statusCode===404||t.status===404||t.code==="itemNotFound"}return!1},"isNotFoundError");class nt extends N{static name="onedrive";checksumTypes=[];meta;basePath;client;copyTimeoutMs;publicByDefault;rootFolderPath;constructor(t){if(super(t),[t.driveId,t.siteId,t.userId].filter(o=>o!==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"}this.rootFolderPath=u(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.copyTimeoutMs=t.copyTimeoutMs??6e4,this.client=D(t),this.meta=t.metaStorage??new S(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,o){return this.instrumentOperation("create",async()=>{const e=new f(t);e.name=this.namingFunction(e),await this.validate(e);try{const r=await this.getMeta(e.id);if(r.bytesWritten>=0)return r}catch{}return e.bytesWritten=0,e.status=E(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,o){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,t.size),!L(t,e))throw new Error("File part does not match");const r=await this.lock(t.id);try{if(M(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await j(t.body),i=e.name||e.id,s=a.byteLength<=F?await this.uploadSimple(i,a,e.contentType,o):await this.uploadSession(i,a,e.contentType,o);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=E(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,r)}})}async delete({id:t},o){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const r=e?.name??t;try{await this.runOperation(o,()=>this.client.api(this.itemApiPath(r)).delete())}catch(a){if(!W(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new f({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,status:"deleted"})})}async get({id:t},o){return this.instrumentOperation("get",async()=>{let e,r=t;try{e=await this.checkIfExpired(await this.getMeta(t)),r=e.name??t}catch{}const a=await this.runOperation(o,()=>this.client.api(this.itemApiPath(r)).get()),i=await this.runOperation(o,()=>this.client.api(this.itemActionPath(r,"content")).responseType(g.ARRAYBUFFER).get()),s=Buffer.from(i);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,o,e){return this.instrumentOperation("copy",async()=>{const r=this.parentReferencePath(o),a={name:R(o),parentReference:{path:r}},i=await this.runOperation(e,()=>this.client.api(this.itemActionPath(t,"copy")).responseType(g.RAW).post(a));if(i.status!==202){const w=await i.text().catch(()=>"");throw d(new Error(w||i.statusText),{adapter:"OneDrive",operation:"copy",status:i.status})}const s=i.headers.get("Location");if(!s)throw d(new Error("response missing Location monitor URL"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});const c=await this.pollCopyMonitor(s,e),l=new f({contentType:"application/octet-stream",metadata:{},originalName:o});return l.id=o,l.name=o,l.driveItemId=c,l})}async move(t,o,e){return this.instrumentOperation("move",async()=>{const r=this.parentReferencePath(o),a=R(o),i=await this.runOperation(e,()=>this.client.api(this.itemApiPath(t)).patch({name:a,parentReference:{path:r}})),s=new f({contentType:"application/octet-stream",metadata:{},originalName:o});s.id=o,s.name=o,s.driveItemId=i.id,s.webUrl=i.webUrl,s.eTag=i.eTag,s.ETag=i.eTag;try{await this.deleteMeta(t)}catch{}return s})}async list(t=1e3,o){return this.instrumentOperation("list",async()=>{const e=[];let r=`${this.folderListChildrenPath()}?$top=${Math.min(t,1e3)}`;for(;r&&e.length<t;){const a=await this.runOperation(o,()=>this.client.api(r).get());for(const i of a.value){if(!i.file)continue;const s=this.itemPathToKey(i);if(!s)continue;const c=new f({contentType:i.file.mimeType??"application/octet-stream",metadata:{},originalName:i.name});if(c.id=s,c.name=s,c.driveItemId=i.id,c.webUrl=i.webUrl,c.eTag=i.eTag,c.ETag=i.eTag,c.size=i.size??0,c.modifiedAt=i.lastModifiedDateTime,e.push(c),e.length>=t)break}r=a["@odata.nextLink"]??null}return e},{limit:t})}async getReadUrl(t,o){if(o?.responseContentDisposition||o?.responseContentType)return _(m.METHOD_NOT_ALLOWED,"OneDrive: `responseContentDisposition` / `responseContentType` are not supported — Graph download URLs have no overrides.");if(this.publicByDefault){const r=(await this.client.api(this.itemActionPath(t,"createLink")).post({scope:"anonymous",type:"view"})).link?.webUrl;if(!r)throw new Error("OneDrive: createLink response missing webUrl");return r}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,o){const e=await this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...o?.contentType&&{file:{mimeType:o.contentType}}}});if(!e.uploadUrl)throw d(new Error("createUploadSession response missing uploadUrl"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"getUploadUrl"});return e.uploadUrl}keyParts(t){const o=u(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),o&&e.push(o),e}itemApiPath(t){const o=this.keyParts(t);return o.length===0?`${this.basePath}/root`:`${this.basePath}/root:/${y(o.join("/"))}`}itemActionPath(t,o){const e=this.keyParts(t);return e.length===0?`${this.basePath}/root/${o}`:`${this.basePath}/root:/${y(e.join("/"))}:/${o}`}folderListChildrenPath(){return this.itemActionPath("","children")}parentReferencePath(t){const o=u(t),e=[];this.rootFolderPath&&e.push(this.rootFolderPath);const r=o.lastIndexOf("/");if(r!==-1){const a=o.slice(0,r);a&&e.push(a)}return e.length===0?"/drive/root:":`/drive/root:/${y(e.join("/"))}`}itemPathToKey(t){const o=t.parentReference?.path??"",e="/root:",r=o.indexOf(e);let a=r===-1?"":o.slice(r+e.length);a=u(decodeURIComponent(a));const i=this.rootFolderPath&&a.startsWith(this.rootFolderPath)?a.slice(this.rootFolderPath.length):a,s=u(i);return s?`${s}/${t.name}`:t.name}async uploadSimple(t,o,e,r){return await this.runOperation(r,()=>this.client.api(`${this.itemActionPath(t,"content")}?@microsoft.graph.conflictBehavior=replace`).header("Content-Type",e??"application/octet-stream").put(o))}async uploadSession(t,o,e,r){const a=await this.runOperation(r,()=>this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...e&&{file:{mimeType:e}}}})),i=o.byteLength;let s=0,c;for(;s<i;){const l=Math.min(s+x,i),w=o.subarray(s,l),p=await this.runOperation(r,()=>fetch(a.uploadUrl,{body:new Uint8Array(w),headers:{"Content-Length":String(w.byteLength),"Content-Range":`bytes ${s}-${l-1}/${i}`},method:"PUT"}));if(p.status===200||p.status===201)c=await p.json();else if(p.status!==202){const b=await p.text().catch(()=>"");throw d(new Error(b||p.statusText),{adapter:"OneDrive",operation:"upload-session chunk",status:p.status})}s=l}if(!c)throw d(new Error("upload-session terminated without a final DriveItem response"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"write"});return c}async pollCopyMonitor(t,o){const e=Date.now()+this.copyTimeoutMs;for(;;){const r=await this.runOperation(o,()=>fetch(t));if(!r.ok)throw d(new Error(r.statusText),{adapter:"OneDrive",operation:"copy monitor",status:r.status});const a=await r.json();if(a.status==="completed")return a.resourceId;if(a.status==="failed")throw d(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(i=>{setTimeout(i,V)})}}internalOnComplete=h(t=>this.deleteMeta(t.id),"internalOnComplete")}const R=h(n=>{const t=u(n),o=t.lastIndexOf("/");return o===-1?t:t.slice(o+1)},"baseName"),rt=h(n=>D(n),"buildGraphClient");export{rt as buildGraphClient,nt as default};
|
package/dist/packem_shared/{PocketBaseMetaStorage-B6utPncj.js → PocketBaseMetaStorage-CemTT_01.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-Dr891Iy7.js";var s=Object.defineProperty,c=a((t,e)=>s(t,"name",{value:e,configurable:!0}),"o");class n extends o{static{a(this,"c")}static{c(this,"PocketBaseMetaStorage")}constructor(e){super(e)}}export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var k=Object.defineProperty;var g=(r,t)=>k(r,"name",{value:t,configurable:!0});import A,{ClientResponseError as E}from"pocketbase";import{throwErrorCode as f,ERRORS as w}from"./ERRORS-CyOuSMLY.js";import{B as N}from"./storage-uhIhcN-O.js";import u from"./PocketBaseFile-CkAiSBb0.js";import B from"./PocketBaseMetaStorage-CemTT_01.js";import{o as O}from"./get-file-status-DLS18Zvd.js";import{u as S}from"./update-size-DANV7aa2.js";import{r as T}from"./part-match-D_NwyoF3.js";import{o as F}from"./has-content-Bx2p8Okx.js";var R=Object.defineProperty,p=g((r,t)=>R(r,"name",{value:t,configurable:!0}),"h");const b=p(async r=>{const t=[];for await(const a of r)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream"),d=p(r=>(r instanceof E||!!r&&typeof r=="object")&&r.status===404,"isNotFound"),m=p((r,t,a,e)=>{const i=r.files.getURL??r.files.getUrl;return i?i(t,a,e):f(w.METHOD_NOT_ALLOWED,"PocketBase: client has no files.getURL()")},"fileUrl");class $ extends N{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 A(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 B(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=O(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&&S(e,t.size),!T(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(F(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await b(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=O(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]??""),o=m(this.client,n,s),c=await this.runOperation(a,()=>fetch(o));if(!c.ok)return f(w.FILE_NOT_FOUND,`PocketBase: object not found at "${e}"`);const h=Buffer.from(await c.arrayBuffer());return{content:h,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??h.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]??""),o=m(this.client,n,s),c=await this.runOperation(e,()=>fetch(o));if(!c.ok)return f(w.FILE_NOT_FOUND,`PocketBase: object not found at "${i}"`);const h=Buffer.from(await c.arrayBuffer()),y=c.headers.get("content-type")??"application/octet-stream";await this.putRecord(a,h,y,e);const l=new u({contentType:y,metadata:{},originalName:a});return l.id=a,l.name=a,l.path=a,l.bucket=this.collectionName,l.size=h.length,l})}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]??""),o=new u({contentType:"application/octet-stream",metadata:{},originalName:n});return o.id=n,o.name=n,o.path=n,o.bucket=this.collectionName,o.ETag=s||void 0,o.createdAt=typeof i.created=="string"?i.created:void 0,o.modifiedAt=typeof i.updated=="string"?i.updated:void 0,o})},{limit:t})}async getReadUrl(t,a){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]??""),o=await this.client.files.getToken();return m(this.client,n,s,{token:o})}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=p(t=>this.deleteMeta(t.id),"internalOnComplete")}export{$ as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var F=Object.defineProperty;var u=(c,t)=>F(c,"name",{value:t,configurable:!0});import{n as i}from"./headers-DC2MEOrK.js";import{hasBody as f}from"type-is";import{a as n,b as p,g as l,r as U}from"./base-handler-core-
|
|
1
|
+
var F=Object.defineProperty;var u=(c,t)=>F(c,"name",{value:t,configurable:!0});import{n as i}from"./headers-DC2MEOrK.js";import{hasBody as f}from"type-is";import{a as n,b as p,g as l,r as U}from"./base-handler-core-Ccvdhx-k.js";import{F as w}from"./base-handler-node-CmCpLlBt.js";import{M as O,v as B,a as N,e as I,p as x,b as E}from"./rest-base-xrnOBxS9.js";var H=Object.defineProperty,P=u((c,t)=>H(c,"name",{value:t,configurable:!0}),"g");class m extends w{static{u(this,"p")}static{P(this,"Rest")}static methods=["delete","download","get","head","options","patch","post","put"];restBase;constructor(t){super(t);const s=this;this.restBase=new class extends O{get storage(){return s.storage}buildFileUrl(e,r){return s.buildFileUrlForRest(e,r)}}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PUT",this.put.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForRest(t,s){return this.buildFileUrl({url:t},s)}async post(t){const s=n(t,"x-chunked-upload",!0)==="true";B(t,!0);const e=N(t,!0,this.storage.maxUploadSize),r=n(t,"content-type")||"application/octet-stream",a=I(t,e,r),o=t.originalUrl||t.url||"",d=p(t);return this.restBase.handlePost(a,s,o,d,e)}async put(t){let s;try{s=l(t)}catch(g){throw this.checkForUndefinedIdOrPath(g),g}if(!f(t))throw i(400,"Request body is required");const e=Number.parseInt(n(t,"content-length")||"0",10);if(e===0)throw i(400,"Content-Length is required and must be greater than 0");if(e>this.storage.maxUploadSize)throw i(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const r=n(t,"content-type")||"application/octet-stream",a=n(t,"x-file-metadata",!0);let o;if(a)try{o=JSON.parse(a)}catch{}const d=x(t),h={contentType:r,metadata:o||{},originalName:d,size:e},y=t.originalUrl||t.url||"",b=p(t);return this.restBase.handlePut(s,h,y,b,e,o)}async delete(t){const s=new URL(t.url||"","http://localhost").searchParams.get("ids");if(s){const e=s.split(",").map(r=>r.trim()).filter(Boolean);if(e.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(e)}if((n(t,"content-type")||"").includes("application/json"))try{const e=await U(t,"utf8",1048576),r=JSON.parse(e);if(Array.isArray(r)){if(r.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(r)}if(typeof r=="object"&&r!==null&&"ids"in r&&Array.isArray(r.ids)){const a=r.ids;if(a.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(a)}}catch(e){if(e.statusCode===400)throw e}try{const e=l(t);return this.restBase.deleteSingle(e)}catch(e){throw this.checkForUndefinedIdOrPath(e),e.code==="ENOENT"||e.UploadErrorCode==="FILE_NOT_FOUND"?i(404,"File not found"):e}}async patch(t){let s;try{s=l(t)}catch(h){throw this.checkForUndefinedIdOrPath(h),h}if(!f(t))throw i(400,"Request body is required");const e=Number.parseInt(n(t,"content-length")||"0",10);if(e===0)throw i(400,"Content-Length is required and must be greater than 0");const{chunkOffset:r}=E(t);if(r===void 0)throw i(400,"X-Chunk-Offset header is required");const a=n(t,"x-chunk-checksum",!0),o=t.originalUrl||t.url||"",d=p(t);return this.restBase.handlePatch(s,r,e,a,o,d)}async head(t){try{const s=l(t);return this.restBase.handleHead(s)}catch(s){throw this.checkForUndefinedIdOrPath(s),s.UploadErrorCode==="FILE_NOT_FOUND"||s.code==="ENOENT"?i(404,"File not found"):s}}async options(){return this.restBase.handleOptions(m.methods,this.storage.maxUploadSize)}async get(t,s){return super.get(t,s)}}export{m as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var N=Object.defineProperty;var u=(d,e)=>N(d,"name",{value:e,configurable:!0});import{n as i}from"./headers-DC2MEOrK.js";import{B}from"./storage-
|
|
1
|
+
var N=Object.defineProperty;var u=(d,e)=>N(d,"name",{value:e,configurable:!0});import{n as i}from"./headers-DC2MEOrK.js";import{B}from"./storage-uhIhcN-O.js";import{ERRORS as g}from"./ERRORS-CyOuSMLY.js";import{b as p}from"./base-handler-core-Ccvdhx-k.js";import{O as x}from"./base-handler-fetch-DzbThEWy.js";import{M as F,c as m}from"./rest-base-xrnOBxS9.js";var I=Object.defineProperty,f=u((d,e)=>I(d,"name",{value:e,configurable:!0}),"u");class y extends x{static{u(this,"m")}static{f(this,"RestFetch")}static methods=["delete","download","get","head","options","patch","post","put"];restBase;constructor(e){super(e);const r=this;this.restBase=new class extends F{get storage(){return r.storage}buildFileUrl(s,t){return r.buildFileUrl({url:s},t)}}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PUT",this.put.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}async post(e){const r=e.headers.get("x-chunked-upload")==="true",s=e.headers.get("content-length"),t=s?Number.parseInt(s,10):0;if(!r){if(!s||Number.isNaN(t)||t===0)throw i(400,"Content-Length is required and must be greater than 0");if(e.body===null)throw i(400,"Request body is required")}if(t>this.storage.maxUploadSize)throw i(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const n=e.headers.get("content-type")||"application/octet-stream",o=O(e,t,n),a=e.url,h=e.body?p(e):void 0;return this.restBase.handlePost(o,r,a,h,t)}async put(e){const r=l(e.url);if(!r)throw i(400,"File ID is required in URL path");if(e.body===null)throw i(400,"Request body is required");const s=e.headers.get("content-length"),t=s?Number.parseInt(s,10):0;if(t===0)throw i(400,"Content-Length is required and must be greater than 0");if(t>this.storage.maxUploadSize)throw i(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const n=e.headers.get("content-type")||"application/octet-stream",o=e.headers.get("x-file-metadata");let a;if(o)try{a=JSON.parse(o)}catch{}const h=m(e.headers.get("content-disposition")),c={contentType:n,metadata:a||{},originalName:h,size:t},b=e.url,w=p(e);return this.restBase.handlePut(r,c,b,w,t,a)}async delete(e){const r=new URL(e.url).searchParams.get("ids");if(r){const t=r.split(",").map(n=>n.trim()).filter(Boolean);if(t.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(t)}if((e.headers.get("content-type")||"").includes("application/json"))try{const t=Number.parseInt(e.headers.get("content-length")??"",10);if(Number.isFinite(t)&&t>1048576)throw i(413,"Batch delete body exceeds 1 MiB");const n=await e.text();if(Buffer.byteLength(n,"utf8")>1048576)throw i(413,"Batch delete body exceeds 1 MiB");const o=JSON.parse(n);if(Array.isArray(o)){if(o.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(o)}if(typeof o=="object"&&o!==null&&"ids"in o&&Array.isArray(o.ids)){const a=o.ids;if(a.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(a)}}catch(t){if(t.statusCode===400)throw t}const s=l(e.url);if(!s)throw i(404,"File not found");try{return this.restBase.deleteSingle(s)}catch(t){const n=t;throw n.UploadErrorCode===g.FILE_NOT_FOUND||n.code==="ENOENT"?i(404,"File not found"):t}}async patch(e){const r=l(e.url);if(!r)throw i(404,"File not found");if(e.body===null)throw i(400,"Request body is required");const s=e.headers.get("content-length"),t=s?Number.parseInt(s,10):0;if(t===0)throw i(400,"Content-Length is required and must be greater than 0");const n=e.headers.get("x-chunk-offset"),o=n?Number.parseInt(n,10):void 0;if(o===void 0)throw i(400,"X-Chunk-Offset header is required");const a=e.headers.get("x-chunk-checksum")||void 0,h=e.url,c=p(e);return this.restBase.handlePatch(r,o,t,a,h,c)}async head(e){const r=l(e.url);if(!r)throw i(404,"File not found");try{return this.restBase.handleHead(r)}catch(s){const t=s;throw t.UploadErrorCode===g.FILE_NOT_FOUND||t.code==="ENOENT"?i(404,"File not found"):s}}async options(e){return this.restBase.handleOptions(y.methods,this.storage.maxUploadSize)}async get(e){throw i(500,"GET requests should be handled via fetch() method")}}const O=f((d,e,r)=>{const s=d.headers.get("x-total-size"),t=s?Number.parseInt(s,10):e,n=d.headers.get("x-file-metadata");let o={};if(n)try{o=JSON.parse(n)}catch{}const a=m(d.headers.get("content-disposition"));return{contentType:r,metadata:o,originalName:a,size:t}},"extractFileInitFromRequest"),l=f(d=>{let e;try{const r=new URL(d).pathname.split("/").filter(Boolean),s=r[r.length-1];if(!s)return null;e=s.replace(/\.[^.]+$/,"")||void 0}catch{return null}if(!e)return null;try{B.assertSafeId(e)}catch{throw i(400,`Invalid file id: "${e}"`)}return e},"getIdFromRequestUrl");export{y as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var w=Object.defineProperty;var l=(r,e)=>w(r,"name",{value:e,configurable:!0});import{CreateMultipartUploadCommand as b,UploadPartCommand as y,CompleteMultipartUploadCommand as B,AbortMultipartUploadCommand as S,ListPartsCommand as T,GetObjectCommand as h,HeadObjectCommand as E,DeleteObjectCommand as U,CopyObjectCommand as K,ListObjectsV2Command as x,waitUntilBucketExists as L,S3Client as I,PutObjectCommand as M}from"@aws-sdk/client-s3";import{fromIni as P}from"@aws-sdk/credential-providers";import{getSignedUrl as m}from"@aws-sdk/s3-request-presigner";import{S as O,b as A}from"./s3-base-storage-CqAyWHR6.js";import{Readable as g}from"node:stream";import{ReadableStream as C}from"node:stream/web";import v from"./S3File-BfmCOET4.js";import j from"./S3MetaStorage-vcriiosn.js";var N=Object.defineProperty,f=l((r,e)=>N(r,"name",{value:e,configurable:!0}),"d");const s=f(r=>r?.signal?{abortSignal:r.signal}:void 0,"sendOptions");class R{static{l(this,"T")}constructor(e,t){this.client=e}client;static{f(this,"S3ClientAdapter")}async createMultipartUpload(e,t){const a=new b({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),n=await this.client.send(a,s(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 C?g.fromWeb(e.Body):e.Body,n=new y({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,s(t));if(!o.ETag)throw new Error("Failed to upload part");return{ETag:o.ETag}}async completeMultipartUpload(e,t){const a=new B({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,s(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 S({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a,s(t))}async listParts(e,t){const a=new T({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),n=await this.client.send(a,s(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 h({Bucket:e.Bucket,Key:e.Key,...e.Range!==void 0&&{Range:e.Range}}),n=await this.client.send(a,s(t));let o;if(n.Body){const i=n.Body;i instanceof g||typeof i=="object"&&"transform"in i&&i instanceof C?o=i:o=g.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 E({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,s(t));return{ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified}}async deleteObject(e,t){const a=new U({Bucket:e.Bucket,Key:e.Key});await this.client.send(a,s(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 K(a);await this.client.send(n,s(t))}async listObjectsV2(e,t){const a=new x({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,MaxKeys:e.MaxKeys}),n=await this.client.send(a,s(t));return{Contents:n.Contents?.map(o=>({Key:o.Key,LastModified:o.LastModified})),IsTruncated:n.IsTruncated,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(e){const t=new y({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return m(this.client,t,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await L({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}var D=Object.defineProperty,z=l((r,e)=>D(r,"name",{value:e,configurable:!0}),"m");class q extends O{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=P({configFilepath:n}));const o=new I(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:z(d=>{const c=d;if(c.$metadata){const p=c.$metadata.httpStatusCode;if(p&&[408,429,500,502,503,504].includes(p)||c.$fault==="server")return!0}return c.retryable??!1},"shouldRetry")}}),this.s3Api=new R(o,t),this.rawClient=o;const{metaStorage:i,metaStorageConfig:u}=e;if(!i){const d={...e,...u,logger:this.logger};"directory"in d||(this.meta=new j(d))}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=A(t?.range),{Body:o,ContentLength:i,ContentType:u,ETag:d,Expires:c,LastModified:p}=await this.runOperation(t,k=>a.getObject({Bucket:this.bucket,Key:e,...n!==void 0&&{Range:n}},{signal:k}));return await this.checkIfExpired({expiredAt:c}),{headers:{"Content-Length":i?.toString()??"0","Content-Type":u,...d&&{ETag:d},...c&&{"X-Upload-Expires":c.toString()},...p&&{"Last-Modified":p.toString()}},size:Number(i),stream:o}})}get raw(){return this.rawClient}async getReadUrl(e,t){const a=new h({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 M({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 v}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{q as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-Dr891Iy7.js";var o=Object.defineProperty,c=a((t,e)=>o(t,"name",{value:e,configurable:!0}),"e");class f extends s{static{a(this,"p")}static{c(this,"SftpMetaStorage")}constructor(e){super(e)}}export{f as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var F=Object.defineProperty;var k=(h,a)=>F(h,"name",{value:a,configurable:!0});import{S as O}from"./index-B4ETk0Lu.js";import M from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-CyOuSMLY.js";import{B as E}from"./storage-uhIhcN-O.js";import P from"./SftpFile-CQCxZNVq.js";import v from"./SftpMetaStorage-Cs8b7uBO.js";import{i as w,n as A,o as l}from"./posix-dirname-CiHXPPnw.js";import{o as b}from"./get-file-status-DLS18Zvd.js";import{u as S}from"./update-size-DANV7aa2.js";import{r as $}from"./part-match-D_NwyoF3.js";import{o as x}from"./has-content-Bx2p8Okx.js";var L=Object.defineProperty,T=k((h,a)=>L(h,"name",{value:a,configurable:!0}),"l");const f=T(h=>{const a=h?.code,e=h instanceof Error?h.message:String(h);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},"isNotFoundError"),g=T(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},"toAbortError");class B extends E{static name="sftp";checksumTypes=[];meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=w(a.rootFolderPath??""),this.meta=a.metaStorage??new v(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new P(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=b(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&&S(t,a.size),!$(a,t))return d(p.FILE_CONFLICT);const i=await this.lock(a.id);try{if(x(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 r=await A(a.body),n=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,o=>this.run(o,async s=>{const c=l(n);c&&await s.mkdir(c,!0),await s.put(r,n)})),t.bytesWritten=r.length,t.size=r.length,t.path=n,t.ETag=O(r)}return t.status=b(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),r=await this.runOperation(e,n=>this.run(n,async o=>{try{return await o.get(i)}catch(s){if(f(s))return d(p.FILE_NOT_FOUND);throw s}}));return{content:r,contentType:t.contentType,ETag:t.ETag??O(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size: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,n=>this.run(n,async o=>{try{await o.delete(i)}catch(s){if(!f(s))throw s}})),await this.deleteMeta(a);const r={...t,status:"deleted"};return await this.onDelete(r),r})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(a),r=i.path??this.keyToPath(i.name||a),n=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=await c.get(r),m=l(n);m&&await c.mkdir(m,!0),await c.put(u,n)}));const o={...i,id:e,name:e,path:n};return await this.saveMeta(o),o})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(a),r=i.path??this.keyToPath(i.name||a),n=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=l(n);u&&await c.mkdir(u,!0);try{await c.rename(r,n)}catch(m){try{const y=await c.get(r);await c.put(y,n),await c.delete(r)}catch(y){throw new AggregateError([m,y],`SFTP move failed: rename and copy+delete fallback both failed for "${r}" → "${n}"`)}}}));const o={...i,id:e,name:e,path:n};await this.saveMeta(o);try{await this.deleteMeta(a)}catch{}return o})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,i=>this.run(i,async r=>{const n=[];return await this.walkList(r,t,n),n}))})}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,r=>this.run(r,async n=>{const o=await n.exists(i);return o==="-"||o==="l"}))})}async walkList(a,e,t){let i;try{i=await a.list(e||".")}catch(r){if(f(r))return;throw r}for(const r of i){const n=e?`${e}/${r.name}`:r.name;if(r.type==="d"){await this.walkList(a,n,t);continue}if(r.type!=="-")continue;const o=this.pathToKey(n);if(!o)continue;const s=new P({contentType:"application/octet-stream",metadata:{},originalName:r.name});s.id=o,s.name=o,s.path=n,s.size=r.size,s.modifiedAt=new Date(r.modifyTime).toISOString(),t.push(s)}}async run(a,e){const t=new M;if(a?.aborted)throw g(a.reason);const i=T(()=>{t.end()},"onAbort");a?.addEventListener("abort",i,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(r){throw a?.aborted?g(r):r}finally{a?.removeEventListener("abort",i),await t.end()}}keyToPath(a){const e=w(a);e&&E.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=w(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{B as default};
|
package/dist/packem_shared/{SharePointMetaStorage-DVM5-X6g.js → SharePointMetaStorage-DTVKAx6f.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-Dr891Iy7.js";var s=Object.defineProperty,i=a((t,e)=>s(t,"name",{value:e,configurable:!0}),"e");class u extends o{static{a(this,"i")}static{i(this,"SharePointMetaStorage")}constructor(e){super(e)}}export{u as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var I=Object.defineProperty;var h=(i,e)=>I(i,"name",{value:e,configurable:!0});import{throwErrorCode as c,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import u,{buildGraphClient as g}from"./OneDriveStorage-
|
|
1
|
+
var I=Object.defineProperty;var h=(i,e)=>I(i,"name",{value:e,configurable:!0});import{throwErrorCode as c,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import u,{buildGraphClient as g}from"./OneDriveStorage-CEGYb6OC.js";import{B as v}from"./storage-uhIhcN-O.js";import E from"./SharePointMetaStorage-DTVKAx6f.js";var m=Object.defineProperty,l=h((i,e)=>m(i,"name",{value:e,configurable:!0}),"d");const p=l(i=>{if(!i)return;const e=i.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},"webUrlLeaf"),S=l(i=>{let e;try{e=new URL(i)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${i}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}},"parseSiteUrl");class C extends v{static name="sharepoint";checksumTypes=[];meta;client;inner;innerPromise;oneDriveAuth;resolvedConfig;constructor(e){super(e);const t=e.accessToken??process.env.SHAREPOINT_ACCESS_TOKEN??process.env.ONEDRIVE_ACCESS_TOKEN,r=e.clientCredentials??(()=>{const o=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,a=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,n=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(o&&a&&n)return{clientId:a,clientSecret:n,tenantId:o}})();this.oneDriveAuth={...e.client&&{client:e.client},...t!==void 0&&{accessToken:t},...r&&{clientCredentials:r},...e.oauth&&{oauth:e.oauth}},this.resolvedConfig={...e,...e.driveId??process.env.SHAREPOINT_DRIVE_ID?{driveId:e.driveId??process.env.SHAREPOINT_DRIVE_ID}:{},...e.siteId??process.env.SHAREPOINT_SITE_ID?{siteId:e.siteId??process.env.SHAREPOINT_SITE_ID}:{},...e.siteUrl??process.env.SHAREPOINT_SITE_URL?{siteUrl:e.siteUrl??process.env.SHAREPOINT_SITE_URL}:{},...e.hostname??process.env.SHAREPOINT_HOSTNAME?{hostname:e.hostname??process.env.SHAREPOINT_HOSTNAME}:{}},this.client=g(this.oneDriveAuth),this.meta=e.metaStorage??new E(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,t){return(await this.getInner()).create(e,t)}async write(e,t){return(await this.getInner()).write(e,t)}async delete(e,t){return(await this.getInner()).delete(e,t)}async get(e,t){return(await this.getInner()).get(e,t)}async copy(e,t,r){return(await this.getInner()).copy(e,t,r)}async move(e,t,r){return(await this.getInner()).move(e,t,r)}async exists(e,t){return(await this.getInner()).exists(e)}async list(e=1e3,t){return(await this.getInner()).list(e,t)}async update(e,t,r){return(await this.getInner()).update(e,t)}async getStream(e,t){return(await this.getInner()).getStream(e)}async getReadUrl(e,t){return(await this.getInner()).getReadUrl(e,t)}async getUploadUrl(e,t){return(await this.getInner()).getUploadUrl(e,t)}async getInner(){return this.inner?this.inner:(this.innerPromise??=this.buildInner(),this.inner=await this.innerPromise,this.inner)}async buildInner(){const e=await this.resolveDriveId(),{documentLibrary:t,hostname:r,siteId:o,sitePath:a,siteUrl:n,...s}=this.genericConfig;return new u({...s,...this.oneDriveAuth,driveId:e,...this.resolvedConfig.copyTimeoutMs!==void 0&&{copyTimeoutMs:this.resolvedConfig.copyTimeoutMs},...this.resolvedConfig.metaStorageConfig&&{metaStorageConfig:this.resolvedConfig.metaStorageConfig},metaStorage:this.meta,...this.resolvedConfig.publicByDefault!==void 0&&{publicByDefault:this.resolvedConfig.publicByDefault},...this.resolvedConfig.rootFolderPath!==void 0&&{rootFolderPath:this.resolvedConfig.rootFolderPath}})}async resolveDriveId(){const e=this.resolvedConfig;if(e.driveId)return e.driveId;const t=await this.resolveSiteId();if(e.documentLibrary){const o=await this.client.api(`/sites/${t}/drives`).get(),a=e.documentLibrary.toLowerCase(),n=(o.value??[]).find(s=>s.name===e.documentLibrary)??(o.value??[]).find(s=>s.name?.toLowerCase()===a||p(s.webUrl)?.toLowerCase()===a);return n?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: document library "${e.documentLibrary}" not found in site "${t}".`)}const r=await this.client.api(`/sites/${t}/drive`).get();return r?.id?r.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site "${t}" has no default drive.`)}async resolveSiteId(){const e=this.resolvedConfig;if(e.siteId)return e.siteId;let t,r;if(e.siteUrl?{hostname:t,sitePath:r}=S(e.siteUrl):e.hostname&&(t=e.hostname,r=e.sitePath??"/"),!t||!r)return c(d.BAD_REQUEST,"SharePoint storage: missing site targeting. Provide `driveId`, `siteId`, `siteUrl`, or `hostname` (+ `sitePath`).");const o=r==="/"?"":r.replace(/^\/+/,""),a=o?`/sites/${t}:/${o}`:`/sites/${t}`;let n;try{n=await this.client.api(a).get()}catch(s){return c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}" (${s instanceof Error?s.message:String(s)}).`)}return n?.id?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{C as default};
|
package/dist/packem_shared/{SupabaseMetaStorage-ivXoYVUu.js → SupabaseMetaStorage-D_fGv0d6.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{v as s}from"./local-meta-storage-Dr891Iy7.js";var o=Object.defineProperty,u=a((t,e)=>o(t,"name",{value:e,configurable:!0}),"t");class i extends s{static{a(this,"p")}static{u(this,"SupabaseMetaStorage")}constructor(e){super(e)}}export{i as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=Object.defineProperty;var u=(o,t)=>g(o,"name",{value:t,configurable:!0});import{StorageClient as w}from"@supabase/storage-js";import{throwErrorCode as p,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import{B as y}from"./storage-uhIhcN-O.js";import c from"./SupabaseFile-DZ1iv9gM.js";import b from"./SupabaseMetaStorage-D_fGv0d6.js";import{o as l}from"./get-file-status-DLS18Zvd.js";import{u as E}from"./update-size-DANV7aa2.js";import{r as k}from"./part-match-D_NwyoF3.js";import{o as S}from"./has-content-Bx2p8Okx.js";var O=Object.defineProperty,h=u((o,t)=>O(o,"name",{value:t,configurable:!0}),"p");const f=3600*24*7,U=h(o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const t=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=t?.[1]??t?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},"parseDownloadOption"),C=h(async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream");class $ extends y{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(t){if(super(t),this.bucket=t.bucket,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,f),t.client)this.storageClient=t.client;else{const a=t.url??process.env.SUPABASE_URL,e=t.serviceKey??process.env.SUPABASE_SERVICE_ROLE_KEY??process.env.SUPABASE_KEY;if(!a)throw new Error("Supabase storage: `url` is required (or set SUPABASE_URL).");if(!e)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const r=a.replace(/\/+$/,"")+(a.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new w(r,{apikey:e,Authorization:`Bearer ${e}`},t.fetch)}this.meta=t.metaStorage??new b(t.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucket,e.path=e.name,await this.validate(e);try{const r=await this.getMeta(e.id);if(r.bytesWritten>=0)return r}catch{}return e.bytesWritten=0,e.status=l(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&E(e,t.size),!k(t,e))throw new Error("File part does not match");const r=await this.lock(t.id);try{if(S(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await C(t.body),n=e.path??e.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,i,{contentType:e.contentType,upsert:!0}));if(m)throw m;e.bytesWritten=i.length,e.size=i.length,e.path=s?.path??n,e.ETag=s?.id}return e.status=l(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,r)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const r=e?.path??e?.name??t,{error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).remove([r]));if(i&&i.message&&!/not.*found/i.test(i.message))throw i;return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.bucket,id:t,name:t,path:r,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}const{data:r,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(e));return i?!1:!!r})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,r;try{r=await this.checkIfExpired(await this.getMeta(t)),e=r.path??r.name??t}catch{}const{data:i,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(e));if(n||!i)throw n??new Error(`Supabase: object not found at "${e}"`);const s=Buffer.from(await this.runOperation(a,()=>i.arrayBuffer()));return{content:s,contentType:r?.contentType??i.type??"application/octet-stream",ETag:r?.ETag,expiredAt:r?.expiredAt,id:t,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??e,originalName:r?.originalName??e,size:r?.size??s.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(t))?.path??t,i=a,{error:n}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).copy(r,i));if(n)throw n;const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=i,s.bucket=this.bucket,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(t))?.path??t,{error:i}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).move(r,a));if(i)throw i;const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucket;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const{data:e,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:t}));if(r)throw r;return(e??[]).map(i=>{const n=new c({contentType:i.metadata?.mimetype??"application/octet-stream",metadata:i.metadata??{},originalName:i.name});return n.id=i.name,n.name=i.name,n.path=i.name,n.bucket=this.bucket,n.size=typeof i.metadata?.size=="number"?i.metadata.size:void 0,n.createdAt=i.created_at??void 0,n.modifiedAt=i.updated_at??void 0,n.ETag=i.metadata?.eTag??i.id??void 0,n})},{limit:t})}async getReadUrl(t,a){const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{data:r,error:i}=await this.storageClient.from(this.bucket).createSignedUrl(t,e,{download:U(a?.responseContentDisposition)});return i||!r?p(d.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUrl failed"):r.signedUrl}async getUploadUrl(t,a){const{data:e,error:r}=await this.storageClient.from(this.bucket).createSignedUploadUrl(t);return r||!e?p(d.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUploadUrl failed"):e.signedUrl}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=h(t=>this.deleteMeta(t.id),"internalOnComplete")}export{$ as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E=Object.defineProperty;var g=(i,e)=>E(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{B as w}from"./storage-
|
|
1
|
+
var E=Object.defineProperty;var g=(i,e)=>E(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{B as w}from"./storage-uhIhcN-O.js";import{O as B}from"./base-handler-fetch-DzbThEWy.js";import{TusBase as H,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as k}from"./TUS_RESUMABLE-B7KtPVeC.js";var R=Object.defineProperty,b=g((i,e)=>R(i,"name",{value:e,configurable:!0}),"g");const l=b(i=>{let e;try{const t=new URL(i).pathname.split("/").filter(Boolean);e=t[t.length-1]||void 0}catch{return}if(e){try{w.assertSafeId(e)}catch{throw a(400,`Invalid file id: "${e}"`)}return e}},"getIdFromRequestUrl");class T extends B{static{g(this,"Tus")}static{b(this,"Tus")}static methods=["delete","download","get","head","options","patch","post"];tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends H{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads??!1}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async fetch(e){const t=await super.fetch(e);if(t.headers.has("Tus-Resumable"))return t;const s=new Headers(t.headers);return s.set("Tus-Resumable",O),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})}async options(){return this.tusBase.handleOptions(T.methods)}async post(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=e.headers.get("upload-length")||void 0,r=e.headers.get("upload-defer-length")||void 0,o=e.headers.get("upload-concat")||void 0,d=e.headers.get("upload-metadata")||void 0,u=e.headers.get("content-type")||"",n=e.headers.get("content-length"),h=n?Number.parseInt(n,10):0,c=e.url,p=e.body;return this.tusBase.handlePost(s,r,o,d,c,p,h,u)}async patch(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");const r=e.headers.get("upload-offset");if(!r)throw a(412,"Missing Upload-Offset header");const o=e.headers.get("content-type");if(!o)throw a(412,"Content-Type header required");if(o!=="application/offset+octet-stream")throw a(415,"Unsupported Media Type");const d=Number.parseInt(r,10),u=e.headers.get("upload-length")||void 0,n=e.headers.get("upload-metadata")||void 0,h=e.headers.get("content-length"),c=h?Number.parseInt(h,10):0,p=e.headers.get("upload-checksum")||void 0,{checksum:U,checksumAlgorithm:F}=this.tusBase.extractChecksum(p),v=e.url,y=e.body;try{return this.tusBase.handlePatch(s,d,u,n,U,F,v,y,c)}catch(m){const f=m;throw f.UploadErrorCode==="GONE"||f.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):m}}async head(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleHead(s)}catch(r){const o=r;throw o.UploadErrorCode==="GONE"||o.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):r}}async get(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleGet(s)}catch(r){throw r.UploadErrorCode==="GONE"?a(410,"Upload expired"):r}}async delete(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleDelete(s)}catch(r){throw r.code==="ENOENT"?a(404,"File not found"):r}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForTus(e,t){const s=new URL(e),{pathname:r,search:o}=s,d=`${r}/${t.id}${o}`;return this.storage.config.useRelativeLocation?d:s.origin+d}}export{O as TUS_RESUMABLE,k as TUS_VERSION,T as Tus};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var U=Object.defineProperty;var p=(h,e)=>U(h,"name",{value:e,configurable:!0});import{format as F}from"node:url";import{n as d}from"./headers-DC2MEOrK.js";import{a,b as m,g as n,c as T}from"./base-handler-core-
|
|
1
|
+
var U=Object.defineProperty;var p=(h,e)=>U(h,"name",{value:e,configurable:!0});import{format as F}from"node:url";import{n as d}from"./headers-DC2MEOrK.js";import{a,b as m,g as n,c as T}from"./base-handler-core-Ccvdhx-k.js";import{F as E}from"./base-handler-node-CmCpLlBt.js";import{TusBase as y,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as w}from"./TUS_RESUMABLE-B7KtPVeC.js";var B=Object.defineProperty,H=p((h,e)=>B(h,"name",{value:e,configurable:!0}),"h");class g extends E{static{p(this,"Tus")}static{H(this,"Tus")}static methods=["delete","download","get","head","options","patch","post"];disableTerminationForFinishedUploads=!1;tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends y{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(g.methods)}async post(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));const t=e.headers["upload-length"],s=e.headers["upload-defer-length"],r=e.headers["upload-concat"],o=a(e,"upload-metadata",!0),i=a(e,"content-type")||"",l=Number.parseInt(a(e,"content-length")||"0",10),u=e.originalUrl||e.url||"",c=m(e);return this.tusBase.handlePost(t,s,r,o,u,c,l,i)}async patch(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);if(e.headers["upload-offset"]===void 0)throw d(412,"Missing Upload-Offset header");if(e.headers["content-type"]===void 0)throw d(412,"Content-Type header required");if(e.headers["content-type"]!=="application/offset+octet-stream")throw d(415,"Unsupported Media Type");const s=Number.parseInt(a(e,"upload-offset"),10),r=e.headers["upload-length"],o=a(e,"upload-metadata",!0),i=Number(a(e,"content-length")),l=a(e,"upload-checksum"),{checksum:u,checksumAlgorithm:c}=this.tusBase.extractChecksum(l),b=e.originalUrl||e.url||"",f=m(e);return this.tusBase.handlePatch(t,s,r,o,u,c,b,f,i)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async head(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleHead(t)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async get(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleGet(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.UploadErrorCode==="GONE"?d(410,"Upload expired"):t}}async delete(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleDelete(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.code==="ENOENT"?d(404,"File not found"):t}}send(e,{body:t="",headers:s={},statusCode:r=200}){const o={body:t,headers:{...s,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control","Tus-Resumable":O},statusCode:r||200};super.send(e,o)}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForTus(e,t){const s=new URL(e,"http://localhost"),{pathname:r}=s,o=Object.fromEntries(s.searchParams.entries()),i=F({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:T({url:e})+i}}export{O as TUS_RESUMABLE,w as TUS_VERSION,g as Tus};
|
package/dist/packem_shared/{UploadThingMetaStorage-BvKNzgm7.js → UploadThingMetaStorage-CAQ1uTfv.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=Object.defineProperty;var r=(a,e)=>t(a,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-
|
|
1
|
+
var t=Object.defineProperty;var r=(a,e)=>t(a,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-Dr891Iy7.js";var s=Object.defineProperty,c=r((a,e)=>s(a,"name",{value:e,configurable:!0}),"a");class u extends o{static{r(this,"r")}static{c(this,"UploadThingMetaStorage")}constructor(e){super(e)}}export{u as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var T=Object.defineProperty;var l=(n,t)=>T(n,"name",{value:t,configurable:!0});import{UTApi as U,UTFile as h}from"uploadthing/server";import{throwErrorCode as m,ERRORS as f}from"./ERRORS-CyOuSMLY.js";import{B as I}from"./storage-uhIhcN-O.js";import d from"./UploadThingFile-BpG9mE8K.js";import O from"./UploadThingMetaStorage-CAQ1uTfv.js";import{o as y}from"./get-file-status-DLS18Zvd.js";import{u as E}from"./update-size-DANV7aa2.js";import{r as k}from"./part-match-D_NwyoF3.js";import{o as v}from"./has-content-Bx2p8Okx.js";var b=Object.defineProperty,u=l((n,t)=>b(n,"name",{value:t,configurable:!0}),"c");const w=3600*24*7,x=u(n=>{let t;try{t=typeof atob=="function"?atob(n):Buffer.from(n,"base64").toString("utf8")}catch(e){throw new Error(`UploadThing: token is not valid base64: ${e.message}`)}let i;try{i=JSON.parse(t)}catch(e){throw new Error(`UploadThing: token does not decode to JSON: ${e.message}`)}if(!i||typeof i!="object"||typeof i.apiKey!="string"||typeof i.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return i},"decodeToken"),N=u(async n=>{const t=[];for await(const i of n)t.push(Buffer.from(i));return Buffer.concat(t)},"collectStream"),g=u(n=>{const t=n.lastIndexOf("/");return t===-1?n:n.slice(t+1)},"basename");class B extends I{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(t){super(t);const i=t.token??process.env.UPLOADTHING_TOKEN;if(t.client)this.utapi=t.client;else{if(!i)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new U({defaultKeyType:"customId",token:i})}if(!i)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=x(i).appId,this.acl=t.acl??"public-read",this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w),this.meta=t.metaStorage??new O(t.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(t,i){return this.instrumentOperation("create",async()=>{const e=new d(t);e.name=this.namingFunction(e),e.customId=e.name,await this.validate(e);try{const a=await this.getMeta(e.id);if(a.bytesWritten>=0)return a}catch{}return e.bytesWritten=0,e.status=y(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&&E(e,t.size),!k(t,e))throw new Error("File part does not match");const a=await this.lock(t.id);try{if(v(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await N(t.body),p=new Blob([new Uint8Array(r)],{type:e.contentType}),o=new h([p],g(e.name||e.id),{customId:e.name||e.id,type:e.contentType}),s=await this.runOperation(i,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const{data:c}=s;e.bytesWritten=r.length,e.size=r.length,e.ufsKey=c.key,e.url=c.ufsUrl??c.url,e.ETag=c.fileHash,e.fileHash=c.fileHash}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,a)}})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const a=e?.customId??e?.name??t;return await this.runOperation(i,()=>this.utapi.deleteFiles(a)),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:t}),{customId:a,id:t,name:t,status:"deleted"})})}async get({id:t},i){return this.instrumentOperation("get",async()=>{let e,a=t;try{e=await this.checkIfExpired(await this.getMeta(t)),a=e.customId??e.name??t}catch{}const r=await this.resolveFetchUrl(a,i),p=await this.runOperation(i,()=>fetch(r));if(!p.ok)throw new Error(`UploadThing: fetch failed: ${p.status} ${p.statusText} for ${a}`);const o=Buffer.from(await p.arrayBuffer());return{content:o,contentType:e?.contentType??p.headers.get("content-type")??"application/octet-stream",ETag:e?.ETag??p.headers.get("etag")??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt,name:e?.name??a,originalName:e?.originalName??a,size:e?.size??o.length}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const a=await this.get({id:t},e),r=new Blob([new Uint8Array(a.content)],{type:a.contentType}),p=new h([r],g(i),{customId:i,type:a.contentType}),o=await this.runOperation(e,()=>this.utapi.uploadFiles(p,{acl:this.acl}));if(o.error)throw new Error(o.error.message);const s=new d({contentType:a.contentType,metadata:{},originalName:i});return s.id=i,s.name=i,s.customId=i,s.size=typeof a.size=="string"?Number(a.size):a.size,s.ufsKey=o.data.key,s.url=o.data.ufsUrl??o.data.url,s.ETag=o.data.fileHash,s})}async move(t,i,e){return this.instrumentOperation("move",async()=>{const a=await this.copy(t,i,e);return await this.delete({id:t},e),a})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>(await this.runOperation(i,()=>this.utapi.listFiles({limit:t}))).files.map(e=>{const a=e.customId??e.key,r=new d({contentType:"application/octet-stream",metadata:{},originalName:a});return r.id=a,r.name=a,r.customId=e.customId??void 0,r.ufsKey=e.key,r.size=e.size,r.modifiedAt=e.uploadedAt?new Date(e.uploadedAt).toISOString():void 0,r}),{limit:t})}async getReadUrl(t,i){if(i?.responseContentDisposition)return m(f.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition` is not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const e=Math.min(i?.expiresIn??this.defaultUrlExpiresIn,w),{ufsUrl:a}=await this.utapi.generateSignedURL(t,{expiresIn:e,keyType:"customId"});return a}async getUploadUrl(t,i){return m(f.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(t,i){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const{ufsUrl:e}=await this.runOperation(i,()=>this.utapi.generateSignedURL(t,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return e}internalOnComplete=u(t=>this.deleteMeta(t.id),"internalOnComplete")}export{B as default};
|
package/dist/packem_shared/{VercelBlobMetaStorage-CwaqWucZ.js → VercelBlobMetaStorage-DY4zAB6M.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-
|
|
1
|
+
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{v as o}from"./local-meta-storage-Dr891Iy7.js";var s=Object.defineProperty,c=t((r,e)=>s(r,"name",{value:e,configurable:!0}),"e");class i extends o{static{t(this,"l")}static{c(this,"VercelBlobMetaStorage")}constructor(e){super(e)}}export{i as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var E=Object.defineProperty;var u=(c,e)=>E(c,"name",{value:e,configurable:!0});import{put as d,list as m,del as h,copy as p}from"@vercel/blob";import{a as g}from"./detect-file-type-5JhzC9RU.js";import{B as v,t as T}from"./storage-uhIhcN-O.js";import{v as b}from"./local-meta-storage-Dr891Iy7.js";import f from"./VercelBlobFile-Cni_1qwD.js";import{o as w}from"./get-file-status-DLS18Zvd.js";import{u as B}from"./update-size-DANV7aa2.js";import{r as _}from"./part-match-D_NwyoF3.js";import{o as k}from"./has-content-Bx2p8Okx.js";var I=Object.defineProperty,C=u((c,e)=>I(c,"name",{value:e,configurable:!0}),"p");class y extends v{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:p,credentials:this.credentials,del:h,list:m,put:d}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=y.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:i,metaStorageConfig:t}=e;this.meta=i||new b(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const i=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,r=t?.startsWith("store_")?t.slice(6):t;if(i&&r)return{oidcToken:i,storeId:r};if(i||r)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${i?"set":"missing"}, storeId=${r?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,i){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?T(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const r=new f(t);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);if(a.bytesWritten>=0)return a}catch{}return r.bytesWritten=0,r.status=w(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&B(t,e.size),!_(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(k(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await g(s);o?.mime&&(t.contentType=o.mime)}catch{}const O=new Blob([s],{type:t.contentType}),l=await this.runOperation(i,()=>d(t.name,O,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=l.url,t.pathname=l.pathname,t.downloadUrl=l.downloadUrl,t.bytesWritten=s.length}return t.status=w(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:r}=t;t.status="deleted";try{await this.runOperation(i,()=>h(r,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},i){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:r}=t;return(await this.runOperation(i,()=>fetch(r,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},i){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.url||t.url.length===0)throw new Error("File URL not found");const{url:r}=t,a=await this.runOperation(i,()=>fetch(r)),n=Buffer.from(await this.runOperation(i,()=>a.arrayBuffer()));return{content:n,contentType:t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||n.length}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const r=await this.getMeta(e);if(!r.url)throw new Error("Source file URL not found");const a=r.url,n=await this.runOperation(t,()=>p(a,i,{access:"public",...this.credentials}));return{...r,id:i,name:i,pathname:n.pathname,url:n.url}})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const r=await this.copy(e,i,t);return await this.delete({id:e},t),r})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>(await this.runOperation(i,()=>m({limit:e,...this.credentials}))).blobs.map(t=>{const r=new f({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return r.createdAt=t.uploadedAt?.toISOString(),r.id=t.pathname,r.modifiedAt=t.uploadedAt?.toISOString(),r.name=t.pathname,r.pathname=t.pathname,r.size=t.size,r.url=t.url,r.downloadUrl=t.downloadUrl,r}),{limit:e})}internalOnComplete=C(e=>this.deleteMeta(e.id),"internalOnComplete");shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{y as default};
|