@teyik0/furin 0.3.0-alpha.1 → 0.4.0-alpha.1

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 (144) hide show
  1. package/dist/adapter/bun.d.ts +1 -1
  2. package/dist/build/client.d.ts +2 -2
  3. package/dist/build/entry-template.d.ts +4 -0
  4. package/dist/build/entry-template.ts +17 -3
  5. package/dist/build/index.d.ts +1 -1
  6. package/dist/build/index.js +8288 -6629
  7. package/dist/build/route-types.d.ts +2 -22
  8. package/dist/build/shared.d.ts +1 -1
  9. package/dist/build/ssg-cache.d.ts +1 -1
  10. package/dist/build/types.d.ts +1 -1
  11. package/dist/cli/index.js +7862 -6168
  12. package/dist/client/boundaries.d.ts +2 -0
  13. package/dist/client/define-route.d.ts +35 -0
  14. package/dist/client/document.d.ts +26 -0
  15. package/dist/client/hmr.d.ts +10 -0
  16. package/dist/client/internal/runtime-types.d.ts +3 -1
  17. package/dist/client/link.js +1177 -894
  18. package/dist/client/router/index.d.ts +1 -1
  19. package/dist/client/router/link-utils.d.ts +9 -0
  20. package/dist/client/router/search/index.d.ts +3 -7
  21. package/dist/client/router/types.d.ts +32 -24
  22. package/dist/client.d.ts +4 -159
  23. package/dist/client.js +183 -21
  24. package/dist/config.d.ts +8 -8
  25. package/dist/config.js +8 -8
  26. package/dist/define-route.d.ts +1355 -0
  27. package/dist/furin.d.ts +17 -33
  28. package/dist/furin.js +13444 -10301
  29. package/dist/plugin/index.js +953 -244
  30. package/dist/plugin/route-config-autofix.d.ts +31 -0
  31. package/dist/plugin/routes.d.ts +27 -0
  32. package/dist/routes.d.ts +6 -0
  33. package/dist/routes.js +1 -0
  34. package/dist/rsc/build/index.d.ts +1 -1
  35. package/dist/rsc.js +3 -3
  36. package/dist/server/dev-page-plugin.d.ts +7 -5
  37. package/dist/server/devtools/instrumentation.d.ts +2 -2
  38. package/dist/server/devtools/instrumentation.production.d.ts +2 -2
  39. package/dist/server/devtools/plugin.d.ts +2 -2
  40. package/dist/server/internal.d.ts +3 -0
  41. package/dist/server/logger.d.ts +4 -0
  42. package/dist/server/render/assemble.d.ts +0 -9
  43. package/dist/server/render/document.d.ts +4 -0
  44. package/dist/server/render/element.d.ts +2 -1
  45. package/dist/server/render/index.d.ts +1 -1
  46. package/dist/server/render/index.ts +0 -1
  47. package/dist/server/render/isr.d.ts +1 -1
  48. package/dist/server/render/loaders.d.ts +1 -1
  49. package/dist/server/render/not-found.d.ts +1 -1
  50. package/dist/server/render/ppr-route.d.ts +1 -1
  51. package/dist/server/render/ssg.d.ts +1 -1
  52. package/dist/server/render/ssr.d.ts +7 -6
  53. package/dist/server/render/template.d.ts +4 -0
  54. package/dist/server/router/defined-route.d.ts +24 -0
  55. package/dist/server/router/hmr.d.ts +16 -8
  56. package/dist/server/router/patterns.d.ts +6 -0
  57. package/dist/server/router/plugin.d.ts +4 -3
  58. package/dist/server/router/schema-merge.d.ts +2 -2
  59. package/dist/server/router/schemas.d.ts +5 -5
  60. package/dist/server/router/source-version.d.ts +2 -0
  61. package/dist/server/router/types.d.ts +1 -0
  62. package/dist/server/sync/index.js +961 -806
  63. package/dist/server/sync/postgres/migrate.js +3 -2
  64. package/dist/shared/await.d.ts +6 -7
  65. package/dist/shared/elysia-contract.d.ts +41 -0
  66. package/dist/shared/route-map.d.ts +5 -0
  67. package/dist/shared/utils/index.d.ts +1 -3
  68. package/package.json +44 -41
  69. package/src/adapter/bun.ts +42 -22
  70. package/src/adapter/package.ts +20 -14
  71. package/src/adapter/static.ts +4 -3
  72. package/src/build/client.ts +20 -3
  73. package/src/build/entry-template.ts +17 -3
  74. package/src/build/hydrate.ts +98 -28
  75. package/src/build/index.ts +2 -2
  76. package/src/build/route-types.ts +19 -114
  77. package/src/build/shared.ts +1 -1
  78. package/src/build/ssg-cache.ts +2 -5
  79. package/src/build/types.ts +1 -1
  80. package/src/cli/config.ts +3 -3
  81. package/src/cli/index.ts +7 -7
  82. package/src/client/boundaries.tsx +9 -1
  83. package/src/client/define-route.ts +48 -0
  84. package/src/client/document.tsx +165 -0
  85. package/src/client/hmr.ts +40 -0
  86. package/src/client/internal/runtime-types.ts +3 -1
  87. package/src/client/link.tsx +21 -6
  88. package/src/client/router/index.ts +1 -0
  89. package/src/client/router/link-utils.ts +26 -0
  90. package/src/client/router/provider.tsx +25 -2
  91. package/src/client/router/search/index.ts +4 -12
  92. package/src/client/router/types.ts +50 -24
  93. package/src/client.ts +14 -316
  94. package/src/config.ts +10 -10
  95. package/src/define-route.ts +959 -0
  96. package/src/devtools/devtools-element.js +11 -10
  97. package/src/furin.ts +303 -53
  98. package/src/plugin/route-config-autofix.ts +1140 -0
  99. package/src/plugin/routes.ts +891 -0
  100. package/src/plugin/transform-client.ts +132 -266
  101. package/src/plugin/transform-isomorphic.ts +1 -1
  102. package/src/routes.ts +6 -0
  103. package/src/rsc/build/index.ts +1 -1
  104. package/src/server/auto-invalidate/registry.ts +2 -2
  105. package/src/server/dev-page-plugin.ts +31 -12
  106. package/src/server/devtools/instrumentation.production.ts +2 -2
  107. package/src/server/devtools/instrumentation.ts +2 -2
  108. package/src/server/devtools/plugin.ts +5 -3
  109. package/src/server/instance.ts +3 -3
  110. package/src/server/internal.ts +3 -0
  111. package/src/server/logger.ts +21 -0
  112. package/src/server/render/assemble.ts +0 -41
  113. package/src/server/render/document.tsx +25 -0
  114. package/src/server/render/element.tsx +13 -1
  115. package/src/server/render/index.ts +0 -1
  116. package/src/server/render/isr.ts +31 -10
  117. package/src/server/render/loaders.ts +31 -6
  118. package/src/server/render/not-found.ts +51 -27
  119. package/src/server/render/ppr-route.ts +1 -1
  120. package/src/server/render/ssg.ts +1 -1
  121. package/src/server/render/ssr.ts +271 -113
  122. package/src/server/render/template.ts +91 -1
  123. package/src/server/router/defined-route.ts +110 -0
  124. package/src/server/router/discovery.ts +129 -29
  125. package/src/server/router/hmr.ts +111 -40
  126. package/src/server/router/patterns.ts +40 -12
  127. package/src/server/router/plugin.ts +63 -46
  128. package/src/server/router/schema-merge.ts +4 -14
  129. package/src/server/router/schemas.ts +11 -8
  130. package/src/server/router/source-version.ts +16 -0
  131. package/src/server/router/types.ts +2 -0
  132. package/src/server/sync/postgres/migrate.ts +3 -2
  133. package/src/server/sync/response.ts +14 -10
  134. package/src/shared/await.tsx +6 -7
  135. package/src/shared/elysia-contract.ts +63 -0
  136. package/src/shared/route-map.ts +37 -0
  137. package/src/shared/utils/index.ts +2 -20
  138. package/dist/build/server-routes-entry.d.ts +0 -13
  139. package/dist/build/server-routes-entry.ts +0 -30
  140. package/dist/server/router/index.d.ts +0 -7
  141. package/dist/server/router/index.js +0 -27
  142. package/dist/server/router/index.ts +0 -28
  143. package/src/build/server-routes-entry.ts +0 -30
  144. package/src/server/router/index.ts +0 -28
