@teyik0/furin 0.1.0-alpha.8 → 0.2.0-alpha.1

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/dist/adapter/bun.d.ts +2 -2
  4. package/dist/adapter/static.d.ts +1 -1
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/compile-entry.d.ts +2 -16
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +24 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +3 -3
  11. package/dist/build/index.d.ts +1 -0
  12. package/dist/build/index.js +4734 -548
  13. package/dist/build/route-types.d.ts +1 -1
  14. package/dist/build/server-routes-entry.d.ts +2 -12
  15. package/dist/build/server-routes-entry.ts +36 -0
  16. package/dist/build/shared.d.ts +1 -1
  17. package/dist/build/ssg-cache.d.ts +4 -0
  18. package/dist/build/types.d.ts +5 -1
  19. package/dist/cli/index.js +4713 -549
  20. package/dist/client/boundaries.d.ts +117 -0
  21. package/dist/client/default-screens.d.ts +17 -0
  22. package/dist/client/link.d.ts +22 -0
  23. package/dist/client/link.js +3450 -0
  24. package/dist/client/router/boundary-tree.d.ts +26 -0
  25. package/dist/client/router/context.d.ts +8 -0
  26. package/dist/client/router/history.d.ts +9 -0
  27. package/dist/client/router/index.d.ts +7 -0
  28. package/dist/client/router/link-utils.d.ts +51 -0
  29. package/dist/client/router/provider.d.ts +4 -0
  30. package/dist/client/router/spa-response.d.ts +58 -0
  31. package/dist/{link.d.ts → client/router/types.d.ts} +114 -80
  32. package/dist/client/server-error.d.ts +12 -0
  33. package/dist/client.d.ts +54 -4
  34. package/dist/client.js +77 -1
  35. package/dist/config.d.ts +12 -2
  36. package/dist/config.js +1 -0
  37. package/dist/env.d.ts +50 -0
  38. package/dist/furin.d.ts +37 -2
  39. package/dist/furin.js +5288 -601
  40. package/dist/plugin/index.js +140 -48
  41. package/dist/plugin/transform-client.d.ts +2 -1
  42. package/dist/server/auto-invalidate/index.d.ts +4 -0
  43. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  44. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  45. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  46. package/dist/server/auto-invalidate/types.d.ts +12 -0
  47. package/dist/server/cache/dev-loader.d.ts +28 -0
  48. package/dist/server/cache/index.d.ts +10 -0
  49. package/dist/server/cache/invalidation.d.ts +12 -0
  50. package/dist/server/cache/isr-ssg.d.ts +26 -0
  51. package/dist/server/cache/isr.d.ts +6 -0
  52. package/dist/server/cache/registry.d.ts +5 -0
  53. package/dist/server/cache/route-cache.d.ts +26 -0
  54. package/dist/server/cache/ssg.d.ts +5 -0
  55. package/dist/server/context-logger.d.ts +28 -0
  56. package/dist/server/dev-inspector.d.ts +89 -0
  57. package/dist/{internal.d.ts → server/internal.d.ts} +16 -0
  58. package/dist/server/internal.js +17 -0
  59. package/dist/server/lang-detect.d.ts +5 -0
  60. package/dist/server/render/assemble.d.ts +47 -0
  61. package/dist/server/render/element.d.ts +24 -0
  62. package/dist/server/render/index.d.ts +7 -0
  63. package/dist/server/render/index.ts +22 -0
  64. package/dist/server/render/isr.d.ts +3 -0
  65. package/dist/server/render/loaders.d.ts +64 -0
  66. package/dist/server/render/not-found.d.ts +6 -0
  67. package/dist/{render → server/render}/shell.d.ts +17 -4
  68. package/{src → dist/server}/render/shell.ts +31 -9
  69. package/dist/server/render/ssg.d.ts +8 -0
  70. package/dist/server/render/ssr.d.ts +107 -0
  71. package/dist/server/router/discovery.d.ts +16 -0
  72. package/dist/server/router/hmr.d.ts +64 -0
  73. package/dist/server/router/index.d.ts +6 -0
  74. package/dist/server/router/index.js +28 -0
  75. package/dist/server/router/index.ts +29 -0
  76. package/dist/server/router/patterns.d.ts +40 -0
  77. package/dist/server/router/plugin.d.ts +20 -0
  78. package/dist/server/router/schemas.d.ts +51 -0
  79. package/dist/server/router/types.d.ts +60 -0
  80. package/dist/server/runtime-env.js +10 -0
  81. package/dist/shared/await.d.ts +67 -0
  82. package/dist/shared/deferred-ndjson.d.ts +32 -0
  83. package/dist/shared/digest.d.ts +16 -0
  84. package/dist/shared/error.d.ts +37 -0
  85. package/dist/shared/not-found.d.ts +19 -0
  86. package/dist/shared/utils/ast-walk.d.ts +18 -0
  87. package/dist/shared/utils/index.d.ts +13 -0
  88. package/package.json +56 -25
  89. package/src/adapter/bun.ts +90 -41
  90. package/src/adapter/static.ts +83 -36
  91. package/src/build/client.ts +8 -12
  92. package/src/build/compile-entry.ts +20 -14
  93. package/src/build/entry-template.ts +90 -8
  94. package/src/build/hydrate.ts +213 -36
  95. package/src/build/index.ts +10 -9
  96. package/src/build/route-types.ts +30 -4
  97. package/src/build/scan-server.ts +52 -67
  98. package/src/build/server-routes-entry.ts +7 -11
  99. package/src/build/shared.ts +1 -1
  100. package/src/build/ssg-cache.ts +31 -0
  101. package/src/build/types.ts +5 -1
  102. package/src/cli/index.ts +1 -0
  103. package/src/client/boundaries.tsx +259 -0
  104. package/src/client/default-screens.tsx +304 -0
  105. package/src/client/link.tsx +338 -0
  106. package/src/client/router/boundary-tree.tsx +116 -0
  107. package/src/client/router/context.ts +38 -0
  108. package/src/client/router/history.ts +41 -0
  109. package/src/client/router/index.ts +47 -0
  110. package/src/client/router/link-utils.ts +180 -0
  111. package/src/client/router/provider.tsx +723 -0
  112. package/src/client/router/spa-response.ts +143 -0
  113. package/src/client/router/types.ts +263 -0
  114. package/src/client/server-error.ts +47 -0
  115. package/src/client.ts +83 -3
  116. package/src/config.ts +11 -3
  117. package/src/env.d.ts +1 -0
  118. package/src/furin.ts +104 -26
  119. package/src/plugin/index.ts +7 -8
  120. package/src/plugin/transform-client.ts +146 -120
  121. package/src/server/auto-invalidate/index.ts +10 -0
  122. package/src/server/auto-invalidate/plugin.ts +25 -0
  123. package/src/server/auto-invalidate/registry.ts +60 -0
  124. package/src/server/auto-invalidate/runtime.ts +133 -0
  125. package/src/server/auto-invalidate/types.ts +16 -0
  126. package/src/server/cache/dev-loader.ts +211 -0
  127. package/src/server/cache/index.ts +34 -0
  128. package/src/server/cache/invalidation.ts +111 -0
  129. package/src/server/cache/isr-ssg.ts +41 -0
  130. package/src/server/cache/isr.ts +17 -0
  131. package/src/server/cache/registry.ts +35 -0
  132. package/src/server/cache/route-cache.ts +124 -0
  133. package/src/server/cache/ssg.ts +15 -0
  134. package/src/server/context-logger.ts +76 -0
  135. package/src/server/dev-inspector.ts +60 -0
  136. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  137. package/src/{internal.ts → server/internal.ts} +17 -0
  138. package/src/server/lang-detect.ts +46 -0
  139. package/src/server/render/assemble.ts +133 -0
  140. package/src/server/render/element.tsx +113 -0
  141. package/src/server/render/index.ts +22 -0
  142. package/src/server/render/isr.ts +295 -0
  143. package/src/server/render/loaders.ts +328 -0
  144. package/src/server/render/not-found.ts +96 -0
  145. package/src/server/render/shell.ts +202 -0
  146. package/src/server/render/ssg.ts +137 -0
  147. package/src/server/render/ssr.ts +545 -0
  148. package/src/server/router/discovery.ts +474 -0
  149. package/src/server/router/hmr.ts +372 -0
  150. package/src/server/router/index.ts +29 -0
  151. package/src/server/router/patterns.ts +214 -0
  152. package/src/server/router/plugin.ts +401 -0
  153. package/src/server/router/schemas.ts +163 -0
  154. package/src/server/router/types.ts +59 -0
  155. package/src/shared/await.tsx +192 -0
  156. package/src/shared/deferred-ndjson.ts +244 -0
  157. package/src/shared/digest.ts +71 -0
  158. package/src/shared/error.ts +49 -0
  159. package/src/shared/not-found.ts +40 -0
  160. package/src/shared/utils/ast-walk.ts +51 -0
  161. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  162. package/dist/link.js +0 -1173
  163. package/dist/render/assemble.d.ts +0 -13
  164. package/dist/render/cache.d.ts +0 -95
  165. package/dist/render/element.d.ts +0 -4
  166. package/dist/render/index.d.ts +0 -27
  167. package/dist/render/loaders.d.ts +0 -12
  168. package/dist/router.d.ts +0 -34
  169. package/dist/router.js +0 -830
  170. package/dist/utils.d.ts +0 -6
  171. package/src/link.tsx +0 -1035
  172. package/src/render/assemble.ts +0 -64
  173. package/src/render/cache.ts +0 -241
  174. package/src/render/element.tsx +0 -28
  175. package/src/render/index.ts +0 -479
  176. package/src/render/loaders.ts +0 -113
  177. package/src/router.ts +0 -400
  178. /package/dist/{dev-page-plugin.d.ts → server/dev-page-plugin.d.ts} +0 -0
  179. /package/dist/{render → server/render}/template.d.ts +0 -0
  180. /package/dist/{runtime-env.d.ts → server/runtime-env.d.ts} +0 -0
  181. /package/src/{render → server/render}/template.ts +0 -0
  182. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -0,0 +1,17 @@
