@junejs/server 1.0.0-dev.42 → 1.0.0-dev.45

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.
package/src/dev.ts CHANGED
@@ -19,20 +19,41 @@ import { findGlobalCss, processCssCached, invalidateCss } from "./css";
19
19
  export type DevServerOptions = {
20
20
  appDir: string;
21
21
  port?: number;
22
+ // The address to bind. Default 127.0.0.1: the dev server is reachable from this
23
+ // machine only (MCP: "when running locally, servers SHOULD bind only to
24
+ // localhost"). "0.0.0.0" opens it to the LAN — `june dev --host`.
25
+ hostname?: string;
22
26
  host?: JuneHost;
23
27
  };
24
28
 
25
- export type DevServer = ServeHandle & { url: string };
29
+ // The Host names a dev server answers /mcp and /api for (#308): localhost and its
30
+ // subdomains, plus IP literals (always allowed — rebinding needs a domain name),
31
+ // plus a named --host and whatever the config allows.
32
+ // The URL to print and return: localhost for loopback or a wildcard bind (it
33
+ // answers there too), else the one address bound — nothing listens on loopback then.
34
+ export function devUrl(hostname: string, port: number): string {
35
+ if (["127.0.0.1", "0.0.0.0", "::", "localhost"].includes(hostname)) return `http://localhost:${port}`;
36
+ return `http://${hostname.includes(":") ? `[${hostname}]` : hostname}:${port}`;
37
+ }
38
+
39
+ export function devAllowedHosts(configured: readonly string[] | undefined, hostname: string): string[] {
40
+ const hosts = new Set(["localhost", ".localhost", ...(configured ?? [])]);
41
+ if (!/^[\d.]+$|:/.test(hostname)) hosts.add(hostname.toLowerCase()); // a name, not 0.0.0.0 / an IP
42
+ return [...hosts];
43
+ }
44
+
45
+ // stop() also shuts the app down (its agent runtime, #317); await it to know that's done.
46
+ export type DevServer = Omit<ServeHandle, "stop"> & { url: string; stop(force?: boolean): Promise<void> };
26
47
 
27
48
  // A taken default port must not be a dead end in dev — walk forward until a
28
49
  // port binds (the Vite convention). Probed with node:net, which both hosts
29
50
  // implement, so the host interface stays untouched.
