@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.14

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 (58) hide show
  1. package/README.md +14 -232
  2. package/dist/await.d.ts +67 -0
  3. package/dist/build/index.js +2013 -191
  4. package/dist/cli/index.js +2007 -190
  5. package/dist/client.d.ts +33 -2
  6. package/dist/client.js +65 -1
  7. package/dist/deferred-ndjson.d.ts +32 -0
  8. package/dist/error.d.ts +14 -0
  9. package/dist/furin.d.ts +3 -0
  10. package/dist/furin.js +2684 -318
  11. package/dist/lang-detect.d.ts +5 -0
  12. package/dist/link.d.ts +1 -0
  13. package/dist/link.js +1453 -95
  14. package/dist/plugin/index.js +96 -25
  15. package/dist/plugin/transform-client.d.ts +2 -1
  16. package/dist/render/assemble.d.ts +32 -0
  17. package/dist/render/cache.d.ts +7 -0
  18. package/dist/render/element.d.ts +17 -1
  19. package/dist/render/index.d.ts +10 -1
  20. package/dist/render/index.ts +247 -44
  21. package/dist/render/loaders.d.ts +46 -3
  22. package/dist/render/shell.d.ts +16 -6
  23. package/dist/render/shell.ts +27 -12
  24. package/dist/router-provider.d.ts +86 -18
  25. package/dist/router.d.ts +63 -0
  26. package/dist/router.js +2768 -317
  27. package/dist/router.ts +543 -54
  28. package/dist/server-error.d.ts +12 -0
  29. package/dist/utils.d.ts +7 -0
  30. package/package.json +8 -7
  31. package/src/adapter/bun.ts +3 -3
  32. package/src/adapter/static.ts +73 -31
  33. package/src/await.tsx +175 -0
  34. package/src/build/client.ts +4 -8
  35. package/src/build/hydrate.ts +67 -1
  36. package/src/build/route-types.ts +5 -1
  37. package/src/build/scan-server.ts +6 -23
  38. package/src/client.ts +58 -1
  39. package/src/deferred-ndjson.ts +212 -0
  40. package/src/dev-page-plugin.ts +2 -0
  41. package/src/error.ts +18 -1
  42. package/src/furin.ts +12 -2
  43. package/src/lang-detect.ts +46 -0
  44. package/src/link.tsx +16 -3
  45. package/src/plugin/index.ts +7 -8
  46. package/src/plugin/transform-client.ts +108 -39
  47. package/src/render/assemble.ts +67 -0
  48. package/src/render/boundaries.tsx +23 -5
  49. package/src/render/cache.ts +7 -0
  50. package/src/render/default-screens.tsx +4 -11
  51. package/src/render/element.tsx +26 -3
  52. package/src/render/index.ts +247 -44
  53. package/src/render/loaders.ts +221 -18
  54. package/src/render/shell.ts +27 -12
  55. package/src/router-provider.tsx +414 -122
  56. package/src/router.ts +543 -54
  57. package/src/server-error.ts +47 -0
  58. package/src/utils.ts +31 -0
@@ -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,17 +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.
152
- * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico").
153
- * When provided, a `<link rel="icon">` tag is injected so browsers can locate
154
- * the favicon even when the site is served from a sub-path.
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).
155
168
  */
