import { CollectionModuleCodeFileBase, CollectionModuleCodeFileWithContentAndUrl, CollectionModuleCodeFileWithUrl, NetworkPath, NetworkPathWithUrl, } from '../../domain/collection-modules/collection-module-definition'; import { HttpMethod, RootAPIHelper } from '../root-api'; export enum S3Operation { GetObject = 'getObject', PutObject = 'putObject', } export const createCodeFilesSignedUrls = async (params: { codeFiles: T[]; collectionModuleKey: string; host: string; apiKey: string; operation: S3Operation; liveVersion: boolean; }): Promise<(T & { signedUrl: string })[]> => { const { collectionModuleKey, host, apiKey, codeFiles, operation, liveVersion } = params; if (codeFiles.length === 0) { return []; } const rootApiHelper = new RootAPIHelper({ apiKey, host, throwResponseErrors: true }); const body: { paths: NetworkPath[]; operation: S3Operation; } = { paths: codeFiles.map((codeFile) => ({ path_segments: codeFile.pathSegments })), operation, }; const response: NetworkPathWithUrl[] = await rootApiHelper.send({ path: `/cli/collection-modules/${collectionModuleKey}/code-files-signed-urls`, method: HttpMethod.Post, body, searchParams: { live_version: liveVersion.toString() }, }); const codeFilesWithUrls = codeFiles.map((codeFile) => { const matchingResponse = response.find( (pathWithUrl) => pathWithUrl.path_segments.join('/') === codeFile.pathSegments.join('/'), ); if (!matchingResponse) { throw new Error( `Could not find matching response for code file with path segments: ${codeFile.pathSegments.toString()}`, ); } return { ...codeFile, signedUrl: matchingResponse.signed_url, }; }); return codeFilesWithUrls; }; export const uploadCodeFileToS3 = async (codeFile: CollectionModuleCodeFileWithContentAndUrl) => { const { signedUrl, content } = codeFile; const response = await fetch(signedUrl, { method: 'PUT', body: content, }); if (!response.ok) { throw new Error(`Failed to upload code file to S3: ${response.statusText}`); } }; export const addContentToCodeFile = async (codeFile: CollectionModuleCodeFileWithUrl) => { const { signedUrl } = codeFile; const response = await fetch(signedUrl, { method: 'GET', }); if (!response.ok) { throw new Error(`Failed to get code file content: ${response.statusText}`); } const content = await response.text(); return { ...codeFile, content, }; };