@visulima/storage 1.0.0-alpha.17 → 1.0.0-alpha.19
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 +21 -0
- package/LICENSE.md +3 -0
- package/dist/adapter/nuxt/module.d.ts +3 -3
- package/dist/adapter/nuxt/module.js +1 -93
- package/dist/handler/http/fetch/index.d.ts +6 -6
- package/dist/handler/http/fetch/index.js +1 -4
- package/dist/handler/http/hono/index.d.ts +3 -3
- package/dist/handler/http/hono/index.js +1 -65
- package/dist/handler/http/nextjs/index.d.ts +4 -4
- package/dist/handler/http/nextjs/index.js +1 -37
- package/dist/handler/http/node/index.d.ts +6 -6
- package/dist/handler/http/node/index.js +1 -8
- package/dist/handler/http/solid-start/index.d.ts +4 -4
- package/dist/handler/http/solid-start/index.js +1 -44
- package/dist/index.js +1 -13
- package/dist/openapi/index.js +1 -5
- package/dist/packem_shared/AwsLightFile-BTLiRxXj.js +1 -0
- package/dist/packem_shared/AwsLightMetaStorage-DHz1nf_H.js +1 -0
- package/dist/packem_shared/AwsLightStorage-CA9cdfJ6.js +1 -0
- package/dist/packem_shared/AzureFile-BKHru1zB.js +1 -0
- package/dist/packem_shared/AzureSMetaStorage-BqA4jUDJ.js +1 -0
- package/dist/packem_shared/AzureStorage-BKUjCymW.js +1 -0
- package/dist/packem_shared/BaseTransformer-D68eLyz1.js +1 -0
- package/dist/packem_shared/DiskStorage-DNjpDMX9.js +1 -0
- package/dist/packem_shared/DiskStorageWithChecksum-Bb6JX_tC.js +1 -0
- package/dist/packem_shared/ERRORS-B9jkvKwx.js +1 -0
- package/dist/packem_shared/File-alcSNpLq.js +1 -0
- package/dist/packem_shared/GCSConfig-BQ0OpVhe.js +1 -0
- package/dist/packem_shared/GCSFile-CHjX_fJk.js +1 -0
- package/dist/packem_shared/GCSMetaStorage-CpxQ8wM9.js +1 -0
- package/dist/packem_shared/GCStorage-DAg1V55T.js +1 -0
- package/dist/packem_shared/LocalMetaStorage-BWuFvWn4.js +1 -0
- package/dist/packem_shared/MediaTransformer-2C8MJeAg.js +1 -0
- package/dist/packem_shared/MetaStorage-Y4m1dWgd.js +1 -0
- package/dist/packem_shared/Metadata-B6Ir0KO7.js +1 -0
- package/dist/packem_shared/Multipart-Bd9YFFn0.js +1 -0
- package/dist/packem_shared/Multipart-D5bcEvga.js +1 -0
- package/dist/packem_shared/NetlifyBlobFile-CpzkMKng.js +1 -0
- package/dist/packem_shared/NetlifyBlobMetaStorage-dD0oBLom.js +1 -0
- package/dist/packem_shared/NetlifyBlobStorage-ByTwCN-h.js +1 -0
- package/dist/packem_shared/NoOpMetrics-Dky06sf1.js +1 -0
- package/dist/packem_shared/OpenTelemetryMetrics-9uxQMSlg.js +1 -0
- package/dist/packem_shared/Rest-CYEBbtCD.js +1 -0
- package/dist/packem_shared/Rest-DoonVU7B.js +1 -0
- package/dist/packem_shared/S3File-Du6wP0Sz.js +1 -0
- package/dist/packem_shared/S3MetaStorage-vcriiosn.js +1 -0
- package/dist/packem_shared/S3Storage-Fx6-OSc-.js +1 -0
- package/dist/packem_shared/TUS_RESUMABLE-B7KtPVeC.js +1 -0
- package/dist/packem_shared/Tus-Bd_2Ki2G.js +1 -0
- package/dist/packem_shared/Tus-CUBCkuPE.js +1 -0
- package/dist/packem_shared/ValidationError-D8KKJiKA.js +1 -0
- package/dist/packem_shared/VercelBlobFile-CL9MjKcY.js +1 -0
- package/dist/packem_shared/VercelBlobMetaStorage-BsOTx-Su.js +1 -0
- package/dist/packem_shared/VercelBlobStorage-kNkk5Cn4.js +1 -0
- package/dist/packem_shared/_commonjsHelpers-D6W6KoPK.js +1 -0
- package/dist/packem_shared/aws-light-meta-storage-TPyQwLvk.js +4 -0
- package/dist/packem_shared/backblaze-DEflv87m.js +1 -0
- package/dist/packem_shared/base-handler-core-DaggCVsq.js +1 -0
- package/dist/packem_shared/base-handler-fetch-DnarP64X.js +1 -0
- package/dist/packem_shared/base-handler-node-BTes6sql.js +1 -0
- package/dist/packem_shared/cache-qV_5Umeq.js +1 -0
- package/dist/packem_shared/cloudflare-DLAeQvgD.js +1 -0
- package/dist/packem_shared/defaultCloudStorageFileNameValidation-yiM9GxHr.js +1 -0
- package/dist/packem_shared/digitalOcean-nhZUds87.js +1 -0
- package/dist/packem_shared/disk-storage-BvdK4bqF.js +5 -0
- package/dist/packem_shared/gcs-meta-storage-CvGkpzVE.js +1 -0
- package/dist/packem_shared/has-content-Bx2p8Okx.js +1 -0
- package/dist/packem_shared/headers-DC2MEOrK.js +27 -0
- package/dist/packem_shared/is-expired-1JuZjDtb.js +1 -0
- package/dist/packem_shared/isRetryableError-DQNSZiBc.js +1 -0
- package/dist/packem_shared/isValidMediaType-B-2UKjZx.js +1 -0
- package/dist/packem_shared/local-meta-storage-Bkwqi_gi.js +1 -0
- package/dist/packem_shared/{media-transformer.d-ChmjTvjc.d.ts → media-transformer.d-CY9CsEOe.d.ts} +1 -1
- package/dist/packem_shared/minio-BWwgGXeE.js +1 -0
- package/dist/packem_shared/multipart-base-C6OjBwMS.js +1 -0
- package/dist/packem_shared/part-match-DqD5U7An.js +1 -0
- package/dist/packem_shared/path-D7rMc9nq-B718mbm6.js +1 -0
- package/dist/packem_shared/response-builder-Wdo_fvcF.js +1 -0
- package/dist/packem_shared/rest-base-B2Dv7esY.js +1 -0
- package/dist/packem_shared/restOpenApiSpec-PaIVbESh.js +1 -0
- package/dist/packem_shared/s3-base-storage-xHZNtsGe.js +1 -0
- package/dist/packem_shared/sharedGet-Ce7WGAsc.js +1 -0
- package/dist/packem_shared/storage-m_Cxgiih.js +1 -0
- package/dist/packem_shared/tigris-DZoyrMNd.js +1 -0
- package/dist/packem_shared/transformOpenApiSpec-C0vEbDTO.js +1 -0
- package/dist/packem_shared/{tus-base.d-CpLzyd-S.d.ts → tus-base.d-DNZRXR9X.d.ts} +2 -2
- package/dist/packem_shared/tusOpenApiSpec-DF0-hlWV.js +1 -0
- package/dist/packem_shared/{types.d-DBjmJvIT.d.ts → types.d-BCN94sB_.d.ts} +1 -1
- package/dist/packem_shared/{types.d-DviSTLOg.d.ts → types.d-D4caL2Fp.d.ts} +1 -1
- package/dist/packem_shared/update-size-DANV7aa2.js +1 -0
- package/dist/packem_shared/validator-DK41xp8N.js +1 -0
- package/dist/packem_shared/waitForStorage-ChSBLhLc.js +1 -0
- package/dist/packem_shared/wasabi-Dmce4x9s.js +1 -0
- package/dist/packem_shared/xhrOpenApiSpec-nyoboz83.js +1 -0
- package/dist/storage/aws/clients/index.js +1 -6
- package/dist/storage/aws/index.js +1 -3
- package/dist/storage/aws-light/index.js +1 -3
- package/dist/storage/azure/index.js +1 -3
- package/dist/storage/gcs/index.js +1 -4
- package/dist/storage/local/index.js +1 -3
- package/dist/storage/netlify-blob/index.js +1 -3
- package/dist/storage/vercel-blob/index.js +1 -3
- package/dist/transformer/audio-transformer.d.ts +1 -1
- package/dist/transformer/audio-transformer.js +1 -278
- package/dist/transformer/image-transformer.d.ts +1 -1
- package/dist/transformer/image-transformer.js +1 -1100
- package/dist/transformer/index.d.ts +2 -2
- package/dist/transformer/index.js +1 -4
- package/dist/transformer/video-transformer.d.ts +1 -1
- package/dist/transformer/video-transformer.js +1 -310
- package/package.json +18 -18
- package/dist/packem_shared/AwsLightFile-C-Nd5rtl.js +0 -11
- package/dist/packem_shared/AwsLightMetaStorage-BIDb5EPg.js +0 -4
- package/dist/packem_shared/AwsLightStorage-CMuKw4bI.js +0 -133
- package/dist/packem_shared/AzureFile-C0kug4w4.js +0 -8
- package/dist/packem_shared/AzureSMetaStorage-BEbXX9Uk.js +0 -89
- package/dist/packem_shared/AzureStorage-98-LRZ1e.js +0 -359
- package/dist/packem_shared/BaseTransformer-9965D4pb.js +0 -83
- package/dist/packem_shared/DiskStorage-COMe_G42.js +0 -12
- package/dist/packem_shared/DiskStorageWithChecksum-BVaaZiyS.js +0 -249
- package/dist/packem_shared/ERRORS-D0apMqnc.js +0 -97
- package/dist/packem_shared/File-CPUhj3DI.js +0 -69
- package/dist/packem_shared/GCSConfig-vPP22kN6.js +0 -11
- package/dist/packem_shared/GCSFile-DaDiCKE2.js +0 -8
- package/dist/packem_shared/GCSMetaStorage-BygVH0Ee.js +0 -7
- package/dist/packem_shared/GCStorage-4hSx_bN1.js +0 -410
- package/dist/packem_shared/LocalMetaStorage-DvnZqf61.js +0 -7
- package/dist/packem_shared/MediaTransformer-BRRqYA0E.js +0 -1202
- package/dist/packem_shared/MetaStorage-pECeFOad.js +0 -46
- package/dist/packem_shared/Metadata-DRLXeJ0F.js +0 -89
- package/dist/packem_shared/Multipart-BzzvNxt4.js +0 -128
- package/dist/packem_shared/Multipart-DLtFLQ8s.js +0 -163
- package/dist/packem_shared/NetlifyBlobFile-CfyJtGWN.js +0 -14
- package/dist/packem_shared/NetlifyBlobMetaStorage-eJT6RFy9.js +0 -9
- package/dist/packem_shared/NetlifyBlobStorage-nPv7iIAG.js +0 -376
- package/dist/packem_shared/NoOpMetrics-DhAk5rXc.js +0 -10
- package/dist/packem_shared/OpenTelemetryMetrics-BnxhqIaH.js +0 -67
- package/dist/packem_shared/Rest-DEa7IA9R.js +0 -267
- package/dist/packem_shared/Rest-qhMbCn5a.js +0 -228
- package/dist/packem_shared/S3File-BXCuJaQZ.js +0 -11
- package/dist/packem_shared/S3MetaStorage-yT4CznlV.js +0 -77
- package/dist/packem_shared/S3Storage-wi5XT-yu.js +0 -317
- package/dist/packem_shared/TUS_RESUMABLE-Dtfsffnj.js +0 -434
- package/dist/packem_shared/Tus-Ck0Hdle5.js +0 -195
- package/dist/packem_shared/Tus-_0vCdHyB.js +0 -200
- package/dist/packem_shared/ValidationError-BfF1aE4h.js +0 -26
- package/dist/packem_shared/VercelBlobFile-DkFIIb9Q.js +0 -18
- package/dist/packem_shared/VercelBlobMetaStorage-DjFmi4vp.js +0 -9
- package/dist/packem_shared/VercelBlobStorage-CmMgiDgr.js +0 -261
- package/dist/packem_shared/_commonjsHelpers-BqLXS_qQ.js +0 -5
- package/dist/packem_shared/aws-light-meta-storage-BGZEiY3y.js +0 -447
- package/dist/packem_shared/backblaze-BlMnIcBC.js +0 -20
- package/dist/packem_shared/base-handler-core-lVB-D59L.js +0 -306
- package/dist/packem_shared/base-handler-fetch-CitgN-Aw.js +0 -291
- package/dist/packem_shared/base-handler-node-BiO2DF87.js +0 -731
- package/dist/packem_shared/cache-B88MXQ_2.js +0 -18
- package/dist/packem_shared/cloudflare-Bi1q8wXE.js +0 -21
- package/dist/packem_shared/defaultCloudStorageFileNameValidation-Brw40ZEP.js +0 -11
- package/dist/packem_shared/digitalOcean-CWQRJM3L.js +0 -21
- package/dist/packem_shared/disk-storage-D9RfoKjW.js +0 -832
- package/dist/packem_shared/gcs-meta-storage-8FovEDbW.js +0 -159
- package/dist/packem_shared/has-content-CY66ehMK.js +0 -3
- package/dist/packem_shared/headers-YLRp1dLo.js +0 -1318
- package/dist/packem_shared/is-expired-CTThU1q5.js +0 -8
- package/dist/packem_shared/isRetryableError-Dycp7127.js +0 -82
- package/dist/packem_shared/isValidMediaType-BeDgiObq.js +0 -35
- package/dist/packem_shared/local-meta-storage-D-pPc3FI.js +0 -658
- package/dist/packem_shared/minio-C2YBZQOw.js +0 -22
- package/dist/packem_shared/multipart-base-C994naBi.js +0 -102
- package/dist/packem_shared/part-match-Dt738Ddb.js +0 -96
- package/dist/packem_shared/path-aV9lMdcn-DMU5H1-h.js +0 -162
- package/dist/packem_shared/response-builder-BtnRiBUI.js +0 -45
- package/dist/packem_shared/rest-base-k1ory8uB.js +0 -457
- package/dist/packem_shared/restOpenApiSpec-BBJ_SiPE.js +0 -800
- package/dist/packem_shared/s3-base-storage-zUO8u8Cp.js +0 -510
- package/dist/packem_shared/sharedGet-CkSLSnMd.js +0 -1022
- package/dist/packem_shared/storage-5XW1E7XU.js +0 -1188
- package/dist/packem_shared/tigris-Hac8TKnX.js +0 -21
- package/dist/packem_shared/transformOpenApiSpec-BodFhFls.js +0 -975
- package/dist/packem_shared/tusOpenApiSpec-DzppyJTW.js +0 -740
- package/dist/packem_shared/update-size-CCGm6i1J.js +0 -8
- package/dist/packem_shared/validator-DuO17wFF.js +0 -79
- package/dist/packem_shared/waitForStorage-Cscw85sx.js +0 -18
- package/dist/packem_shared/wasabi-DIyflHSd.js +0 -21
- package/dist/packem_shared/xhrOpenApiSpec-CXz7BC5J.js +0 -264
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var p=Object.defineProperty;var m=(h,e)=>p(h,"name",{value:e,configurable:!0});import{createHash as u}from"node:crypto";import l from"mime";import{N as g}from"./cache-qV_5Umeq.js";import{isKnownContentType as c}from"./isValidMediaType-B-2UKjZx.js";import s from"./ValidationError-D8KKJiKA.js";var v=Object.defineProperty,b=m((h,e)=>v(h,"name",{value:e,configurable:!0}),"h");class F{static{m(this,"v")}constructor(e,t={}){if(this.storage=e,this.logger=t.logger||this.storage.logger,this.config={audioBitrate:128e3,audioCodec:"aac",cache:t.cache??new g,cacheTtl:3600,maxAudioSize:100*1024*1024,maxImageSize:10*1024*1024,maxVideoSize:500*1024*1024,saveTransformedFiles:!1,supportedAudioFormats:[],supportedImageFormats:[],supportedVideoFormats:[],videoBitrate:2e6,videoCodec:"avc",...t},t.ImageTransformer&&((!Array.isArray(this.config.supportedImageFormats)||this.config.supportedImageFormats.length===0)&&(this.config.supportedImageFormats=["jpeg","png","webp","avif","tiff","gif","svg"]),this.imageTransformer=new t.ImageTransformer(this.storage,{cache:this.config.cache,cacheTtl:this.config.cacheTtl,logger:this.logger,maxImageSize:this.config.maxImageSize,supportedFormats:this.config.supportedImageFormats})),t.VideoTransformer&&((!Array.isArray(this.config.supportedVideoFormats)||this.config.supportedVideoFormats.length===0)&&(this.config.supportedVideoFormats=["mp4","webm","mkv","avi","mov","flv","wmv"]),this.videoTransformer=new t.VideoTransformer(this.storage,{cache:this.config.cache,cacheTtl:this.config.cacheTtl,defaultBitrate:this.config.videoBitrate,defaultCodec:this.config.videoCodec,logger:this.logger,maxVideoSize:this.config.maxVideoSize,supportedFormats:this.config.supportedVideoFormats})),t.AudioTransformer&&((!Array.isArray(this.config.supportedAudioFormats)||this.config.supportedAudioFormats.length===0)&&(this.config.supportedAudioFormats=["mp3","wav","ogg","aac","flac","m4a","wma","aiff"]),this.audioTransformer=new t.AudioTransformer(this.storage,{cache:this.config.cache,cacheTtl:this.config.cacheTtl,defaultBitrate:this.config.audioBitrate,defaultCodec:this.config.audioCodec,logger:this.logger,maxAudioSize:this.config.maxAudioSize,supportedFormats:this.config.supportedAudioFormats})),t.AudioTransformer===void 0&&t.ImageTransformer===void 0&&t.VideoTransformer===void 0)throw new Error("MediaTransformer initialization failed: No transformers are configured. At least one transformer (AudioTransformer, ImageTransformer, or VideoTransformer) must be provided in the configuration to enable media processing functionality.")}storage;static{b(this,"MediaTransformer")}imageTransformer;videoTransformer;audioTransformer;config;logger;supportedFormats(){return[...this.config.supportedAudioFormats,...this.config.supportedImageFormats,...this.config.supportedVideoFormats]}async handle(e,t){const a=this.parseQuery(t),r={id:e},o=await this.storage.get(r),i=this.detectMediaType(o.contentType);if(this.validateQueryParameters(a,i),this.config.saveTransformedFiles&&this.hasTransformations(a)){const d=this.generateTransformedFileId(e,a,i);try{const f=await this.storage.get({id:d});return this.logger?.debug?.(`Serving cached transformed file: ${d}`),this.createMediaTransformResult(f,i,o)}catch{this.logger?.debug?.(`Transformed file not found, processing: ${d}`)}}let n;switch(i){case"audio":{if(!this.audioTransformer)throw new Error("Audio transformer not available. Please install audio transformation dependencies or provide an audio transformer instance.");n=await this.handleAudioTransformation(e,a);break}case"image":{if(!this.imageTransformer)throw new Error("Image transformer not available. Please install image transformation dependencies or provide an image transformer instance.");n=await this.handleImageTransformation(e,a);break}case"video":{if(!this.videoTransformer)throw new Error("Video transformer not available. Please install video transformation dependencies or provide a video transformer instance.");n=await this.handleVideoTransformation(e,a);break}default:throw new Error(`Unsupported media type: ${o.contentType}`)}return this.config.saveTransformedFiles&&this.hasTransformations(a)&&await this.saveTransformedFile(n,e,a,i),n}async fetch(e,t){const a=new URLSearchParams(t);return this.handle(e,a)}clearCache(e){this.imageTransformer?.clearCache(e),this.videoTransformer?.clearCache(e),this.audioTransformer?.clearCache(e)}async clearSavedTransformedFiles(){if(this.config.saveTransformedFiles)try{this.logger?.warn?.("clearSavedTransformedFiles requires custom storage implementation to find and delete transformed files")}catch(e){this.logger?.error?.(`Failed to clear saved transformed files: ${e}`)}}async clearSavedTransformedFilesForFile(e){if(this.config.saveTransformedFiles)try{this.logger?.warn?.("clearSavedTransformedFilesForFile requires custom storage implementation")}catch(t){this.logger?.error?.(`Failed to clear saved transformed files for ${e}: ${t}`)}}getCacheStats(){const e={audio:this.audioTransformer?.getCacheStats(),image:this.imageTransformer?.getCacheStats(),video:this.videoTransformer?.getCacheStats()};return e.image===void 0&&delete e.image,e.video===void 0&&delete e.video,e.audio===void 0&&delete e.audio,e}validateQueryParameters(e,t){switch(t){case"audio":{this.validateAudioQueryParameters(e);break}case"image":{this.validateImageQueryParameters(e);break}case"video":{this.validateVideoQueryParameters(e);break}}}validateImageQueryParameters(e){const t=new Set(["alphaQuality","angle","background","bandbool","blur","boolean","brightness","channel","clahe","colourspace","compressionLevel","convolve","cropHeight","cropWidth","delay","dilate","effort","erode","extractChannel","fastShrinkOnLoad","fit","flatten","flip","flop","format","frameRate","gamma","grayscale","greyscale","height","hue","joinChannel","kernel","left","lightness","linear","loop","maxSlope","median","modulate","negate","normalise","normalize","position","quality","recombine","saturation","sharpen","threshold","tint","top","unflatten","width","withoutEnlargement","withoutReduction"]),a=new Set(["bitrate","codec","frameRate","keyFrameInterval","numberOfChannels","sampleRate"]),r=[];for(const n of a)e[n]!==void 0&&r.push(n);if(r.length>0){const n=[...r].toSorted();throw new s(`Invalid query parameters for image transformation: ${n.join(", ")}. Images support: ${[...t].toSorted().join(", ")}. Video/audio parameters (${n.join(", ")}) are not supported for images.`,"INVALID_PARAMS_FOR_IMAGE","image",n,[...t].toSorted())}if(e.fit&&!["contain","cover","fill","inside","outside"].includes(e.fit))throw new s(`Invalid fit value: "${e.fit}". Supported values: "cover", "contain", "fill", "inside", "outside"`,"INVALID_FIT_VALUE","image",["fit"],["cover","contain","fill","inside","outside"]);if(e.format&&!["avif","gif","jpeg","png","tiff","webp"].includes(e.format))throw new s(`Invalid format for image: "${e.format}". Supported formats: jpeg, png, webp, avif, tiff, gif`,"INVALID_FORMAT","image",["format"],["jpeg","png","webp","avif","tiff","gif"]);const o=["left","top","cropWidth","cropHeight"],i=o.filter(n=>e[n]!==void 0);if(i.length>0&&i.length!==o.length)throw new s(`Incomplete crop parameters: ${i.join(", ")}. All crop parameters must be provided: left, top, cropWidth, cropHeight`,"INCOMPLETE_CROP_PARAMS","image",i,o)}validateVideoQueryParameters(e){const t=new Set(["angle","background","bitrate","codec","cropHeight","cropWidth","fit","format","frameRate","height","keyFrameInterval","left","position","quality","top","width","withoutEnlargement","withoutReduction"]),a=new Set(["numberOfChannels","sampleRate"]),r=[];for(const n of a)e[n]!==void 0&&r.push(n);if(r.length>0){const n=[...r].toSorted();throw new s(`Invalid query parameters for video transformation: ${n.join(", ")}. Videos support: ${[...t].toSorted().join(", ")}. Audio-only parameters (${n.join(", ")}) are not supported for videos.`,"INVALID_PARAMS_FOR_VIDEO","video",n,[...t].toSorted())}if(e.fit&&!["contain","cover","fill","inside","outside"].includes(e.fit))throw new s(`Invalid fit value: "${e.fit}". Supported values: "cover", "contain", "fill", "inside", "outside"`,"INVALID_FIT_VALUE","video",["fit"],["cover","contain","fill","inside","outside"]);if(e.codec&&!["av1","avc","hevc","vp8","vp9"].includes(e.codec))throw new s(`Invalid codec for video: "${e.codec}". Supported codecs: avc, hevc, vp8, vp9, av1`,"INVALID_VIDEO_CODEC","video",["codec"],["avc","hevc","vp8","vp9","av1"]);if(e.format&&!["mkv","mp4","ogg","webm"].includes(e.format))throw new s(`Invalid format for video: "${e.format}". Supported formats: mp4, webm, mkv, ogg`,"INVALID_VIDEO_FORMAT","video",["format"],["mp4","webm","mkv","ogg"]);const o=["left","top","cropWidth","cropHeight"],i=o.filter(n=>e[n]!==void 0);if(i.length>0&&i.length!==o.length)throw new s(`Incomplete crop parameters: ${i.join(", ")}. All crop parameters must be provided: left, top, cropWidth, cropHeight`,"INCOMPLETE_CROP_PARAMS","video",i,o);if(e.width!==void 0&&(typeof e.width!="number"||e.width<=0))throw new s(`Invalid width: ${e.width}. Must be a positive number.`,"INVALID_WIDTH","video",["width"],[]);if(e.height!==void 0&&(typeof e.height!="number"||e.height<=0))throw new s(`Invalid height: ${e.height}. Must be a positive number.`,"INVALID_HEIGHT","video",["height"],[]);if(e.bitrate!==void 0&&(typeof e.bitrate!="number"||e.bitrate<=0))throw new s(`Invalid bitrate: ${e.bitrate}. Must be a positive number.`,"INVALID_BITRATE","video",["bitrate"],[]);if(e.frameRate!==void 0&&(typeof e.frameRate!="number"||e.frameRate<=0))throw new s(`Invalid frameRate: ${e.frameRate}. Must be a positive number.`,"INVALID_FRAME_RATE","video",["frameRate"],[]);if(e.keyFrameInterval!==void 0&&(typeof e.keyFrameInterval!="number"||e.keyFrameInterval<=0))throw new s(`Invalid keyFrameInterval: ${e.keyFrameInterval}. Must be a positive number.`,"INVALID_KEY_FRAME_INTERVAL","video",["keyFrameInterval"],[])}generateTransformedFileId(e,t,a){const r=Object.keys(t).filter(n=>t[n]!==void 0).toSorted().map(n=>`${n}:${t[n]}`).join("|"),o=`${e}|${a}|${r}`,i=u("sha256").update(o).digest("hex").slice(0,16);return`${e}_transformed_${i}`}hasTransformations(e){return this.hasImageTransformations(e)||this.hasVideoTransformations(e)||this.hasAudioTransformations(e)}createMediaTransformResult(e,t,a){const r={buffer:e.content,format:this.getFormatFromContentType(e.contentType||""),mediaType:t,originalFile:a,size:e.content.length};switch(t){case"audio":return{...r,bitrate:e.bitrate,duration:e.duration,mediaType:"audio",numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate};case"image":return{...r,height:e.height,mediaType:"image",width:e.width};case"video":return{...r,bitrate:e.bitrate,duration:e.duration,height:e.height,mediaType:"video",width:e.width};default:return r}}getFormatFromContentType(e){return e?l.getExtension(e)||"application/octet-stream":""}async saveTransformedFile(e,t,a,r){try{const o=this.generateTransformedFileId(t,a,r),i={format:e.format,mediaType:r,originalFileId:t,size:e.size,transformation:a,transformedAt:new Date().toISOString()};r==="image"&&e.width&&e.height?(i.width=e.width,i.height=e.height):r==="video"&&e.width&&e.height?(i.width=e.width,i.height=e.height,i.duration=e.duration,i.bitrate=e.bitrate):r==="audio"&&(i.duration=e.duration,i.numberOfChannels=e.numberOfChannels,i.sampleRate=e.sampleRate,i.bitrate=e.bitrate),await this.storage.create({contentType:l.getType(e.format)??void 0,metadata:i,originalName:`${o}.${e.format}`,size:e.size}),this.logger?.debug?.(`Saved transformed file: ${o}`)}catch(o){this.logger?.error?.(`Failed to save transformed file: ${o}`)}}validateAudioQueryParameters(e){const t=new Set(["bitrate","codec","format","numberOfChannels","quality","sampleRate"]),a=new Set(["angle","background","cropHeight","cropWidth","fit","frameRate","height","keyFrameInterval","left","position","top","width","withoutEnlargement","withoutReduction"]),r=[];for(const o of a)e[o]!==void 0&&r.push(o);if(r.length>0){const o=[...r].toSorted();throw new s(`Invalid query parameters for audio transformation: ${o.join(", ")}. Audio supports: ${[...t].toSorted().join(", ")}. Video-only parameters (${o.join(", ")}) are not supported for audio.`,"INVALID_PARAMS_FOR_AUDIO","audio",o,[...t].toSorted())}if(e.codec&&!["aac","flac","mp3","opus","vorbis"].includes(e.codec))throw new s(`Invalid codec for audio: "${e.codec}". Supported codecs: aac, opus, mp3, vorbis, flac`,"INVALID_AUDIO_CODEC","audio",["codec"],["aac","opus","mp3","vorbis","flac"]);if(e.format&&!["aac","flac","mp3","ogg","wav"].includes(e.format))throw new s(`Invalid format for audio: "${e.format}". Supported formats: mp3, wav, ogg, aac, flac`,"INVALID_AUDIO_FORMAT","audio",["format"],["mp3","wav","ogg","aac","flac"]);if(e.bitrate!==void 0&&(typeof e.bitrate!="number"||e.bitrate<=0))throw new s(`Invalid bitrate: ${e.bitrate}. Must be a positive number.`,"INVALID_BITRATE","audio",["bitrate"],[]);if(e.numberOfChannels!==void 0&&(typeof e.numberOfChannels!="number"||e.numberOfChannels<=0||e.numberOfChannels>8))throw new s(`Invalid numberOfChannels: ${e.numberOfChannels}. Must be a number between 1 and 8.`,"INVALID_CHANNEL_COUNT","audio",["numberOfChannels"],["1","2","3","4","5","6","7","8"]);if(e.sampleRate!==void 0){const o=[8e3,11025,16e3,22050,32e3,44100,48e3,88200,96e3,192e3];if(typeof e.sampleRate!="number"||!o.includes(e.sampleRate))throw new s(`Invalid sampleRate: ${e.sampleRate}. Supported sample rates: ${o.join(", ")}`,"INVALID_SAMPLE_RATE","audio",["sampleRate"],o.map(String))}}async handleImageTransformation(e,t){const a=[];this.hasImageTransformations(t)&&((t.width||t.height||t.fit)&&a.push({options:{fit:t.fit,height:t.height,position:t.position,width:t.width,withoutEnlargement:t.withoutEnlargement,withoutReduction:t.withoutReduction},type:"resize"}),t.left!==void 0&&t.top!==void 0&&t.cropWidth&&t.cropHeight&&a.push({options:{height:t.cropHeight,left:t.left,top:t.top,width:t.cropWidth},type:"crop"}),t.angle&&a.push({options:{angle:t.angle,background:t.background},type:"rotate"}),t.format?a.push({options:{format:t.format,quality:t.quality},type:"format"}):t.quality&&a.push({options:{quality:t.quality},type:"quality"}));const r=a.length>0?await this.imageTransformer.transform(e,a):await this.imageTransformer.transform(e,[]);return this.convertImageResult(r)}async handleVideoTransformation(e,t){const a=[];this.hasVideoTransformations(t)&&((t.width||t.height||t.fit)&&a.push({options:{fit:t.fit,height:t.height,position:t.position,width:t.width,withoutEnlargement:t.withoutEnlargement,withoutReduction:t.withoutReduction},type:"resize"}),t.left!==void 0&&t.top!==void 0&&t.cropWidth&&t.cropHeight&&a.push({options:{height:Number(t.cropHeight),left:t.left,top:t.top,width:t.cropWidth},type:"crop"}),t.angle&&a.push({options:{angle:t.angle,background:t.background},type:"rotate"}),(t.codec||t.bitrate)&&a.push({options:{bitrate:t.bitrate||t.quality,codec:t.codec,frameRate:t.frameRate,keyFrameInterval:t.keyFrameInterval},type:"codec"}),t.format&&a.push({options:{format:t.format},type:"format"}));const r=a.length>0?await this.videoTransformer.transform(e,a):await this.videoTransformer.transform(e,[]);return this.convertVideoResult(r)}async handleAudioTransformation(e,t){const a=[];this.hasAudioTransformations(t)&&(t.sampleRate&&a.push({options:{sampleRate:t.sampleRate},type:"resample"}),t.numberOfChannels&&a.push({options:{numberOfChannels:t.numberOfChannels},type:"channels"}),(t.codec||t.bitrate)&&a.push({options:{bitrate:t.bitrate||t.quality,codec:t.codec},type:"codec"}),t.format&&a.push({options:{format:t.format},type:"format"}));const r=a.length>0?await this.audioTransformer.transform(e,a):await this.audioTransformer.transform(e,[]);return this.convertAudioResult(r)}parseQuery(e){if(typeof e=="string")return this.parseURLSearchParams(new URLSearchParams(e));if(e instanceof URLSearchParams)return this.parseURLSearchParams(e);const t=e;return e.left&&(t.left=Number.parseInt(e.left,10)),e.top&&(t.top=Number.parseInt(e.top,10)),e.cropWidth&&(t.cropWidth=Number.parseInt(e.cropWidth,10)),e.cropHeight&&(t.cropHeight=Number.parseInt(e.cropHeight,10)),e.angle&&(t.angle=Number.parseInt(e.angle,10)),e.quality&&(t.quality=Number.parseInt(e.quality,10)),e.width&&(t.width=Number.parseInt(e.width,10)),e.height&&(t.height=Number.parseInt(e.height,10)),e.bitrate&&(t.bitrate=Number.parseInt(e.bitrate,10)),e.frameRate&&(t.frameRate=Number.parseInt(e.frameRate,10)),e.keyFrameInterval&&(t.keyFrameInterval=Number.parseInt(e.keyFrameInterval,10)),e.numberOfChannels&&(t.numberOfChannels=Number.parseInt(e.numberOfChannels,10)),e.sampleRate&&(t.sampleRate=Number.parseInt(e.sampleRate,10)),t}parseBooleanParameter(e){if(e!==null)return e==="true"||e==="1"}parseURLSearchParams(e){const t={};if(e.has("format")&&(t.format=e.get("format")??void 0),e.has("quality")&&(t.quality=e.get("quality")?Number.parseInt(e.get("quality"),10):void 0),e.has("width")&&(t.width=e.get("width")?Number.parseInt(e.get("width"),10):void 0),e.has("height")&&(t.height=e.get("height")?Number.parseInt(e.get("height"),10):void 0),e.has("fit")){const a=e.get("fit");a&&["contain","cover","fill","inside","outside"].includes(a)&&(t.fit=a)}if(e.has("position")&&(t.position=e.get("position")??void 0),e.has("withoutEnlargement")){const a=e.get("withoutEnlargement");t.withoutEnlargement=a==="true"?!0:void 0}if(e.has("withoutReduction")){const a=e.get("withoutReduction");t.withoutReduction=a==="true"?!0:void 0}if(e.has("left")&&(t.left=e.get("left")?Number.parseInt(e.get("left"),10):void 0),e.has("top")&&(t.top=e.get("top")?Number.parseInt(e.get("top"),10):void 0),e.has("cropWidth")&&(t.cropWidth=e.get("cropWidth")?Number.parseInt(e.get("cropWidth"),10):void 0),e.has("cropHeight")&&(t.cropHeight=e.get("cropHeight")?Number.parseInt(e.get("cropHeight"),10):void 0),e.has("angle")){const a=e.get("angle")?Number.parseInt(e.get("angle"),10):void 0;a!==void 0&&(t.angle=a)}if(e.has("background")&&(t.background=e.get("background")??void 0),e.has("blur")&&(t.blur=this.parseBooleanParameter(e.get("blur"))),e.has("sharpen")&&(t.sharpen=this.parseBooleanParameter(e.get("sharpen"))),e.has("median")&&(t.median=e.get("median")?Number.parseInt(e.get("median"),10):void 0),e.has("clahe")&&(t.clahe=this.parseBooleanParameter(e.get("clahe"))),e.has("threshold")&&(t.threshold=e.get("threshold")?Number.parseInt(e.get("threshold"),10):void 0),e.has("gamma")&&(t.gamma=this.parseBooleanParameter(e.get("gamma"))),e.has("negate")&&(t.negate=this.parseBooleanParameter(e.get("negate"))),(e.has("normalise")||e.has("normalize"))&&(t.normalise=this.parseBooleanParameter(e.get("normalise"))||this.parseBooleanParameter(e.get("normalize"))),e.has("flatten")&&(t.flatten=this.parseBooleanParameter(e.get("flatten"))),e.has("unflatten")&&(t.unflatten=this.parseBooleanParameter(e.get("unflatten"))),e.has("flip")&&(t.flip=this.parseBooleanParameter(e.get("flip"))),e.has("flop")&&(t.flop=this.parseBooleanParameter(e.get("flop"))),e.has("affine")&&(t.affine=this.parseBooleanParameter(e.get("affine"))),e.has("dilate")&&(t.dilate=this.parseBooleanParameter(e.get("dilate"))),e.has("erode")&&(t.erode=this.parseBooleanParameter(e.get("erode"))),e.has("pipelineColourspace")&&(t.pipelineColourspace=this.parseBooleanParameter(e.get("pipelineColourspace"))),e.has("toColourspace")&&(t.toColourspace=this.parseBooleanParameter(e.get("toColourspace"))),e.has("removeAlpha")&&(t.removeAlpha=this.parseBooleanParameter(e.get("removeAlpha"))),e.has("ensureAlpha")&&(t.ensureAlpha=this.parseBooleanParameter(e.get("ensureAlpha"))),(e.has("greyscale")||e.has("grayscale"))&&(t.greyscale=this.parseBooleanParameter(e.get("greyscale"))||this.parseBooleanParameter(e.get("grayscale"))),e.has("modulate")&&(t.modulate=this.parseBooleanParameter(e.get("modulate"))),e.has("tint")&&(t.tint=this.parseBooleanParameter(e.get("tint"))),e.has("brightness")&&(t.brightness=e.get("brightness")?Number.parseFloat(e.get("brightness")):void 0),e.has("saturation")&&(t.saturation=e.get("saturation")?Number.parseFloat(e.get("saturation")):void 0),e.has("hue")&&(t.hue=e.get("hue")?Number.parseInt(e.get("hue"),10):void 0),e.has("lightness")&&(t.lightness=e.get("lightness")?Number.parseInt(e.get("lightness"),10):void 0),e.has("kernel")&&(t.kernel=e.get("kernel")??void 0),e.has("fastShrinkOnLoad")&&(t.fastShrinkOnLoad=e.get("fastShrinkOnLoad")==="true"),e.has("codec")){const a=e.get("codec");a&&["avc","hevc","vp8","vp9","av1","aac","opus","mp3","vorbis","flac"].includes(a)&&(t.codec=a)}return e.has("bitrate")&&(t.bitrate=e.get("bitrate")?Number.parseInt(e.get("bitrate"),10):void 0),e.has("frameRate")&&(t.frameRate=e.get("frameRate")?Number.parseInt(e.get("frameRate"),10):void 0),e.has("keyFrameInterval")&&(t.keyFrameInterval=e.get("keyFrameInterval")?Number.parseInt(e.get("keyFrameInterval"),10):void 0),e.has("numberOfChannels")&&(t.numberOfChannels=e.get("numberOfChannels")?Number.parseInt(e.get("numberOfChannels"),10):void 0),e.has("sampleRate")&&(t.sampleRate=e.get("sampleRate")?Number.parseInt(e.get("sampleRate"),10):void 0),t}detectMediaType(e){if(!e)throw new Error("Cannot detect media type: no content type provided");if(!c(e))throw new Error(`Unknown or invalid content type: ${e}`);if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video";if(e.startsWith("audio/"))return"audio";throw new Error(`Unsupported media type for content type: ${e}`)}hasImageTransformations(e){return!!(e.width||e.height||e.fit||e.position||e.withoutEnlargement||e.withoutReduction||e.left!==void 0||e.top!==void 0||e.cropWidth||e.cropHeight||e.angle!==void 0||e.background||e.blur||e.sharpen||e.median||e.clahe||e.threshold!==void 0||e.gamma||e.negate||e.normalise||e.flatten||e.unflatten||e.flip||e.flop||e.greyscale||e.modulate||e.tint||e.brightness!==void 0||e.saturation!==void 0||e.hue!==void 0||e.lightness!==void 0||e.kernel||e.fastShrinkOnLoad||e.affine||e.dilate||e.erode||e.pipelineColourspace||e.toColourspace||e.removeAlpha||e.ensureAlpha||e.format||e.quality)}hasVideoTransformations(e){return!!(e.width||e.height||e.fit||e.position||e.withoutEnlargement||e.withoutReduction||e.left!==void 0||e.top!==void 0||e.cropWidth||e.cropHeight||e.angle||e.background||e.codec||e.bitrate||e.frameRate||e.keyFrameInterval||e.format||e.quality)}hasAudioTransformations(e){return!!(e.sampleRate||e.numberOfChannels||e.codec||e.bitrate||e.format||e.quality)}convertImageResult(e){return{buffer:e.buffer,format:e.format,height:e.height,mediaType:"image",originalFile:e.originalFile,size:e.size,width:e.width}}convertVideoResult(e){return{bitrate:e.bitrate,buffer:e.buffer,duration:e.duration,format:e.format,height:e.height,mediaType:"video",originalFile:e.originalFile,size:e.size,width:e.width}}convertAudioResult(e){return{bitrate:e.bitrate,buffer:e.buffer,duration:e.duration,format:e.format,mediaType:"audio",numberOfChannels:e.numberOfChannels,originalFile:e.originalFile,sampleRate:e.sampleRate,size:e.size}}}export{F as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var s=Object.defineProperty;var r=(t,e)=>s(t,"name",{value:e,configurable:!0});var o=Object.defineProperty,a=r((t,e)=>o(t,"name",{value:e,configurable:!0}),"r");class f{static{r(this,"o")}static{a(this,"MetaStorage")}prefix="";suffix="";logger;constructor(e){this.prefix=e?.prefix??"",this.suffix=e?.suffix??".META",this.logger=e?.logger}async save(e,i){return i}async delete(e){throw new Error("Not implemented")}async get(e){throw new Error("Not implemented")}async touch(e,i){throw new Error("Not implemented")}getMetaName(e){return this.prefix+e+this.suffix}getIdFromMetaName(e){return e.slice(this.prefix.length,-this.suffix.length)}}export{f as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var u=Object.defineProperty;var l=(e,t)=>u(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,p=l((e,t)=>d(e,"name",{value:t,configurable:!0}),"o");const c=p(e=>e!==null&&typeof e=="object"&&!Array.isArray(e),"isRecord");var g=Object.defineProperty,n=l((e,t)=>g(e,"name",{value:t,configurable:!0}),"i");const y=" ".codePointAt(0)??32,m=",".codePointAt(0)??44,v=/^[\d+/A-Z]*={0,2}$/i,b=n(e=>{if(typeof e!="string")return!1;const t=Number.parseFloat(e);return!Number.isNaN(t)&&Number.isFinite(t)},"isNumeric");class j{static{l(this,"Metadata")}static{n(this,"Metadata")}psize;pname;pfiletype;ptype;pmimeType;pcontentType;ptitle;pfilename;poriginalName;plastModified}const A=n(e=>c(e),"isMetadata"),h=n(e=>{if(e.length===0)return!1;for(let t=0;t<e.length;t+=1){const a=e.codePointAt(t);if(a>127||a===y||a===m)return!1}return!0},"validateKey"),M=n(e=>e.length%4!==0?!1:v.test(e),"validateValue"),O=n(e=>Object.entries(e).map(([t,a])=>{if(a==null)return t;const i=typeof a=="object"?JSON.stringify(a):String(a),o=Buffer.from(i,"utf8").toString("base64");return`${t} ${o}`}).join(","),"stringifyMetadata"),P=n(e=>{const t={};if(!e||e.trim().length===0)throw new Error("Metadata string is not valid");for(const a of e.split(",")){const i=a.split(" "),[o,f]=i;if((i.length===1||i.length===2)&&h(o)&&(i.length===1||M(f))&&!(o in t)){let r="";i.length===1?r=void 0:f&&(r=Buffer.from(f,"base64").toString("utf8"));let s=r;if(r!==void 0)try{s=JSON.parse(r)}catch{r==="true"?s=!0:r==="false"?s=!1:b(r)&&(s=Number(r))}t[o]=s}else throw new Error("Metadata string is not valid")}return t},"parseMetadata");export{j as Metadata,A as isMetadata,P as parseMetadata,O as stringifyMetadata,h as validateKey,M as validateValue};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var h=Object.defineProperty;var d=(s,t)=>h(s,"name",{value:t,configurable:!0});import{Readable as o}from"node:stream";import{parseMultipartRequest as c,MaxFileSizeExceededError as p,MultipartParseError as f}from"@remix-run/multipart-parser";import{n as i}from"./headers-DC2MEOrK.js";import{d as g}from"./validator-DK41xp8N.js";import{O as x}from"./base-handler-fetch-DnarP64X.js";import{F as S}from"./multipart-base-C6OjBwMS.js";var y=Object.defineProperty,l=d((s,t)=>y(s,"name",{value:t,configurable:!0}),"l");const w=/^multipart\/.+|application\/x-www-form-urlencoded$/i,z=l(s=>{try{const t=new URL(s).pathname.split("/").filter(Boolean);return t[t.length-1]||void 0}catch{return}},"getIdFromRequestUrl");class m extends x{static{d(this,"d")}static{l(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 S{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(!w.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 u=t.url;return this.multipartBase.handlePost(a,e,u)}catch(e){throw e instanceof p?i(413,"File size limit exceeded"):e instanceof f?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=z(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};
|
|
@@ -0,0 +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-DaggCVsq.js";import{d as c}from"./validator-DK41xp8N.js";import{F as p}from"./base-handler-node-BTes6sql.js";import{F as g}from"./multipart-base-C6OjBwMS.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var r=Object.defineProperty;var a=(e,t)=>r(e,"name",{value:t,configurable:!0});import l from"./File-alcSNpLq.js";var i=Object.defineProperty,o=a((e,t)=>i(e,"name",{value:t,configurable:!0}),"e");class n extends l{static{a(this,"p")}static{o(this,"NetlifyBlobFile")}url;pathname}export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var r=Object.defineProperty;var a=(t,e)=>r(t,"name",{value:e,configurable:!0});import{O as o}from"./local-meta-storage-Bkwqi_gi.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 p=Object.defineProperty;var h=(o,e)=>p(o,"name",{value:e,configurable:!0});import{getStore as d}from"@netlify/blobs";import{o as f,r as w,a as b}from"./part-match-DqD5U7An.js";import{B as g,t as m,u as E}from"./storage-m_Cxgiih.js";import{createRetryWrapper as O}from"./isRetryableError-DQNSZiBc.js";import{O as N}from"./local-meta-storage-Bkwqi_gi.js";import u from"./NetlifyBlobFile-CpzkMKng.js";import{u as T}from"./update-size-DANV7aa2.js";import{o as k}from"./has-content-Bx2p8Okx.js";var B=Object.defineProperty,y=h((o,e)=>B(o,"name",{value:e,configurable:!0}),"f");class U extends g{static name="netlify-blob";checksumTypes=["md5"];meta;storeName;siteID;token;store;retry;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=d({name:this.storeName,...this.siteID&&{siteID:this.siteID},...this.token&&{token:this.token}});const t={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:y(n=>{if(n instanceof Error){const s=n.code;if(s==="ECONNRESET"||s==="ETIMEDOUT"||s==="ENOTFOUND"||s==="ECONNREFUSED")return!0}const i=n;return!!(i.status&&[408,429,500,502,503,504].includes(i.status))},"shouldRetry"),...e.retryConfig};this.retry=O(t);const{metaStorage:a,metaStorageConfig:r}=e;this.meta=a||new N(r),this.isReady=!0}async create(e){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const r=typeof e.ttl=="string"?m(e.ttl):e.ttl;t.expiredAt=r===void 0?void 0:Date.now()+r}const a=new u(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=f(a),await this.saveMeta(a),await this.onCreate(a),a})}async write(e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&T(t,e.size),!w(e,t))throw new Error("File part does not match");await this.lock(e.id);try{if(k(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],r=e.body;for await(const i of r)a.push(Buffer.from(i));const n=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const i=await b(n);i?.mime&&(t.contentType=i.mime)}catch{}await this.retry(()=>this.store.set(t.name,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),{metadata:{contentType:t.contentType,...t.metadata}})),t.pathname=t.name,t.url=this.getBlobUrl(t.name),t.bytesWritten=n.length}return t.status=f(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id)}})}async delete({id:e}){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.retry(()=>this.store.delete(t.pathname))}catch(r){this.logger?.error("Failed to delete blob from Netlify Blob:",r);const n=this.normalizeError(r instanceof Error?r:new Error(String(r)));await this.onError(n)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);return!t.pathname||t.pathname.length<=0?!1:await this.retry(()=>this.store.get(t.pathname,{type:"blob"}))!=null}catch{return!1}})}async get({id:e}){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.retry(()=>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.retry(()=>a.arrayBuffer());else throw new Error("Invalid blob type returned from Netlify Blob");const n=Buffer.from(r);let i=null;try{i=await this.store.getMetadata?.(t.pathname)??null}catch{}return{content:n,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||n.length}})}async copy(e,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.retry(()=>this.store.get(a.pathname,{type:"blob"}));if(!r)throw new Error("Source file not found in Netlify Blob");let n=null;try{const l=this.store;l.getMetadata&&a.pathname&&(n=await l.getMetadata(a.pathname))}catch{}let i;if(typeof r=="string")i=Buffer.from(r,"utf8").buffer;else if(r&&typeof r=="object"&&"arrayBuffer"in r){const l=r;i=await this.retry(()=>l.arrayBuffer())}else throw new Error("Invalid blob type returned from Netlify Blob");const s=Buffer.from(i);await this.retry(()=>this.store.set(t,s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),{metadata:n||{contentType:a.contentType,...a.metadata}}));const c={...a,id:t,name:t,pathname:t,url:this.getBlobUrl(t)};return await this.saveMeta(c),c})}async move(e,t){return this.instrumentOperation("move",async()=>{const a=await this.copy(e,t);return await this.delete({id:e}),a})}async update({id:e},t){return this.instrumentOperation("update",async()=>{const a=await this.getMeta(e),r={...t};if("ttl"in r&&r.ttl!==void 0){const i=r.ttl,s=typeof i=="string"?m(i):i;s!==void 0&&(r.expiredAt=Date.now()+s),delete r.ttl}E(a,r),await this.saveMeta(a);const n={...a,status:"updated"};return await this.onUpdate(n),n})}async list(e=1e3){return this.instrumentOperation("list",async()=>{const t=await this.retry(()=>this.store.list()),a=[];for await(const r of t.blobs){let n=null;try{n=await this.store.getMetadata?.(r.key)??null}catch{}const i=new u({contentType:n?.contentType||"application/octet-stream",metadata:n?.metadata||{},originalName:r.key}),s=r;if(i.createdAt=s.createdAt?.toISOString(),i.id=r.key,i.modifiedAt=s.updatedAt?.toISOString(),i.name=r.key,i.pathname=r.key,i.size=s.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var n=Object.defineProperty;var r=(t,e)=>n(t,"name",{value:e,configurable:!0});var s=Object.defineProperty,c=r((t,e)=>s(t,"name",{value:e,configurable:!0}),"n");class g{static{r(this,"u")}static{c(this,"NoOpMetrics")}increment(e,i,a){}timing(e,i,a){}gauge(e,i,a){}}export{g as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var n=Object.defineProperty;var a=(i,e)=>n(i,"name",{value:e,configurable:!0});import{metrics as c}from"@opentelemetry/api";var g=Object.defineProperty,h=a((i,e)=>g(i,"name",{value:e,configurable:!0}),"n");class d{static{a(this,"p")}static{h(this,"OpenTelemetryMetrics")}meter;counters=new Map;histograms=new Map;gauges=new Map;constructor(e){this.meter=e||c.getMeter("@visulima/storage","1.0.0")}increment(e,t=1,s){if(!this.counters.has(e)){const o={description:`Counter for ${e}`};this.counters.set(e,this.meter.createCounter(e,o))}const r=this.counters.get(e);if(!r)throw new Error(`Counter ${e} was not created`);r.add(t,s)}timing(e,t,s){if(!this.histograms.has(e)){const o={description:`Duration histogram for ${e}`,unit:"ms"};this.histograms.set(e,this.meter.createHistogram(e,o))}const r=this.histograms.get(e);if(!r)throw new Error(`Histogram ${e} was not created`);r.record(t,s)}gauge(e,t,s){if(!this.gauges.has(e)){const o={description:`Gauge for ${e}`};this.gauges.set(e,this.meter.createUpDownCounter(e,o))}const r=this.gauges.get(e);if(!r)throw new Error(`Gauge ${e} was not created`);r.add(t,s)}}export{d as default};
|
|
@@ -0,0 +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-DaggCVsq.js";import{F as w}from"./base-handler-node-BTes6sql.js";import{A as O,v as B,a as N,e as I,p as x,b as E}from"./rest-base-B2Dv7esY.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var N=Object.defineProperty;var u=(o,e)=>N(o,"name",{value:e,configurable:!0});import{n}from"./headers-DC2MEOrK.js";import{ERRORS as f}from"./ERRORS-B9jkvKwx.js";import{b as p}from"./base-handler-core-DaggCVsq.js";import{O as x}from"./base-handler-fetch-DnarP64X.js";import{A as F,c as m}from"./rest-base-B2Dv7esY.js";var O=Object.defineProperty,g=u((o,e)=>O(o,"name",{value:e,configurable:!0}),"c");class y extends x{static{u(this,"g")}static{g(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(i,t){return r.buildFileUrl({url:i},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",i=e.headers.get("content-length"),t=i?Number.parseInt(i,10):0;if(!r){if(!i||Number.isNaN(t)||t===0)throw n(400,"Content-Length is required and must be greater than 0");if(e.body===null)throw n(400,"Request body is required")}if(t>this.storage.maxUploadSize)throw n(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const s=e.headers.get("content-type")||"application/octet-stream",a=B(e,t,s),d=e.url,h=e.body?p(e):void 0;return this.restBase.handlePost(a,r,d,h,t)}async put(e){const r=l(e.url);if(!r)throw n(400,"File ID is required in URL path");if(e.body===null)throw n(400,"Request body is required");const i=e.headers.get("content-length"),t=i?Number.parseInt(i,10):0;if(t===0)throw n(400,"Content-Length is required and must be greater than 0");if(t>this.storage.maxUploadSize)throw n(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const s=e.headers.get("content-type")||"application/octet-stream",a=e.headers.get("x-file-metadata");let d;if(a)try{d=JSON.parse(a)}catch{}const h=m(e.headers.get("content-disposition")),c={contentType:s,metadata:d||{},originalName:h,size:t},b=e.url,w=p(e);return this.restBase.handlePut(r,c,b,w,t,d)}async delete(e){const r=new URL(e.url).searchParams.get("ids");if(r){const t=r.split(",").map(s=>s.trim()).filter(Boolean);if(t.length===0)throw n(400,"No file IDs provided");return this.restBase.deleteBatch(t)}if((e.headers.get("content-type")||"").includes("application/json"))try{const t=await e.text(),s=JSON.parse(t);if(Array.isArray(s)){if(s.length===0)throw n(400,"No file IDs provided");return this.restBase.deleteBatch(s)}if(typeof s=="object"&&s!==null&&"ids"in s&&Array.isArray(s.ids)){const a=s.ids;if(a.length===0)throw n(400,"No file IDs provided");return this.restBase.deleteBatch(a)}}catch(t){if(t.statusCode===400)throw t}const i=l(e.url);if(!i)throw n(404,"File not found");try{return this.restBase.deleteSingle(i)}catch(t){const s=t;throw s.UploadErrorCode===f.FILE_NOT_FOUND||s.code==="ENOENT"?n(404,"File not found"):t}}async patch(e){const r=l(e.url);if(!r)throw n(404,"File not found");if(e.body===null)throw n(400,"Request body is required");const i=e.headers.get("content-length"),t=i?Number.parseInt(i,10):0;if(t===0)throw n(400,"Content-Length is required and must be greater than 0");const s=e.headers.get("x-chunk-offset"),a=s?Number.parseInt(s,10):void 0;if(a===void 0)throw n(400,"X-Chunk-Offset header is required");const d=e.headers.get("x-chunk-checksum")||void 0,h=e.url,c=p(e);return this.restBase.handlePatch(r,a,t,d,h,c)}async head(e){const r=l(e.url);if(!r)throw n(404,"File not found");try{return this.restBase.handleHead(r)}catch(i){const t=i;throw t.UploadErrorCode===f.FILE_NOT_FOUND||t.code==="ENOENT"?n(404,"File not found"):i}}async options(e){return this.restBase.handleOptions(y.methods,this.storage.maxUploadSize)}async get(e){throw n(500,"GET requests should be handled via fetch() method")}}const B=g((o,e,r)=>{const i=o.headers.get("x-total-size"),t=i?Number.parseInt(i,10):e,s=o.headers.get("x-file-metadata");let a={};if(s)try{a=JSON.parse(s)}catch{}const d=m(o.headers.get("content-disposition"));return{contentType:r,metadata:a,originalName:d,size:t}},"extractFileInitFromRequest"),l=g(o=>{try{const e=new URL(o).pathname.split("/").filter(Boolean),r=e[e.length-1];return r&&r.replace(/\.[^.]+$/,"")||null}catch{return null}},"getIdFromRequestUrl");export{y as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var t=(e,r)=>a(e,"name",{value:r,configurable:!0});import s from"./File-alcSNpLq.js";var i=Object.defineProperty,l=t((e,r)=>i(e,"name",{value:r,configurable:!0}),"t");class d extends s{static{t(this,"e")}static{l(this,"S3File")}Parts;UploadId;uri;partsUrls;partSize}export{d as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var r=Object.defineProperty;var o=(c,t)=>r(c,"name",{value:t,configurable:!0});import{S3Client as d,HeadObjectCommand as m,DeleteObjectCommand as h,PutObjectCommand as u,waitUntilBucketExists as f}from"@aws-sdk/client-s3";import{fromIni as l}from"@aws-sdk/credential-providers";import p from"./MetaStorage-Y4m1dWgd.js";import{parseMetadata as w,stringifyMetadata as k}from"./Metadata-B6Ir0KO7.js";import{o as b}from"./is-expired-1JuZjDtb.js";var g=Object.defineProperty,y=o((c,t)=>g(c,"name",{value:t,configurable:!0}),"c");class B extends p{static{o(this,"b")}constructor(t){super(t),this.config=t;const{client:e,...a}=t,i=a.bucket||process.env.S3_BUCKET;if(e===void 0){if(!i)throw new Error("S3 bucket is not defined");const n=a.keyFile||process.env.S3_KEYFILE;n&&(a.credentials=l({configFilepath:n})),this.client=new d(a),this.accessCheck(i).catch(s=>{throw s})}else this.client=e;this.bucket=i}config;static{y(this,"S3MetaStorage")}bucket;client;async get(t){const e=this.getMetaName(t),a={Bucket:this.bucket,Key:e},{Expires:i,Metadata:n}=await this.client.send(new m(a));if(i&&b({expiredAt:i}))throw await this.delete(e),new Error(`Metafile ${t} not found`);if(n?.metadata!==void 0){const s=JSON.parse(decodeURIComponent(n.metadata));return s.metadata&&typeof s.metadata=="string"&&(s.metadata=w(s.metadata)),s}throw new Error(`Metafile ${t} not found`)}async touch(t,e){return this.save(t,e)}async delete(t){const e={Bucket:this.bucket,Key:this.getMetaName(t)};await this.client.send(new h(e))}async save(t,e){const a={...e};a.metadata&&(a.metadata=k(e.metadata));const i=encodeURIComponent(JSON.stringify(a)),n={Bucket:this.bucket,ContentLength:0,Key:this.getMetaName(t),Metadata:{metadata:i}};return await this.client.send(new u(n)),e}async accessCheck(t,e=30){await f({client:this.client,maxWaitTime:e},{Bucket:t})}}export{B as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var h=Object.defineProperty;var u=(i,e)=>h(i,"name",{value:e,configurable:!0});import{Readable as p}from"node:stream";import{CreateMultipartUploadCommand as C,UploadPartCommand as g,CompleteMultipartUploadCommand as f,AbortMultipartUploadCommand as k,ListPartsCommand as w,GetObjectCommand as b,HeadObjectCommand as B,DeleteObjectCommand as S,CopyObjectCommand as E,ListObjectsV2Command as T,waitUntilBucketExists as U,S3Client as K}from"@aws-sdk/client-s3";import{fromIni as x}from"@aws-sdk/credential-providers";import{S as L}from"./s3-base-storage-xHZNtsGe.js";import{ReadableStream as y}from"node:stream/web";import{getSignedUrl as M}from"@aws-sdk/s3-request-presigner";import P from"./S3File-Du6wP0Sz.js";import I from"./S3MetaStorage-vcriiosn.js";var A=Object.defineProperty,O=u((i,e)=>A(i,"name",{value:e,configurable:!0}),"s");class j{static{u(this,"T")}constructor(e,a){this.client=e}client;static{O(this,"S3ClientAdapter")}async createMultipartUpload(e){const a=new C({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),t=await this.client.send(a);if(!t.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:t.UploadId}}async uploadPart(e){const a=e.Body instanceof y?p.fromWeb(e.Body):e.Body,t=new g({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),n=await this.client.send(t);if(!n.ETag)throw new Error("Failed to upload part");return{ETag:n.ETag}}async completeMultipartUpload(e){const a=new f({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:n,PartNumber:o})=>({ETag:n,PartNumber:o}))},UploadId:e.UploadId}),t=await this.client.send(a);if(!t.Location)throw new Error("Failed to complete multipart upload");return{ETag:t.ETag,Location:t.Location}}async abortMultipartUpload(e){const a=new k({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a)}async listParts(e){const a=new w({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),t=await this.client.send(a),n=[];if(t.Parts)for(const o of t.Parts)o.ETag&&o.PartNumber&&n.push({ETag:o.ETag,PartNumber:o.PartNumber,Size:o.Size});return{Parts:n.length>0?n:void 0}}async getObject(e){const a=new b({Bucket:e.Bucket,Key:e.Key}),t=await this.client.send(a);let n;if(t.Body){const o=t.Body;o instanceof p||typeof o=="object"&&"transform"in o&&o instanceof y?n=o:n=p.from(o)}return{Body:n,ContentLength:t.ContentLength,ContentType:t.ContentType,ETag:t.ETag,Expires:t.Expires,LastModified:t.LastModified,Metadata:t.Metadata}}async headObject(e){const a=new B({Bucket:e.Bucket,Key:e.Key}),t=await this.client.send(a);return{ContentLength:t.ContentLength,ContentType:t.ContentType,ETag:t.ETag,Expires:t.Expires,LastModified:t.LastModified}}async deleteObject(e){const a=new S({Bucket:e.Bucket,Key:e.Key});await this.client.send(a)}async copyObject(e){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const t=new E(a);await this.client.send(t)}async listObjectsV2(e){const a=new T({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,MaxKeys:e.MaxKeys}),t=await this.client.send(a);return{Contents:t.Contents?.map(n=>({Key:n.Key,LastModified:n.LastModified})),IsTruncated:t.IsTruncated,NextContinuationToken:t.NextContinuationToken}}async getPresignedUrl(e){const a=new g({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return M(this.client,a,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await U({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}var N=Object.defineProperty,v=u((i,e)=>N(i,"name",{value:e,configurable:!0}),"u");class H extends L{static name="s3";s3Api;constructor(e){const{bucket:a=process.env.S3_BUCKET,region:t=process.env.S3_REGION}=e;if(!a)throw new Error("S3 bucket is not defined");if(!t)throw new Error("S3 region is not defined");e.region=t;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=x({configFilepath:n}));const o=new K(e);super({bucket:a,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:v(s=>{const r=s;if(r.$metadata){const l=r.$metadata.httpStatusCode;if(l&&[408,429,500,502,503,504].includes(l)||r.$fault==="server")return!0}return r.retryable??!1},"shouldRetry")}}),this.s3Api=new j(o,a);const{metaStorage:d,metaStorageConfig:c}=e;if(!d){const s={...e,...c,logger:this.logger};"directory"in s||(this.meta=new I(s))}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},a){if(this.config.clientDirectUpload){const t=await this.getMeta(e);return this.buildPresigned({...t,...a})}return super.update({id:e},a)}async getStream({id:e}){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),{Body:t,ContentLength:n,ContentType:o,ETag:d,Expires:c,LastModified:s}=await this.retry(()=>a.getObject({Bucket:this.bucket,Key:e}));await this.checkIfExpired({expiredAt:c});const r=t,l=new p({read(){r.on("data",m=>{this.push(m)}),r.on("end",()=>{this.push(null)}),r.on("error",m=>{this.destroy(m)})}});return{headers:{"Content-Length":n?.toString()??"0","Content-Type":o,...d&&{ETag:d},...c&&{"X-Upload-Expires":c.toString()},...s&&{"Last-Modified":s.toString()}},size:Number(n),stream:l}})}getS3Api(){return this.s3Api}getFileClass(){return P}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{H as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var M=Object.defineProperty;var v=(u,t)=>M(u,"name",{value:t,configurable:!0});import{n as s,H as z}from"./headers-DC2MEOrK.js";import{Metadata as W}from"./Metadata-B6Ir0KO7.js";var H=Object.defineProperty,L=v((u,t)=>H(u,"name",{value:t,configurable:!0}),"x");const T="1.0.0",N="1.0.0",x=L((u="")=>{const t=u.split(",").map(o=>o.split(" ")),e=Object.create(W.prototype);return Object.values(t).forEach(([o,r])=>{o&&(e[o]=r?Buffer.from(r,"base64").toString():"")}),e},"parseMetadata"),k=L(u=>!u||Object.keys(u).length===0?"":Object.entries(u).map(([t,e])=>e===void 0?t:`${t} ${Buffer.from(String(e)).toString("base64")}`).toString(),"serializeMetadata");class j{static{v(this,"TusBase")}static{L(this,"TusBase")}get storage(){throw new Error("storage must be implemented")}buildFileUrl(t,e){throw new Error("buildFileUrl must be implemented")}handleOptions(t){return{headers:{"Access-Control-Allow-Headers":"Authorization, Content-Type, Location, Tus-Extension, Tus-Max-Size, Tus-Resumable, Tus-Version, Upload-Concat, Upload-Defer-Length, Upload-Length, Upload-Metadata, Upload-Offset, X-HTTP-Method-Override, X-Requested-With","Access-Control-Allow-Methods":t.map(e=>e.toUpperCase()).join(", "),"Access-Control-Max-Age":86400,"Tus-Checksum-Algorithm":this.storage.checksumTypes.join(","),"Tus-Extension":this.storage.tusExtension.toString(),"Tus-Max-Size":this.storage.maxUploadSize,"Tus-Version":N},statusCode:204}}async handlePost(t,e,o,r,p,m,f,U){if(e!==void 0){if(!this.storage.tusExtension.includes("creation-defer-length"))throw s(501,"creation-defer-length extension is not (yet) supported.");if(t===void 0){const l={metadata:r?x(r):{}};let i=await this.storage.create(l);U==="application/offset+octet-stream"&&f>0&&(i=await this.storage.write({...i,body:m,contentLength:f,start:0}));let a={};this.storage.tusExtension.includes("expiration")&&typeof i.expiredAt=="number"&&i.size===void 0&&(a={"Upload-Expires":new Date(i.expiredAt).toUTCString()});const c=this.buildFileUrl(p,i);a={...a,...this.buildHeaders(i,{Location:c})},a.Location||(a.Location=c),i.bytesWritten>0&&(a["Upload-Offset"]=i.bytesWritten.toString()),a["Upload-Defer-Length"]="1";const b=i.bytesWritten>0?200:201;return{...i,headers:a,statusCode:b}}}if(o){if(!this.storage.tusExtension.includes("concatenation"))throw s(501,"Concatenation extension is not (yet) supported. Disable parallel upload in the tus client.");const l=r?x(r):{};if(o==="partial"){const i={metadata:{...l,uploadConcat:"partial"},size:t};let a=await this.storage.create(i);U==="application/offset+octet-stream"&&f>0&&(a=await this.storage.write({...a,body:m,contentLength:f,start:0}));let c={};this.storage.tusExtension.includes("expiration")&&typeof a.expiredAt=="number"&&a.bytesWritten!==(a.size??0)&&(c={"Upload-Expires":new Date(a.expiredAt).toUTCString()});const b=this.buildFileUrl(p,a);c={...c,...this.buildHeaders(a,{Location:b})},c.Location||(c.Location=b),a.bytesWritten>0&&(c["Upload-Offset"]=a.bytesWritten.toString()),c["Upload-Concat"]="partial";const w=a.bytesWritten>0?200:201;return{...a,headers:c,statusCode:w}}if(o.startsWith("final;")){const i=o.slice(6).trim().split(/\s+/).filter(Boolean);if(i.length===0)throw s(400,"Upload-Concat final must include at least one partial upload ID");let a=0;const c=[];for(const C of i)try{const g=await this.storage.getMeta(C);if(await this.storage.checkIfExpired(g),g.metadata?.uploadConcat!=="partial")throw s(400,`Upload ${C} is not a partial upload`);if(g.status!=="completed"||g.size===void 0)throw s(409,`Partial upload ${C} is not completed`);c.push(g),a+=g.size}catch(g){const S=g;throw S.statusCode===404||S.statusCode===410?s(409,`Partial upload ${C} not found or expired`):g}const b={metadata:{...l,partialIds:i,uploadConcat:`final;${i.join(" ")}`},size:a},w=await this.storage.create(b);await this.concatenateFiles(w,c);const A=this.buildFileUrl(p,w),O={...this.buildHeaders(w,{Location:A}),"Upload-Concat":o};return{...w,headers:O,statusCode:201}}throw s(400,"Invalid Upload-Concat header format")}if(t===void 0&&e===void 0)throw s(400,"Either upload-length or upload-defer-length must be specified.");if(t!==void 0&&Number.isNaN(Number(t)))throw s(400,"Invalid upload-length");const E={metadata:r?x(r):{},size:t};let n=await this.storage.create(E);U==="application/offset+octet-stream"&&f>0&&(n=await this.storage.write({...n,body:m,contentLength:f,start:0}));let h={};this.storage.tusExtension.includes("expiration")&&typeof n.expiredAt=="number"&&n.bytesWritten!==Number.parseInt(t,10)&&(h={"Upload-Expires":new Date(n.expiredAt).toUTCString()});const y=this.buildFileUrl(p,n);h={...h,...this.buildHeaders(n,{Location:y})},h.Location||(h.Location=y),n.bytesWritten>0&&(h["Upload-Offset"]=n.bytesWritten.toString());const d=n.bytesWritten>0?200:201;return{...n,headers:h,statusCode:d}}async handlePatch(t,e,o,r,p,m,f,U,E){const n=r?x(r):void 0;if(n)try{await this.storage.update({id:t},{id:t,metadata:n})}catch(l){throw l.UploadErrorCode==="FILE_NOT_FOUND"?s(410,"Upload expired"):l}let h;try{h=await this.storage.getMeta(t),await this.storage.checkIfExpired(h)}catch(l){const i=l;throw i.UploadErrorCode==="GONE"||i.UploadErrorCode==="FILE_NOT_FOUND"?s(410,"Upload expired"):l}const y=h.metadata?.uploadConcat;if(typeof y=="string"&&y.startsWith("final;"))throw s(403,"Cannot PATCH a final concatenation upload");let d=await this.storage.write({body:U,checksum:p,checksumAlgorithm:m,contentLength:E,id:t,start:e});if(o!==void 0){if(!this.storage.tusExtension.includes("creation-defer-length"))throw s(501,"creation-defer-length extension is not (yet) supported.");if(d.size!==void 0&&!Number.isNaN(d.size))throw s(412,"Upload-Length has already been set for this upload");const l=Number.parseInt(o,10);if(Number.isNaN(l))throw s(400,"Invalid Upload-Length value");if(l<d.bytesWritten)throw s(400,"Upload-Length is smaller than the current offset");d=await this.storage.update({id:t},{size:l}),d.bytesWritten===d.size&&(d={...d,status:"completed"})}return{...d,headers:this.buildHeaders(d,{"Upload-Offset":d.bytesWritten}),statusCode:d.status==="completed"?200:204}}async handleHead(t){const e=await this.storage.getMeta(t);await this.storage.checkIfExpired(e);const o={...typeof e.size=="number"&&!Number.isNaN(e.size)?{"Upload-Length":e.size}:{"Upload-Defer-Length":"1"},...this.buildHeaders(e,{"Cache-Control":z.createCacheControlPreset("no-store"),"Upload-Metadata":k(e.metadata),"Upload-Offset":e.bytesWritten})},r=e.metadata?.uploadConcat;return typeof r=="string"&&(o["Upload-Concat"]=r),{headers:o,statusCode:200}}async handleGet(t){const e=await this.storage.getMeta(t);return{...e,body:e,headers:this.buildHeaders(e,{"Content-Type":z.createContentType({mediaType:"application/json"})}),statusCode:200}}async handleDelete(t){if(this.disableTerminationForFinishedUploads&&(await this.storage.getMeta(t)).status==="completed")throw s(400,"Termination of finished uploads is disabled");const e=await this.storage.delete({id:t});if(e.status===void 0)throw s(404,"File not found");return{...e,headers:this.buildHeaders(e),statusCode:204}}buildHeaders(t,e={}){return e["Tus-Resumable"]=T,this.storage.tusExtension.includes("expiration")&&t.expiredAt!==void 0&&(e["Upload-Expires"]=new Date(t.expiredAt).toUTCString()),e}extractChecksum(t){if(!t)return{checksum:void 0,checksumAlgorithm:void 0};const[e,o]=t.split(/\s+/).filter(Boolean);return{checksum:o,checksumAlgorithm:e}}validateTusResumableHeader(t){if(!t)throw s(412,"Missing Tus-Resumable header");if(t!==T)throw s(412,`Unsupported TUS version: ${t}. Server supports: ${T}`)}async concatenateFiles(t,e){let o=0;for(const r of e){if(!this.storage.getStream)throw s(501,"getStream is not supported by this storage backend");const{size:p,stream:m}=await this.storage.getStream({id:r.id});if(p===void 0)throw s(500,"Partial upload size is undefined");const f=await this.storage.write({...t,body:m,contentLength:p,start:o});Object.assign(t,f),o+=p}}}const P=T,B=N;export{P as TUS_RESUMABLE,B as TUS_VERSION,j as TusBase,x as parseMetadata,k as serializeMetadata};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var y=Object.defineProperty;var g=(i,e)=>y(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{O as B}from"./base-handler-fetch-DnarP64X.js";import{TusBase as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_RESUMABLE as L,TUS_VERSION as P}from"./TUS_RESUMABLE-B7KtPVeC.js";var w=Object.defineProperty,f=g((i,e)=>w(i,"name",{value:e,configurable:!0}),"g");const l=f(i=>{try{const e=new URL(i).pathname.split("/").filter(Boolean);return e[e.length-1]||void 0}catch{return}},"getIdFromRequestUrl");class T extends B{static{g(this,"Tus")}static{f(this,"Tus")}static methods=["delete","download","get","head","options","patch","post"];tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const r=this;this.tusBase=new class extends O{get storage(){return r.storage}get disableTerminationForFinishedUploads(){return r.disableTerminationForFinishedUploads??!1}buildFileUrl(t,s){return r.buildFileUrlForTus(t,s)}}}async options(){return this.tusBase.handleOptions(T.methods)}async post(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=e.headers.get("upload-length")||void 0,s=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(t,s,o,d,c,p,h,u)}async patch(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=l(e.url);if(!t)throw a(404,"File not found");const s=e.headers.get("upload-offset");if(!s)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(s,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,E=e.body;try{return this.tusBase.handlePatch(t,d,u,n,U,F,v,E,c)}catch(m){const b=m;throw b.UploadErrorCode==="GONE"||b.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):m}}async head(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=l(e.url);if(!t)throw a(404,"File not found");try{return this.tusBase.handleHead(t)}catch(s){const o=s;throw o.UploadErrorCode==="GONE"||o.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):s}}async get(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=l(e.url);if(!t)throw a(404,"File not found");try{return this.tusBase.handleGet(t)}catch(s){throw s.UploadErrorCode==="GONE"?a(410,"Upload expired"):s}}async delete(e){const r=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(r||void 0);const t=l(e.url);if(!t)throw a(404,"File not found");try{return this.tusBase.handleDelete(t)}catch(s){throw s.code==="ENOENT"?a(404,"File not found"):s}}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,r){const t=new URL(e),{pathname:s,search:o}=t,d=`${s}/${r.id}${o}`;return this.storage.config.useRelativeLocation?d:t.origin+d}}export{L as TUS_RESUMABLE,P as TUS_VERSION,T as Tus};
|
|
@@ -0,0 +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-DaggCVsq.js";import{F as E}from"./base-handler-node-BTes6sql.js";import{TusBase as y}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_RESUMABLE as k,TUS_VERSION as w}from"./TUS_RESUMABLE-B7KtPVeC.js";var O=Object.defineProperty,B=p((h,e)=>O(h,"name",{value:e,configurable:!0}),"h");class g extends E{static{p(this,"Tus")}static{B(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":"1.0.0"},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{k as TUS_RESUMABLE,w as TUS_VERSION,g as Tus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var l=Object.defineProperty;var r=(e,a)=>l(e,"name",{value:a,configurable:!0});var n=Object.defineProperty,c=r((e,a)=>n(e,"name",{value:a,configurable:!0}),"s");class m extends Error{static{r(this,"g")}static{c(this,"ValidationError")}code;details;constructor(a,s,t,i,o,d){super(a),this.name="ValidationError",this.code=s,this.details={invalidParams:i,mediaType:t,suggestions:d,validParams:o}}}export{m as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t=Object.defineProperty;var a=(e,r)=>t(e,"name",{value:r,configurable:!0});import l from"./File-alcSNpLq.js";var o=Object.defineProperty,n=a((e,r)=>o(e,"name",{value:r,configurable:!0}),"e");class c extends l{static{a(this,"n")}static{n(this,"VercelBlobFile")}url;downloadUrl;pathname}export{c as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var t=(r,e)=>a(r,"name",{value:e,configurable:!0});import{O as o}from"./local-meta-storage-Bkwqi_gi.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 p=Object.defineProperty;var l=(n,e)=>p(n,"name",{value:e,configurable:!0});import{put as h,del as d,copy as f,list as w}from"@vercel/blob";import{o as c,r as y,a as g}from"./part-match-DqD5U7An.js";import{B as E,t as O}from"./storage-m_Cxgiih.js";import{O as b}from"./local-meta-storage-Bkwqi_gi.js";import m from"./VercelBlobFile-CL9MjKcY.js";import{u as v}from"./update-size-DANV7aa2.js";import{o as B}from"./has-content-Bx2p8Okx.js";var T=Object.defineProperty,k=l((n,e)=>T(n,"name",{value:e,configurable:!0}),"l");class z extends E{static name="vercel-blob";checksumTypes=["md5"];meta;token;multipart;constructor(e){if(super(e),this.token=e.token||process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN||"",!this.token)throw new Error("Vercel Blob token is required. Set BLOB_READ_WRITE_TOKEN or VERCEL_BLOB_TOKEN environment variable, or provide token in config.");this.multipart=e.multipart??!1;const{metaStorage:t,metaStorageConfig:a}=e;this.meta=t||new b(a),this.isReady=!0}async create(e){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const i=typeof e.ttl=="string"?O(e.ttl):e.ttl;t.expiredAt=i===void 0?void 0:Date.now()+i}const a=new m(t);a.name=this.namingFunction(a),await this.validate(a);try{const i=await this.getMeta(a.id);if(i.bytesWritten>=0)return i}catch{}return a.bytesWritten=0,a.status=c(a),await this.saveMeta(a),await this.onCreate(a),a})}async write(e){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),!y(e,t))throw new Error("File part does not match");await this.lock(e.id);try{if(B(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],i=e.body;for await(const o of i)a.push(Buffer.from(o));const r=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await g(r);o?.mime&&(t.contentType=o.mime)}catch{}const u=new Blob([r],{type:t.contentType}),s=await h(t.name,u,{access:"public",multipart:this.shouldUseMultipart(t)});t.url=s.url,t.pathname=s.pathname,t.downloadUrl=s.downloadUrl,t.bytesWritten=r.length}return t.status=c(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id)}})}async delete({id:e}){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`);t.status="deleted";try{await d(t.url,{token:this.token})}catch(i){this.logger?.error("Failed to delete blob from Vercel Blob:",i);const r=this.normalizeError(i instanceof Error?i:new Error(String(i)));await this.onError(r)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);return!t.url||t.url.length===0?!1:(await fetch(t.url,{method:"HEAD"})).ok}catch{return!1}})}async get({id:e}){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 a=await fetch(t.url),i=Buffer.from(await a.arrayBuffer());return{content:i,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||i.length}})}async copy(e,t){return this.instrumentOperation("copy",async()=>{const a=await this.getMeta(e);if(!a.url)throw new Error("Source file URL not found");const i=await f(a.url,t,{access:"public"});return{...a,id:t,name:t,pathname:i.pathname,url:i.url}})}async move(e,t){return this.instrumentOperation("move",async()=>{const a=await this.copy(e,t);return await this.delete({id:e}),a})}async list(e=1e3){return this.instrumentOperation("list",async()=>(await w({limit:e})).blobs.map(t=>{const a=new m({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return a.createdAt=t.uploadedAt?.toISOString(),a.id=t.pathname,a.modifiedAt=t.uploadedAt?.toISOString(),a.name=t.pathname,a.pathname=t.pathname,a.size=t.size,a.url=t.url,a.downloadUrl=t.downloadUrl,a}),{limit:e})}internalOnComplete=k(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{z as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=Object.defineProperty;var r=(t,e)=>c(t,"name",{value:e,configurable:!0});var p=Object.defineProperty,a=r((t,e)=>p(t,"name",{value:e,configurable:!0}),"t");function f(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}r(f,"getDefaultExportFromCjs");a(f,"getDefaultExportFromCjs");function l(t){return t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}r(l,"getDefaultExportFromNamespaceIfPresent");a(l,"getDefaultExportFromNamespaceIfPresent");function s(t){return t&&Object.prototype.hasOwnProperty.call(t,"default")&&Object.keys(t).length===1?t.default:t}r(s,"getDefaultExportFromNamespaceIfNotNamed");a(s,"getDefaultExportFromNamespaceIfNotNamed");function m(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var o=a(r(function n(){var u=!1;try{u=this instanceof n}catch{}return u?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)},"a"),"a");o.prototype=e.prototype}else o={};return Object.defineProperty(o,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var u=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(o,n,u.get?u:{enumerable:!0,get:a(function(){return t[n]},"get")})}),o}r(m,"getAugmentedNamespace");a(m,"getAugmentedNamespace");export{f as g};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var f=Object.defineProperty;var u=(l,t)=>f(l,"name",{value:t,configurable:!0});import b from"./MetaStorage-Y4m1dWgd.js";import{parseMetadata as T,stringifyMetadata as k}from"./Metadata-B6Ir0KO7.js";import{Readable as w}from"node:stream";import{AwsClient as C}from"aws4fetch";import{o as E}from"./is-expired-1JuZjDtb.js";var x=Object.defineProperty,y=u((l,t)=>x(l,"name",{value:t,configurable:!0}),"p");const p=y(l=>{const t={},a=l.replaceAll(/<\?xml[^>]*\?>/g,"").replaceAll(/xmlns[^=]*="[^"]*"/g,""),e=/<([^>]+)>([^<]*)<\/\1>/g,o=[...a.matchAll(e)];for(const r of o){const[,n,i]=r;n&&i?.trim()&&(t[n]?(Array.isArray(t[n])||(t[n]=[t[n]]),t[n].push(i.trim())):t[n]=i.trim())}const s=/<([^>]+)>([\s\S]*?)<\/\1>/g;let c;for(;(c=s.exec(a))!==null;){const[,r,n]=c;if(r&&n?.includes("<")){const i=p(n);Object.keys(i).length>0&&(t[r]=i)}}return t},"parseXml");class U{static{u(this,"w")}static{y(this,"AwsLightApiAdapter")}aws;bucket;endpoint;constructor(t){this.bucket=t.bucket,this.endpoint=t.endpoint||`https://${t.bucket}.s3.${t.region}.amazonaws.com`,this.aws=new C({accessKeyId:t.accessKeyId,region:t.region,secretAccessKey:t.secretAccessKey,service:t.service||"s3",sessionToken:t.sessionToken})}async createMultipartUpload(t){const a={uploads:""},e={};if(t.ContentType&&(e["Content-Type"]=t.ContentType),t.ACL&&(e["x-amz-acl"]=t.ACL),t.Metadata)for(const[i,d]of Object.entries(t.Metadata))e[`x-amz-meta-${i}`]=d;const o=this.buildUrl(t.Key,a),s=await this.aws.fetch(o,{headers:e,method:"POST"}),c=await s.text();if(!s.ok)throw new Error(`Failed to create multipart upload: ${s.status} ${c}`);const r=p(c),n=r.UploadId||r.InitiateMultipartUploadResult?.UploadId;if(!n){const i=new Error("Failed to parse UploadId from response");throw i.retryable=!1,i}return{UploadId:n}}async uploadPart(t){const a={partNumber:String(t.PartNumber),uploadId:t.UploadId},e={};t.ContentLength&&(e["Content-Length"]=String(t.ContentLength)),t.ContentMD5&&(e["Content-MD5"]=t.ContentMD5);const o=t.Body instanceof w?w.toWeb(t.Body):t.Body,s=this.buildUrl(t.Key,a),c=await this.aws.fetch(s,{body:o,headers:e,method:"PUT"});if(!c.ok){const n=await c.text();throw new Error(`Failed to upload part: ${c.status} ${n}`)}const r=c.headers.get("ETag");if(!r)throw new Error("Failed to get ETag from response");return{ETag:r.replaceAll(/(^"|"$)/g,"")}}async completeMultipartUpload(t){const a={uploadId:t.UploadId},e=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<CompleteMultipartUpload xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
3
|
+
${t.Parts.map(({ETag:d,PartNumber:h})=>`<Part><PartNumber>${h}</PartNumber><ETag>"${d}"</ETag></Part>`).join("")}
|
|
4
|
+
</CompleteMultipartUpload>`,o=this.buildUrl(t.Key,a),s=await this.aws.fetch(o,{body:e,headers:{"Content-Type":"application/xml"},method:"POST"}),c=await s.text();if(!s.ok)throw new Error(`Failed to complete multipart upload: ${s.status} ${c}`);const r=p(c),n=r.CompleteMultipartUploadResult||r,i=n.Location||`${this.endpoint}/${t.Key}`;return{ETag:n.ETag?.replaceAll(/(^"|"$)/g,""),Location:i}}async abortMultipartUpload(t){const a={uploadId:t.UploadId},e=this.buildUrl(t.Key,a),o=await this.aws.fetch(e,{method:"DELETE"});if(!o.ok){const s=await o.text();throw new Error(`Failed to abort multipart upload: ${o.status} ${s}`)}}async listParts(t){const a={uploadId:t.UploadId},e=this.buildUrl(t.Key,a),o=await this.aws.fetch(e,{method:"GET"}),s=await o.text();if(!o.ok)throw new Error(`Failed to list parts: ${o.status} ${s}`);const c=p(s),r=c.ListPartsResult||c;let n=[];return r.Part&&(n=Array.isArray(r.Part)?r.Part:[r.Part]),{Parts:n.map(i=>({ETag:i.ETag?.replaceAll(/(^"|"$)/g,""),PartNumber:Number(i.PartNumber)||0,Size:i.Size?Number(i.Size):void 0}))}}async getObject(t){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"GET"});if(!e.ok){const h=await e.text();throw new Error(`Failed to get object: ${e.status} ${h}`)}const o=e.headers.get("Content-Length"),s=e.headers.get("Content-Type"),c=e.headers.get("ETag"),r=e.headers.get("Expires"),n=e.headers.get("Last-Modified"),i={};for(const[h,m]of e.headers.entries())if(h.toLowerCase().startsWith("x-amz-meta-")){const g=h.toLowerCase().replace("x-amz-meta-","");i[g]=m}const{body:d}=e;return{Body:d?this.streamToReadable(d):void 0,ContentLength:o?Number(o):void 0,ContentType:s||void 0,ETag:c?.replaceAll(/(^"|"$)/g,"")||void 0,Expires:r?new Date(r):void 0,LastModified:n?new Date(n):void 0,Metadata:Object.keys(i).length>0?i:void 0}}async headObject(t){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"HEAD"});if(!e.ok){const d=await e.text();throw new Error(`Failed to head object: ${e.status} ${d}`)}const o=e.headers.get("Content-Length"),s=e.headers.get("Content-Type"),c=e.headers.get("ETag"),r=e.headers.get("Expires"),n=e.headers.get("Last-Modified"),i={};for(const[d,h]of e.headers.entries())if(d.toLowerCase().startsWith("x-amz-meta-")){const m=d.toLowerCase().replace("x-amz-meta-","");i[m]=h}return{ContentLength:o?Number(o):void 0,ContentType:s||void 0,ETag:c?.replaceAll(/(^"|"$)/g,"")||void 0,Expires:r?new Date(r):void 0,LastModified:n?new Date(n):void 0,Metadata:Object.keys(i).length>0?i:void 0}}async deleteObject(t){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"DELETE"});if(!e.ok){const o=await e.text();throw new Error(`Failed to delete object: ${e.status} ${o}`)}}async copyObject(t){const a={"x-amz-copy-source":t.CopySource};t.StorageClass&&(a["x-amz-storage-class"]=t.StorageClass);let e=this.buildUrl(t.Key);t.Bucket!==this.bucket&&(e=e.replace(this.bucket,t.Bucket));const o=await this.aws.fetch(e,{headers:a,method:"PUT"});if(!o.ok){const s=await o.text();throw new Error(`Failed to copy object: ${o.status} ${s}`)}}async listObjectsV2(t){const a={"list-type":"2"};t.MaxKeys&&(a["max-keys"]=String(t.MaxKeys)),t.ContinuationToken&&(a["continuation-token"]=t.ContinuationToken);const e=this.buildUrl("",a),o=await this.aws.fetch(e,{method:"GET"}),s=await o.text();if(!o.ok)throw new Error(`Failed to list objects: ${o.status} ${s}`);const c=p(s),r=c.ListBucketResult||c,n=r.Contents||(Array.isArray(r.Contents)?r.Contents:[]);return{Contents:Array.isArray(n)?n.map(i=>({Key:i.Key,LastModified:i.LastModified?new Date(String(i.LastModified)):void 0})):[],IsTruncated:r.IsTruncated==="true"||r.IsTruncated===!0,NextContinuationToken:r.NextContinuationToken}}async getPresignedUrl(t){const a={partNumber:String(t.PartNumber),uploadId:t.UploadId,"X-Amz-Expires":String(t.expiresIn)};return this.buildUrl(t.Key,a)}async putObject(t){const a=this.buildUrl(t.Key),e={};if(t.ContentType&&(e["Content-Type"]=t.ContentType),t.ContentLength!==void 0&&(e["Content-Length"]=String(t.ContentLength)),t.Metadata)for(const[c,r]of Object.entries(t.Metadata))e[`x-amz-meta-${c}`]=r;let o;t.Body===void 0?o=void 0:t.Body instanceof Uint8Array?o=new Uint8Array(t.Body):t.Body instanceof ReadableStream?o=t.Body:o=void 0;const s=await this.aws.fetch(a,{body:o,headers:e,method:"PUT"});if(!s.ok){const c=await s.text();throw new Error(`Failed to put object: ${s.status} ${c}`)}}async checkBucketAccess(t){const a=this.buildUrl(""),e=await this.aws.fetch(a,{method:"HEAD"});if(!e.ok&&e.status!==404){const o=await e.text();throw new Error(`Failed to access bucket: ${e.status} ${o}`)}}buildUrl(t,a){const e=new URL(t,this.endpoint);if(a)for(const[o,s]of Object.entries(a))e.searchParams.set(o,s);return e.toString()}streamToReadable(t){return w.fromWeb(t)}}var $=Object.defineProperty,A=u((l,t)=>$(l,"name",{value:t,configurable:!0}),"n");class I extends b{static{u(this,"l")}constructor(t){super(t),this.config=t;const a=t.bucket||process.env.S3_BUCKET||process.env.AWS_S3_BUCKET;if(!a)throw new Error("S3 bucket is not defined");this.bucket=a,this.adapter=new U({accessKeyId:t.accessKeyId,bucket:a,endpoint:t.endpoint,region:t.region,secretAccessKey:t.secretAccessKey,service:t.service,sessionToken:t.sessionToken}),this.adapter.checkBucketAccess({Bucket:a}).catch(e=>{throw e})}config;static{A(this,"AwsLightMetaStorage")}adapter;bucket;async get(t){const a=this.getMetaName(t),{Expires:e,Metadata:o}=await this.adapter.headObject({Bucket:this.bucket,Key:a});if(e&&E({expiredAt:e}))throw await this.delete(a),new Error(`Metafile ${t} not found`);if(o?.metadata!==void 0){const s=JSON.parse(decodeURIComponent(o.metadata));return s.metadata&&typeof s.metadata=="string"&&(s.metadata=T(s.metadata)),s}throw new Error(`Metafile ${t} not found`)}async touch(t,a){return this.save(t,a)}async delete(t){await this.adapter.deleteObject({Bucket:this.bucket,Key:this.getMetaName(t)})}async save(t,a){const e={...a};e.metadata&&(e.metadata=k(a.metadata));const o=encodeURIComponent(JSON.stringify(e));return await this.adapter.putObject({Bucket:this.bucket,ContentLength:0,ContentType:"application/json",Key:this.getMetaName(t),Metadata:{metadata:o}}),a}}export{I as l,U as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var n=(r,e)=>a(r,"name",{value:e,configurable:!0});var o=Object.defineProperty,p=n((r,e)=>o(r,"name",{value:e,configurable:!0}),"n");const i=p(r=>{const{applicationKey:e,applicationKeyId:c,region:s}=r??{applicationKey:process.env.AWS_SECRET_ACCESS_KEY||process.env.B2_APP_KEY||process.env.BACKBLAZE_APP_KEY,applicationKeyId:process.env.AWS_ACCESS_KEY_ID||process.env.B2_APP_KEY_ID||process.env.BACKBLAZE_APP_KEY_ID,region:process.env.AWS_REGION||process.env.B2_REGION||process.env.BACKBLAZE_REGION};if(!s||!c||!e)throw new Error("Missing required parameters for Backblaze B2 client.");return{credentials:{accessKeyId:c,secretAccessKey:e},endpoint:`https://s3.${s}.backblazeb2.com`,region:s}},"backblaze");export{i as backblaze,i as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=Object.defineProperty;var c=(r,e)=>g(r,"name",{value:e,configurable:!0});import{EventEmitter as b}from"node:events";import{format as y}from"node:url";import w from"mime";import{ErrorMap as E}from"./ERRORS-B9jkvKwx.js";import{H as R}from"./headers-DC2MEOrK.js";import{Readable as h}from"node:stream";import v,{hasBody as U}from"type-is";var H=Object.defineProperty,I=c((r,e)=>H(r,"name",{value:e,configurable:!0}),"a");const L=I(r=>r.at(-1),"getLastOne");var N=Object.defineProperty,i=c((r,e)=>N(r,"name",{value:e,configurable:!0}),"n");const x=i(r=>{let e="",t="";const s=f(r,"forwarded");return s&&s.split(";").forEach(n=>{const[a,o]=n.split("=");a==="proto"&&(e=o),a==="host"&&(t=o)}),{host:t,proto:e}},"extractForwarded"),P=i((r,e="utf8",t)=>new Promise((s,n)=>{let a="";r.setEncoding(e),r.on("data",o=>{if(t&&a.length+o.length>t){n(new Error("Request body length limit exceeded"));return}a+=o}),r.once("end",()=>{s(a)})}),"readBody"),f=i((r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const n=Array.isArray(s)?s:s.split(",");return L(n).trim()},"getHeader");i(async(r,e=16777216)=>{if(!v(r,["json"]))return{};if(r.body)return{...r.body};if(U(r)){const s=Number.parseInt(f(r,"content-length"),10);if(!Number.isNaN(s)&&s>e)throw new Error("body length limit")}const t=await P(r,"utf8",e);return{...JSON.parse(t)}},"getMetadata");const $=i((r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},"appendHeader"),G=i((r,e={})=>{const t=Object.keys(e);t.length>0&&$(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{["link","location"].includes(s.toLowerCase())?r.setHeader(s,encodeURI(e[s].toString())):r.setHeader(s,e[s])})},"setHeaders"),q=i(r=>f(r,"host")||f(r,"x-forwarded-host"),"extractHost"),F=i(r=>f(r,"x-forwarded-proto").toLowerCase(),"extractProto"),T=i(r=>{let{host:e,proto:t}=x(r);return e||=q(r),t||=F(r),e?t?`${t}://${e}`:`//${e}`:""},"getBaseUrl"),B=i(r=>{let e=(r.originalUrl||r.url||"").split("?")[0];if(!e)throw new TypeError("Invalid request URL");return e.startsWith("/")||(e=`/${e}`),e.startsWith("http")&&(e=new URL(e).pathname),e},"getRealPath"),O=/(?:[\dA-Z]+-){2}[\dA-Z]+/i,K=i(r=>{const e=B(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(!a)continue;const o=a.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(o.toLowerCase())&&O.test(o))return o}const t=e[e.length-1];if(!t)throw new Error("Invalid request URL");const s=t.replace(/\.[^/.]+$/,"");if(["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(s.toLowerCase()))throw new Error("Invalid request URL");if(s.length<8)throw new Error("Invalid request URL");if(e.length>1)return s;throw new Error("Invalid request URL")},"getIdFromRequest"),Q=i(r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?h.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?h.from(Buffer.from(r.body)):r instanceof h?r:h.from(new Uint8Array(0)),"getRequestStream");var j=Object.defineProperty,C=c((r,e)=>j(r,"name",{value:e,configurable:!0}),"r");const V=C((r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},"pick");var A=Object.defineProperty,p=c((r,e)=>A(r,"name",{value:e,configurable:!0}),"d");class X extends b{static{c(this,"E")}static{p(this,"BaseHandlerCore")}responseType="json";storage;mediaTransformer;disableTerminationForFinishedUploads;logger;get loggerInstance(){return this.logger}internalErrorResponses={};get errorResponses(){return this.internalErrorResponses}constructor({disableTerminationForFinishedUploads:e,mediaTransformer:t,storage:s}){super(),this.storage=s,this.mediaTransformer=t,this.disableTerminationForFinishedUploads=e,this.logger=this.storage?.logger,this.assembleErrors()}set errorResponses(e){this.assembleErrors(e)}assembleErrors=p((e={})=>{this.internalErrorResponses={...E,...this.internalErrorResponses,...this.storage.errorResponses,...e}},"assembleErrors");parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const n=s[0]?.trim();if(!n)return;const a=n.split("-");if(a.length!==2)return;const[o,u]=a;let d,l;if(o&&u)d=Number.parseInt(o,10),l=Number.parseInt(u,10);else if(o&&!u)d=Number.parseInt(o,10),l=t-1;else if(!o&&u){const m=Number.parseInt(u,10);d=Math.max(0,t-m),l=t-1}else return;if(!(Number.isNaN(d)||Number.isNaN(l)||d>=t||l>=t||d>l))return{end:l,start:d}}buildFileUrlFromString(e,t){const s=new URL(e,"http://localhost"),{pathname:n}=s,a=Object.fromEntries(s.searchParams.entries()),o=y({pathname:`${n}/${t.id}`,query:a});return`${this.storage.config.useRelativeLocation?"":T({url:e})}${o}.${w.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return R.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{X as E,V as T,f as a,Q as b,T as c,B as d,K as g,P as r,G as s,O as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var E=Object.defineProperty;var u=(h,t)=>E(h,"name",{value:t,configurable:!0});import{H as m,h as b}from"./headers-DC2MEOrK.js";import{ERRORS as g,isUploadError as R}from"./ERRORS-B9jkvKwx.js";import{E as v,T as O}from"./base-handler-core-DaggCVsq.js";import{i as H}from"./validator-DK41xp8N.js";import{waitForStorage as w}from"./waitForStorage-ChSBLhLc.js";var T=Object.defineProperty,x=u((h,t)=>T(h,"name",{value:t,configurable:!0}),"m");class z extends v{static{u(this,"O")}static{x(this,"BaseHandlerFetch")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(t){super(t),this.compose()}get handlers(){return this.registeredHandlers}async fetch(t){this.logger?.debug("[fetch request]: %s %s",t.method,t.url);const e=this.registeredHandlers.get(t.method||"GET");if(!e)return this.createErrorResponse({UploadErrorCode:g.METHOD_NOT_ALLOWED});try{await w(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:g.STORAGE_ERROR})}try{const r=await e.call(this,t);return this.handleFetchResponse(t,r)}catch(r){const s=r instanceof Error?r:new Error(String(r)),o={...O(s,["name",...Object.getOwnPropertyNames(s)]),request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}};return this.listenerCount("error")>0&&this.emit("error",o),this.logger?.error("[fetch error]: %O",o),this.createErrorResponse(s)}}async handleFetchResponse(t,e){if(t.method==="HEAD"||t.method==="OPTIONS"){const{headers:n,statusCode:d}=e;return new Response(void 0,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}if(t.method==="GET"){const{headers:n,statusCode:d}=e;let c="";return e.content!==void 0?c=new Uint8Array(e.content):typeof e=="object"&&"data"in e&&(c=JSON.stringify(e.data)),new Response(c,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}const{headers:r,statusCode:s,...o}=e;if(o.status!==void 0&&this.listenerCount(o.status)>0&&this.emit(o.status,{...o,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),o.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(o,n)}catch(p){throw this.logger?.error("[onComplete error]: %O",p),p}const{headers:d,statusCode:c,...f}=n,{content:j,stream:S,...C}=f;return this.createResponse({body:C,headers:d||r,statusCode:c||s||200})}const y={...r,...e.headers},a=this.convertHeaders({...y,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control",...o.hash===void 0?{}:{[`X-Range-${o.hash?.algorithm.toUpperCase()}`]:o.hash?.value}}),l=e.headers||{};l.Location&&!a.location&&!a.Location?a.location=String(l.Location):l.location&&!a.location&&!a.Location?a.location=String(l.location):r.Location&&!a.location&&!a.Location?a.location=String(r.Location):r.location&&!a.location&&!a.Location&&(a.location=String(r.location));let i;return s>=200&&s<300&&(i=Object.keys(o).length>0?{...o}:{},"content"in i&&delete i.content,"stream"in i&&delete i.stream,Object.keys(i).length===0&&(i={})),this.createResponse({body:i,headers:a,statusCode:s||200})}convertHeaders(t){const e={};for(const[r,s]of Object.entries(t))e[r]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:r={},statusCode:s}=t;let o;return s===204?o=null:typeof e=="string"?o=e:e instanceof Buffer?o=new Uint8Array(e):e&&typeof e=="object"?(o=JSON.stringify(e),r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(o="{}",r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(o,{headers:this.convertHeaders(r),status:s})}async createErrorResponse(t){let e;R(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!H(t)&&!b.isHttpError(t)?e=this.storage.normalizeError(t):e={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(e);let r;return e.body?typeof e.body=="object"&&e.body!==null?r={body:e.body,headers:e.headers,statusCode:e.statusCode}:r={body:{error:{code:e.code||e.name||"Error",message:e.body||e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500}:r={body:{error:{code:e.code||e.name||"Error",message:e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500},this.createResponse(r)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{z as O};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var M=Object.defineProperty;var C=(i,e)=>M(i,"name",{value:e,configurable:!0});import{paginate as P}from"@visulima/pagination";import{H as T,h as z,n as y}from"./headers-DC2MEOrK.js";import O from"mime";import{isUploadError as $,ERRORS as m}from"./ERRORS-B9jkvKwx.js";import{match as k}from"path-to-regexp";import{T as S,E as q,s as A,d as U,u as x}from"./base-handler-core-DaggCVsq.js";import{i as D}from"./validator-DK41xp8N.js";import{waitForStorage as _}from"./waitForStorage-ChSBLhLc.js";import{PassThrough as I}from"node:stream";import{e as H}from"./response-builder-Wdo_fvcF.js";var X=Object.defineProperty,G=C((i,e)=>X(i,"name",{value:e,configurable:!0}),"n");const W=k(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),L=G(i=>{const e=W(i);if(!e)return;const{params:t}=e;if(!t.uuid)return;const r={uuid:t.uuid};return t.metadata!==void 0&&(r.metadata=t.metadata),t.path!==void 0&&(r.path=t.path),t.ext!==void 0&&(r.ext=t.ext),{params:r,path:e.path}},"filePathUrlMatcher");var B=Object.defineProperty,v=C((i,e)=>B(i,"name",{value:e,configurable:!0}),"a");const J=v((i,e,t)=>{let r=0,a=0;const o=t-e+1;return new I({highWaterMark:Math.min(64*1024,o),transform(n,h,s){const l=n.length,d=r,p=d+l-1;if(r+=l,p<e){s();return}if(d>t){this.end(),s();return}const u=Math.max(0,e-d),f=Math.min(l,t-d+1);if(u<f){const b=n.subarray(u,f);a+=b.length,this.push(b)||i.pause()}a>=o&&(this.end(),i.destroy()),s()}})},"createRangeLimitedStream"),V=v((i,e,t)=>{let r=!1;const a=v(()=>{r||(r=!0,i.destroy())},"cleanup");e.on("drain",()=>{i.resume()}),e.on("close",a),e.on("finish",a),e.on("error",a),i.on("end",()=>{e.end()}),i.on("error",async o=>{r||(await t(e,o),a())}),i.on("data",o=>{e.write(o)||i.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",a)},"pipeWithBackpressure");v((i,e,t={})=>({headers:t,size:e,stream:i}),"createStreamResponse");var K=Object.defineProperty,w=C((i,e)=>K(i,"name",{value:e,configurable:!0}),"u");const Q=w((i,e,t)=>{const{headers:r,statusCode:a}=i;e(t,{headers:r,statusCode:a})},"handleHeadOptionsRequest"),Y=w((i,e,t,r,a,o,n)=>{e.body=i?.data===void 0?i:i.data;const{headers:h,statusCode:s}=i,l=i;if(l.stream)if(typeof r=="function")r();else{const d=n(e.headers.range,l.size||0);o(t,l.stream,{headers:h,range:d||void 0,size:l.size,statusCode:s})}else{let d="";i.content!==void 0?d=i.content:typeof i=="object"&&"data"in i&&(d=i.data),typeof r=="function"?r():a(t,{body:d,headers:h,statusCode:s})}},"handleGetRequest"),Z=w(async(i,e,t,r,a,o,n)=>{const{headers:h,statusCode:s,...l}=i;if(typeof r=="function")e._body=!0,e.body=l,r();else{const d=i,p=d.headers?{...d.headers}:{};d.headers===void 0&&(d.headers={}),d.statusCode===void 0&&(d.statusCode=200);try{const u=a.onComplete(l,d,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(d.headers||{}).length===0&&Object.keys(p).length>0?d.headers=p:d.headers&&Object.keys(p).length>0&&(d.headers={...p,...d.headers}),n(e,t,d)}},"handleCompletedUpload"),ee=w((i,e,t,r)=>{const{headers:a,statusCode:o,...n}=i,h=a||{},s=h["X-Chunked-Upload"]==="true"||h["x-chunked-upload"]==="true";let l;const d={...H(h),...a?H(a):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};s&&(l=JSON.stringify(n),!d["Content-Type"]&&!d["content-type"]&&(d["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(l=""),r(t,{body:l,headers:d,statusCode:o||200})},"handlePartialUpload"),te=w(async(i,e,t,r,a,o,n)=>{const h=i instanceof Error?i:new Error(String(i)),s={...S(h,["name",...Object.getOwnPropertyNames(h)]),request:S(e,["headers","method","url"])};r("error")>0&&t("error",s),a?.error&&a.error("[error]: %O",s),await o(n,h)},"handleUploadError");var re=Object.defineProperty,R=C((i,e)=>re(i,"name",{value:e,configurable:!0}),"C");const g="Content-Type";class N extends q{static{C(this,"F")}static{R(this,"BaseHandlerNode")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=R(async(e,t)=>this.upload(e,t),"handle");upload=R(async(e,t,r)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const a=this.registeredHandlers.get(e.method);if(!a){await this.sendError(t,{UploadErrorCode:m.METHOD_NOT_ALLOWED});return}try{await _(this.storage)}catch{await this.sendError(t,{UploadErrorCode:m.STORAGE_ERROR});return}try{const o=await a.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))Q(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&Y(n,e,t,r,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:h,...s}=o;this.logger?.debug("[%s]: %s: %d/%d",s.status,s.name,s.bytesWritten,s.size),s.status!==void 0&&this.listenerCount(s.status)>0&&this.emit(s.status,{...s,request:S(e,["headers","method","url"])}),s.status==="completed"?await Z(o,e,t,r,this.storage,this.logger,(l,d,p)=>{this.finish(l,d,p)}):ee(o,e,t,(l,d)=>{this.send(l,{body:d.body,headers:d.headers,statusCode:d.statusCode})})}}catch(o){await te(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}},"upload");send(e,{body:t="",headers:r={},statusCode:a=200}){let o;const n={...r};if(typeof t=="string"){if(o=t,n[g]===void 0)n[g]=T.createContentType({mediaType:"text/plain"});else{const h=Array.isArray(n[g])?n[g].join(", "):String(n[g]);n[g]=T.ensureCharset(h)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[g]||(n[g]=T.createContentType({charset:"utf8",mediaType:"application/json"})));A(e,n),e.statusCode=a,e.end(o)}async sendError(e,t){let r;$(t)?r=this.internalErrorResponses[t.UploadErrorCode]:!D(t)&&!z.isHttpError(t)?r=this.storage.normalizeError(t):r={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(r);let a;r.body?typeof r.body=="object"&&r.body!==null?a={body:r.body,headers:r.headers,statusCode:r.statusCode}:a={body:{error:{code:r.code||r.name||"Error",message:r.body||r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500}:a={body:{error:{code:r.code||r.name||"Error",message:r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500},this.send(e,a)}sendStream(e,t,{headers:r={},range:a,size:o,statusCode:n=200}){A(e,r),e.statusCode=n;let h=t;a&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${a.start}-${a.end}/${o}`),e.setHeader("Content-Length",a.end-a.start+1),e.setHeader("Accept-Ranges","bytes"),h=J(t,a.start,a.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),V(h,e,(s,l)=>this.sendError(s,l))}finish(e,t,r){const a="id"in r&&"headers"in r&&!("body"in r);let o,n,h;if(a){const s=r,l=s.headers||{},d=s.statusCode||200,{headers:p,statusCode:u,...f}=s;o=f,n={...l},h=d}else{const s=r;o=s.body,n=s.headers||{},h=s.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:s,contentType:l}=o;o=s,n={...n,"Content-Type":l}}this.send(t,{body:o||r,headers:n,statusCode:h})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||N.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const r=L(U(e));if(r?.params.uuid){const{ext:a,metadata:o,uuid:n}=r.params,h=a?n.replace(new RegExp(String.raw`\.${a}$`),""):n;if(o==="metadata"&&U(e).endsWith("/metadata"))try{const s=await this.storage.getMeta(h);return{...s,content:JSON.stringify(s),headers:{"Content-Type":T.createContentType({charset:"utf8",mediaType:"application/json"}),...s.expiredAt===void 0?{}:{"X-Upload-Expires":s.expiredAt.toString()},...s.modifiedAt===void 0?{}:{"Last-Modified":s.modifiedAt.toString()}},statusCode:200}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File metadata not found"):s}if(!x.test(h))return this.list(e,t);try{const s=new URL(e.url||"","http://localhost"),l=Object.fromEntries(s.searchParams.entries());if(Object.keys(l).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const c=await this.mediaTransformer.handle(h,l);return{content:c.buffer,headers:{"Content-Length":String(c.size),"Content-Type":`${c.mediaType}/${c.format}`,"X-Media-Type":c.mediaType,"X-Original-Format":c.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":c.format,...c.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":c.originalFile.expiredAt.toString()},...c.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":c.originalFile.modifiedAt.toString()},...c.originalFile?.ETag===void 0?{}:{ETag:c.originalFile.ETag}},statusCode:200}}catch(c){if(c.name==="ValidationError")throw y(400,c.message);this.logger?.warn(`Media transformation failed: ${c.message}`)}const d=await this.storage.getMeta(h);if((e.headers.range||d.size&&d.size>1024*1024)&&this.storage.getStream)try{const c=await this.storage.getStream({id:h});let E=c.headers?.["Content-Type"]||d.contentType;return E.includes("image")&&typeof a=="string"&&(E=O.getType(a)||E),{headers:{...c.headers,"Accept-Ranges":"bytes","Content-Type":E},size:c.size,statusCode:200,stream:c.stream,...d,contentType:E}}catch(c){this.logger?.warn(`Streaming failed, falling back to buffer: ${c}`)}const p=await this.storage.get({id:h});let{contentType:u}=p;u.includes("image")&&typeof a=="string"&&(u=O.getType(a)||u);const{ETag:f,expiredAt:b,modifiedAt:F,size:j}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(j),"Content-Type":u,...b===void 0?{}:{"X-Upload-Expires":b.toString()},...F===void 0?{}:{"Last-Modified":F.toString()},...f===void 0?{}:{ETag:f}},statusCode:200,...p,contentType:u}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File not found"):s}}return this.list(e,t)}async list(e,t){const r=new URL(e.url||"","http://localhost"),a=r.searchParams.get("limit"),o=r.searchParams.get("page"),n=await this.storage.list(Number(a||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&a!==void 0?{data:P(Number(o),Number(a),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const r=L(U(e));if(!r?.params.uuid||!x.test(r.params.uuid))throw y(404,"File not found");const{ext:a,uuid:o}=r.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,y(501,"Streaming download not supported"));return}const h=await this.storage.getStream({id:o});let s=h.headers?.["Content-Type"]||n.contentType;s.includes("image")&&typeof a=="string"&&(s=O.getType(a)||s);const l=this.parseRangeHeader(e.headers.range,h.size||0),d={...h.headers,"Accept-Ranges":"bytes","Content-Disposition":T.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":s};this.sendStream(t,h.stream,{headers:d,range:l||void 0,size:h.size,statusCode:l?206:200})}catch(n){const h=n;if(h.UploadErrorCode===m.FILE_NOT_FOUND||h.UploadErrorCode===m.GONE){await this.sendError(t,y(404,"File not found"));return}await this.sendError(t,n)}}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw y(404,"File not found")}}export{N as F};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var t=(e,r)=>a(e,"name",{value:r,configurable:!0});var s=Object.defineProperty,u=t((e,r)=>s(e,"name",{value:r,configurable:!0}),"n");class n{static{t(this,"NoOpCache")}static{u(this,"NoOpCache")}get(){}set(){return!0}delete(){return!0}clear(){}has(){return!1}}export{n as N};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var C=Object.defineProperty;var n=(s,e)=>C(s,"name",{value:e,configurable:!0});var t=Object.defineProperty,E=n((s,e)=>t(s,"name",{value:e,configurable:!0}),"C");const _=E(s=>{const{accessKeyId:e,accountId:c,jurisdiction:r,secretAccessKey:o}=s??{accessKeyId:process.env.AWS_ACCESS_KEY_ID||process.env.CLOUDFLARE_ACCESS_KEY_ID||process.env.CLOUDFLARE_ACCESS_KEY,accountId:process.env.CLOUDFLARE_ACCOUNT_ID,jurisdiction:process.env.CLOUDFLARE_JURISDICTION||process.env.CLOUDFLARE_R2_JURISDICTION,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||process.env.CLOUDFLARE_SECRET_ACCESS_KEY||process.env.CLOUDFLARE_SECRET_KEY};if(!c||!e||!o)throw new Error("Missing required parameters for Cloudflare R2 client.");return{credentials:{accessKeyId:e,secretAccessKey:o},endpoint:`https://${c}.${r?`${r}.`:""}r2.cloudflarestorage.com`,region:"auto"}},"cloudflare");export{_ as cloudflare,_ as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"node:stream";import"node:timers";import"node:util";import{B as u,d as F,a as g}from"./storage-m_Cxgiih.js";import"./path-D7rMc9nq-B718mbm6.js";import"type-is";import"./NoOpMetrics-Dky06sf1.js";import"./cache-qV_5Umeq.js";import"./ERRORS-B9jkvKwx.js";import"./validator-DK41xp8N.js";import"./is-expired-1JuZjDtb.js";export{u as BaseStorage,F as defaultCloudStorageFileNameValidation,g as defaultFilesystemFileNameValidation};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t=Object.defineProperty;var n=(r,e)=>t(r,"name",{value:e,configurable:!0});var a=Object.defineProperty,o=n((r,e)=>a(r,"name",{value:e,configurable:!0}),"n");const S=o(r=>{const{key:e,region:s,secret:c}=r??{key:process.env.AWS_ACCESS_KEY_ID||process.env.SPACES_KEY,region:process.env.AWS_REGION||process.env.SPACES_REGION,secret:process.env.AWS_SECRET_ACCESS_KEY||process.env.SPACES_SECRET};if(!s||!e||!c)throw new Error("Missing required parameters for DigitalOcean Spaces client.");return{credentials:{accessKeyId:e,secretAccessKey:c},endpoint:`https://${s}.digitaloceanspaces.com`,forcePathStyle:!1,region:"us-east-1"}},"digitalOcean");export{S as default};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var le=Object.defineProperty;var m=(t,e)=>le(t,"name",{value:e,configurable:!0});import{createReadStream as ue,createWriteStream as me}from"node:fs";import{truncate as he,stat as I,copyFile as C}from"node:fs/promises";import{Transform as H,PassThrough as de,pipeline as ye}from"node:stream";import{f as x,l as fe,w as K,U as b,_ as ge,i as pe,O as we,B as be,y as W}from"./local-meta-storage-Bkwqi_gi.js";import{createRequire as P}from"node:module";import{K as w,C as T,M as Q,L as ve,Q as Ee,O as $e}from"./path-D7rMc9nq-B718mbm6.js";import{g as Se}from"./_commonjsHelpers-D6W6KoPK.js";import Oe from"crypto";import Te from"fs";import{o as A,r as ke,d as Fe}from"./part-match-DqD5U7An.js";import{throwErrorCode as p,ERRORS as f,isUploadError as Pe}from"./ERRORS-B9jkvKwx.js";import{createHash as Ne}from"node:crypto";import{B as De,a as _e,t as je}from"./storage-m_Cxgiih.js";import Me from"./File-alcSNpLq.js";import{u as Re}from"./update-size-DANV7aa2.js";import{o as xe}from"./has-content-Bx2p8Okx.js";var Le=Object.defineProperty,ze=m((t,e)=>Le(t,"name",{value:e,configurable:!0}),"i$4"),Ie=Object.defineProperty,X=ze((t,e)=>Ie(t,"name",{value:e,configurable:!0}),"t");const Ce=P(import.meta.url),$=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,We=X(t=>{if(typeof $<"u"&&$.versions&&$.versions.node){const[e,r]=$.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return $.getBuiltinModule(t)}return Ce(t)},"__cjs_getBuiltinModule"),{lstat:Ae,writeFile:Be}=We("node:fs/promises");var Ue=Object.defineProperty,qe=X((t,e)=>Ue(t,"name",{value:e,configurable:!0}),"o");const M=qe(async t=>{x(t);try{const e=await Ae(t);if(!e.isFile())throw new Error(`Ensure path exists, expected 'file', got '${String(fe(e))}'`)}catch(e){if(e.code==="ENOENT"){await K(w(b(t))),await Be(t,new Uint8Array);return}throw e}},"ensureFile");var Ve=Object.defineProperty,Y=m((t,e)=>Ve(t,"name",{value:e,configurable:!0}),"t$2"),He=Object.defineProperty,G=Y((t,e)=>He(t,"name",{value:e,configurable:!0}),"t"),Ke=Object.defineProperty,Qe=G((t,e)=>Ke(t,"name",{value:e,configurable:!0}),"t");let B=class extends Error{static{m(this,"l")}static{Y(this,"c")}static{G(this,"i")}static{Qe(this,"WalkError")}root;constructor(e,r){super(`${e instanceof Error?e.message:String(e)} for path "${r}"`),this.cause=e,this.root=r}get name(){return"WalkError"}set name(e){throw new Error("Cannot overwrite name of WalkError")}};var Xe=Object.defineProperty,Ye=m((t,e)=>Xe(t,"name",{value:e,configurable:!0}),"n"),Ge=Object.defineProperty,J=Ye((t,e)=>Ge(t,"name",{value:e,configurable:!0}),"t"),Je=Object.defineProperty,Ze=J((t,e)=>Je(t,"name",{value:e,configurable:!0}),"g");const U=Ze(t=>{const e=t.replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,String.raw`\.`).replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");return new RegExp(`^${e}$`)},"globToRegExp");var et=Object.defineProperty,tt=J((t,e)=>et(t,"name",{value:e,configurable:!0}),"n");const F=tt((t,e,r,i)=>Array.isArray(e)&&e.length>0&&!e.some(s=>t.endsWith(s))||r&&!r.some(s=>s.test(t))?!1:!i?.some(s=>s.test(t)),"walkInclude");var rt=Object.defineProperty,Z=m((t,e)=>rt(t,"name",{value:e,configurable:!0}),"u$1"),it=Object.defineProperty,L=Z((t,e)=>it(t,"name",{value:e,configurable:!0}),"y");const at=P(import.meta.url),S=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,st=L(t=>{if(typeof S<"u"&&S.versions&&S.versions.node){const[e,r]=S.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return S.getBuiltinModule(t)}return at(t)},"__cjs_getBuiltinModule"),{readdir:nt,realpath:ot,stat:ct}=st("node:fs/promises");var lt=Object.defineProperty,g=L((t,e)=>lt(t,"name",{value:e,configurable:!0}),"r");const ut=g(async t=>{const e=ve(t),r=Ee(e),i=await ct(e);return{isDirectory:g(()=>i.isDirectory(),"isDirectory"),isFile:g(()=>i.isFile(),"isFile"),isSymbolicLink:g(()=>i.isSymbolicLink(),"isSymbolicLink"),name:r,path:e}},"_createWalkEntry");async function*k(t,{extensions:e,followSymlinks:r=!1,includeDirs:i=!0,includeFiles:s=!0,includeSymlinks:n=!0,match:o,maxDepth:h=Number.POSITIVE_INFINITY,skip:d}={}){if(x(t),h<0)return;const a=o?o.map(c=>typeof c=="string"?U(c):c):void 0,l=d?d.map(c=>typeof c=="string"?U(c):c):void 0;if(t=T(b(t)),i&&F(t,e,a,l)&&(yield await ut(t)),!(h<1||!F(t,void 0,void 0,l)))try{const c=await nt(t,{withFileTypes:!0});for(const u of c){let y=Q(t,u.name);if(u.isSymbolicLink())if(r)y=await ot(y);else if(n&&F(y,e,a,l)){yield{isDirectory:g(()=>u.isDirectory(),"isDirectory"),isFile:g(()=>u.isFile(),"isFile"),isSymbolicLink:g(()=>u.isSymbolicLink(),"isSymbolicLink"),name:u.name,path:y};continue}else continue;u.isDirectory()?yield*k(y,{extensions:e,followSymlinks:r,includeDirs:i,includeFiles:s,includeSymlinks:n,match:a,maxDepth:h-1,skip:l}):u.isFile()&&s&&F(y,e,a,l)&&(yield{isDirectory:g(()=>u.isDirectory(),"isDirectory"),isFile:g(()=>u.isFile(),"isFile"),isSymbolicLink:g(()=>u.isSymbolicLink(),"isSymbolicLink"),name:u.name,path:y})}}catch(c){throw c instanceof B?c:new B(c,t)}}m(k,"f$1");Z(k,"D");L(k,"g");g(k,"walk");var mt=Object.defineProperty,ee=m((t,e)=>mt(t,"name",{value:e,configurable:!0}),"t"),ht=Object.defineProperty,z=ee((t,e)=>ht(t,"name",{value:e,configurable:!0}),"t");const dt=P(import.meta.url),O=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,yt=z(t=>{if(typeof O<"u"&&O.versions&&O.versions.node){const[e,r]=O.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return O.getBuiltinModule(t)}return dt(t)},"__cjs_getBuiltinModule"),{accessSync:ft}=yt("node:fs");var gt=Object.defineProperty,pt=z((t,e)=>gt(t,"name",{value:e,configurable:!0}),"o");function N(t,e=ge){x(t),t=b(t);try{return ft(t,e),!0}catch{return!1}}m(N,"i$1");ee(N,"d");z(N,"m");pt(N,"isAccessibleSync");var wt=Object.defineProperty,te=m((t,e)=>wt(t,"name",{value:e,configurable:!0}),"v"),bt=Object.defineProperty,E=te((t,e)=>bt(t,"name",{value:e,configurable:!0}),"i");const vt=P(import.meta.url),v=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,re=E(t=>{if(typeof v<"u"&&v.versions&&v.versions.node){const[e,r]=v.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return v.getBuiltinModule(t)}return vt(t)},"__cjs_getBuiltinModule"),{cwd:D}=v,{mkdir:Et,rename:$t,copyFile:St,unlink:Ot}=re("node:fs/promises"),{mkdirSync:Tt,renameSync:kt,copyFileSync:Ft,unlinkSync:Pt}=re("node:fs");var Nt=Object.defineProperty,ie=E((t,e)=>Nt(t,"name",{value:e,configurable:!0}),"o");class Dt extends Error{static{m(this,"V")}static{te(this,"O")}static{E(this,"a")}static{ie(this,"SameDirectoryError")}constructor(e,r){super(`Source directory "${w(e)}" does not match destination directory "${w(r)}"`),this.name="SameDirectoryError"}}const ae=ie((t,e)=>{if(!t||!e)throw new Error("Source and destination paths must not be empty");if(w(t)!==w(e))throw new Dt(t,e)},"validateSameDirectory");var _t=Object.defineProperty,jt=E((t,e)=>_t(t,"name",{value:e,configurable:!0}),"m$1");const se=jt(async(t,e,{cwd:r,directoryMode:i,overwrite:s,validateDirectory:n})=>{if(r&&(t=T(r,t),e=T(r,e)),n&&ae(t,e),!s&&await pe(e))throw new Error(`The destination file exists: ${e}`);await Et(w(e),{mode:i,recursive:!0});try{await $t(t,e)}catch(o){if(o.code==="EXDEV")await St(t,e),await Ot(t);else throw o}},"internalMoveFile");var Mt=Object.defineProperty,Rt=E((t,e)=>Mt(t,"name",{value:e,configurable:!0}),"m");const ne=Rt((t,e,{cwd:r,directoryMode:i,overwrite:s,validateDirectory:n})=>{if(r&&(t=T(r,t),e=T(r,e)),n&&ae(t,e),!s&&N(e))throw new Error(`The destination file exists: ${e}`);Tt(w(e),{mode:i,recursive:!0});try{kt(t,e)}catch(o){if(o.code==="EXDEV")Ft(t,e),Pt(t);else throw o}},"internalMoveFileSync");var xt=Object.defineProperty,_=E((t,e)=>xt(t,"name",{value:e,configurable:!0}),"i");const Lt=_(async(t,e,r={})=>{const i={overwrite:!0,validateDirectory:!1,...r,cwd:r.cwd?b(r.cwd):D()};await se(t,e,i)},"move");_((t,e,r)=>{const i={overwrite:!0,validateDirectory:!1,...r};i.cwd=i.cwd?b(i.cwd):D(),ne(t,e,i)},"moveSync");_(async(t,e,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):D(),await se(t,e,i)},"rename");_((t,e,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):D(),ne(t,e,i)},"renameSync");var R,q;function zt(){if(q)return R;q=1;var t=Object.defineProperty,e=m((a,l)=>t(a,"name",{value:l,configurable:!0}),"i");/*!
|
|
2
|
+
* etag
|
|
3
|
+
* Copyright(c) 2014-2016 Douglas Christopher Wilson
|
|
4
|
+
* MIT Licensed
|
|
5
|
+
*/R=o;var r=Oe,i=Te.Stats,s=Object.prototype.toString;function n(a){if(a.length===0)return'"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"';var l=r.createHash("sha1").update(a,"utf8").digest("base64").substring(0,27),c=typeof a=="string"?Buffer.byteLength(a,"utf8"):a.length;return'"'+c.toString(16)+"-"+l+'"'}m(n,"entitytag"),e(n,"entitytag");function o(a,l){if(a==null)throw new TypeError("argument entity is required");var c=h(a),u=l&&typeof l.weak=="boolean"?l.weak:c;if(!c&&typeof a!="string"&&!Buffer.isBuffer(a))throw new TypeError("argument entity must be string, Buffer, or fs.Stats");var y=c?d(a):n(a);return u?"W/"+y:y}m(o,"etag"),e(o,"etag");function h(a){return typeof i=="function"&&a instanceof i?!0:a&&typeof a=="object"&&"ctime"in a&&s.call(a.ctime)==="[object Date]"&&"mtime"in a&&s.call(a.mtime)==="[object Date]"&&"ino"in a&&typeof a.ino=="number"&&"size"in a&&typeof a.size=="number"}m(h,"isstats"),e(h,"isstats");function d(a){var l=a.mtime.getTime().toString(16),c=a.size.toString(16);return'"'+c+"-"+l+'"'}return m(d,"stattag"),e(d,"stattag"),R}m(zt,"requireEtag");var It=zt();const Ct=Se(It);var Wt=Object.defineProperty,oe=m((t,e)=>Wt(t,"name",{value:e,configurable:!0}),"r");class At extends H{static{m(this,"StreamChecksum")}constructor(e,r,i="base64"){super(),this.checksum=e,this.algorithm=r,this.encoding=i,this.hash=Ne(r)}checksum;algorithm;encoding;static{oe(this,"StreamChecksum")}length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(e,r,i){this.push(e),this.hash.update(e),this.length+=e.length,i()}_flush(e){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?e(new Error("Checksum mismatch")):e()}}const Bt=oe((t,e,r="base64")=>e?new At(t,e,r):new de,"streamChecksum");var Ut=Object.defineProperty,qt=m((t,e)=>Ut(t,"name",{value:e,configurable:!0}),"o");class Vt extends H{static{m(this,"m")}constructor(e=Number.POSITIVE_INFINITY){super(),this.limit=e}limit;static{qt(this,"StreamLength")}length=0;_transform(e,r,i){const s=this.length+e.length;this.limit>=s?(this.push(e),this.length=s,i()):i(new Error("Stream length limit exceeded"))}}var Ht=Object.defineProperty,V=m((t,e)=>Ht(t,"name",{value:e,configurable:!0}),"p");class mr extends De{static name="disk";checksumTypes=["md5","sha1"];directory;meta;constructor(e){if(super(e),this.directory=e.directory,e.metaStorage)this.meta=e.metaStorage;else{const r={...e,...e.metaStorageConfig,logger:this.logger};this.meta=new we(r)}e.fileNameValidation||(e.fileNameValidation=_e),this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(r=>{this.logger?.error("Storage access check failed: %O",r)})}normalizeError(e){return super.normalizeError(e)}async create(e){return this.instrumentOperation("create",async()=>{const r={...e};if(e.ttl){const n=typeof e.ttl=="string"?je(e.ttl):e.ttl;n!==void 0&&(r.expiredAt=Date.now()+n)}r.size!==void 0&&Number(r.size)<0&&p(f.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const i=new Me(r);try{const n=await this.getMeta(i.id);if(n.status==="completed")return n}catch{}i.name=this.namingFunction(i),(i.size===void 0||Number.isNaN(i.size))&&(i.size===void 0||(i.size=this.maxUploadSize)),await this.validate(i);const s=this.getFilePath(i.name);try{await M(s),i.bytesWritten=0}catch(n){const o=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(o),p(f.FILE_ERROR,o.message)}return i.status=A(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(e){return this.instrumentOperation("write",async()=>{let r;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?r=e:(r=await this.getMeta(e.id),await this.checkIfExpired(r)),r.status==="completed")return r;if(e.size!==void 0&&Re(r,e.size),!ke(e,r))return p(f.FILE_CONFLICT);const i=this.getFilePath(r.name);await this.lock(i);try{const s=e.start||0;if(await M(i),r.bytesWritten===0&&(r.bytesWritten=s),xe(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))return p(f.UNSUPPORTED_CHECKSUM_ALGORITHM);if((e.start===0||e.start===void 0)&&(r.bytesWritten===0||Number.isNaN(r.bytesWritten))&&(!r.contentType||r.contentType==="application/octet-stream"))try{const{fileType:l,stream:c}=await Fe(e.body);l?.mime&&(r.contentType=l.mime),e.body=c}catch{}const n=e.signal,o={...r,...e,body:e.body};n&&(o.signal=n);const[h,d]=await this.lazyWrite(o);if(d)return await he(i,r.bytesWritten),p(d);const a=s+(e.contentLength||0);r.bytesWritten=Math.max(r.bytesWritten||0,a),r.bytesWritten=Math.max(r.bytesWritten||0,h),r.status=A(r),await this.saveMeta(r)}else await M(i),r.bytesWritten=0;return r}catch(s){if(Pe(s))throw s;const n=this.normalizeError(s instanceof Error?s:new Error(String(s)));return await this.onError(n),p(f.FILE_ERROR,(typeof n.message=="string"?n.message:String(s))||String(s))}finally{await this.unlock(i)}})}async get({id:e}){return this.instrumentOperation("get",async()=>{const r=await this.checkIfExpired(await this.meta.get(e)),{bytesWritten:i,contentType:s,expiredAt:n,metadata:o,modifiedAt:h,name:d,originalName:a,size:l}=r;let c;try{c=await be(this.getFilePath(d),{buffer:!0})}catch(u){const y=u;if(y.code==="ENOENT"||y.code==="EPERM"){const j=this.normalizeError(u instanceof Error?u:new Error(y.message||String(u)));return await this.onError(j),p(f.FILE_NOT_FOUND,(typeof j.message=="string"?j.message:String(u))||String(u))}const ce=this.normalizeError(u instanceof Error?u:new Error(String(u)));throw await this.onError(ce),u}return{content:c,contentType:s,ETag:Ct(c),expiredAt:n,id:e,metadata:o,modifiedAt:h,name:d,originalName:a,size:l||i}})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const r=await this.getMeta(e),i=this.getFilePath(r.name);return await I(i),!0}catch{return!1}})}async getStream({id:e}){return this.instrumentOperation("getStream",async()=>{try{const r=await this.checkIfExpired(await this.meta.get(e)),{bytesWritten:i,contentType:s,expiredAt:n,modifiedAt:o,name:h,size:d}=r,a=ue(this.getFilePath(h));return{headers:{"Content-Length":String(d||i),"Content-Type":s,...n&&{"X-Upload-Expires":n.toString()},...o&&{"Last-Modified":o.toString()}},size:d||i,stream:a}}catch(r){const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));throw await this.onError(i),p(f.FILE_NOT_FOUND,(typeof i.message=="string"?i.message:String(r))||String(r))}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{const r=await this.getMeta(e);await W(this.getFilePath(r.name)),await this.deleteMeta(e);const i={...r,status:"deleted"};return await this.onDelete(i),i})}async copy(e,r){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(e);return await C(this.getFilePath(i.name),this.getFilePath(r)),{...i,name:r}})}async move(e,r){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(e),s=this.getFilePath(i.name),n=this.getFilePath(r);try{await Lt(s,n)}catch(o){if(o?.code==="EXDEV")await C(s,n),await W(s);else{const h=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(h),o}}return{...i,id:i.id,name:r}})}async list(){return this.instrumentOperation("list",async()=>{const e={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},r=[],{directory:i}=this;for await(const s of k(i,e)){const{suffix:n}=this.meta,{path:o}=s;if(!o.includes(n)){const{birthtime:h,ctime:d,mtime:a}=await I(o);r.push({createdAt:h||d,id:o.replace(i,""),modifiedAt:a})}}return r})}getFilePath(e){return $e(e)?e:Q(this.directory,e)}lazyWrite(e){return new Promise((r,i)=>{const s=me(this.getFilePath(e.name),{flags:"r+",start:e.start}),n=new Vt(e.contentLength||e.size-e.start),o=Bt(e.checksum,e.checksumAlgorithm),h=!e.checksum,{signal:d}=e,a=V(()=>{s.close(),n.destroy(),o.destroy()},"cleanupStreams"),l=V(c=>{a(),r([Number.NaN,c])},"failWithCode");if(n.on("error",()=>{l(f.FILE_CONFLICT)}),o.on("error",()=>{l(f.CHECKSUM_MISMATCH)}),e.body.on("aborted",()=>{l(h?void 0:f.REQUEST_ABORTED)}),e.body.on("error",c=>{a(),i(c)}),d?.aborted){l(h?void 0:f.REQUEST_ABORTED);return}d&&d.addEventListener("abort",()=>{a(),s.destroy(),n.destroy(),o.destroy(),e.body.destroy(),r([Number.NaN,h?void 0:f.REQUEST_ABORTED])}),ye(e.body,n,o,s,c=>{if(c){if(a(),d?.aborted){r([Number.NaN,h?void 0:f.REQUEST_ABORTED]);return}r([Number.NaN,f.FILE_ERROR]);return}r([e.start+s.bytesWritten])})})}async accessCheck(){await K(this.directory)}}export{Vt as m,mr as q,Bt as s,M as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=Object.defineProperty;var o=(s,t)=>g(s,"name",{value:t,configurable:!0});import{randomUUID as y}from"node:crypto";import{request as f}from"gaxios";import{GoogleAuth as C}from"google-auth-library";import v from"./MetaStorage-Y4m1dWgd.js";import{stringifyMetadata as R,parseMetadata as E}from"./Metadata-B6Ir0KO7.js";import n from"./GCSConfig-BQ0OpVhe.js";import{o as $}from"./has-content-Bx2p8Okx.js";var I="@visulima/storage",P="1.0.0-alpha.18";const i={name:I,version:P};var A=Object.defineProperty,u=o((s,t)=>A(s,"name",{value:t,configurable:!0}),"n");const T=u(s=>{const t=s.match(/(\d+)-(\d+)/),e=t?.[2]?+t[2]:0;return e>0?e+1:0},"getRangeEnd"),G=u(s=>{if($(s)){const t=s.contentLength?s.start+s.contentLength-1:"*";return`bytes ${s.start}-${t}/${s.size??"*"}`}return`bytes */${s.size??"*"}`},"buildContentRange"),U=u(s=>{if(s.response!==void 0){const{response:t}=s;return t?.data?.error?.errors?.map(({reason:e=""})=>e==="rateLimitExceeded"||e==="userRateLimitExceeded"?!0:!!(e&&e.includes("EAI_AGAIN"))).includes(!0)}return!1},"shouldRetry"),w={retry:3,shouldRetry:U,statusCodesToRetry:[[408,429,500,502,503,504],[100,199],[429],[500,599]]};var b=Object.defineProperty,j=o((s,t)=>b(s,"name",{value:t,configurable:!0}),"p");class N extends v{static{o(this,"E")}constructor(t){super(t),this.config=t;const{authClient:e,...a}=t,r=a.bucket||process.env.GCS_BUCKET;if(e===void 0){if(!r)throw new Error("GCS bucket is not defined");if(!a.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");a.scopes||=n.authScopes,this.authClient=new C(a)}else this.authClient=e;this.storageBaseURI=`${a.storageAPI||n.storageAPI}/${r}/o`,this.uploadBaseURI=`${a.uploadAPI||n.uploadAPI}/${r}/o`;const h=["storage.googleapis.com"],d=new URL(this.storageBaseURI).hostname;this.isCustomEndpoint=!h.includes(d);const{retryOptions:m,useAuthWithCustomEndpoint:p,userProject:l}=t;this.userProject=l,this.useAuthWithCustomEndpoint=p||!1,this.retryOptions={...w,...m},e===void 0&&this.accessCheck().catch(c=>{throw c.code==="404"?new Error(`Bucket ${r} does not exist`):c})}config;static{j(this,"GCSMetaStorage")}authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;async save(t,e){const a={...e};return a.metadata&&(a.metadata=R(e.metadata)),await this.makeRequest({body:JSON.stringify(a),headers:{"Content-Type":"application/json; charset=utf-8"},method:"POST",params:{name:encodeURIComponent(this.getMetaName(t)),uploadType:"media"},url:this.uploadBaseURI}),e}async delete(t){const e=this.getMetaPath(t);await this.makeRequest({method:"DELETE",url:e})}async get(t){const e=this.getMetaPath(t),{data:a}=await this.makeRequest({params:{alt:"media"},url:e});return a.metadata&&typeof a.metadata=="string"&&(a.metadata=E(a.metadata)),a}async touch(t,e){return this.save(t,e)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}getMetaPath(t){return`${this.storageBaseURI}/${this.getMetaName(t)}`}async makeRequest(t){return typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":")),t={...t,headers:{"User-Agent":`${i.name}/${i.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${i.version} gccl-invocation-id/${y()}`},params:{...this.userProject===void 0?{}:{userProject:this.userProject}},retry:!0,retryConfig:this.retryOptions,timeout:6e4},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?f(t):this.authClient.request(t)}}export{N as E,G as b,i as d,T as g,w as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var t=(e,r)=>a(e,"name",{value:r,configurable:!0});var o=Object.defineProperty,n=t((e,r)=>o(e,"name",{value:r,configurable:!0}),"e");const s=n(e=>typeof e.start=="number"&&e.start>=0&&!!e.body,"hasContent");export{s as o};
|