@nifrajs/cli 5.17.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.
- package/CHANGELOG.md +50 -0
- package/dist/check-diagnostics.d.ts +7 -0
- package/dist/check-diagnostics.d.ts.map +1 -1
- package/dist/check-diagnostics.js +3 -0
- package/dist/check-diagnostics.js.map +1 -1
- package/dist/check-scan-sql.d.ts +95 -0
- package/dist/check-scan-sql.d.ts.map +1 -0
- package/dist/check-scan-sql.js +1190 -0
- package/dist/check-scan-sql.js.map +1 -0
- package/dist/check-scan.d.ts +5 -93
- package/dist/check-scan.d.ts.map +1 -1
- package/dist/check-scan.js +20 -1207
- package/dist/check-scan.js.map +1 -1
- package/dist/check.d.ts.map +1 -1
- package/dist/check.js +9 -0
- package/dist/check.js.map +1 -1
- package/dist/cli.d.ts +2 -6
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +249 -80
- package/dist/cli.js.map +1 -1
- package/dist/command-catalog.d.ts +3 -0
- package/dist/command-catalog.d.ts.map +1 -1
- package/dist/command-catalog.js +18 -4
- package/dist/command-catalog.js.map +1 -1
- package/dist/frontend-guidance.js +1 -1
- package/dist/frontend-guidance.js.map +1 -1
- package/dist/internal/a11y-element.d.ts +33 -0
- package/dist/internal/a11y-element.d.ts.map +1 -0
- package/dist/internal/a11y-element.js +124 -0
- package/dist/internal/a11y-element.js.map +1 -0
- package/dist/internal/a11y-jsx.d.ts +12 -0
- package/dist/internal/a11y-jsx.d.ts.map +1 -0
- package/dist/internal/a11y-jsx.js +42 -0
- package/dist/internal/a11y-jsx.js.map +1 -0
- package/dist/internal/a11y-template.d.ts +11 -0
- package/dist/internal/a11y-template.d.ts.map +1 -0
- package/dist/internal/a11y-template.js +56 -0
- package/dist/internal/a11y-template.js.map +1 -0
- package/dist/internal/aria-data.d.ts +23 -0
- package/dist/internal/aria-data.d.ts.map +1 -0
- package/dist/internal/aria-data.js +220 -0
- package/dist/internal/aria-data.js.map +1 -0
- package/dist/internal/edit-distance.d.ts +3 -0
- package/dist/internal/edit-distance.d.ts.map +1 -0
- package/dist/internal/edit-distance.js +12 -0
- package/dist/internal/edit-distance.js.map +1 -0
- package/dist/internal/imported-as.d.ts +10 -0
- package/dist/internal/imported-as.d.ts.map +1 -0
- package/dist/internal/imported-as.js +23 -0
- package/dist/internal/imported-as.js.map +1 -0
- package/dist/internal/source-facts.d.ts +3 -0
- package/dist/internal/source-facts.d.ts.map +1 -1
- package/dist/internal/source-facts.js +2 -0
- package/dist/internal/source-facts.js.map +1 -1
- package/dist/internal/template-markup.d.ts +58 -0
- package/dist/internal/template-markup.d.ts.map +1 -0
- package/dist/internal/template-markup.js +221 -0
- package/dist/internal/template-markup.js.map +1 -0
- package/dist/internal/typescript-import.d.ts.map +1 -1
- package/dist/internal/typescript-import.js +11 -0
- package/dist/internal/typescript-import.js.map +1 -1
- package/dist/mcp-exec.d.ts.map +1 -1
- package/dist/mcp-exec.js +37 -23
- package/dist/mcp-exec.js.map +1 -1
- package/dist/mcp-http.js +1 -1
- package/dist/mcp-io.d.ts.map +1 -1
- package/dist/mcp-io.js +5 -3
- package/dist/mcp-io.js.map +1 -1
- package/dist/mcp-root.js +1 -1
- package/dist/mcp-root.js.map +1 -1
- package/dist/mcp-ws.d.ts.map +1 -1
- package/dist/mcp-ws.js +3 -2
- package/dist/mcp-ws.js.map +1 -1
- package/dist/migrate-layout-config.d.ts +63 -0
- package/dist/migrate-layout-config.d.ts.map +1 -0
- package/dist/migrate-layout-config.js +507 -0
- package/dist/migrate-layout-config.js.map +1 -0
- package/dist/migrate-layout-split.d.ts +46 -0
- package/dist/migrate-layout-split.d.ts.map +1 -0
- package/dist/migrate-layout-split.js +687 -0
- package/dist/migrate-layout-split.js.map +1 -0
- package/dist/migrate-layout.d.ts +4 -24
- package/dist/migrate-layout.d.ts.map +1 -1
- package/dist/migrate-layout.js +8 -1183
- package/dist/migrate-layout.js.map +1 -1
- package/dist/output-schemas.d.ts.map +1 -1
- package/dist/output-schemas.js +78 -10
- package/dist/output-schemas.js.map +1 -1
- package/dist/recipes/5.18.0.d.ts +9 -0
- package/dist/recipes/5.18.0.d.ts.map +1 -0
- package/dist/recipes/5.18.0.js +56 -0
- package/dist/recipes/5.18.0.js.map +1 -0
- package/dist/recipes/index.d.ts.map +1 -1
- package/dist/recipes/index.js +2 -0
- package/dist/recipes/index.js.map +1 -1
- package/dist/review.d.ts.map +1 -1
- package/dist/review.js +6 -0
- package/dist/review.js.map +1 -1
- package/dist/rules/a11y.d.ts +5 -0
- package/dist/rules/a11y.d.ts.map +1 -0
- package/dist/rules/a11y.js +78 -0
- package/dist/rules/a11y.js.map +1 -0
- package/dist/rules/codes.d.ts +6 -0
- package/dist/rules/codes.d.ts.map +1 -1
- package/dist/rules/codes.js +6 -0
- package/dist/rules/codes.js.map +1 -1
- package/dist/rules/comment-markers.js +1 -1
- package/dist/rules/comment-markers.js.map +1 -1
- package/dist/rules/explanations.d.ts.map +1 -1
- package/dist/rules/explanations.js +30 -0
- package/dist/rules/explanations.js.map +1 -1
- package/dist/rules/host-exposure.d.ts +23 -0
- package/dist/rules/host-exposure.d.ts.map +1 -0
- package/dist/rules/host-exposure.js +380 -0
- package/dist/rules/host-exposure.js.map +1 -0
- package/dist/rules/internal-links.d.ts.map +1 -1
- package/dist/rules/internal-links.js +16 -141
- package/dist/rules/internal-links.js.map +1 -1
- package/dist/rules/islands.d.ts +54 -0
- package/dist/rules/islands.d.ts.map +1 -1
- package/dist/rules/islands.js +577 -80
- package/dist/rules/islands.js.map +1 -1
- package/dist/rules/security.d.ts +1 -0
- package/dist/rules/security.d.ts.map +1 -1
- package/dist/rules/security.js +34 -7
- package/dist/rules/security.js.map +1 -1
- package/dist/runtime-differences.js +3 -3
- package/dist/runtime-differences.js.map +1 -1
- package/dist/scaffold.d.ts +1 -1
- package/dist/scaffold.d.ts.map +1 -1
- package/dist/scaffold.js +2 -2
- package/dist/scaffold.js.map +1 -1
- package/dist/source-rewrites.d.ts.map +1 -1
- package/dist/source-rewrites.js +2 -19
- package/dist/source-rewrites.js.map +1 -1
- package/docs/examples.json +4 -4
- package/docs/llms-full.txt +422 -42
- package/docs/types.json +466 -56
- package/package.json +12 -12
- package/src/check-diagnostics.ts +11 -0
- package/src/check-scan-sql.ts +1746 -0
- package/src/check-scan.ts +34 -1754
- package/src/check.ts +10 -1
- package/src/cli.ts +258 -98
- package/src/command-catalog.ts +21 -4
- package/src/frontend-guidance.ts +1 -1
- package/src/internal/a11y-element.ts +227 -0
- package/src/internal/a11y-jsx.ts +54 -0
- package/src/internal/a11y-template.ts +74 -0
- package/src/internal/aria-data.ts +242 -0
- package/src/internal/edit-distance.ts +16 -0
- package/src/internal/imported-as.ts +30 -0
- package/src/internal/source-facts.ts +4 -0
- package/src/internal/template-markup.ts +270 -0
- package/src/internal/typescript-import.ts +15 -0
- package/src/mcp-exec.ts +43 -22
- package/src/mcp-http.ts +1 -1
- package/src/mcp-io.ts +5 -3
- package/src/mcp-root.ts +1 -1
- package/src/mcp-ws.ts +3 -2
- package/src/migrate-layout-config.ts +615 -0
- package/src/migrate-layout-split.ts +870 -0
- package/src/migrate-layout.ts +37 -1468
- package/src/output-schemas.ts +85 -17
- package/src/recipes/5.18.0.ts +63 -0
- package/src/recipes/index.ts +2 -0
- package/src/review.ts +6 -0
- package/src/rules/a11y.ts +119 -0
- package/src/rules/codes.ts +6 -0
- package/src/rules/comment-markers.ts +2 -2
- package/src/rules/explanations.ts +30 -0
- package/src/rules/host-exposure.ts +531 -0
- package/src/rules/internal-links.ts +21 -154
- package/src/rules/islands.ts +698 -86
- package/src/rules/security.ts +48 -7
- package/src/runtime-differences.ts +3 -3
- package/src/scaffold.ts +3 -3
- package/src/source-rewrites.ts +2 -15
package/src/migrate-layout.ts
CHANGED
|
@@ -31,15 +31,12 @@ import {
|
|
|
31
31
|
readdirSync,
|
|
32
32
|
readFileSync,
|
|
33
33
|
renameSync,
|
|
34
|
-
rmdirSync,
|
|
35
34
|
rmSync,
|
|
36
35
|
statSync,
|
|
37
36
|
writeFileSync,
|
|
38
37
|
} from "node:fs"
|
|
39
38
|
import { builtinModules } from "node:module"
|
|
40
|
-
import { dirname, extname, isAbsolute, join, posix, relative, resolve
|
|
41
|
-
import { BACKEND_ROUTE_EXPORTS } from "@nifrajs/web/route-manifest"
|
|
42
|
-
import { parseZoneConfig, type ZoneConfig } from "@nifrajs/web/zones"
|
|
39
|
+
import { dirname, extname, isAbsolute, join, posix, relative, resolve } from "node:path"
|
|
43
40
|
import type * as TS from "typescript"
|
|
44
41
|
import { BACKEND_APP_FILE, CONFIG_FILE, FRAMEWORK_FILE, retiredRootFiles } from "./app-files.ts"
|
|
45
42
|
import { codeUnitOrder } from "./internal/code-unit-order.ts"
|
|
@@ -54,11 +51,8 @@ import { type OutputSchemaEntry, planOutputSchemas } from "./output-schemas.ts"
|
|
|
54
51
|
import { missingOutputSchemas } from "./rules/data-guard.ts"
|
|
55
52
|
import { apiPrefixFix } from "./rules/pages.ts"
|
|
56
53
|
|
|
57
|
-
/** Exports only the server or the build reads: `@nifrajs/web`'s route-pair contract. */
|
|
58
|
-
const BACKEND_EXPORTS = BACKEND_ROUTE_EXPORTS
|
|
59
|
-
|
|
60
54
|
const ROUTE_FILE = /\.(?:tsx|jsx|svelte|vue|mdx)$/
|
|
61
|
-
const SOURCE_FILE = /\.(?:[cm]?[jt]sx?|svelte|vue|mdx)$/
|
|
55
|
+
export const SOURCE_FILE = /\.(?:[cm]?[jt]sx?|svelte|vue|mdx)$/
|
|
62
56
|
const RESOLVE_EXTENSIONS = [
|
|
63
57
|
".ts",
|
|
64
58
|
".tsx",
|
|
@@ -82,7 +76,7 @@ const TOOLING_FILE =
|
|
|
82
76
|
/(?:\.(?:json|jsonc|ya?ml|toml|sh|bash|zsh|ps1)|(?:^|\/)(?:Dockerfile|Makefile|Procfile))$/
|
|
83
77
|
const SELF_LOCATION = /\bimport\.meta\.(?:dirname|dir|filename|url)\b|\b__(?:dirname|filename)\b/
|
|
84
78
|
const SKIP_DIRS = new Set(["node_modules", "dist", "build", "coverage", ".git", ".vite", "public"])
|
|
85
|
-
const ZONE_DIRS = new Set(["frontend", "backend", "shared", "routes", "public"])
|
|
79
|
+
export const ZONE_DIRS = new Set(["frontend", "backend", "shared", "routes", "public"])
|
|
86
80
|
type FolderSide = "frontend" | "backend" | "shared"
|
|
87
81
|
const FOLDER_SIDES: readonly FolderSide[] = ["frontend", "backend", "shared"]
|
|
88
82
|
/** Data other tools may read by path too; reported, never moved. Images and fonts still move. */
|
|
@@ -213,865 +207,40 @@ function listFiles(root: string): string[] {
|
|
|
213
207
|
return out.sort()
|
|
214
208
|
}
|
|
215
209
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
readonly exports: ReadonlyMap<string, readonly string[]>
|
|
227
|
-
readonly valueRefs: ReadonlySet<string>
|
|
228
|
-
readonly typeRefs: ReadonlySet<string>
|
|
229
|
-
/** A local `export { a, b as c }`: each entry, which the reachability of its own half follows. */
|
|
230
|
-
readonly listed: ReadonlyArray<ListedExport>
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
interface ListedExport {
|
|
234
|
-
readonly exported: string
|
|
235
|
-
readonly local: string
|
|
236
|
-
/** `export type { X }` or `export { type X }`: a read in a type position. */
|
|
237
|
-
readonly type: boolean
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** The names one half reads, by position. */
|
|
241
|
-
interface Uses {
|
|
242
|
-
readonly value: ReadonlySet<string>
|
|
243
|
-
readonly type: ReadonlySet<string>
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
export interface SplitResult {
|
|
247
|
-
readonly frontend: string
|
|
248
|
-
/** `undefined` when the file exports nothing for the server. */
|
|
249
|
-
readonly backend: string | undefined
|
|
250
|
-
/** The module beside the route that holds constant data both halves import, when there is any. */
|
|
251
|
-
readonly shared?: string
|
|
252
|
-
readonly moved: readonly string[]
|
|
253
|
-
readonly issues: readonly string[]
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
function bindingNames(ts: typeof TS, name: TS.BindingName, into: Set<string>): void {
|
|
257
|
-
if (ts.isIdentifier(name)) into.add(name.text)
|
|
258
|
-
else
|
|
259
|
-
for (const element of name.elements)
|
|
260
|
-
if (!ts.isOmittedExpression(element)) bindingNames(ts, element.name, into)
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
const hasModifier = (ts: typeof TS, node: TS.Node, kind: TS.SyntaxKind): boolean =>
|
|
264
|
-
(ts.canHaveModifiers(node) ? (ts.getModifiers(node) ?? []) : []).some((m) => m.kind === kind)
|
|
265
|
-
|
|
266
|
-
/** Identifiers a statement reads, split into value and type positions. Over-approximates on purpose:
|
|
267
|
-
* an extra name only keeps a declaration in a half that did not need it. */
|
|
268
|
-
interface JsxBindings {
|
|
269
|
-
readonly element: readonly string[]
|
|
270
|
-
readonly fragment: readonly string[]
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* The bindings classic JSX compiles to calls of, which no identifier in the source names: the roots
|
|
275
|
-
* of the `@jsx`/`@jsxFrag` pragmas, else TypeScript's default `React`. A file that names its own
|
|
276
|
-
* `@jsxImportSource` imports the runtime itself.
|
|
277
|
-
*/
|
|
278
|
-
function jsxBindings(ts: typeof TS, source: string): JsxBindings {
|
|
279
|
-
const comments = (ts.getLeadingCommentRanges(source, 0) ?? [])
|
|
280
|
-
.map(({ pos, end }) => source.slice(pos, end))
|
|
281
|
-
.join("\n")
|
|
282
|
-
if (/@jsxImportSource\s/.test(comments)) return { element: [], fragment: [] }
|
|
283
|
-
const root = (pragma: string): string | undefined =>
|
|
284
|
-
new RegExp(`@${pragma}\\s+([A-Za-z_$][\\w$]*)`).exec(comments)?.[1]
|
|
285
|
-
const element = root("jsx") ?? "React"
|
|
286
|
-
return { element: [element], fragment: [root("jsxFrag") ?? element] }
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function references(
|
|
290
|
-
ts: typeof TS,
|
|
291
|
-
node: TS.Node,
|
|
292
|
-
jsx: JsxBindings,
|
|
293
|
-
): { value: Set<string>; type: Set<string> } {
|
|
294
|
-
const value = new Set<string>()
|
|
295
|
-
const type = new Set<string>()
|
|
296
|
-
const visit = (current: TS.Node, inType: boolean): void => {
|
|
297
|
-
if (ts.isJsxOpeningElement(current) || ts.isJsxSelfClosingElement(current))
|
|
298
|
-
for (const name of jsx.element) value.add(name)
|
|
299
|
-
else if (ts.isJsxFragment(current)) for (const name of jsx.fragment) value.add(name)
|
|
300
|
-
const typed =
|
|
301
|
-
inType ||
|
|
302
|
-
ts.isTypeNode(current) ||
|
|
303
|
-
// nifra-expect NF-S002: `token` is the heritage clause's syntax kind, not a credential.
|
|
304
|
-
(ts.isHeritageClause(current) && current.token === ts.SyntaxKind.ImplementsKeyword)
|
|
305
|
-
if (ts.isIdentifier(current)) {
|
|
306
|
-
const parent = current.parent
|
|
307
|
-
const isName =
|
|
308
|
-
parent !== undefined &&
|
|
309
|
-
((ts.isPropertyAccessExpression(parent) && parent.name === current) ||
|
|
310
|
-
(ts.isPropertyAssignment(parent) && parent.name === current) ||
|
|
311
|
-
(ts.isPropertySignature(parent) && parent.name === current) ||
|
|
312
|
-
(ts.isPropertyDeclaration(parent) && parent.name === current) ||
|
|
313
|
-
(ts.isMethodDeclaration(parent) && parent.name === current) ||
|
|
314
|
-
(ts.isMethodSignature(parent) && parent.name === current) ||
|
|
315
|
-
(ts.isQualifiedName(parent) && parent.right === current) ||
|
|
316
|
-
(ts.isJsxAttribute(parent) && parent.name === current) ||
|
|
317
|
-
(ts.isBindingElement(parent) && parent.propertyName === current) ||
|
|
318
|
-
ts.isImportSpecifier(parent) ||
|
|
319
|
-
ts.isExportSpecifier(parent) ||
|
|
320
|
-
ts.isImportClause(parent) ||
|
|
321
|
-
ts.isNamespaceImport(parent))
|
|
322
|
-
if (!isName) (typed ? type : value).add(current.text)
|
|
323
|
-
return
|
|
324
|
-
}
|
|
325
|
-
if (ts.isShorthandPropertyAssignment(current)) value.add(current.name.text)
|
|
326
|
-
ts.forEachChild(current, (child) => visit(child, typed))
|
|
327
|
-
}
|
|
328
|
-
visit(node, false)
|
|
329
|
-
return { value, type }
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
function describeStatements(ts: typeof TS, sf: TS.SourceFile): StatementInfo[] {
|
|
333
|
-
const jsx = jsxBindings(ts, sf.text)
|
|
334
|
-
return sf.statements.map((node) => {
|
|
335
|
-
const declares = new Set<string>()
|
|
336
|
-
const exports = new Map<string, string[]>()
|
|
337
|
-
const listed: ListedExport[] = []
|
|
338
|
-
const exported = hasModifier(ts, node, ts.SyntaxKind.ExportKeyword)
|
|
339
|
-
const isDefault = hasModifier(ts, node, ts.SyntaxKind.DefaultKeyword)
|
|
340
|
-
const addExport = (local: string, as: string): void => {
|
|
341
|
-
exports.set(local, [...(exports.get(local) ?? []), as])
|
|
342
|
-
}
|
|
343
|
-
if (ts.isImportDeclaration(node)) {
|
|
344
|
-
const clause = node.importClause
|
|
345
|
-
if (clause?.name) declares.add(clause.name.text)
|
|
346
|
-
const bindings = clause?.namedBindings
|
|
347
|
-
if (bindings && ts.isNamespaceImport(bindings)) declares.add(bindings.name.text)
|
|
348
|
-
if (bindings && ts.isNamedImports(bindings))
|
|
349
|
-
for (const el of bindings.elements) declares.add(el.name.text)
|
|
350
|
-
} else if (ts.isVariableStatement(node)) {
|
|
351
|
-
for (const decl of node.declarationList.declarations) {
|
|
352
|
-
const names = new Set<string>()
|
|
353
|
-
bindingNames(ts, decl.name, names)
|
|
354
|
-
for (const name of names) {
|
|
355
|
-
declares.add(name)
|
|
356
|
-
if (exported) addExport(name, name)
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
} else if (
|
|
360
|
-
ts.isFunctionDeclaration(node) ||
|
|
361
|
-
ts.isClassDeclaration(node) ||
|
|
362
|
-
ts.isInterfaceDeclaration(node) ||
|
|
363
|
-
ts.isTypeAliasDeclaration(node) ||
|
|
364
|
-
ts.isEnumDeclaration(node)
|
|
365
|
-
) {
|
|
366
|
-
const name = node.name?.text
|
|
367
|
-
if (name !== undefined) declares.add(name)
|
|
368
|
-
if (exported) addExport(name ?? "default", isDefault ? "default" : (name ?? "default"))
|
|
369
|
-
} else if (ts.isExportAssignment(node)) {
|
|
370
|
-
addExport("default", "default")
|
|
371
|
-
} else if (
|
|
372
|
-
ts.isExportDeclaration(node) &&
|
|
373
|
-
node.exportClause &&
|
|
374
|
-
ts.isNamedExports(node.exportClause)
|
|
375
|
-
) {
|
|
376
|
-
for (const el of node.exportClause.elements) {
|
|
377
|
-
const local = (el.propertyName ?? el.name).text
|
|
378
|
-
addExport(node.moduleSpecifier ? `\0${el.name.text}` : local, el.name.text)
|
|
379
|
-
if (node.moduleSpecifier === undefined)
|
|
380
|
-
listed.push({ exported: el.name.text, local, type: node.isTypeOnly || el.isTypeOnly })
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
const refs = ts.isImportDeclaration(node)
|
|
384
|
-
? { value: new Set<string>(), type: new Set<string>() }
|
|
385
|
-
: references(ts, node, jsx)
|
|
386
|
-
for (const name of declares) {
|
|
387
|
-
refs.value.delete(name)
|
|
388
|
-
refs.type.delete(name)
|
|
389
|
-
}
|
|
390
|
-
return {
|
|
391
|
-
node,
|
|
392
|
-
text: node.getFullText(sf),
|
|
393
|
-
declares,
|
|
394
|
-
exports,
|
|
395
|
-
valueRefs: refs.value,
|
|
396
|
-
typeRefs: refs.type,
|
|
397
|
-
listed,
|
|
398
|
-
}
|
|
399
|
-
})
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* Rebuild an import keeping only the bindings `uses` names; `undefined` when none remain. Bindings
|
|
404
|
-
* read only in types become `import type`, so no bundler loads the module for them: always in a
|
|
405
|
-
* `fresh` module, and in the page only where the split narrowed the import.
|
|
406
|
-
*/
|
|
407
|
-
function filterImport(
|
|
408
|
-
ts: typeof TS,
|
|
409
|
-
sf: TS.SourceFile,
|
|
410
|
-
node: TS.ImportDeclaration,
|
|
411
|
-
uses: Uses,
|
|
412
|
-
fresh: boolean,
|
|
413
|
-
): string | undefined {
|
|
414
|
-
const clause = node.importClause
|
|
415
|
-
const spec = node.moduleSpecifier.getText(sf)
|
|
416
|
-
const attributes = node.attributes ? ` ${node.attributes.getText(sf)}` : ""
|
|
417
|
-
if (clause === undefined) return node.getFullText(sf)
|
|
418
|
-
interface Part {
|
|
419
|
-
readonly text: string
|
|
420
|
-
/** Without an inline `type`, for an `import type`. */
|
|
421
|
-
readonly bare: string
|
|
422
|
-
readonly typeOnly: boolean
|
|
423
|
-
}
|
|
424
|
-
const heads: Part[] = []
|
|
425
|
-
const named: Part[] = []
|
|
426
|
-
let total = 0
|
|
427
|
-
const add = (into: Part[], name: string, text: string, bare: string): void => {
|
|
428
|
-
total++
|
|
429
|
-
if (uses.value.has(name) || uses.type.has(name))
|
|
430
|
-
into.push({ text, bare, typeOnly: !uses.value.has(name) })
|
|
431
|
-
}
|
|
432
|
-
if (clause.name) add(heads, clause.name.text, clause.name.text, clause.name.text)
|
|
433
|
-
const bindings = clause.namedBindings
|
|
434
|
-
if (bindings && ts.isNamespaceImport(bindings)) {
|
|
435
|
-
const text = `* as ${bindings.name.text}`
|
|
436
|
-
add(heads, bindings.name.text, text, text)
|
|
437
|
-
}
|
|
438
|
-
if (bindings && ts.isNamedImports(bindings)) {
|
|
439
|
-
for (const el of bindings.elements) {
|
|
440
|
-
const renamed = el.propertyName ? `${el.propertyName.getText(sf)} as ` : ""
|
|
441
|
-
add(named, el.name.text, el.getText(sf), `${renamed}${el.name.text}`)
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
const kept = [...heads, ...named]
|
|
445
|
-
if (kept.length === 0) return undefined
|
|
446
|
-
const leading = node.getFullText(sf).slice(0, node.getStart(sf) - node.getFullStart())
|
|
447
|
-
const statement = (typeOnly: boolean, body: string): string =>
|
|
448
|
-
`import ${typeOnly ? "type " : ""}${body} from ${spec}${attributes}${terminatorOf(sf, node)}`
|
|
449
|
-
const list = (parts: readonly Part[], text: (part: Part) => string): string[] =>
|
|
450
|
-
parts.length === 0 ? [] : [`{ ${parts.map(text).join(", ")} }`]
|
|
451
|
-
if (
|
|
452
|
-
!clause.isTypeOnly &&
|
|
453
|
-
node.attributes === undefined &&
|
|
454
|
-
(fresh || kept.length < total) &&
|
|
455
|
-
kept.every((part) => part.typeOnly)
|
|
456
|
-
) {
|
|
457
|
-
// `import type` takes one default, namespace or list, so each goes in its own statement.
|
|
458
|
-
const bodies = [...heads.map((part) => part.bare), ...list(named, (part) => part.bare)]
|
|
459
|
-
return `${leading}${bodies.map((body) => statement(true, body)).join("\n")}`
|
|
460
|
-
}
|
|
461
|
-
const body = [...heads.map((part) => part.text), ...list(named, (part) => part.text)]
|
|
462
|
-
return `${leading}${statement(clause.isTypeOnly, body.join(", "))}`
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
/** The `;` a statement was written with, so a rebuilt one keeps the file's style. */
|
|
466
|
-
const terminatorOf = (sf: TS.SourceFile, node: TS.Node): string =>
|
|
467
|
-
node.getText(sf).endsWith(";") ? ";" : ""
|
|
468
|
-
|
|
469
|
-
/** Rebuild `export { a, b as c }` keeping only the exported names `keep` accepts. */
|
|
470
|
-
function filterExportList(
|
|
471
|
-
ts: typeof TS,
|
|
472
|
-
sf: TS.SourceFile,
|
|
473
|
-
node: TS.ExportDeclaration,
|
|
474
|
-
keep: (exported: string) => boolean,
|
|
475
|
-
): string | undefined {
|
|
476
|
-
const clause = node.exportClause
|
|
477
|
-
if (!clause || !ts.isNamedExports(clause)) return node.getFullText(sf)
|
|
478
|
-
const kept = clause.elements.filter((el) => keep(el.name.text)).map((el) => el.getText(sf))
|
|
479
|
-
if (kept.length === 0) return undefined
|
|
480
|
-
const from = node.moduleSpecifier ? ` from ${node.moduleSpecifier.getText(sf)}` : ""
|
|
481
|
-
const leading = node.getFullText(sf).slice(0, node.getStart(sf) - node.getFullStart())
|
|
482
|
-
return `${leading}export ${node.isTypeOnly ? "type " : ""}{ ${kept.join(", ")} }${from}${terminatorOf(sf, node)}`
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
const joinStatements = (texts: readonly string[]): string => {
|
|
486
|
-
const body = texts.join("").replace(/^\s*\n/, "")
|
|
487
|
-
return body.endsWith("\n") ? body : `${body}\n`
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
/** Options for {@link splitRouteSource}. */
|
|
491
|
-
export interface SplitOptions {
|
|
492
|
-
/**
|
|
493
|
-
* The file name of a module beside the route (`index.shared.ts`) to hold constant data both halves
|
|
494
|
-
* read, which each half then imports. Without it, that data is copied into each half.
|
|
495
|
-
*/
|
|
496
|
-
readonly sharedFile?: string
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
const PURE_OBJECT_CALLS = new Set(["keys", "values", "entries", "freeze", "fromEntries"])
|
|
500
|
-
|
|
501
|
-
/**
|
|
502
|
-
* Whether `node` builds constant data: literals, arrays and objects of it, operators over it,
|
|
503
|
-
* `Object.keys`-style reads, and the file's own top-level names, which go into `reads`. `undefined`
|
|
504
|
-
* when it is data; else the import it reads, or `""` for anything else (a call, a function, a global).
|
|
505
|
-
*/
|
|
506
|
-
function dataBlocker(
|
|
507
|
-
ts: typeof TS,
|
|
508
|
-
node: TS.Node,
|
|
509
|
-
isLocal: (name: string) => boolean,
|
|
510
|
-
reads: Set<string>,
|
|
511
|
-
): string | undefined {
|
|
512
|
-
const data = (n: TS.Node): string | undefined => {
|
|
513
|
-
if (
|
|
514
|
-
ts.isStringLiteral(n) ||
|
|
515
|
-
ts.isNumericLiteral(n) ||
|
|
516
|
-
ts.isBigIntLiteral(n) ||
|
|
517
|
-
ts.isNoSubstitutionTemplateLiteral(n) ||
|
|
518
|
-
n.kind === ts.SyntaxKind.TrueKeyword ||
|
|
519
|
-
n.kind === ts.SyntaxKind.FalseKeyword ||
|
|
520
|
-
n.kind === ts.SyntaxKind.NullKeyword
|
|
521
|
-
)
|
|
522
|
-
return undefined
|
|
523
|
-
if (ts.isIdentifier(n)) {
|
|
524
|
-
if (isLocal(n.text)) {
|
|
525
|
-
reads.add(n.text)
|
|
526
|
-
return undefined
|
|
527
|
-
}
|
|
528
|
-
return n.text === "undefined" ? undefined : n.text
|
|
529
|
-
}
|
|
530
|
-
const every = (nodes: readonly TS.Node[]): string | undefined => {
|
|
531
|
-
for (const child of nodes) {
|
|
532
|
-
const blocker = data(child)
|
|
533
|
-
if (blocker !== undefined) return blocker
|
|
534
|
-
}
|
|
535
|
-
return undefined
|
|
536
|
-
}
|
|
537
|
-
if (ts.isTemplateExpression(n)) return every(n.templateSpans.map((span) => span.expression))
|
|
538
|
-
if (ts.isPrefixUnaryExpression(n))
|
|
539
|
-
return n.operator === ts.SyntaxKind.PlusPlusToken ||
|
|
540
|
-
n.operator === ts.SyntaxKind.MinusMinusToken
|
|
541
|
-
? ""
|
|
542
|
-
: data(n.operand)
|
|
543
|
-
if (ts.isBinaryExpression(n)) {
|
|
544
|
-
const operator = n.operatorToken.kind
|
|
545
|
-
const assigns =
|
|
546
|
-
operator >= ts.SyntaxKind.FirstAssignment && operator <= ts.SyntaxKind.LastAssignment
|
|
547
|
-
if (
|
|
548
|
-
assigns ||
|
|
549
|
-
operator === ts.SyntaxKind.CommaToken ||
|
|
550
|
-
operator === ts.SyntaxKind.InKeyword ||
|
|
551
|
-
operator === ts.SyntaxKind.InstanceOfKeyword
|
|
552
|
-
)
|
|
553
|
-
return ""
|
|
554
|
-
return every([n.left, n.right])
|
|
555
|
-
}
|
|
556
|
-
if (ts.isConditionalExpression(n)) return every([n.condition, n.whenTrue, n.whenFalse])
|
|
557
|
-
if (ts.isArrayLiteralExpression(n))
|
|
558
|
-
return every(
|
|
559
|
-
n.elements.flatMap((element) =>
|
|
560
|
-
ts.isOmittedExpression(element)
|
|
561
|
-
? []
|
|
562
|
-
: [ts.isSpreadElement(element) ? element.expression : element],
|
|
563
|
-
),
|
|
564
|
-
)
|
|
565
|
-
if (ts.isObjectLiteralExpression(n)) {
|
|
566
|
-
for (const property of n.properties) {
|
|
567
|
-
const blocker = ts.isPropertyAssignment(property)
|
|
568
|
-
? ((ts.isComputedPropertyName(property.name)
|
|
569
|
-
? data(property.name.expression)
|
|
570
|
-
: undefined) ?? data(property.initializer))
|
|
571
|
-
: ts.isShorthandPropertyAssignment(property)
|
|
572
|
-
? property.objectAssignmentInitializer === undefined
|
|
573
|
-
? data(property.name)
|
|
574
|
-
: ""
|
|
575
|
-
: ts.isSpreadAssignment(property)
|
|
576
|
-
? data(property.expression)
|
|
577
|
-
: ""
|
|
578
|
-
if (blocker !== undefined) return blocker
|
|
579
|
-
}
|
|
580
|
-
return undefined
|
|
581
|
-
}
|
|
582
|
-
if (
|
|
583
|
-
ts.isParenthesizedExpression(n) ||
|
|
584
|
-
ts.isAsExpression(n) ||
|
|
585
|
-
ts.isSatisfiesExpression(n) ||
|
|
586
|
-
ts.isNonNullExpression(n) ||
|
|
587
|
-
ts.isTypeAssertionExpression(n)
|
|
588
|
-
)
|
|
589
|
-
return data(n.expression)
|
|
590
|
-
if (ts.isPropertyAccessExpression(n))
|
|
591
|
-
return ts.isPrivateIdentifier(n.name) ? "" : data(n.expression)
|
|
592
|
-
if (ts.isElementAccessExpression(n)) return every([n.expression, n.argumentExpression])
|
|
593
|
-
if (ts.isCallExpression(n)) {
|
|
594
|
-
const callee = n.expression
|
|
595
|
-
const objectRead =
|
|
596
|
-
ts.isPropertyAccessExpression(callee) &&
|
|
597
|
-
ts.isIdentifier(callee.expression) &&
|
|
598
|
-
callee.expression.text === "Object" &&
|
|
599
|
-
!isLocal("Object") &&
|
|
600
|
-
PURE_OBJECT_CALLS.has(callee.name.text) &&
|
|
601
|
-
n.questionDotToken === undefined &&
|
|
602
|
-
n.typeArguments === undefined
|
|
603
|
-
return objectRead ? every(n.arguments) : ""
|
|
604
|
-
}
|
|
605
|
-
return ""
|
|
606
|
-
}
|
|
607
|
-
return data(node)
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
/**
|
|
611
|
-
* Split one route module's source into its frontend and backend halves. `backendSpecifier` is how the
|
|
612
|
-
* frontend refers to the backend half in an `import type` (`./index.backend.ts`).
|
|
613
|
-
*/
|
|
614
|
-
export function splitRouteSource(
|
|
615
|
-
ts: typeof TS,
|
|
616
|
-
source: string,
|
|
617
|
-
fileName: string,
|
|
618
|
-
backendSpecifier: string,
|
|
619
|
-
options: SplitOptions = {},
|
|
620
|
-
): SplitResult {
|
|
621
|
-
const kind = fileName.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
|
|
622
|
-
const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, kind)
|
|
623
|
-
const statements = describeStatements(ts, sf)
|
|
624
|
-
const issues: string[] = []
|
|
625
|
-
const exportsOf = (info: StatementInfo): string[] => [...info.exports.values()].flat()
|
|
626
|
-
const isBackendStatement = (info: StatementInfo): boolean =>
|
|
627
|
-
exportsOf(info).some((name) => BACKEND_EXPORTS.has(name))
|
|
628
|
-
const moved = statements.flatMap(exportsOf).filter((name) => BACKEND_EXPORTS.has(name))
|
|
629
|
-
if (moved.length === 0) return { frontend: source, backend: undefined, moved: [], issues: [] }
|
|
630
|
-
|
|
631
|
-
const declaredBy = new Map<string, StatementInfo>()
|
|
632
|
-
const importedBy = new Map<string, StatementInfo>()
|
|
633
|
-
for (const info of statements) {
|
|
634
|
-
const into = ts.isImportDeclaration(info.node) ? importedBy : declaredBy
|
|
635
|
-
for (const name of info.declares) into.set(name, info)
|
|
636
|
-
}
|
|
637
|
-
const isTypeDeclaration = (info: StatementInfo): boolean =>
|
|
638
|
-
ts.isInterfaceDeclaration(info.node) || ts.isTypeAliasDeclaration(info.node)
|
|
639
|
-
/** What `info` reads for one half: an export list reads only the locals it exports there. */
|
|
640
|
-
const readsFor = (info: StatementInfo, backend: boolean): Uses => {
|
|
641
|
-
if (info.listed.length === 0) return { value: info.valueRefs, type: info.typeRefs }
|
|
642
|
-
const mine = info.listed.filter((entry) => BACKEND_EXPORTS.has(entry.exported) === backend)
|
|
643
|
-
return {
|
|
644
|
-
value: new Set(mine.filter((entry) => !entry.type).map((entry) => entry.local)),
|
|
645
|
-
type: new Set(mine.filter((entry) => entry.type).map((entry) => entry.local)),
|
|
646
|
-
}
|
|
647
|
-
}
|
|
648
|
-
const movedLocals = new Set<string>()
|
|
649
|
-
for (const info of statements) {
|
|
650
|
-
for (const [local, names] of info.exports)
|
|
651
|
-
if (names.some((name) => BACKEND_EXPORTS.has(name))) movedLocals.add(local)
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
/** Each half's statements. What `shared` holds, both import, so neither half keeps a copy. */
|
|
655
|
-
const partition = (
|
|
656
|
-
shared: ReadonlySet<StatementInfo>,
|
|
657
|
-
): { backendSet: Set<StatementInfo>; frontendKeep: Set<StatementInfo> } => {
|
|
658
|
-
const local = (name: string): StatementInfo | undefined => {
|
|
659
|
-
const target = declaredBy.get(name)
|
|
660
|
-
return target === undefined || shared.has(target) ? undefined : target
|
|
661
|
-
}
|
|
662
|
-
// The backend half: its export statements plus every top-level declaration they reach.
|
|
663
|
-
const backendSet = new Set<StatementInfo>()
|
|
664
|
-
const queue: StatementInfo[] = statements.filter(isBackendStatement)
|
|
665
|
-
for (const info of queue) backendSet.add(info)
|
|
666
|
-
while (queue.length > 0) {
|
|
667
|
-
const info = queue.pop() as StatementInfo
|
|
668
|
-
const reads = readsFor(info, true)
|
|
669
|
-
for (const name of [...reads.value, ...reads.type]) {
|
|
670
|
-
const target = local(name)
|
|
671
|
-
if (target !== undefined && !backendSet.has(target)) {
|
|
672
|
-
backendSet.add(target)
|
|
673
|
-
queue.push(target)
|
|
674
|
-
}
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
// The frontend half: everything that is not a backend export statement, minus declarations that
|
|
679
|
-
// only the backend half needs. An export list that also names backend exports keeps the rest.
|
|
680
|
-
const frontendKeep = new Set<StatementInfo>()
|
|
681
|
-
const seed = statements.filter(
|
|
682
|
-
(info) =>
|
|
683
|
-
!ts.isImportDeclaration(info.node) &&
|
|
684
|
-
!shared.has(info) &&
|
|
685
|
-
(!backendSet.has(info) ||
|
|
686
|
-
exportsOf(info).some((name) => !BACKEND_EXPORTS.has(name)) ||
|
|
687
|
-
// a statement with no declaration (a side effect) stays where it ran
|
|
688
|
-
(info.declares.size === 0 && info.exports.size === 0)),
|
|
689
|
-
)
|
|
690
|
-
const fqueue = [...seed]
|
|
691
|
-
for (const info of fqueue) frontendKeep.add(info)
|
|
692
|
-
while (fqueue.length > 0) {
|
|
693
|
-
const info = fqueue.pop() as StatementInfo
|
|
694
|
-
const reads = readsFor(info, false)
|
|
695
|
-
for (const name of reads.value) {
|
|
696
|
-
if (movedLocals.has(name) && !info.declares.has(name)) continue
|
|
697
|
-
const target = local(name)
|
|
698
|
-
if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
|
|
699
|
-
frontendKeep.add(target)
|
|
700
|
-
fqueue.push(target)
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
for (const name of reads.type) {
|
|
704
|
-
if (movedLocals.has(name)) continue
|
|
705
|
-
const target = local(name)
|
|
706
|
-
if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
|
|
707
|
-
frontendKeep.add(target)
|
|
708
|
-
fqueue.push(target)
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
return { backendSet, frontendKeep }
|
|
713
|
-
}
|
|
714
|
-
let { backendSet, frontendKeep } = partition(new Set())
|
|
715
|
-
const copies = (): StatementInfo[] =>
|
|
716
|
-
[...frontendKeep].filter(
|
|
717
|
-
(info) =>
|
|
718
|
-
backendSet.has(info) &&
|
|
719
|
-
!isBackendStatement(info) &&
|
|
720
|
-
info.declares.size > 0 &&
|
|
721
|
-
!isTypeDeclaration(info),
|
|
722
|
-
)
|
|
723
|
-
|
|
724
|
-
// Constant data both halves read moves to a module beside the route, with the declarations it
|
|
725
|
-
// needs: one definition, which neither half's bundle can drift from.
|
|
726
|
-
const shared = new Set<StatementInfo>()
|
|
727
|
-
const sharedTypes = new Set<StatementInfo>()
|
|
728
|
-
const sharedImports = new Set<string>()
|
|
729
|
-
const unshared = new Map<StatementInfo, string>()
|
|
730
|
-
if (options.sharedFile !== undefined) {
|
|
731
|
-
interface Closure {
|
|
732
|
-
readonly values: Set<StatementInfo>
|
|
733
|
-
readonly types: Set<StatementInfo>
|
|
734
|
-
readonly imports: Set<string>
|
|
735
|
-
}
|
|
736
|
-
/** Why `info` cannot move to the shared module, or `undefined` once it and what it needs are in `closure`. */
|
|
737
|
-
const gather = (info: StatementInfo, closure: Closure): string | undefined => {
|
|
738
|
-
if (closure.values.has(info) || shared.has(info)) return undefined
|
|
739
|
-
const node = info.node
|
|
740
|
-
const reads = new Set<string>()
|
|
741
|
-
let blocker: string | undefined = ""
|
|
742
|
-
if (
|
|
743
|
-
!isBackendStatement(info) &&
|
|
744
|
-
ts.isVariableStatement(node) &&
|
|
745
|
-
(node.declarationList.flags & ts.NodeFlags.Const) !== 0 &&
|
|
746
|
-
!hasModifier(ts, node, ts.SyntaxKind.DeclareKeyword)
|
|
747
|
-
) {
|
|
748
|
-
blocker = undefined
|
|
749
|
-
for (const declaration of node.declarationList.declarations) {
|
|
750
|
-
blocker =
|
|
751
|
-
ts.isIdentifier(declaration.name) && declaration.initializer !== undefined
|
|
752
|
-
? dataBlocker(ts, declaration.initializer, (name) => declaredBy.has(name), reads)
|
|
753
|
-
: ""
|
|
754
|
-
if (blocker !== undefined) break
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
if (blocker !== undefined)
|
|
758
|
-
return blocker !== "" && importedBy.has(blocker)
|
|
759
|
-
? `it reads the import "${blocker}"`
|
|
760
|
-
: "it is not constant data"
|
|
761
|
-
closure.values.add(info)
|
|
762
|
-
for (const name of reads) {
|
|
763
|
-
const target = declaredBy.get(name)
|
|
764
|
-
const why = target === undefined ? undefined : gather(target, closure)
|
|
765
|
-
if (why !== undefined) return `it reads "${name}", which ${why.slice(3)}`
|
|
766
|
-
}
|
|
767
|
-
for (const name of info.typeRefs) {
|
|
768
|
-
const why = gatherType(name, closure)
|
|
769
|
-
if (why !== undefined) return why
|
|
770
|
-
}
|
|
771
|
-
return undefined
|
|
772
|
-
}
|
|
773
|
-
const gatherType = (name: string, closure: Closure): string | undefined => {
|
|
774
|
-
const local = declaredBy.get(name)
|
|
775
|
-
if (local === undefined) {
|
|
776
|
-
if (importedBy.has(name)) closure.imports.add(name)
|
|
777
|
-
return undefined
|
|
778
|
-
}
|
|
779
|
-
if (!isTypeDeclaration(local)) {
|
|
780
|
-
const why = gather(local, closure)
|
|
781
|
-
return why === undefined ? undefined : `its type reads "${name}", which ${why.slice(3)}`
|
|
782
|
-
}
|
|
783
|
-
if (closure.types.has(local) || sharedTypes.has(local)) return undefined
|
|
784
|
-
closure.types.add(local)
|
|
785
|
-
for (const ref of [...local.typeRefs, ...local.valueRefs]) {
|
|
786
|
-
const why = gatherType(ref, closure)
|
|
787
|
-
if (why !== undefined) return why
|
|
788
|
-
}
|
|
789
|
-
return undefined
|
|
790
|
-
}
|
|
791
|
-
for (const info of copies()) {
|
|
792
|
-
const closure: Closure = { values: new Set(), types: new Set(), imports: new Set() }
|
|
793
|
-
const why = gather(info, closure)
|
|
794
|
-
if (why !== undefined) {
|
|
795
|
-
unshared.set(info, why)
|
|
796
|
-
continue
|
|
797
|
-
}
|
|
798
|
-
for (const value of closure.values) shared.add(value)
|
|
799
|
-
for (const type of closure.types) sharedTypes.add(type)
|
|
800
|
-
for (const name of closure.imports) sharedImports.add(name)
|
|
801
|
-
}
|
|
802
|
-
if (shared.size > 0) ({ backendSet, frontendKeep } = partition(shared))
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
// A moved name the frontend still mentions: in a type it becomes `import type`; at runtime it is an
|
|
806
|
-
// error the author has to resolve.
|
|
807
|
-
const typeImports = new Set<string>()
|
|
808
|
-
for (const info of frontendKeep) {
|
|
809
|
-
if (isBackendStatement(info)) continue
|
|
810
|
-
const reads = readsFor(info, false)
|
|
811
|
-
for (const name of movedLocals) {
|
|
812
|
-
if (info.declares.has(name)) continue
|
|
813
|
-
if (reads.value.has(name))
|
|
814
|
-
issues.push(`the frontend uses "${name}" at runtime, but it runs on the server only`)
|
|
815
|
-
if (reads.type.has(name) || reads.value.has(name)) typeImports.add(name)
|
|
816
|
-
}
|
|
817
|
-
}
|
|
818
|
-
for (const info of copies()) {
|
|
819
|
-
const why = unshared.get(info)
|
|
820
|
-
issues.push(
|
|
821
|
-
`"${[...info.declares].join(", ")}" is needed by both halves and was copied into each${why === undefined ? "" : `, since ${why}`}; consider moving it to shared/`,
|
|
822
|
-
)
|
|
823
|
-
}
|
|
824
|
-
|
|
825
|
-
const uses = (infos: Iterable<StatementInfo>, backend: boolean): Uses => {
|
|
826
|
-
const value = new Set<string>()
|
|
827
|
-
const type = new Set<string>()
|
|
828
|
-
for (const info of infos) {
|
|
829
|
-
const reads = readsFor(info, backend)
|
|
830
|
-
for (const name of reads.value) value.add(name)
|
|
831
|
-
for (const name of reads.type) type.add(name)
|
|
832
|
-
}
|
|
833
|
-
return { value, type }
|
|
834
|
-
}
|
|
835
|
-
const backendUses = uses(backendSet, true)
|
|
836
|
-
const frontendUses = uses(frontendKeep, false)
|
|
837
|
-
|
|
838
|
-
const semi = statements.some((info) => terminatorOf(sf, info.node) !== "") ? ";" : ""
|
|
839
|
-
// The imports the split writes quote the way the file's own imports do.
|
|
840
|
-
const firstImport = statements.find((info) => ts.isImportDeclaration(info.node))?.node
|
|
841
|
-
const quote =
|
|
842
|
-
firstImport !== undefined && ts.isImportDeclaration(firstImport)
|
|
843
|
-
? (firstImport.moduleSpecifier.getText(sf)[0] ?? '"')
|
|
844
|
-
: '"'
|
|
845
|
-
const sharedNames = [...shared].flatMap((info) => [...info.declares])
|
|
846
|
-
const sharedSpecifier = (() => {
|
|
847
|
-
const file = options.sharedFile ?? ""
|
|
848
|
-
// The halves name the module the way the route names its other relative imports.
|
|
849
|
-
const relative = statements.flatMap((info) =>
|
|
850
|
-
ts.isImportDeclaration(info.node) &&
|
|
851
|
-
ts.isStringLiteral(info.node.moduleSpecifier) &&
|
|
852
|
-
info.node.moduleSpecifier.text.startsWith(".")
|
|
853
|
-
? [info.node.moduleSpecifier.text]
|
|
854
|
-
: [],
|
|
855
|
-
)
|
|
856
|
-
const extension = relative
|
|
857
|
-
.map((specifier) => /\.(ts|tsx|js|jsx)$/.exec(specifier)?.[1])
|
|
858
|
-
.find((found) => found !== undefined)
|
|
859
|
-
const suffix = extension === undefined ? "" : extension.startsWith("t") ? ".ts" : ".js"
|
|
860
|
-
return `./${file.replace(/\.ts$/, "")}${suffix}`
|
|
861
|
-
})()
|
|
862
|
-
const sharedImport = (half: Uses): string[] => {
|
|
863
|
-
const names = sharedNames
|
|
864
|
-
.filter((name) => half.value.has(name) || half.type.has(name))
|
|
865
|
-
.sort(codeUnitOrder)
|
|
866
|
-
if (names.length === 0) return []
|
|
867
|
-
const typeOnly = names.every((name) => !half.value.has(name))
|
|
868
|
-
return [
|
|
869
|
-
`\nimport ${typeOnly ? "type " : ""}{ ${names.join(", ")} } from ${quote}${sharedSpecifier}${quote}${semi}`,
|
|
870
|
-
]
|
|
871
|
-
}
|
|
872
|
-
// The page still exports what it exported, now from the shared module.
|
|
873
|
-
const reexported = [...shared].flatMap((info) =>
|
|
874
|
-
[...info.exports].flatMap(([local, names]) =>
|
|
875
|
-
names.map((name) => (name === local ? local : `${local} as ${name}`)),
|
|
876
|
-
),
|
|
877
|
-
)
|
|
210
|
+
export {
|
|
211
|
+
applyEdits,
|
|
212
|
+
mergeModules,
|
|
213
|
+
middlewareSource,
|
|
214
|
+
type SplitOptions,
|
|
215
|
+
type SplitResult,
|
|
216
|
+
scriptBlocks,
|
|
217
|
+
splitRouteSource,
|
|
218
|
+
type TextEdit,
|
|
219
|
+
} from "./migrate-layout-split.ts"
|
|
878
220
|
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
)
|
|
903
|
-
continue
|
|
904
|
-
}
|
|
905
|
-
if (exportsOf(info).some((name) => !BACKEND_EXPORTS.has(name))) {
|
|
906
|
-
issues.push(
|
|
907
|
-
`one statement exports both "${exportsOf(info).join('", "')}"; split it by hand`,
|
|
908
|
-
)
|
|
909
|
-
}
|
|
910
|
-
backendTexts.push(info.text)
|
|
911
|
-
continue
|
|
912
|
-
}
|
|
913
|
-
if (backendSet.has(info)) backendTexts.push(stripExport(ts, sf, info))
|
|
914
|
-
if (frontendKeep.has(info)) frontendTexts.push(info.text)
|
|
915
|
-
}
|
|
916
|
-
// After the other imports: the nearest relative path sorts last.
|
|
917
|
-
const frontendImports = sharedImport(frontendUses)
|
|
918
|
-
if (reexported.length > 0)
|
|
919
|
-
frontendImports.push(
|
|
920
|
-
`\nexport { ${reexported.join(", ")} } from ${quote}${sharedSpecifier}${quote}${semi}`,
|
|
921
|
-
)
|
|
922
|
-
if (typeImports.size > 0)
|
|
923
|
-
frontendImports.push(
|
|
924
|
-
`\nimport type { ${[...typeImports].sort().join(", ")} } from ${quote}${backendSpecifier}${quote}${semi}`,
|
|
925
|
-
)
|
|
926
|
-
frontendTexts.splice(afterImports, 0, ...frontendImports)
|
|
927
|
-
backendTexts.splice(backendAfterImports, 0, ...sharedImport(backendUses))
|
|
928
|
-
// A JSX pragma counts only in the file's leading comments, and the backend half has no JSX.
|
|
929
|
-
const pragmas = (ts.getLeadingCommentRanges(source, 0) ?? [])
|
|
930
|
-
.map((range) => source.slice(range.pos, range.end))
|
|
931
|
-
.filter((comment) => /@jsx/.test(comment))
|
|
932
|
-
const lift = (text: string): string =>
|
|
933
|
-
pragmas.reduce(
|
|
934
|
-
(out, pragma) => out.replace(new RegExp(`${escapeRegExp(pragma)}[ \\t]*\\n?`), ""),
|
|
935
|
-
text,
|
|
936
|
-
)
|
|
937
|
-
const frontend = lift(joinStatements(frontendTexts))
|
|
938
|
-
let sharedText: string | undefined
|
|
939
|
-
if (shared.size > 0) {
|
|
940
|
-
const texts: string[] = []
|
|
941
|
-
const typeUses: Uses = { value: new Set(), type: sharedImports }
|
|
942
|
-
for (const info of statements) {
|
|
943
|
-
if (ts.isImportDeclaration(info.node)) {
|
|
944
|
-
const kept = filterImport(ts, sf, info.node, typeUses, true)
|
|
945
|
-
if (kept !== undefined && info.node.importClause !== undefined) texts.push(kept)
|
|
946
|
-
} else if (shared.has(info) || sharedTypes.has(info)) {
|
|
947
|
-
texts.push(withExport(ts, sf, info))
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
sharedText = lift(joinStatements(texts))
|
|
951
|
-
}
|
|
952
|
-
const result: SplitResult = {
|
|
953
|
-
frontend: pragmas.length > 0 ? `${pragmas.join("\n")}\n${frontend}` : frontend,
|
|
954
|
-
backend: lift(joinStatements(backendTexts)),
|
|
955
|
-
moved: [...new Set(moved)].sort(),
|
|
956
|
-
issues,
|
|
957
|
-
}
|
|
958
|
-
return sharedText === undefined ? result : { ...result, shared: sharedText }
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
/** A declaration the shared module holds is exported, so either half can import it. */
|
|
962
|
-
function withExport(ts: typeof TS, sf: TS.SourceFile, info: StatementInfo): string {
|
|
963
|
-
if (hasModifier(ts, info.node, ts.SyntaxKind.ExportKeyword)) return info.text
|
|
964
|
-
const at = info.node.getStart(sf) - info.node.getFullStart()
|
|
965
|
-
return `${info.text.slice(0, at)}export ${info.text.slice(at)}`
|
|
966
|
-
}
|
|
967
|
-
|
|
968
|
-
/** A helper the backend half copies keeps its declaration; an `export` on it would add a backend export. */
|
|
969
|
-
function stripExport(ts: typeof TS, sf: TS.SourceFile, info: StatementInfo): string {
|
|
970
|
-
if (info.exports.size === 0) return info.text
|
|
971
|
-
const node = info.node
|
|
972
|
-
const exportKeyword = (ts.canHaveModifiers(node) ? (ts.getModifiers(node) ?? []) : []).find(
|
|
973
|
-
(m) => m.kind === ts.SyntaxKind.ExportKeyword,
|
|
974
|
-
)
|
|
975
|
-
if (exportKeyword === undefined) return info.text
|
|
976
|
-
const start = exportKeyword.getStart(sf) - node.getFullStart()
|
|
977
|
-
const end = exportKeyword.getEnd() - node.getFullStart()
|
|
978
|
-
return info.text.slice(0, start) + info.text.slice(end).replace(/^\s+/, "")
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
/** `_middleware.ts`'s default export, as the `middleware` export of a `_layout.backend.ts`. */
|
|
982
|
-
export function middlewareSource(ts: typeof TS, source: string, fileName: string): string {
|
|
983
|
-
const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
|
984
|
-
let out = source
|
|
985
|
-
// Edit from the end so earlier offsets stay valid.
|
|
986
|
-
for (const node of [...sf.statements].reverse()) {
|
|
987
|
-
if (ts.isExportAssignment(node) && !node.isExportEquals) {
|
|
988
|
-
out = `${out.slice(0, node.getStart(sf))}export const middleware = ${node.expression.getText(sf)}${terminatorOf(sf, node)}${out.slice(node.getEnd())}`
|
|
989
|
-
} else if (
|
|
990
|
-
ts.isFunctionDeclaration(node) &&
|
|
991
|
-
hasModifier(ts, node, ts.SyntaxKind.DefaultKeyword)
|
|
992
|
-
) {
|
|
993
|
-
const modifiers = (ts.getModifiers(node) ?? []).filter(
|
|
994
|
-
(m) => m.kind === ts.SyntaxKind.ExportKeyword || m.kind === ts.SyntaxKind.DefaultKeyword,
|
|
995
|
-
)
|
|
996
|
-
const first = modifiers[0]
|
|
997
|
-
const last = modifiers[modifiers.length - 1]
|
|
998
|
-
if (first === undefined || last === undefined) continue
|
|
999
|
-
if (node.name === undefined) {
|
|
1000
|
-
const text = out
|
|
1001
|
-
.slice(last.getEnd(), node.getEnd())
|
|
1002
|
-
.replace(/^(\s*(?:async\s+)?function\s*\*?)\s*/, "$1 middleware")
|
|
1003
|
-
out = `${out.slice(0, first.getStart(sf))}export${text}${out.slice(node.getEnd())}`
|
|
1004
|
-
} else {
|
|
1005
|
-
out = `${out.slice(0, first.getStart(sf))}${out.slice(last.getEnd()).replace(/^\s+/, "")}`
|
|
1006
|
-
const semi = sf.statements.some((s) => terminatorOf(sf, s) !== "") ? ";" : ""
|
|
1007
|
-
out = `${out.trimEnd()}\nexport { ${node.name.text} as middleware }${semi}\n`
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
}
|
|
1011
|
-
return out
|
|
1012
|
-
}
|
|
1013
|
-
|
|
1014
|
-
/** Merge two backend modules: imports first (identical ones once), then the rest of each in order. */
|
|
1015
|
-
function mergeModules(ts: typeof TS, first: string, second: string): string {
|
|
1016
|
-
if (first.trim() === "") return second
|
|
1017
|
-
const split = (text: string): { imports: string[]; body: string[] } => {
|
|
1018
|
-
const sf = ts.createSourceFile("merge.ts", text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
|
1019
|
-
const imports: string[] = []
|
|
1020
|
-
const body: string[] = []
|
|
1021
|
-
for (const node of sf.statements) {
|
|
1022
|
-
;(ts.isImportDeclaration(node) ? imports : body).push(
|
|
1023
|
-
node.getFullText(sf).replace(/^\s*\n/, ""),
|
|
1024
|
-
)
|
|
1025
|
-
}
|
|
1026
|
-
return { imports, body }
|
|
1027
|
-
}
|
|
1028
|
-
const a = split(first)
|
|
1029
|
-
const b = split(second)
|
|
1030
|
-
const imports = [...new Set([...a.imports, ...b.imports].map((text) => text.trim()))]
|
|
1031
|
-
const body = [...a.body, ...b.body].map((text) => text.trim()).join("\n\n")
|
|
1032
|
-
return `${imports.join("\n")}${imports.length > 0 ? "\n\n" : ""}${body}\n`
|
|
1033
|
-
}
|
|
1034
|
-
|
|
1035
|
-
// ---------------------------------------------------------------------------------------------------
|
|
1036
|
-
// SFC script blocks
|
|
1037
|
-
// ---------------------------------------------------------------------------------------------------
|
|
1038
|
-
|
|
1039
|
-
/** The `<script>` blocks of a Svelte/Vue file: their content range and whether it is the module script. */
|
|
1040
|
-
function scriptBlocks(
|
|
1041
|
-
source: string,
|
|
1042
|
-
): Array<{ start: number; end: number; module: boolean; setup: boolean }> {
|
|
1043
|
-
const blocks: Array<{ start: number; end: number; module: boolean; setup: boolean }> = []
|
|
1044
|
-
// A closing tag ends at any space, slash or `>` after its name, as the compilers read it.
|
|
1045
|
-
const pattern = /<script\b([^>]*)>([\s\S]*?)<\/script(?=[\s/>])[^>]*>/gi
|
|
1046
|
-
// A `<script>` written inside an HTML comment is prose, not a block; blank comments out, keeping offsets.
|
|
1047
|
-
const visible = source.replace(/<!--[\s\S]*?-->/g, (comment) => comment.replace(/[^\n]/g, " "))
|
|
1048
|
-
for (const match of visible.matchAll(pattern)) {
|
|
1049
|
-
const attrs = match[1] ?? ""
|
|
1050
|
-
const start = (match.index ?? 0) + match[0].indexOf(">") + 1
|
|
1051
|
-
blocks.push({
|
|
1052
|
-
start,
|
|
1053
|
-
end: start + (match[2] ?? "").length,
|
|
1054
|
-
module: /\bmodule\b|context=["']module["']/.test(attrs),
|
|
1055
|
-
setup: /\bsetup\b/.test(attrs),
|
|
1056
|
-
})
|
|
1057
|
-
}
|
|
1058
|
-
return blocks
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
/** A replacement of the source between `start` and `end`. */
|
|
1062
|
-
interface TextEdit {
|
|
1063
|
-
start: number
|
|
1064
|
-
end: number
|
|
1065
|
-
text: string
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
/** `text` with every edit made, last offset first so the ones before it still point where they did. */
|
|
1069
|
-
function applyEdits(text: string, edits: TextEdit[]): string {
|
|
1070
|
-
let out = text
|
|
1071
|
-
for (const edit of edits.sort((a, b) => b.start - a.start))
|
|
1072
|
-
out = out.slice(0, edit.start) + edit.text + out.slice(edit.end)
|
|
1073
|
-
return out
|
|
1074
|
-
}
|
|
221
|
+
import {
|
|
222
|
+
appZones,
|
|
223
|
+
declareApiKind,
|
|
224
|
+
declareZones,
|
|
225
|
+
followTsconfigs,
|
|
226
|
+
ignoreNifraState,
|
|
227
|
+
pruneVacatedDirs,
|
|
228
|
+
rewritePackagePaths,
|
|
229
|
+
staleContentGlobs,
|
|
230
|
+
zoneDeclarations,
|
|
231
|
+
} from "./migrate-layout-config.ts"
|
|
232
|
+
import {
|
|
233
|
+
applyEdits,
|
|
234
|
+
hasModifier,
|
|
235
|
+
mergeModules,
|
|
236
|
+
middlewareSource,
|
|
237
|
+
type SplitOptions,
|
|
238
|
+
type SplitResult,
|
|
239
|
+
scriptBlocks,
|
|
240
|
+
splitRouteSource,
|
|
241
|
+
type TextEdit,
|
|
242
|
+
terminatorOf,
|
|
243
|
+
} from "./migrate-layout-split.ts"
|
|
1075
244
|
|
|
1076
245
|
// ---------------------------------------------------------------------------------------------------
|
|
1077
246
|
// Import graph + zoning
|
|
@@ -2197,7 +1366,7 @@ const packageName = (specifier: string): string => {
|
|
|
2197
1366
|
|
|
2198
1367
|
const isRootScript = (file: string, rootMoves: Readonly<Record<string, string>>): boolean =>
|
|
2199
1368
|
!file.includes("/") && SOURCE_FILE.test(file) && rootMoves[file] === undefined
|
|
2200
|
-
const isTestFile = (file: string): boolean =>
|
|
1369
|
+
export const isTestFile = (file: string): boolean =>
|
|
2201
1370
|
/(?:^|\/)(?:test|tests|__tests__)\//.test(file) || /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(file)
|
|
2202
1371
|
|
|
2203
1372
|
/** The web config an app has, old root `framework.ts` included, or `undefined`. */
|
|
@@ -3294,603 +2463,3 @@ export async function splitRouteFile(
|
|
|
3294
2463
|
writeFileSync(join(root, sharedFile), result.shared)
|
|
3295
2464
|
return [file, backendFile, sharedFile]
|
|
3296
2465
|
}
|
|
3297
|
-
|
|
3298
|
-
/** The app's `"nifra": { "zones": ... }`, so folders it already zones are left where they are. */
|
|
3299
|
-
function appZones(root: string): ZoneConfig {
|
|
3300
|
-
const manifest = join(root, "package.json")
|
|
3301
|
-
if (!existsSync(manifest)) return {}
|
|
3302
|
-
let parsed: unknown
|
|
3303
|
-
try {
|
|
3304
|
-
parsed = JSON.parse(readFileSync(manifest, "utf8"))
|
|
3305
|
-
} catch {
|
|
3306
|
-
return {}
|
|
3307
|
-
}
|
|
3308
|
-
const nifra =
|
|
3309
|
-
typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "nifra") : undefined
|
|
3310
|
-
const zones =
|
|
3311
|
-
typeof nifra === "object" && nifra !== null ? Reflect.get(nifra, "zones") : undefined
|
|
3312
|
-
return zones === undefined ? {} : parseZoneConfig(zones, manifest)
|
|
3313
|
-
}
|
|
3314
|
-
|
|
3315
|
-
const matchers = new Map<string, (file: string) => boolean>()
|
|
3316
|
-
|
|
3317
|
-
/** Whether a tsconfig `include` or `exclude` entry takes in `file` (app-relative), the way tsc reads it. */
|
|
3318
|
-
function matches(pattern: string, file: string): boolean {
|
|
3319
|
-
let match = matchers.get(pattern)
|
|
3320
|
-
if (match === undefined) {
|
|
3321
|
-
let spec = pattern
|
|
3322
|
-
.replaceAll("\\", "/")
|
|
3323
|
-
.replace(/^\.\//, "")
|
|
3324
|
-
.replace(/(?<!\/)\/+$/, "")
|
|
3325
|
-
if (spec === "" || spec === ".") match = () => true
|
|
3326
|
-
else if (!/[*?]/.test(spec)) {
|
|
3327
|
-
const folder = `${spec}/`
|
|
3328
|
-
match = (path) => path === spec || path.startsWith(folder)
|
|
3329
|
-
} else {
|
|
3330
|
-
if (spec.endsWith("**")) spec = `${spec}/*`
|
|
3331
|
-
else if (!/[*?.][^/]*$/.test(spec.slice(spec.lastIndexOf("/") + 1))) spec = `${spec}/**/*`
|
|
3332
|
-
const glob = new Bun.Glob(spec)
|
|
3333
|
-
match = (path) => glob.match(path)
|
|
3334
|
-
}
|
|
3335
|
-
matchers.set(pattern, match)
|
|
3336
|
-
}
|
|
3337
|
-
return match(file)
|
|
3338
|
-
}
|
|
3339
|
-
|
|
3340
|
-
const TSCONFIG = /^tsconfig(?:\.[\w-]+)?\.json$/
|
|
3341
|
-
const TS_FILE = /\.(?:[cm]?ts|tsx)$/
|
|
3342
|
-
|
|
3343
|
-
interface ProgramLists {
|
|
3344
|
-
readonly include: readonly string[]
|
|
3345
|
-
readonly exclude: readonly string[]
|
|
3346
|
-
readonly files: readonly string[]
|
|
3347
|
-
}
|
|
3348
|
-
|
|
3349
|
-
const inProgram = (lists: ProgramLists, file: string): boolean =>
|
|
3350
|
-
lists.files.includes(file) ||
|
|
3351
|
-
(lists.include.some((pattern) => matches(pattern, file)) &&
|
|
3352
|
-
!lists.exclude.some((pattern) => matches(pattern, file)))
|
|
3353
|
-
|
|
3354
|
-
/** `pattern` under the zone folder `to` landed in, when that reaches `to`; else `to` itself. */
|
|
3355
|
-
function twinEntry(pattern: string | undefined, to: string): string {
|
|
3356
|
-
const slash = to.indexOf("/")
|
|
3357
|
-
if (pattern === undefined || slash === -1) return to
|
|
3358
|
-
const bare = pattern.replace(/^\.\//, "")
|
|
3359
|
-
const twin = `${to.slice(0, slash)}/${bare}`
|
|
3360
|
-
if (!matches(twin, to)) return to
|
|
3361
|
-
return bare === pattern ? twin : `./${twin}`
|
|
3362
|
-
}
|
|
3363
|
-
|
|
3364
|
-
/**
|
|
3365
|
-
* Keep every TypeScript file in, or out of, each app-root `tsconfig*.json` program as it was. An entry
|
|
3366
|
-
* naming a moved file follows it; a folder or glob that took a moved file in gains its twin under the
|
|
3367
|
-
* zone folder (`src` -> `frontend/src`), and one that kept a file out does the same in `exclude`. So a
|
|
3368
|
-
* test run under its own config's types, or a folder left out on purpose, stays out after the move,
|
|
3369
|
-
* and code the config checked stays checked. An `include` or `exclude` a config inherits is not edited.
|
|
3370
|
-
*/
|
|
3371
|
-
function followTsconfigs(
|
|
3372
|
-
ts: typeof TS,
|
|
3373
|
-
root: string,
|
|
3374
|
-
moves: ReadonlyMap<string, string>,
|
|
3375
|
-
layout: ReadonlyArray<{ readonly from: string; readonly to: string }>,
|
|
3376
|
-
): {
|
|
3377
|
-
readonly files: Map<string, { readonly text: string; readonly changes: readonly string[] }>
|
|
3378
|
-
readonly issues: LayoutMigrationIssue[]
|
|
3379
|
-
} {
|
|
3380
|
-
const files = new Map<string, { readonly text: string; readonly changes: readonly string[] }>()
|
|
3381
|
-
const issues: LayoutMigrationIssue[] = []
|
|
3382
|
-
const typescript = layout.filter(({ to }) => TS_FILE.test(to))
|
|
3383
|
-
const names = readdirSync(root)
|
|
3384
|
-
.filter((name) => TSCONFIG.test(name) && isFile(join(root, name)))
|
|
3385
|
-
.sort(codeUnitOrder)
|
|
3386
|
-
// Each config's lists before and after the move, for the configs that extend it.
|
|
3387
|
-
const settled = new Map<string, { readonly before: ProgramLists; readonly after: ProgramLists }>()
|
|
3388
|
-
const pending = [...names]
|
|
3389
|
-
for (let progress = true; progress && pending.length > 0; ) {
|
|
3390
|
-
progress = false
|
|
3391
|
-
for (const name of [...pending]) {
|
|
3392
|
-
const text = readFileSync(join(root, name), "utf8")
|
|
3393
|
-
const source = ts.parseJsonText(name, text)
|
|
3394
|
-
const top = source.statements[0]?.expression
|
|
3395
|
-
if (top === undefined || !ts.isObjectLiteralExpression(top)) {
|
|
3396
|
-
pending.splice(pending.indexOf(name), 1)
|
|
3397
|
-
progress = true
|
|
3398
|
-
if (moves.size > 0)
|
|
3399
|
-
issues.push({
|
|
3400
|
-
file: name,
|
|
3401
|
-
reason: "is not a JSON object; keep the moved files in its include and exclude by hand",
|
|
3402
|
-
})
|
|
3403
|
-
continue
|
|
3404
|
-
}
|
|
3405
|
-
const base = jsonProperty(ts, top, "extends")?.initializer
|
|
3406
|
-
let parent: string | undefined
|
|
3407
|
-
if (base !== undefined && ts.isStringLiteral(base) && base.text.startsWith(".")) {
|
|
3408
|
-
const path = posix.normalize(base.text)
|
|
3409
|
-
const file = path.endsWith(".json") ? path : `${path}.json`
|
|
3410
|
-
if (names.includes(file) && file !== name) parent = file
|
|
3411
|
-
}
|
|
3412
|
-
if (parent !== undefined && pending.includes(parent)) continue
|
|
3413
|
-
pending.splice(pending.indexOf(name), 1)
|
|
3414
|
-
progress = true
|
|
3415
|
-
const inherited = parent === undefined ? undefined : settled.get(parent)
|
|
3416
|
-
const extendsOther = base !== undefined && inherited === undefined
|
|
3417
|
-
|
|
3418
|
-
const edits: TextEdit[] = []
|
|
3419
|
-
const own = new Map<string, { before: string[]; after: string[] }>()
|
|
3420
|
-
let malformed: string | undefined
|
|
3421
|
-
for (const key of ["include", "exclude", "files"]) {
|
|
3422
|
-
const array = jsonProperty(ts, top, key)?.initializer
|
|
3423
|
-
if (array === undefined) continue
|
|
3424
|
-
if (!ts.isArrayLiteralExpression(array)) {
|
|
3425
|
-
malformed = key
|
|
3426
|
-
continue
|
|
3427
|
-
}
|
|
3428
|
-
const lists: { before: string[]; after: string[] } = { before: [], after: [] }
|
|
3429
|
-
for (const element of array.elements) {
|
|
3430
|
-
if (!ts.isStringLiteral(element)) continue
|
|
3431
|
-
const to = moves.get(posix.normalize(element.text))
|
|
3432
|
-
lists.before.push(element.text)
|
|
3433
|
-
if (to === undefined) {
|
|
3434
|
-
lists.after.push(element.text)
|
|
3435
|
-
continue
|
|
3436
|
-
}
|
|
3437
|
-
const spelled = element.text.startsWith("./") ? `./${to}` : to
|
|
3438
|
-
lists.after.push(spelled)
|
|
3439
|
-
edits.push({
|
|
3440
|
-
start: element.getStart(source) + 1,
|
|
3441
|
-
end: element.getEnd() - 1,
|
|
3442
|
-
text: spelled,
|
|
3443
|
-
})
|
|
3444
|
-
}
|
|
3445
|
-
own.set(key, lists)
|
|
3446
|
-
}
|
|
3447
|
-
let updated = applyEdits(text, edits)
|
|
3448
|
-
const changes: string[] = []
|
|
3449
|
-
if (edits.length > 0) changes.push(`${edits.length} file path(s) follow their moved files`)
|
|
3450
|
-
|
|
3451
|
-
const list = (key: "include" | "exclude", when: "before" | "after"): string[] | undefined => {
|
|
3452
|
-
const mine = own.get(key)
|
|
3453
|
-
if (mine !== undefined) return mine[when]
|
|
3454
|
-
if (inherited !== undefined) return [...inherited[when][key]]
|
|
3455
|
-
if (extendsOther) return undefined
|
|
3456
|
-
// tsc's default: everything below the config, unless `files` lists the program.
|
|
3457
|
-
return key === "exclude" ? [] : own.has("files") ? [] : ["**/*"]
|
|
3458
|
-
}
|
|
3459
|
-
const filesOf = (when: "before" | "after"): string[] =>
|
|
3460
|
-
(own.get("files")?.[when] ?? []).map((entry) => posix.normalize(entry))
|
|
3461
|
-
const beforeInclude = list("include", "before")
|
|
3462
|
-
const beforeExclude = list("exclude", "before")
|
|
3463
|
-
const afterInclude = list("include", "after")
|
|
3464
|
-
const afterExclude = list("exclude", "after")
|
|
3465
|
-
if (
|
|
3466
|
-
malformed !== undefined ||
|
|
3467
|
-
beforeInclude === undefined ||
|
|
3468
|
-
beforeExclude === undefined ||
|
|
3469
|
-
afterInclude === undefined ||
|
|
3470
|
-
afterExclude === undefined
|
|
3471
|
-
) {
|
|
3472
|
-
if (malformed !== undefined && moves.size > 0)
|
|
3473
|
-
issues.push({
|
|
3474
|
-
file: name,
|
|
3475
|
-
reason: `"${malformed}" is not an array; keep the moved files in its program by hand`,
|
|
3476
|
-
})
|
|
3477
|
-
if (edits.length > 0) files.set(name, { text: updated, changes })
|
|
3478
|
-
continue
|
|
3479
|
-
}
|
|
3480
|
-
const before: ProgramLists = {
|
|
3481
|
-
include: beforeInclude,
|
|
3482
|
-
exclude: beforeExclude,
|
|
3483
|
-
files: filesOf("before"),
|
|
3484
|
-
}
|
|
3485
|
-
const after = { include: afterInclude, exclude: afterExclude, files: filesOf("after") }
|
|
3486
|
-
const added: { include: string[]; exclude: string[] } = { include: [], exclude: [] }
|
|
3487
|
-
let stranded: { readonly from: string; readonly to: string; readonly key: string } | undefined
|
|
3488
|
-
let strandedCount = 0
|
|
3489
|
-
const quiet = new Map<string, boolean>()
|
|
3490
|
-
// The whole zone folder is the entry that keeps covering code added there later, but only when
|
|
3491
|
-
// it takes in no file the config left out.
|
|
3492
|
-
const takesInOnlyChecked = (folder: string): boolean => {
|
|
3493
|
-
let safe = quiet.get(folder)
|
|
3494
|
-
if (safe === undefined) {
|
|
3495
|
-
const wider = { ...after, include: [...after.include, folder] }
|
|
3496
|
-
safe = typescript.every(
|
|
3497
|
-
(file) =>
|
|
3498
|
-
!matches(folder, file.to) ||
|
|
3499
|
-
inProgram(before, file.from) ||
|
|
3500
|
-
!inProgram(wider, file.to),
|
|
3501
|
-
)
|
|
3502
|
-
quiet.set(folder, safe)
|
|
3503
|
-
}
|
|
3504
|
-
return safe
|
|
3505
|
-
}
|
|
3506
|
-
for (const { from, to } of typescript) {
|
|
3507
|
-
if (!inProgram(before, from) || inProgram(after, to)) continue
|
|
3508
|
-
if (after.include.some((pattern) => matches(pattern, to))) {
|
|
3509
|
-
// Its new place sits under an `exclude` that did not hold the old one.
|
|
3510
|
-
stranded ??= { from, to, key: "exclude" }
|
|
3511
|
-
strandedCount++
|
|
3512
|
-
continue
|
|
3513
|
-
}
|
|
3514
|
-
const zone = to.includes("/") ? to.slice(0, to.indexOf("/")) : undefined
|
|
3515
|
-
const entry =
|
|
3516
|
-
zone !== undefined && takesInOnlyChecked(zone)
|
|
3517
|
-
? zone
|
|
3518
|
-
: twinEntry(
|
|
3519
|
-
before.include.find((pattern) => matches(pattern, from)),
|
|
3520
|
-
to,
|
|
3521
|
-
)
|
|
3522
|
-
added.include.push(entry)
|
|
3523
|
-
after.include.push(entry)
|
|
3524
|
-
}
|
|
3525
|
-
for (const { from, to } of typescript) {
|
|
3526
|
-
if (inProgram(before, from) || !inProgram(after, to)) continue
|
|
3527
|
-
let entry = twinEntry(
|
|
3528
|
-
before.exclude.find((pattern) => matches(pattern, from)),
|
|
3529
|
-
to,
|
|
3530
|
-
)
|
|
3531
|
-
// A twin that would also drop a file the config checked is too wide: name the file.
|
|
3532
|
-
if (
|
|
3533
|
-
entry !== to &&
|
|
3534
|
-
typescript.some((other) => matches(entry, other.to) && inProgram(before, other.from))
|
|
3535
|
-
)
|
|
3536
|
-
entry = to
|
|
3537
|
-
added.exclude.push(entry)
|
|
3538
|
-
after.exclude.push(entry)
|
|
3539
|
-
}
|
|
3540
|
-
for (const key of ["include", "exclude"] as const) {
|
|
3541
|
-
const entries = [...new Set(added[key])].sort(codeUnitOrder)
|
|
3542
|
-
if (entries.length === 0) continue
|
|
3543
|
-
const reparsed = ts.parseJsonText(name, updated)
|
|
3544
|
-
const object = reparsed.statements[0]?.expression
|
|
3545
|
-
const array =
|
|
3546
|
-
object !== undefined && ts.isObjectLiteralExpression(object)
|
|
3547
|
-
? jsonProperty(ts, object, key)?.initializer
|
|
3548
|
-
: undefined
|
|
3549
|
-
if (array === undefined || !ts.isArrayLiteralExpression(array)) {
|
|
3550
|
-
stranded ??= { from: "", to: entries[0] ?? "", key }
|
|
3551
|
-
strandedCount += entries.length
|
|
3552
|
-
continue
|
|
3553
|
-
}
|
|
3554
|
-
updated = appendToArray(reparsed, updated, array, entries)
|
|
3555
|
-
changes.push(`${key} += ${entries.join(", ")}`)
|
|
3556
|
-
}
|
|
3557
|
-
if (stranded !== undefined)
|
|
3558
|
-
issues.push({
|
|
3559
|
-
file: name,
|
|
3560
|
-
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`,
|
|
3561
|
-
})
|
|
3562
|
-
settled.set(name, { before, after })
|
|
3563
|
-
if (changes.length > 0) files.set(name, { text: updated, changes })
|
|
3564
|
-
}
|
|
3565
|
-
}
|
|
3566
|
-
return { files, issues }
|
|
3567
|
-
}
|
|
3568
|
-
|
|
3569
|
-
/** `text` with `entries` appended to `array`: one per line in a multi-line array, else inline. */
|
|
3570
|
-
function appendToArray(
|
|
3571
|
-
source: TS.JsonSourceFile,
|
|
3572
|
-
text: string,
|
|
3573
|
-
array: TS.ArrayLiteralExpression,
|
|
3574
|
-
entries: readonly string[],
|
|
3575
|
-
): string {
|
|
3576
|
-
const quoted = entries.map((entry) => JSON.stringify(entry))
|
|
3577
|
-
const last = array.elements[array.elements.length - 1]
|
|
3578
|
-
if (last === undefined) {
|
|
3579
|
-
const at = array.getStart(source) + 1
|
|
3580
|
-
return `${text.slice(0, at)}${quoted.join(", ")}${text.slice(at)}`
|
|
3581
|
-
}
|
|
3582
|
-
let at = last.end
|
|
3583
|
-
const trailing = /^\s*,/.exec(text.slice(at))
|
|
3584
|
-
if (trailing !== null) at += trailing[0].length
|
|
3585
|
-
// A multi-line array gets one entry per line at the last element's indent, below any comment that
|
|
3586
|
-
// closes the last element's line; anything else gets them inline.
|
|
3587
|
-
if (text.slice(array.getStart(source), last.getStart(source)).includes("\n")) {
|
|
3588
|
-
const lineStart = text.lastIndexOf("\n", last.getStart(source)) + 1
|
|
3589
|
-
const indent = text.slice(lineStart, last.getStart(source)).match(/^\s*/)?.[0] ?? ""
|
|
3590
|
-
const newline = text.indexOf("\n", at)
|
|
3591
|
-
const eol = newline === -1 ? text.length : newline
|
|
3592
|
-
if (/^\s*(?:\/\/.*|\/\*.*\*\/\s*)?$/.test(text.slice(at, eol))) {
|
|
3593
|
-
const head =
|
|
3594
|
-
trailing !== null
|
|
3595
|
-
? text.slice(0, eol)
|
|
3596
|
-
: `${text.slice(0, last.end)},${text.slice(last.end, eol)}`
|
|
3597
|
-
const lines = quoted.join(`,\n${indent}`)
|
|
3598
|
-
return `${head}\n${indent}${lines}${trailing !== null ? "," : ""}${text.slice(eol)}`
|
|
3599
|
-
}
|
|
3600
|
-
}
|
|
3601
|
-
const insert = trailing !== null ? ` ${quoted.join(", ")},` : `, ${quoted.join(", ")}`
|
|
3602
|
-
return `${text.slice(0, at)}${insert}${text.slice(at)}`
|
|
3603
|
-
}
|
|
3604
|
-
|
|
3605
|
-
const jsonProperty = (
|
|
3606
|
-
ts: typeof TS,
|
|
3607
|
-
object: TS.ObjectLiteralExpression,
|
|
3608
|
-
key: string,
|
|
3609
|
-
): TS.PropertyAssignment | undefined =>
|
|
3610
|
-
object.properties.find(
|
|
3611
|
-
(property): property is TS.PropertyAssignment =>
|
|
3612
|
-
ts.isPropertyAssignment(property) &&
|
|
3613
|
-
ts.isStringLiteral(property.name) &&
|
|
3614
|
-
property.name.text === key,
|
|
3615
|
-
)
|
|
3616
|
-
|
|
3617
|
-
/** `text` with `entry` as the last property of `object`, on its own line when the object spans lines. */
|
|
3618
|
-
function insertProperty(
|
|
3619
|
-
source: TS.JsonSourceFile,
|
|
3620
|
-
text: string,
|
|
3621
|
-
object: TS.ObjectLiteralExpression,
|
|
3622
|
-
entry: string,
|
|
3623
|
-
): string {
|
|
3624
|
-
const open = object.getStart(source)
|
|
3625
|
-
const last = object.properties[object.properties.length - 1]
|
|
3626
|
-
if (last === undefined) return `${text.slice(0, open)}{ ${entry} }${text.slice(object.end)}`
|
|
3627
|
-
const start = last.getStart(source)
|
|
3628
|
-
if (!text.slice(open, start).includes("\n")) {
|
|
3629
|
-
return `${text.slice(0, last.end)}, ${entry}${text.slice(last.end)}`
|
|
3630
|
-
}
|
|
3631
|
-
const indent = /^[ \t]*/.exec(text.slice(text.lastIndexOf("\n", start) + 1, start))?.[0] ?? ""
|
|
3632
|
-
return `${text.slice(0, last.end)},\n${indent}${entry}${text.slice(last.end)}`
|
|
3633
|
-
}
|
|
3634
|
-
|
|
3635
|
-
/**
|
|
3636
|
-
* The `nifra.zones` entries that keep `inPlace` files where they are: for each, the widest folder
|
|
3637
|
-
* above it whose zoned files all take its side (a nested package stops the climb), else the file
|
|
3638
|
-
* itself. A file another side's suffix or a server built-in claims counts against a folder.
|
|
3639
|
-
*/
|
|
3640
|
-
function zoneDeclarations(
|
|
3641
|
-
inPlace: ReadonlyMap<string, FolderSide>,
|
|
3642
|
-
files: readonly string[],
|
|
3643
|
-
text: (file: string) => string | undefined,
|
|
3644
|
-
configured: (file: string) => boolean,
|
|
3645
|
-
): Map<string, FolderSide> {
|
|
3646
|
-
const sides = new Map<string, Set<string>>()
|
|
3647
|
-
const packages = new Set<string>()
|
|
3648
|
-
for (const file of files) {
|
|
3649
|
-
const top = file.split("/")[0] ?? ""
|
|
3650
|
-
if (!file.includes("/") || ZONE_DIRS.has(top)) continue
|
|
3651
|
-
if (posix.basename(file) === "package.json") {
|
|
3652
|
-
for (let dir = posix.dirname(file); dir !== "."; dir = posix.dirname(dir)) packages.add(dir)
|
|
3653
|
-
continue
|
|
3654
|
-
}
|
|
3655
|
-
// A configured path is more specific than any folder above it, so it never counts against one.
|
|
3656
|
-
if (isTestFile(file) || file.endsWith(".d.ts") || configured(file)) continue
|
|
3657
|
-
const suffix = /\.(frontend|backend|shared|fn)\.[cm]?[jt]sx?$/.exec(file)?.[1]
|
|
3658
|
-
const side =
|
|
3659
|
-
inPlace.get(file) ??
|
|
3660
|
-
(suffix === "fn" ? "backend" : suffix) ??
|
|
3661
|
-
(SOURCE_FILE.test(file) && /from\s+["'](?:node:|bun:)/.test(text(file) ?? "")
|
|
3662
|
-
? "backend"
|
|
3663
|
-
: undefined)
|
|
3664
|
-
if (side === undefined) continue
|
|
3665
|
-
for (let dir = posix.dirname(file); dir !== "."; dir = posix.dirname(dir))
|
|
3666
|
-
sides.set(dir, (sides.get(dir) ?? new Set<string>()).add(side))
|
|
3667
|
-
}
|
|
3668
|
-
const declared = new Map<string, FolderSide>()
|
|
3669
|
-
for (const [file, side] of [...inPlace].sort(([a], [b]) => codeUnitOrder(a, b))) {
|
|
3670
|
-
const parts = file.split("/")
|
|
3671
|
-
let path = file
|
|
3672
|
-
for (let depth = 1; depth < parts.length; depth++) {
|
|
3673
|
-
const dir = parts.slice(0, depth).join("/")
|
|
3674
|
-
const found = sides.get(dir)
|
|
3675
|
-
if (!packages.has(dir) && found?.size === 1 && found.has(side)) {
|
|
3676
|
-
path = dir
|
|
3677
|
-
break
|
|
3678
|
-
}
|
|
3679
|
-
}
|
|
3680
|
-
declared.set(path, side)
|
|
3681
|
-
}
|
|
3682
|
-
return declared
|
|
3683
|
-
}
|
|
3684
|
-
|
|
3685
|
-
/** The app's package.json with `paths` added to `"nifra": { "zones": ... }`, editing only where they go. */
|
|
3686
|
-
function declareZones(
|
|
3687
|
-
ts: typeof TS,
|
|
3688
|
-
root: string,
|
|
3689
|
-
paths: ReadonlyMap<string, FolderSide>,
|
|
3690
|
-
): { text?: string; issue?: string } {
|
|
3691
|
-
const listed = (side: FolderSide): string[] =>
|
|
3692
|
-
[...paths].flatMap(([path, of]) => (of === side ? [path] : []))
|
|
3693
|
-
const setting = `{ ${FOLDER_SIDES.filter((side) => listed(side).length > 0)
|
|
3694
|
-
.map((side) => `"${side}": ${JSON.stringify(listed(side))}`)
|
|
3695
|
-
.join(", ")} }`
|
|
3696
|
-
const path = join(root, "package.json")
|
|
3697
|
-
if (!existsSync(path))
|
|
3698
|
-
return { issue: `there is none in the app; declare "nifra": { "zones": ${setting} } in it` }
|
|
3699
|
-
let text = readFileSync(path, "utf8")
|
|
3700
|
-
// Parsed again for each edit: an edit moves every offset after it.
|
|
3701
|
-
const find = (keys: readonly string[]) => {
|
|
3702
|
-
const source = ts.parseJsonText(path, text)
|
|
3703
|
-
let node: TS.Expression | undefined = source.statements[0]?.expression
|
|
3704
|
-
for (const key of keys)
|
|
3705
|
-
node =
|
|
3706
|
-
node !== undefined && ts.isObjectLiteralExpression(node)
|
|
3707
|
-
? jsonProperty(ts, node, key)?.initializer
|
|
3708
|
-
: undefined
|
|
3709
|
-
return { source, node }
|
|
3710
|
-
}
|
|
3711
|
-
const top = find([])
|
|
3712
|
-
if (top.node === undefined || !ts.isObjectLiteralExpression(top.node))
|
|
3713
|
-
return { issue: `is not a JSON object; add "nifra": { "zones": ${setting} } to it by hand` }
|
|
3714
|
-
const nifra = find(["nifra"])
|
|
3715
|
-
if (nifra.node === undefined)
|
|
3716
|
-
return { text: insertProperty(top.source, text, top.node, `"nifra": { "zones": ${setting} }`) }
|
|
3717
|
-
if (!ts.isObjectLiteralExpression(nifra.node))
|
|
3718
|
-
return { issue: `"nifra" is not an object; add "zones": ${setting} to it by hand` }
|
|
3719
|
-
const zones = find(["nifra", "zones"])
|
|
3720
|
-
if (zones.node === undefined)
|
|
3721
|
-
return { text: insertProperty(nifra.source, text, nifra.node, `"zones": ${setting}`) }
|
|
3722
|
-
for (const side of FOLDER_SIDES) {
|
|
3723
|
-
const add = listed(side)
|
|
3724
|
-
if (add.length === 0) continue
|
|
3725
|
-
const { source, node } = find(["nifra", "zones"])
|
|
3726
|
-
if (node === undefined || !ts.isObjectLiteralExpression(node))
|
|
3727
|
-
return { issue: `"nifra.zones" is not an object; add ${setting} to it by hand` }
|
|
3728
|
-
const array = jsonProperty(ts, node, side)?.initializer
|
|
3729
|
-
if (array === undefined)
|
|
3730
|
-
text = insertProperty(source, text, node, `"${side}": ${JSON.stringify(add)}`)
|
|
3731
|
-
else if (ts.isArrayLiteralExpression(array)) text = appendToArray(source, text, array, add)
|
|
3732
|
-
else
|
|
3733
|
-
return {
|
|
3734
|
-
issue: `"nifra.zones.${side}" is not an array; add ${JSON.stringify(add)} to it by hand`,
|
|
3735
|
-
}
|
|
3736
|
-
}
|
|
3737
|
-
return { text }
|
|
3738
|
-
}
|
|
3739
|
-
|
|
3740
|
-
/** The app's package.json with `"nifra": { "kind": "api" }` added, editing only where it goes. */
|
|
3741
|
-
function declareApiKind(ts: typeof TS, root: string): { text?: string; issue?: string } {
|
|
3742
|
-
const path = join(root, "package.json")
|
|
3743
|
-
if (!existsSync(path)) {
|
|
3744
|
-
return {
|
|
3745
|
-
issue:
|
|
3746
|
-
'there is none in the app; declare "nifra": { "kind": "api" } in the package.json that governs it',
|
|
3747
|
-
}
|
|
3748
|
-
}
|
|
3749
|
-
const text = readFileSync(path, "utf8")
|
|
3750
|
-
const source = ts.parseJsonText(path, text)
|
|
3751
|
-
const top = source.statements[0]?.expression
|
|
3752
|
-
if (top === undefined || !ts.isObjectLiteralExpression(top))
|
|
3753
|
-
return { issue: 'is not a JSON object; add "nifra": { "kind": "api" } to it by hand' }
|
|
3754
|
-
const nifra = jsonProperty(ts, top, "nifra")
|
|
3755
|
-
if (nifra === undefined) {
|
|
3756
|
-
return { text: insertProperty(source, text, top, '"nifra": { "kind": "api" }') }
|
|
3757
|
-
}
|
|
3758
|
-
if (!ts.isObjectLiteralExpression(nifra.initializer))
|
|
3759
|
-
return { issue: '"nifra" is not an object; add "kind": "api" to it by hand' }
|
|
3760
|
-
return { text: insertProperty(source, text, nifra.initializer, '"kind": "api"') }
|
|
3761
|
-
}
|
|
3762
|
-
|
|
3763
|
-
/** package.json fields whose string values name files from the package folder. */
|
|
3764
|
-
const PACKAGE_PATH_FIELDS = new Set([
|
|
3765
|
-
"main",
|
|
3766
|
-
"module",
|
|
3767
|
-
"types",
|
|
3768
|
-
"typings",
|
|
3769
|
-
"browser",
|
|
3770
|
-
"source",
|
|
3771
|
-
"bin",
|
|
3772
|
-
"exports",
|
|
3773
|
-
"imports",
|
|
3774
|
-
"files",
|
|
3775
|
-
"scripts",
|
|
3776
|
-
])
|
|
3777
|
-
|
|
3778
|
-
/**
|
|
3779
|
-
* `text` (a package.json at the app root) with each moved file it names by its exact path, in the
|
|
3780
|
-
* fields above, named at its new path; `./` kept as written. A value with a `*` outside `scripts` is a
|
|
3781
|
-
* pattern over a folder, which no single move settles, so it stays and the path scan reports it.
|
|
3782
|
-
*/
|
|
3783
|
-
function rewritePackagePaths(
|
|
3784
|
-
ts: typeof TS,
|
|
3785
|
-
text: string,
|
|
3786
|
-
moves: ReadonlyMap<string, string>,
|
|
3787
|
-
): { readonly text: string; readonly count: number } {
|
|
3788
|
-
const source = ts.parseJsonText("package.json", text)
|
|
3789
|
-
const top = source.statements[0]?.expression
|
|
3790
|
-
if (top === undefined || !ts.isObjectLiteralExpression(top) || moves.size === 0)
|
|
3791
|
-
return { text, count: 0 }
|
|
3792
|
-
// Longest first, so `lib/a.test.ts` is not read as `lib/a.ts` with a tail.
|
|
3793
|
-
const ordered = [...moves].sort(([a], [b]) => b.length - a.length)
|
|
3794
|
-
const pattern = new RegExp(
|
|
3795
|
-
`(?<![\\w.@/-])(\\./)?(${ordered.map(([from]) => escapeRegExp(from)).join("|")})(?![\\w/-]|\\.\\w)`,
|
|
3796
|
-
"g",
|
|
3797
|
-
)
|
|
3798
|
-
const edits: TextEdit[] = []
|
|
3799
|
-
let count = 0
|
|
3800
|
-
const visit = (node: TS.Node, field: string): void => {
|
|
3801
|
-
if (ts.isStringLiteral(node)) {
|
|
3802
|
-
if (field !== "scripts" && node.text.includes("*")) return
|
|
3803
|
-
const value = node.text.replace(pattern, (_match, dot: string | undefined, from: string) => {
|
|
3804
|
-
count += 1
|
|
3805
|
-
return `${dot ?? ""}${moves.get(from) ?? from}`
|
|
3806
|
-
})
|
|
3807
|
-
if (value !== node.text)
|
|
3808
|
-
edits.push({
|
|
3809
|
-
start: node.getStart(source),
|
|
3810
|
-
end: node.getEnd(),
|
|
3811
|
-
text: JSON.stringify(value),
|
|
3812
|
-
})
|
|
3813
|
-
return
|
|
3814
|
-
}
|
|
3815
|
-
if (ts.isArrayLiteralExpression(node)) {
|
|
3816
|
-
for (const element of node.elements) visit(element, field)
|
|
3817
|
-
return
|
|
3818
|
-
}
|
|
3819
|
-
if (!ts.isObjectLiteralExpression(node)) return
|
|
3820
|
-
for (const property of node.properties) {
|
|
3821
|
-
if (!ts.isPropertyAssignment(property)) continue
|
|
3822
|
-
// `"//x"` keys are comments by npm convention.
|
|
3823
|
-
if (ts.isStringLiteral(property.name) && property.name.text.startsWith("//")) continue
|
|
3824
|
-
visit(property.initializer, field)
|
|
3825
|
-
}
|
|
3826
|
-
}
|
|
3827
|
-
for (const property of top.properties) {
|
|
3828
|
-
if (!ts.isPropertyAssignment(property) || !ts.isStringLiteral(property.name)) continue
|
|
3829
|
-
if (PACKAGE_PATH_FIELDS.has(property.name.text)) visit(property.initializer, property.name.text)
|
|
3830
|
-
}
|
|
3831
|
-
return { text: applyEdits(text, edits), count }
|
|
3832
|
-
}
|
|
3833
|
-
|
|
3834
|
-
/** Tailwind `content` globs that matched a moved file at its old path and match nothing at its new one. */
|
|
3835
|
-
function staleContentGlobs(
|
|
3836
|
-
ts: typeof TS,
|
|
3837
|
-
text: string,
|
|
3838
|
-
moves: ReadonlyArray<{ readonly from: string; readonly to: string }>,
|
|
3839
|
-
): string | undefined {
|
|
3840
|
-
const globs: string[] = []
|
|
3841
|
-
const source = ts.createSourceFile("tailwind.config.ts", text, ts.ScriptTarget.Latest, true)
|
|
3842
|
-
const visit = (node: TS.Node): void => {
|
|
3843
|
-
if (ts.isStringLiteralLike(node) && /[*/]/.test(node.text) && !node.text.startsWith("!"))
|
|
3844
|
-
globs.push(node.text.replace(/^\.\//, ""))
|
|
3845
|
-
ts.forEachChild(node, visit)
|
|
3846
|
-
}
|
|
3847
|
-
visit(source)
|
|
3848
|
-
const matchers = globs.map((glob) => ({ glob, matcher: new Bun.Glob(glob) }))
|
|
3849
|
-
const lost = moves.filter(
|
|
3850
|
-
({ from, to }) =>
|
|
3851
|
-
matchers.some(({ matcher }) => matcher.match(from)) &&
|
|
3852
|
-
!matchers.some(({ matcher }) => matcher.match(to)),
|
|
3853
|
-
)
|
|
3854
|
-
const first = lost[0]
|
|
3855
|
-
if (first === undefined) return undefined
|
|
3856
|
-
const folders = [...new Set(lost.map(({ to }) => to.split("/")[0] ?? to))].sort(codeUnitOrder)
|
|
3857
|
-
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)`
|
|
3858
|
-
}
|
|
3859
|
-
|
|
3860
|
-
/**
|
|
3861
|
-
* `.nifra/` holds generated types, dev state and the dev server's launch token; none of it belongs in
|
|
3862
|
-
* git. The new `.gitignore` text when it is not ignored yet, else `undefined`.
|
|
3863
|
-
*/
|
|
3864
|
-
function ignoreNifraState(root: string): string | undefined {
|
|
3865
|
-
let exitCode: number | null = null
|
|
3866
|
-
try {
|
|
3867
|
-
exitCode = Bun.spawnSync(["git", "check-ignore", "-q", ".nifra/types"], {
|
|
3868
|
-
cwd: root,
|
|
3869
|
-
stdout: "ignore",
|
|
3870
|
-
stderr: "ignore",
|
|
3871
|
-
}).exitCode
|
|
3872
|
-
} catch {
|
|
3873
|
-
// No git installed: the same as no checkout.
|
|
3874
|
-
}
|
|
3875
|
-
if (exitCode === 0) return undefined
|
|
3876
|
-
const path = join(root, ".gitignore")
|
|
3877
|
-
const current = existsSync(path) ? readFileSync(path, "utf8") : ""
|
|
3878
|
-
// Outside a git checkout `check-ignore` cannot answer; the app's own file decides.
|
|
3879
|
-
if (exitCode !== 1 && /^\/?\.nifra(?:\/|\*|\/\*\*)?\s*$/m.test(current)) return undefined
|
|
3880
|
-
const separator = current === "" || current.endsWith("\n") ? "" : "\n"
|
|
3881
|
-
return `${current}${separator}.nifra/\n`
|
|
3882
|
-
}
|
|
3883
|
-
|
|
3884
|
-
/** Remove each directory the run emptied, then each parent that leaves empty. A directory that was
|
|
3885
|
-
* empty before the run is the app's own, not the migration's to remove. */
|
|
3886
|
-
function pruneVacatedDirs(root: string, vacated: Iterable<string>): void {
|
|
3887
|
-
const dirs = new Set<string>()
|
|
3888
|
-
for (const file of vacated) dirs.add(dirname(join(root, file)))
|
|
3889
|
-
// Deepest first, so a parent is judged after its emptied children are gone.
|
|
3890
|
-
for (const start of [...dirs].sort((a, b) => b.length - a.length)) {
|
|
3891
|
-
for (let dir = start; dir !== root && dir.startsWith(`${root}${sep}`); dir = dirname(dir)) {
|
|
3892
|
-
if (!existsSync(dir) || readdirSync(dir).length > 0) break
|
|
3893
|
-
rmdirSync(dir)
|
|
3894
|
-
}
|
|
3895
|
-
}
|
|
3896
|
-
}
|