supercov-engine 0.0.10

Rust instrumentation, evidence, attribution, and query engine for Supercov
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import childProcess from "node:child_process";
import { createHash } from "node:crypto";
import { appendFileSync, mkdirSync } from "node:fs";
import Module, { syncBuiltinESMExports } from "node:module";
import { dirname, isAbsolute, relative, resolve } from "node:path";
import { pathToFileURL } from "node:url";
const HOST_PATH_KEYS = ["hostPath", "source", "src", "localPath"];
const GUEST_PATH_KEYS = [
    "guestPath",
    "target",
    "destination",
    "containerPath",
];
const CACHE_IDENTITY = /^(?:warmup|snapshot|cache)(?:key|tag|id)$/i;
const patchedBuilders = new WeakSet();
const exportedValues = new WeakSet();
const capabilityProxies = new WeakMap();
const importedCapabilityProxies = new WeakMap();
let installed = false;
let remoteLaunchSequence = 0;
function executionLogPath(path) {
    const shard = (process.env["SUPERCOV_EXECUTION_LOG_SHARD"] ?? "host").replace(/[^A-Za-z0-9_.-]/g, "_");
    const suffix = `.${shard}.${process.pid}.jsonl`;
    return path.endsWith(".jsonl")
        ? `${path.slice(0, -".jsonl".length)}${suffix}`
        : `${path}${suffix}`;
}
function record(value) {
    const configuredPath = process.env["SUPERCOV_EXECUTION_LOG"];
    if (!configuredPath)
        return;
    const path = executionLogPath(configuredPath);
    try {
        mkdirSync(dirname(path), { recursive: true });
        appendFileSync(path, `${JSON.stringify({
            at: new Date().toISOString(),
            pid: process.pid,
            ppid: process.ppid,
            ...value,
        })}\n`);
    }
    catch {
        // Process tracing is diagnostic and must never change test behavior.
    }
}
function safeArgument(value) {
    if (value.length <= 160 && !value.includes("\n") && !value.includes("\r"))
        return value;
    return {
        bytes: Buffer.byteLength(value),
        sha256: createHash("sha256").update(value).digest("hex"),
    };
}
function commandSummary(argv) {
    return {
        executable: argv[0] ? safeArgument(argv[0]) : undefined,
        arguments: argv.slice(1, 9).map(safeArgument),
        argumentCount: Math.max(0, argv.length - 1),
    };
}
function stringProperty(value, keys) {
    for (const key of keys) {
        const candidate = value[key];
        if (typeof candidate === "string" && candidate.length > 0)
            return candidate;
    }
    return undefined;
}
function containsPath(parent, child) {
    const local = relative(resolve(parent), resolve(child));
    if (local === "")
        return "";
    if (local.startsWith("..") || isAbsolute(local))
        return undefined;
    return local;
}
/**
 * Find a host-to-guest mount that makes the isolated project visible to a
 * remote executor. This deliberately recognizes data shape, not a provider or
 * package name.
 */
