@nifrajs/cli 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +10 -0
  2. package/dist/assure-hydration.d.ts.map +1 -1
  3. package/dist/assure-hydration.js +6 -1
  4. package/dist/assure-hydration.js.map +1 -1
  5. package/dist/assure.d.ts.map +1 -1
  6. package/dist/assure.js +3 -2
  7. package/dist/assure.js.map +1 -1
  8. package/dist/check-diagnostics.d.ts +165 -0
  9. package/dist/check-diagnostics.d.ts.map +1 -0
  10. package/dist/check-diagnostics.js +1009 -0
  11. package/dist/check-diagnostics.js.map +1 -0
  12. package/dist/check-scan.d.ts +245 -0
  13. package/dist/check-scan.d.ts.map +1 -0
  14. package/dist/check-scan.js +1599 -0
  15. package/dist/check-scan.js.map +1 -0
  16. package/dist/check.d.ts +4 -324
  17. package/dist/check.d.ts.map +1 -1
  18. package/dist/check.js +8 -2366
  19. package/dist/check.js.map +1 -1
  20. package/dist/cli.d.ts.map +1 -1
  21. package/dist/cli.js +247 -10
  22. package/dist/cli.js.map +1 -1
  23. package/dist/command-catalog.d.ts +21 -1
  24. package/dist/command-catalog.d.ts.map +1 -1
  25. package/dist/command-catalog.js +122 -0
  26. package/dist/command-catalog.js.map +1 -1
  27. package/dist/env-file.js +5 -5
  28. package/dist/env-file.js.map +1 -1
  29. package/dist/frontend-guidance.d.ts +57 -0
  30. package/dist/frontend-guidance.d.ts.map +1 -0
  31. package/dist/frontend-guidance.js +195 -0
  32. package/dist/frontend-guidance.js.map +1 -0
  33. package/dist/levels-tool.d.ts.map +1 -1
  34. package/dist/levels-tool.js +6 -0
  35. package/dist/levels-tool.js.map +1 -1
  36. package/dist/load.d.ts.map +1 -1
  37. package/dist/load.js +4 -1
  38. package/dist/load.js.map +1 -1
  39. package/dist/mcp-context.d.ts +48 -0
  40. package/dist/mcp-context.d.ts.map +1 -0
  41. package/dist/mcp-context.js +215 -0
  42. package/dist/mcp-context.js.map +1 -0
  43. package/dist/mcp-docs-tools.d.ts.map +1 -1
  44. package/dist/mcp-docs-tools.js +31 -0
  45. package/dist/mcp-docs-tools.js.map +1 -1
  46. package/dist/mcp-exec.d.ts +74 -0
  47. package/dist/mcp-exec.d.ts.map +1 -0
  48. package/dist/mcp-exec.js +844 -0
  49. package/dist/mcp-exec.js.map +1 -0
  50. package/dist/mcp-http.js +1 -1
  51. package/dist/mcp-io.d.ts +26 -0
  52. package/dist/mcp-io.d.ts.map +1 -0
  53. package/dist/mcp-io.js +100 -0
  54. package/dist/mcp-io.js.map +1 -0
  55. package/dist/mcp-reflect.d.ts +16 -0
  56. package/dist/mcp-reflect.d.ts.map +1 -0
  57. package/dist/mcp-reflect.js +101 -0
  58. package/dist/mcp-reflect.js.map +1 -0
  59. package/dist/mcp-root.d.ts +7 -0
  60. package/dist/mcp-root.d.ts.map +1 -1
  61. package/dist/mcp-root.js +51 -3
  62. package/dist/mcp-root.js.map +1 -1
  63. package/dist/mcp.d.ts +10 -92
  64. package/dist/mcp.d.ts.map +1 -1
  65. package/dist/mcp.js +13 -1232
  66. package/dist/mcp.js.map +1 -1
  67. package/dist/openapi-tool.d.ts +5 -10
  68. package/dist/openapi-tool.d.ts.map +1 -1
  69. package/dist/openapi-tool.js +21 -2
  70. package/dist/openapi-tool.js.map +1 -1
  71. package/dist/openapi-types.d.ts +21 -0
  72. package/dist/openapi-types.d.ts.map +1 -0
  73. package/dist/openapi-types.js +214 -0
  74. package/dist/openapi-types.js.map +1 -0
  75. package/dist/port.d.ts.map +1 -1
  76. package/dist/port.js +2 -1
  77. package/dist/port.js.map +1 -1
  78. package/dist/project-facts.d.ts +2 -1
  79. package/dist/project-facts.d.ts.map +1 -1
  80. package/dist/project-facts.js.map +1 -1
  81. package/dist/release-verification.d.ts +4 -1
  82. package/dist/release-verification.d.ts.map +1 -1
  83. package/dist/release-verification.js +6 -138
  84. package/dist/release-verification.js.map +1 -1
  85. package/dist/rules/codes.d.ts +4 -0
  86. package/dist/rules/codes.d.ts.map +1 -1
  87. package/dist/rules/codes.js +4 -0
  88. package/dist/rules/codes.js.map +1 -1
  89. package/dist/rules/islands.d.ts +4 -0
  90. package/dist/rules/islands.d.ts.map +1 -0
  91. package/dist/rules/islands.js +155 -0
  92. package/dist/rules/islands.js.map +1 -0
  93. package/dist/rules/nano.d.ts +6 -0
  94. package/dist/rules/nano.d.ts.map +1 -0
  95. package/dist/rules/nano.js +264 -0
  96. package/dist/rules/nano.js.map +1 -0
  97. package/dist/rules/security.d.ts.map +1 -1
  98. package/dist/rules/security.js +38 -4
  99. package/dist/rules/security.js.map +1 -1
  100. package/dist/scaffold.d.ts +12 -6
  101. package/dist/scaffold.d.ts.map +1 -1
  102. package/dist/scaffold.js +149 -10
  103. package/dist/scaffold.js.map +1 -1
  104. package/dist/search-terms.d.ts.map +1 -1
  105. package/dist/search-terms.js +5 -3
  106. package/dist/search-terms.js.map +1 -1
  107. package/dist/stylex-migrate.d.ts +38 -0
  108. package/dist/stylex-migrate.d.ts.map +1 -0
  109. package/dist/stylex-migrate.js +1052 -0
  110. package/dist/stylex-migrate.js.map +1 -0
  111. package/dist/sync-manifest.d.ts.map +1 -1
  112. package/dist/sync-manifest.js +2 -1
  113. package/dist/sync-manifest.js.map +1 -1
  114. package/dist/verification-plan.d.ts +24 -0
  115. package/dist/verification-plan.d.ts.map +1 -0
  116. package/dist/verification-plan.js +116 -0
  117. package/dist/verification-plan.js.map +1 -0
  118. package/dist/work-graph.d.ts.map +1 -1
  119. package/dist/work-graph.js +6 -3
  120. package/dist/work-graph.js.map +1 -1
  121. package/docs/examples.json +46 -4
  122. package/docs/llms-full.txt +1346 -28
  123. package/docs/types.json +4185 -87
  124. package/package.json +9 -9
  125. package/src/assure-hydration.ts +6 -1
  126. package/src/assure.ts +4 -2
  127. package/src/check-diagnostics.ts +1219 -0
  128. package/src/check-scan.ts +1825 -0
  129. package/src/check.ts +47 -2752
  130. package/src/cli.ts +252 -10
  131. package/src/command-catalog.ts +155 -0
  132. package/src/env-file.ts +5 -5
  133. package/src/frontend-guidance.ts +259 -0
  134. package/src/levels-tool.ts +6 -0
  135. package/src/load.ts +4 -1
  136. package/src/mcp-context.ts +266 -0
  137. package/src/mcp-docs-tools.ts +37 -0
  138. package/src/mcp-exec.ts +1040 -0
  139. package/src/mcp-http.ts +1 -1
  140. package/src/mcp-io.ts +118 -0
  141. package/src/mcp-reflect.ts +140 -0
  142. package/src/mcp-root.ts +62 -4
  143. package/src/mcp.ts +61 -1511
  144. package/src/openapi-tool.ts +32 -2
  145. package/src/openapi-types.ts +261 -0
  146. package/src/port.ts +2 -1
  147. package/src/project-facts.ts +2 -4
  148. package/src/release-verification.ts +22 -164
  149. package/src/rules/codes.ts +4 -0
  150. package/src/rules/islands.ts +171 -0
  151. package/src/rules/nano.ts +295 -0
  152. package/src/rules/security.ts +40 -4
  153. package/src/scaffold.ts +169 -9
  154. package/src/search-terms.ts +7 -3
  155. package/src/stylex-migrate.ts +1139 -0
  156. package/src/sync-manifest.ts +2 -1
  157. package/src/verification-plan.ts +242 -0
  158. package/src/work-graph.ts +6 -3
