From 42c0f0b07301d1cf4a45eff72affbfc51f656738 Mon Sep 17 00:00:00 2001 From: cgombauld Date: Fri, 4 Jul 2025 08:47:11 +0200 Subject: [PATCH] refactor(probes): isFetch detect fetch re-assigment --- .changeset/public-coats-give.md | 5 +++++ workspaces/js-x-ray/src/probes/isFetch.ts | 16 ++++++++++++++-- workspaces/js-x-ray/test/probes/isFetch.spec.ts | 10 ++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 .changeset/public-coats-give.md diff --git a/.changeset/public-coats-give.md b/.changeset/public-coats-give.md new file mode 100644 index 0000000..ad5288b --- /dev/null +++ b/.changeset/public-coats-give.md @@ -0,0 +1,5 @@ +--- +"@nodesecure/js-x-ray": minor +--- + +refactor(probes): isFetch detect fetch re-assigment diff --git a/workspaces/js-x-ray/src/probes/isFetch.ts b/workspaces/js-x-ray/src/probes/isFetch.ts index 2025013..931880b 100644 --- a/workspaces/js-x-ray/src/probes/isFetch.ts +++ b/workspaces/js-x-ray/src/probes/isFetch.ts @@ -6,11 +6,22 @@ import type { ESTree } from "meriyah"; import { SourceFile } from "../SourceFile.js"; function validateNode( - node: ESTree.Node + node: ESTree.Node, + { tracer }: SourceFile ): [boolean, any?] { const id = getCallExpressionIdentifier(node); - return [id === "fetch"]; + if (id === null) { + return [false]; + } + + const data = tracer.getDataFromIdentifier(id); + + return [data !== null && data.identifierOrMemberExpr === "fetch"]; +} + +function initialize(sourceFile: SourceFile) { + sourceFile.tracer.trace("fetch", { followConsecutiveAssignment: true }); } function main( @@ -23,6 +34,7 @@ function main( export default { name: "isFetch", validateNode, + initialize, main, breakOnMatch: false }; diff --git a/workspaces/js-x-ray/test/probes/isFetch.spec.ts b/workspaces/js-x-ray/test/probes/isFetch.spec.ts index 2215a3a..38aee2e 100644 --- a/workspaces/js-x-ray/test/probes/isFetch.spec.ts +++ b/workspaces/js-x-ray/test/probes/isFetch.spec.ts @@ -12,3 +12,13 @@ test("it should detect native fetch", () => { assert.ok(flags.has("fetch")); assert.strictEqual(flags.size, 1); }); + +test("it should detect a re-assigned native fetch", () => { + const code = `const fetchBis = fetch + await fetchBis(url); + `; + const { flags } = new AstAnalyser().analyse(code); + + assert.ok(flags.has("fetch")); + assert.strictEqual(flags.size, 1); +});