export function discoverWorkspaceMapping(value, hostRoot, depth = 0) {
    if (!value || typeof value !== "object" || depth > 5)
        return undefined;
    if (Array.isArray(value)) {
        for (const item of value.slice(0, 200)) {
            const mapping = discoverWorkspaceMapping(item, hostRoot, depth + 1);
            if (mapping)
                return mapping;
        }
        return undefined;
    }
    const candidate = value;
    const hostPath = stringProperty(candidate, HOST_PATH_KEYS);
    const guestPath = stringProperty(candidate, GUEST_PATH_KEYS);
    if (hostPath && guestPath) {
        const local = containsPath(hostPath, hostRoot);
        if (local !== undefined) {
            return {
                hostRoot: resolve(hostRoot),
                guestRoot: local ? resolve(guestPath, local) : resolve(guestPath),
            };
        }
    }
    for (const nested of Object.values(candidate).slice(0, 200)) {
        const mapping = discoverWorkspaceMapping(nested, hostRoot, depth + 1);
        if (mapping)
            return mapping;
    }
    return undefined;
}
function scopeCacheValue(value, fingerprint) {
    const suffix = `supercov-${fingerprint.slice(0, 20)}`;
    return value.includes(suffix) ? value : `${value}-${suffix}`;
}
/** Clone only branches that contain a recognized cache/snapshot identity. */
export function scopeCapabilityCache(value, fingerprint, depth = 0) {
    if (!value || typeof value !== "object" || depth > 5)
        return { value, changed: [] };
    if (Array.isArray(value)) {
        const changed = [];
        let cloned;
        for (let index = 0; index < value.length; index += 1) {
            const nested = scopeCapabilityCache(value[index], fingerprint, depth + 1);
            if (nested.changed.length > 0) {
                cloned ??= [...value];
                cloned[index] = nested.value;
                changed.push(...nested.changed.map((path) => `[${index}]${path}`));
            }
        }
        return { value: cloned ?? value, changed };
    }
    const source = value;
    let clone;
    const changed = [];
    for (const key of Reflect.ownKeys(source)) {
        if (typeof key !== "string")
            continue;
        const nestedValue = source[key];
        if (CACHE_IDENTITY.test(key) && typeof nestedValue === "string") {
            clone ??= { ...source };
            clone[key] = scopeCacheValue(nestedValue, fingerprint);
            changed.push(key);
            continue;
        }
        const nested = scopeCapabilityCache(nestedValue, fingerprint, depth + 1);
        if (nested.changed.length > 0) {
            clone ??= { ...source };
            clone[key] = nested.value;
            changed.push(...nested.changed.map((path) => `${key}.${path}`));
        }
    }
    return { value: clone ?? value, changed };
}
function replaceRoot(value, mapping) {
    const hostRoot = mapping.hostRoot.replaceAll("\\", "/").replace(/\/$/, "");
    const guestRoot = mapping.guestRoot.replaceAll("\\", "/").replace(/\/$/, "");
    const normalized = value.replaceAll("\\", "/");
    const hostUrl = pathToFileURL(mapping.hostRoot).href.replace(/\/$/, "");
    const guestUrl = pathToFileURL(mapping.guestRoot).href.replace(/\/$/, "");
    if (normalized === hostRoot)
        return guestRoot;
    if (normalized.startsWith(`${hostRoot}/`))
        return `${guestRoot}/${normalized.slice(hostRoot.length + 1)}`;
    if (value === hostUrl)
        return guestUrl;
    if (value.startsWith(`${hostUrl}/`))
        return `${guestUrl}/${value.slice(hostUrl.length + 1)}`;
    return value;
}
function appendNodeImport(existing, registerUrl) {
    const addition = `--import=${registerUrl}`;
    if (existing?.includes(addition))
        return existing;
    return [existing, addition].filter(Boolean).join(" ");
}
function coverageVariables(environment) {
    return Object.fromEntries(Object.entries(environment).filter(([key, value]) => key.startsWith("SUPERCOV_") && value !== undefined));
}
/** Build an environment whose paths remain valid inside the discovered VM. */
export function guestCoverageEnvironment(mapping, coverageEnvironment = process.env, existingEnvironment = {}) {
    const translated = Object.fromEntries(Object.entries(coverageVariables(coverageEnvironment)).map(([key, value]) => [
        key,
        value === undefined ? value : replaceRoot(value, mapping),
    ]));
    const registerUrl = pathToFileURL(resolve(mapping.guestRoot, ".supercov/register.mjs")).href;
    return {
        ...existingEnvironment,
        ...translated,
        SUPERCOV_PROJECT_ROOT: mapping.guestRoot,
        SUPERCOV_CJS_INTERCEPT: "1",
        NODE_OPTIONS: appendNodeImport(existingEnvironment.NODE_OPTIONS, registerUrl),
    };
}
function launchOptions(value) {
    if (!value || typeof value !== "object" || Array.isArray(value))
        return false;
    const candidate = value;
    return ((Array.isArray(candidate.argv) &&
        candidate.argv.every((item) => typeof item === "string")) ||
        (Array.isArray(candidate.cmd) &&
            candidate.cmd.every((item) => typeof item === "string")) ||
        typeof candidate.command === "string");
}
function launchArgv(value) {
    if (Array.isArray(value.argv))
        return value.argv;
    if (Array.isArray(value.cmd))
        return value.cmd;
    return [String(value.command)];
}
function injectRemoteLaunch(options, mapping) {
    const environmentKey = "environment" in options && !("env" in options) ? "environment" : "env";
    const existing = options[environmentKey];
    return {
        ...options,
        [environmentKey]: guestCoverageEnvironment(mapping, {
            ...process.env,
            SUPERCOV_EXECUTION_LOG_SHARD: `${process.pid}-${++remoteLaunchSequence}`,
        }, existing && typeof existing === "object"
            ? existing
            : {}),
    };
}
function wrapResult(value, mapping) {
    if (value instanceof Promise)
        return value.then((result) => wrapCapabilityObject(result, mapping));
    return wrapCapabilityObject(value, mapping);
}
/**
 * A remote SDK can hide its first executable launch inside a configuration
 * callback (for example an image warmup hook). Decorate callbacks in ordinary
 * configuration data so capability objects delivered later receive the same
 * provider-neutral launch supervision as objects returned directly by the SDK.
 * Accessors and class instances are deliberately left alone.
 */
