@teyik0/furin 0.9.0-alpha.0 → 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 (100) hide show
  1. package/README.md +1 -1
  2. package/dist/adapter/runtime-build.d.ts +7 -3
  3. package/dist/adapter/vercel.js +31 -6
  4. package/dist/build/client.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -12
  6. package/dist/build/entry-template.ts +3 -15
  7. package/dist/build/hydrate.d.ts +6 -1
  8. package/dist/build/index.d.ts +1 -1
  9. package/dist/build/index.js +565 -401
  10. package/dist/build/route-metadata.d.ts +2 -2
  11. package/dist/build/route-types.d.ts +1 -1
  12. package/dist/build/types.d.ts +10 -4
  13. package/dist/cli/dev-worker.ts +10 -4
  14. package/dist/cli/index.js +624 -445
  15. package/dist/client/chunks/{client-xy6g38kx.js → client-a7spxfnn.js} +24 -5
  16. package/dist/client/chunks/{client-rjhxgt64.js → client-d9v49jwz.js} +1 -1
  17. package/dist/client/chunks/{client-k29262a4.js → client-rdxyrw11.js} +1 -1
  18. package/dist/client/define-route.d.ts +14 -0
  19. package/dist/client/internal/runtime-types.d.ts +8 -0
  20. package/dist/client/link.js +20 -17
  21. package/dist/client/router/link-utils.d.ts +3 -2
  22. package/dist/client/router/search/index.js +2 -2
  23. package/dist/client/router/types.d.ts +9 -3
  24. package/dist/client.js +22 -6
  25. package/dist/config.d.ts +4 -0
  26. package/dist/config.js +4 -1
  27. package/dist/define-route.d.ts +53 -12
  28. package/dist/furin.d.ts +13 -3
  29. package/dist/furin.js +815 -661
  30. package/dist/plugin/route-config.d.ts +3 -3
  31. package/dist/plugin/route-manifest.d.ts +46 -0
  32. package/dist/plugin/route-tree.d.ts +13 -29
  33. package/dist/routes.d.ts +2 -2
  34. package/dist/server/dev/runtime.d.ts +2 -1
  35. package/dist/server/internal.d.ts +6 -0
  36. package/dist/server/internal.js +97 -114
  37. package/dist/server/registrations.d.ts +4 -2
  38. package/dist/server/render/index.d.ts +0 -1
  39. package/dist/server/render/index.ts +0 -1
  40. package/dist/server/render/shell.d.ts +1 -13
  41. package/dist/server/render/shell.ts +1 -90
  42. package/dist/server/router/defined-route.d.ts +4 -0
  43. package/dist/server/router/discovery.d.ts +14 -4
  44. package/dist/server/router/hmr.d.ts +12 -12
  45. package/dist/server/router/patterns.d.ts +4 -12
  46. package/dist/server/router/types.d.ts +16 -1
  47. package/dist/server/static-export.js +128 -158
  48. package/dist/server/sync/drizzle/index.d.ts +8 -10
  49. package/dist/shared/not-found.d.ts +1 -1
  50. package/dist/shared/route-specificity.d.ts +10 -1
  51. package/package.json +8 -11
  52. package/src/adapter/package.ts +11 -37
  53. package/src/adapter/runtime-build.ts +5 -4
  54. package/src/adapter/static.ts +1 -1
  55. package/src/adapter/vercel.ts +2 -1
  56. package/src/build/client.ts +3 -3
  57. package/src/build/discover-pages-process.ts +1 -1
  58. package/src/build/elysia-aot.ts +2 -2
  59. package/src/build/entry-template.ts +3 -15
  60. package/src/build/hydrate.ts +12 -6
  61. package/src/build/index.ts +19 -9
  62. package/src/build/route-metadata.ts +15 -8
  63. package/src/build/route-types.ts +18 -43
  64. package/src/build/types.ts +12 -5
  65. package/src/cli/config.ts +6 -0
  66. package/src/cli/dev-worker.ts +10 -4
  67. package/src/cli/dev.ts +41 -26
  68. package/src/cli/index.ts +30 -14
  69. package/src/client/define-route.ts +29 -4
  70. package/src/client/internal/runtime-types.ts +8 -0
  71. package/src/client/link.tsx +21 -22
  72. package/src/client/router/context.ts +8 -7
  73. package/src/client/router/link-utils.ts +16 -8
  74. package/src/client/router/provider.tsx +5 -0
  75. package/src/client/router/types.ts +40 -14
  76. package/src/config.ts +5 -0
  77. package/src/define-route.ts +85 -16
  78. package/src/furin.ts +31 -7
  79. package/src/plugin/dev-routes.ts +8 -17
  80. package/src/plugin/route-config.ts +77 -62
  81. package/src/plugin/route-manifest.ts +437 -0
  82. package/src/plugin/route-modules.ts +6 -1
  83. package/src/plugin/route-registry.ts +7 -21
  84. package/src/plugin/route-tree.ts +71 -181
  85. package/src/routes.ts +2 -2
  86. package/src/server/dev/runtime.ts +16 -22
  87. package/src/server/internal.ts +4 -1
  88. package/src/server/registrations.ts +5 -2
  89. package/src/server/render/index.ts +0 -1
  90. package/src/server/render/shell.ts +1 -90
  91. package/src/server/render/static-params.ts +2 -10
  92. package/src/server/router/defined-route.ts +8 -0
  93. package/src/server/router/discovery.ts +237 -196
  94. package/src/server/router/hmr.ts +45 -63
  95. package/src/server/router/patterns.ts +41 -117
  96. package/src/server/router/types.ts +17 -1
  97. package/src/server/sync/drizzle/index.ts +18 -19
  98. package/src/shared/not-found.ts +1 -1
  99. package/src/shared/route-specificity.ts +34 -2
  100. package/src/shared/utils/index.ts +1 -1
