@teyik0/furin 0.2.0-alpha.5 → 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 (282) hide show
  1. package/README.md +2 -3
  2. package/dist/adapter/bun.d.ts +1 -1
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/bun-build.d.ts +3 -0
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/entry-template.d.ts +6 -0
  7. package/dist/build/entry-template.ts +20 -3
  8. package/dist/build/hydrate.d.ts +1 -1
  9. package/dist/build/index.d.ts +1 -1
  10. package/dist/build/index.js +9363 -5827
  11. package/dist/build/production-instrumentation.d.ts +1 -0
  12. package/dist/build/route-types.d.ts +3 -23
  13. package/dist/build/shared.d.ts +1 -1
  14. package/dist/build/ssg-cache.d.ts +1 -1
  15. package/dist/build/types.d.ts +2 -1
  16. package/dist/cli/index.js +9467 -5870
  17. package/dist/client/boundaries.d.ts +6 -4
  18. package/dist/client/define-route.d.ts +35 -0
  19. package/dist/client/document.d.ts +26 -0
  20. package/dist/client/hmr.d.ts +10 -0
  21. package/dist/client/internal/runtime-types.d.ts +32 -0
  22. package/dist/client/link.d.ts +2 -1
  23. package/dist/client/link.js +1884 -1227
  24. package/dist/client/router/boundary-tree.d.ts +1 -1
  25. package/dist/client/router/index.d.ts +2 -2
  26. package/dist/client/router/link-utils.d.ts +14 -1
  27. package/dist/client/router/search/index.d.ts +3 -7
  28. package/dist/client/router/sync-catch-up.d.ts +4 -4
  29. package/dist/client/router/types.d.ts +34 -26
  30. package/dist/client-only.d.ts +1 -0
  31. package/dist/client-only.js +1 -0
  32. package/dist/client.d.ts +11 -169
  33. package/dist/client.js +197 -36
  34. package/dist/config.d.ts +8 -8
  35. package/dist/config.js +10 -10
  36. package/dist/define-route.d.ts +1355 -0
  37. package/dist/devtools/devtools-element.d.ts +1 -0
  38. package/dist/devtools/protocol.d.ts +119 -0
  39. package/dist/furin.d.ts +24 -39
  40. package/dist/furin.js +14432 -7929
  41. package/dist/isomorphic.d.ts +18 -0
  42. package/dist/plugin/binding-scope.d.ts +2 -0
  43. package/dist/plugin/dead-code-elimination.d.ts +3 -0
  44. package/dist/plugin/index.js +1708 -489
  45. package/dist/plugin/route-config-autofix.d.ts +31 -0
  46. package/dist/plugin/routes.d.ts +27 -0
  47. package/dist/plugin/transform-client.d.ts +0 -2
  48. package/dist/plugin/transform-isomorphic.d.ts +9 -0
  49. package/dist/routes.d.ts +6 -0
  50. package/dist/routes.js +1 -0
  51. package/dist/rsc/build/environment.d.ts +2 -0
  52. package/dist/rsc/build/index.d.ts +15 -0
  53. package/dist/rsc/client-codec.d.ts +1 -0
  54. package/dist/rsc/codec.d.ts +4 -0
  55. package/dist/rsc/flight-drain.d.ts +11 -0
  56. package/dist/rsc/render-error.d.ts +17 -0
  57. package/dist/rsc/server-codec.d.ts +2 -0
  58. package/dist/rsc/server-codec.js +24 -0
  59. package/dist/rsc/shared.d.ts +30 -0
  60. package/dist/rsc/symbols.d.ts +2 -0
  61. package/dist/rsc/transport-benchmark.d.ts +13 -0
  62. package/dist/rsc/version.d.ts +7 -0
  63. package/dist/rsc-client.d.ts +4 -0
  64. package/dist/rsc-client.js +166 -0
  65. package/dist/rsc-server.d.ts +11 -0
  66. package/dist/rsc.d.ts +11 -0
  67. package/dist/rsc.js +353 -0
  68. package/dist/server/cache/index.d.ts +2 -2
  69. package/dist/server/cache/invalidation.d.ts +2 -3
  70. package/dist/server/cache/isr-ssg.d.ts +5 -1
  71. package/dist/server/cache/isr.d.ts +9 -0
  72. package/dist/server/cache/route-cache.d.ts +10 -8
  73. package/dist/server/cache/store-view.d.ts +7 -7
  74. package/dist/server/dev-page-plugin.d.ts +11 -5
  75. package/dist/server/devtools/hub.d.ts +11 -0
  76. package/dist/server/devtools/instrumentation.d.ts +22 -0
  77. package/dist/server/devtools/instrumentation.production.d.ts +44 -0
  78. package/dist/server/devtools/plugin.d.ts +3 -0
  79. package/dist/server/devtools/request-context.d.ts +6 -0
  80. package/dist/server/internal.d.ts +5 -0
  81. package/dist/server/internal.js +3 -3
  82. package/dist/server/lang-detect.d.ts +1 -0
  83. package/dist/server/logger.d.ts +4 -0
  84. package/dist/server/render/assemble.d.ts +4 -9
  85. package/dist/server/render/document.d.ts +4 -0
  86. package/dist/server/render/element.d.ts +3 -2
  87. package/dist/server/render/index.d.ts +2 -2
  88. package/dist/server/render/index.ts +6 -3
  89. package/dist/server/render/isr.d.ts +1 -1
  90. package/dist/server/render/loaders.d.ts +9 -1
  91. package/dist/server/render/not-found.d.ts +2 -2
  92. package/dist/server/render/ppr-route.d.ts +8 -0
  93. package/dist/server/render/route-frame-transport.d.ts +2 -0
  94. package/dist/server/render/shell.ts +0 -1
  95. package/dist/server/render/ssg.d.ts +1 -1
  96. package/dist/server/render/ssr.d.ts +9 -9
  97. package/dist/server/render/template.d.ts +4 -0
  98. package/dist/server/router/defined-route.d.ts +24 -0
  99. package/dist/server/router/discovery.d.ts +1 -1
  100. package/dist/server/router/hmr.d.ts +17 -9
  101. package/dist/server/router/patterns.d.ts +7 -1
  102. package/dist/server/router/plugin.d.ts +8 -10
  103. package/dist/server/router/schema-merge.d.ts +3 -0
  104. package/dist/server/router/schemas.d.ts +14 -9
  105. package/dist/server/router/source-version.d.ts +2 -0
  106. package/dist/server/router/types.d.ts +2 -1
  107. package/dist/server/runtime-env.js +2 -2
  108. package/dist/server/sync/adapter.d.ts +45 -26
  109. package/dist/server/sync/config.d.ts +5 -9
  110. package/dist/server/sync/fingerprint.d.ts +2 -1
  111. package/dist/server/sync/index.d.ts +15 -4
  112. package/dist/server/sync/index.js +3023 -0
  113. package/dist/server/sync/notifier.d.ts +18 -0
  114. package/dist/server/sync/plugin.d.ts +53 -54
  115. package/dist/server/sync/postgres/index.d.ts +19 -0
  116. package/dist/server/sync/postgres/index.js +252 -0
  117. package/dist/server/sync/postgres/migrate.d.ts +2 -0
  118. package/dist/server/sync/postgres/migrate.js +17 -0
  119. package/dist/server/sync/postgres/migration.sql +66 -0
  120. package/dist/server/sync/redis/index.d.ts +30 -0
  121. package/dist/server/sync/redis/index.js +336 -0
  122. package/dist/server/sync/redis/scripts.d.ts +4 -0
  123. package/dist/server/sync/response.d.ts +10 -1
  124. package/dist/server/sync/runtime.d.ts +6 -0
  125. package/dist/server/sync/sqlite/index.d.ts +20 -0
  126. package/dist/server/sync/sqlite/index.js +250 -0
  127. package/dist/server/sync/stream.d.ts +12 -11
  128. package/dist/server-only.d.ts +1 -0
  129. package/dist/server-only.js +1 -0
  130. package/dist/shared/await.d.ts +6 -7
  131. package/dist/shared/elysia-contract.d.ts +41 -0
  132. package/dist/shared/parser.d.ts +2 -0
  133. package/dist/shared/route-frame.d.ts +49 -0
  134. package/dist/shared/route-map.d.ts +5 -0
  135. package/dist/shared/utils/index.d.ts +1 -3
  136. package/package.json +86 -41
  137. package/src/adapter/bun.ts +113 -36
  138. package/src/adapter/package.ts +23 -15
  139. package/src/adapter/static.ts +97 -50
  140. package/src/build/bun-build.ts +11 -0
  141. package/src/build/client.ts +41 -26
  142. package/src/build/entry-template.ts +20 -3
  143. package/src/build/hydrate.ts +128 -33
  144. package/src/build/index.ts +14 -2
  145. package/src/build/production-instrumentation.ts +14 -0
  146. package/src/build/route-types.ts +20 -116
  147. package/src/build/scan-server.ts +3 -2
  148. package/src/build/shared.ts +1 -1
  149. package/src/build/ssg-cache.ts +4 -2
  150. package/src/build/types.ts +2 -1
  151. package/src/cli/config.ts +3 -3
  152. package/src/cli/index.ts +58 -27
  153. package/src/client/boundaries.tsx +51 -19
  154. package/src/client/default-screens.tsx +4 -4
  155. package/src/client/define-route.ts +48 -0
  156. package/src/client/document.tsx +165 -0
  157. package/src/client/hmr.ts +40 -0
  158. package/src/client/internal/runtime-types.ts +33 -0
  159. package/src/client/link.tsx +51 -38
  160. package/src/client/router/boundary-tree.tsx +2 -2
  161. package/src/client/router/context.ts +13 -9
  162. package/src/client/router/index.ts +4 -0
  163. package/src/client/router/link-utils.ts +92 -3
  164. package/src/client/router/navigation.ts +9 -15
  165. package/src/client/router/provider.tsx +98 -53
  166. package/src/client/router/search/index.ts +9 -19
  167. package/src/client/router/search-store.ts +5 -1
  168. package/src/client/router/spa-response.ts +3 -4
  169. package/src/client/router/sync-catch-up.ts +9 -8
  170. package/src/client/router/types.ts +52 -26
  171. package/src/client/sync.ts +3 -2
  172. package/src/client-only.ts +1 -0
  173. package/src/client.ts +28 -283
  174. package/src/config.ts +10 -10
  175. package/src/define-route.ts +959 -0
  176. package/src/devtools/devtools-element.js +885 -0
  177. package/src/devtools/protocol.ts +139 -0
  178. package/src/furin.ts +475 -136
  179. package/src/isomorphic.ts +66 -0
  180. package/src/plugin/binding-scope.ts +158 -0
  181. package/src/plugin/dead-code-elimination.ts +202 -0
  182. package/src/plugin/index.ts +14 -18
  183. package/src/plugin/route-config-autofix.ts +1140 -0
  184. package/src/plugin/routes.ts +891 -0
  185. package/src/plugin/transform-client.ts +160 -330
  186. package/src/plugin/transform-isomorphic.ts +464 -0
  187. package/src/routes.ts +6 -0
  188. package/src/rsc/build/environment.ts +30 -0
  189. package/src/rsc/build/index.ts +94 -0
  190. package/src/rsc/client-codec.ts +11 -0
  191. package/src/rsc/codec.ts +85 -0
  192. package/src/rsc/flight-drain.ts +68 -0
  193. package/src/rsc/react-server-dom-webpack.d.ts +23 -0
  194. package/src/rsc/render-error.ts +120 -0
  195. package/src/rsc/server-codec.ts +25 -0
  196. package/src/rsc/shared.tsx +113 -0
  197. package/src/rsc/symbols.ts +2 -0
  198. package/src/rsc/transport-benchmark.ts +73 -0
  199. package/src/rsc/version.ts +57 -0
  200. package/src/rsc-client.ts +12 -0
  201. package/src/rsc-server.tsx +91 -0
  202. package/src/rsc.tsx +75 -0
  203. package/src/server/auto-invalidate/registry.ts +2 -2
  204. package/src/server/auto-invalidate/runtime.ts +32 -6
  205. package/src/server/cache/dev-loader.ts +70 -10
  206. package/src/server/cache/index.ts +7 -3
  207. package/src/server/cache/invalidation.ts +33 -15
  208. package/src/server/cache/isr-ssg.ts +12 -3
  209. package/src/server/cache/isr.ts +84 -9
  210. package/src/server/cache/route-cache.ts +49 -36
  211. package/src/server/cache/store-view.ts +7 -7
  212. package/src/server/context-logger.ts +7 -7
  213. package/src/server/dev-page-plugin.ts +38 -17
  214. package/src/server/devtools/hub.ts +64 -0
  215. package/src/server/devtools/instrumentation.production.ts +80 -0
  216. package/src/server/devtools/instrumentation.ts +72 -0
  217. package/src/server/devtools/plugin.ts +269 -0
  218. package/src/server/devtools/request-context.ts +76 -0
  219. package/src/server/instance.ts +4 -4
  220. package/src/server/internal.ts +5 -0
  221. package/src/server/lang-detect.ts +14 -10
  222. package/src/server/logger.ts +21 -0
  223. package/src/server/render/assemble.ts +58 -36
  224. package/src/server/render/document.tsx +25 -0
  225. package/src/server/render/element.tsx +24 -9
  226. package/src/server/render/index.ts +6 -3
  227. package/src/server/render/isr.ts +182 -117
  228. package/src/server/render/loaders.ts +289 -50
  229. package/src/server/render/not-found.ts +57 -38
  230. package/src/server/render/ppr-route.ts +146 -0
  231. package/src/server/render/route-frame-transport.ts +62 -0
  232. package/src/server/render/shell.ts +0 -1
  233. package/src/server/render/ssg.ts +7 -6
  234. package/src/server/render/ssr.ts +412 -166
  235. package/src/server/render/template.ts +93 -2
  236. package/src/server/router/defined-route.ts +110 -0
  237. package/src/server/router/discovery.ts +165 -48
  238. package/src/server/router/hmr.ts +126 -53
  239. package/src/server/router/patterns.ts +56 -27
  240. package/src/server/router/plugin.ts +210 -200
  241. package/src/server/router/schema-merge.ts +42 -0
  242. package/src/server/router/schemas.ts +61 -76
  243. package/src/server/router/source-version.ts +16 -0
  244. package/src/server/router/types.ts +3 -1
  245. package/src/server/sync/adapter.ts +44 -28
  246. package/src/server/sync/config.ts +9 -27
  247. package/src/server/sync/fingerprint.ts +8 -3
  248. package/src/server/sync/index.ts +37 -13
  249. package/src/server/sync/notifier.ts +109 -0
  250. package/src/server/sync/plugin.ts +184 -89
  251. package/src/server/sync/postgres/index.ts +301 -0
  252. package/src/server/sync/postgres/migrate.ts +16 -0
  253. package/src/server/sync/postgres/migration.sql +66 -0
  254. package/src/server/sync/redis/index.ts +342 -0
  255. package/src/server/sync/redis/scripts.ts +74 -0
  256. package/src/server/sync/response.ts +145 -16
  257. package/src/server/sync/runtime.ts +27 -0
  258. package/src/server/sync/sql.d.ts +4 -0
  259. package/src/server/sync/sqlite/index.ts +337 -0
  260. package/src/server/sync/sqlite/migration.sql +70 -0
  261. package/src/server/sync/stream.ts +137 -81
  262. package/src/server-only.ts +1 -0
  263. package/src/shared/await.tsx +10 -11
  264. package/src/shared/deferred-ndjson.ts +34 -6
  265. package/src/shared/digest.ts +2 -2
  266. package/src/shared/elysia-contract.ts +63 -0
  267. package/src/shared/parser.ts +5 -0
  268. package/src/shared/route-frame.ts +429 -0
  269. package/src/shared/route-map.ts +37 -0
  270. package/src/shared/search-params.ts +7 -7
  271. package/src/shared/utils/index.ts +6 -22
  272. package/dist/build/server-routes-entry.d.ts +0 -13
  273. package/dist/build/server-routes-entry.ts +0 -30
  274. package/dist/server/dev-inspector.d.ts +0 -89
  275. package/dist/server/router/index.d.ts +0 -6
  276. package/dist/server/router/index.js +0 -27
  277. package/dist/server/router/index.ts +0 -28
  278. package/dist/server/sync/memory-adapter.d.ts +0 -17
  279. package/src/build/server-routes-entry.ts +0 -30
  280. package/src/server/dev-inspector.ts +0 -60
  281. package/src/server/router/index.ts +0 -28
  282. package/src/server/sync/memory-adapter.ts +0 -196
@@ -1,4 +1,40 @@
1
1
  // @bun
