@fal-ai/client
Version:
The fal.ai client for JavaScript and TypeScript
162 lines • 7.13 kB
JavaScript
;
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.createStorageClient = createStorageClient;
const config_1 = require("./config");
const request_1 = require("./request");
const utils_1 = require("./utils");
/**
* 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) {
return __awaiter(this, void 0, void 0, function* () {
const filename = file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`;
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,
});
});
}
/**
* 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) {
return __awaiter(this, void 0, void 0, function* () {
const filename = file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`;
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,
});
});
}
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) {
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);
// 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) => __awaiter(this, void 0, void 0, function* () {
// Check for 90+ MB file size to do multipart upload
if (file.size > 90 * 1024 * 1024) {
return yield multipartUpload(file, config);
}
const contentType = file.type || "application/octet-stream";
const { fetch, responseHandler } = config;
const { upload_url: uploadUrl, file_url: url } = yield initiateUpload(file, config, contentType);
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