@nifrajs/cli 5.16.0 → 5.18.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 (183) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/dist/check-diagnostics.d.ts +7 -0
  3. package/dist/check-diagnostics.d.ts.map +1 -1
  4. package/dist/check-diagnostics.js +3 -0
  5. package/dist/check-diagnostics.js.map +1 -1
  6. package/dist/check-scan-sql.d.ts +95 -0
  7. package/dist/check-scan-sql.d.ts.map +1 -0
  8. package/dist/check-scan-sql.js +1190 -0
  9. package/dist/check-scan-sql.js.map +1 -0
  10. package/dist/check-scan.d.ts +5 -93
  11. package/dist/check-scan.d.ts.map +1 -1
  12. package/dist/check-scan.js +20 -1207
  13. package/dist/check-scan.js.map +1 -1
  14. package/dist/check.d.ts.map +1 -1
  15. package/dist/check.js +9 -0
  16. package/dist/check.js.map +1 -1
  17. package/dist/cli.d.ts +2 -6
  18. package/dist/cli.d.ts.map +1 -1
  19. package/dist/cli.js +249 -80
  20. package/dist/cli.js.map +1 -1
  21. package/dist/command-catalog.d.ts +3 -0
  22. package/dist/command-catalog.d.ts.map +1 -1
  23. package/dist/command-catalog.js +18 -4
  24. package/dist/command-catalog.js.map +1 -1
  25. package/dist/frontend-guidance.js +1 -1
  26. package/dist/frontend-guidance.js.map +1 -1
  27. package/dist/internal/a11y-element.d.ts +33 -0
  28. package/dist/internal/a11y-element.d.ts.map +1 -0
  29. package/dist/internal/a11y-element.js +124 -0
  30. package/dist/internal/a11y-element.js.map +1 -0
  31. package/dist/internal/a11y-jsx.d.ts +12 -0
  32. package/dist/internal/a11y-jsx.d.ts.map +1 -0
  33. package/dist/internal/a11y-jsx.js +42 -0
  34. package/dist/internal/a11y-jsx.js.map +1 -0
  35. package/dist/internal/a11y-template.d.ts +11 -0
  36. package/dist/internal/a11y-template.d.ts.map +1 -0
  37. package/dist/internal/a11y-template.js +56 -0
  38. package/dist/internal/a11y-template.js.map +1 -0
  39. package/dist/internal/aria-data.d.ts +23 -0
  40. package/dist/internal/aria-data.d.ts.map +1 -0
  41. package/dist/internal/aria-data.js +220 -0
  42. package/dist/internal/aria-data.js.map +1 -0
  43. package/dist/internal/edit-distance.d.ts +3 -0
  44. package/dist/internal/edit-distance.d.ts.map +1 -0
  45. package/dist/internal/edit-distance.js +12 -0
  46. package/dist/internal/edit-distance.js.map +1 -0
  47. package/dist/internal/imported-as.d.ts +10 -0
  48. package/dist/internal/imported-as.d.ts.map +1 -0
  49. package/dist/internal/imported-as.js +23 -0
  50. package/dist/internal/imported-as.js.map +1 -0
  51. package/dist/internal/source-facts.d.ts +3 -0
  52. package/dist/internal/source-facts.d.ts.map +1 -1
  53. package/dist/internal/source-facts.js +2 -0
  54. package/dist/internal/source-facts.js.map +1 -1
  55. package/dist/internal/template-markup.d.ts +58 -0
  56. package/dist/internal/template-markup.d.ts.map +1 -0
  57. package/dist/internal/template-markup.js +221 -0
  58. package/dist/internal/template-markup.js.map +1 -0
  59. package/dist/internal/typescript-import.d.ts.map +1 -1
  60. package/dist/internal/typescript-import.js +11 -0
  61. package/dist/internal/typescript-import.js.map +1 -1
  62. package/dist/mcp-exec.d.ts.map +1 -1
  63. package/dist/mcp-exec.js +37 -23
  64. package/dist/mcp-exec.js.map +1 -1
  65. package/dist/mcp-http.js +1 -1
  66. package/dist/mcp-io.d.ts.map +1 -1
  67. package/dist/mcp-io.js +5 -3
  68. package/dist/mcp-io.js.map +1 -1
  69. package/dist/mcp-root.js +1 -1
  70. package/dist/mcp-root.js.map +1 -1
  71. package/dist/mcp-ws.d.ts.map +1 -1
  72. package/dist/mcp-ws.js +3 -2
  73. package/dist/mcp-ws.js.map +1 -1
  74. package/dist/migrate-layout-config.d.ts +63 -0
  75. package/dist/migrate-layout-config.d.ts.map +1 -0
  76. package/dist/migrate-layout-config.js +507 -0
  77. package/dist/migrate-layout-config.js.map +1 -0
  78. package/dist/migrate-layout-split.d.ts +46 -0
  79. package/dist/migrate-layout-split.d.ts.map +1 -0
  80. package/dist/migrate-layout-split.js +687 -0
  81. package/dist/migrate-layout-split.js.map +1 -0
  82. package/dist/migrate-layout.d.ts +4 -24
  83. package/dist/migrate-layout.d.ts.map +1 -1
  84. package/dist/migrate-layout.js +8 -1183
  85. package/dist/migrate-layout.js.map +1 -1
  86. package/dist/output-schemas.d.ts.map +1 -1
  87. package/dist/output-schemas.js +78 -10
  88. package/dist/output-schemas.js.map +1 -1
  89. package/dist/recipes/5.17.0.d.ts +10 -0
  90. package/dist/recipes/5.17.0.d.ts.map +1 -0
  91. package/dist/recipes/5.17.0.js +20 -0
  92. package/dist/recipes/5.17.0.js.map +1 -0
  93. package/dist/recipes/5.18.0.d.ts +9 -0
  94. package/dist/recipes/5.18.0.d.ts.map +1 -0
  95. package/dist/recipes/5.18.0.js +56 -0
  96. package/dist/recipes/5.18.0.js.map +1 -0
  97. package/dist/recipes/index.d.ts.map +1 -1
  98. package/dist/recipes/index.js +4 -0
  99. package/dist/recipes/index.js.map +1 -1
  100. package/dist/review.d.ts.map +1 -1
  101. package/dist/review.js +6 -0
  102. package/dist/review.js.map +1 -1
  103. package/dist/rules/a11y.d.ts +5 -0
  104. package/dist/rules/a11y.d.ts.map +1 -0
  105. package/dist/rules/a11y.js +78 -0
  106. package/dist/rules/a11y.js.map +1 -0
  107. package/dist/rules/codes.d.ts +6 -0
  108. package/dist/rules/codes.d.ts.map +1 -1
  109. package/dist/rules/codes.js +6 -0
  110. package/dist/rules/codes.js.map +1 -1
  111. package/dist/rules/comment-markers.js +1 -1
  112. package/dist/rules/comment-markers.js.map +1 -1
  113. package/dist/rules/explanations.d.ts.map +1 -1
  114. package/dist/rules/explanations.js +30 -0
  115. package/dist/rules/explanations.js.map +1 -1
  116. package/dist/rules/host-exposure.d.ts +23 -0
  117. package/dist/rules/host-exposure.d.ts.map +1 -0
  118. package/dist/rules/host-exposure.js +380 -0
  119. package/dist/rules/host-exposure.js.map +1 -0
  120. package/dist/rules/internal-links.d.ts.map +1 -1
  121. package/dist/rules/internal-links.js +16 -141
  122. package/dist/rules/internal-links.js.map +1 -1
  123. package/dist/rules/islands.d.ts +54 -0
  124. package/dist/rules/islands.d.ts.map +1 -1
  125. package/dist/rules/islands.js +577 -80
  126. package/dist/rules/islands.js.map +1 -1
  127. package/dist/rules/security.d.ts +1 -0
  128. package/dist/rules/security.d.ts.map +1 -1
  129. package/dist/rules/security.js +34 -7
  130. package/dist/rules/security.js.map +1 -1
  131. package/dist/runtime-differences.js +3 -3
  132. package/dist/runtime-differences.js.map +1 -1
  133. package/dist/scaffold.d.ts +1 -1
  134. package/dist/scaffold.d.ts.map +1 -1
  135. package/dist/scaffold.js +2 -2
  136. package/dist/scaffold.js.map +1 -1
  137. package/dist/source-rewrites.d.ts.map +1 -1
  138. package/dist/source-rewrites.js +2 -19
  139. package/dist/source-rewrites.js.map +1 -1
  140. package/docs/examples.json +4 -4
  141. package/docs/llms-full.txt +443 -46
  142. package/docs/types.json +490 -66
  143. package/package.json +12 -12
  144. package/src/check-diagnostics.ts +11 -0
  145. package/src/check-scan-sql.ts +1746 -0
  146. package/src/check-scan.ts +34 -1754
  147. package/src/check.ts +10 -1
  148. package/src/cli.ts +258 -98
  149. package/src/command-catalog.ts +21 -4
  150. package/src/frontend-guidance.ts +1 -1
  151. package/src/internal/a11y-element.ts +227 -0
  152. package/src/internal/a11y-jsx.ts +54 -0
  153. package/src/internal/a11y-template.ts +74 -0
  154. package/src/internal/aria-data.ts +242 -0
  155. package/src/internal/edit-distance.ts +16 -0
  156. package/src/internal/imported-as.ts +30 -0
  157. package/src/internal/source-facts.ts +4 -0
  158. package/src/internal/template-markup.ts +270 -0
  159. package/src/internal/typescript-import.ts +15 -0
  160. package/src/mcp-exec.ts +43 -22
  161. package/src/mcp-http.ts +1 -1
  162. package/src/mcp-io.ts +5 -3
  163. package/src/mcp-root.ts +1 -1
  164. package/src/mcp-ws.ts +3 -2
  165. package/src/migrate-layout-config.ts +615 -0
  166. package/src/migrate-layout-split.ts +870 -0
  167. package/src/migrate-layout.ts +37 -1468
  168. package/src/output-schemas.ts +85 -17
  169. package/src/recipes/5.17.0.ts +28 -0
  170. package/src/recipes/5.18.0.ts +63 -0
  171. package/src/recipes/index.ts +4 -0
  172. package/src/review.ts +6 -0
  173. package/src/rules/a11y.ts +119 -0
  174. package/src/rules/codes.ts +6 -0
  175. package/src/rules/comment-markers.ts +2 -2
  176. package/src/rules/explanations.ts +30 -0
  177. package/src/rules/host-exposure.ts +531 -0
  178. package/src/rules/internal-links.ts +21 -154
  179. package/src/rules/islands.ts +698 -86
  180. package/src/rules/security.ts +48 -7
  181. package/src/runtime-differences.ts +3 -3
  182. package/src/scaffold.ts +3 -3
  183. package/src/source-rewrites.ts +2 -15