@@ -62,10 +62,16 @@ const timer = setTimeout(() => {
62
62
  }, 30_000);
63
63
  try {
64
64
  if (integration) {
65
- const addon: { createWebDevelopment: () => WebDevelopment } = await import(
66
- pathToFileURL(integration).href
67
- );
68
- web = addon.createWebDevelopment();
65
+ const addon: {
66
+ createDevelopment?: () => WebDevelopment;
67
+ createWebDevelopment?: () => WebDevelopment;
68
+ } = await import(pathToFileURL(integration).href);
69
+ // Desktop integrations export createDevelopment; web-dev keeps its published name.
70
+ const create = addon.createDevelopment ?? addon.createWebDevelopment;
71
+ if (!create) {
72
+ throw new Error("Invalid development integration.");
73
+ }
74
+ web = create();
69
75
  }
70
76
  const { listen } = BunAdapter;
71
77
  if (!listen) {
package/src/cli/dev.ts CHANGED
@@ -5,6 +5,36 @@ import { loadCliConfig } from "./config";
5
5
 
6
6
  const PORT = /^\d+$/;
7
7
 
8
+ /** The hot worker serves the backend; the desktop integration owns the native shell. */
9
+ async function desktopIntegration(cwd: string, openBrowser: boolean) {
10
+ let entry: string;
11
+ let integration: string;
12
+ try {
13
+ entry = Bun.resolveSync("@teyik0/furin-electrobun/dev", cwd);
14
+ integration = Bun.resolveSync("@teyik0/furin-electrobun/desktop-dev", cwd);
15
+ } catch (cause) {
16
+ throw new Error("Install @teyik0/furin-electrobun to run this desktop configuration.", {
17
+ cause,
18
+ });
19
+ }
20
+ const addon: {
21
+ prepareDesktopDevelopment: (
22
+ cwd: string,
23
+ openBrowser: boolean
24
+ ) => Promise<{ [name: string]: string }>;
25
+ } = await import(pathToFileURL(entry).href);
26
+ return { integration, env: await addon.prepareDesktopDevelopment(cwd, openBrowser) };
27
+ }
28
+
29
+ function webIntegration(cwd: string): { integration: string; env: { [name: string]: string } } {
30
+ try {
31
+ return { integration: Bun.resolveSync("@teyik0/furin-electrobun/web-dev", cwd), env: {} };
32
+ } catch {
33
+ // Web-only apps can run without the optional desktop integration installed.
34
+ return { integration: "", env: {} };
35
+ }
36
+ }
37
+
8
38
  export async function runDevelopment(cwd: string, args: string[]): Promise<void> {
9
39
  const { values } = parseArgs({
10
40
  args: args.filter((arg) => arg !== "--"),
@@ -16,36 +46,20 @@ export async function runDevelopment(cwd: string, args: string[]): Promise<void>
16
46
  }
17
47
  const config = await loadCliConfig(cwd);
18
48
  const hasDesktop = config.desktop !== undefined;
19
- if (hasDesktop && !values.web) {
20
- if (values.port !== undefined) {
21
- throw new Error("--port is only available with --web.");
22
- }
23
- let entry: string;
24
- try {
25
- entry = Bun.resolveSync("@teyik0/furin-electrobun/dev", cwd);
26
- } catch (cause) {
27
- throw new Error("Install @teyik0/furin-electrobun to run this desktop configuration.", {
28
- cause,
29
- });
30
- }
31
- const addon: { runDesktopDevelopment: (cwd: string, openBrowser: boolean) => Promise<void> } =
32
- await import(pathToFileURL(entry).href);
33
- await addon.runDesktopDevelopment(cwd, !values.desktop);
34
- return;
35
- }
36
- if (values.desktop) {
49
+ if (values.desktop && !hasDesktop) {
37
50
  throw new Error("Add desktop to furin.config.ts before using --desktop.");
38
51
  }
39
- const port = values.port ?? process.env.PORT;
52
+ const desktop = hasDesktop && !values.web;
53
+ if (desktop && values.port !== undefined) {
54
+ throw new Error("--port is only available with --web.");
55
+ }
56
+ const port = desktop ? undefined : (values.port ?? process.env.PORT);
40
57
  if (port !== undefined && (!PORT.test(port) || Number(port) > 65_535)) {
41
58
  throw new Error("Invalid development port.");
42
59
  }
43
- let webDevelopment = "";
44
- try {
45
- webDevelopment = Bun.resolveSync("@teyik0/furin-electrobun/web-dev", cwd);
46
- } catch {
47
- // Web-only apps can run without the optional desktop integration installed.
48
- }
60
+ const { integration, env } = desktop
61
+ ? await desktopIntegration(cwd, !values.desktop)
62
+ : webIntegration(cwd);
49
63
  const child = Bun.spawn(
50
64
  [
51
65
  process.execPath,
@@ -53,10 +67,11 @@ export async function runDevelopment(cwd: string, args: string[]): Promise<void>
53
67
  join(import.meta.dir, "dev-worker.ts"),
54
68
  resolve(config.rootDir, config.serverEntry ?? "src/server.ts"),
55
69
  port ?? "",
56
- webDevelopment,
70
+ integration,
57
71
  ],
58
72
  {
59
73
  cwd: config.rootDir,
74
+ env: { ...process.env, ...env },
60
75
  stdin: "inherit",
61
76
  stdout: "inherit",
62
77
  stderr: "inherit",
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[];
@@ -160,16 +160,15 @@ function LinkInteractive<To extends RouteTo>({
160
160
  if (target !== null) {
161
161
  prefetch(target, { staleTime: effectiveStaleTime });
162
162
  }
163
- // react-doctor-disable-next-line react-doctor/exhaustive-deps
164
- }, [prefetch, logicalHref, effectiveStaleTime, router.basePath]);
163
+ }, [prefetch, effectiveStaleTime, router.basePath]);
165
164
 
166
- // "render": preload immediately on mount
165
+ // "render": preload immediately on mount, and again when the target changes.
167
166
  useEffect(() => {
168
167
  if (effectivePreload === "render") {
169
168
  triggerPrefetch();
170
169
  }
171
170
  // react-doctor-disable-next-line react-doctor/exhaustive-deps
172
- }, [effectivePreload, triggerPrefetch]);
171
+ }, [effectivePreload, triggerPrefetch, logicalHref]);
173
172
 
174
173
  // "viewport": preload when link enters viewport
175
174
  useEffect(() => {
@@ -188,7 +187,7 @@ function LinkInteractive<To extends RouteTo>({
188
187
  observer.observe(anchorRef.current);
189
188
  return () => observer.disconnect();
190
189
  // react-doctor-disable-next-line react-doctor/exhaustive-deps
191
- }, [effectivePreload, triggerPrefetch]);
190
+ }, [effectivePreload, triggerPrefetch, logicalHref]);
192
191
 
193
192
  // Clear any pending intent prefetch timer on unmount to avoid leaking
194
193
  // setTimeout callbacks between test cases (or across re-renders).
@@ -232,7 +231,7 @@ function LinkInteractive<To extends RouteTo>({
232
231
  // When there is no RouterProvider, fall back to a full-page navigation so
233
232
  // the link is still functional (e.g. in storybooks or third-party pages).
234
233
  if (typeof window !== "undefined" && router.navigate === CLIENT_FALLBACK_ROUTER.navigate) {
235
- window.location.href = href;
234
+ window.location.assign(href);
236
235
  return;
237
236
  }
238
237
  // navigate() expects the logical href (no basePath prefix).
@@ -261,22 +260,22 @@ function LinkInteractive<To extends RouteTo>({
261
260
  }
262
261
  };
263
262
 
264
- return createElement(
265
- "a",
266
- {
267
- "data-furin-link": true,
268
- href,
269
- onClick: handleClick,
270
- onFocus: handleFocus,
271
- onMouseEnter: handleMouseEnter,
272
- onMouseLeave: handleMouseLeave,
273
- ref: anchorRef,
274
- ...(isActive ? { "data-status": "active" } : {}),
275
- ...anchorProps,
276
- ...extraProps,
277
- ...(disabled ? { "aria-disabled": true } : {}),
278
- },
279
- resolvedChildren
263
+ return (
264
+ <a
265
+ data-furin-link
266
+ href={href}
267
+ onClick={handleClick}
268
+ onFocus={handleFocus}
269
+ onMouseEnter={handleMouseEnter}
270
+ onMouseLeave={handleMouseLeave}
271
+ ref={anchorRef}
272
+ {...(isActive ? { "data-status": "active" } : {})}
273
+ {...anchorProps}
274
+ {...extraProps}
275
+ {...(disabled ? { "aria-disabled": true } : {})}
276
+ >
277
+ {resolvedChildren}
278
+ </a>
280
279
  );
281
280
  }
282
281
 
@@ -81,9 +81,10 @@ export function useRouterStore(): RouterStore {
81
81
  }
82
82
 
83
83
  export function useTypedNavigation(context: StableRouter): Pick<Router, "navigate" | "prefetch"> {
84
+ const { navigate: navigateHref, prefetch: prefetchHref, searchRoutes } = context;
84
85
  const navigate: RouterNavigate = useCallback(
85
86
  (next: string | (RuntimeRouteTarget & NavigationOptions), opts?: NavigationOptions) => {
86
- const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
87
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, searchRoutes);
87
88
  const policy = navigationHrefPolicy(
88
89
  href,
89
90
  typeof window === "undefined" ? undefined : window.location.origin
@@ -96,22 +97,22 @@ export function useTypedNavigation(context: StableRouter): Pick<Router, "navigat
96
97
  return Promise.resolve();
97
98
  }
98
99
  if (typeof next === "string") {
99
- return context.navigate(href, opts);
100
+ return navigateHref(href, opts);
100
101
  }
101
102
  const options =
102
103
  next.replace === undefined && next.resetScroll === undefined
103
104
  ? undefined
104
105
  : { replace: next.replace, resetScroll: next.resetScroll };
105
- return context.navigate(href, options);
106
+ return navigateHref(href, options);
106
107
  },
107
- [context.navigate, context.searchRoutes]
108
+ [navigateHref, searchRoutes]
108
109
  );
109
110
  const prefetch: Prefetch = useCallback(
110
111
  (
111
112
  next: string | (RuntimeRouteTarget & { staleTime?: number }),
112
113
  opts?: { staleTime?: number }
113
114
  ) => {
114
- const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
115
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, searchRoutes);
115
116
  const policy = navigationHrefPolicy(
116
117
  href,
117
118
  typeof window === "undefined" ? undefined : window.location.origin
@@ -119,9 +120,9 @@ export function useTypedNavigation(context: StableRouter): Pick<Router, "navigat
119
120
  if (policy !== "internal") {
120
121
  return;
121
122
  }
122
- context.prefetch(href, typeof next === "string" ? opts : { staleTime: next.staleTime });
123
+ prefetchHref(href, typeof next === "string" ? opts : { staleTime: next.staleTime });
123
124
  },
124
- [context.prefetch, context.searchRoutes]
125
+ [prefetchHref, searchRoutes]
125
126
  );
126
127
  return { navigate, prefetch };
127
128
  }
@@ -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}`);
@@ -127,6 +127,7 @@ export function RouterProvider({
127
127
  const syncResponse = useRef<
128
128
  ((response: Response | undefined, optimistic: boolean) => void) | undefined
129
129
  >(undefined);
130
+ // biome-ignore lint/nursery/useReactCompiler: the runtime reads these refs only from its callbacks, after render.
130
131
  const [optimisticRuntime] = useState(() =>
131
132
  createOptimisticRuntime({
132
133
  basePath,
@@ -366,6 +367,8 @@ export function RouterProvider({
366
367
  });
367
368
  useSyncStream({ autoRefresh, basePath, controller, invalidationRefresh, queries, syncPath });
368
369
 
370
+ // The query store and resolved deferred promises are mutable sources outside
371
+ // React; queryRevision and deferredRevision are the keys that invalidate them.
369
372
  const queryData = useMemo(
370
373
  () =>
371
374
  projectDeferredQueryData(
@@ -380,8 +383,10 @@ export function RouterProvider({
380
383
  }
381
384
  return queries.snapshot(seed.url).data;
382
385
  },
386
+ // biome-ignore lint/nursery/useReactCompiler: deferredRevision invalidates this read.
383
387
  resolvedQueries.current
384
388
  ),
389
+ // biome-ignore lint/nursery/useReactCompiler: revisions intentionally key reads of external mutable sources.
385
390
  [queries, state.data, state.querySeeds, queryRevision, deferredRevision]
386
391
  );
387
392
  const renderedData = optimisticRuntime.project(queryData, currentHref);
@@ -36,18 +36,42 @@ type SegmentMatches<
36
36
  ? true
37
37
  : false;
38
38
 
39
- /** Mirrors the router: `:param` matches one non-empty segment, `*` the rest. */
39
+ /** An optional `:param?` segment followed by `Rest`: skip it, or let it take one segment. */
40
+ type OptionalSegmentMatches<Rest extends string, Path extends string> =
41
+ PatternMatches<Rest, Path> extends true
42
+ ? true
43
+ : Path extends `${infer PathHead}/${infer PathRest}`
44
+ ? PathHead extends ""
45
+ ? false
46
+ : PatternMatches<Rest, PathRest>
47
+ : false;
48
+
49
+ /**
50
+ * Mirrors the router: `:param` matches one non-empty segment, `:param?` one
51
+ * or none, `*` the rest. `Head` is always a single segment: `${infer Head}/`
52
+ * stops at the first slash.
53
+ */
40
54
  type PatternMatches<Pattern extends string, Path extends string> = Pattern extends "*"
41
55
  ? true
42
56
  : Pattern extends `${infer Head}/${infer Rest}`
43
- ? Path extends `${infer PathHead}/${infer PathRest}`
44
- ? SegmentMatches<Head, PathHead> extends true
45
- ? PatternMatches<Rest, PathRest>
46
- : false
47
- : false
48
- : Path extends `${string}/${string}`
49
- ? false
50
- : SegmentMatches<Pattern, Path>;
57
+ ? Head extends `:${string}?`
58
+ ? OptionalSegmentMatches<Rest, Path>
59
+ : Path extends `${infer PathHead}/${infer PathRest}`
60
+ ? SegmentMatches<Head, PathHead> extends true
61
+ ? PatternMatches<Rest, PathRest>
62
+ : false
63
+ : Rest extends `${string}/${string}`
64
+ ? false
65
+ : Rest extends `:${string}?`
66
+ ? SegmentMatches<Head, Path>
67
+ : false
68
+ : Pattern extends `:${string}?`
69
+ ? Path extends `${string}/${string}`
70
+ ? false
71
+ : true
72
+ : Path extends `${string}/${string}`
73
+ ? false
74
+ : SegmentMatches<Pattern, Path>;
51
75
 
52
76
  type MatchingPattern<Path extends string> = {
53
77
  [Pattern in RoutePattern]: PatternMatches<Pattern, Path> extends true ? Pattern : never;
@@ -177,11 +201,13 @@ export type PreloadStrategy = false | "intent" | "viewport" | "render";
177
201
 
178
202
  type LinkPathParamKeys<Path extends string> = Path extends `${infer Segment}/${infer Rest}`
179
203
  ? LinkPathParamKeys<Segment> | LinkPathParamKeys<Rest>
180
- : Path extends `:${infer Key}`
181
- ? Key
182
- : Path extends "*"
183
- ? "*"
184
- : never;
204
+ : Path extends `:${string}?`
205
+ ? never
206
+ : Path extends `:${infer Key}`
207
+ ? Key
208
+ : Path extends "*"
209
+ ? "_splat"
210
+ : never;
185
211
 
186
212
  type LinkParams<To extends RouteTo> = [To] extends [RoutePattern]
187
213
  ? LinkPathParamKeys<To> extends never
package/src/config.ts CHANGED
@@ -45,6 +45,7 @@ export interface StaticExportConfig {
45
45
  }
46
46
 
47
47
  const compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
48
+ const routeStyleSchema = t.Union([t.Literal("nextjs"), t.Literal("tanstack")]);
48
49
 
49
50
  export const configSchema = t.Object({
50
51
  /**
@@ -57,6 +58,7 @@ export const configSchema = t.Object({
57
58
  t.Object({
58
59
  pagesDir: t.String(),
59
60
  prefix: t.Optional(t.String()),
61
+ style: routeStyleSchema,
60
62
  })
61
63
  )
62
64
  ),
@@ -80,6 +82,7 @@ export const configSchema = t.Object({
80
82
  * Packages declaring `sideEffects: false` are optimized automatically.
81
83
  */
82
84
  optimizeImports: t.Optional(t.Array(t.String())),
85
+ /** Single-app build: its pages directory, with `style`. Prefer `apps` or the server entry's mounts. */
83
86
  pagesDir: t.Optional(t.String()),
84
87
  /**
85
88
  * Module preloading. `routeChunks` (default true) makes `<HeadContent />`
@@ -95,6 +98,8 @@ export const configSchema = t.Object({
95
98
  serverEntry: t.Optional(t.String()),
96
99
  /** Emit private server source maps for error-tool uploads. Off by default. */
97
100
  serverSourceMaps: t.Optional(t.Boolean()),
101
+ /** File-routing style of `pagesDir`: `"nextjs"` or `"tanstack"`. */
102
+ style: t.Optional(routeStyleSchema),
98
103
  static: t.Optional(
99
104
  t.Object({
100
105
  basePath: t.Optional(t.String()),