@jami-studio/core 0.92.21 → 0.92.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/corpus/core/CHANGELOG.md +12 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/deploy/build.ts +19 -5
- package/corpus/core/src/server/framework-request-handler.ts +57 -2
- package/dist/deploy/build.d.ts.map +1 -1
- package/dist/deploy/build.js +19 -5
- package/dist/deploy/build.js.map +1 -1
- package/dist/server/framework-request-handler.d.ts.map +1 -1
- package/dist/server/framework-request-handler.js +50 -2
- package/dist/server/framework-request-handler.js.map +1 -1
- package/package.json +1 -1
package/dist/deploy/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../src/deploy/build.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,OAAO,EACL,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EACL,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,EAC9B,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EACL,6BAA6B,EAC7B,sCAAsC,EACtC,gCAAgC,EAChC,8BAA8B,EAC9B,8BAA8B,EAC9B,+BAA+B,GAChC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AACl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,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAE3E,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,kBAAkB,CAAC;QACxB,KAAK,kBAAkB;YACrB,4EAA4E;YAC5E,yEAAyE;YACzE,iEAAiE;YACjE,MAAM,oBAAoB,EAAE,CAAC;YAC7B,MAAM;QACR;YACE,qEAAqE;YACrE,6CAA6C;YAC7C,MAAM,cAAc,EAAE,CAAC;YACvB,MAAM;IACV,CAAC;AACH,CAAC;AAED,IACE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IACf,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAC9E,CAAC;IACD,MAAM,IAAI,EAAE,CAAC;AACf,CAAC","sourcesContent":["#!/usr/bin/env node\n\n/**\n * Post-build step for deploying agent-native apps to edge/serverless targets.\n *\n * When NITRO_PRESET is set, this script:\n * 1. Takes the React Router build output (build/client/ + build/server/)\n * 2. Generates a platform-specific server entry point\n * 3. Bundles everything with esbuild into the target format\n *\n * Supported presets:\n * - cloudflare_pages: Outputs dist/ with _worker.js for Cloudflare Pages\n *\n * Usage: node deploy/build.js (called automatically by `agent-native build`)\n */\n\nimport { execFileSync } from \"child_process\";\nimport fs from \"fs\";\nimport { createRequire } from \"module\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nimport {\n AGENT_BACKGROUND_FUNCTION_NAME,\n AGENT_CHAT_PROCESS_RUN_PATH,\n} from \"../agent/durable-background.js\";\nimport { normalizeAppBasePath } from \"../server/app-base-path.js\";\nimport {\n DEFAULT_SSR_CDN_CACHE_CONTROL,\n DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL,\n DEFAULT_SPECULATION_RULES_PATH,\n DEFAULT_SSR_CACHE_CONTROL,\n} from \"../shared/cache-control.js\";\nimport { mcpEmbedStaticAssetRouteRules } from \"../shared/mcp-embed-headers.js\";\nimport {\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER,\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n} from \"../shared/social-meta.js\";\nimport { generateActionRegistryForProject } from \"../vite/action-types-plugin.js\";\nimport {\n collectImmutableAssetPaths,\n IMMUTABLE_ASSET_CACHE_CONTROL,\n IMMUTABLE_ASSET_CACHE_HEADERS,\n prefixAssetPath,\n} from \"./immutable-assets.js\";\nimport {\n discoverApiRoutes,\n discoverPlugins,\n discoverActionFiles,\n getMissingDefaultPlugins,\n DEFAULT_PLUGIN_REGISTRY,\n type DiscoveredRoute,\n type DiscoveredAction,\n} from \"./route-discovery.js\";\nimport {\n getWorkspaceCoreExports,\n type WorkspaceCoreExports,\n} from \"./workspace-core.js\";\n\nconst cwd = process.cwd();\nconst preset = process.env.NITRO_PRESET || \"node\";\nexport const NITRO_RUNTIME_IGNORE_PATTERNS = [\n \"**/*.spec.ts\",\n \"**/*.spec.tsx\",\n \"**/*.spec.mts\",\n \"**/*.spec.cts\",\n \"**/*.spec.js\",\n \"**/*.spec.jsx\",\n \"**/*.spec.mjs\",\n \"**/*.spec.cjs\",\n \"**/*.test.ts\",\n \"**/*.test.tsx\",\n \"**/*.test.mts\",\n \"**/*.test.cts\",\n \"**/*.test.js\",\n \"**/*.test.jsx\",\n \"**/*.test.mjs\",\n \"**/*.test.cjs\",\n];\n\nexport const CLOUDFLARE_WORKER_ESBUILD_EXTERNALS = [\n \"mermaid\",\n \"@excalidraw/excalidraw\",\n \"@excalidraw/mermaid-to-excalidraw\",\n \"pdf-parse\",\n \"pdfjs-dist\",\n \"@google/genai\",\n \"chartjs-node-canvas\",\n \"@napi-rs/canvas\",\n \"@anthropic-ai/tokenizer\",\n \"@resvg/resvg-js\",\n \"playwright\",\n \"playwright-core\",\n \"chromium-bidi\",\n \"chromium-bidi/*\",\n \"@sparticuz/chromium-min\",\n \"fsevents\",\n];\nexport const CLOUDFLARE_WORKER_STUB_MODULES: Record<string, string> = {\n // detect-libc calls process.report.getReport() at require time to sniff\n // musl vs glibc; unenv's process.report stub throws \"not implemented\",\n // killing the worker at module init. Stub it with static glibc answers —\n // nothing that consults libc can run on workerd anyway.\n \"detect-libc\": [\n \"export const GLIBC = 'glibc';\",\n \"export const MUSL = 'musl';\",\n \"export const family = async () => null;\",\n \"export const familySync = () => null;\",\n \"export const version = async () => null;\",\n \"export const versionSync = () => null;\",\n \"export const isNonGlibcLinux = async () => false;\",\n \"export const isNonGlibcLinuxSync = () => false;\",\n \"export default { GLIBC, MUSL, family, familySync, version, versionSync, isNonGlibcLinux, isNonGlibcLinuxSync };\",\n \"\",\n ].join(\"\\n\"),\n \"better-sqlite3\":\n \"export default {}; export const Database = class {}; export const watch = () => ({ close() {} });\\n\",\n // sharp loads its native binary (@img/sharp-<platform>) at require time and\n // throws \"Could not load the sharp module using the linux- runtime\" at\n // worker module init. Stub it with a callable that throws at call time —\n // image processing can't run on workerd regardless.\n sharp: [\n \"const unavailable = () => { throw new Error('sharp unavailable in Cloudflare Pages worker'); };\",\n \"const sharp = new Proxy(unavailable, { get: (_t, prop) => (prop === 'default' ? sharp : unavailable), apply: unavailable });\",\n \"export default sharp;\",\n \"\",\n ].join(\"\\n\"),\n \"node-pty\":\n \"export default {}; export const watch = () => ({ close() {} });\\n\",\n chokidar: \"export default {}; export const watch = () => ({ close() {} });\\n\",\n fsevents: \"export default {}; export const watch = () => ({ close() {} });\\n\",\n dotenv: \"export default {}; export const config = () => ({ parsed: {} });\\n\",\n \"@anthropic-ai/sdk\": \"export default class Anthropic {}\\n\",\n \"@anthropic-ai/tokenizer\":\n \"export default {}; export const countTokens = undefined;\\n\",\n \"@sentry/node\": [\n \"export const init = () => {};\",\n \"const scope = {\",\n \" setUser() {},\",\n \" setTag() {},\",\n \" setExtra() {},\",\n \" setContext() {},\",\n \" setLevel() {},\",\n \" getScopeData() { return {}; },\",\n \"};\",\n \"export const getIsolationScope = () => scope;\",\n \"export const withScope = (fn) => fn(scope);\",\n \"export const captureException = () => undefined;\",\n \"export default { init, getIsolationScope, withScope, captureException };\",\n \"\",\n ].join(\"\\n\"),\n \"@resvg/resvg-js\": [\n \"export class Resvg {\",\n ' constructor() { throw new Error(\"@resvg/resvg-js unavailable in Cloudflare Pages worker\"); }',\n \"}\",\n \"export default { Resvg };\",\n \"\",\n ].join(\"\\n\"),\n \"playwright-core\": [\n \"const unavailable = async () => { throw new Error('playwright-core unavailable in Cloudflare Pages worker'); };\",\n \"export const chromium = { launch: unavailable };\",\n \"export const firefox = { launch: unavailable };\",\n \"export const webkit = { launch: unavailable };\",\n \"export default { chromium, firefox, webkit };\",\n \"\",\n ].join(\"\\n\"),\n // playwright and its playwright/test subpath are imported with literal\n // dynamic import() in template actions (e.g. design's screenshot action\n // imports \"playwright/test\"), so a bare --external leaves an unresolvable\n // import in the final _worker.js — wrangler/Pages then refuses the bundle.\n // Stub both so the import resolves and degrades at call time like Node.\n playwright: [\n \"const unavailable = async () => { throw new Error('playwright unavailable in Cloudflare Pages worker'); };\",\n \"export const chromium = { launch: unavailable };\",\n \"export const firefox = { launch: unavailable };\",\n \"export const webkit = { launch: unavailable };\",\n \"export default { chromium, firefox, webkit };\",\n \"\",\n ].join(\"\\n\"),\n \"playwright/test\": [\n \"const unavailable = async () => { throw new Error('playwright/test unavailable in Cloudflare Pages worker'); };\",\n \"export const chromium = { launch: unavailable };\",\n \"export const firefox = { launch: unavailable };\",\n \"export const webkit = { launch: unavailable };\",\n \"export const test = undefined;\",\n \"export const expect = undefined;\",\n \"export default { chromium, firefox, webkit };\",\n \"\",\n ].join(\"\\n\"),\n \"@sparticuz/chromium-min\": [\n \"const chromium = {\",\n \" args: [],\",\n \" setGraphicsMode: false,\",\n \" executablePath: async () => { throw new Error('@sparticuz/chromium-min unavailable in Cloudflare Pages worker'); },\",\n \"};\",\n \"export default chromium;\",\n \"\",\n ].join(\"\\n\"),\n \"@google/genai\": [\n \"export class GoogleGenAI {\",\n \" constructor() { throw new Error('@google/genai unavailable in Cloudflare Pages worker'); }\",\n \"}\",\n \"export default { GoogleGenAI };\",\n \"\",\n ].join(\"\\n\"),\n \"pdf-parse\": [\n \"export class PDFParse {\",\n \" constructor() { throw new Error('pdf-parse unavailable in Cloudflare Pages worker'); }\",\n \"}\",\n \"export default { PDFParse };\",\n \"\",\n ].join(\"\\n\"),\n \"pdfjs-dist\":\n \"export default {}; export const getDocument = () => { throw new Error('pdfjs-dist unavailable in Cloudflare Pages worker'); };\\n\",\n \"chartjs-node-canvas\": [\n \"export class ChartJSNodeCanvas {\",\n \" constructor() { throw new Error('chartjs-node-canvas unavailable in Cloudflare Pages worker'); }\",\n \"}\",\n \"export default { ChartJSNodeCanvas };\",\n \"\",\n ].join(\"\\n\"),\n \"@napi-rs/canvas\":\n \"export default {}; export const createCanvas = () => { throw new Error('@napi-rs/canvas unavailable in Cloudflare Pages worker'); };\\n\",\n mermaid: \"export default {}; export const mermaidAPI = {};\\n\",\n \"@excalidraw/excalidraw\":\n \"export default {}; export const MainMenu = {}; export const WelcomeScreen = {};\\n\",\n \"@excalidraw/mermaid-to-excalidraw\":\n \"export default async () => ({ elements: [], files: {} });\\n\",\n};\n\n/**\n * Optional AI SDK packages that ai-sdk-engine imports with LITERAL dynamic\n * import() specifiers (so bundlers include provider packages when present).\n * They are optional peer dependencies — when an app hasn't installed one,\n * esbuild fails the worker bundle with \"Could not resolve\". Stub every\n * uninstalled one with a module that throws at import time, which makes the\n * dynamic import() reject exactly like the missing package does under Node.\n */\nexport const OPTIONAL_AI_SDK_MODULES = [\n \"ai\",\n \"@ai-sdk/anthropic\",\n \"@ai-sdk/openai\",\n \"@ai-sdk/google\",\n \"@ai-sdk/groq\",\n \"@ai-sdk/mistral\",\n \"@ai-sdk/cohere\",\n \"@openrouter/ai-sdk-provider\",\n \"ai-sdk-ollama\",\n];\n\nexport function uninstalledOptionalAiSdkStubs(\n appDir: string,\n): Record<string, string> {\n const appRequire = createRequire(path.join(appDir, \"package.json\"));\n const stubs: Record<string, string> = {};\n for (const mod of OPTIONAL_AI_SDK_MODULES) {\n try {\n appRequire.resolve(mod);\n } catch {\n stubs[mod] = `throw new Error(${JSON.stringify(\n `${mod} is not installed in this deployment`,\n )});\\n`;\n }\n }\n return stubs;\n}\n\nfunction cloudflareNodeBuiltinStubSource(\n moduleName: string,\n namedExports: string[],\n overrides: string[] = [],\n): string {\n const overridden = new Set(\n overrides.flatMap((source) =>\n Array.from(source.matchAll(/\\bexport const ([A-Za-z_$][\\w$]*)/g)).map(\n (match) => match[1],\n ),\n ),\n );\n const exports = Array.from(new Set(namedExports))\n .filter((name) => !overridden.has(name))\n .sort();\n // The default export must expose the SAME members as the named exports —\n // including functional overrides like os.tmpdir() — because most consumers\n // use the default import (`import os from \"os\"; os.tmpdir()`). A bare\n // throwing proxy here killed workers at module init whenever a dependency\n // called an overridden member through the default export.\n const allNames = Array.from(new Set([...overridden, ...exports])).sort();\n return [\n `const unavailable = (name) => (..._args) => { throw new Error(name + \" is unavailable in Cloudflare Pages workers\"); };`,\n ...overrides,\n ...exports.map(\n (name) => `export const ${name} = unavailable(\"${moduleName}.${name}\");`,\n ),\n `const __members = { ${allNames.join(\", \")} };`,\n `const proxy = new Proxy(__members, { get(target, prop) { return prop in target ? target[prop] : unavailable(\"${moduleName}.\" + String(prop)); } });`,\n \"export default proxy;\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport const CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES: Record<\n string,\n string\n> = {\n child_process: cloudflareNodeBuiltinStubSource(\"child_process\", [\n \"exec\",\n \"execFile\",\n \"execFileSync\",\n \"execSync\",\n \"fork\",\n \"spawn\",\n \"spawnSync\",\n ]),\n cluster: cloudflareNodeBuiltinStubSource(\"cluster\", [\n \"disconnect\",\n \"fork\",\n \"isMaster\",\n \"isPrimary\",\n \"isWorker\",\n \"setupMaster\",\n \"setupPrimary\",\n \"worker\",\n \"workers\",\n ]),\n console: [\n \"const globalConsole = globalThis.console;\",\n \"const bind = (name) => typeof globalConsole?.[name] === 'function' ? globalConsole[name].bind(globalConsole) : () => undefined;\",\n \"export class Console {\",\n \" constructor() { return globalConsole; }\",\n \"}\",\n \"export const assert = bind('assert');\",\n \"export const clear = bind('clear');\",\n \"export const count = bind('count');\",\n \"export const countReset = bind('countReset');\",\n \"export const debug = bind('debug');\",\n \"export const dir = bind('dir');\",\n \"export const dirxml = bind('dirxml');\",\n \"export const error = bind('error');\",\n \"export const group = bind('group');\",\n \"export const groupCollapsed = bind('groupCollapsed');\",\n \"export const groupEnd = bind('groupEnd');\",\n \"export const info = bind('info');\",\n \"export const log = bind('log');\",\n \"export const profile = bind('profile');\",\n \"export const profileEnd = bind('profileEnd');\",\n \"export const table = bind('table');\",\n \"export const time = bind('time');\",\n \"export const timeEnd = bind('timeEnd');\",\n \"export const timeLog = bind('timeLog');\",\n \"export const timeStamp = bind('timeStamp');\",\n \"export const trace = bind('trace');\",\n \"export const warn = bind('warn');\",\n \"export { globalConsole as console };\",\n \"export default globalConsole;\",\n \"\",\n ].join(\"\\n\"),\n dgram: cloudflareNodeBuiltinStubSource(\"dgram\", [\"createSocket\"]),\n dns: cloudflareNodeBuiltinStubSource(\"dns\", [\n \"lookup\",\n \"promises\",\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n ]),\n \"dns/promises\": cloudflareNodeBuiltinStubSource(\"dns/promises\", [\n \"lookup\",\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n ]),\n domain: cloudflareNodeBuiltinStubSource(\"domain\", [\"create\"]),\n fs: cloudflareNodeBuiltinStubSource(\n \"fs\",\n [\n \"access\",\n \"accessSync\",\n \"appendFile\",\n \"appendFileSync\",\n \"chmod\",\n \"chmodSync\",\n \"close\",\n \"closeSync\",\n \"copyFile\",\n \"copyFileSync\",\n \"cp\",\n \"cpSync\",\n \"createReadStream\",\n \"createWriteStream\",\n \"existsSync\",\n \"lstat\",\n \"lstatSync\",\n \"mkdir\",\n \"mkdirSync\",\n \"open\",\n \"openSync\",\n \"readFile\",\n \"readFileSync\",\n \"readdir\",\n \"readdirSync\",\n \"readlink\",\n \"readlinkSync\",\n \"realpath\",\n \"realpathSync\",\n \"rename\",\n \"renameSync\",\n \"rm\",\n \"rmSync\",\n \"stat\",\n \"statSync\",\n \"symlink\",\n \"symlinkSync\",\n \"unlink\",\n \"unlinkSync\",\n \"watch\",\n \"writeFile\",\n \"writeFileSync\",\n ],\n [\n \"export const constants = {};\",\n \"export const promises = {};\",\n \"export const existsSync = () => false;\",\n \"export const readdirSync = () => [];\",\n \"export const realpathSync = (value) => value;\",\n \"export const mkdirSync = () => undefined;\",\n \"export const rmSync = () => undefined;\",\n ],\n ),\n \"fs/promises\": cloudflareNodeBuiltinStubSource(\"fs/promises\", [\n \"access\",\n \"appendFile\",\n \"chmod\",\n \"copyFile\",\n \"cp\",\n \"lstat\",\n \"mkdtemp\",\n \"mkdir\",\n \"readFile\",\n \"readdir\",\n \"readlink\",\n \"realpath\",\n \"rename\",\n \"rm\",\n \"stat\",\n \"symlink\",\n \"unlink\",\n \"writeFile\",\n ]),\n http: cloudflareNodeBuiltinStubSource(\"http\", [\n \"Agent\",\n \"ClientRequest\",\n \"IncomingMessage\",\n \"ServerResponse\",\n \"createServer\",\n \"get\",\n \"request\",\n ]),\n http2: cloudflareNodeBuiltinStubSource(\"http2\", [\n \"Http2ServerRequest\",\n \"Http2ServerResponse\",\n \"constants\",\n \"connect\",\n \"createSecureServer\",\n \"createServer\",\n ]),\n https: cloudflareNodeBuiltinStubSource(\"https\", [\n \"Agent\",\n \"createServer\",\n \"get\",\n \"request\",\n ]),\n inspector: cloudflareNodeBuiltinStubSource(\"inspector\", [\n \"Session\",\n \"close\",\n \"open\",\n \"url\",\n \"waitForDebugger\",\n ]),\n module: cloudflareNodeBuiltinStubSource(\n \"module\",\n [\"Module\", \"builtinModules\", \"createRequire\", \"syncBuiltinESMExports\"],\n [\n \"export const builtinModules = [];\",\n \"export const createRequire = () => globalThis.require ?? ((specifier) => { throw new Error('Cannot require: ' + specifier); });\",\n ],\n ),\n net: cloudflareNodeBuiltinStubSource(\n \"net\",\n [\"Socket\", \"connect\", \"createConnection\", \"createServer\", \"isIP\"],\n [\n `export const isIP = (value) => {\n const input = String(value ?? \"\");\n const ipv4Parts = input.split(\".\");\n if (\n ipv4Parts.length === 4 &&\n ipv4Parts.every((part) => /^\\\\d{1,3}$/.test(part) && Number(part) >= 0 && Number(part) <= 255)\n ) {\n return 4;\n }\n if (input.includes(\":\") && /^[0-9A-Fa-f:.]+$/.test(input)) {\n return 6;\n }\n return 0;\n};`,\n ],\n ),\n os: cloudflareNodeBuiltinStubSource(\n \"os\",\n [\n \"arch\",\n \"cpus\",\n \"endianness\",\n \"freemem\",\n \"homedir\",\n \"hostname\",\n \"networkInterfaces\",\n \"platform\",\n \"release\",\n \"tmpdir\",\n \"totalmem\",\n \"type\",\n \"userInfo\",\n ],\n [\n 'export const EOL = \"\\\\n\";',\n 'export const arch = () => \"x64\";',\n \"export const cpus = () => [];\",\n 'export const endianness = () => \"LE\";',\n \"export const freemem = () => 0;\",\n 'export const homedir = () => \"/tmp\";',\n 'export const hostname = () => \"cloudflare-worker\";',\n \"export const networkInterfaces = () => ({});\",\n 'export const platform = () => \"linux\";',\n 'export const release = () => \"\";',\n 'export const tmpdir = () => \"/tmp\";',\n \"export const totalmem = () => 0;\",\n 'export const type = () => \"Worker\";',\n \"export const userInfo = () => ({ username: 'worker', homedir: '/tmp' });\",\n ],\n ),\n readline: cloudflareNodeBuiltinStubSource(\"readline\", [\n \"Interface\",\n \"clearLine\",\n \"clearScreenDown\",\n \"createInterface\",\n \"cursorTo\",\n \"emitKeypressEvents\",\n \"moveCursor\",\n ]),\n repl: cloudflareNodeBuiltinStubSource(\"repl\", [\"start\"]),\n sqlite: cloudflareNodeBuiltinStubSource(\"sqlite\", [\"DatabaseSync\"]),\n sys: cloudflareNodeBuiltinStubSource(\"sys\", [\n \"debug\",\n \"deprecate\",\n \"error\",\n \"inspect\",\n \"log\",\n \"print\",\n \"puts\",\n ]),\n tls: cloudflareNodeBuiltinStubSource(\"tls\", [\n \"TLSSocket\",\n \"connect\",\n \"createSecureContext\",\n \"createServer\",\n ]),\n trace_events: cloudflareNodeBuiltinStubSource(\"trace_events\", [\n \"createTracing\",\n \"getEnabledCategories\",\n ]),\n tty: cloudflareNodeBuiltinStubSource(\"tty\", [\n \"ReadStream\",\n \"WriteStream\",\n \"isatty\",\n ]),\n v8: cloudflareNodeBuiltinStubSource(\"v8\", [\n \"deserialize\",\n \"getHeapStatistics\",\n \"serialize\",\n ]),\n vm: cloudflareNodeBuiltinStubSource(\"vm\", [\n \"Script\",\n \"compileFunction\",\n \"createContext\",\n \"runInContext\",\n \"runInNewContext\",\n \"runInThisContext\",\n ]),\n wasi: cloudflareNodeBuiltinStubSource(\"wasi\", [\"WASI\"]),\n worker_threads: cloudflareNodeBuiltinStubSource(\n \"worker_threads\",\n [\"MessageChannel\", \"MessagePort\", \"Worker\", \"isMainThread\", \"parentPort\"],\n [\"export const isMainThread = true;\", \"export const parentPort = null;\"],\n ),\n};\n\nexport interface GenerateWorkerEntryOptions {\n includeReactRouterSsr?: boolean;\n}\n\ninterface ReactRouterAssetManifest {\n entry: ReactRouterAssetManifestEntry;\n routes: Record<string, ReactRouterAssetManifestRoute>;\n url: string;\n}\n\ninterface ReactRouterAssetManifestEntry {\n module: string;\n imports?: string[];\n css?: string[];\n}\n\ninterface ReactRouterAssetManifestRoute {\n id: string;\n module: string;\n imports?: string[];\n css?: string[];\n hasLoader?: boolean;\n clientActionModule?: string;\n clientLoaderModule?: string;\n clientMiddlewareModule?: string;\n hydrateFallbackModule?: string;\n}\n\nfunction normalizeConfiguredAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\n/** Plugins that require Node.js runtime and cannot run on edge/serverless */\nconst NODE_ONLY_PLUGINS = new Set([\n \"terminal\", // PTY requires child_process\n // @sentry/node ships node:fs / node:async_hooks bindings that don't load\n // on workerd / Cloudflare Workers. Templates running on edge presets can\n // mount their own edge-compatible Sentry wrapper if they want server\n // observability there; the framework default is the Node SDK.\n \"sentry\",\n]);\nconst EDGE_SERVER_ENTRYPOINT = \"@agent-native/core/server/edge\";\n\nfunction isNodeOnlyPlugin(filePath: string): boolean {\n const basename = path.basename(filePath, path.extname(filePath));\n return NODE_ONLY_PLUGINS.has(basename);\n}\n\nexport function generateProvidedPluginsNitroPluginSource(\n pluginStems: string[],\n): string {\n const stems = [...new Set(pluginStems.filter(Boolean))].sort();\n return `// AUTO-GENERATED by @agent-native/core deploy build\nimport { markDefaultPluginProvided } from \"${EDGE_SERVER_ENTRYPOINT}\";\n\nconst pluginStems = ${JSON.stringify(stems)};\n\nexport default function markBuildDiscoveredPlugins(nitroApp) {\n for (const stem of pluginStems) {\n markDefaultPluginProvided(nitroApp, stem);\n }\n}\n`;\n}\n\nasync function writeProvidedPluginsNitroPlugin(): Promise<string | null> {\n const plugins = await discoverPlugins(cwd);\n const stems = plugins.map((plugin) =>\n path.basename(plugin, path.extname(plugin)),\n );\n if (stems.length === 0) return null;\n\n const tmpDir = path.join(cwd, \".deploy-tmp\");\n fs.mkdirSync(tmpDir, { recursive: true });\n const pluginPath = path.join(tmpDir, \"agent-native-provided-plugins.mjs\");\n fs.writeFileSync(pluginPath, generateProvidedPluginsNitroPluginSource(stems));\n return pluginPath;\n}\n\ntype RouteRules = Record<string, { headers?: Record<string, string> }>;\n\nfunction addImmutableAssetRouteRule(\n routeRules: RouteRules,\n pathname: string,\n): void {\n const existing = routeRules[pathname] ?? {};\n routeRules[pathname] = {\n ...existing,\n headers: {\n ...(existing.headers ?? {}),\n ...IMMUTABLE_ASSET_CACHE_HEADERS,\n },\n };\n}\n\nexport function addImmutableAssetRouteRulesForClientBuild(\n routeRules: RouteRules,\n clientDir: string,\n appBasePath = \"\",\n): void {\n for (const assetPath of collectImmutableAssetPaths(clientDir)) {\n addImmutableAssetRouteRule(routeRules, assetPath);\n const mountedPath = prefixAssetPath(assetPath, appBasePath);\n if (mountedPath !== assetPath) {\n addImmutableAssetRouteRule(routeRules, mountedPath);\n }\n }\n}\n\n/**\n * Generate the worker entry source code that wires up H3 + React Router SSR.\n *\n * If a workspace core is present (monorepo with `agent-native.workspaceCore`\n * configured and the named package resolves), any plugin slot that the\n * workspace core exports is imported from there instead of from\n * `@agent-native/core/server/edge`. This is the middle layer of the three-layer\n * inheritance model: app local > workspace core > framework default.\n */\nexport function generateWorkerEntry(\n routes: DiscoveredRoute[],\n pluginPaths: string[],\n defaultPluginStems: string[] = [],\n actions: DiscoveredAction[] = [],\n workspaceCore: WorkspaceCoreExports | null = null,\n immutableAssetPaths: string[] = [],\n builtAppBasePath = normalizeConfiguredAppBasePath(),\n options: GenerateWorkerEntryOptions = {},\n): string {\n const includeReactRouterSsr = options.includeReactRouterSsr ?? true;\n const routeImports: string[] = [];\n const routeRegistrations: string[] = [];\n\n for (let i = 0; i < routes.length; i++) {\n const r = routes[i];\n const varName = `route_${i}`;\n routeImports.push(`import ${varName} from ${JSON.stringify(r.absPath)};`);\n routeRegistrations.push(\n ` app.on(${JSON.stringify(r.method.toUpperCase())}, ${JSON.stringify(r.route)}, ${varName});`,\n );\n if (r.method.toLowerCase() === \"get\") {\n routeRegistrations.push(\n ` app.on(\"HEAD\", ${JSON.stringify(r.route)}, defineEventHandler(async (event) => {\n const originalReq = event.req;\n event.req = requestWithMethod(event.req, \"GET\");\n try {\n const result = await ${varName}(event);\n const response = result instanceof Response ? result : toResponse(result, event);\n return new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } finally {\n event.req = originalReq;\n }\n }));`,\n );\n }\n }\n\n // Action route imports and registrations\n const actionImports: string[] = [];\n const actionRegistrations: string[] = [];\n for (let i = 0; i < actions.length; i++) {\n const a = actions[i];\n const varName = `action_${i}`;\n actionImports.push(`import ${varName} from ${JSON.stringify(a.absPath)};`);\n // Mirror the runtime mount (action-routes.ts): `path = http?.path ?? name`.\n const routePath = `/_agent-native/actions/${a.path ?? a.name}`;\n actionRegistrations.push(\n ` app.on(${JSON.stringify(a.method.toUpperCase())}, ${JSON.stringify(routePath)}, defineEventHandler(async (event) => {\n const params = ${a.method === \"get\" ? \"parseActionSearchParams(event.url.searchParams)\" : \"(await readBody(event)) ?? {}\"};\n try {\n const result = await ${varName}.run(params, { caller: \"http\" });\n if (typeof result === \"string\") { try { return JSON.parse(result); } catch { return result; } }\n return result;\n } catch (err) {\n return new Response(JSON.stringify({ error: err?.message || \"Action failed\" }), { status: err?.message?.startsWith(\"Invalid action parameters\") ? 400 : 500, headers: { \"Content-Type\": \"application/json\" } });\n }\n }));`,\n );\n }\n\n // Filter out Node-only plugins\n const edgePlugins = pluginPaths.filter((p) => !isNodeOnlyPlugin(p));\n const pluginImports: string[] = [];\n const pluginCalls: string[] = [];\n const providedPluginStems = new Set<string>();\n\n for (let i = 0; i < edgePlugins.length; i++) {\n const varName = `plugin_${i}`;\n providedPluginStems.add(\n path.basename(edgePlugins[i], path.extname(edgePlugins[i])),\n );\n pluginImports.push(\n `import ${varName} from ${JSON.stringify(edgePlugins[i])};`,\n );\n pluginCalls.push(` if (typeof ${varName} === \"function\") {\n await ${varName}(nitroApp);\n }`);\n }\n // Auto-mounted default plugins (for slots the template doesn't override\n // locally). For each slot, prefer a workspace-core export over the\n // @agent-native/core default, if the workspace core provides one.\n const edgeDefaultStems = defaultPluginStems.filter(\n (stem) => !NODE_ONLY_PLUGINS.has(stem),\n );\n for (let i = 0; i < edgeDefaultStems.length; i++) {\n const stem = edgeDefaultStems[i];\n providedPluginStems.add(stem);\n const varName = `defaultPlugin_${i}`;\n\n const workspaceExportName = workspaceCore?.plugins?.[stem as never];\n if (workspaceCore && workspaceExportName) {\n // Workspace-core layer wins over the framework default.\n pluginImports.push(\n `import { ${workspaceExportName} as ${varName} } from ${JSON.stringify(\n `${workspaceCore.packageName}/server`,\n )};`,\n );\n } else {\n // Fall back to the framework default from the edge-safe core entrypoint.\n const defaultExportName = DEFAULT_PLUGIN_REGISTRY[stem];\n if (!defaultExportName) continue;\n pluginImports.push(\n `import { ${defaultExportName} as ${varName} } from \"${EDGE_SERVER_ENTRYPOINT}\";`,\n );\n }\n pluginCalls.push(` if (typeof ${varName} === \"function\") {\n await ${varName}(nitroApp);\n }`);\n }\n const generatedPluginMarks =\n providedPluginStems.size > 0\n ? [\n ...new Set([\n ...Object.keys(DEFAULT_PLUGIN_REGISTRY),\n ...providedPluginStems,\n ]),\n ]\n : [];\n if (generatedPluginMarks.length > 0) {\n pluginImports.unshift(\n `import { markDefaultPluginProvided as markGeneratedPluginProvided } from \"${EDGE_SERVER_ENTRYPOINT}\";`,\n );\n }\n\n return `\n// Auto-generated worker entry point for ${preset}\nimport { H3, defineEventHandler, readBody, toResponse } from \"h3\";\n${includeReactRouterSsr ? 'import { createRequestHandler } from \"react-router\";' : \"\"}\n${includeReactRouterSsr ? 'import * as serverBuild from \"./server-build.js\";' : \"\"}\n\nfunction normalizeAppBasePath(value) {\n if (!value || value === \"/\") return \"\";\n const trimmed = String(value).trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return \"/\" + trimmed.replace(/^\\\\/+/, \"\").replace(/\\\\/+$/, \"\");\n}\n\nfunction getAppBasePath() {\n const builtAppBasePath = ${JSON.stringify(builtAppBasePath)};\n return normalizeAppBasePath(\n globalThis.process?.env?.VITE_APP_BASE_PATH ||\n globalThis.process?.env?.APP_BASE_PATH ||\n builtAppBasePath,\n );\n}\n\nfunction stripAppBasePath(pathname) {\n const basePath = getAppBasePath();\n if (!basePath) return pathname;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(basePath + \"/\")) {\n return pathname.slice(basePath.length) || \"/\";\n }\n return pathname;\n}\n\nfunction parseActionSearchParams(searchParams) {\n const params = {};\n for (const [rawKey, value] of searchParams.entries()) {\n const isArrayKey = rawKey.endsWith(\"[]\");\n // The core client serializes arrays as key[]=value so one-item arrays\n // survive GET action parsing in generated worker deployments.\n const key = isArrayKey ? rawKey.slice(0, -2) : rawKey;\n const current = params[key];\n if (current === undefined) {\n params[key] = isArrayKey ? [value] : value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n params[key] = [current, value];\n }\n }\n return params;\n}\n\nfunction isApiPath(pathname) {\n return pathname === \"/api\" || pathname.startsWith(\"/api/\");\n}\n\nfunction isFrameworkPath(pathname) {\n return (\n pathname === \"/_agent-native\" || pathname.startsWith(\"/_agent-native/\")\n );\n}\n\nfunction requestWithMountedApiPrefixStripped(request) {\n const basePath = getAppBasePath();\n if (!basePath) return request;\n const url = new URL(request.url);\n const strippedPathname = stripAppBasePath(url.pathname);\n if (strippedPathname === url.pathname) {\n return request;\n }\n if (!isApiPath(strippedPathname) && !isFrameworkPath(strippedPathname)) {\n return request;\n }\n url.pathname = strippedPathname;\n return new Request(url, request);\n}\n\nfunction prefixMountedPath(path, basePath) {\n if (!basePath || !path.startsWith(\"/\") || path.startsWith(\"//\")) return path;\n if (path === basePath || path.startsWith(basePath + \"/\")) return path;\n return basePath + path;\n}\n\nfunction prefixMountedHtml(html, basePath) {\n if (!basePath) return html;\n return html\n .replace(\n /\\\\b(href|src|action|formaction|poster)=([\"'])(\\\\/(?!\\\\/)[^\"']*)\\\\2/g,\n (_match, attr, quote, path) =>\n attr + \"=\" + quote + prefixMountedPath(path, basePath) + quote,\n )\n .replace(/url\\\\(([\"']?)(\\\\/(?!\\\\/)[^)'\" ]+)\\\\1\\\\)/g, (_match, quote, path) => {\n const q = quote || \"\";\n return \"url(\" + q + prefixMountedPath(path, basePath) + q + \")\";\n });\n}\n\nfunction firstNonEmpty() {\n for (const value of arguments) {\n const trimmed = typeof value === \"string\" ? value.trim() : \"\";\n if (trimmed) return trimmed;\n }\n}\n\nfunction getSentryClientConfigScript() {\n const env = globalThis.process?.env || {};\n const key = firstNonEmpty(env.SENTRY_CLIENT_KEY, env.VITE_SENTRY_CLIENT_KEY);\n const projectId = firstNonEmpty(\n env.SENTRY_PROJECT_ID,\n env.VITE_SENTRY_PROJECT_ID,\n );\n const host = firstNonEmpty(\n env.SENTRY_INGEST_HOST,\n env.VITE_SENTRY_INGEST_HOST,\n );\n const dsn =\n firstNonEmpty(\n env.SENTRY_CLIENT_DSN,\n env.VITE_SENTRY_CLIENT_DSN,\n env.VITE_SENTRY_DSN,\n env.SENTRY_DSN,\n ) || (key && projectId && host ? \"https://\" + key + \"@\" + host + \"/\" + projectId : undefined);\n if (!dsn) return null;\n const config = {\n sentryDsn: dsn,\n sentryEnvironment:\n firstNonEmpty(\n env.SENTRY_ENVIRONMENT,\n env.NETLIFY_CONTEXT,\n env.VERCEL_ENV,\n env.NODE_ENV,\n ) || \"production\",\n };\n return (\n '<script data-agent-native-sentry-config>' +\n 'window.__AGENT_NATIVE_CONFIG__=Object.assign({},window.__AGENT_NATIVE_CONFIG__,' +\n JSON.stringify(config) +\n \");</script>\"\n );\n}\n\nfunction injectHeadScript(html, script) {\n if (!script) return html;\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);\n}\n\nconst DEFAULT_SSR_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CACHE_CONTROL)};\nconst DEFAULT_SSR_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CDN_CACHE_CONTROL)};\nconst DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL)};\nconst DEFAULT_SPECULATION_RULES_PATH = ${JSON.stringify(DEFAULT_SPECULATION_RULES_PATH)};\nconst IMMUTABLE_ASSET_CACHE_CONTROL = ${JSON.stringify(IMMUTABLE_ASSET_CACHE_CONTROL)};\nconst IMMUTABLE_ASSET_PATHS = new Set(${JSON.stringify(\n [...new Set(immutableAssetPaths)].sort(),\n )});\nconst AGENT_NATIVE_SOCIAL_IMAGE_PATH = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_ALT = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_TYPE = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_WIDTH = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n )};\nconst OG_IMAGE_META_RE = /<meta\\\\b(?=[^>]*\\\\bproperty=([\"'])og:image\\\\1)[^>]*>/i;\nconst TWITTER_CARD_META_RE = /<meta\\\\b(?=[^>]*\\\\bname=([\"'])twitter:card\\\\1)[^>]*>/i;\nconst TWITTER_IMAGE_META_RE = /<meta\\\\b(?=[^>]*\\\\bname=([\"'])twitter:image\\\\1)[^>]*>/i;\n\nfunction withAgentNativeSocialImageCacheBuster(image) {\n const separator = image.includes(\"?\") ? \"&\" : \"?\";\n return image + separator + \"v=\" + encodeURIComponent(AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER);\n}\n\nfunction defaultSocialImageUrl(request, basePath) {\n return withAgentNativeSocialImageCacheBuster(\n new URL(prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath), request.url).toString()\n );\n}\n\nfunction injectDefaultSocialImageMeta(html, imageUrl) {\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n\n const hasAnySocialImage =\n OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);\n const tags = [];\n\n if (!hasAnySocialImage) {\n tags.push('<meta property=\"og:image\" content=\"' + imageUrl + '\">');\n tags.push('<meta property=\"og:image:secure_url\" content=\"' + imageUrl + '\">');\n tags.push('<meta property=\"og:image:type\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_TYPE + '\">');\n tags.push('<meta property=\"og:image:width\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_WIDTH + '\">');\n tags.push('<meta property=\"og:image:height\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT + '\">');\n tags.push('<meta property=\"og:image:alt\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '\">');\n }\n if (!TWITTER_CARD_META_RE.test(html)) {\n tags.push('<meta name=\"twitter:card\" content=\"summary_large_image\">');\n }\n if (!hasAnySocialImage) {\n tags.push('<meta name=\"twitter:image\" content=\"' + imageUrl + '\">');\n tags.push('<meta name=\"twitter:image:alt\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '\">');\n }\n\n if (tags.length === 0) return html;\n return html.slice(0, headCloseIdx) + tags.join(\"\") + html.slice(headCloseIdx);\n}\n\nfunction isSsrHtmlOrDataResponse(headers, status, pathname) {\n if (status < 200 || status >= 400) return false;\n const contentType = (headers.get(\"content-type\") || \"\").toLowerCase();\n if (contentType.includes(\"text/html\")) return true;\n return pathname.endsWith(\".data\") && contentType.includes(\"text/x-script\");\n}\n\n/**\n * Apply the SSR cache policy to the response headers.\n *\n * SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE.\n * Every SSR HTML / React Router .data response gets the same public\n * stale-while-revalidate policy for ALL visitors, authenticated or not. The SSR\n * output is impersonal (the handler never reads the request's session/cookies),\n * so it is safe to hard-cache one shared copy at the edge. Do NOT reintroduce\n * per-user / cookie-based cache variation here (no private, no no-store, no\n * \"authenticated then don't cache\" branch) — that makes every logged-in\n * visitor's pages uncacheable. Per-user state is resolved client-side instead.\n */\nfunction applyDefaultSsrCacheHeader(headers, status, pathname) {\n if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;\n\n headers.set(\"cache-control\", DEFAULT_SSR_CACHE_CONTROL);\n headers.set(\"cdn-cache-control\", DEFAULT_SSR_CDN_CACHE_CONTROL);\n // Netlify function responses are dynamic by default and can otherwise show\n // Cache-Status fwd=bypass even with Cache-Control: public. Keep this\n // Netlify-specific header so SSR HTML/.data are served from the shared\n // durable CDN cache instead of stampeding origin — for every visitor.\n headers.set(\"netlify-cdn-cache-control\", DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL);\n}\n\nfunction applyDefaultSpeculationRulesHeader(headers, status, basePath) {\n if (status < 200 || status >= 400) return;\n if (headers.has(\"speculation-rules\")) return;\n\n const contentType = (headers.get(\"content-type\") || \"\").toLowerCase();\n if (!contentType.includes(\"text/html\")) return;\n\n // Cloudflare Speed Brain injects Speculation-Rules when origin omits this\n // header. Those browser prefetches carry Sec-Purpose: prefetch and\n // Cloudflare can return 503 before the request reaches origin. Publish an\n // explicit no-op ruleset by default; apps can still provide their own header.\n headers.set(\"speculation-rules\", '\"' + prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath) + '\"');\n}\nfunction isImmutableAssetRequest(request) {\n const pathname = stripAppBasePath(new URL(request.url).pathname);\n return IMMUTABLE_ASSET_PATHS.has(pathname);\n}\n\nfunction applyImmutableAssetCacheHeaders(response, request) {\n if (!isImmutableAssetRequest(request)) return response;\n if (!((response.status >= 200 && response.status < 300) || response.status === 304)) {\n return response;\n }\n const headers = new Headers(response.headers);\n headers.set(\"Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n headers.set(\"CDN-Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n headers.set(\"Netlify-CDN-Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nasync function rewriteMountedResponse(response, basePath, pathname, request) {\n const sentryClientConfigScript = getSentryClientConfigScript();\n const headers = new Headers(response.headers);\n applyDefaultSsrCacheHeader(headers, response.status, pathname);\n applyDefaultSpeculationRulesHeader(headers, response.status, basePath);\n\n const location = headers.get(\"location\");\n if (location?.startsWith(\"/\") && !location.startsWith(\"//\")) {\n headers.set(\"location\", prefixMountedPath(location, basePath));\n }\n\n const contentType = headers.get(\"content-type\") || \"\";\n if (!contentType.toLowerCase().includes(\"text/html\") || !response.body) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n const html = await response.text();\n headers.delete(\"content-length\");\n return new Response(\n injectHeadScript(\n injectDefaultSocialImageMeta(\n prefixMountedHtml(html, basePath),\n defaultSocialImageUrl(request, basePath),\n ),\n sentryClientConfigScript,\n ),\n {\n status: response.status,\n statusText: response.statusText,\n headers,\n },\n );\n}\n\nfunction requestWithMethod(request, method) {\n return new Request(request.url, {\n method,\n headers: request.headers,\n signal: request.signal,\n });\n}\n\nfunction requestWithPathname(request, pathname) {\n const url = new URL(request.url);\n if (url.pathname === pathname) return request;\n url.pathname = pathname;\n return new Request(url, request);\n}\n\nfunction isStaticAppShellRequest(request) {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return false;\n const p = stripAppBasePath(new URL(request.url).pathname);\n if (\n p.startsWith(\"/.well-known/\") ||\n p.startsWith(\"/_agent-native/\") ||\n isApiPath(p) ||\n p === \"/favicon.ico\" ||\n p === \"/favicon.png\" ||\n /\\\\.\\\\w+$/.test(p)\n ) {\n return false;\n }\n return true;\n}\n\nasync function fetchStaticAppShell(request, env) {\n if (!env?.ASSETS || !isStaticAppShellRequest(request)) return null;\n const basePath = getAppBasePath();\n const p = stripAppBasePath(new URL(request.url).pathname);\n const shellRequest = requestWithPathname(\n requestWithMethod(request, \"GET\"),\n \"/index.html\",\n );\n let response;\n try {\n response = await env.ASSETS.fetch(shellRequest);\n } catch {\n return null;\n }\n if (response.status === 404) return null;\n if (request.method === \"HEAD\") {\n return rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n request,\n );\n }\n return rewriteMountedResponse(response, basePath, p, request);\n}\n\n// API route handlers\n${routeImports.join(\"\\n\")}\n\n// Action handlers (auto-discovered from actions/)\n${actionImports.join(\"\\n\")}\n\n// Server plugins\n${pluginImports.join(\"\\n\")}\n\nlet _handler;\n\nasync function getHandler() {\n if (_handler) return _handler;\n\n const app = new H3();\n\n // Build a fake nitroApp surface so framework plugins (which expect\n // \\`nitroApp.h3[\"~middleware\"]\\`) can register routes via getH3App().\n const noop = () => {};\n const nitroApp = {\n h3: app,\n hooks: { hook: noop, callHook: noop, hookOnce: noop },\n captureError: noop,\n };\n\n // CORS — applied as global middleware via .use(handler)\n app.use(defineEventHandler((event) => {\n if (event.req.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,X-Agent-Native-Embed-Target\",\n },\n });\n }\n }));\n\n // Run plugins — they call getH3App(nitroApp).use(path, handler) which\n // pushes path-prefix middleware onto app[\"~middleware\"].\n // Pre-mark every build-time plugin slot before any plugin awaits the runtime\n // default bootstrap. Bundled serverless workers often lack server/plugins/\n // on disk, so runtime discovery would otherwise auto-mount duplicate\n // framework defaults before later custom plugins get a chance to mark\n // themselves as provided.\n${generatedPluginMarks.map((stem) => ` markGeneratedPluginProvided(nitroApp, ${JSON.stringify(stem)});`).join(\"\\n\")}\n${pluginCalls.join(\"\\n\")}\n\n // Register API routes\n${routeRegistrations.join(\"\\n\")}\n\n // Register action routes (/_agent-native/actions/*)\n${actionRegistrations.join(\"\\n\")}\n\n${\n includeReactRouterSsr\n ? ` // SSR catch-all for React Router\n const rrHandler = createRequestHandler(() => serverBuild);\n app.all(\"/**\", defineEventHandler(async (event) => {\n const basePath = getAppBasePath();\n const p = stripAppBasePath(new URL(event.req.url).pathname);\n if (\n p.startsWith(\"/.well-known/\") ||\n p.startsWith(\"/_agent-native/\") ||\n isApiPath(p) ||\n p === \"/favicon.ico\" ||\n p === \"/favicon.png\" ||\n (/\\\\.\\\\w+$/.test(p) && !p.endsWith(\".data\"))\n ) {\n return new Response(null, { status: 404 });\n }\n const request = requestWithPathname(event.req, p);\n if (event.req.method === \"HEAD\") {\n const getRequest = requestWithMethod(request, \"GET\");\n const response = await rrHandler(getRequest);\n return rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n getRequest\n );\n }\n return rewriteMountedResponse(await rrHandler(request), basePath, p, request);\n }));`\n : \"\"\n}\n\n _handler = app.fetch.bind(app);\n return _handler;\n}\n\nexport default {\n async fetch(request, env, ctx) {\n // Expose env and ctx bindings globally for compatibility\n if (ctx) globalThis.__cf_ctx = ctx;\n if (env) {\n globalThis.process = globalThis.process || { env: {} };\n globalThis.process.env = globalThis.process.env || {};\n // Expose D1/KV/R2 bindings on globalThis.__cf_env for the db layer\n globalThis.__cf_env = env;\n for (const [key, value] of Object.entries(env)) {\n if (typeof value === \"string\") {\n globalThis.process.env[key] = value;\n }\n }\n }\n\n // Try serving static assets first (CF Pages advanced mode).\n // Only attempt this for GET/HEAD — the ASSETS binding is a static file\n // server and returns 405 for any other method, which would short-circuit\n // API calls (PUT/POST/DELETE to /_agent-native/*) before they reach our\n // h3 middleware.\n if (env?.ASSETS && (request.method === \"GET\" || request.method === \"HEAD\")) {\n try {\n const assetResponse = await env.ASSETS.fetch(request);\n if (assetResponse.status !== 404) {\n return applyImmutableAssetCacheHeaders(assetResponse, request);\n }\n } catch {\n // Asset fetch failed — fall through to SSR\n }\n }\n\n const handler = await getHandler();\n const response = await handler(requestWithMountedApiPrefixStripped(request));\n${\n includeReactRouterSsr\n ? \" return response;\"\n : ` if (response.status === 404) {\n const shellResponse = await fetchStaticAppShell(request, env);\n if (shellResponse) return shellResponse;\n }\n return response;`\n}\n }\n};\n`;\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll('\"', \""\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\");\n}\n\nfunction findReactRouterManifest(distDir: string): ReactRouterAssetManifest {\n const assetsDir = path.join(distDir, \"assets\");\n const manifestFile = fs\n .readdirSync(assetsDir)\n .find((file) => /^manifest-[\\w-]+\\.js$/.test(file));\n if (!manifestFile) {\n throw new Error(`React Router client manifest not found in ${assetsDir}`);\n }\n\n const source = fs.readFileSync(path.join(assetsDir, manifestFile), \"utf8\");\n const match = source.match(/^window\\.__reactRouterManifest=(.*);?\\s*$/);\n if (!match) {\n throw new Error(`Could not parse React Router manifest ${manifestFile}`);\n }\n\n return JSON.parse(match[1].replace(/;$/, \"\")) as ReactRouterAssetManifest;\n}\n\nfunction collectModulePreloads(\n manifest: ReactRouterAssetManifest,\n route: ReactRouterAssetManifestRoute,\n): string[] {\n const paths = new Set<string>();\n const add = (value: string | undefined) => {\n if (value) paths.add(value);\n };\n add(manifest.url);\n add(manifest.entry.module);\n manifest.entry.imports?.forEach(add);\n add(route.module);\n route.imports?.forEach(add);\n add(route.clientActionModule);\n add(route.clientLoaderModule);\n add(route.clientMiddlewareModule);\n add(route.hydrateFallbackModule);\n return [...paths];\n}\n\nfunction collectStylesheetLinks(\n manifest: ReactRouterAssetManifest,\n route: ReactRouterAssetManifestRoute,\n): string[] {\n return [...new Set([...(manifest.entry.css ?? []), ...(route.css ?? [])])];\n}\n\nfunction generateRouteModuleImportScript(\n manifest: ReactRouterAssetManifest,\n route: ReactRouterAssetManifestRoute,\n): string {\n const modules = [\n [\"route0\", route.module],\n [\"route0_clientAction\", route.clientActionModule],\n [\"route0_clientLoader\", route.clientLoaderModule],\n [\"route0_clientMiddleware\", route.clientMiddlewareModule],\n [\"route0_hydrateFallback\", route.hydrateFallbackModule],\n ] as const;\n const imports = modules\n .filter(([, modulePath]) => modulePath)\n .map(\n ([name, modulePath]) =>\n `import * as ${name} from ${JSON.stringify(modulePath)};`,\n );\n const parts = modules\n .filter(([, modulePath]) => modulePath)\n .map(([name]) => `...${name}`);\n\n return [\n `import ${JSON.stringify(manifest.url)};`,\n ...imports,\n `window.__reactRouterRouteModules = {${JSON.stringify(route.id)}:{${parts.join(\",\")}}};`,\n `import(${JSON.stringify(manifest.entry.module)});`,\n ].join(\"\\n\");\n}\n\nconst EMPTY_REACT_ROUTER_TURBO_STREAM =\n '[{\"_1\":2,\"_3\":-5,\"_4\":-5},\"loaderData\",{},\"actionData\",\"errors\"]\\n';\n\n// Manifest fallbacks cannot execute server loaders, so root loaders get the\n// framework's default locale shape to keep hydration from reading undefined.\nconst DEFAULT_ROOT_LOADER_REACT_ROUTER_TURBO_STREAM =\n '[{\"_1\":2,\"_3\":-5,\"_4\":-5},\"loaderData\",{\"_5\":6},\"actionData\",\"errors\",\"root\",{\"_7\":8,\"_9\":10,\"_11\":12,\"_13\":14},\"locale\",\"en-US\",\"preference\",{\"_7\":15},\"dir\",\"ltr\",\"messages\",{},\"system\"]\\n';\n\nexport function generateCloudflarePagesStaticShellFromManifest(\n manifest: ReactRouterAssetManifest,\n basePath = normalizeConfiguredAppBasePath(),\n): string {\n const rootRoute = manifest.routes.root;\n if (!rootRoute) {\n throw new Error(\"React Router manifest is missing the root route\");\n }\n\n const modulePreloads = collectModulePreloads(manifest, rootRoute)\n .map(\n (href) =>\n `<link rel=\"modulepreload\" href=\"${escapeHtmlAttribute(href)}\"/>`,\n )\n .join(\"\");\n const stylesheets = collectStylesheetLinks(manifest, rootRoute)\n .map(\n (href) => `<link rel=\"stylesheet\" href=\"${escapeHtmlAttribute(href)}\"/>`,\n )\n .join(\"\");\n const routeModuleScript = generateRouteModuleImportScript(\n manifest,\n rootRoute,\n );\n const context = {\n basename: basePath || \"/\",\n future: { unstable_optimizeDeps: false },\n routeDiscovery: { mode: \"initial\" },\n ssr: true,\n isSpaMode: true,\n };\n const encodedInitialState = rootRoute.hasLoader\n ? DEFAULT_ROOT_LOADER_REACT_ROUTER_TURBO_STREAM\n : EMPTY_REACT_ROUTER_TURBO_STREAM;\n\n return `<!DOCTYPE html><html lang=\"en\"><head><meta charSet=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\"/><link rel=\"manifest\" href=\"/manifest.json\"/><link rel=\"icon\" type=\"image/svg+xml\" href=\"/favicon.svg\"/>${modulePreloads}${stylesheets}</head><body><div style=\"display:flex;align-items:center;justify-content:center;height:100vh;width:100%\"><svg role=\"status\" aria-label=\"Loading\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"animation:an-spin 1s linear infinite;opacity:0.7\"><path d=\"M21 12a9 9 0 1 1-6.219-8.56\"></path></svg><style>@keyframes an-spin { to { transform: rotate(360deg) } } @media (prefers-color-scheme: dark) { html { background: #09090b; color: #fafafa } }</style></div><script>window.__reactRouterContext = ${JSON.stringify(context)};window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());</script><script type=\"module\" async=\"\">${routeModuleScript}</script><!--$--><script>window.__reactRouterContext.streamController.enqueue(${JSON.stringify(encodedInitialState)});</script><!--$--><script>window.__reactRouterContext.streamController.close();</script><!--/$--><!--/$--></body></html>`;\n}\n\nfunction writeCloudflarePagesStaticShell({\n serverDir,\n distDir,\n tmpDir,\n}: {\n serverDir: string;\n distDir: string;\n tmpDir: string;\n}): void {\n const serverEntry = path.join(serverDir, \"index.js\");\n if (!fs.existsSync(serverEntry)) {\n throw new Error(`React Router server build not found at ${serverEntry}`);\n }\n\n const outFile = path.join(distDir, \"index.html\");\n const renderScript = path.join(tmpDir, \"render-cloudflare-static-shell.mjs\");\n const basePath = normalizeConfiguredAppBasePath();\n fs.writeFileSync(\n renderScript,\n `\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\n\nconst cwd = ${JSON.stringify(cwd)};\nconst serverEntry = ${JSON.stringify(serverEntry)};\nconst outFile = ${JSON.stringify(outFile)};\nconst basePath = ${JSON.stringify(basePath)};\n\nconst requireFromApp = createRequire(cwd + \"/package.json\");\nconst reactRouterEntry = requireFromApp.resolve(\"react-router\");\nconst { createRequestHandler } = await import(pathToFileURL(reactRouterEntry).href);\nconst serverBuild = await import(pathToFileURL(serverEntry).href);\nconst handler = createRequestHandler(serverBuild, \"production\");\nconst pathname = basePath ? basePath + \"/\" : \"/\";\nconst response = await handler(\n new Request(new URL(pathname, \"https://agent-native.local\"), {\n headers: { \"X-React-Router-SPA-Mode\": \"yes\" },\n }),\n);\nconst html = await response.text();\n\nif (!html || !html.includes(\"__reactRouterContext\") || !html.includes(\"entry.client\")) {\n throw new Error(\"React Router did not render a usable Cloudflare Pages static shell\");\n}\n\nfs.writeFileSync(outFile, html);\nprocess.exit(0);\n`,\n );\n\n try {\n execFileSync(process.execPath, [renderScript], {\n cwd,\n env: {\n ...process.env,\n NODE_ENV: process.env.NODE_ENV || \"production\",\n IS_RR_BUILD_REQUEST: \"yes\",\n },\n stdio: \"inherit\",\n });\n console.log(\"[deploy] Wrote Cloudflare Pages static app shell.\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(\n `[deploy] React Router static shell render failed; using manifest fallback. ${message}`,\n );\n fs.writeFileSync(\n outFile,\n generateCloudflarePagesStaticShellFromManifest(\n findReactRouterManifest(distDir),\n basePath,\n ),\n );\n console.log(\"[deploy] Wrote Cloudflare Pages static app shell fallback.\");\n }\n}\n\n/**\n * Build for Cloudflare Pages.\n * Output structure:\n * dist/\n * _worker.js (bundled worker entry)\n * assets/ (static client assets)\n */\nasync function buildCloudflarePages() {\n generateActionRegistryForProject(cwd);\n\n const buildDir = path.join(cwd, \"build\");\n const clientDir = path.join(buildDir, \"client\");\n const serverDir = path.join(buildDir, \"server\");\n const distDir = path.join(cwd, \"dist\");\n\n // Verify build output exists\n if (!fs.existsSync(clientDir) || !fs.existsSync(serverDir)) {\n console.error(\n \"Build output not found at build/client/ and build/server/. Run react-router build first.\",\n );\n process.exit(1);\n }\n\n // Clean dist\n if (fs.existsSync(distDir)) {\n fs.rmSync(distDir, { recursive: true });\n }\n fs.mkdirSync(distDir, { recursive: true });\n\n // Copy client assets to dist/\n copyDir(clientDir, distDir);\n\n const tmpDir = path.join(cwd, \".deploy-tmp\");\n fs.mkdirSync(tmpDir, { recursive: true });\n writeCloudflarePagesStaticShell({ serverDir, distDir, tmpDir });\n\n // Exclude _worker.js from being served as a public asset\n fs.writeFileSync(path.join(distDir, \".assetsignore\"), \"_worker.js\\n\");\n\n // Write package metadata inside _worker.js/ for the ES module worker that\n // Wrangler compiles and uploads for Cloudflare Pages.\n fs.mkdirSync(path.join(distDir, \"_worker.js\"), { recursive: true });\n fs.writeFileSync(\n path.join(distDir, \"_worker.js\", \"package.json\"),\n JSON.stringify({ main: \"index.js\", type: \"module\" }),\n );\n\n // Create empty stub for native modules that wrangler's bundler needs to resolve\n const stubsDir = path.join(distDir, \"_worker.js\", \"stubs\");\n fs.mkdirSync(stubsDir, { recursive: true });\n fs.writeFileSync(\n path.join(stubsDir, \"empty.js\"),\n \"export default {}; export const watch = () => ({ close() {} }); export const Database = class {};\\n\",\n );\n\n // Discover routes, plugins, actions, and the workspace core (if any).\n const routes = await discoverApiRoutes(cwd);\n const plugins = await discoverPlugins(cwd);\n const actions = await discoverActionFiles(cwd);\n const missingDefaults = await getMissingDefaultPlugins(cwd);\n const workspaceCore = await getWorkspaceCoreExports(cwd);\n const includeReactRouterSsr = false;\n\n const workspaceSlotCount = workspaceCore\n ? Object.keys(workspaceCore.plugins).length\n : 0;\n console.log(\n `[deploy] ${routes.length} API routes, ${actions.length} actions, ${plugins.length} plugins (${plugins.filter((p) => isNodeOnlyPlugin(p)).length} skipped as Node-only), ${missingDefaults.length} auto-mounted defaults${workspaceCore ? `, workspace-core ${workspaceCore.packageName} (${workspaceSlotCount} plugin slots)` : \"\"}`,\n );\n\n // Generate the worker entry\n const immutableAssetPaths = collectImmutableAssetPaths(clientDir);\n const entrySource = generateWorkerEntry(\n routes,\n plugins,\n missingDefaults,\n actions,\n workspaceCore,\n immutableAssetPaths,\n normalizeConfiguredAppBasePath(),\n { includeReactRouterSsr },\n );\n\n // Create _worker.js output directory\n const workerOutDir = path.join(distDir, \"_worker.js\");\n fs.mkdirSync(workerOutDir, { recursive: true });\n\n // Write the worker entry\n const entryFile = path.join(workerOutDir, \"index.js\");\n\n // Rewrite the server-build import to point at the copied files when this\n // worker intentionally includes React Router SSR.\n const adjustedEntry = includeReactRouterSsr\n ? entrySource.replace(\n `import * as serverBuild from \"./server-build.js\";`,\n `import * as serverBuild from \"./server/index.js\";`,\n )\n : entrySource;\n\n // Write a temp file for esbuild to bundle everything into a single worker entry.\n // When React Router SSR is enabled, the server build is copied to tmp so\n // esbuild can resolve it. Cloudflare Pages currently uses a static app shell\n // instead so the worker stays under the platform bundle size limit.\n // Name the entry \"index.js\" so esbuild outputs index.js in the outdir,\n // matching the _worker.js/index.js entry point that Cloudflare Pages expects.\n const tmpEntry = path.join(tmpDir, \"index.js\");\n fs.writeFileSync(tmpEntry, adjustedEntry);\n\n if (includeReactRouterSsr) {\n copyDir(serverDir, path.join(tmpDir, \"server\"));\n }\n\n // Create a require shim so CJS require(\"fs\") calls resolve via ESM imports.\n // This is injected via esbuild --inject to replace its broken __require shim.\n fs.writeFileSync(\n path.join(tmpDir, \"_require-shim.js\"),\n generateRequireShim(),\n );\n\n const nitroServerAssetsStub = path.join(\n tmpDir,\n \"_nitro-server-assets-stub.js\",\n );\n fs.writeFileSync(\n nitroServerAssetsStub,\n [\n \"const empty = async () => undefined;\",\n \"export const assets = {\",\n \" getItem: empty,\",\n \" getItemRaw: empty,\",\n \" getKeys: async () => [],\",\n \" getMeta: async () => undefined,\",\n \" hasItem: async () => false,\",\n \"};\",\n \"export default assets;\",\n \"\",\n ].join(\"\\n\"),\n );\n\n // Create stub modules for native/Node-only deps that can't run on Workers.\n // These get resolved by esbuild instead of the real modules, avoiding bundling\n // native code that would fail on the Workers runtime. Uninstalled optional\n // AI SDK provider packages are stubbed the same way so their literal dynamic\n // import() sites in ai-sdk-engine don't fail the bundle.\n const workerStubModules: Record<string, string> = {\n ...CLOUDFLARE_WORKER_STUB_MODULES,\n ...uninstalledOptionalAiSdkStubs(cwd),\n };\n const stubDir = path.join(tmpDir, \"node_modules\");\n for (const [mod, source] of Object.entries(workerStubModules)) {\n const modDir = path.join(stubDir, mod);\n fs.mkdirSync(modDir, { recursive: true });\n fs.writeFileSync(path.join(modDir, \"index.js\"), source);\n fs.writeFileSync(\n path.join(modDir, \"package.json\"),\n JSON.stringify({ name: mod, main: \"index.js\", type: \"module\" }),\n );\n }\n const stubAliases = Object.keys(workerStubModules).map(\n (mod) => `--alias:${mod}=${path.join(stubDir, mod, \"index.js\")}`,\n );\n const nodeBuiltinStubDir = path.join(tmpDir, \"node-builtin-stubs\");\n fs.mkdirSync(nodeBuiltinStubDir, { recursive: true });\n const nodeBuiltinStubAliases: string[] = [];\n for (const [mod, source] of Object.entries(\n CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES,\n ).sort(([a], [b]) => b.length - a.length)) {\n const stubFile = path.join(\n nodeBuiltinStubDir,\n `${mod.replace(/\\W+/g, \"_\")}.js`,\n );\n fs.writeFileSync(stubFile, source);\n nodeBuiltinStubAliases.push(\n `--alias:${mod}=${stubFile}`,\n `--alias:node:${mod}=${stubFile}`,\n );\n }\n\n const esbuildBin = findEsbuild();\n\n // Externalize node builtins (both bare and node: prefixed) — the require\n // shim handles bare ones. Also alias every `node:*` specifier to its bare\n // name so esbuild emits `import from \"fs\"` everywhere, never\n // `import from \"node:fs\"`. CF Pages Functions (wrangler 3.x, nodejs_compat\n // v1) rejects the `node:` prefix in chunks with:\n // No such module \"node:fs\" imported from chunks/...\n // The alias is the authoritative fix; the post-build strip stays as belt\n // & suspenders in case esbuild emits a node: string via some other path.\n const builtinNames = getNodeBuiltinNames();\n // Only externalize bare names. node:* externals would otherwise pin\n // the prefix in output; instead we alias node:* → bare so anything that\n // resolves past alias land as bare externals.\n const nodeBuiltinStubs = new Set(\n Object.keys(CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES),\n );\n const nodeExternals = builtinNames\n .filter((n) => !nodeBuiltinStubs.has(n))\n .sort((a, b) => b.length - a.length)\n .map((n) => `--external:${n}`);\n const nodeAliases = builtinNames\n .filter((n) => !nodeBuiltinStubs.has(n))\n .sort((a, b) => b.length - a.length)\n .map((n) => `--alias:node:${n}=${n}`);\n\n // Hard externalize large client-only / node-only libraries so they don't\n // bloat the edge worker. These are never executed in the CF Pages runtime\n // — mermaid/excalidraw render in the browser, pdf-parse and @google/genai\n // run from node-only action scripts. Without this, slides' bundle hits\n // the 25 MiB Pages Functions limit.\n //\n // @anthropic-ai/tokenizer (tiktoken .wasm) and @resvg/resvg-js (native\n // .node binding) can't be bundled by esbuild at all — no loader for those\n // files. Both import sites degrade gracefully when the runtime import\n // fails: context-xray token counts fall back to char/4 estimates and the\n // OG image route falls back to SVG.\n const heavyClientExternals = CLOUDFLARE_WORKER_ESBUILD_EXTERNALS.filter(\n (p) => !Object.hasOwn(CLOUDFLARE_WORKER_STUB_MODULES, p),\n ).map((p) => `--external:${p}`);\n\n const esbuildCommand = esbuildSpawnCommand(esbuildBin, [\n tmpEntry,\n \"--bundle\",\n \"--format=esm\",\n \"--target=es2022\",\n // browser platform for npm resolution; node builtins externalized separately\n \"--platform=browser\",\n \"--minify\",\n // Single-file bundle (no --splitting). CF Pages Functions' deploy\n // validator fails to load chunked _worker.js/ bundles even when the\n // chunks contain only bare node-builtin imports (wrangler 3.101.0\n // + nodejs_compat v2). Matches main's working config.\n `--outdir=${workerOutDir}`,\n \"--conditions=workerd,worker,import\",\n // The ssr-handler imports a virtual module that only exists at dev time\n \"--external:virtual:react-router/server-build\",\n `--alias:#nitro/virtual/server-assets=${nitroServerAssetsStub}`,\n // Banner: override the __require shim that esbuild generates for CJS modules.\n // This provides a real require() backed by ESM imports of node builtins.\n // Without this, CF Workers rejects the bundle because esbuild's default\n // __require shim throws \"Dynamic require of X is not supported\".\n `--banner:js=${generateRequireShim()}`,\n // Externalize node: builtins — CF Workers runtime provides them\n ...nodeExternals,\n ...heavyClientExternals,\n ...stubAliases,\n ...nodeBuiltinStubAliases,\n // Rewrite node:* -> bare names so chunks never contain node: imports\n ...nodeAliases,\n ]);\n execFileSync(esbuildCommand.file, esbuildCommand.args, {\n stdio: \"inherit\",\n cwd,\n });\n\n // Clean up tmp\n fs.rmSync(tmpDir, { recursive: true });\n\n // Rewrite the external virtual import to a local stub.\n // esbuild externalizes \"virtual:react-router/server-build\" (used by ssr-handler),\n // but wrangler re-bundles and chokes on it. Replace the import with a no-op stub.\n const virtualStub = path.join(workerOutDir, \"chunks\", \"_virtual-stub.js\");\n fs.mkdirSync(path.dirname(virtualStub), { recursive: true });\n fs.writeFileSync(virtualStub, \"export default {};\\n\");\n\n // Post-build patches — apply to ALL .js files in the worker output directory\n // (entry + chunks) since code can land in any chunk after splitting.\n const allJsFiles = getAllJsFiles(workerOutDir);\n for (const jsFile of allJsFiles) {\n let code = fs.readFileSync(jsFile, \"utf-8\");\n const isEntry = path.basename(jsFile) === \"index.js\";\n\n // Strip \"node:\" prefix from all imports/requires. Cloudflare Pages\n // Functions runs under nodejs_compat v1, which exposes builtins as\n // bare names (\"fs\") and rejects \"node:fs\" at worker init:\n // No such module \"node:fs\" imported from chunks/...\n // (Workers-on-the-edge use v2 and require the prefix; Pages lags.)\n // Preserve the original quote char (single vs double) when rewriting —\n // esbuild's minifier sometimes places `import('node:buffer')` inside a\n // double-quoted string literal; swapping to double quotes breaks the\n // outer literal and produces `Unexpected identifier 'buffer'`.\n code = code.replace(\n /\\bfrom(\\s*)([\"'])node:([^\"']+)\\2/g,\n (_, ws, q, mod) => `from${ws}${q}${mod}${q}`,\n );\n code = code.replace(\n /\\bimport(\\s*)([\"'])node:([^\"']+)\\2/g,\n (_, ws, q, mod) => `import${ws}${q}${mod}${q}`,\n );\n // Strip `node:` prefix from any string literal that names a node\n // builtin. Covers dynamic imports, require(), getBuiltinModule(),\n // and minified wrappers like `Ut(\"node:fs\")` that Nitro/h3 emit.\n // Pages' loader scans chunks for `\"node:*\"` literals and fails with\n // 'No such module \"node:fs\"' whether or not the string is reached\n // at runtime. Scoping to known builtins avoids touching user data.\n // Sorted longest-first so `fs/promises` matches before `fs`.\n const builtinsPattern = [...NODE_BUILTINS]\n .sort((a, b) => b.length - a.length)\n .join(\"|\");\n const builtinRe = new RegExp(`([\"'])node:(${builtinsPattern})\\\\1`, \"g\");\n code = code.replace(\n builtinRe,\n (_, q: string, mod: string) => `${q}${mod}${q}`,\n );\n\n // Rewrite virtual:react-router/server-build imports to the local stub.\n // The generated entry handles SSR directly; this import is dead code from ssr-handler.\n const relStub = path\n .relative(path.dirname(jsFile), virtualStub)\n .replace(/\\\\/g, \"/\");\n code = code.replace(\n /[\"']virtual:react-router\\/server-build[\"']/g,\n `\"./${relStub}\"`,\n );\n\n // Patch createRequire(import.meta.url) — import.meta.url is undefined in CF Workers.\n // Matches both `from \"module\"` and `from \"node:module\"` — with the node:\n // prefix preserved (for nodejs_compat_v2), the latter is what esbuild now emits.\n code = code.replace(\n /\\bimport\\s*\\{\\s*createRequire\\s+as\\s+([\\w$]+)\\s*\\}\\s*from\\s*[\"'](?:node:)?module[\"']\\s*;/g,\n \"var $1 = function() { return typeof require !== 'undefined' ? require : function(m) { throw new Error('require not supported: ' + m); }; };\",\n );\n\n // Patch remaining import.meta.url occurrences — when wrangler/Pages\n // re-bundles the worker, inner modules get an emptied import.meta, so\n // fileURLToPath(import.meta.url) throws at module init (\"path\" argument\n // must be string, received undefined). Same treatment as the Vite\n // server-build path: replace with a stable synthetic file URL.\n code = code.replace(/\\bimport\\.meta\\.url\\b/g, '\"file:///worker.mjs\"');\n\n // Patch setInterval/setTimeout at module scope — CF Workers disallows timers in global scope.\n // Some dependencies (e.g. Anthropic SDK rate limiter) call setInterval at module init.\n // With code splitting, chunks evaluate before the entry, so the shim must be in every file.\n // The restore only happens in the entry's fetch() handler.\n if (!code.includes(\"__origSetInterval\")) {\n const timerShim = [\n \"var __origSetInterval=globalThis.setInterval;\",\n \"globalThis.setInterval=function(){return{unref(){},ref(){},close(){}}};\",\n ].join(\"\");\n code = timerShim + code;\n }\n if (isEntry) {\n const timerRestore =\n \"if(__origSetInterval)globalThis.setInterval=__origSetInterval;\";\n code = code.replace(\n /async fetch\\(request,\\s*env,\\s*ctx\\)\\s*\\{/,\n (match) => match + timerRestore,\n );\n }\n\n fs.writeFileSync(jsFile, code);\n }\n\n // Report size\n const entrySize = fs.statSync(entryFile).size;\n const totalSize = getDirSize(workerOutDir);\n const chunkCount = allJsFiles.length - 1; // exclude entry\n console.log(\n `[deploy] Cloudflare Pages output written to dist/ (entry: ${(entrySize / 1024).toFixed(0)}KB, ${chunkCount} chunks, total: ${(totalSize / 1024 / 1024).toFixed(1)}MB)`,\n );\n}\n\nconst NODE_BUILTINS = [\n \"assert\",\n \"async_hooks\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"console\",\n \"constants\",\n \"crypto\",\n \"dgram\",\n \"diagnostics_channel\",\n \"dns\",\n \"dns/promises\",\n \"domain\",\n \"events\",\n \"fs\",\n \"fs/promises\",\n \"http\",\n \"http2\",\n \"https\",\n \"inspector\",\n \"module\",\n \"net\",\n \"os\",\n \"path\",\n \"perf_hooks\",\n \"process\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"repl\",\n \"sqlite\",\n \"stream\",\n \"stream/web\",\n \"string_decoder\",\n \"sys\",\n \"timers\",\n \"tls\",\n \"trace_events\",\n \"tty\",\n \"url\",\n \"util\",\n \"v8\",\n \"vm\",\n \"wasi\",\n \"worker_threads\",\n \"zlib\",\n];\n\nexport function getNodeBuiltinNames(): string[] {\n return NODE_BUILTINS;\n}\n\n/**\n * Generate a require() shim that bridges CJS require(\"fs\") calls to ESM imports.\n * Injected via esbuild --inject so CJS deps work on Workers runtime.\n */\nfunction generateRequireShim(): string {\n // Shim Node builtins that Cloudflare Pages can import, and return lazy\n // unavailable proxies for builtins that Pages Functions reject at upload\n // time (child_process, fs, net, etc.). This lets optional Node-only code stay\n // present in the shared bundle without making worker initialization fail.\n const stubbed = new Set(\n Object.keys(CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES),\n );\n const shimmed = NODE_BUILTINS.filter((name) => !stubbed.has(name));\n\n // Bare module names — CF Pages Functions runs under nodejs_compat v1,\n // which rejects \"node:fs\" and only accepts \"fs\". The post-build pass in\n // buildCloudflarePages() also strips any `node:` prefix that esbuild or\n // dependencies emit elsewhere.\n const imports = shimmed\n .map((m) => `import __${m.replace(\"/\", \"_\")} from \"${m}\";`)\n .join(\"\");\n // Only bare-name keys. Pages' Functions loader appears to scan chunks\n // for \"node:*\" string literals and pre-resolves them as module specs —\n // so keeping \"node:fs\" as an object key caused deploy to fail with\n // 'No such module \"node:fs\"' even though nothing imported it. The\n // post-build strip turns every runtime `require(\"node:fs\")` into\n // `require(\"fs\")` so bare keys are sufficient.\n const entries = shimmed\n .map((m) => `\"${m}\":__${m.replace(\"/\", \"_\")}`)\n .join(\",\");\n const stubEntries = Array.from(stubbed)\n .sort()\n .map((m) => `\"${m}\":__unavailable(\"${m}\")`)\n .join(\",\");\n const allEntries = [entries, stubEntries].filter(Boolean).join(\",\");\n\n const messageChannelPolyfill = `if(typeof MessageChannel===\"undefined\"){globalThis.MessageChannel=class{constructor(){const a={onmessage:null},b={onmessage:null};a.postMessage=d=>{if(b.onmessage)setTimeout(()=>b.onmessage({data:d}),0)};b.postMessage=d=>{if(a.onmessage)setTimeout(()=>a.onmessage({data:d}),0)};this.port1=a;this.port2=b}}}`;\n return `${imports}\\n${messageChannelPolyfill}\\nconst __unavailable=(m)=>new Proxy({}, { get(_target, prop) { return (..._args) => { throw new Error(m + \".\" + String(prop) + \" is unavailable in Cloudflare Pages workers\"); }; } });\\nconst __mods={${allEntries}};export var require=globalThis.require||function(m){const r=__mods[m];if(r!==undefined)return r;throw new Error(\"Cannot require: \"+m)};\\n`;\n}\n\nfunction findEsbuild(): string {\n // Try to resolve esbuild's binary via Node module resolution\n // This works regardless of hoisting or .bin symlink creation\n try {\n const _require = createRequire(cwd + \"/\");\n const esbuildPkg = path.dirname(_require.resolve(\"esbuild/package.json\"));\n const bin = path.join(esbuildPkg, \"bin\", \"esbuild\");\n if (fs.existsSync(bin)) return bin;\n } catch {}\n\n // Fallback: check local and workspace .bin\n const localBin = path.resolve(cwd, \"node_modules/.bin/esbuild\");\n if (fs.existsSync(localBin)) return localBin;\n\n const workspaceRoot = findWorkspaceRoot(cwd);\n if (workspaceRoot) {\n const workspaceBin = path.resolve(\n workspaceRoot,\n \"node_modules/.bin/esbuild\",\n );\n if (fs.existsSync(workspaceBin)) return workspaceBin;\n }\n\n return \"esbuild\";\n}\n\n/**\n * `esbuild/bin/esbuild` is a `#!/usr/bin/env node` JS shim, not a native\n * executable. Shebangs don't exist on Windows, so `execFileSync(shim)` fails\n * there with ENOENT even though the file exists. Run any node-shebang script\n * through the current Node executable (works on every platform — the shim\n * locates and execs the real platform binary itself); native executables and\n * PATH lookups spawn directly.\n */\nexport function esbuildSpawnCommand(\n esbuildBin: string,\n args: string[],\n): { file: string; args: string[] } {\n if (isNodeShebangScript(esbuildBin)) {\n return { file: process.execPath, args: [esbuildBin, ...args] };\n }\n return { file: esbuildBin, args };\n}\n\nfunction isNodeShebangScript(file: string): boolean {\n if (!file.includes(\"/\") && !file.includes(path.sep)) return false;\n try {\n const fd = fs.openSync(file, \"r\");\n const buf = Buffer.alloc(128);\n const bytesRead = fs.readSync(fd, buf, 0, buf.length, 0);\n fs.closeSync(fd);\n const firstLine = buf.toString(\"utf8\", 0, bytesRead).split(/\\r?\\n/)[0];\n // Only the shebang line decides — a `#!/bin/sh` wrapper that merely\n // mentions node in its body must still spawn directly.\n return firstLine.startsWith(\"#!\") && /\\bnode\\s*$/.test(firstLine);\n } catch {\n return false;\n }\n}\n\nfunction findWorkspaceRoot(dir: string): string | null {\n let current = dir;\n while (current !== path.dirname(current)) {\n if (\n fs.existsSync(path.join(current, \"pnpm-workspace.yaml\")) ||\n fs.existsSync(path.join(current, \"pnpm-lock.yaml\"))\n ) {\n return current;\n }\n current = path.dirname(current);\n }\n return null;\n}\n\n/** Recursively collect all .js files in a directory. */\nfunction getAllJsFiles(dir: string): string[] {\n const results: string[] = [];\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...getAllJsFiles(fullPath));\n } else if (entry.name.endsWith(\".js\")) {\n results.push(fullPath);\n }\n }\n return results;\n}\n\nfunction getDirSize(dir: string): number {\n let size = 0;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n size += getDirSize(fullPath);\n } else {\n size += fs.statSync(fullPath).size;\n }\n }\n return size;\n}\n\nexport function copyDir(\n src: string,\n dest: string,\n ancestorRealPaths = new Set<string>(),\n) {\n const realSrc = fs.realpathSync(src);\n if (ancestorRealPaths.has(realSrc)) return;\n const nextAncestorRealPaths = new Set(ancestorRealPaths);\n nextAncestorRealPaths.add(realSrc);\n\n fs.mkdirSync(dest, { recursive: true });\n const entries = fs.readdirSync(src, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n if (entry.isSymbolicLink()) {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(srcPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.warn(\n `[deploy] Skipping broken symlink while copying ${srcPath}`,\n );\n continue;\n }\n throw error;\n }\n if (stat.isDirectory()) {\n copyDir(srcPath, destPath, nextAncestorRealPaths);\n } else {\n fs.copyFileSync(srcPath, destPath);\n }\n } else if (entry.isDirectory()) {\n copyDir(srcPath, destPath, nextAncestorRealPaths);\n } else {\n fs.copyFileSync(srcPath, destPath);\n }\n }\n}\n\nconst LIBSQL_NATIVE_PACKAGE_NAMES = [\n \"darwin-arm64\",\n \"darwin-x64\",\n \"linux-arm-gnueabihf\",\n \"linux-arm-musleabihf\",\n \"linux-arm64-gnu\",\n \"linux-arm64-musl\",\n \"linux-x64-gnu\",\n \"linux-x64-musl\",\n \"win32-x64-msvc\",\n];\nconst FFMPEG_STATIC_PACKAGE_NAME = \"ffmpeg-static\";\nconst RESVG_SCOPE = \"@resvg\";\nconst RESVG_PACKAGE_PREFIX = \"resvg-js\";\nconst FFMPEG_STATIC_BINARY_NAMES =\n process.platform === \"win32\" ? [\"ffmpeg.exe\", \"ffmpeg\"] : [\"ffmpeg\"];\nconst SERVERLESS_FFMPEG_STATIC_PLATFORM = \"linux\";\nconst SERVERLESS_FFMPEG_STATIC_ARCHES = new Set<NodeJS.Architecture>([\n \"arm64\",\n \"x64\",\n]);\nconst SERVERLESS_FUNCTION_PACKAGE_DENYLIST = new Set([\n \"@vscode/test-electron\",\n \"electron\",\n \"electron-builder\",\n \"electron-updater\",\n \"electron-vite\",\n \"fsevents\",\n \"node-pty\",\n \"playwright\",\n]);\ntype ServerlessFfmpegStaticArch = \"arm64\" | \"x64\";\n\nfunction serverlessFfmpegStaticTargetArchFromEnv(): ServerlessFfmpegStaticArch | null {\n const value = process.env.AGENT_NATIVE_SERVERLESS_FFMPEG_ARCH;\n if (value === \"arm64\" || value === \"x64\") return value;\n return null;\n}\n\nexport function shouldBundleFfmpegStaticForServerless(\n hostPlatform: NodeJS.Platform = process.platform,\n hostArch: NodeJS.Architecture = process.arch,\n targetArch: ServerlessFfmpegStaticArch | null = serverlessFfmpegStaticTargetArchFromEnv(),\n): boolean {\n return (\n hostPlatform === SERVERLESS_FFMPEG_STATIC_PLATFORM &&\n targetArch !== null &&\n hostArch === targetArch &&\n SERVERLESS_FFMPEG_STATIC_ARCHES.has(targetArch)\n );\n}\n\nfunction nodeModulesAncestors(startDir: string): string[] {\n const dirs: string[] = [];\n let current = path.resolve(startDir);\n while (true) {\n const candidate = path.join(current, \"node_modules\");\n if (fs.existsSync(candidate)) dirs.push(candidate);\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return dirs;\n}\n\nfunction findInstalledLibsqlNativePackage(\n nodeModulesRoots: string[],\n packageName: string,\n): string | null {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, \"@libsql\", packageName);\n if (fs.existsSync(path.join(direct, \"index.node\"))) return direct;\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `@libsql+${packageName}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n \"@libsql\",\n packageName,\n );\n if (fs.existsSync(path.join(nested, \"index.node\"))) return nested;\n }\n }\n return null;\n}\n\nfunction hasFfmpegStaticBinary(packageDir: string): boolean {\n return FFMPEG_STATIC_BINARY_NAMES.some((binaryName) =>\n fs.existsSync(path.join(packageDir, binaryName)),\n );\n}\n\nfunction hasInstalledFfmpegStaticPackage(nodeModulesRoots: string[]): boolean {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, FFMPEG_STATIC_PACKAGE_NAME);\n if (fs.existsSync(path.join(direct, \"package.json\"))) return true;\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `${FFMPEG_STATIC_PACKAGE_NAME}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n FFMPEG_STATIC_PACKAGE_NAME,\n );\n if (fs.existsSync(path.join(nested, \"package.json\"))) return true;\n }\n }\n return false;\n}\n\nexport function findInstalledFfmpegStaticPackage(\n nodeModulesRoots: string[],\n): string | null {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, FFMPEG_STATIC_PACKAGE_NAME);\n if (\n fs.existsSync(path.join(direct, \"package.json\")) &&\n hasFfmpegStaticBinary(direct)\n ) {\n return direct;\n }\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `${FFMPEG_STATIC_PACKAGE_NAME}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n FFMPEG_STATIC_PACKAGE_NAME,\n );\n if (\n fs.existsSync(path.join(nested, \"package.json\")) &&\n hasFfmpegStaticBinary(nested)\n ) {\n return nested;\n }\n }\n }\n return null;\n}\n\nexport function findInstalledResvgPackages(\n nodeModulesRoots: string[],\n): Array<{ packageName: string; packageDir: string }> {\n const found = new Map<string, string>();\n\n for (const root of nodeModulesRoots) {\n const directScope = path.join(root, RESVG_SCOPE);\n if (fs.existsSync(directScope)) {\n for (const entry of fs.readdirSync(directScope)) {\n if (!entry.startsWith(RESVG_PACKAGE_PREFIX)) continue;\n const packageDir = path.join(directScope, entry);\n if (fs.existsSync(path.join(packageDir, \"package.json\"))) {\n found.set(entry, packageDir);\n }\n }\n }\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n const match = entry.match(/^@resvg\\+(resvg-js[^@]*)@/);\n if (!match) continue;\n const packageName = match[1];\n const packageDir = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n RESVG_SCOPE,\n packageName,\n );\n if (fs.existsSync(path.join(packageDir, \"package.json\"))) {\n found.set(packageName, packageDir);\n }\n }\n }\n\n return [...found.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([packageName, packageDir]) => ({ packageName, packageDir }));\n}\n\n/**\n * Deploy-time gate for emitting the second `-background` Netlify function.\n * Reads the same env flag the runtime gate uses\n * (`AGENT_CHAT_DURABLE_BACKGROUND`).\n *\n * DEFAULT-OFF (opt-in), matching the runtime gate (`isFlagEnabled` in\n * durable-background.ts): unset/empty/unknown means DISABLED; an app opts IN\n * only with an explicit truthy value (`true`/`1`/`yes`/`on`). A premature\n * fleet-wide default-on caused real-user incidents (2026-06-24) before the\n * async worker path was proven, so durable is opt-in until verified live. This\n * gate is what emits the 15-min `-background` function so the `_process-run`\n * dispatch lands on it (async 202 → the worker runs with the real 15-min budget\n * → its ~13-min soft-timeout fits). The deploy gate and runtime gate MUST agree:\n * if the deploy emitted no `-background` function but the runtime still routed\n * the worker into the ~13-min timeout regime, the worker would overshoot the\n * ~60s synchronous wall and re-dispatch in a loop. (The runtime now also guards\n * the ~13-min budget on the real function name via `isInBackgroundFunctionRuntime`,\n * so a missing emit degrades to clean 40s-chunked runs rather than the loop.)\n */\nexport function isDurableBackgroundDeployEnabled(): boolean {\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const v = raw.trim().toLowerCase();\n return v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\";\n}\n\n/**\n * Single-template Netlify build: emit an async (background) function INSIDE the\n * scanned functions dir so the chat `_process-run` worker runs on Netlify's\n * 15-min async function instead of the synchronous `/*` catch-all.\n * Additive + flag-gated (see `isDurableBackgroundDeployEnabled`).\n *\n * GROUNDED IN THE REAL NETLIFY BUILD OUTPUT (verified from a local Nitro build)\n * AND THE NETLIFY DOCS DEFAULT-URL RULE:\n * - Nitro's `netlify` preset emits exactly ONE function source at\n * `.netlify/functions-internal/server/`. `server.mjs` re-exports `main.mjs`\n * and declares `export const config = { path: \"/*\", excludedPath:\n * [\"/.netlify/*\"], preferStatic: true, ... }`. The `/*` catch-all is an\n * IN-CODE Functions-API-v2 `config.path` and it ALREADY EXCLUDES\n * `/.netlify/*`.\n * - The generated `.netlify/netlify.toml` sets\n * `functionsDirectory = \".netlify/functions-internal\"`. Netlify scans EXACTLY\n * that dir; functions placed anywhere else (e.g. `.netlify/functions/`, which\n * is the BUILD OUTPUT dir where `@netlify/build` later writes the zipped\n * functions + `manifest.json`) are NEVER deployed.\n * - Every scanned function is reachable at its DEFAULT url\n * `/.netlify/functions/<name>` BY DEFAULT. A custom `config.path` REMOVES\n * that default url; declaring NO custom `config.path` KEEPS it.\n *\n * THEREFORE we:\n * 1. Emit the background function INTO the scanned dir\n * (`.netlify/functions-internal/server-agent-background/`), sharing the same\n * built `main.mjs` bundle, so Netlify discovers it and honors its config.\n * 2. Give its `export const config` `background: true` (→ async invoke,\n * immediate 202, 15-min budget) and NO custom `config.path`. With no custom\n * path the function keeps its DEFAULT url\n * `/.netlify/functions/server-agent-background`, and because the Nitro\n * `server` function's `/*` catch-all already excludes `/.netlify/*`, that\n * default-url namespace is NEVER shadowed by the synchronous function — no\n * catch-all patch is needed.\n * 3. The entry NORMALIZES/rewrites the incoming request pathname to\n * `AGENT_CHAT_PROCESS_RUN_PATH` before delegating to `./main.mjs`. The\n * function is reached at its default url\n * (`/.netlify/functions/server-agent-background`), so the Nitro router needs\n * the path rewritten to the framework `_process-run` route, preserving the\n * method, ALL headers (the HMAC `Authorization: Bearer` MUST survive), and\n * the body.\n * 4. Set `globalThis.__AGENT_NATIVE_BACKGROUND_RUNTIME__ = true` at cold start\n * (read back by `isInBackgroundFunctionRuntime()` so the worker takes the\n * ~13-min soft-timeout). A `globalThis` flag — NOT `process.env` — keeps the\n * no-env-mutation guard satisfied and carries no cross-request state.\n *\n * The foreground dispatches to this DEFAULT url on hosted Netlify\n * (`resolveAgentChatProcessRunDispatchPath` → `AGENT_BACKGROUND_FUNCTION_URL_PATH`).\n *\n * WHY THIS IS THE DOC-CORRECT FIX: a prior attempt gave the function a custom\n * `config.path` (= the framework route) plus a catch-all `excludedPath` patch.\n * The custom `config.path` was NOT honored as a route in prod — a probe of\n * `POST /_agent-native/agent-chat/_process-run` returned 404. The doc-correct\n * approach (confirmed against the Netlify docs) is to use the DEFAULT function\n * url with no custom path: the function stays reachable at\n * `/.netlify/functions/<name>` and is never shadowed because `/.netlify/*` is\n * already excluded from the `server` catch-all.\n *\n * Safety net regardless of Netlify routing nuance: if the dispatch fast-fails\n * (e.g. the function was not emitted), the foreground handler degrades to an\n * inline 40s synchronous run (see production-agent.ts).\n */\nexport function emitSingleTemplateNetlifyBackgroundFunction(\n projectCwd: string,\n): void {\n const internalDir = path.join(projectCwd, \".netlify\", \"functions-internal\");\n const serverDir = path.join(internalDir, \"server\");\n if (!fs.existsSync(path.join(serverDir, \"main.mjs\"))) {\n // Nitro output layout differs from what we expected — skip rather than\n // guess. The single-function deploy is unaffected.\n console.warn(\n \"[build] Durable-background emit skipped: expected Nitro Netlify function \" +\n \"at .netlify/functions-internal/server/main.mjs was not found.\",\n );\n return;\n }\n const backgroundName = AGENT_BACKGROUND_FUNCTION_NAME;\n // Emit INTO the SCANNED functions dir (functions-internal) so Netlify discovers\n // the function and honors its `export const config`. `.netlify/functions/` is\n // the build OUTPUT dir (where @netlify/build writes the zip + manifest) and is\n // NOT scanned — emitting there is why the standalone attempt 404'd.\n const dest = path.join(internalDir, backgroundName);\n fs.rmSync(dest, { recursive: true, force: true });\n copyDir(serverDir, dest);\n // Drop the original Nitro `/*` entry so our entry is the entrypoint and the\n // copied bundle does NOT re-register the catch-all `config.path`.\n fs.rmSync(path.join(dest, \"server.mjs\"), { force: true });\n\n const processRunPath = JSON.stringify(AGENT_CHAT_PROCESS_RUN_PATH);\n const entry = `// Mark this isolate as the durable background runtime BEFORE the handler\n// bundle is imported, so isInBackgroundFunctionRuntime() reliably returns true\n// in this function. The deployed Lambda name is NOT guaranteed to end in\n// \"-background\" (Netlify may mangle/prefix it), so we cannot depend on\n// AWS_LAMBDA_FUNCTION_NAME alone. A globalThis flag (NOT process.env) avoids the\n// no-env-mutation guard and carries no cross-request state — it is a static,\n// set-once isolate marker read back by isInBackgroundFunctionRuntime().\nglobalThis.__AGENT_NATIVE_BACKGROUND_RUNTIME__ = true;\n\n// The framework route the Nitro router dispatches to (the _process-run plugin).\nconst PROCESS_RUN_PATH = ${processRunPath};\n\nlet cachedHandler;\n\n// Netlify v2 invokes this as (request, context). The Nitro netlify handler is a\n// Web-standard \\`async (Request) => Response\\` (see nitro/presets/netlify/runtime).\n// This function declares NO custom \\`config.path\\`, so it is reached at its\n// DEFAULT url (/.netlify/functions/${backgroundName}). The Nitro router only\n// knows the framework route, so we REWRITE the incoming pathname to\n// PROCESS_RUN_PATH before delegating. Method, ALL headers (the HMAC\n// Authorization: Bearer MUST survive — the plugin verifies it) and the body are\n// preserved by cloning the incoming Request with only its URL pathname set.\nexport default async function handler(request, context) {\n try {\n cachedHandler ??= (await import(\"./main.mjs\")).default;\n const url = new URL(request.url);\n url.pathname = PROCESS_RUN_PATH;\n // Read the body once and pass it through. GET/HEAD have no body.\n const method = request.method || \"POST\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const body = hasBody ? await request.text() : undefined;\n const rewritten = new Request(url.toString(), {\n method,\n headers: request.headers,\n body,\n });\n // Netlify Functions v2 invokes the handler as (request, context); the Nitro\n // netlify handler accepts (request[, context]). Pass context through so a\n // handler that uses it (e.g. waitUntil) does not trip over an undefined arg\n // before it ever routes the request.\n return await cachedHandler(rewritten, context);\n } catch (err) {\n // Netlify already returned 202 for this background invocation and DISCARDS\n // this return, so a throw here is otherwise INVISIBLE — it would only surface\n // downstream as the reaper's \"worker never claimed the run\". Log it loudly\n // for the function log; the FOREGROUND circuit-breaker (production-agent.ts)\n // is what recovers the run by executing it inline when no worker claims.\n console.error(\n \"[agent-background] wrapper failed before reaching the route:\",\n (err && err.stack) || err,\n );\n throw err;\n }\n}\n\nexport const config = {\n name: \"agent background handler\",\n generator: \"agent-native build\",\n // background: true makes Netlify invoke this ASYNCHRONOUSLY (immediate HTTP\n // 202 ack) with the 15-minute budget (Netlify docs:\n // build/functions/background-functions + build/functions/api). We declare NO\n // custom path, so the function keeps its DEFAULT url\n // /.netlify/functions/${backgroundName}; the Nitro \\`server\\` /* catch-all\n // already excludes /.netlify/* so that default url is never shadowed by the\n // synchronous function. The foreground dispatches to that default url.\n background: true,\n nodeBundler: \"none\",\n includedFiles: [\"**\"],\n preferStatic: false,\n};\n`;\n fs.writeFileSync(path.join(dest, `${backgroundName}.mjs`), entry);\n console.log(\n `[build] Emitted durable-background function \"${backgroundName}\" into the ` +\n `scanned dir .netlify/functions-internal with config { background:true } ` +\n `and NO custom path — reachable at its default url ` +\n `/.netlify/functions/${backgroundName} (never shadowed; the server /* ` +\n `catch-all already excludes /.netlify/*). REQUIRES real-deploy ` +\n `verification of Netlify async (202) invocation — see ` +\n `docs/design/durable-agent-runs.md.`,\n );\n}\n\n/**\n * Nitro's Netlify preset can emit a harmful fallback rewrite to\n * `/.netlify/functions/server`. With `config.path: \"/*\"`, that default URL is\n * removed, so the rewrite publishes platform 404s. Single-template deploys keep\n * Nitro's `preferStatic: true` so hashed `/assets/*` files in dist win before\n * the SSR catch-all runs.\n */\nconst NETLIFY_DEFAULT_FUNCTION_URL_REDIRECT =\n \"/* /.netlify/functions/server 200\";\n\n/**\n * Resolve where the client publish output actually lives for this build.\n * Single-template builds emit hashed assets at `dist/assets`; mounted builds\n * (APP_BASE_PATH=/<app>, e.g. every app in a workspace deploy) nest the\n * client output under the base path at `dist/<app>/assets`.\n */\nfunction netlifyClientPublishDir(projectCwd: string): {\n dir: string;\n label: string;\n} {\n const baseSegments = normalizeConfiguredAppBasePath()\n .split(\"/\")\n .filter(Boolean);\n return {\n dir: path.join(projectCwd, \"dist\", ...baseSegments),\n label: [\"dist\", ...baseSegments].join(\"/\"),\n };\n}\n\nfunction hasBareYjsRuntimeImport(source: string): boolean {\n return /\\b(?:from\\s*|import\\s*\\(\\s*|import\\s*)[\"']yjs(?:\\/[^\"']*)?[\"']/.test(\n source,\n );\n}\n\nfunction hasUnsupportedYjsSubpathImport(source: string): boolean {\n return /\\b(?:from\\s*|import\\s*\\(\\s*|import\\s*)[\"']yjs\\/[^\"']*[\"']/.test(\n source,\n );\n}\n\nfunction walkServerJavaScriptFiles(\n dir: string,\n onFile: (filePath: string) => void,\n): void {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const entryPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n walkServerJavaScriptFiles(entryPath, onFile);\n continue;\n }\n if (/\\.(?:[cm]?js)$/.test(entry.name)) onFile(entryPath);\n }\n}\n\n/**\n * Nitro can preserve Vite's `yjs` external in a split server chunk even when\n * its own server build has emitted `_libs/yjs.mjs`. Netlify does not install\n * that bare package at runtime, so make every emitted server chunk use the\n * bundled copy before its function is packaged.\n */\nexport function rewriteBareYjsImportsForServerlessOutput(\n serverDir: string,\n): string[] {\n const bareImports: string[] = [];\n const unsupportedSubpathImports: string[] = [];\n const bundledYjsPath = path.join(serverDir, \"_libs\", \"yjs.mjs\");\n\n walkServerJavaScriptFiles(serverDir, (filePath) => {\n const source = fs.readFileSync(filePath, \"utf-8\");\n if (!hasBareYjsRuntimeImport(source)) return;\n if (hasUnsupportedYjsSubpathImport(source)) {\n unsupportedSubpathImports.push(filePath);\n return;\n }\n bareImports.push(filePath);\n });\n\n if (unsupportedSubpathImports.length > 0) {\n throw new Error(\n `[deploy] Serverless output left unsupported yjs subpath imports in ${unsupportedSubpathImports.join(\", \")}`,\n );\n }\n if (bareImports.length === 0) return [];\n if (!fs.existsSync(bundledYjsPath)) {\n throw new Error(\n `[deploy] Serverless output left yjs as a runtime import but did not emit ${bundledYjsPath}`,\n );\n }\n\n for (const filePath of bareImports) {\n const bundledImport = path\n .relative(path.dirname(filePath), bundledYjsPath)\n .split(path.sep)\n .join(\"/\");\n const relativeBundledImport = bundledImport.startsWith(\".\")\n ? bundledImport\n : `./${bundledImport}`;\n const source = fs.readFileSync(filePath, \"utf-8\");\n fs.writeFileSync(\n filePath,\n source.replace(\n /(\\b(?:from\\s*|import\\s*\\(\\s*|import\\s*))([\"'])yjs\\2/g,\n (_match, importPrefix: string, quote: string) =>\n `${importPrefix}${quote}${relativeBundledImport}${quote}`,\n ),\n );\n }\n\n return bareImports;\n}\n\nexport function assertSingleTemplateNetlifyBuildOutput(\n projectCwd: string,\n): void {\n const failures: string[] = [];\n const publishDir = path.join(projectCwd, \"dist\");\n const clientPublish = netlifyClientPublishDir(projectCwd);\n const internalDir = path.join(projectCwd, \".netlify\", \"functions-internal\");\n const serverDir = path.join(internalDir, \"server\");\n const serverEntryPath = path.join(serverDir, \"server.mjs\");\n const serverMainPath = path.join(serverDir, \"main.mjs\");\n\n if (!fs.existsSync(publishDir)) {\n failures.push(\"missing publish directory: dist\");\n } else {\n const assetsDir = path.join(clientPublish.dir, \"assets\");\n if (\n !fs.existsSync(assetsDir) ||\n fs.readdirSync(assetsDir).every((name) => name.startsWith(\".\"))\n ) {\n failures.push(\n `${clientPublish.label}/assets is missing hashed client assets — the publish dir would load an infinite spinner`,\n );\n }\n }\n\n // `_redirects` may sit at the dist root or (for mounted builds) inside the\n // base-path dir — reject the incompatible default-function rewrite in both.\n const redirectsCandidates = [\n path.join(publishDir, \"_redirects\"),\n path.join(clientPublish.dir, \"_redirects\"),\n ];\n for (const redirectsPath of new Set(redirectsCandidates)) {\n if (!fs.existsSync(publishDir) || !fs.existsSync(redirectsPath)) continue;\n const redirects = fs.readFileSync(redirectsPath, \"utf-8\");\n if (\n redirects\n .split(/\\r?\\n/)\n .some(\n (line) =>\n line.trim().replace(/\\s+/g, \" \") ===\n NETLIFY_DEFAULT_FUNCTION_URL_REDIRECT,\n )\n ) {\n failures.push(\n `${path.relative(projectCwd, redirectsPath).replace(/\\\\/g, \"/\")} must not contain \"/* /.netlify/functions/server 200\" — Nitro's custom config.path: \"/*\" removes that default function URL`,\n );\n }\n }\n\n if (!fs.existsSync(serverDir)) {\n failures.push(\n \"missing scanned Netlify server function: .netlify/functions-internal/server\",\n );\n }\n\n if (!fs.existsSync(serverMainPath)) {\n failures.push(\n \"missing Netlify server bundle: .netlify/functions-internal/server/main.mjs\",\n );\n }\n\n if (!fs.existsSync(serverEntryPath)) {\n failures.push(\n \"missing Netlify server entry: .netlify/functions-internal/server/server.mjs\",\n );\n } else {\n const serverEntry = fs.readFileSync(serverEntryPath, \"utf-8\");\n if (!/\\bpath\\s*:\\s*[\"']\\/\\*[\"']/.test(serverEntry)) {\n failures.push(\n 'Netlify server entry is missing the \"/*\" catch-all function path',\n );\n }\n if (!serverEntry.includes('\"/.netlify/*\"')) {\n failures.push(\n 'Netlify server catch-all is missing the \"/.netlify/*\" exclusion',\n );\n }\n if (!serverEntry.includes(\"./main.mjs\")) {\n failures.push(\n \"Netlify server entry does not reference the generated main.mjs bundle\",\n );\n }\n if (!/\\bpreferStatic:\\s*true\\b/.test(serverEntry)) {\n failures.push(\n \"Netlify server entry must keep preferStatic: true so /assets/* is served from dist before the SSR catch-all\",\n );\n }\n }\n\n // Netlify's function packager does not install arbitrary runtime package\n // imports left in Nitro chunks. A bare Yjs import here would deploy\n // successfully but fail on the first SSR request with ERR_MODULE_NOT_FOUND.\n // Keep this check adjacent to the output guard so both local builds and CI\n // reject that artifact before it reaches Netlify.\n const bareYjsImports: string[] = [];\n walkServerJavaScriptFiles(serverDir, (filePath) => {\n if (hasBareYjsRuntimeImport(fs.readFileSync(filePath, \"utf-8\"))) {\n bareYjsImports.push(path.relative(projectCwd, filePath));\n }\n });\n if (bareYjsImports.length > 0) {\n failures.push(\n `Netlify server bundle leaves yjs as a runtime import: ${bareYjsImports.join(\", \")}`,\n );\n }\n\n if (isDurableBackgroundDeployEnabled()) {\n const backgroundDir = path.join(\n internalDir,\n AGENT_BACKGROUND_FUNCTION_NAME,\n );\n const backgroundEntryPath = path.join(\n backgroundDir,\n `${AGENT_BACKGROUND_FUNCTION_NAME}.mjs`,\n );\n if (!fs.existsSync(backgroundEntryPath)) {\n failures.push(\n `durable background is enabled but ${path.relative(\n projectCwd,\n backgroundEntryPath,\n )} was not emitted`,\n );\n } else {\n const backgroundEntry = fs.readFileSync(backgroundEntryPath, \"utf-8\");\n if (!/\\bbackground\\s*:\\s*true\\b/.test(backgroundEntry)) {\n failures.push(\n `durable background entry ${path.relative(\n projectCwd,\n backgroundEntryPath,\n )} is missing background: true`,\n );\n }\n if (/^\\s*path\\s*:/m.test(backgroundEntry)) {\n failures.push(\n `durable background entry ${path.relative(\n projectCwd,\n backgroundEntryPath,\n )} must not declare a custom path`,\n );\n }\n }\n }\n\n if (failures.length > 0) {\n throw new Error(\n \"[deploy] Netlify deploy guard failed; refusing to publish an output \" +\n \"that would likely serve Netlify 404s:\\n\" +\n failures.map((failure) => `- ${failure}`).join(\"\\n\"),\n );\n }\n\n console.log(\n \"[deploy] Netlify deploy guard passed: publish dir and catch-all server function are present.\",\n );\n}\n\n/**\n * Strip the harmful single-template catch-all rewrite that points at\n * `/.netlify/functions/server`. Nitro declares `config.path: \"/*\"`, which\n * removes the default function URL, so rewriting to that URL publishes\n * Netlify platform 404s. Preserve any real redirects from `public/_redirects`.\n */\nexport function writeSingleTemplateNetlifyRedirects(projectCwd: string): void {\n const publishDir = path.join(projectCwd, \"dist\");\n const clientPublish = netlifyClientPublishDir(projectCwd);\n // `_redirects` may sit at the dist root or (for mounted builds) inside the\n // base-path dir — strip the harmful rewrite wherever it landed.\n const redirectsCandidates = new Set([\n path.join(publishDir, \"_redirects\"),\n path.join(clientPublish.dir, \"_redirects\"),\n ]);\n for (const redirectsPath of redirectsCandidates) {\n stripNetlifyDefaultFunctionRedirect(redirectsPath);\n }\n}\n\nfunction stripNetlifyDefaultFunctionRedirect(redirectsPath: string): void {\n if (!fs.existsSync(redirectsPath)) return;\n\n const existing = fs.readFileSync(redirectsPath, \"utf-8\");\n const kept: string[] = [];\n let removed = 0;\n\n for (const line of existing.split(/\\r?\\n/)) {\n const normalized = line.trim().replace(/\\s+/g, \" \");\n if (\n normalized === NETLIFY_DEFAULT_FUNCTION_URL_REDIRECT ||\n normalized ===\n \"# Generated by agent-native build for Netlify single-template deploys\" ||\n normalized ===\n \"# Static files are served first; dynamic routes fall through to the server function.\"\n ) {\n removed += 1;\n continue;\n }\n kept.push(line);\n }\n\n while (kept.length > 0 && kept[kept.length - 1].trim() === \"\") {\n kept.pop();\n }\n\n if (removed === 0) return;\n\n if (kept.every((line) => line.trim() === \"\")) {\n fs.rmSync(redirectsPath, { force: true });\n } else {\n fs.writeFileSync(redirectsPath, kept.join(\"\\n\").trimEnd() + \"\\n\");\n }\n console.log(\n '[deploy] Removed Netlify fallback rewrite to /.netlify/functions/server (incompatible with Nitro config.path: \"/*\").',\n );\n}\n\nfunction copyInstalledLibsqlNativePackages(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const nodeModulesRoots = nodeModulesAncestors(cwd);\n const destScopeDir = path.join(serverDir, \"node_modules\", \"@libsql\");\n let copied = 0;\n\n for (const packageName of LIBSQL_NATIVE_PACKAGE_NAMES) {\n const src = findInstalledLibsqlNativePackage(nodeModulesRoots, packageName);\n if (!src) continue;\n\n copyDir(src, path.join(destScopeDir, packageName));\n copied += 1;\n }\n\n if (copied > 0) {\n console.log(\n `[deploy] Copied ${copied} installed libsql native package(s) into the server bundle.`,\n );\n }\n}\n\nfunction copyInstalledResvgPackages(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const packages = findInstalledResvgPackages(nodeModulesAncestors(cwd));\n if (packages.length === 0) return;\n\n const destScopeDir = path.join(serverDir, \"node_modules\", RESVG_SCOPE);\n for (const { packageName, packageDir } of packages) {\n copyDir(packageDir, path.join(destScopeDir, packageName));\n }\n\n console.log(\n `[deploy] Copied ${packages.length} resvg package(s) into the server bundle for OG image rendering.`,\n );\n}\n\nfunction copyInstalledFfmpegStaticPackage(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const nodeModulesRoots = nodeModulesAncestors(cwd);\n if (!shouldBundleFfmpegStaticForServerless()) {\n if (hasInstalledFfmpegStaticPackage(nodeModulesRoots)) {\n console.warn(\n `[deploy] ffmpeg-static installs a ${process.platform}-${process.arch} binary, but the serverless runtime architecture is not known to match it; ` +\n \"set AGENT_NATIVE_SERVERLESS_FFMPEG_ARCH=x64 or arm64 to bundle a matching binary, otherwise server-side media transcription fallback will require FFMPEG_PATH or a system ffmpeg.\",\n );\n }\n return;\n }\n\n const src = findInstalledFfmpegStaticPackage(nodeModulesRoots);\n if (!src) {\n if (hasInstalledFfmpegStaticPackage(nodeModulesRoots)) {\n console.warn(\n \"[deploy] ffmpeg-static is installed without a downloaded ffmpeg binary; \" +\n \"server-side media transcription fallback will require FFMPEG_PATH or a system ffmpeg.\",\n );\n }\n return;\n }\n\n copyDir(\n src,\n path.join(serverDir, \"node_modules\", FFMPEG_STATIC_PACKAGE_NAME),\n );\n console.log(\n \"[deploy] Copied ffmpeg-static into the server bundle for media transcription fallback.\",\n );\n}\n\n/**\n * Nitro's file tracer can over-include optional desktop/dev packages that are\n * present in a monorepo install but cannot run in serverless. Netlify installs\n * the generated per-function package.json before upload; if `electron` remains\n * there, the function can exceed Netlify's 250 MB unzipped size limit even\n * though the server bundle never imports Electron at runtime.\n */\nexport function sanitizeServerlessFunctionPackageManifest(\n functionDir: string | undefined,\n): void {\n if (!functionDir || !fs.existsSync(functionDir)) return;\n\n const packageJsonPath = path.join(functionDir, \"package.json\");\n if (!fs.existsSync(packageJsonPath)) return;\n\n let packageJson: Record<string, unknown>;\n try {\n packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n } catch {\n return;\n }\n\n let removed = 0;\n const depFields = [\n \"dependencies\",\n \"optionalDependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n ];\n for (const field of depFields) {\n const deps = packageJson[field];\n if (!deps || typeof deps !== \"object\" || Array.isArray(deps)) continue;\n const depRecord = deps as Record<string, unknown>;\n for (const packageName of SERVERLESS_FUNCTION_PACKAGE_DENYLIST) {\n if (Object.prototype.hasOwnProperty.call(depRecord, packageName)) {\n delete depRecord[packageName];\n removed++;\n }\n }\n if (Object.keys(depRecord).length === 0) {\n delete packageJson[field];\n }\n }\n\n const nodeModulesDir = path.join(functionDir, \"node_modules\");\n for (const packageName of SERVERLESS_FUNCTION_PACKAGE_DENYLIST) {\n const packageDir = path.join(nodeModulesDir, ...packageName.split(\"/\"));\n if (fs.existsSync(packageDir)) {\n fs.rmSync(packageDir, { recursive: true, force: true });\n removed++;\n }\n }\n\n if (removed > 0) {\n fs.writeFileSync(\n packageJsonPath,\n `${JSON.stringify(packageJson, null, 2)}\\n`,\n );\n console.log(\n `[deploy] Removed ${removed} desktop-only package reference(s) from ${path.relative(cwd, functionDir)}.`,\n );\n }\n}\n\n/**\n * Create stub directories for dangling platform-specific optional dependency\n * symlinks in the pnpm store.\n *\n * pnpm's store at `node_modules/.pnpm/<pkg>@<ver>/node_modules/<pkg>/<dep>`\n * contains symlinks for ALL optional deps declared by a package, but only\n * installs the ones matching the current OS/CPU as real packages. The other\n * symlinks dangle — their targets at `.pnpm/<scope>+<pkg>@<ver>/node_modules/...`\n * don't exist.\n *\n * Nitro's `nitro:externals` plugin (via nf3 / @vercel/nft) walks\n * optionalDependencies when tracing files and calls `realpath` on them, which\n * throws ENOENT on dangling targets. This blocks builds with presets like\n * netlify / vercel / aws-lambda on macOS when packages like `libsql` declare\n * Linux-only platform variants as optional deps.\n *\n * Fix: walk `node_modules/.pnpm/` and for every dangling symlink under\n * `<pkg>/node_modules/<scope>/<dep>`, create the symlink's target as a tiny\n * stub directory containing just a valid `package.json`. The tracer can now\n * `realpath` and read the package.json without throwing — the stub is empty\n * so no binary is bundled (which is what we want: we're building from macOS,\n * the target deploy platform will install its own native binary).\n */\nfunction createDanglingOptionalDepStubs() {\n // In pnpm monorepos, the store may live at the workspace root rather than\n // in the template dir. Walk up from `cwd` to find every `.pnpm` directory.\n const pnpmRoots: string[] = [];\n let dir = cwd;\n while (true) {\n const candidate = path.join(dir, \"node_modules\", \".pnpm\");\n if (fs.existsSync(candidate)) pnpmRoots.push(candidate);\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n if (pnpmRoots.length === 0) return;\n\n let stubsCreated = 0;\n\n for (const pnpmRoot of pnpmRoots) {\n let pkgDirs: string[];\n try {\n pkgDirs = fs.readdirSync(pnpmRoot);\n } catch {\n continue;\n }\n\n for (const pkgDir of pkgDirs) {\n // e.g. `libsql@0.5.29`, `@libsql+client@0.15.15`\n const innerNm = path.join(pnpmRoot, pkgDir, \"node_modules\");\n if (!fs.existsSync(innerNm)) continue;\n\n let innerEntries: fs.Dirent[];\n try {\n innerEntries = fs.readdirSync(innerNm, { withFileTypes: true });\n } catch {\n continue;\n }\n\n for (const entry of innerEntries) {\n // Top-level entry: either `foo` (unscoped) or `@scope` (scoped)\n const entryPath = path.join(innerNm, entry.name);\n const candidates: { symlinkPath: string; pkgName: string }[] = [];\n if (entry.name.startsWith(\"@\")) {\n // Scoped — iterate children\n let scopedChildren: fs.Dirent[];\n try {\n scopedChildren = fs.readdirSync(entryPath, {\n withFileTypes: true,\n });\n } catch {\n continue;\n }\n for (const child of scopedChildren) {\n candidates.push({\n symlinkPath: path.join(entryPath, child.name),\n pkgName: `${entry.name}/${child.name}`,\n });\n }\n } else {\n candidates.push({ symlinkPath: entryPath, pkgName: entry.name });\n }\n\n for (const { symlinkPath, pkgName } of candidates) {\n let isSymlink = false;\n try {\n isSymlink = fs.lstatSync(symlinkPath).isSymbolicLink();\n } catch {\n continue;\n }\n if (!isSymlink) continue;\n\n // Check if the symlink target exists\n try {\n fs.statSync(symlinkPath);\n continue; // Target exists — nothing to do\n } catch {\n // Dangling symlink — create a stub at the target\n }\n\n let linkTarget: string;\n try {\n linkTarget = fs.readlinkSync(symlinkPath);\n } catch {\n continue;\n }\n const resolvedTarget = path.resolve(\n path.dirname(symlinkPath),\n linkTarget,\n );\n\n try {\n fs.mkdirSync(resolvedTarget, { recursive: true });\n const stubPkgJson = {\n name: pkgName,\n version: \"0.0.0-stub\",\n description:\n \"Empty stub created by @agent-native/core deploy build to satisfy nitro's file tracer on platforms where this optional dep is not installed.\",\n };\n fs.writeFileSync(\n path.join(resolvedTarget, \"package.json\"),\n JSON.stringify(stubPkgJson, null, 2),\n );\n stubsCreated++;\n } catch {\n // Best-effort — ignore failures\n }\n }\n }\n }\n }\n\n if (stubsCreated > 0) {\n console.log(\n `[deploy] Created ${stubsCreated} stub package dir(s) for dangling optional deps (platform-specific binaries not installed on this host).`,\n );\n }\n}\n\n/**\n * Build for any non-Cloudflare preset using Nitro's programmatic build API.\n * Handles netlify, vercel, deno_deploy, aws-lambda, and all other targets.\n */\nexport interface NitroBuildHooks {\n prepare: (nitro: any) => Promise<void>;\n copyPublicAssets: (nitro: any) => Promise<void>;\n nitroBuild: (nitro: any) => Promise<void>;\n}\n\nexport interface NitroBuildPipelineOptions {\n nitro: any;\n hooks: NitroBuildHooks;\n clientDir: string;\n publicOutputDir: string | undefined;\n appBasePath: string;\n cwd: string;\n}\n\n/**\n * Run Nitro's lifecycle in the order required to ship a working React Router\n * framework-mode build.\n *\n * The critical ordering constraint is that the React Router client build must\n * be copied into `publicOutputDir` *before* `nitroBuild` runs. Nitro generates\n * the static-asset manifest baked into the server bundle by globbing\n * `publicDir` during the server build; files copied in after that point exist\n * on disk but are invisible to the runtime `serveStatic` handler. Every\n * /assets/* request then falls through to the SSR catch-all, which 404s\n * anything with a file extension.\n */\nexport async function runNitroBuildPipeline(\n opts: NitroBuildPipelineOptions,\n): Promise<void> {\n const { nitro, hooks, clientDir, publicOutputDir, appBasePath, cwd } = opts;\n const hasClientBuild = fs.existsSync(clientDir) && Boolean(publicOutputDir);\n\n if (hasClientBuild) {\n // Install hashed-asset route rules before Nitro prepares platform output.\n // Some presets materialize headers during prepare/copy phases, not only in\n // nitroBuild; adding these later leaves Netlify/Vercel static assets without\n // the one-year immutable CDN policy even though the runtime manifest works.\n nitro.options.routeRules ??= {};\n addImmutableAssetRouteRulesForClientBuild(\n nitro.options.routeRules,\n clientDir,\n appBasePath,\n );\n }\n\n await hooks.prepare(nitro);\n await hooks.copyPublicAssets(nitro);\n\n if (hasClientBuild && publicOutputDir) {\n copyDir(clientDir, publicOutputDir);\n if (appBasePath) {\n copyDir(clientDir, path.join(publicOutputDir, appBasePath.slice(1)));\n }\n console.log(\n `[deploy] Copied client assets to ${path.relative(cwd, publicOutputDir)}`,\n );\n }\n\n await hooks.nitroBuild(nitro);\n}\n\n/**\n * Browser-only diagram/drawing renderers that execute `window`-touching code at\n * module-evaluation time. They are rendered exclusively client-side — core's\n * `MermaidBlock` and templates' Excalidraw slides mount them inside `useEffect` /\n * `React.lazy`, never during SSR — so the server never needs the real module.\n *\n * Keep this list to libraries that are *provably never* invoked on the server.\n * Node-only deps that DO run server-side (pdf-parse, @google/genai, canvas, …)\n * must NOT go here — see `heavyClientExternals` for the edge-worker externals.\n */\nconst BROWSER_ONLY_SERVER_LIBS = [\n \"@excalidraw/excalidraw\",\n \"@excalidraw/mermaid-to-excalidraw\",\n \"mermaid\",\n];\n\n/**\n * Dependencies that must be bundled into every Nitro server output instead of\n * being left as runtime package imports.\n *\n * `yjs` is a direct core dependency, but it is deliberately externalized from\n * the intermediate Vite SSR graph so that Vite and Nitro do not create two\n * incompatible Yjs constructors. On file-traced serverless presets, leaving it\n * external at Nitro's final build can emit `import \"yjs\"` into a function\n * chunk without placing the package in that function's `node_modules`. Bundle\n * it in Nitro's final output so every template receives the one portable copy.\n */\nexport const NITRO_SERVER_RUNTIME_BUNDLED_DEPS = [\"yjs\"] as const;\n\n/**\n * Edge runtimes have no node_modules, while Node/serverless outputs only need\n * the small set above bundled to keep their package manifests traceable.\n */\nexport function nitroNoExternalsForPreset(\n targetPreset: string,\n): true | readonly string[] {\n return targetPreset.startsWith(\"cloudflare\") ||\n targetPreset.startsWith(\"deno\")\n ? true\n : NITRO_SERVER_RUNTIME_BUNDLED_DEPS;\n}\n\n/**\n * Rolldown plugin for the Nitro server bundle that replaces the browser-only\n * renderers above with an inert proxy module.\n *\n * Why this is needed: Nitro re-bundles the server from node_modules with its own\n * Rolldown pipeline, and Rolldown merges Excalidraw into a SHARED vendor chunk\n * that the SSR render path (tiptap / radix-ui / recharts) imports *statically*.\n * That evaluates Excalidraw's top-level `window` access at function cold-start\n * and crashes every request with `ReferenceError: window is not defined` (HTTP\n * 502). The Vite SSR build already stubs these via `ssrStubPlugin` for\n * `build/server`, but that Vite plugin doesn't run during Nitro's separate\n * bundle — so mirror the same stub here.\n */\nfunction createBrowserOnlyServerStubPlugin() {\n const stubbed = new Set(BROWSER_ONLY_SERVER_LIBS);\n const STUB_ID = \"\\0agent-native-browser-only-server-stub\";\n return {\n name: \"agent-native-browser-only-server-stub\",\n // enforce: \"pre\" so we intercept before Nitro's node resolver bundles the\n // real package. defu concatenates rollupConfig.plugins ahead of Nitro's own.\n resolveId(id: string) {\n // Match the bare package name or any subpath (incl. `/index.css`).\n const pkg = id\n .split(\"/\")\n .slice(0, id.startsWith(\"@\") ? 2 : 1)\n .join(\"/\");\n return stubbed.has(pkg) ? STUB_ID : null;\n },\n load(id: string) {\n if (id !== STUB_ID) return null;\n // A Proxy answers any property access (default or named) with another\n // proxy, so every import shape resolves without evaluating real browser\n // code. It is never actually invoked on the server, so it never throws.\n return (\n \"const handler = { get(_t, p) {\" +\n \" if (p === Symbol.toPrimitive) return () => '';\" +\n \" if (p === 'then') return undefined;\" +\n \" if (p === '__esModule') return true;\" +\n \" return new Proxy(function () {}, handler); } };\" +\n \"const stub = new Proxy(function () {}, handler);\" +\n \"export default stub;\"\n );\n },\n };\n}\n\nasync function buildWithNitro() {\n console.log(`[deploy] Building for preset \"${preset}\" via Nitro...`);\n const appBasePath = normalizeConfiguredAppBasePath();\n\n // Nitro runs its own server build after the React Router/Vite build. The\n // template's agent-chat plugin imports .generated/actions-registry.ts so the\n // serverless bundle has static imports for every domain action. Regenerate\n // here as well so deploy builds are not coupled to a previous Vite run or to\n // ignored local .generated files being present.\n generateActionRegistryForProject(cwd);\n\n // Work around pnpm + nitro:externals (nf3) bug where dangling symlinks for\n // platform-specific optional deps cause realpath ENOENT during file tracing.\n createDanglingOptionalDepStubs();\n\n const {\n createNitro,\n prepare,\n copyPublicAssets,\n build: nitroBuild,\n } = await import(\"nitro/builder\");\n\n // Resolve the React Router server build so the SSR catch-all route\n // can import \"virtual:react-router/server-build\" in production.\n const rrServerBuild = path.join(cwd, \"build\", \"server\", \"index.js\");\n\n // Inline the template's AGENTS.md + .agents/skills/ content into the Nitro\n // bundle via the `virtual` config option. Nitro's internal `nitro:virtual`\n // Rollup plugin picks this up and resolves `virtual:agents-bundle` to the\n // generated ES module source. Without this, Nitro's Rolldown build (used for\n // netlify, vercel, aws-lambda, node presets) can't resolve the virtual\n // module that `server/agents-bundle.ts` imports — it silently falls through\n // to an empty bundle and the agent gets no instructions/skills at runtime.\n //\n // The Vite plugin at `vite/agents-bundle-plugin.ts` handles this for the\n // React Router client/server build (and cloudflare via esbuild rebundle),\n // but Nitro runs its OWN build from ./server/ without Vite, so it needs its\n // own virtual module registration. Both paths reuse `readAgentsBundleFromFs`\n // from `server/agents-bundle.ts` to guarantee identical content.\n const { readAgentsBundleFromFs } = await import(\"../server/agents-bundle.js\");\n // Resolve the workspace core (if present) up front so the bundle embeds\n // enterprise-wide AGENTS.md + skills alongside the template's.\n const nitroWorkspaceCore = await getWorkspaceCoreExports(cwd);\n const nitroWorkspaceSource = nitroWorkspaceCore\n ? {\n skillsDir: nitroWorkspaceCore.skillsDir,\n agentsMdPath: nitroWorkspaceCore.agentsMdPath,\n rootDir: nitroWorkspaceCore.packageDir,\n }\n : null;\n const agentsBundleModuleSource = () => {\n const bundle = readAgentsBundleFromFs(cwd, nitroWorkspaceSource);\n return `// AUTO-GENERATED by @agent-native/core deploy build (Nitro virtual)\n// Contains the inlined AGENTS.md + .agents/skills/ content from the template,\n// merged with the workspace core's AGENTS.md + skills/ when present.\nconst bundle = ${JSON.stringify(bundle)};\nexport default bundle;\n`;\n };\n\n // Path aliases used by templates (mirrors tsconfig + Vite config). Nitro\n // bundles server/ and actions/ with its own Rolldown pipeline that doesn't\n // see Vite's resolve.alias — so without this, action files that import\n // `@/foo` (= `app/foo`) end up with the literal `@/foo` specifier in the\n // serverless function output and crash at runtime with\n // \"Cannot find package '@/foo' imported from /var/task/main.mjs\".\n const appDir = path.join(cwd, \"app\");\n const sharedDir = path.join(cwd, \"shared\");\n const pathAliases: Record<string, string> = {};\n if (fs.existsSync(appDir)) pathAliases[\"@\"] = appDir;\n if (fs.existsSync(sharedDir)) pathAliases[\"@shared\"] = sharedDir;\n\n const providedPluginsNitroPlugin = await writeProvidedPluginsNitroPlugin();\n\n const nitro = await createNitro({\n rootDir: cwd,\n dev: false,\n preset,\n baseURL: appBasePath || \"/\",\n minify: true,\n serverDir: \"./server\",\n ignore: NITRO_RUNTIME_IGNORE_PATTERNS,\n alias: {\n ...pathAliases,\n ...(fs.existsSync(rrServerBuild)\n ? { \"virtual:react-router/server-build\": rrServerBuild }\n : {}),\n },\n virtual: {\n \"virtual:agents-bundle\": agentsBundleModuleSource,\n },\n replace: {\n \"process.env.AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID\": JSON.stringify(\n process.env.GA_MEASUREMENT_ID?.trim() || \"\",\n ),\n },\n // Replace browser-only renderers (Excalidraw/Mermaid) with an inert proxy in\n // the server bundle. Without this, Nitro's Rolldown build pulls the real\n // Excalidraw into a shared vendor chunk imported statically by the SSR render\n // path, and its top-level `window` access crashes the function at cold-start\n // (ReferenceError: window is not defined → every request 502s). Mirrors the\n // Vite `ssrStubPlugin`, which only covers the `build/server` step.\n rollupConfig: {\n plugins: [createBrowserOnlyServerStubPlugin()],\n },\n ...(providedPluginsNitroPlugin\n ? { plugins: [providedPluginsNitroPlugin] }\n : {}),\n routeRules: mcpEmbedStaticAssetRouteRules(appBasePath),\n // Edge presets (cloudflare, deno) bundle all deps because node_modules are\n // unavailable at runtime. Node/serverless presets also bundle Yjs: Nitro's\n // file tracer otherwise leaves a bare import that Netlify function bundles\n // cannot resolve under pnpm.\n noExternals: nitroNoExternalsForPreset(preset),\n } as any);\n\n await runNitroBuildPipeline({\n nitro,\n hooks: { prepare, copyPublicAssets, nitroBuild },\n clientDir: path.join(cwd, \"build\", \"client\"),\n publicOutputDir: nitro.options.output.publicDir,\n appBasePath,\n cwd,\n });\n\n if (preset === \"netlify\" || preset === \"vercel\" || preset === \"aws-lambda\") {\n copyInstalledLibsqlNativePackages(nitro.options.output.serverDir);\n copyInstalledResvgPackages(nitro.options.output.serverDir);\n copyInstalledFfmpegStaticPackage(nitro.options.output.serverDir);\n sanitizeServerlessFunctionPackageManifest(nitro.options.output.serverDir);\n rewriteBareYjsImportsForServerlessOutput(nitro.options.output.serverDir);\n }\n\n // Durable background agent runs (default-OFF / opt-in; enable with a truthy\n // AGENT_CHAT_DURABLE_BACKGROUND). Additive ONLY: emits a SECOND Netlify\n // function whose name ends in `-background` re-exporting the same handler\n // bundle, so the chat `_process-run` POST lands on Netlify's async (15-min)\n // function. When not opted in this is a no-op and the single-function\n // deploy is byte-for-byte unchanged.\n if (preset === \"netlify\" && isDurableBackgroundDeployEnabled()) {\n try {\n emitSingleTemplateNetlifyBackgroundFunction(cwd);\n } catch (err) {\n console.warn(\n \"[build] Failed to emit durable-background Netlify function (non-fatal):\",\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n if (preset === \"netlify\") {\n writeSingleTemplateNetlifyRedirects(cwd);\n assertSingleTemplateNetlifyBuildOutput(cwd);\n }\n\n // Resolve remaining bare npm imports by bundling them into _libs/.\n // Nitro sometimes leaves small packages as externals even with noExternals.\n if (preset.startsWith(\"cloudflare\") || preset.startsWith(\"deno\")) {\n const { execFileSync } = await import(\"child_process\");\n const { createRequire } = await import(\"module\");\n const esbuildBin = (() => {\n try {\n const _req = createRequire(cwd + \"/\");\n const pkg = path.dirname(_req.resolve(\"esbuild/package.json\"));\n const bin = path.join(pkg, \"bin\", \"esbuild\");\n if (fs.existsSync(bin)) return bin;\n } catch {}\n return \"esbuild\";\n })();\n\n // Scan all output files for bare npm imports\n const outputDir =\n nitro.options.output.serverDir || path.join(cwd, \"dist\", \"_worker.js\");\n const bareImports = new Set<string>();\n function scanForBareImports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n scanForBareImports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n const code = fs.readFileSync(p, \"utf-8\");\n const matches = code.matchAll(/from\\s*[\"']([a-z@][a-z0-9._\\-/]*)[\"']/g);\n for (const m of matches) {\n const mod = m[1];\n if (mod.startsWith(\"node:\")) continue;\n // Skip Node builtins that are available via nodejs_compat\n const builtins = new Set([\n \"fs\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"url\",\n \"util\",\n \"events\",\n \"buffer\",\n \"console\",\n \"net\",\n \"tls\",\n \"assert\",\n \"timers\",\n \"child_process\",\n \"module\",\n \"process\",\n \"sqlite\",\n \"worker_threads\",\n \"querystring\",\n \"zlib\",\n \"vm\",\n \"string_decoder\",\n \"diagnostics_channel\",\n \"async_hooks\",\n \"perf_hooks\",\n \"inspector\",\n ]);\n if (builtins.has(mod)) continue;\n bareImports.add(mod);\n }\n }\n }\n scanForBareImports(outputDir);\n\n // For each bare import, try to bundle it as a standalone module\n if (bareImports.size > 0) {\n const libsDir = path.join(outputDir, \"_libs\");\n fs.mkdirSync(libsDir, { recursive: true });\n for (const mod of bareImports) {\n const outFile = path.join(libsDir, `${mod.replace(/[/@]/g, \"_\")}.mjs`);\n try {\n // Resolve the module — check workspace node_modules and pnpm store\n let resolvedMod = mod;\n const _require = createRequire(cwd + \"/\");\n try {\n const resolved = _require.resolve(mod);\n resolvedMod = resolved;\n } catch {\n // Try from workspace root\n try {\n const wsRequire = createRequire(\n path.resolve(cwd, \"../../package.json\"),\n );\n resolvedMod = wsRequire.resolve(mod);\n } catch {\n // Will fail at esbuild\n }\n }\n // Scan what named imports the consumer expects, then generate\n // explicit re-exports to handle CJS modules properly.\n const neededExports = new Set<string>();\n function findNeededExports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n findNeededExports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n const code = fs.readFileSync(p, \"utf-8\");\n // Match: import{foo as bar,baz}from\"<mod>\"\n const escaped = mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(\n `import\\\\{([^}]+)\\\\}from[\"']${escaped}[\"']`,\n \"g\",\n );\n for (const m2 of code.matchAll(re)) {\n for (const part of m2[1].split(\",\")) {\n const name = part\n .trim()\n .split(/\\s+as\\s+/)[0]\n .trim();\n if (name && /^[a-zA-Z_$]/.test(name)) neededExports.add(name);\n }\n }\n }\n }\n findNeededExports(outputDir);\n\n const entryCode =\n neededExports.size > 0\n ? [\n `import _mod from \"${resolvedMod}\";`,\n `export default _mod;`,\n ...Array.from(neededExports).map(\n (n) =>\n `export const ${n} = _mod.${n} ?? _mod?.default?.${n};`,\n ),\n ].join(\"\\n\")\n : `export * from \"${resolvedMod}\"; export { default } from \"${resolvedMod}\";`;\n\n const libEsbuildCommand = esbuildSpawnCommand(esbuildBin, [\n \"--bundle\",\n `--outfile=${outFile}`,\n \"--format=esm\",\n \"--platform=neutral\",\n \"--target=es2022\",\n \"--external:node:*\",\n ]);\n execFileSync(libEsbuildCommand.file, libEsbuildCommand.args, {\n input: entryCode,\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n // Rewrite imports in all files to point to the bundled module\n function rewriteImports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n rewriteImports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n let code = fs.readFileSync(p, \"utf-8\");\n const relPath = path\n .relative(path.dirname(p), outFile)\n .replace(/\\\\/g, \"/\");\n const importPath = relPath.startsWith(\".\")\n ? relPath\n : \"./\" + relPath;\n const re = new RegExp(\n `from[\"']${mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}[\"']`,\n \"g\",\n );\n if (re.test(code)) {\n code = code.replace(re, `from\"${importPath}\"`);\n fs.writeFileSync(p, code);\n }\n }\n }\n rewriteImports(outputDir);\n console.log(`[deploy] Bundled external: ${mod}`);\n } catch {\n console.warn(\n `[deploy] Could not bundle: ${mod} (may not be needed at runtime)`,\n );\n }\n }\n }\n }\n\n // Cloudflare-specific post-build patches\n if (preset.startsWith(\"cloudflare\")) {\n const serverDir2 = nitro.options.output.serverDir;\n const scanDirs = [serverDir2];\n if (serverDir2) {\n const chunksDir = path.join(serverDir2, \"_chunks\");\n const libsDir = path.join(serverDir2, \"_libs\");\n if (fs.existsSync(chunksDir)) scanDirs.push(chunksDir);\n if (fs.existsSync(libsDir)) scanDirs.push(libsDir);\n }\n\n for (const scanDir of scanDirs) {\n if (!scanDir || !fs.existsSync(scanDir)) continue;\n for (const file of fs.readdirSync(scanDir)) {\n if (!file.endsWith(\".mjs\") && !file.endsWith(\".js\")) continue;\n const filePath = path.join(scanDir, file);\n let code = fs.readFileSync(filePath, \"utf-8\");\n let changed = false;\n\n // 1. Rewrite bare Node.js imports to node: prefixed.\n // CF Workers requires the node: prefix for built-in modules.\n const NODE_BUILTINS = [\n \"fs\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"url\",\n \"util\",\n \"events\",\n \"buffer\",\n \"console\",\n \"querystring\",\n \"zlib\",\n \"net\",\n \"tls\",\n \"assert\",\n \"timers\",\n \"child_process\",\n \"module\",\n \"process\",\n \"sqlite\",\n \"worker_threads\",\n \"string_decoder\",\n \"diagnostics_channel\",\n \"async_hooks\",\n \"perf_hooks\",\n \"inspector\",\n \"vm\",\n ];\n for (const mod of NODE_BUILTINS) {\n // Match: from\"fs\" or from \"fs\" (but not from\"node:fs\")\n const re = new RegExp(`from\\\\s*[\"']${mod}[\"']`, \"g\");\n if (re.test(code)) {\n code = code.replace(re, `from\"node:${mod}\"`);\n changed = true;\n }\n }\n\n // 2. Patch import.meta.url for createRequire().\n // React Router's server build uses createRequire(import.meta.url)\n // but import.meta.url is undefined on CF Workers.\n if (code.includes(\"import.meta.url\")) {\n code = code.replace(/import\\.meta\\.url/g, '\"file:///worker.mjs\"');\n changed = true;\n }\n\n // 3. Patch setInterval/setTimeout at global scope.\n // CF Workers disallows timers in global scope.\n if (code.includes(\"setInterval\") && !code.includes(\"__timer_shim__\")) {\n const shim =\n \"/* __timer_shim__ */\" +\n \"var __origSetInterval=globalThis.setInterval;\" +\n \"globalThis.setInterval=function(){return{unref(){},ref(){},close(){}}};\";\n const restore =\n \";(function(){if(typeof __origSetInterval!=='undefined')globalThis.setInterval=__origSetInterval})();\";\n code = shim + code + \"\\n\" + restore;\n changed = true;\n }\n\n if (changed) fs.writeFileSync(filePath, code);\n }\n }\n // 3. Create stub modules in _libs/ for native deps that Nitro's rolldown\n // bundler references but can't resolve on CF Workers, and rewrite\n // bare imports to point to the stub files.\n const libsDir2 = path.join(\n serverDir2 || path.join(cwd, \"dist\", \"_worker.js\"),\n \"_libs\",\n );\n if (fs.existsSync(libsDir2)) {\n const NATIVE_STUBS = [\"better-sqlite3\", \"node-pty\", \"cron-parser\"];\n for (const mod of NATIVE_STUBS) {\n const libFiles = fs\n .readdirSync(libsDir2)\n .filter((f) => f.endsWith(\".mjs\"));\n const referencingFiles: string[] = [];\n for (const f of libFiles) {\n const filePath = path.join(libsDir2, f);\n const content = fs.readFileSync(filePath, \"utf-8\");\n if (content.includes(`\"${mod}\"`) || content.includes(`'${mod}'`)) {\n referencingFiles.push(filePath);\n }\n }\n if (referencingFiles.length === 0) continue;\n\n // Create a stub _libs/<mod>.mjs that exports empty defaults\n const stubName = mod.replace(/[/@]/g, \"__\") + \".mjs\";\n const stubPath = path.join(libsDir2, stubName);\n if (!fs.existsSync(stubPath)) {\n fs.writeFileSync(\n stubPath,\n `export default {}; export const watch = () => ({ close() {} });\\n`,\n );\n console.log(`[deploy] Created stub for _libs/${stubName}`);\n }\n\n // Rewrite bare imports in _libs/ and _chunks/ to use the stub\n const escaped = mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const importRe = new RegExp(`(from\\\\s*[\"'])${escaped}([\"'])`, \"g\");\n // Scan _libs/ files\n for (const filePath of referencingFiles) {\n let code = fs.readFileSync(filePath, \"utf-8\");\n if (importRe.test(code)) {\n code = code.replace(importRe, `$1./${stubName}$2`);\n fs.writeFileSync(filePath, code);\n console.log(\n `[deploy] Rewrote ${mod} imports in _libs/${path.basename(filePath)}`,\n );\n }\n }\n // Also scan _chunks/ files (they import native deps too)\n const chunksDir2 = path.join(\n serverDir2 || path.join(cwd, \"dist\", \"_worker.js\"),\n \"_chunks\",\n );\n if (fs.existsSync(chunksDir2)) {\n for (const f of fs\n .readdirSync(chunksDir2)\n .filter((f) => f.endsWith(\".mjs\") || f.endsWith(\".js\"))) {\n const filePath = path.join(chunksDir2, f);\n let code = fs.readFileSync(filePath, \"utf-8\");\n if (importRe.test(code)) {\n // From _chunks/, the stub is at ../_libs/<stubName>\n code = code.replace(importRe, `$1../_libs/${stubName}$2`);\n fs.writeFileSync(filePath, code);\n console.log(`[deploy] Rewrote ${mod} imports in _chunks/${f}`);\n }\n }\n }\n }\n }\n\n console.log(\n \"[deploy] Patched bare Node imports, timer calls, and route finder for CF Workers\",\n );\n }\n\n await nitro.close();\n console.log(`[deploy] Nitro build complete for preset \"${preset}\".`);\n}\n\nasync function main() {\n console.log(`[deploy] Building for ${preset}...`);\n\n // Sweep stale .deploy-tmp before anything writes into it. A crashed prior\n // build (any preset) leaves partial artifacts behind; both build paths\n // mkdirSync over the dir without clearing it, and the stale contents can\n // silently poison the next build (observed: an interrupted node-preset\n // build made the following cloudflare_pages build fail with no error\n // output). Fresh tmp every run is the invariant.\n fs.rmSync(path.join(cwd, \".deploy-tmp\"), { recursive: true, force: true });\n\n switch (preset) {\n case \"cloudflare_pages\":\n case \"cloudflare-pages\":\n // Cloudflare Workers require a single-file bundle that wrangler can deploy.\n // Nitro's native presets produce split chunks that wrangler can't upload\n // as multi-module Workers. Use the custom esbuild-based bundler.\n await buildCloudflarePages();\n break;\n default:\n // All other presets (netlify, vercel, deno_deploy, aws-lambda, etc.)\n // are handled natively by Nitro's build API.\n await buildWithNitro();\n break;\n }\n}\n\nif (\n process.argv[1] &&\n path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))\n) {\n await main();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../src/deploy/build.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,OAAO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B,GAAG,uBAAuB,CAAC,EAAE,CAAC,CAAC;wBACjE,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,CAAC,GAAG,CACT,kFAAkF,CACnF,CAAC;IACJ,CAAC;IAED,MAAM,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,OAAO,CAAC,GAAG,CAAC,6CAA6C,MAAM,IAAI,CAAC,CAAC;AACvE,CAAC;AAED,KAAK,UAAU,IAAI;IACjB,OAAO,CAAC,GAAG,CAAC,yBAAyB,MAAM,KAAK,CAAC,CAAC;IAElD,0EAA0E;IAC1E,uEAAuE;IACvE,yEAAyE;IACzE,uEAAuE;IACvE,qEAAqE;IACrE,iDAAiD;IACjD,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAE3E,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,kBAAkB,CAAC;QACxB,KAAK,kBAAkB;YACrB,4EAA4E;YAC5E,yEAAyE;YACzE,iEAAiE;YACjE,MAAM,oBAAoB,EAAE,CAAC;YAC7B,MAAM;QACR;YACE,qEAAqE;YACrE,6CAA6C;YAC7C,MAAM,cAAc,EAAE,CAAC;YACvB,MAAM;IACV,CAAC;AACH,CAAC;AAED,IACE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IACf,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAC9E,CAAC;IACD,MAAM,IAAI,EAAE,CAAC;AACf,CAAC","sourcesContent":["#!/usr/bin/env node\n\n/**\n * Post-build step for deploying agent-native apps to edge/serverless targets.\n *\n * When NITRO_PRESET is set, this script:\n * 1. Takes the React Router build output (build/client/ + build/server/)\n * 2. Generates a platform-specific server entry point\n * 3. Bundles everything with esbuild into the target format\n *\n * Supported presets:\n * - cloudflare_pages: Outputs dist/ with _worker.js for Cloudflare Pages\n *\n * Usage: node deploy/build.js (called automatically by `agent-native build`)\n */\n\nimport { execFileSync } from \"child_process\";\nimport fs from \"fs\";\nimport { createRequire } from \"module\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nimport {\n AGENT_BACKGROUND_FUNCTION_NAME,\n AGENT_CHAT_PROCESS_RUN_PATH,\n} from \"../agent/durable-background.js\";\nimport { normalizeAppBasePath } from \"../server/app-base-path.js\";\nimport {\n DEFAULT_SSR_CDN_CACHE_CONTROL,\n DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL,\n DEFAULT_SPECULATION_RULES_PATH,\n DEFAULT_SSR_CACHE_CONTROL,\n} from \"../shared/cache-control.js\";\nimport { mcpEmbedStaticAssetRouteRules } from \"../shared/mcp-embed-headers.js\";\nimport {\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER,\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n} from \"../shared/social-meta.js\";\nimport { generateActionRegistryForProject } from \"../vite/action-types-plugin.js\";\nimport {\n collectImmutableAssetPaths,\n IMMUTABLE_ASSET_CACHE_CONTROL,\n IMMUTABLE_ASSET_CACHE_HEADERS,\n prefixAssetPath,\n} from \"./immutable-assets.js\";\nimport {\n discoverApiRoutes,\n discoverPlugins,\n discoverActionFiles,\n getMissingDefaultPlugins,\n DEFAULT_PLUGIN_REGISTRY,\n type DiscoveredRoute,\n type DiscoveredAction,\n} from \"./route-discovery.js\";\nimport {\n getWorkspaceCoreExports,\n type WorkspaceCoreExports,\n} from \"./workspace-core.js\";\n\nconst cwd = process.cwd();\nconst preset = process.env.NITRO_PRESET || \"node\";\nexport const NITRO_RUNTIME_IGNORE_PATTERNS = [\n \"**/*.spec.ts\",\n \"**/*.spec.tsx\",\n \"**/*.spec.mts\",\n \"**/*.spec.cts\",\n \"**/*.spec.js\",\n \"**/*.spec.jsx\",\n \"**/*.spec.mjs\",\n \"**/*.spec.cjs\",\n \"**/*.test.ts\",\n \"**/*.test.tsx\",\n \"**/*.test.mts\",\n \"**/*.test.cts\",\n \"**/*.test.js\",\n \"**/*.test.jsx\",\n \"**/*.test.mjs\",\n \"**/*.test.cjs\",\n];\n\nexport const CLOUDFLARE_WORKER_ESBUILD_EXTERNALS = [\n \"mermaid\",\n \"@excalidraw/excalidraw\",\n \"@excalidraw/mermaid-to-excalidraw\",\n \"pdf-parse\",\n \"pdfjs-dist\",\n \"@google/genai\",\n \"chartjs-node-canvas\",\n \"@napi-rs/canvas\",\n \"@anthropic-ai/tokenizer\",\n \"@resvg/resvg-js\",\n \"playwright\",\n \"playwright-core\",\n \"chromium-bidi\",\n \"chromium-bidi/*\",\n \"@sparticuz/chromium-min\",\n \"fsevents\",\n];\nexport const CLOUDFLARE_WORKER_STUB_MODULES: Record<string, string> = {\n // detect-libc calls process.report.getReport() at require time to sniff\n // musl vs glibc; unenv's process.report stub throws \"not implemented\",\n // killing the worker at module init. Stub it with static glibc answers —\n // nothing that consults libc can run on workerd anyway.\n \"detect-libc\": [\n \"export const GLIBC = 'glibc';\",\n \"export const MUSL = 'musl';\",\n \"export const family = async () => null;\",\n \"export const familySync = () => null;\",\n \"export const version = async () => null;\",\n \"export const versionSync = () => null;\",\n \"export const isNonGlibcLinux = async () => false;\",\n \"export const isNonGlibcLinuxSync = () => false;\",\n \"export default { GLIBC, MUSL, family, familySync, version, versionSync, isNonGlibcLinux, isNonGlibcLinuxSync };\",\n \"\",\n ].join(\"\\n\"),\n \"better-sqlite3\":\n \"export default {}; export const Database = class {}; export const watch = () => ({ close() {} });\\n\",\n // sharp loads its native binary (@img/sharp-<platform>) at require time and\n // throws \"Could not load the sharp module using the linux- runtime\" at\n // worker module init. Stub it with a callable that throws at call time —\n // image processing can't run on workerd regardless.\n sharp: [\n \"const unavailable = () => { throw new Error('sharp unavailable in Cloudflare Pages worker'); };\",\n \"const sharp = new Proxy(unavailable, { get: (_t, prop) => (prop === 'default' ? sharp : unavailable), apply: unavailable });\",\n \"export default sharp;\",\n \"\",\n ].join(\"\\n\"),\n \"node-pty\":\n \"export default {}; export const watch = () => ({ close() {} });\\n\",\n chokidar: \"export default {}; export const watch = () => ({ close() {} });\\n\",\n fsevents: \"export default {}; export const watch = () => ({ close() {} });\\n\",\n dotenv: \"export default {}; export const config = () => ({ parsed: {} });\\n\",\n \"@anthropic-ai/sdk\": \"export default class Anthropic {}\\n\",\n \"@anthropic-ai/tokenizer\":\n \"export default {}; export const countTokens = undefined;\\n\",\n \"@sentry/node\": [\n \"export const init = () => {};\",\n \"const scope = {\",\n \" setUser() {},\",\n \" setTag() {},\",\n \" setExtra() {},\",\n \" setContext() {},\",\n \" setLevel() {},\",\n \" getScopeData() { return {}; },\",\n \"};\",\n \"export const getIsolationScope = () => scope;\",\n \"export const withScope = (fn) => fn(scope);\",\n \"export const captureException = () => undefined;\",\n \"export default { init, getIsolationScope, withScope, captureException };\",\n \"\",\n ].join(\"\\n\"),\n \"@resvg/resvg-js\": [\n \"export class Resvg {\",\n ' constructor() { throw new Error(\"@resvg/resvg-js unavailable in Cloudflare Pages worker\"); }',\n \"}\",\n \"export default { Resvg };\",\n \"\",\n ].join(\"\\n\"),\n \"playwright-core\": [\n \"const unavailable = async () => { throw new Error('playwright-core unavailable in Cloudflare Pages worker'); };\",\n \"export const chromium = { launch: unavailable };\",\n \"export const firefox = { launch: unavailable };\",\n \"export const webkit = { launch: unavailable };\",\n \"export default { chromium, firefox, webkit };\",\n \"\",\n ].join(\"\\n\"),\n // playwright and its playwright/test subpath are imported with literal\n // dynamic import() in template actions (e.g. design's screenshot action\n // imports \"playwright/test\"), so a bare --external leaves an unresolvable\n // import in the final _worker.js — wrangler/Pages then refuses the bundle.\n // Stub both so the import resolves and degrades at call time like Node.\n playwright: [\n \"const unavailable = async () => { throw new Error('playwright unavailable in Cloudflare Pages worker'); };\",\n \"export const chromium = { launch: unavailable };\",\n \"export const firefox = { launch: unavailable };\",\n \"export const webkit = { launch: unavailable };\",\n \"export default { chromium, firefox, webkit };\",\n \"\",\n ].join(\"\\n\"),\n \"playwright/test\": [\n \"const unavailable = async () => { throw new Error('playwright/test unavailable in Cloudflare Pages worker'); };\",\n \"export const chromium = { launch: unavailable };\",\n \"export const firefox = { launch: unavailable };\",\n \"export const webkit = { launch: unavailable };\",\n \"export const test = undefined;\",\n \"export const expect = undefined;\",\n \"export default { chromium, firefox, webkit };\",\n \"\",\n ].join(\"\\n\"),\n \"@sparticuz/chromium-min\": [\n \"const chromium = {\",\n \" args: [],\",\n \" setGraphicsMode: false,\",\n \" executablePath: async () => { throw new Error('@sparticuz/chromium-min unavailable in Cloudflare Pages worker'); },\",\n \"};\",\n \"export default chromium;\",\n \"\",\n ].join(\"\\n\"),\n \"@google/genai\": [\n \"export class GoogleGenAI {\",\n \" constructor() { throw new Error('@google/genai unavailable in Cloudflare Pages worker'); }\",\n \"}\",\n \"export default { GoogleGenAI };\",\n \"\",\n ].join(\"\\n\"),\n \"pdf-parse\": [\n \"export class PDFParse {\",\n \" constructor() { throw new Error('pdf-parse unavailable in Cloudflare Pages worker'); }\",\n \"}\",\n \"export default { PDFParse };\",\n \"\",\n ].join(\"\\n\"),\n \"pdfjs-dist\":\n \"export default {}; export const getDocument = () => { throw new Error('pdfjs-dist unavailable in Cloudflare Pages worker'); };\\n\",\n \"chartjs-node-canvas\": [\n \"export class ChartJSNodeCanvas {\",\n \" constructor() { throw new Error('chartjs-node-canvas unavailable in Cloudflare Pages worker'); }\",\n \"}\",\n \"export default { ChartJSNodeCanvas };\",\n \"\",\n ].join(\"\\n\"),\n \"@napi-rs/canvas\":\n \"export default {}; export const createCanvas = () => { throw new Error('@napi-rs/canvas unavailable in Cloudflare Pages worker'); };\\n\",\n mermaid: \"export default {}; export const mermaidAPI = {};\\n\",\n \"@excalidraw/excalidraw\":\n \"export default {}; export const MainMenu = {}; export const WelcomeScreen = {};\\n\",\n \"@excalidraw/mermaid-to-excalidraw\":\n \"export default async () => ({ elements: [], files: {} });\\n\",\n};\n\n/**\n * Optional AI SDK packages that ai-sdk-engine imports with LITERAL dynamic\n * import() specifiers (so bundlers include provider packages when present).\n * They are optional peer dependencies — when an app hasn't installed one,\n * esbuild fails the worker bundle with \"Could not resolve\". Stub every\n * uninstalled one with a module that throws at import time, which makes the\n * dynamic import() reject exactly like the missing package does under Node.\n */\nexport const OPTIONAL_AI_SDK_MODULES = [\n \"ai\",\n \"@ai-sdk/anthropic\",\n \"@ai-sdk/openai\",\n \"@ai-sdk/google\",\n \"@ai-sdk/groq\",\n \"@ai-sdk/mistral\",\n \"@ai-sdk/cohere\",\n \"@openrouter/ai-sdk-provider\",\n \"ai-sdk-ollama\",\n];\n\nexport function uninstalledOptionalAiSdkStubs(\n appDir: string,\n): Record<string, string> {\n const appRequire = createRequire(path.join(appDir, \"package.json\"));\n const stubs: Record<string, string> = {};\n for (const mod of OPTIONAL_AI_SDK_MODULES) {\n try {\n appRequire.resolve(mod);\n } catch {\n stubs[mod] = `throw new Error(${JSON.stringify(\n `${mod} is not installed in this deployment`,\n )});\\n`;\n }\n }\n return stubs;\n}\n\nfunction cloudflareNodeBuiltinStubSource(\n moduleName: string,\n namedExports: string[],\n overrides: string[] = [],\n): string {\n const overridden = new Set(\n overrides.flatMap((source) =>\n Array.from(source.matchAll(/\\bexport const ([A-Za-z_$][\\w$]*)/g)).map(\n (match) => match[1],\n ),\n ),\n );\n const exports = Array.from(new Set(namedExports))\n .filter((name) => !overridden.has(name))\n .sort();\n // The default export must expose the SAME members as the named exports —\n // including functional overrides like os.tmpdir() — because most consumers\n // use the default import (`import os from \"os\"; os.tmpdir()`). A bare\n // throwing proxy here killed workers at module init whenever a dependency\n // called an overridden member through the default export.\n const allNames = Array.from(new Set([...overridden, ...exports])).sort();\n return [\n `const unavailable = (name) => (..._args) => { throw new Error(name + \" is unavailable in Cloudflare Pages workers\"); };`,\n ...overrides,\n ...exports.map(\n (name) => `export const ${name} = unavailable(\"${moduleName}.${name}\");`,\n ),\n `const __members = { ${allNames.join(\", \")} };`,\n `const proxy = new Proxy(__members, { get(target, prop) { return prop in target ? target[prop] : unavailable(\"${moduleName}.\" + String(prop)); } });`,\n \"export default proxy;\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport const CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES: Record<\n string,\n string\n> = {\n child_process: cloudflareNodeBuiltinStubSource(\"child_process\", [\n \"exec\",\n \"execFile\",\n \"execFileSync\",\n \"execSync\",\n \"fork\",\n \"spawn\",\n \"spawnSync\",\n ]),\n cluster: cloudflareNodeBuiltinStubSource(\"cluster\", [\n \"disconnect\",\n \"fork\",\n \"isMaster\",\n \"isPrimary\",\n \"isWorker\",\n \"setupMaster\",\n \"setupPrimary\",\n \"worker\",\n \"workers\",\n ]),\n console: [\n \"const globalConsole = globalThis.console;\",\n \"const bind = (name) => typeof globalConsole?.[name] === 'function' ? globalConsole[name].bind(globalConsole) : () => undefined;\",\n \"export class Console {\",\n \" constructor() { return globalConsole; }\",\n \"}\",\n \"export const assert = bind('assert');\",\n \"export const clear = bind('clear');\",\n \"export const count = bind('count');\",\n \"export const countReset = bind('countReset');\",\n \"export const debug = bind('debug');\",\n \"export const dir = bind('dir');\",\n \"export const dirxml = bind('dirxml');\",\n \"export const error = bind('error');\",\n \"export const group = bind('group');\",\n \"export const groupCollapsed = bind('groupCollapsed');\",\n \"export const groupEnd = bind('groupEnd');\",\n \"export const info = bind('info');\",\n \"export const log = bind('log');\",\n \"export const profile = bind('profile');\",\n \"export const profileEnd = bind('profileEnd');\",\n \"export const table = bind('table');\",\n \"export const time = bind('time');\",\n \"export const timeEnd = bind('timeEnd');\",\n \"export const timeLog = bind('timeLog');\",\n \"export const timeStamp = bind('timeStamp');\",\n \"export const trace = bind('trace');\",\n \"export const warn = bind('warn');\",\n \"export { globalConsole as console };\",\n \"export default globalConsole;\",\n \"\",\n ].join(\"\\n\"),\n dgram: cloudflareNodeBuiltinStubSource(\"dgram\", [\"createSocket\"]),\n dns: cloudflareNodeBuiltinStubSource(\"dns\", [\n \"lookup\",\n \"promises\",\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n ]),\n \"dns/promises\": cloudflareNodeBuiltinStubSource(\"dns/promises\", [\n \"lookup\",\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n ]),\n domain: cloudflareNodeBuiltinStubSource(\"domain\", [\"create\"]),\n fs: cloudflareNodeBuiltinStubSource(\n \"fs\",\n [\n \"access\",\n \"accessSync\",\n \"appendFile\",\n \"appendFileSync\",\n \"chmod\",\n \"chmodSync\",\n \"close\",\n \"closeSync\",\n \"copyFile\",\n \"copyFileSync\",\n \"cp\",\n \"cpSync\",\n \"createReadStream\",\n \"createWriteStream\",\n \"existsSync\",\n \"lstat\",\n \"lstatSync\",\n \"mkdir\",\n \"mkdirSync\",\n \"open\",\n \"openSync\",\n \"readFile\",\n \"readFileSync\",\n \"readdir\",\n \"readdirSync\",\n \"readlink\",\n \"readlinkSync\",\n \"realpath\",\n \"realpathSync\",\n \"rename\",\n \"renameSync\",\n \"rm\",\n \"rmSync\",\n \"stat\",\n \"statSync\",\n \"symlink\",\n \"symlinkSync\",\n \"unlink\",\n \"unlinkSync\",\n \"watch\",\n \"writeFile\",\n \"writeFileSync\",\n ],\n [\n \"export const constants = {};\",\n \"export const promises = {};\",\n \"export const existsSync = () => false;\",\n \"export const readdirSync = () => [];\",\n \"export const realpathSync = (value) => value;\",\n \"export const mkdirSync = () => undefined;\",\n \"export const rmSync = () => undefined;\",\n ],\n ),\n \"fs/promises\": cloudflareNodeBuiltinStubSource(\"fs/promises\", [\n \"access\",\n \"appendFile\",\n \"chmod\",\n \"copyFile\",\n \"cp\",\n \"lstat\",\n \"mkdtemp\",\n \"mkdir\",\n \"readFile\",\n \"readdir\",\n \"readlink\",\n \"realpath\",\n \"rename\",\n \"rm\",\n \"stat\",\n \"symlink\",\n \"unlink\",\n \"writeFile\",\n ]),\n http: cloudflareNodeBuiltinStubSource(\"http\", [\n \"Agent\",\n \"ClientRequest\",\n \"IncomingMessage\",\n \"ServerResponse\",\n \"createServer\",\n \"get\",\n \"request\",\n ]),\n http2: cloudflareNodeBuiltinStubSource(\"http2\", [\n \"Http2ServerRequest\",\n \"Http2ServerResponse\",\n \"constants\",\n \"connect\",\n \"createSecureServer\",\n \"createServer\",\n ]),\n https: cloudflareNodeBuiltinStubSource(\"https\", [\n \"Agent\",\n \"createServer\",\n \"get\",\n \"request\",\n ]),\n inspector: cloudflareNodeBuiltinStubSource(\"inspector\", [\n \"Session\",\n \"close\",\n \"open\",\n \"url\",\n \"waitForDebugger\",\n ]),\n module: cloudflareNodeBuiltinStubSource(\n \"module\",\n [\"Module\", \"builtinModules\", \"createRequire\", \"syncBuiltinESMExports\"],\n [\n \"export const builtinModules = [];\",\n \"export const createRequire = () => globalThis.require ?? ((specifier) => { throw new Error('Cannot require: ' + specifier); });\",\n ],\n ),\n net: cloudflareNodeBuiltinStubSource(\n \"net\",\n [\"Socket\", \"connect\", \"createConnection\", \"createServer\", \"isIP\"],\n [\n `export const isIP = (value) => {\n const input = String(value ?? \"\");\n const ipv4Parts = input.split(\".\");\n if (\n ipv4Parts.length === 4 &&\n ipv4Parts.every((part) => /^\\\\d{1,3}$/.test(part) && Number(part) >= 0 && Number(part) <= 255)\n ) {\n return 4;\n }\n if (input.includes(\":\") && /^[0-9A-Fa-f:.]+$/.test(input)) {\n return 6;\n }\n return 0;\n};`,\n ],\n ),\n os: cloudflareNodeBuiltinStubSource(\n \"os\",\n [\n \"arch\",\n \"cpus\",\n \"endianness\",\n \"freemem\",\n \"homedir\",\n \"hostname\",\n \"networkInterfaces\",\n \"platform\",\n \"release\",\n \"tmpdir\",\n \"totalmem\",\n \"type\",\n \"userInfo\",\n ],\n [\n 'export const EOL = \"\\\\n\";',\n 'export const arch = () => \"x64\";',\n \"export const cpus = () => [];\",\n 'export const endianness = () => \"LE\";',\n \"export const freemem = () => 0;\",\n 'export const homedir = () => \"/tmp\";',\n 'export const hostname = () => \"cloudflare-worker\";',\n \"export const networkInterfaces = () => ({});\",\n 'export const platform = () => \"linux\";',\n 'export const release = () => \"\";',\n 'export const tmpdir = () => \"/tmp\";',\n \"export const totalmem = () => 0;\",\n 'export const type = () => \"Worker\";',\n \"export const userInfo = () => ({ username: 'worker', homedir: '/tmp' });\",\n ],\n ),\n readline: cloudflareNodeBuiltinStubSource(\"readline\", [\n \"Interface\",\n \"clearLine\",\n \"clearScreenDown\",\n \"createInterface\",\n \"cursorTo\",\n \"emitKeypressEvents\",\n \"moveCursor\",\n ]),\n repl: cloudflareNodeBuiltinStubSource(\"repl\", [\"start\"]),\n sqlite: cloudflareNodeBuiltinStubSource(\"sqlite\", [\"DatabaseSync\"]),\n sys: cloudflareNodeBuiltinStubSource(\"sys\", [\n \"debug\",\n \"deprecate\",\n \"error\",\n \"inspect\",\n \"log\",\n \"print\",\n \"puts\",\n ]),\n tls: cloudflareNodeBuiltinStubSource(\"tls\", [\n \"TLSSocket\",\n \"connect\",\n \"createSecureContext\",\n \"createServer\",\n ]),\n trace_events: cloudflareNodeBuiltinStubSource(\"trace_events\", [\n \"createTracing\",\n \"getEnabledCategories\",\n ]),\n tty: cloudflareNodeBuiltinStubSource(\"tty\", [\n \"ReadStream\",\n \"WriteStream\",\n \"isatty\",\n ]),\n v8: cloudflareNodeBuiltinStubSource(\"v8\", [\n \"deserialize\",\n \"getHeapStatistics\",\n \"serialize\",\n ]),\n vm: cloudflareNodeBuiltinStubSource(\"vm\", [\n \"Script\",\n \"compileFunction\",\n \"createContext\",\n \"runInContext\",\n \"runInNewContext\",\n \"runInThisContext\",\n ]),\n wasi: cloudflareNodeBuiltinStubSource(\"wasi\", [\"WASI\"]),\n worker_threads: cloudflareNodeBuiltinStubSource(\n \"worker_threads\",\n [\"MessageChannel\", \"MessagePort\", \"Worker\", \"isMainThread\", \"parentPort\"],\n [\"export const isMainThread = true;\", \"export const parentPort = null;\"],\n ),\n};\n\nexport interface GenerateWorkerEntryOptions {\n includeReactRouterSsr?: boolean;\n}\n\ninterface ReactRouterAssetManifest {\n entry: ReactRouterAssetManifestEntry;\n routes: Record<string, ReactRouterAssetManifestRoute>;\n url: string;\n}\n\ninterface ReactRouterAssetManifestEntry {\n module: string;\n imports?: string[];\n css?: string[];\n}\n\ninterface ReactRouterAssetManifestRoute {\n id: string;\n module: string;\n imports?: string[];\n css?: string[];\n hasLoader?: boolean;\n clientActionModule?: string;\n clientLoaderModule?: string;\n clientMiddlewareModule?: string;\n hydrateFallbackModule?: string;\n}\n\nfunction normalizeConfiguredAppBasePath(): string {\n return normalizeAppBasePath(\n process.env.VITE_APP_BASE_PATH || process.env.APP_BASE_PATH,\n );\n}\n\n/** Plugins that require Node.js runtime and cannot run on edge/serverless */\nconst NODE_ONLY_PLUGINS = new Set([\n \"terminal\", // PTY requires child_process\n // @sentry/node ships node:fs / node:async_hooks bindings that don't load\n // on workerd / Cloudflare Workers. Templates running on edge presets can\n // mount their own edge-compatible Sentry wrapper if they want server\n // observability there; the framework default is the Node SDK.\n \"sentry\",\n]);\nconst EDGE_SERVER_ENTRYPOINT = \"@agent-native/core/server/edge\";\n\nfunction isNodeOnlyPlugin(filePath: string): boolean {\n const basename = path.basename(filePath, path.extname(filePath));\n return NODE_ONLY_PLUGINS.has(basename);\n}\n\nexport function generateProvidedPluginsNitroPluginSource(\n pluginStems: string[],\n): string {\n const stems = [...new Set(pluginStems.filter(Boolean))].sort();\n return `// AUTO-GENERATED by @agent-native/core deploy build\nimport { markDefaultPluginProvided } from \"${EDGE_SERVER_ENTRYPOINT}\";\n\nconst pluginStems = ${JSON.stringify(stems)};\n\nexport default function markBuildDiscoveredPlugins(nitroApp) {\n for (const stem of pluginStems) {\n markDefaultPluginProvided(nitroApp, stem);\n }\n}\n`;\n}\n\nasync function writeProvidedPluginsNitroPlugin(): Promise<string | null> {\n const plugins = await discoverPlugins(cwd);\n const stems = plugins.map((plugin) =>\n path.basename(plugin, path.extname(plugin)),\n );\n if (stems.length === 0) return null;\n\n const tmpDir = path.join(cwd, \".deploy-tmp\");\n fs.mkdirSync(tmpDir, { recursive: true });\n const pluginPath = path.join(tmpDir, \"agent-native-provided-plugins.mjs\");\n fs.writeFileSync(pluginPath, generateProvidedPluginsNitroPluginSource(stems));\n return pluginPath;\n}\n\ntype RouteRules = Record<string, { headers?: Record<string, string> }>;\n\nfunction addImmutableAssetRouteRule(\n routeRules: RouteRules,\n pathname: string,\n): void {\n const existing = routeRules[pathname] ?? {};\n routeRules[pathname] = {\n ...existing,\n headers: {\n ...(existing.headers ?? {}),\n ...IMMUTABLE_ASSET_CACHE_HEADERS,\n },\n };\n}\n\nexport function addImmutableAssetRouteRulesForClientBuild(\n routeRules: RouteRules,\n clientDir: string,\n appBasePath = \"\",\n): void {\n for (const assetPath of collectImmutableAssetPaths(clientDir)) {\n addImmutableAssetRouteRule(routeRules, assetPath);\n const mountedPath = prefixAssetPath(assetPath, appBasePath);\n if (mountedPath !== assetPath) {\n addImmutableAssetRouteRule(routeRules, mountedPath);\n }\n }\n}\n\n/**\n * Generate the worker entry source code that wires up H3 + React Router SSR.\n *\n * If a workspace core is present (monorepo with `agent-native.workspaceCore`\n * configured and the named package resolves), any plugin slot that the\n * workspace core exports is imported from there instead of from\n * `@agent-native/core/server/edge`. This is the middle layer of the three-layer\n * inheritance model: app local > workspace core > framework default.\n */\nexport function generateWorkerEntry(\n routes: DiscoveredRoute[],\n pluginPaths: string[],\n defaultPluginStems: string[] = [],\n actions: DiscoveredAction[] = [],\n workspaceCore: WorkspaceCoreExports | null = null,\n immutableAssetPaths: string[] = [],\n builtAppBasePath = normalizeConfiguredAppBasePath(),\n options: GenerateWorkerEntryOptions = {},\n): string {\n const includeReactRouterSsr = options.includeReactRouterSsr ?? true;\n const routeImports: string[] = [];\n const routeRegistrations: string[] = [];\n\n for (let i = 0; i < routes.length; i++) {\n const r = routes[i];\n const varName = `route_${i}`;\n routeImports.push(`import ${varName} from ${JSON.stringify(r.absPath)};`);\n routeRegistrations.push(\n ` app.on(${JSON.stringify(r.method.toUpperCase())}, ${JSON.stringify(r.route)}, ${varName});`,\n );\n if (r.method.toLowerCase() === \"get\") {\n routeRegistrations.push(\n ` app.on(\"HEAD\", ${JSON.stringify(r.route)}, defineEventHandler(async (event) => {\n const originalReq = event.req;\n event.req = requestWithMethod(event.req, \"GET\");\n try {\n const result = await ${varName}(event);\n const response = result instanceof Response ? result : toResponse(result, event);\n return new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } finally {\n event.req = originalReq;\n }\n }));`,\n );\n }\n }\n\n // Action route imports and registrations\n const actionImports: string[] = [];\n const actionRegistrations: string[] = [];\n for (let i = 0; i < actions.length; i++) {\n const a = actions[i];\n const varName = `action_${i}`;\n actionImports.push(`import ${varName} from ${JSON.stringify(a.absPath)};`);\n // Mirror the runtime mount (action-routes.ts): `path = http?.path ?? name`.\n const routePath = `/_agent-native/actions/${a.path ?? a.name}`;\n actionRegistrations.push(\n ` app.on(${JSON.stringify(a.method.toUpperCase())}, ${JSON.stringify(routePath)}, defineEventHandler(async (event) => {\n const params = ${a.method === \"get\" ? \"parseActionSearchParams(event.url.searchParams)\" : \"(await readBody(event)) ?? {}\"};\n try {\n const result = await ${varName}.run(params, { caller: \"http\" });\n if (typeof result === \"string\") { try { return JSON.parse(result); } catch { return result; } }\n return result;\n } catch (err) {\n return new Response(JSON.stringify({ error: err?.message || \"Action failed\" }), { status: err?.message?.startsWith(\"Invalid action parameters\") ? 400 : 500, headers: { \"Content-Type\": \"application/json\" } });\n }\n }));`,\n );\n }\n\n // Filter out Node-only plugins\n const edgePlugins = pluginPaths.filter((p) => !isNodeOnlyPlugin(p));\n const pluginImports: string[] = [];\n const pluginCalls: string[] = [];\n const providedPluginStems = new Set<string>();\n\n for (let i = 0; i < edgePlugins.length; i++) {\n const varName = `plugin_${i}`;\n providedPluginStems.add(\n path.basename(edgePlugins[i], path.extname(edgePlugins[i])),\n );\n pluginImports.push(\n `import ${varName} from ${JSON.stringify(edgePlugins[i])};`,\n );\n pluginCalls.push(` if (typeof ${varName} === \"function\") {\n await ${varName}(nitroApp);\n }`);\n }\n // Auto-mounted default plugins (for slots the template doesn't override\n // locally). For each slot, prefer a workspace-core export over the\n // @agent-native/core default, if the workspace core provides one.\n const edgeDefaultStems = defaultPluginStems.filter(\n (stem) => !NODE_ONLY_PLUGINS.has(stem),\n );\n for (let i = 0; i < edgeDefaultStems.length; i++) {\n const stem = edgeDefaultStems[i];\n providedPluginStems.add(stem);\n const varName = `defaultPlugin_${i}`;\n\n const workspaceExportName = workspaceCore?.plugins?.[stem as never];\n if (workspaceCore && workspaceExportName) {\n // Workspace-core layer wins over the framework default.\n pluginImports.push(\n `import { ${workspaceExportName} as ${varName} } from ${JSON.stringify(\n `${workspaceCore.packageName}/server`,\n )};`,\n );\n } else {\n // Fall back to the framework default from the edge-safe core entrypoint.\n const defaultExportName = DEFAULT_PLUGIN_REGISTRY[stem];\n if (!defaultExportName) continue;\n pluginImports.push(\n `import { ${defaultExportName} as ${varName} } from \"${EDGE_SERVER_ENTRYPOINT}\";`,\n );\n }\n pluginCalls.push(` if (typeof ${varName} === \"function\") {\n await ${varName}(nitroApp);\n }`);\n }\n const generatedPluginMarks =\n providedPluginStems.size > 0\n ? [\n ...new Set([\n ...Object.keys(DEFAULT_PLUGIN_REGISTRY),\n ...providedPluginStems,\n ]),\n ]\n : [];\n if (generatedPluginMarks.length > 0) {\n pluginImports.unshift(\n `import { markDefaultPluginProvided as markGeneratedPluginProvided } from \"${EDGE_SERVER_ENTRYPOINT}\";`,\n );\n }\n\n return `\n// Auto-generated worker entry point for ${preset}\nimport { H3, defineEventHandler, readBody, toResponse } from \"h3\";\n${includeReactRouterSsr ? 'import { createRequestHandler } from \"react-router\";' : \"\"}\n${includeReactRouterSsr ? 'import * as serverBuild from \"./server-build.js\";' : \"\"}\n\nfunction normalizeAppBasePath(value) {\n if (!value || value === \"/\") return \"\";\n const trimmed = String(value).trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n return \"/\" + trimmed.replace(/^\\\\/+/, \"\").replace(/\\\\/+$/, \"\");\n}\n\nfunction getAppBasePath() {\n const builtAppBasePath = ${JSON.stringify(builtAppBasePath)};\n return normalizeAppBasePath(\n globalThis.process?.env?.VITE_APP_BASE_PATH ||\n globalThis.process?.env?.APP_BASE_PATH ||\n builtAppBasePath,\n );\n}\n\nfunction stripAppBasePath(pathname) {\n const basePath = getAppBasePath();\n if (!basePath) return pathname;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(basePath + \"/\")) {\n return pathname.slice(basePath.length) || \"/\";\n }\n return pathname;\n}\n\nfunction parseActionSearchParams(searchParams) {\n const params = {};\n for (const [rawKey, value] of searchParams.entries()) {\n const isArrayKey = rawKey.endsWith(\"[]\");\n // The core client serializes arrays as key[]=value so one-item arrays\n // survive GET action parsing in generated worker deployments.\n const key = isArrayKey ? rawKey.slice(0, -2) : rawKey;\n const current = params[key];\n if (current === undefined) {\n params[key] = isArrayKey ? [value] : value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n params[key] = [current, value];\n }\n }\n return params;\n}\n\nfunction isApiPath(pathname) {\n return pathname === \"/api\" || pathname.startsWith(\"/api/\");\n}\n\nfunction isFrameworkPath(pathname) {\n return (\n pathname === \"/_agent-native\" || pathname.startsWith(\"/_agent-native/\")\n );\n}\n\nfunction requestWithMountedApiPrefixStripped(request) {\n const basePath = getAppBasePath();\n if (!basePath) return request;\n const url = new URL(request.url);\n const strippedPathname = stripAppBasePath(url.pathname);\n if (strippedPathname === url.pathname) {\n return request;\n }\n if (!isApiPath(strippedPathname) && !isFrameworkPath(strippedPathname)) {\n return request;\n }\n url.pathname = strippedPathname;\n return new Request(url, request);\n}\n\nfunction prefixMountedPath(path, basePath) {\n if (!basePath || !path.startsWith(\"/\") || path.startsWith(\"//\")) return path;\n if (path === basePath || path.startsWith(basePath + \"/\")) return path;\n return basePath + path;\n}\n\nfunction prefixMountedHtml(html, basePath) {\n if (!basePath) return html;\n return html\n .replace(\n /\\\\b(href|src|action|formaction|poster)=([\"'])(\\\\/(?!\\\\/)[^\"']*)\\\\2/g,\n (_match, attr, quote, path) =>\n attr + \"=\" + quote + prefixMountedPath(path, basePath) + quote,\n )\n .replace(/url\\\\(([\"']?)(\\\\/(?!\\\\/)[^)'\" ]+)\\\\1\\\\)/g, (_match, quote, path) => {\n const q = quote || \"\";\n return \"url(\" + q + prefixMountedPath(path, basePath) + q + \")\";\n });\n}\n\nfunction firstNonEmpty() {\n for (const value of arguments) {\n const trimmed = typeof value === \"string\" ? value.trim() : \"\";\n if (trimmed) return trimmed;\n }\n}\n\nfunction getSentryClientConfigScript() {\n const env = globalThis.process?.env || {};\n const key = firstNonEmpty(env.SENTRY_CLIENT_KEY, env.VITE_SENTRY_CLIENT_KEY);\n const projectId = firstNonEmpty(\n env.SENTRY_PROJECT_ID,\n env.VITE_SENTRY_PROJECT_ID,\n );\n const host = firstNonEmpty(\n env.SENTRY_INGEST_HOST,\n env.VITE_SENTRY_INGEST_HOST,\n );\n const dsn =\n firstNonEmpty(\n env.SENTRY_CLIENT_DSN,\n env.VITE_SENTRY_CLIENT_DSN,\n env.VITE_SENTRY_DSN,\n env.SENTRY_DSN,\n ) || (key && projectId && host ? \"https://\" + key + \"@\" + host + \"/\" + projectId : undefined);\n if (!dsn) return null;\n const config = {\n sentryDsn: dsn,\n sentryEnvironment:\n firstNonEmpty(\n env.SENTRY_ENVIRONMENT,\n env.NETLIFY_CONTEXT,\n env.VERCEL_ENV,\n env.NODE_ENV,\n ) || \"production\",\n };\n return (\n '<script data-agent-native-sentry-config>' +\n 'window.__AGENT_NATIVE_CONFIG__=Object.assign({},window.__AGENT_NATIVE_CONFIG__,' +\n JSON.stringify(config) +\n \");</script>\"\n );\n}\n\nfunction injectHeadScript(html, script) {\n if (!script) return html;\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n return html.slice(0, headCloseIdx) + script + html.slice(headCloseIdx);\n}\n\nconst DEFAULT_SSR_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CACHE_CONTROL)};\nconst DEFAULT_SSR_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_CDN_CACHE_CONTROL)};\nconst DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL = ${JSON.stringify(DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL)};\nconst DEFAULT_SPECULATION_RULES_PATH = ${JSON.stringify(DEFAULT_SPECULATION_RULES_PATH)};\nconst IMMUTABLE_ASSET_CACHE_CONTROL = ${JSON.stringify(IMMUTABLE_ASSET_CACHE_CONTROL)};\nconst IMMUTABLE_ASSET_PATHS = new Set(${JSON.stringify(\n [...new Set(immutableAssetPaths)].sort(),\n )});\nconst AGENT_NATIVE_SOCIAL_IMAGE_PATH = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_PATH,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_ALT = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_ALT,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_TYPE = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_TYPE,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_WIDTH = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_WIDTH,\n )};\nconst AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT = ${JSON.stringify(\n AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT,\n )};\nconst OG_IMAGE_META_RE = /<meta\\\\b(?=[^>]*\\\\bproperty=([\"'])og:image\\\\1)[^>]*>/i;\nconst TWITTER_CARD_META_RE = /<meta\\\\b(?=[^>]*\\\\bname=([\"'])twitter:card\\\\1)[^>]*>/i;\nconst TWITTER_IMAGE_META_RE = /<meta\\\\b(?=[^>]*\\\\bname=([\"'])twitter:image\\\\1)[^>]*>/i;\n\nfunction withAgentNativeSocialImageCacheBuster(image) {\n const separator = image.includes(\"?\") ? \"&\" : \"?\";\n return image + separator + \"v=\" + encodeURIComponent(AGENT_NATIVE_SOCIAL_IMAGE_CACHE_BUSTER);\n}\n\nfunction defaultSocialImageUrl(request, basePath) {\n return withAgentNativeSocialImageCacheBuster(\n new URL(prefixMountedPath(AGENT_NATIVE_SOCIAL_IMAGE_PATH, basePath), request.url).toString()\n );\n}\n\nfunction injectDefaultSocialImageMeta(html, imageUrl) {\n const headCloseIdx = html.indexOf(\"</head>\");\n if (headCloseIdx === -1) return html;\n\n const hasAnySocialImage =\n OG_IMAGE_META_RE.test(html) || TWITTER_IMAGE_META_RE.test(html);\n const tags = [];\n\n if (!hasAnySocialImage) {\n tags.push('<meta property=\"og:image\" content=\"' + imageUrl + '\">');\n tags.push('<meta property=\"og:image:secure_url\" content=\"' + imageUrl + '\">');\n tags.push('<meta property=\"og:image:type\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_TYPE + '\">');\n tags.push('<meta property=\"og:image:width\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_WIDTH + '\">');\n tags.push('<meta property=\"og:image:height\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_HEIGHT + '\">');\n tags.push('<meta property=\"og:image:alt\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '\">');\n }\n if (!TWITTER_CARD_META_RE.test(html)) {\n tags.push('<meta name=\"twitter:card\" content=\"summary_large_image\">');\n }\n if (!hasAnySocialImage) {\n tags.push('<meta name=\"twitter:image\" content=\"' + imageUrl + '\">');\n tags.push('<meta name=\"twitter:image:alt\" content=\"' + AGENT_NATIVE_SOCIAL_IMAGE_ALT + '\">');\n }\n\n if (tags.length === 0) return html;\n return html.slice(0, headCloseIdx) + tags.join(\"\") + html.slice(headCloseIdx);\n}\n\nfunction isSsrHtmlOrDataResponse(headers, status, pathname) {\n if (status < 200 || status >= 400) return false;\n const contentType = (headers.get(\"content-type\") || \"\").toLowerCase();\n if (contentType.includes(\"text/html\")) return true;\n return pathname.endsWith(\".data\") && contentType.includes(\"text/x-script\");\n}\n\n/**\n * Apply the SSR cache policy to the response headers.\n *\n * SSR IS A PUBLIC, HARD-CDN-CACHED SHELL — SERVED IDENTICALLY TO EVERYONE.\n * Every SSR HTML / React Router .data response gets the same public\n * stale-while-revalidate policy for ALL visitors, authenticated or not. The SSR\n * output is impersonal (the handler never reads the request's session/cookies),\n * so it is safe to hard-cache one shared copy at the edge. Do NOT reintroduce\n * per-user / cookie-based cache variation here (no private, no no-store, no\n * \"authenticated then don't cache\" branch) — that makes every logged-in\n * visitor's pages uncacheable. Per-user state is resolved client-side instead.\n */\nfunction applyDefaultSsrCacheHeader(headers, status, pathname) {\n if (!isSsrHtmlOrDataResponse(headers, status, pathname)) return;\n\n headers.set(\"cache-control\", DEFAULT_SSR_CACHE_CONTROL);\n headers.set(\"cdn-cache-control\", DEFAULT_SSR_CDN_CACHE_CONTROL);\n // Netlify function responses are dynamic by default and can otherwise show\n // Cache-Status fwd=bypass even with Cache-Control: public. Keep this\n // Netlify-specific header so SSR HTML/.data are served from the shared\n // durable CDN cache instead of stampeding origin — for every visitor.\n headers.set(\"netlify-cdn-cache-control\", DEFAULT_SSR_NETLIFY_CDN_CACHE_CONTROL);\n}\n\nfunction applyDefaultSpeculationRulesHeader(headers, status, basePath) {\n if (status < 200 || status >= 400) return;\n if (headers.has(\"speculation-rules\")) return;\n\n const contentType = (headers.get(\"content-type\") || \"\").toLowerCase();\n if (!contentType.includes(\"text/html\")) return;\n\n // Cloudflare Speed Brain injects Speculation-Rules when origin omits this\n // header. Those browser prefetches carry Sec-Purpose: prefetch and\n // Cloudflare can return 503 before the request reaches origin. Publish an\n // explicit no-op ruleset by default; apps can still provide their own header.\n headers.set(\"speculation-rules\", '\"' + prefixMountedPath(DEFAULT_SPECULATION_RULES_PATH, basePath) + '\"');\n}\nfunction isImmutableAssetRequest(request) {\n const pathname = stripAppBasePath(new URL(request.url).pathname);\n return IMMUTABLE_ASSET_PATHS.has(pathname);\n}\n\nfunction applyImmutableAssetCacheHeaders(response, request) {\n if (!isImmutableAssetRequest(request)) return response;\n if (!((response.status >= 200 && response.status < 300) || response.status === 304)) {\n return response;\n }\n const headers = new Headers(response.headers);\n headers.set(\"Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n headers.set(\"CDN-Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n headers.set(\"Netlify-CDN-Cache-Control\", IMMUTABLE_ASSET_CACHE_CONTROL);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nasync function rewriteMountedResponse(response, basePath, pathname, request) {\n const sentryClientConfigScript = getSentryClientConfigScript();\n const headers = new Headers(response.headers);\n applyDefaultSsrCacheHeader(headers, response.status, pathname);\n applyDefaultSpeculationRulesHeader(headers, response.status, basePath);\n\n const location = headers.get(\"location\");\n if (location?.startsWith(\"/\") && !location.startsWith(\"//\")) {\n headers.set(\"location\", prefixMountedPath(location, basePath));\n }\n\n const contentType = headers.get(\"content-type\") || \"\";\n if (!contentType.toLowerCase().includes(\"text/html\") || !response.body) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n const html = await response.text();\n headers.delete(\"content-length\");\n return new Response(\n injectHeadScript(\n injectDefaultSocialImageMeta(\n prefixMountedHtml(html, basePath),\n defaultSocialImageUrl(request, basePath),\n ),\n sentryClientConfigScript,\n ),\n {\n status: response.status,\n statusText: response.statusText,\n headers,\n },\n );\n}\n\nfunction requestWithMethod(request, method) {\n return new Request(request.url, {\n method,\n headers: request.headers,\n signal: request.signal,\n });\n}\n\nfunction requestWithPathname(request, pathname) {\n const url = new URL(request.url);\n if (url.pathname === pathname) return request;\n url.pathname = pathname;\n return new Request(url, request);\n}\n\nfunction isStaticAppShellRequest(request) {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return false;\n const p = stripAppBasePath(new URL(request.url).pathname);\n if (\n p.startsWith(\"/.well-known/\") ||\n p.startsWith(\"/_agent-native/\") ||\n isApiPath(p) ||\n p === \"/favicon.ico\" ||\n p === \"/favicon.png\" ||\n /\\\\.\\\\w+$/.test(p)\n ) {\n return false;\n }\n return true;\n}\n\nasync function fetchStaticAppShell(request, env) {\n if (!env?.ASSETS || !isStaticAppShellRequest(request)) return null;\n const basePath = getAppBasePath();\n const p = stripAppBasePath(new URL(request.url).pathname);\n // Workspace deployments serve each app's static files under its base path\n // (/dispatch/index.html on the unified origin) — an unprefixed\n // \"/index.html\" 404s against the shared ASSETS binding and authed deep\n // links (e.g. /dispatch/overview) leaked h3's JSON 404 instead of the SPA\n // shell. Try the base-path-prefixed shell first, fall back to the root\n // shell for single-app deployments.\n let response;\n try {\n if (basePath) {\n response = await env.ASSETS.fetch(\n requestWithPathname(\n requestWithMethod(request, \"GET\"),\n basePath + \"/index.html\",\n ),\n );\n }\n if (!response || response.status === 404) {\n response = await env.ASSETS.fetch(\n requestWithPathname(requestWithMethod(request, \"GET\"), \"/index.html\"),\n );\n }\n } catch {\n return null;\n }\n if (response.status === 404) return null;\n if (request.method === \"HEAD\") {\n return rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n request,\n );\n }\n return rewriteMountedResponse(response, basePath, p, request);\n}\n\n// API route handlers\n${routeImports.join(\"\\n\")}\n\n// Action handlers (auto-discovered from actions/)\n${actionImports.join(\"\\n\")}\n\n// Server plugins\n${pluginImports.join(\"\\n\")}\n\nlet _handler;\n\nasync function getHandler() {\n if (_handler) return _handler;\n\n const app = new H3();\n\n // Build a fake nitroApp surface so framework plugins (which expect\n // \\`nitroApp.h3[\"~middleware\"]\\`) can register routes via getH3App().\n const noop = () => {};\n const nitroApp = {\n h3: app,\n hooks: { hook: noop, callHook: noop, hookOnce: noop },\n captureError: noop,\n };\n\n // CORS — applied as global middleware via .use(handler)\n app.use(defineEventHandler((event) => {\n if (event.req.method === \"OPTIONS\") {\n return new Response(null, {\n status: 204,\n headers: {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type,Authorization,X-Requested-With,X-Request-Source,X-Agent-Native-CSRF,X-User-Timezone,X-Agent-Native-Tool-Bridge,X-Agent-Native-Tool-Id,X-Agent-Native-Frontend,X-Agent-Native-Embed-Target\",\n },\n });\n }\n }));\n\n // Run plugins — they call getH3App(nitroApp).use(path, handler) which\n // pushes path-prefix middleware onto app[\"~middleware\"].\n // Pre-mark every build-time plugin slot before any plugin awaits the runtime\n // default bootstrap. Bundled serverless workers often lack server/plugins/\n // on disk, so runtime discovery would otherwise auto-mount duplicate\n // framework defaults before later custom plugins get a chance to mark\n // themselves as provided.\n${generatedPluginMarks.map((stem) => ` markGeneratedPluginProvided(nitroApp, ${JSON.stringify(stem)});`).join(\"\\n\")}\n${pluginCalls.join(\"\\n\")}\n\n // Register API routes\n${routeRegistrations.join(\"\\n\")}\n\n // Register action routes (/_agent-native/actions/*)\n${actionRegistrations.join(\"\\n\")}\n\n${\n includeReactRouterSsr\n ? ` // SSR catch-all for React Router\n const rrHandler = createRequestHandler(() => serverBuild);\n app.all(\"/**\", defineEventHandler(async (event) => {\n const basePath = getAppBasePath();\n const p = stripAppBasePath(new URL(event.req.url).pathname);\n if (\n p.startsWith(\"/.well-known/\") ||\n p.startsWith(\"/_agent-native/\") ||\n isApiPath(p) ||\n p === \"/favicon.ico\" ||\n p === \"/favicon.png\" ||\n (/\\\\.\\\\w+$/.test(p) && !p.endsWith(\".data\"))\n ) {\n return new Response(null, { status: 404 });\n }\n const request = requestWithPathname(event.req, p);\n if (event.req.method === \"HEAD\") {\n const getRequest = requestWithMethod(request, \"GET\");\n const response = await rrHandler(getRequest);\n return rewriteMountedResponse(\n new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n }),\n basePath,\n p,\n getRequest\n );\n }\n return rewriteMountedResponse(await rrHandler(request), basePath, p, request);\n }));`\n : \"\"\n}\n\n _handler = app.fetch.bind(app);\n return _handler;\n}\n\nexport default {\n async fetch(request, env, ctx) {\n // Expose env and ctx bindings globally for compatibility\n if (ctx) globalThis.__cf_ctx = ctx;\n if (env) {\n globalThis.process = globalThis.process || { env: {} };\n globalThis.process.env = globalThis.process.env || {};\n // Expose D1/KV/R2 bindings on globalThis.__cf_env for the db layer\n globalThis.__cf_env = env;\n for (const [key, value] of Object.entries(env)) {\n if (typeof value === \"string\") {\n globalThis.process.env[key] = value;\n }\n }\n }\n\n // Try serving static assets first (CF Pages advanced mode).\n // Only attempt this for GET/HEAD — the ASSETS binding is a static file\n // server and returns 405 for any other method, which would short-circuit\n // API calls (PUT/POST/DELETE to /_agent-native/*) before they reach our\n // h3 middleware.\n if (env?.ASSETS && (request.method === \"GET\" || request.method === \"HEAD\")) {\n try {\n const assetResponse = await env.ASSETS.fetch(request);\n if (assetResponse.status !== 404) {\n return applyImmutableAssetCacheHeaders(assetResponse, request);\n }\n } catch {\n // Asset fetch failed — fall through to SSR\n }\n }\n\n const handler = await getHandler();\n const response = await handler(requestWithMountedApiPrefixStripped(request));\n${\n includeReactRouterSsr\n ? \" return response;\"\n : ` if (response.status === 404) {\n const shellResponse = await fetchStaticAppShell(request, env);\n if (shellResponse) return shellResponse;\n }\n return response;`\n}\n }\n};\n`;\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll('\"', \""\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\");\n}\n\nfunction findReactRouterManifest(distDir: string): ReactRouterAssetManifest {\n const assetsDir = path.join(distDir, \"assets\");\n const manifestFile = fs\n .readdirSync(assetsDir)\n .find((file) => /^manifest-[\\w-]+\\.js$/.test(file));\n if (!manifestFile) {\n throw new Error(`React Router client manifest not found in ${assetsDir}`);\n }\n\n const source = fs.readFileSync(path.join(assetsDir, manifestFile), \"utf8\");\n const match = source.match(/^window\\.__reactRouterManifest=(.*);?\\s*$/);\n if (!match) {\n throw new Error(`Could not parse React Router manifest ${manifestFile}`);\n }\n\n return JSON.parse(match[1].replace(/;$/, \"\")) as ReactRouterAssetManifest;\n}\n\nfunction collectModulePreloads(\n manifest: ReactRouterAssetManifest,\n route: ReactRouterAssetManifestRoute,\n): string[] {\n const paths = new Set<string>();\n const add = (value: string | undefined) => {\n if (value) paths.add(value);\n };\n add(manifest.url);\n add(manifest.entry.module);\n manifest.entry.imports?.forEach(add);\n add(route.module);\n route.imports?.forEach(add);\n add(route.clientActionModule);\n add(route.clientLoaderModule);\n add(route.clientMiddlewareModule);\n add(route.hydrateFallbackModule);\n return [...paths];\n}\n\nfunction collectStylesheetLinks(\n manifest: ReactRouterAssetManifest,\n route: ReactRouterAssetManifestRoute,\n): string[] {\n return [...new Set([...(manifest.entry.css ?? []), ...(route.css ?? [])])];\n}\n\nfunction generateRouteModuleImportScript(\n manifest: ReactRouterAssetManifest,\n route: ReactRouterAssetManifestRoute,\n): string {\n const modules = [\n [\"route0\", route.module],\n [\"route0_clientAction\", route.clientActionModule],\n [\"route0_clientLoader\", route.clientLoaderModule],\n [\"route0_clientMiddleware\", route.clientMiddlewareModule],\n [\"route0_hydrateFallback\", route.hydrateFallbackModule],\n ] as const;\n const imports = modules\n .filter(([, modulePath]) => modulePath)\n .map(\n ([name, modulePath]) =>\n `import * as ${name} from ${JSON.stringify(modulePath)};`,\n );\n const parts = modules\n .filter(([, modulePath]) => modulePath)\n .map(([name]) => `...${name}`);\n\n return [\n `import ${JSON.stringify(manifest.url)};`,\n ...imports,\n `window.__reactRouterRouteModules = {${JSON.stringify(route.id)}:{${parts.join(\",\")}}};`,\n `import(${JSON.stringify(manifest.entry.module)});`,\n ].join(\"\\n\");\n}\n\nconst EMPTY_REACT_ROUTER_TURBO_STREAM =\n '[{\"_1\":2,\"_3\":-5,\"_4\":-5},\"loaderData\",{},\"actionData\",\"errors\"]\\n';\n\n// Manifest fallbacks cannot execute server loaders, so root loaders get the\n// framework's default locale shape to keep hydration from reading undefined.\nconst DEFAULT_ROOT_LOADER_REACT_ROUTER_TURBO_STREAM =\n '[{\"_1\":2,\"_3\":-5,\"_4\":-5},\"loaderData\",{\"_5\":6},\"actionData\",\"errors\",\"root\",{\"_7\":8,\"_9\":10,\"_11\":12,\"_13\":14},\"locale\",\"en-US\",\"preference\",{\"_7\":15},\"dir\",\"ltr\",\"messages\",{},\"system\"]\\n';\n\nexport function generateCloudflarePagesStaticShellFromManifest(\n manifest: ReactRouterAssetManifest,\n basePath = normalizeConfiguredAppBasePath(),\n): string {\n const rootRoute = manifest.routes.root;\n if (!rootRoute) {\n throw new Error(\"React Router manifest is missing the root route\");\n }\n\n const modulePreloads = collectModulePreloads(manifest, rootRoute)\n .map(\n (href) =>\n `<link rel=\"modulepreload\" href=\"${escapeHtmlAttribute(href)}\"/>`,\n )\n .join(\"\");\n const stylesheets = collectStylesheetLinks(manifest, rootRoute)\n .map(\n (href) => `<link rel=\"stylesheet\" href=\"${escapeHtmlAttribute(href)}\"/>`,\n )\n .join(\"\");\n const routeModuleScript = generateRouteModuleImportScript(\n manifest,\n rootRoute,\n );\n const context = {\n basename: basePath || \"/\",\n future: { unstable_optimizeDeps: false },\n routeDiscovery: { mode: \"initial\" },\n ssr: true,\n isSpaMode: true,\n };\n const encodedInitialState = rootRoute.hasLoader\n ? DEFAULT_ROOT_LOADER_REACT_ROUTER_TURBO_STREAM\n : EMPTY_REACT_ROUTER_TURBO_STREAM;\n\n return `<!DOCTYPE html><html lang=\"en\"><head><meta charSet=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\"/><link rel=\"manifest\" href=\"/manifest.json\"/><link rel=\"icon\" type=\"image/svg+xml\" href=\"/favicon.svg\"/>${modulePreloads}${stylesheets}</head><body><div style=\"display:flex;align-items:center;justify-content:center;height:100vh;width:100%\"><svg role=\"status\" aria-label=\"Loading\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" style=\"animation:an-spin 1s linear infinite;opacity:0.7\"><path d=\"M21 12a9 9 0 1 1-6.219-8.56\"></path></svg><style>@keyframes an-spin { to { transform: rotate(360deg) } } @media (prefers-color-scheme: dark) { html { background: #09090b; color: #fafafa } }</style></div><script>window.__reactRouterContext = ${JSON.stringify(context)};window.__reactRouterContext.stream = new ReadableStream({start(controller){window.__reactRouterContext.streamController = controller;}}).pipeThrough(new TextEncoderStream());</script><script type=\"module\" async=\"\">${routeModuleScript}</script><!--$--><script>window.__reactRouterContext.streamController.enqueue(${JSON.stringify(encodedInitialState)});</script><!--$--><script>window.__reactRouterContext.streamController.close();</script><!--/$--><!--/$--></body></html>`;\n}\n\nfunction writeCloudflarePagesStaticShell({\n serverDir,\n distDir,\n tmpDir,\n}: {\n serverDir: string;\n distDir: string;\n tmpDir: string;\n}): void {\n const serverEntry = path.join(serverDir, \"index.js\");\n if (!fs.existsSync(serverEntry)) {\n throw new Error(`React Router server build not found at ${serverEntry}`);\n }\n\n const outFile = path.join(distDir, \"index.html\");\n const renderScript = path.join(tmpDir, \"render-cloudflare-static-shell.mjs\");\n const basePath = normalizeConfiguredAppBasePath();\n fs.writeFileSync(\n renderScript,\n `\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\n\nconst cwd = ${JSON.stringify(cwd)};\nconst serverEntry = ${JSON.stringify(serverEntry)};\nconst outFile = ${JSON.stringify(outFile)};\nconst basePath = ${JSON.stringify(basePath)};\n\nconst requireFromApp = createRequire(cwd + \"/package.json\");\nconst reactRouterEntry = requireFromApp.resolve(\"react-router\");\nconst { createRequestHandler } = await import(pathToFileURL(reactRouterEntry).href);\nconst serverBuild = await import(pathToFileURL(serverEntry).href);\nconst handler = createRequestHandler(serverBuild, \"production\");\nconst pathname = basePath ? basePath + \"/\" : \"/\";\nconst response = await handler(\n new Request(new URL(pathname, \"https://agent-native.local\"), {\n headers: { \"X-React-Router-SPA-Mode\": \"yes\" },\n }),\n);\nconst html = await response.text();\n\nif (!html || !html.includes(\"__reactRouterContext\") || !html.includes(\"entry.client\")) {\n throw new Error(\"React Router did not render a usable Cloudflare Pages static shell\");\n}\n\nfs.writeFileSync(outFile, html);\nprocess.exit(0);\n`,\n );\n\n try {\n execFileSync(process.execPath, [renderScript], {\n cwd,\n env: {\n ...process.env,\n NODE_ENV: process.env.NODE_ENV || \"production\",\n IS_RR_BUILD_REQUEST: \"yes\",\n },\n stdio: \"inherit\",\n });\n console.log(\"[deploy] Wrote Cloudflare Pages static app shell.\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(\n `[deploy] React Router static shell render failed; using manifest fallback. ${message}`,\n );\n fs.writeFileSync(\n outFile,\n generateCloudflarePagesStaticShellFromManifest(\n findReactRouterManifest(distDir),\n basePath,\n ),\n );\n console.log(\"[deploy] Wrote Cloudflare Pages static app shell fallback.\");\n }\n}\n\n/**\n * Build for Cloudflare Pages.\n * Output structure:\n * dist/\n * _worker.js (bundled worker entry)\n * assets/ (static client assets)\n */\nasync function buildCloudflarePages() {\n generateActionRegistryForProject(cwd);\n\n const buildDir = path.join(cwd, \"build\");\n const clientDir = path.join(buildDir, \"client\");\n const serverDir = path.join(buildDir, \"server\");\n const distDir = path.join(cwd, \"dist\");\n\n // Verify build output exists\n if (!fs.existsSync(clientDir) || !fs.existsSync(serverDir)) {\n console.error(\n \"Build output not found at build/client/ and build/server/. Run react-router build first.\",\n );\n process.exit(1);\n }\n\n // Clean dist\n if (fs.existsSync(distDir)) {\n fs.rmSync(distDir, { recursive: true });\n }\n fs.mkdirSync(distDir, { recursive: true });\n\n // Copy client assets to dist/\n copyDir(clientDir, distDir);\n\n const tmpDir = path.join(cwd, \".deploy-tmp\");\n fs.mkdirSync(tmpDir, { recursive: true });\n writeCloudflarePagesStaticShell({ serverDir, distDir, tmpDir });\n\n // Exclude _worker.js from being served as a public asset\n fs.writeFileSync(path.join(distDir, \".assetsignore\"), \"_worker.js\\n\");\n\n // Write package metadata inside _worker.js/ for the ES module worker that\n // Wrangler compiles and uploads for Cloudflare Pages.\n fs.mkdirSync(path.join(distDir, \"_worker.js\"), { recursive: true });\n fs.writeFileSync(\n path.join(distDir, \"_worker.js\", \"package.json\"),\n JSON.stringify({ main: \"index.js\", type: \"module\" }),\n );\n\n // Create empty stub for native modules that wrangler's bundler needs to resolve\n const stubsDir = path.join(distDir, \"_worker.js\", \"stubs\");\n fs.mkdirSync(stubsDir, { recursive: true });\n fs.writeFileSync(\n path.join(stubsDir, \"empty.js\"),\n \"export default {}; export const watch = () => ({ close() {} }); export const Database = class {};\\n\",\n );\n\n // Discover routes, plugins, actions, and the workspace core (if any).\n const routes = await discoverApiRoutes(cwd);\n const plugins = await discoverPlugins(cwd);\n const actions = await discoverActionFiles(cwd);\n const missingDefaults = await getMissingDefaultPlugins(cwd);\n const workspaceCore = await getWorkspaceCoreExports(cwd);\n const includeReactRouterSsr = false;\n\n const workspaceSlotCount = workspaceCore\n ? Object.keys(workspaceCore.plugins).length\n : 0;\n console.log(\n `[deploy] ${routes.length} API routes, ${actions.length} actions, ${plugins.length} plugins (${plugins.filter((p) => isNodeOnlyPlugin(p)).length} skipped as Node-only), ${missingDefaults.length} auto-mounted defaults${workspaceCore ? `, workspace-core ${workspaceCore.packageName} (${workspaceSlotCount} plugin slots)` : \"\"}`,\n );\n\n // Generate the worker entry\n const immutableAssetPaths = collectImmutableAssetPaths(clientDir);\n const entrySource = generateWorkerEntry(\n routes,\n plugins,\n missingDefaults,\n actions,\n workspaceCore,\n immutableAssetPaths,\n normalizeConfiguredAppBasePath(),\n { includeReactRouterSsr },\n );\n\n // Create _worker.js output directory\n const workerOutDir = path.join(distDir, \"_worker.js\");\n fs.mkdirSync(workerOutDir, { recursive: true });\n\n // Write the worker entry\n const entryFile = path.join(workerOutDir, \"index.js\");\n\n // Rewrite the server-build import to point at the copied files when this\n // worker intentionally includes React Router SSR.\n const adjustedEntry = includeReactRouterSsr\n ? entrySource.replace(\n `import * as serverBuild from \"./server-build.js\";`,\n `import * as serverBuild from \"./server/index.js\";`,\n )\n : entrySource;\n\n // Write a temp file for esbuild to bundle everything into a single worker entry.\n // When React Router SSR is enabled, the server build is copied to tmp so\n // esbuild can resolve it. Cloudflare Pages currently uses a static app shell\n // instead so the worker stays under the platform bundle size limit.\n // Name the entry \"index.js\" so esbuild outputs index.js in the outdir,\n // matching the _worker.js/index.js entry point that Cloudflare Pages expects.\n const tmpEntry = path.join(tmpDir, \"index.js\");\n fs.writeFileSync(tmpEntry, adjustedEntry);\n\n if (includeReactRouterSsr) {\n copyDir(serverDir, path.join(tmpDir, \"server\"));\n }\n\n // Create a require shim so CJS require(\"fs\") calls resolve via ESM imports.\n // This is injected via esbuild --inject to replace its broken __require shim.\n fs.writeFileSync(\n path.join(tmpDir, \"_require-shim.js\"),\n generateRequireShim(),\n );\n\n const nitroServerAssetsStub = path.join(\n tmpDir,\n \"_nitro-server-assets-stub.js\",\n );\n fs.writeFileSync(\n nitroServerAssetsStub,\n [\n \"const empty = async () => undefined;\",\n \"export const assets = {\",\n \" getItem: empty,\",\n \" getItemRaw: empty,\",\n \" getKeys: async () => [],\",\n \" getMeta: async () => undefined,\",\n \" hasItem: async () => false,\",\n \"};\",\n \"export default assets;\",\n \"\",\n ].join(\"\\n\"),\n );\n\n // Create stub modules for native/Node-only deps that can't run on Workers.\n // These get resolved by esbuild instead of the real modules, avoiding bundling\n // native code that would fail on the Workers runtime. Uninstalled optional\n // AI SDK provider packages are stubbed the same way so their literal dynamic\n // import() sites in ai-sdk-engine don't fail the bundle.\n const workerStubModules: Record<string, string> = {\n ...CLOUDFLARE_WORKER_STUB_MODULES,\n ...uninstalledOptionalAiSdkStubs(cwd),\n };\n const stubDir = path.join(tmpDir, \"node_modules\");\n for (const [mod, source] of Object.entries(workerStubModules)) {\n const modDir = path.join(stubDir, mod);\n fs.mkdirSync(modDir, { recursive: true });\n fs.writeFileSync(path.join(modDir, \"index.js\"), source);\n fs.writeFileSync(\n path.join(modDir, \"package.json\"),\n JSON.stringify({ name: mod, main: \"index.js\", type: \"module\" }),\n );\n }\n const stubAliases = Object.keys(workerStubModules).map(\n (mod) => `--alias:${mod}=${path.join(stubDir, mod, \"index.js\")}`,\n );\n const nodeBuiltinStubDir = path.join(tmpDir, \"node-builtin-stubs\");\n fs.mkdirSync(nodeBuiltinStubDir, { recursive: true });\n const nodeBuiltinStubAliases: string[] = [];\n for (const [mod, source] of Object.entries(\n CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES,\n ).sort(([a], [b]) => b.length - a.length)) {\n const stubFile = path.join(\n nodeBuiltinStubDir,\n `${mod.replace(/\\W+/g, \"_\")}.js`,\n );\n fs.writeFileSync(stubFile, source);\n nodeBuiltinStubAliases.push(\n `--alias:${mod}=${stubFile}`,\n `--alias:node:${mod}=${stubFile}`,\n );\n }\n\n const esbuildBin = findEsbuild();\n\n // Externalize node builtins (both bare and node: prefixed) — the require\n // shim handles bare ones. Also alias every `node:*` specifier to its bare\n // name so esbuild emits `import from \"fs\"` everywhere, never\n // `import from \"node:fs\"`. CF Pages Functions (wrangler 3.x, nodejs_compat\n // v1) rejects the `node:` prefix in chunks with:\n // No such module \"node:fs\" imported from chunks/...\n // The alias is the authoritative fix; the post-build strip stays as belt\n // & suspenders in case esbuild emits a node: string via some other path.\n const builtinNames = getNodeBuiltinNames();\n // Only externalize bare names. node:* externals would otherwise pin\n // the prefix in output; instead we alias node:* → bare so anything that\n // resolves past alias land as bare externals.\n const nodeBuiltinStubs = new Set(\n Object.keys(CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES),\n );\n const nodeExternals = builtinNames\n .filter((n) => !nodeBuiltinStubs.has(n))\n .sort((a, b) => b.length - a.length)\n .map((n) => `--external:${n}`);\n const nodeAliases = builtinNames\n .filter((n) => !nodeBuiltinStubs.has(n))\n .sort((a, b) => b.length - a.length)\n .map((n) => `--alias:node:${n}=${n}`);\n\n // Hard externalize large client-only / node-only libraries so they don't\n // bloat the edge worker. These are never executed in the CF Pages runtime\n // — mermaid/excalidraw render in the browser, pdf-parse and @google/genai\n // run from node-only action scripts. Without this, slides' bundle hits\n // the 25 MiB Pages Functions limit.\n //\n // @anthropic-ai/tokenizer (tiktoken .wasm) and @resvg/resvg-js (native\n // .node binding) can't be bundled by esbuild at all — no loader for those\n // files. Both import sites degrade gracefully when the runtime import\n // fails: context-xray token counts fall back to char/4 estimates and the\n // OG image route falls back to SVG.\n const heavyClientExternals = CLOUDFLARE_WORKER_ESBUILD_EXTERNALS.filter(\n (p) => !Object.hasOwn(CLOUDFLARE_WORKER_STUB_MODULES, p),\n ).map((p) => `--external:${p}`);\n\n const esbuildCommand = esbuildSpawnCommand(esbuildBin, [\n tmpEntry,\n \"--bundle\",\n \"--format=esm\",\n \"--target=es2022\",\n // browser platform for npm resolution; node builtins externalized separately\n \"--platform=browser\",\n \"--minify\",\n // Single-file bundle (no --splitting). CF Pages Functions' deploy\n // validator fails to load chunked _worker.js/ bundles even when the\n // chunks contain only bare node-builtin imports (wrangler 3.101.0\n // + nodejs_compat v2). Matches main's working config.\n `--outdir=${workerOutDir}`,\n \"--conditions=workerd,worker,import\",\n // The ssr-handler imports a virtual module that only exists at dev time\n \"--external:virtual:react-router/server-build\",\n `--alias:#nitro/virtual/server-assets=${nitroServerAssetsStub}`,\n // Banner: override the __require shim that esbuild generates for CJS modules.\n // This provides a real require() backed by ESM imports of node builtins.\n // Without this, CF Workers rejects the bundle because esbuild's default\n // __require shim throws \"Dynamic require of X is not supported\".\n `--banner:js=${generateRequireShim()}`,\n // Externalize node: builtins — CF Workers runtime provides them\n ...nodeExternals,\n ...heavyClientExternals,\n ...stubAliases,\n ...nodeBuiltinStubAliases,\n // Rewrite node:* -> bare names so chunks never contain node: imports\n ...nodeAliases,\n ]);\n execFileSync(esbuildCommand.file, esbuildCommand.args, {\n stdio: \"inherit\",\n cwd,\n });\n\n // Clean up tmp\n fs.rmSync(tmpDir, { recursive: true });\n\n // Rewrite the external virtual import to a local stub.\n // esbuild externalizes \"virtual:react-router/server-build\" (used by ssr-handler),\n // but wrangler re-bundles and chokes on it. Replace the import with a no-op stub.\n const virtualStub = path.join(workerOutDir, \"chunks\", \"_virtual-stub.js\");\n fs.mkdirSync(path.dirname(virtualStub), { recursive: true });\n fs.writeFileSync(virtualStub, \"export default {};\\n\");\n\n // Post-build patches — apply to ALL .js files in the worker output directory\n // (entry + chunks) since code can land in any chunk after splitting.\n const allJsFiles = getAllJsFiles(workerOutDir);\n for (const jsFile of allJsFiles) {\n let code = fs.readFileSync(jsFile, \"utf-8\");\n const isEntry = path.basename(jsFile) === \"index.js\";\n\n // Strip \"node:\" prefix from all imports/requires. Cloudflare Pages\n // Functions runs under nodejs_compat v1, which exposes builtins as\n // bare names (\"fs\") and rejects \"node:fs\" at worker init:\n // No such module \"node:fs\" imported from chunks/...\n // (Workers-on-the-edge use v2 and require the prefix; Pages lags.)\n // Preserve the original quote char (single vs double) when rewriting —\n // esbuild's minifier sometimes places `import('node:buffer')` inside a\n // double-quoted string literal; swapping to double quotes breaks the\n // outer literal and produces `Unexpected identifier 'buffer'`.\n code = code.replace(\n /\\bfrom(\\s*)([\"'])node:([^\"']+)\\2/g,\n (_, ws, q, mod) => `from${ws}${q}${mod}${q}`,\n );\n code = code.replace(\n /\\bimport(\\s*)([\"'])node:([^\"']+)\\2/g,\n (_, ws, q, mod) => `import${ws}${q}${mod}${q}`,\n );\n // Strip `node:` prefix from any string literal that names a node\n // builtin. Covers dynamic imports, require(), getBuiltinModule(),\n // and minified wrappers like `Ut(\"node:fs\")` that Nitro/h3 emit.\n // Pages' loader scans chunks for `\"node:*\"` literals and fails with\n // 'No such module \"node:fs\"' whether or not the string is reached\n // at runtime. Scoping to known builtins avoids touching user data.\n // Sorted longest-first so `fs/promises` matches before `fs`.\n const builtinsPattern = [...NODE_BUILTINS]\n .sort((a, b) => b.length - a.length)\n .join(\"|\");\n const builtinRe = new RegExp(`([\"'])node:(${builtinsPattern})\\\\1`, \"g\");\n code = code.replace(\n builtinRe,\n (_, q: string, mod: string) => `${q}${mod}${q}`,\n );\n\n // Rewrite virtual:react-router/server-build imports to the local stub.\n // The generated entry handles SSR directly; this import is dead code from ssr-handler.\n const relStub = path\n .relative(path.dirname(jsFile), virtualStub)\n .replace(/\\\\/g, \"/\");\n code = code.replace(\n /[\"']virtual:react-router\\/server-build[\"']/g,\n `\"./${relStub}\"`,\n );\n\n // Patch createRequire(import.meta.url) — import.meta.url is undefined in CF Workers.\n // Matches both `from \"module\"` and `from \"node:module\"` — with the node:\n // prefix preserved (for nodejs_compat_v2), the latter is what esbuild now emits.\n code = code.replace(\n /\\bimport\\s*\\{\\s*createRequire\\s+as\\s+([\\w$]+)\\s*\\}\\s*from\\s*[\"'](?:node:)?module[\"']\\s*;/g,\n \"var $1 = function() { return typeof require !== 'undefined' ? require : function(m) { throw new Error('require not supported: ' + m); }; };\",\n );\n\n // Patch remaining import.meta.url occurrences — when wrangler/Pages\n // re-bundles the worker, inner modules get an emptied import.meta, so\n // fileURLToPath(import.meta.url) throws at module init (\"path\" argument\n // must be string, received undefined). Same treatment as the Vite\n // server-build path: replace with a stable synthetic file URL.\n code = code.replace(/\\bimport\\.meta\\.url\\b/g, '\"file:///worker.mjs\"');\n\n // Patch setInterval/setTimeout at module scope — CF Workers disallows timers in global scope.\n // Some dependencies (e.g. Anthropic SDK rate limiter) call setInterval at module init.\n // With code splitting, chunks evaluate before the entry, so the shim must be in every file.\n // The restore only happens in the entry's fetch() handler.\n if (!code.includes(\"__origSetInterval\")) {\n const timerShim = [\n \"var __origSetInterval=globalThis.setInterval;\",\n \"globalThis.setInterval=function(){return{unref(){},ref(){},close(){}}};\",\n ].join(\"\");\n code = timerShim + code;\n }\n if (isEntry) {\n const timerRestore =\n \"if(__origSetInterval)globalThis.setInterval=__origSetInterval;\";\n code = code.replace(\n /async fetch\\(request,\\s*env,\\s*ctx\\)\\s*\\{/,\n (match) => match + timerRestore,\n );\n }\n\n fs.writeFileSync(jsFile, code);\n }\n\n // Report size\n const entrySize = fs.statSync(entryFile).size;\n const totalSize = getDirSize(workerOutDir);\n const chunkCount = allJsFiles.length - 1; // exclude entry\n console.log(\n `[deploy] Cloudflare Pages output written to dist/ (entry: ${(entrySize / 1024).toFixed(0)}KB, ${chunkCount} chunks, total: ${(totalSize / 1024 / 1024).toFixed(1)}MB)`,\n );\n}\n\nconst NODE_BUILTINS = [\n \"assert\",\n \"async_hooks\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"console\",\n \"constants\",\n \"crypto\",\n \"dgram\",\n \"diagnostics_channel\",\n \"dns\",\n \"dns/promises\",\n \"domain\",\n \"events\",\n \"fs\",\n \"fs/promises\",\n \"http\",\n \"http2\",\n \"https\",\n \"inspector\",\n \"module\",\n \"net\",\n \"os\",\n \"path\",\n \"perf_hooks\",\n \"process\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"repl\",\n \"sqlite\",\n \"stream\",\n \"stream/web\",\n \"string_decoder\",\n \"sys\",\n \"timers\",\n \"tls\",\n \"trace_events\",\n \"tty\",\n \"url\",\n \"util\",\n \"v8\",\n \"vm\",\n \"wasi\",\n \"worker_threads\",\n \"zlib\",\n];\n\nexport function getNodeBuiltinNames(): string[] {\n return NODE_BUILTINS;\n}\n\n/**\n * Generate a require() shim that bridges CJS require(\"fs\") calls to ESM imports.\n * Injected via esbuild --inject so CJS deps work on Workers runtime.\n */\nfunction generateRequireShim(): string {\n // Shim Node builtins that Cloudflare Pages can import, and return lazy\n // unavailable proxies for builtins that Pages Functions reject at upload\n // time (child_process, fs, net, etc.). This lets optional Node-only code stay\n // present in the shared bundle without making worker initialization fail.\n const stubbed = new Set(\n Object.keys(CLOUDFLARE_WORKER_NODE_BUILTIN_STUB_MODULES),\n );\n const shimmed = NODE_BUILTINS.filter((name) => !stubbed.has(name));\n\n // Bare module names — CF Pages Functions runs under nodejs_compat v1,\n // which rejects \"node:fs\" and only accepts \"fs\". The post-build pass in\n // buildCloudflarePages() also strips any `node:` prefix that esbuild or\n // dependencies emit elsewhere.\n const imports = shimmed\n .map((m) => `import __${m.replace(\"/\", \"_\")} from \"${m}\";`)\n .join(\"\");\n // Only bare-name keys. Pages' Functions loader appears to scan chunks\n // for \"node:*\" string literals and pre-resolves them as module specs —\n // so keeping \"node:fs\" as an object key caused deploy to fail with\n // 'No such module \"node:fs\"' even though nothing imported it. The\n // post-build strip turns every runtime `require(\"node:fs\")` into\n // `require(\"fs\")` so bare keys are sufficient.\n const entries = shimmed\n .map((m) => `\"${m}\":__${m.replace(\"/\", \"_\")}`)\n .join(\",\");\n const stubEntries = Array.from(stubbed)\n .sort()\n .map((m) => `\"${m}\":__unavailable(\"${m}\")`)\n .join(\",\");\n const allEntries = [entries, stubEntries].filter(Boolean).join(\",\");\n\n const messageChannelPolyfill = `if(typeof MessageChannel===\"undefined\"){globalThis.MessageChannel=class{constructor(){const a={onmessage:null},b={onmessage:null};a.postMessage=d=>{if(b.onmessage)setTimeout(()=>b.onmessage({data:d}),0)};b.postMessage=d=>{if(a.onmessage)setTimeout(()=>a.onmessage({data:d}),0)};this.port1=a;this.port2=b}}}`;\n return `${imports}\\n${messageChannelPolyfill}\\nconst __unavailable=(m)=>new Proxy({}, { get(_target, prop) { return (..._args) => { throw new Error(m + \".\" + String(prop) + \" is unavailable in Cloudflare Pages workers\"); }; } });\\nconst __mods={${allEntries}};export var require=globalThis.require||function(m){const r=__mods[m];if(r!==undefined)return r;throw new Error(\"Cannot require: \"+m)};\\n`;\n}\n\nfunction findEsbuild(): string {\n // Try to resolve esbuild's binary via Node module resolution\n // This works regardless of hoisting or .bin symlink creation\n try {\n const _require = createRequire(cwd + \"/\");\n const esbuildPkg = path.dirname(_require.resolve(\"esbuild/package.json\"));\n const bin = path.join(esbuildPkg, \"bin\", \"esbuild\");\n if (fs.existsSync(bin)) return bin;\n } catch {}\n\n // Fallback: check local and workspace .bin\n const localBin = path.resolve(cwd, \"node_modules/.bin/esbuild\");\n if (fs.existsSync(localBin)) return localBin;\n\n const workspaceRoot = findWorkspaceRoot(cwd);\n if (workspaceRoot) {\n const workspaceBin = path.resolve(\n workspaceRoot,\n \"node_modules/.bin/esbuild\",\n );\n if (fs.existsSync(workspaceBin)) return workspaceBin;\n }\n\n return \"esbuild\";\n}\n\n/**\n * `esbuild/bin/esbuild` is a `#!/usr/bin/env node` JS shim, not a native\n * executable. Shebangs don't exist on Windows, so `execFileSync(shim)` fails\n * there with ENOENT even though the file exists. Run any node-shebang script\n * through the current Node executable (works on every platform — the shim\n * locates and execs the real platform binary itself); native executables and\n * PATH lookups spawn directly.\n */\nexport function esbuildSpawnCommand(\n esbuildBin: string,\n args: string[],\n): { file: string; args: string[] } {\n if (isNodeShebangScript(esbuildBin)) {\n return { file: process.execPath, args: [esbuildBin, ...args] };\n }\n return { file: esbuildBin, args };\n}\n\nfunction isNodeShebangScript(file: string): boolean {\n if (!file.includes(\"/\") && !file.includes(path.sep)) return false;\n try {\n const fd = fs.openSync(file, \"r\");\n const buf = Buffer.alloc(128);\n const bytesRead = fs.readSync(fd, buf, 0, buf.length, 0);\n fs.closeSync(fd);\n const firstLine = buf.toString(\"utf8\", 0, bytesRead).split(/\\r?\\n/)[0];\n // Only the shebang line decides — a `#!/bin/sh` wrapper that merely\n // mentions node in its body must still spawn directly.\n return firstLine.startsWith(\"#!\") && /\\bnode\\s*$/.test(firstLine);\n } catch {\n return false;\n }\n}\n\nfunction findWorkspaceRoot(dir: string): string | null {\n let current = dir;\n while (current !== path.dirname(current)) {\n if (\n fs.existsSync(path.join(current, \"pnpm-workspace.yaml\")) ||\n fs.existsSync(path.join(current, \"pnpm-lock.yaml\"))\n ) {\n return current;\n }\n current = path.dirname(current);\n }\n return null;\n}\n\n/** Recursively collect all .js files in a directory. */\nfunction getAllJsFiles(dir: string): string[] {\n const results: string[] = [];\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...getAllJsFiles(fullPath));\n } else if (entry.name.endsWith(\".js\")) {\n results.push(fullPath);\n }\n }\n return results;\n}\n\nfunction getDirSize(dir: string): number {\n let size = 0;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n size += getDirSize(fullPath);\n } else {\n size += fs.statSync(fullPath).size;\n }\n }\n return size;\n}\n\nexport function copyDir(\n src: string,\n dest: string,\n ancestorRealPaths = new Set<string>(),\n) {\n const realSrc = fs.realpathSync(src);\n if (ancestorRealPaths.has(realSrc)) return;\n const nextAncestorRealPaths = new Set(ancestorRealPaths);\n nextAncestorRealPaths.add(realSrc);\n\n fs.mkdirSync(dest, { recursive: true });\n const entries = fs.readdirSync(src, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n if (entry.isSymbolicLink()) {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(srcPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.warn(\n `[deploy] Skipping broken symlink while copying ${srcPath}`,\n );\n continue;\n }\n throw error;\n }\n if (stat.isDirectory()) {\n copyDir(srcPath, destPath, nextAncestorRealPaths);\n } else {\n fs.copyFileSync(srcPath, destPath);\n }\n } else if (entry.isDirectory()) {\n copyDir(srcPath, destPath, nextAncestorRealPaths);\n } else {\n fs.copyFileSync(srcPath, destPath);\n }\n }\n}\n\nconst LIBSQL_NATIVE_PACKAGE_NAMES = [\n \"darwin-arm64\",\n \"darwin-x64\",\n \"linux-arm-gnueabihf\",\n \"linux-arm-musleabihf\",\n \"linux-arm64-gnu\",\n \"linux-arm64-musl\",\n \"linux-x64-gnu\",\n \"linux-x64-musl\",\n \"win32-x64-msvc\",\n];\nconst FFMPEG_STATIC_PACKAGE_NAME = \"ffmpeg-static\";\nconst RESVG_SCOPE = \"@resvg\";\nconst RESVG_PACKAGE_PREFIX = \"resvg-js\";\nconst FFMPEG_STATIC_BINARY_NAMES =\n process.platform === \"win32\" ? [\"ffmpeg.exe\", \"ffmpeg\"] : [\"ffmpeg\"];\nconst SERVERLESS_FFMPEG_STATIC_PLATFORM = \"linux\";\nconst SERVERLESS_FFMPEG_STATIC_ARCHES = new Set<NodeJS.Architecture>([\n \"arm64\",\n \"x64\",\n]);\nconst SERVERLESS_FUNCTION_PACKAGE_DENYLIST = new Set([\n \"@vscode/test-electron\",\n \"electron\",\n \"electron-builder\",\n \"electron-updater\",\n \"electron-vite\",\n \"fsevents\",\n \"node-pty\",\n \"playwright\",\n]);\ntype ServerlessFfmpegStaticArch = \"arm64\" | \"x64\";\n\nfunction serverlessFfmpegStaticTargetArchFromEnv(): ServerlessFfmpegStaticArch | null {\n const value = process.env.AGENT_NATIVE_SERVERLESS_FFMPEG_ARCH;\n if (value === \"arm64\" || value === \"x64\") return value;\n return null;\n}\n\nexport function shouldBundleFfmpegStaticForServerless(\n hostPlatform: NodeJS.Platform = process.platform,\n hostArch: NodeJS.Architecture = process.arch,\n targetArch: ServerlessFfmpegStaticArch | null = serverlessFfmpegStaticTargetArchFromEnv(),\n): boolean {\n return (\n hostPlatform === SERVERLESS_FFMPEG_STATIC_PLATFORM &&\n targetArch !== null &&\n hostArch === targetArch &&\n SERVERLESS_FFMPEG_STATIC_ARCHES.has(targetArch)\n );\n}\n\nfunction nodeModulesAncestors(startDir: string): string[] {\n const dirs: string[] = [];\n let current = path.resolve(startDir);\n while (true) {\n const candidate = path.join(current, \"node_modules\");\n if (fs.existsSync(candidate)) dirs.push(candidate);\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return dirs;\n}\n\nfunction findInstalledLibsqlNativePackage(\n nodeModulesRoots: string[],\n packageName: string,\n): string | null {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, \"@libsql\", packageName);\n if (fs.existsSync(path.join(direct, \"index.node\"))) return direct;\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `@libsql+${packageName}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n \"@libsql\",\n packageName,\n );\n if (fs.existsSync(path.join(nested, \"index.node\"))) return nested;\n }\n }\n return null;\n}\n\nfunction hasFfmpegStaticBinary(packageDir: string): boolean {\n return FFMPEG_STATIC_BINARY_NAMES.some((binaryName) =>\n fs.existsSync(path.join(packageDir, binaryName)),\n );\n}\n\nfunction hasInstalledFfmpegStaticPackage(nodeModulesRoots: string[]): boolean {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, FFMPEG_STATIC_PACKAGE_NAME);\n if (fs.existsSync(path.join(direct, \"package.json\"))) return true;\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `${FFMPEG_STATIC_PACKAGE_NAME}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n FFMPEG_STATIC_PACKAGE_NAME,\n );\n if (fs.existsSync(path.join(nested, \"package.json\"))) return true;\n }\n }\n return false;\n}\n\nexport function findInstalledFfmpegStaticPackage(\n nodeModulesRoots: string[],\n): string | null {\n for (const root of nodeModulesRoots) {\n const direct = path.join(root, FFMPEG_STATIC_PACKAGE_NAME);\n if (\n fs.existsSync(path.join(direct, \"package.json\")) &&\n hasFfmpegStaticBinary(direct)\n ) {\n return direct;\n }\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n const pnpmPrefix = `${FFMPEG_STATIC_PACKAGE_NAME}@`;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n if (!entry.startsWith(pnpmPrefix)) continue;\n const nested = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n FFMPEG_STATIC_PACKAGE_NAME,\n );\n if (\n fs.existsSync(path.join(nested, \"package.json\")) &&\n hasFfmpegStaticBinary(nested)\n ) {\n return nested;\n }\n }\n }\n return null;\n}\n\nexport function findInstalledResvgPackages(\n nodeModulesRoots: string[],\n): Array<{ packageName: string; packageDir: string }> {\n const found = new Map<string, string>();\n\n for (const root of nodeModulesRoots) {\n const directScope = path.join(root, RESVG_SCOPE);\n if (fs.existsSync(directScope)) {\n for (const entry of fs.readdirSync(directScope)) {\n if (!entry.startsWith(RESVG_PACKAGE_PREFIX)) continue;\n const packageDir = path.join(directScope, entry);\n if (fs.existsSync(path.join(packageDir, \"package.json\"))) {\n found.set(entry, packageDir);\n }\n }\n }\n\n const pnpmRoot = path.join(root, \".pnpm\");\n if (!fs.existsSync(pnpmRoot)) continue;\n for (const entry of fs.readdirSync(pnpmRoot)) {\n const match = entry.match(/^@resvg\\+(resvg-js[^@]*)@/);\n if (!match) continue;\n const packageName = match[1];\n const packageDir = path.join(\n pnpmRoot,\n entry,\n \"node_modules\",\n RESVG_SCOPE,\n packageName,\n );\n if (fs.existsSync(path.join(packageDir, \"package.json\"))) {\n found.set(packageName, packageDir);\n }\n }\n }\n\n return [...found.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([packageName, packageDir]) => ({ packageName, packageDir }));\n}\n\n/**\n * Deploy-time gate for emitting the second `-background` Netlify function.\n * Reads the same env flag the runtime gate uses\n * (`AGENT_CHAT_DURABLE_BACKGROUND`).\n *\n * DEFAULT-OFF (opt-in), matching the runtime gate (`isFlagEnabled` in\n * durable-background.ts): unset/empty/unknown means DISABLED; an app opts IN\n * only with an explicit truthy value (`true`/`1`/`yes`/`on`). A premature\n * fleet-wide default-on caused real-user incidents (2026-06-24) before the\n * async worker path was proven, so durable is opt-in until verified live. This\n * gate is what emits the 15-min `-background` function so the `_process-run`\n * dispatch lands on it (async 202 → the worker runs with the real 15-min budget\n * → its ~13-min soft-timeout fits). The deploy gate and runtime gate MUST agree:\n * if the deploy emitted no `-background` function but the runtime still routed\n * the worker into the ~13-min timeout regime, the worker would overshoot the\n * ~60s synchronous wall and re-dispatch in a loop. (The runtime now also guards\n * the ~13-min budget on the real function name via `isInBackgroundFunctionRuntime`,\n * so a missing emit degrades to clean 40s-chunked runs rather than the loop.)\n */\nexport function isDurableBackgroundDeployEnabled(): boolean {\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const v = raw.trim().toLowerCase();\n return v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\";\n}\n\n/**\n * Single-template Netlify build: emit an async (background) function INSIDE the\n * scanned functions dir so the chat `_process-run` worker runs on Netlify's\n * 15-min async function instead of the synchronous `/*` catch-all.\n * Additive + flag-gated (see `isDurableBackgroundDeployEnabled`).\n *\n * GROUNDED IN THE REAL NETLIFY BUILD OUTPUT (verified from a local Nitro build)\n * AND THE NETLIFY DOCS DEFAULT-URL RULE:\n * - Nitro's `netlify` preset emits exactly ONE function source at\n * `.netlify/functions-internal/server/`. `server.mjs` re-exports `main.mjs`\n * and declares `export const config = { path: \"/*\", excludedPath:\n * [\"/.netlify/*\"], preferStatic: true, ... }`. The `/*` catch-all is an\n * IN-CODE Functions-API-v2 `config.path` and it ALREADY EXCLUDES\n * `/.netlify/*`.\n * - The generated `.netlify/netlify.toml` sets\n * `functionsDirectory = \".netlify/functions-internal\"`. Netlify scans EXACTLY\n * that dir; functions placed anywhere else (e.g. `.netlify/functions/`, which\n * is the BUILD OUTPUT dir where `@netlify/build` later writes the zipped\n * functions + `manifest.json`) are NEVER deployed.\n * - Every scanned function is reachable at its DEFAULT url\n * `/.netlify/functions/<name>` BY DEFAULT. A custom `config.path` REMOVES\n * that default url; declaring NO custom `config.path` KEEPS it.\n *\n * THEREFORE we:\n * 1. Emit the background function INTO the scanned dir\n * (`.netlify/functions-internal/server-agent-background/`), sharing the same\n * built `main.mjs` bundle, so Netlify discovers it and honors its config.\n * 2. Give its `export const config` `background: true` (→ async invoke,\n * immediate 202, 15-min budget) and NO custom `config.path`. With no custom\n * path the function keeps its DEFAULT url\n * `/.netlify/functions/server-agent-background`, and because the Nitro\n * `server` function's `/*` catch-all already excludes `/.netlify/*`, that\n * default-url namespace is NEVER shadowed by the synchronous function — no\n * catch-all patch is needed.\n * 3. The entry NORMALIZES/rewrites the incoming request pathname to\n * `AGENT_CHAT_PROCESS_RUN_PATH` before delegating to `./main.mjs`. The\n * function is reached at its default url\n * (`/.netlify/functions/server-agent-background`), so the Nitro router needs\n * the path rewritten to the framework `_process-run` route, preserving the\n * method, ALL headers (the HMAC `Authorization: Bearer` MUST survive), and\n * the body.\n * 4. Set `globalThis.__AGENT_NATIVE_BACKGROUND_RUNTIME__ = true` at cold start\n * (read back by `isInBackgroundFunctionRuntime()` so the worker takes the\n * ~13-min soft-timeout). A `globalThis` flag — NOT `process.env` — keeps the\n * no-env-mutation guard satisfied and carries no cross-request state.\n *\n * The foreground dispatches to this DEFAULT url on hosted Netlify\n * (`resolveAgentChatProcessRunDispatchPath` → `AGENT_BACKGROUND_FUNCTION_URL_PATH`).\n *\n * WHY THIS IS THE DOC-CORRECT FIX: a prior attempt gave the function a custom\n * `config.path` (= the framework route) plus a catch-all `excludedPath` patch.\n * The custom `config.path` was NOT honored as a route in prod — a probe of\n * `POST /_agent-native/agent-chat/_process-run` returned 404. The doc-correct\n * approach (confirmed against the Netlify docs) is to use the DEFAULT function\n * url with no custom path: the function stays reachable at\n * `/.netlify/functions/<name>` and is never shadowed because `/.netlify/*` is\n * already excluded from the `server` catch-all.\n *\n * Safety net regardless of Netlify routing nuance: if the dispatch fast-fails\n * (e.g. the function was not emitted), the foreground handler degrades to an\n * inline 40s synchronous run (see production-agent.ts).\n */\nexport function emitSingleTemplateNetlifyBackgroundFunction(\n projectCwd: string,\n): void {\n const internalDir = path.join(projectCwd, \".netlify\", \"functions-internal\");\n const serverDir = path.join(internalDir, \"server\");\n if (!fs.existsSync(path.join(serverDir, \"main.mjs\"))) {\n // Nitro output layout differs from what we expected — skip rather than\n // guess. The single-function deploy is unaffected.\n console.warn(\n \"[build] Durable-background emit skipped: expected Nitro Netlify function \" +\n \"at .netlify/functions-internal/server/main.mjs was not found.\",\n );\n return;\n }\n const backgroundName = AGENT_BACKGROUND_FUNCTION_NAME;\n // Emit INTO the SCANNED functions dir (functions-internal) so Netlify discovers\n // the function and honors its `export const config`. `.netlify/functions/` is\n // the build OUTPUT dir (where @netlify/build writes the zip + manifest) and is\n // NOT scanned — emitting there is why the standalone attempt 404'd.\n const dest = path.join(internalDir, backgroundName);\n fs.rmSync(dest, { recursive: true, force: true });\n copyDir(serverDir, dest);\n // Drop the original Nitro `/*` entry so our entry is the entrypoint and the\n // copied bundle does NOT re-register the catch-all `config.path`.\n fs.rmSync(path.join(dest, \"server.mjs\"), { force: true });\n\n const processRunPath = JSON.stringify(AGENT_CHAT_PROCESS_RUN_PATH);\n const entry = `// Mark this isolate as the durable background runtime BEFORE the handler\n// bundle is imported, so isInBackgroundFunctionRuntime() reliably returns true\n// in this function. The deployed Lambda name is NOT guaranteed to end in\n// \"-background\" (Netlify may mangle/prefix it), so we cannot depend on\n// AWS_LAMBDA_FUNCTION_NAME alone. A globalThis flag (NOT process.env) avoids the\n// no-env-mutation guard and carries no cross-request state — it is a static,\n// set-once isolate marker read back by isInBackgroundFunctionRuntime().\nglobalThis.__AGENT_NATIVE_BACKGROUND_RUNTIME__ = true;\n\n// The framework route the Nitro router dispatches to (the _process-run plugin).\nconst PROCESS_RUN_PATH = ${processRunPath};\n\nlet cachedHandler;\n\n// Netlify v2 invokes this as (request, context). The Nitro netlify handler is a\n// Web-standard \\`async (Request) => Response\\` (see nitro/presets/netlify/runtime).\n// This function declares NO custom \\`config.path\\`, so it is reached at its\n// DEFAULT url (/.netlify/functions/${backgroundName}). The Nitro router only\n// knows the framework route, so we REWRITE the incoming pathname to\n// PROCESS_RUN_PATH before delegating. Method, ALL headers (the HMAC\n// Authorization: Bearer MUST survive — the plugin verifies it) and the body are\n// preserved by cloning the incoming Request with only its URL pathname set.\nexport default async function handler(request, context) {\n try {\n cachedHandler ??= (await import(\"./main.mjs\")).default;\n const url = new URL(request.url);\n url.pathname = PROCESS_RUN_PATH;\n // Read the body once and pass it through. GET/HEAD have no body.\n const method = request.method || \"POST\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const body = hasBody ? await request.text() : undefined;\n const rewritten = new Request(url.toString(), {\n method,\n headers: request.headers,\n body,\n });\n // Netlify Functions v2 invokes the handler as (request, context); the Nitro\n // netlify handler accepts (request[, context]). Pass context through so a\n // handler that uses it (e.g. waitUntil) does not trip over an undefined arg\n // before it ever routes the request.\n return await cachedHandler(rewritten, context);\n } catch (err) {\n // Netlify already returned 202 for this background invocation and DISCARDS\n // this return, so a throw here is otherwise INVISIBLE — it would only surface\n // downstream as the reaper's \"worker never claimed the run\". Log it loudly\n // for the function log; the FOREGROUND circuit-breaker (production-agent.ts)\n // is what recovers the run by executing it inline when no worker claims.\n console.error(\n \"[agent-background] wrapper failed before reaching the route:\",\n (err && err.stack) || err,\n );\n throw err;\n }\n}\n\nexport const config = {\n name: \"agent background handler\",\n generator: \"agent-native build\",\n // background: true makes Netlify invoke this ASYNCHRONOUSLY (immediate HTTP\n // 202 ack) with the 15-minute budget (Netlify docs:\n // build/functions/background-functions + build/functions/api). We declare NO\n // custom path, so the function keeps its DEFAULT url\n // /.netlify/functions/${backgroundName}; the Nitro \\`server\\` /* catch-all\n // already excludes /.netlify/* so that default url is never shadowed by the\n // synchronous function. The foreground dispatches to that default url.\n background: true,\n nodeBundler: \"none\",\n includedFiles: [\"**\"],\n preferStatic: false,\n};\n`;\n fs.writeFileSync(path.join(dest, `${backgroundName}.mjs`), entry);\n console.log(\n `[build] Emitted durable-background function \"${backgroundName}\" into the ` +\n `scanned dir .netlify/functions-internal with config { background:true } ` +\n `and NO custom path — reachable at its default url ` +\n `/.netlify/functions/${backgroundName} (never shadowed; the server /* ` +\n `catch-all already excludes /.netlify/*). REQUIRES real-deploy ` +\n `verification of Netlify async (202) invocation — see ` +\n `docs/design/durable-agent-runs.md.`,\n );\n}\n\n/**\n * Nitro's Netlify preset can emit a harmful fallback rewrite to\n * `/.netlify/functions/server`. With `config.path: \"/*\"`, that default URL is\n * removed, so the rewrite publishes platform 404s. Single-template deploys keep\n * Nitro's `preferStatic: true` so hashed `/assets/*` files in dist win before\n * the SSR catch-all runs.\n */\nconst NETLIFY_DEFAULT_FUNCTION_URL_REDIRECT =\n \"/* /.netlify/functions/server 200\";\n\n/**\n * Resolve where the client publish output actually lives for this build.\n * Single-template builds emit hashed assets at `dist/assets`; mounted builds\n * (APP_BASE_PATH=/<app>, e.g. every app in a workspace deploy) nest the\n * client output under the base path at `dist/<app>/assets`.\n */\nfunction netlifyClientPublishDir(projectCwd: string): {\n dir: string;\n label: string;\n} {\n const baseSegments = normalizeConfiguredAppBasePath()\n .split(\"/\")\n .filter(Boolean);\n return {\n dir: path.join(projectCwd, \"dist\", ...baseSegments),\n label: [\"dist\", ...baseSegments].join(\"/\"),\n };\n}\n\nfunction hasBareYjsRuntimeImport(source: string): boolean {\n return /\\b(?:from\\s*|import\\s*\\(\\s*|import\\s*)[\"']yjs(?:\\/[^\"']*)?[\"']/.test(\n source,\n );\n}\n\nfunction hasUnsupportedYjsSubpathImport(source: string): boolean {\n return /\\b(?:from\\s*|import\\s*\\(\\s*|import\\s*)[\"']yjs\\/[^\"']*[\"']/.test(\n source,\n );\n}\n\nfunction walkServerJavaScriptFiles(\n dir: string,\n onFile: (filePath: string) => void,\n): void {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const entryPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n walkServerJavaScriptFiles(entryPath, onFile);\n continue;\n }\n if (/\\.(?:[cm]?js)$/.test(entry.name)) onFile(entryPath);\n }\n}\n\n/**\n * Nitro can preserve Vite's `yjs` external in a split server chunk even when\n * its own server build has emitted `_libs/yjs.mjs`. Netlify does not install\n * that bare package at runtime, so make every emitted server chunk use the\n * bundled copy before its function is packaged.\n */\nexport function rewriteBareYjsImportsForServerlessOutput(\n serverDir: string,\n): string[] {\n const bareImports: string[] = [];\n const unsupportedSubpathImports: string[] = [];\n const bundledYjsPath = path.join(serverDir, \"_libs\", \"yjs.mjs\");\n\n walkServerJavaScriptFiles(serverDir, (filePath) => {\n const source = fs.readFileSync(filePath, \"utf-8\");\n if (!hasBareYjsRuntimeImport(source)) return;\n if (hasUnsupportedYjsSubpathImport(source)) {\n unsupportedSubpathImports.push(filePath);\n return;\n }\n bareImports.push(filePath);\n });\n\n if (unsupportedSubpathImports.length > 0) {\n throw new Error(\n `[deploy] Serverless output left unsupported yjs subpath imports in ${unsupportedSubpathImports.join(\", \")}`,\n );\n }\n if (bareImports.length === 0) return [];\n if (!fs.existsSync(bundledYjsPath)) {\n throw new Error(\n `[deploy] Serverless output left yjs as a runtime import but did not emit ${bundledYjsPath}`,\n );\n }\n\n for (const filePath of bareImports) {\n const bundledImport = path\n .relative(path.dirname(filePath), bundledYjsPath)\n .split(path.sep)\n .join(\"/\");\n const relativeBundledImport = bundledImport.startsWith(\".\")\n ? bundledImport\n : `./${bundledImport}`;\n const source = fs.readFileSync(filePath, \"utf-8\");\n fs.writeFileSync(\n filePath,\n source.replace(\n /(\\b(?:from\\s*|import\\s*\\(\\s*|import\\s*))([\"'])yjs\\2/g,\n (_match, importPrefix: string, quote: string) =>\n `${importPrefix}${quote}${relativeBundledImport}${quote}`,\n ),\n );\n }\n\n return bareImports;\n}\n\nexport function assertSingleTemplateNetlifyBuildOutput(\n projectCwd: string,\n): void {\n const failures: string[] = [];\n const publishDir = path.join(projectCwd, \"dist\");\n const clientPublish = netlifyClientPublishDir(projectCwd);\n const internalDir = path.join(projectCwd, \".netlify\", \"functions-internal\");\n const serverDir = path.join(internalDir, \"server\");\n const serverEntryPath = path.join(serverDir, \"server.mjs\");\n const serverMainPath = path.join(serverDir, \"main.mjs\");\n\n if (!fs.existsSync(publishDir)) {\n failures.push(\"missing publish directory: dist\");\n } else {\n const assetsDir = path.join(clientPublish.dir, \"assets\");\n if (\n !fs.existsSync(assetsDir) ||\n fs.readdirSync(assetsDir).every((name) => name.startsWith(\".\"))\n ) {\n failures.push(\n `${clientPublish.label}/assets is missing hashed client assets — the publish dir would load an infinite spinner`,\n );\n }\n }\n\n // `_redirects` may sit at the dist root or (for mounted builds) inside the\n // base-path dir — reject the incompatible default-function rewrite in both.\n const redirectsCandidates = [\n path.join(publishDir, \"_redirects\"),\n path.join(clientPublish.dir, \"_redirects\"),\n ];\n for (const redirectsPath of new Set(redirectsCandidates)) {\n if (!fs.existsSync(publishDir) || !fs.existsSync(redirectsPath)) continue;\n const redirects = fs.readFileSync(redirectsPath, \"utf-8\");\n if (\n redirects\n .split(/\\r?\\n/)\n .some(\n (line) =>\n line.trim().replace(/\\s+/g, \" \") ===\n NETLIFY_DEFAULT_FUNCTION_URL_REDIRECT,\n )\n ) {\n failures.push(\n `${path.relative(projectCwd, redirectsPath).replace(/\\\\/g, \"/\")} must not contain \"/* /.netlify/functions/server 200\" — Nitro's custom config.path: \"/*\" removes that default function URL`,\n );\n }\n }\n\n if (!fs.existsSync(serverDir)) {\n failures.push(\n \"missing scanned Netlify server function: .netlify/functions-internal/server\",\n );\n }\n\n if (!fs.existsSync(serverMainPath)) {\n failures.push(\n \"missing Netlify server bundle: .netlify/functions-internal/server/main.mjs\",\n );\n }\n\n if (!fs.existsSync(serverEntryPath)) {\n failures.push(\n \"missing Netlify server entry: .netlify/functions-internal/server/server.mjs\",\n );\n } else {\n const serverEntry = fs.readFileSync(serverEntryPath, \"utf-8\");\n if (!/\\bpath\\s*:\\s*[\"']\\/\\*[\"']/.test(serverEntry)) {\n failures.push(\n 'Netlify server entry is missing the \"/*\" catch-all function path',\n );\n }\n if (!serverEntry.includes('\"/.netlify/*\"')) {\n failures.push(\n 'Netlify server catch-all is missing the \"/.netlify/*\" exclusion',\n );\n }\n if (!serverEntry.includes(\"./main.mjs\")) {\n failures.push(\n \"Netlify server entry does not reference the generated main.mjs bundle\",\n );\n }\n if (!/\\bpreferStatic:\\s*true\\b/.test(serverEntry)) {\n failures.push(\n \"Netlify server entry must keep preferStatic: true so /assets/* is served from dist before the SSR catch-all\",\n );\n }\n }\n\n // Netlify's function packager does not install arbitrary runtime package\n // imports left in Nitro chunks. A bare Yjs import here would deploy\n // successfully but fail on the first SSR request with ERR_MODULE_NOT_FOUND.\n // Keep this check adjacent to the output guard so both local builds and CI\n // reject that artifact before it reaches Netlify.\n const bareYjsImports: string[] = [];\n walkServerJavaScriptFiles(serverDir, (filePath) => {\n if (hasBareYjsRuntimeImport(fs.readFileSync(filePath, \"utf-8\"))) {\n bareYjsImports.push(path.relative(projectCwd, filePath));\n }\n });\n if (bareYjsImports.length > 0) {\n failures.push(\n `Netlify server bundle leaves yjs as a runtime import: ${bareYjsImports.join(\", \")}`,\n );\n }\n\n if (isDurableBackgroundDeployEnabled()) {\n const backgroundDir = path.join(\n internalDir,\n AGENT_BACKGROUND_FUNCTION_NAME,\n );\n const backgroundEntryPath = path.join(\n backgroundDir,\n `${AGENT_BACKGROUND_FUNCTION_NAME}.mjs`,\n );\n if (!fs.existsSync(backgroundEntryPath)) {\n failures.push(\n `durable background is enabled but ${path.relative(\n projectCwd,\n backgroundEntryPath,\n )} was not emitted`,\n );\n } else {\n const backgroundEntry = fs.readFileSync(backgroundEntryPath, \"utf-8\");\n if (!/\\bbackground\\s*:\\s*true\\b/.test(backgroundEntry)) {\n failures.push(\n `durable background entry ${path.relative(\n projectCwd,\n backgroundEntryPath,\n )} is missing background: true`,\n );\n }\n if (/^\\s*path\\s*:/m.test(backgroundEntry)) {\n failures.push(\n `durable background entry ${path.relative(\n projectCwd,\n backgroundEntryPath,\n )} must not declare a custom path`,\n );\n }\n }\n }\n\n if (failures.length > 0) {\n throw new Error(\n \"[deploy] Netlify deploy guard failed; refusing to publish an output \" +\n \"that would likely serve Netlify 404s:\\n\" +\n failures.map((failure) => `- ${failure}`).join(\"\\n\"),\n );\n }\n\n console.log(\n \"[deploy] Netlify deploy guard passed: publish dir and catch-all server function are present.\",\n );\n}\n\n/**\n * Strip the harmful single-template catch-all rewrite that points at\n * `/.netlify/functions/server`. Nitro declares `config.path: \"/*\"`, which\n * removes the default function URL, so rewriting to that URL publishes\n * Netlify platform 404s. Preserve any real redirects from `public/_redirects`.\n */\nexport function writeSingleTemplateNetlifyRedirects(projectCwd: string): void {\n const publishDir = path.join(projectCwd, \"dist\");\n const clientPublish = netlifyClientPublishDir(projectCwd);\n // `_redirects` may sit at the dist root or (for mounted builds) inside the\n // base-path dir — strip the harmful rewrite wherever it landed.\n const redirectsCandidates = new Set([\n path.join(publishDir, \"_redirects\"),\n path.join(clientPublish.dir, \"_redirects\"),\n ]);\n for (const redirectsPath of redirectsCandidates) {\n stripNetlifyDefaultFunctionRedirect(redirectsPath);\n }\n}\n\nfunction stripNetlifyDefaultFunctionRedirect(redirectsPath: string): void {\n if (!fs.existsSync(redirectsPath)) return;\n\n const existing = fs.readFileSync(redirectsPath, \"utf-8\");\n const kept: string[] = [];\n let removed = 0;\n\n for (const line of existing.split(/\\r?\\n/)) {\n const normalized = line.trim().replace(/\\s+/g, \" \");\n if (\n normalized === NETLIFY_DEFAULT_FUNCTION_URL_REDIRECT ||\n normalized ===\n \"# Generated by agent-native build for Netlify single-template deploys\" ||\n normalized ===\n \"# Static files are served first; dynamic routes fall through to the server function.\"\n ) {\n removed += 1;\n continue;\n }\n kept.push(line);\n }\n\n while (kept.length > 0 && kept[kept.length - 1].trim() === \"\") {\n kept.pop();\n }\n\n if (removed === 0) return;\n\n if (kept.every((line) => line.trim() === \"\")) {\n fs.rmSync(redirectsPath, { force: true });\n } else {\n fs.writeFileSync(redirectsPath, kept.join(\"\\n\").trimEnd() + \"\\n\");\n }\n console.log(\n '[deploy] Removed Netlify fallback rewrite to /.netlify/functions/server (incompatible with Nitro config.path: \"/*\").',\n );\n}\n\nfunction copyInstalledLibsqlNativePackages(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const nodeModulesRoots = nodeModulesAncestors(cwd);\n const destScopeDir = path.join(serverDir, \"node_modules\", \"@libsql\");\n let copied = 0;\n\n for (const packageName of LIBSQL_NATIVE_PACKAGE_NAMES) {\n const src = findInstalledLibsqlNativePackage(nodeModulesRoots, packageName);\n if (!src) continue;\n\n copyDir(src, path.join(destScopeDir, packageName));\n copied += 1;\n }\n\n if (copied > 0) {\n console.log(\n `[deploy] Copied ${copied} installed libsql native package(s) into the server bundle.`,\n );\n }\n}\n\nfunction copyInstalledResvgPackages(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const packages = findInstalledResvgPackages(nodeModulesAncestors(cwd));\n if (packages.length === 0) return;\n\n const destScopeDir = path.join(serverDir, \"node_modules\", RESVG_SCOPE);\n for (const { packageName, packageDir } of packages) {\n copyDir(packageDir, path.join(destScopeDir, packageName));\n }\n\n console.log(\n `[deploy] Copied ${packages.length} resvg package(s) into the server bundle for OG image rendering.`,\n );\n}\n\nfunction copyInstalledFfmpegStaticPackage(serverDir: string | undefined) {\n if (!serverDir || !fs.existsSync(serverDir)) return;\n const nodeModulesRoots = nodeModulesAncestors(cwd);\n if (!shouldBundleFfmpegStaticForServerless()) {\n if (hasInstalledFfmpegStaticPackage(nodeModulesRoots)) {\n console.warn(\n `[deploy] ffmpeg-static installs a ${process.platform}-${process.arch} binary, but the serverless runtime architecture is not known to match it; ` +\n \"set AGENT_NATIVE_SERVERLESS_FFMPEG_ARCH=x64 or arm64 to bundle a matching binary, otherwise server-side media transcription fallback will require FFMPEG_PATH or a system ffmpeg.\",\n );\n }\n return;\n }\n\n const src = findInstalledFfmpegStaticPackage(nodeModulesRoots);\n if (!src) {\n if (hasInstalledFfmpegStaticPackage(nodeModulesRoots)) {\n console.warn(\n \"[deploy] ffmpeg-static is installed without a downloaded ffmpeg binary; \" +\n \"server-side media transcription fallback will require FFMPEG_PATH or a system ffmpeg.\",\n );\n }\n return;\n }\n\n copyDir(\n src,\n path.join(serverDir, \"node_modules\", FFMPEG_STATIC_PACKAGE_NAME),\n );\n console.log(\n \"[deploy] Copied ffmpeg-static into the server bundle for media transcription fallback.\",\n );\n}\n\n/**\n * Nitro's file tracer can over-include optional desktop/dev packages that are\n * present in a monorepo install but cannot run in serverless. Netlify installs\n * the generated per-function package.json before upload; if `electron` remains\n * there, the function can exceed Netlify's 250 MB unzipped size limit even\n * though the server bundle never imports Electron at runtime.\n */\nexport function sanitizeServerlessFunctionPackageManifest(\n functionDir: string | undefined,\n): void {\n if (!functionDir || !fs.existsSync(functionDir)) return;\n\n const packageJsonPath = path.join(functionDir, \"package.json\");\n if (!fs.existsSync(packageJsonPath)) return;\n\n let packageJson: Record<string, unknown>;\n try {\n packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n } catch {\n return;\n }\n\n let removed = 0;\n const depFields = [\n \"dependencies\",\n \"optionalDependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n ];\n for (const field of depFields) {\n const deps = packageJson[field];\n if (!deps || typeof deps !== \"object\" || Array.isArray(deps)) continue;\n const depRecord = deps as Record<string, unknown>;\n for (const packageName of SERVERLESS_FUNCTION_PACKAGE_DENYLIST) {\n if (Object.prototype.hasOwnProperty.call(depRecord, packageName)) {\n delete depRecord[packageName];\n removed++;\n }\n }\n if (Object.keys(depRecord).length === 0) {\n delete packageJson[field];\n }\n }\n\n const nodeModulesDir = path.join(functionDir, \"node_modules\");\n for (const packageName of SERVERLESS_FUNCTION_PACKAGE_DENYLIST) {\n const packageDir = path.join(nodeModulesDir, ...packageName.split(\"/\"));\n if (fs.existsSync(packageDir)) {\n fs.rmSync(packageDir, { recursive: true, force: true });\n removed++;\n }\n }\n\n if (removed > 0) {\n fs.writeFileSync(\n packageJsonPath,\n `${JSON.stringify(packageJson, null, 2)}\\n`,\n );\n console.log(\n `[deploy] Removed ${removed} desktop-only package reference(s) from ${path.relative(cwd, functionDir)}.`,\n );\n }\n}\n\n/**\n * Create stub directories for dangling platform-specific optional dependency\n * symlinks in the pnpm store.\n *\n * pnpm's store at `node_modules/.pnpm/<pkg>@<ver>/node_modules/<pkg>/<dep>`\n * contains symlinks for ALL optional deps declared by a package, but only\n * installs the ones matching the current OS/CPU as real packages. The other\n * symlinks dangle — their targets at `.pnpm/<scope>+<pkg>@<ver>/node_modules/...`\n * don't exist.\n *\n * Nitro's `nitro:externals` plugin (via nf3 / @vercel/nft) walks\n * optionalDependencies when tracing files and calls `realpath` on them, which\n * throws ENOENT on dangling targets. This blocks builds with presets like\n * netlify / vercel / aws-lambda on macOS when packages like `libsql` declare\n * Linux-only platform variants as optional deps.\n *\n * Fix: walk `node_modules/.pnpm/` and for every dangling symlink under\n * `<pkg>/node_modules/<scope>/<dep>`, create the symlink's target as a tiny\n * stub directory containing just a valid `package.json`. The tracer can now\n * `realpath` and read the package.json without throwing — the stub is empty\n * so no binary is bundled (which is what we want: we're building from macOS,\n * the target deploy platform will install its own native binary).\n */\nfunction createDanglingOptionalDepStubs() {\n // In pnpm monorepos, the store may live at the workspace root rather than\n // in the template dir. Walk up from `cwd` to find every `.pnpm` directory.\n const pnpmRoots: string[] = [];\n let dir = cwd;\n while (true) {\n const candidate = path.join(dir, \"node_modules\", \".pnpm\");\n if (fs.existsSync(candidate)) pnpmRoots.push(candidate);\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n if (pnpmRoots.length === 0) return;\n\n let stubsCreated = 0;\n\n for (const pnpmRoot of pnpmRoots) {\n let pkgDirs: string[];\n try {\n pkgDirs = fs.readdirSync(pnpmRoot);\n } catch {\n continue;\n }\n\n for (const pkgDir of pkgDirs) {\n // e.g. `libsql@0.5.29`, `@libsql+client@0.15.15`\n const innerNm = path.join(pnpmRoot, pkgDir, \"node_modules\");\n if (!fs.existsSync(innerNm)) continue;\n\n let innerEntries: fs.Dirent[];\n try {\n innerEntries = fs.readdirSync(innerNm, { withFileTypes: true });\n } catch {\n continue;\n }\n\n for (const entry of innerEntries) {\n // Top-level entry: either `foo` (unscoped) or `@scope` (scoped)\n const entryPath = path.join(innerNm, entry.name);\n const candidates: { symlinkPath: string; pkgName: string }[] = [];\n if (entry.name.startsWith(\"@\")) {\n // Scoped — iterate children\n let scopedChildren: fs.Dirent[];\n try {\n scopedChildren = fs.readdirSync(entryPath, {\n withFileTypes: true,\n });\n } catch {\n continue;\n }\n for (const child of scopedChildren) {\n candidates.push({\n symlinkPath: path.join(entryPath, child.name),\n pkgName: `${entry.name}/${child.name}`,\n });\n }\n } else {\n candidates.push({ symlinkPath: entryPath, pkgName: entry.name });\n }\n\n for (const { symlinkPath, pkgName } of candidates) {\n let isSymlink = false;\n try {\n isSymlink = fs.lstatSync(symlinkPath).isSymbolicLink();\n } catch {\n continue;\n }\n if (!isSymlink) continue;\n\n // Check if the symlink target exists\n try {\n fs.statSync(symlinkPath);\n continue; // Target exists — nothing to do\n } catch {\n // Dangling symlink — create a stub at the target\n }\n\n let linkTarget: string;\n try {\n linkTarget = fs.readlinkSync(symlinkPath);\n } catch {\n continue;\n }\n const resolvedTarget = path.resolve(\n path.dirname(symlinkPath),\n linkTarget,\n );\n\n try {\n fs.mkdirSync(resolvedTarget, { recursive: true });\n const stubPkgJson = {\n name: pkgName,\n version: \"0.0.0-stub\",\n description:\n \"Empty stub created by @agent-native/core deploy build to satisfy nitro's file tracer on platforms where this optional dep is not installed.\",\n };\n fs.writeFileSync(\n path.join(resolvedTarget, \"package.json\"),\n JSON.stringify(stubPkgJson, null, 2),\n );\n stubsCreated++;\n } catch {\n // Best-effort — ignore failures\n }\n }\n }\n }\n }\n\n if (stubsCreated > 0) {\n console.log(\n `[deploy] Created ${stubsCreated} stub package dir(s) for dangling optional deps (platform-specific binaries not installed on this host).`,\n );\n }\n}\n\n/**\n * Build for any non-Cloudflare preset using Nitro's programmatic build API.\n * Handles netlify, vercel, deno_deploy, aws-lambda, and all other targets.\n */\nexport interface NitroBuildHooks {\n prepare: (nitro: any) => Promise<void>;\n copyPublicAssets: (nitro: any) => Promise<void>;\n nitroBuild: (nitro: any) => Promise<void>;\n}\n\nexport interface NitroBuildPipelineOptions {\n nitro: any;\n hooks: NitroBuildHooks;\n clientDir: string;\n publicOutputDir: string | undefined;\n appBasePath: string;\n cwd: string;\n}\n\n/**\n * Run Nitro's lifecycle in the order required to ship a working React Router\n * framework-mode build.\n *\n * The critical ordering constraint is that the React Router client build must\n * be copied into `publicOutputDir` *before* `nitroBuild` runs. Nitro generates\n * the static-asset manifest baked into the server bundle by globbing\n * `publicDir` during the server build; files copied in after that point exist\n * on disk but are invisible to the runtime `serveStatic` handler. Every\n * /assets/* request then falls through to the SSR catch-all, which 404s\n * anything with a file extension.\n */\nexport async function runNitroBuildPipeline(\n opts: NitroBuildPipelineOptions,\n): Promise<void> {\n const { nitro, hooks, clientDir, publicOutputDir, appBasePath, cwd } = opts;\n const hasClientBuild = fs.existsSync(clientDir) && Boolean(publicOutputDir);\n\n if (hasClientBuild) {\n // Install hashed-asset route rules before Nitro prepares platform output.\n // Some presets materialize headers during prepare/copy phases, not only in\n // nitroBuild; adding these later leaves Netlify/Vercel static assets without\n // the one-year immutable CDN policy even though the runtime manifest works.\n nitro.options.routeRules ??= {};\n addImmutableAssetRouteRulesForClientBuild(\n nitro.options.routeRules,\n clientDir,\n appBasePath,\n );\n }\n\n await hooks.prepare(nitro);\n await hooks.copyPublicAssets(nitro);\n\n if (hasClientBuild && publicOutputDir) {\n copyDir(clientDir, publicOutputDir);\n if (appBasePath) {\n copyDir(clientDir, path.join(publicOutputDir, appBasePath.slice(1)));\n }\n console.log(\n `[deploy] Copied client assets to ${path.relative(cwd, publicOutputDir)}`,\n );\n }\n\n await hooks.nitroBuild(nitro);\n}\n\n/**\n * Browser-only diagram/drawing renderers that execute `window`-touching code at\n * module-evaluation time. They are rendered exclusively client-side — core's\n * `MermaidBlock` and templates' Excalidraw slides mount them inside `useEffect` /\n * `React.lazy`, never during SSR — so the server never needs the real module.\n *\n * Keep this list to libraries that are *provably never* invoked on the server.\n * Node-only deps that DO run server-side (pdf-parse, @google/genai, canvas, …)\n * must NOT go here — see `heavyClientExternals` for the edge-worker externals.\n */\nconst BROWSER_ONLY_SERVER_LIBS = [\n \"@excalidraw/excalidraw\",\n \"@excalidraw/mermaid-to-excalidraw\",\n \"mermaid\",\n];\n\n/**\n * Dependencies that must be bundled into every Nitro server output instead of\n * being left as runtime package imports.\n *\n * `yjs` is a direct core dependency, but it is deliberately externalized from\n * the intermediate Vite SSR graph so that Vite and Nitro do not create two\n * incompatible Yjs constructors. On file-traced serverless presets, leaving it\n * external at Nitro's final build can emit `import \"yjs\"` into a function\n * chunk without placing the package in that function's `node_modules`. Bundle\n * it in Nitro's final output so every template receives the one portable copy.\n */\nexport const NITRO_SERVER_RUNTIME_BUNDLED_DEPS = [\"yjs\"] as const;\n\n/**\n * Edge runtimes have no node_modules, while Node/serverless outputs only need\n * the small set above bundled to keep their package manifests traceable.\n */\nexport function nitroNoExternalsForPreset(\n targetPreset: string,\n): true | readonly string[] {\n return targetPreset.startsWith(\"cloudflare\") ||\n targetPreset.startsWith(\"deno\")\n ? true\n : NITRO_SERVER_RUNTIME_BUNDLED_DEPS;\n}\n\n/**\n * Rolldown plugin for the Nitro server bundle that replaces the browser-only\n * renderers above with an inert proxy module.\n *\n * Why this is needed: Nitro re-bundles the server from node_modules with its own\n * Rolldown pipeline, and Rolldown merges Excalidraw into a SHARED vendor chunk\n * that the SSR render path (tiptap / radix-ui / recharts) imports *statically*.\n * That evaluates Excalidraw's top-level `window` access at function cold-start\n * and crashes every request with `ReferenceError: window is not defined` (HTTP\n * 502). The Vite SSR build already stubs these via `ssrStubPlugin` for\n * `build/server`, but that Vite plugin doesn't run during Nitro's separate\n * bundle — so mirror the same stub here.\n */\nfunction createBrowserOnlyServerStubPlugin() {\n const stubbed = new Set(BROWSER_ONLY_SERVER_LIBS);\n const STUB_ID = \"\\0agent-native-browser-only-server-stub\";\n return {\n name: \"agent-native-browser-only-server-stub\",\n // enforce: \"pre\" so we intercept before Nitro's node resolver bundles the\n // real package. defu concatenates rollupConfig.plugins ahead of Nitro's own.\n resolveId(id: string) {\n // Match the bare package name or any subpath (incl. `/index.css`).\n const pkg = id\n .split(\"/\")\n .slice(0, id.startsWith(\"@\") ? 2 : 1)\n .join(\"/\");\n return stubbed.has(pkg) ? STUB_ID : null;\n },\n load(id: string) {\n if (id !== STUB_ID) return null;\n // A Proxy answers any property access (default or named) with another\n // proxy, so every import shape resolves without evaluating real browser\n // code. It is never actually invoked on the server, so it never throws.\n return (\n \"const handler = { get(_t, p) {\" +\n \" if (p === Symbol.toPrimitive) return () => '';\" +\n \" if (p === 'then') return undefined;\" +\n \" if (p === '__esModule') return true;\" +\n \" return new Proxy(function () {}, handler); } };\" +\n \"const stub = new Proxy(function () {}, handler);\" +\n \"export default stub;\"\n );\n },\n };\n}\n\nasync function buildWithNitro() {\n console.log(`[deploy] Building for preset \"${preset}\" via Nitro...`);\n const appBasePath = normalizeConfiguredAppBasePath();\n\n // Nitro runs its own server build after the React Router/Vite build. The\n // template's agent-chat plugin imports .generated/actions-registry.ts so the\n // serverless bundle has static imports for every domain action. Regenerate\n // here as well so deploy builds are not coupled to a previous Vite run or to\n // ignored local .generated files being present.\n generateActionRegistryForProject(cwd);\n\n // Work around pnpm + nitro:externals (nf3) bug where dangling symlinks for\n // platform-specific optional deps cause realpath ENOENT during file tracing.\n createDanglingOptionalDepStubs();\n\n const {\n createNitro,\n prepare,\n copyPublicAssets,\n build: nitroBuild,\n } = await import(\"nitro/builder\");\n\n // Resolve the React Router server build so the SSR catch-all route\n // can import \"virtual:react-router/server-build\" in production.\n const rrServerBuild = path.join(cwd, \"build\", \"server\", \"index.js\");\n\n // Inline the template's AGENTS.md + .agents/skills/ content into the Nitro\n // bundle via the `virtual` config option. Nitro's internal `nitro:virtual`\n // Rollup plugin picks this up and resolves `virtual:agents-bundle` to the\n // generated ES module source. Without this, Nitro's Rolldown build (used for\n // netlify, vercel, aws-lambda, node presets) can't resolve the virtual\n // module that `server/agents-bundle.ts` imports — it silently falls through\n // to an empty bundle and the agent gets no instructions/skills at runtime.\n //\n // The Vite plugin at `vite/agents-bundle-plugin.ts` handles this for the\n // React Router client/server build (and cloudflare via esbuild rebundle),\n // but Nitro runs its OWN build from ./server/ without Vite, so it needs its\n // own virtual module registration. Both paths reuse `readAgentsBundleFromFs`\n // from `server/agents-bundle.ts` to guarantee identical content.\n const { readAgentsBundleFromFs } = await import(\"../server/agents-bundle.js\");\n // Resolve the workspace core (if present) up front so the bundle embeds\n // enterprise-wide AGENTS.md + skills alongside the template's.\n const nitroWorkspaceCore = await getWorkspaceCoreExports(cwd);\n const nitroWorkspaceSource = nitroWorkspaceCore\n ? {\n skillsDir: nitroWorkspaceCore.skillsDir,\n agentsMdPath: nitroWorkspaceCore.agentsMdPath,\n rootDir: nitroWorkspaceCore.packageDir,\n }\n : null;\n const agentsBundleModuleSource = () => {\n const bundle = readAgentsBundleFromFs(cwd, nitroWorkspaceSource);\n return `// AUTO-GENERATED by @agent-native/core deploy build (Nitro virtual)\n// Contains the inlined AGENTS.md + .agents/skills/ content from the template,\n// merged with the workspace core's AGENTS.md + skills/ when present.\nconst bundle = ${JSON.stringify(bundle)};\nexport default bundle;\n`;\n };\n\n // Path aliases used by templates (mirrors tsconfig + Vite config). Nitro\n // bundles server/ and actions/ with its own Rolldown pipeline that doesn't\n // see Vite's resolve.alias — so without this, action files that import\n // `@/foo` (= `app/foo`) end up with the literal `@/foo` specifier in the\n // serverless function output and crash at runtime with\n // \"Cannot find package '@/foo' imported from /var/task/main.mjs\".\n const appDir = path.join(cwd, \"app\");\n const sharedDir = path.join(cwd, \"shared\");\n const pathAliases: Record<string, string> = {};\n if (fs.existsSync(appDir)) pathAliases[\"@\"] = appDir;\n if (fs.existsSync(sharedDir)) pathAliases[\"@shared\"] = sharedDir;\n\n const providedPluginsNitroPlugin = await writeProvidedPluginsNitroPlugin();\n\n const nitro = await createNitro({\n rootDir: cwd,\n dev: false,\n preset,\n baseURL: appBasePath || \"/\",\n minify: true,\n serverDir: \"./server\",\n ignore: NITRO_RUNTIME_IGNORE_PATTERNS,\n alias: {\n ...pathAliases,\n ...(fs.existsSync(rrServerBuild)\n ? { \"virtual:react-router/server-build\": rrServerBuild }\n : {}),\n },\n virtual: {\n \"virtual:agents-bundle\": agentsBundleModuleSource,\n },\n replace: {\n \"process.env.AGENT_NATIVE_BUILD_GA_MEASUREMENT_ID\": JSON.stringify(\n process.env.GA_MEASUREMENT_ID?.trim() || \"\",\n ),\n },\n // Replace browser-only renderers (Excalidraw/Mermaid) with an inert proxy in\n // the server bundle. Without this, Nitro's Rolldown build pulls the real\n // Excalidraw into a shared vendor chunk imported statically by the SSR render\n // path, and its top-level `window` access crashes the function at cold-start\n // (ReferenceError: window is not defined → every request 502s). Mirrors the\n // Vite `ssrStubPlugin`, which only covers the `build/server` step.\n rollupConfig: {\n plugins: [createBrowserOnlyServerStubPlugin()],\n },\n ...(providedPluginsNitroPlugin\n ? { plugins: [providedPluginsNitroPlugin] }\n : {}),\n routeRules: mcpEmbedStaticAssetRouteRules(appBasePath),\n // Edge presets (cloudflare, deno) bundle all deps because node_modules are\n // unavailable at runtime. Node/serverless presets also bundle Yjs: Nitro's\n // file tracer otherwise leaves a bare import that Netlify function bundles\n // cannot resolve under pnpm.\n noExternals: nitroNoExternalsForPreset(preset),\n } as any);\n\n await runNitroBuildPipeline({\n nitro,\n hooks: { prepare, copyPublicAssets, nitroBuild },\n clientDir: path.join(cwd, \"build\", \"client\"),\n publicOutputDir: nitro.options.output.publicDir,\n appBasePath,\n cwd,\n });\n\n if (preset === \"netlify\" || preset === \"vercel\" || preset === \"aws-lambda\") {\n copyInstalledLibsqlNativePackages(nitro.options.output.serverDir);\n copyInstalledResvgPackages(nitro.options.output.serverDir);\n copyInstalledFfmpegStaticPackage(nitro.options.output.serverDir);\n sanitizeServerlessFunctionPackageManifest(nitro.options.output.serverDir);\n rewriteBareYjsImportsForServerlessOutput(nitro.options.output.serverDir);\n }\n\n // Durable background agent runs (default-OFF / opt-in; enable with a truthy\n // AGENT_CHAT_DURABLE_BACKGROUND). Additive ONLY: emits a SECOND Netlify\n // function whose name ends in `-background` re-exporting the same handler\n // bundle, so the chat `_process-run` POST lands on Netlify's async (15-min)\n // function. When not opted in this is a no-op and the single-function\n // deploy is byte-for-byte unchanged.\n if (preset === \"netlify\" && isDurableBackgroundDeployEnabled()) {\n try {\n emitSingleTemplateNetlifyBackgroundFunction(cwd);\n } catch (err) {\n console.warn(\n \"[build] Failed to emit durable-background Netlify function (non-fatal):\",\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n if (preset === \"netlify\") {\n writeSingleTemplateNetlifyRedirects(cwd);\n assertSingleTemplateNetlifyBuildOutput(cwd);\n }\n\n // Resolve remaining bare npm imports by bundling them into _libs/.\n // Nitro sometimes leaves small packages as externals even with noExternals.\n if (preset.startsWith(\"cloudflare\") || preset.startsWith(\"deno\")) {\n const { execFileSync } = await import(\"child_process\");\n const { createRequire } = await import(\"module\");\n const esbuildBin = (() => {\n try {\n const _req = createRequire(cwd + \"/\");\n const pkg = path.dirname(_req.resolve(\"esbuild/package.json\"));\n const bin = path.join(pkg, \"bin\", \"esbuild\");\n if (fs.existsSync(bin)) return bin;\n } catch {}\n return \"esbuild\";\n })();\n\n // Scan all output files for bare npm imports\n const outputDir =\n nitro.options.output.serverDir || path.join(cwd, \"dist\", \"_worker.js\");\n const bareImports = new Set<string>();\n function scanForBareImports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n scanForBareImports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n const code = fs.readFileSync(p, \"utf-8\");\n const matches = code.matchAll(/from\\s*[\"']([a-z@][a-z0-9._\\-/]*)[\"']/g);\n for (const m of matches) {\n const mod = m[1];\n if (mod.startsWith(\"node:\")) continue;\n // Skip Node builtins that are available via nodejs_compat\n const builtins = new Set([\n \"fs\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"url\",\n \"util\",\n \"events\",\n \"buffer\",\n \"console\",\n \"net\",\n \"tls\",\n \"assert\",\n \"timers\",\n \"child_process\",\n \"module\",\n \"process\",\n \"sqlite\",\n \"worker_threads\",\n \"querystring\",\n \"zlib\",\n \"vm\",\n \"string_decoder\",\n \"diagnostics_channel\",\n \"async_hooks\",\n \"perf_hooks\",\n \"inspector\",\n ]);\n if (builtins.has(mod)) continue;\n bareImports.add(mod);\n }\n }\n }\n scanForBareImports(outputDir);\n\n // For each bare import, try to bundle it as a standalone module\n if (bareImports.size > 0) {\n const libsDir = path.join(outputDir, \"_libs\");\n fs.mkdirSync(libsDir, { recursive: true });\n for (const mod of bareImports) {\n const outFile = path.join(libsDir, `${mod.replace(/[/@]/g, \"_\")}.mjs`);\n try {\n // Resolve the module — check workspace node_modules and pnpm store\n let resolvedMod = mod;\n const _require = createRequire(cwd + \"/\");\n try {\n const resolved = _require.resolve(mod);\n resolvedMod = resolved;\n } catch {\n // Try from workspace root\n try {\n const wsRequire = createRequire(\n path.resolve(cwd, \"../../package.json\"),\n );\n resolvedMod = wsRequire.resolve(mod);\n } catch {\n // Will fail at esbuild\n }\n }\n // Scan what named imports the consumer expects, then generate\n // explicit re-exports to handle CJS modules properly.\n const neededExports = new Set<string>();\n function findNeededExports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n findNeededExports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n const code = fs.readFileSync(p, \"utf-8\");\n // Match: import{foo as bar,baz}from\"<mod>\"\n const escaped = mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const re = new RegExp(\n `import\\\\{([^}]+)\\\\}from[\"']${escaped}[\"']`,\n \"g\",\n );\n for (const m2 of code.matchAll(re)) {\n for (const part of m2[1].split(\",\")) {\n const name = part\n .trim()\n .split(/\\s+as\\s+/)[0]\n .trim();\n if (name && /^[a-zA-Z_$]/.test(name)) neededExports.add(name);\n }\n }\n }\n }\n findNeededExports(outputDir);\n\n const entryCode =\n neededExports.size > 0\n ? [\n `import _mod from \"${resolvedMod}\";`,\n `export default _mod;`,\n ...Array.from(neededExports).map(\n (n) =>\n `export const ${n} = _mod.${n} ?? _mod?.default?.${n};`,\n ),\n ].join(\"\\n\")\n : `export * from \"${resolvedMod}\"; export { default } from \"${resolvedMod}\";`;\n\n const libEsbuildCommand = esbuildSpawnCommand(esbuildBin, [\n \"--bundle\",\n `--outfile=${outFile}`,\n \"--format=esm\",\n \"--platform=neutral\",\n \"--target=es2022\",\n \"--external:node:*\",\n ]);\n execFileSync(libEsbuildCommand.file, libEsbuildCommand.args, {\n input: entryCode,\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n // Rewrite imports in all files to point to the bundled module\n function rewriteImports(dir: string) {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const p = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n rewriteImports(p);\n continue;\n }\n if (!entry.name.endsWith(\".mjs\") && !entry.name.endsWith(\".js\"))\n continue;\n let code = fs.readFileSync(p, \"utf-8\");\n const relPath = path\n .relative(path.dirname(p), outFile)\n .replace(/\\\\/g, \"/\");\n const importPath = relPath.startsWith(\".\")\n ? relPath\n : \"./\" + relPath;\n const re = new RegExp(\n `from[\"']${mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}[\"']`,\n \"g\",\n );\n if (re.test(code)) {\n code = code.replace(re, `from\"${importPath}\"`);\n fs.writeFileSync(p, code);\n }\n }\n }\n rewriteImports(outputDir);\n console.log(`[deploy] Bundled external: ${mod}`);\n } catch {\n console.warn(\n `[deploy] Could not bundle: ${mod} (may not be needed at runtime)`,\n );\n }\n }\n }\n }\n\n // Cloudflare-specific post-build patches\n if (preset.startsWith(\"cloudflare\")) {\n const serverDir2 = nitro.options.output.serverDir;\n const scanDirs = [serverDir2];\n if (serverDir2) {\n const chunksDir = path.join(serverDir2, \"_chunks\");\n const libsDir = path.join(serverDir2, \"_libs\");\n if (fs.existsSync(chunksDir)) scanDirs.push(chunksDir);\n if (fs.existsSync(libsDir)) scanDirs.push(libsDir);\n }\n\n for (const scanDir of scanDirs) {\n if (!scanDir || !fs.existsSync(scanDir)) continue;\n for (const file of fs.readdirSync(scanDir)) {\n if (!file.endsWith(\".mjs\") && !file.endsWith(\".js\")) continue;\n const filePath = path.join(scanDir, file);\n let code = fs.readFileSync(filePath, \"utf-8\");\n let changed = false;\n\n // 1. Rewrite bare Node.js imports to node: prefixed.\n // CF Workers requires the node: prefix for built-in modules.\n const NODE_BUILTINS = [\n \"fs\",\n \"path\",\n \"os\",\n \"crypto\",\n \"http\",\n \"https\",\n \"stream\",\n \"url\",\n \"util\",\n \"events\",\n \"buffer\",\n \"console\",\n \"querystring\",\n \"zlib\",\n \"net\",\n \"tls\",\n \"assert\",\n \"timers\",\n \"child_process\",\n \"module\",\n \"process\",\n \"sqlite\",\n \"worker_threads\",\n \"string_decoder\",\n \"diagnostics_channel\",\n \"async_hooks\",\n \"perf_hooks\",\n \"inspector\",\n \"vm\",\n ];\n for (const mod of NODE_BUILTINS) {\n // Match: from\"fs\" or from \"fs\" (but not from\"node:fs\")\n const re = new RegExp(`from\\\\s*[\"']${mod}[\"']`, \"g\");\n if (re.test(code)) {\n code = code.replace(re, `from\"node:${mod}\"`);\n changed = true;\n }\n }\n\n // 2. Patch import.meta.url for createRequire().\n // React Router's server build uses createRequire(import.meta.url)\n // but import.meta.url is undefined on CF Workers.\n if (code.includes(\"import.meta.url\")) {\n code = code.replace(/import\\.meta\\.url/g, '\"file:///worker.mjs\"');\n changed = true;\n }\n\n // 3. Patch setInterval/setTimeout at global scope.\n // CF Workers disallows timers in global scope.\n if (code.includes(\"setInterval\") && !code.includes(\"__timer_shim__\")) {\n const shim =\n \"/* __timer_shim__ */\" +\n \"var __origSetInterval=globalThis.setInterval;\" +\n \"globalThis.setInterval=function(){return{unref(){},ref(){},close(){}}};\";\n const restore =\n \";(function(){if(typeof __origSetInterval!=='undefined')globalThis.setInterval=__origSetInterval})();\";\n code = shim + code + \"\\n\" + restore;\n changed = true;\n }\n\n if (changed) fs.writeFileSync(filePath, code);\n }\n }\n // 3. Create stub modules in _libs/ for native deps that Nitro's rolldown\n // bundler references but can't resolve on CF Workers, and rewrite\n // bare imports to point to the stub files.\n const libsDir2 = path.join(\n serverDir2 || path.join(cwd, \"dist\", \"_worker.js\"),\n \"_libs\",\n );\n if (fs.existsSync(libsDir2)) {\n const NATIVE_STUBS = [\"better-sqlite3\", \"node-pty\", \"cron-parser\"];\n for (const mod of NATIVE_STUBS) {\n const libFiles = fs\n .readdirSync(libsDir2)\n .filter((f) => f.endsWith(\".mjs\"));\n const referencingFiles: string[] = [];\n for (const f of libFiles) {\n const filePath = path.join(libsDir2, f);\n const content = fs.readFileSync(filePath, \"utf-8\");\n if (content.includes(`\"${mod}\"`) || content.includes(`'${mod}'`)) {\n referencingFiles.push(filePath);\n }\n }\n if (referencingFiles.length === 0) continue;\n\n // Create a stub _libs/<mod>.mjs that exports empty defaults\n const stubName = mod.replace(/[/@]/g, \"__\") + \".mjs\";\n const stubPath = path.join(libsDir2, stubName);\n if (!fs.existsSync(stubPath)) {\n fs.writeFileSync(\n stubPath,\n `export default {}; export const watch = () => ({ close() {} });\\n`,\n );\n console.log(`[deploy] Created stub for _libs/${stubName}`);\n }\n\n // Rewrite bare imports in _libs/ and _chunks/ to use the stub\n const escaped = mod.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const importRe = new RegExp(`(from\\\\s*[\"'])${escaped}([\"'])`, \"g\");\n // Scan _libs/ files\n for (const filePath of referencingFiles) {\n let code = fs.readFileSync(filePath, \"utf-8\");\n if (importRe.test(code)) {\n code = code.replace(importRe, `$1./${stubName}$2`);\n fs.writeFileSync(filePath, code);\n console.log(\n `[deploy] Rewrote ${mod} imports in _libs/${path.basename(filePath)}`,\n );\n }\n }\n // Also scan _chunks/ files (they import native deps too)\n const chunksDir2 = path.join(\n serverDir2 || path.join(cwd, \"dist\", \"_worker.js\"),\n \"_chunks\",\n );\n if (fs.existsSync(chunksDir2)) {\n for (const f of fs\n .readdirSync(chunksDir2)\n .filter((f) => f.endsWith(\".mjs\") || f.endsWith(\".js\"))) {\n const filePath = path.join(chunksDir2, f);\n let code = fs.readFileSync(filePath, \"utf-8\");\n if (importRe.test(code)) {\n // From _chunks/, the stub is at ../_libs/<stubName>\n code = code.replace(importRe, `$1../_libs/${stubName}$2`);\n fs.writeFileSync(filePath, code);\n console.log(`[deploy] Rewrote ${mod} imports in _chunks/${f}`);\n }\n }\n }\n }\n }\n\n console.log(\n \"[deploy] Patched bare Node imports, timer calls, and route finder for CF Workers\",\n );\n }\n\n await nitro.close();\n console.log(`[deploy] Nitro build complete for preset \"${preset}\".`);\n}\n\nasync function main() {\n console.log(`[deploy] Building for ${preset}...`);\n\n // Sweep stale .deploy-tmp before anything writes into it. A crashed prior\n // build (any preset) leaves partial artifacts behind; both build paths\n // mkdirSync over the dir without clearing it, and the stale contents can\n // silently poison the next build (observed: an interrupted node-preset\n // build made the following cloudflare_pages build fail with no error\n // output). Fresh tmp every run is the invariant.\n fs.rmSync(path.join(cwd, \".deploy-tmp\"), { recursive: true, force: true });\n\n switch (preset) {\n case \"cloudflare_pages\":\n case \"cloudflare-pages\":\n // Cloudflare Workers require a single-file bundle that wrangler can deploy.\n // Nitro's native presets produce split chunks that wrangler can't upload\n // as multi-module Workers. Use the custom esbuild-based bundler.\n await buildCloudflarePages();\n break;\n default:\n // All other presets (netlify, vercel, deno_deploy, aws-lambda, etc.)\n // are handled natively by Nitro's build API.\n await buildWithNitro();\n break;\n }\n}\n\nif (\n process.argv[1] &&\n path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))\n) {\n await main();\n}\n"]}
|