2
+ // src/server/lang-detect.ts
3
+ function detectLangFromPath(filePath) {
4
+ if (filePath.endsWith(".d.ts")) {
5
+ return "dts";
6
+ }
7
+ if (filePath.endsWith(".tsx")) {
8
+ return "tsx";
9
+ }
10
+ if (filePath.endsWith(".ts")) {
11
+ return "ts";
12
+ }
13
+ if (filePath.endsWith(".jsx")) {
14
+ return "jsx";
15
+ }
16
+ return "js";
17
+ }
18
+ function detectLoaderFromPath(filePath) {
19
+ const lang = detectLangFromPath(filePath);
20
+ return lang === "dts" ? "ts" : lang;
21
+ }
22
+ var TS_WRAPPER_TYPES = new Set([
23
+ "TSAsExpression",
24
+ "TSSatisfiesExpression",
25
+ "TSTypeAssertion",
26
+ "TSNonNullExpression",
27
+ "TSInstantiationExpression",
28
+ "ParenthesizedExpression"
29
+ ]);
30
+ function unwrapTSExpression(node) {
31
+ let current = node;
32
+ while (current && typeof current === "object" && TS_WRAPPER_TYPES.has(current.type) && current.expression && typeof current.expression === "object") {
33
+ current = current.expression;
34
+ }
35
+ return current;
36
+ }
37
+
2
38
  // ../../node_modules/.bun/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
3
39
  var comma = 44;
4
40
  var semicolon = 59;
@@ -87,8 +123,8 @@ function encode(decoded) {
87
123
  return writer.flush();
88
124
  }
89
125
 
