@nifrajs/cli 5.1.0 → 5.3.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 (230) hide show
  1. package/CHANGELOG.md +3313 -0
  2. package/README.md +3 -0
  3. package/dist/agent-files.d.ts +19 -11
  4. package/dist/agent-files.d.ts.map +1 -1
  5. package/dist/agent-files.js +26 -18
  6. package/dist/agent-files.js.map +1 -1
  7. package/dist/assure-hydration.d.ts.map +1 -1
  8. package/dist/assure-hydration.js +7 -2
  9. package/dist/assure-hydration.js.map +1 -1
  10. package/dist/assure.d.ts.map +1 -1
  11. package/dist/assure.js +14 -1
  12. package/dist/assure.js.map +1 -1
  13. package/dist/capabilities-tool.d.ts.map +1 -1
  14. package/dist/capabilities-tool.js +131 -45
  15. package/dist/capabilities-tool.js.map +1 -1
  16. package/dist/check-diagnostics.d.ts +5 -0
  17. package/dist/check-diagnostics.d.ts.map +1 -1
  18. package/dist/check-diagnostics.js +5 -0
  19. package/dist/check-diagnostics.js.map +1 -1
  20. package/dist/check-scan.d.ts +9 -3
  21. package/dist/check-scan.d.ts.map +1 -1
  22. package/dist/check-scan.js +61 -21
  23. package/dist/check-scan.js.map +1 -1
  24. package/dist/check.d.ts.map +1 -1
  25. package/dist/check.js +55 -15
  26. package/dist/check.js.map +1 -1
  27. package/dist/cli.d.ts.map +1 -1
  28. package/dist/cli.js +37 -18
  29. package/dist/cli.js.map +1 -1
  30. package/dist/command-catalog.d.ts.map +1 -1
  31. package/dist/command-catalog.js +9 -5
  32. package/dist/command-catalog.js.map +1 -1
  33. package/dist/db-tool.d.ts.map +1 -1
  34. package/dist/db-tool.js +2 -1
  35. package/dist/db-tool.js.map +1 -1
  36. package/dist/dev-bun-config.d.ts +6 -3
  37. package/dist/dev-bun-config.d.ts.map +1 -1
  38. package/dist/dev-bun-config.js +13 -10
  39. package/dist/dev-bun-config.js.map +1 -1
  40. package/dist/dev-feed-tool.d.ts +3 -2
  41. package/dist/dev-feed-tool.d.ts.map +1 -1
  42. package/dist/dev-feed-tool.js +26 -5
  43. package/dist/dev-feed-tool.js.map +1 -1
  44. package/dist/doctor.d.ts +15 -1
  45. package/dist/doctor.d.ts.map +1 -1
  46. package/dist/doctor.js +79 -61
  47. package/dist/doctor.js.map +1 -1
  48. package/dist/env-file.d.ts.map +1 -1
  49. package/dist/env-file.js +41 -8
  50. package/dist/env-file.js.map +1 -1
  51. package/dist/i18n-check.d.ts +11 -1
  52. package/dist/i18n-check.d.ts.map +1 -1
  53. package/dist/i18n-check.js +170 -17
  54. package/dist/i18n-check.js.map +1 -1
  55. package/dist/init-agents.d.ts +46 -6
  56. package/dist/init-agents.d.ts.map +1 -1
  57. package/dist/init-agents.js +193 -31
  58. package/dist/init-agents.js.map +1 -1
  59. package/dist/internal/project-specifiers.d.ts.map +1 -1
  60. package/dist/internal/project-specifiers.js +9 -1
  61. package/dist/internal/project-specifiers.js.map +1 -1
  62. package/dist/internal/source-facts.d.ts +22 -0
  63. package/dist/internal/source-facts.d.ts.map +1 -1
  64. package/dist/internal/source-facts.js +322 -0
  65. package/dist/internal/source-facts.js.map +1 -1
  66. package/dist/internal/workspace-packages.d.ts +22 -0
  67. package/dist/internal/workspace-packages.d.ts.map +1 -0
  68. package/dist/internal/workspace-packages.js +215 -0
  69. package/dist/internal/workspace-packages.js.map +1 -0
  70. package/dist/load.d.ts +7 -2
  71. package/dist/load.d.ts.map +1 -1
  72. package/dist/load.js +11 -2
  73. package/dist/load.js.map +1 -1
  74. package/dist/lock-links.d.ts +42 -0
  75. package/dist/lock-links.d.ts.map +1 -0
  76. package/dist/lock-links.js +144 -0
  77. package/dist/lock-links.js.map +1 -0
  78. package/dist/mcp-exec.d.ts +1 -0
  79. package/dist/mcp-exec.d.ts.map +1 -1
  80. package/dist/mcp-exec.js +16 -5
  81. package/dist/mcp-exec.js.map +1 -1
  82. package/dist/mcp-http.js +1 -1
  83. package/dist/mcp-io.d.ts +23 -3
  84. package/dist/mcp-io.d.ts.map +1 -1
  85. package/dist/mcp-io.js +59 -12
  86. package/dist/mcp-io.js.map +1 -1
  87. package/dist/mcp-isolate.d.ts.map +1 -1
  88. package/dist/mcp-isolate.js +2 -1
  89. package/dist/mcp-isolate.js.map +1 -1
  90. package/dist/mcp-root.d.ts +6 -4
  91. package/dist/mcp-root.d.ts.map +1 -1
  92. package/dist/mcp-root.js +12 -8
  93. package/dist/mcp-root.js.map +1 -1
  94. package/dist/migrate-layout.d.ts +2 -1
  95. package/dist/migrate-layout.d.ts.map +1 -1
  96. package/dist/migrate-layout.js +435 -29
  97. package/dist/migrate-layout.js.map +1 -1
  98. package/dist/project-site.d.ts +7 -0
  99. package/dist/project-site.d.ts.map +1 -0
  100. package/dist/project-site.js +19 -0
  101. package/dist/project-site.js.map +1 -0
  102. package/dist/recipes/4.0.0.d.ts.map +1 -1
  103. package/dist/recipes/4.0.0.js +2 -0
  104. package/dist/recipes/4.0.0.js.map +1 -1
  105. package/dist/recipes/5.1.0.d.ts +9 -0
  106. package/dist/recipes/5.1.0.d.ts.map +1 -0
  107. package/dist/recipes/5.1.0.js +22 -0
  108. package/dist/recipes/5.1.0.js.map +1 -0
  109. package/dist/recipes/5.2.0.d.ts +10 -0
  110. package/dist/recipes/5.2.0.d.ts.map +1 -0
  111. package/dist/recipes/5.2.0.js +32 -0
  112. package/dist/recipes/5.2.0.js.map +1 -0
  113. package/dist/recipes/5.3.0.d.ts +11 -0
  114. package/dist/recipes/5.3.0.d.ts.map +1 -0
  115. package/dist/recipes/5.3.0.js +35 -0
  116. package/dist/recipes/5.3.0.js.map +1 -0
  117. package/dist/recipes/index.d.ts +3 -0
  118. package/dist/recipes/index.d.ts.map +1 -1
  119. package/dist/recipes/index.js +9 -0
  120. package/dist/recipes/index.js.map +1 -1
  121. package/dist/review.d.ts.map +1 -1
  122. package/dist/review.js +4 -0
  123. package/dist/review.js.map +1 -1
  124. package/dist/rule-explain.d.ts +26 -0
  125. package/dist/rule-explain.d.ts.map +1 -0
  126. package/dist/rule-explain.js +49 -0
  127. package/dist/rule-explain.js.map +1 -0
  128. package/dist/rules/codes.d.ts +4 -0
  129. package/dist/rules/codes.d.ts.map +1 -1
  130. package/dist/rules/codes.js +4 -0
  131. package/dist/rules/codes.js.map +1 -1
  132. package/dist/rules/contract-visibility.d.ts.map +1 -1
  133. package/dist/rules/contract-visibility.js +93 -21
  134. package/dist/rules/contract-visibility.js.map +1 -1
  135. package/dist/rules/explanations.d.ts +14 -0
  136. package/dist/rules/explanations.d.ts.map +1 -0
  137. package/dist/rules/explanations.js +326 -0
  138. package/dist/rules/explanations.js.map +1 -0
  139. package/dist/rules/legacy.d.ts.map +1 -1
  140. package/dist/rules/legacy.js +24 -1
  141. package/dist/rules/legacy.js.map +1 -1
  142. package/dist/rules/merge-auth.d.ts +12 -0
  143. package/dist/rules/merge-auth.d.ts.map +1 -0
  144. package/dist/rules/merge-auth.js +52 -0
  145. package/dist/rules/merge-auth.js.map +1 -0
  146. package/dist/rules/pages.d.ts +51 -0
  147. package/dist/rules/pages.d.ts.map +1 -1
  148. package/dist/rules/pages.js +293 -2
  149. package/dist/rules/pages.js.map +1 -1
  150. package/dist/rules/route-statement.d.ts +10 -0
  151. package/dist/rules/route-statement.d.ts.map +1 -0
  152. package/dist/rules/route-statement.js +150 -0
  153. package/dist/rules/route-statement.js.map +1 -0
  154. package/dist/rules/routes.d.ts +3 -2
  155. package/dist/rules/routes.d.ts.map +1 -1
  156. package/dist/rules/routes.js +4 -3
  157. package/dist/rules/routes.js.map +1 -1
  158. package/dist/rules/zones.d.ts.map +1 -1
  159. package/dist/rules/zones.js +3 -2
  160. package/dist/rules/zones.js.map +1 -1
  161. package/dist/typecheck-coverage.d.ts +11 -0
  162. package/dist/typecheck-coverage.d.ts.map +1 -1
  163. package/dist/typecheck-coverage.js +50 -7
  164. package/dist/typecheck-coverage.js.map +1 -1
  165. package/dist/upgrade.d.ts +80 -11
  166. package/dist/upgrade.d.ts.map +1 -1
  167. package/dist/upgrade.js +332 -65
  168. package/dist/upgrade.js.map +1 -1
  169. package/dist/verification-plan.d.ts.map +1 -1
  170. package/dist/verification-plan.js +2 -0
  171. package/dist/verification-plan.js.map +1 -1
  172. package/dist/version-drift.d.ts.map +1 -1
  173. package/dist/version-drift.js +12 -1
  174. package/dist/version-drift.js.map +1 -1
  175. package/dist/web-app-options.d.ts +1 -1
  176. package/dist/web-app-options.d.ts.map +1 -1
  177. package/dist/web-app-options.js.map +1 -1
  178. package/docs/examples.json +19 -1
  179. package/docs/llms-full.txt +716 -138
  180. package/docs/types.json +516 -74
  181. package/package.json +13 -12
  182. package/src/agent-files.ts +27 -17
  183. package/src/assure-hydration.ts +8 -1
  184. package/src/assure.ts +11 -1
  185. package/src/capabilities-tool.ts +159 -50
  186. package/src/check-diagnostics.ts +10 -0
  187. package/src/check-scan.ts +64 -19
  188. package/src/check.ts +75 -15
  189. package/src/cli.ts +38 -17
  190. package/src/command-catalog.ts +16 -8
  191. package/src/db-tool.ts +2 -0
  192. package/src/dev-bun-config.ts +13 -9
  193. package/src/dev-feed-tool.ts +40 -6
  194. package/src/doctor.ts +102 -66
  195. package/src/env-file.ts +42 -7
  196. package/src/i18n-check.ts +254 -18
  197. package/src/init-agents.ts +221 -41
  198. package/src/internal/project-specifiers.ts +9 -1
  199. package/src/internal/source-facts.ts +397 -0
  200. package/src/internal/workspace-packages.ts +218 -0
  201. package/src/load.ts +19 -3
  202. package/src/lock-links.ts +173 -0
  203. package/src/mcp-exec.ts +18 -4
  204. package/src/mcp-http.ts +1 -1
  205. package/src/mcp-io.ts +72 -12
  206. package/src/mcp-isolate.ts +2 -0
  207. package/src/mcp-root.ts +14 -8
  208. package/src/migrate-layout.ts +496 -31
  209. package/src/project-site.ts +18 -0
  210. package/src/recipes/4.0.0.ts +2 -0
  211. package/src/recipes/5.1.0.ts +23 -0
  212. package/src/recipes/5.2.0.ts +33 -0
  213. package/src/recipes/5.3.0.ts +36 -0
  214. package/src/recipes/index.ts +9 -0
  215. package/src/review.ts +4 -0
  216. package/src/rule-explain.ts +75 -0
  217. package/src/rules/codes.ts +4 -0
  218. package/src/rules/contract-visibility.ts +118 -20
  219. package/src/rules/explanations.ts +339 -0
  220. package/src/rules/legacy.ts +24 -1
  221. package/src/rules/merge-auth.ts +55 -0
  222. package/src/rules/pages.ts +381 -2
  223. package/src/rules/route-statement.ts +170 -0
  224. package/src/rules/routes.ts +4 -3
  225. package/src/rules/zones.ts +3 -2
  226. package/src/typecheck-coverage.ts +51 -6
  227. package/src/upgrade.ts +430 -70
  228. package/src/verification-plan.ts +6 -0
  229. package/src/version-drift.ts +15 -0
  230. package/src/web-app-options.ts +9 -1
