@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.
- package/README.md +14 -232
- package/dist/await.d.ts +67 -0
- package/dist/build/index.js +2013 -191
- package/dist/cli/index.js +2007 -190
- package/dist/client.d.ts +33 -2
- package/dist/client.js +65 -1
- package/dist/deferred-ndjson.d.ts +32 -0
- package/dist/error.d.ts +14 -0
- package/dist/furin.d.ts +3 -0
- package/dist/furin.js +2684 -318
- package/dist/lang-detect.d.ts +5 -0
- package/dist/link.d.ts +1 -0
- package/dist/link.js +1453 -95
- package/dist/plugin/index.js +96 -25
- package/dist/plugin/transform-client.d.ts +2 -1
- package/dist/render/assemble.d.ts +32 -0
- package/dist/render/cache.d.ts +7 -0
- package/dist/render/element.d.ts +17 -1
- package/dist/render/index.d.ts +10 -1
- package/dist/render/index.ts +247 -44
- package/dist/render/loaders.d.ts +46 -3
- package/dist/render/shell.d.ts +16 -6
- package/dist/render/shell.ts +27 -12
- package/dist/router-provider.d.ts +86 -18
- package/dist/router.d.ts +63 -0
- package/dist/router.js +2768 -317
- package/dist/router.ts +543 -54
- package/dist/server-error.d.ts +12 -0
- package/dist/utils.d.ts +7 -0
- package/package.json +8 -7
- package/src/adapter/bun.ts +3 -3
- package/src/adapter/static.ts +73 -31
- package/src/await.tsx +175 -0
- package/src/build/client.ts +4 -8
- package/src/build/hydrate.ts +67 -1
- package/src/build/route-types.ts +5 -1
- package/src/build/scan-server.ts +6 -23
- package/src/client.ts +58 -1
- package/src/deferred-ndjson.ts +212 -0
- package/src/dev-page-plugin.ts +2 -0
- package/src/error.ts +18 -1
- package/src/furin.ts +12 -2
- package/src/lang-detect.ts +46 -0
- package/src/link.tsx +16 -3
- package/src/plugin/index.ts +7 -8
- package/src/plugin/transform-client.ts +108 -39
- package/src/render/assemble.ts +67 -0
- package/src/render/boundaries.tsx +23 -5
- package/src/render/cache.ts +7 -0
- package/src/render/default-screens.tsx +4 -11
- package/src/render/element.tsx +26 -3
- package/src/render/index.ts +247 -44
- package/src/render/loaders.ts +221 -18
- package/src/render/shell.ts +27 -12
- package/src/router-provider.tsx +414 -122
- package/src/router.ts +543 -54
- package/src/server-error.ts +47 -0
- package/src/utils.ts +31 -0
package/src/router.ts
CHANGED
|
@@ -3,7 +3,12 @@ import { readdir } from "node:fs/promises";
|
|
|
3
3
|
import { join, parse } from "node:path";
|
|
4
4
|
import { type AnyElysia, type Context, Elysia, t } from "elysia";
|
|
5
5
|
import type { AnySchema } from "elysia/types";
|
|
6
|
+
import { toCrossJSON, toCrossJSONAsync } from "seroval";
|
|
6
7
|
import type { RuntimePage, RuntimeRoute } from "./client.ts";
|
|
8
|
+
// Use the project-local `useLogger` (not `evlog/elysia` directly) so the
|
|
9
|
+
// `/_furin/data` enrichment also works in synthetic render scopes (ISR/SSG)
|
|
10
|
+
// and falls back to a no-op outside any request — see context-logger.ts.
|
|
11
|
+
import { useLogger } from "./context-logger.ts";
|
|
7
12
|
import type { ErrorComponent } from "./error.ts";
|
|
8
13
|
import { type CompileContext, getCompileContext } from "./internal.ts";
|
|
9
14
|
import type { NotFoundComponent } from "./not-found.ts";
|
|
@@ -16,18 +21,22 @@ import {
|
|
|
16
21
|
setDevISRLoaderCache,
|
|
17
22
|
setDevSSGLoaderCache,
|
|
18
23
|
} from "./render/dev-cache.ts";
|
|
24
|
+
import { computeErrorDigest } from "./render/digest.ts";
|
|
19
25
|
import {
|
|
20
26
|
handleISR,
|
|
21
27
|
type LoaderResult,
|
|
22
28
|
prerenderSSG,
|
|
23
29
|
renderSSR,
|
|
24
30
|
runLoaders,
|
|
31
|
+
serializeDeferredRejection,
|
|
25
32
|
} from "./render/index.ts";
|
|
33
|
+
import { extractTitle } from "./render/shell.ts";
|
|
26
34
|
import { IS_DEV } from "./runtime-env.ts";
|
|
27
35
|
import {
|
|
28
36
|
collectRouteChainFromRoute,
|
|
29
37
|
isFurinPage,
|
|
30
38
|
isFurinRoute,
|
|
39
|
+
mapWithConcurrency,
|
|
31
40
|
validateRouteChain,
|
|
32
41
|
} from "./utils.ts";
|
|
33
42
|
|
|
@@ -200,8 +209,10 @@ export async function scanRootLayout(pagesDir: string): Promise<RootLayout> {
|
|
|
200
209
|
throw new Error("[furin] root.tsx: createRoute() has no layout.");
|
|
201
210
|
}
|
|
202
211
|
|
|
203
|
-
const notFoundEntry = await
|
|
204
|
-
|
|
212
|
+
const [notFoundEntry, errorEntry] = await Promise.all([
|
|
213
|
+
loadConventionComponent<NotFoundComponent>(pagesDir, "not-found"),
|
|
214
|
+
loadConventionComponent<ErrorComponent>(pagesDir, "error"),
|
|
215
|
+
]);
|
|
205
216
|
return {
|
|
206
217
|
path: rootPath,
|
|
207
218
|
route: rootExport,
|
|
@@ -271,28 +282,23 @@ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<Resolv
|
|
|
271
282
|
continue;
|
|
272
283
|
}
|
|
273
284
|
|
|
274
|
-
const notFound = await
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
absolutePath,
|
|
292
|
-
pagesDir,
|
|
293
|
-
notFoundCache,
|
|
294
|
-
errorCache
|
|
295
|
-
);
|
|
285
|
+
const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
|
|
286
|
+
resolveNearestConvention<NotFoundComponent>(
|
|
287
|
+
absolutePath,
|
|
288
|
+
pagesDir,
|
|
289
|
+
"not-found",
|
|
290
|
+
notFoundCache,
|
|
291
|
+
root.notFound
|
|
292
|
+
),
|
|
293
|
+
resolveNearestConvention<ErrorComponent>(
|
|
294
|
+
absolutePath,
|
|
295
|
+
pagesDir,
|
|
296
|
+
"error",
|
|
297
|
+
errorCache,
|
|
298
|
+
root.error
|
|
299
|
+
),
|
|
300
|
+
collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache),
|
|
301
|
+
]);
|
|
296
302
|
|
|
297
303
|
if (IS_DEV) {
|
|
298
304
|
const devRoute = await buildDevRoute(absolutePath, relativePath, root);
|
|
@@ -365,15 +371,20 @@ async function collectSegmentBoundaries(
|
|
|
365
371
|
for (let depth = 0; depth < dirs.length; depth++) {
|
|
366
372
|
const dir = dirs[depth] as string;
|
|
367
373
|
|
|
368
|
-
|
|
369
|
-
errorCache.
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
374
|
+
const [errorEntry, notFoundEntry] = await Promise.all([
|
|
375
|
+
errorCache.has(dir)
|
|
376
|
+
? Promise.resolve(errorCache.get(dir))
|
|
377
|
+
: loadConventionComponent<ErrorComponent>(dir, "error").then((r) => {
|
|
378
|
+
errorCache.set(dir, r);
|
|
379
|
+
return r;
|
|
380
|
+
}),
|
|
381
|
+
notFoundCache.has(dir)
|
|
382
|
+
? Promise.resolve(notFoundCache.get(dir))
|
|
383
|
+
: loadConventionComponent<NotFoundComponent>(dir, "not-found").then((r) => {
|
|
384
|
+
notFoundCache.set(dir, r);
|
|
385
|
+
return r;
|
|
386
|
+
}),
|
|
387
|
+
]);
|
|
377
388
|
if (errorEntry || notFoundEntry) {
|
|
378
389
|
boundaries.push({
|
|
379
390
|
path: dir,
|
|
@@ -467,16 +478,28 @@ async function buildDevRoute(
|
|
|
467
478
|
// contains keys absent from the URL, defaults were applied → 302 redirect to
|
|
468
479
|
// the canonical URL so the address bar always reflects the actual app state.
|
|
469
480
|
|
|
470
|
-
/**
|
|
471
|
-
|
|
472
|
-
|
|
481
|
+
/**
|
|
482
|
+
* Detects whether a validator filled in default query values that the original
|
|
483
|
+
* URL did not carry, and returns the canonical `pathname + search` to redirect
|
|
484
|
+
* to — or `undefined` when the URL already reflects the resolved query.
|
|
485
|
+
*
|
|
486
|
+
* Pure helper extracted from `queryDefaultRedirectHook` so the `/_furin/data`
|
|
487
|
+
* NDJSON endpoint can detect the same condition without going through
|
|
488
|
+
* Elysia's `status()` shim (which only emits HTTP 302s, unparseable by the
|
|
489
|
+
* SPA client).
|
|
490
|
+
*
|
|
491
|
+
* @internal Exported for unit testing.
|
|
492
|
+
*/
|
|
493
|
+
export function detectQueryDefaultRedirect(
|
|
494
|
+
request: Request,
|
|
495
|
+
resolvedQuery: Record<string, unknown>
|
|
496
|
+
): string | undefined {
|
|
473
497
|
const queryKeys = Object.keys(resolvedQuery);
|
|
474
498
|
if (queryKeys.length === 0) {
|
|
475
499
|
return;
|
|
476
500
|
}
|
|
477
501
|
|
|
478
502
|
const rawParams = new URL(request.url).searchParams;
|
|
479
|
-
|
|
480
503
|
let needsRedirect = false;
|
|
481
504
|
for (const key of queryKeys) {
|
|
482
505
|
if (!rawParams.has(key) && resolvedQuery[key] != null) {
|
|
@@ -494,8 +517,45 @@ export function queryDefaultRedirectHook({ request, query, status, set }: Contex
|
|
|
494
517
|
url.searchParams.set(k, String(v));
|
|
495
518
|
}
|
|
496
519
|
}
|
|
520
|
+
return url.pathname + url.search;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Parses the `?path=` argument of `/_furin/data`, rejecting absolute /
|
|
525
|
+
* protocol-relative inputs that would let a caller smuggle a foreign origin
|
|
526
|
+
* into the synthetic loader request.
|
|
527
|
+
*
|
|
528
|
+
* Returns `{ url, pathname }` on success, or `undefined` when the input is
|
|
529
|
+
* unsafe (the caller should reply 400). `new URL(rawPath, base)` ignores the
|
|
530
|
+
* base when `rawPath` is itself absolute, so without these prefix and origin
|
|
531
|
+
* checks a value like `https://evil.com/foo` would propagate to
|
|
532
|
+
* `syntheticRequest.url`.
|
|
533
|
+
*
|
|
534
|
+
* @internal Exported for unit testing.
|
|
535
|
+
*/
|
|
536
|
+
export function parseDataEndpointPath(rawPath: string): { url: URL; pathname: string } | undefined {
|
|
537
|
+
if (rawPath.includes("://") || rawPath.startsWith("//")) {
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
let url: URL;
|
|
541
|
+
try {
|
|
542
|
+
url = new URL(rawPath, "http://localhost");
|
|
543
|
+
} catch {
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
if (url.origin !== "http://localhost") {
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
return { url, pathname: url.pathname };
|
|
550
|
+
}
|
|
497
551
|
|
|
498
|
-
|
|
552
|
+
/** @internal Exported for unit testing. */
|
|
553
|
+
export function queryDefaultRedirectHook({ request, query, status, set }: Context) {
|
|
554
|
+
const location = detectQueryDefaultRedirect(request, query as Record<string, unknown>);
|
|
555
|
+
if (!location) {
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
set.headers.location = location;
|
|
499
559
|
return status("Found");
|
|
500
560
|
}
|
|
501
561
|
|
|
@@ -616,12 +676,19 @@ export async function refreshLayoutChain(
|
|
|
616
676
|
// so we must only advance chainIdx for directories whose _route module actually
|
|
617
677
|
// exists. A positional assumption (i = chainIdx - 1) drifts whenever
|
|
618
678
|
// isModuleNotFoundError is swallowed for a gap directory.
|
|
679
|
+
//
|
|
680
|
+
// Imports are parallelised for speed; patching stays sequential so the
|
|
681
|
+
// chainIdx-to-layoutDir positional mapping remains deterministic.
|
|
682
|
+
const freshMods = await Promise.all(
|
|
683
|
+
layoutDirs.map((layoutDir) =>
|
|
684
|
+
importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx)
|
|
685
|
+
)
|
|
686
|
+
);
|
|
619
687
|
let chainIdx = 1; // chain[0] is the root
|
|
620
|
-
for (const
|
|
688
|
+
for (const freshMod of freshMods) {
|
|
621
689
|
if (chainIdx >= chain.length) {
|
|
622
690
|
break;
|
|
623
691
|
}
|
|
624
|
-
const freshMod = await importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx);
|
|
625
692
|
if (!freshMod) {
|
|
626
693
|
// No _route module in this directory — no chain entry to match, so
|
|
627
694
|
// do NOT advance chainIdx. The next deeper layoutDir may correspond
|
|
@@ -638,6 +705,34 @@ export async function refreshLayoutChain(
|
|
|
638
705
|
}
|
|
639
706
|
}
|
|
640
707
|
|
|
708
|
+
/**
|
|
709
|
+
* Rebuilds a `ResolvedRoute` from freshly-imported `page` and `chain` so that
|
|
710
|
+
* `mode` reflects the CURRENT contents of the page module — not the value
|
|
711
|
+
* captured at scan time.
|
|
712
|
+
*
|
|
713
|
+
* In dev, `handleDevRequest` re-imports the page on every request to pick up
|
|
714
|
+
* source edits via the `?furin-server&t=<ts>` cache-buster. Without this
|
|
715
|
+
* function the spread `{ ...route, page, chain }` would carry over the stale
|
|
716
|
+
* `route.mode` resolved at startup, so toggling `revalidate` or removing a
|
|
717
|
+
* loader in source would not retake effect until a server restart.
|
|
718
|
+
*
|
|
719
|
+
* Only `mode` is recomputed: it is the only field DERIVED from page+chain.
|
|
720
|
+
* Structural fields (`pattern`, `path`, `segmentBoundaries`, `error`,
|
|
721
|
+
* `notFound`) are scan-time invariants in dev and are preserved as-is.
|
|
722
|
+
*/
|
|
723
|
+
export function rebuildDevRoute(
|
|
724
|
+
base: ResolvedRoute,
|
|
725
|
+
page: RuntimePage,
|
|
726
|
+
chain: RuntimeRoute[]
|
|
727
|
+
): ResolvedRoute {
|
|
728
|
+
return {
|
|
729
|
+
...base,
|
|
730
|
+
page,
|
|
731
|
+
routeChain: chain,
|
|
732
|
+
mode: resolveMode(page, chain),
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
|
|
641
736
|
/** @internal Handles a request in dev mode — re-imports the page fresh on every request. */
|
|
642
737
|
async function handleDevRequest(
|
|
643
738
|
route: ResolvedRoute,
|
|
@@ -684,7 +779,7 @@ async function handleDevRequest(
|
|
|
684
779
|
chain[0].loader = currentRoot.route.loader;
|
|
685
780
|
}
|
|
686
781
|
|
|
687
|
-
const refreshedRoute
|
|
782
|
+
const refreshedRoute = rebuildDevRoute(route, page, chain);
|
|
688
783
|
|
|
689
784
|
// Live ISR — the loader chain is short-circuited by the dev cache when
|
|
690
785
|
// a fresh entry exists. HTML re-assembles every time so the dev shell
|
|
@@ -733,20 +828,21 @@ async function renderDevISRWithLoaderCache(
|
|
|
733
828
|
if (cached && isDevLoaderCacheValid(cached)) {
|
|
734
829
|
const precomputed: LoaderResult = {
|
|
735
830
|
type: "data",
|
|
736
|
-
|
|
831
|
+
syncData: cached.loaderData,
|
|
832
|
+
deferredPromises: undefined,
|
|
737
833
|
headers: cached.headers,
|
|
738
834
|
};
|
|
739
835
|
return renderSSR(route, ctx, root, precomputed);
|
|
740
836
|
}
|
|
741
837
|
|
|
742
|
-
const result = await runLoaders(route, ctx
|
|
838
|
+
const result = await runLoaders(route, ctx);
|
|
743
839
|
if (result.type === "data") {
|
|
744
840
|
const revalidate = route.page._route.revalidate ?? 60;
|
|
745
841
|
const entry: DevLoaderCacheEntry = {
|
|
746
842
|
dependencies: computeRouteDependencies(route.path, root.path),
|
|
747
843
|
generatedAt: Date.now(),
|
|
748
844
|
headers: result.headers,
|
|
749
|
-
loaderData: result.
|
|
845
|
+
loaderData: result.syncData,
|
|
750
846
|
mode: "isr",
|
|
751
847
|
revalidate,
|
|
752
848
|
};
|
|
@@ -773,19 +869,20 @@ async function renderDevSSGWithLoaderCache(
|
|
|
773
869
|
if (cached && isDevLoaderCacheValid(cached)) {
|
|
774
870
|
const precomputed: LoaderResult = {
|
|
775
871
|
type: "data",
|
|
776
|
-
|
|
872
|
+
syncData: cached.loaderData,
|
|
873
|
+
deferredPromises: undefined,
|
|
777
874
|
headers: cached.headers,
|
|
778
875
|
};
|
|
779
876
|
return renderSSR(route, ctx, root, precomputed);
|
|
780
877
|
}
|
|
781
878
|
|
|
782
|
-
const result = await runLoaders(route, ctx
|
|
879
|
+
const result = await runLoaders(route, ctx);
|
|
783
880
|
if (result.type === "data") {
|
|
784
881
|
const entry: DevLoaderCacheEntry = {
|
|
785
882
|
dependencies: computeRouteDependencies(route.path, root.path),
|
|
786
883
|
generatedAt: Date.now(),
|
|
787
884
|
headers: result.headers,
|
|
788
|
-
loaderData: result.
|
|
885
|
+
loaderData: result.syncData,
|
|
789
886
|
mode: "ssg",
|
|
790
887
|
// SSG entries are forever-fresh — only source-aware invalidation drops them.
|
|
791
888
|
revalidate: Number.POSITIVE_INFINITY,
|
|
@@ -872,7 +969,7 @@ export function mergeRouteSchemas(
|
|
|
872
969
|
routeChain: RuntimeRoute[],
|
|
873
970
|
key: "params" | "query"
|
|
874
971
|
): AnySchema | undefined {
|
|
875
|
-
const schemas = routeChain.
|
|
972
|
+
const schemas = routeChain.flatMap((r) => (r[key] ? [r[key]] : [])) as Record<string, unknown>[];
|
|
876
973
|
|
|
877
974
|
if (schemas.length === 0) {
|
|
878
975
|
return;
|
|
@@ -954,6 +1051,13 @@ export function createRoutePlugin(route: ResolvedRoute, root: RootLayout, buildI
|
|
|
954
1051
|
return plugin;
|
|
955
1052
|
}
|
|
956
1053
|
|
|
1054
|
+
/**
|
|
1055
|
+
* Per-level cap on parallel directory traversals. Bounds peak in-flight
|
|
1056
|
+
* `readdir` calls to roughly `DIR_SCAN_CONCURRENCY * tree-depth`, which keeps
|
|
1057
|
+
* a wide flat pagesDir from opening thousands of FDs at once.
|
|
1058
|
+
*/
|
|
1059
|
+
const DIR_SCAN_CONCURRENCY = 8;
|
|
1060
|
+
|
|
957
1061
|
async function collectPageFilePaths(dir: string): Promise<string[]> {
|
|
958
1062
|
const files: string[] = [];
|
|
959
1063
|
|
|
@@ -966,17 +1070,21 @@ async function collectPageFilePaths(dir: string): Promise<string[]> {
|
|
|
966
1070
|
a.name.localeCompare(b.name)
|
|
967
1071
|
);
|
|
968
1072
|
|
|
969
|
-
|
|
1073
|
+
// Walk subdirectories with bounded parallelism, then merge results in the
|
|
1074
|
+
// original alphabetical entry order so the depth-first interleaving is
|
|
1075
|
+
// preserved (file, then its sub-tree, then next file…).
|
|
1076
|
+
const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
|
|
970
1077
|
const absolutePath = join(dir, entry.name);
|
|
971
|
-
|
|
972
1078
|
if (entry.isDirectory()) {
|
|
973
|
-
|
|
974
|
-
continue;
|
|
1079
|
+
return await collectPageFilePaths(absolutePath);
|
|
975
1080
|
}
|
|
976
|
-
|
|
977
1081
|
if (entry.isFile()) {
|
|
978
|
-
|
|
1082
|
+
return [absolutePath];
|
|
979
1083
|
}
|
|
1084
|
+
return [];
|
|
1085
|
+
});
|
|
1086
|
+
for (const chunk of resolved) {
|
|
1087
|
+
files.push(...chunk);
|
|
980
1088
|
}
|
|
981
1089
|
|
|
982
1090
|
return files;
|
|
@@ -1032,3 +1140,384 @@ export function filePathToPattern(path: string): string {
|
|
|
1032
1140
|
|
|
1033
1141
|
return `/${segments.join("/")}`;
|
|
1034
1142
|
}
|
|
1143
|
+
|
|
1144
|
+
// ── /_furin/data endpoint ──────────────────────────────────────────────────────
|
|
1145
|
+
|
|
1146
|
+
const REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/;
|
|
1147
|
+
|
|
1148
|
+
function escapeRegExpChar(ch: string): string {
|
|
1149
|
+
return REGEX_META_CHARS_RE.test(ch) ? `\\${ch}` : ch;
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
/**
|
|
1153
|
+
* Scores how specific a route pattern is so the `/_furin/data` matcher can
|
|
1154
|
+
* prefer a static route over a dynamic sibling that also matches. Per segment:
|
|
1155
|
+
* a literal segment outranks a `:param`, which outranks a `*` wildcard.
|
|
1156
|
+
*/
|
|
1157
|
+
function routeSpecificity(pattern: string): number {
|
|
1158
|
+
let score = 0;
|
|
1159
|
+
for (const segment of pattern.split("/")) {
|
|
1160
|
+
if (segment.length === 0) {
|
|
1161
|
+
continue;
|
|
1162
|
+
}
|
|
1163
|
+
if (segment === "*") {
|
|
1164
|
+
score += 1;
|
|
1165
|
+
} else if (segment.startsWith(":")) {
|
|
1166
|
+
score += 2;
|
|
1167
|
+
} else {
|
|
1168
|
+
score += 3;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
return score;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/**
|
|
1175
|
+
* Builds a regex from a route pattern, extracts named capture groups for
|
|
1176
|
+
* each `:param` segment, and returns `{ regex, paramNames }`.
|
|
1177
|
+
*
|
|
1178
|
+
* Literal characters (e.g. dots in filenames like `v1.0`) are escaped so
|
|
1179
|
+
* they are matched exactly rather than interpreted as regex syntax.
|
|
1180
|
+
*/
|
|
1181
|
+
function buildRouteRegex(pattern: string): { regex: RegExp; paramNames: string[] } {
|
|
1182
|
+
const paramNames: string[] = [];
|
|
1183
|
+
let source = "";
|
|
1184
|
+
let i = 0;
|
|
1185
|
+
while (i < pattern.length) {
|
|
1186
|
+
if (pattern[i] === ":") {
|
|
1187
|
+
const start = ++i;
|
|
1188
|
+
while (i < pattern.length && pattern[i] !== "/") {
|
|
1189
|
+
i++;
|
|
1190
|
+
}
|
|
1191
|
+
paramNames.push(pattern.slice(start, i));
|
|
1192
|
+
source += "([^/]+)";
|
|
1193
|
+
} else if (pattern[i] === "*") {
|
|
1194
|
+
paramNames.push("*");
|
|
1195
|
+
source += "(.*)";
|
|
1196
|
+
i++;
|
|
1197
|
+
} else {
|
|
1198
|
+
const ch = pattern[i];
|
|
1199
|
+
if (ch !== undefined) {
|
|
1200
|
+
source += escapeRegExpChar(ch);
|
|
1201
|
+
}
|
|
1202
|
+
i++;
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
return { regex: new RegExp(`^${source}$`), paramNames };
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* Applies top-level `default` values from a TypeBox TObject schema to a
|
|
1210
|
+
* values record. Used in the `/_furin/data` endpoint so loaders see the same
|
|
1211
|
+
* defaulted query objects that the SSR path produces via Elysia's guard.
|
|
1212
|
+
*/
|
|
1213
|
+
function applySchemaDefaults(
|
|
1214
|
+
schema: Record<string, unknown> | undefined,
|
|
1215
|
+
values: Record<string, unknown>
|
|
1216
|
+
): Record<string, unknown> {
|
|
1217
|
+
if (!schema || typeof schema !== "object") {
|
|
1218
|
+
return values;
|
|
1219
|
+
}
|
|
1220
|
+
const s = schema as Record<string, unknown>;
|
|
1221
|
+
if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
|
|
1222
|
+
return values;
|
|
1223
|
+
}
|
|
1224
|
+
const result = { ...values };
|
|
1225
|
+
const properties = s.properties as Record<string, Record<string, unknown>>;
|
|
1226
|
+
for (const [key, propSchema] of Object.entries(properties)) {
|
|
1227
|
+
if (
|
|
1228
|
+
!(key in result) &&
|
|
1229
|
+
propSchema &&
|
|
1230
|
+
typeof propSchema === "object" &&
|
|
1231
|
+
"default" in propSchema
|
|
1232
|
+
) {
|
|
1233
|
+
result[key] = propSchema.default;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
return result;
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
/**
|
|
1240
|
+
* Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
|
|
1241
|
+
*
|
|
1242
|
+
* Returns an NDJSON stream (one-line, v1) produced by `toCrossJSONAsync`:
|
|
1243
|
+
* Line 0 — CrossJSON serialisation of `{ ...syncData, ...deferredPromises }`
|
|
1244
|
+
*
|
|
1245
|
+
* The `deferredPromises` values are awaited by `toCrossJSONAsync` before
|
|
1246
|
+
* serialising, so the client receives all data resolved in one round-trip.
|
|
1247
|
+
* SPA navigation calls this endpoint via `parseDeferredNdjson` in
|
|
1248
|
+
* `router-provider.tsx`.
|
|
1249
|
+
*
|
|
1250
|
+
* Special fields emitted alongside data:
|
|
1251
|
+
* - `__furinStatus: 404` — when the loader called `notFound()`
|
|
1252
|
+
* - `__furinNotFound` — not-found payload
|
|
1253
|
+
* - `__furinRedirect` — logical path after a server-side redirect
|
|
1254
|
+
*/
|
|
1255
|
+
export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
|
|
1256
|
+
const plugin = new Elysia();
|
|
1257
|
+
|
|
1258
|
+
plugin.get(
|
|
1259
|
+
"/_furin/data",
|
|
1260
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: data endpoint handler validates path, resolves loaders, handles deferred/SPA/ISR modes — each branch is a distinct protocol case; splitting would spread context across many functions
|
|
1261
|
+
async (ctx) => {
|
|
1262
|
+
const rawPath = ctx.query.path;
|
|
1263
|
+
if (!rawPath || typeof rawPath !== "string") {
|
|
1264
|
+
return new Response("Missing required query param: path", { status: 400 });
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
const parsed = parseDataEndpointPath(rawPath);
|
|
1268
|
+
if (!parsed) {
|
|
1269
|
+
return new Response("Invalid path", { status: 400 });
|
|
1270
|
+
}
|
|
1271
|
+
const { url, pathname } = parsed;
|
|
1272
|
+
|
|
1273
|
+
// Rewrite the request-scoped wide event so logs / drains report the
|
|
1274
|
+
// *logical* path the user navigated to (e.g. "/board/123/card/456")
|
|
1275
|
+
// instead of the technical "/_furin/data" transport URL. We set this
|
|
1276
|
+
// before the route-match check so 404s also surface the attempted path
|
|
1277
|
+
// — otherwise monitoring just sees "GET /_furin/data 404" with no clue.
|
|
1278
|
+
const wideEventLog = useLogger();
|
|
1279
|
+
wideEventLog.set({ path: rawPath });
|
|
1280
|
+
|
|
1281
|
+
// Find the MOST SPECIFIC matching route. A first-match scan would let a
|
|
1282
|
+
// dynamic route (`/users/:id`) shadow a static sibling (`/users/new`)
|
|
1283
|
+
// whenever it is scanned first — and `[id]` sorts before `new`, so it
|
|
1284
|
+
// is. Score each match (static segment > :param > wildcard) and keep the
|
|
1285
|
+
// highest, mirroring the precedence Elysia's router applies on the SSR path.
|
|
1286
|
+
const matched = routes.reduce<{
|
|
1287
|
+
route: ResolvedRoute;
|
|
1288
|
+
params: Record<string, string>;
|
|
1289
|
+
score: number;
|
|
1290
|
+
} | null>((acc, route) => {
|
|
1291
|
+
const { regex, paramNames } = buildRouteRegex(route.pattern);
|
|
1292
|
+
const m = regex.exec(pathname);
|
|
1293
|
+
if (!m) {
|
|
1294
|
+
return acc;
|
|
1295
|
+
}
|
|
1296
|
+
const score = routeSpecificity(route.pattern);
|
|
1297
|
+
if (acc && acc.score >= score) {
|
|
1298
|
+
return acc;
|
|
1299
|
+
}
|
|
1300
|
+
const params: Record<string, string> = {};
|
|
1301
|
+
for (let i = 0; i < paramNames.length; i++) {
|
|
1302
|
+
const name = paramNames[i];
|
|
1303
|
+
if (name !== undefined) {
|
|
1304
|
+
params[name] = m[i + 1] ?? "";
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
return { route, params, score };
|
|
1308
|
+
}, null);
|
|
1309
|
+
|
|
1310
|
+
if (!matched) {
|
|
1311
|
+
return new Response("Route not found", { status: 404 });
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
// Now that we know the matched pattern, add it as a stable aggregation
|
|
1315
|
+
// key for drains (e.g. "p99 latency by route").
|
|
1316
|
+
wideEventLog.set({ routePattern: matched.route.pattern });
|
|
1317
|
+
|
|
1318
|
+
// Build a synthetic Elysia-compatible context for the matched route.
|
|
1319
|
+
// Loaders receive request, params, query, set, headers, and cookie.
|
|
1320
|
+
// Build the synthetic URL from the parsed `pathname + search` only —
|
|
1321
|
+
// never from `rawPath` directly — so an attacker cannot smuggle a
|
|
1322
|
+
// foreign origin into `syntheticRequest.url`.
|
|
1323
|
+
const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
|
|
1324
|
+
const syntheticSet = { headers: {} as Record<string, string>, status: 200 as number };
|
|
1325
|
+
const syntheticCtx = {
|
|
1326
|
+
request: syntheticRequest,
|
|
1327
|
+
params: matched.params,
|
|
1328
|
+
query: Object.fromEntries(url.searchParams),
|
|
1329
|
+
set: syntheticSet,
|
|
1330
|
+
headers: ctx.headers,
|
|
1331
|
+
cookie: ctx.cookie,
|
|
1332
|
+
path: pathname,
|
|
1333
|
+
// Loader-emitted redirects flow through `runLoaders` → `result.type
|
|
1334
|
+
// === "redirect"` and are converted to NDJSON below. The Response we
|
|
1335
|
+
// return here only has to be detectable by that pipeline.
|
|
1336
|
+
redirect: (location: string, status?: number) =>
|
|
1337
|
+
new Response(null, { status: status ?? 302, headers: { location } }),
|
|
1338
|
+
// Synthetic `status` helper: numeric codes only. Callers that reach
|
|
1339
|
+
// this endpoint never dispatch a string-keyed status; rejecting them
|
|
1340
|
+
// is safer than coercing via `Number(code)` and silently producing
|
|
1341
|
+
// `NaN`. Query-default redirects no longer flow through this helper —
|
|
1342
|
+
// they are detected via `detectQueryDefaultRedirect` below.
|
|
1343
|
+
status: (code: number) => new Response(null, { status: code }),
|
|
1344
|
+
} as unknown as Context;
|
|
1345
|
+
|
|
1346
|
+
// Normalize params and query through the same merged schemas used by
|
|
1347
|
+
// createRoutePlugin so loaders see identical typed/defaulted inputs.
|
|
1348
|
+
const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
|
|
1349
|
+
const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
|
|
1350
|
+
syntheticCtx.params = applySchemaDefaults(
|
|
1351
|
+
mergedParams as Record<string, unknown> | undefined,
|
|
1352
|
+
syntheticCtx.params as Record<string, unknown>
|
|
1353
|
+
) as Record<string, string>;
|
|
1354
|
+
syntheticCtx.query = applySchemaDefaults(
|
|
1355
|
+
mergedQuery as Record<string, unknown> | undefined,
|
|
1356
|
+
syntheticCtx.query as Record<string, unknown>
|
|
1357
|
+
) as Record<string, string>;
|
|
1358
|
+
|
|
1359
|
+
// Query-default redirect: detect via the pure helper so we can emit the
|
|
1360
|
+
// NDJSON `__furinRedirect` sentinel (the SPA client cannot parse a real
|
|
1361
|
+
// HTTP 302 — it never sees one because `parseDeferredNdjson` reads the
|
|
1362
|
+
// body, not the redirect chain).
|
|
1363
|
+
if (mergedQuery) {
|
|
1364
|
+
const redirectLocation = detectQueryDefaultRedirect(
|
|
1365
|
+
syntheticRequest,
|
|
1366
|
+
syntheticCtx.query as Record<string, unknown>
|
|
1367
|
+
);
|
|
1368
|
+
if (redirectLocation) {
|
|
1369
|
+
const serialized = await toCrossJSONAsync({ __furinRedirect: redirectLocation });
|
|
1370
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
1371
|
+
headers: { "content-type": "application/x-ndjson" },
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
const result = await runLoaders(matched.route, syntheticCtx);
|
|
1377
|
+
|
|
1378
|
+
if (result.type === "redirect") {
|
|
1379
|
+
// Encode the redirect target as a special field for the client to follow
|
|
1380
|
+
const redirectUrl = new URL(
|
|
1381
|
+
result.response.headers.get("location") ?? "/",
|
|
1382
|
+
ctx.request.url
|
|
1383
|
+
);
|
|
1384
|
+
const serialized = await toCrossJSONAsync({
|
|
1385
|
+
__furinRedirect: redirectUrl.pathname + redirectUrl.search,
|
|
1386
|
+
});
|
|
1387
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
1388
|
+
headers: { "content-type": "application/x-ndjson" },
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
if (result.type === "not-found") {
|
|
1393
|
+
const serialized = await toCrossJSONAsync({
|
|
1394
|
+
__furinStatus: 404,
|
|
1395
|
+
__furinNotFound: { message: result.error.message, data: result.error.data },
|
|
1396
|
+
});
|
|
1397
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
1398
|
+
status: 200,
|
|
1399
|
+
headers: { "content-type": "application/x-ndjson" },
|
|
1400
|
+
});
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
if (result.type === "error") {
|
|
1404
|
+
// Compute the digest server-side ONCE so:
|
|
1405
|
+
// 1. The HTTP response body carries it (client error UI displays the
|
|
1406
|
+
// same id the server logs).
|
|
1407
|
+
// 2. The server-log line below uses the SAME digest a user would see
|
|
1408
|
+
// on screen, enabling support correlation.
|
|
1409
|
+
// Recomputing client-side from a synthetic message + stack would yield
|
|
1410
|
+
// a different hash — see boundaries.tsx for the digest precedence.
|
|
1411
|
+
const digest = computeErrorDigest(result.error);
|
|
1412
|
+
const serialized = await toCrossJSONAsync({
|
|
1413
|
+
__furinError: {
|
|
1414
|
+
digest,
|
|
1415
|
+
message: result.message,
|
|
1416
|
+
status: result.status,
|
|
1417
|
+
},
|
|
1418
|
+
});
|
|
1419
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
1420
|
+
status: result.status,
|
|
1421
|
+
headers: { "content-type": "application/x-ndjson" },
|
|
1422
|
+
});
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
// Resolve the page title server-side: head() never runs in the browser,
|
|
1426
|
+
// so SPA navigation depends on the endpoint shipping it as __furinTitle.
|
|
1427
|
+
const syncDataWithTitle = withResolvedTitle(matched.route, result.syncData);
|
|
1428
|
+
|
|
1429
|
+
if (result.deferredPromises) {
|
|
1430
|
+
return new Response(
|
|
1431
|
+
createDeferredNdjsonStream(syncDataWithTitle, result.deferredPromises),
|
|
1432
|
+
{
|
|
1433
|
+
headers: {
|
|
1434
|
+
"content-type": "application/x-ndjson",
|
|
1435
|
+
...result.headers,
|
|
1436
|
+
},
|
|
1437
|
+
}
|
|
1438
|
+
);
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
// No deferred fields: emit the single-line payload used by the legacy path.
|
|
1442
|
+
const serialized = await toCrossJSONAsync(syncDataWithTitle);
|
|
1443
|
+
return new Response(`${JSON.stringify(serialized)}\n`, {
|
|
1444
|
+
headers: {
|
|
1445
|
+
"content-type": "application/x-ndjson",
|
|
1446
|
+
...result.headers,
|
|
1447
|
+
},
|
|
1448
|
+
});
|
|
1449
|
+
},
|
|
1450
|
+
{
|
|
1451
|
+
query: t.Object({ path: t.Optional(t.String()) }),
|
|
1452
|
+
}
|
|
1453
|
+
);
|
|
1454
|
+
|
|
1455
|
+
return plugin;
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
/**
|
|
1459
|
+
* Runs the matched page's `head()` against the resolved sync data and, when it
|
|
1460
|
+
* yields a title, returns a copy of `syncData` carrying the reserved
|
|
1461
|
+
* `__furinTitle` field. `head()` never executes in the browser, so this is the
|
|
1462
|
+
* only channel through which SPA navigation can learn the new document title.
|
|
1463
|
+
*
|
|
1464
|
+
* Deferred fields are absent from `syncData` (they are still Promises), so a
|
|
1465
|
+
* `head()` that reads one sees `undefined` — titles should be derived from
|
|
1466
|
+
* synchronous loader data. A throwing `head()` is swallowed: a missing title
|
|
1467
|
+
* must never break the data response.
|
|
1468
|
+
*/
|
|
1469
|
+
function withResolvedTitle(
|
|
1470
|
+
route: ResolvedRoute,
|
|
1471
|
+
syncData: Record<string, unknown>
|
|
1472
|
+
): Record<string, unknown> {
|
|
1473
|
+
const head = route.page.head;
|
|
1474
|
+
if (!head) {
|
|
1475
|
+
return syncData;
|
|
1476
|
+
}
|
|
1477
|
+
let title: string | undefined;
|
|
1478
|
+
try {
|
|
1479
|
+
title = extractTitle(head(syncData).meta);
|
|
1480
|
+
} catch {
|
|
1481
|
+
return syncData;
|
|
1482
|
+
}
|
|
1483
|
+
if (title === undefined) {
|
|
1484
|
+
return syncData;
|
|
1485
|
+
}
|
|
1486
|
+
return { ...syncData, __furinTitle: title };
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
function createDeferredNdjsonStream(
|
|
1490
|
+
syncData: Record<string, unknown>,
|
|
1491
|
+
deferredPromises: Record<string, Promise<unknown>>
|
|
1492
|
+
): ReadableStream<Uint8Array> {
|
|
1493
|
+
const enc = new TextEncoder();
|
|
1494
|
+
const entries = Object.entries(deferredPromises);
|
|
1495
|
+
|
|
1496
|
+
return new ReadableStream<Uint8Array>({
|
|
1497
|
+
async start(controller) {
|
|
1498
|
+
const initial = toCrossJSON({
|
|
1499
|
+
...syncData,
|
|
1500
|
+
__furinDeferredKeys: entries.map(([key]) => key),
|
|
1501
|
+
});
|
|
1502
|
+
controller.enqueue(enc.encode(`${JSON.stringify(initial)}\n`));
|
|
1503
|
+
|
|
1504
|
+
await Promise.all(
|
|
1505
|
+
entries.map(async ([key, promise]) => {
|
|
1506
|
+
try {
|
|
1507
|
+
const value = await promise;
|
|
1508
|
+
controller.enqueue(
|
|
1509
|
+
enc.encode(
|
|
1510
|
+
`${JSON.stringify({ key, action: "resolve", value: toCrossJSON(value) })}\n`
|
|
1511
|
+
)
|
|
1512
|
+
);
|
|
1513
|
+
} catch (err) {
|
|
1514
|
+
const normalized = await serializeDeferredRejection(err);
|
|
1515
|
+
const value = toCrossJSON(normalized);
|
|
1516
|
+
controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "reject", value })}\n`));
|
|
1517
|
+
}
|
|
1518
|
+
})
|
|
1519
|
+
);
|
|
1520
|
+
controller.close();
|
|
1521
|
+
},
|
|
1522
|
+
});
|
|
1523
|
+
}
|