@teyik0/furin 0.2.0-alpha.2 → 0.2.0-alpha.3

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.
Files changed (132) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/bun.d.ts +3 -0
  4. package/dist/adapter/static.d.ts +3 -0
  5. package/dist/build/client.d.ts +25 -0
  6. package/dist/build/compile-entry.d.ts +9 -0
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +38 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +24 -0
  11. package/dist/build/index.d.ts +8 -0
  12. package/dist/build/index.js +8106 -0
  13. package/dist/build/route-types.d.ts +23 -0
  14. package/dist/build/scan-server.d.ts +8 -0
  15. package/dist/build/server-routes-entry.d.ts +13 -0
  16. package/dist/build/server-routes-entry.ts +36 -0
  17. package/dist/build/shared.d.ts +12 -0
  18. package/dist/build/ssg-cache.d.ts +4 -0
  19. package/dist/build/types.d.ts +80 -0
  20. package/dist/cli/config.d.ts +9 -0
  21. package/dist/cli/index.d.ts +2 -0
  22. package/dist/cli/index.js +8097 -0
  23. package/dist/client/boundaries.d.ts +117 -0
  24. package/dist/client/default-screens.d.ts +17 -0
  25. package/dist/client/link.d.ts +22 -0
  26. package/dist/client/link.js +4244 -0
  27. package/dist/client/router/boundary-tree.d.ts +26 -0
  28. package/dist/client/router/context.d.ts +8 -0
  29. package/dist/client/router/history.d.ts +9 -0
  30. package/dist/client/router/index.d.ts +11 -0
  31. package/dist/client/router/link-utils.d.ts +53 -0
  32. package/dist/client/router/navigation.d.ts +10 -0
  33. package/dist/client/router/provider.d.ts +4 -0
  34. package/dist/client/router/search/index.d.ts +18 -0
  35. package/dist/client/router/search-store.d.ts +21 -0
  36. package/dist/client/router/spa-response.d.ts +58 -0
  37. package/dist/client/router/types.d.ts +292 -0
  38. package/dist/client/server-error.d.ts +12 -0
  39. package/dist/client/sync.d.ts +25 -0
  40. package/dist/client.d.ts +243 -0
  41. package/dist/client.js +140 -0
  42. package/dist/config.d.ts +57 -0
  43. package/dist/config.js +29 -0
  44. package/dist/env.d.ts +50 -0
  45. package/dist/furin.d.ts +77 -0
  46. package/dist/furin.js +8693 -0
  47. package/dist/plugin/index.d.ts +20 -0
  48. package/dist/plugin/index.js +1500 -0
  49. package/dist/plugin/transform-client.d.ts +10 -0
  50. package/dist/server/auto-invalidate/index.d.ts +4 -0
  51. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  52. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  53. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  54. package/dist/server/auto-invalidate/types.d.ts +12 -0
  55. package/dist/server/cache/dev-loader.d.ts +28 -0
  56. package/dist/server/cache/index.d.ts +10 -0
  57. package/dist/server/cache/invalidation.d.ts +12 -0
  58. package/dist/server/cache/isr-ssg.d.ts +26 -0
  59. package/dist/server/cache/isr.d.ts +6 -0
  60. package/dist/server/cache/registry.d.ts +5 -0
  61. package/dist/server/cache/route-cache.d.ts +26 -0
  62. package/dist/server/cache/ssg.d.ts +5 -0
  63. package/dist/server/context-logger.d.ts +28 -0
  64. package/dist/server/dev-inspector.d.ts +89 -0
  65. package/dist/server/dev-page-plugin.d.ts +112 -0
  66. package/dist/server/internal.d.ts +35 -0
  67. package/dist/server/internal.js +17 -0
  68. package/dist/server/lang-detect.d.ts +5 -0
  69. package/dist/server/render/assemble.d.ts +49 -0
  70. package/dist/server/render/element.d.ts +24 -0
  71. package/dist/server/render/index.d.ts +7 -0
  72. package/dist/server/render/index.ts +22 -0
  73. package/dist/server/render/isr.d.ts +4 -0
  74. package/dist/server/render/loaders.d.ts +64 -0
  75. package/dist/server/render/not-found.d.ts +6 -0
  76. package/dist/server/render/shell.d.ts +39 -0
  77. package/dist/server/render/shell.ts +202 -0
  78. package/dist/server/render/ssg.d.ts +9 -0
  79. package/dist/server/render/ssr.d.ts +108 -0
  80. package/dist/server/render/template.d.ts +6 -0
  81. package/dist/server/router/discovery.d.ts +16 -0
  82. package/dist/server/router/hmr.d.ts +65 -0
  83. package/dist/server/router/index.d.ts +6 -0
  84. package/dist/server/router/index.js +27 -0
  85. package/dist/server/router/index.ts +28 -0
  86. package/dist/server/router/patterns.d.ts +40 -0
  87. package/dist/server/router/plugin.d.ts +21 -0
  88. package/dist/server/router/schemas.d.ts +59 -0
  89. package/dist/server/router/types.d.ts +60 -0
  90. package/dist/server/runtime-env.d.ts +3 -0
  91. package/dist/server/runtime-env.js +10 -0
  92. package/dist/server/sync/config.d.ts +6 -0
  93. package/dist/server/sync/index.d.ts +4 -0
  94. package/dist/server/sync/plugin.d.ts +369 -0
  95. package/dist/server/sync/stream.d.ts +47 -0
  96. package/dist/shared/await.d.ts +67 -0
  97. package/dist/shared/deferred-ndjson.d.ts +32 -0
  98. package/dist/shared/digest.d.ts +16 -0
  99. package/dist/shared/error.d.ts +37 -0
  100. package/dist/shared/not-found.d.ts +19 -0
  101. package/dist/shared/search-params.d.ts +17 -0
  102. package/dist/shared/utils/ast-walk.d.ts +18 -0
  103. package/dist/shared/utils/index.d.ts +13 -0
  104. package/package.json +5 -5
  105. package/src/adapter/README.md +13 -13
  106. package/src/build/client.ts +152 -152
  107. package/src/build/compile-entry.ts +109 -109
  108. package/src/build/entry-template.ts +156 -156
  109. package/src/build/hydrate.ts +340 -337
  110. package/src/build/index.ts +152 -152
  111. package/src/build/route-types.ts +145 -145
  112. package/src/build/scan-server.ts +95 -95
  113. package/src/build/server-routes-entry.ts +36 -36
  114. package/src/build/shared.ts +80 -79
  115. package/src/build/ssg-cache.ts +32 -32
  116. package/src/build/types.ts +89 -89
  117. package/src/client/router/link-utils.ts +184 -177
  118. package/src/client/router/provider.tsx +804 -759
  119. package/src/client/router/types.ts +276 -271
  120. package/src/client/sync.ts +98 -0
  121. package/src/client.ts +369 -355
  122. package/src/furin.ts +465 -444
  123. package/src/server/auto-invalidate/runtime.ts +134 -133
  124. package/src/server/dev-page-plugin.ts +454 -449
  125. package/src/server/render/assemble.ts +160 -133
  126. package/src/server/render/isr.ts +323 -317
  127. package/src/server/render/ssr.ts +585 -583
  128. package/src/server/router/plugin.ts +384 -384
  129. package/src/server/sync/config.ts +29 -0
  130. package/src/server/sync/index.ts +14 -0
  131. package/src/server/sync/plugin.ts +108 -0
  132. package/src/server/sync/stream.ts +144 -0
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Result returned by `parseDeferredNdjson`.
3
+ */
4
+ export interface DeferredNdjsonResult {
5
+ /**
6
+ * Deferred promises keyed by their field name. Each Promise resolves (or
7
+ * rejects) once the corresponding data is available. In the SSR case the
8
+ * promises are already settled (serialised by `toCrossJSONAsync`). For
9
+ * streaming endpoints they will settle as the server flushes resolution
10
+ * chunks.
11
+ */
12
+ deferredPromises: Record<string, Promise<unknown>>;
13
+ /** Scalar/sync values from the loader — available immediately. */
14
+ syncData: Record<string, unknown>;
15
+ }
16
+ /**
17
+ * Parses an NDJSON stream produced by `/_furin/data`.
18
+ *
19
+ * Protocol (v1 — single-line, all-resolved):
20
+ * Line 0 — `JSON.stringify(await toCrossJSONAsync(loaderData))`
21
+ *
22
+ * The CrossJSON node is deserialised with `fromCrossJSON`. Values that are
23
+ * Promises (seroval type 12) land in `deferredPromises`; everything else
24
+ * lands in `syncData`.
25
+ *
26
+ * @param stream - A `ReadableStream<Uint8Array>` from `fetch().body`.
27
+ * @param signal - AbortSignal that, when aborted, cancels the reader and
28
+ * rejects every still-pending deferred promise with an
29
+ * `AbortError`. Pass `undefined` to opt out (no implicit
30
+ * default — see CLAUDE.md).
31
+ */
32
+ export declare function parseDeferredNdjson(stream: ReadableStream<Uint8Array>, signal: AbortSignal | undefined): Promise<DeferredNdjsonResult>;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Computes a deterministic, opaque 10-hex-character digest for an error.
3
+ *
4
+ * Purpose: render this digest in client-facing error UIs (e.g. `Error ID:
5
+ * a3f2b9c1d8`) and log the same digest alongside the full stack on the server,
6
+ * so support can correlate user reports with server logs without leaking stack
7
+ * traces or sensitive message content to the browser.
8
+ *
9
+ * Deterministic: identical error message + stack ⇒ identical digest across
10
+ * restarts, processes, and environments (server + client).
11
+ *
12
+ * Uses a pure-JS 53-bit hash so the function works identically in Bun and in
13
+ * the browser — `computeErrorDigest` is called from `FurinErrorBoundary`, which
14
+ * runs on both sides.
15
+ */
16
+ export declare function computeErrorDigest(err: unknown): string;
@@ -0,0 +1,37 @@
1
+ import type { FC } from "react";
2
+ export interface ErrorProps {
3
+ error: {
4
+ /** Safe user-facing message. */
5
+ message: string;
6
+ /**
7
+ * Opaque 10-hex-char hash of the original error. The same digest appears
8
+ * in the server logs next to the full stack trace, so support can
9
+ * correlate a user-reported error ID with server-side diagnostics
10
+ * without leaking stack traces to the browser.
11
+ */
12
+ digest: string;
13
+ /**
14
+ * HTTP status associated with the error.
15
+ * - For thrown `Response` objects with a 4xx/5xx status: the response's
16
+ * status (e.g. 401, 403, 404, 500).
17
+ * - For all other errors (thrown `Error`, non-Error throws, shell-render
18
+ * crashes): always `500`.
19
+ *
20
+ * Always present so consumers never need a `?? 500` fallback. Note that
21
+ * `prepared.status` is honoured ONLY for loader-time errors. If a Suspense
22
+ * boundary throws AFTER the SSR shell has flushed (i.e. during streaming),
23
+ * the HTTP status cannot be changed and the user-visible status here may
24
+ * differ from the actual response code.
25
+ */
26
+ status: number;
27
+ };
28
+ /**
29
+ * Clears the nearest FurinErrorBoundary's error state, remounting its
30
+ * children. On the client this re-runs the route's loader; on the server
31
+ * it's a no-op (the request has already produced output by the time
32
+ * `reset` could run).
33
+ */
34
+ reset: () => void;
35
+ }
36
+ export type ErrorComponent = FC<ErrorProps>;
37
+ export declare function getPublicErrorMessage(error: Error | unknown): string;
@@ -0,0 +1,19 @@
1
+ import type { FC } from "react";
2
+ export interface NotFoundOptions {
3
+ data?: unknown;
4
+ message?: string;
5
+ }
6
+ export interface NotFoundProps {
7
+ error: {
8
+ message?: string;
9
+ data?: unknown;
10
+ };
11
+ }
12
+ export type NotFoundComponent = FC<NotFoundProps>;
13
+ export declare class FurinNotFoundError extends Error {
14
+ readonly __furinBrand: "FURIN_NOT_FOUND";
15
+ readonly data: unknown;
16
+ constructor(options: NotFoundOptions | undefined);
17
+ }
18
+ export declare function notFound(options: NotFoundOptions | undefined): never;
19
+ export declare function isNotFoundError(err: unknown): err is FurinNotFoundError;
@@ -0,0 +1,17 @@
1
+ export type SearchParamValue = string | number | boolean | null | undefined | SearchParamValue[] | {
2
+ [key: string]: SearchParamValue;
3
+ };
4
+ export interface SearchParamsInput {
5
+ [key: string]: SearchParamValue;
6
+ }
7
+ export interface SearchRouteMetadata {
8
+ pattern: string;
9
+ regex: RegExp;
10
+ searchDefaults?: SearchParamsInput;
11
+ }
12
+ export declare function stripSearchDefaults(search: SearchParamsInput, defaults: SearchParamsInput | undefined): SearchParamsInput;
13
+ export declare function appendSearchParamValue(params: URLSearchParams, key: string, value: unknown): void;
14
+ export declare function buildSearchParams(search: SearchParamsInput, defaults?: SearchParamsInput): URLSearchParams;
15
+ export declare function collectSearchDefaults(schema: unknown): SearchParamsInput | undefined;
16
+ export declare function findSearchDefaults(pathname: string, routes: readonly SearchRouteMetadata[]): SearchParamsInput | undefined;
17
+ export declare function findSearchDefaultsForRouteTarget(to: string, routes: readonly SearchRouteMetadata[]): SearchParamsInput | undefined;
@@ -0,0 +1,18 @@
1
+ import type { BaseNode, Node as YukuNode } from "yuku-parser";
2
+ /**
3
+ * Minimal ESTree node interface used by AST-walking utilities across the
4
+ * framework (build scanning, client transform, etc.).
5
+ */
6
+ export interface AstNode extends BaseNode {
7
+ body?: AstNode[];
8
+ type: YukuNode["type"] | string;
9
+ [key: string]: unknown;
10
+ }
11
+ /**
12
+ * Walks an ESTree-compatible AST node recursively, calling `visitor` for every
13
+ * node that has a `type` property.
14
+ *
15
+ * Arrays are traversed element-by-element. The keys `type`, `start` and `end`
16
+ * are skipped so that the visitor is only invoked on genuine child nodes.
17
+ */
18
+ export declare function walkAST(node: unknown, visitor: (n: AstNode) => void): void;
@@ -0,0 +1,13 @@
1
+ import type { RuntimePage, RuntimeRoute } from "../../client";
2
+ export declare function isFurinPage(value: unknown): value is RuntimePage;
3
+ export declare function isFurinRoute(value: unknown): value is RuntimeRoute;
4
+ export declare function collectRouteChainFromRoute(route: RuntimeRoute): RuntimeRoute[];
5
+ export declare function hasCycle(route: RuntimeRoute): boolean;
6
+ /**
7
+ * Maps over `items` with a bounded worker pool, preserving input order.
8
+ * Use whenever an `await Promise.all(items.map(...))` would open as many
9
+ * concurrent async operations as there are items — unbounded fan-out can
10
+ * exhaust file descriptors, sockets, or memory on large inputs.
11
+ */
12
+ export declare function mapWithConcurrency<T, R>(items: readonly T[], concurrency: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
13
+ export declare function validateRouteChain(chain: RuntimeRoute[], root: RuntimeRoute, pagePath?: string): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teyik0/furin",
3
- "version": "0.2.0-alpha.2",
3
+ "version": "0.2.0-alpha.3",
4
4
  "description": "React meta-framework powered by Elysia and Bun with file-based routing, SSR, SSG, and ISR.",
5
5
  "license": "MIT",
6
6
  "author": "teyik0",
@@ -97,16 +97,16 @@
97
97
  "@elysiajs/static": "^1.4.10",
98
98
  "magic-string": "^0.30.21",
99
99
  "seroval": "^1.5.4",
100
- "yuku-parser": "^0.5.37"
100
+ "yuku-parser": "^0.5.43"
101
101
  },
