@nifrajs/cli 5.5.1 → 5.7.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 (205) hide show
  1. package/CHANGELOG.md +314 -0
  2. package/dist/cdn-check.d.ts +7 -6
  3. package/dist/cdn-check.d.ts.map +1 -1
  4. package/dist/cdn-check.js +13 -1
  5. package/dist/cdn-check.js.map +1 -1
  6. package/dist/check-diagnostics.d.ts.map +1 -1
  7. package/dist/check-diagnostics.js +9 -3
  8. package/dist/check-diagnostics.js.map +1 -1
  9. package/dist/check-scan.d.ts +6 -0
  10. package/dist/check-scan.d.ts.map +1 -1
  11. package/dist/check-scan.js +30 -32
  12. package/dist/check-scan.js.map +1 -1
  13. package/dist/check.d.ts.map +1 -1
  14. package/dist/check.js +35 -12
  15. package/dist/check.js.map +1 -1
  16. package/dist/cli.d.ts +4 -0
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +66 -9
  19. package/dist/cli.js.map +1 -1
  20. package/dist/command-catalog.d.ts +19 -1
  21. package/dist/command-catalog.d.ts.map +1 -1
  22. package/dist/command-catalog.js +111 -6
  23. package/dist/command-catalog.js.map +1 -1
  24. package/dist/contracts.d.ts +42 -4
  25. package/dist/contracts.d.ts.map +1 -1
  26. package/dist/contracts.js +288 -9
  27. package/dist/contracts.js.map +1 -1
  28. package/dist/doctor.d.ts +12 -2
  29. package/dist/doctor.d.ts.map +1 -1
  30. package/dist/doctor.js +67 -1
  31. package/dist/doctor.js.map +1 -1
  32. package/dist/fix-recipes.d.ts.map +1 -1
  33. package/dist/fix-recipes.js +27 -0
  34. package/dist/fix-recipes.js.map +1 -1
  35. package/dist/frontend-guidance.d.ts +1 -1
  36. package/dist/frontend-guidance.d.ts.map +1 -1
  37. package/dist/frontend-guidance.js +17 -8
  38. package/dist/frontend-guidance.js.map +1 -1
  39. package/dist/internal/git-ignored.d.ts +12 -0
  40. package/dist/internal/git-ignored.d.ts.map +1 -0
  41. package/dist/internal/git-ignored.js +49 -0
  42. package/dist/internal/git-ignored.js.map +1 -0
  43. package/dist/internal/source-facts.d.ts +29 -0
  44. package/dist/internal/source-facts.d.ts.map +1 -1
  45. package/dist/internal/source-facts.js +160 -0
  46. package/dist/internal/source-facts.js.map +1 -1
  47. package/dist/introspect.js +1 -1
  48. package/dist/introspect.js.map +1 -1
  49. package/dist/load.d.ts +7 -1
  50. package/dist/load.d.ts.map +1 -1
  51. package/dist/load.js +18 -0
  52. package/dist/load.js.map +1 -1
  53. package/dist/local-cli.d.ts +15 -0
  54. package/dist/local-cli.d.ts.map +1 -0
  55. package/dist/local-cli.js +74 -0
  56. package/dist/local-cli.js.map +1 -0
  57. package/dist/lock-links.d.ts +0 -7
  58. package/dist/lock-links.d.ts.map +1 -1
  59. package/dist/lock-links.js +5 -44
  60. package/dist/lock-links.js.map +1 -1
  61. package/dist/mcp-delegate.d.ts +13 -5
  62. package/dist/mcp-delegate.d.ts.map +1 -1
  63. package/dist/mcp-delegate.js +24 -8
  64. package/dist/mcp-delegate.js.map +1 -1
  65. package/dist/mcp-exec.d.ts.map +1 -1
  66. package/dist/mcp-exec.js +57 -3
  67. package/dist/mcp-exec.js.map +1 -1
  68. package/dist/mcp-http.d.ts +2 -1
  69. package/dist/mcp-http.d.ts.map +1 -1
  70. package/dist/mcp-http.js +3 -2
  71. package/dist/mcp-http.js.map +1 -1
  72. package/dist/mcp-tool-meta.d.ts +21 -0
  73. package/dist/mcp-tool-meta.d.ts.map +1 -0
  74. package/dist/mcp-tool-meta.js +246 -0
  75. package/dist/mcp-tool-meta.js.map +1 -0
  76. package/dist/mcp.d.ts +3 -2
  77. package/dist/mcp.d.ts.map +1 -1
  78. package/dist/mcp.js +36 -98
  79. package/dist/mcp.js.map +1 -1
  80. package/dist/openapi-types.d.ts.map +1 -1
  81. package/dist/openapi-types.js +45 -2
  82. package/dist/openapi-types.js.map +1 -1
  83. package/dist/output-schemas.d.ts +8 -0
  84. package/dist/output-schemas.d.ts.map +1 -1
  85. package/dist/output-schemas.js +14 -0
  86. package/dist/output-schemas.js.map +1 -1
  87. package/dist/ppr-read-fix.d.ts +8 -0
  88. package/dist/ppr-read-fix.d.ts.map +1 -0
  89. package/dist/ppr-read-fix.js +356 -0
  90. package/dist/ppr-read-fix.js.map +1 -0
  91. package/dist/recipes/5.6.0.d.ts +10 -0
  92. package/dist/recipes/5.6.0.d.ts.map +1 -0
  93. package/dist/recipes/5.6.0.js +68 -0
  94. package/dist/recipes/5.6.0.js.map +1 -0
  95. package/dist/recipes/5.7.0.d.ts +12 -0
  96. package/dist/recipes/5.7.0.d.ts.map +1 -0
  97. package/dist/recipes/5.7.0.js +70 -0
  98. package/dist/recipes/5.7.0.js.map +1 -0
  99. package/dist/recipes/index.d.ts +13 -0
  100. package/dist/recipes/index.d.ts.map +1 -1
  101. package/dist/recipes/index.js +4 -0
  102. package/dist/recipes/index.js.map +1 -1
  103. package/dist/review.d.ts.map +1 -1
  104. package/dist/review.js +9 -2
  105. package/dist/review.js.map +1 -1
  106. package/dist/rules/codes.d.ts +10 -3
  107. package/dist/rules/codes.d.ts.map +1 -1
  108. package/dist/rules/codes.js +11 -4
  109. package/dist/rules/codes.js.map +1 -1
  110. package/dist/rules/explanations.d.ts.map +1 -1
  111. package/dist/rules/explanations.js +52 -16
  112. package/dist/rules/explanations.js.map +1 -1
  113. package/dist/rules/islands.d.ts +91 -0
  114. package/dist/rules/islands.d.ts.map +1 -1
  115. package/dist/rules/islands.js +757 -3
  116. package/dist/rules/islands.js.map +1 -1
  117. package/dist/rules/legacy.js +1 -1
  118. package/dist/rules/legacy.js.map +1 -1
  119. package/dist/rules/ppr.d.ts +16 -0
  120. package/dist/rules/ppr.d.ts.map +1 -0
  121. package/dist/rules/ppr.js +114 -0
  122. package/dist/rules/ppr.js.map +1 -0
  123. package/dist/rules/swap.d.ts +7 -0
  124. package/dist/rules/swap.d.ts.map +1 -0
  125. package/dist/rules/swap.js +338 -0
  126. package/dist/rules/swap.js.map +1 -0
  127. package/dist/rules/text-slot-boolean.d.ts +8 -0
  128. package/dist/rules/text-slot-boolean.d.ts.map +1 -0
  129. package/dist/rules/text-slot-boolean.js +57 -0
  130. package/dist/rules/text-slot-boolean.js.map +1 -0
  131. package/dist/rules/undeclared-response.d.ts +9 -0
  132. package/dist/rules/undeclared-response.d.ts.map +1 -0
  133. package/dist/rules/undeclared-response.js +93 -0
  134. package/dist/rules/undeclared-response.js.map +1 -0
  135. package/dist/scaffold-hole.d.ts +105 -0
  136. package/dist/scaffold-hole.d.ts.map +1 -0
  137. package/dist/scaffold-hole.js +688 -0
  138. package/dist/scaffold-hole.js.map +1 -0
  139. package/dist/scaffold.d.ts +5 -3
  140. package/dist/scaffold.d.ts.map +1 -1
  141. package/dist/scaffold.js +56 -46
  142. package/dist/scaffold.js.map +1 -1
  143. package/dist/upgrade.d.ts +34 -8
  144. package/dist/upgrade.d.ts.map +1 -1
  145. package/dist/upgrade.js +197 -25
  146. package/dist/upgrade.js.map +1 -1
  147. package/dist/verification-plan.d.ts.map +1 -1
  148. package/dist/verification-plan.js +12 -1
  149. package/dist/verification-plan.js.map +1 -1
  150. package/dist/version-drift.js +1 -1
  151. package/dist/version-drift.js.map +1 -1
  152. package/dist/web-app-options.d.ts +1 -1
  153. package/dist/web-app-options.d.ts.map +1 -1
  154. package/dist/web-app-options.js.map +1 -1
  155. package/docs/examples.json +70 -10
  156. package/docs/llms-full.txt +3162 -1196
  157. package/docs/types.json +1473 -322
  158. package/package.json +11 -11
  159. package/src/cdn-check.ts +21 -7
  160. package/src/check-diagnostics.ts +9 -3
  161. package/src/check-scan.ts +35 -32
  162. package/src/check.ts +32 -10
  163. package/src/cli.ts +71 -9
  164. package/src/command-catalog.ts +149 -6
  165. package/src/contracts.ts +348 -14
  166. package/src/doctor.ts +62 -3
  167. package/src/fix-recipes.ts +28 -0
  168. package/src/frontend-guidance.ts +20 -8
  169. package/src/internal/git-ignored.ts +47 -0
  170. package/src/internal/source-facts.ts +198 -0
  171. package/src/introspect.ts +1 -1
  172. package/src/load.ts +29 -0
  173. package/src/local-cli.ts +83 -0
  174. package/src/lock-links.ts +5 -43
  175. package/src/mcp-delegate.ts +30 -9
  176. package/src/mcp-exec.ts +74 -3
  177. package/src/mcp-http.ts +3 -2
  178. package/src/mcp-tool-meta.ts +268 -0
  179. package/src/mcp.ts +35 -99
  180. package/src/openapi-types.ts +43 -2
  181. package/src/output-schemas.ts +28 -0
  182. package/src/ppr-read-fix.ts +426 -0
  183. package/src/recipes/5.6.0.ts +69 -0
  184. package/src/recipes/5.7.0.ts +72 -0
  185. package/src/recipes/index.ts +18 -0
  186. package/src/review.ts +9 -2
  187. package/src/rules/codes.ts +11 -4
  188. package/src/rules/explanations.ts +52 -16
  189. package/src/rules/islands.ts +875 -3
  190. package/src/rules/legacy.ts +1 -1
  191. package/src/rules/ppr.ts +143 -0
  192. package/src/rules/swap.ts +402 -0
  193. package/src/rules/text-slot-boolean.ts +56 -0
  194. package/src/rules/undeclared-response.ts +92 -0
  195. package/src/scaffold-hole.ts +880 -0
  196. package/src/scaffold.ts +60 -49
  197. package/src/upgrade.ts +229 -33
  198. package/src/verification-plan.ts +20 -1
  199. package/src/version-drift.ts +1 -1
  200. package/src/web-app-options.ts +2 -0
  201. package/dist/rules/nano.d.ts +0 -6
  202. package/dist/rules/nano.d.ts.map +0 -1
  203. package/dist/rules/nano.js +0 -273
  204. package/dist/rules/nano.js.map +0 -1
  205. package/src/rules/nano.ts +0 -307
