vitest-spock 0.8.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 CHANGED
@@ -20,7 +20,17 @@ import { defineConfig } from "vitest/config";
20
20
  import { spock } from "vitest-spock/node";
21
21
 
22
22
  export default defineConfig({
23
- plugins: [spock({ rootDir: resolve(import.meta.dirname) })],
23
+ plugins: [
24
+ spock({
25
+ rootDir: resolve(import.meta.dirname),
26
+ // Optional zero-boilerplate mode: auto-capture existing console JSON logs in every test
27
+ // spec: "specs/counter.spock",
28
+ // model: "two",
29
+ // captureConsole: true,
30
+ // requireAllActions: true,
31
+ // requireAllFields: true,
32
+ }),
33
+ ],
24
34
  });
25
35
  ```
26
36
 
@@ -80,6 +90,13 @@ test("ProjectionDO conforms to spec", async () => {
80
90
  });
81
91
  ```
82
92
 
93
+ ### Zero-instrumentation hooks (Console, OpenTelemetry, Cloudflare Workers Tail)
94
+
95
+ - **`spock({ captureConsole: true, spec, model, requireAllActions: true })`** / **`autoVerifyConsole(...)`**: automatically captures existing structured `console.log`/`info`/`debug` JSON logs (Workers Logs, Pino JSON) across every Vitest test and enforces suite-level coverage in `afterAll`.
96
+ - **`createOtelSpanProcessor()`**: structural OpenTelemetry `SpanProcessor` (zero `@opentelemetry/*` dep, `workerd`-safe) converting existing OTel spans and span events into traces.
97
+ - **`createSpockTailHandler({ session })`** (`vitest-spock/cloudflare/emitter`): 1-line Cloudflare Tail Worker (`export default createSpockTailHandler({ session: "main" })`) that forwards existing `console.log({ ... })` Workers Logs from auxiliary Workers and Durable Objects into `env.SPOCK_TRACE`.
98
+ - **`fromWorkersTail(items)`**: extracts a `Trace` from Cloudflare `TailItem[]` logs (`wrangler tail --format json`).
99
+
83
100
  ### Optional live emission from inside Durable Objects
84
101
 
