@visulima/storage 1.0.0-alpha.32 → 1.0.0-alpha.33
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 +24 -0
- package/README.md +1 -1
- package/dist/adapter/nuxt/module.d.ts +4 -4
- package/dist/adapter/nuxt/node_modules/.bin/nuxi +2 -2
- package/dist/adapter/nuxt/node_modules/.bin/nuxt +2 -2
- package/dist/ai/ai-sdk/index.d.ts +5 -5
- package/dist/ai/ai-sdk/index.js +1 -1
- package/dist/ai/claude/index.d.ts +4 -4
- package/dist/ai/claude/index.js +1 -1
- package/dist/ai/openai/index.d.ts +5 -5
- package/dist/ai/openai/index.js +1 -1
- package/dist/ai/tanstack/index.d.ts +4 -4
- package/dist/ai/tanstack/index.js +1 -1
- package/dist/handler/http/fetch/index.d.ts +7 -7
- package/dist/handler/http/fetch/index.js +1 -1
- package/dist/handler/http/hono/index.d.ts +4 -4
- package/dist/handler/http/hono/index.js +1 -1
- package/dist/handler/http/nextjs/index.d.ts +4 -4
- package/dist/handler/http/nextjs/index.js +1 -1
- package/dist/handler/http/node/index.d.ts +7 -7
- package/dist/handler/http/node/index.js +1 -1
- package/dist/handler/http/solid-start/index.d.ts +4 -4
- package/dist/handler/http/solid-start/index.js +1 -1
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/packem_shared/{AwsLightMetaStorage-B-iQbToR.js → AwsLightMetaStorage-Cj7ym1qI.js} +1 -1
- package/dist/packem_shared/{AwsLightStorage-B1jNF7sv.js → AwsLightStorage-6Z1ovz9R.js} +1 -1
- package/dist/packem_shared/AzureSMetaStorage-YCj-X8a1.js +1 -0
- package/dist/packem_shared/AzureStorage-CbAN4vPm.js +1 -0
- package/dist/packem_shared/{BoxMetaStorage-nESVquA1.js → BoxMetaStorage-BGBPZWoL.js} +1 -1
- package/dist/packem_shared/{BoxStorage-CHYDrcxw.js → BoxStorage-DitlyKVB.js} +1 -1
- package/dist/packem_shared/{BunS3MetaStorage-BkZx5q4w.js → BunS3MetaStorage-DAskpG_G.js} +1 -1
- package/dist/packem_shared/BunS3Storage-D1gxh5Tt.js +1 -0
- package/dist/packem_shared/{BunnyMetaStorage-bB8NXGUI.js → BunnyMetaStorage-ByUvvuPc.js} +1 -1
- package/dist/packem_shared/BunnyStorage-r6DptjUt.js +1 -0
- package/dist/packem_shared/{CloudinaryMetaStorage-BzibHydK.js → CloudinaryMetaStorage-DsJyN0iQ.js} +1 -1
- package/dist/packem_shared/{CloudinaryStorage-Cj00ZXWV.js → CloudinaryStorage-BR8CZhlL.js} +1 -1
- package/dist/packem_shared/{DiskStorage-BrAb28Je.js → DiskStorage-DHcHDZeO.js} +1 -1
- package/dist/packem_shared/{DiskStorageWithChecksum-BX85CHJ6.js → DiskStorageWithChecksum--U7zOz-0.js} +1 -1
- package/dist/packem_shared/{DropboxMetaStorage-Bfm5bblb.js → DropboxMetaStorage-B7eY16fU.js} +1 -1
- package/dist/packem_shared/{DropboxStorage-Btz9h9Mj.js → DropboxStorage-9-jj7H8C.js} +1 -1
- package/dist/packem_shared/ERRORS-vMSqlI69.js +1 -0
- package/dist/packem_shared/{FirebaseMetaStorage-CshnJMb0.js → FirebaseMetaStorage-BpYykWhG.js} +1 -1
- package/dist/packem_shared/FirebaseStorage-DB87abIF.js +2 -0
- package/dist/packem_shared/{FtpMetaStorage-CoyWJafY.js → FtpMetaStorage-v2wXTwqX.js} +1 -1
- package/dist/packem_shared/FtpStorage-DdRf0Wg6.js +1 -0
- package/dist/packem_shared/{GCSMetaStorage-CfZj52hQ.js → GCSMetaStorage-BMtou9o7.js} +1 -1
- package/dist/packem_shared/GCStorage-CRVpuZ5_.js +1 -0
- package/dist/packem_shared/{GoogleDriveMetaStorage-CBSdEQr6.js → GoogleDriveMetaStorage-BT9N1Wji.js} +1 -1
- package/dist/packem_shared/GoogleDriveStorage-BzuSZZzN.js +1 -0
- package/dist/packem_shared/LocalMetaStorage-BFQz8VPm.js +1 -0
- package/dist/packem_shared/MemoryStorage-BuNY963D.js +1 -0
- package/dist/packem_shared/{Multipart-qaEOWKz1.js → Multipart-IE3j_gAJ.js} +1 -1
- package/dist/packem_shared/{Multipart-kQ5wJQaV.js → Multipart-UIRqOPCf.js} +1 -1
- package/dist/packem_shared/{NetlifyBlobMetaStorage-CqluIgV0.js → NetlifyBlobMetaStorage-DNgncijZ.js} +1 -1
- package/dist/packem_shared/{NetlifyBlobStorage-CkMw9Uyv.js → NetlifyBlobStorage-eP0pkR0o.js} +1 -1
- package/dist/packem_shared/{OneDriveMetaStorage-DPTNMpeq.js → OneDriveMetaStorage-CkaFJFHe.js} +1 -1
- package/dist/packem_shared/OneDriveStorage-3Iq5vBfd.js +1 -0
- package/dist/packem_shared/{PocketBaseMetaStorage-CemTT_01.js → PocketBaseMetaStorage-CxnGde_n.js} +1 -1
- package/dist/packem_shared/{PocketBaseStorage-BZNzWj09.js → PocketBaseStorage-DHphg8yi.js} +1 -1
- package/dist/packem_shared/{Rest-DukkeDZe.js → Rest-B_E4TrqF.js} +1 -1
- package/dist/packem_shared/{Rest-BAcUFAgk.js → Rest-DItHKz-N.js} +1 -1
- package/dist/packem_shared/S3Storage-Bc9eq5vJ.js +1 -0
- package/dist/packem_shared/{SftpMetaStorage-Cs8b7uBO.js → SftpMetaStorage-CBcUhZRU.js} +1 -1
- package/dist/packem_shared/SftpStorage-DSsMhTZC.js +1 -0
- package/dist/packem_shared/{SharePointMetaStorage-DTVKAx6f.js → SharePointMetaStorage-yzxvwgKr.js} +1 -1
- package/dist/packem_shared/{SharePointStorage-D1cWu-14.js → SharePointStorage-C6KIGN2r.js} +1 -1
- package/dist/packem_shared/{SupabaseMetaStorage-D_fGv0d6.js → SupabaseMetaStorage-D26wob-R.js} +1 -1
- package/dist/packem_shared/SupabaseStorage-B_knTpFQ.js +1 -0
- package/dist/packem_shared/{Tus-BrP4RFTg.js → Tus-CAestp2j.js} +1 -1
- package/dist/packem_shared/{Tus-BYTcw17H.js → Tus-KQ8J2WF3.js} +1 -1
- package/dist/packem_shared/UploadControl-Otw_5jxw.js +1 -0
- package/dist/packem_shared/{UploadThingMetaStorage-CAQ1uTfv.js → UploadThingMetaStorage-DPIokkHa.js} +1 -1
- package/dist/packem_shared/UploadThingStorage-B3aIKSMh.js +1 -0
- package/dist/packem_shared/{VercelBlobMetaStorage-DY4zAB6M.js → VercelBlobMetaStorage-Bx0l9Xt6.js} +1 -1
- package/dist/packem_shared/{VercelBlobStorage-u6xmp8ox.js → VercelBlobStorage-CGxoGkv4.js} +1 -1
- package/dist/packem_shared/{agentsListFiles-R-CnGKc4.js → agentsListFiles-Bl2TOnMy.js} +1 -1
- package/dist/packem_shared/{approval.d-CMAYH9GF.d.ts → approval.d-3sw7wbPG.d.ts} +1 -1
- package/dist/packem_shared/aws-light-meta-storage-CXIZfLXR.js +4 -0
- package/dist/packem_shared/{azure-meta-storage-C4SrMtT2.js → azure-meta-storage-B-D-tBVw.js} +1 -1
- package/dist/packem_shared/{base-handler-core-Ccvdhx-k.js → base-handler-core-OdTz4-Pm.js} +1 -1
- package/dist/packem_shared/{base-handler-fetch-DzbThEWy.js → base-handler-fetch-B0FWPun7.js} +1 -1
- package/dist/packem_shared/{base-handler-node-CmCpLlBt.js → base-handler-node-CR2Bg43M.js} +1 -1
- package/dist/packem_shared/{claudeListFiles-DAezbKEi.js → claudeListFiles-yLqM5iFS.js} +1 -1
- package/dist/packem_shared/{createResponsesFileTools-BCep-qdO.js → createResponsesFileTools-DFFHq35s.js} +1 -1
- package/dist/packem_shared/{defaultCloudStorageFileNameValidation-DwDn0XB5.js → defaultCloudStorageFileNameValidation-De0HFP7m.js} +1 -1
- package/dist/packem_shared/disk-storage-CklneE2m.js +1 -0
- package/dist/packem_shared/{disk-storage-with-checksum.d-aYBmkg45.d.ts → disk-storage-with-checksum.d-Z_Z-OQpm.d.ts} +1 -1
- package/dist/packem_shared/executors-MzQbS9FT.js +1 -0
- package/dist/packem_shared/{executors.d-WGJGPSZs.d.ts → executors.d-CRI3jlk4.d.ts} +2 -2
- package/dist/packem_shared/{gcs-meta-storage-COq32th7.js → gcs-meta-storage-Dh0TAqB_.js} +1 -1
- package/dist/packem_shared/{index.d-CYdFIB-w.d.ts → index.d-C4o9jVLx.d.ts} +229 -12
- package/dist/packem_shared/{listFiles-BtP6VnUp.js → listFiles-BNGQbV_d.js} +1 -1
- package/dist/packem_shared/{listFiles-B6VF05d-.js → listFiles-BdBngq3i.js} +1 -1
- package/dist/packem_shared/local-meta-storage-Bvl0Flac.js +1 -0
- package/dist/packem_shared/{local-meta-storage.d-CuvN-KQ3.d.ts → local-meta-storage.d-CobcjyWu.d.ts} +1 -1
- package/dist/packem_shared/{media-transformer.d-DfU7VbFl.d.ts → media-transformer.d-B5cQJz30.d.ts} +2 -2
- package/dist/packem_shared/{memory-storage.d-DRbE0WMO.d.ts → memory-storage.d-CunLnxmE.d.ts} +1 -1
- package/dist/packem_shared/{path-D7rMc9nq-CPbxyMDy.js → path-D7rMc9nq-B718mbm6.js} +1 -1
- package/dist/packem_shared/{rest-base-xrnOBxS9.js → rest-base-DHkzq0rj.js} +1 -1
- package/dist/packem_shared/s3-base-storage-o_zkj15Y.js +1 -0
- package/dist/packem_shared/{s3-base-storage.d-BrHiKWFw.d.ts → s3-base-storage.d-ByfwKeid.d.ts} +21 -1
- package/dist/packem_shared/storage-z0o24zmZ.js +1 -0
- package/dist/packem_shared/{storage.d-X6TimMHY.d.ts → storage.d-D5UN5mRz.d.ts} +43 -1
- package/dist/packem_shared/{tus-base.d-Ds7xYAJC.d.ts → tus-base.d-D7UPhqdW.d.ts} +3 -3
- package/dist/packem_shared/{types.d-C4QumoP1.d.ts → types.d-BsjUOfBJ.d.ts} +2 -2
- package/dist/packem_shared/{types.d-B72PbsLY.d.ts → types.d-CPUyyEj9.d.ts} +2 -2
- package/dist/packem_shared/{types.d-a1grKnaX.d.ts → types.d-GogSTfRh.d.ts} +1 -1
- package/dist/storage/aws/index.d.ts +7 -2
- package/dist/storage/aws/index.js +1 -1
- package/dist/storage/aws-light/index.d.ts +7 -2
- package/dist/storage/aws-light/index.js +1 -1
- package/dist/storage/azure/index.d.ts +26 -7
- package/dist/storage/azure/index.js +1 -1
- package/dist/storage/box/index.d.ts +2 -2
- package/dist/storage/box/index.js +1 -1
- package/dist/storage/bun-s3/index.d.ts +2 -2
- package/dist/storage/bun-s3/index.js +1 -1
- package/dist/storage/bunny/index.d.ts +2 -2
- package/dist/storage/bunny/index.js +1 -1
- package/dist/storage/cloudinary/index.d.ts +2 -2
- package/dist/storage/cloudinary/index.js +1 -1
- package/dist/storage/dropbox/index.d.ts +2 -2
- package/dist/storage/dropbox/index.js +1 -1
- package/dist/storage/firebase/index.d.ts +2 -2
- package/dist/storage/firebase/index.js +1 -1
- package/dist/storage/ftp/index.d.ts +9 -3
- package/dist/storage/ftp/index.js +1 -1
- package/dist/storage/gcs/index.d.ts +15 -1
- package/dist/storage/gcs/index.js +1 -1
- package/dist/storage/google-drive/index.d.ts +2 -2
- package/dist/storage/google-drive/index.js +1 -1
- package/dist/storage/local/index.d.ts +3 -3
- package/dist/storage/local/index.js +1 -1
- package/dist/storage/memory/index.d.ts +2 -2
- package/dist/storage/memory/index.js +1 -1
- package/dist/storage/netlify-blob/index.d.ts +2 -2
- package/dist/storage/netlify-blob/index.js +1 -1
- package/dist/storage/onedrive/index.d.ts +4 -4
- package/dist/storage/onedrive/index.js +1 -1
- package/dist/storage/pocketbase/index.d.ts +2 -2
- package/dist/storage/pocketbase/index.js +1 -1
- package/dist/storage/sftp/index.d.ts +9 -3
- package/dist/storage/sftp/index.js +1 -1
- package/dist/storage/sharepoint/index.d.ts +3 -3
- package/dist/storage/sharepoint/index.js +1 -1
- package/dist/storage/supabase/index.d.ts +3 -3
- package/dist/storage/supabase/index.js +1 -1
- package/dist/storage/uploadthing/index.d.ts +2 -2
- package/dist/storage/uploadthing/index.js +1 -1
- package/dist/storage/vercel-blob/index.d.ts +2 -2
- package/dist/storage/vercel-blob/index.js +1 -1
- package/dist/transformer/audio-transformer.d.ts +2 -2
- package/dist/transformer/image-transformer.d.ts +2 -2
- package/dist/transformer/index.d.ts +3 -3
- package/dist/transformer/video-transformer.d.ts +2 -2
- package/package.json +1 -1
- package/dist/packem_shared/AzureSMetaStorage-CR-lfQNQ.js +0 -1
- package/dist/packem_shared/AzureStorage-B4E6VLn5.js +0 -1
- package/dist/packem_shared/BunS3Storage-BopE7kmX.js +0 -1
- package/dist/packem_shared/BunnyStorage-C3IBxJqr.js +0 -1
- package/dist/packem_shared/ERRORS-CyOuSMLY.js +0 -1
- package/dist/packem_shared/Files-tnc_buzM.js +0 -1
- package/dist/packem_shared/FirebaseStorage-Y9P6Dx8I.js +0 -2
- package/dist/packem_shared/FtpStorage-DCKPMX0z.js +0 -1
- package/dist/packem_shared/GCStorage-hfL1u2KQ.js +0 -1
- package/dist/packem_shared/GoogleDriveStorage-C7iuV7qb.js +0 -1
- package/dist/packem_shared/LocalMetaStorage-DSwsmdt7.js +0 -1
- package/dist/packem_shared/OneDriveStorage-CEGYb6OC.js +0 -1
- package/dist/packem_shared/S3Storage-7hG3izjU.js +0 -1
- package/dist/packem_shared/SftpStorage-DnigT9GT.js +0 -1
- package/dist/packem_shared/SupabaseStorage-DbIUa6NZ.js +0 -1
- package/dist/packem_shared/UploadThingStorage-B1qw1GrM.js +0 -1
- package/dist/packem_shared/aws-light-meta-storage-CstQBYXG.js +0 -4
- package/dist/packem_shared/default-BrhEhSqN.js +0 -1
- package/dist/packem_shared/disk-storage-fWizVrge.js +0 -1
- package/dist/packem_shared/executors-DG6hGtvm.js +0 -1
- package/dist/packem_shared/local-meta-storage-Dr891Iy7.js +0 -1
- package/dist/packem_shared/s3-base-storage-CqAyWHR6.js +0 -1
- package/dist/packem_shared/storage-uhIhcN-O.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { F as File, L as LocalMetaStorageOptions,
|
|
1
|
+
import { F as File, L as LocalMetaStorageOptions, j as BaseStorageOptions, M as MetaStorage, e as FileInit, O as OperationOptions, f as FilePart, g as FileQuery, a as FileReturn, B as BaseStorage } from "../../packem_shared/storage.d-D5UN5mRz.js";
|
|
2
2
|
import 'node:stream';
|
|
3
|
-
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-
|
|
3
|
+
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-CobcjyWu.js";
|
|
4
4
|
import { ConnectOptions } from 'ssh2-sftp-client';
|
|
5
5
|
import 'node:crypto';
|
|
6
6
|
import 'node:http';
|
|
@@ -51,6 +51,7 @@ interface SftpStorageOptions extends BaseStorageOptions {
|
|
|
51
51
|
declare class SftpStorage extends BaseStorage<SftpFile> {
|
|
52
52
|
static override readonly name: string;
|
|
53
53
|
override checksumTypes: string[];
|
|
54
|
+
override readonly supportsRange: boolean;
|
|
54
55
|
protected meta: MetaStorage<SftpFile>;
|
|
55
56
|
private readonly connection;
|
|
56
57
|
private readonly rootFolderPath;
|
|
@@ -59,7 +60,12 @@ declare class SftpStorage extends BaseStorage<SftpFile> {
|
|
|
59
60
|
write(part: FilePart | FileQuery | SftpFile, options?: OperationOptions): Promise<SftpFile>;
|
|
60
61
|
get({
|
|
61
62
|
id
|
|
62
|
-
}: FileQuery, options?: OperationOptions
|
|
63
|
+
}: FileQuery, options?: OperationOptions & {
|
|
64
|
+
range?: {
|
|
65
|
+
end?: number;
|
|
66
|
+
start: number;
|
|
67
|
+
};
|
|
68
|
+
}): Promise<FileReturn>;
|
|
63
69
|
delete({
|
|
64
70
|
id
|
|
65
71
|
}: FileQuery, options?: OperationOptions): Promise<SftpFile>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as a}from"../../packem_shared/SftpFile-CQCxZNVq.js";import{default as o}from"../../packem_shared/SftpMetaStorage-
|
|
1
|
+
import{default as a}from"../../packem_shared/SftpFile-CQCxZNVq.js";import{default as o}from"../../packem_shared/SftpMetaStorage-CBcUhZRU.js";import{default as p}from"../../packem_shared/SftpStorage-DSsMhTZC.js";export{a as SftpFile,o as SftpMetaStorage,p as SftpStorage};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { O as OneDriveFile, a as OneDriveStorageOptions } from "../../packem_shared/types.d-
|
|
2
|
-
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-
|
|
3
|
-
import { L as LocalMetaStorageOptions,
|
|
1
|
+
import { O as OneDriveFile, a as OneDriveStorageOptions } from "../../packem_shared/types.d-GogSTfRh.js";
|
|
2
|
+
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-CobcjyWu.js";
|
|
3
|
+
import { L as LocalMetaStorageOptions, j as BaseStorageOptions, M as MetaStorage, e as FileInit, O as OperationOptions, f as FilePart, g as FileQuery, a as FileReturn, B as BaseStorage } from "../../packem_shared/storage.d-D5UN5mRz.js";
|
|
4
4
|
import { Readable } from 'node:stream';
|
|
5
5
|
import { Client } from '@microsoft/microsoft-graph-client';
|
|
6
6
|
import 'node:crypto';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as t}from"../../packem_shared/SharePointFile-BA6X9Sxr.js";import{default as r}from"../../packem_shared/SharePointMetaStorage-
|
|
1
|
+
import{default as t}from"../../packem_shared/SharePointFile-BA6X9Sxr.js";import{default as r}from"../../packem_shared/SharePointMetaStorage-yzxvwgKr.js";import{default as S}from"../../packem_shared/SharePointStorage-C6KIGN2r.js";export{t as SharePointFile,r as SharePointMetaStorage,S as SharePointStorage};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { F as File, L as LocalMetaStorageOptions,
|
|
1
|
+
import { F as File, L as LocalMetaStorageOptions, j as BaseStorageOptions, M as MetaStorage, e as FileInit, O as OperationOptions, f as FilePart, g as FileQuery, a as FileReturn, B as BaseStorage } from "../../packem_shared/storage.d-D5UN5mRz.js";
|
|
2
2
|
import 'node:stream';
|
|
3
|
-
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-
|
|
3
|
+
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-CobcjyWu.js";
|
|
4
4
|
import { StorageClient } from '@supabase/storage-js';
|
|
5
5
|
import 'node:crypto';
|
|
6
6
|
import 'node:http';
|
|
@@ -104,7 +104,7 @@ declare class SupabaseStorage extends BaseStorage<SupabaseFile> {
|
|
|
104
104
|
responseContentDisposition?: string;
|
|
105
105
|
responseContentType?: string;
|
|
106
106
|
}): Promise<string>;
|
|
107
|
-
override getUploadUrl(key: string,
|
|
107
|
+
override getUploadUrl(key: string, options?: {
|
|
108
108
|
contentLength?: number;
|
|
109
109
|
contentType?: string;
|
|
110
110
|
expiresIn?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as t}from"../../packem_shared/SupabaseFile-DZ1iv9gM.js";import{default as r}from"../../packem_shared/SupabaseMetaStorage-
|
|
1
|
+
import{default as t}from"../../packem_shared/SupabaseFile-DZ1iv9gM.js";import{default as r}from"../../packem_shared/SupabaseMetaStorage-D26wob-R.js";import{default as p}from"../../packem_shared/SupabaseStorage-B_knTpFQ.js";export{t as SupabaseFile,r as SupabaseMetaStorage,p as SupabaseStorage};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { UTApi } from 'uploadthing/server';
|
|
2
|
-
import { L as LocalMetaStorageOptions,
|
|
2
|
+
import { L as LocalMetaStorageOptions, j as BaseStorageOptions, F as File, M as MetaStorage, e as FileInit, O as OperationOptions, f as FilePart, g as FileQuery, a as FileReturn, B as BaseStorage } from "../../packem_shared/storage.d-D5UN5mRz.js";
|
|
3
3
|
import 'node:stream';
|
|
4
|
-
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-
|
|
4
|
+
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-CobcjyWu.js";
|
|
5
5
|
import 'node:crypto';
|
|
6
6
|
import 'node:http';
|
|
7
7
|
import 'lru-cache';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as e}from"../../packem_shared/UploadThingFile-BpG9mE8K.js";import{default as r}from"../../packem_shared/UploadThingMetaStorage-
|
|
1
|
+
import{default as e}from"../../packem_shared/UploadThingFile-BpG9mE8K.js";import{default as r}from"../../packem_shared/UploadThingMetaStorage-DPIokkHa.js";import{default as d}from"../../packem_shared/UploadThingStorage-B3aIKSMh.js";export{e as UploadThingFile,r as UploadThingMetaStorage,d as UploadThingStorage};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { L as LocalMetaStorageOptions,
|
|
1
|
+
import { L as LocalMetaStorageOptions, j as BaseStorageOptions, F as File, M as MetaStorage, e as FileInit, O as OperationOptions, f as FilePart, g as FileQuery, a as FileReturn, B as BaseStorage } from "../../packem_shared/storage.d-D5UN5mRz.js";
|
|
2
2
|
import 'node:stream';
|
|
3
|
-
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-
|
|
3
|
+
import { L as LocalMetaStorage } from "../../packem_shared/local-meta-storage.d-CobcjyWu.js";
|
|
4
4
|
import { copy, del, list, put } from '@vercel/blob';
|
|
5
5
|
import 'node:crypto';
|
|
6
6
|
import 'node:http';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as r}from"../../packem_shared/VercelBlobFile-Cni_1qwD.js";import{default as a}from"../../packem_shared/VercelBlobMetaStorage-
|
|
1
|
+
import{default as r}from"../../packem_shared/VercelBlobFile-Cni_1qwD.js";import{default as a}from"../../packem_shared/VercelBlobMetaStorage-Bx0l9Xt6.js";import{default as f}from"../../packem_shared/VercelBlobStorage-CGxoGkv4.js";export{r as VercelBlobFile,a as VercelBlobMetaStorage,f as VercelBlobStorage};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { F as File, a as FileReturn, B as BaseStorage } from "../packem_shared/storage.d-
|
|
2
|
-
import { A as AudioTransformerConfig,
|
|
1
|
+
import { F as File, a as FileReturn, B as BaseStorage } from "../packem_shared/storage.d-D5UN5mRz.js";
|
|
2
|
+
import { A as AudioTransformerConfig, a as AudioTransformResult, b as AudioResampleOptions, c as AudioChannelMixOptions, d as AudioTransformOptions, e as AudioTransformationStep, B as BaseTransformer } from "../packem_shared/types.d-BsjUOfBJ.js";
|
|
3
3
|
import 'node:stream';
|
|
4
4
|
import 'node:crypto';
|
|
5
5
|
import 'node:http';
|
|
@@ -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, m as RotateOptions, n as ImageFormat, o as TransformOptions, S as SharpenOptions, p as BlurOptions, q as MedianOptions, r as CLAHEOptions, s as ConvolveOptions, t as ThresholdOptions, u as BooleanOptions, L as LinearOptions, v as RecombineOptions, w as ModulateOptions, x as TintOptions, G as GreyscaleOptions, y as ColourspaceOptions, E as ExtractChannelOptions, J as JoinChannelOptions, z as BandboolOptions, D as AffineOptions, F as DilateOptions, H as ErodeOptions, P as PipelineColourspaceOptions, K as ToColourspaceOptions, N as RemoveAlphaOptions, O as EnsureAlphaOptions, Q 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-D5UN5mRz.js";
|
|
3
|
+
import { I as ImageTransformerConfig, T as TransformResult, R as ResizeOptions, C as CropOptions, m as RotateOptions, n as ImageFormat, o as TransformOptions, S as SharpenOptions, p as BlurOptions, q as MedianOptions, r as CLAHEOptions, s as ConvolveOptions, t as ThresholdOptions, u as BooleanOptions, L as LinearOptions, v as RecombineOptions, w as ModulateOptions, x as TintOptions, G as GreyscaleOptions, y as ColourspaceOptions, E as ExtractChannelOptions, J as JoinChannelOptions, z as BandboolOptions, D as AffineOptions, F as DilateOptions, H as ErodeOptions, P as PipelineColourspaceOptions, K as ToColourspaceOptions, N as RemoveAlphaOptions, O as EnsureAlphaOptions, Q as TransformationStep, B as BaseTransformer } from "../packem_shared/types.d-BsjUOfBJ.js";
|
|
4
4
|
import 'node:crypto';
|
|
5
5
|
import 'node:http';
|
|
6
6
|
import 'lru-cache';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { type
|
|
2
|
-
export { M as MediaTransformer } from "../packem_shared/media-transformer.d-
|
|
3
|
-
import { a as FileReturn } from "../packem_shared/storage.d-
|
|
1
|
+
export { type c as AudioChannelMixOptions, type b as AudioResampleOptions, type d as AudioTransformOptions, type a as AudioTransformResult, type e as AudioTransformationStep, type A as AudioTransformerConfig, B as BaseTransformer, type C as CropOptions, type n as ImageFormat, type I as ImageTransformerConfig, type U as MediaTransformQuery, type l as MediaTransformResult, type W as MediaTransformationStep, type M as MediaTransformerConfig, type R as ResizeOptions, type m as RotateOptions, type o as TransformOptions, type T as TransformResult, type Q as TransformationStep, type h as VideoCropOptions, type g as VideoResizeOptions, type i as VideoRotateOptions, type j as VideoTransformOptions, type f as VideoTransformResult, type k as VideoTransformationStep, type V as VideoTransformerConfig } from "../packem_shared/types.d-BsjUOfBJ.js";
|
|
2
|
+
export { M as MediaTransformer } from "../packem_shared/media-transformer.d-B5cQJz30.js";
|
|
3
|
+
import { a as FileReturn } from "../packem_shared/storage.d-D5UN5mRz.js";
|
|
4
4
|
import 'node:stream';
|
|
5
5
|
import 'node:crypto';
|
|
6
6
|
import 'node:http';
|
|
@@ -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,
|
|
1
|
+
import { F as File, a as FileReturn, B as BaseStorage } from "../packem_shared/storage.d-D5UN5mRz.js";
|
|
2
|
+
import { V as VideoTransformerConfig, f as VideoTransformResult, g as VideoResizeOptions, h as VideoCropOptions, i as VideoRotateOptions, j as VideoTransformOptions, k as VideoTransformationStep, B as BaseTransformer } from "../packem_shared/types.d-BsjUOfBJ.js";
|
|
3
3
|
import 'node:stream';
|
|
4
4
|
import 'node:crypto';
|
|
5
5
|
import 'node:http';
|
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.33",
|
|
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",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./ERRORS-CyOuSMLY.js";import"./MetaStorage-Y4m1dWgd.js";import"./Metadata-B6Ir0KO7.js";import{b as i}from"./azure-meta-storage-C4SrMtT2.js";export{i as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var f=Object.defineProperty;var y=(d,t)=>f(d,"name",{value:t,configurable:!0});import{L as b}from"./path-D7rMc9nq-CPbxyMDy.js";import{d as C}from"./detect-file-type-5JhzC9RU.js";import{throwErrorCode as c,ERRORS as u}from"./ERRORS-CyOuSMLY.js";import{B as w,t as O}from"./storage-uhIhcN-O.js";import{v as T}from"./local-meta-storage-Dr891Iy7.js";import{c as k,b as E,a as p,d as m}from"./azure-meta-storage-C4SrMtT2.js";import S from"./AzureFile-Dgj2Tef4.js";import{r as F}from"./part-match-D_NwyoF3.js";import{o as N}from"./has-content-Bx2p8Okx.js";import{o as v}from"./get-file-status-DLS18Zvd.js";var B=Object.defineProperty,R=y((d,t)=>B(d,"name",{value:t,configurable:!0}),"f");class W extends w{static name="azure";checksumTypes=["md5"];get raw(){return this.client}meta;client;containerClient;root;resolvedRetryConfig;signer;sasToken;anonymous;constructor(t){if(super(t),!t.containerName)throw new Error("Missing required parameter: Azure container name.");const{anonymous:r,client:e,sasToken:n,signer:s}=k(t);this.client=e,this.signer=s,this.sasToken=n,this.anonymous=r,this.containerClient=this.client.getContainerClient(t.containerName),this.root=t.root?b(t.root).replace(/^\//,""):"";const o={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:R(a=>{const i=a;if(i.statusCode&&[408,429,500,502,503,504].includes(i.statusCode))return!0;if(a instanceof Error){const l=i.code;if(l==="ECONNRESET"||l==="ETIMEDOUT"||l==="ENOTFOUND"||l==="ECONNREFUSED")return!0}return!1},"shouldRetry"),...t.retryConfig};if(this.resolvedRetryConfig=o,t.metaStorage)this.meta=t.metaStorage;else{let a={...t,...t.metaStorageConfig,logger:this.logger};if("directory"in a)this.logger?.debug("Using local meta storage"),this.meta=new T(a);else{const i=t.metaStorageConfig;i&&["accountKey","accountName","connectionString","credential","endpoint","sasToken"].some(l=>l in i)||(a={...a,client:this.client}),this.meta=new E(a)}}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(a=>{this.logger?.error("Storage access check failed: %O",a)})}getRetryConfig(){return this.resolvedRetryConfig}async create(t,r){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const i=typeof t.ttl=="string"?O(t.ttl):t.ttl;i!==void 0&&(e.expiredAt=Date.now()+i)}const n=new S(e);n.name=this.namingFunction(n),await this.validate(n);try{const i=await this.getMeta(n.id);if(i.bytesWritten>=0)return i}catch{}const s=this.containerClient.getBlockBlobClient(this.getFullPath(n.name)),o={};for(const[i,l]of Object.entries(n.metadata||{}))o[i]=JSON.stringify(l);const a=await this.runOperation(r,i=>s.uploadData(Buffer.from(""),{abortSignal:i,blobHTTPHeaders:{blobContentType:n.contentType},metadata:{name:n.name,originalName:n.originalName,...o}}));return a.requestId===void 0?c(u.FILE_ERROR,"azure create upload error"):(n.requestId=a.requestId,n.uri=a._response.headers.get("location"),n.bytesWritten=0,await this.saveMeta(n),n.status="created",await this.onCreate(n),n)})}async delete({id:t},r){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await this.runOperation(r,s=>this.containerClient.getBlockBlobClient(this.getFullPath(e.name)).deleteIfExists({abortSignal:s})),await this.deleteMeta(e.id);const n={...e};return await this.onDelete(n),n})}async move(t,r,e){return this.instrumentOperation("move",async()=>{const n=await this.copy(t,r,e),s=this.getFullPath(t);return await this.runOperation(e,o=>this.containerClient.getBlockBlobClient(s).deleteIfExists({abortSignal:o})),n})}async write(t,r){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 c(u.FILE_CONFLICT);const n=await this.lock(t.id);try{if(N(t)){if((e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:i,stream:l}=await C(t.body);i?.mime&&(e.contentType=i.mime),t.body=l}catch{}const s=this.containerClient.getBlockBlobClient(this.getFullPath(e.name)),o=new AbortController;t.body.on("error",()=>{o.abort()});const a=await this.runOperation(r,i=>{const l=i?AbortSignal.any([o.signal,i]):o.signal;return s.uploadStream(t.body,void 0,void 0,{abortSignal:l,blobHTTPHeaders:{blobContentType:e.contentType??"application/octet-stream"},metadata:e.metadata})},{replayable:!1});if(a.requestId===void 0)return c(u.FILE_ERROR,"azure write upload error");e.requestId=a.requestId,e.bytesWritten+=t.contentLength||0,e.status=v(e),e.status==="completed"&&(e.uri=a._response.headers.get("location"),await this.deleteMeta(e.id))}}finally{await this.unlock(t.id,n)}return e})}async get({id:t},r){return this.instrumentOperation("get",async()=>{const e=this.containerClient.getBlockBlobClient(this.getFullPath(t));if(!await this.runOperation(r,h=>e.exists({abortSignal:h})))try{return await this.getMeta(t),c(u.GONE)}catch{return c(u.FILE_NOT_FOUND)}const n=await this.runOperation(r,h=>e.getProperties({abortSignal:h})),{contentLength:s,contentType:o,etag:a,expiresOn:i,lastModified:l,metadata:g}=n;return{content:await this.runOperation(r,h=>e.downloadToBuffer(0,void 0,{abortSignal:h})),contentType:o,ETag:a,expiredAt:i,id:t,metadata:g||{},modifiedAt:l,name:g?.name||t,originalName:g?.originalName||"",size:s}})}async exists({id:t},r){return this.instrumentOperation("exists",async()=>{try{await this.getMeta(t);const e=this.containerClient.getBlockBlobClient(this.getFullPath(t));return await this.runOperation(r,n=>e.exists({abortSignal:n}))}catch{return!1}})}async copy(t,r,e){return this.instrumentOperation("copy",async()=>{const n=this.containerClient.getBlockBlobClient(this.getFullPath(t));if(!await this.runOperation(e,i=>n.exists({abortSignal:i})))try{return await this.getMeta(t),c(u.GONE)}catch{return c(u.FILE_NOT_FOUND)}const s=this.containerClient.getBlockBlobClient(this.getFullPath(r));let o=n.url;this.signer?.kind==="userDelegation"?o=await p(this.containerClient.getBlobClient(this.getFullPath(t)),this.signer,{expiresIn:300,permissions:"r"}):this.sasToken&&(o=m(n.url,this.sasToken));const a=await this.runOperation(e,i=>s.beginCopyFromURL(o,{abortSignal:i}));return await this.runOperation(e,()=>a.pollUntilDone()),{...await this.getMeta(t),id:r,name:r}})}async list(t=1e3,r){return this.instrumentOperation("list",async()=>{const e=[];let n=!0,s;for(;n&&e.length<t;)try{const o=Math.min(t-e.length,1e3),a=(await this.runOperation(r,i=>this.containerClient.listBlobsFlat({abortSignal:i,includeMetadata:!0,prefix:this.root}).byPage({continuationToken:s,maxPageSize:o}).next())).value;if(a!==void 0&&"segment"in a){for(const i of a.segment.blobItems)if(!i.deleted&&(e.push({createdAt:i.properties.createdOn,id:i.name,modifiedAt:i.properties.lastModified}),e.length>=t))break}n=a?.continuationToken!==void 0,n&&(s=a.continuationToken)}catch(o){const a=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(a),o}return e},{limit:t})}async getReadUrl(t,r){const e=this.containerClient.getBlobClient(this.getFullPath(t));return this.signer?p(e,this.signer,{expiresIn:r?.expiresIn??3600,permissions:"r",...r?.responseContentDisposition&&{contentDisposition:r.responseContentDisposition},...r?.responseContentType&&{contentType:r.responseContentType}}):this.sasToken?m(e.url,this.sasToken):this.anonymous?e.url:c(u.METHOD_NOT_ALLOWED,"azure: cannot produce a read URL without a shared key, Microsoft Entra credential, or SAS token. Construct the adapter with accountKey + accountName, a connectionString containing an account key, a credential + accountName, or a sasToken.")}async getUploadUrl(t,r){const e=this.containerClient.getBlobClient(this.getFullPath(t));return this.signer?p(e,this.signer,{expiresIn:r?.expiresIn??3600,permissions:"cw"}):this.sasToken?m(e.url,this.sasToken):c(u.METHOD_NOT_ALLOWED,"azure: cannot produce an upload URL without a shared key, Microsoft Entra credential, or SAS token. Anonymous (public-container) access is read-only.")}getFullPath(t){return this.assetFolder!==void 0?`${this.assetFolder}/${t}`:t}async accessCheck(){await this.runOperation(void 0,t=>this.containerClient.getProperties({abortSignal:t}))}}export{W as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var T=Object.defineProperty;var g=(r,e)=>T(r,"name",{value:e,configurable:!0});import{Readable as b}from"node:stream";import{wrapStorageError as h}from"./ERRORS-CyOuSMLY.js";import{B as E}from"./storage-uhIhcN-O.js";import l from"./BunS3File-D-SRiyrm.js";import O from"./BunS3MetaStorage-BkZx5q4w.js";import{o as f}from"./get-file-status-DLS18Zvd.js";import{u as I}from"./update-size-DANV7aa2.js";import{r as v}from"./part-match-D_NwyoF3.js";import{o as C}from"./has-content-Bx2p8Okx.js";var k=Object.defineProperty,p=g((r,e)=>k(r,"name",{value:e,configurable:!0}),"c");const c=p(r=>r.replace(/^\/+/u,""),"toKey"),z=p(async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},"collectStream"),B=p(r=>{const e=r?.code;return typeof e=="string"&&/nosuchkey|notfound/iu.test(e)},"isNotFoundError"),u=p((r,e)=>{const i=r?.code,t=typeof i=="string"?i:"";return/nosuchkey|notfound/iu.test(t)?h(r,{adapter:"Bun S3",operation:e,status:404}):/accessdenied|forbidden|ERR_S3_INVALID_SIGNATURE|ERR_S3_MISSING_CREDENTIALS/iu.test(t)?h(r,{adapter:"Bun S3",operation:e,status:403}):h(r,{adapter:"Bun S3",operation:e})},"wrapBunS3Error"),M=p(r=>{if(r.client)return r.client;const e=globalThis.Bun;if(!e?.S3Client)throw new Error("BunS3Storage requires the Bun runtime (Bun.S3Client). Run this under Bun, or pass a pre-built `client` instance. For Node/edge runtimes use the `aws` or `aws-light` provider instead.");return new e.S3Client({accessKeyId:r.accessKeyId,acl:r.acl,bucket:r.bucket,endpoint:r.endpoint,region:r.region,secretAccessKey:r.secretAccessKey,sessionToken:r.sessionToken,virtualHostedStyle:r.virtualHostedStyle})},"resolveClient");class W extends E{static name="bun-s3";meta;client;constructor(e){super(e),this.client=M(e),this.meta=e.metaStorage??new O(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new l(e);t.name=this.namingFunction(t),t.bunS3Key=c(t.name),await this.validate(t);try{const n=await this.getMeta(t.id);if(n.bytesWritten>=0)return n}catch{}return t.bytesWritten=0,t.status=f(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&I(t,e.size),!v(e,t))throw new Error("File part does not match");const n=await this.lock(e.id);try{if(C(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const s=await z(e.body),a=c(t.name||t.id);try{await this.runOperation(i,()=>this.client.write(a,s,{type:t.contentType}))}catch(o){throw u(o,"upload")}t.bytesWritten=s.length,t.size=s.length,t.bunS3Key=a}return t.status=f(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,n)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const n=t?.bunS3Key??c(t?.name??e);try{await this.runOperation(i,()=>this.client.delete(n))}catch(a){if(!B(a))throw u(a,"delete")}if(t)return t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t;const s=new l({contentType:"application/octet-stream",metadata:{},originalName:e});return s.id=e,s.name=e,s.bunS3Key=n,s.status="deleted",s})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,n;try{t=await this.checkIfExpired(await this.getMeta(e)),n=t.bunS3Key??c(t.name??e)}catch{n=c(e)}const s=this.client.file(n);let a,o;try{t||(o=await this.runOperation(i,()=>s.stat())),a=Buffer.from(await this.runOperation(i,()=>s.arrayBuffer()))}catch(d){throw u(d,"get")}return{content:a,contentType:t?.contentType??o?.type??"application/octet-stream",ETag:t?.ETag??o?.etag??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??o?.lastModified?.toISOString(),name:t?.name??n,originalName:t?.originalName??n,size:t?.size??o?.size??a.length}})}async getStream({id:e},i){return this.instrumentOperation("getStream",async()=>{let t,n;try{t=await this.checkIfExpired(await this.getMeta(e)),n=t.bunS3Key??c(t.name??e)}catch{n=c(e)}const s=this.client.file(n);let a,o;try{a=await this.runOperation(i,()=>s.stat()),o=s.stream()}catch(S){throw u(S,"getStream")}const d=t?.size??a.size,w=t?.contentType??a.type??"application/octet-stream",m=t?.ETag??a.etag,y=t?.modifiedAt??a.lastModified?.toISOString();return{headers:{"Content-Length":String(d??0),"Content-Type":w,...m&&{ETag:m},...y&&{"Last-Modified":String(y)}},size:typeof d=="number"?d:void 0,stream:b.fromWeb(o)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const n=await this.get({id:e},t),s=c(i);try{await this.runOperation(t,()=>this.client.write(s,n.content,{type:n.contentType}))}catch(o){throw u(o,"copy")}const a=new l({contentType:n.contentType,metadata:{},originalName:i});return a.id=i,a.name=i,a.bunS3Key=s,a.size=typeof n.size=="string"?Number(n.size):n.size??n.content.length,a.ETag=n.ETag,a.bunS3ETag=n.ETag,a})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const n=await this.copy(e,i,t);return await this.delete({id:e},t),n})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{let t;try{t=await this.runOperation(i,()=>this.client.list({maxKeys:e}))}catch(n){throw u(n,"list")}return(t.contents??[]).filter(n=>!!n.key).slice(0,e).map(n=>{const s=c(n.key),a=new l({contentType:"application/octet-stream",metadata:{},originalName:s});return a.id=s,a.name=s,a.bunS3Key=s,a.size=n.size,a.ETag=n.eTag??void 0,a.bunS3ETag=n.eTag??void 0,a.modifiedAt=n.lastModified?new Date(n.lastModified).toISOString():void 0,a})},{limit:e})}async getReadUrl(e,i){return this.client.file(c(e)).presign({...i?.responseContentDisposition&&{contentDisposition:i.responseContentDisposition},...i?.expiresIn!==void 0&&{expiresIn:i.expiresIn},method:"GET",...i?.responseContentType&&{type:i.responseContentType}})}async getUploadUrl(e,i){return this.client.presign(c(e),{...i?.expiresIn!==void 0&&{expiresIn:i.expiresIn},method:"PUT",...i?.contentType&&{type:i.contentType}})}internalOnComplete=p(e=>this.deleteMeta(e.id),"internalOnComplete")}export{W as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var N=Object.defineProperty;var f=(n,t)=>N(n,"name",{value:t,configurable:!0});import*as u from"@bunny.net/storage-sdk";import{throwErrorCode as y,ERRORS as g,wrapStorageError as m}from"./ERRORS-CyOuSMLY.js";import{B}from"./storage-uhIhcN-O.js";import d from"./BunnyFile-Dotl-lO9.js";import b from"./BunnyMetaStorage-bB8NXGUI.js";import{o as E}from"./get-file-status-DLS18Zvd.js";import{u as A}from"./update-size-DANV7aa2.js";import{r as _}from"./part-match-D_NwyoF3.js";import{o as R}from"./has-content-Bx2p8Okx.js";var U=Object.defineProperty,c=f((n,t)=>U(n,"name",{value:t,configurable:!0}),"u");const O=new Set(Object.values(u.regions.StorageRegion)),h=c(n=>`/${n.replace(/^\/+/u,"")}`,"toBunnyPath"),w=c(n=>n.replace(/^\/+/u,""),"fromBunnyPath"),C=c((n,t)=>{const r=n.replace(/\/+$/u,""),e=t.replace(/^\/+/u,"");return`${r}/${e}`},"joinPublicUrl"),v=c(async n=>{const t=[];for await(const r of n)t.push(Buffer.from(r));return Buffer.concat(t)},"collectStream"),S=c(n=>new ReadableStream({start(t){t.enqueue(new Uint8Array(n)),t.close()}}),"streamFromBuffer"),z=c(n=>{if(n){if(!O.has(n))throw new Error(`Bunny Storage: unsupported region "${n}". Pass one of ${[...O].join(", ")}.`);return n}},"parseRegion"),P=c(n=>{if(n.client)return n.client;const t=n.zone??process.env.BUNNY_STORAGE_ZONE??process.env.STORAGE_ZONE,r=n.accessKey??process.env.BUNNY_STORAGE_ACCESS_KEY??process.env.BUNNY_ACCESS_KEY??process.env.STORAGE_ACCESS_KEY,e=z(n.region??process.env.BUNNY_STORAGE_REGION??process.env.STORAGE_REGION);if(!t||!r||!e)throw new Error("Bunny Storage: missing credentials. Pass `zone` + `accessKey` + `region`, or set BUNNY_STORAGE_ZONE / BUNNY_STORAGE_ACCESS_KEY / BUNNY_STORAGE_REGION (SDK aliases: STORAGE_ZONE / STORAGE_ACCESS_KEY / STORAGE_REGION).");return u.zone.connect_with_accesskey(e,t,r)},"resolveClient"),k=c(async n=>Buffer.from(await new Response(n).arrayBuffer()),"collectFromWebStream"),p=c((n,t)=>{const r=n?.message,e=typeof r=="string"?r:"";return/^file not found/iu.test(e)?m(n,{adapter:"Bunny Storage",operation:t,status:404}):/^unauthorized access/iu.test(e)?m(n,{adapter:"Bunny Storage",operation:t,status:401}):/^unable to upload file/iu.test(e)?m(n,{adapter:"Bunny Storage",operation:t,status:400}):m(n,{adapter:"Bunny Storage",operation:t})},"wrapBunnyError");class W extends B{static name="bunny";checksumTypes=["SHA256"];meta;client;publicBaseUrl;zoneName;constructor(t){super(t),this.client=P(t),this.zoneName=u.zone.name(this.client),this.publicBaseUrl=t.publicBaseUrl,this.meta=t.metaStorage??new b(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}get zone(){return this.zoneName}async create(t,r){return this.instrumentOperation("create",async()=>{const e=new d(t);e.name=this.namingFunction(e),e.bunnyPath=h(e.name),await this.validate(e);try{const a=await this.getMeta(e.id);if(a.bytesWritten>=0)return a}catch{}return e.bytesWritten=0,e.status=E(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,r){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&A(e,t.size),!_(t,e))throw new Error("File part does not match");const a=await this.lock(t.id);try{if(R(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await v(t.body),o=h(e.name||e.id);try{await this.runOperation(r,()=>u.file.upload(this.client,o,S(i),{contentType:e.contentType,...t.checksum&&t.checksumAlgorithm==="sha256"&&{sha256Checksum:t.checksum}}))}catch(s){throw p(s,"upload")}e.bytesWritten=i.length,e.size=i.length,e.bunnyPath=o}return e.status=E(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,a)}})}async delete({id:t},r){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const a=e?.bunnyPath??h(e?.name??t);try{await this.runOperation(r,()=>u.file.remove(this.client,a))}catch(o){throw p(o,"delete")}if(e)return e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e;const i=new d({contentType:"application/octet-stream",metadata:{},originalName:t});return i.id=t,i.name=t,i.bunnyPath=a,i.status="deleted",i})}async get({id:t},r){return this.instrumentOperation("get",async()=>{let e,a;try{e=await this.checkIfExpired(await this.getMeta(t)),a=e.bunnyPath??h(e.name??t)}catch{a=h(t)}let i;try{i=await this.runOperation(r,()=>u.file.get(this.client,a))}catch(s){throw p(s,"get")}let o;try{const s=await this.runOperation(r,()=>i.data());o=await k(s.stream)}catch(s){throw p(s,"download")}return{content:o,contentType:e?.contentType??i.contentType??"application/octet-stream",ETag:e?.ETag??i.checksum??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??i.lastChanged?.toISOString(),name:e?.name??w(a),originalName:e?.originalName??w(a),size:e?.size??i.length??o.length}})}async copy(t,r,e){return this.instrumentOperation("copy",async()=>{const a=await this.get({id:t},e),i=h(r),o=a.content,s=typeof a.size=="string"?Number(a.size):a.size??o.length;try{await this.runOperation(e,()=>u.file.upload(this.client,i,S(o),{contentType:a.contentType}))}catch(T){throw p(T,"copy")}const l=new d({contentType:a.contentType,metadata:{},originalName:r});return l.id=r,l.name=r,l.bunnyPath=i,l.size=s,l.ETag=a.ETag,l.bunnyChecksum=a.ETag,l})}async move(t,r,e){return this.instrumentOperation("move",async()=>{const a=await this.copy(t,r,e);return await this.delete({id:t},e),a})}async list(t=1e3,r){return this.instrumentOperation("list",async()=>{let e;try{e=await this.runOperation(r,()=>u.file.list(this.client,"/"))}catch(a){throw p(a,"list")}return e.filter(a=>!a.isDirectory).slice(0,t).map(a=>{const i=a.path.endsWith(a.objectName)||!a.objectName?a.path:`${a.path.replace(/\/+$/u,"")}/${a.objectName}`,o=w(i),s=new d({contentType:a.contentType||"application/octet-stream",metadata:{},originalName:o});return s.id=o,s.name=o,s.bunnyPath=h(o),s.bunnyChecksum=a.checksum??void 0,s.ETag=a.checksum??void 0,s.size=a.length,s.modifiedAt=a.lastChanged?.toISOString(),s})},{limit:t})}async getReadUrl(t,r){return r?.responseContentDisposition?y(g.METHOD_NOT_ALLOWED,"Bunny Storage: `responseContentDisposition` is not supported — no override exists on Bunny Storage / Pull Zone URLs."):this.publicBaseUrl?C(this.publicBaseUrl,t):y(g.METHOD_NOT_ALLOWED,"Bunny Storage: `getReadUrl` requires `publicBaseUrl` (for example a Bunny Pull Zone or custom CDN hostname). The Storage API URL itself requires an AccessKey header and cannot be handed out as a public URL.")}async getUploadUrl(t,r){return y(g.METHOD_NOT_ALLOWED,"Bunny Storage: presigned PUT URLs are not supported — writes go through the Storage API with an AccessKey header. Upload server-side via the SDK or proxy through your application.")}internalOnComplete=c(t=>this.deleteMeta(t.id),"internalOnComplete")}export{W as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var c=Object.defineProperty;var i=(e,r)=>c(e,"name",{value:r,configurable:!0});var p=Object.defineProperty,a=i((e,r)=>p(e,"name",{value:r,configurable:!0}),"i"),u=(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))(u||{});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"]},r={};return Object.keys(e).forEach(t=>{const[o,s]=e[t];r[t]={code:t,message:s,statusCode:o}}),r})();class l extends Error{static{i(this,"UploadError")}static{a(this,"UploadError")}name="UploadError";UploadErrorCode="UnknownError";detail;constructor(r="UnknownError",t,o){super(t||r),this.name="UploadError",this.detail=o,Object.values(u).includes(r)&&(this.UploadErrorCode=r)}}const R=a(e=>!!e.UploadErrorCode,"isUploadError"),g=a(e=>{if(!e||typeof e!="object")return;const r=e;if(typeof r.status=="number")return r.status;if(typeof r.statusCode=="number")return r.statusCode;if(typeof r.code=="number")return r.code;const t=r.response;if(typeof t?.status=="number")return t.status;if(typeof t?.statusCode=="number")return t.statusCode},"extractHttpStatus"),U=a(e=>{if(e===void 0)return"StorageError";switch(e){case 400:return"BadRequest";case 401:case 403:return"Forbidden";case 404:return"FileNotFound";case 405:return"MethodNotAllowed";case 409:return"FileConflict";case 410:return"Gone";case 413:return"RequestEntityTooLarge";case 415:return"UnsupportedMediaType";case 422:return"UnprocessableEntity";case 423:return"FileLocked";case 429:return"TooManyRequests";case 503:return"StorageBusy";default:return e>=500&&e<600?"StorageError":e>=400&&e<500?"BadRequest":"UnknownError"}},"mapStatusToErrorCode"),m=a((e,r,t,o)=>{const s=`${e}: ${r} failed`;return t?`${s} — ${t}`:o!==void 0?`${s} (HTTP ${o})`:s},"composeWrappedMessage"),y=a((e,r)=>{if(R(e))return e;const t=r.status??g(e),o=r.code??U(t),s=e?.message,n=typeof s=="string"&&s.length>0?s:void 0,E=r.message??m(r.adapter,r.operation,n,t);return new l(o,E,e)},"wrapStorageError"),F=a((e,r)=>{const t=e;let o;t&&typeof t=="string"&&t in d&&(o=d[t]);const s=r||(o?.body&&typeof o.body=="object"&&"message"in o.body?o.body.message:void 0)||o?.message||"UnknownError",n=new l(t,s);throw n.UploadErrorCode=t,typeof r=="string"&&(n.detail=r),n},"throwErrorCode");export{u as ERRORS,d as ErrorMap,l as UploadError,g as extractHttpStatus,R as isUploadError,U as mapStatusToErrorCode,F as throwErrorCode,y as wrapStorageError};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var K=Object.defineProperty;var T=(s,t)=>K(s,"name",{value:t,configurable:!0});import{PassThrough as R,Readable as A}from"node:stream";import{B as O}from"./storage-uhIhcN-O.js";var H=Object.defineProperty,k=T((s,t)=>H(s,"name",{value:t,configurable:!0}),"h");const z=8,L=k(s=>typeof s=="object"&&s!==null&&typeof s.getReader=="function","isWebReadableStream"),C=k(s=>typeof s=="object"&&s!==null&&typeof s.pipe=="function"&&typeof s.read=="function","isNodeReadable"),j=k(async(s,t)=>{if(typeof s=="string"){const e=Buffer.from(s);return{size:e.byteLength,stream:A.from(e)}}if(Buffer.isBuffer(s))return{size:s.byteLength,stream:A.from(s)};if(s instanceof Uint8Array){const e=Buffer.from(s.buffer,s.byteOffset,s.byteLength);return{size:e.byteLength,stream:A.from(e)}}if(s instanceof ArrayBuffer){const e=Buffer.from(s);return{size:e.byteLength,stream:A.from(e)}}if(ArrayBuffer.isView(s)){const e=s,r=Buffer.from(e.buffer,e.byteOffset,e.byteLength);return{size:r.byteLength,stream:A.from(r)}}if(typeof Blob<"u"&&s instanceof Blob)return{size:s.size,stream:A.fromWeb(s.stream())};if(L(s))return{size:t,stream:A.fromWeb(s)};if(C(s))return{size:t,stream:s};throw new TypeError(`Unsupported body type: ${Object.prototype.toString.call(s)}`)},"normalizeBody"),M=k((s,t)=>({contentType:s.contentType??"application/octet-stream",etag:s.ETag,key:s.name||s.id||t||"",lastModified:s.modifiedAt??s.createdAt,metadata:s.metadata,size:typeof s.size=="number"?s.size:void 0}),"toFileObject"),F=k(s=>s?s.split("/").filter(t=>t.length>0).join("/"):"","normalizePrefix"),W=k((s,t)=>{if(!t&&!s.signal&&s.timeout===void 0&&s.retries===void 0)return;const e={...s};return t&&(t.signal!==void 0&&(e.signal=t.signal),t.timeout!==void 0&&(e.timeout=t.timeout),t.retries!==void 0&&(e.retries=t.retries)),s.signal&&t?.signal&&(e.signal=AbortSignal.any([s.signal,t.signal])),e},"mergeOperationOptions"),P=k(async(s,t,e)=>{const r=Array.from({length:s.length});let n=0,a=!1;const l=k(async()=>{for(;n<s.length;){if(a||e.signal?.aborted)return;const o=n;n+=1;try{const i=await t(s[o],o);r[o]={status:"fulfilled",value:i}}catch(i){r[o]={reason:i,status:"rejected"},e.stopOnError&&(a=!0)}}},"worker"),p=Math.max(1,Math.min(e.concurrency,s.length)),c=Array.from({length:p},()=>l());return await Promise.all(c),r},"runConcurrent"),w=k((s,t)=>t instanceof Error?{error:t,key:s}:{error:new Error(typeof t=="string"?t:"Unknown error",{cause:t}),key:s},"toBulkError"),I=k((s,t)=>{if(s)try{s(t)}catch{}},"safeInvoke");class V{static{T(this,"Files")}static{k(this,"Files")}adapter;defaults;hooks;prefix;constructor(t){this.adapter=t.adapter,this.defaults=t.defaults??{},this.hooks=t.hooks??{},this.prefix=F(t.prefix??"")}get raw(){return this.adapter.raw}resolveKey(t){return this.prefix?`${this.prefix}/${t}`:t}stripPrefix(t){const e=t.startsWith("/")?t.slice(1):t;if(!this.prefix)return e;const r=`${this.prefix}/`;return e.startsWith(r)?e.slice(r.length):null}mergeOptions(t,e){const r=W(this.defaults,t);if(!e||!this.hooks.onRetry)return r;const n=r?.retries,a=typeof n=="number"?{maxRetries:n}:{...n??{}},l=a.onRetry,p=this.hooks.onRetry;return a.onRetry=(c,o)=>{if(l)try{l(c,o)}catch{}try{const i=o instanceof Error?o:new Error(typeof o=="string"?o:"Unknown error",{cause:o});p({...e,attempt:c,error:i})}catch{}},{...r??{},retries:a}}emitAction(t,e){if(this.hooks.onAction)try{this.hooks.onAction({type:t,...e})}catch{}}emitError(t,e,r){if(this.hooks.onError)try{this.hooks.onError({error:r,type:t,...e})}catch{}}async withHooks(t,e,r){const n=Date.now();try{const a=await r();return this.emitAction(t,{...e,durationMs:Date.now()-n}),a}catch(a){const l=a instanceof Error?a:new Error(typeof a=="string"?a:"Unknown error",{cause:a});throw this.emitError(t,{...e,durationMs:Date.now()-n},l),l}}async upload(t,e,r){return Array.isArray(t)?this.uploadMany(t,e):this.uploadOne(t,e,r)}async uploadOne(t,e,r){return this.withHooks("upload",{key:t},async()=>{const n=this.resolveKey(t);O.assertSafeId(n);const{size:a,stream:l}=await j(e,r?.size),p=r?.size??a,c={...r?.metadata??{},name:n,...r?.contentType?{type:r.contentType}:{},...p===void 0?{}:{size:p}},o=this.mergeOptions(r,{key:t,type:"upload"}),i=r?.multipart,y=await this.adapter.create({contentType:r?.contentType,id:n,metadata:c,originalName:n,size:p,storageClass:r?.storageClass},o),d=this.adapter.reportsUploadProgress,f=!!r?.onProgress;let h=l;if(f&&!d){const x=r?.onProgress;let S=0;const u=new R;p!==void 0&&I(x,{loaded:0,total:p}),l.on("data",B=>{const E=typeof B=="string"?Buffer.byteLength(B):B.byteLength;S+=E,I(x,{loaded:S,total:p})}),l.pipe(u),h=u}const g={body:h,contentLength:p,id:y.id,start:0,...i!==void 0&&{multipart:i},...d&&f&&{onProgress:r?.onProgress}},b=await this.adapter.write(g,o),m=M(b,n),v=this.stripPrefix(m.key);return v!==null&&(m.key=v),m})}async uploadMany(t,e){const{concurrency:r=z,multipart:n,onProgress:a,stopOnError:l=!1,...p}=e??{},c=await P(t,async({body:y,key:d,...f})=>{const h=f.onProgress??(a?g=>a({...g,key:d}):void 0);return this.uploadOne(d,y,{...p,multipart:n,...f,...h&&{onProgress:h}})},{concurrency:r,signal:p.signal,stopOnError:l}),o=[],i=[];for(const[y,d]of c.entries()){const f=t[y];if(!d){i.push(w(f.key,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?o.push(d.value):i.push(w(f.key,d.reason))}return i.length>0?{errors:i,uploaded:o}:{uploaded:o}}async download(t,e){return Array.isArray(t)?this.downloadMany(t,e):this.downloadOne(t,e)}assertRangeSupported(t){if(t){if(!Number.isFinite(t.start)||t.start<0)throw new TypeError(`Invalid range.start: ${String(t.start)}`);if(t.end!==void 0&&(!Number.isFinite(t.end)||t.end<t.start))throw new TypeError(`Invalid range.end: ${String(t.end)}`);if(!this.adapter.supportsRange)throw new Error(`Adapter ${this.adapter.constructor.name} does not support range downloads`)}}async downloadOne(t,e){return this.withHooks("download",{key:t},async()=>{const r=this.resolveKey(t);O.assertSafeId(r),this.assertRangeSupported(e?.range);const n=this.mergeOptions(e,{key:t,type:"download"})??{},a=e?.range?{...n,range:e.range}:n,l=await this.adapter.get({id:r},a);return{body:l.content,contentType:l.contentType??"application/octet-stream",etag:l.ETag,key:t,lastModified:l.modifiedAt,metadata:l.metadata,size:typeof l.size=="number"?l.size:void 0}})}async downloadMany(t,e){const{concurrency:r=z,range:n,stopOnError:a=!1,...l}=e??{},p=await P(t,async i=>this.downloadOne(i,n?{...l,range:n}:l),{concurrency:r,signal:l.signal,stopOnError:a}),c=[],o=[];for(const[i,y]of p.entries()){const d=t[i];if(!y){o.push(w(d,new Error("Operation skipped (stopOnError)")));continue}y.status==="fulfilled"?c.push(y.value):o.push(w(d,y.reason))}return o.length>0?{downloaded:c,errors:o}:{downloaded:c}}async head(t,e){return Array.isArray(t)?this.headMany(t,e):this.headOne(t,e)}async headOne(t,e){return this.withHooks("head",{key:t},async()=>{const r=this.resolveKey(t);O.assertSafeId(r);const n=await this.adapter.getMeta(r,this.mergeOptions(e,{key:t,type:"head"})),a=M(n,r);return a.key=t,a})}async headMany(t,e){const{concurrency:r=z,stopOnError:n=!1,...a}=e??{},l=await P(t,async o=>this.headOne(o,a),{concurrency:r,signal:a.signal,stopOnError:n}),p=[],c=[];for(const[o,i]of l.entries()){const y=t[o];if(!i){c.push(w(y,new Error("Operation skipped (stopOnError)")));continue}i.status==="fulfilled"?p.push(i.value):c.push(w(y,i.reason))}return c.length>0?{errors:c,files:p}:{files:p}}async exists(t,e){return Array.isArray(t)?this.existsMany(t,e):this.existsOne(t,e)}async existsOne(t,e){return this.withHooks("exists",{key:t},async()=>{const r=this.resolveKey(t);return O.assertSafeId(r),this.adapter.exists({id:r},this.mergeOptions(e,{key:t,type:"exists"}))})}async existsMany(t,e){const{concurrency:r=z,stopOnError:n=!1,...a}=e??{},l=await P(t,async i=>this.existsOne(i,a),{concurrency:r,signal:a.signal,stopOnError:n}),p=[],c=[],o=[];for(const[i,y]of l.entries()){const d=t[i];if(!y){o.push(w(d,new Error("Operation skipped (stopOnError)")));continue}y.status==="fulfilled"?y.value?p.push(d):c.push(d):o.push(w(d,y.reason))}return o.length>0?{errors:o,existing:p,missing:c}:{existing:p,missing:c}}async delete(t,e){if(Array.isArray(t))return this.deleteMany(t,e);await this.deleteOne(t,e)}async deleteOne(t,e){await this.withHooks("delete",{key:t},async()=>{const r=this.resolveKey(t);O.assertSafeId(r),await this.adapter.delete({id:r},this.mergeOptions(e,{key:t,type:"delete"}))})}async deleteMany(t,e){const{concurrency:r=z,stopOnError:n=!1,...a}=e??{},l=this.mergeOptions(a,{keys:t,type:"delete"});if(!n&&typeof this.adapter.deleteBatch=="function"){const i=[],y=[],d=[];for(const f of t){const h=this.resolveKey(f);try{O.assertSafeId(h),i.push(f),y.push(h)}catch(g){d.push(w(f,g))}}return this.withHooks("delete",{keys:i},async()=>{const f=y.length>0?await this.adapter.deleteBatch(y,l):{failed:[],successful:[]},h=new Map(y.map((m,v)=>[m,v])),g=f.successful.map(m=>this.stripPrefix(m.id)??m.id),b=[...d,...f.failed.map(({error:m,id:v})=>{const x=h.get(v),S=x===void 0?v:i[x];return w(S,new Error(m))})];return b.length>0?{deleted:g,errors:b}:{deleted:g}})}const p=await P(t,async i=>this.deleteOne(i,a),{concurrency:r,signal:a.signal,stopOnError:n}),c=[],o=[];for(const[i,y]of p.entries()){const d=t[i];if(!y){o.push(w(d,new Error("Operation skipped (stopOnError)")));continue}y.status==="fulfilled"?c.push(d):o.push(w(d,y.reason))}return o.length>0?{deleted:c,errors:o}:{deleted:c}}async copy(t,e,r){return this.withHooks("copy",{from:t,to:e},async()=>{const n=this.resolveKey(t),a=this.resolveKey(e);O.assertSafeId(n),O.assertSafeId(a);const l=await this.adapter.copy(n,a,{...this.mergeOptions(r,{from:t,to:e,type:"copy"}),storageClass:r?.storageClass}),p=M(l,a);return p.key=e,p})}async move(t,e,r){return Array.isArray(t)?this.moveMany(t,e):this.moveOne(t,e,r)}async moveOne(t,e,r){return this.withHooks("move",{from:t,to:e},async()=>{const n=this.resolveKey(t);if(O.assertSafeId(n),t===e){const o=await this.adapter.getMeta(n,this.mergeOptions(r,{from:t,to:e,type:"move"})),i=M(o,n);return i.key=t,i}const a=this.resolveKey(e);O.assertSafeId(a);const l={...this.mergeOptions(r,{from:t,to:e,type:"move"}),...r?.storageClass!==void 0&&{storageClass:r.storageClass}},p=await this.adapter.move(n,a,l),c=M(p,a);return c.key=e,c})}async moveMany(t,e){const{concurrency:r=z,stopOnError:n=!1,...a}=e??{},l=await P(t,async({from:o,to:i})=>this.moveOne(o,i,a),{concurrency:r,signal:a.signal,stopOnError:n}),p=[],c=[];for(const[o,i]of l.entries()){const y=t[o];if(!i){c.push(w(y.from,new Error("Operation skipped (stopOnError)")));continue}i.status==="fulfilled"?p.push(i.value):c.push(w(y.from,i.reason))}return c.length>0?{errors:c,moved:p}:{moved:p}}async list(t={}){return this.withHooks("list",{},async()=>{const{limit:e,prefix:r,...n}=t,a=await this.adapter.list(e??1e3,this.mergeOptions(n,{type:"list"})),l=[];for(const p of a){const c=M(p),o=this.stripPrefix(c.key);o!==null&&(c.key=o,l.push(c))}return r?l.filter(p=>p.key.startsWith(r)):l})}async*listAll(t={}){const{limit:e,prefix:r,...n}=t,a=Math.max(1,e??1e3),l=Date.now(),p=new Set;let c;try{for(;;){const o=await this.adapter.list(a,this.mergeOptions(n,{type:"listAll"}));let i=0;for(const y of o){const d=M(y),f=this.stripPrefix(d.key);f!==null&&(d.key=f,!(r&&!d.key.startsWith(r))&&(p.has(d.key)||(p.add(d.key),i+=1,yield d)))}if(i===0||o.length<a)break}}catch(o){throw c=o instanceof Error?o:new Error(typeof o=="string"?o:"Unknown error",{cause:o}),c}finally{const o=Date.now()-l;c?this.emitError("listAll",{durationMs:o},c):this.emitAction("listAll",{durationMs:o})}}async url(t,e){return this.withHooks("url",{key:t},async()=>{const r=this.resolveKey(t);return O.assertSafeId(r),this.adapter.getReadUrl(r,{...this.mergeOptions(e,{key:t,type:"url"}),...e})})}async signedUploadUrl(t,e){return this.withHooks("signedUploadUrl",{key:t},async()=>{const r=this.resolveKey(t);return O.assertSafeId(r),this.adapter.getUploadUrl(r,{...this.mergeOptions(e,{key:t,type:"signedUploadUrl"}),...e})})}}const q=k(async(s,t,e={})=>{const{concurrency:r=z,limit:n,onProgress:a,overwrite:l=!1,prefix:p,signal:c,stopOnError:o=!1,transformKey:i}=e,y=[],d=[],f=[];let h=!1,g=0;const b=k(u=>{if(a)try{a(u)}catch{}},"emit"),m=s.listAll({...p!==void 0&&{prefix:p},...n!==void 0&&{limit:n}}),v=k(async u=>{if(h||c?.aborted)return;const B=i?i(u):u;try{if(!l&&await t.exists(B,{signal:c})){d.push(u),g+=1,b({done:g,key:u,status:"skipped"});return}const E=await s.download(u,{signal:c});await t.upload(B,E.body,{...E.contentType&&{contentType:E.contentType},...E.metadata&&{metadata:E.metadata},signal:c}),y.push(u),g+=1,b({done:g,key:u,status:"transferred"})}catch(E){const U=w(u,E);if(f.push(U),g+=1,b({done:g,error:U.error,key:u,status:"errored"}),o)throw h=!0,U.error}},"transferOne");if(o){try{for await(const u of m){if(h||c?.aborted)break;try{await v(u.key)}catch{break}}}finally{await m.return?.()}return f.length>0?{errors:f,skipped:d,transferred:y}:{skipped:d,transferred:y}}const x=Math.max(1,r),S=k(async()=>{for(;!h&&!c?.aborted;){const u=await m.next();if(u.done)return;await v(u.value.key)}},"worker");try{await Promise.all(Array.from({length:x},()=>S()))}finally{await m.return?.()}return f.length>0?{errors:f,skipped:d,transferred:y}:{skipped:d,transferred:y}},"transfer");export{V as Files,V as default,q as transfer};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var g=Object.defineProperty;var m=(s,t)=>g(s,"name",{value:t,configurable:!0});import{readFileSync as w}from"node:fs";import{getApps as b,getApp as h,initializeApp as O,cert as k}from"firebase-admin/app";import{getStorage as A}from"firebase-admin/storage";import{throwErrorCode as d,ERRORS as f}from"./ERRORS-CyOuSMLY.js";import{B as T}from"./storage-uhIhcN-O.js";import o from"./FirebaseFile-JEu3plMP.js";import I from"./FirebaseMetaStorage-CshnJMb0.js";import{o as y}from"./get-file-status-DLS18Zvd.js";import{u as v}from"./update-size-DANV7aa2.js";import{r as S}from"./part-match-D_NwyoF3.js";import{o as _}from"./has-content-Bx2p8Okx.js";var N=Object.defineProperty,u=m((s,t)=>N(s,"name",{value:t,configurable:!0}),"l");const U=3600,R=u(async s=>{const t=[];for await(const i of s)t.push(Buffer.from(i));return Buffer.concat(t)},"collectStream"),B=u(s=>typeof s=="object"&&s!==null&&typeof s.file=="function"&&typeof s.getFiles=="function","isBucket");class E extends T{static name="firebase";checksumTypes=[];meta;bucket;bucketName;defaultUrlExpiresIn;publicBaseUrl;constructor(t){if(super(t),this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??U,this.publicBaseUrl=t.publicBaseUrl?.replace(/\/+$/,""),t.app&&B(t.app))this.bucket=t.app,this.bucketName=t.app.name??"";else{const i=t.bucket??process.env.FIREBASE_STORAGE_BUCKET;if(!i)throw new Error("Firebase storage: `bucket` is required (or set FIREBASE_STORAGE_BUCKET).");this.bucketName=i;const e=t.app??E.resolveApp(t,i);this.bucket=A(e).bucket(i)}this.meta=t.metaStorage??new I(t.metaStorageConfig),this.isReady=!0}get raw(){return this.bucket}async create(t,i){return this.instrumentOperation("create",async()=>{const e=new o(t);e.name=this.namingFunction(e),e.bucket=this.bucketName,e.path=e.name,await this.validate(e);try{const a=await this.getMeta(e.id);if(a.bytesWritten>=0)return a}catch{}return e.bytesWritten=0,e.status=y(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,i){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&v(e,t.size),!S(t,e))throw new Error("File part does not match");const a=await this.lock(t.id);try{if(_(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await R(t.body),c=e.path??e.name;await this.runOperation(i,()=>this.bucket.file(c).save(r,{contentType:e.contentType,resumable:!1})),e.bytesWritten=r.length,e.size=r.length,e.path=c}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,a)}})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const a=e?.path??e?.name??t;return await this.runOperation(i,()=>this.bucket.file(a).delete({ignoreNotFound:!0})),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new o({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.bucketName,id:t,name:t,path:a,status:"deleted"})})}async exists({id:t},i){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}try{const[a]=await this.runOperation(i,()=>this.bucket.file(e).exists());return a}catch{return!1}})}async get({id:t},i){return this.instrumentOperation("get",async()=>{let e=t,a;try{a=await this.checkIfExpired(await this.getMeta(t)),e=a.path??a.name??t}catch{}const r=this.bucket.file(e),[c]=await this.runOperation(i,()=>r.download());let n={};try{[n]=await this.runOperation(i,()=>r.getMetadata())}catch{}return{content:c,contentType:a?.contentType??n.contentType??"application/octet-stream",ETag:a?.ETag??n.etag,expiredAt:a?.expiredAt,id:t,metadata:a?.metadata??{},modifiedAt:a?.modifiedAt??n.updated,name:a?.name??e,originalName:a?.originalName??e,size:a?.size??(n.size===void 0?c.length:Number(n.size))}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const a=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(a).copy(this.bucket.file(i)));const r=new o({contentType:"application/octet-stream",metadata:{},originalName:i});return r.id=i,r.name=i,r.path=i,r.bucket=this.bucketName,r})}async move(t,i,e){return this.instrumentOperation("move",async()=>{const a=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(a).move(i));const r=new o({contentType:"application/octet-stream",metadata:{},originalName:i});r.id=i,r.name=i,r.path=i,r.bucket=this.bucketName;try{await this.deleteMeta(t)}catch{}return r})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const[e]=await this.runOperation(i,()=>this.bucket.getFiles({maxResults:t}));return(e??[]).map(a=>{const r=new o({contentType:"application/octet-stream",metadata:{},originalName:a.name});return r.id=a.name,r.name=a.name,r.path=a.name,r.bucket=this.bucketName,r})},{limit:t})}async getReadUrl(t,i){if(this.publicBaseUrl)return`${this.publicBaseUrl}/${t}`;const e=i?.expiresIn??this.defaultUrlExpiresIn;try{const[a]=await this.bucket.file(t).getSignedUrl({action:"read",expires:Date.now()+e*1e3});return a}catch(a){return d(f.METHOD_NOT_ALLOWED,a instanceof Error?a.message:"Firebase: getSignedUrl failed")}}async getUploadUrl(t,i){const e=i?.expiresIn??this.defaultUrlExpiresIn;try{const[a]=await this.bucket.file(t).getSignedUrl({action:"write",contentType:i?.contentType,expires:Date.now()+e*1e3});return a}catch(a){return d(f.METHOD_NOT_ALLOWED,a instanceof Error?a.message:"Firebase: getSignedUrl failed")}}static resolveApp(t,i){const{appName:e}=t,a=b();if(e?a.find(p=>p.name===e):a[0])return e?h(e):h();const r=t.projectId??process.env.FIREBASE_PROJECT_ID??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT;let c=t.credentials?.clientEmail??process.env.FIREBASE_CLIENT_EMAIL,n=t.credentials?.privateKey??process.env.FIREBASE_PRIVATE_KEY;const l=t.serviceAccountPath??process.env.GOOGLE_APPLICATION_CREDENTIALS;if((!c||!n)&&l){const p=JSON.parse(w(l,"utf8"));c??=p.client_email,n??=p.private_key}if(!c||!n)throw new Error("Firebase storage: service-account credentials are required. Provide `credentials` ({ clientEmail, privateKey }), `serviceAccountPath`, or set FIREBASE_CLIENT_EMAIL / FIREBASE_PRIVATE_KEY / GOOGLE_APPLICATION_CREDENTIALS.");return O({credential:k({clientEmail:c,privateKey:n.replaceAll(String.raw`\n`,`
|
|
2
|
-
`),projectId:r}),projectId:r,storageBucket:i},e)}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=u(t=>this.deleteMeta(t.id),"internalOnComplete")}export{E as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var F=Object.defineProperty;var O=(o,a)=>F(o,"name",{value:a,configurable:!0});import{Readable as w,Writable as v}from"node:stream";import{Client as M}from"basic-ftp";import{S as k}from"./index-B4ETk0Lu.js";import{throwErrorCode as u,ERRORS as m}from"./ERRORS-CyOuSMLY.js";import{B as E}from"./storage-uhIhcN-O.js";import P from"./FtpFile-B8jaICTB.js";import A from"./FtpMetaStorage-CoyWJafY.js";import{i as y,n as $,o as D}from"./posix-dirname-CiHXPPnw.js";import{o as b}from"./get-file-status-DLS18Zvd.js";import{u as R}from"./update-size-DANV7aa2.js";import{r as L}from"./part-match-D_NwyoF3.js";import{o as S}from"./has-content-Bx2p8Okx.js";var x=Object.defineProperty,p=O((o,a)=>x(o,"name",{value:a,configurable:!0}),"u");const d=p(o=>{const a=o?.code;if(a===550||a===450||a===553)return!0;const e=o instanceof Error?o.message:String(o);return/no such file|not exist|cannot find|file unavailable/i.test(e)},"isNotFoundError"),g=p(o=>{if(o instanceof Error&&o.name==="AbortError")return o;const a=new Error(o instanceof Error&&o.message?o.message:"The operation was aborted",{cause:o});return a.name="AbortError",a},"toAbortError"),T=p(async(o,a)=>{const e=[],t=new v({write(n,r,i){e.push(Buffer.from(n)),i()}});return await o.downloadTo(t,a),Buffer.concat(e)},"downloadToBuffer");class J extends E{static name="ftp";checksumTypes=[];meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=y(a.rootFolderPath??""),this.meta=a.metaStorage??new A(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new P(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const n=await this.getMeta(t.id);if(n.status==="completed")return n}catch{}return t.bytesWritten=0,t.status=b(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&R(t,a.size),!L(a,t))return u(m.FILE_CONFLICT);const n=await this.lock(a.id);try{if(S(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return u(m.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return u(m.METHOD_NOT_ALLOWED,"FTP storage does not support chunked or resumable uploads; send the file in a single request.");const r=await $(a.body),i=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,c=>this.run(c,async s=>{await this.ensureRemoteDirectory(s,i),await s.uploadFrom(w.from(r),i)})),t.bytesWritten=r.length,t.size=r.length,t.path=i,t.ETag=k(r)}return t.status=b(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,n)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),n=t.path??this.keyToPath(t.name||a),r=await this.runOperation(e,i=>this.run(i,async c=>{try{return await T(c,n)}catch(s){if(d(s))return u(m.FILE_NOT_FOUND);throw s}}));return{content:r,contentType:t.contentType,ETag:t.ETag??k(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),n=t.path??this.keyToPath(t.name||a);await this.runOperation(e,i=>this.run(i,async c=>{try{await c.remove(n)}catch(s){if(!d(s))throw s}})),await this.deleteMeta(a);const r={...t,status:"deleted"};return await this.onDelete(r),r})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async h=>{const f=await T(h,r);await this.ensureRemoteDirectory(h,i),await h.uploadFrom(w.from(f),i)}));const c={...n,id:e,name:e,path:i};return await this.saveMeta(c),c})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async h=>{try{await this.ensureRemoteDirectory(h,i),await h.rename(r,i)}catch(f){try{const l=await T(h,r);await this.ensureRemoteDirectory(h,i),await h.uploadFrom(w.from(l),i),await h.remove(r)}catch(l){throw new AggregateError([f,l],`FTP move failed: rename and copy+delete fallback both failed for "${r}" → "${i}"`)}}}));const c={...n,id:e,name:e,path:i};await this.saveMeta(c);try{await this.deleteMeta(a)}catch{}return c})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,n=>this.run(n,async r=>{const i=[];return await this.walkList(r,t,i),i}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const n=t.path??this.keyToPath(t.name||a);return this.runOperation(e,r=>this.run(r,async i=>{try{return await i.size(n),!0}catch(c){if(d(c))return!1;throw c}}))})}async walkList(a,e,t){let n;try{n=await a.list(e||".")}catch(r){if(d(r))return;throw r}for(const r of n){const i=e?`${e}/${r.name}`:r.name;if(r.isDirectory){await this.walkList(a,i,t);continue}if(!r.isFile)continue;const c=this.pathToKey(i);if(!c)continue;const s=new P({contentType:"application/octet-stream",metadata:{},originalName:r.name});s.id=c,s.name=c,s.path=i,s.size=r.size,r.modifiedAt&&(s.modifiedAt=r.modifiedAt.toISOString()),t.push(s)}}async run(a,e){const t=new M;if(a?.aborted)throw g(a.reason);const n=p(()=>{t.close()},"onAbort");a?.addEventListener("abort",n,{once:!0});try{if(await t.access(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(r){throw a?.aborted?g(r):r}finally{a?.removeEventListener("abort",n),t.close()}}async ensureRemoteDirectory(a,e){const t=D(e);t&&(await a.ensureDir(t),await a.cd("/"))}keyToPath(a){const e=y(a);e&&E.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":`/${t.join("/")}`}pathToKey(a){const e=y(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{J as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var y=Object.defineProperty;var h=(l,t)=>y(l,"name",{value:t,configurable:!0});import{randomUUID as w}from"node:crypto";import{request as b}from"gaxios";import{GoogleAuth as C}from"google-auth-library";import{r as R,E,b as U,g as k,d}from"./gcs-meta-storage-COq32th7.js";import{d as $}from"./detect-file-type-5JhzC9RU.js";import{throwErrorCode as I,ERRORS as S}from"./ERRORS-CyOuSMLY.js";import{B as v,t as O}from"./storage-uhIhcN-O.js";import{v as T}from"./local-meta-storage-Dr891Iy7.js";import m from"./GCSConfig-BQ0OpVhe.js";import B from"./GCSFile-CDQ6IWAz.js";import{r as A}from"./part-match-D_NwyoF3.js";import{o as j}from"./has-content-Bx2p8Okx.js";import{o as x}from"./get-file-status-DLS18Zvd.js";var P=Object.defineProperty,G=h((l,t)=>P(l,"name",{value:t,configurable:!0}),"e");class q extends Error{static{h(this,"o")}constructor(t,a,e){super(t),this.code=a,this.config=e}code;config;static{G(this,"FetchError")}name="FetchError"}var W=Object.defineProperty,g=h((l,t)=>W(l,"name",{value:t,configurable:!0}),"m");const M=g(l=>l>=200&&l<300||l===308||l===499,"validateStatus");class f extends v{static name="gcs";checksumTypes=["md5","crc32c"];get raw(){return this.authClient}meta;bucket;authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;constructor(t){super(t);const a=t.bucket||process.env.GCS_BUCKET;if(!a)throw new Error("GCS bucket is not defined");if(!t.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");this.bucket=a,this.storageBaseURI=`${t.storageAPI||m.storageAPI}/${this.bucket}/o`,this.uploadBaseURI=`${t.uploadAPI||m.uploadAPI}/${this.bucket}/o`,this.isCustomEndpoint=new URL(this.storageBaseURI).hostname!=="storage.googleapis.com";const{retryOptions:e,useAuthWithCustomEndpoint:r,userProject:i}=t;this.userProject=i,this.useAuthWithCustomEndpoint=r||!1,this.retryOptions={...R,...e},t.scopes||=m.authScopes,this.authClient=new C(t);const{bucket:o,metaStorage:c,metaStorageConfig:u,projectId:s}=t;if(c)this.meta=c;else{let n={...t,...u,logger:this.logger};"directory"in n?(this.logger?.debug("Using local meta storage"),this.meta=new T(n)):(o===n.bucket&&s===n.projectId&&(n={...n,authClient:this.authClient}),this.meta=new E(n))}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(n=>{this.logger?.error("Storage access check failed: %O",n)})}normalizeError(t){if(t.config){const a=+t.code||500;return{code:`GCS${a}`,message:t.message,name:t.name,retryable:a>=499,statusCode:a}}return{code:"GenericUploadError",message:`[${this.constructor.name}] ${t.message}`,name:t.name,statusCode:500}}async create(t,a){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const s=typeof t.ttl=="string"?O(t.ttl):t.ttl;s!==void 0&&(e.expiredAt=Date.now()+s)}const r=new B(e);r.name=this.namingFunction(r),await this.validate(r);try{const s=await this.getMeta(r.id);return s.bytesWritten=await this.internalWrite(s,a),s}catch{}const i={"Content-Type":"application/json; charset=utf-8","X-Goog-Upload-Command":"start","X-Goog-Upload-Protocol":"resumable","X-Upload-Content-Length":r.size.toString(),"X-Upload-Content-Type":r.contentType},o={body:JSON.stringify({metadata:r.metadata}),headers:i,method:"POST",params:{name:r.name,size:r.size,uploadType:"resumable"},url:this.uploadBaseURI},c=await this.makeRequest(o,a);if(c.status!==200)throw new Error("Expected 200 response from GCS");const u=c.headers.get("X-Goog-Upload-Status")||c.headers.get("x-goog-upload-status");if(u!=="active")throw new Error(`X-Goog-Upload-Status response header expected 'active' got: ${u}`);return r.uri=c.headers.get("location"),this.config.clientDirectUpload?(r.GCSUploadURI=r.uri,this.logger?.debug("send uploadURI to client: %s",r.GCSUploadURI),r.status="created",r):(r.bytesWritten=0,await this.saveMeta(r),r.status="created",await this.onCreate(r),r)})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(!A(t,e))return I(S.FILE_CONFLICT);const r=await this.lock(t.id);try{if(j(t)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:i,stream:o}=await $(t.body);i?.mime&&(e.contentType=i.mime),t.body=o}catch{}e.bytesWritten=await this.internalWrite({...e,...t},a),e.status=x(e),e.status==="completed"&&(e.uri=`${this.storageBaseURI}/${e.name}`,await this.internalOnComplete(e))}finally{await this.unlock(t.id,r)}return e})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);if(!e.uri)throw new Error(`File ${t} does not have a valid URI`);e.status="deleted",await this.makeRequest({method:"DELETE",url:e.uri,validateStatus:M},a),await this.deleteMeta(e.id);const r={...e};return await this.onDelete(r),r})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const r=new URL(`/${this.bucket}/${t}`,"file://"),i=new URL(encodeURI(a),r).pathname,[,o,...c]=i.split("/"),u=c.join("/"),s=`${this.storageBaseURI}/${t}/rewriteTo/b/${o}/o/${u}`;let n={};const p={body:"",headers:{"Content-Type":"application/json"},method:"POST",url:s};do p.body=n.rewriteToken?JSON.stringify({rewriteToken:n.rewriteToken}):"",n=(await this.makeRequest(p,e)).data||{};while(n.rewriteToken);return await this.getMeta(a)})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const r=await this.copy(t,a,e),i=`${this.storageBaseURI}/${t}`;return await this.makeRequest({method:"DELETE",url:i},e),r})}async get({id:t},a){return this.instrumentOperation("get",async()=>{const{data:e}=await this.makeRequest({params:{alt:"json"},url:`${this.storageBaseURI}/${t}`},a);if(await this.checkIfExpired({expiredAt:e.timeDeleted}),!e.uri)throw new Error("File URI not found");const r=(await this.makeRequest({params:{alt:"media"},url:e.uri},a)).data;let i;if(typeof r=="string")i=Buffer.from(r,"utf8");else if(r&&typeof r=="object"&&"data"in r){const o=r.data;i=Buffer.from(o)}else i=Buffer.from(r);return{...e,content:i}})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{try{return await this.getMeta(t),await this.makeRequest({method:"HEAD",url:`${this.storageBaseURI}/${t}`},a),!0}catch{return!1}})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const e=[],r=Math.min(t,1e3);let i=!0,o={params:{maxResults:r},url:this.storageBaseURI};for(;i&&e.length<t;)try{const{data:c}=await this.makeRequest(o,a);for(const{name:u,timeCreated:s,updated:n}of c?.items||[]){if(e.length>=t)break;e.push({createdAt:s,id:u,modifiedAt:n})}i=c?.nextPageToken!==void 0,i&&e.length<t&&(o={...o,params:{...o.params,maxResults:Math.min(r,t-e.length),pageToken:c.nextPageToken}})}catch(c){const u=this.normalizeError(c instanceof Error?c:new Error(String(c)));throw await this.onError(u),c}return e},{limit:t})}async internalWrite(t,a){const{body:e,bytesWritten:r,size:i,uri:o=""}=t,c=U(t),u={method:"PUT"};if(e?.on){const s=new AbortController;e.on("aborted",()=>{s.abort()}),u.body=e,u.signal=s.signal,u.retry=!1}u.headers={Accept:"application/json","Content-Range":c,...i===r?{"X-Goog-Upload-Command":"upload, finalize"}:{}};try{const s=await this.makeRequest({url:o,...u},a);if(s.status===308){const n=s.headers.get("range");return n?k(n):0}if(s.status===200)return this.logger?.debug("uploaded %O",s.data),i;throw new q(String(s.data),`GCS${s.status}`,{uri:o})}catch(s){this.logger?.error(o,s);const n=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(n),s}}internalOnComplete=g(t=>this.deleteMeta(t.id),"internalOnComplete");static buildCallSignal(t,a){const e=[];if(a&&e.push(a),t?.signal&&e.push(t.signal),e.length!==0)return e.length===1?e[0]:AbortSignal.any(e)}async makeRequest(t,a){typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":"));const e=f.buildCallSignal(a,t.signal);let r=this.retryOptions;if(a?.retries!==void 0){const o=typeof a.retries=="number"?a.retries:a.retries.maxRetries;typeof o=="number"&&(r={...this.retryOptions,retry:o})}const i=typeof a?.timeout=="number"&&a.timeout>0?a.timeout:6e4;return t={...t,headers:{"User-Agent":`${d.name}/${d.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${d.version} gccl-invocation-id/${w()}`,...t.headers},params:{...this.userProject===void 0?{}:{userProject:this.userProject},...t.params},retry:t.retry===!1?!1:a?.retries!==0,retryConfig:r,timeout:i,...e?{signal:e}:{}},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?b(t):this.authClient.request(t)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}}export{f as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var C=Object.defineProperty;var y=(r,e)=>C(r,"name",{value:e,configurable:!0});import{Readable as k}from"node:stream";import{drive as F}from"@googleapis/drive";import{JWT as T,GoogleAuth as E,OAuth2Client as _}from"google-auth-library";import{throwErrorCode as v,ERRORS as u,wrapStorageError as I}from"./ERRORS-CyOuSMLY.js";import{B as L}from"./storage-uhIhcN-O.js";import m from"./GoogleDriveFile-D0aGfGbL.js";import G from"./GoogleDriveMetaStorage-CBSdEQr6.js";import{o as O}from"./get-file-status-DLS18Zvd.js";import{u as A}from"./update-size-DANV7aa2.js";import{r as R}from"./part-match-D_NwyoF3.js";import{o as P}from"./has-content-Bx2p8Okx.js";var B=Object.defineProperty,c=y((r,e)=>B(r,"name",{value:e,configurable:!0}),"u");const f="https://www.googleapis.com/auth/drive",U=1024,p="fsdkKey",w="fsdkContentType",D="id, name, size, mimeType, md5Checksum, modifiedTime, appProperties",g=c(r=>{const e=r.lastIndexOf("/");return e===-1?r:r.slice(e+1)},"basename"),b=c(r=>r.replaceAll("\\","\\\\").replaceAll("'",String.raw`\'`),"escapeQueryValue");class z{static{y(this,"S")}static{c(this,"LRU")}#t;#e=new Map;constructor(e){this.#t=Math.max(1,e)}delete(e){this.#e.delete(e)}get(e){const i=this.#e.get(e);if(i!==void 0)return this.#e.delete(e),this.#e.set(e,i),i}set(e,i){if(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,i),this.#e.size>this.#t){const t=this.#e.keys().next().value;t!==void 0&&this.#e.delete(t)}}}const S=c(r=>{const e=r.subject??process.env.GOOGLE_DRIVE_SUBJECT;if(r.credentials)return new T({email:r.credentials.client_email,key:r.credentials.private_key,scopes:[f],...e&&{subject:e}});if(r.keyFilename)return new E({keyFile:r.keyFilename,scopes:[f],...e&&{clientOptions:{subject:e}}});if(r.oauth){const a=new _({clientId:r.oauth.clientId,clientSecret:r.oauth.clientSecret});return a.setCredentials({refresh_token:r.oauth.refreshToken}),a}const i=process.env.GOOGLE_DRIVE_CLIENT_EMAIL,t=process.env.GOOGLE_DRIVE_PRIVATE_KEY;if(i&&t)return new T({email:i,key:t,scopes:[f],...e&&{subject:e}});const o=process.env.GOOGLE_DRIVE_KEY_FILE;if(o)return new E({keyFile:o,scopes:[f],...e&&{clientOptions:{subject:e}}})},"buildAuth"),x=c(async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},"collectStream"),M=c(r=>{if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(Buffer.isBuffer(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof r=="string")return new TextEncoder().encode(r);throw new Error("Google Drive: unexpected response payload shape")},"toUint8");class ee extends L{static name="google-drive";checksumTypes=[];meta;authForTokens;driveClient;fileIdCache;publicByDefault;rootFolderId;sharedDriveParams;constructor(e){if(super(e),e.client)this.driveClient=e.client,this.authForTokens=void 0;else{const t=S(e);if(!t)throw new Error("Google Drive storage: missing auth. Pass `client`, `credentials`, `keyFilename`, or `oauth`. Env fallbacks: GOOGLE_DRIVE_CLIENT_EMAIL + GOOGLE_DRIVE_PRIVATE_KEY, or GOOGLE_DRIVE_KEY_FILE.");this.authForTokens=t,this.driveClient=F({auth:t,version:"v3"})}const i=e.driveId??process.env.GOOGLE_DRIVE_ID;this.rootFolderId=e.rootFolderId??process.env.GOOGLE_DRIVE_ROOT_FOLDER_ID??i??"root",this.publicByDefault=e.publicByDefault??!1,this.fileIdCache=new z(e.fileIdCacheSize??U),this.sharedDriveParams={includeItemsFromAllDrives:!0,supportsAllDrives:!0,...i&&{corpora:"drive",driveId:i}},this.meta=e.metaStorage??new G(e.metaStorageConfig),this.isReady=!0}get raw(){return this.driveClient}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new m(e);t.name=this.namingFunction(t),await this.validate(t);try{const o=await this.getMeta(t.id);if(o.bytesWritten>=0)return o}catch{}return t.bytesWritten=0,t.status=O(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&A(t,e.size),!R(e,t))throw new Error("File part does not match");const o=await this.lock(e.id);try{if(P(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await x(e.body),n=t.name||t.id,s={[w]:t.contentType,[p]:n},l=await this.runOperation(i,()=>this.driveClient.files.create({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum, modifiedTime",media:{body:k.from(a),mimeType:t.contentType},requestBody:{appProperties:s,mimeType:t.contentType,name:g(n),parents:[this.rootFolderId]}})),{data:d}=l,h=d.id??void 0;h&&(this.fileIdCache.set(n,h),this.publicByDefault&&await this.runOperation(i,()=>this.driveClient.permissions.create({...this.sharedDriveParams,fileId:h,requestBody:{role:"reader",type:"anyone"}}))),t.bytesWritten=a.length,t.size=a.length,t.driveFileId=h,t.mimeType=d.mimeType??t.contentType,t.ETag=d.md5Checksum??void 0}return t.status=O(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,o)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;const o=e;try{t=await this.getMeta(e)}catch{}try{const a=t?.driveFileId??await this.resolveFileId(o,i);await this.runOperation(i,()=>this.driveClient.files.delete({...this.sharedDriveParams,fileId:a})),this.fileIdCache.delete(o)}catch(a){if(!N(a))throw a;this.fileIdCache.delete(o)}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new m({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,status:"deleted"})})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,o;try{t=await this.checkIfExpired(await this.getMeta(e)),o=t.driveFileId??await this.resolveFileId(t.name??e,i)}catch{o=await this.resolveFileId(e,i)}const[a,n]=await Promise.all([this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,fields:D,fileId:o})),this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,alt:"media",fileId:o},{responseType:"arraybuffer"}))]),{data:s}=a,l=M(n.data),d=Buffer.from(l.buffer,l.byteOffset,l.byteLength),h=s.appProperties??{};return{content:d,contentType:t?.contentType??h[w]??s.mimeType??"application/octet-stream",ETag:t?.ETag??s.md5Checksum??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??s.modifiedTime??void 0,name:t?.name??s.name??e,originalName:t?.originalName??s.name??e,size:t?.size??Number(s.size??d.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const o=await this.resolveFileId(e,t),a=await this.runOperation(t,()=>this.driveClient.files.copy({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum",fileId:o,requestBody:{appProperties:{[p]:i},name:g(i),parents:[this.rootFolderId]}})),n=a.data.id??void 0;n&&this.fileIdCache.set(i,n);const s=new m({contentType:a.data.mimeType??"application/octet-stream",metadata:{},originalName:i});return s.id=i,s.name=i,s.driveFileId=n,s.mimeType=a.data.mimeType??void 0,s.ETag=a.data.md5Checksum??void 0,s.size=Number(a.data.size??0),s})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const o=await this.copy(e,i,t);return await this.delete({id:e},t),o})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{const t=`'${b(this.rootFolderId)}' in parents and trashed=false`,o=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:`nextPageToken, files(${D})`,pageSize:e,q:t}))).data.files??[],a=[];for(const n of o){const s=n.appProperties??{},l=s[p];if(!l)continue;n.id&&this.fileIdCache.set(l,n.id);const d=new m({contentType:s[w]??n.mimeType??"application/octet-stream",metadata:{},originalName:n.name??l});d.id=l,d.name=l,d.driveFileId=n.id??void 0,d.mimeType=n.mimeType??void 0,d.size=Number(n.size??0),d.modifiedAt=n.modifiedTime??void 0,d.ETag=n.md5Checksum??void 0,a.push(d)}return a},{limit:e})}async getReadUrl(e,i){return i?.responseContentDisposition?v(u.METHOD_NOT_ALLOWED,"Google Drive: `responseContentDisposition` is not supported — Drive's webContentLink has no Content-Disposition override."):this.publicByDefault?`https://drive.google.com/uc?export=download&id=${await this.resolveFileId(e)}`:v(u.METHOD_NOT_ALLOWED,"Google Drive: getReadUrl() requires the adapter to be constructed with `publicByDefault: true`. Drive has no signed URL primitive — use get() for private files.")}async getUploadUrl(e,i){if(!this.authForTokens)return v(u.METHOD_NOT_ALLOWED,"Google Drive: getUploadUrl() requires `credentials`, `keyFilename`, or `oauth` — not the pre-built `client` escape hatch.");const t=await this.authForTokens.getAccessToken(),o=typeof t=="string"?t:t?.token;if(!o)throw new Error("Google Drive: failed to mint access token for resumable upload session");const a={Authorization:`Bearer ${o}`,"Content-Type":"application/json; charset=UTF-8"};i?.contentType&&(a["X-Upload-Content-Type"]=i.contentType),i?.contentLength!==void 0&&(a["X-Upload-Content-Length"]=String(i.contentLength));const n={appProperties:{[p]:e},name:g(e),parents:[this.rootFolderId]},s=await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",{body:JSON.stringify(n),headers:a,method:"POST"});if(!s.ok){const d=await s.text().catch(()=>"");throw I(new Error(`${s.statusText} ${d}`.trim()||s.statusText),{adapter:"Google Drive",operation:"resumable upload session",status:s.status})}const l=s.headers.get("location")??s.headers.get("Location");if(!l)throw I(new Error("response missing Location header"),{adapter:"Google Drive",code:u.STORAGE_ERROR,operation:"resumable upload session"});return l}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const o=`appProperties has { key='${p}' and value='${b(e)}' } and trashed=false`,a=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:"files(id)",pageSize:2,q:o}))).data.files??[];if(a.length===0)throw new Error(`Google Drive: not found: ${e}`);if(a.length>1)throw new Error(`Google Drive: multiple files share virtual key '${e}'. Resolve via storage.raw.`);const n=a[0]?.id;if(!n)throw new Error(`Google Drive: list returned no fileId for ${e}`);return this.fileIdCache.set(e,n),n}internalOnComplete=c(e=>this.deleteMeta(e.id),"internalOnComplete")}const N=c(r=>{if(r===null||typeof r!="object")return!1;const e=r;return typeof e.code=="number"&&e.code===404||typeof e.status=="number"&&e.status===404?!0:typeof e.response?.status=="number"&&e.response.status===404},"isNotFoundError");export{ee as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"node:fs/promises";import"node:os";import{v as f}from"./local-meta-storage-Dr891Iy7.js";import"./path-D7rMc9nq-CPbxyMDy.js";import"./ERRORS-CyOuSMLY.js";import"./MetaStorage-Y4m1dWgd.js";import"./Metadata-B6Ir0KO7.js";export{f as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var k=Object.defineProperty;var T=(n,t)=>k(n,"name",{value:t,configurable:!0});import{ResponseType as g,Client as A,GraphError as U}from"@microsoft/microsoft-graph-client";import{wrapStorageError as d,ERRORS as m,throwErrorCode as _}from"./ERRORS-CyOuSMLY.js";import{c as C}from"./oauth-refresh-Dg2ybc6_.js";import{B as N}from"./storage-uhIhcN-O.js";import f from"./OneDriveFile-XbVVKIJh.js";import S from"./OneDriveMetaStorage-DPTNMpeq.js";import{o as E}from"./get-file-status-DLS18Zvd.js";import{u as $}from"./update-size-DANV7aa2.js";import{r as L}from"./part-match-D_NwyoF3.js";import{o as M}from"./has-content-Bx2p8Okx.js";var B=Object.defineProperty,h=T((n,t)=>B(n,"name",{value:t,configurable:!0}),"l");const P="https://graph.microsoft.com/.default",F=250*1024*1024,x=16*320*1024,V=1e3,u=h(n=>{let t=0,o=n.length;for(;t<o&&n[t]==="/";)t+=1;for(;o>t&&n[o-1]==="/";)o-=1;return t===0&&o===n.length?n:n.slice(t,o)},"trimSlashes"),y=h(n=>n.split("/").map(t=>encodeURIComponent(t)).join("/"),"encodePathSegments"),j=h(async n=>{const t=[];for await(const o of n)t.push(Buffer.from(o));return Buffer.concat(t)},"collectStream"),I=h(n=>({getAccessToken:h(()=>Promise.resolve(n),"getAccessToken")}),"createStaticAccessTokenAuth"),z=h(n=>({getAccessToken:h(async()=>n(),"ensure")}),"createCallableAccessTokenAuth"),O=h(n=>C({buildBody:h(()=>new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials",scope:P}),"buildBody"),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(n.tenantId)}/oauth2/v2.0/token`}),"createClientCredentialsAuth"),v=h(n=>C({buildBody:h(()=>new URLSearchParams({client_id:n.clientId,grant_type:"refresh_token",refresh_token:n.refreshToken,scope:P,...n.clientSecret&&{client_secret:n.clientSecret}}),"buildBody"),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(n.tenantId??"common")}/oauth2/v2.0/token`}),"createRefreshTokenAuth"),G=h(n=>({getAccessToken:h(()=>n.getAccessToken(),"getAccessToken")}),"makeAuthProvider"),D=h(n=>{if(n.client)return n.client;const t=n.accessToken!==void 0,o=n.clientCredentials!==void 0,e=n.oauth!==void 0;if([t,o,e].filter(Boolean).length>1)throw new Error("OneDrive storage: pass exactly one of `accessToken`, `clientCredentials`, or `oauth`.");let r;if(n.accessToken!==void 0?r=typeof n.accessToken=="function"?z(n.accessToken):I(n.accessToken):n.clientCredentials?r=O(n.clientCredentials):n.oauth&&(r=v({clientId:n.oauth.clientId,refreshToken:n.oauth.refreshToken,...n.oauth.clientSecret&&{clientSecret:n.oauth.clientSecret},...n.oauth.tenantId&&{tenantId:n.oauth.tenantId}})),!r){const a=process.env.ONEDRIVE_ACCESS_TOKEN;if(a)r=I(a);else{const i=process.env.ONEDRIVE_CLIENT_ID,s=process.env.ONEDRIVE_CLIENT_SECRET,c=process.env.ONEDRIVE_TENANT_ID,l=process.env.ONEDRIVE_REFRESH_TOKEN;l&&i?r=v({clientId:i,refreshToken:l,...s&&{clientSecret:s},...c&&{tenantId:c}}):i&&s&&c&&(r=O({clientId:i,clientSecret:s,tenantId:c}))}}if(!r)throw new Error("OneDrive storage: missing auth. Pass `client`, `accessToken`, `clientCredentials`, or `oauth`. Env fallbacks: ONEDRIVE_ACCESS_TOKEN; or ONEDRIVE_REFRESH_TOKEN + ONEDRIVE_CLIENT_ID (+ optional ONEDRIVE_CLIENT_SECRET, ONEDRIVE_TENANT_ID); or ONEDRIVE_CLIENT_ID + ONEDRIVE_CLIENT_SECRET + ONEDRIVE_TENANT_ID.");return A.initWithMiddleware({authProvider:G(r)})},"resolveAuth"),W=h(n=>{if(n instanceof U)return n.statusCode===404||n.code==="itemNotFound";if(n&&typeof n=="object"){const t=n;return t.statusCode===404||t.status===404||t.code==="itemNotFound"}return!1},"isNotFoundError");class nt extends N{static name="onedrive";checksumTypes=[];meta;basePath;client;copyTimeoutMs;publicByDefault;rootFolderPath;constructor(t){if(super(t),[t.driveId,t.siteId,t.userId].filter(o=>o!==void 0).length>1)throw new Error("OneDrive storage: pass at most one of `driveId`, `siteId`, or `userId`.");if(t.driveId)this.basePath=`/drives/${encodeURIComponent(t.driveId)}`;else if(t.siteId)this.basePath=`/sites/${encodeURIComponent(t.siteId)}/drive`;else if(t.userId)this.basePath=`/users/${encodeURIComponent(t.userId)}/drive`;else{if(t.clientCredentials)throw new Error("OneDrive storage: `clientCredentials` (app-only) auth requires `driveId`, `siteId`, or `userId`.");this.basePath="/me/drive"}this.rootFolderPath=u(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.copyTimeoutMs=t.copyTimeoutMs??6e4,this.client=D(t),this.meta=t.metaStorage??new S(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,o){return this.instrumentOperation("create",async()=>{const e=new f(t);e.name=this.namingFunction(e),await this.validate(e);try{const r=await this.getMeta(e.id);if(r.bytesWritten>=0)return r}catch{}return e.bytesWritten=0,e.status=E(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,o){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&$(e,t.size),!L(t,e))throw new Error("File part does not match");const r=await this.lock(t.id);try{if(M(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await j(t.body),i=e.name||e.id,s=a.byteLength<=F?await this.uploadSimple(i,a,e.contentType,o):await this.uploadSession(i,a,e.contentType,o);e.bytesWritten=a.length,e.size=a.length,e.driveItemId=s.id,e.webUrl=s.webUrl,e.eTag=s.eTag,e.ETag=s.eTag}return e.status=E(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,r)}})}async delete({id:t},o){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const r=e?.name??t;try{await this.runOperation(o,()=>this.client.api(this.itemApiPath(r)).delete())}catch(a){if(!W(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new f({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,status:"deleted"})})}async get({id:t},o){return this.instrumentOperation("get",async()=>{let e,r=t;try{e=await this.checkIfExpired(await this.getMeta(t)),r=e.name??t}catch{}const a=await this.runOperation(o,()=>this.client.api(this.itemApiPath(r)).get()),i=await this.runOperation(o,()=>this.client.api(this.itemActionPath(r,"content")).responseType(g.ARRAYBUFFER).get()),s=Buffer.from(i);return{content:s,contentType:e?.contentType??a.file?.mimeType??"application/octet-stream",ETag:e?.ETag??a.eTag,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.lastModifiedDateTime,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??s.length}})}async copy(t,o,e){return this.instrumentOperation("copy",async()=>{const r=this.parentReferencePath(o),a={name:R(o),parentReference:{path:r}},i=await this.runOperation(e,()=>this.client.api(this.itemActionPath(t,"copy")).responseType(g.RAW).post(a));if(i.status!==202){const w=await i.text().catch(()=>"");throw d(new Error(w||i.statusText),{adapter:"OneDrive",operation:"copy",status:i.status})}const s=i.headers.get("Location");if(!s)throw d(new Error("response missing Location monitor URL"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});const c=await this.pollCopyMonitor(s,e),l=new f({contentType:"application/octet-stream",metadata:{},originalName:o});return l.id=o,l.name=o,l.driveItemId=c,l})}async move(t,o,e){return this.instrumentOperation("move",async()=>{const r=this.parentReferencePath(o),a=R(o),i=await this.runOperation(e,()=>this.client.api(this.itemApiPath(t)).patch({name:a,parentReference:{path:r}})),s=new f({contentType:"application/octet-stream",metadata:{},originalName:o});s.id=o,s.name=o,s.driveItemId=i.id,s.webUrl=i.webUrl,s.eTag=i.eTag,s.ETag=i.eTag;try{await this.deleteMeta(t)}catch{}return s})}async list(t=1e3,o){return this.instrumentOperation("list",async()=>{const e=[];let r=`${this.folderListChildrenPath()}?$top=${Math.min(t,1e3)}`;for(;r&&e.length<t;){const a=await this.runOperation(o,()=>this.client.api(r).get());for(const i of a.value){if(!i.file)continue;const s=this.itemPathToKey(i);if(!s)continue;const c=new f({contentType:i.file.mimeType??"application/octet-stream",metadata:{},originalName:i.name});if(c.id=s,c.name=s,c.driveItemId=i.id,c.webUrl=i.webUrl,c.eTag=i.eTag,c.ETag=i.eTag,c.size=i.size??0,c.modifiedAt=i.lastModifiedDateTime,e.push(c),e.length>=t)break}r=a["@odata.nextLink"]??null}return e},{limit:t})}async getReadUrl(t,o){if(o?.responseContentDisposition||o?.responseContentType)return _(m.METHOD_NOT_ALLOWED,"OneDrive: `responseContentDisposition` / `responseContentType` are not supported — Graph download URLs have no overrides.");if(this.publicByDefault){const r=(await this.client.api(this.itemActionPath(t,"createLink")).post({scope:"anonymous",type:"view"})).link?.webUrl;if(!r)throw new Error("OneDrive: createLink response missing webUrl");return r}const e=(await this.client.api(this.itemApiPath(t)).select("@microsoft.graph.downloadUrl").get())["@microsoft.graph.downloadUrl"];if(!e)throw new Error("OneDrive: item has no `@microsoft.graph.downloadUrl` — it may be a folder or have no content.");return e}async getUploadUrl(t,o){const e=await this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...o?.contentType&&{file:{mimeType:o.contentType}}}});if(!e.uploadUrl)throw d(new Error("createUploadSession response missing uploadUrl"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"getUploadUrl"});return e.uploadUrl}keyParts(t){const o=u(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),o&&e.push(o),e}itemApiPath(t){const o=this.keyParts(t);return o.length===0?`${this.basePath}/root`:`${this.basePath}/root:/${y(o.join("/"))}`}itemActionPath(t,o){const e=this.keyParts(t);return e.length===0?`${this.basePath}/root/${o}`:`${this.basePath}/root:/${y(e.join("/"))}:/${o}`}folderListChildrenPath(){return this.itemActionPath("","children")}parentReferencePath(t){const o=u(t),e=[];this.rootFolderPath&&e.push(this.rootFolderPath);const r=o.lastIndexOf("/");if(r!==-1){const a=o.slice(0,r);a&&e.push(a)}return e.length===0?"/drive/root:":`/drive/root:/${y(e.join("/"))}`}itemPathToKey(t){const o=t.parentReference?.path??"",e="/root:",r=o.indexOf(e);let a=r===-1?"":o.slice(r+e.length);a=u(decodeURIComponent(a));const i=this.rootFolderPath&&a.startsWith(this.rootFolderPath)?a.slice(this.rootFolderPath.length):a,s=u(i);return s?`${s}/${t.name}`:t.name}async uploadSimple(t,o,e,r){return await this.runOperation(r,()=>this.client.api(`${this.itemActionPath(t,"content")}?@microsoft.graph.conflictBehavior=replace`).header("Content-Type",e??"application/octet-stream").put(o))}async uploadSession(t,o,e,r){const a=await this.runOperation(r,()=>this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...e&&{file:{mimeType:e}}}})),i=o.byteLength;let s=0,c;for(;s<i;){const l=Math.min(s+x,i),w=o.subarray(s,l),p=await this.runOperation(r,()=>fetch(a.uploadUrl,{body:new Uint8Array(w),headers:{"Content-Length":String(w.byteLength),"Content-Range":`bytes ${s}-${l-1}/${i}`},method:"PUT"}));if(p.status===200||p.status===201)c=await p.json();else if(p.status!==202){const b=await p.text().catch(()=>"");throw d(new Error(b||p.statusText),{adapter:"OneDrive",operation:"upload-session chunk",status:p.status})}s=l}if(!c)throw d(new Error("upload-session terminated without a final DriveItem response"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"write"});return c}async pollCopyMonitor(t,o){const e=Date.now()+this.copyTimeoutMs;for(;;){const r=await this.runOperation(o,()=>fetch(t));if(!r.ok)throw d(new Error(r.statusText),{adapter:"OneDrive",operation:"copy monitor",status:r.status});const a=await r.json();if(a.status==="completed")return a.resourceId;if(a.status==="failed")throw d(new Error(a.error?.message??"unknown error"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});if(Date.now()>=e)throw new Error(`OneDrive: copy timed out after ${this.copyTimeoutMs}ms (status: ${a.status??"unknown"})`);await new Promise(i=>{setTimeout(i,V)})}}internalOnComplete=h(t=>this.deleteMeta(t.id),"internalOnComplete")}const R=h(n=>{const t=u(n),o=t.lastIndexOf("/");return o===-1?t:t.slice(o+1)},"baseName"),rt=h(n=>D(n),"buildGraphClient");export{rt as buildGraphClient,nt as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var w=Object.defineProperty;var l=(r,e)=>w(r,"name",{value:e,configurable:!0});import{CreateMultipartUploadCommand as b,UploadPartCommand as y,CompleteMultipartUploadCommand as B,AbortMultipartUploadCommand as S,ListPartsCommand as T,GetObjectCommand as h,HeadObjectCommand as E,DeleteObjectCommand as U,CopyObjectCommand as K,ListObjectsV2Command as x,waitUntilBucketExists as L,S3Client as I,PutObjectCommand as M}from"@aws-sdk/client-s3";import{fromIni as P}from"@aws-sdk/credential-providers";import{getSignedUrl as m}from"@aws-sdk/s3-request-presigner";import{S as O,b as A}from"./s3-base-storage-CqAyWHR6.js";import{Readable as g}from"node:stream";import{ReadableStream as C}from"node:stream/web";import v from"./S3File-BfmCOET4.js";import j from"./S3MetaStorage-vcriiosn.js";var N=Object.defineProperty,f=l((r,e)=>N(r,"name",{value:e,configurable:!0}),"d");const s=f(r=>r?.signal?{abortSignal:r.signal}:void 0,"sendOptions");class R{static{l(this,"T")}constructor(e,t){this.client=e}client;static{f(this,"S3ClientAdapter")}async createMultipartUpload(e,t){const a=new b({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),n=await this.client.send(a,s(t));if(!n.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:n.UploadId}}async uploadPart(e,t){const a=e.Body instanceof C?g.fromWeb(e.Body):e.Body,n=new y({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),o=await this.client.send(n,s(t));if(!o.ETag)throw new Error("Failed to upload part");return{ETag:o.ETag}}async completeMultipartUpload(e,t){const a=new B({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:o,PartNumber:i})=>({ETag:o,PartNumber:i}))},UploadId:e.UploadId}),n=await this.client.send(a,s(t));if(!n.Location)throw new Error("Failed to complete multipart upload");return{ETag:n.ETag,Location:n.Location}}async abortMultipartUpload(e,t){const a=new S({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a,s(t))}async listParts(e,t){const a=new T({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),n=await this.client.send(a,s(t)),o=[];if(n.Parts)for(const i of n.Parts)i.ETag&&i.PartNumber&&o.push({ETag:i.ETag,PartNumber:i.PartNumber,Size:i.Size});return{Parts:o.length>0?o:void 0}}async getObject(e,t){const a=new h({Bucket:e.Bucket,Key:e.Key,...e.Range!==void 0&&{Range:e.Range}}),n=await this.client.send(a,s(t));let o;if(n.Body){const i=n.Body;i instanceof g||typeof i=="object"&&"transform"in i&&i instanceof C?o=i:o=g.from(i)}return{Body:o,ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified,Metadata:n.Metadata}}async headObject(e,t){const a=new E({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,s(t));return{ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified}}async deleteObject(e,t){const a=new U({Bucket:e.Bucket,Key:e.Key});await this.client.send(a,s(t))}async copyObject(e,t){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const n=new K(a);await this.client.send(n,s(t))}async listObjectsV2(e,t){const a=new x({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,MaxKeys:e.MaxKeys}),n=await this.client.send(a,s(t));return{Contents:n.Contents?.map(o=>({Key:o.Key,LastModified:o.LastModified})),IsTruncated:n.IsTruncated,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(e){const t=new y({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return m(this.client,t,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await L({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}var D=Object.defineProperty,z=l((r,e)=>D(r,"name",{value:e,configurable:!0}),"m");class q extends O{static name="s3";s3Api;rawClient;constructor(e){const{bucket:t=process.env.S3_BUCKET,region:a=process.env.S3_REGION}=e;if(!t)throw new Error("S3 bucket is not defined");if(!a)throw new Error("S3 region is not defined");e.region=a;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=P({configFilepath:n}));const o=new I(e);super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:z(d=>{const c=d;if(c.$metadata){const p=c.$metadata.httpStatusCode;if(p&&[408,429,500,502,503,504].includes(p)||c.$fault==="server")return!0}return c.retryable??!1},"shouldRetry")}}),this.s3Api=new R(o,t),this.rawClient=o;const{metaStorage:i,metaStorageConfig:u}=e;if(!i){const d={...e,...u,logger:this.logger};"directory"in d||(this.meta=new j(d))}this.config.clientDirectUpload&&(this.onCreate=async()=>{})}normalizeError(e){return e.$metadata?{code:e.Code||e.name,message:e.message,name:e.name,statusCode:e.$metadata.httpStatusCode||500}:super.normalizeError(e)}async update({id:e},t){if(this.config.clientDirectUpload){const a=await this.getMeta(e);return this.buildPresigned({...a,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),n=A(t?.range),{Body:o,ContentLength:i,ContentType:u,ETag:d,Expires:c,LastModified:p}=await this.runOperation(t,k=>a.getObject({Bucket:this.bucket,Key:e,...n!==void 0&&{Range:n}},{signal:k}));return await this.checkIfExpired({expiredAt:c}),{headers:{"Content-Length":i?.toString()??"0","Content-Type":u,...d&&{ETag:d},...c&&{"X-Upload-Expires":c.toString()},...p&&{"Last-Modified":p.toString()}},size:Number(i),stream:o}})}get raw(){return this.rawClient}async getReadUrl(e,t){const a=new h({Bucket:this.bucket,Key:e,...t?.responseContentDisposition&&{ResponseContentDisposition:t.responseContentDisposition},...t?.responseContentType&&{ResponseContentType:t.responseContentType}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}async getUploadUrl(e,t){const a=new M({Bucket:this.bucket,Key:e,...t?.contentType&&{ContentType:t.contentType},...t?.contentLength!==void 0&&{ContentLength:t.contentLength}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}getS3Api(){return this.s3Api}getFileClass(){return v}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{q as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var F=Object.defineProperty;var k=(h,a)=>F(h,"name",{value:a,configurable:!0});import{S as O}from"./index-B4ETk0Lu.js";import M from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-CyOuSMLY.js";import{B as E}from"./storage-uhIhcN-O.js";import P from"./SftpFile-CQCxZNVq.js";import v from"./SftpMetaStorage-Cs8b7uBO.js";import{i as w,n as A,o as l}from"./posix-dirname-CiHXPPnw.js";import{o as b}from"./get-file-status-DLS18Zvd.js";import{u as S}from"./update-size-DANV7aa2.js";import{r as $}from"./part-match-D_NwyoF3.js";import{o as x}from"./has-content-Bx2p8Okx.js";var L=Object.defineProperty,T=k((h,a)=>L(h,"name",{value:a,configurable:!0}),"l");const f=T(h=>{const a=h?.code,e=h instanceof Error?h.message:String(h);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},"isNotFoundError"),g=T(h=>{if(h instanceof Error&&h.name==="AbortError")return h;const a=new Error(h instanceof Error&&h.message?h.message:"The operation was aborted",{cause:h});return a.name="AbortError",a},"toAbortError");class B extends E{static name="sftp";checksumTypes=[];meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=w(a.rootFolderPath??""),this.meta=a.metaStorage??new v(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new P(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const i=await this.getMeta(t.id);if(i.status==="completed")return i}catch{}return t.bytesWritten=0,t.status=b(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&S(t,a.size),!$(a,t))return d(p.FILE_CONFLICT);const i=await this.lock(a.id);try{if(x(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return d(p.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return d(p.METHOD_NOT_ALLOWED,"SFTP storage does not support chunked or resumable uploads; send the file in a single request.");const r=await A(a.body),n=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,o=>this.run(o,async s=>{const c=l(n);c&&await s.mkdir(c,!0),await s.put(r,n)})),t.bytesWritten=r.length,t.size=r.length,t.path=n,t.ETag=O(r)}return t.status=b(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,i)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),i=t.path??this.keyToPath(t.name||a),r=await this.runOperation(e,n=>this.run(n,async o=>{try{return await o.get(i)}catch(s){if(f(s))return d(p.FILE_NOT_FOUND);throw s}}));return{content:r,contentType:t.contentType,ETag:t.ETag??O(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),i=t.path??this.keyToPath(t.name||a);await this.runOperation(e,n=>this.run(n,async o=>{try{await o.delete(i)}catch(s){if(!f(s))throw s}})),await this.deleteMeta(a);const r={...t,status:"deleted"};return await this.onDelete(r),r})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(a),r=i.path??this.keyToPath(i.name||a),n=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=await c.get(r),m=l(n);m&&await c.mkdir(m,!0),await c.put(u,n)}));const o={...i,id:e,name:e,path:n};return await this.saveMeta(o),o})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(a),r=i.path??this.keyToPath(i.name||a),n=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=l(n);u&&await c.mkdir(u,!0);try{await c.rename(r,n)}catch(m){try{const y=await c.get(r);await c.put(y,n),await c.delete(r)}catch(y){throw new AggregateError([m,y],`SFTP move failed: rename and copy+delete fallback both failed for "${r}" → "${n}"`)}}}));const o={...i,id:e,name:e,path:n};await this.saveMeta(o);try{await this.deleteMeta(a)}catch{}return o})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,i=>this.run(i,async r=>{const n=[];return await this.walkList(r,t,n),n}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const i=t.path??this.keyToPath(t.name||a);return this.runOperation(e,r=>this.run(r,async n=>{const o=await n.exists(i);return o==="-"||o==="l"}))})}async walkList(a,e,t){let i;try{i=await a.list(e||".")}catch(r){if(f(r))return;throw r}for(const r of i){const n=e?`${e}/${r.name}`:r.name;if(r.type==="d"){await this.walkList(a,n,t);continue}if(r.type!=="-")continue;const o=this.pathToKey(n);if(!o)continue;const s=new P({contentType:"application/octet-stream",metadata:{},originalName:r.name});s.id=o,s.name=o,s.path=n,s.size=r.size,s.modifiedAt=new Date(r.modifyTime).toISOString(),t.push(s)}}async run(a,e){const t=new M;if(a?.aborted)throw g(a.reason);const i=T(()=>{t.end()},"onAbort");a?.addEventListener("abort",i,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(r){throw a?.aborted?g(r):r}finally{a?.removeEventListener("abort",i),await t.end()}}keyToPath(a){const e=w(a);e&&E.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":this.rootFolderPath.startsWith("/")?`/${t.join("/")}`:t.join("/")}pathToKey(a){const e=w(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{B as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var g=Object.defineProperty;var u=(o,t)=>g(o,"name",{value:t,configurable:!0});import{StorageClient as w}from"@supabase/storage-js";import{throwErrorCode as p,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import{B as y}from"./storage-uhIhcN-O.js";import c from"./SupabaseFile-DZ1iv9gM.js";import b from"./SupabaseMetaStorage-D_fGv0d6.js";import{o as l}from"./get-file-status-DLS18Zvd.js";import{u as E}from"./update-size-DANV7aa2.js";import{r as k}from"./part-match-D_NwyoF3.js";import{o as S}from"./has-content-Bx2p8Okx.js";var O=Object.defineProperty,h=u((o,t)=>O(o,"name",{value:t,configurable:!0}),"p");const f=3600*24*7,U=h(o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const t=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=t?.[1]??t?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},"parseDownloadOption"),C=h(async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream");class $ extends y{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(t){if(super(t),this.bucket=t.bucket,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,f),t.client)this.storageClient=t.client;else{const a=t.url??process.env.SUPABASE_URL,e=t.serviceKey??process.env.SUPABASE_SERVICE_ROLE_KEY??process.env.SUPABASE_KEY;if(!a)throw new Error("Supabase storage: `url` is required (or set SUPABASE_URL).");if(!e)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const r=a.replace(/\/+$/,"")+(a.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new w(r,{apikey:e,Authorization:`Bearer ${e}`},t.fetch)}this.meta=t.metaStorage??new b(t.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucket,e.path=e.name,await this.validate(e);try{const r=await this.getMeta(e.id);if(r.bytesWritten>=0)return r}catch{}return e.bytesWritten=0,e.status=l(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&E(e,t.size),!k(t,e))throw new Error("File part does not match");const r=await this.lock(t.id);try{if(S(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await C(t.body),n=e.path??e.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,i,{contentType:e.contentType,upsert:!0}));if(m)throw m;e.bytesWritten=i.length,e.size=i.length,e.path=s?.path??n,e.ETag=s?.id}return e.status=l(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,r)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const r=e?.path??e?.name??t,{error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).remove([r]));if(i&&i.message&&!/not.*found/i.test(i.message))throw i;return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.bucket,id:t,name:t,path:r,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}const{data:r,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(e));return i?!1:!!r})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,r;try{r=await this.checkIfExpired(await this.getMeta(t)),e=r.path??r.name??t}catch{}const{data:i,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(e));if(n||!i)throw n??new Error(`Supabase: object not found at "${e}"`);const s=Buffer.from(await this.runOperation(a,()=>i.arrayBuffer()));return{content:s,contentType:r?.contentType??i.type??"application/octet-stream",ETag:r?.ETag,expiredAt:r?.expiredAt,id:t,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??e,originalName:r?.originalName??e,size:r?.size??s.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(t))?.path??t,i=a,{error:n}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).copy(r,i));if(n)throw n;const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=i,s.bucket=this.bucket,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(t))?.path??t,{error:i}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).move(r,a));if(i)throw i;const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucket;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const{data:e,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:t}));if(r)throw r;return(e??[]).map(i=>{const n=new c({contentType:i.metadata?.mimetype??"application/octet-stream",metadata:i.metadata??{},originalName:i.name});return n.id=i.name,n.name=i.name,n.path=i.name,n.bucket=this.bucket,n.size=typeof i.metadata?.size=="number"?i.metadata.size:void 0,n.createdAt=i.created_at??void 0,n.modifiedAt=i.updated_at??void 0,n.ETag=i.metadata?.eTag??i.id??void 0,n})},{limit:t})}async getReadUrl(t,a){const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{data:r,error:i}=await this.storageClient.from(this.bucket).createSignedUrl(t,e,{download:U(a?.responseContentDisposition)});return i||!r?p(d.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUrl failed"):r.signedUrl}async getUploadUrl(t,a){const{data:e,error:r}=await this.storageClient.from(this.bucket).createSignedUploadUrl(t);return r||!e?p(d.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUploadUrl failed"):e.signedUrl}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=h(t=>this.deleteMeta(t.id),"internalOnComplete")}export{$ as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var T=Object.defineProperty;var l=(n,t)=>T(n,"name",{value:t,configurable:!0});import{UTApi as U,UTFile as h}from"uploadthing/server";import{throwErrorCode as m,ERRORS as f}from"./ERRORS-CyOuSMLY.js";import{B as I}from"./storage-uhIhcN-O.js";import d from"./UploadThingFile-BpG9mE8K.js";import O from"./UploadThingMetaStorage-CAQ1uTfv.js";import{o as y}from"./get-file-status-DLS18Zvd.js";import{u as E}from"./update-size-DANV7aa2.js";import{r as k}from"./part-match-D_NwyoF3.js";import{o as v}from"./has-content-Bx2p8Okx.js";var b=Object.defineProperty,u=l((n,t)=>b(n,"name",{value:t,configurable:!0}),"c");const w=3600*24*7,x=u(n=>{let t;try{t=typeof atob=="function"?atob(n):Buffer.from(n,"base64").toString("utf8")}catch(e){throw new Error(`UploadThing: token is not valid base64: ${e.message}`)}let i;try{i=JSON.parse(t)}catch(e){throw new Error(`UploadThing: token does not decode to JSON: ${e.message}`)}if(!i||typeof i!="object"||typeof i.apiKey!="string"||typeof i.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return i},"decodeToken"),N=u(async n=>{const t=[];for await(const i of n)t.push(Buffer.from(i));return Buffer.concat(t)},"collectStream"),g=u(n=>{const t=n.lastIndexOf("/");return t===-1?n:n.slice(t+1)},"basename");class B extends I{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(t){super(t);const i=t.token??process.env.UPLOADTHING_TOKEN;if(t.client)this.utapi=t.client;else{if(!i)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new U({defaultKeyType:"customId",token:i})}if(!i)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=x(i).appId,this.acl=t.acl??"public-read",this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w),this.meta=t.metaStorage??new O(t.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(t,i){return this.instrumentOperation("create",async()=>{const e=new d(t);e.name=this.namingFunction(e),e.customId=e.name,await this.validate(e);try{const a=await this.getMeta(e.id);if(a.bytesWritten>=0)return a}catch{}return e.bytesWritten=0,e.status=y(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,i){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&E(e,t.size),!k(t,e))throw new Error("File part does not match");const a=await this.lock(t.id);try{if(v(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await N(t.body),p=new Blob([new Uint8Array(r)],{type:e.contentType}),o=new h([p],g(e.name||e.id),{customId:e.name||e.id,type:e.contentType}),s=await this.runOperation(i,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const{data:c}=s;e.bytesWritten=r.length,e.size=r.length,e.ufsKey=c.key,e.url=c.ufsUrl??c.url,e.ETag=c.fileHash,e.fileHash=c.fileHash}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,a)}})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const a=e?.customId??e?.name??t;return await this.runOperation(i,()=>this.utapi.deleteFiles(a)),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:t}),{customId:a,id:t,name:t,status:"deleted"})})}async get({id:t},i){return this.instrumentOperation("get",async()=>{let e,a=t;try{e=await this.checkIfExpired(await this.getMeta(t)),a=e.customId??e.name??t}catch{}const r=await this.resolveFetchUrl(a,i),p=await this.runOperation(i,()=>fetch(r));if(!p.ok)throw new Error(`UploadThing: fetch failed: ${p.status} ${p.statusText} for ${a}`);const o=Buffer.from(await p.arrayBuffer());return{content:o,contentType:e?.contentType??p.headers.get("content-type")??"application/octet-stream",ETag:e?.ETag??p.headers.get("etag")??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt,name:e?.name??a,originalName:e?.originalName??a,size:e?.size??o.length}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const a=await this.get({id:t},e),r=new Blob([new Uint8Array(a.content)],{type:a.contentType}),p=new h([r],g(i),{customId:i,type:a.contentType}),o=await this.runOperation(e,()=>this.utapi.uploadFiles(p,{acl:this.acl}));if(o.error)throw new Error(o.error.message);const s=new d({contentType:a.contentType,metadata:{},originalName:i});return s.id=i,s.name=i,s.customId=i,s.size=typeof a.size=="string"?Number(a.size):a.size,s.ufsKey=o.data.key,s.url=o.data.ufsUrl??o.data.url,s.ETag=o.data.fileHash,s})}async move(t,i,e){return this.instrumentOperation("move",async()=>{const a=await this.copy(t,i,e);return await this.delete({id:t},e),a})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>(await this.runOperation(i,()=>this.utapi.listFiles({limit:t}))).files.map(e=>{const a=e.customId??e.key,r=new d({contentType:"application/octet-stream",metadata:{},originalName:a});return r.id=a,r.name=a,r.customId=e.customId??void 0,r.ufsKey=e.key,r.size=e.size,r.modifiedAt=e.uploadedAt?new Date(e.uploadedAt).toISOString():void 0,r}),{limit:t})}async getReadUrl(t,i){if(i?.responseContentDisposition)return m(f.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition` is not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const e=Math.min(i?.expiresIn??this.defaultUrlExpiresIn,w),{ufsUrl:a}=await this.utapi.generateSignedURL(t,{expiresIn:e,keyType:"customId"});return a}async getUploadUrl(t,i){return m(f.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(t,i){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const{ufsUrl:e}=await this.runOperation(i,()=>this.utapi.generateSignedURL(t,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return e}internalOnComplete=u(t=>this.deleteMeta(t.id),"internalOnComplete")}export{B as default};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var f=Object.defineProperty;var p=(h,t)=>f(h,"name",{value:t,configurable:!0});import C from"./MetaStorage-Y4m1dWgd.js";import{parseMetadata as T,stringifyMetadata as k}from"./Metadata-B6Ir0KO7.js";import{Readable as w}from"node:stream";import{AwsClient as E}from"aws4fetch";import{o as x}from"./is-expired-1JuZjDtb.js";var U=Object.defineProperty,y=p((h,t)=>U(h,"name",{value:t,configurable:!0}),"b");const g=y(h=>{const t={},s=h.replaceAll(/<\?xml[^>]*\?>/g,"").replaceAll(/xmlns[^=]*="[^"]*"/g,""),a=/<([^>]+)>([^<]*)<\/\1>/g,e=[...s.matchAll(a)];for(const i of e){const[,n,c]=i;n&&c?.trim()&&(t[n]?(Array.isArray(t[n])||(t[n]=[t[n]]),t[n].push(c.trim())):t[n]=c.trim())}const o=/<([^>]+)>([\s\S]*?)<\/\1>/g;let r;for(;(r=o.exec(s))!==null;){const[,i,n]=r;if(i&&n?.includes("<")){const c=g(n);Object.keys(c).length>0&&(t[i]=c)}}return t},"parseXml");class ${static{p(this,"C")}static{y(this,"AwsLightApiAdapter")}aws;bucket;endpoint;constructor(t){this.bucket=t.bucket,this.endpoint=t.endpoint||`https://${t.bucket}.s3.${t.region}.amazonaws.com`,this.aws=new E({accessKeyId:t.accessKeyId,region:t.region,secretAccessKey:t.secretAccessKey,service:t.service||"s3",sessionToken:t.sessionToken})}async createMultipartUpload(t,s){const a={uploads:""},e={};if(t.ContentType&&(e["Content-Type"]=t.ContentType),t.ACL&&(e["x-amz-acl"]=t.ACL),t.Metadata)for(const[d,l]of Object.entries(t.Metadata))e[`x-amz-meta-${d}`]=l;const o=this.buildUrl(t.Key,a),r=await this.aws.fetch(o,{headers:e,method:"POST",signal:s?.signal}),i=await r.text();if(!r.ok)throw new Error(`Failed to create multipart upload: ${r.status} ${i}`);const n=g(i),c=n.UploadId||n.InitiateMultipartUploadResult?.UploadId;if(!c){const d=new Error("Failed to parse UploadId from response");throw d.retryable=!1,d}return{UploadId:c}}async uploadPart(t,s){const a={partNumber:String(t.PartNumber),uploadId:t.UploadId},e={};t.ContentLength&&(e["Content-Length"]=String(t.ContentLength)),t.ContentMD5&&(e["Content-MD5"]=t.ContentMD5);const o=t.Body instanceof w?w.toWeb(t.Body):t.Body,r=this.buildUrl(t.Key,a),i=await this.aws.fetch(r,{body:o,headers:e,method:"PUT",signal:s?.signal});if(!i.ok){const c=await i.text();throw new Error(`Failed to upload part: ${i.status} ${c}`)}const n=i.headers.get("ETag");if(!n)throw new Error("Failed to get ETag from response");return{ETag:n.replaceAll(/(^"|"$)/g,"")}}async completeMultipartUpload(t,s){const a={uploadId:t.UploadId},e=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
-
<CompleteMultipartUpload xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
3
|
-
${t.Parts.map(({ETag:l,PartNumber:u})=>`<Part><PartNumber>${u}</PartNumber><ETag>"${l}"</ETag></Part>`).join("")}
|
|
4
|
-
</CompleteMultipartUpload>`,o=this.buildUrl(t.Key,a),r=await this.aws.fetch(o,{body:e,headers:{"Content-Type":"application/xml"},method:"POST",signal:s?.signal}),i=await r.text();if(!r.ok)throw new Error(`Failed to complete multipart upload: ${r.status} ${i}`);const n=g(i),c=n.CompleteMultipartUploadResult||n,d=c.Location||`${this.endpoint}/${t.Key}`;return{ETag:c.ETag?.replaceAll(/(^"|"$)/g,""),Location:d}}async abortMultipartUpload(t,s){const a={uploadId:t.UploadId},e=this.buildUrl(t.Key,a),o=await this.aws.fetch(e,{method:"DELETE",signal:s?.signal});if(!o.ok){const r=await o.text();throw new Error(`Failed to abort multipart upload: ${o.status} ${r}`)}}async listParts(t,s){const a={uploadId:t.UploadId},e=this.buildUrl(t.Key,a),o=await this.aws.fetch(e,{method:"GET",signal:s?.signal}),r=await o.text();if(!o.ok)throw new Error(`Failed to list parts: ${o.status} ${r}`);const i=g(r),n=i.ListPartsResult||i;let c=[];return n.Part&&(c=Array.isArray(n.Part)?n.Part:[n.Part]),{Parts:c.map(d=>({ETag:d.ETag?.replaceAll(/(^"|"$)/g,""),PartNumber:Number(d.PartNumber)||0,Size:d.Size?Number(d.Size):void 0}))}}async getObject(t,s){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"GET",signal:s?.signal});if(!e.ok){const u=await e.text();throw new Error(`Failed to get object: ${e.status} ${u}`)}const o=e.headers.get("Content-Length"),r=e.headers.get("Content-Type"),i=e.headers.get("ETag"),n=e.headers.get("Expires"),c=e.headers.get("Last-Modified"),d={};for(const[u,m]of e.headers.entries())if(u.toLowerCase().startsWith("x-amz-meta-")){const b=u.toLowerCase().replace("x-amz-meta-","");d[b]=m}const{body:l}=e;return{Body:l?this.streamToReadable(l):void 0,ContentLength:o?Number(o):void 0,ContentType:r||void 0,ETag:i?.replaceAll(/(^"|"$)/g,"")||void 0,Expires:n?new Date(n):void 0,LastModified:c?new Date(c):void 0,Metadata:Object.keys(d).length>0?d:void 0}}async headObject(t,s){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"HEAD",signal:s?.signal});if(!e.ok){const l=await e.text();throw new Error(`Failed to head object: ${e.status} ${l}`)}const o=e.headers.get("Content-Length"),r=e.headers.get("Content-Type"),i=e.headers.get("ETag"),n=e.headers.get("Expires"),c=e.headers.get("Last-Modified"),d={};for(const[l,u]of e.headers.entries())if(l.toLowerCase().startsWith("x-amz-meta-")){const m=l.toLowerCase().replace("x-amz-meta-","");d[m]=u}return{ContentLength:o?Number(o):void 0,ContentType:r||void 0,ETag:i?.replaceAll(/(^"|"$)/g,"")||void 0,Expires:n?new Date(n):void 0,LastModified:c?new Date(c):void 0,Metadata:Object.keys(d).length>0?d:void 0}}async deleteObject(t,s){const a=this.buildUrl(t.Key),e=await this.aws.fetch(a,{method:"DELETE",signal:s?.signal});if(!e.ok){const o=await e.text();throw new Error(`Failed to delete object: ${e.status} ${o}`)}}async copyObject(t,s){const a={"x-amz-copy-source":t.CopySource};t.StorageClass&&(a["x-amz-storage-class"]=t.StorageClass);let e=this.buildUrl(t.Key);t.Bucket!==this.bucket&&(e=e.replace(this.bucket,t.Bucket));const o=await this.aws.fetch(e,{headers:a,method:"PUT",signal:s?.signal});if(!o.ok){const r=await o.text();throw new Error(`Failed to copy object: ${o.status} ${r}`)}}async listObjectsV2(t,s){const a={"list-type":"2"};t.MaxKeys&&(a["max-keys"]=String(t.MaxKeys)),t.ContinuationToken&&(a["continuation-token"]=t.ContinuationToken);const e=this.buildUrl("",a),o=await this.aws.fetch(e,{method:"GET",signal:s?.signal}),r=await o.text();if(!o.ok)throw new Error(`Failed to list objects: ${o.status} ${r}`);const i=g(r),n=i.ListBucketResult||i,c=n.Contents||(Array.isArray(n.Contents)?n.Contents:[]);return{Contents:Array.isArray(c)?c.map(d=>({Key:d.Key,LastModified:d.LastModified?new Date(String(d.LastModified)):void 0})):[],IsTruncated:n.IsTruncated==="true"||n.IsTruncated===!0,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(t){const s={partNumber:String(t.PartNumber),uploadId:t.UploadId,"X-Amz-Expires":String(t.expiresIn)};return this.buildUrl(t.Key,s)}async putObject(t){const s=this.buildUrl(t.Key),a={};if(t.ContentType&&(a["Content-Type"]=t.ContentType),t.ContentLength!==void 0&&(a["Content-Length"]=String(t.ContentLength)),t.Metadata)for(const[r,i]of Object.entries(t.Metadata))a[`x-amz-meta-${r}`]=i;let e;t.Body===void 0?e=void 0:t.Body instanceof Uint8Array?e=new Uint8Array(t.Body):t.Body instanceof ReadableStream?e=t.Body:e=void 0;const o=await this.aws.fetch(s,{body:e,headers:a,method:"PUT"});if(!o.ok){const r=await o.text();throw new Error(`Failed to put object: ${o.status} ${r}`)}}async checkBucketAccess(t){const s=this.buildUrl(""),a=await this.aws.fetch(s,{method:"HEAD"});if(!a.ok&&a.status!==404){const e=await a.text();throw new Error(`Failed to access bucket: ${a.status} ${e}`)}}buildUrl(t,s){const a=new URL(t,this.endpoint);if(s)for(const[e,o]of Object.entries(s))a.searchParams.set(e,o);return a.toString()}streamToReadable(t){return w.fromWeb(t)}}var A=Object.defineProperty,v=p((h,t)=>A(h,"name",{value:t,configurable:!0}),"n");class S extends C{static{p(this,"l")}constructor(t){super(t),this.config=t;const s=t.bucket||process.env.S3_BUCKET||process.env.AWS_S3_BUCKET;if(!s)throw new Error("S3 bucket is not defined");this.bucket=s,this.adapter=new $({accessKeyId:t.accessKeyId,bucket:s,endpoint:t.endpoint,region:t.region,secretAccessKey:t.secretAccessKey,service:t.service,sessionToken:t.sessionToken}),this.adapter.checkBucketAccess({Bucket:s}).catch(a=>{throw a})}config;static{v(this,"AwsLightMetaStorage")}adapter;bucket;async get(t){const s=this.getMetaName(t),{Expires:a,Metadata:e}=await this.adapter.headObject({Bucket:this.bucket,Key:s});if(a&&x({expiredAt:a}))throw await this.delete(s),new Error(`Metafile ${t} not found`);if(e?.metadata!==void 0){const o=JSON.parse(decodeURIComponent(e.metadata));return o.metadata&&typeof o.metadata=="string"&&(o.metadata=T(o.metadata)),o}throw new Error(`Metafile ${t} not found`)}async touch(t,s){return this.save(t,s)}async delete(t){await this.adapter.deleteObject({Bucket:this.bucket,Key:this.getMetaName(t)})}async save(t,s){const a={...s};a.metadata&&(a.metadata=k(s.metadata));const e=encodeURIComponent(JSON.stringify(a));return await this.adapter.putObject({Bucket:this.bucket,ContentLength:0,ContentType:"application/json",Key:this.getMetaName(t),Metadata:{metadata:e}}),s}}export{$ as C,S as l};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Readable as w}from"node:stream";import{S as p}from"./index-B4ETk0Lu.js";import{throwErrorCode as f,ERRORS as h}from"./ERRORS-CyOuSMLY.js";import{B as c}from"./storage-uhIhcN-O.js";import b from"./MemoryMetaStorage-DEzfBNgL.js";import l from"./File-BhfUgJjs.js";import{o as u}from"./get-file-status-DLS18Zvd.js";import{o as T}from"./has-content-Bx2p8Okx.js";import{u as A}from"./update-size-DANV7aa2.js";class F extends c{static name="memory";checksumTypes=["md5"];supportsRange=!0;meta;store;constructor(e={}){if(super(e),this.store=new Map,this.meta=e.metaStorage??new b({...e.metaStorageConfig,logger:this.logger}),e.initial)for(const[s,t]of Object.entries(e.initial)){c.assertSafeId(s);const a=Buffer.from(t),r=new Date().toISOString(),n=p(a);this.store.set(s,{bytes:a,contentType:"application/octet-stream",createdAt:r,eTag:n,metadata:{},modifiedAt:r});const i=new l({contentType:"application/octet-stream",id:s,metadata:{name:s,size:a.length},originalName:s,size:a.length});i.name=s,i.bytesWritten=a.length,i.ETag=n,i.createdAt=r,i.modifiedAt=r,i.status=u(i),this.meta.save(s,i).catch(()=>{})}}get raw(){return this.store}async create(e,s){return this.instrumentOperation("create",async()=>{const t=new l(e);return t.name=this.namingFunction(t),c.assertSafeId(t.name),await this.validate(t),t.bytesWritten=0,t.status=u(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,s){return this.instrumentOperation("write",async()=>{const t=await this.getMeta(e.id);if(!T(e))return t;const{body:a,start:r=0}=e,n=[];for await(const o of a)Buffer.isBuffer(o)?n.push(o):typeof o=="string"?n.push(Buffer.from(o)):ArrayBuffer.isView(o)?n.push(Buffer.from(o.buffer,o.byteOffset,o.byteLength)):n.push(Buffer.from(o));const i=Buffer.concat(n),m=this.store.get(t.name)?.bytes;let d;r===0||!m?d=i:d=Buffer.concat([m.subarray(0,r),i]);const y=new Date().toISOString(),g={bytes:d,contentType:t.contentType,createdAt:this.store.get(t.name)?.createdAt??y,eTag:p(d),metadata:{...t.metadata},modifiedAt:y};return this.store.set(t.name,g),t.bytesWritten=d.length,t.ETag=g.eTag,t.modifiedAt=g.modifiedAt,A(t,d.length),t.status=u(t),await this.saveMeta(t),t.status==="completed"&&await this.onComplete(t,{}),t})}async get({id:e},s){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);if(i>m||i>=a.bytes.length)return f(h.BAD_REQUEST,`Invalid range ${i}-${n.end??""}`);r=a.bytes.subarray(i,m+1)}return{content:r,contentType:a.contentType,ETag:a.eTag,expiredAt:t.expiredAt,id:e,metadata:{...a.metadata},modifiedAt:a.modifiedAt,name:t.name,originalName:t.originalName,size:r.length}})}async getStream({id:e},s){return this.instrumentOperation("getStream",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);r=a.bytes.subarray(i,m+1)}return{headers:{"Content-Length":String(r.length),"Content-Type":a.contentType,ETag:a.eTag,"Last-Modified":a.modifiedAt},size:r.length,stream:w.from(r)}})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const s=await this.meta.get(e);return this.store.has(s.name)}catch{return!1}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{const s=await this.getMeta(e);this.store.delete(s.name),await this.deleteMeta(e);const t={...s,status:"deleted"};return await this.onDelete(t),t})}async copy(e,s){return this.instrumentOperation("copy",async()=>{c.assertSafeId(e),c.assertSafeId(s);const t=await this.getMeta(e),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);const r=new Date().toISOString();this.store.set(s,{...a,bytes:Buffer.from(a.bytes),metadata:{...a.metadata},modifiedAt:r});const n={...t,ETag:a.eTag,id:s,name:s,modifiedAt:r};return await this.saveMeta(n),n})}async move(e,s){return this.instrumentOperation("move",async()=>{if(e===s)return this.getMeta(e);const t=await this.copy(e,s);return await this.delete({id:e}),t})}async list(){return this.instrumentOperation("list",async()=>{const e=[];for(const[s,t]of this.store)e.push({contentType:t.contentType,createdAt:t.createdAt,ETag:t.eTag,id:s,metadata:{...t.metadata},modifiedAt:t.modifiedAt,name:s,size:t.bytes.length});return e})}async getReadUrl(e){return c.assertSafeId(e),`memory://${e}`}async getUploadUrl(e){return c.assertSafeId(e),`memory://${e}`}}export{F as default};
|