@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/jest.js
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
|
-
import { FixtureLoadError } from "./fixture-loader.js";
|
|
1
|
+
import { FixtureLoadError, MisbehaviorConfigError } from "./fixture-loader.js";
|
|
2
|
+
import { AimockTestIdCollisionError } from "./mcp-fakes-report.js";
|
|
2
3
|
import { LLMock } from "./llmock.js";
|
|
4
|
+
import { FakesPluginState, TEST_ID_SEPARATOR, fakesReportMode, fakesTarget, fetchFakesReport } from "./fakes-plugin.js";
|
|
3
5
|
import { statSync } from "node:fs";
|
|
4
|
-
import { resolve } from "node:path";
|
|
6
|
+
import { relative, resolve, sep } from "node:path";
|
|
5
7
|
|
|
6
8
|
//#region src/jest.ts
|
|
9
|
+
/** TI2: `<testPath relative to root, with "/"> › <currentTestName>`. */
|
|
10
|
+
function defaultJestId(root) {
|
|
11
|
+
const { testPath, currentTestName } = expect.getState();
|
|
12
|
+
if (!testPath || currentTestName === void 0) throw new AimockTestIdCollisionError("default test ids are not supported here (concurrent test or no running test); pass an explicit testId");
|
|
13
|
+
return relative(root, testPath).split(sep).join("/") + TEST_ID_SEPARATOR + currentTestName;
|
|
14
|
+
}
|
|
7
15
|
/**
|
|
8
16
|
* Start an aimock server for the duration of the test suite.
|
|
9
17
|
*
|
|
@@ -11,7 +19,8 @@ import { resolve } from "node:path";
|
|
|
11
19
|
* `mcpFakes` blocks; a bad `mcpFakes` block fails `beforeAll`)
|
|
12
20
|
* - `beforeEach`: closes Live sessions and resets fixture match counts and MCP fake
|
|
13
21
|
* consumption (not fixtures or fakes)
|
|
14
|
-
* - `afterEach`: closes Live sessions owned by this helper's server
|
|
22
|
+
* - `afterEach`: closes Live sessions owned by this helper's server, then checks
|
|
23
|
+
* the MCP fake report under `fakesReport: "warn" | "fail"`
|
|
15
24
|
* - `afterAll`: stops the server
|
|
16
25
|
*
|
|
17
26
|
* Returns a getter function — call it inside tests to access the handle.
|
|
@@ -23,8 +32,11 @@ function useAimock(options = {}) {
|
|
|
23
32
|
let handle = null;
|
|
24
33
|
let origOpenaiUrl;
|
|
25
34
|
let origAnthropicUrl;
|
|
35
|
+
const root = resolve(options.testIdRoot ?? process.cwd());
|
|
36
|
+
let state = new FakesPluginState("off");
|
|
26
37
|
beforeAll(async () => {
|
|
27
|
-
const { fixtures: fixturePath, patchEnv, ...serverOpts } = options;
|
|
38
|
+
const { fixtures: fixturePath, patchEnv, fakesReport, testIdRoot, ...serverOpts } = options;
|
|
39
|
+
state = new FakesPluginState(fakesReportMode(fakesReport));
|
|
28
40
|
const llm = new LLMock(serverOpts);
|
|
29
41
|
if (fixturePath) loadFixtures(llm, resolve(fixturePath));
|
|
30
42
|
const url = await llm.start();
|
|
@@ -36,17 +48,27 @@ function useAimock(options = {}) {
|
|
|
36
48
|
}
|
|
37
49
|
handle = {
|
|
38
50
|
llm,
|
|
39
|
-
url
|
|
51
|
+
url,
|
|
52
|
+
fakesFor(testId, opts = {}) {
|
|
53
|
+
const id = testId ?? defaultJestId(root);
|
|
54
|
+
state.register(id, opts.context ?? null);
|
|
55
|
+
return fakesTarget(url, id, opts);
|
|
56
|
+
},
|
|
57
|
+
fakesReport(testId, opts = {}) {
|
|
58
|
+
return fetchFakesReport(url, testId ?? defaultJestId(root), opts.context ?? null);
|
|
59
|
+
}
|
|
40
60
|
};
|
|
41
61
|
});
|
|
42
62
|
beforeEach(() => {
|
|
43
63
|
if (handle) {
|
|
44
64
|
handle.llm.closeLiveSessions();
|
|
45
65
|
handle.llm.resetMatchCounts();
|
|
66
|
+
state.beforeEach(handle.llm);
|
|
46
67
|
}
|
|
47
68
|
});
|
|
48
|
-
afterEach(() => {
|
|
69
|
+
afterEach(async () => {
|
|
49
70
|
handle?.llm.closeLiveSessions();
|
|
71
|
+
if (handle) await state.afterEach(handle.llm, handle.url);
|
|
50
72
|
});
|
|
51
73
|
afterAll(async () => {
|
|
52
74
|
if (handle) {
|
|
@@ -68,15 +90,17 @@ function useAimock(options = {}) {
|
|
|
68
90
|
/**
|
|
69
91
|
* Load a fixture file or directory into `llm`: its LLM fixtures and its
|
|
70
92
|
* `mcpFakes` blocks, which the LLMock buffers and auto-mounts at start (F12).
|
|
71
|
-
* A `FixtureLoadError` (a bad `mcpFakes` block)
|
|
72
|
-
*
|
|
93
|
+
* A `FixtureLoadError` (a bad `mcpFakes` block) or a `MisbehaviorConfigError`
|
|
94
|
+
* (a bad fixture `misbehavior` key, thrown only with `enableMisbehavior: true`)
|
|
95
|
+
* propagates and fails `beforeAll`; any other load failure is only warned
|
|
96
|
+
* about, as before.
|
|
73
97
|
*/
|
|
74
98
|
function loadFixtures(llm, fixturePath) {
|
|
75
99
|
try {
|
|
76
100
|
if (statSync(fixturePath).isDirectory()) llm.loadFixtureDir(fixturePath);
|
|
77
101
|
else llm.loadFixtureFile(fixturePath);
|
|
78
102
|
} catch (err) {
|
|
79
|
-
if (err instanceof FixtureLoadError) throw err;
|
|
103
|
+
if (err instanceof FixtureLoadError || err instanceof MisbehaviorConfigError) throw err;
|
|
80
104
|
console.warn(`[aimock] Failed to load fixtures from ${fixturePath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
81
105
|
}
|
|
82
106
|
}
|
package/dist/jest.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jest.js","names":[],"sources":["../src/jest.ts"],"sourcesContent":["/**\n * Jest integration for aimock.\n *\n * Usage:\n * import { useAimock } from \"@copilotkit/aimock/jest\";\n *\n * const mock = useAimock({ fixtures: \"./fixtures\" });\n *\n * it(\"responds\", async () => {\n * const res = await fetch(`${mock().url}/v1/chat/completions`, { ... });\n * });\n */\n\n/* eslint-disable no-var */\n// Jest globals — available at runtime in jest test files\ndeclare var beforeAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var beforeEach: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterEach: (fn: () => Promise<void> | void, timeout?: number) => void;\n/* eslint-enable no-var */\n\nimport { LLMock } from \"./llmock.js\";\nimport { FixtureLoadError } from \"./fixture-loader.js\";\nimport type { MockServerOptions } from \"./types.js\";\nimport { statSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nexport interface UseAimockOptions extends MockServerOptions {\n /** Path to fixture file or directory. Loaded automatically on start. */\n fixtures?: string;\n /** If true, sets process.env.OPENAI_BASE_URL to the mock URL + /v1. */\n patchEnv?: boolean;\n}\n\nexport interface AimockHandle {\n /** The LLMock instance. */\n readonly llm: LLMock;\n /** The server URL (e.g., http://127.0.0.1:4010). */\n readonly url: string;\n}\n\n/**\n * Start an aimock server for the duration of the test suite.\n *\n * - `beforeAll`: starts the server and optionally loads fixtures (LLM fixtures and\n * `mcpFakes` blocks; a bad `mcpFakes` block fails `beforeAll`)\n * - `beforeEach`: closes Live sessions and resets fixture match counts and MCP fake\n * consumption (not fixtures or fakes)\n * - `afterEach`: closes Live sessions owned by this helper's server\n * - `afterAll`: stops the server\n *\n * Returns a getter function — call it inside tests to access the handle.\n *\n * NOTE: Jest globals (beforeAll, afterAll, beforeEach, afterEach) must be available\n * in the test environment. This works with the default jest configuration.\n */\nexport function useAimock(options: UseAimockOptions = {}): () => AimockHandle {\n let handle: AimockHandle | null = null;\n let origOpenaiUrl: string | undefined;\n let origAnthropicUrl: string | undefined;\n\n beforeAll(async () => {\n const { fixtures: fixturePath, patchEnv, ...serverOpts } = options;\n const llm = new LLMock(serverOpts);\n\n if (fixturePath) {\n loadFixtures(llm, resolve(fixturePath));\n }\n\n const url = await llm.start();\n\n if (patchEnv !== false) {\n origOpenaiUrl = process.env.OPENAI_BASE_URL;\n origAnthropicUrl = process.env.ANTHROPIC_BASE_URL;\n process.env.OPENAI_BASE_URL = `${url}/v1`;\n process.env.ANTHROPIC_BASE_URL = `${url}/v1`;\n }\n\n handle = { llm, url };\n });\n\n beforeEach(() => {\n if (handle) {\n handle.llm.closeLiveSessions();\n handle.llm.resetMatchCounts();\n }\n });\n\n afterEach(() => {\n handle?.llm.closeLiveSessions();\n });\n\n afterAll(async () => {\n if (handle) {\n if (options.patchEnv !== false) {\n if (origOpenaiUrl !== undefined) process.env.OPENAI_BASE_URL = origOpenaiUrl;\n else delete process.env.OPENAI_BASE_URL;\n if (origAnthropicUrl !== undefined) process.env.ANTHROPIC_BASE_URL = origAnthropicUrl;\n else delete process.env.ANTHROPIC_BASE_URL;\n }\n await handle.llm.stop();\n handle = null;\n }\n });\n\n return () => {\n if (!handle) {\n throw new Error(\"useAimock(): server not started — are you calling this inside a test?\");\n }\n return handle;\n };\n}\n\n/**\n * Load a fixture file or directory into `llm`: its LLM fixtures and its\n * `mcpFakes` blocks, which the LLMock buffers and auto-mounts at start (F12).\n * A `FixtureLoadError` (a bad `mcpFakes` block) propagates and fails\n * `beforeAll`; any other load failure is only warned about, as before.\n */\nfunction loadFixtures(llm: LLMock, fixturePath: string): void {\n try {\n const stat = statSync(fixturePath);\n if (stat.isDirectory()) {\n llm.loadFixtureDir(fixturePath);\n } else {\n llm.loadFixtureFile(fixturePath);\n }\n } catch (err) {\n if (err instanceof FixtureLoadError) throw err;\n console.warn(\n `[aimock] Failed to load fixtures from ${fixturePath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nexport { LLMock } from \"./llmock.js\";\nexport type { MockServerOptions, Fixture } from \"./types.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,UAAU,UAA4B,EAAE,EAAsB;CAC5E,IAAI,SAA8B;CAClC,IAAI;CACJ,IAAI;AAEJ,WAAU,YAAY;EACpB,MAAM,EAAE,UAAU,aAAa,UAAU,GAAG,eAAe;EAC3D,MAAM,MAAM,IAAI,OAAO,WAAW;AAElC,MAAI,YACF,cAAa,KAAK,QAAQ,YAAY,CAAC;EAGzC,MAAM,MAAM,MAAM,IAAI,OAAO;AAE7B,MAAI,aAAa,OAAO;AACtB,mBAAgB,QAAQ,IAAI;AAC5B,sBAAmB,QAAQ,IAAI;AAC/B,WAAQ,IAAI,kBAAkB,GAAG,IAAI;AACrC,WAAQ,IAAI,qBAAqB,GAAG,IAAI;;AAG1C,WAAS;GAAE;GAAK;GAAK;GACrB;AAEF,kBAAiB;AACf,MAAI,QAAQ;AACV,UAAO,IAAI,mBAAmB;AAC9B,UAAO,IAAI,kBAAkB;;GAE/B;AAEF,iBAAgB;AACd,UAAQ,IAAI,mBAAmB;GAC/B;AAEF,UAAS,YAAY;AACnB,MAAI,QAAQ;AACV,OAAI,QAAQ,aAAa,OAAO;AAC9B,QAAI,kBAAkB,OAAW,SAAQ,IAAI,kBAAkB;QAC1D,QAAO,QAAQ,IAAI;AACxB,QAAI,qBAAqB,OAAW,SAAQ,IAAI,qBAAqB;QAChE,QAAO,QAAQ,IAAI;;AAE1B,SAAM,OAAO,IAAI,MAAM;AACvB,YAAS;;GAEX;AAEF,cAAa;AACX,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,wEAAwE;AAE1F,SAAO;;;;;;;;;AAUX,SAAS,aAAa,KAAa,aAA2B;AAC5D,KAAI;AAEF,MADa,SAAS,YAAY,CACzB,aAAa,CACpB,KAAI,eAAe,YAAY;MAE/B,KAAI,gBAAgB,YAAY;UAE3B,KAAK;AACZ,MAAI,eAAe,iBAAkB,OAAM;AAC3C,UAAQ,KACN,yCAAyC,YAAY,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,GAC1G"}
|
|
1
|
+
{"version":3,"file":"jest.js","names":[],"sources":["../src/jest.ts"],"sourcesContent":["/**\n * Jest integration for aimock.\n *\n * Usage:\n * import { useAimock } from \"@copilotkit/aimock/jest\";\n *\n * const mock = useAimock({ fixtures: \"./fixtures\" });\n *\n * it(\"responds\", async () => {\n * const res = await fetch(`${mock().url}/v1/chat/completions`, { ... });\n * });\n */\n\n/* eslint-disable no-var */\n// Jest globals — available at runtime in jest test files\ndeclare var beforeAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterAll: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var beforeEach: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var afterEach: (fn: () => Promise<void> | void, timeout?: number) => void;\ndeclare var expect: { getState(): { testPath?: string; currentTestName?: string } };\n/* eslint-enable no-var */\n\nimport { LLMock } from \"./llmock.js\";\nimport { FixtureLoadError, MisbehaviorConfigError } from \"./fixture-loader.js\";\nimport type { MockServerOptions } from \"./types.js\";\nimport {\n FakesPluginState,\n TEST_ID_SEPARATOR,\n fakesReportMode,\n fakesTarget,\n fetchFakesReport,\n type FakesForOptions,\n type FakesReportMode,\n type FakesTarget,\n} from \"./fakes-plugin.js\";\nimport { AimockTestIdCollisionError, type McpFakesReport } from \"./mcp-fakes-report.js\";\nimport { statSync } from \"node:fs\";\nimport { relative, resolve, sep } from \"node:path\";\n\nexport interface UseAimockOptions extends MockServerOptions {\n /** Path to fixture file or directory. Loaded automatically on start. */\n fixtures?: string;\n /** If true, sets process.env.OPENAI_BASE_URL to the mock URL + /v1. */\n patchEnv?: boolean;\n /**\n * The per-test MCP fake report, read in `afterEach` (RP7): `\"off\"` (the\n * default), `\"warn\"` (print a failing report) or `\"fail\"` (throw\n * `AimockFakesReportError`). Not supported with `test.concurrent`: the\n * report keeps one state per `useAimock`, so concurrent tests clear and read\n * each other's identities, and Jest cannot tell this plugin that a test is\n * concurrent. Keep `\"off\"` for a suite with concurrent tests.\n */\n fakesReport?: FakesReportMode;\n /**\n * The directory default test ids are relative to (TI2). Defaults to\n * `process.cwd()` when `useAimock` is called; Jest does not expose\n * `rootDir` to test code.\n */\n testIdRoot?: string;\n}\n\nexport interface AimockHandle {\n /** The LLMock instance. */\n readonly llm: LLMock;\n /** The server URL (e.g., http://127.0.0.1:4010). */\n readonly url: string;\n}\n\n/**\n * The handle `useAimock` returns: an `AimockHandle` plus the MCP fakes\n * helpers (RP7). A separate type, so that `AimockHandle` stays as it was and\n * code that builds its own `AimockHandle` keeps compiling.\n */\nexport interface AimockFakesHandle extends AimockHandle {\n /**\n * The MCP URL and headers for the fakes scoped to `testId` (RP7), and\n * registers that identity for this test's report. With no `testId`, the\n * default is `<test file relative to testIdRoot> › <currentTestName>` (TI2);\n * it is used only here and in `fakesReport`, never on LLM traffic (TI4).\n * Two tests with the same full name in one file share a default id (TI5):\n * pass an explicit `testId` for them. In `test.concurrent`, Jest can\n * report another test's name, so pass an explicit `testId` there too (with\n * `fakesReport: \"off\"`; the report is not supported in concurrent tests).\n */\n fakesFor(testId?: string, opts?: FakesForOptions): FakesTarget;\n /** The MCP fake report for `testId` (default as in `fakesFor`). */\n fakesReport(testId?: string, opts?: { context?: string }): Promise<McpFakesReport>;\n}\n\n/** TI2: `<testPath relative to root, with \"/\"> › <currentTestName>`. */\nfunction defaultJestId(root: string): string {\n const { testPath, currentTestName } = expect.getState();\n if (!testPath || currentTestName === undefined) {\n throw new AimockTestIdCollisionError(\n \"default test ids are not supported here (concurrent test or no running test); pass an explicit testId\",\n );\n }\n return relative(root, testPath).split(sep).join(\"/\") + TEST_ID_SEPARATOR + currentTestName;\n}\n\n/**\n * Start an aimock server for the duration of the test suite.\n *\n * - `beforeAll`: starts the server and optionally loads fixtures (LLM fixtures and\n * `mcpFakes` blocks; a bad `mcpFakes` block fails `beforeAll`)\n * - `beforeEach`: closes Live sessions and resets fixture match counts and MCP fake\n * consumption (not fixtures or fakes)\n * - `afterEach`: closes Live sessions owned by this helper's server, then checks\n * the MCP fake report under `fakesReport: \"warn\" | \"fail\"`\n * - `afterAll`: stops the server\n *\n * Returns a getter function — call it inside tests to access the handle.\n *\n * NOTE: Jest globals (beforeAll, afterAll, beforeEach, afterEach) must be available\n * in the test environment. This works with the default jest configuration.\n */\nexport function useAimock(options: UseAimockOptions = {}): () => AimockFakesHandle {\n let handle: AimockFakesHandle | null = null;\n let origOpenaiUrl: string | undefined;\n let origAnthropicUrl: string | undefined;\n const root = resolve(options.testIdRoot ?? process.cwd());\n let state = new FakesPluginState(\"off\");\n\n beforeAll(async () => {\n const { fixtures: fixturePath, patchEnv, fakesReport, testIdRoot, ...serverOpts } = options;\n void testIdRoot; // read above, when useAimock is called\n state = new FakesPluginState(fakesReportMode(fakesReport));\n const llm = new LLMock(serverOpts);\n\n if (fixturePath) {\n loadFixtures(llm, resolve(fixturePath));\n }\n\n const url = await llm.start();\n\n if (patchEnv !== false) {\n origOpenaiUrl = process.env.OPENAI_BASE_URL;\n origAnthropicUrl = process.env.ANTHROPIC_BASE_URL;\n process.env.OPENAI_BASE_URL = `${url}/v1`;\n process.env.ANTHROPIC_BASE_URL = `${url}/v1`;\n }\n\n handle = {\n llm,\n url,\n fakesFor(testId?: string, opts: FakesForOptions = {}): FakesTarget {\n const id = testId ?? defaultJestId(root); // TI4: an explicit id wins\n state.register(id, opts.context ?? null);\n return fakesTarget(url, id, opts);\n },\n fakesReport(testId?: string, opts: { context?: string } = {}): Promise<McpFakesReport> {\n return fetchFakesReport(url, testId ?? defaultJestId(root), opts.context ?? null);\n },\n };\n });\n\n beforeEach(() => {\n if (handle) {\n handle.llm.closeLiveSessions();\n handle.llm.resetMatchCounts();\n state.beforeEach(handle.llm);\n }\n });\n\n afterEach(async () => {\n handle?.llm.closeLiveSessions();\n if (handle) await state.afterEach(handle.llm, handle.url);\n });\n\n afterAll(async () => {\n if (handle) {\n if (options.patchEnv !== false) {\n if (origOpenaiUrl !== undefined) process.env.OPENAI_BASE_URL = origOpenaiUrl;\n else delete process.env.OPENAI_BASE_URL;\n if (origAnthropicUrl !== undefined) process.env.ANTHROPIC_BASE_URL = origAnthropicUrl;\n else delete process.env.ANTHROPIC_BASE_URL;\n }\n await handle.llm.stop();\n handle = null;\n }\n });\n\n return () => {\n if (!handle) {\n throw new Error(\"useAimock(): server not started — are you calling this inside a test?\");\n }\n return handle;\n };\n}\n\n/**\n * Load a fixture file or directory into `llm`: its LLM fixtures and its\n * `mcpFakes` blocks, which the LLMock buffers and auto-mounts at start (F12).\n * A `FixtureLoadError` (a bad `mcpFakes` block) or a `MisbehaviorConfigError`\n * (a bad fixture `misbehavior` key, thrown only with `enableMisbehavior: true`)\n * propagates and fails `beforeAll`; any other load failure is only warned\n * about, as before.\n */\nfunction loadFixtures(llm: LLMock, fixturePath: string): void {\n try {\n const stat = statSync(fixturePath);\n if (stat.isDirectory()) {\n llm.loadFixtureDir(fixturePath);\n } else {\n llm.loadFixtureFile(fixturePath);\n }\n } catch (err) {\n if (err instanceof FixtureLoadError || err instanceof MisbehaviorConfigError) throw err;\n console.warn(\n `[aimock] Failed to load fixtures from ${fixturePath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nexport { LLMock } from \"./llmock.js\";\nexport type { MockServerOptions, Fixture } from \"./types.js\";\nexport type { FakesForOptions, FakesReportMode, FakesTarget } from \"./fakes-plugin.js\";\nexport type { McpFakesReport } from \"./mcp-fakes-report.js\";\n"],"mappings":";;;;;;;;;AA0FA,SAAS,cAAc,MAAsB;CAC3C,MAAM,EAAE,UAAU,oBAAoB,OAAO,UAAU;AACvD,KAAI,CAAC,YAAY,oBAAoB,OACnC,OAAM,IAAI,2BACR,wGACD;AAEH,QAAO,SAAS,MAAM,SAAS,CAAC,MAAM,IAAI,CAAC,KAAK,IAAI,GAAG,oBAAoB;;;;;;;;;;;;;;;;;;AAmB7E,SAAgB,UAAU,UAA4B,EAAE,EAA2B;CACjF,IAAI,SAAmC;CACvC,IAAI;CACJ,IAAI;CACJ,MAAM,OAAO,QAAQ,QAAQ,cAAc,QAAQ,KAAK,CAAC;CACzD,IAAI,QAAQ,IAAI,iBAAiB,MAAM;AAEvC,WAAU,YAAY;EACpB,MAAM,EAAE,UAAU,aAAa,UAAU,aAAa,YAAY,GAAG,eAAe;AAEpF,UAAQ,IAAI,iBAAiB,gBAAgB,YAAY,CAAC;EAC1D,MAAM,MAAM,IAAI,OAAO,WAAW;AAElC,MAAI,YACF,cAAa,KAAK,QAAQ,YAAY,CAAC;EAGzC,MAAM,MAAM,MAAM,IAAI,OAAO;AAE7B,MAAI,aAAa,OAAO;AACtB,mBAAgB,QAAQ,IAAI;AAC5B,sBAAmB,QAAQ,IAAI;AAC/B,WAAQ,IAAI,kBAAkB,GAAG,IAAI;AACrC,WAAQ,IAAI,qBAAqB,GAAG,IAAI;;AAG1C,WAAS;GACP;GACA;GACA,SAAS,QAAiB,OAAwB,EAAE,EAAe;IACjE,MAAM,KAAK,UAAU,cAAc,KAAK;AACxC,UAAM,SAAS,IAAI,KAAK,WAAW,KAAK;AACxC,WAAO,YAAY,KAAK,IAAI,KAAK;;GAEnC,YAAY,QAAiB,OAA6B,EAAE,EAA2B;AACrF,WAAO,iBAAiB,KAAK,UAAU,cAAc,KAAK,EAAE,KAAK,WAAW,KAAK;;GAEpF;GACD;AAEF,kBAAiB;AACf,MAAI,QAAQ;AACV,UAAO,IAAI,mBAAmB;AAC9B,UAAO,IAAI,kBAAkB;AAC7B,SAAM,WAAW,OAAO,IAAI;;GAE9B;AAEF,WAAU,YAAY;AACpB,UAAQ,IAAI,mBAAmB;AAC/B,MAAI,OAAQ,OAAM,MAAM,UAAU,OAAO,KAAK,OAAO,IAAI;GACzD;AAEF,UAAS,YAAY;AACnB,MAAI,QAAQ;AACV,OAAI,QAAQ,aAAa,OAAO;AAC9B,QAAI,kBAAkB,OAAW,SAAQ,IAAI,kBAAkB;QAC1D,QAAO,QAAQ,IAAI;AACxB,QAAI,qBAAqB,OAAW,SAAQ,IAAI,qBAAqB;QAChE,QAAO,QAAQ,IAAI;;AAE1B,SAAM,OAAO,IAAI,MAAM;AACvB,YAAS;;GAEX;AAEF,cAAa;AACX,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,wEAAwE;AAE1F,SAAO;;;;;;;;;;;AAYX,SAAS,aAAa,KAAa,aAA2B;AAC5D,KAAI;AAEF,MADa,SAAS,YAAY,CACzB,aAAa,CACpB,KAAI,eAAe,YAAY;MAE/B,KAAI,gBAAgB,YAAY;UAE3B,KAAK;AACZ,MAAI,eAAe,oBAAoB,eAAe,uBAAwB,OAAM;AACpF,UAAQ,KACN,yCAAyC,YAAY,IAAI,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,GAC1G"}
|
package/dist/journal.cjs
CHANGED
|
@@ -76,12 +76,43 @@ function systemMessageEqual(a, b) {
|
|
|
76
76
|
* (ignoring sequenceIndex). Used to group sequenced fixtures.
|
|
77
77
|
*/
|
|
78
78
|
function matchCriteriaEqual(a, b) {
|
|
79
|
-
return fieldEqual(a.userMessage, b.userMessage) && systemMessageEqual(a.systemMessage, b.systemMessage) && fieldEqual(a.inputText, b.inputText) && fieldEqual(a.toolCallId, b.toolCallId) && fieldEqual(a.toolName, b.toolName) && fieldEqual(a.model, b.model) && fieldEqual(a.responseFormat, b.responseFormat) && fieldEqual(a.predicate, b.predicate) && fieldEqual(a.endpoint, b.endpoint) && fieldEqual(a.turnIndex, b.turnIndex) && fieldEqual(a.hasToolResult, b.hasToolResult) && fieldEqual(a.toolResultContains, b.toolResultContains) && fieldEqual(a.context, b.context);
|
|
79
|
+
return fieldEqual(a.userMessage, b.userMessage) && systemMessageEqual(a.systemMessage, b.systemMessage) && fieldEqual(a.inputText, b.inputText) && fieldEqual(a.toolCallId, b.toolCallId) && fieldEqual(a.toolName, b.toolName) && fieldEqual(a.toolNamespace, b.toolNamespace) && fieldEqual(a.model, b.model) && fieldEqual(a.responseFormat, b.responseFormat) && fieldEqual(a.predicate, b.predicate) && fieldEqual(a.endpoint, b.endpoint) && fieldEqual(a.turnIndex, b.turnIndex) && fieldEqual(a.hasToolResult, b.hasToolResult) && fieldEqual(a.toolResultContains, b.toolResultContains) && fieldEqual(a.context, b.context);
|
|
80
80
|
}
|
|
81
|
+
/** Count-map keys resolve through `identity`, so every alias of a fixture finds its caller entry. */
|
|
82
|
+
var FixtureCountMap = class extends Map {
|
|
83
|
+
constructor(identity) {
|
|
84
|
+
super();
|
|
85
|
+
this.identity = identity;
|
|
86
|
+
}
|
|
87
|
+
get(key) {
|
|
88
|
+
return super.get(this.identity(key));
|
|
89
|
+
}
|
|
90
|
+
has(key) {
|
|
91
|
+
return super.has(this.identity(key));
|
|
92
|
+
}
|
|
93
|
+
set(key, value) {
|
|
94
|
+
return super.set(this.identity(key), value);
|
|
95
|
+
}
|
|
96
|
+
delete(key) {
|
|
97
|
+
return super.delete(this.identity(key));
|
|
98
|
+
}
|
|
99
|
+
};
|
|
81
100
|
var Journal = class {
|
|
82
101
|
entries = [];
|
|
83
102
|
matchedFixtures = /* @__PURE__ */ new WeakMap();
|
|
103
|
+
/** The fixture a request was served from, where the entry names its caller fixture instead. */
|
|
104
|
+
servedFixtures = /* @__PURE__ */ new WeakMap();
|
|
84
105
|
fixtureMatchCountsByTestId = /* @__PURE__ */ new Map();
|
|
106
|
+
/** An extended server's view of a fixture to the caller's fixture (configureFixtureViewSource). */
|
|
107
|
+
fixtureViewSource = (fixture) => fixture;
|
|
108
|
+
fixtureCountIdentity = (fixture) => fixture;
|
|
109
|
+
/** The key a fixture is counted under: the caller's object behind any view or copy. */
|
|
110
|
+
fixtureCountKey = (fixture) => this.fixtureCountIdentity(this.fixtureViewSource(fixture));
|
|
111
|
+
createFixtureCountMap = () => /* @__PURE__ */ new Map();
|
|
112
|
+
fixtureCountIdentityConfigured = false;
|
|
113
|
+
fixtureViewSourceConfigured = false;
|
|
114
|
+
counterTestIds = /* @__PURE__ */ new Set();
|
|
115
|
+
misbehaviorCountersByTestId = /* @__PURE__ */ new Map();
|
|
85
116
|
maxEntries;
|
|
86
117
|
fixtureCountsMaxTestIds;
|
|
87
118
|
onAdd;
|
|
@@ -124,7 +155,16 @@ var Journal = class {
|
|
|
124
155
|
...entry,
|
|
125
156
|
body: capBody(entry.body)
|
|
126
157
|
};
|
|
127
|
-
|
|
158
|
+
const fixture = full.response.fixture;
|
|
159
|
+
const source = fixture ? this.fixtureCountKey(fixture) : fixture;
|
|
160
|
+
if (fixture && source !== fixture) {
|
|
161
|
+
full.response = {
|
|
162
|
+
...full.response,
|
|
163
|
+
fixture: source
|
|
164
|
+
};
|
|
165
|
+
this.servedFixtures.set(full, fixture);
|
|
166
|
+
}
|
|
167
|
+
if (matchedFixture) this.matchedFixtures.set(full, this.fixtureCountKey(matchedFixture));
|
|
128
168
|
this.entries.push(full);
|
|
129
169
|
if (this.maxEntries > 0 && this.entries.length > this.maxEntries) this.entries.shift();
|
|
130
170
|
this.onAdd?.(full);
|
|
@@ -151,7 +191,16 @@ var Journal = class {
|
|
|
151
191
|
return this.entries.length > 0 ? this.entries[this.entries.length - 1] : null;
|
|
152
192
|
}
|
|
153
193
|
findByFixture(fixture) {
|
|
154
|
-
|
|
194
|
+
const key = this.fixtureCountKey(fixture);
|
|
195
|
+
return this.entries.filter((e) => (this.matchedFixtures.get(e) ?? e.response.fixture) === key);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* @internal The fixture `entry`'s request was served from: the extended
|
|
199
|
+
* view or the per-addition copy when the entry names the caller's fixture
|
|
200
|
+
* behind it, otherwise `entry.response.fixture`. The journal JSON shows it.
|
|
201
|
+
*/
|
|
202
|
+
servedFixture(entry) {
|
|
203
|
+
return this.servedFixtures.get(entry) ?? entry.response.fixture;
|
|
155
204
|
}
|
|
156
205
|
/**
|
|
157
206
|
* READ-ONLY accessor. Returns the existing count map for `testId`, or an
|
|
@@ -161,7 +210,7 @@ var Journal = class {
|
|
|
161
210
|
* `getOrCreateFixtureMatchCountsForTest`.
|
|
162
211
|
*/
|
|
163
212
|
getFixtureMatchCountsForTest(testId) {
|
|
164
|
-
return this.fixtureMatchCountsByTestId.get(testId) ??
|
|
213
|
+
return this.fixtureMatchCountsByTestId.get(testId) ?? this.createFixtureCountMap();
|
|
165
214
|
}
|
|
166
215
|
/**
|
|
167
216
|
* WRITE path: get the count map for `testId`, inserting a fresh empty Map
|
|
@@ -172,15 +221,83 @@ var Journal = class {
|
|
|
172
221
|
getOrCreateFixtureMatchCountsForTest(testId) {
|
|
173
222
|
let counts = this.fixtureMatchCountsByTestId.get(testId);
|
|
174
223
|
if (!counts) {
|
|
175
|
-
counts =
|
|
224
|
+
counts = this.createFixtureCountMap();
|
|
176
225
|
this.fixtureMatchCountsByTestId.set(testId, counts);
|
|
177
|
-
|
|
178
|
-
const oldest = this.fixtureMatchCountsByTestId.keys().next().value;
|
|
179
|
-
if (oldest !== void 0) this.fixtureMatchCountsByTestId.delete(oldest);
|
|
180
|
-
}
|
|
226
|
+
this.admitCounterTestId(testId);
|
|
181
227
|
}
|
|
182
228
|
return counts;
|
|
183
229
|
}
|
|
230
|
+
/** Match and fault mutations share one admission order and capacity. */
|
|
231
|
+
admitCounterTestId(testId) {
|
|
232
|
+
this.counterTestIds.add(testId);
|
|
233
|
+
if (this.fixtureCountsMaxTestIds > 0 && this.counterTestIds.size > this.fixtureCountsMaxTestIds) {
|
|
234
|
+
const oldest = this.counterTestIds.values().next().value;
|
|
235
|
+
if (oldest !== void 0) {
|
|
236
|
+
this.counterTestIds.delete(oldest);
|
|
237
|
+
this.fixtureMatchCountsByTestId.delete(oldest);
|
|
238
|
+
this.misbehaviorCountersByTestId.delete(oldest);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
getOrCreateMisbehaviorCounter(key) {
|
|
243
|
+
let sources = this.misbehaviorCountersByTestId.get(key.testId);
|
|
244
|
+
if (!sources) {
|
|
245
|
+
sources = /* @__PURE__ */ new Map();
|
|
246
|
+
this.misbehaviorCountersByTestId.set(key.testId, sources);
|
|
247
|
+
this.admitCounterTestId(key.testId);
|
|
248
|
+
}
|
|
249
|
+
let entries = sources.get(key.sourceKey);
|
|
250
|
+
if (!entries) {
|
|
251
|
+
entries = /* @__PURE__ */ new Map();
|
|
252
|
+
sources.set(key.sourceKey, entries);
|
|
253
|
+
}
|
|
254
|
+
let counter = entries.get(key.entryIndex);
|
|
255
|
+
if (!counter) {
|
|
256
|
+
counter = {
|
|
257
|
+
ordinal: 0,
|
|
258
|
+
firings: 0
|
|
259
|
+
};
|
|
260
|
+
entries.set(key.entryIndex, counter);
|
|
261
|
+
}
|
|
262
|
+
return counter;
|
|
263
|
+
}
|
|
264
|
+
getFiringCount(key) {
|
|
265
|
+
return this.misbehaviorCountersByTestId.get(key.testId)?.get(key.sourceKey)?.get(key.entryIndex)?.firings ?? 0;
|
|
266
|
+
}
|
|
267
|
+
nextOrdinal(key) {
|
|
268
|
+
return this.getOrCreateMisbehaviorCounter(key).ordinal++;
|
|
269
|
+
}
|
|
270
|
+
recordFiring(key) {
|
|
271
|
+
this.getOrCreateMisbehaviorCounter(key).firings++;
|
|
272
|
+
}
|
|
273
|
+
clearMisbehaviorCounters(testId) {
|
|
274
|
+
if (testId !== void 0) {
|
|
275
|
+
this.misbehaviorCountersByTestId.delete(testId);
|
|
276
|
+
if (!this.fixtureMatchCountsByTestId.has(testId)) this.counterTestIds.delete(testId);
|
|
277
|
+
} else {
|
|
278
|
+
this.misbehaviorCountersByTestId.clear();
|
|
279
|
+
for (const id of this.counterTestIds) if (!this.fixtureMatchCountsByTestId.has(id)) this.counterTestIds.delete(id);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
/** @internal LLMock configures caller count identity before serving requests. */
|
|
283
|
+
configureFixtureCountIdentity(identity) {
|
|
284
|
+
if (this.fixtureCountIdentityConfigured || this.fixtureMatchCountsByTestId.size > 0) throw new Error("Fixture count identity must be configured once before counting");
|
|
285
|
+
this.fixtureCountIdentity = identity;
|
|
286
|
+
this.createFixtureCountMap = () => new FixtureCountMap(this.fixtureCountKey);
|
|
287
|
+
this.fixtureCountIdentityConfigured = true;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* @internal A server with `responsesTools: "extended"` matches each fixture
|
|
291
|
+
* through its extended view. `source` maps a view back to the caller's
|
|
292
|
+
* fixture, so counts, `findByFixture` and `JournalEntry.response.fixture`
|
|
293
|
+
* keep the caller's object. Configured once, before counting.
|
|
294
|
+
*/
|
|
295
|
+
configureFixtureViewSource(source) {
|
|
296
|
+
if (this.fixtureViewSourceConfigured || this.fixtureMatchCountsByTestId.size > 0) throw new Error("Fixture view source must be configured once before counting");
|
|
297
|
+
this.fixtureViewSource = source;
|
|
298
|
+
this.createFixtureCountMap = () => new FixtureCountMap(this.fixtureCountKey);
|
|
299
|
+
this.fixtureViewSourceConfigured = true;
|
|
300
|
+
}
|
|
184
301
|
getFixtureMatchCount(fixture, testId = require_constants.DEFAULT_TEST_ID) {
|
|
185
302
|
return this.getFixtureMatchCountsForTest(testId).get(fixture) ?? 0;
|
|
186
303
|
}
|
|
@@ -188,14 +305,19 @@ var Journal = class {
|
|
|
188
305
|
const counts = this.getOrCreateFixtureMatchCountsForTest(testId);
|
|
189
306
|
counts.set(fixture, (counts.get(fixture) ?? 0) + 1);
|
|
190
307
|
if (fixture.match.sequenceIndex !== void 0 && allFixtures) for (const sibling of allFixtures) {
|
|
191
|
-
if (sibling === fixture) continue;
|
|
308
|
+
if (this.fixtureCountKey(sibling) === this.fixtureCountKey(fixture)) continue;
|
|
192
309
|
if (sibling.match.sequenceIndex === void 0) continue;
|
|
193
310
|
if (matchCriteriaEqual(fixture.match, sibling.match)) counts.set(sibling, (counts.get(sibling) ?? 0) + 1);
|
|
194
311
|
}
|
|
195
312
|
}
|
|
196
313
|
clearMatchCounts(testId) {
|
|
197
|
-
if (testId !== void 0)
|
|
198
|
-
|
|
314
|
+
if (testId !== void 0) {
|
|
315
|
+
this.fixtureMatchCountsByTestId.delete(testId);
|
|
316
|
+
this.clearMisbehaviorCounters(testId);
|
|
317
|
+
} else {
|
|
318
|
+
this.fixtureMatchCountsByTestId.clear();
|
|
319
|
+
this.clearMisbehaviorCounters();
|
|
320
|
+
}
|
|
199
321
|
}
|
|
200
322
|
/**
|
|
201
323
|
* Clear ONLY the request journal entries, preserving fixture match-counts.
|
|
@@ -209,7 +331,7 @@ var Journal = class {
|
|
|
209
331
|
}
|
|
210
332
|
clear() {
|
|
211
333
|
this.entries = [];
|
|
212
|
-
this.
|
|
334
|
+
this.clearMatchCounts();
|
|
213
335
|
}
|
|
214
336
|
get size() {
|
|
215
337
|
return this.entries.length;
|
package/dist/journal.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.cjs","names":["DEFAULT_TEST_ID","generateId"],"sources":["../src/journal.ts"],"sourcesContent":["import { generateId } from \"./helpers.js\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureMatch,\n JournalBody,\n JournalEntry,\n} from \"./types.js\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nexport { DEFAULT_TEST_ID } from \"./constants.js\";\n\n/**\n * Maximum UTF-8 byte length of a serialized request body retained in a\n * journal entry. Bodies whose JSON serialization exceeds this byte size are\n * replaced with a truncation marker.\n *\n * Only the request `body` field is capped here. `headers` and `path` are\n * retained uncapped, but they are naturally bounded by Node's default ~16 KB\n * maximum HTTP header size, so the per-entry overhead beyond the body cap\n * remains small. Combined with the journal's maxEntries limit (default 1000),\n * the total `JSON.stringify(journal.getAll())` output stays well under V8's\n * ~512 MB string limit even at maximum capacity.\n */\nconst JOURNAL_BODY_CAP_BYTES = 64 * 1024; // 64 KB\n\n/**\n * If `body` serializes to more than JOURNAL_BODY_CAP_BYTES (in UTF-8 bytes),\n * replace it with a truncation marker. Returns the original body when within\n * the cap, or null when `body` is null.\n *\n * The gate uses Buffer.byteLength (UTF-8 bytes) rather than .length (UTF-16\n * code units) to match the constant name and to correctly cap multibyte\n * content (e.g. CJK/emoji) whose code-unit count falls under the threshold\n * but whose byte size does not.\n */\nfunction capBody(body: JournalBody | null): JournalBody | null {\n if (body === null) return null;\n const serialized = JSON.stringify(body);\n if (Buffer.byteLength(serialized, \"utf8\") <= JOURNAL_BODY_CAP_BYTES) return body;\n // The marker is not a chat request, and `JournalBody` no longer claims it is\n // — downstream consumers (e.g. GET /journal) treat the body as opaque JSON.\n return {\n __aimock_truncated: true,\n originalByteSize: Buffer.byteLength(serialized, \"utf8\"),\n note: \"body truncated by aimock journal cap (64 KB limit)\",\n };\n}\n\n/**\n * Narrow a journaled body to a chat-completion request.\n *\n * `JournalEntry.body` is a union (see {@link JournalBody}): most entries hold a\n * chat request, but the fine-tuning create payload and this module's own\n * truncation marker do not. Anything reading `messages`, `model` or the rest of\n * the chat shape off a journal entry — inside aimock or in a consumer's test\n * — goes through here, so an entry that is not a chat request fails as a\n * `false` it can assert on rather than as an undefined property three accesses\n * later.\n *\n * `messages` is the discriminator because it is the one required field no\n * other journaled shape carries.\n */\nexport function isChatCompletionBody(\n body: JournalBody | null | undefined,\n): body is ChatCompletionRequest {\n return (\n body !== null &&\n body !== undefined &&\n Array.isArray((body as { messages?: unknown }).messages) &&\n typeof (body as { model?: unknown }).model === \"string\"\n );\n}\n\n/**\n * Compare two field values, handling RegExp by source+flags rather than reference.\n */\nfunction fieldEqual(a: unknown, b: unknown): boolean {\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return a === b;\n}\n\n/**\n * Compare two systemMessage values. Handles string, string[], and RegExp.\n * Both-undefined is treated as equal.\n */\nfunction systemMessageEqual(\n a: string | string[] | RegExp | undefined,\n b: string | string[] | RegExp | undefined,\n): boolean {\n if (a === undefined && b === undefined) return true;\n if (a === undefined || b === undefined) return false;\n if (typeof a === \"string\" && typeof b === \"string\") return a === b;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i]);\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return false;\n}\n\n/**\n * Check whether two fixture match objects have the same criteria\n * (ignoring sequenceIndex). Used to group sequenced fixtures.\n */\nfunction matchCriteriaEqual(a: FixtureMatch, b: FixtureMatch): boolean {\n return (\n fieldEqual(a.userMessage, b.userMessage) &&\n systemMessageEqual(a.systemMessage, b.systemMessage) &&\n fieldEqual(a.inputText, b.inputText) &&\n fieldEqual(a.toolCallId, b.toolCallId) &&\n fieldEqual(a.toolName, b.toolName) &&\n fieldEqual(a.model, b.model) &&\n fieldEqual(a.responseFormat, b.responseFormat) &&\n fieldEqual(a.predicate, b.predicate) &&\n fieldEqual(a.endpoint, b.endpoint) &&\n fieldEqual(a.turnIndex, b.turnIndex) &&\n fieldEqual(a.hasToolResult, b.hasToolResult) &&\n fieldEqual(a.toolResultContains, b.toolResultContains) &&\n fieldEqual(a.context, b.context)\n );\n}\n\nexport interface JournalOptions {\n /**\n * Maximum number of entries to retain. When exceeded, oldest entries are\n * dropped FIFO. Set to 0 (or omit) for unbounded retention (the historical\n * default — suitable for short-lived test runs only). Negative values are\n * rejected at the CLI parse layer; programmatically they are treated as 0\n * (unbounded) for back-compat.\n *\n * Long-running servers (e.g. mock proxies in CI/demo environments) should\n * always set a finite cap: every request appends an entry holding the\n * request body + headers + fixture reference, and without a cap the\n * journal grows until the process OOMs.\n */\n maxEntries?: number;\n /**\n * Maximum number of unique testIds retained in the fixture match-count\n * map (`fixtureMatchCountsByTestId`). When exceeded, the oldest testId\n * (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for\n * unbounded retention. Negative values are rejected at the CLI parse\n * layer; programmatically they are treated as 0 (unbounded) for\n * back-compat. Without a cap this map can grow over time in long-running\n * servers that see many unique testIds.\n */\n fixtureCountsMaxTestIds?: number;\n /**\n * Called with every entry {@link Journal.add} creates, right after it is\n * recorded. The hook exists so an embedder can attribute an entry to the\n * request that produced it WITHOUT touching each of the ~100 `journal.add`\n * call sites spread across the handler modules: the server binds the entry\n * to the in-flight `IncomingMessage` here, and its error arm then amends\n * that exact object rather than guessing from a caller-supplied header.\n *\n * The entry is already recorded when the hook runs, so a hook that throws\n * does not lose the write — but it does propagate out of `add` into the\n * caller's error path, so a hook must not throw.\n */\n onAdd?: (entry: JournalEntry) => void;\n}\n\nexport class Journal {\n private entries: JournalEntry[] = [];\n private readonly matchedFixtures = new WeakMap<JournalEntry, Fixture>();\n private readonly fixtureMatchCountsByTestId: Map<string, Map<Fixture, number>> = new Map();\n private readonly maxEntries: number;\n private readonly fixtureCountsMaxTestIds: number;\n private readonly onAdd?: (entry: JournalEntry) => void;\n\n constructor(options: JournalOptions = {}) {\n this.onAdd = options.onAdd;\n // Treat 0 or negative as \"unbounded\" to preserve prior behavior when\n // the option is omitted or explicitly disabled.\n const cap = options.maxEntries;\n this.maxEntries = cap !== undefined && cap > 0 ? cap : 0;\n const testIdCap = options.fixtureCountsMaxTestIds;\n this.fixtureCountsMaxTestIds = testIdCap !== undefined && testIdCap > 0 ? testIdCap : 0;\n }\n\n /**\n * The per-test-id cap on fixture match-count maps, for an MCP mount to pass\n * to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`\n * meaning unbounded, and never throws, whatever option was passed:\n * omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above\n * `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more\n * is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values\n * it is the number of test ids the journal keeps.\n *\n * An option between 0 and 1 is the exception. The journal keeps no test id\n * (each new count map is evicted as soon as it is made, so counts never\n * advance), and a store cap cannot say \"keep none\" because `0` is\n * unbounded. The getter returns `1`, the smallest bounded cap, so a store\n * given it keeps 1 test id where the journal keeps 0.\n */\n get fixtureCountsMaxTestIdsCap(): number {\n const cap = this.fixtureCountsMaxTestIds;\n if (!(cap > 0) || cap > Number.MAX_SAFE_INTEGER) return 0;\n return Math.max(1, Math.floor(cap));\n }\n\n /** Backwards-compatible accessor — returns the default (no testId) count map. */\n get fixtureMatchCounts(): Map<Fixture, number> {\n return this.getFixtureMatchCountsForTest(DEFAULT_TEST_ID);\n }\n\n /** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */\n add(entry: Omit<JournalEntry, \"id\" | \"timestamp\">, matchedFixture?: Fixture): JournalEntry {\n const full: JournalEntry = {\n id: generateId(\"req\"),\n timestamp: Date.now(),\n ...entry,\n body: capBody(entry.body),\n };\n if (matchedFixture) this.matchedFixtures.set(full, matchedFixture);\n this.entries.push(full);\n // FIFO eviction when over capacity. Array.prototype.shift() is O(n)\n // regardless of how many we drop per add; we accept it at small caps\n // (default 1000) because the constant factor is tiny and this runs once\n // per request. For much larger caps, switch to a ring buffer for true\n // O(1) eviction.\n if (this.maxEntries > 0 && this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n this.onAdd?.(full);\n return full;\n }\n\n /**\n * Return every entry, or with `limit` the most recent `limit` entries.\n * `0` returns `[]` — exactly what `GET /__aimock/journal?limit=0` answers.\n * `slice(-0)` is `slice(0)`, so a `0` used to return the ENTIRE journal; it\n * is special-cased so the library and the HTTP route agree. This is a public\n * library API, so odd limits are tolerated rather than thrown on: a\n * non-finite limit (`NaN`, `Infinity`) means \"no limit\", a fractional limit\n * floors, and any limit at or below `0` asks for nothing.\n */\n getAll(opts?: { limit?: number }): JournalEntry[] {\n if (opts?.limit !== undefined && Number.isFinite(opts.limit)) {\n const limit = Math.floor(opts.limit);\n if (limit <= 0) return [];\n return this.entries.slice(-limit);\n }\n return this.entries.slice();\n }\n\n getLast(): JournalEntry | null {\n return this.entries.length > 0 ? this.entries[this.entries.length - 1] : null;\n }\n\n findByFixture(fixture: Fixture): JournalEntry[] {\n return this.entries.filter(\n (e) => (this.matchedFixtures.get(e) ?? e.response.fixture) === fixture,\n );\n }\n\n /**\n * READ-ONLY accessor. Returns the existing count map for `testId`, or an\n * empty transient Map if none exists. Does NOT insert into the cache and\n * does NOT trigger FIFO eviction — callers may read freely without\n * perturbing cache state. For the write path, see\n * `getOrCreateFixtureMatchCountsForTest`.\n */\n getFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n return this.fixtureMatchCountsByTestId.get(testId) ?? new Map();\n }\n\n /**\n * WRITE path: get the count map for `testId`, inserting a fresh empty Map\n * if missing and running FIFO eviction when the testId cap is exceeded.\n * Only callers that intend to mutate the map (e.g. incrementing a count)\n * should use this.\n */\n private getOrCreateFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n let counts = this.fixtureMatchCountsByTestId.get(testId);\n if (!counts) {\n counts = new Map();\n this.fixtureMatchCountsByTestId.set(testId, counts);\n // FIFO eviction when over capacity. JS Map preserves insertion order,\n // so the first key returned by keys() is the oldest. Same O(n) shift\n // caveat as `entries`: acceptable at small caps (createServer\n // default 500; a bare Journal is unbounded).\n if (\n this.fixtureCountsMaxTestIds > 0 &&\n this.fixtureMatchCountsByTestId.size > this.fixtureCountsMaxTestIds\n ) {\n const oldest = this.fixtureMatchCountsByTestId.keys().next().value;\n if (oldest !== undefined) {\n this.fixtureMatchCountsByTestId.delete(oldest);\n }\n }\n }\n return counts;\n }\n\n getFixtureMatchCount(fixture: Fixture, testId = DEFAULT_TEST_ID): number {\n return this.getFixtureMatchCountsForTest(testId).get(fixture) ?? 0;\n }\n\n incrementFixtureMatchCount(\n fixture: Fixture,\n allFixtures?: readonly Fixture[],\n testId = DEFAULT_TEST_ID,\n ): void {\n const counts = this.getOrCreateFixtureMatchCountsForTest(testId);\n counts.set(fixture, (counts.get(fixture) ?? 0) + 1);\n // When a sequenced fixture matches, also increment all siblings with matching criteria\n if (fixture.match.sequenceIndex !== undefined && allFixtures) {\n for (const sibling of allFixtures) {\n if (sibling === fixture) continue;\n if (sibling.match.sequenceIndex === undefined) continue;\n if (matchCriteriaEqual(fixture.match, sibling.match)) {\n counts.set(sibling, (counts.get(sibling) ?? 0) + 1);\n }\n }\n }\n }\n\n clearMatchCounts(testId?: string): void {\n if (testId !== undefined) {\n this.fixtureMatchCountsByTestId.delete(testId);\n } else {\n this.fixtureMatchCountsByTestId.clear();\n }\n }\n\n /**\n * Clear ONLY the request journal entries, preserving fixture match-counts.\n * Match-counts are fixture-matching/sequencing state, not journal data, so\n * clearing the journal must not silently rewind sequenced fixtures. Used by\n * `POST /__aimock/reset/journal`. For a full reset (entries + match-counts),\n * use `clear()` instead.\n */\n clearEntries(): void {\n this.entries = [];\n }\n\n clear(): void {\n this.entries = [];\n this.fixtureMatchCountsByTestId.clear();\n }\n\n get size(): number {\n return this.entries.length;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAM,yBAAyB,KAAK;;;;;;;;;;;AAYpC,SAAS,QAAQ,MAA8C;AAC7D,KAAI,SAAS,KAAM,QAAO;CAC1B,MAAM,aAAa,KAAK,UAAU,KAAK;AACvC,KAAI,OAAO,WAAW,YAAY,OAAO,IAAI,uBAAwB,QAAO;AAG5E,QAAO;EACL,oBAAoB;EACpB,kBAAkB,OAAO,WAAW,YAAY,OAAO;EACvD,MAAM;EACP;;;;;;;;;;;;;;;;AAiBH,SAAgB,qBACd,MAC+B;AAC/B,QACE,SAAS,QACT,SAAS,UACT,MAAM,QAAS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IAAI,OAAe;AACjB,SAAO,KAAK,QAAQ"}
|
|
1
|
+
{"version":3,"file":"journal.cjs","names":["DEFAULT_TEST_ID","generateId"],"sources":["../src/journal.ts"],"sourcesContent":["import { generateId } from \"./helpers.js\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureMatch,\n JournalBody,\n JournalEntry,\n MisbehaviorCounterKey,\n MisbehaviorCounters,\n} from \"./types.js\";\nimport { DEFAULT_TEST_ID } from \"./constants.js\";\nexport { DEFAULT_TEST_ID } from \"./constants.js\";\n\n/**\n * Maximum UTF-8 byte length of a serialized request body retained in a\n * journal entry. Bodies whose JSON serialization exceeds this byte size are\n * replaced with a truncation marker.\n *\n * Only the request `body` field is capped here. `headers` and `path` are\n * retained uncapped, but they are naturally bounded by Node's default ~16 KB\n * maximum HTTP header size, so the per-entry overhead beyond the body cap\n * remains small. Combined with the journal's maxEntries limit (default 1000),\n * the total `JSON.stringify(journal.getAll())` output stays well under V8's\n * ~512 MB string limit even at maximum capacity.\n */\nconst JOURNAL_BODY_CAP_BYTES = 64 * 1024; // 64 KB\n\n/**\n * If `body` serializes to more than JOURNAL_BODY_CAP_BYTES (in UTF-8 bytes),\n * replace it with a truncation marker. Returns the original body when within\n * the cap, or null when `body` is null.\n *\n * The gate uses Buffer.byteLength (UTF-8 bytes) rather than .length (UTF-16\n * code units) to match the constant name and to correctly cap multibyte\n * content (e.g. CJK/emoji) whose code-unit count falls under the threshold\n * but whose byte size does not.\n */\nfunction capBody(body: JournalBody | null): JournalBody | null {\n if (body === null) return null;\n const serialized = JSON.stringify(body);\n if (Buffer.byteLength(serialized, \"utf8\") <= JOURNAL_BODY_CAP_BYTES) return body;\n // The marker is not a chat request, and `JournalBody` no longer claims it is\n // — downstream consumers (e.g. GET /journal) treat the body as opaque JSON.\n return {\n __aimock_truncated: true,\n originalByteSize: Buffer.byteLength(serialized, \"utf8\"),\n note: \"body truncated by aimock journal cap (64 KB limit)\",\n };\n}\n\n/**\n * Narrow a journaled body to a chat-completion request.\n *\n * `JournalEntry.body` is a union (see {@link JournalBody}): most entries hold a\n * chat request, but the fine-tuning create payload and this module's own\n * truncation marker do not. Anything reading `messages`, `model` or the rest of\n * the chat shape off a journal entry — inside aimock or in a consumer's test\n * — goes through here, so an entry that is not a chat request fails as a\n * `false` it can assert on rather than as an undefined property three accesses\n * later.\n *\n * `messages` is the discriminator because it is the one required field no\n * other journaled shape carries.\n */\nexport function isChatCompletionBody(\n body: JournalBody | null | undefined,\n): body is ChatCompletionRequest {\n return (\n body !== null &&\n body !== undefined &&\n Array.isArray((body as { messages?: unknown }).messages) &&\n typeof (body as { model?: unknown }).model === \"string\"\n );\n}\n\n/**\n * Compare two field values, handling RegExp by source+flags rather than reference.\n */\nfunction fieldEqual(a: unknown, b: unknown): boolean {\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return a === b;\n}\n\n/**\n * Compare two systemMessage values. Handles string, string[], and RegExp.\n * Both-undefined is treated as equal.\n */\nfunction systemMessageEqual(\n a: string | string[] | RegExp | undefined,\n b: string | string[] | RegExp | undefined,\n): boolean {\n if (a === undefined && b === undefined) return true;\n if (a === undefined || b === undefined) return false;\n if (typeof a === \"string\" && typeof b === \"string\") return a === b;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i]);\n if (a instanceof RegExp && b instanceof RegExp)\n return a.source === b.source && a.flags === b.flags;\n return false;\n}\n\n/**\n * Check whether two fixture match objects have the same criteria\n * (ignoring sequenceIndex). Used to group sequenced fixtures.\n */\nfunction matchCriteriaEqual(a: FixtureMatch, b: FixtureMatch): boolean {\n return (\n fieldEqual(a.userMessage, b.userMessage) &&\n systemMessageEqual(a.systemMessage, b.systemMessage) &&\n fieldEqual(a.inputText, b.inputText) &&\n fieldEqual(a.toolCallId, b.toolCallId) &&\n fieldEqual(a.toolName, b.toolName) &&\n fieldEqual(a.toolNamespace, b.toolNamespace) &&\n fieldEqual(a.model, b.model) &&\n fieldEqual(a.responseFormat, b.responseFormat) &&\n fieldEqual(a.predicate, b.predicate) &&\n fieldEqual(a.endpoint, b.endpoint) &&\n fieldEqual(a.turnIndex, b.turnIndex) &&\n fieldEqual(a.hasToolResult, b.hasToolResult) &&\n fieldEqual(a.toolResultContains, b.toolResultContains) &&\n fieldEqual(a.context, b.context)\n );\n}\n\n/** Count-map keys resolve through `identity`, so every alias of a fixture finds its caller entry. */\nclass FixtureCountMap extends Map<Fixture, number> {\n constructor(private readonly identity: (fixture: Fixture) => Fixture) {\n super();\n }\n\n override get(key: Fixture): number | undefined {\n return super.get(this.identity(key));\n }\n\n override has(key: Fixture): boolean {\n return super.has(this.identity(key));\n }\n\n override set(key: Fixture, value: number): this {\n return super.set(this.identity(key), value);\n }\n\n override delete(key: Fixture): boolean {\n return super.delete(this.identity(key));\n }\n}\n\nexport interface JournalOptions {\n /**\n * Maximum number of entries to retain. When exceeded, oldest entries are\n * dropped FIFO. Set to 0 (or omit) for unbounded retention (the historical\n * default — suitable for short-lived test runs only). Negative values are\n * rejected at the CLI parse layer; programmatically they are treated as 0\n * (unbounded) for back-compat.\n *\n * Long-running servers (e.g. mock proxies in CI/demo environments) should\n * always set a finite cap: every request appends an entry holding the\n * request body + headers + fixture reference, and without a cap the\n * journal grows until the process OOMs.\n */\n maxEntries?: number;\n /**\n * Maximum number of unique testIds retained across fixture match-count\n * and misbehavior counters. When exceeded, the oldest testId\n * (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for\n * unbounded retention. Negative values are rejected at the CLI parse\n * layer; programmatically they are treated as 0 (unbounded) for\n * back-compat. Without a cap this map can grow over time in long-running\n * servers that see many unique testIds.\n */\n fixtureCountsMaxTestIds?: number;\n /**\n * Called with every entry {@link Journal.add} creates, right after it is\n * recorded. The hook exists so an embedder can attribute an entry to the\n * request that produced it WITHOUT touching each of the ~100 `journal.add`\n * call sites spread across the handler modules: the server binds the entry\n * to the in-flight `IncomingMessage` here, and its error arm then amends\n * that exact object rather than guessing from a caller-supplied header.\n *\n * The entry is already recorded when the hook runs, so a hook that throws\n * does not lose the write — but it does propagate out of `add` into the\n * caller's error path, so a hook must not throw.\n */\n onAdd?: (entry: JournalEntry) => void;\n}\n\nexport class Journal implements MisbehaviorCounters {\n private entries: JournalEntry[] = [];\n private readonly matchedFixtures = new WeakMap<JournalEntry, Fixture>();\n /** The fixture a request was served from, where the entry names its caller fixture instead. */\n private readonly servedFixtures = new WeakMap<JournalEntry, Fixture>();\n private readonly fixtureMatchCountsByTestId: Map<string, Map<Fixture, number>> = new Map();\n /** An extended server's view of a fixture to the caller's fixture (configureFixtureViewSource). */\n private fixtureViewSource = (fixture: Fixture): Fixture => fixture;\n private fixtureCountIdentity = (fixture: Fixture): Fixture => fixture;\n /** The key a fixture is counted under: the caller's object behind any view or copy. */\n private readonly fixtureCountKey = (fixture: Fixture): Fixture =>\n this.fixtureCountIdentity(this.fixtureViewSource(fixture));\n private createFixtureCountMap = (): Map<Fixture, number> => new Map();\n private fixtureCountIdentityConfigured = false;\n private fixtureViewSourceConfigured = false;\n private readonly counterTestIds = new Set<string>();\n private readonly misbehaviorCountersByTestId = new Map<\n string,\n Map<string, Map<number, { ordinal: number; firings: number }>>\n >();\n private readonly maxEntries: number;\n private readonly fixtureCountsMaxTestIds: number;\n private readonly onAdd?: (entry: JournalEntry) => void;\n\n constructor(options: JournalOptions = {}) {\n this.onAdd = options.onAdd;\n // Treat 0 or negative as \"unbounded\" to preserve prior behavior when\n // the option is omitted or explicitly disabled.\n const cap = options.maxEntries;\n this.maxEntries = cap !== undefined && cap > 0 ? cap : 0;\n const testIdCap = options.fixtureCountsMaxTestIds;\n this.fixtureCountsMaxTestIds = testIdCap !== undefined && testIdCap > 0 ? testIdCap : 0;\n }\n\n /**\n * The per-test-id cap on fixture match-count maps, for an MCP mount to pass\n * to `McpFakeStore.setMaxTestIds`. Always a non-negative safe integer, `0`\n * meaning unbounded, and never throws, whatever option was passed:\n * omitted, zero, negative or `NaN` is `0`; `Infinity` or a value above\n * `Number.MAX_SAFE_INTEGER` (never reached) is `0`; a fraction of 1 or more\n * is rounded down (`1.5` evicts at 2 ids, so it keeps 1). For these values\n * it is the number of test ids the journal keeps.\n *\n * An option between 0 and 1 is the exception. The journal keeps no test id\n * (each new count map is evicted as soon as it is made, so counts never\n * advance), and a store cap cannot say \"keep none\" because `0` is\n * unbounded. The getter returns `1`, the smallest bounded cap, so a store\n * given it keeps 1 test id where the journal keeps 0.\n */\n get fixtureCountsMaxTestIdsCap(): number {\n const cap = this.fixtureCountsMaxTestIds;\n if (!(cap > 0) || cap > Number.MAX_SAFE_INTEGER) return 0;\n return Math.max(1, Math.floor(cap));\n }\n\n /** Backwards-compatible accessor — returns the default (no testId) count map. */\n get fixtureMatchCounts(): Map<Fixture, number> {\n return this.getFixtureMatchCountsForTest(DEFAULT_TEST_ID);\n }\n\n /** @internal matchedFixture preserves identity when Live supplies safe diagnostics. */\n add(entry: Omit<JournalEntry, \"id\" | \"timestamp\">, matchedFixture?: Fixture): JournalEntry {\n const full: JournalEntry = {\n id: generateId(\"req\"),\n timestamp: Date.now(),\n ...entry,\n body: capBody(entry.body),\n };\n // A request is served from an extended server's view of a fixture, or\n // from LLMock's per-addition copy with misbehavior enabled; the entry\n // names the caller's fixture behind it, as in 1.44.0.\n const fixture = full.response.fixture;\n const source = fixture ? this.fixtureCountKey(fixture) : fixture;\n if (fixture && source !== fixture) {\n full.response = { ...full.response, fixture: source };\n this.servedFixtures.set(full, fixture);\n }\n if (matchedFixture) this.matchedFixtures.set(full, this.fixtureCountKey(matchedFixture));\n this.entries.push(full);\n // FIFO eviction when over capacity. Array.prototype.shift() is O(n)\n // regardless of how many we drop per add; we accept it at small caps\n // (default 1000) because the constant factor is tiny and this runs once\n // per request. For much larger caps, switch to a ring buffer for true\n // O(1) eviction.\n if (this.maxEntries > 0 && this.entries.length > this.maxEntries) {\n this.entries.shift();\n }\n this.onAdd?.(full);\n return full;\n }\n\n /**\n * Return every entry, or with `limit` the most recent `limit` entries.\n * `0` returns `[]` — exactly what `GET /__aimock/journal?limit=0` answers.\n * `slice(-0)` is `slice(0)`, so a `0` used to return the ENTIRE journal; it\n * is special-cased so the library and the HTTP route agree. This is a public\n * library API, so odd limits are tolerated rather than thrown on: a\n * non-finite limit (`NaN`, `Infinity`) means \"no limit\", a fractional limit\n * floors, and any limit at or below `0` asks for nothing.\n */\n getAll(opts?: { limit?: number }): JournalEntry[] {\n if (opts?.limit !== undefined && Number.isFinite(opts.limit)) {\n const limit = Math.floor(opts.limit);\n if (limit <= 0) return [];\n return this.entries.slice(-limit);\n }\n return this.entries.slice();\n }\n\n getLast(): JournalEntry | null {\n return this.entries.length > 0 ? this.entries[this.entries.length - 1] : null;\n }\n\n findByFixture(fixture: Fixture): JournalEntry[] {\n const key = this.fixtureCountKey(fixture);\n return this.entries.filter((e) => (this.matchedFixtures.get(e) ?? e.response.fixture) === key);\n }\n\n /**\n * @internal The fixture `entry`'s request was served from: the extended\n * view or the per-addition copy when the entry names the caller's fixture\n * behind it, otherwise `entry.response.fixture`. The journal JSON shows it.\n */\n servedFixture(entry: JournalEntry): Fixture | null {\n return this.servedFixtures.get(entry) ?? entry.response.fixture;\n }\n\n /**\n * READ-ONLY accessor. Returns the existing count map for `testId`, or an\n * empty transient Map if none exists. Does NOT insert into the cache and\n * does NOT trigger FIFO eviction — callers may read freely without\n * perturbing cache state. For the write path, see\n * `getOrCreateFixtureMatchCountsForTest`.\n */\n getFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n return this.fixtureMatchCountsByTestId.get(testId) ?? this.createFixtureCountMap();\n }\n\n /**\n * WRITE path: get the count map for `testId`, inserting a fresh empty Map\n * if missing and running FIFO eviction when the testId cap is exceeded.\n * Only callers that intend to mutate the map (e.g. incrementing a count)\n * should use this.\n */\n private getOrCreateFixtureMatchCountsForTest(testId: string): Map<Fixture, number> {\n let counts = this.fixtureMatchCountsByTestId.get(testId);\n if (!counts) {\n counts = this.createFixtureCountMap();\n this.fixtureMatchCountsByTestId.set(testId, counts);\n this.admitCounterTestId(testId);\n }\n return counts;\n }\n\n /** Match and fault mutations share one admission order and capacity. */\n private admitCounterTestId(testId: string): void {\n this.counterTestIds.add(testId);\n if (\n this.fixtureCountsMaxTestIds > 0 &&\n this.counterTestIds.size > this.fixtureCountsMaxTestIds\n ) {\n const oldest = this.counterTestIds.values().next().value;\n if (oldest !== undefined) {\n this.counterTestIds.delete(oldest);\n this.fixtureMatchCountsByTestId.delete(oldest);\n this.misbehaviorCountersByTestId.delete(oldest);\n }\n }\n }\n\n private getOrCreateMisbehaviorCounter(key: MisbehaviorCounterKey) {\n let sources = this.misbehaviorCountersByTestId.get(key.testId);\n if (!sources) {\n sources = new Map();\n this.misbehaviorCountersByTestId.set(key.testId, sources);\n this.admitCounterTestId(key.testId);\n }\n let entries = sources.get(key.sourceKey);\n if (!entries) {\n entries = new Map();\n sources.set(key.sourceKey, entries);\n }\n let counter = entries.get(key.entryIndex);\n if (!counter) {\n counter = { ordinal: 0, firings: 0 };\n entries.set(key.entryIndex, counter);\n }\n return counter;\n }\n\n getFiringCount(key: MisbehaviorCounterKey): number {\n return (\n this.misbehaviorCountersByTestId.get(key.testId)?.get(key.sourceKey)?.get(key.entryIndex)\n ?.firings ?? 0\n );\n }\n\n nextOrdinal(key: MisbehaviorCounterKey): number {\n return this.getOrCreateMisbehaviorCounter(key).ordinal++;\n }\n\n recordFiring(key: MisbehaviorCounterKey): void {\n this.getOrCreateMisbehaviorCounter(key).firings++;\n }\n\n clearMisbehaviorCounters(testId?: string): void {\n if (testId !== undefined) {\n this.misbehaviorCountersByTestId.delete(testId);\n if (!this.fixtureMatchCountsByTestId.has(testId)) this.counterTestIds.delete(testId);\n } else {\n this.misbehaviorCountersByTestId.clear();\n for (const id of this.counterTestIds) {\n if (!this.fixtureMatchCountsByTestId.has(id)) this.counterTestIds.delete(id);\n }\n }\n }\n\n /** @internal LLMock configures caller count identity before serving requests. */\n configureFixtureCountIdentity(identity: (fixture: Fixture) => Fixture): void {\n if (this.fixtureCountIdentityConfigured || this.fixtureMatchCountsByTestId.size > 0) {\n throw new Error(\"Fixture count identity must be configured once before counting\");\n }\n this.fixtureCountIdentity = identity;\n this.createFixtureCountMap = () => new FixtureCountMap(this.fixtureCountKey);\n this.fixtureCountIdentityConfigured = true;\n }\n\n /**\n * @internal A server with `responsesTools: \"extended\"` matches each fixture\n * through its extended view. `source` maps a view back to the caller's\n * fixture, so counts, `findByFixture` and `JournalEntry.response.fixture`\n * keep the caller's object. Configured once, before counting.\n */\n configureFixtureViewSource(source: (fixture: Fixture) => Fixture): void {\n if (this.fixtureViewSourceConfigured || this.fixtureMatchCountsByTestId.size > 0) {\n throw new Error(\"Fixture view source must be configured once before counting\");\n }\n this.fixtureViewSource = source;\n this.createFixtureCountMap = () => new FixtureCountMap(this.fixtureCountKey);\n this.fixtureViewSourceConfigured = true;\n }\n\n getFixtureMatchCount(fixture: Fixture, testId = DEFAULT_TEST_ID): number {\n return this.getFixtureMatchCountsForTest(testId).get(fixture) ?? 0;\n }\n\n incrementFixtureMatchCount(\n fixture: Fixture,\n allFixtures?: readonly Fixture[],\n testId = DEFAULT_TEST_ID,\n ): void {\n const counts = this.getOrCreateFixtureMatchCountsForTest(testId);\n counts.set(fixture, (counts.get(fixture) ?? 0) + 1);\n // When a sequenced fixture matches, also increment all siblings with matching criteria\n if (fixture.match.sequenceIndex !== undefined && allFixtures) {\n for (const sibling of allFixtures) {\n if (this.fixtureCountKey(sibling) === this.fixtureCountKey(fixture)) continue;\n if (sibling.match.sequenceIndex === undefined) continue;\n if (matchCriteriaEqual(fixture.match, sibling.match)) {\n counts.set(sibling, (counts.get(sibling) ?? 0) + 1);\n }\n }\n }\n }\n\n clearMatchCounts(testId?: string): void {\n if (testId !== undefined) {\n this.fixtureMatchCountsByTestId.delete(testId);\n this.clearMisbehaviorCounters(testId);\n } else {\n this.fixtureMatchCountsByTestId.clear();\n this.clearMisbehaviorCounters();\n }\n }\n\n /**\n * Clear ONLY the request journal entries, preserving fixture match-counts.\n * Match-counts are fixture-matching/sequencing state, not journal data, so\n * clearing the journal must not silently rewind sequenced fixtures. Used by\n * `POST /__aimock/reset/journal`. For a full reset (entries + match-counts),\n * use `clear()` instead.\n */\n clearEntries(): void {\n this.entries = [];\n }\n\n clear(): void {\n this.entries = [];\n this.clearMatchCounts();\n }\n\n get size(): number {\n return this.entries.length;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,MAAM,yBAAyB,KAAK;;;;;;;;;;;AAYpC,SAAS,QAAQ,MAA8C;AAC7D,KAAI,SAAS,KAAM,QAAO;CAC1B,MAAM,aAAa,KAAK,UAAU,KAAK;AACvC,KAAI,OAAO,WAAW,YAAY,OAAO,IAAI,uBAAwB,QAAO;AAG5E,QAAO;EACL,oBAAoB;EACpB,kBAAkB,OAAO,WAAW,YAAY,OAAO;EACvD,MAAM;EACP;;;;;;;;;;;;;;;;AAiBH,SAAgB,qBACd,MAC+B;AAC/B,QACE,SAAS,QACT,SAAS,UACT,MAAM,QAAS,KAAgC,SAAS,IACxD,OAAQ,KAA6B,UAAU;;;;;AAOnD,SAAS,WAAW,GAAY,GAAqB;AACnD,KAAI,aAAa,UAAU,aAAa,OACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE;AAChD,QAAO,MAAM;;;;;;AAOf,SAAS,mBACP,GACA,GACS;AACT,KAAI,MAAM,UAAa,MAAM,OAAW,QAAO;AAC/C,KAAI,MAAM,UAAa,MAAM,OAAW,QAAO;AAC/C,KAAI,OAAO,MAAM,YAAY,OAAO,MAAM,SAAU,QAAO,MAAM;AACjE,KAAI,MAAM,QAAQ,EAAE,IAAI,MAAM,QAAQ,EAAE,CACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,GAAG,MAAM,MAAM,EAAE,GAAG;AAC/D,KAAI,aAAa,UAAU,aAAa,OACtC,QAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE;AAChD,QAAO;;;;;;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AA6C;AACtE,MAAI,KAAK,+BAA+B,KAAK,2BAA2B,OAAO,EAC7E,OAAM,IAAI,MAAM,8DAA8D;AAEhF,OAAK,oBAAoB;AACzB,OAAK,8BAA8B,IAAI,gBAAgB,KAAK,gBAAgB;AAC5E,OAAK,8BAA8B;;CAGrC,qBAAqB,SAAkB,SAASD,mCAAyB;AACvE,SAAO,KAAK,6BAA6B,OAAO,CAAC,IAAI,QAAQ,IAAI;;CAGnE,2BACE,SACA,aACA,SAASA,mCACH;EACN,MAAM,SAAS,KAAK,qCAAqC,OAAO;AAChE,SAAO,IAAI,UAAU,OAAO,IAAI,QAAQ,IAAI,KAAK,EAAE;AAEnD,MAAI,QAAQ,MAAM,kBAAkB,UAAa,YAC/C,MAAK,MAAM,WAAW,aAAa;AACjC,OAAI,KAAK,gBAAgB,QAAQ,KAAK,KAAK,gBAAgB,QAAQ,CAAE;AACrE,OAAI,QAAQ,MAAM,kBAAkB,OAAW;AAC/C,OAAI,mBAAmB,QAAQ,OAAO,QAAQ,MAAM,CAClD,QAAO,IAAI,UAAU,OAAO,IAAI,QAAQ,IAAI,KAAK,EAAE;;;CAM3D,iBAAiB,QAAuB;AACtC,MAAI,WAAW,QAAW;AACxB,QAAK,2BAA2B,OAAO,OAAO;AAC9C,QAAK,yBAAyB,OAAO;SAChC;AACL,QAAK,2BAA2B,OAAO;AACvC,QAAK,0BAA0B;;;;;;;;;;CAWnC,eAAqB;AACnB,OAAK,UAAU,EAAE;;CAGnB,QAAc;AACZ,OAAK,UAAU,EAAE;AACjB,OAAK,kBAAkB;;CAGzB,IAAI,OAAe;AACjB,SAAO,KAAK,QAAQ"}
|
package/dist/journal.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DEFAULT_TEST_ID } from "./constants.cjs";
|
|
2
|
-
import { ChatCompletionRequest, Fixture, JournalBody, JournalEntry } from "./types.cjs";
|
|
2
|
+
import { ChatCompletionRequest, Fixture, JournalBody, JournalEntry, MisbehaviorCounterKey, MisbehaviorCounters } from "./types.cjs";
|
|
3
3
|
|
|
4
4
|
//#region src/journal.d.ts
|
|
5
5
|
|
|
@@ -33,8 +33,8 @@ interface JournalOptions {
|
|
|
33
33
|
*/
|
|
34
34
|
maxEntries?: number;
|
|
35
35
|
/**
|
|
36
|
-
* Maximum number of unique testIds retained
|
|
37
|
-
*
|
|
36
|
+
* Maximum number of unique testIds retained across fixture match-count
|
|
37
|
+
* and misbehavior counters. When exceeded, the oldest testId
|
|
38
38
|
* (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for
|
|
39
39
|
* unbounded retention. Negative values are rejected at the CLI parse
|
|
40
40
|
* layer; programmatically they are treated as 0 (unbounded) for
|
|
@@ -56,10 +56,22 @@ interface JournalOptions {
|
|
|
56
56
|
*/
|
|
57
57
|
onAdd?: (entry: JournalEntry) => void;
|
|
58
58
|
}
|
|
59
|
-
declare class Journal {
|
|
59
|
+
declare class Journal implements MisbehaviorCounters {
|
|
60
60
|
private entries;
|
|
61
61
|
private readonly matchedFixtures;
|
|
62
|
+
/** The fixture a request was served from, where the entry names its caller fixture instead. */
|
|
63
|
+
private readonly servedFixtures;
|
|
62
64
|
private readonly fixtureMatchCountsByTestId;
|
|
65
|
+
/** An extended server's view of a fixture to the caller's fixture (configureFixtureViewSource). */
|
|
66
|
+
private fixtureViewSource;
|
|
67
|
+
private fixtureCountIdentity;
|
|
68
|
+
/** The key a fixture is counted under: the caller's object behind any view or copy. */
|
|
69
|
+
private readonly fixtureCountKey;
|
|
70
|
+
private createFixtureCountMap;
|
|
71
|
+
private fixtureCountIdentityConfigured;
|
|
72
|
+
private fixtureViewSourceConfigured;
|
|
73
|
+
private readonly counterTestIds;
|
|
74
|
+
private readonly misbehaviorCountersByTestId;
|
|
63
75
|
private readonly maxEntries;
|
|
64
76
|
private readonly fixtureCountsMaxTestIds;
|
|
65
77
|
private readonly onAdd?;
|
|
@@ -98,6 +110,12 @@ declare class Journal {
|
|
|
98
110
|
}): JournalEntry[];
|
|
99
111
|
getLast(): JournalEntry | null;
|
|
100
112
|
findByFixture(fixture: Fixture): JournalEntry[];
|
|
113
|
+
/**
|
|
114
|
+
* @internal The fixture `entry`'s request was served from: the extended
|
|
115
|
+
* view or the per-addition copy when the entry names the caller's fixture
|
|
116
|
+
* behind it, otherwise `entry.response.fixture`. The journal JSON shows it.
|
|
117
|
+
*/
|
|
118
|
+
servedFixture(entry: JournalEntry): Fixture | null;
|
|
101
119
|
/**
|
|
102
120
|
* READ-ONLY accessor. Returns the existing count map for `testId`, or an
|
|
103
121
|
* empty transient Map if none exists. Does NOT insert into the cache and
|
|
@@ -113,6 +131,22 @@ declare class Journal {
|
|
|
113
131
|
* should use this.
|
|
114
132
|
*/
|
|
115
133
|
private getOrCreateFixtureMatchCountsForTest;
|
|
134
|
+
/** Match and fault mutations share one admission order and capacity. */
|
|
135
|
+
private admitCounterTestId;
|
|
136
|
+
private getOrCreateMisbehaviorCounter;
|
|
137
|
+
getFiringCount(key: MisbehaviorCounterKey): number;
|
|
138
|
+
nextOrdinal(key: MisbehaviorCounterKey): number;
|
|
139
|
+
recordFiring(key: MisbehaviorCounterKey): void;
|
|
140
|
+
clearMisbehaviorCounters(testId?: string): void;
|
|
141
|
+
/** @internal LLMock configures caller count identity before serving requests. */
|
|
142
|
+
configureFixtureCountIdentity(identity: (fixture: Fixture) => Fixture): void;
|
|
143
|
+
/**
|
|
144
|
+
* @internal A server with `responsesTools: "extended"` matches each fixture
|
|
145
|
+
* through its extended view. `source` maps a view back to the caller's
|
|
146
|
+
* fixture, so counts, `findByFixture` and `JournalEntry.response.fixture`
|
|
147
|
+
* keep the caller's object. Configured once, before counting.
|
|
148
|
+
*/
|
|
149
|
+
configureFixtureViewSource(source: (fixture: Fixture) => Fixture): void;
|
|
116
150
|
getFixtureMatchCount(fixture: Fixture, testId?: string): number;
|
|
117
151
|
incrementFixtureMatchCount(fixture: Fixture, allFixtures?: readonly Fixture[], testId?: string): void;
|
|
118
152
|
clearMatchCounts(testId?: string): void;
|
package/dist/journal.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.d.cts","names":[],"sources":["../src/journal.ts"],"sourcesContent":[],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"journal.d.cts","names":[],"sources":["../src/journal.ts"],"sourcesContent":[],"mappings":";;;;;;;AAgEA;;;;;AAoFA;AAuCA;;;;;;AA6Da,iBAxLG,oBAAA,CAwLH,IAAA,EAvLL,WAuLK,GAAA,IAAA,GAAA,SAAA,CAAA,EAAA,IAAA,IAtLF,qBAsLE;AAAyD,UApGrD,cAAA,CAoGqD;;;;;;;;;;;;;YA6JlB,CAAA,EAAA,MAAA;;;;;;;;;;;;;;;;;;;;;;;kBA7NlC;;cAGL,OAAA,YAAmB;;;;;;;;;;;;;;;;;;;wBAwBT;;;;;;;;;;;;;;;;;;4BAgCK,IAAI;;aAKnB,KAAK,oDAAoD,UAAU;;;;;;;;;;;;MAuC3C;aASxB;yBAIY,UAAU;;;;;;uBAUZ,eAAe;;;;;;;;gDAWU,IAAI;;;;;;;;;;;sBAwD9B;mBAOH;oBAIC;;;oDAiBgC,YAAY;;;;;;;+CAejB,YAAY;gCAS3B;sCAKnB,gCACc"}
|
package/dist/journal.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DEFAULT_TEST_ID } from "./constants.js";
|
|
2
|
-
import { ChatCompletionRequest, Fixture, JournalBody, JournalEntry } from "./types.js";
|
|
2
|
+
import { ChatCompletionRequest, Fixture, JournalBody, JournalEntry, MisbehaviorCounterKey, MisbehaviorCounters } from "./types.js";
|
|
3
3
|
|
|
4
4
|
//#region src/journal.d.ts
|
|
5
5
|
|
|
@@ -33,8 +33,8 @@ interface JournalOptions {
|
|
|
33
33
|
*/
|
|
34
34
|
maxEntries?: number;
|
|
35
35
|
/**
|
|
36
|
-
* Maximum number of unique testIds retained
|
|
37
|
-
*
|
|
36
|
+
* Maximum number of unique testIds retained across fixture match-count
|
|
37
|
+
* and misbehavior counters. When exceeded, the oldest testId
|
|
38
38
|
* (by first-insertion order) is evicted FIFO. Set to 0 (or omit) for
|
|
39
39
|
* unbounded retention. Negative values are rejected at the CLI parse
|
|
40
40
|
* layer; programmatically they are treated as 0 (unbounded) for
|
|
@@ -56,10 +56,22 @@ interface JournalOptions {
|
|
|
56
56
|
*/
|
|
57
57
|
onAdd?: (entry: JournalEntry) => void;
|
|
58
58
|
}
|
|
59
|
-
declare class Journal {
|
|
59
|
+
declare class Journal implements MisbehaviorCounters {
|
|
60
60
|
private entries;
|
|
61
61
|
private readonly matchedFixtures;
|
|
62
|
+
/** The fixture a request was served from, where the entry names its caller fixture instead. */
|
|
63
|
+
private readonly servedFixtures;
|
|
62
64
|
private readonly fixtureMatchCountsByTestId;
|
|
65
|
+
/** An extended server's view of a fixture to the caller's fixture (configureFixtureViewSource). */
|
|
66
|
+
private fixtureViewSource;
|
|
67
|
+
private fixtureCountIdentity;
|
|
68
|
+
/** The key a fixture is counted under: the caller's object behind any view or copy. */
|
|
69
|
+
private readonly fixtureCountKey;
|
|
70
|
+
private createFixtureCountMap;
|
|
71
|
+
private fixtureCountIdentityConfigured;
|
|
72
|
+
private fixtureViewSourceConfigured;
|
|
73
|
+
private readonly counterTestIds;
|
|
74
|
+
private readonly misbehaviorCountersByTestId;
|
|
63
75
|
private readonly maxEntries;
|
|
64
76
|
private readonly fixtureCountsMaxTestIds;
|
|
65
77
|
private readonly onAdd?;
|
|
@@ -98,6 +110,12 @@ declare class Journal {
|
|
|
98
110
|
}): JournalEntry[];
|
|
99
111
|
getLast(): JournalEntry | null;
|
|
100
112
|
findByFixture(fixture: Fixture): JournalEntry[];
|
|
113
|
+
/**
|
|
114
|
+
* @internal The fixture `entry`'s request was served from: the extended
|
|
115
|
+
* view or the per-addition copy when the entry names the caller's fixture
|
|
116
|
+
* behind it, otherwise `entry.response.fixture`. The journal JSON shows it.
|
|
117
|
+
*/
|
|
118
|
+
servedFixture(entry: JournalEntry): Fixture | null;
|
|
101
119
|
/**
|
|
102
120
|
* READ-ONLY accessor. Returns the existing count map for `testId`, or an
|
|
103
121
|
* empty transient Map if none exists. Does NOT insert into the cache and
|
|
@@ -113,6 +131,22 @@ declare class Journal {
|
|
|
113
131
|
* should use this.
|
|
114
132
|
*/
|
|
115
133
|
private getOrCreateFixtureMatchCountsForTest;
|
|
134
|
+
/** Match and fault mutations share one admission order and capacity. */
|
|
135
|
+
private admitCounterTestId;
|
|
136
|
+
private getOrCreateMisbehaviorCounter;
|
|
137
|
+
getFiringCount(key: MisbehaviorCounterKey): number;
|
|
138
|
+
nextOrdinal(key: MisbehaviorCounterKey): number;
|
|
139
|
+
recordFiring(key: MisbehaviorCounterKey): void;
|
|
140
|
+
clearMisbehaviorCounters(testId?: string): void;
|
|
141
|
+
/** @internal LLMock configures caller count identity before serving requests. */
|
|
142
|
+
configureFixtureCountIdentity(identity: (fixture: Fixture) => Fixture): void;
|
|
143
|
+
/**
|
|
144
|
+
* @internal A server with `responsesTools: "extended"` matches each fixture
|
|
145
|
+
* through its extended view. `source` maps a view back to the caller's
|
|
146
|
+
* fixture, so counts, `findByFixture` and `JournalEntry.response.fixture`
|
|
147
|
+
* keep the caller's object. Configured once, before counting.
|
|
148
|
+
*/
|
|
149
|
+
configureFixtureViewSource(source: (fixture: Fixture) => Fixture): void;
|
|
116
150
|
getFixtureMatchCount(fixture: Fixture, testId?: string): number;
|
|
117
151
|
incrementFixtureMatchCount(fixture: Fixture, allFixtures?: readonly Fixture[], testId?: string): void;
|
|
118
152
|
clearMatchCounts(testId?: string): void;
|
package/dist/journal.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.d.ts","names":[],"sources":["../src/journal.ts"],"sourcesContent":[],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"journal.d.ts","names":[],"sources":["../src/journal.ts"],"sourcesContent":[],"mappings":";;;;;;;AAgEA;;;;;AAoFA;AAuCA;;;;;;AA6Da,iBAxLG,oBAAA,CAwLH,IAAA,EAvLL,WAuLK,GAAA,IAAA,GAAA,SAAA,CAAA,EAAA,IAAA,IAtLF,qBAsLE;AAAyD,UApGrD,cAAA,CAoGqD;;;;;;;;;;;;;YA6JlB,CAAA,EAAA,MAAA;;;;;;;;;;;;;;;;;;;;;;;kBA7NlC;;cAGL,OAAA,YAAmB;;;;;;;;;;;;;;;;;;;wBAwBT;;;;;;;;;;;;;;;;;;4BAgCK,IAAI;;aAKnB,KAAK,oDAAoD,UAAU;;;;;;;;;;;;MAuC3C;aASxB;yBAIY,UAAU;;;;;;uBAUZ,eAAe;;;;;;;;gDAWU,IAAI;;;;;;;;;;;sBAwD9B;mBAOH;oBAIC;;;oDAiBgC,YAAY;;;;;;;+CAejB,YAAY;gCAS3B;sCAKnB,gCACc"}
|