@@ -1,12 +1,6 @@
1
1
  import MagicString from "magic-string";
2
- import type {
3
- CallExpression,
4
- ImportDeclaration,
5
- ObjectExpression,
6
- ObjectProperty,
7
- Program,
8
- } from "yuku-parser";
9
- import { walk } from "yuku-parser";
2
+ import { walk } from "yuku-ast";
3
+ import type { ImportDeclaration, Program } from "yuku-parser";
10
4
  import { detectLangFromPath, unwrapTSExpression } from "../server/lang-detect.ts";
11
5
  import { parseSource } from "../shared/parser.ts";
12
6
  import type { AstNode } from "../shared/utils/ast-walk.ts";
@@ -14,16 +8,9 @@ import { hasShadowingDeclaration } from "./binding-scope.ts";
14
8
  import { deadCodeElimination } from "./dead-code-elimination.ts";
15
9
  import { transformIsomorphicFunctions } from "./transform-isomorphic.ts";
16
10
 
17
- // loader: data fetching (runs on server only)
18
- // query / params: Elysia TypeBox schemas — validated server-side, not used in browser
19
- const SERVER_ONLY_PROPERTIES = new Set([
20
- "loader",
21
- "requestLoader",
22
- "query",
23
- "params",
24
- "staticParams",
25
- ]);
26
11
  const FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