export function wrapCapabilityCallbacks(value, mapping, depth = 0, seen = new WeakMap()) {
    if (typeof value === "function") {
        const cached = seen.get(value);
        if (cached)
            return cached;
        const original = value;
        const wrapped = function supercovCapabilityCallback(...args) {
            return wrapResult(Reflect.apply(original, this, args.map((argument) => wrapCapabilityObject(argument, mapping))), mapping);
        };
        seen.set(value, wrapped);
        return wrapped;
    }
    if (!value || typeof value !== "object" || depth > 5)
        return value;
    const cached = seen.get(value);
    if (cached)
        return cached;
    const prototype = Object.getPrototypeOf(value);
    if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
        return value;
    const clone = Array.isArray(value)
        ? [...value]
        : Object.create(prototype);
    seen.set(value, clone);
    let changed = false;
    for (const key of Reflect.ownKeys(value).slice(0, 200)) {
        const descriptor = Object.getOwnPropertyDescriptor(value, key);
        if (!descriptor || !("value" in descriptor))
            continue;
        const wrapped = wrapCapabilityCallbacks(descriptor.value, mapping, depth + 1, seen);
        if (wrapped !== descriptor.value)
            changed = true;
        Object.defineProperty(clone, key, { ...descriptor, value: wrapped });
    }
    if (!changed) {
        seen.set(value, value);
        return value;
    }
    return clone;
}
/**
 * Follow an opaque image/pool/machine-style object graph. Any method accepting
 * an argv-shaped options object receives the translated Supercov environment.
 */