85
102
  Import `vitest-spock/cloudflare/emitter` in Worker/DO code (zero Vitest or Node dependencies;
@@ -106,9 +123,9 @@ await expect(session).toConformTo("specs/projection-dlq.spock", { model: "fixed_
106
123
 
107
124
  | Import | Environment | Purpose |
108
125
  |---|---|---|
109
- | `vitest-spock` | Universal (`workerd` + Node) | `createTrace`, `toConformTo`, `checkTrace`, `formatConformanceFailure`, types |
126
+ | `vitest-spock` | Universal (`workerd` + Node) | `createTrace`, `toConformTo`, `checkTrace`, `createCoverageTracker`, `captureConsole`, `autoVerifyConsole`, `createOtelSpanProcessor`, `fromWorkersTail`, types |
110
127
  | `vitest-spock/node` | Node | `spock()` plugin, `setupNodeSpock`, `findSpockBinary`, `runSpockTrace`, `runSpockCheck`, `runSpockProve` |
111
128
  | `vitest-spock/node/setup` | Node `setupFiles` | Auto-registers Node transport and `toConformTo` matcher |
112
129
  | `vitest-spock/cloudflare` | Node (`vitest.config.ts`) | `spockServiceBinding({ rootDir, spockBin?, binding?, onMissingBinary? })` |
113
130
  | `vitest-spock/cloudflare/setup` | `workerd` `setupFiles` | Auto-registers `env.SPOCK_TRACE` transport, `toConformTo`, and exports `startSpockSession` |
114
- | `vitest-spock/cloudflare/emitter` | `workerd` / Production | Zero-dep, zero-cost-in-prod `emitSpock` and `createTraceSink` |
131
+ | `vitest-spock/cloudflare/emitter` | `workerd` / Production | Zero-dep, zero-cost-in-prod `emitSpock`, `createTraceSink`, `forwardWorkersTail`, `createSpockTailHandler` |
@@ -0,0 +1,84 @@
1
+ import type { Trace, TraceLine } from "./types.js";
2
+ /** A structured log object captured from `console`, Pino, Cloudflare Workers Logs, or OTel. */
3
+ export type LogRecord = Readonly<Record<string, unknown>>;
4
+ /** Maps an arbitrary structured log/span record into a `TraceLine`, or `null`/`undefined` to skip. */
5
+ export type RecordMapper<T = LogRecord> = (record: T) => TraceLine | null | undefined;
6
+ /** Destination accepting mapped `TraceLine`s (either a `Trace` builder or a callback/sink). */
7
+ export type TraceTarget = Trace | Readonly<{
8
+ push(line: TraceLine): unknown;
9
+ }> | ((line: TraceLine) => unknown);
10
+ export declare function defaultRecordMapper(record: LogRecord): TraceLine | null;
11
+ /** Options for [`captureConsole`]. */
12
+ export type ConsoleCaptureOptions = Readonly<{
13
+ /** Console methods to intercept. Defaults to `["log", "info", "debug"]`. */
14
+ methods?: readonly ("log" | "info" | "debug" | "warn")[] | undefined;
15
+ /** Custom mapper from structured log objects to `TraceLine`s. Defaults to `defaultRecordMapper`. */
16
+ mapper?: RecordMapper<LogRecord> | undefined;
17
+ /** Optional target to forward lines to instead of (or in addition to) the returned `trace`. */
18
+ target?: TraceTarget | undefined;
19
+ /** Still forward intercepted calls to the original `console` methods. Defaults to `false`. */
20
+ passthrough?: boolean | undefined;
21
+ }>;
22
+ /** Active console capture handle. Call `restore()` (or use `using`) when the test finishes. */
23
+ export interface ConsoleCapture {
24
+ readonly trace: Trace;
25
+ restore(): void;
26
+ [Symbol.dispose](): void;
27
+ }
28
+ /**
29
+ * Intercepts existing `console.log`/`info`/`debug` structured JSON logs (e.g. Cloudflare
30
+ * Workers Logs, Pino JSON transport, or plain `console.log({ action, ... })`) with zero
31
+ * changes to application code.
32
+ *
33
+ * Works in both Node and Cloudflare Workers (`workerd`) test environments.
34
+ */
35
+ export declare function captureConsole(options?: ConsoleCaptureOptions | undefined): ConsoleCapture;
36
+ /** Minimal structural OpenTelemetry span event shape (zero `@opentelemetry/*` dependency). */
37
+ export type OtelSpanEvent = Readonly<{
38
+ name: string;
39
+ attributes?: Readonly<Record<string, unknown>> | undefined;
40
+ }>;
41
+ /** Minimal structural OpenTelemetry `ReadableSpan` shape (zero `@opentelemetry/*` dependency). */
42
+ export type OtelReadableSpan = Readonly<{
43
+ name: string;
44
+ attributes: Readonly<Record<string, unknown>>;
45
+ events?: readonly OtelSpanEvent[] | undefined;
46
+ }>;
47
+ /** Structural OpenTelemetry `SpanProcessor` compatible with `@opentelemetry/sdk-trace-base`. */
48
+ export interface OtelSpanProcessor {
49
+ readonly trace: Trace;
50
+ onStart(span: unknown, parentContext?: unknown): void;
51
+ onEnd(span: OtelReadableSpan): void;
52
+ forceFlush(): Promise<void>;
53
+ shutdown(): Promise<void>;
54
+ }
55
+ /** Options for [`createOtelSpanProcessor`]. */
56
+ export type OtelProcessorOptions = Readonly<{
57
+ /** Custom mapper from a completed OTel span to a `TraceLine` (or `null` to ignore). */
58
+ mapSpan?: RecordMapper<OtelReadableSpan> | undefined;
59
+ /** Custom mapper from a span event (`span.addEvent(...)`) to a `TraceLine`. */
60
+ mapEvent?: ((event: OtelSpanEvent, span: OtelReadableSpan) => TraceLine | null | undefined) | undefined;
61
+ /** Optional target to forward lines to in addition to the processor's `trace`. */
62
+ target?: TraceTarget | undefined;
63
+ }>;
64
+ /**
65
+ * Creates a structural OpenTelemetry `SpanProcessor` (zero `@opentelemetry/*` dependency,
66
+ * safe in both Node and Cloudflare Workers) that converts existing OTel spans and span
67
+ * events into a `spock` trace automatically.
68
+ */
69
+ export declare function createOtelSpanProcessor(options?: OtelProcessorOptions | undefined): OtelSpanProcessor;
70
+ /** Minimal structural Cloudflare Workers `TailItem` shape (`wrangler tail --format json` / Tail Workers). */
71
+ export type WorkersTailLog = Readonly<{
72
+ message?: readonly unknown[] | undefined;
73
+ level?: string | undefined;
74
+ timestamp?: number | undefined;
75
+ }>;
76
+ export type WorkersTailItem = Readonly<{
77
+ logs?: readonly WorkersTailLog[] | undefined;
78
+ }>;
79
+ /**
80
+ * Extracts a `spock` [`Trace`] from Cloudflare Workers `TailItem[]` logs (produced by a Tail
81
+ * Worker or `wrangler tail --format json`), turning existing `console.log({ ... })` Workers
82
+ * Logs directly into conformance traces with zero manual instrumentation.
83
+ */
84
+ export declare function fromWorkersTail(items: readonly WorkersTailItem[], mapper?: RecordMapper<LogRecord>): Trace;
@@ -0,0 +1,272 @@
1
+ import { createTrace } from "./trace.js";
2
+ function emitToTarget(target, line) {
3
+ if (typeof target === "function") {
4
+ target(line);
5
+ }
6
+ else {
7
+ target.push(line);
8
+ }
9
+ }
10
+ function isPlainObject(v) {
11
+ return typeof v === "object" && v !== null && !Array.isArray(v);
12
+ }
13
+ /**
14
+ * Default convention mapper for zero-instrumentation structured logs (Workers Logs, Pino,
15
+ * `console.log({ ... })`, or OTel attributes):
16
+ *
17
+ * - Recognizes `{ event: "init", state: { ... } }` or `{ event: "init", x: 0, ... }`
18
+ * - Recognizes `{ action: "incr", args: ["a"], state: { x: 1 } }` or `{ action: "incr", arg: "a", x: 1 }`
19
+ * - Recognizes `{ state: { ... } }` (unlabeled observation)
20
+ * - Strips common logger metadata keys (`level`, `time`, `timestamp`, `msg`, `message`,
21
+ * `target`, `pid`, `hostname`, `event`, `action`, `args`, `arg`, `spock`) when collecting
22
+ * flat state fields.
23
+ * - Returns `null` for unrelated logs so noisy application logs are safely ignored.
24
+ */
25
+ const IGNORED_META_KEYS = new Set([
26
+ "level",
27
+ "time",
28
+ "timestamp",
29
+ "ts",
30
+ "msg",
31
+ "message",
32
+ "target",
33
+ "logger",
34
+ "service",
35
+ "pid",
36
+ "hostname",
37
+ "event",
38
+ "action",
39
+ "args",
40
+ "arg",
41
+ "state",
42
+ "spock",
43
+ ]);
44
+ export function defaultRecordMapper(record) {
45
+ const event = typeof record["event"] === "string" ? record["event"] : undefined;
46
+ const action = typeof record["action"] === "string" ? record["action"] : undefined;
47
+ const rawState = isPlainObject(record["state"]) ? record["state"] : undefined;
48
+ let args;
49
+ if (Array.isArray(record["args"])) {
50
+ args = record["args"];
51
+ }
52
+ else if (record["arg"] !== undefined) {
53
+ args = [record["arg"]];
54
+ }
55
+ // Extract flat state fields when `state` wasn't passed as a nested object.
56
+ // Preserve explicit `undefined` values so `validateTraceLine` catches broken JS fields
57
+ // instead of silently dropping them into spock wildcards.
58
+ const collectFlatState = () => {
59
+ const flat = {};
60
+ let count = 0;
61
+ for (const [k, v] of Object.entries(record)) {
62
+ if (IGNORED_META_KEYS.has(k))
63
+ continue;
64
+ flat[k] = v;
65
+ count += 1;
66
+ }
67
+ return count > 0 ? flat : undefined;
68
+ };
69
+ if (event === "init") {
70
+ const state = rawState ?? collectFlatState();
71
+ return state !== undefined ? { state } : {};
72
+ }
73
+ if (action !== undefined && action.length > 0) {
74
+ const state = rawState ?? collectFlatState();
75
+ const line = { action };
76
+ if (args !== undefined && args.length > 0)
77
+ line.args = args;
78
+ if (state !== undefined)
79
+ line.state = state;
80
+ return line;
81
+ }
82
+ if (rawState !== undefined) {
83
+ return { state: rawState };
84
+ }
85
+ return null;
86
+ }
87
+ function tryExtractLogObject(args) {
88
+ if (args.length === 0)
89
+ return null;
90
+ // Support `console.log({ ... })` and `console.log("msg", { ... })`
91
+ for (const arg of args) {
92
+ if (isPlainObject(arg))
93
+ return arg;
94
+ if (typeof arg === "string") {
95
+ const trimmed = arg.trim();
96
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
97
+ try {
98
+ const parsed = JSON.parse(trimmed);
99
+ if (isPlainObject(parsed))
100
+ return parsed;
101
+ }
102
+ catch {
103
+ // Not JSON; keep checking remaining arguments.
104
+ }
105
+ }
106
+ }
107
+ }
108
+ return null;
109
+ }
110
+ /**
111
+ * Intercepts existing `console.log`/`info`/`debug` structured JSON logs (e.g. Cloudflare
112
+ * Workers Logs, Pino JSON transport, or plain `console.log({ action, ... })`) with zero
113
+ * changes to application code.
114
+ *
115
+ * Works in both Node and Cloudflare Workers (`workerd`) test environments.
116
+ */
117
+ export function captureConsole(options) {
118
+ const methods = options?.methods ?? ["log", "info", "debug"];
119
+ const mapper = options?.mapper ?? defaultRecordMapper;
120
+ const passthrough = options?.passthrough ?? false;
121
+ const trace = createTrace();
122
+ const target = options?.target;
123
+ const originals = new Map();
124
+ const c = console;
125
+ for (const method of methods) {
126
+ const orig = c[method];
127
+ if (typeof orig !== "function")
128
+ continue;
129
+ originals.set(method, orig);
130
+ c[method] = (...args) => {
131
+ const record = tryExtractLogObject(args);
132
+ if (record !== null) {
133
+ const mapped = mapper(record);
134
+ if (mapped !== null && mapped !== undefined) {
135
+ trace.push(mapped);
136
+ if (target !== undefined)
137
+ emitToTarget(target, mapped);
138
+ }
139
+ }
140
+ if (passthrough) {
141
+ orig.apply(console, args);
142
+ }
143
+ };
144
+ }
145
+ let restored = false;
146
+ const restore = () => {
147
+ if (restored)
148
+ return;
149
+ restored = true;
150
+ for (const [method, orig] of originals) {
151
+ c[method] = orig;
152
+ }
153
+ };
154
+ return {
155
+ trace,
156
+ restore,
157
+ [Symbol.dispose]: restore,
158
+ };
159
+ }
160
+ function defaultMapOtelSpan(span) {
161
+ const attrs = span.attributes;
162
+ // First try the explicit record convention on attributes (`event`, `action`, `state`, ...).
163
+ const direct = defaultRecordMapper(attrs);
164
+ if (direct !== null)
165
+ return direct;
166
+ // Otherwise treat `spock.action` or `spock.init` attributes, or `span.name` + `state.*` attrs.
167
+ const spockInit = attrs["spock.init"] === true || span.name === "init";
168
+ const spockAction = typeof attrs["spock.action"] === "string" ? attrs["spock.action"] : undefined;
169
+ const state = {};
170
+ let hasState = false;
171
+ for (const [k, v] of Object.entries(attrs)) {
172
+ if (k.startsWith("state.")) {
173
+ state[k.slice("state.".length)] = v;
174
+ hasState = true;
175
+ }
176
+ else if (k.startsWith("spock.state.")) {
177
+ state[k.slice("spock.state.".length)] = v;
178
+ hasState = true;
179
+ }
180
+ }
181
+ let args;
182
+ const rawArgs = attrs["spock.args"] ?? attrs["args"];
183
+ if (Array.isArray(rawArgs)) {
184
+ args = rawArgs;
185
+ }
186
+ else if (attrs["spock.arg"] !== undefined) {
187
+ args = [attrs["spock.arg"]];
188
+ }
189
+ if (spockInit) {
190
+ return hasState ? { state } : {};
191
+ }
192
+ if (spockAction !== undefined) {
193
+ const line = { action: spockAction };
194
+ if (args !== undefined && args.length > 0)
195
+ line.args = args;
196
+ if (hasState)
197
+ line.state = state;
198
+ return line;
199
+ }
200
+ if (hasState) {
201
+ const line = { action: span.name };
202
+ if (args !== undefined && args.length > 0)
203
+ line.args = args;
204
+ line.state = state;
205
+ return line;
206
+ }
207
+ return null;
208
+ }
209
+ /**
210
+ * Creates a structural OpenTelemetry `SpanProcessor` (zero `@opentelemetry/*` dependency,
211
+ * safe in both Node and Cloudflare Workers) that converts existing OTel spans and span
212
+ * events into a `spock` trace automatically.
213
+ */
214
+ export function createOtelSpanProcessor(options) {
215
+ const trace = createTrace();
216
+ const mapSpan = options?.mapSpan ?? defaultMapOtelSpan;
217
+ const mapEvent = options?.mapEvent;
218
+ const target = options?.target;
219
+ const record = (line) => {
220
+ if (line === null || line === undefined)
221
+ return;
222
+ trace.push(line);
223
+ if (target !== undefined)
224
+ emitToTarget(target, line);
225
+ };
226
+ return {
227
+ trace,
228
+ onStart() {
229
+ // Captured on span completion so attributes added during execution are present.
230
+ },
231
+ onEnd(span) {
232
+ if (span.events !== undefined && span.events.length > 0) {
233
+ for (const ev of span.events) {
234
+ if (mapEvent !== undefined) {
235
+ record(mapEvent(ev, span));
236
+ }
237
+ else if (ev.attributes !== undefined) {
238
+ record(defaultRecordMapper({ event: ev.name, ...ev.attributes }));
239
+ }
240
+ }
241
+ }
242
+ record(mapSpan(span));
243
+ },
244
+ async forceFlush() { },
245
+ async shutdown() { },
246
+ };
247
+ }
248
+ /**
249
+ * Extracts a `spock` [`Trace`] from Cloudflare Workers `TailItem[]` logs (produced by a Tail
250
+ * Worker or `wrangler tail --format json`), turning existing `console.log({ ... })` Workers
251
+ * Logs directly into conformance traces with zero manual instrumentation.
252
+ */
253
+ export function fromWorkersTail(items, mapper = defaultRecordMapper) {
254
+ const trace = createTrace();
255
+ for (const item of items) {
256
+ if (item.logs === undefined)
257
+ continue;
258
+ for (const entry of item.logs) {
259
+ if (entry.message === undefined)
260
+ continue;
261
+ const record = tryExtractLogObject(entry.message);
262
+ if (record === null)
263
+ continue;
264
+ const line = mapper(record);
265
+ if (line !== null && line !== undefined) {
266
+ trace.push(line);
267
+ }
268
+ }
269
+ }
270
+ return trace;
271
+ }
272
+ //# sourceMappingURL=adapters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapters.js","sourceRoot":"","sources":["../src/adapters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CA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E,CAAC;QACzB,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS;YAAE,SAAS;QACtC,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YAC9B,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS;gBAAE,SAAS;YAC1C,MAAM,MAAM,GAAG,mBAAmB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAClD,IAAI,MAAM,KAAK,IAAI;gBAAE,SAAS;YAC9B,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;YAC5B,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;gBACxC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnB,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { createTrace } from \"./trace.js\";\nimport type { Trace, TraceArgs, TraceLine, TraceState } from \"./types.js\";\n\n/** A structured log object captured from `console`, Pino, Cloudflare Workers Logs, or OTel. */\nexport type LogRecord = Readonly<Record<string, unknown>>;\n\n/** Maps an arbitrary structured log/span record into a `TraceLine`, or `null`/`undefined` to skip. */\nexport type RecordMapper<T = LogRecord> = (record: T) => TraceLine | null | undefined;\n\n/** Destination accepting mapped `TraceLine`s (either a `Trace` builder or a callback/sink). */\nexport type TraceTarget =\n | Trace\n | Readonly<{\n push(line: TraceLine): unknown;\n }>\n | ((line: TraceLine) => unknown);\n\nfunction emitToTarget(target: TraceTarget, line: TraceLine): void {\n if (typeof target === \"function\") {\n target(line);\n } else {\n target.push(line);\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * Default convention mapper for zero-instrumentation structured logs (Workers Logs, Pino,\n * `console.log({ ... })`, or OTel attributes):\n *\n * - Recognizes `{ event: \"init\", state: { ... } }` or `{ event: \"init\", x: 0, ... }`\n * - Recognizes `{ action: \"incr\", args: [\"a\"], state: { x: 1 } }` or `{ action: \"incr\", arg: \"a\", x: 1 }`\n * - Recognizes `{ state: { ... } }` (unlabeled observation)\n * - Strips common logger metadata keys (`level`, `time`, `timestamp`, `msg`, `message`,\n * `target`, `pid`, `hostname`, `event`, `action`, `args`, `arg`, `spock`) when collecting\n * flat state fields.\n * - Returns `null` for unrelated logs so noisy application logs are safely ignored.\n */\nconst IGNORED_META_KEYS = new Set([\n \"level\",\n \"time\",\n \"timestamp\",\n \"ts\",\n \"msg\",\n \"message\",\n \"target\",\n \"logger\",\n \"service\",\n \"pid\",\n \"hostname\",\n \"event\",\n \"action\",\n \"args\",\n \"arg\",\n \"state\",\n \"spock\",\n]);\n\nexport function defaultRecordMapper(record: LogRecord): TraceLine | null {\n const event = typeof record[\"event\"] === \"string\" ? record[\"event\"] : undefined;\n const action = typeof record[\"action\"] === \"string\" ? record[\"action\"] : undefined;\n const rawState = isPlainObject(record[\"state\"]) ? (record[\"state\"] as TraceState) : undefined;\n\n let args: TraceArgs | undefined;\n if (Array.isArray(record[\"args\"])) {\n args = record[\"args\"] as TraceArgs;\n } else if (record[\"arg\"] !== undefined) {\n args = [record[\"arg\"]];\n }\n\n // Extract flat state fields when `state` wasn't passed as a nested object.\n // Preserve explicit `undefined` values so `validateTraceLine` catches broken JS fields\n // instead of silently dropping them into spock wildcards.\n const collectFlatState = (): TraceState | undefined => {\n const flat: Record<string, unknown> = {};\n let count = 0;\n for (const [k, v] of Object.entries(record)) {\n if (IGNORED_META_KEYS.has(k)) continue;\n flat[k] = v;\n count += 1;\n }\n return count > 0 ? flat : undefined;\n };\n\n if (event === \"init\") {\n const state = rawState ?? collectFlatState();\n return state !== undefined ? { state } : {};\n }\n\n if (action !== undefined && action.length > 0) {\n const state = rawState ?? collectFlatState();\n const line: { action: string; args?: TraceArgs; state?: TraceState } = { action };\n if (args !== undefined && args.length > 0) line.args = args;\n if (state !== undefined) line.state = state;\n return line;\n }\n\n if (rawState !== undefined) {\n return { state: rawState };\n }\n\n return null;\n}\n\n/** Options for [`captureConsole`]. */\nexport type ConsoleCaptureOptions = Readonly<{\n /** Console methods to intercept. Defaults to `[\"log\", \"info\", \"debug\"]`. */\n methods?: readonly (\"log\" | \"info\" | \"debug\" | \"warn\")[] | undefined;\n /** Custom mapper from structured log objects to `TraceLine`s. Defaults to `defaultRecordMapper`. */\n mapper?: RecordMapper<LogRecord> | undefined;\n /** Optional target to forward lines to instead of (or in addition to) the returned `trace`. */\n target?: TraceTarget | undefined;\n /** Still forward intercepted calls to the original `console` methods. Defaults to `false`. */\n passthrough?: boolean | undefined;\n}>;\n\n/** Active console capture handle. Call `restore()` (or use `using`) when the test finishes. */\nexport interface ConsoleCapture {\n readonly trace: Trace;\n restore(): void;\n [Symbol.dispose](): void;\n}\n\nfunction tryExtractLogObject(args: readonly unknown[]): LogRecord | null {\n if (args.length === 0) return null;\n // Support `console.log({ ... })` and `console.log(\"msg\", { ... })`\n for (const arg of args) {\n if (isPlainObject(arg)) return arg;\n if (typeof arg === \"string\") {\n const trimmed = arg.trim();\n if (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) {\n try {\n const parsed: unknown = JSON.parse(trimmed);\n if (isPlainObject(parsed)) return parsed;\n } catch {\n // Not JSON; keep checking remaining arguments.\n }\n }\n }\n }\n return null;\n}\n\n/**\n * Intercepts existing `console.log`/`info`/`debug` structured JSON logs (e.g. Cloudflare\n * Workers Logs, Pino JSON transport, or plain `console.log({ action, ... })`) with zero\n * changes to application code.\n *\n * Works in both Node and Cloudflare Workers (`workerd`) test environments.\n */\nexport function captureConsole(options?: ConsoleCaptureOptions | undefined): ConsoleCapture {\n const methods = options?.methods ?? ([\"log\", \"info\", \"debug\"] as const);\n const mapper = options?.mapper ?? defaultRecordMapper;\n const passthrough = options?.passthrough ?? false;\n const trace = createTrace();\n const target = options?.target;\n\n const originals = new Map<string, (...args: unknown[]) => void>();\n const c = console as unknown as Record<string, (...args: unknown[]) => void>;\n\n for (const method of methods) {\n const orig = c[method];\n if (typeof orig !== \"function\") continue;\n originals.set(method, orig);\n c[method] = (...args: unknown[]): void => {\n const record = tryExtractLogObject(args);\n if (record !== null) {\n const mapped = mapper(record);\n if (mapped !== null && mapped !== undefined) {\n trace.push(mapped);\n if (target !== undefined) emitToTarget(target, mapped);\n }\n }\n if (passthrough) {\n orig.apply(console, args);\n }\n };\n }\n\n let restored = false;\n const restore = (): void => {\n if (restored) return;\n restored = true;\n for (const [method, orig] of originals) {\n c[method] = orig;\n }\n };\n\n return {\n trace,\n restore,\n [Symbol.dispose]: restore,\n };\n}\n\n/** Minimal structural OpenTelemetry span event shape (zero `@opentelemetry/*` dependency). */\nexport type OtelSpanEvent = Readonly<{\n name: string;\n attributes?: Readonly<Record<string, unknown>> | undefined;\n}>;\n\n/** Minimal structural OpenTelemetry `ReadableSpan` shape (zero `@opentelemetry/*` dependency). */\nexport type OtelReadableSpan = Readonly<{\n name: string;\n attributes: Readonly<Record<string, unknown>>;\n events?: readonly OtelSpanEvent[] | undefined;\n}>;\n\n/** Structural OpenTelemetry `SpanProcessor` compatible with `@opentelemetry/sdk-trace-base`. */\nexport interface OtelSpanProcessor {\n readonly trace: Trace;\n onStart(span: unknown, parentContext?: unknown): void;\n onEnd(span: OtelReadableSpan): void;\n forceFlush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\n/** Options for [`createOtelSpanProcessor`]. */\nexport type OtelProcessorOptions = Readonly<{\n /** Custom mapper from a completed OTel span to a `TraceLine` (or `null` to ignore). */\n mapSpan?: RecordMapper<OtelReadableSpan> | undefined;\n /** Custom mapper from a span event (`span.addEvent(...)`) to a `TraceLine`. */\n mapEvent?: ((event: OtelSpanEvent, span: OtelReadableSpan) => TraceLine | null | undefined) | undefined;\n /** Optional target to forward lines to in addition to the processor's `trace`. */\n target?: TraceTarget | undefined;\n}>;\n\nfunction defaultMapOtelSpan(span: OtelReadableSpan): TraceLine | null {\n const attrs = span.attributes;\n // First try the explicit record convention on attributes (`event`, `action`, `state`, ...).\n const direct = defaultRecordMapper(attrs);\n if (direct !== null) return direct;\n\n // Otherwise treat `spock.action` or `spock.init` attributes, or `span.name` + `state.*` attrs.\n const spockInit = attrs[\"spock.init\"] === true || span.name === \"init\";\n const spockAction =\n typeof attrs[\"spock.action\"] === \"string\" ? (attrs[\"spock.action\"] as string) : undefined;\n\n const state: Record<string, unknown> = {};\n let hasState = false;\n for (const [k, v] of Object.entries(attrs)) {\n if (k.startsWith(\"state.\")) {\n state[k.slice(\"state.\".length)] = v;\n hasState = true;\n } else if (k.startsWith(\"spock.state.\")) {\n state[k.slice(\"spock.state.\".length)] = v;\n hasState = true;\n }\n }\n\n let args: TraceArgs | undefined;\n const rawArgs = attrs[\"spock.args\"] ?? attrs[\"args\"];\n if (Array.isArray(rawArgs)) {\n args = rawArgs as TraceArgs;\n } else if (attrs[\"spock.arg\"] !== undefined) {\n args = [attrs[\"spock.arg\"]];\n }\n\n if (spockInit) {\n return hasState ? { state } : {};\n }\n if (spockAction !== undefined) {\n const line: { action: string; args?: TraceArgs; state?: TraceState } = { action: spockAction };\n if (args !== undefined && args.length > 0) line.args = args;\n if (hasState) line.state = state;\n return line;\n }\n if (hasState) {\n const line: { action: string; args?: TraceArgs; state?: TraceState } = { action: span.name };\n if (args !== undefined && args.length > 0) line.args = args;\n line.state = state;\n return line;\n }\n return null;\n}\n\n/**\n * Creates a structural OpenTelemetry `SpanProcessor` (zero `@opentelemetry/*` dependency,\n * safe in both Node and Cloudflare Workers) that converts existing OTel spans and span\n * events into a `spock` trace automatically.\n */\nexport function createOtelSpanProcessor(\n options?: OtelProcessorOptions | undefined,\n): OtelSpanProcessor {\n const trace = createTrace();\n const mapSpan = options?.mapSpan ?? defaultMapOtelSpan;\n const mapEvent = options?.mapEvent;\n const target = options?.target;\n\n const record = (line: TraceLine | null | undefined): void => {\n if (line === null || line === undefined) return;\n trace.push(line);\n if (target !== undefined) emitToTarget(target, line);\n };\n\n return {\n trace,\n onStart(): void {\n // Captured on span completion so attributes added during execution are present.\n },\n onEnd(span: OtelReadableSpan): void {\n if (span.events !== undefined && span.events.length > 0) {\n for (const ev of span.events) {\n if (mapEvent !== undefined) {\n record(mapEvent(ev, span));\n } else if (ev.attributes !== undefined) {\n record(defaultRecordMapper({ event: ev.name, ...ev.attributes }));\n }\n }\n }\n record(mapSpan(span));\n },\n async forceFlush(): Promise<void> {},\n async shutdown(): Promise<void> {},\n };\n}\n\n/** Minimal structural Cloudflare Workers `TailItem` shape (`wrangler tail --format json` / Tail Workers). */\nexport type WorkersTailLog = Readonly<{\n message?: readonly unknown[] | undefined;\n level?: string | undefined;\n timestamp?: number | undefined;\n}>;\n\nexport type WorkersTailItem = Readonly<{\n logs?: readonly WorkersTailLog[] | undefined;\n}>;\n\n/**\n * Extracts a `spock` [`Trace`] from Cloudflare Workers `TailItem[]` logs (produced by a Tail\n * Worker or `wrangler tail --format json`), turning existing `console.log({ ... })` Workers\n * Logs directly into conformance traces with zero manual instrumentation.\n */\nexport function fromWorkersTail(\n items: readonly WorkersTailItem[],\n mapper: RecordMapper<LogRecord> = defaultRecordMapper,\n): Trace {\n const trace = createTrace();\n for (const item of items) {\n if (item.logs === undefined) continue;\n for (const entry of item.logs) {\n if (entry.message === undefined) continue;\n const record = tryExtractLogObject(entry.message);\n if (record === null) continue;\n const line = mapper(record);\n if (line !== null && line !== undefined) {\n trace.push(line);\n }\n }\n }\n return trace;\n}\n"]}
package/dist/auto.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { type LogRecord, type RecordMapper } from "./adapters.js";
2
+ import type { ConformOptions } from "./types.js";
3
+ /** Options for [`autoVerifyConsole`], enabling zero-boilerplate closed-loop trace checks in Vitest. */
4
+ export type AutoVerifyConsoleOptions = Readonly<{
5
+ /** Path to the `.spock` specification. */
6
+ spec: string;
7
+ /** Optional model name inside the `.spock` spec. */
8
+ model?: string | undefined;
9
+ /** Console methods to intercept. Defaults to `["log", "info", "debug"]`. */
10
+ methods?: readonly ("log" | "info" | "debug" | "warn")[] | undefined;
11
+ /** Custom mapper from structured log objects to `TraceLine`s. Defaults to `defaultRecordMapper`. */
12
+ mapper?: RecordMapper<LogRecord> | undefined;
13
+ /** Forward intercepted calls to the original console. Defaults to `true`. */
14
+ passthrough?: boolean | undefined;
15
+ /** Require every leaf action reachable from `model.next` across the suite. */
16
+ requireAllActions?: boolean | undefined;
17
+ /** Suite-level action coverage requirement checked in `afterAll`. */
18
+ requireActions?: readonly string[] | undefined;
19
+ /** Require every `State` field to be observed across the suite. */
20
+ requireAllFields?: boolean | undefined;
21
+ /** Suite-level state-field coverage requirement checked in `afterAll`. */
22
+ requireFields?: readonly string[] | undefined;
23
+ /** Suite-level stutter budget checked in `afterAll`. */
24
+ maxStutters?: number | undefined;
25
+ /** Fail `afterAll` if zero tests emitted any trace events. Defaults to `false`. */
26
+ requireAnyTrace?: boolean | undefined;
27
+ /** Timeout passed to `spock trace`. */
28
+ timeoutMs?: number | undefined;
29
+ /** Missing-binary policy passed to `spock trace`. */
30
+ onMissingBinary?: ConformOptions["onMissingBinary"];
31
+ }>;
32
+ /**
33
+ * Installs Vitest `beforeEach`/`afterEach`/`afterAll` hooks that automatically capture
34
+ * existing structured `console` JSON logs during every test and validate each non-empty
35
+ * trace against `spec` via `spock trace` — zero changes to application code or test bodies.
36
+ *
37
+ * Works in both Node and Cloudflare Workers (`workerd`) Vitest suites.
38
+ */
39
+ export declare function autoVerifyConsole(options: AutoVerifyConsoleOptions): void;
package/dist/auto.js ADDED
@@ -0,0 +1,63 @@
1
+ import { afterAll, afterEach, beforeEach } from "vitest";
2
+ import { captureConsole } from "./adapters.js";
3
+ import { createCoverageTracker } from "./coverage.js";
4
+ import { formatConformanceFailure } from "./format.js";
5
+ import { checkTrace } from "./matcher.js";
6
+ /**
7
+ * Installs Vitest `beforeEach`/`afterEach`/`afterAll` hooks that automatically capture
8
+ * existing structured `console` JSON logs during every test and validate each non-empty
9
+ * trace against `spec` via `spock trace` — zero changes to application code or test bodies.
10
+ *
11
+ * Works in both Node and Cloudflare Workers (`workerd`) Vitest suites.
12
+ */
13
+ export function autoVerifyConsole(options) {
14
+ const tracker = createCoverageTracker();
15
+ let active;
16
+ beforeEach(() => {
17
+ active = captureConsole({
18
+ methods: options.methods,
19
+ mapper: options.mapper,
20
+ passthrough: options.passthrough ?? true,
21
+ });
22
+ });
23
+ afterEach(async () => {
24
+ const cap = active;
25
+ active = undefined;
26
+ if (cap === undefined)
27
+ return;
28
+ cap.restore();
29
+ const lines = cap.trace.lines();
30
+ if (lines.length === 0)
31
+ return;
32
+ const report = await checkTrace(cap.trace, options.spec, {
33
+ model: options.model,
34
+ timeoutMs: options.timeoutMs,
35
+ onMissingBinary: options.onMissingBinary,
36
+ });
37
+ if (report.outcome.kind !== "matches") {
38
+ throw new Error(formatConformanceFailure(report, lines, false));
39
+ }
40
+ tracker.record(report, lines);
41
+ });
42
+ afterAll(() => {
43
+ const snap = tracker.snapshot();
44
+ if (options.requireAnyTrace && snap.traces === 0) {
45
+ throw new Error(`vitest-spock autoVerifyConsole: zero tests emitted trace events for ${options.spec}`);
46
+ }
47
+ if (snap.traces > 0 &&
48
+ (options.requireAllActions === true ||
49
+ options.requireActions !== undefined ||
50
+ options.requireAllFields === true ||
51
+ options.requireFields !== undefined ||
52
+ options.maxStutters !== undefined)) {
53
+ tracker.assertCoverage({
54
+ requireAllActions: options.requireAllActions,
55
+ requireActions: options.requireActions,
56
+ requireAllFields: options.requireAllFields,
57
+ requireFields: options.requireFields,
58
+ maxStutters: options.maxStutters,
59
+ });
60
+ }
61
+ });
62
+ }
63
+ //# sourceMappingURL=auto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto.js","sourceRoot":"","sources":["../src/auto.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACzD,OAAO,EAAE,cAAc,EAA0D,MAAM,eAAe,CAAC;AACvG,OAAO,EAAE,qBAAqB,EAA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AC,CAAC;IAEH,QAAQ,CAAC,GAAG,EAAE;QACZ,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;QAChC,IAAI,OAAO,CAAC,eAAe,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACjD,MAAM,IAAI,KAAK,CACb,uEAAuE,OAAO,CAAC,IAAI,EAAE,CACtF,CAAC;QACJ,CAAC;QACD,IACE,IAAI,CAAC,MAAM,GAAG,CAAC;YACf,CAAC,OAAO,CAAC,iBAAiB,KAAK,IAAI;gBACjC,OAAO,CAAC,cAAc,KAAK,SAAS;gBACpC,OAAO,CAAC,gBAAgB,KAAK,IAAI;gBACjC,OAAO,CAAC,aAAa,KAAK,SAAS;gBACnC,OAAO,CAAC,WAAW,KAAK,SAAS,CAAC,EACpC,CAAC;YACD,OAAO,CAAC,cAAc,CAAC;gBACrB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;gBAC5C,cAAc,EAAE,OAAO,CAAC,cAAc;gBACtC,gBAAgB,EAAE,OAAO,CAAC,gBAAgB;gBAC1C,aAAa,EAAE,OAAO,CAAC,aAAa;gBACpC,WAAW,EAAE,OAAO,CAAC,WAAW;aACjC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { afterAll, afterEach, beforeEach } from \"vitest\";\nimport { captureConsole, type ConsoleCapture, type LogRecord, type RecordMapper } from \"./adapters.js\";\nimport { createCoverageTracker } from \"./coverage.js\";\nimport { formatConformanceFailure } from \"./format.js\";\nimport { checkTrace } from \"./matcher.js\";\nimport type { ConformOptions } from \"./types.js\";\n\n/** Options for [`autoVerifyConsole`], enabling zero-boilerplate closed-loop trace checks in Vitest. */\nexport type AutoVerifyConsoleOptions = Readonly<{\n /** Path to the `.spock` specification. */\n spec: string;\n /** Optional model name inside the `.spock` spec. */\n model?: string | undefined;\n /** Console methods to intercept. Defaults to `[\"log\", \"info\", \"debug\"]`. */\n methods?: readonly (\"log\" | \"info\" | \"debug\" | \"warn\")[] | undefined;\n /** Custom mapper from structured log objects to `TraceLine`s. Defaults to `defaultRecordMapper`. */\n mapper?: RecordMapper<LogRecord> | undefined;\n /** Forward intercepted calls to the original console. Defaults to `true`. */\n passthrough?: boolean | undefined;\n /** Require every leaf action reachable from `model.next` across the suite. */\n requireAllActions?: boolean | undefined;\n /** Suite-level action coverage requirement checked in `afterAll`. */\n requireActions?: readonly string[] | undefined;\n /** Require every `State` field to be observed across the suite. */\n requireAllFields?: boolean | undefined;\n /** Suite-level state-field coverage requirement checked in `afterAll`. */\n requireFields?: readonly string[] | undefined;\n /** Suite-level stutter budget checked in `afterAll`. */\n maxStutters?: number | undefined;\n /** Fail `afterAll` if zero tests emitted any trace events. Defaults to `false`. */\n requireAnyTrace?: boolean | undefined;\n /** Timeout passed to `spock trace`. */\n timeoutMs?: number | undefined;\n /** Missing-binary policy passed to `spock trace`. */\n onMissingBinary?: ConformOptions[\"onMissingBinary\"];\n}>;\n\n/**\n * Installs Vitest `beforeEach`/`afterEach`/`afterAll` hooks that automatically capture\n * existing structured `console` JSON logs during every test and validate each non-empty\n * trace against `spec` via `spock trace` — zero changes to application code or test bodies.\n *\n * Works in both Node and Cloudflare Workers (`workerd`) Vitest suites.\n */\nexport function autoVerifyConsole(options: AutoVerifyConsoleOptions): void {\n const tracker = createCoverageTracker();\n let active: ConsoleCapture | undefined;\n\n beforeEach(() => {\n active = captureConsole({\n methods: options.methods,\n mapper: options.mapper,\n passthrough: options.passthrough ?? true,\n });\n });\n\n afterEach(async () => {\n const cap = active;\n active = undefined;\n if (cap === undefined) return;\n cap.restore();\n const lines = cap.trace.lines();\n if (lines.length === 0) return;\n\n const report = await checkTrace(cap.trace, options.spec, {\n model: options.model,\n timeoutMs: options.timeoutMs,\n onMissingBinary: options.onMissingBinary,\n });\n if (report.outcome.kind !== \"matches\") {\n throw new Error(formatConformanceFailure(report, lines, false));\n }\n tracker.record(report, lines);\n });\n\n afterAll(() => {\n const snap = tracker.snapshot();\n if (options.requireAnyTrace && snap.traces === 0) {\n throw new Error(\n `vitest-spock autoVerifyConsole: zero tests emitted trace events for ${options.spec}`,\n );\n }\n if (\n snap.traces > 0 &&\n (options.requireAllActions === true ||\n options.requireActions !== undefined ||\n options.requireAllFields === true ||\n options.requireFields !== undefined ||\n options.maxStutters !== undefined)\n ) {\n tracker.assertCoverage({\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"]}
@@ -1,3 +1,4 @@
1
+ import { type LogRecord, type RecordMapper, type WorkersTailItem } from "../adapters.js";
1
2
  import type { TraceArgs, TraceLine, TraceState } from "../types.js";
2
3
  /** Default Cloudflare service binding name used by `vitest-spock/cloudflare`. */
3
4
  export declare const DEFAULT_SPOCK_BINDING = "SPOCK_TRACE";
@@ -36,3 +37,25 @@ export interface TraceSink {
36
37
  * instrumenting DO methods or alarms has zero runtime overhead in deployed Workers.
37
38
  */
38
39
  export declare function createTraceSink(env: Readonly<Record<string, unknown>> | undefined, session: string, binding?: string): TraceSink;
40
+ /** Options for [`forwardWorkersTail`] and [`createSpockTailHandler`]. */
41
+ export type SpockTailHandlerOptions = Readonly<{
42
+ /** Host trace session name (`startSpockSession(session)`). Defaults to `"default"`. */
43
+ session?: string | undefined;
44
+ /** Service binding name (`spockServiceBinding(...)`). Defaults to `"SPOCK_TRACE"`. */
45
+ binding?: string | undefined;
46
+ /** Custom mapper from structured log records to `TraceLine`s. Defaults to `defaultRecordMapper`. */
47
+ mapper?: RecordMapper<LogRecord> | undefined;
48
+ }>;
49
+ /**
50
+ * Extract structured trace lines from Cloudflare Workers `TailItem[]` logs and forward them
51
+ * to the host `SPOCK_TRACE` session. No-op in production when `env[binding]` is absent.
52
+ */
53
+ export declare function forwardWorkersTail(events: readonly WorkersTailItem[], env: Readonly<Record<string, unknown>> | undefined, options?: SpockTailHandlerOptions | undefined): Promise<number>;
54
+ /**
55
+ * One-line Cloudflare Tail Worker module (`export default createSpockTailHandler(...)`) that
56
+ * automatically streams existing `console.log({ ... })` Workers Logs from any auxiliary
57
+ * Worker or Durable Object into a `vitest-spock` host session with zero manual instrumentation.
58
+ */
59
+ export declare function createSpockTailHandler(options?: SpockTailHandlerOptions | undefined): {
60
+ tail(events: readonly WorkersTailItem[], env?: Readonly<Record<string, unknown>>): Promise<void>;
61
+ };
@@ -1,3 +1,5 @@
1
+ import { defaultRecordMapper, fromWorkersTail, } from "../adapters.js";
2
+ import { validateTraceLine } from "../trace.js";
1
3
  /** Default Cloudflare service binding name used by `vitest-spock/cloudflare`. */
2
4
  export const DEFAULT_SPOCK_BINDING = "SPOCK_TRACE";
3
5
  function getFetcher(env, binding) {
@@ -22,6 +24,7 @@ export async function emitSpock(env, session, line, binding = DEFAULT_SPOCK_BIND
22
24
  const fetcher = getFetcher(env, binding);
23
25
  if (fetcher === undefined)
24
26
  return;
27
+ validateTraceLine(line);
25
28
  await fetcher.fetch("https://spock.internal/emit", {
26
29
  method: "POST",
27
30
  headers: { "content-type": "application/json" },
@@ -46,6 +49,7 @@ export function createTraceSink(env, session, binding = DEFAULT_SPOCK_BINDING) {
46
49
  if (fetcher === undefined)
47
50
  return NOOP_SINK;
48
51
  const send = async (line) => {
52
+ validateTraceLine(line);
49
53
  await fetcher.fetch("https://spock.internal/emit", {
50
54
  method: "POST",
51
55
  headers: { "content-type": "application/json" },
@@ -76,4 +80,32 @@ export function createTraceSink(env, session, binding = DEFAULT_SPOCK_BINDING) {
76
80
  },
77
81
  };
78
82
  }
83
+ /**
84
+ * Extract structured trace lines from Cloudflare Workers `TailItem[]` logs and forward them
85
+ * to the host `SPOCK_TRACE` session. No-op in production when `env[binding]` is absent.
86
+ */
87
+ export async function forwardWorkersTail(events, env, options) {
88
+ const binding = options?.binding ?? DEFAULT_SPOCK_BINDING;
89
+ const fetcher = getFetcher(env, binding);
90
+ if (fetcher === undefined)
91
+ return 0;
92
+ const session = options?.session ?? "default";
93
+ const lines = fromWorkersTail(events, options?.mapper ?? defaultRecordMapper).lines();
94
+ for (const line of lines) {
95
+ await emitSpock(env, session, line, binding);
96
+ }
97
+ return lines.length;
98
+ }
99
+ /**
100
+ * One-line Cloudflare Tail Worker module (`export default createSpockTailHandler(...)`) that
101
+ * automatically streams existing `console.log({ ... })` Workers Logs from any auxiliary
102
+ * Worker or Durable Object into a `vitest-spock` host session with zero manual instrumentation.
103
+ */
104
+ export function createSpockTailHandler(options) {
105
+ return {
106
+ async tail(events, env) {
107
+ await forwardWorkersTail(events, env, options);
108
+ },
109
+ };
110
+ }
79
111
  //# sourceMappingURL=emitter.js.map