12
+ const FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
13
+ const SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
27
14
 
28
15
  interface TransformResult {
29
16
  code: string;
@@ -31,24 +18,15 @@ interface TransformResult {
31
18
  removedServerCode: boolean;
32
19
  }
33
20
 
34
- interface RouteTransformBindings {
35
- createRouteNames: Set<string>;
36
- routeNames: Set<string>;
37
- }
38
-
39
- // ---------------------------------------------------------------------------
40
- // Check if a CallExpression is createRoute() or route.page()
41
- // ---------------------------------------------------------------------------
42
- function isFurinClientModule(source: unknown): boolean {
43
- return typeof source === "string" && FURIN_CLIENT_MODULES.has(source);
44
- }
45
-
46
- function isRelativeModule(source: unknown): boolean {
47
- return typeof source === "string" && source.startsWith(".");
21
+ function isFurinRouteModule(source: unknown): source is string {
22
+ return (
23
+ typeof source === "string" &&
24
+ (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES.has(source))
25
+ );
48
26
  }
49
27
 
50
- function importedName(spec: AstNode): string | null {
51
- const { imported } = spec;
28
+ function importedName(specifier: AstNode): string | null {
29
+ const { imported } = specifier;
52
30
  if (!imported || typeof imported !== "object") {
53
31
  return null;
54
32
  }
@@ -62,8 +40,8 @@ function importedName(spec: AstNode): string | null {
62
40
  return null;
63
41
  }
64
42
 
65
- function localName(spec: AstNode): string | null {
66
- const { local } = spec;
43
+ function localName(specifier: AstNode): string | null {
44
+ const { local } = specifier;
67
45
  if (!local || typeof local !== "object") {
68
46
  return null;
69
47
  }
@@ -71,261 +49,144 @@ function localName(spec: AstNode): string | null {
71
49
  return node.type === "Identifier" && typeof node.name === "string" ? node.name : null;
72
50
  }
73
51
 
74
- function addImportedBinding(
75
- source: unknown,
76
- spec: AstNode,
77
- bindings: RouteTransformBindings
78
- ): void {
79
- if (spec.type !== "ImportSpecifier" || spec.importKind === "type") {
80
- return;
81
- }
82
- const imported = importedName(spec);
83
- const local = localName(spec);
84
- if (!local) {
85
- return;
86
- }
87
- if (isFurinClientModule(source) && imported === "createRoute") {
88
- bindings.createRouteNames.add(local);
89
- }
90
- if (isRelativeModule(source) && imported === "route") {
91
- bindings.routeNames.add(local);
92
- }
93
- }
94
-
95
- function collectImportedBindings(program: Program): RouteTransformBindings {
96
- const bindings = {
97
- createRouteNames: new Set<string>(),
98
- routeNames: new Set<string>(),
99
- };
100
-
101
- for (const stmt of program.body) {
102
- if (stmt.type !== "ImportDeclaration") {
52
+ function collectDefineRouteBindings(program: Program): Set<string> {
53
+ const bindings = new Set<string>();
54
+ for (const statement of program.body) {
55
+ if (statement.type !== "ImportDeclaration") {
103
56
  continue;
104
57
  }
105
- const decl = stmt as unknown as ImportDeclaration;
106
- if (decl.importKind === "type") {
58
+ const declaration = statement as unknown as ImportDeclaration;
59
+ if (declaration.importKind === "type") {
107
60
  continue;
108
61
  }
109
- const source = decl.source.value;
110
-
111
- for (const spec of decl.specifiers as unknown as AstNode[]) {
112
- addImportedBinding(source, spec, bindings);
62
+ const source = declaration.source.value;
63
+ if (!isFurinRouteModule(source)) {
64
+ continue;
113
65
  }
114
- }
115
-
116
- return bindings;
117
- }
118
-
119
- function isCreateRouteCall(
120
- node: CallExpression,
121
- bindings: RouteTransformBindings,
122
- ancestors: AstNode[]
123
- ): boolean {
124
- return (
125
- node.callee.type === "Identifier" &&
126
- bindings.createRouteNames.has(node.callee.name) &&
127
- !hasShadowingDeclaration(node.callee.name, ancestors)
128
- );
129
- }
130
-
131
- function isCreateRouteExpression(
132
- node: unknown,
133
- bindings: RouteTransformBindings,
134
- ancestors: AstNode[]
135
- ): boolean {
136
- if (!node || typeof node !== "object") {
137
- return false;
138
- }
139
- const expression = unwrapTSExpression(node as { type: string }) as AstNode;
140
- return (
141
- expression.type === "CallExpression" &&
142
- isCreateRouteCall(expression as unknown as CallExpression, bindings, ancestors)
143
- );
144
- }
145
-
146
- function collectLocalRouteBindings(program: Program, bindings: RouteTransformBindings): void {
147
- walk(program, {
148
- VariableDeclarator(node, context) {
149
- if (node.type !== "VariableDeclarator") {
150
- return;
66
+ for (const specifier of declaration.specifiers as unknown as AstNode[]) {
67
+ if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") {
68
+ continue;
151
69
  }
152
- const { id, init } = node;
153
- if (!id || typeof id !== "object") {
154
- return;
155
- }
156
- const identifier = id as unknown as AstNode;
157
- if (identifier.type !== "Identifier" || typeof identifier.name !== "string") {
158
- return;
70
+ const imported = importedName(specifier);
71
+ if (imported !== "defineRoute" && imported !== "defineRootRoute") {
72
+ continue;
159
73
  }
160
- if (isCreateRouteExpression(init, bindings, context.ancestors() as AstNode[])) {
161
- bindings.routeNames.add(identifier.name);
74
+ const local = localName(specifier);
75
+ if (local) {
76
+ bindings.add(local);
162
77
  }
163
- },
164
- });
165
- }
166
-
167
- function collectRouteTransformBindings(program: Program): RouteTransformBindings {
168
- const bindings = collectImportedBindings(program);
169
- collectLocalRouteBindings(program, bindings);
170
- return bindings;
171
- }
172
-
173
- function isRoutePageCall(
174
- node: CallExpression,
175
- bindings: RouteTransformBindings,
176
- ancestors: AstNode[]
177
- ): boolean {
178
- const { callee } = node;
179
- if (
180
- callee.type === "MemberExpression" &&
181
- !callee.computed &&
182
- callee.property.type === "Identifier" &&
183
- callee.property.name === "page"
184
- ) {
185
- const object = unwrapTSExpression(callee.object);
186
- if (
187
- object.type === "Identifier" &&
188
- bindings.routeNames.has(object.name) &&
189
- !hasShadowingDeclaration(object.name, ancestors)
190
- ) {
191
- return true;
192
78
  }
193
- return isCreateRouteExpression(object, bindings, ancestors);
194
79
  }
195
- return false;
80
+ return bindings;
196
81
  }
197
82
 
198
- function isTargetCall(
199
- node: CallExpression,
200
- bindings: RouteTransformBindings,
201
- ancestors: AstNode[]
83
+ function rewriteClientImports(
84
+ source: MagicString,
85
+ program: Program,
86
+ bindings: Set<string>
202
87
  ): boolean {
203
- return isCreateRouteCall(node, bindings, ancestors) || isRoutePageCall(node, bindings, ancestors);
204
- }
205
-
206
- function isObjectExpressionNode(node: { type: string }): node is ObjectExpression {
207
- return node.type === "ObjectExpression";
208
- }
209
-
210
- function staticPropertyName(property: ObjectProperty): string | undefined {
211
- const { key } = property;
212
- if (key.type === "Identifier" && !property.computed && typeof key.name === "string") {
213
- return key.name;
214
- }
215
- if (key.type === "Literal" && typeof key.value === "string") {
216
- return key.value;
217
- }
218
- }
219
-
220
- function assertRoutePropertiesAreStaticallySafe(obj: ObjectExpression): void {
221
- for (const property of obj.properties) {
222
- if (property.type !== "Property") {
223
- throw new Error(
224
- "[furin] Route configuration spreads are not allowed because server-only properties cannot be stripped safely."
225
- );
88
+ let rewritten = false;
89
+ for (const statement of program.body) {
90
+ if (statement.type !== "ImportDeclaration") {
91
+ continue;
226
92
  }
227
- if (property.computed && staticPropertyName(property) === undefined) {
228
- throw new Error(
229
- "[furin] A dynamic computed property in route configuration cannot be stripped safely."
230
- );
93
+ const declaration = statement as unknown as ImportDeclaration;
94
+ const moduleName = declaration.source.value;
95
+ if (typeof moduleName !== "string" || !FURIN_SERVER_MODULES.has(moduleName)) {
96
+ continue;
231
97
  }
98
+ const importsClientValue = (declaration.specifiers as unknown as AstNode[]).some(
99
+ (specifier) => {
100
+ const local = localName(specifier);
101
+ const imported = importedName(specifier);
102
+ return (
103
+ (local !== null && bindings.has(local)) ||
104
+ imported === "HeadContent" ||
105
+ imported === "Scripts"
106
+ );
107
+ }
108
+ );
109
+ if (!importsClientValue) {
110
+ continue;
111
+ }
112
+ const clientModule = moduleName === "furin" ? "furin/client" : "@teyik0/furin/client";
113
+ source.update(declaration.source.start + 1, declaration.source.end - 1, clientModule);
114
+ rewritten = true;
232
115
  }
116
+ return rewritten;
233
117
  }
234
118
 
235
- // ---------------------------------------------------------------------------
236
- // Remove server-only properties from an ObjectExpression using MagicString.
237
- // Returns true if any property was removed.
238
- // ---------------------------------------------------------------------------
239
- function removeServerProperties(s: MagicString, source: string, obj: ObjectExpression): boolean {
240
- assertRoutePropertiesAreStaticallySafe(obj);
241
-
242
- const toRemove = obj.properties.filter((p): p is ObjectProperty => {
243
- if (p.type !== "Property") {
244
- return false;
245
- }
246
- const name = staticPropertyName(p);
247
- return name !== undefined && SERVER_ONLY_PROPERTIES.has(name);
248
- });
249
- if (toRemove.length === 0) {
250
- return false;
119
+ function asAstNode(node: unknown): AstNode | null {
120
+ if (!node || typeof node !== "object" || !("type" in node)) {
121
+ return null;
251
122
  }
123
+ return unwrapTSExpression(node as { type: string }) as AstNode;
124
+ }
252
125
 
253
- for (const prop of toRemove) {
254
- // Find the range to remove including the trailing comma + whitespace.
255
- let removeEnd = prop.end;
256
- // Skip comma and whitespace after the property
257
- while (
258
- removeEnd < source.length &&
259
- (source[removeEnd] === "," ||
260
- source[removeEnd] === " " ||
261
- source[removeEnd] === "\n" ||
262
- source[removeEnd] === "\r" ||
263
- source[removeEnd] === "\t")
264
- ) {
265
- if (source[removeEnd] === ",") {
266
- removeEnd += 1;
267
- break;
268
- }
269
- removeEnd += 1;
270
- }
271
-
272
- // Also remove leading whitespace (indentation before the property)
273
- let removeStart = prop.start;
274
- while (
275
- removeStart > 0 &&
276
- (source[removeStart - 1] === " " || source[removeStart - 1] === "\t")
277
- ) {
278
- removeStart -= 1;
126
+ function chainRootIsDefineRoute(
127
+ node: unknown,
128
+ bindings: Set<string>,
129
+ ancestors: AstNode[]
130
+ ): boolean {
131
+ let current = asAstNode(node);
132
+ while (current) {
133
+ if (current.type === "MemberExpression") {
134
+ current = asAstNode(current.object);
135
+ continue;
279
136
  }
280
- // If there's a newline before the leading whitespace, consume it too
281
- if (removeStart > 0 && source[removeStart - 1] === "\n") {
282
- removeStart -= 1;
283
- if (removeStart > 0 && source[removeStart - 1] === "\r") {
284
- removeStart -= 1;
285
- }
137
+ if (current.type === "CallExpression") {
138
+ current = asAstNode(current.callee);
139
+ continue;
286
140
  }
287
-
288
- s.remove(removeStart, removeEnd);
141
+ return (
142
+ current.type === "Identifier" &&
143
+ typeof current.name === "string" &&
144
+ bindings.has(current.name) &&
145
+ !hasShadowingDeclaration(current.name, ancestors)
146
+ );
289
147
  }
290
-
291
- return true;
148
+ return false;
292
149
  }
293
150
 
294
- // TypeScript-specific node types that introduce a type-only scope. Any
295
- // ---------------------------------------------------------------------------
296
- // Remove server-only properties from createRoute() / route.page()
297
- // calls found anywhere in the AST.
298
- // ---------------------------------------------------------------------------
299
- function removeServerExports(s: MagicString, source: string, program: Program): boolean {
300
- let removedServerCode = false;
301
- const bindings = collectRouteTransformBindings(program);
151
+ function removeChainedServerCalls(
152
+ source: MagicString,
153
+ program: Program,
154
+ bindings: Set<string>
155
+ ): boolean {
156
+ let transformed = rewriteClientImports(source, program, bindings);
302
157
 
303
158
  walk(program, {
304
159
  CallExpression(call, context) {
305
- if (!isTargetCall(call, bindings, context.ancestors() as AstNode[])) {
160
+ const callee = asAstNode(call.callee);
161
+ if (
162
+ callee?.type !== "MemberExpression" ||
163
+ callee.computed === true ||
164
+ !callee.property ||
165
+ typeof callee.property !== "object"
166
+ ) {
306
167
  return;
307
168
  }
308
- // Unwrap `createRoute({...} as Config)` / `route.page({...} satisfies Opts)` etc.
309
- const [firstArg] = call.arguments;
310
- if (!firstArg) {
169
+ const property = callee.property as AstNode;
170
+ if (
171
+ property.type !== "Identifier" ||
172
+ typeof property.name !== "string" ||
173
+ !SERVER_ONLY_METHODS.has(property.name) ||
174
+ !chainRootIsDefineRoute(callee.object, bindings, context.ancestors() as AstNode[])
175
+ ) {
311
176
  return;
312
177
  }
313
- const arg = unwrapTSExpression(firstArg);
314
- if (!isObjectExpressionNode(arg)) {
178
+ const object = asAstNode(callee.object);
179
+ if (!object) {
315
180
  return;
316
181
  }
317
- if (removeServerProperties(s, source, arg)) {
318
- removedServerCode = true;
319
- }
182
+ source.remove(object.end, call.end);
183
+ transformed = true;
320
184
  },
321
185
  });
322
-
323
- return removedServerCode;
186
+ return transformed;
324
187
  }
325
188
 
326
189
  export function transformForClient(code: string, filename: string): TransformResult {
327
- // .d.ts files have no runtime code — yuku rejects parsing them as modules.
328
- // Treat as a passthrough so callers don't need to pre-filter.
329
190
  const lang = detectLangFromPath(filename);
330
191
  if (lang === "dts") {
331
192
  return { code, map: null, removedServerCode: false };
@@ -333,30 +194,35 @@ export function transformForClient(code: string, filename: string): TransformRes
333
194
 
334
195
  const isomorphicResult = transformIsomorphicFunctions(code, filename, "client");
335
196
  const clientSource = isomorphicResult.code;
336
-
337
- // Pass 1 — yuku-parser: parse TS/TSX/JS/JSX directly to ESTree AST with
338
- // span offsets calibrated against `code` itself (no transpile step).
339
- const { program, diagnostics } = parseSource(clientSource, lang);
340
- const firstError = diagnostics.find((d) => d.severity === "error");
197
+ const { diagnostics, program } = parseSource(clientSource, lang);
198
+ const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
341
199
  if (firstError) {
342
200
  throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
343
201
  }
344
202
 
345
- // Pass 2 — MagicString: surgically remove server-only properties.
346
- let s = new MagicString(clientSource);
347
- const removedRouteCode = removeServerExports(s, clientSource, program);
203
+ let source = new MagicString(clientSource);
204
+ const routeBindings = collectDefineRouteBindings(program);
205
+ const removedRouteCode = removeChainedServerCalls(source, program, routeBindings);
348
206
  const removedServerCode = isomorphicResult.transformed || removedRouteCode;
349
-
350
- // Pass 3 — DCE: prune imports that are no longer referenced.
351
- // deadCodeElimination returns a fresh MagicString keyed on the current
352
- // output so its internal AST offsets remain consistent.
353
207
  if (removedServerCode) {
354
- s = deadCodeElimination(s, code, lang);
208
+ source = deadCodeElimination(source, code, lang);
209
+ }
210
+ if (routeBindings.size > 0) {
211
+ source.append(`
212
+ if (import.meta.hot) {
213
+ import.meta.hot.accept((updatedModule) => {
214
+ const updatedRoute = updatedModule?.route;
215
+ if (updatedRoute?.component) {
216
+ window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component);
217
+ }
218
+ });
219
+ }
220
+ `);
355
221
  }
356
222
 
357
223
  return {
358
- code: s.toString(),
359
- map: s.generateMap({ includeContent: true, source: filename }),
224
+ code: source.toString(),
225
+ map: source.generateMap({ includeContent: true, source: filename }),
360
226
  removedServerCode,
361
227
  };
362
228
  }
@@ -1,6 +1,6 @@
1
1
  import MagicString from "magic-string";
2
+ import { walk } from "yuku-ast";
2
3
  import type { CallExpression, ImportDeclaration, Program } from "yuku-parser";
3
- import { walk } from "yuku-parser";
4
4
  import {
5
5
  detectLangFromPath,
6
6
  detectLoaderFromPath,
package/src/routes.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Typecheck fallback for the virtual `furin/routes` module.
3
+ * The generated furin-env.d.ts augments this interface with application routes.
4
+ */
5
+ // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmented by generated route types
6
+ export interface RouteMap {}
@@ -3,7 +3,7 @@ import { basename, join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { runBunBuild } from "../../build/bun-build.ts";
5
5
  import { isomorphicTransformPlugin } from "../../plugin/transform-isomorphic.ts";
6
- import type { ResolvedRoute, RootLayout } from "../../server/router/index.ts";
6
+ import type { ResolvedRoute, RootLayout } from "../../server/router/types.ts";
7
7
  import { assertInstalledRscVersions } from "../version.ts";
8
8
  import { environmentGuardPlugin } from "./environment.ts";
9
9
 
@@ -74,9 +74,9 @@ export const autoInvalidateRegistry: Pick<
74
74
  AutoInvalidateRegistry,
75
75
  "registerLoaderTags" | "pathsForTags" | "unregisterPath" | "reset"
76
76
  > = {
77
+ pathsForTags: (tags) => instanceAutoInvalidateRegistry().pathsForTags(tags),
77
78
  registerLoaderTags: (urlPath, tags) =>
78
79
  instanceAutoInvalidateRegistry().registerLoaderTags(urlPath, tags),
79
- pathsForTags: (tags) => instanceAutoInvalidateRegistry().pathsForTags(tags),
80
- unregisterPath: (urlPath) => instanceAutoInvalidateRegistry().unregisterPath(urlPath),
81
80
  reset: () => instanceAutoInvalidateRegistry().reset(),
81
+ unregisterPath: (urlPath) => instanceAutoInvalidateRegistry().unregisterPath(urlPath),
82
82
  };
@@ -16,16 +16,18 @@
16
16
  * stale module while the client received fresh HMR code, causing a React
17
17
  * hydration mismatch.
18
18
  *
19
- * Solution: the caller appends `?furin-server&t=<timestamp>` to the import
20
- * specifier (a new timestamp on every request). `onResolve` preserves the
21
- * `?t=...` fragment in the resolved path so each request gets a unique
22
- * `(namespace, path)` key and Bun always calls `onLoad` fresh.
19
+ * Solution: the caller appends `?furin-server&t=<source-version>` to the import
20
+ * specifier. `onResolve` preserves the `?t=...` fragment in the resolved path,
21
+ * so Bun calls `onLoad` again after an edit without allocating a new permanent
22
+ * ESM registry entry for every request.
23
23
  *
24
24
  * ## Relative import rewriting
25
25
  *
26
26
  * Modules in a virtual namespace cannot resolve relative specifiers on their
27
27
  * own (there is no real directory context). We rewrite every `./` / `../`
28
- * path to an absolute one before returning the source.
28
+ * path to an absolute one before returning the source. Local JS/TS dependencies
29
+ * use the same source-version rule as routes, so refreshing a route does not
30
+ * retain an old helper module. Shared dependencies keep one identity per version.
29
31
  *
30
32
  * ## Bare specifier rewriting
31
33
  *
@@ -55,6 +57,7 @@ import { dirname, resolve } from "node:path";
55
57
  import { fileURLToPath } from "node:url";
56
58
  import { transformIsomorphicFunctions } from "../plugin/transform-isomorphic.ts";
57
59
  import { invalidateDevLoaderCacheBySource } from "./cache/dev-loader.ts";
60
+ import { routeModuleSourceVersion } from "./router/source-version.ts";
58
61
 
59
62
  // Matches ?furin-server with an optional &t=<ms> cache-buster.
60
63
  const FURIN_SERVER_FILTER = /\?furin-server(?:&t=\d+)?$/;
@@ -215,6 +218,14 @@ const RELATIVE_SPECIFIER_RE = /(?:from|import)\s+["'](\.\.?\/[^"']+)["']/g;
215
218
 
216
219
  /** @internal exported for testing */
217
220
  export function rewriteRelativeImports(source: string, dir: string): string {
221
+ return rewriteRelativeImportsWithVersion(source, dir, false);
222
+ }
223
+
224
+ function rewriteRelativeImportsWithVersion(
225
+ source: string,
226
+ dir: string,
227
+ versioned: boolean
228
+ ): string {
218
229
  return source.replace(RELATIVE_SPECIFIER_RE, (match, relPath, offset) => {
219
230
  // Skip matches that appear on a comment line (// ...)
220
231
  const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
@@ -222,9 +233,16 @@ export function rewriteRelativeImports(source: string, dir: string): string {
222
233
  if (linePrefix.startsWith("//") || linePrefix.startsWith("*")) {
223
234
  return match;
224
235
  }
225
- const absPath = toImportSpecifier(resolve(dir, relPath));
236
+ let absPath = toImportSpecifier(resolve(dir, relPath));
237
+ if (versioned) {
238
+ absPath = toImportSpecifier(Bun.resolveSync(relPath, dir));
239
+ }
240
+ const specifier =
241
+ versioned && getSourceLoader(absPath) !== null
242
+ ? `${absPath}?furin-server&t=${routeModuleSourceVersion(absPath)}`
243
+ : absPath;
226
244
  const keyword = match.startsWith("import") ? "import" : "from";
227
- return `${keyword} ${JSON.stringify(absPath)}`;
245
+ return `${keyword} ${JSON.stringify(specifier)}`;
228
246
  });
229
247
  }
230
248
 
@@ -328,7 +346,7 @@ export function transformDevSource(
328
346
  const dir = dirname(filePath);
329
347
  const serverSource = transformIsomorphicFunctions(raw, filePath, "server").code;
330
348
  const sourceForTranspile = options.rewriteRelativeImports
331
- ? rewriteRelativeImports(serverSource, dir)
349
+ ? rewriteRelativeImportsWithVersion(serverSource, dir, true)
332
350
  : serverSource;
333
351
  const transpiler = new Bun.Transpiler({ loader });
334
352
  const transpiled = transpiler.transformSync(sourceForTranspile, loader);
@@ -351,8 +369,8 @@ export function registerDevPagePlugin(): void {
351
369
  name: "furin-dev-page-loader",
352
370
  setup(build) {
353
371
  /**
354
- * Strip `?furin-server` but keep `?t=<ms>` in the resolved path so
355
- * each request gets a unique module identity, bypassing Bun's cache.
372
+ * Strip `?furin-server` but keep `?t=<source-version>` in the resolved
373
+ * path so each edited version gets a new module identity.
356
374
  */
357
375
  build.onResolve({ filter: FURIN_SERVER_FILTER }, (args) => {
358
376
  const tMatch = T_PARAM_RE.exec(args.path);
@@ -405,8 +423,9 @@ export function registerDevPagePlugin(): void {
405
423
  });
406
424
 
407
425
  /**
408
- * Read the page file fresh from disk. The `?t=...` suffix guarantees
409
- * this handler is called on every request; strip it before file I/O.
426
+ * Read the page file fresh from disk. The `?t=...` suffix guarantees
427
+ * this handler is called for each edited source version; strip it before
428
+ * file I/O.
410
429
  *
411
430
  * ## Why we pre-transpile with Bun.Transpiler
412
431
  *
@@ -1,5 +1,5 @@
1
1
  import { type AnyElysia, Elysia } from "elysia";
2
- import type { ResolvedRoute } from "../router/types.ts";
2
+ import type { ResolvedRoutesSource } from "../router/types.ts";
3
3
 
4
4
  interface CacheAccessInput {
5
5
  cache: "isr-loader" | "ssg-loader";
@@ -69,7 +69,7 @@ export function instrumentationLoggerExclusions(_prefix: string): string[] {
69
69
  }
70
70
 
71
71
  export function createInstrumentationPlugin(
72
- _routes: ResolvedRoute[],
72
+ _routes: ResolvedRoutesSource,
73
73
  _syncStreamPath: string | undefined
74
74
  ): AnyElysia {
75
75
  return new Elysia({ name: "furin-production-instrumentation" });
@@ -1,6 +1,6 @@
1
1
  import type { AnyElysia } from "elysia";
2
2
  import type { DevtoolsServerEventInput } from "../../devtools/protocol.ts";
3
- import type { ResolvedRoute } from "../router/types.ts";
3
+ import type { ResolvedRoutesSource } from "../router/types.ts";
4
4
  import { appendDevtoolsEvent } from "./hub.ts";
5
5
  import { createDevtoolsPlugin } from "./plugin.ts";
6
6
  import {
@@ -55,7 +55,7 @@ export function instrumentationLoggerExclusions(prefix: string): string[] {
55
55
  }
56
56
 
57
57
  export function createInstrumentationPlugin(
58
- routes: ResolvedRoute[],
58
+ routes: ResolvedRoutesSource,
59
59
  syncStreamPath: string | undefined
60
60
  ): AnyElysia {
61
61
  return createDevtoolsPlugin(routes, syncStreamPath);