@copilotkit/aimock 1.44.0 → 1.45.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +31 -0
- package/README.md +6 -0
- package/dist/agui-types.d.ts.map +1 -1
- package/dist/aimock-cli.cjs +31 -5
- package/dist/aimock-cli.cjs.map +1 -1
- package/dist/aimock-cli.d.cts.map +1 -1
- package/dist/aimock-cli.d.ts.map +1 -1
- package/dist/aimock-cli.js +31 -5
- package/dist/aimock-cli.js.map +1 -1
- package/dist/bedrock-converse.cjs +312 -39
- package/dist/bedrock-converse.cjs.map +1 -1
- package/dist/bedrock-converse.d.cts.map +1 -1
- package/dist/bedrock-converse.d.ts.map +1 -1
- package/dist/bedrock-converse.js +313 -40
- package/dist/bedrock-converse.js.map +1 -1
- package/dist/bedrock.cjs +195 -42
- package/dist/bedrock.cjs.map +1 -1
- package/dist/bedrock.d.cts.map +1 -1
- package/dist/bedrock.d.ts.map +1 -1
- package/dist/bedrock.js +196 -43
- package/dist/bedrock.js.map +1 -1
- package/dist/chaos.cjs +1 -0
- package/dist/chaos.js +1 -1
- package/dist/cli.cjs +152 -5
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +155 -8
- package/dist/cli.js.map +1 -1
- package/dist/cohere.cjs +132 -71
- package/dist/cohere.cjs.map +1 -1
- package/dist/cohere.d.cts.map +1 -1
- package/dist/cohere.d.ts.map +1 -1
- package/dist/cohere.js +133 -72
- package/dist/cohere.js.map +1 -1
- package/dist/config-loader.cjs +62 -4
- package/dist/config-loader.cjs.map +1 -1
- package/dist/config-loader.d.cts +37 -4
- package/dist/config-loader.d.cts.map +1 -1
- package/dist/config-loader.d.ts +37 -4
- package/dist/config-loader.d.ts.map +1 -1
- package/dist/config-loader.js +62 -4
- package/dist/config-loader.js.map +1 -1
- package/dist/fakes-plugin.cjs +131 -0
- package/dist/fakes-plugin.cjs.map +1 -0
- package/dist/fakes-plugin.d.cts +23 -0
- package/dist/fakes-plugin.d.cts.map +1 -0
- package/dist/fakes-plugin.d.ts +23 -0
- package/dist/fakes-plugin.d.ts.map +1 -0
- package/dist/fakes-plugin.js +127 -0
- package/dist/fakes-plugin.js.map +1 -0
- package/dist/fixture-loader-services.cjs +1 -1
- package/dist/fixture-loader-services.cjs.map +1 -1
- package/dist/fixture-loader-services.js +1 -1
- package/dist/fixture-loader-services.js.map +1 -1
- package/dist/fixture-loader.cjs +389 -27
- package/dist/fixture-loader.cjs.map +1 -1
- package/dist/fixture-loader.d.cts +47 -3
- package/dist/fixture-loader.d.cts.map +1 -1
- package/dist/fixture-loader.d.ts +47 -3
- package/dist/fixture-loader.d.ts.map +1 -1
- package/dist/fixture-loader.js +384 -29
- package/dist/fixture-loader.js.map +1 -1
- package/dist/gemini-interactions.cjs +250 -52
- package/dist/gemini-interactions.cjs.map +1 -1
- package/dist/gemini-interactions.d.cts.map +1 -1
- package/dist/gemini-interactions.d.ts.map +1 -1
- package/dist/gemini-interactions.js +251 -53
- package/dist/gemini-interactions.js.map +1 -1
- package/dist/gemini.cjs +226 -37
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.d.cts.map +1 -1
- package/dist/gemini.d.ts.map +1 -1
- package/dist/gemini.js +227 -38
- package/dist/gemini.js.map +1 -1
- package/dist/helpers.cjs +881 -7
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts +85 -4
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.ts +85 -4
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +839 -8
- package/dist/helpers.js.map +1 -1
- package/dist/index.cjs +9 -0
- package/dist/index.d.cts +7 -5
- package/dist/index.d.ts +7 -5
- package/dist/index.js +4 -3
- package/dist/jest.cjs +31 -7
- package/dist/jest.cjs.map +1 -1
- package/dist/jest.d.cts +43 -3
- package/dist/jest.d.cts.map +1 -1
- package/dist/jest.d.ts +43 -3
- package/dist/jest.d.ts.map +1 -1
- package/dist/jest.js +33 -9
- package/dist/jest.js.map +1 -1
- package/dist/journal.cjs +135 -13
- package/dist/journal.cjs.map +1 -1
- package/dist/journal.d.cts +38 -4
- package/dist/journal.d.cts.map +1 -1
- package/dist/journal.d.ts +38 -4
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +135 -13
- package/dist/journal.js.map +1 -1
- package/dist/live-sanitize.cjs +4 -32
- package/dist/live-sanitize.cjs.map +1 -1
- package/dist/live-sanitize.js +4 -32
- package/dist/live-sanitize.js.map +1 -1
- package/dist/llmock.cjs +123 -30
- package/dist/llmock.cjs.map +1 -1
- package/dist/llmock.d.cts +16 -1
- package/dist/llmock.d.cts.map +1 -1
- package/dist/llmock.d.ts +16 -1
- package/dist/llmock.d.ts.map +1 -1
- package/dist/llmock.js +125 -32
- package/dist/llmock.js.map +1 -1
- package/dist/mcp-fakes-mount.cjs +1 -0
- package/dist/mcp-fakes-mount.cjs.map +1 -1
- package/dist/mcp-fakes-mount.js +1 -0
- package/dist/mcp-fakes-mount.js.map +1 -1
- package/dist/mcp-fakes-report.cjs +111 -0
- package/dist/mcp-fakes-report.cjs.map +1 -0
- package/dist/mcp-fakes-report.d.cts +40 -0
- package/dist/mcp-fakes-report.d.cts.map +1 -0
- package/dist/mcp-fakes-report.d.ts +40 -0
- package/dist/mcp-fakes-report.d.ts.map +1 -0
- package/dist/mcp-fakes-report.js +107 -0
- package/dist/mcp-fakes-report.js.map +1 -0
- package/dist/mcp-fakes.cjs +331 -8
- package/dist/mcp-fakes.cjs.map +1 -1
- package/dist/mcp-fakes.d.cts +406 -3
- package/dist/mcp-fakes.d.cts.map +1 -1
- package/dist/mcp-fakes.d.ts +406 -3
- package/dist/mcp-fakes.d.ts.map +1 -1
- package/dist/mcp-fakes.js +331 -8
- package/dist/mcp-fakes.js.map +1 -1
- package/dist/mcp-handler.cjs +209 -16
- package/dist/mcp-handler.cjs.map +1 -1
- package/dist/mcp-handler.d.cts +49 -0
- package/dist/mcp-handler.d.cts.map +1 -0
- package/dist/mcp-handler.d.ts +49 -0
- package/dist/mcp-handler.d.ts.map +1 -0
- package/dist/mcp-handler.js +207 -17
- package/dist/mcp-handler.js.map +1 -1
- package/dist/mcp-mock.cjs +112 -1
- package/dist/mcp-mock.cjs.map +1 -1
- package/dist/mcp-mock.d.cts +33 -2
- package/dist/mcp-mock.d.cts.map +1 -1
- package/dist/mcp-mock.d.ts +33 -2
- package/dist/mcp-mock.d.ts.map +1 -1
- package/dist/mcp-mock.js +112 -1
- package/dist/mcp-mock.js.map +1 -1
- package/dist/mcp-recorder.cjs +1224 -0
- package/dist/mcp-recorder.cjs.map +1 -0
- package/dist/mcp-recorder.d.cts +108 -0
- package/dist/mcp-recorder.d.cts.map +1 -0
- package/dist/mcp-recorder.d.ts +108 -0
- package/dist/mcp-recorder.d.ts.map +1 -0
- package/dist/mcp-recorder.js +1215 -0
- package/dist/mcp-recorder.js.map +1 -0
- package/dist/messages.cjs +362 -56
- package/dist/messages.cjs.map +1 -1
- package/dist/messages.d.cts.map +1 -1
- package/dist/messages.d.ts.map +1 -1
- package/dist/messages.js +363 -58
- package/dist/messages.js.map +1 -1
- package/dist/misbehavior.cjs +1523 -0
- package/dist/misbehavior.cjs.map +1 -0
- package/dist/misbehavior.d.cts +43 -0
- package/dist/misbehavior.d.cts.map +1 -0
- package/dist/misbehavior.d.ts +43 -0
- package/dist/misbehavior.d.ts.map +1 -0
- package/dist/misbehavior.js +1511 -0
- package/dist/misbehavior.js.map +1 -0
- package/dist/ollama.cjs +310 -112
- package/dist/ollama.cjs.map +1 -1
- package/dist/ollama.d.cts.map +1 -1
- package/dist/ollama.d.ts.map +1 -1
- package/dist/ollama.js +311 -113
- package/dist/ollama.js.map +1 -1
- package/dist/record-sanitize.cjs +231 -0
- package/dist/record-sanitize.cjs.map +1 -0
- package/dist/record-sanitize.js +224 -0
- package/dist/record-sanitize.js.map +1 -0
- package/dist/recorder.cjs +106 -5
- package/dist/recorder.cjs.map +1 -1
- package/dist/recorder.d.cts +2 -1
- package/dist/recorder.d.cts.map +1 -1
- package/dist/recorder.d.ts +2 -1
- package/dist/recorder.d.ts.map +1 -1
- package/dist/recorder.js +107 -7
- package/dist/recorder.js.map +1 -1
- package/dist/responses.cjs +667 -171
- package/dist/responses.cjs.map +1 -1
- package/dist/responses.d.cts +5 -13
- package/dist/responses.d.cts.map +1 -1
- package/dist/responses.d.ts +5 -13
- package/dist/responses.d.ts.map +1 -1
- package/dist/responses.js +665 -174
- package/dist/responses.js.map +1 -1
- package/dist/router.cjs +24 -2
- package/dist/router.cjs.map +1 -1
- package/dist/router.d.cts.map +1 -1
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +25 -4
- package/dist/router.js.map +1 -1
- package/dist/server.cjs +572 -76
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +574 -78
- package/dist/server.js.map +1 -1
- package/dist/stream-collapse.cjs +236 -34
- package/dist/stream-collapse.cjs.map +1 -1
- package/dist/stream-collapse.d.cts +39 -4
- package/dist/stream-collapse.d.cts.map +1 -1
- package/dist/stream-collapse.d.ts +39 -4
- package/dist/stream-collapse.d.ts.map +1 -1
- package/dist/stream-collapse.js +235 -35
- package/dist/stream-collapse.js.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +315 -4
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +315 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/validate-cli.cjs +36 -4
- package/dist/validate-cli.cjs.map +1 -1
- package/dist/validate-cli.js +37 -5
- package/dist/validate-cli.js.map +1 -1
- package/dist/vector-types.d.ts.map +1 -1
- package/dist/version.cjs +45 -0
- package/dist/version.cjs.map +1 -0
- package/dist/version.js +44 -0
- package/dist/version.js.map +1 -0
- package/dist/vitest.cjs +66 -10
- package/dist/vitest.cjs.map +1 -1
- package/dist/vitest.d.cts +35 -4
- package/dist/vitest.d.cts.map +1 -1
- package/dist/vitest.d.ts +35 -4
- package/dist/vitest.d.ts.map +1 -1
- package/dist/vitest.js +67 -11
- package/dist/vitest.js.map +1 -1
- package/dist/watcher.cjs +6 -2
- package/dist/watcher.cjs.map +1 -1
- package/dist/watcher.js +6 -2
- package/dist/watcher.js.map +1 -1
- package/dist/ws-gemini-live.cjs +210 -101
- package/dist/ws-gemini-live.cjs.map +1 -1
- package/dist/ws-gemini-live.d.cts +9 -3
- package/dist/ws-gemini-live.d.cts.map +1 -1
- package/dist/ws-gemini-live.d.ts +9 -3
- package/dist/ws-gemini-live.d.ts.map +1 -1
- package/dist/ws-gemini-live.js +211 -102
- package/dist/ws-gemini-live.js.map +1 -1
- package/dist/ws-realtime.cjs +175 -62
- package/dist/ws-realtime.cjs.map +1 -1
- package/dist/ws-realtime.d.cts +8 -3
- package/dist/ws-realtime.d.cts.map +1 -1
- package/dist/ws-realtime.d.ts +8 -3
- package/dist/ws-realtime.d.ts.map +1 -1
- package/dist/ws-realtime.js +176 -63
- package/dist/ws-realtime.js.map +1 -1
- package/dist/ws-responses.cjs +109 -16
- package/dist/ws-responses.cjs.map +1 -1
- package/dist/ws-responses.d.cts +8 -12
- package/dist/ws-responses.d.cts.map +1 -1
- package/dist/ws-responses.d.ts +8 -12
- package/dist/ws-responses.d.ts.map +1 -1
- package/dist/ws-responses.js +111 -18
- package/dist/ws-responses.js.map +1 -1
- package/package.json +10 -2
- package/skills/write-fixtures/SKILL.md +179 -21
package/dist/cli.cjs
CHANGED
|
@@ -8,10 +8,13 @@ const require_provider_auth = require('./provider-auth.cjs');
|
|
|
8
8
|
const require_logger = require('./logger.cjs');
|
|
9
9
|
const require_agui_mock = require('./agui-mock.cjs');
|
|
10
10
|
const require_mcp_fakes = require('./mcp-fakes.cjs');
|
|
11
|
+
const require_mcp_recorder = require('./mcp-recorder.cjs');
|
|
12
|
+
const require_mcp_mock = require('./mcp-mock.cjs');
|
|
11
13
|
const require_server = require('./server.cjs');
|
|
12
14
|
const require_fixture_loader_services = require('./fixture-loader-services.cjs');
|
|
13
15
|
const require_watcher = require('./watcher.cjs');
|
|
14
16
|
const require_fixtures_remote = require('./fixtures-remote.cjs');
|
|
17
|
+
let node_crypto = require("node:crypto");
|
|
15
18
|
let node_fs = require("node:fs");
|
|
16
19
|
let node_path = require("node:path");
|
|
17
20
|
let node_util = require("node:util");
|
|
@@ -31,11 +34,16 @@ Options:
|
|
|
31
34
|
-w, --watch Watch fixture path for changes and reload
|
|
32
35
|
--log-level <level> Log verbosity: silent, warn, info, debug (default: info)
|
|
33
36
|
--validate-on-load Validate fixture schemas at startup
|
|
37
|
+
--misbehavior Enable model misbehavior: fixture misbehavior keys and the
|
|
38
|
+
X-AIMock-Misbehavior header (ignored without this flag)
|
|
34
39
|
--metrics Enable Prometheus metrics at GET /metrics
|
|
35
40
|
--record Record mode: proxy unmatched requests and save fixtures
|
|
36
41
|
--record-full-model-version Record exact model version without date stripping (default: false)
|
|
37
42
|
--proxy-only Proxy mode: forward unmatched requests without saving
|
|
38
43
|
--strict Strict mode: fail on unmatched requests (overridable per-request via X-AIMock-Strict header)
|
|
44
|
+
--strict-tool-arguments Reject fixture tool calls with invalid JSON arguments instead of serving {} (default: false)
|
|
45
|
+
--responses-tools <mode> OpenAI Responses tool handling: legacy (default) or extended (namespaced and
|
|
46
|
+
custom tools visible to matching, custom tool rounds counted, namespaces emitted and recorded)
|
|
39
47
|
--journal-max <n> Max request entries retained in memory (default: 1000, 0 = unbounded)
|
|
40
48
|
--fixture-counts-max <n> Max unique testIds retained in fixture match-count map (default: 500, 0 = unbounded)
|
|
41
49
|
--provider-openai <url> Upstream URL for OpenAI (used with --record)
|
|
@@ -55,6 +63,8 @@ Options:
|
|
|
55
63
|
--agui-record Enable AG-UI recording (proxy unmatched AG-UI requests)
|
|
56
64
|
--agui-upstream <url> Upstream AG-UI agent URL (used with --agui-record)
|
|
57
65
|
--agui-proxy-only AG-UI proxy mode: forward without saving
|
|
66
|
+
--mcp-record <mount>=<url> Record an upstream MCP server into mcpFakes (repeatable)
|
|
67
|
+
--mcp-proxy-only <mount>=<url> Proxy an upstream MCP server without saving
|
|
58
68
|
--replay-speed <n> Replay speed multiplier (default: 1.0, 2.0 = 2x faster)
|
|
59
69
|
--chaos-drop <rate> Probability (0-1) of dropping requests with 500
|
|
60
70
|
--chaos-malformed <rate> Probability (0-1) of returning malformed JSON
|
|
@@ -104,6 +114,10 @@ const { values } = (0, node_util.parseArgs)({
|
|
|
104
114
|
type: "boolean",
|
|
105
115
|
default: false
|
|
106
116
|
},
|
|
117
|
+
misbehavior: {
|
|
118
|
+
type: "boolean",
|
|
119
|
+
default: false
|
|
120
|
+
},
|
|
107
121
|
metrics: {
|
|
108
122
|
type: "boolean",
|
|
109
123
|
default: false
|
|
@@ -124,6 +138,11 @@ const { values } = (0, node_util.parseArgs)({
|
|
|
124
138
|
type: "boolean",
|
|
125
139
|
default: false
|
|
126
140
|
},
|
|
141
|
+
"strict-tool-arguments": {
|
|
142
|
+
type: "boolean",
|
|
143
|
+
default: false
|
|
144
|
+
},
|
|
145
|
+
"responses-tools": { type: "string" },
|
|
127
146
|
"provider-openai": { type: "string" },
|
|
128
147
|
"provider-anthropic": { type: "string" },
|
|
129
148
|
"provider-gemini": { type: "string" },
|
|
@@ -147,6 +166,14 @@ const { values } = (0, node_util.parseArgs)({
|
|
|
147
166
|
type: "boolean",
|
|
148
167
|
default: false
|
|
149
168
|
},
|
|
169
|
+
"mcp-record": {
|
|
170
|
+
type: "string",
|
|
171
|
+
multiple: true
|
|
172
|
+
},
|
|
173
|
+
"mcp-proxy-only": {
|
|
174
|
+
type: "string",
|
|
175
|
+
multiple: true
|
|
176
|
+
},
|
|
150
177
|
"replay-speed": {
|
|
151
178
|
type: "string",
|
|
152
179
|
default: "1.0"
|
|
@@ -210,6 +237,12 @@ if (Number.isNaN(replaySpeed) || replaySpeed <= 0) {
|
|
|
210
237
|
console.error("--replay-speed must be a positive number");
|
|
211
238
|
process.exit(1);
|
|
212
239
|
}
|
|
240
|
+
const responsesToolsFlag = values["responses-tools"];
|
|
241
|
+
if (responsesToolsFlag !== void 0 && responsesToolsFlag !== "legacy" && responsesToolsFlag !== "extended") {
|
|
242
|
+
console.error(`Invalid --responses-tools: ${responsesToolsFlag} (expected "legacy" or "extended")`);
|
|
243
|
+
process.exit(1);
|
|
244
|
+
}
|
|
245
|
+
const responsesTools = responsesToolsFlag;
|
|
213
246
|
const journalMax = Number(values["journal-max"]);
|
|
214
247
|
if (Number.isNaN(journalMax) || !Number.isInteger(journalMax) || journalMax < 0) {
|
|
215
248
|
console.error(`Invalid journal-max: ${values["journal-max"]} (must be a non-negative integer; 0 = unbounded)`);
|
|
@@ -378,6 +411,59 @@ if (values["agui-record"] || values["agui-proxy-only"]) {
|
|
|
378
411
|
handler: agui
|
|
379
412
|
};
|
|
380
413
|
}
|
|
414
|
+
const mcpRecordMounts = [];
|
|
415
|
+
{
|
|
416
|
+
const recordValues = values["mcp-record"] ?? [];
|
|
417
|
+
const proxyValues = values["mcp-proxy-only"] ?? [];
|
|
418
|
+
if (recordValues.length > 0) {
|
|
419
|
+
if (!(values.fixtures && values.fixtures.length > 0)) {
|
|
420
|
+
console.error("Error: --mcp-record requires --fixtures <local path> for the recording destination");
|
|
421
|
+
process.exit(1);
|
|
422
|
+
}
|
|
423
|
+
if (/^https?:\/\//i.test(values.fixtures[0])) {
|
|
424
|
+
console.error(`Error: --mcp-record requires a local --fixtures path for the recording destination; got URL ${values.fixtures[0]}`);
|
|
425
|
+
process.exit(1);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
const flags = [...recordValues.map((value) => ({
|
|
429
|
+
flag: "--mcp-record",
|
|
430
|
+
value,
|
|
431
|
+
proxyOnly: false
|
|
432
|
+
})), ...proxyValues.map((value) => ({
|
|
433
|
+
flag: "--mcp-proxy-only",
|
|
434
|
+
value,
|
|
435
|
+
proxyOnly: true
|
|
436
|
+
}))];
|
|
437
|
+
if (flags.length > 0) {
|
|
438
|
+
let env;
|
|
439
|
+
try {
|
|
440
|
+
env = require_mcp_recorder.mcpRecordEnv(process.env);
|
|
441
|
+
} catch (err) {
|
|
442
|
+
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
|
|
443
|
+
process.exit(1);
|
|
444
|
+
}
|
|
445
|
+
for (const { flag, value, proxyOnly } of flags) try {
|
|
446
|
+
const { mount, upstream } = require_mcp_recorder.parseMcpRecordFlag(value, flag);
|
|
447
|
+
if (aguiMount && mount === aguiMount.path) throw new Error(`${flag} mount ${mount} is held by a mount that is not an MCP mock`);
|
|
448
|
+
if (mcpRecordMounts.some((m) => m.path === mount)) throw new Error(`${flag} mount ${mount} is given more than once`);
|
|
449
|
+
const mcp = new require_mcp_mock.MCPMock().enableRecording({
|
|
450
|
+
upstream,
|
|
451
|
+
fixturePath: proxyOnly ? void 0 : (0, node_path.resolve)(values.fixtures[0], "recorded"),
|
|
452
|
+
proxyOnly,
|
|
453
|
+
secretValues: env.secretValues,
|
|
454
|
+
upstreamAuth: env.upstreamAuth,
|
|
455
|
+
strict: values.strict
|
|
456
|
+
});
|
|
457
|
+
mcpRecordMounts.push({
|
|
458
|
+
path: mount,
|
|
459
|
+
handler: mcp
|
|
460
|
+
});
|
|
461
|
+
} catch (err) {
|
|
462
|
+
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
|
|
463
|
+
process.exit(1);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
381
467
|
async function resolveAllFixtureSources() {
|
|
382
468
|
const resolved = [];
|
|
383
469
|
for (const value of fixtureValues) {
|
|
@@ -412,7 +498,9 @@ async function resolveAllFixtureSources() {
|
|
|
412
498
|
return resolved;
|
|
413
499
|
}
|
|
414
500
|
function loadSource(source) {
|
|
415
|
-
|
|
501
|
+
const loaded = source.isDir ? require_fixture_loader_services.loadFixturesFromDirWithServices(source.path, logger) : require_fixture_loader_services.loadFixtureFileWithServices(source.path, logger, void 0, source.source);
|
|
502
|
+
if (values.misbehavior) loaded.fixtures.forEach(require_fixture_loader.enableHeldFixtureMisbehavior);
|
|
503
|
+
return loaded;
|
|
416
504
|
}
|
|
417
505
|
/** Each source's `mcpFakes` blocks, in load order, for the --watch comparison. */
|
|
418
506
|
function fakesBySource(blocks) {
|
|
@@ -460,6 +548,58 @@ var WatchLogger = class extends require_logger.Logger {
|
|
|
460
548
|
super.error(...args);
|
|
461
549
|
}
|
|
462
550
|
};
|
|
551
|
+
/**
|
|
552
|
+
* MR13: --watch with record mounts. (a) An event for a recorder temp file, or
|
|
553
|
+
* for a file whose bytes are exactly what a recorder last wrote there, does
|
|
554
|
+
* not reload; everything else (a delete, a directory, a user edit) reloads as
|
|
555
|
+
* on main. (b) Each recorder write moves the --watch baseline of that file,
|
|
556
|
+
* so the next reload does not reject the recording as a changed `mcpFakes`.
|
|
557
|
+
* Without record mounts (or for a file source), --watch is exactly as on main.
|
|
558
|
+
*/
|
|
559
|
+
function recorderWatch(primary, moveBaseline) {
|
|
560
|
+
const events = mcpRecordMounts.map((m) => m.handler.recorderEvents()).filter((ev) => ev !== null);
|
|
561
|
+
if (events.length === 0 || !primary.isDir) return {};
|
|
562
|
+
for (const ev of events) ev.onWrite((file, written) => {
|
|
563
|
+
const source = (0, node_path.relative)(primary.path, file).split(node_path.sep).join("/");
|
|
564
|
+
const blocks = Array.isArray(written) ? written.map((raw, blockIndex) => ({
|
|
565
|
+
source,
|
|
566
|
+
blockIndex,
|
|
567
|
+
raw
|
|
568
|
+
})) : [{
|
|
569
|
+
source,
|
|
570
|
+
blockIndex: null,
|
|
571
|
+
raw: written
|
|
572
|
+
}];
|
|
573
|
+
moveBaseline((boot) => {
|
|
574
|
+
const others = boot.filter((b) => b.source !== source);
|
|
575
|
+
const at = boot.findIndex((b) => b.source === source);
|
|
576
|
+
const pos = at === -1 ? others.length : at;
|
|
577
|
+
return [
|
|
578
|
+
...others.slice(0, pos),
|
|
579
|
+
...blocks,
|
|
580
|
+
...others.slice(pos)
|
|
581
|
+
];
|
|
582
|
+
});
|
|
583
|
+
});
|
|
584
|
+
return { ignore: (absPath) => {
|
|
585
|
+
if (/\.tmp\.[0-9a-f-]+$/i.test(absPath)) return true;
|
|
586
|
+
let st;
|
|
587
|
+
try {
|
|
588
|
+
st = (0, node_fs.statSync)(absPath);
|
|
589
|
+
} catch {
|
|
590
|
+
return false;
|
|
591
|
+
}
|
|
592
|
+
if (st.isDirectory()) return false;
|
|
593
|
+
let data;
|
|
594
|
+
try {
|
|
595
|
+
data = (0, node_fs.readFileSync)(absPath);
|
|
596
|
+
} catch {
|
|
597
|
+
return false;
|
|
598
|
+
}
|
|
599
|
+
const hash = (0, node_crypto.createHash)("sha256").update(data).digest("hex");
|
|
600
|
+
return events.some((ev) => ev.lastWrittenHash(absPath) === hash);
|
|
601
|
+
} };
|
|
602
|
+
}
|
|
463
603
|
async function main() {
|
|
464
604
|
const sources = await resolveAllFixtureSources();
|
|
465
605
|
const fixtures = [];
|
|
@@ -482,6 +622,7 @@ async function main() {
|
|
|
482
622
|
const sourceLabel = sources.map((s) => s.source).join(", ") || "<none>";
|
|
483
623
|
logger.info(`Loaded ${fixtures.length} fixture(s) from ${sourceLabel}`);
|
|
484
624
|
if (validateOnLoad) {
|
|
625
|
+
if (responsesTools === "extended") fixtures.forEach(require_fixture_loader.markFixtureResponsesToolsExtended);
|
|
485
626
|
const results = require_fixture_loader.validateFixtures(fixtures);
|
|
486
627
|
const errors = results.filter((r) => r.severity === "error");
|
|
487
628
|
const warnings = results.filter((r) => r.severity === "warning");
|
|
@@ -492,7 +633,8 @@ async function main() {
|
|
|
492
633
|
process.exit(1);
|
|
493
634
|
}
|
|
494
635
|
}
|
|
495
|
-
const
|
|
636
|
+
const allMounts = [...aguiMount ? [aguiMount] : [], ...mcpRecordMounts];
|
|
637
|
+
const mounts = allMounts.length > 0 ? allMounts : void 0;
|
|
496
638
|
const instance = await require_server.createServer(fixtures, {
|
|
497
639
|
port,
|
|
498
640
|
host,
|
|
@@ -504,6 +646,9 @@ async function main() {
|
|
|
504
646
|
metrics: values.metrics,
|
|
505
647
|
record,
|
|
506
648
|
strict: values.strict,
|
|
649
|
+
strictToolArguments: values["strict-tool-arguments"],
|
|
650
|
+
enableMisbehavior: values.misbehavior,
|
|
651
|
+
...responsesTools !== void 0 ? { responsesTools } : {},
|
|
507
652
|
journalMaxEntries: journalMax,
|
|
508
653
|
fixtureCountsMaxTestIds: fixtureCountsMax,
|
|
509
654
|
auth: require_api_key_auth.resolveInboundAuth(require_api_key_auth.selectInboundAuthSource(void 0)).publicConfig
|
|
@@ -537,7 +682,7 @@ async function main() {
|
|
|
537
682
|
try {
|
|
538
683
|
loaded = loadSource(primary);
|
|
539
684
|
} catch (err) {
|
|
540
|
-
if (err instanceof require_fixture_loader.FixtureLoadError) return reject(err);
|
|
685
|
+
if (err instanceof require_fixture_loader.FixtureLoadError || err instanceof require_fixture_loader.MisbehaviorConfigError) return reject(err);
|
|
541
686
|
throw err;
|
|
542
687
|
}
|
|
543
688
|
const changed = changedFakesSource(primaryFakes, loaded.mcpFakes, new Set(loaded.unreadable));
|
|
@@ -546,19 +691,21 @@ async function main() {
|
|
|
546
691
|
file: changed,
|
|
547
692
|
detail: require_message_text.msg`mcpFakes changed on --watch reload; MCP fakes are not reloaded, so the whole reload is rejected and the previous fixtures stay loaded. Restart aimock to load the new fakes`
|
|
548
693
|
}));
|
|
694
|
+
if (responsesTools === "extended") loaded.fixtures.forEach(require_fixture_loader.markFixtureResponsesToolsExtended);
|
|
549
695
|
return loaded.fixtures;
|
|
550
696
|
};
|
|
551
697
|
watcher = require_watcher.watchFixtures(primary.path, fixtures, loadFn, {
|
|
552
698
|
logger: new WatchLogger(logLevel),
|
|
553
699
|
validate: validateOnLoad,
|
|
554
|
-
validateFn: require_fixture_loader.validateFixtures
|
|
700
|
+
validateFn: require_fixture_loader.validateFixtures,
|
|
701
|
+
...recorderWatch(primary, (moved) => primaryFakes = moved(primaryFakes))
|
|
555
702
|
});
|
|
556
703
|
logger.info(`Watching ${primary.path} for changes`);
|
|
557
704
|
}
|
|
558
705
|
}
|
|
559
706
|
}
|
|
560
707
|
main().catch((err) => {
|
|
561
|
-
if (err instanceof require_fixture_loader.FixtureLoadError) printLoadError(err);
|
|
708
|
+
if (err instanceof require_fixture_loader.FixtureLoadError || err instanceof require_fixture_loader.MisbehaviorConfigError) printLoadError(err);
|
|
562
709
|
else console.error(err);
|
|
563
710
|
process.exit(1);
|
|
564
711
|
});
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.cjs","names":["CHAOS_FIELDS","Logger","parseChaosField","readProviderKeysFromEnv","AGUIMock","resolveFixturesValue","loadFixturesFromDirWithServices","loadFixtureFileWithServices","McpFakesAddError","build","validateFixtures","createServer","resolveInboundAuth","selectInboundAuthSource","FixtureLoadError","watchFixtures"],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { isDeepStrictEqual, parseArgs } from \"node:util\";\nimport { statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { createServer } from \"./server.js\";\nimport { FixtureLoadError, validateFixtures } from \"./fixture-loader.js\";\nimport {\n loadFixtureFileWithServices,\n loadFixturesFromDirWithServices,\n type FixturesWithServices,\n} from \"./fixture-loader-services.js\";\nimport { McpFakesAddError } from \"./mcp-fakes.js\";\nimport { build, msg } from \"./message-text.js\";\nimport { Logger, type LogLevel } from \"./logger.js\";\nimport { watchFixtures } from \"./watcher.js\";\nimport { AGUIMock } from \"./agui-mock.js\";\nimport { parseChaosField, CHAOS_FIELDS, type ChaosField } from \"./chaos.js\";\nimport { resolveFixturesValue } from \"./fixtures-remote.js\";\nimport { readProviderKeysFromEnv } from \"./provider-auth.js\";\nimport { resolveInboundAuth, selectInboundAuthSource } from \"./api-key-auth.js\";\nimport type { Fixture, ChaosConfig, RecordConfig, McpFakeSource } from \"./types.js\";\n\nconst HELP = `\nUsage: aimock [options]\n\nOptions:\n -p, --port <number> Port to listen on (default: 4010)\n -h, --host <string> Host to bind to (default: 127.0.0.1)\n -f, --fixtures <value> Fixture source (repeatable). Accepts:\n - filesystem path to a directory or .json file (default: ./fixtures)\n - https:// or http:// URL to a .json fixture file\n -l, --latency <ms> Latency in ms between SSE chunks (default: 0)\n -c, --chunk-size <chars> Chunk size in characters (default: 20)\n -w, --watch Watch fixture path for changes and reload\n --log-level <level> Log verbosity: silent, warn, info, debug (default: info)\n --validate-on-load Validate fixture schemas at startup\n --metrics Enable Prometheus metrics at GET /metrics\n --record Record mode: proxy unmatched requests and save fixtures\n --record-full-model-version Record exact model version without date stripping (default: false)\n --proxy-only Proxy mode: forward unmatched requests without saving\n --strict Strict mode: fail on unmatched requests (overridable per-request via X-AIMock-Strict header)\n --journal-max <n> Max request entries retained in memory (default: 1000, 0 = unbounded)\n --fixture-counts-max <n> Max unique testIds retained in fixture match-count map (default: 500, 0 = unbounded)\n --provider-openai <url> Upstream URL for OpenAI (used with --record)\n --provider-anthropic <url> Upstream URL for Anthropic\n --provider-gemini <url> Upstream URL for Gemini\n --provider-vertexai <url> Upstream URL for Vertex AI\n --provider-bedrock <url> Upstream URL for Bedrock\n --provider-azure <url> Upstream URL for Azure OpenAI\n --provider-ollama <url> Upstream URL for Ollama\n --provider-cohere <url> Upstream URL for Cohere\n --provider-openrouter <url> Upstream URL for OpenRouter (video record proxy)\n --provider-byteplus <url> Upstream ORIGIN for BytePlus Ark (e.g. https://ark.ap-southeast.bytepluses.com — origin only, no /api/v3)\n --upstream-timeout-ms <ms> Idle timeout (ms) on upstream socket before response (default: 30000)\n --body-timeout-ms <ms> Idle timeout (ms) on upstream response body between chunks (default: 30000)\n --max-proxy-buffer-bytes <n> Cap (bytes) on in-memory proxy-path buffer; full body still relayed (default: 67108864)\n --max-proxy-buffer-frames <n> Cap (frames) on in-memory proxy-path per-frame state; full body still relayed (default: 5000000)\n --agui-record Enable AG-UI recording (proxy unmatched AG-UI requests)\n --agui-upstream <url> Upstream AG-UI agent URL (used with --agui-record)\n --agui-proxy-only AG-UI proxy mode: forward without saving\n --replay-speed <n> Replay speed multiplier (default: 1.0, 2.0 = 2x faster)\n --chaos-drop <rate> Probability (0-1) of dropping requests with 500\n --chaos-malformed <rate> Probability (0-1) of returning malformed JSON\n --chaos-disconnect <rate> Probability (0-1) of destroying connection\n --chaos-ratelimit <rate> Probability (0-1) of 429 with Retry-After\n --chaos-latency <ms> Delay (0-${CHAOS_FIELDS.latencyMs.max}ms) injected before handling\n AIMOCK_API_KEYS Comma-separated inbound test API keys (environment only)\n --help Show this help message\n`.trim();\n\nconst { values } = parseArgs({\n options: {\n port: { type: \"string\", short: \"p\", default: \"4010\" },\n host: { type: \"string\", short: \"h\", default: \"127.0.0.1\" },\n fixtures: { type: \"string\", short: \"f\", multiple: true },\n latency: { type: \"string\", short: \"l\", default: \"0\" },\n \"chunk-size\": { type: \"string\", short: \"c\", default: \"20\" },\n watch: { type: \"boolean\", short: \"w\", default: false },\n \"log-level\": { type: \"string\", default: \"info\" },\n \"validate-on-load\": { type: \"boolean\", default: false },\n metrics: { type: \"boolean\", default: false },\n record: { type: \"boolean\", default: false },\n \"record-full-model-version\": { type: \"boolean\", default: false },\n \"proxy-only\": { type: \"boolean\", default: false },\n strict: { type: \"boolean\", default: false },\n \"provider-openai\": { type: \"string\" },\n \"provider-anthropic\": { type: \"string\" },\n \"provider-gemini\": { type: \"string\" },\n \"provider-vertexai\": { type: \"string\" },\n \"provider-bedrock\": { type: \"string\" },\n \"provider-azure\": { type: \"string\" },\n \"provider-ollama\": { type: \"string\" },\n \"provider-cohere\": { type: \"string\" },\n \"provider-openrouter\": { type: \"string\" },\n \"provider-byteplus\": { type: \"string\" },\n \"upstream-timeout-ms\": { type: \"string\" },\n \"body-timeout-ms\": { type: \"string\" },\n \"max-proxy-buffer-bytes\": { type: \"string\" },\n \"max-proxy-buffer-frames\": { type: \"string\" },\n \"agui-record\": { type: \"boolean\", default: false },\n \"agui-upstream\": { type: \"string\" },\n \"agui-proxy-only\": { type: \"boolean\", default: false },\n \"replay-speed\": { type: \"string\", default: \"1.0\" },\n \"chaos-drop\": { type: \"string\" },\n \"chaos-malformed\": { type: \"string\" },\n \"chaos-disconnect\": { type: \"string\" },\n \"chaos-ratelimit\": { type: \"string\" },\n \"chaos-latency\": { type: \"string\" },\n \"journal-max\": { type: \"string\", default: \"1000\" },\n \"fixture-counts-max\": { type: \"string\", default: \"500\" },\n help: { type: \"boolean\", default: false },\n },\n strict: true,\n});\n\nif (values.help) {\n console.log(HELP);\n process.exit(0);\n}\n\nconst port = Number(values.port);\nconst host = values.host!;\nconst latency = Number(values.latency);\nconst chunkSize = Number(values[\"chunk-size\"]);\nconst fixtureValues: string[] =\n values.fixtures && values.fixtures.length > 0 ? values.fixtures : [\"./fixtures\"];\nconst watchMode = values.watch!;\nconst validateOnLoad = values[\"validate-on-load\"]!;\nconst logLevelStr = values[\"log-level\"]!;\n\nif (![\"silent\", \"warn\", \"info\", \"debug\"].includes(logLevelStr)) {\n console.error(`Invalid log-level: ${logLevelStr} (must be silent, warn, info, or debug)`);\n process.exit(1);\n}\nconst logLevel = logLevelStr as LogLevel;\n\nif (Number.isNaN(port) || port < 0 || port > 65535) {\n console.error(`Invalid port: ${values.port}`);\n process.exit(1);\n}\n\nif (Number.isNaN(latency) || latency < 0) {\n console.error(`Invalid latency: ${values.latency}`);\n process.exit(1);\n}\n\nif (Number.isNaN(chunkSize) || chunkSize < 1) {\n console.error(`Invalid chunk-size: ${values[\"chunk-size\"]}`);\n process.exit(1);\n}\n\nconst replaySpeed = Number(values[\"replay-speed\"]);\nif (Number.isNaN(replaySpeed) || replaySpeed <= 0) {\n console.error(\"--replay-speed must be a positive number\");\n process.exit(1);\n}\n\nconst journalMax = Number(values[\"journal-max\"]);\nif (Number.isNaN(journalMax) || !Number.isInteger(journalMax) || journalMax < 0) {\n console.error(\n `Invalid journal-max: ${values[\"journal-max\"]} (must be a non-negative integer; 0 = unbounded)`,\n );\n process.exit(1);\n}\n\nconst fixtureCountsMaxStr = values[\"fixture-counts-max\"];\nconst fixtureCountsMax = Number(fixtureCountsMaxStr);\nif (Number.isNaN(fixtureCountsMax) || !Number.isInteger(fixtureCountsMax) || fixtureCountsMax < 0) {\n console.error(\n `Invalid fixture-counts-max: ${fixtureCountsMaxStr} (must be a non-negative integer; 0 = unbounded)`,\n );\n process.exit(1);\n}\n\nconst upstreamTimeoutMsStr = values[\"upstream-timeout-ms\"];\nlet upstreamTimeoutMs: number | undefined;\nif (upstreamTimeoutMsStr !== undefined) {\n upstreamTimeoutMs = Number(upstreamTimeoutMsStr);\n if (!Number.isFinite(upstreamTimeoutMs) || upstreamTimeoutMs <= 0) {\n console.error(\n `Invalid upstream-timeout-ms: ${upstreamTimeoutMsStr} (must be a positive finite number)`,\n );\n process.exit(1);\n }\n}\n\nconst bodyTimeoutMsStr = values[\"body-timeout-ms\"];\nlet bodyTimeoutMs: number | undefined;\nif (bodyTimeoutMsStr !== undefined) {\n bodyTimeoutMs = Number(bodyTimeoutMsStr);\n if (!Number.isFinite(bodyTimeoutMs) || bodyTimeoutMs <= 0) {\n console.error(\n `Invalid body-timeout-ms: ${bodyTimeoutMsStr} (must be a positive finite number)`,\n );\n process.exit(1);\n }\n}\n\nconst maxProxyBufferBytesStr = values[\"max-proxy-buffer-bytes\"];\nlet maxProxyBufferBytes: number | undefined;\nif (maxProxyBufferBytesStr !== undefined) {\n maxProxyBufferBytes = Number(maxProxyBufferBytesStr);\n if (!Number.isFinite(maxProxyBufferBytes) || maxProxyBufferBytes <= 0) {\n console.error(\n `Invalid max-proxy-buffer-bytes: ${maxProxyBufferBytesStr} (must be a positive finite number)`,\n );\n process.exit(1);\n }\n}\n\nconst maxProxyBufferFramesStr = values[\"max-proxy-buffer-frames\"];\nlet maxProxyBufferFrames: number | undefined;\nif (maxProxyBufferFramesStr !== undefined) {\n maxProxyBufferFrames = Number(maxProxyBufferFramesStr);\n if (!Number.isFinite(maxProxyBufferFrames) || maxProxyBufferFrames <= 0) {\n console.error(\n `Invalid max-proxy-buffer-frames: ${maxProxyBufferFramesStr} (must be a positive finite number)`,\n );\n process.exit(1);\n }\n}\n\nconst logger = new Logger(logLevel);\n\n// Parse chaos config from CLI flags\nlet chaos: ChaosConfig | undefined;\n{\n const dropStr = values[\"chaos-drop\"];\n const malformedStr = values[\"chaos-malformed\"];\n const disconnectStr = values[\"chaos-disconnect\"];\n const ratelimitStr = values[\"chaos-ratelimit\"];\n const latencyStr = values[\"chaos-latency\"];\n\n if (\n dropStr !== undefined ||\n malformedStr !== undefined ||\n disconnectStr !== undefined ||\n ratelimitStr !== undefined ||\n latencyStr !== undefined\n ) {\n // Same parser, same TABLE, same reject-never-clamp policy as every other\n // chaos input (headers, fixture, server default, control API) — see\n // `ChaosConfig`. The bounds and the integer-vs-rate grammar are read out of\n // `CHAOS_FIELDS`, never re-typed here, so raising a cap in that one table\n // moves the flag with it instead of leaving `--chaos-latency` on the old\n // limit with no compile error.\n chaos = {};\n const flagFields: Array<{ flag: string; field: ChaosField; raw: string | undefined }> = [\n { flag: \"chaos-drop\", field: \"dropRate\", raw: dropStr },\n { flag: \"chaos-malformed\", field: \"malformedRate\", raw: malformedStr },\n { flag: \"chaos-disconnect\", field: \"disconnectRate\", raw: disconnectStr },\n { flag: \"chaos-ratelimit\", field: \"rateLimitRate\", raw: ratelimitStr },\n { flag: \"chaos-latency\", field: \"latencyMs\", raw: latencyStr },\n ];\n for (const { flag, field, raw } of flagFields) {\n if (raw === undefined) continue;\n const val = parseChaosField(field, raw);\n if (val === undefined) {\n console.error(`Invalid ${flag}: ${raw} (must be 0-${CHAOS_FIELDS[field].max})`);\n process.exit(1);\n }\n chaos[field] = val;\n }\n }\n}\n\n// Parse record/proxy config from CLI flags\nlet record: RecordConfig | undefined;\nif (values.record || values[\"proxy-only\"]) {\n const providers: RecordConfig[\"providers\"] = {};\n if (values[\"provider-openai\"]) providers.openai = values[\"provider-openai\"];\n if (values[\"provider-anthropic\"]) providers.anthropic = values[\"provider-anthropic\"];\n if (values[\"provider-gemini\"]) providers.gemini = values[\"provider-gemini\"];\n if (values[\"provider-vertexai\"]) providers.vertexai = values[\"provider-vertexai\"];\n if (values[\"provider-bedrock\"]) providers.bedrock = values[\"provider-bedrock\"];\n if (values[\"provider-azure\"]) providers.azure = values[\"provider-azure\"];\n if (values[\"provider-ollama\"]) providers.ollama = values[\"provider-ollama\"];\n if (values[\"provider-cohere\"]) providers.cohere = values[\"provider-cohere\"];\n if (values[\"provider-openrouter\"]) providers.openrouter = values[\"provider-openrouter\"];\n if (values[\"provider-byteplus\"]) providers.byteplus = values[\"provider-byteplus\"];\n\n if (Object.keys(providers).length === 0) {\n console.error(\n `Error: --${values[\"proxy-only\"] ? \"proxy-only\" : \"record\"} requires at least one --provider-* flag`,\n );\n process.exit(1);\n }\n\n // For --record, the first --fixtures value is the base path for the recording\n // destination and must be a local filesystem path — writing to a URL is not supported.\n // For --proxy-only, unmatched requests are forwarded without saving, so no writable\n // destination is required; URL-only --fixtures is valid in that mode.\n const recordBase = fixtureValues[0];\n const recordBaseIsUrl = /^https?:\\/\\//i.test(recordBase);\n if (values.record && recordBaseIsUrl) {\n console.error(\n `Error: --record requires a local --fixtures path for the recording destination; got URL ${recordBase}`,\n );\n process.exit(1);\n }\n record = {\n providers,\n // aimock's own upstream keys, sourced from AIMOCK_PROVIDER_*_KEY env vars\n // (not CLI flags — secrets must not appear in `ps`). Injected on a\n // fixture-miss passthrough when the caller sent no/dummy credential.\n providerKeys: readProviderKeysFromEnv(),\n // In proxy-only mode with only URL sources, fixturePath is never consumed\n // (recorder.ts skips disk writes when proxyOnly is set). Leave it undefined\n // rather than resolving a URL string as a filesystem path.\n fixturePath: recordBaseIsUrl ? undefined : resolve(recordBase, \"recorded\"),\n proxyOnly: values[\"proxy-only\"],\n recordFullModelVersion: values[\"record-full-model-version\"],\n upstreamTimeoutMs,\n bodyTimeoutMs,\n maxProxyBufferBytes,\n maxProxyBufferFrames,\n };\n} else {\n // These flags configure upstream proxying — without --record or\n // --proxy-only they would be parsed and then silently dropped. Routed\n // through the constructed logger so --log-level is respected.\n const droppedProviderFlags = (\n [\n \"provider-openai\",\n \"provider-anthropic\",\n \"provider-gemini\",\n \"provider-vertexai\",\n \"provider-bedrock\",\n \"provider-azure\",\n \"provider-ollama\",\n \"provider-cohere\",\n \"provider-openrouter\",\n \"provider-byteplus\",\n ] as const\n ).filter((flag) => values[flag] !== undefined);\n if (droppedProviderFlags.length > 0) {\n logger.warn(\n `--${droppedProviderFlags.join(\"/--\")} only apply to --record/--proxy-only upstream proxying — ignored without one of those flags.`,\n );\n }\n if (\n upstreamTimeoutMs !== undefined ||\n bodyTimeoutMs !== undefined ||\n maxProxyBufferBytes !== undefined ||\n maxProxyBufferFrames !== undefined\n ) {\n logger.warn(\n \"--upstream-timeout-ms/--body-timeout-ms/--max-proxy-buffer-bytes/--max-proxy-buffer-frames only apply to --record/--proxy-only upstream proxying — ignored without one of those flags.\",\n );\n }\n}\n\n// Parse AG-UI record/proxy config from CLI flags\nlet aguiMount: { path: string; handler: AGUIMock } | undefined;\nif (values[\"agui-record\"] || values[\"agui-proxy-only\"]) {\n if (!values[\"agui-upstream\"]) {\n console.error(\"Error: --agui-record/--agui-proxy-only requires --agui-upstream\");\n process.exit(1);\n }\n // --agui-record writes recorded AG-UI fixtures to disk, so a URL source is unsupported.\n // --agui-proxy-only forwards without saving, so URL-only --fixtures is valid.\n const aguiBase = fixtureValues[0];\n const aguiBaseIsUrl = /^https?:\\/\\//i.test(aguiBase);\n if (values[\"agui-record\"] && aguiBaseIsUrl) {\n console.error(\n `Error: --agui-record requires a local --fixtures path for the recording destination; got URL ${aguiBase}`,\n );\n process.exit(1);\n }\n const agui = new AGUIMock();\n agui.enableRecording({\n upstream: values[\"agui-upstream\"],\n // In proxy-only mode with a URL-only --fixtures, the AG-UI recorder never\n // writes to disk (see agui-recorder.ts). Leave fixturePath undefined rather\n // than resolving a URL as a filesystem path.\n fixturePath: aguiBaseIsUrl ? undefined : resolve(aguiBase, \"agui-recorded\"),\n proxyOnly: values[\"agui-proxy-only\"],\n });\n aguiMount = { path: \"/agui\", handler: agui };\n}\n\ninterface ResolvedFixtureSource {\n source: string;\n path: string;\n isDir: boolean;\n}\n\nasync function resolveAllFixtureSources(): Promise<ResolvedFixtureSource[]> {\n const resolved: ResolvedFixtureSource[] = [];\n for (const value of fixtureValues) {\n let local;\n try {\n local = await resolveFixturesValue(value, {\n validateOnLoad,\n logger,\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`Failed to resolve --fixtures value \"${value}\": ${msg}`);\n process.exit(1);\n }\n if (!local.path) {\n // Remote fetch failed without validate-on-load and no cache — already warned; skip.\n continue;\n }\n try {\n const stat = statSync(local.path);\n resolved.push({ source: local.source, path: local.path, isDir: stat.isDirectory() });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.error(`Fixtures path not found: ${local.path}`);\n } else {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`Failed to load fixtures from ${local.path}: ${msg}`);\n }\n process.exit(1);\n }\n }\n return resolved;\n}\n\n// F3: the loaders that carry `mcpFakes`. A file's entry-id source (I6) is the\n// --fixtures value as given: the path, or the URL of a remote file (whose\n// `path` is the on-disk cache).\nfunction loadSource(source: ResolvedFixtureSource): FixturesWithServices {\n return source.isDir\n ? loadFixturesFromDirWithServices(source.path, logger)\n : loadFixtureFileWithServices(source.path, logger, undefined, source.source);\n}\n\n/** Each source's `mcpFakes` blocks, in load order, for the --watch comparison. */\nfunction fakesBySource(blocks: McpFakeSource[]): Map<string, unknown[]> {\n const bySource = new Map<string, unknown[]>();\n for (const block of blocks) {\n const list = bySource.get(block.source) ?? [];\n list.push([block.blockIndex, block.raw]);\n bySource.set(block.source, list);\n }\n return bySource;\n}\n\n/**\n * R9/F11: fakes are not reloaded by --watch, so a reload whose `mcpFakes`\n * differ from the boot set is rejected. Returns the first changed source.\n * A source in `unreadable` could not be read or parsed: it is not compared,\n * because its blocks are unknown, not removed.\n */\nfunction changedFakesSource(\n boot: McpFakeSource[],\n reload: McpFakeSource[],\n unreadable: ReadonlySet<string>,\n): string | null {\n const before = fakesBySource(boot);\n const after = fakesBySource(reload);\n for (const source of new Set([...before.keys(), ...after.keys()])) {\n if (unreadable.has(source)) continue;\n if (!isDeepStrictEqual(before.get(source), after.get(source))) return source;\n }\n return null;\n}\n\n/**\n * L3: a load error on stderr, whatever the log level: every error of a\n * `McpFakesAddError`, one per line, then its L8 warnings.\n */\nfunction printLoadError(err: FixtureLoadError): void {\n const errors = err instanceof McpFakesAddError ? err.errors : [err];\n for (const e of errors) console.error(e.message);\n if (err instanceof McpFakesAddError) {\n for (const w of err.warnings) console.warn(w.message);\n }\n}\n\n/** A --watch reload that `loadFn` rejected and already printed (L3, L7). */\nclass ReloadRejected extends Error {}\n\n/**\n * The --watch logger: as `Logger`, except that the watcher's own report of a\n * {@link ReloadRejected} reload is dropped, so the error is printed once.\n */\nclass WatchLogger extends Logger {\n override error(...args: unknown[]): void {\n if (args.some((a) => a instanceof ReloadRejected)) return;\n super.error(...args);\n }\n}\n\nasync function main() {\n const sources = await resolveAllFixtureSources();\n\n const fixtures: Fixture[] = [];\n const mcpFakes: McpFakeSource[] = [];\n // The primary source's blocks: what a --watch reload of it is compared with.\n let primaryFakes: McpFakeSource[] = [];\n for (const src of sources) {\n const loaded = loadSource(src);\n fixtures.push(...loaded.fixtures);\n mcpFakes.push(...loaded.mcpFakes);\n if (src === sources[0]) primaryFakes = loaded.mcpFakes;\n }\n\n if (fixtures.length === 0 && mcpFakes.length > 0) {\n // F5/L9: fake blocks count as loaded; only LLM requests have nothing to match.\n console.warn(build(msg`Warning: No LLM fixtures loaded; LLM requests will return 404`));\n } else if (fixtures.length === 0) {\n if (validateOnLoad || values.strict) {\n console.error(\"Error: No fixtures loaded and validation/strict mode is enabled — aborting.\");\n process.exit(1);\n }\n console.warn(\"Warning: No fixtures loaded. The server will return 404 for all requests.\");\n }\n\n const sourceLabel = sources.map((s) => s.source).join(\", \") || \"<none>\";\n logger.info(`Loaded ${fixtures.length} fixture(s) from ${sourceLabel}`);\n\n // Validate fixtures if requested\n if (validateOnLoad) {\n const results = validateFixtures(fixtures);\n const errors = results.filter((r) => r.severity === \"error\");\n const warnings = results.filter((r) => r.severity === \"warning\");\n\n for (const w of warnings) {\n logger.warn(`Fixture ${w.fixtureIndex}: ${w.message}`);\n }\n // L8 (shadowed mcpFakes entries) is not printed here: the hand-off in\n // createServer prints it on every start.\n for (const e of errors) {\n logger.error(`Fixture ${e.fixtureIndex}: ${e.message}`);\n }\n\n if (errors.length > 0) {\n console.error(`Validation failed: ${errors.length} error(s), ${warnings.length} warning(s)`);\n process.exit(1);\n }\n }\n\n const mounts = aguiMount ? [aguiMount] : undefined;\n\n const instance = await createServer(\n fixtures,\n {\n port,\n host,\n latency,\n chunkSize,\n replaySpeed,\n logLevel,\n chaos,\n metrics: values.metrics,\n record,\n strict: values.strict,\n journalMaxEntries: journalMax,\n fixtureCountsMaxTestIds: fixtureCountsMax,\n auth: resolveInboundAuth(selectInboundAuthSource(undefined)).publicConfig,\n },\n mounts,\n { search: [], rerank: [], moderation: [], mcpFakes },\n );\n\n // Only the first local source is watched — remote URL sources are fetched once\n // at boot and are not monitored. Declared before the readiness announcement so\n // shutdown can close it whenever the signal arrives.\n let watcher: { close: () => void } | null = null;\n\n function shutdown() {\n logger.info(\"Shutting down...\");\n if (watcher) watcher.close();\n instance.server.close(() => {\n process.exit(0);\n });\n }\n\n // Register BEFORE announcing readiness. Writes to a pipe are synchronous on Linux\n // (and to a file on every POSIX platform), so a supervisor that reacts to the line\n // below can deliver SIGTERM while this process is still mid-statement. Announcing\n // first left a window in which SIGTERM hit Node's default disposition, which\n // re-raises: the process died with a null exit code instead of shutting down.\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n logger.info(`aimock server listening on ${instance.url}`);\n\n // Start file watcher if requested.\n if (watchMode) {\n const primary = sources[0];\n if (!primary) {\n logger.warn(\"--watch requested but no resolvable fixture sources; skipping watcher\");\n } else {\n // A rejected reload is printed here, whatever the log level, then\n // thrown as ReloadRejected: watchFixtures keeps the previous fixtures,\n // and its WatchLogger does not print the error a second time.\n const reject = (err: FixtureLoadError): never => {\n printLoadError(err);\n throw new ReloadRejected(build(msg`--watch reload rejected`));\n };\n const loadFn = (): Fixture[] => {\n let loaded: FixturesWithServices;\n try {\n loaded = loadSource(primary);\n } catch (err) {\n // L3: a bad block in the reloaded file.\n if (err instanceof FixtureLoadError) return reject(err);\n throw err;\n }\n const changed = changedFakesSource(\n primaryFakes,\n loaded.mcpFakes,\n new Set(loaded.unreadable),\n );\n if (changed !== null) {\n // L7.\n return reject(\n new FixtureLoadError({\n rule: \"mcp-fakes/watch-reload-changed\",\n file: changed,\n detail: msg`mcpFakes changed on --watch reload; MCP fakes are not reloaded, so the whole reload is rejected and the previous fixtures stay loaded. Restart aimock to load the new fakes`,\n }),\n );\n }\n return loaded.fixtures;\n };\n watcher = watchFixtures(primary.path, fixtures, loadFn, {\n logger: new WatchLogger(logLevel),\n validate: validateOnLoad,\n validateFn: validateFixtures,\n });\n logger.info(`Watching ${primary.path} for changes`);\n }\n }\n}\n\nmain().catch((err) => {\n if (err instanceof FixtureLoadError) {\n printLoadError(err);\n } else {\n console.error(err);\n }\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBA,MAAM,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sCA2CyBA,2BAAa,UAAU,IAAI;;;EAG/D,MAAM;AAER,MAAM,EAAE,oCAAqB;CAC3B,SAAS;EACP,MAAM;GAAE,MAAM;GAAU,OAAO;GAAK,SAAS;GAAQ;EACrD,MAAM;GAAE,MAAM;GAAU,OAAO;GAAK,SAAS;GAAa;EAC1D,UAAU;GAAE,MAAM;GAAU,OAAO;GAAK,UAAU;GAAM;EACxD,SAAS;GAAE,MAAM;GAAU,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U,QAAQ;AACxB,MAAI,CAAC,QACH,QAAO,KAAK,wEAAwE;OAC/E;GAIL,MAAM,UAAU,QAAiC;AAC/C,mBAAe,IAAI;AACnB,UAAM,IAAI,eAAeJ,2BAAM,wBAAG,0BAA0B,CAAC;;GAE/D,MAAM,eAA0B;IAC9B,IAAI;AACJ,QAAI;AACF,cAAS,WAAW,QAAQ;aACrB,KAAK;AAEZ,SAAI,eAAeK,wCAAkB,QAAO,OAAO,IAAI;AACvD,WAAM;;IAER,MAAM,UAAU,mBACd,cACA,OAAO,UACP,IAAI,IAAI,OAAO,WAAW,CAC3B;AACD,QAAI,YAAY,KAEd,QAAO,OACL,IAAIA,wCAAiB;KACnB,MAAM;KACN,MAAM;KACN,QAAQ,wBAAG;KACZ,CAAC,CACH;AAEH,WAAO,OAAO;;AAEhB,aAAUC,8BAAc,QAAQ,MAAM,UAAU,QAAQ;IACtD,QAAQ,IAAI,YAAY,SAAS;IACjC,UAAU;IACV,YAAYL;IACb,CAAC;AACF,UAAO,KAAK,YAAY,QAAQ,KAAK,cAAc;;;;AAKzD,MAAM,CAAC,OAAO,QAAQ;AACpB,KAAI,eAAeI,wCACjB,gBAAe,IAAI;KAEnB,SAAQ,MAAM,IAAI;AAEpB,SAAQ,KAAK,EAAE;EACf"}
|
|
1
|
+
{"version":3,"file":"cli.cjs","names":["CHAOS_FIELDS","Logger","parseChaosField","readProviderKeysFromEnv","AGUIMock","mcpRecordEnv","parseMcpRecordFlag","MCPMock","resolveFixturesValue","loadFixturesFromDirWithServices","loadFixtureFileWithServices","enableHeldFixtureMisbehavior","McpFakesAddError","sep","build","markFixtureResponsesToolsExtended","validateFixtures","createServer","resolveInboundAuth","selectInboundAuthSource","FixtureLoadError","MisbehaviorConfigError","watchFixtures"],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { isDeepStrictEqual, parseArgs } from \"node:util\";\nimport { createHash } from \"node:crypto\";\nimport { readFileSync, statSync, type Stats } from \"node:fs\";\nimport { relative, resolve, sep } from \"node:path\";\nimport { createServer } from \"./server.js\";\nimport type { ResponsesToolsMode } from \"./types.js\";\nimport {\n FixtureLoadError,\n MisbehaviorConfigError,\n enableHeldFixtureMisbehavior,\n markFixtureResponsesToolsExtended,\n validateFixtures,\n} from \"./fixture-loader.js\";\nimport {\n loadFixtureFileWithServices,\n loadFixturesFromDirWithServices,\n type FixturesWithServices,\n} from \"./fixture-loader-services.js\";\nimport { McpFakesAddError } from \"./mcp-fakes.js\";\nimport { build, msg } from \"./message-text.js\";\nimport { Logger, type LogLevel } from \"./logger.js\";\nimport { watchFixtures } from \"./watcher.js\";\nimport { AGUIMock } from \"./agui-mock.js\";\nimport { MCPMock } from \"./mcp-mock.js\";\nimport { mcpRecordEnv, parseMcpRecordFlag } from \"./mcp-recorder.js\";\nimport { parseChaosField, CHAOS_FIELDS, type ChaosField } from \"./chaos.js\";\nimport { resolveFixturesValue } from \"./fixtures-remote.js\";\nimport { readProviderKeysFromEnv } from \"./provider-auth.js\";\nimport { resolveInboundAuth, selectInboundAuthSource } from \"./api-key-auth.js\";\nimport type { Fixture, ChaosConfig, RecordConfig, McpFakeSource, Mountable } from \"./types.js\";\n\nconst HELP = `\nUsage: aimock [options]\n\nOptions:\n -p, --port <number> Port to listen on (default: 4010)\n -h, --host <string> Host to bind to (default: 127.0.0.1)\n -f, --fixtures <value> Fixture source (repeatable). Accepts:\n - filesystem path to a directory or .json file (default: ./fixtures)\n - https:// or http:// URL to a .json fixture file\n -l, --latency <ms> Latency in ms between SSE chunks (default: 0)\n -c, --chunk-size <chars> Chunk size in characters (default: 20)\n -w, --watch Watch fixture path for changes and reload\n --log-level <level> Log verbosity: silent, warn, info, debug (default: info)\n --validate-on-load Validate fixture schemas at startup\n --misbehavior Enable model misbehavior: fixture misbehavior keys and the\n X-AIMock-Misbehavior header (ignored without this flag)\n --metrics Enable Prometheus metrics at GET /metrics\n --record Record mode: proxy unmatched requests and save fixtures\n --record-full-model-version Record exact model version without date stripping (default: false)\n --proxy-only Proxy mode: forward unmatched requests without saving\n --strict Strict mode: fail on unmatched requests (overridable per-request via X-AIMock-Strict header)\n --strict-tool-arguments Reject fixture tool calls with invalid JSON arguments instead of serving {} (default: false)\n --responses-tools <mode> OpenAI Responses tool handling: legacy (default) or extended (namespaced and\n custom tools visible to matching, custom tool rounds counted, namespaces emitted and recorded)\n --journal-max <n> Max request entries retained in memory (default: 1000, 0 = unbounded)\n --fixture-counts-max <n> Max unique testIds retained in fixture match-count map (default: 500, 0 = unbounded)\n --provider-openai <url> Upstream URL for OpenAI (used with --record)\n --provider-anthropic <url> Upstream URL for Anthropic\n --provider-gemini <url> Upstream URL for Gemini\n --provider-vertexai <url> Upstream URL for Vertex AI\n --provider-bedrock <url> Upstream URL for Bedrock\n --provider-azure <url> Upstream URL for Azure OpenAI\n --provider-ollama <url> Upstream URL for Ollama\n --provider-cohere <url> Upstream URL for Cohere\n --provider-openrouter <url> Upstream URL for OpenRouter (video record proxy)\n --provider-byteplus <url> Upstream ORIGIN for BytePlus Ark (e.g. https://ark.ap-southeast.bytepluses.com — origin only, no /api/v3)\n --upstream-timeout-ms <ms> Idle timeout (ms) on upstream socket before response (default: 30000)\n --body-timeout-ms <ms> Idle timeout (ms) on upstream response body between chunks (default: 30000)\n --max-proxy-buffer-bytes <n> Cap (bytes) on in-memory proxy-path buffer; full body still relayed (default: 67108864)\n --max-proxy-buffer-frames <n> Cap (frames) on in-memory proxy-path per-frame state; full body still relayed (default: 5000000)\n --agui-record Enable AG-UI recording (proxy unmatched AG-UI requests)\n --agui-upstream <url> Upstream AG-UI agent URL (used with --agui-record)\n --agui-proxy-only AG-UI proxy mode: forward without saving\n --mcp-record <mount>=<url> Record an upstream MCP server into mcpFakes (repeatable)\n --mcp-proxy-only <mount>=<url> Proxy an upstream MCP server without saving\n --replay-speed <n> Replay speed multiplier (default: 1.0, 2.0 = 2x faster)\n --chaos-drop <rate> Probability (0-1) of dropping requests with 500\n --chaos-malformed <rate> Probability (0-1) of returning malformed JSON\n --chaos-disconnect <rate> Probability (0-1) of destroying connection\n --chaos-ratelimit <rate> Probability (0-1) of 429 with Retry-After\n --chaos-latency <ms> Delay (0-${CHAOS_FIELDS.latencyMs.max}ms) injected before handling\n AIMOCK_API_KEYS Comma-separated inbound test API keys (environment only)\n --help Show this help message\n`.trim();\n\nconst { values } = parseArgs({\n options: {\n port: { type: \"string\", short: \"p\", default: \"4010\" },\n host: { type: \"string\", short: \"h\", default: \"127.0.0.1\" },\n fixtures: { type: \"string\", short: \"f\", multiple: true },\n latency: { type: \"string\", short: \"l\", default: \"0\" },\n \"chunk-size\": { type: \"string\", short: \"c\", default: \"20\" },\n watch: { type: \"boolean\", short: \"w\", default: false },\n \"log-level\": { type: \"string\", default: \"info\" },\n \"validate-on-load\": { type: \"boolean\", default: false },\n misbehavior: { type: \"boolean\", default: false },\n metrics: { type: \"boolean\", default: false },\n record: { type: \"boolean\", default: false },\n \"record-full-model-version\": { type: \"boolean\", default: false },\n \"proxy-only\": { type: \"boolean\", default: false },\n strict: { type: \"boolean\", default: false },\n \"strict-tool-arguments\": { type: \"boolean\", default: false },\n \"responses-tools\": { type: \"string\" },\n \"provider-openai\": { type: \"string\" },\n \"provider-anthropic\": { type: \"string\" },\n \"provider-gemini\": { type: \"string\" },\n \"provider-vertexai\": { type: \"string\" },\n \"provider-bedrock\": { type: \"string\" },\n \"provider-azure\": { type: \"string\" },\n \"provider-ollama\": { type: \"string\" },\n \"provider-cohere\": { type: \"string\" },\n \"provider-openrouter\": { type: \"string\" },\n \"provider-byteplus\": { type: \"string\" },\n \"upstream-timeout-ms\": { type: \"string\" },\n \"body-timeout-ms\": { type: \"string\" },\n \"max-proxy-buffer-bytes\": { type: \"string\" },\n \"max-proxy-buffer-frames\": { type: \"string\" },\n \"agui-record\": { type: \"boolean\", default: false },\n \"agui-upstream\": { type: \"string\" },\n \"agui-proxy-only\": { type: \"boolean\", default: false },\n \"mcp-record\": { type: \"string\", multiple: true },\n \"mcp-proxy-only\": { type: \"string\", multiple: true },\n \"replay-speed\": { type: \"string\", default: \"1.0\" },\n \"chaos-drop\": { type: \"string\" },\n \"chaos-malformed\": { type: \"string\" },\n \"chaos-disconnect\": { type: \"string\" },\n \"chaos-ratelimit\": { type: \"string\" },\n \"chaos-latency\": { type: \"string\" },\n \"journal-max\": { type: \"string\", default: \"1000\" },\n \"fixture-counts-max\": { type: \"string\", default: \"500\" },\n help: { type: \"boolean\", default: false },\n },\n strict: true,\n});\n\nif (values.help) {\n console.log(HELP);\n process.exit(0);\n}\n\nconst port = Number(values.port);\nconst host = values.host!;\nconst latency = Number(values.latency);\nconst chunkSize = Number(values[\"chunk-size\"]);\nconst fixtureValues: string[] =\n values.fixtures && values.fixtures.length > 0 ? values.fixtures : [\"./fixtures\"];\nconst watchMode = values.watch!;\nconst validateOnLoad = values[\"validate-on-load\"]!;\nconst logLevelStr = values[\"log-level\"]!;\n\nif (![\"silent\", \"warn\", \"info\", \"debug\"].includes(logLevelStr)) {\n console.error(`Invalid log-level: ${logLevelStr} (must be silent, warn, info, or debug)`);\n process.exit(1);\n}\nconst logLevel = logLevelStr as LogLevel;\n\nif (Number.isNaN(port) || port < 0 || port > 65535) {\n console.error(`Invalid port: ${values.port}`);\n process.exit(1);\n}\n\nif (Number.isNaN(latency) || latency < 0) {\n console.error(`Invalid latency: ${values.latency}`);\n process.exit(1);\n}\n\nif (Number.isNaN(chunkSize) || chunkSize < 1) {\n console.error(`Invalid chunk-size: ${values[\"chunk-size\"]}`);\n process.exit(1);\n}\n\nconst replaySpeed = Number(values[\"replay-speed\"]);\nif (Number.isNaN(replaySpeed) || replaySpeed <= 0) {\n console.error(\"--replay-speed must be a positive number\");\n process.exit(1);\n}\n\nconst responsesToolsFlag = values[\"responses-tools\"];\nif (\n responsesToolsFlag !== undefined &&\n responsesToolsFlag !== \"legacy\" &&\n responsesToolsFlag !== \"extended\"\n) {\n console.error(\n `Invalid --responses-tools: ${responsesToolsFlag} (expected \"legacy\" or \"extended\")`,\n );\n process.exit(1);\n}\nconst responsesTools: ResponsesToolsMode | undefined = responsesToolsFlag;\n\nconst journalMax = Number(values[\"journal-max\"]);\nif (Number.isNaN(journalMax) || !Number.isInteger(journalMax) || journalMax < 0) {\n console.error(\n `Invalid journal-max: ${values[\"journal-max\"]} (must be a non-negative integer; 0 = unbounded)`,\n );\n process.exit(1);\n}\n\nconst fixtureCountsMaxStr = values[\"fixture-counts-max\"];\nconst fixtureCountsMax = Number(fixtureCountsMaxStr);\nif (Number.isNaN(fixtureCountsMax) || !Number.isInteger(fixtureCountsMax) || fixtureCountsMax < 0) {\n console.error(\n `Invalid fixture-counts-max: ${fixtureCountsMaxStr} (must be a non-negative integer; 0 = unbounded)`,\n );\n process.exit(1);\n}\n\nconst upstreamTimeoutMsStr = values[\"upstream-timeout-ms\"];\nlet upstreamTimeoutMs: number | undefined;\nif (upstreamTimeoutMsStr !== undefined) {\n upstreamTimeoutMs = Number(upstreamTimeoutMsStr);\n if (!Number.isFinite(upstreamTimeoutMs) || upstreamTimeoutMs <= 0) {\n console.error(\n `Invalid upstream-timeout-ms: ${upstreamTimeoutMsStr} (must be a positive finite number)`,\n );\n process.exit(1);\n }\n}\n\nconst bodyTimeoutMsStr = values[\"body-timeout-ms\"];\nlet bodyTimeoutMs: number | undefined;\nif (bodyTimeoutMsStr !== undefined) {\n bodyTimeoutMs = Number(bodyTimeoutMsStr);\n if (!Number.isFinite(bodyTimeoutMs) || bodyTimeoutMs <= 0) {\n console.error(\n `Invalid body-timeout-ms: ${bodyTimeoutMsStr} (must be a positive finite number)`,\n );\n process.exit(1);\n }\n}\n\nconst maxProxyBufferBytesStr = values[\"max-proxy-buffer-bytes\"];\nlet maxProxyBufferBytes: number | undefined;\nif (maxProxyBufferBytesStr !== undefined) {\n maxProxyBufferBytes = Number(maxProxyBufferBytesStr);\n if (!Number.isFinite(maxProxyBufferBytes) || maxProxyBufferBytes <= 0) {\n console.error(\n `Invalid max-proxy-buffer-bytes: ${maxProxyBufferBytesStr} (must be a positive finite number)`,\n );\n process.exit(1);\n }\n}\n\nconst maxProxyBufferFramesStr = values[\"max-proxy-buffer-frames\"];\nlet maxProxyBufferFrames: number | undefined;\nif (maxProxyBufferFramesStr !== undefined) {\n maxProxyBufferFrames = Number(maxProxyBufferFramesStr);\n if (!Number.isFinite(maxProxyBufferFrames) || maxProxyBufferFrames <= 0) {\n console.error(\n `Invalid max-proxy-buffer-frames: ${maxProxyBufferFramesStr} (must be a positive finite number)`,\n );\n process.exit(1);\n }\n}\n\nconst logger = new Logger(logLevel);\n\n// Parse chaos config from CLI flags\nlet chaos: ChaosConfig | undefined;\n{\n const dropStr = values[\"chaos-drop\"];\n const malformedStr = values[\"chaos-malformed\"];\n const disconnectStr = values[\"chaos-disconnect\"];\n const ratelimitStr = values[\"chaos-ratelimit\"];\n const latencyStr = values[\"chaos-latency\"];\n\n if (\n dropStr !== undefined ||\n malformedStr !== undefined ||\n disconnectStr !== undefined ||\n ratelimitStr !== undefined ||\n latencyStr !== undefined\n ) {\n // Same parser, same TABLE, same reject-never-clamp policy as every other\n // chaos input (headers, fixture, server default, control API) — see\n // `ChaosConfig`. The bounds and the integer-vs-rate grammar are read out of\n // `CHAOS_FIELDS`, never re-typed here, so raising a cap in that one table\n // moves the flag with it instead of leaving `--chaos-latency` on the old\n // limit with no compile error.\n chaos = {};\n const flagFields: Array<{ flag: string; field: ChaosField; raw: string | undefined }> = [\n { flag: \"chaos-drop\", field: \"dropRate\", raw: dropStr },\n { flag: \"chaos-malformed\", field: \"malformedRate\", raw: malformedStr },\n { flag: \"chaos-disconnect\", field: \"disconnectRate\", raw: disconnectStr },\n { flag: \"chaos-ratelimit\", field: \"rateLimitRate\", raw: ratelimitStr },\n { flag: \"chaos-latency\", field: \"latencyMs\", raw: latencyStr },\n ];\n for (const { flag, field, raw } of flagFields) {\n if (raw === undefined) continue;\n const val = parseChaosField(field, raw);\n if (val === undefined) {\n console.error(`Invalid ${flag}: ${raw} (must be 0-${CHAOS_FIELDS[field].max})`);\n process.exit(1);\n }\n chaos[field] = val;\n }\n }\n}\n\n// Parse record/proxy config from CLI flags\nlet record: RecordConfig | undefined;\nif (values.record || values[\"proxy-only\"]) {\n const providers: RecordConfig[\"providers\"] = {};\n if (values[\"provider-openai\"]) providers.openai = values[\"provider-openai\"];\n if (values[\"provider-anthropic\"]) providers.anthropic = values[\"provider-anthropic\"];\n if (values[\"provider-gemini\"]) providers.gemini = values[\"provider-gemini\"];\n if (values[\"provider-vertexai\"]) providers.vertexai = values[\"provider-vertexai\"];\n if (values[\"provider-bedrock\"]) providers.bedrock = values[\"provider-bedrock\"];\n if (values[\"provider-azure\"]) providers.azure = values[\"provider-azure\"];\n if (values[\"provider-ollama\"]) providers.ollama = values[\"provider-ollama\"];\n if (values[\"provider-cohere\"]) providers.cohere = values[\"provider-cohere\"];\n if (values[\"provider-openrouter\"]) providers.openrouter = values[\"provider-openrouter\"];\n if (values[\"provider-byteplus\"]) providers.byteplus = values[\"provider-byteplus\"];\n\n if (Object.keys(providers).length === 0) {\n console.error(\n `Error: --${values[\"proxy-only\"] ? \"proxy-only\" : \"record\"} requires at least one --provider-* flag`,\n );\n process.exit(1);\n }\n\n // For --record, the first --fixtures value is the base path for the recording\n // destination and must be a local filesystem path — writing to a URL is not supported.\n // For --proxy-only, unmatched requests are forwarded without saving, so no writable\n // destination is required; URL-only --fixtures is valid in that mode.\n const recordBase = fixtureValues[0];\n const recordBaseIsUrl = /^https?:\\/\\//i.test(recordBase);\n if (values.record && recordBaseIsUrl) {\n console.error(\n `Error: --record requires a local --fixtures path for the recording destination; got URL ${recordBase}`,\n );\n process.exit(1);\n }\n record = {\n providers,\n // aimock's own upstream keys, sourced from AIMOCK_PROVIDER_*_KEY env vars\n // (not CLI flags — secrets must not appear in `ps`). Injected on a\n // fixture-miss passthrough when the caller sent no/dummy credential.\n providerKeys: readProviderKeysFromEnv(),\n // In proxy-only mode with only URL sources, fixturePath is never consumed\n // (recorder.ts skips disk writes when proxyOnly is set). Leave it undefined\n // rather than resolving a URL string as a filesystem path.\n fixturePath: recordBaseIsUrl ? undefined : resolve(recordBase, \"recorded\"),\n proxyOnly: values[\"proxy-only\"],\n recordFullModelVersion: values[\"record-full-model-version\"],\n upstreamTimeoutMs,\n bodyTimeoutMs,\n maxProxyBufferBytes,\n maxProxyBufferFrames,\n };\n} else {\n // These flags configure upstream proxying — without --record or\n // --proxy-only they would be parsed and then silently dropped. Routed\n // through the constructed logger so --log-level is respected.\n const droppedProviderFlags = (\n [\n \"provider-openai\",\n \"provider-anthropic\",\n \"provider-gemini\",\n \"provider-vertexai\",\n \"provider-bedrock\",\n \"provider-azure\",\n \"provider-ollama\",\n \"provider-cohere\",\n \"provider-openrouter\",\n \"provider-byteplus\",\n ] as const\n ).filter((flag) => values[flag] !== undefined);\n if (droppedProviderFlags.length > 0) {\n logger.warn(\n `--${droppedProviderFlags.join(\"/--\")} only apply to --record/--proxy-only upstream proxying — ignored without one of those flags.`,\n );\n }\n if (\n upstreamTimeoutMs !== undefined ||\n bodyTimeoutMs !== undefined ||\n maxProxyBufferBytes !== undefined ||\n maxProxyBufferFrames !== undefined\n ) {\n logger.warn(\n \"--upstream-timeout-ms/--body-timeout-ms/--max-proxy-buffer-bytes/--max-proxy-buffer-frames only apply to --record/--proxy-only upstream proxying — ignored without one of those flags.\",\n );\n }\n}\n\n// Parse AG-UI record/proxy config from CLI flags\nlet aguiMount: { path: string; handler: AGUIMock } | undefined;\nif (values[\"agui-record\"] || values[\"agui-proxy-only\"]) {\n if (!values[\"agui-upstream\"]) {\n console.error(\"Error: --agui-record/--agui-proxy-only requires --agui-upstream\");\n process.exit(1);\n }\n // --agui-record writes recorded AG-UI fixtures to disk, so a URL source is unsupported.\n // --agui-proxy-only forwards without saving, so URL-only --fixtures is valid.\n const aguiBase = fixtureValues[0];\n const aguiBaseIsUrl = /^https?:\\/\\//i.test(aguiBase);\n if (values[\"agui-record\"] && aguiBaseIsUrl) {\n console.error(\n `Error: --agui-record requires a local --fixtures path for the recording destination; got URL ${aguiBase}`,\n );\n process.exit(1);\n }\n const agui = new AGUIMock();\n agui.enableRecording({\n upstream: values[\"agui-upstream\"],\n // In proxy-only mode with a URL-only --fixtures, the AG-UI recorder never\n // writes to disk (see agui-recorder.ts). Leave fixturePath undefined rather\n // than resolving a URL as a filesystem path.\n fixturePath: aguiBaseIsUrl ? undefined : resolve(aguiBase, \"agui-recorded\"),\n proxyOnly: values[\"agui-proxy-only\"],\n });\n aguiMount = { path: \"/agui\", handler: agui };\n}\n\n// Parse MCP record/proxy mounts (MR1, AM6): --mcp-record / --mcp-proxy-only <mount>=<url>\nconst mcpRecordMounts: { path: string; handler: MCPMock }[] = [];\n{\n const recordValues = values[\"mcp-record\"] ?? [];\n const proxyValues = values[\"mcp-proxy-only\"] ?? [];\n if (recordValues.length > 0) {\n // C11: check the flag itself; fixtureValues defaults to ./fixtures.\n if (!(values.fixtures && values.fixtures.length > 0)) {\n console.error(\n \"Error: --mcp-record requires --fixtures <local path> for the recording destination\",\n );\n process.exit(1);\n }\n if (/^https?:\\/\\//i.test(values.fixtures[0])) {\n console.error(\n `Error: --mcp-record requires a local --fixtures path for the recording destination; got URL ${values.fixtures[0]}`,\n );\n process.exit(1);\n }\n }\n const flags = [\n ...recordValues.map((value) => ({ flag: \"--mcp-record\", value, proxyOnly: false })),\n ...proxyValues.map((value) => ({ flag: \"--mcp-proxy-only\", value, proxyOnly: true })),\n ];\n if (flags.length > 0) {\n let env: ReturnType<typeof mcpRecordEnv>;\n try {\n env = mcpRecordEnv(process.env);\n } catch (err) {\n console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n for (const { flag, value, proxyOnly } of flags) {\n try {\n const { mount, upstream } = parseMcpRecordFlag(value, flag);\n if (aguiMount && mount === aguiMount.path) {\n throw new Error(`${flag} mount ${mount} is held by a mount that is not an MCP mock`);\n }\n if (mcpRecordMounts.some((m) => m.path === mount)) {\n throw new Error(`${flag} mount ${mount} is given more than once`);\n }\n const mcp = new MCPMock().enableRecording({\n upstream,\n fixturePath: proxyOnly ? undefined : resolve(values.fixtures![0], \"recorded\"),\n proxyOnly,\n secretValues: env.secretValues,\n upstreamAuth: env.upstreamAuth,\n strict: values.strict,\n });\n mcpRecordMounts.push({ path: mount, handler: mcp });\n } catch (err) {\n console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n }\n }\n}\n\ninterface ResolvedFixtureSource {\n source: string;\n path: string;\n isDir: boolean;\n}\n\nasync function resolveAllFixtureSources(): Promise<ResolvedFixtureSource[]> {\n const resolved: ResolvedFixtureSource[] = [];\n for (const value of fixtureValues) {\n let local;\n try {\n local = await resolveFixturesValue(value, {\n validateOnLoad,\n logger,\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`Failed to resolve --fixtures value \"${value}\": ${msg}`);\n process.exit(1);\n }\n if (!local.path) {\n // Remote fetch failed without validate-on-load and no cache — already warned; skip.\n continue;\n }\n try {\n const stat = statSync(local.path);\n resolved.push({ source: local.source, path: local.path, isDir: stat.isDirectory() });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.error(`Fixtures path not found: ${local.path}`);\n } else {\n const msg = err instanceof Error ? err.message : String(err);\n console.error(`Failed to load fixtures from ${local.path}: ${msg}`);\n }\n process.exit(1);\n }\n }\n return resolved;\n}\n\n// F3: the loaders that carry `mcpFakes`. A file's entry-id source (I6) is the\n// --fixtures value as given: the path, or the URL of a remote file (whose\n// `path` is the on-disk cache).\nfunction loadSource(source: ResolvedFixtureSource): FixturesWithServices {\n const loaded = source.isDir\n ? loadFixturesFromDirWithServices(source.path, logger)\n : loadFixtureFileWithServices(source.path, logger, undefined, source.source);\n // --misbehavior: a bad fixture `misbehavior` key fails the load; without it the key is ignored.\n if (values.misbehavior) loaded.fixtures.forEach(enableHeldFixtureMisbehavior);\n return loaded;\n}\n\n/** Each source's `mcpFakes` blocks, in load order, for the --watch comparison. */\nfunction fakesBySource(blocks: McpFakeSource[]): Map<string, unknown[]> {\n const bySource = new Map<string, unknown[]>();\n for (const block of blocks) {\n const list = bySource.get(block.source) ?? [];\n list.push([block.blockIndex, block.raw]);\n bySource.set(block.source, list);\n }\n return bySource;\n}\n\n/**\n * R9/F11: fakes are not reloaded by --watch, so a reload whose `mcpFakes`\n * differ from the boot set is rejected. Returns the first changed source.\n * A source in `unreadable` could not be read or parsed: it is not compared,\n * because its blocks are unknown, not removed.\n */\nfunction changedFakesSource(\n boot: McpFakeSource[],\n reload: McpFakeSource[],\n unreadable: ReadonlySet<string>,\n): string | null {\n const before = fakesBySource(boot);\n const after = fakesBySource(reload);\n for (const source of new Set([...before.keys(), ...after.keys()])) {\n if (unreadable.has(source)) continue;\n if (!isDeepStrictEqual(before.get(source), after.get(source))) return source;\n }\n return null;\n}\n\n/**\n * L3: a load error on stderr, whatever the log level: every error of a\n * `McpFakesAddError`, one per line, then its L8 warnings.\n */\nfunction printLoadError(err: FixtureLoadError | MisbehaviorConfigError): void {\n const errors = err instanceof McpFakesAddError ? err.errors : [err];\n for (const e of errors) console.error(e.message);\n if (err instanceof McpFakesAddError) {\n for (const w of err.warnings) console.warn(w.message);\n }\n}\n\n/** A --watch reload that `loadFn` rejected and already printed (L3, L7). */\nclass ReloadRejected extends Error {}\n\n/**\n * The --watch logger: as `Logger`, except that the watcher's own report of a\n * {@link ReloadRejected} reload is dropped, so the error is printed once.\n */\nclass WatchLogger extends Logger {\n override error(...args: unknown[]): void {\n if (args.some((a) => a instanceof ReloadRejected)) return;\n super.error(...args);\n }\n}\n\n/**\n * MR13: --watch with record mounts. (a) An event for a recorder temp file, or\n * for a file whose bytes are exactly what a recorder last wrote there, does\n * not reload; everything else (a delete, a directory, a user edit) reloads as\n * on main. (b) Each recorder write moves the --watch baseline of that file,\n * so the next reload does not reject the recording as a changed `mcpFakes`.\n * Without record mounts (or for a file source), --watch is exactly as on main.\n */\nfunction recorderWatch(\n primary: ResolvedFixtureSource,\n moveBaseline: (moved: (boot: McpFakeSource[]) => McpFakeSource[]) => void,\n): { ignore?: (absPath: string) => boolean } {\n const events = mcpRecordMounts.map((m) => m.handler.recorderEvents()).filter((ev) => ev !== null);\n if (events.length === 0 || !primary.isDir) return {};\n for (const ev of events) {\n ev.onWrite((file, written) => {\n const source = relative(primary.path, file).split(sep).join(\"/\");\n const blocks: McpFakeSource[] = Array.isArray(written)\n ? written.map((raw, blockIndex) => ({ source, blockIndex, raw }))\n : [{ source, blockIndex: null, raw: written }];\n moveBaseline((boot) => {\n // Replace this source's blocks in place; a new source goes last.\n const others = boot.filter((b) => b.source !== source);\n const at = boot.findIndex((b) => b.source === source);\n const pos = at === -1 ? others.length : at;\n return [...others.slice(0, pos), ...blocks, ...others.slice(pos)];\n });\n });\n }\n return {\n ignore: (absPath: string): boolean => {\n // Recorder temp files only (persistServiceFakes writes `<file>.tmp.<uuid>`, then renames it).\n if (/\\.tmp\\.[0-9a-f-]+$/i.test(absPath)) return true;\n let st: Stats;\n try {\n st = statSync(absPath);\n } catch {\n return false; // gone: a user deleted a fixture — this MUST reload (r2 N2)\n }\n if (st.isDirectory()) return false; // directory events behave as on main\n let data: Buffer;\n try {\n data = readFileSync(absPath);\n } catch {\n return false;\n }\n const hash = createHash(\"sha256\").update(data).digest(\"hex\");\n return events.some((ev) => ev.lastWrittenHash(absPath) === hash);\n },\n };\n}\n\nasync function main() {\n const sources = await resolveAllFixtureSources();\n\n const fixtures: Fixture[] = [];\n const mcpFakes: McpFakeSource[] = [];\n // The primary source's blocks: what a --watch reload of it is compared with.\n let primaryFakes: McpFakeSource[] = [];\n for (const src of sources) {\n const loaded = loadSource(src);\n fixtures.push(...loaded.fixtures);\n mcpFakes.push(...loaded.mcpFakes);\n if (src === sources[0]) primaryFakes = loaded.mcpFakes;\n }\n\n if (fixtures.length === 0 && mcpFakes.length > 0) {\n // F5/L9: fake blocks count as loaded; only LLM requests have nothing to match.\n console.warn(build(msg`Warning: No LLM fixtures loaded; LLM requests will return 404`));\n } else if (fixtures.length === 0) {\n if (validateOnLoad || values.strict) {\n console.error(\"Error: No fixtures loaded and validation/strict mode is enabled — aborting.\");\n process.exit(1);\n }\n console.warn(\"Warning: No fixtures loaded. The server will return 404 for all requests.\");\n }\n\n const sourceLabel = sources.map((s) => s.source).join(\", \") || \"<none>\";\n logger.info(`Loaded ${fixtures.length} fixture(s) from ${sourceLabel}`);\n\n // Validate fixtures if requested\n if (validateOnLoad) {\n if (responsesTools === \"extended\") fixtures.forEach(markFixtureResponsesToolsExtended);\n const results = validateFixtures(fixtures);\n const errors = results.filter((r) => r.severity === \"error\");\n const warnings = results.filter((r) => r.severity === \"warning\");\n\n for (const w of warnings) {\n logger.warn(`Fixture ${w.fixtureIndex}: ${w.message}`);\n }\n // L8 (shadowed mcpFakes entries) is not printed here: the hand-off in\n // createServer prints it on every start.\n for (const e of errors) {\n logger.error(`Fixture ${e.fixtureIndex}: ${e.message}`);\n }\n\n if (errors.length > 0) {\n console.error(`Validation failed: ${errors.length} error(s), ${warnings.length} warning(s)`);\n process.exit(1);\n }\n }\n\n const allMounts: { path: string; handler: Mountable }[] = [\n ...(aguiMount ? [aguiMount] : []),\n ...mcpRecordMounts,\n ];\n const mounts = allMounts.length > 0 ? allMounts : undefined;\n\n const instance = await createServer(\n fixtures,\n {\n port,\n host,\n latency,\n chunkSize,\n replaySpeed,\n logLevel,\n chaos,\n metrics: values.metrics,\n record,\n strict: values.strict,\n strictToolArguments: values[\"strict-tool-arguments\"],\n enableMisbehavior: values.misbehavior,\n ...(responsesTools !== undefined ? { responsesTools } : {}),\n journalMaxEntries: journalMax,\n fixtureCountsMaxTestIds: fixtureCountsMax,\n auth: resolveInboundAuth(selectInboundAuthSource(undefined)).publicConfig,\n },\n mounts,\n { search: [], rerank: [], moderation: [], mcpFakes },\n );\n\n // Only the first local source is watched — remote URL sources are fetched once\n // at boot and are not monitored. Declared before the readiness announcement so\n // shutdown can close it whenever the signal arrives.\n let watcher: { close: () => void } | null = null;\n\n function shutdown() {\n logger.info(\"Shutting down...\");\n if (watcher) watcher.close();\n instance.server.close(() => {\n process.exit(0);\n });\n }\n\n // Register BEFORE announcing readiness. Writes to a pipe are synchronous on Linux\n // (and to a file on every POSIX platform), so a supervisor that reacts to the line\n // below can deliver SIGTERM while this process is still mid-statement. Announcing\n // first left a window in which SIGTERM hit Node's default disposition, which\n // re-raises: the process died with a null exit code instead of shutting down.\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n logger.info(`aimock server listening on ${instance.url}`);\n\n // Start file watcher if requested.\n if (watchMode) {\n const primary = sources[0];\n if (!primary) {\n logger.warn(\"--watch requested but no resolvable fixture sources; skipping watcher\");\n } else {\n // A rejected reload is printed here, whatever the log level, then\n // thrown as ReloadRejected: watchFixtures keeps the previous fixtures,\n // and its WatchLogger does not print the error a second time.\n const reject = (err: FixtureLoadError | MisbehaviorConfigError): never => {\n printLoadError(err);\n throw new ReloadRejected(build(msg`--watch reload rejected`));\n };\n const loadFn = (): Fixture[] => {\n let loaded: FixturesWithServices;\n try {\n loaded = loadSource(primary);\n } catch (err) {\n // L3: a bad block in the reloaded file.\n if (err instanceof FixtureLoadError || err instanceof MisbehaviorConfigError) {\n return reject(err);\n }\n throw err;\n }\n const changed = changedFakesSource(\n primaryFakes,\n loaded.mcpFakes,\n new Set(loaded.unreadable),\n );\n if (changed !== null) {\n // L7.\n return reject(\n new FixtureLoadError({\n rule: \"mcp-fakes/watch-reload-changed\",\n file: changed,\n detail: msg`mcpFakes changed on --watch reload; MCP fakes are not reloaded, so the whole reload is rejected and the previous fixtures stay loaded. Restart aimock to load the new fakes`,\n }),\n );\n }\n if (responsesTools === \"extended\") {\n loaded.fixtures.forEach(markFixtureResponsesToolsExtended);\n }\n return loaded.fixtures;\n };\n watcher = watchFixtures(primary.path, fixtures, loadFn, {\n logger: new WatchLogger(logLevel),\n validate: validateOnLoad,\n validateFn: validateFixtures,\n ...recorderWatch(primary, (moved) => (primaryFakes = moved(primaryFakes))),\n });\n logger.info(`Watching ${primary.path} for changes`);\n }\n }\n}\n\nmain().catch((err) => {\n if (err instanceof FixtureLoadError || err instanceof MisbehaviorConfigError) {\n printLoadError(err);\n } else {\n console.error(err);\n }\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sCAkDyBA,2BAAa,UAAU,IAAI;;;EAG/D,MAAM;AAER,MAAM,EAAE,oCAAqB;CAC3B,SAAS;EACP,MAAM;GAAE,MAAM;GAAU,OAAO;GAAK,SAAS;GAAQ;EACrD,MAAM;GAAE,MAAM;GAAU,OAAO;GAAK,SAAS;GAAa;EAC1D,UAAU;GAAE,MAAM;GAAU,OAAO;GAAK,UAAU;GAAM;EACxD,SAAS;GAAE,MAAM;GAAU,OAAO;GAAK,SAAS;GAAK;EACrD,cAAc;GAAE,MAAM;GAAU,OAAO;GAAK,SAAS;GAAM;EAC3D,OAAO;GAAE,MAAM;GAAW,OAAO;GAAK,SAAS;GAAO;EACtD,aAAa;GAAE,MAAM;GAAU,SAAS;GAAQ;EAChD,oBAAoB;GAAE,MAAM;GAAW,SAAS;GAAO;EACvD,aAAa;GAAE,MAAM;GAAW,SAAS;GAAO;EAChD,SAAS;GAAE,MAAM;GAAW,SAAS;GAAO;EAC5C,QAAQ;GAAE,MAAM;GAAW,SAAS;GAAO;EAC3C,6BAA6B;GAAE,MAAM;GAAW,SAAS;GAAO;EAChE,cAAc;GAAE,MAAM;GAAW,SAAS;GAAO;EACjD,QAAQ;GAAE,MAAM;GAAW,SAAS;GAAO;EAC3C,yBAAyB;GAAE,MAAM;GAAW,SAAS;GAAO;EAC5D,mBAAmB,EAAE,MAAM,UAAU;EACrC,mBAAmB,EAAE,MAAM,UAAU;EACrC,sBAAsB,EAAE,MAAM,UAAU;EACxC,mBAAmB,EAAE,MAAM,UAAU;EACrC,qBAAqB,EAAE,MAAM,UAAU;EAC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