@nifrajs/cli 3.1.0 → 3.2.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.
- package/README.md +10 -0
- package/dist/assure-hydration.d.ts.map +1 -1
- package/dist/assure-hydration.js +6 -1
- package/dist/assure-hydration.js.map +1 -1
- package/dist/assure.d.ts.map +1 -1
- package/dist/assure.js +3 -2
- package/dist/assure.js.map +1 -1
- package/dist/check-diagnostics.d.ts +165 -0
- package/dist/check-diagnostics.d.ts.map +1 -0
- package/dist/check-diagnostics.js +1009 -0
- package/dist/check-diagnostics.js.map +1 -0
- package/dist/check-scan.d.ts +245 -0
- package/dist/check-scan.d.ts.map +1 -0
- package/dist/check-scan.js +1599 -0
- package/dist/check-scan.js.map +1 -0
- package/dist/check.d.ts +4 -324
- package/dist/check.d.ts.map +1 -1
- package/dist/check.js +8 -2366
- package/dist/check.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +247 -10
- package/dist/cli.js.map +1 -1
- package/dist/command-catalog.d.ts +21 -1
- package/dist/command-catalog.d.ts.map +1 -1
- package/dist/command-catalog.js +122 -0
- package/dist/command-catalog.js.map +1 -1
- package/dist/env-file.js +5 -5
- package/dist/env-file.js.map +1 -1
- package/dist/frontend-guidance.d.ts +57 -0
- package/dist/frontend-guidance.d.ts.map +1 -0
- package/dist/frontend-guidance.js +195 -0
- package/dist/frontend-guidance.js.map +1 -0
- package/dist/levels-tool.d.ts.map +1 -1
- package/dist/levels-tool.js +6 -0
- package/dist/levels-tool.js.map +1 -1
- package/dist/load.d.ts.map +1 -1
- package/dist/load.js +4 -1
- package/dist/load.js.map +1 -1
- package/dist/mcp-context.d.ts +48 -0
- package/dist/mcp-context.d.ts.map +1 -0
- package/dist/mcp-context.js +215 -0
- package/dist/mcp-context.js.map +1 -0
- package/dist/mcp-docs-tools.d.ts.map +1 -1
- package/dist/mcp-docs-tools.js +31 -0
- package/dist/mcp-docs-tools.js.map +1 -1
- package/dist/mcp-exec.d.ts +74 -0
- package/dist/mcp-exec.d.ts.map +1 -0
- package/dist/mcp-exec.js +844 -0
- package/dist/mcp-exec.js.map +1 -0
- package/dist/mcp-http.js +1 -1
- package/dist/mcp-io.d.ts +26 -0
- package/dist/mcp-io.d.ts.map +1 -0
- package/dist/mcp-io.js +100 -0
- package/dist/mcp-io.js.map +1 -0
- package/dist/mcp-reflect.d.ts +16 -0
- package/dist/mcp-reflect.d.ts.map +1 -0
- package/dist/mcp-reflect.js +101 -0
- package/dist/mcp-reflect.js.map +1 -0
- package/dist/mcp-root.d.ts +7 -0
- package/dist/mcp-root.d.ts.map +1 -1
- package/dist/mcp-root.js +51 -3
- package/dist/mcp-root.js.map +1 -1
- package/dist/mcp.d.ts +10 -92
- package/dist/mcp.d.ts.map +1 -1
- package/dist/mcp.js +13 -1232
- package/dist/mcp.js.map +1 -1
- package/dist/openapi-tool.d.ts +5 -10
- package/dist/openapi-tool.d.ts.map +1 -1
- package/dist/openapi-tool.js +21 -2
- package/dist/openapi-tool.js.map +1 -1
- package/dist/openapi-types.d.ts +21 -0
- package/dist/openapi-types.d.ts.map +1 -0
- package/dist/openapi-types.js +214 -0
- package/dist/openapi-types.js.map +1 -0
- package/dist/port.d.ts.map +1 -1
- package/dist/port.js +2 -1
- package/dist/port.js.map +1 -1
- package/dist/project-facts.d.ts +2 -1
- package/dist/project-facts.d.ts.map +1 -1
- package/dist/project-facts.js.map +1 -1
- package/dist/release-verification.d.ts +4 -1
- package/dist/release-verification.d.ts.map +1 -1
- package/dist/release-verification.js +6 -138
- package/dist/release-verification.js.map +1 -1
- package/dist/rules/codes.d.ts +4 -0
- package/dist/rules/codes.d.ts.map +1 -1
- package/dist/rules/codes.js +4 -0
- package/dist/rules/codes.js.map +1 -1
- package/dist/rules/islands.d.ts +4 -0
- package/dist/rules/islands.d.ts.map +1 -0
- package/dist/rules/islands.js +155 -0
- package/dist/rules/islands.js.map +1 -0
- package/dist/rules/nano.d.ts +6 -0
- package/dist/rules/nano.d.ts.map +1 -0
- package/dist/rules/nano.js +264 -0
- package/dist/rules/nano.js.map +1 -0
- package/dist/rules/security.d.ts.map +1 -1
- package/dist/rules/security.js +38 -4
- package/dist/rules/security.js.map +1 -1
- package/dist/scaffold.d.ts +12 -6
- package/dist/scaffold.d.ts.map +1 -1
- package/dist/scaffold.js +149 -10
- package/dist/scaffold.js.map +1 -1
- package/dist/search-terms.d.ts.map +1 -1
- package/dist/search-terms.js +5 -3
- package/dist/search-terms.js.map +1 -1
- package/dist/stylex-migrate.d.ts +38 -0
- package/dist/stylex-migrate.d.ts.map +1 -0
- package/dist/stylex-migrate.js +1052 -0
- package/dist/stylex-migrate.js.map +1 -0
- package/dist/sync-manifest.d.ts.map +1 -1
- package/dist/sync-manifest.js +2 -1
- package/dist/sync-manifest.js.map +1 -1
- package/dist/verification-plan.d.ts +24 -0
- package/dist/verification-plan.d.ts.map +1 -0
- package/dist/verification-plan.js +116 -0
- package/dist/verification-plan.js.map +1 -0
- package/dist/work-graph.d.ts.map +1 -1
- package/dist/work-graph.js +6 -3
- package/dist/work-graph.js.map +1 -1
- package/docs/examples.json +36 -0
- package/docs/llms-full.txt +1226 -14
- package/docs/types.json +4185 -87
- package/package.json +9 -9
- package/src/assure-hydration.ts +6 -1
- package/src/assure.ts +4 -2
- package/src/check-diagnostics.ts +1219 -0
- package/src/check-scan.ts +1825 -0
- package/src/check.ts +47 -2752
- package/src/cli.ts +252 -10
- package/src/command-catalog.ts +155 -0
- package/src/env-file.ts +5 -5
- package/src/frontend-guidance.ts +259 -0
- package/src/levels-tool.ts +6 -0
- package/src/load.ts +4 -1
- package/src/mcp-context.ts +266 -0
- package/src/mcp-docs-tools.ts +37 -0
- package/src/mcp-exec.ts +1040 -0
- package/src/mcp-http.ts +1 -1
- package/src/mcp-io.ts +118 -0
- package/src/mcp-reflect.ts +140 -0
- package/src/mcp-root.ts +62 -4
- package/src/mcp.ts +61 -1511
- package/src/openapi-tool.ts +32 -2
- package/src/openapi-types.ts +261 -0
- package/src/port.ts +2 -1
- package/src/project-facts.ts +2 -4
- package/src/release-verification.ts +22 -164
- package/src/rules/codes.ts +4 -0
- package/src/rules/islands.ts +171 -0
- package/src/rules/nano.ts +295 -0
- package/src/rules/security.ts +40 -4
- package/src/scaffold.ts +169 -9
- package/src/search-terms.ts +7 -3
- package/src/stylex-migrate.ts +1139 -0
- package/src/sync-manifest.ts +2 -1
- package/src/verification-plan.ts +242 -0
- package/src/work-graph.ts +6 -3
package/dist/mcp-exec.js
ADDED
|
@@ -0,0 +1,844 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared project-tool execution for stdio, run, and render.
|
|
3
|
+
*
|
|
4
|
+
* This module owns child-process limits, warm-worker lifecycle, source fingerprinting, and cached app
|
|
5
|
+
* loading. It has no JSON-RPC transport or root-trust policy, so those seams remain independently
|
|
6
|
+
* replaceable.
|
|
7
|
+
*/
|
|
8
|
+
import { stat } from "node:fs/promises";
|
|
9
|
+
import { resolve, sep } from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { Glob } from "bun";
|
|
12
|
+
import { commandCatalog, commandMcpName, findCommandSpec, } from "./command-catalog.js";
|
|
13
|
+
import { collectContractProof } from "./contract-proof.js";
|
|
14
|
+
import { loadDocsCorpus } from "./docs-search.js";
|
|
15
|
+
import { loadExamplesCorpus } from "./examples.js";
|
|
16
|
+
import { dirError, openApiHandler, resolveProjectDir, } from "./mcp-context.js";
|
|
17
|
+
import { docsTools } from "./mcp-docs-tools.js";
|
|
18
|
+
import { CHILD_OUTPUT_MAX_BYTES, CHILD_TIMEOUT_MS, LOCAL_TOOL_FETCH_TIMEOUT_MS, notNifraResponse, readBoundedResponse, readBoundedStream, timeoutMessage, validateLocalPort, } from "./mcp-io.js";
|
|
19
|
+
import { loadTypesCorpus } from "./types-search.js";
|
|
20
|
+
/** Path to a sibling child entry (`mcp-run` / `mcp-render` / `mcp-ws`), resolved next to this module (`.ts` in
|
|
21
|
+
* dev, `.js` once built). Each runs in a FRESH subprocess per call so the project's current code loads. */
|
|
22
|
+
export function toMcpTool(source, options) {
|
|
23
|
+
const spec = "run" in source ? source : findCommandSpec(source.name);
|
|
24
|
+
if (spec === undefined)
|
|
25
|
+
throw new Error(`missing command spec for ${source.name}`);
|
|
26
|
+
const entry = "run" in source ? undefined : source;
|
|
27
|
+
const { cwd } = options;
|
|
28
|
+
const loadAppCached = options.loadAppCached ?? createCachedAppLoader(cwd);
|
|
29
|
+
return {
|
|
30
|
+
name: commandMcpName(entry?.name ?? spec.name),
|
|
31
|
+
description: entry?.summary ?? spec.summary,
|
|
32
|
+
inputSchema: entry?.inputSchema ?? spec.input.jsonSchema,
|
|
33
|
+
handler: async (args, context) => {
|
|
34
|
+
const raw = { ...args };
|
|
35
|
+
const dir = raw.dir;
|
|
36
|
+
if (dir !== undefined && typeof dir !== "string")
|
|
37
|
+
return dirError(undefined);
|
|
38
|
+
const target = resolveProjectDir(cwd, dir);
|
|
39
|
+
if (target === null)
|
|
40
|
+
return dirError(dir);
|
|
41
|
+
if (typeof raw.config === "string") {
|
|
42
|
+
const config = resolve(target, raw.config);
|
|
43
|
+
if (config !== target && !config.startsWith(`${target}${sep}`))
|
|
44
|
+
return JSON.stringify({ ok: false, error: "config must stay inside the selected project directory" }, null, 2);
|
|
45
|
+
}
|
|
46
|
+
delete raw.dir;
|
|
47
|
+
let input;
|
|
48
|
+
try {
|
|
49
|
+
input = spec.input.parse(raw);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
return JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }, null, 2);
|
|
53
|
+
}
|
|
54
|
+
const commandContext = {
|
|
55
|
+
cwd: target,
|
|
56
|
+
signal: context.signal,
|
|
57
|
+
progress: () => context.reportProgress?.(0.5, 1),
|
|
58
|
+
...(target === cwd ? { loadApp: loadAppCached } : {}),
|
|
59
|
+
};
|
|
60
|
+
const output = await spec.run(input, commandContext);
|
|
61
|
+
const value = spec.json?.(output, input) ?? output;
|
|
62
|
+
return typeof value === "string" ? value : JSON.stringify(value, null, 2);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export function catalogProjectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
|
|
67
|
+
return commandCatalog
|
|
68
|
+
.filter((entry) => entry.transports.includes("mcp"))
|
|
69
|
+
.map((entry) => {
|
|
70
|
+
const spec = findCommandSpec(entry.name);
|
|
71
|
+
if (spec === undefined)
|
|
72
|
+
throw new Error(`missing command spec for ${entry.name}`);
|
|
73
|
+
return toMcpTool(spec, { cwd, loadAppCached });
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export function projectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
|
|
77
|
+
const warmRun = createWarmHandler("mcp-run", cwd, "run");
|
|
78
|
+
const warmRender = createWarmHandler("mcp-render", cwd, "render");
|
|
79
|
+
const catalogTools = catalogProjectTools(cwd, () => loadAppCached());
|
|
80
|
+
const legacyTools = [
|
|
81
|
+
{
|
|
82
|
+
name: "nifra_verify",
|
|
83
|
+
description: "Run the shared repository verification plan. Set release=true for the full release plan; the response preserves the declarative gate order and each gate's remediation.",
|
|
84
|
+
inputSchema: {
|
|
85
|
+
type: "object",
|
|
86
|
+
properties: {
|
|
87
|
+
release: {
|
|
88
|
+
type: "boolean",
|
|
89
|
+
description: "Run the full release plan instead of the default plan.",
|
|
90
|
+
},
|
|
91
|
+
dir: {
|
|
92
|
+
type: "string",
|
|
93
|
+
description: "Project subdirectory to resolve the repository from.",
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
additionalProperties: false,
|
|
97
|
+
},
|
|
98
|
+
handler: async (args) => {
|
|
99
|
+
const raw = args;
|
|
100
|
+
if (raw.release !== undefined && typeof raw.release !== "boolean") {
|
|
101
|
+
return JSON.stringify({ ok: false, error: "release must be a boolean" }, null, 2);
|
|
102
|
+
}
|
|
103
|
+
if (raw.dir !== undefined && typeof raw.dir !== "string") {
|
|
104
|
+
return JSON.stringify({ ok: false, error: "dir must be a string" }, null, 2);
|
|
105
|
+
}
|
|
106
|
+
const target = resolveProjectDir(cwd, raw.dir);
|
|
107
|
+
if (target === null)
|
|
108
|
+
return dirError(raw.dir);
|
|
109
|
+
const { collectReleaseVerification } = await import("./release-verification.js");
|
|
110
|
+
return JSON.stringify(await collectReleaseVerification(target, {
|
|
111
|
+
mode: raw.release === true ? "release" : "default",
|
|
112
|
+
}), null, 2);
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
name: "nifra_contract_proof",
|
|
117
|
+
description: "Compare the current route contract with its snapshot and join each changed route to its route-assurance and capability evidence. Returns hasBreaking as the gate. The typed-contract check is lazy and runs only when check is true.",
|
|
118
|
+
inputSchema: {
|
|
119
|
+
type: "object",
|
|
120
|
+
properties: {
|
|
121
|
+
baseline: {
|
|
122
|
+
type: "string",
|
|
123
|
+
description: "Snapshot path relative to the selected project directory. Defaults to api-snapshot.json.",
|
|
124
|
+
},
|
|
125
|
+
check: {
|
|
126
|
+
type: "boolean",
|
|
127
|
+
description: "Also run the typed-contract check. Default false to keep the diff lazy.",
|
|
128
|
+
},
|
|
129
|
+
dir: {
|
|
130
|
+
type: "string",
|
|
131
|
+
description: "Project subdirectory to inspect.",
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
additionalProperties: false,
|
|
135
|
+
},
|
|
136
|
+
handler: async (args) => {
|
|
137
|
+
const raw = args;
|
|
138
|
+
if (raw.dir !== undefined && typeof raw.dir !== "string") {
|
|
139
|
+
return JSON.stringify({ ok: false, error: "dir must be a string" }, null, 2);
|
|
140
|
+
}
|
|
141
|
+
if (raw.baseline !== undefined && typeof raw.baseline !== "string") {
|
|
142
|
+
return JSON.stringify({ ok: false, error: "baseline must be a string" }, null, 2);
|
|
143
|
+
}
|
|
144
|
+
const dir = raw.dir;
|
|
145
|
+
const baseline = raw.baseline;
|
|
146
|
+
const target = resolveProjectDir(cwd, dir);
|
|
147
|
+
if (target === null)
|
|
148
|
+
return dirError(dir);
|
|
149
|
+
if (baseline !== undefined && baseline.trim() === "") {
|
|
150
|
+
return JSON.stringify({ ok: false, error: "baseline must not be empty" }, null, 2);
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
return JSON.stringify(await collectContractProof(target, {
|
|
154
|
+
...(baseline === undefined ? {} : { baselinePath: baseline }),
|
|
155
|
+
...(raw.check === undefined ? {} : { check: raw.check === true }),
|
|
156
|
+
}), null, 2);
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
return JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }, null, 2);
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
name: "nifra_explain",
|
|
165
|
+
description: "Turn a nifra error into a STRUCTURED diagnostic instead of eyeballing a stack trace: a stable `code`, the top frame in YOUR source, a codeframe around the offending line, and - when nifra recognises the failure - the plain-language `cause` + `fix` + docs anchor. Pass `error` (and `stack` if you have it, e.g. from nifra_run/nifra_test output or a failing build) to explain a specific failure; or pass `port` to fetch the running dev server's most recent SSR failure from `/__nifra/last-error`. Returns the same JSON the dev overlay renders.",
|
|
166
|
+
inputSchema: {
|
|
167
|
+
type: "object",
|
|
168
|
+
properties: {
|
|
169
|
+
error: {
|
|
170
|
+
type: "string",
|
|
171
|
+
description: "The error message to explain (copy it from nifra_run/nifra_test output or a failing build).",
|
|
172
|
+
},
|
|
173
|
+
stack: {
|
|
174
|
+
type: "string",
|
|
175
|
+
description: "The error's stack trace, if you have it - enables the source codeframe and the top user frame.",
|
|
176
|
+
},
|
|
177
|
+
name: {
|
|
178
|
+
type: "string",
|
|
179
|
+
description: "The error's class name (e.g. TypeError, SchemaError), if known - sharpens classification.",
|
|
180
|
+
},
|
|
181
|
+
port: {
|
|
182
|
+
type: "number",
|
|
183
|
+
description: "Instead of a pasted error, fetch the running dev server's most recent SSR failure from this port.",
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
additionalProperties: false,
|
|
187
|
+
},
|
|
188
|
+
handler: async (args) => {
|
|
189
|
+
const { error, stack, name, port } = args;
|
|
190
|
+
if (error !== undefined || stack !== undefined) {
|
|
191
|
+
const { buildDiagnostic } = await import("@nifrajs/web/diagnostic");
|
|
192
|
+
const e = new Error(error ?? "");
|
|
193
|
+
if (name !== undefined)
|
|
194
|
+
e.name = name;
|
|
195
|
+
if (stack !== undefined)
|
|
196
|
+
e.stack = stack;
|
|
197
|
+
return JSON.stringify(buildDiagnostic(e, { root: cwd }), null, 2);
|
|
198
|
+
}
|
|
199
|
+
if (port !== undefined) {
|
|
200
|
+
const validPort = validateLocalPort(port);
|
|
201
|
+
if (validPort === undefined) {
|
|
202
|
+
return JSON.stringify({ code: "NIFRA_INVALID_PORT", message: "port must be an integer from 1 to 65535." }, null, 2);
|
|
203
|
+
}
|
|
204
|
+
const { LAST_ERROR_PATH } = await import("@nifrajs/web/diagnostic");
|
|
205
|
+
try {
|
|
206
|
+
const res = await fetch(`http://127.0.0.1:${validPort}${LAST_ERROR_PATH}`, {
|
|
207
|
+
signal: AbortSignal.timeout(LOCAL_TOOL_FETCH_TIMEOUT_MS),
|
|
208
|
+
});
|
|
209
|
+
if (res.headers.get("x-nifra-diagnostic") !== "true")
|
|
210
|
+
return notNifraResponse("diagnostic");
|
|
211
|
+
if (!res.ok) {
|
|
212
|
+
return JSON.stringify({
|
|
213
|
+
code: "NIFRA_NONE",
|
|
214
|
+
message: `dev server at :${validPort} returned ${res.status}`,
|
|
215
|
+
}, null, 2);
|
|
216
|
+
}
|
|
217
|
+
return await readBoundedResponse(res);
|
|
218
|
+
}
|
|
219
|
+
catch (cause) {
|
|
220
|
+
return JSON.stringify({
|
|
221
|
+
code: "NIFRA_NONE",
|
|
222
|
+
message: `could not reach a nifra dev server at :${validPort} - ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
223
|
+
}, null, 2);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return JSON.stringify({
|
|
227
|
+
code: "NIFRA_NONE",
|
|
228
|
+
message: "Pass `error` (and `stack` if available) to explain a failure, or `port` to fetch the dev server's last error.",
|
|
229
|
+
}, null, 2);
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
{
|
|
233
|
+
name: "nifra_inspect",
|
|
234
|
+
description: "Observe what your requests ACTUALLY did on the running dev server - the recent request traces the DevTools plugin records: `{ method, path, status, durationMs, isrStatus, bodyBytes }` per request. The read no other tool gives you: after nifra_run or a real browser request, call this to SEE the outcome (which route answered, the status, how long, ISR hit/miss) instead of guessing. Pass `port` (the running dev server); narrow with `path` (a path prefix) or `limit` (most recent N). Requires the app to mount `@nifrajs/web`'s `devtools()` plugin (which auto-enables in development).",
|
|
235
|
+
inputSchema: {
|
|
236
|
+
type: "object",
|
|
237
|
+
properties: {
|
|
238
|
+
port: { type: "number", description: "The running dev server's port." },
|
|
239
|
+
path: { type: "string", description: "Only traces whose path starts with this prefix." },
|
|
240
|
+
limit: { type: "number", description: "Return only the most recent N traces." },
|
|
241
|
+
},
|
|
242
|
+
required: ["port"],
|
|
243
|
+
additionalProperties: false,
|
|
244
|
+
},
|
|
245
|
+
handler: async (args) => {
|
|
246
|
+
const { port, path, limit } = args;
|
|
247
|
+
if (port === undefined) {
|
|
248
|
+
return JSON.stringify({
|
|
249
|
+
events: [],
|
|
250
|
+
note: "Pass `port` - the running dev server whose request traces to read.",
|
|
251
|
+
}, null, 2);
|
|
252
|
+
}
|
|
253
|
+
try {
|
|
254
|
+
const validPort = validateLocalPort(port);
|
|
255
|
+
if (validPort === undefined) {
|
|
256
|
+
return JSON.stringify({
|
|
257
|
+
events: [],
|
|
258
|
+
code: "NIFRA_INVALID_PORT",
|
|
259
|
+
note: "port must be an integer from 1 to 65535.",
|
|
260
|
+
}, null, 2);
|
|
261
|
+
}
|
|
262
|
+
const url = new URL(`http://127.0.0.1:${validPort}/_nifra/devtools/state`);
|
|
263
|
+
if (path !== undefined)
|
|
264
|
+
url.searchParams.set("path", path);
|
|
265
|
+
if (limit !== undefined)
|
|
266
|
+
url.searchParams.set("limit", String(limit));
|
|
267
|
+
const res = await fetch(url, {
|
|
268
|
+
signal: AbortSignal.timeout(LOCAL_TOOL_FETCH_TIMEOUT_MS),
|
|
269
|
+
});
|
|
270
|
+
if (res.headers.get("x-nifra-devtools") !== "true")
|
|
271
|
+
return notNifraResponse("DevTools");
|
|
272
|
+
if (res.status === 404) {
|
|
273
|
+
return JSON.stringify({
|
|
274
|
+
events: [],
|
|
275
|
+
note: "No DevTools endpoint on that server. Mount `devtools()` from @nifrajs/web and run in development.",
|
|
276
|
+
}, null, 2);
|
|
277
|
+
}
|
|
278
|
+
if (!res.ok) {
|
|
279
|
+
return JSON.stringify({ events: [], note: `DevTools state returned ${res.status}.` }, null, 2);
|
|
280
|
+
}
|
|
281
|
+
return await readBoundedResponse(res);
|
|
282
|
+
}
|
|
283
|
+
catch (cause) {
|
|
284
|
+
const validPort = validateLocalPort(port);
|
|
285
|
+
return JSON.stringify({
|
|
286
|
+
events: [],
|
|
287
|
+
note: `Could not reach a dev server at :${validPort ?? String(port)} - ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
288
|
+
}, null, 2);
|
|
289
|
+
}
|
|
290
|
+
},
|
|
291
|
+
},
|
|
292
|
+
{
|
|
293
|
+
name: "nifra_openapi",
|
|
294
|
+
description: 'Return this project\'s backend OpenAPI 3.1 document generated from backend.ts route schemas via @nifrajs/schema. Use `format:"json"` for machine edits (default) or `format:"yaml"` for humans. Pass `path` (a route prefix like /api/orders, mirroring nifra_routes) to narrow a large backend to operations under that prefix instead of the whole document. Frontend-only apps return a valid empty paths object.',
|
|
295
|
+
inputSchema: {
|
|
296
|
+
type: "object",
|
|
297
|
+
properties: {
|
|
298
|
+
format: {
|
|
299
|
+
type: "string",
|
|
300
|
+
enum: ["json", "yaml"],
|
|
301
|
+
description: "Output format (default: json).",
|
|
302
|
+
},
|
|
303
|
+
path: {
|
|
304
|
+
type: "string",
|
|
305
|
+
description: "Only operations whose path starts with this prefix (omit for the whole document).",
|
|
306
|
+
},
|
|
307
|
+
},
|
|
308
|
+
additionalProperties: false,
|
|
309
|
+
},
|
|
310
|
+
handler: (args) => openApiHandler(args, loadAppCached),
|
|
311
|
+
},
|
|
312
|
+
{
|
|
313
|
+
name: "nifra_run",
|
|
314
|
+
description: "Run HTTP requests through this project's backend and return structured results (status, headers, parsed body, and any thrown error). Use it to verify code after editing: by default the backend is re-loaded in a fresh process each call. Pass warm:true to reuse a hot worker while source files are unchanged; it restarts automatically when files change. Each request: { method?, path, body?, headers? }.",
|
|
315
|
+
inputSchema: {
|
|
316
|
+
type: "object",
|
|
317
|
+
properties: {
|
|
318
|
+
requests: {
|
|
319
|
+
type: "array",
|
|
320
|
+
items: {
|
|
321
|
+
type: "object",
|
|
322
|
+
properties: {
|
|
323
|
+
method: { type: "string" },
|
|
324
|
+
path: { type: "string" },
|
|
325
|
+
body: {},
|
|
326
|
+
headers: { type: "object" },
|
|
327
|
+
},
|
|
328
|
+
required: ["path"],
|
|
329
|
+
},
|
|
330
|
+
},
|
|
331
|
+
entry: {
|
|
332
|
+
type: "string",
|
|
333
|
+
description: "Backend entry file (default: backend.ts | app.ts).",
|
|
334
|
+
},
|
|
335
|
+
warm: {
|
|
336
|
+
type: "boolean",
|
|
337
|
+
description: "Reuse a hot backend worker while source files are unchanged. Default false for maximum isolation.",
|
|
338
|
+
},
|
|
339
|
+
},
|
|
340
|
+
required: ["requests"],
|
|
341
|
+
additionalProperties: false,
|
|
342
|
+
},
|
|
343
|
+
handler: (args, context) => runHandler(cwd, args, context, warmRun),
|
|
344
|
+
},
|
|
345
|
+
{
|
|
346
|
+
name: "nifra_render",
|
|
347
|
+
description: "SSR a page route (routes/) through this project's CURRENT web app and return { status, headers, body: the rendered HTML }. The page half of nifra_run: use it to verify a page renders and its loader ran after an edit. No build needed (a placeholder client entry is used; the SSR HTML renders regardless). Each request: { path, headers? }. By default re-loaded in a fresh process each call; pass warm:true to reuse a hot worker while source files are unchanged (it restarts automatically when files change), mirroring nifra_run.",
|
|
348
|
+
inputSchema: {
|
|
349
|
+
type: "object",
|
|
350
|
+
properties: {
|
|
351
|
+
requests: {
|
|
352
|
+
type: "array",
|
|
353
|
+
items: {
|
|
354
|
+
type: "object",
|
|
355
|
+
properties: {
|
|
356
|
+
path: { type: "string" },
|
|
357
|
+
headers: { type: "object" },
|
|
358
|
+
},
|
|
359
|
+
required: ["path"],
|
|
360
|
+
},
|
|
361
|
+
},
|
|
362
|
+
warm: {
|
|
363
|
+
type: "boolean",
|
|
364
|
+
description: "Reuse a hot web-app worker while source files are unchanged. Default false for maximum isolation.",
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
required: ["requests"],
|
|
368
|
+
additionalProperties: false,
|
|
369
|
+
},
|
|
370
|
+
handler: (args, context) => renderHandler(cwd, args, context, warmRender),
|
|
371
|
+
},
|
|
372
|
+
{
|
|
373
|
+
name: "nifra_ws",
|
|
374
|
+
description: 'Verify a WebSocket route against this project by starting the backend on an ephemeral localhost port, opening a real Bun WebSocket, sending string frames, and returning structured evidence: { ok, opened, sent, received, close?, error? }. Use after adding or editing app.ws() routes. Pass path including query, e.g. "/chat?token=secret". By default expects one message when no messages are sent, or one response per sent message; set expectMessages:0 to verify connect-only routes.',
|
|
375
|
+
inputSchema: {
|
|
376
|
+
type: "object",
|
|
377
|
+
properties: {
|
|
378
|
+
path: {
|
|
379
|
+
type: "string",
|
|
380
|
+
description: 'App-local WebSocket path, optionally with query, e.g. "/chat?token=secret".',
|
|
381
|
+
},
|
|
382
|
+
messages: {
|
|
383
|
+
type: "array",
|
|
384
|
+
items: { type: "string" },
|
|
385
|
+
description: "String frames to send after the socket opens (max 50).",
|
|
386
|
+
},
|
|
387
|
+
expectMessages: {
|
|
388
|
+
type: "number",
|
|
389
|
+
description: "How many inbound messages must be observed before success (default: messages.length, or 1 with no sent messages; max 50).",
|
|
390
|
+
},
|
|
391
|
+
timeoutMs: {
|
|
392
|
+
type: "number",
|
|
393
|
+
description: "Bounded verification timeout in milliseconds (default 3000, max 30000).",
|
|
394
|
+
},
|
|
395
|
+
entry: {
|
|
396
|
+
type: "string",
|
|
397
|
+
description: "Backend entry file (default: backend.ts | app.ts).",
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
required: ["path"],
|
|
401
|
+
additionalProperties: false,
|
|
402
|
+
},
|
|
403
|
+
handler: (args, context) => wsHandler(cwd, args, context),
|
|
404
|
+
},
|
|
405
|
+
{
|
|
406
|
+
name: "nifra_test",
|
|
407
|
+
description: "Run `bun test` for this project and return bounded structured results: { ok, command, durationMs, exitCode, timedOut, summary, stdout, stderr }. Pass `pattern` to narrow to a test file/path; pass `timeoutMs` (default 30000, max 300000). Use after editing code, alongside nifra_run/nifra_render for behavioral checks.",
|
|
408
|
+
inputSchema: {
|
|
409
|
+
type: "object",
|
|
410
|
+
properties: {
|
|
411
|
+
pattern: {
|
|
412
|
+
type: "string",
|
|
413
|
+
description: "Optional test file/path pattern passed as an argv item to `bun test`.",
|
|
414
|
+
},
|
|
415
|
+
timeoutMs: {
|
|
416
|
+
type: "number",
|
|
417
|
+
description: "Timeout in milliseconds (default 30000, max 300000).",
|
|
418
|
+
},
|
|
419
|
+
dir: {
|
|
420
|
+
type: "string",
|
|
421
|
+
description: 'Run the tests in this subdirectory (relative to the project root), e.g. "app". Use it when the MCP server\'s root is a monorepo but you want to test just one app. Default: the project root.',
|
|
422
|
+
},
|
|
423
|
+
},
|
|
424
|
+
additionalProperties: false,
|
|
425
|
+
},
|
|
426
|
+
handler: async (args, context) => {
|
|
427
|
+
const { collectTestResult } = await import("./test-tool.js");
|
|
428
|
+
const opts = args;
|
|
429
|
+
const target = resolveProjectDir(cwd, opts.dir);
|
|
430
|
+
if (target === null)
|
|
431
|
+
return dirError(opts.dir);
|
|
432
|
+
return JSON.stringify(await collectTestResult(target, args, { signal: context.signal }), null, 2);
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
// nifra_docs + nifra_example are project-independent (corpus-backed); the shared factory keeps their
|
|
436
|
+
// definitions identical to the CLI HTTP server and the site's edge worker.
|
|
437
|
+
...docsTools(loadDocsCorpus, loadExamplesCorpus, loadTypesCorpus),
|
|
438
|
+
{
|
|
439
|
+
name: "nifra_scaffold",
|
|
440
|
+
description: 'Map a URL path to the CORRECT routes/ file and get a contract-correct page stub. Agents routinely place file routes wrong - this applies the convention for you: ":id"/"[id]" → [id], "*rest" → [...rest], "/" → index. Pass path (e.g. "/users/:id"). Returns the file to create + the route-module contract (loader/action/meta/default) + a stub (ready-to-write for react/preact/solid; path+contract for vue/svelte/vanilla - use nifra_example for those bodies).',
|
|
441
|
+
inputSchema: {
|
|
442
|
+
type: "object",
|
|
443
|
+
properties: {
|
|
444
|
+
path: {
|
|
445
|
+
type: "string",
|
|
446
|
+
description: 'The URL path for the new page route, e.g. "/users/:id" or "/blog/*slug".',
|
|
447
|
+
},
|
|
448
|
+
write: {
|
|
449
|
+
type: "boolean",
|
|
450
|
+
description: "When true, create the file if a verified ready-to-write stub exists. Refuses overwrite.",
|
|
451
|
+
},
|
|
452
|
+
variant: {
|
|
453
|
+
type: "string",
|
|
454
|
+
enum: ["default", "stateful"],
|
|
455
|
+
description: 'Stub flavour. "default" is the plain page stub. "stateful" (vanilla only) emits the golden nano pattern - explicit reactivity (signal + computed(fn,[deps]) + keyed bindList + collected cleanups) whose three mistakes NF-C021/C022/C023 catch statically. Use it for a small app with local state (a list a human edits) instead of reaching for a framework.',
|
|
456
|
+
},
|
|
457
|
+
},
|
|
458
|
+
required: ["path"],
|
|
459
|
+
additionalProperties: false,
|
|
460
|
+
},
|
|
461
|
+
handler: async (args) => {
|
|
462
|
+
const { path, write, variant } = args;
|
|
463
|
+
if (typeof path !== "string" || path.length === 0)
|
|
464
|
+
return "scaffold: `path` is required.";
|
|
465
|
+
const flavour = variant === "stateful" ? "stateful" : "default";
|
|
466
|
+
const { frameworkFromClientModule, renderScaffold, writeScaffoldRoute } = await import("./scaffold.js");
|
|
467
|
+
const app = await loadAppCached();
|
|
468
|
+
const framework = frameworkFromClientModule(app.framework.clientModule);
|
|
469
|
+
if (write !== true)
|
|
470
|
+
return renderScaffold(path, framework, flavour);
|
|
471
|
+
const result = await writeScaffoldRoute(cwd, path, framework, flavour);
|
|
472
|
+
const status = result.written
|
|
473
|
+
? `Written: \`${result.file}\``
|
|
474
|
+
: `Not written: ${result.reason ?? "no write performed"}`;
|
|
475
|
+
return `${status}\n\n${renderScaffold(path, framework, flavour)}`;
|
|
476
|
+
},
|
|
477
|
+
},
|
|
478
|
+
{
|
|
479
|
+
name: "nifra_hydrate",
|
|
480
|
+
description: "Run the hydration assurance gate and return stable NF-H diagnostics.",
|
|
481
|
+
inputSchema: {
|
|
482
|
+
type: "object",
|
|
483
|
+
properties: {
|
|
484
|
+
dir: { type: "string", description: "Project subdirectory to inspect." },
|
|
485
|
+
interact: { type: "boolean", description: "Run declared hydration probes." },
|
|
486
|
+
},
|
|
487
|
+
additionalProperties: false,
|
|
488
|
+
},
|
|
489
|
+
handler: async (args) => {
|
|
490
|
+
const opts = args;
|
|
491
|
+
const target = resolveProjectDir(cwd, opts.dir);
|
|
492
|
+
if (target === null)
|
|
493
|
+
return dirError(opts.dir);
|
|
494
|
+
const { runHydrationAssurance } = await import("./assure-hydration.js");
|
|
495
|
+
return JSON.stringify(await runHydrationAssurance(target, { interact: opts.interact === true }), null, 2);
|
|
496
|
+
},
|
|
497
|
+
},
|
|
498
|
+
];
|
|
499
|
+
return [...catalogTools, ...legacyTools];
|
|
500
|
+
}
|
|
501
|
+
function childPath(name) {
|
|
502
|
+
return fileURLToPath(new URL(import.meta.url)).replace(/mcp-exec\.(ts|js)$/, `${name}.$1`);
|
|
503
|
+
}
|
|
504
|
+
/** Spawn `bun <child> <cwd>`, pipe `input` to its stdin, return its stdout (or a stderr-backed error). */
|
|
505
|
+
/**
|
|
506
|
+
* How long a child gets before it is killed.
|
|
507
|
+
*
|
|
508
|
+
* A child loads the app, which runs its module side effects - a database pool, a Redis client, a
|
|
509
|
+
* metrics interval. Any of those keeps the child's event loop alive after the work is done, and the
|
|
510
|
+
* parent is sitting in `await proc.exited`. The children now exit explicitly, so this is the backstop
|
|
511
|
+
* rather than the fix: without it a single wedged child blocks an agent indefinitely, and the caller
|
|
512
|
+
* has no way to tell "still working" from "never returning".
|
|
513
|
+
*
|
|
514
|
+
* Generous enough for a cold start that compiles route modules, short enough that a hang is reported
|
|
515
|
+
* within one attention span rather than after minutes of polling.
|
|
516
|
+
*/
|
|
517
|
+
export async function spawnChild(child, cwd, input, label, signal) {
|
|
518
|
+
if (signal?.aborted)
|
|
519
|
+
return `${label} cancelled before it started.`;
|
|
520
|
+
const proc = Bun.spawn(["bun", childPath(child), cwd], {
|
|
521
|
+
stdin: "pipe",
|
|
522
|
+
stdout: "pipe",
|
|
523
|
+
stderr: "pipe",
|
|
524
|
+
});
|
|
525
|
+
let killed = false;
|
|
526
|
+
const kill = () => {
|
|
527
|
+
if (killed)
|
|
528
|
+
return;
|
|
529
|
+
killed = true;
|
|
530
|
+
proc.kill();
|
|
531
|
+
};
|
|
532
|
+
const abort = () => kill();
|
|
533
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
534
|
+
let timedOut = false;
|
|
535
|
+
const timer = setTimeout(() => {
|
|
536
|
+
timedOut = true;
|
|
537
|
+
kill();
|
|
538
|
+
}, CHILD_TIMEOUT_MS);
|
|
539
|
+
let outputExceeded = false;
|
|
540
|
+
try {
|
|
541
|
+
proc.stdin.write(JSON.stringify(input));
|
|
542
|
+
await proc.stdin.end();
|
|
543
|
+
const [out, err] = await Promise.all([
|
|
544
|
+
readBoundedStream(proc.stdout, CHILD_OUTPUT_MAX_BYTES, () => {
|
|
545
|
+
outputExceeded = true;
|
|
546
|
+
kill();
|
|
547
|
+
}),
|
|
548
|
+
readBoundedStream(proc.stderr, CHILD_OUTPUT_MAX_BYTES, () => {
|
|
549
|
+
outputExceeded = true;
|
|
550
|
+
kill();
|
|
551
|
+
}),
|
|
552
|
+
]);
|
|
553
|
+
await proc.exited;
|
|
554
|
+
if (signal?.aborted) {
|
|
555
|
+
const reason = typeof signal.reason === "string" ? `: ${signal.reason}` : "";
|
|
556
|
+
return `${label} cancelled${reason}.`;
|
|
557
|
+
}
|
|
558
|
+
if (outputExceeded) {
|
|
559
|
+
return `${label} output exceeded ${CHILD_OUTPUT_MAX_BYTES} bytes and was terminated.`;
|
|
560
|
+
}
|
|
561
|
+
// A killed child may still have flushed a complete result before the timer fired; prefer real
|
|
562
|
+
// output over the timeout message so a slow-but-successful render is not reported as a failure.
|
|
563
|
+
const text = out.text.trim();
|
|
564
|
+
if (timedOut && text === "")
|
|
565
|
+
return timeoutMessage(label, CHILD_TIMEOUT_MS);
|
|
566
|
+
return text || `${label} failed:\n${err.text.trim() || "(no output)"}`;
|
|
567
|
+
}
|
|
568
|
+
finally {
|
|
569
|
+
clearTimeout(timer);
|
|
570
|
+
signal?.removeEventListener("abort", abort);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
const WARM_RUN_GLOB = new Glob("**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,json}");
|
|
574
|
+
const WARM_RUN_IGNORED = /(^|\/)(node_modules|dist(-[a-z0-9]+)?|build|\.nifra|\.git|\.wrangler|coverage)\//;
|
|
575
|
+
const WARM_RUN_EXTRA_FILES = ["bun.lock", "bun.lockb"];
|
|
576
|
+
async function warmRunFingerprint(cwd) {
|
|
577
|
+
const parts = [];
|
|
578
|
+
for await (const rawRel of WARM_RUN_GLOB.scan({ cwd, dot: false })) {
|
|
579
|
+
const rel = rawRel.replaceAll("\\", "/");
|
|
580
|
+
if (WARM_RUN_IGNORED.test(rel))
|
|
581
|
+
continue;
|
|
582
|
+
try {
|
|
583
|
+
const s = await stat(resolve(cwd, rel));
|
|
584
|
+
if (s.isFile())
|
|
585
|
+
parts.push(`${rel}:${s.mtimeMs}:${s.size}`);
|
|
586
|
+
}
|
|
587
|
+
catch {
|
|
588
|
+
// A file can disappear while an agent is editing. The next call will rescan the settled tree.
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
for (const rel of WARM_RUN_EXTRA_FILES) {
|
|
592
|
+
parts.push(`${rel}:${await fileFingerprint(resolve(cwd, rel))}`);
|
|
593
|
+
}
|
|
594
|
+
return cacheToken(parts.sort().join("|"));
|
|
595
|
+
}
|
|
596
|
+
function boundedAppend(current, next, max = 12_000) {
|
|
597
|
+
const combined = `${current}${next}`;
|
|
598
|
+
return combined.length <= max ? combined : combined.slice(combined.length - max);
|
|
599
|
+
}
|
|
600
|
+
/** A persistent `mcp-run`/`mcp-render` `--worker` subprocess: the backend/web app is loaded ONCE and
|
|
601
|
+
* reused across newline-delimited `{ id, input }` requests, replying `{ id, output }`. The same machinery
|
|
602
|
+
* powers both `nifra_run warm` and `nifra_render warm` - `child` selects which engine, `label` shapes the
|
|
603
|
+
* cancellation message. The owning handler ({@link createWarmHandler}) fingerprints the source tree and
|
|
604
|
+
* replaces the worker when a file changes, so warm reuse never serves a stale result. Exported for the
|
|
605
|
+
* concurrency test that proves a single per-request cancel doesn't tear down the shared worker. */
|
|
606
|
+
export class WarmWorker {
|
|
607
|
+
fingerprint;
|
|
608
|
+
label;
|
|
609
|
+
proc;
|
|
610
|
+
pending = new Map();
|
|
611
|
+
stdoutBuffer = "";
|
|
612
|
+
stderrBuffer = "";
|
|
613
|
+
nextId = 0;
|
|
614
|
+
closed = false;
|
|
615
|
+
constructor(child, cwd, fingerprint, label) {
|
|
616
|
+
this.fingerprint = fingerprint;
|
|
617
|
+
this.label = label;
|
|
618
|
+
this.proc = Bun.spawn(["bun", childPath(child), cwd, "--worker"], {
|
|
619
|
+
stdin: "pipe",
|
|
620
|
+
stdout: "pipe",
|
|
621
|
+
stderr: "pipe",
|
|
622
|
+
});
|
|
623
|
+
void this.readStdout();
|
|
624
|
+
void this.readStderr();
|
|
625
|
+
void this.proc.exited.then((code) => {
|
|
626
|
+
this.closed = true;
|
|
627
|
+
const err = new Error(`warm ${this.label} worker exited (${code})${this.stderrBuffer ? `:\n${this.stderrBuffer}` : ""}`);
|
|
628
|
+
for (const pending of this.pending.values()) {
|
|
629
|
+
pending.cleanup();
|
|
630
|
+
pending.reject(err);
|
|
631
|
+
}
|
|
632
|
+
this.pending.clear();
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
stop() {
|
|
636
|
+
if (!this.closed)
|
|
637
|
+
this.proc.kill();
|
|
638
|
+
}
|
|
639
|
+
async request(input, signal) {
|
|
640
|
+
if (this.closed)
|
|
641
|
+
throw new Error(`warm ${this.label} worker is closed`);
|
|
642
|
+
if (signal?.aborted)
|
|
643
|
+
return `${this.label} cancelled before it started.`;
|
|
644
|
+
const id = ++this.nextId;
|
|
645
|
+
return new Promise((resolve, reject) => {
|
|
646
|
+
const abort = () => {
|
|
647
|
+
// Per-request cancel: drop just THIS id and resolve its cancellation. The worker is shared
|
|
648
|
+
// across concurrent requests (`pending` is id-keyed for exactly this reason), so killing the
|
|
649
|
+
// process here would reject every OTHER in-flight request via the `exited` handler and force a
|
|
650
|
+
// cold rebuild. Leave it hot - `createWarmHandler` already replaces it on file change.
|
|
651
|
+
this.pending.delete(id);
|
|
652
|
+
clearTimeout(timer);
|
|
653
|
+
const reason = typeof signal?.reason === "string" ? `: ${signal.reason}` : "";
|
|
654
|
+
resolve(`${this.label} cancelled${reason}.`);
|
|
655
|
+
};
|
|
656
|
+
// Same backstop as the cold path: a worker wedged mid-request would otherwise leave this
|
|
657
|
+
// promise unsettled forever. Drop the id and replace the worker - unlike a per-request cancel,
|
|
658
|
+
// a timeout means the worker itself is suspect, so the next call should start from a fresh one.
|
|
659
|
+
const timer = setTimeout(() => {
|
|
660
|
+
if (!this.pending.delete(id))
|
|
661
|
+
return;
|
|
662
|
+
signal?.removeEventListener("abort", abort);
|
|
663
|
+
this.stop();
|
|
664
|
+
resolve(timeoutMessage(this.label, CHILD_TIMEOUT_MS));
|
|
665
|
+
}, CHILD_TIMEOUT_MS);
|
|
666
|
+
const cleanup = () => {
|
|
667
|
+
clearTimeout(timer);
|
|
668
|
+
signal?.removeEventListener("abort", abort);
|
|
669
|
+
};
|
|
670
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
671
|
+
this.pending.set(id, { resolve, reject, cleanup });
|
|
672
|
+
try {
|
|
673
|
+
this.proc.stdin.write(`${JSON.stringify({ id, input })}\n`);
|
|
674
|
+
}
|
|
675
|
+
catch (err) {
|
|
676
|
+
this.pending.delete(id);
|
|
677
|
+
cleanup();
|
|
678
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
679
|
+
}
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
async readStdout() {
|
|
683
|
+
const decoder = new TextDecoder();
|
|
684
|
+
const reader = this.proc.stdout.getReader();
|
|
685
|
+
for (;;) {
|
|
686
|
+
const { done, value } = await reader.read();
|
|
687
|
+
if (done)
|
|
688
|
+
break;
|
|
689
|
+
if (value !== undefined && value.byteLength > CHILD_OUTPUT_MAX_BYTES) {
|
|
690
|
+
this.stderrBuffer = boundedAppend(this.stderrBuffer, `warm ${this.label} worker stdout exceeded ${CHILD_OUTPUT_MAX_BYTES} bytes\n`);
|
|
691
|
+
this.stop();
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
this.stdoutBuffer += decoder.decode(value, { stream: true });
|
|
695
|
+
if (this.stdoutBuffer.length > CHILD_OUTPUT_MAX_BYTES) {
|
|
696
|
+
this.stderrBuffer = boundedAppend(this.stderrBuffer, `warm ${this.label} worker stdout exceeded ${CHILD_OUTPUT_MAX_BYTES} bytes\n`);
|
|
697
|
+
this.stop();
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
let nl = this.stdoutBuffer.indexOf("\n");
|
|
701
|
+
while (nl !== -1) {
|
|
702
|
+
const line = this.stdoutBuffer.slice(0, nl).trim();
|
|
703
|
+
this.stdoutBuffer = this.stdoutBuffer.slice(nl + 1);
|
|
704
|
+
nl = this.stdoutBuffer.indexOf("\n");
|
|
705
|
+
if (line !== "")
|
|
706
|
+
this.handleLine(line);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
async readStderr() {
|
|
711
|
+
const decoder = new TextDecoder();
|
|
712
|
+
const reader = this.proc.stderr.getReader();
|
|
713
|
+
for (;;) {
|
|
714
|
+
const { done, value } = await reader.read();
|
|
715
|
+
if (done)
|
|
716
|
+
break;
|
|
717
|
+
this.stderrBuffer = boundedAppend(this.stderrBuffer, decoder.decode(value, { stream: true }));
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
handleLine(line) {
|
|
721
|
+
let message;
|
|
722
|
+
try {
|
|
723
|
+
message = JSON.parse(line);
|
|
724
|
+
}
|
|
725
|
+
catch {
|
|
726
|
+
this.stderrBuffer = boundedAppend(this.stderrBuffer, `invalid warm ${this.label} worker line: ${line}\n`);
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (typeof message.id !== "number")
|
|
730
|
+
return;
|
|
731
|
+
const pending = this.pending.get(message.id);
|
|
732
|
+
if (pending === undefined)
|
|
733
|
+
return;
|
|
734
|
+
this.pending.delete(message.id);
|
|
735
|
+
pending.cleanup();
|
|
736
|
+
pending.resolve(JSON.stringify(message.output, null, 2));
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
/** A warm handler that reuses a hot {@link WarmWorker} across calls and falls back to a one-shot fresh
|
|
740
|
+
* subprocess on any worker failure. Shared by `nifra_run` (`child: "mcp-run"`, `label: "run"`) and
|
|
741
|
+
* `nifra_render` (`child: "mcp-render"`, `label: "render"`) - the only differences are the engine and the
|
|
742
|
+
* message label, so there's a single source for the reuse + auto-restart-on-file-change logic. */
|
|
743
|
+
export function createWarmHandler(child, cwd, label) {
|
|
744
|
+
let worker;
|
|
745
|
+
return async (input, signal) => {
|
|
746
|
+
const fingerprint = await warmRunFingerprint(cwd);
|
|
747
|
+
if (worker === undefined || worker.fingerprint !== fingerprint) {
|
|
748
|
+
worker?.stop();
|
|
749
|
+
worker = new WarmWorker(child, cwd, fingerprint, label);
|
|
750
|
+
}
|
|
751
|
+
try {
|
|
752
|
+
return await worker.request(input, signal);
|
|
753
|
+
}
|
|
754
|
+
catch {
|
|
755
|
+
worker.stop();
|
|
756
|
+
worker = undefined;
|
|
757
|
+
if (signal?.aborted) {
|
|
758
|
+
const reason = typeof signal.reason === "string" ? `: ${signal.reason}` : "";
|
|
759
|
+
return `${label} cancelled${reason}.`;
|
|
760
|
+
}
|
|
761
|
+
return spawnChild(child, cwd, input, label, signal);
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
/** The `nifra_run` handler: run requests through the project's CURRENT backend, return structured results. */
|
|
766
|
+
export async function runHandler(cwd, args, context, warmRun) {
|
|
767
|
+
const requests = Array.isArray(args.requests) ? args.requests : [];
|
|
768
|
+
if (requests.length === 0) {
|
|
769
|
+
return 'No requests provided. Pass { "requests": [{ "path": "/..." }] }.';
|
|
770
|
+
}
|
|
771
|
+
const input = { requests, entry: args.entry };
|
|
772
|
+
if (args.warm === true) {
|
|
773
|
+
context.reportProgress(0.2, 1);
|
|
774
|
+
return warmRun(input, context.signal);
|
|
775
|
+
}
|
|
776
|
+
return spawnChild("mcp-run", cwd, input, "run", context.signal);
|
|
777
|
+
}
|
|
778
|
+
/** The `nifra_render` handler: SSR page routes through the project's CURRENT web app, return the HTML.
|
|
779
|
+
* By default a fresh subprocess loads the current code each call; `warm:true` reuses a hot worker (like
|
|
780
|
+
* `nifra_run`) that auto-restarts when a source file changes. */
|
|
781
|
+
export async function renderHandler(cwd, args, context, warmRender) {
|
|
782
|
+
const requests = Array.isArray(args.requests) ? args.requests : [];
|
|
783
|
+
if (requests.length === 0) {
|
|
784
|
+
return 'No requests provided. Pass { "requests": [{ "path": "/..." }] }.';
|
|
785
|
+
}
|
|
786
|
+
const input = { requests };
|
|
787
|
+
if (args.warm === true) {
|
|
788
|
+
context.reportProgress(0.2, 1);
|
|
789
|
+
return warmRender(input, context.signal);
|
|
790
|
+
}
|
|
791
|
+
return spawnChild("mcp-render", cwd, input, "render", context.signal);
|
|
792
|
+
}
|
|
793
|
+
/** The `nifra_ws` handler: verify WebSocket routes through a fresh app subprocess. */
|
|
794
|
+
export async function wsHandler(cwd, args, context) {
|
|
795
|
+
return spawnChild("mcp-ws", cwd, args, "websocket", context.signal);
|
|
796
|
+
}
|
|
797
|
+
const APP_FINGERPRINT_FILES = ["nifra.config.ts", "framework.ts", "backend.ts"];
|
|
798
|
+
function cacheToken(input) {
|
|
799
|
+
let hash = 2166136261;
|
|
800
|
+
for (let i = 0; i < input.length; i++) {
|
|
801
|
+
hash ^= input.charCodeAt(i);
|
|
802
|
+
hash = Math.imul(hash, 16777619);
|
|
803
|
+
}
|
|
804
|
+
return `mcp=${(hash >>> 0).toString(36)}`;
|
|
805
|
+
}
|
|
806
|
+
async function fileFingerprint(path) {
|
|
807
|
+
try {
|
|
808
|
+
const s = await stat(path);
|
|
809
|
+
return `${s.mtimeMs}:${s.size}`;
|
|
810
|
+
}
|
|
811
|
+
catch (err) {
|
|
812
|
+
if (err && typeof err === "object" && err.code === "ENOENT") {
|
|
813
|
+
return "missing";
|
|
814
|
+
}
|
|
815
|
+
throw err;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
async function appFingerprint(cwd) {
|
|
819
|
+
return (await Promise.all(APP_FINGERPRINT_FILES.map(async (file) => `${file}:${await fileFingerprint(resolve(cwd, file))}`))).join("|");
|
|
820
|
+
}
|
|
821
|
+
/** Cache LoadedApp inside one MCP server process, invalidating when config/backend mtimes change. */
|
|
822
|
+
export function createCachedAppLoader(cwd, options = {}) {
|
|
823
|
+
const loadAppCached = options.loadApp ??
|
|
824
|
+
(async (root, outDirName, loadOptions) => {
|
|
825
|
+
const mod = await import("./load.js");
|
|
826
|
+
return mod.loadApp(root, outDirName, loadOptions);
|
|
827
|
+
});
|
|
828
|
+
const fingerprint = options.fingerprint ?? appFingerprint;
|
|
829
|
+
let cached;
|
|
830
|
+
return async (outDirName = "dist") => {
|
|
831
|
+
const nextFingerprint = await fingerprint(cwd);
|
|
832
|
+
if (cached !== undefined &&
|
|
833
|
+
cached.outDirName === outDirName &&
|
|
834
|
+
cached.fingerprint === nextFingerprint) {
|
|
835
|
+
return cached.app;
|
|
836
|
+
}
|
|
837
|
+
const app = await loadAppCached(cwd, outDirName, {
|
|
838
|
+
importQuery: cacheToken(nextFingerprint),
|
|
839
|
+
});
|
|
840
|
+
cached = { outDirName, fingerprint: nextFingerprint, app };
|
|
841
|
+
return app;
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
//# sourceMappingURL=mcp-exec.js.map
|