@nifrajs/cli 5.5.1 → 5.6.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 (138) hide show
  1. package/CHANGELOG.md +155 -0
  2. package/dist/cdn-check.d.ts +7 -6
  3. package/dist/cdn-check.d.ts.map +1 -1
  4. package/dist/cdn-check.js +13 -1
  5. package/dist/cdn-check.js.map +1 -1
  6. package/dist/check-diagnostics.d.ts.map +1 -1
  7. package/dist/check-diagnostics.js +5 -3
  8. package/dist/check-diagnostics.js.map +1 -1
  9. package/dist/check-scan.d.ts.map +1 -1
  10. package/dist/check-scan.js +29 -2
  11. package/dist/check-scan.js.map +1 -1
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +14 -5
  14. package/dist/cli.js.map +1 -1
  15. package/dist/command-catalog.d.ts +14 -1
  16. package/dist/command-catalog.d.ts.map +1 -1
  17. package/dist/command-catalog.js +93 -0
  18. package/dist/command-catalog.js.map +1 -1
  19. package/dist/doctor.d.ts +9 -1
  20. package/dist/doctor.d.ts.map +1 -1
  21. package/dist/doctor.js +52 -0
  22. package/dist/doctor.js.map +1 -1
  23. package/dist/fix-recipes.d.ts.map +1 -1
  24. package/dist/fix-recipes.js +27 -0
  25. package/dist/fix-recipes.js.map +1 -1
  26. package/dist/frontend-guidance.d.ts +1 -1
  27. package/dist/frontend-guidance.d.ts.map +1 -1
  28. package/dist/frontend-guidance.js +17 -8
  29. package/dist/frontend-guidance.js.map +1 -1
  30. package/dist/introspect.js +1 -1
  31. package/dist/introspect.js.map +1 -1
  32. package/dist/load.d.ts +4 -1
  33. package/dist/load.d.ts.map +1 -1
  34. package/dist/load.js +8 -0
  35. package/dist/load.js.map +1 -1
  36. package/dist/mcp-exec.d.ts.map +1 -1
  37. package/dist/mcp-exec.js +57 -3
  38. package/dist/mcp-exec.js.map +1 -1
  39. package/dist/mcp-http.d.ts +2 -1
  40. package/dist/mcp-http.d.ts.map +1 -1
  41. package/dist/mcp-http.js +3 -2
  42. package/dist/mcp-http.js.map +1 -1
  43. package/dist/mcp-tool-meta.d.ts +21 -0
  44. package/dist/mcp-tool-meta.d.ts.map +1 -0
  45. package/dist/mcp-tool-meta.js +246 -0
  46. package/dist/mcp-tool-meta.js.map +1 -0
  47. package/dist/mcp.d.ts +3 -2
  48. package/dist/mcp.d.ts.map +1 -1
  49. package/dist/mcp.js +36 -98
  50. package/dist/mcp.js.map +1 -1
  51. package/dist/output-schemas.d.ts +8 -0
  52. package/dist/output-schemas.d.ts.map +1 -1
  53. package/dist/output-schemas.js +14 -0
  54. package/dist/output-schemas.js.map +1 -1
  55. package/dist/ppr-read-fix.d.ts +8 -0
  56. package/dist/ppr-read-fix.d.ts.map +1 -0
  57. package/dist/ppr-read-fix.js +356 -0
  58. package/dist/ppr-read-fix.js.map +1 -0
  59. package/dist/recipes/5.6.0.d.ts +10 -0
  60. package/dist/recipes/5.6.0.d.ts.map +1 -0
  61. package/dist/recipes/5.6.0.js +68 -0
  62. package/dist/recipes/5.6.0.js.map +1 -0
  63. package/dist/recipes/index.d.ts.map +1 -1
  64. package/dist/recipes/index.js +2 -0
  65. package/dist/recipes/index.js.map +1 -1
  66. package/dist/review.d.ts.map +1 -1
  67. package/dist/review.js +7 -2
  68. package/dist/review.js.map +1 -1
  69. package/dist/rules/codes.d.ts +8 -3
  70. package/dist/rules/codes.d.ts.map +1 -1
  71. package/dist/rules/codes.js +9 -4
  72. package/dist/rules/codes.js.map +1 -1
  73. package/dist/rules/explanations.d.ts.map +1 -1
  74. package/dist/rules/explanations.js +39 -13
  75. package/dist/rules/explanations.js.map +1 -1
  76. package/dist/rules/islands.d.ts +91 -0
  77. package/dist/rules/islands.d.ts.map +1 -1
  78. package/dist/rules/islands.js +757 -3
  79. package/dist/rules/islands.js.map +1 -1
  80. package/dist/rules/ppr.d.ts +16 -0
  81. package/dist/rules/ppr.d.ts.map +1 -0
  82. package/dist/rules/ppr.js +114 -0
  83. package/dist/rules/ppr.js.map +1 -0
  84. package/dist/rules/swap.d.ts +7 -0
  85. package/dist/rules/swap.d.ts.map +1 -0
  86. package/dist/rules/swap.js +338 -0
  87. package/dist/rules/swap.js.map +1 -0
  88. package/dist/scaffold-hole.d.ts +105 -0
  89. package/dist/scaffold-hole.d.ts.map +1 -0
  90. package/dist/scaffold-hole.js +688 -0
  91. package/dist/scaffold-hole.js.map +1 -0
  92. package/dist/scaffold.d.ts +5 -3
  93. package/dist/scaffold.d.ts.map +1 -1
  94. package/dist/scaffold.js +56 -46
  95. package/dist/scaffold.js.map +1 -1
  96. package/dist/verification-plan.d.ts.map +1 -1
  97. package/dist/verification-plan.js +12 -1
  98. package/dist/verification-plan.js.map +1 -1
  99. package/dist/web-app-options.d.ts +1 -1
  100. package/dist/web-app-options.d.ts.map +1 -1
  101. package/dist/web-app-options.js.map +1 -1
  102. package/docs/examples.json +63 -9
  103. package/docs/llms-full.txt +2060 -430
  104. package/docs/types.json +1300 -270
  105. package/package.json +11 -11
  106. package/src/cdn-check.ts +21 -7
  107. package/src/check-diagnostics.ts +5 -3
  108. package/src/check-scan.ts +34 -3
  109. package/src/cli.ts +14 -5
  110. package/src/command-catalog.ts +126 -0
  111. package/src/doctor.ts +44 -1
  112. package/src/fix-recipes.ts +28 -0
  113. package/src/frontend-guidance.ts +20 -8
  114. package/src/introspect.ts +1 -1
  115. package/src/load.ts +13 -0
  116. package/src/mcp-exec.ts +74 -3
  117. package/src/mcp-http.ts +3 -2
  118. package/src/mcp-tool-meta.ts +268 -0
  119. package/src/mcp.ts +35 -99
  120. package/src/output-schemas.ts +28 -0
  121. package/src/ppr-read-fix.ts +426 -0
  122. package/src/recipes/5.6.0.ts +69 -0
  123. package/src/recipes/index.ts +2 -0
  124. package/src/review.ts +7 -2
  125. package/src/rules/codes.ts +9 -4
  126. package/src/rules/explanations.ts +39 -13
  127. package/src/rules/islands.ts +875 -3
  128. package/src/rules/ppr.ts +143 -0
  129. package/src/rules/swap.ts +402 -0
  130. package/src/scaffold-hole.ts +880 -0
  131. package/src/scaffold.ts +60 -49
  132. package/src/verification-plan.ts +20 -1
  133. package/src/web-app-options.ts +1 -0
  134. package/dist/rules/nano.d.ts +0 -6
  135. package/dist/rules/nano.d.ts.map +0 -1
  136. package/dist/rules/nano.js +0 -273
  137. package/dist/rules/nano.js.map +0 -1
  138. package/src/rules/nano.ts +0 -307