102
102
  "devDependencies": {
103
103
  "@types/react": "^19.2.17",
104
104
  "@types/react-dom": "^19.2.3",
105
- "expect-type": "^1.3.0"
105
+ "expect-type": "^1.4.0"
106
106
  },
107
107
  "peerDependencies": {
108
- "elysia": "^1.4.28",
109
- "evlog": "^2.19.1",
108
+ "elysia": "^1.4.29",
109
+ "evlog": "^2.19.2",
110
110
  "react": "^19.2.7",
111
111
  "react-dom": "^19.2.7"
112
112
  }
@@ -1,13 +1,13 @@
1
- ## Bun adapter
2
-
3
- Goal is having 3 modes:
4
-
5
- - generate server.js + client/
6
- - generate server (compiled to binary) + client/
7
- - generate server (compiled to binary with client/ [embeded](https://bun.com/docs/bundler/executables.md))
8
-
9
- All should be portable.
10
-
11
- ## Cloudflare adapter
12
-
13
- ## Vercel adapter
1
+ ## Bun adapter
2
+
3
+ Goal is having 3 modes:
4
+
5
+ - generate server.js + client/
6
+ - generate server (compiled to binary) + client/
7
+ - generate server (compiled to binary with client/ [embeded](https://bun.com/docs/bundler/executables.md))
8
+
9
+ All should be portable.
10
+
11
+ ## Cloudflare adapter
12
+
13
+ ## Vercel adapter
@@ -1,152 +1,152 @@
1
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
- import { basename, join } from "node:path";
3
- import { transformForClient } from "../plugin/transform-client";
4
- import type { ResolvedRoute } from "../server/router/index.ts";
5
- import { generateHydrateEntry } from "./hydrate";
6
- import { CLIENT_MODULE_PATH, LINK_MODULE_PATH, SEARCH_MODULE_PATH } from "./shared";
7
- import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
8
-
9
- const TS_FILE_FILTER = /\.(tsx|ts)$/;
10
-
11
- export interface BuildClientResult {
12
- /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
13
- cssChunks: string[];
14
- /** Public path of the JS entry chunk, e.g. `/_client/chunk-abc.js` */
15
- entryChunk: string;
16
- }
17
-
18
- /**
19
- * Builds the production client bundle via Bun.build() using _hydrate.tsx as
20
- * the JS entrypoint (NOT an HTML entrypoint). Bun produces:
21
- * <outDir>/client/chunk-*.js — code-split bundles
22
- * <outDir>/client/chunk-*.css — extracted CSS (if imported)
23
- *
24
- * Returns the chunk paths so the caller can compute a `buildId` and write
25
- * `index.html` with the correct meta tag. Using an HTML entrypoint with
26
- * code-splitting causes a Bun bug where the output index.html references a
27
- * leaf chunk instead of the actual entry chunk, preventing React from mounting
28
- * in production.
29
- *
30
- * The output index.html is NOT served to browsers directly. The server reads
31
- * it as an SSR template, injects the pre-rendered React HTML into
32
- * <!--ssr-outlet-->, and sends the complete page.
33
- */
34
- export async function buildClient(
35
- routes: ResolvedRoute[],
36
- { outDir, rootLayout, plugins, publicPath, basePath, clientLogging }: BuildClientOptions
37
- ): Promise<BuildClientResult> {
38
- const clientDir = join(outDir, "client");
39
-
40
- if (!existsSync(outDir)) {
41
- mkdirSync(outDir, { recursive: true });
42
- }
43
- if (!existsSync(clientDir)) {
44
- mkdirSync(clientDir, { recursive: true });
45
- }
46
-
47
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
48
- const hydratePath = join(outDir, "_hydrate.tsx");
49
- writeFileSync(hydratePath, hydrateCode);
50
-
51
- console.log("[furin] Building production client bundle…");
52
-
53
- const transformPlugin: Bun.BunPlugin = {
54
- name: "furin-transform-client",
55
- setup(build) {
56
- build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
57
- const { path } = args;
58
- if (path.includes("node_modules")) {
59
- return;
60
- }
61
-
62
- const code = await Bun.file(path).text();
63
- try {
64
- const result = transformForClient(code, path);
65
- // transformForClient now emits TS/TSX directly (no pre-transpile),
66
- // so JSX → React handling is delegated to Bun.build's loader, which
67
- // applies the project tsconfig's automatic runtime by default.
68
- const transformed = result.code
69
- .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
70
- .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
71
- .replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
72
- .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH))
73
- .replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH))
74
- .replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
75
-
76
- return {
77
- contents: transformed,
78
- loader: path.endsWith(".tsx") ? "tsx" : "ts",
79
- };
80
- } catch (error) {
81
- console.error(`[furin] Transform error for ${path}:`, error);
82
- return;
83
- }
84
- });
85
- },
86
- };
87
-
88
- const clientBuildConfig: BunBuildAliasConfig = {
89
- // Use the JS file as entrypoint — NOT an HTML file. Bun's HTML bundler
90
- // with code-splitting incorrectly references a leaf chunk in the output
91
- // index.html instead of the actual entry chunk, preventing React from
92
- // mounting. We write index.html ourselves after the build.
93
- entrypoints: [hydratePath],
94
- outdir: clientDir,
95
- target: "browser",
96
- format: "esm",
97
- splitting: true,
98
- minify: true,
99
- sourcemap: "none",
100
- // Hash the entry point name so it gets immutable caching like chunks.
101
- // Without this, _hydrate.js keeps the same name across builds and browsers
102
- // serve stale versions that reference old chunk hashes → dynamic import 404.
103
- naming: {
104
- entry: "[dir]/[name]-[hash].[ext]",
105
- chunk: "[name]-[hash].[ext]",
106
- },
107
- // Absolute public path so SSR template asset URLs resolve on any route.
108
- // Overridable via the `publicPath` option (e.g. "/furin/_client/" for basePath builds).
109
- publicPath,
110
- // User plugins run before the internal transform so they pre-process files first
111
- plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
112
- alias: {
113
- "@teyik0/furin/client": CLIENT_MODULE_PATH,
114
- "@teyik0/furin/link": LINK_MODULE_PATH,
115
- "@teyik0/furin/search": SEARCH_MODULE_PATH,
116
- },
117
- define: {
118
- "process.env.NODE_ENV": JSON.stringify("production"),
119
- },
120
- };
121
-
122
- const result = await Bun.build(clientBuildConfig);
123
- for (const output of result.outputs) {
124
- console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
125
- }
126
-
127
- // Build index.html (SSR template) with correct chunk references.
128
- // We derive these from result.outputs rather than letting Bun write the HTML,
129
- // because Bun's HTML entrypoint + code-splitting produces the wrong entry chunk.
130
- const entryOutput = result.outputs.find((o) => o.kind === "entry-point");
131
- const cssOutputs = result.outputs.filter(
132
- (o) => o.path.endsWith(".css") && !o.path.endsWith(".css.map")
133
- );
134
- if (!entryOutput) {
135
- throw new Error("[furin] client build did not emit entry chunk");
136
- }
137
-
138
- // Normalise: ensure publicPath ends with exactly one "/".
139
- // Preserve an empty publicPath ("") as-is so callers that want
140
- // relative chunk URLs don't get an unintended root-absolute "/".
141
- let publicPrefix: string;
142
- if (publicPath === "") {
143
- publicPrefix = "";
144
- } else {
145
- publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
146
- }
147
- const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
148
- const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
149
-
150
- console.log("[furin] Production client build complete");
151
- return { entryChunk, cssChunks };
152
- }
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { transformForClient } from "../plugin/transform-client";
4
+ import type { ResolvedRoute } from "../server/router/index.ts";
5
+ import { generateHydrateEntry } from "./hydrate";
6
+ import { CLIENT_MODULE_PATH, LINK_MODULE_PATH, SEARCH_MODULE_PATH } from "./shared";
7
+ import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
8
+
9
+ const TS_FILE_FILTER = /\.(tsx|ts)$/;
10
+
11
+ export interface BuildClientResult {
12
+ /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
13
+ cssChunks: string[];
14
+ /** Public path of the JS entry chunk, e.g. `/_client/chunk-abc.js` */
15
+ entryChunk: string;
16
+ }
17
+
18
+ /**
19
+ * Builds the production client bundle via Bun.build() using _hydrate.tsx as
20
+ * the JS entrypoint (NOT an HTML entrypoint). Bun produces:
21
+ * <outDir>/client/chunk-*.js — code-split bundles
22
+ * <outDir>/client/chunk-*.css — extracted CSS (if imported)
23
+ *
24
+ * Returns the chunk paths so the caller can compute a `buildId` and write
25
+ * `index.html` with the correct meta tag. Using an HTML entrypoint with
26
+ * code-splitting causes a Bun bug where the output index.html references a
27
+ * leaf chunk instead of the actual entry chunk, preventing React from mounting
28
+ * in production.
29
+ *
30
+ * The output index.html is NOT served to browsers directly. The server reads
31
+ * it as an SSR template, injects the pre-rendered React HTML into
32
+ * <!--ssr-outlet-->, and sends the complete page.
33
+ */
34
+ export async function buildClient(
35
+ routes: ResolvedRoute[],
36
+ { outDir, rootLayout, plugins, publicPath, basePath, clientLogging }: BuildClientOptions
37
+ ): Promise<BuildClientResult> {
38
+ const clientDir = join(outDir, "client");
39
+
40
+ if (!existsSync(outDir)) {
41
+ mkdirSync(outDir, { recursive: true });
42
+ }
43
+ if (!existsSync(clientDir)) {
44
+ mkdirSync(clientDir, { recursive: true });
45
+ }
46
+
47
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
48
+ const hydratePath = join(outDir, "_hydrate.tsx");
49
+ writeFileSync(hydratePath, hydrateCode);
50
+
51
+ console.log("[furin] Building production client bundle…");
52
+
53
+ const transformPlugin: Bun.BunPlugin = {
54
+ name: "furin-transform-client",
55
+ setup(build) {
56
+ build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
57
+ const { path } = args;
58
+ if (path.includes("node_modules")) {
59
+ return;
60
+ }
61
+
62
+ const code = await Bun.file(path).text();
63
+ try {
64
+ const result = transformForClient(code, path);
65
+ // transformForClient now emits TS/TSX directly (no pre-transpile),
66
+ // so JSX → React handling is delegated to Bun.build's loader, which
67
+ // applies the project tsconfig's automatic runtime by default.
68
+ const transformed = result.code
69
+ .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
70
+ .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
71
+ .replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
72
+ .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH))
73
+ .replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH))
74
+ .replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
75
+
76
+ return {
77
+ contents: transformed,
78
+ loader: path.endsWith(".tsx") ? "tsx" : "ts",
79
+ };
80
+ } catch (error) {
81
+ console.error(`[furin] Transform error for ${path}:`, error);
82
+ return;
83
+ }
84
+ });
85
+ },
86
+ };
87
+
88
+ const clientBuildConfig: BunBuildAliasConfig = {
89
+ // Use the JS file as entrypoint — NOT an HTML file. Bun's HTML bundler
90
+ // with code-splitting incorrectly references a leaf chunk in the output
91
+ // index.html instead of the actual entry chunk, preventing React from
92
+ // mounting. We write index.html ourselves after the build.
93
+ entrypoints: [hydratePath],
94
+ outdir: clientDir,
95
+ target: "browser",
96
+ format: "esm",
97
+ splitting: true,
98
+ minify: true,
99
+ sourcemap: "none",
100
+ // Hash the entry point name so it gets immutable caching like chunks.
101
+ // Without this, _hydrate.js keeps the same name across builds and browsers
102
+ // serve stale versions that reference old chunk hashes → dynamic import 404.
103
+ naming: {
104
+ entry: "[dir]/[name]-[hash].[ext]",
105
+ chunk: "[name]-[hash].[ext]",
106
+ },
107
+ // Absolute public path so SSR template asset URLs resolve on any route.
108
+ // Overridable via the `publicPath` option (e.g. "/furin/_client/" for basePath builds).
109
+ publicPath,
110
+ // User plugins run before the internal transform so they pre-process files first
111
+ plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
112
+ alias: {
113
+ "@teyik0/furin/client": CLIENT_MODULE_PATH,
114
+ "@teyik0/furin/link": LINK_MODULE_PATH,
115
+ "@teyik0/furin/search": SEARCH_MODULE_PATH,
116
+ },
117
+ define: {
118
+ "process.env.NODE_ENV": JSON.stringify("production"),
119
+ },
120
+ };
121
+
122
+ const result = await Bun.build(clientBuildConfig);
123
+ for (const output of result.outputs) {
124
+ console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
125
+ }
126
+
127
+ // Build index.html (SSR template) with correct chunk references.
128
+ // We derive these from result.outputs rather than letting Bun write the HTML,
129
+ // because Bun's HTML entrypoint + code-splitting produces the wrong entry chunk.
130
+ const entryOutput = result.outputs.find((o) => o.kind === "entry-point");
131
+ const cssOutputs = result.outputs.filter(
132
+ (o) => o.path.endsWith(".css") && !o.path.endsWith(".css.map")
133
+ );
134
+ if (!entryOutput) {
135
+ throw new Error("[furin] client build did not emit entry chunk");
136
+ }
137
+
138
+ // Normalise: ensure publicPath ends with exactly one "/".
139
+ // Preserve an empty publicPath ("") as-is so callers that want
140
+ // relative chunk URLs don't get an unintended root-absolute "/".
141
+ let publicPrefix: string;
142
+ if (publicPath === "") {
143
+ publicPrefix = "";
144
+ } else {
145
+ publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
146
+ }
147
+ const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
148
+ const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
149
+
150
+ console.log("[furin] Production client build complete");
151
+ return { entryChunk, cssChunks };
152
+ }