@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 {
27
29
  existsSync,
@@ -42,10 +44,13 @@ import { parseZoneConfig, type ZoneConfig } from "@nifrajs/web/zones"
42
44
  import type * as TS from "typescript"
43
45
  import { BACKEND_APP_FILE, CONFIG_FILE, FRAMEWORK_FILE, retiredRootFiles } from "./app-files.ts"
44
46
  import { codeUnitOrder } from "./internal/code-unit-order.ts"
47
+ import { configPathReader, type StaticConfigPath } from "./internal/config-paths.ts"
45
48
  import { createKindProbe, hasWebConfig } from "./internal/nifra-project.ts"
46
- import { createSpecifierResolver } from "./internal/project-specifiers.ts"
49
+ import { createSpecifierResolver, isFile } from "./internal/project-specifiers.ts"
47
50
  import { importTypeScript } from "./internal/typescript-import.ts"
51
+ import { type OutputSchemaEntry, planOutputSchemas } from "./output-schemas.ts"
48
52
  import { missingOutputSchemas } from "./rules/data-guard.ts"
53
+ import { apiPrefixFix } from "./rules/pages.ts"
49
54
 
50
55
  /** Exports only the server or the build reads: `@nifrajs/web`'s route-pair contract. */
51
56
  const BACKEND_EXPORTS = BACKEND_ROUTE_EXPORTS
@@ -69,12 +74,15 @@ const LEGACY_SERVER = /\.server(\.(?:[cm]?[jt]sx?|svelte|vue|mdx))$/
69
74
  const RETIRED_SPECIFIERS: Readonly<Record<string, string>> = {
70
75
  "@nifrajs/web/server-only": "@nifrajs/web/backend-only",
71
76
  }
72
- /** Scripts and config that name app files by path: scanned for paths that moved, never rewritten. */
77
+ /** Scripts and config that name app files by path: scanned for paths that moved. Only the app's own
78
+ * package.json is rewritten, in the fields `rewritePackagePaths` reads. */
73
79
  const TOOLING_FILE =
74
80
  /(?:\.(?:json|jsonc|ya?ml|toml|sh|bash|zsh|ps1)|(?:^|\/)(?:Dockerfile|Makefile|Procfile))$/
75
81
  const SELF_LOCATION = /\bimport\.meta\.(?:dirname|dir|filename|url)\b|\b__(?:dirname|filename)\b/
76
82
  const SKIP_DIRS = new Set(["node_modules", "dist", "build", "coverage", ".git", ".vite", "public"])
77
83
  const ZONE_DIRS = new Set(["frontend", "backend", "shared", "routes", "public"])
84
+ type FolderSide = "frontend" | "backend" | "shared"
85
+ const FOLDER_SIDES: readonly FolderSide[] = ["frontend", "backend", "shared"]
78
86
  /** Data other tools may read by path too; reported, never moved. Images and fonts still move. */
79
87
  const DATA_FILE = /\.(?:json|jsonc|json5|ndjson|ya?ml|toml|csv|tsv|txt|xml|sql)$/
80
88
  /** Test-runner calls that name a module by path, as an import does. */
@@ -91,13 +99,35 @@ const MOCK_CALLS: ReadonlySet<string> = new Set([
91
99
  "jest.unstable_mockModule",
92
100
  ])
93
101
  const TAILWIND_CONFIG = /^tailwind\.config\.[cm]?[jt]s$/
102
+ /** What a `x.test.ts` beside `x.<ext>` tests. */
103
+ const SUBJECT_EXTENSIONS = [
104
+ ".ts",
105
+ ".tsx",
106
+ ".mts",
107
+ ".cts",
108
+ ".js",
109
+ ".jsx",
110
+ ".mjs",
111
+ ".cjs",
112
+ ".svelte",
113
+ ".vue",
114
+ ]
94
115
 
95
116
  export interface LayoutMigrationIssue {
96
117
  readonly file: string
97
118
  readonly reason: string
98
119
  }
99
120
 
121
+ /** A step left for after the migration that a command takes: it needs no decision, so `ok` ignores it. */
122
+ export interface LayoutMigrationFollowUp {
123
+ readonly file: string
124
+ readonly reason: string
125
+ /** The command that settles it; absent when the step is an edit, such as a comment to update. */
126
+ readonly command?: string
127
+ }
128
+
100
129
  export interface LayoutMigrationResult {
130
+ /** No issue needs a decision; follow-ups may remain. */
101
131
  readonly ok: boolean
102
132
  readonly write: boolean
103
133
  /** `"api"` for an app that serves no pages: only its backend entry moves, nothing is split or zoned. */
@@ -107,6 +137,8 @@ export interface LayoutMigrationResult {
107
137
  readonly file: string
108
138
  readonly backend: string
109
139
  readonly moved: readonly string[]
140
+ /** The module beside the route both halves import constant data from, when the split made one. */
141
+ readonly shared?: string
110
142
  }>
111
143
  /** Files that moved, app-relative. */
112
144
  readonly moves: ReadonlyArray<{ readonly from: string; readonly to: string }>
@@ -114,11 +146,24 @@ export interface LayoutMigrationResult {
114
146
  readonly rewritten: readonly string[]
115
147
  /** Tooling config the migration updated so it still covers what moved. */
116
148
  readonly tooling: ReadonlyArray<{ readonly file: string; readonly change: string }>
149
+ /**
150
+ * Output schemas drafted for the backend halves the split wrote, from their return types:
151
+ * `missing` in a dry run, `generated` once written. Each is a draft the author reviews.
152
+ */
153
+ readonly schemas: readonly OutputSchemaEntry[]
117
154
  readonly issues: readonly LayoutMigrationIssue[]
155
+ /** Commands to run after the migration, each with what it settles. */
156
+ readonly followUps: readonly LayoutMigrationFollowUp[]
118
157
  }
119
158
 
120
159
  export interface LayoutMigrationOptions {
121
160
  readonly write?: boolean
161
+ /**
162
+ * Leave the modules the layout would move into `frontend/`, `backend/` or `shared/` where they are,
163
+ * and list them in the app's `"nifra": { "zones": ... }` instead: the widest folder whose files all
164
+ * belong to one side, else the file itself. Route splits and the root entry moves still happen.
165
+ */
166
+ readonly zones?: boolean
122
167
  /** Inject the TypeScript compiler (tests); defaults to the CLI's own. */
123
168
  readonly typescript?: typeof TS
124
169
  }
@@ -128,6 +173,15 @@ type Files = Map<string, string>
128
173
 
129
174
  const toPosix = (path: string): string => path.replaceAll("\\", "/")
130
175
 
176
+ /** A specifier without its `?query` or `#hash`; a leading `#` names a package.json import. Cut by
177
+ * index, since `/[?#].*$/` retries from every `#` and is quadratic on a long run of them. */
178
+ const withoutQuery = (specifier: string): string => {
179
+ const query = specifier.indexOf("?", 1)
180
+ const hash = specifier.indexOf("#", 1)
181
+ const cut = query === -1 ? hash : hash === -1 ? query : Math.min(query, hash)
182
+ return cut === -1 ? specifier : specifier.slice(0, cut)
183
+ }
184
+
131
185
  /** Every first-party file under `root`, app-relative and posix. */
132
186
  function listFiles(root: string): string[] {
133
187
  const out: string[] = []
@@ -156,12 +210,29 @@ interface StatementInfo {
156
210
  readonly exports: ReadonlyMap<string, readonly string[]>
157
211
  readonly valueRefs: ReadonlySet<string>
158
212
  readonly typeRefs: ReadonlySet<string>
213
+ /** A local `export { a, b as c }`: each entry, which the reachability of its own half follows. */
214
+ readonly listed: ReadonlyArray<ListedExport>
215
+ }
216
+
217
+ interface ListedExport {
218
+ readonly exported: string
219
+ readonly local: string
220
+ /** `export type { X }` or `export { type X }`: a read in a type position. */
221
+ readonly type: boolean
222
+ }
223
+
224
+ /** The names one half reads, by position. */
225
+ interface Uses {
226
+ readonly value: ReadonlySet<string>
227
+ readonly type: ReadonlySet<string>
159
228
  }
160
229
 
161
230
  export interface SplitResult {
162
231
  readonly frontend: string
163
232
  /** `undefined` when the file exports nothing for the server. */
164
233
  readonly backend: string | undefined
234
+ /** The module beside the route that holds constant data both halves import, when there is any. */
235
+ readonly shared?: string
165
236
  readonly moved: readonly string[]
166
237
  readonly issues: readonly string[]
167
238
  }
@@ -247,6 +318,7 @@ function describeStatements(ts: typeof TS, sf: TS.SourceFile): StatementInfo[] {
247
318
  return sf.statements.map((node) => {
248
319
  const declares = new Set<string>()
249
320
  const exports = new Map<string, string[]>()
321
+ const listed: ListedExport[] = []
250
322
  const exported = hasModifier(ts, node, ts.SyntaxKind.ExportKeyword)
251
323
  const isDefault = hasModifier(ts, node, ts.SyntaxKind.DefaultKeyword)
252
324
  const addExport = (local: string, as: string): void => {
@@ -286,10 +358,10 @@ function describeStatements(ts: typeof TS, sf: TS.SourceFile): StatementInfo[] {
286
358
  ts.isNamedExports(node.exportClause)
287
359
  ) {
288
360
  for (const el of node.exportClause.elements) {
289
- addExport(
290
- node.moduleSpecifier ? `\0${el.name.text}` : (el.propertyName ?? el.name).text,
291
- el.name.text,
292
- )
361
+ const local = (el.propertyName ?? el.name).text
362
+ addExport(node.moduleSpecifier ? `\0${el.name.text}` : local, el.name.text)
363
+ if (node.moduleSpecifier === undefined)
364
+ listed.push({ exported: el.name.text, local, type: node.isTypeOnly || el.isTypeOnly })
293
365
  }
294
366
  }
295
367
  const refs = ts.isImportDeclaration(node)
@@ -306,34 +378,72 @@ function describeStatements(ts: typeof TS, sf: TS.SourceFile): StatementInfo[] {
306
378
  exports,
307
379
  valueRefs: refs.value,
308
380
  typeRefs: refs.type,
381
+ listed,
309
382
  }
310
383
  })
311
384
  }
312
385
 
313
- /** Rebuild an import keeping only the bindings `keep` names. `undefined` when none remain. */
386
+ /**
387
+ * Rebuild an import keeping only the bindings `uses` names; `undefined` when none remain. Bindings
388
+ * read only in types become `import type`, so no bundler loads the module for them: always in a
389
+ * `fresh` module, and in the page only where the split narrowed the import.
390
+ */
314
391
  function filterImport(
315
392
  ts: typeof TS,
316
393
  sf: TS.SourceFile,
317
394
  node: TS.ImportDeclaration,
318
- keep: (name: string) => boolean,
395
+ uses: Uses,
396
+ fresh: boolean,
319
397
  ): string | undefined {
320
398
  const clause = node.importClause
321
399
  const spec = node.moduleSpecifier.getText(sf)
322
400
  const attributes = node.attributes ? ` ${node.attributes.getText(sf)}` : ""
323
401
  if (clause === undefined) return node.getFullText(sf)
324
- const parts: string[] = []
325
- if (clause.name && keep(clause.name.text)) parts.push(clause.name.text)
402
+ interface Part {
403
+ readonly text: string
404
+ /** Without an inline `type`, for an `import type`. */
405
+ readonly bare: string
406
+ readonly typeOnly: boolean
407
+ }
408
+ const heads: Part[] = []
409
+ const named: Part[] = []
410
+ let total = 0
411
+ const add = (into: Part[], name: string, text: string, bare: string): void => {
412
+ total++
413
+ if (uses.value.has(name) || uses.type.has(name))
414
+ into.push({ text, bare, typeOnly: !uses.value.has(name) })
415
+ }
416
+ if (clause.name) add(heads, clause.name.text, clause.name.text, clause.name.text)
326
417
  const bindings = clause.namedBindings
327
- if (bindings && ts.isNamespaceImport(bindings) && keep(bindings.name.text))
328
- parts.push(`* as ${bindings.name.text}`)
418
+ if (bindings && ts.isNamespaceImport(bindings)) {
419
+ const text = `* as ${bindings.name.text}`
420
+ add(heads, bindings.name.text, text, text)
421
+ }
329
422
  if (bindings && ts.isNamedImports(bindings)) {
330
- const named = bindings.elements.filter((el) => keep(el.name.text)).map((el) => el.getText(sf))
331
- if (named.length > 0) parts.push(`{ ${named.join(", ")} }`)
423
+ for (const el of bindings.elements) {
424
+ const renamed = el.propertyName ? `${el.propertyName.getText(sf)} as ` : ""
425
+ add(named, el.name.text, el.getText(sf), `${renamed}${el.name.text}`)
426
+ }
332
427
  }
333
- if (parts.length === 0) return undefined
334
- const typeOnly = clause.isTypeOnly ? "type " : ""
428
+ const kept = [...heads, ...named]
429
+ if (kept.length === 0) return undefined
335
430
  const leading = node.getFullText(sf).slice(0, node.getStart(sf) - node.getFullStart())
336
- return `${leading}import ${typeOnly}${parts.join(", ")} from ${spec}${attributes}${terminatorOf(sf, node)}`
431
+ const statement = (typeOnly: boolean, body: string): string =>
432
+ `import ${typeOnly ? "type " : ""}${body} from ${spec}${attributes}${terminatorOf(sf, node)}`
433
+ const list = (parts: readonly Part[], text: (part: Part) => string): string[] =>
434
+ parts.length === 0 ? [] : [`{ ${parts.map(text).join(", ")} }`]
435
+ if (
436
+ !clause.isTypeOnly &&
437
+ node.attributes === undefined &&
438
+ (fresh || kept.length < total) &&
439
+ kept.every((part) => part.typeOnly)
440
+ ) {
441
+ // `import type` takes one default, namespace or list, so each goes in its own statement.
442
+ const bodies = [...heads.map((part) => part.bare), ...list(named, (part) => part.bare)]
443
+ return `${leading}${bodies.map((body) => statement(true, body)).join("\n")}`
444
+ }
445
+ const body = [...heads.map((part) => part.text), ...list(named, (part) => part.text)]
446
+ return `${leading}${statement(clause.isTypeOnly, body.join(", "))}`
337
447
  }
338
448
 
339
449
  /** The `;` a statement was written with, so a rebuilt one keeps the file's style. */
@@ -363,6 +473,126 @@ const joinStatements = (texts: readonly string[]): string => {
363
473
  return body.endsWith("\n") ? body : `${body}\n`
364
474
  }
365
475
 
476
+ /** Options for {@link splitRouteSource}. */
477
+ export interface SplitOptions {
478
+ /**
479
+ * The file name of a module beside the route (`index.shared.ts`) to hold constant data both halves
480
+ * read, which each half then imports. Without it, that data is copied into each half.
481
+ */
482
+ readonly sharedFile?: string
483
+ }
484
+
485
+ const PURE_OBJECT_CALLS = new Set(["keys", "values", "entries", "freeze", "fromEntries"])
486
+
487
+ /**
488
+ * Whether `node` builds constant data: literals, arrays and objects of it, operators over it,
489
+ * `Object.keys`-style reads, and the file's own top-level names, which go into `reads`. `undefined`
490
+ * when it is data; else the import it reads, or `""` for anything else (a call, a function, a global).
491
+ */
492
+ function dataBlocker(
493
+ ts: typeof TS,
494
+ node: TS.Node,
495
+ isLocal: (name: string) => boolean,
496
+ reads: Set<string>,
497
+ ): string | undefined {
498
+ const data = (n: TS.Node): string | undefined => {
499
+ if (
500
+ ts.isStringLiteral(n) ||
501
+ ts.isNumericLiteral(n) ||
502
+ ts.isBigIntLiteral(n) ||
503
+ ts.isNoSubstitutionTemplateLiteral(n) ||
504
+ n.kind === ts.SyntaxKind.TrueKeyword ||
505
+ n.kind === ts.SyntaxKind.FalseKeyword ||
506
+ n.kind === ts.SyntaxKind.NullKeyword
507
+ )
508
+ return undefined
509
+ if (ts.isIdentifier(n)) {
510
+ if (isLocal(n.text)) {
511
+ reads.add(n.text)
512
+ return undefined
513
+ }
514
+ return n.text === "undefined" ? undefined : n.text
515
+ }
516
+ const every = (nodes: readonly TS.Node[]): string | undefined => {
517
+ for (const child of nodes) {
518
+ const blocker = data(child)
519
+ if (blocker !== undefined) return blocker
520
+ }
521
+ return undefined
522
+ }
523
+ if (ts.isTemplateExpression(n)) return every(n.templateSpans.map((span) => span.expression))
524
+ if (ts.isPrefixUnaryExpression(n))
525
+ return n.operator === ts.SyntaxKind.PlusPlusToken ||
526
+ n.operator === ts.SyntaxKind.MinusMinusToken
527
+ ? ""
528
+ : data(n.operand)
529
+ if (ts.isBinaryExpression(n)) {
530
+ const operator = n.operatorToken.kind
531
+ const assigns =
532
+ operator >= ts.SyntaxKind.FirstAssignment && operator <= ts.SyntaxKind.LastAssignment
533
+ if (
534
+ assigns ||
535
+ operator === ts.SyntaxKind.CommaToken ||
536
+ operator === ts.SyntaxKind.InKeyword ||
537
+ operator === ts.SyntaxKind.InstanceOfKeyword
538
+ )
539
+ return ""
540
+ return every([n.left, n.right])
541
+ }
542
+ if (ts.isConditionalExpression(n)) return every([n.condition, n.whenTrue, n.whenFalse])
543
+ if (ts.isArrayLiteralExpression(n))
544
+ return every(
545
+ n.elements.flatMap((element) =>
546
+ ts.isOmittedExpression(element)
547
+ ? []
548
+ : [ts.isSpreadElement(element) ? element.expression : element],
549
+ ),
550
+ )
551
+ if (ts.isObjectLiteralExpression(n)) {
552
+ for (const property of n.properties) {
553
+ const blocker = ts.isPropertyAssignment(property)
554
+ ? ((ts.isComputedPropertyName(property.name)
555
+ ? data(property.name.expression)
556
+ : undefined) ?? data(property.initializer))
557
+ : ts.isShorthandPropertyAssignment(property)
558
+ ? property.objectAssignmentInitializer === undefined
559
+ ? data(property.name)
560
+ : ""
561
+ : ts.isSpreadAssignment(property)
562
+ ? data(property.expression)
563
+ : ""
564
+ if (blocker !== undefined) return blocker
565
+ }
566
+ return undefined
567
+ }
568
+ if (
569
+ ts.isParenthesizedExpression(n) ||
570
+ ts.isAsExpression(n) ||
571
+ ts.isSatisfiesExpression(n) ||
572
+ ts.isNonNullExpression(n) ||
573
+ ts.isTypeAssertionExpression(n)
574
+ )
575
+ return data(n.expression)
576
+ if (ts.isPropertyAccessExpression(n))
577
+ return ts.isPrivateIdentifier(n.name) ? "" : data(n.expression)
578
+ if (ts.isElementAccessExpression(n)) return every([n.expression, n.argumentExpression])
579
+ if (ts.isCallExpression(n)) {
580
+ const callee = n.expression
581
+ const objectRead =
582
+ ts.isPropertyAccessExpression(callee) &&
583
+ ts.isIdentifier(callee.expression) &&
584
+ callee.expression.text === "Object" &&
585
+ !isLocal("Object") &&
586
+ PURE_OBJECT_CALLS.has(callee.name.text) &&
587
+ n.questionDotToken === undefined &&
588
+ n.typeArguments === undefined
589
+ return objectRead ? every(n.arguments) : ""
590
+ }
591
+ return ""
592
+ }
593
+ return data(node)
594
+ }
595
+
366
596
  /**
367
597
  * Split one route module's source into its frontend and backend halves. `backendSpecifier` is how the
368
598
  * frontend refers to the backend half in an `import type` (`./index.backend.ts`).
@@ -372,6 +602,7 @@ export function splitRouteSource(
372
602
  source: string,
373
603
  fileName: string,
374
604
  backendSpecifier: string,
605
+ options: SplitOptions = {},
375
606
  ): SplitResult {
376
607
  const kind = fileName.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
377
608
  const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, kind)
@@ -384,70 +615,177 @@ export function splitRouteSource(
384
615
  if (moved.length === 0) return { frontend: source, backend: undefined, moved: [], issues: [] }
385
616
 
386
617
  const declaredBy = new Map<string, StatementInfo>()
618
+ const importedBy = new Map<string, StatementInfo>()
387
619
  for (const info of statements) {
388
- if (ts.isImportDeclaration(info.node)) continue
389
- for (const name of info.declares) declaredBy.set(name, info)
390
- }
391
-
392
- // The backend half: its export statements plus every top-level declaration they reach.
393
- const backendSet = new Set<StatementInfo>()
394
- const queue: StatementInfo[] = statements.filter(isBackendStatement)
395
- for (const info of queue) backendSet.add(info)
396
- while (queue.length > 0) {
397
- const info = queue.pop() as StatementInfo
398
- for (const name of [...info.valueRefs, ...info.typeRefs]) {
399
- const target = declaredBy.get(name)
400
- if (target !== undefined && !backendSet.has(target)) {
401
- backendSet.add(target)
402
- queue.push(target)
403
- }
404
- }
405
- // An exported-name statement (`export { loader }`) reaches the declaration it names.
406
- for (const local of info.exports.keys()) {
407
- const target = declaredBy.get(local)
408
- if (target !== undefined && !backendSet.has(target)) {
409
- backendSet.add(target)
410
- queue.push(target)
411
- }
620
+ const into = ts.isImportDeclaration(info.node) ? importedBy : declaredBy
621
+ for (const name of info.declares) into.set(name, info)
622
+ }
623
+ const isTypeDeclaration = (info: StatementInfo): boolean =>
624
+ ts.isInterfaceDeclaration(info.node) || ts.isTypeAliasDeclaration(info.node)
625
+ /** What `info` reads for one half: an export list reads only the locals it exports there. */
626
+ const readsFor = (info: StatementInfo, backend: boolean): Uses => {
627
+ if (info.listed.length === 0) return { value: info.valueRefs, type: info.typeRefs }
628
+ const mine = info.listed.filter((entry) => BACKEND_EXPORTS.has(entry.exported) === backend)
629
+ return {
630
+ value: new Set(mine.filter((entry) => !entry.type).map((entry) => entry.local)),
631
+ type: new Set(mine.filter((entry) => entry.type).map((entry) => entry.local)),
412
632
  }
413
633
  }
414
-
415
- // The frontend half: everything that is not a backend export statement, minus declarations that only
416
- // the backend half needs.
417
634
  const movedLocals = new Set<string>()
418
635
  for (const info of statements) {
419
636
  for (const [local, names] of info.exports)
420
637
  if (names.some((name) => BACKEND_EXPORTS.has(name))) movedLocals.add(local)
421
638
  }
422
- const frontendCandidates = statements.filter((info) => !ts.isImportDeclaration(info.node))
423
- const frontendKeep = new Set<StatementInfo>()
424
- const seed = frontendCandidates.filter(
425
- (info) =>
426
- !backendSet.has(info) ||
427
- (!isBackendStatement(info) && exportsOf(info).length > 0) ||
428
- // a statement with no declaration (a side effect) stays where it ran
429
- (info.declares.size === 0 && info.exports.size === 0),
430
- )
431
- const fqueue = [...seed]
432
- for (const info of fqueue) frontendKeep.add(info)
433
- while (fqueue.length > 0) {
434
- const info = fqueue.pop() as StatementInfo
435
- for (const name of info.valueRefs) {
436
- if (movedLocals.has(name) && !info.declares.has(name)) continue
639
+
640
+ /** Each half's statements. What `shared` holds, both import, so neither half keeps a copy. */
641
+ const partition = (
642
+ shared: ReadonlySet<StatementInfo>,
643
+ ): { backendSet: Set<StatementInfo>; frontendKeep: Set<StatementInfo> } => {
644
+ const local = (name: string): StatementInfo | undefined => {
437
645
  const target = declaredBy.get(name)
438
- if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
439
- frontendKeep.add(target)
440
- fqueue.push(target)
646
+ return target === undefined || shared.has(target) ? undefined : target
647
+ }
648
+ // The backend half: its export statements plus every top-level declaration they reach.
649
+ const backendSet = new Set<StatementInfo>()
650
+ const queue: StatementInfo[] = statements.filter(isBackendStatement)
651
+ for (const info of queue) backendSet.add(info)
652
+ while (queue.length > 0) {
653
+ const info = queue.pop() as StatementInfo
654
+ const reads = readsFor(info, true)
655
+ for (const name of [...reads.value, ...reads.type]) {
656
+ const target = local(name)
657
+ if (target !== undefined && !backendSet.has(target)) {
658
+ backendSet.add(target)
659
+ queue.push(target)
660
+ }
441
661
  }
442
662
  }
443
- for (const name of info.typeRefs) {
444
- if (movedLocals.has(name)) continue
445
- const target = declaredBy.get(name)
446
- if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
447
- frontendKeep.add(target)
448
- fqueue.push(target)
663
+
664
+ // The frontend half: everything that is not a backend export statement, minus declarations that
665
+ // only the backend half needs. An export list that also names backend exports keeps the rest.
666
+ const frontendKeep = new Set<StatementInfo>()
667
+ const seed = statements.filter(
668
+ (info) =>
669
+ !ts.isImportDeclaration(info.node) &&
670
+ !shared.has(info) &&
671
+ (!backendSet.has(info) ||
672
+ exportsOf(info).some((name) => !BACKEND_EXPORTS.has(name)) ||
673
+ // a statement with no declaration (a side effect) stays where it ran
674
+ (info.declares.size === 0 && info.exports.size === 0)),
675
+ )
676
+ const fqueue = [...seed]
677
+ for (const info of fqueue) frontendKeep.add(info)
678
+ while (fqueue.length > 0) {
679
+ const info = fqueue.pop() as StatementInfo
680
+ const reads = readsFor(info, false)
681
+ for (const name of reads.value) {
682
+ if (movedLocals.has(name) && !info.declares.has(name)) continue
683
+ const target = local(name)
684
+ if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
685
+ frontendKeep.add(target)
686
+ fqueue.push(target)
687
+ }
688
+ }
689
+ for (const name of reads.type) {
690
+ if (movedLocals.has(name)) continue
691
+ const target = local(name)
692
+ if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
693
+ frontendKeep.add(target)
694
+ fqueue.push(target)
695
+ }
449
696
  }
450
697
  }
698
+ return { backendSet, frontendKeep }
699
+ }
700
+ let { backendSet, frontendKeep } = partition(new Set())
701
+ const copies = (): StatementInfo[] =>
702
+ [...frontendKeep].filter(
703
+ (info) =>
704
+ backendSet.has(info) &&
705
+ !isBackendStatement(info) &&
706
+ info.declares.size > 0 &&
707
+ !isTypeDeclaration(info),
708
+ )
709
+
710
+ // Constant data both halves read moves to a module beside the route, with the declarations it
711
+ // needs: one definition, which neither half's bundle can drift from.
712
+ const shared = new Set<StatementInfo>()
713
+ const sharedTypes = new Set<StatementInfo>()
714
+ const sharedImports = new Set<string>()
715
+ const unshared = new Map<StatementInfo, string>()
716
+ if (options.sharedFile !== undefined) {
717
+ interface Closure {
718
+ readonly values: Set<StatementInfo>
719
+ readonly types: Set<StatementInfo>
720
+ readonly imports: Set<string>
721
+ }
722
+ /** Why `info` cannot move to the shared module, or `undefined` once it and what it needs are in `closure`. */
723
+ const gather = (info: StatementInfo, closure: Closure): string | undefined => {
724
+ if (closure.values.has(info) || shared.has(info)) return undefined
725
+ const node = info.node
726
+ const reads = new Set<string>()
727
+ let blocker: string | undefined = ""
728
+ if (
729
+ !isBackendStatement(info) &&
730
+ ts.isVariableStatement(node) &&
731
+ (node.declarationList.flags & ts.NodeFlags.Const) !== 0 &&
732
+ !hasModifier(ts, node, ts.SyntaxKind.DeclareKeyword)
733
+ ) {
734
+ blocker = undefined
735
+ for (const declaration of node.declarationList.declarations) {
736
+ blocker =
737
+ ts.isIdentifier(declaration.name) && declaration.initializer !== undefined
738
+ ? dataBlocker(ts, declaration.initializer, (name) => declaredBy.has(name), reads)
739
+ : ""
740
+ if (blocker !== undefined) break
741
+ }
742
+ }
743
+ if (blocker !== undefined)
744
+ return blocker !== "" && importedBy.has(blocker)
745
+ ? `it reads the import "${blocker}"`
746
+ : "it is not constant data"
747
+ closure.values.add(info)
748
+ for (const name of reads) {
749
+ const target = declaredBy.get(name)
750
+ const why = target === undefined ? undefined : gather(target, closure)
751
+ if (why !== undefined) return `it reads "${name}", which ${why.slice(3)}`
752
+ }
753
+ for (const name of info.typeRefs) {
754
+ const why = gatherType(name, closure)
755
+ if (why !== undefined) return why
756
+ }
757
+ return undefined
758
+ }
759
+ const gatherType = (name: string, closure: Closure): string | undefined => {
760
+ const local = declaredBy.get(name)
761
+ if (local === undefined) {
762
+ if (importedBy.has(name)) closure.imports.add(name)
763
+ return undefined
764
+ }
765
+ if (!isTypeDeclaration(local)) {
766
+ const why = gather(local, closure)
767
+ return why === undefined ? undefined : `its type reads "${name}", which ${why.slice(3)}`
768
+ }
769
+ if (closure.types.has(local) || sharedTypes.has(local)) return undefined
770
+ closure.types.add(local)
771
+ for (const ref of [...local.typeRefs, ...local.valueRefs]) {
772
+ const why = gatherType(ref, closure)
773
+ if (why !== undefined) return why
774
+ }
775
+ return undefined
776
+ }
777
+ for (const info of copies()) {
778
+ const closure: Closure = { values: new Set(), types: new Set(), imports: new Set() }
779
+ const why = gather(info, closure)
780
+ if (why !== undefined) {
781
+ unshared.set(info, why)
782
+ continue
783
+ }
784
+ for (const value of closure.values) shared.add(value)
785
+ for (const type of closure.types) sharedTypes.add(type)
786
+ for (const name of closure.imports) sharedImports.add(name)
787
+ }
788
+ if (shared.size > 0) ({ backendSet, frontendKeep } = partition(shared))
451
789
  }
452
790
 
453
791
  // A moved name the frontend still mentions: in a type it becomes `import type`; at runtime it is an
@@ -455,44 +793,88 @@ export function splitRouteSource(
455
793
  const typeImports = new Set<string>()
456
794
  for (const info of frontendKeep) {
457
795
  if (isBackendStatement(info)) continue
796
+ const reads = readsFor(info, false)
458
797
  for (const name of movedLocals) {
459
798
  if (info.declares.has(name)) continue
460
- if (info.valueRefs.has(name))
799
+ if (reads.value.has(name))
461
800
  issues.push(`the frontend uses "${name}" at runtime, but it runs on the server only`)
462
- if (info.typeRefs.has(name) || info.valueRefs.has(name)) typeImports.add(name)
801
+ if (reads.type.has(name) || reads.value.has(name)) typeImports.add(name)
463
802
  }
464
803
  }
465
- for (const info of frontendKeep) {
466
- if (!backendSet.has(info) || isBackendStatement(info) || info.declares.size === 0) continue
467
- const values = [...info.declares].filter(
468
- () => !ts.isInterfaceDeclaration(info.node) && !ts.isTypeAliasDeclaration(info.node),
804
+ for (const info of copies()) {
805
+ const why = unshared.get(info)
806
+ issues.push(
807
+ `"${[...info.declares].join(", ")}" is needed by both halves and was copied into each${why === undefined ? "" : `, since ${why}`}; consider moving it to shared/`,
469
808
  )
470
- if (values.length > 0)
471
- issues.push(
472
- `"${values.join(", ")}" is needed by both halves and was copied into each; consider moving it to shared/`,
473
- )
474
809
  }
475
810
 
476
- const used = (infos: Iterable<StatementInfo>): Set<string> => {
477
- const names = new Set<string>()
478
- for (const info of infos)
479
- for (const name of [...info.valueRefs, ...info.typeRefs]) names.add(name)
480
- return names
481
- }
482
- const backendUses = used(backendSet)
483
- const frontendUses = used([...frontendKeep].filter((info) => !isBackendStatement(info)))
811
+ const uses = (infos: Iterable<StatementInfo>, backend: boolean): Uses => {
812
+ const value = new Set<string>()
813
+ const type = new Set<string>()
814
+ for (const info of infos) {
815
+ const reads = readsFor(info, backend)
816
+ for (const name of reads.value) value.add(name)
817
+ for (const name of reads.type) type.add(name)
818
+ }
819
+ return { value, type }
820
+ }
821
+ const backendUses = uses(backendSet, true)
822
+ const frontendUses = uses(frontendKeep, false)
823
+
824
+ const semi = statements.some((info) => terminatorOf(sf, info.node) !== "") ? ";" : ""
825
+ // The imports the split writes quote the way the file's own imports do.
826
+ const firstImport = statements.find((info) => ts.isImportDeclaration(info.node))?.node
827
+ const quote =
828
+ firstImport !== undefined && ts.isImportDeclaration(firstImport)
829
+ ? (firstImport.moduleSpecifier.getText(sf)[0] ?? '"')
830
+ : '"'
831
+ const sharedNames = [...shared].flatMap((info) => [...info.declares])
832
+ const sharedSpecifier = (() => {
833
+ const file = options.sharedFile ?? ""
834
+ // The halves name the module the way the route names its other relative imports.
835
+ const relative = statements.flatMap((info) =>
836
+ ts.isImportDeclaration(info.node) &&
837
+ ts.isStringLiteral(info.node.moduleSpecifier) &&
838
+ info.node.moduleSpecifier.text.startsWith(".")
839
+ ? [info.node.moduleSpecifier.text]
840
+ : [],
841
+ )
842
+ const extension = relative
843
+ .map((specifier) => /\.(ts|tsx|js|jsx)$/.exec(specifier)?.[1])
844
+ .find((found) => found !== undefined)
845
+ const suffix = extension === undefined ? "" : extension.startsWith("t") ? ".ts" : ".js"
846
+ return `./${file.replace(/\.ts$/, "")}${suffix}`
847
+ })()
848
+ const sharedImport = (half: Uses): string[] => {
849
+ const names = sharedNames
850
+ .filter((name) => half.value.has(name) || half.type.has(name))
851
+ .sort(codeUnitOrder)
852
+ if (names.length === 0) return []
853
+ const typeOnly = names.every((name) => !half.value.has(name))
854
+ return [
855
+ `\nimport ${typeOnly ? "type " : ""}{ ${names.join(", ")} } from ${quote}${sharedSpecifier}${quote}${semi}`,
856
+ ]
857
+ }
858
+ // The page still exports what it exported, now from the shared module.
859
+ const reexported = [...shared].flatMap((info) =>
860
+ [...info.exports].flatMap(([local, names]) =>
861
+ names.map((name) => (name === local ? local : `${local} as ${name}`)),
862
+ ),
863
+ )
484
864
 
485
865
  const backendTexts: string[] = []
486
866
  const frontendTexts: string[] = []
487
867
  let afterImports = 0
868
+ let backendAfterImports = 0
488
869
  for (const info of statements) {
489
870
  const node = info.node
490
871
  if (ts.isImportDeclaration(node)) {
491
- const back = filterImport(ts, sf, node, (name) => backendUses.has(name))
872
+ const back = filterImport(ts, sf, node, backendUses, true)
492
873
  if (back !== undefined) backendTexts.push(node.importClause ? back : "")
493
- const front = filterImport(ts, sf, node, (name) => frontendUses.has(name))
874
+ const front = filterImport(ts, sf, node, frontendUses, false)
494
875
  if (front !== undefined) frontendTexts.push(front)
495
876
  afterImports = frontendTexts.length
877
+ backendAfterImports = backendTexts.length
496
878
  continue
497
879
  }
498
880
  if (isBackendStatement(info)) {
@@ -518,14 +900,17 @@ export function splitRouteSource(
518
900
  if (frontendKeep.has(info)) frontendTexts.push(info.text)
519
901
  }
520
902
  // After the other imports: the nearest relative path sorts last.
521
- if (typeImports.size > 0) {
522
- const semi = statements.some((info) => terminatorOf(sf, info.node) !== "") ? ";" : ""
523
- frontendTexts.splice(
524
- afterImports,
525
- 0,
526
- `\nimport type { ${[...typeImports].sort().join(", ")} } from "${backendSpecifier}"${semi}`,
903
+ const frontendImports = sharedImport(frontendUses)
904
+ if (reexported.length > 0)
905
+ frontendImports.push(
906
+ `\nexport { ${reexported.join(", ")} } from ${quote}${sharedSpecifier}${quote}${semi}`,
527
907
  )
528
- }
908
+ if (typeImports.size > 0)
909
+ frontendImports.push(
910
+ `\nimport type { ${[...typeImports].sort().join(", ")} } from ${quote}${backendSpecifier}${quote}${semi}`,
911
+ )
912
+ frontendTexts.splice(afterImports, 0, ...frontendImports)
913
+ backendTexts.splice(backendAfterImports, 0, ...sharedImport(backendUses))
529
914
  // A JSX pragma counts only in the file's leading comments, and the backend half has no JSX.
530
915
  const pragmas = (ts.getLeadingCommentRanges(source, 0) ?? [])
531
916
  .map((range) => source.slice(range.pos, range.end))
@@ -536,12 +921,34 @@ export function splitRouteSource(
536
921
  text,
537
922
  )
538
923
  const frontend = lift(joinStatements(frontendTexts))
539
- return {
924
+ let sharedText: string | undefined
925
+ if (shared.size > 0) {
926
+ const texts: string[] = []
927
+ const typeUses: Uses = { value: new Set(), type: sharedImports }
928
+ for (const info of statements) {
929
+ if (ts.isImportDeclaration(info.node)) {
930
+ const kept = filterImport(ts, sf, info.node, typeUses, true)
931
+ if (kept !== undefined && info.node.importClause !== undefined) texts.push(kept)
932
+ } else if (shared.has(info) || sharedTypes.has(info)) {
933
+ texts.push(withExport(ts, sf, info))
934
+ }
935
+ }
936
+ sharedText = lift(joinStatements(texts))
937
+ }
938
+ const result: SplitResult = {
540
939
  frontend: pragmas.length > 0 ? `${pragmas.join("\n")}\n${frontend}` : frontend,
541
940
  backend: lift(joinStatements(backendTexts)),
542
941
  moved: [...new Set(moved)].sort(),
543
942
  issues,
544
943
  }
944
+ return sharedText === undefined ? result : { ...result, shared: sharedText }
945
+ }
946
+
947
+ /** A declaration the shared module holds is exported, so either half can import it. */
948
+ function withExport(ts: typeof TS, sf: TS.SourceFile, info: StatementInfo): string {
949
+ if (hasModifier(ts, info.node, ts.SyntaxKind.ExportKeyword)) return info.text
950
+ const at = info.node.getStart(sf) - info.node.getFullStart()
951
+ return `${info.text.slice(0, at)}export ${info.text.slice(at)}`
545
952
  }
546
953
 
547
954
  /** A helper the backend half copies keeps its declaration; an `export` on it would add a backend export. */
@@ -729,6 +1136,129 @@ function importsOf(ts: typeof TS, file: string, text: string): ImportRef[] {
729
1136
  return refs
730
1137
  }
731
1138
 
1139
+ /** One `import.meta.glob(...)` call and the spans of its pattern literals, quotes excluded. */
1140
+ interface GlobCall {
1141
+ readonly patterns: ReadonlyArray<{
1142
+ readonly text: string
1143
+ readonly start: number
1144
+ readonly end: number
1145
+ }>
1146
+ /** `false` when a pattern is computed, so what the call loads cannot be read. */
1147
+ readonly literal: boolean
1148
+ readonly line: number
1149
+ }
1150
+
1151
+ /** The `import.meta.glob` calls of a JS/TS module. */
1152
+ function globCalls(ts: typeof TS, file: string, text: string): GlobCall[] {
1153
+ if (!/\.[cm]?[jt]sx?$/.test(file) || !text.includes("import.meta.glob")) return []
1154
+ const sf = ts.createSourceFile(
1155
+ file,
1156
+ text,
1157
+ ts.ScriptTarget.Latest,
1158
+ true,
1159
+ file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
1160
+ )
1161
+ const calls: GlobCall[] = []
1162
+ const visit = (node: TS.Node): void => {
1163
+ if (
1164
+ ts.isCallExpression(node) &&
1165
+ ts.isPropertyAccessExpression(node.expression) &&
1166
+ node.expression.name.text === "glob" &&
1167
+ ts.isMetaProperty(node.expression.expression) &&
1168
+ node.expression.expression.keywordToken === ts.SyntaxKind.ImportKeyword
1169
+ ) {
1170
+ const arg = node.arguments[0]
1171
+ const elements =
1172
+ arg === undefined ? [] : ts.isArrayLiteralExpression(arg) ? [...arg.elements] : [arg]
1173
+ const literals = elements.filter(ts.isStringLiteralLike)
1174
+ const literal = literals.length > 0 && literals.length === elements.length
1175
+ calls.push({
1176
+ patterns: literal
1177
+ ? literals.map((element) => ({
1178
+ text: element.text,
1179
+ start: element.getStart(sf) + 1,
1180
+ end: element.getEnd() - 1,
1181
+ }))
1182
+ : [],
1183
+ literal,
1184
+ line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1,
1185
+ })
1186
+ }
1187
+ ts.forEachChild(node, visit)
1188
+ }
1189
+ visit(sf)
1190
+ return calls
1191
+ }
1192
+
1193
+ /** A glob pattern written in `file` as an app-relative glob, by Vite's rules: `./` and `../` from the
1194
+ * file's folder, `/` from the app root. `undefined` for any other shape, such as an alias. */
1195
+ function appGlob(file: string, pattern: string): string | undefined {
1196
+ if (pattern.startsWith("/")) return pattern.slice(1)
1197
+ if (!pattern.startsWith("./") && !pattern.startsWith("../")) return undefined
1198
+ const at = posix.normalize(posix.join(posix.dirname(file), pattern))
1199
+ return at.startsWith("../") ? undefined : at
1200
+ }
1201
+
1202
+ /** The files among `files` a glob call in `file` loads, a `!` pattern excluding; `undefined` when a
1203
+ * pattern cannot be read from the app. */
1204
+ function globTargets(
1205
+ file: string,
1206
+ patterns: readonly string[],
1207
+ files: Iterable<string>,
1208
+ ): string[] | undefined {
1209
+ const include: Bun.Glob[] = []
1210
+ const exclude: Bun.Glob[] = []
1211
+ for (const raw of patterns) {
1212
+ const at = appGlob(file, raw.startsWith("!") ? raw.slice(1) : raw)
1213
+ if (at === undefined) return undefined
1214
+ ;(raw.startsWith("!") ? exclude : include).push(new Bun.Glob(at))
1215
+ }
1216
+ return [...files].filter(
1217
+ (candidate) =>
1218
+ candidate !== file &&
1219
+ include.some((glob) => glob.match(candidate)) &&
1220
+ !exclude.some((glob) => glob.match(candidate)),
1221
+ )
1222
+ }
1223
+
1224
+ /**
1225
+ * `pattern`, written in `from` (now `to`), re-pointed at the folder its matches `before` moved to: the
1226
+ * part before the first wildcard is the folder, and every match must keep its path below it.
1227
+ * `undefined` when the matches did not move as one folder.
1228
+ */
1229
+ function repointGlob(
1230
+ from: string,
1231
+ to: string,
1232
+ pattern: string,
1233
+ before: readonly string[],
1234
+ newPath: (file: string) => string,
1235
+ ): string | undefined {
1236
+ const negated = pattern.startsWith("!")
1237
+ const written = negated ? pattern.slice(1) : pattern
1238
+ const at = appGlob(from, written)
1239
+ if (at === undefined) return undefined
1240
+ const segments = at.split("/")
1241
+ const wild = segments.findIndex((segment) => /[*?[\]{}]/.test(segment))
1242
+ const base = (wild === -1 ? segments.slice(0, -1) : segments.slice(0, wild)).join("/")
1243
+ const rest = segments.slice(base === "" ? 0 : base.split("/").length).join("/")
1244
+ let moved: string | undefined
1245
+ for (const file of before) {
1246
+ if (base !== "" && !file.startsWith(`${base}/`)) continue
1247
+ const tail = base === "" ? file : file.slice(base.length + 1)
1248
+ const now = newPath(file)
1249
+ if (!now.endsWith(`/${tail}`) && now !== tail) return undefined
1250
+ const folder = now === tail ? "" : now.slice(0, now.length - tail.length - 1)
1251
+ if (moved !== undefined && folder !== moved) return undefined
1252
+ moved = folder
1253
+ }
1254
+ if (moved === undefined) return pattern
1255
+ const folder = posix.relative(posix.dirname(to), moved)
1256
+ const next = written.startsWith("/")
1257
+ ? `/${moved === "" ? "" : `${moved}/`}${rest}`
1258
+ : `${folder === "" ? "." : folder.startsWith("..") ? folder : `./${folder}`}/${rest}`
1259
+ return negated ? `!${next}` : next
1260
+ }
1261
+
732
1262
  /** Resolve a relative specifier against the file map, the way a bundler would. */
733
1263
  function resolveIn(
734
1264
  files: ReadonlySet<string>,
@@ -736,7 +1266,7 @@ function resolveIn(
736
1266
  specifier: string,
737
1267
  ): string | undefined {
738
1268
  if (!specifier.startsWith(".")) return undefined
739
- const clean = specifier.replace(/[?#].*$/, "")
1269
+ const clean = withoutQuery(specifier)
740
1270
  const base = posix.normalize(posix.join(posix.dirname(from), clean))
741
1271
  const candidates = [
742
1272
  base,
@@ -771,8 +1301,140 @@ function liveSpecifierSpans(
771
1301
  return spans
772
1302
  }
773
1303
 
1304
+ /**
1305
+ * The comment spans of a JS/TS module: the leading and trailing trivia of each token. Empty when the
1306
+ * compiler cannot walk the tokens, so every mention in the file stays an issue.
1307
+ */
1308
+ function triviaCommentRanges(
1309
+ ts: typeof TS,
1310
+ file: string,
1311
+ text: string,
1312
+ ): Array<readonly [number, number]> {
1313
+ const spans = new Map<number, number>()
1314
+ const add = (ranges: readonly TS.CommentRange[] | undefined): void => {
1315
+ for (const range of ranges ?? []) spans.set(range.pos, range.end)
1316
+ }
1317
+ try {
1318
+ const kind = /x$/.test(file) ? ts.ScriptKind.TSX : ts.ScriptKind.TS
1319
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind)
1320
+ const visit = (node: TS.Node): void => {
1321
+ // A JSDoc block is itself one of the comments its token's trivia holds; JSX text is not trivia.
1322
+ if (node.kind >= ts.SyntaxKind.FirstJSDocNode && node.kind <= ts.SyntaxKind.LastJSDocNode)
1323
+ return
1324
+ if (ts.isJsxText(node)) return
1325
+ const children = node.getChildren(source)
1326
+ if (children.length > 0) {
1327
+ for (const child of children) visit(child)
1328
+ return
1329
+ }
1330
+ add(ts.getLeadingCommentRanges(text, node.pos))
1331
+ add(ts.getTrailingCommentRanges(text, node.end))
1332
+ }
1333
+ visit(source)
1334
+ } catch {
1335
+ return []
1336
+ }
1337
+ return [...spans]
1338
+ }
1339
+
774
1340
  const OWN_DIR = new Set(["import.meta.dir", "import.meta.dirname", "__dirname"])
775
1341
 
1342
+ /**
1343
+ * The path `relative` names from the folder of `from`, named from the folder of `to`; `undefined` when
1344
+ * neither the file nor the target moved, so a file that stays keeps its spelling.
1345
+ */
1346
+ function rebaseRelative(
1347
+ from: string,
1348
+ to: string,
1349
+ relative: string,
1350
+ locate: (target: string) => string,
1351
+ ): string | undefined {
1352
+ const before = posix.normalize(posix.join(posix.dirname(from), relative))
1353
+ const target = locate(before)
1354
+ if (from === to && target === before) return undefined
1355
+ const next = posix.relative(posix.dirname(to), target) || "."
1356
+ return relative.endsWith("/") && next !== "." ? `${next}/` : next
1357
+ }
1358
+
1359
+ /** A shell script's own folder: `$(dirname "$0")`, `$(dirname "${BASH_SOURCE[0]}")`, `${0%/*}`. */
1360
+ const SHELL_OWN_DIR =
1361
+ /\$\(\s*dirname\s+("?)\$(?:0|\{BASH_SOURCE(?:\[0\])?\}|BASH_SOURCE)\1\s*\)|`dirname\s+("?)\$0\2`|\$\{(?:0|BASH_SOURCE(?:\[0\])?)%\/\*\}/g
1362
+ const SHELL_FILE = /\.(?:sh|bash|zsh)$/
1363
+
1364
+ /**
1365
+ * Re-point the paths a shell script moving from `from` to `to` builds from its own folder
1366
+ * (`cd "$(dirname "$0")/.."`), as `rebaseOwnPaths` does for a module. Returns the new text and the
1367
+ * first use of the script's folder with no literal path after it, which the migration cannot follow.
1368
+ */
1369
+ function rebaseShellPaths(
1370
+ from: string,
1371
+ to: string,
1372
+ text: string,
1373
+ locate: (target: string) => string,
1374
+ ): { readonly text: string; readonly unfollowed: string | undefined } {
1375
+ let unfollowed: string | undefined
1376
+ const edits: Array<{ start: number; end: number; text: string }> = []
1377
+ for (const match of text.matchAll(SHELL_OWN_DIR)) {
1378
+ const start = match.index + match[0].length
1379
+ const trailing = /^\/([\w.@-]+(?:\/[\w.@-]+)*\/?)/.exec(text.slice(start))?.[1]
1380
+ if (trailing === undefined) {
1381
+ unfollowed ??= match[0]
1382
+ continue
1383
+ }
1384
+ const rebased = rebaseRelative(from, to, trailing, locate)
1385
+ if (rebased !== undefined)
1386
+ edits.push({ start, end: start + 1 + trailing.length, text: `/${rebased}` })
1387
+ }
1388
+ let next = text
1389
+ for (const edit of edits.reverse())
1390
+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end)
1391
+ return { text: next, unfollowed }
1392
+ }
1393
+
1394
+ interface OwnDirAlias {
1395
+ readonly name: TS.Identifier
1396
+ readonly initializer: TS.Expression
1397
+ }
1398
+
1399
+ /**
1400
+ * Top-level `const dir = import.meta.dir` (or `.dirname`, `__dirname`) bindings, by name. A name the
1401
+ * file declares anywhere else (a parameter, an inner `let`) is left out: a use could be that binding.
1402
+ */
1403
+ function ownDirAliases(ts: typeof TS, sf: TS.SourceFile): Map<string, OwnDirAlias> {
1404
+ const aliases = new Map<string, OwnDirAlias>()
1405
+ for (const statement of sf.statements) {
1406
+ if (!ts.isVariableStatement(statement)) continue
1407
+ if ((statement.declarationList.flags & ts.NodeFlags.Const) === 0) continue
1408
+ for (const declaration of statement.declarationList.declarations) {
1409
+ const { name, initializer } = declaration
1410
+ if (
1411
+ ts.isIdentifier(name) &&
1412
+ initializer !== undefined &&
1413
+ OWN_DIR.has(initializer.getText(sf))
1414
+ )
1415
+ aliases.set(name.text, { name, initializer })
1416
+ }
1417
+ }
1418
+ if (aliases.size === 0) return aliases
1419
+ const declared = new Map<string, number>()
1420
+ const count = (node: TS.Node): void => {
1421
+ const name =
1422
+ ts.isVariableDeclaration(node) ||
1423
+ ts.isParameter(node) ||
1424
+ ts.isFunctionDeclaration(node) ||
1425
+ ts.isClassDeclaration(node) ||
1426
+ ts.isBindingElement(node)
1427
+ ? node.name
1428
+ : undefined
1429
+ if (name !== undefined && ts.isIdentifier(name))
1430
+ declared.set(name.text, (declared.get(name.text) ?? 0) + 1)
1431
+ ts.forEachChild(node, count)
1432
+ }
1433
+ count(sf)
1434
+ for (const name of [...aliases.keys()]) if (declared.get(name) !== 1) aliases.delete(name)
1435
+ return aliases
1436
+ }
1437
+
776
1438
  /**
777
1439
  * Re-point the paths a module moving from `from` to `to` builds from its own location, so each still
778
1440
  * reaches what it did: `join(import.meta.dir, "..", "x")` (or `resolve`), `import.meta.dir + "/../x"`,
@@ -796,8 +1458,10 @@ function rebaseOwnPaths(
796
1458
  )
797
1459
  const edits: Array<{ start: number; end: number; text: string }> = []
798
1460
  const followed: Array<readonly [number, number]> = []
1461
+ const aliases = ownDirAliases(ts, sf)
799
1462
  const isOwnDir = (node: TS.Node | undefined): node is TS.Expression =>
800
- node !== undefined && OWN_DIR.has(node.getText(sf))
1463
+ node !== undefined &&
1464
+ (OWN_DIR.has(node.getText(sf)) || (ts.isIdentifier(node) && aliases.has(node.text)))
801
1465
  const isLiteral = (
802
1466
  node: TS.Node | undefined,
803
1467
  ): node is TS.StringLiteral | TS.NoSubstitutionTemplateLiteral =>
@@ -806,15 +1470,17 @@ function rebaseOwnPaths(
806
1470
  const quote = node.getText(sf)[0] ?? '"'
807
1471
  return `${quote}${value}${quote}`
808
1472
  }
809
- // The path `relative` names from the module's old folder, named from its new folder.
810
- const rebased = (relative: string): string => {
811
- const target = locate(posix.normalize(posix.join(posix.dirname(from), relative)))
812
- const next = posix.relative(posix.dirname(to), target) || "."
813
- return relative.endsWith("/") && next !== "." ? `${next}/` : next
814
- }
815
- const follow = (anchor: TS.Node, start: number, end: number, replacement: string): void => {
1473
+ const rebased = (relative: string): string | undefined =>
1474
+ rebaseRelative(from, to, relative, locate)
1475
+ const follow = (
1476
+ anchor: TS.Node,
1477
+ start: number,
1478
+ end: number,
1479
+ replacement: string | undefined,
1480
+ ): void => {
816
1481
  followed.push([anchor.getStart(sf), anchor.getEnd()])
817
- if (text.slice(start, end) !== replacement) edits.push({ start, end, text: replacement })
1482
+ if (replacement !== undefined && text.slice(start, end) !== replacement)
1483
+ edits.push({ start, end, text: replacement })
818
1484
  }
819
1485
 
820
1486
  const visit = (node: TS.Node): void => {
@@ -832,8 +1498,12 @@ function rebaseOwnPaths(
832
1498
  !(callee.endsWith("resolve") && parts.some((part) => part.text.startsWith("/")))
833
1499
  ) {
834
1500
  const next = rebased(posix.join(...parts.map((part) => part.text)))
835
- const segments = parts.length === 1 ? [next] : next.split("/").filter((s) => s !== "")
836
- const replacement = segments.map((segment) => quoted(first, segment)).join(", ")
1501
+ const replacement =
1502
+ next === undefined
1503
+ ? undefined
1504
+ : (parts.length === 1 ? [next] : next.split("/").filter((s) => s !== ""))
1505
+ .map((segment) => quoted(first, segment))
1506
+ .join(", ")
837
1507
  follow(dir, first.getStart(sf), last.getEnd(), replacement)
838
1508
  return
839
1509
  }
@@ -850,7 +1520,7 @@ function rebaseOwnPaths(
850
1520
  node.left,
851
1521
  node.right.getStart(sf),
852
1522
  node.right.getEnd(),
853
- quoted(node.right, `/${next}`),
1523
+ next === undefined ? undefined : quoted(node.right, `/${next}`),
854
1524
  )
855
1525
  return
856
1526
  }
@@ -858,7 +1528,8 @@ function rebaseOwnPaths(
858
1528
  const span = node.templateSpans[0]
859
1529
  if (span !== undefined && isOwnDir(span.expression) && span.literal.text.startsWith("/")) {
860
1530
  const next = rebased(span.literal.text.slice(1) || ".")
861
- const replacement = `\`\${${span.expression.getText(sf)}}/${next}\``
1531
+ const replacement =
1532
+ next === undefined ? undefined : `\`\${${span.expression.getText(sf)}}/${next}\``
862
1533
  follow(span.expression, node.getStart(sf), node.getEnd(), replacement)
863
1534
  return
864
1535
  }
@@ -872,7 +1543,8 @@ function rebaseOwnPaths(
872
1543
  const path = node.arguments[0]
873
1544
  if (isLiteral(path) && !/^(?:\/|[a-z][a-z\d+.-]*:)/i.test(path.text)) {
874
1545
  const next = rebased(path.text)
875
- const replacement = quoted(path, next.startsWith("..") ? next : `./${next}`)
1546
+ const replacement =
1547
+ next === undefined ? undefined : quoted(path, next.startsWith("..") ? next : `./${next}`)
876
1548
  follow(node.arguments[1], path.getStart(sf), path.getEnd(), replacement)
877
1549
  return
878
1550
  }
@@ -880,6 +1552,20 @@ function rebaseOwnPaths(
880
1552
  ts.forEachChild(node, visit)
881
1553
  }
882
1554
  visit(sf)
1555
+ // An alias whose every use was re-pointed is followed too; one left in a call the migration cannot
1556
+ // read keeps its `import.meta.dir` unfollowed.
1557
+ for (const [name, declaration] of aliases) {
1558
+ const isFollowed = (node: TS.Node): boolean =>
1559
+ followed.some(([start, end]) => start <= node.getStart(sf) && node.getEnd() <= end)
1560
+ const uses: TS.Identifier[] = []
1561
+ const collect = (node: TS.Node): void => {
1562
+ if (ts.isIdentifier(node) && node.text === name && node !== declaration.name) uses.push(node)
1563
+ ts.forEachChild(node, collect)
1564
+ }
1565
+ collect(sf)
1566
+ if (uses.every(isFollowed))
1567
+ followed.push([declaration.initializer.getStart(sf), declaration.initializer.getEnd()])
1568
+ }
883
1569
 
884
1570
  const unfollowed = [...text.matchAll(new RegExp(SELF_LOCATION.source, "g"))].find(
885
1571
  (match) => !followed.some(([start, end]) => start <= match.index && match.index < end),
@@ -898,7 +1584,7 @@ function respecify(
898
1584
  newFrom: string,
899
1585
  newTarget: string,
900
1586
  ): string {
901
- const query = /[?#].*$/.exec(original)?.[0] ?? ""
1587
+ const query = original.slice(withoutQuery(original).length)
902
1588
  const clean = original.slice(0, original.length - query.length)
903
1589
  let target = newTarget
904
1590
  const writtenExt = extname(clean)
@@ -928,16 +1614,16 @@ function rebase(specifier: string, from: string, newFrom: string): string | unde
928
1614
  }
929
1615
 
930
1616
  /** A split route as an importer sees it: the names that left it, and how this importer spells the
931
- * backend half they went to (`undefined` when an alias cannot name it). */
1617
+ * backend half they went to. */
932
1618
  interface SplitTarget {
933
1619
  readonly backend: string
934
1620
  readonly moved: ReadonlySet<string>
935
- readonly specifier: string | undefined
1621
+ readonly specifier: string
936
1622
  }
937
1623
 
938
1624
  /** `specifier` re-pointed from a split route to its backend half, in the author's extension style. */
939
1625
  function backendSpecifier(specifier: string, route: string, backend: string, from: string): string {
940
- const query = /[?#].*$/.exec(specifier)?.[0] ?? ""
1626
+ const query = specifier.slice(withoutQuery(specifier).length)
941
1627
  const written = extname(specifier.slice(0, specifier.length - query.length))
942
1628
  const stem = backend.slice(0, -extname(backend).length)
943
1629
  const target =
@@ -953,8 +1639,7 @@ function backendSpecifier(specifier: string, route: string, backend: string, fro
953
1639
  /**
954
1640
  * Point an importer's named imports of a split route's moved exports (`loader`, `action`, ...) at the
955
1641
  * backend half, splitting a statement that also names what stayed. What cannot be rewritten (a
956
- * namespace or dynamic import that reads a moved name, `export *`, an alias with no target there) is
957
- * returned as an issue.
1642
+ * namespace or dynamic import that reads a moved name, `export *`) is returned as an issue.
958
1643
  */
959
1644
  function redirectMovedImports(
960
1645
  ts: typeof TS,
@@ -1010,12 +1695,6 @@ function redirectMovedImports(
1010
1695
  split.moved.has((el.propertyName ?? el.name).text)
1011
1696
  const moved = elements.filter(isMoved)
1012
1697
  if (moved.length === 0) return
1013
- if (split.specifier === undefined) {
1014
- issues.push(
1015
- `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`,
1016
- )
1017
- return
1018
- }
1019
1698
  redirects.push({
1020
1699
  names: moved.map((el) => (el.propertyName ?? el.name).text),
1021
1700
  from,
@@ -1049,14 +1728,29 @@ function redirectMovedImports(
1049
1728
  node.arguments[0] !== undefined &&
1050
1729
  ts.isStringLiteralLike(node.arguments[0])
1051
1730
  ) {
1052
- const from = node.arguments[0].text
1731
+ const literal = node.arguments[0]
1732
+ const from = literal.text
1053
1733
  const split = splitOf(from)
1054
1734
  const reads =
1055
1735
  split === undefined ? [] : mentioned(split, (name) => new RegExp(`\\b${name}\\b`))
1056
- if (split !== undefined && reads.length > 0)
1057
- issues.push(
1058
- `loads "${from}" with import() and mentions ${quoted(reads)}, which moved to "${split.backend}"; load the backend half for them by hand`,
1059
- )
1736
+ if (split !== undefined && reads.length > 0) {
1737
+ const names = dynamicReads(ts, sf, node)
1738
+ if (
1739
+ names !== undefined &&
1740
+ names.length > 0 &&
1741
+ names.every((name) => split.moved.has(name))
1742
+ ) {
1743
+ edits.push({
1744
+ start: literal.getStart(sf) + 1,
1745
+ end: literal.getEnd() - 1,
1746
+ text: split.specifier,
1747
+ })
1748
+ redirects.push({ names, from, to: split.specifier })
1749
+ } else
1750
+ issues.push(
1751
+ `loads "${from}" with import() and mentions ${quoted(reads)}, which moved to "${split.backend}"; load the backend half for them by hand`,
1752
+ )
1753
+ }
1060
1754
  }
1061
1755
  ts.forEachChild(node, visit)
1062
1756
  }
@@ -1067,6 +1761,209 @@ function redirectMovedImports(
1067
1761
  return { text: out, issues, redirects }
1068
1762
  }
1069
1763
 
1764
+ /**
1765
+ * The exports code reads from what `import()` loads: off the awaited module (`(await import(x)).a`),
1766
+ * through a destructuring, or through a variable used only as `mod.a`. `undefined` when the module
1767
+ * goes anywhere else, so its reads cannot be listed.
1768
+ */
1769
+ function dynamicReads(
1770
+ ts: typeof TS,
1771
+ sf: TS.SourceFile,
1772
+ call: TS.CallExpression,
1773
+ ): string[] | undefined {
1774
+ let node: TS.Node = call
1775
+ if (!ts.isAwaitExpression(node.parent)) return undefined
1776
+ node = node.parent
1777
+ while (ts.isParenthesizedExpression(node.parent)) node = node.parent
1778
+ const parent = node.parent
1779
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === node) return [parent.name.text]
1780
+ if (!ts.isVariableDeclaration(parent) || parent.initializer !== node) return undefined
1781
+ const binding = parent.name
1782
+ if (ts.isObjectBindingPattern(binding)) {
1783
+ const names: string[] = []
1784
+ for (const element of binding.elements) {
1785
+ const key = element.propertyName ?? element.name
1786
+ if (
1787
+ element.dotDotDotToken !== undefined ||
1788
+ !(ts.isIdentifier(key) || ts.isStringLiteral(key))
1789
+ )
1790
+ return undefined
1791
+ names.push(key.text)
1792
+ }
1793
+ return names
1794
+ }
1795
+ if (!ts.isIdentifier(binding)) return undefined
1796
+ const names = new Set<string>()
1797
+ let escapes = false
1798
+ const visit = (current: TS.Node): void => {
1799
+ if (ts.isIdentifier(current) && current.text === binding.text && current !== binding) {
1800
+ const owner = current.parent
1801
+ if (ts.isPropertyAccessExpression(owner) && owner.expression === current)
1802
+ names.add(owner.name.text)
1803
+ else if (
1804
+ !(
1805
+ (ts.isPropertyAccessExpression(owner) ||
1806
+ ts.isPropertyAssignment(owner) ||
1807
+ ts.isPropertyDeclaration(owner) ||
1808
+ ts.isMethodDeclaration(owner)) &&
1809
+ owner.name === current
1810
+ )
1811
+ )
1812
+ escapes = true
1813
+ }
1814
+ ts.forEachChild(current, visit)
1815
+ }
1816
+ visit(sf)
1817
+ return escapes ? undefined : [...names].sort(codeUnitOrder)
1818
+ }
1819
+
1820
+ /** A `workspaces` glob as a matcher over package-relative folder paths. */
1821
+ function workspacePattern(glob: string): RegExp {
1822
+ const source = glob
1823
+ .replace(/^\.\//, "")
1824
+ .replace(/\/+$/, "")
1825
+ .split("/")
1826
+ .map((segment) =>
1827
+ segment === "**"
1828
+ ? "(?:[^/]+/)*?[^/]*"
1829
+ : segment.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", "[^/]*"),
1830
+ )
1831
+ .join("/")
1832
+ return new RegExp(`^${source}$`)
1833
+ }
1834
+
1835
+ /**
1836
+ * The workspace an app belongs to: the nearest folder above it whose package.json declares
1837
+ * `workspaces` that include the app, and the package folders those globs (less any `!` exclusion)
1838
+ * name, other than the app and any folder that holds it. `undefined` outside one.
1839
+ */
1840
+ function workspaceSiblings(root: string): readonly string[] | undefined {
1841
+ for (let dir = dirname(root), depth = 0; depth < 8; dir = dirname(dir), depth += 1) {
1842
+ let declared: unknown
1843
+ try {
1844
+ declared = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).workspaces
1845
+ } catch {
1846
+ declared = undefined
1847
+ }
1848
+ const listed = Array.isArray(declared)
1849
+ ? declared
1850
+ : typeof declared === "object" && declared !== null
1851
+ ? Reflect.get(declared, "packages")
1852
+ : undefined
1853
+ if (Array.isArray(listed)) {
1854
+ const globs = listed.filter((glob): glob is string => typeof glob === "string")
1855
+ const include = globs.filter((glob) => !glob.startsWith("!")).map(workspacePattern)
1856
+ const exclude = globs
1857
+ .filter((glob) => glob.startsWith("!"))
1858
+ .map((glob) => workspacePattern(glob.slice(1)))
1859
+ const member = (rel: string): boolean =>
1860
+ include.some((pattern) => pattern.test(rel)) &&
1861
+ !exclude.some((pattern) => pattern.test(rel))
1862
+ // The nearest declaration decides, as package managers read it.
1863
+ if (!member(toPosix(relative(dir, root)))) return undefined
1864
+ const packages: string[] = []
1865
+ const walk = (folder: string, depth: number): void => {
1866
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
1867
+ if (!entry.isDirectory() || entry.name.startsWith(".") || SKIP_DIRS.has(entry.name))
1868
+ continue
1869
+ const full = join(folder, entry.name)
1870
+ const rel = toPosix(relative(dir, full))
1871
+ if (exclude.some((pattern) => pattern.test(rel))) continue
1872
+ if (member(rel) && existsSync(join(full, "package.json"))) {
1873
+ const inside = toPosix(relative(full, root))
1874
+ if (inside.startsWith("../") || isAbsolute(inside)) packages.push(full)
1875
+ continue
1876
+ }
1877
+ if (depth < 4) walk(full, depth + 1)
1878
+ }
1879
+ }
1880
+ walk(dir, 0)
1881
+ return packages.sort()
1882
+ }
1883
+ if (dirname(dir) === dir) return undefined
1884
+ }
1885
+ return undefined
1886
+ }
1887
+
1888
+ /**
1889
+ * Where code in a workspace sibling names an app file that moves: a relative import into the app, or
1890
+ * the file's path in a string or command (`bun -e 'import("./src/x.ts")'` with the app as its working
1891
+ * directory). Only files that mention the app's folder or package name are read further, and a path
1892
+ * the sibling's own package holds is its own file. Every line that names a path is listed, each marked
1893
+ * when it lies only in a comment. Report-only: the migration never edits a sibling.
1894
+ */
1895
+ function siblingReferences(
1896
+ ts: typeof TS,
1897
+ root: string,
1898
+ pkg: string,
1899
+ file: string,
1900
+ text: string,
1901
+ moves: ReadonlyMap<string, string>,
1902
+ known: ReadonlySet<string>,
1903
+ ownName: string | undefined,
1904
+ ): Array<{
1905
+ readonly from: string
1906
+ readonly to: string
1907
+ readonly lines: readonly number[]
1908
+ readonly commentLines: readonly number[]
1909
+ }> {
1910
+ const abs = join(pkg, file)
1911
+ // A process started in the app (`cwd: \`${repo}apps/web\``) reads its paths from the app root.
1912
+ const runsInApp = new RegExp(
1913
+ `\\bcwd\\s*:[^,\\n]*\\b${escapeRegExp(posix.basename(toPosix(root)))}\\b`,
1914
+ ).test(text)
1915
+ const comments = /\.[cm]?[jt]sx?$/.test(file) ? triviaCommentRanges(ts, file, text) : []
1916
+ const found = new Map<string, { to: string; lines: Set<number>; commentLines: Set<number> }>()
1917
+ const report = (from: string, index: number, length: number): void => {
1918
+ const to = moves.get(from)
1919
+ if (to === undefined) return
1920
+ const entry = found.get(from) ?? { to, lines: new Set(), commentLines: new Set() }
1921
+ found.set(from, entry)
1922
+ const line = text.slice(0, index).split("\n").length
1923
+ const inComment = comments.some(([start, end]) => start <= index && index + length <= end)
1924
+ ;(inComment ? entry.commentLines : entry.lines).add(line)
1925
+ }
1926
+ if (/\.(?:[cm]?[jt]sx?)$/.test(file)) {
1927
+ for (const { specifier } of importsOf(ts, file, text)) {
1928
+ const clean = withoutQuery(specifier)
1929
+ const inApp = clean.startsWith(".")
1930
+ ? toPosix(relative(root, resolve(dirname(abs), clean)))
1931
+ : ownName !== undefined && clean.startsWith(`${ownName}/`)
1932
+ ? clean.slice(ownName.length + 1)
1933
+ : undefined
1934
+ if (inApp === undefined || inApp.startsWith("../") || isAbsolute(inApp)) continue
1935
+ const target = resolveIn(known, "index.ts", `./${inApp}`)
1936
+ if (target !== undefined) report(target, text.indexOf(specifier), specifier.length)
1937
+ }
1938
+ }
1939
+ for (const from of moves.keys()) {
1940
+ const stem = SOURCE_FILE.test(from)
1941
+ ? from.slice(0, from.length - extname(from).length)
1942
+ : undefined
1943
+ const pattern = new RegExp(
1944
+ `(?<![\\w.-])(?:\\./)?(?:${escapeRegExp(from)}(?![\\w])${stem === undefined ? "" : `|${escapeRegExp(stem)}(?=["'\`])`})`,
1945
+ "g",
1946
+ )
1947
+ for (const match of text.matchAll(pattern)) {
1948
+ // `packages/x/src/a.ts` names another package's `src/a.ts`; only a prefix that reaches the
1949
+ // app counts, and a path the sibling holds itself is its own.
1950
+ const prefix = /(?:[\w.@-]+\/)+$/.exec(text.slice(0, match.index))?.[0] ?? ""
1951
+ const bases = prefix === "" ? [] : [dirname(abs), pkg, dirname(pkg), dirname(dirname(pkg))]
1952
+ if (prefix !== "" && !bases.some((base) => resolve(base, prefix) === root)) continue
1953
+ const own = existsSync(join(pkg, from)) || existsSync(join(dirname(abs), from))
1954
+ if (prefix === "" && own && !runsInApp) continue
1955
+ report(from, match.index, match[0].length)
1956
+ }
1957
+ }
1958
+ const byNumber = (a: number, b: number): number => a - b
1959
+ return [...found].map(([from, { to, lines, commentLines }]) => ({
1960
+ from,
1961
+ to,
1962
+ lines: [...lines].sort(byNumber),
1963
+ commentLines: [...commentLines].filter((line) => !lines.has(line)).sort(byNumber),
1964
+ }))
1965
+ }
1966
+
1070
1967
  /** The package folder an app without its own package.json sits in (`--dir src`), at most two levels
1071
1968
  * up and never a workspace root, so the scan beside it stays inside one package. */
1072
1969
  function enclosingPackage(root: string): string | undefined {
@@ -1219,18 +2116,14 @@ function renameRetiredTypes(ts: typeof TS, file: string, text: string): string {
1219
2116
  /** The config files the loader reads, old layout included; a path field may live in any of them. */
1220
2117
  const CONFIG_FILES = ["nifra.config.ts", "framework.ts", "backend/framework.ts"]
1221
2118
 
1222
- interface ConfigEntry {
2119
+ interface ConfigEntry extends StaticConfigPath {
1223
2120
  /** `clientModule`, or `componentPipeline.entries.<name>`. */
1224
2121
  readonly field: string
1225
2122
  readonly role: "frontend" | "backend"
1226
- readonly value: string
1227
- /** The literal's text, quotes excluded: [start, end). */
1228
- readonly start: number
1229
- readonly end: number
1230
2123
  }
1231
2124
 
1232
2125
  /**
1233
- * The module paths a config exports as string literals: `clientModule` and the component pipeline's
2126
+ * The module paths a config exports, read statically: `clientModule` and the component pipeline's
1234
2127
  * `entries`. The browser loads `clientModule` and `entries.client`; `ssr` and `rsc` run on the server.
1235
2128
  */
1236
2129
  function configEntries(ts: typeof TS, file: string, text: string): ConfigEntry[] {
@@ -1246,17 +2139,11 @@ function configEntries(ts: typeof TS, file: string, text: string): ConfigEntry[]
1246
2139
  current = current.expression
1247
2140
  return current
1248
2141
  }
2142
+ const read = configPathReader(ts, sf)
1249
2143
  const out: ConfigEntry[] = []
1250
2144
  const literal = (field: string, role: ConfigEntry["role"], node: TS.Expression | undefined) => {
1251
- const value = bare(node)
1252
- if (value === undefined || !ts.isStringLiteralLike(value)) return
1253
- out.push({
1254
- field,
1255
- role,
1256
- value: value.text,
1257
- start: value.getStart(sf) + 1,
1258
- end: value.getEnd() - 1,
1259
- })
2145
+ const path = read(node)
2146
+ if (path !== undefined) out.push({ ...path, field, role })
1260
2147
  }
1261
2148
  for (const statement of sf.statements) {
1262
2149
  if (
@@ -1386,7 +2273,7 @@ export async function migrateLayout(
1386
2273
  original.set(file, readFileSync(join(root, file), "utf8"))
1387
2274
  }
1388
2275
  const issues: LayoutMigrationIssue[] = []
1389
- const splits: Array<{ file: string; backend: string; moved: string[] }> = []
2276
+ const splits: Array<{ file: string; backend: string; moved: string[]; shared?: string }> = []
1390
2277
  /** The app after the migration: new path -> text. */
1391
2278
  const next: Files = new Map(original)
1392
2279
  /** Old path -> new path, for every file that moves. */
@@ -1409,13 +2296,25 @@ export async function migrateLayout(
1409
2296
  if (!ROUTE_FILE.test(file)) continue
1410
2297
  const backendFile = file.replace(ROUTE_FILE, ".backend.ts")
1411
2298
  const specifier = `./${posix.basename(backendFile)}`
2299
+ const sharedFile = file.replace(ROUTE_FILE, ".shared.ts")
2300
+ // A taken name leaves data both halves read copied into each, as reported.
2301
+ const splitOptions: SplitOptions =
2302
+ next.has(sharedFile) || existsSync(join(root, sharedFile))
2303
+ ? {}
2304
+ : { sharedFile: posix.basename(sharedFile) }
1412
2305
  let result: SplitResult
1413
2306
  if (/\.(?:svelte|vue)$/.test(file)) {
1414
2307
  const blocks = scriptBlocks(text)
1415
2308
  const block =
1416
2309
  blocks.find((b) => b.module) ?? blocks.find((b) => !b.setup && file.endsWith(".vue"))
1417
2310
  if (block === undefined) continue
1418
- const inner = splitRouteSource(ts, text.slice(block.start, block.end), "block.ts", specifier)
2311
+ const inner = splitRouteSource(
2312
+ ts,
2313
+ text.slice(block.start, block.end),
2314
+ "block.ts",
2315
+ specifier,
2316
+ splitOptions,
2317
+ )
1419
2318
  result = {
1420
2319
  ...inner,
1421
2320
  frontend: `${text.slice(0, block.start)}\n${inner.frontend}${text.slice(block.end)}`,
@@ -1433,7 +2332,7 @@ export async function migrateLayout(
1433
2332
  }
1434
2333
  continue
1435
2334
  } else {
1436
- result = splitRouteSource(ts, text, file, specifier)
2335
+ result = splitRouteSource(ts, text, file, specifier, splitOptions)
1437
2336
  }
1438
2337
  if (result.backend === undefined) continue
1439
2338
  next.set(file, result.frontend)
@@ -1441,7 +2340,12 @@ export async function migrateLayout(
1441
2340
  backendFile,
1442
2341
  mergeModules(ts, backendHalves.get(backendFile) ?? "", result.backend),
1443
2342
  )
1444
- splits.push({ file, backend: backendFile, moved: [...result.moved] })
2343
+ if (result.shared === undefined)
2344
+ splits.push({ file, backend: backendFile, moved: [...result.moved] })
2345
+ else {
2346
+ next.set(sharedFile, result.shared)
2347
+ splits.push({ file, backend: backendFile, moved: [...result.moved], shared: sharedFile })
2348
+ }
1445
2349
  for (const reason of result.issues) issues.push({ file, reason })
1446
2350
  }
1447
2351
  for (const [file, text] of backendHalves) {
@@ -1453,7 +2357,11 @@ export async function migrateLayout(
1453
2357
  for (const [from, to] of Object.entries(rootMoves)) if (next.has(from)) moveMap.set(from, to)
1454
2358
  // Assets (images, fonts) resolve too, so they move with the modules that import them.
1455
2359
  const known = new Set([...next.keys(), ...everyFile])
1456
- const resolver = createSpecifierResolver()
2360
+ const knownPaths = new Set([...known].map((file) => join(root, file)))
2361
+ // Route halves the split creates resolve before they are written.
2362
+ const resolver = createSpecifierResolver({
2363
+ moduleExists: (path) => knownPaths.has(path) || isFile(path),
2364
+ })
1457
2365
  const realRoot = (() => {
1458
2366
  try {
1459
2367
  return realpathSync(root)
@@ -1461,14 +2369,21 @@ export async function migrateLayout(
1461
2369
  return root
1462
2370
  }
1463
2371
  })()
2372
+ /** An app file as the migration names it, from a path the resolver found (real, or as planned). */
2373
+ const appFile = (path: string | undefined): string | undefined => {
2374
+ if (path === undefined) return undefined
2375
+ for (const base of [realRoot, root]) {
2376
+ const rel = toPosix(relative(base, path))
2377
+ if (!rel.startsWith("../") && !isAbsolute(rel)) return rel
2378
+ }
2379
+ return undefined
2380
+ }
1464
2381
  /** A non-relative specifier the app's tsconfig `paths`/`baseUrl` or package.json `imports` maps to
1465
- * one of its files, read from disk as the bundler reads it. */
2382
+ * one of its files, as the bundler reads it. */
1466
2383
  const viaAlias = (file: string, specifier: string): string | undefined => {
1467
2384
  if (specifier.startsWith(".") || isAbsolute(specifier)) return undefined
1468
- const found = resolver(join(root, file), specifier)
1469
- if (found === undefined) return undefined
1470
- const rel = toPosix(relative(realRoot, found))
1471
- return rel.startsWith("../") || isAbsolute(rel) || !known.has(rel) ? undefined : rel
2385
+ const rel = appFile(resolver(join(root, file), withoutQuery(specifier)))
2386
+ return rel === undefined || !known.has(rel) ? undefined : rel
1472
2387
  }
1473
2388
  const resolveAny = (file: string, specifier: string): string | undefined =>
1474
2389
  resolveIn(known, file, specifier) ?? viaAlias(file, specifier)
@@ -1485,7 +2400,7 @@ export async function migrateLayout(
1485
2400
  * scheme the bundler owns, the app's own package name, or a package installed at or above it. */
1486
2401
  const external = (specifier: string): boolean => {
1487
2402
  if (/^[a-z][a-z\d+.-]*:/i.test(specifier) || specifier === "bun") return true
1488
- const name = packageName(specifier.replace(/[?#].*$/, ""))
2403
+ const name = packageName(withoutQuery(specifier))
1489
2404
  if (builtinModules.includes(name) || name === ownName) return true
1490
2405
  let found = installed.get(name)
1491
2406
  if (found === undefined) {
@@ -1518,9 +2433,10 @@ export async function migrateLayout(
1518
2433
  const split = route === undefined ? undefined : splitRoutes.get(route)
1519
2434
  if (route === undefined || split === undefined) return undefined
1520
2435
  const inBase = (path: string): string => toPosix(relative(base, join(root, path)))
2436
+ const relativePath = backendSpecifier(specifier, inBase(route), inBase(split.backend), file)
1521
2437
  const respelled = specifier.startsWith(".")
1522
- ? backendSpecifier(specifier, inBase(route), inBase(split.backend), file)
1523
- : resolver.respell(join(base, file), specifier, join(root, split.backend))
2438
+ ? relativePath
2439
+ : (resolver.respell(join(base, file), specifier, join(root, split.backend)) ?? relativePath)
1524
2440
  return { backend: split.backend, moved: split.moved, specifier: respelled }
1525
2441
  }
1526
2442
  const redirectedFiles = new Set<string>()
@@ -1567,6 +2483,24 @@ export async function migrateLayout(
1567
2483
  })
1568
2484
  }
1569
2485
  }
2486
+ // What a glob loads is imported too: the files it matches go where the module that loads them goes.
2487
+ for (const call of globCalls(ts, file, text)) {
2488
+ const targets = call.literal
2489
+ ? globTargets(
2490
+ file,
2491
+ call.patterns.map((pattern) => pattern.text),
2492
+ known,
2493
+ )
2494
+ : undefined
2495
+ if (targets === undefined) {
2496
+ issues.push({
2497
+ file,
2498
+ 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`,
2499
+ })
2500
+ continue
2501
+ }
2502
+ for (const target of targets) refs.push({ target, typeOnly: false })
2503
+ }
1570
2504
  edges.set(file, refs)
1571
2505
  }
1572
2506
  // The config's module paths are entries too: the browser loads `clientModule`.
@@ -1574,8 +2508,12 @@ export async function migrateLayout(
1574
2508
  configEntries(ts, file, next.get(file) ?? "").map((entry) => ({
1575
2509
  ...entry,
1576
2510
  file,
1577
- // Relative to the app root, as the loader reads it, whichever config file holds it.
1578
- target: resolveAny("nifra.config.ts", entry.value),
2511
+ // A string is read from the app root, whichever config file holds it; a joined path from the
2512
+ // config's own folder.
2513
+ target:
2514
+ entry.base === "app"
2515
+ ? resolveAny("nifra.config.ts", entry.path)
2516
+ : resolveIn(known, file, entry.path.startsWith("../") ? entry.path : `./${entry.path}`),
1579
2517
  })),
1580
2518
  )
1581
2519
  const entryTargets = (role: ConfigEntry["role"]): Set<string> =>
@@ -1589,7 +2527,8 @@ export async function migrateLayout(
1589
2527
  const files = [...new Set([...next.keys(), ...everyFile.filter((f) => !original.has(f))])]
1590
2528
  const frontendRoots = [
1591
2529
  ...files.filter(
1592
- (f) => f.startsWith("routes/") && ROUTE_FILE.test(f) && !f.includes(".backend."),
2530
+ (f) =>
2531
+ f.startsWith("routes/") && ROUTE_FILE.test(f) && !f.includes(".backend.") && !isTestFile(f),
1593
2532
  ),
1594
2533
  ...browserEntries,
1595
2534
  ]
@@ -1645,7 +2584,9 @@ export async function migrateLayout(
1645
2584
  })
1646
2585
  }
1647
2586
  }
1648
- const zoneOf = (file: string): "frontend" | "backend" | "shared" =>
2587
+ /** With `zones`, the files that stay where they are and the side package.json gives them. */
2588
+ const inPlace = new Map<string, FolderSide>()
2589
+ const zoneOf = (file: string): FolderSide =>
1649
2590
  browser.has(file) && server.has(file) ? "shared" : browser.has(file) ? "frontend" : "backend"
1650
2591
  for (const file of api ? [] : files) {
1651
2592
  if (
@@ -1662,6 +2603,10 @@ export async function migrateLayout(
1662
2603
  if (ZONE_DIRS.has(top) || (!browser.has(file) && !server.has(file))) continue
1663
2604
  } else if (!browser.has(file) && !appServer.has(file)) continue
1664
2605
  const zone = zoneOf(file)
2606
+ if (DATA_FILE.test(file) && options.zones === true) {
2607
+ inPlace.set(file, zone)
2608
+ continue
2609
+ }
1665
2610
  if (DATA_FILE.test(file)) {
1666
2611
  const folder = file.includes("/") ? posix.dirname(file) : undefined
1667
2612
  issues.push({
@@ -1672,6 +2617,51 @@ export async function migrateLayout(
1672
2617
  }
1673
2618
  moveMap.set(file, `${zone}/${file}`)
1674
2619
  }
2620
+ // A folder whose reached files all move into one zone takes its other files along: a file nothing
2621
+ // imports at runtime (a component not used yet, an asset) has no zone of its own, and leaving it
2622
+ // behind splits the folder for every tool that lists it. Server built-ins never go to the browser.
2623
+ const zonesUnder = new Map<string, Set<string>>()
2624
+ for (const [from, to] of moveMap) {
2625
+ if (isTestFile(from)) continue
2626
+ for (let dir = posix.dirname(from); dir !== "."; dir = posix.dirname(dir)) {
2627
+ zonesUnder.set(dir, (zonesUnder.get(dir) ?? new Set<string>()).add(to.split("/")[0] ?? ""))
2628
+ }
2629
+ }
2630
+ for (const file of api ? [] : files) {
2631
+ if (moveMap.has(file) || browser.has(file) || server.has(file)) continue
2632
+ if (ZONE_DIRS.has(file.split("/")[0] ?? "") || inConfiguredFolder(file)) continue
2633
+ // A test and its snapshot follow their subject below.
2634
+ if (
2635
+ isTestFile(file) ||
2636
+ file.endsWith(".snap") ||
2637
+ file.endsWith(".d.ts") ||
2638
+ DATA_FILE.test(file)
2639
+ )
2640
+ continue
2641
+ let zones: ReadonlySet<string> | undefined
2642
+ for (
2643
+ let dir = posix.dirname(file);
2644
+ dir !== "." && zones === undefined;
2645
+ dir = posix.dirname(dir)
2646
+ ) {
2647
+ // A nested package is its own install, never part of the app's folder.
2648
+ if (existsSync(join(root, dir, "package.json"))) break
2649
+ zones = zonesUnder.get(dir)
2650
+ }
2651
+ const [zone] = zones?.size === 1 ? zones : []
2652
+ if (zone === undefined) continue
2653
+ if (zone !== "backend" && /from\s+["'](?:node:|bun:)/.test(next.get(file) ?? "")) continue
2654
+ moveMap.set(file, `${zone}/${file}`)
2655
+ }
2656
+ if (options.zones === true) {
2657
+ for (const [from, to] of moveMap) {
2658
+ const side = FOLDER_SIDES.find((side) => to === `${side}/${from}`)
2659
+ if (side === undefined) continue
2660
+ inPlace.set(from, side)
2661
+ moveMap.delete(from)
2662
+ }
2663
+ }
2664
+ const declared = zoneDeclarations(inPlace, files, (file) => next.get(file), inConfiguredFolder)
1675
2665
  const claimed = new Map<string, string>()
1676
2666
  for (const [from, to] of moveMap) {
1677
2667
  const holder = claimed.get(to) ?? (known.has(to) && !moveMap.has(to) ? to : undefined)
@@ -1685,32 +2675,120 @@ export async function migrateLayout(
1685
2675
  })
1686
2676
  moveMap.delete(from)
1687
2677
  }
1688
- for (const [from, to] of moveMap) {
1689
- if (to.startsWith("shared/") && /from\s+["'](?:node:|bun:)/.test(next.get(from) ?? "")) {
2678
+ const newPath = (file: string): string => moveMap.get(file) ?? file
2679
+ // A test beside its subject (`x.test.ts` by `x.ts`, or in a `__tests__/` under its folder) moves
2680
+ // with it, snapshots included, once the subject's place is settled; a test never decides a zone.
2681
+ const present = new Set(files)
2682
+ for (const test of files) {
2683
+ const stem = /^(.+?)\.(?:test|spec)\.[cm]?[jt]sx?$/.exec(posix.basename(test))?.[1]
2684
+ if (stem === undefined || moveMap.has(test) || !next.has(test)) continue
2685
+ const dir = posix.dirname(test)
2686
+ const nested = posix.basename(dir) === "__tests__"
2687
+ const home = nested ? posix.dirname(dir) : dir
2688
+ const subjects = SUBJECT_EXTENSIONS.map((ext) => posix.join(home, `${stem}${ext}`)).filter(
2689
+ (file) => present.has(file) && !isTestFile(file),
2690
+ )
2691
+ const subject = subjects.find((file) => moveMap.has(file))
2692
+ if (subject === undefined) continue
2693
+ if (new Set(subjects.map((file) => posix.dirname(newPath(file)))).size > 1) {
2694
+ issues.push({
2695
+ file: test,
2696
+ reason: `tests ${subjects.map((file) => `"${file}"`).join(" and ")}, which end up in different folders, so it stays here; move it by hand`,
2697
+ })
2698
+ continue
2699
+ }
2700
+ const to = posix.join(
2701
+ posix.dirname(newPath(subject)),
2702
+ nested ? "__tests__" : "",
2703
+ posix.basename(test),
2704
+ )
2705
+ const pairs: Array<readonly [string, string]> = [[test, to]]
2706
+ const snapshot = posix.join(dir, "__snapshots__", `${posix.basename(test)}.snap`)
2707
+ if (present.has(snapshot))
2708
+ pairs.push([
2709
+ snapshot,
2710
+ posix.join(posix.dirname(to), "__snapshots__", posix.basename(snapshot)),
2711
+ ])
2712
+ const taken = pairs.find(([, to]) => claimed.has(to) || (known.has(to) && !moveMap.has(to)))
2713
+ if (taken !== undefined) {
2714
+ issues.push({
2715
+ file: test,
2716
+ reason: `would follow "${subject}" to "${taken[1]}", which already exists or another file moves to; move it by hand`,
2717
+ })
2718
+ continue
2719
+ }
2720
+ for (const [from, to] of pairs) {
2721
+ moveMap.set(from, to)
2722
+ claimed.set(to, from)
2723
+ }
2724
+ }
2725
+ for (const [from, to] of [
2726
+ ...moveMap,
2727
+ ...[...inPlace].map(([file, side]) => [file, side] as const),
2728
+ ]) {
2729
+ // A test is never bundled, so its own server imports decide nothing.
2730
+ if (isTestFile(from)) continue
2731
+ if (
2732
+ (to === "shared" || to.startsWith("shared/")) &&
2733
+ /from\s+["'](?:node:|bun:)/.test(next.get(from) ?? "")
2734
+ ) {
1690
2735
  issues.push({
1691
2736
  file: from,
1692
- reason: `both halves import it at runtime, but it uses a server built-in; split it before moving to ${to}`,
2737
+ 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}`}`,
1693
2738
  })
1694
2739
  }
1695
2740
  }
1696
2741
 
1697
2742
  // 5. Rewrite imports to the new locations.
1698
- const newPath = (file: string): string => moveMap.get(file) ?? file
1699
2743
  const final: Files = new Map()
1700
2744
  const rewritten: string[] = []
1701
- const unspelled = new Set<string>()
1702
- /** An alias for a target that moves, through the same alias, or an issue when none covers it. */
1703
- const respellAlias = (file: string, specifier: string, target: string): string | undefined => {
1704
- if (newPath(target) === target) return undefined
1705
- const respelled = resolver.respell(join(root, file), specifier, join(root, newPath(target)))
1706
- if (respelled === undefined && !unspelled.has(`${file}\0${specifier}`)) {
1707
- unspelled.add(`${file}\0${specifier}`)
1708
- issues.push({
1709
- file,
1710
- 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`,
1711
- })
1712
- }
1713
- return respelled
2745
+ // The app as the migration leaves it, where every rewritten specifier must reach its target.
2746
+ const planned = new Set(
2747
+ [...known].filter((file) => next.has(file) || !original.has(file)).map(newPath),
2748
+ )
2749
+ const plannedResolver = createSpecifierResolver({
2750
+ moduleExists: (path) => {
2751
+ const file = appFile(path)
2752
+ if (file !== undefined && (planned.has(file) || known.has(file))) return planned.has(file)
2753
+ return isFile(path)
2754
+ },
2755
+ })
2756
+ /** Whether `specifier`, written in `from` after the moves, loads `target` there. */
2757
+ const reaches = (from: string, specifier: string, target: string): boolean =>
2758
+ specifier.startsWith(".")
2759
+ ? resolveIn(planned, from, specifier) === target
2760
+ : appFile(plannedResolver(join(root, from), withoutQuery(specifier))) === target
2761
+ const unreached = new Set<string>()
2762
+ const unreachable = (file: string, specifier: string, target: string, from: string): void => {
2763
+ if (unreached.has(`${file}\0${specifier}`)) return
2764
+ unreached.add(`${file}\0${specifier}`)
2765
+ issues.push({
2766
+ file,
2767
+ 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`,
2768
+ })
2769
+ }
2770
+ /**
2771
+ * How `from` names `target` after the moves, for the alias `specifier` that `file` writes: as written
2772
+ * while it still reaches it, through the same alias when one of its targets covers the new place,
2773
+ * else as a relative path. `undefined` leaves it as written.
2774
+ */
2775
+ const aliasTo = (
2776
+ file: string,
2777
+ specifier: string,
2778
+ target: string,
2779
+ from = newPath(file),
2780
+ ): string | undefined => {
2781
+ const to = newPath(target)
2782
+ if (to === target && from === file) return undefined
2783
+ const written = withoutQuery(specifier)
2784
+ if (reaches(from, written, to)) return undefined
2785
+ const respelled = resolver.respell(join(root, file), written, join(root, to))
2786
+ if (respelled !== undefined && reaches(from, respelled, to))
2787
+ return `${respelled}${specifier.slice(written.length)}`
2788
+ const relativePath = respecify(specifier, target, from, to)
2789
+ if (reaches(from, relativePath, to)) return relativePath
2790
+ unreachable(file, specifier, target, from)
2791
+ return undefined
1714
2792
  }
1715
2793
  for (const [file, text] of next) {
1716
2794
  const imports = rewriteImports(ts, file, text, (specifier) => {
@@ -1719,9 +2797,12 @@ export async function migrateLayout(
1719
2797
  const target = resolveAny(file, specifier)
1720
2798
  // Outside the app (or a skipped dir): the target stays put, so only a moved importer re-bases it.
1721
2799
  if (target === undefined) return rebase(specifier, file, newPath(file))
1722
- if (!specifier.startsWith(".")) return respellAlias(file, specifier, target)
2800
+ if (!specifier.startsWith(".")) return aliasTo(file, specifier, target)
1723
2801
  if (newPath(target) === target && newPath(file) === file) return undefined
1724
- return respecify(specifier, target, newPath(file), newPath(target))
2802
+ const relativePath = respecify(specifier, target, newPath(file), newPath(target))
2803
+ if (!reaches(newPath(file), relativePath, newPath(target)))
2804
+ unreachable(file, specifier, target, newPath(file))
2805
+ return relativePath
1725
2806
  })
1726
2807
  const updated = renameRetiredTypes(ts, file, imports)
1727
2808
  final.set(newPath(file), updated)
@@ -1732,19 +2813,62 @@ export async function migrateLayout(
1732
2813
  rewritten.push(file)
1733
2814
  }
1734
2815
 
1735
- // A config path names its module from the app root, so it follows the module, never the config file.
2816
+ // A glob names its files by pattern, which no import rewrite reads: each one must still load, from
2817
+ // the module's new folder, the files it loaded before. A pattern whose matches moved together
2818
+ // into one folder is re-pointed at it; any other change is reported.
2819
+ for (const file of next.keys()) {
2820
+ const at = newPath(file)
2821
+ const text = final.get(at)
2822
+ if (text === undefined) continue
2823
+ const edits: Array<{ start: number; end: number; text: string }> = []
2824
+ for (const call of globCalls(ts, at, text)) {
2825
+ if (!call.literal) continue
2826
+ const written = call.patterns.map((pattern) => pattern.text)
2827
+ const before = globTargets(file, written, known)
2828
+ if (before === undefined || before.length === 0) continue
2829
+ const expected = before.map(newPath).sort(codeUnitOrder)
2830
+ const same = (patterns: readonly string[]): boolean => {
2831
+ const after = globTargets(at, patterns, planned)?.sort(codeUnitOrder)
2832
+ return after !== undefined && after.join("\n") === expected.join("\n")
2833
+ }
2834
+ if (same(written)) continue
2835
+ const repointed = written.map((pattern) => repointGlob(file, at, pattern, before, newPath))
2836
+ if (repointed.every((pattern) => pattern !== undefined) && same(repointed)) {
2837
+ call.patterns.forEach((pattern, index) => {
2838
+ const value = repointed[index]
2839
+ if (value !== undefined && value !== pattern.text)
2840
+ edits.push({ start: pattern.start, end: pattern.end, text: value })
2841
+ })
2842
+ continue
2843
+ }
2844
+ issues.push({
2845
+ file: at,
2846
+ 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`,
2847
+ })
2848
+ }
2849
+ if (edits.length === 0) continue
2850
+ let updated = text
2851
+ for (const edit of edits.sort((a, b) => b.start - a.start))
2852
+ updated = updated.slice(0, edit.start) + edit.text + updated.slice(edit.end)
2853
+ final.set(at, updated)
2854
+ if (!moveMap.has(file) && !rewritten.includes(file)) rewritten.push(file)
2855
+ }
2856
+
2857
+ // A config string names its module from the app root, so it follows the module, never the config
2858
+ // file; a path joined onto the config's folder is re-pointed with the module's own paths below.
1736
2859
  for (const configFile of CONFIG_FILES) {
1737
2860
  const at = newPath(configFile)
1738
2861
  const text = final.get(at)
1739
2862
  if (text === undefined || !next.has(configFile)) continue
1740
2863
  const edits: Array<{ start: number; end: number; text: string }> = []
1741
2864
  for (const entry of configEntries(ts, at, text)) {
1742
- const target = resolveAny("nifra.config.ts", entry.value)
2865
+ if (entry.span === undefined) continue
2866
+ const target = resolveAny("nifra.config.ts", entry.path)
1743
2867
  if (target === undefined || newPath(target) === target) continue
1744
- const value = entry.value.startsWith(".")
1745
- ? respecify(entry.value, target, "nifra.config.ts", newPath(target))
1746
- : respellAlias(configFile, entry.value, target)
1747
- if (value !== undefined) edits.push({ start: entry.start, end: entry.end, text: value })
2868
+ const value = entry.path.startsWith(".")
2869
+ ? respecify(entry.path, target, "nifra.config.ts", newPath(target))
2870
+ : aliasTo(configFile, entry.path, target, "nifra.config.ts")
2871
+ if (value !== undefined) edits.push({ start: entry.span[0], end: entry.span[1], text: value })
1748
2872
  }
1749
2873
  if (edits.length === 0) continue
1750
2874
  let updated = text
@@ -1761,7 +2885,18 @@ export async function migrateLayout(
1761
2885
  // A moved module's paths from its own location now start from its new folder: re-point the ones it
1762
2886
  // spells out, and report the first one it cannot follow.
1763
2887
  const unfollowed = new Map<string, string>()
2888
+ /** Moved shell scripts whose own-folder paths were re-pointed: new path -> text. */
2889
+ const scriptWrites = new Map<string, string>()
1764
2890
  for (const { from, to } of moves) {
2891
+ if (SHELL_FILE.test(to) && !original.has(from)) {
2892
+ const script = readFileSync(join(root, from), "utf8")
2893
+ const result = rebaseShellPaths(from, to, script, (target) =>
2894
+ known.has(target) ? newPath(target) : target,
2895
+ )
2896
+ if (result.text !== script) scriptWrites.set(to, result.text)
2897
+ if (result.unfollowed !== undefined) unfollowed.set(to, result.unfollowed)
2898
+ continue
2899
+ }
1765
2900
  const text = final.get(to)
1766
2901
  if (text === undefined || !SELF_LOCATION.test(text)) continue
1767
2902
  if (!/\.[cm]?[jt]sx?$/.test(to)) {
@@ -1774,11 +2909,38 @@ export async function migrateLayout(
1774
2909
  final.set(to, result.text)
1775
2910
  if (result.unfollowed !== undefined) unfollowed.set(to, result.unfollowed)
1776
2911
  }
2912
+ // A module that stays still names files from its own folder (a config's `clientModule` joined onto
2913
+ // `import.meta.dir`): each that moved is re-pointed.
2914
+ const landed = new Set(moveMap.values())
2915
+ for (const [file, text] of final) {
2916
+ if (landed.has(file) || !/\.[cm]?[jt]sx?$/.test(file) || !SELF_LOCATION.test(text)) continue
2917
+ const result = rebaseOwnPaths(ts, file, file, text, (target) =>
2918
+ known.has(target) ? newPath(target) : target,
2919
+ )
2920
+ if (result.text === text) continue
2921
+ final.set(file, result.text)
2922
+ if (original.has(file) && !rewritten.includes(file)) rewritten.push(file)
2923
+ }
1777
2924
 
1778
2925
  // A path in a string or comment is not an import, so nothing above rewrote it: a build script that
1779
2926
  // writes `data/x.json` would keep writing to the old place, and so would a deploy script or
1780
2927
  // `package.json` beside the code.
1781
2928
  const settled = new Set([...known].map(newPath))
2929
+ // A new backend half starts where its route was, so it keeps that route's place in each program.
2930
+ const splitFrom = new Map(
2931
+ splits
2932
+ .filter((split) => !original.has(split.backend))
2933
+ .map((split) => [split.backend, split.file]),
2934
+ )
2935
+ const layout = [...known]
2936
+ .filter((file) => next.has(file) || !original.has(file))
2937
+ .map((file) => ({ from: splitFrom.get(file) ?? file, to: newPath(file) }))
2938
+ const tsconfigs = followTsconfigs(ts, root, moveMap, layout)
2939
+ // The app's own package.json names files from the app root: its scripts and entry fields follow.
2940
+ const manifestPath = join(root, "package.json")
2941
+ const manifest = existsSync(manifestPath)
2942
+ ? rewritePackagePaths(ts, readFileSync(manifestPath, "utf8"), moveMap)
2943
+ : undefined
1782
2944
  const scanned: Array<readonly [string, string]> = [...final]
1783
2945
  for (const file of everyFile) {
1784
2946
  if (
@@ -1786,16 +2948,24 @@ export async function migrateLayout(
1786
2948
  TOOLING_FILE.test(file) &&
1787
2949
  statSync(join(root, file)).size <= 256_000
1788
2950
  )
1789
- scanned.push([newPath(file), readFileSync(join(root, file), "utf8")])
1790
- }
2951
+ scanned.push([
2952
+ newPath(file),
2953
+ (file === "package.json" ? manifest?.text : undefined) ??
2954
+ tsconfigs.files.get(file)?.text ??
2955
+ readFileSync(join(root, file), "utf8"),
2956
+ ])
2957
+ }
2958
+ // A mention only in comments is worth updating, not a decision: it never changes what runs.
2959
+ const commentFollowUps: LayoutMigrationFollowUp[] = []
1791
2960
  for (const [file, text] of scanned) {
1792
2961
  let live: ReadonlyArray<readonly [number, number]> | undefined
2962
+ let comments: ReadonlyArray<readonly [number, number]> | undefined
1793
2963
  for (const [from, to] of moveMap) {
1794
2964
  // `shared/lib/x.ts` contains `lib/x.ts`; that is the new path, not a stale one.
1795
2965
  const newPrefix = to.endsWith(from) ? to.slice(0, to.length - from.length) : undefined
1796
2966
  const stale = [
1797
2967
  ...text.matchAll(new RegExp(`(?<![\\w.-])${escapeRegExp(from)}(?![\\w])`, "g")),
1798
- ].some((match) => {
2968
+ ].filter((match) => {
1799
2969
  if (newPrefix !== undefined && text.slice(0, match.index).endsWith(newPrefix)) return false
1800
2970
  // An import that resolves after the moves is current, even when it still reads like the old
1801
2971
  // path: `./x.json` from a module that moved together with `x.json`.
@@ -1803,7 +2973,16 @@ export async function migrateLayout(
1803
2973
  const end = match.index + from.length
1804
2974
  return !live.some(([start, stop]) => start <= match.index && end <= stop)
1805
2975
  })
1806
- if (stale) issues.push({ file, reason: `mentions "${from}" by path; it moved to "${to}"` })
2976
+ if (stale.length === 0) continue
2977
+ comments ??= /\.[cm]?[jt]sx?$/.test(file) ? triviaCommentRanges(ts, file, text) : []
2978
+ const inComments = stale.every((match) =>
2979
+ comments?.some(
2980
+ ([start, stop]) => start <= match.index && match.index + from.length <= stop,
2981
+ ),
2982
+ )
2983
+ if (inComments)
2984
+ commentFollowUps.push({ file, reason: `a comment names "${from}", which moved to "${to}"` })
2985
+ else issues.push({ file, reason: `mentions "${from}" by path; it moved to "${to}"` })
1807
2986
  }
1808
2987
  }
1809
2988
 
@@ -1845,6 +3024,46 @@ export async function migrateLayout(
1845
3024
  }
1846
3025
  }
1847
3026
 
3027
+ // A workspace sibling is not the migration's to edit either: each file that names a moved app file,
3028
+ // by import or by path, is reported with the line and both paths.
3029
+ const appName = posix.basename(toPosix(root))
3030
+ const mentionsApp = new RegExp(`(?:^|[/'"\`])${escapeRegExp(appName)}(?:[/'"\`]|$)`, "m")
3031
+ for (const sibling of moveMap.size === 0 ? [] : (workspaceSiblings(root) ?? [])) {
3032
+ for (const file of listFiles(sibling)) {
3033
+ if (!/\.[cm]?[jt]sx?$/.test(file) && !TOOLING_FILE.test(file)) continue
3034
+ if (statSync(join(sibling, file)).size > 256_000) continue
3035
+ const text = readFileSync(join(sibling, file), "utf8")
3036
+ if (!mentionsApp.test(text) && (ownName === undefined || !text.includes(`${ownName}/`)))
3037
+ continue
3038
+ const at = toPosix(relative(root, join(sibling, file)))
3039
+ const onLines = (lines: readonly number[]): string =>
3040
+ `on line${lines.length === 1 ? "" : "s"} ${lines.join(", ")}`
3041
+ for (const { from, to, lines, commentLines } of siblingReferences(
3042
+ ts,
3043
+ root,
3044
+ sibling,
3045
+ file,
3046
+ text,
3047
+ moveMap,
3048
+ known,
3049
+ ownName,
3050
+ )) {
3051
+ const comments =
3052
+ commentLines.length === 0 ? "" : ` (and in a comment ${onLines(commentLines)})`
3053
+ if (lines.length > 0)
3054
+ issues.push({
3055
+ file: at,
3056
+ reason: `names "${from}" ${onLines(lines)}${comments}, and it moves to "${to}" - it is outside the app, so the migration does not rewrite it`,
3057
+ })
3058
+ else
3059
+ commentFollowUps.push({
3060
+ file: at,
3061
+ reason: `a comment ${onLines(commentLines)} names "${from}", which moved to "${to}"`,
3062
+ })
3063
+ }
3064
+ }
3065
+ }
3066
+
1848
3067
  // Paths a module finds at run time are not imports either: one built from the module's own location
1849
3068
  // now starts from its new folder, and a folder listed at run time loses whatever moved out of it.
1850
3069
  const leaving = new Map<string, Array<{ from: string; to: string }>>()
@@ -1878,14 +3097,46 @@ export async function migrateLayout(
1878
3097
  })
1879
3098
  }
1880
3099
 
1881
- // The server refuses data a loader or action returns without an output schema; only the author
1882
- // knows which fields the browser may see.
3100
+ // The server refuses data a loader or action returns without an output schema. Each half the split
3101
+ // wrote gets a draft from its return type, read from the layout as planned so the dry run shows
3102
+ // what --write adds; only the author knows which fields the browser may see, so it is a draft.
3103
+ const halves = [...new Set(splits.map((split) => split.backend))].filter((file) =>
3104
+ final.has(file),
3105
+ )
3106
+ const unwritten = new Map<string, string>()
3107
+ for (const [file, text] of final) if (original.get(file) !== text) unwritten.set(file, text)
3108
+ const schemaPlan =
3109
+ halves.length === 0
3110
+ ? undefined
3111
+ : await planOutputSchemas(root, halves, (file) => final.get(file), {
3112
+ overlay: unwritten,
3113
+ // What NF-C030 would flag: a schema for data the function returns, not for `return null`.
3114
+ draft: (file, schema) =>
3115
+ missingOutputSchemas(final.get(file) ?? "").some((found) => found.schema === schema),
3116
+ })
3117
+ for (const [file, text] of schemaPlan?.edits ?? []) final.set(file, text)
3118
+ const schemas = (schemaPlan?.entries ?? []).filter((entry) => entry.status === "missing")
3119
+ const followUps: LayoutMigrationFollowUp[] = [...commentFollowUps]
1883
3120
  for (const [file, text] of final) {
1884
3121
  if (!file.startsWith("routes/") || !/\.backend\.[cm]?[jt]s$/.test(file)) continue
1885
3122
  for (const { name, schema } of missingOutputSchemas(text)) {
3123
+ const why = schemaPlan?.entries.find(
3124
+ (entry) => entry.file === file && entry.schema === schema && entry.reason !== undefined,
3125
+ )?.reason
3126
+ const missing = `exports ${name === "action" ? "an" : "a"} ${name} but no ${schema}, so data it returns fails the request`
3127
+ // A half this run did not write keeps the schema it had: drafting one is the next command, not a
3128
+ // decision the migration left open.
3129
+ if (why === undefined && (schemaPlan === undefined || schemaPlan.warnings.length === 0)) {
3130
+ followUps.push({
3131
+ file,
3132
+ reason: `${missing}; draft it from the ${name}'s return type`,
3133
+ command: "nifra schemas --write",
3134
+ })
3135
+ continue
3136
+ }
1886
3137
  issues.push({
1887
3138
  file,
1888
- 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`,
3139
+ reason: `${missing}. Declare what the browser may see: export const ${schema} = t.object({ ... }); no draft was written: ${why ?? schemaPlan?.warnings.join("; ")}`,
1889
3140
  })
1890
3141
  }
1891
3142
  }
@@ -1893,12 +3144,11 @@ export async function migrateLayout(
1893
3144
  // Tooling that lists folders or globs, not files: the import rewrite above never sees it.
1894
3145
  const tooling: Array<{ file: string; change: string }> = []
1895
3146
  const toolingWrites = new Map<string, string>()
1896
- const tsconfig = coverMovedFiles(ts, root, moves)
1897
- if (tsconfig?.issue !== undefined) issues.push({ file: "tsconfig.json", reason: tsconfig.issue })
1898
- if (tsconfig?.text !== undefined) {
1899
- toolingWrites.set("tsconfig.json", tsconfig.text)
1900
- tooling.push({ file: "tsconfig.json", change: `include += ${tsconfig.added.join(", ")}` })
3147
+ for (const [file, { text, changes }] of tsconfigs.files) {
3148
+ toolingWrites.set(file, text)
3149
+ for (const change of changes) tooling.push({ file, change })
1901
3150
  }
3151
+ issues.push(...tsconfigs.issues)
1902
3152
  for (const file of everyFile) {
1903
3153
  if (!TAILWIND_CONFIG.test(file)) continue
1904
3154
  const reason = staleContentGlobs(ts, readFileSync(join(root, file), "utf8"), moves)
@@ -1909,6 +3159,33 @@ export async function migrateLayout(
1909
3159
  toolingWrites.set(".gitignore", gitignore)
1910
3160
  tooling.push({ file: ".gitignore", change: "ignore .nifra/ (dev and build state)" })
1911
3161
  }
3162
+ // A root backend.ts was served at /api by default until 5.0, which mounts it only where apiPrefix says.
3163
+ if (!api && rootMoves["backend.ts"] !== undefined) {
3164
+ const mount = apiPrefixFix({
3165
+ framework: final.get(FRAMEWORK_FILE),
3166
+ config: final.get(CONFIG_FILE),
3167
+ })
3168
+ for (const [file, text] of [
3169
+ [FRAMEWORK_FILE, mount.framework],
3170
+ [CONFIG_FILE, mount.config],
3171
+ ] as const) {
3172
+ if (text === undefined) continue
3173
+ final.set(file, text)
3174
+ tooling.push({
3175
+ file,
3176
+ change: 'export const apiPrefix = "/api", the mount 4.x made by default',
3177
+ })
3178
+ }
3179
+ }
3180
+ if (declared.size > 0) {
3181
+ const zoned = declareZones(ts, root, declared)
3182
+ if (zoned.issue !== undefined) issues.push({ file: "package.json", reason: zoned.issue })
3183
+ if (zoned.text !== undefined) {
3184
+ toolingWrites.set("package.json", zoned.text)
3185
+ for (const [path, side] of declared)
3186
+ tooling.push({ file: "package.json", change: `"nifra.zones" lists "${path}" as ${side}` })
3187
+ }
3188
+ }
1912
3189
  // `nifra check` reads the declaration statically; without it, a later routes/ or config would zone the app.
1913
3190
  const kind = api && createKindProbe(root)(root).kind === undefined ? declareApiKind(ts, root) : {}
1914
3191
  if (kind.issue !== undefined) issues.push({ file: "package.json", reason: kind.issue })
@@ -1916,6 +3193,14 @@ export async function migrateLayout(
1916
3193
  toolingWrites.set("package.json", kind.text)
1917
3194
  tooling.push({ file: "package.json", change: '"nifra": { "kind": "api" }' })
1918
3195
  }
3196
+ if (manifest !== undefined && manifest.count > 0) {
3197
+ const current = toolingWrites.get("package.json") ?? readFileSync(manifestPath, "utf8")
3198
+ toolingWrites.set("package.json", rewritePackagePaths(ts, current, moveMap).text)
3199
+ tooling.push({
3200
+ file: "package.json",
3201
+ change: `${manifest.count} file path(s) in scripts and entry fields follow their moved files`,
3202
+ })
3203
+ }
1919
3204
 
1920
3205
  if (options.write === true) {
1921
3206
  for (const [file, text] of toolingWrites) writeFileSync(join(root, file), text)
@@ -1937,20 +3222,64 @@ export async function migrateLayout(
1937
3222
  renameSync(join(root, from), join(root, to))
1938
3223
  vacated.push(from)
1939
3224
  }
3225
+ for (const [file, text] of scriptWrites) writeFileSync(join(root, file), text)
1940
3226
  pruneVacatedDirs(root, vacated)
1941
3227
  }
1942
3228
  return {
1943
3229
  ok: issues.length === 0,
1944
3230
  write: options.write === true,
1945
3231
  mode,
3232
+ followUps,
1946
3233
  splits: splits.sort((a, b) => codeUnitOrder(a.file, b.file)),
1947
3234
  moves,
1948
3235
  rewritten: rewritten.sort(),
1949
3236
  tooling,
3237
+ schemas: schemas.map((entry) =>
3238
+ options.write === true && entry.reason === undefined
3239
+ ? { ...entry, status: "generated" }
3240
+ : entry,
3241
+ ),
1950
3242
  issues,
1951
3243
  }
1952
3244
  }
1953
3245
 
3246
+ /**
3247
+ * Split one route file in place: its server-only exports, and the code only they use, move into its
3248
+ * `x.backend.ts`, created or merged into. Returns the files written, app-relative; nothing for a file
3249
+ * that exports nothing for the server. Refuses, naming why, a split that would need a decision.
3250
+ */
3251
+ export async function splitRouteFile(
3252
+ appRoot: string,
3253
+ file: string,
3254
+ options: Pick<LayoutMigrationOptions, "typescript"> = {},
3255
+ ): Promise<readonly string[]> {
3256
+ if (!/\.[jt]sx$/.test(file)) return []
3257
+ const ts = options.typescript ?? (await importTypeScript())
3258
+ if (ts === undefined)
3259
+ throw new Error("[nifra] splitting a route needs TypeScript: bun add -d typescript")
3260
+ const root = resolve(appRoot)
3261
+ const backendFile = file.replace(ROUTE_FILE, ".backend.ts")
3262
+ const sharedFile = file.replace(ROUTE_FILE, ".shared.ts")
3263
+ const result = splitRouteSource(
3264
+ ts,
3265
+ readFileSync(join(root, file), "utf8"),
3266
+ file,
3267
+ `./${posix.basename(backendFile)}`,
3268
+ existsSync(join(root, sharedFile)) ? {} : { sharedFile: posix.basename(sharedFile) },
3269
+ )
3270
+ if (result.backend === undefined) return []
3271
+ if (result.issues.length > 0) {
3272
+ throw new Error(`[nifra] ${file} was not split: ${result.issues.join("; ")}`)
3273
+ }
3274
+ const backendPath = join(root, backendFile)
3275
+ const existing = existsSync(backendPath) ? readFileSync(backendPath, "utf8") : ""
3276
+ writeFileSync(join(root, file), result.frontend)
3277
+ writeFileSync(backendPath, mergeModules(ts, existing, result.backend))
3278
+ if (result.shared === undefined) return [file, backendFile]
3279
+ writeFileSync(join(root, sharedFile), result.shared)
3280
+ return [file, backendFile, sharedFile]
3281
+ }
3282
+
1954
3283
  /** The app's `"nifra": { "zones": ... }`, so folders it already zones are left where they are. */
1955
3284
  function appZones(root: string): ZoneConfig {
1956
3285
  const manifest = join(root, "package.json")
@@ -1968,53 +3297,271 @@ function appZones(root: string): ZoneConfig {
1968
3297
  return zones === undefined ? {} : parseZoneConfig(zones, manifest)
1969
3298
  }
1970
3299
 
1971
- /** Whether a tsconfig `include` entry takes in `file` (app-relative), the way tsc reads it. */
1972
- function includes(pattern: string, file: string): boolean {
1973
- let spec = pattern.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "")
1974
- if (spec === "" || spec === ".") return true
1975
- if (!/[*?]/.test(spec)) return file === spec || file.startsWith(`${spec}/`)
1976
- if (spec.endsWith("**")) spec = `${spec}/*`
1977
- else if (!/[*?.][^/]*$/.test(spec.slice(spec.lastIndexOf("/") + 1))) spec = `${spec}/**/*`
1978
- return new Bun.Glob(spec).match(file)
3300
+ const matchers = new Map<string, (file: string) => boolean>()
3301
+
3302
+ /** Whether a tsconfig `include` or `exclude` entry takes in `file` (app-relative), the way tsc reads it. */
3303
+ function matches(pattern: string, file: string): boolean {
3304
+ let match = matchers.get(pattern)
3305
+ if (match === undefined) {
3306
+ let spec = pattern.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "")
3307
+ if (spec === "" || spec === ".") match = () => true
3308
+ else if (!/[*?]/.test(spec)) {
3309
+ const folder = `${spec}/`
3310
+ match = (path) => path === spec || path.startsWith(folder)
3311
+ } else {
3312
+ if (spec.endsWith("**")) spec = `${spec}/*`
3313
+ else if (!/[*?.][^/]*$/.test(spec.slice(spec.lastIndexOf("/") + 1))) spec = `${spec}/**/*`
3314
+ const glob = new Bun.Glob(spec)
3315
+ match = (path) => glob.match(path)
3316
+ }
3317
+ matchers.set(pattern, match)
3318
+ }
3319
+ return match(file)
3320
+ }
3321
+
3322
+ const TSCONFIG = /^tsconfig(?:\.[\w-]+)?\.json$/
3323
+ const TS_FILE = /\.(?:[cm]?ts|tsx)$/
3324
+
3325
+ interface ProgramLists {
3326
+ readonly include: readonly string[]
3327
+ readonly exclude: readonly string[]
3328
+ readonly files: readonly string[]
3329
+ }
3330
+
3331
+ const inProgram = (lists: ProgramLists, file: string): boolean =>
3332
+ lists.files.includes(file) ||
3333
+ (lists.include.some((pattern) => matches(pattern, file)) &&
3334
+ !lists.exclude.some((pattern) => matches(pattern, file)))
3335
+
3336
+ /** `pattern` under the zone folder `to` landed in, when that reaches `to`; else `to` itself. */
3337
+ function twinEntry(pattern: string | undefined, to: string): string {
3338
+ const slash = to.indexOf("/")
3339
+ if (pattern === undefined || slash === -1) return to
3340
+ const bare = pattern.replace(/^\.\//, "")
3341
+ const twin = `${to.slice(0, slash)}/${bare}`
3342
+ if (!matches(twin, to)) return to
3343
+ return bare === pattern ? twin : `./${twin}`
1979
3344
  }
1980
3345
 
1981
3346
  /**
1982
- * Add each zone folder that receives moved TypeScript to tsconfig `include`, editing only that array
1983
- * so comments and layout survive. A tsconfig without `include` (or with only `extends`) is left
1984
- * alone: tsc's default, or the base config, decides, and `nifra check` reports any folder left out.
3347
+ * Keep every TypeScript file in, or out of, each app-root `tsconfig*.json` program as it was. An entry
3348
+ * naming a moved file follows it; a folder or glob that took a moved file in gains its twin under the
3349
+ * zone folder (`src` -> `frontend/src`), and one that kept a file out does the same in `exclude`. So a
3350
+ * test run under its own config's types, or a folder left out on purpose, stays out after the move,
3351
+ * and code the config checked stays checked. An `include` or `exclude` a config inherits is not edited.
1985
3352
  */
1986
- function coverMovedFiles(
3353
+ function followTsconfigs(
1987
3354
  ts: typeof TS,
1988
3355
  root: string,
1989
- moves: ReadonlyArray<{ readonly from: string; readonly to: string }>,
1990
- ): { text?: string; added: string[]; issue?: string } | undefined {
1991
- const path = join(root, "tsconfig.json")
1992
- if (!existsSync(path)) return undefined
1993
- const text = readFileSync(path, "utf8")
1994
- const source = ts.parseJsonText(path, text)
1995
- const top = source.statements[0]?.expression
1996
- if (top === undefined || !ts.isObjectLiteralExpression(top))
1997
- return { added: [], issue: "is not a JSON object; add the zone folders to its include by hand" }
1998
- const include = jsonProperty(ts, top, "include")
1999
- if (include === undefined) return undefined
2000
- const array = include.initializer
2001
- if (!ts.isArrayLiteralExpression(array))
2002
- return { added: [], issue: '"include" is not an array; add the zone folders to it by hand' }
2003
- const patterns = array.elements.filter(ts.isStringLiteral).map((element) => element.text)
2004
- const added: string[] = []
2005
- for (const { to } of moves) {
2006
- if (!/\.(?:[cm]?ts|tsx)$/.test(to) || /\.d\.[cm]?ts$/.test(to)) continue
2007
- const folder = to.split("/")[0] ?? to
2008
- if (added.includes(folder) || patterns.some((pattern) => includes(pattern, to))) continue
2009
- added.push(folder)
2010
- }
2011
- if (added.length === 0) return undefined
2012
- added.sort(codeUnitOrder)
2013
- const quoted = added.map((folder) => JSON.stringify(folder))
3356
+ moves: ReadonlyMap<string, string>,
3357
+ layout: ReadonlyArray<{ readonly from: string; readonly to: string }>,
3358
+ ): {
3359
+ readonly files: Map<string, { readonly text: string; readonly changes: readonly string[] }>
3360
+ readonly issues: LayoutMigrationIssue[]
3361
+ } {
3362
+ const files = new Map<string, { readonly text: string; readonly changes: readonly string[] }>()
3363
+ const issues: LayoutMigrationIssue[] = []
3364
+ const typescript = layout.filter(({ to }) => TS_FILE.test(to))
3365
+ const names = readdirSync(root)
3366
+ .filter((name) => TSCONFIG.test(name) && isFile(join(root, name)))
3367
+ .sort(codeUnitOrder)
3368
+ // Each config's lists before and after the move, for the configs that extend it.
3369
+ const settled = new Map<string, { readonly before: ProgramLists; readonly after: ProgramLists }>()
3370
+ const pending = [...names]
3371
+ for (let progress = true; progress && pending.length > 0; ) {
3372
+ progress = false
3373
+ for (const name of [...pending]) {
3374
+ const text = readFileSync(join(root, name), "utf8")
3375
+ const source = ts.parseJsonText(name, text)
3376
+ const top = source.statements[0]?.expression
3377
+ if (top === undefined || !ts.isObjectLiteralExpression(top)) {
3378
+ pending.splice(pending.indexOf(name), 1)
3379
+ progress = true
3380
+ if (moves.size > 0)
3381
+ issues.push({
3382
+ file: name,
3383
+ reason: "is not a JSON object; keep the moved files in its include and exclude by hand",
3384
+ })
3385
+ continue
3386
+ }
3387
+ const base = jsonProperty(ts, top, "extends")?.initializer
3388
+ let parent: string | undefined
3389
+ if (base !== undefined && ts.isStringLiteral(base) && base.text.startsWith(".")) {
3390
+ const path = posix.normalize(base.text)
3391
+ const file = path.endsWith(".json") ? path : `${path}.json`
3392
+ if (names.includes(file) && file !== name) parent = file
3393
+ }
3394
+ if (parent !== undefined && pending.includes(parent)) continue
3395
+ pending.splice(pending.indexOf(name), 1)
3396
+ progress = true
3397
+ const inherited = parent === undefined ? undefined : settled.get(parent)
3398
+ const extendsOther = base !== undefined && inherited === undefined
3399
+
3400
+ const edits: Array<{ start: number; end: number; text: string }> = []
3401
+ const own = new Map<string, { before: string[]; after: string[] }>()
3402
+ let malformed: string | undefined
3403
+ for (const key of ["include", "exclude", "files"]) {
3404
+ const array = jsonProperty(ts, top, key)?.initializer
3405
+ if (array === undefined) continue
3406
+ if (!ts.isArrayLiteralExpression(array)) {
3407
+ malformed = key
3408
+ continue
3409
+ }
3410
+ const lists: { before: string[]; after: string[] } = { before: [], after: [] }
3411
+ for (const element of array.elements) {
3412
+ if (!ts.isStringLiteral(element)) continue
3413
+ const to = moves.get(posix.normalize(element.text))
3414
+ lists.before.push(element.text)
3415
+ if (to === undefined) {
3416
+ lists.after.push(element.text)
3417
+ continue
3418
+ }
3419
+ const spelled = element.text.startsWith("./") ? `./${to}` : to
3420
+ lists.after.push(spelled)
3421
+ edits.push({
3422
+ start: element.getStart(source) + 1,
3423
+ end: element.getEnd() - 1,
3424
+ text: spelled,
3425
+ })
3426
+ }
3427
+ own.set(key, lists)
3428
+ }
3429
+ let updated = text
3430
+ for (const edit of edits.sort((a, b) => b.start - a.start))
3431
+ updated = updated.slice(0, edit.start) + edit.text + updated.slice(edit.end)
3432
+ const changes: string[] = []
3433
+ if (edits.length > 0) changes.push(`${edits.length} file path(s) follow their moved files`)
3434
+
3435
+ const list = (key: "include" | "exclude", when: "before" | "after"): string[] | undefined => {
3436
+ const mine = own.get(key)
3437
+ if (mine !== undefined) return mine[when]
3438
+ if (inherited !== undefined) return [...inherited[when][key]]
3439
+ if (extendsOther) return undefined
3440
+ // tsc's default: everything below the config, unless `files` lists the program.
3441
+ return key === "exclude" ? [] : own.has("files") ? [] : ["**/*"]
3442
+ }
3443
+ const filesOf = (when: "before" | "after"): string[] =>
3444
+ (own.get("files")?.[when] ?? []).map((entry) => posix.normalize(entry))
3445
+ const beforeInclude = list("include", "before")
3446
+ const beforeExclude = list("exclude", "before")
3447
+ const afterInclude = list("include", "after")
3448
+ const afterExclude = list("exclude", "after")
3449
+ if (
3450
+ malformed !== undefined ||
3451
+ beforeInclude === undefined ||
3452
+ beforeExclude === undefined ||
3453
+ afterInclude === undefined ||
3454
+ afterExclude === undefined
3455
+ ) {
3456
+ if (malformed !== undefined && moves.size > 0)
3457
+ issues.push({
3458
+ file: name,
3459
+ reason: `"${malformed}" is not an array; keep the moved files in its program by hand`,
3460
+ })
3461
+ if (edits.length > 0) files.set(name, { text: updated, changes })
3462
+ continue
3463
+ }
3464
+ const before: ProgramLists = {
3465
+ include: beforeInclude,
3466
+ exclude: beforeExclude,
3467
+ files: filesOf("before"),
3468
+ }
3469
+ const after = { include: afterInclude, exclude: afterExclude, files: filesOf("after") }
3470
+ const added: { include: string[]; exclude: string[] } = { include: [], exclude: [] }
3471
+ let stranded: { readonly from: string; readonly to: string; readonly key: string } | undefined
3472
+ let strandedCount = 0
3473
+ const quiet = new Map<string, boolean>()
3474
+ // The whole zone folder is the entry that keeps covering code added there later, but only when
3475
+ // it takes in no file the config left out.
3476
+ const takesInOnlyChecked = (folder: string): boolean => {
3477
+ let safe = quiet.get(folder)
3478
+ if (safe === undefined) {
3479
+ const wider = { ...after, include: [...after.include, folder] }
3480
+ safe = typescript.every(
3481
+ (file) =>
3482
+ !matches(folder, file.to) ||
3483
+ inProgram(before, file.from) ||
3484
+ !inProgram(wider, file.to),
3485
+ )
3486
+ quiet.set(folder, safe)
3487
+ }
3488
+ return safe
3489
+ }
3490
+ for (const { from, to } of typescript) {
3491
+ if (!inProgram(before, from) || inProgram(after, to)) continue
3492
+ if (after.include.some((pattern) => matches(pattern, to))) {
3493
+ // Its new place sits under an `exclude` that did not hold the old one.
3494
+ stranded ??= { from, to, key: "exclude" }
3495
+ strandedCount++
3496
+ continue
3497
+ }
3498
+ const zone = to.includes("/") ? to.slice(0, to.indexOf("/")) : undefined
3499
+ const entry =
3500
+ zone !== undefined && takesInOnlyChecked(zone)
3501
+ ? zone
3502
+ : twinEntry(
3503
+ before.include.find((pattern) => matches(pattern, from)),
3504
+ to,
3505
+ )
3506
+ added.include.push(entry)
3507
+ after.include.push(entry)
3508
+ }
3509
+ for (const { from, to } of typescript) {
3510
+ if (inProgram(before, from) || !inProgram(after, to)) continue
3511
+ let entry = twinEntry(
3512
+ before.exclude.find((pattern) => matches(pattern, from)),
3513
+ to,
3514
+ )
3515
+ // A twin that would also drop a file the config checked is too wide: name the file.
3516
+ if (
3517
+ entry !== to &&
3518
+ typescript.some((other) => matches(entry, other.to) && inProgram(before, other.from))
3519
+ )
3520
+ entry = to
3521
+ added.exclude.push(entry)
3522
+ after.exclude.push(entry)
3523
+ }
3524
+ for (const key of ["include", "exclude"] as const) {
3525
+ const entries = [...new Set(added[key])].sort(codeUnitOrder)
3526
+ if (entries.length === 0) continue
3527
+ const reparsed = ts.parseJsonText(name, updated)
3528
+ const object = reparsed.statements[0]?.expression
3529
+ const array =
3530
+ object !== undefined && ts.isObjectLiteralExpression(object)
3531
+ ? jsonProperty(ts, object, key)?.initializer
3532
+ : undefined
3533
+ if (array === undefined || !ts.isArrayLiteralExpression(array)) {
3534
+ stranded ??= { from: "", to: entries[0] ?? "", key }
3535
+ strandedCount += entries.length
3536
+ continue
3537
+ }
3538
+ updated = appendToArray(reparsed, updated, array, entries)
3539
+ changes.push(`${key} += ${entries.join(", ")}`)
3540
+ }
3541
+ if (stranded !== undefined)
3542
+ issues.push({
3543
+ file: name,
3544
+ 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`,
3545
+ })
3546
+ settled.set(name, { before, after })
3547
+ if (changes.length > 0) files.set(name, { text: updated, changes })
3548
+ }
3549
+ }
3550
+ return { files, issues }
3551
+ }
3552
+
3553
+ /** `text` with `entries` appended to `array`: one per line in a multi-line array, else inline. */
3554
+ function appendToArray(
3555
+ source: TS.JsonSourceFile,
3556
+ text: string,
3557
+ array: TS.ArrayLiteralExpression,
3558
+ entries: readonly string[],
3559
+ ): string {
3560
+ const quoted = entries.map((entry) => JSON.stringify(entry))
2014
3561
  const last = array.elements[array.elements.length - 1]
2015
3562
  if (last === undefined) {
2016
3563
  const at = array.getStart(source) + 1
2017
- return { text: `${text.slice(0, at)}${quoted.join(", ")}${text.slice(at)}`, added }
3564
+ return `${text.slice(0, at)}${quoted.join(", ")}${text.slice(at)}`
2018
3565
  }
2019
3566
  let at = last.end
2020
3567
  const trailing = /^\s*,/.exec(text.slice(at))
@@ -2031,15 +3578,12 @@ function coverMovedFiles(
2031
3578
  trailing !== null
2032
3579
  ? text.slice(0, eol)
2033
3580
  : `${text.slice(0, last.end)},${text.slice(last.end, eol)}`
2034
- const entries = quoted.join(`,\n${indent}`)
2035
- return {
2036
- text: `${head}\n${indent}${entries}${trailing !== null ? "," : ""}${text.slice(eol)}`,
2037
- added,
2038
- }
3581
+ const lines = quoted.join(`,\n${indent}`)
3582
+ return `${head}\n${indent}${lines}${trailing !== null ? "," : ""}${text.slice(eol)}`
2039
3583
  }
2040
3584
  }
2041
3585
  const insert = trailing !== null ? ` ${quoted.join(", ")},` : `, ${quoted.join(", ")}`
2042
- return { text: `${text.slice(0, at)}${insert}${text.slice(at)}`, added }
3586
+ return `${text.slice(0, at)}${insert}${text.slice(at)}`
2043
3587
  }
2044
3588
 
2045
3589
  const jsonProperty = (
@@ -2072,6 +3616,111 @@ function insertProperty(
2072
3616
  return `${text.slice(0, last.end)},\n${indent}${entry}${text.slice(last.end)}`
2073
3617
  }
2074
3618
 
3619
+ /**
3620
+ * The `nifra.zones` entries that keep `inPlace` files where they are: for each, the widest folder
3621
+ * above it whose zoned files all take its side (a nested package stops the climb), else the file
3622
+ * itself. A file another side's suffix or a server built-in claims counts against a folder.
3623
+ */
3624
+ function zoneDeclarations(
3625
+ inPlace: ReadonlyMap<string, FolderSide>,
3626
+ files: readonly string[],
3627
+ text: (file: string) => string | undefined,
3628
+ configured: (file: string) => boolean,
3629
+ ): Map<string, FolderSide> {
3630
+ const sides = new Map<string, Set<string>>()
3631
+ const packages = new Set<string>()
3632
+ for (const file of files) {
3633
+ const top = file.split("/")[0] ?? ""
3634
+ if (!file.includes("/") || ZONE_DIRS.has(top)) continue
3635
+ if (posix.basename(file) === "package.json") {
3636
+ for (let dir = posix.dirname(file); dir !== "."; dir = posix.dirname(dir)) packages.add(dir)
3637
+ continue
3638
+ }
3639
+ // A configured path is more specific than any folder above it, so it never counts against one.
3640
+ if (isTestFile(file) || file.endsWith(".d.ts") || configured(file)) continue
3641
+ const suffix = /\.(frontend|backend|shared|fn)\.[cm]?[jt]sx?$/.exec(file)?.[1]
3642
+ const side =
3643
+ inPlace.get(file) ??
3644
+ (suffix === "fn" ? "backend" : suffix) ??
3645
+ (SOURCE_FILE.test(file) && /from\s+["'](?:node:|bun:)/.test(text(file) ?? "")
3646
+ ? "backend"
3647
+ : undefined)
3648
+ if (side === undefined) continue
3649
+ for (let dir = posix.dirname(file); dir !== "."; dir = posix.dirname(dir))
3650
+ sides.set(dir, (sides.get(dir) ?? new Set<string>()).add(side))
3651
+ }
3652
+ const declared = new Map<string, FolderSide>()
3653
+ for (const [file, side] of [...inPlace].sort(([a], [b]) => codeUnitOrder(a, b))) {
3654
+ const parts = file.split("/")
3655
+ let path = file
3656
+ for (let depth = 1; depth < parts.length; depth++) {
3657
+ const dir = parts.slice(0, depth).join("/")
3658
+ const found = sides.get(dir)
3659
+ if (!packages.has(dir) && found?.size === 1 && found.has(side)) {
3660
+ path = dir
3661
+ break
3662
+ }
3663
+ }
3664
+ declared.set(path, side)
3665
+ }
3666
+ return declared
3667
+ }
3668
+
3669
+ /** The app's package.json with `paths` added to `"nifra": { "zones": ... }`, editing only where they go. */
3670
+ function declareZones(
3671
+ ts: typeof TS,
3672
+ root: string,
3673
+ paths: ReadonlyMap<string, FolderSide>,
3674
+ ): { text?: string; issue?: string } {
3675
+ const listed = (side: FolderSide): string[] =>
3676
+ [...paths].flatMap(([path, of]) => (of === side ? [path] : []))
3677
+ const setting = `{ ${FOLDER_SIDES.filter((side) => listed(side).length > 0)
3678
+ .map((side) => `"${side}": ${JSON.stringify(listed(side))}`)
3679
+ .join(", ")} }`
3680
+ const path = join(root, "package.json")
3681
+ if (!existsSync(path))
3682
+ return { issue: `there is none in the app; declare "nifra": { "zones": ${setting} } in it` }
3683
+ let text = readFileSync(path, "utf8")
3684
+ // Parsed again for each edit: an edit moves every offset after it.
3685
+ const find = (keys: readonly string[]) => {
3686
+ const source = ts.parseJsonText(path, text)
3687
+ let node: TS.Expression | undefined = source.statements[0]?.expression
3688
+ for (const key of keys)
3689
+ node =
3690
+ node !== undefined && ts.isObjectLiteralExpression(node)
3691
+ ? jsonProperty(ts, node, key)?.initializer
3692
+ : undefined
3693
+ return { source, node }
3694
+ }
3695
+ const top = find([])
3696
+ if (top.node === undefined || !ts.isObjectLiteralExpression(top.node))
3697
+ return { issue: `is not a JSON object; add "nifra": { "zones": ${setting} } to it by hand` }
3698
+ const nifra = find(["nifra"])
3699
+ if (nifra.node === undefined)
3700
+ return { text: insertProperty(top.source, text, top.node, `"nifra": { "zones": ${setting} }`) }
3701
+ if (!ts.isObjectLiteralExpression(nifra.node))
3702
+ return { issue: `"nifra" is not an object; add "zones": ${setting} to it by hand` }
3703
+ const zones = find(["nifra", "zones"])
3704
+ if (zones.node === undefined)
3705
+ return { text: insertProperty(nifra.source, text, nifra.node, `"zones": ${setting}`) }
3706
+ for (const side of FOLDER_SIDES) {
3707
+ const add = listed(side)
3708
+ if (add.length === 0) continue
3709
+ const { source, node } = find(["nifra", "zones"])
3710
+ if (node === undefined || !ts.isObjectLiteralExpression(node))
3711
+ return { issue: `"nifra.zones" is not an object; add ${setting} to it by hand` }
3712
+ const array = jsonProperty(ts, node, side)?.initializer
3713
+ if (array === undefined)
3714
+ text = insertProperty(source, text, node, `"${side}": ${JSON.stringify(add)}`)
3715
+ else if (ts.isArrayLiteralExpression(array)) text = appendToArray(source, text, array, add)
3716
+ else
3717
+ return {
3718
+ issue: `"nifra.zones.${side}" is not an array; add ${JSON.stringify(add)} to it by hand`,
3719
+ }
3720
+ }
3721
+ return { text }
3722
+ }
3723
+
2075
3724
  /** The app's package.json with `"nifra": { "kind": "api" }` added, editing only where it goes. */
2076
3725
  function declareApiKind(ts: typeof TS, root: string): { text?: string; issue?: string } {
2077
3726
  const path = join(root, "package.json")
@@ -2095,6 +3744,80 @@ function declareApiKind(ts: typeof TS, root: string): { text?: string; issue?: s
2095
3744
  return { text: insertProperty(source, text, nifra.initializer, '"kind": "api"') }
2096
3745
  }
2097
3746
 
3747
+ /** package.json fields whose string values name files from the package folder. */
3748
+ const PACKAGE_PATH_FIELDS = new Set([
3749
+ "main",
3750
+ "module",
3751
+ "types",
3752
+ "typings",
3753
+ "browser",
3754
+ "source",
3755
+ "bin",
3756
+ "exports",
3757
+ "imports",
3758
+ "files",
3759
+ "scripts",
3760
+ ])
3761
+
3762
+ /**
3763
+ * `text` (a package.json at the app root) with each moved file it names by its exact path, in the
3764
+ * fields above, named at its new path; `./` kept as written. A value with a `*` outside `scripts` is a
3765
+ * pattern over a folder, which no single move settles, so it stays and the path scan reports it.
3766
+ */
3767
+ function rewritePackagePaths(
3768
+ ts: typeof TS,
3769
+ text: string,
3770
+ moves: ReadonlyMap<string, string>,
3771
+ ): { readonly text: string; readonly count: number } {
3772
+ const source = ts.parseJsonText("package.json", text)
3773
+ const top = source.statements[0]?.expression
3774
+ if (top === undefined || !ts.isObjectLiteralExpression(top) || moves.size === 0)
3775
+ return { text, count: 0 }
3776
+ // Longest first, so `lib/a.test.ts` is not read as `lib/a.ts` with a tail.
3777
+ const ordered = [...moves].sort(([a], [b]) => b.length - a.length)
3778
+ const pattern = new RegExp(
3779
+ `(?<![\\w.@/-])(\\./)?(${ordered.map(([from]) => escapeRegExp(from)).join("|")})(?![\\w/-]|\\.\\w)`,
3780
+ "g",
3781
+ )
3782
+ const edits: Array<{ start: number; end: number; text: string }> = []
3783
+ let count = 0
3784
+ const visit = (node: TS.Node, field: string): void => {
3785
+ if (ts.isStringLiteral(node)) {
3786
+ if (field !== "scripts" && node.text.includes("*")) return
3787
+ const value = node.text.replace(pattern, (_match, dot: string | undefined, from: string) => {
3788
+ count += 1
3789
+ return `${dot ?? ""}${moves.get(from) ?? from}`
3790
+ })
3791
+ if (value !== node.text)
3792
+ edits.push({
3793
+ start: node.getStart(source),
3794
+ end: node.getEnd(),
3795
+ text: JSON.stringify(value),
3796
+ })
3797
+ return
3798
+ }
3799
+ if (ts.isArrayLiteralExpression(node)) {
3800
+ for (const element of node.elements) visit(element, field)
3801
+ return
3802
+ }
3803
+ if (!ts.isObjectLiteralExpression(node)) return
3804
+ for (const property of node.properties) {
3805
+ if (!ts.isPropertyAssignment(property)) continue
3806
+ // `"//x"` keys are comments by npm convention.
3807
+ if (ts.isStringLiteral(property.name) && property.name.text.startsWith("//")) continue
3808
+ visit(property.initializer, field)
3809
+ }
3810
+ }
3811
+ for (const property of top.properties) {
3812
+ if (!ts.isPropertyAssignment(property) || !ts.isStringLiteral(property.name)) continue
3813
+ if (PACKAGE_PATH_FIELDS.has(property.name.text)) visit(property.initializer, property.name.text)
3814
+ }
3815
+ let next = text
3816
+ for (const edit of edits.sort((a, b) => b.start - a.start))
3817
+ next = next.slice(0, edit.start) + edit.text + next.slice(edit.end)
3818
+ return { text: next, count }
3819
+ }
3820
+
2098
3821
  /** Tailwind `content` globs that matched a moved file at its old path and match nothing at its new one. */
2099
3822
  function staleContentGlobs(
2100
3823
  ts: typeof TS,