90
- // ../../node_modules/.bun/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
91
- class BitSet {
126
+ // ../../node_modules/.bun/magic-string@1.2.3/node_modules/magic-string/dist/index.mjs
127
+ var BitSet = class BitSet {
92
128
  constructor(arg) {
93
129
  this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
94
130
  }
@@ -98,9 +134,8 @@ class BitSet {
98
134
  has(n) {
99
135
  return !!(this.bits[n >> 5] & 1 << (n & 31));
100
136
  }
101
- }
102
-
103
- class Chunk {
137
+ };
138
+ var Chunk = class Chunk {
104
139
  constructor(start, end, content) {
105
140
  this.start = start;
106
141
  this.end = end;
@@ -110,10 +145,8 @@ class Chunk {
110
145
  this.content = content;
111
146
  this.storeName = false;
112
147
  this.edited = false;
113
- {
114
- this.previous = null;
115
- this.next = null;
116
- }
148
+ this.previous = null;
149
+ this.next = null;
117
150
  }
118
151
  appendLeft(content) {
119
152
  this.outro += content;
@@ -134,14 +167,16 @@ class Chunk {
134
167
  return this.start < index && index < this.end;
135
168
  }
136
169
  eachNext(fn) {
137
- let chunk = this;
170
+ fn(this);
171
+ let chunk = this.next;
138
172
  while (chunk) {
139
173
  fn(chunk);
140
174
  chunk = chunk.next;
141
175
  }
142
176
  }
143
177
  eachPrevious(fn) {
144
- let chunk = this;
178
+ fn(this);
179
+ let chunk = this.previous;
145
180
  while (chunk) {
146
181
  fn(chunk);
147
182
  chunk = chunk.previous;
@@ -184,9 +219,8 @@ class Chunk {
184
219
  if (this.edited) {
185
220
  newChunk.edit("", false);
186
221
  this.content = "";
187
- } else {
222
+ } else
188
223
  this.content = originalBefore;
189
- }
190
224
  newChunk.next = this.next;
191
225
  if (newChunk.next)
192
226
  newChunk.next.previous = newChunk;
@@ -203,12 +237,11 @@ class Chunk {
203
237
  return true;
204
238
  const trimmed = this.content.replace(rx, "");
205
239
  if (trimmed.length) {
206
- if (trimmed !== this.content) {
207
- this.split(this.start + trimmed.length).edit("", undefined, true);
208
- if (this.edited) {
240
+ if (trimmed !== this.content)
241
+ if (this.edited)
209
242
  this.edit(trimmed, this.storeName, true);
210
- }
211
- }
243
+ else
244
+ this.split(this.start + trimmed.length).edit("", undefined, true);
212
245
  return true;
213
246
  } else {
214
247
  this.edit("", undefined, true);
@@ -223,13 +256,13 @@ class Chunk {
223
256
  return true;
224
257
  const trimmed = this.content.replace(rx, "");
225
258
  if (trimmed.length) {
226
- if (trimmed !== this.content) {
227
- const newChunk = this.split(this.end - trimmed.length);
228
- if (this.edited) {
229
- newChunk.edit(trimmed, this.storeName, true);
259
+ if (trimmed !== this.content)
260
+ if (this.edited)
261
+ this.edit(trimmed, this.storeName, true);
262
+ else {
263
+ this.split(this.end - trimmed.length);
264
+ this.edit("", undefined, true);
230
265
  }
231
- this.edit("", undefined, true);
232
- }
233
266
  return true;
234
267
  } else {
235
268
  this.edit("", undefined, true);
@@ -238,21 +271,25 @@ class Chunk {
238
271
  return true;
239
272
  }
240
273
  }
241
- }
274
+ };
275
+ var MagicStringError = class extends Error {
276
+ name = "MagicStringError";
277
+ constructor(message, options) {
278
+ super(`[MagicString] ${message}`, options);
279
+ }
280
+ };
242
281
  function getBtoa() {
243
- if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
282
+ if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function")
244
283
  return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
245
- } else if (typeof Buffer === "function") {
246
- return (str) => Buffer.from(str, "utf-8").toString("base64");
247
- } else {
248
- return () => {
249
- throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
250
- };
251
- }
284
+ const buffer = globalThis["Buffer"];
285
+ if (buffer)
286
+ return (str) => buffer.from(str, "utf-8").toString("base64");
287
+ return () => {
288
+ throw new MagicStringError("unsupported environment: `btoa` or `Buffer` is required");
289
+ };
252
290
  }
253
291
  var btoa = /* @__PURE__ */ getBtoa();
254
-
255
- class SourceMap {
292
+ var SourceMap = class {
256
293
  constructor(properties) {
257
294
  this.version = 3;
258
295
  this.file = properties.file;
@@ -260,36 +297,42 @@ class SourceMap {
260
297
  this.sourcesContent = properties.sourcesContent;
261
298
  this.names = properties.names;
262
299
  this.mappings = encode(properties.mappings);
263
- if (typeof properties.x_google_ignoreList !== "undefined") {
300
+ if (typeof properties.x_google_ignoreList !== "undefined")
264
301
  this.x_google_ignoreList = properties.x_google_ignoreList;
265
- }
266
- if (typeof properties.debugId !== "undefined") {
302
+ if (typeof properties.debugId !== "undefined")
267
303
  this.debugId = properties.debugId;
268
- }
269
304
  }
270
305
  toString() {
271
306
  return JSON.stringify(this);
272
307
  }
273
308
  toUrl() {
274
- return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
309
+ return `data:application/json;charset=utf-8;base64,${btoa(this.toString())}`;
275
310
  }
276
- }
277
- function guessIndent(code) {
278
- const lines = code.split(`
311
+ };
312
+ function getLocator(source) {
313
+ const originalLines = source.split(`
279
314
  `);
280
- const tabbed = lines.filter((line) => /^\t+/.test(line));
281
- const spaced = lines.filter((line) => /^ {2,}/.test(line));
282
- if (tabbed.length === 0 && spaced.length === 0) {
283
- return null;
284
- }
285
- if (tabbed.length >= spaced.length) {
286
- return "\t";
315
+ const lineOffsets = [];
316
+ for (let i = 0, pos = 0;i < originalLines.length; i++) {
317
+ lineOffsets.push(pos);
318
+ pos += originalLines[i].length + 1;
287
319
  }
288
- const min = spaced.reduce((previous, current) => {
289
- const numSpaces = /^ +/.exec(current)[0].length;
290
- return Math.min(numSpaces, previous);
291
- }, Infinity);
292
- return new Array(min + 1).join(" ");
320
+ return function locate(index) {
321
+ let i = 0;
322
+ let j = lineOffsets.length;
323
+ while (i < j) {
324
+ const m = i + j >> 1;
325
+ if (index < lineOffsets[m])
326
+ j = m;
327
+ else
328
+ i = m + 1;
329
+ }
330
+ const line = i - 1;
331
+ return {
332
+ line,
333
+ column: index - lineOffsets[line]
334
+ };
335
+ };
293
336
  }
294
337
  function getRelativePath(from, to) {
295
338
  const fromParts = from.split(/[/\\]/);
@@ -306,37 +349,27 @@ function getRelativePath(from, to) {
306
349
  }
307
350
  return fromParts.concat(toParts).join("/");
308
351
  }
352
+ function guessIndent(code) {
353
+ const lines = code.split(`
354
+ `);
355
+ const tabbed = lines.filter((line) => /^\t+/.test(line));
356
+ const spaced = lines.filter((line) => /^ {2,}/.test(line));
357
+ if (tabbed.length === 0 && spaced.length === 0)
358
+ return null;
359
+ if (tabbed.length >= spaced.length)
360
+ return "\t";
361
+ const min = spaced.reduce((previous, current) => {
362
+ const numSpaces = /^ +/.exec(current)[0].length;
363
+ return Math.min(numSpaces, previous);
364
+ }, Infinity);
365
+ return " ".repeat(min);
366
+ }
309
367
  var toString = Object.prototype.toString;
310
368
  function isObject(thing) {
311
369
  return toString.call(thing) === "[object Object]";
312
370
  }
313
- function getLocator(source) {
314
- const originalLines = source.split(`
315
- `);
316
- const lineOffsets = [];
317
- for (let i = 0, pos = 0;i < originalLines.length; i++) {
318
- lineOffsets.push(pos);
319
- pos += originalLines[i].length + 1;
320
- }
321
- return function locate(index) {
322
- let i = 0;
323
- let j = lineOffsets.length;
324
- while (i < j) {
325
- const m = i + j >> 1;
326
- if (index < lineOffsets[m]) {
327
- j = m;
328
- } else {
329
- i = m + 1;
330
- }
331
- }
332
- const line = i - 1;
333
- const column = index - lineOffsets[line];
334
- return { line, column };
335
- };
336
- }
337
371
  var wordRegex = /\w/;
338
-
339
- class Mappings {
372
+ var Mappings = class {
340
373
  constructor(hires) {
341
374
  this.hires = hires;
342
375
  this.generatedCodeLine = 0;
@@ -352,11 +385,15 @@ class Mappings {
352
385
  `, 0);
353
386
  let previousContentLineEnd = -1;
354
387
  while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
355
- const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
356
- if (nameIndex >= 0) {
357
- segment2.push(nameIndex);
358
- }
359
- this.rawSegments.push(segment2);
388
+ const segment = [
389
+ this.generatedCodeColumn,
390
+ sourceIndex,
391
+ loc.line,
392
+ loc.column
393
+ ];
394
+ if (nameIndex >= 0)
395
+ segment.push(nameIndex);
396
+ this.rawSegments.push(segment);
360
397
  this.generatedCodeLine += 1;
361
398
  this.raw[this.generatedCodeLine] = this.rawSegments = [];
362
399
  this.generatedCodeColumn = 0;
@@ -364,10 +401,14 @@ class Mappings {
364
401
  contentLineEnd = content.indexOf(`
365
402
  `, contentLineEnd + 1);
366
403
  }
367
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
368
- if (nameIndex >= 0) {
404
+ const segment = [
405
+ this.generatedCodeColumn,
406
+ sourceIndex,
407
+ loc.line,
408
+ loc.column
409
+ ];
410
+ if (nameIndex >= 0)
369
411
  segment.push(nameIndex);
370
- }
371
412
  this.rawSegments.push(segment);
372
413
  this.advance(content.slice(previousContentLineEnd + 1));
373
414
  } else if (this.pending) {
@@ -392,8 +433,13 @@ class Mappings {
392
433
  charInHiresBoundary = false;
393
434
  } else {
394
435
  if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
395
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
396
- if (this.hires === "boundary") {
436
+ const segment = [
437
+ this.generatedCodeColumn,
438
+ sourceIndex,
439
+ loc.line,
440
+ loc.column
441
+ ];
442
+ if (this.hires === "boundary")
397
443
  if (wordRegex.test(original[originalCharIndex])) {
398
444
  if (!charInHiresBoundary) {
399
445
  this.rawSegments.push(segment);
@@ -403,9 +449,8 @@ class Mappings {
403
449
  this.rawSegments.push(segment);
404
450
  charInHiresBoundary = false;
405
451
  }
406
- } else {
452
+ else
407
453
  this.rawSegments.push(segment);
408
- }
409
454
  }
410
455
  loc.column += 1;
411
456
  this.generatedCodeColumn += 1;
@@ -429,80 +474,130 @@ class Mappings {
429
474
  }
430
475
  this.generatedCodeColumn += lines[lines.length - 1].length;
431
476
  }
432
- }
477
+ };
433
478
  var n = `
434
479
  `;
480
+ var NEWLINE_CHAR = 10;
481
+ var CR_CHAR = 13;
435
482
  var warned = {
436
483
  insertLeft: false,
437
484
  insertRight: false,
438
485
  storeName: false
439
486
  };
440
-
441
- class MagicString {
487
+ var MagicString = class MagicString {
442
488
  constructor(string, options = {}) {
443
489
  const chunk = new Chunk(0, string.length, string);
444
490
  Object.defineProperties(this, {
445
- original: { writable: true, value: string },
446
- outro: { writable: true, value: "" },
447
- intro: { writable: true, value: "" },
448
- firstChunk: { writable: true, value: chunk },
449
- lastChunk: { writable: true, value: chunk },
450
- lastSearchedChunk: { writable: true, value: chunk },
451
- byStart: { writable: true, value: {} },
452
- byEnd: { writable: true, value: {} },
453
- filename: { writable: true, value: options.filename },
454
- indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
455
- sourcemapLocations: { writable: true, value: new BitSet },
456
- storedNames: { writable: true, value: {} },
457
- indentStr: { writable: true, value: undefined },
458
- ignoreList: { writable: true, value: options.ignoreList },
459
- offset: { writable: true, value: options.offset || 0 }
491
+ original: {
492
+ writable: true,
493
+ value: string
494
+ },
495
+ outro: {
496
+ writable: true,
497
+ value: ""
498
+ },
499
+ intro: {
500
+ writable: true,
501
+ value: ""
502
+ },
503
+ firstChunk: {
504
+ writable: true,
505
+ value: chunk
506
+ },
507
+ lastChunk: {
508
+ writable: true,
509
+ value: chunk
510
+ },
511
+ lastSearchedChunk: {
512
+ writable: true,
513
+ value: chunk
514
+ },
515
+ byStart: {
516
+ writable: true,
517
+ value: /* @__PURE__ */ new Map([[0, chunk]])
518
+ },
519
+ byEnd: {
520
+ writable: true,
521
+ value: /* @__PURE__ */ new Map([[string.length, chunk]])
522
+ },
523
+ filename: {
524
+ writable: true,
525
+ value: options.filename
526
+ },
527
+ indentExclusionRanges: {
528
+ writable: true,
529
+ value: options.indentExclusionRanges
530
+ },
531
+ sourcemapLocations: {
532
+ writable: true,
533
+ value: new BitSet
534
+ },
535
+ storedNames: {
536
+ writable: true,
537
+ value: {}
538
+ },
539
+ indentStr: {
540
+ writable: true,
541
+ value: undefined
542
+ },
543
+ ignoreList: {
544
+ writable: true,
545
+ value: options.ignoreList
546
+ },
547
+ offset: {
548
+ writable: true,
549
+ value: options.offset || 0
550
+ },
551
+ hasMovedChunks: {
552
+ writable: true,
553
+ value: false
554
+ }
460
555
  });
461
- this.byStart[0] = chunk;
462
- this.byEnd[string.length] = chunk;
463
556
  }
464
557
  addSourcemapLocation(char) {
465
558
  this.sourcemapLocations.add(char);
466
559
  }
467
560
  append(content) {
468
561
  if (typeof content !== "string")
469
- throw new TypeError("outro content must be a string");
562
+ throw new MagicStringError(`content must be a string, got ${typeof content}`);
470
563
  this.outro += content;
471
564
  return this;
472
565
  }
473
566
  appendLeft(index, content) {
474
567
  index = index + this.offset;
475
568
  if (typeof content !== "string")
476
- throw new TypeError("inserted content must be a string");
569
+ throw new MagicStringError(`content must be a string, got ${typeof content}`);
477
570
  this._split(index);
478
- const chunk = this.byEnd[index];
479
- if (chunk) {
571
+ const chunk = this.byEnd.get(index);
572
+ if (chunk)
480
573
  chunk.appendLeft(content);
481
- } else {
574
+ else
482
575
  this.intro += content;
483
- }
484
576
  return this;
485
577
  }
486
578
  appendRight(index, content) {
487
579
  index = index + this.offset;
488
580
  if (typeof content !== "string")
489
- throw new TypeError("inserted content must be a string");
581
+ throw new MagicStringError(`content must be a string, got ${typeof content}`);
490
582
  this._split(index);
491
- const chunk = this.byStart[index];
492
- if (chunk) {
583
+ const chunk = this.byStart.get(index);
584
+ if (chunk)
493
585
  chunk.appendRight(content);
494
- } else {
586
+ else
495
587
  this.outro += content;
496
- }
497
588
  return this;
498
589
  }
499
590
  clone() {
500
- const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
591
+ const cloned = new MagicString(this.original, {
592
+ filename: this.filename,
593
+ ignoreList: this.ignoreList,
594
+ offset: this.offset
595
+ });
501
596
  let originalChunk = this.firstChunk;
502
597
  let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
503
598
  while (originalChunk) {
504
- cloned.byStart[clonedChunk.start] = clonedChunk;
505
- cloned.byEnd[clonedChunk.end] = clonedChunk;
599
+ cloned.byStart.set(clonedChunk.start, clonedChunk);
600
+ cloned.byEnd.set(clonedChunk.end, clonedChunk);
506
601
  const nextOriginalChunk = originalChunk.next;
507
602
  const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
508
603
  if (nextClonedChunk) {
@@ -513,12 +608,13 @@ class MagicString {
513
608
  originalChunk = nextOriginalChunk;
514
609
  }
515
610
  cloned.lastChunk = clonedChunk;
516
- if (this.indentExclusionRanges) {
611
+ if (this.indentExclusionRanges)
517
612
  cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
518
- }
519
613
  cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
614
+ cloned.storedNames = { ...this.storedNames };
520
615
  cloned.intro = this.intro;
521
616
  cloned.outro = this.outro;
617
+ cloned.hasMovedChunks = this.hasMovedChunks;
522
618
  return cloned;
523
619
  }
524
620
  generateDecodedMap(options) {
@@ -527,29 +623,24 @@ class MagicString {
527
623
  const names = Object.keys(this.storedNames);
528
624
  const mappings = new Mappings(options.hires);
529
625
  const locate = getLocator(this.original);
530
- if (this.intro) {
626
+ if (this.intro)
531
627
  mappings.advance(this.intro);
532
- }
533
628
  this.firstChunk.eachNext((chunk) => {
534
629
  const loc = locate(chunk.start);
535
630
  if (chunk.intro.length)
536
631
  mappings.advance(chunk.intro);
537
- if (chunk.edited) {
632
+ if (chunk.edited)
538
633
  mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
539
- } else {
634
+ else
540
635
  mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
541
- }
542
636
  if (chunk.outro.length)
543
637
  mappings.advance(chunk.outro);
544
638
  });
545
- if (this.outro) {
639
+ if (this.outro)
546
640
  mappings.advance(this.outro);
547
- }
548
641
  return {
549
642
  file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
550
- sources: [
551
- options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
552
- ],
643
+ sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
553
644
  sourcesContent: options.includeContent ? [this.original] : undefined,
554
645
  names,
555
646
  mappings: mappings.raw,
@@ -560,9 +651,8 @@ class MagicString {
560
651
  return new SourceMap(this.generateDecodedMap(options));
561
652
  }
562
653
  _ensureindentStr() {
563
- if (this.indentStr === undefined) {
654
+ if (this.indentStr === undefined)
564
655
  this.indentStr = guessIndent(this.original);
565
- }
566
656
  }
567
657
  _getRawIndentString() {
568
658
  this._ensureindentStr();
@@ -584,55 +674,72 @@ class MagicString {
584
674
  }
585
675
  if (indentStr === "")
586
676
  return this;
677
+ const resolvedIndentStr = indentStr;
587
678
  options = options || {};
588
679
  const isExcluded = {};
589
- if (options.exclude) {
590
- const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
591
- exclusions.forEach((exclusion) => {
592
- for (let i = exclusion[0];i < exclusion[1]; i += 1) {
680
+ if (options.exclude)
681
+ (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
682
+ for (let i = exclusion[0];i < exclusion[1]; i += 1)
593
683
  isExcluded[i] = true;
594
- }
595
684
  });
596
- }
597
685
  let shouldIndentNextCharacter = options.indentStart !== false;
598
686
  const replacer = (match) => {
599
687
  if (shouldIndentNextCharacter)
600
- return `${indentStr}${match}`;
688
+ return `${resolvedIndentStr}${match}`;
601
689
  shouldIndentNextCharacter = true;
602
690
  return match;
603
691
  };
604
692
  this.intro = this.intro.replace(pattern, replacer);
605
693
  let charIndex = 0;
606
694
  let chunk = this.firstChunk;
695
+ const indentAt = (index) => {
696
+ shouldIndentNextCharacter = false;
697
+ if (index === chunk.start)
698
+ chunk.prependRight(resolvedIndentStr);
699
+ else {
700
+ this._splitChunk(chunk, index);
701
+ chunk = chunk.next;
702
+ chunk.prependRight(resolvedIndentStr);
703
+ }
704
+ };
607
705
  while (chunk) {
608
706
  const end = chunk.end;
609
707
  if (chunk.edited) {
610
708
  if (!isExcluded[charIndex]) {
611
709
  chunk.content = chunk.content.replace(pattern, replacer);
612
- if (chunk.content.length) {
710
+ if (chunk.content.length)
613
711
  shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === `
614
712
  `;
615
- }
616
713
  }
617
- } else {
714
+ } else if (options.exclude) {
618
715
  charIndex = chunk.start;
619
716
  while (charIndex < end) {
620
717
  if (!isExcluded[charIndex]) {
621
- const char = this.original[charIndex];
622
- if (char === `
623
- `) {
718
+ const char = this.original.charCodeAt(charIndex);
719
+ if (char === NEWLINE_CHAR)
624
720
  shouldIndentNextCharacter = true;
625
- } else if (char !== "\r" && shouldIndentNextCharacter) {
626
- shouldIndentNextCharacter = false;
627
- if (charIndex === chunk.start) {
628
- chunk.prependRight(indentStr);
629
- } else {
630
- this._splitChunk(chunk, charIndex);
631
- chunk = chunk.next;
632
- chunk.prependRight(indentStr);
633
- }
634
- }
721
+ else if (char !== CR_CHAR && shouldIndentNextCharacter)
722
+ indentAt(charIndex);
723
+ }
724
+ charIndex += 1;
725
+ }
726
+ } else {
727
+ charIndex = chunk.start;
728
+ while (charIndex < end) {
729
+ if (!shouldIndentNextCharacter) {
730
+ const nextLine = this.original.indexOf(n, charIndex);
731
+ if (nextLine === -1 || nextLine >= end)
732
+ break;
733
+ shouldIndentNextCharacter = true;
734
+ charIndex = nextLine + 1;
735
+ continue;
736
+ }
737
+ const char = this.original.charCodeAt(charIndex);
738
+ if (char === NEWLINE_CHAR || char === CR_CHAR) {
739
+ charIndex += 1;
740
+ continue;
635
741
  }
742
+ indentAt(charIndex);
636
743
  charIndex += 1;
637
744
  }
638
745
  }
@@ -643,7 +750,7 @@ class MagicString {
643
750
  return this;
644
751
  }
645
752
  insert() {
646
- throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
753
+ throw new MagicStringError("insert() is deprecated, use appendLeft() or prependRight()");
647
754
  }
648
755
  insertLeft(index, content) {
649
756
  if (!warned.insertLeft) {
@@ -663,16 +770,26 @@ class MagicString {
663
770
  start = start + this.offset;
664
771
  end = end + this.offset;
665
772
  index = index + this.offset;
773
+ if (start === end)
774
+ return this;
666
775
  if (index >= start && index <= end)
667
- throw new Error("Cannot move a selection inside itself");
776
+ throw new MagicStringError("cannot move a selection inside itself");
668
777
  this._split(start);
669
778
  this._split(end);
670
779
  this._split(index);
671
- const first = this.byStart[start];
672
- const last = this.byEnd[end];
780
+ const first = this.byStart.get(start);
781
+ const last = this.byEnd.get(end);
782
+ if (this.hasMovedChunks) {
783
+ let cursor = first;
784
+ while (cursor !== last) {
785
+ cursor = cursor.next;
786
+ if (!cursor || cursor.start < start || cursor.end > end)
787
+ throw new MagicStringError(`cannot move ${start} to ${end} because an earlier move split that range`);
788
+ }
789
+ }
673
790
  const oldLeft = first.previous;
674
791
  const oldRight = last.next;
675
- const newRight = this.byStart[index];
792
+ const newRight = this.byStart.get(index);
676
793
  if (!newRight && last === this.lastChunk)
677
794
  return this;
678
795
  const newLeft = newRight ? newRight.previous : this.lastChunk;
@@ -696,27 +813,35 @@ class MagicString {
696
813
  this.firstChunk = first;
697
814
  if (!newRight)
698
815
  this.lastChunk = last;
816
+ this.hasMovedChunks = true;
699
817
  return this;
700
818
  }
701
819
  overwrite(start, end, content, options) {
702
- options = options || {};
703
- return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
820
+ const optionObject = typeof options === "object" && options ? options : {};
821
+ return this.update(start, end, content, {
822
+ ...optionObject,
823
+ overwrite: !optionObject.contentOnly
824
+ });
704
825
  }
705
826
  update(start, end, content, options) {
706
827
  start = start + this.offset;
707
828
  end = end + this.offset;
708
829
  if (typeof content !== "string")
709
- throw new TypeError("replacement content must be a string");
830
+ throw new MagicStringError(`content must be a string, got ${typeof content}`);
710
831
  if (this.original.length !== 0) {
711
- while (start < 0)
712
- start += this.original.length;
713
- while (end < 0)
714
- end += this.original.length;
832
+ if (start < 0)
833
+ start = Math.max(0, start + this.original.length);
834
+ if (end < 0)
835
+ end = Math.max(0, end + this.original.length);
715
836
  }
837
+ if (start < 0)
838
+ throw new MagicStringError(`start ${start} is out of bounds`);
716
839
  if (end > this.original.length)
717
- throw new Error("end is out of bounds");
840
+ throw new MagicStringError(`end ${end} is out of bounds`);
718
841
  if (start === end)
719
- throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");
842
+ throw new MagicStringError(`cannot overwrite a zero-length range at ${start}, use appendLeft() or prependRight()`);
843
+ if (start > end)
844
+ throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
720
845
  this._split(start);
721
846
  this._split(end);
722
847
  if (options === true) {
@@ -726,8 +851,9 @@ class MagicString {
726
851
  }
727
852
  options = { storeName: true };
728
853
  }
729
- const storeName = options !== undefined ? options.storeName : false;
730
- const overwrite = options !== undefined ? options.overwrite : false;
854
+ const optionObject = typeof options === "object" && options ? options : {};
855
+ const storeName = optionObject.storeName || false;
856
+ const overwrite = optionObject.overwrite || false;
731
857
  if (storeName) {
732
858
  const original = this.original.slice(start, end);
733
859
  Object.defineProperty(this.storedNames, original, {
@@ -736,14 +862,13 @@ class MagicString {
736
862
  enumerable: true
737
863
  });
738
864
  }
739
- const first = this.byStart[start];
740
- const last = this.byEnd[end];
865
+ const first = this.byStart.get(start);
866
+ const last = this.byEnd.get(end);
741
867
  if (first) {
742
868
  let chunk = first;
743
869
  while (chunk !== last) {
744
- if (chunk.next !== this.byStart[chunk.end]) {
745
- throw new Error("Cannot overwrite across a split point");
746
- }
870
+ if (chunk.next !== this.byStart.get(chunk.end))
871
+ throw new MagicStringError("cannot overwrite across a split point");
747
872
  chunk = chunk.next;
748
873
  chunk.edit("", false);
749
874
  }
@@ -757,59 +882,57 @@ class MagicString {
757
882
  }
758
883
  prepend(content) {
759
884
  if (typeof content !== "string")
760
- throw new TypeError("outro content must be a string");
885
+ throw new MagicStringError(`content must be a string, got ${typeof content}`);
761
886
  this.intro = content + this.intro;
762
887
  return this;
763
888
  }
764
889
  prependLeft(index, content) {
765
890
  index = index + this.offset;
766
891
  if (typeof content !== "string")
767
- throw new TypeError("inserted content must be a string");
892
+ throw new MagicStringError(`content must be a string, got ${typeof content}`);
768
893
  this._split(index);
769
- const chunk = this.byEnd[index];
770
- if (chunk) {
894
+ const chunk = this.byEnd.get(index);
895
+ if (chunk)
771
896
  chunk.prependLeft(content);
772
- } else {
897
+ else
773
898
  this.intro = content + this.intro;
774
- }
775
899
  return this;
776
900
  }
777
901
  prependRight(index, content) {
778
902
  index = index + this.offset;
779
903
  if (typeof content !== "string")
780
- throw new TypeError("inserted content must be a string");
904
+ throw new MagicStringError(`content must be a string, got ${typeof content}`);
781
905
  this._split(index);
782
- const chunk = this.byStart[index];
783
- if (chunk) {
906
+ const chunk = this.byStart.get(index);
907
+ if (chunk)
784
908
  chunk.prependRight(content);
785
- } else {
909
+ else
786
910
  this.outro = content + this.outro;
787
- }
788
911
  return this;
789
912
  }
790
913
  remove(start, end) {
791
914
  start = start + this.offset;
792
915
  end = end + this.offset;
793
916
  if (this.original.length !== 0) {
794
- while (start < 0)
795
- start += this.original.length;
796
- while (end < 0)
797
- end += this.original.length;
917
+ if (start < 0)
918
+ start = Math.max(0, start + this.original.length);
919
+ if (end < 0)
920
+ end = Math.max(0, end + this.original.length);
798
921
  }
799
922
  if (start === end)
800
923
  return this;
801
924
  if (start < 0 || end > this.original.length)
802
- throw new Error("Character is out of bounds");
925
+ throw new MagicStringError(`range ${start}\u2013${end} is out of bounds`);
803
926
  if (start > end)
804
- throw new Error("end must be greater than start");
927
+ throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
805
928
  this._split(start);
806
929
  this._split(end);
807
- let chunk = this.byStart[start];
930
+ let chunk = this.byStart.get(start);
808
931
  while (chunk) {
809
932
  chunk.intro = "";
810
933
  chunk.outro = "";
811
934
  chunk.edit("");
812
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
935
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : null;
813
936
  }
814
937
  return this;
815
938
  }
@@ -817,23 +940,23 @@ class MagicString {
817
940
  start = start + this.offset;
818
941
  end = end + this.offset;
819
942
  if (this.original.length !== 0) {
820
- while (start < 0)
821
- start += this.original.length;
822
- while (end < 0)
823
- end += this.original.length;
943
+ if (start < 0)
944
+ start = Math.max(0, start + this.original.length);
945
+ if (end < 0)
946
+ end = Math.max(0, end + this.original.length);
824
947
  }
825
948
  if (start === end)
826
949
  return this;
827
950
  if (start < 0 || end > this.original.length)
828
- throw new Error("Character is out of bounds");
951
+ throw new MagicStringError(`range ${start}\u2013${end} is out of bounds`);
829
952
  if (start > end)
830
- throw new Error("end must be greater than start");
953
+ throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
831
954
  this._split(start);
832
955
  this._split(end);
833
- let chunk = this.byStart[start];
956
+ let chunk = this.byStart.get(start);
834
957
  while (chunk) {
835
958
  chunk.reset();
836
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
959
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : null;
837
960
  }
838
961
  return this;
839
962
  }
@@ -841,14 +964,15 @@ class MagicString {
841
964
  if (this.outro.length)
842
965
  return this.outro[this.outro.length - 1];
843
966
  let chunk = this.lastChunk;
844
- do {
967
+ while (chunk) {
845
968
  if (chunk.outro.length)
846
969
  return chunk.outro[chunk.outro.length - 1];
847
970
  if (chunk.content.length)
848
971
  return chunk.content[chunk.content.length - 1];
849
972
  if (chunk.intro.length)
850
973
  return chunk.intro[chunk.intro.length - 1];
851
- } while (chunk = chunk.previous);
974
+ chunk = chunk.previous;
975
+ }
852
976
  if (this.intro.length)
853
977
  return this.intro[this.intro.length - 1];
854
978
  return "";
@@ -859,7 +983,7 @@ class MagicString {
859
983
  return this.outro.substr(lineIndex + 1);
860
984
  let lineStr = this.outro;
861
985
  let chunk = this.lastChunk;
862
- do {
986
+ while (chunk) {
863
987
  if (chunk.outro.length > 0) {
864
988
  lineIndex = chunk.outro.lastIndexOf(n);
865
989
  if (lineIndex !== -1)
@@ -878,7 +1002,8 @@ class MagicString {
878
1002
  return chunk.intro.substr(lineIndex + 1) + lineStr;
879
1003
  lineStr = chunk.intro + lineStr;
880
1004
  }
881
- } while (chunk = chunk.previous);
1005
+ chunk = chunk.previous;
1006
+ }
882
1007
  lineIndex = this.intro.lastIndexOf(n);
883
1008
  if (lineIndex !== -1)
884
1009
  return this.intro.substr(lineIndex + 1) + lineStr;
@@ -888,38 +1013,34 @@ class MagicString {
888
1013
  start = start + this.offset;
889
1014
  end = end + this.offset;
890
1015
  if (this.original.length !== 0) {
891
- while (start < 0)
892
- start += this.original.length;
893
- while (end < 0)
894
- end += this.original.length;
1016
+ if (start < 0)
1017
+ start = Math.max(0, start + this.original.length);
1018
+ if (end < 0)
1019
+ end = Math.max(0, end + this.original.length);
895
1020
  }
896
1021
  let result = "";
897
1022
  let chunk = this.firstChunk;
898
1023
  while (chunk && (chunk.start > start || chunk.end <= start)) {
899
- if (chunk.start < end && chunk.end >= end) {
1024
+ if (chunk.start < end && chunk.end >= end)
900
1025
  return result;
901
- }
902
1026
  chunk = chunk.next;
903
1027
  }
904
1028
  if (chunk && chunk.edited && chunk.start !== start)
905
- throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1029
+ throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`);
906
1030
  const startChunk = chunk;
907
1031
  while (chunk) {
908
- if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1032
+ if (chunk.intro && (startChunk !== chunk || chunk.start === start))
909
1033
  result += chunk.intro;
910
- }
911
1034
  const containsEnd = chunk.start < end && chunk.end >= end;
912
1035
  if (containsEnd && chunk.edited && chunk.end !== end)
913
- throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1036
+ throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`);
914
1037
  const sliceStart = startChunk === chunk ? start - chunk.start : 0;
915
1038
  const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
916
1039
  result += chunk.content.slice(sliceStart, sliceEnd);
917
- if (chunk.outro && (!containsEnd || chunk.end === end)) {
1040
+ if (chunk.outro && (!containsEnd || chunk.end === end))
918
1041
  result += chunk.outro;
919
- }
920
- if (containsEnd) {
1042
+ if (containsEnd)
921
1043
  break;
922
- }
923
1044
  chunk = chunk.next;
924
1045
  }
925
1046
  return result;
@@ -931,7 +1052,7 @@ class MagicString {
931
1052
  return clone;
932
1053
  }
933
1054
  _split(index) {
934
- if (this.byStart[index] || this.byEnd[index])
1055
+ if (this.byStart.get(index) || this.byEnd.get(index))
935
1056
  return;
936
1057
  let chunk = this.lastSearchedChunk;
937
1058
  let previousChunk = chunk;
@@ -939,7 +1060,7 @@ class MagicString {
939
1060
  while (chunk) {
940
1061
  if (chunk.contains(index))
941
1062
  return this._splitChunk(chunk, index);
942
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1063
+ chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
943
1064
  if (chunk === previousChunk)
944
1065
  return;
945
1066
  previousChunk = chunk;
@@ -948,12 +1069,12 @@ class MagicString {
948
1069
  _splitChunk(chunk, index) {
949
1070
  if (chunk.edited && chunk.content.length) {
950
1071
  const loc = getLocator(this.original)(index);
951
- throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`);
1072
+ throw new MagicStringError(`cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`);
952
1073
  }
953
1074
  const newChunk = chunk.split(index);
954
- this.byEnd[index] = chunk;
955
- this.byStart[index] = newChunk;
956
- this.byEnd[newChunk.end] = newChunk;
1075
+ this.byEnd.set(index, chunk);
1076
+ this.byStart.set(index, newChunk);
1077
+ this.byEnd.set(newChunk.end, newChunk);
957
1078
  if (chunk === this.lastChunk)
958
1079
  this.lastChunk = newChunk;
959
1080
  this.lastSearchedChunk = chunk;
@@ -970,18 +1091,20 @@ class MagicString {
970
1091
  }
971
1092
  isEmpty() {
972
1093
  let chunk = this.firstChunk;
973
- do {
1094
+ while (chunk) {
974
1095
  if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
975
1096
  return false;
976
- } while (chunk = chunk.next);
1097
+ chunk = chunk.next;
1098
+ }
977
1099
  return true;
978
1100
  }
979
1101
  length() {
980
1102
  let chunk = this.firstChunk;
981
1103
  let length = 0;
982
- do {
1104
+ while (chunk) {
983
1105
  length += chunk.intro.length + chunk.content.length + chunk.outro.length;
984
- } while (chunk = chunk.next);
1106
+ chunk = chunk.next;
1107
+ }
985
1108
  return length;
986
1109
  }
987
1110
  trimLines() {
@@ -991,7 +1114,7 @@ class MagicString {
991
1114
  return this.trimStart(charType).trimEnd(charType);
992
1115
  }
993
1116
  trimEndAborted(charType) {
994
- const rx = new RegExp((charType || "\\s") + "+$");
1117
+ const rx = new RegExp(`${charType || "\\s"}+$`);
995
1118
  this.outro = this.outro.replace(rx, "");
996
1119
  if (this.outro.length)
997
1120
  return true;
@@ -1000,12 +1123,11 @@ class MagicString {
1000
1123
  const end = chunk.end;
1001
1124
  const aborted = chunk.trimEnd(rx);
1002
1125
  if (chunk.end !== end) {
1003
- if (this.lastChunk === chunk) {
1126
+ if (this.lastChunk === chunk)
1004
1127
  this.lastChunk = chunk.next;
1005
- }
1006
- this.byEnd[chunk.end] = chunk;
1007
- this.byStart[chunk.next.start] = chunk.next;
1008
- this.byEnd[chunk.next.end] = chunk.next;
1128
+ this.byEnd.set(chunk.end, chunk);
1129
+ this.byStart.set(chunk.next.start, chunk.next);
1130
+ this.byEnd.set(chunk.next.end, chunk.next);
1009
1131
  }
1010
1132
  if (aborted)
1011
1133
  return true;
@@ -1018,7 +1140,7 @@ class MagicString {
1018
1140
  return this;
1019
1141
  }
1020
1142
  trimStartAborted(charType) {
1021
- const rx = new RegExp("^" + (charType || "\\s") + "+");
1143
+ const rx = new RegExp(`^${charType || "\\s"}+`);
1022
1144
  this.intro = this.intro.replace(rx, "");
1023
1145
  if (this.intro.length)
1024
1146
  return true;
@@ -1029,9 +1151,9 @@ class MagicString {
1029
1151
  if (chunk.end !== end) {
1030
1152
  if (chunk === this.lastChunk)
1031
1153
  this.lastChunk = chunk.next;
1032
- this.byEnd[chunk.end] = chunk;
1033
- this.byStart[chunk.next.start] = chunk.next;
1034
- this.byEnd[chunk.next.end] = chunk.next;
1154
+ this.byEnd.set(chunk.end, chunk);
1155
+ this.byStart.set(chunk.next.start, chunk.next);
1156
+ this.byEnd.set(chunk.next.end, chunk.next);
1035
1157
  }
1036
1158
  if (aborted)
1037
1159
  return true;
@@ -1044,51 +1166,58 @@ class MagicString {
1044
1166
  return this;
1045
1167
  }
1046
1168
  hasChanged() {
1047
- return this.original !== this.toString();
1169
+ if (this.intro || this.outro)
1170
+ return true;
1171
+ let outputIndex = 0;
1172
+ let chunk = this.firstChunk;
1173
+ while (chunk) {
1174
+ if (chunk.intro || chunk.outro)
1175
+ return true;
1176
+ if (!chunk.edited && chunk.start === outputIndex)
1177
+ outputIndex = chunk.end;
1178
+ else {
1179
+ if (!this.original.startsWith(chunk.content, outputIndex))
1180
+ return true;
1181
+ outputIndex += chunk.content.length;
1182
+ }
1183
+ chunk = chunk.next;
1184
+ }
1185
+ return outputIndex !== this.original.length;
1048
1186
  }
1049
1187
  _replaceRegexp(searchValue, replacement) {
1050
1188
  function getReplacement(match, str) {
1051
- if (typeof replacement === "string") {
1189
+ if (typeof replacement === "string")
1052
1190
  return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1053
1191
  if (i === "$")
1054
1192
  return "$";
1055
1193
  if (i === "&")
1056
1194
  return match[0];
1057
- const num = +i;
1058
- if (num < match.length)
1195
+ if (+i < match.length)
1059
1196
  return match[+i];
1060
1197
  return `$${i}`;
1061
1198
  });
1062
- } else {
1063
- return replacement(...match, match.index, str, match.groups);
1064
- }
1065
- }
1066
- function matchAll(re, str) {
1067
- let match;
1068
- const matches = [];
1069
- while (match = re.exec(str)) {
1070
- matches.push(match);
1071
- }
1072
- return matches;
1199
+ else
1200
+ return replacement(match[0], ...match.slice(1), match.index, str, match.groups);
1073
1201
  }
1202
+ const replaceMatch = (match) => {
1203
+ if (match.index == null)
1204
+ return;
1205
+ const replacement = getReplacement(match, this.original);
1206
+ if (replacement === match[0])
1207
+ return;
1208
+ if (match[0].length === 0)
1209
+ this.appendRight(match.index, replacement);
1210
+ else
1211
+ this.overwrite(match.index, match.index + match[0].length, replacement);
1212
+ };
1074
1213
  if (searchValue.global) {
1075
- const matches = matchAll(searchValue, this.original);
1076
- matches.forEach((match) => {
1077
- if (match.index != null) {
1078
- const replacement2 = getReplacement(match, this.original);
1079
- if (replacement2 !== match[0]) {
1080
- this.overwrite(match.index, match.index + match[0].length, replacement2);
1081
- }
1082
- }
1083
- });
1214
+ searchValue.lastIndex = 0;
1215
+ for (const match of this.original.matchAll(searchValue))
1216
+ replaceMatch(match);
1084
1217
  } else {
1085
1218
  const match = this.original.match(searchValue);
1086
- if (match && match.index != null) {
1087
- const replacement2 = getReplacement(match, this.original);
1088
- if (replacement2 !== match[0]) {
1089
- this.overwrite(match.index, match.index + match[0].length, replacement2);
1090
- }
1091
- }
1219
+ if (match)
1220
+ replaceMatch(match);
1092
1221
  }
1093
1222
  return this;
1094
1223
  }
@@ -1096,182 +1225,897 @@ class MagicString {
1096
1225
  const { original } = this;
1097
1226
  const index = original.indexOf(string);
1098
1227
  if (index !== -1) {
1099
- if (typeof replacement === "function") {
1228
+ if (typeof replacement === "function")
1100
1229
  replacement = replacement(string, index, original);
1101
- }
1102
- if (string !== replacement) {
1103
- this.overwrite(index, index + string.length, replacement);
1104
- }
1230
+ if (string !== replacement)
1231
+ if (string.length === 0)
1232
+ this.appendRight(index, replacement);
1233
+ else
1234
+ this.overwrite(index, index + string.length, replacement);
1105
1235
  }
1106
1236
  return this;
1107
1237
  }
1108
1238
  replace(searchValue, replacement) {
1109
- if (typeof searchValue === "string") {
1239
+ if (typeof searchValue === "string")
1110
1240
  return this._replaceString(searchValue, replacement);
1111
- }
1112
1241
  return this._replaceRegexp(searchValue, replacement);
1113
1242
  }
1114
1243
  _replaceAllString(string, replacement) {
1115
1244
  const { original } = this;
1116
1245
  const stringLength = string.length;
1246
+ if (stringLength === 0) {
1247
+ for (let index = 0;index <= original.length; index += 1) {
1248
+ const _replacement = typeof replacement === "function" ? replacement("", index, original) : replacement;
1249
+ if (_replacement !== "")
1250
+ this.appendRight(index, _replacement);
1251
+ }
1252
+ return this;
1253
+ }
1117
1254
  for (let index = original.indexOf(string);index !== -1; index = original.indexOf(string, index + stringLength)) {
1118
1255
  const previous = original.slice(index, index + stringLength);
1119
- let _replacement = replacement;
1120
- if (typeof replacement === "function") {
1121
- _replacement = replacement(previous, index, original);
1122
- }
1256
+ const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : replacement;
1123
1257
  if (previous !== _replacement)
1124
1258
  this.overwrite(index, index + stringLength, _replacement);
1125
1259
  }
1126
1260
  return this;
1127
1261
  }
1128
1262
  replaceAll(searchValue, replacement) {
1129
- if (typeof searchValue === "string") {
1263
+ if (typeof searchValue === "string")
1130
1264
  return this._replaceAllString(searchValue, replacement);
1131
- }
1132
- if (!searchValue.global) {
1133
- throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
1134
- }
1265
+ if (!searchValue.global)
1266
+ throw new MagicStringError("replaceAll() requires a global RegExp");
1135
1267
  return this._replaceRegexp(searchValue, replacement);
1136
1268
  }
1137
- }
1138
-
1139
- // src/plugin/transform-client.ts
1140
- import {
1141
- parse
1142
- } from "yuku-parser";
1269
+ };
1270
+ // ../../node_modules/.bun/yuku-ast@0.9.4/node_modules/yuku-ast/dist/aliases.js
1271
+ var ALIAS_GROUPS = {
1272
+ Expression: [
1273
+ "Identifier",
1274
+ "Literal",
1275
+ "ThisExpression",
1276
+ "Super",
1277
+ "ArrayExpression",
1278
+ "ObjectExpression",
1279
+ "FunctionExpression",
1280
+ "ArrowFunctionExpression",
1281
+ "ClassExpression",
1282
+ "TaggedTemplateExpression",
1283
+ "TemplateLiteral",
1284
+ "MemberExpression",
1285
+ "CallExpression",
1286
+ "NewExpression",
1287
+ "ChainExpression",
1288
+ "SequenceExpression",
1289
+ "ParenthesizedExpression",
1290
+ "BinaryExpression",
1291
+ "LogicalExpression",
1292
+ "ConditionalExpression",
1293
+ "UnaryExpression",
1294
+ "UpdateExpression",
1295
+ "AssignmentExpression",
1296
+ "YieldExpression",
1297
+ "AwaitExpression",
1298
+ "ImportExpression",
1299
+ "MetaProperty",
1300
+ "TSAsExpression",
1301
+ "TSSatisfiesExpression",
1302
+ "TSTypeAssertion",
1303
+ "TSNonNullExpression",
1304
+ "TSInstantiationExpression",
1305
+ "JSXElement",
1306
+ "JSXFragment"
1307
+ ],
1308
+ Statement: [
1309
+ "ExpressionStatement",
1310
+ "BlockStatement",
1311
+ "EmptyStatement",
1312
+ "DebuggerStatement",
1313
+ "ReturnStatement",
1314
+ "LabeledStatement",
1315
+ "BreakStatement",
1316
+ "ContinueStatement",
1317
+ "IfStatement",
1318
+ "SwitchStatement",
1319
+ "ThrowStatement",
1320
+ "TryStatement",
1321
+ "WhileStatement",
1322
+ "DoWhileStatement",
1323
+ "ForStatement",
1324
+ "ForInStatement",
1325
+ "ForOfStatement",
1326
+ "WithStatement",
1327
+ "FunctionDeclaration",
1328
+ "ClassDeclaration",
1329
+ "VariableDeclaration",
1330
+ "TSDeclareFunction",
1331
+ "TSTypeAliasDeclaration",
1332
+ "TSInterfaceDeclaration",
1333
+ "TSEnumDeclaration",
1334
+ "TSModuleDeclaration",
1335
+ "TSImportEqualsDeclaration"
1336
+ ],
1337
+ Declaration: [
1338
+ "FunctionDeclaration",
1339
+ "ClassDeclaration",
1340
+ "VariableDeclaration",
1341
+ "TSDeclareFunction",
1342
+ "TSTypeAliasDeclaration",
1343
+ "TSInterfaceDeclaration",
1344
+ "TSEnumDeclaration",
1345
+ "TSModuleDeclaration",
1346
+ "TSImportEqualsDeclaration"
1347
+ ],
1348
+ ModuleDeclaration: [
1349
+ "ImportDeclaration",
1350
+ "ExportNamedDeclaration",
1351
+ "ExportDefaultDeclaration",
1352
+ "ExportAllDeclaration",
1353
+ "TSExportAssignment",
1354
+ "TSNamespaceExportDeclaration"
1355
+ ],
1356
+ Function: [
1357
+ "FunctionDeclaration",
1358
+ "FunctionExpression",
1359
+ "TSDeclareFunction",
1360
+ "TSEmptyBodyFunctionExpression",
1361
+ "ArrowFunctionExpression"
1362
+ ],
1363
+ Class: ["ClassDeclaration", "ClassExpression"],
1364
+ Method: ["MethodDefinition", "TSAbstractMethodDefinition"],
1365
+ Loop: ["DoWhileStatement", "ForInStatement", "ForOfStatement", "ForStatement", "WhileStatement"],
1366
+ Pattern: ["ArrayPattern", "ObjectPattern", "AssignmentPattern", "RestElement"],
1367
+ JSX: [
1368
+ "JSXAttribute",
1369
+ "JSXClosingElement",
1370
+ "JSXClosingFragment",
1371
+ "JSXElement",
1372
+ "JSXEmptyExpression",
1373
+ "JSXExpressionContainer",
1374
+ "JSXFragment",
1375
+ "JSXIdentifier",
1376
+ "JSXMemberExpression",
1377
+ "JSXNamespacedName",
1378
+ "JSXOpeningElement",
1379
+ "JSXOpeningFragment",
1380
+ "JSXSpreadAttribute",
1381
+ "JSXSpreadChild",
1382
+ "JSXText"
1383
+ ],
1384
+ TSType: [
1385
+ "TSAnyKeyword",
1386
+ "TSUnknownKeyword",
1387
+ "TSNeverKeyword",
1388
+ "TSVoidKeyword",
1389
+ "TSNullKeyword",
1390
+ "TSUndefinedKeyword",
1391
+ "TSStringKeyword",
1392
+ "TSNumberKeyword",
1393
+ "TSBigIntKeyword",
1394
+ "TSBooleanKeyword",
1395
+ "TSSymbolKeyword",
1396
+ "TSObjectKeyword",
1397
+ "TSIntrinsicKeyword",
1398
+ "TSThisType",
1399
+ "TSTypeReference",
1400
+ "TSTypeQuery",
1401
+ "TSImportType",
1402
+ "TSLiteralType",
1403
+ "TSTemplateLiteralType",
1404
+ "TSArrayType",
1405
+ "TSIndexedAccessType",
1406
+ "TSTupleType",
1407
+ "TSNamedTupleMember",
1408
+ "TSJSDocNullableType",
1409
+ "TSJSDocNonNullableType",
1410
+ "TSJSDocUnknownType",
1411
+ "TSUnionType",
1412
+ "TSIntersectionType",
1413
+ "TSConditionalType",
1414
+ "TSInferType",
1415
+ "TSTypeOperator",
1416
+ "TSParenthesizedType",
1417
+ "TSFunctionType",
1418
+ "TSConstructorType",
1419
+ "TSTypePredicate",
1420
+ "TSTypeLiteral",
1421
+ "TSMappedType"
1422
+ ]
1423
+ };
1424
+ var ALIAS_NAMES = Object.keys(ALIAS_GROUPS);
1143
1425
 
1144
- // src/server/lang-detect.ts
1145
- function detectLangFromPath(filePath) {
1146
- if (filePath.endsWith(".d.ts")) {
1147
- return "dts";
1426
+ // ../../node_modules/.bun/yuku-ast@0.9.4/node_modules/yuku-ast/dist/context.js
1427
+ class WalkContext {
1428
+ _ancestors = [];
1429
+ _node = null;
1430
+ _key = null;
1431
+ _list = null;
1432
+ _frame = null;
1433
+ _skip = false;
1434
+ _stopped = false;
1435
+ _removed = false;
1436
+ _replacement = null;
1437
+ state;
1438
+ get node() {
1439
+ return this._node;
1148
1440
  }
1149
- const ext = filePath.split(".").pop()?.toLowerCase();
1150
- switch (ext) {
1151
- case "ts":
1152
- return "ts";
1153
- case "tsx":
1154
- return "tsx";
1155
- case "jsx":
1156
- return "jsx";
1157
- default:
1158
- return "js";
1441
+ get parent() {
1442
+ const a = this._ancestors;
1443
+ return a.length === 0 ? null : a[a.length - 1];
1159
1444
  }
1160
- }
1161
- var TS_WRAPPER_TYPES = new Set([
1162
- "TSAsExpression",
1163
- "TSSatisfiesExpression",
1164
- "TSTypeAssertion",
1165
- "TSNonNullExpression",
1166
- "TSInstantiationExpression",
1167
- "ParenthesizedExpression"
1168
- ]);
1169
- function unwrapTSExpression(node) {
1170
- let current = node;
1171
- while (current && typeof current === "object" && TS_WRAPPER_TYPES.has(current.type) && current.expression && typeof current.expression === "object") {
1172
- current = current.expression;
1445
+ get key() {
1446
+ return this._key;
1173
1447
  }
1174
- return current;
1175
- }
1176
-
1177
- // src/shared/utils/ast-walk.ts
1178
- var SKIP_KEYS = new Set(["type", "start", "end", "comments"]);
1179
- function isAstNode(value) {
1180
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1181
- return false;
1448
+ get index() {
1449
+ return this._list === null ? null : this._frame.i;
1182
1450
  }
1183
- const candidate = value;
1184
- return typeof candidate.type === "string";
1185
- }
1186
- function walkAST(node, visitor) {
1187
- if (!node || typeof node !== "object") {
1188
- return;
1451
+ ancestors() {
1452
+ return [...this._ancestors];
1189
1453
  }
1190
- if (Array.isArray(node)) {
1191
- for (const child of node) {
1192
- walkAST(child, visitor);
1454
+ skip() {
1455
+ this._skip = true;
1456
+ }
1457
+ stop() {
1458
+ this._stopped = true;
1459
+ }
1460
+ replace(node) {
1461
+ if (node === null || typeof node !== "object" || typeof node.type !== "string") {
1462
+ throw new TypeError("replace: expected an AST node");
1193
1463
  }
1194
- return;
1464
+ if (this.parent === null) {
1465
+ throw new TypeError("replace: cannot replace the walk root");
1466
+ }
1467
+ if (node.start === 0 && node.end === 0) {
1468
+ node.start = this.node.start;
1469
+ node.end = this.node.end;
1470
+ }
1471
+ this._replacement = node;
1195
1472
  }
1196
- if (!isAstNode(node)) {
1197
- return;
1473
+ remove() {
1474
+ if (this.parent === null) {
1475
+ throw new TypeError("remove: cannot remove the walk root");
1476
+ }
1477
+ this._removed = true;
1198
1478
  }
1199
- const n2 = node;
1200
- visitor(n2);
1201
- for (const key of Object.keys(n2)) {
1202
- if (SKIP_KEYS.has(key)) {
1203
- continue;
1479
+ insertBefore(node) {
1480
+ this.#insert(node, 0);
1481
+ this._frame.i++;
1482
+ }
1483
+ insertAfter(node) {
1484
+ this.#insert(node, 1);
1485
+ }
1486
+ #insert(node, offset) {
1487
+ if (this._list === null) {
1488
+ throw new TypeError("insertBefore/insertAfter require a node in an array field");
1204
1489
  }
1205
- walkAST(n2[key], visitor);
1490
+ this._list.splice(this._frame.i + offset, 0, node);
1206
1491
  }
1207
1492
  }
1208
1493
 
1209
- // src/plugin/transform-client.ts
1210
- var SERVER_ONLY_PROPERTIES = new Set(["loader", "query", "params", "staticParams"]);
1211
- function isCreateRouteCall(node) {
1212
- return node.callee.type === "Identifier" && node.callee.name === "createRoute";
1494
+ // ../../node_modules/.bun/yuku-ast@0.9.4/node_modules/yuku-ast/dist/generated.js
1495
+ var KEYS = Object.create(null);
1496
+ function ck(type, keys) {
1497
+ const prev = KEYS[type];
1498
+ if (prev === undefined)
1499
+ KEYS[type] = keys;
1500
+ else
1501
+ for (const k of keys)
1502
+ if (!prev.includes(k))
1503
+ prev.push(k);
1213
1504
  }
1214
- function isRoutePageCall(node) {
1215
- const { callee } = node;
1216
- if (callee.type === "Identifier" && callee.name === "page") {
1217
- return true;
1505
+ ck("SequenceExpression", ["expressions"]);
1506
+ ck("ParenthesizedExpression", ["expression"]);
1507
+ ck("ArrowFunctionExpression", ["typeParameters", "params", "returnType", "body"]);
1508
+ ck("FunctionDeclaration", ["id", "typeParameters", "params", "returnType", "body"]);
1509
+ ck("FunctionExpression", ["id", "typeParameters", "params", "returnType", "body"]);
1510
+ ck("TSDeclareFunction", ["id", "typeParameters", "params", "returnType", "body"]);
1511
+ ck("TSEmptyBodyFunctionExpression", ["id", "typeParameters", "params", "returnType", "body"]);
1512
+ ck("BlockStatement", ["body"]);
1513
+ ck("BlockStatement", ["body"]);
1514
+ ck("BinaryExpression", ["left", "right"]);
1515
+ ck("LogicalExpression", ["left", "right"]);
1516
+ ck("ConditionalExpression", ["test", "consequent", "alternate"]);
1517
+ ck("UnaryExpression", ["argument"]);
1518
+ ck("UpdateExpression", ["argument"]);
1519
+ ck("AssignmentExpression", ["left", "right"]);
1520
+ ck("ArrayExpression", ["elements"]);
1521
+ ck("ObjectExpression", ["properties"]);
1522
+ ck("SpreadElement", ["argument"]);
1523
+ ck("Property", ["key", "value"]);
1524
+ ck("MemberExpression", ["object", "property"]);
1525
+ ck("CallExpression", ["callee", "typeArguments", "arguments"]);
1526
+ ck("ChainExpression", ["expression"]);
1527
+ ck("TaggedTemplateExpression", ["tag", "typeArguments", "quasi"]);
1528
+ ck("NewExpression", ["callee", "typeArguments", "arguments"]);
1529
+ ck("AwaitExpression", ["argument"]);
1530
+ ck("YieldExpression", ["argument"]);
1531
+ ck("MetaProperty", ["meta", "property"]);
1532
+ ck("Decorator", ["expression"]);
1533
+ ck("ClassDeclaration", ["decorators", "id", "typeParameters", "superClass", "superTypeArguments", "implements", "body"]);
1534
+ ck("ClassExpression", ["decorators", "id", "typeParameters", "superClass", "superTypeArguments", "implements", "body"]);
1535
+ ck("ClassBody", ["body"]);
1536
+ ck("MethodDefinition", ["decorators", "key", "value"]);
1537
+ ck("TSAbstractMethodDefinition", ["decorators", "key", "value"]);
1538
+ ck("PropertyDefinition", ["decorators", "key", "typeAnnotation", "value"]);
1539
+ ck("AccessorProperty", ["decorators", "key", "typeAnnotation", "value"]);
1540
+ ck("TSAbstractPropertyDefinition", ["decorators", "key", "typeAnnotation", "value"]);
1541
+ ck("TSAbstractAccessorProperty", ["decorators", "key", "typeAnnotation", "value"]);
1542
+ ck("StaticBlock", ["body"]);
1543
+ ck("Super", []);
1544
+ ck("Literal", []);
1545
+ ck("Literal", []);
1546
+ ck("Literal", []);
1547
+ ck("Literal", []);
1548
+ ck("Literal", []);
1549
+ ck("ThisExpression", []);
1550
+ ck("Literal", []);
1551
+ ck("TemplateLiteral", ["quasis", "expressions"]);
1552
+ ck("TemplateElement", []);
1553
+ ck("Identifier", []);
1554
+ ck("PrivateIdentifier", []);
1555
+ ck("Identifier", ["decorators", "typeAnnotation"]);
1556
+ ck("Identifier", []);
1557
+ ck("Identifier", []);
1558
+ ck("ExpressionStatement", ["expression"]);
1559
+ ck("IfStatement", ["test", "consequent", "alternate"]);
1560
+ ck("SwitchStatement", ["discriminant", "cases"]);
1561
+ ck("SwitchCase", ["test", "consequent"]);
1562
+ ck("ForStatement", ["init", "test", "update", "body"]);
1563
+ ck("ForInStatement", ["left", "right", "body"]);
1564
+ ck("ForOfStatement", ["left", "right", "body"]);
1565
+ ck("WhileStatement", ["test", "body"]);
1566
+ ck("DoWhileStatement", ["body", "test"]);
1567
+ ck("BreakStatement", ["label"]);
1568
+ ck("ContinueStatement", ["label"]);
1569
+ ck("LabeledStatement", ["label", "body"]);
1570
+ ck("WithStatement", ["object", "body"]);
1571
+ ck("ReturnStatement", ["argument"]);
1572
+ ck("ThrowStatement", ["argument"]);
1573
+ ck("TryStatement", ["block", "handler", "finalizer"]);
1574
+ ck("CatchClause", ["param", "body"]);
1575
+ ck("DebuggerStatement", []);
1576
+ ck("EmptyStatement", []);
1577
+ ck("VariableDeclaration", ["declarations"]);
1578
+ ck("VariableDeclarator", ["id", "init"]);
1579
+ ck("ExpressionStatement", ["expression"]);
1580
+ ck("AssignmentPattern", ["decorators", "left", "typeAnnotation", "right"]);
1581
+ ck("RestElement", ["decorators", "argument", "typeAnnotation"]);
1582
+ ck("ArrayPattern", ["decorators", "elements", "typeAnnotation"]);
1583
+ ck("ObjectPattern", ["decorators", "properties", "typeAnnotation"]);
1584
+ ck("Property", ["key", "value"]);
1585
+ ck("Program", ["hashbang", "body"]);
1586
+ ck("ImportExpression", ["source", "options"]);
1587
+ ck("ImportDeclaration", ["specifiers", "source", "attributes"]);
1588
+ ck("ImportSpecifier", ["imported", "local"]);
1589
+ ck("ImportDefaultSpecifier", ["local"]);
1590
+ ck("ImportNamespaceSpecifier", ["local"]);
1591
+ ck("ImportAttribute", ["key", "value"]);
1592
+ ck("ExportNamedDeclaration", ["declaration", "specifiers", "source", "attributes"]);
1593
+ ck("ExportDefaultDeclaration", ["declaration"]);
1594
+ ck("ExportAllDeclaration", ["exported", "source", "attributes"]);
1595
+ ck("ExportSpecifier", ["local", "exported"]);
1596
+ ck("TSTypeAnnotation", ["typeAnnotation"]);
1597
+ ck("TSAnyKeyword", []);
1598
+ ck("TSUnknownKeyword", []);
1599
+ ck("TSNeverKeyword", []);
1600
+ ck("TSVoidKeyword", []);
1601
+ ck("TSNullKeyword", []);
1602
+ ck("TSUndefinedKeyword", []);
1603
+ ck("TSStringKeyword", []);
1604
+ ck("TSNumberKeyword", []);
1605
+ ck("TSBigIntKeyword", []);
1606
+ ck("TSBooleanKeyword", []);
1607
+ ck("TSSymbolKeyword", []);
1608
+ ck("TSObjectKeyword", []);
1609
+ ck("TSIntrinsicKeyword", []);
1610
+ ck("TSThisType", []);
1611
+ ck("TSTypeReference", ["typeName", "typeArguments"]);
1612
+ ck("TSQualifiedName", ["left", "right"]);
1613
+ ck("TSTypeQuery", ["exprName", "typeArguments"]);
1614
+ ck("TSImportType", ["source", "options", "qualifier", "typeArguments"]);
1615
+ ck("TSTypeParameter", ["name", "constraint", "default"]);
1616
+ ck("TSTypeParameterDeclaration", ["params"]);
1617
+ ck("TSTypeParameterInstantiation", ["params"]);
1618
+ ck("TSLiteralType", ["literal"]);
1619
+ ck("TSTemplateLiteralType", ["quasis", "types"]);
1620
+ ck("TSArrayType", ["elementType"]);
1621
+ ck("TSIndexedAccessType", ["objectType", "indexType"]);
1622
+ ck("TSTupleType", ["elementTypes"]);
1623
+ ck("TSNamedTupleMember", ["label", "elementType"]);
1624
+ ck("TSOptionalType", ["typeAnnotation"]);
1625
+ ck("TSRestType", ["typeAnnotation"]);
1626
+ ck("TSJSDocNullableType", ["typeAnnotation"]);
1627
+ ck("TSJSDocNonNullableType", ["typeAnnotation"]);
1628
+ ck("TSJSDocUnknownType", []);
1629
+ ck("TSUnionType", ["types"]);
1630
+ ck("TSIntersectionType", ["types"]);
1631
+ ck("TSConditionalType", ["checkType", "extendsType", "trueType", "falseType"]);
1632
+ ck("TSInferType", ["typeParameter"]);
1633
+ ck("TSTypeOperator", ["typeAnnotation"]);
1634
+ ck("TSParenthesizedType", ["typeAnnotation"]);
1635
+ ck("TSFunctionType", ["typeParameters", "params", "returnType"]);
1636
+ ck("TSConstructorType", ["typeParameters", "params", "returnType"]);
1637
+ ck("TSTypePredicate", ["parameterName", "typeAnnotation"]);
1638
+ ck("TSTypeLiteral", ["members"]);
1639
+ ck("TSMappedType", ["key", "constraint", "nameType", "typeAnnotation"]);
1640
+ ck("TSPropertySignature", ["key", "typeAnnotation"]);
1641
+ ck("TSMethodSignature", ["key", "typeParameters", "params", "returnType"]);
1642
+ ck("TSCallSignatureDeclaration", ["typeParameters", "params", "returnType"]);
1643
+ ck("TSConstructSignatureDeclaration", ["typeParameters", "params", "returnType"]);
1644
+ ck("TSIndexSignature", ["parameters", "typeAnnotation"]);
1645
+ ck("TSTypeAliasDeclaration", ["id", "typeParameters", "typeAnnotation"]);
1646
+ ck("TSInterfaceDeclaration", ["id", "typeParameters", "extends", "body"]);
1647
+ ck("TSInterfaceBody", ["body"]);
1648
+ ck("TSInterfaceHeritage", ["expression", "typeArguments"]);
1649
+ ck("TSClassImplements", ["expression", "typeArguments"]);
1650
+ ck("TSEnumDeclaration", ["id", "body"]);
1651
+ ck("TSEnumBody", ["members"]);
1652
+ ck("TSEnumMember", ["id", "initializer"]);
1653
+ ck("TSModuleDeclaration", ["id", "body"]);
1654
+ ck("TSModuleBlock", ["body"]);
1655
+ ck("TSModuleDeclaration", ["id", "body"]);
1656
+ ck("TSParameterProperty", ["decorators", "parameter"]);
1657
+ ck("Identifier", ["typeAnnotation"]);
1658
+ ck("TSAsExpression", ["expression", "typeAnnotation"]);
1659
+ ck("TSSatisfiesExpression", ["expression", "typeAnnotation"]);
1660
+ ck("TSTypeAssertion", ["typeAnnotation", "expression"]);
1661
+ ck("TSNonNullExpression", ["expression"]);
1662
+ ck("TSInstantiationExpression", ["expression", "typeArguments"]);
1663
+ ck("TSExportAssignment", ["expression"]);
1664
+ ck("TSNamespaceExportDeclaration", ["id"]);
1665
+ ck("TSImportEqualsDeclaration", ["id", "moduleReference"]);
1666
+ ck("TSExternalModuleReference", ["expression"]);
1667
+ ck("JSXElement", ["openingElement", "children", "closingElement"]);
1668
+ ck("JSXOpeningElement", ["name", "typeArguments", "attributes"]);
1669
+ ck("JSXClosingElement", ["name"]);
1670
+ ck("JSXFragment", ["openingFragment", "children", "closingFragment"]);
1671
+ ck("JSXOpeningFragment", []);
1672
+ ck("JSXClosingFragment", []);
1673
+ ck("JSXIdentifier", []);
1674
+ ck("JSXNamespacedName", ["namespace", "name"]);
1675
+ ck("JSXMemberExpression", ["object", "property"]);
1676
+ ck("JSXAttribute", ["name", "value"]);
1677
+ ck("JSXSpreadAttribute", ["argument"]);
1678
+ ck("JSXExpressionContainer", ["expression"]);
1679
+ ck("JSXEmptyExpression", []);
1680
+ ck("JSXText", []);
1681
+ ck("JSXSpreadChild", ["expression"]);
1682
+ ck("Hashbang", []);
1683
+ var CHILD_KEYS = KEYS;
1684
+ var TYPES = [
1685
+ "SequenceExpression",
1686
+ "ParenthesizedExpression",
1687
+ "ArrowFunctionExpression",
1688
+ "FunctionDeclaration",
1689
+ "FunctionExpression",
1690
+ "TSDeclareFunction",
1691
+ "TSEmptyBodyFunctionExpression",
1692
+ "BlockStatement",
1693
+ "BlockStatement",
1694
+ "BinaryExpression",
1695
+ "LogicalExpression",
1696
+ "ConditionalExpression",
1697
+ "UnaryExpression",
1698
+ "UpdateExpression",
1699
+ "AssignmentExpression",
1700
+ "ArrayExpression",
1701
+ "ObjectExpression",
1702
+ "SpreadElement",
1703
+ "Property",
1704
+ "MemberExpression",
1705
+ "CallExpression",
1706
+ "ChainExpression",
1707
+ "TaggedTemplateExpression",
1708
+ "NewExpression",
1709
+ "AwaitExpression",
1710
+ "YieldExpression",
1711
+ "MetaProperty",
1712
+ "Decorator",
1713
+ "ClassDeclaration",
1714
+ "ClassExpression",
1715
+ "ClassBody",
1716
+ "MethodDefinition",
1717
+ "TSAbstractMethodDefinition",
1718
+ "PropertyDefinition",
1719
+ "AccessorProperty",
1720
+ "TSAbstractPropertyDefinition",
1721
+ "TSAbstractAccessorProperty",
1722
+ "StaticBlock",
1723
+ "Super",
1724
+ "Literal",
1725
+ "Literal",
1726
+ "Literal",
1727
+ "Literal",
1728
+ "Literal",
1729
+ "ThisExpression",
1730
+ "Literal",
1731
+ "TemplateLiteral",
1732
+ "TemplateElement",
1733
+ "Identifier",
1734
+ "PrivateIdentifier",
1735
+ "Identifier",
1736
+ "Identifier",
1737
+ "Identifier",
1738
+ "ExpressionStatement",
1739
+ "IfStatement",
1740
+ "SwitchStatement",
1741
+ "SwitchCase",
1742
+ "ForStatement",
1743
+ "ForInStatement",
1744
+ "ForOfStatement",
1745
+ "WhileStatement",
1746
+ "DoWhileStatement",
1747
+ "BreakStatement",
1748
+ "ContinueStatement",
1749
+ "LabeledStatement",
1750
+ "WithStatement",
1751
+ "ReturnStatement",
1752
+ "ThrowStatement",
1753
+ "TryStatement",
1754
+ "CatchClause",
1755
+ "DebuggerStatement",
1756
+ "EmptyStatement",
1757
+ "VariableDeclaration",
1758
+ "VariableDeclarator",
1759
+ "ExpressionStatement",
1760
+ "AssignmentPattern",
1761
+ "RestElement",
1762
+ "ArrayPattern",
1763
+ "ObjectPattern",
1764
+ "Property",
1765
+ "Program",
1766
+ "ImportExpression",
1767
+ "ImportDeclaration",
1768
+ "ImportSpecifier",
1769
+ "ImportDefaultSpecifier",
1770
+ "ImportNamespaceSpecifier",
1771
+ "ImportAttribute",
1772
+ "ExportNamedDeclaration",
1773
+ "ExportDefaultDeclaration",
1774
+ "ExportAllDeclaration",
1775
+ "ExportSpecifier",
1776
+ "TSTypeAnnotation",
1777
+ "TSAnyKeyword",
1778
+ "TSUnknownKeyword",
1779
+ "TSNeverKeyword",
1780
+ "TSVoidKeyword",
1781
+ "TSNullKeyword",
1782
+ "TSUndefinedKeyword",
1783
+ "TSStringKeyword",
1784
+ "TSNumberKeyword",
1785
+ "TSBigIntKeyword",
1786
+ "TSBooleanKeyword",
1787
+ "TSSymbolKeyword",
1788
+ "TSObjectKeyword",
1789
+ "TSIntrinsicKeyword",
1790
+ "TSThisType",
1791
+ "TSTypeReference",
1792
+ "TSQualifiedName",
1793
+ "TSTypeQuery",
1794
+ "TSImportType",
1795
+ "TSTypeParameter",
1796
+ "TSTypeParameterDeclaration",
1797
+ "TSTypeParameterInstantiation",
1798
+ "TSLiteralType",
1799
+ "TSTemplateLiteralType",
1800
+ "TSArrayType",
1801
+ "TSIndexedAccessType",
1802
+ "TSTupleType",
1803
+ "TSNamedTupleMember",
1804
+ "TSOptionalType",
1805
+ "TSRestType",
1806
+ "TSJSDocNullableType",
1807
+ "TSJSDocNonNullableType",
1808
+ "TSJSDocUnknownType",
1809
+ "TSUnionType",
1810
+ "TSIntersectionType",
1811
+ "TSConditionalType",
1812
+ "TSInferType",
1813
+ "TSTypeOperator",
1814
+ "TSParenthesizedType",
1815
+ "TSFunctionType",
1816
+ "TSConstructorType",
1817
+ "TSTypePredicate",
1818
+ "TSTypeLiteral",
1819
+ "TSMappedType",
1820
+ "TSPropertySignature",
1821
+ "TSMethodSignature",
1822
+ "TSCallSignatureDeclaration",
1823
+ "TSConstructSignatureDeclaration",
1824
+ "TSIndexSignature",
1825
+ "TSTypeAliasDeclaration",
1826
+ "TSInterfaceDeclaration",
1827
+ "TSInterfaceBody",
1828
+ "TSInterfaceHeritage",
1829
+ "TSClassImplements",
1830
+ "TSEnumDeclaration",
1831
+ "TSEnumBody",
1832
+ "TSEnumMember",
1833
+ "TSModuleDeclaration",
1834
+ "TSModuleBlock",
1835
+ "TSModuleDeclaration",
1836
+ "TSParameterProperty",
1837
+ "Identifier",
1838
+ "TSAsExpression",
1839
+ "TSSatisfiesExpression",
1840
+ "TSTypeAssertion",
1841
+ "TSNonNullExpression",
1842
+ "TSInstantiationExpression",
1843
+ "TSExportAssignment",
1844
+ "TSNamespaceExportDeclaration",
1845
+ "TSImportEqualsDeclaration",
1846
+ "TSExternalModuleReference",
1847
+ "JSXElement",
1848
+ "JSXOpeningElement",
1849
+ "JSXClosingElement",
1850
+ "JSXFragment",
1851
+ "JSXOpeningFragment",
1852
+ "JSXClosingFragment",
1853
+ "JSXIdentifier",
1854
+ "JSXNamespacedName",
1855
+ "JSXMemberExpression",
1856
+ "JSXAttribute",
1857
+ "JSXSpreadAttribute",
1858
+ "JSXExpressionContainer",
1859
+ "JSXEmptyExpression",
1860
+ "JSXText",
1861
+ "JSXSpreadChild",
1862
+ "Hashbang"
1863
+ ];
1864
+ var NODE_TYPES = [...new Set(TYPES)];
1865
+
1866
+ // ../../node_modules/.bun/yuku-ast@0.9.4/node_modules/yuku-ast/dist/walk.js
1867
+ function createDispatch(visitors) {
1868
+ let enter = null;
1869
+ let leave = null;
1870
+ const concrete = new Map;
1871
+ const add = (type, handler) => {
1872
+ const hooks = typeof handler === "function" ? { enter: handler } : handler;
1873
+ let entry = concrete.get(type);
1874
+ if (entry === undefined) {
1875
+ entry = { enter: [], leave: [] };
1876
+ concrete.set(type, entry);
1877
+ }
1878
+ if (hooks.enter)
1879
+ entry.enter.push(hooks.enter);
1880
+ if (hooks.leave)
1881
+ entry.leave.unshift(hooks.leave);
1882
+ };
1883
+ for (const [name, value] of Object.entries(visitors)) {
1884
+ if (value == null)
1885
+ continue;
1886
+ if (name === "enter")
1887
+ enter = value;
1888
+ else if (name === "leave")
1889
+ leave = value;
1890
+ else if (name in ALIAS_GROUPS) {
1891
+ for (const type of ALIAS_GROUPS[name])
1892
+ add(type, value);
1893
+ }
1218
1894
  }
1219
- if (callee.type === "MemberExpression" && callee.property.type === "Identifier" && callee.property.name === "page") {
1220
- return true;
1895
+ for (const [name, value] of Object.entries(visitors)) {
1896
+ if (value == null || name === "enter" || name === "leave" || name in ALIAS_GROUPS)
1897
+ continue;
1898
+ add(name, value);
1221
1899
  }
1222
- return false;
1900
+ return { enter, leave, typed: (type) => concrete.get(type) };
1223
1901
  }
1224
- function isTargetCall(node) {
1225
- return isCreateRouteCall(node) || isRoutePageCall(node);
1902
+ function walk(root, visitors, state) {
1903
+ _walk(root, visitors, state, new WalkContext);
1904
+ return root;
1226
1905
  }
1227
- function isObjectExpressionNode(node) {
1228
- return node.type === "ObjectExpression";
1906
+ function position(ctx, node, key, list, frame) {
1907
+ ctx._node = node;
1908
+ ctx._key = key;
1909
+ ctx._list = list;
1910
+ ctx._frame = frame;
1229
1911
  }
1230
- function removeServerProperties(s, source, obj) {
1231
- const toRemove = obj.properties.filter((p) => {
1232
- if (p.type !== "Property") {
1233
- return false;
1912
+ function applyReplace(ctx, parent, key, list, frame) {
1913
+ const next = ctx._replacement;
1914
+ ctx._replacement = null;
1915
+ if (list !== null)
1916
+ list[frame.i] = next;
1917
+ else
1918
+ parent[key] = next;
1919
+ return next;
1920
+ }
1921
+ function applyRemove(ctx, parent, key, list, frame) {
1922
+ ctx._removed = false;
1923
+ if (list !== null) {
1924
+ list.splice(frame.i, 1);
1925
+ frame.i--;
1926
+ } else {
1927
+ parent[key] = null;
1928
+ }
1929
+ }
1930
+ function _walk(root, visitors, state, ctx) {
1931
+ const d = createDispatch(visitors);
1932
+ ctx.state = state;
1933
+ const ancestors = ctx._ancestors;
1934
+ (function visit(node, key, list, frame) {
1935
+ let typed = d.typed(node.type);
1936
+ const parent = ctx.parent;
1937
+ position(ctx, node, key, list, frame);
1938
+ if (d.enter !== null) {
1939
+ d.enter(node, ctx);
1940
+ if (ctx._stopped)
1941
+ return false;
1234
1942
  }
1235
- const { key } = p;
1236
- if (p.computed) {
1237
- return false;
1943
+ if (typed !== undefined) {
1944
+ for (const handler of typed.enter) {
1945
+ handler(node, ctx);
1946
+ if (ctx._stopped)
1947
+ return false;
1948
+ }
1238
1949
  }
1239
- if (key.type === "Identifier" && typeof key.name === "string") {
1240
- return SERVER_ONLY_PROPERTIES.has(key.name);
1950
+ if (ctx._removed) {
1951
+ applyRemove(ctx, parent, key, list, frame);
1952
+ return true;
1241
1953
  }
1242
- if (key.type === "Literal" && typeof key.value === "string") {
1243
- return SERVER_ONLY_PROPERTIES.has(key.value);
1954
+ if (ctx._replacement !== null) {
1955
+ node = applyReplace(ctx, parent, key, list, frame);
1956
+ typed = d.typed(node.type);
1957
+ }
1958
+ const skipped = ctx._skip;
1959
+ ctx._skip = false;
1960
+ if (!skipped) {
1961
+ const keys = CHILD_KEYS[node.type];
1962
+ if (keys !== undefined && keys.length > 0) {
1963
+ ancestors.push(node);
1964
+ for (let k = 0;k < keys.length; k++) {
1965
+ const key2 = keys[k];
1966
+ const value = node[key2];
1967
+ if (value === null || value === undefined || typeof value !== "object")
1968
+ continue;
1969
+ if (Array.isArray(value)) {
1970
+ const childFrame = { i: 0 };
1971
+ for (;childFrame.i < value.length; childFrame.i++) {
1972
+ const item = value[childFrame.i];
1973
+ if (item !== null && !visit(item, key2, value, childFrame))
1974
+ return false;
1975
+ }
1976
+ } else if (!visit(value, key2, null, null)) {
1977
+ return false;
1978
+ }
1979
+ }
1980
+ ancestors.pop();
1981
+ }
1244
1982
  }
1245
- return false;
1246
- });
1247
- if (toRemove.length === 0) {
1248
- return false;
1249
- }
1250
- for (const prop of toRemove) {
1251
- let removeEnd = prop.end;
1252
- while (removeEnd < source.length && (source[removeEnd] === "," || source[removeEnd] === " " || source[removeEnd] === `
1253
- ` || source[removeEnd] === "\r" || source[removeEnd] === "\t")) {
1254
- if (source[removeEnd] === ",") {
1255
- removeEnd++;
1256
- break;
1983
+ position(ctx, node, key, list, frame);
1984
+ if (typed !== undefined) {
1985
+ for (const handler of typed.leave) {
1986
+ handler(node, ctx);
1987
+ if (ctx._stopped)
1988
+ return false;
1257
1989
  }
1258
- removeEnd++;
1259
1990
  }
1260
- let removeStart = prop.start;
1261
- while (removeStart > 0 && (source[removeStart - 1] === " " || source[removeStart - 1] === "\t")) {
1262
- removeStart--;
1991
+ if (d.leave !== null) {
1992
+ d.leave(node, ctx);
1993
+ if (ctx._stopped)
1994
+ return false;
1263
1995
  }
1264
- if (removeStart > 0 && source[removeStart - 1] === `
1265
- `) {
1266
- removeStart--;
1267
- if (removeStart > 0 && source[removeStart - 1] === "\r") {
1268
- removeStart--;
1996
+ if (ctx._removed)
1997
+ applyRemove(ctx, parent, key, list, frame);
1998
+ else if (ctx._replacement !== null)
1999
+ applyReplace(ctx, parent, key, list, frame);
2000
+ return true;
2001
+ })(root, null, null, null);
2002
+ }
2003
+ // src/shared/parser.ts
2004
+ import { parse } from "yuku-parser";
2005
+ function parseSource(code, lang) {
2006
+ return parse(code, { lang, sourceType: "module" });
2007
+ }
2008
+
2009
+ // src/plugin/binding-scope.ts
2010
+ function bindingPatternHasName(pattern, name) {
2011
+ if (!(pattern && typeof pattern === "object")) {
2012
+ return false;
2013
+ }
2014
+ const node = pattern;
2015
+ if (node.type === "Identifier") {
2016
+ return node.name === name;
2017
+ }
2018
+ if (node.type === "AssignmentPattern") {
2019
+ return bindingPatternHasName(node.left, name);
2020
+ }
2021
+ if (node.type === "RestElement") {
2022
+ return bindingPatternHasName(node.argument, name);
2023
+ }
2024
+ if (node.type === "ArrayPattern") {
2025
+ return Array.isArray(node.elements) && node.elements.some((element) => bindingPatternHasName(element, name));
2026
+ }
2027
+ if (node.type === "ObjectPattern") {
2028
+ return Array.isArray(node.properties) && node.properties.some((property) => {
2029
+ if (!(property && typeof property === "object")) {
2030
+ return false;
1269
2031
  }
2032
+ const propertyNode = property;
2033
+ return bindingPatternHasName(propertyNode.type === "Property" ? propertyNode.value : propertyNode.argument, name);
2034
+ });
2035
+ }
2036
+ if (node.type === "TSParameterProperty") {
2037
+ return bindingPatternHasName(node.parameter, name);
2038
+ }
2039
+ return false;
2040
+ }
2041
+ function declarationHasName(node, name) {
2042
+ if (node.type === "VariableDeclaration" && Array.isArray(node.declarations)) {
2043
+ return node.declarations.some((declaration) => declaration && typeof declaration === "object" ? bindingPatternHasName(declaration.id, name) : false);
2044
+ }
2045
+ if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
2046
+ return bindingPatternHasName(node.id, name);
2047
+ }
2048
+ return false;
2049
+ }
2050
+ function functionBodyHasVarName(value, name, root) {
2051
+ if (!value || typeof value !== "object") {
2052
+ return false;
2053
+ }
2054
+ if (Array.isArray(value)) {
2055
+ return value.some((entry) => functionBodyHasVarName(entry, name, false));
2056
+ }
2057
+ const node = value;
2058
+ if (!root && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "StaticBlock")) {
2059
+ return false;
2060
+ }
2061
+ if (node.type === "VariableDeclaration" && node.kind === "var" && Array.isArray(node.declarations) && node.declarations.some((declaration) => declaration && typeof declaration === "object" ? bindingPatternHasName(declaration.id, name) : false)) {
2062
+ return true;
2063
+ }
2064
+ return Object.values(node).some((entry) => functionBodyHasVarName(entry, name, false));
2065
+ }
2066
+ function functionScopeHasName(scope, name) {
2067
+ if (scope.type !== "FunctionDeclaration" && scope.type !== "FunctionExpression" && scope.type !== "ArrowFunctionExpression") {
2068
+ return false;
2069
+ }
2070
+ return Array.isArray(scope.params) && scope.params.some((parameter) => bindingPatternHasName(parameter, name)) || scope.type === "FunctionExpression" && bindingPatternHasName(scope.id, name) || functionBodyHasVarName(scope.body, name, true);
2071
+ }
2072
+ function blockScopeHasName(scope, name) {
2073
+ return scope.type === "BlockStatement" && Array.isArray(scope.body) && scope.body.some((statement) => statement && typeof statement === "object" ? declarationHasName(statement, name) : false);
2074
+ }
2075
+ function loopScopeHasName(scope, name) {
2076
+ const declaration = scope.type === "ForStatement" ? scope.init : scope.left;
2077
+ return (scope.type === "ForStatement" || scope.type === "ForInStatement" || scope.type === "ForOfStatement") && !!declaration && typeof declaration === "object" && declarationHasName(declaration, name);
2078
+ }
2079
+ function switchScopeHasName(scope, name) {
2080
+ return scope.type === "SwitchStatement" && Array.isArray(scope.cases) && scope.cases.some((switchCase) => switchCase && typeof switchCase === "object" && Array.isArray(switchCase.consequent) && switchCase.consequent.some((statement) => statement && typeof statement === "object" && declarationHasName(statement, name)));
2081
+ }
2082
+ function hasShadowingDeclaration(name, ancestors) {
2083
+ return ancestors.some((scope) => functionScopeHasName(scope, name) || scope.type === "CatchClause" && bindingPatternHasName(scope.param, name) || blockScopeHasName(scope, name) || loopScopeHasName(scope, name) || switchScopeHasName(scope, name));
2084
+ }
2085
+
2086
+ // src/shared/utils/ast-walk.ts
2087
+ var SKIP_KEYS = new Set(["type", "start", "end", "comments"]);
2088
+ function isAstNode(value) {
2089
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
2090
+ return false;
2091
+ }
2092
+ const candidate = value;
2093
+ return typeof candidate.type === "string";
2094
+ }
2095
+ function walkAST(node, visitor) {
2096
+ if (!node || typeof node !== "object") {
2097
+ return;
2098
+ }
2099
+ if (Array.isArray(node)) {
2100
+ for (const child of node) {
2101
+ walkAST(child, visitor);
1270
2102
  }
1271
- s.remove(removeStart, removeEnd);
2103
+ return;
2104
+ }
2105
+ if (!isAstNode(node)) {
2106
+ return;
2107
+ }
2108
+ const n = node;
2109
+ visitor(n);
2110
+ for (const key of Object.keys(n)) {
2111
+ if (SKIP_KEYS.has(key)) {
2112
+ continue;
2113
+ }
2114
+ walkAST(n[key], visitor);
1272
2115
  }
1273
- return true;
1274
2116
  }
2117
+
2118
+ // src/plugin/dead-code-elimination.ts
1275
2119
  var TYPE_SCOPE_NODES = new Set([
1276
2120
  "TSTypeAnnotation",
1277
2121
  "TSTypeParameterDeclaration",
@@ -1279,7 +2123,8 @@ var TYPE_SCOPE_NODES = new Set([
1279
2123
  "TSInterfaceDeclaration",
1280
2124
  "TSTypeAliasDeclaration",
1281
2125
  "TSTypePredicate",
1282
- "TSClassImplements"
2126
+ "TSClassImplements",
2127
+ "TSExpressionWithTypeArguments"
1283
2128
  ]);
1284
2129
  function markTypeDescendants(node, excluded) {
1285
2130
  if (!node || typeof node !== "object") {
@@ -1291,15 +2136,15 @@ function markTypeDescendants(node, excluded) {
1291
2136
  }
1292
2137
  return;
1293
2138
  }
1294
- const n2 = node;
1295
- if (n2.type === "Identifier" || n2.type === "JSXIdentifier") {
1296
- excluded.add(n2);
2139
+ const astNode = node;
2140
+ if (astNode.type === "Identifier" || astNode.type === "JSXIdentifier") {
2141
+ excluded.add(astNode);
1297
2142
  }
1298
- for (const key of Object.keys(n2)) {
2143
+ for (const key of Object.keys(astNode)) {
1299
2144
  if (key === "type" || key === "start" || key === "end") {
1300
2145
  continue;
1301
2146
  }
1302
- markTypeDescendants(n2[key], excluded);
2147
+ markTypeDescendants(astNode[key], excluded);
1303
2148
  }
1304
2149
  }
1305
2150
  function excludeTypePositionIdentifiers(node, excluded) {
@@ -1314,11 +2159,11 @@ function excludeTypePositionIdentifiers(node, excluded) {
1314
2159
  function collectReferencedNames(program) {
1315
2160
  const refs = new Set;
1316
2161
  const excluded = new Set;
1317
- for (const stmt of program.body) {
1318
- if (stmt.type === "ImportDeclaration") {
2162
+ for (const statement of program.body) {
2163
+ if (statement.type === "ImportDeclaration") {
1319
2164
  continue;
1320
2165
  }
1321
- walkAST(stmt, (node) => {
2166
+ walkAST(statement, (node) => {
1322
2167
  if (node.type === "Property" && !node.computed) {
1323
2168
  excluded.add(node.key);
1324
2169
  }
@@ -1334,11 +2179,11 @@ function collectReferencedNames(program) {
1334
2179
  excludeTypePositionIdentifiers(node, excluded);
1335
2180
  });
1336
2181
  }
1337
- for (const stmt of program.body) {
1338
- if (stmt.type === "ImportDeclaration") {
2182
+ for (const statement of program.body) {
2183
+ if (statement.type === "ImportDeclaration") {
1339
2184
  continue;
1340
2185
  }
1341
- walkAST(stmt, (node) => {
2186
+ walkAST(statement, (node) => {
1342
2187
  if (excluded.has(node)) {
1343
2188
  return;
1344
2189
  }
@@ -1349,104 +2194,483 @@ function collectReferencedNames(program) {
1349
2194
  }
1350
2195
  return refs;
1351
2196
  }
1352
- function removeEntireImport(s, code, decl) {
1353
- let removeEnd = decl.end;
2197
+ function preserveImportSideEffect(transformed, code, declaration) {
2198
+ transformed.overwrite(declaration.start, declaration.end, `import ${code.slice(declaration.source.start, declaration.source.end)};`);
2199
+ }
2200
+ function removeEntireImport(transformed, code, declaration) {
2201
+ let removeEnd = declaration.end;
1354
2202
  while (removeEnd < code.length && (code[removeEnd] === `
1355
2203
  ` || code[removeEnd] === "\r")) {
1356
- removeEnd++;
2204
+ removeEnd += 1;
1357
2205
  }
1358
- s.remove(decl.start, removeEnd);
2206
+ transformed.remove(declaration.start, removeEnd);
1359
2207
  }
1360
- function removeUnusedSpecifiers(s, code, decl, refs) {
1361
- const removedSpecs = decl.specifiers.filter((spec) => !refs.has(spec.local.name));
1362
- for (const spec of removedSpecs) {
1363
- let removeStart = spec.start;
1364
- let removeEnd = spec.end;
2208
+ function removeUnusedSpecifiers(transformed, code, declaration, refs) {
2209
+ const removedSpecifiers = declaration.specifiers.filter((specifier) => !refs.has(specifier.local.name));
2210
+ for (const specifier of removedSpecifiers) {
2211
+ let removeStart = specifier.start;
2212
+ let removeEnd = specifier.end;
1365
2213
  while (removeEnd < code.length && (code[removeEnd] === "," || code[removeEnd] === " ")) {
1366
- removeEnd++;
2214
+ removeEnd += 1;
1367
2215
  }
1368
- if (!code.slice(spec.end, removeEnd).includes(",")) {
2216
+ if (!code.slice(specifier.end, removeEnd).includes(",")) {
1369
2217
  while (removeStart > 0 && (code[removeStart - 1] === " " || code[removeStart - 1] === ",")) {
1370
- removeStart--;
2218
+ removeStart -= 1;
1371
2219
  }
1372
2220
  }
1373
- s.remove(removeStart, removeEnd);
2221
+ transformed.remove(removeStart, removeEnd);
1374
2222
  }
1375
2223
  }
1376
- function deadCodeElimination(s, lang) {
1377
- const code = s.toString();
1378
- const { program, diagnostics } = parse(code, { sourceType: "module", lang });
1379
- const firstError = diagnostics.find((d) => d.severity === "error");
2224
+ function deadCodeElimination(transformed, originalCode, lang) {
2225
+ const code = transformed.toString();
2226
+ const { program, diagnostics } = parseSource(code, lang);
2227
+ const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
1380
2228
  if (firstError) {
1381
2229
  console.error("[furin] DCE: failed to parse transformed output:", firstError.message);
1382
- return s;
2230
+ return transformed;
1383
2231
  }
1384
- const fresh = new MagicString(code);
2232
+ const pruned = new MagicString(code);
1385
2233
  const refs = collectReferencedNames(program);
1386
- const body = program.body;
1387
- for (let i = body.length - 1;i >= 0; i--) {
1388
- const stmt = body[i];
1389
- if (!stmt) {
2234
+ const originalParse = parseSource(originalCode, lang);
2235
+ const originalRefs = originalParse.diagnostics.some((diagnostic) => diagnostic.severity === "error") ? refs : collectReferencedNames(originalParse.program);
2236
+ for (let index = program.body.length - 1;index >= 0; index -= 1) {
2237
+ const statement = program.body[index];
2238
+ if (statement?.type !== "ImportDeclaration") {
2239
+ continue;
2240
+ }
2241
+ const declaration = statement;
2242
+ if (declaration.specifiers.length === 0) {
2243
+ continue;
2244
+ }
2245
+ const usedCount = declaration.specifiers.filter((specifier) => refs.has(specifier.local.name)).length;
2246
+ if (usedCount === 0) {
2247
+ const typeOnly = declaration.importKind === "type" || declaration.specifiers.every((specifier) => specifier.importKind === "type");
2248
+ const wasUsedBeforeTransform = declaration.specifiers.some((specifier) => originalRefs.has(specifier.local.name));
2249
+ if (typeOnly || wasUsedBeforeTransform) {
2250
+ removeEntireImport(pruned, code, declaration);
2251
+ } else {
2252
+ preserveImportSideEffect(pruned, code, declaration);
2253
+ }
2254
+ } else if (usedCount < declaration.specifiers.length) {
2255
+ removeUnusedSpecifiers(pruned, code, declaration, refs);
2256
+ }
2257
+ }
2258
+ return pruned;
2259
+ }
2260
+
2261
+ // src/plugin/transform-isomorphic.ts
2262
+ var FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
2263
+ function importedName(specifier) {
2264
+ const { imported } = specifier;
2265
+ if (!(imported && typeof imported === "object")) {
2266
+ return;
2267
+ }
2268
+ const node = imported;
2269
+ if (node.type === "Identifier" && typeof node.name === "string") {
2270
+ return node.name;
2271
+ }
2272
+ if (node.type === "Literal" && typeof node.value === "string") {
2273
+ return node.value;
2274
+ }
2275
+ }
2276
+ function localName(specifier) {
2277
+ const local = specifier.local;
2278
+ return local?.type === "Identifier" && typeof local.name === "string" ? local.name : undefined;
2279
+ }
2280
+ function addImportSpecifier(specifier, bindings) {
2281
+ const local = localName(specifier);
2282
+ if (!local) {
2283
+ return;
2284
+ }
2285
+ if (specifier.type === "ImportNamespaceSpecifier") {
2286
+ bindings.namespaces.add(local);
2287
+ return;
2288
+ }
2289
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && importedName(specifier) === "createIsomorphicFn") {
2290
+ bindings.named.add(local);
2291
+ }
2292
+ }
2293
+ function collectBindings(program) {
2294
+ const bindings = {
2295
+ named: new Set,
2296
+ namespaces: new Set
2297
+ };
2298
+ for (const statement of program.body) {
2299
+ if (statement.type !== "ImportDeclaration") {
1390
2300
  continue;
1391
2301
  }
1392
- if (stmt.type !== "ImportDeclaration") {
2302
+ const declaration = statement;
2303
+ if (declaration.importKind === "type" || !FURIN_MODULES.has(String(declaration.source.value))) {
1393
2304
  continue;
1394
2305
  }
1395
- const decl = stmt;
1396
- if (!decl.specifiers || decl.specifiers.length === 0) {
2306
+ for (const specifier of declaration.specifiers) {
2307
+ addImportSpecifier(specifier, bindings);
2308
+ }
2309
+ }
2310
+ return bindings;
2311
+ }
2312
+ function isCreateIsomorphicCall(node, bindings, ancestors) {
2313
+ if (node.type !== "CallExpression") {
2314
+ return false;
2315
+ }
2316
+ const call = node;
2317
+ if (call.callee.type === "Identifier" && typeof call.callee.name === "string" && bindings.named.has(call.callee.name) && !hasShadowingDeclaration(call.callee.name, ancestors)) {
2318
+ return true;
2319
+ }
2320
+ const { callee } = call;
2321
+ return callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && typeof callee.object.name === "string" && bindings.namespaces.has(callee.object.name) && !hasShadowingDeclaration(callee.object.name, ancestors) && callee.property.type === "Identifier" && callee.property.name === "createIsomorphicFn";
2322
+ }
2323
+ function environmentMethod(node) {
2324
+ if (node.type !== "CallExpression") {
2325
+ return;
2326
+ }
2327
+ const call = node;
2328
+ const { callee } = call;
2329
+ if (callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier") {
2330
+ return;
2331
+ }
2332
+ return callee.property.name === "client" || callee.property.name === "server" ? callee.property.name : undefined;
2333
+ }
2334
+ function parseCandidate(source, filename, node, bindings, ancestors) {
2335
+ let current = node;
2336
+ let client;
2337
+ let server;
2338
+ for (;; ) {
2339
+ const method = environmentMethod(current);
2340
+ if (!method) {
2341
+ break;
2342
+ }
2343
+ const call = current;
2344
+ if (call.callee.type !== "MemberExpression") {
2345
+ return null;
2346
+ }
2347
+ const [implementation] = call.arguments;
2348
+ if (!implementation) {
2349
+ return null;
2350
+ }
2351
+ const unwrappedImplementation = unwrapTSExpression(implementation);
2352
+ if (unwrappedImplementation.type !== "ArrowFunctionExpression" && unwrappedImplementation.type !== "FunctionExpression" && unwrappedImplementation.type !== "Identifier") {
2353
+ throw new Error(`[furin] ${filename}:${sourcePosition(source, implementation.start)} createIsomorphicFn().${method}() must receive a function.`);
2354
+ }
2355
+ if (method === "client") {
2356
+ client = implementation;
2357
+ } else {
2358
+ server = implementation;
2359
+ }
2360
+ current = unwrapTSExpression(call.callee.object);
2361
+ }
2362
+ if (!isCreateIsomorphicCall(current, bindings, ancestors)) {
2363
+ return null;
2364
+ }
2365
+ return {
2366
+ client,
2367
+ end: node.end,
2368
+ server,
2369
+ start: node.start
2370
+ };
2371
+ }
2372
+ function collectCandidates(source, filename, program, bindings) {
2373
+ const candidates = [];
2374
+ walk(program, {
2375
+ CallExpression(node, context) {
2376
+ const candidate = parseCandidate(source, filename, node, bindings, context.ancestors());
2377
+ if (candidate) {
2378
+ candidates.push(candidate);
2379
+ }
2380
+ }
2381
+ });
2382
+ return candidates.toSorted((left, right) => right.end - right.start - (left.end - left.start)).filter((candidate, index, all) => !all.slice(0, index).some((other) => other.start <= candidate.start && other.end >= candidate.end));
2383
+ }
2384
+ function sourcePosition(source, offset) {
2385
+ const before = source.slice(0, offset);
2386
+ const line = before.split(`
2387
+ `).length;
2388
+ const lastNewline = before.lastIndexOf(`
2389
+ `);
2390
+ return `${line}:${offset - lastNewline}`;
2391
+ }
2392
+ function lexicalBindingScope(ancestors) {
2393
+ return ancestors.findLast((ancestor) => ancestor.type === "Program" || ancestor.type === "BlockStatement" || ancestor.type === "SwitchStatement" || ancestor.type === "ForStatement" || ancestor.type === "ForInStatement" || ancestor.type === "ForOfStatement" || ancestor.type === "StaticBlock");
2394
+ }
2395
+ function varBindingScope(ancestors) {
2396
+ return ancestors.findLast((ancestor, index) => {
2397
+ if (ancestor.type === "Program" || ancestor.type === "StaticBlock") {
2398
+ return true;
2399
+ }
2400
+ if (ancestor.type !== "BlockStatement") {
2401
+ return false;
2402
+ }
2403
+ const parent = ancestors[index - 1];
2404
+ return parent?.type === "FunctionDeclaration" || parent?.type === "FunctionExpression" || parent?.type === "ArrowFunctionExpression";
2405
+ });
2406
+ }
2407
+ function collectBuilderBindings(program, bindings) {
2408
+ const builders = [];
2409
+ walk(program, {
2410
+ VariableDeclarator(node, context) {
2411
+ if (!(node.id && node.init && typeof node.id === "object" && typeof node.init === "object")) {
2412
+ return;
2413
+ }
2414
+ const identifier = node.id;
2415
+ const initializer = unwrapTSExpression(node.init);
2416
+ const ancestors = context.ancestors();
2417
+ const declaration = ancestors.at(-1);
2418
+ const scope = declaration?.type === "VariableDeclaration" && declaration.kind === "var" ? varBindingScope(ancestors) : lexicalBindingScope(ancestors);
2419
+ if (scope && identifier.type === "Identifier" && typeof identifier.name === "string" && isCreateIsomorphicCall(initializer, bindings, ancestors)) {
2420
+ builders.push({ name: identifier.name, scope });
2421
+ }
2422
+ }
2423
+ });
2424
+ return builders;
2425
+ }
2426
+ function hasVisibleBuilder(name, ancestors, builders) {
2427
+ let scopeIndex = -1;
2428
+ for (const builder of builders) {
2429
+ if (builder.name === name) {
2430
+ scopeIndex = Math.max(scopeIndex, ancestors.lastIndexOf(builder.scope));
2431
+ }
2432
+ }
2433
+ return scopeIndex >= 0 && !hasShadowingDeclaration(name, ancestors.slice(scopeIndex + 1));
2434
+ }
2435
+ function assertNoSplitChains(source, filename, program, builders) {
2436
+ if (builders.length === 0) {
2437
+ return;
2438
+ }
2439
+ walk(program, {
2440
+ MemberExpression(node, context) {
2441
+ if (node.computed || node.object.type !== "Identifier" || typeof node.object.name !== "string" || !hasVisibleBuilder(node.object.name, context.ancestors(), builders) || node.property.type !== "Identifier" || node.property.name !== "server" && node.property.name !== "client") {
2442
+ return;
2443
+ }
2444
+ throw new Error(`[furin] ${filename}:${sourcePosition(source, node.start)} createIsomorphicFn() must use one fluent chain.`);
2445
+ }
2446
+ });
2447
+ }
2448
+ function chainStartsWithCreateIsomorphicFn(expression, bindings, ancestors) {
2449
+ let current = unwrapTSExpression(expression);
2450
+ for (;; ) {
2451
+ if (isCreateIsomorphicCall(current, bindings, ancestors)) {
2452
+ return true;
2453
+ }
2454
+ if (current.type !== "CallExpression" || !environmentMethod(current)) {
2455
+ return false;
2456
+ }
2457
+ const call = current;
2458
+ if (call.callee.type !== "MemberExpression") {
2459
+ return false;
2460
+ }
2461
+ current = unwrapTSExpression(call.callee.object);
2462
+ }
2463
+ }
2464
+ function assertStaticEnvironmentMethods(source, filename, program, bindings, builders) {
2465
+ walk(program, {
2466
+ MemberExpression(node, context) {
2467
+ if (!node.computed || node.property.type !== "Literal") {
2468
+ return;
2469
+ }
2470
+ if (node.property.value !== "server" && node.property.value !== "client") {
2471
+ return;
2472
+ }
2473
+ const ancestors = context.ancestors();
2474
+ const splitBuilder = node.object.type === "Identifier" && typeof node.object.name === "string" && hasVisibleBuilder(node.object.name, ancestors, builders);
2475
+ if (!(splitBuilder || chainStartsWithCreateIsomorphicFn(node.object, bindings, ancestors))) {
2476
+ return;
2477
+ }
2478
+ throw new Error(`[furin] ${filename}:${sourcePosition(source, node.start)} createIsomorphicFn() requires static .server() and .client() methods.`);
2479
+ }
2480
+ });
2481
+ }
2482
+ function transformIsomorphicFunctions(source, filename, environment) {
2483
+ const lang = detectLangFromPath(filename);
2484
+ if (lang === "dts") {
2485
+ return { code: source, map: null, transformed: false };
2486
+ }
2487
+ const { program, diagnostics } = parseSource(source, lang);
2488
+ const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
2489
+ if (firstError) {
2490
+ throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
2491
+ }
2492
+ const bindings = collectBindings(program);
2493
+ const builders = collectBuilderBindings(program, bindings);
2494
+ assertStaticEnvironmentMethods(source, filename, program, bindings, builders);
2495
+ assertNoSplitChains(source, filename, program, builders);
2496
+ const candidates = collectCandidates(source, filename, program, bindings);
2497
+ if (candidates.length === 0) {
2498
+ return { code: source, map: null, transformed: false };
2499
+ }
2500
+ const transformed = new MagicString(source);
2501
+ for (const candidate of candidates) {
2502
+ const implementation = candidate[environment];
2503
+ transformed.overwrite(candidate.start, candidate.end, implementation ? `(${source.slice(implementation.start, implementation.end)})` : "(() => undefined)");
2504
+ }
2505
+ const pruned = deadCodeElimination(transformed, source, lang);
2506
+ return {
2507
+ code: pruned.toString(),
2508
+ map: pruned.generateMap({ includeContent: true, source: filename }),
2509
+ transformed: true
2510
+ };
2511
+ }
2512
+
2513
+ // src/plugin/transform-client.ts
2514
+ var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
2515
+ var FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
2516
+ var SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
2517
+ function isFurinRouteModule(source) {
2518
+ return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES.has(source));
2519
+ }
2520
+ function importedName2(specifier) {
2521
+ const { imported } = specifier;
2522
+ if (!imported || typeof imported !== "object") {
2523
+ return null;
2524
+ }
2525
+ const node = imported;
2526
+ if (node.type === "Identifier" && typeof node.name === "string") {
2527
+ return node.name;
2528
+ }
2529
+ if (node.type === "Literal" && typeof node.value === "string") {
2530
+ return node.value;
2531
+ }
2532
+ return null;
2533
+ }
2534
+ function localName2(specifier) {
2535
+ const { local } = specifier;
2536
+ if (!local || typeof local !== "object") {
2537
+ return null;
2538
+ }
2539
+ const node = local;
2540
+ return node.type === "Identifier" && typeof node.name === "string" ? node.name : null;
2541
+ }
2542
+ function collectDefineRouteBindings(program) {
2543
+ const bindings = new Set;
2544
+ for (const statement of program.body) {
2545
+ if (statement.type !== "ImportDeclaration") {
1397
2546
  continue;
1398
2547
  }
1399
- const usedCount = decl.specifiers.filter((spec) => refs.has(spec.local.name)).length;
1400
- if (usedCount === 0) {
1401
- removeEntireImport(fresh, code, decl);
1402
- } else if (usedCount < decl.specifiers.length) {
1403
- removeUnusedSpecifiers(fresh, code, decl, refs);
2548
+ const declaration = statement;
2549
+ if (declaration.importKind === "type") {
2550
+ continue;
2551
+ }
2552
+ const source = declaration.source.value;
2553
+ if (!isFurinRouteModule(source)) {
2554
+ continue;
2555
+ }
2556
+ for (const specifier of declaration.specifiers) {
2557
+ if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") {
2558
+ continue;
2559
+ }
2560
+ const imported = importedName2(specifier);
2561
+ if (imported !== "defineRoute" && imported !== "defineRootRoute") {
2562
+ continue;
2563
+ }
2564
+ const local = localName2(specifier);
2565
+ if (local) {
2566
+ bindings.add(local);
2567
+ }
1404
2568
  }
1405
2569
  }
1406
- return fresh;
2570
+ return bindings;
1407
2571
  }
1408
- function removeServerExports(s, source, program) {
1409
- let removedServerCode = false;
1410
- walkAST(program, (node) => {
1411
- if (node.type !== "CallExpression") {
1412
- return;
2572
+ function rewriteClientImports(source, program, bindings) {
2573
+ let rewritten = false;
2574
+ for (const statement of program.body) {
2575
+ if (statement.type !== "ImportDeclaration") {
2576
+ continue;
1413
2577
  }
1414
- const call = node;
1415
- if (!isTargetCall(call)) {
1416
- return;
2578
+ const declaration = statement;
2579
+ const moduleName = declaration.source.value;
2580
+ if (typeof moduleName !== "string" || !FURIN_SERVER_MODULES.has(moduleName)) {
2581
+ continue;
1417
2582
  }
1418
- const firstArg = call.arguments[0];
1419
- if (!firstArg) {
1420
- return;
2583
+ const importsClientValue = declaration.specifiers.some((specifier) => {
2584
+ const local = localName2(specifier);
2585
+ const imported = importedName2(specifier);
2586
+ return local !== null && bindings.has(local) || imported === "HeadContent" || imported === "Scripts";
2587
+ });
2588
+ if (!importsClientValue) {
2589
+ continue;
1421
2590
  }
1422
- const arg = unwrapTSExpression(firstArg);
1423
- if (!isObjectExpressionNode(arg)) {
1424
- return;
2591
+ const clientModule = moduleName === "furin" ? "furin/client" : "@teyik0/furin/client";
2592
+ source.update(declaration.source.start + 1, declaration.source.end - 1, clientModule);
2593
+ rewritten = true;
2594
+ }
2595
+ return rewritten;
2596
+ }
2597
+ function asAstNode(node) {
2598
+ if (!node || typeof node !== "object" || !("type" in node)) {
2599
+ return null;
2600
+ }
2601
+ return unwrapTSExpression(node);
2602
+ }
2603
+ function chainRootIsDefineRoute(node, bindings, ancestors) {
2604
+ let current = asAstNode(node);
2605
+ while (current) {
2606
+ if (current.type === "MemberExpression") {
2607
+ current = asAstNode(current.object);
2608
+ continue;
2609
+ }
2610
+ if (current.type === "CallExpression") {
2611
+ current = asAstNode(current.callee);
2612
+ continue;
1425
2613
  }
1426
- if (removeServerProperties(s, source, arg)) {
1427
- removedServerCode = true;
2614
+ return current.type === "Identifier" && typeof current.name === "string" && bindings.has(current.name) && !hasShadowingDeclaration(current.name, ancestors);
2615
+ }
2616
+ return false;
2617
+ }
2618
+ function removeChainedServerCalls(source, program, bindings) {
2619
+ let transformed = rewriteClientImports(source, program, bindings);
2620
+ walk(program, {
2621
+ CallExpression(call, context) {
2622
+ const callee = asAstNode(call.callee);
2623
+ if (callee?.type !== "MemberExpression" || callee.computed === true || !callee.property || typeof callee.property !== "object") {
2624
+ return;
2625
+ }
2626
+ const property = callee.property;
2627
+ if (property.type !== "Identifier" || typeof property.name !== "string" || !SERVER_ONLY_METHODS.has(property.name) || !chainRootIsDefineRoute(callee.object, bindings, context.ancestors())) {
2628
+ return;
2629
+ }
2630
+ const object = asAstNode(callee.object);
2631
+ if (!object) {
2632
+ return;
2633
+ }
2634
+ source.remove(object.end, call.end);
2635
+ transformed = true;
1428
2636
  }
1429
2637
  });
1430
- return removedServerCode;
2638
+ return transformed;
1431
2639
  }
1432
2640
  function transformForClient(code, filename) {
1433
2641
  const lang = detectLangFromPath(filename);
1434
2642
  if (lang === "dts") {
1435
2643
  return { code, map: null, removedServerCode: false };
1436
2644
  }
1437
- const { program, diagnostics } = parse(code, { sourceType: "module", lang });
1438
- const firstError = diagnostics.find((d) => d.severity === "error");
2645
+ const isomorphicResult = transformIsomorphicFunctions(code, filename, "client");
2646
+ const clientSource = isomorphicResult.code;
2647
+ const { diagnostics, program } = parseSource(clientSource, lang);
2648
+ const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
1439
2649
  if (firstError) {
1440
2650
  throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
1441
2651
  }
1442
- let s = new MagicString(code);
1443
- const removedServerCode = removeServerExports(s, code, program);
2652
+ let source = new MagicString(clientSource);
2653
+ const routeBindings = collectDefineRouteBindings(program);
2654
+ const removedRouteCode = removeChainedServerCalls(source, program, routeBindings);
2655
+ const removedServerCode = isomorphicResult.transformed || removedRouteCode;
1444
2656
  if (removedServerCode) {
1445
- s = deadCodeElimination(s, lang);
2657
+ source = deadCodeElimination(source, code, lang);
2658
+ }
2659
+ if (routeBindings.size > 0) {
2660
+ source.append(`
2661
+ if (import.meta.hot) {
2662
+ import.meta.hot.accept((updatedModule) => {
2663
+ const updatedRoute = updatedModule?.route;
2664
+ if (updatedRoute?.component) {
2665
+ window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component);
2666
+ }
2667
+ });
2668
+ }
2669
+ `);
1446
2670
  }
1447
2671
  return {
1448
- code: s.toString(),
1449
- map: s.generateMap({ source: filename, includeContent: true }),
2672
+ code: source.toString(),
2673
+ map: source.generateMap({ includeContent: true, source: filename }),
1450
2674
  removedServerCode
1451
2675
  };
1452
2676
  }
@@ -1455,7 +2679,7 @@ function transformForClient(code, filename) {
1455
2679
  var ELYSIA_FILTER = /^elysia$/;
1456
2680
  var BUN_BUILTIN_FILTER = /^bun:/;
1457
2681
  var ANY_FILTER = /.*/;
1458
- var TS_FILE_FILTER = /\.(tsx|ts)$/;
2682
+ var SCRIPT_FILE_FILTER = /\.(tsx?|jsx?)$/;
1459
2683
  var ELYSIA_STUB = `export const t = new Proxy({}, { get: () => (...args) => args[0] ?? {} });
1460
2684
  export class NotFoundError extends Error { constructor(m) { super(m); this.name = "NotFoundError"; } }
1461
2685
  export class ValidationError extends Error { constructor(m) { super(m); this.name = "ValidationError"; } }
@@ -1465,32 +2689,27 @@ var plugin = {
1465
2689
  name: "furin-strip-server",
1466
2690
  setup(build) {
1467
2691
  build.onResolve({ filter: ELYSIA_FILTER }, () => ({
1468
- path: "elysia-stub",
1469
- namespace: "furin-stubs"
2692
+ namespace: "furin-stubs",
2693
+ path: "elysia-stub"
1470
2694
  }));
1471
2695
  build.onResolve({ filter: BUN_BUILTIN_FILTER }, () => ({
1472
- path: "bun-builtin-stub",
1473
- namespace: "furin-stubs"
2696
+ namespace: "furin-stubs",
2697
+ path: "bun-builtin-stub"
1474
2698
  }));
1475
- build.onLoad({ namespace: "furin-stubs", filter: ANY_FILTER }, (args) => ({
2699
+ build.onLoad({ filter: ANY_FILTER, namespace: "furin-stubs" }, (args) => ({
1476
2700
  contents: args.path === "elysia-stub" ? ELYSIA_STUB : "",
1477
2701
  loader: "js"
1478
2702
  }));
1479
- build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
2703
+ build.onLoad({ filter: SCRIPT_FILE_FILTER }, async (args) => {
1480
2704
  if (args.path.includes("node_modules")) {
1481
2705
  return;
1482
2706
  }
1483
2707
  const source = await Bun.file(args.path).text();
1484
- try {
1485
- const result = transformForClient(source, args.path);
1486
- return {
1487
- contents: result.code,
1488
- loader: args.path.endsWith(".tsx") ? "tsx" : "ts"
1489
- };
1490
- } catch (err) {
1491
- console.error(`[furin] strip-plugin transform error for ${args.path}:`, err);
1492
- return;
1493
- }
2708
+ const result = transformForClient(source, args.path);
2709
+ return {
2710
+ contents: result.code,
2711
+ loader: detectLoaderFromPath(args.path)
2712
+ };
1494
2713
  });
1495
2714
  }
1496
2715
  };