@nifrajs/cli 5.0.0 → 5.2.0

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 (296) hide show
  1. package/CHANGELOG.md +3211 -0
  2. package/README.md +10 -2
  3. package/dist/agent-files.d.ts +19 -11
  4. package/dist/agent-files.d.ts.map +1 -1
  5. package/dist/agent-files.js +26 -18
  6. package/dist/agent-files.js.map +1 -1
  7. package/dist/assure-hydration.d.ts.map +1 -1
  8. package/dist/assure-hydration.js +5 -2
  9. package/dist/assure-hydration.js.map +1 -1
  10. package/dist/assure.d.ts +12 -2
  11. package/dist/assure.d.ts.map +1 -1
  12. package/dist/assure.js +73 -9
  13. package/dist/assure.js.map +1 -1
  14. package/dist/capabilities-tool.d.ts.map +1 -1
  15. package/dist/capabilities-tool.js +152 -49
  16. package/dist/capabilities-tool.js.map +1 -1
  17. package/dist/check-diagnostics.d.ts +7 -0
  18. package/dist/check-diagnostics.d.ts.map +1 -1
  19. package/dist/check-diagnostics.js +3 -0
  20. package/dist/check-diagnostics.js.map +1 -1
  21. package/dist/check-scan.d.ts +8 -2
  22. package/dist/check-scan.d.ts.map +1 -1
  23. package/dist/check-scan.js +49 -13
  24. package/dist/check-scan.js.map +1 -1
  25. package/dist/check.d.ts.map +1 -1
  26. package/dist/check.js +91 -45
  27. package/dist/check.js.map +1 -1
  28. package/dist/cli.d.ts +2 -0
  29. package/dist/cli.d.ts.map +1 -1
  30. package/dist/cli.js +128 -59
  31. package/dist/cli.js.map +1 -1
  32. package/dist/client-module.d.ts +5 -3
  33. package/dist/client-module.d.ts.map +1 -1
  34. package/dist/client-module.js +34 -10
  35. package/dist/client-module.js.map +1 -1
  36. package/dist/command-catalog.d.ts +9 -1
  37. package/dist/command-catalog.d.ts.map +1 -1
  38. package/dist/command-catalog.js +75 -26
  39. package/dist/command-catalog.js.map +1 -1
  40. package/dist/dev-bun-config.d.ts +6 -3
  41. package/dist/dev-bun-config.d.ts.map +1 -1
  42. package/dist/dev-bun-config.js +13 -10
  43. package/dist/dev-bun-config.js.map +1 -1
  44. package/dist/dev-feed-tool.d.ts +19 -1
  45. package/dist/dev-feed-tool.d.ts.map +1 -1
  46. package/dist/dev-feed-tool.js +114 -0
  47. package/dist/dev-feed-tool.js.map +1 -1
  48. package/dist/doctor.d.ts +15 -1
  49. package/dist/doctor.d.ts.map +1 -1
  50. package/dist/doctor.js +79 -61
  51. package/dist/doctor.js.map +1 -1
  52. package/dist/fix-recipes.d.ts +2 -0
  53. package/dist/fix-recipes.d.ts.map +1 -1
  54. package/dist/fix-recipes.js +93 -12
  55. package/dist/fix-recipes.js.map +1 -1
  56. package/dist/i18n-check.d.ts +11 -1
  57. package/dist/i18n-check.d.ts.map +1 -1
  58. package/dist/i18n-check.js +170 -17
  59. package/dist/i18n-check.js.map +1 -1
  60. package/dist/init-agents.d.ts +60 -4
  61. package/dist/init-agents.d.ts.map +1 -1
  62. package/dist/init-agents.js +196 -33
  63. package/dist/init-agents.js.map +1 -1
  64. package/dist/internal/config-paths.d.ts +16 -0
  65. package/dist/internal/config-paths.d.ts.map +1 -0
  66. package/dist/internal/config-paths.js +124 -0
  67. package/dist/internal/config-paths.js.map +1 -0
  68. package/dist/internal/installed-package.d.ts +4 -0
  69. package/dist/internal/installed-package.d.ts.map +1 -0
  70. package/dist/internal/installed-package.js +17 -0
  71. package/dist/internal/installed-package.js.map +1 -0
  72. package/dist/internal/project-specifiers.d.ts +14 -1
  73. package/dist/internal/project-specifiers.d.ts.map +1 -1
  74. package/dist/internal/project-specifiers.js +63 -16
  75. package/dist/internal/project-specifiers.js.map +1 -1
  76. package/dist/internal/source-facts.d.ts +12 -1
  77. package/dist/internal/source-facts.d.ts.map +1 -1
  78. package/dist/internal/source-facts.js +117 -5
  79. package/dist/internal/source-facts.js.map +1 -1
  80. package/dist/internal/typescript-import.d.ts.map +1 -1
  81. package/dist/internal/typescript-import.js +5 -3
  82. package/dist/internal/typescript-import.js.map +1 -1
  83. package/dist/internal/workspace-packages.d.ts +22 -0
  84. package/dist/internal/workspace-packages.d.ts.map +1 -0
  85. package/dist/internal/workspace-packages.js +215 -0
  86. package/dist/internal/workspace-packages.js.map +1 -0
  87. package/dist/introspect.d.ts +9 -0
  88. package/dist/introspect.d.ts.map +1 -1
  89. package/dist/introspect.js +32 -1
  90. package/dist/introspect.js.map +1 -1
  91. package/dist/levels-tool.d.ts.map +1 -1
  92. package/dist/levels-tool.js +5 -8
  93. package/dist/levels-tool.js.map +1 -1
  94. package/dist/load.d.ts +9 -4
  95. package/dist/load.d.ts.map +1 -1
  96. package/dist/load.js +32 -3
  97. package/dist/load.js.map +1 -1
  98. package/dist/lock-links.d.ts +42 -0
  99. package/dist/lock-links.d.ts.map +1 -0
  100. package/dist/lock-links.js +144 -0
  101. package/dist/lock-links.js.map +1 -0
  102. package/dist/mcp-context.d.ts.map +1 -1
  103. package/dist/mcp-context.js +6 -21
  104. package/dist/mcp-context.js.map +1 -1
  105. package/dist/mcp-delegate.d.ts +2 -2
  106. package/dist/mcp-delegate.d.ts.map +1 -1
  107. package/dist/mcp-delegate.js +19 -7
  108. package/dist/mcp-delegate.js.map +1 -1
  109. package/dist/mcp-exec.d.ts +1 -0
  110. package/dist/mcp-exec.d.ts.map +1 -1
  111. package/dist/mcp-exec.js +13 -5
  112. package/dist/mcp-exec.js.map +1 -1
  113. package/dist/mcp-http.js +1 -1
  114. package/dist/mcp-io.d.ts +13 -0
  115. package/dist/mcp-io.d.ts.map +1 -1
  116. package/dist/mcp-io.js +23 -0
  117. package/dist/mcp-io.js.map +1 -1
  118. package/dist/mcp-path.d.ts +2 -1
  119. package/dist/mcp-path.d.ts.map +1 -1
  120. package/dist/mcp-path.js +9 -24
  121. package/dist/mcp-path.js.map +1 -1
  122. package/dist/mcp-root.d.ts +6 -4
  123. package/dist/mcp-root.d.ts.map +1 -1
  124. package/dist/mcp-root.js +12 -8
  125. package/dist/mcp-root.js.map +1 -1
  126. package/dist/mcp.d.ts.map +1 -1
  127. package/dist/mcp.js +40 -17
  128. package/dist/mcp.js.map +1 -1
  129. package/dist/migrate-layout.d.ts +41 -1
  130. package/dist/migrate-layout.d.ts.map +1 -1
  131. package/dist/migrate-layout.js +1729 -236
  132. package/dist/migrate-layout.js.map +1 -1
  133. package/dist/output-schemas.d.ts +34 -0
  134. package/dist/output-schemas.d.ts.map +1 -1
  135. package/dist/output-schemas.js +132 -21
  136. package/dist/output-schemas.js.map +1 -1
  137. package/dist/project-path.d.ts +6 -0
  138. package/dist/project-path.d.ts.map +1 -1
  139. package/dist/project-path.js +48 -14
  140. package/dist/project-path.js.map +1 -1
  141. package/dist/project-site.d.ts +7 -0
  142. package/dist/project-site.d.ts.map +1 -0
  143. package/dist/project-site.js +19 -0
  144. package/dist/project-site.js.map +1 -0
  145. package/dist/recipes/4.0.0.d.ts.map +1 -1
  146. package/dist/recipes/4.0.0.js +2 -0
  147. package/dist/recipes/4.0.0.js.map +1 -1
  148. package/dist/recipes/5.1.0.d.ts +9 -0
  149. package/dist/recipes/5.1.0.d.ts.map +1 -0
  150. package/dist/recipes/5.1.0.js +22 -0
  151. package/dist/recipes/5.1.0.js.map +1 -0
  152. package/dist/recipes/5.2.0.d.ts +10 -0
  153. package/dist/recipes/5.2.0.d.ts.map +1 -0
  154. package/dist/recipes/5.2.0.js +32 -0
  155. package/dist/recipes/5.2.0.js.map +1 -0
  156. package/dist/recipes/index.d.ts +3 -0
  157. package/dist/recipes/index.d.ts.map +1 -1
  158. package/dist/recipes/index.js +7 -0
  159. package/dist/recipes/index.js.map +1 -1
  160. package/dist/release-verification.d.ts +5 -0
  161. package/dist/release-verification.d.ts.map +1 -1
  162. package/dist/release-verification.js +14 -0
  163. package/dist/release-verification.js.map +1 -1
  164. package/dist/review.d.ts.map +1 -1
  165. package/dist/review.js +7 -0
  166. package/dist/review.js.map +1 -1
  167. package/dist/rule-explain.d.ts +26 -0
  168. package/dist/rule-explain.d.ts.map +1 -0
  169. package/dist/rule-explain.js +49 -0
  170. package/dist/rule-explain.js.map +1 -0
  171. package/dist/rules/codes.d.ts +5 -1
  172. package/dist/rules/codes.d.ts.map +1 -1
  173. package/dist/rules/codes.js +5 -1
  174. package/dist/rules/codes.js.map +1 -1
  175. package/dist/rules/contract-visibility.d.ts.map +1 -1
  176. package/dist/rules/contract-visibility.js +93 -21
  177. package/dist/rules/contract-visibility.js.map +1 -1
  178. package/dist/rules/data-guard.d.ts +6 -0
  179. package/dist/rules/data-guard.d.ts.map +1 -1
  180. package/dist/rules/data-guard.js +37 -0
  181. package/dist/rules/data-guard.js.map +1 -1
  182. package/dist/rules/explanations.d.ts +14 -0
  183. package/dist/rules/explanations.d.ts.map +1 -0
  184. package/dist/rules/explanations.js +316 -0
  185. package/dist/rules/explanations.js.map +1 -0
  186. package/dist/rules/legacy.d.ts.map +1 -1
  187. package/dist/rules/legacy.js +44 -2
  188. package/dist/rules/legacy.js.map +1 -1
  189. package/dist/rules/merge-auth.d.ts +12 -0
  190. package/dist/rules/merge-auth.d.ts.map +1 -0
  191. package/dist/rules/merge-auth.js +52 -0
  192. package/dist/rules/merge-auth.js.map +1 -0
  193. package/dist/rules/pages.d.ts +56 -3
  194. package/dist/rules/pages.d.ts.map +1 -1
  195. package/dist/rules/pages.js +412 -23
  196. package/dist/rules/pages.js.map +1 -1
  197. package/dist/rules/routes.d.ts +3 -2
  198. package/dist/rules/routes.d.ts.map +1 -1
  199. package/dist/rules/routes.js +4 -3
  200. package/dist/rules/routes.js.map +1 -1
  201. package/dist/rules/security.d.ts +3 -2
  202. package/dist/rules/security.d.ts.map +1 -1
  203. package/dist/rules/security.js +42 -11
  204. package/dist/rules/security.js.map +1 -1
  205. package/dist/rules/zones.d.ts.map +1 -1
  206. package/dist/rules/zones.js +34 -11
  207. package/dist/rules/zones.js.map +1 -1
  208. package/dist/stylex-migrate.d.ts.map +1 -1
  209. package/dist/stylex-migrate.js +127 -17
  210. package/dist/stylex-migrate.js.map +1 -1
  211. package/dist/test-tool.d.ts.map +1 -1
  212. package/dist/test-tool.js +3 -9
  213. package/dist/test-tool.js.map +1 -1
  214. package/dist/typecheck-coverage.d.ts +11 -0
  215. package/dist/typecheck-coverage.d.ts.map +1 -1
  216. package/dist/typecheck-coverage.js +50 -7
  217. package/dist/typecheck-coverage.js.map +1 -1
  218. package/dist/upgrade.d.ts +57 -6
  219. package/dist/upgrade.d.ts.map +1 -1
  220. package/dist/upgrade.js +247 -19
  221. package/dist/upgrade.js.map +1 -1
  222. package/dist/verification-plan.d.ts.map +1 -1
  223. package/dist/verification-plan.js +7 -2
  224. package/dist/verification-plan.js.map +1 -1
  225. package/dist/version-drift.d.ts.map +1 -1
  226. package/dist/version-drift.js +66 -3
  227. package/dist/version-drift.js.map +1 -1
  228. package/dist/web-app-options.d.ts +1 -1
  229. package/dist/web-app-options.d.ts.map +1 -1
  230. package/dist/web-app-options.js.map +1 -1
  231. package/docs/examples.json +21 -3
  232. package/docs/llms-full.txt +1083 -168
  233. package/docs/types.json +535 -112
  234. package/package.json +13 -12
  235. package/src/agent-files.ts +27 -17
  236. package/src/assure-hydration.ts +5 -1
  237. package/src/assure.ts +99 -11
  238. package/src/capabilities-tool.ts +188 -53
  239. package/src/check-diagnostics.ts +10 -0
  240. package/src/check-scan.ts +65 -12
  241. package/src/check.ts +122 -51
  242. package/src/cli.ts +127 -45
  243. package/src/client-module.ts +45 -9
  244. package/src/command-catalog.ts +92 -28
  245. package/src/dev-bun-config.ts +13 -9
  246. package/src/dev-feed-tool.ts +146 -1
  247. package/src/doctor.ts +102 -66
  248. package/src/fix-recipes.ts +101 -10
  249. package/src/i18n-check.ts +254 -18
  250. package/src/init-agents.ts +225 -44
  251. package/src/internal/config-paths.ts +154 -0
  252. package/src/internal/installed-package.ts +15 -0
  253. package/src/internal/project-specifiers.ts +78 -17
  254. package/src/internal/source-facts.ts +147 -5
  255. package/src/internal/typescript-import.ts +5 -3
  256. package/src/internal/workspace-packages.ts +218 -0
  257. package/src/introspect.ts +39 -1
  258. package/src/levels-tool.ts +7 -9
  259. package/src/load.ts +46 -4
  260. package/src/lock-links.ts +173 -0
  261. package/src/mcp-context.ts +5 -18
  262. package/src/mcp-delegate.ts +22 -10
  263. package/src/mcp-exec.ts +14 -4
  264. package/src/mcp-http.ts +1 -1
  265. package/src/mcp-io.ts +33 -0
  266. package/src/mcp-path.ts +8 -22
  267. package/src/mcp-root.ts +14 -8
  268. package/src/mcp.ts +48 -19
  269. package/src/migrate-layout.ts +1968 -245
  270. package/src/output-schemas.ts +179 -23
  271. package/src/project-path.ts +44 -13
  272. package/src/project-site.ts +18 -0
  273. package/src/recipes/4.0.0.ts +2 -0
  274. package/src/recipes/5.1.0.ts +23 -0
  275. package/src/recipes/5.2.0.ts +33 -0
  276. package/src/recipes/index.ts +7 -0
  277. package/src/release-verification.ts +20 -0
  278. package/src/review.ts +7 -0
  279. package/src/rule-explain.ts +75 -0
  280. package/src/rules/codes.ts +5 -1
  281. package/src/rules/contract-visibility.ts +118 -20
  282. package/src/rules/data-guard.ts +40 -0
  283. package/src/rules/explanations.ts +329 -0
  284. package/src/rules/legacy.ts +46 -2
  285. package/src/rules/merge-auth.ts +55 -0
  286. package/src/rules/pages.ts +486 -25
  287. package/src/rules/routes.ts +4 -3
  288. package/src/rules/security.ts +49 -11
  289. package/src/rules/zones.ts +33 -9
  290. package/src/stylex-migrate.ts +117 -17
  291. package/src/test-tool.ts +3 -9
  292. package/src/typecheck-coverage.ts +51 -6
  293. package/src/upgrade.ts +312 -19
  294. package/src/verification-plan.ts +15 -2
  295. package/src/version-drift.ts +68 -2
  296. package/src/web-app-options.ts +9 -1
@@ -12,16 +12,18 @@
12
12
  * the server side -> `backend/`, both -> `shared/`. Imports through tsconfig `paths`/`baseUrl` and
13
13
  * package.json `imports` count as the bundler reads them;
14
14
  * 5. rewrites every import in the app to the new locations (test-runner mocks included), an alias
15
- * through the same alias, the config's `clientModule` and `componentPipeline.entries` paths,
16
- * `@nifrajs/web/server-only` to `@nifrajs/web/backend-only`, and `ServerOnly` to `BackendOnly`;
15
+ * through the same alias when one of its targets covers the new place and as a relative path
16
+ * otherwise, each checked to resolve to its target after the moves; the config's `clientModule`
17
+ * and `componentPipeline.entries` paths; `@nifrajs/web/server-only` to
18
+ * `@nifrajs/web/backend-only`; and `ServerOnly` to `BackendOnly`;
17
19
  * 6. adds the zone folders moved TypeScript lands in to tsconfig `include`, and `.nifra/` to
18
20
  * `.gitignore`.
19
21
  *
20
22
  * Data files (JSON, YAML, CSV, ...) and folders the app zones in package.json stay where they are.
21
23
  *
22
24
  * It is a dry run unless `write` is set, and it reports what it could not decide (a frontend that uses
23
- * a moved name at runtime, a helper both halves need, a loader with no output schema, an alias no
24
- * target covers after a move, a specifier that names nothing) instead of guessing.
25
+ * a moved name at runtime, a helper both halves need, a loader with no output schema, an import no
26
+ * specifier reaches after the moves, a specifier that names nothing) instead of guessing.
25
27
  */
26
28
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
27
29
  import { builtinModules } from "node:module";
@@ -30,10 +32,13 @@ import { BACKEND_ROUTE_EXPORTS } from "@nifrajs/web/route-manifest";
30
32
  import { parseZoneConfig } from "@nifrajs/web/zones";
31
33
  import { BACKEND_APP_FILE, CONFIG_FILE, FRAMEWORK_FILE, retiredRootFiles } from "./app-files.js";
32
34
  import { codeUnitOrder } from "./internal/code-unit-order.js";
35
+ import { configPathReader } from "./internal/config-paths.js";
33
36
  import { createKindProbe, hasWebConfig } from "./internal/nifra-project.js";
