Files
reverse-engineering-anything/src/browser/IsolatedWebBundleAnalyzer.test.ts
T
morluto 2430b081c9 refactor(providers): bind provider refusals' per-call controls instead of naming CLI flags (#11455)
* refactor(native): bind producer_limits and max_input_bytes as the per-call controls of pwntools and Apple dispatch refusals

producerLimitControl in src/domain/producerResourceLimits.ts names one producer budget as producer_limits.<field>; the shared provider outcome classifier now carries a resource signal's limit. Pwntools file-size, CPU and output refusals and the Apple dispatch input refusal bind their control, and their remediation no longer names CLI flags.

* fix(native): report the selected output allowance as the omitted file_bytes default

* fix(native): bind producer_limits.diagnostic_bytes as the pwntools command output-limit control

* refactor(rust): bind producer_limits as the per-call control of Rust input and report refusals (#11458)

* refactor(rust): bind producer_limits as the per-call control of Rust input and report refusals

* test(rust): cover the complete-report refusal's producer_limits control

* refactor(browser): bind caller-selectable browser deadlines as per-call controls instead of naming CLI flags (#11466)

* refactor(rust): bind producer_limits as the per-call control of Rust input and report refusals

* test(rust): cover the complete-report refusal's producer_limits control

* refactor(browser): bind caller-selectable browser deadlines as per-call controls instead of naming CLI flags

deadlineParameterLimit in src/domain/analysisResourceLimits.ts owns the millisecond deadline control that nativeDeadlineRecovery and the browser recoveries share. CDP command and discovery, web bundle per-script and total, network capture and source-map decode deadlines now carry it; browserDeadlineIncrease no longer takes CLI flag text.

* fix(browser): record a per-script deadline's parameter control in partial web bundle results

* refactor(providers): bind Wabt, SQLite, EVMole, Apktool and Go controls instead of naming CLI commands (#11472)

* refactor(providers): bind Wabt, SQLite, EVMole and Apktool deadline and byte controls instead of naming CLI commands

These remediation strings named rea commands and flags through template text the cli-option guard did not count. Wabt byte refusals and output limits bind max_input_bytes, max_tool_bytes or max_output_bytes while a larger value is selectable; SQLite worker_timeout_ms, EVMole timeout_ms and Apktool decode_timeout_ms bind through deadlineParameterLimit; the shared provider outcome classifier now carries an output limit's control.

* refactor(go): bind Go analysis budgets as per-call controls instead of naming CLI flags

* fix(providers): keep the typed primary when Wabt, EVMole or pwntools command cleanup fails

* ci(guards): count template-built CLI option and command text outside the CLI layer (#11478)

* refactor(providers): bind Wabt, SQLite, EVMole and Apktool deadline and byte controls instead of naming CLI commands

These remediation strings named rea commands and flags through template text the cli-option guard did not count. Wabt byte refusals and output limits bind max_input_bytes, max_tool_bytes or max_output_bytes while a larger value is selectable; SQLite worker_timeout_ms, EVMole timeout_ms and Apktool decode_timeout_ms bind through deadlineParameterLimit; the shared provider outcome classifier now carries an output limit's control.

* refactor(go): bind Go analysis budgets as per-call controls instead of naming CLI flags

* fix(providers): keep the typed primary when Wabt, EVMole or pwntools command cleanup fails

* ci(guards): count template-built CLI option and command text outside the CLI layer

The cli-option-text-outside-cli pattern now also matches "(CLI ...", "on the CLI", "or use rea ..." and backticked `rea <command>` references, so remediation built from a template such as --${name} or rea inspect-... <path> is counted. Doctor.ts is exempt: setup and doctor run only through the CLI. The baseline records the newly counted pre-existing sites (22 -> 45 across 21 files).

* ci(guards): extract the CLI text matcher, exempt host-only commands with written reasons, and test each spelling

* ci(guards): exempt a host-only command and its own arguments in any matched CLI phrase

* fix(native): bind producer_limits.output_bytes for oversized pwndbg debugger replies through one owner

* fix(cli): name an Evidence target source failure's control by the source option that sets it

* feat(cli): render the flags of result-recorded controls in the full-output envelope (#11507)

* feat(cli): render the flags of result-recorded controls in the full-output envelope

* fix(cli): collect result controls only for a full-output envelope, in its requested format, past undefined values

* ci(guards): end a host-only command's arguments before the next CLI command

* refactor(reverse): record the output budget that stopped a one-shot command as a parameter control (#11528)

* fix(cli): read result controls only at positions the output schema declares as recorded controls

* refactor(providers): record the controls that bounded Rust compiler paths and kernel module text instead of naming CLI options (#11532)

* refactor(rust): record the control that bounded compiler-path coverage instead of naming CLI options

* refactor(native): record the controls that omitted kernel module .modinfo text instead of naming CLI options (#11534)

* fix(rust): describe compiler coverage from the retained result after report trimming

* refactor(providers): record managed representation and JavaScript semantic ceiling controls instead of naming CLI options (#11537)

* refactor(managed): record the representation budget on a resource-limit issue instead of naming its CLI option

* refactor(javascript): record the semantic retention ceilings that stopped a graph instead of naming CLI options (#11540)

* fix(cli): name a composed command's source options for the controls its result records

* fix(cli): read result controls from the delivered Evidence when a summary wraps it

* fix(rust): keep the report-byte control recorded when trimming omits every compiler path

When the complete-report allowance left room for no compiler path, rustc_commit became null and its coverage.limit was lost, so --full-output could not name the option that raises the allowance. The report now records rustc_commit_omission { reason, limit } outside the dropped record, and the summary view carries it.

* refactor(flutter): record the string-pool budgets that left a projection partial instead of naming the CLI option (#11541)

* refactor(flutter): record the string-pool budgets that left a projection partial instead of naming the CLI option

* test(flutter): assert the complete set of recorded string-pool budgets

* feat(cli): name the options of controls a failure's partial Evidence records (#11557)

meta.cli_controls was collected only from a successful result. A failure whose partial observation is Evidence of the command's own operation is now read the same way, at the positions the output schema declares as recorded controls; Evidence of another operation or a retained reference is not read. When --evidence_output publishes the partial, the delivery records it before replacing it.

* refactor(javascript): record the evaluator budgets that limited sources instead of naming the CLI option (#11564)

Per-value unknown reasons and the Electron wrapper limitation named --semantic-precision. The static examination now records the semantic_precision controls that limited a source (examination.controls), and analyze_javascript_application's semantic_graph.coverage.controls records every evaluator budget that limited any source (examination and semantic IR coverage), beside the retention ceilings. The CLI renders --semantic-precision from those records in meta.cli_controls; the reason texts name only the contract field.
2026-11-16 07:12:16 +08:00

602 lines
20 KiB
TypeScript

import {
phaseArrival,
phaseGate,
} from "../../tests/support/lifecycleHarness.js";
import { expect, it } from "vitest";
import { createWebPageInspection } from "../../tests/support/browser/webPageInspection.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
OwnerCancellation,
} from "../domain/analysisErrorCore.js";
import type {
AnalyzeWebBundleInput,
WebBundleAnalysis,
} from "../domain/webBundleAnalysis.js";
import {
analyzeWebBundleInputSchema,
webBundleScriptTimeoutRecovery,
} from "../domain/webBundleAnalysis.js";
import { analyzeCapturedWebScript } from "../domain/webBundleAnalyzer.js";
import { unavailableWebScriptRecovery } from "../domain/webBundleScriptAnalysis.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { OwnedWorkerRuntime } from "../process/OwnedWorkerRuntime.js";
import { err, ok } from "../domain/result.js";
import {
IsolatedWebBundleAnalyzer,
WebBundleAnalysisAdmission,
type WebBundleAnalysisWorkerPort,
} from "./IsolatedWebBundleAnalyzer.js";
import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js";
import { javaScriptMemberMutationRefusal } from "../domain/javascript/javascriptSemanticWorkAllowance.js";
const origin = "https://app.example.test";
const noSourceMaps: WebBundleAnalysis["observations"]["source_maps"] = {
status: "not_requested",
requested: 0,
processed: 0,
items: [],
};
const input: AnalyzeWebBundleInput = analyzeWebBundleInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
target_id: "page-1",
include_script_sources: true,
});
it("preserves completed prefix and suffix facts when one script times out", async () => {
const captured = inspection([
"import './prefix.js'; fetch('/prefix');",
"function stalled() {}",
"import './suffix.js'; fetch('/suffix');",
]);
const calls: string[] = [];
const analyzer = new IsolatedWebBundleAnalyzer(() => ({
analyze: async (script) => {
calls.push(script.script_key);
if (calls.length === 2)
return err({
// The worker's per-script deadline, inside a total that has time left.
error: new AnalysisTimeoutError(
"analyze_web_bundle",
5,
webBundleScriptTimeoutRecovery(5),
),
completed: null,
});
return ok(analyzeCapturedWebScript(script));
},
close: async () => {},
}));
expect((await analyzer.reserve()).ok).toBe(true);
const result = await analyzer.analyze(captured, noSourceMaps, input);
analyzer.releaseReservation();
expect(calls).toEqual(
captured.scripts.items.map(({ script_key }) => script_key),
);
if (!result.ok) throw result.error;
expect(
result.value.observations.chunks.edges.map(({ specifier }) => specifier),
).toEqual(["./prefix.js", "./suffix.js"]);
expect(result.value.observations.endpoints.map(({ value }) => value)).toEqual(
["/prefix", "/suffix"],
);
expect(result.value.completeness).toMatchObject({
status: "partial",
parsed_scripts: 2,
parse_failures: 0,
});
// The partial result records the per-call control by contract field; it
// names no adapter spelling.
const timedOut = result.value.unknowns.find(
({ dimension }) => dimension === "javascript_analysis",
);
expect(timedOut).toEqual({
dimension: "javascript_analysis",
reason: expect.stringContaining("deadline"),
affected_script_keys: [captured.scripts.items[1]?.script_key],
limit: {
control_kind: "parameter",
parameter: "analysis_timeout_ms",
effective_value: 5,
unit: "ms",
minimum: expect.any(Number),
maximum: expect.any(Number),
default_value: expect.any(Number),
applies_at: "next_call",
},
remediation: expect.stringContaining("analysis_timeout_ms"),
});
expect(JSON.stringify(timedOut)).not.toContain("--");
});
it("keeps the selected allowance and its recovery for a refused script", async () => {
const captured = inspection(["fetch('/kept');", "fetch('/refused');"]);
const allowance = { aliasStates: 64, source: "runtime" } as const;
const refusal = javaScriptMemberMutationRefusal(
"analyze_web_bundle",
allowance,
);
const received: unknown[] = [];
const analyzer = new IsolatedWebBundleAnalyzer(() => ({
analyze: async (script, _timeout, _signal, _precision, selected) => {
received.push(selected);
return script.script_key === captured.scripts.items[1]?.script_key
? err({ error: refusal, completed: null })
: ok(analyzeCapturedWebScript(script));
},
close: async () => {},
}));
expect((await analyzer.reserve()).ok).toBe(true);
const result = await analyzer.analyze(
captured,
noSourceMaps,
input,
undefined,
allowance,
);
analyzer.releaseReservation();
if (!result.ok) throw result.error;
expect(received).toEqual([allowance, allowance]);
expect(result.value.unknowns).toContainEqual({
dimension: "javascript_analysis",
reason: expect.stringContaining("resource_constraint"),
affected_script_keys: [captured.scripts.items[1]?.script_key],
limit: refusal.limit,
remediation: refusal.remediationAction,
});
expect(refusal.limit).toMatchObject({
setting: "javascript.member_mutation_alias_states",
effective_value: 64,
source: "runtime",
});
});
it("keeps a refused script's parse and text facts beside its refusal", async () => {
const refused = [
"/* __webpack_require__ */ function probe(input, env) { var m; if (env.first) m = env.first.info;",
...Array.from(
{ length: 4 },
(_, index) =>
`if (/case${String(index)}/.test(input)) m = m[${String(index % 2)}];`,
),
"m[1] = input.length; var c = new Map(); c.get('k'); fetch('/hidden'); return m; }",
].join(" ");
const captured = inspection(["fetch('/kept');", refused]);
const allowance = { aliasStates: 8, source: "runtime" } as const;
const refusal = javaScriptMemberMutationRefusal(
"analyze_web_bundle",
allowance,
);
const analyzer = new IsolatedWebBundleAnalyzer(() => ({
analyze: async (script, _timeout, _signal, precision, selected) => {
const facts = analyzeCapturedWebScript(script, precision, selected);
// The worker parent states the refusal from the allowance it sent.
return ok(
facts.status === "unavailable"
? { ...facts, ...unavailableWebScriptRecovery(refusal) }
: facts,
);
},
close: async () => {},
}));
expect((await analyzer.reserve()).ok).toBe(true);
const result = await analyzer.analyze(
captured,
noSourceMaps,
input,
undefined,
allowance,
);
analyzer.releaseReservation();
if (!result.ok) throw result.error;
const refusedKey = captured.scripts.items[1]?.script_key;
expect(result.value.completeness).toMatchObject({
status: "partial",
parsed_scripts: 2,
parse_failures: 0,
});
expect(result.value.inferences).toContainEqual(
expect.objectContaining({
kind: "bundle_runtime",
value: "webpack",
basis: [expect.objectContaining({ script_key: refusedKey })],
}),
);
expect(result.value.observations.endpoints.map(({ value }) => value)).toEqual(
["/kept"],
);
expect(result.value.unknowns).toContainEqual({
dimension: "javascript_analysis",
reason: expect.stringContaining("resource_constraint"),
affected_script_keys: [refusedKey],
limit: refusal.limit,
remediation: refusal.remediationAction,
refused_phase: "member-mutations",
});
});
it("marks the unstarted suffix when the aggregate deadline expires", async () => {
const captured = inspection([
"fetch('/prefix');",
"fetch('/stalled');",
"fetch('/not-started');",
]);
const calls: string[] = [];
const analyzer = new IsolatedWebBundleAnalyzer(() => ({
analyze: async (script, _timeout, signal) => {
calls.push(script.script_key);
if (calls.length === 1) return ok(analyzeCapturedWebScript(script));
await waitForAbort(signal);
return err({
error: new AnalysisTimeoutError("analyze_web_bundle", 50),
completed: null,
});
},
close: async () => {},
}));
expect((await analyzer.reserve()).ok).toBe(true);
const result = await analyzer.analyze(captured, noSourceMaps, {
...input,
total_analysis_timeout_ms: 50,
});
analyzer.releaseReservation();
expect(calls).toEqual(
captured.scripts.items.slice(0, 2).map(({ script_key }) => script_key),
);
if (result.ok) throw new Error("Expected total deadline failure");
expect(result.error._tag).toBe("AnalysisTimeoutError");
expect(result.error.partialObservation).toMatchObject({
completeness: { status: "partial", parsed_scripts: 1 },
observations: { endpoints: [{ value: "/prefix" }] },
});
expect(result.error.partialObservation).toMatchObject({
unknowns: expect.arrayContaining([
expect.objectContaining({
dimension: "javascript_analysis",
affected_script_keys: [captured.scripts.items[1]?.script_key],
}),
expect.objectContaining({
dimension: "javascript_analysis",
affected_script_keys: [captured.scripts.items[2]?.script_key],
}),
]),
});
});
it("stops after a middle-script result-capacity failure and retains prefix facts", async () => {
const captured = inspection([
"import './prefix.js'; fetch('/prefix');",
"fetch('/capacity-blocked');",
"fetch('/must-not-start');",
]);
const calls: string[] = [];
const caller = new AbortController();
const cancellation = new Error("later cancellation during final close");
const primary = new AnalysisResourceConstraintError(
"analyze_web_bundle",
"memory",
"No result capacity remains",
{ result_bytes: 0 },
);
const analyzer = new IsolatedWebBundleAnalyzer(() => ({
analyze: async (script) => {
calls.push(script.script_key);
if (calls.length === 1) return ok(analyzeCapturedWebScript(script));
return err({
error: primary,
completed: null,
continuation: "result_capacity_exhausted",
});
},
close: async () => {
caller.abort(cancellation);
},
}));
expect((await analyzer.reserve()).ok).toBe(true);
const result = await analyzer.analyze(
captured,
noSourceMaps,
input,
caller.signal,
);
analyzer.releaseReservation();
expect(calls).toEqual(
captured.scripts.items.slice(0, 2).map(({ script_key }) => script_key),
);
if (result.ok) throw new Error("Expected result-capacity failure");
expect(result.error).toBe(primary);
expect(result.error.secondaryFailures).toContainEqual(
expect.objectContaining({
_tag: "AnalysisCancelledError",
cause: cancellation,
}),
);
expect(result.error.partialObservation).toMatchObject({
completeness: { status: "partial", parsed_scripts: 1 },
observations: {
chunks: { edges: [{ specifier: "./prefix.js" }] },
endpoints: [{ value: "/prefix" }],
},
unknowns: expect.arrayContaining([
expect.objectContaining({
dimension: "javascript_analysis",
affected_script_keys: [captured.scripts.items[1]?.script_key],
}),
expect.objectContaining({
dimension: "javascript_analysis",
affected_script_keys: [captured.scripts.items[2]?.script_key],
}),
]),
});
});
it("carries the exact caller cancellation reason and completed prefix facts", async () => {
const captured = inspection([
"fetch('/prefix');",
"fetch('/cancelled');",
"fetch('/cancelled-suffix');",
]);
const started = phaseArrival();
const controller = new AbortController();
const analyzer = new IsolatedWebBundleAnalyzer(() => ({
analyze: async (script, _timeout, signal) => {
if (script.script_key === captured.scripts.items[0]?.script_key)
return ok(analyzeCapturedWebScript(script));
started.arrive();
await waitForAbort(signal);
return err({
error: new AnalysisCancelledError("analyze_web_bundle", {
cause: signal?.reason,
}),
completed: null,
});
},
close: async () => {},
}));
expect((await analyzer.reserve()).ok).toBe(true);
const exactReason = new Error("caller stopped analysis");
const pending = analyzer.analyze(
captured,
noSourceMaps,
input,
controller.signal,
);
let result: Awaited<typeof pending>;
try {
await started.reached(pending, "script analysis");
controller.abort(exactReason);
result = await pending;
} finally {
controller.abort(exactReason);
try {
await pending;
} finally {
analyzer.releaseReservation();
}
}
if (result.ok) throw new Error("Expected cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cause).toBe(exactReason);
expect(result.error.partialObservation).toMatchObject({
completeness: { status: "partial", parsed_scripts: 1 },
observations: { endpoints: [{ value: "/prefix" }] },
unknowns: expect.arrayContaining([
expect.objectContaining({
dimension: "javascript_analysis",
affected_script_keys: [captured.scripts.items[1]?.script_key],
}),
expect.objectContaining({
dimension: "javascript_analysis",
affected_script_keys: [captured.scripts.items[2]?.script_key],
}),
]),
});
});
it("refuses work after close with REA's own cancellation reason, not an absent one", async () => {
const analyzer = new IsolatedWebBundleAnalyzer(() => ({
analyze: async (script) => ok(analyzeCapturedWebScript(script)),
close: async () => {},
}));
await analyzer.close();
const captured = inspection(["fetch('/one');"]);
const reserved = await analyzer.reserve();
const analyzed = await analyzer.analyze(captured, noSourceMaps, input);
for (const result of [reserved, analyzed]) {
if (result.ok) throw new Error("Closed analyzer accepted work");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cause).toBe(OwnerCancellation.ownerClosed);
}
if (analyzed.ok) throw new Error("Closed analyzer accepted work");
expect(analyzed.error.partialObservation).toBe(captured);
});
it("retains all completed facts when cancellation arrives during worker close", async () => {
const captured = inspection(["fetch('/one');", "fetch('/two');"]);
const workerClose = phaseGate();
const analyzer = new IsolatedWebBundleAnalyzer(() => ({
analyze: async (script) => ok(analyzeCapturedWebScript(script)),
close: async () => {
await workerClose.hold();
},
}));
expect((await analyzer.reserve()).ok).toBe(true);
const pending = analyzer.analyze(captured, noSourceMaps, input);
await workerClose.reached(pending, "worker close");
const closing = analyzer.close();
workerClose.release();
await closing;
const result = await pending;
analyzer.releaseReservation();
if (result.ok) throw new Error("Expected cancellation during finalization");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.partialObservation).toMatchObject({
completeness: { status: "complete", parsed_scripts: 2 },
observations: { endpoints: [{ value: "/one" }, { value: "/two" }] },
});
});
it("retains cleanup ownership after mixed worker/close failure and resolves it on retry", async () => {
const captured = inspection(["fetch('/partial');"]);
const primary = new ProviderCleanupError(
"web-bundle-static-analysis",
["worker-job"],
{ reason: "analysis cleanup pending" },
{ operation: "analyze_web_bundle" },
);
const closeFailure = new ProviderCleanupError(
"web-bundle-static-analysis",
["worker-root"],
{ reason: "worker close pending" },
{ operation: "analyze_web_bundle" },
);
let closeAttempts = 0;
const admission = new WebBundleAnalysisAdmission();
const analyzer = new IsolatedWebBundleAnalyzer(
() => ({
analyze: async () => err({ error: primary, completed: null }),
close: async () => {
closeAttempts += 1;
if (closeAttempts <= 2) throw closeFailure;
releaseOwnedCleanup(closeFailure);
releaseOwnedCleanup(primary);
},
}),
admission,
);
expect((await analyzer.reserve()).ok).toBe(true);
const result = await analyzer.analyze(captured, noSourceMaps, input);
if (result.ok) throw new Error("Expected mixed failure");
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupPrimary).toBe(primary);
expect(result.error.cleanupResources).toEqual(["worker-job", "worker-root"]);
expect(result.error.partialObservation).toMatchObject({
completeness: { status: "partial", parsed_scripts: 0 },
});
const replacement = new IsolatedWebBundleAnalyzer(
() => inertWorker(),
admission,
);
analyzer.releaseReservation();
const blocked = await replacement.reserve();
expect(blocked.ok).toBe(false);
await analyzer.close();
expect(closeAttempts).toBe(3);
expect(result.error.cleanupIncomplete).toBe(false);
expect(result.error.cleanupResources).toEqual([]);
expect((await replacement.reserve()).ok).toBe(true);
replacement.releaseReservation();
});
it("shares one capture reservation when analyzers use one admission", async () => {
const admission = new WebBundleAnalysisAdmission();
const first = new IsolatedWebBundleAnalyzer(() => inertWorker(), admission);
const second = new IsolatedWebBundleAnalyzer(() => inertWorker(), admission);
expect((await first.reserve()).ok).toBe(true);
const blocked = await second.reserve();
if (blocked.ok) throw new Error("Expected shared admission refusal");
expect(projectAnalysisError(blocked.error)).toMatchObject({
code: "resource_constraint",
details: {
resource: "capacity",
reported_limits: { concurrent_web_bundle_analyses: 1 },
},
});
first.releaseReservation();
expect((await second.reserve()).ok).toBe(true);
second.releaseReservation();
});
it("does not fail one admission's analysis when another host's worker runtime is retained", async () => {
let fail = true;
const stuck = new OwnedWorkerRuntime({
rootPrefix: "rea-web-host-isolation-",
retryCleanup: async () => {
if (fail) throw new Error("other host still owns its worker");
},
});
stuck.retainForCleanup();
try {
const analyzed: string[] = [];
const analyzer = new IsolatedWebBundleAnalyzer(() => ({
analyze: async (script) => {
analyzed.push(script.script_key);
return ok(analyzeCapturedWebScript(script));
},
close: async () => {},
}));
expect((await analyzer.reserve()).ok).toBe(true);
const captured = inspection(["fetch('/independent');"]);
const result = await analyzer.analyze(captured, noSourceMaps, input);
expect(result.ok).toBe(true);
expect(analyzed).toEqual(
captured.scripts.items.map(({ script_key }) => script_key),
);
if (result.ok)
expect(result.value.observations.endpoints).toMatchObject([
{ value: "/independent" },
]);
analyzer.releaseReservation();
await expect(OwnedWorkerRuntime.retryPending()).rejects.toThrow(
"other host still owns its worker",
);
} finally {
fail = false;
await stuck.close();
}
});
it("does not share a capture reservation across independent admissions", async () => {
const first = new IsolatedWebBundleAnalyzer(() => inertWorker());
const second = new IsolatedWebBundleAnalyzer(() => inertWorker());
expect((await first.reserve()).ok).toBe(true);
expect((await second.reserve()).ok).toBe(true);
first.releaseReservation();
second.releaseReservation();
});
const inertWorker = (): WebBundleAnalysisWorkerPort => ({
analyze: async () =>
err({
error: new AnalysisOutputError("analyze_web_bundle", "unused"),
completed: null,
}),
close: async () => {},
});
const waitForAbort = (signal: AbortSignal | undefined): Promise<void> => {
if (signal?.aborted) return Promise.resolve();
return new Promise((resolve) => {
signal?.addEventListener("abort", () => resolve(), { once: true });
});
};
const inspection = (sources: readonly string[]) =>
createWebPageInspection(
sources.map((source, index) => ({
source,
scriptKey: `scr_${String(index + 1).repeat(64)}`,
url: `${origin}/assets/${String(index)}.js`,
origin,
cdpHash: `hash-${String(index)}`,
})),
);