30
- async function findFreePort(start: number, tries = 20): Promise<number> {
51
+ async function findFreePort(start: number, hostname: string, tries = 20): Promise<number> {
31
52
  for (let p = start; p < start + tries; p++) {
32
53
  const free = await new Promise<boolean>((resolve) => {
33
54
  const probe = createNetServer();
34
55
  probe.once("error", () => resolve(false));
35
- probe.listen(p, () => probe.close(() => resolve(true)));
56
+ probe.listen(p, hostname, () => probe.close(() => resolve(true)));
36
57
  });
37
58
  if (free) return p;
38
59
  }
@@ -42,10 +63,13 @@ async function findFreePort(start: number, tries = 20): Promise<number> {
42
63
  export async function startDevServer({
43
64
  appDir,
44
65
  port = 3000,
66
+ hostname = "127.0.0.1",
45
67
  host = defaultHost,
46
68
  }: DevServerOptions): Promise<DevServer> {
47
69
  await installAsyncContext();
48
- const config = await loadJuneConfig(appDir);
70
+ const loaded = await loadJuneConfig(appDir);
71
+ // The DNS-rebinding check (#308): a local server is exactly what rebinding targets.
72
+ const config = { ...loaded, agent: { ...loaded.agent, allowedHosts: devAllowedHosts(loaded.agent?.allowedHosts, hostname) } };
49
73
 
50
74
  // Apply pending migrations before serving — dev auto-applies the SAFE ones; a
51
75
  // destructive one is reported and skipped (the server still starts, but the
@@ -57,7 +81,7 @@ export async function startDevServer({
57
81
  const app = createApp({ appDir, config });
58
82
  await app.warmup();
59
83
 
60
- const freePort = await findFreePort(port);
84
+ const freePort = await findFreePort(port, hostname);
61
85
  if (freePort !== port) console.log(`[june] port ${port} is taken → using ${freePort}`);
62
86
  port = freePort;
63
87
 
@@ -65,6 +89,7 @@ export async function startDevServer({
65
89
  // dev/built parity) never sees it. See dev-reload.ts.
66
90
  const handle = host.serve(withLiveReload((req) => app.fetch(req)), {
67
91
  port,
92
+ hostname,
68
93
  earlyHints: () => app.earlyHints(),
69
94
  });
70
95
 
@@ -87,7 +112,15 @@ export async function startDevServer({
87
112
  void processCssCached(appDir).catch(() => {});
88
113
  }
89
114
 
90
- const url = `http://localhost:${handle.port}`;
91
- console.log(`june dev → ${url} (host: ${host.name})`);
92
- return { ...handle, url };
115
+ const url = devUrl(hostname, handle.port);
116
+ const lan = hostname === "127.0.0.1" ? "" : ` · listening on ${hostname}`;
117
+ console.log(`june dev → ${url} (host: ${host.name})${lan}`);
118
+ return {
119
+ ...handle,
120
+ url,
121
+ async stop(force?: boolean) {
122
+ handle.stop(force);
123
+ await app.close();
124
+ },
125
+ };
93
126
  }
package/src/host.ts CHANGED
@@ -42,7 +42,8 @@ export interface JuneHost {
42
42
  readonly name: "bun" | "node";
43
43
  serve(
44
44
  handler: (req: Request) => Promise<Response>,
45
- opts: { port: number; earlyHints?: () => string[] },
45
+ // hostname: the address to bind. Absent = all interfaces (production, containers).
46
+ opts: { port: number; hostname?: string; earlyHints?: () => string[] },
46
47
  ): ServeHandle;
47
48
  // Spawn a module in a child runtime (the react-server Flight renderer, which
48
49
  // must run under a different module-resolution condition). Phase 4 supersedes
@@ -63,7 +64,7 @@ function bunHost(): JuneHost {
63
64
  // idleTimeout 0: Bun's 10s default kills quiet long-lived responses —
64
65
  // the dev live-reload SSE most visibly (the browser then reconnects,
65
66
  // reads it as a server restart, and reloads the page every 10s).
66
- const server = Bun.serve({ port: opts.port, fetch: handler, idleTimeout: 0 });
67
+ const server = Bun.serve({ port: opts.port, hostname: opts.hostname, fetch: handler, idleTimeout: 0 });
67
68
  return { port: server.port ?? opts.port, stop: (force) => void server.stop(force) };
68
69
  },
69
70
  spawnModule(entry, args, opts) {
@@ -125,7 +126,7 @@ function nodeHost(): JuneHost {
125
126
  res.end("Internal Server Error");
126
127
  }
127
128
  });
128
- server.listen(opts.port);
129
+ server.listen(opts.port, opts.hostname);
129
130
  return {
130
131
  get port() {
131
132
  const addr = server.address();
package/src/manifest.ts CHANGED
@@ -63,6 +63,7 @@ export async function buildManifest(appRoot: string): Promise<WorkerManifest> {
63
63
  const routes: Record<string, BrandedRoute> = {};
64
64
  const dynamicRoutes: Array<{ pattern: string; def: BrandedRoute }> = [];
65
65
  const resourceRoutes: Array<{ pattern: string; handler: ResourceHandler }> = [];
66
+ const generatedRoutes = scanned.filter((r) => r.generated).map((r) => r.path);
66
67
  const layoutChains: Record<string, LayoutComponent[]> = {};
67
68
  const layoutBoundaries: Record<string, { index: number; key: string }> = {};
68
69
  const loadings: Record<string, LoadingComponent> = {};
@@ -115,6 +116,7 @@ export async function buildManifest(appRoot: string): Promise<WorkerManifest> {
115
116
  routes,
116
117
  dynamicRoutes,
117
118
  resourceRoutes,
119
+ ...(generatedRoutes.length ? { generatedRoutes } : {}),
118
120
  layoutChains,
119
121
  layoutBoundaries,
120
122
  loadings,
package/src/pipeline.ts CHANGED
@@ -48,9 +48,10 @@ import {
48
48
  siteSkill,
49
49
  sitemapXml,
50
50
  } from "@junejs/core/discovery";
51
- import { mcpHandler, mcpServerIdentity, mcpTools } from "@junejs/core/mcp";
51
+ import { mcpForbidden, mcpHandler, mcpServerIdentity, mcpTools, originRejection } from "@junejs/core/mcp";
52
52
  import {
53
53
  apiActionId,
54
+ apiForbidden,
54
55
  apiHandler,
55
56
  apiNamespaceResponse,
56
57
  isApiNamespace,
@@ -854,6 +855,14 @@ export function createPipeline(cfg: PipelineConfig): Pipeline {
854
855
  }
855
856
  }
856
857
 
858
+ // Which browsers may call /mcp and /api (#308) — the config's allowlists.
859
+ const originPolicy = { allowedOrigins: agent.allowedOrigins, allowedHosts: agent.allowedHosts };
860
+ // Only a POST runs an action on /mcp or /api; any other method is a CORS
861
+ // preflight or a 405. A preflight carries no credentials, so a cookie-reading
862
+ // resolver could throw on it — never resolve identity for one.
863
+ const callerIdentity = async (request: Request) =>
864
+ request.method === "POST" && cfg.identity ? await cfg.identity(request) : undefined;
865
+
857
866
  async function handleRequest(request: Request): Promise<Response> {
858
867
  const url = new URL(request.url);
859
868
 
@@ -864,11 +873,16 @@ export function createPipeline(cfg: PipelineConfig): Pipeline {
864
873
  // ambient `db` is the SAME resource the UI uses, and — via cfg.identity —
865
874
  // the same principal: requiresPrincipal actions and per-call connection
866
875
  // auth are live on this surface. ctx carries identity only — not resources.
867
- const identity = cfg.identity ? await cfg.identity(request) : undefined;
876
+ // The origin policy first: a refused browser call must not reach the
877
+ // identity resolver (its I/O, or a throw that would turn 403 into 500).
878
+ const refused = originRejection(request, originPolicy);
879
+ if (refused !== undefined) return mcpForbidden(refused);
880
+ const identity = await callerIdentity(request);
868
881
  return mcpHandler(
869
882
  request,
870
883
  { request, ...identity },
871
884
  mcpServerIdentity(url.origin, { site: docConfig.site, agent }),
885
+ originPolicy,
872
886
  );
873
887
  }
874
888
  // The REST projection of the same actions: POST /api/<id> dispatches through
@@ -887,8 +901,10 @@ export function createPipeline(cfg: PipelineConfig): Pipeline {
887
901
  }
888
902
  const actionId = apiActionId(url.pathname);
889
903
  if (actionId) {
890
- const identity = cfg.identity ? await cfg.identity(request) : undefined;
891
- return apiHandler(request, actionId, { request, ...identity });
904
+ const refused = originRejection(request, originPolicy);
905
+ if (refused !== undefined) return apiForbidden(request, refused);
906
+ const identity = await callerIdentity(request);
907
+ return apiHandler(request, actionId, { request, ...identity }, originPolicy);
892
908
  }
893
909
  }
894
910
  // The server card is read cross-origin by browser-based MCP clients; its
@@ -0,0 +1,60 @@
1
+ // Route precedence — the ONE ranking both resolvers use (#312). The dev matcher
2
+ // (router.ts, matchRouteTree) walks the app tree trying each level's children in
3
+ // this order; the built worker (worker.ts) cannot walk a tree, so it sorts its
4
+ // flat route table with compareRoutePatterns and takes the first regex match.
5
+ // For patterns that both match a URL, the depth-first walk and the sorted table
6
+ // pick the same winner: the first segment where two patterns differ decides.
7
+ //
8
+ // Worker-safe: no node:* imports.
9
+
10
+ export type SegmentKind = "static" | "param" | "optional" | "catchAll" | "optionalCatchAll";
11
+
12
+ // The one segment grammar: a param name is an identifier ([A-Za-z_][A-Za-z0-9_]*).
13
+ // Anything else in brackets (`[1]`, `[foo-bar]`, `[slug].png`) is a STATIC
14
+ // segment named literally, in dev, in the ranking and in the worker's regex.
15
+ const DYNAMIC = /^\[(\[)?(\.\.\.)?([A-Za-z_][A-Za-z0-9_]*)\](\])?$/;
16
+
17
+ export function parseSegment(segment: string): { kind: SegmentKind; name?: string } {
18
+ const m = segment.match(DYNAMIC);
19
+ // Brackets must pair: `[[x]]` or `[x]`, never `[[x]` / `[x]]`.
20
+ if (!m || !!m[1] !== !!m[4]) return { kind: "static" };
21
+ const optional = !!m[1];
22
+ const catchAll = !!m[2];
23
+ const kind: SegmentKind = catchAll
24
+ ? optional ? "optionalCatchAll" : "catchAll"
25
+ : optional ? "optional" : "param";
26
+ return { kind, name: m[3] };
27
+ }
28
+
29
+ const RANK: Record<SegmentKind, number> = { static: 0, param: 1, optional: 2, catchAll: 3, optionalCatchAll: 4 };
30
+
31
+ // Per-segment rank, most specific first: static, [param], [[param]], [...rest],
32
+ // [[...rest]]. Optional sits after its required form, so `[slug]` answers
33
+ // before `[[slug]]` when a segment is present.
34
+ export function segmentRank(segment: string): number {
35
+ return RANK[parseSegment(segment).kind];
36
+ }
37
+
38
+ // Sibling order within one directory level: by rank, then by name so a tie
39
+ // (two [param] dirs) resolves the same on every filesystem.
40
+ export function compareSegments(a: string, b: string): number {
41
+ return segmentRank(a) - segmentRank(b) || (a < b ? -1 : a > b ? 1 : 0);
42
+ }
43
+
44
+ // Order two file-route patterns ("/docs/[[...path]]", "/feed.xml") by
45
+ // precedence. The first differing segment decides; a pattern that ends there
46
+ // beats one that continues, since only absent optional segments can follow a
47
+ // match that already consumed the URL (dev checks a directory's own page before
48
+ // descending into its optional children).
49
+ export function compareRoutePatterns(a: string, b: string): number {
50
+ const as = a.split("/").filter(Boolean);
51
+ const bs = b.split("/").filter(Boolean);
52
+ for (let i = 0; i < Math.max(as.length, bs.length); i++) {
53
+ const x = as[i];
54
+ const y = bs[i];
55
+ if (x === undefined) return -1;
56
+ if (y === undefined) return 1;
57
+ if (x !== y) return compareSegments(x, y);
58
+ }
59
+ return 0;
60
+ }
package/src/route-scan.ts CHANGED
@@ -8,6 +8,8 @@ import { existsSync } from "node:fs";
8
8
  import { readdir } from "node:fs/promises";
9
9
  import { basename, join, relative, sep } from "node:path";
10
10
 
11
+ import { parseSegment } from "./route-rank";
12
+
11
13
  // The segment layout CHAIN root→leaf: every directory level (route groups
12
14
  // included) may contribute a layout.* that wraps routes below it.
13
15
  export type RouteEntry = {
@@ -15,6 +17,7 @@ export type RouteEntry = {
15
17
  file: string;
16
18
  dynamic: boolean;
17
19
  resource?: boolean; // a route.* resource route (raw-Response handler), not a page
20
+ generated?: boolean; // scanned from .june/routes/ — ranks after every app/ route, as in dev
18
21
  layouts: string[];
19
22
  loading?: string; // nearest loading.tsx up the tree → streaming Suspense fallback
20
23
  };
@@ -77,8 +80,82 @@ export async function scanAppRoutes(appRoot: string): Promise<RouteEntry[]> {
77
80
  const juneRoutesDir = join(appRoot, ".june", "routes");
78
81
  const appRoutes = await scanRoutes(appDir);
79
82
  const frameworkRoutes = existsSync(juneRoutesDir) ? await scanRoutes(juneRoutesDir) : [];
83
+ const problems = routeProblems([appRoutes, frameworkRoutes], appRoot);
84
+ if (problems) throw new Error(problems);
80
85
  const appPaths = new Set(appRoutes.map((r) => r.path));
81
- return [...appRoutes, ...frameworkRoutes.filter((r) => !appPaths.has(r.path))].sort((a, b) =>
86
+ const generated = frameworkRoutes
87
+ .filter((r) => !appPaths.has(r.path))
88
+ .map((r) => ({ ...r, generated: true }));
89
+ return [...appRoutes, ...generated].sort((a, b) =>
82
90
  a.path.localeCompare(b.path),
83
91
  );
84
92
  }
93
+
94
+ // Two route files in ONE tree that resolve to the same URL: `(a)/about/page.tsx`
95
+ // and `(b)/about/page.tsx` (groups vanish from the URL), or `page.tsx` next to
96
+ // `index.tsx`. Pages and resource routes are counted apart — a page and a
97
+ // route.ts at the same path are allowed, in one dir or across groups (the page
98
+ // wins). No winner is defined for the rest: dev
99
+ // would pick by group order and the worker by scan order, so the build refuses
100
+ // them and dev reports them (#316).
101
+ export function routeConflicts(routes: RouteEntry[]): Array<{ path: string; files: string[] }> {
102
+ const byKey = new Map<string, { path: string; files: string[] }>();
103
+ for (const r of routes) {
104
+ const key = `${r.resource ? "route" : "page"} ${r.path}`;
105
+ const hit = byKey.get(key);
106
+ if (hit) hit.files.push(r.file);
107
+ else byKey.set(key, { path: r.path, files: [r.file] });
108
+ }
109
+ return [...byKey.values()]
110
+ .filter((c) => c.files.length > 1)
111
+ .map((c) => ({ path: c.path, files: c.files.sort() }))
112
+ .sort((a, b) => a.path.localeCompare(b.path));
113
+ }
114
+
115
+ // An optional or catch-all segment ([[x]], [...x], [[...x]]) must END the route
116
+ // path (#315, the Next.js rule, opinionated). Mid-path there is no behavior to
117
+ // keep: dev never matched past a catch-all nor skipped a mid-path [[x]], while
118
+ // the worker's regex did both. A (group) after it is not a URL segment, so it's
119
+ // fine. Returns the offending routes, path-sorted.
120
+ const ENDS_PATH = new Set(["optional", "catchAll", "optionalCatchAll"]);
121
+ const beforeLast = (path: string) => path.split("/").filter(Boolean).slice(0, -1).map((s) => parseSegment(s).kind);
122
+
123
+ export function misplacedSegments(routes: RouteEntry[]): RouteEntry[] {
124
+ return routes
125
+ .filter((r) => beforeLast(r.path).some((k) => ENDS_PATH.has(k)))
126
+ .sort((a, b) => a.path.localeCompare(b.path) || a.file.localeCompare(b.file));
127
+ }
128
+
129
+ // Every route-table problem the build refuses and dev reports, as one message
130
+ // (null when there are none). Each tree (app/, .june/routes/) is checked on its
131
+ // own: the same path in both is not a conflict — app/ wins.
132
+ export function routeProblems(trees: RouteEntry[][], appRoot: string): string | null {
133
+ const rel = (f: string) => relative(appRoot, f).split(sep).join("/");
134
+ const sections: string[] = [];
135
+
136
+ const conflicts = trees.flatMap(routeConflicts);
137
+ if (conflicts.length) {
138
+ sections.push(
139
+ "[june] more than one route file resolves to the same path — keep one per path:\n" +
140
+ conflicts.map((c) => ` ${c.path}: ${c.files.map(rel).join(", ")}`).join("\n"),
141
+ );
142
+ }
143
+
144
+ const misplaced = trees.flatMap(misplacedSegments);
145
+ if (misplaced.length) {
146
+ const lines = misplaced.map((r) => ` ${r.path}: ${rel(r.file)}`);
147
+ // Developers (and models) read [[x]] the SvelteKit way, skippable anywhere;
148
+ // say so when a single optional is the culprit, and point at the real tool.
149
+ if (misplaced.some((r) => beforeLast(r.path).includes("optional"))) {
150
+ lines.push(
151
+ " Unlike SvelteKit, June does not skip a [[param]] mid-path. For a locale prefix, set i18n.locales in june.config.ts instead of a [[lang]] directory.",
152
+ );
153
+ }
154
+ sections.push(
155
+ "[june] an optional or catch-all segment must be the last segment of a route path — nothing may follow it:\n" +
156
+ lines.join("\n"),
157
+ );
158
+ }
159
+
160
+ return sections.length ? sections.join("\n") : null;
161
+ }
package/src/router.ts CHANGED
@@ -6,6 +6,8 @@ import { existsSync } from "node:fs";
6
6
  import { readdir } from "node:fs/promises";
7
7
  import { join, relative, sep } from "node:path";
8
8
 
9
+ import { compareSegments, parseSegment } from "./route-rank";
10
+
9
11
  export type RouteMatch = {
10
12
  file: string;
11
13
  params: Record<string, string>;
@@ -87,13 +89,13 @@ function isSpecialFile(file: string) {
87
89
  }
88
90
 
89
91
  const isRouteGroup = (name: string) => /^\(.+\)$/.test(name);
90
- const isParamDir = (name: string) => /^\[([A-Za-z_][A-Za-z0-9_]*)\]$/.test(name);
92
+ const isParamDir = (name: string) => parseSegment(name).kind === "param";
91
93
  // [[slug]] / [[...slug]] — match like their required forms, and ALSO match the
92
94
  // segment being absent (the param is then simply missing from ctx.params).
93
- const isOptionalDir = (name: string) => /^\[\[([A-Za-z_][A-Za-z0-9_]*)\]\]$/.test(name);
94
- const isOptionalCatchAllDir = (name: string) => /^\[\[\.\.\.([A-Za-z_][A-Za-z0-9_]*)\]\]$/.test(name);
95
- const isCatchAllDir = (name: string) => /^\[\.\.\.([A-Za-z_][A-Za-z0-9_]*)\]$/.test(name);
96
- const paramName = (name: string) => name.replace(/^\[+(\.\.\.)?|\]+$/g, "");
95
+ const isOptionalDir = (name: string) => parseSegment(name).kind === "optional";
96
+ const isOptionalCatchAllDir = (name: string) => parseSegment(name).kind === "optionalCatchAll";
97
+ const isCatchAllDir = (name: string) => parseSegment(name).kind === "catchAll";
98
+ const paramName = (name: string) => parseSegment(name).name!;
97
99
 
98
100
  type DirEntry = { name: string; dir: boolean };
99
101
 
@@ -147,8 +149,12 @@ function routePath(appDir: string, file: string) {
147
149
  }
148
150
 
149
151
  // Recursive-descent matcher over the app directory. Priority at every level:
150
- // exact static segment > [param] > [...catchAll]; route groups `(name)` descend
151
- // without consuming a URL segment; `_`-prefixed entries never participate.
152
+ // exact static segment > [param] > [...catchAll], required before optional, ties
153
+ // by name (route-rank.ts — the built worker sorts its route table by the same
154
+ // ranking); `_`-prefixed entries never participate. Route groups `(name)` are
155
+ // invisible in the URL, so they are invisible to ranking too: a group's children
156
+ // compete as siblings of the level the group sits in (a grouped `[slug]` never
157
+ // shadows a static sibling), while the group still contributes its layout.
152
158
  // Returns the page file, accumulated params (catch-all joins with "/"), and the
153
159
  // chain of segments (with their special files) from the app root to the page.
154
160
  export async function matchRouteTree(
@@ -158,85 +164,96 @@ export async function matchRouteTree(
158
164
  ): Promise<RouteTreeMatch | null> {
159
165
  const urlSegments = pathname.split("/").filter(Boolean).map(decodeURIComponent);
160
166
 
167
+ // One URL level = this dir plus every route group under it (groups nest), each
168
+ // with the segment chain down to it: the dir first, then groups in name order.
169
+ type Level = { dir: string; entries: DirEntry[]; segments: SegmentMatch[] };
170
+ async function levelAt(dir: string, chain: SegmentMatch[]): Promise<Level[]> {
171
+ // Ranked, not readdir order, so the pick is the same on every filesystem.
172
+ const entries = (await listDir(dir)).sort((a, b) => compareSegments(a.name, b.name));
173
+ const segments = [...chain, segmentAt(dir, entries)];
174
+ const levels: Level[] = [{ dir, entries, segments }];
175
+ for (const e of entries) {
176
+ if (e.dir && isRouteGroup(e.name)) levels.push(...(await levelAt(join(dir, e.name), segments)));
177
+ }
178
+ return levels;
179
+ }
180
+
181
+ // A URL level can span several real dirs: `(a)/blog` and `(b)/blog` are both
182
+ // `/blog`, so they descend TOGETHER — otherwise (a)/blog/[slug] would answer
183
+ // /blog/about before (b)/blog/about was ever seen.
184
+ type Node = { dir: string; chain: SegmentMatch[] };
185
+
161
186
  async function descend(
162
- dir: string,
187
+ nodes: Node[],
163
188
  rest: string[],
164
189
  params: Record<string, string>,
165
- chain: SegmentMatch[],
166
190
  ): Promise<RouteTreeMatch | null> {
167
- const entries = await listDir(dir);
168
- const segments = [...chain, segmentAt(dir, entries)];
191
+ const levels = (await Promise.all(nodes.map((n) => levelAt(n.dir, n.chain)))).flat();
169
192
 
170
- // Terminal: URL consumed → find the page (or resource route) in this dir.
193
+ // Terminal: URL consumed → find the page at this level, groups included,
194
+ // and only then a resource route: a page beats a route.ts at the same path
195
+ // even when the two sit in different groups (the worker ranks them so).
171
196
  if (rest.length === 0) {
172
- const page =
173
- fileFor(entries, dir, "page") ??
174
- fileFor(entries, dir, "index") ??
175
- fileFor(entries, dir, "route");
176
- if (page) return { file: page, params, segments };
177
- } else if (!options.pageConvention) {
197
+ for (const base of [["page", "index"], ["route"]]) {
198
+ for (const { dir: d, entries, segments } of levels) {
199
+ const file = base.map((b) => fileFor(entries, d, b)).find(Boolean);
200
+ if (file) return { file, params, segments };
201
+ }
202
+ }
203
+ } else if (!options.pageConvention && rest.length === 1) {
178
204
  // Legacy flat convention: a non-special leaf FILE names the final segment
179
205
  // (examples/rsc: about.tsx → /about). Only valid for the last segment.
180
- if (rest.length === 1) {
181
- const leaf = fileFor(entries, dir, rest[0]!);
182
- if (leaf && !isSpecialFile(leaf) && !isPageFile(leaf)) {
183
- return { file: leaf, params, segments };
184
- }
206
+ for (const { dir: d, entries, segments } of levels) {
207
+ const leaf = fileFor(entries, d, rest[0]!);
208
+ if (leaf && !isSpecialFile(leaf) && !isPageFile(leaf)) return { file: leaf, params, segments };
185
209
  }
186
210
  }
187
211
 
188
- // Route groups: try descending into every (group) without consuming URL.
189
- for (const e of entries) {
190
- if (!e.dir || !isRouteGroup(e.name)) continue;
191
- const hit = await descend(join(dir, e.name), rest, params, segments);
192
- if (hit) return hit;
212
+ // Every child dir at this level, groups flattened and same names merged, in
213
+ // rank order.
214
+ const children = new Map<string, Node[]>();
215
+ for (const lv of levels) {
216
+ for (const e of lv.entries) {
217
+ if (!e.dir || isRouteGroup(e.name)) continue;
218
+ const node = { dir: join(lv.dir, e.name), chain: lv.segments };
219
+ const same = children.get(e.name);
220
+ if (same) same.push(node);
221
+ else children.set(e.name, [node]);
222
+ }
193
223
  }
224
+ const names = [...children.keys()].sort(compareSegments);
194
225
 
195
226
  if (rest.length === 0) {
196
227
  // Optional segments match ABSENCE too: descend without consuming and
197
228
  // without setting the param.
198
- for (const e of entries) {
199
- if (!e.dir || !(isOptionalDir(e.name) || isOptionalCatchAllDir(e.name))) continue;
200
- const hit = await descend(join(dir, e.name), [], params, segments);
229
+ for (const name of names) {
230
+ if (!(isOptionalDir(name) || isOptionalCatchAllDir(name))) continue;
231
+ const hit = await descend(children.get(name)!, [], params);
201
232
  if (hit) return hit;
202
233
  }
203
234
  return null;
204
235
  }
205
236
  const [head, ...tail] = rest as [string, ...string[]];
206
237
 
207
- // 1) exact static dir
208
- const exact = entries.find((e) => e.dir && e.name === head);
209
- if (exact) {
210
- const hit = await descend(join(dir, head), tail, params, segments);
211
- if (hit) return hit;
212
- }
213
- // 2) [param] and [[param]] dirs consume one segment
214
- for (const e of entries) {
215
- if (!e.dir || !(isParamDir(e.name) || isOptionalDir(e.name))) continue;
216
- const hit = await descend(
217
- join(dir, e.name),
218
- tail,
219
- { ...params, [paramName(e.name)]: head },
220
- segments,
221
- );
222
- if (hit) return hit;
223
- }
224
- // 3) [...catchAll] and [[...catchAll]] dirs consume everything remaining
225
- for (const e of entries) {
226
- if (!e.dir || !(isCatchAllDir(e.name) || isOptionalCatchAllDir(e.name))) continue;
227
- const hit = await descend(
228
- join(dir, e.name),
229
- [],
230
- { ...params, [paramName(e.name)]: rest.join("/") },
231
- segments,
232
- );
238
+ for (const name of names) {
239
+ const into = children.get(name)!;
240
+ let hit: RouteTreeMatch | null = null;
241
+ if (isParamDir(name) || isOptionalDir(name)) {
242
+ // [param] and [[param]] consume one segment
243
+ hit = await descend(into, tail, { ...params, [paramName(name)]: head });
244
+ } else if (isCatchAllDir(name) || isOptionalCatchAllDir(name)) {
245
+ // [...catchAll] and [[...catchAll]] consume everything remaining
246
+ hit = await descend(into, [], { ...params, [paramName(name)]: rest.join("/") });
247
+ } else if (name === head) {
248
+ hit = await descend(into, tail, params); // exact static dir
249
+ }
233
250
  if (hit) return hit;
234
251
  }
235
252
 
236
253
  return null;
237
254
  }
238
255
 
239
- return descend(appDir, urlSegments, {}, []);
256
+ return descend([{ dir: appDir, chain: [] }], urlSegments, {});
240
257
  }
241
258
 
242
259
  // 404 path: walk the longest matchable STATIC prefix of the URL collecting