@@ -0,0 +1,880 @@
1
+ /**
2
+ * `nifra scaffold hole <route> <name>`: add a partially prerendered hole to a route whose backend half
3
+ * exports `shellLoader`. The page gets the hole's definition, its entry in `boundaries` and a `<Hole>`
4
+ * where its markup ends; the backend half gets the hole's loader and output schema. Every edit lands
5
+ * at a position the project's TypeScript parser found, and nothing is written unless every edit has
6
+ * one. A Vue or Svelte page gets the code to paste instead.
7
+ */
8
+ import { readFileSync } from "node:fs"
9
+ import { lstat, mkdir, readFile, writeFile } from "node:fs/promises"
10
+ import { dirname, relative, resolve, sep } from "node:path"
11
+ import type * as TS from "typescript"
12
+ import type { ProjectTypeScriptLoad } from "./internal/typescript-import.ts"
13
+ import { backendFileOf, type Framework, pageExtension, routePathToFile } from "./scaffold.ts"
14
+
15
+ export interface HoleScaffoldOptions {
16
+ /** The same for every visitor: built once and kept on its own `revalidate`. */
17
+ readonly shared?: boolean | undefined
18
+ /** Ships its props and hydrates as its own root. */
19
+ readonly interactive?: boolean | undefined
20
+ /** The hole's deadline in milliseconds, 1 to 30000. */
21
+ readonly timeout?: number | undefined
22
+ /** Shows a server component, which the coordinated compiler builds. */
23
+ readonly server?: boolean | undefined
24
+ }
25
+
26
+ export interface HoleScaffoldResult {
27
+ readonly ok: boolean
28
+ readonly page: string
29
+ readonly backend: string
30
+ /** Files written or created, relative to the app root. */
31
+ readonly changed: readonly string[]
32
+ /** Code to place by hand, for a page the scaffold does not edit. */
33
+ readonly snippets: readonly { readonly file: string; readonly code: string }[]
34
+ readonly next: readonly string[]
35
+ /** Without `write`: each file as the scaffold would leave it. */
36
+ readonly preview?: readonly { readonly file: string; readonly text: string }[]
37
+ readonly reason?: string
38
+ }
39
+
40
+ /** The hole name rule `@nifrajs/web` enforces: a name becomes a DOM id and a hashed script. */
41
+ export const HOLE_NAME = /^(?=[a-z0-9-]{1,32}$)[a-z](?:-?[a-z0-9])*$/
42
+ export const MAX_HOLES = 32
43
+ export const ADAPTER: Partial<Record<Framework, string>> = {
44
+ react: "@nifrajs/web-react/ppr",
45
+ preact: "@nifrajs/web-preact/ppr",
46
+ solid: "@nifrajs/web-solid/ppr",
47
+ }
48
+
49
+ export interface Edit {
50
+ readonly at: number
51
+ readonly text: string
52
+ /** Characters the edit replaces, from `at`. */
53
+ readonly remove?: number
54
+ }
55
+
56
+ /** `cart-count` → `cartCount`. */
57
+ const camel = (name: string): string =>
58
+ name.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase())
59
+ const pascal = (name: string): string => {
60
+ const value = camel(name)
61
+ return value.charAt(0).toUpperCase() + value.slice(1)
62
+ }
63
+ /** A property key or access for `name`: bare when it is an identifier, quoted when it has a hyphen. */
64
+ const keyOf = (name: string): string => (name.includes("-") ? JSON.stringify(name) : name)
65
+ const accessOf = (name: string): string =>
66
+ name.includes("-") ? `?.[${JSON.stringify(name)}]` : `?.${name}`
67
+
68
+ /** `edits` applied to `source`; edits at one position land in the order they are listed. */
69
+ export function apply(source: string, edits: readonly Edit[]): string {
70
+ let out = source
71
+ const order = edits.map((edit, index) => ({ edit, index }))
72
+ for (const { edit } of order.sort((a, b) => b.edit.at - a.edit.at || b.index - a.index)) {
73
+ out = out.slice(0, edit.at) + edit.text + out.slice(edit.at + (edit.remove ?? 0))
74
+ }
75
+ return out
76
+ }
77
+
78
+ /** Leading whitespace of the line `pos` is on. */
79
+ export function indentAt(source: string, pos: number): string {
80
+ const start = source.lastIndexOf("\n", pos - 1) + 1
81
+ return /^[ \t]*/.exec(source.slice(start))?.[0] ?? ""
82
+ }
83
+
84
+ /** Whether only whitespace sits between the start of `pos`'s line and `pos`. */
85
+ function ownLine(source: string, pos: number): boolean {
86
+ const start = source.lastIndexOf("\n", pos - 1) + 1
87
+ return source.slice(start, pos).trim() === ""
88
+ }
89
+
90
+ /** Read from `node.modifiers`: TypeScript 7's API has no `getModifiers`. */
91
+ const hasModifier = (
92
+ node: TS.VariableStatement | TS.FunctionDeclaration,
93
+ kind: TS.SyntaxKind,
94
+ ): boolean => node.modifiers?.some((modifier) => modifier.kind === kind) === true
95
+ const hasExport = (ts: typeof TS, node: TS.VariableStatement | TS.FunctionDeclaration): boolean =>
96
+ hasModifier(node, ts.SyntaxKind.ExportKeyword)
97
+
98
+ /** An exported `const <name> = <initializer>`, its initializer without `as`, `satisfies` or parens. */
99
+ function exportedConst(
100
+ ts: typeof TS,
101
+ sf: TS.SourceFile,
102
+ name: string,
103
+ ):
104
+ | { readonly statement: TS.VariableStatement; readonly value: TS.Expression | undefined }
105
+ | undefined {
106
+ for (const statement of sf.statements) {
107
+ if (!ts.isVariableStatement(statement) || !hasExport(ts, statement)) continue
108
+ for (const declaration of statement.declarationList.declarations) {
109
+ if (!ts.isIdentifier(declaration.name) || declaration.name.text !== name) continue
110
+ let value = declaration.initializer
111
+ while (
112
+ value !== undefined &&
113
+ (ts.isAsExpression(value) ||
114
+ ts.isSatisfiesExpression(value) ||
115
+ ts.isParenthesizedExpression(value))
116
+ )
117
+ value = value.expression
118
+ return { statement, value }
119
+ }
120
+ }
121
+ return undefined
122
+ }
123
+
124
+ function exportsName(ts: typeof TS, sf: TS.SourceFile, name: string): boolean {
125
+ return (
126
+ exportedConst(ts, sf, name) !== undefined ||
127
+ sf.statements.some(
128
+ (statement) =>
129
+ ts.isFunctionDeclaration(statement) &&
130
+ hasExport(ts, statement) &&
131
+ statement.name?.text === name,
132
+ )
133
+ )
134
+ }
135
+
136
+ const propertyName = (ts: typeof TS, name: TS.PropertyName): string | undefined =>
137
+ ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)
138
+ ? name.text
139
+ : undefined
140
+
141
+ /** Every name a module's top level binds, so a new one cannot shadow or clash. */
142
+ export function topLevelNames(ts: typeof TS, sf: TS.SourceFile): Set<string> {
143
+ const names = new Set<string>()
144
+ const bind = (name: TS.BindingName): void => {
145
+ if (ts.isIdentifier(name)) names.add(name.text)
146
+ else
147
+ for (const element of name.elements) if (!ts.isOmittedExpression(element)) bind(element.name)
148
+ }
149
+ for (const statement of sf.statements) {
150
+ if (ts.isVariableStatement(statement))
151
+ for (const declaration of statement.declarationList.declarations) bind(declaration.name)
152
+ else if (
153
+ (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) &&
154
+ statement.name !== undefined
155
+ )
156
+ names.add(statement.name.text)
157
+ else if (ts.isImportDeclaration(statement) && statement.importClause !== undefined) {
158
+ const clause = statement.importClause
159
+ if (clause.name !== undefined) names.add(clause.name.text)
160
+ const bindings = clause.namedBindings
161
+ if (bindings !== undefined && ts.isNamespaceImport(bindings)) names.add(bindings.name.text)
162
+ if (bindings !== undefined && ts.isNamedImports(bindings))
163
+ for (const element of bindings.elements) names.add(element.name.text)
164
+ }
165
+ }
166
+ return names
167
+ }
168
+
169
+ /** A named import a planned edit needs: `name` is the local binding, `imported` the export's name. */
170
+ export interface ImportNeed {
171
+ readonly module: string
172
+ readonly name: string
173
+ readonly imported?: string
174
+ readonly typeOnly?: boolean
175
+ }
176
+
177
+ /** The edit that makes `need` importable, or none when it already is. */
178
+ function ensureImport(ts: typeof TS, sf: TS.SourceFile, need: ImportNeed): Edit | undefined {
179
+ const { module, name } = need
180
+ const typeOnly = need.typeOnly === true
181
+ const named =
182
+ need.imported === undefined || need.imported === name ? name : `${need.imported} as ${name}`
183
+ let last: TS.ImportDeclaration | undefined
184
+ for (const statement of sf.statements) {
185
+ if (!ts.isImportDeclaration(statement)) continue
186
+ last = statement
187
+ if (!ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== module)
188
+ continue
189
+ const clause = statement.importClause
190
+ const bindings = clause?.namedBindings
191
+ if (clause === undefined || bindings === undefined || !ts.isNamedImports(bindings)) continue
192
+ if (bindings.elements.some((element) => element.name.text === name)) return undefined
193
+ // A type-only declaration takes a type name as it is; a value one needs `type` on it.
194
+ if (!typeOnly && clause.isTypeOnly) continue
195
+ const specifier = typeOnly && !clause.isTypeOnly ? `type ${named}` : named
196
+ const lastElement = bindings.elements.at(-1)
197
+ return lastElement === undefined
198
+ ? { at: bindings.getEnd() - 1, text: specifier }
199
+ : { at: lastElement.getEnd(), text: `, ${specifier}` }
200
+ }
201
+ const line = `import ${typeOnly ? "type " : ""}{ ${named} } from ${JSON.stringify(module)}\n`
202
+ return last === undefined
203
+ ? { at: 0, text: line }
204
+ : { at: last.getEnd(), text: `\n${line.trimEnd()}` }
205
+ }
206
+
207
+ interface Plan {
208
+ readonly edits: Edit[]
209
+ reason?: string
210
+ }
211
+
212
+ /** A hole's loader: the lines inside its `boundaryLoaders` entry, and the imports they use. */
213
+ export interface LoaderEntry {
214
+ readonly body: readonly string[]
215
+ readonly imports: readonly ImportNeed[]
216
+ }
217
+
218
+ /** The TODO loader the scaffold writes. */
219
+ function scaffoldLoader(options: HoleScaffoldOptions): LoaderEntry {
220
+ const context = options.shared === true ? "SharedHoleCtx" : "BoundaryRequestCtx"
221
+ const load =
222
+ options.server === true
223
+ ? `load: ({ params }: ${context}) => ({ id: params.id ?? "" }),\noutput: t.object({ id: t.string() }),`
224
+ : `load: (_ctx: ${context}) => ({ text: "TODO" }),\noutput: t.object({ text: t.string() }),`
225
+ const comment =
226
+ options.server === true
227
+ ? "// Returns the server component's input, which reaches the browser in its record."
228
+ : options.shared === true
229
+ ? "// The same for every visitor: no request; built once and kept for `revalidate` seconds."
230
+ : "// Runs for each visitor, under the hole's own deadline."
231
+ return {
232
+ body: [comment, ...load.split("\n"), ...(options.shared === true ? ["revalidate: 60,"] : [])],
233
+ imports: [
234
+ { module: "@nifrajs/schema", name: "t" },
235
+ { module: "@nifrajs/web", name: context, typeOnly: true },
236
+ ],
237
+ }
238
+ }
239
+
240
+ /** The backend half's edits: hole `name`'s loader entry, and the imports it uses. */
241
+ export function backendPlan(
242
+ ts: typeof TS,
243
+ sf: TS.SourceFile,
244
+ name: string,
245
+ loader: LoaderEntry,
246
+ ): Plan & { readonly keys: readonly string[] } {
247
+ const source = sf.text
248
+ const edits: Edit[] = []
249
+ const entry = (indent: string): string =>
250
+ [
251
+ `${indent}${keyOf(name)}: {`,
252
+ ...loader.body.map((line) => `${indent} ${line}`),
253
+ `${indent}},`,
254
+ ].join("\n")
255
+
256
+ const loaders = exportedConst(ts, sf, "boundaryLoaders")
257
+ let keys: string[] = []
258
+ if (loaders === undefined) {
259
+ const satisfies = /import\s+type\s*\{[^}]*\bRoute\b[^}]*\}\s*from\s*["']\.\/\+types\//.test(
260
+ source,
261
+ )
262
+ ? " satisfies Route.BoundaryLoaders"
263
+ : ""
264
+ edits.push({
265
+ at: source.trimEnd().length,
266
+ text: `\n\nexport const boundaryLoaders = {\n${entry(" ")}\n}${satisfies}`,
267
+ })
268
+ } else {
269
+ const object = loaders.value
270
+ if (object === undefined || !ts.isObjectLiteralExpression(object))
271
+ return { edits, keys, reason: "`boundaryLoaders` is not an object literal" }
272
+ keys = object.properties.flatMap((property) => {
273
+ const key = property.name === undefined ? undefined : propertyName(ts, property.name)
274
+ return key === undefined ? [] : [key]
275
+ })
276
+ const close = object.getEnd() - 1
277
+ const lastProperty = object.properties.at(-1)
278
+ if (lastProperty === undefined) {
279
+ edits.push({
280
+ at: object.getStart(sf),
281
+ remove: object.getWidth(sf),
282
+ text: `{\n${entry(" ")}\n}`,
283
+ })
284
+ } else if (ownLine(source, close)) {
285
+ const indent = indentAt(source, lastProperty.getStart(sf))
286
+ if (!object.properties.hasTrailingComma) edits.push({ at: lastProperty.getEnd(), text: "," })
287
+ const lineStart = source.lastIndexOf("\n", close - 1) + 1
288
+ edits.push({ at: lineStart, text: `${entry(indent)}\n` })
289
+ } else {
290
+ return {
291
+ edits,
292
+ keys,
293
+ reason: "`boundaryLoaders` is written on one line; spread it over lines first",
294
+ }
295
+ }
296
+ }
297
+ for (const need of loader.imports) {
298
+ const edit = ensureImport(ts, sf, need)
299
+ if (edit !== undefined) edits.push(edit)
300
+ }
301
+ return { edits, keys }
302
+ }
303
+
304
+ /** The component a page module exports as default, as a function node. */
305
+ export function defaultComponent(
306
+ ts: typeof TS,
307
+ sf: TS.SourceFile,
308
+ ): TS.FunctionDeclaration | TS.ArrowFunction | TS.FunctionExpression | undefined {
309
+ const local = (
310
+ name: string,
311
+ ): TS.FunctionDeclaration | TS.ArrowFunction | TS.FunctionExpression | undefined => {
312
+ for (const statement of sf.statements) {
313
+ if (ts.isFunctionDeclaration(statement) && statement.name?.text === name) return statement
314
+ if (!ts.isVariableStatement(statement)) continue
315
+ for (const declaration of statement.declarationList.declarations) {
316
+ const value = declaration.initializer
317
+ if (
318
+ ts.isIdentifier(declaration.name) &&
319
+ declaration.name.text === name &&
320
+ value !== undefined &&
321
+ (ts.isArrowFunction(value) || ts.isFunctionExpression(value))
322
+ )
323
+ return value
324
+ }
325
+ }
326
+ return undefined
327
+ }
328
+ for (const statement of sf.statements) {
329
+ if (ts.isFunctionDeclaration(statement) && hasModifier(statement, ts.SyntaxKind.DefaultKeyword))
330
+ return statement
331
+ if (ts.isExportAssignment(statement) && !statement.isExportEquals) {
332
+ const value = statement.expression
333
+ if (ts.isArrowFunction(value) || ts.isFunctionExpression(value)) return value
334
+ if (ts.isIdentifier(value)) return local(value.text)
335
+ }
336
+ }
337
+ return undefined
338
+ }
339
+
340
+ /** The JSX a component returns: its one top-level `return`, or an arrow's expression body. */
341
+ export function returnedJsx(
342
+ ts: typeof TS,
343
+ component: TS.FunctionDeclaration | TS.ArrowFunction | TS.FunctionExpression,
344
+ ): TS.JsxElement | TS.JsxFragment | undefined {
345
+ let value: TS.Expression | undefined
346
+ const body = component.body
347
+ if (body === undefined) return undefined
348
+ if (ts.isBlock(body)) {
349
+ const returns = body.statements.filter(ts.isReturnStatement)
350
+ if (returns.length !== 1) return undefined
351
+ value = returns[0]?.expression
352
+ } else value = body
353
+ while (value !== undefined && ts.isParenthesizedExpression(value)) value = value.expression
354
+ return value !== undefined && (ts.isJsxElement(value) || ts.isJsxFragment(value))
355
+ ? value
356
+ : undefined
357
+ }
358
+
359
+ /** Every name a function binds, in its parameters and anywhere in its body. */
360
+ export function localNames(ts: typeof TS, fn: TS.Node, into: Set<string>): void {
361
+ const visit = (node: TS.Node): void => {
362
+ if (
363
+ (ts.isVariableDeclaration(node) ||
364
+ ts.isParameter(node) ||
365
+ ts.isBindingElement(node) ||
366
+ ts.isFunctionDeclaration(node) ||
367
+ ts.isClassDeclaration(node)) &&
368
+ node.name !== undefined &&
369
+ ts.isIdentifier(node.name)
370
+ )
371
+ into.add(node.name.text)
372
+ ts.forEachChild(node, visit)
373
+ }
374
+ visit(fn)
375
+ }
376
+
377
+ /** A hole's definition in the page: its fields after `name`, and the imports they use. */
378
+ export interface HoleDefinition {
379
+ readonly fields: readonly string[]
380
+ readonly imports: readonly ImportNeed[]
381
+ /** The JSX the `<Hole>` takes the place of; without it, the hole goes where the markup ends. */
382
+ readonly replaces?: TS.Node
383
+ }
384
+
385
+ /** A placeholder fallback: without one, a browser without JavaScript shows nothing in the hole. */
386
+ export const fallbackField = (framework: Framework): string =>
387
+ // Solid: a function, since JSX evaluated at import would be one DOM node every page shares.
388
+ framework === "solid" ? "fallback: () => <p>Loading</p>," : "fallback: <p>Loading</p>,"
389
+
390
+ /** The definition the scaffold writes: a TODO render, or the server component's. */
391
+ function scaffoldDefinition(
392
+ framework: Framework,
393
+ options: HoleScaffoldOptions,
394
+ component: { readonly name: string; readonly specifier: string } | undefined,
395
+ ): HoleDefinition {
396
+ return {
397
+ fields: [
398
+ `mode: "${options.shared === true ? "shared" : "dynamic"}",`,
399
+ ...(options.interactive === true
400
+ ? ["interactive: true, // ships its props and hydrates as its own root"]
401
+ : []),
402
+ ...(options.timeout === undefined ? [] : [`timeout: ${options.timeout},`]),
403
+ component === undefined
404
+ ? "render: (data: { readonly text: string }) => <p>{data.text}</p>,"
405
+ : `render: serverHole(${component.name}),`,
406
+ fallbackField(framework),
407
+ ],
408
+ imports:
409
+ component === undefined
410
+ ? []
411
+ : [
412
+ { module: "@nifrajs/web/server-components/hole", name: "serverHole" },
413
+ { module: component.specifier, name: component.name },
414
+ ],
415
+ }
416
+ }
417
+
418
+ /** The page's edits, for a JSX-family page: the definition, `boundaries`, imports and the `<Hole>`. */
419
+ export function pagePlan(
420
+ ts: typeof TS,
421
+ sf: TS.SourceFile,
422
+ name: string,
423
+ framework: Framework,
424
+ definition: HoleDefinition,
425
+ ): Plan & { readonly names: readonly string[]; readonly ident: string } {
426
+ const source = sf.text
427
+ const edits: Edit[] = []
428
+ // Listed first: the definition can land where the imports end, and goes below them.
429
+ const imports: Edit[] = []
430
+ const taken = topLevelNames(ts, sf)
431
+ let ident = camel(name)
432
+ const none: readonly string[] = []
433
+ const refuse = (reason: string) => ({ edits, names: none, ident, reason })
434
+
435
+ const boundaries = exportedConst(ts, sf, "boundaries")
436
+ const names: string[] = []
437
+ if (boundaries !== undefined) {
438
+ const list = boundaries.value
439
+ if (list === undefined || !ts.isArrayLiteralExpression(list))
440
+ return refuse("`boundaries` is not an array literal")
441
+ for (const element of list.elements) {
442
+ // A boundary written inline, or declared in this module, names itself in its `name` field.
443
+ let value: TS.Expression | undefined = element
444
+ if (ts.isIdentifier(element)) {
445
+ value = undefined
446
+ for (const statement of sf.statements)
447
+ if (ts.isVariableStatement(statement))
448
+ for (const declaration of statement.declarationList.declarations)
449
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === element.text)
450
+ value = declaration.initializer
451
+ }
452
+ while (value !== undefined && (ts.isAsExpression(value) || ts.isSatisfiesExpression(value)))
453
+ value = value.expression
454
+ if (value === undefined || !ts.isObjectLiteralExpression(value)) continue
455
+ for (const property of value.properties)
456
+ if (
457
+ ts.isPropertyAssignment(property) &&
458
+ propertyName(ts, property.name) === "name" &&
459
+ ts.isStringLiteralLike(property.initializer)
460
+ )
461
+ names.push(property.initializer.text)
462
+ }
463
+ if (list.elements.length >= MAX_HOLES)
464
+ return refuse(
465
+ `the page already declares ${list.elements.length} boundaries, the most a route may have`,
466
+ )
467
+ }
468
+
469
+ const page = defaultComponent(ts, sf)
470
+ if (page === undefined) return refuse("the page has no default-exported component")
471
+ const jsx = returnedJsx(ts, page)
472
+ if (jsx === undefined)
473
+ return refuse("the page component does not return one JSX element the hole can go inside")
474
+ // The definition is a module name the component reads, so a name of the component's own shadows it.
475
+ localNames(ts, page, taken)
476
+ if (taken.has(ident)) ident = `${ident}Hole`
477
+ if (taken.has(ident)) return refuse(`\`${ident}\` is already declared in the page`)
478
+
479
+ // How the component reads its boundary states.
480
+ const param = page.parameters[0]
481
+ if (param === undefined) return refuse("the page component takes no props")
482
+ let states: string
483
+ if (ts.isIdentifier(param.name)) states = `${param.name.text}.boundaries`
484
+ else if (ts.isObjectBindingPattern(param.name)) {
485
+ const bound = param.name.elements.find(
486
+ (element) =>
487
+ (element.propertyName === undefined
488
+ ? ts.isIdentifier(element.name) && element.name.text
489
+ : propertyName(ts, element.propertyName)) === "boundaries",
490
+ )
491
+ if (bound !== undefined && !ts.isIdentifier(bound.name))
492
+ return refuse("the page destructures `boundaries` further")
493
+ if (bound !== undefined && ts.isIdentifier(bound.name)) states = bound.name.text
494
+ else {
495
+ states = taken.has("boundaries") ? "" : "boundaries"
496
+ if (states === "") return refuse("`boundaries` is already a name in the page")
497
+ if (param.name.elements.some((element) => element.dotDotDotToken !== undefined))
498
+ return refuse("the page's props end in a rest element")
499
+ const lastElement = param.name.elements.at(-1)
500
+ edits.push(
501
+ lastElement === undefined
502
+ ? { at: param.name.getStart(sf) + 1, text: " boundaries " }
503
+ : { at: lastElement.getEnd(), text: ", boundaries" },
504
+ )
505
+ }
506
+ } else return refuse("the page component's props are not a name or an object pattern")
507
+ const type = param.type
508
+ if (type !== undefined && ts.isTypeLiteralNode(type)) {
509
+ const has = type.members.some(
510
+ (member) => member.name !== undefined && propertyName(ts, member.name) === "boundaries",
511
+ )
512
+ if (!has) {
513
+ const lastMember = type.members.at(-1)
514
+ const member = "readonly boundaries?: BoundaryStates"
515
+ if (lastMember === undefined) edits.push({ at: type.getStart(sf) + 1, text: ` ${member} ` })
516
+ else if (ownLine(source, type.getEnd() - 1)) {
517
+ const lineStart = source.lastIndexOf("\n", type.getEnd() - 2) + 1
518
+ edits.push({
519
+ at: lineStart,
520
+ text: `${indentAt(source, lastMember.getStart(sf))}${member}\n`,
521
+ })
522
+ } else {
523
+ const ends = source.slice(lastMember.getStart(sf), lastMember.getEnd()).trimEnd()
524
+ edits.push({
525
+ at: lastMember.getEnd(),
526
+ text: ends.endsWith(";") || ends.endsWith(",") ? ` ${member}` : `; ${member}`,
527
+ })
528
+ }
529
+ const typeImport = ensureImport(ts, sf, {
530
+ module: "@nifrajs/web",
531
+ name: "BoundaryStates",
532
+ typeOnly: true,
533
+ })
534
+ if (typeImport !== undefined) imports.push(typeImport)
535
+ }
536
+ }
537
+
538
+ const hole = `<Hole of={${ident}} state={${states}${accessOf(name)}} />`
539
+ const replaces = definition.replaces
540
+ if (replaces !== undefined) {
541
+ const at = replaces.getStart(sf)
542
+ edits.push({ at, remove: replaces.getEnd() - at, text: hole })
543
+ } else {
544
+ const closing = ts.isJsxElement(jsx) ? jsx.closingElement : jsx.closingFragment
545
+ const at = closing.getStart(sf)
546
+ edits.push({
547
+ at,
548
+ text: ownLine(source, at) ? ` ${hole}\n${indentAt(source, at)}` : hole,
549
+ })
550
+ }
551
+
552
+ const lines = [`name: ${JSON.stringify(name)},`, ...definition.fields].flatMap((field) =>
553
+ field.split("\n"),
554
+ )
555
+ const text = `const ${ident} = {\n${lines.map((line) => (line === "" ? "" : ` ${line}`)).join("\n")}\n} as const`
556
+ if (boundaries !== undefined) {
557
+ const list = boundaries.value
558
+ if (list === undefined || !ts.isArrayLiteralExpression(list))
559
+ return refuse("`boundaries` is not an array literal")
560
+ const lastElement = list.elements.at(-1)
561
+ edits.push(
562
+ lastElement === undefined
563
+ ? { at: list.getStart(sf) + 1, text: ident }
564
+ : { at: lastElement.getEnd(), text: `, ${ident}` },
565
+ )
566
+ edits.push({ at: boundaries.statement.getFullStart(), text: `\n\n${text}` })
567
+ } else {
568
+ const anchor = sf.statements.find(
569
+ (statement) =>
570
+ (ts.isFunctionDeclaration(statement) &&
571
+ hasModifier(statement, ts.SyntaxKind.DefaultKeyword)) ||
572
+ ts.isExportAssignment(statement),
573
+ )
574
+ if (anchor === undefined)
575
+ return refuse("the page has no default export to place the hole above")
576
+ edits.push({
577
+ at: anchor.getFullStart(),
578
+ text: `\n\n${text}\nexport const boundaries = [${ident}]`,
579
+ })
580
+ }
581
+ for (const need of [{ module: ADAPTER[framework] ?? "", name: "Hole" }, ...definition.imports]) {
582
+ const edit = ensureImport(ts, sf, need)
583
+ if (edit !== undefined) imports.push(edit)
584
+ }
585
+ return { edits: [...imports, ...edits], names, ident }
586
+ }
587
+
588
+ /** The server component a `--server` hole shows: its React view renders on the server only. */
589
+ function componentStub(name: string): string {
590
+ return `import { t } from "@nifrajs/schema"
591
+ import { defineServerComponent } from "@nifrajs/web/server-components"
592
+
593
+ /** Rendered on the server for each visitor; the browser gets its HTML, never this file. */
594
+ export const ${name} = defineServerComponent({
595
+ input: t.object({ id: t.string() }),
596
+ props: t.object({ title: t.string() }),
597
+ // Refuse a visitor who may not see it: throw a Response such as 403.
598
+ authorize() {},
599
+ load: (_ctx, input) => ({ title: \`TODO: \${input.id}\` }),
600
+ view: ({ props }) => <section>{props.title}</section>,
601
+ })
602
+ `
603
+ }
604
+
605
+ function snippetFor(
606
+ framework: Framework,
607
+ name: string,
608
+ ident: string,
609
+ options: HoleScaffoldOptions,
610
+ ): string {
611
+ const fields = [
612
+ `name: ${JSON.stringify(name)},`,
613
+ `mode: "${options.shared === true ? "shared" : "dynamic"}",`,
614
+ ...(options.interactive === true ? ["interactive: true,"] : []),
615
+ ...(options.timeout === undefined ? [] : [`timeout: ${options.timeout},`]),
616
+ ]
617
+ if (framework === "vue")
618
+ return `<script lang="ts">
619
+ // Beside the page's other imports; a hole renders h() output.
620
+ import { Hole } from "@nifrajs/web-vue/ppr"
621
+ import { h } from "vue"
622
+
623
+ const ${ident} = {
624
+ ${fields.map((line) => ` ${line}`).join("\n")}
625
+ render: (data: { readonly text: string }) => h("p", data.text),
626
+ fallback: h("p", "Loading"),
627
+ } as const
628
+ export const boundaries = [${ident}] // with any boundaries the page already has
629
+ </script>
630
+
631
+ <!-- In the template, where the hole renders (props from defineProps(["data", "boundaries"])): -->
632
+ <Hole :of="${ident}" :state="props.boundaries${accessOf(name)}" />`
633
+ return `<script module>
634
+ // Beside the page's other imports; Text is any component that renders the data.
635
+ import Hole from "@nifrajs/web-svelte/hole"
636
+ import { ui } from "@nifrajs/web-svelte/ppr"
637
+ import Text from "../../frontend/Text.svelte"
638
+
639
+ const ${ident} = {
640
+ ${fields.map((line) => ` ${line}`).join("\n")}
641
+ render: (data) => ui(Text, { text: data.text }),
642
+ }
643
+ export const boundaries = [${ident}] // with any boundaries the page already has
644
+ </script>
645
+
646
+ <!-- In the markup, where the hole renders (states from let { boundaries: states } = $props()): -->
647
+ <Hole of={${ident}} state={states${accessOf(name)}} />`
648
+ }
649
+
650
+ /** `routes/tea/[id].tsx` → `tea/[id]`, the id `createServerComponents({ holes })` keys by. */
651
+ const routeIdOf = (page: string): string => page.replace(/^routes\//, "").replace(/\.[^./]+$/, "")
652
+
653
+ async function exists(path: string): Promise<boolean> {
654
+ return (await lstat(path).catch(() => undefined)) !== undefined
655
+ }
656
+
657
+ export function insideRoot(root: string, file: string): string {
658
+ const base = resolve(root)
659
+ const target = resolve(base, file)
660
+ if (!target.startsWith(`${base}${sep}`))
661
+ throw new Error(`refusing to write outside the app: ${file}`)
662
+ return target
663
+ }
664
+
665
+ /** The page and backend half `route` names: a URL path such as `/tea/:id`, or the page file. */
666
+ export function holeRouteFiles(
667
+ route: string,
668
+ framework: Framework,
669
+ ): { readonly page: string; readonly backend: string } {
670
+ const page = /\.(tsx|jsx|vue|svelte)$/.test(route)
671
+ ? route.startsWith("routes/")
672
+ ? route
673
+ : `routes/${route.replace(/^\/+/, "")}`
674
+ : routePathToFile(route, pageExtension(framework))
675
+ return { page, backend: backendFileOf(page) }
676
+ }
677
+
678
+ /** The project's TypeScript with `files` opened: TypeScript 7 parses only the files its session has. */
679
+ export async function routeTypeScript(
680
+ root: string,
681
+ files: readonly string[],
682
+ ): Promise<ProjectTypeScriptLoad> {
683
+ const { loadProjectTypeScript } = await import("./internal/typescript-import.ts")
684
+ const base = resolve(root)
685
+ return loadProjectTypeScript(root, undefined, {
686
+ files,
687
+ read: (file) => {
688
+ const path = resolve(base, file)
689
+ if (!path.startsWith(`${base}${sep}`)) return undefined
690
+ try {
691
+ return readFileSync(path, "utf8")
692
+ } catch {
693
+ return undefined
694
+ }
695
+ },
696
+ })
697
+ }
698
+
699
+ /**
700
+ * Add hole `name` to the route at `route` (a URL path such as `/tea/:id`, or its page file). Nothing is
701
+ * written when `write` is false, or when any edit cannot be placed.
702
+ */
703
+ export async function scaffoldHole(
704
+ root: string,
705
+ route: string,
706
+ name: string,
707
+ framework: Framework,
708
+ options: HoleScaffoldOptions,
709
+ ts: typeof TS,
710
+ write = true,
711
+ ): Promise<HoleScaffoldResult> {
712
+ const { page, backend } = holeRouteFiles(route, framework)
713
+ const result = (
714
+ fields: Partial<HoleScaffoldResult> & { readonly ok: boolean },
715
+ ): HoleScaffoldResult => ({
716
+ page,
717
+ backend,
718
+ changed: [],
719
+ snippets: [],
720
+ next: [],
721
+ ...fields,
722
+ })
723
+ const refuse = (reason: string) => result({ ok: false, reason })
724
+
725
+ if (!HOLE_NAME.test(name))
726
+ return refuse(
727
+ `"${name}" is not a hole name: 1 to 32 lowercase letters, digits and single hyphens, starting with a letter`,
728
+ )
729
+ if (framework === "vanilla")
730
+ return refuse("partial prerendering needs a framework adapter's Hole; a vanilla page has none")
731
+ if (
732
+ options.timeout !== undefined &&
733
+ !(Number.isInteger(options.timeout) && options.timeout >= 1 && options.timeout <= 30000)
734
+ )
735
+ return refuse("--timeout is a whole number of milliseconds from 1 to 30000")
736
+ if (options.server === true && (options.shared === true || options.interactive === true))
737
+ return refuse("a hole that shows a server component is dynamic and not interactive")
738
+ // Another adapter's server view is a native component in a file of its own, which the scaffold
739
+ // cannot write for it.
740
+ if (options.server === true && framework !== "react")
741
+ return refuse(
742
+ "--server writes a React server component; for this adapter, define the component with nativeServerView first (see the server components docs), then render it with serverHole(Component)",
743
+ )
744
+
745
+ const backendPath = insideRoot(root, backend)
746
+ const pagePath = insideRoot(root, page)
747
+ if (!(await exists(pagePath))) return refuse(`no page at ${page}`)
748
+ if (!(await exists(backendPath)))
749
+ return refuse(
750
+ `${page} is not partially prerendered: it has no backend half. Add ${backend} with \`export const shellLoader\` and \`shellOutput\` first (see the partial prerendering docs)`,
751
+ )
752
+ const backendSource = await readFile(backendPath, "utf8")
753
+ const backendFile = ts.createSourceFile(
754
+ backend,
755
+ backendSource,
756
+ ts.ScriptTarget.Latest,
757
+ true,
758
+ ts.ScriptKind.TS,
759
+ )
760
+ if (!exportsName(ts, backendFile, "shellLoader"))
761
+ return refuse(
762
+ `${page} is not partially prerendered: ${backend} exports no \`shellLoader\`. Add it, with \`shellOutput\`, first (see the partial prerendering docs)`,
763
+ )
764
+ const back = backendPlan(ts, backendFile, name, scaffoldLoader(options))
765
+ if (back.reason !== undefined) return refuse(`${backend}: ${back.reason}`)
766
+ if (back.keys.includes(name)) return refuse(`${backend} already has a loader for "${name}"`)
767
+ if (back.keys.length >= MAX_HOLES)
768
+ return refuse(
769
+ `${backend} already has ${back.keys.length} hole loaders, the most a route may have`,
770
+ )
771
+
772
+ const component =
773
+ options.server === true
774
+ ? {
775
+ name: pascal(name),
776
+ file: `components/${pascal(name)}.component.server.tsx`,
777
+ }
778
+ : undefined
779
+ const specifier =
780
+ component === undefined
781
+ ? undefined
782
+ : (() => {
783
+ const rel = relative(dirname(pagePath), resolve(root, component.file))
784
+ .split(sep)
785
+ .join("/")
786
+ return rel.startsWith(".") ? rel : `./${rel}`
787
+ })()
788
+
789
+ const snippets: { file: string; code: string }[] = []
790
+ const writes: { file: string; path: string; text: string; create?: true }[] = []
791
+ if (ADAPTER[framework] !== undefined) {
792
+ const pageSource = await readFile(pagePath, "utf8")
793
+ const pageFile = ts.createSourceFile(
794
+ page,
795
+ pageSource,
796
+ ts.ScriptTarget.Latest,
797
+ true,
798
+ ts.ScriptKind.TSX,
799
+ )
800
+ const front = pagePlan(
801
+ ts,
802
+ pageFile,
803
+ name,
804
+ framework,
805
+ scaffoldDefinition(
806
+ framework,
807
+ options,
808
+ component === undefined || specifier === undefined
809
+ ? undefined
810
+ : { name: component.name, specifier },
811
+ ),
812
+ )
813
+ if (front.reason !== undefined) return refuse(`${page}: ${front.reason}`)
814
+ if (front.names.includes(name))
815
+ return refuse(`${page} already declares a boundary named "${name}"`)
816
+ writes.push({ file: page, path: pagePath, text: apply(pageSource, front.edits) })
817
+ } else {
818
+ snippets.push({ file: page, code: snippetFor(framework, name, camel(name), options) })
819
+ }
820
+ writes.push({ file: backend, path: backendPath, text: apply(backendSource, back.edits) })
821
+ if (component !== undefined) {
822
+ const path = insideRoot(root, component.file)
823
+ if (await exists(path)) return refuse(`${component.file} already exists`)
824
+ writes.push({ file: component.file, path, text: componentStub(component.name), create: true })
825
+ }
826
+
827
+ const next: string[] = []
828
+ if (component !== undefined) {
829
+ next.push(
830
+ `List ${component.name} for this route in the server entry: createServerComponents({ holes: { ${JSON.stringify(routeIdOf(page))}: { components: [${component.name}] } } }).`,
831
+ "Call holeComponents() with the adapter's component client in the client entry, before the router mounts.",
832
+ "Build with the coordinated compiler (buildServerComponents).",
833
+ )
834
+ }
835
+ if (snippets.length > 0) next.push(`Place the hole in ${page} from the snippet.`)
836
+ next.push(
837
+ `Replace the TODO loader in ${backend}, and its output schema with what the hole renders.`,
838
+ )
839
+
840
+ if (!write)
841
+ return result({
842
+ ok: true,
843
+ snippets,
844
+ next,
845
+ preview: writes.map((entry) => ({ file: entry.file, text: entry.text })),
846
+ })
847
+ for (const entry of writes) {
848
+ if (entry.create === true) {
849
+ await mkdir(dirname(entry.path), { recursive: true })
850
+ await writeFile(entry.path, entry.text, { flag: "wx" })
851
+ } else await writeFile(entry.path, entry.text, "utf8")
852
+ }
853
+ // The page's `./+types` module now names the new hole, so `Route.BoundaryLoaders` checks its key.
854
+ const { refreshRouteTypes } = await import("./route-types.ts")
855
+ refreshRouteTypes(root, () => {})
856
+ return result({ ok: true, changed: writes.map((entry) => entry.file), snippets, next })
857
+ }
858
+
859
+ /** The MCP tool's answer: what was written or would be, and what is left. */
860
+ export function renderHoleScaffold(
861
+ name: string,
862
+ framework: Framework,
863
+ out: HoleScaffoldResult,
864
+ ): string {
865
+ const head = `# Scaffold hole \`${name}\` on \`${out.page}\` (${framework})`
866
+ if (!out.ok) return `${head}\n\nNot scaffolded: ${out.reason ?? "unknown reason"}`
867
+ const status =
868
+ out.preview === undefined
869
+ ? `**Written:** ${out.changed.map((file) => `\`${file}\``).join(", ")}`
870
+ : "**Dry run:** pass `write: true` to apply these files."
871
+ const previews = (out.preview ?? []).map(
872
+ (entry) => `\n\n\`${entry.file}\`:\n\n\`\`\`tsx\n${entry.text}\`\`\``,
873
+ )
874
+ const snippets = out.snippets.map(
875
+ (snippet) =>
876
+ `\n\nPaste into \`${snippet.file}\`:\n\n\`\`\`${framework}\n${snippet.code}\n\`\`\``,
877
+ )
878
+ const next = out.next.map((step) => `- ${step}`).join("\n")
879
+ return `${head}\n\n${status}${previews.join("")}${snippets.join("")}\n\n**Next:**\n${next}`
880
+ }