export function wrapCapabilityObject(value, mapping) {
    if ((!value || typeof value !== "object") && typeof value !== "function")
        return value;
    const object = value;
    const cached = capabilityProxies.get(object);
    if (cached)
        return cached;
    const proxy = new Proxy(object, {
        get(target, property) {
            // Use the real target as the receiver so SDK getters backed by private
            // fields keep their brand check. Method calls are likewise bound below.
            const member = Reflect.get(target, property, target);
            if (typeof member !== "function")
                return member;
            return (...args) => {
                let callArguments = args;
                let index = args.findIndex(launchOptions);
                let positionalCommand;
                if (index < 0 &&
                    typeof property === "string" &&
                    /^(?:exec|execute|launch|run|spawn)$/i.test(property)) {
                    const commandIndex = args.findIndex((argument) => typeof argument === "string" ||
                        (Array.isArray(argument) && argument.every((item) => typeof item === "string")));
                    if (commandIndex >= 0) {
                        const command = args[commandIndex];
                        positionalCommand = Array.isArray(command)
                            ? command
                            : [String(command), ...(Array.isArray(args[commandIndex + 1]) ? args[commandIndex + 1] : [])];
                        index = args.findIndex((argument, argumentIndex) => argumentIndex > commandIndex &&
                            Boolean(argument) &&
                            typeof argument === "object" &&
                            !Array.isArray(argument));
                    }
                }
                if (index >= 0) {
                    const original = args[index];
                    callArguments = [...args];
                    callArguments[index] = injectRemoteLaunch(original, mapping);
                    record({
                        event: "remote-launch",
                        command: commandSummary(positionalCommand ?? launchArgv(original)),
                        guestRoot: mapping.guestRoot,
                    });
                }
                return wrapResult(Reflect.apply(member, target, callArguments), mapping);
            };
        },
    });
    capabilityProxies.set(object, proxy);
    return proxy;
}
/**
 * Proxy a value imported by a first-party ESM launcher. The proxy remains
 * provider-neutral: it waits until arguments reveal a host/guest mount, then
 * delegates to the same capability graph used for CommonJS exports.
 */
