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

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 (98) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/adapter/bun.d.ts +17 -1
  4. package/dist/adapter/package.d.ts +26 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +3 -3
  7. package/dist/build/compile-entry.ts +114 -109
  8. package/dist/build/entry-template.d.ts +35 -9
  9. package/dist/build/entry-template.ts +206 -156
  10. package/dist/build/hydrate.d.ts +1 -1
  11. package/dist/build/index.js +643 -247
  12. package/dist/build/scan-server.d.ts +10 -4
  13. package/dist/build/server-routes-entry.d.ts +3 -3
  14. package/dist/build/server-routes-entry.ts +30 -36
  15. package/dist/build/ssg-cache.d.ts +1 -1
  16. package/dist/build/types.d.ts +36 -1
  17. package/dist/cli/config.d.ts +6 -1
  18. package/dist/cli/index.js +662 -260
  19. package/dist/client/link.js +163 -16
  20. package/dist/client/router/abort.d.ts +1 -0
  21. package/dist/client/router/sync-catch-up.d.ts +29 -0
  22. package/dist/config.d.ts +11 -2
  23. package/dist/config.js +5 -1
  24. package/dist/furin.d.ts +37 -19
  25. package/dist/furin.js +982 -378
  26. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  27. package/dist/server/cache/dev-loader.d.ts +3 -2
  28. package/dist/server/cache/invalidation.d.ts +19 -0
  29. package/dist/server/cache/isr.d.ts +6 -2
  30. package/dist/server/cache/registry.d.ts +3 -3
  31. package/dist/server/cache/ssg.d.ts +6 -2
  32. package/dist/server/cache/store-view.d.ts +11 -0
  33. package/dist/server/instance.d.ts +86 -0
  34. package/dist/server/internal.d.ts +16 -1
  35. package/dist/server/internal.js +72 -5
  36. package/dist/server/render/template.d.ts +3 -2
  37. package/dist/server/sync/adapter.d.ts +62 -0
  38. package/dist/server/sync/config.d.ts +11 -0
  39. package/dist/server/sync/fingerprint.d.ts +6 -0
  40. package/dist/server/sync/index.d.ts +2 -2
  41. package/dist/server/sync/memory-adapter.d.ts +17 -0
  42. package/dist/server/sync/plugin.d.ts +12 -195
  43. package/dist/server/sync/response.d.ts +4 -0
  44. package/dist/server/sync/stream.d.ts +24 -5
  45. package/dist/shared/prefix.d.ts +15 -0
  46. package/package.json +6 -1
  47. package/src/adapter/README.md +13 -13
  48. package/src/adapter/bun.ts +113 -50
  49. package/src/adapter/package.ts +206 -0
  50. package/src/build/client.ts +158 -152
  51. package/src/build/compile-entry.ts +114 -109
  52. package/src/build/entry-template.ts +206 -156
  53. package/src/build/hydrate.ts +342 -340
  54. package/src/build/index.ts +223 -152
  55. package/src/build/route-types.ts +145 -145
  56. package/src/build/scan-server.ts +111 -95
  57. package/src/build/server-routes-entry.ts +30 -36
  58. package/src/build/shared.ts +80 -80
  59. package/src/build/ssg-cache.ts +36 -32
  60. package/src/build/types.ts +125 -89
  61. package/src/cli/config.ts +9 -3
  62. package/src/cli/index.ts +21 -3
  63. package/src/client/router/abort.ts +5 -0
  64. package/src/client/router/link-utils.ts +184 -184
  65. package/src/client/router/provider.tsx +883 -804
  66. package/src/client/router/sync-catch-up.ts +113 -0
  67. package/src/client/router/types.ts +276 -276
  68. package/src/client/sync.ts +98 -98
  69. package/src/client.ts +369 -369
  70. package/src/config.ts +14 -1
  71. package/src/furin.ts +619 -465
  72. package/src/server/auto-invalidate/registry.ts +23 -1
  73. package/src/server/auto-invalidate/runtime.ts +159 -134
  74. package/src/server/cache/dev-loader.ts +77 -38
  75. package/src/server/cache/invalidation.ts +71 -30
  76. package/src/server/cache/isr.ts +20 -5
  77. package/src/server/cache/registry.ts +17 -20
  78. package/src/server/cache/ssg.ts +19 -4
  79. package/src/server/cache/store-view.ts +30 -0
  80. package/src/server/dev-page-plugin.ts +454 -454
  81. package/src/server/instance.ts +252 -0
  82. package/src/server/internal.ts +100 -5
  83. package/src/server/render/assemble.ts +160 -160
  84. package/src/server/render/isr.ts +323 -323
  85. package/src/server/render/not-found.ts +9 -3
  86. package/src/server/render/ssr.ts +603 -585
  87. package/src/server/render/template.ts +57 -24
  88. package/src/server/router/plugin.ts +384 -384
  89. package/src/server/sync/adapter.ts +65 -0
  90. package/src/server/sync/config.ts +60 -29
  91. package/src/server/sync/fingerprint.ts +44 -0
  92. package/src/server/sync/index.ts +15 -14
  93. package/src/server/sync/memory-adapter.ts +196 -0
  94. package/src/server/sync/plugin.ts +199 -108
  95. package/src/server/sync/response.ts +77 -0
  96. package/src/server/sync/stream.ts +162 -144
  97. package/src/shared/deferred-ndjson.ts +7 -0
  98. package/src/shared/prefix.ts +38 -0
