@teyik0/furin 0.4.0-alpha.2 → 0.5.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/build/compile-entry.d.ts +2 -1
  2. package/dist/build/compile-entry.ts +17 -13
  3. package/dist/build/elysia-aot.d.ts +9 -0
  4. package/dist/build/entry-template.d.ts +5 -1
  5. package/dist/build/entry-template.ts +24 -5
  6. package/dist/build/index.js +753 -453
  7. package/dist/build/server-app-entry.d.ts +12 -0
  8. package/dist/cache.d.ts +1 -0
  9. package/dist/cache.js +185 -0
  10. package/dist/cli/index.js +766 -466
  11. package/dist/client/internal/runtime-types.d.ts +8 -1
  12. package/dist/client/link.js +221 -11
  13. package/dist/client/sync.d.ts +1 -0
  14. package/dist/config.d.ts +22 -21
  15. package/dist/config.js +1 -1
  16. package/dist/define-route.d.ts +273 -1009
  17. package/dist/furin.d.ts +20 -5
  18. package/dist/furin.js +6222 -5383
  19. package/dist/plugin/routes.d.ts +6 -0
  20. package/dist/server/assets/production.d.ts +3 -0
  21. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  22. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  23. package/dist/server/cache/invalidation.d.ts +1 -1
  24. package/dist/server/cache/page-cache-state.d.ts +5 -0
  25. package/dist/server/cache/page-cache.d.ts +53 -0
  26. package/dist/server/cache/redis/index.d.ts +39 -0
  27. package/dist/server/cache/redis/index.js +396 -0
  28. package/dist/server/cache/redis/scripts.d.ts +6 -0
  29. package/dist/server/context-logger.d.ts +2 -2
  30. package/dist/server/dev/runtime.production.d.ts +1 -0
  31. package/dist/server/dev-page-plugin.d.ts +7 -0
  32. package/dist/server/evlog.d.ts +14 -0
  33. package/dist/server/internal.d.ts +6 -0
  34. package/dist/server/internal.js +2537 -0
  35. package/dist/server/render/not-found.d.ts +1 -1
  36. package/dist/server/render/ssg.d.ts +5 -0
  37. package/dist/server/render/static-params.d.ts +4 -0
  38. package/dist/server/router/defined-route.d.ts +1 -1
  39. package/dist/server/router/schemas.d.ts +1 -0
  40. package/dist/server/sync/index.js +794 -116
  41. package/dist/server/sync/plugin.d.ts +31 -158
  42. package/dist/server/sync/stream.d.ts +34 -49
  43. package/dist/shared/elysia-contract.d.ts +8 -14
  44. package/package.json +13 -7
  45. package/src/adapter/README.md +9 -2
  46. package/src/adapter/bun.ts +73 -27
  47. package/src/adapter/package.ts +6 -2
  48. package/src/adapter/runtime-build.ts +11 -4
  49. package/src/adapter/static.ts +8 -6
  50. package/src/adapter/vercel.ts +49 -30
  51. package/src/build/client.ts +18 -1
  52. package/src/build/compile-entry.ts +17 -13
  53. package/src/build/elysia-aot.ts +102 -0
  54. package/src/build/entry-template.ts +24 -5
  55. package/src/build/index.ts +0 -5
  56. package/src/build/production-instrumentation.ts +2 -2
  57. package/src/build/server-app-entry.ts +60 -0
  58. package/src/build/shared.ts +3 -1
  59. package/src/build/ssg-cache.ts +5 -10
  60. package/src/build/virtual-entry.ts +5 -4
  61. package/src/cache.ts +12 -0
  62. package/src/cli/config.ts +3 -3
  63. package/src/cli/index.ts +5 -2
  64. package/src/client/internal/runtime-types.ts +10 -1
  65. package/src/client/sync.ts +1 -0
  66. package/src/config.ts +3 -2
  67. package/src/define-route.ts +266 -128
  68. package/src/furin.ts +138 -149
  69. package/src/plugin/route-config-autofix.ts +11 -2
  70. package/src/plugin/routes.ts +85 -29
  71. package/src/server/assets/production.ts +99 -0
  72. package/src/server/auto-invalidate/plugin.ts +4 -4
  73. package/src/server/auto-invalidate/runtime.ts +74 -42
  74. package/src/server/browser-events/plugin.ts +6 -1
  75. package/src/server/cache/invalidation.ts +61 -20
  76. package/src/server/cache/page-cache-state.ts +22 -0
  77. package/src/server/cache/page-cache.ts +300 -0
  78. package/src/server/cache/redis/index.ts +350 -0
  79. package/src/server/cache/redis/scripts.ts +160 -0
  80. package/src/server/context-logger.ts +5 -5
  81. package/src/server/dev/runtime.production.ts +4 -0
  82. package/src/server/dev-page-plugin.ts +54 -10
  83. package/src/server/evlog.ts +99 -0
  84. package/src/server/internal.ts +7 -0
  85. package/src/server/render/isr.ts +480 -132
  86. package/src/server/render/loaders.ts +18 -12
  87. package/src/server/render/not-found.ts +4 -4
  88. package/src/server/render/ppr-document.ts +2 -2
  89. package/src/server/render/ppr-route.ts +193 -7
  90. package/src/server/render/ssg.ts +148 -4
  91. package/src/server/render/ssr.ts +4 -6
  92. package/src/server/render/static-params.ts +174 -0
  93. package/src/server/router/defined-route.ts +2 -1
  94. package/src/server/router/hmr.ts +2 -0
  95. package/src/server/router/plugin.ts +44 -35
  96. package/src/server/router/schema-merge.ts +1 -1
  97. package/src/server/router/schemas.ts +174 -61
  98. package/src/server/sync/plugin.ts +14 -10
  99. package/src/server/sync/response.ts +3 -3
  100. package/src/shared/elysia-contract.ts +23 -25