export function wrapImportedCapability(value) {
    if ((!value || typeof value !== "object") && typeof value !== "function")
        return value;
    const object = value;
    const cached = importedCapabilityProxies.get(object);
    if (cached)
        return cached;
    const invoke = (callable, receiver, args) => {
        const hostRoot = process.env["SUPERCOV_PROJECT_ROOT"];
        const mapping = hostRoot
            ? args.map((argument) => discoverWorkspaceMapping(argument, hostRoot)).find(Boolean)
            : undefined;
        if (mapping) {
            const fingerprint = process.env["SUPERCOV_EXECUTION_FINGERPRINT"] ?? "unversioned";
            const scopedArguments = args.map((argument) => scopeCapabilityCache(argument, fingerprint));
            const supervisedArguments = scopedArguments.map((entry) => wrapCapabilityCallbacks(entry.value, mapping));
            record({
                event: "workspace-capability",
                hostRoot: mapping.hostRoot,
                guestRoot: mapping.guestRoot,
                cacheIdentities: scopedArguments.flatMap((entry) => entry.changed),
            });
            return wrapResult(Reflect.apply(callable, receiver, supervisedArguments), mapping);
        }
        return wrapImportedCapability(Reflect.apply(callable, receiver, args));
    };
    const proxy = new Proxy(object, {
        get(target, property) {
            const member = Reflect.get(target, property, target);
            if (typeof member !== "function")
                return wrapImportedCapability(member);
            return (...args) => invoke(member, target, args);
        },
        ...(typeof value === "function"
            ? {
                apply(target, thisArgument, args) {
                    return invoke(target, thisArgument, args);
                },
                construct(target, args, newTarget) {
                    const result = Reflect.construct(target, args, newTarget);
                    return wrapImportedCapability(result);
                },
            }
            : {}),
    });
    importedCapabilityProxies.set(object, proxy);
    return proxy;
}
function patchBuilder(builder) {
    if (patchedBuilders.has(builder))
        return;
    const descriptor = Object.getOwnPropertyDescriptor(builder, "build");
    if (!descriptor || typeof descriptor.value !== "function" || !descriptor.writable)
        return;
    const original = descriptor.value;
    Object.defineProperty(builder, "build", {
        ...descriptor,
        value: function supercovCapabilityBuild(...args) {
            const hostRoot = process.env["SUPERCOV_PROJECT_ROOT"];
            const mapping = hostRoot
                ? discoverWorkspaceMapping(args[0], hostRoot)
                : undefined;
            if (!mapping)
                return Reflect.apply(original, this, args);
            const fingerprint = process.env["SUPERCOV_EXECUTION_FINGERPRINT"] ?? "unversioned";
            const scoped = scopeCapabilityCache(args[0], fingerprint);
            const callArguments = [
                wrapCapabilityCallbacks(scoped.value, mapping),
                ...args.slice(1),
            ];
            record({
                event: "workspace-capability",
                hostRoot: mapping.hostRoot,
                guestRoot: mapping.guestRoot,
                cacheIdentities: scoped.changed,
            });
            return wrapResult(Reflect.apply(original, this, callArguments), mapping);
        },
    });
    patchedBuilders.add(builder);
}
function inspectExports(value, depth = 0) {
    if (((!value || typeof value !== "object") && typeof value !== "function") ||
        depth > 2)
        return;
    const object = value;
    if (exportedValues.has(object))
        return;
    exportedValues.add(object);
    if (typeof value === "function")
        patchBuilder(value);
    for (const key of Reflect.ownKeys(object).slice(0, 200)) {
        if (key === "prototype" || key === "caller" || key === "callee")
            continue;
        try {
            const descriptor = Object.getOwnPropertyDescriptor(object, key);
            if (descriptor && "value" in descriptor)
                inspectExports(descriptor.value, depth + 1);
        }
        catch {
            // Export inspection is best-effort and never invokes accessors.
        }
    }
}
function childOptionsIndex(method, args) {
    if (method === "spawn" || method === "spawnSync" || method === "fork")
        return Array.isArray(args[1]) || (args.length > 2 && args[2] !== undefined)
            ? 2
            : 1;
    if (method === "exec" ||
        method === "execSync" ||
        method === "execFile" ||
        method === "execFileSync")
        return Array.isArray(args[1]) || (args.length > 2 && args[2] !== undefined)
            ? 2
            : 1;
    return undefined;
}
function injectChildEnvironment(method, args) {
    const index = childOptionsIndex(method, args);
    if (index === undefined)
        return args;
    const next = [...args];
    const original = next[index];
    const options = original && typeof original === "object" && !Array.isArray(original)
        ? original
        : {};
    const inherited = coverageVariables(process.env);
    const existingEnvironment = options.env && typeof options.env === "object"
        ? options.env
        : undefined;
    if (existingEnvironment?.["SUPERCOV_INTERNAL_ENGINE"] === "1" ||
        existingEnvironment?.["SUPERCOV_INTERNAL_INSTRUMENTER"] === "1")
        return args;
    const environment = existingEnvironment
        ? { ...existingEnvironment, ...inherited }
        : { ...process.env, ...inherited };
    environment.NODE_OPTIONS = appendNodeImport(existingEnvironment?.NODE_OPTIONS ?? process.env.NODE_OPTIONS, pathToFileURL(resolve(process.env["SUPERCOV_PROJECT_ROOT"] ?? process.cwd(), ".supercov/register.mjs")).href);
    next[index] = { ...options, env: environment };
    if (typeof original === "function")
        next.splice(index + 1, 0, original);
    record({
        event: "child-launch",
        method,
        command: safeArgument(String(args[0] ?? "")),
    });
    return next;
}
function patchChildProcesses() {
    const methods = [
        "spawn",
        "spawnSync",
        "exec",
        "execSync",
        "execFile",
        "execFileSync",
        "fork",
    ];
    for (const method of methods) {
        const original = childProcess[method];
        Object.defineProperty(childProcess, method, {
            configurable: true,
            enumerable: true,
            writable: true,
            value: (...args) => Reflect.apply(original, childProcess, injectChildEnvironment(method, args)),
        });
    }
    syncBuiltinESMExports();
}
export function installLaunchSupervisor() {
    if (installed)
        return;
    installed = true;
    patchChildProcesses();
    const moduleLoader = Module;
    const originalLoad = moduleLoader._load;
    moduleLoader._load = function supercovCapabilityLoad(request, parent, isMain) {
        const exports = originalLoad.call(this, request, parent, isMain);
        inspectExports(exports);
        return exports;
    };
    record({
        event: "process",
        cwd: process.cwd(),
        command: commandSummary(process.argv),
        entrypoint: process.argv[1],
    });
}
//# sourceMappingURL=launchSupervisor.js.map