nukejs 0.0.4 → 0.0.5

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.
@@ -9,7 +9,7 @@
9
9
  * — collection : collectServerPages, collectGlobalClientRegistry
10
10
  * — template codegen : makeApiAdapterSource, makePageAdapterSource
11
11
  * — bundle operations : bundleApiHandler, bundlePageHandler,
12
- * bundleClientComponents, buildReactBundle, buildNukeBundle
12
+ * bundleClientComponents, buildCombinedBundle
13
13
  */
14
14
  export interface AnalyzedRoute {
15
15
  srcRegex: string;
@@ -160,16 +160,19 @@ export declare function bundlePageHandler(opts: PageBundleOptions): Promise<stri
160
160
  */
161
161
  export declare function bundleClientComponents(globalRegistry: Map<string, string>, pagesDir: string, staticDir: string): Promise<Map<string, string>>;
162
162
  /**
163
- * Builds the full React + ReactDOM browser bundle to `<staticDir>/__react.js`.
164
- * Exports every public hook and helper so client component bundles can import
165
- * them via the importmap without bundling React a second time.
166
- */
167
- export declare function buildReactBundle(staticDir: string): Promise<void>;
168
- /**
169
- * Builds the nukejs client runtime to `<staticDir>/__n.js`.
170
- * React and react-dom/client are kept external (resolved via importmap).
163
+ * Builds a single combined browser bundle to `<staticDir>/__n.js`.
164
+ *
165
+ * Inlines the full React + ReactDOM runtime together with the NukeJS client
166
+ * runtime (bundle.ts) so the browser only needs one file instead of two.
167
+ * The importmap in every page points 'react', 'react-dom/client',
168
+ * 'react/jsx-runtime', and 'nukejs' all to /__n.js, so dynamic imports
169
+ * inside the runtime (e.g. `await import('react')`) hit the module cache
170
+ * and return the same singleton that was already loaded.
171
+ *
172
+ * Dev mode (bundler.ts) keeps separate /__react.js and /__n.js files for
173
+ * easier debugging — this function is production-only.
171
174
  */
172
- export declare function buildNukeBundle(staticDir: string): Promise<void>;
175
+ export declare function buildCombinedBundle(staticDir: string): Promise<void>;
173
176
  /**
174
177
  * Recursively copies every file from `app/public/` into `destDir`,
175
178
  * preserving the directory structure.
@@ -445,10 +445,14 @@ export default async function handler(req: IncomingMessage, res: ServerResponse)
445
445
  ' <meta charset="utf-8" />',
446
446
  ' <meta name="viewport" content="width=device-width, initial-scale=1" />',
447
447
  \` <title>\${escapeHtml(pageTitle)}</title>\`,
448
- ...store.meta.map(renderMetaTag),
449
- ...store.link.map(renderLinkTag),
450
- ...store.style.map(renderStyleTag),
451
- ...store.script.map(renderScriptTag),
448
+ ...(store.meta.length || store.link.length || store.style.length || store.script.length ? [
449
+ ' <!--n-head-->',
450
+ ...store.meta.map(renderMetaTag),
451
+ ...store.link.map(renderLinkTag),
452
+ ...store.style.map(renderStyleTag),
453
+ ...store.script.map(renderScriptTag),
454
+ ' <!--/n-head-->',
455
+ ] : []),
452
456
  ];
453
457
 
454
458
  const runtimeData = JSON.stringify({
@@ -472,9 +476,9 @@ export default async function handler(req: IncomingMessage, res: ServerResponse)
472
476
  <script type="importmap">
473
477
  {
474
478
  "imports": {
475
- "react": "/__react.js",
476
- "react-dom/client": "/__react.js",
477
- "react/jsx-runtime": "/__react.js",
479
+ "react": "/__n.js",
480
+ "react-dom/client": "/__n.js",
481
+ "react/jsx-runtime": "/__n.js",
478
482
  "nukejs": "/__n.js"
479
483
  }
480
484
  }
@@ -640,7 +644,9 @@ async function bundleClientComponents(globalRegistry, pagesDir, staticDir) {
640
644
  console.log(` bundled ${globalRegistry.size} client component(s) \u2192 ${path.relative(process.cwd(), outDir)}/`);
641
645
  return prerendered;
642
646
  }
643
- async function buildReactBundle(staticDir) {
647
+ async function buildCombinedBundle(staticDir) {
648
+ const nukeDir = path.dirname(fileURLToPath(import.meta.url));
649
+ const bundleFile = nukeDir.endsWith("dist") ? "bundle" : "bundle.ts";
644
650
  const result = await build({
645
651
  stdin: {
646
652
  contents: `
@@ -653,6 +659,7 @@ import React, {
653
659
  } from 'react';
654
660
  import { jsx, jsxs } from 'react/jsx-runtime';
655
661
  import { hydrateRoot, createRoot } from 'react-dom/client';
662
+ export { initRuntime, setupLocationChangeMonitor } from "./${bundleFile}.js";
656
663
 
657
664
  export {
658
665
  useState, useEffect, useContext, useReducer, useCallback, useMemo,
@@ -664,7 +671,8 @@ export {
664
671
  };
665
672
  export default React;
666
673
  `,
667
- loader: "ts"
674
+ loader: "ts",
675
+ resolveDir: nukeDir
668
676
  },
669
677
  bundle: true,
670
678
  write: false,
@@ -678,21 +686,8 @@ export default React;
678
686
  },
679
687
  define: { "process.env.NODE_ENV": '"production"' }
680
688
  });
681
- fs.writeFileSync(path.join(staticDir, "__react.js"), result.outputFiles[0].text);
682
- console.log(" built __react.js");
683
- }
684
- async function buildNukeBundle(staticDir) {
685
- const nukeDir = path.dirname(fileURLToPath(import.meta.url));
686
- const result = await build({
687
- entryPoints: [path.join(nukeDir, "bundle.js")],
688
- bundle: true,
689
- write: false,
690
- format: "esm",
691
- minify: true,
692
- external: ["react", "react-dom/client"]
693
- });
694
689
  fs.writeFileSync(path.join(staticDir, "__n.js"), result.outputFiles[0].text);
695
- console.log(" built __n.js");
690
+ console.log(" built __n.js (react + runtime)");
696
691
  }
697
692
  function copyPublicFiles(publicDir, destDir) {
698
693
  if (!fs.existsSync(publicDir)) return;
@@ -716,10 +711,9 @@ function copyPublicFiles(publicDir, destDir) {
716
711
  }
717
712
  export {
718
713
  analyzeFile,
719
- buildNukeBundle,
714
+ buildCombinedBundle,
720
715
  buildPages,
721
716
  buildPerPageRegistry,
722
- buildReactBundle,
723
717
  bundleApiHandler,
724
718
  bundleClientComponents,
725
719
  bundlePageHandler,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/build-common.ts"],
4
- "sourcesContent": ["/**\r\n * build-common.ts\r\n *\r\n * Shared build logic used by both build-vercel.ts and build-node.ts.\r\n *\r\n * Exports:\r\n * \u2014 utility helpers : walkFiles, analyzeFile, isServerComponent,\r\n * findPageLayouts, extractDefaultExportName\r\n * \u2014 collection : collectServerPages, collectGlobalClientRegistry\r\n * \u2014 template codegen : makeApiAdapterSource, makePageAdapterSource\r\n * \u2014 bundle operations : bundleApiHandler, bundlePageHandler,\r\n * bundleClientComponents, buildReactBundle, buildNukeBundle\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport crypto from 'crypto';\r\nimport { fileURLToPath, pathToFileURL } from 'url';\r\nimport { build } from 'esbuild';\r\nimport { findClientComponentsInTree } from './component-analyzer';\r\n\r\n// \u2500\u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport interface AnalyzedRoute {\r\n srcRegex: string;\r\n paramNames: string[];\r\n /** Path used as function namespace, e.g. '/api/users' or '/page/about'. */\r\n funcPath: string;\r\n specificity: number;\r\n}\r\n\r\nexport interface ServerPage extends AnalyzedRoute {\r\n absPath: string;\r\n}\r\n\r\n/** A server page together with its fully bundled ESM text, ready to emit. */\r\nexport interface BuiltPage extends ServerPage {\r\n bundleText: string;\r\n}\r\n\r\n// \u2500\u2500\u2500 File walker \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport function walkFiles(dir: string, base: string = dir): string[] {\r\n if (!fs.existsSync(dir)) return [];\r\n const results: string[] = [];\r\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\r\n const full = path.join(dir, entry.name);\r\n if (entry.isDirectory()) {\r\n results.push(...walkFiles(full, base));\r\n } else if (entry.name.endsWith('.ts') || entry.name.endsWith('.tsx')) {\r\n results.push(path.relative(base, full));\r\n }\r\n }\r\n return results;\r\n}\r\n\r\n// \u2500\u2500\u2500 Route analysis \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Parses dynamic-route segments from a relative file path and returns a regex,\r\n * captured param names, a function path, and a specificity score.\r\n *\r\n * @param relPath Relative path from the dir root (e.g. 'users/[id].tsx').\r\n * @param prefix Namespace for funcPath ('api' | 'page').\r\n */\r\nexport function analyzeFile(relPath: string, prefix = 'api'): AnalyzedRoute {\r\n const normalized = relPath.replace(/\\\\/g, '/').replace(/\\.(tsx?)$/, '');\r\n let segments = normalized.split('/');\r\n if (segments.at(-1) === 'index') segments = segments.slice(0, -1);\r\n\r\n const paramNames: string[] = [];\r\n const regexParts: string[] = [];\r\n let specificity = 0;\r\n\r\n for (const seg of segments) {\r\n const optCatchAll = seg.match(/^\\[\\[\\.\\.\\.(.+)\\]\\]$/);\r\n if (optCatchAll) { paramNames.push(optCatchAll[1]); regexParts.push('(.*)'); specificity += 1; continue; }\r\n const catchAll = seg.match(/^\\[\\.\\.\\.(.+)\\]$/);\r\n if (catchAll) { paramNames.push(catchAll[1]); regexParts.push('(.+)'); specificity += 10; continue; }\r\n const dynamic = seg.match(/^\\[(.+)\\]$/);\r\n if (dynamic) { paramNames.push(dynamic[1]); regexParts.push('([^/]+)'); specificity += 100; continue; }\r\n regexParts.push(seg.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'));\r\n specificity += 1000;\r\n }\r\n\r\n const srcRegex = segments.length === 0\r\n ? '^/$'\r\n : '^/' + regexParts.join('/') + '$';\r\n\r\n const funcSegments = normalized.split('/');\r\n if (funcSegments.at(-1) === 'index') funcSegments.pop();\r\n const funcPath = funcSegments.length === 0\r\n ? `/${prefix}/_index`\r\n : `/${prefix}/` + funcSegments.join('/');\r\n\r\n return { srcRegex, paramNames, funcPath, specificity };\r\n}\r\n\r\n// \u2500\u2500\u2500 Server-component detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Returns true when a file does NOT begin with a \"use client\" directive \u2014\r\n * i.e. it is a server component.\r\n */\r\nexport function isServerComponent(filePath: string): boolean {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n for (const line of content.split('\\n').slice(0, 5)) {\r\n const trimmed = line.trim();\r\n if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('/*')) continue;\r\n if (/^[\"']use client[\"'];?$/.test(trimmed)) return false;\r\n break;\r\n }\r\n return true;\r\n}\r\n\r\n// \u2500\u2500\u2500 Layout discovery \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Walks from the pages root to the directory containing `routeFilePath` and\r\n * returns every layout.tsx found, in outermost-first order.\r\n */\r\nexport function findPageLayouts(routeFilePath: string, pagesDir: string): string[] {\r\n const layouts: string[] = [];\r\n\r\n const rootLayout = path.join(pagesDir, 'layout.tsx');\r\n if (fs.existsSync(rootLayout)) layouts.push(rootLayout);\r\n\r\n const relativePath = path.relative(pagesDir, path.dirname(routeFilePath));\r\n if (!relativePath || relativePath === '.') return layouts;\r\n\r\n const segments = relativePath.split(path.sep).filter(Boolean);\r\n for (let i = 1; i <= segments.length; i++) {\r\n const layoutPath = path.join(pagesDir, ...segments.slice(0, i), 'layout.tsx');\r\n if (fs.existsSync(layoutPath)) layouts.push(layoutPath);\r\n }\r\n\r\n return layouts;\r\n}\r\n\r\n/**\r\n * Extracts the identifier used as the default export from a component file.\r\n * Returns null when no default export is found.\r\n */\r\nexport function extractDefaultExportName(filePath: string): string | null {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const match = content.match(/export\\s+default\\s+(?:function\\s+)?(\\w+)/);\r\n return match?.[1] ?? null;\r\n}\r\n\r\n// \u2500\u2500\u2500 Server page collection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Returns all server-component pages inside `pagesDir`, sorted by specificity\r\n * (most-specific first so more-precise routes shadow catch-alls in routers).\r\n * layout.tsx files and \"use client\" files are excluded.\r\n */\r\nexport function collectServerPages(pagesDir: string): ServerPage[] {\r\n if (!fs.existsSync(pagesDir)) return [];\r\n return walkFiles(pagesDir)\r\n .filter(relPath => {\r\n const base = path.basename(relPath, path.extname(relPath));\r\n if (base === 'layout') return false;\r\n return isServerComponent(path.join(pagesDir, relPath));\r\n })\r\n .map(relPath => ({\r\n ...analyzeFile(relPath, 'page'),\r\n absPath: path.join(pagesDir, relPath),\r\n }))\r\n .sort((a, b) => b.specificity - a.specificity);\r\n}\r\n\r\n/**\r\n * Walks every server page and its layout chain to collect all client component\r\n * IDs reachable anywhere in the app. Deduplication is automatic because the\r\n * Map key is the stable content-hash ID produced by component-analyzer.ts.\r\n */\r\nexport function collectGlobalClientRegistry(\r\n serverPages: ServerPage[],\r\n pagesDir: string,\r\n): Map<string, string> {\r\n const registry = new Map<string, string>(); // id \u2192 absFilePath\r\n for (const { absPath } of serverPages) {\r\n for (const [id, p] of findClientComponentsInTree(absPath, pagesDir)) {\r\n registry.set(id, p);\r\n }\r\n for (const layoutPath of findPageLayouts(absPath, pagesDir)) {\r\n for (const [id, p] of findClientComponentsInTree(layoutPath, pagesDir)) {\r\n registry.set(id, p);\r\n }\r\n }\r\n }\r\n return registry;\r\n}\r\n\r\n// \u2500\u2500\u2500 Per-page registry helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Builds the per-page client component registry (page + its layout chain) and\r\n * returns both the id\u2192path map and the name\u2192id map needed by bundlePageHandler.\r\n *\r\n * Extracted here to eliminate the identical loop duplicated across\r\n * build-node.ts and build-vercel.ts.\r\n */\r\nexport function buildPerPageRegistry(\r\n absPath: string,\r\n layoutPaths: string[],\r\n pagesDir: string,\r\n): { registry: Map<string, string>; clientComponentNames: Record<string, string> } {\r\n const registry = new Map<string, string>();\r\n\r\n for (const [id, p] of findClientComponentsInTree(absPath, pagesDir)) {\r\n registry.set(id, p);\r\n }\r\n for (const lp of layoutPaths) {\r\n for (const [id, p] of findClientComponentsInTree(lp, pagesDir)) {\r\n registry.set(id, p);\r\n }\r\n }\r\n\r\n const clientComponentNames: Record<string, string> = {};\r\n for (const [id, filePath] of registry) {\r\n const name = extractDefaultExportName(filePath);\r\n if (name) clientComponentNames[name] = id;\r\n }\r\n\r\n return { registry, clientComponentNames };\r\n}\r\n\r\n// \u2500\u2500\u2500 High-level page builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Runs both passes of the page build:\r\n *\r\n * Pass 1 \u2014 bundles all client components to `staticDir/__client-component/`\r\n * and collects pre-rendered HTML for each.\r\n * Pass 2 \u2014 bundles every server-component page into a self-contained ESM\r\n * handler and returns the results as `BuiltPage[]`.\r\n *\r\n * Callers (build-node, build-vercel) only need to write the bundled text to\r\n * their respective output destinations \u2014 the format-specific logic stays local.\r\n *\r\n * Returns an empty array when there are no server pages.\r\n */\r\nexport async function buildPages(\r\n pagesDir: string,\r\n staticDir: string,\r\n): Promise<BuiltPage[]> {\r\n const serverPages = collectServerPages(pagesDir);\r\n\r\n if (fs.existsSync(pagesDir) && walkFiles(pagesDir).length > 0 && serverPages.length === 0) {\r\n console.warn(`\u26A0 Pages found in ${pagesDir} but none are server components`);\r\n }\r\n\r\n if (serverPages.length === 0) return [];\r\n\r\n // Pass 1 \u2014 bundle all client components to static files.\r\n const globalClientRegistry = collectGlobalClientRegistry(serverPages, pagesDir);\r\n const prerenderedHtml = await bundleClientComponents(globalClientRegistry, pagesDir, staticDir);\r\n const prerenderedHtmlRecord = Object.fromEntries(prerenderedHtml);\r\n\r\n // Pass 2 \u2014 bundle each server-component page.\r\n const builtPages: BuiltPage[] = [];\r\n\r\n for (const page of serverPages) {\r\n const { funcPath, absPath } = page;\r\n console.log(` building ${fs.existsSync(absPath) ? absPath : absPath} \u2192 ${funcPath} [page]`);\r\n\r\n const layoutPaths = findPageLayouts(absPath, pagesDir);\r\n const { registry, clientComponentNames } = buildPerPageRegistry(absPath, layoutPaths, pagesDir);\r\n\r\n const bundleText = await bundlePageHandler({\r\n absPath,\r\n pagesDir,\r\n clientComponentNames,\r\n allClientIds: [...registry.keys()],\r\n layoutPaths,\r\n prerenderedHtml: prerenderedHtmlRecord,\r\n });\r\n\r\n builtPages.push({ ...page, bundleText });\r\n }\r\n\r\n return builtPages;\r\n}\r\n\r\n// \u2500\u2500\u2500 API adapter template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Returns the TypeScript source for a thin HTTP adapter that wraps an API\r\n * route module and exposes a single `handler(req, res)` default export.\r\n *\r\n * @param handlerFilename Basename of the handler file relative to the adapter\r\n * (e.g. 'users.ts'). Must be in the same directory.\r\n */\r\nexport function makeApiAdapterSource(handlerFilename: string): string {\r\n return `\r\nimport type { IncomingMessage, ServerResponse } from 'http';\r\nimport * as mod from ${JSON.stringify('./' + handlerFilename)};\r\n\r\nfunction enhance(res: ServerResponse) {\r\n (res as any).json = function (data: any, status = 200) {\r\n this.statusCode = status;\r\n this.setHeader('Content-Type', 'application/json');\r\n this.end(JSON.stringify(data));\r\n };\r\n (res as any).status = function (code: number) { this.statusCode = code; return this; };\r\n return res;\r\n}\r\n\r\nasync function parseBody(req: IncomingMessage): Promise<any> {\r\n return new Promise((resolve, reject) => {\r\n let body = '';\r\n req.on('data', chunk => { body += chunk.toString(); });\r\n req.on('end', () => {\r\n try {\r\n resolve(body && req.headers['content-type']?.includes('application/json')\r\n ? JSON.parse(body) : body);\r\n } catch (e) { reject(e); }\r\n });\r\n req.on('error', reject);\r\n });\r\n}\r\n\r\nexport default async function handler(req: IncomingMessage, res: ServerResponse) {\r\n const method = (req.method || 'GET').toUpperCase();\r\n const apiRes = enhance(res);\r\n const apiReq = req as any;\r\n\r\n apiReq.body = await parseBody(req);\r\n apiReq.query = Object.fromEntries(new URL(req.url || '/', 'http://localhost').searchParams);\r\n apiReq.params = apiReq.query;\r\n\r\n const fn = (mod as any)[method] ?? (mod as any).default;\r\n if (typeof fn !== 'function') {\r\n (apiRes as any).json({ error: \\`Method \\${method} not allowed\\` }, 405);\r\n return;\r\n }\r\n await fn(apiReq, apiRes);\r\n}\r\n`.trimStart();\r\n}\r\n\r\n// \u2500\u2500\u2500 Page adapter template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport interface PageAdapterOptions {\r\n /** e.g. './home.tsx' \u2014 relative import for the page default export */\r\n pageImport: string;\r\n /** Newline-joined import statements for layout components */\r\n layoutImports: string;\r\n /** function-name \u2192 cc_id map, computed at build time */\r\n clientComponentNames: Record<string, string>;\r\n /** All client component IDs reachable from this page */\r\n allClientIds: string[];\r\n /** Comma-separated list of __layout_N__ identifiers */\r\n layoutArrayItems: string;\r\n /** Pre-rendered HTML per client component ID, computed at build time */\r\n prerenderedHtml: Record<string, string>;\r\n}\r\n\r\n/**\r\n * Returns the TypeScript source for a fully self-contained page handler.\r\n *\r\n * The adapter:\r\n * \u2022 Inlines the html-store so useHtml() works without external deps.\r\n * \u2022 Contains an async recursive renderer that handles server + client\r\n * components without react-dom/server.\r\n * \u2022 Client components are identified via the pre-computed CLIENT_COMPONENTS\r\n * map (no fs.readFileSync at runtime).\r\n * \u2022 Emits the same full HTML document structure as ssr.ts including the\r\n * __n_data blob, importmap, and initRuntime bootstrap.\r\n */\r\nexport function makePageAdapterSource(opts: PageAdapterOptions): string {\r\n const {\r\n pageImport,\r\n layoutImports,\r\n clientComponentNames,\r\n allClientIds,\r\n layoutArrayItems,\r\n prerenderedHtml,\r\n } = opts;\r\n\r\n return `\r\nimport type { IncomingMessage, ServerResponse } from 'http';\r\nimport * as __page__ from ${pageImport};\r\n${layoutImports}\r\n\r\n// \u2500\u2500\u2500 Pre-built client component registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Computed at BUILD TIME from the import tree. Source files are not deployed,\r\n// so we must not read them with fs.readFileSync at runtime.\r\n// Key: default-export function name \u2192 Value: stable content-hash ID\r\nconst CLIENT_COMPONENTS: Record<string, string> = ${JSON.stringify(clientComponentNames)};\r\n\r\n// All client component IDs reachable from this page (page + layouts).\r\n// Sent to initRuntime so the browser pre-loads all bundles for SPA navigation.\r\nconst ALL_CLIENT_IDS: string[] = ${JSON.stringify(allClientIds)};\r\n\r\n// Pre-rendered HTML for each client component, produced at BUILD TIME by\r\n// renderToString with default props. Used directly in the span wrapper so\r\n// the server response contains real markup and React hydration never sees a\r\n// mismatch. No react-dom/server is needed at runtime.\r\nconst PRERENDERED_HTML: Record<string, string> = ${JSON.stringify(prerenderedHtml)};\r\n\r\n// \u2500\u2500\u2500 html-store (inlined \u2014 no external refs) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Uses the same globalThis Symbol key as html-store.ts so any useHtml() call\r\n// (however imported) writes into the same store that runWithHtmlStore reads.\r\ntype TitleValue = string | ((prev: string) => string);\r\ninterface HtmlStore {\r\n titleOps: TitleValue[];\r\n htmlAttrs: Record<string, string | undefined>;\r\n bodyAttrs: Record<string, string | undefined>;\r\n meta: Record<string, string | undefined>[];\r\n link: Record<string, string | undefined>[];\r\n script: Record<string, any>[];\r\n style: { content?: string; media?: string }[];\r\n}\r\nconst __STORE_KEY__ = Symbol.for('__nukejs_html_store__');\r\nfunction __getStore(): HtmlStore | null { return (globalThis as any)[__STORE_KEY__] ?? null; }\r\nfunction __setStore(s: HtmlStore | null): void { (globalThis as any)[__STORE_KEY__] = s; }\r\nfunction __emptyStore(): HtmlStore {\r\n return { titleOps: [], htmlAttrs: {}, bodyAttrs: {}, meta: [], link: [], script: [], style: [] };\r\n}\r\nasync function runWithHtmlStore(fn: () => Promise<void>): Promise<HtmlStore> {\r\n __setStore(__emptyStore());\r\n try { await fn(); return { ...(__getStore() ?? __emptyStore()) }; }\r\n finally { __setStore(null); }\r\n}\r\nfunction resolveTitle(ops: TitleValue[], fallback = ''): string {\r\n let t = fallback;\r\n for (let i = ops.length - 1; i >= 0; i--) {\r\n const op = ops[i]; t = typeof op === 'string' ? op : op(t);\r\n }\r\n return t;\r\n}\r\n\r\n// \u2500\u2500\u2500 HTML helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\nfunction escapeHtml(s: string): string {\r\n return String(s)\r\n .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\r\n .replace(/\"/g, '&quot;').replace(/'/g, '&#039;');\r\n}\r\nfunction escapeAttr(s: string): string {\r\n return String(s).replace(/&/g, '&amp;').replace(/\"/g, '&quot;');\r\n}\r\nfunction renderAttrs(attrs: Record<string, string | boolean | undefined>): string {\r\n return Object.entries(attrs)\r\n .filter(([, v]) => v !== undefined && v !== false)\r\n .map(([k, v]) => v === true ? k : \\`\\${k}=\"\\${escapeAttr(String(v))}\"\\`)\r\n .join(' ');\r\n}\r\nfunction openTag(tag: string, attrs: Record<string, string | undefined>): string {\r\n const s = renderAttrs(attrs as Record<string, string | boolean | undefined>);\r\n return s ? \\`<\\${tag} \\${s}>\\` : \\`<\\${tag}>\\`;\r\n}\r\nfunction metaKey(k: string): string { return k === 'httpEquiv' ? 'http-equiv' : k; }\r\nfunction linkKey(k: string): string {\r\n if (k === 'hrefLang') return 'hreflang';\r\n if (k === 'crossOrigin') return 'crossorigin';\r\n return k;\r\n}\r\nfunction renderMetaTag(tag: Record<string, string | undefined>): string {\r\n const attrs: Record<string, string | undefined> = {};\r\n for (const [k, v] of Object.entries(tag)) if (v !== undefined) attrs[metaKey(k)] = v;\r\n return \\` <meta \\${renderAttrs(attrs as any)} />\\`;\r\n}\r\nfunction renderLinkTag(tag: Record<string, string | undefined>): string {\r\n const attrs: Record<string, string | undefined> = {};\r\n for (const [k, v] of Object.entries(tag)) if (v !== undefined) attrs[linkKey(k)] = v;\r\n return \\` <link \\${renderAttrs(attrs as any)} />\\`;\r\n}\r\nfunction renderScriptTag(tag: any): string {\r\n const attrs: Record<string, any> = {\r\n src: tag.src, type: tag.type, crossorigin: tag.crossOrigin,\r\n integrity: tag.integrity, defer: tag.defer, async: tag.async, nomodule: tag.noModule,\r\n };\r\n const s = renderAttrs(attrs);\r\n const open = s ? \\`<script \\${s}>\\` : '<script>';\r\n return \\` \\${open}\\${tag.src ? '' : (tag.content ?? '')}</script>\\`;\r\n}\r\nfunction renderStyleTag(tag: any): string {\r\n const media = tag.media ? \\` media=\"\\${escapeAttr(tag.media)}\"\\` : '';\r\n return \\` <style\\${media}>\\${tag.content ?? ''}</style>\\`;\r\n}\r\n\r\n// \u2500\u2500\u2500 Void element set \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\nconst VOID_TAGS = new Set([\r\n 'area','base','br','col','embed','hr','img','input',\r\n 'link','meta','param','source','track','wbr',\r\n]);\r\n\r\n// \u2500\u2500\u2500 Prop serialization \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Converts React element trees in props to a JSON-safe format that\r\n// bundle.ts / initRuntime can reconstruct on the client.\r\nfunction serializeProps(value: any): any {\r\n if (value == null || typeof value !== 'object') return value;\r\n if (typeof value === 'function') return undefined;\r\n if (Array.isArray(value)) {\r\n return value.map(serializeProps).filter((v: any) => v !== undefined);\r\n }\r\n if ((value as any).$$typeof) {\r\n const { type, props: elProps } = value as any;\r\n if (typeof type === 'string') {\r\n return { __re: 'html', tag: type, props: serializeProps(elProps) };\r\n }\r\n if (typeof type === 'function') {\r\n const cid = CLIENT_COMPONENTS[type.name];\r\n if (cid) return { __re: 'client', componentId: cid, props: serializeProps(elProps) };\r\n }\r\n return undefined;\r\n }\r\n const out: any = {};\r\n for (const [k, v] of Object.entries(value as Record<string, any>)) {\r\n const s = serializeProps(v);\r\n if (s !== undefined) out[k] = s;\r\n }\r\n return out;\r\n}\r\n\r\n// \u2500\u2500\u2500 Async recursive renderer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Handles: null/undefined/boolean \u2192 '', strings/numbers \u2192 escaped text, arrays,\r\n// Fragment, void/non-void HTML elements, class components, sync + async functions.\r\n// Client components \u2192 <span data-hydrate-id=\"\u2026\"> markers for browser hydration.\r\nasync function renderNode(node: any, hydrated: Set<string>): Promise<string> {\r\n if (node == null || typeof node === 'boolean') return '';\r\n if (typeof node === 'string') return escapeHtml(node);\r\n if (typeof node === 'number') return String(node);\r\n if (Array.isArray(node)) {\r\n return (await Promise.all(node.map(n => renderNode(n, hydrated)))).join('');\r\n }\r\n\r\n const { type, props } = node as { type: any; props: Record<string, any> };\r\n if (!type) return '';\r\n\r\n if (type === Symbol.for('react.fragment')) {\r\n return renderNode(props?.children ?? null, hydrated);\r\n }\r\n\r\n if (typeof type === 'string') {\r\n const { children, dangerouslySetInnerHTML, ...rest } = props || {};\r\n const attrParts: string[] = [];\r\n for (const [k, v] of Object.entries(rest as Record<string, any>)) {\r\n const name = k === 'className' ? 'class' : k === 'htmlFor' ? 'for' : k;\r\n if (typeof v === 'boolean') { if (v) attrParts.push(name); continue; }\r\n if (v == null) continue;\r\n if (k === 'style' && typeof v === 'object') {\r\n const css = Object.entries(v as Record<string, any>)\r\n .map(([p, val]) => \\`\\${p.replace(/[A-Z]/g, m => \\`-\\${m.toLowerCase()}\\`)}:\\${escapeHtml(String(val))}\\`)\r\n .join(';');\r\n attrParts.push(\\`style=\"\\${css}\"\\`);\r\n continue;\r\n }\r\n attrParts.push(\\`\\${name}=\"\\${escapeHtml(String(v))}\"\\`);\r\n }\r\n const attrStr = attrParts.length ? ' ' + attrParts.join(' ') : '';\r\n if (VOID_TAGS.has(type)) return \\`<\\${type}\\${attrStr} />\\`;\r\n const inner = dangerouslySetInnerHTML\r\n ? (dangerouslySetInnerHTML as any).__html\r\n : await renderNode(children ?? null, hydrated);\r\n return \\`<\\${type}\\${attrStr}>\\${inner}</\\${type}>\\`;\r\n }\r\n\r\n if (typeof type === 'function') {\r\n const clientId = CLIENT_COMPONENTS[type.name];\r\n if (clientId) {\r\n hydrated.add(clientId);\r\n const serializedProps = serializeProps(props ?? {});\r\n // Render with actual props so children/content appear in the SSR HTML.\r\n // Fall back to the build-time pre-rendered HTML if the component throws\r\n // (e.g. it references browser-only APIs during render).\r\n let ssrHtml: string;\r\n try {\r\n const result = await (type as Function)(props || {});\r\n ssrHtml = await renderNode(result, new Set());\r\n } catch {\r\n ssrHtml = PRERENDERED_HTML[clientId] ?? '';\r\n }\r\n return \\`<span data-hydrate-id=\"\\${clientId}\" data-hydrate-props=\"\\${escapeHtml(JSON.stringify(serializedProps))}\">\\${ssrHtml}</span>\\`;\r\n }\r\n const instance = type.prototype?.isReactComponent ? new (type as any)(props) : null;\r\n const result = instance ? instance.render() : await (type as Function)(props || {});\r\n return renderNode(result, hydrated);\r\n }\r\n\r\n return '';\r\n}\r\n\r\n// \u2500\u2500\u2500 Layout wrapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\nconst LAYOUT_COMPONENTS: Array<(props: any) => any> = [${layoutArrayItems}];\r\n\r\nfunction wrapWithLayouts(element: any): any {\r\n let el = element;\r\n for (let i = LAYOUT_COMPONENTS.length - 1; i >= 0; i--) {\r\n el = { type: LAYOUT_COMPONENTS[i], props: { children: el }, key: null, ref: null };\r\n }\r\n return el;\r\n}\r\n\r\n// \u2500\u2500\u2500 Handler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\nexport default async function handler(req: IncomingMessage, res: ServerResponse): Promise<void> {\r\n try {\r\n const parsed = new URL(req.url || '/', 'http://localhost');\r\n const params: Record<string, string> = {};\r\n parsed.searchParams.forEach((v, k) => { params[k] = v; });\r\n const url = req.url || '/';\r\n\r\n const hydrated = new Set<string>();\r\n const pageElement = { type: __page__.default, props: params as any, key: null, ref: null };\r\n const wrapped = wrapWithLayouts(pageElement);\r\n\r\n let appHtml = '';\r\n const store = await runWithHtmlStore(async () => {\r\n appHtml = await renderNode(wrapped, hydrated);\r\n });\r\n\r\n const pageTitle = resolveTitle(store.titleOps, 'SSR App');\r\n const headLines: string[] = [\r\n ' <meta charset=\"utf-8\" />',\r\n ' <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />',\r\n \\` <title>\\${escapeHtml(pageTitle)}</title>\\`,\r\n ...store.meta.map(renderMetaTag),\r\n ...store.link.map(renderLinkTag),\r\n ...store.style.map(renderStyleTag),\r\n ...store.script.map(renderScriptTag),\r\n ];\r\n\r\n const runtimeData = JSON.stringify({\r\n hydrateIds: [...hydrated],\r\n allIds: ALL_CLIENT_IDS,\r\n url,\r\n params,\r\n debug: 'silent',\r\n }).replace(/</g, '\\\\u003c').replace(/>/g, '\\\\u003e').replace(/&/g, '\\\\u0026');\r\n\r\n const html = \\`<!DOCTYPE html>\r\n\\${openTag('html', store.htmlAttrs)}\r\n<head>\r\n\\${headLines.join('\\\\n')}\r\n</head>\r\n\\${openTag('body', store.bodyAttrs)}\r\n <div id=\"app\">\\${appHtml}</div>\r\n\r\n <script id=\"__n_data\" type=\"application/json\">\\${runtimeData}</script>\r\n\r\n <script type=\"importmap\">\r\n {\r\n \"imports\": {\r\n \"react\": \"/__react.js\",\r\n \"react-dom/client\": \"/__react.js\",\r\n \"react/jsx-runtime\": \"/__react.js\",\r\n \"nukejs\": \"/__n.js\"\r\n }\r\n }\r\n </script>\r\n\r\n <script type=\"module\">\r\n const { initRuntime } = await import('nukejs');\r\n const data = JSON.parse(document.getElementById('__n_data').textContent);\r\n await initRuntime(data);\r\n </script>\r\n</body>\r\n</html>\\`;\r\n\r\n res.statusCode = 200;\r\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\r\n res.end(html);\r\n } catch (err: any) {\r\n console.error('[page render error]', err);\r\n res.statusCode = 500;\r\n res.setHeader('Content-Type', 'text/plain; charset=utf-8');\r\n res.end('Internal Server Error');\r\n }\r\n}\r\n`.trimStart();\r\n}\r\n\r\n// \u2500\u2500\u2500 Bundle operations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Bundles an API route handler into a single self-contained ESM string.\r\n *\r\n * Writes a temporary adapter next to `absPath`, bundles them together with\r\n * esbuild (node_modules kept external), then removes the temp file.\r\n *\r\n * @returns The bundled ESM text ready to write to disk.\r\n */\r\nexport async function bundleApiHandler(absPath: string): Promise<string> {\r\n const adapterName = `_api_adapter_${crypto.randomBytes(4).toString('hex')}.ts`;\r\n const adapterPath = path.join(path.dirname(absPath), adapterName);\r\n\r\n fs.writeFileSync(adapterPath, makeApiAdapterSource(path.basename(absPath)));\r\n\r\n let text: string;\r\n try {\r\n const result = await build({\r\n entryPoints: [adapterPath],\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'node',\r\n target: 'node20',\r\n packages: 'external',\r\n write: false,\r\n });\r\n text = result.outputFiles[0].text;\r\n } finally {\r\n fs.unlinkSync(adapterPath);\r\n }\r\n return text;\r\n}\r\n\r\nexport interface PageBundleOptions {\r\n absPath: string;\r\n pagesDir: string;\r\n clientComponentNames: Record<string, string>;\r\n allClientIds: string[];\r\n layoutPaths: string[];\r\n prerenderedHtml: Record<string, string>;\r\n}\r\n\r\n/**\r\n * Bundles a server-component page into a single self-contained ESM string.\r\n *\r\n * Writes a temporary adapter next to `absPath` (so relative imports inside\r\n * the component resolve from the correct base directory), bundles it with\r\n * esbuild (React and all npm deps inlined, only Node built-ins stay external),\r\n * then removes the temp file.\r\n *\r\n * @returns The bundled ESM text ready to write to disk.\r\n */\r\nexport async function bundlePageHandler(opts: PageBundleOptions): Promise<string> {\r\n const { absPath, clientComponentNames, allClientIds, layoutPaths, prerenderedHtml } = opts;\r\n\r\n // The adapter is written next to the page file, so make every layout path\r\n // relative to that same directory. Absolute Windows paths like \"C:\\...\" in\r\n // import statements are not valid ESM URL schemes and throw\r\n // ERR_UNSUPPORTED_ESM_URL_SCHEME. Relative paths work on all platforms.\r\n const adapterName = `_page_adapter_${crypto.randomBytes(4).toString('hex')}.ts`;\r\n const adapterDir = path.dirname(absPath);\r\n const adapterPath = path.join(adapterDir, adapterName);\r\n\r\n const layoutImports = layoutPaths\r\n .map((lp, i) => {\r\n const rel = path.relative(adapterDir, lp).replace(/\\\\/g, '/');\r\n const importPath = rel.startsWith('.') ? rel : './' + rel;\r\n return `import __layout_${i}__ from ${JSON.stringify(importPath)};`;\r\n })\r\n .join('\\n');\r\n const layoutArrayItems = layoutPaths\r\n .map((_, i) => `__layout_${i}__`)\r\n .join(', ');\r\n\r\n fs.writeFileSync(adapterPath, makePageAdapterSource({\r\n pageImport: JSON.stringify('./' + path.basename(absPath)),\r\n layoutImports,\r\n clientComponentNames,\r\n allClientIds,\r\n layoutArrayItems,\r\n prerenderedHtml,\r\n }));\r\n\r\n let text: string;\r\n try {\r\n const result = await build({\r\n entryPoints: [adapterPath],\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'node',\r\n target: 'node20',\r\n jsx: 'automatic',\r\n external: [\r\n // Node built-ins only \u2014 all npm packages (react, nukejs, \u2026) are inlined\r\n 'node:*',\r\n 'http', 'https', 'fs', 'path', 'url', 'crypto', 'stream', 'buffer',\r\n 'events', 'util', 'os', 'net', 'tls', 'child_process', 'worker_threads',\r\n 'cluster', 'dgram', 'dns', 'readline', 'zlib', 'assert', 'module',\r\n 'perf_hooks', 'string_decoder', 'timers', 'async_hooks', 'v8', 'vm',\r\n ],\r\n define: { 'process.env.NODE_ENV': '\"production\"' },\r\n write: false,\r\n });\r\n text = result.outputFiles[0].text;\r\n } finally {\r\n fs.unlinkSync(adapterPath);\r\n }\r\n return text;\r\n}\r\n\r\n/**\r\n * Bundles every client component in `globalRegistry` to\r\n * `<staticDir>/__client-component/<id>.js`.\r\n *\r\n * Mirrors bundleClientComponent() in bundler.ts:\r\n * \u2022 browser ESM, JSX automatic\r\n * \u2022 react / react-dom/client / react/jsx-runtime kept external so the\r\n * importmap can resolve them to the already-loaded /__react.js bundle.\r\n */\r\nexport async function bundleClientComponents(\r\n globalRegistry: Map<string, string>,\r\n pagesDir: string,\r\n staticDir: string,\r\n): Promise<Map<string, string>> {\r\n if (globalRegistry.size === 0) return new Map();\r\n\r\n const outDir = path.join(staticDir, '__client-component');\r\n fs.mkdirSync(outDir, { recursive: true });\r\n\r\n const prerendered = new Map<string, string>(); // id \u2192 pre-rendered HTML\r\n\r\n for (const [id, filePath] of globalRegistry) {\r\n console.log(` bundling client ${id} (${path.relative(pagesDir, filePath)})`);\r\n\r\n // 1. Browser bundle \u2014 served to the client for hydration\r\n const browserResult = await build({\r\n entryPoints: [filePath],\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'browser',\r\n jsx: 'automatic',\r\n minify: true,\r\n external: ['react', 'react-dom/client', 'react/jsx-runtime'],\r\n define: { 'process.env.NODE_ENV': '\"production\"' },\r\n write: false,\r\n });\r\n fs.writeFileSync(path.join(outDir, `${id}.js`), browserResult.outputFiles[0].text);\r\n\r\n // 2. SSR pre-render \u2014 bundle for Node, import, renderToString, discard\r\n const ssrTmp = path.join(\r\n path.dirname(filePath),\r\n `_ssr_${id}_${crypto.randomBytes(4).toString('hex')}.mjs`,\r\n );\r\n try {\r\n const ssrResult = await build({\r\n entryPoints: [filePath],\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'node',\r\n target: 'node20',\r\n jsx: 'automatic',\r\n packages: 'external',\r\n define: { 'process.env.NODE_ENV': '\"production\"' },\r\n write: false,\r\n });\r\n fs.writeFileSync(ssrTmp, ssrResult.outputFiles[0].text);\r\n\r\n const { default: Component } = await import(pathToFileURL(ssrTmp).href);\r\n const { createElement } = await import('react');\r\n const { renderToString } = await import('react-dom/server');\r\n\r\n prerendered.set(id, renderToString(createElement(Component, {})));\r\n console.log(` prerendered ${id}`);\r\n } catch (e) {\r\n //console.warn(` [SSR prerender failed for ${id}]`, e);\r\n prerendered.set(id, '');\r\n } finally {\r\n if (fs.existsSync(ssrTmp)) fs.unlinkSync(ssrTmp);\r\n }\r\n }\r\n\r\n console.log(` bundled ${globalRegistry.size} client component(s) \u2192 ${path.relative(process.cwd(), outDir)}/`);\r\n return prerendered;\r\n}\r\n\r\n/**\r\n * Builds the full React + ReactDOM browser bundle to `<staticDir>/__react.js`.\r\n * Exports every public hook and helper so client component bundles can import\r\n * them via the importmap without bundling React a second time.\r\n */\r\nexport async function buildReactBundle(staticDir: string): Promise<void> {\r\n const result = await build({\r\n stdin: {\r\n contents: `\r\nimport React, {\r\n useState, useEffect, useContext, useReducer, useCallback, useMemo,\r\n useRef, useImperativeHandle, useLayoutEffect, useDebugValue,\r\n useDeferredValue, useTransition, useId, useSyncExternalStore,\r\n useInsertionEffect, createContext, forwardRef, memo, lazy,\r\n Suspense, Fragment, StrictMode, Component, PureComponent\r\n} from 'react';\r\nimport { jsx, jsxs } from 'react/jsx-runtime';\r\nimport { hydrateRoot, createRoot } from 'react-dom/client';\r\n\r\nexport {\r\n useState, useEffect, useContext, useReducer, useCallback, useMemo,\r\n useRef, useImperativeHandle, useLayoutEffect, useDebugValue,\r\n useDeferredValue, useTransition, useId, useSyncExternalStore,\r\n useInsertionEffect, createContext, forwardRef, memo, lazy,\r\n Suspense, Fragment, StrictMode, Component, PureComponent,\r\n hydrateRoot, createRoot, jsx, jsxs\r\n};\r\nexport default React;\r\n`,\r\n loader: 'ts',\r\n },\r\n bundle: true,\r\n write: false,\r\n treeShaking: true,\r\n minify: true,\r\n format: 'esm',\r\n jsx: 'automatic',\r\n alias: {\r\n react: path.dirname(fileURLToPath(import.meta.resolve('react/package.json'))),\r\n 'react-dom': path.dirname(fileURLToPath(import.meta.resolve('react-dom/package.json'))),\r\n },\r\n define: { 'process.env.NODE_ENV': '\"production\"' },\r\n });\r\n fs.writeFileSync(path.join(staticDir, '__react.js'), result.outputFiles[0].text);\r\n console.log(' built __react.js');\r\n}\r\n\r\n/**\r\n * Builds the nukejs client runtime to `<staticDir>/__n.js`.\r\n * React and react-dom/client are kept external (resolved via importmap).\r\n */\r\nexport async function buildNukeBundle(staticDir: string): Promise<void> {\r\n const nukeDir = path.dirname(fileURLToPath(import.meta.url));\r\n const result = await build({\r\n entryPoints: [path.join(nukeDir, 'bundle.js')],\r\n bundle: true,\r\n write: false,\r\n format: 'esm',\r\n minify: true,\r\n external: ['react', 'react-dom/client'],\r\n });\r\n fs.writeFileSync(path.join(staticDir, '__n.js'), result.outputFiles[0].text);\r\n console.log(' built __n.js');\r\n}\r\n\r\n// \u2500\u2500\u2500 Public static file copying \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Recursively copies every file from `app/public/` into `destDir`,\r\n * preserving the directory structure.\r\n *\r\n * Called by both build-vercel.ts (dest = .vercel/output/static/) and\r\n * build-node.ts (dest = dist/static/) so that:\r\n *\r\n * app/public/favicon.ico \u2192 <destDir>/favicon.ico\r\n * app/public/images/logo.png \u2192 <destDir>/images/logo.png\r\n *\r\n * On Vercel, the Build Output API v3 serves everything in .vercel/output/static/\r\n * directly \u2014 no route entry needed, same as __react.js and __n.js.\r\n *\r\n * On Node, the serverEntry template serves files from dist/static/ with the\r\n * same MIME-type logic as the dev middleware.\r\n *\r\n * Skips silently when the public directory does not exist so projects without\r\n * one don't need any special configuration.\r\n */\r\nexport function copyPublicFiles(publicDir: string, destDir: string): void {\r\n if (!fs.existsSync(publicDir)) return;\r\n\r\n let count = 0;\r\n\r\n (function walk(src: string, dest: string) {\r\n fs.mkdirSync(dest, { recursive: true });\r\n for (const entry of fs.readdirSync(src, { withFileTypes: true })) {\r\n const srcPath = path.join(src, entry.name);\r\n const destPath = path.join(dest, entry.name);\r\n if (entry.isDirectory()) {\r\n walk(srcPath, destPath);\r\n } else {\r\n fs.copyFileSync(srcPath, destPath);\r\n count++;\r\n }\r\n }\r\n })(publicDir, destDir);\r\n\r\n if (count > 0) {\r\n console.log(` copied ${count} public file(s) \u2192 ${path.relative(process.cwd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O,SAAS,gBAAgB,WAAmB,SAAuB;AACxE,MAAI,CAAC,GAAG,WAAW,SAAS,EAAG;AAE/B,MAAI,QAAQ;AAEZ,GAAC,SAAS,KAAK,KAAa,MAAc;AACxC,OAAG,UAAU,MAAM,EAAE,WAAW,KAAK,CAAC;AACtC,eAAW,SAAS,GAAG,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC,GAAG;AAChE,YAAM,UAAU,KAAK,KAAK,KAAK,MAAM,IAAI;AACzC,YAAM,WAAW,KAAK,KAAK,MAAM,MAAM,IAAI;AAC3C,UAAI,MAAM,YAAY,GAAG;AACvB,aAAK,SAAS,QAAQ;AAAA,MACxB,OAAO;AACL,WAAG,aAAa,SAAS,QAAQ;AACjC;AAAA,MACF;AAAA,IACF;AAAA,EACF,GAAG,WAAW,OAAO;AAErB,MAAI,QAAQ,GAAG;AACb,YAAQ,IAAI,eAAe,KAAK,0BAAqB,KAAK,SAAS,QAAQ,IAAI,GAAG,OAAO,CAAC,GAAG;AAAA,EAC/F;AACF;",
4
+ "sourcesContent": ["/**\r\n * build-common.ts\r\n *\r\n * Shared build logic used by both build-vercel.ts and build-node.ts.\r\n *\r\n * Exports:\r\n * \u2014 utility helpers : walkFiles, analyzeFile, isServerComponent,\r\n * findPageLayouts, extractDefaultExportName\r\n * \u2014 collection : collectServerPages, collectGlobalClientRegistry\r\n * \u2014 template codegen : makeApiAdapterSource, makePageAdapterSource\r\n * \u2014 bundle operations : bundleApiHandler, bundlePageHandler,\r\n * bundleClientComponents, buildCombinedBundle\r\n */\r\n\r\nimport fs from 'fs';\r\nimport path from 'path';\r\nimport crypto from 'crypto';\r\nimport { fileURLToPath, pathToFileURL } from 'url';\r\nimport { build } from 'esbuild';\r\nimport { findClientComponentsInTree } from './component-analyzer';\r\n\r\n// \u2500\u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport interface AnalyzedRoute {\r\n srcRegex: string;\r\n paramNames: string[];\r\n /** Path used as function namespace, e.g. '/api/users' or '/page/about'. */\r\n funcPath: string;\r\n specificity: number;\r\n}\r\n\r\nexport interface ServerPage extends AnalyzedRoute {\r\n absPath: string;\r\n}\r\n\r\n/** A server page together with its fully bundled ESM text, ready to emit. */\r\nexport interface BuiltPage extends ServerPage {\r\n bundleText: string;\r\n}\r\n\r\n// \u2500\u2500\u2500 File walker \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport function walkFiles(dir: string, base: string = dir): string[] {\r\n if (!fs.existsSync(dir)) return [];\r\n const results: string[] = [];\r\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\r\n const full = path.join(dir, entry.name);\r\n if (entry.isDirectory()) {\r\n results.push(...walkFiles(full, base));\r\n } else if (entry.name.endsWith('.ts') || entry.name.endsWith('.tsx')) {\r\n results.push(path.relative(base, full));\r\n }\r\n }\r\n return results;\r\n}\r\n\r\n// \u2500\u2500\u2500 Route analysis \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Parses dynamic-route segments from a relative file path and returns a regex,\r\n * captured param names, a function path, and a specificity score.\r\n *\r\n * @param relPath Relative path from the dir root (e.g. 'users/[id].tsx').\r\n * @param prefix Namespace for funcPath ('api' | 'page').\r\n */\r\nexport function analyzeFile(relPath: string, prefix = 'api'): AnalyzedRoute {\r\n const normalized = relPath.replace(/\\\\/g, '/').replace(/\\.(tsx?)$/, '');\r\n let segments = normalized.split('/');\r\n if (segments.at(-1) === 'index') segments = segments.slice(0, -1);\r\n\r\n const paramNames: string[] = [];\r\n const regexParts: string[] = [];\r\n let specificity = 0;\r\n\r\n for (const seg of segments) {\r\n const optCatchAll = seg.match(/^\\[\\[\\.\\.\\.(.+)\\]\\]$/);\r\n if (optCatchAll) { paramNames.push(optCatchAll[1]); regexParts.push('(.*)'); specificity += 1; continue; }\r\n const catchAll = seg.match(/^\\[\\.\\.\\.(.+)\\]$/);\r\n if (catchAll) { paramNames.push(catchAll[1]); regexParts.push('(.+)'); specificity += 10; continue; }\r\n const dynamic = seg.match(/^\\[(.+)\\]$/);\r\n if (dynamic) { paramNames.push(dynamic[1]); regexParts.push('([^/]+)'); specificity += 100; continue; }\r\n regexParts.push(seg.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'));\r\n specificity += 1000;\r\n }\r\n\r\n const srcRegex = segments.length === 0\r\n ? '^/$'\r\n : '^/' + regexParts.join('/') + '$';\r\n\r\n const funcSegments = normalized.split('/');\r\n if (funcSegments.at(-1) === 'index') funcSegments.pop();\r\n const funcPath = funcSegments.length === 0\r\n ? `/${prefix}/_index`\r\n : `/${prefix}/` + funcSegments.join('/');\r\n\r\n return { srcRegex, paramNames, funcPath, specificity };\r\n}\r\n\r\n// \u2500\u2500\u2500 Server-component detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Returns true when a file does NOT begin with a \"use client\" directive \u2014\r\n * i.e. it is a server component.\r\n */\r\nexport function isServerComponent(filePath: string): boolean {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n for (const line of content.split('\\n').slice(0, 5)) {\r\n const trimmed = line.trim();\r\n if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('/*')) continue;\r\n if (/^[\"']use client[\"'];?$/.test(trimmed)) return false;\r\n break;\r\n }\r\n return true;\r\n}\r\n\r\n// \u2500\u2500\u2500 Layout discovery \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Walks from the pages root to the directory containing `routeFilePath` and\r\n * returns every layout.tsx found, in outermost-first order.\r\n */\r\nexport function findPageLayouts(routeFilePath: string, pagesDir: string): string[] {\r\n const layouts: string[] = [];\r\n\r\n const rootLayout = path.join(pagesDir, 'layout.tsx');\r\n if (fs.existsSync(rootLayout)) layouts.push(rootLayout);\r\n\r\n const relativePath = path.relative(pagesDir, path.dirname(routeFilePath));\r\n if (!relativePath || relativePath === '.') return layouts;\r\n\r\n const segments = relativePath.split(path.sep).filter(Boolean);\r\n for (let i = 1; i <= segments.length; i++) {\r\n const layoutPath = path.join(pagesDir, ...segments.slice(0, i), 'layout.tsx');\r\n if (fs.existsSync(layoutPath)) layouts.push(layoutPath);\r\n }\r\n\r\n return layouts;\r\n}\r\n\r\n/**\r\n * Extracts the identifier used as the default export from a component file.\r\n * Returns null when no default export is found.\r\n */\r\nexport function extractDefaultExportName(filePath: string): string | null {\r\n const content = fs.readFileSync(filePath, 'utf-8');\r\n const match = content.match(/export\\s+default\\s+(?:function\\s+)?(\\w+)/);\r\n return match?.[1] ?? null;\r\n}\r\n\r\n// \u2500\u2500\u2500 Server page collection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Returns all server-component pages inside `pagesDir`, sorted by specificity\r\n * (most-specific first so more-precise routes shadow catch-alls in routers).\r\n * layout.tsx files and \"use client\" files are excluded.\r\n */\r\nexport function collectServerPages(pagesDir: string): ServerPage[] {\r\n if (!fs.existsSync(pagesDir)) return [];\r\n return walkFiles(pagesDir)\r\n .filter(relPath => {\r\n const base = path.basename(relPath, path.extname(relPath));\r\n if (base === 'layout') return false;\r\n return isServerComponent(path.join(pagesDir, relPath));\r\n })\r\n .map(relPath => ({\r\n ...analyzeFile(relPath, 'page'),\r\n absPath: path.join(pagesDir, relPath),\r\n }))\r\n .sort((a, b) => b.specificity - a.specificity);\r\n}\r\n\r\n/**\r\n * Walks every server page and its layout chain to collect all client component\r\n * IDs reachable anywhere in the app. Deduplication is automatic because the\r\n * Map key is the stable content-hash ID produced by component-analyzer.ts.\r\n */\r\nexport function collectGlobalClientRegistry(\r\n serverPages: ServerPage[],\r\n pagesDir: string,\r\n): Map<string, string> {\r\n const registry = new Map<string, string>(); // id \u2192 absFilePath\r\n for (const { absPath } of serverPages) {\r\n for (const [id, p] of findClientComponentsInTree(absPath, pagesDir)) {\r\n registry.set(id, p);\r\n }\r\n for (const layoutPath of findPageLayouts(absPath, pagesDir)) {\r\n for (const [id, p] of findClientComponentsInTree(layoutPath, pagesDir)) {\r\n registry.set(id, p);\r\n }\r\n }\r\n }\r\n return registry;\r\n}\r\n\r\n// \u2500\u2500\u2500 Per-page registry helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Builds the per-page client component registry (page + its layout chain) and\r\n * returns both the id\u2192path map and the name\u2192id map needed by bundlePageHandler.\r\n *\r\n * Extracted here to eliminate the identical loop duplicated across\r\n * build-node.ts and build-vercel.ts.\r\n */\r\nexport function buildPerPageRegistry(\r\n absPath: string,\r\n layoutPaths: string[],\r\n pagesDir: string,\r\n): { registry: Map<string, string>; clientComponentNames: Record<string, string> } {\r\n const registry = new Map<string, string>();\r\n\r\n for (const [id, p] of findClientComponentsInTree(absPath, pagesDir)) {\r\n registry.set(id, p);\r\n }\r\n for (const lp of layoutPaths) {\r\n for (const [id, p] of findClientComponentsInTree(lp, pagesDir)) {\r\n registry.set(id, p);\r\n }\r\n }\r\n\r\n const clientComponentNames: Record<string, string> = {};\r\n for (const [id, filePath] of registry) {\r\n const name = extractDefaultExportName(filePath);\r\n if (name) clientComponentNames[name] = id;\r\n }\r\n\r\n return { registry, clientComponentNames };\r\n}\r\n\r\n// \u2500\u2500\u2500 High-level page builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Runs both passes of the page build:\r\n *\r\n * Pass 1 \u2014 bundles all client components to `staticDir/__client-component/`\r\n * and collects pre-rendered HTML for each.\r\n * Pass 2 \u2014 bundles every server-component page into a self-contained ESM\r\n * handler and returns the results as `BuiltPage[]`.\r\n *\r\n * Callers (build-node, build-vercel) only need to write the bundled text to\r\n * their respective output destinations \u2014 the format-specific logic stays local.\r\n *\r\n * Returns an empty array when there are no server pages.\r\n */\r\nexport async function buildPages(\r\n pagesDir: string,\r\n staticDir: string,\r\n): Promise<BuiltPage[]> {\r\n const serverPages = collectServerPages(pagesDir);\r\n\r\n if (fs.existsSync(pagesDir) && walkFiles(pagesDir).length > 0 && serverPages.length === 0) {\r\n console.warn(`\u26A0 Pages found in ${pagesDir} but none are server components`);\r\n }\r\n\r\n if (serverPages.length === 0) return [];\r\n\r\n // Pass 1 \u2014 bundle all client components to static files.\r\n const globalClientRegistry = collectGlobalClientRegistry(serverPages, pagesDir);\r\n const prerenderedHtml = await bundleClientComponents(globalClientRegistry, pagesDir, staticDir);\r\n const prerenderedHtmlRecord = Object.fromEntries(prerenderedHtml);\r\n\r\n // Pass 2 \u2014 bundle each server-component page.\r\n const builtPages: BuiltPage[] = [];\r\n\r\n for (const page of serverPages) {\r\n const { funcPath, absPath } = page;\r\n console.log(` building ${fs.existsSync(absPath) ? absPath : absPath} \u2192 ${funcPath} [page]`);\r\n\r\n const layoutPaths = findPageLayouts(absPath, pagesDir);\r\n const { registry, clientComponentNames } = buildPerPageRegistry(absPath, layoutPaths, pagesDir);\r\n\r\n const bundleText = await bundlePageHandler({\r\n absPath,\r\n pagesDir,\r\n clientComponentNames,\r\n allClientIds: [...registry.keys()],\r\n layoutPaths,\r\n prerenderedHtml: prerenderedHtmlRecord,\r\n });\r\n\r\n builtPages.push({ ...page, bundleText });\r\n }\r\n\r\n return builtPages;\r\n}\r\n\r\n// \u2500\u2500\u2500 API adapter template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Returns the TypeScript source for a thin HTTP adapter that wraps an API\r\n * route module and exposes a single `handler(req, res)` default export.\r\n *\r\n * @param handlerFilename Basename of the handler file relative to the adapter\r\n * (e.g. 'users.ts'). Must be in the same directory.\r\n */\r\nexport function makeApiAdapterSource(handlerFilename: string): string {\r\n return `\r\nimport type { IncomingMessage, ServerResponse } from 'http';\r\nimport * as mod from ${JSON.stringify('./' + handlerFilename)};\r\n\r\nfunction enhance(res: ServerResponse) {\r\n (res as any).json = function (data: any, status = 200) {\r\n this.statusCode = status;\r\n this.setHeader('Content-Type', 'application/json');\r\n this.end(JSON.stringify(data));\r\n };\r\n (res as any).status = function (code: number) { this.statusCode = code; return this; };\r\n return res;\r\n}\r\n\r\nasync function parseBody(req: IncomingMessage): Promise<any> {\r\n return new Promise((resolve, reject) => {\r\n let body = '';\r\n req.on('data', chunk => { body += chunk.toString(); });\r\n req.on('end', () => {\r\n try {\r\n resolve(body && req.headers['content-type']?.includes('application/json')\r\n ? JSON.parse(body) : body);\r\n } catch (e) { reject(e); }\r\n });\r\n req.on('error', reject);\r\n });\r\n}\r\n\r\nexport default async function handler(req: IncomingMessage, res: ServerResponse) {\r\n const method = (req.method || 'GET').toUpperCase();\r\n const apiRes = enhance(res);\r\n const apiReq = req as any;\r\n\r\n apiReq.body = await parseBody(req);\r\n apiReq.query = Object.fromEntries(new URL(req.url || '/', 'http://localhost').searchParams);\r\n apiReq.params = apiReq.query;\r\n\r\n const fn = (mod as any)[method] ?? (mod as any).default;\r\n if (typeof fn !== 'function') {\r\n (apiRes as any).json({ error: \\`Method \\${method} not allowed\\` }, 405);\r\n return;\r\n }\r\n await fn(apiReq, apiRes);\r\n}\r\n`.trimStart();\r\n}\r\n\r\n// \u2500\u2500\u2500 Page adapter template \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nexport interface PageAdapterOptions {\r\n /** e.g. './home.tsx' \u2014 relative import for the page default export */\r\n pageImport: string;\r\n /** Newline-joined import statements for layout components */\r\n layoutImports: string;\r\n /** function-name \u2192 cc_id map, computed at build time */\r\n clientComponentNames: Record<string, string>;\r\n /** All client component IDs reachable from this page */\r\n allClientIds: string[];\r\n /** Comma-separated list of __layout_N__ identifiers */\r\n layoutArrayItems: string;\r\n /** Pre-rendered HTML per client component ID, computed at build time */\r\n prerenderedHtml: Record<string, string>;\r\n}\r\n\r\n/**\r\n * Returns the TypeScript source for a fully self-contained page handler.\r\n *\r\n * The adapter:\r\n * \u2022 Inlines the html-store so useHtml() works without external deps.\r\n * \u2022 Contains an async recursive renderer that handles server + client\r\n * components without react-dom/server.\r\n * \u2022 Client components are identified via the pre-computed CLIENT_COMPONENTS\r\n * map (no fs.readFileSync at runtime).\r\n * \u2022 Emits the same full HTML document structure as ssr.ts including the\r\n * __n_data blob, importmap, and initRuntime bootstrap.\r\n */\r\nexport function makePageAdapterSource(opts: PageAdapterOptions): string {\r\n const {\r\n pageImport,\r\n layoutImports,\r\n clientComponentNames,\r\n allClientIds,\r\n layoutArrayItems,\r\n prerenderedHtml,\r\n } = opts;\r\n\r\n return `\r\nimport type { IncomingMessage, ServerResponse } from 'http';\r\nimport * as __page__ from ${pageImport};\r\n${layoutImports}\r\n\r\n// \u2500\u2500\u2500 Pre-built client component registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Computed at BUILD TIME from the import tree. Source files are not deployed,\r\n// so we must not read them with fs.readFileSync at runtime.\r\n// Key: default-export function name \u2192 Value: stable content-hash ID\r\nconst CLIENT_COMPONENTS: Record<string, string> = ${JSON.stringify(clientComponentNames)};\r\n\r\n// All client component IDs reachable from this page (page + layouts).\r\n// Sent to initRuntime so the browser pre-loads all bundles for SPA navigation.\r\nconst ALL_CLIENT_IDS: string[] = ${JSON.stringify(allClientIds)};\r\n\r\n// Pre-rendered HTML for each client component, produced at BUILD TIME by\r\n// renderToString with default props. Used directly in the span wrapper so\r\n// the server response contains real markup and React hydration never sees a\r\n// mismatch. No react-dom/server is needed at runtime.\r\nconst PRERENDERED_HTML: Record<string, string> = ${JSON.stringify(prerenderedHtml)};\r\n\r\n// \u2500\u2500\u2500 html-store (inlined \u2014 no external refs) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Uses the same globalThis Symbol key as html-store.ts so any useHtml() call\r\n// (however imported) writes into the same store that runWithHtmlStore reads.\r\ntype TitleValue = string | ((prev: string) => string);\r\ninterface HtmlStore {\r\n titleOps: TitleValue[];\r\n htmlAttrs: Record<string, string | undefined>;\r\n bodyAttrs: Record<string, string | undefined>;\r\n meta: Record<string, string | undefined>[];\r\n link: Record<string, string | undefined>[];\r\n script: Record<string, any>[];\r\n style: { content?: string; media?: string }[];\r\n}\r\nconst __STORE_KEY__ = Symbol.for('__nukejs_html_store__');\r\nfunction __getStore(): HtmlStore | null { return (globalThis as any)[__STORE_KEY__] ?? null; }\r\nfunction __setStore(s: HtmlStore | null): void { (globalThis as any)[__STORE_KEY__] = s; }\r\nfunction __emptyStore(): HtmlStore {\r\n return { titleOps: [], htmlAttrs: {}, bodyAttrs: {}, meta: [], link: [], script: [], style: [] };\r\n}\r\nasync function runWithHtmlStore(fn: () => Promise<void>): Promise<HtmlStore> {\r\n __setStore(__emptyStore());\r\n try { await fn(); return { ...(__getStore() ?? __emptyStore()) }; }\r\n finally { __setStore(null); }\r\n}\r\nfunction resolveTitle(ops: TitleValue[], fallback = ''): string {\r\n let t = fallback;\r\n for (let i = ops.length - 1; i >= 0; i--) {\r\n const op = ops[i]; t = typeof op === 'string' ? op : op(t);\r\n }\r\n return t;\r\n}\r\n\r\n// \u2500\u2500\u2500 HTML helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\nfunction escapeHtml(s: string): string {\r\n return String(s)\r\n .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\r\n .replace(/\"/g, '&quot;').replace(/'/g, '&#039;');\r\n}\r\nfunction escapeAttr(s: string): string {\r\n return String(s).replace(/&/g, '&amp;').replace(/\"/g, '&quot;');\r\n}\r\nfunction renderAttrs(attrs: Record<string, string | boolean | undefined>): string {\r\n return Object.entries(attrs)\r\n .filter(([, v]) => v !== undefined && v !== false)\r\n .map(([k, v]) => v === true ? k : \\`\\${k}=\"\\${escapeAttr(String(v))}\"\\`)\r\n .join(' ');\r\n}\r\nfunction openTag(tag: string, attrs: Record<string, string | undefined>): string {\r\n const s = renderAttrs(attrs as Record<string, string | boolean | undefined>);\r\n return s ? \\`<\\${tag} \\${s}>\\` : \\`<\\${tag}>\\`;\r\n}\r\nfunction metaKey(k: string): string { return k === 'httpEquiv' ? 'http-equiv' : k; }\r\nfunction linkKey(k: string): string {\r\n if (k === 'hrefLang') return 'hreflang';\r\n if (k === 'crossOrigin') return 'crossorigin';\r\n return k;\r\n}\r\nfunction renderMetaTag(tag: Record<string, string | undefined>): string {\r\n const attrs: Record<string, string | undefined> = {};\r\n for (const [k, v] of Object.entries(tag)) if (v !== undefined) attrs[metaKey(k)] = v;\r\n return \\` <meta \\${renderAttrs(attrs as any)} />\\`;\r\n}\r\nfunction renderLinkTag(tag: Record<string, string | undefined>): string {\r\n const attrs: Record<string, string | undefined> = {};\r\n for (const [k, v] of Object.entries(tag)) if (v !== undefined) attrs[linkKey(k)] = v;\r\n return \\` <link \\${renderAttrs(attrs as any)} />\\`;\r\n}\r\nfunction renderScriptTag(tag: any): string {\r\n const attrs: Record<string, any> = {\r\n src: tag.src, type: tag.type, crossorigin: tag.crossOrigin,\r\n integrity: tag.integrity, defer: tag.defer, async: tag.async, nomodule: tag.noModule,\r\n };\r\n const s = renderAttrs(attrs);\r\n const open = s ? \\`<script \\${s}>\\` : '<script>';\r\n return \\` \\${open}\\${tag.src ? '' : (tag.content ?? '')}</script>\\`;\r\n}\r\nfunction renderStyleTag(tag: any): string {\r\n const media = tag.media ? \\` media=\"\\${escapeAttr(tag.media)}\"\\` : '';\r\n return \\` <style\\${media}>\\${tag.content ?? ''}</style>\\`;\r\n}\r\n\r\n// \u2500\u2500\u2500 Void element set \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\nconst VOID_TAGS = new Set([\r\n 'area','base','br','col','embed','hr','img','input',\r\n 'link','meta','param','source','track','wbr',\r\n]);\r\n\r\n// \u2500\u2500\u2500 Prop serialization \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Converts React element trees in props to a JSON-safe format that\r\n// bundle.ts / initRuntime can reconstruct on the client.\r\nfunction serializeProps(value: any): any {\r\n if (value == null || typeof value !== 'object') return value;\r\n if (typeof value === 'function') return undefined;\r\n if (Array.isArray(value)) {\r\n return value.map(serializeProps).filter((v: any) => v !== undefined);\r\n }\r\n if ((value as any).$$typeof) {\r\n const { type, props: elProps } = value as any;\r\n if (typeof type === 'string') {\r\n return { __re: 'html', tag: type, props: serializeProps(elProps) };\r\n }\r\n if (typeof type === 'function') {\r\n const cid = CLIENT_COMPONENTS[type.name];\r\n if (cid) return { __re: 'client', componentId: cid, props: serializeProps(elProps) };\r\n }\r\n return undefined;\r\n }\r\n const out: any = {};\r\n for (const [k, v] of Object.entries(value as Record<string, any>)) {\r\n const s = serializeProps(v);\r\n if (s !== undefined) out[k] = s;\r\n }\r\n return out;\r\n}\r\n\r\n// \u2500\u2500\u2500 Async recursive renderer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Handles: null/undefined/boolean \u2192 '', strings/numbers \u2192 escaped text, arrays,\r\n// Fragment, void/non-void HTML elements, class components, sync + async functions.\r\n// Client components \u2192 <span data-hydrate-id=\"\u2026\"> markers for browser hydration.\r\nasync function renderNode(node: any, hydrated: Set<string>): Promise<string> {\r\n if (node == null || typeof node === 'boolean') return '';\r\n if (typeof node === 'string') return escapeHtml(node);\r\n if (typeof node === 'number') return String(node);\r\n if (Array.isArray(node)) {\r\n return (await Promise.all(node.map(n => renderNode(n, hydrated)))).join('');\r\n }\r\n\r\n const { type, props } = node as { type: any; props: Record<string, any> };\r\n if (!type) return '';\r\n\r\n if (type === Symbol.for('react.fragment')) {\r\n return renderNode(props?.children ?? null, hydrated);\r\n }\r\n\r\n if (typeof type === 'string') {\r\n const { children, dangerouslySetInnerHTML, ...rest } = props || {};\r\n const attrParts: string[] = [];\r\n for (const [k, v] of Object.entries(rest as Record<string, any>)) {\r\n const name = k === 'className' ? 'class' : k === 'htmlFor' ? 'for' : k;\r\n if (typeof v === 'boolean') { if (v) attrParts.push(name); continue; }\r\n if (v == null) continue;\r\n if (k === 'style' && typeof v === 'object') {\r\n const css = Object.entries(v as Record<string, any>)\r\n .map(([p, val]) => \\`\\${p.replace(/[A-Z]/g, m => \\`-\\${m.toLowerCase()}\\`)}:\\${escapeHtml(String(val))}\\`)\r\n .join(';');\r\n attrParts.push(\\`style=\"\\${css}\"\\`);\r\n continue;\r\n }\r\n attrParts.push(\\`\\${name}=\"\\${escapeHtml(String(v))}\"\\`);\r\n }\r\n const attrStr = attrParts.length ? ' ' + attrParts.join(' ') : '';\r\n if (VOID_TAGS.has(type)) return \\`<\\${type}\\${attrStr} />\\`;\r\n const inner = dangerouslySetInnerHTML\r\n ? (dangerouslySetInnerHTML as any).__html\r\n : await renderNode(children ?? null, hydrated);\r\n return \\`<\\${type}\\${attrStr}>\\${inner}</\\${type}>\\`;\r\n }\r\n\r\n if (typeof type === 'function') {\r\n const clientId = CLIENT_COMPONENTS[type.name];\r\n if (clientId) {\r\n hydrated.add(clientId);\r\n const serializedProps = serializeProps(props ?? {});\r\n // Render with actual props so children/content appear in the SSR HTML.\r\n // Fall back to the build-time pre-rendered HTML if the component throws\r\n // (e.g. it references browser-only APIs during render).\r\n let ssrHtml: string;\r\n try {\r\n const result = await (type as Function)(props || {});\r\n ssrHtml = await renderNode(result, new Set());\r\n } catch {\r\n ssrHtml = PRERENDERED_HTML[clientId] ?? '';\r\n }\r\n return \\`<span data-hydrate-id=\"\\${clientId}\" data-hydrate-props=\"\\${escapeHtml(JSON.stringify(serializedProps))}\">\\${ssrHtml}</span>\\`;\r\n }\r\n const instance = type.prototype?.isReactComponent ? new (type as any)(props) : null;\r\n const result = instance ? instance.render() : await (type as Function)(props || {});\r\n return renderNode(result, hydrated);\r\n }\r\n\r\n return '';\r\n}\r\n\r\n// \u2500\u2500\u2500 Layout wrapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\nconst LAYOUT_COMPONENTS: Array<(props: any) => any> = [${layoutArrayItems}];\r\n\r\nfunction wrapWithLayouts(element: any): any {\r\n let el = element;\r\n for (let i = LAYOUT_COMPONENTS.length - 1; i >= 0; i--) {\r\n el = { type: LAYOUT_COMPONENTS[i], props: { children: el }, key: null, ref: null };\r\n }\r\n return el;\r\n}\r\n\r\n// \u2500\u2500\u2500 Handler \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\nexport default async function handler(req: IncomingMessage, res: ServerResponse): Promise<void> {\r\n try {\r\n const parsed = new URL(req.url || '/', 'http://localhost');\r\n const params: Record<string, string> = {};\r\n parsed.searchParams.forEach((v, k) => { params[k] = v; });\r\n const url = req.url || '/';\r\n\r\n const hydrated = new Set<string>();\r\n const pageElement = { type: __page__.default, props: params as any, key: null, ref: null };\r\n const wrapped = wrapWithLayouts(pageElement);\r\n\r\n let appHtml = '';\r\n const store = await runWithHtmlStore(async () => {\r\n appHtml = await renderNode(wrapped, hydrated);\r\n });\r\n\r\n const pageTitle = resolveTitle(store.titleOps, 'SSR App');\r\n const headLines: string[] = [\r\n ' <meta charset=\"utf-8\" />',\r\n ' <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />',\r\n \\` <title>\\${escapeHtml(pageTitle)}</title>\\`,\r\n ...(store.meta.length || store.link.length || store.style.length || store.script.length ? [\r\n ' <!--n-head-->',\r\n ...store.meta.map(renderMetaTag),\r\n ...store.link.map(renderLinkTag),\r\n ...store.style.map(renderStyleTag),\r\n ...store.script.map(renderScriptTag),\r\n ' <!--/n-head-->',\r\n ] : []),\r\n ];\r\n\r\n const runtimeData = JSON.stringify({\r\n hydrateIds: [...hydrated],\r\n allIds: ALL_CLIENT_IDS,\r\n url,\r\n params,\r\n debug: 'silent',\r\n }).replace(/</g, '\\\\u003c').replace(/>/g, '\\\\u003e').replace(/&/g, '\\\\u0026');\r\n\r\n const html = \\`<!DOCTYPE html>\r\n\\${openTag('html', store.htmlAttrs)}\r\n<head>\r\n\\${headLines.join('\\\\n')}\r\n</head>\r\n\\${openTag('body', store.bodyAttrs)}\r\n <div id=\"app\">\\${appHtml}</div>\r\n\r\n <script id=\"__n_data\" type=\"application/json\">\\${runtimeData}</script>\r\n\r\n <script type=\"importmap\">\r\n {\r\n \"imports\": {\r\n \"react\": \"/__n.js\",\r\n \"react-dom/client\": \"/__n.js\",\r\n \"react/jsx-runtime\": \"/__n.js\",\r\n \"nukejs\": \"/__n.js\"\r\n }\r\n }\r\n </script>\r\n\r\n <script type=\"module\">\r\n const { initRuntime } = await import('nukejs');\r\n const data = JSON.parse(document.getElementById('__n_data').textContent);\r\n await initRuntime(data);\r\n </script>\r\n</body>\r\n</html>\\`;\r\n\r\n res.statusCode = 200;\r\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\r\n res.end(html);\r\n } catch (err: any) {\r\n console.error('[page render error]', err);\r\n res.statusCode = 500;\r\n res.setHeader('Content-Type', 'text/plain; charset=utf-8');\r\n res.end('Internal Server Error');\r\n }\r\n}\r\n`.trimStart();\r\n}\r\n\r\n// \u2500\u2500\u2500 Bundle operations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Bundles an API route handler into a single self-contained ESM string.\r\n *\r\n * Writes a temporary adapter next to `absPath`, bundles them together with\r\n * esbuild (node_modules kept external), then removes the temp file.\r\n *\r\n * @returns The bundled ESM text ready to write to disk.\r\n */\r\nexport async function bundleApiHandler(absPath: string): Promise<string> {\r\n const adapterName = `_api_adapter_${crypto.randomBytes(4).toString('hex')}.ts`;\r\n const adapterPath = path.join(path.dirname(absPath), adapterName);\r\n\r\n fs.writeFileSync(adapterPath, makeApiAdapterSource(path.basename(absPath)));\r\n\r\n let text: string;\r\n try {\r\n const result = await build({\r\n entryPoints: [adapterPath],\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'node',\r\n target: 'node20',\r\n packages: 'external',\r\n write: false,\r\n });\r\n text = result.outputFiles[0].text;\r\n } finally {\r\n fs.unlinkSync(adapterPath);\r\n }\r\n return text;\r\n}\r\n\r\nexport interface PageBundleOptions {\r\n absPath: string;\r\n pagesDir: string;\r\n clientComponentNames: Record<string, string>;\r\n allClientIds: string[];\r\n layoutPaths: string[];\r\n prerenderedHtml: Record<string, string>;\r\n}\r\n\r\n/**\r\n * Bundles a server-component page into a single self-contained ESM string.\r\n *\r\n * Writes a temporary adapter next to `absPath` (so relative imports inside\r\n * the component resolve from the correct base directory), bundles it with\r\n * esbuild (React and all npm deps inlined, only Node built-ins stay external),\r\n * then removes the temp file.\r\n *\r\n * @returns The bundled ESM text ready to write to disk.\r\n */\r\nexport async function bundlePageHandler(opts: PageBundleOptions): Promise<string> {\r\n const { absPath, clientComponentNames, allClientIds, layoutPaths, prerenderedHtml } = opts;\r\n\r\n // The adapter is written next to the page file, so make every layout path\r\n // relative to that same directory. Absolute Windows paths like \"C:\\...\" in\r\n // import statements are not valid ESM URL schemes and throw\r\n // ERR_UNSUPPORTED_ESM_URL_SCHEME. Relative paths work on all platforms.\r\n const adapterName = `_page_adapter_${crypto.randomBytes(4).toString('hex')}.ts`;\r\n const adapterDir = path.dirname(absPath);\r\n const adapterPath = path.join(adapterDir, adapterName);\r\n\r\n const layoutImports = layoutPaths\r\n .map((lp, i) => {\r\n const rel = path.relative(adapterDir, lp).replace(/\\\\/g, '/');\r\n const importPath = rel.startsWith('.') ? rel : './' + rel;\r\n return `import __layout_${i}__ from ${JSON.stringify(importPath)};`;\r\n })\r\n .join('\\n');\r\n const layoutArrayItems = layoutPaths\r\n .map((_, i) => `__layout_${i}__`)\r\n .join(', ');\r\n\r\n fs.writeFileSync(adapterPath, makePageAdapterSource({\r\n pageImport: JSON.stringify('./' + path.basename(absPath)),\r\n layoutImports,\r\n clientComponentNames,\r\n allClientIds,\r\n layoutArrayItems,\r\n prerenderedHtml,\r\n }));\r\n\r\n let text: string;\r\n try {\r\n const result = await build({\r\n entryPoints: [adapterPath],\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'node',\r\n target: 'node20',\r\n jsx: 'automatic',\r\n external: [\r\n // Node built-ins only \u2014 all npm packages (react, nukejs, \u2026) are inlined\r\n 'node:*',\r\n 'http', 'https', 'fs', 'path', 'url', 'crypto', 'stream', 'buffer',\r\n 'events', 'util', 'os', 'net', 'tls', 'child_process', 'worker_threads',\r\n 'cluster', 'dgram', 'dns', 'readline', 'zlib', 'assert', 'module',\r\n 'perf_hooks', 'string_decoder', 'timers', 'async_hooks', 'v8', 'vm',\r\n ],\r\n define: { 'process.env.NODE_ENV': '\"production\"' },\r\n write: false,\r\n });\r\n text = result.outputFiles[0].text;\r\n } finally {\r\n fs.unlinkSync(adapterPath);\r\n }\r\n return text;\r\n}\r\n\r\n/**\r\n * Bundles every client component in `globalRegistry` to\r\n * `<staticDir>/__client-component/<id>.js`.\r\n *\r\n * Mirrors bundleClientComponent() in bundler.ts:\r\n * \u2022 browser ESM, JSX automatic\r\n * \u2022 react / react-dom/client / react/jsx-runtime kept external so the\r\n * importmap can resolve them to the already-loaded /__react.js bundle.\r\n */\r\nexport async function bundleClientComponents(\r\n globalRegistry: Map<string, string>,\r\n pagesDir: string,\r\n staticDir: string,\r\n): Promise<Map<string, string>> {\r\n if (globalRegistry.size === 0) return new Map();\r\n\r\n const outDir = path.join(staticDir, '__client-component');\r\n fs.mkdirSync(outDir, { recursive: true });\r\n\r\n const prerendered = new Map<string, string>(); // id \u2192 pre-rendered HTML\r\n\r\n for (const [id, filePath] of globalRegistry) {\r\n console.log(` bundling client ${id} (${path.relative(pagesDir, filePath)})`);\r\n\r\n // 1. Browser bundle \u2014 served to the client for hydration\r\n const browserResult = await build({\r\n entryPoints: [filePath],\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'browser',\r\n jsx: 'automatic',\r\n minify: true,\r\n external: ['react', 'react-dom/client', 'react/jsx-runtime'],\r\n define: { 'process.env.NODE_ENV': '\"production\"' },\r\n write: false,\r\n });\r\n fs.writeFileSync(path.join(outDir, `${id}.js`), browserResult.outputFiles[0].text);\r\n\r\n // 2. SSR pre-render \u2014 bundle for Node, import, renderToString, discard\r\n const ssrTmp = path.join(\r\n path.dirname(filePath),\r\n `_ssr_${id}_${crypto.randomBytes(4).toString('hex')}.mjs`,\r\n );\r\n try {\r\n const ssrResult = await build({\r\n entryPoints: [filePath],\r\n bundle: true,\r\n format: 'esm',\r\n platform: 'node',\r\n target: 'node20',\r\n jsx: 'automatic',\r\n packages: 'external',\r\n define: { 'process.env.NODE_ENV': '\"production\"' },\r\n write: false,\r\n });\r\n fs.writeFileSync(ssrTmp, ssrResult.outputFiles[0].text);\r\n\r\n const { default: Component } = await import(pathToFileURL(ssrTmp).href);\r\n const { createElement } = await import('react');\r\n const { renderToString } = await import('react-dom/server');\r\n\r\n prerendered.set(id, renderToString(createElement(Component, {})));\r\n console.log(` prerendered ${id}`);\r\n } catch (e) {\r\n //console.warn(` [SSR prerender failed for ${id}]`, e);\r\n prerendered.set(id, '');\r\n } finally {\r\n if (fs.existsSync(ssrTmp)) fs.unlinkSync(ssrTmp);\r\n }\r\n }\r\n\r\n console.log(` bundled ${globalRegistry.size} client component(s) \u2192 ${path.relative(process.cwd(), outDir)}/`);\r\n return prerendered;\r\n}\r\n\r\n/**\r\n * Builds a single combined browser bundle to `<staticDir>/__n.js`.\r\n *\r\n * Inlines the full React + ReactDOM runtime together with the NukeJS client\r\n * runtime (bundle.ts) so the browser only needs one file instead of two.\r\n * The importmap in every page points 'react', 'react-dom/client',\r\n * 'react/jsx-runtime', and 'nukejs' all to /__n.js, so dynamic imports\r\n * inside the runtime (e.g. `await import('react')`) hit the module cache\r\n * and return the same singleton that was already loaded.\r\n *\r\n * Dev mode (bundler.ts) keeps separate /__react.js and /__n.js files for\r\n * easier debugging \u2014 this function is production-only.\r\n */\r\nexport async function buildCombinedBundle(staticDir: string): Promise<void> {\r\n const nukeDir = path.dirname(fileURLToPath(import.meta.url));\r\n // In the dist/ directory the compiled file is bundle.js; in source it is bundle.ts.\r\n // Omit the .js extension when pointing at the compiled bundle \u2014 esbuild\r\n // resolves it correctly and avoids the double-extension chunk name (bundle.js.js)\r\n // that occurs when the import specifier already carries a .js suffix.\r\n const bundleFile = nukeDir.endsWith('dist') ? 'bundle' : 'bundle.ts';\r\n\r\n const result = await build({\r\n stdin: {\r\n contents: `\r\nimport React, {\r\n useState, useEffect, useContext, useReducer, useCallback, useMemo,\r\n useRef, useImperativeHandle, useLayoutEffect, useDebugValue,\r\n useDeferredValue, useTransition, useId, useSyncExternalStore,\r\n useInsertionEffect, createContext, forwardRef, memo, lazy,\r\n Suspense, Fragment, StrictMode, Component, PureComponent\r\n} from 'react';\r\nimport { jsx, jsxs } from 'react/jsx-runtime';\r\nimport { hydrateRoot, createRoot } from 'react-dom/client';\r\nexport { initRuntime, setupLocationChangeMonitor } from './${bundleFile}';\r\n\r\nexport {\r\n useState, useEffect, useContext, useReducer, useCallback, useMemo,\r\n useRef, useImperativeHandle, useLayoutEffect, useDebugValue,\r\n useDeferredValue, useTransition, useId, useSyncExternalStore,\r\n useInsertionEffect, createContext, forwardRef, memo, lazy,\r\n Suspense, Fragment, StrictMode, Component, PureComponent,\r\n hydrateRoot, createRoot, jsx, jsxs\r\n};\r\nexport default React;\r\n`,\r\n loader: 'ts',\r\n resolveDir: nukeDir,\r\n },\r\n bundle: true,\r\n write: false,\r\n treeShaking: true,\r\n minify: true,\r\n format: 'esm',\r\n jsx: 'automatic',\r\n alias: {\r\n react: path.dirname(fileURLToPath(import.meta.resolve('react/package.json'))),\r\n 'react-dom': path.dirname(fileURLToPath(import.meta.resolve('react-dom/package.json'))),\r\n },\r\n define: { 'process.env.NODE_ENV': '\"production\"' },\r\n });\r\n fs.writeFileSync(path.join(staticDir, '__n.js'), result.outputFiles[0].text);\r\n console.log(' built __n.js (react + runtime)');\r\n}\r\n\r\n// \u2500\u2500\u2500 Public static file copying \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/**\r\n * Recursively copies every file from `app/public/` into `destDir`,\r\n * preserving the directory structure.\r\n *\r\n * Called by both build-vercel.ts (dest = .vercel/output/static/) and\r\n * build-node.ts (dest = dist/static/) so that:\r\n *\r\n * app/public/favicon.ico \u2192 <destDir>/favicon.ico\r\n * app/public/images/logo.png \u2192 <destDir>/images/logo.png\r\n *\r\n * On Vercel, the Build Output API v3 serves everything in .vercel/output/static/\r\n * directly \u2014 no route entry needed, same as __react.js and __n.js.\r\n *\r\n * On Node, the serverEntry template serves files from dist/static/ with the\r\n * same MIME-type logic as the dev middleware.\r\n *\r\n * Skips silently when the public directory does not exist so projects without\r\n * one don't need any special configuration.\r\n */\r\nexport function copyPublicFiles(publicDir: string, destDir: string): void {\r\n if (!fs.existsSync(publicDir)) return;\r\n\r\n let count = 0;\r\n\r\n (function walk(src: string, dest: string) {\r\n fs.mkdirSync(dest, { recursive: true });\r\n for (const entry of fs.readdirSync(src, { withFileTypes: true })) {\r\n const srcPath = path.join(src, entry.name);\r\n const destPath = path.join(dest, entry.name);\r\n if (entry.isDirectory()) {\r\n walk(srcPath, destPath);\r\n } else {\r\n fs.copyFileSync(srcPath, destPath);\r\n count++;\r\n }\r\n }\r\n })(publicDir, destDir);\r\n\r\n if (count > 0) {\r\n console.log(` copied ${count} public file(s) \u2192 ${path.relative(process.cwd(), destDir)}/`);\r\n }\r\n}"],
5
+ "mappings": "AAcA,OAAO,QAAQ;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,YAAM,WAAW,KAAK,KAAK,MAAM,MAAM,IAAI;AAC3C,UAAI,MAAM,YAAY,GAAG;AACvB,aAAK,SAAS,QAAQ;AAAA,MACxB,OAAO;AACL,WAAG,aAAa,SAAS,QAAQ;AACjC;AAAA,MACF;AAAA,IACF;AAAA,EACF,GAAG,WAAW,OAAO;AAErB,MAAI,QAAQ,GAAG;AACb,YAAQ,IAAI,eAAe,KAAK,0BAAqB,KAAK,SAAS,QAAQ,IAAI,GAAG,OAAO,CAAC,GAAG;AAAA,EAC/F;AACF;",
6
6
  "names": []