package/src/furin.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { basename, dirname, join, resolve } from "node:path";
2
+ import { basename, delimiter, dirname, join, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import { staticPlugin } from "@elysiajs/static";
5
- import { type AnyElysia, Elysia, file } from "elysia";
4
+ import { staticPlugin } from "@elysia/static";
5
+ import { type AnyElysia, Elysia, file, NotFound, problem } from "elysia";
6
6
  import type { DrainContext, LoggerConfig } from "evlog";
7
- import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
7
  import { FURIN_RENDER_DECORATOR, type FurinRouteDispatcher } from "./define-route.ts";
9
- import { createBrowserEventsPlugin } from "./server/browser-events/plugin.ts";
8
+ import { createProductionAssetsPlugin } from "./server/assets/production.ts";
10
9
  import { consumePendingInvalidations } from "./server/cache/invalidation.ts";
10
+ import type { PageCacheAdapter } from "./server/cache/page-cache.ts";
11
+ import { setPageCacheAdapter } from "./server/cache/page-cache-state.ts";
11
12
  import { setSSGCache } from "./server/cache/ssg.ts";
12
13
  import type { DevelopmentRouteSnapshot, DevGraph } from "./server/dev/graph.ts";
13
14
  import {
@@ -16,6 +17,7 @@ import {
16
17
  runWithRequestInstrumentation,
17
18
  shouldInstrumentRequest,
18
19
  } from "./server/devtools/instrumentation.ts";
20
+ import { createFurinEvlog, type FurinEvlogOptions } from "./server/evlog.ts";
19
21
  import {
20
22
  assertPrefixAvailable,
21
23
  createInstance,
@@ -50,15 +52,18 @@ import {
50
52
  import type { ResolvedRoute, RootLayout } from "./server/router/types.ts";
51
53
  import { IS_DEV } from "./server/runtime-env.ts";
52
54
  import { type FurinSyncOption, resolveSyncPath } from "./server/sync/config.ts";
53
- import { createSyncChangesPlugin } from "./server/sync/stream.ts";
54
55
 
55
56
  // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
56
57
  export interface FurinCacheTags {}
57
58
 
58
59
  export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
59
60
 
60
- function createProductionBrowserEventsPlugin(sync: FurinSyncOption | undefined): AnyElysia {
61
- return sync ? createBrowserEventsPlugin({ sync }) : new Elysia();
61
+ async function createProductionBrowserEventsPlugin(
62
+ sync: FurinSyncOption | undefined
63
+ ): Promise<AnyElysia> {
64
+ return sync
65
+ ? (await import("./server/browser-events/plugin.ts")).createBrowserEventsPlugin({ sync })
66
+ : new Elysia();
62
67
  }
63
68
 
64
69
  function repairedDevelopmentRoutes(
@@ -177,7 +182,10 @@ function resolveClientDirFromCandidate(candidate: string, dirName: string): stri
177
182
 
178
183
  const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
179
184
  if (existsSync(absolute)) {
180
- return join(dirname(absolute), dirName);
185
+ const clientDir = join(dirname(absolute), dirName);
186
+ if (existsSync(join(clientDir, "index.html"))) {
187
+ return clientDir;
188
+ }
181
189
  }
182
190
 
183
191
  if (!candidate.includes("/")) {
@@ -188,11 +196,14 @@ function resolveClientDirFromCandidate(candidate: string, dirName: string): stri
188
196
  }
189
197
 
190
198
  function resolveClientDirFromPath(candidate: string, dirName: string): string | null {
191
- const pathEntries = process.env.PATH?.split(":") ?? [];
199
+ const pathEntries = process.env.PATH?.split(delimiter) ?? [];
192
200
  for (const dir of pathEntries) {
193
201
  const fullPath = join(dir, candidate);
194
202
  if (existsSync(fullPath)) {
195
- return join(dirname(fullPath), dirName);
203
+ const clientDir = join(dirname(fullPath), dirName);
204
+ if (existsSync(join(clientDir, "index.html"))) {
205
+ return clientDir;
206
+ }
196
207
  }
197
208
  }
198
209
  return null;
@@ -310,12 +321,12 @@ async function readBrowserIngest(request: Request): Promise<BrowserIngestRead> {
310
321
  function createLoggerPlugin(
311
322
  prefix: string,
312
323
  syncPath: string | undefined,
313
- logger: EvlogElysiaOptions | undefined,
324
+ logger: FurinEvlogOptions | undefined,
314
325
  clientLogging: boolean
315
- ): Elysia {
326
+ ) {
316
327
  const { exclude: userExclude, ...evlogOptions } = logger ?? {};
317
328
  const app = new Elysia().use(
318
- evlog({
329
+ createFurinEvlog({
319
330
  ...evlogOptions,
320
331
  // Exclude patterns match the PHYSICAL request path — prefix them.
321
332
  exclude: [
@@ -326,7 +337,7 @@ function createLoggerPlugin(
326
337
  ...instrumentationLoggerExclusions(prefix),
327
338
  ...(syncPath ? [`${prefix}${syncPath}/**`] : []),
328
339
  // Note: /_furin/data is logged with the *logical* path rewritten by
329
- // createDataEndpoint via useLogger().set({ path }), so SPA navigations
340
+ // createDataEndpoint via getLogger().set({ path }), so SPA navigations
330
341
  // appear as "GET /board/123 200" — same shape as a normal SSR nav.
331
342
  // /_furin/ingest remains loggable when browser logging is explicitly
332
343
  // enabled so browser-side events show up.
@@ -338,50 +349,46 @@ function createLoggerPlugin(
338
349
  );
339
350
 
340
351
  if (!clientLogging) {
341
- return app as unknown as Elysia;
352
+ return app;
342
353
  }
343
354
 
344
- return app.post(
345
- "/_furin/ingest",
346
- async ({ log, request, status }) => {
347
- const parsed = await readBrowserIngest(request);
348
- if (parsed.kind === "oversized") {
349
- return status(413);
350
- }
351
- if (parsed.kind === "invalid") {
352
- return status("Bad Request");
355
+ return app.post("/_furin/ingest", { parse: "none" }, async ({ log, request, status }) => {
356
+ const parsed = await readBrowserIngest(request);
357
+ if (parsed.kind === "oversized") {
358
+ return problem(413, { detail: "Browser event payload exceeds 64 KiB." });
359
+ }
360
+ if (parsed.kind === "invalid") {
361
+ return problem("Bad Request", { detail: "Browser event payload must be valid JSON." });
362
+ }
363
+ const { body } = parsed;
364
+ if (!Array.isArray(body)) {
365
+ return problem("Bad Request", { detail: "Browser event payload must be a JSON array." });
366
+ }
367
+ const batch = (body as DrainContext[]).slice(0, MAX_BROWSER_INGEST_EVENTS);
368
+ for (const entry of batch) {
369
+ if (!entry || typeof entry !== "object" || !("event" in entry)) {
370
+ log.set({ msg: "[furin] ingest: skipping malformed entry" });
371
+ continue;
353
372
  }
354
- const { body } = parsed;
355
- if (!Array.isArray(body)) {
356
- return status("Bad Request");
373
+ // Pick only safe, known fields from the event to prevent prototype pollution
374
+ const event = entry.event as FurinBrowserEvent | undefined;
375
+ if (!event || typeof event !== "object") {
376
+ continue;
357
377
  }
358
- const batch = (body as DrainContext[]).slice(0, MAX_BROWSER_INGEST_EVENTS);
359
- for (const entry of batch) {
360
- if (!entry || typeof entry !== "object" || !("event" in entry)) {
361
- log.set({ msg: "[furin] ingest: skipping malformed entry" });
362
- continue;
363
- }
364
- // Pick only safe, known fields from the event to prevent prototype pollution
365
- const event = entry.event as FurinBrowserEvent | undefined;
366
- if (!event || typeof event !== "object") {
367
- continue;
368
- }
369
- const {
370
- __proto__,
371
- constructor: _ctor,
372
- prototype,
373
- environment: _browserEnv,
374
- ...safeEvent
375
- } = event;
376
- log.set({ ...safeEvent, service: "furin:browser" });
377
- }
378
- return status("No Content");
379
- },
380
- { parse: "none" }
381
- ) as unknown as Elysia;
378
+ const {
379
+ __proto__,
380
+ constructor: _ctor,
381
+ prototype,
382
+ environment: _browserEnv,
383
+ ...safeEvent
384
+ } = event;
385
+ log.set({ ...safeEvent, service: "furin:browser" });
386
+ }
387
+ return status("No Content");
388
+ }) as unknown as Elysia;
382
389
  }
383
390
 
384
- function initializeLogger(logger: FurinLoggerOptions | undefined): EvlogElysiaOptions {
391
+ function initializeLogger(logger: FurinLoggerOptions | undefined): FurinEvlogOptions {
385
392
  const { sampling, ...elysiaLoggerOptions } = logger ?? {};
386
393
  initializeFurinLogger({
387
394
  env: { service: "furin" },
@@ -409,32 +416,25 @@ function initializeLogger(logger: FurinLoggerOptions | undefined): EvlogElysiaOp
409
416
  * closure — which wrap executes first is therefore irrelevant.
410
417
  */
411
418
  function wrapWithRequestScope(app: AnyElysia): Elysia {
412
- return app.wrap((handler, request) => (ctx: unknown) => {
419
+ return app.wrap((fetch) => (request, ...rest) => {
413
420
  if (hasRequestScope()) {
414
- return handler(ctx);
421
+ return fetch(request, ...rest);
415
422
  }
416
423
  markTraffic();
417
- const req = request ?? (ctx as { request?: Request } | undefined)?.request;
418
- const pathname = req ? new URL(req.url).pathname : "/";
424
+ const { pathname } = new URL(request.url);
419
425
  const instance = resolveInstanceByPath(pathname);
420
426
  return runWithInstanceScope(instance, () => {
421
- if (!(req && shouldInstrumentRequest(pathname, instance.prefix))) {
422
- return handler(ctx);
427
+ if (!shouldInstrumentRequest(pathname, instance.prefix)) {
428
+ return fetch(request, ...rest);
423
429
  }
424
- return runWithRequestInstrumentation(req, () => handler(ctx));
430
+ return runWithRequestInstrumentation(request, () => fetch(request, ...rest));
425
431
  });
426
432
  });
427
433
  }
428
434
 
429
- function createFurinPlugin(
430
- app: AnyElysia,
431
- prepareParent: ((parentApp: AnyElysia) => void) | undefined
432
- ) {
435
+ function createFurinPlugin(app: AnyElysia) {
433
436
  const scopedApp = wrapWithRequestScope(app);
434
- return <ParentApp extends AnyElysia>(parentApp: ParentApp) => {
435
- prepareParent?.(parentApp);
436
- return parentApp.use(scopedApp);
437
- };
437
+ return <ParentApp extends AnyElysia>(parentApp: ParentApp) => parentApp.use(scopedApp);
438
438
  }
439
439
 
440
440
  async function loadDevelopmentRoutes(resolvedPagesDir: string) {
@@ -469,20 +469,14 @@ function createNativeRouteRenderer(
469
469
  mergeRouteSchemas(matched.route.routeChain, "params")
470
470
  );
471
471
  if (!parsedParams.ok) {
472
- return Response.json(
473
- { errors: parsedParams.errors, message: "Invalid params", type: "validation" },
474
- { status: 422 }
475
- );
472
+ return problem(422, { detail: "Invalid params", errors: parsedParams.errors });
476
473
  }
477
474
  const parsedQuery = await parseRouteQuery(
478
475
  requestUrl,
479
476
  mergeRouteSchemas(matched.route.routeChain, "query")
480
477
  );
481
478
  if (!parsedQuery.ok) {
482
- return Response.json(
483
- { errors: parsedQuery.errors, message: "Invalid query", type: "validation" },
484
- { status: 422 }
485
- );
479
+ return problem(422, { detail: "Invalid query", errors: parsedQuery.errors });
486
480
  }
487
481
  context.params = parsedParams.params;
488
482
  context.query = parsedQuery.query;
@@ -530,7 +524,7 @@ function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
530
524
  }
531
525
 
532
526
  /** Options for the {@link furin} plugin. */
533
- export type FurinLoggerOptions = EvlogElysiaOptions & Pick<LoggerConfig, "sampling">;
527
+ export type FurinLoggerOptions = FurinEvlogOptions & Pick<LoggerConfig, "sampling">;
534
528
 
535
529
  export interface FurinOptions {
536
530
  /**
@@ -548,6 +542,12 @@ export interface FurinOptions {
548
542
  */
549
543
  clientLogging?: boolean;
550
544
  logger?: FurinLoggerOptions;
545
+ /**
546
+ * Cache for public page artifacts. Use a distributed adapter when several
547
+ * replicas serve the same application. When omitted, Furin keeps its
548
+ * process-local cache.
549
+ */
550
+ pageCache?: PageCacheAdapter;
551
551
  pagesDir?: string;
552
552
  /**
553
553
  * Mount prefix for this app, e.g. `"/admin"`. All pages, framework
@@ -564,6 +564,21 @@ export interface FurinOptions {
564
564
  sync?: FurinSyncOption;
565
565
  }
566
566
 
567
+ function configurePageCache(
568
+ instance: FurinInstance,
569
+ ctx: CompileContext | null,
570
+ pageCache: PageCacheAdapter | undefined
571
+ ): void {
572
+ if (pageCache !== undefined && ctx?.deploymentTarget === "vercel") {
573
+ throw new Error(
574
+ "[furin] pageCache cannot be configured with the Vercel target. Vercel owns SSG, ISR, and PPR public caching."
575
+ );
576
+ }
577
+ if (pageCache !== undefined) {
578
+ setPageCacheAdapter(instance, pageCache);
579
+ }
580
+ }
581
+
567
582
  /**
568
583
  * Main Furin plugin.
569
584
  *
@@ -586,6 +601,7 @@ export async function furin({
586
601
  clientDir: explicitClientDir,
587
602
  logger,
588
603
  clientLogging,
604
+ pageCache,
589
605
  sync,
590
606
  }: FurinOptions = {}) {
591
607
  const prefix = normalizePrefix(rawPrefix);
@@ -618,6 +634,7 @@ export async function furin({
618
634
  assertPrefixAvailable(prefix, normalizedPagesDir);
619
635
  const instance = createInstance(prefix, normalizedPagesDir);
620
636
  instance.syncPath = syncPath;
637
+ configurePageCache(instance, ctx, pageCache);
621
638
 
622
639
  // ── Dev: Bun native HMR ────────────────────────────────────────────────
623
640
  if (IS_DEV) {
@@ -733,10 +750,8 @@ export async function furin({
733
750
  throw error;
734
751
  }
735
752
  });
736
- const devHtmlBundle = (await import(join(furinDir, "index.html"))).default;
737
753
  const publicDir = resolve(cwd, "public");
738
754
  const publicExists = existsSync(publicDir);
739
- const hmrEntryPath = `${prefix}/_bun_hmr_entry`;
740
755
  let routeTopologyWatcher: ReturnType<typeof registerDevRouteTopologyWatcher> | undefined;
741
756
 
742
757
  // Routes registered below are LOGICAL — Elysia's `prefix` makes them
@@ -747,7 +762,7 @@ export async function furin({
747
762
  prefix: prefix || undefined,
748
763
  seed: resolvedPagesDir,
749
764
  })
750
- .onStart(() => {
765
+ .setup(() => {
751
766
  routeTopologyWatcher = registerDevRouteTopologyWatcher({
752
767
  instance: routeInstance,
753
768
  onRouteFilesTouched: async (sourcePaths) => {
@@ -777,22 +792,18 @@ export async function furin({
777
792
  },
778
793
  });
779
794
  })
780
- .onStop(() => {
795
+ .cleanup(() => {
781
796
  routeTopologyWatcher?.close();
782
797
  routeTopologyWatcher = undefined;
783
798
  })
784
- // Elysia 1.4.30 only preserves Bun's native HTMLBundle handler when the
785
- // bundle is also present in serve.routes once request hooks are installed.
786
799
  .use(await staticPlugin({ assets: furinDir, bunFullstack: true, prefix: "/_bun_hmr_entry" }))
787
800
  .use(loggerPlugin)
788
801
  // Local scope (default) — a global hook would leak onto sibling furin
789
802
  // instances mounted on the same parent app.
790
- .onError(async ({ code, request, server }) => {
791
- if (code === "NOT_FOUND") {
792
- return await renderRootNotFound(currentSnapshot().root, request, server?.url.origin);
793
- }
794
- })
795
- .onAfterHandle(({ set }) => {
803
+ .error(NotFound, async ({ request, server }) =>
804
+ renderRootNotFound(currentSnapshot().root, request, server?.url.origin)
805
+ )
806
+ .afterHandle(({ set }) => {
796
807
  // Forward pending revalidation paths so the client can bust its prefetch cache
797
808
  const pending = consumePendingInvalidations();
798
809
  if (pending.length > 0) {
@@ -809,7 +820,7 @@ export async function furin({
809
820
  : () => new Response(null, { status: 404 })
810
821
  )
811
822
  .use(
812
- createBrowserEventsPlugin({
823
+ (await import("./server/browser-events/plugin.ts")).createBrowserEventsPlugin({
813
824
  sources: createDevelopmentBrowserEventSources(instance, devDiagnosticStore(instance)),
814
825
  sync: sync || undefined,
815
826
  })
@@ -820,7 +831,11 @@ export async function furin({
820
831
  })
821
832
  )
822
833
  .use(createInstrumentationPlugin(() => currentSnapshot().routes, syncPath))
823
- .use(sync ? createSyncChangesPlugin(sync) : new Elysia())
834
+ .use(
835
+ sync
836
+ ? (await import("./server/sync/stream.ts")).createSyncChangesPlugin(sync)
837
+ : new Elysia()
838
+ )
824
839
  .use(
825
840
  createDataEndpoint(async (request) => {
826
841
  if (request.headers.get("x-furin-hmr-refresh") === "1") {
@@ -846,15 +861,7 @@ export async function furin({
846
861
  })
847
862
  );
848
863
  registerInstance(instance);
849
- return createFurinPlugin(devApp, (parentApp) => {
850
- parentApp.config.serve = {
851
- ...parentApp.config.serve,
852
- routes: {
853
- ...parentApp.config.serve?.routes,
854
- [hmrEntryPath]: devHtmlBundle,
855
- },
856
- };
857
- });
864
+ return createFurinPlugin(devApp);
858
865
  }
859
866
 
860
867
  // ── Production ──────────────────────────────────────────────────────────
@@ -883,7 +890,8 @@ export async function furin({
883
890
  });
884
891
 
885
892
  const embedded = ctx?.embedded;
886
- const clientDir = embedded?.clientDir ?? explicitClientDir ?? resolveClientDirFromArgv(prefix);
893
+ const clientDir =
894
+ embedded?.clientDir ?? explicitClientDir ?? ctx.clientDir ?? resolveClientDirFromArgv(prefix);
887
895
  await setupCompiledTemplate(ctx, embedded, clientDir, instance);
888
896
 
889
897
  const prodApp = new Elysia({
@@ -894,12 +902,10 @@ export async function furin({
894
902
  .use(loggerPlugin)
895
903
  // Local scope (default) — a global hook would leak onto sibling furin
896
904
  // instances mounted on the same parent app.
897
- .onError(async ({ code, request, server }) => {
898
- if (code === "NOT_FOUND") {
899
- return await renderRootNotFound(root, request, server?.url.origin);
900
- }
901
- })
902
- .onAfterHandle(({ set }) => {
905
+ .error(NotFound, async ({ request, server }) =>
906
+ renderRootNotFound(root, request, server?.url.origin)
907
+ )
908
+ .afterHandle(({ set }) => {
903
909
  // Forward pending revalidation paths so the client can bust its prefetch cache
904
910
  const pending = consumePendingInvalidations();
905
911
  if (pending.length > 0) {
@@ -910,7 +916,7 @@ export async function furin({
910
916
  set.headers["x-furin-build-id"] = instance.buildId;
911
917
  }
912
918
  })
913
- .onStart(async ({ server }) => {
919
+ .setup(async ({ server }) => {
914
920
  if (ctx.ssgCache) {
915
921
  return;
916
922
  }
@@ -919,45 +925,24 @@ export async function furin({
919
925
  // render pipeline resolves its template/caches, not a sibling's.
920
926
  await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
921
927
  })
928
+ .use(await createProductionAssetsPlugin(ctx, embedded, clientDir))
929
+ .use(await createProductionBrowserEventsPlugin(sync))
922
930
  .use(
923
- await (async () => {
924
- if (ctx.serveAssets === false) {
925
- return new Elysia();
926
- }
927
- const publicDir = embedded?.publicDir ?? join(dirname(clientDir), "public");
928
- const app = new Elysia();
929
- if (existsSync(publicDir)) {
930
- app
931
- .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
932
- .use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
933
- }
934
- app.use(
935
- await staticPlugin({
936
- assets: clientDir,
937
- headers: {
938
- "Cache-Control": "public, max-age=31536000, immutable",
939
- },
940
- prefix: "/_client",
941
- })
942
- );
943
- return app;
944
- })()
931
+ sync ? (await import("./server/sync/stream.ts")).createSyncChangesPlugin(sync) : new Elysia()
945
932
  )
946
- .use(createProductionBrowserEventsPlugin(sync))
947
- .use(sync ? createSyncChangesPlugin(sync) : new Elysia())
948
933
  .use(createDataEndpoint(routes, root))
949
934
  .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
950
935
  .use(ctx.nativeRoutes)
951
936
  .use(createNotFoundHandling(prefix, routes, root));
952
937
  registerInstance(instance);
953
- return createFurinPlugin(prodApp, undefined);
938
+ return createFurinPlugin(prodApp);
954
939
  }
955
940
 
956
941
  /**
957
942
  * 404 handling per mount position:
958
943
  *
959
- * - ROOT instance (`prefix === ""`): the historical `{as:"global"}`
960
- * onError(NOT_FOUND) hook — it owns the root scope, and a parent `.onError`
944
+ * - ROOT instance (`prefix === ""`): a global `NotFound` handler owns the root
945
+ * scope, and a parent `.error()`
961
946
  * registered BEFORE `.use(furin)` still wins (documented escape hatch for
962
947
  * JSON API 404s).
963
948
  * - PREFIXED instance: a global hook would leak onto sibling apps, and a
@@ -974,16 +959,23 @@ function createNotFoundHandling(
974
959
  tryNativeDispatch?: (context: { request: Request }) => Promise<unknown>
975
960
  ): Elysia {
976
961
  const app = new Elysia();
962
+ const dispatch =
963
+ tryNativeDispatch ??
964
+ (routes.some((route) => route.pattern === "/*")
965
+ ? async (context: { request: Request }): Promise<unknown> => {
966
+ if (context.request.method !== "GET") {
967
+ return;
968
+ }
969
+ return await dispatchNativeRoute(context as Parameters<FurinRouteDispatcher>[0]);
970
+ }
971
+ : undefined);
977
972
  if (prefix === "") {
978
- app.onError({ as: "global" }, async (context) => {
979
- if (context.code !== "NOT_FOUND") {
980
- return;
981
- }
973
+ app.error("global", NotFound, async (context) => {
982
974
  // Dev topology: the native renderer is rebuilt by the watcher on route
983
975
  // add/remove, so a hot-added route (no mounted Elysia route yet) can
984
- // still be served here. `tryNativeDispatch` is undefined in production.
985
- if (tryNativeDispatch) {
986
- const rendered = await tryNativeDispatch(context);
976
+ // still be served here. Production also renders root catch-all pages here.
977
+ if (dispatch) {
978
+ const rendered = await dispatch(context);
987
979
  if (rendered !== undefined && rendered !== null) {
988
980
  return rendered;
989
981
  }
@@ -992,17 +984,14 @@ function createNotFoundHandling(
992
984
  });
993
985
  return app;
994
986
  }
995
- if (routes.some((route) => route.pattern === "/*")) {
996
- return app;
997
- }
998
- app.get("/*", async ({ request, server }) => {
999
- if (tryNativeDispatch) {
1000
- const rendered = await tryNativeDispatch({ request });
987
+ app.get("/*", async (context) => {
988
+ if (dispatch) {
989
+ const rendered = await dispatch(context);
1001
990
  if (rendered !== undefined && rendered !== null) {
1002
991
  return rendered;
1003
992
  }
1004
993
  }
1005
- return renderRootNotFound(root, request, server?.url.origin);
994
+ return renderRootNotFound(root, context.request, context.server?.url.origin);
1006
995
  });
1007
996
  return app;
1008
997
  }
@@ -448,6 +448,7 @@ interface FixContext {
448
448
  expectedResolvedPath: string;
449
449
  filePath: string;
450
450
  hasLoader: boolean;
451
+ hasStaticParams: boolean;
451
452
  imports: LayoutImport[];
452
453
  isRootLayout: boolean;
453
454
  lastImportEnd: number;
@@ -659,6 +660,9 @@ function validateConfigProperties(
659
660
  ctx: FixContext
660
661
  ): { inferredMode: InferredRenderingMode | null; layoutValue: AstNode | null } {
661
662
  const layoutValue = properties.layout ? asAstNode(properties.layout.value) : null;
663
+ if (properties.staticParams) {
664
+ throw routeConfigError(ctx.filePath, "staticParams must be chained after config");
665
+ }
662
666
  if (!ctx.isRootLayout && properties.layout && layoutValue?.type !== "Identifier") {
663
667
  throw routeConfigError(ctx.filePath, "use a static layout route reference");
664
668
  }
@@ -670,7 +674,7 @@ function validateConfigProperties(
670
674
  ) {
671
675
  throw routeConfigError(ctx.filePath, "revalidate requires mode isr");
672
676
  }
673
- if (properties.staticParams && modeValue?.type === "Literal" && modeValue.value === "ssr") {
677
+ if (ctx.hasStaticParams && modeValue?.type === "Literal" && modeValue.value === "ssr") {
674
678
  throw routeConfigError(ctx.filePath, "staticParams requires mode ssg or isr");
675
679
  }
676
680
  if (!properties.revalidate && modeValue?.type === "Literal" && modeValue.value === "isr") {
@@ -685,7 +689,7 @@ function validateConfigProperties(
685
689
  hasRevalidate: Boolean(properties.revalidate),
686
690
  isRootLayout: ctx.isRootLayout,
687
691
  });
688
- if (properties.staticParams && inferredMode === "ssr") {
692
+ if (ctx.hasStaticParams && inferredMode === "ssr") {
689
693
  throw routeConfigError(ctx.filePath, "staticParams requires mode ssg or isr");
690
694
  }
691
695
  return { inferredMode, layoutValue };
@@ -970,6 +974,9 @@ function insertCompleteConfig(routeHead: ChainHead, ctx: FixContext): void {
970
974
  hasRevalidate: false,
971
975
  isRootLayout: ctx.isRootLayout,
972
976
  });
977
+ if (ctx.hasStaticParams && mode === "ssr") {
978
+ throw routeConfigError(ctx.filePath, "staticParams requires mode ssg or isr");
979
+ }
973
980
  entries.push(`mode: "${mode}"`);
974
981
  if (ctx.dynamicParams.length > 0) {
975
982
  const typeBoxBinding = ensureTImport(ctx);
@@ -1097,6 +1104,7 @@ export function fixRouteConfigLayout(
1097
1104
  );
1098
1105
  const bindings = collectBuilderBindings(parsed.program);
1099
1106
  const hasLoader = builderChainHasMethod(parsed.program, bindings, "loader");
1107
+ const hasStaticParams = builderChainHasMethod(parsed.program, bindings, "staticParams");
1100
1108
  const heads = collectChainHeads(parsed.program, bindings).filter(
1101
1109
  (candidate) => candidate.end !== 0
1102
1110
  );
@@ -1116,6 +1124,7 @@ export function fixRouteConfigLayout(
1116
1124
  expectedResolvedPath,
1117
1125
  filePath,
1118
1126
  hasLoader,
1127
+ hasStaticParams,
1119
1128
  imports,
1120
1129
  isRootLayout: convention.isRootLayout,
1121
1130
  lastImportEnd,