@teyik0/furin 0.7.0-alpha.1 → 0.7.0-alpha.3

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.
@@ -70,12 +70,8 @@ export function buildPageElement(
70
70
  });
71
71
 
72
72
  // Reconstruct the FULL route chain (shallow→deep, index 0 = root) by walking
73
- // parents. We keep every route — not only the ones declaring a layout — so a
74
- // route's chain index equals its directory depth. This mirrors the server's
75
- // `buildElement` exactly, which is what guarantees the per-segment boundaries
76
- // and layouts attach at the same depths on both sides (hydration parity).
77
- // Compacting to layouts-only (the previous approach) misaligned boundaries
78
- // and dropped the first nested layout whenever an ancestor lacked a layout.
73
+ // parents. Boundary depths refer to these indices, including routes without
74
+ // layouts, so server and client attach boundaries at the same positions.
79
75
  const chain: RuntimeRoute[] = [];
80
76
  let current: RuntimeRoute | undefined = match.pageRoute;
81
77
  while (current) {
@@ -85,9 +81,11 @@ export function buildPageElement(
85
81
 
86
82
  // Index boundaries by depth for O(1) lookup. A boundary's `depth` maps 1:1 to
87
83
  // the route-chain index (depth 0 = root layout, handled separately below).
88
- const byDepth = new Map<number, ClientSegmentBoundary>();
84
+ const byDepth = new Map<number, ClientSegmentBoundary[]>();
89
85
  for (const segment of match.segmentBoundaries ?? []) {
90
- byDepth.set(segment.depth, segment);
86
+ const boundaries = byDepth.get(segment.depth) ?? [];
87
+ boundaries.unshift(segment);
88
+ byDepth.set(segment.depth, boundaries);
91
89
  }
92
90
 
93
91
  // When a root route is present it occupies chain index 0 and is wrapped
@@ -101,7 +99,9 @@ export function buildPageElement(
101
99
  // boundary (so the boundary sits INSIDE the layout), then wrap with the
102
100
  // layout itself when this route declares one.
103
101
  for (let i = chain.length - 1; i >= rootOffset; i -= 1) {
104
- element = wrapSegmentBoundaries(element, byDepth.get(i), options);
102
+ for (const segment of byDepth.get(i) ?? []) {
103
+ element = wrapSegmentBoundaries(element, segment, options);
104
+ }
105
105
  const Layout = chain[i]?.layout;
106
106
  if (Layout) {
107
107
  element = createElement(Layout as ElementType, data, element);
@@ -110,7 +110,9 @@ export function buildPageElement(
110
110
 
111
111
  if (root) {
112
112
  // Depth 0 boundary wraps EVERYTHING below the root layout.
113
- element = wrapSegmentBoundaries(element, byDepth.get(0), options);
113
+ for (const segment of byDepth.get(0) ?? []) {
114
+ element = wrapSegmentBoundaries(element, segment, options);
115
+ }
114
116
  if (root.layout) {
115
117
  element = createElement(root.layout as ElementType, data, element);
116
118
  }
@@ -281,14 +281,14 @@ export function RouterProvider({
281
281
  const resolvedSearch = (state.data.query as SearchParamsInput | undefined) ?? EMPTY_SEARCH;
282
282
 
283
283
  /**
284
- * Depth-0 boundary (pagesDir root level) for the "no client route matched" 404
284
+ * Root-owned boundary for the "no client route matched" 404
285
285
  * path. When an unknown URL is navigated to, the server's `renderRootNotFound`
286
286
  * handles it — the root `not-found.tsx` (depth 0) is the correct component to
287
287
  * render inline instead of doing a full-page reload.
288
288
  */
289
289
  const rootBoundaries = useMemo<ClientSegmentBoundary[] | undefined>(() => {
290
290
  for (const route of routes) {
291
- const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
291
+ const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0 && b.isRoot !== false);
292
292
  if (depth0) {
293
293
  return [depth0];
294
294
  }
@@ -216,6 +216,8 @@ export interface RouterContextValue {
216
216
  export interface ClientSegmentBoundary {
217
217
  depth: number;
218
218
  error?: ErrorComponent;
219
+ /** False when a pathless directory shares index 0 but does not own the root fallback. */
220
+ isRoot?: boolean;
219
221
  notFound?: NotFoundComponent;
220
222
  }
221
223
 
@@ -12,7 +12,13 @@ import { pathToFileURL } from "node:url";
12
12
  import { type AnyElysia, Elysia } from "elysia";
13
13
  import { type FurinNativeRouteContext, getFurinRenderer } from "../define-route.ts";
14
14
  import { detectLoaderFromPath } from "../server/lang-detect.ts";
15
- import { parseDynamicRouteSegment, routeSegmentToPattern } from "../server/router/patterns.ts";
15
+ import {
16
+ filePathToPattern,
17
+ isRouteGroup,
18
+ parseDynamicRouteSegment,
19
+ routePatternKey,
20
+ routeSegmentToPattern,
21
+ } from "../server/router/patterns.ts";
16
22
  import { routeModuleSourceVersion } from "../server/router/source-version.ts";
17
23
 
18
24
  const ROUTES_NAMESPACE_PREFIX = "furin-routes";
@@ -118,7 +124,10 @@ function scanRouteFiles(
118
124
  directorySegments: string[],
119
125
  files: ScannedRouteFile[]
120
126
  ): void {
121
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
127
+ const entries = readdirSync(directory, { withFileTypes: true }).sort((left, right) =>
128
+ left.name.localeCompare(right.name)
129
+ );
130
+ for (const entry of entries) {
122
131
  if (entry.isDirectory()) {
123
132
  // Underscore-prefixed directories are co-located private folders
124
133
  // (components, libs) — never route segments.
@@ -157,10 +166,6 @@ function segmentPath(segment: string): string {
157
166
  return routeSegmentToPattern(segment);
158
167
  }
159
168
 
160
- function routePath(segments: string[]): string {
161
- return segments.length === 0 ? "/" : `/${segments.map(segmentPath).join("/")}`;
162
- }
163
-
164
169
  function routeId(instanceId: string, path: string): string {
165
170
  const encodedPath = Array.from(new TextEncoder().encode(path), (byte) =>
166
171
  byte.toString(16).padStart(2, "0")
@@ -193,18 +198,25 @@ function buildRouteTree(pagesDir: string, instanceId: string): RouteTreeNode {
193
198
  return node;
194
199
  };
195
200
  const root = ensureNode([]);
201
+ const seenPatterns = new Map<string, string>();
196
202
 
197
203
  for (const file of scannedFiles) {
198
204
  const node = ensureNode(file.directorySegments);
199
205
  if (file.base === "_route") {
200
- const path = `${routePath(file.directorySegments)}#layout`;
206
+ const path = `/${file.directorySegments.map(segmentPath).join("/")}#layout`;
201
207
  node.layout = { id: routeId(instanceId, path), path: "", sourcePath: file.sourcePath };
202
208
  continue;
203
209
  }
204
- const path =
205
- file.base === "index"
206
- ? routePath(file.directorySegments)
207
- : routePath([...file.directorySegments, file.base]);
210
+ const path = filePathToPattern(relative(pagesDir, file.sourcePath));
211
+ const patternKey = routePatternKey(path);
212
+ const relativePath = relative(pagesDir, file.sourcePath).replaceAll("\\", "/");
213
+ const previousPath = seenPatterns.get(patternKey);
214
+ if (previousPath !== undefined) {
215
+ throw new Error(
216
+ `[furin] Duplicate route pattern "${patternKey}" from "${previousPath}" and "${relativePath}".`
217
+ );
218
+ }
219
+ seenPatterns.set(patternKey, relativePath);
208
220
  const route = { id: routeId(instanceId, path), path, sourcePath: file.sourcePath };
209
221
  if (file.base === "index") {
210
222
  node.indexRoute = route;
@@ -547,7 +559,7 @@ function emitRouteNode(
547
559
  includeRootCatchAll: boolean
548
560
  ): string {
549
561
  const childIndentation = `${indentation} `;
550
- const prefix = node.name ? `/${segmentPath(node.name)}` : "";
562
+ const prefix = node.name && !isRouteGroup(node.name) ? `/${segmentPath(node.name)}` : "";
551
563
  const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
552
564
  const content: string[] = [];
553
565
  if (node.indexRoute) {
@@ -905,7 +917,7 @@ async function composableRouteApps(route: RouteFile): Promise<DevRoutesApps | un
905
917
  }
906
918
 
907
919
  async function composeRuntimeNode(node: RouteTreeNode): Promise<DevRoutesApps> {
908
- const prefix = node.name ? `/${segmentPath(node.name)}` : "";
920
+ const prefix = node.name && !isRouteGroup(node.name) ? `/${segmentPath(node.name)}` : "";
909
921
  const { fileRoutes } = node;
910
922
  const [layoutApps, indexRouteApps, fileRouteApps, childApps] = await Promise.all([
911
923
  node.layout ? composableRouteApps(node.layout) : undefined,
@@ -20,22 +20,25 @@ export function buildElement(
20
20
  key: pageKey(route.pattern, data, route.page._route.remountDeps),
21
21
  });
22
22
 
23
- // Index segmentBoundaries by depth for O(1) lookup during the wrap loop.
24
- // Directory depth `d` maps 1:1 to routeChain[d] in Furin's model (routeChain
25
- // is ordered shallow→deep, with index 0 being the root).
26
- const byDepth = new Map<number, SegmentBoundary>();
23
+ // Directories without layouts share their enclosing layout's chain index.
24
+ // Keep their boundaries in inside-out order instead of overwriting them.
25
+ const byDepth = new Map<number, SegmentBoundary[]>();
27
26
  const legacyRoute = route as ResolvedRoute & {
28
27
  segmentBoundaries?: SegmentBoundary[];
29
28
  };
30
29
  for (const segment of legacyRoute.segmentBoundaries ?? []) {
31
- byDepth.set(segment.depth, segment);
30
+ const boundaries = byDepth.get(segment.depth) ?? [];
31
+ boundaries.unshift(segment);
32
+ byDepth.set(segment.depth, boundaries);
32
33
  }
33
34
 
34
35
  // Build inside-out. At each level we first wrap the accumulated subtree
35
36
  // with the boundary declared at this depth (so the boundary sits INSIDE
36
37
  // the layout at the same depth), THEN wrap with the layout itself.
37
38
  for (let i = route.routeChain.length - 1; i >= 1; i -= 1) {
38
- element = wrapSegmentBoundaries(element, byDepth.get(i), undefined);
39
+ for (const segment of byDepth.get(i) ?? []) {
40
+ element = wrapSegmentBoundaries(element, segment, undefined);
41
+ }
39
42
  const routeEntry = route.routeChain[i];
40
43
  if (routeEntry?.layout) {
41
44
  const Layout = routeEntry.layout;
@@ -43,9 +46,11 @@ export function buildElement(
43
46
  }
44
47
  }
45
48
 
46
- // Depth 0 = pagesDir itself = the root layout directory. Boundary wraps
47
- // everything below the root layout; root layout wraps the boundary.
48
- element = wrapSegmentBoundaries(element, byDepth.get(0), undefined);
49
+ // Index-0 boundaries wrap everything below the root layout, including
50
+ // pathless directories without their own layouts.
51
+ for (const segment of byDepth.get(0) ?? []) {
52
+ element = wrapSegmentBoundaries(element, segment, undefined);
53
+ }
49
54
 
50
55
  if (rootLayout.layout) {
51
56
  const RootLayoutComponent = rootLayout.layout;
@@ -13,7 +13,7 @@ import {
13
13
  import { type CompileContext, getCompileContext } from "../internal.ts";
14
14
  import { IS_DEV } from "../runtime-env.ts";
15
15
  import { adaptDefinedLayout, adaptDefinedPage, isDefinedRouteTerminal } from "./defined-route.ts";
16
- import { filePathToPattern, resolveMode } from "./patterns.ts";
16
+ import { filePathToPattern, resolveMode, routePatternKey } from "./patterns.ts";
17
17
  import { routeModuleSourceVersion } from "./source-version.ts";
18
18
  import type { ResolvedRoute, RootLayout, SegmentBoundary } from "./types.ts";
19
19
 
@@ -248,12 +248,6 @@ export async function scanRootLayout(pagesDir: string): Promise<RootLayout> {
248
248
 
249
249
  const CONVENTION_FILE_NAMES = ["not-found", "error"] as const;
250
250
  const SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"] as const;
251
- const DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
252
-
253
- function routePatternKey(pattern: string): string {
254
- return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
255
- }
256
-
257
251
  function isConventionFileName(name: string): boolean {
258
252
  return (CONVENTION_FILE_NAMES as readonly string[]).includes(name);
259
253
  }
@@ -346,7 +340,10 @@ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<Resolv
346
340
  const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir);
347
341
  devRoute.notFound = notFound;
348
342
  devRoute.error = errorComponent;
349
- devRoute.segmentBoundaries = segmentBoundaries;
343
+ devRoute.segmentBoundaries = alignSegmentBoundaryDepths(
344
+ segmentBoundaries,
345
+ devRoute.routeChain
346
+ );
350
347
  routes.push(devRoute);
351
348
  continue;
352
349
  }
@@ -372,7 +369,7 @@ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<Resolv
372
369
  path: absolutePath,
373
370
  pattern,
374
371
  routeChain,
375
- segmentBoundaries,
372
+ segmentBoundaries: alignSegmentBoundaryDepths(segmentBoundaries, routeChain),
376
373
  tags: collectRouteTags(routeChain, page),
377
374
  });
378
375
  }
@@ -427,6 +424,25 @@ async function resolveDefinedLayoutParent(
427
424
  return parent;
428
425
  }
429
426
 
427
+ function alignSegmentBoundaryDepths(
428
+ boundaries: SegmentBoundary[],
429
+ routeChain: RuntimeRoute[]
430
+ ): SegmentBoundary[] {
431
+ return boundaries.map((boundary) => {
432
+ let depth = 0;
433
+ for (const [index, entry] of routeChain.entries()) {
434
+ if (!entry.sourcePath) {
435
+ continue;
436
+ }
437
+ const directory = entry.sourcePath.slice(0, entry.sourcePath.lastIndexOf("/"));
438
+ if (boundary.path === directory || boundary.path.startsWith(`${directory}/`)) {
439
+ depth = index;
440
+ }
441
+ }
442
+ return { ...boundary, depth };
443
+ });
444
+ }
445
+
430
446
  /**
431
447
  * Walks every directory from `pagesDir` down to the directory containing
432
448
  * `pageAbsolutePath` and records the OWN (not inherited) error.tsx /
@@ -108,6 +108,18 @@ export function routeSegmentToPattern(segment: string): string {
108
108
  return dynamic.catchAll ? "*" : `:${dynamic.name}`;
109
109
  }
110
110
 
111
+ const ROUTE_GROUP_RE = /^\([^()]+\)$/;
112
+
113
+ export function isRouteGroup(segment: string): boolean {
114
+ return ROUTE_GROUP_RE.test(segment);
115
+ }
116
+
117
+ const DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
118
+
119
+ export function routePatternKey(pattern: string): string {
120
+ return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
121
+ }
122
+
111
123
  export function filePathToPattern(path: string): string {
112
124
  const parts = path.replaceAll("\\", "/").split("/");
113
125
  const segments: string[] = [];
@@ -125,6 +137,10 @@ export function filePathToPattern(path: string): string {
125
137
  const isFile = idx === lastIndex;
126
138
  const name = isFile ? parse(part).name : part;
127
139
 
140
+ if (!isFile && isRouteGroup(name)) {
141
+ continue;
142
+ }
143
+
128
144
  // `index` collapses to its parent ONLY as a leaf filename. A directory
129
145
  // literally named `index` is a real route segment and must be preserved.
130
146
  if (isFile && name === "index") {
@@ -12,7 +12,7 @@ import type { NotFoundComponent } from "../../shared/not-found.ts";
12
12
  * exact nesting level where the user authored them (Next.js app-router model).
13
13
  */
14
14
  export interface SegmentBoundary {
15
- /** 0 = `pagesDir`; increments with each nested subdirectory. */
15
+ /** Index of the enclosing layout in routeChain; 0 = the root layout. */
16
16
  depth: number;
17
17
  error?: ErrorComponent;
18
18
  /**
@@ -45,7 +45,12 @@ export function installMutationHandlers(app: Elysia): void {
45
45
  table.macroScope?.get(index),
46
46
  ] as NonNullable<typeof route>)
47
47
  : app["~routes"][index]);
48
- if (!nativeRoute || ["GET", "HEAD", "OPTIONS", "WS"].includes(nativeRoute[0])) {
48
+ if (
49
+ !nativeRoute ||
50
+ ["GET", "HEAD", "OPTIONS", "WS"].includes(nativeRoute[0]) ||
51
+ // Elysia resolves mount placeholders and rewrites their Request paths during compilation.
52
+ (typeof nativeRoute[2] === "function" && "~mount" in nativeRoute[2])
53
+ ) {
49
54
  return compileHandler(index, immediate, route, aliases, table);
50
55
  }
51
56
  const [method, path, handle, owner, hooks, chain, inherited, macroScope] = nativeRoute;