main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
import StorageFileApi from './packages/StorageFileApi';
import StorageBucketApi from './packages/StorageBucketApi';
import { Fetch } from './lib/fetch';
export declare class StorageClient extends StorageBucketApi {
constructor(url: string, headers?: {
[key: string]: string;
}, fetch?: Fetch);
/**
* Perform file operation in a bucket.
*
* @param id The bucket id to operate on.
*/
from(id: string): StorageFileApi;
}
//# sourceMappingURL=StorageClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"StorageClient.d.ts","sourceRoot":"","sources":["../../src/StorageClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,2BAA2B,CAAA;AACtD,OAAO,gBAAgB,MAAM,6BAA6B,CAAA;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAEnC,qBAAa,aAAc,SAAQ,gBAAgB;gBACrC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAO,EAAE,KAAK,CAAC,EAAE,KAAK;IAI/E;;;;OAIG;IACH,IAAI,CAAC,EAAE,EAAE,MAAM,GAAG,cAAc;CAGjC"}

View File

@@ -0,0 +1,16 @@
import StorageFileApi from './packages/StorageFileApi';
import StorageBucketApi from './packages/StorageBucketApi';
export class StorageClient extends StorageBucketApi {
constructor(url, headers = {}, fetch) {
super(url, headers, fetch);
}
/**
* Perform file operation in a bucket.
*
* @param id The bucket id to operate on.
*/
from(id) {
return new StorageFileApi(this.url, this.headers, id, this.fetch);
}
}
//# sourceMappingURL=StorageClient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"StorageClient.js","sourceRoot":"","sources":["../../src/StorageClient.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,2BAA2B,CAAA;AACtD,OAAO,gBAAgB,MAAM,6BAA6B,CAAA;AAG1D,MAAM,OAAO,aAAc,SAAQ,gBAAgB;IACjD,YAAY,GAAW,EAAE,UAAqC,EAAE,EAAE,KAAa;QAC7E,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC,CAAA;IAC5B,CAAC;IAED;;;;OAIG;IACH,IAAI,CAAC,EAAU;QACb,OAAO,IAAI,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAA;IACnE,CAAC;CACF"}

View File

@@ -0,0 +1,4 @@
export { StorageClient as StorageClient } from './StorageClient';
export * from './lib/types';
export * from './lib/errors';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAChE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA"}

View File

@@ -0,0 +1,4 @@
export { StorageClient as StorageClient } from './StorageClient';
export * from './lib/types';
export * from './lib/errors';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAChE,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA"}

View File

@@ -0,0 +1,4 @@
export declare const DEFAULT_HEADERS: {
'X-Client-Info': string;
};
//# sourceMappingURL=constants.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,eAAe;;CAA+C,CAAA"}

View File

@@ -0,0 +1,3 @@
import { version } from './version';
export const DEFAULT_HEADERS = { 'X-Client-Info': `storage-js/${version}` };
//# sourceMappingURL=constants.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/lib/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,eAAe,EAAE,cAAc,OAAO,EAAE,EAAE,CAAA"}

View File

@@ -0,0 +1,19 @@
export declare class StorageError extends Error {
protected __isStorageError: boolean;
constructor(message: string);
}
export declare function isStorageError(error: unknown): error is StorageError;
export declare class StorageApiError extends StorageError {
status: number;
constructor(message: string, status: number);
toJSON(): {
name: string;
message: string;
status: number;
};
}
export declare class StorageUnknownError extends StorageError {
originalError: unknown;
constructor(message: string, originalError: unknown);
}
//# sourceMappingURL=errors.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,YAAa,SAAQ,KAAK;IACrC,SAAS,CAAC,gBAAgB,UAAO;gBAErB,OAAO,EAAE,MAAM;CAI5B;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAEpE;AAED,qBAAa,eAAgB,SAAQ,YAAY;IAC/C,MAAM,EAAE,MAAM,CAAA;gBAEF,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAM3C,MAAM;;;;;CAOP;AAED,qBAAa,mBAAoB,SAAQ,YAAY;IACnD,aAAa,EAAE,OAAO,CAAA;gBAEV,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO;CAKpD"}

View File

@@ -0,0 +1,32 @@
export class StorageError extends Error {
constructor(message) {
super(message);
this.__isStorageError = true;
this.name = 'StorageError';
}
}
export function isStorageError(error) {
return typeof error === 'object' && error !== null && '__isStorageError' in error;
}
export class StorageApiError extends StorageError {
constructor(message, status) {
super(message);
this.name = 'StorageApiError';
this.status = status;
}
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status,
};
}
}
export class StorageUnknownError extends StorageError {
constructor(message, originalError) {
super(message);
this.name = 'StorageUnknownError';
this.originalError = originalError;
}
}
//# sourceMappingURL=errors.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/lib/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,YAAa,SAAQ,KAAK;IAGrC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QAHN,qBAAgB,GAAG,IAAI,CAAA;QAI/B,IAAI,CAAC,IAAI,GAAG,cAAc,CAAA;IAC5B,CAAC;CACF;AAED,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,kBAAkB,IAAI,KAAK,CAAA;AACnF,CAAC;AAED,MAAM,OAAO,eAAgB,SAAQ,YAAY;IAG/C,YAAY,OAAe,EAAE,MAAc;QACzC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAA;QAC7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAED,MAAM;QACJ,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAA;IACH,CAAC;CACF;AAED,MAAM,OAAO,mBAAoB,SAAQ,YAAY;IAGnD,YAAY,OAAe,EAAE,aAAsB;QACjD,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAA;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAA;IACpC,CAAC;CACF"}

