@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
@@ -496,6 +496,8 @@ interface ProbeRoute {
496
496
  readonly file: string
497
497
  readonly fns: readonly RouteFn[]
498
498
  readonly schemas: readonly OutputExport[]
499
+ /** Holes whose `boundaryLoaders` entry's `load` return type to read. */
500
+ readonly holes?: readonly string[]
499
501
  }
500
502
 
501
503
  /** Shapes keyed `<file>#<export>`: a route function's return type, or a schema's output type. */
@@ -532,6 +534,13 @@ function probeSource(routes: readonly ProbeRoute[]): {
532
534
  names.set(name, `${route.file}#${schema}`)
533
535
  lines.push(`declare const ${name}: __NifraDeclared<typeof __nifra_m${i}, "${schema}">`)
534
536
  }
537
+ route.holes?.forEach((hole, j) => {
538
+ const name = `__nifra_h${i}_${j}`
539
+ names.set(name, `${route.file}#boundaryLoaders.${hole}`)
540
+ lines.push(
541
+ `declare const ${name}: __NifraReturned<(typeof __nifra_m${i})["boundaryLoaders"][${JSON.stringify(hole)}], "load">`,
542
+ )
543
+ })
535
544
  })
536
545
  return { text: `${lines.join("\n")}\n`, names }
537
546
  }
@@ -1147,6 +1156,25 @@ export async function planOutputSchemas(
1147
1156
  return { entries, edits, warnings }
1148
1157
  }
1149
1158
 
1159
+ /**
1160
+ * What hole `hole`'s loader in the backend half `file` returns, with `text` read as that file: the
1161
+ * data a fix that writes the loader drafts its output schema from.
1162
+ */
1163
+ export async function holeLoaderShape(
1164
+ root: string,
1165
+ file: string,
1166
+ hole: string,
1167
+ text: string,
1168
+ ): Promise<{ readonly shape?: Shape; readonly warnings: readonly string[] }> {
1169
+ const { shapes, warnings } = await readShapes(
1170
+ root,
1171
+ [{ file, fns: [], schemas: [], holes: [hole] }],
1172
+ new Map([[file, text]]),
1173
+ )
1174
+ const shape = shapes.get(`${file}#boundaryLoaders.${hole}`)
1175
+ return shape === undefined ? { warnings } : { shape: dataShape(shape), warnings }
1176
+ }
1177
+
1150
1178
  // ---- entry points ------------------------------------------------------------------------------
1151
1179
 
1152
1180
  const ROUTE_BACKEND_TS = /\.backend\.[cm]?ts$/