@@ -12,7 +12,7 @@
12
12
  * startup and build checks.
13
13
  */
14
14
  import { existsSync, readFileSync } from "node:fs"
15
- import { join } from "node:path"
15
+ import { join, posix } from "node:path"
16
16
  import { discoverRoutes } from "@nifrajs/web/fs"
17
17
  import { BACKEND_ROUTE_EXPORTS, shadowedPages } from "@nifrajs/web/route-manifest"
18
18
  import type * as TSApi from "typescript"
@@ -22,6 +22,7 @@ import { type Diagnostic, diagnostic } from "../diagnostics.ts"
22
22
  import { codeUnitOrder } from "../internal/code-unit-order.ts"
23
23
  import { hasWebConfig } from "../internal/nifra-project.ts"
24
24
  import { scriptKindOf } from "../internal/script-kind.ts"
25
+ import { commentBlockExpectation } from "./comment-markers.ts"
25
26
  import type { CheckRule } from "./index.ts"
26
27
  import { loadRuleTypeScript } from "./typescript.ts"
27
28
 
@@ -173,10 +174,259 @@ function effectiveApiPrefix({ framework, config }: ApiPrefixSources): StaticApiP
173
174
  return own.kind !== "default" || framework === undefined ? own : readStaticApiPrefix(framework)