View File

@@ -0,0 +1,15 @@
import { FetchParameters } from './types';
export declare type Fetch = typeof fetch;
export interface FetchOptions {
headers?: {
[key: string]: string;
};
noResolveJson?: boolean;
}
export declare type RequestMethodType = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD';
export declare function get(fetcher: Fetch, url: string, options?: FetchOptions, parameters?: FetchParameters): Promise<any>;
export declare function post(fetcher: Fetch, url: string, body: object, options?: FetchOptions, parameters?: FetchParameters): Promise<any>;
export declare function put(fetcher: Fetch, url: string, body: object, options?: FetchOptions, parameters?: FetchParameters): Promise<any>;
export declare function head(fetcher: Fetch, url: string, options?: FetchOptions, parameters?: FetchParameters): Promise<any>;
export declare function remove(fetcher: Fetch, url: string, body: object, options?: FetchOptions, parameters?: FetchParameters): Promise<any>;
//# sourceMappingURL=fetch.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAEzC,oBAAY,KAAK,GAAG,OAAO,KAAK,CAAA;AAEhC,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE;QACR,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KACtB,CAAA;IACD,aAAa,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,oBAAY,iBAAiB,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAA;AAkE1E,wBAAsB,GAAG,CACvB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd;AAED,wBAAsB,IAAI,CACxB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd;AAED,wBAAsB,GAAG,CACvB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd;AAED,wBAAsB,IAAI,CACxB,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAWd;AAED,wBAAsB,MAAM,CAC1B,OAAO,EAAE,KAAK,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,YAAY,EACtB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CAAC,GAAG,CAAC,CAEd"}

View File

@@ -0,0 +1,81 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { StorageApiError, StorageUnknownError } from './errors';
import { resolveResponse } from './helpers';
const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
const handleError = (error, reject, options) => __awaiter(void 0, void 0, void 0, function* () {
const Res = yield resolveResponse();
if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) {
error
.json()
.then((err) => {
reject(new StorageApiError(_getErrorMessage(err), error.status || 500));
})
.catch((err) => {
reject(new StorageUnknownError(_getErrorMessage(err), err));
});
}
else {
reject(new StorageUnknownError(_getErrorMessage(error), error));
}
});
const _getRequestParams = (method, options, parameters, body) => {
const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} };
if (method === 'GET') {
return params;
}
params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers);
if (body) {
params.body = JSON.stringify(body);
}
return Object.assign(Object.assign({}, params), parameters);
};
function _handleRequest(fetcher, method, url, options, parameters, body) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
fetcher(url, _getRequestParams(method, options, parameters, body))
.then((result) => {
if (!result.ok)
throw result;
if (options === null || options === void 0 ? void 0 : options.noResolveJson)
return result;
return result.json();
})
.then((data) => resolve(data))
.catch((error) => handleError(error, reject, options));
});
});
}
export function get(fetcher, url, options, parameters) {
return __awaiter(this, void 0, void 0, function* () {
return _handleRequest(fetcher, 'GET', url, options, parameters);
});
}
export function post(fetcher, url, body, options, parameters) {
return __awaiter(this, void 0, void 0, function* () {
return _handleRequest(fetcher, 'POST', url, options, parameters, body);
});
}
export function put(fetcher, url, body, options, parameters) {
return __awaiter(this, void 0, void 0, function* () {
return _handleRequest(fetcher, 'PUT', url, options, parameters, body);
});
}
export function head(fetcher, url, options, parameters) {
return __awaiter(this, void 0, void 0, function* () {
return _handleRequest(fetcher, 'HEAD', url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters);
});
}
export function remove(fetcher, url, body, options, parameters) {
return __awaiter(this, void 0, void 0, function* () {
return _handleRequest(fetcher, 'DELETE', url, options, parameters, body);
});
}
//# sourceMappingURL=fetch.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAA;AAC/D,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAc3C,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAU,EAAE,CAC5C,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,iBAAiB,IAAI,GAAG,CAAC,KA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AAM,UAAgB,GAAG,CACvB,OAAc,EACd,GAAW,EACX,IAAY,EACZ,OAAsB,EACtB,UAA4B;;QAE5B,OAAO,cAAc,CAAC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;IACvE,CAAC;CAAA;AAED,MAAM,UAAgB,IAAI,CACxB,OAAc,EACd,GAAW,EACX,OAAsB,EACtB,UAA4B;;QAE5B,OAAO,cAAc,CACnB,OAAO,EACP,MAAM,EACN,GAAG,kCAEE,OAAO,KACV,aAAa,EAAE,IAAI,KAErB,UAAU,CACX,CAAA;IACH,CAAC;CAAA;AAED,MAAM,UAAgB,MAAM,CAC1B,OAAc,EACd,GAAW,EACX,IAAY,EACZ,OAAsB,EACtB,UAA4B;;QAE5B,OAAO,cAAc,CAAC,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,CAAC,CAAA;IAC1E,CAAC;CAAA"}

