chore: reconcile iNES inventory with current main
This commit is contained in:
@@ -18,6 +18,7 @@ import {
|
||||
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
|
||||
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
javascriptApplicationAnalysisResultSchema,
|
||||
type JavaScriptApplicationAnalysisResult,
|
||||
@@ -1530,6 +1531,60 @@ const analyzeComparisonSources = async (
|
||||
);
|
||||
};
|
||||
|
||||
it("retains bundled isolated-world contextBridge APIs through dedicated and generic CLI routes", async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-context-bridge-isolated-cli-",
|
||||
);
|
||||
await writeFile(
|
||||
join(root, "preload.js"),
|
||||
`(() => {
|
||||
const modules = {
|
||||
2(module) { module.exports = require("electron"); },
|
||||
5(module, exports, load) {
|
||||
const electron = load(2);
|
||||
electron.contextBridge.exposeInIsolatedWorld(1001, "isolatedApi", { ping: true });
|
||||
},
|
||||
};
|
||||
function load(id) {
|
||||
const module = { exports: {} };
|
||||
modules[id].call(module.exports, module, module.exports, load);
|
||||
return module.exports;
|
||||
}
|
||||
load(5);
|
||||
})();`,
|
||||
);
|
||||
|
||||
for (const arguments_ of [
|
||||
["analyze-javascript-application", root, "--json"],
|
||||
["analyze", root, "--format", "json"],
|
||||
]) {
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(await runCli(arguments_)).normalized_result,
|
||||
);
|
||||
expect(result.summary.context_bridge_apis).toBe(1);
|
||||
const bridge = result.graph.nodes.find(
|
||||
({ kind }) => kind === "context-bridge-api",
|
||||
);
|
||||
expect(bridge?.observations).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
world: "isolated",
|
||||
world_id: { status: "literal", value: 1001, expression: null },
|
||||
api_key: "isolatedApi",
|
||||
members: ["ping"],
|
||||
resolution_basis: "wrapper-substitution",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
location: expect.objectContaining({
|
||||
available: true,
|
||||
value: expect.objectContaining({ source: "preload.js" }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const runCli = async (
|
||||
arguments_: readonly string[],
|
||||
environment: Readonly<Record<string, string>> = {},
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { buildBinary } from "plist";
|
||||
|
||||
import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
|
||||
import { appleAssetCatalogResultSchema } from "../../../src/domain/apple/appleAssetCatalog.js";
|
||||
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
// Exact rooted NIBArchive bytes from #2176; inert parser fixture, not ibtool output.
|
||||
const reportedArchive = Buffer.from(
|
||||
"TklCQXJjaGl2ZQEAAAAKAAAABAAAADIAAAAEAAAAPgAAAAQAAABgAAAABAAAAHwAAACAgIGBgYGCgoGDg4GGTlNSb290hWltYWdli05TSW1hZ2VOYW1liE5TLmJ5dGVzgAoBAAAAgQoCAAAAggoDAAAAgwiHVG9vbGJhco6ATlNJQk9iamVjdERhdGGLgE5TSW1hZ2VWaWV3h4BOU0ltYWdliIBOU1N0cmluZw==",
|
||||
"base64",
|
||||
);
|
||||
const resourceArchive = (field: string) =>
|
||||
encodeNibArchiveFixture({
|
||||
classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
|
||||
objects: [
|
||||
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
|
||||
{ classIndex: 1, values: { image: { ref: 2 } } },
|
||||
{ classIndex: 2, values: { [field]: { ref: 3 } } },
|
||||
{ classIndex: 3, values: { "NS.bytes": "Toolbar" } },
|
||||
],
|
||||
});
|
||||
|
||||
const keyedArchive = (nested: boolean) =>
|
||||
buildBinary({
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$top: { root: { UID: 1 } },
|
||||
$objects: [
|
||||
"$null",
|
||||
{
|
||||
$class: { UID: 2 },
|
||||
...(nested
|
||||
? { nibValues: { NSImageName: "Toolbar" } }
|
||||
: { NSImageName: "Toolbar" }),
|
||||
},
|
||||
{ $classname: "NSImage", $classes: ["NSImage", "NSObject"] },
|
||||
],
|
||||
});
|
||||
|
||||
cliTest.skipIf(process.platform !== "darwin")(
|
||||
"retains recognized NIBArchive resource keys and provenance through CLI and MCP without a catalog",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-asset-resource-keys-");
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [name, field, archive, recognized] of [
|
||||
["reported", "NSImageName", reportedArchive, true],
|
||||
["alias", "imageName", resourceArchive("imageName"), true],
|
||||
["title", "title", resourceArchive("title"), false],
|
||||
["keyed-direct", "NSImageName", keyedArchive(false), true],
|
||||
["keyed-nested", "NSImageName", keyedArchive(true), false],
|
||||
] as const) {
|
||||
const app = join(root, `${name}.app`);
|
||||
const contents = join(app, "Contents");
|
||||
await mkdir(join(contents, "Resources"), { recursive: true });
|
||||
await mkdir(join(contents, "MacOS"));
|
||||
const mach = Buffer.alloc(32);
|
||||
mach.writeUInt32LE(0xfeedfacf, 0);
|
||||
mach.writeUInt32LE(0x0100000c, 4);
|
||||
mach.writeUInt32LE(2, 12);
|
||||
await writeFile(join(contents, "MacOS", "App"), mach);
|
||||
await writeFile(
|
||||
join(contents, "Info.plist"),
|
||||
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
|
||||
);
|
||||
await writeFile(join(contents, "Resources", "Panel.nib"), archive);
|
||||
const decoded = await cli.run({
|
||||
arguments: ["decode-interface-builder", app, "--json"],
|
||||
});
|
||||
expect(decoded.exitCode, decoded.stderr).toBe(0);
|
||||
const graph = interfaceBuilderAnalysisSchema.parse(
|
||||
parseEvidence(decoded.json).normalized_result,
|
||||
).graph;
|
||||
expect(graph.truncated).toBe(false);
|
||||
const resource = graph.nodes.find(
|
||||
(node) =>
|
||||
node.kind === "resource" && node.attributes.class_name === "NSImage",
|
||||
);
|
||||
expect(
|
||||
name === "keyed-direct"
|
||||
? resource?.attributes
|
||||
: resource?.attributes.nibValues,
|
||||
).toMatchObject({
|
||||
[field]: "Toolbar",
|
||||
});
|
||||
const inspected = await cli.run({
|
||||
arguments: ["inspect-asset-catalog", app, "--json"],
|
||||
});
|
||||
expect(inspected.exitCode, inspected.stderr).toBe(0);
|
||||
const result = appleAssetCatalogResultSchema.parse(
|
||||
parseEvidence(inspected.json).normalized_result,
|
||||
);
|
||||
expect(result.catalogs).toEqual([]);
|
||||
expect(result.resource_key_matches).toEqual(
|
||||
!recognized
|
||||
? []
|
||||
: [
|
||||
{
|
||||
source_node_id: resource?.id,
|
||||
source_path: "Contents/Resources/Panel.nib",
|
||||
source_archive_sha256: createHash("sha256")
|
||||
.update(archive)
|
||||
.digest("hex"),
|
||||
field,
|
||||
key: "Toolbar",
|
||||
status: "unmatched",
|
||||
renditions: [],
|
||||
},
|
||||
],
|
||||
);
|
||||
const opened = await call("open_binary", { path: app });
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const mcp = await call("inspect_asset_catalog", {});
|
||||
expect(mcp.isError).not.toBe(true);
|
||||
expect(parseEvidence(mcp.structuredContent).normalized_result).toEqual(
|
||||
result,
|
||||
);
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
@@ -0,0 +1,69 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"reports every unresolved Electron path through CLI and MCP without launching",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-electron-invalid-paths-");
|
||||
const application = join(root, "main.js");
|
||||
await writeFile(application, "module.exports = {};\n");
|
||||
const missing = {
|
||||
executable_path: join(root, "missing-electron"),
|
||||
application_path: join(root, "missing-application"),
|
||||
application_root: join(root, "missing-root"),
|
||||
};
|
||||
const requestPath = join(root, "input.json");
|
||||
await writeFile(requestPath, JSON.stringify(missing));
|
||||
const response = await cli.run({
|
||||
arguments: ["capture-electron-scenario", requestPath, "--format", "json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode).toBe(1);
|
||||
const expectedIssues = Object.entries(missing).map(([field, path]) => ({
|
||||
path: [field],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining(path),
|
||||
}));
|
||||
expect(response.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: expectedIssues },
|
||||
});
|
||||
expect(response.stdout).toContain("ENOENT");
|
||||
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [field, path] of Object.entries(missing)) {
|
||||
const result = await call("capture_electron_scenario", {
|
||||
executable_path: process.execPath,
|
||||
application_path: application,
|
||||
application_root: root,
|
||||
[field]: path,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const content = result.content.find((item) => item.type === "text");
|
||||
if (content?.type !== "text") throw new Error("Missing error response");
|
||||
expect(JSON.parse(content.text)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [field],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringContaining(path),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(content.text).toContain("ENOENT");
|
||||
}
|
||||
const session = await call("binary_session", {});
|
||||
expect(session.isError, JSON.stringify(session)).not.toBe(true);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,88 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"decodes a rooted UIKit keyed-archive outlet through CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-cli-uikit-outlet-");
|
||||
const app = join(root, "UIKitFixture.app");
|
||||
const contents = join(app, "Contents");
|
||||
const resources = join(contents, "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
await mkdir(join(contents, "MacOS"));
|
||||
await writeFile(
|
||||
join(contents, "MacOS", "Fixture"),
|
||||
thinMach(0xfeedfacf, 0x0100000c),
|
||||
);
|
||||
await writeFile(
|
||||
join(contents, "Info.plist"),
|
||||
"<plist><dict><key>CFBundleExecutable</key><string>Fixture</string></dict></plist>",
|
||||
);
|
||||
await writeFile(
|
||||
join(resources, "Main.nib"),
|
||||
await readFile(
|
||||
join(process.cwd(), "tests/fixtures/interface-builder/UIKitOutlet.xml"),
|
||||
),
|
||||
);
|
||||
|
||||
const output = await cli.run({
|
||||
arguments: ["decode-interface-builder", app, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
const result = interfaceBuilderAnalysisSchema.parse(
|
||||
parseEvidence(output.json).normalized_result,
|
||||
);
|
||||
const owner = result.graph.nodes.find(
|
||||
({ attributes }) => attributes.interface_builder_object_id === "1",
|
||||
);
|
||||
const destination = result.graph.nodes.find(
|
||||
({ attributes }) => attributes.interface_builder_object_id === "2",
|
||||
);
|
||||
const outlet = result.graph.nodes.find(({ kind }) => kind === "outlet");
|
||||
expect(result.documents).toEqual([
|
||||
expect.objectContaining({ connection_count: 1 }),
|
||||
]);
|
||||
expect(outlet).toMatchObject({
|
||||
id: 'ib:"Contents/Resources/Main.nib":outlet:["archive:3"]',
|
||||
name: "view",
|
||||
attributes: {
|
||||
UISource: { archiveUID: 1 },
|
||||
UIDestination: { archiveUID: 2 },
|
||||
UILabel: "view",
|
||||
},
|
||||
});
|
||||
expect(owner).toBeDefined();
|
||||
expect(destination).toBeDefined();
|
||||
expect(
|
||||
result.graph.edges.some(
|
||||
({ from, to, relation }) =>
|
||||
from === owner?.id && to === outlet?.id && relation === "contains",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.graph.edges.some(
|
||||
({ from, to, relation }) =>
|
||||
from === outlet?.id &&
|
||||
to === destination?.id &&
|
||||
relation === "outlet_to",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(result.graph.coverage).toContainEqual(
|
||||
expect.objectContaining({
|
||||
facet: "connections:Contents/Resources/Main.nib",
|
||||
status: "complete",
|
||||
examined: 1,
|
||||
omitted: 0,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,626 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import type { JavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
const workerReferences = (graph: JavaScriptApplicationGraph) =>
|
||||
graph.nodes
|
||||
.filter(({ kind }) => kind === "worker")
|
||||
.flatMap((node) =>
|
||||
node.observations.map(({ properties, evidence }) => ({
|
||||
source:
|
||||
evidence.location.available &&
|
||||
evidence.location.value.kind === "source-range"
|
||||
? evidence.location.value.source
|
||||
: null,
|
||||
declared_specifier: properties.declared_specifier,
|
||||
expression: properties.expression,
|
||||
resolved_path: properties.resolved_path,
|
||||
mapped_paths: graph.edges
|
||||
.filter(
|
||||
({ relation, source_node_id }) =>
|
||||
relation === "maps_to" && source_node_id === node.node_id,
|
||||
)
|
||||
.map(({ properties: edge }) => edge.resolved_path),
|
||||
})),
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"promotes Worker URLs only for known constructor bindings through the CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-identity-");
|
||||
const identityCases = [
|
||||
...["globalThis", "window", "self"].map((namespace) => ({
|
||||
prefix: "",
|
||||
constructor: `new ${namespace}.Worker`,
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
})),
|
||||
...["worker_threads", "node:worker_threads"].flatMap((specifier) => [
|
||||
{
|
||||
prefix: `import { Worker } from "${specifier}";`,
|
||||
constructor: "new Worker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: `import * as threads from "${specifier}";`,
|
||||
constructor: "new threads.Worker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
]),
|
||||
{
|
||||
prefix: 'import { Worker as ThreadWorker } from "node:worker_threads";',
|
||||
constructor: "new ThreadWorker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: 'import { Worker } from "node:worker_threads";',
|
||||
constructor: "new (Worker as typeof Worker)",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: 'import * as threads from "node:worker_threads";',
|
||||
constructor: "new ((threads as typeof threads).Worker!)",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix:
|
||||
'import { Worker } from "node:worker_threads"; function start(globalThis) { globalThis.URL = Fake;',
|
||||
constructor: "new Worker",
|
||||
suffix: "}",
|
||||
resolves: true,
|
||||
},
|
||||
{
|
||||
prefix: 'globalThis.unrelated = Fake; URL.extra = "metadata";',
|
||||
constructor: "new Worker",
|
||||
suffix: "",
|
||||
resolves: true,
|
||||
},
|
||||
...[
|
||||
["class Worker {}", "new Worker", ""],
|
||||
["globalThis.Worker = Fake;", "new Worker", ""],
|
||||
["globalThis.Worker = Fake;", "new window.Worker", ""],
|
||||
["globalThis = replacement;", "new globalThis.Worker", ""],
|
||||
["function start(Worker) {", "new Worker", "}"],
|
||||
['import { Worker } from "./custom.js";', "new Worker", ""],
|
||||
["const custom = { Worker: class {} };", "new custom.Worker", ""],
|
||||
["function start(window) {", "new window.Worker", "}"],
|
||||
["function start(globalThis) {", "new globalThis.Worker", "}"],
|
||||
[
|
||||
'import type { Worker } from "node:worker_threads";',
|
||||
"new Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import { type Worker } from "node:worker_threads";',
|
||||
"new Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import type * as threads from "node:worker_threads";',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import threads from "node:worker_threads"; threads.Worker = Fake;',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'const threads = require("node:worker_threads"); threads.Worker = Fake;',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import threads = require("node:worker_threads"); threads.Worker = Fake;',
|
||||
"new threads.Worker",
|
||||
"",
|
||||
],
|
||||
[
|
||||
'import { Worker } from "node:worker_threads"; Worker = Fake;',
|
||||
"new Worker",
|
||||
"",
|
||||
],
|
||||
["", "Worker", ""],
|
||||
].map(([prefix, constructor, suffix]) => ({
|
||||
prefix,
|
||||
constructor,
|
||||
suffix,
|
||||
resolves: false,
|
||||
})),
|
||||
].map(({ prefix, constructor, suffix, resolves }, index) => ({
|
||||
source: `identity-${index}.ts`,
|
||||
prefix,
|
||||
expression: `${constructor}(new URL("./worker.js", import.meta.url))`,
|
||||
suffix,
|
||||
resolves,
|
||||
}));
|
||||
await writeFixtureFiles(root, {
|
||||
...Object.fromEntries(
|
||||
identityCases.map(({ source, prefix, expression, suffix }) => [
|
||||
source,
|
||||
`${prefix}\n${expression};${suffix}`,
|
||||
]),
|
||||
),
|
||||
"worker.js": "self.postMessage('existing worker file');",
|
||||
"custom.js": "export class Worker {}",
|
||||
"custom-alias.mjs":
|
||||
'import { Worker as ThreadWorker } from "./custom.js"; new ThreadWorker(new URL("./worker.js", import.meta.url));',
|
||||
});
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(identityCases.length);
|
||||
expect(references.some(({ source }) => source === "custom-alias.mjs")).toBe(
|
||||
false,
|
||||
);
|
||||
for (const { source, expression, resolves } of identityCases)
|
||||
expect(references).toContainEqual({
|
||||
source,
|
||||
declared_specifier: resolves ? "./worker.js" : null,
|
||||
expression: resolves ? null : expression,
|
||||
resolved_path: resolves ? "worker.js" : null,
|
||||
mapped_paths: resolves ? ["worker.js"] : [],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"resolves module-relative Worker URL constructors through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-module-url-");
|
||||
const cases = [
|
||||
{
|
||||
source: "nested/relative.mjs",
|
||||
expression: 'new Worker(new URL("./worker.js", import.meta.url));',
|
||||
specifier: "./worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
},
|
||||
...[
|
||||
'import.meta.unrelated = "metadata";',
|
||||
'globalThis["import.meta"] = { url: "file:///other/entry.mjs" };',
|
||||
'const meta = import.meta; meta.unrelated = "metadata";',
|
||||
'const ambient = globalThis; ambient.unrelated = "metadata";',
|
||||
'const copy = { ...import.meta }; Object.defineProperty(copy, "url", { value: "file:///other/entry.mjs" });',
|
||||
"const copy = { ...globalThis }; copy.URL = replacement;",
|
||||
"function update(globalThis) { const ambient = globalThis; ambient.URL = replacement; } update({});",
|
||||
"const define = Object.defineProperty.bind(Object);",
|
||||
'Object.defineProperty(...[import.meta, "unrelated", { value: "metadata" }]);',
|
||||
'let meta = import.meta; meta = {}; let base = import.meta.url; base = "file:///other/entry.mjs";',
|
||||
].map((mutation, index) => ({
|
||||
source: `nested/unrelated-meta-${index}.mjs`,
|
||||
expression: `import { Worker } from "node:worker_threads"; ${mutation} new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
specifier: "./worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
})),
|
||||
{
|
||||
source: "nested/parent.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("../parent-worker.js", import.meta.url));',
|
||||
specifier: "../parent-worker.js",
|
||||
resolved: "parent-worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/dot-segments.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./child/.././worker.js", import.meta.url));',
|
||||
specifier: "./child/.././worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/template.mjs",
|
||||
expression:
|
||||
"new Worker(new URL(`./template-worker.js`, import.meta.url));",
|
||||
specifier: "./template-worker.js",
|
||||
resolved: "nested/template-worker.js",
|
||||
},
|
||||
...[
|
||||
'new URL("./worker.js", import.meta.url) as URL',
|
||||
'<URL>new URL("./worker.js", import.meta.url)',
|
||||
'new URL("./worker.js", import.meta.url)!',
|
||||
'new URL("./worker.js", import.meta.url) satisfies URL',
|
||||
'((new URL("./worker.js", import.meta.url) as URL)!) satisfies URL',
|
||||
'new (URL as typeof URL)("./worker.js", import.meta.url)',
|
||||
'new URL("./worker.js" as string, import.meta.url as string)',
|
||||
'new URL("./worker.js", (import.meta as ImportMeta).url)',
|
||||
'new globalThis.URL("./worker.js", import.meta.url)',
|
||||
'new window.URL("./worker.js", import.meta.url)',
|
||||
'new self.URL("./worker.js", import.meta.url)',
|
||||
'new global.URL("./worker.js", import.meta.url)',
|
||||
'new ((globalThis as typeof globalThis)["URL"]!)("./worker.js", import.meta.url)',
|
||||
].map((urlExpression, index) => ({
|
||||
source: `nested/typed-${index}.ts`,
|
||||
expression: `new Worker(${urlExpression});`,
|
||||
specifier: "./worker.js",
|
||||
resolved: "nested/worker.js",
|
||||
})),
|
||||
{
|
||||
source: "nested/space.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./space%20worker.js?worker=1#entry", import.meta.url));',
|
||||
specifier: "./space%20worker.js?worker=1#entry",
|
||||
resolved: "nested/space worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/percent.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./percent%2520worker.js", import.meta.url));',
|
||||
specifier: "./percent%2520worker.js",
|
||||
resolved: "nested/percent%20worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/literal-percent.mjs",
|
||||
expression:
|
||||
'new Worker(new URL("./percent%25worker.js", import.meta.url));',
|
||||
specifier: "./percent%25worker.js",
|
||||
resolved: "nested/percent%worker.js",
|
||||
},
|
||||
...["?value=", "#value="].map((suffix, index) => {
|
||||
const specifier = `./worker.js${suffix}%2F%2E%5C%00%FF%GG%2%\\\0`;
|
||||
return {
|
||||
source: `nested/suffix-${index}.mjs`,
|
||||
expression: `new Worker(new URL(${JSON.stringify(specifier)}, import.meta.url));`,
|
||||
specifier,
|
||||
resolved: "nested/worker.js",
|
||||
};
|
||||
}),
|
||||
{
|
||||
source: "bundled/entry.mjs",
|
||||
expression:
|
||||
'self.webpackChunkdemo.push([[1], {1: function(module, exports, require) { new Worker(new URL("./worker.js", import.meta.url)); }, "./worker.js": function(module) { module.exports = 42; }}]);',
|
||||
specifier: "./worker.js",
|
||||
resolved: "bundled/worker.js",
|
||||
},
|
||||
{
|
||||
source: "nested/literal.mjs",
|
||||
expression: 'new Worker("./literal-worker.js");',
|
||||
specifier: "./literal-worker.js",
|
||||
resolved: "nested/literal-worker.js",
|
||||
},
|
||||
];
|
||||
await writeFixtureFiles(root, {
|
||||
...Object.fromEntries(
|
||||
cases.flatMap(({ source, expression, resolved }) => [
|
||||
[source, expression],
|
||||
[resolved, `self.postMessage(${JSON.stringify(resolved)});`],
|
||||
]),
|
||||
),
|
||||
"nested/percent worker.js": "self.postMessage('double-decoding decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
expect(workerReferences(result.graph)).toEqual(
|
||||
expect.arrayContaining(
|
||||
cases.map(({ source, specifier, resolved }) => ({
|
||||
source,
|
||||
declared_specifier: specifier,
|
||||
expression: null,
|
||||
resolved_path: resolved,
|
||||
mapped_paths: [resolved],
|
||||
})),
|
||||
),
|
||||
);
|
||||
expect(workerReferences(result.graph)).toHaveLength(cases.length);
|
||||
expect(result.graph.nodes).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "javascript-module",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({ module_key: "./worker.js" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"keeps unsupported Worker URL expressions and missing exact files unresolved through the CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-url-unknown-");
|
||||
const malformedPercentPaths = [
|
||||
["./worker%.js", "worker%.js"],
|
||||
["./worker%2.js", "worker%2.js"],
|
||||
["./worker%GG.js", "worker%GG.js"],
|
||||
["./space%20worker%GG.js", "space worker%GG.js"],
|
||||
];
|
||||
const expressions = {
|
||||
"dynamic-path.mjs": "new Worker(new URL(path, import.meta.url));",
|
||||
"absolute.mjs":
|
||||
'import { Worker } from "node:worker_threads"; new Worker(new URL("/worker.js", import.meta.url));',
|
||||
"typed-apply-meta.ts":
|
||||
'import { Worker } from "node:worker_threads"; Object.defineProperty.apply(Object, ([import.meta, "url", { value: "file:///other.mjs" }] as const)); new Worker(new URL("./worker.js", import.meta.url));',
|
||||
"overwritten-qualified-url.mjs":
|
||||
'globalThis.URL = replacement; new Worker(new globalThis.URL("./worker.js", import.meta.url));',
|
||||
"shadowed-qualified-url.mjs":
|
||||
'function start(window) { new Worker(new window.URL("./worker.js", import.meta.url)); }',
|
||||
...Object.fromEntries(
|
||||
["globalThis.URL", "URL", 'globalThis["URL"]'].map((target, index) => [
|
||||
`overwritten-url-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; const RealURL = URL; ${target} = class { constructor() { return new RealURL("./other.js", import.meta.url); } }; new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
[
|
||||
"delete globalThis.URL;",
|
||||
"({ URL: globalThis.URL } = replacements);",
|
||||
"globalThis[key] = replacement;",
|
||||
'Object.defineProperty(globalThis, "URL", { value: replacement });',
|
||||
'Reflect.set(globalThis, "URL", replacement);',
|
||||
"globalThis.globalThis.URL = replacement;",
|
||||
"globalThis.global.URL = replacement;",
|
||||
"const ambient = globalThis; ambient.URL = replacement;",
|
||||
"const { globalThis: ambient } = globalThis; ambient.URL = replacement;",
|
||||
].map((mutation, index) => [
|
||||
`mutated-url-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; ${mutation} new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
[
|
||||
'import.meta.url = "file:///other/entry.mjs";',
|
||||
"delete import.meta.url;",
|
||||
'Object.defineProperty(import.meta, "url", { value: "file:///other/entry.mjs" });',
|
||||
"import.meta[key] = replacement;",
|
||||
'const meta = import.meta; const alias = meta; alias.url = "file:///other/entry.mjs";',
|
||||
'let meta = import.meta; meta.url = "file:///other/entry.mjs"; meta = {};',
|
||||
'const define = Object.defineProperty; define(import.meta, "url", { value: "file:///other/entry.mjs" });',
|
||||
'const set = Reflect.set.bind(Reflect); set(import.meta, "url", "file:///other/entry.mjs");',
|
||||
'Object.defineProperty.bind(Object, import.meta, "url")({ value: "file:///other/entry.mjs" });',
|
||||
'Object.assign(...[import.meta, { url: "file:///other/entry.mjs" }]);',
|
||||
'Object.defineProperty(...[import.meta, "url", { value: "file:///other/entry.mjs" }]);',
|
||||
].map((mutation, index) => [
|
||||
`mutated-import-meta-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; ${mutation} new Worker(new URL("./worker.js", import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
...Object.fromEntries(
|
||||
malformedPercentPaths.map(([specifier], index) => [
|
||||
`malformed-percent-${index}.mjs`,
|
||||
`import { Worker } from "node:worker_threads"; new Worker(new URL(${JSON.stringify(specifier)}, import.meta.url));`,
|
||||
]),
|
||||
),
|
||||
"dynamic-base.mjs": 'new Worker(new URL("./worker.js", base));',
|
||||
"shadowed.mjs":
|
||||
'function start(URL) { return new Worker(new URL("./worker.js", import.meta.url)); }',
|
||||
"typed-shadowed.ts":
|
||||
'function start(URL: typeof globalThis.URL) { return new Worker((new (URL as typeof globalThis.URL)("./worker.js", import.meta.url) as URL)!); }',
|
||||
"typed-dynamic-path.ts":
|
||||
"new Worker((new URL(path as string, import.meta.url) as URL)!);",
|
||||
"typed-dynamic-base.ts":
|
||||
'new Worker((new URL("./worker.js", base as string) as URL)!);',
|
||||
"call.mjs": 'new Worker(URL("./worker.js", import.meta.url));',
|
||||
"custom.mjs":
|
||||
'new Worker(new custom.URL("./worker.js", import.meta.url));',
|
||||
"extension.mjs":
|
||||
'new Worker(new URL("./extensionless", import.meta.url));',
|
||||
"directory.mjs": 'new Worker(new URL("./directory", import.meta.url));',
|
||||
"directory-dot.mjs":
|
||||
'new Worker(new URL("./worker.js/.", import.meta.url));',
|
||||
"directory-parent.mjs":
|
||||
'new Worker(new URL("./worker.js/child/..", import.meta.url));',
|
||||
"empty-segment.mjs":
|
||||
'new Worker(new URL("./child//../worker.js", import.meta.url));',
|
||||
"package.mjs":
|
||||
'new Worker(new URL("./package-worker", import.meta.url));',
|
||||
"external.mjs":
|
||||
'new Worker(new URL("https://example.test/worker.js", import.meta.url));',
|
||||
"empty.mjs": 'new Worker(new URL("", import.meta.url));',
|
||||
"query.mjs": 'new Worker(new URL("?worker=1", import.meta.url));',
|
||||
"whitespace.mjs":
|
||||
'new Worker(new URL(" ./worker.js ", import.meta.url));',
|
||||
"control.mjs": 'new Worker(new URL("./worker\\t.js", import.meta.url));',
|
||||
"leading-control.mjs":
|
||||
'new Worker(new URL("\\u0001./worker.js", import.meta.url));',
|
||||
};
|
||||
const knownSpecifiers: Readonly<Record<string, string>> = {
|
||||
"extension.mjs": "./extensionless",
|
||||
"directory.mjs": "./directory",
|
||||
"directory-dot.mjs": "./worker.js/.",
|
||||
"directory-parent.mjs": "./worker.js/child/..",
|
||||
"empty-segment.mjs": "./child//../worker.js",
|
||||
"package.mjs": "./package-worker",
|
||||
"external.mjs": "https://example.test/worker.js",
|
||||
};
|
||||
await writeFixtureFiles(root, {
|
||||
...expressions,
|
||||
...Object.fromEntries(
|
||||
malformedPercentPaths.map(([, decoy]) => [
|
||||
decoy,
|
||||
"self.postMessage('malformed percent pathname decoy');",
|
||||
]),
|
||||
),
|
||||
"worker.js": "self.postMessage('existing decoy');",
|
||||
"other.js": "self.postMessage('custom URL result decoy');",
|
||||
"extensionless.js": "self.postMessage('extension decoy');",
|
||||
"directory/index.js": "self.postMessage('index decoy');",
|
||||
"package-worker/package.json": JSON.stringify({ main: "selected.js" }),
|
||||
"package-worker/selected.js": "self.postMessage('package main decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(Object.keys(expressions).length);
|
||||
for (const [source, expression] of Object.entries(expressions)) {
|
||||
const specifier = knownSpecifiers[source] ?? null;
|
||||
expect(references).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source,
|
||||
declared_specifier: specifier,
|
||||
expression:
|
||||
specifier === null
|
||||
? expression.slice(
|
||||
expression.indexOf("new Worker("),
|
||||
expression.lastIndexOf(";"),
|
||||
)
|
||||
: null,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"bounds repeated ambient alias branches through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-alias-branches-");
|
||||
const aliases = [
|
||||
"const alias0 = globalThis;",
|
||||
...Array.from(
|
||||
{ length: 40 },
|
||||
(_, index) =>
|
||||
`const alias${index + 1} = flag${index} ? alias${index} : alias${index};`,
|
||||
),
|
||||
"alias40.URL = replacement;",
|
||||
].join("\n");
|
||||
const splitAliases = [
|
||||
"const alias0 = globalThis;",
|
||||
...Array.from(
|
||||
{ length: 40 },
|
||||
(_, index) =>
|
||||
`const left${index} = alias${index}; const right${index} = alias${index}; const alias${index + 1} = flag${index} ? left${index} : right${index};`,
|
||||
),
|
||||
"alias40.URL = replacement;",
|
||||
].join("\n");
|
||||
const memberAliases = [
|
||||
"const alias0 = globalThis;",
|
||||
...Array.from(
|
||||
{ length: 40 },
|
||||
(_, index) =>
|
||||
`const alias${index + 1} = flag${index} ? alias${index}.globalThis : alias${index}.window;`,
|
||||
),
|
||||
"alias40.URL = replacement;",
|
||||
].join("\n");
|
||||
const expression = 'new Worker(new URL("./worker.js", import.meta.url))';
|
||||
await writeFixtureFiles(root, {
|
||||
"entry.mjs": `import { Worker } from "node:worker_threads";\n${aliases}\n${expression};`,
|
||||
"split.mjs": `import { Worker } from "node:worker_threads";\n${splitAliases}\n${expression};`,
|
||||
"member.mjs": `import { Worker } from "node:worker_threads";\n${memberAliases}\n${expression};`,
|
||||
"worker.js": "self.postMessage('existing alias-mutation decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory(
|
||||
"CLI",
|
||||
{ run: (invocation) => cli.run({ ...invocation, timeoutMs: 20_000 }) },
|
||||
root,
|
||||
);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(3);
|
||||
expect(references).toEqual(
|
||||
expect.arrayContaining(
|
||||
["entry.mjs", "split.mjs", "member.mjs"].map((source) => ({
|
||||
source,
|
||||
declared_specifier: null,
|
||||
expression,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
})),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"keeps Node Worker filesystem strings unresolved through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-node-worker-filesystem-");
|
||||
const cases = [
|
||||
{
|
||||
prefix: 'import { Worker } from "node:worker_threads";',
|
||||
expression: 'new Worker("./worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import { Worker as ThreadWorker } from "worker_threads";',
|
||||
expression: 'new ThreadWorker("/worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import * as threads from "node:worker_threads";',
|
||||
expression: 'new threads.Worker("./worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import { Worker } from "node:worker_threads";',
|
||||
expression: 'new (Worker as typeof Worker)("/worker.js")',
|
||||
},
|
||||
{
|
||||
prefix: 'import * as threads from "node:worker_threads";',
|
||||
expression: 'new ((threads as typeof threads).Worker!)("./worker.js")',
|
||||
},
|
||||
].map((fixture, index) => ({
|
||||
...fixture,
|
||||
source: `nested/node-literal-${index}.ts`,
|
||||
}));
|
||||
await writeFixtureFiles(root, {
|
||||
...Object.fromEntries(
|
||||
cases.map(({ prefix, expression, source }) => [
|
||||
source,
|
||||
`${prefix}\n${expression};`,
|
||||
]),
|
||||
),
|
||||
"worker.js": "self.postMessage('filesystem-root decoy');",
|
||||
"nested/worker.js": "self.postMessage('source-sibling decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(cases.length);
|
||||
for (const { source, expression } of cases)
|
||||
expect(references).toContainEqual({
|
||||
source,
|
||||
declared_specifier: null,
|
||||
expression,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Windows cannot materialize the pipe-named directory needed for this decoy.
|
||||
cliTest.skipIf(process.platform === "win32")(
|
||||
"keeps file-URL drive letters distinct from encoded POSIX paths through the compiled CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-worker-url-drive-");
|
||||
await writeFixtureFiles(root, {
|
||||
"dist/drive.mjs": 'new Worker(new URL("c|/worker.js", import.meta.url));',
|
||||
"dist/encoded.mjs":
|
||||
'new Worker(new URL("c%7C/worker.js", import.meta.url));',
|
||||
"dist/c|/worker.js": "self.postMessage('existing relative-path decoy');",
|
||||
});
|
||||
|
||||
const result = await analyzeJavaScriptDirectory("CLI", cli, root);
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
const references = workerReferences(result.graph);
|
||||
expect(references).toHaveLength(2);
|
||||
expect(references).toEqual(
|
||||
expect.arrayContaining([
|
||||
{
|
||||
source: "dist/drive.mjs",
|
||||
declared_specifier: "c|/worker.js",
|
||||
expression: null,
|
||||
resolved_path: null,
|
||||
mapped_paths: [],
|
||||
},
|
||||
{
|
||||
source: "dist/encoded.mjs",
|
||||
declared_specifier: "c%7C/worker.js",
|
||||
expression: null,
|
||||
resolved_path: "dist/c|/worker.js",
|
||||
mapped_paths: ["dist/c|/worker.js"],
|
||||
},
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { z } from "zod";
|
||||
@@ -28,12 +29,18 @@ const createPackageSubpathFixture = async () => {
|
||||
'const literal = require("fi%xture");',
|
||||
'const scalar = require("scalar");',
|
||||
'const self = require("../node_modules/fi%xture/run.cjs");',
|
||||
'const uri = require("file:///src/uri-dep.cjs");',
|
||||
'const relativeUri = require("./uri-dep.cjs");',
|
||||
].join("\n");
|
||||
const selfSource = 'const self = require("fi%xture"); module.exports = self;';
|
||||
const importSource = 'import literal from "fi%xture";';
|
||||
const importSource = [
|
||||
'import literal from "fi%xture";',
|
||||
'import uri from "FILE:///src/uri-dep.cjs?token=%2F#entry";',
|
||||
].join("\n");
|
||||
const files = {
|
||||
"src/main.cjs": source,
|
||||
"src/imports.mjs": importSource,
|
||||
"src/uri-dep.cjs": "module.exports = 42;",
|
||||
"src/node_modules/fixture/parser.js": "module.exports = 1;",
|
||||
"src/node_modules/fixture.js": "module.exports = 'file';",
|
||||
"src/node_modules/fixture/index.js": "module.exports = 'directory';",
|
||||
@@ -104,11 +111,20 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"fi%xture": "node_modules/fi%xture.js",
|
||||
scalar: "node_modules/scalar.js",
|
||||
"../node_modules/fi%xture/run.cjs": "node_modules/fi%xture/run.cjs",
|
||||
"./uri-dep.cjs": "src/uri-dep.cjs",
|
||||
};
|
||||
for (const [specifier, target] of Object.entries(expectedTargets))
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(specifier)).replaceAll("\\", "/"),
|
||||
).toBe(target);
|
||||
expect(nativeRequire("./uri-dep.cjs")).toBe(42);
|
||||
for (const specifier of [
|
||||
"file:///src/uri-dep.cjs",
|
||||
pathToFileURL(join(root, "src/uri-dep.cjs")).href,
|
||||
])
|
||||
expect(() => nativeRequire.resolve(specifier)).toThrow(
|
||||
expect.objectContaining({ code: "MODULE_NOT_FOUND" }),
|
||||
);
|
||||
for (const specifier of ["exported/parser/", "exported/hidden", "blocked"])
|
||||
expect(() => nativeRequire.resolve(specifier)).toThrow(
|
||||
expect.objectContaining({ code: "ERR_PACKAGE_PATH_NOT_EXPORTED" }),
|
||||
@@ -137,6 +153,41 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
},
|
||||
])
|
||||
expectResolvedImports(imports, observation);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "require",
|
||||
specifier: "file:///src/uri-dep.cjs",
|
||||
resolved_path: null,
|
||||
resolution_status: "external",
|
||||
}),
|
||||
evidence: sourceEvidence("src/main.cjs", source),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
kind: "require",
|
||||
specifier: "file:///src/uri-dep.cjs",
|
||||
resolved_path: null,
|
||||
}),
|
||||
evidence: sourceEvidence("src/main.cjs", source),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "import",
|
||||
specifier: "FILE:///src/uri-dep.cjs?token=%2F#entry",
|
||||
resolved_path: "src/uri-dep.cjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: sourceEvidence("src/imports.mjs", importSource),
|
||||
}),
|
||||
);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { join, relative } from "node:path";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
@@ -10,6 +12,318 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const compiler = join(
|
||||
dirname(createRequire(import.meta.url).resolve("typescript/package.json")),
|
||||
"bin",
|
||||
"tsc",
|
||||
);
|
||||
|
||||
const typedLines = [
|
||||
'export import typed = require("typed-package");',
|
||||
'import type TypeOnly = require("./type-only.cjs");',
|
||||
] as const;
|
||||
const typedSource = typedLines.join("\n");
|
||||
const aliasSource = [
|
||||
'import raw = require("typed-package");',
|
||||
"const alias = raw;",
|
||||
"export { alias };",
|
||||
].join("\n");
|
||||
const mixedSource = [
|
||||
'import { value as imported } from "mixed-package";',
|
||||
'import required = require("mixed-package");',
|
||||
"const mixed = Date.now() > 0 ? imported : required.value;",
|
||||
"export { imported as staticChoice, mixed };",
|
||||
"export const requireChoice = required.value;",
|
||||
].join("\n");
|
||||
const typescriptSourceFiles = {
|
||||
"typed.cts": typedSource,
|
||||
"typed.mts": typedSource,
|
||||
"alias.cts": aliasSource,
|
||||
"alias.mts": aliasSource,
|
||||
"mixed.cts": mixedSource,
|
||||
"mixed.mts": mixedSource,
|
||||
};
|
||||
const typedPackageFiles = {
|
||||
"node_modules/typed-package/package.json": JSON.stringify({
|
||||
exports: { require: "./actual.cjs", import: "./decoy.mjs" },
|
||||
}),
|
||||
"node_modules/typed-package/actual.cjs": "module.exports = 42;",
|
||||
"node_modules/typed-package/actual.d.cts":
|
||||
"declare const value: number; export = value;",
|
||||
"node_modules/typed-package/decoy.mjs": "export default 99;",
|
||||
"node_modules/typed-package/decoy.d.mts":
|
||||
"declare const value: number; export default value;",
|
||||
"node_modules/mixed-package/package.json": JSON.stringify({
|
||||
exports: { require: "./actual.cjs", import: "./decoy.mjs" },
|
||||
}),
|
||||
"node_modules/mixed-package/actual.cjs": "exports.value = 42;",
|
||||
"node_modules/mixed-package/actual.d.cts":
|
||||
"export declare const value: number;",
|
||||
"node_modules/mixed-package/decoy.mjs": "export const value = 99;",
|
||||
"node_modules/mixed-package/decoy.d.mts":
|
||||
"export declare const value: number;",
|
||||
};
|
||||
|
||||
const expectNativeModuleControls = async (root: string): Promise<void> => {
|
||||
const emitted = await createTestTempDirectory("rea-import-equals-output-");
|
||||
await writeFixtureFiles(emitted, typedPackageFiles);
|
||||
await execute(
|
||||
process.execPath,
|
||||
[
|
||||
compiler,
|
||||
"--module",
|
||||
"NodeNext",
|
||||
"--moduleResolution",
|
||||
"NodeNext",
|
||||
"--target",
|
||||
"ES2022",
|
||||
"--skipLibCheck",
|
||||
"--allowJs",
|
||||
"--outDir",
|
||||
emitted,
|
||||
join(root, "typed.cts"),
|
||||
join(root, "typed.mts"),
|
||||
join(root, "alias.cts"),
|
||||
join(root, "alias.mts"),
|
||||
join(root, "mixed.cts"),
|
||||
join(root, "mixed.mts"),
|
||||
],
|
||||
{ cwd: root, timeout: 10_000 },
|
||||
);
|
||||
for (const [filename, script] of [
|
||||
[
|
||||
"typed.cjs",
|
||||
'console.log(require("./typed.cjs").typed, require("./alias.cjs").alias);',
|
||||
],
|
||||
[
|
||||
"typed.mjs",
|
||||
'Promise.all([import("./typed.mjs"), import("./alias.mjs")]).then(([first, second]) => console.log(first.typed, second.alias));',
|
||||
],
|
||||
] as const) {
|
||||
const typedControl = await execute(process.execPath, ["-e", script], {
|
||||
cwd: emitted,
|
||||
timeout: 5_000,
|
||||
});
|
||||
expect(typedControl.stdout.trim()).toBe("42 42");
|
||||
expect(await readFile(join(emitted, filename), "utf8")).not.toContain(
|
||||
"./type-only.cjs",
|
||||
);
|
||||
}
|
||||
for (const [filename, expected] of [
|
||||
["mixed.cjs", "42 42 42"],
|
||||
["mixed.mjs", "99 42 99"],
|
||||
] as const) {
|
||||
const control = await execute(
|
||||
process.execPath,
|
||||
[
|
||||
"-e",
|
||||
`import("./${filename}").then(({staticChoice, requireChoice, mixed}) => console.log(staticChoice, requireChoice, mixed));`,
|
||||
],
|
||||
{ cwd: emitted, timeout: 5_000 },
|
||||
);
|
||||
expect(control.stdout.trim()).toBe(expected);
|
||||
}
|
||||
const nativeRequire = createRequire(join(root, "main.cjs"));
|
||||
for (const name of ["dependency", "nested"])
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(`./${name}.cjs`)).replaceAll(
|
||||
"\\",
|
||||
"/",
|
||||
),
|
||||
).toBe(`${name}.cjs`);
|
||||
};
|
||||
|
||||
const expectAliasRelationships = (
|
||||
graph: ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>["graph"],
|
||||
): void => {
|
||||
for (const source of ["alias.cts", "alias.mts"]) {
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "export",
|
||||
local_name: "alias",
|
||||
exported_name: "alias",
|
||||
resolution_mode: "require",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
resolution_status: "resolved",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
artifact: expect.objectContaining({
|
||||
sha256: createHash("sha256").update(aliasSource).digest("hex"),
|
||||
}),
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const expectMixedRelationships = (
|
||||
graph: ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>["graph"],
|
||||
): void => {
|
||||
const exported = (source: string, name: string) =>
|
||||
graph.edges.filter(
|
||||
({ relation, properties, evidence }) =>
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "export" &&
|
||||
properties.exported_name === name &&
|
||||
evidence.location.available &&
|
||||
evidence.location.value.kind === "source-range" &&
|
||||
evidence.location.value.source === source,
|
||||
);
|
||||
for (const source of ["mixed.cts", "mixed.mts"]) {
|
||||
for (const [name, target] of [
|
||||
["staticChoice", source.endsWith(".cts") ? "actual.cjs" : "decoy.mjs"],
|
||||
["requireChoice", "actual.cjs"],
|
||||
] as const)
|
||||
expect(exported(source, name)).toMatchObject([
|
||||
{
|
||||
properties: {
|
||||
resolved_path: `node_modules/mixed-package/${target}`,
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
artifact: {
|
||||
sha256: createHash("sha256").update(mixedSource).digest("hex"),
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
expect(exported("mixed.cts", "mixed")).toMatchObject([
|
||||
{
|
||||
properties: {
|
||||
resolved_path: "node_modules/mixed-package/actual.cjs",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
artifact: {
|
||||
sha256: createHash("sha256").update(mixedSource).digest("hex"),
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(exported("mixed.mts", "mixed")).toEqual([]);
|
||||
};
|
||||
|
||||
const expectImportEqualsRelationships = (
|
||||
graph: ReturnType<
|
||||
typeof javascriptApplicationAnalysisResultSchema.parse
|
||||
>["graph"],
|
||||
): void => {
|
||||
for (const [sourcePath, format] of [
|
||||
["typed.cts", "commonjs"],
|
||||
["typed.mts", "esm"],
|
||||
] as const) {
|
||||
const typedLinks = graph.edges.filter(
|
||||
({ relation, properties, evidence: edgeEvidence }) =>
|
||||
relation === "imports" &&
|
||||
properties.module_link_kind === "require" &&
|
||||
edgeEvidence.location.available &&
|
||||
edgeEvidence.location.value.kind === "source-range" &&
|
||||
edgeEvidence.location.value.source === sourcePath,
|
||||
);
|
||||
expect(typedLinks).toHaveLength(1);
|
||||
expect(typedLinks[0]).toMatchObject({
|
||||
properties: {
|
||||
specifier: "typed-package",
|
||||
imported_name: null,
|
||||
local_name: "typed",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
resolution_status: "resolved",
|
||||
},
|
||||
evidence: {
|
||||
artifact: {
|
||||
available: true,
|
||||
sha256: createHash("sha256").update(typedSource).digest("hex"),
|
||||
},
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
source: sourcePath,
|
||||
start: { line: 1, column: 7 },
|
||||
end: { line: 1, column: typedLines[0].length },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
module_link_kind: "export",
|
||||
local_name: "typed",
|
||||
resolution_mode: "require",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
}),
|
||||
evidence: expect.objectContaining({
|
||||
location: expect.objectContaining({
|
||||
value: expect.objectContaining({ source: sourcePath }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
graph.nodes.flatMap(({ observations }) => observations),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
semantic_role: "source-module",
|
||||
path: sourcePath,
|
||||
export_names: ["typed"],
|
||||
export_relationships: 1,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, evidence: edgeEvidence }) =>
|
||||
relation === "exposes" &&
|
||||
edgeEvidence.location.available &&
|
||||
edgeEvidence.location.value.kind === "source-range" &&
|
||||
edgeEvidence.location.value.source === sourcePath,
|
||||
),
|
||||
).toHaveLength(1);
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
relation: "imports",
|
||||
properties: expect.objectContaining({
|
||||
kind: "require",
|
||||
specifier: "typed-package",
|
||||
resolved_path: "node_modules/typed-package/actual.cjs",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
graph.nodes.flatMap(({ observations }) => observations),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
semantic_role: "source-module",
|
||||
path: sourcePath,
|
||||
module_format: format,
|
||||
import_relationships: 1,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(
|
||||
graph.edges.filter(
|
||||
({ relation, properties }) =>
|
||||
relation === "imports" && properties.specifier === "./type-only.cjs",
|
||||
),
|
||||
).toHaveLength(0);
|
||||
};
|
||||
|
||||
cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"retains unbound CommonJS semantic relationships through %s",
|
||||
@@ -34,20 +348,16 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
"imports.mjs": 'import "./dependency.cjs";',
|
||||
"dependency.cjs": 'throw new Error("fixture must not execute");',
|
||||
"nested.cjs": 'throw new Error("fixture must not execute");',
|
||||
...typescriptSourceFiles,
|
||||
"type-only.d.cts": "declare const value: unknown; export = value;",
|
||||
};
|
||||
await Promise.all(
|
||||
Object.entries(files).map(([path, text]) =>
|
||||
writeFile(join(root, path), text),
|
||||
),
|
||||
);
|
||||
const nativeRequire = createRequire(join(root, "main.cjs"));
|
||||
for (const name of ["dependency", "nested"])
|
||||
expect(
|
||||
relative(root, nativeRequire.resolve(`./${name}.cjs`)).replaceAll(
|
||||
"\\",
|
||||
"/",
|
||||
),
|
||||
).toBe(`${name}.cjs`);
|
||||
await writeFixtureFiles(root, typedPackageFiles);
|
||||
await expectNativeModuleControls(root);
|
||||
|
||||
let document: unknown;
|
||||
if (surface === "CLI") {
|
||||
@@ -70,6 +380,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expectImportEqualsRelationships(graph);
|
||||
expectAliasRelationships(graph);
|
||||
expectMixedRelationships(graph);
|
||||
const links = graph.edges.filter(
|
||||
({ relation, properties, evidence: edgeEvidence }) =>
|
||||
relation === "imports" &&
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"reports Webpack exports attached to renamed factory parameters",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-webpack-renamed-exports-");
|
||||
await mkdir(join(root, "src"));
|
||||
await writeFile(
|
||||
join(root, "src", "chunk.js"),
|
||||
`globalThis.webpackChunkApp.push([[1], {
|
||||
17(module, __webpack_exports__, __webpack_require__) {
|
||||
__webpack_require__.d(__webpack_exports__, { alpha: () => 1, "beta.gamma": () => 2 });
|
||||
Object.defineProperty(__webpack_exports__, "delta", { enumerable: true, get() { return 3; } });
|
||||
__webpack_require__.d(__webpack_exports__.nested, { nested_target: () => 0 });
|
||||
__webpack_exports__ = { rebound: () => 0 };
|
||||
__webpack_require__.d({}, { unrelated: () => 0 });
|
||||
{ const exports = {}; __webpack_require__.d(exports, { shadowed_exports: () => 5 }); }
|
||||
},
|
||||
23(m, e, r) { r.d(e, { alpha: () => 1 }); }
|
||||
}]);`,
|
||||
);
|
||||
const response = await cli.run({
|
||||
arguments: ["analyze-javascript-application", root, "--format", "json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(response.exitCode).toBe(0);
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
parseEvidence(response.json).normalized_result,
|
||||
);
|
||||
const modules = result.graph.nodes
|
||||
.filter(({ kind }) => kind === "javascript-module")
|
||||
.map(({ observations }) => observations[0]?.properties);
|
||||
expect(modules).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
module_key: "17",
|
||||
exports: ["alpha", "beta.gamma", "delta"],
|
||||
}),
|
||||
expect.objectContaining({ module_key: "23", exports: ["alpha"] }),
|
||||
]),
|
||||
);
|
||||
expect(result.graph.coverage.status).toBe("complete");
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,84 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const cli = fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url));
|
||||
const plist =
|
||||
'<?xml version="1.0"?><plist version="1.0"><dict><key>label</key><string>hello</string></dict></plist>';
|
||||
|
||||
it("compares identical complete plist inventories across CLI and MCP and creates no unknowns", async () => {
|
||||
const root = await createTestTempDirectory("rea-plist-compare-acceptance-");
|
||||
const leftPath = join(root, "left.plist");
|
||||
const rightPath = join(root, "right.plist");
|
||||
await Promise.all([writeFile(leftPath, plist), writeFile(rightPath, plist)]);
|
||||
|
||||
const cliResult = await execute(process.execPath, [
|
||||
cli,
|
||||
"inspect-artifact",
|
||||
leftPath,
|
||||
"--json",
|
||||
]);
|
||||
const cliInspection = artifactInspectionResultSchema.parse(
|
||||
parseEvidence(JSON.parse(cliResult.stdout)).normalized_result,
|
||||
);
|
||||
const cliInventory = cliInspection.substeps[0]?.evidence;
|
||||
if (cliInventory === undefined)
|
||||
throw new Error("CLI inspection did not retain inventory Evidence");
|
||||
expect(cliInventory.normalized_result).toMatchObject({
|
||||
coverage_status: "complete",
|
||||
limitations: ["Artifact has no child container entries."],
|
||||
});
|
||||
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const opened = await call("open_binary", { path: rightPath });
|
||||
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
|
||||
const inspected = await call("inspect_artifact", {});
|
||||
expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true);
|
||||
const mcpInspection = artifactInspectionResultSchema.parse(
|
||||
parseEvidence(inspected.structuredContent).normalized_result,
|
||||
);
|
||||
const mcpInventory = mcpInspection.substeps[0]?.evidence;
|
||||
if (mcpInventory === undefined)
|
||||
throw new Error("MCP inspection did not retain inventory Evidence");
|
||||
expect(mcpInventory.normalized_result).toMatchObject({
|
||||
coverage_status: "complete",
|
||||
limitations: ["Artifact has no child container entries."],
|
||||
});
|
||||
|
||||
const compared = await call("compare_artifacts", {
|
||||
left: cliInventory,
|
||||
right: mcpInventory,
|
||||
});
|
||||
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
|
||||
const comparison = parseEvidence(compared.structuredContent);
|
||||
expect(comparison.normalized_result).toMatchObject({
|
||||
status: "unchanged",
|
||||
summary: { unchanged: 1, unknown: 0 },
|
||||
changes: [],
|
||||
});
|
||||
|
||||
const behavior = await call("find_changed_behavior", {
|
||||
comparisons: [comparison],
|
||||
});
|
||||
expect(behavior.isError, JSON.stringify(behavior)).not.toBe(true);
|
||||
expect(behavior.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
behavior_status: "unknown",
|
||||
findings: { items: [] },
|
||||
},
|
||||
});
|
||||
const unknowns = await call("list_unknowns", {
|
||||
domain: "artifact-comparison",
|
||||
});
|
||||
expect(unknowns.isError, JSON.stringify(unknowns)).not.toBe(true);
|
||||
expect(unknowns.structuredContent).toMatchObject({ result: { items: [] } });
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
|
||||
import { artifactInventoryResultSchema } from "../../src/domain/artifactGraph.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import {
|
||||
fatImage,
|
||||
CPU,
|
||||
machoImage,
|
||||
} from "../../src/artifacts/apple/MachoImage.fixture.js";
|
||||
import { javaClassFile } from "../fixtures/javaClassFile.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const cli = fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url));
|
||||
|
||||
const archive = async (
|
||||
entries: readonly (readonly [string, Uint8Array])[],
|
||||
): Promise<Buffer> => {
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
for (const [name, bytes] of entries)
|
||||
await writer.add(name, new Uint8ArrayReader(bytes));
|
||||
return Buffer.from(await writer.close());
|
||||
};
|
||||
|
||||
const inspectArchive = async (path: string) => {
|
||||
const result = await execute(process.execPath, [
|
||||
cli,
|
||||
"inspect-artifact",
|
||||
path,
|
||||
"--json",
|
||||
]);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
parseEvidence(JSON.parse(result.stdout)).normalized_result,
|
||||
);
|
||||
const evidence = inspection.substeps[0]?.evidence;
|
||||
if (evidence === undefined)
|
||||
throw new Error("CLI inspection did not retain inventory Evidence");
|
||||
return artifactInventoryResultSchema.parse(evidence.normalized_result);
|
||||
};
|
||||
|
||||
it("keeps valid JVM classes from being classified as Mach-O while identifying FAT controls", async () => {
|
||||
const directory = await createTestTempDirectory("rea-jvm-inventory-");
|
||||
const javaEntries = [
|
||||
["Hello.class", javaClassFile()],
|
||||
["pkg/Big.class", javaClassFile(4000)],
|
||||
] as const;
|
||||
const fatControls = [
|
||||
[
|
||||
"fat-be32.bin",
|
||||
fatImage([{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }]),
|
||||
],
|
||||
[
|
||||
"fat-le32.bin",
|
||||
fatImage(
|
||||
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
|
||||
false,
|
||||
true,
|
||||
),
|
||||
],
|
||||
[
|
||||
"fat-be64.bin",
|
||||
fatImage(
|
||||
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
|
||||
true,
|
||||
),
|
||||
],
|
||||
[
|
||||
"fat-le64.bin",
|
||||
fatImage(
|
||||
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
|
||||
true,
|
||||
true,
|
||||
),
|
||||
],
|
||||
] as const;
|
||||
|
||||
const jarPath = join(directory, "classes.jar");
|
||||
await writeFile(
|
||||
jarPath,
|
||||
await archive([
|
||||
["META-INF/MANIFEST.MF", Buffer.from("Manifest-Version: 1.0\n\n")],
|
||||
...javaEntries,
|
||||
]),
|
||||
);
|
||||
const jar = await inspectArchive(jarPath);
|
||||
expect(
|
||||
jar.occurrences
|
||||
.filter(({ logical_path }) => logical_path.endsWith(".class"))
|
||||
.map(({ logical_path, artifact_kind, artifact_format }) => ({
|
||||
logical_path,
|
||||
artifact_kind,
|
||||
artifact_format,
|
||||
})),
|
||||
).toEqual([
|
||||
{
|
||||
logical_path: "Hello.class",
|
||||
artifact_kind: "resource",
|
||||
artifact_format: "file",
|
||||
},
|
||||
{
|
||||
logical_path: "pkg/Big.class",
|
||||
artifact_kind: "unknown",
|
||||
artifact_format: "unknown",
|
||||
},
|
||||
]);
|
||||
const jarClassIds = new Set(
|
||||
jar.occurrences
|
||||
.filter(({ logical_path }) => logical_path.endsWith(".class"))
|
||||
.map(({ artifact_id }) => artifact_id),
|
||||
);
|
||||
expect(
|
||||
jar.nodes
|
||||
.filter(({ artifact_id }) => jarClassIds.has(artifact_id))
|
||||
.map(({ format }) => format)
|
||||
.sort(),
|
||||
).toEqual(["file", "unknown"]);
|
||||
|
||||
const mixedPath = join(directory, "mixed.zip");
|
||||
await writeFile(mixedPath, await archive([...javaEntries, ...fatControls]));
|
||||
const mixed = await inspectArchive(mixedPath);
|
||||
const formatsByPath = new Map(
|
||||
mixed.occurrences.map(
|
||||
({ logical_path, artifact_kind, artifact_format }) => [
|
||||
logical_path,
|
||||
{ artifact_kind, artifact_format },
|
||||
],
|
||||
),
|
||||
);
|
||||
for (const [name] of javaEntries)
|
||||
expect(formatsByPath.get(name)).toEqual(
|
||||
name === "Hello.class"
|
||||
? { artifact_kind: "resource", artifact_format: "file" }
|
||||
: { artifact_kind: "unknown", artifact_format: "unknown" },
|
||||
);
|
||||
for (const [name] of fatControls)
|
||||
expect(formatsByPath.get(name)).toEqual({
|
||||
artifact_kind: "executable",
|
||||
artifact_format: "mach-o-universal",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect } from "vitest";
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import {
|
||||
aotFixtureImage,
|
||||
engineFixtureImage,
|
||||
REFERENCE_HASH,
|
||||
} from "../../src/flutter/FlutterBuild.fixture.js";
|
||||
import {
|
||||
createFlutterApk,
|
||||
createDuplicateFlutterApk,
|
||||
} from "../fixtures/flutterApk.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"CLI and stdio MCP retain Flutter identity, selected ABI and duplicate-member refusals",
|
||||
async ({ cli }) => {
|
||||
const image = aotFixtureImage();
|
||||
Buffer.from("Login\0").copy(image, 0x2300);
|
||||
const engine = engineFixtureImage({
|
||||
notes: Buffer.from(
|
||||
"040000000800000003000000474e55000123456789abcdef",
|
||||
"hex",
|
||||
),
|
||||
prefix: Buffer.from(
|
||||
"040000000800000003000000474e55001111111111111111",
|
||||
"hex",
|
||||
),
|
||||
labels: ["Android (test) clang version 9.0.8"],
|
||||
});
|
||||
const path = await createFlutterApk("selected target.apk", [
|
||||
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
|
||||
{
|
||||
path: "lib/arm64-v8a/libflutter.so",
|
||||
bytes: engine,
|
||||
},
|
||||
{ path: "lib/x86_64/libapp.so", bytes: image },
|
||||
{
|
||||
path: "lib/x86_64/libflutter.so",
|
||||
bytes: engine,
|
||||
},
|
||||
]);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const [name, abi] of [
|
||||
["identify_flutter_build", undefined],
|
||||
["inspect_dart_aot", undefined],
|
||||
["inspect_dart_aot", "x86_64"],
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
name.replaceAll("_", "-"),
|
||||
path,
|
||||
"--json",
|
||||
...(abi === undefined ? [] : ["--abi", abi]),
|
||||
],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract(name).outputSchema.parse(result.json);
|
||||
const response = await call(name, {
|
||||
path,
|
||||
...(abi === undefined ? {} : { abi }),
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const mcp = parseEvidence(response.structuredContent);
|
||||
expect(mcp.normalized_result).toEqual(evidence.normalized_result);
|
||||
expect(mcp.subject).toEqual(evidence.subject);
|
||||
expect(mcp.subject).toMatchObject({
|
||||
local_path: path,
|
||||
format: "apk",
|
||||
digest: { sha256: evidence.normalized_result.target.sha256 },
|
||||
});
|
||||
expect(mcp.evidence_id).toBe(evidence.evidence_id);
|
||||
if (name === "inspect_dart_aot") {
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
abi: abi ?? "arm64-v8a",
|
||||
libapp: {
|
||||
coverage: "complete",
|
||||
snapshot_hash: REFERENCE_HASH,
|
||||
sha256: createHash("sha256").update(image).digest("hex"),
|
||||
},
|
||||
string_pool: {
|
||||
coverage: "complete",
|
||||
class_like_tokens: expect.arrayContaining(["Login"]),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const identified = toolContract(
|
||||
"identify_flutter_build",
|
||||
).outputSchema.parse(result.json).normalized_result;
|
||||
expect(identified.coverage).toBe("complete");
|
||||
for (const abi of identified.abis) {
|
||||
expect(abi.libflutter).toMatchObject({
|
||||
build_id: "0123456789abcdef",
|
||||
build_id_candidates: ["0123456789abcdef"],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const duplicate = await createDuplicateFlutterApk();
|
||||
for (const name of [
|
||||
"identify_flutter_build",
|
||||
"inspect_dart_aot",
|
||||
] as const) {
|
||||
const result = await cli.run({
|
||||
arguments: [name.replaceAll("_", "-"), duplicate, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
const mcp = parseMcpToolError(await call(name, { path: duplicate }));
|
||||
expect(mcp.error).toEqual(result.json);
|
||||
expect(mcp.error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: [{ message: expect.stringContaining(duplicate) }] },
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"CLI and MCP retain unsupported snapshot kinds as partial evidence",
|
||||
async ({ cli }) => {
|
||||
const image = aotFixtureImage();
|
||||
for (const offset of [0x1000, 0x2000])
|
||||
image.writeBigUInt64LE(4n, offset + 12);
|
||||
const path = await createFlutterApk("unsupported-kind.apk", [
|
||||
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
|
||||
]);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-dart-aot", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_dart_aot").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_dart_aot", { path });
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(parseEvidence(response.structuredContent).normalized_result).toEqual(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
coverage: "partial",
|
||||
libapp: { coverage: "partial", snapshot_hash: REFERENCE_HASH },
|
||||
string_pool: { coverage: "complete" },
|
||||
});
|
||||
expect(
|
||||
evidence.normalized_result.libapp.sections
|
||||
.filter((section) => section.name.endsWith("Data"))
|
||||
.map((section) => section.kind),
|
||||
).toEqual([4, 4]);
|
||||
},
|
||||
);
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
artifactInspectionResultSchema,
|
||||
} from "../../src/domain/artifactInspection.js";
|
||||
import {
|
||||
artifactInventoryResultSchema,
|
||||
artifactInventoryOutputSchema,
|
||||
artifactExtractionResultSchema,
|
||||
} from "../../src/domain/artifactGraph.js";
|
||||
import { analysisViewResultSchema } from "../../src/domain/analysisView/analysisView.js";
|
||||
@@ -36,9 +36,14 @@ const inventoryFrom = (input: unknown) => {
|
||||
const substep = inspection.substeps[0];
|
||||
if (substep === undefined) throw new Error("Missing inventory substep");
|
||||
parseEvidence(substep.evidence);
|
||||
return artifactInventoryResultSchema.parse(
|
||||
const inventory = artifactInventoryOutputSchema.parse(
|
||||
substep.evidence.normalized_result,
|
||||
);
|
||||
expect(inventory.coverage_status).toBe("complete");
|
||||
expect(inventory.limitations).toContainEqual(
|
||||
expect.stringContaining("CPU bank mappings"),
|
||||
);
|
||||
return inventory;
|
||||
};
|
||||
|
||||
cliTest(
|
||||
|
||||
@@ -30,7 +30,7 @@ type CaptureOutcome =
|
||||
| { readonly kind: "partial"; readonly partial: unknown };
|
||||
|
||||
const captureScenario = (
|
||||
mode: "cooperative" | "ignoring" | "descendant",
|
||||
mode: "cooperative" | "ignoring" | "delayed-ignoring" | "descendant",
|
||||
root: string,
|
||||
additions: CaptureScenario = {},
|
||||
finalExitCode?: number,
|
||||
@@ -453,11 +453,13 @@ captureTest(
|
||||
"rea-finalization-cli-cancel-",
|
||||
);
|
||||
const cliScenarioPath = join(cliRoot, "scenario.json");
|
||||
// Match the other finalization cases' observation window. The old 300 ms
|
||||
// deadline could signal the fixture before it installed its handlers.
|
||||
await writeFile(
|
||||
cliScenarioPath,
|
||||
JSON.stringify(
|
||||
captureScenario("ignoring", cliRoot, {
|
||||
timeout_ms: 300,
|
||||
captureScenario("delayed-ignoring", cliRoot, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
),
|
||||
@@ -527,18 +529,36 @@ captureTest(
|
||||
const mcpRoot = await createTestTempDirectory(
|
||||
"rea-finalization-mcp-cancel-",
|
||||
);
|
||||
const { client } = await connectLocalToolsMcp();
|
||||
const { client, call: callTool } = await connectLocalToolsMcp();
|
||||
const controller = new AbortController();
|
||||
const call = client.callTool(
|
||||
{
|
||||
name: "capture_process_scenario",
|
||||
arguments: captureScenario("ignoring", mcpRoot, {
|
||||
timeout_ms: 300,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
let reportStarted: (() => void) | undefined;
|
||||
const captureStarted = new Promise<void>((resolve) => {
|
||||
reportStarted = resolve;
|
||||
});
|
||||
const call = callTool(
|
||||
"capture_process_scenario",
|
||||
captureScenario("delayed-ignoring", mcpRoot, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
{ signal: controller.signal, onprogress: () => reportStarted?.() },
|
||||
);
|
||||
// Observe rejection immediately: a failed readiness wait must not leave a
|
||||
// pending request to reject unhandled when the fixture closes its client.
|
||||
// The original promise remains available for the cancellation assertion.
|
||||
const observedCall = call.catch(() => undefined);
|
||||
onTestFinished(async () => {
|
||||
controller.abort();
|
||||
await observedCall;
|
||||
});
|
||||
// Start the fixture's readiness wait after the server begins this capture;
|
||||
// SDK schema preparation before dispatch is not target startup time.
|
||||
await Promise.race([
|
||||
captureStarted,
|
||||
call.then(() => {
|
||||
throw new Error("MCP capture completed before reporting startup");
|
||||
}),
|
||||
]);
|
||||
const mcpFixturePid = await waitForFinalization(mcpRoot);
|
||||
const mcpStarted = Date.now();
|
||||
controller.abort(new Error("cancel finalization acceptance fixture"));
|
||||
@@ -548,7 +568,7 @@ captureTest(
|
||||
).rejects.toThrow("cancel finalization acceptance fixture");
|
||||
await waitForProcessExit(mcpFixturePid);
|
||||
await expect(
|
||||
client.listTools(),
|
||||
client.listTools(undefined, { cacheMode: "refresh" }),
|
||||
"the server accepts a follow-up request after cancelling the capture",
|
||||
).resolves.toMatchObject({ tools: expect.any(Array) });
|
||||
expect(
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const cases = [
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "[]",
|
||||
diagnostic: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "null",
|
||||
diagnostic: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: '{"mcpServers":null,"keep":1}',
|
||||
diagnostic: '"mcpServers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: '{"mcpServers":"x","keep":1}',
|
||||
diagnostic: '"mcpServers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "pi",
|
||||
path: ".pi/agent/mcp.json",
|
||||
text: '{"mcpServers":[]}',
|
||||
diagnostic: '"mcpServers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "codex",
|
||||
path: ".codex/config.toml",
|
||||
text: 'mcp_servers = "x"\n',
|
||||
diagnostic: '"mcp_servers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "opencode",
|
||||
path: ".config/opencode/opencode.json",
|
||||
text: '{"mcp":{"servers":null}}',
|
||||
diagnostic: '"mcp.servers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "hermes",
|
||||
path: ".hermes/config.yaml",
|
||||
text: "- item\n",
|
||||
diagnostic: "The configuration root must be an object",
|
||||
},
|
||||
{
|
||||
client: "hermes",
|
||||
path: ".hermes/config.yaml",
|
||||
text: "mcp_servers: null\nkeep: 1\n",
|
||||
diagnostic: '"mcp_servers" must be an object',
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
path: ".cursor/mcp.json",
|
||||
text: "not-json",
|
||||
diagnostic: "Configuration is not valid JSON",
|
||||
syntax: "JSON",
|
||||
},
|
||||
{
|
||||
client: "hermes",
|
||||
path: ".hermes/config.yaml",
|
||||
text: "mcp_servers: [\n",
|
||||
diagnostic: "Configuration is not valid YAML",
|
||||
syntax: "YAML",
|
||||
},
|
||||
{
|
||||
client: "dsh",
|
||||
path: ".dsh/cordis.patch.yml",
|
||||
text: "- insert: [\n",
|
||||
diagnostic: "Configuration is not valid YAML",
|
||||
syntax: "YAML",
|
||||
},
|
||||
] as const;
|
||||
|
||||
for (const scenario of cases)
|
||||
cliTest(
|
||||
`setup and uninstall explain ${scenario.client} configuration ${scenario.text}`,
|
||||
async ({ cli }) => {
|
||||
const home = await createTestTempDirectory(
|
||||
"rea-client-config-diagnostic-",
|
||||
);
|
||||
const config = join(home, scenario.path);
|
||||
await mkdir(dirname(config), { recursive: true });
|
||||
await writeFile(config, scenario.text);
|
||||
const environment = {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(home, ".config"),
|
||||
HERMES_HOME: join(home, ".hermes"),
|
||||
DSH_HOME: join(home, ".dsh"),
|
||||
};
|
||||
const setup = await cli.run({
|
||||
arguments: [
|
||||
"setup",
|
||||
"--client",
|
||||
scenario.client,
|
||||
"--skill=false",
|
||||
"--yes",
|
||||
"--json",
|
||||
],
|
||||
cwd: home,
|
||||
environment,
|
||||
});
|
||||
expect(setup.exitCode).toBe(1);
|
||||
expect(setup.json).toMatchObject({
|
||||
status: "needs_human",
|
||||
plannedActions: [],
|
||||
appliedActions: [],
|
||||
});
|
||||
if ("syntax" in scenario) {
|
||||
expect(setup.json).toMatchObject({ remediation: expect.any(String) });
|
||||
if (scenario.syntax === "JSON")
|
||||
expect(setup.stdout).toContain("Invalid JSON/JSONC");
|
||||
} else {
|
||||
expect(setup.json).toMatchObject({
|
||||
remediation: expect.stringContaining(scenario.diagnostic),
|
||||
});
|
||||
expect(setup.stdout).not.toContain("invalid_type");
|
||||
}
|
||||
const uninstall = await cli.run({
|
||||
arguments: ["uninstall", "--json"],
|
||||
cwd: home,
|
||||
environment,
|
||||
});
|
||||
expect(uninstall.exitCode).toBe(1);
|
||||
expect(uninstall.json).toMatchObject({
|
||||
status: "failed",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: scenario.client,
|
||||
status: "failed",
|
||||
detail: expect.stringContaining(scenario.diagnostic),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
if (!("syntax" in scenario))
|
||||
expect(uninstall.stdout).not.toContain("not valid JSON");
|
||||
expect(await readFile(config, "utf8")).toBe(scenario.text);
|
||||
expect(await readdir(dirname(config))).toEqual([
|
||||
scenario.path.split("/").at(-1),
|
||||
]);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,139 @@
|
||||
import { access, mkdir, readFile } from "node:fs/promises";
|
||||
import { userInfo } from "node:os";
|
||||
import { isAbsolute, join, relative, sep } from "node:path";
|
||||
import { parse } from "jsonc-parser";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"setup dry run resolves empty home values without writing to the cwd",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-empty-home-dry-run-");
|
||||
const workingDirectory = join(directory, "cwd");
|
||||
await mkdir(workingDirectory);
|
||||
const hostHome = userInfo().homedir;
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"setup",
|
||||
"--client",
|
||||
"cursor",
|
||||
"--skill=false",
|
||||
"--dry-run",
|
||||
"--json",
|
||||
],
|
||||
cwd: workingDirectory,
|
||||
environment: {
|
||||
HOME: "",
|
||||
USERPROFILE: "",
|
||||
HOMEDRIVE: "",
|
||||
HOMEPATH: "",
|
||||
XDG_CONFIG_HOME: "",
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.exitCode, result.stdout).toBe(0);
|
||||
const output = result.json as {
|
||||
plannedActions?: Array<{ kind?: unknown; target?: unknown }>;
|
||||
status?: unknown;
|
||||
};
|
||||
expect(["planned", "ready"]).toContain(output.status);
|
||||
const configTargets = (output.plannedActions ?? [])
|
||||
.filter((action) => action.kind === "configure_client")
|
||||
.map((action) => action.target);
|
||||
for (const target of configTargets) {
|
||||
expect(typeof target).toBe("string");
|
||||
if (typeof target !== "string") continue;
|
||||
expect(isAbsolute(target)).toBe(true);
|
||||
const relativeTarget = relative(hostHome, target);
|
||||
expect(
|
||||
relativeTarget === "" ||
|
||||
(!relativeTarget.startsWith(`..${sep}`) && relativeTarget !== ".."),
|
||||
).toBe(true);
|
||||
}
|
||||
expect(configTargets).not.toContain(
|
||||
join(workingDirectory, ".cursor", "mcp.json"),
|
||||
);
|
||||
await expect(
|
||||
access(join(workingDirectory, ".cursor", "mcp.json")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.skipIf(process.platform === "win32")(
|
||||
"setup, doctor, and uninstall use the nonempty fallback home when HOME is empty",
|
||||
async ({ cli }) => {
|
||||
const directory = await createTestTempDirectory(
|
||||
"rea-empty-home-lifecycle-",
|
||||
);
|
||||
const home = join(directory, "fallback-home");
|
||||
const workingDirectory = join(directory, "cwd");
|
||||
await mkdir(home);
|
||||
await mkdir(workingDirectory);
|
||||
const environment = {
|
||||
HOME: "",
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(home, ".config"),
|
||||
};
|
||||
const run = (arguments_: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: arguments_,
|
||||
cwd: workingDirectory,
|
||||
environment,
|
||||
});
|
||||
|
||||
const setup = await run(["setup", "--client", "cursor", "--yes", "--json"]);
|
||||
expect(setup.exitCode, setup.stderr).toBe(0);
|
||||
expect(setup.json).toMatchObject({ status: "ready" });
|
||||
await access(join(home, ".cursor", "mcp.json"));
|
||||
await access(
|
||||
join(home, ".agents", "skills", "reverse-engineer-anything", "SKILL.md"),
|
||||
);
|
||||
await expect(
|
||||
access(join(workingDirectory, ".cursor", "mcp.json")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
await expect(
|
||||
access(join(workingDirectory, ".agents", "skills")),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
const doctor = await run([
|
||||
"doctor",
|
||||
"--client",
|
||||
"cursor",
|
||||
"--skill",
|
||||
"--json",
|
||||
]);
|
||||
expect(doctor.exitCode, doctor.stdout).toBe(0);
|
||||
expect(doctor.json).toMatchObject({ healthy: true });
|
||||
|
||||
const uninstall = await run(["uninstall", "--json"]);
|
||||
expect(uninstall.exitCode, uninstall.stderr).toBe(0);
|
||||
expect(uninstall.json).toMatchObject({ status: "complete" });
|
||||
const remainingConfig = parse(
|
||||
await readFile(join(home, ".cursor", "mcp.json"), "utf8"),
|
||||
);
|
||||
expect(remainingConfig).not.toHaveProperty("mcpServers.rea");
|
||||
await expect(
|
||||
access(
|
||||
join(
|
||||
home,
|
||||
".agents",
|
||||
"skills",
|
||||
"reverse-engineer-anything",
|
||||
"SKILL.md",
|
||||
),
|
||||
),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(
|
||||
access(join(workingDirectory, ".cursor", "mcp.json")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,597 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { expect, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
expandProviderCapabilities,
|
||||
expandToolAvailability,
|
||||
providerCapabilitySet,
|
||||
toolAvailabilityInventory,
|
||||
} from "../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
|
||||
import { SQLITE_NATIVE_LIMITS_AVAILABLE } from "../fixtures/sqlite/database.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
const digest = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"bounds default context and projects exact columns without evaluating unrelated cells",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-selective-");
|
||||
const path = join(root, "selected.db");
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec(`
|
||||
CREATE TABLE selected(id INTEGER, "" TEXT, payload BLOB GENERATED ALWAYS AS (zeroblob(72*1024*1024)) VIRTUAL);
|
||||
CREATE TABLE unrelated(value TEXT);
|
||||
CREATE VIEW unrelated_view AS SELECT value FROM unrelated;
|
||||
CREATE INDEX selected_id ON selected(id);
|
||||
CREATE TRIGGER selected_trigger AFTER INSERT ON selected BEGIN SELECT 1; END;
|
||||
WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM numbers WHERE n<21)
|
||||
INSERT INTO selected(id, "") SELECT n, 'retained' FROM numbers;
|
||||
`);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const before = await readFile(path);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const inventory = await call("inspect_sqlite_database", { path });
|
||||
expect(inventory.isError).not.toBe(true);
|
||||
const schema = z
|
||||
.object({
|
||||
normalized_result: z.object({
|
||||
schema: z.object({
|
||||
scope: z.literal("inventory"),
|
||||
tables: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
columns: z.array(z.unknown()),
|
||||
columns_completeness: z.literal("not_requested"),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.parse(inventory.structuredContent).normalized_result.schema;
|
||||
expect(schema.tables.map((table) => table.name)).toEqual([
|
||||
"selected",
|
||||
"unrelated",
|
||||
]);
|
||||
expect(schema.tables.every((table) => table.columns.length === 0)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(JSON.stringify(inventory.structuredContent)).not.toContain(
|
||||
"zeroblob",
|
||||
);
|
||||
const selected = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: "selected",
|
||||
columns: ["", "id", "id"],
|
||||
});
|
||||
expect(selected.isError).not.toBe(true);
|
||||
expect(selected.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
schema: {
|
||||
scope: "selected_table",
|
||||
tables: [{ name: "selected" }],
|
||||
views: [],
|
||||
indexes: [{ name: "selected_id" }],
|
||||
triggers: [{ name: "selected_trigger" }],
|
||||
},
|
||||
rows: {
|
||||
columns: ["", "id", "id"],
|
||||
row_limit: 20,
|
||||
returned_rows: 20,
|
||||
truncated: true,
|
||||
values: expect.arrayContaining([
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
value: "retained",
|
||||
bytes_hex: "72657461696e6564",
|
||||
encoding: "UTF-8",
|
||||
},
|
||||
{ type: "integer", value: "1" },
|
||||
{ type: "integer", value: "1" },
|
||||
],
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
const cliResult = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
path,
|
||||
"--table",
|
||||
"selected",
|
||||
"--column",
|
||||
"id",
|
||||
"--column",
|
||||
"",
|
||||
"--row-limit",
|
||||
"1",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(cliResult.exitCode, cliResult.stdout + cliResult.stderr).toBe(0);
|
||||
expect(cliResult.json).toMatchObject({
|
||||
normalized_result: { rows: { columns: ["id", ""], returned_rows: 1 } },
|
||||
});
|
||||
for (const input of [
|
||||
{ path, columns: ["id"] },
|
||||
{ path, schema_scope: "selected_table" },
|
||||
{ path, table: "selected", columns: [] },
|
||||
{ path, table: "selected", columns: ["ID"] },
|
||||
])
|
||||
expect((await call("inspect_sqlite_database", input)).isError).toBe(true);
|
||||
expect(await readFile(path)).toEqual(before);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"discovers SQLite runtime availability before inspecting a database through CLI and MCP",
|
||||
async ({ cli }) => {
|
||||
const result = await cli.run({
|
||||
arguments: ["capabilities", "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
const status = z
|
||||
.object({
|
||||
open: z.literal(false),
|
||||
capabilities: z.array(providerCapabilitySet),
|
||||
})
|
||||
.parse(result.json);
|
||||
expect(expandProviderCapabilities(status.capabilities)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "inspect_sqlite_database",
|
||||
available: SQLITE_NATIVE_LIMITS_AVAILABLE,
|
||||
reason: SQLITE_NATIVE_LIMITS_AVAILABLE
|
||||
? null
|
||||
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
|
||||
availability_code: SQLITE_NATIVE_LIMITS_AVAILABLE
|
||||
? null
|
||||
: "unsupported_version",
|
||||
limitations: [expect.stringContaining("DatabaseSync.limits")],
|
||||
effects: {
|
||||
mutates_artifact: false,
|
||||
launches_process: true,
|
||||
may_show_ui: false,
|
||||
may_access_network: false,
|
||||
may_write_filesystem: true,
|
||||
changes_permissions: false,
|
||||
requires_root: false,
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("binary_session", {});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const sessionStatus = z
|
||||
.object({
|
||||
result: z.object({ tool_availability: toolAvailabilityInventory }),
|
||||
})
|
||||
.parse(response.structuredContent);
|
||||
expect(
|
||||
expandToolAvailability(sessionStatus.result.tool_availability),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "inspect_sqlite_database",
|
||||
available: SQLITE_NATIVE_LIMITS_AVAILABLE,
|
||||
remediation: SQLITE_NATIVE_LIMITS_AVAILABLE
|
||||
? null
|
||||
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.skipIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"reports the required native SQLite limits capability through CLI and MCP",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-unavailable-");
|
||||
const path = join(root, "selected.db");
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec("CREATE TABLE items(value INTEGER)");
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-sqlite-database", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("DatabaseSync.limits"),
|
||||
});
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_sqlite_database", { path });
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response).error).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
message: expect.stringContaining("DatabaseSync.limits"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"accepts small samples above 1000 rows within the real resource budgets",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-row-budget-");
|
||||
const path = join(root, "rows.db");
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec(`CREATE TABLE items(value INTEGER);
|
||||
WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers WHERE value < 1002)
|
||||
INSERT INTO items SELECT value FROM numbers;`);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const limit of [1001, Number.MAX_SAFE_INTEGER]) {
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
path,
|
||||
"--table",
|
||||
"items",
|
||||
"--row-limit",
|
||||
String(limit),
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result: {
|
||||
rows: {
|
||||
row_limit: limit,
|
||||
returned_rows: Math.min(limit, 1002),
|
||||
truncated: limit < 1002,
|
||||
},
|
||||
},
|
||||
});
|
||||
const response = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: "items",
|
||||
row_limit: limit,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(response.structuredContent).toEqual(result.json);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const sourceState = async (path: string) => {
|
||||
const bytes = await readFile(path);
|
||||
const metadata = await stat(path, { bigint: true });
|
||||
return {
|
||||
bytes,
|
||||
device: metadata.dev,
|
||||
inode: metadata.ino,
|
||||
size: metadata.size,
|
||||
modified: metadata.mtimeNs,
|
||||
changed: metadata.ctimeNs,
|
||||
};
|
||||
};
|
||||
|
||||
const createLosslessSnapshot = (path: string, journalMode: string): void => {
|
||||
const database = new DatabaseSync(path);
|
||||
try {
|
||||
database.exec(`PRAGMA journal_mode=${journalMode}`);
|
||||
database.exec(`
|
||||
CREATE TABLE "odd "" table" (
|
||||
id INTEGER PRIMARY KEY,
|
||||
payload BLOB,
|
||||
amount REAL,
|
||||
missing TEXT,
|
||||
text_value TEXT,
|
||||
negative_zero,
|
||||
generated TEXT GENERATED ALWAYS AS (hex(payload)) VIRTUAL
|
||||
);
|
||||
CREATE UNIQUE INDEX "quoted "" index" ON "odd "" table"(payload, id);
|
||||
CREATE VIEW readable AS SELECT id FROM "odd "" table";
|
||||
CREATE TRIGGER observed AFTER INSERT ON "odd "" table" BEGIN SELECT 1; END;
|
||||
CREATE TABLE keyed(k TEXT PRIMARY KEY) WITHOUT ROWID, STRICT;
|
||||
`);
|
||||
const insert = database.prepare(
|
||||
'INSERT INTO "odd "" table"(id,payload,amount,missing,text_value,negative_zero) VALUES(?,?,?,NULL,CAST(X\'80ff\' AS TEXT),?)',
|
||||
);
|
||||
insert.setReadBigInts(true);
|
||||
expect(
|
||||
insert.run(
|
||||
9007199254740993n,
|
||||
Buffer.from("deadbeef", "hex"),
|
||||
Infinity,
|
||||
-0,
|
||||
).lastInsertRowid,
|
||||
).toBe(9007199254740993n);
|
||||
insert.run(9007199254740994n, Buffer.from("deadbeef", "hex"), Infinity, -0);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
};
|
||||
|
||||
cliTest
|
||||
.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)
|
||||
.for(["DELETE", "PERSIST", "TRUNCATE"])(
|
||||
"inspects a real %s SQLite schema and lossless selected records identically through CLI and MCP",
|
||||
async (journalMode, { cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-public-");
|
||||
const path = join(root, "selected.db");
|
||||
createLosslessSnapshot(path, journalMode);
|
||||
const original = await readFile(path);
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
"selected.db",
|
||||
"--schema-scope",
|
||||
"database",
|
||||
"--table",
|
||||
'odd " table',
|
||||
"--row-limit",
|
||||
"1",
|
||||
"--json",
|
||||
],
|
||||
cwd: root,
|
||||
environment: {
|
||||
REA_LOG_LEVEL: "silent",
|
||||
REA_ANALYSIS_PROVIDER: "ghidra",
|
||||
REA_GHIDRA_HOME: "/unconfigured/ghidra",
|
||||
},
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
operation: "inspect_sqlite_database",
|
||||
confidence: "observed",
|
||||
subject: { local_path: path, digest: { sha256: digest(original) } },
|
||||
normalized_result: {
|
||||
artifact: { path, sha256: digest(original), bytes: original.length },
|
||||
wal: null,
|
||||
schema: {
|
||||
completeness: "complete",
|
||||
tables: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: 'odd " table',
|
||||
columns: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "id",
|
||||
primary_key_position: 1,
|
||||
}),
|
||||
expect.objectContaining({ name: "generated", hidden: 2 }),
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "keyed",
|
||||
without_rowid: true,
|
||||
strict: true,
|
||||
}),
|
||||
]),
|
||||
indexes: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: 'quoted " index',
|
||||
table: 'odd " table',
|
||||
}),
|
||||
]),
|
||||
views: [
|
||||
{ name: "readable", sql: expect.stringContaining("SELECT id") },
|
||||
],
|
||||
triggers: [
|
||||
{
|
||||
name: "observed",
|
||||
table: 'odd " table',
|
||||
sql: expect.stringContaining("AFTER INSERT"),
|
||||
},
|
||||
],
|
||||
},
|
||||
rows: {
|
||||
table: 'odd " table',
|
||||
columns: [
|
||||
"id",
|
||||
"payload",
|
||||
"amount",
|
||||
"missing",
|
||||
"text_value",
|
||||
"negative_zero",
|
||||
"generated",
|
||||
],
|
||||
returned_rows: 1,
|
||||
row_limit: 1,
|
||||
truncated: true,
|
||||
values: [
|
||||
[
|
||||
{
|
||||
type: "integer",
|
||||
value: expect.stringMatching(/^900719925474099[34]$/),
|
||||
},
|
||||
{ type: "blob", hex: "deadbeef" },
|
||||
{ type: "real", value: "Infinity" },
|
||||
{ type: "null" },
|
||||
{ type: "text", value: "\ufffd\ufffd", bytes_hex: "80ff" },
|
||||
{ type: "real", value: "-0" },
|
||||
{
|
||||
type: "text",
|
||||
value: "DEADBEEF",
|
||||
bytes_hex: "4445414442454546",
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: 'odd " table',
|
||||
schema_scope: "database",
|
||||
row_limit: 1,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(response.structuredContent).toEqual(result.json);
|
||||
expect(await readFile(path)).toEqual(original);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"includes uncheckpointed committed WAL data without modifying the source database or sidecars",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-wal-public-");
|
||||
const path = join(root, "wal.db");
|
||||
const database = new DatabaseSync(path);
|
||||
onTestFinished(() => database.close());
|
||||
database.exec(
|
||||
"PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; CREATE TABLE committed(value TEXT); INSERT INTO committed VALUES('only in WAL');",
|
||||
);
|
||||
const files = [path, `${path}-wal`, `${path}-shm`];
|
||||
const before = await Promise.all(files.map(sourceState));
|
||||
const db = before[0];
|
||||
const wal = before[1];
|
||||
expect(db).toBeDefined();
|
||||
expect(wal).toBeDefined();
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
path,
|
||||
"--table",
|
||||
"committed",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result: {
|
||||
artifact: { sha256: db === undefined ? "missing" : digest(db.bytes) },
|
||||
wal: {
|
||||
path: `${path}-wal`,
|
||||
sha256: wal === undefined ? "missing" : digest(wal.bytes),
|
||||
},
|
||||
rows: {
|
||||
values: [
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
value: "only in WAL",
|
||||
bytes_hex: Buffer.from("only in WAL").toString("hex"),
|
||||
},
|
||||
],
|
||||
],
|
||||
returned_rows: 1,
|
||||
truncated: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("inspect_sqlite_database", {
|
||||
path,
|
||||
table: "committed",
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
expect(response.structuredContent).toEqual(result.json);
|
||||
const after = await Promise.all(files.map(sourceState));
|
||||
expect(after).toEqual(before);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
|
||||
"returns actionable public errors for corrupt input, unknown or ambiguous tables and invalid record choices",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-sqlite-errors-public-");
|
||||
const path = join(root, "invalid.db");
|
||||
await writeFile(path, "not a SQLite database");
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const corrupt = await cli.run({
|
||||
arguments: ["inspect-sqlite-database", path, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(corrupt.exitCode).toBe(1);
|
||||
expect(corrupt.json).toMatchObject({ code: "invalid_request" });
|
||||
expect((await call("inspect_sqlite_database", { path })).isError).toBe(
|
||||
true,
|
||||
);
|
||||
const valid = join(root, "valid.db");
|
||||
const database = new DatabaseSync(valid);
|
||||
try {
|
||||
database.exec(
|
||||
"CREATE TABLE present(value TEXT); CREATE VIRTUAL TABLE search USING fts5(body);",
|
||||
);
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
const bytes = await readFile(valid);
|
||||
const declaration = bytes.indexOf(Buffer.from("USING fts5"));
|
||||
if (declaration < 0) throw new Error("Virtual declaration missing");
|
||||
bytes.write("zzzz", declaration + Buffer.byteLength("USING "), "utf8");
|
||||
await writeFile(valid, bytes);
|
||||
const schema = await call("inspect_sqlite_database", { path: valid });
|
||||
expect(schema.isError).not.toBe(true);
|
||||
expect(schema.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
schema: {
|
||||
tables: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "search_data", kind: "unknown" }),
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
const ambiguous = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
valid,
|
||||
"--table",
|
||||
"search_data",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(ambiguous.exitCode).toBe(1);
|
||||
expect(ambiguous.stdout).toContain("shadow table");
|
||||
expect(
|
||||
(
|
||||
await call("inspect_sqlite_database", {
|
||||
path: valid,
|
||||
table: "search_data",
|
||||
})
|
||||
).isError,
|
||||
).toBe(true);
|
||||
const missing = await cli.run({
|
||||
arguments: [
|
||||
"inspect-sqlite-database",
|
||||
valid,
|
||||
"--table",
|
||||
"absent",
|
||||
"--json",
|
||||
],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(missing.exitCode).toBe(1);
|
||||
expect(missing.stdout).toContain("absent");
|
||||
expect(
|
||||
(await call("inspect_sqlite_database", { path: valid, table: "absent" }))
|
||||
.isError,
|
||||
).toBe(true);
|
||||
for (const input of [
|
||||
{ path: valid, row_limit: 1 },
|
||||
{ path: valid, table: "present", row_limit: 0 },
|
||||
{ path: valid, query: "DELETE FROM present" },
|
||||
]) {
|
||||
expect(
|
||||
(await call("inspect_sqlite_database", input)).isError,
|
||||
JSON.stringify(input),
|
||||
).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -19,6 +19,25 @@ const electron = {
|
||||
executable_path: "/tmp/Electron",
|
||||
application_path: "/tmp/main.js",
|
||||
};
|
||||
|
||||
const runCliExpectingInputError = async (
|
||||
scenarioPath: string,
|
||||
): Promise<unknown> => {
|
||||
const failure = await execute(process.execPath, [
|
||||
cli,
|
||||
"capture-process",
|
||||
scenarioPath,
|
||||
"--json",
|
||||
]).then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
expect(failure).toMatchObject({ code: 1 });
|
||||
if (!(failure instanceof Error) || !("stdout" in failure))
|
||||
throw new Error("Expected the CLI to report an input error on stdout");
|
||||
return JSON.parse(String(failure.stdout)) as unknown;
|
||||
};
|
||||
|
||||
const pathRequests: readonly [string, Record<string, unknown>][] = [
|
||||
["open_binary", { path: nul }],
|
||||
["open_binary", { path: process.execPath, snapshot_path: nul }],
|
||||
@@ -235,25 +254,80 @@ captureTest(
|
||||
});
|
||||
expect(parseMcpToolError(failed)).toMatchObject({
|
||||
error: {
|
||||
code: "process_capture_failed",
|
||||
message: expect.stringContaining(missing),
|
||||
details: { execution_failure: expect.stringContaining(missing) },
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["executable"],
|
||||
message: expect.stringContaining(`${missing} (ENOENT)`),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
await writeFile(
|
||||
join(root, "scenario.json"),
|
||||
JSON.stringify({ executable: missing }),
|
||||
);
|
||||
await expect(
|
||||
execute(process.execPath, [
|
||||
cli,
|
||||
"capture-process",
|
||||
join(root, "scenario.json"),
|
||||
"--json",
|
||||
]),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining(missing),
|
||||
const executableCliFailure = await runCliExpectingInputError(
|
||||
join(root, "scenario.json"),
|
||||
);
|
||||
expect(executableCliFailure).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["executable"],
|
||||
message: expect.stringContaining(`${missing} (ENOENT)`),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const missingWorkingDirectory = join(root, "missing-working-directory");
|
||||
const cwdFailure = await call("capture_process_scenario", {
|
||||
executable: process.execPath,
|
||||
working_directory: missingWorkingDirectory,
|
||||
});
|
||||
expect(parseMcpToolError(cwdFailure)).toMatchObject({
|
||||
error: {
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["working_directory"],
|
||||
message: expect.stringContaining(
|
||||
`${missingWorkingDirectory} (ENOENT)`,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const cwdScenario = join(root, "missing-working-directory.json");
|
||||
await writeFile(
|
||||
cwdScenario,
|
||||
JSON.stringify({
|
||||
executable: process.execPath,
|
||||
working_directory: missingWorkingDirectory,
|
||||
}),
|
||||
);
|
||||
expect(await runCliExpectingInputError(cwdScenario)).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "capture_process_scenario",
|
||||
issues: [
|
||||
{
|
||||
path: ["working_directory"],
|
||||
message: expect.stringContaining(
|
||||
`${missingWorkingDirectory} (ENOENT)`,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
60_000,
|
||||
|
||||
Reference in New Issue
Block a user