package/src/doctor.ts CHANGED
@@ -16,10 +16,11 @@
16
16
  * therefore also covers `*.test.ts`/`*.spec.ts`, which `nifra check` skips - `tsc` compiles them, so an
17
17
  * undeclared import there fails a clean `bun install --frozen-lockfile` build just the same.
18
18
  */
19
- import type { Dirent } from "node:fs"
19
+ import { type Dirent, existsSync } from "node:fs"
20
20
  import { readdir, realpath, stat } from "node:fs/promises"
21
21
  import { builtinModules } from "node:module"
22
22
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
23
+ import { discoverRoutes } from "@nifrajs/web/fs"
23
24
  import {
24
25
  collectIdentityParity,
25
26
  displayPath,
@@ -218,10 +219,18 @@ export interface DoctorResult {
218
219
  }
219
220
  /**
220
221
  * `file:` entries of the project's bun.lock whose recorded dependencies the linked package.json no
221
- * longer declares: Bun never refreshes them, so it installs a second copy under the linked package.
222
+ * longer declares: Bun 1.4.2 never refreshes them, so it installs a second copy under the linked package.
222
223
  * Advisory (never folded into `ok`). `lock` is the lockfile, relative to the project.
223
224
  */
224
225
  readonly staleLinkLocks?: { readonly lock: string; readonly entries: readonly StaleLinkLock[] }
226
+ /**
227
+ * Route files that export `keepAlive` in an app where nothing names its sign-in cookie: no
228
+ * `identityCookies`, `rotateIdentityEpoch()` or `identityChanged()`, and either no `@nifrajs/auth`,
229
+ * Better Auth or Auth.js dependency or a source file (`renamedIn`) that gives the session cookie a
230
+ * name of its own. A sign-out there may leave the previous visitor's kept pages. Advisory (never
231
+ * folded into `ok`).
232
+ */
233
+ readonly keepAliveIdentity?: { readonly routes: readonly string[]; readonly renamedIn?: string }
225
234
  /** Static production-readiness evidence for the selected deploy target. */
226
235
  readonly readiness?: DoctorReadiness
227
236
  /** The explicit source boundary used by the dependency scan. */
@@ -773,7 +782,7 @@ async function collectDoctorReadiness(
773
782
  : configured(
774
783
  "graceful-lifecycle",
775
784
  "graceful lifecycle",
776
- /\bgracefulSignals\s*:\s*(?:true\b|\{)|\bonStop\s*\(/,
785
+ /\bgracefulSignals\s*:\s*(?:true\b|\{)|\bonStop(?:ping)?\s*\(/,
777
786
  ),
778
787
  ]
779
788
  return {
@@ -855,6 +864,33 @@ async function inferDependencyFix(
855
864
  }
856
865
 
857
866
  /** Run doctor against the project at `cwd`: diff source imports vs declared deps. */
867
+ // Packages whose session cookies the identity epoch knows by their default names.
868
+ const KNOWN_AUTH_PACKAGES = [
869
+ "@nifrajs/auth",
870
+ "@nifrajs/authjs",
871
+ "better-auth",
872
+ "@auth/core",
873
+ "next-auth",
874
+ ]
875
+ const IDENTITY_SIGNAL = /\b(?:identityCookies\s*:|rotateIdentityEpoch\s*\(|identityChanged\s*\()/
876
+ // A session cookie renamed outright: Better Auth's `advanced.cookies.session_token.name`, Auth.js's
877
+ // `cookies.sessionToken.name`, `@nifrajs/auth`'s `cookieName`. A Better Auth `cookiePrefix` keeps the
878
+ // suffix the identity epoch matches, so it is not one.
879
+ const RENAMED_SESSION =
880
+ /\b(?:session_token|sessionToken)\s*:\s*\{[^}]*\bname\s*:|\bcookieName\s*:\s*["'`]/
881
+
882
+ function keepAliveRoutes(cwd: string): readonly string[] {
883
+ const routesDir = join(cwd, "routes")
884
+ if (!existsSync(routesDir)) return []
885
+ try {
886
+ return discoverRoutes(routesDir)
887
+ .routes.filter((route) => route.keepAlive === true)
888
+ .map((route) => `routes/${route.file}`)
889
+ } catch {
890
+ return []
891
+ }
892
+ }
893
+
858
894
  export async function collectDoctorResult(
859
895
  cwd: string,
860
896
  opts: { readonly target?: string; readonly strict?: boolean; readonly cliVersion?: string } = {},
@@ -867,6 +903,8 @@ export async function collectDoctorResult(
867
903
 
868
904
  const findings: DoctorFinding[] = []
869
905
  const manifestLists: ManifestList[] = []
906
+ let identitySignal = false
907
+ let renamedIn: string | undefined
870
908
  // A standalone app owns its tests, so they remain in the declaration check. A workspace root owns
871
909
  // the published package source while its root devDependencies intentionally own shared tests,
872
910
  // benchmarks, and scaffold copy-surfaces. Keep that boundary explicit instead of reporting a
@@ -898,6 +936,8 @@ export async function collectDoctorResult(
898
936
  findings.push({ file: f.file, line: f.line, package: f.snippet })
899
937
  }
900
938
  manifestLists.push(...manifestListsIn(rel, content))
939
+ if (!identitySignal && IDENTITY_SIGNAL.test(content)) identitySignal = true
940
+ if (renamedIn === undefined && RENAMED_SESSION.test(content)) renamedIn = rel
901
941
  },
902
942
  { includeTests: scanScope.includeTests, ignore: workspaceSurface },
903
943
  )
@@ -918,6 +958,15 @@ export async function collectDoctorResult(
918
958
  const lockDir = bunLockDir(cwd)
919
959
  const linkLocks = lockDir === undefined ? [] : staleLinkLocks(lockDir)
920
960
  const handBuilt = handBuiltManifests(cwd, manifestLists)
961
+ const knownAuth = KNOWN_AUTH_PACKAGES.some((name) => dependencySpec(pkg, name) !== undefined)
962
+ const unnamedIdentity =
963
+ identitySignal || (knownAuth && renamedIn === undefined) ? [] : keepAliveRoutes(cwd)
964
+ const keepAliveIdentity =
965
+ unnamedIdentity.length === 0
966
+ ? undefined
967
+ : knownAuth && renamedIn !== undefined
968
+ ? { routes: unnamedIdentity, renamedIn }
969
+ : { routes: unnamedIdentity }
921
970
  // `staleDists`, `toolingDrift` and `staleMcpPins` are advisory (see DoctorResult): they never fail `ok`.
922
971
  return {
923
972
  ok:
@@ -937,6 +986,7 @@ export async function collectDoctorResult(
937
986
  ...(toolingDrift !== undefined ? { toolingDrift } : {}),
938
987
  ...(versionDrift !== undefined ? { versionDrift } : {}),
939
988
  ...(handBuilt.length > 0 ? { handBuiltManifests: handBuilt } : {}),
989
+ ...(keepAliveIdentity !== undefined ? { keepAliveIdentity } : {}),
940
990
  ...(staleMcpPins !== undefined && staleMcpPins.files.length > 0 ? { staleMcpPins } : {}),
941
991
  ...(lockDir !== undefined && linkLocks.length > 0
942
992
  ? {
@@ -1144,6 +1194,15 @@ export function doctorReport(result: DoctorResult, cliVersion?: string): string[
1144
1194
  for (const finding of result.handBuiltManifests ?? []) {
1145
1195
  lines.push(`⚠ ${handBuiltManifestMessage(finding)}\n`)
1146
1196
  }
1197
+ if (result.keepAliveIdentity !== undefined) {
1198
+ const { routes, renamedIn } = result.keepAliveIdentity
1199
+ lines.push(
1200
+ renamedIn === undefined
1201
+ ? `⚠ ${routes.join(", ")} keep pages alive, and nothing names this app's sign-in cookie (no @nifrajs/auth, Better Auth or Auth.js, no identityCookies): a sign-out may leave the previous visitor's pages one back away`
1202
+ : `⚠ ${routes.join(", ")} keep pages alive, and ${renamedIn} renames the session cookie, which nifra knows only by its default name (no identityCookies): a sign-out may leave the previous visitor's pages one back away`,
1203
+ " fix: name the session cookie in keepAlive.identityCookies - exported from backend/framework.ts, or passed to createWebApp in a server you write - or call identityChanged() from @nifrajs/web/client for token auth - /docs/keep-alive#sign-in\n",
1204
+ )
1205
+ }
1147
1206
  // Advisory: the agent's MCP server is launched from these pins, so a stale one answers for an old
1148
1207
  // release even when the CLI running doctor matches the project.
1149
1208
  if (result.staleMcpPins !== undefined) {
@@ -190,6 +190,34 @@ registerFixRecipe({
190
190
  },
191
191
  })
192
192
 
193
+ registerFixRecipe({
194
+ id: "ppr.read-to-hole",
195
+ description:
196
+ "Move a partially prerendered page's request read into a new dynamic hole: the read becomes the hole's loader, and the element that shows it the hole's render.",
197
+ onlyWhenNamed: true,
198
+ verify: "nifra check",
199
+ async apply(root, diagnostic) {
200
+ const file = diagnostic.file
201
+ if (file === undefined || (await resolveInsideProject(root, file)) === undefined) return []
202
+ const { loadApp } = await import("./load.ts")
203
+ const { backendFileOf, frameworkFromClientModule } = await import("./scaffold.ts")
204
+ const framework = frameworkFromClientModule((await loadApp(root)).framework.clientModule)
205
+ const { routeTypeScript } = await import("./scaffold-hole.ts")
206
+ const loaded = await routeTypeScript(root, [file, backendFileOf(file)])
207
+ if (loaded.unsupported !== undefined) throw loaded.unsupported
208
+ if (loaded.compiler === undefined)
209
+ throw new Error(
210
+ "[nifra] the hole fix places each edit through the page's syntax tree, so it needs TypeScript - run `bun add -d typescript`, then rerun the fix",
211
+ )
212
+ try {
213
+ const { moveReadToHole } = await import("./ppr-read-fix.ts")
214
+ return await moveReadToHole(root, file, diagnostic.line, framework, loaded.compiler)
215
+ } finally {
216
+ await loaded.session?.close()
217
+ }
218
+ },
219
+ })
220
+
193
221
  registerFixRecipe({
194
222
  id: "layout.migrate",
195
223
  description:
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `nifra_frontend` - a symptom-indexed catalog of the mistakes an agent (or a human) hits on the client
3
3
  * side of a nifra app, across every adapter. It is the FRONTEND companion to `nifra_check`: where the
4
- * check statically flags the footguns nifra's own seam owns (server-only imports, the nano lane), this
4
+ * check statically flags the footguns nifra's own seam owns (server-only imports, island bindings), this
5
5
  * catalog covers the ones a static rule can't own cheaply - hydration nondeterminism, a duplicated
6
6
  * framework runtime, and the per-framework reactivity-loss idioms that each ecosystem's own linter is
7
7
  * the real authority on.
@@ -102,8 +102,8 @@ export const FRONTEND_GUIDANCE: readonly GuidanceEntry[] = [
102
102
  "The list is keyed by the array index (or not keyed at all), so add/remove/reorder maps the wrong item to an existing node.",
103
103
  fix: "Key each row by a stable, unique id from the item, never its position in the array.",
104
104
  verify:
105
- "The framework's own linter for JSX keys; on the vanilla nano lane, nifra_check flags an index key as NF-C022.",
106
- seeAlso: "list key stable id reconcile nano",
105
+ "The framework's own linter for JSX keys; for an islands bindList, nifra_check flags a positional key as NF-C022.",
106
+ seeAlso: "list key stable id reconcile bindList islands",
107
107
  },
108
108
  {
109
109
  id: "vue-lost-reactivity",
@@ -153,16 +153,28 @@ export const FRONTEND_GUIDANCE: readonly GuidanceEntry[] = [
153
153
  seeAlso: "eslint-plugin-react-hooks exhaustive-deps effect closure",
154
154
  },
155
155
  {
156
- id: "prefer-nano-or-island",
156
+ id: "prefer-reactive-island",
157
157
  adapters: ["vanilla"],
158
158
  symptom:
159
159
  "A vanilla page needs local state or a list a human edits, and hand-written DOM updates are getting fragile.",
160
160
  cause:
161
- "The islands lane is imperative and has no state primitive, so each update is hand-wired and a list means rebuilding the container.",
162
- fix: "Use the nano lane: `signal` + `computed(fn, [deps])` for state, `bindList` for a keyed list, `resource` for async. Every reactive edge is a visible call, so its mistakes are static lints.",
161
+ "An imperative defineIsland enhancer has no state primitive, so each update is hand-wired and a list means rebuilding the container.",
162
+ fix: "Mount the island with `bindIsland`: `state(key, fallback)` for state, `data-bind-*` attributes for the markup, `bindList` for a keyed list, `resource` for async. Everything the setup creates stops when the island unmounts.",
163
163
  verify:
164
- "nifra_check runs NF-C021 (discarded disposer), NF-C022 (index key), NF-C023 (missing dep) over the nano code.",
165
- seeAlso: "nano signal computed bindList resource islands",
164
+ "nifra_check runs NF-C047 (a binding names no state or handler), NF-C048 (a binding outside a bindIsland host) and NF-C022 (a positional list key) over the island code.",
165
+ seeAlso: "bindIsland state data-bind bindList resource islands",
166
+ },
167
+ {
168
+ id: "swap-a-region",
169
+ adapters: ["vanilla"],
170
+ symptom:
171
+ 'A search form, a filter or a "more" link on a vanilla page reloads the whole document to change one region.',
172
+ cause:
173
+ "A plain link or form always loads a full page, and a vanilla page has no client router to fetch only the part that changed.",
174
+ fix: 'Mark the region `data-swap-slot="results"` and make `slot("results", content)` its only content, add `data-swap="replace:results"` (or `append:results`) to the link or form, and call `enableSwap` from `@nifrajs/web/islands/swap` in place of `mountIslands`. The server answers with that slot of the same page; anything else loads normally.',
175
+ verify:
176
+ "nifra_check runs NF-C049 to NF-C052 over the swap markup and NF-C048 over bindings inside a slot.",
177
+ seeAlso: "data-swap data-swap-slot slot enableSwap islands",
166
178
  },
167
179
  ]
168
180
 
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Paths git considers ignored under `cwd`, in ONE batched `git check-ignore` call - so `.gitignore`
3
+ * (root + nested + the global excludesfile) is honoured, not just a built-in list. This keeps a scan out
4
+ * of generated trees and other copies that live under a repo but aren't the project: a
5
+ * monorepo that gitignores `builder/projects/` (238 generated apps) would otherwise be walked in full.
6
+ * Tracked files are never reported, whatever a pattern says. Returns an EMPTY set when there's no git /
7
+ * not a repo / git errors, so the caller degrades to its own list - never throws, never blocks.
8
+ */
9
+ export async function gitIgnored(cwd: string, rels: readonly string[]): Promise<Set<string>> {
10
+ if (rels.length === 0) return new Set()
11
+ try {
12
+ const proc = Bun.spawn(["git", "check-ignore", "--stdin", "-z"], {
13
+ cwd,
14
+ stdin: "pipe",
15
+ stdout: "pipe",
16
+ stderr: "ignore",
17
+ })
18
+ proc.stdin.write(`${rels.join("\0")}\0`)
19
+ await proc.stdin.end()
20
+ // -z keeps both directions literal: Git otherwise C-quotes Unicode/escapes on output and
21
+ // interprets quoted input. Only matching paths are emitted; exit 1 means none matched.
22
+ const out = await new Response(proc.stdout).text()
23
+ await proc.exited
24
+ return ignoredOf(out)
25
+ } catch {
26
+ return new Set()
27
+ }
28
+ }
29
+
30
+ /** {@link gitIgnored} for a caller that cannot await. */
31
+ export function gitIgnoredSync(cwd: string, rels: readonly string[]): Set<string> {
32
+ if (rels.length === 0) return new Set()
33
+ try {
34
+ const result = Bun.spawnSync(["git", "check-ignore", "--stdin", "-z"], {
35
+ cwd,
36
+ stdin: new TextEncoder().encode(`${rels.join("\0")}\0`),
37
+ stdout: "pipe",
38
+ stderr: "ignore",
39
+ })
40
+ return ignoredOf(result.stdout.toString())
41
+ } catch {
42
+ return new Set()
43
+ }
44
+ }
45
+
46
+ const ignoredOf = (out: string): Set<string> =>
47
+ new Set(out.split("\0").filter((path) => path !== ""))
@@ -19,6 +19,23 @@ export interface UntypedResponseRoutes {
19
19
  readonly indirectReturns: readonly number[]
20
20
  }
21
21
 
22
+ /** A route registration of one file that declares no `response`, from {@link SourceFacts.undeclaredResponseRoutes}. */
23
+ export interface UndeclaredResponseRoute {
24
+ /** The start of the registration's method name (`get` in `.get("/x", h)`). */
25
+ readonly position: number
26
+ readonly method: string
27
+ readonly path: string
28
+ }
29
+
30
+ /** A zod `coerce.boolean()` that a route's text slot reaches, from {@link SourceFacts.textSlotBooleanCoercions}. */
31
+ export interface TextSlotBooleanCoercion {
32
+ /** The start of the `coerce.boolean()` call. */
33
+ readonly position: number
34
+ readonly slot: "query" | "headers" | "cookies"
35
+ readonly method: string
36
+ readonly path: string
37
+ }
38
+
22
39
  export interface SourceFacts {
23
40
  parse(file: string, content: string): TSApi.SourceFile | undefined
24
41
  isValueImportAt(
@@ -61,6 +78,20 @@ export interface SourceFacts {
61
78
  source: TSApi.SourceFile,
62
79
  importReturnsResponse?: (specifier: string, name: string) => boolean,
63
80
  ): UntypedResponseRoutes
81
+ /**
82
+ * The `.get("/path", …)` registrations (and the other methods) whose options are all object
83
+ * literals and none declares `response`, leaving out those whose handlers {@link untypedResponseRoutes}
84
+ * reports: a raw `Response` has no JSON body to declare. One whose options are a variable or a call is
85
+ * left out too, since the file does not show whether it declares one.
86
+ */
87
+ undeclaredResponseRoutes(source: TSApi.SourceFile): readonly UndeclaredResponseRoute[]
88
+ /**
89
+ * The zod `coerce.boolean()` calls a route's `query`, `headers` or `cookies` schema reaches in
90
+ * `source`: written in the route's options, or in a variable of the file the options name, at any
91
+ * depth. Each call is reported once, for the first route that reaches it. A schema imported from
92
+ * another file is not followed.
93
+ */
94
+ textSlotBooleanCoercions(source: TSApi.SourceFile): readonly TextSlotBooleanCoercion[]
64
95
  /** Whether the function `source` exports as `name` returns a raw `Response` on some path. */
65
96
  exportReturnsResponse(source: TSApi.SourceFile, name: string): boolean
66
97
  /** Whether the `import` keyword at `position` starts a runtime `import(specifier)` call (true) or a
@@ -120,6 +151,56 @@ const REGISTRATION_METHODS: ReadonlySet<string> = new Set([
120
151
  "all",
121
152
  ])
122
153
 
154
+ const ZOD_MODULES: ReadonlySet<string> = new Set(["zod", "zod/v4", "zod/mini", "zod/v4/mini"])
155
+
156
+ /** The names `source` binds zod's namespace to (`z`), and those it binds zod's `coerce` to. */
157
+ function zodBindings(
158
+ ts: TypeScriptApi,
159
+ source: TSApi.SourceFile,
160
+ ): { readonly namespaces: ReadonlySet<string>; readonly coerce: ReadonlySet<string> } {
161
+ const namespaces = new Set<string>()
162
+ const coerce = new Set<string>()
163
+ for (const statement of source.statements) {
164
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
165
+ continue
166
+ const clause = statement.importClause
167
+ if (!ZOD_MODULES.has(statement.moduleSpecifier.text) || clause === undefined) continue
168
+ if (clause.isTypeOnly) continue
169
+ if (clause.name !== undefined) namespaces.add(clause.name.text)
170
+ const bindings = clause.namedBindings
171
+ if (bindings !== undefined && ts.isNamespaceImport(bindings)) namespaces.add(bindings.name.text)
172
+ else if (bindings !== undefined) {
173
+ for (const element of bindings.elements) {
174
+ const imported = (element.propertyName ?? element.name).text
175
+ if (element.isTypeOnly) continue
176
+ if (imported === "z") namespaces.add(element.name.text)
177
+ if (imported === "coerce") coerce.add(element.name.text)
178
+ }
179
+ }
180
+ }
181
+ return { namespaces, coerce }
182
+ }
183
+
184
+ /** The initializer of each variable of `source`, any scope, by name: the first one wins. */
185
+ function variableInitializers(
186
+ ts: TypeScriptApi,
187
+ source: TSApi.SourceFile,
188
+ ): Map<string, TSApi.Expression> {
189
+ const consts = new Map<string, TSApi.Expression>()
190
+ const visit = (node: TSApi.Node): void => {
191
+ if (
192
+ ts.isVariableDeclaration(node) &&
193
+ ts.isIdentifier(node.name) &&
194
+ node.initializer !== undefined &&
195
+ !consts.has(node.name.text)
196
+ )
197
+ consts.set(node.name.text, node.initializer)
198
+ ts.forEachChild(node, visit)
199
+ }
200
+ visit(source)
201
+ return consts
202
+ }
203
+
123
204
  function unwrapExpression(ts: TypeScriptApi, node: TSApi.Expression): TSApi.Expression {
124
205
  let current = node
125
206
  while (
@@ -618,6 +699,121 @@ export function createSourceFacts(
618
699
  }
619
700
  }
620
701
 
702
+ const undeclaredResponseRoutes = (
703
+ source: TSApi.SourceFile,
704
+ ): readonly UndeclaredResponseRoute[] => {
705
+ const locals = localFunctions(ts, source)
706
+ const raw = untypedResponseRoutes(source)
707
+ const routes: UndeclaredResponseRoute[] = []
708
+ const visit = (node: TSApi.Node): void => {
709
+ ts.forEachChild(node, visit)
710
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) return
711
+ const method = node.expression.name.text
712
+ const [first, ...rest] = node.arguments
713
+ if (
714
+ !REGISTRATION_METHODS.has(method) ||
715
+ first === undefined ||
716
+ !ts.isStringLiteralLike(first)
717
+ )
718
+ return
719
+ const handlers: FunctionNode[] = []
720
+ for (const argument of rest.map((value) => unwrapExpression(ts, value))) {
721
+ const local = ts.isIdentifier(argument) ? locals.get(argument.text) : undefined
722
+ if (isFunctionValue(ts, argument)) handlers.push(argument)
723
+ else if (local !== undefined) handlers.push(...local)
724
+ else if (!ts.isObjectLiteralExpression(argument) || declaresResponse(ts, argument)) return
725
+ }
726
+ if (handlers.length > 0 && handlers.every((fn) => raw.isUntypedAt(fn.getStart(source))))
727
+ return
728
+ routes.push({
729
+ position: node.expression.name.getStart(source),
730
+ method: method.toUpperCase(),
731
+ path: first.text,
732
+ })
733
+ }
734
+ visit(source)
735
+ return routes.sort((a, b) => a.position - b.position)
736
+ }
737
+
738
+ const textSlotBooleanCoercions = (
739
+ source: TSApi.SourceFile,
740
+ ): readonly TextSlotBooleanCoercion[] => {
741
+ const zod = zodBindings(ts, source)
742
+ if (zod.namespaces.size === 0 && zod.coerce.size === 0) return []
743
+ const consts = variableInitializers(ts, source)
744
+ const isCoerceBoolean = (node: TSApi.Node): boolean => {
745
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression))
746
+ return false
747
+ const { expression, name } = node.expression
748
+ if (name.text !== "boolean") return false
749
+ if (ts.isIdentifier(expression)) return zod.coerce.has(expression.text)
750
+ return (
751
+ ts.isPropertyAccessExpression(expression) &&
752
+ expression.name.text === "coerce" &&
753
+ ts.isIdentifier(expression.expression) &&
754
+ zod.namespaces.has(expression.expression.text)
755
+ )
756
+ }
757
+ const found: TextSlotBooleanCoercion[] = []
758
+ const reported = new Set<number>()
759
+ const reach = (
760
+ node: TSApi.Node,
761
+ seen: Set<TSApi.Node>,
762
+ route: Omit<TextSlotBooleanCoercion, "position">,
763
+ ): void => {
764
+ if (ts.isIdentifier(node)) {
765
+ const initializer = consts.get(node.text)
766
+ if (initializer !== undefined && !seen.has(initializer)) {
767
+ seen.add(initializer)
768
+ reach(initializer, seen, route)
769
+ }
770
+ return
771
+ }
772
+ if (isCoerceBoolean(node)) {
773
+ const position = node.getStart(source)
774
+ if (!reported.has(position)) {
775
+ reported.add(position)
776
+ found.push({ position, ...route })
777
+ }
778
+ }
779
+ // Only the value side: a property name or a member name is never a schema.
780
+ if (ts.isPropertyAccessExpression(node)) reach(node.expression, seen, route)
781
+ else if (ts.isPropertyAssignment(node)) reach(node.initializer, seen, route)
782
+ else ts.forEachChild(node, (child) => reach(child, seen, route))
783
+ }
784
+ const visit = (node: TSApi.Node): void => {
785
+ ts.forEachChild(node, visit)
786
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) return
787
+ const method = node.expression.name.text
788
+ const [first, ...rest] = node.arguments
789
+ if (
790
+ !REGISTRATION_METHODS.has(method) ||
791
+ first === undefined ||
792
+ !ts.isStringLiteralLike(first)
793
+ )
794
+ return
795
+ for (const argument of rest) {
796
+ let options = unwrapExpression(ts, argument)
797
+ const named = ts.isIdentifier(options) ? consts.get(options.text) : undefined
798
+ if (named !== undefined) options = unwrapExpression(ts, named)
799
+ if (!ts.isObjectLiteralExpression(options)) continue
800
+ for (const property of options.properties) {
801
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property))
802
+ continue
803
+ const slot =
804
+ ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)
805
+ ? property.name.text
806
+ : undefined
807
+ if (slot !== "query" && slot !== "headers" && slot !== "cookies") continue
808
+ const value = ts.isPropertyAssignment(property) ? property.initializer : property.name
809
+ reach(value, new Set(), { slot, method: method.toUpperCase(), path: first.text })
810
+ }
811
+ }
812
+ }
813
+ visit(source)
814
+ return found.sort((a, b) => a.position - b.position)
815
+ }
816
+
621
817
  const exportReturnsResponse = (source: TSApi.SourceFile, name: string): boolean => {
622
818
  const local = exportedLocal(ts, source, name)
623
819
  if (local === undefined) return false
@@ -655,6 +851,8 @@ export function createSourceFacts(
655
851
  isFunctionRouteCallAt,
656
852
  isResponseSyntaxAt,
657
853
  untypedResponseRoutes,
854
+ undeclaredResponseRoutes,
855
+ textSlotBooleanCoercions,
658
856
  exportReturnsResponse,
659
857
  isDynamicImportAt,
660
858
  }
package/src/introspect.ts CHANGED
@@ -610,7 +610,7 @@ export function routeTableToJson(rows: readonly RouteTableEntry[]): {
610
610
  methods: r.methods,
611
611
  ...(r.file !== undefined ? { file: r.file } : {}),
612
612
  ...(r.kind === "api" ? { autoMounted: r.autoMounted === true } : {}),
613
- // biome-ignore lint/plugin/noConditionalEmptyObjectSpread: `--json` rows gain the key only where it is true, so existing consumers see no change.
613
+ // `--json` rows gain the key only where it is true, so existing consumers see no change.
614
614
  ...(r.inProcessOnly === true ? { inProcessOnly: true } : {}),
615
615
  ...(client === undefined
616
616
  ? {}
package/src/load.ts CHANGED
@@ -119,6 +119,12 @@ export interface NifraFramework {
119
119
  /** Which pages and files each host serves, from `createHostPolicy()`: checked before the app's
120
120
  * static files, mounts and pages. See `createWebApp`'s `hostPolicy`. */
121
121
  readonly hostPolicy?: CreateWebAppOptions["hostPolicy"]
122
+ /** Live data refresh, the runtime `live()` from `@nifrajs/web/live` returns: the app serves its
123
+ * endpoints and the client entry keeps what is on screen fresh, in `nifra dev` and in the build. */
124
+ readonly live?: CreateWebAppOptions["live"]
125
+ /** Which cookies say who is signed in, for an app with a `keepAlive` route: a sign-in or sign-out
126
+ * through one drops every tab's kept pages. See `createWebApp`'s `keepAlive`. */
127
+ readonly keepAlive?: CreateWebAppOptions["keepAlive"]
122
128
  }
123
129
 
124
130
  /** The {@link NifraFramework} fields forwarded to `createWebApp` and imported by the generated server
@@ -132,6 +138,8 @@ export const FRAMEWORK_WEB_OPTIONS = [
132
138
  "serverComponents",
133
139
  "i18n",
134
140
  "hostPolicy",
141
+ "live",
142
+ "keepAlive",
135
143
  ] as const
136
144
  export type FrameworkWebOption = (typeof FRAMEWORK_WEB_OPTIONS)[number]
137
145
 
@@ -187,6 +195,27 @@ function assertFrameworkWebOptions(fw: Partial<NifraFramework>, configFile: stri
187
195
  ) {
188
196
  wrong("hostPolicy", "the policy createHostPolicy() from @nifrajs/web returns")
189
197
  }
198
+ if (
199
+ fw.live !== undefined &&
200
+ (typeof fw.live !== "object" ||
201
+ fw.live === null ||
202
+ typeof fw.live.publish !== "function" ||
203
+ typeof fw.live.clientEntry !== "object")
204
+ ) {
205
+ wrong("live", "the runtime live() from @nifrajs/web/live returns")
206
+ }
207
+ if (fw.keepAlive !== undefined) {
208
+ const names = (value: unknown): boolean =>
209
+ value === undefined ||
210
+ (Array.isArray(value) && value.every((name) => typeof name === "string" && name !== ""))
211
+ if (
212
+ typeof fw.keepAlive !== "object" ||
213
+ fw.keepAlive === null ||
214
+ !names(Reflect.get(fw.keepAlive, "identityCookies")) ||
215
+ !names(Reflect.get(fw.keepAlive, "ignoreCookies"))
216
+ )
217
+ wrong("keepAlive", 'an object such as { identityCookies: ["sid"] }')
218
+ }
190
219
  if (fw.publicEnvPrefix !== undefined && typeof fw.publicEnvPrefix !== "string") {
191
220
  wrong("publicEnvPrefix", 'a string such as "PUBLIC_", or "" to expose no environment variable')
192
221
  }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * One nifra per project command: the copy the project installs.
3
+ *
4
+ * `dev`, `build`, `start` and `check` run the app inside this process, beside this CLI's own
5
+ * `@nifrajs/core`. A global or `bun link`ed CLI therefore loads a second core next to the project's,
6
+ * and `nifra check` cannot see it: its scan reads the project, not the CLI that runs it. So a command
7
+ * started from another install hands itself to the project's `@nifrajs/cli`, and when there is none to
8
+ * hand to, says which two copies the app is about to load.
9
+ */
10
+ import { existsSync, readFileSync, realpathSync } from "node:fs"
11
+ import { dirname, join } from "node:path"
12
+ import { fileURLToPath } from "node:url"
13
+ import { findProjectCli, handOffSession, isOtherInstall, OWN_CLI_DIR } from "./mcp-delegate.ts"
14
+
15
+ /** `0` runs the CLI as invoked. Set on the hand-off child, and by hand to try a linked CLI. */
16
+ export const LOCAL_CLI_ENV = "NIFRA_LOCAL_CLI"
17
+
18
+ /** The commands that run the project with this CLI's copy of nifra in the process. */
19
+ export const PROJECT_COMMANDS: ReadonlySet<string> = new Set(["dev", "build", "start", "check"])
20
+
21
+ const MAX_ANCESTOR_DIRS = 8
22
+
23
+ /** The nearest `@nifrajs/core` install at or above `dir`, resolved through its links. */
24
+ function projectCore(dir: string): string | undefined {
25
+ for (let depth = 0; depth < MAX_ANCESTOR_DIRS; depth++) {
26
+ const pkg = join(dir, "node_modules", "@nifrajs", "core")
27
+ if (existsSync(join(pkg, "package.json"))) return realpathSync(pkg)
28
+ const parent = dirname(dir)
29
+ if (parent === dir) return undefined
30
+ dir = parent
31
+ }
32
+ return undefined
33
+ }
34
+
35
+ /** The `@nifrajs/core` this CLI imports: the package directory above its resolved entry. */
36
+ function ownCore(): string | undefined {
37
+ try {
38
+ let dir = dirname(fileURLToPath(import.meta.resolve("@nifrajs/core")))
39
+ for (let depth = 0; depth < MAX_ANCESTOR_DIRS; depth++) {
40
+ const manifest = join(dir, "package.json")
41
+ if (
42
+ existsSync(manifest) &&
43
+ JSON.parse(readFileSync(manifest, "utf8")).name === "@nifrajs/core"
44
+ )
45
+ return realpathSync(dir)
46
+ dir = dirname(dir)
47
+ }
48
+ } catch {
49
+ // Unresolvable from here: nothing to compare.
50
+ }
51
+ return undefined
52
+ }
53
+
54
+ /**
55
+ * Run `command` through the project's own CLI when this one is another install. Resolves to the
56
+ * child's exit code, or `undefined` when this process should run the command itself: then, if the
57
+ * project resolves another `@nifrajs/core` than this CLI, it warns with both paths first.
58
+ */
59
+ export async function runThroughLocalCli(options: {
60
+ readonly cwd: string
61
+ readonly version: string
62
+ readonly args: readonly string[]
63
+ }): Promise<number | undefined> {
64
+ if (process.env[LOCAL_CLI_ENV] !== "0") {
65
+ const cli = await findProjectCli(options.cwd)
66
+ if (cli?.bin !== undefined && isOtherInstall(cli.dir)) {
67
+ const exit = await handOffSession([process.execPath, cli.bin, ...options.args], {
68
+ cwd: options.cwd,
69
+ env: { ...process.env, [LOCAL_CLI_ENV]: "0" },
70
+ announce: `[nifra] this nifra CLI (${options.version}, ${OWN_CLI_DIR}) is not the project's; running its @nifrajs/cli ${cli.version} from ${cli.dir} (${LOCAL_CLI_ENV}=0 runs this one)`,
71
+ })
72
+ if (exit !== undefined) return exit
73
+ }
74
+ }
75
+ const project = projectCore(options.cwd)
76
+ const own = ownCore()
77
+ if (project !== undefined && own !== undefined && project !== own) {
78
+ console.warn(
79
+ `[nifra] this nifra CLI (${OWN_CLI_DIR}) runs its own @nifrajs/core from ${own}, and the project resolves ${project}: the app loads both, and \`nifra check\` cannot see this CLI's copy. Run the project's CLI (\`./node_modules/.bin/nifra\`, or add it: \`bun add -d @nifrajs/cli\`).`,
80
+ )
81
+ }
82
+ return undefined
83
+ }