View File

@@ -0,0 +1,6 @@
declare type Fetch = typeof fetch;
export declare const resolveFetch: (customFetch?: typeof fetch | undefined) => Fetch;
export declare const resolveResponse: () => Promise<typeof Response>;
export declare const recursiveToCamel: (item: Record<string, any>) => unknown;
export {};
//# sourceMappingURL=helpers.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":"AAAA,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,8CAA0B,KAWlD,CAAA;AAED,eAAO,MAAM,eAAe,QAAa,QAAQ,eAAe,CAO/D,CAAA;AAED,eAAO,MAAM,gBAAgB,SAAU,OAAO,MAAM,EAAE,GAAG,CAAC,KAAG,OAc5D,CAAA"}

View File

@@ -0,0 +1,44 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
export const resolveFetch = (customFetch) => {
let _fetch;
if (customFetch) {
_fetch = customFetch;
}
else if (typeof fetch === 'undefined') {
_fetch = (...args) => import('@supabase/node-fetch').then(({ default: fetch }) => fetch(...args));
}
else {
_fetch = fetch;
}
return (...args) => _fetch(...args);
};
export const resolveResponse = () => __awaiter(void 0, void 0, void 0, function* () {
if (typeof Response === 'undefined') {
// @ts-ignore
return (yield import('@supabase/node-fetch')).Response;
}
return Response;
});
export const recursiveToCamel = (item) => {
if (Array.isArray(item)) {
return item.map((el) => recursiveToCamel(el));
}
else if (typeof item === 'function' || item !== Object(item)) {
return item;
}
const result = {};
Object.entries(item).forEach(([key, value]) => {
const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, ''));
result[newKey] = recursiveToCamel(value);
});
return result;
};
//# sourceMappingURL=helpers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../../src/lib/helpers.ts"],"names":[],"mappings":";;;;;;;;;AAEA,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,CAAC,GAAG,IAAI,EAAE,EAAE,CACnB,MAAM,CAAC,sBAA6B,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,CAAA;KACrF;SAAM;QACL,M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* from './constants';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/lib/index.ts"],"names":[],"mappings":"AAAA,cAAc,8BAA8B,CAAA;AAC5C,cAAc,4BAA4B,CAAA;AAC1C,cAAc,SAAS,CAAA;AACvB,cAAc,aAAa,CAAA"}

View File

@@ -0,0 +1,5 @@
export * from '../packages/StorageBucketApi';
export * from '../packages/StorageFileApi';
export * from './types';
export * from './constants';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/lib/index.ts"],"names":[],"mappings":"AAAA,cAAc,8BAA8B,CAAA;AAC5C,cAAc,4BAA4B,CAAA;AAC1C,cAAc,SAAS,CAAA;AACvB,cAAc,aAAa,CAAA"}

View File

@@ -0,0 +1,132 @@
export interface Bucket {
id: string;
name: string;
owner: string;
file_size_limit?: number;
allowed_mime_types?: string[];
created_at: string;
updated_at: string;
public: boolean;
}
export interface FileObject {
name: string;
bucket_id: string;
owner: string;
id: string;
updated_at: string;
created_at: string;
last_accessed_at: string;
metadata: Record<string, any>;
buckets: Bucket;
}
export interface FileObjectV2 {
id: string;
version: string;
name: string;
bucket_id: string;
updated_at: string;
created_at: string;
last_accessed_at: string;
size?: number;
cache_control?: string;
content_type?: string;
etag?: string;
last_modified?: string;
metadata?: Record<string, any>;
}
export interface SortBy {
column?: string;
order?: string;
}
export interface FileOptions {
/**
* The number of seconds the asset is cached in the browser and in the Supabase CDN. This is set in the `Cache-Control: max-age=<seconds>` header. Defaults to 3600 seconds.
*/
cacheControl?: string;
/**
* the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`.
*/
contentType?: string;
/**
* When upsert is set to true, the file is overwritten if it exists. When set to false, an error is thrown if the object already exists. Defaults to false.
*/
upsert?: boolean;
/**
* The duplex option is a string parameter that enables or disables duplex streaming, allowing for both reading and writing data in the same stream. It can be passed as an option to the fetch() method.
*/
duplex?: string;
/**
* The metadata option is an object that allows you to store additional information about the file. This information can be used to filter and search for files. The metadata object can contain any key-value pairs you want to store.
*/
metadata?: Record<string, any>;
/**
* Optionally add extra headers
*/
headers?: Record<string, string>;
}
export interface DestinationOptions {
destinationBucket?: string;
}
export interface SearchOptions {
/**
* The number of files you want to be returned.
*/
limit?: number;
/**
* The starting position.
*/
offset?: number;
/**
* The column to sort by. Can be any column inside a FileObject.
*/
sortBy?: SortBy;
/**
* The search string to filter files by.
*/
search?: string;
}
export interface FetchParameters {
/**
* Pass in an AbortController's signal to cancel the request.
*/
signal?: AbortSignal;
}
export interface Metadata {
name: string;
}
export interface TransformOptions {
/**
* The width of the image in pixels.
*/
width?: number;
/**
* The height of the image in pixels.
*/
height?: number;
/**
* The resize mode can be cover, contain or fill. Defaults to cover.
* Cover resizes the image to maintain it's aspect ratio while filling the entire width and height.
* Contain resizes the image to maintain it's aspect ratio while fitting the entire image within the width and height.
* Fill resizes the image to fill the entire width and height. If the object's aspect ratio does not match the width and height, the image will be stretched to fit.
*/
resize?: 'cover' | 'contain' | 'fill';
/**
* Set the quality of the returned image.
* A number from 20 to 100, with 100 being the highest quality.
* Defaults to 80
*/
quality?: number;
/**
* Specify the format of the image requested.
*
* When using 'origin' we force the format to be the same as the original image.
* When this option is not passed in, images are optimized to modern image formats like Webp.
*/
format?: 'origin';
}
declare type CamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}` ? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}` : S;
export declare type Camelize<T> = {
[K in keyof T as CamelCase<Extract<K, string>>]: T[K];
};
export {};
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,MAAM;IACrB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;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E,GAClD,CAAC,CAAA;AAEL,oBAAY,QAAQ,CAAC,CAAC,IAAI;KACvB,CAAC,IAAI,MAAM,CAAC,IAAI,SAAS,CAAC,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CACtD,CAAA"}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/types.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,2 @@
export declare const version = "2.7.1";
//# sourceMappingURL=version.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,OAAO,UAAU,CAAA"}

View File

@@ -0,0 +1,3 @@
// generated by genversion
export const version = '2.7.1';
//# sourceMappingURL=version.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../../src/lib/version.ts"],"names":[],"mappings":"AAAA,0BAA0B;AAC1B,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAA"}

View File

@@ -0,0 +1,114 @@
import { StorageError } from '../lib/errors';
import { Fetch } from '../lib/fetch';
import { Bucket } from '../lib/types';
export default class StorageBucketApi {
protected url: string;
protected headers: {
[key: string]: string;
};
protected fetch: Fetch;
constructor(url: string, headers?: {
[key: string]: string;
}, fetch?: Fetch);
/**
* Retrieves the details of all Storage buckets within an existing project.
*/
listBuckets(): Promise<{
data: Bucket[];
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Retrieves the details of an existing Storage bucket.
*
* @param id The unique identifier of the bucket you would like to retrieve.
*/
getBucket(id: string): Promise<{
data: Bucket;
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Creates a new Storage bucket
*
* @param id A unique identifier for the bucket you are creating.
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private.
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
* The global file size limit takes precedence over this value.
* The default value is null, which doesn't set a per bucket file size limit.
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
* The default value is null, which allows files with all mime types to be uploaded.
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
* @returns newly created bucket id
*/
createBucket(id: string, options?: {
public: boolean;
fileSizeLimit?: number | string | null;
allowedMimeTypes?: string[] | null;
}): Promise<{
data: Pick<Bucket, 'name'>;
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Updates a Storage bucket
*
* @param id A unique identifier for the bucket you are updating.
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations.
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
* The global file size limit takes precedence over this value.
* The default value is null, which doesn't set a per bucket file size limit.
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
* The default value is null, which allows files with all mime types to be uploaded.
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
*/
updateBucket(id: string, options: {
public: boolean;
fileSizeLimit?: number | string | null;
allowedMimeTypes?: string[] | null;
}): Promise<{
data: {
message: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Removes all objects inside a single bucket.
*
* @param id The unique identifier of the bucket you would like to empty.
*/
emptyBucket(id: string): Promise<{
data: {
message: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Deletes an existing bucket. A bucket can't be deleted with existing objects inside it.
* You must first `empty()` the bucket.
*
* @param id The unique identifier of the bucket you would like to delete.
*/
deleteBucket(id: string): Promise<{
data: {
message: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
}
//# sourceMappingURL=StorageBucketApi.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"StorageBucketApi.d.ts","sourceRoot":"","sources":["../../../src/packages/StorageBucketApi.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;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAwBD;;;;;;;;;;;OAWG;IACG,YAAY,CAChB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE;QACP,MAAM,EAAE,OAAO,CAAA;QACf,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;QACtC,gBAAgB,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,CAAA;KACnC,GACA,OAAO,CACN;QACE,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAwBD;;;;OAIG;IACG,WAAW,CACf,EAAE,EAAE,MAAM,GACT,OAAO,CACN;QACE,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAkBD;;;;;OAKG;IACG,YAAY,CAChB,EAAE,EAAE,MAAM,GACT,OAAO,CACN;QACE,IAAI,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;QACzB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;CAiBF"}

View File

@@ -0,0 +1,163 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { DEFAULT_HEADERS } from '../lib/constants';
import { isStorageError } from '../lib/errors';
import { get, post, put, remove } from '../lib/fetch';
import { resolveFetch } from '../lib/helpers';
export default class StorageBucketApi {
constructor(url, headers = {}, fetch) {
this.url = url;
this.headers = Object.assign(Object.assign({}, DEFAULT_HEADERS), headers);
this.fetch = resolveFetch(fetch);
}
/**
* Retrieves the details of all Storage buckets within an existing project.
*/
listBuckets() {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield get(this.fetch, `${this.url}/bucket`, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Retrieves the details of an existing Storage bucket.
*
* @param id The unique identifier of the bucket you would like to retrieve.
*/
getBucket(id) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield get(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Creates a new Storage bucket
*
* @param id A unique identifier for the bucket you are creating.
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private.
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
* The global file size limit takes precedence over this value.
* The default value is null, which doesn't set a per bucket file size limit.
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
* The default value is null, which allows files with all mime types to be uploaded.
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
* @returns newly created bucket id
*/
createBucket(id, options = {
public: false,
}) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield post(this.fetch, `${this.url}/bucket`, {
id,
name: id,
public: options.public,
file_size_limit: options.fileSizeLimit,
allowed_mime_types: options.allowedMimeTypes,
}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Updates a Storage bucket
*
* @param id A unique identifier for the bucket you are updating.
* @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations.
* @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket.
* The global file size limit takes precedence over this value.
* The default value is null, which doesn't set a per bucket file size limit.
* @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload.
* The default value is null, which allows files with all mime types to be uploaded.
* Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
*/
updateBucket(id, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield put(this.fetch, `${this.url}/bucket/${id}`, {
id,
name: id,
public: options.public,
file_size_limit: options.fileSizeLimit,
allowed_mime_types: options.allowedMimeTypes,
}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Removes all objects inside a single bucket.
*
* @param id The unique identifier of the bucket you would like to empty.
*/
emptyBucket(id) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield post(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Deletes an existing bucket. A bucket can't be deleted with existing objects inside it.
* You must first `empty()` the bucket.
*
* @param id The unique identifier of the bucket you would like to delete.
*/
deleteBucket(id) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield remove(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
}
//# sourceMappingURL=StorageBucketApi.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"StorageBucketApi.js","sourceRoot":"","sources":["../../../src/packages/StorageBucketApi.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kB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// <reference types="node" />
import { StorageError } from '../lib/errors';
import { Fetch } from '../lib/fetch';
import { FileObject, FileOptions, SearchOptions, FetchParameters, TransformOptions, DestinationOptions, FileObjectV2, Camelize } from '../lib/types';
declare type FileBody = ArrayBuffer | ArrayBufferView | Blob | Buffer | File | FormData | NodeJS.ReadableStream | ReadableStream<Uint8Array> | URLSearchParams | string;
export default class StorageFileApi {
protected url: string;
protected headers: {
[key: string]: string;
};
protected bucketId?: string;
protected fetch: Fetch;
constructor(url: string, headers?: {
[key: string]: string;
}, bucketId?: string, fetch?: Fetch);
/**
* Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one.
*
* @param method HTTP method.
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
*/
private uploadOrUpdate;
/**
* Uploads a file to an existing bucket.
*
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
*/
upload(path: string, fileBody: FileBody, fileOptions?: FileOptions): Promise<{
data: {
id: string;
path: string;
fullPath: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Upload a file with a token generated from `createSignedUploadUrl`.
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param token The token generated from `createSignedUploadUrl`
* @param fileBody The body of the file to be stored in the bucket.
*/
uploadToSignedUrl(path: string, token: string, fileBody: FileBody, fileOptions?: FileOptions): Promise<{
data: {
path: string;
fullPath: any;
};
error: null;
} | {
data: null;
error: any;
}>;
/**
* Creates a signed upload URL.
* Signed upload URLs can be used to upload files to the bucket without further authentication.
* They are valid for 2 hours.
* @param path The file path, including the current file name. For example `folder/image.png`.
* @param options.upsert If set to true, allows the file to be overwritten if it already exists.
*/
createSignedUploadUrl(path: string, options?: {
upsert: boolean;
}): Promise<{
data: {
signedUrl: string;
token: string;
path: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Replaces an existing file at the specified path with a new one.
*
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update.
* @param fileBody The body of the file to be stored in the bucket.
*/
update(path: string, fileBody: ArrayBuffer | ArrayBufferView | Blob | Buffer | File | FormData | NodeJS.ReadableStream | ReadableStream<Uint8Array> | URLSearchParams | string, fileOptions?: FileOptions): Promise<{
data: {
id: string;
path: string;
fullPath: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Moves an existing file to a new path in the same bucket.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-new.png`.
* @param options The destination options.
*/
move(fromPath: string, toPath: string, options?: DestinationOptions): Promise<{
data: {
message: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Copies an existing file to a new path in the same bucket.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-copy.png`.
* @param options The destination options.
*/
copy(fromPath: string, toPath: string, options?: DestinationOptions): Promise<{
data: {
path: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Creates a signed URL. Use a signed URL to share a file for a fixed amount of time.
*
* @param path The file path, including the current file name. For example `folder/image.png`.
* @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
* @param options.transform Transform the asset before serving it to the client.
*/
createSignedUrl(path: string, expiresIn: number, options?: {
download?: string | boolean;
transform?: TransformOptions;
}): Promise<{
data: {
signedUrl: string;
};
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time.
*
* @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`.
* @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
*/
createSignedUrls(paths: string[], expiresIn: number, options?: {
download: string | boolean;
}): Promise<{
data: {
error: string | null;
path: string | null;
signedUrl: string;
}[];
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead.
*
* @param path The full path and file name of the file to be downloaded. For example `folder/image.png`.
* @param options.transform Transform the asset before serving it to the client.
*/
download(path: string, options?: {
transform?: TransformOptions;
}): Promise<{
data: Blob;
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Retrieves the details of an existing file.
* @param path
*/
info(path: string): Promise<{
data: Camelize<FileObjectV2>;
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Checks the existence of a file.
* @param path
*/
exists(path: string): Promise<{
data: boolean;
error: null;
} | {
data: boolean;
error: StorageError;
}>;
/**
* A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.
* This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.
*
* @param path The path and name of the file to generate the public URL for. For example `folder/image.png`.
* @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
* @param options.transform Transform the asset before serving it to the client.
*/
getPublicUrl(path: string, options?: {
download?: string | boolean;
transform?: TransformOptions;
}): {
data: {
publicUrl: string;
};
};
/**
* Deletes files within the same bucket
*
* @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`].
*/
remove(paths: string[]): Promise<{
data: FileObject[];
error: null;
} | {
data: null;
error: StorageError;
}>;
/**
* Get file metadata
* @param id the file id to retrieve metadata
*/
/**
* Update file metadata
* @param id the file id to update metadata
* @param meta the new file metadata
*/
/**
* Lists all the files within a bucket.
* @param path The folder path.
*/
list(path?: string, options?: SearchOptions, parameters?: FetchParameters): Promise<{
data: FileObject[];
error: null;
} | {
data: null;
error: StorageError;
}>;
protected encodeMetadata(metadata: Record<string, any>): string;
toBase64(data: string): string;
private _getFinalPath;
private _removeEmptyFolders;
private transformOptsToQueryString;
}
export {};
//# sourceMappingURL=StorageFileApi.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"StorageFileApi.d.ts","sourceRoot":"","sources":["../../../src/packages/StorageFileApi.ts"],"names":[],"mappings":";AAAA,OAAO,EAAkB,YAAY,EAAuB,MAAM,eAAe,CAAA;AACjF,OAAO,EAAE,KAAK,EAA2B,MAAM,cAAc,CAAA;AAE7D,OAAO,EACL,UAAU,EACV,WAAW,EACX,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,YAAY,EACZ,QAAQ,EACT,MAAM,cAAc,CAAA;AAiBrB,aAAK,QAAQ,GACT,WAAW,GACX,eAAe,GACf,IAAI,GACJ,MAAM,GACN,IAAI,GACJ,QAAQ,GACR,MAAM,CAAC,cAAc,GACrB,cAAc,CAAC,UAAU,CAAC,GAC1B,eAAe,GACf,MAAM,CAAA;AAEV,MAAM,CAAC,OAAO,OAAO,cAAc;IACjC,SAAS,CAAC,GAAG,EAAE,MAAM,CAAA;IACrB,SAAS,CAAC,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAA;IAC5C,SAAS,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;IAC3B,SAAS,CAAC,KAAK,EAAE,KAAK,CAAA;gBAGpB,GAAG,EAAE,MAAM,EACX,OAAO,GAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAO,EACvC,QAAQ,CAAC,EAAE,MAAM,EACjB,KAAK,CAAC,EAAE,KAAK;IAQf;;;;;;OAMG;YACW,cAAc;IAiF5B;;;;;OAKG;IACG,MAAM,CACV,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,QAAQ,EAClB,WAAW,CAAC,EAAE,WAAW,GACxB,OAAO,CACN;QACE,IAAI,EAAE;YAAE,EAAE,EAAE,MAAM,CAAC;YA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IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAkBD;;;OAGG;IAyBH;;;;OAIG;IA+BH;;;OAGG;IACG,IAAI,CACR,IAAI,CAAC,EAAE,MAAM,EACb,OAAO,CAAC,EAAE,aAAa,EACvB,UAAU,CAAC,EAAE,eAAe,GAC3B,OAAO,CACN;QACE,IAAI,EAAE,UAAU,EAAE,CAAA;QAClB,KAAK,EAAE,IAAI,CAAA;KACZ,GACD;QACE,IAAI,EAAE,IAAI,CAAA;QACV,KAAK,EAAE,YAAY,CAAA;KACpB,CACJ;IAoBD,SAAS,CAAC,cAAc,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;IAItD,QAAQ,CAAC,IAAI,EAAE,MAAM;IAOrB,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,0BAA0B;CAwBnC"}

View File

@@ -0,0 +1,550 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { isStorageError, StorageError, StorageUnknownError } from '../lib/errors';
import { get, head, post, remove } from '../lib/fetch';
import { recursiveToCamel, resolveFetch } from '../lib/helpers';
const DEFAULT_SEARCH_OPTIONS = {
limit: 100,
offset: 0,
sortBy: {
column: 'name',
order: 'asc',
},
};
const DEFAULT_FILE_OPTIONS = {
cacheControl: '3600',
contentType: 'text/plain;charset=UTF-8',
upsert: false,
};
export default class StorageFileApi {
constructor(url, headers = {}, bucketId, fetch) {
this.url = url;
this.headers = headers;
this.bucketId = bucketId;
this.fetch = resolveFetch(fetch);
}
/**
* Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one.
*
* @param method HTTP method.
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
*/
uploadOrUpdate(method, path, fileBody, fileOptions) {
return __awaiter(this, void 0, void 0, function* () {
try {
let body;
const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions);
let headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) }));
const metadata = options.metadata;
if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {
body = new FormData();
body.append('cacheControl', options.cacheControl);
if (metadata) {
body.append('metadata', this.encodeMetadata(metadata));
}
body.append('', fileBody);
}
else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {
body = fileBody;
body.append('cacheControl', options.cacheControl);
if (metadata) {
body.append('metadata', this.encodeMetadata(metadata));
}
}
else {
body = fileBody;
headers['cache-control'] = `max-age=${options.cacheControl}`;
headers['content-type'] = options.contentType;
if (metadata) {
headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata));
}
}
if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) {
headers = Object.assign(Object.assign({}, headers), fileOptions.headers);
}
const cleanPath = this._removeEmptyFolders(path);
const _path = this._getFinalPath(cleanPath);
const res = yield this.fetch(`${this.url}/object/${_path}`, Object.assign({ method, body: body, headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {})));
const data = yield res.json();
if (res.ok) {
return {
data: { path: cleanPath, id: data.Id, fullPath: data.Key },
error: null,
};
}
else {
const error = data;
return { data: null, error };
}
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Uploads a file to an existing bucket.
*
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param fileBody The body of the file to be stored in the bucket.
*/
upload(path, fileBody, fileOptions) {
return __awaiter(this, void 0, void 0, function* () {
return this.uploadOrUpdate('POST', path, fileBody, fileOptions);
});
}
/**
* Upload a file with a token generated from `createSignedUploadUrl`.
* @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
* @param token The token generated from `createSignedUploadUrl`
* @param fileBody The body of the file to be stored in the bucket.
*/
uploadToSignedUrl(path, token, fileBody, fileOptions) {
return __awaiter(this, void 0, void 0, function* () {
const cleanPath = this._removeEmptyFolders(path);
const _path = this._getFinalPath(cleanPath);
const url = new URL(this.url + `/object/upload/sign/${_path}`);
url.searchParams.set('token', token);
try {
let body;
const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions);
const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) });
if (typeof Blob !== 'undefined' && fileBody instanceof Blob) {
body = new FormData();
body.append('cacheControl', options.cacheControl);
body.append('', fileBody);
}
else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) {
body = fileBody;
body.append('cacheControl', options.cacheControl);
}
else {
body = fileBody;
headers['cache-control'] = `max-age=${options.cacheControl}`;
headers['content-type'] = options.contentType;
}
const res = yield this.fetch(url.toString(), {
method: 'PUT',
body: body,
headers,
});
const data = yield res.json();
if (res.ok) {
return {
data: { path: cleanPath, fullPath: data.Key },
error: null,
};
}
else {
const error = data;
return { data: null, error };
}
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Creates a signed upload URL.
* Signed upload URLs can be used to upload files to the bucket without further authentication.
* They are valid for 2 hours.
* @param path The file path, including the current file name. For example `folder/image.png`.
* @param options.upsert If set to true, allows the file to be overwritten if it already exists.
*/
createSignedUploadUrl(path, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
let _path = this._getFinalPath(path);
const headers = Object.assign({}, this.headers);
if (options === null || options === void 0 ? void 0 : options.upsert) {
headers['x-upsert'] = 'true';
}
const data = yield post(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers });
const url = new URL(this.url + data.url);
const token = url.searchParams.get('token');
if (!token) {
throw new StorageError('No token returned by API');
}
return { data: { signedUrl: url.toString(), path, token }, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Replaces an existing file at the specified path with a new one.
*
* @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update.
* @param fileBody The body of the file to be stored in the bucket.
*/
update(path, fileBody, fileOptions) {
return __awaiter(this, void 0, void 0, function* () {
return this.uploadOrUpdate('PUT', path, fileBody, fileOptions);
});
}
/**
* Moves an existing file to a new path in the same bucket.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-new.png`.
* @param options The destination options.
*/
move(fromPath, toPath, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield post(this.fetch, `${this.url}/object/move`, {
bucketId: this.bucketId,
sourceKey: fromPath,
destinationKey: toPath,
destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket,
}, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Copies an existing file to a new path in the same bucket.
*
* @param fromPath The original file path, including the current file name. For example `folder/image.png`.
* @param toPath The new file path, including the new file name. For example `folder/image-copy.png`.
* @param options The destination options.
*/
copy(fromPath, toPath, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield post(this.fetch, `${this.url}/object/copy`, {
bucketId: this.bucketId,
sourceKey: fromPath,
destinationKey: toPath,
destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket,
}, { headers: this.headers });
return { data: { path: data.Key }, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Creates a signed URL. Use a signed URL to share a file for a fixed amount of time.
*
* @param path The file path, including the current file name. For example `folder/image.png`.
* @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
* @param options.transform Transform the asset before serving it to the client.
*/
createSignedUrl(path, expiresIn, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
let _path = this._getFinalPath(path);
let data = yield post(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers });
const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download)
? `&download=${options.download === true ? '' : options.download}`
: '';
const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`);
data = { signedUrl };
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time.
*
* @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`.
* @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.
* @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
*/
createSignedUrls(paths, expiresIn, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield post(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers });
const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download)
? `&download=${options.download === true ? '' : options.download}`
: '';
return {
data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL
? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`)
: null }))),
error: null,
};
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead.
*
* @param path The full path and file name of the file to be downloaded. For example `folder/image.png`.
* @param options.transform Transform the asset before serving it to the client.
*/
download(path, options) {
return __awaiter(this, void 0, void 0, function* () {
const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined';
const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object';
const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {});
const queryString = transformationQuery ? `?${transformationQuery}` : '';
try {
const _path = this._getFinalPath(path);
const res = yield get(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, {
headers: this.headers,
noResolveJson: true,
});
const data = yield res.blob();
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Retrieves the details of an existing file.
* @param path
*/
info(path) {
return __awaiter(this, void 0, void 0, function* () {
const _path = this._getFinalPath(path);
try {
const data = yield get(this.fetch, `${this.url}/object/info/${_path}`, {
headers: this.headers,
});
return { data: recursiveToCamel(data), error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Checks the existence of a file.
* @param path
*/
exists(path) {
return __awaiter(this, void 0, void 0, function* () {
const _path = this._getFinalPath(path);
try {
yield head(this.fetch, `${this.url}/object/${_path}`, {
headers: this.headers,
});
return { data: true, error: null };
}
catch (error) {
if (isStorageError(error) && error instanceof StorageUnknownError) {
const originalError = error.originalError;
if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) {
return { data: false, error };
}
}
throw error;
}
});
}
/**
* A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.
* This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.
*
* @param path The path and name of the file to generate the public URL for. For example `folder/image.png`.
* @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
* @param options.transform Transform the asset before serving it to the client.
*/
getPublicUrl(path, options) {
const _path = this._getFinalPath(path);
const _queryString = [];
const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download)
? `download=${options.download === true ? '' : options.download}`
: '';
if (downloadQueryParam !== '') {
_queryString.push(downloadQueryParam);
}
const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined';
const renderPath = wantsTransformation ? 'render/image' : 'object';
const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {});
if (transformationQuery !== '') {
_queryString.push(transformationQuery);
}
let queryString = _queryString.join('&');
if (queryString !== '') {
queryString = `?${queryString}`;
}
return {
data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) },
};
}
/**
* Deletes files within the same bucket
*
* @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`].
*/
remove(paths) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield remove(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers });
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
/**
* Get file metadata
* @param id the file id to retrieve metadata
*/
// async getMetadata(
// id: string
// ): Promise<
// | {
// data: Metadata
// error: null
// }
// | {
// data: null
// error: StorageError
// }
// > {
// try {
// const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers })
// return { data, error: null }
// } catch (error) {
// if (isStorageError(error)) {
// return { data: null, error }
// }
// throw error
// }
// }
/**
* Update file metadata
* @param id the file id to update metadata
* @param meta the new file metadata
*/
// async updateMetadata(
// id: string,
// meta: Metadata
// ): Promise<
// | {
// data: Metadata
// error: null
// }
// | {
// data: null
// error: StorageError
// }
// > {
// try {
// const data = await post(
// this.fetch,
// `${this.url}/metadata/${id}`,
// { ...meta },
// { headers: this.headers }
// )
// return { data, error: null }
// } catch (error) {
// if (isStorageError(error)) {
// return { data: null, error }
// }
// throw error
// }
// }
/**
* Lists all the files within a bucket.
* @param path The folder path.
*/
list(path, options, parameters) {
return __awaiter(this, void 0, void 0, function* () {
try {
const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' });
const data = yield post(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters);
return { data, error: null };
}
catch (error) {
if (isStorageError(error)) {
return { data: null, error };
}
throw error;
}
});
}
encodeMetadata(metadata) {
return JSON.stringify(metadata);
}
toBase64(data) {
if (typeof Buffer !== 'undefined') {
return Buffer.from(data).toString('base64');
}
return btoa(data);
}
_getFinalPath(path) {
return `${this.bucketId}/${path}`;
}
_removeEmptyFolders(path) {
return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/');
}
transformOptsToQueryString(transform) {
const params = [];
if (transform.width) {
params.push(`width=${transform.width}`);
}
if (transform.height) {
params.push(`height=${transform.height}`);
}
if (transform.resize) {
params.push(`resize=${transform.resize}`);
}
if (transform.format) {
params.push(`format=${transform.format}`);
}
if (transform.quality) {
params.push(`quality=${transform.quality}`);
}
return params.join('&');
}
}
//# sourceMappingURL=StorageFileApi.js.map

File diff suppressed because one or more lines are too long