@@ -0,0 +1,426 @@
1
+ /**
2
+ * `nifra fix --code NF-C053`: move a partially prerendered page's request read into a dynamic hole.
3
+ * The read must be held in one `const` of the page component's body, and every use of it must sit in
4
+ * one element of the markup the component returns. That element becomes the hole's render, reading
5
+ * the value from the hole's data, and the read becomes the hole's loader in the backend half, with an
6
+ * output schema drafted from its type. Anything else is refused with the reason, and nothing is
7
+ * written.
8
+ */
9
+ import { readFile, writeFile } from "node:fs/promises"
10
+ import type * as TS from "typescript"
11
+ import { holeLoaderShape, omittedPaths, type Shape, schemaSource } from "./output-schemas.ts"
12
+ import { lineOf } from "./rules/islands.ts"
13
+ import { REQUEST_READ_MODULE, requestReadCalls, requestReadImports } from "./rules/ppr.ts"
14
+ import type { Framework } from "./scaffold.ts"
15
+ import { backendFileOf } from "./scaffold.ts"
16
+ import {
17
+ ADAPTER,
18
+ apply,
19
+ backendPlan,
20
+ defaultComponent,
21
+ type Edit,
22
+ fallbackField,
23
+ HOLE_NAME,
24
+ type ImportNeed,
25
+ indentAt,
26
+ insideRoot,
27
+ localNames,
28
+ MAX_HOLES,
29
+ pagePlan,
30
+ returnedJsx,
31
+ topLevelNames,
32
+ } from "./scaffold-hole.ts"
33
+
34
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
35
+
36
+ /** The TypeScript type `shape` describes, or undefined for one the hole's data cannot carry. */
37
+ function typeText(shape: Shape): string | undefined {
38
+ switch (shape.kind) {
39
+ case "string":
40
+ case "number":
41
+ case "boolean":
42
+ case "null":
43
+ return shape.kind
44
+ case "literal":
45
+ return JSON.stringify(shape.value)
46
+ case "array":
47
+ case "tuple": {
48
+ const items = shape.kind === "array" ? [shape.items] : shape.items
49
+ const types = items.map(typeText)
50
+ return types.some((type) => type === undefined)
51
+ ? undefined
52
+ : `readonly (${[...new Set(types)].join(" | ")})[]`
53
+ }
54
+ case "record": {
55
+ const values = typeText(shape.values)
56
+ return values === undefined ? undefined : `Readonly<Record<string, ${values}>>`
57
+ }
58
+ case "union": {
59
+ const types = shape.members.map(typeText)
60
+ return types.some((type) => type === undefined) ? undefined : types.join(" | ")
61
+ }
62
+ case "object": {
63
+ const fields: string[] = []
64
+ for (const field of shape.fields) {
65
+ const type = typeText(field.shape)
66
+ if (type === undefined) return undefined
67
+ const key = IDENTIFIER.test(field.name) ? field.name : JSON.stringify(field.name)
68
+ fields.push(`readonly ${key}${field.optional ? "?" : ""}: ${type}`)
69
+ }
70
+ return fields.length === 0 ? "{}" : `{ ${fields.join("; ")} }`
71
+ }
72
+ default:
73
+ return undefined
74
+ }
75
+ }
76
+
77
+ /** Whether `id` reads a binding: not a property name, a declared name or an intrinsic tag. */
78
+ function isReference(ts: typeof TS, id: TS.Identifier): boolean {
79
+ const parent = id.parent
80
+ if (parent === undefined || ts.isImportSpecifier(parent) || ts.isImportClause(parent))
81
+ return false
82
+ if (ts.isShorthandPropertyAssignment(parent)) return true
83
+ // A declaration's, property's or attribute's own name binds or labels; it reads nothing. Read by
84
+ // field, since TypeScript 7's API lacks some of the guards (`isPropertySignature`).
85
+ if ("name" in parent && parent.name === id) return false
86
+ if (ts.isQualifiedName(parent)) return parent.left === id
87
+ if (ts.isBindingElement(parent)) return parent.propertyName !== id
88
+ if (
89
+ ts.isJsxOpeningElement(parent) ||
90
+ ts.isJsxSelfClosingElement(parent) ||
91
+ ts.isJsxClosingElement(parent)
92
+ )
93
+ return !/^[a-z]/.test(id.text)
94
+ return true
95
+ }
96
+
97
+ /** Every identifier under `node` that reads a binding. */
98
+ function references(ts: typeof TS, node: TS.Node): TS.Identifier[] {
99
+ const found: TS.Identifier[] = []
100
+ const visit = (at: TS.Node): void => {
101
+ if (ts.isIdentifier(at) && isReference(ts, at)) found.push(at)
102
+ ts.forEachChild(at, visit)
103
+ }
104
+ visit(node)
105
+ return found
106
+ }
107
+
108
+ /** Each name `node` declares, as often as it declares it. */
109
+ function declarations(ts: typeof TS, node: TS.Node): string[] {
110
+ const names: string[] = []
111
+ const visit = (at: TS.Node): void => {
112
+ if (
113
+ (ts.isVariableDeclaration(at) ||
114
+ ts.isParameter(at) ||
115
+ ts.isBindingElement(at) ||
116
+ ts.isFunctionDeclaration(at)) &&
117
+ at.name !== undefined &&
118
+ ts.isIdentifier(at.name)
119
+ )
120
+ names.push(at.name.text)
121
+ ts.forEachChild(at, visit)
122
+ }
123
+ visit(node)
124
+ return names
125
+ }
126
+
127
+ const within = (sf: TS.SourceFile, outer: TS.Node, inner: TS.Node): boolean =>
128
+ outer.getStart(sf) <= inner.getStart(sf) && inner.getEnd() <= outer.getEnd()
129
+
130
+ /** `text`, its lines after the first moved from `from` indentation to `to`. */
131
+ function reindent(text: string, from: string, to: string): string {
132
+ return text
133
+ .split("\n")
134
+ .map((line, i) =>
135
+ i === 0 ? line : `${to}${line.startsWith(from) ? line.slice(from.length) : line.trimStart()}`,
136
+ )
137
+ .join("\n")
138
+ }
139
+
140
+ /** `visitorName` → `visitor-name`, or undefined when no hole name comes of it. */
141
+ function holeNameOf(local: string): string | undefined {
142
+ const name = local
143
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
144
+ .toLowerCase()
145
+ .replace(/[^a-z0-9]+/g, "-")
146
+ .replace(/^[^a-z]+|-+$/g, "")
147
+ .slice(0, 28)
148
+ .replace(/-+$/, "")
149
+ return HOLE_NAME.test(name) ? name : undefined
150
+ }
151
+
152
+ /**
153
+ * Move the request read `diagnostic` found at `line` of the page `file` (relative to `root`) into a new
154
+ * dynamic hole. Returns the files it wrote; throws with the reason when it cannot, writing nothing.
155
+ */
156
+ export async function moveReadToHole(
157
+ root: string,
158
+ file: string,
159
+ line: number | undefined,
160
+ framework: Framework,
161
+ ts: typeof TS,
162
+ ): Promise<readonly string[]> {
163
+ const refuse = (reason: string): never => {
164
+ throw new Error(`[nifra] ${file}: ${reason}; nothing was changed`)
165
+ }
166
+ const adapter = ADAPTER[framework]
167
+ if (adapter === undefined)
168
+ return refuse(
169
+ `the fix writes a JSX hole, and a ${framework} page renders none; move the read by hand (nifra scaffold hole prints the hole to start from)`,
170
+ )
171
+ if (!/\.[jt]sx$/.test(file)) return refuse("the fix edits a .tsx or .jsx page only")
172
+ const backend = backendFileOf(file)
173
+ const pagePath = insideRoot(root, file)
174
+ const backendPath = insideRoot(root, backend)
175
+ const pageSource = await readFile(pagePath, "utf8")
176
+ const backendSource = await readFile(backendPath, "utf8")
177
+ const sf = ts.createSourceFile(file, pageSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)
178
+ const backendFile = ts.createSourceFile(
179
+ backend,
180
+ backendSource,
181
+ ts.ScriptTarget.Latest,
182
+ true,
183
+ ts.ScriptKind.TS,
184
+ )
185
+
186
+ const reads = requestReadImports(ts, sf)
187
+ const call = requestReadCalls(ts, sf, reads).find((found) => lineOf(sf, found) === line)
188
+ if (call === undefined)
189
+ return refuse(
190
+ `no request read is at line ${line ?? "?"} any more; rerun \`nifra fix --code NF-C053\``,
191
+ )
192
+ const page = defaultComponent(ts, sf)
193
+ const body = page?.body
194
+ if (page === undefined || body === undefined || !ts.isBlock(body))
195
+ return refuse("the read is not in the body of the page's default-exported component")
196
+ let statement: TS.Node = call
197
+ while (statement.parent !== body) {
198
+ if (statement.parent === undefined || statement.parent === sf)
199
+ return refuse("the read is not in a statement of the page component's own body")
200
+ statement = statement.parent
201
+ }
202
+ const declaration = ts.isVariableStatement(statement)
203
+ ? statement.declarationList.declarations[0]
204
+ : undefined
205
+ if (
206
+ !ts.isVariableStatement(statement) ||
207
+ !/^const\s/.test(statement.declarationList.getText(sf)) ||
208
+ statement.declarationList.declarations.length !== 1 ||
209
+ declaration === undefined ||
210
+ !ts.isIdentifier(declaration.name) ||
211
+ declaration.initializer === undefined
212
+ )
213
+ return refuse("the read is not held in one `const <name> = ...` of the page component")
214
+ const local = declaration.name.text
215
+ const initializer = declaration.initializer
216
+
217
+ // The loader sees module scope in the backend half: globals and the request reads, not the page's
218
+ // own names or the component's.
219
+ const pageNames = topLevelNames(ts, sf)
220
+ const componentNames = new Set<string>()
221
+ localNames(ts, page, componentNames)
222
+ const ownNames = new Set(declarations(ts, initializer))
223
+ for (const id of references(ts, initializer)) {
224
+ if (reads.has(id.text) || ownNames.has(id.text)) continue
225
+ if (componentNames.has(id.text) || pageNames.has(id.text))
226
+ return refuse(
227
+ `the read uses \`${id.text}\`, which the page defines or imports, and a hole's loader runs in the backend half without it`,
228
+ )
229
+ }
230
+
231
+ if (declarations(ts, page).filter((name) => name === local).length > 1)
232
+ return refuse(`\`${local}\` is declared more than once in the page component`)
233
+ const uses = references(ts, body).filter((id) => id.text === local && !within(sf, statement, id))
234
+ if (uses.length === 0) return refuse(`\`${local}\` is not used in the page's markup`)
235
+ const jsx = returnedJsx(ts, page)
236
+ if (jsx === undefined)
237
+ return refuse("the page component does not return one JSX element the hole can go inside")
238
+ const outside = uses.find((use) => !within(sf, jsx, use))
239
+ if (outside !== undefined)
240
+ return refuse(
241
+ `\`${local}\` is also used outside the markup the page returns (line ${lineOf(sf, outside)}), and only markup moves into a hole`,
242
+ )
243
+
244
+ // The element the hole takes the place of: the innermost one holding every use.
245
+ const elementOf = (node: TS.Node): TS.Node | undefined => {
246
+ for (let at = node.parent; at !== undefined; at = at.parent)
247
+ if (ts.isJsxElement(at) || ts.isJsxSelfClosingElement(at) || ts.isJsxFragment(at)) return at
248
+ return undefined
249
+ }
250
+ const holdsAll = (node: TS.Node): boolean => uses.every((use) => within(sf, node, use))
251
+ const [first] = uses
252
+ let target = first === undefined ? undefined : elementOf(first)
253
+ while (target !== undefined && !holdsAll(target)) target = elementOf(target)
254
+ if (target === undefined || target === jsx)
255
+ return refuse(
256
+ `the uses of \`${local}\` span the page's root element; wrap them in one element, then rerun the fix`,
257
+ )
258
+ const subtree = target
259
+ for (const id of references(ts, subtree)) {
260
+ if (id.text === local) continue
261
+ if (componentNames.has(id.text))
262
+ return refuse(
263
+ `the markup that uses \`${local}\` also uses \`${id.text}\`, which the page component declares, and a hole renders from its loader's data alone`,
264
+ )
265
+ if (reads.has(id.text))
266
+ return refuse(`the markup that uses \`${local}\` reads the request itself`)
267
+ }
268
+ const interactive = (() => {
269
+ let found = false
270
+ const visit = (node: TS.Node): void => {
271
+ if (ts.isJsxAttribute(node) && /^on[A-Z]/.test(node.name.getText(sf))) found = true
272
+ if (!found) ts.forEachChild(node, visit)
273
+ }
274
+ visit(subtree)
275
+ return found
276
+ })()
277
+
278
+ // The hole's name, unused by the page's boundaries and the backend half's loaders.
279
+ const base = holeNameOf(local) ?? "request"
280
+ const usedNames = (name: string): readonly string[] => [
281
+ ...pagePlan(ts, sf, name, framework, { fields: [], imports: [] }).names,
282
+ ...backendPlan(ts, backendFile, name, { body: [], imports: [] }).keys,
283
+ ]
284
+ let name = base
285
+ for (let n = 2; usedNames(name).includes(name); n++) name = `${base}-${n}`
286
+ const loaderKeys = backendPlan(ts, backendFile, name, { body: [], imports: [] }).keys
287
+ if (loaderKeys.length >= MAX_HOLES)
288
+ return refuse(
289
+ `${backend} already has ${loaderKeys.length} hole loaders, the most a route may have`,
290
+ )
291
+
292
+ const readImports: ImportNeed[] = []
293
+ const backendNames = topLevelNames(ts, backendFile)
294
+ const backendReads = requestReadImports(ts, backendFile)
295
+ const readsUsed = new Set(references(ts, initializer).map((id) => id.text))
296
+ for (const [binding, imported] of reads) {
297
+ if (!readsUsed.has(binding)) continue
298
+ if (backendNames.has(binding) && backendReads.get(binding) !== imported)
299
+ return refuse(`${backend} already declares \`${binding}\``)
300
+ readImports.push({ module: REQUEST_READ_MODULE, name: binding, imported })
301
+ }
302
+ const statementIndent = indentAt(pageSource, statement.getStart(sf))
303
+ const read = reindent(initializer.getText(sf), statementIndent, "")
304
+ const loader = (output: string) => ({
305
+ body: [
306
+ "// Read for each visitor, under the hole's own deadline; the shell never sees it.",
307
+ ...`load: () => ({ ${local}: ${read} }),`.split("\n"),
308
+ ...`output: ${output},`.split("\n"),
309
+ ],
310
+ imports: [{ module: "@nifrajs/schema", name: "t" }, ...readImports],
311
+ })
312
+ const probe = backendPlan(ts, backendFile, name, loader("t.json()"))
313
+ if (probe.reason !== undefined) return refuse(`${backend}: ${probe.reason}`)
314
+ const { shape, warnings } = await holeLoaderShape(
315
+ root,
316
+ backend,
317
+ name,
318
+ apply(backendSource, probe.edits),
319
+ )
320
+ if (warnings.length > 0)
321
+ return refuse(`the read's type could not be read: ${warnings.join("; ")}`)
322
+ const field =
323
+ shape?.kind === "object" ? shape.fields.find((entry) => entry.name === local) : undefined
324
+ const data: Shape | undefined =
325
+ field === undefined ? undefined : { kind: "object", fields: [field] }
326
+ const dataType = data === undefined ? undefined : typeText(data)
327
+ if (data === undefined || dataType === undefined || omittedPaths(data).length > 0)
328
+ return refuse(
329
+ `the read's value is not a type the fix can describe with a schema (strings, numbers, booleans, null, and arrays and objects of them); move it by hand`,
330
+ )
331
+ const back = backendPlan(ts, backendFile, name, loader(schemaSource(data)))
332
+ if (back.reason !== undefined) return refuse(`${backend}: ${back.reason}`)
333
+
334
+ // The render reads the value from the hole's data, under a parameter name the markup leaves free.
335
+ const subtreeNames = new Set(references(ts, subtree).map((id) => id.text))
336
+ const param = ["data", "hole", "holeData"].find((candidate) => !subtreeNames.has(candidate))
337
+ if (param === undefined) return refuse("the markup uses every name the fix would give the data")
338
+ const start = subtree.getStart(sf)
339
+ const renames: Edit[] = uses.map((use) =>
340
+ use.parent !== undefined && ts.isShorthandPropertyAssignment(use.parent)
341
+ ? {
342
+ at: use.getStart(sf) - start,
343
+ remove: use.getWidth(sf),
344
+ text: `${local}: ${param}.${local}`,
345
+ }
346
+ : { at: use.getStart(sf) - start, remove: use.getWidth(sf), text: `${param}.${local}` },
347
+ )
348
+ const markup = reindent(apply(subtree.getText(sf), renames), indentAt(pageSource, start), " ")
349
+ const signature = `render: (${param}: ${dataType}) =>`
350
+ const render =
351
+ markup.includes("\n") || signature.length + markup.length > 90
352
+ ? `${signature} (\n ${markup}\n),`
353
+ : `${signature} ${markup},`
354
+ const front = pagePlan(ts, sf, name, framework, {
355
+ fields: [
356
+ 'mode: "dynamic",',
357
+ ...(interactive ? ["interactive: true, // its event handlers hydrate with the hole"] : []),
358
+ render,
359
+ fallbackField(framework),
360
+ ],
361
+ imports: [],
362
+ replaces: subtree,
363
+ })
364
+ if (front.reason !== undefined) return refuse(front.reason)
365
+
366
+ // The read's statement goes, with its line when it has one to itself.
367
+ const lineStart = pageSource.lastIndexOf("\n", statement.getStart(sf) - 1) + 1
368
+ const lineEnd = pageSource.indexOf("\n", statement.getEnd())
369
+ const ownLines =
370
+ pageSource.slice(lineStart, statement.getStart(sf)).trim() === "" &&
371
+ pageSource.slice(statement.getEnd(), lineEnd === -1 ? undefined : lineEnd).trim() === ""
372
+ const edits: Edit[] = [
373
+ ...front.edits,
374
+ ownLines
375
+ ? {
376
+ at: lineStart,
377
+ remove: (lineEnd === -1 ? pageSource.length : lineEnd + 1) - lineStart,
378
+ text: "",
379
+ }
380
+ : { at: statement.getStart(sf), remove: statement.getWidth(sf), text: "" },
381
+ ]
382
+ // A read import nothing else in the page uses goes too.
383
+ const stillUsed = new Set(
384
+ references(ts, sf)
385
+ .filter((id) => reads.has(id.text) && !within(sf, statement, id))
386
+ .map((id) => id.text),
387
+ )
388
+ for (const imported of sf.statements) {
389
+ if (
390
+ !ts.isImportDeclaration(imported) ||
391
+ !ts.isStringLiteral(imported.moduleSpecifier) ||
392
+ imported.moduleSpecifier.text !== REQUEST_READ_MODULE
393
+ )
394
+ continue
395
+ const clause = imported.importClause
396
+ const bindings = clause?.namedBindings
397
+ if (clause === undefined || bindings === undefined || !ts.isNamedImports(bindings)) continue
398
+ const kept = bindings.elements.filter(
399
+ (element) => !reads.has(element.name.text) || stillUsed.has(element.name.text),
400
+ )
401
+ if (kept.length === bindings.elements.length) continue
402
+ if (kept.length === 0 && clause.name === undefined) {
403
+ // From the line break before it: a new import may be placed right where this one ends.
404
+ const start = imported.getStart(sf)
405
+ const from = start > 0 && pageSource[start - 1] === "\n" ? start - 1 : start
406
+ edits.push({ at: from, remove: imported.getEnd() - from, text: "" })
407
+ } else
408
+ edits.push({
409
+ at: bindings.getStart(sf),
410
+ remove: bindings.getWidth(sf),
411
+ text: `{ ${kept.map((element) => element.getText(sf)).join(", ")} }`,
412
+ })
413
+ }
414
+
415
+ const fixed = apply(pageSource, edits)
416
+ // An import removed from the very top leaves the line break that followed it.
417
+ await writeFile(
418
+ pagePath,
419
+ fixed.startsWith("\n") && !pageSource.startsWith("\n") ? fixed.slice(1) : fixed,
420
+ "utf8",
421
+ )
422
+ await writeFile(backendPath, apply(backendSource, back.edits), "utf8")
423
+ const { refreshRouteTypes } = await import("./route-types.ts")
424
+ refreshRouteTypes(root, () => {})
425
+ return [file, backend]
426
+ }
@@ -0,0 +1,69 @@
1
+ import type { UpgradeRecipe } from "./index.ts"
2
+
3
+ /**
4
+ * Upgrade recipe for Nifra 5.6.
5
+ *
6
+ * `@nifrajs/islets` and `@nifrajs/web/nano` merge into `@nifrajs/web/islands`. The imports move
7
+ * mechanically; the call shapes and the island host markup do not, so the notes list each removed
8
+ * name with what replaces it.
9
+ */
10
+ export const recipe: UpgradeRecipe = {
11
+ version: "5.6.0",
12
+ pins: [
13
+ { match: "@nifrajs/", to: "5.6.0" },
14
+ { match: "create-nifra", to: "5.6.0" },
15
+ { match: "nifra", to: "5.6.0" },
16
+ ],
17
+ dependencyMoves: [{ from: "@nifrajs/islets", to: "@nifrajs/web", toVersion: "5.6.0" }],
18
+ importMoves: [
19
+ { from: "@nifrajs/islets", to: "@nifrajs/web/islands" },
20
+ { from: "@nifrajs/web/nano", to: "@nifrajs/web/islands" },
21
+ { from: "@nifrajs/uploads/detect", to: "@nifrajs/core/file-type" },
22
+ ],
23
+ retiredMarkers: [
24
+ {
25
+ marker: "nifra-expect NF-C021",
26
+ instead: "nothing: NF-C021 is retired, so delete the comment",
27
+ },
28
+ {
29
+ marker: "nifra-expect NF-C023",
30
+ instead: "nothing: NF-C023 is retired, so delete the comment",
31
+ },
32
+ ],
33
+ affects: [
34
+ "@nifrajs/cli",
35
+ "@nifrajs/coding-agent",
36
+ "@nifrajs/core",
37
+ "@nifrajs/env",
38
+ "@nifrajs/islets",
39
+ "@nifrajs/middleware",
40
+ "@nifrajs/schema",
41
+ "@nifrajs/uploads",
42
+ "@nifrajs/web",
43
+ "@nifrajs/web-react",
44
+ "@nifrajs/web-svelte",
45
+ "@nifrajs/web-vanilla",
46
+ ],
47
+ notes: [
48
+ 'Island hosts are any element with `data-island="<id>"`. `<nifra-island data-id>` markers are no longer mounted: rename `data-id` to `data-island`, `data-props` to `data-island-props`, `data-strategy` to `data-island-strategy` and `data-media` to `data-island-media`. The `@nifrajs/web-react` `<Island>` marker renders the new names; `@nifrajs/islets`\' `data-island-state` becomes `data-island-props`.',
49
+ '`@nifrajs/islets`: `island("id", setup)` plus its own `mountIslands()` becomes `const id = bindIsland(setup)` and `mountIslands({ id })`; the setup still receives `{ root, state }` and returns its handlers, and gains `props` and `onDispose(fn)`. `islandState(value)` is `islandProps(value)`. `signal`, `computed`, `effect` and `batch` keep their shapes.',
50
+ "`@nifrajs/web/nano`: a signal is read by calling it (`count()`, was `count.get()`); `computed(fn, [deps])` is `computed(fn)`, which tracks what it reads; `bind(el, source, apply)` is `effect(() => apply(el, source()))`; `bindResource` is an `effect` over the resource's state; `resource(fetcher, [deps])` is `resource(source, (key, abort) => fetcher)`, where `source` returns the key and the fetcher's reads are not dependencies; `Readable.subscribe(fn)` is `effect(() => fn(source()))`. `bindList(source, container, { key, create, update })` keeps its shape; `key` receives only the item.",
51
+ "Effects, computeds, `bindList` and `resource` created while an enhancer sets up stop when its island unmounts, so the disposers nano asked you to collect can go. An effect created later, inside an event handler, is not owned.",
52
+ "`nifra check` adds NF-C047 (a `data-bind-*` name its `bindIsland` setup never declares) and NF-C048 (a binding no `bindIsland` host walks), and NF-C022 now checks the islands `bindList` key. NF-C021 and NF-C023 are retired; a `nifra.check.json` override of either no longer does anything.",
53
+ "`nifra scaffold --variant stateful` emits a reactive island where it emitted the nano pattern.",
54
+ "The server-component pipeline is certified on Vite 8.3.4: set `vite` to exactly 8.3.4. Until it matches, the plugin's guard stops the build and `nifra check` names the installed version.",
55
+ '`withISR` over any store but `MemoryCacheStore` (a `KVCacheStore`, or a `CacheStore` of your own) needs `storeSecret`, the same in every process, at least 32 characters and generated at random (`openssl rand -hex 32`), and throws at construction without one; on Workers, set it with `wrangler secret put` and pass `env.<NAME>`. Pages stored before the upgrade carry no signature, so each renders once more and is stored signed. A page that fails the check reaches `onStoreError` with op `"verify"`.',
56
+ "`detectFileType`, `DETECTABLE_MIME_TYPES`, `FILE_TYPE_PREFIX_BYTES` and the `FileType` type are exported from `@nifrajs/core/file-type`, and `@nifrajs/uploads` no longer exports them. `@nifrajs/uploads/detect` imports are rewritten; import those names from `@nifrajs/core/file-type` where they came from `@nifrajs/uploads`. `@nifrajs/uploads` takes `@nifrajs/core` as a peer dependency.",
57
+ "`idempotency()` from `@nifrajs/middleware` covers the routes declared after it, and installing it after a route that uses a covered method throws: move the `.use(idempotency(...))` above those routes. A replay now runs just before the handler, after the route's authentication, validation and every guard admit the retry, and stored records without an admission marker are refused. It returns an `IdentityPlugin` (from `@nifrajs/core`) rather than a `Middleware`: replace an explicit `Middleware` annotation on it, or let TypeScript infer the type.",
58
+ '`multipartBody` and `t.form` parse a form themselves, by the Fetch standard\'s parser, instead of the runtime\'s `formData()`, so every runtime reads the same parts. A part\'s disposition must be `form-data; name="..."` with an optional `; filename="..."`, a body led by a preamble is refused, and a file part with no `Content-Type` is `text/plain` on every runtime.',
59
+ "`@nifrajs/web-vanilla`'s `html` writes each value for the place it lands: an unquoted attribute value is quoted, a `javascript:` or `vbscript:` URL at the start of a URL attribute becomes `about:invalid`, and a string or nested template throws as a tag name, inside `<script>` or `<style>`, or in an `on*` or `srcdoc` value. Interpolate a number or `raw()` trusted text there instead.",
60
+ "A reload of the page on screen keeps the identity of every part of `data` it did not change, and React and Preact layouts render memoized on their own props. Svelte pages receive `data` as the router published it, not as a deep reactive proxy, so writing into `data` in place no longer updates the page: copy what you edit into the page's own state. A page that compares `data` with its value from before a reload exports `shareData = false`.",
61
+ 'While an intercept boundary holds a route in a modal, `useLocation`, `useSearch`, `useMatches` and the route props describe the page underneath; `RouterState.intercepted` names the boundary, and `path` stays the address-bar URL. A form with no action inside `data-nifra-boundary="<name>"` posts to the target, and the result arrives as the boundary\'s `actionData`.',
62
+ "`@nifrajs/coding-agent`: a plan with more subagent nodes than `limits.maxChildren` (default 4) fails to compile with `E_MAX_CHILDREN`, the ceiling counts retries, and `OrchestrationHost`'s `policy.allowedCapabilities` bounds every catalog step a plan resolves to.",
63
+ "`nifra mcp` answers a line that is not valid UTF-8 with `-32700` instead of running it, sends no reply to a notification whose handler throws, processes a last line without a trailing newline, and lets running requests answer before it shuts down when stdin closes.",
64
+ "An `authenticate()` stage, and the auth plugins built on one (`bearer()`, `jwt()`, `basicAuth()`, `apiKey()`), now gates the `mount()` and `mountFetch()` handlers registered after it, WebSocket upgrades included: a caller the stage refuses gets its response, not the mounted app. Register a mount that must stay public before the stage.",
65
+ "`t.integer()` is bounded to the safe-integer range by default, so a JSON or query value past 2^53 - 1, which has already been rounded when it is parsed, fails validation with a 422 instead of reaching the handler as a different number. A bound passed to `t.integer()` replaces the default on that side.",
66
+ "`env.number()` reads plain decimal text only, so `0x10`, `1e3` and `Infinity` are refused at startup. A value of only spaces is unset for `env.number()` and `env.port()`, so a `default` applies, and `env.boolean({ default })` returns the default for a variable that is set but empty.",
67
+ "`etag()` keeps an `ETag` the handler already set and answers `If-None-Match` against it, instead of replacing it with a hash of the body.",
68
+ ],
69
+ }
@@ -17,6 +17,7 @@ import { recipe as v5_2_0 } from "./5.2.0.ts"
17
17
  import { recipe as v5_3_0 } from "./5.3.0.ts"
