@teyik0/furin 0.9.0-alpha.1 → 0.9.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.
- package/dist/adapter/runtime-build.d.ts +7 -3
- package/dist/adapter/vercel.js +31 -6
- package/dist/build/client.d.ts +1 -1
- package/dist/build/entry-template.d.ts +3 -12
- package/dist/build/entry-template.ts +3 -15
- package/dist/build/hydrate.d.ts +6 -1
- package/dist/build/index.d.ts +1 -1
- package/dist/build/index.js +597 -445
- package/dist/build/route-metadata.d.ts +2 -2
- package/dist/build/route-types.d.ts +1 -1
- package/dist/build/types.d.ts +10 -4
- package/dist/cli/index.js +626 -466
- package/dist/client/chunks/{client-xy6g38kx.js → client-a7spxfnn.js} +24 -5
- package/dist/client/chunks/{client-rjhxgt64.js → client-d9v49jwz.js} +1 -1
- package/dist/client/chunks/{client-k29262a4.js → client-rdxyrw11.js} +1 -1
- package/dist/client/define-route.d.ts +14 -0
- package/dist/client/dev-error-overlay.ts +18 -0
- package/dist/client/internal/runtime-types.d.ts +8 -0
- package/dist/client/link.js +3 -3
- package/dist/client/router/link-utils.d.ts +3 -2
- package/dist/client/router/search/index.js +2 -2
- package/dist/client/router/types.d.ts +9 -3
- package/dist/client.js +22 -6
- package/dist/config.d.ts +4 -0
- package/dist/config.js +4 -1
- package/dist/define-route.d.ts +53 -12
- package/dist/furin.d.ts +13 -3
- package/dist/furin.js +771 -616
- package/dist/plugin/client-plugin.d.ts +1 -1
- package/dist/plugin/index.js +5 -4
- package/dist/plugin/route-config.d.ts +3 -3
- package/dist/plugin/route-manifest.d.ts +46 -0
- package/dist/plugin/route-tree.d.ts +13 -29
- package/dist/routes.d.ts +2 -2
- package/dist/server/dev/runtime.d.ts +2 -1
- package/dist/server/internal.d.ts +6 -0
- package/dist/server/internal.js +57 -76
- package/dist/server/registrations.d.ts +4 -2
- package/dist/server/router/defined-route.d.ts +4 -0
- package/dist/server/router/discovery.d.ts +14 -4
- package/dist/server/router/hmr.d.ts +12 -12
- package/dist/server/router/patterns.d.ts +4 -12
- package/dist/server/router/types.d.ts +16 -1
- package/dist/server/static-export.js +88 -120
- package/dist/server/sync/drizzle/index.d.ts +8 -10
- package/dist/shared/route-specificity.d.ts +10 -1
- package/package.json +4 -7
- package/src/adapter/package.ts +11 -37
- package/src/adapter/runtime-build.ts +5 -4
- package/src/adapter/static.ts +1 -1
- package/src/adapter/vercel.ts +2 -1
- package/src/build/client.ts +3 -3
- package/src/build/discover-pages-process.ts +1 -1
- package/src/build/elysia-aot.ts +2 -2
- package/src/build/entry-template.ts +3 -15
- package/src/build/hydrate.ts +14 -6
- package/src/build/index.ts +19 -9
- package/src/build/route-metadata.ts +15 -8
- package/src/build/route-types.ts +18 -43
- package/src/build/types.ts +12 -5
- package/src/cli/config.ts +6 -0
- package/src/cli/index.ts +30 -14
- package/src/client/define-route.ts +29 -4
- package/src/client/dev-error-overlay.ts +18 -0
- package/src/client/internal/runtime-types.ts +8 -0
- package/src/client/router/link-utils.ts +16 -8
- package/src/client/router/types.ts +40 -14
- package/src/config.ts +5 -0
- package/src/define-route.ts +85 -16
- package/src/furin.ts +31 -7
- package/src/plugin/client-plugin.ts +13 -8
- package/src/plugin/dev-routes.ts +8 -17
- package/src/plugin/route-config.ts +77 -62
- package/src/plugin/route-manifest.ts +437 -0
- package/src/plugin/route-modules.ts +6 -1
- package/src/plugin/route-registry.ts +11 -42
- package/src/plugin/route-tree.ts +71 -181
- package/src/routes.ts +2 -2
- package/src/server/dev/runtime.ts +16 -22
- package/src/server/dev-page-plugin.ts +5 -2
- package/src/server/internal.ts +4 -1
- package/src/server/registrations.ts +5 -2
- package/src/server/render/static-params.ts +2 -10
- package/src/server/router/defined-route.ts +8 -0
- package/src/server/router/discovery.ts +237 -196
- package/src/server/router/hmr.ts +45 -63
- package/src/server/router/patterns.ts +41 -117
- package/src/server/router/types.ts +17 -1
- package/src/server/sync/drizzle/index.ts +18 -19
- package/src/shared/route-specificity.ts +34 -2
- package/src/shared/utils/index.ts +1 -1
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
2
|
+
import { extname } from "node:path";
|
|
3
|
+
import { expandOptionalSegments } from "../shared/route-specificity.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* File-routing convention of one `furin()` app. Both styles produce the same
|
|
7
|
+
* manifest, keyed by TanStack Start ids, so switching style only renames files.
|
|
8
|
+
*/
|
|
9
|
+
export type RouteStyle = "nextjs" | "tanstack";
|
|
10
|
+
|
|
11
|
+
export interface RouteInstanceSpec {
|
|
12
|
+
pagesDir: string;
|
|
13
|
+
prefix: string;
|
|
14
|
+
style: RouteStyle;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface RouteParam {
|
|
18
|
+
/** `_splat` for a catch-all segment. */
|
|
19
|
+
name: string;
|
|
20
|
+
optional: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ManifestRoute {
|
|
24
|
+
/** `defineRoute(id)`: the app prefix, then the TanStack id (`/board/$boardId/` for an index). */
|
|
25
|
+
id: string;
|
|
26
|
+
kind: "layout" | "page";
|
|
27
|
+
/** Path params of the route and its layouts, shallow → deep. */
|
|
28
|
+
params: RouteParam[];
|
|
29
|
+
/** Source of the parent layout; `undefined` when the root layout is the parent. */
|
|
30
|
+
parentPath: string | undefined;
|
|
31
|
+
/** URL pattern under the app prefix: `/board/:boardId`, `/docs/*`, `/:lang?/about`. */
|
|
32
|
+
pattern: string;
|
|
33
|
+
sourcePath: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A Next.js-style `error` / `not-found` pair declared in one directory. */
|
|
37
|
+
export interface ManifestBoundary {
|
|
38
|
+
directory: string;
|
|
39
|
+
errorPath: string | undefined;
|
|
40
|
+
notFoundPath: string | undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface RouteManifest {
|
|
44
|
+
/** Directory boundaries, shallow → deep. Always empty in the TanStack style. */
|
|
45
|
+
boundaries: ManifestBoundary[];
|
|
46
|
+
/** Root layout module (`__root.tsx`, or `layout.tsx` at the top of a Next.js app). */
|
|
47
|
+
rootPath: string;
|
|
48
|
+
/** Layouts and pages in deterministic depth-first order. */
|
|
49
|
+
routes: ManifestRoute[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type Segment =
|
|
53
|
+
| { type: "group"; raw: string }
|
|
54
|
+
| { type: "param"; name: string; optional: boolean; raw: string }
|
|
55
|
+
| { type: "pathless"; raw: string }
|
|
56
|
+
| { type: "splat"; raw: string }
|
|
57
|
+
| { type: "static"; raw: string; value: string };
|
|
58
|
+
|
|
59
|
+
interface Candidate {
|
|
60
|
+
/** `route.tsx`, `layout.tsx` or a pathless file: a layout whatever its children. */
|
|
61
|
+
forcedLayout: boolean;
|
|
62
|
+
index: boolean;
|
|
63
|
+
segments: Segment[];
|
|
64
|
+
sourcePath: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface StyleScan {
|
|
68
|
+
boundaries: ManifestBoundary[];
|
|
69
|
+
candidates: Candidate[];
|
|
70
|
+
rootPath: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const ROUTE_EXTENSION = /\.(?:jsx?|tsx?)$/;
|
|
74
|
+
const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
75
|
+
const BRACKET_ESCAPE = /\[([^\]]*)\]/g;
|
|
76
|
+
const SOURCE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
|
|
77
|
+
const PARAM_SEGMENT = /(^|\/):[^/]+/g;
|
|
78
|
+
/** `[...slug]` and the optional `[[...slug]]`. */
|
|
79
|
+
const NEXT_CATCH_ALL = /^\[\[?\.\.\.([^\]]+)\]\]?$/;
|
|
80
|
+
|
|
81
|
+
/** Posix paths on every platform: consumers compare and slice them by "/". */
|
|
82
|
+
function child(directory: string, name: string): string {
|
|
83
|
+
return `${directory}/${name}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function sortedEntries(directory: string) {
|
|
87
|
+
return readdirSync(directory, { withFileTypes: true }).sort((left, right) =>
|
|
88
|
+
left.name.localeCompare(right.name)
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function moduleBase(name: string): string | undefined {
|
|
93
|
+
if (name.endsWith(".d.ts") || !ROUTE_EXTENSION.test(name)) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
return name.slice(0, -extname(name).length);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function findModule(directory: string, base: string): string | undefined {
|
|
100
|
+
return SOURCE_EXTENSIONS.map((extension) => child(directory, `${base}${extension}`)).find(
|
|
101
|
+
(path) => existsSync(path)
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function paramName(name: string, raw: string, sourcePath: string): string {
|
|
106
|
+
if (!PARAM_NAME.test(name)) {
|
|
107
|
+
throw new Error(
|
|
108
|
+
`[furin] Invalid dynamic parameter ${JSON.stringify(raw)} in ${JSON.stringify(sourcePath)}. Parameter names must match ${PARAM_NAME}.`
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
return name;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ── TanStack Start ──────────────────────────────────────────────────────────
|
|
115
|
+
|
|
116
|
+
/** Splits `posts.$postId.edit` on dots outside `[...]` escapes. */
|
|
117
|
+
function splitFlatName(base: string): string[] {
|
|
118
|
+
const tokens: string[] = [];
|
|
119
|
+
let current = "";
|
|
120
|
+
let escaped = false;
|
|
121
|
+
for (const character of base) {
|
|
122
|
+
if (character === "[") {
|
|
123
|
+
escaped = true;
|
|
124
|
+
} else if (character === "]") {
|
|
125
|
+
escaped = false;
|
|
126
|
+
}
|
|
127
|
+
if (character === "." && !escaped) {
|
|
128
|
+
tokens.push(current);
|
|
129
|
+
current = "";
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
current += character;
|
|
133
|
+
}
|
|
134
|
+
tokens.push(current);
|
|
135
|
+
return tokens;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function tanstackSegment(raw: string, sourcePath: string): Segment {
|
|
139
|
+
if (raw.startsWith("(") && raw.endsWith(")")) {
|
|
140
|
+
return { raw, type: "group" };
|
|
141
|
+
}
|
|
142
|
+
if (raw === "$") {
|
|
143
|
+
return { raw, type: "splat" };
|
|
144
|
+
}
|
|
145
|
+
if (raw.startsWith("{-$") && raw.endsWith("}")) {
|
|
146
|
+
return {
|
|
147
|
+
name: paramName(raw.slice(3, -1), raw, sourcePath),
|
|
148
|
+
optional: true,
|
|
149
|
+
raw,
|
|
150
|
+
type: "param",
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
if (raw.startsWith("$")) {
|
|
154
|
+
return { name: paramName(raw.slice(1), raw, sourcePath), optional: false, raw, type: "param" };
|
|
155
|
+
}
|
|
156
|
+
if (raw.startsWith("_")) {
|
|
157
|
+
return { raw, type: "pathless" };
|
|
158
|
+
}
|
|
159
|
+
// `posts_` leaves the `posts` layout: same URL segment, different id.
|
|
160
|
+
const value = (raw.endsWith("_") ? raw.slice(0, -1) : raw).replace(BRACKET_ESCAPE, "$1");
|
|
161
|
+
return { raw, type: "static", value };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A TanStack route file: `index`, `route` and flat `a.$b` names under `segments`. */
|
|
165
|
+
function tanstackCandidate(base: string, segments: Segment[], sourcePath: string): Candidate {
|
|
166
|
+
const tokens = splitFlatName(base);
|
|
167
|
+
const last = tokens.at(-1);
|
|
168
|
+
const index = last === "index";
|
|
169
|
+
const routeFile = last === "route";
|
|
170
|
+
const own = (index || routeFile ? tokens.slice(0, -1) : tokens).map((token) =>
|
|
171
|
+
tanstackSegment(token, sourcePath)
|
|
172
|
+
);
|
|
173
|
+
const routeSegments = [...segments, ...own];
|
|
174
|
+
if (routeFile && routeSegments.length === 0) {
|
|
175
|
+
throw new Error(
|
|
176
|
+
`[furin] ${sourcePath}: a top-level route.tsx has no path to wrap. The root layout lives in __root.tsx.`
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
forcedLayout: routeFile || routeSegments.at(-1)?.type === "pathless",
|
|
181
|
+
index,
|
|
182
|
+
segments: routeSegments,
|
|
183
|
+
sourcePath,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function scanTanstack(pagesDir: string): StyleScan {
|
|
188
|
+
const candidates: Candidate[] = [];
|
|
189
|
+
const walk = (directory: string, segments: Segment[]): void => {
|
|
190
|
+
for (const entry of sortedEntries(directory)) {
|
|
191
|
+
if (entry.name.startsWith("-")) {
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
const sourcePath = child(directory, entry.name);
|
|
195
|
+
if (entry.isDirectory()) {
|
|
196
|
+
walk(sourcePath, [...segments, tanstackSegment(entry.name, sourcePath)]);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const base = moduleBase(entry.name);
|
|
200
|
+
if (base !== undefined && !(segments.length === 0 && base === "__root")) {
|
|
201
|
+
candidates.push(tanstackCandidate(base, segments, sourcePath));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
walk(pagesDir, []);
|
|
206
|
+
return {
|
|
207
|
+
boundaries: [],
|
|
208
|
+
candidates,
|
|
209
|
+
rootPath: findModule(pagesDir, "__root") ?? child(pagesDir, "__root.tsx"),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ── Next.js App Router ──────────────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
function nextSegment(name: string, sourcePath: string): Segment {
|
|
216
|
+
if (name.startsWith("(") && name.endsWith(")")) {
|
|
217
|
+
return { raw: name, type: "group" };
|
|
218
|
+
}
|
|
219
|
+
const catchAll = name.match(NEXT_CATCH_ALL);
|
|
220
|
+
if (catchAll?.[1] !== undefined) {
|
|
221
|
+
paramName(catchAll[1], name, sourcePath);
|
|
222
|
+
return { raw: "$", type: "splat" };
|
|
223
|
+
}
|
|
224
|
+
if (name.startsWith("[") && name.endsWith("]")) {
|
|
225
|
+
const name_ = paramName(name.slice(1, -1), name, sourcePath);
|
|
226
|
+
return { name: name_, optional: false, raw: `$${name_}`, type: "param" };
|
|
227
|
+
}
|
|
228
|
+
return { raw: name, type: "static", value: name };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
interface NextScanState {
|
|
232
|
+
boundary: ManifestBoundary;
|
|
233
|
+
candidates: Candidate[];
|
|
234
|
+
rootPath: string | undefined;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Records one App Router file: a page, a layout, the root layout or a boundary. */
|
|
238
|
+
function addNextFile(
|
|
239
|
+
state: NextScanState,
|
|
240
|
+
base: string | undefined,
|
|
241
|
+
segments: Segment[],
|
|
242
|
+
sourcePath: string
|
|
243
|
+
): void {
|
|
244
|
+
if (base === "route") {
|
|
245
|
+
throw new Error(
|
|
246
|
+
`[furin] ${sourcePath}: route handlers are not supported. Declare API routes on your Elysia app instead.`
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
if (base === "layout" && segments.at(-1)?.type === "splat") {
|
|
250
|
+
throw new Error(
|
|
251
|
+
`[furin] ${sourcePath}: a layout cannot share a catch-all folder with its page: move it to the parent folder.`
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
if (base === "page" || (base === "layout" && segments.length > 0)) {
|
|
255
|
+
state.candidates.push({
|
|
256
|
+
forcedLayout: base === "layout",
|
|
257
|
+
// `docs/[...slug]/page.tsx` is TanStack's `docs/$.tsx`, not an index.
|
|
258
|
+
index: base === "page" && segments.at(-1)?.type !== "splat",
|
|
259
|
+
segments,
|
|
260
|
+
sourcePath,
|
|
261
|
+
});
|
|
262
|
+
} else if (base === "layout") {
|
|
263
|
+
state.rootPath ??= sourcePath;
|
|
264
|
+
} else if (base === "error") {
|
|
265
|
+
state.boundary.errorPath ??= sourcePath;
|
|
266
|
+
} else if (base === "not-found") {
|
|
267
|
+
state.boundary.notFoundPath ??= sourcePath;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function scanNext(pagesDir: string): StyleScan {
|
|
272
|
+
const candidates: Candidate[] = [];
|
|
273
|
+
const boundaries: ManifestBoundary[] = [];
|
|
274
|
+
let rootPath: string | undefined;
|
|
275
|
+
const walk = (directory: string, segments: Segment[]): void => {
|
|
276
|
+
const boundary: ManifestBoundary = { directory, errorPath: undefined, notFoundPath: undefined };
|
|
277
|
+
const state: NextScanState = { boundary, candidates, rootPath };
|
|
278
|
+
for (const entry of sortedEntries(directory)) {
|
|
279
|
+
const sourcePath = child(directory, entry.name);
|
|
280
|
+
if (!entry.isDirectory()) {
|
|
281
|
+
addNextFile(state, moduleBase(entry.name), segments, sourcePath);
|
|
282
|
+
} else if (!entry.name.startsWith("_")) {
|
|
283
|
+
// `_folder` opts a folder out of routing, as in the App Router.
|
|
284
|
+
walk(sourcePath, [...segments, nextSegment(entry.name, sourcePath)]);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
rootPath ??= state.rootPath;
|
|
288
|
+
if (boundary.errorPath || boundary.notFoundPath) {
|
|
289
|
+
boundaries.push(boundary);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
walk(pagesDir, []);
|
|
293
|
+
// Parents first: the walk pushes a directory's boundary after its children.
|
|
294
|
+
boundaries.sort((left, right) => left.directory.length - right.directory.length);
|
|
295
|
+
return { boundaries, candidates, rootPath: rootPath ?? child(pagesDir, "layout.tsx") };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// ── Shared tree ─────────────────────────────────────────────────────────────
|
|
299
|
+
|
|
300
|
+
function segmentKey(segments: Segment[]): string {
|
|
301
|
+
return segments.map((segment) => segment.raw).join("/");
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function segmentPattern(segment: Segment): string | undefined {
|
|
305
|
+
switch (segment.type) {
|
|
306
|
+
case "group":
|
|
307
|
+
case "pathless":
|
|
308
|
+
return;
|
|
309
|
+
case "param":
|
|
310
|
+
return `:${segment.name}${segment.optional ? "?" : ""}`;
|
|
311
|
+
case "splat":
|
|
312
|
+
return "*";
|
|
313
|
+
default:
|
|
314
|
+
return segment.value;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function urlPattern(segments: Segment[]): string {
|
|
319
|
+
return `/${segments.flatMap((segment) => segmentPattern(segment) ?? []).join("/")}`;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function routeParams(segments: Segment[]): RouteParam[] {
|
|
323
|
+
return segments.flatMap((segment): RouteParam[] => {
|
|
324
|
+
if (segment.type === "param") {
|
|
325
|
+
return [{ name: segment.name, optional: segment.optional }];
|
|
326
|
+
}
|
|
327
|
+
return segment.type === "splat" ? [{ name: "_splat", optional: false }] : [];
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function assertSplatLast(candidate: Candidate): void {
|
|
332
|
+
const splat = candidate.segments.findIndex((segment) => segment.type === "splat");
|
|
333
|
+
if (splat !== -1 && splat < candidate.segments.length - 1) {
|
|
334
|
+
throw new Error(
|
|
335
|
+
`[furin] ${candidate.sourcePath}: a catch-all segment must be the last segment of its path.`
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** Collision keys of a page: one per concrete variant, params renamed `:param`. */
|
|
341
|
+
function patternKeys(pattern: string): string[] {
|
|
342
|
+
const keys = expandOptionalSegments(pattern).map((variant) =>
|
|
343
|
+
variant.replace(PARAM_SEGMENT, "$1:param")
|
|
344
|
+
);
|
|
345
|
+
// `/{-$a}/{-$b}/docs` serves `/:param/docs` twice: one page, not a collision.
|
|
346
|
+
return [...new Set(keys)];
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Records a page's collision keys, rejecting one another page already claims. */
|
|
350
|
+
function claimPatterns(
|
|
351
|
+
seenPatterns: Map<string, string>,
|
|
352
|
+
pattern: string,
|
|
353
|
+
sourcePath: string,
|
|
354
|
+
relativePath: (path: string) => string
|
|
355
|
+
): void {
|
|
356
|
+
for (const patternKey of patternKeys(pattern)) {
|
|
357
|
+
const previous = seenPatterns.get(patternKey);
|
|
358
|
+
if (previous !== undefined) {
|
|
359
|
+
throw new Error(
|
|
360
|
+
`[furin] Duplicate route pattern "${patternKey}" from "${relativePath(previous)}" and "${relativePath(sourcePath)}".`
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
seenPatterns.set(patternKey, sourcePath);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function buildManifest(scan: StyleScan, pagesDir: string, prefix: string): RouteManifest {
|
|
368
|
+
const relativePath = (path: string): string => path.slice(pagesDir.length + 1);
|
|
369
|
+
const { candidates } = scan;
|
|
370
|
+
const keys = candidates.map((candidate) => segmentKey(candidate.segments));
|
|
371
|
+
const hasDescendant = (key: string, self: Candidate): boolean =>
|
|
372
|
+
candidates.some(
|
|
373
|
+
(other, index) =>
|
|
374
|
+
other !== self &&
|
|
375
|
+
(keys[index]?.startsWith(`${key}/`) === true || (other.index && keys[index] === key))
|
|
376
|
+
);
|
|
377
|
+
|
|
378
|
+
const layouts = new Map<string, string>();
|
|
379
|
+
const kinds = candidates.map((candidate, index): ManifestRoute["kind"] => {
|
|
380
|
+
assertSplatLast(candidate);
|
|
381
|
+
const key = keys[index] ?? "";
|
|
382
|
+
const isLayout = !candidate.index && (candidate.forcedLayout || hasDescendant(key, candidate));
|
|
383
|
+
if (!isLayout) {
|
|
384
|
+
return "page";
|
|
385
|
+
}
|
|
386
|
+
const existing = layouts.get(key);
|
|
387
|
+
if (existing !== undefined) {
|
|
388
|
+
throw new Error(
|
|
389
|
+
`[furin] Two layouts wrap "/${key}": "${relativePath(existing)}" and "${relativePath(candidate.sourcePath)}".`
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
layouts.set(key, candidate.sourcePath);
|
|
393
|
+
return "layout";
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
const seenIds = new Map<string, string>();
|
|
397
|
+
const seenPatterns = new Map<string, string>();
|
|
398
|
+
const routes = candidates.map((candidate, index): ManifestRoute => {
|
|
399
|
+
const kind = kinds[index] ?? "page";
|
|
400
|
+
const { segments, sourcePath } = candidate;
|
|
401
|
+
const key = keys[index] ?? "";
|
|
402
|
+
// An index sits under the layout sharing its path; anything else under a strict ancestor.
|
|
403
|
+
let parentPath = candidate.index ? layouts.get(key) : undefined;
|
|
404
|
+
for (let depth = segments.length - 1; parentPath === undefined && depth > 0; depth -= 1) {
|
|
405
|
+
parentPath = layouts.get(segmentKey(segments.slice(0, depth)));
|
|
406
|
+
}
|
|
407
|
+
const path = `/${key}${candidate.index && key !== "" ? "/" : ""}`;
|
|
408
|
+
const id = prefix === "" ? path : `${prefix}${path}`;
|
|
409
|
+
const previousId = seenIds.get(id);
|
|
410
|
+
if (previousId !== undefined) {
|
|
411
|
+
throw new Error(
|
|
412
|
+
`[furin] Duplicate route id "${id}" from "${relativePath(previousId)}" and "${relativePath(sourcePath)}".`
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
seenIds.set(id, sourcePath);
|
|
416
|
+
const pattern = urlPattern(segments);
|
|
417
|
+
if (kind === "page") {
|
|
418
|
+
claimPatterns(seenPatterns, pattern, sourcePath, relativePath);
|
|
419
|
+
}
|
|
420
|
+
return { id, kind, params: routeParams(segments), parentPath, pattern, sourcePath };
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
return { boundaries: scan.boundaries, rootPath: scan.rootPath, routes };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* The single filesystem walk behind every route consumer (route tree,
|
|
428
|
+
* discovery, typegen, route-config checks, dev topology).
|
|
429
|
+
*/
|
|
430
|
+
export function scanRouteManifest({ pagesDir, prefix, style }: RouteInstanceSpec): RouteManifest {
|
|
431
|
+
const directory = pagesDir.replaceAll("\\", "/");
|
|
432
|
+
return buildManifest(
|
|
433
|
+
style === "nextjs" ? scanNext(directory) : scanTanstack(directory),
|
|
434
|
+
directory,
|
|
435
|
+
prefix
|
|
436
|
+
);
|
|
437
|
+
}
|
|
@@ -4,6 +4,7 @@ import { pathToFileURL } from "node:url";
|
|
|
4
4
|
import type { AnyElysia } from "elysia";
|
|
5
5
|
import type { CompiledModule } from "../server/internal.ts";
|
|
6
6
|
import { detectLoaderFromPath, SCRIPT_FILE_FILTER } from "../server/lang-detect.ts";
|
|
7
|
+
import { SPLAT_PARAM } from "../server/router/patterns.ts";
|
|
7
8
|
|
|
8
9
|
const ROUTE_MODULE_CACHE_SYMBOL = Symbol.for("@teyik0/furin/route-module-cache");
|
|
9
10
|
|
|
@@ -12,6 +13,8 @@ export interface RouteModuleInfo {
|
|
|
12
13
|
sourcePath: string;
|
|
13
14
|
}
|
|
14
15
|
|
|
16
|
+
const OPTIONAL_MARK = /\?$/;
|
|
17
|
+
|
|
15
18
|
export function validateRouteParams(
|
|
16
19
|
path: string,
|
|
17
20
|
schemas: { params?: { properties?: object } } | undefined
|
|
@@ -19,7 +22,9 @@ export function validateRouteParams(
|
|
|
19
22
|
const pathParams = path
|
|
20
23
|
.split("/")
|
|
21
24
|
.filter((segment) => segment === "*" || segment.startsWith(":"))
|
|
22
|
-
.map((segment) =>
|
|
25
|
+
.map((segment) =>
|
|
26
|
+
segment === "*" ? SPLAT_PARAM : segment.slice(1).replace(OPTIONAL_MARK, "")
|
|
27
|
+
);
|
|
23
28
|
if (pathParams.length === 0) {
|
|
24
29
|
return;
|
|
25
30
|
}
|
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { detectLoaderFromPath } from "../server/lang-detect.ts";
|
|
3
|
-
import { isRouteGroup } from "../server/router/patterns.ts";
|
|
1
|
+
import { join, resolve } from "node:path";
|
|
4
2
|
import {
|
|
5
3
|
loadRouteModule,
|
|
6
4
|
type RouteModuleInfo,
|
|
@@ -15,7 +13,6 @@ import {
|
|
|
15
13
|
type RouteInstanceSpec,
|
|
16
14
|
type RouteTreeNode,
|
|
17
15
|
routeModuleSpecifier,
|
|
18
|
-
segmentPath,
|
|
19
16
|
} from "./route-tree.ts";
|
|
20
17
|
|
|
21
18
|
const ROUTES_NAMESPACE_PREFIX = "furin-routes";
|
|
@@ -23,7 +20,6 @@ const ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry";
|
|
|
23
20
|
const COMPOSABLE_ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry=composable";
|
|
24
21
|
const ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry(?:=composable)?$/;
|
|
25
22
|
const ROUTE_FILE_FILTER = /^furin-route-file:.+$/;
|
|
26
|
-
const ROUTE_FILES_NAMESPACE = "furin-route-files";
|
|
27
23
|
const ROUTES_REGISTRY_FILE_FILTER =
|
|
28
24
|
/[\\/]\.furin-routes-registry(?:-composable)?\.ts\?furin-virtual$/;
|
|
29
25
|
const CLIENT_ROUTES_NAMESPACE = "furin-routes-client";
|
|
@@ -63,18 +59,11 @@ function emitRouteNode(
|
|
|
63
59
|
includeRootCatchAll: boolean
|
|
64
60
|
): string {
|
|
65
61
|
const childIndentation = `${indentation} `;
|
|
66
|
-
const
|
|
67
|
-
const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
|
|
62
|
+
const head = `new Elysia({ prefix: ${JSON.stringify(node.prefix)} })`;
|
|
68
63
|
const content: string[] = [];
|
|
69
|
-
|
|
64
|
+
for (const route of node.pages.filter((file) => includeRootCatchAll || file.path !== "/*")) {
|
|
70
65
|
content.push(
|
|
71
|
-
`${childIndentation}.use(new Elysia({ prefix:
|
|
72
|
-
);
|
|
73
|
-
}
|
|
74
|
-
for (const route of node.fileRoutes.filter((file) => includeRootCatchAll || file.path !== "/*")) {
|
|
75
|
-
const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
|
|
76
|
-
content.push(
|
|
77
|
-
`${childIndentation}.use(new Elysia({ prefix: ${JSON.stringify(`/${segment}`)} }).use(${route.id}.elysia))`
|
|
66
|
+
`${childIndentation}.use(new Elysia({ prefix: ${JSON.stringify(route.prefix)} }).use(${route.id}.elysia))`
|
|
78
67
|
);
|
|
79
68
|
}
|
|
80
69
|
for (const child of node.children) {
|
|
@@ -112,15 +101,10 @@ async function retainComposableRoutes(node: RouteTreeNode): Promise<void> {
|
|
|
112
101
|
if (node.layout && !(await isComposable(node.layout))) {
|
|
113
102
|
node.layout = undefined;
|
|
114
103
|
}
|
|
115
|
-
if (node.indexRoute && !(await isComposable(node.indexRoute))) {
|
|
116
|
-
node.indexRoute = undefined;
|
|
117
|
-
}
|
|
118
104
|
const composableRoutes = (
|
|
119
|
-
await Promise.all(
|
|
120
|
-
node.fileRoutes.map(async (route) => ({ keep: await isComposable(route), route }))
|
|
121
|
-
)
|
|
105
|
+
await Promise.all(node.pages.map(async (route) => ({ keep: await isComposable(route), route })))
|
|
122
106
|
).flatMap(({ keep, route }) => (keep ? [route] : []));
|
|
123
|
-
node.
|
|
107
|
+
node.pages = composableRoutes;
|
|
124
108
|
await Promise.all(node.children.map((child) => retainComposableRoutes(child)));
|
|
125
109
|
}
|
|
126
110
|
|
|
@@ -139,7 +123,7 @@ async function generateServerInstance(
|
|
|
139
123
|
: instance.routeRegistry.composable;
|
|
140
124
|
}
|
|
141
125
|
const instanceId = Bun.hash(instanceKey(instance)).toString(16);
|
|
142
|
-
const tree = buildRouteTree(instance
|
|
126
|
+
const tree = buildRouteTree(instance, instanceId);
|
|
143
127
|
await retainComposableRoutes(tree);
|
|
144
128
|
const imports = collectRouteFiles(tree)
|
|
145
129
|
.sort((left, right) => left.sourcePath.localeCompare(right.sourcePath))
|
|
@@ -207,7 +191,7 @@ async function clientRoutesSource(instance: RegistryInstance): Promise<string> {
|
|
|
207
191
|
if (instance.routeRegistry) {
|
|
208
192
|
return instance.routeRegistry.client;
|
|
209
193
|
}
|
|
210
|
-
const tree = buildRouteTree(instance
|
|
194
|
+
const tree = buildRouteTree(instance, Bun.hash(instanceKey(instance)).toString(16));
|
|
211
195
|
const routes = collectRouteFiles(tree)
|
|
212
196
|
.filter((route) => route.path !== "")
|
|
213
197
|
.sort((left, right) => left.path.localeCompare(right.path));
|
|
@@ -260,7 +244,6 @@ function serverProxySource(instance: RouteInstanceSpec, includeRootCatchAll: boo
|
|
|
260
244
|
|
|
261
245
|
export function createRoutesPlugin(options: CreateRoutesPluginOptions): Bun.BunPlugin {
|
|
262
246
|
const routeFilesBySpecifier = new Map<string, RouteModuleInfo>();
|
|
263
|
-
const routeFilesByResolvedPath = new Map<string, RouteModuleInfo>();
|
|
264
247
|
const registryVirtualPath = join(
|
|
265
248
|
resolve(primaryInstance(options.instances).pagesDir),
|
|
266
249
|
".furin-routes-registry.ts?furin-virtual"
|
|
@@ -328,29 +311,15 @@ export function createRoutesPlugin(options: CreateRoutesPluginOptions): Bun.BunP
|
|
|
328
311
|
}
|
|
329
312
|
return { contents, loader: "ts" };
|
|
330
313
|
});
|
|
314
|
+
// Route files resolve to their real path so the file-namespace server
|
|
315
|
+
// transforms apply and the bundle keeps one copy of each route module.
|
|
331
316
|
build.onResolve({ filter: ROUTE_FILE_FILTER }, ({ path }) => {
|
|
332
317
|
const routeFile = routeFilesBySpecifier.get(path);
|
|
333
318
|
if (!routeFile) {
|
|
334
319
|
throw new Error(`[furin] Unknown route module: ${path}`);
|
|
335
320
|
}
|
|
336
|
-
|
|
337
|
-
routeFilesByResolvedPath.set(resolvedPath, routeFile);
|
|
338
|
-
return { namespace: ROUTE_FILES_NAMESPACE, path: resolvedPath };
|
|
321
|
+
return { path: routeFile.sourcePath };
|
|
339
322
|
});
|
|
340
|
-
build.onLoad(
|
|
341
|
-
{ filter: VIRTUAL_ROUTES_FILTER, namespace: ROUTE_FILES_NAMESPACE },
|
|
342
|
-
async ({ path }) => {
|
|
343
|
-
const routeFile = routeFilesByResolvedPath.get(path);
|
|
344
|
-
if (!routeFile) {
|
|
345
|
-
throw new Error(`[furin] Unknown route module: ${path}`);
|
|
346
|
-
}
|
|
347
|
-
return {
|
|
348
|
-
contents: await Bun.file(routeFile.sourcePath).text(),
|
|
349
|
-
loader: detectLoaderFromPath(routeFile.sourcePath),
|
|
350
|
-
resolveDir: dirname(routeFile.sourcePath),
|
|
351
|
-
};
|
|
352
|
-
}
|
|
353
|
-
);
|
|
354
323
|
for (const { instance, namespace, includeRootCatchAll } of instancesBySpecifier.values()) {
|
|
355
324
|
build.onLoad({ filter: VIRTUAL_ROUTES_FILTER, namespace }, () => ({
|
|
356
325
|
contents: serverProxySource(instance, includeRootCatchAll),
|