156
169
  export function generateProdIndexHtml(
157
170
  entryChunk: string,
158
171
  cssChunks: string[],
159
- buildId?: string,
160
- faviconHref?: string
172
+ buildId: string | undefined,
173
+ faviconHref: string | undefined,
174
+ staticMode: boolean
161
175
  ): string {
162
176
  const cssLinks = cssChunks
163
177
  .map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`)
@@ -169,6 +183,7 @@ export function generateProdIndexHtml(
169
183
  const faviconLink = faviconHref
170
184
  ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">\n`
171
185
  : "";
186
+ const modeMeta = staticMode ? ` <meta name="furin-mode" content="static">\n` : "";
172
187
 
173
188
  return `<!DOCTYPE html>
174
189
  <html lang="en">
@@ -176,7 +191,7 @@ export function generateProdIndexHtml(
176
191
  <meta charset="UTF-8">
177
192
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
178
193
  ${THEME_INIT_SCRIPT}
179
- ${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
194
+ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
180
195
  </head>
181
196
  <body>
182
197
  <div id="root"><!--ssr-outlet--></div>
@@ -269,6 +269,19 @@ export interface RouterProviderProps {
269
269
  }
270
270
  interface RouterState {
271
271
  data: Record<string, unknown>;
272
+ /**
273
+ * Set when the server's NDJSON payload carried an `__furinError` sentinel
274
+ * (loader threw a non-redirect `Response`, or an `Error`). The provider's
275
+ * render path injects a `<RouteErrorThrower>` in place of the page so the
276
+ * nearest `<FurinErrorBoundary>` catches a `FurinServerError` carrying the
277
+ * server's digest + status. Mirrors the `__furinError` channel that already
278
+ * exists for SSR digest correlation.
279
+ */
280
+ error?: {
281
+ digest: string;
282
+ message: string;
283
+ status: number;
284
+ };
272
285
  /** The canonical href after server-side redirects (e.g. query-default redirect). */
273
286
  finalHref?: string;
274
287
  /**
@@ -322,9 +335,13 @@ export declare function normalizeHref(href: string): string;
322
335
  * - `ok` — 2xx response with usable loader data; render normally.
323
336
  * - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`; the
324
337
  * caller should render the not-found UI inline (no full-page reload).
325
- * - `bail` — any other non-2xx (5xx, stale-deploy, unparseable payload…);
326
- * the caller falls back to a full-page navigation so the browser picks up
327
- * whatever the server wants to send (could be an error page, redirect, etc.).
338
+ * - `error` — server signalled `__FURIN_DATA__.__furinError` (loader threw a
339
+ * non-redirect `Response` or an `Error`). The caller surfaces this through
340
+ * the nearest `error.tsx` inline by throwing a `FurinServerError` during
341
+ * render so the existing `FurinErrorBoundary` catches it.
342
+ * - `bail` — any other non-2xx without sentinels (stale-deploy, unparseable
343
+ * payload, opaque crash…); the caller falls back to a full-page navigation
344
+ * so the browser shows whatever the server actually sent.
328
345
  *
329
346
  * @internal Exported for unit testing only.
330
347
  */
@@ -336,15 +353,24 @@ export type SpaResponseKind = {
336
353
  data?: unknown;
337
354
  message?: string;
338
355
  };
356
+ } | {
357
+ kind: "error";
358
+ error: {
359
+ digest: string;
360
+ message: string;
361
+ status: number;
362
+ };
339
363
  } | {
340
364
  kind: "bail";
341
365
  };
342
366
  /**
343
367
  * Pure classifier for an SPA-nav fetch result. Takes the HTTP status and the
344
- * already-parsed `__FURIN_DATA__` payload. The 404 signal is trusted over the
345
- * HTTP status (guards against proxies that rewrite status but preserve body),
346
- * while any other non-ok HTTP status triggers a bail even if the payload is
347
- * well-formed.
368
+ * already-parsed `__FURIN_DATA__` payload.
369
+ *
370
+ * Sentinels (`__furinError`, `__furinStatus`) are trusted over the raw HTTP
371
+ * status — proxies / CDNs sometimes rewrite the status code but pass the body
372
+ * through untouched. A non-2xx response without any sentinel triggers a bail
373
+ * so the browser handles it (could be an error page, redirect, etc.).
348
374
  *
349
375
  * @internal Exported for unit testing only.
350
376
  */
