@teyik0/furin 0.9.0-alpha.1 → 0.9.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.
Files changed (85) hide show
  1. package/dist/adapter/runtime-build.d.ts +7 -3
  2. package/dist/adapter/vercel.js +31 -6
  3. package/dist/build/client.d.ts +1 -1
  4. package/dist/build/entry-template.d.ts +3 -12
  5. package/dist/build/entry-template.ts +3 -15
  6. package/dist/build/hydrate.d.ts +6 -1
  7. package/dist/build/index.d.ts +1 -1
  8. package/dist/build/index.js +565 -401
  9. package/dist/build/route-metadata.d.ts +2 -2
  10. package/dist/build/route-types.d.ts +1 -1
  11. package/dist/build/types.d.ts +10 -4
  12. package/dist/cli/index.js +594 -422
  13. package/dist/client/chunks/{client-xy6g38kx.js → client-a7spxfnn.js} +24 -5
  14. package/dist/client/chunks/{client-rjhxgt64.js → client-d9v49jwz.js} +1 -1
  15. package/dist/client/chunks/{client-k29262a4.js → client-rdxyrw11.js} +1 -1
  16. package/dist/client/define-route.d.ts +14 -0
  17. package/dist/client/internal/runtime-types.d.ts +8 -0
  18. package/dist/client/link.js +3 -3
  19. package/dist/client/router/link-utils.d.ts +3 -2
  20. package/dist/client/router/search/index.js +2 -2
  21. package/dist/client/router/types.d.ts +9 -3
  22. package/dist/client.js +22 -6
  23. package/dist/config.d.ts +4 -0
  24. package/dist/config.js +4 -1
  25. package/dist/define-route.d.ts +53 -12
  26. package/dist/furin.d.ts +13 -3
  27. package/dist/furin.js +766 -614
  28. package/dist/plugin/route-config.d.ts +3 -3
  29. package/dist/plugin/route-manifest.d.ts +46 -0
  30. package/dist/plugin/route-tree.d.ts +13 -29
  31. package/dist/routes.d.ts +2 -2
  32. package/dist/server/dev/runtime.d.ts +2 -1
  33. package/dist/server/internal.d.ts +6 -0
  34. package/dist/server/internal.js +57 -76
  35. package/dist/server/registrations.d.ts +4 -2
  36. package/dist/server/router/defined-route.d.ts +4 -0
  37. package/dist/server/router/discovery.d.ts +14 -4
  38. package/dist/server/router/hmr.d.ts +12 -12
  39. package/dist/server/router/patterns.d.ts +4 -12
  40. package/dist/server/router/types.d.ts +16 -1
  41. package/dist/server/static-export.js +88 -120
  42. package/dist/server/sync/drizzle/index.d.ts +8 -10
  43. package/dist/shared/route-specificity.d.ts +10 -1
  44. package/package.json +3 -6
  45. package/src/adapter/package.ts +11 -37
  46. package/src/adapter/runtime-build.ts +5 -4
  47. package/src/adapter/static.ts +1 -1
  48. package/src/adapter/vercel.ts +2 -1
  49. package/src/build/client.ts +3 -3
  50. package/src/build/discover-pages-process.ts +1 -1
  51. package/src/build/elysia-aot.ts +2 -2
  52. package/src/build/entry-template.ts +3 -15
  53. package/src/build/hydrate.ts +12 -6
  54. package/src/build/index.ts +19 -9
  55. package/src/build/route-metadata.ts +15 -8
  56. package/src/build/route-types.ts +18 -43
  57. package/src/build/types.ts +12 -5
  58. package/src/cli/config.ts +6 -0
  59. package/src/cli/index.ts +30 -14
  60. package/src/client/define-route.ts +29 -4
  61. package/src/client/internal/runtime-types.ts +8 -0
  62. package/src/client/router/link-utils.ts +16 -8
  63. package/src/client/router/types.ts +40 -14
  64. package/src/config.ts +5 -0
  65. package/src/define-route.ts +85 -16
  66. package/src/furin.ts +31 -7
  67. package/src/plugin/dev-routes.ts +8 -17
  68. package/src/plugin/route-config.ts +77 -62
  69. package/src/plugin/route-manifest.ts +437 -0
  70. package/src/plugin/route-modules.ts +6 -1
  71. package/src/plugin/route-registry.ts +7 -21
  72. package/src/plugin/route-tree.ts +71 -181
  73. package/src/routes.ts +2 -2
  74. package/src/server/dev/runtime.ts +16 -22
  75. package/src/server/internal.ts +4 -1
  76. package/src/server/registrations.ts +5 -2
  77. package/src/server/render/static-params.ts +2 -10
  78. package/src/server/router/defined-route.ts +8 -0
  79. package/src/server/router/discovery.ts +237 -196
  80. package/src/server/router/hmr.ts +45 -63
  81. package/src/server/router/patterns.ts +41 -117
  82. package/src/server/router/types.ts +17 -1
  83. package/src/server/sync/drizzle/index.ts +18 -19
  84. package/src/shared/route-specificity.ts +34 -2
  85. package/src/shared/utils/index.ts +1 -1
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import type { CompileContextAdapter } from "../server/internal.ts";
4
+ import type { CompileContext, CompileContextAdapter } from "../server/internal.ts";
5
5
  import type { ClientPreloadManifest } from "./preload-manifest.ts";
