diff --git a/src/domain/javascript/javascriptGraphqlOperations.ts b/src/domain/javascript/javascriptGraphqlOperations.ts index f95d0b0768..8bdf8798df 100644 --- a/src/domain/javascript/javascriptGraphqlOperations.ts +++ b/src/domain/javascript/javascriptGraphqlOperations.ts @@ -24,50 +24,40 @@ import type { * earlier strings still belong to this object and must not become standalone * operation findings during the string scan. */ -const graphqlSourceBodyLiterals = ( +const graphqlSourceOwnership = ( node: t.ObjectExpression, -): readonly t.StringLiteral[] | undefined => { - const hasLocationOffset = node.properties.some( - (property) => - t.isObjectProperty(property) && - semanticStaticPropertyKey(property.key, property.computed) === - "locationOffset", - ); - if (!hasLocationOffset) return undefined; - - const bodyStrings = (object: t.ObjectExpression) => - object.properties.flatMap((property) => - t.isObjectProperty(property) && - semanticStaticPropertyKey(property.key, property.computed) === "body" && - t.isStringLiteral(property.value) - ? [property.value] - : [], - ); - const bodies = bodyStrings(node); - - // Inline object spreads can own additional body values which the surrounding - // Source object may select. Include only body-key string literals from those - // spread values; ordinary strings elsewhere in the object remain scannable. - const visited = new WeakSet(); - visited.add(node); - const pending = node.properties.flatMap((property) => { - if (!t.isSpreadElement(property)) return []; - const spread = unwrapJavaScriptExpression(property.argument).node; - return t.isObjectExpression(spread) ? [spread] : []; - }); +): + | { + readonly bodies: readonly t.StringLiteral[]; + readonly objects: ReadonlySet; + } + | undefined => { + const bodies: t.StringLiteral[] = []; + let hasLocationOffset = false; + // Own marker presence and body literals through the same inline-spread walk. + // Unknown spreads cannot remove a known own marker. Ordinary nested objects + // and non-body strings remain independently scannable. + const visited = new Set(); + const pending = [node]; while (pending.length > 0) { const current = pending.pop(); if (current === undefined || visited.has(current)) continue; visited.add(current); - bodies.push(...bodyStrings(current)); for (const property of current.properties) { - if (t.isSpreadElement(property)) { + if (t.isObjectProperty(property)) { + const key = semanticStaticPropertyKey(property.key, property.computed); + if (key === "locationOffset") hasLocationOffset = true; + else if (key === "body" && t.isStringLiteral(property.value)) + bodies.push(property.value); + } else if (t.isSpreadElement(property)) { const spread = unwrapJavaScriptExpression(property.argument).node; if (t.isObjectExpression(spread)) pending.push(spread); } } } - return bodies.length === 0 ? undefined : bodies; + return hasLocationOffset && bodies.length > 0 + ? { bodies, objects: visited } + : undefined; }; const GRAPHQL_OPERATION_TYPES: ReadonlySet = new Set([ @@ -442,6 +432,7 @@ export const createJavaScriptGraphqlScan = ( index: JavaScriptBindingIndex, ): JavaScriptRpcScan => { const bodies = new WeakSet(); + const ownedSources = new WeakSet(); const copied = new WeakMap>(); const copies: GraphqlSourceCopy[] = []; const sources: { @@ -474,9 +465,14 @@ export const createJavaScriptGraphqlScan = ( copies.push({ ...source, operations }); } } - const owned = graphqlSourceBodyLiterals(node); + const owned = ownedSources.has(node) + ? undefined + : graphqlSourceOwnership(node); if (owned !== undefined) { - for (const body of owned) bodies.add(body); + for (const body of owned.bodies) bodies.add(body); + // The outer Source owns its inline spread objects too: they cannot + // later emit overwritten or unknown bodies as independent Sources. + for (const object of owned.objects) ownedSources.add(object); const body = semanticFinalObjectProperty(node, "body"); const recovered = t.isStringLiteral(body) ? graphqlOperationFromText(body.value) diff --git a/src/domain/javascript/javascriptGraphqlSourceOwnership.test.ts b/src/domain/javascript/javascriptGraphqlSourceOwnership.test.ts new file mode 100644 index 0000000000..a98174ae34 --- /dev/null +++ b/src/domain/javascript/javascriptGraphqlSourceOwnership.test.ts @@ -0,0 +1,60 @@ +import { expect, it } from "vitest"; +import { analyzeJavaScriptStaticSource } from "../../../tests/fixtures/javascriptStaticAnalysis.js"; + +it.each([ + [ + "direct marker", + 'locationOffset:{line:1,column:1},body:"query Old { x }",body:"query Current { x }"', + ["Current"], + ], + [ + "marker in an inline spread", + '...{locationOffset:{line:1,column:1}},body:"query Old { x }",body:"query Current { x }"', + ["Current"], + ], + [ + "marker in nested inline spreads", + '...{...{locationOffset:{line:1,column:1}}},body:"query Old { x }",body:"query Current { x }"', + ["Current"], + ], + [ + "overwritten Source in an inline spread", + '...{locationOffset:{line:1,column:1},body:"query Old { x }"},body:"query Current { x }"', + ["Current"], + ], + [ + "unknown final body after an inline Source", + '...{locationOffset:{line:1,column:1},body:"query Old { x }"},...runtimeOptions', + [], + ], + [ + "nested inline Sources with an unrelated nested Source", + '...{...{locationOffset:{line:1,column:1},body:"query Old { x }"},body:"query Middle { x }"},body:"query Current { x }",metadata:{locationOffset:{line:1,column:1},body:"query Independent { x }"}', + ["Current", "Independent"], + ], + [ + "unknown later body with an owned marker", + 'locationOffset:{line:1,column:1},body:"query Old { x }",...runtimeOptions', + [], + ], + [ + "ordinary nested metadata", + 'metadata:{locationOffset:{line:1,column:1}},body:"query Plain { x }"', + ["Plain"], + ], + [ + "unknown computed property after the body", + 'locationOffset:{line:1,column:1},body:"query Old { x }",[key]:runtimeValue', + [], + ], +] as const)( + "preserves Source body ownership for %s", + (_name, fields, expected) => { + const result = analyzeJavaScriptStaticSource(`const source={${fields}};`); + expect( + result.endpoints + .filter(({ mechanism }) => mechanism === "graphql:query") + .map(({ value }) => value), + ).toEqual(expected); + }, +); diff --git a/tests/acceptance/applications/javascriptGraphqlWideSourceCli.test.ts b/tests/acceptance/applications/javascriptGraphqlWideSourceCli.test.ts new file mode 100644 index 0000000000..91d920fc86 --- /dev/null +++ b/tests/acceptance/applications/javascriptGraphqlWideSourceCli.test.ts @@ -0,0 +1,58 @@ +import { createHash } from "node:crypto"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect } from "vitest"; + +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; +import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js"; + +cliTest.for(["CLI", "stdio MCP"] as const)( + "retains wide GraphQL Source ownership without dropping its file through %s", + async (surface, { cli }) => { + const root = await createTestTempDirectory("rea-graphql-wide-source-"); + const path = join(root, "main.mjs"); + // This exceeds the worker's 2 MiB V8 argument stack while staying within + // admitted source/AST limits. Duplicate properties are valid inert JS. + const source = `const source = { + locationOffset: { line: 1, column: 1 }, + ...{locationOffset: { line: 1, column: 1 }, + ${'body:"query Overwritten { x }",'.repeat(270_000)}}, + body: "query Active { viewer { id } }", + note: "query Unrelated { viewer { id } }", + };`; + await writeFile(path, source); + + const result = await analyzeJavaScriptDirectory(surface, cli, root); + expect(result.statistics).toMatchObject({ + parsed_javascript_files: 1, + skipped_javascript_files: 0, + parse_failures: 0, + }); + const operations = result.graph.nodes + .filter((node) => node.kind === "endpoint") + .flatMap((node) => node.observations) + .filter(({ properties }) => properties.mechanism === "graphql:query"); + // Overwritten body copies stay owned by the Source; its unrelated string + // remains independently scannable, and the final body supplies the query. + expect(operations.map(({ properties }) => properties.value).sort()).toEqual( + ["Active", "Unrelated"], + ); + expect(result.graph.coverage.status).toBe("complete"); + for (const operation of operations) + expect(operation.evidence).toMatchObject({ + authority: "ast-static-analysis", + state: "observed", + artifact: { available: true }, + location: { + available: true, + value: { kind: "source-range", source: "main.mjs" }, + }, + }); + expect( + createHash("sha256") + .update(await readFile(path)) + .digest("hex"), + ).toBe(createHash("sha256").update(source).digest("hex")); + }, +);