@@ -418,19 +444,26 @@ export interface RootBoundaryOptions {
418
444
  /**
419
445
  * Composes the outermost tree produced by `RouterProvider`:
420
446
  *
421
- * <FurinErrorBoundary digest onReset resetKey>
422
- * <RouterContext.Provider value={context}>
447
+ * <RouterContext.Provider value={context}>
448
+ * <FurinErrorBoundary digest onReset resetKey>
423
449
  * {pageElement}
424
- * </RouterContext.Provider>
425
- * </FurinErrorBoundary>
450
+ * </FurinErrorBoundary>
451
+ * </RouterContext.Provider>
452
+ *
453
+ * `RouterContext.Provider` is the OUTERMOST element so that a root-level
454
+ * `error.tsx` rendered by the boundary can still call `useRouter()` / render
455
+ * `<Link>` (the context is in scope above the boundary).
426
456
  *
427
- * This top boundary is the LAST line of defence. Per-segment
428
- * `FurinErrorBoundary`s inserted by `buildPageElement` only wrap the page
429
- * subtree BELOW the root layout, so they cannot catch errors thrown in:
457
+ * The `FurinErrorBoundary` is the LAST line of defence for render errors.
458
+ * Per-segment `FurinErrorBoundary`s inserted by `buildPageElement` only wrap
459
+ * the page subtree BELOW the root layout, so this top boundary is the only one
460
+ * that catches errors thrown in:
430
461
  * - the root layout itself,
431
- * - hydration mismatches (these tear the whole tree before any inner
432
- * boundary is reached),
433
- * - the RouterProvider / page-building scaffolding code.
462
+ * - hydration mismatches within the rendered tree.
463
+ *
464
+ * It does NOT catch errors thrown by `RouterProvider` itself or by the
465
+ * `buildPageElement` / `buildRouterTree` scaffolding — those run before the
466
+ * boundary exists in the tree, so React has no boundary to propagate to.
434
467
  *
435
468
  * We deliberately omit the `fallback` prop so the boundary falls back to its
436
469
  * built-in `DefaultErrorFallback` — if a user-authored fallback crashed
@@ -460,7 +493,42 @@ export interface BoundaryOptions {
460
493
  resetKey?: string | number;
461
494
  }
462
495
  /** @internal Exported for unit testing only. */
463
- export declare function buildPageElement(match: LoadedClientRoute, root: RuntimeRoute | null, data: Record<string, unknown>, options: BoundaryOptions | undefined): React.ReactNode;
496
+ export declare function buildPageElement(match: LoadedClientRoute, root: RuntimeRoute | null, data: Record<string, unknown>, options: BoundaryOptions | undefined, error: {
497
+ digest: string;
498
+ message: string;
499
+ status: number;
500
+ } | undefined): React.ReactNode;
501
+ /**
502
+ * Builds the URL the SPA navigation flow uses to fetch a route's loader data.
503
+ *
504
+ * Two transports are supported:
505
+ *
506
+ * • **Runtime (SSR/ISR/dev)** — `${basePath}/_furin/data?path=<logicalHref>`.
507
+ * Served by the Elysia plugin in `createDataEndpoint`, which dynamically
508
+ * re-runs the loader with the requested path/query.
509
+ *
510
+ * • **Static export** — `${basePath}<logicalPathname>/__furin_data.ndjson`.
511
+ * Pre-written next to each `index.html` by `buildStaticTarget`, served
512
+ * verbatim by any file server (GitHub Pages, S3, …). The loader does not
513
+ * execute at request time, so query strings are *intentionally* ignored:
514
+ * a single NDJSON exists per route, computed at build time.
515
+ *
516
+ * `staticMode` is decided once at boot from the `<meta name="furin-mode">`
517
+ * tag injected by `generateProdIndexHtml` — flipping the transport at runtime
518
+ * for the wrong deployment would just produce 404s.
519
+ *
520
+ * @internal Exported for unit testing.
521
+ */
522
+ export declare function buildDataEndpoint(basePath: string, logicalHref: string, staticMode: boolean): string;
523
+ /**
524
+ * Reads `<meta name="furin-mode" content="static">` from the document at boot.
525
+ * The static adapter injects this tag (`shell.ts:generateProdIndexHtml`) so the
526
+ * SPA client picks the static-friendly transport. SSR/dev shells omit the tag
527
+ * and the client uses the runtime endpoint.
528
+ *
529
+ * @internal Exported for unit testing.
530
+ */
531
+ export declare function detectStaticMode(): boolean;
464
532
  /** Strips basePath prefix from a physical pathname, returning the logical path. */
465
533
  export declare function toLogical(physicalPathname: string, basePath: string): string;
466
534
  export declare function RouterProvider({ routes, root, initialMatch, initialData, initialDigest, initialNotFound, autoRefresh, basePath, defaultPreload, defaultPreloadDelay, defaultPreloadStaleTime, prefetchCacheSize, }: RouterProviderProps): React.ReactElement;
package/dist/router.d.ts CHANGED
@@ -69,6 +69,36 @@ export declare function scanPages(pagesDir: string): Promise<{
69
69
  routes: ResolvedRoute[];
70
70
  }>;
71
71
  export declare function scanRootLayout(pagesDir: string): Promise<RootLayout>;
72
+ /**
73
+ * Detects whether a validator filled in default query values that the original
74
+ * URL did not carry, and returns the canonical `pathname + search` to redirect
75
+ * to — or `undefined` when the URL already reflects the resolved query.
76
+ *
77
+ * Pure helper extracted from `queryDefaultRedirectHook` so the `/_furin/data`
78
+ * NDJSON endpoint can detect the same condition without going through
79
+ * Elysia's `status()` shim (which only emits HTTP 302s, unparseable by the
80
+ * SPA client).
81
+ *
82
+ * @internal Exported for unit testing.
83
+ */
84
+ export declare function detectQueryDefaultRedirect(request: Request, resolvedQuery: Record<string, unknown>): string | undefined;
85
+ /**
86
+ * Parses the `?path=` argument of `/_furin/data`, rejecting absolute /
87
+ * protocol-relative inputs that would let a caller smuggle a foreign origin
88
+ * into the synthetic loader request.
89
+ *
90
+ * Returns `{ url, pathname }` on success, or `undefined` when the input is
91
+ * unsafe (the caller should reply 400). `new URL(rawPath, base)` ignores the
92
+ * base when `rawPath` is itself absolute, so without these prefix and origin
93
+ * checks a value like `https://evil.com/foo` would propagate to
94
+ * `syntheticRequest.url`.
95
+ *
96
+ * @internal Exported for unit testing.
97
+ */
98
+ export declare function parseDataEndpointPath(rawPath: string): {
99
+ url: URL;
100
+ pathname: string;
101
+ } | undefined;
72
102
  /** @internal Exported for unit testing. */
73
103
  export declare function queryDefaultRedirectHook({ request, query, status, set }: Context): import("elysia").ElysiaCustomStatusResponse<"Found", "Found", 302> | undefined;
74
104
  /**
@@ -81,6 +111,22 @@ export declare function queryDefaultRedirectHook({ request, query, status, set }
81
111
  * it defaults to the real `import()`.
82
112
  */
83
113
  export declare function refreshLayoutChain(chain: RuntimeRoute[], pagePath: string, rootPath: string, importFn: ((specifier: string) => Promise<Record<string, unknown>>) | undefined): Promise<void>;
114
+ /**
115
+ * Rebuilds a `ResolvedRoute` from freshly-imported `page` and `chain` so that
116
+ * `mode` reflects the CURRENT contents of the page module — not the value
117
+ * captured at scan time.
118
+ *
119
+ * In dev, `handleDevRequest` re-imports the page on every request to pick up
120
+ * source edits via the `?furin-server&t=<ts>` cache-buster. Without this
121
+ * function the spread `{ ...route, page, chain }` would carry over the stale
122
+ * `route.mode` resolved at startup, so toggling `revalidate` or removing a
123
+ * loader in source would not retake effect until a server restart.
124
+ *
125
+ * Only `mode` is recomputed: it is the only field DERIVED from page+chain.
126
+ * Structural fields (`pattern`, `path`, `segmentBoundaries`, `error`,
127
+ * `notFound`) are scan-time invariants in dev and are preserved as-is.
128
+ */
129
+ export declare function rebuildDevRoute(base: ResolvedRoute, page: RuntimePage, chain: RuntimeRoute[]): ResolvedRoute;
84
130
  /**
85
131
  * @internal Lists every source file whose contents can affect the render
86
132
  * output for a given page: the page itself, every intermediate `_route.*`
@@ -108,3 +154,20 @@ export declare function mergeRouteSchemas(routeChain: RuntimeRoute[], key: "para
108
154
  export declare function createRoutePlugin(route: ResolvedRoute, root: RootLayout, buildId?: string): AnyElysia;
109
155
  export declare function resolveMode(page: RuntimePage, routeChain: RuntimeRoute[]): "ssr" | "ssg" | "isr";
110
156
  export declare function filePathToPattern(path: string): string;
157
+ /**
158
+ * Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
159
+ *
160
+ * Returns an NDJSON stream (one-line, v1) produced by `toCrossJSONAsync`:
161
+ * Line 0 — CrossJSON serialisation of `{ ...syncData, ...deferredPromises }`
162
+ *
163
+ * The `deferredPromises` values are awaited by `toCrossJSONAsync` before
164
+ * serialising, so the client receives all data resolved in one round-trip.
165
+ * SPA navigation calls this endpoint via `parseDeferredNdjson` in
166
+ * `router-provider.tsx`.
167
+ *
168
+ * Special fields emitted alongside data:
169
+ * - `__furinStatus: 404` — when the loader called `notFound()`
170
+ * - `__furinNotFound` — not-found payload
171
+ * - `__furinRedirect` — logical path after a server-side redirect
172
+ */
173
+ export declare function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia;