@specific.dev/spectest 0.58.0 → 0.59.1

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.
@@ -0,0 +1,142 @@
1
+ import type { ServiceConfig } from "./index.js";
2
+ import { COVERAGE_CONTAINER_DIR } from "./harness/coverage.js";
3
+ export { COVERAGE_CONTAINER_DIR };
4
+ /** Where `node()` mounts its hook inside the container. */
5
+ export declare const NODE_COVERAGE_HOOK_PATH = "/spectest/coverage-hook.cjs";
6
+ /** The socket the node hook answers on, relative to the coverage dir. */
7
+ export declare const NODE_COVERAGE_SOCKET = ".ctl";
8
+ /** What `configure` learns about the service it rewrites. */
9
+ export interface CoverageConfigureInfo {
10
+ /** The services-map key. */
11
+ key: string;
12
+ }
13
+ /** The harness capabilities an adapter can ask for at `/load`. */
14
+ export interface CoverageLoadContext {
15
+ /** The services-map key. */
16
+ service: string;
17
+ /**
18
+ * Collect V8 coverage for every script the guest browser
19
+ * (`ctx.browser()` / `ctx.mobile()`) loads from this service's origins:
20
+ * its key, `<key>.internal`, its `hostnames`/`dnsName` aliases, its
21
+ * `tls`/`proxy` hostnames and any service-targeted wildcard. The
22
+ * harness maps each script back to source through the served source
23
+ * map and keeps per-service totals in memory (they fork with the
24
+ * environment). `browser()` calls this and writes the totals
25
+ * at capture.
26
+ */
27
+ collectBrowserScripts(): void;
28
+ }
29
+ /** What one adapter's `capture` runs against. */
30
+ export interface CoverageCaptureContext {
31
+ /** The services-map key. */
32
+ service: string;
33
+ /**
34
+ * The coverage directory, seen from the harness. It is the same
35
+ * directory the container sees at `/spectest/coverage/` (a bind
36
+ * mount), so a file written here is in the container and a socket the
37
+ * container bound here is reachable.
38
+ */
39
+ reportDir: string;
40
+ /** Run a shell command (`sh -c`) inside the container. Rejects on a
41
+ * non-zero exit with the command's output in the message. */
42
+ exec(command: string): Promise<{
43
+ stdout: string;
44
+ stderr: string;
45
+ }>;
46
+ /** Write one report file (name relative to the directory). */
47
+ writeReport(name: string, content: string): Promise<void>;
48
+ /** Aborts when the per-service capture budget runs out. */
49
+ signal: AbortSignal;
50
+ }
51
+ export interface CoverageAdapter {
52
+ /** Names the adapter in errors (`coverage adapter "node" on service …`). */
53
+ name: string;
54
+ /**
55
+ * Rewrite the service at config time. Must be pure and deterministic
56
+ * (the result is hashed into the warm-template key) and must **append**
57
+ * to `env` values like `NODE_OPTIONS` rather than replace them.
58
+ */
59
+ configure?(service: ServiceConfig, info: CoverageConfigureInfo): ServiceConfig;
60
+ /** Ask the harness for capabilities, at `/load`. */
61
+ load?(ctx: CoverageLoadContext): void | Promise<void>;
62
+ /** Make the report appear in the directory. A throw fails the test. */
63
+ capture?(ctx: CoverageCaptureContext): void | Promise<void>;
64
+ }
65
+ /** `ServiceConfig.coverage`: the program writes its own reports, or a
66
+ * list of adapters gets them out. */
67
+ export type ServiceCoverage = true | {
68
+ adapters: readonly CoverageAdapter[];
69
+ };
70
+ /** Type an inline adapter. Identity at runtime. */
71
+ export declare function defineAdapter(adapter: CoverageAdapter): CoverageAdapter;
72
+ /** Check one service's `coverage` field. Exported so the daemon applies
73
+ * the same rule to a runtime `startService` spec. */
74
+ export declare function validateCoverage(service: string, cov: unknown): void;
75
+ /** The adapters of a `coverage` value (`true` has none). */
76
+ export declare function coverageAdapters(cov: ServiceCoverage | undefined): readonly CoverageAdapter[];
77
+ /**
78
+ * Apply every adapter's `configure` to a service, in list order. Called by
79
+ * `defineEnvironment` (after group expansion, before validation) and by
80
+ * the daemon for a runtime `startService` spec. The adapter list stays on
81
+ * the returned config for the harness; on the wire it serializes as the
82
+ * adapter names (`toJSON`), never as functions.
83
+ */
84
+ export declare function applyCoverageAdapters<S extends ServiceConfig>(key: string, svc: S): S;
85
+ /** `env` with `value` appended to `name` (space-separated), or set. */
86
+ export declare function appendEnvFlag(env: Readonly<Record<string, string>> | undefined, name: string, value: string): Record<string, string>;
87
+ /**
88
+ * The hook `node()` mounts and `--require`s into every node
89
+ * process of the container. Node writes V8 coverage JSON into
90
+ * `NODE_V8_COVERAGE` when a process exits; a long-lived server never
91
+ * exits, so the hook binds a Unix socket in the coverage directory and
92
+ * calls `v8.takeCoverage()` for each connection. The first process to
93
+ * start owns the socket (a stale socket left by a dead process is
94
+ * reclaimed); a later process — a CLI run by `ctx.exec` — leaves it
95
+ * alone and writes at its own exit. No signal is used: signals are
96
+ * claimed by frameworks (SIGUSR2 stops a Temporal worker, restarts
97
+ * nodemon), a socket is nobody's.
98
+ */
99
+ export declare const NODE_COVERAGE_HOOK: string;
100
+ /**
101
+ * Coverage for a Node service. Sets `NODE_V8_COVERAGE` to the coverage
102
+ * directory (every node process in the container then writes V8
103
+ * coverage JSON when it exits) and `--require`s a hook that lets spectest
104
+ * ask the long-lived server process for a dump at capture time. Nothing
105
+ * for the app to write. Each dump is compacted to the app's own scripts
106
+ * at capture ({@link compactV8Document}). Source maps: with `--enable-source-maps` (or a
107
+ * `sourceMappingURL` next to the file) Node records the map in the
108
+ * report, which is what maps a TypeScript service back to its sources.
109
+ */
110
+ export declare function node(): CoverageAdapter;
111
+ /** A script is the app's own when it is a file outside node_modules. */
112
+ export declare function isAppScriptUrl(url: string): boolean;
113
+ /**
114
+ * Compact one V8 coverage document to the app's own scripts. What Node
115
+ * writes is everything the process loaded: `node:` internals, every
116
+ * `node_modules` file, and — under `--enable-source-maps` — a
117
+ * `source-map-cache` with each file's full map **and its sources**,
118
+ * repeated in every dump. Measured on a real project: a 12–20 MiB dump
119
+ * per capture, of which the app's own coverage was under 0.5 MiB, and a
120
+ * suite that hit the 64 MiB cap on its third test. Kept: `file://`
121
+ * scripts outside `node_modules`, the map entries of exactly those
122
+ * scripts, minus `sourcesContent` (the sources are the repo). Still a V8
123
+ * document — nothing is converted.
124
+ */
125
+ export declare function compactV8Document(doc: Record<string, unknown>): Record<string, unknown>;
126
+ /** Compact every not-yet-compacted V8 document in `dir`, in place. */
127
+ export declare function compactV8Reports(dir: string): Promise<void>;
128
+ /**
129
+ * Coverage for the frontend a service serves. The code runs in the guest
130
+ * browser — spectest's own process — so no report can be written by the
131
+ * container; spectest collects V8 coverage for every script the browser
132
+ * loads from this service's origins, maps it back to source through the
133
+ * served source map, and writes one lcov per capture. Nothing ran yet on
134
+ * this branch ⇒ an lcov with no records, which is a report saying so.
135
+ */
136
+ export declare function browser(): CoverageAdapter;
137
+ /**
138
+ * Run `command` (via `sh -c`) in the container at every capture, so the
139
+ * service writes a fresh report into `/spectest/coverage/`. The escape
140
+ * hatch for a runtime with no shipped adapter.
141
+ */
142
+ export declare function command(command: string): CoverageAdapter;
@@ -0,0 +1,314 @@
1
+ // Coverage adapters — how spectest gets a coverage report out of a service.
2
+ //
3
+ // A service opts in with `coverage: true` (the program writes its own
4
+ // reports into `/spectest/coverage/`) or `coverage: { adapters: [...] }`
5
+ // (spectest gets the reports out). An adapter has three optional moments:
6
+ //
7
+ // configure — config time, inside `defineEnvironment`. Rewrites the
8
+ // service (env, files, command). Pure: its output is part
9
+ // of the wire config and of the warm-template hash.
10
+ // load — harness, at /load. Asks the harness for capabilities a
11
+ // container cannot supply itself (browser scripts).
12
+ // capture — harness, after bring-up and after every test. Must leave
13
+ // a report in the directory.
14
+ //
15
+ // After every adapter ran, the harness reads the directory the same way
16
+ // it does for `coverage: true`: at least one well-formed report (lcov or
17
+ // V8 JSON), shipped verbatim. Adapters convert nothing — the control
18
+ // plane derives what it needs from the stored bytes.
19
+ //
20
+ // Imported from `@specific.dev/spectest/coverage`. The three shipped
21
+ // adapters: `node()` (V8 JSON through a hook spectest mounts), `browser()`
22
+ // (scripts the guest browser loads from the service), `command(cmd)` (run
23
+ // a command, then read). A project writes its own with `defineAdapter`.
24
+ //
25
+ // import * as coverage from "@specific.dev/spectest/coverage";
26
+ // coverage: { adapters: [coverage.node(), coverage.browser()] }
27
+ import { browserCoverageReports } from "./browser-coverage.js";
28
+ import { COVERAGE_CONTAINER_DIR } from "./harness/coverage.js";
29
+ export { COVERAGE_CONTAINER_DIR };
30
+ /** Where `node()` mounts its hook inside the container. */
31
+ export const NODE_COVERAGE_HOOK_PATH = "/spectest/coverage-hook.cjs";
32
+ /** The socket the node hook answers on, relative to the coverage dir. */
33
+ export const NODE_COVERAGE_SOCKET = ".ctl";
34
+ /** Type an inline adapter. Identity at runtime. */
35
+ export function defineAdapter(adapter) {
36
+ return adapter;
37
+ }
38
+ /** Check one service's `coverage` field. Exported so the daemon applies
39
+ * the same rule to a runtime `startService` spec. */
40
+ export function validateCoverage(service, cov) {
41
+ if (cov === undefined || cov === true)
42
+ return;
43
+ const adapters = cov?.adapters;
44
+ if (typeof cov === "object" && cov !== null && Array.isArray(adapters)) {
45
+ for (const a of adapters) {
46
+ const ok = typeof a === "object" &&
47
+ a !== null &&
48
+ typeof a.name === "string" &&
49
+ a.name.length > 0 &&
50
+ ["configure", "load", "capture"].every((k) => a[k] === undefined ||
51
+ typeof a[k] === "function");
52
+ if (!ok) {
53
+ throw new Error(`service "${service}" has an invalid coverage adapter — an adapter is \`{ name, configure?, load?, capture? }\` (see \`defineAdapter\` in @specific.dev/spectest/coverage)`);
54
+ }
55
+ }
56
+ return;
57
+ }
58
+ throw new Error(`service "${service}" has an invalid \`coverage\` value — use \`true\` (the program writes its own reports) or \`{ adapters: [...] }\` from @specific.dev/spectest/coverage (\`node()\`, \`browser()\`, \`command("…")\`)`);
59
+ }
60
+ /** The adapters of a `coverage` value (`true` has none). */
61
+ export function coverageAdapters(cov) {
62
+ return typeof cov === "object" && cov !== null ? cov.adapters : [];
63
+ }
64
+ /**
65
+ * Apply every adapter's `configure` to a service, in list order. Called by
66
+ * `defineEnvironment` (after group expansion, before validation) and by
67
+ * the daemon for a runtime `startService` spec. The adapter list stays on
68
+ * the returned config for the harness; on the wire it serializes as the
69
+ * adapter names (`toJSON`), never as functions.
70
+ */
71
+ export function applyCoverageAdapters(key, svc) {
72
+ validateCoverage(key, svc.coverage);
73
+ const adapters = coverageAdapters(svc.coverage);
74
+ if (adapters.length === 0)
75
+ return svc;
76
+ let out = svc;
77
+ for (const a of adapters) {
78
+ if (a.configure)
79
+ out = a.configure(out, { key });
80
+ }
81
+ const wire = { adapters: adapters.map((a) => withWireName(a)) };
82
+ return { ...out, coverage: wire };
83
+ }
84
+ function withWireName(a) {
85
+ if (Object.prototype.hasOwnProperty.call(a, "toJSON"))
86
+ return a;
87
+ return Object.assign(Object.create(Object.getPrototypeOf(a)), a, {
88
+ toJSON: () => ({ adapter: a.name }),
89
+ });
90
+ }
91
+ /** `env` with `value` appended to `name` (space-separated), or set. */
92
+ export function appendEnvFlag(env, name, value) {
93
+ const prior = env?.[name]?.trim();
94
+ return { ...env, [name]: prior ? `${prior} ${value}` : value };
95
+ }
96
+ // ── node ──────────────────────────────────────────────────────────
97
+ /**
98
+ * The hook `node()` mounts and `--require`s into every node
99
+ * process of the container. Node writes V8 coverage JSON into
100
+ * `NODE_V8_COVERAGE` when a process exits; a long-lived server never
101
+ * exits, so the hook binds a Unix socket in the coverage directory and
102
+ * calls `v8.takeCoverage()` for each connection. The first process to
103
+ * start owns the socket (a stale socket left by a dead process is
104
+ * reclaimed); a later process — a CLI run by `ctx.exec` — leaves it
105
+ * alone and writes at its own exit. No signal is used: signals are
106
+ * claimed by frameworks (SIGUSR2 stops a Temporal worker, restarts
107
+ * nodemon), a socket is nobody's.
108
+ */
109
+ export const NODE_COVERAGE_HOOK = `"use strict";
110
+ // spectest coverage hook (coverage.node() adapter). See \`spectest docs /services/coverage\`.
111
+ if (process.env.NODE_V8_COVERAGE) {
112
+ const net = require("node:net");
113
+ const fs = require("node:fs");
114
+ const v8 = require("node:v8");
115
+ const SOCK = require("node:path").join(process.env.NODE_V8_COVERAGE, ${JSON.stringify(NODE_COVERAGE_SOCKET)});
116
+ const server = net.createServer((conn) => {
117
+ // A dump is taken only on an explicit "dump" request: a bystander's
118
+ // liveness probe connects and closes without one.
119
+ let buf = "";
120
+ conn.on("data", (chunk) => {
121
+ buf += chunk;
122
+ if (!buf.includes("\\n")) return;
123
+ let reply;
124
+ try {
125
+ if (!buf.startsWith("dump")) throw new Error("unknown request");
126
+ v8.takeCoverage();
127
+ reply = "ok\\n";
128
+ } catch (err) {
129
+ reply = "error " + (err && err.message ? err.message : String(err)) + "\\n";
130
+ }
131
+ conn.end(reply);
132
+ });
133
+ });
134
+ server.unref();
135
+ server.on("error", (err) => {
136
+ if (err.code !== "EADDRINUSE") return;
137
+ // Someone holds the socket. If it answers, it is the live server and
138
+ // this process is a bystander; if not, it is a stale file.
139
+ const probe = net.connect(SOCK);
140
+ probe.on("connect", () => probe.destroy());
141
+ probe.on("error", () => {
142
+ try { fs.unlinkSync(SOCK); } catch {}
143
+ server.listen(SOCK);
144
+ });
145
+ });
146
+ server.listen(SOCK);
147
+ }
148
+ `;
149
+ /**
150
+ * Coverage for a Node service. Sets `NODE_V8_COVERAGE` to the coverage
151
+ * directory (every node process in the container then writes V8
152
+ * coverage JSON when it exits) and `--require`s a hook that lets spectest
153
+ * ask the long-lived server process for a dump at capture time. Nothing
154
+ * for the app to write. Each dump is compacted to the app's own scripts
155
+ * at capture ({@link compactV8Document}). Source maps: with `--enable-source-maps` (or a
156
+ * `sourceMappingURL` next to the file) Node records the map in the
157
+ * report, which is what maps a TypeScript service back to its sources.
158
+ */
159
+ export function node() {
160
+ return {
161
+ name: "node",
162
+ configure(svc) {
163
+ const env = appendEnvFlag(svc.env, "NODE_OPTIONS", `--require ${NODE_COVERAGE_HOOK_PATH}`);
164
+ env.NODE_V8_COVERAGE = COVERAGE_CONTAINER_DIR;
165
+ return {
166
+ ...svc,
167
+ env,
168
+ files: [...(svc.files ?? []), { path: NODE_COVERAGE_HOOK_PATH, content: NODE_COVERAGE_HOOK }],
169
+ };
170
+ },
171
+ async capture(ctx) {
172
+ const { connect } = await import("node:net");
173
+ const path = await import("node:path");
174
+ const sock = path.join(ctx.reportDir, NODE_COVERAGE_SOCKET);
175
+ const reply = await new Promise((resolve, reject) => {
176
+ const chunks = [];
177
+ const c = connect(sock, () => c.write("dump\n"));
178
+ const onAbort = () => {
179
+ c.destroy();
180
+ reject(new Error("timed out waiting for the node hook to write a report"));
181
+ };
182
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
183
+ c.on("data", (b) => chunks.push(b));
184
+ c.on("error", (err) => {
185
+ ctx.signal.removeEventListener("abort", onAbort);
186
+ reject(new Error(err.code === "ENOENT" || err.code === "ECONNREFUSED"
187
+ ? `no node process is serving ${COVERAGE_CONTAINER_DIR}/${NODE_COVERAGE_SOCKET} — is the service's main process node, and does it run with the service's env (NODE_OPTIONS)?`
188
+ : err.message));
189
+ });
190
+ c.on("close", () => {
191
+ ctx.signal.removeEventListener("abort", onAbort);
192
+ resolve(Buffer.concat(chunks).toString("utf8").trim());
193
+ });
194
+ });
195
+ if (reply !== "ok")
196
+ throw new Error(`the node hook answered: ${reply || "(nothing)"}`);
197
+ await compactV8Reports(ctx.reportDir);
198
+ },
199
+ };
200
+ }
201
+ /** V8 files already compacted, by path. Module memory: forks with the
202
+ * environment, so a child never re-parses its ancestors' dumps. */
203
+ const COMPACTED_V8_REPORTS = new Set();
204
+ /** A script is the app's own when it is a file outside node_modules. */
205
+ export function isAppScriptUrl(url) {
206
+ return url.startsWith("file://") && !url.includes("/node_modules/");
207
+ }
208
+ /**
209
+ * Compact one V8 coverage document to the app's own scripts. What Node
210
+ * writes is everything the process loaded: `node:` internals, every
211
+ * `node_modules` file, and — under `--enable-source-maps` — a
212
+ * `source-map-cache` with each file's full map **and its sources**,
213
+ * repeated in every dump. Measured on a real project: a 12–20 MiB dump
214
+ * per capture, of which the app's own coverage was under 0.5 MiB, and a
215
+ * suite that hit the 64 MiB cap on its third test. Kept: `file://`
216
+ * scripts outside `node_modules`, the map entries of exactly those
217
+ * scripts, minus `sourcesContent` (the sources are the repo). Still a V8
218
+ * document — nothing is converted.
219
+ */
220
+ export function compactV8Document(doc) {
221
+ const result = Array.isArray(doc.result) ? doc.result : [];
222
+ const kept = result.filter((s) => typeof s.url === "string" && isAppScriptUrl(s.url));
223
+ const out = { ...doc, result: kept };
224
+ const cache = doc["source-map-cache"];
225
+ if (cache && typeof cache === "object") {
226
+ const urls = new Set(kept.map((s) => s.url));
227
+ const slim = {};
228
+ for (const [url, entry] of Object.entries(cache)) {
229
+ if (!urls.has(url) || !entry || typeof entry !== "object")
230
+ continue;
231
+ const e = { ...entry };
232
+ if (e.data && typeof e.data === "object") {
233
+ const { sourcesContent: _dropped, ...data } = e.data;
234
+ e.data = data;
235
+ }
236
+ slim[url] = e;
237
+ }
238
+ if (Object.keys(slim).length > 0)
239
+ out["source-map-cache"] = slim;
240
+ else
241
+ delete out["source-map-cache"];
242
+ }
243
+ return out;
244
+ }
245
+ /** Compact every not-yet-compacted V8 document in `dir`, in place. */
246
+ export async function compactV8Reports(dir) {
247
+ const fs = await import("node:fs/promises");
248
+ const path = await import("node:path");
249
+ let names;
250
+ try {
251
+ names = await fs.readdir(dir);
252
+ }
253
+ catch {
254
+ return;
255
+ }
256
+ for (const name of names) {
257
+ if (!name.startsWith("coverage-") || !name.endsWith(".json"))
258
+ continue;
259
+ const file = path.join(dir, name);
260
+ if (COMPACTED_V8_REPORTS.has(file))
261
+ continue;
262
+ let doc;
263
+ try {
264
+ doc = JSON.parse(await fs.readFile(file, "utf8"));
265
+ }
266
+ catch {
267
+ continue; // a dump mid-write, or not ours; the read path judges it
268
+ }
269
+ if (!Array.isArray(doc.result))
270
+ continue;
271
+ const tmp = path.join(dir, `.${name}.compact`);
272
+ await fs.writeFile(tmp, JSON.stringify(compactV8Document(doc)));
273
+ await fs.rename(tmp, file);
274
+ COMPACTED_V8_REPORTS.add(file);
275
+ }
276
+ }
277
+ // ── browser ───────────────────────────────────────────────────────
278
+ /**
279
+ * Coverage for the frontend a service serves. The code runs in the guest
280
+ * browser — spectest's own process — so no report can be written by the
281
+ * container; spectest collects V8 coverage for every script the browser
282
+ * loads from this service's origins, maps it back to source through the
283
+ * served source map, and writes one lcov per capture. Nothing ran yet on
284
+ * this branch ⇒ an lcov with no records, which is a report saying so.
285
+ */
286
+ export function browser() {
287
+ return {
288
+ name: "browser",
289
+ load(ctx) {
290
+ ctx.collectBrowserScripts();
291
+ },
292
+ async capture(ctx) {
293
+ const lcov = browserCoverageReports().get(ctx.service) ?? "TN:\n";
294
+ await ctx.writeReport("browser.lcov", lcov);
295
+ },
296
+ };
297
+ }
298
+ // ── command ───────────────────────────────────────────────────────
299
+ /**
300
+ * Run `command` (via `sh -c`) in the container at every capture, so the
301
+ * service writes a fresh report into `/spectest/coverage/`. The escape
302
+ * hatch for a runtime with no shipped adapter.
303
+ */
304
+ export function command(command) {
305
+ if (typeof command !== "string" || command.trim().length === 0) {
306
+ throw new Error("coverage.command: `command` must be a non-empty shell command");
307
+ }
308
+ return {
309
+ name: "command",
310
+ async capture(ctx) {
311
+ await ctx.exec(command);
312
+ },
313
+ };
314
+ }