UNPKG

@fal-ai/client

Version:

The fal.ai client for JavaScript and TypeScript

232 lines 9.82 kB
"use strict"; 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OBJECT_LIFECYCYLE_PREFERENCE_HEADER = void 0; exports.getExpirationDurationSeconds = getExpirationDurationSeconds; exports.buildObjectLifecycleHeaders = buildObjectLifecycleHeaders; exports.createStorageClient = createStorageClient; const config_1 = require("./config"); const request_1 = require("./request"); const utils_1 = require("./utils"); exports.OBJECT_LIFECYCYLE_PREFERENCE_HEADER = "x-fal-object-lifecycle-preference"; const EXPIRATION_VALUES = { never: undefined, immediate: 60, "1h": 3600, "1d": 86400, "7d": 604800, "30d": 2592000, "1y": 31536000, }; /** * Converts an `StorageSettings` to the expiration duration in seconds. * @param lifecycle the lifecycle preference * @returns the expiration duration in seconds, or undefined if not applicable */ function getExpirationDurationSeconds(lifecycle) { const { expiresIn } = lifecycle; if (expiresIn === undefined) { return undefined; } return typeof expiresIn === "number" ? expiresIn : EXPIRATION_VALUES[expiresIn]; } function buildUploadLifecycleConfig(lifecycle) { if (!lifecycle) { return undefined; } const expirationDurationSeconds = getExpirationDurationSeconds(lifecycle); const lifecycleConfig = {}; if (expirationDurationSeconds !== undefined) { lifecycleConfig.expiration_duration_seconds = expirationDurationSeconds; } if (lifecycle.initialAcl !== undefined) { lifecycleConfig.initial_acl = lifecycle.initialAcl; } return Object.keys(lifecycleConfig).length > 0 ? lifecycleConfig : undefined; } /** * Builds the headers for the Object Lifecycle preference to be used in API requests. * This is used by the queue and run APIs to control the lifecycle of generated objects. * * @param lifecycle the lifecycle preference * @returns a record with the `X-Fal-Object-Lifecycle-Preference` header */ function buildObjectLifecycleHeaders(lifecycle) { const lifecycleConfig = buildUploadLifecycleConfig(lifecycle); if (!lifecycleConfig) { return {}; } return { [exports.OBJECT_LIFECYCYLE_PREFERENCE_HEADER]: JSON.stringify(lifecycleConfig), }; } /** * Get the file extension from the content type. This is used to generate * a file name if the file name is not provided. * * @param contentType the content type of the file. * @returns the file extension or `bin` if the content type is not recognized. */ function getExtensionFromContentType(contentType) { var _a; const [, fileType] = contentType.split("/"); return (_a = fileType.split(/[-;]/)[0]) !== null && _a !== void 0 ? _a : "bin"; } /** * Initiate the upload of a file to the server. This returns the URL to upload * the file to and the URL of the file once it is uploaded. */ function initiateUpload(file, config, contentType, lifecycle) { return __awaiter(this, void 0, void 0, function* () { const filename = file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`; const headers = {}; const lifecycleConfig = buildUploadLifecycleConfig(lifecycle); if (lifecycleConfig) { headers["X-Fal-Object-Lifecycle"] = JSON.stringify(lifecycleConfig); } return yield (0, request_1.dispatchRequest)({ method: "POST", // NOTE: We want to test V3 without making it the default at the API level targetUrl: `${(0, config_1.getRestApiUrl)()}/storage/upload/initiate?storage_type=fal-cdn-v3`, input: { content_type: contentType, file_name: filename, }, config, headers, }); }); } /** * Initiate the multipart upload of a file to the server. This returns the URL to upload * the file to and the URL of the file once it is uploaded. */ function initiateMultipartUpload(file, config, contentType, lifecycle) { return __awaiter(this, void 0, void 0, function* () { const filename = file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`; const headers = {}; const lifecycleConfig = buildUploadLifecycleConfig(lifecycle); if (lifecycleConfig) { headers["X-Fal-Object-Lifecycle"] = JSON.stringify(lifecycleConfig); } return yield (0, request_1.dispatchRequest)({ method: "POST", targetUrl: `${(0, config_1.getRestApiUrl)()}/storage/upload/initiate-multipart?storage_type=fal-cdn-v3`, input: { content_type: contentType, file_name: filename, }, config, headers, }); }); } function partUploadRetries(uploadUrl_1, chunk_1, config_2) { return __awaiter(this, arguments, void 0, function* (uploadUrl, chunk, config, tries = 3) { if (tries === 0) { throw new Error("Part upload failed, retries exhausted"); } const { fetch, responseHandler } = config; try { const response = yield fetch(uploadUrl, { method: "PUT", body: chunk, }); return (yield responseHandler(response)); } catch (error) { return yield partUploadRetries(uploadUrl, chunk, config, tries - 1); } }); } function multipartUpload(file, config, lifecycle) { return __awaiter(this, void 0, void 0, function* () { const { fetch, responseHandler } = config; const contentType = file.type || "application/octet-stream"; const { upload_url: uploadUrl, file_url: url } = yield initiateMultipartUpload(file, config, contentType, lifecycle); // Break the file into 10MB chunks const chunkSize = 10 * 1024 * 1024; const chunks = Math.ceil(file.size / chunkSize); const parsedUrl = new URL(uploadUrl); const responses = []; for (let i = 0; i < chunks; i++) { const start = i * chunkSize; const end = Math.min(start + chunkSize, file.size); const chunk = file.slice(start, end); const partNumber = i + 1; // {uploadUrl}/{part_number}?uploadUrlParams=... const partUploadUrl = `${parsedUrl.origin}${parsedUrl.pathname}/${partNumber}${parsedUrl.search}`; responses.push(yield partUploadRetries(partUploadUrl, chunk, config)); } // Complete the upload const completeUrl = `${parsedUrl.origin}${parsedUrl.pathname}/complete${parsedUrl.search}`; const response = yield fetch(completeUrl, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ parts: responses.map((mpart) => ({ partNumber: mpart.partNumber, etag: mpart.etag, })), }), }); yield responseHandler(response); return url; }); } function createStorageClient({ config, }) { const ref = { upload: (file, options) => __awaiter(this, void 0, void 0, function* () { const lifecycle = options === null || options === void 0 ? void 0 : options.lifecycle; // Check for 90+ MB file size to do multipart upload if (file.size > 90 * 1024 * 1024) { return yield multipartUpload(file, config, lifecycle); } const contentType = file.type || "application/octet-stream"; const { fetch, responseHandler } = config; const { upload_url: uploadUrl, file_url: url } = yield initiateUpload(file, config, contentType, lifecycle); const response = yield fetch(uploadUrl, { method: "PUT", body: file, headers: { "Content-Type": file.type || "application/octet-stream", }, }); yield responseHandler(response); return url; }), // eslint-disable-next-line @typescript-eslint/no-explicit-any transformInput: (input) => __awaiter(this, void 0, void 0, function* () { if (Array.isArray(input)) { return Promise.all(input.map((item) => ref.transformInput(item))); } else if (input instanceof Blob) { return yield ref.upload(input); } else if ((0, utils_1.isPlainObject)(input)) { const inputObject = input; const promises = Object.entries(inputObject).map((_a) => __awaiter(this, [_a], void 0, function* ([key, value]) { return [key, yield ref.transformInput(value)]; })); const results = yield Promise.all(promises); return Object.fromEntries(results); } // Return the input as is if it's neither an object nor a file/blob/data URI return input; }), }; return ref; } //# sourceMappingURL=storage.js.map