package/src/furin.ts CHANGED
@@ -1,465 +1,619 @@
1
- import { existsSync } from "node:fs";
2
- import { basename, dirname, join, resolve } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { staticPlugin } from "@elysiajs/static";
5
- import { type AnyElysia, Elysia, file } from "elysia";
6
- import { type DrainContext, initLogger } from "evlog";
7
- import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
- import {
9
- _runWithRequestInvalidationScope,
10
- consumePendingInvalidations,
11
- getBuildId,
12
- setBuildId,
13
- } from "./server/cache/invalidation.ts";
14
- import { setSSGCache } from "./server/cache/ssg.ts";
15
- import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
16
- import { getCompileContext } from "./server/internal.ts";
17
- import { renderRootNotFound, warmSSGCache } from "./server/render/index.ts";
18
- import {
19
- setProductionTemplateContent,
20
- setProductionTemplatePath,
21
- } from "./server/render/template.ts";
22
- import {
23
- createDataEndpoint,
24
- createRoutePlugin,
25
- createSearchRouteMetadata,
26
- loadProdRoutes,
27
- } from "./server/router/index.ts";
28
- import { IS_DEV } from "./server/runtime-env.ts";
29
- import {
30
- createSyncStreamPlugin,
31
- type FurinSyncOption,
32
- resolveSyncStreamPath,
33
- runWithSyncStreamPath,
34
- } from "./server/sync/index.ts";
35
-
36
- // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
37
- export interface FurinCacheTags {}
38
-
39
- export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
40
-
41
- function resolveClientDirFromArgv(): string {
42
- return (
43
- resolveClientDirFromEnv() ??
44
- resolveClientDirFromModuleUrl() ??
45
- resolveClientDirFromProcessArgs() ??
46
- resolveFallbackClientDir()
47
- );
48
- }
49
-
50
- function resolveClientDirFromEnv(): string | null {
51
- const envClientDir = process.env.FURIN_CLIENT_DIR;
52
- if (!envClientDir) {
53
- return null;
54
- }
55
- return envClientDir.startsWith("/") ? envClientDir : resolve(process.cwd(), envClientDir);
56
- }
57
-
58
- function resolveClientDirFromModuleUrl(): string | null {
59
- try {
60
- const moduleUrl = new URL(import.meta.url);
61
- if (moduleUrl.protocol !== "file:") {
62
- return null;
63
- }
64
- const modulePath = fileURLToPath(moduleUrl);
65
- if (modulePath.includes("/$bunfs/")) {
66
- return null;
67
- }
68
- const moduleClientDir = join(dirname(modulePath), "client");
69
- if (existsSync(join(moduleClientDir, "index.html"))) {
70
- return moduleClientDir;
71
- }
72
- } catch {
73
- // ignore, fallback to argv-based resolution
74
- }
75
- return null;
76
- }
77
-
78
- function resolveClientDirFromProcessArgs(): string | null {
79
- const candidates = [
80
- process.argv[1],
81
- process.argv[0],
82
- (process as { argv0?: string }).argv0,
83
- process.execPath,
84
- ].filter((value): value is string => typeof value === "string" && value.length > 0);
85
-
86
- for (const candidate of candidates) {
87
- const resolved = resolveClientDirFromCandidate(candidate);
88
- if (resolved) {
89
- return resolved;
90
- }
91
- }
92
-
93
- return null;
94
- }
95
-
96
- function resolveClientDirFromCandidate(candidate: string): string | null {
97
- const name = basename(candidate);
98
- if (name === "bun" || name === "node") {
99
- return null;
100
- }
101
- if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
102
- return null;
103
- }
104
-
105
- const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
106
- if (existsSync(absolute)) {
107
- return join(dirname(absolute), "client");
108
- }
109
-
110
- if (!candidate.includes("/")) {
111
- return resolveClientDirFromPath(candidate);
112
- }
113
-
114
- return null;
115
- }
116
-
117
- function resolveClientDirFromPath(candidate: string): string | null {
118
- const pathEntries = process.env.PATH?.split(":") ?? [];
119
- for (const dir of pathEntries) {
120
- const fullPath = join(dir, candidate);
121
- if (existsSync(fullPath)) {
122
- return join(dirname(fullPath), "client");
123
- }
124
- }
125
- return null;
126
- }
127
-
128
- function resolveFallbackClientDir(): string {
129
- const defaultClientDir = resolve(process.cwd(), ".furin/build/bun/client");
130
- if (existsSync(join(defaultClientDir, "index.html"))) {
131
- return defaultClientDir;
132
- }
133
-
134
- return join(process.cwd(), "client");
135
- }
136
-
137
- async function setupProdTemplate(
138
- embedded: EmbeddedAppData | undefined,
139
- clientDir: string
140
- ): Promise<void> {
141
- if (embedded) {
142
- if (!embedded.template) {
143
- throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
144
- }
145
- const html = await Bun.file(embedded.template).text();
146
- setProductionTemplateContent(html);
147
- return;
148
- }
149
-
150
- const templatePath = join(clientDir, "index.html");
151
- if (!existsSync(templatePath)) {
152
- throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
153
- }
154
- setProductionTemplatePath(templatePath);
155
- }
156
-
157
- /**
158
- * Registers a HigherOrderFunction on the Elysia instance so that every request
159
- * runs inside a fresh `AsyncLocalStorage` scope. This isolates
160
- * `pendingInvalidations` per request, preventing concurrent requests from
161
- * stealing each other's `revalidatePath()` calls.
162
- *
163
- * Uses `app.wrap()` (Elysia HigherOrderFunction) instead of mutating
164
- * `app.handle`, because handle mutations are lost when the Furin plugin is
165
- * `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
166
- * plugin merge and wrap the entire composed `map` handler.
167
- */
168
- function wrapWithRequestScope(app: AnyElysia, syncStreamPath: string | undefined): Elysia {
169
- return app.wrap(
170
- (handler, _request) => (ctx: unknown) =>
171
- runWithSyncStreamPath(syncStreamPath, () =>
172
- _runWithRequestInvalidationScope(() => handler(ctx))
173
- )
174
- );
175
- }
176
-
177
- function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
178
- if (!ctx.ssgCache) {
179
- return;
180
- }
181
- for (const [path, entry] of Object.entries(ctx.ssgCache)) {
182
- setSSGCache(path, entry);
183
- }
184
- }
185
-
186
- /**
187
- * Main Furin plugin.
188
- *
189
- * Returns a standalone Elysia instance (async function) so that routes are
190
- * properly registered in Elysia's router for SPA navigation to work.
191
- *
192
- * ## Usage
193
- *
194
- * ```ts
195
- * new Elysia()
196
- * .use(await furin({ ... }))
197
- * .listen(3000)
198
- * ```
199
- */
200
- export async function furin({
201
- pagesDir,
202
- logger,
203
- clientLogging,
204
- sync,
205
- }: {
206
- pagesDir?: string;
207
- logger?: EvlogElysiaOptions;
208
- /**
209
- * Initialize the browser HTTP log drain in the hydration entry. Off by
210
- * default — enabling it adds `evlog/http` drain setup and points browser
211
- * events at `/_furin/ingest`. Server-side logging is configured via `logger`
212
- * and unaffected.
213
- */
214
- clientLogging?: boolean;
215
- /**
216
- * Enables Furin's built-in sync event stream. The opinionated default mounts
217
- * Server-Sent Events at `/_furin/sync`; pass an object only for constrained
218
- * reverse-proxy deployments that need a custom internal path.
219
- */
220
- sync?: FurinSyncOption;
221
- }) {
222
- const syncStreamPath = resolveSyncStreamPath(sync);
223
- const { exclude: userExclude, ...evlogOptions } = logger ?? {};
224
- initLogger({ env: { service: "furin" } });
225
-
226
- const loggerPlugin = new Elysia()
227
- .use(
228
- evlog({
229
- ...evlogOptions,
230
- exclude: [
231
- "/_client/**",
232
- "/public/**",
233
- "/favicon.ico",
234
- "/_bun_hmr_entry/**",
235
- ...(syncStreamPath ? [syncStreamPath] : []),
236
- // Note: /_furin/data is logged with the *logical* path rewritten by
237
- // createDataEndpoint via useLogger().set({ path }), so SPA navigations
238
- // appear as "GET /board/123 200" — same shape as a normal SSR nav.
239
- // /_furin/ingest is kept loggable so browser-side events show up.
240
- // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
241
- // like `!(...)` matches nothing, so don't add patterns relying on it.
242
- ...(userExclude ?? []),
243
- ],
244
- })
245
- )
246
- .post(
247
- "/_furin/ingest",
248
- ({ body, log, status }) => {
249
- if (!Array.isArray(body)) {
250
- return status("Bad Request");
251
- }
252
- // Cap batch size to prevent abuse
253
- const batch = (body as DrainContext[]).slice(0, 100);
254
- for (const entry of batch) {
255
- if (!entry || typeof entry !== "object" || !("event" in entry)) {
256
- log.set({ msg: "[furin] ingest: skipping malformed entry" });
257
- continue;
258
- }
259
- // Pick only safe, known fields from the event to prevent prototype pollution
260
- const event = entry.event as Record<string, unknown> | undefined;
261
- if (!event || typeof event !== "object") {
262
- continue;
263
- }
264
- const {
265
- __proto__,
266
- constructor: _ctor,
267
- prototype,
268
- environment: _browserEnv,
269
- ...safeEvent
270
- } = event as Record<string, unknown>;
271
- log.set({ ...safeEvent, service: "furin:browser" });
272
- }
273
- return status("No Content");
274
- },
275
- { parse: "json" }
276
- );
277
-
278
- const cwd = process.cwd();
279
- const ctx = getCompileContext();
280
- const resolvedPagesDir = ctx?.rootPath
281
- ? dirname(ctx.rootPath)
282
- : resolve(cwd, pagesDir ?? "src/pages");
283
-
284
- // Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
285
- const instanceName = `furin-${resolvedPagesDir.replaceAll("\\", "/")}`;
286
-
287
- // ── Dev: Bun native HMR ────────────────────────────────────────────────
288
- if (IS_DEV) {
289
- const furinDir = resolve(cwd, ".furin");
290
- // Lazy import — build pipeline has native deps not available in compiled binaries
291
- const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
292
- registerDevPagePlugin();
293
-
294
- const { createDevInspectorPlugin } = await import("./server/dev-inspector.ts");
295
-
296
- const { scanPages } = await import("./server/router/index.ts");
297
- const { root, routes } = await scanPages(resolvedPagesDir);
298
- const searchRoutes = createSearchRouteMetadata(routes);
299
-
300
- const { writeDevFiles } = await import("./build/hydrate.ts");
301
- writeDevFiles(
302
- routes,
303
- {
304
- outDir: furinDir,
305
- rootLayout: root.path,
306
- basePath: "",
307
- publicPath: "/_client/",
308
- clientLogging: clientLogging ?? false,
309
- },
310
- cwd
311
- );
312
-
313
- const publicDir = resolve(cwd, "public");
314
- const publicExists = existsSync(publicDir);
315
-
316
- const devApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
317
- .use(loggerPlugin)
318
- .onError({ as: "global" }, async ({ code, request }) => {
319
- if (code === "NOT_FOUND") {
320
- return await renderRootNotFound(root, request);
321
- }
322
- })
323
- .onAfterHandle({ as: "global" }, ({ set }) => {
324
- // Forward pending revalidation paths so the client can bust its prefetch cache
325
- const pending = consumePendingInvalidations();
326
- if (pending.length > 0) {
327
- set.headers["x-furin-revalidate"] = pending.join(",");
328
- }
329
- })
330
- .use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true }))
331
- .use(
332
- publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia()
333
- )
334
- .get(
335
- "/favicon.ico",
336
- publicExists
337
- ? file(join(publicDir, "favicon.ico"))
338
- : () => new Response(null, { status: 404 })
339
- )
340
- .use(createDevInspectorPlugin())
341
- .use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia())
342
- .use(createDataEndpoint(routes))
343
- .use((app) => {
344
- for (const route of routes) {
345
- app.use(createRoutePlugin(route, root, undefined, searchRoutes));
346
- }
347
- return app;
348
- });
349
- return wrapWithRequestScope(devApp, syncStreamPath);
350
- }
351
-
352
- // ── Production ──────────────────────────────────────────────────────────
353
- if (!ctx) {
354
- throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
355
- }
356
- const { root, routes } = loadProdRoutes(ctx);
357
- const searchRoutes = createSearchRouteMetadata(routes);
358
- const prodBuildId = ctx.buildId ?? "";
359
- setBuildId(prodBuildId);
360
- hydrateSSGCacheFromCompileContext(ctx);
361
-
362
- const embedded = ctx?.embedded;
363
- const clientDir = embedded ? "" : resolveClientDirFromArgv();
364
- await setupProdTemplate(embedded, clientDir);
365
-
366
- const prodApp = new Elysia({ name: instanceName, seed: resolvedPagesDir })
367
- .use(loggerPlugin)
368
- .onError({ as: "global" }, async ({ code, request }) => {
369
- if (code === "NOT_FOUND") {
370
- return await renderRootNotFound(root, request);
371
- }
372
- })
373
- .onAfterHandle({ as: "global" }, ({ path, set }) => {
374
- // Content-hashed client assets are permanently cacheable — browsers never need to
375
- // revalidate them because any change produces a new filename.
376
- if (path.startsWith("/_client/")) {
377
- set.headers["cache-control"] = "public, max-age=31536000, immutable";
378
- }
379
- // Forward pending revalidation paths so the client can bust its prefetch cache
380
- const pending = consumePendingInvalidations();
381
- if (pending.length > 0) {
382
- set.headers["x-furin-revalidate"] = pending.join(",");
383
- }
384
- // Tell the client the current build ID so it can detect stale deploys
385
- const buildId = getBuildId();
386
- if (buildId) {
387
- set.headers["x-furin-build-id"] = buildId;
388
- }
389
- })
390
- .onStart(async ({ server }) => {
391
- if (ctx.ssgCache) {
392
- return;
393
- }
394
- const origin = server?.url?.origin ?? "http://localhost:3000";
395
- await warmSSGCache(routes, root, origin, searchRoutes);
396
- })
397
- .use(
398
- await (async () => {
399
- if (embedded) {
400
- return new Elysia()
401
- .get("/favicon.ico", ({ status }) => {
402
- const asset = embedded.assets["/public/favicon.ico"];
403
- if (!asset) {
404
- return status("Not Found");
405
- }
406
- return Bun.file(asset);
407
- })
408
- .get("/_client/*", ({ params, status }) => {
409
- const asset = embedded.assets[`/_client/${params["*"]}`];
410
- if (!asset) {
411
- return status("Not Found");
412
- }
413
- return Bun.file(asset);
414
- })
415
- .get("/public/*", ({ params, status }) => {
416
- const asset = embedded.assets[`/public/${params["*"]}`];
417
- if (!asset) {
418
- return status("Not Found");
419
- }
420
- return Bun.file(asset);
421
- });
422
- }
423
- const publicDir = join(dirname(clientDir), "public");
424
- const app = new Elysia();
425
- if (existsSync(publicDir)) {
426
- app
427
- .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
428
- .use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
429
- }
430
- app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
431
- return app;
432
- })()
433
- )
434
- .use(syncStreamPath ? createSyncStreamPlugin(syncStreamPath) : new Elysia())
435
- .use(createDataEndpoint(routes))
436
- .use((app) => {
437
- for (const route of routes) {
438
- app.use(createRoutePlugin(route, root, prodBuildId, searchRoutes));
439
- }
440
- return app;
441
- });
442
- return wrapWithRequestScope(prodApp, syncStreamPath);
443
- }
444
-
445
- // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
446
- export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
447
- // ── Public API re-export ──────────────────────────────────────────────────────
448
- // biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
449
- export type { DeferredData, RuntimePage, RuntimeRoute } from "./client.ts";
450
- export { defer, isDeferred } from "./client.ts";
451
- export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
452
- export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
453
- export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
454
- export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
455
- export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
456
- export { furinSync, type SyncInput } from "./server/sync/index.ts";
457
- export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
458
- export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
459
- export type {
460
- NotFoundComponent,
461
- NotFoundOptions,
462
- NotFoundProps,
463
- } from "./shared/not-found.ts";
464
- export { isNotFoundError, notFound } from "./shared/not-found.ts";
465
- // biome-ignore-end lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
1
+ import { existsSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { staticPlugin } from "@elysiajs/static";
5
+ import { type AnyElysia, Elysia, file } from "elysia";
6
+ import { type DrainContext, initLogger } from "evlog";
7
+ import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
+ import { consumePendingInvalidations } from "./server/cache/invalidation.ts";
9
+ import { setSSGCache } from "./server/cache/ssg.ts";
10
+ import {
11
+ assertPrefixAvailable,
12
+ createInstance,
13
+ type FurinInstance,
14
+ hasRequestScope,
15
+ markTraffic,
16
+ normalizePrefix,
17
+ registerInstance,
18
+ resolveInstanceByPath,
19
+ runWithInstanceScope,
20
+ withInstance,
21
+ } from "./server/instance.ts";
22
+ import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
23
+ import { getCompileContext } from "./server/internal.ts";
24
+ import { renderRootNotFound, warmSSGCache } from "./server/render/index.ts";
25
+ import {
26
+ setProductionTemplateContent,
27
+ setProductionTemplatePath,
28
+ } from "./server/render/template.ts";
29
+ import {
30
+ createDataEndpoint,
31
+ createRoutePlugin,
32
+ createSearchRouteMetadata,
33
+ loadProdRoutes,
34
+ } from "./server/router/index.ts";
35
+ import { IS_DEV } from "./server/runtime-env.ts";
36
+ import {
37
+ createSyncStreamPlugin,
38
+ type FurinSyncOption,
39
+ resolveSyncStreamPath,
40
+ } from "./server/sync/index.ts";
41
+
42
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
43
+ export interface FurinCacheTags {}
44
+
45
+ export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
46
+
47
+ import { clientDirNameForPrefix } from "./shared/prefix.ts";
48
+
49
+ // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
50
+ export { clientDirNameForPrefix } from "./shared/prefix.ts";
51
+
52
+ function resolveClientDirFromArgv(prefix: string): string {
53
+ const dirName = clientDirNameForPrefix(prefix);
54
+ return (
55
+ resolveClientDirFromEnv(dirName) ??
56
+ resolveClientDirFromModuleUrl(dirName) ??
57
+ resolveClientDirFromProcessArgs(dirName) ??
58
+ resolveFallbackClientDir(dirName)
59
+ );
60
+ }
61
+
62
+ function resolveClientDirFromEnv(dirName: string): string | null {
63
+ const envClientDir = process.env.FURIN_CLIENT_DIR;
64
+ if (!envClientDir) {
65
+ return null;
66
+ }
67
+ const base = envClientDir.startsWith("/") ? envClientDir : resolve(process.cwd(), envClientDir);
68
+ // FURIN_CLIENT_DIR points at the ROOT instance's client dir; sibling
69
+ // instances live next to it under their own dir name.
70
+ return dirName === "client" ? base : join(dirname(base), dirName);
71
+ }
72
+
73
+ function resolveClientDirFromModuleUrl(dirName: string): string | null {
74
+ try {
75
+ const moduleUrl = new URL(import.meta.url);
76
+ if (moduleUrl.protocol !== "file:") {
77
+ return null;
78
+ }
79
+ const modulePath = fileURLToPath(moduleUrl);
80
+ if (modulePath.includes("/$bunfs/")) {
81
+ return null;
82
+ }
83
+ const moduleClientDir = join(dirname(modulePath), dirName);
84
+ if (existsSync(join(moduleClientDir, "index.html"))) {
85
+ return moduleClientDir;
86
+ }
87
+ } catch {
88
+ // ignore, fallback to argv-based resolution
89
+ }
90
+ return null;
91
+ }
92
+
93
+ function resolveClientDirFromProcessArgs(dirName: string): string | null {
94
+ const candidates = [
95
+ process.argv[1],
96
+ process.argv[0],
97
+ (process as { argv0?: string }).argv0,
98
+ process.execPath,
99
+ ].filter((value): value is string => typeof value === "string" && value.length > 0);
100
+
101
+ for (const candidate of candidates) {
102
+ const resolved = resolveClientDirFromCandidate(candidate, dirName);
103
+ if (resolved) {
104
+ return resolved;
105
+ }
106
+ }
107
+
108
+ return null;
109
+ }
110
+
111
+ function resolveClientDirFromCandidate(candidate: string, dirName: string): string | null {
112
+ const name = basename(candidate);
113
+ if (name === "bun" || name === "node") {
114
+ return null;
115
+ }
116
+ if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
117
+ return null;
118
+ }
119
+
120
+ const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
121
+ if (existsSync(absolute)) {
122
+ return join(dirname(absolute), dirName);
123
+ }
124
+
125
+ if (!candidate.includes("/")) {
126
+ return resolveClientDirFromPath(candidate, dirName);
127
+ }
128
+
129
+ return null;
130
+ }
131
+
132
+ function resolveClientDirFromPath(candidate: string, dirName: string): string | null {
133
+ const pathEntries = process.env.PATH?.split(":") ?? [];
134
+ for (const dir of pathEntries) {
135
+ const fullPath = join(dir, candidate);
136
+ if (existsSync(fullPath)) {
137
+ return join(dirname(fullPath), dirName);
138
+ }
139
+ }
140
+ return null;
141
+ }
142
+
143
+ function resolveFallbackClientDir(dirName: string): string {
144
+ const defaultClientDir = resolve(process.cwd(), ".furin/build/bun", dirName);
145
+ if (existsSync(join(defaultClientDir, "index.html"))) {
146
+ return defaultClientDir;
147
+ }
148
+
149
+ return join(process.cwd(), dirName);
150
+ }
151
+
152
+ async function setupProdTemplate(
153
+ embedded: EmbeddedAppData | undefined,
154
+ clientDir: string,
155
+ instance: FurinInstance
156
+ ): Promise<void> {
157
+ if (embedded) {
158
+ if (!embedded.template) {
159
+ throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
160
+ }
161
+ const html = await Bun.file(embedded.template).text();
162
+ setProductionTemplateContent(html, instance);
163
+ return;
164
+ }
165
+
166
+ const templatePath = join(clientDir, "index.html");
167
+ if (!existsSync(templatePath)) {
168
+ throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
169
+ }
170
+ setProductionTemplatePath(templatePath, instance);
171
+ }
172
+
173
+ /**
174
+ * Shape of one browser-submitted log event. The named keys are the dangerous
175
+ * ones stripped before `log.set` (prototype-pollution vectors, plus the
176
+ * browser `environment` which must not overwrite the server's); everything
177
+ * else is forwarded as-is.
178
+ */
179
+ type FurinBrowserEvent = {
180
+ __proto__?: unknown;
181
+ constructor?: unknown;
182
+ prototype?: unknown;
183
+ environment?: unknown;
184
+ } & Record<string, unknown>;
185
+
186
+ /** Evlog wide-event plugin + browser log ingest endpoint for one instance. */
187
+ function createLoggerPlugin(
188
+ prefix: string,
189
+ syncStreamPath: string | undefined,
190
+ logger: EvlogElysiaOptions | undefined
191
+ ): Elysia {
192
+ const { exclude: userExclude, ...evlogOptions } = logger ?? {};
193
+ return new Elysia()
194
+ .use(
195
+ evlog({
196
+ ...evlogOptions,
197
+ // Exclude patterns match the PHYSICAL request path — prefix them.
198
+ exclude: [
199
+ `${prefix}/_client/**`,
200
+ `${prefix}/public/**`,
201
+ `${prefix}/favicon.ico`,
202
+ `${prefix}/_bun_hmr_entry/**`,
203
+ ...(syncStreamPath ? [`${prefix}${syncStreamPath}`] : []),
204
+ // Note: /_furin/data is logged with the *logical* path rewritten by
205
+ // createDataEndpoint via useLogger().set({ path }), so SPA navigations
206
+ // appear as "GET /board/123 200" — same shape as a normal SSR nav.
207
+ // /_furin/ingest is kept loggable so browser-side events show up.
208
+ // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
209
+ // like `!(...)` matches nothing, so don't add patterns relying on it.
210
+ ...(userExclude ?? []),
211
+ ],
212
+ })
213
+ )
214
+ .post(
215
+ "/_furin/ingest",
216
+ ({ body, log, status }) => {
217
+ if (!Array.isArray(body)) {
218
+ return status("Bad Request");
219
+ }
220
+ // Cap batch size to prevent abuse
221
+ const batch = (body as DrainContext[]).slice(0, 100);
222
+ for (const entry of batch) {
223
+ if (!entry || typeof entry !== "object" || !("event" in entry)) {
224
+ log.set({ msg: "[furin] ingest: skipping malformed entry" });
225
+ continue;
226
+ }
227
+ // Pick only safe, known fields from the event to prevent prototype pollution
228
+ const event = entry.event as FurinBrowserEvent | undefined;
229
+ if (!event || typeof event !== "object") {
230
+ continue;
231
+ }
232
+ const {
233
+ __proto__,
234
+ constructor: _ctor,
235
+ prototype,
236
+ environment: _browserEnv,
237
+ ...safeEvent
238
+ } = event;
239
+ log.set({ ...safeEvent, service: "furin:browser" });
240
+ }
241
+ return status("No Content");
242
+ },
243
+ { parse: "json" }
244
+ ) as unknown as Elysia;
245
+ }
246
+
247
+ /**
248
+ * Registers a HigherOrderFunction on the Elysia instance so that every request
249
+ * runs inside a fresh instance-bound `AsyncLocalStorage` scope. This isolates
250
+ * `pendingInvalidations` per request AND binds the request to the furin
251
+ * instance that owns its path, so render/cache code resolves the right
252
+ * per-instance state (build ID, template, caches, sync path).
253
+ *
254
+ * Uses `app.wrap()` (Elysia HigherOrderFunction) instead of mutating
255
+ * `app.handle`, because handle mutations are lost when the Furin plugin is
256
+ * `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
257
+ * plugin merge and wrap the entire composed `map` handler.
258
+ *
259
+ * IMPORTANT — multi-instance: HigherOrderFunctions apply to the WHOLE parent
260
+ * app, so with N mounted furin instances all N wraps run stacked on every
261
+ * request. The scope guard makes the wrap idempotent (first one wins) and the
262
+ * owning instance is resolved from the request PATH, never from this
263
+ * closure — which wrap executes first is therefore irrelevant.
264
+ */
265
+ function wrapWithRequestScope(app: AnyElysia): Elysia {
266
+ return app.wrap((handler, request) => (ctx: unknown) => {
267
+ if (hasRequestScope()) {
268
+ return handler(ctx);
269
+ }
270
+ markTraffic();
271
+ const req = request ?? (ctx as { request?: Request } | undefined)?.request;
272
+ const pathname = req ? new URL(req.url).pathname : "/";
273
+ return runWithInstanceScope(resolveInstanceByPath(pathname), () => handler(ctx));
274
+ });
275
+ }
276
+
277
+ function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
278
+ if (!ctx.ssgCache) {
279
+ return;
280
+ }
281
+ for (const [path, entry] of Object.entries(ctx.ssgCache)) {
282
+ setSSGCache(path, entry);
283
+ }
284
+ }
285
+
286
+ /** Options for the {@link furin} plugin. */
287
+ export interface FurinOptions {
288
+ /**
289
+ * Production only: explicit directory holding this app's built client
290
+ * assets (chunks + index.html template). Packaged furin apps pass their own
291
+ * `dist/furin/client` here; when omitted the directory is auto-resolved
292
+ * next to the server artifact.
293
+ */
294
+ clientDir?: string;
295
+ /**
296
+ * Initialize the browser HTTP log drain in the hydration entry. Off by
297
+ * default — enabling it adds `evlog/http` drain setup and points browser
298
+ * events at `/_furin/ingest`. Server-side logging is configured via `logger`
299
+ * and unaffected.
300
+ */
301
+ clientLogging?: boolean;
302
+ logger?: EvlogElysiaOptions;
303
+ pagesDir?: string;
304
+ /**
305
+ * Mount prefix for this app, e.g. `"/admin"`. All pages, framework
306
+ * endpoints (`/_furin/*`) and client assets (`/_client/*`) are served under
307
+ * it, and the client bundle is built with the matching basePath. Defaults
308
+ * to `""` (root). Mounting two furin instances on the same prefix throws.
309
+ */
310
+ prefix?: string;
311
+ /**
312
+ * Enables Furin's built-in sync event stream. The opinionated default mounts
313
+ * Server-Sent Events at `/_furin/sync`; pass an object only for constrained
314
+ * reverse-proxy deployments that need a custom internal path.
315
+ */
316
+ sync?: FurinSyncOption;
317
+ }
318
+
319
+ /**
320
+ * Main Furin plugin.
321
+ *
322
+ * Returns a standalone Elysia instance (async function) so that routes are
323
+ * properly registered in Elysia's router for SPA navigation to work.
324
+ *
325
+ * ## Usage
326
+ *
327
+ * ```ts
328
+ * new Elysia()
329
+ * .use(await furin({ pagesDir: "./src/pages" }))
330
+ * .use(await furin({ pagesDir: "./src/admin", prefix: "/admin" }))
331
+ * .listen(3000)
332
+ * ```
333
+ */
334
+ export async function furin({
335
+ pagesDir,
336
+ prefix: rawPrefix,
337
+ clientDir: explicitClientDir,
338
+ logger,
339
+ clientLogging,
340
+ sync,
341
+ }: FurinOptions = {}) {
342
+ const prefix = normalizePrefix(rawPrefix);
343
+ const syncStreamPath = resolveSyncStreamPath(sync);
344
+ initLogger({ env: { service: "furin" } });
345
+ const loggerPlugin = createLoggerPlugin(prefix, syncStreamPath, logger);
346
+
347
+ const cwd = process.cwd();
348
+ // The pagesDir param drives which compile context this instance loads. In a
349
+ // deployed binary the cwd-resolved path may miss the build-time key — the
350
+ // lookup then falls back to the (stable) prefix, then to the sole context.
351
+ const paramPagesDir = resolve(cwd, pagesDir ?? "src/pages");
352
+ const ctx = getCompileContext(paramPagesDir, prefix);
353
+ const resolvedPagesDir = ctx?.rootPath ? dirname(ctx.rootPath) : paramPagesDir;
354
+
355
+ // Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
356
+ const instanceName = `furin-${prefix}-${resolvedPagesDir.replaceAll("\\", "/")}`;
357
+
358
+ // Same prefix + different pagesDir is a mount collision — fail fast, but
359
+ // only REGISTER right before returning so a failed mount leaves no stale
360
+ // registration behind. All per-app runtime state (build ID, caches,
361
+ // template, sync path) hangs off this object; requests are bound to it by
362
+ // path in wrapWithRequestScope.
363
+ const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
364
+ assertPrefixAvailable(prefix, normalizedPagesDir);
365
+ const instance = createInstance(prefix, normalizedPagesDir);
366
+ instance.syncStreamPath = syncStreamPath;
367
+
368
+ // ── Dev: Bun native HMR ────────────────────────────────────────────────
369
+ if (IS_DEV) {
370
+ // Each instance gets its own generated-files dir so two mounted apps do
371
+ // not overwrite each other's hydrate entry (root keeps plain `.furin`).
372
+ const instanceSlug = prefix === "" ? "" : prefix.slice(1).replaceAll("/", "__");
373
+ const furinDir = resolve(cwd, ".furin", instanceSlug);
374
+ // Lazy import — build pipeline has native deps not available in compiled binaries
375
+ const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
376
+ registerDevPagePlugin();
377
+
378
+ const { createDevInspectorPlugin } = await import("./server/dev-inspector.ts");
379
+
380
+ const { scanPages } = await import("./server/router/index.ts");
381
+ const { root, routes } = await scanPages(resolvedPagesDir);
382
+ const searchRoutes = createSearchRouteMetadata(routes);
383
+
384
+ const { writeDevFiles } = await import("./build/hydrate.ts");
385
+ writeDevFiles(
386
+ routes,
387
+ {
388
+ outDir: furinDir,
389
+ rootLayout: root.path,
390
+ basePath: prefix,
391
+ publicPath: `${prefix}/_client/`,
392
+ clientLogging: clientLogging ?? false,
393
+ // furin-env.d.ts is one file at the project root — only the root
394
+ // instance owns it, otherwise mounted apps clobber each other's types.
395
+ skipRouteTypes: prefix !== "",
396
+ },
397
+ cwd
398
+ );
399
+
400
+ const publicDir = resolve(cwd, "public");
401
+ const publicExists = existsSync(publicDir);
402
+
403
+ // Routes registered below are LOGICAL — Elysia's `prefix` makes them
404
+ // physical when this plugin is merged into the parent app (child prefixes
405
+ // like staticPlugin's compose underneath).
406
+ const devApp = new Elysia({
407
+ name: instanceName,
408
+ seed: resolvedPagesDir,
409
+ prefix: prefix || undefined,
410
+ })
411
+ .use(loggerPlugin)
412
+ // Local scope (default) — a global hook would leak onto sibling furin
413
+ // instances mounted on the same parent app.
414
+ .onError(async ({ code, request }) => {
415
+ if (code === "NOT_FOUND") {
416
+ return await renderRootNotFound(root, request);
417
+ }
418
+ })
419
+ .onAfterHandle(({ set }) => {
420
+ // Forward pending revalidation paths so the client can bust its prefetch cache
421
+ const pending = consumePendingInvalidations();
422
+ if (pending.length > 0) {
423
+ set.headers["x-furin-revalidate"] = pending.join(",");
424
+ }
425
+ })
426
+ .use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true }))
427
+ .use(
428
+ publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia()
429
+ )
430
+ .get(
431
+ "/favicon.ico",
432
+ publicExists
433
+ ? file(join(publicDir, "favicon.ico"))
434
+ : () => new Response(null, { status: 404 })
435
+ )
436
+ .use(createDevInspectorPlugin())
437
+ .use(
438
+ syncStreamPath
439
+ ? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`)
440
+ : new Elysia()
441
+ )
442
+ .use(createDataEndpoint(routes))
443
+ .use((app) =>
444
+ routes.reduce(
445
+ (chain, route) => chain.use(createRoutePlugin(route, root, undefined, searchRoutes)),
446
+ app
447
+ )
448
+ )
449
+ .use(createNotFoundHandling(prefix, routes, root));
450
+ registerInstance(instance);
451
+ return wrapWithRequestScope(devApp);
452
+ }
453
+
454
+ // ── Production ──────────────────────────────────────────────────────────
455
+ if (!ctx) {
456
+ throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
457
+ }
458
+ const { root, routes } = loadProdRoutes(ctx);
459
+ const searchRoutes = createSearchRouteMetadata(routes);
460
+ const prodBuildId = ctx.buildId ?? "";
461
+ instance.buildId = prodBuildId;
462
+ // Init-time writes target THIS instance explicitly — with several mounted
463
+ // apps there is no ambient request scope to resolve it from.
464
+ withInstance(instance, () => {
465
+ hydrateSSGCacheFromCompileContext(ctx);
466
+ });
467
+
468
+ const embedded = ctx?.embedded;
469
+ const clientDir = embedded ? "" : (explicitClientDir ?? resolveClientDirFromArgv(prefix));
470
+ await setupProdTemplate(embedded, clientDir, instance);
471
+
472
+ const clientAssetPrefix = `${prefix}/_client/`;
473
+ const prodApp = new Elysia({
474
+ name: instanceName,
475
+ seed: resolvedPagesDir,
476
+ prefix: prefix || undefined,
477
+ })
478
+ .use(loggerPlugin)
479
+ // Local scope (default) — a global hook would leak onto sibling furin
480
+ // instances mounted on the same parent app.
481
+ .onError(async ({ code, request }) => {
482
+ if (code === "NOT_FOUND") {
483
+ return await renderRootNotFound(root, request);
484
+ }
485
+ })
486
+ .onAfterHandle(({ path, set }) => {
487
+ // Content-hashed client assets are permanently cacheable — browsers never need to
488
+ // revalidate them because any change produces a new filename.
489
+ if (path.startsWith(clientAssetPrefix)) {
490
+ set.headers["cache-control"] = "public, max-age=31536000, immutable";
491
+ }
492
+ // Forward pending revalidation paths so the client can bust its prefetch cache
493
+ const pending = consumePendingInvalidations();
494
+ if (pending.length > 0) {
495
+ set.headers["x-furin-revalidate"] = pending.join(",");
496
+ }
497
+ // Tell the client the current build ID so it can detect stale deploys
498
+ if (instance.buildId) {
499
+ set.headers["x-furin-build-id"] = instance.buildId;
500
+ }
501
+ })
502
+ .onStart(async ({ server }) => {
503
+ if (ctx.ssgCache) {
504
+ return;
505
+ }
506
+ const origin = server?.url?.origin ?? "http://localhost:3000";
507
+ // Synthetic (non-request) renders — bind them to this instance so the
508
+ // render pipeline resolves its template/caches, not a sibling's.
509
+ await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
510
+ })
511
+ .use(
512
+ await (async () => {
513
+ if (embedded) {
514
+ return new Elysia()
515
+ .get("/favicon.ico", ({ status }) => {
516
+ const asset = embedded.assets["/public/favicon.ico"];
517
+ if (!asset) {
518
+ return status("Not Found");
519
+ }
520
+ return Bun.file(asset);
521
+ })
522
+ .get("/_client/*", ({ params, status }) => {
523
+ const asset = embedded.assets[`/_client/${params["*"]}`];
524
+ if (!asset) {
525
+ return status("Not Found");
526
+ }
527
+ return Bun.file(asset);
528
+ })
529
+ .get("/public/*", ({ params, status }) => {
530
+ const asset = embedded.assets[`/public/${params["*"]}`];
531
+ if (!asset) {
532
+ return status("Not Found");
533
+ }
534
+ return Bun.file(asset);
535
+ });
536
+ }
537
+ const publicDir = join(dirname(clientDir), "public");
538
+ const app = new Elysia();
539
+ if (existsSync(publicDir)) {
540
+ app
541
+ .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
542
+ .use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
543
+ }
544
+ app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
545
+ return app;
546
+ })()
547
+ )
548
+ .use(
549
+ syncStreamPath
550
+ ? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`)
551
+ : new Elysia()
552
+ )
553
+ .use(createDataEndpoint(routes))
554
+ .use((app) =>
555
+ routes.reduce(
556
+ (chain, route) => chain.use(createRoutePlugin(route, root, prodBuildId, searchRoutes)),
557
+ app
558
+ )
559
+ )
560
+ .use(createNotFoundHandling(prefix, routes, root));
561
+ registerInstance(instance);
562
+ return wrapWithRequestScope(prodApp);
563
+ }
564
+
565
+ /**
566
+ * 404 handling per mount position:
567
+ *
568
+ * - ROOT instance (`prefix === ""`): the historical `{as:"global"}`
569
+ * onError(NOT_FOUND) hook — it owns the root scope, and a parent `.onError`
570
+ * registered BEFORE `.use(furin)` still wins (documented escape hatch for
571
+ * JSON API 404s).
572
+ * - PREFIXED instance: a global hook would leak onto sibling apps, and a
573
+ * local one never sees unmatched paths (they belong to no route). Instead
574
+ * the instance registers a lowest-priority catch-all under its own prefix;
575
+ * the router prefers every more-specific route, so this only fires for
576
+ * paths no page matched. Skipped when the app defines its own `[...rest]`
577
+ * catch-all page.
578
+ */
579
+ function createNotFoundHandling(
580
+ prefix: string,
581
+ routes: Array<{ pattern: string }>,
582
+ root: Parameters<typeof renderRootNotFound>[0]
583
+ ): Elysia {
584
+ const app = new Elysia();
585
+ if (prefix === "") {
586
+ app.onError({ as: "global" }, async ({ code, request }) => {
587
+ if (code === "NOT_FOUND") {
588
+ return await renderRootNotFound(root, request);
589
+ }
590
+ });
591
+ return app;
592
+ }
593
+ if (routes.some((route) => route.pattern === "/*")) {
594
+ return app;
595
+ }
596
+ app.get("/*", ({ request }) => renderRootNotFound(root, request));
597
+ return app;
598
+ }
599
+
600
+ export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
601
+ // ── Public API re-export ──────────────────────────────────────────────────────
602
+ // biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
603
+ export type { DeferredData, RuntimePage, RuntimeRoute } from "./client.ts";
604
+ export { defer, isDeferred } from "./client.ts";
605
+ export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
606
+ export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
607
+ export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
608
+ export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
609
+ export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
610
+ export { furinSync, type SyncInput, type SyncRouteOption } from "./server/sync/index.ts";
611
+ export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
612
+ export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
613
+ export type {
614
+ NotFoundComponent,
615
+ NotFoundOptions,
616
+ NotFoundProps,
617
+ } from "./shared/not-found.ts";
618
+ export { isNotFoundError, notFound } from "./shared/not-found.ts";
619
+ // biome-ignore-end lint/performance/noBarrelFile: intentional — furin.ts is the public package entry