34
- import { createSpecifierResolver } from "./internal/project-specifiers.js";
37
+ import { createSpecifierResolver, isFile } from "./internal/project-specifiers.js";
35
38
  import { importTypeScript } from "./internal/typescript-import.js";
39
+ import { planOutputSchemas } from "./output-schemas.js";
36
40
  import { missingOutputSchemas } from "./rules/data-guard.js";
41
+ import { apiPrefixFix } from "./rules/pages.js";
37
42
  /** Exports only the server or the build reads: `@nifrajs/web`'s route-pair contract. */
38
43
  const BACKEND_EXPORTS = BACKEND_ROUTE_EXPORTS;
39
44
  const ROUTE_FILE = /\.(?:tsx|jsx|svelte|vue|mdx)$/;
@@ -55,11 +60,13 @@ const LEGACY_SERVER = /\.server(\.(?:[cm]?[jt]sx?|svelte|vue|mdx))$/;
55
60
  const RETIRED_SPECIFIERS = {
56
61
  "@nifrajs/web/server-only": "@nifrajs/web/backend-only",
57
62
  };
58
- /** Scripts and config that name app files by path: scanned for paths that moved, never rewritten. */
63
+ /** Scripts and config that name app files by path: scanned for paths that moved. Only the app's own
64
+ * package.json is rewritten, in the fields `rewritePackagePaths` reads. */
59
65
  const TOOLING_FILE = /(?:\.(?:json|jsonc|ya?ml|toml|sh|bash|zsh|ps1)|(?:^|\/)(?:Dockerfile|Makefile|Procfile))$/;
60
66
  const SELF_LOCATION = /\bimport\.meta\.(?:dirname|dir|filename|url)\b|\b__(?:dirname|filename)\b/;
61
67
  const SKIP_DIRS = new Set(["node_modules", "dist", "build", "coverage", ".git", ".vite", "public"]);
62
68
  const ZONE_DIRS = new Set(["frontend", "backend", "shared", "routes", "public"]);
69
+ const FOLDER_SIDES = ["frontend", "backend", "shared"];
63
70
  /** Data other tools may read by path too; reported, never moved. Images and fonts still move. */
64
71
  const DATA_FILE = /\.(?:json|jsonc|json5|ndjson|ya?ml|toml|csv|tsv|txt|xml|sql)$/;
65
72
  /** Test-runner calls that name a module by path, as an import does. */
@@ -76,7 +83,28 @@ const MOCK_CALLS = new Set([
76
83
  "jest.unstable_mockModule",
77
84
  ]);
78
85
  const TAILWIND_CONFIG = /^tailwind\.config\.[cm]?[jt]s$/;
86
+ /** What a `x.test.ts` beside `x.<ext>` tests. */
87
+ const SUBJECT_EXTENSIONS = [
88
+ ".ts",
89
+ ".tsx",
90
+ ".mts",
91
+ ".cts",
92
+ ".js",
93
+ ".jsx",
94
+ ".mjs",
95
+ ".cjs",
96
+ ".svelte",
97
+ ".vue",
98
+ ];
79
99
  const toPosix = (path) => path.replaceAll("\\", "/");
100
+ /** A specifier without its `?query` or `#hash`; a leading `#` names a package.json import. Cut by
101
+ * index, since `/[?#].*$/` retries from every `#` and is quadratic on a long run of them. */
102
+ const withoutQuery = (specifier) => {
103
+ const query = specifier.indexOf("?", 1);
104
+ const hash = specifier.indexOf("#", 1);
105
+ const cut = query === -1 ? hash : hash === -1 ? query : Math.min(query, hash);
106
+ return cut === -1 ? specifier : specifier.slice(0, cut);
107
+ };
80
108
  /** Every first-party file under `root`, app-relative and posix. */
