vitest-spock 0.6.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -3
- package/dist/adapters.d.ts +84 -0
- package/dist/adapters.js +272 -0
- package/dist/adapters.js.map +1 -0
- package/dist/auto.d.ts +39 -0
- package/dist/auto.js +63 -0
- package/dist/auto.js.map +1 -0
- package/dist/cloudflare/emitter.d.ts +23 -0
- package/dist/cloudflare/emitter.js +32 -0
- package/dist/cloudflare/emitter.js.map +1 -1
- package/dist/coverage.d.ts +10 -0
- package/dist/coverage.js +169 -0
- package/dist/coverage.js.map +1 -0
- package/dist/format.js +5 -0
- package/dist/format.js.map +1 -1
- package/dist/index.d.ts +7 -2
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/matcher.js +33 -0
- package/dist/matcher.js.map +1 -1
- package/dist/node/binary.d.ts +1 -1
- package/dist/node/binary.js +31 -10
- package/dist/node/binary.js.map +1 -1
- package/dist/node/plugin.d.ts +28 -4
- package/dist/node/plugin.js +53 -2
- package/dist/node/plugin.js.map +1 -1
- package/dist/trace.d.ts +7 -1
- package/dist/trace.js +43 -2
- package/dist/trace.js.map +1 -1
- package/dist/types.d.ts +65 -0
- package/dist/types.js.map +1 -1
- package/package.json +12 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"emitter.js","sourceRoot":"","sources":["../../src/cloudflare/emitter.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"emitter.js","sourceRoot":"","sources":["../../src/cloudflare/emitter.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,eAAe,GAIhB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD,iFAAiF;AACjF,MAAM,CAAC,MAAM,qBAAqB,GAAG,aAAa,CAAC;AAWnD,SAAS,UAAU,CACjB,GAAkD,EAClD,OAAe;IAE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;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,MAAkC,EAClC,GAAkD,EAClD,OAA6C;IAE7C,MAAM,OAAO,GAAG,OAAO,EAAE,OAAO,IAAI,qBAAqB,CAAC;IAC1D,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACzC,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,CAAC,CAAC;IAEpC,MAAM,OAAO,GAAG,OAAO,EAAE,OAAO,IAAI,SAAS,CAAC;IAC9C,MAAM,KAAK,GAAG,eAAe,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,mBAAmB,CAAC,CAAC,KAAK,EAAE,CAAC;IACtF,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;IACD,OAAO,KAAK,CAAC,MAAM,CAAC;AACtB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAA6C;IAI7C,OAAO;QACL,KAAK,CAAC,IAAI,CACR,MAAkC,EAClC,GAAuC;YAEvC,MAAM,kBAAkB,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;QACjD,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n defaultRecordMapper,\n fromWorkersTail,\n type LogRecord,\n type RecordMapper,\n type WorkersTailItem,\n} from \"../adapters.js\";\nimport { validateTraceLine } from \"../trace.js\";\nimport type { TraceArgs, TraceLine, TraceState } from \"../types.js\";\n\n/** Default Cloudflare service binding name used by `vitest-spock/cloudflare`. */\nexport const DEFAULT_SPOCK_BINDING = \"SPOCK_TRACE\";\n\n/** Minimal Fetcher interface satisfied by Cloudflare service bindings (`env.SPOCK_TRACE`). */\nexport interface SpockServiceFetcher {\n fetch(input: string, init?: { method?: string; headers?: Record<string, string>; body?: string }): Promise<{\n ok: boolean;\n status: number;\n text(): Promise<string>;\n }>;\n}\n\nfunction getFetcher(\n env: Readonly<Record<string, unknown>> | undefined,\n binding: string,\n): SpockServiceFetcher | undefined {\n if (env === undefined) return undefined;\n const candidate = env[binding];\n if (\n typeof candidate === \"object\" &&\n candidate !== null &&\n \"fetch\" in candidate &&\n typeof (candidate as { fetch?: unknown }).fetch === \"function\"\n ) {\n return candidate as SpockServiceFetcher;\n }\n return undefined;\n}\n\n/**\n * Emit a single `TraceLine` from inside a Cloudflare Worker or Durable Object to the test host.\n *\n * In production (when `env.SPOCK_TRACE` is unbound), this is an immediate no-op with zero\n * network or serialization cost.\n */\nexport async function emitSpock(\n env: Readonly<Record<string, unknown>> | undefined,\n session: string,\n line: TraceLine,\n binding: string = DEFAULT_SPOCK_BINDING,\n): Promise<void> {\n const fetcher = getFetcher(env, binding);\n if (fetcher === undefined) return;\n validateTraceLine(line);\n await fetcher.fetch(\"https://spock.internal/emit\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ session, line }),\n });\n}\n\n/** Zero-cost-in-production trace emitter bound to a Cloudflare Worker / Durable Object `env`. */\nexport interface TraceSink {\n /** `true` when the `SPOCK_TRACE` test binding is present on `env`; `false` in production. */\n readonly enabled: boolean;\n init(state: TraceState): Promise<void>;\n step(\n action: string,\n argsOrState?: TraceArgs | TraceState | undefined,\n state?: TraceState | undefined,\n ): Promise<void>;\n saw(state: TraceState): Promise<void>;\n emit(line: TraceLine): Promise<void>;\n}\n\nconst NOOP_SINK: TraceSink = {\n enabled: false,\n async init() {},\n async step() {},\n async saw() {},\n async emit() {},\n};\n\n/**\n * Create a trace sink for a Cloudflare Worker or Durable Object.\n *\n * Returns a shared frozen no-op sink when `env[binding]` is absent (production), so\n * instrumenting DO methods or alarms has zero runtime overhead in deployed Workers.\n */\nexport function createTraceSink(\n env: Readonly<Record<string, unknown>> | undefined,\n session: string,\n binding: string = DEFAULT_SPOCK_BINDING,\n): TraceSink {\n const fetcher = getFetcher(env, binding);\n if (fetcher === undefined) return NOOP_SINK;\n\n const send = async (line: TraceLine): Promise<void> => {\n validateTraceLine(line);\n await fetcher.fetch(\"https://spock.internal/emit\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ session, line }),\n });\n };\n\n return {\n enabled: true,\n init(state) {\n return send({ state });\n },\n step(action, argsOrState, state) {\n if (argsOrState === undefined) {\n return send(state === undefined ? { action } : { action, state });\n }\n if (Array.isArray(argsOrState)) {\n return send(\n state === undefined\n ? { action, args: argsOrState }\n : { action, args: argsOrState, state },\n );\n }\n return send({ action, state: argsOrState as TraceState });\n },\n saw(state) {\n return send({ state });\n },\n emit(line) {\n return send(line);\n },\n };\n}\n\n/** Options for [`forwardWorkersTail`] and [`createSpockTailHandler`]. */\nexport type SpockTailHandlerOptions = Readonly<{\n /** Host trace session name (`startSpockSession(session)`). Defaults to `\"default\"`. */\n session?: string | undefined;\n /** Service binding name (`spockServiceBinding(...)`). Defaults to `\"SPOCK_TRACE\"`. */\n binding?: string | undefined;\n /** Custom mapper from structured log records to `TraceLine`s. Defaults to `defaultRecordMapper`. */\n mapper?: RecordMapper<LogRecord> | undefined;\n}>;\n\n/**\n * Extract structured trace lines from Cloudflare Workers `TailItem[]` logs and forward them\n * to the host `SPOCK_TRACE` session. No-op in production when `env[binding]` is absent.\n */\nexport async function forwardWorkersTail(\n events: readonly WorkersTailItem[],\n env: Readonly<Record<string, unknown>> | undefined,\n options?: SpockTailHandlerOptions | undefined,\n): Promise<number> {\n const binding = options?.binding ?? DEFAULT_SPOCK_BINDING;\n const fetcher = getFetcher(env, binding);\n if (fetcher === undefined) return 0;\n\n const session = options?.session ?? \"default\";\n const lines = fromWorkersTail(events, options?.mapper ?? defaultRecordMapper).lines();\n for (const line of lines) {\n await emitSpock(env, session, line, binding);\n }\n return lines.length;\n}\n\n/**\n * One-line Cloudflare Tail Worker module (`export default createSpockTailHandler(...)`) that\n * automatically streams existing `console.log({ ... })` Workers Logs from any auxiliary\n * Worker or Durable Object into a `vitest-spock` host session with zero manual instrumentation.\n */\nexport function createSpockTailHandler(\n options?: SpockTailHandlerOptions | undefined,\n): {\n tail(events: readonly WorkersTailItem[], env?: Readonly<Record<string, unknown>>): Promise<void>;\n} {\n return {\n async tail(\n events: readonly WorkersTailItem[],\n env?: Readonly<Record<string, unknown>>,\n ): Promise<void> {\n await forwardWorkersTail(events, env, options);\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CoverageRequirement, CoverageResult, CoverageSnapshot, CoverageTracker, TraceLine, TraceReport } from "./types.js";
|
|
2
|
+
/** Extract exercised action names, observed top-level fields, and stutter count from one run. */
|
|
3
|
+
export declare function extractTraceCoverage(report: TraceReport, observedLines: readonly TraceLine[]): CoverageSnapshot;
|
|
4
|
+
/** Evaluate `req` against an observed coverage snapshot. */
|
|
5
|
+
export declare function evaluateCoverage(snapshot: CoverageSnapshot, req: CoverageRequirement): CoverageResult;
|
|
6
|
+
/**
|
|
7
|
+
* Create a mutable suite-level coverage tracker that accumulates exercised actions,
|
|
8
|
+
* observed state fields, and stutter counts across multiple `toConformTo` assertions.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createCoverageTracker(): CoverageTracker;
|
package/dist/coverage.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
function topLevelField(key) {
|
|
2
|
+
const bracket = key.indexOf("[");
|
|
3
|
+
const dot = key.indexOf(".");
|
|
4
|
+
let cut = key.length;
|
|
5
|
+
if (bracket >= 0 && bracket < cut)
|
|
6
|
+
cut = bracket;
|
|
7
|
+
if (dot >= 0 && dot < cut)
|
|
8
|
+
cut = dot;
|
|
9
|
+
return key.slice(0, cut);
|
|
10
|
+
}
|
|
11
|
+
function actionMatches(observed, wanted) {
|
|
12
|
+
if (observed.has(wanted))
|
|
13
|
+
return true;
|
|
14
|
+
const suffix = `::${wanted}`;
|
|
15
|
+
for (const name of observed) {
|
|
16
|
+
if (name.endsWith(suffix))
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
/** Extract exercised action names, observed top-level fields, and stutter count from one run. */
|
|
22
|
+
export function extractTraceCoverage(report, observedLines) {
|
|
23
|
+
const actions = new Set();
|
|
24
|
+
let stutters = 0;
|
|
25
|
+
for (let i = 0; i < report.behavior.length; i += 1) {
|
|
26
|
+
const step = report.behavior[i];
|
|
27
|
+
if (step === undefined)
|
|
28
|
+
continue;
|
|
29
|
+
if (step.action !== null) {
|
|
30
|
+
actions.add(step.action);
|
|
31
|
+
}
|
|
32
|
+
else if (i > 0 && step.line !== null) {
|
|
33
|
+
stutters += 1;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const fields = new Set();
|
|
37
|
+
for (const line of observedLines) {
|
|
38
|
+
if (line.state === undefined)
|
|
39
|
+
continue;
|
|
40
|
+
for (const key of Object.keys(line.state)) {
|
|
41
|
+
const top = topLevelField(key);
|
|
42
|
+
if (top.length > 0)
|
|
43
|
+
fields.add(top);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
traces: 1,
|
|
48
|
+
lines: observedLines.length,
|
|
49
|
+
stutters: report.coverage?.stutters ?? stutters,
|
|
50
|
+
actions: report.coverage ? [...report.coverage.actions].sort() : [...actions].sort(),
|
|
51
|
+
leafActions: report.coverage ? [...report.coverage.leaf_actions].sort() : [],
|
|
52
|
+
fields: report.coverage ? [...report.coverage.observed_fields].sort() : [...fields].sort(),
|
|
53
|
+
specFields: report.coverage ? [...report.coverage.spec_fields].sort() : [],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** Evaluate `req` against an observed coverage snapshot. */
|
|
57
|
+
export function evaluateCoverage(snapshot, req) {
|
|
58
|
+
const actionSet = new Set(snapshot.actions);
|
|
59
|
+
const fieldSet = new Set(snapshot.fields);
|
|
60
|
+
const missingActions = [];
|
|
61
|
+
if (req.requireAllActions) {
|
|
62
|
+
for (const leaf of snapshot.leafActions) {
|
|
63
|
+
if (!actionMatches(actionSet, leaf) && !missingActions.includes(leaf)) {
|
|
64
|
+
missingActions.push(leaf);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (req.requireActions !== undefined) {
|
|
69
|
+
for (const wanted of req.requireActions) {
|
|
70
|
+
if (!actionMatches(actionSet, wanted) && !missingActions.includes(wanted)) {
|
|
71
|
+
missingActions.push(wanted);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const missingFields = [];
|
|
76
|
+
if (req.requireAllFields) {
|
|
77
|
+
for (const field of snapshot.specFields) {
|
|
78
|
+
if (!fieldSet.has(field) && !missingFields.includes(field)) {
|
|
79
|
+
missingFields.push(field);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (req.requireFields !== undefined) {
|
|
84
|
+
for (const wanted of req.requireFields) {
|
|
85
|
+
if (!fieldSet.has(wanted) && !missingFields.includes(wanted)) {
|
|
86
|
+
missingFields.push(wanted);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const tooManyStutters = req.maxStutters !== undefined && snapshot.stutters > req.maxStutters;
|
|
91
|
+
const ok = missingActions.length === 0 && missingFields.length === 0 && !tooManyStutters;
|
|
92
|
+
const parts = [];
|
|
93
|
+
if (missingActions.length > 0) {
|
|
94
|
+
parts.push(`missing required actions: ${missingActions.join(", ")}`);
|
|
95
|
+
}
|
|
96
|
+
if (missingFields.length > 0) {
|
|
97
|
+
parts.push(`never observed required state fields: ${missingFields.join(", ")}`);
|
|
98
|
+
}
|
|
99
|
+
if (tooManyStutters && req.maxStutters !== undefined) {
|
|
100
|
+
parts.push(`stutters ${snapshot.stutters} exceeded maxStutters(${req.maxStutters})`);
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
ok,
|
|
104
|
+
missingActions,
|
|
105
|
+
missingFields,
|
|
106
|
+
stutters: snapshot.stutters,
|
|
107
|
+
message: parts.join("\n"),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Create a mutable suite-level coverage tracker that accumulates exercised actions,
|
|
112
|
+
* observed state fields, and stutter counts across multiple `toConformTo` assertions.
|
|
113
|
+
*/
|
|
114
|
+
export function createCoverageTracker() {
|
|
115
|
+
let traces = 0;
|
|
116
|
+
let lines = 0;
|
|
117
|
+
let stutters = 0;
|
|
118
|
+
const actions = new Set();
|
|
119
|
+
const leafActions = new Set();
|
|
120
|
+
const fields = new Set();
|
|
121
|
+
const specFields = new Set();
|
|
122
|
+
const snapshot = () => ({
|
|
123
|
+
traces,
|
|
124
|
+
lines,
|
|
125
|
+
stutters,
|
|
126
|
+
actions: [...actions].sort(),
|
|
127
|
+
leafActions: [...leafActions].sort(),
|
|
128
|
+
fields: [...fields].sort(),
|
|
129
|
+
specFields: [...specFields].sort(),
|
|
130
|
+
});
|
|
131
|
+
return {
|
|
132
|
+
record(report, observedLines) {
|
|
133
|
+
if (report.outcome.kind !== "matches")
|
|
134
|
+
return;
|
|
135
|
+
const delta = extractTraceCoverage(report, observedLines);
|
|
136
|
+
traces += delta.traces;
|
|
137
|
+
lines += delta.lines;
|
|
138
|
+
stutters += delta.stutters;
|
|
139
|
+
for (const a of delta.actions)
|
|
140
|
+
actions.add(a);
|
|
141
|
+
for (const a of delta.leafActions)
|
|
142
|
+
leafActions.add(a);
|
|
143
|
+
for (const f of delta.fields)
|
|
144
|
+
fields.add(f);
|
|
145
|
+
for (const f of delta.specFields)
|
|
146
|
+
specFields.add(f);
|
|
147
|
+
},
|
|
148
|
+
snapshot,
|
|
149
|
+
check(req) {
|
|
150
|
+
return evaluateCoverage(snapshot(), req);
|
|
151
|
+
},
|
|
152
|
+
assertCoverage(req) {
|
|
153
|
+
const res = evaluateCoverage(snapshot(), req);
|
|
154
|
+
if (!res.ok) {
|
|
155
|
+
throw new Error(`spock trace coverage failed:\n${res.message}`);
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
reset() {
|
|
159
|
+
traces = 0;
|
|
160
|
+
lines = 0;
|
|
161
|
+
stutters = 0;
|
|
162
|
+
actions.clear();
|
|
163
|
+
leafActions.clear();
|
|
164
|
+
fields.clear();
|
|
165
|
+
specFields.clear();
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
//# sourceMappingURL=coverage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coverage.js","sourceRoot":"","sources":["../src/coverage.ts"],"names":[],"mappings":"AASA,SAAS,aAAa,CAAC,GAAW;IAChC,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACjC,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC7B,IAAI,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC;IACrB,IAAI,OAAO,IAAI,CAAC,IAAI,OAAO,GAAG,GAAG;QAAE,GAAG,GAAG,OAAO,CAAC;IACjD,IAAI,GAAG,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG;QAAE,GAAG,GAAG,GAAG,CAAC;IACrC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AAC3B,CAAC;AAED,SAAS,aAAa,CAAC,QAA6B,EAAE,MAAc;IAClE,IAAI,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,MAAM,GAAG,KAAK,MAAM,EAAE,CAAC;IAC7B,KAAK,MAAM,IAAI,IAAI,QAAQ,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;YAAE,OAAO,IAAI,CAAC;IACzC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,iGAAiG;AACjG,MAAM,UAAU,oBAAoB,CAClC,MAAmB,EACnB,aA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AK,EAAE,CAAC;YAChB,WAAW,CAAC,KAAK,EAAE,CAAC;YACpB,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,UAAU,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n CoverageRequirement,\n CoverageResult,\n CoverageSnapshot,\n CoverageTracker,\n TraceLine,\n TraceReport,\n} from \"./types.js\";\n\nfunction topLevelField(key: string): string {\n const bracket = key.indexOf(\"[\");\n const dot = key.indexOf(\".\");\n let cut = key.length;\n if (bracket >= 0 && bracket < cut) cut = bracket;\n if (dot >= 0 && dot < cut) cut = dot;\n return key.slice(0, cut);\n}\n\nfunction actionMatches(observed: ReadonlySet<string>, wanted: string): boolean {\n if (observed.has(wanted)) return true;\n const suffix = `::${wanted}`;\n for (const name of observed) {\n if (name.endsWith(suffix)) return true;\n }\n return false;\n}\n\n/** Extract exercised action names, observed top-level fields, and stutter count from one run. */\nexport function extractTraceCoverage(\n report: TraceReport,\n observedLines: readonly TraceLine[],\n): CoverageSnapshot {\n const actions = new Set<string>();\n let stutters = 0;\n for (let i = 0; i < report.behavior.length; i += 1) {\n const step = report.behavior[i];\n if (step === undefined) continue;\n if (step.action !== null) {\n actions.add(step.action);\n } else if (i > 0 && step.line !== null) {\n stutters += 1;\n }\n }\n const fields = new Set<string>();\n for (const line of observedLines) {\n if (line.state === undefined) continue;\n for (const key of Object.keys(line.state)) {\n const top = topLevelField(key);\n if (top.length > 0) fields.add(top);\n }\n }\n return {\n traces: 1,\n lines: observedLines.length,\n stutters: report.coverage?.stutters ?? stutters,\n actions: report.coverage ? [...report.coverage.actions].sort() : [...actions].sort(),\n leafActions: report.coverage ? [...report.coverage.leaf_actions].sort() : [],\n fields: report.coverage ? [...report.coverage.observed_fields].sort() : [...fields].sort(),\n specFields: report.coverage ? [...report.coverage.spec_fields].sort() : [],\n };\n}\n\n/** Evaluate `req` against an observed coverage snapshot. */\nexport function evaluateCoverage(\n snapshot: CoverageSnapshot,\n req: CoverageRequirement,\n): CoverageResult {\n const actionSet = new Set(snapshot.actions);\n const fieldSet = new Set(snapshot.fields);\n\n const missingActions: string[] = [];\n if (req.requireAllActions) {\n for (const leaf of snapshot.leafActions) {\n if (!actionMatches(actionSet, leaf) && !missingActions.includes(leaf)) {\n missingActions.push(leaf);\n }\n }\n }\n if (req.requireActions !== undefined) {\n for (const wanted of req.requireActions) {\n if (!actionMatches(actionSet, wanted) && !missingActions.includes(wanted)) {\n missingActions.push(wanted);\n }\n }\n }\n\n const missingFields: string[] = [];\n if (req.requireAllFields) {\n for (const field of snapshot.specFields) {\n if (!fieldSet.has(field) && !missingFields.includes(field)) {\n missingFields.push(field);\n }\n }\n }\n if (req.requireFields !== undefined) {\n for (const wanted of req.requireFields) {\n if (!fieldSet.has(wanted) && !missingFields.includes(wanted)) {\n missingFields.push(wanted);\n }\n }\n }\n\n const tooManyStutters = req.maxStutters !== undefined && snapshot.stutters > req.maxStutters;\n const ok = missingActions.length === 0 && missingFields.length === 0 && !tooManyStutters;\n\n const parts: string[] = [];\n if (missingActions.length > 0) {\n parts.push(`missing required actions: ${missingActions.join(\", \")}`);\n }\n if (missingFields.length > 0) {\n parts.push(`never observed required state fields: ${missingFields.join(\", \")}`);\n }\n if (tooManyStutters && req.maxStutters !== undefined) {\n parts.push(`stutters ${snapshot.stutters} exceeded maxStutters(${req.maxStutters})`);\n }\n\n return {\n ok,\n missingActions,\n missingFields,\n stutters: snapshot.stutters,\n message: parts.join(\"\\n\"),\n };\n}\n\n/**\n * Create a mutable suite-level coverage tracker that accumulates exercised actions,\n * observed state fields, and stutter counts across multiple `toConformTo` assertions.\n */\nexport function createCoverageTracker(): CoverageTracker {\n let traces = 0;\n let lines = 0;\n let stutters = 0;\n const actions = new Set<string>();\n const leafActions = new Set<string>();\n const fields = new Set<string>();\n const specFields = new Set<string>();\n\n const snapshot = (): CoverageSnapshot => ({\n traces,\n lines,\n stutters,\n actions: [...actions].sort(),\n leafActions: [...leafActions].sort(),\n fields: [...fields].sort(),\n specFields: [...specFields].sort(),\n });\n\n return {\n record(report: TraceReport, observedLines: readonly TraceLine[]): void {\n if (report.outcome.kind !== \"matches\") return;\n const delta = extractTraceCoverage(report, observedLines);\n traces += delta.traces;\n lines += delta.lines;\n stutters += delta.stutters;\n for (const a of delta.actions) actions.add(a);\n for (const a of delta.leafActions) leafActions.add(a);\n for (const f of delta.fields) fields.add(f);\n for (const f of delta.specFields) specFields.add(f);\n },\n snapshot,\n check(req: CoverageRequirement): CoverageResult {\n return evaluateCoverage(snapshot(), req);\n },\n assertCoverage(req: CoverageRequirement): void {\n const res = evaluateCoverage(snapshot(), req);\n if (!res.ok) {\n throw new Error(`spock trace coverage failed:\\n${res.message}`);\n }\n },\n reset(): void {\n traces = 0;\n lines = 0;\n stutters = 0;\n actions.clear();\n leafActions.clear();\n fields.clear();\n specFields.clear();\n },\n };\n}\n"]}
|
package/dist/format.js
CHANGED
|
@@ -41,6 +41,11 @@ export function formatConformanceFailure(report, observedLines, negated) {
|
|
|
41
41
|
switch (out.kind) {
|
|
42
42
|
case "matches":
|
|
43
43
|
return `Trace conformed to ${target} (${report.matched}/${report.states} matched).`;
|
|
44
|
+
case "coverage":
|
|
45
|
+
return [
|
|
46
|
+
`Trace conformed to ${target}, but failed coverage gate:`,
|
|
47
|
+
...out.errors.map((e) => ` - ${e}`),
|
|
48
|
+
].join("\n");
|
|
44
49
|
case "skipped":
|
|
45
50
|
return `Spock conformance check skipped for ${target}: ${out.reason}`;
|
|
46
51
|
case "diverges": {
|
package/dist/format.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.js","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAEA,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,OAAO,CAAC,IAAsB;IACrC,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,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,CAAC,CAAC,CAAC,kBAAkB,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACrE,OAAO,0BAA0B,MAAM,GAAG,MAAM,GAAG,GAAG,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC;QAC3E,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type { TraceLine, TraceMiss, TraceReport, TraceStep } from \"./types.js\";\n\nfunction fmtVal(value: unknown): string {\n return JSON.stringify(value);\n}\n\nfunction fmtStep(step: TraceStep | null): string {\n if (step === null) return \"(initial)\";\n const head =\n step.action === null\n ? \"(stutter)\"\n : step.args.length > 0\n ? `${step.action}(${step.args.map(fmtVal).join(\", \")})`\n : step.action;\n return `${head} ${fmtVal(step.state)}`;\n}\n\nfunction fmtMiss(miss: TraceMiss, index: number): string {\n const prefix = ` candidate #${index + 1} from ${fmtStep(miss.from)}:`;\n switch (miss.why.kind) {\n case \"not_enabled\":\n return `${prefix}\\n action is not enabled in this state`;\n case \"arguments\": {\n const shown = miss.why.arguments.slice(0, 6).map((args) => `(${args.map(fmtVal).join(\", \")})`);\n const more = miss.why.arguments.length > 6 ? `, … (+${miss.why.arguments.length - 6} more)` : \"\";\n return `${prefix}\\n action enabled only for arguments: ${shown.join(\", \")}${more}`;\n }\n case \"differs\": {\n const header = `${prefix}\\n nearest spec transition: ${fmtStep(miss.why.step)}`;\n const diffs = miss.why.differences.map(\n (d) => ` ${d.path}: observed ${fmtVal(d.seen)} != spec ${fmtVal(d.spec)}`,\n );\n return [header, ...diffs].join(\"\\n\");\n }\n }\n}\n\n/** Render a concise, actionable failure message for Vitest from a `TraceReport`. */\nexport function formatConformanceFailure(\n report: TraceReport,\n observedLines: readonly TraceLine[],\n negated: boolean,\n): string {\n const target = report.model ? `${report.spec} (model ${report.model})` : report.spec;\n\n if (negated) {\n return [\n `Expected trace NOT to conform to ${target}, but all ${report.matched}/${report.states} line(s) matched.`,\n ` matched behavior (${report.behavior.length} state(s)) in ${(report.seconds * 1000).toFixed(1)} ms`,\n ].join(\"\\n\");\n }\n\n const out = report.outcome;\n switch (out.kind) {\n case \"matches\":\n return `Trace conformed to ${target} (${report.matched}/${report.states} matched).`;\n\n case \"skipped\":\n return `Spock conformance check skipped for ${target}: ${out.reason}`;\n\n case \"diverges\": {\n const obs = observedLines[out.line - 1];\n const parts = [\n `Trace diverged from ${target} at line ${out.line} (matched ${report.matched}/${report.states} line(s)):`,\n ];\n if (obs !== undefined) {\n parts.push(` observed line ${out.line}: ${JSON.stringify(obs)}`);\n }\n const shownMisses = out.misses.slice(0, 5);\n for (let i = 0; i < shownMisses.length; i++) {\n const miss = shownMisses[i];\n if (miss !== undefined) {\n parts.push(fmtMiss(miss, i));\n }\n }\n if (out.misses.length > 5) {\n parts.push(` … (+${out.misses.length - 5} more reachable candidate state(s))`);\n }\n return parts.join(\"\\n\");\n }\n\n case \"invariant\": {\n const obs = observedLines[out.line - 1];\n const parts = [\n `Trace violated invariant ${out.name} in ${target} at line ${out.line} (matched ${report.matched}/${report.states} line(s)):`,\n ];\n if (obs !== undefined) {\n parts.push(` observed line ${out.line}: ${JSON.stringify(obs)}`);\n }\n return parts.join(\"\\n\");\n }\n\n case \"step_property\": {\n const obs = observedLines[out.line - 1];\n const parts = [\n `Trace violated step property ${out.name} in ${target} at line ${out.line} (matched ${report.matched}/${report.states} line(s)):`,\n ];\n if (obs !== undefined) {\n parts.push(` observed line ${out.line}: ${JSON.stringify(obs)}`);\n }\n return parts.join(\"\\n\");\n }\n\n case \"error\": {\n const loc = out.location ? ` (${out.location.file}:${out.location.line}:${out.location.column})` : \"\";\n const atLine = out.line !== null ? ` at trace line ${out.line}` : \"\";\n return `spock trace failed for ${target}${atLine}${loc}: ${out.message}`;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"format.js","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAEA,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,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AAC;QAED,KAAK,OAAO,CAAC,CAAC,CAAC;YACb,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,QAAQ,CAAC,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YACtG,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,kBAAkB,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACrE,OAAO,0BAA0B,MAAM,GAAG,MAAM,GAAG,GAAG,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC;QAC3E,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type { TraceLine, TraceMiss, TraceReport, TraceStep } from \"./types.js\";\n\nfunction fmtVal(value: unknown): string {\n return JSON.stringify(value);\n}\n\nfunction fmtStep(step: TraceStep | null): string {\n if (step === null) return \"(initial)\";\n const head =\n step.action === null\n ? \"(stutter)\"\n : step.args.length > 0\n ? `${step.action}(${step.args.map(fmtVal).join(\", \")})`\n : step.action;\n return `${head} ${fmtVal(step.state)}`;\n}\n\nfunction fmtMiss(miss: TraceMiss, index: number): string {\n const prefix = ` candidate #${index + 1} from ${fmtStep(miss.from)}:`;\n switch (miss.why.kind) {\n case \"not_enabled\":\n return `${prefix}\\n action is not enabled in this state`;\n case \"arguments\": {\n const shown = miss.why.arguments.slice(0, 6).map((args) => `(${args.map(fmtVal).join(\", \")})`);\n const more = miss.why.arguments.length > 6 ? `, … (+${miss.why.arguments.length - 6} more)` : \"\";\n return `${prefix}\\n action enabled only for arguments: ${shown.join(\", \")}${more}`;\n }\n case \"differs\": {\n const header = `${prefix}\\n nearest spec transition: ${fmtStep(miss.why.step)}`;\n const diffs = miss.why.differences.map(\n (d) => ` ${d.path}: observed ${fmtVal(d.seen)} != spec ${fmtVal(d.spec)}`,\n );\n return [header, ...diffs].join(\"\\n\");\n }\n }\n}\n\n/** Render a concise, actionable failure message for Vitest from a `TraceReport`. */\nexport function formatConformanceFailure(\n report: TraceReport,\n observedLines: readonly TraceLine[],\n negated: boolean,\n): string {\n const target = report.model ? `${report.spec} (model ${report.model})` : report.spec;\n\n if (negated) {\n return [\n `Expected trace NOT to conform to ${target}, but all ${report.matched}/${report.states} line(s) matched.`,\n ` matched behavior (${report.behavior.length} state(s)) in ${(report.seconds * 1000).toFixed(1)} ms`,\n ].join(\"\\n\");\n }\n\n const out = report.outcome;\n switch (out.kind) {\n case \"matches\":\n return `Trace conformed to ${target} (${report.matched}/${report.states} matched).`;\n\n case \"coverage\":\n return [\n `Trace conformed to ${target}, but failed coverage gate:`,\n ...out.errors.map((e) => ` - ${e}`),\n ].join(\"\\n\");\n\n case \"skipped\":\n return `Spock conformance check skipped for ${target}: ${out.reason}`;\n\n case \"diverges\": {\n const obs = observedLines[out.line - 1];\n const parts = [\n `Trace diverged from ${target} at line ${out.line} (matched ${report.matched}/${report.states} line(s)):`,\n ];\n if (obs !== undefined) {\n parts.push(` observed line ${out.line}: ${JSON.stringify(obs)}`);\n }\n const shownMisses = out.misses.slice(0, 5);\n for (let i = 0; i < shownMisses.length; i++) {\n const miss = shownMisses[i];\n if (miss !== undefined) {\n parts.push(fmtMiss(miss, i));\n }\n }\n if (out.misses.length > 5) {\n parts.push(` … (+${out.misses.length - 5} more reachable candidate state(s))`);\n }\n return parts.join(\"\\n\");\n }\n\n case \"invariant\": {\n const obs = observedLines[out.line - 1];\n const parts = [\n `Trace violated invariant ${out.name} in ${target} at line ${out.line} (matched ${report.matched}/${report.states} line(s)):`,\n ];\n if (obs !== undefined) {\n parts.push(` observed line ${out.line}: ${JSON.stringify(obs)}`);\n }\n return parts.join(\"\\n\");\n }\n\n case \"step_property\": {\n const obs = observedLines[out.line - 1];\n const parts = [\n `Trace violated step property ${out.name} in ${target} at line ${out.line} (matched ${report.matched}/${report.states} line(s)):`,\n ];\n if (obs !== undefined) {\n parts.push(` observed line ${out.line}: ${JSON.stringify(obs)}`);\n }\n return parts.join(\"\\n\");\n }\n\n case \"error\": {\n const loc = out.location ? ` (${out.location.file}:${out.location.line}:${out.location.column})` : \"\";\n const atLine = out.line !== null ? ` at trace line ${out.line}` : \"\";\n return `spock trace failed for ${target}${atLine}${loc}: ${out.message}`;\n }\n }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
+
export { captureConsole, createOtelSpanProcessor, defaultRecordMapper, fromWorkersTail, } from "./adapters.js";
|
|
2
|
+
export type { ConsoleCapture, ConsoleCaptureOptions, LogRecord, OtelProcessorOptions, OtelReadableSpan, OtelSpanEvent, OtelSpanProcessor, RecordMapper, TraceTarget, WorkersTailItem, WorkersTailLog, } from "./adapters.js";
|
|
3
|
+
export { autoVerifyConsole } from "./auto.js";
|
|
4
|
+
export type { AutoVerifyConsoleOptions } from "./auto.js";
|
|
5
|
+
export { createCoverageTracker, evaluateCoverage, extractTraceCoverage, } from "./coverage.js";
|
|
1
6
|
export { formatConformanceFailure } from "./format.js";
|
|
2
7
|
export { checkTrace, getSpockTransport, registerSpockMatchers, registerSpockTransport, toConformTo, } from "./matcher.js";
|
|
3
|
-
export { createTrace, isSpockSession, isTraceBuilder, normalizeTraceInput, toNdjson, } from "./trace.js";
|
|
4
|
-
export type { ConformOptions, MatchedStep, MissingBinaryPolicy, SpockLocation, SpockSession, SpockTransport, Trace, TraceArgs, TraceCheckRequest, TraceDifference, TraceInput, TraceLine, TraceMiss, TraceOutcome, TraceReport, TraceState, TraceStep, TraceWhy, } from "./types.js";
|
|
8
|
+
export { createTrace, isSpockSession, isTraceBuilder, normalizeTraceInput, toNdjson, validateTraceLine, } from "./trace.js";
|
|
9
|
+
export type { ConformOptions, CoverageRequirement, CoverageResult, CoverageSnapshot, CoverageTracker, MatchedStep, MissingBinaryPolicy, SpockLocation, SpockSession, SpockTransport, Trace, TraceArgs, TraceCheckRequest, TraceCoverageSummary, TraceDifference, TraceInput, TraceLine, TraceMiss, TraceOutcome, TraceReport, TraceState, TraceStep, TraceWhy, } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
export { captureConsole, createOtelSpanProcessor, defaultRecordMapper, fromWorkersTail, } from "./adapters.js";
|
|
2
|
+
export { autoVerifyConsole } from "./auto.js";
|
|
3
|
+
export { createCoverageTracker, evaluateCoverage, extractTraceCoverage, } from "./coverage.js";
|
|
1
4
|
export { formatConformanceFailure } from "./format.js";
|
|
2
5
|
export { checkTrace, getSpockTransport, registerSpockMatchers, registerSpockTransport, toConformTo, } from "./matcher.js";
|
|
3
|
-
export { createTrace, isSpockSession, isTraceBuilder, normalizeTraceInput, toNdjson, } from "./trace.js";
|
|
6
|
+
export { createTrace, isSpockSession, isTraceBuilder, normalizeTraceInput, toNdjson, validateTraceLine, } from "./trace.js";
|
|
4
7
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,qBAAqB,EACrB,sBAAsB,EACtB,WAAW,GACZ,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,WAAW,EACX,cAAc,EACd,cAAc,EACd,mBAAmB,EACnB,QAAQ,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,uBAAuB,EACvB,mBAAmB,EACnB,eAAe,GAChB,MAAM,eAAe,CAAC;AAcvB,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAE9C,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,qBAAqB,EACrB,sBAAsB,EACtB,WAAW,GACZ,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,WAAW,EACX,cAAc,EACd,cAAc,EACd,mBAAmB,EACnB,QAAQ,EACR,iBAAiB,GAClB,MAAM,YAAY,CAAC","sourcesContent":["export {\n captureConsole,\n createOtelSpanProcessor,\n defaultRecordMapper,\n fromWorkersTail,\n} from \"./adapters.js\";\nexport type {\n ConsoleCapture,\n ConsoleCaptureOptions,\n LogRecord,\n OtelProcessorOptions,\n OtelReadableSpan,\n OtelSpanEvent,\n OtelSpanProcessor,\n RecordMapper,\n TraceTarget,\n WorkersTailItem,\n WorkersTailLog,\n} from \"./adapters.js\";\nexport { autoVerifyConsole } from \"./auto.js\";\nexport type { AutoVerifyConsoleOptions } from \"./auto.js\";\nexport {\n createCoverageTracker,\n evaluateCoverage,\n extractTraceCoverage,\n} from \"./coverage.js\";\nexport { formatConformanceFailure } from \"./format.js\";\nexport {\n checkTrace,\n getSpockTransport,\n registerSpockMatchers,\n registerSpockTransport,\n toConformTo,\n} from \"./matcher.js\";\nexport {\n createTrace,\n isSpockSession,\n isTraceBuilder,\n normalizeTraceInput,\n toNdjson,\n validateTraceLine,\n} from \"./trace.js\";\nexport type {\n ConformOptions,\n CoverageRequirement,\n CoverageResult,\n CoverageSnapshot,\n CoverageTracker,\n MatchedStep,\n MissingBinaryPolicy,\n SpockLocation,\n SpockSession,\n SpockTransport,\n Trace,\n TraceArgs,\n TraceCheckRequest,\n TraceCoverageSummary,\n TraceDifference,\n TraceInput,\n TraceLine,\n TraceMiss,\n TraceOutcome,\n TraceReport,\n TraceState,\n TraceStep,\n TraceWhy,\n} from \"./types.js\";\n"]}
|
package/dist/matcher.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { expect } from "vitest";
|
|
2
|
+
import { evaluateCoverage, extractTraceCoverage } from "./coverage.js";
|
|
2
3
|
import { formatConformanceFailure } from "./format.js";
|
|
3
4
|
import { isSpockSession, normalizeTraceInput } from "./trace.js";
|
|
4
5
|
const TRANSPORT_KEY = Symbol.for("vitest-spock.transport");
|
|
@@ -53,6 +54,38 @@ export async function toConformTo(received, spec, options) {
|
|
|
53
54
|
message: () => formatConformanceFailure(report, observedLines, isNot),
|
|
54
55
|
};
|
|
55
56
|
}
|
|
57
|
+
if (report.outcome.kind === "matches") {
|
|
58
|
+
options?.coverage?.record(report, observedLines);
|
|
59
|
+
const hasCoverageGate = options?.requireAllActions === true ||
|
|
60
|
+
options?.requireActions !== undefined ||
|
|
61
|
+
options?.requireAllFields === true ||
|
|
62
|
+
options?.requireFields !== undefined ||
|
|
63
|
+
options?.maxStutters !== undefined;
|
|
64
|
+
if (hasCoverageGate) {
|
|
65
|
+
const snap = extractTraceCoverage(report, observedLines);
|
|
66
|
+
const cov = evaluateCoverage(snap, {
|
|
67
|
+
requireAllActions: options?.requireAllActions,
|
|
68
|
+
requireActions: options?.requireActions,
|
|
69
|
+
requireAllFields: options?.requireAllFields,
|
|
70
|
+
requireFields: options?.requireFields,
|
|
71
|
+
maxStutters: options?.maxStutters,
|
|
72
|
+
});
|
|
73
|
+
if (!cov.ok) {
|
|
74
|
+
return {
|
|
75
|
+
pass: false,
|
|
76
|
+
message: () => `Trace conformed to ${report.spec} (${report.model ?? "default"}), but failed coverage gate:\n${cov.message}`,
|
|
77
|
+
actual: snap,
|
|
78
|
+
expected: {
|
|
79
|
+
requireAllActions: options?.requireAllActions,
|
|
80
|
+
requireActions: options?.requireActions,
|
|
81
|
+
requireAllFields: options?.requireAllFields,
|
|
82
|
+
requireFields: options?.requireFields,
|
|
83
|
+
maxStutters: options?.maxStutters,
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
56
89
|
const pass = report.outcome.kind === "matches";
|
|
57
90
|
return {
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AC;AACJ,CAAC;AAED,IAAI,kBAAkB,GAAG,KAAK,CAAC;AAE/B,yFAAyF;AACzF,MAAM,UAAU,qBAAqB;IACnC,IAAI,kBAAkB;QAAE,OAAO;IAC/B,MAAM,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;IAC/B,kBAAkB,GAAG,IAAI,CAAC;AAC5B,CAAC","sourcesContent":["import { expect } from \"vitest\";\nimport { formatConformanceFailure } from \"./format.js\";\nimport { isSpockSession, normalizeTraceInput } from \"./trace.js\";\nimport type {\n ConformOptions,\n SpockTransport,\n TraceInput,\n TraceLine,\n TraceReport,\n} from \"./types.js\";\n\nconst TRANSPORT_KEY = Symbol.for(\"vitest-spock.transport\");\n\nfunction globalSlot(): Record<symbol, SpockTransport | undefined> {\n return globalThis as unknown as Record<symbol, SpockTransport | undefined>;\n}\n\n/** Register the host transport used by `toConformTo` and `checkTrace`. */\nexport function registerSpockTransport(transport: SpockTransport): void {\n globalSlot()[TRANSPORT_KEY] = transport;\n}\n\n/** Return the currently registered `SpockTransport`, if any. */\nexport function getSpockTransport(): SpockTransport | undefined {\n return globalSlot()[TRANSPORT_KEY];\n}\n\n/** Validate `input` against a `.spock` specification using the active transport. */\nexport async function checkTrace(\n input: TraceInput,\n spec: string,\n options?: ConformOptions | undefined,\n): Promise<TraceReport> {\n if (isSpockSession(input)) {\n return input.check(spec, options);\n }\n const transport = getSpockTransport();\n if (transport === undefined) {\n throw new Error(\n \"vitest-spock: no transport registered. Add `vitest-spock/node/setup` (Node) or \" +\n \"`vitest-spock/cloudflare/setup` (Cloudflare Workers) to Vitest `setupFiles`, \" +\n \"or call `setupNodeSpock()` / `setupCloudflareSpock()`.\",\n );\n }\n const { ndjson } = normalizeTraceInput(input);\n return transport.checkTrace({\n spec,\n model: options?.model,\n ndjson,\n timeoutMs: options?.timeoutMs,\n onMissingBinary: options?.onMissingBinary,\n });\n}\n\n/** Vitest matcher implementation for `expect(trace).toConformTo(spec, options)`. */\nexport async function toConformTo(\n this: { isNot?: boolean | undefined },\n received: TraceInput,\n spec: string,\n options?: ConformOptions | undefined,\n): Promise<{ pass: boolean; message: () => string; actual?: unknown; expected?: unknown }> {\n const isNot = Boolean(this.isNot);\n let observedLines: readonly TraceLine[] = [];\n let report: TraceReport;\n\n if (isSpockSession(received)) {\n observedLines = await received.lines({ clear: false });\n report = await received.check(spec, options);\n } else {\n const normalized = normalizeTraceInput(received);\n observedLines = normalized.lines;\n report = await checkTrace(received, spec, options);\n }\n\n if (report.outcome.kind === \"skipped\") {\n return {\n pass: !isNot,\n message: () => formatConformanceFailure(report, observedLines, isNot),\n };\n }\n\n const pass = report.outcome.kind === \"matches\";\n return {\n pass,\n message: () => formatConformanceFailure(report, observedLines, isNot),\n actual: report.outcome,\n expected: { kind: \"matches\" },\n };\n}\n\nlet matchersRegistered = false;\n\n/** Register `toConformTo` with Vitest's `expect.extend`. Safe to call multiple times. */\nexport function registerSpockMatchers(): void {\n if (matchersRegistered) return;\n expect.extend({ toConformTo });\n matchersRegistered = true;\n}\n\ninterface SpockMatchers<R = unknown> {\n /**\n * Assert that a recorded trace (`createTrace()`, `SpockSession`, `TraceLine[]`, or NDJSON)\n * conforms step-for-step to a `.spock` specification via `spock trace`.\n */\n toConformTo(spec: string, options?: ConformOptions | undefined): Promise<R>;\n}\n\ndeclare module \"vitest\" {\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Assertion<T = any> extends SpockMatchers<T> {}\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface AsymmetricMatchersContaining extends SpockMatchers {}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"matcher.js","sourceRoot":"","sources":["../src/matcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AACvE,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO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from \"vitest\";\nimport { evaluateCoverage, extractTraceCoverage } from \"./coverage.js\";\nimport { formatConformanceFailure } from \"./format.js\";\nimport { isSpockSession, normalizeTraceInput } from \"./trace.js\";\nimport type {\n ConformOptions,\n SpockTransport,\n TraceInput,\n TraceLine,\n TraceReport,\n} from \"./types.js\";\n\nconst TRANSPORT_KEY = Symbol.for(\"vitest-spock.transport\");\n\nfunction globalSlot(): Record<symbol, SpockTransport | undefined> {\n return globalThis as unknown as Record<symbol, SpockTransport | undefined>;\n}\n\n/** Register the host transport used by `toConformTo` and `checkTrace`. */\nexport function registerSpockTransport(transport: SpockTransport): void {\n globalSlot()[TRANSPORT_KEY] = transport;\n}\n\n/** Return the currently registered `SpockTransport`, if any. */\nexport function getSpockTransport(): SpockTransport | undefined {\n return globalSlot()[TRANSPORT_KEY];\n}\n\n/** Validate `input` against a `.spock` specification using the active transport. */\nexport async function checkTrace(\n input: TraceInput,\n spec: string,\n options?: ConformOptions | undefined,\n): Promise<TraceReport> {\n if (isSpockSession(input)) {\n return input.check(spec, options);\n }\n const transport = getSpockTransport();\n if (transport === undefined) {\n throw new Error(\n \"vitest-spock: no transport registered. Add `vitest-spock/node/setup` (Node) or \" +\n \"`vitest-spock/cloudflare/setup` (Cloudflare Workers) to Vitest `setupFiles`, \" +\n \"or call `setupNodeSpock()` / `setupCloudflareSpock()`.\",\n );\n }\n const { ndjson } = normalizeTraceInput(input);\n return transport.checkTrace({\n spec,\n model: options?.model,\n ndjson,\n timeoutMs: options?.timeoutMs,\n onMissingBinary: options?.onMissingBinary,\n });\n}\n\n/** Vitest matcher implementation for `expect(trace).toConformTo(spec, options)`. */\nexport async function toConformTo(\n this: { isNot?: boolean | undefined },\n received: TraceInput,\n spec: string,\n options?: ConformOptions | undefined,\n): Promise<{ pass: boolean; message: () => string; actual?: unknown; expected?: unknown }> {\n const isNot = Boolean(this.isNot);\n let observedLines: readonly TraceLine[] = [];\n let report: TraceReport;\n\n if (isSpockSession(received)) {\n observedLines = await received.lines({ clear: false });\n report = await received.check(spec, options);\n } else {\n const normalized = normalizeTraceInput(received);\n observedLines = normalized.lines;\n report = await checkTrace(received, spec, options);\n }\n\n if (report.outcome.kind === \"skipped\") {\n return {\n pass: !isNot,\n message: () => formatConformanceFailure(report, observedLines, isNot),\n };\n }\n\n if (report.outcome.kind === \"matches\") {\n options?.coverage?.record(report, observedLines);\n const hasCoverageGate =\n options?.requireAllActions === true ||\n options?.requireActions !== undefined ||\n options?.requireAllFields === true ||\n options?.requireFields !== undefined ||\n options?.maxStutters !== undefined;\n if (hasCoverageGate) {\n const snap = extractTraceCoverage(report, observedLines);\n const cov = evaluateCoverage(snap, {\n requireAllActions: options?.requireAllActions,\n requireActions: options?.requireActions,\n requireAllFields: options?.requireAllFields,\n requireFields: options?.requireFields,\n maxStutters: options?.maxStutters,\n });\n if (!cov.ok) {\n return {\n pass: false,\n message: () =>\n `Trace conformed to ${report.spec} (${report.model ?? \"default\"}), but failed coverage gate:\\n${cov.message}`,\n actual: snap,\n expected: {\n requireAllActions: options?.requireAllActions,\n requireActions: options?.requireActions,\n requireAllFields: options?.requireAllFields,\n requireFields: options?.requireFields,\n maxStutters: options?.maxStutters,\n },\n };\n }\n }\n }\n\n const pass = report.outcome.kind === \"matches\";\n return {\n pass,\n message: () => formatConformanceFailure(report, observedLines, isNot),\n actual: report.outcome,\n expected: { kind: \"matches\" },\n };\n}\n\nlet matchersRegistered = false;\n\n/** Register `toConformTo` with Vitest's `expect.extend`. Safe to call multiple times. */\nexport function registerSpockMatchers(): void {\n if (matchersRegistered) return;\n expect.extend({ toConformTo });\n matchersRegistered = true;\n}\n\ninterface SpockMatchers<R = unknown> {\n /**\n * Assert that a recorded trace (`createTrace()`, `SpockSession`, `TraceLine[]`, or NDJSON)\n * conforms step-for-step to a `.spock` specification via `spock trace`.\n */\n toConformTo(spec: string, options?: ConformOptions | undefined): Promise<R>;\n}\n\ndeclare module \"vitest\" {\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Assertion<T = any> extends SpockMatchers<T> {}\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface AsymmetricMatchersContaining extends SpockMatchers {}\n}\n"]}
|
package/dist/node/binary.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ export type FindBinaryOptions = Readonly<{
|
|
|
10
10
|
* Resolution order:
|
|
11
11
|
* 1. `options.spockBin`
|
|
12
12
|
* 2. `process.env.SPOCK_BIN`
|
|
13
|
-
* 3.
|
|
13
|
+
* 3. Bundled binary inside `spock-cli` (or legacy `@leostera/spock-<platform>-<arch>`)
|
|
14
14
|
* 4. Nearest `node_modules/.bin/spock` walking up from `options.rootDir` / `process.cwd()`
|
|
15
15
|
* 5. `~/.cargo/bin/spock`
|
|
16
16
|
* 6. `spock` on `PATH`
|
package/dist/node/binary.js
CHANGED
|
@@ -3,7 +3,14 @@ import { existsSync } from "node:fs";
|
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { dirname, join, resolve } from "node:path";
|
|
6
|
-
const
|
|
6
|
+
const BUNDLED_TARGETS = {
|
|
7
|
+
"darwin:arm64": "darwin-arm64/spock",
|
|
8
|
+
"darwin:x64": "darwin-x64/spock",
|
|
9
|
+
"linux:x64": "linux-x64/spock",
|
|
10
|
+
"linux:arm64": "linux-arm64/spock",
|
|
11
|
+
"win32:x64": "win32-x64/spock.exe",
|
|
12
|
+
};
|
|
13
|
+
const LEGACY_PLATFORM_PACKAGES = {
|
|
7
14
|
"darwin:arm64": "@leostera/spock-darwin-arm64/bin/spock",
|
|
8
15
|
"darwin:x64": "@leostera/spock-darwin-x64/bin/spock",
|
|
9
16
|
"linux:x64": "@leostera/spock-linux-x64/bin/spock",
|
|
@@ -35,13 +42,27 @@ function walkNodeModulesBins(startDir) {
|
|
|
35
42
|
}
|
|
36
43
|
return found;
|
|
37
44
|
}
|
|
38
|
-
function
|
|
39
|
-
const
|
|
40
|
-
|
|
45
|
+
function resolveSpockCliBinary(startDir) {
|
|
46
|
+
const key = `${process.platform}:${process.arch}`;
|
|
47
|
+
const req = createRequire(join(resolve(startDir), "package.json"));
|
|
48
|
+
const bundledRel = BUNDLED_TARGETS[key];
|
|
49
|
+
if (bundledRel !== undefined) {
|
|
50
|
+
try {
|
|
51
|
+
const cliPkg = req.resolve("spock-cli/package.json");
|
|
52
|
+
const candidate = join(dirname(cliPkg), "vendor", bundledRel);
|
|
53
|
+
if (existsSync(candidate)) {
|
|
54
|
+
return candidate;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// Fall through to legacy platform package / PATH lookup.
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const legacyTarget = LEGACY_PLATFORM_PACKAGES[key];
|
|
62
|
+
if (legacyTarget === undefined)
|
|
41
63
|
return null;
|
|
42
64
|
try {
|
|
43
|
-
|
|
44
|
-
return req.resolve(target);
|
|
65
|
+
return req.resolve(legacyTarget);
|
|
45
66
|
}
|
|
46
67
|
catch {
|
|
47
68
|
return null;
|
|
@@ -54,7 +75,7 @@ const binaryCache = new Map();
|
|
|
54
75
|
* Resolution order:
|
|
55
76
|
* 1. `options.spockBin`
|
|
56
77
|
* 2. `process.env.SPOCK_BIN`
|
|
57
|
-
* 3.
|
|
78
|
+
* 3. Bundled binary inside `spock-cli` (or legacy `@leostera/spock-<platform>-<arch>`)
|
|
58
79
|
* 4. Nearest `node_modules/.bin/spock` walking up from `options.rootDir` / `process.cwd()`
|
|
59
80
|
* 5. `~/.cargo/bin/spock`
|
|
60
81
|
* 6. `spock` on `PATH`
|
|
@@ -70,9 +91,9 @@ export function findSpockBinary(options) {
|
|
|
70
91
|
candidates.push(options.spockBin);
|
|
71
92
|
if (process.env["SPOCK_BIN"])
|
|
72
93
|
candidates.push(process.env["SPOCK_BIN"]);
|
|
73
|
-
const
|
|
74
|
-
if (
|
|
75
|
-
candidates.push(
|
|
94
|
+
const cliBin = resolveSpockCliBinary(startDir);
|
|
95
|
+
if (cliBin)
|
|
96
|
+
candidates.push(cliBin);
|
|
76
97
|
candidates.push(...walkNodeModulesBins(startDir));
|
|
77
98
|
candidates.push(resolve(homedir(), ".cargo", "bin", process.platform === "win32" ? "spock.exe" : "spock"));
|
|
78
99
|
candidates.push("spock");
|
package/dist/node/binary.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"binary.js","sourceRoot":"","sources":["../../src/node/binary.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AASnD,MAAM,iBAAiB,GAAqC;
|
|
1
|
+
{"version":3,"file":"binary.js","sourceRoot":"","sources":["../../src/node/binary.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AASnD,MAAM,eAAe,GAAqC;IACxD,cAAc,EAAE,oBAAoB;IACpC,YAAY,EAAE,kBAAkB;IAChC,WAAW,EAAE,iBAAiB;IAC9B,aAAa,EAAE,mBAAmB;IAClC,WAAW,EAAE,qBAAqB;CACnC,CAAC;AAEF,MAAM,wBAAwB,GAAqC;IACjE,cAAc,EAAE,wCAAwC;IACxD,YAAY,EAAE,sCAAsC;IACpD,WAAW,EAAE,qCAAqC;IAClD,aAAa,EAAE,uCAAu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AAI,OAAO,EAAE,QAAQ;QAAE,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACzD,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;QAAE,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC;IACxE,MAAM,MAAM,GAAG,qBAAqB,CAAC,QAAQ,CAAC,CAAC;IAC/C,IAAI,MAAM;QAAE,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpC,UAAU,CAAC,IAAI,CAAC,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAC,CAAC;IAClD,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3G,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAEzB,IAAI,QAAQ,GAAkB,IAAI,CAAC;IACnC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,IAAI,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC;YACtB,QAAQ,GAAG,SAAS,CAAC;YACrB,MAAM;QACR,CAAC;IACH,CAAC;IACD,WAAW,CAAC,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACpC,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,qBAAqB;IACnC,WAAW,CAAC,KAAK,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import { execFileSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\n\nexport type FindBinaryOptions = Readonly<{\n /** Explicit path to the `spock` executable. */\n spockBin?: string | undefined;\n /** Starting directory when searching `node_modules/.bin/spock`. Defaults to `process.cwd()`. */\n rootDir?: string | undefined;\n}>;\n\nconst BUNDLED_TARGETS: Readonly<Record<string, string>> = {\n \"darwin:arm64\": \"darwin-arm64/spock\",\n \"darwin:x64\": \"darwin-x64/spock\",\n \"linux:x64\": \"linux-x64/spock\",\n \"linux:arm64\": \"linux-arm64/spock\",\n \"win32:x64\": \"win32-x64/spock.exe\",\n};\n\nconst LEGACY_PLATFORM_PACKAGES: Readonly<Record<string, string>> = {\n \"darwin:arm64\": \"@leostera/spock-darwin-arm64/bin/spock\",\n \"darwin:x64\": \"@leostera/spock-darwin-x64/bin/spock\",\n \"linux:x64\": \"@leostera/spock-linux-x64/bin/spock\",\n \"linux:arm64\": \"@leostera/spock-linux-arm64/bin/spock\",\n \"win32:x64\": \"@leostera/spock-win32-x64/bin/spock.exe\",\n};\n\nfunction canRun(bin: string): boolean {\n if ((bin.includes(\"/\") || bin.includes(\"\\\\\")) && !existsSync(bin)) {\n return false;\n }\n try {\n execFileSync(bin, [\"--version\"], { stdio: \"pipe\", timeout: 5_000 });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction walkNodeModulesBins(startDir: string): string[] {\n const found: string[] = [];\n const exe = process.platform === \"win32\" ? \"spock.cmd\" : \"spock\";\n let cur = resolve(startDir);\n while (true) {\n found.push(join(cur, \"node_modules\", \".bin\", exe));\n const parent = dirname(cur);\n if (parent === cur) break;\n cur = parent;\n }\n return found;\n}\n\nfunction resolveSpockCliBinary(startDir: string): string | null {\n const key = `${process.platform}:${process.arch}`;\n const req = createRequire(join(resolve(startDir), \"package.json\"));\n\n const bundledRel = BUNDLED_TARGETS[key];\n if (bundledRel !== undefined) {\n try {\n const cliPkg = req.resolve(\"spock-cli/package.json\");\n const candidate = join(dirname(cliPkg), \"vendor\", bundledRel);\n if (existsSync(candidate)) {\n return candidate;\n }\n } catch {\n // Fall through to legacy platform package / PATH lookup.\n }\n }\n\n const legacyTarget = LEGACY_PLATFORM_PACKAGES[key];\n if (legacyTarget === undefined) return null;\n try {\n return req.resolve(legacyTarget);\n } catch {\n return null;\n }\n}\n\nconst binaryCache = new Map<string, string | null>();\n\n/**\n * Locate the `spock` binary.\n *\n * Resolution order:\n * 1. `options.spockBin`\n * 2. `process.env.SPOCK_BIN`\n * 3. Bundled binary inside `spock-cli` (or legacy `@leostera/spock-<platform>-<arch>`)\n * 4. Nearest `node_modules/.bin/spock` walking up from `options.rootDir` / `process.cwd()`\n * 5. `~/.cargo/bin/spock`\n * 6. `spock` on `PATH`\n */\nexport function findSpockBinary(options?: FindBinaryOptions | undefined): string | null {\n const startDir = options?.rootDir ?? process.cwd();\n const cacheKey = `${options?.spockBin ?? \"\"}\\0${process.env[\"SPOCK_BIN\"] ?? \"\"}\\0${startDir}`;\n if (binaryCache.has(cacheKey)) {\n return binaryCache.get(cacheKey) ?? null;\n }\n\n const candidates: string[] = [];\n if (options?.spockBin) candidates.push(options.spockBin);\n if (process.env[\"SPOCK_BIN\"]) candidates.push(process.env[\"SPOCK_BIN\"]);\n const cliBin = resolveSpockCliBinary(startDir);\n if (cliBin) candidates.push(cliBin);\n candidates.push(...walkNodeModulesBins(startDir));\n candidates.push(resolve(homedir(), \".cargo\", \"bin\", process.platform === \"win32\" ? \"spock.exe\" : \"spock\"));\n candidates.push(\"spock\");\n\n let resolved: string | null = null;\n for (const candidate of candidates) {\n if (canRun(candidate)) {\n resolved = candidate;\n break;\n }\n }\n binaryCache.set(cacheKey, resolved);\n return resolved;\n}\n\n/** Clear the cached binary resolution result (primarily for tests). */\nexport function resetSpockBinaryCache(): void {\n binaryCache.clear();\n}\n"]}
|
package/dist/node/plugin.d.ts
CHANGED
|
@@ -1,13 +1,37 @@
|
|
|
1
1
|
import { type NodeRunnerOptions } from "./runner.js";
|
|
2
|
+
export type SpockPluginOptions = NodeRunnerOptions & Readonly<{
|
|
3
|
+
/**
|
|
4
|
+
* When `true` alongside `spec`, automatically installs `autoVerifyConsole` in every
|
|
5
|
+
* Vitest test so existing structured `console.log` JSON logs are checked against `spec`
|
|
6
|
+
* with zero changes to app code or test bodies.
|
|
7
|
+
*/
|
|
8
|
+
captureConsole?: boolean | undefined;
|
|
9
|
+
/** `.spock` specification path used when `captureConsole` is enabled. */
|
|
10
|
+
spec?: string | undefined;
|
|
11
|
+
/** Optional model name inside `spec` used when `captureConsole` is enabled. */
|
|
12
|
+
model?: string | undefined;
|
|
13
|
+
/** Require every leaf action reachable from `model.next` across the suite. */
|
|
14
|
+
requireAllActions?: boolean | undefined;
|
|
15
|
+
/** Suite-level required action names checked in `afterAll`. */
|
|
16
|
+
requireActions?: readonly string[] | undefined;
|
|
17
|
+
/** Require every `State` field to be observed across the suite. */
|
|
18
|
+
requireAllFields?: boolean | undefined;
|
|
19
|
+
/** Suite-level required observed field names checked in `afterAll`. */
|
|
20
|
+
requireFields?: readonly string[] | undefined;
|
|
21
|
+
/** Suite-level maximum pure stutter observations checked in `afterAll`. */
|
|
22
|
+
maxStutters?: number | undefined;
|
|
23
|
+
}>;
|
|
2
24
|
/**
|
|
3
25
|
* Configure `vitest-spock` for a Node Vitest environment: registers the local `spock` CLI
|
|
4
|
-
* transport and Vitest's `toConformTo` matcher.
|
|
26
|
+
* transport and Vitest's `toConformTo` matcher. If `captureConsole` (or
|
|
27
|
+
* `VITEST_SPOCK_CAPTURE_CONSOLE=1` + `VITEST_SPOCK_SPEC`) is set, also hooks `console`
|
|
28
|
+
* automatically via [`autoVerifyConsole`].
|
|
5
29
|
*/
|
|
6
|
-
export declare function setupNodeSpock(options?:
|
|
7
|
-
export type SpockPluginOptions = NodeRunnerOptions;
|
|
30
|
+
export declare function setupNodeSpock(options?: SpockPluginOptions | undefined): void;
|
|
8
31
|
/**
|
|
9
32
|
* Minimal Vite/Vitest plugin for Node projects. Exports `VITEST_SPOCK_ROOT` (and `SPOCK_BIN`
|
|
10
|
-
* when specified) and registers `vitest-spock/node/setup` in
|
|
33
|
+
* / auto-capture settings when specified) and registers `vitest-spock/node/setup` in
|
|
34
|
+
* `test.setupFiles`.
|
|
11
35
|
*/
|
|
12
36
|
export declare function spock(options?: SpockPluginOptions | undefined): {
|
|
13
37
|
name: string;
|