@@ -0,0 +1,259 @@
1
+ /**
2
+ * `nifra_frontend` - a symptom-indexed catalog of the mistakes an agent (or a human) hits on the client
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
5
+ * catalog covers the ones a static rule can't own cheaply - hydration nondeterminism, a duplicated
6
+ * framework runtime, and the per-framework reactivity-loss idioms that each ecosystem's own linter is
7
+ * the real authority on.
8
+ *
9
+ * Deliberately a compact reference, not an accumulated fault corpus: two kinds of entry only.
10
+ * - Seam entries (`adapters: ["all"]`) - the boundary nifra defines: server/client split, the loader
11
+ * data contract, hydration determinism, one framework copy. These point at a `nifra_*` tool to fix
12
+ * and verify, because nifra owns that surface.
13
+ * - Framework entries - the classic reactivity-loss shape for one adapter (Vue ref, Solid props,
14
+ * Svelte runes, React/Preact deps). These point at that framework's own ESLint plugin, which is the
15
+ * authority; nifra does not re-implement it, it routes you to it.
16
+ *
17
+ * One source, two heads: `nifra_frontend` (MCP) serves it to an agent; `nifra frontend` (CLI) prints it
18
+ * for a human. Both call {@link renderFrontendResult}, so they can never drift.
19
+ */
20
+
21
+ import type { Framework } from "./scaffold.ts"
22
+
23
+ /** An adapter an entry applies to, or `all` for a seam issue that is adapter-independent. */
24
+ export type GuidanceAdapter = Framework | "all"
25
+
26
+ export interface GuidanceEntry {
27
+ /** Stable slug, e.g. `server-import`. */
28
+ readonly id: string
29
+ /** Which adapters this applies to. `["all"]` is a seam issue every adapter shares. */
30
+ readonly adapters: readonly GuidanceAdapter[]
31
+ /** What you observe - the searchable symptom, phrased as the failure, not the cause. */
32
+ readonly symptom: string
33
+ /** Why it happens. */
34
+ readonly cause: string
35
+ /** The concrete change that fixes it. */
36
+ readonly fix: string
37
+ /** How to confirm it is fixed - a `nifra_*` tool for a seam issue, the framework's linter otherwise. */
38
+ readonly verify: string
39
+ /** Where to go deeper - a `nifra_docs`/`nifra_example` query, or the ecosystem linter that owns it. */
40
+ readonly seeAlso?: string | undefined
41
+ }
42
+
43
+ /**
44
+ * The catalog. Seam entries first (they are the nifra-specific value and apply everywhere), then the
45
+ * per-framework reactivity-loss entries. Keep it compact and high-signal - a curated fault corpus mined
46
+ * from real failures is operated depth and lives elsewhere, not in the public package.
47
+ */
48
+ export const FRONTEND_GUIDANCE: readonly GuidanceEntry[] = [
49
+ {
50
+ id: "server-import",
51
+ adapters: ["all"],
52
+ symptom:
53
+ "A client component crashes at build or runtime with a missing Node built-in, a leaked secret, or 'module not found in the browser'.",
54
+ cause:
55
+ "A server-only module (the DB, a secret, `node:*`, the backend file) is imported at the top level of a component, so the bundler tries to ship it to the browser.",
56
+ fix: "Move the access into a server-only `loader`/`action` and read the result in the component. Reach the backend through the typed `api` argument, never a top-level server-only import.",
57
+ verify:
58
+ "nifra_check - its transitive server-import scan flags the exact import chain into a client module.",
59
+ seeAlso: "loader action server-only import boundary",
60
+ },
61
+ {
62
+ id: "hydration-mismatch",
63
+ adapters: ["all"],
64
+ symptom:
65
+ "A hydration warning, text that flips on load, or 'server HTML did not match client' the first time the page becomes interactive.",
66
+ cause:
67
+ "The first client render is not identical to the SSR HTML - usually a non-deterministic read during render: `Date.now()`, `Math.random()`, `window`/`localStorage`, or a locale/timezone the server did not have.",
68
+ fix: "Render deterministic markup, then apply anything client-only in an effect / `onMount` after the first paint. Pass anything the server knew (time, locale, flags) down through loader data so both renders agree.",
69
+ verify:
70
+ "nifra_render the route and diff its HTML against the first client render; nifra_check's hydration assurance reports nondeterminism it can see.",
71
+ seeAlso: "hydration ssr determinism loader data",
72
+ },
73
+ {
74
+ id: "duplicate-runtime",
75
+ adapters: ["react", "preact", "solid", "vue", "svelte"],
76
+ symptom:
77
+ "'Invalid hook call', a null context/provider, signals that never update, or a component that mounts twice.",
78
+ cause:
79
+ "Two copies of the framework are in the bundle - the app's own dependency and a second one resolved through the adapter - so the two runtimes do not share the same module-level state.",
80
+ fix: "Dedupe the framework to a single version across the workspace (one entry in the lockfile). The adapter must resolve the app's copy, not bundle its own.",
81
+ verify: "nifra_doctor - it detects a duplicated framework runtime (NF-H002).",
82
+ seeAlso: "duplicate framework runtime dedupe NF-H002",
83
+ },
84
+ {
85
+ id: "loader-typing",
86
+ adapters: ["all"],
87
+ symptom:
88
+ "Loader data is typed `any` in the page, or a hand-written interface silently drifts from what the loader actually returns.",
89
+ cause:
90
+ "The component types its props by hand instead of inferring them from the loader, so a change to the loader is not a type error at the use site.",
91
+ fix: "Type the page from the loader: `props: { data: LoaderData<typeof loader> }`. Call the backend through the typed `api` so the request/response shape is inferred, not restated.",
92
+ verify:
93
+ "nifra_context prints the exact loader shape and typed call form; nifra_check fails on drift.",
94
+ seeAlso: "LoaderData typed client loader inference",
95
+ },
96
+ {
97
+ id: "list-key",
98
+ adapters: ["all"],
99
+ symptom:
100
+ "List rows keep the wrong state on reorder/insert - a checked box, focus, or an input value jumps to a different row.",
101
+ cause:
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
+ fix: "Key each row by a stable, unique id from the item, never its position in the array.",
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",
107
+ },
108
+ {
109
+ id: "vue-lost-reactivity",
110
+ adapters: ["vue"],
111
+ symptom:
112
+ "A value stops updating the template after you pull it out of a ref, reactive object, or props.",
113
+ cause:
114
+ "Destructuring a `reactive()` object or `props` copies the current value and drops the reactive link; a `ref` read in script forgets `.value`.",
115
+ fix: "Keep the reactive source intact: use `toRefs`/`storeToRefs` when you must destructure, access `props.x` directly, and remember `.value` on a ref in script (templates unwrap it for you).",
116
+ verify:
117
+ "eslint-plugin-vue - it is the authority on Vue reactivity; nifra does not re-implement it.",
118
+ seeAlso: "eslint-plugin-vue toRefs reactivity",
119
+ },
120
+ {
121
+ id: "solid-lost-reactivity",
122
+ adapters: ["solid"],
123
+ symptom: "A prop or store value renders once and never tracks updates in a Solid component.",
124
+ cause:
125
+ "Solid props are getters, evaluated where you read them. Destructuring props (or reading them outside JSX/an effect) reads once and loses tracking.",
126
+ fix: "Access `props.x` at the point of use inside JSX, or `splitProps`/`mergeProps` when you need to pass a subset on. Never destructure props in the function signature.",
127
+ verify:
128
+ "eslint-plugin-solid - the authority on Solid reactivity; nifra routes you to it, not around it.",
129
+ seeAlso: "eslint-plugin-solid splitProps props getters",
130
+ },
131
+ {
132
+ id: "svelte-runes",
133
+ adapters: ["svelte"],
134
+ symptom:
135
+ "In a Svelte 5 component, `export let` props or a `$:` statement do not behave as expected, or the compiler rejects them in runes mode.",
136
+ cause:
137
+ "Runes mode replaces the Svelte 4 idioms: props come from `$props()`, derived values from `$derived`, side effects from `$effect`. Mixing the two models is the mismatch.",
138
+ fix: "In runes mode use `$props()` for inputs, `$state` for local state, `$derived` for computed values, and `$effect` for side effects - not `export let` or `$:`.",
139
+ verify:
140
+ "eslint-plugin-svelte and the Svelte compiler warnings own this; nifra points you at them.",
141
+ seeAlso: "eslint-plugin-svelte runes $props $derived",
142
+ },
143
+ {
144
+ id: "react-stale-deps",
145
+ adapters: ["react", "preact"],
146
+ symptom:
147
+ "An effect or callback uses a stale value, fires too often, or never re-runs when a value it reads changes.",
148
+ cause:
149
+ "The dependency array omits a value the effect/callback closes over (or the effect has no array), so the closure captures an old render's value.",
150
+ fix: "List every reactive value the effect reads in its deps, or hold the mutable value in a ref when it must not trigger a re-run. Do not silence the rule by emptying the array.",
151
+ verify:
152
+ "eslint-plugin-react-hooks (`exhaustive-deps`) is the authority on effect deps; nifra does not duplicate it.",
153
+ seeAlso: "eslint-plugin-react-hooks exhaustive-deps effect closure",
154
+ },
155
+ {
156
+ id: "prefer-nano-or-island",
157
+ adapters: ["vanilla"],
158
+ symptom:
159
+ "A vanilla page needs local state or a list a human edits, and hand-written DOM updates are getting fragile.",
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.",
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",
166
+ },
167
+ ]
168
+
169
+ const ADAPTER_ALIASES: Record<string, GuidanceAdapter> = {
170
+ all: "all",
171
+ react: "react",
172
+ preact: "preact",
173
+ solid: "solid",
174
+ vue: "vue",
175
+ svelte: "svelte",
176
+ vanilla: "vanilla",
177
+ }
178
+
179
+ /** Normalize a free-text adapter argument to a known adapter, or `undefined` if it is not one. */
180
+ export function parseAdapter(value: string | undefined): GuidanceAdapter | undefined {
181
+ if (value === undefined) return undefined
182
+ return ADAPTER_ALIASES[value.trim().toLowerCase()]
183
+ }
184
+
185
+ const appliesTo = (entry: GuidanceEntry, adapter: GuidanceAdapter): boolean =>
186
+ adapter === "all" || entry.adapters.includes("all") || entry.adapters.includes(adapter)
187
+
188
+ /** Keyword score of an entry against a query - counts distinct query words found in its text. */
189
+ function score(entry: GuidanceEntry, words: readonly string[]): number {
190
+ const hay =
191
+ `${entry.id} ${entry.symptom} ${entry.cause} ${entry.fix} ${entry.seeAlso ?? ""}`.toLowerCase()
192
+ let hits = 0
193
+ for (const w of words) if (hay.includes(w)) hits++
194
+ return hits
195
+ }
196
+
197
+ function renderEntry(entry: GuidanceEntry): string {
198
+ const scope = entry.adapters.includes("all") ? "all adapters" : entry.adapters.join(", ")
199
+ const parts = [
200
+ `[${entry.id}] (${scope})`,
201
+ `Symptom: ${entry.symptom}`,
202
+ `Cause: ${entry.cause}`,
203
+ `Fix: ${entry.fix}`,
204
+ `Verify: ${entry.verify}`,
205
+ ]
206
+ if (entry.seeAlso !== undefined) parts.push(`See: ${entry.seeAlso}`)
207
+ return parts.join("\n")
208
+ }
209
+
210
+ function renderIndex(
211
+ entries: readonly GuidanceEntry[],
212
+ adapter: GuidanceAdapter | undefined,
213
+ ): string {
214
+ const scope = adapter === undefined ? "all adapters" : `adapter: ${adapter}`
215
+ const lines = entries.map((e) => {
216
+ const s = e.adapters.includes("all") ? "all" : e.adapters.join("/")
217
+ return `- ${e.id} (${s}) - ${e.symptom}`
218
+ })
219
+ return [
220
+ `nifra frontend guidance (${entries.length} of ${FRONTEND_GUIDANCE.length}, ${scope}). Pass a symptom to get the cause + fix + how to verify; pass an adapter to filter.`,
221
+ "",
222
+ ...lines,
223
+ ].join("\n")
224
+ }
225
+
226
+ /**
227
+ * Render the catalog. Filters by `adapter` (when it names a known one), then by a `symptom` keyword
228
+ * query. With no query it returns the (filtered) index; with a query it returns the best-matching
229
+ * entries in full, or the index plus a "no match" note when nothing scores. Pure, so both heads agree.
230
+ */
231
+ export function renderFrontendResult(args: {
232
+ adapter?: string | undefined
233
+ symptom?: string | undefined
234
+ limit?: number | undefined
235
+ }): string {
236
+ const adapter = parseAdapter(args.adapter)
237
+ const scoped =
238
+ adapter === undefined
239
+ ? FRONTEND_GUIDANCE
240
+ : FRONTEND_GUIDANCE.filter((e) => appliesTo(e, adapter))
241
+ const query = args.symptom?.trim()
242
+ if (query === undefined || query.length === 0) return renderIndex(scoped, adapter)
243
+
244
+ const words = query
245
+ .toLowerCase()
246
+ .split(/\s+/)
247
+ .filter((w) => w.length > 1)
248
+ const limit = Math.min(Math.max(args.limit ?? 3, 1), 5)
249
+ const ranked = scoped
250
+ .map((entry) => ({ entry, s: score(entry, words) }))
251
+ .filter((r) => r.s > 0)
252
+ .sort((a, b) => b.s - a.s)
253
+ .slice(0, limit)
254
+
255
+ if (ranked.length === 0) {
256
+ return `No frontend-guidance entry matched "${query}"${adapter ? ` for ${adapter}` : ""}.\n\n${renderIndex(scoped, adapter)}`
257
+ }
258
+ return ranked.map((r) => renderEntry(r.entry)).join("\n\n")
259
+ }
@@ -132,6 +132,12 @@ export async function collectVerificationLevels(
132
132
  if (assurance.ok && (capabilityReport === undefined || capabilityReport.ok)) {
133
133
  const current = await buildNifraManifest({
134
134
  source: config.source,
135
+ // `evidence` is NOT optional detail here - it is what `nifra manifest emit` and the
136
+ // `versioned trust manifest drift` check in `nifra check` both hash. Omitting it made
137
+ // this recompute a manifest nothing else ever emits, so every app that publishes
138
+ // assurance evidence from outside its `.use()` chain (the `assure()` seam) reported a
139
+ // freshly emitted manifest as stale and could never reach L3.
140
+ ...(verification.evidence !== undefined ? { evidence: verification.evidence } : {}),
135
141
  assurance,
136
142
  ...(capabilityReport !== undefined ? { capabilities: capabilityReport } : {}),
137
143
  })
package/src/load.ts CHANGED
@@ -214,7 +214,10 @@ export async function loadApp(
214
214
  // and passes through unchanged.
215
215
  let clientModule: string
216
216
  if (fw.clientModule.startsWith("./") || fw.clientModule.startsWith("../")) {
217
- clientModule = resolve(cwd, fw.clientModule)
217
+ // The value is embedded in generated import source, not passed directly to a filesystem API.
218
+ // Keep it absolute but slash-normalized so the generated module is identical on POSIX and
219
+ // Windows (Bun accepts an absolute drive path with forward slashes).
220
+ clientModule = resolve(cwd, fw.clientModule).replaceAll("\\", "/")
218
221
  } else {
219
222
  // A specifier that is neither `./`-relative, scoped (`@…`), nor absolute is read as a BARE PACKAGE
220
223
  // specifier - resolved against `node_modules`, not `cwd`. If a real local file sits at that path
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Project context and trust-local utilities for the MCP server.
3
+ *
4
+ * Resources, prompts, path scoping, and monorepo namespacing are independent of the JSON-RPC loop and
5
+ * of backend reflection. App loading is injected through the shared cached loader seam.
6
+ */
7
+
8
+ import { realpathSync } from "node:fs"
9
+ import { readFile } from "node:fs/promises"
10
+ import { basename, isAbsolute, relative, resolve, sep } from "node:path"
11
+ import type { LoadedApp } from "./load.ts"
12
+ import { createCachedAppLoader } from "./mcp-exec.ts"
13
+ import type { McpPrompt, McpResource, McpServerFeatures, McpTool } from "./mcp-protocol.ts"
14
+
15
+ function openApiFormat(args: Record<string, unknown>): "json" | "yaml" {
16
+ const format = args.format
17
+ return format === "yaml" ? "yaml" : "json"
18
+ }
19
+
20
+ export async function openApiHandler(
21
+ args: Record<string, unknown>,
22
+ loadAppCached: (outDirName?: string) => Promise<LoadedApp>,
23
+ ): Promise<string> {
24
+ const { renderOpenApiWithTypes } = await import("./openapi-tool.ts")
25
+ const pathPrefix = typeof args.path === "string" ? args.path : undefined
26
+ return renderOpenApiWithTypes(await loadAppCached(), openApiFormat(args), pathPrefix)
27
+ }
28
+
29
+ async function readProjectFile(
30
+ cwd: string,
31
+ relativeFile: string,
32
+ maxChars: number,
33
+ ): Promise<string> {
34
+ const target = resolve(cwd, relativeFile)
35
+ const root = resolve(cwd)
36
+ if (target !== root && !target.startsWith(`${root}${sep}`)) {
37
+ throw new Error(`refusing to read outside project root: ${relativeFile}`)
38
+ }
39
+ try {
40
+ const text = await readFile(target, "utf8")
41
+ return text.length <= maxChars
42
+ ? text
43
+ : `${text.slice(0, maxChars)}\n…(trimmed; read ${relativeFile} directly for the rest)`
44
+ } catch (err) {
45
+ if (err && typeof err === "object" && (err as { code?: string }).code === "ENOENT") {
46
+ return `No ${relativeFile} found in ${basename(cwd)}.`
47
+ }
48
+ throw err
49
+ }
50
+ }
51
+
52
+ function promptText(
53
+ text: string,
54
+ ): readonly [
55
+ { readonly role: "user"; readonly content: { readonly type: "text"; readonly text: string } },
56
+ ] {
57
+ return [{ role: "user", content: { type: "text", text } }]
58
+ }
59
+
60
+ export function projectResources(
61
+ cwd: string,
62
+ loadAppCached: (outDirName?: string) => Promise<LoadedApp> = createCachedAppLoader(cwd),
63
+ ): McpResource[] {
64
+ return [
65
+ {
66
+ uri: "nifra://routes",
67
+ name: "API routes",
68
+ description:
69
+ "Structured API routes with typed-client calls and compact request/response shapes.",
70
+ mimeType: "application/json",
71
+ read: async () => {
72
+ const { routesToJson } = await import("./introspect.ts")
73
+ return { text: JSON.stringify(routesToJson(await loadAppCached()), null, 2) }
74
+ },
75
+ },
76
+ {
77
+ uri: "nifra://openapi",
78
+ name: "OpenAPI 3.1",
79
+ description: "OpenAPI document generated from backend.ts using @nifrajs/schema.",
80
+ mimeType: "application/json",
81
+ read: async () => ({ text: await openApiHandler({ format: "json" }, loadAppCached) }),
82
+ },
83
+ {
84
+ uri: "nifra://package-json",
85
+ name: "package.json",
86
+ description: "Project package metadata and scripts.",
87
+ mimeType: "application/json",
88
+ read: async () => ({ text: await readProjectFile(cwd, "package.json", 40_000) }),
89
+ },
90
+ {
91
+ uri: "nifra://agents-md",
92
+ name: "AGENTS.md",
93
+ description: "Repository-specific agent instructions if the project has them.",
94
+ mimeType: "text/markdown",
95
+ read: async () => ({ text: await readProjectFile(cwd, "AGENTS.md", 40_000) }),
96
+ },
97
+ ]
98
+ }
99
+
100
+ export function projectPrompts(): McpPrompt[] {
101
+ return [
102
+ {
103
+ name: "nifra_new_route",
104
+ description:
105
+ "Implement a new file route with the right routes/ filename, examples, and checks.",
106
+ arguments: [
107
+ { name: "path", description: 'URL path, e.g. "/users/:id".', required: true },
108
+ { name: "goal", description: "What the page should do.", required: false },
109
+ ],
110
+ handler: async (args) =>
111
+ promptText(
112
+ [
113
+ `Create a nifra page route for ${JSON.stringify(args.path ?? "/new-route")}.`,
114
+ args.goal ? `Goal: ${String(args.goal)}` : undefined,
115
+ 'Use `nifra_context` with `{ kind: "pages" }`, then `nifra_scaffold` for the exact file path.',
116
+ "If the stub is not writable for this framework, call `nifra_example` for a verified page/loader example before editing.",
117
+ "Verify with `nifra_render` for the route and finish with `nifra_check`.",
118
+ ]
119
+ .filter(Boolean)
120
+ .join("\n"),
121
+ ),
122
+ },
123
+ {
124
+ name: "nifra_add_endpoint",
125
+ description:
126
+ "Add or update a backend endpoint with schemas, typed-client usage, and verification.",
127
+ arguments: [
128
+ { name: "method", description: "HTTP method.", required: true },
129
+ { name: "path", description: 'API path, e.g. "/users/:id".', required: true },
130
+ { name: "goal", description: "What the endpoint should do.", required: false },
131
+ ],
132
+ handler: async (args) =>
133
+ promptText(
134
+ [
135
+ `Add a nifra backend endpoint: ${String(args.method ?? "GET").toUpperCase()} ${String(args.path ?? "/api")}.`,
136
+ args.goal ? `Goal: ${String(args.goal)}` : undefined,
137
+ "Read `nifra://routes` or call `nifra_routes` first so the new route fits the existing API shape.",
138
+ "Use route schemas for untrusted body/query input and declare `response` when the frontend consumes the shape.",
139
+ "Verify behavior with `nifra_run`, then run `nifra_check` and `nifra_test` for the touched area.",
140
+ ]
141
+ .filter(Boolean)
142
+ .join("\n"),
143
+ ),
144
+ },
145
+ {
146
+ name: "nifra_debug_drift",
147
+ description:
148
+ "Debug frontend/backend contract drift using the typed client and checker output.",
149
+ arguments: [
150
+ { name: "symptom", description: "The error or behavior to investigate.", required: false },
151
+ ],
152
+ handler: async (args) =>
153
+ promptText(
154
+ [
155
+ "Debug nifra contract drift.",
156
+ args.symptom ? `Symptom: ${String(args.symptom)}` : undefined,
157
+ "Start with `nifra_check`; use each diagnostic as the source of truth.",
158
+ "Read `nifra://routes` for the exact typed-client calls and compact body/query/response shapes.",
159
+ "Prefer `client<typeof app>` over hand-rolled internal `fetch`. Verify fixed endpoints with `nifra_run`.",
160
+ ]
161
+ .filter(Boolean)
162
+ .join("\n"),
163
+ ),
164
+ },
165
+ ]
166
+ }
167
+
168
+ export function projectFeatures(
169
+ cwd: string,
170
+ loadAppCached: (outDirName?: string) => Promise<LoadedApp> = createCachedAppLoader(cwd),
171
+ ): McpServerFeatures {
172
+ return { resources: projectResources(cwd, loadAppCached), prompts: projectPrompts() }
173
+ }
174
+
175
+ /**
176
+ * Resolve an optional `dir` tool argument - a subdirectory of the project root the caller wants to scope a
177
+ * check/test to (e.g. `nifra check` on `app/` when the MCP server's root is a monorepo). Returns the
178
+ * absolute target, or `null` if `dir` escapes the root (a path-traversal guard: no `..` out, no absolute
179
+ * path elsewhere). `undefined`/empty → the root itself.
180
+ */
181
+ export function resolveProjectDir(root: string, dir: string | undefined): string | null {
182
+ if (dir === undefined || dir === "") return root
183
+ const target = resolve(root, dir)
184
+ let canonicalRoot: string
185
+ try {
186
+ canonicalRoot = realpathSync(root)
187
+ } catch {
188
+ const lexical = relative(root, target)
189
+ return lexical === "" || (!lexical.startsWith("..") && !isAbsolute(lexical)) ? target : null
190
+ }
191
+ let probe = target
192
+ const missing: string[] = []
193
+ while (true) {
194
+ try {
195
+ const canonicalProbe = realpathSync(probe)
196
+ const rel = relative(canonicalRoot, canonicalProbe)
197
+ if (rel.startsWith("..") || isAbsolute(rel)) return null
198
+ return missing.length === 0 ? canonicalProbe : resolve(canonicalProbe, ...missing.reverse())
199
+ } catch {
200
+ const parent = resolve(probe, "..")
201
+ if (parent === probe) return null
202
+ // `basename`, not a slice past `parent`: when `parent` is the filesystem root its trailing
203
+ // separator is part of it, so `parent.length + 1` eats the first character of the segment and
204
+ // the path gets rebuilt wrong.
205
+ missing.push(basename(probe))
206
+ probe = parent
207
+ }
208
+ }
209
+ }
210
+
211
+ /** Consistent error string for a `dir` that escapes the project root. */
212
+ export function dirError(dir: string | undefined): string {
213
+ return JSON.stringify(
214
+ { ok: false, error: `dir must be a subdirectory of the project root - "${dir}" escapes it.` },
215
+ null,
216
+ 2,
217
+ )
218
+ }
219
+
220
+ /** Build the project-scoped tools for `cwd`. */
221
+ export interface CommandMcpToolOptions {
222
+ readonly cwd: string
223
+ readonly loadAppCached?: () => Promise<LoadedApp>
224
+ }
225
+
226
+ /** Adapt one executable catalog spec to its MCP descriptor and project-scoped handler. */
227
+ export function namespaceForApp(
228
+ name: string,
229
+ tools: McpTool[],
230
+ features: McpServerFeatures,
231
+ ): { tools: McpTool[]; features: McpServerFeatures } {
232
+ const prefix = `nifra_${name}_`
233
+ const namespacedTools = tools.map((t) => ({
234
+ ...t,
235
+ name: t.name.startsWith("nifra_") ? t.name.replace(/^nifra_/, prefix) : `${name}_${t.name}`,
236
+ }))
237
+ const namespacedResources = (features.resources ?? []).map((r) => ({
238
+ ...r,
239
+ uri: r.uri.replace(/^nifra:\/\//, `nifra://${name}/`),
240
+ }))
241
+ const namespacedPrompts = (features.prompts ?? []).map((p) => ({
242
+ ...p,
243
+ name: p.name.replace(/^nifra_/, prefix),
244
+ }))
245
+ return {
246
+ tools: namespacedTools,
247
+ features: { resources: namespacedResources, prompts: namespacedPrompts },
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Merge the backend-derived resources/prompts into `base` - and keep a project that cannot be loaded
253
+ * from deciding whether the server starts at all.
254
+ *
255
+ * Resources and prompts are OPTIONAL capabilities extracted from the app's backend, so this load is a
256
+ * best-effort enrichment. It was awaited unguarded, which made it a hard boot requirement: `loadApp`
257
+ * needs a web config (`adapter` + `clientModule`) and a `routes/` directory, and a backend-only
258
+ * project - the shape `create-nifra`'s DEFAULT template produces - has neither. On those projects the
259
+ * throw escaped before the JSON-RPC loop began, so the server wrote nothing and exited. `nifra
260
+ * init-agents` would happily register an `.mcp.json` pointing at a server that could never start, and
261
+ * every tool went with it, including the twelve that never touch the app (docs, examples, types,
262
+ * check, doctor, levels, test).
263
+ *
264
+ * Degrading costs only the backend resources/prompts. Tools that genuinely need the app still fail,
265
+ * but per call, with their own message - which is a diagnosis instead of a silence.
266
+ */
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { renderDocsResult } from "./docs-search.ts"
11
11
  import { type Example, renderExamplesResult } from "./examples.ts"
12
+ import { renderFrontendResult } from "./frontend-guidance.ts"
12
13
  import { renderLearnResult } from "./learn.ts"
13
14
  import type { McpTool } from "./mcp-protocol.ts"
14
15
  import { renderTypesResult, type TypeEntry } from "./types-search.ts"
@@ -147,5 +148,41 @@ export function docsTools(
147
148
  },
148
149
  handler: async (args) => renderLearnResult((args as { step?: number }).step),
149
150
  },
151
+ {
152
+ name: "nifra_frontend",
153
+ annotations: {
154
+ title: "Frontend footgun guidance",
155
+ readOnlyHint: true,
156
+ openWorldHint: false,
157
+ },
158
+ description:
159
+ 'Diagnose a CLIENT-SIDE nifra problem by symptom, across every adapter (React/Preact/Solid/Vue/Svelte/vanilla). Returns the cause, the concrete fix, and how to verify it. Covers the nifra SEAM (a server-only import leaking into a client component, a hydration mismatch, a duplicated framework runtime, loader-data typing) - where it points at the nifra_* tool that fixes and checks it - and the per-framework reactivity-loss idioms (Vue ref, Solid props, Svelte runes, React effect deps), where it points at that framework\'s own ESLint plugin. Call with no args for the index; pass `symptom` (e.g. "hydration mismatch", "value stopped updating") and/or `adapter` to filter. Use this when a rendered page misbehaves and nifra_check is green (check owns the static seam; this owns the rest).',
160
+ inputSchema: {
161
+ type: "object",
162
+ properties: {
163
+ symptom: {
164
+ type: "string",
165
+ maxLength: 256,
166
+ description: "What you observe (omit for the index).",
167
+ },
168
+ adapter: {
169
+ type: "string",
170
+ enum: ["react", "preact", "solid", "vue", "svelte", "vanilla"],
171
+ description:
172
+ "Filter to one adapter's entries (plus the adapter-independent seam entries).",
173
+ },
174
+ limit: { type: "number", description: "Max entries to return (default 3, max 5)." },
175
+ },
176
+ additionalProperties: false,
177
+ },
178
+ handler: async (args) => {
179
+ const { symptom, adapter, limit } = args as {
180
+ symptom?: string
181
+ adapter?: string
182
+ limit?: number
183
+ }
184
+ return renderFrontendResult({ symptom, adapter, limit: clamp(limit, 1, 5, 3) })
185
+ },
186
+ },
150
187
  ]
151
188
  }