81
109
  function listFiles(root) {
82
110
  const out = [];
@@ -164,6 +192,7 @@ function describeStatements(ts, sf) {
164
192
  return sf.statements.map((node) => {
165
193
  const declares = new Set();
166
194
  const exports = new Map();
195
+ const listed = [];
167
196
  const exported = hasModifier(ts, node, ts.SyntaxKind.ExportKeyword);
168
197
  const isDefault = hasModifier(ts, node, ts.SyntaxKind.DefaultKeyword);
169
198
  const addExport = (local, as) => {
@@ -209,7 +238,10 @@ function describeStatements(ts, sf) {
209
238
  node.exportClause &&
210
239
  ts.isNamedExports(node.exportClause)) {
211
240
  for (const el of node.exportClause.elements) {
212
- addExport(node.moduleSpecifier ? `\0${el.name.text}` : (el.propertyName ?? el.name).text, el.name.text);
241
+ const local = (el.propertyName ?? el.name).text;
242
+ addExport(node.moduleSpecifier ? `\0${el.name.text}` : local, el.name.text);
243
+ if (node.moduleSpecifier === undefined)
244
+ listed.push({ exported: el.name.text, local, type: node.isTypeOnly || el.isTypeOnly });
213
245
  }
214
246
  }
215
247
  const refs = ts.isImportDeclaration(node)
@@ -226,32 +258,58 @@ function describeStatements(ts, sf) {
226
258
  exports,
227
259
  valueRefs: refs.value,
228
260
  typeRefs: refs.type,
261
+ listed,
229
262
  };
230
263
  });
231
264
  }
232
- /** Rebuild an import keeping only the bindings `keep` names. `undefined` when none remain. */
233
- function filterImport(ts, sf, node, keep) {
265
+ /**
266
+ * Rebuild an import keeping only the bindings `uses` names; `undefined` when none remain. Bindings
267
+ * read only in types become `import type`, so no bundler loads the module for them: always in a
268
+ * `fresh` module, and in the page only where the split narrowed the import.
269
+ */
270
+ function filterImport(ts, sf, node, uses, fresh) {
234
271
  const clause = node.importClause;
235
272
  const spec = node.moduleSpecifier.getText(sf);
236
273
  const attributes = node.attributes ? ` ${node.attributes.getText(sf)}` : "";
237
274
  if (clause === undefined)
238
275
  return node.getFullText(sf);
239
- const parts = [];
240
- if (clause.name && keep(clause.name.text))
241
- parts.push(clause.name.text);
276
+ const heads = [];
277
+ const named = [];
278
+ let total = 0;
279
+ const add = (into, name, text, bare) => {
280
+ total++;
281
+ if (uses.value.has(name) || uses.type.has(name))
282
+ into.push({ text, bare, typeOnly: !uses.value.has(name) });
283
+ };
284
+ if (clause.name)
285
+ add(heads, clause.name.text, clause.name.text, clause.name.text);
242
286
  const bindings = clause.namedBindings;
243
- if (bindings && ts.isNamespaceImport(bindings) && keep(bindings.name.text))
244
- parts.push(`* as ${bindings.name.text}`);
287
+ if (bindings && ts.isNamespaceImport(bindings)) {
288
+ const text = `* as ${bindings.name.text}`;
289
+ add(heads, bindings.name.text, text, text);
290
+ }
245
291
  if (bindings && ts.isNamedImports(bindings)) {
246
- const named = bindings.elements.filter((el) => keep(el.name.text)).map((el) => el.getText(sf));
247
- if (named.length > 0)
248
- parts.push(`{ ${named.join(", ")} }`);
292
+ for (const el of bindings.elements) {
293
+ const renamed = el.propertyName ? `${el.propertyName.getText(sf)} as ` : "";
294
+ add(named, el.name.text, el.getText(sf), `${renamed}${el.name.text}`);
295
+ }
249
296
  }
250
- if (parts.length === 0)
297
+ const kept = [...heads, ...named];
298
+ if (kept.length === 0)
251
299
  return undefined;
252
- const typeOnly = clause.isTypeOnly ? "type " : "";
253
300
  const leading = node.getFullText(sf).slice(0, node.getStart(sf) - node.getFullStart());
254
- return `${leading}import ${typeOnly}${parts.join(", ")} from ${spec}${attributes}${terminatorOf(sf, node)}`;
301
+ const statement = (typeOnly, body) => `import ${typeOnly ? "type " : ""}${body} from ${spec}${attributes}${terminatorOf(sf, node)}`;
302
+ const list = (parts, text) => parts.length === 0 ? [] : [`{ ${parts.map(text).join(", ")} }`];
303
+ if (!clause.isTypeOnly &&
304
+ node.attributes === undefined &&
305
+ (fresh || kept.length < total) &&
306
+ kept.every((part) => part.typeOnly)) {
307
+ // `import type` takes one default, namespace or list, so each goes in its own statement.
308
+ const bodies = [...heads.map((part) => part.bare), ...list(named, (part) => part.bare)];
309
+ return `${leading}${bodies.map((body) => statement(true, body)).join("\n")}`;
310
+ }
311
+ const body = [...heads.map((part) => part.text), ...list(named, (part) => part.text)];
312
+ return `${leading}${statement(clause.isTypeOnly, body.join(", "))}`;
255
313
  }
256
314
  /** The `;` a statement was written with, so a rebuilt one keeps the file's style. */
257
315
  const terminatorOf = (sf, node) => node.getText(sf).endsWith(";") ? ";" : "";
@@ -272,11 +330,108 @@ const joinStatements = (texts) => {
272
330
  const body = texts.join("").replace(/^\s*\n/, "");
273
331
  return body.endsWith("\n") ? body : `${body}\n`;
274
332
  };
333
+ const PURE_OBJECT_CALLS = new Set(["keys", "values", "entries", "freeze", "fromEntries"]);
334
+ /**
335
+ * Whether `node` builds constant data: literals, arrays and objects of it, operators over it,
336
+ * `Object.keys`-style reads, and the file's own top-level names, which go into `reads`. `undefined`
337
+ * when it is data; else the import it reads, or `""` for anything else (a call, a function, a global).
338
+ */
339
+ function dataBlocker(ts, node, isLocal, reads) {
340
+ const data = (n) => {
341
+ if (ts.isStringLiteral(n) ||
342
+ ts.isNumericLiteral(n) ||
343
+ ts.isBigIntLiteral(n) ||
344
+ ts.isNoSubstitutionTemplateLiteral(n) ||
345
+ n.kind === ts.SyntaxKind.TrueKeyword ||
346
+ n.kind === ts.SyntaxKind.FalseKeyword ||
347
+ n.kind === ts.SyntaxKind.NullKeyword)
348
+ return undefined;
349
+ if (ts.isIdentifier(n)) {
350
+ if (isLocal(n.text)) {
351
+ reads.add(n.text);
352
+ return undefined;
353
+ }
354
+ return n.text === "undefined" ? undefined : n.text;
355
+ }
356
+ const every = (nodes) => {
357
+ for (const child of nodes) {
358
+ const blocker = data(child);
359
+ if (blocker !== undefined)
360
+ return blocker;
361
+ }
362
+ return undefined;
363
+ };
364
+ if (ts.isTemplateExpression(n))
365
+ return every(n.templateSpans.map((span) => span.expression));
366
+ if (ts.isPrefixUnaryExpression(n))
367
+ return n.operator === ts.SyntaxKind.PlusPlusToken ||
368
+ n.operator === ts.SyntaxKind.MinusMinusToken
369
+ ? ""
370
+ : data(n.operand);
371
+ if (ts.isBinaryExpression(n)) {
372
+ const operator = n.operatorToken.kind;
373
+ const assigns = operator >= ts.SyntaxKind.FirstAssignment && operator <= ts.SyntaxKind.LastAssignment;
374
+ if (assigns ||
375
+ operator === ts.SyntaxKind.CommaToken ||
376
+ operator === ts.SyntaxKind.InKeyword ||
377
+ operator === ts.SyntaxKind.InstanceOfKeyword)
378
+ return "";
379
+ return every([n.left, n.right]);
380
+ }
381
+ if (ts.isConditionalExpression(n))
382
+ return every([n.condition, n.whenTrue, n.whenFalse]);
383
+ if (ts.isArrayLiteralExpression(n))
384
+ return every(n.elements.flatMap((element) => ts.isOmittedExpression(element)
385
+ ? []
386
+ : [ts.isSpreadElement(element) ? element.expression : element]));
387
+ if (ts.isObjectLiteralExpression(n)) {
388
+ for (const property of n.properties) {
389
+ const blocker = ts.isPropertyAssignment(property)
390
+ ? ((ts.isComputedPropertyName(property.name)
391
+ ? data(property.name.expression)
392
+ : undefined) ?? data(property.initializer))
393
+ : ts.isShorthandPropertyAssignment(property)
394
+ ? property.objectAssignmentInitializer === undefined
395
+ ? data(property.name)
396
+ : ""
397
+ : ts.isSpreadAssignment(property)
398
+ ? data(property.expression)
399
+ : "";
400
+ if (blocker !== undefined)
401
+ return blocker;
402
+ }
403
+ return undefined;
404
+ }
405
+ if (ts.isParenthesizedExpression(n) ||
406
+ ts.isAsExpression(n) ||
407
+ ts.isSatisfiesExpression(n) ||
408
+ ts.isNonNullExpression(n) ||
409
+ ts.isTypeAssertionExpression(n))
410
+ return data(n.expression);
411
+ if (ts.isPropertyAccessExpression(n))
412
+ return ts.isPrivateIdentifier(n.name) ? "" : data(n.expression);
413
+ if (ts.isElementAccessExpression(n))
414
+ return every([n.expression, n.argumentExpression]);
415
+ if (ts.isCallExpression(n)) {
416
+ const callee = n.expression;
417
+ const objectRead = ts.isPropertyAccessExpression(callee) &&
418
+ ts.isIdentifier(callee.expression) &&
419
+ callee.expression.text === "Object" &&
420
+ !isLocal("Object") &&
421
+ PURE_OBJECT_CALLS.has(callee.name.text) &&
422
+ n.questionDotToken === undefined &&
423
+ n.typeArguments === undefined;
424
+ return objectRead ? every(n.arguments) : "";
425
+ }
426
+ return "";
427
+ };
428
+ return data(node);
429
+ }
275
430
  /**
276
431
  * Split one route module's source into its frontend and backend halves. `backendSpecifier` is how the
277
432
  * frontend refers to the backend half in an `import type` (`./index.backend.ts`).
278
433
  */
279
- export function splitRouteSource(ts, source, fileName, backendSpecifier) {
434
+ export function splitRouteSource(ts, source, fileName, backendSpecifier, options = {}) {
280
435
  const kind = fileName.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
281
436
  const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, kind);
282
437
  const statements = describeStatements(ts, sf);
@@ -287,72 +442,175 @@ export function splitRouteSource(ts, source, fileName, backendSpecifier) {
287
442
  if (moved.length === 0)
288
443
  return { frontend: source, backend: undefined, moved: [], issues: [] };
289
444
  const declaredBy = new Map();
445
+ const importedBy = new Map();
290
446
  for (const info of statements) {
291
- if (ts.isImportDeclaration(info.node))
292
- continue;
447
+ const into = ts.isImportDeclaration(info.node) ? importedBy : declaredBy;
293
448
  for (const name of info.declares)
294
- declaredBy.set(name, info);
295
- }
296
- // The backend half: its export statements plus every top-level declaration they reach.
297
- const backendSet = new Set();
298
- const queue = statements.filter(isBackendStatement);
299
- for (const info of queue)
300
- backendSet.add(info);
301
- while (queue.length > 0) {
302
- const info = queue.pop();
303
- for (const name of [...info.valueRefs, ...info.typeRefs]) {
304
- const target = declaredBy.get(name);
305
- if (target !== undefined && !backendSet.has(target)) {
306
- backendSet.add(target);
307
- queue.push(target);
308
- }
309
- }
310
- // An exported-name statement (`export { loader }`) reaches the declaration it names.
311
- for (const local of info.exports.keys()) {
312
- const target = declaredBy.get(local);
313
- if (target !== undefined && !backendSet.has(target)) {
314
- backendSet.add(target);
315
- queue.push(target);
316
- }
317
- }
449
+ into.set(name, info);
318
450
  }
319
- // The frontend half: everything that is not a backend export statement, minus declarations that only
320
- // the backend half needs.
451
+ const isTypeDeclaration = (info) => ts.isInterfaceDeclaration(info.node) || ts.isTypeAliasDeclaration(info.node);
452
+ /** What `info` reads for one half: an export list reads only the locals it exports there. */
453
+ const readsFor = (info, backend) => {
454
+ if (info.listed.length === 0)
455
+ return { value: info.valueRefs, type: info.typeRefs };
456
+ const mine = info.listed.filter((entry) => BACKEND_EXPORTS.has(entry.exported) === backend);
457
+ return {
458
+ value: new Set(mine.filter((entry) => !entry.type).map((entry) => entry.local)),
459
+ type: new Set(mine.filter((entry) => entry.type).map((entry) => entry.local)),
460
+ };
461
+ };
321
462
  const movedLocals = new Set();
322
463
  for (const info of statements) {
323
464
  for (const [local, names] of info.exports)
324
465
  if (names.some((name) => BACKEND_EXPORTS.has(name)))
325
466
  movedLocals.add(local);
326
467
  }
327
- const frontendCandidates = statements.filter((info) => !ts.isImportDeclaration(info.node));
328
- const frontendKeep = new Set();
329
- const seed = frontendCandidates.filter((info) => !backendSet.has(info) ||
330
- (!isBackendStatement(info) && exportsOf(info).length > 0) ||
331
- // a statement with no declaration (a side effect) stays where it ran
332
- (info.declares.size === 0 && info.exports.size === 0));
333
- const fqueue = [...seed];
334
- for (const info of fqueue)
335
- frontendKeep.add(info);
336
- while (fqueue.length > 0) {
337
- const info = fqueue.pop();
338
- for (const name of info.valueRefs) {
339
- if (movedLocals.has(name) && !info.declares.has(name))
340
- continue;
468
+ /** Each half's statements. What `shared` holds, both import, so neither half keeps a copy. */
469
+ const partition = (shared) => {
470
+ const local = (name) => {
341
471
  const target = declaredBy.get(name);
342
- if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
343
- frontendKeep.add(target);
344
- fqueue.push(target);
472
+ return target === undefined || shared.has(target) ? undefined : target;
473
+ };
474
+ // The backend half: its export statements plus every top-level declaration they reach.
475
+ const backendSet = new Set();
476
+ const queue = statements.filter(isBackendStatement);
477
+ for (const info of queue)
478
+ backendSet.add(info);
479
+ while (queue.length > 0) {
480
+ const info = queue.pop();
481
+ const reads = readsFor(info, true);
482
+ for (const name of [...reads.value, ...reads.type]) {
483
+ const target = local(name);
484
+ if (target !== undefined && !backendSet.has(target)) {
485
+ backendSet.add(target);
486
+ queue.push(target);
487
+ }
345
488
  }
346
489
  }
347
- for (const name of info.typeRefs) {
348
- if (movedLocals.has(name))
349
- continue;
350
- const target = declaredBy.get(name);
351
- if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
352
- frontendKeep.add(target);
353
- fqueue.push(target);
490
+ // The frontend half: everything that is not a backend export statement, minus declarations that
491
+ // only the backend half needs. An export list that also names backend exports keeps the rest.
492
+ const frontendKeep = new Set();
493
+ const seed = statements.filter((info) => !ts.isImportDeclaration(info.node) &&
494
+ !shared.has(info) &&
495
+ (!backendSet.has(info) ||
496
+ exportsOf(info).some((name) => !BACKEND_EXPORTS.has(name)) ||
497
+ // a statement with no declaration (a side effect) stays where it ran
498
+ (info.declares.size === 0 && info.exports.size === 0)));
499
+ const fqueue = [...seed];
500
+ for (const info of fqueue)
501
+ frontendKeep.add(info);
502
+ while (fqueue.length > 0) {
503
+ const info = fqueue.pop();
504
+ const reads = readsFor(info, false);
505
+ for (const name of reads.value) {
506
+ if (movedLocals.has(name) && !info.declares.has(name))
507
+ continue;
508
+ const target = local(name);
509
+ if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
510
+ frontendKeep.add(target);
511
+ fqueue.push(target);
512
+ }
513
+ }
514
+ for (const name of reads.type) {
515
+ if (movedLocals.has(name))
516
+ continue;
517
+ const target = local(name);
518
+ if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
519
+ frontendKeep.add(target);
520
+ fqueue.push(target);
521
+ }
354
522
  }
355
523
  }
524
+ return { backendSet, frontendKeep };
525
+ };
526
+ let { backendSet, frontendKeep } = partition(new Set());
527
+ const copies = () => [...frontendKeep].filter((info) => backendSet.has(info) &&
528
+ !isBackendStatement(info) &&
529
+ info.declares.size > 0 &&
530
+ !isTypeDeclaration(info));
531
+ // Constant data both halves read moves to a module beside the route, with the declarations it
532
+ // needs: one definition, which neither half's bundle can drift from.
533
+ const shared = new Set();
534
+ const sharedTypes = new Set();
535
+ const sharedImports = new Set();
536
+ const unshared = new Map();
537
+ if (options.sharedFile !== undefined) {
538
+ /** Why `info` cannot move to the shared module, or `undefined` once it and what it needs are in `closure`. */
539
+ const gather = (info, closure) => {
540
+ if (closure.values.has(info) || shared.has(info))
541
+ return undefined;
542
+ const node = info.node;
543
+ const reads = new Set();
544
+ let blocker = "";
545
+ if (!isBackendStatement(info) &&
546
+ ts.isVariableStatement(node) &&
547
+ (node.declarationList.flags & ts.NodeFlags.Const) !== 0 &&
548
+ !hasModifier(ts, node, ts.SyntaxKind.DeclareKeyword)) {
549
+ blocker = undefined;
550
+ for (const declaration of node.declarationList.declarations) {
551
+ blocker =
552
+ ts.isIdentifier(declaration.name) && declaration.initializer !== undefined
553
+ ? dataBlocker(ts, declaration.initializer, (name) => declaredBy.has(name), reads)
554
+ : "";
555
+ if (blocker !== undefined)
556
+ break;
557
+ }
558
+ }
559
+ if (blocker !== undefined)
560
+ return blocker !== "" && importedBy.has(blocker)
561
+ ? `it reads the import "${blocker}"`
562
+ : "it is not constant data";
563
+ closure.values.add(info);
564
+ for (const name of reads) {
565
+ const target = declaredBy.get(name);
566
+ const why = target === undefined ? undefined : gather(target, closure);
567
+ if (why !== undefined)
568
+ return `it reads "${name}", which ${why.slice(3)}`;
569
+ }
570
+ for (const name of info.typeRefs) {
571
+ const why = gatherType(name, closure);
572
+ if (why !== undefined)
573
+ return why;
574
+ }
575
+ return undefined;
576
+ };
577
+ const gatherType = (name, closure) => {
578
+ const local = declaredBy.get(name);
579
+ if (local === undefined) {
580
+ if (importedBy.has(name))
581
+ closure.imports.add(name);
582
+ return undefined;
583
+ }
584
+ if (!isTypeDeclaration(local)) {
585
+ const why = gather(local, closure);
586
+ return why === undefined ? undefined : `its type reads "${name}", which ${why.slice(3)}`;
587
+ }
588
+ if (closure.types.has(local) || sharedTypes.has(local))
589
+ return undefined;
590
+ closure.types.add(local);
591
+ for (const ref of [...local.typeRefs, ...local.valueRefs]) {
592
+ const why = gatherType(ref, closure);
593
+ if (why !== undefined)
594
+ return why;
595
+ }
596
+ return undefined;
597
+ };
598
+ for (const info of copies()) {
599
+ const closure = { values: new Set(), types: new Set(), imports: new Set() };
600
+ const why = gather(info, closure);
601
+ if (why !== undefined) {
602
+ unshared.set(info, why);
603
+ continue;
604
+ }
605
+ for (const value of closure.values)
606
+ shared.add(value);
607
+ for (const type of closure.types)
608
+ sharedTypes.add(type);
609
+ for (const name of closure.imports)
610
+ sharedImports.add(name);
611
+ }
612
+ if (shared.size > 0)
613
+ ({ backendSet, frontendKeep } = partition(shared));
356
614
  }
357
615
  // A moved name the frontend still mentions: in a type it becomes `import type`; at runtime it is an
358
616
  // error the author has to resolve.
@@ -360,44 +618,83 @@ export function splitRouteSource(ts, source, fileName, backendSpecifier) {
360
618
  for (const info of frontendKeep) {
361
619
  if (isBackendStatement(info))
362
620
  continue;
621
+ const reads = readsFor(info, false);
363
622
  for (const name of movedLocals) {
364
623
  if (info.declares.has(name))
365
624
  continue;
366
- if (info.valueRefs.has(name))
625
+ if (reads.value.has(name))
367
626
  issues.push(`the frontend uses "${name}" at runtime, but it runs on the server only`);
368
- if (info.typeRefs.has(name) || info.valueRefs.has(name))
627
+ if (reads.type.has(name) || reads.value.has(name))
369
628
  typeImports.add(name);
370
629
  }
371
630
  }
372
- for (const info of frontendKeep) {
373
- if (!backendSet.has(info) || isBackendStatement(info) || info.declares.size === 0)
374
- continue;
375
- const values = [...info.declares].filter(() => !ts.isInterfaceDeclaration(info.node) && !ts.isTypeAliasDeclaration(info.node));
376
- if (values.length > 0)
377
- issues.push(`"${values.join(", ")}" is needed by both halves and was copied into each; consider moving it to shared/`);
378
- }
379
- const used = (infos) => {
380
- const names = new Set();
381
- for (const info of infos)
382
- for (const name of [...info.valueRefs, ...info.typeRefs])
383
- names.add(name);
384
- return names;
631
+ for (const info of copies()) {
632
+ const why = unshared.get(info);
633
+ issues.push(`"${[...info.declares].join(", ")}" is needed by both halves and was copied into each${why === undefined ? "" : `, since ${why}`}; consider moving it to shared/`);
634
+ }
635
+ const uses = (infos, backend) => {
636
+ const value = new Set();
637
+ const type = new Set();
638
+ for (const info of infos) {
639
+ const reads = readsFor(info, backend);
640
+ for (const name of reads.value)
641
+ value.add(name);
642
+ for (const name of reads.type)
643
+ type.add(name);
644
+ }
645
+ return { value, type };
385
646
  };
386
- const backendUses = used(backendSet);
387
- const frontendUses = used([...frontendKeep].filter((info) => !isBackendStatement(info)));
647
+ const backendUses = uses(backendSet, true);
648
+ const frontendUses = uses(frontendKeep, false);
649
+ const semi = statements.some((info) => terminatorOf(sf, info.node) !== "") ? ";" : "";
650
+ // The imports the split writes quote the way the file's own imports do.
651
+ const firstImport = statements.find((info) => ts.isImportDeclaration(info.node))?.node;
652
+ const quote = firstImport !== undefined && ts.isImportDeclaration(firstImport)
653
+ ? (firstImport.moduleSpecifier.getText(sf)[0] ?? '"')
654
+ : '"';
655
+ const sharedNames = [...shared].flatMap((info) => [...info.declares]);
656
+ const sharedSpecifier = (() => {
657
+ const file = options.sharedFile ?? "";
658
+ // The halves name the module the way the route names its other relative imports.
659
+ const relative = statements.flatMap((info) => ts.isImportDeclaration(info.node) &&
660
+ ts.isStringLiteral(info.node.moduleSpecifier) &&
661
+ info.node.moduleSpecifier.text.startsWith(".")
662
+ ? [info.node.moduleSpecifier.text]
663
+ : []);
664
+ const extension = relative
665
+ .map((specifier) => /\.(ts|tsx|js|jsx)$/.exec(specifier)?.[1])
666
+ .find((found) => found !== undefined);
667
+ const suffix = extension === undefined ? "" : extension.startsWith("t") ? ".ts" : ".js";
668
+ return `./${file.replace(/\.ts$/, "")}${suffix}`;
669
+ })();
670
+ const sharedImport = (half) => {
671
+ const names = sharedNames
672
+ .filter((name) => half.value.has(name) || half.type.has(name))
673
+ .sort(codeUnitOrder);
674
+ if (names.length === 0)
675
+ return [];
676
+ const typeOnly = names.every((name) => !half.value.has(name));
677
+ return [
678
+ `\nimport ${typeOnly ? "type " : ""}{ ${names.join(", ")} } from ${quote}${sharedSpecifier}${quote}${semi}`,
679
+ ];
680
+ };
681
+ // The page still exports what it exported, now from the shared module.
682
+ const reexported = [...shared].flatMap((info) => [...info.exports].flatMap(([local, names]) => names.map((name) => (name === local ? local : `${local} as ${name}`))));
388
683
  const backendTexts = [];
389
684
  const frontendTexts = [];
390
685
  let afterImports = 0;
686
+ let backendAfterImports = 0;
391
687
  for (const info of statements) {
392
688
  const node = info.node;
393
689
  if (ts.isImportDeclaration(node)) {
394
- const back = filterImport(ts, sf, node, (name) => backendUses.has(name));
690
+ const back = filterImport(ts, sf, node, backendUses, true);
395
691
  if (back !== undefined)
396
692
  backendTexts.push(node.importClause ? back : "");
397
- const front = filterImport(ts, sf, node, (name) => frontendUses.has(name));
693
+ const front = filterImport(ts, sf, node, frontendUses, false);
398
694
  if (front !== undefined)
399
695
  frontendTexts.push(front);
400
696
  afterImports = frontendTexts.length;
697
+ backendAfterImports = backendTexts.length;
401
698
  continue;
402
699
  }
403
700
  if (isBackendStatement(info)) {
@@ -419,22 +716,49 @@ export function splitRouteSource(ts, source, fileName, backendSpecifier) {
419
716
  frontendTexts.push(info.text);
420
717
  }
421
718
  // After the other imports: the nearest relative path sorts last.
422
- if (typeImports.size > 0) {
423
- const semi = statements.some((info) => terminatorOf(sf, info.node) !== "") ? ";" : "";
424
- frontendTexts.splice(afterImports, 0, `\nimport type { ${[...typeImports].sort().join(", ")} } from "${backendSpecifier}"${semi}`);
425
- }
719
+ const frontendImports = sharedImport(frontendUses);
720
+ if (reexported.length > 0)
721
+ frontendImports.push(`\nexport { ${reexported.join(", ")} } from ${quote}${sharedSpecifier}${quote}${semi}`);
722
+ if (typeImports.size > 0)
723
+ frontendImports.push(`\nimport type { ${[...typeImports].sort().join(", ")} } from ${quote}${backendSpecifier}${quote}${semi}`);
724
+ frontendTexts.splice(afterImports, 0, ...frontendImports);
725
+ backendTexts.splice(backendAfterImports, 0, ...sharedImport(backendUses));
426
726
  // A JSX pragma counts only in the file's leading comments, and the backend half has no JSX.
427
727
  const pragmas = (ts.getLeadingCommentRanges(source, 0) ?? [])
428
728
  .map((range) => source.slice(range.pos, range.end))
429
729
  .filter((comment) => /@jsx/.test(comment));
430
730
  const lift = (text) => pragmas.reduce((out, pragma) => out.replace(new RegExp(`${escapeRegExp(pragma)}[ \\t]*\\n?`), ""), text);
431
731
  const frontend = lift(joinStatements(frontendTexts));
432
- return {
732
+ let sharedText;
733
+ if (shared.size > 0) {
734
+ const texts = [];
735
+ const typeUses = { value: new Set(), type: sharedImports };
736
+ for (const info of statements) {
737
+ if (ts.isImportDeclaration(info.node)) {
738
+ const kept = filterImport(ts, sf, info.node, typeUses, true);
739
+ if (kept !== undefined && info.node.importClause !== undefined)
740
+ texts.push(kept);
741
+ }
742
+ else if (shared.has(info) || sharedTypes.has(info)) {
743
+ texts.push(withExport(ts, sf, info));
744
+ }
745
+ }
746
+ sharedText = lift(joinStatements(texts));
747
+ }
748
+ const result = {
433
749
  frontend: pragmas.length > 0 ? `${pragmas.join("\n")}\n${frontend}` : frontend,
434
750
  backend: lift(joinStatements(backendTexts)),
435
751
  moved: [...new Set(moved)].sort(),
436
752
  issues,
437
753
  };
754
+ return sharedText === undefined ? result : { ...result, shared: sharedText };
755
+ }
756
+ /** A declaration the shared module holds is exported, so either half can import it. */
757
+ function withExport(ts, sf, info) {
758
+ if (hasModifier(ts, info.node, ts.SyntaxKind.ExportKeyword))
759
+ return info.text;
760
+ const at = info.node.getStart(sf) - info.node.getFullStart();
761
+ return `${info.text.slice(0, at)}export ${info.text.slice(at)}`;
438
762
  }
439
763
  /** A helper the backend half copies keeps its declaration; an `export` on it would add a backend export. */
440
764
  function stripExport(ts, sf, info) {
@@ -596,11 +920,105 @@ function importsOf(ts, file, text) {
596
920
  visit(sf);
597
921
  return refs;
598
922
  }
923
+ /** The `import.meta.glob` calls of a JS/TS module. */
924
+ function globCalls(ts, file, text) {
925
+ if (!/\.[cm]?[jt]sx?$/.test(file) || !text.includes("import.meta.glob"))
926
+ return [];
927
+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
928
+ const calls = [];
929
+ const visit = (node) => {
930
+ if (ts.isCallExpression(node) &&
931
+ ts.isPropertyAccessExpression(node.expression) &&
932
+ node.expression.name.text === "glob" &&
933
+ ts.isMetaProperty(node.expression.expression) &&
934
+ node.expression.expression.keywordToken === ts.SyntaxKind.ImportKeyword) {
935
+ const arg = node.arguments[0];
936
+ const elements = arg === undefined ? [] : ts.isArrayLiteralExpression(arg) ? [...arg.elements] : [arg];
937
+ const literals = elements.filter(ts.isStringLiteralLike);
938
+ const literal = literals.length > 0 && literals.length === elements.length;
939
+ calls.push({
940
+ patterns: literal
941
+ ? literals.map((element) => ({
942
+ text: element.text,
943
+ start: element.getStart(sf) + 1,
944
+ end: element.getEnd() - 1,
945
+ }))
946
+ : [],
947
+ literal,
948
+ line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1,
949
+ });
950
+ }
951
+ ts.forEachChild(node, visit);
952
+ };
953
+ visit(sf);
954
+ return calls;
955
+ }
956
+ /** A glob pattern written in `file` as an app-relative glob, by Vite's rules: `./` and `../` from the
957
+ * file's folder, `/` from the app root. `undefined` for any other shape, such as an alias. */
958
+ function appGlob(file, pattern) {
959
+ if (pattern.startsWith("/"))
960
+ return pattern.slice(1);
961
+ if (!pattern.startsWith("./") && !pattern.startsWith("../"))
962
+ return undefined;
963
+ const at = posix.normalize(posix.join(posix.dirname(file), pattern));
964
+ return at.startsWith("../") ? undefined : at;
965
+ }
966
+ /** The files among `files` a glob call in `file` loads, a `!` pattern excluding; `undefined` when a
967
+ * pattern cannot be read from the app. */
968
+ function globTargets(file, patterns, files) {
969
+ const include = [];
970
+ const exclude = [];
971
+ for (const raw of patterns) {
972
+ const at = appGlob(file, raw.startsWith("!") ? raw.slice(1) : raw);
973
+ if (at === undefined)
974
+ return undefined;
975
+ (raw.startsWith("!") ? exclude : include).push(new Bun.Glob(at));
976
+ }
977
+ return [...files].filter((candidate) => candidate !== file &&
978
+ include.some((glob) => glob.match(candidate)) &&
979
+ !exclude.some((glob) => glob.match(candidate)));
980
+ }
981
+ /**
982
+ * `pattern`, written in `from` (now `to`), re-pointed at the folder its matches `before` moved to: the
983
+ * part before the first wildcard is the folder, and every match must keep its path below it.
984
+ * `undefined` when the matches did not move as one folder.
985
+ */
986
+ function repointGlob(from, to, pattern, before, newPath) {
987
+ const negated = pattern.startsWith("!");
988
+ const written = negated ? pattern.slice(1) : pattern;
989
+ const at = appGlob(from, written);
990
+ if (at === undefined)
991
+ return undefined;
992
+ const segments = at.split("/");
993
+ const wild = segments.findIndex((segment) => /[*?[\]{}]/.test(segment));
994
+ const base = (wild === -1 ? segments.slice(0, -1) : segments.slice(0, wild)).join("/");
995
+ const rest = segments.slice(base === "" ? 0 : base.split("/").length).join("/");
996
+ let moved;
997
+ for (const file of before) {
998
+ if (base !== "" && !file.startsWith(`${base}/`))
999
+ continue;
1000
+ const tail = base === "" ? file : file.slice(base.length + 1);
1001
+ const now = newPath(file);
1002
+ if (!now.endsWith(`/${tail}`) && now !== tail)
1003
+ return undefined;
1004
+ const folder = now === tail ? "" : now.slice(0, now.length - tail.length - 1);
1005
+ if (moved !== undefined && folder !== moved)
1006
+ return undefined;
1007
+ moved = folder;
1008
+ }
1009
+ if (moved === undefined)
1010
+ return pattern;
1011
+ const folder = posix.relative(posix.dirname(to), moved);
1012
+ const next = written.startsWith("/")
1013
+ ? `/${moved === "" ? "" : `${moved}/`}${rest}`
1014
+ : `${folder === "" ? "." : folder.startsWith("..") ? folder : `./${folder}`}/${rest}`;
1015
+ return negated ? `!${next}` : next;
1016
+ }
599
1017
  /** Resolve a relative specifier against the file map, the way a bundler would. */
600
1018
  function resolveIn(files, from, specifier) {
601
1019
  if (!specifier.startsWith("."))
602
1020
  return undefined;
603
- const clean = specifier.replace(/[?#].*$/, "");
1021
+ const clean = withoutQuery(specifier);
604
1022
  const base = posix.normalize(posix.join(posix.dirname(from), clean));
605
1023
  const candidates = [
606
1024
  base,
@@ -629,7 +1047,121 @@ function liveSpecifierSpans(ts, file, text, files) {
629
1047
  }
630
1048
  return spans;
631
1049
  }
1050
+ /**
1051
+ * The comment spans of a JS/TS module: the leading and trailing trivia of each token. Empty when the
1052
+ * compiler cannot walk the tokens, so every mention in the file stays an issue.
1053
+ */
1054
+ function triviaCommentRanges(ts, file, text) {
1055
+ const spans = new Map();
1056
+ const add = (ranges) => {
1057
+ for (const range of ranges ?? [])
1058
+ spans.set(range.pos, range.end);
1059
+ };
1060
+ try {
1061
+ const kind = /x$/.test(file) ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
1062
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
1063
+ const visit = (node) => {
1064
+ // A JSDoc block is itself one of the comments its token's trivia holds; JSX text is not trivia.
1065
+ if (node.kind >= ts.SyntaxKind.FirstJSDocNode && node.kind <= ts.SyntaxKind.LastJSDocNode)
1066
+ return;
1067
+ if (ts.isJsxText(node))
1068
+ return;
1069
+ const children = node.getChildren(source);
1070
+ if (children.length > 0) {
1071
+ for (const child of children)
1072
+ visit(child);
1073
+ return;
1074
+ }
1075
+ add(ts.getLeadingCommentRanges(text, node.pos));
1076
+ add(ts.getTrailingCommentRanges(text, node.end));
1077
+ };
1078
+ visit(source);
1079
+ }
1080
+ catch {
1081
+ return [];
1082
+ }
1083
+ return [...spans];
1084
+ }
632
1085
  const OWN_DIR = new Set(["import.meta.dir", "import.meta.dirname", "__dirname"]);
1086
+ /**
1087
+ * The path `relative` names from the folder of `from`, named from the folder of `to`; `undefined` when
1088
+ * neither the file nor the target moved, so a file that stays keeps its spelling.
1089
+ */
1090
+ function rebaseRelative(from, to, relative, locate) {
1091
+ const before = posix.normalize(posix.join(posix.dirname(from), relative));
1092
+ const target = locate(before);
1093
+ if (from === to && target === before)
1094
+ return undefined;
1095
+ const next = posix.relative(posix.dirname(to), target) || ".";
1096
+ return relative.endsWith("/") && next !== "." ? `${next}/` : next;
1097
+ }
1098
+ /** A shell script's own folder: `$(dirname "$0")`, `$(dirname "${BASH_SOURCE[0]}")`, `${0%/*}`. */
1099
+ const SHELL_OWN_DIR = /\$\(\s*dirname\s+("?)\$(?:0|\{BASH_SOURCE(?:\[0\])?\}|BASH_SOURCE)\1\s*\)|`dirname\s+("?)\$0\2`|\$\{(?:0|BASH_SOURCE(?:\[0\])?)%\/\*\}/g;
1100
+ const SHELL_FILE = /\.(?:sh|bash|zsh)$/;
1101
+ /**
1102
+ * Re-point the paths a shell script moving from `from` to `to` builds from its own folder
1103
+ * (`cd "$(dirname "$0")/.."`), as `rebaseOwnPaths` does for a module. Returns the new text and the
1104
+ * first use of the script's folder with no literal path after it, which the migration cannot follow.
1105
+ */
1106
+ function rebaseShellPaths(from, to, text, locate) {
1107
+ let unfollowed;
1108
+ const edits = [];
1109
+ for (const match of text.matchAll(SHELL_OWN_DIR)) {
1110
+ const start = match.index + match[0].length;
1111
+ const trailing = /^\/([\w.@-]+(?:\/[\w.@-]+)*\/?)/.exec(text.slice(start))?.[1];
1112
+ if (trailing === undefined) {
1113
+ unfollowed ??= match[0];
1114
+ continue;
1115
+ }
1116
+ const rebased = rebaseRelative(from, to, trailing, locate);
1117
+ if (rebased !== undefined)
1118
+ edits.push({ start, end: start + 1 + trailing.length, text: `/${rebased}` });
1119
+ }
1120
+ let next = text;
1121
+ for (const edit of edits.reverse())
1122
+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);
1123
+ return { text: next, unfollowed };
1124
+ }
1125
+ /**
1126
+ * Top-level `const dir = import.meta.dir` (or `.dirname`, `__dirname`) bindings, by name. A name the
1127
+ * file declares anywhere else (a parameter, an inner `let`) is left out: a use could be that binding.
1128
+ */
1129
+ function ownDirAliases(ts, sf) {
1130
+ const aliases = new Map();
1131
+ for (const statement of sf.statements) {
1132
+ if (!ts.isVariableStatement(statement))
1133
+ continue;
1134
+ if ((statement.declarationList.flags & ts.NodeFlags.Const) === 0)
1135
+ continue;
1136
+ for (const declaration of statement.declarationList.declarations) {
1137
+ const { name, initializer } = declaration;
1138
+ if (ts.isIdentifier(name) &&
1139
+ initializer !== undefined &&
1140
+ OWN_DIR.has(initializer.getText(sf)))
1141
+ aliases.set(name.text, { name, initializer });
1142
+ }
1143
+ }
1144
+ if (aliases.size === 0)
1145
+ return aliases;
1146
+ const declared = new Map();
1147
+ const count = (node) => {
1148
+ const name = ts.isVariableDeclaration(node) ||
1149
+ ts.isParameter(node) ||
1150
+ ts.isFunctionDeclaration(node) ||
1151
+ ts.isClassDeclaration(node) ||
1152
+ ts.isBindingElement(node)
1153
+ ? node.name
1154
+ : undefined;
1155
+ if (name !== undefined && ts.isIdentifier(name))
1156
+ declared.set(name.text, (declared.get(name.text) ?? 0) + 1);
1157
+ ts.forEachChild(node, count);
1158
+ };
1159
+ count(sf);
1160
+ for (const name of [...aliases.keys()])
1161
+ if (declared.get(name) !== 1)
1162
+ aliases.delete(name);
1163
+ return aliases;
1164
+ }
633
1165
  /**
634
1166
  * Re-point the paths a module moving from `from` to `to` builds from its own location, so each still
635
1167
  * reaches what it did: `join(import.meta.dir, "..", "x")` (or `resolve`), `import.meta.dir + "/../x"`,
@@ -641,21 +1173,18 @@ function rebaseOwnPaths(ts, from, to, text, locate) {
641
1173
  const sf = ts.createSourceFile(to, text, ts.ScriptTarget.Latest, true, to.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
642
1174
  const edits = [];
643
1175
  const followed = [];
644
- const isOwnDir = (node) => node !== undefined && OWN_DIR.has(node.getText(sf));
1176
+ const aliases = ownDirAliases(ts, sf);
1177
+ const isOwnDir = (node) => node !== undefined &&
1178
+ (OWN_DIR.has(node.getText(sf)) || (ts.isIdentifier(node) && aliases.has(node.text)));
645
1179
  const isLiteral = (node) => node !== undefined && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node));
646
1180
  const quoted = (node, value) => {
647
1181
  const quote = node.getText(sf)[0] ?? '"';
648
1182
  return `${quote}${value}${quote}`;
649
1183
  };
650
- // The path `relative` names from the module's old folder, named from its new folder.
651
- const rebased = (relative) => {
652
- const target = locate(posix.normalize(posix.join(posix.dirname(from), relative)));
653
- const next = posix.relative(posix.dirname(to), target) || ".";
654
- return relative.endsWith("/") && next !== "." ? `${next}/` : next;
655
- };
1184
+ const rebased = (relative) => rebaseRelative(from, to, relative, locate);
656
1185
  const follow = (anchor, start, end, replacement) => {
657
1186
  followed.push([anchor.getStart(sf), anchor.getEnd()]);
658
- if (text.slice(start, end) !== replacement)
1187
+ if (replacement !== undefined && text.slice(start, end) !== replacement)
659
1188
  edits.push({ start, end, text: replacement });
660
1189
  };
661
1190
  const visit = (node) => {
@@ -671,8 +1200,11 @@ function rebaseOwnPaths(ts, from, to, text, locate) {
671
1200
  parts.every(isLiteral) &&
672
1201
  !(callee.endsWith("resolve") && parts.some((part) => part.text.startsWith("/")))) {
673
1202
  const next = rebased(posix.join(...parts.map((part) => part.text)));
674
- const segments = parts.length === 1 ? [next] : next.split("/").filter((s) => s !== "");
675
- const replacement = segments.map((segment) => quoted(first, segment)).join(", ");
1203
+ const replacement = next === undefined
1204
+ ? undefined
1205
+ : (parts.length === 1 ? [next] : next.split("/").filter((s) => s !== ""))
1206
+ .map((segment) => quoted(first, segment))
1207
+ .join(", ");
676
1208
  follow(dir, first.getStart(sf), last.getEnd(), replacement);
677
1209
  return;
678
1210
  }
@@ -683,14 +1215,14 @@ function rebaseOwnPaths(ts, from, to, text, locate) {
683
1215
  isLiteral(node.right) &&
684
1216
  node.right.text.startsWith("/")) {
685
1217
  const next = rebased(node.right.text.slice(1) || ".");
686
- follow(node.left, node.right.getStart(sf), node.right.getEnd(), quoted(node.right, `/${next}`));
1218
+ follow(node.left, node.right.getStart(sf), node.right.getEnd(), next === undefined ? undefined : quoted(node.right, `/${next}`));
687
1219
  return;
688
1220
  }
689
1221
  if (ts.isTemplateExpression(node) && node.head.text === "" && node.templateSpans.length === 1) {
690
1222
  const span = node.templateSpans[0];
691
1223
  if (span !== undefined && isOwnDir(span.expression) && span.literal.text.startsWith("/")) {
692
1224
  const next = rebased(span.literal.text.slice(1) || ".");
693
- const replacement = `\`\${${span.expression.getText(sf)}}/${next}\``;
1225
+ const replacement = next === undefined ? undefined : `\`\${${span.expression.getText(sf)}}/${next}\``;
694
1226
  follow(span.expression, node.getStart(sf), node.getEnd(), replacement);
695
1227
  return;
696
1228
  }
@@ -702,7 +1234,7 @@ function rebaseOwnPaths(ts, from, to, text, locate) {
702
1234
  const path = node.arguments[0];
703
1235
  if (isLiteral(path) && !/^(?:\/|[a-z][a-z\d+.-]*:)/i.test(path.text)) {
704
1236
  const next = rebased(path.text);
705
- const replacement = quoted(path, next.startsWith("..") ? next : `./${next}`);
1237
+ const replacement = next === undefined ? undefined : quoted(path, next.startsWith("..") ? next : `./${next}`);
706
1238
  follow(node.arguments[1], path.getStart(sf), path.getEnd(), replacement);
707
1239
  return;
708
1240
  }
@@ -710,6 +1242,20 @@ function rebaseOwnPaths(ts, from, to, text, locate) {
710
1242
  ts.forEachChild(node, visit);
711
1243
  };
712
1244
  visit(sf);
1245
+ // An alias whose every use was re-pointed is followed too; one left in a call the migration cannot
1246
+ // read keeps its `import.meta.dir` unfollowed.
1247
+ for (const [name, declaration] of aliases) {
1248
+ const isFollowed = (node) => followed.some(([start, end]) => start <= node.getStart(sf) && node.getEnd() <= end);
1249
+ const uses = [];
1250
+ const collect = (node) => {
1251
+ if (ts.isIdentifier(node) && node.text === name && node !== declaration.name)
1252
+ uses.push(node);
1253
+ ts.forEachChild(node, collect);
1254
+ };
1255
+ collect(sf);
1256
+ if (uses.every(isFollowed))
1257
+ followed.push([declaration.initializer.getStart(sf), declaration.initializer.getEnd()]);
1258
+ }
713
1259
  const unfollowed = [...text.matchAll(new RegExp(SELF_LOCATION.source, "g"))].find((match) => !followed.some(([start, end]) => start <= match.index && match.index < end))?.[0];
714
1260
  let next = text;
715
1261
  for (const edit of edits.sort((a, b) => b.start - a.start))
@@ -719,7 +1265,7 @@ function rebaseOwnPaths(ts, from, to, text, locate) {
719
1265
  /** Rewrite one relative specifier from `from`'s new location to `target`'s new location, keeping the
720
1266
  * author's style: extension kept when written, dropped when not, `/index` collapsed when it was. */
721
1267
  function respecify(original, oldTarget, newFrom, newTarget) {
722
- const query = /[?#].*$/.exec(original)?.[0] ?? "";
1268
+ const query = original.slice(withoutQuery(original).length);
723
1269
  const clean = original.slice(0, original.length - query.length);
724
1270
  let target = newTarget;
725
1271
  const writtenExt = extname(clean);
@@ -749,7 +1295,7 @@ function rebase(specifier, from, newFrom) {
749
1295
  }
750
1296
  /** `specifier` re-pointed from a split route to its backend half, in the author's extension style. */
751
1297
  function backendSpecifier(specifier, route, backend, from) {
752
- const query = /[?#].*$/.exec(specifier)?.[0] ?? "";
1298
+ const query = specifier.slice(withoutQuery(specifier).length);
753
1299
  const written = extname(specifier.slice(0, specifier.length - query.length));
754
1300
  const stem = backend.slice(0, -extname(backend).length);
755
1301
  const target = written === ""
@@ -763,8 +1309,7 @@ function backendSpecifier(specifier, route, backend, from) {
763
1309
  /**
764
1310
  * Point an importer's named imports of a split route's moved exports (`loader`, `action`, ...) at the
765
1311
  * backend half, splitting a statement that also names what stayed. What cannot be rewritten (a
766
- * namespace or dynamic import that reads a moved name, `export *`, an alias with no target there) is
767
- * returned as an issue.
1312
+ * namespace or dynamic import that reads a moved name, `export *`) is returned as an issue.
768
1313
  */
769
1314
  function redirectMovedImports(ts, file, text, splitOf) {
770
1315
  const redirects = [];
@@ -799,10 +1344,6 @@ function redirectMovedImports(ts, file, text, splitOf) {
799
1344
  const moved = elements.filter(isMoved);
800
1345
  if (moved.length === 0)
801
1346
  return;
802
- if (split.specifier === undefined) {
803
- issues.push(`imports ${quoted(moved.map((el) => (el.propertyName ?? el.name).text))} from "${from}", but they moved to "${split.backend}" and no target of that alias covers it; point the import there by hand`);
804
- return;
805
- }
806
1347
  redirects.push({
807
1348
  names: moved.map((el) => (el.propertyName ?? el.name).text),
808
1349
  from,
@@ -832,11 +1373,25 @@ function redirectMovedImports(ts, file, text, splitOf) {
832
1373
  node.expression.kind === ts.SyntaxKind.ImportKeyword &&
833
1374
  node.arguments[0] !== undefined &&
834
1375
  ts.isStringLiteralLike(node.arguments[0])) {
835
- const from = node.arguments[0].text;
1376
+ const literal = node.arguments[0];
1377
+ const from = literal.text;
836
1378
  const split = splitOf(from);
837
1379
  const reads = split === undefined ? [] : mentioned(split, (name) => new RegExp(`\\b${name}\\b`));
838
- if (split !== undefined && reads.length > 0)
839
- issues.push(`loads "${from}" with import() and mentions ${quoted(reads)}, which moved to "${split.backend}"; load the backend half for them by hand`);
1380
+ if (split !== undefined && reads.length > 0) {
1381
+ const names = dynamicReads(ts, sf, node);
1382
+ if (names !== undefined &&
1383
+ names.length > 0 &&
1384
+ names.every((name) => split.moved.has(name))) {
1385
+ edits.push({
1386
+ start: literal.getStart(sf) + 1,
1387
+ end: literal.getEnd() - 1,
1388
+ text: split.specifier,
1389
+ });
1390
+ redirects.push({ names, from, to: split.specifier });
1391
+ }
1392
+ else
1393
+ issues.push(`loads "${from}" with import() and mentions ${quoted(reads)}, which moved to "${split.backend}"; load the backend half for them by hand`);
1394
+ }
840
1395
  }
841
1396
  ts.forEachChild(node, visit);
842
1397
  };
@@ -846,6 +1401,189 @@ function redirectMovedImports(ts, file, text, splitOf) {
846
1401
  out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
847
1402
  return { text: out, issues, redirects };
848
1403
  }
1404
+ /**
1405
+ * The exports code reads from what `import()` loads: off the awaited module (`(await import(x)).a`),
1406
+ * through a destructuring, or through a variable used only as `mod.a`. `undefined` when the module
1407
+ * goes anywhere else, so its reads cannot be listed.
1408
+ */
1409
+ function dynamicReads(ts, sf, call) {
1410
+ let node = call;
1411
+ if (!ts.isAwaitExpression(node.parent))
1412
+ return undefined;
1413
+ node = node.parent;
1414
+ while (ts.isParenthesizedExpression(node.parent))
1415
+ node = node.parent;
1416
+ const parent = node.parent;
1417
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === node)
1418
+ return [parent.name.text];
1419
+ if (!ts.isVariableDeclaration(parent) || parent.initializer !== node)
1420
+ return undefined;
1421
+ const binding = parent.name;
1422
+ if (ts.isObjectBindingPattern(binding)) {
1423
+ const names = [];
1424
+ for (const element of binding.elements) {
1425
+ const key = element.propertyName ?? element.name;
1426
+ if (element.dotDotDotToken !== undefined ||
1427
+ !(ts.isIdentifier(key) || ts.isStringLiteral(key)))
1428
+ return undefined;
1429
+ names.push(key.text);
1430
+ }
1431
+ return names;
1432
+ }
1433
+ if (!ts.isIdentifier(binding))
1434
+ return undefined;
1435
+ const names = new Set();
1436
+ let escapes = false;
1437
+ const visit = (current) => {
1438
+ if (ts.isIdentifier(current) && current.text === binding.text && current !== binding) {
1439
+ const owner = current.parent;
1440
+ if (ts.isPropertyAccessExpression(owner) && owner.expression === current)
1441
+ names.add(owner.name.text);
1442
+ else if (!((ts.isPropertyAccessExpression(owner) ||
1443
+ ts.isPropertyAssignment(owner) ||
1444
+ ts.isPropertyDeclaration(owner) ||
1445
+ ts.isMethodDeclaration(owner)) &&
1446
+ owner.name === current))
1447
+ escapes = true;
1448
+ }
1449
+ ts.forEachChild(current, visit);
1450
+ };
1451
+ visit(sf);
1452
+ return escapes ? undefined : [...names].sort(codeUnitOrder);
1453
+ }
1454
+ /** A `workspaces` glob as a matcher over package-relative folder paths. */
1455
+ function workspacePattern(glob) {
1456
+ const source = glob
1457
+ .replace(/^\.\//, "")
1458
+ .replace(/\/+$/, "")
1459
+ .split("/")
1460
+ .map((segment) => segment === "**"
1461
+ ? "(?:[^/]+/)*?[^/]*"
1462
+ : segment.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", "[^/]*"))
1463
+ .join("/");
1464
+ return new RegExp(`^${source}$`);
1465
+ }
1466
+ /**
1467
+ * The workspace an app belongs to: the nearest folder above it whose package.json declares
1468
+ * `workspaces` that include the app, and the package folders those globs (less any `!` exclusion)
1469
+ * name, other than the app and any folder that holds it. `undefined` outside one.
1470
+ */
1471
+ function workspaceSiblings(root) {
1472
+ for (let dir = dirname(root), depth = 0; depth < 8; dir = dirname(dir), depth += 1) {
1473
+ let declared;
1474
+ try {
1475
+ declared = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).workspaces;
1476
+ }
1477
+ catch {
1478
+ declared = undefined;
1479
+ }
1480
+ const listed = Array.isArray(declared)
1481
+ ? declared
1482
+ : typeof declared === "object" && declared !== null
1483
+ ? Reflect.get(declared, "packages")
1484
+ : undefined;
1485
+ if (Array.isArray(listed)) {
1486
+ const globs = listed.filter((glob) => typeof glob === "string");
1487
+ const include = globs.filter((glob) => !glob.startsWith("!")).map(workspacePattern);
1488
+ const exclude = globs
1489
+ .filter((glob) => glob.startsWith("!"))
1490
+ .map((glob) => workspacePattern(glob.slice(1)));
1491
+ const member = (rel) => include.some((pattern) => pattern.test(rel)) &&
1492
+ !exclude.some((pattern) => pattern.test(rel));
1493
+ // The nearest declaration decides, as package managers read it.
1494
+ if (!member(toPosix(relative(dir, root))))
1495
+ return undefined;
1496
+ const packages = [];
1497
+ const walk = (folder, depth) => {
1498
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
1499
+ if (!entry.isDirectory() || entry.name.startsWith(".") || SKIP_DIRS.has(entry.name))
1500
+ continue;
1501
+ const full = join(folder, entry.name);
1502
+ const rel = toPosix(relative(dir, full));
1503
+ if (exclude.some((pattern) => pattern.test(rel)))
1504
+ continue;
1505
+ if (member(rel) && existsSync(join(full, "package.json"))) {
1506
+ const inside = toPosix(relative(full, root));
1507
+ if (inside.startsWith("../") || isAbsolute(inside))
1508
+ packages.push(full);
1509
+ continue;
1510
+ }
1511
+ if (depth < 4)
1512
+ walk(full, depth + 1);
1513
+ }
1514
+ };
1515
+ walk(dir, 0);
1516
+ return packages.sort();
1517
+ }
1518
+ if (dirname(dir) === dir)
1519
+ return undefined;
1520
+ }
1521
+ return undefined;
1522
+ }
1523
+ /**
1524
+ * Where code in a workspace sibling names an app file that moves: a relative import into the app, or
1525
+ * the file's path in a string or command (`bun -e 'import("./src/x.ts")'` with the app as its working
1526
+ * directory). Only files that mention the app's folder or package name are read further, and a path
1527
+ * the sibling's own package holds is its own file. Every line that names a path is listed, each marked
1528
+ * when it lies only in a comment. Report-only: the migration never edits a sibling.
1529
+ */
1530
+ function siblingReferences(ts, root, pkg, file, text, moves, known, ownName) {
1531
+ const abs = join(pkg, file);
1532
+ // A process started in the app (`cwd: \`${repo}apps/web\``) reads its paths from the app root.
1533
+ const runsInApp = new RegExp(`\\bcwd\\s*:[^,\\n]*\\b${escapeRegExp(posix.basename(toPosix(root)))}\\b`).test(text);
1534
+ const comments = /\.[cm]?[jt]sx?$/.test(file) ? triviaCommentRanges(ts, file, text) : [];
1535
+ const found = new Map();
1536
+ const report = (from, index, length) => {
1537
+ const to = moves.get(from);
1538
+ if (to === undefined)
1539
+ return;
1540
+ const entry = found.get(from) ?? { to, lines: new Set(), commentLines: new Set() };
1541
+ found.set(from, entry);
1542
+ const line = text.slice(0, index).split("\n").length;
1543
+ const inComment = comments.some(([start, end]) => start <= index && index + length <= end);
1544
+ (inComment ? entry.commentLines : entry.lines).add(line);
1545
+ };
1546
+ if (/\.(?:[cm]?[jt]sx?)$/.test(file)) {
1547
+ for (const { specifier } of importsOf(ts, file, text)) {
1548
+ const clean = withoutQuery(specifier);
1549
+ const inApp = clean.startsWith(".")
1550
+ ? toPosix(relative(root, resolve(dirname(abs), clean)))
1551
+ : ownName !== undefined && clean.startsWith(`${ownName}/`)
1552
+ ? clean.slice(ownName.length + 1)
1553
+ : undefined;
1554
+ if (inApp === undefined || inApp.startsWith("../") || isAbsolute(inApp))
1555
+ continue;
1556
+ const target = resolveIn(known, "index.ts", `./${inApp}`);
1557
+ if (target !== undefined)
1558
+ report(target, text.indexOf(specifier), specifier.length);
1559
+ }
1560
+ }
1561
+ for (const from of moves.keys()) {
1562
+ const stem = SOURCE_FILE.test(from)
1563
+ ? from.slice(0, from.length - extname(from).length)
1564
+ : undefined;
1565
+ const pattern = new RegExp(`(?<![\\w.-])(?:\\./)?(?:${escapeRegExp(from)}(?![\\w])${stem === undefined ? "" : `|${escapeRegExp(stem)}(?=["'\`])`})`, "g");
1566
+ for (const match of text.matchAll(pattern)) {
1567
+ // `packages/x/src/a.ts` names another package's `src/a.ts`; only a prefix that reaches the
1568
+ // app counts, and a path the sibling holds itself is its own.
1569
+ const prefix = /(?:[\w.@-]+\/)+$/.exec(text.slice(0, match.index))?.[0] ?? "";
1570
+ const bases = prefix === "" ? [] : [dirname(abs), pkg, dirname(pkg), dirname(dirname(pkg))];
1571
+ if (prefix !== "" && !bases.some((base) => resolve(base, prefix) === root))
1572
+ continue;
1573
+ const own = existsSync(join(pkg, from)) || existsSync(join(dirname(abs), from));
1574
+ if (prefix === "" && own && !runsInApp)
1575
+ continue;
1576
+ report(from, match.index, match[0].length);
1577
+ }
1578
+ }
1579
+ const byNumber = (a, b) => a - b;
1580
+ return [...found].map(([from, { to, lines, commentLines }]) => ({
1581
+ from,
1582
+ to,
1583
+ lines: [...lines].sort(byNumber),
1584
+ commentLines: [...commentLines].filter((line) => !lines.has(line)).sort(byNumber),
1585
+ }));
1586
+ }
849
1587
  /** The package folder an app without its own package.json sits in (`--dir src`), at most two levels
850
1588
  * up and never a workspace root, so the scan beside it stays inside one package. */
851
1589
  function enclosingPackage(root) {
@@ -991,7 +1729,7 @@ function renameRetiredTypes(ts, file, text) {
991
1729
  /** The config files the loader reads, old layout included; a path field may live in any of them. */
992
1730
  const CONFIG_FILES = ["nifra.config.ts", "framework.ts", "backend/framework.ts"];
993
1731
  /**
994
- * The module paths a config exports as string literals: `clientModule` and the component pipeline's
1732
+ * The module paths a config exports, read statically: `clientModule` and the component pipeline's
995
1733
  * `entries`. The browser loads `clientModule` and `entries.client`; `ssr` and `rsc` run on the server.
996
1734
  */
997
1735
  function configEntries(ts, file, text) {
@@ -1005,18 +1743,12 @@ function configEntries(ts, file, text) {
1005
1743
  current = current.expression;
1006
1744
  return current;
1007
1745
  };
1746
+ const read = configPathReader(ts, sf);
1008
1747
  const out = [];
1009
1748
  const literal = (field, role, node) => {
1010
- const value = bare(node);
1011
- if (value === undefined || !ts.isStringLiteralLike(value))
1012
- return;
1013
- out.push({
1014
- field,
1015
- role,
1016
- value: value.text,
1017
- start: value.getStart(sf) + 1,
1018
- end: value.getEnd() - 1,
1019
- });
1749
+ const path = read(node);
1750
+ if (path !== undefined)
1751
+ out.push({ ...path, field, role });
1020
1752
  };
1021
1753
  for (const statement of sf.statements) {
1022
1754
  if (!ts.isVariableStatement(statement) ||
@@ -1147,13 +1879,18 @@ export async function migrateLayout(appRoot, options = {}) {
1147
1879
  continue;
1148
1880
  const backendFile = file.replace(ROUTE_FILE, ".backend.ts");
1149
1881
  const specifier = `./${posix.basename(backendFile)}`;
1882
+ const sharedFile = file.replace(ROUTE_FILE, ".shared.ts");
1883
+ // A taken name leaves data both halves read copied into each, as reported.
1884
+ const splitOptions = next.has(sharedFile) || existsSync(join(root, sharedFile))
1885
+ ? {}
1886
+ : { sharedFile: posix.basename(sharedFile) };
1150
1887
  let result;
1151
1888
  if (/\.(?:svelte|vue)$/.test(file)) {
1152
1889
  const blocks = scriptBlocks(text);
1153
1890
  const block = blocks.find((b) => b.module) ?? blocks.find((b) => !b.setup && file.endsWith(".vue"));
1154
1891
  if (block === undefined)
1155
1892
  continue;
1156
- const inner = splitRouteSource(ts, text.slice(block.start, block.end), "block.ts", specifier);
1893
+ const inner = splitRouteSource(ts, text.slice(block.start, block.end), "block.ts", specifier, splitOptions);
1157
1894
  result = {
1158
1895
  ...inner,
1159
1896
  frontend: `${text.slice(0, block.start)}\n${inner.frontend}${text.slice(block.end)}`,
@@ -1169,13 +1906,18 @@ export async function migrateLayout(appRoot, options = {}) {
1169
1906
  continue;
1170
1907
  }
1171
1908
  else {
1172
- result = splitRouteSource(ts, text, file, specifier);
1909
+ result = splitRouteSource(ts, text, file, specifier, splitOptions);
1173
1910
  }
1174
1911
  if (result.backend === undefined)
1175
1912
  continue;
1176
1913
  next.set(file, result.frontend);
1177
1914
  backendHalves.set(backendFile, mergeModules(ts, backendHalves.get(backendFile) ?? "", result.backend));
1178
- splits.push({ file, backend: backendFile, moved: [...result.moved] });
1915
+ if (result.shared === undefined)
1916
+ splits.push({ file, backend: backendFile, moved: [...result.moved] });
1917
+ else {
1918
+ next.set(sharedFile, result.shared);
1919
+ splits.push({ file, backend: backendFile, moved: [...result.moved], shared: sharedFile });
1920
+ }
1179
1921
  for (const reason of result.issues)
1180
1922
  issues.push({ file, reason });
1181
1923
  }
@@ -1189,7 +1931,11 @@ export async function migrateLayout(appRoot, options = {}) {
1189
1931
  moveMap.set(from, to);
1190
1932
  // Assets (images, fonts) resolve too, so they move with the modules that import them.
1191
1933
  const known = new Set([...next.keys(), ...everyFile]);
1192
- const resolver = createSpecifierResolver();
1934
+ const knownPaths = new Set([...known].map((file) => join(root, file)));
1935
+ // Route halves the split creates resolve before they are written.
1936
+ const resolver = createSpecifierResolver({
1937
+ moduleExists: (path) => knownPaths.has(path) || isFile(path),
1938
+ });
1193
1939
  const realRoot = (() => {
1194
1940
  try {
1195
1941
  return realpathSync(root);
@@ -1198,16 +1944,24 @@ export async function migrateLayout(appRoot, options = {}) {
1198
1944
  return root;
1199
1945
  }
1200
1946
  })();
1947
+ /** An app file as the migration names it, from a path the resolver found (real, or as planned). */
1948
+ const appFile = (path) => {
1949
+ if (path === undefined)
1950
+ return undefined;
1951
+ for (const base of [realRoot, root]) {
1952
+ const rel = toPosix(relative(base, path));
1953
+ if (!rel.startsWith("../") && !isAbsolute(rel))
1954
+ return rel;
1955
+ }
1956
+ return undefined;
1957
+ };
1201
1958
  /** A non-relative specifier the app's tsconfig `paths`/`baseUrl` or package.json `imports` maps to
1202
- * one of its files, read from disk as the bundler reads it. */
1959
+ * one of its files, as the bundler reads it. */
1203
1960
  const viaAlias = (file, specifier) => {
1204
1961
  if (specifier.startsWith(".") || isAbsolute(specifier))
1205
1962
  return undefined;
1206
- const found = resolver(join(root, file), specifier);
1207
- if (found === undefined)
1208
- return undefined;
1209
- const rel = toPosix(relative(realRoot, found));
1210
- return rel.startsWith("../") || isAbsolute(rel) || !known.has(rel) ? undefined : rel;
1963
+ const rel = appFile(resolver(join(root, file), withoutQuery(specifier)));
1964
+ return rel === undefined || !known.has(rel) ? undefined : rel;
1211
1965
  };
1212
1966
  const resolveAny = (file, specifier) => resolveIn(known, file, specifier) ?? viaAlias(file, specifier);
1213
1967
  const ownName = (() => {
@@ -1225,7 +1979,7 @@ export async function migrateLayout(appRoot, options = {}) {
1225
1979
  const external = (specifier) => {
1226
1980
  if (/^[a-z][a-z\d+.-]*:/i.test(specifier) || specifier === "bun")
1227
1981
  return true;
1228
- const name = packageName(specifier.replace(/[?#].*$/, ""));
1982
+ const name = packageName(withoutQuery(specifier));
1229
1983
  if (builtinModules.includes(name) || name === ownName)
1230
1984
  return true;
1231
1985
  let found = installed.get(name);
@@ -1258,9 +2012,10 @@ export async function migrateLayout(appRoot, options = {}) {
1258
2012
  if (route === undefined || split === undefined)
1259
2013
  return undefined;
1260
2014
  const inBase = (path) => toPosix(relative(base, join(root, path)));
2015
+ const relativePath = backendSpecifier(specifier, inBase(route), inBase(split.backend), file);
1261
2016
  const respelled = specifier.startsWith(".")
1262
- ? backendSpecifier(specifier, inBase(route), inBase(split.backend), file)
1263
- : resolver.respell(join(base, file), specifier, join(root, split.backend));
2017
+ ? relativePath
2018
+ : (resolver.respell(join(base, file), specifier, join(root, split.backend)) ?? relativePath);
1264
2019
  return { backend: split.backend, moved: split.moved, specifier: respelled };
1265
2020
  };
1266
2021
  const redirectedFiles = new Set();
@@ -1302,21 +2057,39 @@ export async function migrateLayout(appRoot, options = {}) {
1302
2057
  });
1303
2058
  }
1304
2059
  }
2060
+ // What a glob loads is imported too: the files it matches go where the module that loads them goes.
2061
+ for (const call of globCalls(ts, file, text)) {
2062
+ const targets = call.literal
2063
+ ? globTargets(file, call.patterns.map((pattern) => pattern.text), known)
2064
+ : undefined;
2065
+ if (targets === undefined) {
2066
+ issues.push({
2067
+ file,
2068
+ reason: `the import.meta.glob on line ${call.line} takes a pattern the migration cannot read (computed, or not starting with ./, ../ or /), so the files it loads stay where they are; check it by hand`,
2069
+ });
2070
+ continue;
2071
+ }
2072
+ for (const target of targets)
2073
+ refs.push({ target, typeOnly: false });
2074
+ }
1305
2075
  edges.set(file, refs);
1306
2076
  }
1307
2077
  // The config's module paths are entries too: the browser loads `clientModule`.
1308
2078
  const entries = CONFIG_FILES.filter((file) => next.has(file)).flatMap((file) => configEntries(ts, file, next.get(file) ?? "").map((entry) => ({
1309
2079
  ...entry,
1310
2080
  file,
1311
- // Relative to the app root, as the loader reads it, whichever config file holds it.
1312
- target: resolveAny("nifra.config.ts", entry.value),
2081
+ // A string is read from the app root, whichever config file holds it; a joined path from the
2082
+ // config's own folder.
2083
+ target: entry.base === "app"
2084
+ ? resolveAny("nifra.config.ts", entry.path)
2085
+ : resolveIn(known, file, entry.path.startsWith("../") ? entry.path : `./${entry.path}`),
1313
2086
  })));
1314
2087
  const entryTargets = (role) => new Set(entries.flatMap((entry) => entry.role === role && entry.target !== undefined ? [entry.target] : []));
1315
2088
  const browserEntries = entryTargets("frontend");
1316
2089
  const serverEntries = entryTargets("backend");
1317
2090
  const files = [...new Set([...next.keys(), ...everyFile.filter((f) => !original.has(f))])];
1318
2091
  const frontendRoots = [
1319
- ...files.filter((f) => f.startsWith("routes/") && ROUTE_FILE.test(f) && !f.includes(".backend.")),
2092
+ ...files.filter((f) => f.startsWith("routes/") && ROUTE_FILE.test(f) && !f.includes(".backend.") && !isTestFile(f)),
1320
2093
  ...browserEntries,
1321
2094
  ];
1322
2095
  // A route page the server imports - a generated `server-manifest.ts` imports them all - is rendered
@@ -1369,6 +2142,8 @@ export async function migrateLayout(appRoot, options = {}) {
1369
2142
  });
1370
2143
  }
1371
2144
  }
2145
+ /** With `zones`, the files that stay where they are and the side package.json gives them. */
2146
+ const inPlace = new Map();
1372
2147
  const zoneOf = (file) => browser.has(file) && server.has(file) ? "shared" : browser.has(file) ? "frontend" : "backend";
1373
2148
  for (const file of api ? [] : files) {
1374
2149
  if (moveMap.has(file) ||
@@ -1387,6 +2162,10 @@ export async function migrateLayout(appRoot, options = {}) {
1387
2162
  else if (!browser.has(file) && !appServer.has(file))
1388
2163
  continue;
1389
2164
  const zone = zoneOf(file);
2165
+ if (DATA_FILE.test(file) && options.zones === true) {
2166
+ inPlace.set(file, zone);
2167
+ continue;
2168
+ }
1390
2169
  if (DATA_FILE.test(file)) {
1391
2170
  const folder = file.includes("/") ? posix.dirname(file) : undefined;
1392
2171
  issues.push({
@@ -1397,6 +2176,52 @@ export async function migrateLayout(appRoot, options = {}) {
1397
2176
  }
1398
2177
  moveMap.set(file, `${zone}/${file}`);
1399
2178
  }
2179
+ // A folder whose reached files all move into one zone takes its other files along: a file nothing
2180
+ // imports at runtime (a component not used yet, an asset) has no zone of its own, and leaving it
2181
+ // behind splits the folder for every tool that lists it. Server built-ins never go to the browser.
2182
+ const zonesUnder = new Map();
2183
+ for (const [from, to] of moveMap) {
2184
+ if (isTestFile(from))
2185
+ continue;
2186
+ for (let dir = posix.dirname(from); dir !== "."; dir = posix.dirname(dir)) {
2187
+ zonesUnder.set(dir, (zonesUnder.get(dir) ?? new Set()).add(to.split("/")[0] ?? ""));
2188
+ }
2189
+ }
2190
+ for (const file of api ? [] : files) {
2191
+ if (moveMap.has(file) || browser.has(file) || server.has(file))
2192
+ continue;
2193
+ if (ZONE_DIRS.has(file.split("/")[0] ?? "") || inConfiguredFolder(file))
2194
+ continue;
2195
+ // A test and its snapshot follow their subject below.
2196
+ if (isTestFile(file) ||
2197
+ file.endsWith(".snap") ||
2198
+ file.endsWith(".d.ts") ||
2199
+ DATA_FILE.test(file))
2200
+ continue;
2201
+ let zones;
2202
+ for (let dir = posix.dirname(file); dir !== "." && zones === undefined; dir = posix.dirname(dir)) {
2203
+ // A nested package is its own install, never part of the app's folder.
2204
+ if (existsSync(join(root, dir, "package.json")))
2205
+ break;
2206
+ zones = zonesUnder.get(dir);
2207
+ }
2208
+ const [zone] = zones?.size === 1 ? zones : [];
2209
+ if (zone === undefined)
2210
+ continue;
2211
+ if (zone !== "backend" && /from\s+["'](?:node:|bun:)/.test(next.get(file) ?? ""))
2212
+ continue;
2213
+ moveMap.set(file, `${zone}/${file}`);
2214
+ }
2215
+ if (options.zones === true) {
2216
+ for (const [from, to] of moveMap) {
2217
+ const side = FOLDER_SIDES.find((side) => to === `${side}/${from}`);
2218
+ if (side === undefined)
2219
+ continue;
2220
+ inPlace.set(from, side);
2221
+ moveMap.delete(from);
2222
+ }
2223
+ }
2224
+ const declared = zoneDeclarations(inPlace, files, (file) => next.get(file), inConfiguredFolder);
1400
2225
  const claimed = new Map();
1401
2226
  for (const [from, to] of moveMap) {
1402
2227
  const holder = claimed.get(to) ?? (known.has(to) && !moveMap.has(to) ? to : undefined);
@@ -1410,32 +2235,111 @@ export async function migrateLayout(appRoot, options = {}) {
1410
2235
  });
1411
2236
  moveMap.delete(from);
1412
2237
  }
1413
- for (const [from, to] of moveMap) {
1414
- if (to.startsWith("shared/") && /from\s+["'](?:node:|bun:)/.test(next.get(from) ?? "")) {
2238
+ const newPath = (file) => moveMap.get(file) ?? file;
2239
+ // A test beside its subject (`x.test.ts` by `x.ts`, or in a `__tests__/` under its folder) moves
2240
+ // with it, snapshots included, once the subject's place is settled; a test never decides a zone.
2241
+ const present = new Set(files);
2242
+ for (const test of files) {
2243
+ const stem = /^(.+?)\.(?:test|spec)\.[cm]?[jt]sx?$/.exec(posix.basename(test))?.[1];
2244
+ if (stem === undefined || moveMap.has(test) || !next.has(test))
2245
+ continue;
2246
+ const dir = posix.dirname(test);
2247
+ const nested = posix.basename(dir) === "__tests__";
2248
+ const home = nested ? posix.dirname(dir) : dir;
2249
+ const subjects = SUBJECT_EXTENSIONS.map((ext) => posix.join(home, `${stem}${ext}`)).filter((file) => present.has(file) && !isTestFile(file));
2250
+ const subject = subjects.find((file) => moveMap.has(file));
2251
+ if (subject === undefined)
2252
+ continue;
2253
+ if (new Set(subjects.map((file) => posix.dirname(newPath(file)))).size > 1) {
2254
+ issues.push({
2255
+ file: test,
2256
+ reason: `tests ${subjects.map((file) => `"${file}"`).join(" and ")}, which end up in different folders, so it stays here; move it by hand`,
2257
+ });
2258
+ continue;
2259
+ }
2260
+ const to = posix.join(posix.dirname(newPath(subject)), nested ? "__tests__" : "", posix.basename(test));
2261
+ const pairs = [[test, to]];
2262
+ const snapshot = posix.join(dir, "__snapshots__", `${posix.basename(test)}.snap`);
2263
+ if (present.has(snapshot))
2264
+ pairs.push([
2265
+ snapshot,
2266
+ posix.join(posix.dirname(to), "__snapshots__", posix.basename(snapshot)),
2267
+ ]);
2268
+ const taken = pairs.find(([, to]) => claimed.has(to) || (known.has(to) && !moveMap.has(to)));
2269
+ if (taken !== undefined) {
2270
+ issues.push({
2271
+ file: test,
2272
+ reason: `would follow "${subject}" to "${taken[1]}", which already exists or another file moves to; move it by hand`,
2273
+ });
2274
+ continue;
2275
+ }
2276
+ for (const [from, to] of pairs) {
2277
+ moveMap.set(from, to);
2278
+ claimed.set(to, from);
2279
+ }
2280
+ }
2281
+ for (const [from, to] of [
2282
+ ...moveMap,
2283
+ ...[...inPlace].map(([file, side]) => [file, side]),
2284
+ ]) {
2285
+ // A test is never bundled, so its own server imports decide nothing.
2286
+ if (isTestFile(from))
2287
+ continue;
2288
+ if ((to === "shared" || to.startsWith("shared/")) &&
2289
+ /from\s+["'](?:node:|bun:)/.test(next.get(from) ?? "")) {
1415
2290
  issues.push({
1416
2291
  file: from,
1417
- reason: `both halves import it at runtime, but it uses a server built-in; split it before moving to ${to}`,
2292
+ reason: `both halves import it at runtime, but it uses a server built-in; split it before ${to === "shared" ? "zoning it shared" : `moving to ${to}`}`,
1418
2293
  });
1419
2294
  }
1420
2295
  }
1421
2296
  // 5. Rewrite imports to the new locations.
1422
- const newPath = (file) => moveMap.get(file) ?? file;
1423
2297
  const final = new Map();
1424
2298
  const rewritten = [];
1425
- const unspelled = new Set();
1426
- /** An alias for a target that moves, through the same alias, or an issue when none covers it. */
1427
- const respellAlias = (file, specifier, target) => {
1428
- if (newPath(target) === target)
2299
+ // The app as the migration leaves it, where every rewritten specifier must reach its target.
2300
+ const planned = new Set([...known].filter((file) => next.has(file) || !original.has(file)).map(newPath));
2301
+ const plannedResolver = createSpecifierResolver({
2302
+ moduleExists: (path) => {
2303
+ const file = appFile(path);
2304
+ if (file !== undefined && (planned.has(file) || known.has(file)))
2305
+ return planned.has(file);
2306
+ return isFile(path);
2307
+ },
2308
+ });
2309
+ /** Whether `specifier`, written in `from` after the moves, loads `target` there. */
2310
+ const reaches = (from, specifier, target) => specifier.startsWith(".")
2311
+ ? resolveIn(planned, from, specifier) === target
2312
+ : appFile(plannedResolver(join(root, from), withoutQuery(specifier))) === target;
2313
+ const unreached = new Set();
2314
+ const unreachable = (file, specifier, target, from) => {
2315
+ if (unreached.has(`${file}\0${specifier}`))
2316
+ return;
2317
+ unreached.add(`${file}\0${specifier}`);
2318
+ issues.push({
2319
+ file,
2320
+ reason: `"${specifier}" names "${target}", which moves to "${newPath(target)}", and no specifier the migration can write from "${from}" reaches it there; point it there by hand`,
2321
+ });
2322
+ };
2323
+ /**
2324
+ * How `from` names `target` after the moves, for the alias `specifier` that `file` writes: as written
2325
+ * while it still reaches it, through the same alias when one of its targets covers the new place,
2326
+ * else as a relative path. `undefined` leaves it as written.
2327
+ */
2328
+ const aliasTo = (file, specifier, target, from = newPath(file)) => {
2329
+ const to = newPath(target);
2330
+ if (to === target && from === file)
1429
2331
  return undefined;
1430
- const respelled = resolver.respell(join(root, file), specifier, join(root, newPath(target)));
1431
- if (respelled === undefined && !unspelled.has(`${file}\0${specifier}`)) {
1432
- unspelled.add(`${file}\0${specifier}`);
1433
- issues.push({
1434
- file,
1435
- reason: `the path alias "${specifier}" names "${target}", which moves to "${newPath(target)}", and no target of that alias covers the new location; point it there by hand`,
1436
- });
1437
- }
1438
- return respelled;
2332
+ const written = withoutQuery(specifier);
2333
+ if (reaches(from, written, to))
2334
+ return undefined;
2335
+ const respelled = resolver.respell(join(root, file), written, join(root, to));
2336
+ if (respelled !== undefined && reaches(from, respelled, to))
2337
+ return `${respelled}${specifier.slice(written.length)}`;
2338
+ const relativePath = respecify(specifier, target, from, to);
2339
+ if (reaches(from, relativePath, to))
2340
+ return relativePath;
2341
+ unreachable(file, specifier, target, from);
2342
+ return undefined;
1439
2343
  };
1440
2344
  for (const [file, text] of next) {
1441
2345
  const imports = rewriteImports(ts, file, text, (specifier) => {
@@ -1447,10 +2351,13 @@ export async function migrateLayout(appRoot, options = {}) {
1447
2351
  if (target === undefined)
1448
2352
  return rebase(specifier, file, newPath(file));
1449
2353
  if (!specifier.startsWith("."))
1450
- return respellAlias(file, specifier, target);
2354
+ return aliasTo(file, specifier, target);
1451
2355
  if (newPath(target) === target && newPath(file) === file)
1452
2356
  return undefined;
1453
- return respecify(specifier, target, newPath(file), newPath(target));
2357
+ const relativePath = respecify(specifier, target, newPath(file), newPath(target));
2358
+ if (!reaches(newPath(file), relativePath, newPath(target)))
2359
+ unreachable(file, specifier, target, newPath(file));
2360
+ return relativePath;
1454
2361
  });
1455
2362
  const updated = renameRetiredTypes(ts, file, imports);
1456
2363
  final.set(newPath(file), updated);
@@ -1458,7 +2365,54 @@ export async function migrateLayout(appRoot, options = {}) {
1458
2365
  (redirectedFiles.has(file) || (updated !== text && original.get(file) === text)))
1459
2366
  rewritten.push(file);
1460
2367
  }
1461
- // A config path names its module from the app root, so it follows the module, never the config file.
2368
+ // A glob names its files by pattern, which no import rewrite reads: each one must still load, from
2369
+ // the module's new folder, the files it loaded before. A pattern whose matches moved together
2370
+ // into one folder is re-pointed at it; any other change is reported.
2371
+ for (const file of next.keys()) {
2372
+ const at = newPath(file);
2373
+ const text = final.get(at);
2374
+ if (text === undefined)
2375
+ continue;
2376
+ const edits = [];
2377
+ for (const call of globCalls(ts, at, text)) {
2378
+ if (!call.literal)
2379
+ continue;
2380
+ const written = call.patterns.map((pattern) => pattern.text);
2381
+ const before = globTargets(file, written, known);
2382
+ if (before === undefined || before.length === 0)
2383
+ continue;
2384
+ const expected = before.map(newPath).sort(codeUnitOrder);
2385
+ const same = (patterns) => {
2386
+ const after = globTargets(at, patterns, planned)?.sort(codeUnitOrder);
2387
+ return after !== undefined && after.join("\n") === expected.join("\n");
2388
+ };
2389
+ if (same(written))
2390
+ continue;
2391
+ const repointed = written.map((pattern) => repointGlob(file, at, pattern, before, newPath));
2392
+ if (repointed.every((pattern) => pattern !== undefined) && same(repointed)) {
2393
+ call.patterns.forEach((pattern, index) => {
2394
+ const value = repointed[index];
2395
+ if (value !== undefined && value !== pattern.text)
2396
+ edits.push({ start: pattern.start, end: pattern.end, text: value });
2397
+ });
2398
+ continue;
2399
+ }
2400
+ issues.push({
2401
+ file: at,
2402
+ reason: `the import.meta.glob on line ${call.line} loaded ${before.length} file(s) such as "${before[0]}", which do not stay together under one folder after the moves, so its pattern cannot follow them; move them together or point the pattern at them by hand`,
2403
+ });
2404
+ }
2405
+ if (edits.length === 0)
2406
+ continue;
2407
+ let updated = text;
2408
+ for (const edit of edits.sort((a, b) => b.start - a.start))
2409
+ updated = updated.slice(0, edit.start) + edit.text + updated.slice(edit.end);
2410
+ final.set(at, updated);
2411
+ if (!moveMap.has(file) && !rewritten.includes(file))
2412
+ rewritten.push(file);
2413
+ }
2414
+ // A config string names its module from the app root, so it follows the module, never the config
2415
+ // file; a path joined onto the config's folder is re-pointed with the module's own paths below.
1462
2416
  for (const configFile of CONFIG_FILES) {
1463
2417
  const at = newPath(configFile);
1464
2418
  const text = final.get(at);
@@ -1466,14 +2420,16 @@ export async function migrateLayout(appRoot, options = {}) {
1466
2420
  continue;
1467
2421
  const edits = [];
1468
2422
  for (const entry of configEntries(ts, at, text)) {
1469
- const target = resolveAny("nifra.config.ts", entry.value);
2423
+ if (entry.span === undefined)
2424
+ continue;
2425
+ const target = resolveAny("nifra.config.ts", entry.path);
1470
2426
  if (target === undefined || newPath(target) === target)
1471
2427
  continue;
1472
- const value = entry.value.startsWith(".")
1473
- ? respecify(entry.value, target, "nifra.config.ts", newPath(target))
1474
- : respellAlias(configFile, entry.value, target);
2428
+ const value = entry.path.startsWith(".")
2429
+ ? respecify(entry.path, target, "nifra.config.ts", newPath(target))
2430
+ : aliasTo(configFile, entry.path, target, "nifra.config.ts");
1475
2431
  if (value !== undefined)
1476
- edits.push({ start: entry.start, end: entry.end, text: value });
2432
+ edits.push({ start: entry.span[0], end: entry.span[1], text: value });
1477
2433
  }
1478
2434
  if (edits.length === 0)
1479
2435
  continue;
@@ -1490,7 +2446,18 @@ export async function migrateLayout(appRoot, options = {}) {
1490
2446
  // A moved module's paths from its own location now start from its new folder: re-point the ones it
1491
2447
  // spells out, and report the first one it cannot follow.
1492
2448
  const unfollowed = new Map();
2449
+ /** Moved shell scripts whose own-folder paths were re-pointed: new path -> text. */
2450
+ const scriptWrites = new Map();
1493
2451
  for (const { from, to } of moves) {
2452
+ if (SHELL_FILE.test(to) && !original.has(from)) {
2453
+ const script = readFileSync(join(root, from), "utf8");
2454
+ const result = rebaseShellPaths(from, to, script, (target) => known.has(target) ? newPath(target) : target);
2455
+ if (result.text !== script)
2456
+ scriptWrites.set(to, result.text);
2457
+ if (result.unfollowed !== undefined)
2458
+ unfollowed.set(to, result.unfollowed);
2459
+ continue;
2460
+ }
1494
2461
  const text = final.get(to);
1495
2462
  if (text === undefined || !SELF_LOCATION.test(text))
1496
2463
  continue;
@@ -1503,25 +2470,59 @@ export async function migrateLayout(appRoot, options = {}) {
1503
2470
  if (result.unfollowed !== undefined)
1504
2471
  unfollowed.set(to, result.unfollowed);
1505
2472
  }
2473
+ // A module that stays still names files from its own folder (a config's `clientModule` joined onto
2474
+ // `import.meta.dir`): each that moved is re-pointed.
2475
+ const landed = new Set(moveMap.values());
2476
+ for (const [file, text] of final) {
2477
+ if (landed.has(file) || !/\.[cm]?[jt]sx?$/.test(file) || !SELF_LOCATION.test(text))
2478
+ continue;
2479
+ const result = rebaseOwnPaths(ts, file, file, text, (target) => known.has(target) ? newPath(target) : target);
2480
+ if (result.text === text)
2481
+ continue;
2482
+ final.set(file, result.text);
2483
+ if (original.has(file) && !rewritten.includes(file))
2484
+ rewritten.push(file);
2485
+ }
1506
2486
  // A path in a string or comment is not an import, so nothing above rewrote it: a build script that
1507
2487
  // writes `data/x.json` would keep writing to the old place, and so would a deploy script or
1508
2488
  // `package.json` beside the code.
1509
2489
  const settled = new Set([...known].map(newPath));
2490
+ // A new backend half starts where its route was, so it keeps that route's place in each program.
2491
+ const splitFrom = new Map(splits
2492
+ .filter((split) => !original.has(split.backend))
2493
+ .map((split) => [split.backend, split.file]));
2494
+ const layout = [...known]
2495
+ .filter((file) => next.has(file) || !original.has(file))
2496
+ .map((file) => ({ from: splitFrom.get(file) ?? file, to: newPath(file) }));
2497
+ const tsconfigs = followTsconfigs(ts, root, moveMap, layout);
2498
+ // The app's own package.json names files from the app root: its scripts and entry fields follow.
2499
+ const manifestPath = join(root, "package.json");
2500
+ const manifest = existsSync(manifestPath)
2501
+ ? rewritePackagePaths(ts, readFileSync(manifestPath, "utf8"), moveMap)
2502
+ : undefined;
1510
2503
  const scanned = [...final];
1511
2504
  for (const file of everyFile) {
1512
2505
  if (!original.has(file) &&
1513
2506
  TOOLING_FILE.test(file) &&
1514
2507
  statSync(join(root, file)).size <= 256_000)
1515
- scanned.push([newPath(file), readFileSync(join(root, file), "utf8")]);
2508
+ scanned.push([
2509
+ newPath(file),
2510
+ (file === "package.json" ? manifest?.text : undefined) ??
2511
+ tsconfigs.files.get(file)?.text ??
2512
+ readFileSync(join(root, file), "utf8"),
2513
+ ]);
1516
2514
  }
2515
+ // A mention only in comments is worth updating, not a decision: it never changes what runs.
2516
+ const commentFollowUps = [];
1517
2517
  for (const [file, text] of scanned) {
1518
2518
  let live;
2519
+ let comments;
1519
2520
  for (const [from, to] of moveMap) {
1520
2521
  // `shared/lib/x.ts` contains `lib/x.ts`; that is the new path, not a stale one.
1521
2522
  const newPrefix = to.endsWith(from) ? to.slice(0, to.length - from.length) : undefined;
1522
2523
  const stale = [
1523
2524
  ...text.matchAll(new RegExp(`(?<![\\w.-])${escapeRegExp(from)}(?![\\w])`, "g")),
1524
- ].some((match) => {
2525
+ ].filter((match) => {
1525
2526
  if (newPrefix !== undefined && text.slice(0, match.index).endsWith(newPrefix))
1526
2527
  return false;
1527
2528
  // An import that resolves after the moves is current, even when it still reads like the old
@@ -1530,7 +2531,13 @@ export async function migrateLayout(appRoot, options = {}) {
1530
2531
  const end = match.index + from.length;
1531
2532
  return !live.some(([start, stop]) => start <= match.index && end <= stop);
1532
2533
  });
1533
- if (stale)
2534
+ if (stale.length === 0)
2535
+ continue;
2536
+ comments ??= /\.[cm]?[jt]sx?$/.test(file) ? triviaCommentRanges(ts, file, text) : [];
2537
+ const inComments = stale.every((match) => comments?.some(([start, stop]) => start <= match.index && match.index + from.length <= stop));
2538
+ if (inComments)
2539
+ commentFollowUps.push({ file, reason: `a comment names "${from}", which moved to "${to}"` });
2540
+ else
1534
2541
  issues.push({ file, reason: `mentions "${from}" by path; it moved to "${to}"` });
1535
2542
  }
1536
2543
  }
@@ -1567,6 +2574,36 @@ export async function migrateLayout(appRoot, options = {}) {
1567
2574
  issues.push({ file: at, reason });
1568
2575
  }
1569
2576
  }
2577
+ // A workspace sibling is not the migration's to edit either: each file that names a moved app file,
2578
+ // by import or by path, is reported with the line and both paths.
2579
+ const appName = posix.basename(toPosix(root));
2580
+ const mentionsApp = new RegExp(`(?:^|[/'"\`])${escapeRegExp(appName)}(?:[/'"\`]|$)`, "m");
2581
+ for (const sibling of moveMap.size === 0 ? [] : (workspaceSiblings(root) ?? [])) {
2582
+ for (const file of listFiles(sibling)) {
2583
+ if (!/\.[cm]?[jt]sx?$/.test(file) && !TOOLING_FILE.test(file))
2584
+ continue;
2585
+ if (statSync(join(sibling, file)).size > 256_000)
2586
+ continue;
2587
+ const text = readFileSync(join(sibling, file), "utf8");
2588
+ if (!mentionsApp.test(text) && (ownName === undefined || !text.includes(`${ownName}/`)))
2589
+ continue;
2590
+ const at = toPosix(relative(root, join(sibling, file)));
2591
+ const onLines = (lines) => `on line${lines.length === 1 ? "" : "s"} ${lines.join(", ")}`;
2592
+ for (const { from, to, lines, commentLines } of siblingReferences(ts, root, sibling, file, text, moveMap, known, ownName)) {
2593
+ const comments = commentLines.length === 0 ? "" : ` (and in a comment ${onLines(commentLines)})`;
2594
+ if (lines.length > 0)
2595
+ issues.push({
2596
+ file: at,
2597
+ reason: `names "${from}" ${onLines(lines)}${comments}, and it moves to "${to}" - it is outside the app, so the migration does not rewrite it`,
2598
+ });
2599
+ else
2600
+ commentFollowUps.push({
2601
+ file: at,
2602
+ reason: `a comment ${onLines(commentLines)} names "${from}", which moved to "${to}"`,
2603
+ });
2604
+ }
2605
+ }
2606
+ }
1570
2607
  // Paths a module finds at run time are not imports either: one built from the module's own location
1571
2608
  // now starts from its new folder, and a folder listed at run time loses whatever moved out of it.
1572
2609
  const leaving = new Map();
@@ -1597,28 +2634,56 @@ export async function migrateLayout(appRoot, options = {}) {
1597
2634
  reason: `moves to "${first.to}"${others} but ${left} in ${dir}/; code or tooling that lists ${dir}/ no longer finds what moved - move the folder together by hand`,
1598
2635
  });
1599
2636
  }
1600
- // The server refuses data a loader or action returns without an output schema; only the author
1601
- // knows which fields the browser may see.
2637
+ // The server refuses data a loader or action returns without an output schema. Each half the split
2638
+ // wrote gets a draft from its return type, read from the layout as planned so the dry run shows
2639
+ // what --write adds; only the author knows which fields the browser may see, so it is a draft.
2640
+ const halves = [...new Set(splits.map((split) => split.backend))].filter((file) => final.has(file));
2641
+ const unwritten = new Map();
2642
+ for (const [file, text] of final)
2643
+ if (original.get(file) !== text)
2644
+ unwritten.set(file, text);
2645
+ const schemaPlan = halves.length === 0
2646
+ ? undefined
2647
+ : await planOutputSchemas(root, halves, (file) => final.get(file), {
2648
+ overlay: unwritten,
2649
+ // What NF-C030 would flag: a schema for data the function returns, not for `return null`.
2650
+ draft: (file, schema) => missingOutputSchemas(final.get(file) ?? "").some((found) => found.schema === schema),
2651
+ });
2652
+ for (const [file, text] of schemaPlan?.edits ?? [])
2653
+ final.set(file, text);
2654
+ const schemas = (schemaPlan?.entries ?? []).filter((entry) => entry.status === "missing");
2655
+ const followUps = [...commentFollowUps];
1602
2656
  for (const [file, text] of final) {
1603
2657
  if (!file.startsWith("routes/") || !/\.backend\.[cm]?[jt]s$/.test(file))
1604
2658
  continue;
1605
2659
  for (const { name, schema } of missingOutputSchemas(text)) {
2660
+ const why = schemaPlan?.entries.find((entry) => entry.file === file && entry.schema === schema && entry.reason !== undefined)?.reason;
2661
+ const missing = `exports ${name === "action" ? "an" : "a"} ${name} but no ${schema}, so data it returns fails the request`;
2662
+ // A half this run did not write keeps the schema it had: drafting one is the next command, not a
2663
+ // decision the migration left open.
2664
+ if (why === undefined && (schemaPlan === undefined || schemaPlan.warnings.length === 0)) {
2665
+ followUps.push({
2666
+ file,
2667
+ reason: `${missing}; draft it from the ${name}'s return type`,
2668
+ command: "nifra schemas --write",
2669
+ });
2670
+ continue;
2671
+ }
1606
2672
  issues.push({
1607
2673
  file,
1608
- reason: `exports ${name === "action" ? "an" : "a"} ${name} but no ${schema}, so data it returns fails the request. Declare what the browser may see: export const ${schema} = t.object({ ... }), or run \`nifra schemas --write\` after the migration to draft it from the ${name}'s return type`,
2674
+ reason: `${missing}. Declare what the browser may see: export const ${schema} = t.object({ ... }); no draft was written: ${why ?? schemaPlan?.warnings.join("; ")}`,
1609
2675
  });
1610
2676
  }
1611
2677
  }
1612
2678
  // Tooling that lists folders or globs, not files: the import rewrite above never sees it.
1613
2679
  const tooling = [];
1614
2680
  const toolingWrites = new Map();
1615
- const tsconfig = coverMovedFiles(ts, root, moves);
1616
- if (tsconfig?.issue !== undefined)
1617
- issues.push({ file: "tsconfig.json", reason: tsconfig.issue });
1618
- if (tsconfig?.text !== undefined) {
1619
- toolingWrites.set("tsconfig.json", tsconfig.text);
1620
- tooling.push({ file: "tsconfig.json", change: `include += ${tsconfig.added.join(", ")}` });
2681
+ for (const [file, { text, changes }] of tsconfigs.files) {
2682
+ toolingWrites.set(file, text);
2683
+ for (const change of changes)
2684
+ tooling.push({ file, change });
1621
2685
  }
2686
+ issues.push(...tsconfigs.issues);
1622
2687
  for (const file of everyFile) {
1623
2688
  if (!TAILWIND_CONFIG.test(file))
1624
2689
  continue;
@@ -1631,6 +2696,35 @@ export async function migrateLayout(appRoot, options = {}) {
1631
2696
  toolingWrites.set(".gitignore", gitignore);
1632
2697
  tooling.push({ file: ".gitignore", change: "ignore .nifra/ (dev and build state)" });
1633
2698
  }
2699
+ // A root backend.ts was served at /api by default until 5.0, which mounts it only where apiPrefix says.
2700
+ if (!api && rootMoves["backend.ts"] !== undefined) {
2701
+ const mount = apiPrefixFix({
2702
+ framework: final.get(FRAMEWORK_FILE),
2703
+ config: final.get(CONFIG_FILE),
2704
+ });
2705
+ for (const [file, text] of [
2706
+ [FRAMEWORK_FILE, mount.framework],
2707
+ [CONFIG_FILE, mount.config],
2708
+ ]) {
2709
+ if (text === undefined)
2710
+ continue;
2711
+ final.set(file, text);
2712
+ tooling.push({
2713
+ file,
2714
+ change: 'export const apiPrefix = "/api", the mount 4.x made by default',
2715
+ });
2716
+ }
2717
+ }
2718
+ if (declared.size > 0) {
2719
+ const zoned = declareZones(ts, root, declared);
2720
+ if (zoned.issue !== undefined)
2721
+ issues.push({ file: "package.json", reason: zoned.issue });
2722
+ if (zoned.text !== undefined) {
2723
+ toolingWrites.set("package.json", zoned.text);
2724
+ for (const [path, side] of declared)
2725
+ tooling.push({ file: "package.json", change: `"nifra.zones" lists "${path}" as ${side}` });
2726
+ }
2727
+ }
1634
2728
  // `nifra check` reads the declaration statically; without it, a later routes/ or config would zone the app.
1635
2729
  const kind = api && createKindProbe(root)(root).kind === undefined ? declareApiKind(ts, root) : {};
1636
2730
  if (kind.issue !== undefined)
@@ -1639,6 +2733,14 @@ export async function migrateLayout(appRoot, options = {}) {
1639
2733
  toolingWrites.set("package.json", kind.text);
1640
2734
  tooling.push({ file: "package.json", change: '"nifra": { "kind": "api" }' });
1641
2735
  }
2736
+ if (manifest !== undefined && manifest.count > 0) {
2737
+ const current = toolingWrites.get("package.json") ?? readFileSync(manifestPath, "utf8");
2738
+ toolingWrites.set("package.json", rewritePackagePaths(ts, current, moveMap).text);
2739
+ tooling.push({
2740
+ file: "package.json",
2741
+ change: `${manifest.count} file path(s) in scripts and entry fields follow their moved files`,
2742
+ });
2743
+ }
1642
2744
  if (options.write === true) {
1643
2745
  for (const [file, text] of toolingWrites)
1644
2746
  writeFileSync(join(root, file), text);
@@ -1663,19 +2765,54 @@ export async function migrateLayout(appRoot, options = {}) {
1663
2765
  renameSync(join(root, from), join(root, to));
1664
2766
  vacated.push(from);
1665
2767
  }
2768
+ for (const [file, text] of scriptWrites)
2769
+ writeFileSync(join(root, file), text);
1666
2770
  pruneVacatedDirs(root, vacated);
1667
2771
  }
1668
2772
  return {
1669
2773
  ok: issues.length === 0,
1670
2774
  write: options.write === true,
1671
2775
  mode,
2776
+ followUps,
1672
2777
  splits: splits.sort((a, b) => codeUnitOrder(a.file, b.file)),
1673
2778
  moves,
1674
2779
  rewritten: rewritten.sort(),
1675
2780
  tooling,
2781
+ schemas: schemas.map((entry) => options.write === true && entry.reason === undefined
2782
+ ? { ...entry, status: "generated" }
2783
+ : entry),
1676
2784
  issues,
1677
2785
  };
1678
2786
  }
2787
+ /**
2788
+ * Split one route file in place: its server-only exports, and the code only they use, move into its
2789
+ * `x.backend.ts`, created or merged into. Returns the files written, app-relative; nothing for a file
2790
+ * that exports nothing for the server. Refuses, naming why, a split that would need a decision.
2791
+ */
2792
+ export async function splitRouteFile(appRoot, file, options = {}) {
2793
+ if (!/\.[jt]sx$/.test(file))
2794
+ return [];
2795
+ const ts = options.typescript ?? (await importTypeScript());
2796
+ if (ts === undefined)
2797
+ throw new Error("[nifra] splitting a route needs TypeScript: bun add -d typescript");
2798
+ const root = resolve(appRoot);
2799
+ const backendFile = file.replace(ROUTE_FILE, ".backend.ts");
2800
+ const sharedFile = file.replace(ROUTE_FILE, ".shared.ts");
2801
+ const result = splitRouteSource(ts, readFileSync(join(root, file), "utf8"), file, `./${posix.basename(backendFile)}`, existsSync(join(root, sharedFile)) ? {} : { sharedFile: posix.basename(sharedFile) });
2802
+ if (result.backend === undefined)
2803
+ return [];
2804
+ if (result.issues.length > 0) {
2805
+ throw new Error(`[nifra] ${file} was not split: ${result.issues.join("; ")}`);
2806
+ }
2807
+ const backendPath = join(root, backendFile);
2808
+ const existing = existsSync(backendPath) ? readFileSync(backendPath, "utf8") : "";
2809
+ writeFileSync(join(root, file), result.frontend);
2810
+ writeFileSync(backendPath, mergeModules(ts, existing, result.backend));
2811
+ if (result.shared === undefined)
2812
+ return [file, backendFile];
2813
+ writeFileSync(join(root, sharedFile), result.shared);
2814
+ return [file, backendFile, sharedFile];
2815
+ }
1679
2816
  /** The app's `"nifra": { "zones": ... }`, so folders it already zones are left where they are. */
1680
2817
  function appZones(root) {
1681
2818
  const manifest = join(root, "package.json");
@@ -1692,57 +2829,246 @@ function appZones(root) {
1692
2829
  const zones = typeof nifra === "object" && nifra !== null ? Reflect.get(nifra, "zones") : undefined;
1693
2830
  return zones === undefined ? {} : parseZoneConfig(zones, manifest);
1694
2831
  }
1695
- /** Whether a tsconfig `include` entry takes in `file` (app-relative), the way tsc reads it. */
1696
- function includes(pattern, file) {
1697
- let spec = pattern.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
1698
- if (spec === "" || spec === ".")
1699
- return true;
1700
- if (!/[*?]/.test(spec))
1701
- return file === spec || file.startsWith(`${spec}/`);
1702
- if (spec.endsWith("**"))
1703
- spec = `${spec}/*`;
1704
- else if (!/[*?.][^/]*$/.test(spec.slice(spec.lastIndexOf("/") + 1)))
1705
- spec = `${spec}/**/*`;
1706
- return new Bun.Glob(spec).match(file);
2832
+ const matchers = new Map();
2833
+ /** Whether a tsconfig `include` or `exclude` entry takes in `file` (app-relative), the way tsc reads it. */
2834
+ function matches(pattern, file) {
2835
+ let match = matchers.get(pattern);
2836
+ if (match === undefined) {
2837
+ let spec = pattern.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
2838
+ if (spec === "" || spec === ".")
2839
+ match = () => true;
2840
+ else if (!/[*?]/.test(spec)) {
2841
+ const folder = `${spec}/`;
2842
+ match = (path) => path === spec || path.startsWith(folder);
2843
+ }
2844
+ else {
2845
+ if (spec.endsWith("**"))
2846
+ spec = `${spec}/*`;
2847
+ else if (!/[*?.][^/]*$/.test(spec.slice(spec.lastIndexOf("/") + 1)))
2848
+ spec = `${spec}/**/*`;
2849
+ const glob = new Bun.Glob(spec);
2850
+ match = (path) => glob.match(path);
2851
+ }
2852
+ matchers.set(pattern, match);
2853
+ }
2854
+ return match(file);
2855
+ }
2856
+ const TSCONFIG = /^tsconfig(?:\.[\w-]+)?\.json$/;
2857
+ const TS_FILE = /\.(?:[cm]?ts|tsx)$/;
2858
+ const inProgram = (lists, file) => lists.files.includes(file) ||
2859
+ (lists.include.some((pattern) => matches(pattern, file)) &&
2860
+ !lists.exclude.some((pattern) => matches(pattern, file)));
2861
+ /** `pattern` under the zone folder `to` landed in, when that reaches `to`; else `to` itself. */
2862
+ function twinEntry(pattern, to) {
2863
+ const slash = to.indexOf("/");
2864
+ if (pattern === undefined || slash === -1)
2865
+ return to;
2866
+ const bare = pattern.replace(/^\.\//, "");
2867
+ const twin = `${to.slice(0, slash)}/${bare}`;
2868
+ if (!matches(twin, to))
2869
+ return to;
2870
+ return bare === pattern ? twin : `./${twin}`;
1707
2871
  }
1708
2872
  /**
1709
- * Add each zone folder that receives moved TypeScript to tsconfig `include`, editing only that array
1710
- * so comments and layout survive. A tsconfig without `include` (or with only `extends`) is left
1711
- * alone: tsc's default, or the base config, decides, and `nifra check` reports any folder left out.
2873
+ * Keep every TypeScript file in, or out of, each app-root `tsconfig*.json` program as it was. An entry
2874
+ * naming a moved file follows it; a folder or glob that took a moved file in gains its twin under the
2875
+ * zone folder (`src` -> `frontend/src`), and one that kept a file out does the same in `exclude`. So a
2876
+ * test run under its own config's types, or a folder left out on purpose, stays out after the move,
2877
+ * and code the config checked stays checked. An `include` or `exclude` a config inherits is not edited.
1712
2878
  */
1713
- function coverMovedFiles(ts, root, moves) {
1714
- const path = join(root, "tsconfig.json");
1715
- if (!existsSync(path))
1716
- return undefined;
1717
- const text = readFileSync(path, "utf8");
1718
- const source = ts.parseJsonText(path, text);
1719
- const top = source.statements[0]?.expression;
1720
- if (top === undefined || !ts.isObjectLiteralExpression(top))
1721
- return { added: [], issue: "is not a JSON object; add the zone folders to its include by hand" };
1722
- const include = jsonProperty(ts, top, "include");
1723
- if (include === undefined)
1724
- return undefined;
1725
- const array = include.initializer;
1726
- if (!ts.isArrayLiteralExpression(array))
1727
- return { added: [], issue: '"include" is not an array; add the zone folders to it by hand' };
1728
- const patterns = array.elements.filter(ts.isStringLiteral).map((element) => element.text);
1729
- const added = [];
1730
- for (const { to } of moves) {
1731
- if (!/\.(?:[cm]?ts|tsx)$/.test(to) || /\.d\.[cm]?ts$/.test(to))
1732
- continue;
1733
- const folder = to.split("/")[0] ?? to;
1734
- if (added.includes(folder) || patterns.some((pattern) => includes(pattern, to)))
1735
- continue;
1736
- added.push(folder);
2879
+ function followTsconfigs(ts, root, moves, layout) {
2880
+ const files = new Map();
2881
+ const issues = [];
2882
+ const typescript = layout.filter(({ to }) => TS_FILE.test(to));
2883
+ const names = readdirSync(root)
2884
+ .filter((name) => TSCONFIG.test(name) && isFile(join(root, name)))
2885
+ .sort(codeUnitOrder);
2886
+ // Each config's lists before and after the move, for the configs that extend it.
2887
+ const settled = new Map();
2888
+ const pending = [...names];
2889
+ for (let progress = true; progress && pending.length > 0;) {
2890
+ progress = false;
2891
+ for (const name of [...pending]) {
2892
+ const text = readFileSync(join(root, name), "utf8");
2893
+ const source = ts.parseJsonText(name, text);
2894
+ const top = source.statements[0]?.expression;
2895
+ if (top === undefined || !ts.isObjectLiteralExpression(top)) {
2896
+ pending.splice(pending.indexOf(name), 1);
2897
+ progress = true;
2898
+ if (moves.size > 0)
2899
+ issues.push({
2900
+ file: name,
2901
+ reason: "is not a JSON object; keep the moved files in its include and exclude by hand",
2902
+ });
2903
+ continue;
2904
+ }
2905
+ const base = jsonProperty(ts, top, "extends")?.initializer;
2906
+ let parent;
2907
+ if (base !== undefined && ts.isStringLiteral(base) && base.text.startsWith(".")) {
2908
+ const path = posix.normalize(base.text);
2909
+ const file = path.endsWith(".json") ? path : `${path}.json`;
2910
+ if (names.includes(file) && file !== name)
2911
+ parent = file;
2912
+ }
2913
+ if (parent !== undefined && pending.includes(parent))
2914
+ continue;
2915
+ pending.splice(pending.indexOf(name), 1);
2916
+ progress = true;
2917
+ const inherited = parent === undefined ? undefined : settled.get(parent);
2918
+ const extendsOther = base !== undefined && inherited === undefined;
2919
+ const edits = [];
2920
+ const own = new Map();
2921
+ let malformed;
2922
+ for (const key of ["include", "exclude", "files"]) {
2923
+ const array = jsonProperty(ts, top, key)?.initializer;
2924
+ if (array === undefined)
2925
+ continue;
2926
+ if (!ts.isArrayLiteralExpression(array)) {
2927
+ malformed = key;
2928
+ continue;
2929
+ }
2930
+ const lists = { before: [], after: [] };
2931
+ for (const element of array.elements) {
2932
+ if (!ts.isStringLiteral(element))
2933
+ continue;
2934
+ const to = moves.get(posix.normalize(element.text));
2935
+ lists.before.push(element.text);
2936
+ if (to === undefined) {
2937
+ lists.after.push(element.text);
2938
+ continue;
2939
+ }
2940
+ const spelled = element.text.startsWith("./") ? `./${to}` : to;
2941
+ lists.after.push(spelled);
2942
+ edits.push({
2943
+ start: element.getStart(source) + 1,
2944
+ end: element.getEnd() - 1,
2945
+ text: spelled,
2946
+ });
2947
+ }
2948
+ own.set(key, lists);
2949
+ }
2950
+ let updated = text;
2951
+ for (const edit of edits.sort((a, b) => b.start - a.start))
2952
+ updated = updated.slice(0, edit.start) + edit.text + updated.slice(edit.end);
2953
+ const changes = [];
2954
+ if (edits.length > 0)
2955
+ changes.push(`${edits.length} file path(s) follow their moved files`);
2956
+ const list = (key, when) => {
2957
+ const mine = own.get(key);
2958
+ if (mine !== undefined)
2959
+ return mine[when];
2960
+ if (inherited !== undefined)
2961
+ return [...inherited[when][key]];
2962
+ if (extendsOther)
2963
+ return undefined;
2964
+ // tsc's default: everything below the config, unless `files` lists the program.
2965
+ return key === "exclude" ? [] : own.has("files") ? [] : ["**/*"];
2966
+ };
2967
+ const filesOf = (when) => (own.get("files")?.[when] ?? []).map((entry) => posix.normalize(entry));
2968
+ const beforeInclude = list("include", "before");
2969
+ const beforeExclude = list("exclude", "before");
2970
+ const afterInclude = list("include", "after");
2971
+ const afterExclude = list("exclude", "after");
2972
+ if (malformed !== undefined ||
2973
+ beforeInclude === undefined ||
2974
+ beforeExclude === undefined ||
2975
+ afterInclude === undefined ||
2976
+ afterExclude === undefined) {
2977
+ if (malformed !== undefined && moves.size > 0)
2978
+ issues.push({
2979
+ file: name,
2980
+ reason: `"${malformed}" is not an array; keep the moved files in its program by hand`,
2981
+ });
2982
+ if (edits.length > 0)
2983
+ files.set(name, { text: updated, changes });
2984
+ continue;
2985
+ }
2986
+ const before = {
2987
+ include: beforeInclude,
2988
+ exclude: beforeExclude,
2989
+ files: filesOf("before"),
2990
+ };
2991
+ const after = { include: afterInclude, exclude: afterExclude, files: filesOf("after") };
2992
+ const added = { include: [], exclude: [] };
2993
+ let stranded;
2994
+ let strandedCount = 0;
2995
+ const quiet = new Map();
2996
+ // The whole zone folder is the entry that keeps covering code added there later, but only when
2997
+ // it takes in no file the config left out.
2998
+ const takesInOnlyChecked = (folder) => {
2999
+ let safe = quiet.get(folder);
3000
+ if (safe === undefined) {
3001
+ const wider = { ...after, include: [...after.include, folder] };
3002
+ safe = typescript.every((file) => !matches(folder, file.to) ||
3003
+ inProgram(before, file.from) ||
3004
+ !inProgram(wider, file.to));
3005
+ quiet.set(folder, safe);
3006
+ }
3007
+ return safe;
3008
+ };
3009
+ for (const { from, to } of typescript) {
3010
+ if (!inProgram(before, from) || inProgram(after, to))
3011
+ continue;
3012
+ if (after.include.some((pattern) => matches(pattern, to))) {
3013
+ // Its new place sits under an `exclude` that did not hold the old one.
3014
+ stranded ??= { from, to, key: "exclude" };
3015
+ strandedCount++;
3016
+ continue;
3017
+ }
3018
+ const zone = to.includes("/") ? to.slice(0, to.indexOf("/")) : undefined;
3019
+ const entry = zone !== undefined && takesInOnlyChecked(zone)
3020
+ ? zone
3021
+ : twinEntry(before.include.find((pattern) => matches(pattern, from)), to);
3022
+ added.include.push(entry);
3023
+ after.include.push(entry);
3024
+ }
3025
+ for (const { from, to } of typescript) {
3026
+ if (inProgram(before, from) || !inProgram(after, to))
3027
+ continue;
3028
+ let entry = twinEntry(before.exclude.find((pattern) => matches(pattern, from)), to);
3029
+ // A twin that would also drop a file the config checked is too wide: name the file.
3030
+ if (entry !== to &&
3031
+ typescript.some((other) => matches(entry, other.to) && inProgram(before, other.from)))
3032
+ entry = to;
3033
+ added.exclude.push(entry);
3034
+ after.exclude.push(entry);
3035
+ }
3036
+ for (const key of ["include", "exclude"]) {
3037
+ const entries = [...new Set(added[key])].sort(codeUnitOrder);
3038
+ if (entries.length === 0)
3039
+ continue;
3040
+ const reparsed = ts.parseJsonText(name, updated);
3041
+ const object = reparsed.statements[0]?.expression;
3042
+ const array = object !== undefined && ts.isObjectLiteralExpression(object)
3043
+ ? jsonProperty(ts, object, key)?.initializer
3044
+ : undefined;
3045
+ if (array === undefined || !ts.isArrayLiteralExpression(array)) {
3046
+ stranded ??= { from: "", to: entries[0] ?? "", key };
3047
+ strandedCount += entries.length;
3048
+ continue;
3049
+ }
3050
+ updated = appendToArray(reparsed, updated, array, entries);
3051
+ changes.push(`${key} += ${entries.join(", ")}`);
3052
+ }
3053
+ if (stranded !== undefined)
3054
+ issues.push({
3055
+ file: name,
3056
+ reason: `cannot keep ${strandedCount} moved file(s) in or out of its program as before (first: "${stranded.to}"); its "${stranded.key}" is inherited or would hide them, so set it by hand`,
3057
+ });
3058
+ settled.set(name, { before, after });
3059
+ if (changes.length > 0)
3060
+ files.set(name, { text: updated, changes });
3061
+ }
1737
3062
  }
1738
- if (added.length === 0)
1739
- return undefined;
1740
- added.sort(codeUnitOrder);
1741
- const quoted = added.map((folder) => JSON.stringify(folder));
3063
+ return { files, issues };
3064
+ }
3065
+ /** `text` with `entries` appended to `array`: one per line in a multi-line array, else inline. */
3066
+ function appendToArray(source, text, array, entries) {
3067
+ const quoted = entries.map((entry) => JSON.stringify(entry));
1742
3068
  const last = array.elements[array.elements.length - 1];
1743
3069
  if (last === undefined) {
1744
3070
  const at = array.getStart(source) + 1;
1745
- return { text: `${text.slice(0, at)}${quoted.join(", ")}${text.slice(at)}`, added };
3071
+ return `${text.slice(0, at)}${quoted.join(", ")}${text.slice(at)}`;
1746
3072
  }
1747
3073
  let at = last.end;
1748
3074
  const trailing = /^\s*,/.exec(text.slice(at));
@@ -1759,15 +3085,12 @@ function coverMovedFiles(ts, root, moves) {
1759
3085
  const head = trailing !== null
1760
3086
  ? text.slice(0, eol)
1761
3087
  : `${text.slice(0, last.end)},${text.slice(last.end, eol)}`;
1762
- const entries = quoted.join(`,\n${indent}`);
1763
- return {
1764
- text: `${head}\n${indent}${entries}${trailing !== null ? "," : ""}${text.slice(eol)}`,
1765
- added,
1766
- };
3088
+ const lines = quoted.join(`,\n${indent}`);
3089
+ return `${head}\n${indent}${lines}${trailing !== null ? "," : ""}${text.slice(eol)}`;
1767
3090
  }
1768
3091
  }
1769
3092
  const insert = trailing !== null ? ` ${quoted.join(", ")},` : `, ${quoted.join(", ")}`;
1770
- return { text: `${text.slice(0, at)}${insert}${text.slice(at)}`, added };
3093
+ return `${text.slice(0, at)}${insert}${text.slice(at)}`;
1771
3094
  }
1772
3095
  const jsonProperty = (ts, object, key) => object.properties.find((property) => ts.isPropertyAssignment(property) &&
1773
3096
  ts.isStringLiteral(property.name) &&
@@ -1785,6 +3108,104 @@ function insertProperty(source, text, object, entry) {
1785
3108
  const indent = /^[ \t]*/.exec(text.slice(text.lastIndexOf("\n", start) + 1, start))?.[0] ?? "";
1786
3109
  return `${text.slice(0, last.end)},\n${indent}${entry}${text.slice(last.end)}`;
1787
3110
  }
3111
+ /**
3112
+ * The `nifra.zones` entries that keep `inPlace` files where they are: for each, the widest folder
3113
+ * above it whose zoned files all take its side (a nested package stops the climb), else the file
3114
+ * itself. A file another side's suffix or a server built-in claims counts against a folder.
3115
+ */
3116
+ function zoneDeclarations(inPlace, files, text, configured) {
3117
+ const sides = new Map();
3118
+ const packages = new Set();
3119
+ for (const file of files) {
3120
+ const top = file.split("/")[0] ?? "";
3121
+ if (!file.includes("/") || ZONE_DIRS.has(top))
3122
+ continue;
3123
+ if (posix.basename(file) === "package.json") {
3124
+ for (let dir = posix.dirname(file); dir !== "."; dir = posix.dirname(dir))
3125
+ packages.add(dir);
3126
+ continue;
3127
+ }
3128
+ // A configured path is more specific than any folder above it, so it never counts against one.
3129
+ if (isTestFile(file) || file.endsWith(".d.ts") || configured(file))
3130
+ continue;
3131
+ const suffix = /\.(frontend|backend|shared|fn)\.[cm]?[jt]sx?$/.exec(file)?.[1];
3132
+ const side = inPlace.get(file) ??
3133
+ (suffix === "fn" ? "backend" : suffix) ??
3134
+ (SOURCE_FILE.test(file) && /from\s+["'](?:node:|bun:)/.test(text(file) ?? "")
3135
+ ? "backend"
3136
+ : undefined);
3137
+ if (side === undefined)
3138
+ continue;
3139
+ for (let dir = posix.dirname(file); dir !== "."; dir = posix.dirname(dir))
3140
+ sides.set(dir, (sides.get(dir) ?? new Set()).add(side));
3141
+ }
3142
+ const declared = new Map();
3143
+ for (const [file, side] of [...inPlace].sort(([a], [b]) => codeUnitOrder(a, b))) {
3144
+ const parts = file.split("/");
3145
+ let path = file;
3146
+ for (let depth = 1; depth < parts.length; depth++) {
3147
+ const dir = parts.slice(0, depth).join("/");
3148
+ const found = sides.get(dir);
3149
+ if (!packages.has(dir) && found?.size === 1 && found.has(side)) {
3150
+ path = dir;
3151
+ break;
3152
+ }
3153
+ }
3154
+ declared.set(path, side);
3155
+ }
3156
+ return declared;
3157
+ }
3158
+ /** The app's package.json with `paths` added to `"nifra": { "zones": ... }`, editing only where they go. */
3159
+ function declareZones(ts, root, paths) {
3160
+ const listed = (side) => [...paths].flatMap(([path, of]) => (of === side ? [path] : []));
3161
+ const setting = `{ ${FOLDER_SIDES.filter((side) => listed(side).length > 0)
3162
+ .map((side) => `"${side}": ${JSON.stringify(listed(side))}`)
3163
+ .join(", ")} }`;
3164
+ const path = join(root, "package.json");
3165
+ if (!existsSync(path))
3166
+ return { issue: `there is none in the app; declare "nifra": { "zones": ${setting} } in it` };
3167
+ let text = readFileSync(path, "utf8");
3168
+ // Parsed again for each edit: an edit moves every offset after it.
3169
+ const find = (keys) => {
3170
+ const source = ts.parseJsonText(path, text);
3171
+ let node = source.statements[0]?.expression;
3172
+ for (const key of keys)
3173
+ node =
3174
+ node !== undefined && ts.isObjectLiteralExpression(node)
3175
+ ? jsonProperty(ts, node, key)?.initializer
3176
+ : undefined;
3177
+ return { source, node };
3178
+ };
3179
+ const top = find([]);
3180
+ if (top.node === undefined || !ts.isObjectLiteralExpression(top.node))
3181
+ return { issue: `is not a JSON object; add "nifra": { "zones": ${setting} } to it by hand` };
3182
+ const nifra = find(["nifra"]);
3183
+ if (nifra.node === undefined)
3184
+ return { text: insertProperty(top.source, text, top.node, `"nifra": { "zones": ${setting} }`) };
3185
+ if (!ts.isObjectLiteralExpression(nifra.node))
3186
+ return { issue: `"nifra" is not an object; add "zones": ${setting} to it by hand` };
3187
+ const zones = find(["nifra", "zones"]);
3188
+ if (zones.node === undefined)
3189
+ return { text: insertProperty(nifra.source, text, nifra.node, `"zones": ${setting}`) };
3190
+ for (const side of FOLDER_SIDES) {
3191
+ const add = listed(side);
3192
+ if (add.length === 0)
3193
+ continue;
3194
+ const { source, node } = find(["nifra", "zones"]);
3195
+ if (node === undefined || !ts.isObjectLiteralExpression(node))
3196
+ return { issue: `"nifra.zones" is not an object; add ${setting} to it by hand` };
3197
+ const array = jsonProperty(ts, node, side)?.initializer;
3198
+ if (array === undefined)
3199
+ text = insertProperty(source, text, node, `"${side}": ${JSON.stringify(add)}`);
3200
+ else if (ts.isArrayLiteralExpression(array))
3201
+ text = appendToArray(source, text, array, add);
3202
+ else
3203
+ return {
3204
+ issue: `"nifra.zones.${side}" is not an array; add ${JSON.stringify(add)} to it by hand`,
3205
+ };
3206
+ }
3207
+ return { text };
3208
+ }
1788
3209
  /** The app's package.json with `"nifra": { "kind": "api" }` added, editing only where it goes. */
1789
3210
  function declareApiKind(ts, root) {
1790
3211
  const path = join(root, "package.json");
@@ -1806,6 +3227,78 @@ function declareApiKind(ts, root) {
1806
3227
  return { issue: '"nifra" is not an object; add "kind": "api" to it by hand' };
1807
3228
  return { text: insertProperty(source, text, nifra.initializer, '"kind": "api"') };
1808
3229
  }
3230
+ /** package.json fields whose string values name files from the package folder. */
3231
+ const PACKAGE_PATH_FIELDS = new Set([
3232
+ "main",
3233
+ "module",
3234
+ "types",
3235
+ "typings",
3236
+ "browser",
3237
+ "source",
3238
+ "bin",
3239
+ "exports",
3240
+ "imports",
3241
+ "files",
3242
+ "scripts",
3243
+ ]);
3244
+ /**
3245
+ * `text` (a package.json at the app root) with each moved file it names by its exact path, in the
3246
+ * fields above, named at its new path; `./` kept as written. A value with a `*` outside `scripts` is a
3247
+ * pattern over a folder, which no single move settles, so it stays and the path scan reports it.
3248
+ */
3249
+ function rewritePackagePaths(ts, text, moves) {
3250
+ const source = ts.parseJsonText("package.json", text);
3251
+ const top = source.statements[0]?.expression;
3252
+ if (top === undefined || !ts.isObjectLiteralExpression(top) || moves.size === 0)
3253
+ return { text, count: 0 };
3254
+ // Longest first, so `lib/a.test.ts` is not read as `lib/a.ts` with a tail.
3255
+ const ordered = [...moves].sort(([a], [b]) => b.length - a.length);
3256
+ const pattern = new RegExp(`(?<![\\w.@/-])(\\./)?(${ordered.map(([from]) => escapeRegExp(from)).join("|")})(?![\\w/-]|\\.\\w)`, "g");
3257
+ const edits = [];
3258
+ let count = 0;
3259
+ const visit = (node, field) => {
3260
+ if (ts.isStringLiteral(node)) {
3261
+ if (field !== "scripts" && node.text.includes("*"))
3262
+ return;
3263
+ const value = node.text.replace(pattern, (_match, dot, from) => {
3264
+ count += 1;
3265
+ return `${dot ?? ""}${moves.get(from) ?? from}`;
3266
+ });
3267
+ if (value !== node.text)
3268
+ edits.push({
3269
+ start: node.getStart(source),
3270
+ end: node.getEnd(),
3271
+ text: JSON.stringify(value),
3272
+ });
3273
+ return;
3274
+ }
3275
+ if (ts.isArrayLiteralExpression(node)) {
3276
+ for (const element of node.elements)
3277
+ visit(element, field);
3278
+ return;
3279
+ }
3280
+ if (!ts.isObjectLiteralExpression(node))
3281
+ return;
3282
+ for (const property of node.properties) {
3283
+ if (!ts.isPropertyAssignment(property))
3284
+ continue;
3285
+ // `"//x"` keys are comments by npm convention.
3286
+ if (ts.isStringLiteral(property.name) && property.name.text.startsWith("//"))
3287
+ continue;
3288
+ visit(property.initializer, field);
3289
+ }
3290
+ };
3291
+ for (const property of top.properties) {
3292
+ if (!ts.isPropertyAssignment(property) || !ts.isStringLiteral(property.name))
3293
+ continue;
3294
+ if (PACKAGE_PATH_FIELDS.has(property.name.text))
3295
+ visit(property.initializer, property.name.text);
3296
+ }
3297
+ let next = text;
3298
+ for (const edit of edits.sort((a, b) => b.start - a.start))
3299
+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);
3300
+ return { text: next, count };
3301
+ }
1809
3302
  /** Tailwind `content` globs that matched a moved file at its old path and match nothing at its new one. */
1810
3303
  function staleContentGlobs(ts, text, moves) {
1811
3304
  const globs = [];