7
7
  }
@@ -6,8 +6,7 @@ import {
6
6
  walkFiles,
7
7
  buildPages,
8
8
  bundleApiHandler,
9
- buildReactBundle,
10
- buildNukeBundle,
9
+ buildCombinedBundle,
11
10
  copyPublicFiles
12
11
  } from "./build-common.js";
13
12
  const OUT_DIR = path.resolve("dist");
@@ -49,8 +48,7 @@ fs.writeFileSync(
49
48
  path.join(OUT_DIR, "manifest.json"),
50
49
  JSON.stringify({ routes: manifest }, null, 2)
51
50
  );
52
- await buildReactBundle(STATIC_DIR);
53
- await buildNukeBundle(STATIC_DIR);
51
+ await buildCombinedBundle(STATIC_DIR);
54
52
  copyPublicFiles(PUBLIC_DIR, STATIC_DIR);
55
53
  const serverEntry = `
56
54
  import http from 'http';
@@ -107,9 +105,8 @@ const server = http.createServer(async (req, res) => {
107
105
  const url = req.url || '/';
108
106
  const clean = url.split('?')[0];
109
107
 
110
- // Internal __-prefixed static assets (/__react.js, /__n.js, /__client-component/*)
108
+ // Internal __-prefixed static assets (/__n.js, /__client-component/*)
111
109
  if (
112
- clean === '/__react.js' ||
113
110
  clean === '/__n.js' ||
114
111
  clean.startsWith('/__client-component/')
115
112
  ) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/build-node.ts"],
4
- "sourcesContent": ["import fs from 'fs';\r\nimport path from 'path';\r\n\r\nimport { loadConfig } from './config';\r\nimport {\r\n analyzeFile,\r\n walkFiles,\r\n buildPages,\r\n bundleApiHandler,\r\n buildReactBundle,\r\n buildNukeBundle,\r\n copyPublicFiles,\r\n type AnalyzedRoute,\r\n} from './build-common';\r\n\r\n// \u2500\u2500\u2500 Output directories \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst OUT_DIR = path.resolve('dist');\r\nconst API_DIR = path.join(OUT_DIR, 'api');\r\nconst PAGES_DIR_ = path.join(OUT_DIR, 'pages');\r\nconst STATIC_DIR = path.join(OUT_DIR, 'static');\r\n\r\nfs.mkdirSync(API_DIR, { recursive: true });\r\nfs.mkdirSync(PAGES_DIR_, { recursive: true });\r\nfs.mkdirSync(STATIC_DIR, { recursive: true });\r\n\r\n// \u2500\u2500\u2500 Config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst config = await loadConfig();\r\nconst SERVER_DIR = path.resolve(config.serverDir);\r\nconst PAGES_DIR = path.resolve('./app/pages');\r\nconst PUBLIC_DIR = path.resolve('./app/public');\r\n\r\n// \u2500\u2500\u2500 Route manifest \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Written to dist/manifest.json so the runtime HTTP server can dispatch\r\n// incoming requests to the correct pre-built handler module.\r\n\r\ninterface ManifestEntry {\r\n /** Regex string matching the URL path, e.g. '^/users/([^/]+)$' */\r\n srcRegex: string;\r\n /** Names of captured groups in srcRegex order */\r\n paramNames: string[];\r\n /** Path to the bundled handler relative to dist/, e.g. 'api/users/[id].mjs' */\r\n handler: string;\r\n type: 'api' | 'page';\r\n}\r\n\r\nconst manifest: ManifestEntry[] = [];\r\n\r\n// \u2500\u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/** Converts a funcPath like '/api/users/[id]' to a safe filename 'users/[id].mjs'. */\r\nfunction funcPathToFilename(funcPath: string, prefix: 'api' | 'page'): string {\r\n const rel = funcPath.replace(new RegExp(`^\\/${prefix}\\/`), '');\r\n return rel + '.mjs';\r\n}\r\n\r\n// \u2500\u2500\u2500 API routes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst apiFiles = walkFiles(SERVER_DIR);\r\nif (apiFiles.length === 0) console.warn(`\u26A0 No server files found in ${SERVER_DIR}`);\r\n\r\nconst apiRoutes = apiFiles\r\n .map(relPath => ({ ...analyzeFile(relPath, 'api'), absPath: path.join(SERVER_DIR, relPath) }))\r\n .sort((a, b) => b.specificity - a.specificity);\r\n\r\nfor (const { srcRegex, paramNames, funcPath, absPath } of apiRoutes) {\r\n console.log(` building ${path.relative(SERVER_DIR, absPath)} \u2192 ${funcPath}`);\r\n\r\n const filename = funcPathToFilename(funcPath, 'api');\r\n const outPath = path.join(API_DIR, filename);\r\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\r\n\r\n fs.writeFileSync(outPath, await bundleApiHandler(absPath));\r\n\r\n manifest.push({ srcRegex, paramNames, handler: path.join('api', filename), type: 'api' });\r\n}\r\n\r\n// \u2500\u2500\u2500 Page routes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst builtPages = await buildPages(PAGES_DIR, STATIC_DIR);\r\n\r\nfor (const { srcRegex, paramNames, funcPath, bundleText } of builtPages) {\r\n const filename = funcPathToFilename(funcPath, 'page');\r\n const outPath = path.join(PAGES_DIR_, filename);\r\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\r\n fs.writeFileSync(outPath, bundleText);\r\n\r\n manifest.push({ srcRegex, paramNames, handler: path.join('pages', filename), type: 'page' });\r\n}\r\n\r\n// \u2500\u2500\u2500 Route manifest \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Entries are already sorted most-specific first (both apiRoutes and buildPages\r\n// sort before their loops), so the server can match top-to-bottom.\r\n\r\nfs.writeFileSync(\r\n path.join(OUT_DIR, 'manifest.json'),\r\n JSON.stringify({ routes: manifest }, null, 2),\r\n);\r\n\r\n// \u2500\u2500\u2500 Static assets \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nawait buildReactBundle(STATIC_DIR);\r\nawait buildNukeBundle(STATIC_DIR);\r\ncopyPublicFiles(PUBLIC_DIR, STATIC_DIR);\r\n\r\n// \u2500\u2500\u2500 Server entry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// A thin HTTP server that reads manifest.json and dispatches requests to the\r\n// pre-built handler modules. Written to dist/index.mjs \u2014 run with:\r\n// node dist/index.mjs\r\n\r\nconst serverEntry = `\r\nimport http from 'http';\r\nimport path from 'path';\r\nimport fs from 'fs';\r\nimport { fileURLToPath, pathToFileURL } from 'url';\r\n\r\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\r\n\r\nconst { routes } = JSON.parse(\r\n fs.readFileSync(path.join(__dirname, 'manifest.json'), 'utf-8'),\r\n);\r\n\r\n// Pre-compile all route regexes once at startup.\r\nconst compiled = routes.map(r => ({ ...r, regex: new RegExp(r.srcRegex) }));\r\n\r\nconst STATIC_DIR = path.join(__dirname, 'static');\r\n\r\nconst MIME_MAP = {\r\n '.html': 'text/html; charset=utf-8',\r\n '.htm': 'text/html; charset=utf-8',\r\n '.css': 'text/css; charset=utf-8',\r\n '.js': 'application/javascript; charset=utf-8',\r\n '.mjs': 'application/javascript; charset=utf-8',\r\n '.cjs': 'application/javascript; charset=utf-8',\r\n '.map': 'application/json; charset=utf-8',\r\n '.json': 'application/json; charset=utf-8',\r\n '.xml': 'application/xml; charset=utf-8',\r\n '.txt': 'text/plain; charset=utf-8',\r\n '.csv': 'text/csv; charset=utf-8',\r\n '.png': 'image/png',\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.gif': 'image/gif',\r\n '.webp': 'image/webp',\r\n '.avif': 'image/avif',\r\n '.svg': 'image/svg+xml',\r\n '.ico': 'image/x-icon',\r\n '.bmp': 'image/bmp',\r\n '.woff': 'font/woff',\r\n '.woff2':'font/woff2',\r\n '.ttf': 'font/ttf',\r\n '.otf': 'font/otf',\r\n '.mp4': 'video/mp4',\r\n '.webm': 'video/webm',\r\n '.mp3': 'audio/mpeg',\r\n '.wav': 'audio/wav',\r\n '.ogg': 'audio/ogg',\r\n '.pdf': 'application/pdf',\r\n '.wasm': 'application/wasm',\r\n};\r\n\r\nconst server = http.createServer(async (req, res) => {\r\n const url = req.url || '/';\r\n const clean = url.split('?')[0];\r\n\r\n // Internal __-prefixed static assets (/__react.js, /__n.js, /__client-component/*)\r\n if (\r\n clean === '/__react.js' ||\r\n clean === '/__n.js' ||\r\n clean.startsWith('/__client-component/')\r\n ) {\r\n const filePath = path.join(STATIC_DIR, clean);\r\n if (fs.existsSync(filePath)) {\r\n const ext = path.extname(filePath);\r\n res.setHeader('Content-Type', MIME_MAP[ext] ?? 'application/javascript');\r\n res.end(fs.readFileSync(filePath));\r\n return;\r\n }\r\n res.statusCode = 404;\r\n res.end('Not found');\r\n return;\r\n }\r\n\r\n // User public files from app/public/. path.join normalises '..' segments\r\n // before the startsWith guard, preventing directory traversal.\r\n {\r\n const candidate = path.join(STATIC_DIR, clean);\r\n const staticBase = STATIC_DIR.endsWith(path.sep) ? STATIC_DIR : STATIC_DIR + path.sep;\r\n const safe = candidate.startsWith(staticBase) && candidate !== STATIC_DIR;\r\n if (safe && fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {\r\n const ext = path.extname(candidate);\r\n res.setHeader('Content-Type', MIME_MAP[ext] ?? 'application/octet-stream');\r\n res.end(fs.readFileSync(candidate));\r\n return;\r\n }\r\n }\r\n\r\n // Route manifest dispatch.\r\n for (const { regex, paramNames, handler } of compiled) {\r\n const m = clean.match(regex);\r\n if (!m) continue;\r\n\r\n const params = Object.fromEntries(paramNames.map((n, i) => [n, m[i + 1]]));\r\n const qs = new URLSearchParams({ ...params, ...Object.fromEntries(new URL(url, 'http://localhost').searchParams) });\r\n req.url = clean + (qs.toString() ? '?' + qs.toString() : '');\r\n\r\n const mod = await import(pathToFileURL(path.join(__dirname, handler)).href);\r\n await mod.default(req, res);\r\n return;\r\n }\r\n\r\n res.statusCode = 404;\r\n res.setHeader('Content-Type', 'text/plain');\r\n res.end('Not found');\r\n});\r\n\r\nconst PORT = Number(process.env.PORT ?? 3000);\r\nserver.listen(PORT, () => {\r\n console.log('nukejs built server listening on http://localhost:' + PORT);\r\n});\r\n`.trimStart();\r\n\r\nfs.writeFileSync(path.join(OUT_DIR, 'index.mjs'), serverEntry);\r\n\r\nconsole.log(`\\n\u2713 Node build complete \u2014 ${manifest.length} route(s) \u2192 dist/`);\r\nconsole.log(` run with: node dist/index.mjs`);"],
5
- "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAIP,MAAM,UAAa,KAAK,QAAQ,MAAM;AACtC,MAAM,UAAa,KAAK,KAAK,SAAS,KAAK;AAC3C,MAAM,aAAa,KAAK,KAAK,SAAS,OAAO;AAC7C,MAAM,aAAa,KAAK,KAAK,SAAS,QAAQ;AAE9C,GAAG,UAAU,SAAY,EAAE,WAAW,KAAK,CAAC;AAC5C,GAAG,UAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AAC5C,GAAG,UAAU,YAAY,EAAE,WAAW,KAAK,CAAC;AAI5C,MAAM,SAAa,MAAM,WAAW;AACpC,MAAM,aAAa,KAAK,QAAQ,OAAO,SAAS;AAChD,MAAM,YAAa,KAAK,QAAQ,aAAa;AAC7C,MAAM,aAAa,KAAK,QAAQ,cAAc;AAgB9C,MAAM,WAA4B,CAAC;AAKnC,SAAS,mBAAmB,UAAkB,QAAgC;AAC5E,QAAM,MAAM,SAAS,QAAQ,IAAI,OAAO,KAAM,MAAM,GAAI,GAAG,EAAE;AAC7D,SAAO,MAAM;AACf;AAIA,MAAM,WAAW,UAAU,UAAU;AACrC,IAAI,SAAS,WAAW,EAAG,SAAQ,KAAK,oCAA+B,UAAU,EAAE;AAEnF,MAAM,YAAY,SACf,IAAI,cAAY,EAAE,GAAG,YAAY,SAAS,KAAK,GAAG,SAAS,KAAK,KAAK,YAAY,OAAO,EAAE,EAAE,EAC5F,KAAK,CAAC,GAAG,MAAM,EAAE,cAA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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8GlB,UAAU;AAEZ,GAAG,cAAc,KAAK,KAAK,SAAS,WAAW,GAAG,WAAW;AAE7D,QAAQ,IAAI;AAAA,oCAA6B,SAAS,MAAM,wBAAmB;AAC3E,QAAQ,IAAI,iCAAiC;",
4
+ "sourcesContent": ["import fs from 'fs';\r\nimport path from 'path';\r\n\r\nimport { loadConfig } from './config';\r\nimport {\r\n analyzeFile,\r\n walkFiles,\r\n buildPages,\r\n bundleApiHandler,\r\n buildCombinedBundle,\r\n copyPublicFiles,\r\n type AnalyzedRoute,\r\n} from './build-common';\r\n\r\n// \u2500\u2500\u2500 Output directories \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst OUT_DIR = path.resolve('dist');\r\nconst API_DIR = path.join(OUT_DIR, 'api');\r\nconst PAGES_DIR_ = path.join(OUT_DIR, 'pages');\r\nconst STATIC_DIR = path.join(OUT_DIR, 'static');\r\n\r\nfs.mkdirSync(API_DIR, { recursive: true });\r\nfs.mkdirSync(PAGES_DIR_, { recursive: true });\r\nfs.mkdirSync(STATIC_DIR, { recursive: true });\r\n\r\n// \u2500\u2500\u2500 Config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst config = await loadConfig();\r\nconst SERVER_DIR = path.resolve(config.serverDir);\r\nconst PAGES_DIR = path.resolve('./app/pages');\r\nconst PUBLIC_DIR = path.resolve('./app/public');\r\n\r\n// \u2500\u2500\u2500 Route manifest \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Written to dist/manifest.json so the runtime HTTP server can dispatch\r\n// incoming requests to the correct pre-built handler module.\r\n\r\ninterface ManifestEntry {\r\n /** Regex string matching the URL path, e.g. '^/users/([^/]+)$' */\r\n srcRegex: string;\r\n /** Names of captured groups in srcRegex order */\r\n paramNames: string[];\r\n /** Path to the bundled handler relative to dist/, e.g. 'api/users/[id].mjs' */\r\n handler: string;\r\n type: 'api' | 'page';\r\n}\r\n\r\nconst manifest: ManifestEntry[] = [];\r\n\r\n// \u2500\u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/** Converts a funcPath like '/api/users/[id]' to a safe filename 'users/[id].mjs'. */\r\nfunction funcPathToFilename(funcPath: string, prefix: 'api' | 'page'): string {\r\n const rel = funcPath.replace(new RegExp(`^\\/${prefix}\\/`), '');\r\n return rel + '.mjs';\r\n}\r\n\r\n// \u2500\u2500\u2500 API routes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst apiFiles = walkFiles(SERVER_DIR);\r\nif (apiFiles.length === 0) console.warn(`\u26A0 No server files found in ${SERVER_DIR}`);\r\n\r\nconst apiRoutes = apiFiles\r\n .map(relPath => ({ ...analyzeFile(relPath, 'api'), absPath: path.join(SERVER_DIR, relPath) }))\r\n .sort((a, b) => b.specificity - a.specificity);\r\n\r\nfor (const { srcRegex, paramNames, funcPath, absPath } of apiRoutes) {\r\n console.log(` building ${path.relative(SERVER_DIR, absPath)} \u2192 ${funcPath}`);\r\n\r\n const filename = funcPathToFilename(funcPath, 'api');\r\n const outPath = path.join(API_DIR, filename);\r\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\r\n\r\n fs.writeFileSync(outPath, await bundleApiHandler(absPath));\r\n\r\n manifest.push({ srcRegex, paramNames, handler: path.join('api', filename), type: 'api' });\r\n}\r\n\r\n// \u2500\u2500\u2500 Page routes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nconst builtPages = await buildPages(PAGES_DIR, STATIC_DIR);\r\n\r\nfor (const { srcRegex, paramNames, funcPath, bundleText } of builtPages) {\r\n const filename = funcPathToFilename(funcPath, 'page');\r\n const outPath = path.join(PAGES_DIR_, filename);\r\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\r\n fs.writeFileSync(outPath, bundleText);\r\n\r\n manifest.push({ srcRegex, paramNames, handler: path.join('pages', filename), type: 'page' });\r\n}\r\n\r\n// \u2500\u2500\u2500 Route manifest \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// Entries are already sorted most-specific first (both apiRoutes and buildPages\r\n// sort before their loops), so the server can match top-to-bottom.\r\n\r\nfs.writeFileSync(\r\n path.join(OUT_DIR, 'manifest.json'),\r\n JSON.stringify({ routes: manifest }, null, 2),\r\n);\r\n\r\n// \u2500\u2500\u2500 Static assets \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\nawait buildCombinedBundle(STATIC_DIR);\r\ncopyPublicFiles(PUBLIC_DIR, STATIC_DIR);\r\n\r\n// \u2500\u2500\u2500 Server entry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n// A thin HTTP server that reads manifest.json and dispatches requests to the\r\n// pre-built handler modules. Written to dist/index.mjs \u2014 run with:\r\n// node dist/index.mjs\r\n\r\nconst serverEntry = `\r\nimport http from 'http';\r\nimport path from 'path';\r\nimport fs from 'fs';\r\nimport { fileURLToPath, pathToFileURL } from 'url';\r\n\r\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\r\n\r\nconst { routes } = JSON.parse(\r\n fs.readFileSync(path.join(__dirname, 'manifest.json'), 'utf-8'),\r\n);\r\n\r\n// Pre-compile all route regexes once at startup.\r\nconst compiled = routes.map(r => ({ ...r, regex: new RegExp(r.srcRegex) }));\r\n\r\nconst STATIC_DIR = path.join(__dirname, 'static');\r\n\r\nconst MIME_MAP = {\r\n '.html': 'text/html; charset=utf-8',\r\n '.htm': 'text/html; charset=utf-8',\r\n '.css': 'text/css; charset=utf-8',\r\n '.js': 'application/javascript; charset=utf-8',\r\n '.mjs': 'application/javascript; charset=utf-8',\r\n '.cjs': 'application/javascript; charset=utf-8',\r\n '.map': 'application/json; charset=utf-8',\r\n '.json': 'application/json; charset=utf-8',\r\n '.xml': 'application/xml; charset=utf-8',\r\n '.txt': 'text/plain; charset=utf-8',\r\n '.csv': 'text/csv; charset=utf-8',\r\n '.png': 'image/png',\r\n '.jpg': 'image/jpeg',\r\n '.jpeg': 'image/jpeg',\r\n '.gif': 'image/gif',\r\n '.webp': 'image/webp',\r\n '.avif': 'image/avif',\r\n '.svg': 'image/svg+xml',\r\n '.ico': 'image/x-icon',\r\n '.bmp': 'image/bmp',\r\n '.woff': 'font/woff',\r\n '.woff2':'font/woff2',\r\n '.ttf': 'font/ttf',\r\n '.otf': 'font/otf',\r\n '.mp4': 'video/mp4',\r\n '.webm': 'video/webm',\r\n '.mp3': 'audio/mpeg',\r\n '.wav': 'audio/wav',\r\n '.ogg': 'audio/ogg',\r\n '.pdf': 'application/pdf',\r\n '.wasm': 'application/wasm',\r\n};\r\n\r\nconst server = http.createServer(async (req, res) => {\r\n const url = req.url || '/';\r\n const clean = url.split('?')[0];\r\n\r\n // Internal __-prefixed static assets (/__n.js, /__client-component/*)\r\n if (\r\n clean === '/__n.js' ||\r\n clean.startsWith('/__client-component/')\r\n ) {\r\n const filePath = path.join(STATIC_DIR, clean);\r\n if (fs.existsSync(filePath)) {\r\n const ext = path.extname(filePath);\r\n res.setHeader('Content-Type', MIME_MAP[ext] ?? 'application/javascript');\r\n res.end(fs.readFileSync(filePath));\r\n return;\r\n }\r\n res.statusCode = 404;\r\n res.end('Not found');\r\n return;\r\n }\r\n\r\n // User public files from app/public/. path.join normalises '..' segments\r\n // before the startsWith guard, preventing directory traversal.\r\n {\r\n const candidate = path.join(STATIC_DIR, clean);\r\n const staticBase = STATIC_DIR.endsWith(path.sep) ? STATIC_DIR : STATIC_DIR + path.sep;\r\n const safe = candidate.startsWith(staticBase) && candidate !== STATIC_DIR;\r\n if (safe && fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {\r\n const ext = path.extname(candidate);\r\n res.setHeader('Content-Type', MIME_MAP[ext] ?? 'application/octet-stream');\r\n res.end(fs.readFileSync(candidate));\r\n return;\r\n }\r\n }\r\n\r\n // Route manifest dispatch.\r\n for (const { regex, paramNames, handler } of compiled) {\r\n const m = clean.match(regex);\r\n if (!m) continue;\r\n\r\n const params = Object.fromEntries(paramNames.map((n, i) => [n, m[i + 1]]));\r\n const qs = new URLSearchParams({ ...params, ...Object.fromEntries(new URL(url, 'http://localhost').searchParams) });\r\n req.url = clean + (qs.toString() ? '?' + qs.toString() : '');\r\n\r\n const mod = await import(pathToFileURL(path.join(__dirname, handler)).href);\r\n await mod.default(req, res);\r\n return;\r\n }\r\n\r\n res.statusCode = 404;\r\n res.setHeader('Content-Type', 'text/plain');\r\n res.end('Not found');\r\n});\r\n\r\nconst PORT = Number(process.env.PORT ?? 3000);\r\nserver.listen(PORT, () => {\r\n console.log('nukejs built server listening on http://localhost:' + PORT);\r\n});\r\n`.trimStart();\r\n\r\nfs.writeFileSync(path.join(OUT_DIR, 'index.mjs'), serverEntry);\r\n\r\nconsole.log(`\\n\u2713 Node build complete \u2014 ${manifest.length} route(s) \u2192 dist/`);\r\nconsole.log(` run with: node dist/index.mjs`);"],
5
+ "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAIP,MAAM,UAAa,KAAK,QAAQ,MAAM;AACtC,MAAM,UAAa,KAAK,KAAK,SAAS,KAAK;AAC3C,MAAM,aAAa,KAAK,KAAK,SAAS,OAAO;AAC7C,MAAM,aAAa,KAAK,KAAK,SAAS,QAAQ;AAE9C,GAAG,UAAU,SAAY,EAAE,WAAW,KAAK,CAAC;AAC5C,GAAG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,iCAAiC;",
6
6
  "names": []
7
7
  }
@@ -12,8 +12,7 @@ import {
12
12
  findPageLayouts,
13
13
  buildPerPageRegistry,
14
14
  makePageAdapterSource,
15
- buildReactBundle,
16
- buildNukeBundle,
15
+ buildCombinedBundle,
17
16
  copyPublicFiles
18
17
  } from "./build-common.js";
19
18
  const OUTPUT_DIR = path.resolve(".vercel/output");
@@ -267,8 +266,7 @@ fs.writeFileSync(
267
266
  path.resolve("vercel.json"),
268
267
  JSON.stringify({ runtime: "nodejs20.x" }, null, 2)
269
268
  );
270
- await buildReactBundle(STATIC_DIR);
271
- await buildNukeBundle(STATIC_DIR);
269
+ await buildCombinedBundle(STATIC_DIR);
272
270
  copyPublicFiles(PUBLIC_DIR, STATIC_DIR);
273
271
  const fnCount = (apiRoutes.length > 0 ? 1 : 0) + (serverPages.length > 0 ? 1 : 0);
274
272
  console.log(`