1
+ // @bun
2
+ // src/server/internal.ts
3
+ var _compileCtx = null;
4
+ function __setCompileContext(ctx) {
5
+ _compileCtx = ctx;
6
+ }
7
+ function getCompileContext() {
8
+ return _compileCtx;
9
+ }
10
+ function __resetCompileContext() {
11
+ _compileCtx = null;
12
+ }
13
+ export {
14
+ getCompileContext,
15
+ __setCompileContext,
16
+ __resetCompileContext
17
+ };
@@ -0,0 +1,5 @@
1
+ import type { SourceLang } from "yuku-parser";
2
+ export declare function detectLangFromPath(filePath: string): SourceLang;
3
+ export declare function unwrapTSExpression<T extends {
4
+ type: string;
5
+ }>(node: T): T;
@@ -0,0 +1,47 @@
1
+ import type { toCrossJSON } from "seroval";
2
+ import type { buildHeadInjection } from "./shell";
3
+ /**
4
+ * Single source of truth for the global registry name used by the SSR
5
+ * streaming script, the client hydration entry, and any test helper. Keeping
6
+ * it centralised here avoids `<script>`/JS source drift if the name is ever
7
+ * renamed.
8
+ */
9
+ export declare const FURIN_DEFERRED_GLOBAL = "__FURIN_DEFERRED__";
10
+ /**
11
+ * Generates the `window.__FURIN_DEFERRED__` registry script that is injected
12
+ * BEFORE the React stream starts. It sets up the resolve/reject/getPromise API
13
+ * for late chunks.
14
+ *
15
+ * Client-side `<Await>` components call `getPromise(key)` to obtain a Promise
16
+ * they can pass to React 19's `use()`. The late resolution scripts call
17
+ * `resolve(key, chunk)` / `reject(key, chunk)` to settle those Promises.
18
+ *
19
+ * Synchronous loader data is NOT carried here — it lives exclusively in the
20
+ * `__FURIN_DATA__` JSON script that the hydrate entry reads.
21
+ *
22
+ * CSP note: this is an inline `<script>` — nonce support is a v2 concern.
23
+ */
24
+ export declare function buildDeferredScript(deferredKeys: string[]): string;
25
+ /**
26
+ * Generates a late `<script>` that settles one deferred Promise on the client.
27
+ * The `chunk` must be a seroval CrossJSON value produced by `toCrossJSON(value)`.
28
+ *
29
+ * @param key - The Promise key (matches what `getPromise(key)` was called with)
30
+ * @param chunk - The already-serialised CrossJSON value
31
+ * @param action - "resolve" or "reject"
32
+ */
33
+ export declare function buildDeferredResolution(key: string, chunk: ReturnType<typeof toCrossJSON>, action: "resolve" | "reject"): string;
34
+ /** Minimal context passed to background / synthetic render helpers — only `request` is needed. */
35
+ export interface LoaderContext {
36
+ request: Request;
37
+ }
38
+ export declare function resolvePath(pattern: string, params: Record<string, string>): string;
39
+ export declare function streamToString(stream: ReadableStream): Promise<string>;
40
+ interface SplitTemplate {
41
+ bodyPost: string;
42
+ bodyPre: string;
43
+ headPre: string;
44
+ }
45
+ export declare function splitTemplate(template: string): SplitTemplate;
46
+ export declare function assembleHTML(template: string, headData: ReturnType<typeof buildHeadInjection>, reactHtml: string, data: Record<string, unknown> | undefined): string;
47
+ export {};
@@ -0,0 +1,24 @@
1
+ import type { ReactNode } from "react";
2
+ import type { RuntimeRoute } from "../../client.ts";
3
+ import type { ErrorComponent } from "../../shared/error.ts";
4
+ import type { FurinNotFoundError, NotFoundComponent } from "../../shared/not-found.ts";
5
+ import type { ResolvedRoute } from "../router/index.ts";
6
+ export declare function buildElement(route: ResolvedRoute, data: Record<string, unknown>, rootLayout: RuntimeRoute): ReactNode;
7
+ export declare function buildNotFoundElement(component: NotFoundComponent | undefined, error: FurinNotFoundError): ReactNode;
8
+ /**
9
+ * Builds the error element rendered when a loader (or the SSR shell) fails.
10
+ *
11
+ * @param component - User-declared `error.tsx` component, or `undefined` to
12
+ * fall back to the built-in `DefaultErrorScreen` with a generic message.
13
+ * @param error - The original thrown value. Kept for `errorMessageOf` lookup
14
+ * when no explicit `messageOverride` is provided (e.g. shell-render errors).
15
+ * @param digest - 10-hex-char digest correlating with server logs.
16
+ * @param messageOverride - Pre-extracted public message. Set by the loader
17
+ * pipeline when the thrown value is a `Response` (whose body has already
18
+ * been consumed in `runLoaders`); pass `undefined` to derive the message
19
+ * from `error` via `errorMessageOf`.
20
+ * @param status - HTTP status to surface in `ErrorProps.error.status`. The
21
+ * loader pipeline passes the thrown `Response.status` (default 500); the
22
+ * shell-error recovery path always passes 500.
23
+ */
24
+ export declare function buildErrorElement(component: ErrorComponent | undefined, error: unknown, digest: string, messageOverride: string | undefined, status: number): ReactNode;
@@ -0,0 +1,7 @@
1
+ export { type LoaderContext, streamToString } from "./assemble.ts";
2
+ export { buildElement, buildErrorElement } from "./element.tsx";
3
+ export { handleISR } from "./isr.ts";
4
+ export { type LoaderResult, runLoaders, serializeDeferredRejection } from "./loaders.ts";
5
+ export { renderRootNotFound } from "./not-found.ts";
6
+ export { prerenderSSG, warmSSGCache } from "./ssg.ts";
7
+ export { assertDeferredModeAllowed, type PreparedRender, prepareRender, type RenderResult, renderForPath, renderSSR, renderToHTML, renderToStream, serializeLoaderDataNdjson, splitBeforeBodyClose, withSSRRouterContext, } from "./ssr.ts";
@@ -0,0 +1,22 @@
1
+ // biome-ignore-all lint/performance/noBarrelFile: intentional barrel for public API
2
+
3
+ export { type LoaderContext, streamToString } from "./assemble.ts";
4
+ export { buildElement, buildErrorElement } from "./element.tsx";
5
+ export { handleISR } from "./isr.ts";
6
+ export { type LoaderResult, runLoaders, serializeDeferredRejection } from "./loaders.ts";
7
+ export { renderRootNotFound } from "./not-found.ts";
8
+
9
+ export { prerenderSSG, warmSSGCache } from "./ssg.ts";
10
+ export {
11
+ assertDeferredModeAllowed,
12
+ type PreparedRender,
13
+ prepareRender,
14
+ type RenderResult,
15
+ renderForPath,
16
+ renderSSR,
17
+ renderToHTML,
18
+ renderToStream,
19
+ serializeLoaderDataNdjson,
20
+ splitBeforeBodyClose,
21
+ withSSRRouterContext,
22
+ } from "./ssr.ts";
@@ -0,0 +1,3 @@
1
+ import type { Context } from "elysia";
2
+ import type { ResolvedRoute, RootLayout } from "../router/index.ts";
3
+ export declare function handleISR(route: ResolvedRoute, ctx: Context, root: RootLayout, buildId: string | undefined): Promise<string | Response | undefined>;
@@ -0,0 +1,64 @@
1
+ import type { Context } from "elysia";
2
+ import { type FurinNotFoundError } from "../../shared/not-found.ts";
3
+ import type { ResolvedRoute } from "../router/index.ts";
4
+ export type LoaderResult = {
5
+ type: "data";
6
+ /**
7
+ * Synchronous (JSON-serialisable) loader fields. Injected into the initial
8
+ * HTML shell as `__FURIN_DATA__` / the deferred registry's `_data` object.
9
+ */
10
+ syncData: Record<string, unknown>;
11
+ /**
12
+ * Promise-valued fields from a `defer()` return. `undefined` when the page
13
+ * loader did not call `defer()`. Streamed as late `<script>` resolution
14
+ * chunks (SSR) or as NDJSON chunks via `/_furin/data` (SPA nav).
15
+ */
16
+ deferredPromises: Record<string, Promise<unknown>> | undefined;
17
+ headers: Record<string, string>;
18
+ } | {
19
+ type: "redirect";
20
+ response: Response;
21
+ } | {
22
+ type: "not-found";
23
+ error: FurinNotFoundError;
24
+ headers: Record<string, string>;
25
+ } | {
26
+ type: "error";
27
+ /**
28
+ * Original thrown value, kept for digest computation and server logging.
29
+ * For thrown `Response` objects this is the Response instance whose body
30
+ * has already been consumed by `runLoaders` (do NOT read it again).
31
+ */
32
+ error: unknown;
33
+ /** HTTP status to return. Default 500; sourced from `Response.status` for thrown Response objects. */
34
+ status: number;
35
+ /**
36
+ * Safe public message extracted at the loader boundary. For thrown
37
+ * `Response` objects: response body or `statusText`. For thrown `Error`
38
+ * / non-Error values: a generic "Something went wrong" string (the raw
39
+ * error/message is never leaked here — `errorMessageOf` decides what to
40
+ * surface from the original `error` value when an `error.tsx` fallback
41
+ * exists).
42
+ */
43
+ message: string;
44
+ headers: Record<string, string>;
45
+ };
46
+ /**
47
+ * Normalises an error thrown inside a deferred Promise into a value that is
48
+ * safe to send through `toCrossJSON` and that preserves the original semantics
49
+ * after `fromCrossJSON` on the client.
50
+ *
51
+ * Symmetric to the rejection handling in `runLoaders` (lines 247-272) but for
52
+ * the *deferred* path, where the rejection is delivered to a client-side
53
+ * `<Await>` instead of becoming a top-level response.
54
+ *
55
+ * - `notFound()` → `Error` carrying `__furinBrand` + `data` so the
56
+ * client-side `isNotFoundError()` (duck-typed)
57
+ * recognises the rejection.
58
+ * - `Response(status, body)` → `Error` carrying `__furinStatus` and the
59
+ * body/statusText as `message`.
60
+ * - `Error` → returned unchanged.
61
+ * - anything else → wrapped in `new Error(String(value))`.
62
+ */
63
+ export declare function serializeDeferredRejection(err: unknown): Promise<unknown>;
64
+ export declare function runLoaders(route: ResolvedRoute, ctx: Context): Promise<LoaderResult>;
@@ -0,0 +1,6 @@
1
+ import type { RootLayout } from "../router/index.ts";
2
+ /**
3
+ * Renders the root-level not-found component into a complete 404 HTML Response.
4
+ * Used by the Elysia `.onError` catch-all when no route matches the request URL.
5
+ */
6
+ export declare function renderRootNotFound(root: RootLayout, request: Request | undefined): Promise<Response>;
@@ -1,4 +1,4 @@
1
- import type { HeadOptions, MetaDescriptor } from "../client.ts";
1
+ import type { HeadOptions, MetaDescriptor } from "../../client.ts";
2
2
  export declare function extractTitle(meta?: MetaDescriptor[]): string | undefined;