@@ -0,0 +1,615 @@
1
+ /**
2
+ * Tsconfig, package.json, zone declarations, and filesystem cleanup helpers for `nifra migrate layout`.
3
+ */
4
+ import { existsSync, readdirSync, readFileSync, rmdirSync } from "node:fs"
5
+ import { dirname, join, posix, sep } from "node:path"
6
+ import { parseZoneConfig, type ZoneConfig } from "@nifrajs/web/zones"
7
+ import type * as TS from "typescript"
8
+ import { codeUnitOrder } from "./internal/code-unit-order.ts"
9
+ import { escapeRegExp } from "./internal/escape-regexp.ts"
10
+ import { isFile } from "./internal/project-specifiers.ts"
11
+ import { isTestFile, type LayoutMigrationIssue, SOURCE_FILE, ZONE_DIRS } from "./migrate-layout.ts"
12
+ import { applyEdits, type TextEdit } from "./migrate-layout-split.ts"
13
+
14
+ export type FolderSide = "frontend" | "backend" | "shared"
15
+ export const FOLDER_SIDES: readonly FolderSide[] = ["frontend", "backend", "shared"]
16
+
17
+ /** The app's `"nifra": { "zones": ... }`, so folders it already zones are left where they are. */
18
+ export function appZones(root: string): ZoneConfig {
19
+ const manifest = join(root, "package.json")
20
+ if (!existsSync(manifest)) return {}
21
+ let parsed: unknown
22
+ try {
23
+ parsed = JSON.parse(readFileSync(manifest, "utf8"))
24
+ } catch {
25
+ return {}
26
+ }
27
+ const nifra =
28
+ typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "nifra") : undefined
29
+ const zones =
30
+ typeof nifra === "object" && nifra !== null ? Reflect.get(nifra, "zones") : undefined
31
+ return zones === undefined ? {} : parseZoneConfig(zones, manifest)
32
+ }
33
+
34
+ const matchers = new Map<string, (file: string) => boolean>()
35
+
36
+ /** Whether a tsconfig `include` or `exclude` entry takes in `file` (app-relative), the way tsc reads it. */
37
+ function matches(pattern: string, file: string): boolean {
38
+ let match = matchers.get(pattern)
39
+ if (match === undefined) {
40
+ let spec = pattern
41
+ .replaceAll("\\", "/")
42
+ .replace(/^\.\//, "")
43
+ .replace(/(?<!\/)\/+$/, "")
44
+ if (spec === "" || spec === ".") match = () => true
45
+ else if (!/[*?]/.test(spec)) {
46
+ const folder = `${spec}/`
47
+ match = (path) => path === spec || path.startsWith(folder)
48
+ } else {
49
+ if (spec.endsWith("**")) spec = `${spec}/*`
50
+ else if (!/[*?.][^/]*$/.test(spec.slice(spec.lastIndexOf("/") + 1))) spec = `${spec}/**/*`
51
+ const glob = new Bun.Glob(spec)
52
+ match = (path) => glob.match(path)
53
+ }
54
+ matchers.set(pattern, match)
55
+ }
56
+ return match(file)
57
+ }
58
+
59
+ const TSCONFIG = /^tsconfig(?:\.[\w-]+)?\.json$/
60
+ const TS_FILE = /\.(?:[cm]?ts|tsx)$/
61
+
62
+ interface ProgramLists {
63
+ readonly include: readonly string[]
64
+ readonly exclude: readonly string[]
65
+ readonly files: readonly string[]
66
+ }
67
+
68
+ const inProgram = (lists: ProgramLists, file: string): boolean =>
69
+ lists.files.includes(file) ||
70
+ (lists.include.some((pattern) => matches(pattern, file)) &&
71
+ !lists.exclude.some((pattern) => matches(pattern, file)))
72
+
73
+ /** `pattern` under the zone folder `to` landed in, when that reaches `to`; else `to` itself. */
74
+ function twinEntry(pattern: string | undefined, to: string): string {
75
+ const slash = to.indexOf("/")
76
+ if (pattern === undefined || slash === -1) return to
77
+ const bare = pattern.replace(/^\.\//, "")
78
+ const twin = `${to.slice(0, slash)}/${bare}`
79
+ if (!matches(twin, to)) return to
80
+ return bare === pattern ? twin : `./${twin}`
81
+ }
82
+
83
+ /**
84
+ * Keep every TypeScript file in, or out of, each app-root `tsconfig*.json` program as it was. An entry
85
+ * naming a moved file follows it; a folder or glob that took a moved file in gains its twin under the
86
+ * zone folder (`src` -> `frontend/src`), and one that kept a file out does the same in `exclude`. So a
87
+ * test run under its own config's types, or a folder left out on purpose, stays out after the move,
88
+ * and code the config checked stays checked. An `include` or `exclude` a config inherits is not edited.
89
+ */
90
+ export function followTsconfigs(
91
+ ts: typeof TS,
92
+ root: string,
93
+ moves: ReadonlyMap<string, string>,
94
+ layout: ReadonlyArray<{ readonly from: string; readonly to: string }>,
95
+ ): {
96
+ readonly files: Map<string, { readonly text: string; readonly changes: readonly string[] }>
97
+ readonly issues: LayoutMigrationIssue[]
98
+ } {
99
+ const files = new Map<string, { readonly text: string; readonly changes: readonly string[] }>()
100
+ const issues: LayoutMigrationIssue[] = []
101
+ const typescript = layout.filter(({ to }) => TS_FILE.test(to))
102
+ const names = readdirSync(root)
103
+ .filter((name) => TSCONFIG.test(name) && isFile(join(root, name)))
104
+ .sort(codeUnitOrder)
105
+ // Each config's lists before and after the move, for the configs that extend it.
106
+ const settled = new Map<string, { readonly before: ProgramLists; readonly after: ProgramLists }>()
107
+ const pending = [...names]
108
+ for (let progress = true; progress && pending.length > 0; ) {
109
+ progress = false
110
+ for (const name of [...pending]) {
111
+ const text = readFileSync(join(root, name), "utf8")
112
+ const source = ts.parseJsonText(name, text)
113
+ const top = source.statements[0]?.expression
114
+ if (top === undefined || !ts.isObjectLiteralExpression(top)) {
115
+ pending.splice(pending.indexOf(name), 1)
116
+ progress = true
117
+ if (moves.size > 0)
118
+ issues.push({
119
+ file: name,
120
+ reason: "is not a JSON object; keep the moved files in its include and exclude by hand",
121
+ })
122
+ continue
123
+ }
124
+ const base = jsonProperty(ts, top, "extends")?.initializer
125
+ let parent: string | undefined
126
+ if (base !== undefined && ts.isStringLiteral(base) && base.text.startsWith(".")) {
127
+ const path = posix.normalize(base.text)
128
+ const file = path.endsWith(".json") ? path : `${path}.json`
129
+ if (names.includes(file) && file !== name) parent = file
130
+ }
131
+ if (parent !== undefined && pending.includes(parent)) continue
132
+ pending.splice(pending.indexOf(name), 1)
133
+ progress = true
134
+ const inherited = parent === undefined ? undefined : settled.get(parent)
135
+ const extendsOther = base !== undefined && inherited === undefined
136
+
137
+ const edits: TextEdit[] = []
138
+ const own = new Map<string, { before: string[]; after: string[] }>()
139
+ let malformed: string | undefined
140
+ for (const key of ["include", "exclude", "files"]) {
141
+ const array = jsonProperty(ts, top, key)?.initializer
142
+ if (array === undefined) continue
143
+ if (!ts.isArrayLiteralExpression(array)) {
144
+ malformed = key
145
+ continue
146
+ }
147
+ const lists: { before: string[]; after: string[] } = { before: [], after: [] }
148
+ for (const element of array.elements) {
149
+ if (!ts.isStringLiteral(element)) continue
150
+ const to = moves.get(posix.normalize(element.text))
151
+ lists.before.push(element.text)
152
+ if (to === undefined) {
153
+ lists.after.push(element.text)
154
+ continue
155
+ }
156
+ const spelled = element.text.startsWith("./") ? `./${to}` : to
157
+ lists.after.push(spelled)
158
+ edits.push({
159
+ start: element.getStart(source) + 1,
160
+ end: element.getEnd() - 1,
161
+ text: spelled,
162
+ })
163
+ }
164
+ own.set(key, lists)
165
+ }
166
+ let updated = applyEdits(text, edits)
167
+ const changes: string[] = []
168
+ if (edits.length > 0) changes.push(`${edits.length} file path(s) follow their moved files`)
169
+
170
+ const list = (key: "include" | "exclude", when: "before" | "after"): string[] | undefined => {
171
+ const mine = own.get(key)
172
+ if (mine !== undefined) return mine[when]
173
+ if (inherited !== undefined) return [...inherited[when][key]]
174
+ if (extendsOther) return undefined
175
+ // tsc's default: everything below the config, unless `files` lists the program.
176
+ return key === "exclude" ? [] : own.has("files") ? [] : ["**/*"]
177
+ }
178
+ const filesOf = (when: "before" | "after"): string[] =>
179
+ (own.get("files")?.[when] ?? []).map((entry) => posix.normalize(entry))
180
+ const beforeInclude = list("include", "before")
181
+ const beforeExclude = list("exclude", "before")
182
+ const afterInclude = list("include", "after")
183
+ const afterExclude = list("exclude", "after")
184
+ if (
185
+ malformed !== undefined ||
186
+ beforeInclude === undefined ||
187
+ beforeExclude === undefined ||
188
+ afterInclude === undefined ||
189
+ afterExclude === undefined
190
+ ) {
191
+ if (malformed !== undefined && moves.size > 0)
192
+ issues.push({
193
+ file: name,
194
+ reason: `"${malformed}" is not an array; keep the moved files in its program by hand`,
195
+ })
196
+ if (edits.length > 0) files.set(name, { text: updated, changes })
197
+ continue
198
+ }
199
+ const before: ProgramLists = {
200
+ include: beforeInclude,
201
+ exclude: beforeExclude,
202
+ files: filesOf("before"),
203
+ }
204
+ const after = { include: afterInclude, exclude: afterExclude, files: filesOf("after") }
205
+ const added: { include: string[]; exclude: string[] } = { include: [], exclude: [] }
206
+ let stranded: { readonly from: string; readonly to: string; readonly key: string } | undefined
207
+ let strandedCount = 0
208
+ const quiet = new Map<string, boolean>()
209
+ // The whole zone folder is the entry that keeps covering code added there later, but only when
210
+ // it takes in no file the config left out.
211
+ const takesInOnlyChecked = (folder: string): boolean => {
212
+ let safe = quiet.get(folder)
213
+ if (safe === undefined) {
214
+ const wider = { ...after, include: [...after.include, folder] }
215
+ safe = typescript.every(
216
+ (file) =>
217
+ !matches(folder, file.to) ||
218
+ inProgram(before, file.from) ||
219
+ !inProgram(wider, file.to),
220
+ )
221
+ quiet.set(folder, safe)
222
+ }
223
+ return safe
224
+ }
225
+ for (const { from, to } of typescript) {
226
+ if (!inProgram(before, from) || inProgram(after, to)) continue
227
+ if (after.include.some((pattern) => matches(pattern, to))) {
228
+ // Its new place sits under an `exclude` that did not hold the old one.
229
+ stranded ??= { from, to, key: "exclude" }
230
+ strandedCount++
231
+ continue
232
+ }
233
+ const zone = to.includes("/") ? to.slice(0, to.indexOf("/")) : undefined
234
+ const entry =
235
+ zone !== undefined && takesInOnlyChecked(zone)
236
+ ? zone
237
+ : twinEntry(
238
+ before.include.find((pattern) => matches(pattern, from)),
239
+ to,
240
+ )
241
+ added.include.push(entry)
242
+ after.include.push(entry)
243
+ }
244
+ for (const { from, to } of typescript) {
245
+ if (inProgram(before, from) || !inProgram(after, to)) continue
246
+ let entry = twinEntry(
247
+ before.exclude.find((pattern) => matches(pattern, from)),
248
+ to,
249
+ )
250
+ // A twin that would also drop a file the config checked is too wide: name the file.
251
+ if (
252
+ entry !== to &&
253
+ typescript.some((other) => matches(entry, other.to) && inProgram(before, other.from))
254
+ )
255
+ entry = to
256
+ added.exclude.push(entry)
257
+ after.exclude.push(entry)
258
+ }
259
+ for (const key of ["include", "exclude"] as const) {
260
+ const entries = [...new Set(added[key])].sort(codeUnitOrder)
261
+ if (entries.length === 0) continue
262
+ const reparsed = ts.parseJsonText(name, updated)
263
+ const object = reparsed.statements[0]?.expression
264
+ const array =
265
+ object !== undefined && ts.isObjectLiteralExpression(object)
266
+ ? jsonProperty(ts, object, key)?.initializer
267
+ : undefined
268
+ if (array === undefined || !ts.isArrayLiteralExpression(array)) {
269
+ stranded ??= { from: "", to: entries[0] ?? "", key }
270
+ strandedCount += entries.length
271
+ continue
272
+ }
273
+ updated = appendToArray(reparsed, updated, array, entries)
274
+ changes.push(`${key} += ${entries.join(", ")}`)
275
+ }
276
+ if (stranded !== undefined)
277
+ issues.push({
278
+ file: name,
279
+ 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`,
280
+ })
281
+ settled.set(name, { before, after })
282
+ if (changes.length > 0) files.set(name, { text: updated, changes })
283
+ }
284
+ }
285
+ return { files, issues }
286
+ }
287
+
288
+ /** `text` with `entries` appended to `array`: one per line in a multi-line array, else inline. */
289
+ function appendToArray(
290
+ source: TS.JsonSourceFile,
291
+ text: string,
292
+ array: TS.ArrayLiteralExpression,
293
+ entries: readonly string[],
294
+ ): string {
295
+ const quoted = entries.map((entry) => JSON.stringify(entry))
296
+ const last = array.elements[array.elements.length - 1]
297
+ if (last === undefined) {
298
+ const at = array.getStart(source) + 1
299
+ return `${text.slice(0, at)}${quoted.join(", ")}${text.slice(at)}`
300
+ }
301
+ let at = last.end
302
+ const trailing = /^\s*,/.exec(text.slice(at))
303
+ if (trailing !== null) at += trailing[0].length
304
+ // A multi-line array gets one entry per line at the last element's indent, below any comment that
305
+ // closes the last element's line; anything else gets them inline.
306
+ if (text.slice(array.getStart(source), last.getStart(source)).includes("\n")) {
307
+ const lineStart = text.lastIndexOf("\n", last.getStart(source)) + 1
308
+ const indent = text.slice(lineStart, last.getStart(source)).match(/^\s*/)?.[0] ?? ""
309
+ const newline = text.indexOf("\n", at)
310
+ const eol = newline === -1 ? text.length : newline
311
+ if (/^\s*(?:\/\/.*|\/\*.*\*\/\s*)?$/.test(text.slice(at, eol))) {
312
+ const head =
313
+ trailing !== null
314
+ ? text.slice(0, eol)
315
+ : `${text.slice(0, last.end)},${text.slice(last.end, eol)}`
316
+ const lines = quoted.join(`,\n${indent}`)
317
+ return `${head}\n${indent}${lines}${trailing !== null ? "," : ""}${text.slice(eol)}`
318
+ }
319
+ }
320
+ const insert = trailing !== null ? ` ${quoted.join(", ")},` : `, ${quoted.join(", ")}`
321
+ return `${text.slice(0, at)}${insert}${text.slice(at)}`
322
+ }
323
+
324
+ const jsonProperty = (
325
+ ts: typeof TS,
326
+ object: TS.ObjectLiteralExpression,
327
+ key: string,
328
+ ): TS.PropertyAssignment | undefined =>
329
+ object.properties.find(
330
+ (property): property is TS.PropertyAssignment =>
331
+ ts.isPropertyAssignment(property) &&
332
+ ts.isStringLiteral(property.name) &&
333
+ property.name.text === key,
334
+ )
335
+
336
+ /** `text` with `entry` as the last property of `object`, on its own line when the object spans lines. */
337
+ function insertProperty(
338
+ source: TS.JsonSourceFile,
339
+ text: string,
340
+ object: TS.ObjectLiteralExpression,
341
+ entry: string,
342
+ ): string {
343
+ const open = object.getStart(source)
344
+ const last = object.properties[object.properties.length - 1]
345
+ if (last === undefined) return `${text.slice(0, open)}{ ${entry} }${text.slice(object.end)}`
346
+ const start = last.getStart(source)
347
+ if (!text.slice(open, start).includes("\n")) {
348
+ return `${text.slice(0, last.end)}, ${entry}${text.slice(last.end)}`
349
+ }
350
+ const indent = /^[ \t]*/.exec(text.slice(text.lastIndexOf("\n", start) + 1, start))?.[0] ?? ""
351
+ return `${text.slice(0, last.end)},\n${indent}${entry}${text.slice(last.end)}`
352
+ }
353
+
354
+ /**
355
+ * The `nifra.zones` entries that keep `inPlace` files where they are: for each, the widest folder
356
+ * above it whose zoned files all take its side (a nested package stops the climb), else the file
357
+ * itself. A file another side's suffix or a server built-in claims counts against a folder.
358
+ */
359
+ export function zoneDeclarations(
360
+ inPlace: ReadonlyMap<string, FolderSide>,
361
+ files: readonly string[],
362
+ text: (file: string) => string | undefined,
363
+ configured: (file: string) => boolean,
364
+ ): Map<string, FolderSide> {
365
+ const sides = new Map<string, Set<string>>()
366
+ const packages = new Set<string>()
367
+ for (const file of files) {
368
+ const top = file.split("/")[0] ?? ""
369
+ if (!file.includes("/") || ZONE_DIRS.has(top)) continue
370
+ if (posix.basename(file) === "package.json") {
371
+ for (let dir = posix.dirname(file); dir !== "."; dir = posix.dirname(dir)) packages.add(dir)
372
+ continue
373
+ }
374
+ // A configured path is more specific than any folder above it, so it never counts against one.
375
+ if (isTestFile(file) || file.endsWith(".d.ts") || configured(file)) continue
376
+ const suffix = /\.(frontend|backend|shared|fn)\.[cm]?[jt]sx?$/.exec(file)?.[1]
377
+ const side =
378
+ inPlace.get(file) ??
379
+ (suffix === "fn" ? "backend" : suffix) ??
380
+ (SOURCE_FILE.test(file) && /from\s+["'](?:node:|bun:)/.test(text(file) ?? "")
381
+ ? "backend"
382
+ : undefined)
383
+ if (side === undefined) continue
384
+ for (let dir = posix.dirname(file); dir !== "."; dir = posix.dirname(dir))
385
+ sides.set(dir, (sides.get(dir) ?? new Set<string>()).add(side))
386
+ }
387
+ const declared = new Map<string, FolderSide>()
388
+ for (const [file, side] of [...inPlace].sort(([a], [b]) => codeUnitOrder(a, b))) {
389
+ const parts = file.split("/")
390
+ let path = file
391
+ for (let depth = 1; depth < parts.length; depth++) {
392
+ const dir = parts.slice(0, depth).join("/")
393
+ const found = sides.get(dir)
394
+ if (!packages.has(dir) && found?.size === 1 && found.has(side)) {
395
+ path = dir
396
+ break
397
+ }
398
+ }
399
+ declared.set(path, side)
400
+ }
401
+ return declared
402
+ }
403
+
404
+ /** The app's package.json with `paths` added to `"nifra": { "zones": ... }`, editing only where they go. */
405
+ export function declareZones(
406
+ ts: typeof TS,
407
+ root: string,
408
+ paths: ReadonlyMap<string, FolderSide>,
409
+ ): { text?: string; issue?: string } {
410
+ const listed = (side: FolderSide): string[] =>
411
+ [...paths].flatMap(([path, of]) => (of === side ? [path] : []))
412
+ const setting = `{ ${FOLDER_SIDES.filter((side) => listed(side).length > 0)
413
+ .map((side) => `"${side}": ${JSON.stringify(listed(side))}`)
414
+ .join(", ")} }`
415
+ const path = join(root, "package.json")
416
+ if (!existsSync(path))
417
+ return { issue: `there is none in the app; declare "nifra": { "zones": ${setting} } in it` }
418
+ let text = readFileSync(path, "utf8")
419
+ // Parsed again for each edit: an edit moves every offset after it.
420
+ const find = (keys: readonly string[]) => {
421
+ const source = ts.parseJsonText(path, text)
422
+ let node: TS.Expression | undefined = source.statements[0]?.expression
423
+ for (const key of keys)
424
+ node =
425
+ node !== undefined && ts.isObjectLiteralExpression(node)
426
+ ? jsonProperty(ts, node, key)?.initializer
427
+ : undefined
428
+ return { source, node }
429
+ }
430
+ const top = find([])
431
+ if (top.node === undefined || !ts.isObjectLiteralExpression(top.node))
432
+ return { issue: `is not a JSON object; add "nifra": { "zones": ${setting} } to it by hand` }
433
+ const nifra = find(["nifra"])
434
+ if (nifra.node === undefined)
435
+ return { text: insertProperty(top.source, text, top.node, `"nifra": { "zones": ${setting} }`) }
436
+ if (!ts.isObjectLiteralExpression(nifra.node))
437
+ return { issue: `"nifra" is not an object; add "zones": ${setting} to it by hand` }
438
+ const zones = find(["nifra", "zones"])
439
+ if (zones.node === undefined)
440
+ return { text: insertProperty(nifra.source, text, nifra.node, `"zones": ${setting}`) }
441
+ for (const side of FOLDER_SIDES) {
442
+ const add = listed(side)
443
+ if (add.length === 0) continue
444
+ const { source, node } = find(["nifra", "zones"])
445
+ if (node === undefined || !ts.isObjectLiteralExpression(node))
446
+ return { issue: `"nifra.zones" is not an object; add ${setting} to it by hand` }
447
+ const array = jsonProperty(ts, node, side)?.initializer
448
+ if (array === undefined)
449
+ text = insertProperty(source, text, node, `"${side}": ${JSON.stringify(add)}`)
450
+ else if (ts.isArrayLiteralExpression(array)) text = appendToArray(source, text, array, add)
451
+ else
452
+ return {
453
+ issue: `"nifra.zones.${side}" is not an array; add ${JSON.stringify(add)} to it by hand`,
454
+ }
455
+ }
456
+ return { text }
457
+ }
458
+
459
+ /** The app's package.json with `"nifra": { "kind": "api" }` added, editing only where it goes. */
460
+ export function declareApiKind(ts: typeof TS, root: string): { text?: string; issue?: string } {
461
+ const path = join(root, "package.json")
462
+ if (!existsSync(path)) {
463
+ return {
464
+ issue:
465
+ 'there is none in the app; declare "nifra": { "kind": "api" } in the package.json that governs it',
466
+ }
467
+ }
468
+ const text = readFileSync(path, "utf8")
469
+ const source = ts.parseJsonText(path, text)
470
+ const top = source.statements[0]?.expression
471
+ if (top === undefined || !ts.isObjectLiteralExpression(top))
472
+ return { issue: 'is not a JSON object; add "nifra": { "kind": "api" } to it by hand' }
473
+ const nifra = jsonProperty(ts, top, "nifra")
474
+ if (nifra === undefined) {
475
+ return { text: insertProperty(source, text, top, '"nifra": { "kind": "api" }') }
476
+ }
477
+ if (!ts.isObjectLiteralExpression(nifra.initializer))
478
+ return { issue: '"nifra" is not an object; add "kind": "api" to it by hand' }
479
+ return { text: insertProperty(source, text, nifra.initializer, '"kind": "api"') }
480
+ }
481
+
482
+ /** package.json fields whose string values name files from the package folder. */
483
+ const PACKAGE_PATH_FIELDS = new Set([
484
+ "main",
485
+ "module",
486
+ "types",
487
+ "typings",
488
+ "browser",
489
+ "source",
490
+ "bin",
491
+ "exports",
492
+ "imports",
493
+ "files",
494
+ "scripts",
495
+ ])
496
+
497
+ /**
498
+ * `text` (a package.json at the app root) with each moved file it names by its exact path, in the
499
+ * fields above, named at its new path; `./` kept as written. A value with a `*` outside `scripts` is a
500
+ * pattern over a folder, which no single move settles, so it stays and the path scan reports it.
501
+ */
502
+ export function rewritePackagePaths(
503
+ ts: typeof TS,
504
+ text: string,
505
+ moves: ReadonlyMap<string, string>,
506
+ ): { readonly text: string; readonly count: number } {
507
+ const source = ts.parseJsonText("package.json", text)
508
+ const top = source.statements[0]?.expression
509
+ if (top === undefined || !ts.isObjectLiteralExpression(top) || moves.size === 0)
510
+ return { text, count: 0 }
511
+ // Longest first, so `lib/a.test.ts` is not read as `lib/a.ts` with a tail.
512
+ const ordered = [...moves].sort(([a], [b]) => b.length - a.length)
513
+ const pattern = new RegExp(
514
+ `(?<![\\w.@/-])(\\./)?(${ordered.map(([from]) => escapeRegExp(from)).join("|")})(?![\\w/-]|\\.\\w)`,
515
+ "g",
516
+ )
517
+ const edits: TextEdit[] = []
518
+ let count = 0
519
+ const visit = (node: TS.Node, field: string): void => {
520
+ if (ts.isStringLiteral(node)) {
521
+ if (field !== "scripts" && node.text.includes("*")) return
522
+ const value = node.text.replace(pattern, (_match, dot: string | undefined, from: string) => {
523
+ count += 1
524
+ return `${dot ?? ""}${moves.get(from) ?? from}`
525
+ })
526
+ if (value !== node.text)
527
+ edits.push({
528
+ start: node.getStart(source),
529
+ end: node.getEnd(),
530
+ text: JSON.stringify(value),
531
+ })
532
+ return
533
+ }
534
+ if (ts.isArrayLiteralExpression(node)) {
535
+ for (const element of node.elements) visit(element, field)
536
+ return
537
+ }
538
+ if (!ts.isObjectLiteralExpression(node)) return
539
+ for (const property of node.properties) {
540
+ if (!ts.isPropertyAssignment(property)) continue
541
+ // `"//x"` keys are comments by npm convention.
542
+ if (ts.isStringLiteral(property.name) && property.name.text.startsWith("//")) continue
543
+ visit(property.initializer, field)
544
+ }
545
+ }
546
+ for (const property of top.properties) {
547
+ if (!ts.isPropertyAssignment(property) || !ts.isStringLiteral(property.name)) continue
548
+ if (PACKAGE_PATH_FIELDS.has(property.name.text)) visit(property.initializer, property.name.text)
549
+ }
550
+ return { text: applyEdits(text, edits), count }
551
+ }
552
+
553
+ /** Tailwind `content` globs that matched a moved file at its old path and match nothing at its new one. */
554
+ export function staleContentGlobs(
555
+ ts: typeof TS,
556
+ text: string,
557
+ moves: ReadonlyArray<{ readonly from: string; readonly to: string }>,
558
+ ): string | undefined {
559
+ const globs: string[] = []
560
+ const source = ts.createSourceFile("tailwind.config.ts", text, ts.ScriptTarget.Latest, true)
561
+ const visit = (node: TS.Node): void => {
562
+ if (ts.isStringLiteralLike(node) && /[*/]/.test(node.text) && !node.text.startsWith("!"))
563
+ globs.push(node.text.replace(/^\.\//, ""))
564
+ ts.forEachChild(node, visit)
565
+ }
566
+ visit(source)
567
+ const matchers = globs.map((glob) => ({ glob, matcher: new Bun.Glob(glob) }))
568
+ const lost = moves.filter(
569
+ ({ from, to }) =>
570
+ matchers.some(({ matcher }) => matcher.match(from)) &&
571
+ !matchers.some(({ matcher }) => matcher.match(to)),
572
+ )
573
+ const first = lost[0]
574
+ if (first === undefined) return undefined
575
+ const folders = [...new Set(lost.map(({ to }) => to.split("/")[0] ?? to))].sort(codeUnitOrder)
576
+ return `its content globs matched ${lost.length} file(s) that move, but none of their new paths (such as "${first.from}" -> "${first.to}"), so Tailwind would stop seeing their classes. Add globs for ${folders.map((folder) => `"./${folder}/**/*"`).join(", ")} (with the extensions you use)`
577
+ }
578
+
579
+ /**
580
+ * `.nifra/` holds generated types, dev state and the dev server's launch token; none of it belongs in
581
+ * git. The new `.gitignore` text when it is not ignored yet, else `undefined`.
582
+ */
583
+ export function ignoreNifraState(root: string): string | undefined {
584
+ let exitCode: number | null = null
585
+ try {
586
+ exitCode = Bun.spawnSync(["git", "check-ignore", "-q", ".nifra/types"], {
587
+ cwd: root,
588
+ stdout: "ignore",
589
+ stderr: "ignore",
590
+ }).exitCode
591
+ } catch {
592
+ // No git installed: the same as no checkout.
593
+ }
594
+ if (exitCode === 0) return undefined
595
+ const path = join(root, ".gitignore")
596
+ const current = existsSync(path) ? readFileSync(path, "utf8") : ""
597
+ // Outside a git checkout `check-ignore` cannot answer; the app's own file decides.
598
+ if (exitCode !== 1 && /^\/?\.nifra(?:\/|\*|\/\*\*)?\s*$/m.test(current)) return undefined
599
+ const separator = current === "" || current.endsWith("\n") ? "" : "\n"
600
+ return `${current}${separator}.nifra/\n`
601
+ }
602
+
603
+ /** Remove each directory the run emptied, then each parent that leaves empty. A directory that was
604
+ * empty before the run is the app's own, not the migration's to remove. */
605
+ export function pruneVacatedDirs(root: string, vacated: Iterable<string>): void {
606
+ const dirs = new Set<string>()
607
+ for (const file of vacated) dirs.add(dirname(join(root, file)))
608
+ // Deepest first, so a parent is judged after its emptied children are gone.
609
+ for (const start of [...dirs].sort((a, b) => b.length - a.length)) {
610
+ for (let dir = start; dir !== root && dir.startsWith(`${root}${sep}`); dir = dirname(dir)) {
611
+ if (!existsSync(dir) || readdirSync(dir).length > 0) break
612
+ rmdirSync(dir)
613
+ }
614
+ }
615
+ }