174
175
  }
175
176
 
177
+ /** What a `createWebApp` call passes as `apiPrefix`: a value, the framework config's own, or neither. */
178
+ type EntryApiPrefix =
179
+ | { readonly kind: "literal"; readonly value: string; readonly unset: boolean }
180
+ | { readonly kind: "config" }
181
+ | { readonly kind: "unreadable" }
182
+
183
+ const SCRIPT_SOURCE = /\.[cm]?[jt]sx?$/
184
+ const WEB_PACKAGE = "@nifrajs/web"
185
+ const CONFIG_MODULES: ReadonlySet<string> = new Set(
186
+ [FRAMEWORK_FILE, CONFIG_FILE].map((file) => file.replace(SCRIPT_SOURCE, "")),
187
+ )
188
+
189
+ /** Whether a relative specifier in `file` names backend/framework.ts or nifra.config.ts. */
190
+ const namesFrameworkConfig = (file: string, specifier: string): boolean =>
191
+ specifier.startsWith(".") &&
192
+ CONFIG_MODULES.has(posix.join(posix.dirname(file), specifier).replace(SCRIPT_SOURCE, ""))
193
+
194
+ const unwrapExpression = (ts: typeof TSApi, node: TSApi.Expression): TSApi.Expression => {
195
+ let expr = node
196
+ while (
197
+ ts.isParenthesizedExpression(expr) ||
198
+ ts.isAsExpression(expr) ||
199
+ ts.isSatisfiesExpression(expr)
200
+ ) {
201
+ expr = expr.expression
202
+ }
203
+ return expr
204
+ }
205
+
206
+ /** A `createWebApp` call that mounts a backend (`api`), with the `apiPrefix` it passes. */
207
+ export interface EntryApiMount {
208
+ readonly line: number
209
+ readonly apiPrefix: EntryApiPrefix
210
+ /** The line of the `apiPrefix` property that decides it, when one does. */
211
+ readonly prefixLine: number | undefined
212
+ }
213
+
214
+ /** A module's matcher for `createWebApp` callees imported from `@nifrajs/web`, by name or through a
215
+ * namespace; `undefined` when the module imports it neither way. */
216
+ function createWebAppCallee(
217
+ ts: typeof TSApi,
218
+ tree: TSApi.SourceFile,
219
+ ): ((callee: TSApi.Expression) => boolean) | undefined {
220
+ const names = new Set<string>()
221
+ const namespaces = new Set<string>()
222
+ for (const statement of tree.statements) {
223
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
224
+ continue
225
+ const bindings = statement.importClause?.namedBindings
226
+ if (bindings === undefined || statement.moduleSpecifier.text !== WEB_PACKAGE) continue
227
+ if (ts.isNamespaceImport(bindings)) namespaces.add(bindings.name.text)
228
+ else
229
+ for (const element of bindings.elements)
230
+ if ((element.propertyName ?? element.name).text === "createWebApp")
231
+ names.add(element.name.text)
232
+ }
233
+ if (names.size === 0 && namespaces.size === 0) return undefined
234
+ return (callee) =>
235
+ ts.isIdentifier(callee)
236
+ ? names.has(callee.text)
237
+ : ts.isPropertyAccessExpression(callee) &&
238
+ ts.isIdentifier(callee.expression) &&
239
+ namespaces.has(callee.expression.text) &&
240
+ callee.name.text === "createWebApp"
241
+ }
242
+
243
+ const objectPropertyName = (
244
+ ts: typeof TSApi,
245
+ property: TSApi.ObjectLiteralElementLike,
246
+ ): string | undefined =>
247
+ property.name !== undefined &&
248
+ (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))
249
+ ? property.name.text
250
+ : undefined
251
+
252
+ /**
253
+ * Every `createWebApp({ api, ... })` call in a module, `createWebApp` imported from `@nifrajs/web`.
254
+ * `apiPrefix` reads as a string literal, a same-module string `const`, or the framework config's own
255
+ * export (`import { apiPrefix } from "./backend/framework"`); a call whose options come from a spread
256
+ * or a variable is unreadable. A call with no `api` mounts nothing and is left out. Pure.
257
+ */
258
+ export function entryApiMounts(
259
+ ts: typeof TSApi,
260
+ tree: TSApi.SourceFile,
261
+ file: string,
262
+ ): EntryApiMount[] {
263
+ const isCreateWebApp = createWebAppCallee(ts, tree)
264
+ if (isCreateWebApp === undefined) return []
265
+ const configNames = new Set<string>()
266
+ const configNamespaces = new Set<string>()
267
+ const strings = new Map<string, string>()
268
+ for (const statement of tree.statements) {
269
+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
270
+ const bindings = statement.importClause?.namedBindings
271
+ if (bindings === undefined || !namesFrameworkConfig(file, statement.moduleSpecifier.text))
272
+ continue
273
+ if (ts.isNamespaceImport(bindings)) {
274
+ configNamespaces.add(bindings.name.text)
275
+ continue
276
+ }
277
+ for (const element of bindings.elements)
278
+ if ((element.propertyName ?? element.name).text === "apiPrefix")
279
+ configNames.add(element.name.text)
280
+ continue
281
+ }
282
+ if (
283
+ !ts.isVariableStatement(statement) ||
284
+ (statement.declarationList.flags & ts.NodeFlags.Const) === 0
285
+ )
286
+ continue
287
+ for (const declaration of statement.declarationList.declarations) {
288
+ const init =
289
+ declaration.initializer === undefined
290
+ ? undefined
291
+ : unwrapExpression(ts, declaration.initializer)
292
+ if (
293
+ ts.isIdentifier(declaration.name) &&
294
+ init !== undefined &&
295
+ (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init))
296
+ )
297
+ strings.set(declaration.name.text, init.text)
298
+ }
299
+ }
300
+
301
+ const readPrefix = (node: TSApi.Expression): EntryApiPrefix => {
302
+ const expr = unwrapExpression(ts, node)
303
+ if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr))
304
+ return { kind: "literal", value: expr.text, unset: false }
305
+ if (ts.isIdentifier(expr)) {
306
+ if (configNames.has(expr.text)) return { kind: "config" }
307
+ const value = strings.get(expr.text)
308
+ return value === undefined ? { kind: "unreadable" } : { kind: "literal", value, unset: false }
309
+ }
310
+ if (
311
+ ts.isPropertyAccessExpression(expr) &&
312
+ ts.isIdentifier(expr.expression) &&
313
+ configNamespaces.has(expr.expression.text) &&
314
+ expr.name.text === "apiPrefix"
315
+ )
316
+ return { kind: "config" }
317
+ return { kind: "unreadable" }
318
+ }
319
+ const mounts: EntryApiMount[] = []
320
+ const visit = (node: TSApi.Node): void => {
321
+ const arg = ts.isCallExpression(node) ? node.arguments[0] : undefined
322
+ const options = arg === undefined ? undefined : unwrapExpression(ts, arg)
323
+ if (
324
+ ts.isCallExpression(node) &&
325
+ isCreateWebApp(node.expression) &&
326
+ options !== undefined &&
327
+ ts.isObjectLiteralExpression(options) &&
328
+ options.properties.some((property) => objectPropertyName(ts, property) === "api")
329
+ ) {
330
+ // The last of an `apiPrefix` property and a spread decides, as it does at runtime.
331
+ let apiPrefix: EntryApiPrefix = { kind: "literal", value: "", unset: true }
332
+ let prefixNode: TSApi.Node | undefined
333
+ for (const property of options.properties) {
334
+ if (ts.isSpreadAssignment(property)) apiPrefix = { kind: "unreadable" }
335
+ else if (objectPropertyName(ts, property) !== "apiPrefix") continue
336
+ else if (ts.isPropertyAssignment(property)) apiPrefix = readPrefix(property.initializer)
337
+ else if (ts.isShorthandPropertyAssignment(property)) apiPrefix = readPrefix(property.name)
338
+ else apiPrefix = { kind: "unreadable" }
339
+ prefixNode = ts.isSpreadAssignment(property) ? undefined : property
340
+ }
341
+ const lineOf = (at: TSApi.Node): number =>
342
+ tree.getLineAndCharacterOfPosition(at.getStart(tree)).line + 1
343
+ mounts.push({
344
+ line: lineOf(node),
345
+ apiPrefix,
346
+ prefixLine: prefixNode === undefined ? undefined : lineOf(prefixNode),
347
+ })
348
+ }
349
+ ts.forEachChild(node, visit)
350
+ }
351
+ visit(tree)
352
+ return mounts
353
+ }
354
+
355
+ const ENTRY_PREFIX_EXPECTATION = ["NF-C035"]
356
+
357
+ const servedAt = (prefix: string): string => (prefix === "" ? "nowhere" : `at ${prefix}`)
358
+
359
+ /**
360
+ * The NF-C035 findings for app modules that start their own server: a `createWebApp` call that
361
+ * mounts a backend at a different `apiPrefix` than the one `nifra dev` reads, or with none, so
362
+ * production serves the backend somewhere dev and e2e never exercised.
363
+ */
364
+ async function entryApiPrefixFindings(
365
+ ctx: Parameters<CheckRule["scan"]>[0],
366
+ expected: string,
367
+ origin: string,
368
+ ): Promise<Diagnostic[]> {
369
+ const candidates = ctx.sources.files.filter(
370
+ (file) => SCRIPT_SOURCE.test(file) && ctx.sources.read(file)?.includes("createWebApp") === true,
371
+ )
372
+ if (candidates.length === 0) return []
373
+ const ts = (await loadRuleTypeScript(ctx)).compiler
374
+ if (ts === undefined) return []
375
+ const findings: Diagnostic[] = []
376
+ for (const file of [...candidates].sort(codeUnitOrder)) {
377
+ const text = ctx.sources.read(file) ?? ""
378
+ const tree = ts.createSourceFile(
379
+ file,
380
+ text,
381
+ ts.ScriptTarget.Latest,
382
+ true,
383
+ scriptKindOf(ts, file),
384
+ )
385
+ const lines = text.split("\n")
386
+ for (const { line, apiPrefix, prefixLine } of entryApiMounts(ts, tree, file)) {
387
+ if (apiPrefix.kind !== "literal" || apiPrefix.value === expected) continue
388
+ if (
389
+ [line, prefixLine].some(
390
+ (at) => at !== undefined && commentBlockExpectation(lines, at, ENTRY_PREFIX_EXPECTATION),
391
+ )
392
+ )
393
+ continue
394
+ const specifier = posix.relative(posix.dirname(file), origin.replace(SCRIPT_SOURCE, ""))
395
+ const passed = apiPrefix.unset
396
+ ? "no apiPrefix"
397
+ : `apiPrefix ${JSON.stringify(apiPrefix.value)}`
398
+ const hatch =
399
+ expected === ""
400
+ ? "Mark a deliberate difference with `// nifra-expect NF-C035: <reason>` above the call."
401
+ : `If another server already serves this backend at ${expected}, mark the call with \`// nifra-expect NF-C035: <reason>\` instead${apiPrefix.value === "" ? ": an apiPrefix here would add a second path to it that skips that server's middleware" : ""}.`
402
+ findings.push(
403
+ diagnostic({
404
+ code: "NF-C035",
405
+ severity: "warn",
406
+ file,
407
+ line,
408
+ message: `${file} calls createWebApp with a backend and ${passed}, so the server it starts serves the backend ${servedAt(apiPrefix.value)}, while \`nifra dev\` serves it ${servedAt(expected)} (${origin}). Pass the framework config's value: \`import { apiPrefix } from "${specifier.startsWith(".") ? specifier : `./${specifier}`}"\` and \`createWebApp({ ..., apiPrefix })\`. ${hatch}`,
409
+ evidence: [
410
+ `createWebApp apiPrefix: ${apiPrefix.unset ? "unset" : JSON.stringify(apiPrefix.value)}`,
411
+ `${origin} apiPrefix: ${JSON.stringify(expected)}`,
412
+ ],
413
+ verify: "nifra check",
414
+ }),
415
+ )
416
+ }
417
+ }
418
+ return findings
419
+ }
420
+
176
421
  /**
177
422
  * NF-C035: `backend/app.ts` exports a backend that is not served over HTTP, so a browser call to `/api`
178
423
  * reaches page routing. The framework config sets no `apiPrefix`; loader-only is a valid choice, and
179
424
  * the finding asks for it to be stated. An unreadable `apiPrefix` is NF-C027's.
425
+ *
426
+ * An app module that calls `createWebApp` itself is checked against the same value, since only the
427
+ * framework config reaches `nifra dev`: a backend it mounts at another `apiPrefix`, or with none, is
428
+ * served in production where dev never served it. No static read sees a mount another server makes,
429
+ * so `// nifra-expect NF-C035: <reason>` on the call or its `apiPrefix` line accepts the difference.
180
430
  */
181
431
  export const implicitApiMountRule: CheckRule = {
182
432
  code: "NF-C035",
@@ -190,7 +440,19 @@ export const implicitApiMountRule: CheckRule = {
190
440
  existsSync(join(ctx.root, file)) ? readFileSync(join(ctx.root, file), "utf8") : undefined
191
441
  const sources = { framework: read(FRAMEWORK_FILE), config: read(CONFIG_FILE) }
192
442
  if (sources.framework === undefined && sources.config === undefined) return []
193
- if (effectiveApiPrefix(sources).kind !== "default") return []
443
+ const effective = effectiveApiPrefix(sources)
444
+ if (effective.kind === "unreadable") return []
445
+ const configOwn = sources.config === undefined ? undefined : readStaticApiPrefix(sources.config)
446
+ const origin =
447
+ configOwn !== undefined && (configOwn.kind !== "default" || sources.framework === undefined)
448
+ ? CONFIG_FILE
449
+ : FRAMEWORK_FILE
450
+ const entries = await entryApiPrefixFindings(
451
+ ctx,
452
+ effective.kind === "literal" ? effective.value : "",
453
+ origin,
454
+ )
455
+ if (effective.kind === "literal") return entries
194
456
  const file = sources.framework === undefined ? CONFIG_FILE : FRAMEWORK_FILE
195
457
  return [
196
458
  diagnostic({
@@ -201,10 +463,126 @@ export const implicitApiMountRule: CheckRule = {
201
463
  fix: { recipe: "framework.api-prefix", command: "nifra fix --code NF-C035" },
202
464
  verify: "nifra check",
203
465
  }),
466
+ ...entries,
204
467
  ]
205
468
  },
206
469
  }
207
470
 
471
+ const COPY_MODULE = "@nifrajs/i18n/copy"
472
+ const SERVER_MANIFEST = /(?:^|\/)server-manifest(?:\.[cm]?[jt]s)?$/
473
+ const ENTRY_COPY_EXPECTATION = ["NF-C044"]
474
+
475
+ /** A `createWebApp` call that serves a client build and passes no `copyChunks`. */
476
+ export interface EntryCopyChunksGap {
477
+ readonly line: number
478
+ /** The generated server manifest the module imports from, when it does. */
479
+ readonly manifest: string | undefined
480
+ }
481
+
482
+ /**
483
+ * Every `createWebApp({ clientEntry, ... })` call in a module that passes no `copyChunks`. A call with
484
+ * no `clientEntry` ships no client build; one whose options come from a spread, a variable or a
485
+ * computed key may carry `copyChunks`, so it is left out. Pure.
486
+ */
487
+ export function entryCopyChunksGaps(
488
+ ts: typeof TSApi,
489
+ tree: TSApi.SourceFile,
490
+ ): EntryCopyChunksGap[] {
491
+ const isCreateWebApp = createWebAppCallee(ts, tree)
492
+ if (isCreateWebApp === undefined) return []
493
+ let manifest: string | undefined
494
+ for (const statement of tree.statements)
495
+ if (
496
+ manifest === undefined &&
497
+ ts.isImportDeclaration(statement) &&
498
+ ts.isStringLiteral(statement.moduleSpecifier) &&
499
+ SERVER_MANIFEST.test(statement.moduleSpecifier.text)
500
+ )
501
+ manifest = statement.moduleSpecifier.text
502
+ const gaps: EntryCopyChunksGap[] = []
503
+ const visit = (node: TSApi.Node): void => {
504
+ const arg = ts.isCallExpression(node) ? node.arguments[0] : undefined
505
+ const options = arg === undefined ? undefined : unwrapExpression(ts, arg)
506
+ if (
507
+ ts.isCallExpression(node) &&
508
+ isCreateWebApp(node.expression) &&
509
+ options !== undefined &&
510
+ ts.isObjectLiteralExpression(options)
511
+ ) {
512
+ const names = options.properties.map((property) =>
513
+ ts.isSpreadAssignment(property) ? undefined : objectPropertyName(ts, property),
514
+ )
515
+ if (
516
+ names.includes("clientEntry") &&
517
+ !names.includes("copyChunks") &&
518
+ !names.includes(undefined)
519
+ )
520
+ gaps.push({
521
+ line: tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1,
522
+ manifest,
523
+ })
524
+ }
525
+ ts.forEachChild(node, visit)
526
+ }
527
+ visit(tree)
528
+ return gaps
529
+ }
530
+
531
+ /**
532
+ * NF-C044: an app module calls `createWebApp` with a client build and no `copyChunks` while the app
533
+ * defines copy tables (`@nifrajs/i18n/copy`). A production client build moves the tables into one
534
+ * chunk per locale, which a page loads from the `copyChunks` its server lists, so the first page that
535
+ * renders copy fails. `nifra dev` never splits them, so dev and e2e pass. The split reads the source
536
+ * with the app's TypeScript compiler API, which TypeScript 7 lacks; such an app ships its tables whole,
537
+ * so it is left out.
538
+ */
539
+ export const entryCopyChunksRule: CheckRule = {
540
+ code: "NF-C044",
541
+ title: "createWebApp passes no copy chunks",
542
+ async scan(ctx) {
543
+ const scripts = ctx.sources.files.filter((file) => SCRIPT_SOURCE.test(file)).sort(codeUnitOrder)
544
+ const definer = scripts.find((file) => ctx.sources.read(file)?.includes(COPY_MODULE) === true)
545
+ if (definer === undefined) return []
546
+ const candidates = scripts.filter(
547
+ (file) => ctx.sources.read(file)?.includes("createWebApp") === true,
548
+ )
549
+ if (candidates.length === 0) return []
550
+ const ts = (await loadRuleTypeScript(ctx)).compiler
551
+ if (ts === undefined || Number.parseInt(ts.version, 10) >= 7) return []
552
+ const findings: Diagnostic[] = []
553
+ for (const file of candidates) {
554
+ const text = ctx.sources.read(file) ?? ""
555
+ const tree = ts.createSourceFile(
556
+ file,
557
+ text,
558
+ ts.ScriptTarget.Latest,
559
+ true,
560
+ scriptKindOf(ts, file),
561
+ )
562
+ const lines = text.split("\n")
563
+ for (const { line, manifest } of entryCopyChunksGaps(ts, tree)) {
564
+ if (commentBlockExpectation(lines, line, ENTRY_COPY_EXPECTATION)) continue
565
+ const pass =
566
+ manifest === undefined
567
+ ? "the `copyChunks` its `clientEntry` comes with (the generated server manifest's export, or `buildClient()`'s result)"
568
+ : `\`import { copyChunks } from "${manifest}"\``
569
+ findings.push(
570
+ diagnostic({
571
+ code: "NF-C044",
572
+ severity: "warn",
573
+ file,
574
+ line,
575
+ message: `${file} calls createWebApp with a clientEntry and no copyChunks, while ${definer} defines copy tables. A production client build moves them into one chunk per locale, and a page loads its locale's chunk from the copyChunks the server lists, so the first page that renders copy fails ("no copy chunk for locale"); \`nifra dev\` never splits them, so dev and e2e pass. Pass ${pass} and \`createWebApp({ ..., copyChunks })\`. Mark a deliberate omission with \`// nifra-expect NF-C044: <reason>\` above the call.`,
576
+ evidence: ["createWebApp copyChunks: unset", `copy tables: ${definer}`],
577
+ verify: "nifra check",
578
+ }),
579
+ )
580
+ }
581
+ }
582
+ return findings
583
+ },
584
+ }
585
+
208
586
  const appendLine = (source: string, line: string): string =>
209
587
  source === "" ? line : `${source}${source.endsWith("\n") ? "" : "\n"}${line}`
210
588
 
@@ -570,6 +948,7 @@ export const pageRules = Object.freeze([
570
948
  shadowedPageRule,
571
949
  statusLayoutRule,
572
950
  implicitApiMountRule,
951
+ entryCopyChunksRule,
573
952
  layoutMetaDataRule,
574
953
  frontendServerExportRule,
575
954
  ungatedLayoutRefusalRule,
@@ -0,0 +1,170 @@
1
+ import type * as TSApi from "typescript"
2
+ import { type Diagnostic, diagnostic } from "../diagnostics.ts"
3
+ import { scriptKindOf } from "../internal/script-kind.ts"
4
+ import type { TypeScriptApi } from "../internal/typescript-import.ts"
5
+ import { commentBlockExpectation } from "./comment-markers.ts"
6
+ import type { CheckRule } from "./index.ts"
7
+ import { loadRuleTypeScript } from "./typescript.ts"
8
+
9
+ const ROUTE_STATEMENT_EXPECTATION = ["NF-C045", "route-statement"]
10
+ const SERVER_FACTORY = /(?<![.\w$])(?:server|createWebApp)\s*\(/
11
+
12
+ /** The `Server` methods whose return type is the only place the route they add is recorded. */
13
+ const REGISTRY_METHODS: ReadonlySet<string> = new Set([
14
+ "get",
15
+ "post",
16
+ "put",
17
+ "patch",
18
+ "delete",
19
+ "sse",
20
+ "ws",
21
+ "tool",
22
+ "group",
23
+ "merge",
24
+ ])
25
+
26
+ function unwrap(ts: TypeScriptApi, node: TSApi.Expression): TSApi.Expression {
27
+ let current = node
28
+ while (
29
+ ts.isParenthesizedExpression(current) ||
30
+ ts.isAsExpression(current) ||
31
+ ts.isSatisfiesExpression(current) ||
32
+ ts.isNonNullExpression(current)
33
+ )
34
+ current = current.expression
35
+ return current
36
+ }
37
+
38
+ /** The member calls of a chain, outermost first, and the expression it starts from. */
39
+ function chainOf(
40
+ ts: TypeScriptApi,
41
+ expression: TSApi.Expression,
42
+ ): { readonly calls: readonly TSApi.CallExpression[]; readonly root: TSApi.Expression } {
43
+ const calls: TSApi.CallExpression[] = []
44
+ let current = unwrap(ts, expression)
45
+ while (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression)) {
46
+ calls.push(current)
47
+ current = unwrap(ts, current.expression.expression)
48
+ }
49
+ return { calls, root: current }
50
+ }
51
+
52
+ function isServerFactoryCall(ts: TypeScriptApi, node: TSApi.Expression): boolean {
53
+ return (
54
+ ts.isCallExpression(node) &&
55
+ ts.isIdentifier(node.expression) &&
56
+ (node.expression.text === "server" || node.expression.text === "createWebApp")
57
+ )
58
+ }
59
+
60
+ /** Names bound to a `server(...)`/`createWebApp(...)` chain whose type leaves the file: exported, or
61
+ * read by a `typeof` (the shape `client<typeof app>` and `export type App = typeof app` take). */
62
+ function typedServerBindings(ts: TypeScriptApi, tree: TSApi.SourceFile): ReadonlySet<string> {
63
+ const servers = new Set<string>()
64
+ const exported = new Set<string>()
65
+ const typed = new Set<string>()
66
+ const isExported = (modifiers: readonly TSApi.ModifierLike[] | undefined): boolean =>
67
+ modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) === true
68
+ const visit = (node: TSApi.Node): void => {
69
+ if (
70
+ ts.isVariableDeclaration(node) &&
71
+ ts.isIdentifier(node.name) &&
72
+ node.initializer !== undefined &&
73
+ isServerFactoryCall(ts, chainOf(ts, node.initializer).root)
74
+ )
75
+ servers.add(node.name.text)
76
+ else if (ts.isVariableStatement(node) && isExported(node.modifiers)) {
77
+ for (const declaration of node.declarationList.declarations)
78
+ if (ts.isIdentifier(declaration.name)) exported.add(declaration.name.text)
79
+ } else if (
80
+ ts.isExportDeclaration(node) &&
81
+ node.moduleSpecifier === undefined &&
82
+ node.exportClause !== undefined &&
83
+ ts.isNamedExports(node.exportClause)
84
+ ) {
85
+ for (const element of node.exportClause.elements)
86
+ exported.add((element.propertyName ?? element.name).text)
87
+ } else if (ts.isExportAssignment(node) && ts.isIdentifier(node.expression))
88
+ exported.add(node.expression.text)
89
+ else if (ts.isTypeQueryNode(node) && ts.isIdentifier(node.exprName))
90
+ typed.add(node.exprName.text)
91
+ ts.forEachChild(node, visit)
92
+ }
93
+ visit(tree)
94
+ return new Set([...servers].filter((name) => exported.has(name) || typed.has(name)))
95
+ }
96
+
97
+ function routeLabel(ts: TypeScriptApi, call: TSApi.CallExpression, method: string): string {
98
+ const first = call.arguments[0]
99
+ return first !== undefined && ts.isStringLiteralLike(first)
100
+ ? `${method}("${first.text}", ...)`
101
+ : `${method}(...)`
102
+ }
103
+
104
+ /**
105
+ * NF-C045: a route added to a typed server as its own statement - `app.get("/x", h)` on a line of its
106
+ * own, its result unused. Each registration returns a NEW type that records the route, so the statement
107
+ * registers the route at runtime while `typeof app` - what the typed client and an `App` export read -
108
+ * never contains it, and the client call fails to compile with no hint why. Reported only for a binding
109
+ * whose type leaves the file (exported, or read by `typeof`); a server nothing types is unaffected.
110
+ */
111
+ export const routeStatementRule: CheckRule = {
112
+ code: "NF-C045",
113
+ title: "Route registered outside the typed chain",
114
+ async scan(ctx) {
115
+ const loaded = await loadRuleTypeScript(ctx)
116
+ if (loaded.diagnostics !== undefined) return loaded.diagnostics
117
+ // Without TypeScript there is no typed client to keep in step.
118
+ const ts = loaded.compiler
119
+ if (ts === undefined) return []
120
+ const findings: Diagnostic[] = []
121
+ for (const file of ctx.project.source.files) {
122
+ if (!/\.[cm]?tsx?$/.test(file)) continue
123
+ const text = ctx.project.source.read(file)
124
+ if (text === undefined || !SERVER_FACTORY.test(text)) continue
125
+ const tree = ts.createSourceFile(
126
+ file,
127
+ text,
128
+ ts.ScriptTarget.Latest,
129
+ true,
130
+ scriptKindOf(ts, file),
131
+ )
132
+ const bindings = typedServerBindings(ts, tree)
133
+ if (bindings.size === 0) continue
134
+ const lines = text.split("\n")
135
+ for (const statement of tree.statements) {
136
+ if (!ts.isExpressionStatement(statement)) continue
137
+ const { calls, root } = chainOf(ts, statement.expression)
138
+ if (!ts.isIdentifier(root) || !bindings.has(root.text)) continue
139
+ // Innermost first: the route the statement adds before anything chained after it.
140
+ const registration = [...calls].reverse().find((call) => {
141
+ const callee = call.expression
142
+ return ts.isPropertyAccessExpression(callee) && REGISTRY_METHODS.has(callee.name.text)
143
+ })
144
+ if (registration === undefined || !ts.isPropertyAccessExpression(registration.expression))
145
+ continue
146
+ const line = tree.getLineAndCharacterOfPosition(statement.getStart(tree)).line + 1
147
+ if (commentBlockExpectation(lines, line, ROUTE_STATEMENT_EXPECTATION)?.reason !== undefined)
148
+ continue
149
+ const name = root.text
150
+ const route = routeLabel(ts, registration, registration.expression.name.text)
151
+ findings.push(
152
+ diagnostic({
153
+ code: "NF-C045",
154
+ severity: "warn",
155
+ file,
156
+ line,
157
+ message: `\`${name}.${route}\` is a statement of its own, so \`typeof ${name}\` does not include it: the route runs, but the typed client built from \`typeof ${name}\` has no such call. Chain it onto the server's declaration, or merge() a server that declares it.`,
158
+ evidence: [
159
+ "each route registration returns a new type that records the route; a discarded result drops it",
160
+ `\`${name}\` is exported or read by \`typeof\`, so its type is what a typed client sees`,
161
+ "a route kept off the type on purpose: `// nifra-expect NF-C045: <reason>` above the statement",
162
+ ],
163
+ verify: "nifra check",
164
+ }),
165
+ )
166
+ }
167
+ }
168
+ return findings
169
+ },
170
+ }
@@ -388,8 +388,9 @@ export const paramModifierRule: CheckRule = {
388
388
 
389
389
  /**
390
390
  * NF-C036: a registration whose path the static scan cannot read. The route still serves; what it
391
- * loses is every source-level analysis keyed by path - automatic capability provenance and the route
392
- * lints above - so it is reported as information, naming the expression.
391
+ * loses is every source-level analysis keyed by path - the route lints above, and the scan's half of
392
+ * capability provenance (the other half is the registering module recorded when the app loads) - so
393
+ * it is reported as information, naming the expression.
393
394
  */
394
395
  export const unresolvedRoutePathRule: CheckRule = {
395
396
  code: "NF-C036",
@@ -411,7 +412,7 @@ export const unresolvedRoutePathRule: CheckRule = {
411
412
  severity: "info",
412
413
  file: route.file,
413
414
  line: route.line,
414
- message: `${route.method} ${route.expression} - the static scan cannot read this route path, so automatic capability provenance and the route lints do not see the route. Write the path as a string literal, or as a module-level \`const\` (optionally \`as const\`) in this file or exported from a project file it imports; mark a deliberately computed path with a \`// nifra-expect NF-C036: <reason>\` comment above the registration`,
415
+ message: `${route.method} ${route.expression} - the static scan cannot read this route path, so the route lints do not see the route, and capability provenance finds its module only from the app \`nifra.assurance.ts\` loads. Write the path as a string literal, or as a module-level \`const\` (optionally \`as const\`) in this file or exported from a project file it imports; mark a deliberately computed path with a \`// nifra-expect NF-C036: <reason>\` comment above the registration`,
415
416
  evidence: [`${route.method} ${route.expression}`],
416
417
  verify: "nifra check --lints-only",
417
418
  }),
@@ -334,9 +334,10 @@ export const apiKindRule: CheckRule = {
334
334
  const PREFIX_EXPORT =
335
335
  /\bexport\s+const\s+publicEnvPrefix\s*(?::\s*string\s*)?=\s*(?:"([^"\\\r\n]*)"|'([^'\\\r\n]*)')/
336
336
 
337
- /** The app's public-env prefix when its config declares it as a string literal, else the default. */
337
+ /** The app's public-env prefix when its config declares it as a string literal, else the default.
338
+ * nifra.config.ts is read first, as `loadApp` does. */
338
339
  function publicPrefix(root: string, app: string): string {
339
- for (const config of [FRAMEWORK_FILE, CONFIG_FILE]) {
340
+ for (const config of [CONFIG_FILE, FRAMEWORK_FILE]) {
340
341
  const path = join(root, app, config)
341
342
  if (!existsSync(path)) continue
342
343
  const match = PREFIX_EXPORT.exec(stripComments(readFileSync(path, "utf8")))