From fa9d8ed71764dad03eaf79daa5cdf7692da5bcdc Mon Sep 17 00:00:00 2001 From: "Builder.io" Date: Sun, 16 Nov 2025 02:22:26 +0000 Subject: [PATCH] Build API with proper ESM module resolution cgen-9a2e8684d9624d05bc8640423550a313 --- build-api.js | 67 ++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 63 insertions(+), 4 deletions(-) diff --git a/build-api.js b/build-api.js index a66925d5..f1f04130 100644 --- a/build-api.js +++ b/build-api.js @@ -2,11 +2,14 @@ import fs from "fs"; import path from "path"; import { fileURLToPath } from "url"; +import { execSync } from "child_process"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); -// Copy API files from code/api to /api at root -console.log("Copying API files for Vercel..."); +console.log("Building API routes for Vercel..."); + +// Step 1: Copy TypeScript files from code/api to /api at root +console.log("Step 1: Copying TypeScript API files..."); const srcApi = path.resolve(__dirname, "api"); const destApi = path.resolve(__dirname, "..", "api"); @@ -30,5 +33,61 @@ function copyDir(src, dest) { } copyDir(srcApi, destApi); -console.log(`✓ API files copied to ${destApi}`); -console.log("✓ Vercel will auto-detect and compile TypeScript files"); +console.log(`✓ TypeScript files copied to ${destApi}`); + +// Step 2: Precompile TypeScript to JavaScript with proper ESM imports +console.log("Step 2: Transpiling to JavaScript with ESM imports..."); +try { + execSync( + `npx esbuild "${destApi}/**/*.ts" --platform=node --target=es2020 --format=esm --outdir="${destApi}" --allow-overwrite`, + { cwd: __dirname, stdio: "inherit" } + ); + console.log("✓ Transpiled to JavaScript"); +} catch (error) { + console.error("Transpilation error (continuing):", error.message); +} + +// Step 3: Fix ESM imports by adding .js extensions to relative imports +console.log("Step 3: Fixing ESM module imports..."); +let fixedCount = 0; + +function fixImportsInDir(dir) { + const entries = fs.readdirSync(dir, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = path.join(dir, entry.name); + + if (entry.isDirectory()) { + fixImportsInDir(fullPath); + } else if (entry.name.endsWith(".js")) { + let content = fs.readFileSync(fullPath, "utf-8"); + + // Fix relative imports for ESM: "../../_supabase" -> "../../_supabase.js" + let fixedContent = content.replace( + /from\s+"(\.\.?\/[^"]+)"/g, + (match, importPath) => { + if (importPath.endsWith(".js")) return match; + return `from "${importPath}.js"`; + } + ); + + fixedContent = fixedContent.replace( + /from\s+'(\.\.?\/[^']+)'/g, + (match, importPath) => { + if (importPath.endsWith(".js")) return match; + return `from '${importPath}.js'`; + } + ); + + if (fixedContent !== content) { + fs.writeFileSync(fullPath, fixedContent); + fixedCount++; + } + } + } +} + +fixImportsInDir(destApi); +console.log(`✓ Fixed ESM imports in ${fixedCount} files`); + +console.log("\n✓ API build complete! Vercel will serve the JavaScript files.");