3
3
  export declare function isMetaTag(entry: MetaDescriptor): boolean;
4
4
  export declare function escapeHtml(str: string): string;
@@ -20,7 +20,20 @@ export declare function generateIndexHtml(): string;
20
20
  * Called after Bun.build() completes so we can inject the correct entry chunk
21
21
  * and CSS paths derived from result.outputs.
22
22
  *
23
- * @param buildId - Short hash identifying this specific build. Injected as a
24
- * `<meta name="furin-build-id">` tag so the client can detect stale deploys.
23
+ * @param entryChunk - Hashed URL of the client entry script.
24
+ * @param cssChunks - Hashed URLs of the CSS chunks to inject as `<link>`s.
25
+ * @param buildId - Short hash identifying this specific build (or `undefined`
26
+ * for static exports where stale-deploy detection is not applicable).
27
+ * Injected as a `<meta name="furin-build-id">` tag so the client can
28
+ * detect stale deploys.
29
+ * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico"),
30
+ * or `undefined` when no favicon is provided. When set, a `<link rel="icon">`
31
+ * tag is injected so browsers can locate the favicon even when the site is
32
+ * served from a sub-path.
33
+ * @param staticMode - `true` for static exports, `false` for SSR/ISR. When
34
+ * `true`, a `<meta name="furin-mode" content="static">` tag is injected so
35
+ * the SPA client knows to fetch loader data from the per-route
36
+ * `__furin_data.ndjson` file instead of the runtime `/_furin/data` endpoint
37
+ * (which doesn't exist on a static host).
25
38
  */
26
- export declare function generateProdIndexHtml(entryChunk: string, cssChunks: string[], buildId?: string): string;
39
+ export declare function generateProdIndexHtml(entryChunk: string, cssChunks: string[], buildId: string | undefined, faviconHref: string | undefined, staticMode: boolean): string;
@@ -1,4 +1,4 @@
1
- import type { HeadOptions, MetaDescriptor } from "../client.ts";
1
+ import type { HeadOptions, MetaDescriptor } from "../../client.ts";
2
2
 
3
3
  export function extractTitle(meta?: MetaDescriptor[]): string | undefined {
4
4
  if (!meta) {
@@ -39,10 +39,13 @@ export function safeJson(value: unknown): string {
39
39
  }
40
40
 
41
41
  export function renderAttrs(obj: Record<string, string | undefined>): string {
42
- return Object.entries(obj)
43
- .filter(([, v]) => v !== undefined)
44
- .map(([k, v]) => `${k}="${escapeHtml(String(v))}"`)
45
- .join(" ");
42
+ const parts: string[] = [];
43
+ for (const [k, v] of Object.entries(obj)) {
44
+ if (v !== undefined) {
45
+ parts.push(`${k}="${escapeHtml(String(v))}"`);
46
+ }
47
+ }
48
+ return parts.join(" ");
46
49
  }
47
50
 
48
51
  // ---------------------------------------------------------------------------
@@ -147,13 +150,28 @@ export function generateIndexHtml(): string {
147
150
  * Called after Bun.build() completes so we can inject the correct entry chunk
148
151
  * and CSS paths derived from result.outputs.
149
152
  *
150
- * @param buildId - Short hash identifying this specific build. Injected as a
151
- * `<meta name="furin-build-id">` tag so the client can detect stale deploys.
153
+ * @param entryChunk - Hashed URL of the client entry script.
154
+ * @param cssChunks - Hashed URLs of the CSS chunks to inject as `<link>`s.
155
+ * @param buildId - Short hash identifying this specific build (or `undefined`
156
+ * for static exports where stale-deploy detection is not applicable).
157
+ * Injected as a `<meta name="furin-build-id">` tag so the client can
158
+ * detect stale deploys.
159
+ * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico"),
160
+ * or `undefined` when no favicon is provided. When set, a `<link rel="icon">`
161
+ * tag is injected so browsers can locate the favicon even when the site is
162
+ * served from a sub-path.
163
+ * @param staticMode - `true` for static exports, `false` for SSR/ISR. When
164
+ * `true`, a `<meta name="furin-mode" content="static">` tag is injected so
165
+ * the SPA client knows to fetch loader data from the per-route
166
+ * `__furin_data.ndjson` file instead of the runtime `/_furin/data` endpoint
167
+ * (which doesn't exist on a static host).
152
168
  */
153
169
  export function generateProdIndexHtml(
154
170
  entryChunk: string,
155
171
  cssChunks: string[],
156
- buildId?: string
172
+ buildId: string | undefined,
173
+ faviconHref: string | undefined,
174
+ staticMode: boolean
157
175
  ): string {
158
176
  const cssLinks = cssChunks
159
177
  .map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`)
@@ -162,6 +180,10 @@ export function generateProdIndexHtml(
162
180
  const buildIdMeta = buildId
163
181
  ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">\n`
164
182
  : "";
183
+ const faviconLink = faviconHref
184
+ ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">\n`
185
+ : "";
186
+ const modeMeta = staticMode ? ` <meta name="furin-mode" content="static">\n` : "";
165
187
 
166
188
  return `<!DOCTYPE html>
167
189
  <html lang="en">
@@ -169,7 +191,7 @@ export function generateProdIndexHtml(
169
191
  <meta charset="UTF-8">
170
192
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
171
193
  ${THEME_INIT_SCRIPT}
172
- ${buildIdMeta}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
194
+ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
173
195
  </head>
174
196
  <body>
175
197
  <div id="root"><!--ssr-outlet--></div>
@@ -0,0 +1,8 @@
1
+ import type { SsgCacheEntry } from "../cache/isr-ssg.ts";
2
+ import type { ResolvedRoute, RootLayout } from "../router/index.ts";
3
+ export declare function prerenderSSG(route: ResolvedRoute, params: Record<string, string>, root: RootLayout, origin: string, basePath: string | undefined): Promise<SsgCacheEntry | Response>;
4
+ /**
5
+ * Pre-renders all SSG routes that declare `staticParams` and populates the
6
+ * in-memory cache before the first real request arrives.
7
+ */
8
+ export declare function warmSSGCache(routes: ResolvedRoute[], root: RootLayout, origin: string): Promise<void>;
@@ -0,0 +1,107 @@
1
+ import type { Context } from "elysia";
2
+ import { type ReactNode } from "react";
3
+ import { renderToReadableStream } from "react-dom/server";
4
+ import { type RouterContextValue } from "../../client/router/index.ts";
5
+ import type { ResolvedRoute, RootLayout } from "../router/index.ts";
6
+ import { buildErrorElement } from "./element.tsx";
7
+ import { type LoaderResult } from "./loaders.ts";
8
+ export type { LoaderContext } from "./assemble.ts";
9
+ export type { LoaderResult } from "./loaders.ts";
10
+ export interface RenderResult {
11
+ headers: Record<string, string>;
12
+ html: string;
13
+ /**
14
+ * NDJSON payload (one CrossJSON-serialised line) carrying the loader's
15
+ * resolved sync + deferred data. Identical in shape to the body the live
16
+ * `/_furin/data` endpoint emits, so the SPA client can consume both
17
+ * interchangeably.
18
+ */
19
+ ndjson: string;
20
+ status: number;
21
+ }
22
+ export interface PreparedRender {
23
+ /**
24
+ * All props passed to the React component tree. For deferred renders this
25
+ * includes the Promise objects (for `<Await resolve={promise}>`) alongside
26
+ * the scalar sync fields. Never serialise this directly — use `syncData`.
27
+ */
28
+ componentProps: Record<string, unknown>;
29
+ /**
30
+ * Promise-valued fields from a `defer()` loader return. Undefined for normal
31
+ * (non-deferred) loaders. These are streamed as late `<script>` chunks after
32
+ * the React stream finishes.
33
+ */
34
+ deferredPromises: Record<string, Promise<unknown>> | undefined;
35
+ element: ReactNode;
36
+ /** Set when the prepared element is an error UI. */
37
+ errorDigest?: string;
38
+ headData: string;
39
+ headers: Record<string, string>;
40
+ loader_ms: number;
41
+ /**
42
+ * Populated only when the loader threw `notFound()`. Mirrored into
43
+ * `__FURIN_DATA__.__furinNotFound` so the client-side can render the
44
+ * not-found UI inline on SPA navigation.
45
+ */
46
+ notFoundError?: {
47
+ data?: unknown;
48
+ message?: string;
49
+ };
50
+ ssrContext: RouterContextValue;
51
+ status: number;
52
+ /**
53
+ * JSON-serialisable subset of `componentProps`. For deferred renders this
54
+ * excludes the Promise fields (those are streamed separately).
55
+ */
56
+ syncData: Record<string, unknown>;
57
+ template: string;
58
+ }
59
+ export declare function withSSRRouterContext(element: ReactNode, contextValue: RouterContextValue): ReactNode;
60
+ interface ShellFallbackResult {
61
+ /**
62
+ * Set when the primary element threw synchronously during render and a
63
+ * fallback error UI was streamed instead. Carries the digest so the caller
64
+ * can surface it in logs and the `__furinError` payload.
65
+ */
66
+ shellError: {
67
+ digest: string;
68
+ } | undefined;
69
+ stream: Awaited<ReturnType<typeof renderToReadableStream>>;
70
+ }
71
+ /**
72
+ * Renders `element` to a React stream, recovering from a synchronous shell
73
+ * throw with a 500 error UI. The supplied error component (route-level, else
74
+ * root-level) is tried first; if it ALSO throws, the built-in error element is
75
+ * used, so a broken custom error page can never take down the whole response.
76
+ *
77
+ * Shared by SSR (which pipes the stream) and ISR/SSG non-200 (which drains it
78
+ * to a string) — both start from this same React stream and only diverge in how
79
+ * they consume it and which fields they log.
80
+ */
81
+ export declare function renderElementWithShellFallback(element: ReactNode, errorComponent: Parameters<typeof buildErrorElement>[0], ssrContext: RouterContextValue): Promise<ShellFallbackResult>;
82
+ /**
83
+ * defer() streams data progressively — it only makes sense in SSR. In SSG/ISR
84
+ * the HTML is pre-rendered and cached, so the deferred fields would be absent
85
+ * from the embedded `__FURIN_DATA__` and the client `<Await>` would hydrate
86
+ * with `undefined`. Fail fast at the loader boundary.
87
+ */
88
+ export declare function assertDeferredModeAllowed(route: ResolvedRoute, deferredPromises: Record<string, Promise<unknown>> | undefined): void;
89
+ /**
90
+ * Shared pipeline steps used by both `renderToHTML` (buffered) and `renderSSR`
91
+ * (streaming). Runs loaders, builds props, head injection, resolves template,
92
+ * and creates the React element.
93
+ *
94
+ * Returns the redirect Response directly when a loader redirects, so callers
95
+ * never need try/catch for redirect handling.
96
+ */
97
+ export declare function prepareRender(route: ResolvedRoute, ctx: Context, root: RootLayout, basePath: string | undefined, throwOnFailure: boolean, precomputedLoaderResult: LoaderResult | undefined): Promise<PreparedRender | Response>;
98
+ export declare function renderForPath(route: ResolvedRoute, params: Record<string, string>, root: RootLayout, origin: string, mode: "ssg" | "isr", basePath: string | undefined): Promise<RenderResult | Response>;
99
+ /**
100
+ * Serialises a loader's `syncData` + `deferredPromises` into the same one-line
101
+ * NDJSON shape the live `/_furin/data` endpoint emits.
102
+ */
103
+ export declare function serializeLoaderDataNdjson(syncData: Record<string, unknown>, deferredPromises: Record<string, Promise<unknown>> | undefined): Promise<string>;
104
+ export declare function renderToHTML(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<RenderResult>;
105
+ export declare function renderToStream(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<ReadableStream | Response>;
106
+ export declare function renderSSR(route: ResolvedRoute, ctx: Context, root: RootLayout, precomputedLoaderResult: LoaderResult | undefined): Promise<Response>;
107
+ export declare function splitBeforeBodyClose(bodyPost: string): [string, string];
@@ -0,0 +1,16 @@
1
+ import type { RuntimePage, RuntimeRoute } from "../../client.ts";
2
+ import { type CompileContext } from "../internal.ts";
3
+ import type { ResolvedRoute, RootLayout } from "./types.ts";
4
+ export declare function isModuleNotFoundError(err: unknown): boolean;
5
+ /** @internal Exported for unit testing. */
6
+ export declare function collectRouteTags(routeChain: RuntimeRoute[], page: Pick<RuntimePage, "tags"> | undefined): string[] | undefined;
7
+ export declare function loadProdRoutes(ctx: CompileContext): {
8
+ root: RootLayout;
9
+ routes: ResolvedRoute[];
10
+ };
11
+ export declare function scanPages(pagesDir: string): Promise<{
12
+ root: RootLayout;
13
+ routes: ResolvedRoute[];
14
+ }>;
15
+ export declare function scanRootLayout(pagesDir: string): Promise<RootLayout>;
16
+ export declare function getSourceModuleCandidates(dir: string, name: string): string[];
@@ -0,0 +1,64 @@
1
+ import type { Context } from "elysia";
2
+ import type { RuntimePage, RuntimeRoute } from "../../client.ts";
3
+ import { type CompileContext } from "../internal.ts";
4
+ import type { ResolvedRoute, RootLayout } from "./types.ts";
5
+ type RouteModuleImport = (specifier: string) => Promise<Record<string, unknown>>;
6
+ export declare function importFreshRouteModuleCandidate(layoutPath: string, timestamp: number, resolveImport: RouteModuleImport, ctx: CompileContext | null): Promise<Record<string, unknown> | undefined>;
7
+ /**
8
+ * Re-imports intermediate layout _route.tsx files with cache-busting so that
9
+ * server-side renders reflect the latest code after an HMR edit. Bun's ESM
10
+ * cache keeps the original module alive, so we import via ?furin-server and
11
+ * patch the layout/loader references on the existing route-chain objects.
12
+ *
13
+ * The optional `importFn` parameter exists only for unit testing. In production
14
+ * it defaults to the real `import()`.
15
+ */
16
+ export declare function refreshLayoutChain(chain: RuntimeRoute[], pagePath: string, rootPath: string, importFn: ((specifier: string) => Promise<Record<string, unknown>>) | undefined): Promise<void>;
17
+ /**
18
+ * Rebuilds a `ResolvedRoute` from freshly-imported `page` and `chain` so that
19
+ * `mode` reflects the CURRENT contents of the page module — not the value
20
+ * captured at scan time.
21
+ *
22
+ * In dev, `handleDevRequest` re-imports the page on every request to pick up
23
+ * source edits via the `?furin-server&t=<ts>` cache-buster. Without this
24
+ * function the spread `{ ...route, page, chain }` would carry over the stale
25
+ * `route.mode` resolved at startup, so toggling `revalidate` or removing a
26
+ * loader in source would not retake effect until a server restart.
27
+ *
28
+ * Only `mode` is recomputed: it is the only field DERIVED from page+chain.
29
+ * Structural fields (`pattern`, `path`, `segmentBoundaries`, `error`,
30
+ * `notFound`) are scan-time invariants in dev and are preserved as-is.
31
+ */
32
+ export declare function rebuildDevRoute(base: ResolvedRoute, page: RuntimePage, chain: RuntimeRoute[]): ResolvedRoute;
33
+ /** @internal Handles a request in dev mode — re-imports the page fresh on every request. */
34
+ export declare function handleDevRequest(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<unknown>;
35
+ /**
36
+ * @internal Dev "Live ISR" — caches loader output, not assembled HTML. On a
37
+ * fresh cache hit the loader chain is skipped; the React render still runs so
38
+ * the response embeds the latest dev shell (chunk URL, HMR runtime, …). On
39
+ * miss, runs loaders normally and stores the merged data record.
40
+ */
41
+ export declare function renderDevISRWithLoaderCache(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<Response>;
42
+ /**
43
+ * @internal Dev "Live SSG" — same shape as `renderDevISRWithLoaderCache`, but
44
+ * the cached entry is tagged forever-fresh (`revalidate: Infinity`) so it
45
+ * survives indefinitely until source-aware invalidation drops it. This makes
46
+ * dev SSG behave like production SSG: the loader runs ONCE per cache key,
47
+ * not on every refresh.
48
+ */
49
+ export declare function renderDevSSGWithLoaderCache(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<Response>;
50
+ /**
51
+ * @internal Lists every source file whose contents can affect the render
52
+ * output for a given page: the page itself, every intermediate `_route.*`
53
+ * between the page and the pages root, and `root.tsx`.
54
+ *
55
+ * Only paths that EXIST on disk are returned. `isDevLoaderCacheValid` treats
56
+ * a `statSync` throw as "invalid" (conservative on missing files), so listing
57
+ * non-authored extension candidates here would force a permanent cache MISS
58
+ * for every nested route — silently disabling the dev ISR/SSG cache for any
59
+ * page in a subdirectory. Renames and deletions of TRACKED deps are still
60
+ * detected: the path that previously existed will then `statSync`-throw on
61
+ * the next read and yield the same conservative miss.
62
+ */
63
+ export declare function computeRouteDependencies(pagePath: string, rootPath: string): string[];
64
+ export {};
@@ -0,0 +1,6 @@
1
+ export { collectRouteTags, loadProdRoutes, scanPages, scanRootLayout } from "./discovery.ts";
2
+ export { computeRouteDependencies, importFreshRouteModuleCandidate, rebuildDevRoute, refreshLayoutChain, renderDevISRWithLoaderCache, renderDevSSGWithLoaderCache, } from "./hmr.ts";
3
+ export { buildRouteMatcher, buildRouteRegex, collectIntermediateLayoutDirs, compareRouteSpecificity, compareRouteSpecificity as routeSpecificity, escapeRegExpChar, filePathToPattern, resolveMode, } from "./patterns.ts";
4
+ export { createDataEndpoint, createRoutePlugin } from "./plugin.ts";
5
+ export { applySchemaDefaults, detectQueryDefaultRedirect, mergeRouteSchemas, parseDataEndpointPath, queryDefaultRedirectHook, } from "./schemas.ts";
6
+ export type { ResolvedRoute, RootLayout, SegmentBoundary } from "./types.ts";
@@ -0,0 +1,28 @@
1
+ // @bun
2
+ export {
3
+ scanRootLayout,
4
+ scanPages,
5
+ compareRouteSpecificity2 as routeSpecificity,
6
+ resolveMode,
7
+ renderDevSSGWithLoaderCache,
8
+ renderDevISRWithLoaderCache,
9
+ refreshLayoutChain,
10
+ rebuildDevRoute,
11
+ queryDefaultRedirectHook,
12
+ parseDataEndpointPath,
13
+ mergeRouteSchemas,
14
+ loadProdRoutes,
15
+ importFreshRouteModuleCandidate,
16
+ filePathToPattern,
17
+ escapeRegExpChar,
18
+ detectQueryDefaultRedirect,
19
+ createRoutePlugin,
20
+ createDataEndpoint,
21
+ computeRouteDependencies,
22
+ compareRouteSpecificity,
23
+ collectRouteTags,
24
+ collectIntermediateLayoutDirs,
25
+ buildRouteRegex,
26
+ buildRouteMatcher,
27
+ applySchemaDefaults
28
+ };
@@ -0,0 +1,29 @@
1
+ // biome-ignore-all lint/performance/noBarrelFile: server/router barrel is the public surface of the routing module
2
+ export { collectRouteTags, loadProdRoutes, scanPages, scanRootLayout } from "./discovery.ts";
3
+ export {
4
+ computeRouteDependencies,
5
+ importFreshRouteModuleCandidate,
6
+ rebuildDevRoute,
7
+ refreshLayoutChain,
8
+ renderDevISRWithLoaderCache,
9
+ renderDevSSGWithLoaderCache,
10
+ } from "./hmr.ts";
11
+ export {
12
+ buildRouteMatcher,
13
+ buildRouteRegex,
14
+ collectIntermediateLayoutDirs,
15
+ compareRouteSpecificity,
16
+ compareRouteSpecificity as routeSpecificity,
17
+ escapeRegExpChar,
18
+ filePathToPattern,
19
+ resolveMode,
20
+ } from "./patterns.ts";
21
+ export { createDataEndpoint, createRoutePlugin } from "./plugin.ts";
22
+ export {
23
+ applySchemaDefaults,
24
+ detectQueryDefaultRedirect,
25
+ mergeRouteSchemas,
26
+ parseDataEndpointPath,
27
+ queryDefaultRedirectHook,
28
+ } from "./schemas.ts";
29
+ export type { ResolvedRoute, RootLayout, SegmentBoundary } from "./types.ts";
@@ -0,0 +1,40 @@
1
+ import type { RuntimePage, RuntimeRoute } from "../../client.ts";
2
+ export declare function collectIntermediateLayoutDirs(pagePath: string, rootPath: string): string[];
3
+ export declare function resolveMode(page: RuntimePage, routeChain: RuntimeRoute[]): "ssr" | "ssg" | "isr";
4
+ export declare function filePathToPattern(path: string): string;
5
+ export declare function escapeRegExpChar(ch: string): string;
6
+ /**
7
+ * Compares two route patterns by specificity so the `/_furin/data` matcher can
8
+ * prefer the more specific of two siblings that both match a pathname.
9
+ *
10
+ * Patterns are compared segment by segment from the left; the first position
11
+ * where they differ decides (literal > `:param` > `*`). When every shared
12
+ * position ties, the pattern with more explicit segments wins over a shorter
13
+ * one whose wildcard absorbs the tail.
14
+ *
15
+ * Returns a positive number when `a` is MORE specific than `b`, negative when
16
+ * less, and `0` only when the two are indistinguishable. This lexicographic
17
+ * ranking replaces the previous summed-weight score, which produced ties such
18
+ * as `/blog/new/:section` vs `/blog/:id/edit` (both summed to 8) that resolved
19
+ * non-deterministically by scan order.
20
+ */
21
+ export declare function compareRouteSpecificity(a: string, b: string): number;
22
+ /**
23
+ * Builds a regex from a route pattern, extracts named capture groups for
24
+ * each `:param` segment, and returns `{ regex, paramNames }`.
25
+ *
26
+ * Literal characters (e.g. dots in filenames like `v1.0`) are escaped so
27
+ * they are matched exactly rather than interpreted as regex syntax.
28
+ */
29
+ export declare function buildRouteRegex(pattern: string): {
30
+ regex: RegExp;
31
+ paramNames: string[];
32
+ };
33
+ export interface RoutePatternLike {
34
+ pattern: string;
35
+ }
36
+ export interface RouteMatch<TRoute extends RoutePatternLike> {
37
+ params: Record<string, string>;
38
+ route: TRoute;
39
+ }
40
+ export declare function buildRouteMatcher<TRoute extends RoutePatternLike>(routes: TRoute[]): (pathname: string) => RouteMatch<TRoute> | null;
@@ -0,0 +1,20 @@
1
+ import { type AnyElysia } from "elysia";
2
+ import type { ResolvedRoute, RootLayout } from "./types.ts";
3
+ export declare function createRoutePlugin(route: ResolvedRoute, root: RootLayout, buildId?: string): AnyElysia;
4
+ /**
5
+ * Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
6
+ *
7
+ * Returns an NDJSON stream (one-line, v1) produced by `toCrossJSONAsync`:
8
+ * Line 0 — CrossJSON serialisation of `{ ...syncData, ...deferredPromises }`
9
+ *
10
+ * The `deferredPromises` values are awaited by `toCrossJSONAsync` before
11
+ * serialising, so the client receives all data resolved in one round-trip.
12
+ * SPA navigation calls this endpoint via `parseDeferredNdjson` in
13
+ * `router-provider.tsx`.
14
+ *
15
+ * Special fields emitted alongside data:
16
+ * - `__furinStatus: 404` — when the loader called `notFound()`
17
+ * - `__furinNotFound` — not-found payload
18
+ * - `__furinRedirect` — logical path after a server-side redirect
19
+ */
20
+ export declare function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia;