@nifrajs/cli 3.3.0 → 4.0.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 (425) hide show
  1. package/README.md +42 -3
  2. package/dist/app-files.d.ts +11 -0
  3. package/dist/app-files.d.ts.map +1 -0
  4. package/dist/app-files.js +34 -0
  5. package/dist/app-files.js.map +1 -0
  6. package/dist/assure-hydration.d.ts +7 -1
  7. package/dist/assure-hydration.d.ts.map +1 -1
  8. package/dist/assure-hydration.js +128 -43
  9. package/dist/assure-hydration.js.map +1 -1
  10. package/dist/assure.d.ts.map +1 -1
  11. package/dist/assure.js +16 -2
  12. package/dist/assure.js.map +1 -1
  13. package/dist/capabilities-tool.d.ts +5 -1
  14. package/dist/capabilities-tool.d.ts.map +1 -1
  15. package/dist/capabilities-tool.js +32 -10
  16. package/dist/capabilities-tool.js.map +1 -1
  17. package/dist/cdn-check.d.ts +41 -0
  18. package/dist/cdn-check.d.ts.map +1 -0
  19. package/dist/cdn-check.js +207 -0
  20. package/dist/cdn-check.js.map +1 -0
  21. package/dist/check-diagnostics.d.ts +7 -15
  22. package/dist/check-diagnostics.d.ts.map +1 -1
  23. package/dist/check-diagnostics.js +162 -713
  24. package/dist/check-diagnostics.js.map +1 -1
  25. package/dist/check-scan.d.ts +58 -7
  26. package/dist/check-scan.d.ts.map +1 -1
  27. package/dist/check-scan.js +323 -62
  28. package/dist/check-scan.js.map +1 -1
  29. package/dist/check.d.ts +1 -0
  30. package/dist/check.d.ts.map +1 -1
  31. package/dist/check.js +145 -54
  32. package/dist/check.js.map +1 -1
  33. package/dist/cli.d.ts +42 -16
  34. package/dist/cli.d.ts.map +1 -1
  35. package/dist/cli.js +306 -87
  36. package/dist/cli.js.map +1 -1
  37. package/dist/command-catalog.d.ts +60 -5
  38. package/dist/command-catalog.d.ts.map +1 -1
  39. package/dist/command-catalog.js +298 -33
  40. package/dist/command-catalog.js.map +1 -1
  41. package/dist/config-target.d.ts +8 -0
  42. package/dist/config-target.d.ts.map +1 -0
  43. package/dist/config-target.js +45 -0
  44. package/dist/config-target.js.map +1 -0
  45. package/dist/contracts.d.ts +3 -2
  46. package/dist/contracts.d.ts.map +1 -1
  47. package/dist/contracts.js +56 -16
  48. package/dist/contracts.js.map +1 -1
  49. package/dist/db-audit.d.ts +37 -0
  50. package/dist/db-audit.d.ts.map +1 -0
  51. package/dist/db-audit.js +99 -0
  52. package/dist/db-audit.js.map +1 -0
  53. package/dist/db-child.d.ts +64 -0
  54. package/dist/db-child.d.ts.map +1 -0
  55. package/dist/db-child.js +213 -0
  56. package/dist/db-child.js.map +1 -0
  57. package/dist/db-config.d.ts +60 -0
  58. package/dist/db-config.d.ts.map +1 -0
  59. package/dist/db-config.js +176 -0
  60. package/dist/db-config.js.map +1 -0
  61. package/dist/db-tool.d.ts +84 -0
  62. package/dist/db-tool.d.ts.map +1 -0
  63. package/dist/db-tool.js +537 -0
  64. package/dist/db-tool.js.map +1 -0
  65. package/dist/dev-bun-config.d.ts +20 -13
  66. package/dist/dev-bun-config.d.ts.map +1 -1
  67. package/dist/dev-bun-config.js +98 -41
  68. package/dist/dev-bun-config.js.map +1 -1
  69. package/dist/dev-feed-tool.d.ts +106 -0
  70. package/dist/dev-feed-tool.d.ts.map +1 -0
  71. package/dist/dev-feed-tool.js +713 -0
  72. package/dist/dev-feed-tool.js.map +1 -0
  73. package/dist/dev-server-client.d.ts +67 -0
  74. package/dist/dev-server-client.d.ts.map +1 -0
  75. package/dist/dev-server-client.js +195 -0
  76. package/dist/dev-server-client.js.map +1 -0
  77. package/dist/diagnostics.d.ts +86 -0
  78. package/dist/diagnostics.d.ts.map +1 -1
  79. package/dist/diagnostics.js +85 -0
  80. package/dist/diagnostics.js.map +1 -1
  81. package/dist/diff-tool.d.ts +3 -3
  82. package/dist/diff-tool.d.ts.map +1 -1
  83. package/dist/diff-tool.js +6 -5
  84. package/dist/diff-tool.js.map +1 -1
  85. package/dist/docs-search.d.ts.map +1 -1
  86. package/dist/docs-search.js +12 -4
  87. package/dist/docs-search.js.map +1 -1
  88. package/dist/doctor.d.ts +17 -0
  89. package/dist/doctor.d.ts.map +1 -1
  90. package/dist/doctor.js +76 -15
  91. package/dist/doctor.js.map +1 -1
  92. package/dist/env-file.d.ts +15 -0
  93. package/dist/env-file.d.ts.map +1 -1
  94. package/dist/env-file.js +73 -1
  95. package/dist/env-file.js.map +1 -1
  96. package/dist/fix-recipes.d.ts.map +1 -1
  97. package/dist/fix-recipes.js +41 -21
  98. package/dist/fix-recipes.js.map +1 -1
  99. package/dist/frontend-guidance.js +5 -5
  100. package/dist/frontend-guidance.js.map +1 -1
  101. package/dist/i18n-check.d.ts +16 -0
  102. package/dist/i18n-check.d.ts.map +1 -0
  103. package/dist/i18n-check.js +154 -0
  104. package/dist/i18n-check.js.map +1 -0
  105. package/dist/init-agents.d.ts +49 -13
  106. package/dist/init-agents.d.ts.map +1 -1
  107. package/dist/init-agents.js +239 -34
  108. package/dist/init-agents.js.map +1 -1
  109. package/dist/internal/code-unit-order.d.ts +4 -0
  110. package/dist/internal/code-unit-order.d.ts.map +1 -0
  111. package/dist/internal/code-unit-order.js +6 -0
  112. package/dist/internal/code-unit-order.js.map +1 -0
  113. package/dist/internal/script-kind.d.ts +7 -0
  114. package/dist/internal/script-kind.d.ts.map +1 -0
  115. package/dist/internal/script-kind.js +12 -0
  116. package/dist/internal/script-kind.js.map +1 -0
  117. package/dist/internal/source-facts.d.ts +5 -0
  118. package/dist/internal/source-facts.d.ts.map +1 -1
  119. package/dist/internal/source-facts.js +61 -5
  120. package/dist/internal/source-facts.js.map +1 -1
  121. package/dist/internal/typescript-import.d.ts +49 -24
  122. package/dist/internal/typescript-import.d.ts.map +1 -1
  123. package/dist/internal/typescript-import.js +507 -67
  124. package/dist/internal/typescript-import.js.map +1 -1
  125. package/dist/introspect.d.ts +6 -4
  126. package/dist/introspect.d.ts.map +1 -1
  127. package/dist/introspect.js +93 -74
  128. package/dist/introspect.js.map +1 -1
  129. package/dist/learn.js +3 -3
  130. package/dist/learn.js.map +1 -1
  131. package/dist/levels-tool.d.ts +10 -0
  132. package/dist/levels-tool.d.ts.map +1 -1
  133. package/dist/levels-tool.js +33 -3
  134. package/dist/levels-tool.js.map +1 -1
  135. package/dist/load.d.ts +71 -16
  136. package/dist/load.d.ts.map +1 -1
  137. package/dist/load.js +78 -18
  138. package/dist/load.js.map +1 -1
  139. package/dist/manifest-tool.d.ts.map +1 -1
  140. package/dist/manifest-tool.js +3 -2
  141. package/dist/manifest-tool.js.map +1 -1
  142. package/dist/mcp-app-tool.d.ts.map +1 -1
  143. package/dist/mcp-app-tool.js +2 -0
  144. package/dist/mcp-app-tool.js.map +1 -1
  145. package/dist/mcp-context.d.ts.map +1 -1
  146. package/dist/mcp-context.js +5 -6
  147. package/dist/mcp-context.js.map +1 -1
  148. package/dist/mcp-delegate.d.ts +57 -0
  149. package/dist/mcp-delegate.d.ts.map +1 -0
  150. package/dist/mcp-delegate.js +130 -0
  151. package/dist/mcp-delegate.js.map +1 -0
  152. package/dist/mcp-docs-tools.d.ts.map +1 -1
  153. package/dist/mcp-docs-tools.js +23 -5
  154. package/dist/mcp-docs-tools.js.map +1 -1
  155. package/dist/mcp-exec.d.ts +3 -0
  156. package/dist/mcp-exec.d.ts.map +1 -1
  157. package/dist/mcp-exec.js +263 -131
  158. package/dist/mcp-exec.js.map +1 -1
  159. package/dist/mcp-http.d.ts.map +1 -1
  160. package/dist/mcp-http.js +20 -5
  161. package/dist/mcp-http.js.map +1 -1
  162. package/dist/mcp-io.d.ts +26 -0
  163. package/dist/mcp-io.d.ts.map +1 -1
  164. package/dist/mcp-io.js +113 -0
  165. package/dist/mcp-io.js.map +1 -1
  166. package/dist/mcp-isolate.d.ts +48 -0
  167. package/dist/mcp-isolate.d.ts.map +1 -0
  168. package/dist/mcp-isolate.js +222 -0
  169. package/dist/mcp-isolate.js.map +1 -0
  170. package/dist/mcp-path.d.ts +10 -0
  171. package/dist/mcp-path.d.ts.map +1 -0
  172. package/dist/mcp-path.js +51 -0
  173. package/dist/mcp-path.js.map +1 -0
  174. package/dist/mcp-project-child.d.ts +74 -0
  175. package/dist/mcp-project-child.d.ts.map +1 -0
  176. package/dist/mcp-project-child.js +130 -0
  177. package/dist/mcp-project-child.js.map +1 -0
  178. package/dist/mcp-reflect.d.ts.map +1 -1
  179. package/dist/mcp-reflect.js +2 -2
  180. package/dist/mcp-reflect.js.map +1 -1
  181. package/dist/mcp-render.d.ts.map +1 -1
  182. package/dist/mcp-render.js +64 -45
  183. package/dist/mcp-render.js.map +1 -1
  184. package/dist/mcp-root.d.ts +37 -9
  185. package/dist/mcp-root.d.ts.map +1 -1
  186. package/dist/mcp-root.js +124 -25
  187. package/dist/mcp-root.js.map +1 -1
  188. package/dist/mcp-run.d.ts +18 -1
  189. package/dist/mcp-run.d.ts.map +1 -1
  190. package/dist/mcp-run.js +159 -55
  191. package/dist/mcp-run.js.map +1 -1
  192. package/dist/mcp-ws.js +4 -1
  193. package/dist/mcp-ws.js.map +1 -1
  194. package/dist/mcp.d.ts +18 -5
  195. package/dist/mcp.d.ts.map +1 -1
  196. package/dist/mcp.js +165 -82
  197. package/dist/mcp.js.map +1 -1
  198. package/dist/migrate-layout.d.ts +44 -0
  199. package/dist/migrate-layout.d.ts.map +1 -0
  200. package/dist/migrate-layout.js +982 -0
  201. package/dist/migrate-layout.js.map +1 -0
  202. package/dist/openapi-tool.d.ts +2 -2
  203. package/dist/openapi-tool.d.ts.map +1 -1
  204. package/dist/openapi-tool.js.map +1 -1
  205. package/dist/openapi-types.d.ts +2 -1
  206. package/dist/openapi-types.d.ts.map +1 -1
  207. package/dist/openapi-types.js +240 -12
  208. package/dist/openapi-types.js.map +1 -1
  209. package/dist/pipeline-report.d.ts +3 -2
  210. package/dist/pipeline-report.d.ts.map +1 -1
  211. package/dist/pipeline-report.js +19 -16
  212. package/dist/pipeline-report.js.map +1 -1
  213. package/dist/port.d.ts +5 -4
  214. package/dist/port.d.ts.map +1 -1
  215. package/dist/port.js +46 -29
  216. package/dist/port.js.map +1 -1
  217. package/dist/project-facts.d.ts +28 -4
  218. package/dist/project-facts.d.ts.map +1 -1
  219. package/dist/project-facts.js +12 -2
  220. package/dist/project-facts.js.map +1 -1
  221. package/dist/recipes/4.0.0.d.ts +9 -0
  222. package/dist/recipes/4.0.0.d.ts.map +1 -0
  223. package/dist/recipes/4.0.0.js +34 -0
  224. package/dist/recipes/4.0.0.js.map +1 -0
  225. package/dist/recipes/index.d.ts.map +1 -1
  226. package/dist/recipes/index.js +2 -0
  227. package/dist/recipes/index.js.map +1 -1
  228. package/dist/release-verification.d.ts +11 -1
  229. package/dist/release-verification.d.ts.map +1 -1
  230. package/dist/release-verification.js +47 -4
  231. package/dist/release-verification.js.map +1 -1
  232. package/dist/review.d.ts +21 -0
  233. package/dist/review.d.ts.map +1 -0
  234. package/dist/review.js +823 -0
  235. package/dist/review.js.map +1 -0
  236. package/dist/route-types.d.ts +28 -0
  237. package/dist/route-types.d.ts.map +1 -0
  238. package/dist/route-types.js +106 -0
  239. package/dist/route-types.js.map +1 -0
  240. package/dist/rules/codes.d.ts +9 -0
  241. package/dist/rules/codes.d.ts.map +1 -1
  242. package/dist/rules/codes.js +9 -0
  243. package/dist/rules/codes.js.map +1 -1
  244. package/dist/rules/data-guard.d.ts +12 -0
  245. package/dist/rules/data-guard.d.ts.map +1 -0
  246. package/dist/rules/data-guard.js +213 -0
  247. package/dist/rules/data-guard.js.map +1 -0
  248. package/dist/rules/index.d.ts +3 -0
  249. package/dist/rules/index.d.ts.map +1 -1
  250. package/dist/rules/index.js +17 -5
  251. package/dist/rules/index.js.map +1 -1
  252. package/dist/rules/islands.d.ts.map +1 -1
  253. package/dist/rules/islands.js +7 -4
  254. package/dist/rules/islands.js.map +1 -1
  255. package/dist/rules/legacy.d.ts +3 -1
  256. package/dist/rules/legacy.d.ts.map +1 -1
  257. package/dist/rules/legacy.js +829 -34
  258. package/dist/rules/legacy.js.map +1 -1
  259. package/dist/rules/nano.d.ts.map +1 -1
  260. package/dist/rules/nano.js +15 -6
  261. package/dist/rules/nano.js.map +1 -1
  262. package/dist/rules/pages.d.ts +15 -0
  263. package/dist/rules/pages.d.ts.map +1 -0
  264. package/dist/rules/pages.js +88 -0
  265. package/dist/rules/pages.js.map +1 -0
  266. package/dist/rules/routes.d.ts +11 -0
  267. package/dist/rules/routes.d.ts.map +1 -1
  268. package/dist/rules/routes.js +180 -2
  269. package/dist/rules/routes.js.map +1 -1
  270. package/dist/rules/secrets.d.ts +10 -0
  271. package/dist/rules/secrets.d.ts.map +1 -0
  272. package/dist/rules/secrets.js +169 -0
  273. package/dist/rules/secrets.js.map +1 -0
  274. package/dist/rules/security.d.ts +7 -0
  275. package/dist/rules/security.d.ts.map +1 -1
  276. package/dist/rules/security.js +171 -65
  277. package/dist/rules/security.js.map +1 -1
  278. package/dist/rules/typescript.d.ts +16 -0
  279. package/dist/rules/typescript.d.ts.map +1 -0
  280. package/dist/rules/typescript.js +59 -0
  281. package/dist/rules/typescript.js.map +1 -0
  282. package/dist/rules/zones.d.ts +17 -0
  283. package/dist/rules/zones.d.ts.map +1 -0
  284. package/dist/rules/zones.js +174 -0
  285. package/dist/rules/zones.js.map +1 -0
  286. package/dist/scaffold.d.ts +25 -12
  287. package/dist/scaffold.d.ts.map +1 -1
  288. package/dist/scaffold.js +154 -90
  289. package/dist/scaffold.js.map +1 -1
  290. package/dist/sdk.d.ts +17 -3
  291. package/dist/sdk.d.ts.map +1 -1
  292. package/dist/sdk.js +941 -153
  293. package/dist/sdk.js.map +1 -1
  294. package/dist/search-terms.d.ts +2 -0
  295. package/dist/search-terms.d.ts.map +1 -1
  296. package/dist/search-terms.js +23 -8
  297. package/dist/search-terms.js.map +1 -1
  298. package/dist/smoke.d.ts +79 -0
  299. package/dist/smoke.d.ts.map +1 -0
  300. package/dist/smoke.js +494 -0
  301. package/dist/smoke.js.map +1 -0
  302. package/dist/sync-manifest.d.ts.map +1 -1
  303. package/dist/sync-manifest.js +2 -1
  304. package/dist/sync-manifest.js.map +1 -1
  305. package/dist/sync-routes.d.ts +4 -3
  306. package/dist/sync-routes.d.ts.map +1 -1
  307. package/dist/sync-routes.js +4 -3
  308. package/dist/sync-routes.js.map +1 -1
  309. package/dist/test-tool.d.ts.map +1 -1
  310. package/dist/test-tool.js +30 -11
  311. package/dist/test-tool.js.map +1 -1
  312. package/dist/types-search.d.ts.map +1 -1
  313. package/dist/types-search.js +11 -5
  314. package/dist/types-search.js.map +1 -1
  315. package/dist/upgrade.d.ts +36 -6
  316. package/dist/upgrade.d.ts.map +1 -1
  317. package/dist/upgrade.js +167 -29
  318. package/dist/upgrade.js.map +1 -1
  319. package/dist/verification-plan.d.ts.map +1 -1
  320. package/dist/verification-plan.js +8 -0
  321. package/dist/verification-plan.js.map +1 -1
  322. package/dist/verification.d.ts.map +1 -1
  323. package/dist/verification.js +45 -12
  324. package/dist/verification.js.map +1 -1
  325. package/dist/web-app-options.d.ts +19 -0
  326. package/dist/web-app-options.d.ts.map +1 -0
  327. package/dist/web-app-options.js +49 -0
  328. package/dist/web-app-options.js.map +1 -0
  329. package/dist/work-graph.d.ts +3 -0
  330. package/dist/work-graph.d.ts.map +1 -1
  331. package/dist/work-graph.js +33 -16
  332. package/dist/work-graph.js.map +1 -1
  333. package/docs/examples.json +185 -29
  334. package/docs/llms-full.txt +4123 -548
  335. package/docs/types.json +14391 -10060
  336. package/package.json +19 -11
  337. package/src/app-files.ts +40 -0
  338. package/src/assure-hydration.ts +139 -46
  339. package/src/assure.ts +17 -2
  340. package/src/capabilities-tool.ts +35 -9
  341. package/src/cdn-check.ts +268 -0
  342. package/src/check-diagnostics.ts +199 -797
  343. package/src/check-scan.ts +394 -63
  344. package/src/check.ts +146 -58
  345. package/src/cli.ts +347 -92
  346. package/src/command-catalog.ts +407 -45
  347. package/src/config-target.ts +47 -0
  348. package/src/contracts.ts +66 -15
  349. package/src/db-audit.ts +128 -0
  350. package/src/db-child.ts +285 -0
  351. package/src/db-config.ts +224 -0
  352. package/src/db-tool.ts +690 -0
  353. package/src/dev-bun-config.ts +116 -40
  354. package/src/dev-feed-tool.ts +912 -0
  355. package/src/dev-server-client.ts +267 -0
  356. package/src/diagnostics.ts +179 -0
  357. package/src/diff-tool.ts +6 -5
  358. package/src/docs-search.ts +10 -3
  359. package/src/doctor.ts +98 -15
  360. package/src/env-file.ts +78 -1
  361. package/src/fix-recipes.ts +44 -31
  362. package/src/frontend-guidance.ts +5 -5
  363. package/src/i18n-check.ts +179 -0
  364. package/src/init-agents.ts +301 -38
  365. package/src/internal/code-unit-order.ts +5 -0
  366. package/src/internal/script-kind.ts +11 -0
  367. package/src/internal/source-facts.ts +96 -22
  368. package/src/internal/typescript-import.ts +663 -68
  369. package/src/introspect.ts +93 -82
  370. package/src/learn.ts +3 -3
  371. package/src/levels-tool.ts +47 -2
  372. package/src/load.ts +144 -32
  373. package/src/manifest-tool.ts +3 -2
  374. package/src/mcp-app-tool.ts +2 -0
  375. package/src/mcp-context.ts +5 -7
  376. package/src/mcp-delegate.ts +162 -0
  377. package/src/mcp-docs-tools.ts +23 -5
  378. package/src/mcp-exec.ts +301 -161
  379. package/src/mcp-http.ts +22 -5
  380. package/src/mcp-io.ts +130 -0
  381. package/src/mcp-isolate.ts +287 -0
  382. package/src/mcp-path.ts +50 -0
  383. package/src/mcp-project-child.ts +182 -0
  384. package/src/mcp-reflect.ts +3 -2
  385. package/src/mcp-render.ts +72 -42
  386. package/src/mcp-root.ts +130 -24
  387. package/src/mcp-run.ts +190 -56
  388. package/src/mcp-ws.ts +4 -1
  389. package/src/mcp.ts +193 -91
  390. package/src/migrate-layout.ts +1121 -0
  391. package/src/openapi-tool.ts +7 -3
  392. package/src/openapi-types.ts +315 -13
  393. package/src/pipeline-report.ts +22 -18
  394. package/src/port.ts +53 -30
  395. package/src/project-facts.ts +42 -8
  396. package/src/recipes/4.0.0.ts +35 -0
  397. package/src/recipes/index.ts +2 -0
  398. package/src/release-verification.ts +74 -5
  399. package/src/review.ts +988 -0
  400. package/src/route-types.ts +133 -0
  401. package/src/rules/codes.ts +9 -0
  402. package/src/rules/data-guard.ts +230 -0
  403. package/src/rules/index.ts +18 -5
  404. package/src/rules/islands.ts +12 -4
  405. package/src/rules/legacy.ts +947 -35
  406. package/src/rules/nano.ts +18 -6
  407. package/src/rules/pages.ts +99 -0
  408. package/src/rules/routes.ts +181 -2
  409. package/src/rules/secrets.ts +174 -0
  410. package/src/rules/security.ts +198 -70
  411. package/src/rules/typescript.ts +77 -0
  412. package/src/rules/zones.ts +195 -0
  413. package/src/scaffold.ts +175 -98
  414. package/src/sdk.ts +1215 -158
  415. package/src/search-terms.ts +24 -7
  416. package/src/smoke.ts +607 -0
  417. package/src/sync-manifest.ts +2 -1
  418. package/src/sync-routes.ts +4 -3
  419. package/src/test-tool.ts +32 -11
  420. package/src/types-search.ts +11 -4
  421. package/src/upgrade.ts +205 -25
  422. package/src/verification-plan.ts +27 -0
  423. package/src/verification.ts +50 -12
  424. package/src/web-app-options.ts +57 -0
  425. package/src/work-graph.ts +40 -16
@@ -5,19 +5,19 @@
5
5
  * structured diagnostic views. The CLI, JSON output, and MCP all consume the resulting CheckResult.
6
6
  */
7
7
  import { existsSync } from "node:fs";
8
- import { join, resolve } from "node:path";
9
- import { snapshotProjectEvidence } from "@nifrajs/core/evidence";
10
- import { SINGLE_COPY_REGISTER_SPECIFIER } from "@nifrajs/core/single-copy";
11
- import { IDENT, parseSimpleFetchCall, REMOVED_IMPORTS, SIMPLE_REWRITE_METHODS, } from "./check-scan.js";
12
- import { diagnostic } from "./diagnostics.js";
8
+ import { join } from "node:path";
9
+ import { diagnostic, diagnosticCompatibilityOf, } from "./diagnostics.js";
13
10
  import { freezeProjectFacts } from "./project-facts.js";
11
+ import { dataGuardRules } from "./rules/data-guard.js";
14
12
  import { parseRulePacks, runRuleRegistry } from "./rules/index.js";
15
13
  import { islandRules } from "./rules/islands.js";
16
- import { LEGACY_RULE_CODES, legacyRules } from "./rules/legacy.js";
14
+ import { LEGACY_RULE_CODES, LEGACY_RULE_ORDER, legacyRules } from "./rules/legacy.js";
17
15
  import { nanoRules } from "./rules/nano.js";
16
+ import { pageRules } from "./rules/pages.js";
18
17
  import { routeRules } from "./rules/routes.js";
18
+ import { secretRules } from "./rules/secrets.js";
19
19
  import { securityRules } from "./rules/security.js";
20
- const TSC_LINE = /^(.+?)\((\d+),\d+\):\s*(?:error|warning)\s+TS\d+:\s*(.+)$/;
20
+ import { zoneRules } from "./rules/zones.js";
21
21
  const MAX_IGNORE_GLOB_LENGTH = 4096;
22
22
  const MAX_IGNORE_GLOB_ALTERNATIVES = 64;
23
23
  /**
@@ -216,676 +216,51 @@ function matchIgnoreGlobClass(spec, value) {
216
216
  }
217
217
  return negated ? !matched : matched;
218
218
  }
219
- const UNTYPED_CLIENT_HINT = 'client("…") without a type argument - write client<typeof app>("…") (or client(contract, url)) so the compiler can catch drift';
220
- const FETCH_HINT = "hand-rolled fetch() to your own API - call it through client<typeof app> (from @nifrajs/client) so the compiler catches drift";
221
- const SERVER_IMPORT_HINT = "server-only import in a route module (bundled for the browser) - reach it via c.db / ctx.api inside a loader, never a top-level import";
222
- const RESPONSE_ROUTE_HINT = "route handler returns a raw Response - the typed client infers `data: never`, so drift detection is lost for this route. Return a plain object (it's serialized for you); for a stream use a typed SSE route (`app.sse(...)`), which keeps typed events; or, if a raw Response is intended (file/redirect), add `{ response: t.… }` or a `// nifra-expect raw-response` comment to mark it and silence this";
223
- const PIPELINE_DOC_HINT = "nifra runs one bundler per phase - `vitePlugins` feed Vite, `clientPlugins`/`serverPlugins` feed Bun, and the file `nifra build` imports the adapter from is bundled into the server. See the Gotchas section of the Dev & HMR guide.";
224
- const UNDECLARED_DEP_HINT = "imported package is not declared in package.json dependencies - run bun add to declare it";
225
- const SQL_COMPILER_MISSING_HINT = "the interpolated-SQL rule did NOT run - it parses source with the TypeScript compiler, which is an optional peer and is not installed here. This report says nothing about SQL injection either way. Install it with `bun add -d typescript`";
226
- const SQL_INTERPOLATION_EXAMPLE = "$" + "{value}";
227
- const INTERPOLATED_SQL_HINT = `SQL built by interpolating a value into the statement text - the value becomes statement, not a parameter, so anything the caller controls can end the literal and continue as SQL. Pass it as a bound parameter (\`?\` / \`$1\` and an argument), or use your driver's tagged template (sql\`… ${SQL_INTERPOLATION_EXAMPLE} …\`), which binds the substitutions for you`;
228
- const MANIFEST_DRIFT_HINT = "server-manifest.ts is out of sync with routes/ - re-run the build to regenerate it (a disk-less worker bakes this route table, so the drift is a silent edge break), then commit it";
229
- const TRUST_MANIFEST_DRIFT_HINT = "nifra.manifest.json is missing, invalid, or out of sync - run `nifra manifest emit`, review it, and commit the regenerated trust artifact";
230
- const CAPABILITY_HINT = "effect/capability assurance failed - align the route declaration with approved adapter provenance; never bypass an owned effect seam";
231
- const bySite = (a, b) => a.file.localeCompare(b.file) || a.line - b.line;
232
- function oneLineDiff(file, line, before, after) {
233
- return `--- ${file}:${line}\n+++ ${file}:${line}\n@@\n-${before}\n+${after}`;
234
- }
235
- function untypedClientSuggestion(f) {
236
- const replacement = f.snippet.replace(/(?<![.\w])client\s*\(/, "client<typeof app>(");
237
- return replacement === f.snippet
238
- ? {
239
- kind: "manual",
240
- title: "Add the app type argument to the client factory",
241
- steps: [
242
- 'Change `client("...")` to `client<typeof app>("...")`.',
243
- "Make sure the backend app type is imported or otherwise in scope.",
244
- ],
245
- }
246
- : {
247
- kind: "edit",
248
- title: "Insert `<typeof app>` into the client factory call",
249
- diff: oneLineDiff(f.file, f.line, f.snippet, replacement),
250
- steps: ["Make sure the backend app type is imported or otherwise in scope."],
251
- };
252
- }
253
- function routeKey(method, path) {
254
- return `${method.toUpperCase()} ${path}`;
255
- }
256
- function typedClientCall(method, path) {
257
- const segs = path.split("/").filter((seg) => seg !== "");
258
- let chain = "api";
259
- if (segs.length === 0)
260
- chain += ".index";
261
- else {
262
- for (const seg of segs) {
263
- chain += IDENT.test(seg) ? `.${seg}` : `[${JSON.stringify(seg)}]`;
264
- }
265
- }
266
- return `${chain}.${method.toLowerCase()}()`;
267
- }
268
- function staticRouteMap(routes) {
269
- const out = new Map();
270
- for (const route of routes) {
271
- if (route.path.includes(":") || route.path.includes("*"))
272
- continue;
273
- const key = routeKey(route.method, route.path);
274
- const bucket = out.get(key);
275
- if (bucket === undefined)
276
- out.set(key, [route]);
277
- else
278
- bucket.push(route);
279
- }
280
- return out;
281
- }
282
- function ownFetchEditSuggestion(f, routes) {
283
- const call = parseSimpleFetchCall(f.snippet);
284
- if (call === undefined || !SIMPLE_REWRITE_METHODS.has(call.method))
285
- return undefined;
286
- const matches = routes.get(routeKey(call.method, call.path));
287
- if (matches === undefined || matches.length !== 1)
288
- return undefined;
289
- const replacementCall = typedClientCall(call.method, call.path);
290
- const replacement = `${f.snippet.slice(0, call.start)}${replacementCall}${f.snippet.slice(call.end)}`;
291
- if (replacement === f.snippet)
292
- return undefined;
293
- const route = matches[0];
294
- if (route === undefined)
295
- return undefined;
296
- return {
297
- kind: "edit",
298
- title: "Rewrite simple own-API fetch to the typed nifra client",
299
- diff: oneLineDiff(f.file, f.line, f.snippet, replacement),
300
- steps: [
301
- `Matched ${route.method} ${route.path} at ${route.file}:${route.line}.`,
302
- "Use an in-scope typed client named `api` (`client<typeof app>(baseUrl)` or the route loader/action `api`).",
303
- "Update downstream `Response` handling to branch on `{ ok, data, error }` if this variable is used later.",
304
- ],
305
- };
306
- }
307
- function ownFetchSuggestion(f, routes) {
308
- const exact = ownFetchEditSuggestion(f, routes);
309
- if (exact !== undefined)
310
- return exact;
311
- return {
312
- kind: "manual",
313
- title: "Replace own-API fetch with the typed nifra client",
314
- steps: [
315
- "Call `nifra_routes` or read `nifra://routes` for the exact typed-client call form.",
316
- "Create `const api = client<typeof app>(baseUrl)` from `@nifrajs/client`.",
317
- "Replace the relative `fetch()` call with the generated `api...get/post/...` call and branch on `{ ok, data, error }`.",
318
- ],
319
- };
320
- }
321
- function serverImportSuggestion(specifier, chain, fallback) {
322
- const sink = chain[chain.length - 1] ?? specifier;
323
- // Surface the resolved chain in the fix steps so the agent sees the full path (`route → ../data →
324
- // ../db → node:crypto`) and which module to cut - not just the route's own top-level import.
325
- const chainStep = chain.length > 2
326
- ? fallback
327
- ? `Server-only code reaches this route through \`${chain.join(" → ")}\` (the deeper chain couldn't be resolved precisely - trace it from \`${specifier}\`).`
328
- : `Server-only code reaches this route transitively: \`${chain.join(" → ")}\`. The sink is \`${sink}\`; break the chain at the first hop (\`${specifier}\`) or move the sink behind the server boundary.`
329
- : undefined;
330
- return {
331
- kind: "manual",
332
- title: "Move server-only code behind the route server boundary",
333
- steps: [
334
- ...(chainStep !== undefined ? [chainStep] : []),
335
- `Remove the top-level \`import … from "${specifier}"\` from this route module (it's bundled for the browser).`,
336
- "Access backend/data work through the route `loader`/`action` context (`api`, `env`, or project server context).",
337
- `If a direct module import is unavoidable, lazy-load it (\`await import("${specifier}")\`) inside the server-only loader/action path.`,
338
- ],
339
- };
340
- }
341
- function responseRouteSuggestion() {
342
- return {
343
- kind: "manual",
344
- title: "Preserve typed-client response inference",
345
- steps: [
346
- "Prefer returning a plain object from JSON routes; nifra serializes it for you.",
347
- "For a stream, use a typed SSE route - `app.sse(...)` (or `sse(c, run)` from `@nifrajs/core/server`) - which keeps typed events instead of collapsing the client to `data: never`.",
348
- "If this route must return a raw Response (redirect, file), declare an explicit response schema, or add a `// nifra-expect raw-response` comment above the return to mark it intentional and silence this advisory.",
349
- ],
350
- };
351
- }
352
219
  export async function collectCheckDiagnostics(cwd, scan, opts = {}) {
353
- const factsSeed = scan.facts;
354
- const { fetches, untypedClients, removedImports, responseRoutes, interpolatedSql } = factsSeed.sourceFindings;
355
- const staticRoutes = factsSeed.routes;
356
- const serverImports = factsSeed.importGraph;
357
- const { doctor: dr, manifestDrift } = factsSeed.packages;
358
- const { checkConfig } = factsSeed.policies;
359
- const tc = scan.typecheck;
360
- const sqlCompiler = scan.sqlCompiler;
361
- const checkConfigError = scan.checkConfigError;
362
- const checkConfigWarnings = scan.checkConfigWarnings;
363
- const diagnostics = [];
364
- const structuredExtras = [];
365
- if (checkConfigError !== undefined) {
366
- diagnostics.push({
367
- rule: "check-config",
368
- severity: "warning",
369
- file: "nifra.check.json",
370
- message: `nifra.check.json could not be parsed (${checkConfigError}) - its external-mount allowlist was ignored`,
371
- fix: "Fix the JSON syntax in nifra.check.json",
372
- });
373
- }
374
- for (const warning of checkConfigWarnings) {
375
- diagnostics.push({
376
- rule: "check-config",
377
- severity: "warning",
378
- file: "nifra.check.json",
379
- message: `nifra.check.json: ${warning}`,
380
- fix: "Fix the entry in nifra.check.json",
381
- });
382
- }
383
- if (tc.missingTypeScript === true) {
384
- // A tsconfig with no reachable `typescript` install is a broken gate, not a benign skip: the
385
- // contract check the project asked for (by having a tsconfig) silently didn't run. Fail closed.
386
- diagnostics.push({
387
- rule: "typecheck",
388
- severity: "error",
389
- file: "tsconfig.json",
390
- message: "tsconfig.json is present but no `typescript` install was found from this directory upward - the typecheck gate did NOT run",
391
- fix: "bun add -d typescript",
392
- suggestion: {
393
- kind: "command",
394
- title: "Install TypeScript so the contract gate can run",
395
- command: ["bun", "add", "-d", "typescript"],
396
- },
397
- });
398
- }
399
- if (tc.ran && !tc.ok) {
400
- const lines = (tc.output ?? "").split("\n");
401
- let matched = false;
402
- for (const l of lines) {
403
- const m = TSC_LINE.exec(l.trim());
404
- if (m) {
405
- matched = true;
406
- diagnostics.push({
407
- rule: "typecheck",
408
- severity: "error",
409
- file: m[1],
410
- line: Number(m[2]),
411
- message: m[3],
412
- suggestion: {
413
- kind: "manual",
414
- title: "Fix the TypeScript contract error",
415
- steps: [
416
- "Open the reported file and line.",
417
- "Align the handler, route schema, or typed-client call with the compiler error.",
418
- "Run `nifra_check` again after the edit.",
419
- ],
420
- },
421
- });
422
- }
423
- }
424
- if (!matched)
425
- diagnostics.push({
426
- rule: "typecheck",
427
- severity: "error",
428
- message: tc.output || "typecheck failed",
429
- suggestion: {
430
- kind: "manual",
431
- title: "Fix the TypeScript contract error",
432
- steps: ["Run `tsc --noEmit` locally for the full compiler output."],
433
- },
434
- });
435
- }
436
- const routes = staticRouteMap(staticRoutes);
437
- for (const f of [...fetches].sort(bySite)) {
438
- diagnostics.push({
439
- rule: "typed-client",
440
- severity: "error",
441
- file: f.file,
442
- line: f.line,
443
- message: `${f.snippet} - ${FETCH_HINT}`,
444
- fix: FETCH_HINT,
445
- suggestion: ownFetchSuggestion(f, routes),
446
- });
447
- }
448
- for (const f of [...removedImports].sort(bySite)) {
449
- const entry = REMOVED_IMPORTS.find((candidate) => f.snippet.includes(`"${candidate.specifier}`) ||
450
- f.snippet.includes(`'${candidate.specifier}`));
451
- diagnostics.push({
452
- rule: "removed-import",
453
- severity: "error",
454
- file: f.file,
455
- line: f.line,
456
- message: `${f.snippet} - removed in nifra ${entry?.since ?? "2.0"}: ${entry?.replacement ?? "see the changelog"}`,
457
- fix: entry?.replacement ?? "see the changelog",
458
- });
459
- }
460
- for (const f of [...untypedClients].sort(bySite)) {
461
- diagnostics.push({
462
- rule: "untyped-client",
463
- severity: "error",
464
- file: f.file,
465
- line: f.line,
466
- message: `${f.snippet} - ${UNTYPED_CLIENT_HINT}`,
467
- fix: UNTYPED_CLIENT_HINT,
468
- suggestion: untypedClientSuggestion(f),
469
- });
470
- }
471
- for (const f of [...serverImports].sort(bySite)) {
472
- // #4.4: the FULL transitive chain the import-resolution walk found - `route → ../data → ../db →
473
- // node:crypto`, matching the build leak-guard's depth - instead of just the direct edge. The chain's
474
- // tail is the actual server-only sink; the head is the route. When a precise resolve wasn't possible
475
- // (a bare pkg / path alias), `fallback` is set and the chain degrades to the honest direct edge.
476
- const chain = f.chain;
477
- const sink = chain[chain.length - 1] ?? f.specifier;
478
- diagnostics.push({
479
- rule: "server-only-import",
480
- severity: "error",
481
- file: f.file,
482
- line: f.line,
483
- message: `${f.snippet} - server-only "${sink}" reaches the browser bundle via ${chain.join(" → ")}${f.fallback ? " (direct edge - couldn't resolve the transitive chain precisely)" : ""}; ${SERVER_IMPORT_HINT}`,
484
- fix: SERVER_IMPORT_HINT,
485
- chain,
486
- suggestion: serverImportSuggestion(f.specifier, chain, f.fallback),
487
- });
488
- }
489
- if (sqlCompiler === undefined) {
490
- // A security rule that could not run must say so. Silence here is indistinguishable from a clean
491
- // result, and this is the one rule whose clean result means "no SQL injection was found".
492
- diagnostics.push({
493
- rule: "interpolated-sql",
494
- severity: "warning",
495
- message: SQL_COMPILER_MISSING_HINT,
496
- fix: SQL_COMPILER_MISSING_HINT,
497
- suggestion: {
498
- kind: "command",
499
- title: "Install TypeScript so the SQL rule can run",
500
- command: ["bun add -d typescript"],
501
- },
502
- });
503
- }
504
- for (const f of [...interpolatedSql].sort(bySite)) {
505
- diagnostics.push({
506
- rule: "interpolated-sql",
507
- severity: "error",
508
- file: f.file,
509
- line: f.line,
510
- message: `${f.snippet} - ${INTERPOLATED_SQL_HINT}`,
511
- fix: "bind the value as a parameter instead of interpolating it into the statement",
512
- suggestion: {
513
- kind: "manual",
514
- title: "Bind the value instead of interpolating it",
515
- steps: [
516
- "Replace the interpolation with a placeholder your driver understands (`?` for SQLite/MySQL, `$1` for Postgres).",
517
- "Pass the value as an argument alongside the statement, so the driver binds it.",
518
- `Or switch to the driver's tagged template (sql\`… ${SQL_INTERPOLATION_EXAMPLE} …\`): the tag receives substitutions separately and binds them.`,
519
- "An identifier that genuinely cannot be bound (a table or column name) must be checked against an allowlist you control, never taken from the request.",
520
- "If the statement is dynamic but every value is already bound (generating `($1),($2),…` for a batch insert), mark it with a `// nifra-expect sql-dynamic: <reason>` comment on the line above - the reason is required.",
521
- ],
522
- },
523
- });
524
- }
525
- // Advisory - surfaced but NOT folded into `ok`, so it never fails the gate (a raw Response is valid).
526
- for (const f of [...responseRoutes].sort(bySite)) {
527
- diagnostics.push({
528
- rule: "response-route",
529
- severity: "warning",
530
- file: f.file,
531
- line: f.line,
532
- message: `${f.snippet} - ${RESPONSE_ROUTE_HINT}`,
533
- fix: RESPONSE_ROUTE_HINT,
534
- suggestion: responseRouteSuggestion(),
535
- });
536
- }
537
- if (dr.ran) {
538
- for (const f of dr.findings) {
539
- diagnostics.push({
540
- rule: "undeclared-dependency",
541
- severity: "error",
542
- file: f.file,
543
- line: f.line,
544
- message: `imports ${f.package} which is not declared in package.json - ${UNDECLARED_DEP_HINT}`,
545
- fix: `add ${f.package} to package.json dependencies`,
546
- suggestion: {
547
- kind: "command",
548
- title: `Declare ${f.package} in package.json`,
549
- command: ["bun", "add", f.package],
550
- },
551
- });
552
- }
553
- for (const finding of dr.duplicateInstalls) {
554
- // One line per physical copy: version, resolved absolute path, and who pulled it in. The
555
- // absolute path is what a reader pastes into an editor or `rm -rf`; the importer list is what
556
- // tells them WHICH package.json to fix - a relative path alone answers neither.
557
- const copyLines = finding.copies.map((copy) => `${finding.package}@${copy.version} at ${copy.absolutePath ?? copy.path} - pulled in by ${copy.importers.join(", ")}`);
558
- diagnostics.push({
559
- rule: "duplicate-install",
560
- severity: "error",
561
- message: `${finding.package} identity preflight found ${finding.cause} - ${finding.explanation}${finding.topology === undefined ? "" : `. Topology: ${finding.topology}`}${finding.scope === undefined ? "" : `. Scope: ${finding.scope}`}`,
562
- fix: finding.remediation,
563
- evidence: copyLines,
564
- suggestion: {
565
- kind: "manual",
566
- title: `Resolve ${finding.package} to one loaded copy`,
567
- // The renderer prints this block verbatim before the steps: the exact config for fix 2, so
568
- // the reader pastes instead of transcribing prose into JSON and TOML.
569
- diff: [
570
- "package.json:",
571
- ` "nifra": { "singleCopy": ["${finding.package}"] }`,
572
- "bunfig.toml:",
573
- ` preload = ["${SINGLE_COPY_REGISTER_SPECIFIER}"]`,
574
- " [test]",
575
- ` preload = ["${SINGLE_COPY_REGISTER_SPECIFIER}"]`,
576
- ].join("\n"),
577
- steps: [
578
- ...copyLines.map((line) => `Copy: ${line}`),
579
- "Fix 1 - deduplicate: align workspace dependency and peer ranges on one compatible version, remove stale nested installs, and reinstall from the workspace root so every importer resolves one physical copy.",
580
- `Fix 2 - declare single-copy: apply the package.json and bunfig.toml config printed above; nifra then rewrites every duplicate to this app's copy.${finding.cause === "version-skew" ? " A declaration only covers same-version duplicates, so fix 1's range alignment must land first." : ""}`,
581
- "Re-run `nifra check`; the gate stays failing until one fix lands.",
582
- ],
583
- },
584
- });
585
- }
586
- // Declared single-copy: the resolver collapses these before anything loads, so the build is sound
587
- // and the gate stays green. It is still worth a line - the guarantee lives in a declaration now,
588
- // and a reader who deletes it gets a null hook dispatcher with no obvious cause.
589
- for (const finding of dr.deduplicatedInstalls ?? []) {
590
- const copies = finding.copies.map((copy) => copy.path).join("; ");
591
- diagnostics.push({
592
- rule: "duplicate-install",
593
- severity: "warning",
594
- message: `${finding.package} is installed at ${finding.copies.length} paths (${copies}) and is declared single-copy - nifra resolves every duplicate to this app's copy`,
595
- fix: finding.remediation,
596
- });
597
- }
598
- // Advisory (never fails the gate): while actively editing a linked package its dist is always
599
- // momentarily behind. The finding earns its keep when a dev server is about to start against it -
600
- // Bun reads live `src` while Vite's SSR runner reads the artifact, so a stale one 500s inside
601
- // framework/shared-package code and reads exactly like an upstream regression.
602
- for (const f of dr.staleDists) {
603
- // The rebuild is only actionable with the LOCATION: a workspace link routinely points into a
604
- // sibling repo, so "rebuild @nifrajs/core" left the developer to go find the checkout and guess
605
- // the script. Name the directory and the package's own script, or say plainly that it declares
606
- // none - never suggest a command that would fail.
607
- const rebuild = f.buildScript === undefined
608
- ? `${f.packageDir} declares no build script - build it the way that package expects`
609
- : `cd ${f.packageDir} && bun run ${f.buildScript} (or \`nifra fix --code NF-C010\`)`;
610
- diagnostics.push({
611
- rule: "stale-workspace-dist",
612
- severity: "warning",
613
- message: f.missing
614
- ? `${f.package} was never built - ${f.distFile} is missing, but its export map serves it to Vite SSR/node consumers while Bun reads src - ${rebuild}`
615
- : `${f.package} has a stale build artifact - ${f.distFile} is ${f.behindSeconds}s older than ${f.sourceFile}, and Vite SSR/node consumers read the artifact while Bun reads src - ${rebuild}`,
616
- fix: rebuild,
617
- evidence: [f.package, f.distFile, f.sourceFile, f.packageDir],
618
- suggestion: {
619
- kind: "manual",
620
- title: `Rebuild ${f.package}`,
621
- steps: [
622
- rebuild,
623
- "Only workspace-linked installs drift; npm tarballs are immutable and never flagged.",
624
- ],
625
- },
626
- });
627
- }
628
- }
629
- // The two-pipeline rule, read from the config as TEXT (doctor collects it - see ./pipeline-report.ts).
630
- // `loadApp` already refuses a misplaced plugin, but only when something loads the app; a check that
631
- // never executes project code, and CI that never starts a dev server, would otherwise meet these for
632
- // the first time as a production server that built cleanly and died at startup.
633
- for (const f of dr.pipeline?.findings ?? []) {
634
- diagnostics.push({
635
- rule: "pipeline",
636
- severity: f.severity,
637
- file: f.file,
638
- ...(f.line !== undefined ? { line: f.line } : {}),
639
- message: f.message,
640
- fix: f.fix,
641
- suggestion: { kind: "manual", title: f.fix, steps: [PIPELINE_DOC_HINT] },
642
- });
643
- }
644
- // #7: a committed server-manifest.ts that drifted from routes/ - name the exact missing/extra routes.
645
- for (const f of manifestDrift) {
646
- const parts = [];
647
- if (f.missing.length > 0)
648
- parts.push(`missing from manifest: ${f.missing.join(", ")}`);
649
- if (f.extra.length > 0)
650
- parts.push(`stale in manifest: ${f.extra.join(", ")}`);
651
- diagnostics.push({
652
- rule: "server-manifest-drift",
653
- severity: "error",
654
- file: f.file,
655
- message: `${f.file} drifted from routes/ (${parts.join("; ")}) - ${MANIFEST_DRIFT_HINT}`,
656
- fix: MANIFEST_DRIFT_HINT,
657
- evidence: [...f.missing, ...f.extra],
658
- suggestion: {
659
- kind: "manual",
660
- title: "Regenerate the committed server manifest",
661
- steps: [
662
- "Re-run your build (`nifra build --target <t>` or your build script) - it regenerates server-manifest.ts from the current routes/.",
663
- "Commit the updated server-manifest.ts.",
664
- ],
665
- },
666
- });
667
- }
668
- // G+B+D+F: when the project opts into capability assurance, `nifra check` becomes the static
669
- // provenance firewall as well as the typed-contract gate. Loading is explicit/config-owned; projects
670
- // without nifra.assurance.ts retain the historical scan and hot path unchanged.
671
- const provided = opts.assurance;
672
- let applicationRulePacks = [];
673
- let loadedPolicy = provided;
674
- let loadedCapability = provided?.capability;
220
+ // The rule registry is the only diagnostic producer. This preparation phase may load executable
221
+ // assurance configuration because rules need its reflected facts, but it never formats findings.
222
+ let factsSeed = scan.facts;
223
+ let loadedPolicy = opts.assurance ?? factsSeed.policies.assurance;
224
+ let loadedCapability = loadedPolicy?.capability ?? factsSeed.policies.capability;
225
+ let applicationRulePacks = factsSeed.policies.rulePacks;
675
226
  const assuranceConfigPath = join(cwd, "nifra.assurance.ts");
676
- if (provided !== undefined ? provided.present : existsSync(assuranceConfigPath)) {
227
+ if (loadedPolicy === undefined && existsSync(assuranceConfigPath)) {
677
228
  try {
678
- // Either the shared reflection from `collectProjectVerification` (no second pass) or, on the
679
- // standalone path, loaded + reflected here. Both branches yield the same config + evidence.
680
- let config;
681
- let project;
682
- let routeAssurance;
683
- let evidence;
684
- if (provided !== undefined) {
685
- // A load/evaluate failure travels as `provided.error`; re-throwing lands it in the same
686
- // capability-config diagnostic the standalone catch produces.
687
- if (provided.error !== undefined)
688
- throw provided.error;
689
- config = provided.config;
690
- project = provided.capability;
691
- routeAssurance = provided.routeAssurance;
692
- evidence = provided.evidence;
693
- }
694
- else {
695
- const { loadAssuranceConfig } = await import("./assure.js");
696
- config = await loadAssuranceConfig(cwd);
697
- if (config.capabilities !== undefined) {
698
- const { collectCapabilityProjectReport } = await import("./capabilities-tool.js");
699
- project = await collectCapabilityProjectReport(cwd, config.source, config.capabilities);
700
- }
701
- loadedPolicy = {
702
- present: true,
703
- config,
704
- ...(routeAssurance === undefined ? {} : { routeAssurance }),
705
- ...(project === undefined ? {} : { capability: project }),
706
- ...(evidence === undefined ? {} : { evidence }),
707
- };
708
- loadedCapability = project;
229
+ const { loadAssuranceConfig } = await import("./assure.js");
230
+ const config = await loadAssuranceConfig(cwd);
231
+ let capability;
232
+ if (config.capabilities !== undefined) {
233
+ const { collectCapabilityProjectReport } = await import("./capabilities-tool.js");
234
+ capability = await collectCapabilityProjectReport(cwd, config.source, config.capabilities);
709
235
  }
236
+ loadedPolicy = {
237
+ present: true,
238
+ config,
239
+ ...(capability === undefined ? {} : { capability }),
240
+ };
241
+ loadedCapability = capability;
710
242
  applicationRulePacks = parseRulePacks(config.rulePacks);
711
- const capabilityReport = project?.report;
712
- if (config.capabilities !== undefined && project !== undefined) {
713
- for (const finding of project.report.findings) {
714
- const violation = finding.code === "forbidden-effect-import"
715
- ? project.violations.find((candidate) => candidate.method === finding.method && candidate.path === finding.path)
716
- : undefined;
717
- const truncation = finding.code === "provenance-truncated"
718
- ? project.truncations.find((candidate) => candidate.method === finding.method && candidate.path === finding.path)
719
- : undefined;
720
- // An unmatched seam is a policy defect, not a route defect: the fix is in the policy file,
721
- // so it gets its own steps instead of the route-side provenance guidance.
722
- const seamFix = finding.code === "unmatched-provenance-seam"
723
- ? "Write the seam exactly as the code imports it, or delete the rule."
724
- : undefined;
725
- diagnostics.push({
726
- rule: "capability-assurance",
727
- severity: "error",
728
- ...(violation !== undefined
729
- ? { file: violation.module, chain: violation.chain }
730
- : truncation !== undefined
731
- ? { chain: truncation.chain }
732
- : {}),
733
- message: `${finding.message}${seamFix === undefined ? ` - ${CAPABILITY_HINT}` : ""}`,
734
- fix: seamFix ?? CAPABILITY_HINT,
735
- suggestion: seamFix === undefined
736
- ? {
737
- kind: "manual",
738
- title: "Restore declared effect provenance",
739
- steps: [
740
- "Route effectful work through an import listed in capabilities.provenance.imports.",
741
- "Declare the exact capability token on the route; do not widen unrelated routes in the same file.",
742
- "For domain writes, add the adapter the capability definition requires: `schema.idempotency` for the `request` tier, `.use(durableCommand({ journal }))` from @nifrajs/middleware for the `durable` tier.",
743
- "Run `nifra capabilities snapshot` only after assurance passes, then review the lockfile diff.",
744
- ],
745
- }
746
- : {
747
- kind: "manual",
748
- title: "Point the provenance rule at a module that exists",
749
- steps: [
750
- "Copy the specifier from the import statement itself - it is matched as written, with no extension or index resolution.",
751
- "Use a trailing `/*` when the seam is a directory of modules (`@myorg/db/*`).",
752
- "For a routeModules entry, give the project-relative path of the file that implements the route.",
753
- "Delete the rule if the seam it governed is gone; leaving it in place proves nothing.",
754
- ],
755
- },
756
- });
757
- }
758
- }
759
- if (config.manifest !== undefined) {
760
- const { buildNifraManifest, parseNifraManifest, serializeNifraManifest } = await import("@nifrajs/core/manifest");
761
- const assurance = routeAssurance ??
762
- (await import("@nifrajs/core/assurance")).evaluateRouteAssurance(config.source, config.policy, {
763
- ...(config.capabilities !== undefined
764
- ? { definitions: config.capabilities.definitions }
765
- : {}),
766
- });
767
- evidence ??= snapshotProjectEvidence(config.source, {
768
- assurance,
769
- ...(capabilityReport !== undefined ? { capabilities: capabilityReport } : {}),
770
- });
771
- const path = resolve(cwd, config.manifest.path ?? "nifra.manifest.json");
772
- let message;
773
- if (!assurance.ok || (capabilityReport !== undefined && !capabilityReport.ok)) {
774
- message =
775
- "the configured assurance policy is failing, so a trusted manifest cannot be built";
776
- }
777
- else if (!existsSync(path)) {
778
- message = "the configured trust manifest is missing";
779
- }
780
- else {
781
- try {
782
- const current = await buildNifraManifest({
783
- evidence,
784
- assurance,
785
- ...(capabilityReport !== undefined ? { capabilities: capabilityReport } : {}),
786
- });
787
- const storedText = await Bun.file(path).text();
788
- const stored = await parseNifraManifest(storedText, path);
789
- const expectedText = `${serializeNifraManifest(current)}\n`;
790
- if (storedText !== expectedText || stored.contentHash !== current.contentHash) {
791
- message = "the configured trust manifest does not match live route reflection";
792
- }
793
- }
794
- catch (error) {
795
- message = `the configured trust manifest is invalid: ${error instanceof Error ? error.message : String(error)}`;
796
- }
797
- }
798
- if (message !== undefined) {
799
- diagnostics.push({
800
- rule: "manifest-drift",
801
- severity: "error",
802
- file: path,
803
- message: `${message} - ${TRUST_MANIFEST_DRIFT_HINT}`,
804
- fix: TRUST_MANIFEST_DRIFT_HINT,
805
- suggestion: {
806
- kind: "command",
807
- title: "Regenerate the signed-manifest input artifact",
808
- command: ["nifra", "manifest", "emit"],
809
- steps: [
810
- "Review the route, assurance, capability, and classification delta before committing it.",
811
- ],
812
- },
813
- });
814
- }
815
- }
816
243
  }
817
- catch (err) {
818
- loadedPolicy = { present: true, error: err };
819
- diagnostics.push({
820
- rule: "capability-config",
821
- severity: "error",
822
- file: "nifra.assurance.ts",
823
- message: `capability assurance config could not be evaluated: ${err instanceof Error ? err.message : String(err)}`,
824
- suggestion: {
825
- kind: "manual",
826
- title: "Repair the assurance config",
827
- steps: [
828
- "Ensure nifra.assurance.ts default-exports defineAssuranceConfig({ source, policy, capabilities }).",
829
- "Fix configuration/import errors; the provenance firewall fails closed when its policy cannot load.",
830
- ],
831
- },
832
- });
244
+ catch (error) {
245
+ loadedPolicy = { present: true, error };
246
+ loadedCapability = undefined;
247
+ applicationRulePacks = [];
833
248
  }
834
249
  }
835
- try {
836
- const { checkContractsLock } = await import("./contracts.js");
837
- if (!existsSync(join(cwd, "backend.ts")) && !existsSync(join(cwd, "contracts.lock.json"))) {
838
- throw new Error("contract source not configured");
839
- }
840
- const contract = await checkContractsLock(cwd);
841
- if (!contract.present) {
842
- structuredExtras.push(diagnostic({
843
- code: "NF-K001",
844
- severity: "info",
845
- message: "no contract lock; run `nifra contracts snapshot` to enable drift detection",
846
- verify: "nifra contracts snapshot",
847
- }));
848
- }
849
- else {
850
- if (contract.vacuous) {
851
- // Every route hashes to the empty-schema digest, so the lock exists but the drift rule guards
852
- // nothing: it can only ever compare "no schema" to "no schema". Say so, or a green contract check
853
- // reads as proof of a stable contract when there is no contract to be stable.
854
- structuredExtras.push(diagnostic({
855
- code: "NF-K001",
856
- severity: "info",
857
- message: "no route schemas declared - the trust manifest is vacuous: every contract hash is the empty-schema digest, so drift detection guards nothing. Declare route schemas (body/query/params/response) so the lock has a contract to protect.",
858
- verify: "nifra check --lints-only",
859
- }));
860
- }
861
- for (const finding of contract.diagnostics) {
862
- diagnostics.push({
863
- rule: "contract-drift",
864
- severity: "error",
865
- code: "NF-K001",
866
- ...(finding.route !== undefined ? { evidence: [finding.route] } : {}),
867
- message: finding.message,
868
- fix: "run `nifra contracts snapshot` after reviewing the contract change",
869
- verify: "nifra check --lints-only",
870
- });
871
- }
250
+ else if (loadedPolicy?.present === true && loadedPolicy.error === undefined) {
251
+ try {
252
+ if (loadedPolicy.config === undefined)
253
+ throw new Error("assurance configuration unavailable");
254
+ applicationRulePacks = parseRulePacks(loadedPolicy.config.rulePacks);
255
+ loadedCapability = loadedPolicy.capability ?? loadedCapability;
872
256
  }
873
- }
874
- catch (error) {
875
- if (error instanceof Error && error.message === "contract source not configured") {
876
- // API-only source scans have no contract surface to snapshot.
877
- }
878
- else {
879
- diagnostics.push({
880
- rule: "contract-drift",
881
- severity: "error",
882
- code: "NF-K001",
883
- message: `contract lock could not be checked: ${error instanceof Error ? error.message : String(error)}`,
884
- verify: "nifra contracts snapshot",
885
- });
257
+ catch (error) {
258
+ loadedPolicy = { present: true, error };
259
+ loadedCapability = undefined;
260
+ applicationRulePacks = [];
886
261
  }
887
262
  }
888
- const projectFacts = freezeProjectFacts({
263
+ factsSeed = {
889
264
  ...factsSeed,
890
265
  policies: {
891
266
  ...factsSeed.policies,
@@ -893,50 +268,111 @@ export async function collectCheckDiagnostics(cwd, scan, opts = {}) {
893
268
  ...(loadedCapability === undefined ? {} : { capability: loadedCapability }),
894
269
  rulePacks: applicationRulePacks,
895
270
  },
896
- }, diagnostics);
271
+ };
272
+ const projectFacts = freezeProjectFacts(factsSeed);
897
273
  const ruleContext = {
898
274
  root: cwd,
899
275
  sources: projectFacts.source,
900
276
  project: projectFacts,
277
+ ...(projectFacts.check.typescriptSession === undefined
278
+ ? {}
279
+ : { typescriptSession: projectFacts.check.typescriptSession }),
901
280
  };
902
- const structuredDiagnostics = [...structuredExtras];
281
+ const builtInRules = [
282
+ ...legacyRules,
283
+ ...securityRules,
284
+ ...routeRules,
285
+ ...pageRules,
286
+ ...zoneRules,
287
+ ...dataGuardRules,
288
+ ...secretRules,
289
+ ...islandRules,
290
+ ...nanoRules,
291
+ ];
903
292
  let registryDiagnostics = [];
293
+ let builtInsSucceeded = false;
904
294
  try {
905
- registryDiagnostics = await runRuleRegistry(ruleContext, [...legacyRules, ...securityRules, ...routeRules, ...islandRules, ...nanoRules], projectFacts.policies.rulePacks);
906
- structuredDiagnostics.push(...registryDiagnostics);
295
+ registryDiagnostics = await runRuleRegistry(ruleContext, builtInRules);
296
+ builtInsSucceeded = true;
907
297
  }
908
298
  catch (error) {
909
299
  registryDiagnostics = [
910
300
  diagnostic({
911
301
  code: "NF-C017",
912
302
  severity: "error",
913
- message: `rule registry failed closed: ${error instanceof Error ? error.message : String(error)}`,
303
+ message: "rule registry failed closed: " +
304
+ (error instanceof Error ? error.message : String(error)),
914
305
  fix: { recipe: "rule-pack.repair", command: "nifra check --lints-only" },
915
306
  verify: "nifra check --lints-only",
916
307
  }),
917
308
  ];
918
- structuredDiagnostics.push(...registryDiagnostics);
919
309
  }
310
+ if (builtInsSucceeded && projectFacts.policies.rulePacks.length > 0) {
311
+ try {
312
+ registryDiagnostics.push(...(await runRuleRegistry(ruleContext, [], projectFacts.policies.rulePacks)));
313
+ }
314
+ catch (error) {
315
+ // Keep all built-in findings when an application rule fails. The old compatibility path had
316
+ // already materialized those findings before packs ran; preserving that property matters when
317
+ // a broken pack must not hide a more actionable built-in failure.
318
+ registryDiagnostics.push(diagnostic({
319
+ code: "NF-C017",
320
+ severity: "error",
321
+ message: "rule registry failed closed: " +
322
+ (error instanceof Error ? error.message : String(error)),
323
+ fix: { recipe: "rule-pack.repair", command: "nifra check --lints-only" },
324
+ verify: "nifra check --lints-only",
325
+ }));
326
+ }
327
+ }
328
+ const knownLegacyCodes = new Set(Object.values(LEGACY_RULE_CODES));
329
+ const compatibilityRows = [];
920
330
  for (const item of registryDiagnostics) {
921
- // The legacy adapters publish stable structured findings; the human compatibility view already
922
- // contains their original rule names. Security rules and application packs still need a legacy-view
923
- // row because they have no pre-registry diagnostic.
924
- if (legacyRules.some((rule) => rule.code === item.code))
331
+ const compatibility = diagnosticCompatibilityOf(item);
332
+ if (compatibility !== undefined) {
333
+ compatibilityRows.push({
334
+ rule: compatibility.rule,
335
+ severity: item.severity === "warn" ? "warning" : item.severity,
336
+ ...(compatibility.includeCode === true ? { code: item.code } : {}),
337
+ ...(item.file === undefined ? {} : { file: item.file }),
338
+ ...(item.line === undefined ? {} : { line: item.line }),
339
+ message: item.message,
340
+ ...(compatibility.fix === undefined ? {} : { fix: compatibility.fix }),
341
+ // A legacy chain was a separate field; canonical diagnostics expose the same values as
342
+ // evidence for structured consumers, so do not leak that projection back into the old view.
343
+ ...(item.evidence === undefined || compatibility.chain !== undefined
344
+ ? {}
345
+ : { evidence: item.evidence }),
346
+ ...(compatibility.chain === undefined ? {} : { chain: compatibility.chain }),
347
+ ...(compatibility.suggestion === undefined ? {} : { suggestion: compatibility.suggestion }),
348
+ ...(item.verify === undefined ? {} : { verify: item.verify }),
349
+ });
350
+ continue;
351
+ }
352
+ // A structured informational contract note intentionally has no old human/legacy row. Every
353
+ // other non-legacy rule (security, route, island, nano, or an application pack) retains the
354
+ // existing fallback row keyed by its stable code.
355
+ if (knownLegacyCodes.has(item.code))
925
356
  continue;
926
- diagnostics.push({
357
+ compatibilityRows.push({
927
358
  rule: item.code,
928
359
  severity: item.severity === "error" ? "error" : "warning",
929
360
  code: item.code,
930
- ...(item.file !== undefined ? { file: item.file } : {}),
931
- ...(item.line !== undefined ? { line: item.line } : {}),
361
+ ...(item.file === undefined ? {} : { file: item.file }),
362
+ ...(item.line === undefined ? {} : { line: item.line }),
932
363
  message: item.message,
933
- ...(item.evidence !== undefined ? { evidence: item.evidence } : {}),
934
- ...(item.verify !== undefined ? { verify: item.verify } : {}),
364
+ ...(item.evidence === undefined ? {} : { evidence: item.evidence }),
365
+ ...(item.verify === undefined ? {} : { verify: item.verify }),
935
366
  });
936
367
  }
937
- // Per-rule overrides from `nifra.check.json` `rules`, applied centrally to BOTH diagnostic views
938
- // before `ok` is computed - never inside individual rules, so no rule can dodge (or double-apply)
939
- // them. A key matches the legacy rule name or the stable NF- code.
368
+ // Keep the old compatibility order stable even though the canonical registry order is explicit.
369
+ const order = new Map(LEGACY_RULE_ORDER.map((rule, index) => [rule, index]));
370
+ const orderedLegacy = compatibilityRows
371
+ .map((value, index) => ({ value, index }))
372
+ .sort((a, b) => (order.get(a.value.rule) ?? LEGACY_RULE_ORDER.length) -
373
+ (order.get(b.value.rule) ?? LEGACY_RULE_ORDER.length) || a.index - b.index)
374
+ .map((entry) => entry.value);
375
+ const checkConfig = projectFacts.policies.checkConfig;
940
376
  const overrideFor = (...keys) => {
941
377
  for (const key of keys) {
942
378
  if (key !== undefined && checkConfig.rules[key] !== undefined)
@@ -952,56 +388,69 @@ export async function collectCheckDiagnostics(cwd, scan, opts = {}) {
952
388
  return override.ignore.some((pattern) => safeIgnoreGlobMatch(pattern, file));
953
389
  };
954
390
  const codeToLegacy = new Map(Object.entries(LEGACY_RULE_CODES).map(([name, code]) => [code, name]));
955
- const finalDiagnostics = diagnostics.flatMap((d) => {
956
- const override = overrideFor(d.rule, d.code, LEGACY_RULE_CODES[d.rule]);
391
+ const finalDiagnostics = orderedLegacy.flatMap((value) => {
392
+ const override = overrideFor(value.rule, value.code, LEGACY_RULE_CODES[value.rule]);
957
393
  if (override === undefined)
958
- return [d];
959
- if (dropped(override, d.file))
394
+ return [value];
395
+ if (dropped(override, value.file))
960
396
  return [];
961
- // "off" is fully handled by `dropped` above - only real severities reach the retag.
962
397
  if (override.severity === undefined || override.severity === "off")
963
- return [d];
964
- return [{ ...d, severity: override.severity === "warn" ? "warning" : override.severity }];
398
+ return [value];
399
+ return [{ ...value, severity: override.severity === "warn" ? "warning" : override.severity }];
965
400
  });
966
- const finalStructured = structuredDiagnostics.flatMap((d) => {
967
- const override = overrideFor(d.code, codeToLegacy.get(d.code));
401
+ const structuredExtras = registryDiagnostics.filter((value) => diagnosticCompatibilityOf(value) === undefined && knownLegacyCodes.has(value.code));
402
+ const structuredDiagnostics = [
403
+ ...structuredExtras,
404
+ ...registryDiagnostics.filter((value) => !structuredExtras.includes(value)),
405
+ ];
406
+ const finalStructured = structuredDiagnostics.flatMap((value) => {
407
+ const override = overrideFor(value.code, codeToLegacy.get(value.code));
968
408
  if (override === undefined)
969
- return [d];
970
- if (dropped(override, d.file))
409
+ return [value];
410
+ if (dropped(override, value.file))
971
411
  return [];
972
412
  if (override.severity === undefined || override.severity === "off")
973
- return [d];
974
- return [Object.freeze({ ...d, severity: override.severity })];
413
+ return [value];
414
+ return [Object.freeze({ ...value, severity: override.severity })];
975
415
  });
976
- // Cap the diagnostics when asked (the MCP path), so a project with thousands of findings can't return a
977
- // message that breaks the stdio transport. `ok` reflects the FULL set - truncation never flips it.
978
416
  const total = finalDiagnostics.length;
979
417
  const max = opts.maxDiagnostics;
980
418
  const shown = max !== undefined && total > max ? finalDiagnostics.slice(0, max) : finalDiagnostics;
419
+ const nonLegacyStructuredCount = finalStructured.filter((value) => knownLegacyCodes.has(value.code) && diagnosticCompatibilityOf(value) === undefined).length;
420
+ const structuredLimit = shown.length < total ? shown.length + nonLegacyStructuredCount : finalStructured.length;
421
+ const doctor = projectFacts.packages.doctor;
422
+ const knownGaps = projectFacts.policies.capability?.report.gaps ?? [];
981
423
  const result = {
982
- ok: !finalDiagnostics.some((diagnostic) => diagnostic.severity === "error"),
983
- typecheck: tc.ran ? (tc.ok ? "pass" : "fail") : "skipped",
984
- ...(!tc.ran && tc.note !== undefined ? { typecheckNote: tc.note } : {}),
424
+ ok: !finalDiagnostics.some((value) => value.severity === "error"),
425
+ typecheck: projectFacts.check.typecheck.ran
426
+ ? projectFacts.check.typecheck.ok
427
+ ? "pass"
428
+ : "fail"
429
+ : "skipped",
430
+ ...(!projectFacts.check.typecheck.ran && projectFacts.check.typecheck.note !== undefined
431
+ ? { typecheckNote: projectFacts.check.typecheck.note }
432
+ : {}),
985
433
  diagnostics: shown,
986
- ...(dr.pipeline !== undefined ? { pipeline: dr.pipeline } : {}),
987
- ...(dr.ran
434
+ ...(projectFacts.pipeline !== undefined ? { pipeline: projectFacts.pipeline } : {}),
435
+ ...(doctor.ran
988
436
  ? {
989
437
  identityPreflight: {
990
- ...(dr.identityBasis !== undefined ? { basis: dr.identityBasis } : {}),
991
- ...(dr.identityScanTruncated === true ? { truncated: true } : {}),
992
- duplicates: dr.duplicateInstalls,
993
- deduplicated: dr.deduplicatedInstalls ?? [],
438
+ ...(doctor.identityBasis === undefined ? {} : { basis: doctor.identityBasis }),
439
+ ...(doctor.identityScanTruncated === true ? { truncated: true } : {}),
440
+ duplicates: doctor.duplicateInstalls,
441
+ deduplicated: doctor.deduplicatedInstalls ?? [],
994
442
  },
995
443
  }
996
444
  : {}),
997
- ...(checkConfig.externalMounts.length > 0
998
- ? { externalMounts: checkConfig.externalMounts }
999
- : {}),
1000
- ...(Object.keys(checkConfig.rules).length > 0 ? { ruleOverrides: checkConfig.rules } : {}),
445
+ ...(checkConfig.externalMounts.length === 0
446
+ ? {}
447
+ : { externalMounts: checkConfig.externalMounts }),
448
+ ...(knownGaps.length === 0 ? {} : { knownGaps }),
449
+ ...(Object.keys(checkConfig.rules).length === 0 ? {} : { ruleOverrides: checkConfig.rules }),
1001
450
  ...(shown.length < total ? { truncated: { shown: shown.length, total } } : {}),
1002
451
  };
1003
452
  Object.defineProperty(result, "structuredDiagnostics", {
1004
- value: finalStructured.slice(0, shown.length + structuredExtras.length),
453
+ value: finalStructured.slice(0, structuredLimit),
1005
454
  enumerable: false,
1006
455
  });
1007
456
  return result;