6
6
 
7
7
  // import.meta.resolve() runs at runtime (not inlined at bundle time), resolves
@@ -31,7 +31,7 @@ export interface EntryAppContext {
31
31
  clientLogging?: boolean;
32
32
  /** Extra lines injected inside this app's `__setCompileContext({...})` call. */
33
33
  extraContext?: string[];
34
- /** Additional route modules such as filesystem-derived `_route` layouts. */
34
+ /** Additional route modules such as filesystem-derived layouts. */
35
35
  modulePaths?: string[];
36
36
  /** Virtual module specifier exporting this app's composed Elysia route tree. */
37
37
  nativeRoutes?: string;
@@ -41,19 +41,7 @@ export interface EntryAppContext {
41
41
  preloadManifest?: ClientPreloadManifest;
42
42
  rootConventions?: { errorPath?: string; notFoundPath?: string };
43
43
  rootPath: string;
44
- routeMetadata?: Record<
45
- string,
46
- {
47
- requestKeys?: string[];
48
- requestKeysByLoader?: string[][];
49
- segmentBoundaries: Array<{
50
- depth: number;
51
- path: string;
52
- errorPath?: string;
53
- notFoundPath?: string;
54
- }>;
55
- }
56
- >;
44
+ routeMetadata?: CompileContext["routeMetadata"];
57
45
  routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
58
46
  /** In-memory production document template for filesystem-free runtimes. */
59
47
  templateHtml?: string;
@@ -1,10 +1,11 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname, join } from "node:path";
2
+ import { join } from "node:path";
3
3
  import { generateIndexHtml } from "../server/render/shell.ts";
4
4
  import {
5
5
  buildRouteRegex,
6
6
  compareRouteSpecificity,
7
7
  } from "../server/router/patterns.ts";
8
+ import type { RouteStyle } from "../plugin/route-manifest.ts";
8
9
  import type { ResolvedRoute } from "../server/router/types.ts";
9
10
  import { type BuildRouteInput, routeBuildInfo } from "./route-metadata.ts";
10
11
  import type { ClientBoundary } from "../rsc/build/discover.ts";
@@ -121,11 +122,14 @@ function hydrateEntry(
121
122
  continue;
122
123
  }
123
124
  const parts = [`depth: ${seg.depth}`];
125
+ // TanStack style: `.error()` / `.notFound()` live on the route export.
126
+ const errorExport = seg.fromRoute ? "route.errorComponent" : "default";
127
+ const notFoundExport = seg.fromRoute ? "route.notFoundComponent" : "default";
124
128
  if (errorIdent) {
125
- parts.push(`error: ${errorIdent}.default`);
129
+ parts.push(`error: ${errorIdent}.${errorExport}`);
126
130
  }
127
131
  if (notFoundIdent) {
128
- parts.push(`notFound: ${notFoundIdent}.default`);
132
+ parts.push(`notFound: ${notFoundIdent}.${notFoundExport}`);
129
133
  }
130
134
  if (seg.depth === 0 && seg.path.replaceAll("\\", "/") !== rootDirectory) {
131
135
  parts.push("isRoot: false");
@@ -491,6 +495,7 @@ if (__deferred && __deferred._chunks) {
491
495
  interface DevRouteTypesApp {
492
496
  pagesDir: string;
493
497
  routes: ResolvedRoute[];
498
+ style: RouteStyle;
494
499
  }
495
500
 
496
501
  /**
@@ -517,7 +522,7 @@ function writeDevRouteTypes(
517
522
  return writeRouteTypes(
518
523
  live.find(([appPrefix]) => appPrefix === "")?.[1].routes ?? [],
519
524
  projectRoot,
520
- live.map(([appPrefix, { pagesDir }]) => ({ pagesDir, prefix: appPrefix }))
525
+ live.map(([appPrefix, { pagesDir, style }]) => ({ pagesDir, prefix: appPrefix, style }))
521
526
  );
522
527
  }
523
528
 
@@ -536,8 +541,9 @@ export function writeDevFiles(
536
541
  basePath,
537
542
  clientLogging,
538
543
  clientBoundaries,
544
+ pages,
539
545
  prefix,
540
- }: BuildClientOptions & { prefix: string },
546
+ }: BuildClientOptions & { pages: { pagesDir: string; style: RouteStyle }; prefix: string },
541
547
  projectRoot: string,
542
548
  serverSourceVersion?: string
543
549
  ): void {
@@ -571,7 +577,7 @@ export function writeDevFiles(
571
577
  }
572
578
 
573
579
  changed =
574
- writeDevRouteTypes(projectRoot, prefix, { pagesDir: dirname(rootLayout), routes }) || changed;
580
+ writeDevRouteTypes(projectRoot, prefix, { ...pages, routes }) || changed;
575
581
 
576
582
  if (changed) {
577
583
  console.log(
@@ -10,6 +10,7 @@ import type { FurinAdapter } from "../adapter/types.ts";
10
10
  import { vercel } from "../adapter/vercel.ts";
11
11
  import { BUILD_TARGETS, type BuildTarget, type FurinTarget } from "../config";
12
12
  import { assertValidRouteConfig } from "../plugin/route-config.ts";
13
+ import type { RouteInstanceSpec } from "../plugin/route-manifest.ts";
13
14
  import { normalizePrefix } from "../server/instance.ts";
14
15
  import { assertNoPrefixSlugCollisions, assertOnePagesDirPerMount } from "../shared/prefix.ts";
15
16
  import { withProductionBuild } from "../shared/production-build.ts";
@@ -65,14 +66,13 @@ const BUILD_OUTPUT_DIR = ".furin/build";
65
66
  * Resolves the list of apps to build, in priority order:
66
67
  * 1. explicit `apps` config (furin.config.ts),
67
68
  * 2. explicit single `pagesDir` option (mounted at root),
68
- * 3. every `furin({ pagesDir, prefix })` call made by evaluating the server entry,
69
- * 4. the `src/pages` default.
69
+ * 3. every `furin({ pagesDir, prefix, style })` call made by evaluating the server entry.
70
70
  */
71
71
  async function resolveAppSpecs(
72
72
  options: RouteTypegenOptions,
73
73
  serverEntry: string | null,
74
74
  rootDir: string
75
- ): Promise<Array<{ pagesDir: string; prefix: string }>> {
75
+ ): Promise<RouteInstanceSpec[]> {
76
76
  if (options.apps && options.apps.length > 0) {
77
77
  // normalizePrefix is the choke point for config/CLI-provided prefixes:
78
78
  // `"/"` → `""` (otherwise the bun target derives `publicPath: "//_client/"`,
@@ -81,21 +81,22 @@ async function resolveAppSpecs(
81
81
  return options.apps.map((app) => ({
82
82
  pagesDir: resolve(rootDir, app.pagesDir),
83
83
  prefix: normalizePrefix(app.prefix),
84
+ style: app.style,
84
85
  }));
85
86
  }
86
- if (options.pagesDir) {
87
- return [{ pagesDir: resolve(rootDir, options.pagesDir), prefix: "" }];
88
- }
89
87
  if (serverEntry) {
90
88
  const mounted = await discoverFurinMounts(serverEntry, rootDir);
91
89
  if (mounted.length > 0) {
92
90
  return mounted.map((app) => ({
93
91
  pagesDir: resolve(rootDir, app.pagesDir),
94
92
  prefix: app.prefix,
93
+ style: app.style,
95
94
  }));
96
95
  }
97
96
  }
98
- return [{ pagesDir: resolve(rootDir, "src/pages"), prefix: "" }];
97
+ throw new Error(
98
+ `[furin] No app to build: ${serverEntry ? `${toPosixPath(relative(rootDir, serverEntry))} mounts no furin() plugin` : "no server entry found"}. Mount furin({ style }) in the server entry, or list the apps in furin.config.ts: apps: [{ pagesDir: "src/routes", style: "tanstack" }].`
99
+ );
99
100
  }
100
101
 
101
102
  /**
@@ -136,7 +137,7 @@ function writeAppRouteTypes(apps: RuntimeTargetApp[], rootDir: string): void {
136
137
  /** Options for `generateRouteTypes()`, a subset of the build options. */
137
138
  export type RouteTypegenOptions = Pick<
138
139
  BuildAppOptions,
139
- "apps" | "pagesDir" | "plugins" | "rootDir" | "serverEntry"
140
+ "apps" | "plugins" | "rootDir" | "serverEntry"
140
141
  >;
141
142
 
142
143
  /**
@@ -156,6 +157,11 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
156
157
  return withProductionBuild(() => buildAppInternal(options));
157
158
  }
158
159
 
160
+ function existingServerEntry(options: BuildAppOptions, rootDir: string): string | null {
161
+ const entry = resolve(rootDir, options.serverEntry ?? "src/server.ts");
162
+ return existsSync(entry) ? entry : null;
163
+ }
164
+
159
165
  async function buildAppInternal(options: BuildAppOptions): Promise<BuildAppResult> {
160
166
  const rootDir = resolve(options.rootDir ?? process.cwd());
161
167
  const buildRoot = join(rootDir, BUILD_OUTPUT_DIR);
@@ -179,7 +185,10 @@ async function buildAppInternal(options: BuildAppOptions): Promise<BuildAppResul
179
185
  return entry;
180
186
  })();
181
187
 
182
- const apps = await scanApps(options, serverEntry, rootDir);
188
+ // Serverless targets bundle no server entry, but its furin({ style }) mounts
189
+ // still name the apps to build when config `apps` does not.
190
+ const mountEntry = serverEntry ?? existingServerEntry(options, rootDir);
191
+ const apps = await scanApps(options, mountEntry, rootDir);
183
192
  // furin-env.d.ts is one file at the project root, owned by the root-mounted
184
193
  // app — the same rule as the dev server, so builds keep types current too.
185
194
  writeAppRouteTypes(apps, rootDir);
@@ -199,6 +208,7 @@ async function buildAppInternal(options: BuildAppOptions): Promise<BuildAppResul
199
208
  apps: apps.map((app) => ({
200
209
  pagesDir: toPosixPath(relative(rootDir, app.pagesDir)),
201
210
  prefix: app.prefix,
211
+ style: app.style,
202
212
  routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
203
213
  })),
204
214
  targets: {},
@@ -25,11 +25,14 @@ interface RouteBuildInfo {
25
25
  export interface BuildRoute
26
26
  extends Pick<
27
27
  ResolvedRoute,
28
- "mode" | "path" | "pattern" | "requestKeys" | "requestKeysByLoader" | "tags"
28
+ "layouts" | "mode" | "path" | "pattern" | "requestKeys" | "requestKeysByLoader" | "tags"
29
29
  > {
30
30
  build: RouteBuildInfo;
31
31
  routeChain: { layout: boolean; sourcePath?: string }[];
32
- segmentBoundaries: Pick<SegmentBoundary, "depth" | "path" | "errorPath" | "notFoundPath">[];
32
+ segmentBoundaries: Pick<
33
+ SegmentBoundary,
34
+ "depth" | "path" | "errorPath" | "fromRoute" | "notFoundPath"
35
+ >[];
33
36
  }
34
37
 
35
38
  export type BuildRouteInput = BuildRoute | ResolvedRoute;
@@ -70,6 +73,7 @@ export function routeBuildInfo(route: BuildRouteInput): RouteBuildInfo {
70
73
  export function buildRouteMetadata(route: ResolvedRoute): BuildRoute {
71
74
  return {
72
75
  build: routeBuildInfo(route),
76
+ layouts: route.layouts,
73
77
  mode: route.mode,
74
78
  path: route.path,
75
79
  pattern: route.pattern,
@@ -79,12 +83,15 @@ export function buildRouteMetadata(route: ResolvedRoute): BuildRoute {
79
83
  layout: !!entry.layout,
80
84
  sourcePath: entry.sourcePath,
81
85
  })),
82
- segmentBoundaries: route.segmentBoundaries.map(({ depth, path, errorPath, notFoundPath }) => ({
83
- depth,
84
- path,
85
- errorPath,
86
- notFoundPath,
87
- })),
86
+ segmentBoundaries: route.segmentBoundaries.map(
87
+ ({ depth, path, errorPath, fromRoute, notFoundPath }) => ({
88
+ depth,
89
+ path,
90
+ errorPath,
91
+ ...(fromRoute ? { fromRoute } : {}),
92
+ notFoundPath,
93
+ })
94
+ ),
88
95
  tags: route.tags,
89
96
  };
90
97
  }
@@ -1,7 +1,6 @@
1
1
  import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { extname, join, relative, resolve } from "node:path";
3
- import { fileRouteId, type RouteInstanceSpec, routeSourcePaths } from "../plugin/route-tree.ts";
4
- import { filePathToPattern, parseDynamicRouteSegment } from "../server/router/patterns.ts";
3
+ import { type RouteInstanceSpec, scanRouteManifest } from "../plugin/route-manifest.ts";
5
4
  import type { ResolvedRoute } from "../server/router/types.ts";
6
5
  import { compareCodeUnits, routeMapDeclaration, type RouteMapEntry } from "../shared/route-map.ts";
7
6
 
@@ -22,55 +21,31 @@ function importSpecifier(path: string, projectRoot: string): string {
22
21
  }
23
22
 
24
23
  /**
25
- * One `FileRoutes` entry per page and `_route` layout of an app, keyed by the
26
- * app's prefix and its path under `pagesDir` (brackets and groups kept,
27
- * `/index` dropped). Read from the tree alone, so the entries stay right while
28
- * a route module is broken.
24
+ * One `FileRoutes` entry per page and layout of an app, keyed by its
25
+ * TanStack Start id (the app's prefix included). Read from the route
26
+ * manifest alone, so the entries stay right while a route module is broken.
29
27
  */
30
28
  function fileRouteEntries(
31
- { pagesDir, prefix }: RouteInstanceSpec,
29
+ instance: RouteInstanceSpec,
32
30
  projectRoot: string
33
31
  ): { id: string; lines: string }[] {
34
- const pages = resolve(pagesDir);
35
- const files = routeSourcePaths({ pagesDir: pages, prefix }).map((path) => {
36
- const relativePath = relative(pages, path).replaceAll("\\", "/");
37
- const segments = relativePath.split("/");
38
- const base = (segments.pop() ?? "").slice(0, -extname(path).length);
39
- return { base, path, relativePath, segments };
40
- });
41
- const layouts = new Map(
42
- files.filter(({ base }) => base === "_route").map((file) => [file.segments.join("/"), file.path])
43
- );
44
- return files
45
- .map(({ base, path, relativePath, segments }) => {
46
- const isLayout = base === "_route";
47
- // Nearest `_route` in an enclosing directory, as discovery resolves it.
48
- let parent = join(pages, "root.tsx");
49
- for (let depth = isLayout ? segments.length - 1 : segments.length; depth > 0; depth -= 1) {
50
- const layout = layouts.get(segments.slice(0, depth).join("/"));
51
- if (layout) {
52
- parent = layout;
53
- break;
54
- }
55
- }
56
- const pathParams = [...segments, base].flatMap((segment) => {
57
- const dynamic = parseDynamicRouteSegment(segment, path);
58
- return dynamic ? [dynamic.catchAll ? '"*": string' : `${dynamic.name}: string`] : [];
59
- });
60
- const id = fileRouteId({ pagesDir: pages, prefix }, path);
61
- const pattern = filePathToPattern(
62
- isLayout ? segments.concat("index").join("/") : relativePath
63
- );
64
- return {
65
- id,
66
- lines: ` ${JSON.stringify(id)}: {
67
- kind: "${isLayout ? "layout" : "page"}";
32
+ const { prefix } = instance;
33
+ const manifest = scanRouteManifest({ ...instance, pagesDir: resolve(instance.pagesDir) });
34
+ return manifest.routes.map(({ id, kind, params, parentPath, pattern }) => {
35
+ const parent = parentPath ?? manifest.rootPath;
36
+ const pathParams = params.map(
37
+ ({ name, optional }) => `${name}${optional ? "?" : ""}: string`
38
+ );
39
+ return {
40
+ id,
41
+ lines: ` ${JSON.stringify(id)}: {
42
+ kind: "${kind}";
68
43
  pattern: ${JSON.stringify(`${prefix}${pattern === "/" ? "" : pattern}` || "/")};
69
44
  parent: typeof import(${JSON.stringify(importSpecifier(parent, projectRoot))}).route;
70
45
  pathParams: {${pathParams.length > 0 ? ` ${pathParams.join("; ")} ` : ""}};
71
46
  };`,
72
- };
73
- });
47
+ };
48
+ });
74
49
  }
75
50
 
76
51
  function fileRoutesDeclaration(apps: readonly RouteInstanceSpec[], projectRoot: string): string {
@@ -1,5 +1,6 @@
1
1
  import type { AdapterTargetManifest } from "../adapter/types.ts";
2
2
  import type { FurinTarget, StaticExportConfig } from "../config";
3
+ import type { RouteStyle } from "../plugin/route-manifest.ts";
3
4
  import type { RouteRegistrySnapshot } from "../plugin/route-registry.ts";
4
5
  import type { ResolvedRoute } from "../server/router/types.ts";
5
6
  import type { ClientBoundary } from "../rsc/build/discover.ts";
@@ -27,7 +28,8 @@ export interface BuildClientOptions {
27
28
  /** Package barrels Bun should parse on demand instead of loading in full. */
28
29
  optimizeImports?: string[];
29
30
  outDir: string;
30
- pagesDir?: string;
31
+ /** The app whose route registry the client bundle embeds. */
32
+ pages?: { pagesDir: string; style: RouteStyle };
31
33
  plugins?: Bun.BunPlugin[];
32
34
  /** Record route chunks in the preload manifest. Defaults to true. */
33
35
  preloadRouteChunks?: boolean;
@@ -83,11 +85,17 @@ interface BuildAppSpec {
83
85
  pagesDir: string;
84
86
  /** Mount prefix (`""` or absent = root). */
85
87
  prefix?: string;
88
+ style: RouteStyle;
86
89
  }
87
90
 
88
91
  export interface BuildManifest {
89
92
  /** Every mounted app built into this artifact (multi-instance). */
90
- apps?: Array<{ pagesDir: string; prefix: string; routes: BuildRouteManifestEntry[] }>;
93
+ apps?: Array<{
94
+ pagesDir: string;
95
+ prefix: string;
96
+ routes: BuildRouteManifestEntry[];
97
+ style: RouteStyle;
98
+ }>;
91
99
  generatedAt: string;
92
100
  pagesDir: string;
93
101
  rootDir: string;
@@ -105,8 +113,8 @@ export interface BuildAppOptions {
105
113
  /** Bun emits a listening server unless output is explicitly "app". */
106
114
  bun?: { output?: "app" | "server" };
107
115
  /**
108
- * Explicit multi-app build (furin.config.ts `apps`). Overrides `pagesDir`
109
- * and the mounts found by evaluating the server entry.
116
+ * Explicit multi-app build (furin.config.ts `apps`). Overrides the mounts
117
+ * found by evaluating the server entry.
110
118
  */
111
119
  apps?: BuildAppSpec[];
112
120
  /** Inject the evlog client logger into the hydrate entry. Defaults to false. */
@@ -114,7 +122,6 @@ export interface BuildAppOptions {
114
122
  compile?: "server" | "embed";
115
123
  /** Package barrels Bun should parse on demand in production client bundles. */
116
124
  optimizeImports?: string[];
117
- pagesDir?: string;
118
125
  plugins?: Bun.BunPlugin[];
119
126
  /** Module preloading (furin.config.ts `preload`). */
120
127
  preload?: { routeChunks?: boolean };
package/src/cli/config.ts CHANGED
@@ -191,6 +191,12 @@ export async function loadCliConfig(
191
191
  );
192
192
  }
193
193
 
194
+ if (configToValidate.pagesDir !== undefined && configToValidate.style === undefined) {
195
+ throw new Error(
196
+ `[furin] Invalid config at ${configPath}: pagesDir needs its file-routing style: add style: "nextjs" or "tanstack".`
197
+ );
198
+ }
199
+
194
200
  const resolvedRootDir = resolve(rootDir, configToValidate.rootDir ?? ".");
195
201
  return {
196
202
  ...configToValidate,
package/src/cli/index.ts CHANGED
@@ -4,6 +4,7 @@ import { resolve } from "node:path";
4
4
  import { parseArgs } from "node:util";
5
5
  import { buildApp, generateRouteTypes } from "../build/index.ts";
6
6
  import { BUILD_TARGETS, type FurinTarget } from "../config.ts";
7
+ import type { RouteStyle } from "../plugin/route-manifest.ts";
7
8
  import { normalizePrefix } from "../server/instance.ts";
8
9
  import { loadCliConfig } from "./config.ts";
9
10
  import { runDevelopment } from "./dev.ts";
@@ -21,6 +22,23 @@ function bail(msg: string): never {
21
22
  process.exit(1);
22
23
  }
23
24
 
25
+ /** `--pagesDir` / config `pagesDir` builds one explicit app, which needs its routing style. */
26
+ function singleApp(
27
+ pagesDir: string | undefined,
28
+ style: string | undefined,
29
+ prefix: string | undefined
30
+ ): [{ pagesDir: string; prefix: string; style: RouteStyle }] | undefined {
31
+ if (!pagesDir) {
32
+ return;
33
+ }
34
+ if (style !== "nextjs" && style !== "tanstack") {
35
+ bail(
36
+ `pagesDir ${pagesDir} needs its file-routing style: pass --style nextjs|tanstack or set \`style\` in furin.config.ts.`
37
+ );
38
+ }
39
+ return [{ pagesDir, prefix: normalizePrefix(prefix), style }];
40
+ }
41
+
24
42
  function resolveCompileMode(
25
43
  flag: string | boolean | undefined,
26
44
  configCompile: "server" | "embed" | undefined
@@ -127,6 +145,7 @@ if (command === "dev") {
127
145
  output: { type: "string" },
128
146
  pagesDir: { type: "string" },
129
147
  prefix: { type: "string" },
148
+ style: { type: "string" },
130
149
  target: { type: "string" },
131
150
  },
132
151
  strict: true,
@@ -142,6 +161,7 @@ if (command === "dev") {
142
161
  target?: string;
143
162
  pagesDir?: string;
144
163
  prefix?: string;
164
+ style?: string;
145
165
  config?: string;
146
166
  };
147
167
 
@@ -194,18 +214,11 @@ if (command === "dev") {
194
214
  // normalizePrefix here so a bad --prefix fails before buildApp starts
195
215
  // (resolveAppSpecs normalizes config-provided prefixes the same way).
196
216
  apps:
197
- (values.pagesDir ?? config.pagesDir)
198
- ? [
199
- {
200
- pagesDir: values.pagesDir ?? (config.pagesDir as string),
201
- prefix: normalizePrefix(values.prefix),
202
- },
203
- ]
204
- : config.apps,
217
+ singleApp(values.pagesDir ?? config.pagesDir, values.style ?? config.style, values.prefix) ??
218
+ config.apps,
205
219
  clientLogging: config.clientLogging ?? false,
206
220
  compile: resolveCompileMode(compileFlag, config.bun?.compile),
207
221
  optimizeImports: config.optimizeImports,
208
- pagesDir: undefined,
209
222
  plugins: config.plugins,
210
223
  serverExternalPackages: values.external,
211
224
  preload: config.preload,
@@ -227,6 +240,7 @@ if (command === "dev") {
227
240
  options: {
228
241
  config: { type: "string" },
229
242
  pagesDir: { type: "string" },
243
+ style: { type: "string" },
230
244
  },
231
245
  strict: true,
232
246
  }).values;
@@ -234,12 +248,12 @@ if (command === "dev") {
234
248
  bail(error instanceof Error ? error.message : String(error));
235
249
  }
236
250
 
237
- const values = rawValues as { config?: string; pagesDir?: string };
251
+ const values = rawValues as { config?: string; pagesDir?: string; style?: string };
238
252
  const config = await loadCliConfig(process.cwd(), values.config);
239
- const pagesDir = values.pagesDir ?? config.pagesDir;
240
253
  await generateRouteTypes({
241
- apps: pagesDir ? [{ pagesDir, prefix: "" }] : config.apps,
242
- pagesDir: undefined,
254
+ apps:
255
+ singleApp(values.pagesDir ?? config.pagesDir, values.style ?? config.style, undefined) ??
256
+ config.apps,
243
257
  plugins: config.plugins,
244
258
  rootDir: config.rootDir,
245
259
  serverEntry: config.serverEntry,
@@ -259,6 +273,7 @@ BUILD OPTIONS
259
273
  --target ${BUILD_TARGETS.join(" | ")} | all (default: bun)
260
274
  "package" builds a publishable Elysia-plugin artifact (register.js + factory + client assets)
261
275
  --pagesDir Pages directory
276
+ --style File-routing style of --pagesDir: nextjs or tanstack
262
277
  --prefix Mount prefix for the built app (e.g. /admin) — pairs with --pagesDir
263
278
  --config Config file path
264
279
  --compile server | embed Compile to binary: "server" keeps client on disk, "embed" is self-contained
@@ -268,7 +283,8 @@ BUILD OPTIONS
268
283
 
269
284
  TYPEGEN OPTIONS
270
285
  Writes furin-env.d.ts for every mounted app (run it before tsc in CI)
271
- --pagesDir Pages directory (default: config apps, server entry furin() mounts, then src/pages)
286
+ --pagesDir Pages directory (default: config pagesDir, config apps, then the server entry's furin() mounts)
287
+ --style File-routing style of --pagesDir: nextjs or tanstack
272
288
  --config Config file path
273
289
 
274
290
  PREVIEW OPTIONS
@@ -1,3 +1,5 @@
1
+ import type { ErrorComponent } from "../shared/error.ts";
2
+ import type { NotFoundComponent } from "../shared/not-found.ts";
1
3
  import type { RemountDeps } from "../shared/page-key.ts";
2
4
 
3
5
  type ClientComponent = (props: never) => React.ReactNode;
@@ -12,24 +14,41 @@ interface ClientRuntimeProps {
12
14
 
13
15
  type ClientRuntimeComponent = (props: ClientRuntimeProps) => React.ReactNode;
14
16
 
15
- function createRouteBuilder(remountDeps: RemountDeps<never, never> | undefined) {
17
+ interface ClientBuilderState {
18
+ errorComponent: ErrorComponent | undefined;
19
+ notFoundComponent: NotFoundComponent | undefined;
20
+ remountDeps: RemountDeps<never, never> | undefined;
21
+ }
22
+
23
+ function createRouteBuilder(state: ClientBuilderState) {
24
+ const { errorComponent, notFoundComponent, remountDeps } = state;
16
25
  return {
17
26
  config(options: { remountDeps?: RemountDeps<never, never> }) {
18
- return createRouteBuilder(options.remountDeps);
27
+ return createRouteBuilder({ ...state, remountDeps: options.remountDeps });
28
+ },
29
+ error(component: ErrorComponent) {
30
+ return createRouteBuilder({ ...state, errorComponent: component });
19
31
  },
20
32
  layout<Component extends ClientComponent>(component: Component) {
21
33
  const runtimeComponent = component as unknown as ClientRuntimeComponent;
22
34
  return {
23
35
  __type: "FURIN_ROUTE" as const,
24
36
  component: runtimeComponent,
37
+ errorComponent,
25
38
  layout: runtimeComponent,
39
+ notFoundComponent,
26
40
  };
27
41
  },
42
+ notFound(component: NotFoundComponent) {
43
+ return createRouteBuilder({ ...state, notFoundComponent: component });
44
+ },
28
45
  page<Component extends ClientComponent>(component: Component) {
29
46
  const runtimeComponent = component as unknown as ClientRuntimeComponent;
30
47
  return {
31
48
  __type: "FURIN_ROUTE" as const,
32
49
  component: runtimeComponent,
50
+ errorComponent,
51
+ notFoundComponent,
33
52
  page: runtimeComponent,
34
53
  remountDeps,
35
54
  };
@@ -37,12 +56,18 @@ function createRouteBuilder(remountDeps: RemountDeps<never, never> | undefined)
37
56
  };
38
57
  }
39
58
 
59
+ const EMPTY_BUILDER: ClientBuilderState = {
60
+ errorComponent: undefined,
61
+ notFoundComponent: undefined,
62
+ remountDeps: undefined,
63
+ };
64
+
40
65
  /** The file id of `defineRoute(id)` is type-only: the client ignores it. */
41
66
  export function defineRoute(_id: string) {
42
- return createRouteBuilder(undefined);
67
+ return createRouteBuilder(EMPTY_BUILDER);
43
68
  }
44
69
 
45
70
  /** Client stub for the root-layout builder — identical surface. */
46
71
  export function defineRootRoute() {
47
- return createRouteBuilder(undefined);
72
+ return createRouteBuilder(EMPTY_BUILDER);
48
73
  }
@@ -1,6 +1,8 @@
1
1
  import type React from "react";
2
2
  import type { HeadOptions, RenderingMode } from "../../client.ts";
3
3
  import type { RequestLoaderContext } from "../../define-route.ts";
4
+ import type { ErrorComponent } from "../../shared/error.ts";
5
+ import type { NotFoundComponent } from "../../shared/not-found.ts";
4
6
  import type { RemountDeps } from "../../shared/page-key.ts";
5
7
 
6
8
  /**
@@ -23,9 +25,13 @@ export type RuntimeStaticParams = (
23
25
 
24
26
  export interface RuntimeRoute {
25
27
  __type: "FURIN_ROUTE";
28
+ /** TanStack style: `.error()` of the route. */
29
+ errorComponent?: ErrorComponent;
26
30
  layout?: React.FC<RuntimeData & { children: React.ReactNode }>;
27
31
  loader?: (ctx: RuntimeData) => Awaitable<RuntimeData>;
28
32
  mode?: RenderingMode;
33
+ /** TanStack style: `.notFound()` of the route. */
34
+ notFoundComponent?: NotFoundComponent;
29
35
  params?: unknown;
30
36
  parent?: RuntimeRoute;
31
37
  query?: unknown;
@@ -41,9 +47,11 @@ export interface RuntimePage {
41
47
  __type: "FURIN_PAGE";
42
48
  _route: RuntimeRoute;
43
49
  component: React.FC<RuntimeData>;
50
+ errorComponent?: ErrorComponent;
44
51
  head?: (ctx: RuntimeData) => HeadOptions;
45
52
  loader?: (ctx: RuntimeData) => Awaitable<RuntimeData>;
46
53
  mode?: RenderingMode;
54
+ notFoundComponent?: NotFoundComponent;
47
55
  revalidate?: number;
48
56
  staticParams?: RuntimeStaticParams;
49
57
  tags?: string[];
@@ -77,8 +77,9 @@ export function isSameOriginFetchResult(
77
77
 
78
78
  /**
79
79
  * Substitutes typed path params into a route pattern: `/board/:boardId` with
80
- * `{ boardId: 42 }` → `/board/42`. The `*` wildcard segment (catch-all) is
81
- * replaced from `params["*"]`. Unknown segments are left untouched so
80
+ * `{ boardId: 42 }` → `/board/42`. An optional `/:lang?` segment is dropped
81
+ * when its param is absent. The `*` wildcard segment (catch-all) is
82
+ * replaced from `params._splat`. Unknown segments are left untouched so
82
83
  * partially-applied patterns stay visible.
83
84
  *
84
85
  * @internal Exported for unit testing only.
@@ -87,13 +88,20 @@ export function applyLinkParams(
87
88
  to: string,
88
89
  params: Record<string, string | number> | null | undefined
89
90
  ): string {
90
- if (!params) {
91
- return to;
91
+ const values = params ?? {};
92
+ let url = to
93
+ .replaceAll(/\/:([a-zA-Z0-9_]+)\?(?=\/|$)/g, (_match: string, name: string) =>
94
+ values[name] === undefined || values[name] === ""
95
+ ? ""
96
+ : `/${encodeURIComponent(String(values[name]))}`
97
+ )
98
+ .replaceAll(/:([a-zA-Z0-9_]+)/g, (match: string, name: string) =>
99
+ name in values ? encodeURIComponent(String(values[name])) : match
100
+ );
101
+ if (url === "") {
102
+ url = "/";
92
103
  }
93
- let url = to.replaceAll(/:([a-zA-Z0-9_]+)/g, (match: string, name: string) =>
94
- name in params ? encodeURIComponent(String(params[name])) : match
95
- );
96
- const wildcard: string | number | undefined = params["*"];
104
+ const wildcard: string | number | undefined = values._splat;
97
105
  if (wildcard !== undefined && url.includes("/*")) {
98
106
  const encodedWildcard = String(wildcard).split("/").map(encodeURIComponent).join("/");
99
107
  url = url.replace("/*", () => `/${encodedWildcard}`);