@visulima/storage 1.0.0-alpha.26 → 1.0.0-alpha.27
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 +25 -0
- package/LICENSE.md +0 -1104
- package/README.md +79 -466
- package/dist/adapter/nuxt/module.d.ts +4 -4
- package/dist/adapter/nuxt/node_modules/.bin/nuxi +22 -0
- package/dist/adapter/nuxt/node_modules/.bin/nuxt +22 -0
- package/dist/ai/ai-sdk/index.d.ts +113 -0
- package/dist/ai/ai-sdk/index.js +1 -0
- package/dist/ai/claude/index.d.ts +177 -0
- package/dist/ai/claude/index.js +1 -0
- package/dist/ai/openai/index.d.ts +205 -0
- package/dist/ai/openai/index.js +1 -0
- package/dist/ai/tanstack/index.d.ts +115 -0
- package/dist/ai/tanstack/index.js +1 -0
- package/dist/handler/http/fetch/index.d.ts +13 -7
- package/dist/handler/http/fetch/index.js +1 -1
- package/dist/handler/http/hono/index.d.ts +5 -1412
- package/dist/handler/http/hono/index.js +1 -1
- package/dist/handler/http/nextjs/index.d.ts +4 -4
- package/dist/handler/http/nextjs/index.js +1 -1
- package/dist/handler/http/node/index.d.ts +7 -7
- package/dist/handler/http/node/index.js +1 -1
- package/dist/handler/http/solid-start/index.d.ts +4 -4
- package/dist/handler/http/solid-start/index.js +1 -1
- package/dist/index.d.ts +6 -324
- package/dist/index.js +1 -1
- package/dist/packem_shared/{AwsLightFile-BTLiRxXj.js → AwsLightFile-BSqjc_rD.js} +1 -1
- package/dist/packem_shared/{AwsLightStorage-CA9cdfJ6.js → AwsLightStorage-SH7j-myh.js} +1 -1
- package/dist/packem_shared/{AzureFile-BKHru1zB.js → AzureFile-Dgj2Tef4.js} +1 -1
- package/dist/packem_shared/{AzureSMetaStorage-BqA4jUDJ.js → AzureSMetaStorage-DV2tNjKh.js} +1 -1
- package/dist/packem_shared/AzureStorage-BVYMFEBP.js +1 -0
- package/dist/packem_shared/BaseTransformer-Fpcuz4kj.js +1 -0
- package/dist/packem_shared/BoxFile-Be0S4N1L.js +1 -0
- package/dist/packem_shared/BoxMetaStorage-BUe5Qmqe.js +1 -0
- package/dist/packem_shared/BoxStorage-CgC81_So.js +1 -0
- package/dist/packem_shared/BunnyFile-Dotl-lO9.js +1 -0
- package/dist/packem_shared/BunnyMetaStorage-D0mT6veJ.js +1 -0
- package/dist/packem_shared/BunnyStorage-Bl4usdVT.js +1 -0
- package/dist/packem_shared/DiskStorage-B5uIDVXr.js +1 -0
- package/dist/packem_shared/DiskStorageWithChecksum-CbXWpSOr.js +1 -0
- package/dist/packem_shared/DropboxFile-BGVG2kXM.js +1 -0
- package/dist/packem_shared/DropboxMetaStorage-CICuUZ1n.js +1 -0
- package/dist/packem_shared/DropboxStorage-CPjhDN5B.js +1 -0
- package/dist/packem_shared/ERRORS-CyOuSMLY.js +1 -0
- package/dist/packem_shared/File-BhfUgJjs.js +1 -0
- package/dist/packem_shared/Files-B7hlJcB4.js +1 -0
- package/dist/packem_shared/{GCSFile-CHjX_fJk.js → GCSFile-CDQ6IWAz.js} +1 -1
- package/dist/packem_shared/{GCSMetaStorage-DV0MBO3W.js → GCSMetaStorage-CqP9ifYB.js} +1 -1
- package/dist/packem_shared/GCStorage-XSBKVx90.js +1 -0
- package/dist/packem_shared/GoogleDriveFile-D0aGfGbL.js +1 -0
- package/dist/packem_shared/GoogleDriveMetaStorage-rghGy3Fa.js +1 -0
- package/dist/packem_shared/GoogleDriveStorage-DuB6glUk.js +1 -0
- package/dist/packem_shared/LocalMetaStorage-B5uh1snG.js +1 -0
- package/dist/packem_shared/MediaTransformer-D-1c9Q_k.js +1 -0
- package/dist/packem_shared/Multipart-7FSSy2n1.js +1 -0
- package/dist/packem_shared/Multipart-DACQFsrn.js +1 -0
- package/dist/packem_shared/{NetlifyBlobFile-CpzkMKng.js → NetlifyBlobFile-PMZLJ8AC.js} +1 -1
- package/dist/packem_shared/NetlifyBlobMetaStorage-BcRFPky8.js +1 -0
- package/dist/packem_shared/NetlifyBlobStorage-C4qkJv1R.js +1 -0
- package/dist/packem_shared/OneDriveFile-XbVVKIJh.js +1 -0
- package/dist/packem_shared/OneDriveMetaStorage-B_BkGLzW.js +1 -0
- package/dist/packem_shared/OneDriveStorage-Cu0cGcrh.js +1 -0
- package/dist/packem_shared/Rest-5NwM1xYj.js +1 -0
- package/dist/packem_shared/{Rest-CYEBbtCD.js → Rest-y8Vz2Rt0.js} +1 -1
- package/dist/packem_shared/{S3File-Du6wP0Sz.js → S3File-BfmCOET4.js} +1 -1
- package/dist/packem_shared/S3Storage-D8dopWoO.js +1 -0
- package/dist/packem_shared/SupabaseFile-DZ1iv9gM.js +1 -0
- package/dist/packem_shared/SupabaseMetaStorage-BR1UGqnj.js +1 -0
- package/dist/packem_shared/SupabaseStorage-CCtMTiN5.js +1 -0
- package/dist/packem_shared/{Tus-CUBCkuPE.js → Tus-BCVAbJIi.js} +1 -1
- package/dist/packem_shared/Tus-CJMcygk7.js +1 -0
- package/dist/packem_shared/UploadThingFile-BpG9mE8K.js +1 -0
- package/dist/packem_shared/UploadThingMetaStorage-DyGNyaAq.js +1 -0
- package/dist/packem_shared/UploadThingStorage-B_fNzNFO.js +1 -0
- package/dist/packem_shared/{VercelBlobFile-CL9MjKcY.js → VercelBlobFile-Cni_1qwD.js} +1 -1
- package/dist/packem_shared/{VercelBlobMetaStorage-BsOTx-Su.js → VercelBlobMetaStorage-Do9ZoKrl.js} +1 -1
- package/dist/packem_shared/VercelBlobStorage-D5zy4PPQ.js +1 -0
- package/dist/packem_shared/agentsListFiles-R-CnGKc4.js +1 -0
- package/dist/packem_shared/akamai-BYS9pP8S.js +1 -0
- package/dist/packem_shared/approval-BBeX3o4E.js +1 -0
- package/dist/packem_shared/approval.d-CMAYH9GF.d.ts +75 -0
- package/dist/packem_shared/backblaze-CvdtCvJL.js +1 -0
- package/dist/packem_shared/base-handler-core-BfwZ1RS1.js +1 -0
- package/dist/packem_shared/base-handler-fetch-CLxqXTQf.js +1 -0
- package/dist/packem_shared/base-handler-node-DBZjcqsp.js +1 -0
- package/dist/packem_shared/claudeListFiles-DAezbKEi.js +1 -0
- package/dist/packem_shared/cloudflare-Bm_Pg6yx.js +1 -0
- package/dist/packem_shared/createResponsesFileTools-BCep-qdO.js +1 -0
- package/dist/packem_shared/defaultCloudStorageFileNameValidation-6URTv-Mp.js +1 -0
- package/dist/packem_shared/detect-file-type-5JhzC9RU.js +1 -0
- package/dist/packem_shared/digitalOcean-Lj1NfDzc.js +1 -0
- package/dist/packem_shared/disk-storage-CbSSPnOf.js +5 -0
- package/dist/packem_shared/{disk-storage-with-checksum.d-hEoe2ugb.d.ts → disk-storage-with-checksum.d-BQMXA4Wl.d.ts} +6 -4
- package/dist/packem_shared/executors-DG6hGtvm.js +1 -0
- package/dist/packem_shared/executors.d-UtkeCbk1.d.ts +65 -0
- package/dist/packem_shared/{gcs-meta-storage-BfJB-ejI.js → gcs-meta-storage-XB-UPJn6.js} +1 -1
- package/dist/packem_shared/hetzner-DDxE7Gy7.js +1 -0
- package/dist/packem_shared/index.d-DotjipuX.d.ts +89 -0
- package/dist/packem_shared/isRetryableError-B6ZS_-5I.js +1 -0
- package/dist/packem_shared/listFiles-B6VF05d-.js +1 -0
- package/dist/packem_shared/listFiles-BtP6VnUp.js +1 -0
- package/dist/packem_shared/{local-meta-storage-Bkwqi_gi.js → local-meta-storage-CT1audnK.js} +1 -1
- package/dist/packem_shared/{local-meta-storage.d-Dop9RP9k.d.ts → local-meta-storage.d-B5R1nswK.d.ts} +2 -1
- package/dist/packem_shared/{media-transformer.d-CY9CsEOe.d.ts → media-transformer.d-DK7NJncf.d.ts} +2 -2
- package/dist/packem_shared/minio-T_Z3iEy7.js +1 -0
- package/dist/packem_shared/multipart-base-BxckfvQf.js +1 -0
- package/dist/packem_shared/oauth-refresh-Dg2ybc6_.js +1 -0
- package/dist/packem_shared/part-match-B5fLLmFw.js +1 -0
- package/dist/packem_shared/rest-base-CCv78k7h.js +1 -0
- package/dist/packem_shared/s3-base-storage-f_EyFAAt.js +1 -0
- package/dist/packem_shared/{s3-base-storage.d-CczjSe98.d.ts → s3-base-storage.d-BROGYJ4F.d.ts} +1 -1
- package/dist/packem_shared/storage-CoyB2O-Y.js +1 -0
- package/dist/packem_shared/{storage.d-BOMUJD96.d.ts → storage.d-Cr6f2lac.d.ts} +179 -78
- package/dist/packem_shared/storj-CVA9mM-7.js +1 -0
- package/dist/packem_shared/tigris-wmhjfsH2.js +1 -0
- package/dist/packem_shared/{tus-base.d-DNZRXR9X.d.ts → tus-base.d-4-ZfDQwl.d.ts} +3 -3
- package/dist/packem_shared/{types.d-D4caL2Fp.d.ts → types.d-BgCmSE94.d.ts} +2 -2
- package/dist/packem_shared/{types.d-BCN94sB_.d.ts → types.d-C8eSxqX9.d.ts} +13 -1
- package/dist/packem_shared/wasabi-JQzxdrFy.js +1 -0
- package/dist/storage/aws/clients/index.d.ts +90 -15
- package/dist/storage/aws/clients/index.js +1 -1
- package/dist/storage/aws/index.d.ts +16 -15
- package/dist/storage/aws/index.js +1 -1
- package/dist/storage/aws-light/index.d.ts +5 -3
- package/dist/storage/aws-light/index.js +1 -1
- package/dist/storage/azure/index.d.ts +4 -10277
- package/dist/storage/azure/index.js +1 -1
- package/dist/storage/box/index.d.ts +186 -0
- package/dist/storage/box/index.js +1 -0
- package/dist/storage/bunny/index.d.ts +116 -0
- package/dist/storage/bunny/index.js +1 -0
- package/dist/storage/dropbox/index.d.ts +129 -0
- package/dist/storage/dropbox/index.js +1 -0
- package/dist/storage/gcs/index.d.ts +6 -3941
- package/dist/storage/gcs/index.js +1 -1
- package/dist/storage/google-drive/index.d.ts +145 -0
- package/dist/storage/google-drive/index.js +1 -0
- package/dist/storage/local/index.d.ts +3 -3
- package/dist/storage/local/index.js +1 -1
- package/dist/storage/netlify-blob/index.d.ts +4 -2
- package/dist/storage/netlify-blob/index.js +1 -1
- package/dist/storage/onedrive/index.d.ts +192 -0
- package/dist/storage/onedrive/index.js +1 -0
- package/dist/storage/supabase/index.d.ts +111 -0
- package/dist/storage/supabase/index.js +1 -0
- package/dist/storage/uploadthing/index.d.ts +91 -0
- package/dist/storage/uploadthing/index.js +1 -0
- package/dist/storage/vercel-blob/index.d.ts +17 -2
- package/dist/storage/vercel-blob/index.js +1 -1
- package/dist/transformer/audio-transformer.d.ts +2 -2
- package/dist/transformer/audio-transformer.js +1 -1
- package/dist/transformer/image-transformer.d.ts +6 -2
- package/dist/transformer/image-transformer.js +1 -1
- package/dist/transformer/index.d.ts +3 -3
- package/dist/transformer/index.js +1 -1
- package/dist/transformer/video-transformer.d.ts +2 -2
- package/dist/transformer/video-transformer.js +1 -1
- package/package.json +99 -3
- package/dist/packem_shared/AzureStorage-BKUjCymW.js +0 -1
- package/dist/packem_shared/BaseTransformer-D68eLyz1.js +0 -1
- package/dist/packem_shared/DiskStorage-DNjpDMX9.js +0 -1
- package/dist/packem_shared/DiskStorageWithChecksum-Bb6JX_tC.js +0 -1
- package/dist/packem_shared/ERRORS-B9jkvKwx.js +0 -1
- package/dist/packem_shared/File-alcSNpLq.js +0 -1
- package/dist/packem_shared/GCStorage-B8dl6TGK.js +0 -1
- package/dist/packem_shared/LocalMetaStorage-BWuFvWn4.js +0 -1
- package/dist/packem_shared/MediaTransformer-2C8MJeAg.js +0 -1
- package/dist/packem_shared/Multipart-Bd9YFFn0.js +0 -1
- package/dist/packem_shared/Multipart-D5bcEvga.js +0 -1
- package/dist/packem_shared/NetlifyBlobMetaStorage-dD0oBLom.js +0 -1
- package/dist/packem_shared/NetlifyBlobStorage-ByTwCN-h.js +0 -1
- package/dist/packem_shared/Rest-DoonVU7B.js +0 -1
- package/dist/packem_shared/S3Client.d-CZ62Jztg.d.ts +0 -20357
- package/dist/packem_shared/S3Storage-Fx6-OSc-.js +0 -1
- package/dist/packem_shared/Tus-Bd_2Ki2G.js +0 -1
- package/dist/packem_shared/VercelBlobStorage-kNkk5Cn4.js +0 -1
- package/dist/packem_shared/backblaze-DEflv87m.js +0 -1
- package/dist/packem_shared/base-handler-core-DaggCVsq.js +0 -1
- package/dist/packem_shared/base-handler-fetch-DnarP64X.js +0 -1
- package/dist/packem_shared/base-handler-node-BTes6sql.js +0 -1
- package/dist/packem_shared/cloudflare-DLAeQvgD.js +0 -1
- package/dist/packem_shared/defaultCloudStorageFileNameValidation-yiM9GxHr.js +0 -1
- package/dist/packem_shared/digitalOcean-nhZUds87.js +0 -1
- package/dist/packem_shared/disk-storage-BvdK4bqF.js +0 -5
- package/dist/packem_shared/isRetryableError-DQNSZiBc.js +0 -1
- package/dist/packem_shared/minio-BWwgGXeE.js +0 -1
- package/dist/packem_shared/multipart-base-C6OjBwMS.js +0 -1
- package/dist/packem_shared/part-match-DqD5U7An.js +0 -1
- package/dist/packem_shared/rest-base-B2Dv7esY.js +0 -1
- package/dist/packem_shared/s3-base-storage-xHZNtsGe.js +0 -1
- package/dist/packem_shared/storage-m_Cxgiih.js +0 -1
- package/dist/packem_shared/tigris-DZoyrMNd.js +0 -1
- package/dist/packem_shared/validator-DK41xp8N.js +0 -1
- package/dist/packem_shared/wasabi-Dmce4x9s.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var l=Object.defineProperty;var u=(s,t)=>l(s,"name",{value:t,configurable:!0});import{Input as m,BufferSource as f,ALL_FORMATS as p,Output as w,BufferTarget as g,Conversion as y,Mp3OutputFormat as d,WavOutputFormat as b,OggOutputFormat as O,FlacOutputFormat as T,AdtsOutputFormat as F}from"mediabunny";import A from"../packem_shared/BaseTransformer-
|
|
1
|
+
var l=Object.defineProperty;var u=(s,t)=>l(s,"name",{value:t,configurable:!0});import{Input as m,BufferSource as f,ALL_FORMATS as p,Output as w,BufferTarget as g,Conversion as y,Mp3OutputFormat as d,WavOutputFormat as b,OggOutputFormat as O,FlacOutputFormat as T,AdtsOutputFormat as F}from"mediabunny";import A from"../packem_shared/BaseTransformer-Fpcuz4kj.js";import{isValidMediaType as C,getFormatFromContentType as v}from"../packem_shared/isValidMediaType-B-2UKjZx.js";var x=Object.defineProperty,z=u((s,t)=>x(s,"name",{value:t,configurable:!0}),"d");class E extends A{static{u(this,"S")}static{z(this,"AudioTransformer")}constructor(t,e={}){const a=e.logger||t.logger,r={cacheTtl:3600,defaultBitrate:128e3,defaultCodec:"aac",maxAudioSize:100*1024*1024,maxCacheSize:100,supportedFormats:["mp3","wav","ogg","aac","flac","m4a","wma","aiff"],...e};super(t,r,a)}async resample(t,e){return this.transform(t,[{options:e,type:"resample"}])}async mixChannels(t,e){return this.transform(t,[{options:e,type:"channels"}])}async convertFormat(t,e,a={}){return this.transform(t,[{options:{...a,format:e},type:"format"}])}async transcode(t,e,a={}){return this.transform(t,[{options:{...a,codec:e},type:"codec"}])}async transform(t,e){const a={id:t},r=this.generateCacheKey(t,e);if(this.cache){const i=await Promise.resolve(this.cache.get(r));if(i)return this.logger?.debug("Returning cached transformed audio for %s",t),i}const o=await this.storage.get(a);await this.validateAudio(o);const c=await this.applyTransformations(o.content,e),n=await this.createTransformResult(c,o);return this.cache&&this.cache.set(r,n),n}async applyTransformations(t,e){const a=new m({formats:p,source:new f(t)}),r=this.determineOutputFormat(e),o=new w({format:r,target:new g}),c=this.stepsToAudioOptions(e),n=await y.init({audio:c,input:a,output:o});if(!n.isValid){const i=n.discardedTracks.map(h=>h.reason).join(", ");throw new Error(`Audio transformation failed: ${i}`)}return await n.execute(),Buffer.from(o.target.buffer)}stepsToAudioOptions(t){const e={};for(const a of t)switch(a.type){case"bitrate":{const r=a.options;r.bitrate&&(e.bitrate=r.bitrate);break}case"channels":{const r=a.options;r.numberOfChannels&&(e.numberOfChannels=r.numberOfChannels);break}case"codec":{const r=a.options;r.codec&&(e.codec=r.codec),r.bitrate&&(e.bitrate=r.bitrate);break}case"resample":{const r=a.options;r.sampleRate&&(e.sampleRate=r.sampleRate);break}}return e}determineOutputFormat(t){for(const e of t)if(e.type==="format"&&e.options.format)return this.formatStringToOutputFormat(e.options.format);return new d}formatStringToOutputFormat(t){switch(t.toLowerCase()){case"aac":return new F;case"flac":return new T;case"mp3":return new d;case"ogg":return new O;case"wav":return new b;default:return new d}}async validateAudio(t){const e=typeof t.size=="string"?Number.parseInt(t.size,10):t.size;if(this.config?.maxAudioSize&&e>this.config.maxAudioSize)throw new Error(`Audio size ${e} exceeds maximum allowed size ${this.config.maxAudioSize}`);if(!C(t.contentType,"audio"))throw new Error(`File is not audio: ${t.contentType}`);const a=v(t.contentType);if(this.config?.supportedFormats&&a&&!this.config.supportedFormats.includes(a))throw new Error(`Unsupported audio format: ${a}`);try{if(!await new m({formats:p,source:new f(t.content)}).getPrimaryAudioTrack())throw new Error("No audio track found")}catch(r){throw new Error(`Invalid audio file: ${r}`)}}async createTransformResult(t,e){const a=new m({formats:p,source:new f(t)}),r=await a.getPrimaryAudioTrack(),o=await a.computeDuration();return{bitrate:this.config.defaultBitrate,buffer:t,duration:o,format:"mp3",numberOfChannels:r?.numberOfChannels||2,originalFile:e,sampleRate:r?.sampleRate||44100,size:t.length}}generateCacheKey(t,e){const a=e.map(r=>`${r.type}:${JSON.stringify(r.options)}`).join("|");return`${t}:${a}`}}export{E as default};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Readable } from 'node:stream';
|
|
2
|
-
import { F as File, a as FileReturn, B as BaseStorage } from "../packem_shared/storage.d-
|
|
3
|
-
import { I as ImageTransformerConfig, T as TransformResult, R as ResizeOptions, C as CropOptions, l as RotateOptions, m as ImageFormat, n as TransformOptions, S as SharpenOptions, o as BlurOptions, M as MedianOptions, p as CLAHEOptions, q as ConvolveOptions, r as ThresholdOptions, s as BooleanOptions, L as LinearOptions, t as RecombineOptions, u as ModulateOptions, v as TintOptions, G as GreyscaleOptions, w as ColourspaceOptions, E as ExtractChannelOptions, J as JoinChannelOptions, x as BandboolOptions, y as AffineOptions, D as DilateOptions, z as ErodeOptions, P as PipelineColourspaceOptions, F as ToColourspaceOptions, H as RemoveAlphaOptions, K as EnsureAlphaOptions, N as TransformationStep, B as BaseTransformer } from "../packem_shared/types.d-
|
|
2
|
+
import { F as File, a as FileReturn, B as BaseStorage } from "../packem_shared/storage.d-Cr6f2lac.js";
|
|
3
|
+
import { I as ImageTransformerConfig, T as TransformResult, R as ResizeOptions, C as CropOptions, l as RotateOptions, m as ImageFormat, n as TransformOptions, S as SharpenOptions, o as BlurOptions, M as MedianOptions, p as CLAHEOptions, q as ConvolveOptions, r as ThresholdOptions, s as BooleanOptions, L as LinearOptions, t as RecombineOptions, u as ModulateOptions, v as TintOptions, G as GreyscaleOptions, w as ColourspaceOptions, E as ExtractChannelOptions, J as JoinChannelOptions, x as BandboolOptions, y as AffineOptions, D as DilateOptions, z as ErodeOptions, P as PipelineColourspaceOptions, F as ToColourspaceOptions, H as RemoveAlphaOptions, K as EnsureAlphaOptions, N as TransformationStep, B as BaseTransformer } from "../packem_shared/types.d-C8eSxqX9.js";
|
|
4
4
|
import 'node:crypto';
|
|
5
5
|
import 'node:http';
|
|
6
6
|
import 'lru-cache';
|
|
@@ -50,6 +50,10 @@ declare class ImageTransformer<TFile extends File = File, TFileReturn extends Fi
|
|
|
50
50
|
*/
|
|
51
51
|
constructor(storage: BaseStorage<TFile, TFileReturn>, config?: ImageTransformerConfig);
|
|
52
52
|
/**
|
|
53
|
+
* Returns a sharp() invocation that applies the transformer's configured decompression-bomb defenses.
|
|
54
|
+
*/
|
|
55
|
+
private openImage;
|
|
56
|
+
/**
|
|
53
57
|
* Resizes an image to specified dimensions with optional fit mode.
|
|
54
58
|
* @param fileId Unique identifier of the image file to resize.
|
|
55
59
|
* @param options Resize options including width, height, and fit mode.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var f=Object.defineProperty;var y=(c,e)=>f(c,"name",{value:e,configurable:!0});import{Readable as d}from"node:stream";import u from"sharp";import b from"../packem_shared/BaseTransformer-D68eLyz1.js";import{isValidMediaType as k,getFormatFromContentType as v}from"../packem_shared/isValidMediaType-B-2UKjZx.js";var A=Object.defineProperty,w=y((c,e)=>A(c,"name",{value:e,configurable:!0}),"f");class z extends b{static{y(this,"R")}static{w(this,"ImageTransformer")}constructor(e,a={}){const t=a.logger||e.logger,n={cacheTtl:3600,maxCacheSize:100,maxImageSize:50*1024*1024,supportedFormats:["jpeg","png","webp","avif","tiff","gif","svg"],...a};super(e,n,t)}async resize(e,a){return this.transform(e,[{options:a,type:"resize"}])}async crop(e,a){return this.transform(e,[{options:a,type:"crop"}])}async rotate(e,a){return this.transform(e,[{options:a,type:"rotate"}])}async convertFormat(e,a,t={}){return this.transform(e,[{options:{...t,format:a},type:"format"}])}async sharpen(e,a={}){return this.transform(e,[{options:a,type:"sharpen"}])}async blur(e,a={}){return this.transform(e,[{options:a,type:"blur"}])}async median(e,a={}){return this.transform(e,[{options:a,type:"median"}])}async clahe(e,a={}){return this.transform(e,[{options:a,type:"clahe"}])}async convolve(e,a){return this.transform(e,[{options:a,type:"convolve"}])}async threshold(e,a={}){return this.transform(e,[{options:a,type:"threshold"}])}async boolean(e,a){return this.transform(e,[{options:a,type:"boolean"}])}async linear(e,a){return this.transform(e,[{options:a,type:"linear"}])}async recombine(e,a){return this.transform(e,[{options:a,type:"recombine"}])}async modulate(e,a){return this.transform(e,[{options:a,type:"modulate"}])}async tint(e,a){return this.transform(e,[{options:a,type:"tint"}])}async greyscale(e,a={}){return this.transform(e,[{options:a,type:"greyscale"}])}async colourspace(e,a){return this.transform(e,[{options:a,type:"colourspace"}])}async extractChannel(e,a){return this.transform(e,[{options:a,type:"extractChannel"}])}async joinChannel(e,a){return this.transform(e,[{options:a,type:"joinChannel"}])}async bandbool(e,a){return this.transform(e,[{options:a,type:"bandbool"}])}async autoOrient(e,a={}){return this.transform(e,[{options:a,type:"autoOrient"}])}async flip(e,a={}){return this.transform(e,[{options:a,type:"flip"}])}async flop(e,a={}){return this.transform(e,[{options:a,type:"flop"}])}async flatten(e,a={}){return this.transform(e,[{options:a,type:"flatten"}])}async unflatten(e,a={}){return this.transform(e,[{options:a,type:"unflatten"}])}async gamma(e,a={}){return this.transform(e,[{options:a,type:"gamma"}])}async negate(e,a={}){return this.transform(e,[{options:a,type:"negate"}])}async normalise(e,a={}){return this.transform(e,[{options:a,type:"normalise"}])}async affine(e,a){return this.transform(e,[{options:a,type:"affine"}])}async dilate(e,a={}){return this.transform(e,[{options:a,type:"dilate"}])}async erode(e,a={}){return this.transform(e,[{options:a,type:"erode"}])}async pipelineColourspace(e,a){return this.transform(e,[{options:a,type:"pipelineColourspace"}])}async toColourspace(e,a){return this.transform(e,[{options:a,type:"toColourspace"}])}async removeAlpha(e,a={}){return this.transform(e,[{options:a,type:"removeAlpha"}])}async ensureAlpha(e,a={}){return this.transform(e,[{options:a,type:"ensureAlpha"}])}async transform(e,a){const t={id:e},n=this.generateCacheKey(e,a),o=this.cache?await Promise.resolve(this.cache.get(n)):void 0;if(o)return this.logger?.debug("Returning cached transformed image for %s",e),o;const r=await this.storage.get(t);await this.validateImage(r);const s=await this.applyTransformations(r.content,a),i=await this.createTransformResult(s,r);return this.cache&&this.cache.set(n,i),i}async transformStream(e,a){const t=await this.transform(e,a);return{headers:{"Content-Length":t.buffer.length.toString(),"Content-Type":this.getContentTypeFromResult(t),"X-Image-Height":t.height?.toString(),"X-Image-Width":t.width?.toString()},size:t.buffer.length,stream:d.from(t.buffer)}}async applyTransformations(e,a){let t=u(e);for(const n of a)switch(n.type){case"affine":{t=this.applyAffine(t,n.options);break}case"autoOrient":{t=t.rotate();break}case"bandbool":{t=this.applyBandbool(t,n.options);break}case"blur":{t=this.applyBlur(t,n.options);break}case"boolean":{t=this.applyBoolean(t,n.options);break}case"clahe":{t=this.applyCLAHE(t,n.options);break}case"colourspace":{t=this.applyColourspace(t,n.options);break}case"convolve":{t=this.applyConvolve(t,n.options);break}case"crop":{t=this.applyCrop(t,n.options);break}case"dilate":{t=this.applyDilate(t,n.options);break}case"ensureAlpha":{t=this.applyEnsureAlpha(t,n.options);break}case"erode":{t=this.applyErode(t,n.options);break}case"extractChannel":{t=this.applyExtractChannel(t,n.options);break}case"flatten":{t=t.flatten();break}case"flip":{t=t.flip();break}case"flop":{t=t.flop();break}case"format":case"quality":{t=this.applyFormatAndQuality(t,n.options);break}case"gamma":{t=t.gamma();break}case"greyscale":{t=this.applyGreyscale(t,n.options);break}case"joinChannel":{t=this.applyJoinChannel(t,n.options);break}case"linear":{t=this.applyLinear(t,n.options);break}case"median":{t=this.applyMedian(t,n.options);break}case"modulate":{t=this.applyModulate(t,n.options);break}case"negate":{t=t.negate();break}case"normalise":case"normalize":{t=t.normalise();break}case"pipelineColourspace":{t=this.applyPipelineColourspace(t,n.options);break}case"recombine":{t=this.applyRecombine(t,n.options);break}case"removeAlpha":{t=this.applyRemoveAlpha(t,n.options);break}case"resize":{t=this.applyResize(t,n.options);break}case"rotate":{t=this.applyRotate(t,n.options);break}case"sharpen":{t=this.applySharpen(t,n.options);break}case"threshold":{t=this.applyThreshold(t,n.options);break}case"tint":{t=this.applyTint(t,n.options);break}case"toColourspace":{t=this.applyToColourspace(t,n.options);break}case"unflatten":{t=t.unflatten();break}default:throw new Error(`Unknown transformation type: ${n.type}`)}return t.toBuffer()}applyResize(e,a){const{background:t,fastShrinkOnLoad:n,fit:o="cover",height:r,kernel:s,position:i,width:l,withoutEnlargement:p,withoutReduction:g,...m}=a;let h={background:t||"transparent",fastShrinkOnLoad:n,fit:o,height:r,kernel:s,position:i,width:l,withoutEnlargement:p,withoutReduction:g};return Object.keys(m).length>0&&(h={...h,...this.getFormatOptions(m)}),e.resize(h)}applyCrop(e,a){const{height:t,left:n,top:o,width:r,...s}=a;let i=e.extract({height:t,left:n,top:o,width:r});return Object.keys(s).length>0&&(i=this.applyFormatAndQuality(i,s)),i}applyRotate(e,a){const{angle:t,background:n,...o}=a;let r=e.rotate(t,{background:n||"transparent"});return Object.keys(o).length>0&&(r=this.applyFormatAndQuality(r,o)),r}applySharpen(e,a){const{sigma:t,...n}=a,o={};t!==void 0&&(o.sigma=t);let r=e.sharpen(o);return Object.keys(n).length>0&&(r=this.applyFormatAndQuality(r,n)),r}applyBlur(e,a){const{sigma:t,...n}=a;let o=e.blur(t===void 0?!0:t);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyMedian(e,a){const{size:t,...n}=a;let o=e.median(t);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyCLAHE(e,a){const{height:t,maxSlope:n,width:o,...r}=a;let s=e.clahe({height:t,maxSlope:n,width:o});return Object.keys(r).length>0&&(s=this.applyFormatAndQuality(s,r)),s}applyConvolve(e,a){const{height:t,kernel:n,offset:o,scale:r,width:s,...i}=a;let l=e.convolve({height:t,kernel:n,offset:o,scale:r,width:s});return Object.keys(i).length>0&&(l=this.applyFormatAndQuality(l,i)),l}applyThreshold(e,a){const{grayscale:t,greyscale:n,threshold:o=128,...r}=a;let s=e.threshold(o,{greyscale:n||t});return Object.keys(r).length>0&&(s=this.applyFormatAndQuality(s,r)),s}applyBoolean(e,a){const{operand:t,operator:n,raw:o,...r}=a;let s=e.boolean(t,n,o);return Object.keys(r).length>0&&(s=this.applyFormatAndQuality(s,r)),s}applyLinear(e,a){const{a:t,b:n,...o}=a;let r=e.linear(t,n);return Object.keys(o).length>0&&(r=this.applyFormatAndQuality(r,o)),r}applyRecombine(e,a){const{matrix:t,...n}=a;let o=e.recomb(t.flat());return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyModulate(e,a){const{brightness:t,hue:n,lightness:o,saturation:r,...s}=a;let i=e.modulate({brightness:t,hue:n,lightness:o,saturation:r});return Object.keys(s).length>0&&(i=this.applyFormatAndQuality(i,s)),i}applyTint(e,a){const{rgb:t,...n}=a;let o=e.tint(Array.isArray(t)?{b:t[2],g:t[1],r:t[0]}:t);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyGreyscale(e,a){const{grayscale:t,greyscale:n,...o}=a;let r=e.greyscale(n||t);return Object.keys(o).length>0&&(r=this.applyFormatAndQuality(r,o)),r}applyColourspace(e,a){const{colourspace:t,...n}=a;let o=e.toColourspace(t);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyExtractChannel(e,a){const{channel:t,...n}=a;let o=e.extractChannel(t);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyJoinChannel(e,a){const{images:t,...n}=a;let o=e.joinChannel(t);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyBandbool(e,a){const{operator:t,...n}=a;let o=e.bandbool(t);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyAffine(e,a){const{background:t,interpolation:n,matrix:o,...r}=a;let s=e.affine(o,{background:t||"transparent",interpolator:n||"bicubic"});return Object.keys(r).length>0&&(s=this.applyFormatAndQuality(s,r)),s}applyDilate(e,a){const{kernelSize:t,...n}=a;let o=t?e.dilate(t):e.dilate();return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyErode(e,a){const{kernelSize:t,...n}=a;let o=t?e.erode(t):e.erode();return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyPipelineColourspace(e,a){const{colourspace:t,...n}=a;let o=e.pipelineColourspace(t);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyToColourspace(e,a){const{colourspace:t,...n}=a;let o=e.toColourspace(t);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyRemoveAlpha(e,a){const{background:t,...n}=a;let o=e.removeAlpha();return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyEnsureAlpha(e,a){const{alpha:t,...n}=a;let o=e.ensureAlpha();return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyFormatAndQuality(e,a){const t=this.getFormatOptions(a);return a.format?e.toFormat(a.format,t):Object.keys(t).length>0?e.jpeg(t).png(t).webp(t):e}getFormatOptions(e){const{alphaQuality:a,compressionLevel:t,delay:n,effort:o,loop:r,lossless:s,progressive:i,quality:l}=e,p={};return l!==void 0&&(p.quality=l),i!==void 0&&(p.progressive=i),s!==void 0&&(p.lossless=s),t!==void 0&&(p.compressionLevel=t),o!==void 0&&(p.effort=o),a!==void 0&&(p.alphaQuality=a),r!==void 0&&(p.loop=r),n!==void 0&&(p.delay=n),p}async validateImage(e){const a=typeof e.size=="string"?Number.parseInt(e.size,10):e.size;if(this.config?.maxImageSize&&a>this.config.maxImageSize)throw new Error(`Image size ${a} exceeds maximum allowed size ${this.config.maxImageSize}`);if(!k(e.contentType,"image"))throw new Error(`File is not an image: ${e.contentType}`);const t=v(e.contentType);if(this.config?.supportedFormats&&t&&!this.config.supportedFormats.includes(t))throw new Error(`Unsupported image format: ${t}`);try{const n=await u(e.content).metadata();if(!n.width||!n.height)throw new Error("Invalid image: missing dimensions")}catch(n){throw new Error(`Invalid image file: ${n}`)}}async createTransformResult(e,a){const t=await u(e).metadata();return{buffer:e,format:t.format||"unknown",height:t.height||0,originalFile:a,size:e.length,width:t.width||0}}generateCacheKey(e,a){const t=a.map(n=>`${n.type}:${JSON.stringify(n.options)}`).join("|");return`${e}:${t}`}}export{z as default};
|
|
1
|
+
var f=Object.defineProperty;var y=(h,t)=>f(h,"name",{value:t,configurable:!0});import{Readable as d}from"node:stream";import u from"sharp";import b from"../packem_shared/BaseTransformer-Fpcuz4kj.js";import{isValidMediaType as k,getFormatFromContentType as w}from"../packem_shared/isValidMediaType-B-2UKjZx.js";var v=Object.defineProperty,A=y((h,t)=>v(h,"name",{value:t,configurable:!0}),"h");class Q extends b{static{y(this,"R")}static{A(this,"ImageTransformer")}constructor(t,a={}){const e=a.logger||t.logger,n={cacheTtl:3600,failOn:"warning",limitInputPixels:268435456,maxCacheSize:100,maxImageSize:50*1024*1024,supportedFormats:["jpeg","png","webp","avif","tiff","gif","svg"],...a};super(t,n,e)}openImage(t){return u(t,{failOn:this.config?.failOn??"warning",limitInputPixels:this.config?.limitInputPixels??268435456})}async resize(t,a){return this.transform(t,[{options:a,type:"resize"}])}async crop(t,a){return this.transform(t,[{options:a,type:"crop"}])}async rotate(t,a){return this.transform(t,[{options:a,type:"rotate"}])}async convertFormat(t,a,e={}){return this.transform(t,[{options:{...e,format:a},type:"format"}])}async sharpen(t,a={}){return this.transform(t,[{options:a,type:"sharpen"}])}async blur(t,a={}){return this.transform(t,[{options:a,type:"blur"}])}async median(t,a={}){return this.transform(t,[{options:a,type:"median"}])}async clahe(t,a={}){return this.transform(t,[{options:a,type:"clahe"}])}async convolve(t,a){return this.transform(t,[{options:a,type:"convolve"}])}async threshold(t,a={}){return this.transform(t,[{options:a,type:"threshold"}])}async boolean(t,a){return this.transform(t,[{options:a,type:"boolean"}])}async linear(t,a){return this.transform(t,[{options:a,type:"linear"}])}async recombine(t,a){return this.transform(t,[{options:a,type:"recombine"}])}async modulate(t,a){return this.transform(t,[{options:a,type:"modulate"}])}async tint(t,a){return this.transform(t,[{options:a,type:"tint"}])}async greyscale(t,a={}){return this.transform(t,[{options:a,type:"greyscale"}])}async colourspace(t,a){return this.transform(t,[{options:a,type:"colourspace"}])}async extractChannel(t,a){return this.transform(t,[{options:a,type:"extractChannel"}])}async joinChannel(t,a){return this.transform(t,[{options:a,type:"joinChannel"}])}async bandbool(t,a){return this.transform(t,[{options:a,type:"bandbool"}])}async autoOrient(t,a={}){return this.transform(t,[{options:a,type:"autoOrient"}])}async flip(t,a={}){return this.transform(t,[{options:a,type:"flip"}])}async flop(t,a={}){return this.transform(t,[{options:a,type:"flop"}])}async flatten(t,a={}){return this.transform(t,[{options:a,type:"flatten"}])}async unflatten(t,a={}){return this.transform(t,[{options:a,type:"unflatten"}])}async gamma(t,a={}){return this.transform(t,[{options:a,type:"gamma"}])}async negate(t,a={}){return this.transform(t,[{options:a,type:"negate"}])}async normalise(t,a={}){return this.transform(t,[{options:a,type:"normalise"}])}async affine(t,a){return this.transform(t,[{options:a,type:"affine"}])}async dilate(t,a={}){return this.transform(t,[{options:a,type:"dilate"}])}async erode(t,a={}){return this.transform(t,[{options:a,type:"erode"}])}async pipelineColourspace(t,a){return this.transform(t,[{options:a,type:"pipelineColourspace"}])}async toColourspace(t,a){return this.transform(t,[{options:a,type:"toColourspace"}])}async removeAlpha(t,a={}){return this.transform(t,[{options:a,type:"removeAlpha"}])}async ensureAlpha(t,a={}){return this.transform(t,[{options:a,type:"ensureAlpha"}])}async transform(t,a){const e={id:t},n=this.generateCacheKey(t,a),o=this.cache?await Promise.resolve(this.cache.get(n)):void 0;if(o)return this.logger?.debug("Returning cached transformed image for %s",t),o;const r=await this.storage.get(e);await this.validateImage(r);const s=await this.applyTransformations(r.content,a),i=await this.createTransformResult(s,r);return this.cache&&this.cache.set(n,i),i}async transformStream(t,a){const e=await this.transform(t,a);return{headers:{"Content-Length":e.buffer.length.toString(),"Content-Type":this.getContentTypeFromResult(e),"X-Image-Height":e.height?.toString(),"X-Image-Width":e.width?.toString()},size:e.buffer.length,stream:d.from(e.buffer)}}async applyTransformations(t,a){let e=this.openImage(t);for(const n of a)switch(n.type){case"affine":{e=this.applyAffine(e,n.options);break}case"autoOrient":{e=e.rotate();break}case"bandbool":{e=this.applyBandbool(e,n.options);break}case"blur":{e=this.applyBlur(e,n.options);break}case"boolean":{e=this.applyBoolean(e,n.options);break}case"clahe":{e=this.applyCLAHE(e,n.options);break}case"colourspace":{e=this.applyColourspace(e,n.options);break}case"convolve":{e=this.applyConvolve(e,n.options);break}case"crop":{e=this.applyCrop(e,n.options);break}case"dilate":{e=this.applyDilate(e,n.options);break}case"ensureAlpha":{e=this.applyEnsureAlpha(e,n.options);break}case"erode":{e=this.applyErode(e,n.options);break}case"extractChannel":{e=this.applyExtractChannel(e,n.options);break}case"flatten":{e=e.flatten();break}case"flip":{e=e.flip();break}case"flop":{e=e.flop();break}case"format":case"quality":{e=this.applyFormatAndQuality(e,n.options);break}case"gamma":{e=e.gamma();break}case"greyscale":{e=this.applyGreyscale(e,n.options);break}case"joinChannel":{e=this.applyJoinChannel(e,n.options);break}case"linear":{e=this.applyLinear(e,n.options);break}case"median":{e=this.applyMedian(e,n.options);break}case"modulate":{e=this.applyModulate(e,n.options);break}case"negate":{e=e.negate();break}case"normalise":case"normalize":{e=e.normalise();break}case"pipelineColourspace":{e=this.applyPipelineColourspace(e,n.options);break}case"recombine":{e=this.applyRecombine(e,n.options);break}case"removeAlpha":{e=this.applyRemoveAlpha(e,n.options);break}case"resize":{e=this.applyResize(e,n.options);break}case"rotate":{e=this.applyRotate(e,n.options);break}case"sharpen":{e=this.applySharpen(e,n.options);break}case"threshold":{e=this.applyThreshold(e,n.options);break}case"tint":{e=this.applyTint(e,n.options);break}case"toColourspace":{e=this.applyToColourspace(e,n.options);break}case"unflatten":{e=e.unflatten();break}default:throw new Error(`Unknown transformation type: ${n.type}`)}return e.toBuffer()}applyResize(t,a){const{background:e,fastShrinkOnLoad:n,fit:o="cover",height:r,kernel:s,position:i,width:l,withoutEnlargement:p,withoutReduction:g,...m}=a;let c={background:e||"transparent",fastShrinkOnLoad:n,fit:o,height:r,kernel:s,position:i,width:l,withoutEnlargement:p,withoutReduction:g};return Object.keys(m).length>0&&(c={...c,...this.getFormatOptions(m)}),t.resize(c)}applyCrop(t,a){const{height:e,left:n,top:o,width:r,...s}=a;let i=t.extract({height:e,left:n,top:o,width:r});return Object.keys(s).length>0&&(i=this.applyFormatAndQuality(i,s)),i}applyRotate(t,a){const{angle:e,background:n,...o}=a;let r=t.rotate(e,{background:n||"transparent"});return Object.keys(o).length>0&&(r=this.applyFormatAndQuality(r,o)),r}applySharpen(t,a){const{sigma:e,...n}=a,o={};e!==void 0&&(o.sigma=e);let r=t.sharpen(o);return Object.keys(n).length>0&&(r=this.applyFormatAndQuality(r,n)),r}applyBlur(t,a){const{sigma:e,...n}=a;let o=t.blur(e===void 0?!0:e);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyMedian(t,a){const{size:e,...n}=a;let o=t.median(e);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyCLAHE(t,a){const{height:e,maxSlope:n,width:o,...r}=a;let s=t.clahe({height:e,maxSlope:n,width:o});return Object.keys(r).length>0&&(s=this.applyFormatAndQuality(s,r)),s}applyConvolve(t,a){const{height:e,kernel:n,offset:o,scale:r,width:s,...i}=a;let l=t.convolve({height:e,kernel:n,offset:o,scale:r,width:s});return Object.keys(i).length>0&&(l=this.applyFormatAndQuality(l,i)),l}applyThreshold(t,a){const{grayscale:e,greyscale:n,threshold:o=128,...r}=a;let s=t.threshold(o,{greyscale:n||e});return Object.keys(r).length>0&&(s=this.applyFormatAndQuality(s,r)),s}applyBoolean(t,a){const{operand:e,operator:n,raw:o,...r}=a;let s=t.boolean(e,n,o);return Object.keys(r).length>0&&(s=this.applyFormatAndQuality(s,r)),s}applyLinear(t,a){const{a:e,b:n,...o}=a;let r=t.linear(e,n);return Object.keys(o).length>0&&(r=this.applyFormatAndQuality(r,o)),r}applyRecombine(t,a){const{matrix:e,...n}=a;let o=t.recomb(e.flat());return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyModulate(t,a){const{brightness:e,hue:n,lightness:o,saturation:r,...s}=a;let i=t.modulate({brightness:e,hue:n,lightness:o,saturation:r});return Object.keys(s).length>0&&(i=this.applyFormatAndQuality(i,s)),i}applyTint(t,a){const{rgb:e,...n}=a;let o=t.tint(Array.isArray(e)?{b:e[2],g:e[1],r:e[0]}:e);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyGreyscale(t,a){const{grayscale:e,greyscale:n,...o}=a;let r=t.greyscale(n||e);return Object.keys(o).length>0&&(r=this.applyFormatAndQuality(r,o)),r}applyColourspace(t,a){const{colourspace:e,...n}=a;let o=t.toColourspace(e);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyExtractChannel(t,a){const{channel:e,...n}=a;let o=t.extractChannel(e);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyJoinChannel(t,a){const{images:e,...n}=a;let o=t.joinChannel(e);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyBandbool(t,a){const{operator:e,...n}=a;let o=t.bandbool(e);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyAffine(t,a){const{background:e,interpolation:n,matrix:o,...r}=a;let s=t.affine(o,{background:e||"transparent",interpolator:n||"bicubic"});return Object.keys(r).length>0&&(s=this.applyFormatAndQuality(s,r)),s}applyDilate(t,a){const{kernelSize:e,...n}=a;let o=e?t.dilate(e):t.dilate();return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyErode(t,a){const{kernelSize:e,...n}=a;let o=e?t.erode(e):t.erode();return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyPipelineColourspace(t,a){const{colourspace:e,...n}=a;let o=t.pipelineColourspace(e);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyToColourspace(t,a){const{colourspace:e,...n}=a;let o=t.toColourspace(e);return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyRemoveAlpha(t,a){const{background:e,...n}=a;let o=t.removeAlpha();return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyEnsureAlpha(t,a){const{alpha:e,...n}=a;let o=t.ensureAlpha();return Object.keys(n).length>0&&(o=this.applyFormatAndQuality(o,n)),o}applyFormatAndQuality(t,a){const e=this.getFormatOptions(a);return a.format?t.toFormat(a.format,e):Object.keys(e).length>0?t.jpeg(e).png(e).webp(e):t}getFormatOptions(t){const{alphaQuality:a,compressionLevel:e,delay:n,effort:o,loop:r,lossless:s,progressive:i,quality:l}=t,p={};return l!==void 0&&(p.quality=l),i!==void 0&&(p.progressive=i),s!==void 0&&(p.lossless=s),e!==void 0&&(p.compressionLevel=e),o!==void 0&&(p.effort=o),a!==void 0&&(p.alphaQuality=a),r!==void 0&&(p.loop=r),n!==void 0&&(p.delay=n),p}async validateImage(t){const a=typeof t.size=="string"?Number.parseInt(t.size,10):t.size;if(this.config?.maxImageSize&&a>this.config.maxImageSize)throw new Error(`Image size ${a} exceeds maximum allowed size ${this.config.maxImageSize}`);if(!k(t.contentType,"image"))throw new Error(`File is not an image: ${t.contentType}`);const e=w(t.contentType);if(this.config?.supportedFormats&&e&&!this.config.supportedFormats.includes(e))throw new Error(`Unsupported image format: ${e}`);try{const n=await this.openImage(t.content).metadata();if(!n.width||!n.height)throw new Error("Invalid image: missing dimensions");const{maxImageHeight:o,maxImageWidth:r}=this.config??{};if(r!==void 0&&n.width>r)throw new Error(`Image width ${n.width}px exceeds maximum ${r}px`);if(o!==void 0&&n.height>o)throw new Error(`Image height ${n.height}px exceeds maximum ${o}px`)}catch(n){throw new Error(`Invalid image file: ${n}`)}}async createTransformResult(t,a){const e=await u(t).metadata();return{buffer:t,format:e.format||"unknown",height:e.height||0,originalFile:a,size:t.length,width:e.width||0}}generateCacheKey(t,a){const e=a.map(n=>`${n.type}:${JSON.stringify(n.options)}`).join("|");return`${t}:${e}`}}export{Q as default};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { type i as AudioChannelMixOptions, type h as AudioResampleOptions, type j as AudioTransformOptions, type g as AudioTransformResult, type k as AudioTransformationStep, type A as AudioTransformerConfig, B as BaseTransformer, type C as CropOptions, type m as ImageFormat, type I as ImageTransformerConfig, type U as MediaTransformQuery, type Q as MediaTransformResult, type W as MediaTransformationStep, type O as MediaTransformerConfig, type R as ResizeOptions, type l as RotateOptions, type n as TransformOptions, type T as TransformResult, type N as TransformationStep, type c as VideoCropOptions, type b as VideoResizeOptions, type d as VideoRotateOptions, type e as VideoTransformOptions, type a as VideoTransformResult, type f as VideoTransformationStep, type V as VideoTransformerConfig } from "../packem_shared/types.d-
|
|
2
|
-
export { M as MediaTransformer } from "../packem_shared/media-transformer.d-
|
|
3
|
-
import { a as FileReturn } from "../packem_shared/storage.d-
|
|
1
|
+
export { type i as AudioChannelMixOptions, type h as AudioResampleOptions, type j as AudioTransformOptions, type g as AudioTransformResult, type k as AudioTransformationStep, type A as AudioTransformerConfig, B as BaseTransformer, type C as CropOptions, type m as ImageFormat, type I as ImageTransformerConfig, type U as MediaTransformQuery, type Q as MediaTransformResult, type W as MediaTransformationStep, type O as MediaTransformerConfig, type R as ResizeOptions, type l as RotateOptions, type n as TransformOptions, type T as TransformResult, type N as TransformationStep, type c as VideoCropOptions, type b as VideoResizeOptions, type d as VideoRotateOptions, type e as VideoTransformOptions, type a as VideoTransformResult, type f as VideoTransformationStep, type V as VideoTransformerConfig } from "../packem_shared/types.d-C8eSxqX9.js";
|
|
2
|
+
export { M as MediaTransformer } from "../packem_shared/media-transformer.d-DK7NJncf.js";
|
|
3
|
+
import { a as FileReturn } from "../packem_shared/storage.d-Cr6f2lac.js";
|
|
4
4
|
import 'node:stream';
|
|
5
5
|
import 'node:crypto';
|
|
6
6
|
import 'node:http';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as a}from"../packem_shared/BaseTransformer-
|
|
1
|
+
import{default as a}from"../packem_shared/BaseTransformer-Fpcuz4kj.js";import{default as t}from"../packem_shared/MediaTransformer-D-1c9Q_k.js";import{getFormatFromContentType as d,isKnownContentType as f,isValidMediaType as n,validateMediaFile as m}from"../packem_shared/isValidMediaType-B-2UKjZx.js";import{default as l}from"../packem_shared/ValidationError-D8KKJiKA.js";export{a as BaseTransformer,t as MediaTransformer,l as ValidationError,d as getFormatFromContentType,f as isKnownContentType,n as isValidMediaType,m as validateMediaFile};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { F as File, a as FileReturn, B as BaseStorage } from "../packem_shared/storage.d-
|
|
2
|
-
import { V as VideoTransformerConfig, a as VideoTransformResult, b as VideoResizeOptions, c as VideoCropOptions, d as VideoRotateOptions, e as VideoTransformOptions, f as VideoTransformationStep, B as BaseTransformer } from "../packem_shared/types.d-
|
|
1
|
+
import { F as File, a as FileReturn, B as BaseStorage } from "../packem_shared/storage.d-Cr6f2lac.js";
|
|
2
|
+
import { V as VideoTransformerConfig, a as VideoTransformResult, b as VideoResizeOptions, c as VideoCropOptions, d as VideoRotateOptions, e as VideoTransformOptions, f as VideoTransformationStep, B as BaseTransformer } from "../packem_shared/types.d-C8eSxqX9.js";
|
|
3
3
|
import 'node:stream';
|
|
4
4
|
import 'node:crypto';
|
|
5
5
|
import 'node:http';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var w=Object.defineProperty;var p=(n,t)=>w(n,"name",{value:t,configurable:!0});import{Input as f,BufferSource as m,ALL_FORMATS as u,Output as g,BufferTarget as l,Conversion as y,Mp4OutputFormat as d,WebMOutputFormat as b,OggOutputFormat as v,MkvOutputFormat as T}from"mediabunny";import F from"../packem_shared/BaseTransformer-
|
|
1
|
+
var w=Object.defineProperty;var p=(n,t)=>w(n,"name",{value:t,configurable:!0});import{Input as f,BufferSource as m,ALL_FORMATS as u,Output as g,BufferTarget as l,Conversion as y,Mp4OutputFormat as d,WebMOutputFormat as b,OggOutputFormat as v,MkvOutputFormat as T}from"mediabunny";import F from"../packem_shared/BaseTransformer-Fpcuz4kj.js";import{isValidMediaType as k,getFormatFromContentType as O}from"../packem_shared/isValidMediaType-B-2UKjZx.js";var V=Object.defineProperty,z=p((n,t)=>V(n,"name",{value:t,configurable:!0}),"d");class C extends F{static{p(this,"b")}static{z(this,"VideoTransformer")}constructor(t,e={}){const r=e.logger||t.logger,o={cacheTtl:3600,defaultBitrate:2e6,defaultCodec:"avc",maxCacheSize:50,maxVideoSize:500*1024*1024,supportedFormats:["mp4","webm","mkv","avi","mov","flv","wmv"],...e};super(t,o,r)}async resize(t,e){return this.transform(t,[{options:e,type:"resize"}])}async crop(t,e){return this.transform(t,[{options:e,type:"crop"}])}async rotate(t,e){return this.transform(t,[{options:e,type:"rotate"}])}async convertFormat(t,e,r={}){return this.transform(t,[{options:{...r,format:e},type:"format"}])}async transcode(t,e,r={}){return this.transform(t,[{options:{...r,codec:e},type:"codec"}])}async transform(t,e){const r={id:t},o=this.generateCacheKey(t,e);if(this.cache){const s=await Promise.resolve(this.cache.get(o));if(s)return this.logger?.debug("Returning cached transformed video for %s",t),s}const a=await this.storage.get(r);await this.validateVideo(a);const c=await this.applyTransformations(a.content,e),i=await this.createTransformResult(c,a);return this.cache&&this.cache.set(o,i),i}async applyTransformations(t,e){const r=new f({formats:u,source:new m(t)}),o=this.determineOutputFormat(e),a=new g({format:o,target:new l}),c=this.stepsToVideoOptions(e),i=await y.init({input:r,output:a,video:c});if(!i.isValid){const s=i.discardedTracks.map(h=>h.reason).join(", ");throw new Error(`Video transformation failed: ${s}`)}return await i.execute(),Buffer.from(a.target.buffer)}stepsToVideoOptions(t){const e={};for(const r of t)switch(r.type){case"bitrate":{const o=r.options;o.bitrate&&(e.bitrate=o.bitrate);break}case"codec":{const o=r.options;o.codec&&(e.codec=o.codec),o.bitrate&&(e.bitrate=o.bitrate);break}case"crop":{const o=r.options;e.crop={height:o.height,left:o.left,top:o.top,width:o.width};break}case"frameRate":{const o=r.options;o.frameRate&&(e.frameRate=o.frameRate);break}case"resize":{const o=r.options;e.width=o.width,e.height=o.height,e.fit=o.fit,o.position!==void 0&&(e.position=o.position);break}case"rotate":{const o=r.options;e.rotate=o.angle,o.background&&(e.background=o.background);break}}return e}determineOutputFormat(t){for(const e of t)if(e.type==="format"&&e.options.format)return this.formatStringToOutputFormat(e.options.format);return new d}formatStringToOutputFormat(t){switch(t.toLowerCase()){case"mkv":return new T;case"mp4":return new d;case"ogg":return new v;case"webm":return new b;default:return new d}}async validateVideo(t){const e=typeof t.size=="string"?Number.parseInt(t.size,10):t.size;if(this.config?.maxVideoSize&&e>this.config.maxVideoSize)throw new Error(`Video size ${e} exceeds maximum allowed size ${this.config.maxVideoSize}`);if(!k(t.contentType,"video"))throw new Error(`File is not a video: ${t.contentType}`);const r=O(t.contentType);if(this.config?.supportedFormats&&r&&!this.config.supportedFormats.includes(r))throw new Error(`Unsupported video format: ${r}`);try{if(!await new f({formats:u,source:new m(t.content)}).getPrimaryVideoTrack())throw new Error("No video track found")}catch(o){throw new Error(`Invalid video file: ${o}`)}}async createTransformResult(t,e){const r=new f({formats:u,source:new m(t)}),o=await r.getPrimaryVideoTrack(),a=await r.computeDuration();return{bitrate:this.config.defaultBitrate,buffer:t,duration:a,format:"mp4",height:o?.displayHeight||0,originalFile:e,size:t.length,width:o?.displayWidth||0}}generateCacheKey(t,e){const r=e.map(o=>`${o.type}:${JSON.stringify(o.options)}`).join("|");return`${t}:${r}`}}export{C as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@visulima/storage",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.27",
|
|
4
4
|
"description": "Visulima upload - Store files in a web-accessible location via a simplified API. Can automatically scale and rotate images. Includes S3, Azure, GCS and local filesystem-based backends with the most convenient features of each.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"anolilab",
|
|
@@ -31,6 +31,8 @@
|
|
|
31
31
|
"gcs",
|
|
32
32
|
"google",
|
|
33
33
|
"google-cloud-storage",
|
|
34
|
+
"hetzner",
|
|
35
|
+
"hetzner-object-storage",
|
|
34
36
|
"hono",
|
|
35
37
|
"middleware",
|
|
36
38
|
"minio",
|
|
@@ -46,6 +48,7 @@
|
|
|
46
48
|
"s3",
|
|
47
49
|
"serverless",
|
|
48
50
|
"storage",
|
|
51
|
+
"storj",
|
|
49
52
|
"sveltekit",
|
|
50
53
|
"tus",
|
|
51
54
|
"typescript",
|
|
@@ -117,6 +120,34 @@
|
|
|
117
120
|
"types": "./dist/storage/local/index.d.ts",
|
|
118
121
|
"import": "./dist/storage/local/index.js"
|
|
119
122
|
},
|
|
123
|
+
"./provider/supabase": {
|
|
124
|
+
"types": "./dist/storage/supabase/index.d.ts",
|
|
125
|
+
"import": "./dist/storage/supabase/index.js"
|
|
126
|
+
},
|
|
127
|
+
"./provider/uploadthing": {
|
|
128
|
+
"types": "./dist/storage/uploadthing/index.d.ts",
|
|
129
|
+
"import": "./dist/storage/uploadthing/index.js"
|
|
130
|
+
},
|
|
131
|
+
"./provider/dropbox": {
|
|
132
|
+
"types": "./dist/storage/dropbox/index.d.ts",
|
|
133
|
+
"import": "./dist/storage/dropbox/index.js"
|
|
134
|
+
},
|
|
135
|
+
"./provider/google-drive": {
|
|
136
|
+
"types": "./dist/storage/google-drive/index.d.ts",
|
|
137
|
+
"import": "./dist/storage/google-drive/index.js"
|
|
138
|
+
},
|
|
139
|
+
"./provider/onedrive": {
|
|
140
|
+
"types": "./dist/storage/onedrive/index.d.ts",
|
|
141
|
+
"import": "./dist/storage/onedrive/index.js"
|
|
142
|
+
},
|
|
143
|
+
"./provider/box": {
|
|
144
|
+
"types": "./dist/storage/box/index.d.ts",
|
|
145
|
+
"import": "./dist/storage/box/index.js"
|
|
146
|
+
},
|
|
147
|
+
"./provider/bunny": {
|
|
148
|
+
"types": "./dist/storage/bunny/index.d.ts",
|
|
149
|
+
"import": "./dist/storage/bunny/index.js"
|
|
150
|
+
},
|
|
120
151
|
"./openapi": {
|
|
121
152
|
"types": "./dist/openapi/index.d.ts",
|
|
122
153
|
"import": "./dist/openapi/index.js"
|
|
@@ -177,6 +208,22 @@
|
|
|
177
208
|
"types": "./dist/adapter/nuxt/module.d.ts",
|
|
178
209
|
"import": "./dist/adapter/nuxt/module.js"
|
|
179
210
|
},
|
|
211
|
+
"./ai/sdk": {
|
|
212
|
+
"types": "./dist/ai/ai-sdk/index.d.ts",
|
|
213
|
+
"import": "./dist/ai/ai-sdk/index.js"
|
|
214
|
+
},
|
|
215
|
+
"./ai/openai": {
|
|
216
|
+
"types": "./dist/ai/openai/index.d.ts",
|
|
217
|
+
"import": "./dist/ai/openai/index.js"
|
|
218
|
+
},
|
|
219
|
+
"./ai/claude": {
|
|
220
|
+
"types": "./dist/ai/claude/index.d.ts",
|
|
221
|
+
"import": "./dist/ai/claude/index.js"
|
|
222
|
+
},
|
|
223
|
+
"./ai/tanstack": {
|
|
224
|
+
"types": "./dist/ai/tanstack/index.d.ts",
|
|
225
|
+
"import": "./dist/ai/tanstack/index.js"
|
|
226
|
+
},
|
|
180
227
|
"./package.json": "./package.json"
|
|
181
228
|
},
|
|
182
229
|
"files": [
|
|
@@ -194,30 +241,46 @@
|
|
|
194
241
|
"mime": "^4.1.0",
|
|
195
242
|
"nanoid": "5.1.11",
|
|
196
243
|
"path-to-regexp": "8.4.2",
|
|
197
|
-
"type-is": "^2.0.1"
|
|
244
|
+
"type-is": "^2.0.1",
|
|
245
|
+
"zod": "4.4.3"
|
|
198
246
|
},
|
|
199
247
|
"peerDependencies": {
|
|
248
|
+
"@anthropic-ai/claude-agent-sdk": ">=0.2.0",
|
|
200
249
|
"@aws-sdk/client-s3": ">=3.901.0",
|
|
201
250
|
"@aws-sdk/credential-providers": ">=3.901.0",
|
|
202
251
|
"@aws-sdk/s3-request-presigner": ">=3.901.0",
|
|
203
252
|
"@aws-sdk/signature-v4-crt": ">=3.901.0",
|
|
204
253
|
"@aws-sdk/types": ">=3.930.0",
|
|
205
254
|
"@azure/storage-blob": ">=12.28.0",
|
|
255
|
+
"@bunny.net/storage-sdk": ">=0.3.0",
|
|
256
|
+
"@googleapis/drive": ">=20.0.0",
|
|
257
|
+
"@microsoft/microsoft-graph-client": ">=3.0.0",
|
|
206
258
|
"@netlify/blobs": ">=10.3.1",
|
|
207
259
|
"@nuxt/kit": ">=4.2.1",
|
|
260
|
+
"@openai/agents": ">=0.11.0",
|
|
208
261
|
"@opentelemetry/api": ">=1.9.0",
|
|
209
262
|
"@solidjs/start": ">=1.1.0",
|
|
263
|
+
"@supabase/storage-js": ">=2.105.0",
|
|
264
|
+
"@tanstack/ai": ">=0.16.0",
|
|
210
265
|
"@vercel/blob": ">=2.0.0",
|
|
266
|
+
"ai": ">=5.0.0",
|
|
211
267
|
"aws-crt": ">=1.27.3",
|
|
212
268
|
"aws4fetch": ">=1.0.0",
|
|
269
|
+
"box-typescript-sdk-gen": ">=1.19.0",
|
|
270
|
+
"dropbox": ">=10.34.0",
|
|
213
271
|
"gaxios": ">=7.1.2",
|
|
214
272
|
"google-auth-library": ">=10.4.0",
|
|
215
273
|
"hono": ">=4.0.0",
|
|
216
274
|
"mediabunny": ">=1.23.0",
|
|
217
275
|
"next": ">=15",
|
|
218
|
-
"
|
|
276
|
+
"openai": ">=5.0.0",
|
|
277
|
+
"sharp": ">=0.34.5",
|
|
278
|
+
"uploadthing": ">=7.0.0"
|
|
219
279
|
},
|
|
220
280
|
"peerDependenciesMeta": {
|
|
281
|
+
"@anthropic-ai/claude-agent-sdk": {
|
|
282
|
+
"optional": true
|
|
283
|
+
},
|
|
221
284
|
"@aws-sdk/client-s3": {
|
|
222
285
|
"optional": true
|
|
223
286
|
},
|
|
@@ -236,27 +299,54 @@
|
|
|
236
299
|
"@azure/storage-blob": {
|
|
237
300
|
"optional": true
|
|
238
301
|
},
|
|
302
|
+
"@bunny.net/storage-sdk": {
|
|
303
|
+
"optional": true
|
|
304
|
+
},
|
|
305
|
+
"@googleapis/drive": {
|
|
306
|
+
"optional": true
|
|
307
|
+
},
|
|
308
|
+
"@microsoft/microsoft-graph-client": {
|
|
309
|
+
"optional": true
|
|
310
|
+
},
|
|
239
311
|
"@netlify/blobs": {
|
|
240
312
|
"optional": true
|
|
241
313
|
},
|
|
242
314
|
"@nuxt/kit": {
|
|
243
315
|
"optional": true
|
|
244
316
|
},
|
|
317
|
+
"@openai/agents": {
|
|
318
|
+
"optional": true
|
|
319
|
+
},
|
|
245
320
|
"@opentelemetry/api": {
|
|
246
321
|
"optional": true
|
|
247
322
|
},
|
|
248
323
|
"@solidjs/start": {
|
|
249
324
|
"optional": true
|
|
250
325
|
},
|
|
326
|
+
"@supabase/storage-js": {
|
|
327
|
+
"optional": true
|
|
328
|
+
},
|
|
329
|
+
"@tanstack/ai": {
|
|
330
|
+
"optional": true
|
|
331
|
+
},
|
|
251
332
|
"@vercel/blob": {
|
|
252
333
|
"optional": true
|
|
253
334
|
},
|
|
335
|
+
"ai": {
|
|
336
|
+
"optional": true
|
|
337
|
+
},
|
|
254
338
|
"aws-crt": {
|
|
255
339
|
"optional": true
|
|
256
340
|
},
|
|
257
341
|
"aws4fetch": {
|
|
258
342
|
"optional": true
|
|
259
343
|
},
|
|
344
|
+
"box-typescript-sdk-gen": {
|
|
345
|
+
"optional": true
|
|
346
|
+
},
|
|
347
|
+
"dropbox": {
|
|
348
|
+
"optional": true
|
|
349
|
+
},
|
|
260
350
|
"gaxios": {
|
|
261
351
|
"optional": true
|
|
262
352
|
},
|
|
@@ -272,8 +362,14 @@
|
|
|
272
362
|
"next": {
|
|
273
363
|
"optional": true
|
|
274
364
|
},
|
|
365
|
+
"openai": {
|
|
366
|
+
"optional": true
|
|
367
|
+
},
|
|
275
368
|
"sharp": {
|
|
276
369
|
"optional": true
|
|
370
|
+
},
|
|
371
|
+
"uploadthing": {
|
|
372
|
+
"optional": true
|
|
277
373
|
}
|
|
278
374
|
},
|
|
279
375
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var y=Object.defineProperty;var d=(l,t)=>y(l,"name",{value:t,configurable:!0});import{BlobServiceClient as m,StorageSharedKeyCredential as p}from"@azure/storage-blob";import{L as g}from"./path-D7rMc9nq-B718mbm6.js";import{r as f,d as w,o as b}from"./part-match-DqD5U7An.js";import{throwErrorCode as s,ERRORS as c}from"./ERRORS-B9jkvKwx.js";import{B as C,t as E}from"./storage-m_Cxgiih.js";import{createRetryWrapper as O}from"./isRetryableError-DQNSZiBc.js";import{O as T}from"./local-meta-storage-Bkwqi_gi.js";import N from"./AzureFile-BKHru1zB.js";import R from"./AzureSMetaStorage-BqA4jUDJ.js";import{o as S}from"./has-content-Bx2p8Okx.js";var F=Object.defineProperty,v=d((l,t)=>F(l,"name",{value:t,configurable:!0}),"m");class q extends C{static name="azure";checksumTypes=["md5"];meta;client;containerClient;root;retry;constructor(t){if(super(t),!t.containerName)throw new Error("Missing required parameter: Azure container name.");const e=t.connectionString||process.env.AZURE_STORAGE_CONNECTION_STRING||void 0;if(e)this.client=m.fromConnectionString(e);else{const i=t.accountKey||process.env.AZURE_STORAGE_ACCOUNT_KEY||void 0,n=t.accountName||process.env.AZURE_STORAGE_ACCOUNT||void 0;if(!t.accountKey)throw new Error("Missing required parameter: Azure blob storage account key.");if(!t.accountName)throw new Error("Missing required parameter: Azure blob storage account name.");const a=new p(n,i);this.client=new m(t.endpoint??`https://${n}.blob.core.windows.net`,a)}this.containerClient=this.client.getContainerClient(t.containerName),this.root=t.root?g(t.root).replace(/^\//,""):"";const r={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:v(i=>{const n=i;if(n.statusCode&&[408,429,500,502,503,504].includes(n.statusCode))return!0;if(i instanceof Error){const a=n.code;if(a==="ECONNRESET"||a==="ETIMEDOUT"||a==="ENOTFOUND"||a==="ECONNREFUSED")return!0}return!1},"shouldRetry"),...t.retryConfig};if(this.retry=O(r),t.metaStorage)this.meta=t.metaStorage;else{let i={...t,...t.metaStorageConfig,logger:this.logger};"directory"in i?(this.logger?.debug("Using local meta storage"),this.meta=new T(i)):(e===i.connectionString&&(i={...i,client:this.client}),this.meta=new R(i))}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}async create(t){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const o=typeof t.ttl=="string"?E(t.ttl):t.ttl;o!==void 0&&(e.expiredAt=Date.now()+o)}const r=new N(e);r.name=this.namingFunction(r),await this.validate(r);try{const o=await this.getMeta(r.id);if(o.bytesWritten>=0)return o}catch{}const i=this.containerClient.getBlockBlobClient(this.getFullPath(r.name)),n={};for(const[o,h]of Object.entries(r.metadata||{}))n[o]=JSON.stringify(h);const a=await this.retry(()=>i.uploadData(Buffer.from(""),{blobHTTPHeaders:{blobContentType:r.contentType},metadata:{name:r.name,originalName:r.originalName,...n}}));return a.requestId===void 0?s(c.FILE_ERROR,"azure create upload error"):(r.requestId=a.requestId,r.uri=a._response.headers.get("location"),r.bytesWritten=0,await this.saveMeta(r),r.status="created",await this.onCreate(r),r)})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await Promise.all([this.deleteMeta(e.id),this.retry(()=>this.containerClient.getBlockBlobClient(this.getFullPath(e.name)).deleteIfExists())]);const r={...e};return await this.onDelete(r),r})}async move(t,e){return this.instrumentOperation("move",async()=>{const r=await this.copy(t,e),i=this.getFullPath(t);return await this.retry(()=>this.containerClient.getBlockBlobClient(i).deleteIfExists()),r})}async write(t){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(!f(t,e))return s(c.FILE_CONFLICT);await this.lock(t.id);try{if(S(t)){if((e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:a,stream:o}=await w(t.body);a?.mime&&(e.contentType=a.mime),t.body=o}catch{}const r=this.containerClient.getBlockBlobClient(this.getFullPath(e.name)),i=new AbortController;t.body.on("error",()=>{i.abort()});const n=await this.retry(()=>r.uploadStream(t.body,void 0,void 0,{abortSignal:i.signal,blobHTTPHeaders:{blobContentType:e.contentType??"application/octet-stream"},metadata:e.metadata}));if(n.requestId===void 0)return s(c.FILE_ERROR,"azure write upload error");e.requestId=n.requestId,e.bytesWritten+=t.contentLength||0,e.status=b(e),e.status==="completed"&&(e.uri=n._response.headers.get("location"),await this.deleteMeta(e.id))}}finally{await this.unlock(t.id)}return e})}async get({id:t}){return this.instrumentOperation("get",async()=>{const e=this.containerClient.getBlockBlobClient(t);if(!await this.retry(()=>e.exists()))try{return await this.getMeta(t),s(c.GONE)}catch{return s(c.FILE_NOT_FOUND)}const r=await this.retry(()=>e.getProperties()),{contentLength:i,contentType:n,etag:a,expiresOn:o,lastModified:h,metadata:u}=r;return{content:await this.retry(()=>e.downloadToBuffer()),contentType:n,ETag:a,expiredAt:o,id:t,metadata:u||{},modifiedAt:h,name:u?.name||t,originalName:u?.originalName||"",size:i}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{await this.getMeta(t);const e=this.containerClient.getBlockBlobClient(t);return await this.retry(()=>e.exists())}catch{return!1}})}async copy(t,e){return this.instrumentOperation("copy",async()=>{const r=this.containerClient.getBlockBlobClient(this.getFullPath(t));if(!await this.retry(()=>r.exists()))try{return await this.getMeta(t),s(c.GONE)}catch{return s(c.FILE_NOT_FOUND)}const i=this.containerClient.getBlockBlobClient(this.getFullPath(e)),n=await this.retry(()=>i.beginCopyFromURL(r.url));return await this.retry(()=>n.pollUntilDone()),{...await this.getMeta(t),id:e,name:e}})}async list(t=1e3){return this.instrumentOperation("list",async()=>{const e=[];let r=!0,i;for(;r;)try{const n=this.containerClient.listBlobsFlat({includeMetadata:!0,prefix:this.root}).byPage({continuationToken:i,maxPageSize:t}),a=(await this.retry(()=>n.next())).value;a!==void 0&&"segment"in a&&a.segment.blobItems.forEach(o=>{o.deleted||e.push({createdAt:o.properties.createdOn,id:o.name,modifiedAt:o.properties.lastModified})}),r=a?.continuationToken!==void 0,r&&(i=a.continuationToken)}catch(n){const a=this.normalizeError(n instanceof Error?n:new Error(String(n)));throw await this.onError(a),n}return e},{limit:t})}getFullPath(t){return this.assetFolder!==void 0?`${this.assetFolder}/${t}`:t}async accessCheck(){await this.retry(()=>this.containerClient.getProperties())}}export{q as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var n=Object.defineProperty;var s=(a,t)=>n(a,"name",{value:t,configurable:!0});import{Readable as i}from"node:stream";import c from"mime";import{N as h}from"./cache-qV_5Umeq.js";var f=Object.defineProperty,m=s((a,t)=>f(a,"name",{value:t,configurable:!0}),"n");class C{static{s(this,"l")}constructor(t,e,r){this.storage=t,this.config=e,this.logger=r,this.cache=e.cache??new h}storage;static{m(this,"BaseTransformer")}config;logger;cache;async transformStream(t,e){const r=await this.transform(t,e);if(r&&"buffer"in r){const{buffer:o}=r;return{headers:{"Content-Length":o.length.toString(),"Content-Type":this.getContentTypeFromResult(r)},size:o.length,stream:i.from(o)}}throw new Error("Streaming transformation not supported for this transformer")}clearCache(t){t?this.cache?.delete(t):this.cache?.clear?.()}getCacheStats(){return{maxSize:-1,size:this.cache?.size??0}}getContentTypeFromResult(t){if(t?.format){const e=c.getType(t.format);if(e)return e}return"application/octet-stream"}}export{C as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"node:fs";import"node:fs/promises";import"node:stream";import"./local-meta-storage-Bkwqi_gi.js";import{q as u}from"./disk-storage-BvdK4bqF.js";import"./path-D7rMc9nq-B718mbm6.js";import"./part-match-DqD5U7An.js";import"./ERRORS-B9jkvKwx.js";import"./storage-m_Cxgiih.js";import"./File-alcSNpLq.js";import"./update-size-DANV7aa2.js";import"./has-content-Bx2p8Okx.js";export{u as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var g=Object.defineProperty;var o=(i,t)=>g(i,"name",{value:t,configurable:!0});import{createReadStream as f,createWriteStream as b}from"node:fs";import{truncate as w}from"node:fs/promises";import{Transform as E,pipeline as F}from"node:stream";import{q as C,y as v,m as W,s as R}from"./disk-storage-BvdK4bqF.js";import{y as S}from"./local-meta-storage-Bkwqi_gi.js";import{r as T,d as N,o as O}from"./part-match-DqD5U7An.js";import{throwErrorCode as p,ERRORS as n}from"./ERRORS-B9jkvKwx.js";import{LRUCache as k}from"lru-cache";import{createHash as P}from"node:crypto";import{u as x}from"./update-size-DANV7aa2.js";import{o as M}from"./has-content-Bx2p8Okx.js";var _=Object.defineProperty,I=o((i,t)=>_(i,"name",{value:t,configurable:!0}),"a");class L extends E{static{o(this,"n")}constructor(t,e){super(),this.path=e,this.hashes=t,this.hash=this.hashes.get(e)||P(this.hashes.algorithm),this.hashCopy=this.hash.copy()}path;static{I(this,"RangeChecksum")}hash;hashCopy;hashes;reset(){this.hashes.set(this.path,this.hashCopy)}digest(t="hex"){return this.hash.copy().digest(t)}_transform(t,e,s){this.push(t),this.hash.update(t),s()}_flush(t){t()}}var z=Object.defineProperty,U=o((i,t)=>z(i,"name",{value:t,configurable:!0}),"h");class A extends k{static{o(this,"p")}constructor(t="sha1",e){super({ttl:1e3,ttlAutopurge:!0,...e}),this.algorithm=t}algorithm;static{U(this,"RangeHasher")}hex(t){return this.get(t)?.copy().digest("hex")||""}base64(t){return this.get(t)?.copy().digest("base64")||""}async init(t,e=0){return this.get(t)?.copy()||this.updateFromFs(t,e)}digester(t){return new L(this,t)}async updateFromFs(t,e=0,s){const r=await this.fromFs(t,e,s);return this.set(t,r),r}fromFs(t,e=0,s){return new Promise((r,a)=>{const h=this.digester(t);s!==void 0&&(h.hash=s),f(t,{start:e}).on("error",a).on("end",()=>{r(h.hash)}).pipe(h).resume()})}}var H=Object.defineProperty,l=o((i,t)=>H(i,"name",{value:t,configurable:!0}),"d");class Z extends C{static{o(this,"O")}static{l(this,"DiskStorageWithChecksum")}hashes;constructor(t){super(t),this.hashes=new A(t?.checksum==="sha1"?"sha1":"md5")}async delete({id:t}){try{const e=await this.getMeta(t),s=this.getFilePath(e.name);this.hashes.delete(s),await S(s),await this.deleteMeta(t);const r={...e,status:"deleted"};return await this.onDelete(r),r}catch(e){this.logger?.error("[error]: Could not delete file: %O",e);const s=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(s)}return{id:t}}async write(t){let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&x(e,t.size),!T(t,e))return p(n.FILE_CONFLICT);const s=this.getFilePath(e.name);try{const r=t.start||0;if(await v(s),(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(e.bytesWritten=r),await this.hashes.init(s),M(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return p(n.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:m,stream:c}=await N(t.body);m?.mime&&(e.contentType=m.mime),t.body=c}catch{}const[a,h]=await this.lazyWrite({...t,...e});if(h)return await w(s,e.bytesWritten),p(h);typeof a!="number"&&await this.hashes.updateFromFs(s,e.bytesWritten),e.bytesWritten=a}return e.status=O(e),e.hash={algorithm:this.hashes.algorithm,value:this.hashes.hex(s)},e.status==="completed"&&this.hashes.delete(s),await this.saveMeta(e),e}catch(r){await this.hashes.updateFromFs(s,e.bytesWritten);const a=this.normalizeError(r instanceof Error?r:new Error(String(r)));return await this.onError(a),p(n.FILE_ERROR,(typeof a.message=="string"?a.message:String(r))||String(r))}}lazyWrite(t){return new Promise((e,s)=>{const r=this.getFilePath(t.name),a=b(r,{flags:"r+",start:t.start}),h=new W(t.contentLength||Number(t.size)-t.start),m=R(t.checksum,t.checksumAlgorithm),c=this.hashes.digester(r),y=!t.checksum,d=l(u=>{c.reset(),a.close(),e([Number.NaN,u])},"failWithCode");h.on("error",()=>{d(n.FILE_CONFLICT)}),m.on("error",()=>{d(n.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{d(y?void 0:n.REQUEST_ABORTED)}),F(t.body,h,m,c,a,u=>{if(u){c.reset(),s(u);return}e([t.start+a.bytesWritten])})})}}export{Z as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var E=Object.defineProperty;var a=(e,o)=>E(e,"name",{value:o,configurable:!0});var c=Object.defineProperty,s=a((e,o)=>c(e,"name",{value:o,configurable:!0}),"s"),l=(e=>(e.BAD_REQUEST="BadRequest",e.CHECKSUM_MISMATCH="ChecksumMismatch",e.FILE_CONFLICT="FileConflict",e.FILE_ERROR="FileError",e.FILE_LOCKED="FileLocked",e.FILE_NOT_ALLOWED="FileNotAllowed",e.FILE_NOT_FOUND="FileNotFound",e.FORBIDDEN="Forbidden",e.GONE="Gone",e.INVALID_FILE_NAME="InvalidFileName",e.INVALID_FILE_SIZE="InvalidFileSize",e.INVALID_RANGE="InvalidRange",e.INVALID_TYPE="Invalidtype",e.METHOD_NOT_ALLOWED="MethodNotAllowed",e.REQUEST_ABORTED="RequestAborted",e.REQUEST_ENTITY_TOO_LARGE="RequestEntityTooLarge",e.STORAGE_BUSY="StorageBusy",e.STORAGE_ERROR="StorageError",e.TOO_MANY_REQUESTS="TooManyRequests",e.UNKNOWN_ERROR="UnknownError",e.UNPROCESSABLE_ENTITY="UnprocessableEntity",e.UNSUPPORTED_CHECKSUM_ALGORITHM="UnsupportedChecksumAlgorithm",e.UNSUPPORTED_MEDIA_TYPE="UnsupportedMediaType",e))(l||{});const d=(()=>{const e={BadRequest:[400,"Bad request"],ChecksumMismatch:[460,"Checksum mismatch"],FileConflict:[409,"File conflict"],FileError:[500,"Something went wrong writing the file"],FileLocked:[423,"File locked"],FileNotAllowed:[403,"File not allowed"],FileNotFound:[404,"Not found"],Forbidden:[403,"Authenticated user is not allowed access"],Gone:[410,"The file for this url no longer exists"],InvalidFileName:[400,"Invalid file name or it cannot be retrieved"],InvalidFileSize:[400,"File size cannot be retrieved"],InvalidRange:[400,"Invalid or missing content-range header"],Invalidtype:[400,'Invalid or missing "content-type" header'],MethodNotAllowed:[405,"Method not allowed"],RequestAborted:[499,"Request aborted"],RequestEntityTooLarge:[413,"Request entity too large"],StorageBusy:[503,"Storage is busy"],StorageError:[503,"Storage error"],TooManyRequests:[429,"Too many requests"],UnknownError:[500,"Something went wrong"],UnprocessableEntity:[422,"Validation failed"],UnsupportedChecksumAlgorithm:[400,"Unsupported checksum algorithm"],UnsupportedMediaType:[415,"Unsupported media type"]},o={};return Object.keys(e).forEach(r=>{const[t,n]=e[r];o[r]={code:r,message:n,statusCode:t}}),o})();class u extends Error{static{a(this,"UploadError")}static{s(this,"UploadError")}name="UploadError";UploadErrorCode="UnknownError";detail;constructor(o="UnknownError",r,t){super(r||o),this.name="UploadError",this.detail=t,Object.values(l).includes(o)&&(this.UploadErrorCode=o)}}const p=s(e=>!!e.UploadErrorCode,"isUploadError"),U=s((e,o)=>{const r=e;let t;r&&typeof r=="string"&&r in d&&(t=d[r]);const n=o||(t?.body&&typeof t.body=="object"&&"message"in t.body?t.body.message:void 0)||t?.message||"UnknownError",i=new u(r,n);throw i.UploadErrorCode=r,typeof o=="string"&&(i.detail=o),i},"throwErrorCode");export{l as ERRORS,d as ErrorMap,u as UploadError,p as isUploadError,U as throwErrorCode};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var m=Object.defineProperty;var o=(t,i)=>m(t,"name",{value:i,configurable:!0});import p from"@sindresorhus/fnv1a";import{nanoid as f}from"nanoid";var y=Object.defineProperty,a=o((t,i)=>y(t,"name",{value:i,configurable:!0}),"t");const l=a(t=>p(t,{size:64}).toString(16),"hash"),g=a(t=>{if(typeof t.mimeType=="string")return t.mimeType;if(typeof t.type=="string")return t.type;if(typeof t.filetype=="string")return t.filetype},"extractMimeType"),u=a(t=>{if(typeof t.name=="string")return t.name;if(typeof t.title=="string")return t.title;if(typeof t.originalName=="string")return t.originalName;if(typeof t.filename=="string")return t.filename},"extractOriginalName"),d=a(t=>{const{metadata:i,originalName:n,size:e}=t,s=String(i.lastModified??Date.now());return[n,e,s].filter(Boolean).map(String).map(r=>l(r)).join("-")},"generateFileId");class N{static{o(this,"g")}static{a(this,"File")}bytesWritten=Number.NaN;contentType;originalName;id;metadata;name="";size;status;expiredAt;createdAt;modifiedAt;hash;content;ETag;constructor({contentType:i,expiredAt:n,metadata:e,originalName:s,size:r}){this.metadata=e,this.originalName=s||u(e)||(this.id=f()),this.contentType=i||g(e)||"application/octet-stream",this.expiredAt=n,typeof r=="string"||typeof r=="number"?this.size=Number(r):(typeof e.size=="string"||typeof e.size=="number")&&(this.size=Number(e.size)),typeof this.size=="number"&&this.size<=0&&(this.size=void 0),this.id||=d(this)}}export{N as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var g=Object.defineProperty;var d=(c,t)=>g(c,"name",{value:t,configurable:!0});import{randomUUID as f}from"node:crypto";import{request as y}from"gaxios";import{GoogleAuth as w}from"google-auth-library";import{r as C,E,b as R,g as b,d as l}from"./gcs-meta-storage-BfJB-ejI.js";import{r as U,d as k,o as $}from"./part-match-DqD5U7An.js";import{throwErrorCode as I,ERRORS as O}from"./ERRORS-B9jkvKwx.js";import{B as S,t as T}from"./storage-m_Cxgiih.js";import{O as v}from"./local-meta-storage-Bkwqi_gi.js";import m from"./GCSConfig-BQ0OpVhe.js";import A from"./GCSFile-CHjX_fJk.js";import{o as B}from"./has-content-Bx2p8Okx.js";var P=Object.defineProperty,j=d((c,t)=>P(c,"name",{value:t,configurable:!0}),"e");class x extends Error{static{d(this,"o")}constructor(t,e,r){super(t),this.code=e,this.config=r}code;config;static{j(this,"FetchError")}name="FetchError"}var G=Object.defineProperty,p=d((c,t)=>G(c,"name",{value:t,configurable:!0}),"m");const q=p(c=>c>=200&&c<300||c===308||c===499,"validateStatus");class Q extends S{static name="gcs";checksumTypes=["md5","crc32c"];meta;bucket;authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;constructor(t){super(t);const e=t.bucket||process.env.GCS_BUCKET;if(!e)throw new Error("GCS bucket is not defined");if(!t.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");this.bucket=e,this.storageBaseURI=`${t.storageAPI||m.storageAPI}/${this.bucket}/o`,this.uploadBaseURI=`${t.uploadAPI||m.uploadAPI}/${this.bucket}/o`,this.isCustomEndpoint=new URL(this.storageBaseURI).hostname!=="storage.googleapis.com";const{retryOptions:r,useAuthWithCustomEndpoint:s,userProject:o}=t;this.userProject=o,this.useAuthWithCustomEndpoint=s||!1,this.retryOptions={...C,...r},t.scopes||=m.authScopes,this.authClient=new w(t);const{bucket:i,metaStorage:n,metaStorageConfig:a,projectId:h}=t;if(n)this.meta=n;else{let u={...t,...a,logger:this.logger};"directory"in u?(this.logger?.debug("Using local meta storage"),this.meta=new v(u)):(i===u.bucket&&h===u.projectId&&(u={...u,authClient:this.authClient}),this.meta=new E(u))}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(u=>{this.logger?.error("Storage access check failed: %O",u)})}normalizeError(t){if(t.config){const e=+t.code||500;return{code:`GCS${e}`,message:t.message,name:t.name,retryable:e>=499,statusCode:e}}return{code:"GenericUploadError",message:`[${this.constructor.name}] ${t.message}`,name:t.name,statusCode:500}}async create(t){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const a=typeof t.ttl=="string"?T(t.ttl):t.ttl;a!==void 0&&(e.expiredAt=Date.now()+a)}const r=new A(e);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);return a.bytesWritten=await this.internalWrite(a),a}catch{}const s={"Content-Type":"application/json; charset=utf-8","X-Goog-Upload-Command":"start","X-Goog-Upload-Protocol":"resumable","X-Upload-Content-Length":r.size.toString(),"X-Upload-Content-Type":r.contentType},o={body:JSON.stringify({metadata:r.metadata}),headers:s,method:"POST",params:{name:r.name,size:r.size,uploadType:"resumable"},url:this.uploadBaseURI},i=await this.makeRequest(o);if(i.status!==200)throw new Error("Expected 200 response from GCS");const n=i.headers.get("X-Goog-Upload-Status")||i.headers.get("x-goog-upload-status");if(n!=="active")throw new Error(`X-Goog-Upload-Status response header expected 'active' got: ${n}`);return r.uri=i.headers.get("location"),this.config.clientDirectUpload?(r.GCSUploadURI=r.uri,this.logger?.debug("send uploadURI to client: %s",r.GCSUploadURI),r.status="created",r):(r.bytesWritten=0,await this.saveMeta(r),r.status="created",await this.onCreate(r),r)})}async write(t){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(!U(t,e))return I(O.FILE_CONFLICT);await this.lock(t.id);try{if(B(t)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:r,stream:s}=await k(t.body);r?.mime&&(e.contentType=r.mime),t.body=s}catch{}e.bytesWritten=await this.internalWrite({...e,...t}),e.status=$(e),e.status==="completed"&&(e.uri=`${this.storageBaseURI}/${e.name}`,await this.internalOnComplete(e))}finally{await this.unlock(t.id)}return e})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);if(!e.uri)throw new Error(`File ${t} does not have a valid URI`);e.status="deleted",await Promise.all([this.makeRequest({method:"DELETE",url:e.uri,validateStatus:q}),this.deleteMeta(e.id)]);const r={...e};return await this.onDelete(r),r})}async copy(t,e){return this.instrumentOperation("copy",async()=>{const r=new URL(`/${this.bucket}/${t}`,"file://"),s=new URL(encodeURI(e),r).pathname,[,o,...i]=s.split("/"),n=i.join("/"),a=`${this.storageBaseURI}/${t}/rewriteTo/b/${o}/o/${n}`;let h={};const u={body:"",headers:{"Content-Type":"application/json"},method:"POST",url:a};do u.body=h.rewriteToken?JSON.stringify({rewriteToken:h.rewriteToken}):"",h=(await this.makeRequest(u)).data||{};while(h.rewriteToken);return await this.getMeta(e)})}async move(t,e){return this.instrumentOperation("move",async()=>{const r=await this.copy(t,e),s=`${this.storageBaseURI}/${t}`;return await this.makeRequest({method:"DELETE",url:s}),r})}async get({id:t}){return this.instrumentOperation("get",async()=>{const{data:e}=await this.makeRequest({params:{alt:"json"},url:`${this.storageBaseURI}/${t}`});if(await this.checkIfExpired({expiredAt:e.timeDeleted}),!e.uri)throw new Error("File URI not found");const r=(await this.makeRequest({params:{alt:"media"},url:e.uri})).data;let s;if(typeof r=="string")s=Buffer.from(r,"utf8");else if(r&&typeof r=="object"&&"data"in r){const o=r.data;s=Buffer.from(o)}else s=Buffer.from(r);return{...e,content:s}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{return await this.getMeta(t),await this.makeRequest({method:"HEAD",url:`${this.storageBaseURI}/${t}`}),!0}catch{return!1}})}async list(t=1e3){return this.instrumentOperation("list",async()=>{const e=[];let r=!0,s={params:{maxResults:t},url:this.storageBaseURI};for(;r;)try{const{data:o}=await this.makeRequest(s);(o?.items||[]).forEach(({name:i,timeCreated:n,updated:a})=>{e.push({createdAt:n,id:i,modifiedAt:a})}),r=o?.nextPageToken!==void 0,r&&(s={...s,params:{...s.params,pageToken:o.nextPageToken}})}catch(o){const i=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(i),o}return e},{limit:t})}async internalWrite(t){const{body:e,bytesWritten:r,size:s,uri:o=""}=t,i=R(t),n={method:"PUT"};if(e?.on){const a=new AbortController;e.on("aborted",()=>{a.abort()}),n.body=e,n.signal=a.signal}n.headers={Accept:"application/json","Content-Range":i,...s===r?{"X-Goog-Upload-Command":"upload, finalize"}:{}};try{const a=await this.makeRequest({url:o,...n});if(a.status===308){const h=a.headers.get("range");return h?b(h):0}if(a.status===200)return this.logger?.debug("uploaded %O",a.data),s;throw new x(String(a.data),`GCS${a.status}`,{uri:o})}catch(a){this.logger?.error(o,a);const h=this.normalizeError(a instanceof Error?a:new Error(String(a)));throw await this.onError(h),a}}internalOnComplete=p(t=>this.deleteMeta(t.id),"internalOnComplete");async makeRequest(t){return typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":")),t={...t,headers:{"User-Agent":`${l.name}/${l.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${l.version} gccl-invocation-id/${f()}`},params:{...this.userProject===void 0?{}:{userProject:this.userProject}},retry:!0,retryConfig:this.retryOptions,timeout:6e4},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?y(t):this.authClient.request(t)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}}export{Q as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"node:fs/promises";import"node:os";import{O as f}from"./local-meta-storage-Bkwqi_gi.js";import"./path-D7rMc9nq-B718mbm6.js";import"./ERRORS-B9jkvKwx.js";import"./MetaStorage-Y4m1dWgd.js";import"./Metadata-B6Ir0KO7.js";export{f as default};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|