@teyik0/furin 0.1.0-alpha.9 → 0.2.0-alpha.2
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/LICENSE +21 -0
- package/README.md +33 -0
- package/package.json +61 -25
- package/src/adapter/bun.ts +90 -41
- package/src/adapter/static.ts +100 -40
- package/src/build/client.ts +13 -14
- package/src/build/compile-entry.ts +20 -14
- package/src/build/entry-template.ts +90 -8
- package/src/build/hydrate.ts +219 -36
- package/src/build/index.ts +10 -9
- package/src/build/route-types.ts +65 -9
- package/src/build/scan-server.ts +52 -67
- package/src/build/server-routes-entry.ts +7 -11
- package/src/build/shared.ts +2 -1
- package/src/build/ssg-cache.ts +32 -0
- package/src/build/types.ts +5 -1
- package/src/cli/index.ts +1 -0
- package/src/client/boundaries.tsx +259 -0
- package/src/client/default-screens.tsx +304 -0
- package/src/client/link.tsx +347 -0
- package/src/client/router/boundary-tree.tsx +116 -0
- package/src/client/router/context.ts +40 -0
- package/src/client/router/history.ts +41 -0
- package/src/client/router/index.ts +56 -0
- package/src/client/router/link-utils.ts +177 -0
- package/src/client/router/navigation.ts +61 -0
- package/src/client/router/provider.tsx +759 -0
- package/src/client/router/search/index.ts +99 -0
- package/src/client/router/search-store.ts +86 -0
- package/src/client/router/spa-response.ts +143 -0
- package/src/client/router/types.ts +271 -0
- package/src/client/server-error.ts +47 -0
- package/src/client.ts +80 -3
- package/src/config.ts +11 -3
- package/src/env.d.ts +1 -0
- package/src/furin.ts +114 -29
- package/src/plugin/index.ts +7 -8
- package/src/plugin/transform-client.ts +146 -120
- package/src/server/auto-invalidate/index.ts +10 -0
- package/src/server/auto-invalidate/plugin.ts +25 -0
- package/src/server/auto-invalidate/registry.ts +60 -0
- package/src/server/auto-invalidate/runtime.ts +133 -0
- package/src/server/auto-invalidate/types.ts +16 -0
- package/src/server/cache/dev-loader.ts +211 -0
- package/src/server/cache/index.ts +34 -0
- package/src/server/cache/invalidation.ts +111 -0
- package/src/server/cache/isr-ssg.ts +41 -0
- package/src/server/cache/isr.ts +17 -0
- package/src/server/cache/registry.ts +35 -0
- package/src/server/cache/route-cache.ts +124 -0
- package/src/server/cache/ssg.ts +15 -0
- package/src/{context-logger.ts → server/context-logger.ts} +5 -0
- package/src/server/dev-inspector.ts +60 -0
- package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
- package/src/{internal.ts → server/internal.ts} +17 -0
- package/src/server/lang-detect.ts +46 -0
- package/src/server/render/assemble.ts +133 -0
- package/src/server/render/element.tsx +113 -0
- package/src/server/render/index.ts +22 -0
- package/src/server/render/isr.ts +317 -0
- package/src/server/render/loaders.ts +328 -0
- package/src/server/render/not-found.ts +98 -0
- package/src/{render → server/render}/shell.ts +28 -13
- package/src/server/render/ssg.ts +148 -0
- package/src/server/render/ssr.ts +583 -0
- package/src/server/router/discovery.ts +474 -0
- package/src/server/router/hmr.ts +376 -0
- package/src/server/router/index.ts +28 -0
- package/src/server/router/patterns.ts +219 -0
- package/src/server/router/plugin.ts +384 -0
- package/src/server/router/schemas.ts +278 -0
- package/src/server/router/types.ts +59 -0
- package/src/shared/await.tsx +192 -0
- package/src/shared/deferred-ndjson.ts +244 -0
- package/src/shared/digest.ts +71 -0
- package/src/shared/error.ts +49 -0
- package/src/shared/not-found.ts +40 -0
- package/src/shared/search-params.ts +182 -0
- package/src/shared/utils/ast-walk.ts +51 -0
- package/src/{utils.ts → shared/utils/index.ts} +32 -1
- package/dist/adapter/bun.d.ts +0 -3
- package/dist/adapter/static.d.ts +0 -3
- package/dist/build/client.d.ts +0 -25
- package/dist/build/compile-entry.d.ts +0 -23
- package/dist/build/entry-template.d.ts +0 -14
- package/dist/build/hydrate.d.ts +0 -24
- package/dist/build/index.d.ts +0 -7
- package/dist/build/index.js +0 -3727
- package/dist/build/route-types.d.ts +0 -21
- package/dist/build/scan-server.d.ts +0 -8
- package/dist/build/server-routes-entry.d.ts +0 -23
- package/dist/build/shared.d.ts +0 -11
- package/dist/build/types.d.ts +0 -76
- package/dist/cli/config.d.ts +0 -9
- package/dist/cli/index.d.ts +0 -2
- package/dist/cli/index.js +0 -3762
- package/dist/client.d.ts +0 -195
- package/dist/client.js +0 -20
- package/dist/config.d.ts +0 -47
- package/dist/config.js +0 -28
- package/dist/context-logger.d.ts +0 -26
- package/dist/dev-page-plugin.d.ts +0 -109
- package/dist/furin.d.ts +0 -34
- package/dist/furin.js +0 -2744
- package/dist/internal.d.ts +0 -19
- package/dist/link.d.ts +0 -245
- package/dist/link.js +0 -1232
- package/dist/plugin/index.d.ts +0 -20
- package/dist/plugin/index.js +0 -1408
- package/dist/plugin/transform-client.d.ts +0 -9
- package/dist/render/assemble.d.ts +0 -15
- package/dist/render/cache.d.ts +0 -95
- package/dist/render/element.d.ts +0 -4
- package/dist/render/index.d.ts +0 -27
- package/dist/render/loaders.d.ts +0 -12
- package/dist/render/shell.d.ts +0 -29
- package/dist/render/template.d.ts +0 -6
- package/dist/router.d.ts +0 -45
- package/dist/router.js +0 -1671
- package/dist/runtime-env.d.ts +0 -3
- package/dist/utils.d.ts +0 -6
- package/src/link.tsx +0 -1120
- package/src/render/assemble.ts +0 -66
- package/src/render/cache.ts +0 -241
- package/src/render/element.tsx +0 -28
- package/src/render/index.ts +0 -483
- package/src/render/loaders.ts +0 -117
- package/src/router.ts +0 -439
- /package/src/{render → server/render}/template.ts +0 -0
- /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import type { Context } from "elysia";
|
|
3
|
+
import type { RuntimePage, RuntimeRoute } from "../../client.ts";
|
|
4
|
+
import type { SearchRouteMetadata } from "../../shared/search-params.ts";
|
|
5
|
+
import { collectRouteChainFromRoute, isFurinPage, isFurinRoute } from "../../shared/utils/index.ts";
|
|
6
|
+
import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
|
|
7
|
+
import {
|
|
8
|
+
type DevLoaderCacheEntry,
|
|
9
|
+
getDevISRLoaderCache,
|
|
10
|
+
getDevSSGLoaderCache,
|
|
11
|
+
isDevLoaderCacheValid,
|
|
12
|
+
setDevISRLoaderCache,
|
|
13
|
+
setDevSSGLoaderCache,
|
|
14
|
+
} from "../cache/dev-loader.ts";
|
|
15
|
+
import { type CompileContext, getCompileContext } from "../internal.ts";
|
|
16
|
+
import { resolvePath } from "../render/assemble.ts";
|
|
17
|
+
import { type LoaderResult, renderSSR, runLoaders } from "../render/index.ts";
|
|
18
|
+
import { collectRouteTags, getSourceModuleCandidates, isModuleNotFoundError } from "./discovery.ts";
|
|
19
|
+
import { collectIntermediateLayoutDirs, resolveMode } from "./patterns.ts";
|
|
20
|
+
import type { ResolvedRoute, RootLayout } from "./types.ts";
|
|
21
|
+
|
|
22
|
+
type RouteModuleImport = (specifier: string) => Promise<Record<string, unknown>>;
|
|
23
|
+
|
|
24
|
+
function isResolvedRouteModuleCandidate(
|
|
25
|
+
layoutPath: string,
|
|
26
|
+
imported: Record<string, unknown>,
|
|
27
|
+
ctx: CompileContext | null
|
|
28
|
+
): boolean {
|
|
29
|
+
if (existsSync(layoutPath) || ctx?.modules[layoutPath]) {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return Object.keys(imported).length > 0;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function importFreshRouteModuleCandidate(
|
|
37
|
+
layoutPath: string,
|
|
38
|
+
timestamp: number,
|
|
39
|
+
resolveImport: RouteModuleImport,
|
|
40
|
+
ctx: CompileContext | null
|
|
41
|
+
): Promise<Record<string, unknown> | undefined> {
|
|
42
|
+
try {
|
|
43
|
+
const imported = await resolveImport(`${layoutPath}?furin-server&t=${timestamp}`);
|
|
44
|
+
if (!isResolvedRouteModuleCandidate(layoutPath, imported, ctx)) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return imported;
|
|
49
|
+
} catch (err) {
|
|
50
|
+
// Distinguish "this layout file does not exist" (legitimate skip) from
|
|
51
|
+
// "this layout file's transitive imports failed" (real bug to surface).
|
|
52
|
+
// If the layoutPath itself is on disk or registered in the compile ctx,
|
|
53
|
+
// a ModuleNotFoundError must come from a sub-import — re-throw it so
|
|
54
|
+
// the developer sees the actual broken import instead of a silently
|
|
55
|
+
// ignored layout chain.
|
|
56
|
+
const layoutFileIsKnown = existsSync(layoutPath) || Boolean(ctx?.modules[layoutPath]);
|
|
57
|
+
if (!layoutFileIsKnown && isModuleNotFoundError(err)) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function importFreshLayoutRouteModule(
|
|
65
|
+
layoutDir: string,
|
|
66
|
+
timestamp: number,
|
|
67
|
+
resolveImport: RouteModuleImport,
|
|
68
|
+
ctx: CompileContext | null
|
|
69
|
+
): Promise<Record<string, unknown> | undefined> {
|
|
70
|
+
for (const layoutPath of getSourceModuleCandidates(layoutDir, "_route")) {
|
|
71
|
+
const freshMod = await importFreshRouteModuleCandidate(
|
|
72
|
+
layoutPath,
|
|
73
|
+
timestamp,
|
|
74
|
+
resolveImport,
|
|
75
|
+
ctx
|
|
76
|
+
);
|
|
77
|
+
if (freshMod) {
|
|
78
|
+
return freshMod;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function patchRouteEntryFromFreshModule(
|
|
86
|
+
entry: RuntimeRoute | undefined,
|
|
87
|
+
freshMod: Record<string, unknown>
|
|
88
|
+
): void {
|
|
89
|
+
const freshRoute = freshMod.route ?? freshMod.default;
|
|
90
|
+
if (!(entry && freshRoute && isFurinRoute(freshRoute))) {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
entry.layout = freshRoute.layout;
|
|
95
|
+
entry.loader = freshRoute.loader;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Re-imports intermediate layout _route.tsx files with cache-busting so that
|
|
100
|
+
* server-side renders reflect the latest code after an HMR edit. Bun's ESM
|
|
101
|
+
* cache keeps the original module alive, so we import via ?furin-server and
|
|
102
|
+
* patch the layout/loader references on the existing route-chain objects.
|
|
103
|
+
*
|
|
104
|
+
* The optional `importFn` parameter exists only for unit testing. In production
|
|
105
|
+
* it defaults to the real `import()`.
|
|
106
|
+
*/
|
|
107
|
+
export async function refreshLayoutChain(
|
|
108
|
+
chain: RuntimeRoute[],
|
|
109
|
+
pagePath: string,
|
|
110
|
+
rootPath: string,
|
|
111
|
+
importFn: ((specifier: string) => Promise<Record<string, unknown>>) | undefined
|
|
112
|
+
): Promise<void> {
|
|
113
|
+
const resolveImport: RouteModuleImport =
|
|
114
|
+
importFn ?? ((s: string) => import(s) as Promise<Record<string, unknown>>);
|
|
115
|
+
const ctx = getCompileContext();
|
|
116
|
+
const timestamp = Date.now();
|
|
117
|
+
const layoutDirs = collectIntermediateLayoutDirs(pagePath, rootPath);
|
|
118
|
+
|
|
119
|
+
// Track chainIdx independently rather than deriving it from layoutPaths
|
|
120
|
+
// index. Directories without a _route module produce import errors that are
|
|
121
|
+
// silently skipped, but those directories have no corresponding chain entry —
|
|
122
|
+
// so we must only advance chainIdx for directories whose _route module actually
|
|
123
|
+
// exists. A positional assumption (i = chainIdx - 1) drifts whenever
|
|
124
|
+
// isModuleNotFoundError is swallowed for a gap directory.
|
|
125
|
+
//
|
|
126
|
+
// Imports are parallelised for speed; patching stays sequential so the
|
|
127
|
+
// chainIdx-to-layoutDir positional mapping remains deterministic.
|
|
128
|
+
const freshMods = await Promise.all(
|
|
129
|
+
layoutDirs.map((layoutDir) =>
|
|
130
|
+
importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx)
|
|
131
|
+
)
|
|
132
|
+
);
|
|
133
|
+
let chainIdx = 1; // chain[0] is the root
|
|
134
|
+
for (const freshMod of freshMods) {
|
|
135
|
+
if (chainIdx >= chain.length) {
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
if (!freshMod) {
|
|
139
|
+
// No _route module in this directory — no chain entry to match, so
|
|
140
|
+
// do NOT advance chainIdx. The next deeper layoutDir may correspond
|
|
141
|
+
// to the current chainIdx.
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
patchRouteEntryFromFreshModule(chain[chainIdx], freshMod);
|
|
146
|
+
// An _route module exists at this depth — advance chainIdx regardless of
|
|
147
|
+
// whether the export is currently a valid route (the chain entry was
|
|
148
|
+
// populated by the initial import and should be revisited on the next
|
|
149
|
+
// successful HMR cycle).
|
|
150
|
+
chainIdx++;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Rebuilds a `ResolvedRoute` from freshly-imported `page` and `chain` so that
|
|
156
|
+
* `mode` reflects the CURRENT contents of the page module — not the value
|
|
157
|
+
* captured at scan time.
|
|
158
|
+
*
|
|
159
|
+
* In dev, `handleDevRequest` re-imports the page on every request to pick up
|
|
160
|
+
* source edits via the `?furin-server&t=<ts>` cache-buster. Without this
|
|
161
|
+
* function the spread `{ ...route, page, chain }` would carry over the stale
|
|
162
|
+
* `route.mode` resolved at startup, so toggling `revalidate` or removing a
|
|
163
|
+
* loader in source would not retake effect until a server restart.
|
|
164
|
+
*
|
|
165
|
+
* Only `mode` is recomputed: it is the only field DERIVED from page+chain.
|
|
166
|
+
* Structural fields (`pattern`, `path`, `segmentBoundaries`, `error`,
|
|
167
|
+
* `notFound`) are scan-time invariants in dev and are preserved as-is.
|
|
168
|
+
*/
|
|
169
|
+
export function rebuildDevRoute(
|
|
170
|
+
base: ResolvedRoute,
|
|
171
|
+
page: RuntimePage,
|
|
172
|
+
chain: RuntimeRoute[]
|
|
173
|
+
): ResolvedRoute {
|
|
174
|
+
return {
|
|
175
|
+
...base,
|
|
176
|
+
page,
|
|
177
|
+
routeChain: chain,
|
|
178
|
+
mode: resolveMode(page, chain),
|
|
179
|
+
tags: collectRouteTags(chain, page),
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** @internal Handles a request in dev mode — re-imports the page fresh on every request. */
|
|
184
|
+
export async function handleDevRequest(
|
|
185
|
+
route: ResolvedRoute,
|
|
186
|
+
ctx: Context,
|
|
187
|
+
root: RootLayout,
|
|
188
|
+
searchRoutes?: SearchRouteMetadata[]
|
|
189
|
+
): Promise<unknown> {
|
|
190
|
+
// Load the page via ?furin-server virtual namespace so it stays out of
|
|
191
|
+
// --hot's file watcher, then hand off to renderSSR which runs loaders,
|
|
192
|
+
// renders React to HTML, and injects __FURIN_DATA__.
|
|
193
|
+
try {
|
|
194
|
+
let currentRoot = root;
|
|
195
|
+
const rootMod = (await import(`${root.path}?furin-server&t=${Date.now()}`)) as Record<
|
|
196
|
+
string,
|
|
197
|
+
unknown
|
|
198
|
+
>;
|
|
199
|
+
const rootExport = rootMod.route ?? rootMod.default;
|
|
200
|
+
if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
|
|
201
|
+
// Preserve the RootLayout-level convention fields (error, notFound,
|
|
202
|
+
// errorPath, notFoundPath) populated by `scanRootLayout` from
|
|
203
|
+
// `pages/error.tsx` and `pages/not-found.tsx`. Replacing the whole
|
|
204
|
+
// RootLayout with just `{ path, route }` would silently drop these
|
|
205
|
+
// fallbacks — `route.error ?? root.error` would resolve to `undefined`
|
|
206
|
+
// in dev after the first request, making custom 404/500 screens
|
|
207
|
+
// disappear after a HMR refresh.
|
|
208
|
+
currentRoot = { ...currentRoot, route: rootExport };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
|
|
212
|
+
const page = pageMod.default;
|
|
213
|
+
if (page && isFurinPage(page)) {
|
|
214
|
+
const chain = collectRouteChainFromRoute(page._route as RuntimeRoute);
|
|
215
|
+
await refreshLayoutChain(chain, route.path, root.path, undefined);
|
|
216
|
+
|
|
217
|
+
// Patch chain[0] (the root) with the freshly-imported root's loader
|
|
218
|
+
// and layout. `refreshLayoutChain` deliberately starts at chainIdx=1
|
|
219
|
+
// because the root is already loaded separately above; without this
|
|
220
|
+
// patch, chain[0] points to whatever object `_route.parent` captured
|
|
221
|
+
// at _route's first evaluation — a STALE reference if Bun --hot
|
|
222
|
+
// re-evaluated root.tsx without propagating the re-evaluation to
|
|
223
|
+
// _route.tsx (the standard ESM behaviour). Mirroring the pattern
|
|
224
|
+
// used by patchRouteEntryFromFreshModule.
|
|
225
|
+
if (chain[0] && currentRoot.route) {
|
|
226
|
+
chain[0].layout = currentRoot.route.layout;
|
|
227
|
+
chain[0].loader = currentRoot.route.loader;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const refreshedRoute = rebuildDevRoute(route, page, chain);
|
|
231
|
+
|
|
232
|
+
// Live ISR — the loader chain is short-circuited by the dev cache when
|
|
233
|
+
// a fresh entry exists. HTML re-assembles every time so the dev shell
|
|
234
|
+
// chunk URL is always current.
|
|
235
|
+
if (refreshedRoute.mode === "isr") {
|
|
236
|
+
return renderDevISRWithLoaderCache(refreshedRoute, ctx, currentRoot, searchRoutes);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Live SSG — same trick as Live ISR, but the cache entry is forever-fresh
|
|
240
|
+
// (revalidate: Infinity) so the loader runs ONCE per cache key until a
|
|
241
|
+
// source file in its dependency chain changes. This matches production
|
|
242
|
+
// SSG semantics ("loader runs once") in dev, instead of re-running the
|
|
243
|
+
// loader on every refresh — which would make expensive loaders (DB
|
|
244
|
+
// queries, MDX parsing, sitemap reads) painful in dev.
|
|
245
|
+
if (refreshedRoute.mode === "ssg") {
|
|
246
|
+
return renderDevSSGWithLoaderCache(refreshedRoute, ctx, currentRoot, searchRoutes);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return renderSSR(refreshedRoute, ctx, currentRoot, undefined, searchRoutes);
|
|
250
|
+
}
|
|
251
|
+
} catch (err) {
|
|
252
|
+
console.error(`[furin] Dev page load error for ${route.path}:`, err);
|
|
253
|
+
}
|
|
254
|
+
// Fallback: page couldn't load — return a clear error response rather than
|
|
255
|
+
// delegating to renderSSR with an undefined page.
|
|
256
|
+
return new Response(
|
|
257
|
+
`<!doctype html><html><body><h1>Page load error</h1><p>Could not load ${route.path}. Check the server console for details.</p></body></html>`,
|
|
258
|
+
{ status: 500, headers: { "Content-Type": "text/html; charset=utf-8" } }
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* @internal Dev "Live ISR" — caches loader output, not assembled HTML. On a
|
|
264
|
+
* fresh cache hit the loader chain is skipped; the React render still runs so
|
|
265
|
+
* the response embeds the latest dev shell (chunk URL, HMR runtime, …). On
|
|
266
|
+
* miss, runs loaders normally and stores the merged data record.
|
|
267
|
+
*/
|
|
268
|
+
export async function renderDevISRWithLoaderCache(
|
|
269
|
+
route: ResolvedRoute,
|
|
270
|
+
ctx: Context,
|
|
271
|
+
root: RootLayout,
|
|
272
|
+
searchRoutes?: SearchRouteMetadata[]
|
|
273
|
+
): Promise<Response> {
|
|
274
|
+
const cacheKey = `${root.path}:${resolvePath(route.pattern, ctx.params ?? {})}`;
|
|
275
|
+
const cached = getDevISRLoaderCache(cacheKey);
|
|
276
|
+
|
|
277
|
+
if (cached && isDevLoaderCacheValid(cached)) {
|
|
278
|
+
const precomputed: LoaderResult = {
|
|
279
|
+
type: "data",
|
|
280
|
+
syncData: cached.loaderData,
|
|
281
|
+
deferredPromises: undefined,
|
|
282
|
+
headers: cached.headers,
|
|
283
|
+
};
|
|
284
|
+
return renderSSR(route, ctx, root, precomputed, searchRoutes);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const result = await runLoaders(route, ctx);
|
|
288
|
+
if (result.type === "data") {
|
|
289
|
+
const revalidate = route.page._route.revalidate ?? 60;
|
|
290
|
+
const entry: DevLoaderCacheEntry = {
|
|
291
|
+
dependencies: computeRouteDependencies(route.path, root.path),
|
|
292
|
+
generatedAt: Date.now(),
|
|
293
|
+
headers: result.headers,
|
|
294
|
+
loaderData: result.syncData,
|
|
295
|
+
mode: "isr",
|
|
296
|
+
revalidate,
|
|
297
|
+
};
|
|
298
|
+
setDevISRLoaderCache(cacheKey, entry);
|
|
299
|
+
autoInvalidateRegistry.registerLoaderTags(
|
|
300
|
+
resolvePath(route.pattern, ctx.params ?? {}),
|
|
301
|
+
route.tags
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
return renderSSR(route, ctx, root, result, searchRoutes);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* @internal Dev "Live SSG" — same shape as `renderDevISRWithLoaderCache`, but
|
|
309
|
+
* the cached entry is tagged forever-fresh (`revalidate: Infinity`) so it
|
|
310
|
+
* survives indefinitely until source-aware invalidation drops it. This makes
|
|
311
|
+
* dev SSG behave like production SSG: the loader runs ONCE per cache key,
|
|
312
|
+
* not on every refresh.
|
|
313
|
+
*/
|
|
314
|
+
export async function renderDevSSGWithLoaderCache(
|
|
315
|
+
route: ResolvedRoute,
|
|
316
|
+
ctx: Context,
|
|
317
|
+
root: RootLayout,
|
|
318
|
+
searchRoutes?: SearchRouteMetadata[]
|
|
319
|
+
): Promise<Response> {
|
|
320
|
+
const cacheKey = `${root.path}:${resolvePath(route.pattern, ctx.params ?? {})}`;
|
|
321
|
+
const cached = getDevSSGLoaderCache(cacheKey);
|
|
322
|
+
|
|
323
|
+
if (cached && isDevLoaderCacheValid(cached)) {
|
|
324
|
+
const precomputed: LoaderResult = {
|
|
325
|
+
type: "data",
|
|
326
|
+
syncData: cached.loaderData,
|
|
327
|
+
deferredPromises: undefined,
|
|
328
|
+
headers: cached.headers,
|
|
329
|
+
};
|
|
330
|
+
return renderSSR(route, ctx, root, precomputed, searchRoutes);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const result = await runLoaders(route, ctx);
|
|
334
|
+
if (result.type === "data") {
|
|
335
|
+
const entry: DevLoaderCacheEntry = {
|
|
336
|
+
dependencies: computeRouteDependencies(route.path, root.path),
|
|
337
|
+
generatedAt: Date.now(),
|
|
338
|
+
headers: result.headers,
|
|
339
|
+
loaderData: result.syncData,
|
|
340
|
+
mode: "ssg",
|
|
341
|
+
// SSG entries are forever-fresh — only source-aware invalidation drops them.
|
|
342
|
+
revalidate: Number.POSITIVE_INFINITY,
|
|
343
|
+
};
|
|
344
|
+
setDevSSGLoaderCache(cacheKey, entry);
|
|
345
|
+
autoInvalidateRegistry.registerLoaderTags(
|
|
346
|
+
resolvePath(route.pattern, ctx.params ?? {}),
|
|
347
|
+
route.tags
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
return renderSSR(route, ctx, root, result, searchRoutes);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* @internal Lists every source file whose contents can affect the render
|
|
355
|
+
* output for a given page: the page itself, every intermediate `_route.*`
|
|
356
|
+
* between the page and the pages root, and `root.tsx`.
|
|
357
|
+
*
|
|
358
|
+
* Only paths that EXIST on disk are returned. `isDevLoaderCacheValid` treats
|
|
359
|
+
* a `statSync` throw as "invalid" (conservative on missing files), so listing
|
|
360
|
+
* non-authored extension candidates here would force a permanent cache MISS
|
|
361
|
+
* for every nested route — silently disabling the dev ISR/SSG cache for any
|
|
362
|
+
* page in a subdirectory. Renames and deletions of TRACKED deps are still
|
|
363
|
+
* detected: the path that previously existed will then `statSync`-throw on
|
|
364
|
+
* the next read and yield the same conservative miss.
|
|
365
|
+
*/
|
|
366
|
+
export function computeRouteDependencies(pagePath: string, rootPath: string): string[] {
|
|
367
|
+
const deps = [pagePath, rootPath];
|
|
368
|
+
for (const dir of collectIntermediateLayoutDirs(pagePath, rootPath)) {
|
|
369
|
+
for (const candidate of getSourceModuleCandidates(dir, "_route")) {
|
|
370
|
+
if (existsSync(candidate)) {
|
|
371
|
+
deps.push(candidate);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return deps;
|
|
376
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
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
|
+
createSearchRouteMetadata,
|
|
25
|
+
mergeRouteSchemas,
|
|
26
|
+
parseDataEndpointPath,
|
|
27
|
+
} from "./schemas.ts";
|
|
28
|
+
export type { ResolvedRoute, RootLayout, SegmentBoundary } from "./types.ts";
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { parse } from "node:path";
|
|
2
|
+
import type { RuntimePage, RuntimeRoute } from "../../client.ts";
|
|
3
|
+
|
|
4
|
+
export function collectIntermediateLayoutDirs(pagePath: string, rootPath: string): string[] {
|
|
5
|
+
const pageDir = pagePath.slice(0, pagePath.lastIndexOf("/"));
|
|
6
|
+
const pagesDir = rootPath.slice(0, rootPath.lastIndexOf("/"));
|
|
7
|
+
const layoutDirs: string[] = [];
|
|
8
|
+
let dir = pageDir;
|
|
9
|
+
|
|
10
|
+
while (dir.length > pagesDir.length) {
|
|
11
|
+
layoutDirs.unshift(dir);
|
|
12
|
+
dir = dir.slice(0, dir.lastIndexOf("/"));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
return layoutDirs;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function resolveMode(page: RuntimePage, routeChain: RuntimeRoute[]): "ssr" | "ssg" | "isr" {
|
|
19
|
+
const routeConfig = page._route;
|
|
20
|
+
const mode = routeConfig.mode ?? (page as { mode?: string }).mode;
|
|
21
|
+
const revalidate = routeConfig.revalidate ?? (page as { revalidate?: number }).revalidate;
|
|
22
|
+
|
|
23
|
+
if (mode) {
|
|
24
|
+
return mode as "ssr" | "ssg" | "isr";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
|
|
28
|
+
const hasQuery = routeChain.some((r) => r.query);
|
|
29
|
+
|
|
30
|
+
if (hasQuery) {
|
|
31
|
+
return "ssr";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (!hasLoader) {
|
|
35
|
+
return "ssg";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (typeof revalidate === "number" && revalidate >= 0) {
|
|
39
|
+
return "isr";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return "ssr";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function filePathToPattern(path: string): string {
|
|
46
|
+
const parts = path.replaceAll("\\", "/").split("/");
|
|
47
|
+
const segments: string[] = [];
|
|
48
|
+
const lastIndex = parts.length - 1;
|
|
49
|
+
|
|
50
|
+
for (let idx = 0; idx < parts.length; idx++) {
|
|
51
|
+
const part = parts[idx];
|
|
52
|
+
if (part === undefined || part.length === 0) {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Only the leaf (file) segment carries an extension to strip. Directory
|
|
57
|
+
// segments are kept verbatim so valid folder names with dots — e.g.
|
|
58
|
+
// `v1.0` — are not truncated into `v1` by `parse().ext` handling.
|
|
59
|
+
const isFile = idx === lastIndex;
|
|
60
|
+
const name = isFile ? parse(part).name : part;
|
|
61
|
+
|
|
62
|
+
// `index` collapses to its parent ONLY as a leaf filename. A directory
|
|
63
|
+
// literally named `index` is a real route segment and must be preserved.
|
|
64
|
+
if (isFile && name === "index") {
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (name.startsWith("[") && name.endsWith("]")) {
|
|
69
|
+
const inner = name.slice(1, -1);
|
|
70
|
+
|
|
71
|
+
if (inner.startsWith("...")) {
|
|
72
|
+
segments.push("*");
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
segments.push(`:${inner}`);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
segments.push(name);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return `/${segments.join("/")}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/;
|
|
87
|
+
|
|
88
|
+
export function escapeRegExpChar(ch: string): string {
|
|
89
|
+
return REGEX_META_CHARS_RE.test(ch) ? `\\${ch}` : ch;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Ranks a single route segment by how tightly it constrains a URL position:
|
|
94
|
+
* a literal segment outranks a `:param`, which outranks a `*` wildcard.
|
|
95
|
+
*/
|
|
96
|
+
function segmentSpecificity(segment: string): number {
|
|
97
|
+
if (segment === "*") {
|
|
98
|
+
return 1;
|
|
99
|
+
}
|
|
100
|
+
if (segment.startsWith(":")) {
|
|
101
|
+
return 2;
|
|
102
|
+
}
|
|
103
|
+
return 3;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Compares two route patterns by specificity so the `/_furin/data` matcher can
|
|
108
|
+
* prefer the more specific of two siblings that both match a pathname.
|
|
109
|
+
*
|
|
110
|
+
* Patterns are compared segment by segment from the left; the first position
|
|
111
|
+
* where they differ decides (literal > `:param` > `*`). When every shared
|
|
112
|
+
* position ties, the pattern with more explicit segments wins over a shorter
|
|
113
|
+
* one whose wildcard absorbs the tail.
|
|
114
|
+
*
|
|
115
|
+
* Returns a positive number when `a` is MORE specific than `b`, negative when
|
|
116
|
+
* less, and `0` only when the two are indistinguishable. This lexicographic
|
|
117
|
+
* ranking replaces the previous summed-weight score, which produced ties such
|
|
118
|
+
* as `/blog/new/:section` vs `/blog/:id/edit` (both summed to 8) that resolved
|
|
119
|
+
* non-deterministically by scan order.
|
|
120
|
+
*/
|
|
121
|
+
export function compareRouteSpecificity(a: string, b: string): number {
|
|
122
|
+
const aSegments = a.split("/").filter((segment) => segment.length > 0);
|
|
123
|
+
const bSegments = b.split("/").filter((segment) => segment.length > 0);
|
|
124
|
+
const length = Math.max(aSegments.length, bSegments.length);
|
|
125
|
+
for (let i = 0; i < length; i++) {
|
|
126
|
+
const aSegment = aSegments[i];
|
|
127
|
+
const bSegment = bSegments[i];
|
|
128
|
+
// The pattern that still has a segment here constrains one more position.
|
|
129
|
+
if (aSegment === undefined) {
|
|
130
|
+
return -1;
|
|
131
|
+
}
|
|
132
|
+
if (bSegment === undefined) {
|
|
133
|
+
return 1;
|
|
134
|
+
}
|
|
135
|
+
const diff = segmentSpecificity(aSegment) - segmentSpecificity(bSegment);
|
|
136
|
+
if (diff !== 0) {
|
|
137
|
+
return diff;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Builds a regex from a route pattern, extracts named capture groups for
|
|
145
|
+
* each `:param` segment, and returns `{ regex, paramNames }`.
|
|
146
|
+
*
|
|
147
|
+
* Literal characters (e.g. dots in filenames like `v1.0`) are escaped so
|
|
148
|
+
* they are matched exactly rather than interpreted as regex syntax.
|
|
149
|
+
*/
|
|
150
|
+
export function buildRouteRegex(pattern: string): { regex: RegExp; paramNames: string[] } {
|
|
151
|
+
const paramNames: string[] = [];
|
|
152
|
+
let source = "";
|
|
153
|
+
let i = 0;
|
|
154
|
+
while (i < pattern.length) {
|
|
155
|
+
if (pattern[i] === ":") {
|
|
156
|
+
const start = ++i;
|
|
157
|
+
while (i < pattern.length && pattern[i] !== "/") {
|
|
158
|
+
i++;
|
|
159
|
+
}
|
|
160
|
+
paramNames.push(pattern.slice(start, i));
|
|
161
|
+
source += "([^/]+)";
|
|
162
|
+
} else if (pattern[i] === "*") {
|
|
163
|
+
paramNames.push("*");
|
|
164
|
+
source += "(.*)";
|
|
165
|
+
i++;
|
|
166
|
+
} else {
|
|
167
|
+
const ch = pattern[i];
|
|
168
|
+
if (ch !== undefined) {
|
|
169
|
+
source += escapeRegExpChar(ch);
|
|
170
|
+
}
|
|
171
|
+
i++;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { regex: new RegExp(`^${source}$`), paramNames };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface RoutePatternLike {
|
|
178
|
+
pattern: string;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export interface RouteMatch<TRoute extends RoutePatternLike> {
|
|
182
|
+
params: Record<string, string>;
|
|
183
|
+
route: TRoute;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
interface CompiledRoutePattern<TRoute extends RoutePatternLike> {
|
|
187
|
+
paramNames: string[];
|
|
188
|
+
regex: RegExp;
|
|
189
|
+
route: TRoute;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function buildRouteMatcher<TRoute extends RoutePatternLike>(
|
|
193
|
+
routes: TRoute[]
|
|
194
|
+
): (pathname: string) => RouteMatch<TRoute> | null {
|
|
195
|
+
const compiled = routes
|
|
196
|
+
.map((route): CompiledRoutePattern<TRoute> => {
|
|
197
|
+
const { regex, paramNames } = buildRouteRegex(route.pattern);
|
|
198
|
+
return { paramNames, regex, route };
|
|
199
|
+
})
|
|
200
|
+
.sort((a, b) => compareRouteSpecificity(b.route.pattern, a.route.pattern));
|
|
201
|
+
|
|
202
|
+
return (pathname) => {
|
|
203
|
+
for (const candidate of compiled) {
|
|
204
|
+
const match = candidate.regex.exec(pathname);
|
|
205
|
+
if (!match) {
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const params: Record<string, string> = {};
|
|
209
|
+
for (let i = 0; i < candidate.paramNames.length; i++) {
|
|
210
|
+
const name = candidate.paramNames[i];
|
|
211
|
+
if (name !== undefined) {
|
|
212
|
+
params[name] = match[i + 1] ?? "";
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return { route: candidate.route, params };
|
|
216
|
+
}
|
|
217
|
+
return null;
|
|
218
|
+
};
|
|
219
|
+
}
|