18
18
  import { recipe as v5_4_0 } from "./5.4.0.ts"
19
19
  import { recipe as v5_5_0 } from "./5.5.0.ts"
20
+ import { recipe as v5_6_0 } from "./5.6.0.ts"
20
21
 
21
22
  /** A pin rule: every dependency whose name starts with `match` is set to version `to`. */
22
23
  export interface PinRule {
@@ -74,6 +75,7 @@ const RECIPES: Record<string, UpgradeRecipe> = {
74
75
  [v5_3_0.version]: v5_3_0,
75
76
  [v5_4_0.version]: v5_4_0,
76
77
  [v5_5_0.version]: v5_5_0,
78
+ [v5_6_0.version]: v5_6_0,
77
79
  }
78
80
 
79
81
  export function getRecipe(version: string): UpgradeRecipe | undefined {
package/src/review.ts CHANGED
@@ -132,9 +132,14 @@ export const CHECK_CODES: Readonly<Record<string, ReviewCheckId>> = {
132
132
  "NF-C018": "route-boundary",
133
133
  "NF-C019": "route-boundary",
134
134
  "NF-C020": "route-boundary",
135
- "NF-C021": "route-boundary",
136
135
  "NF-C022": "route-boundary",
137
- "NF-C023": "route-boundary",
136
+ "NF-C047": "route-boundary",
137
+ "NF-C048": "route-boundary",
138
+ "NF-C049": "route-boundary",
139
+ "NF-C050": "route-boundary",
140
+ "NF-C051": "route-boundary",
141
+ "NF-C052": "route-boundary",
142
+ "NF-C053": "route-boundary",
138
143
  "NF-C024": "route-boundary",
139
144
  "NF-C025": "route-boundary",
140
145
  "NF-C026": "route-boundary",
@@ -44,9 +44,14 @@ export const RULE_CODES = Object.freeze({
44
44
  "NF-C045": "Route registered outside the typed chain",
45
45
  "NF-C046": "Identity-sensitive version skew",
46
46
  "NF-C020": "Island enhancer cleanup check",
47
- "NF-C021": "nano binding cleanup check",
48
- "NF-C022": "nano bindList key check",
49
- "NF-C023": "nano computed deps check",
47
+ "NF-C022": "bindList key check",
48
+ "NF-C047": "Island binding name check",
49
+ "NF-C048": "Island binding outside a bindIsland host",
50
+ "NF-C049": "Swap link or form misdeclared",
51
+ "NF-C050": "Swap names a slot nothing declares",
52
+ "NF-C051": "Slot content is not its slot() alone",
53
+ "NF-C052": "Swap URL's page renders no such slot",
54
+ "NF-C053": "Partially prerendered page reads the request",
50
55
  "NF-D001": "Doctor check",
51
56
  "NF-D002": "Mixed nifra versions",
52
57
  "NF-D003": "Stale file: dependencies in bun.lock",
@@ -68,7 +73,7 @@ export const RULE_CODES = Object.freeze({
68
73
  } as const)
69
74
 
70
75
  /** Codes that no longer fire but remain reserved forever. */
71
- export const RETIRED_CODES: ReadonlySet<string> = new Set()
76
+ export const RETIRED_CODES: ReadonlySet<string> = new Set(["NF-C021", "NF-C023"])
72
77
 
73
78
  export type BuiltInCode = keyof typeof RULE_CODES
74
79