mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-23 22:06:04 +00:00
Merge upstream/main (01af8338) into r-language-support-rebased
This commit is contained in:
commit
d50f4e7bae
89 changed files with 15899 additions and 764 deletions
|
|
@ -220,6 +220,11 @@ an unproven argument, or a reassigned parameter establishes nothing, and a helpe
|
|||
with no recorded call site is read as written, so an unknown mount path still
|
||||
suppresses its router's standalone paths.
|
||||
|
||||
Fetch-wrapper facts use the same lexical identities. The shared resolver in
|
||||
`route-extractors/fetch-wrapper-index.ts` names no language, but it applies
|
||||
ECMAScript `ResolveExport` rules to the re-export facts it receives: only
|
||||
providers whose modules link that way implement the re-export hook.
|
||||
|
||||
A standalone router retains its local paths. A known dynamic mount suppresses
|
||||
that fallback, while independently proven static mounts remain available. Cycles
|
||||
terminate, and exceeding the expansion budget omits the affected mount component
|
||||
|
|
|
|||
|
|
@ -18,13 +18,21 @@ Calls, constructors, receiver/type inference, inheritance, namespace lookup, and
|
|||
fallback consumers use these ownership facts rather than independently choosing a
|
||||
same-named symbol.
|
||||
|
||||
Ownership and inferred type facts are separate. For providers that mark their
|
||||
name claims complete, an `assignment-inferred` or `constructor-inferred` fact
|
||||
does not declare a name. Lookup continues to the actual declaration, import, or
|
||||
shadowing barrier. Providers without complete claims retain their existing
|
||||
ownership rules.
|
||||
|
||||
The [shared records](../../gitnexus-shared/src/scope-resolution/types.ts) carry
|
||||
ownership, activation positions, directive destinations, and lookup purpose as
|
||||
serializable data. They retain declaration identity and ambiguity; they contain
|
||||
no AST nodes or callbacks. `declaredAtScope` describes ownership, while
|
||||
`runsOnlyWhenCalled` describes deferred execution. A function-local Rust `use` or
|
||||
C `#include` is not deferred merely because of its position; Python and Ruby
|
||||
loading can be. The
|
||||
no AST nodes or callbacks. For imports, `declaredAtScope` records lexical location
|
||||
independently of `runsOnlyWhenCalled`, which describes deferred execution. On a
|
||||
`TypeRef`, `declaredAtScope` anchors type-name lookup where the annotation or
|
||||
inference was written; it can differ from the binding's owner. A function-local
|
||||
Rust `use` or C `#include` is not deferred merely because of its position; Python
|
||||
and Ruby loading can be. The
|
||||
[function-local import chain tests](../../gitnexus/test/unit/scope-resolution/function-local-import-chain.test.ts)
|
||||
pin that distinction.
|
||||
|
||||
|
|
@ -88,6 +96,104 @@ namespace aliases. Computed specifiers, indirect loader/Promise chains, and
|
|||
unsupported destructuring remain unresolved; see the
|
||||
[loader regressions](../../gitnexus/test/unit/scope-resolution/typescript/local-loader-imports.test.ts).
|
||||
|
||||
#### Receiver type precedence
|
||||
|
||||
A constructor assignment inside a closure does not make that closure the owner
|
||||
of the assigned name. Lookup may retain the nearest constructor fact on its path
|
||||
to the owner when the owner has no type fact or only an inferred or propagated
|
||||
fact. It keeps the complete selected `TypeRef`, including the scope, position,
|
||||
and namespace in which its type name must resolve.
|
||||
|
||||
The owner's annotation, parameter annotation, return annotation, `self`, or
|
||||
decorator fact takes precedence. For example, assigning `new Foo()` to a
|
||||
parameter annotated `Base` inside a closure leaves receiver lookup anchored to
|
||||
`Base`, including its inherited methods. Same-scope precedence and
|
||||
`METHOD_OVERRIDES` relationships retain their existing rules. A nested write is
|
||||
not promoted into an unconditional type fact for reads outside that closure.
|
||||
These are static inference rules, not control-flow narrowing or a prediction of
|
||||
the receiver's runtime class. The
|
||||
[type ownership regressions](../../gitnexus/test/unit/scope-resolution/typescript/lexical-type-ownership.test.ts)
|
||||
and [shared lookup regressions](../../gitnexus/test/unit/scope-resolution/lexical-name-claims.test.ts)
|
||||
cover declaration ownership, fact precedence, and retained lookup anchors.
|
||||
|
||||
#### HTTP provenance
|
||||
|
||||
Express route receivers and fetch-wrapper analysis share
|
||||
[per-file lexical bindings](../../gitnexus/src/core/ingestion/route-extractors/lexical-bindings.ts).
|
||||
They track declaration identity across closures and check identity at each use;
|
||||
an unrelated same-named declaration in a sibling scope does not invalidate a
|
||||
binding. Writes to the tracked binding do invalidate its provenance. For a
|
||||
forwarded Express parameter, an initialized `var` redeclaration or a body
|
||||
function declaration is a write, while an uninitialized `var` declaration alone
|
||||
preserves the parameter value. See the
|
||||
[route provenance regressions](../../gitnexus/test/unit/framework-route-provenance.test.ts).
|
||||
|
||||
Automatic fetch-wrapper detection requires evidence of platform fetch. Bare
|
||||
`fetch` must be unshadowed; `globalThis.fetch`, `window.fetch`, and `self.fetch`
|
||||
require an unshadowed global root. Unresolved or blocked local names are not
|
||||
globals. An injected `fetch` parameter alone is not evidence. A default such as
|
||||
`fetch = globalThis.fetch` supplies potential platform evidence, not a guarantee
|
||||
that callers use that default. A self-referential
|
||||
`fetch = fetch` default or a locally shadowed `globalThis` does not supply it.
|
||||
Stable aliases retain this provenance by binding identity.
|
||||
|
||||
Nested callable bodies contribute only when reachable from the function's
|
||||
evaluated code through resolved binding references. Unused self-recursive or
|
||||
mutually recursive helpers do not prove a wrapper. IIFEs, inline callbacks, and
|
||||
directly escaping anonymous functions participate; a named stored helper needs
|
||||
a reachable reference. Class heritage, computed keys, static fields, and static
|
||||
blocks participate during class evaluation. Methods and instance fields remain
|
||||
deferred until the class binding is referenced from reachable code. This is a
|
||||
conservative approximation of potential execution: reading or returning a
|
||||
function does not execute its body, and referencing a class does not establish
|
||||
that every method runs. The
|
||||
[wrapper provenance cases](../../gitnexus/test/unit/fetch-wrapper-provenance.test.ts)
|
||||
cover these boundaries.
|
||||
|
||||
Bare wrapper calls and forwarded calls resolve declaration or import identity
|
||||
before using name fallback. Relative imports, renamed imports, tsconfig aliases,
|
||||
and workspace imports use the project module resolver. A known local
|
||||
non-wrapper, a different resolved target, or an ambiguous target blocks fallback.
|
||||
An unresolved name can fall back only when exactly one distinct definition can
|
||||
be the target, including non-wrappers, and that definition is a proven wrapper.
|
||||
For an import the resolver cannot follow, the candidates are module-level
|
||||
functions exported under the imported name; for an undeclared global, they are
|
||||
top-level functions of that name. Nested and unexported helpers are never
|
||||
candidates. This fallback is an analyzer recovery heuristic; it does not prove
|
||||
lexical identity. A function whose binding is reassigned in its file, including
|
||||
through `export { request as send }; request = other;` or a later
|
||||
`var request = …` initializer, proves no wrapper in importing files either. Explicit `fetchWrappers` configuration takes precedence
|
||||
over automatic inference, including for names shadowed by local parameters; member
|
||||
calls retain their existing matching rules. See the
|
||||
[wrapper consumer integration tests](../../gitnexus/test/integration/resolvers/fetch-wrapper-consumers.test.ts)
|
||||
and [configured wrapper tests](../../gitnexus/test/integration/resolvers/configurable-fetch-wrapper.test.ts).
|
||||
|
||||
The scope model does not represent separate parameter and body environments.
|
||||
When formals contain expressions, including nested defaults or computed pattern
|
||||
keys, HTTP inference therefore declines an affected binding if a body `var` or
|
||||
function declaration shares a parameter's name or a binding referenced by a
|
||||
parameter expression. Declarations inside nested functions do not count as outer
|
||||
body declarations; a rest parameter alone is not a parameter expression. The
|
||||
[lexical binding tests](../../gitnexus/test/unit/route-lexical-bindings.test.ts)
|
||||
pin this conservative boundary. If scope extraction fails, scope-dependent HTTP
|
||||
facts are omitted and the existing scope-extraction failure remains visible;
|
||||
unrelated structural extraction continues. A failing HTTP hook drops only that
|
||||
file's HTTP facts. Either way the file's function names are still recorded, so
|
||||
name fallback elsewhere declines instead of treating another definition as
|
||||
unique.
|
||||
|
||||
Barrels follow ECMAScript `ResolveExport`. A local or named export shadows
|
||||
`export *`, star exports never carry `default`, and a name that two star-exported
|
||||
modules export as different bindings is ambiguous, whether or not either is a
|
||||
wrapper. Two export names of one declaration are one binding.
|
||||
|
||||
Some recall is given up deliberately. A helper that conditionally rebinds its
|
||||
parameter, as in `if (!app) { var app = express(); }`, loses that parameter's
|
||||
provenance: the initialized `var` is a write. A dynamic-import shim such as
|
||||
`(...args) => import('node-fetch').then(...)` is not platform fetch evidence. A
|
||||
write to the URL parameter clears URL forwarding. Calls inside recovered syntax
|
||||
are still resolved, but nothing else inside an `ERROR` node is trusted.
|
||||
|
||||
Vue's explicit JS/JSX script requires an additional bounded semantic parse because
|
||||
the worker's structural tree uses TypeScript. That parse runs inside the real
|
||||
worker. The [parity test](../../gitnexus/test/integration/local-import-worker-parity.test.ts)
|
||||
|
|
@ -149,17 +255,29 @@ exact call-site positions are missing.
|
|||
|
||||
## Cache migration and verification evidence
|
||||
|
||||
[Parse-cache schema 136](../../gitnexus/src/storage/parse-cache.ts) replaces 133,
|
||||
134, and 135. It invalidates overly broad Python/TS/JS binding barriers,
|
||||
incorrect parameter-annotation lookup ownership, and embedded Vue grammar and
|
||||
source positions. The same version gate applies to the
|
||||
[durable ParsedFile store](../../gitnexus/src/storage/parsedfile-store.ts).
|
||||
Incompatible records are rejected and rebuilt on the next analysis; unchanged
|
||||
records can then be reused. The
|
||||
[schema regression](../../gitnexus/test/unit/incremental-parse-cache.test.ts)
|
||||
explicitly rejects valid schema-133, schema-134, and schema-135 records in both stores.
|
||||
PDG-mode chunk keys also advance to `pdg:6`, so embedded-script CFGs with
|
||||
incorrect call anchors are rebuilt before the resolved-callee join.
|
||||
Parser compatibility uses
|
||||
[automatic artifact-derived identities](../../MIGRATION.md#automatic-parser-cache-identities),
|
||||
not manually assigned semantic counters. The
|
||||
[worker-result cache](../../gitnexus/src/storage/parse-cache.ts) and
|
||||
[durable ParsedFile store](../../gitnexus/src/storage/parsedfile-store.ts)
|
||||
validate the same base identity and include it in their chunk keys. PDG-enabled
|
||||
chunks also include the PDG identity and resolved function-line cap. Legacy
|
||||
numeric, missing, malformed, or foreign identities cause a cache miss and rebuild;
|
||||
compatible records remain eligible for reuse. If identity verification fails,
|
||||
analysis uses a transient store without persistent cache reads or writes.
|
||||
|
||||
Parser contributors update no counter or generated digest. The
|
||||
[identity tests](../../gitnexus/test/unit/parse-cache-identity.test.ts),
|
||||
[input-coverage tests](../../gitnexus/test/unit/parse-cache-input-coverage.test.ts),
|
||||
and [lifecycle tests](../../gitnexus/test/integration/parse-cache-identity-lifecycle.test.ts)
|
||||
cover the compatibility gates. Source changes invalidate identity immediately,
|
||||
but compiled workers still need `npm run build` in `gitnexus/` before verification.
|
||||
|
||||
Cached wrapper import facts retain raw specifiers and imported names. Each
|
||||
analysis resolves them against the current project configuration, including on
|
||||
warm runs, so a changed tsconfig alias does not retain a stale wrapper target.
|
||||
The [wrapper persistence tests](../../gitnexus/test/integration/resolvers/fetch-wrapper-persistence.test.ts)
|
||||
cover raw cache transport, warm reuse, and alias changes.
|
||||
|
||||
The [real-worker parity suite](../../gitnexus/test/integration/local-import-worker-parity.test.ts)
|
||||
witnesses worker boot, dispatch, and returned ParsedFiles, then compares complete
|
||||
|
|
@ -180,13 +298,10 @@ ensures each is selected exactly once across the four Windows/macOS shards.
|
|||
Ubuntu's full suite discovers the tests normally. These are focused evidence
|
||||
boundaries, not a statement that the final full suite or every platform has passed.
|
||||
|
||||
## Relationship to main and issue #3499
|
||||
## Related Python ownership behavior
|
||||
|
||||
The integrated main baseline `50aa4be3` already includes #3502's nested Python
|
||||
declaration ownership fix for the original #3499 case and #3504's aliased package
|
||||
re-export fix. Their [Python integration coverage](../../gitnexus/test/integration/resolvers/python.test.ts)
|
||||
The nested declaration ownership fix in #3502 for the original #3499 case and
|
||||
the aliased package re-export fix in #3504 remain part of Python's provider rules.
|
||||
Their [Python integration coverage](../../gitnexus/test/integration/resolvers/python.test.ts)
|
||||
and [module namespace coverage](../../gitnexus/test/unit/scope-resolution/python/python-module-namespace-construction.test.ts)
|
||||
remain relevant. This branch extends that base with the lexical claims, provider
|
||||
semantics, and persistence evidence described above. Issue coverage is **Related
|
||||
#3499**; this document does not assert that all dynamic Python behavior is solved
|
||||
or make an issue-status claim.
|
||||
remain relevant. Lexical ownership does not model all dynamic Python behavior.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,260 @@
|
|||
---
|
||||
title: "fix: Preserve lexical binding ownership and HTTP provenance"
|
||||
date: 2026-10-18
|
||||
type: fix
|
||||
artifact_contract: ce-unified-plan/v1
|
||||
artifact_readiness: implementation-ready
|
||||
product_contract_source: legacy-requirements
|
||||
origin: https://github.com/abhigyanpatwari/GitNexus/issues/3630
|
||||
execution: code
|
||||
baseline_commit: 565e50276dc9aa4e3b6e36dfabe8a92571b0d699
|
||||
---
|
||||
|
||||
# Preserve lexical binding ownership and HTTP provenance
|
||||
|
||||
## Goal Capsule
|
||||
|
||||
**Objective:** GitNexus users receive HTTP routes, fetch consumers and member targets that respect the declarations their code actually refers to.
|
||||
|
||||
**Means:** Declaration-based lexical ownership and binding-based HTTP provenance (KTD1–KTD4).
|
||||
|
||||
**Authority:** The user request and issue #3630, including both revision-5 plan comments, govern behavior. The user's linear-scaling requirement supersedes the comment's suggestion to leave the repeated wrapper closure scan unchanged.
|
||||
|
||||
**Execution profile:** Implement and verify all units, with regression-first coverage and rebuilt workers. Apply SOLID, KISS, DRY, YAGNI and clean code; keep language policy in providers.
|
||||
|
||||
**Tail ownership:** LFG owns simplification, code review, fixes, shipping and CI. Create the PR through the authenticated GitHub browser; do not merge it.
|
||||
|
||||
**Stop conditions:** A genuine access blocker or evidence that the required behavior cannot be achieved within the stated scope must be reported with preserved work. Routine implementation decisions remain autonomous.
|
||||
|
||||
---
|
||||
|
||||
## Product Contract
|
||||
|
||||
### Summary
|
||||
|
||||
Correct assignment ownership, remove compensating text heuristics, and resolve Express and fetch-wrapper provenance using the existing scope model. Preserve declared-type precedence, configured wrappers, unrelated ingestion and other language providers.
|
||||
|
||||
### Problem Frame
|
||||
|
||||
A closure's inferred constructor fact can currently make it appear to declare an outer variable. HTTP analysis invalidates the wrong binding, rename compensates with a walk-past workaround, and wrapper analysis confuses unrelated same-named values. Repeated scans also make wrapper chains and large files vulnerable to quadratic work.
|
||||
|
||||
### Requirements
|
||||
|
||||
**Ownership and type information**
|
||||
|
||||
- R1. When a provider sets `nameClaimsComplete`, assignment-derived facts cannot establish lexical ownership. Genuine declarations and shadowing retain ownership; providers without that policy retain current behavior.
|
||||
- R2. Carry the nearest eligible skipped constructor fact only when the owner has no stronger fact. Return the complete selected `TypeRef`, preserving its scope, position and namespace. Keep same-scope tie rules unchanged and never propagate a nested write into an unconditional outer fact.
|
||||
- R3. Remove the imported-receiver rename walk-past workaround after real indexing/rename coverage proves the core fix suffices.
|
||||
|
||||
**HTTP provenance**
|
||||
|
||||
- R4. Share lexical ownership, binding IDs, global checks and ambiguity checks between route and wrapper analysis. Invalidate initialized `var` redeclarations of forwarded parameters; keep uninitialized redeclarations. Remove `written` and `shadowedBetween`.
|
||||
- R5. Bare platform `fetch` and platform-global member access require unshadowed global identity. Unknown injected parameters provide no evidence. Valid platform defaults provide potential evidence; self-referential defaults and shadowed platform globals do not.
|
||||
- R6. Determine nested callable reachability from evaluated outer code and resolved binding references. Unrooted recursive cycles remain excluded. IIFEs, inline callbacks and directly escaping anonymous values participate. Named stored helpers require a reachable binding reference. Class heritage, computed keys, static fields and static blocks are evaluated independently of class-name references; methods and instance fields remain deferred until a reachable class reference. Supported decorator expression/application/initializer behavior follows the provider dialect.
|
||||
- R7. Resolve bare callees to declaration/import identity before automatic fallback. Use project import resolution for relative, tsconfig and workspace specifiers. Known local non-wrappers, different resolved targets and ambiguity prevent name fallback. Fallback requires exactly one distinct same-named definition, including non-wrappers in the collision universe, and that definition must be proven. Apply the same rule to forwarding. Preserve existing member-call behavior and explicit configured wrapper-name overrides, including through local parameters.
|
||||
- R8. Fail closed for collapsed parameter/body environments: if formals contain expressions, including nested defaults or computed pattern keys, a body `var`/function name also declared as a parameter or referenced in a parameter expression is ambiguous. Do not treat declarations in nested functions as outer body declarations. Rest alone is not an expression. Missing `ParsedFile` skips scope-dependent HTTP analysis only and retains existing scope-failure accounting.
|
||||
|
||||
**Verification and delivery**
|
||||
|
||||
- R9. Compare every `CALLS` edge at call-site/target identity level on the identical TS/JS fixture corpus and pinned rebuilt baseline/candidate builds; inspect every change. Receiver changes must be explained by restored owner declarations. Preserve `METHOD_OVERRIDES` and ancestor dispatch. Keep route/FETCHES, rename, import ownership, inheritance and taint suites green, including the existing seven fetch-base-url-wrapper edges, receiver-resolution and tool-accuracy checks.
|
||||
- R10. Provide repeatable warmed scaling benchmarks with multiple sizes, repetitions, statistics, semantic fingerprints and explicit linear-factor checks. Include reversed forwarding chains, name collisions, concentrated declarations/reads, nested helper reachability and fresh per-file index construction. Report measured bounds and limitations honestly.
|
||||
- R11. Update `docs/languages/local-import-scoping.md` for ownership versus facts, type precedence, provenance, ambiguity and automatic cache identities. Rebuild workers before validation; prove cold/warm cache transport. Open a reviewable PR with the validation and benchmark evidence.
|
||||
|
||||
### Scope Boundaries
|
||||
|
||||
Do not implement full control-flow narrowing, factory-call narrowing, capture-time binding storage, other-language ownership changes, separate parameter environments, SvelteKit fetch injection, or unrelated refactors. Do not manually bump parser cache counters or alter CI/release/security configuration.
|
||||
|
||||
### Sources
|
||||
|
||||
- [Issue body](https://github.com/abhigyanpatwari/GitNexus/issues/3630).
|
||||
- [Plan sections 1–10](https://github.com/abhigyanpatwari/GitNexus/issues/3630#issuecomment-6255593894).
|
||||
- [Plan sections 11–13](https://github.com/abhigyanpatwari/GitNexus/issues/3630#issuecomment-6255594141).
|
||||
- `docs/languages/local-import-scoping.md`, `MIGRATION.md`, `AGENTS.md`, `GUARDRAILS.md`, `CONTRIBUTING.md`.
|
||||
|
||||
---
|
||||
|
||||
## Planning Contract
|
||||
|
||||
### Key Technical Decisions
|
||||
|
||||
- KTD1. **Honor complete declaration claims in shared lookup.** Change `name-claims.ts` without naming languages. Preserve whole facts and their existing strength policy; `scope-extractor.ts` provides the precedence reference.
|
||||
- KTD2. **One per-file lexical analysis context.** Extract `createLexicalBindings` and pass the existing AST root explicitly alongside `ParsedFile` and line offset. `ParsedFile` does not retain parameter expression syntax, so the extra AST input is necessary for R8 without expanding the persisted scope model. Cache ownership by node/use and index ambiguity once. Avoid repeated linear scope-position scans in affected hot paths.
|
||||
- KTD3. **Provider-owned wrapper analysis.** Replace the worker's language-name branch with an optional provider hook/context. Build shared context once per file and reuse it for facts/call sites. Keep new serializable identity metadata in parser-owned result shapes so automatic identities invalidate old cache entries.
|
||||
- KTD4. **Resolve imports before route classification.** Reuse `resolveRouteModuleTargets` in `parse-impl.ts`, including wrapper-only files when loading project configs. Preserve unresolved, blocked and resolved target states. Index all relevant distinct definitions by binding identity and module/name; do not infer uniqueness from seed-only definitions.
|
||||
- KTD5. **Work queues instead of repeated closure scans.** Build dependency edges once, propagate wrapper status through reverse dependencies, and index reachable callable regions once. Use mutable collision buckets instead of repeated array copying. Scaling checks include fresh context construction and adversarial ordering.
|
||||
- KTD6. **Pinned semantic comparison plus separate timing.** Retain an untouched checkout/build at the baseline SHA. Export sorted full call-site edges and override edges from real pipelines before/after; exact fingerprints and positive result counts prevent fast empty answers. Follow `bench/go-route-resolution/measure.cjs` for reproducibility, adding mean/median/deviation and at least three workload sizes.
|
||||
|
||||
### High-Level Technical Design
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
P["Provider: AST and ParsedFile"] --> L["Per-file lexical context"]
|
||||
L --> F["Route and wrapper facts"]
|
||||
F --> I["Project import resolution"]
|
||||
I --> D["Definition and dependency indexes"]
|
||||
D --> W["Wrapper work queue"]
|
||||
W --> H["HTTP graph edges"]
|
||||
```
|
||||
|
||||
### Assumptions and Risks
|
||||
|
||||
- The baseline is current `main` with both prerequisite PRs merged. Issue line numbers are navigation hints; current source is authoritative.
|
||||
- A lookup cache alone does not prove linearity: position-index scans, deep repeated AST traversals and long dependency chains need direct measurement. Optimize only demonstrated hot paths required by R10.
|
||||
- Runtime allocation and timing vary on this host. Use warmed repeated samples and generous normalized ratio gates; treat timing evidence as empirical, backed by traversal structure and semantic checks.
|
||||
- No GitNexus MCP or existing checkout index is available. Attempt the documented CLI impact/change commands and record any unavailable graph evidence; source caller tracing supplements unresolved results.
|
||||
- No new dependency is expected. No behavior of unsupported parameter environments is claimed beyond fail-closed HTTP inference.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Units
|
||||
|
||||
### U1. Declaration ownership and rename
|
||||
|
||||
**Goal:** Restore lexical ownership while preserving receiver facts under R1–R3.
|
||||
|
||||
**Dependencies:** Baseline capture in U5 before production edits.
|
||||
|
||||
**Files:** `gitnexus-shared/src/scope-resolution/name-claims.ts`; `gitnexus/src/core/ingestion/languages/typescript/rename.ts`; `gitnexus/test/unit/scope-resolution/lexical-name-claims.test.ts`; `gitnexus/test/unit/scope-resolution/typescript/lexical-type-ownership.test.ts`; relevant receiver/rename integration fixtures.
|
||||
|
||||
**Approach:** Apply KTD1, then remove the workaround once ownership tests pass. Avoid changing method dispatch.
|
||||
|
||||
**Test scenarios:**
|
||||
- Direct and chained constructor writes in closures resolve to outer parameters/module bindings for TS and JS.
|
||||
- Owner annotations and parameter annotations, including JSDoc, return the complete owner fact; untyped owners retain the nearest eligible carried fact.
|
||||
- Real local shadowing remains local and incomplete-claims providers retain prior ownership.
|
||||
- A nested write does not type an outer read; same-scope and closure annotated receivers target `Base.m` with unchanged override edges.
|
||||
- Existing imported receiver reassignment remains rejected by real rename tests.
|
||||
|
||||
**Verification:** Focused ownership and rename tests, full edge comparison and receiver check.
|
||||
|
||||
### U2. Shared bindings and Express invalidation
|
||||
|
||||
**Goal:** Satisfy R4/R8 using KTD2.
|
||||
|
||||
**Dependencies:** U1.
|
||||
|
||||
**Files:** `gitnexus/src/core/ingestion/route-extractors/lexical-bindings.ts`; `framework-route-facts.ts` in that directory; `gitnexus/test/unit/framework-route-provenance.test.ts`; `gitnexus/test/unit/group/express-provider-provenance.test.ts`; a focused lexical-helper test if needed.
|
||||
|
||||
**Approach:** Extract the existing ownership mechanism, index parameter/body ambiguity from the AST, add initialized-parameter redeclaration invalidation, then remove text guards.
|
||||
|
||||
**Test scenarios:**
|
||||
- Module `let app` reassigned in a closure produces no `/let-closure` route.
|
||||
- Initialized `var app` overwrites forwarding with and without other defaults; bare `var app` retains forwarding in supported simple-formal cases.
|
||||
- Nested same-named parameter writes do not invalidate the outer parameter; destructuring writes and block shadowing remain correct.
|
||||
- Nested destructuring defaults/computed keys trigger ambiguity; rest alone does not; body function declarations count, nested-function declarations do not.
|
||||
|
||||
**Verification:** Route provenance/group suites and rebuilt real Express integration.
|
||||
|
||||
### U3. Scope-aware wrapper extraction
|
||||
|
||||
**Goal:** Satisfy R5/R6/R8 using KTD2/KTD3.
|
||||
|
||||
**Dependencies:** U2 helper interface.
|
||||
|
||||
**Files:** `gitnexus/src/core/ingestion/route-extractors/fetch-wrapper.ts`; `gitnexus/src/core/ingestion/language-provider.ts`; `gitnexus/src/core/ingestion/languages/typescript.ts`; `gitnexus/src/core/ingestion/workers/parse-worker.ts`; `gitnexus/test/unit/fetch-wrapper-calls.test.ts`; targeted worker/integration fixtures.
|
||||
|
||||
**Approach:** Use binding IDs for URL parameters, aliases and nested references. Reuse file-level region indexing; no conflicting/localNames/referenced text sets. Preserve full declaration inventory for U4.
|
||||
|
||||
**Test scenarios:**
|
||||
- All four platform-fetch/default rows from the issue, plus sibling block shadowing and alias shadowing.
|
||||
- Self-recursive and mutually recursive unused helpers remain excluded; rooted chains/cycles participate.
|
||||
- IIFE, inline callback, escaping anonymous function, unused named arrow helper and referenced helper are distinguished.
|
||||
- Class declaration/expression heritage, computed keys, static blocks/static fields participate; methods/instance fields defer until referenced; supported decorators follow evaluation boundaries.
|
||||
- Missing scope skips wrapper facts/call sites, retains unrelated definitions and reports scope failure; Vue line offsets remain correct.
|
||||
|
||||
**Verification:** Data-driven facts tests plus real worker/cache transport and unchanged seven-edge integration fixture.
|
||||
|
||||
### U4. Target identity and linear propagation
|
||||
|
||||
**Goal:** Satisfy R7/R10 using KTD4/KTD5.
|
||||
|
||||
**Dependencies:** U3 serialized identity contract; implementation can prepare independent resolution helpers after that contract is fixed.
|
||||
|
||||
**Files:** `gitnexus/src/core/ingestion/pipeline-phases/parse-impl.ts`; `gitnexus/src/core/ingestion/pipeline-phases/routes.ts`; provider-owned wrapper resolver helper if extraction and classification need a focused boundary; `gitnexus/test/unit/fetch-wrapper-calls.test.ts`; `gitnexus/test/integration/resolvers/fetch-wrapper-consumers.test.ts` and fixtures.
|
||||
|
||||
**Approach:** Resolve specifiers with the existing project resolver, classify known targets directly, enforce unique fallback across all definitions and propagate through a work queue. Configured names match first.
|
||||
|
||||
**Test scenarios:**
|
||||
- Relative renamed imports, tsconfig path aliases and workspace imports target the actual wrapper.
|
||||
- A different resolved target, local parameter, nested local or blocked claim cannot inherit same-name wrapper status.
|
||||
- One wrapper plus one plain non-wrapper and two wrappers both prevent fallback; duplicate captures of one definition do not create false ambiguity.
|
||||
- Unique unresolved fallback succeeds; forwarding uses the same rule.
|
||||
- Configured local-parameter calls succeed, identical unconfigured calls decline; member behavior remains covered.
|
||||
- Reversed long chains terminate with correct results; unrooted cycles remain excluded.
|
||||
|
||||
**Verification:** Extraction/classifier tests, pipeline FETCHES fixtures and scaling checks.
|
||||
|
||||
### U5. Semantic comparison and scaling evidence
|
||||
|
||||
**Goal:** Establish R9/R10 with KTD6.
|
||||
|
||||
**Dependencies:** Baseline capture precedes U1; candidate runs follow U1–U4.
|
||||
|
||||
**Files:** `gitnexus/bench/lexical-binding-provenance/measure.cjs`; `baseline.json` and `README.md` in that directory; a reusable call-site export/comparison runner there if no existing runner preserves all required identities; targeted comparison fixtures.
|
||||
|
||||
**Approach:** Use the identical baseline/candidate fixture corpus and pinned builds. Record all CALLS and METHOD_OVERRIDES edges, classify every delta, and measure fresh-context workloads over N/2N/4N or wider scales with warmups and at least 15 samples. Report environment, min/mean/median/deviation, normalized ratios, exact fingerprints and positive counts. Benchmark extraction separately from wrapper closure. Include aliases, nested helpers, concentrated reads following many completed scopes, collisions and reversed chains. Set a normalized linear-factor ceiling before checking the candidate; investigate any failure rather than widening it to fit.
|
||||
|
||||
**Test scenarios:**
|
||||
- Semantic changes in annotated closure receivers are explained at their exact sites; other call categories remain unchanged.
|
||||
- Baseline/candidate exports preserve source/target identity and multiplicity; override edge sets remain identical.
|
||||
- Incorrect empty output fails correctness gates even if fast; reversed order exposes repeated scans.
|
||||
|
||||
**Verification:** Reproducible `--check` benchmark and saved edge-diff report in the PR evidence.
|
||||
|
||||
### U6. Contract and full validation
|
||||
|
||||
**Goal:** Complete R9/R11.
|
||||
|
||||
**Dependencies:** U1–U5.
|
||||
|
||||
**Files:** `docs/languages/local-import-scoping.md`; benchmark evidence documentation; only justified receiver baseline updates if exact edge review warrants them.
|
||||
|
||||
**Approach:** Document analysis policy versus runtime semantics, supported ownership guarantees and fail-closed limits. Replace stale numeric cache gate text with automatic identity references. Run mandatory regression, accuracy and cache gates on rebuilt code.
|
||||
|
||||
**Test scenarios:** Existing suites provide behavioral coverage; documentation adds no new executable behavior.
|
||||
|
||||
**Verification:** All required commands below pass or any concrete environment failure is isolated against the pinned baseline and explicitly reported.
|
||||
|
||||
---
|
||||
|
||||
## Verification Contract
|
||||
|
||||
Run from `gitnexus/`; use `GITNEXUS_WORKER_READY_TIMEOUT_MS=180000` for worker-based commands on this host.
|
||||
|
||||
| Gate | Command or evidence | Units |
|
||||
| --- | --- | --- |
|
||||
| Build | `npm run build` before worker verification | All |
|
||||
| Types | `npx tsc --noEmit` and test typecheck when tests change | All |
|
||||
| Focused regressions | Ownership, wrapper, route, rename, taint lexical imports and group unit suites | U1–U4 |
|
||||
| Real integration | `npm run test:integration -- test/integration/resolvers/ test/integration/rename-provider-matrix.test.ts test/integration/local-import-worker-parity.test.ts` | U1–U4 |
|
||||
| Receiver accuracy | `node --import tsx bench/receiver-resolution/measure.mjs --check` | U1/U5 |
|
||||
| Tool accuracy | `node --import tsx bench/tool-accuracy/run.ts --check` | U5/U6 |
|
||||
| Scaling | `node --import tsx bench/lexical-binding-provenance/measure.cjs --check` | U5 |
|
||||
| Cache identities | `npm test -- test/unit/parse-cache-identity.test.ts test/unit/parse-cache-input-coverage.test.ts` plus cold/warm transport | U3/U6 |
|
||||
| Full suite | `npm test` as required before commit; bound workers for host resources | All |
|
||||
| Semantic parity | Sorted call-site/target export diff and unchanged override/ancestor behavior | U1/U5 |
|
||||
|
||||
---
|
||||
|
||||
## Definition of Done
|
||||
|
||||
Every requirement and issue acceptance table is covered, no unjustified call-target difference remains, required accuracy checks and regression suites pass, and scaling is measured with semantic identity guards. The production diff contains no abandoned experiments, unrelated cleanup or text-based scope heuristics. The contract is updated, work is reviewed and committed, and an open PR created through the authenticated browser contains benchmark results and any material validation limitations.
|
||||
|
||||
## Execution checkpoint
|
||||
|
||||
- U1 committed as `f791aae2`; declaration-ownership regressions and the imported-receiver rename regression pass. The write lookup explicitly preserves source order across deferred scopes so it sees the import before the write's blocker.
|
||||
- U2 committed as `a18f9faa`; 154 focused tests, production/test types, and scoped lint pass. Deterministic comparison-count regressions justified replacing the position index's expired-prefix scan with a maximum-end tree.
|
||||
- U3/U4 committed as `685e8189`. Regression-first evidence includes 42 extraction failures and real pipeline false positives/missed imports. The rebuilt pipeline preserves the seven existing base-URL edges, passes six new identity-based edges and configured overrides, and passes cold/warm cache reuse with alias retargeting. All 503 focused tests passed, including a real-worker scope-extraction failure that retains structural ingestion while omitting HTTP facts.
|
||||
- U5 captured the original baseline before production changes. Formatting the standalone ownership probe required a second fixed corpus; the original remains retained. The final baseline is still immutable `565e50276dc9aa4e3b6e36dfabe8a92571b0d699`, with 432 files, 432 `CALLS`, 11 `METHOD_OVERRIDES`, and corpus fingerprint `88be1faf45e9aec145f9d168b8959d67f31ec3b09b5455e9c8d8b2b1681ade5a`. Clean candidate `685e8189` changes exactly one target: `declaredOwner.writeAndRead` at callsite line 14, column 4 now calls `Base.m` instead of `Foo.m`. The other 431 CALLS and all 11 override edges are unchanged; the exact diff is committed under the benchmark results.
|
||||
- The quiet baseline scaling run completed with the fixed 5 warmups, 15 samples, and 1.8 normalized ceiling. A loaded candidate diagnostic exposed two native AST costs: parent lookup descends from the root, and indexed child lookup rescans siblings. Three deterministic regressions failed with semantic controls passing (parent work 66,564 and 265,092 versus 4,096; sibling work 69,906 versus 8,192). U2/U3 now record traversal parents and use one bulk child array per node; the three complexity cases and 376 semantic tests pass, as do the build, test typecheck, and scoped lint (warnings only). Earlier broad/full candidate runs were canceled before changing production code; none is reported as complete.
|
||||
- U6 documentation is updated. Receiver accuracy passes; tool accuracy exactly matches the baseline (29/32 answers, three documented gaps, regression gate passes).
|
||||
- Review and simplification fixes are committed as `67c268e88`, `6f28dd6c7`, `a8bbc00ec`, `fe67b0856`, `205787b2c` and `47d09da4a`: wrapped assignment targets are writes, wrappers resolve through overloads, declarator lists, barrels, HOCs, CommonJS exports, object keys and fetch packages, and per-file HTTP contexts are released after use. `c41ad6ea9` replaces recursion in the new traversals with explicit stacks.
|
||||
- Profiling the 512-unit wrapper arm showed native node construction (`namedChildren`, `childForFieldName`, `id`) dominating context construction. `7fcf3506c` limits the lexical-binding walk to functions whose formals contain an expression; `6061ca71b` collects wrapper evidence in one tree-cursor walk that materializes only inspected nodes and keys declarations by start offset. On the 512-unit wrapper workload, context construction fell from 58 to 48 ms.
|
||||
- Review of `61de364ff` found that star exports reaching two export names of one declaration (`export { request, request as send }` behind two barrels) were counted as conflicting, which blocked the import and dropped its FETCHES edge. `4d62bd045` keys star-export candidates by the declaration each name refers to; distinct declarations stay ambiguous. A unit diamond and a real-parser fixture pair cover both cases; with the fix reverted only the diamond edge disappears.
|
||||
- A multi-lane review of `5c179994c` (review 5575463241) found two recall regressions and several smaller gaps; `3c00b9f32` and `d3c357276` fix them. CommonJS wrappers captured as their assignment produce facts again. Name-only fallback considers only definitions that can be the target (module-level exports for an unresolvable import, top-level functions for an undeclared global). Only possible wrappers and module-level functions are emitted, and the index is built only with routes and candidate calls. Rebound bindings prove no wrapper across files; `(<T>x) = …` is a write; calls inside recovered syntax and instance-field initializers resolve; local exports make star-export conflicts visible; resolved barrel frames are shared; HTTP hooks are guarded per file and failed files still record their function names; an undeclared constructor write keeps its type for reads in the writing scope. Each behavior row fails on the previous source. The receiver baseline counts one new dropped write from the added CommonJS fixture (`9c4821106`).
|
||||
- A behavior-preserving simplification pass (`3db8657ba`) shares the CommonJS `module`/`exports` checks, derives `LEXICAL_FUNCTION_TYPES` from the TypeScript `FUNCTION_NODE_TYPES`, reads each node's type once in the route-facts loop, and returns the latest-starting scope from the position index before the max-end search when it already contains the point. Focused suites (5019 tests), build, typechecks and lint pass; the resolver integration files that timed out at 30 s on the 9p checkout pass with a 120 s limit.
|
||||
- Review fixes in `c263c4f72` retain fetch evidence from destructuring defaults (shorthand, renamed, array and local forms), count each binding initialization once, and record parenthesized default exports. JS/TS/TSX regression rows fail against the previous source, and two fixture consumers cover imported wrappers. The commit also clarifies failed-extraction fallback records and the collapsed parameter/body environment test boundary. All 73 CI checks pass for this revision; the refreshed receiver check matches the existing baseline.
|
||||
- Final semantic comparison at `c263c4f72` (export fingerprint `4db24f57…`, clean tree, unchanged since `6061ca71b`) keeps the single expected CALLS change; the other 431 CALLS and all 11 override edges match the baseline export `3e00ca5b…`. Both exports use the same frozen 432-file corpus (`88be1faf…`).
|
||||
- Final scaling at `c263c4f72` against baseline `565e50276` ran back to back on CPU 23; the host's 1-minute load, sampled every 30 s in an uncommitted log, had a median of 1.50 and peaked at 4.53. The largest candidate factor is 1.245 (rounded), below the 1.8 ceiling. The baseline fails six of nine arms: `position-index`, `position-deep-completed`, `nested-helpers`, `nested-helper-chain`, `reverse-chain` and `name-collisions`. Workload fingerprints match except `name-collisions`, where the baseline's false positive is recorded as `known-baseline-failure`. For the three arms that were already linear, candidate median times relative to baseline at the largest input are 1.07x spread aliases, 1.00x completed scopes and 0.99x wrapper aliases (between 1.01x and 1.24x across earlier pairs; run-to-run noise on this host is about 0.1x).
|
||||
- The full suite passed in CI at `61de364ff` (1269 files passed and 12 skipped; 27194 tests passed, 83 skipped, none failed) and again at `5c179994c` (73 checks green). A local full run on the 9p checkout was stopped after four hours in the serial database lane, where real-analysis tests hit their timeouts; it is not recorded as a pass. At `528ea1478`, focused suites (5019 tests), HTTP integration (56), build, test typecheck, lint and formatting pass; receiver accuracy matches the updated baseline and tool accuracy matches (29/32).
|
||||
- Graph impact/change checks remain unavailable: neither repository-wide indexing attempt published an index. Source caller tracing supplements this unknown result; no clean or low-risk graph result is claimed.
|
||||
|
|
@ -176,6 +176,14 @@ function matchesBindingClaim(range: Range | undefined, claim: NameClaim): boolea
|
|||
);
|
||||
}
|
||||
|
||||
/** A fact inferred from an assigned value; it describes a value, never a declaration. */
|
||||
const isInferredWrite = (source: TypeRef['source']): boolean =>
|
||||
source === 'assignment-inferred' || source === 'constructor-inferred';
|
||||
|
||||
/** Any inferred fact, including types propagated from a receiver. */
|
||||
const isInferredFact = (source: TypeRef['source']): boolean =>
|
||||
isInferredWrite(source) || source === 'receiver-propagated';
|
||||
|
||||
export function lookupLexicalName(
|
||||
startScope: ScopeId,
|
||||
name: string,
|
||||
|
|
@ -185,6 +193,7 @@ export function lookupLexicalName(
|
|||
let id: ScopeId | null = startScope;
|
||||
let position = options.position;
|
||||
let forcedClaims: readonly NameClaim[] | undefined;
|
||||
let carriedConstructor: TypeRef | undefined;
|
||||
const visited = new Set<ScopeId>();
|
||||
while (id !== null && !visited.has(id)) {
|
||||
visited.add(id);
|
||||
|
|
@ -225,7 +234,8 @@ export function lookupLexicalName(
|
|||
const skippedIds = new Set<ScopeId>();
|
||||
while (skipped !== undefined && skipped.id !== target.id && !skippedIds.has(skipped.id)) {
|
||||
skippedIds.add(skipped.id);
|
||||
if (skipped.lookupPolicy?.deferParentActivation) position = undefined;
|
||||
if (skipped.lookupPolicy?.deferParentActivation && !options.preservePosition)
|
||||
position = undefined;
|
||||
skipped = skipped.parent === null ? undefined : sources.scopes.getScope(skipped.parent);
|
||||
}
|
||||
id = target.id;
|
||||
|
|
@ -271,7 +281,7 @@ export function lookupLexicalName(
|
|||
const ownType = scope.typeBindings.get(name);
|
||||
const typeFactOwnsName =
|
||||
ownType !== undefined &&
|
||||
!(scope.lookupPolicy?.nameClaimsComplete && ownType.source === 'assignment-inferred');
|
||||
!(scope.lookupPolicy?.nameClaimsComplete && isInferredWrite(ownType.source));
|
||||
const owns =
|
||||
selected.status === 'selected' ||
|
||||
bindings.length > 0 ||
|
||||
|
|
@ -293,16 +303,15 @@ export function lookupLexicalName(
|
|||
// Check ownership after that fact binds its value, not at the producer's
|
||||
// lookup position: a later shadowing let still reads the earlier binding
|
||||
// in its initializer, but must not lend that binding its inferred type.
|
||||
const factClaims =
|
||||
ownType.source === 'constructor-inferred' || ownType.source === 'assignment-inferred'
|
||||
? selectClaimsAtScope(scope, name, {
|
||||
...options,
|
||||
position: {
|
||||
startLine: ownType.bindingRange.endLine,
|
||||
startCol: ownType.bindingRange.endCol,
|
||||
},
|
||||
})
|
||||
: undefined;
|
||||
const factClaims = isInferredWrite(ownType.source)
|
||||
? selectClaimsAtScope(scope, name, {
|
||||
...options,
|
||||
position: {
|
||||
startLine: ownType.bindingRange.endLine,
|
||||
startCol: ownType.bindingRange.endCol,
|
||||
},
|
||||
})
|
||||
: undefined;
|
||||
if (
|
||||
factClaims?.status !== 'selected' ||
|
||||
factClaims.claims.length !== selected.claims.length ||
|
||||
|
|
@ -312,6 +321,13 @@ export function lookupLexicalName(
|
|||
)
|
||||
typeBinding = undefined;
|
||||
}
|
||||
// Inferred writes do not declare bindings. Preserve the nearest write's
|
||||
// complete lookup anchor, but never replace the owner's declared type.
|
||||
if (
|
||||
carriedConstructor !== undefined &&
|
||||
(typeBinding === undefined || isInferredFact(typeBinding.source))
|
||||
)
|
||||
typeBinding = carriedConstructor;
|
||||
const usable = bindings.filter(
|
||||
(b) => (options.purpose ?? 'value') !== 'value' || b.via?.typeOnly !== true,
|
||||
);
|
||||
|
|
@ -330,8 +346,18 @@ export function lookupLexicalName(
|
|||
claims: selected.claims,
|
||||
};
|
||||
}
|
||||
if (scope.lookupPolicy?.deferParentActivation) position = undefined;
|
||||
if (
|
||||
scope.lookupPolicy?.nameClaimsComplete &&
|
||||
!hasClaimsForName &&
|
||||
ownType?.source === 'constructor-inferred'
|
||||
)
|
||||
carriedConstructor ??= ownType;
|
||||
if (scope.lookupPolicy?.deferParentActivation && !options.preservePosition)
|
||||
position = undefined;
|
||||
id = scope.lookupPolicy?.parentScope ?? scope.parent;
|
||||
}
|
||||
return id === null ? ABSENT : { ...ABSENT, status: 'blocked' };
|
||||
// A write to an undeclared name declares nothing, but it still carries the
|
||||
// value's type to reads inside the writing scope.
|
||||
const carried = carriedConstructor === undefined ? {} : { typeBinding: carriedConstructor };
|
||||
return id === null ? { ...ABSENT, ...carried } : { ...ABSENT, ...carried, status: 'blocked' };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,21 +5,19 @@
|
|||
* Per-file sorted array of `(range, scopeId)` entries, sorted by start
|
||||
* position ASC (`startLine`, then `startCol`). `atPosition(filePath, line,
|
||||
* col)` binary-searches for the last entry whose start ≤ (line, col), then
|
||||
* scans backward through the sorted prefix and returns the first entry
|
||||
* whose range contains the query position.
|
||||
* searches a range-maximum tree for the rightmost entry that has not ended.
|
||||
*
|
||||
* **Why this works.** `ScopeTree`'s invariants (parent strictly contains
|
||||
* child; siblings don't overlap) guarantee that the scopes containing a
|
||||
* given point form an **ancestor chain**. When scanning backward through
|
||||
* entries sorted by start position ASC, the first scope we find that
|
||||
* contains the query is the innermost one — any deeper-starting scope
|
||||
* that also contained the query would appear *later* in the sorted array,
|
||||
* but we're only scanning entries with start ≤ query, so anything later
|
||||
* necessarily starts after the query and can't contain it.
|
||||
* given point form an **ancestor chain**. Among entries whose start is at or
|
||||
* before the query, the last containing entry is innermost: a deeper-starting
|
||||
* scope would appear later in the sorted array. The maximum-end tree finds
|
||||
* that last match without visiting completed scopes individually.
|
||||
*
|
||||
* Expected complexity: `O(log N_file + D)` where `D` is the lexical depth
|
||||
* at the query position (typically ≤ 10). Worst-case degrades to `O(N_file)`
|
||||
* only under pathological inputs (many scopes starting at the same line).
|
||||
* The maximum end position lets a query skip an entire interval of completed
|
||||
* scopes at once, including completed nested scopes. Queries take
|
||||
* `O(log N_file)`; the auxiliary tree takes linear space and construction time
|
||||
* after sorting. Repeated outer reads never rescan all preceding siblings.
|
||||
*
|
||||
* **Line/column conventions.** Matches `Range` in `types.ts`: lines are
|
||||
* 1-based, columns are 0-based. Ranges are **inclusive on both ends** —
|
||||
|
|
@ -45,9 +43,8 @@ export interface PositionIndex {
|
|||
* contained by **both**. The innermost-wins tie-break rule applies as
|
||||
* usual: since neither is nested inside the other, the one that
|
||||
* **starts latest** wins, i.e. the **right** sibling. The mechanism
|
||||
* is the backward scan through the start-position-sorted array (see
|
||||
* `findLastStartLteIndex` below) — both siblings land before the
|
||||
* upper-bound cursor, and the right sibling is scanned first. Queries at non-boundary positions between them naturally
|
||||
* is the rightmost match in the start-position-sorted array — both siblings
|
||||
* land before the upper-bound cursor, and the right sibling wins. Queries at non-boundary positions between them naturally
|
||||
* fall to the unique containing scope.
|
||||
*/
|
||||
atPosition(filePath: string, line: number, col: number): ScopeId | undefined;
|
||||
|
|
@ -77,11 +74,13 @@ export function buildPositionIndex(scopes: readonly Scope[]): PositionIndex {
|
|||
bucket.push({ id: scope.id, range: scope.range });
|
||||
}
|
||||
|
||||
for (const bucket of entriesByFile.values()) {
|
||||
const files = new Map<string, FileIndex>();
|
||||
for (const [filePath, bucket] of entriesByFile) {
|
||||
bucket.sort(compareEntry);
|
||||
files.set(filePath, { entries: bucket, maximumEnds: buildEndIndex(bucket) });
|
||||
}
|
||||
|
||||
return wrapIndex(entriesByFile, seen.size);
|
||||
return wrapIndex(files, seen.size);
|
||||
}
|
||||
|
||||
// ─── Internals ──────────────────────────────────────────────────────────────
|
||||
|
|
@ -91,11 +90,44 @@ interface Entry {
|
|||
readonly range: Range;
|
||||
}
|
||||
|
||||
interface FileIndex {
|
||||
readonly entries: readonly Entry[];
|
||||
readonly maximumEnds: readonly Range[];
|
||||
}
|
||||
|
||||
/** Each tree node stores the latest end in its contiguous entry interval. */
|
||||
function buildEndIndex(entries: readonly Entry[]): Range[] {
|
||||
const maximumEnds: Range[] = [];
|
||||
// Post-order without recursion: a node combines its children once both exist.
|
||||
const stack: [node: number, first: number, last: number, combine: boolean][] = [
|
||||
[1, 0, entries.length - 1, false],
|
||||
];
|
||||
while (stack.length > 0) {
|
||||
const [node, first, last, combine] = stack.pop()!;
|
||||
if (first === last) {
|
||||
maximumEnds[node] = entries[first]!.range;
|
||||
continue;
|
||||
}
|
||||
if (!combine) {
|
||||
const middle = (first + last) >>> 1;
|
||||
stack.push(
|
||||
[node, first, last, true],
|
||||
[node * 2 + 1, middle + 1, last, false],
|
||||
[node * 2, first, middle, false],
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const left = maximumEnds[node * 2]!;
|
||||
const right = maximumEnds[node * 2 + 1]!;
|
||||
maximumEnds[node] = endIsAtOrAfter(left, right.endLine, right.endCol) ? left : right;
|
||||
}
|
||||
return maximumEnds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort by start position ASC, breaking ties by end position DESC so that
|
||||
* larger (outer) scopes appear before their smaller (inner) co-starting
|
||||
* siblings in the array. Makes the backward-scan contract crisp: the
|
||||
* first containing hit from the end of the scanned prefix is the
|
||||
* siblings in the array. The rightmost containing entry is the
|
||||
* innermost scope.
|
||||
*/
|
||||
function compareEntry(a: Entry, b: Entry): number {
|
||||
|
|
@ -140,27 +172,43 @@ function findLastStartLteIndex(arr: readonly Entry[], line: number, col: number)
|
|||
return lo - 1;
|
||||
}
|
||||
|
||||
function wrapIndex(entriesByFile: Map<string, Entry[]>, size: number): PositionIndex {
|
||||
/** Rightmost entry at or before `upper` whose range still contains the point. */
|
||||
function findLastContainingEntry(
|
||||
file: FileIndex,
|
||||
upper: number,
|
||||
line: number,
|
||||
col: number,
|
||||
): number {
|
||||
// Depth-first, right subtree before left, so the first leaf reached is the rightmost.
|
||||
const stack: [node: number, first: number, last: number][] = [[1, 0, file.entries.length - 1]];
|
||||
while (stack.length > 0) {
|
||||
const [node, first, last] = stack.pop()!;
|
||||
if (first > upper || !endIsAtOrAfter(file.maximumEnds[node]!, line, col)) continue;
|
||||
if (first === last) return first;
|
||||
const middle = (first + last) >>> 1;
|
||||
stack.push([node * 2, first, middle]);
|
||||
if (upper > middle) stack.push([node * 2 + 1, middle + 1, last]);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function wrapIndex(files: ReadonlyMap<string, FileIndex>, size: number): PositionIndex {
|
||||
return {
|
||||
get size() {
|
||||
return size;
|
||||
},
|
||||
atPosition(filePath: string, line: number, col: number): ScopeId | undefined {
|
||||
const bucket = entriesByFile.get(filePath);
|
||||
if (bucket === undefined || bucket.length === 0) return undefined;
|
||||
const file = files.get(filePath);
|
||||
if (file === undefined) return undefined;
|
||||
|
||||
const endIdx = findLastStartLteIndex(bucket, line, col);
|
||||
const endIdx = findLastStartLteIndex(file.entries, line, col);
|
||||
if (endIdx < 0) return undefined;
|
||||
// The innermost scope usually starts last; it is then the rightmost match.
|
||||
const latest = file.entries[endIdx];
|
||||
if (latest && endIsAtOrAfter(latest.range, line, col)) return latest.id;
|
||||
|
||||
// Scan backward; first containing hit is innermost (see file header).
|
||||
for (let i = endIdx; i >= 0; i--) {
|
||||
const entry = bucket[i]!;
|
||||
if (endIsAtOrAfter(entry.range, line, col)) {
|
||||
// `startIsAtOrBefore` is guaranteed true by the binary search.
|
||||
return entry.id;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
const match = findLastContainingEntry(file, endIdx, line, col);
|
||||
return match < 0 ? undefined : file.entries[match]!.id;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -716,6 +716,8 @@ export interface ScopeLookupPolicy {
|
|||
export interface NameLookupOptions {
|
||||
readonly skipEnclosingClasses?: boolean;
|
||||
readonly position?: SourcePosition;
|
||||
/** Keep source order across deferred scopes when locating the binding before a write. */
|
||||
readonly preservePosition?: boolean;
|
||||
readonly purpose?: LookupPurpose;
|
||||
}
|
||||
|
||||
|
|
|
|||
152
gitnexus/bench/lexical-binding-provenance/README.md
Normal file
152
gitnexus/bench/lexical-binding-provenance/README.md
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
# Lexical binding provenance benchmark
|
||||
|
||||
Run from `gitnexus/` after building the checkout under test:
|
||||
|
||||
```sh
|
||||
node --import tsx bench/lexical-binding-provenance/measure.cjs --check
|
||||
```
|
||||
|
||||
`BENCH_SOURCE_ROOT` selects another repository checkout. Each checkout needs its
|
||||
own built `gitnexus-shared` and worker output. `--output report.json` writes the
|
||||
full report; `--arm position-index` selects an arm; `--verify` checks semantics
|
||||
without timing and is useful while other tests are using the machine.
|
||||
|
||||
## Measurement protocol
|
||||
|
||||
The predeclared `duration-calibrated-v2` protocol in `baseline.json` uses a pilot,
|
||||
five warmup batches, fifteen measured batches, and three input sizes spanning 4×
|
||||
growth. This is a custom Node.js harness, not BenchmarkDotNet. Its 500 ms pilot
|
||||
target follows the [official BenchmarkDotNet iteration-time guidance](https://benchmarkdotnet.org/articles/guides/console-args.html).
|
||||
|
||||
The pilot tries 1, 2, 4, … invocations per batch until three consecutive batches
|
||||
at the same count each contain at least 500 ms of measured work. It fails after
|
||||
64 pilot batches or when 1,048,576 invocations cannot meet the target. That count
|
||||
then remains fixed for all five warmup and fifteen measured batches. Baseline
|
||||
and candidate calibrate independently using the same protocol; faster code can
|
||||
need more invocations to reach the target duration.
|
||||
|
||||
Every invocation creates a fresh index/context. Its input preparation runs
|
||||
outside its timing window, even within a batch. A sample is the batch's total
|
||||
measured work divided by its invocation count, so all reported summary times are
|
||||
per-operation averages. The standard deviation describes those batch averages,
|
||||
not the latency distribution of individual invocations. Reports retain every
|
||||
pilot, warmup, and measured batch's invocation count, measured work, and wall
|
||||
time, as well as every normalized sample. No outliers are removed and no measured
|
||||
batches are retried to obtain a passing result.
|
||||
|
||||
The prior single-operation protocol produced millisecond-scale samples with
|
||||
large runtime transients. Its failed reports remain evidence; they must not be
|
||||
mixed with v2 measurements. A protocol change requires rerunning both revisions.
|
||||
Only relative scaling is gated, so results do not depend on a particular CPU's
|
||||
absolute speed. For both the minimum and median, the normalized factor is:
|
||||
|
||||
```text
|
||||
(larger time / smaller time) / (larger units / smaller units)
|
||||
```
|
||||
|
||||
Both 2× and 4× comparisons must be at most 1.8. The ceiling is fixed before the
|
||||
candidate measurements; a failure requires investigation rather than a wider
|
||||
ceiling. These measurements bound behavior on the generated workloads; they do
|
||||
not prove an asymptotic bound for arbitrary source programs. Prefer an idle host
|
||||
without concurrent builds, tests, or indexing. Alternatively, pin both benchmark
|
||||
processes to the same dedicated CPU and partition other work onto disjoint CPUs,
|
||||
using identical conditions for baseline and candidate. CPU affinity does not
|
||||
isolate shared caches or memory bandwidth, so disclose concurrent work and retain
|
||||
the full sample distributions. Linux reports include the process's exact
|
||||
`Cpus_allowed_list` as `environment.allowedCpus`; `BENCH_ENVIRONMENT_NOTE` adds an
|
||||
explicit note to the report, for example:
|
||||
|
||||
```sh
|
||||
BENCH_ENVIRONMENT_NOTE='Benchmark CPU 7; native integration suite restricted to CPUs 0-3; caches and memory bandwidth shared' \
|
||||
taskset -c 7 node --import tsx bench/lexical-binding-provenance/measure.cjs --check
|
||||
```
|
||||
|
||||
Parsing and `ParsedFile` creation happen outside extraction timing. The operation
|
||||
under test creates its indexes on every measured invocation. Wrapper extraction
|
||||
also gets a fresh AST for each invocation, prepared outside timing; this prevents
|
||||
the historical module WeakMap from hiding index construction in the baseline.
|
||||
Correctness checks run before timing and on the final result. They and the
|
||||
fingerprints remain outside timing. Returning no facts cannot pass.
|
||||
|
||||
| Arm | Sizes | Measured operation | Exact semantic guard |
|
||||
| ------------------------- | --------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------- |
|
||||
| `position-index` | 2,000 / 4,000 / 8,000 | Build index, then N outer reads after N completed siblings | Every read returns root |
|
||||
| `position-deep-completed` | 2,000 / 4,000 / 8,000 | Build index, then N reads after N completed nested scopes | Every read returns root |
|
||||
| `spread-aliases` | 128 / 256 / 512 | Fresh framework extraction across N functions | N exact GET paths |
|
||||
| `completed-scopes` | 128 / 256 / 512 | Fresh extraction of N outer reads after N completed functions | N exact GET paths |
|
||||
| `wrapper-aliases` | 128 / 256 / 512 | Fresh wrapper context, all definition facts and call candidates | N seeds, URL carriers, exact call/path identities |
|
||||
| `nested-helpers` | 128 / 256 / 512 | All facts for N reachable sibling helpers and their outer function | N+1 seeds, one URL carrier |
|
||||
| `nested-helper-chain` | 32 / 64 / 128 | All facts for deeply nested reachable helpers | N+1 seeds, one URL carrier |
|
||||
| `reverse-chain` | 1,000 / 2,000 / 4,000 | Fresh classifier with seed last, then N decisions | Every chain node matches |
|
||||
| `name-collisions` | 1,000 / 2,000 / 4,000 | Fresh classifier with N same-name definitions, half negative | Exact bound decisions, unresolved name rejected, unique positive retained |
|
||||
|
||||
The deep helper sizes keep parser/model setup practical while still exposing
|
||||
repeated descendant work. Parsing costs are not included in these measurements.
|
||||
The classifier arms include index construction and all call decisions; they do
|
||||
not include filesystem or route extraction overhead.
|
||||
|
||||
The baseline predates the classifier factory. `baseline-closure.cjs` reproduces
|
||||
the historical closure algorithm only for the pinned `routes.ts` SHA-256; it
|
||||
refuses other source revisions. The candidate calls the production factory.
|
||||
The collision workload records the baseline's known false positive explicitly
|
||||
as `known-baseline-failure`; those rows are not semantically equivalent to the
|
||||
candidate and cannot pass `--check`. Other workload fingerprints must agree.
|
||||
Reports record the adapter, revision, dirty flag, source hashes, and harness
|
||||
fingerprint so a dirty candidate is never presented as a clean commit result.
|
||||
|
||||
## Exact call graph comparison
|
||||
|
||||
Prepare the corpus once before changing production code, then use that same
|
||||
directory for the baseline and candidate exports:
|
||||
|
||||
```sh
|
||||
node --import tsx bench/lexical-binding-provenance/edges.mjs \
|
||||
--prepare-corpus /tmp/binding-corpus
|
||||
BENCH_SOURCE_ROOT=/path/to/baseline-checkout node --import tsx \
|
||||
bench/lexical-binding-provenance/edges.mjs \
|
||||
--corpus /tmp/binding-corpus --output /tmp/baseline-edges.json
|
||||
node --import tsx bench/lexical-binding-provenance/edges.mjs \
|
||||
--corpus /tmp/binding-corpus --output /tmp/candidate-edges.json
|
||||
node --import tsx bench/lexical-binding-provenance/edges.mjs \
|
||||
--compare /tmp/baseline-edges.json --candidate /tmp/candidate-edges.json \
|
||||
--note 'why the reviewed call-target changes are expected' \
|
||||
--output /tmp/edge-diff.json
|
||||
```
|
||||
|
||||
The frozen corpus contains all TS/JS source files from the
|
||||
`test/fixtures/lang-resolution` fixture groups that contain those languages,
|
||||
their JSON/YAML configuration, and the targeted binding ownership probe here.
|
||||
The actual ingestion pipeline runs with MRO enabled; only derived community and
|
||||
process extraction is skipped. Each export records the git revision, every input
|
||||
file's hash, corpus fingerprint, and sorted `CALLS` and `METHOD_OVERRIDES` edge
|
||||
arrays. Edge records retain `id`, `sourceId`, `targetId`, and readable source and
|
||||
target names, paths, and lines. Arrays preserve graph-edge multiplicity.
|
||||
|
||||
The report also records both exports' revisions, dirty flags and fingerprints,
|
||||
the unchanged edge counts, and the `--note` review explanation.
|
||||
Comparison refuses different corpus manifests, exports from dirty checkouts, and
|
||||
a candidate export whose revision is not the checkout running the comparison. It
|
||||
always fails if an override
|
||||
edge changes. Every added/removed call edge is written in full for review. Add
|
||||
`--check` when zero call changes are expected; the ownership fix intentionally
|
||||
changes the annotated closure probe's target, so its first comparison requires
|
||||
reviewing that exact delta rather than blessing aggregate counts.
|
||||
|
||||
The captured pre-fix revision is `565e50276dc9aa4e3b6e36dfabe8a92571b0d699`:
|
||||
117 fixture groups, 432 input files, 432 `CALLS`, and 11 `METHOD_OVERRIDES`.
|
||||
Corpus SHA-256:
|
||||
`88be1faf45e9aec145f9d168b8959d67f31ec3b09b5455e9c8d8b2b1681ade5a`.
|
||||
|
||||
The final corpus differs from the first capture only in formatting of the
|
||||
standalone ownership probe. Both final exports use this identical corpus and
|
||||
the baseline remains the untouched revision above.
|
||||
|
||||
## Committed results
|
||||
|
||||
`results/baseline-scaling.json`, `results/candidate-scaling.json` and
|
||||
`results/semantic-diff.json` are point-in-time reports. Each records the revision
|
||||
it measured (`source.revision`, or the export revisions in the comparison), so a
|
||||
later commit that changes no measured file keeps them valid. Regenerate all three
|
||||
with the commands above after changing a measured file. Host load during a run is
|
||||
described only by the report's environment note; any sampled load log stays with
|
||||
the operator.
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
/**
|
||||
* Benchmark-only adapter for routes.ts at 565e502. Keep the historical bucket
|
||||
* copying and repeated scans: those are the costs this benchmark compares.
|
||||
* The source hash prevents silently applying this adapter to another baseline.
|
||||
*/
|
||||
const assert = require('node:assert/strict');
|
||||
const { createHash } = require('node:crypto');
|
||||
const { readFileSync } = require('node:fs');
|
||||
const { join } = require('node:path');
|
||||
|
||||
const SOURCE_HASH = '0ad2c5cebf550a6e0b25c52f6edaa1ea268f0fc138156616f179ef620d1a912e';
|
||||
const moduleStem = (filePath) => filePath.replace(/\.[cm]?[jt]sx?$/, '').replace(/\/index$/, '');
|
||||
|
||||
function loadBaselineClosure(sourceRoot) {
|
||||
const source = readFileSync(join(sourceRoot, 'src/core/ingestion/pipeline-phases/routes.ts'));
|
||||
assert.equal(
|
||||
createHash('sha256').update(source).digest('hex'),
|
||||
SOURCE_HASH,
|
||||
'the legacy classifier adapter only matches the pinned pre-fix routes.ts',
|
||||
);
|
||||
return (wrapperDefs, configuredWrappers = []) => {
|
||||
const wrapperNames = new Set([
|
||||
...wrapperDefs.filter((d) => d.seed).map((d) => d.functionName),
|
||||
...configuredWrappers,
|
||||
]);
|
||||
const carriers = new Set(wrapperDefs.filter((d) => d.forwardsUrl));
|
||||
const defsByName = new Map();
|
||||
const defsByModule = new Map();
|
||||
for (const def of wrapperDefs) {
|
||||
const key = `${moduleStem(def.filePath)}\0${def.functionName}`;
|
||||
defsByName.set(def.functionName, [...(defsByName.get(def.functionName) ?? []), def]);
|
||||
defsByModule.set(key, [...(defsByModule.get(key) ?? []), def]);
|
||||
}
|
||||
const carriesUrl = ({ callee, module }) =>
|
||||
configuredWrappers.includes(callee) ||
|
||||
(module === null
|
||||
? (defsByName.get(callee)?.every((def) => carriers.has(def)) ?? false)
|
||||
: (defsByModule.get(`${module}\0${callee}`)?.some((def) => carriers.has(def)) ?? false));
|
||||
for (let grew = true; grew; ) {
|
||||
grew = false;
|
||||
for (const def of wrapperDefs) {
|
||||
if (carriers.has(def) || !def.forwardsTo.some(carriesUrl)) continue;
|
||||
carriers.add(def);
|
||||
wrapperNames.add(def.functionName);
|
||||
grew = true;
|
||||
}
|
||||
}
|
||||
return {
|
||||
isWrapperCall: ({ functionName, module, declaredName }) =>
|
||||
configuredWrappers.includes(functionName) ||
|
||||
(module === undefined
|
||||
? wrapperNames.has(functionName)
|
||||
: (defsByModule
|
||||
.get(`${module}\0${declaredName ?? functionName}`)
|
||||
?.some((def) => def.seed || carriers.has(def)) ?? false)),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { loadBaselineClosure, moduleStem };
|
||||
14
gitnexus/bench/lexical-binding-provenance/baseline.json
Normal file
14
gitnexus/bench/lexical-binding-provenance/baseline.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"protocol": "duration-calibrated-v2",
|
||||
"targetIterationMs": 500,
|
||||
"pilotConfirmationBatches": 3,
|
||||
"maxPilotIterations": 64,
|
||||
"maxInvocationsPerIteration": 1048576,
|
||||
"warmup": 5,
|
||||
"repetitions": 15,
|
||||
"sizes": [128, 256, 512],
|
||||
"lookupSizes": [2000, 4000, 8000],
|
||||
"closureSizes": [1000, 2000, 4000],
|
||||
"deepHelperSizes": [32, 64, 128],
|
||||
"linearScalingBudget": 1.8
|
||||
}
|
||||
247
gitnexus/bench/lexical-binding-provenance/edges.mjs
Normal file
247
gitnexus/bench/lexical-binding-provenance/edges.mjs
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
#!/usr/bin/env node
|
||||
/** Export or compare exact CALLS/METHOD_OVERRIDES multisets on a frozen corpus. */
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO = path.resolve(HERE, '../../..');
|
||||
const SOURCE = path.resolve(process.env.BENCH_SOURCE_ROOT ?? REPO);
|
||||
const args = process.argv.slice(2);
|
||||
const option = (name) => {
|
||||
const at = args.indexOf(name);
|
||||
if (at === -1) return undefined;
|
||||
assert.ok(args[at + 1] && !args[at + 1].startsWith('--'), `${name} requires a value`);
|
||||
return args[at + 1];
|
||||
};
|
||||
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
||||
const canonical = (edge) => JSON.stringify(edge);
|
||||
const compareText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
||||
|
||||
function filesUnder(root) {
|
||||
const files = [];
|
||||
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
||||
const file = path.join(root, entry.name);
|
||||
if (entry.isDirectory()) files.push(...filesUnder(file));
|
||||
else if (entry.isFile()) files.push(file);
|
||||
}
|
||||
return files.sort(compareText);
|
||||
}
|
||||
|
||||
function corpusManifest(root) {
|
||||
return filesUnder(root).map((file) => ({
|
||||
path: path.relative(root, file).split(path.sep).join('/'),
|
||||
sha256: hash(fs.readFileSync(file)),
|
||||
}));
|
||||
}
|
||||
|
||||
function prepareCorpus(destination) {
|
||||
assert.equal(fs.existsSync(destination), false, 'refusing to replace an existing corpus');
|
||||
const fixtures = path.join(REPO, 'gitnexus/test/fixtures/lang-resolution');
|
||||
const fixtureFiles = filesUnder(fixtures);
|
||||
const code = fixtureFiles.filter((file) => /\.[cm]?[jt]sx?$/.test(file));
|
||||
const selectedRoots = new Set(
|
||||
code.map((file) => path.relative(fixtures, file).split(path.sep)[0]),
|
||||
);
|
||||
fs.mkdirSync(destination, { recursive: true });
|
||||
for (const file of fixtureFiles) {
|
||||
const relative = path.relative(fixtures, file);
|
||||
if (!selectedRoots.has(relative.split(path.sep)[0])) continue;
|
||||
// Include configuration and other support files only in fixtures containing
|
||||
// TS/JS. Other source languages are excluded from this exact comparison.
|
||||
if (!/\.[cm]?[jt]sx?$/.test(file) && !/\.(?:json|jsonc|yaml|yml)$/.test(file)) continue;
|
||||
const target = path.join(destination, relative);
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.copyFileSync(file, target);
|
||||
}
|
||||
const probes = path.join(HERE, 'fixtures');
|
||||
if (fs.existsSync(probes))
|
||||
fs.cpSync(probes, path.join(destination, 'binding-provenance'), { recursive: true });
|
||||
return { files: corpusManifest(destination), fixtureCount: selectedRoots.size };
|
||||
}
|
||||
|
||||
function nodeIdentity(graph, id) {
|
||||
const node = graph.getNode(id);
|
||||
assert.ok(node, `edge references missing node ${id}`);
|
||||
return {
|
||||
label: node.label,
|
||||
filePath: node.properties.filePath ?? null,
|
||||
name: node.properties.name ?? null,
|
||||
startLine: node.properties.startLine ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function exportEdges(corpus, destination) {
|
||||
const manifest = corpusManifest(corpus);
|
||||
assert.ok(
|
||||
manifest.some((file) => /\.[cm]?[jt]sx?$/.test(file.path)),
|
||||
'empty TS/JS corpus',
|
||||
);
|
||||
const { runPipelineFromRepo } = await import(
|
||||
pathToFileURL(path.join(SOURCE, 'gitnexus/src/core/ingestion/pipeline.ts')).href
|
||||
);
|
||||
const result = await runPipelineFromRepo(corpus, () => {}, {
|
||||
workerPoolSize: 2,
|
||||
skipDerivedGraphPhases: true,
|
||||
});
|
||||
const keyedEdges = [];
|
||||
for (const edge of result.graph.iterRelationships()) {
|
||||
if (edge.type !== 'CALLS' && edge.type !== 'METHOD_OVERRIDES') continue;
|
||||
const identity = {
|
||||
type: edge.type,
|
||||
id: edge.id,
|
||||
sourceId: edge.sourceId,
|
||||
targetId: edge.targetId,
|
||||
source: nodeIdentity(result.graph, edge.sourceId),
|
||||
target: nodeIdentity(result.graph, edge.targetId),
|
||||
};
|
||||
keyedEdges.push({ edge: identity, key: canonical(identity) });
|
||||
}
|
||||
keyedEdges.sort((a, b) => compareText(a.key, b.key));
|
||||
const edges = keyedEdges.map(({ edge }) => edge);
|
||||
assert.ok(
|
||||
edges.some((edge) => edge.type === 'CALLS'),
|
||||
'pipeline produced no CALLS edges',
|
||||
);
|
||||
assert.ok(
|
||||
edges.some((edge) => edge.type === 'METHOD_OVERRIDES'),
|
||||
'pipeline produced no override edges',
|
||||
);
|
||||
// Arrays deliberately preserve multiplicity; a Set would hide duplicate edges.
|
||||
const output = {
|
||||
schema: 1,
|
||||
revision: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: SOURCE, encoding: 'utf8' }).trim(),
|
||||
dirty:
|
||||
execFileSync('git', ['status', '--porcelain'], { cwd: SOURCE, encoding: 'utf8' }).trim()
|
||||
.length > 0,
|
||||
nodeVersion: process.version,
|
||||
corpusFingerprint: hash(JSON.stringify(manifest)),
|
||||
manifest,
|
||||
counts: Object.fromEntries(
|
||||
['CALLS', 'METHOD_OVERRIDES'].map((type) => [
|
||||
type,
|
||||
edges.filter((edge) => edge.type === type).length,
|
||||
]),
|
||||
),
|
||||
fingerprint: hash(keyedEdges.map(({ key }) => key).join('\n')),
|
||||
edges,
|
||||
};
|
||||
fs.writeFileSync(destination, `${JSON.stringify(output, null, 2)}\n`);
|
||||
console.error(
|
||||
JSON.stringify(
|
||||
{
|
||||
revision: output.revision,
|
||||
corpusFingerprint: output.corpusFingerprint,
|
||||
counts: output.counts,
|
||||
fingerprint: output.fingerprint,
|
||||
destination,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function multisetDifference(before, after) {
|
||||
const counts = new Map();
|
||||
for (const edge of before) {
|
||||
const key = canonical(edge);
|
||||
const entry = counts.get(key) ?? { edge, count: 0 };
|
||||
entry.count++;
|
||||
counts.set(key, entry);
|
||||
}
|
||||
const added = [];
|
||||
for (const edge of after) {
|
||||
const entry = counts.get(canonical(edge));
|
||||
if (entry?.count) entry.count--;
|
||||
else added.push(edge);
|
||||
}
|
||||
const removed = [...counts.values()].flatMap(({ edge, count }) =>
|
||||
Array.from({ length: count }, () => edge),
|
||||
);
|
||||
return { removed, added };
|
||||
}
|
||||
|
||||
const prepare = option('--prepare-corpus');
|
||||
const compare = option('--compare');
|
||||
const output = option('--output');
|
||||
if (prepare) {
|
||||
const result = prepareCorpus(path.resolve(prepare));
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
fixtureCount: result.fixtureCount,
|
||||
files: result.files.length,
|
||||
corpusFingerprint: hash(JSON.stringify(result.files)),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
} else if (compare) {
|
||||
const candidate = option('--candidate');
|
||||
assert.ok(candidate, '--compare requires --candidate');
|
||||
const before = JSON.parse(fs.readFileSync(compare, 'utf8'));
|
||||
const after = JSON.parse(fs.readFileSync(candidate, 'utf8'));
|
||||
assert.equal(
|
||||
after.corpusFingerprint,
|
||||
before.corpusFingerprint,
|
||||
'corpora differ; comparison is invalid',
|
||||
);
|
||||
assert.deepEqual(after.manifest, before.manifest, 'corpus file identities differ');
|
||||
// Parity evidence holds only for clean exports and for the checkout under review.
|
||||
assert.equal(before.dirty, false, 'baseline export came from a dirty checkout');
|
||||
assert.equal(after.dirty, false, 'candidate export came from a dirty checkout');
|
||||
assert.equal(
|
||||
after.revision,
|
||||
execFileSync('git', ['rev-parse', 'HEAD'], { cwd: SOURCE, encoding: 'utf8' }).trim(),
|
||||
'candidate export does not come from the current checkout',
|
||||
);
|
||||
const difference = multisetDifference(before.edges, after.edges);
|
||||
const unchanged = (type) =>
|
||||
before.counts[type] - difference.removed.filter((edge) => edge.type === type).length;
|
||||
const exportSummary = ({ revision, dirty, corpusFingerprint, fingerprint }) => ({
|
||||
revision,
|
||||
dirty,
|
||||
corpusFingerprint,
|
||||
fingerprint,
|
||||
});
|
||||
const note = option('--note');
|
||||
const report = {
|
||||
baselineRevision: before.revision,
|
||||
candidateRevision: after.revision,
|
||||
corpusFingerprint: before.corpusFingerprint,
|
||||
counts: { baseline: before.counts, candidate: after.counts },
|
||||
...difference,
|
||||
review: {
|
||||
...(note ? { expectedCallTargetChange: note } : {}),
|
||||
unchangedCalls: unchanged('CALLS'),
|
||||
unchangedMethodOverrides: unchanged('METHOD_OVERRIDES'),
|
||||
},
|
||||
baselineExport: exportSummary(before),
|
||||
candidateExport: exportSummary(after),
|
||||
};
|
||||
const text = `${JSON.stringify(report, null, 2)}\n`;
|
||||
if (output) fs.writeFileSync(output, text);
|
||||
else process.stdout.write(text);
|
||||
const overrideDeltas = [...difference.removed, ...difference.added].filter(
|
||||
(edge) => edge.type === 'METHOD_OVERRIDES',
|
||||
);
|
||||
assert.equal(overrideDeltas.length, 0, 'METHOD_OVERRIDES changed');
|
||||
if (args.includes('--check'))
|
||||
assert.equal(
|
||||
difference.removed.length + difference.added.length,
|
||||
0,
|
||||
'CALLS changed; inspect every exact site/target delta',
|
||||
);
|
||||
} else {
|
||||
const corpus = option('--corpus');
|
||||
assert.ok(
|
||||
corpus && output,
|
||||
'use --prepare-corpus DIR, --corpus DIR --output FILE, or --compare BASELINE --candidate CANDIDATE [--output FILE] [--note TEXT] [--check]',
|
||||
);
|
||||
await exportEdges(path.resolve(corpus), path.resolve(output));
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
export class Base {
|
||||
m() {
|
||||
return 'base';
|
||||
}
|
||||
}
|
||||
export class Foo extends Base {
|
||||
override m() {
|
||||
return 'foo';
|
||||
}
|
||||
}
|
||||
export function declaredOwner(a: Base) {
|
||||
function writeAndRead() {
|
||||
a = new Foo();
|
||||
a.m();
|
||||
}
|
||||
writeAndRead();
|
||||
a.m();
|
||||
}
|
||||
export function inferredOwner() {
|
||||
let a = new Base();
|
||||
function writeAndRead() {
|
||||
a = new Foo();
|
||||
a.m();
|
||||
}
|
||||
writeAndRead();
|
||||
a.m();
|
||||
}
|
||||
export function directConstructor() {
|
||||
const a = new Foo();
|
||||
a.m();
|
||||
}
|
||||
558
gitnexus/bench/lexical-binding-provenance/measure.cjs
Normal file
558
gitnexus/bench/lexical-binding-provenance/measure.cjs
Normal file
|
|
@ -0,0 +1,558 @@
|
|||
#!/usr/bin/env node
|
||||
/** Fresh-context extraction and wrapper-propagation scaling benchmark (#3630). */
|
||||
const assert = require('node:assert/strict');
|
||||
const { createHash } = require('node:crypto');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { existsSync, readFileSync, writeFileSync } = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const { join, resolve } = require('node:path');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
const { loadBaselineClosure, moduleStem } = require('./baseline-closure.cjs');
|
||||
|
||||
const ROOT = resolve(__dirname, '../../..');
|
||||
const SOURCE = resolve(process.env.BENCH_SOURCE_ROOT ?? ROOT, 'gitnexus');
|
||||
const SETTINGS = JSON.parse(readFileSync(join(__dirname, 'baseline.json'), 'utf8'));
|
||||
const FILE = 'bench.ts';
|
||||
const hash = (identities) =>
|
||||
createHash('sha256')
|
||||
.update([...identities].sort().join('\n'))
|
||||
.digest('hex');
|
||||
const load = (file) => import(pathToFileURL(join(SOURCE, 'src', file)).href);
|
||||
const args = process.argv.slice(2);
|
||||
const check = args.includes('--check');
|
||||
const verifyOnly = args.includes('--verify');
|
||||
const armIndex = args.indexOf('--arm');
|
||||
const selected = armIndex < 0 ? undefined : args[armIndex + 1];
|
||||
|
||||
function environmentMetadata() {
|
||||
let allowedCpus;
|
||||
if (process.platform === 'linux') {
|
||||
try {
|
||||
allowedCpus = readFileSync('/proc/self/status', 'utf8')
|
||||
.match(/^Cpus_allowed_list:\s*(.+)$/m)?.[1]
|
||||
.trim();
|
||||
} catch {
|
||||
// /proc can be unavailable in otherwise valid Linux environments.
|
||||
}
|
||||
}
|
||||
return {
|
||||
node: process.version,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
cpu: os.cpus()[0]?.model,
|
||||
cpuCount: os.cpus().length,
|
||||
...(allowedCpus === undefined ? {} : { allowedCpus }),
|
||||
...(process.env.BENCH_ENVIRONMENT_NOTE ? { note: process.env.BENCH_ENVIRONMENT_NOTE } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function sourceMetadata() {
|
||||
const revision = execFileSync('git', ['rev-parse', 'HEAD'], {
|
||||
cwd: SOURCE,
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
const status = execFileSync('git', ['status', '--porcelain'], { cwd: SOURCE, encoding: 'utf8' });
|
||||
const files = [
|
||||
'../gitnexus-shared/src/scope-resolution/position-index.ts',
|
||||
'../gitnexus-shared/src/scope-resolution/name-claims.ts',
|
||||
'src/core/ingestion/route-extractors/fetch-wrapper.ts',
|
||||
'src/core/ingestion/route-extractors/fetch-wrapper-index.ts',
|
||||
'src/core/ingestion/route-extractors/framework-route-facts.ts',
|
||||
'src/core/ingestion/route-extractors/lexical-bindings.ts',
|
||||
'src/core/ingestion/pipeline-phases/routes.ts',
|
||||
];
|
||||
return {
|
||||
revision,
|
||||
dirty: status.trim().length > 0,
|
||||
measuredSourceHashes: Object.fromEntries(
|
||||
files
|
||||
.filter((file) => existsSync(join(SOURCE, file)))
|
||||
.map((file) => [
|
||||
file,
|
||||
createHash('sha256')
|
||||
.update(readFileSync(join(SOURCE, file)))
|
||||
.digest('hex'),
|
||||
]),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function sample(run, verify, prepare = () => undefined) {
|
||||
const initial = run(prepare());
|
||||
verify(initial);
|
||||
if (verifyOnly) return { last: initial };
|
||||
let last;
|
||||
const iteration = (invocations) => {
|
||||
const wallStart = performance.now();
|
||||
let workMs = 0;
|
||||
for (let i = 0; i < invocations; i++) {
|
||||
// Setup is deliberately outside each operation's timing window. Each run
|
||||
// still creates a fresh index/context; batching never reuses that state.
|
||||
const input = prepare();
|
||||
const start = performance.now();
|
||||
last = run(input);
|
||||
workMs += performance.now() - start;
|
||||
}
|
||||
return { invocations, workMs, wallMs: performance.now() - wallStart };
|
||||
};
|
||||
const pilotIterations = [];
|
||||
let invocations = 1;
|
||||
let confirmations = 0;
|
||||
for (let i = 0; i < SETTINGS.maxPilotIterations; i++) {
|
||||
const pilot = iteration(invocations);
|
||||
const qualified = pilot.workMs >= SETTINGS.targetIterationMs;
|
||||
pilotIterations.push({ ...pilot, qualified });
|
||||
if (qualified) {
|
||||
confirmations++;
|
||||
if (confirmations === SETTINGS.pilotConfirmationBatches) break;
|
||||
} else {
|
||||
confirmations = 0;
|
||||
if (invocations >= SETTINGS.maxInvocationsPerIteration) break;
|
||||
invocations *= 2;
|
||||
}
|
||||
}
|
||||
if (confirmations !== SETTINGS.pilotConfirmationBatches) {
|
||||
throw Object.assign(new Error('Duration calibration exhausted its bounded pilot budget'), {
|
||||
targetIterationMs: SETTINGS.targetIterationMs,
|
||||
pilotIterations,
|
||||
});
|
||||
}
|
||||
// The pilot chooses the count once. Warmup and measured iterations retain the
|
||||
// same count, and every measurement is kept; there is no retry-until-pass path.
|
||||
const warmupIterations = Array.from({ length: SETTINGS.warmup }, () => iteration(invocations));
|
||||
const measuredIterations = Array.from({ length: SETTINGS.repetitions }, () =>
|
||||
iteration(invocations),
|
||||
);
|
||||
const samples = measuredIterations.map(({ workMs }) => workMs / invocations);
|
||||
const sorted = [...samples].sort((a, b) => a - b);
|
||||
const mean = samples.reduce((a, b) => a + b, 0) / samples.length;
|
||||
const deviation = Math.sqrt(
|
||||
samples.reduce((sum, ms) => sum + (ms - mean) ** 2, 0) / (samples.length - 1),
|
||||
);
|
||||
verify(last);
|
||||
return {
|
||||
last,
|
||||
timing: {
|
||||
invocationsPerIteration: invocations,
|
||||
pilotIterations,
|
||||
warmupIterations,
|
||||
measuredIterations,
|
||||
minMs: sorted[0],
|
||||
meanMs: mean,
|
||||
medianMs: sorted[Math.floor(sorted.length / 2)],
|
||||
standardDeviationMs: deviation,
|
||||
samplesMs: samples,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function wrapperSource(shape, units) {
|
||||
const lines = [];
|
||||
if (shape === 'wrapper-aliases') {
|
||||
for (let i = 0; i < units; i++) {
|
||||
lines.push(`function wrapper${i}(url) { const send = globalThis.fetch; return send(url); }`);
|
||||
lines.push(`wrapper${i}('/route-${i}');`);
|
||||
}
|
||||
} else if (shape === 'nested-helper-chain') {
|
||||
lines.push('function outer(url) {');
|
||||
for (let i = 0; i < units; i++) lines.push(`function helper${i}() {`);
|
||||
lines.push('return fetch(url);');
|
||||
for (let i = units - 1; i >= 0; i--) lines.push('}', `helper${i}();`);
|
||||
lines.push('}', "outer('/nested');");
|
||||
} else {
|
||||
lines.push('function outer(url) {');
|
||||
for (let i = 0; i < units; i++) lines.push(`function helper${i}() { return fetch(url); }`);
|
||||
for (let i = 0; i < units; i++) lines.push(`helper${i}();`);
|
||||
lines.push('}', "outer('/nested');");
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function closureWorkload(shape, units) {
|
||||
const defs = [];
|
||||
const calls = [];
|
||||
const expected = [];
|
||||
const addDefinition = (name, filePath, seed, target) => {
|
||||
const bindingId = `${filePath}\0${name}`;
|
||||
const def = {
|
||||
filePath,
|
||||
functionName: name,
|
||||
definitionId: `definition:${bindingId}`,
|
||||
bindingId,
|
||||
moduleScope: true,
|
||||
exportedNames: [name],
|
||||
seed,
|
||||
forwardsUrl: seed,
|
||||
forwardsTo: target
|
||||
? [{ callee: target.name, target: { kind: 'binding', bindingId: target.bindingId } }]
|
||||
: [],
|
||||
};
|
||||
defs.push(def);
|
||||
return def;
|
||||
};
|
||||
const addCall = (def, matches) => {
|
||||
calls.push({
|
||||
filePath: def.filePath,
|
||||
functionName: def.functionName,
|
||||
target: { kind: 'binding', bindingId: def.bindingId },
|
||||
});
|
||||
expected.push(matches);
|
||||
};
|
||||
if (shape === 'reverse-chain') {
|
||||
// The seed comes last: a repeated forward scan grows by only one node per
|
||||
// pass. A reverse-dependency queue touches each edge once.
|
||||
for (let i = 0; i < units; i++) {
|
||||
const next =
|
||||
i + 1 < units
|
||||
? { name: `wrapper${i + 1}`, bindingId: `${FILE}\0wrapper${i + 1}` }
|
||||
: undefined;
|
||||
const def = addDefinition(`wrapper${i}`, FILE, !next, next);
|
||||
addCall(def, true);
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < units; i++) {
|
||||
const def = addDefinition('request', `modules/module${i}.ts`, i % 2 === 0);
|
||||
addCall(def, i % 2 === 0);
|
||||
}
|
||||
calls.push({ filePath: FILE, functionName: 'request', target: { kind: 'unresolved' } });
|
||||
expected.push(false);
|
||||
// A distinct positive control guards against a classifier that rejects all
|
||||
// names merely because the workload contains ambiguous declarations.
|
||||
addCall(addDefinition('uniqueRequest', FILE, true), true);
|
||||
}
|
||||
const byBinding = new Map(defs.map((def) => [def.bindingId, def]));
|
||||
const legacyDefs = defs.map((def) => ({
|
||||
...def,
|
||||
forwardsTo: def.forwardsTo.map(({ callee, target }) => ({
|
||||
callee,
|
||||
module: moduleStem(byBinding.get(target.bindingId).filePath),
|
||||
})),
|
||||
}));
|
||||
const legacyCalls = calls.map((call) => ({
|
||||
...call,
|
||||
...(call.target.kind === 'binding'
|
||||
? { module: moduleStem(byBinding.get(call.target.bindingId).filePath) }
|
||||
: {}),
|
||||
}));
|
||||
const legacyExpected = [...expected];
|
||||
if (shape === 'name-collisions') legacyExpected[units] = true;
|
||||
return { defs, calls, expected, legacyDefs, legacyCalls, legacyExpected };
|
||||
}
|
||||
|
||||
function frameworkSource(shape, units) {
|
||||
const lines = ["import express from 'express';", 'function handler() {}'];
|
||||
if (shape === 'completed-scopes') {
|
||||
lines.push('const app = express(); const alias = app;');
|
||||
for (let i = 0; i < units; i++) lines.push(`function done${i}(value) { return value; }`);
|
||||
for (let i = 0; i < units; i++) lines.push(`alias.get('/route-${i}', handler);`);
|
||||
} else {
|
||||
for (let i = 0; i < units; i++) {
|
||||
lines.push(
|
||||
`function setup${i}() { const app = express(); const alias = app; alias.get('/route-${i}', handler); }`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function ratios(rows) {
|
||||
const small = rows[0];
|
||||
return rows.slice(1).map((large) => ({
|
||||
fromUnits: small.units,
|
||||
toUnits: large.units,
|
||||
minLinearFactor: large.timing.minMs / small.timing.minMs / (large.units / small.units),
|
||||
medianLinearFactor: large.timing.medianMs / small.timing.medianMs / (large.units / small.units),
|
||||
}));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
assert.equal(SETTINGS.protocol, 'duration-calibrated-v2');
|
||||
assert.equal(SETTINGS.targetIterationMs, 500);
|
||||
assert.equal(SETTINGS.pilotConfirmationBatches, 3);
|
||||
assert.equal(SETTINGS.warmup, 5);
|
||||
assert.equal(SETTINGS.repetitions, 15);
|
||||
assert.ok(Number.isSafeInteger(SETTINGS.maxPilotIterations) && SETTINGS.maxPilotIterations >= 3);
|
||||
assert.ok(
|
||||
Number.isSafeInteger(SETTINGS.maxInvocationsPerIteration) &&
|
||||
SETTINGS.maxInvocationsPerIteration > 0 &&
|
||||
Number.isInteger(Math.log2(SETTINGS.maxInvocationsPerIteration)),
|
||||
);
|
||||
assert.ok(SETTINGS.sizes.length >= 3 && SETTINGS.sizes[2] / SETTINGS.sizes[0] >= 4);
|
||||
assert.equal(SETTINGS.linearScalingBudget, 1.8, 'keep the predeclared scaling ceiling');
|
||||
const [
|
||||
{ default: Parser },
|
||||
{ default: TypeScript },
|
||||
{ typescriptProvider },
|
||||
{ extractParsedFile },
|
||||
{ extractFrameworkRouteFacts },
|
||||
{ resolveFrameworkRouteFacts },
|
||||
{ buildPositionIndex },
|
||||
wrappers,
|
||||
] = await Promise.all([
|
||||
import('tree-sitter'),
|
||||
import('tree-sitter-typescript'),
|
||||
load('core/ingestion/languages/typescript.ts'),
|
||||
load('core/ingestion/scope-extractor-bridge.ts'),
|
||||
load('core/ingestion/route-extractors/framework-route-facts.ts'),
|
||||
load('core/ingestion/route-extractors/framework-route-resolver.ts'),
|
||||
import(
|
||||
pathToFileURL(join(SOURCE, '../gitnexus-shared/src/scope-resolution/position-index.ts')).href
|
||||
),
|
||||
load('core/ingestion/route-extractors/fetch-wrapper.ts'),
|
||||
]);
|
||||
const parser = new Parser();
|
||||
parser.setLanguage(TypeScript.typescript);
|
||||
const arms = {};
|
||||
for (const shape of ['position-index', 'position-deep-completed']) {
|
||||
if (selected && selected !== shape) continue;
|
||||
arms[shape] = SETTINGS.lookupSizes.map((units) => {
|
||||
const deep = shape === 'position-deep-completed';
|
||||
const queryStart = deep ? units * 2 + 2 : units + 2;
|
||||
const scopes = [
|
||||
{
|
||||
id: 'root',
|
||||
filePath: FILE,
|
||||
range: { startLine: 1, startCol: 0, endLine: queryStart + units + 1, endCol: 0 },
|
||||
},
|
||||
];
|
||||
for (let i = 0; i < units; i++) {
|
||||
scopes.push({
|
||||
id: `scope-${i}`,
|
||||
filePath: FILE,
|
||||
range: {
|
||||
startLine: i + 2,
|
||||
startCol: 0,
|
||||
endLine: deep ? units * 2 - i + 1 : i + 2,
|
||||
endCol: 10,
|
||||
},
|
||||
});
|
||||
}
|
||||
const { last, timing } = sample(
|
||||
() => {
|
||||
const index = buildPositionIndex(scopes);
|
||||
return Array.from({ length: units }, (_, i) => index.atPosition(FILE, queryStart + i, 0));
|
||||
},
|
||||
(result) =>
|
||||
assert.deepEqual(
|
||||
result,
|
||||
Array(units).fill('root'),
|
||||
`${shape}: completed scopes must resolve to the outer scope`,
|
||||
),
|
||||
);
|
||||
return {
|
||||
units,
|
||||
scopes: scopes.length,
|
||||
outerReads: last.length,
|
||||
fingerprint: hash(last),
|
||||
...(timing ? { timing } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
for (const shape of ['spread-aliases', 'completed-scopes']) {
|
||||
if (selected && selected !== shape) continue;
|
||||
arms[shape] = SETTINGS.sizes.map((units) => {
|
||||
const text = frameworkSource(shape, units);
|
||||
const tree = parser.parse(text, null, { bufferSize: Buffer.byteLength(text) + 1 });
|
||||
assert.equal(tree.rootNode.hasError, false, `${shape}: invalid benchmark source`);
|
||||
const parsed = extractParsedFile(typescriptProvider, text, FILE, undefined, tree);
|
||||
assert.ok(parsed, `${shape}: missing parsed file`);
|
||||
// Parsing/model construction is setup. The extractor builds fresh scope,
|
||||
// position and binding indexes on every timed invocation.
|
||||
const expected = Array.from({ length: units }, (_, i) => `GET /route-${i}`).sort();
|
||||
const verify = (facts) => {
|
||||
const resolved = resolveFrameworkRouteFacts([facts], () => []);
|
||||
const identities = resolved.registrations.map(
|
||||
({ route }) => `${route.httpMethod} ${route.routePath}`,
|
||||
);
|
||||
assert.deepEqual(identities.sort(), expected, `${shape}: exact route identities changed`);
|
||||
assert.ok(facts.calls.length >= units, `${shape}: missing positive call evidence`);
|
||||
};
|
||||
const { last, timing } = sample(() => extractFrameworkRouteFacts(tree, parsed), verify);
|
||||
const resolved = resolveFrameworkRouteFacts([last], () => []);
|
||||
const identities = resolved.registrations.map(
|
||||
({ route }) => `${route.httpMethod} ${route.routePath}`,
|
||||
);
|
||||
return {
|
||||
units,
|
||||
bytes: Buffer.byteLength(text),
|
||||
routes: identities.length,
|
||||
calls: last.calls.length,
|
||||
fingerprint: hash(identities),
|
||||
...(timing ? { timing } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
const contextAvailable = typeof wrappers.createFetchWrapperContext === 'function';
|
||||
for (const shape of ['wrapper-aliases', 'nested-helpers', 'nested-helper-chain']) {
|
||||
if (selected && selected !== shape) continue;
|
||||
const sizes = shape === 'nested-helper-chain' ? SETTINGS.deepHelperSizes : SETTINGS.sizes;
|
||||
arms[shape] = sizes.map((units) => {
|
||||
const text = wrapperSource(shape, units);
|
||||
const prepare = () => {
|
||||
const tree = parser.parse(text, null, { bufferSize: Buffer.byteLength(text) + 1 });
|
||||
assert.equal(tree.rootNode.hasError, false, `${shape}: invalid benchmark source`);
|
||||
const parsed = extractParsedFile(typescriptProvider, text, FILE, undefined, tree);
|
||||
assert.ok(parsed, `${shape}: missing parsed file`);
|
||||
return {
|
||||
tree,
|
||||
parsed,
|
||||
definitions: tree.rootNode.descendantsOfType('function_declaration'),
|
||||
};
|
||||
};
|
||||
const project = ({ facts, calls, definitions }) => ({
|
||||
facts: facts
|
||||
.map(
|
||||
(fact, i) =>
|
||||
`${definitions[i].childForFieldName('name').text}:${fact.seed}:${fact.forwardsUrl}`,
|
||||
)
|
||||
.sort(),
|
||||
calls: calls.map((call) => `${call.functionName}:${call.fetchURL}`).sort(),
|
||||
});
|
||||
const expected = {
|
||||
facts:
|
||||
shape === 'wrapper-aliases'
|
||||
? Array.from({ length: units }, (_, i) => `wrapper${i}:true:true`).sort()
|
||||
: [
|
||||
'outer:true:true',
|
||||
...Array.from({ length: units }, (_, i) => `helper${i}:true:false`),
|
||||
].sort(),
|
||||
calls:
|
||||
shape === 'wrapper-aliases'
|
||||
? Array.from({ length: units }, (_, i) => `wrapper${i}:/route-${i}`).sort()
|
||||
: ['outer:/nested'],
|
||||
};
|
||||
const run = contextAvailable
|
||||
? ({ tree, parsed, definitions }) => {
|
||||
const context = wrappers.createFetchWrapperContext(tree, parsed);
|
||||
return {
|
||||
definitions,
|
||||
facts: definitions.map((definition) =>
|
||||
context.facts(definition, definition.childForFieldName('name')),
|
||||
),
|
||||
calls: context.calls(),
|
||||
};
|
||||
}
|
||||
: ({ tree, definitions }) => ({
|
||||
definitions,
|
||||
facts: definitions.map((definition) => wrappers.fetchWrapperFacts(definition, FILE)),
|
||||
calls: wrappers.extractFetchWrapperCalls(tree, FILE, 0),
|
||||
});
|
||||
// A fresh AST per invocation prevents the baseline's module WeakMap cache
|
||||
// from turning this into a warm-index comparison. Parsing/capture setup
|
||||
// is excluded in both arms; context creation is included.
|
||||
const { last, timing } = sample(
|
||||
run,
|
||||
(result) =>
|
||||
assert.deepEqual(project(result), expected, `${shape}: wrapper evidence changed`),
|
||||
prepare,
|
||||
);
|
||||
const identities = project(last);
|
||||
return {
|
||||
units,
|
||||
bytes: Buffer.byteLength(text),
|
||||
definitions: last.facts.length,
|
||||
seeds: last.facts.filter((fact) => fact.seed).length,
|
||||
carriers: last.facts.filter((fact) => fact.forwardsUrl).length,
|
||||
calls: last.calls.length,
|
||||
fingerprint: hash([...identities.facts, ...identities.calls]),
|
||||
...(timing ? { timing } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
const classifierPath = 'core/ingestion/route-extractors/fetch-wrapper-index.ts';
|
||||
const classifierAvailable = existsSync(join(SOURCE, 'src', classifierPath));
|
||||
let classifier;
|
||||
if (!selected || ['reverse-chain', 'name-collisions'].includes(selected)) {
|
||||
classifier = classifierAvailable
|
||||
? (await load(classifierPath)).buildFetchWrapperIndex
|
||||
: loadBaselineClosure(SOURCE);
|
||||
assert.equal(typeof classifier, 'function', 'missing wrapper classifier');
|
||||
}
|
||||
for (const shape of ['reverse-chain', 'name-collisions']) {
|
||||
if (selected && selected !== shape) continue;
|
||||
arms[shape] = SETTINGS.closureSizes.map((units) => {
|
||||
const workload = closureWorkload(shape, units);
|
||||
const defs = classifierAvailable ? workload.defs : workload.legacyDefs;
|
||||
const calls = classifierAvailable ? workload.calls : workload.legacyCalls;
|
||||
const expected = classifierAvailable ? workload.expected : workload.legacyExpected;
|
||||
const { last, timing } = sample(
|
||||
() => {
|
||||
const index = classifier(defs, []);
|
||||
return calls.map((call) => index.isWrapperCall(call));
|
||||
},
|
||||
(result) => assert.deepEqual(result, expected, `${shape}: exact wrapper decisions changed`),
|
||||
);
|
||||
const divergences = last.flatMap((matches, i) =>
|
||||
matches === workload.expected[i]
|
||||
? []
|
||||
: [
|
||||
{
|
||||
index: i,
|
||||
functionName: calls[i].functionName,
|
||||
expected: workload.expected[i],
|
||||
actual: matches,
|
||||
},
|
||||
],
|
||||
);
|
||||
return {
|
||||
units,
|
||||
definitions: defs.length,
|
||||
calls: calls.length,
|
||||
matched: last.filter(Boolean).length,
|
||||
rejected: last.filter((matched) => !matched).length,
|
||||
fingerprint: hash(last.map((matches, i) => `${i}:${matches}`)),
|
||||
semanticStatus: divergences.length ? 'known-baseline-failure' : 'correct',
|
||||
divergences,
|
||||
...(timing ? { timing } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
assert.ok(Object.keys(arms).length > 0, `unknown benchmark arm: ${selected}`);
|
||||
const scaling = verifyOnly
|
||||
? undefined
|
||||
: Object.fromEntries(Object.entries(arms).map(([name, rows]) => [name, ratios(rows)]));
|
||||
const output = {
|
||||
source: sourceMetadata(),
|
||||
harnessFingerprint: hash(
|
||||
['measure.cjs', 'baseline-closure.cjs', 'baseline.json'].map((file) =>
|
||||
readFileSync(join(__dirname, file), 'utf8'),
|
||||
),
|
||||
),
|
||||
environment: environmentMetadata(),
|
||||
settings: SETTINGS,
|
||||
adapters: {
|
||||
extraction: contextAvailable ? 'fresh-provider-context' : 'baseline-per-definition',
|
||||
classification: classifierAvailable ? 'production-index' : 'pinned-baseline-closure',
|
||||
},
|
||||
arms,
|
||||
...(scaling ? { scaling } : {}),
|
||||
};
|
||||
const outputIndex = args.indexOf('--output');
|
||||
const text = `${JSON.stringify(output, null, 2)}\n`;
|
||||
if (outputIndex >= 0) writeFileSync(args[outputIndex + 1], text);
|
||||
else process.stdout.write(text);
|
||||
if (check && scaling) {
|
||||
for (const [arm, rows] of Object.entries(arms)) {
|
||||
assert.ok(
|
||||
rows.every((row) => !row.divergences?.length),
|
||||
`${arm}: known baseline semantic failure is not a passing candidate`,
|
||||
);
|
||||
}
|
||||
for (const [arm, comparisons] of Object.entries(scaling)) {
|
||||
for (const comparison of comparisons) {
|
||||
for (const metric of ['minLinearFactor', 'medianLinearFactor']) {
|
||||
assert.ok(
|
||||
comparison[metric] <= SETTINGS.linearScalingBudget,
|
||||
`${arm} ${comparison.fromUnits}->${comparison.toUnits} ` +
|
||||
`${metric}=${comparison[metric].toFixed(3)} exceeds ${SETTINGS.linearScalingBudget}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,72 @@
|
|||
{
|
||||
"baselineRevision": "565e50276dc9aa4e3b6e36dfabe8a92571b0d699",
|
||||
"candidateRevision": "c263c4f72089cb07ce1de9033f7aa6b564c914ce",
|
||||
"corpusFingerprint": "88be1faf45e9aec145f9d168b8959d67f31ec3b09b5455e9c8d8b2b1681ade5a",
|
||||
"counts": {
|
||||
"baseline": {
|
||||
"CALLS": 432,
|
||||
"METHOD_OVERRIDES": 11
|
||||
},
|
||||
"candidate": {
|
||||
"CALLS": 432,
|
||||
"METHOD_OVERRIDES": 11
|
||||
}
|
||||
},
|
||||
"removed": [
|
||||
{
|
||||
"type": "CALLS",
|
||||
"id": "rel:CALLS:Function:binding-provenance/ownership.ts:declaredOwner.writeAndRead@11:2->Method:binding-provenance/ownership.ts:Foo.m#0:14:4",
|
||||
"sourceId": "Function:binding-provenance/ownership.ts:declaredOwner.writeAndRead@11:2",
|
||||
"targetId": "Method:binding-provenance/ownership.ts:Foo.m#0",
|
||||
"source": {
|
||||
"label": "Function",
|
||||
"filePath": "binding-provenance/ownership.ts",
|
||||
"name": "writeAndRead",
|
||||
"startLine": 11
|
||||
},
|
||||
"target": {
|
||||
"label": "Method",
|
||||
"filePath": "binding-provenance/ownership.ts",
|
||||
"name": "m",
|
||||
"startLine": 6
|
||||
}
|
||||
}
|
||||
],
|
||||
"added": [
|
||||
{
|
||||
"type": "CALLS",
|
||||
"id": "rel:CALLS:Function:binding-provenance/ownership.ts:declaredOwner.writeAndRead@11:2->Method:binding-provenance/ownership.ts:Base.m#0:14:4",
|
||||
"sourceId": "Function:binding-provenance/ownership.ts:declaredOwner.writeAndRead@11:2",
|
||||
"targetId": "Method:binding-provenance/ownership.ts:Base.m#0",
|
||||
"source": {
|
||||
"label": "Function",
|
||||
"filePath": "binding-provenance/ownership.ts",
|
||||
"name": "writeAndRead",
|
||||
"startLine": 11
|
||||
},
|
||||
"target": {
|
||||
"label": "Method",
|
||||
"filePath": "binding-provenance/ownership.ts",
|
||||
"name": "m",
|
||||
"startLine": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"review": {
|
||||
"expectedCallTargetChange": "The declared Base annotation owns the closure receiver; a constructor assignment must not retarget it to Foo.",
|
||||
"unchangedCalls": 431,
|
||||
"unchangedMethodOverrides": 11
|
||||
},
|
||||
"baselineExport": {
|
||||
"revision": "565e50276dc9aa4e3b6e36dfabe8a92571b0d699",
|
||||
"dirty": false,
|
||||
"corpusFingerprint": "88be1faf45e9aec145f9d168b8959d67f31ec3b09b5455e9c8d8b2b1681ade5a",
|
||||
"fingerprint": "3e00ca5b1d6e0c5d84eb33531bb8148aba3598a8b987dd526b8f9ddab2e12fed"
|
||||
},
|
||||
"candidateExport": {
|
||||
"revision": "c263c4f72089cb07ce1de9033f7aa6b564c914ce",
|
||||
"dirty": false,
|
||||
"corpusFingerprint": "88be1faf45e9aec145f9d168b8959d67f31ec3b09b5455e9c8d8b2b1681ade5a",
|
||||
"fingerprint": "4db24f57b329263d31a8c9d55e1148c9cd7bde552c3dcbcba7d256f1c8a4e37c"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,13 @@
|
|||
# Receiver-resolution baseline
|
||||
|
||||
## CommonJS member-assigned wrapper fixture (#3630)
|
||||
|
||||
The `fetch-wrapper-target-identity` fixture gained `lib/cjs-member.js`, which
|
||||
exports `module.exports.arrowRequest = (url) => fetch(url);`. That
|
||||
`module.exports` member write is one new `receiver-unresolved` write site, so
|
||||
all-kind drops move from 190 to 191 and writes from 19 to 20. Call drops and
|
||||
every shape-arm state are unchanged; no existing site changed state.
|
||||
|
||||
## Semantic rename provider captures (#3486)
|
||||
|
||||
A same-corpus A/B against `origin/main` (`191a954b`) reproduced the committed
|
||||
|
|
|
|||
|
|
@ -200,11 +200,11 @@
|
|||
},
|
||||
"countArm": {
|
||||
"callDrops": 128,
|
||||
"totalDropsAllKinds": 190,
|
||||
"totalDropsAllKinds": 191,
|
||||
"bySiteKind": {
|
||||
"call": 128,
|
||||
"read": 43,
|
||||
"write": 19
|
||||
"write": 20
|
||||
},
|
||||
"callDropsByExtension": {
|
||||
".java": 49,
|
||||
|
|
|
|||
|
|
@ -349,6 +349,8 @@ const WORKER_THREADS = [
|
|||
// local-import ownership on each platform's native grammar/runtime pair.
|
||||
'test/integration/local-import-worker-parity.test.ts',
|
||||
'test/integration/resolvers/local-import-persistence.test.ts',
|
||||
// The same worker and store path for fetch-wrapper facts and their resolution.
|
||||
'test/integration/resolvers/fetch-wrapper-persistence.test.ts',
|
||||
];
|
||||
|
||||
// Tree-sitter native addon smoke tests — verify that native grammars
|
||||
|
|
|
|||
|
|
@ -51,7 +51,11 @@ import type {
|
|||
RepoConstants,
|
||||
} from './route-extractors/constant-resolver.js';
|
||||
import type Parser from 'tree-sitter';
|
||||
import type { FetchWrapperCall } from './route-extractors/fetch-wrapper.js';
|
||||
import type {
|
||||
FetchWrapperCall,
|
||||
FetchWrapperFacts,
|
||||
FetchWrapperReexport,
|
||||
} from './route-extractors/fetch-wrapper.js';
|
||||
import type { ExtractedDecoratorRoute, ExtractedToolDef } from './workers/parse-worker.js';
|
||||
import type { SemanticModel } from './model/semantic-model.js';
|
||||
|
||||
|
|
@ -649,10 +653,25 @@ interface LanguageProviderConfig {
|
|||
* are known across files. Routes selects known wrappers after parsing. */
|
||||
readonly extractFetchWrapperCalls?: (
|
||||
tree: Parser.Tree,
|
||||
filePath: string,
|
||||
parsedFile: ParsedFile,
|
||||
lineOffset: number,
|
||||
) => FetchWrapperCall[];
|
||||
|
||||
/** Module exports that forward another module's export, so barrels resolve to definitions. */
|
||||
readonly extractFetchWrapperReexports?: (
|
||||
tree: Parser.Tree,
|
||||
parsedFile: ParsedFile,
|
||||
lineOffset: number,
|
||||
) => FetchWrapperReexport[];
|
||||
|
||||
/** Scope-aware evidence for every callable declaration, including non-wrappers. */
|
||||
readonly extractFetchWrapperFacts?: (
|
||||
definition: Parser.SyntaxNode,
|
||||
nameNode: Parser.SyntaxNode | undefined,
|
||||
parsedFile: ParsedFile,
|
||||
lineOffset: number,
|
||||
) => FetchWrapperFacts | undefined;
|
||||
|
||||
/**
|
||||
* Name of the function a route decorator captured by the worker's generic
|
||||
* `@decorator` query applies to, given the decorator's own AST node.
|
||||
|
|
|
|||
|
|
@ -7,8 +7,9 @@
|
|||
*/
|
||||
|
||||
import { SupportedLanguages } from 'gitnexus-shared';
|
||||
import type Parser from 'tree-sitter';
|
||||
import { unboundCallableName } from './typescript/unbound-callables.js';
|
||||
import type { CaptureMatch, NodeLabel } from 'gitnexus-shared';
|
||||
import type { CaptureMatch, NodeLabel, ParsedFile } from 'gitnexus-shared';
|
||||
import { defineLanguage } from '../language-provider.js';
|
||||
import type { AstFrameworkPatternConfig } from '../language-provider.js';
|
||||
import { createClassExtractor } from '../class-extractors/generic.js';
|
||||
|
|
@ -129,7 +130,10 @@ import {
|
|||
import { extractDispatchGuardRoutes } from '../route-extractors/dispatch-guard.js';
|
||||
import { extractDataRouteTableRoutes } from '../route-extractors/data-route-table.js';
|
||||
import { extractNestRoutes } from '../route-extractors/nest.js';
|
||||
import { extractFetchWrapperCalls } from '../route-extractors/fetch-wrapper.js';
|
||||
import {
|
||||
createFetchWrapperContext,
|
||||
type FetchWrapperContext,
|
||||
} from '../route-extractors/fetch-wrapper.js';
|
||||
import { extractFrameworkRouteFacts } from '../route-extractors/framework-route-facts.js';
|
||||
import { resolveProjectFrameworkRouteFacts } from '../route-extractors/framework-route-paths.js';
|
||||
import { extractTrpcRoutes, shouldScanForTrpcRoutes } from '../route-extractors/trpc.js';
|
||||
|
|
@ -413,6 +417,43 @@ const TS_OWNED_RECEIVERS: ReadonlySet<string> = new Set(['this']);
|
|||
const tsScopeOwnsReceivers = (match: CaptureMatch): ReadonlySet<string> | undefined =>
|
||||
match['@receiver-owner.this'] === undefined ? undefined : TS_OWNED_RECEIVERS;
|
||||
|
||||
// Keyed by tree, not ParsedFile: workers retain ParsedFiles for the whole chunk,
|
||||
// while a file's tree, and with it this AST-holding context, is released per file.
|
||||
const httpContexts = new WeakMap<
|
||||
Parser.Tree,
|
||||
{ parsedFile: ParsedFile; lineOffset: number; context: FetchWrapperContext }
|
||||
>();
|
||||
function httpContext(
|
||||
tree: Parser.Tree,
|
||||
parsedFile: ParsedFile,
|
||||
lineOffset: number,
|
||||
): FetchWrapperContext {
|
||||
const cached = httpContexts.get(tree);
|
||||
if (cached?.parsedFile === parsedFile && cached.lineOffset === lineOffset) return cached.context;
|
||||
const context = createFetchWrapperContext(tree, parsedFile, lineOffset);
|
||||
httpContexts.set(tree, { parsedFile, lineOffset, context });
|
||||
return context;
|
||||
}
|
||||
const httpExtraction = {
|
||||
extractRouteFacts: (tree: Parser.Tree, parsedFile: ParsedFile, lineOffset: number) =>
|
||||
extractFrameworkRouteFacts(
|
||||
tree,
|
||||
parsedFile,
|
||||
lineOffset,
|
||||
httpContext(tree, parsedFile, lineOffset).bindings,
|
||||
),
|
||||
extractFetchWrapperCalls: (tree: Parser.Tree, parsedFile: ParsedFile, lineOffset: number) =>
|
||||
httpContext(tree, parsedFile, lineOffset).calls(),
|
||||
extractFetchWrapperReexports: (tree: Parser.Tree, parsedFile: ParsedFile, lineOffset: number) =>
|
||||
httpContext(tree, parsedFile, lineOffset).reexports(),
|
||||
extractFetchWrapperFacts: (
|
||||
definition: Parser.SyntaxNode,
|
||||
name: Parser.SyntaxNode | undefined,
|
||||
parsedFile: ParsedFile,
|
||||
lineOffset: number,
|
||||
) => httpContext(definition.tree, parsedFile, lineOffset).facts(definition, name),
|
||||
};
|
||||
|
||||
export const typescriptProvider = defineLanguage({
|
||||
id: SupportedLanguages.TypeScript,
|
||||
rename: typescriptRenameProvider,
|
||||
|
|
@ -506,9 +547,8 @@ export const typescriptProvider = defineLanguage({
|
|||
// to a literal; nothing else in this pipeline can see that shape. TS and JS
|
||||
// share the grammar, so they share the extractor.
|
||||
extractDecoratorRoutes: extractJsTsRoutes,
|
||||
extractRouteFacts: extractFrameworkRouteFacts,
|
||||
...httpExtraction,
|
||||
resolveRouteFacts: resolveProjectFrameworkRouteFacts,
|
||||
extractFetchWrapperCalls,
|
||||
// Content-based (not AST): tRPC procedure routers are scanned from source text.
|
||||
// Path-gate lives here (language provider), not in the shared parse worker.
|
||||
extractTextRoutes: extractJsTsTextRoutes,
|
||||
|
|
@ -595,9 +635,8 @@ export const javascriptProvider = defineLanguage({
|
|||
arityCompatibility: jsArityCompatibility,
|
||||
// See the TypeScript provider above.
|
||||
extractDecoratorRoutes: extractJsTsRoutes,
|
||||
extractRouteFacts: extractFrameworkRouteFacts,
|
||||
...httpExtraction,
|
||||
resolveRouteFacts: resolveProjectFrameworkRouteFacts,
|
||||
extractFetchWrapperCalls,
|
||||
// Content-based (not AST): tRPC procedure routers are scanned from source text.
|
||||
extractTextRoutes: extractJsTsTextRoutes,
|
||||
extractToolDefinitions,
|
||||
|
|
|
|||
|
|
@ -326,31 +326,14 @@ function importedReceiverIsReassigned(
|
|||
const node = occurrence.node;
|
||||
if (!node || !receiverWrite(node)) continue;
|
||||
const scope = innermostRenameScope(other.parsed, node);
|
||||
let written = scope
|
||||
const written = scope
|
||||
? lookupNameClaim(scope, occurrence.name, context.indexes, {
|
||||
position: nodeRange(node),
|
||||
// Resolve the written binding before this write invalidates its import proof.
|
||||
preservePosition: true,
|
||||
purpose: 'value',
|
||||
})
|
||||
: undefined;
|
||||
// Assignment inference describes a value, not a new lexical declaration.
|
||||
// Continue only when the provider's complete claims prove this scope
|
||||
// declares no binding; the eventual import must still resolve by identity.
|
||||
while (
|
||||
written?.scope?.lookupPolicy?.nameClaimsComplete &&
|
||||
written.claims.length === 0 &&
|
||||
written.bindings.length === 0 &&
|
||||
written.imports.length === 0 &&
|
||||
(written.typeBinding?.source === 'constructor-inferred' ||
|
||||
written.typeBinding?.source === 'assignment-inferred')
|
||||
) {
|
||||
const parent = written.scope.lookupPolicy.parentScope ?? written.scope.parent;
|
||||
if (!parent) break;
|
||||
written = lookupNameClaim(parent, occurrence.name, context.indexes, {
|
||||
// Resolve the binding being written, before this write's blocker.
|
||||
position: nodeRange(node),
|
||||
purpose: 'value',
|
||||
});
|
||||
}
|
||||
if (written && written.bindings.some(({ def }) => def.nodeId === declarationId)) {
|
||||
cache.set(declarationId, true);
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { FetchWrapperCall } from './route-extractors/fetch-wrapper.js';
|
||||
import type { FetchWrapperCall, FetchWrapperReexport } from './route-extractors/fetch-wrapper.js';
|
||||
import type { NodeLabel } from 'gitnexus-shared';
|
||||
import { KnowledgeGraph } from '../graph/types.js';
|
||||
import type { SymbolTableWriter } from './model/index.js';
|
||||
|
|
@ -39,6 +39,7 @@ export interface WorkerExtractedData {
|
|||
fetchCalls: ExtractedFetchCall[];
|
||||
fetchWrapperDefs: FetchWrapperDef[];
|
||||
fetchWrapperCalls: FetchWrapperCall[];
|
||||
fetchWrapperReexports: FetchWrapperReexport[];
|
||||
decoratorRoutes: ExtractedDecoratorRoute[];
|
||||
routeFacts?: { filePath: string; facts: unknown; routePosition: number }[];
|
||||
routerIncludes: ExtractedRouterInclude[];
|
||||
|
|
@ -122,6 +123,7 @@ export const mergeChunkResults = (
|
|||
const allFetchCalls: ExtractedFetchCall[] = [];
|
||||
const allFetchWrapperDefs: FetchWrapperDef[] = [];
|
||||
const allFetchWrapperCalls: FetchWrapperCall[] = [];
|
||||
const allFetchWrapperReexports: FetchWrapperReexport[] = [];
|
||||
const allDecoratorRoutes: ExtractedDecoratorRoute[] = [];
|
||||
const allRouteFacts: { filePath: string; facts: unknown; routePosition: number }[] = [];
|
||||
const allRouterIncludes: ExtractedRouterInclude[] = [];
|
||||
|
|
@ -174,6 +176,7 @@ export const mergeChunkResults = (
|
|||
for (const item of result.fetchCalls) allFetchCalls.push(item);
|
||||
for (const item of result.fetchWrapperDefs ?? []) allFetchWrapperDefs.push(item);
|
||||
for (const item of result.fetchWrapperCalls ?? []) allFetchWrapperCalls.push(item);
|
||||
for (const item of result.fetchWrapperReexports ?? []) allFetchWrapperReexports.push(item);
|
||||
for (const item of result.routeFacts ?? [])
|
||||
allRouteFacts.push({
|
||||
...item,
|
||||
|
|
@ -203,6 +206,7 @@ export const mergeChunkResults = (
|
|||
fetchCalls: allFetchCalls,
|
||||
fetchWrapperDefs: allFetchWrapperDefs,
|
||||
fetchWrapperCalls: allFetchWrapperCalls,
|
||||
fetchWrapperReexports: allFetchWrapperReexports,
|
||||
decoratorRoutes: allDecoratorRoutes,
|
||||
routeFacts: allRouteFacts,
|
||||
routerIncludes: allRouterIncludes,
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@
|
|||
*/
|
||||
|
||||
import type { LanguageProvider } from '../language-provider.js';
|
||||
import type { FetchWrapperCall } from '../route-extractors/fetch-wrapper.js';
|
||||
import type { FetchWrapperCall, FetchWrapperReexport } from '../route-extractors/fetch-wrapper.js';
|
||||
import { resolveFetchWrapperTargets } from '../route-extractors/fetch-wrapper-index.js';
|
||||
import {
|
||||
BindingAccumulator,
|
||||
enrichExportedTypeMap,
|
||||
|
|
@ -754,8 +755,9 @@ export async function runChunkedParseAndResolve(
|
|||
const exportedTypeMap: ExportedTypeMap = new Map();
|
||||
const bindingAccumulator = new BindingAccumulator();
|
||||
const allFetchCalls: ExtractedFetchCall[] = [];
|
||||
const allFetchWrapperDefs: FetchWrapperDef[] = [];
|
||||
const allFetchWrapperCalls: FetchWrapperCall[] = [];
|
||||
let allFetchWrapperDefs: FetchWrapperDef[] = [];
|
||||
let allFetchWrapperCalls: FetchWrapperCall[] = [];
|
||||
const allFetchWrapperReexports: FetchWrapperReexport[] = [];
|
||||
const allExtractedRoutes: ExtractedRoute[] = [];
|
||||
const allDecoratorRoutes: ExtractedDecoratorRoute[] = [];
|
||||
const allRouteFacts: { filePath: string; facts: unknown; routePosition: number }[] = [];
|
||||
|
|
@ -985,6 +987,8 @@ export async function runChunkedParseAndResolve(
|
|||
for (const item of chunkWorkerData.fetchCalls) allFetchCalls.push(item);
|
||||
}
|
||||
for (const item of chunkWorkerData.fetchWrapperCalls ?? []) allFetchWrapperCalls.push(item);
|
||||
for (const item of chunkWorkerData.fetchWrapperReexports ?? [])
|
||||
allFetchWrapperReexports.push(item);
|
||||
if (chunkWorkerData.fetchWrapperDefs?.length) {
|
||||
for (const item of chunkWorkerData.fetchWrapperDefs) allFetchWrapperDefs.push(item);
|
||||
}
|
||||
|
|
@ -1572,7 +1576,15 @@ export async function runChunkedParseAndResolve(
|
|||
|
||||
const routeFilePaths = new Set(allPaths);
|
||||
const routeResolutionConfigs = new Map<SupportedLanguages, unknown>();
|
||||
for (const filePath of new Set(allRouteFacts.map((file) => file.filePath))) {
|
||||
const resolutionFilePaths = new Set<string>();
|
||||
for (const facts of [
|
||||
allRouteFacts,
|
||||
allFetchWrapperDefs,
|
||||
allFetchWrapperCalls,
|
||||
allFetchWrapperReexports,
|
||||
] as const)
|
||||
for (const { filePath } of facts) resolutionFilePaths.add(filePath);
|
||||
for (const filePath of resolutionFilePaths) {
|
||||
const language = getLanguageFromFilename(filePath);
|
||||
if (language === null || routeResolutionConfigs.has(language)) continue;
|
||||
const resolver = SCOPE_RESOLVERS.get(language);
|
||||
|
|
@ -1609,6 +1621,15 @@ export async function runChunkedParseAndResolve(
|
|||
): readonly string[] =>
|
||||
resolveRouteModuleTargets(fromFile, parsedImport.targetRaw ?? '', parsedImport);
|
||||
|
||||
const resolvedFetchWrappers = resolveFetchWrapperTargets(
|
||||
allFetchWrapperDefs,
|
||||
allFetchWrapperCalls,
|
||||
resolveRouteModuleTargets,
|
||||
allFetchWrapperReexports,
|
||||
);
|
||||
allFetchWrapperDefs = resolvedFetchWrappers.definitions;
|
||||
allFetchWrapperCalls = resolvedFetchWrappers.calls;
|
||||
|
||||
// A resolver's identity defines a fact family, including providers sharing
|
||||
// one language implementation. Shared ingestion never inspects the payload.
|
||||
const routeFactGroups = new Map<
|
||||
|
|
|
|||
|
|
@ -16,11 +16,7 @@ import { getPhaseOutput } from './types.js';
|
|||
import type { ParseOutput } from './parse.js';
|
||||
import { isTemplateRouteCandidate } from '../utils/template-file.js';
|
||||
import { nextjsFileToRouteURL, normalizeFetchURL } from '../route-extractors/nextjs.js';
|
||||
import {
|
||||
moduleStem,
|
||||
type FetchWrapperCall,
|
||||
type ForwardedCallee,
|
||||
} from '../route-extractors/fetch-wrapper.js';
|
||||
import { buildFetchWrapperIndex } from '../route-extractors/fetch-wrapper-index.js';
|
||||
import { expoFileToRouteURL } from '../route-extractors/expo.js';
|
||||
import { phpFileToRouteURL } from '../route-extractors/php.js';
|
||||
import {
|
||||
|
|
@ -510,55 +506,12 @@ export const routesPhase: PipelinePhase<RoutesOutput> = {
|
|||
const configuredWrappers = (ctx.options?.fetchWrappers ?? []).filter(
|
||||
(n): n is string => typeof n === 'string' && n.trim().length > 0,
|
||||
);
|
||||
const wrapperDefs = allFetchWrapperDefs ?? [];
|
||||
const wrapperNames = new Set<string>([
|
||||
...wrapperDefs.filter((d) => d.seed).map((d) => d.functionName),
|
||||
...configuredWrappers,
|
||||
]);
|
||||
// A function that forwards its own first parameter to a URL-carrying
|
||||
// wrapper is one too (`fetchWithTimeout(url)` → `resilientFetch(url)` →
|
||||
// fetch, #3488). A callee the caller's file declares or imports from a
|
||||
// relative module must be a URL carrier in exactly that module; otherwise
|
||||
// (a package import) the name is followed only when every recorded
|
||||
// function of that name carries a URL. So a same-named function elsewhere
|
||||
// (an IPC `request(channel)`) or a fetch caller whose first parameter is
|
||||
// not the URL (`track(event)`) lends nothing. The set only grows, so this
|
||||
// reaches a fixed point.
|
||||
const carriers = new Set(wrapperDefs.filter((d) => d.forwardsUrl));
|
||||
const defsByName = new Map<string, typeof wrapperDefs>();
|
||||
const defsByModule = new Map<string, typeof wrapperDefs>();
|
||||
for (const def of wrapperDefs) {
|
||||
const key = `${moduleStem(def.filePath)}\0${def.functionName}`;
|
||||
defsByName.set(def.functionName, [...(defsByName.get(def.functionName) ?? []), def]);
|
||||
defsByModule.set(key, [...(defsByModule.get(key) ?? []), def]);
|
||||
}
|
||||
const carriesUrl = ({ callee, module }: ForwardedCallee): boolean =>
|
||||
configuredWrappers.includes(callee) ||
|
||||
(module === null
|
||||
? (defsByName.get(callee)?.every((def) => carriers.has(def)) ?? false)
|
||||
: (defsByModule.get(`${module}\0${callee}`)?.some((def) => carriers.has(def)) ?? false));
|
||||
for (let grew = true; grew; ) {
|
||||
grew = false;
|
||||
for (const def of wrapperDefs) {
|
||||
if (carriers.has(def) || !def.forwardsTo.some(carriesUrl)) continue;
|
||||
carriers.add(def);
|
||||
wrapperNames.add(def.functionName);
|
||||
grew = true;
|
||||
}
|
||||
}
|
||||
// A call whose callee the file declares or imports relatively must reach a
|
||||
// wrapper in exactly that module; a package or member callee keeps the
|
||||
// name match.
|
||||
const isWrapperCall = ({ functionName, module, declaredName }: FetchWrapperCall): boolean =>
|
||||
configuredWrappers.includes(functionName) ||
|
||||
(module === undefined
|
||||
? wrapperNames.has(functionName)
|
||||
: (defsByModule
|
||||
.get(`${module}\0${declaredName ?? functionName}`)
|
||||
?.some((def) => def.seed || carriers.has(def)) ?? false));
|
||||
if (wrapperNames.size > 0 && routeRegistry.size > 0) {
|
||||
for (const call of allFetchWrapperCalls ?? []) {
|
||||
if (isWrapperCall(call)) allFetchCalls.push(call);
|
||||
// The index is only worth building when a candidate call can match a route.
|
||||
const wrapperCalls = allFetchWrapperCalls ?? [];
|
||||
if (routeRegistry.size > 0 && wrapperCalls.length > 0) {
|
||||
const wrappers = buildFetchWrapperIndex(allFetchWrapperDefs ?? [], configuredWrappers);
|
||||
for (const call of wrapperCalls) {
|
||||
if (wrappers.isWrapperCall(call)) allFetchCalls.push(call);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,296 @@
|
|||
import type { FetchWrapperDef } from '../workers/parse-worker.js';
|
||||
import type { CalleeTarget, FetchWrapperCall, FetchWrapperReexport } from './fetch-wrapper.js';
|
||||
|
||||
interface NameGroup {
|
||||
remainingCarriers: number;
|
||||
hasWrapper: boolean;
|
||||
dependents: number[];
|
||||
}
|
||||
|
||||
function addUnique(index: Map<string, number | null>, key: string, definition: number): void {
|
||||
const existing = index.get(key);
|
||||
if (existing === undefined) index.set(key, definition);
|
||||
else if (existing !== definition) index.set(key, null);
|
||||
}
|
||||
|
||||
/** Build target indexes and propagate URL carriers once through each dependency. */
|
||||
export function buildFetchWrapperIndex(
|
||||
definitions: readonly FetchWrapperDef[],
|
||||
configuredNames: readonly string[] = [],
|
||||
): {
|
||||
isWrapperCall(call: Pick<FetchWrapperCall, 'filePath' | 'functionName' | 'target'>): boolean;
|
||||
} {
|
||||
const configured = new Set(configuredNames);
|
||||
const seen = new Set<string>();
|
||||
const defs: FetchWrapperDef[] = [];
|
||||
const bindings = new Map<string, number | null>();
|
||||
const exports = new Map<string, number | null>();
|
||||
// Name-only fallbacks consider only definitions that can be the target: an
|
||||
// unresolvable import names some module's export, an undeclared global a
|
||||
// top-level function. Nested and unexported helpers never collide with them.
|
||||
const exportedAnywhere = new Map<string, number | null>();
|
||||
const topLevel = new Map<string, number | null>();
|
||||
const names = new Map<string, NameGroup>();
|
||||
|
||||
for (const definition of definitions) {
|
||||
const identity = `${definition.filePath}\0${definition.definitionId}`;
|
||||
if (seen.has(identity)) continue;
|
||||
seen.add(identity);
|
||||
const index = defs.length;
|
||||
defs.push(definition);
|
||||
if (definition.bindingId !== undefined) {
|
||||
addUnique(bindings, `${definition.filePath}\0${definition.bindingId}`, index);
|
||||
}
|
||||
if (definition.moduleScope) {
|
||||
for (const name of definition.exportedNames) {
|
||||
addUnique(exports, `${definition.filePath}\0${name}`, index);
|
||||
addUnique(exportedAnywhere, name, index);
|
||||
}
|
||||
addUnique(topLevel, definition.functionName, index);
|
||||
}
|
||||
const group = names.get(definition.functionName);
|
||||
if (group) {
|
||||
group.remainingCarriers++;
|
||||
group.hasWrapper ||= definition.seed;
|
||||
} else {
|
||||
names.set(definition.functionName, {
|
||||
remainingCarriers: 1,
|
||||
hasWrapper: definition.seed,
|
||||
dependents: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const targetDefinition = (
|
||||
filePath: string,
|
||||
name: string,
|
||||
target: CalleeTarget,
|
||||
): number | null | undefined => {
|
||||
switch (target.kind) {
|
||||
case 'binding':
|
||||
return bindings.get(`${filePath}\0${target.bindingId}`);
|
||||
case 'resolved-import':
|
||||
return exports.get(`${target.filePath}\0${target.importedName}`);
|
||||
case 'import':
|
||||
return exportedAnywhere.get(target.importedName);
|
||||
case 'unresolved':
|
||||
return topLevel.get(name);
|
||||
case 'blocked':
|
||||
case 'member':
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const carriers = new Set<number>();
|
||||
const queue: number[] = [];
|
||||
const dependents: number[][] = Array.from({ length: defs.length }, () => []);
|
||||
const activate = (index: number): void => {
|
||||
if (carriers.has(index)) return;
|
||||
carriers.add(index);
|
||||
queue.push(index);
|
||||
};
|
||||
|
||||
for (let index = 0; index < defs.length; index++) {
|
||||
const definition = defs[index];
|
||||
if (definition.forwardsUrl) activate(index);
|
||||
for (const forwarded of definition.forwardsTo) {
|
||||
if (configured.has(forwarded.callee)) {
|
||||
activate(index);
|
||||
} else if (forwarded.target.kind === 'member') {
|
||||
// Preserve member forwarding's existing all-definitions requirement.
|
||||
names.get(forwarded.callee)?.dependents.push(index);
|
||||
} else {
|
||||
const target = targetDefinition(definition.filePath, forwarded.callee, forwarded.target);
|
||||
if (target !== undefined && target !== null) dependents[target].push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let cursor = 0; cursor < queue.length; cursor++) {
|
||||
const index = queue[cursor];
|
||||
for (const dependent of dependents[index]) activate(dependent);
|
||||
const group = names.get(defs[index].functionName);
|
||||
if (!group) continue;
|
||||
group.hasWrapper = true;
|
||||
if (--group.remainingCarriers === 0) {
|
||||
for (const dependent of group.dependents) activate(dependent);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isWrapperCall: ({ filePath, functionName, target }) => {
|
||||
if (configured.has(functionName)) return true;
|
||||
if (target.kind === 'member') return names.get(functionName)?.hasWrapper ?? false;
|
||||
const index = targetDefinition(filePath, functionName, target);
|
||||
return index !== undefined && index !== null && (defs[index].seed || carriers.has(index));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve serialized import facts with the pipeline's existing project resolver.
|
||||
* Only providers whose modules link by ECMAScript rules emit re-export facts, so
|
||||
* the barrel walk applies ResolveExport; it names no language and consults no
|
||||
* provider.
|
||||
*/
|
||||
export function resolveFetchWrapperTargets(
|
||||
definitions: readonly FetchWrapperDef[],
|
||||
calls: readonly FetchWrapperCall[],
|
||||
resolveModuleTargets: (fromFile: string, specifier: string) => readonly string[],
|
||||
reexports: readonly FetchWrapperReexport[] = [],
|
||||
): { definitions: FetchWrapperDef[]; calls: FetchWrapperCall[] } {
|
||||
const modules = new Map<string, readonly string[]>();
|
||||
const moduleTargets = (filePath: string, specifier: string): readonly string[] => {
|
||||
const key = `${filePath}\0${specifier}`;
|
||||
let targets = modules.get(key);
|
||||
if (targets === undefined) {
|
||||
targets = resolveModuleTargets(filePath, specifier);
|
||||
modules.set(key, targets);
|
||||
}
|
||||
return targets;
|
||||
};
|
||||
// Each export name maps to the declaration it names; a name two declarations
|
||||
// claim keeps a name-only identity, so it never merges with another export.
|
||||
const declared = new Map<string, string>();
|
||||
for (const definition of definitions)
|
||||
if (definition.moduleScope)
|
||||
for (const name of definition.exportedNames) {
|
||||
const key = `${definition.filePath}\0${name}`;
|
||||
const identity = `${definition.filePath}\0${definition.definitionId}`;
|
||||
const existing = declared.get(key);
|
||||
declared.set(key, existing === undefined || existing === identity ? identity : `${key}\0`);
|
||||
}
|
||||
const named = new Map<string, FetchWrapperReexport[]>();
|
||||
const stars = new Map<string, FetchWrapperReexport[]>();
|
||||
for (const reexport of reexports) {
|
||||
const [index, key] =
|
||||
reexport.exportedName === '*'
|
||||
? [stars, reexport.filePath]
|
||||
: [named, `${reexport.filePath}\0${reexport.exportedName}`];
|
||||
const bucket = index.get(key);
|
||||
if (bucket) bucket.push(reexport);
|
||||
else index.set(key, [reexport]);
|
||||
}
|
||||
// Follow a barrel to the module declaring the export. Local and named exports
|
||||
// shadow `export *`; star exports never carry `default`, and conflicting star
|
||||
// exports leave the name unexported (ECMAScript ResolveExport).
|
||||
interface ExportFrame {
|
||||
filePath: string;
|
||||
name: string;
|
||||
candidates: readonly FetchWrapperReexport[];
|
||||
cursor: number;
|
||||
found: Map<string, CalleeTarget>;
|
||||
/** A branch stopped at an export already on this walk, so the result is not reusable. */
|
||||
partial: boolean;
|
||||
}
|
||||
type ExportStep = { frame: ExportFrame } | { value: CalleeTarget | undefined; partial?: true };
|
||||
// Fully explored exports, shared by every walk: calls that enter a chain at
|
||||
// different hops reuse the hops below, keeping the work linear in the chain.
|
||||
const resolvedExports = new Map<string, CalleeTarget | undefined>();
|
||||
// Explicit frames instead of recursion, so long re-export chains cannot
|
||||
// exhaust the call stack. One walk shares `seen` across all of its branches.
|
||||
const exporter = (startFile: string, startName: string): CalleeTarget | undefined => {
|
||||
const seen = new Set<string>();
|
||||
const open = (filePath: string, name: string): ExportStep => {
|
||||
const key = `${filePath}\0${name}`;
|
||||
if (declared.has(key))
|
||||
return { value: { kind: 'resolved-import', filePath, importedName: name } };
|
||||
if (resolvedExports.has(key)) return { value: resolvedExports.get(key) };
|
||||
if (seen.has(key)) return { value: undefined, partial: true };
|
||||
seen.add(key);
|
||||
const candidates =
|
||||
named.get(key) ?? (name === 'default' ? undefined : stars.get(filePath)) ?? [];
|
||||
return { frame: { filePath, name, candidates, cursor: 0, found: new Map(), partial: false } };
|
||||
};
|
||||
// Star exports conflict only when they reach different bindings, so two
|
||||
// export names of one declaration are one candidate.
|
||||
const record = (frame: ExportFrame, target: CalleeTarget | undefined) => {
|
||||
if (!target) return;
|
||||
const identity =
|
||||
target.kind === 'resolved-import'
|
||||
? declared.get(`${target.filePath}\0${target.importedName}`)
|
||||
: undefined;
|
||||
const key = identity ?? JSON.stringify(target);
|
||||
if (!frame.found.has(key)) frame.found.set(key, target);
|
||||
};
|
||||
const first = open(startFile, startName);
|
||||
if ('value' in first) return first.value;
|
||||
const frames = [first.frame];
|
||||
let finished: CalleeTarget | undefined;
|
||||
while (frames.length > 0) {
|
||||
const frame = frames[frames.length - 1];
|
||||
let nested: ExportFrame | undefined;
|
||||
let local = false;
|
||||
while (frame.cursor < frame.candidates.length) {
|
||||
const { from } = frame.candidates[frame.cursor++];
|
||||
// A local export that declares no wrapper shadows every forwarded name.
|
||||
if (!from) {
|
||||
local = true;
|
||||
break;
|
||||
}
|
||||
const targets = moduleTargets(frame.filePath, from.specifier);
|
||||
if (targets.length !== 1) continue;
|
||||
const step = open(targets[0], from.importedName === '*' ? frame.name : from.importedName);
|
||||
if ('value' in step) {
|
||||
record(frame, step.value);
|
||||
if (step.partial) frame.partial = true;
|
||||
} else {
|
||||
nested = step.frame;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (nested) {
|
||||
frames.push(nested);
|
||||
continue;
|
||||
}
|
||||
frames.pop();
|
||||
// A local non-wrapper export is still an export: it shadows star exports
|
||||
// here and conflicts with a wrapper another star export reaches.
|
||||
finished = local
|
||||
? { kind: 'resolved-import', filePath: frame.filePath, importedName: frame.name }
|
||||
: frame.found.size > 1
|
||||
? { kind: 'blocked' }
|
||||
: frame.found.values().next().value;
|
||||
if (!frame.partial) resolvedExports.set(`${frame.filePath}\0${frame.name}`, finished);
|
||||
const parent = frames[frames.length - 1];
|
||||
if (parent) {
|
||||
record(parent, finished);
|
||||
if (frame.partial) parent.partial = true;
|
||||
}
|
||||
}
|
||||
return finished;
|
||||
};
|
||||
const resolve = (filePath: string, target: CalleeTarget): CalleeTarget => {
|
||||
if (target.kind !== 'import') return target;
|
||||
const targets = moduleTargets(filePath, target.specifier);
|
||||
if (targets.length === 0) return target;
|
||||
if (targets.length !== 1) return { kind: 'blocked' };
|
||||
return (
|
||||
exporter(targets[0], target.importedName) ?? {
|
||||
kind: 'resolved-import',
|
||||
filePath: targets[0],
|
||||
importedName: target.importedName,
|
||||
}
|
||||
);
|
||||
};
|
||||
// Aggregates share facts with the parse cache. Keep its raw specifiers intact
|
||||
// so a warm parse resolves imports against the current project configuration.
|
||||
return {
|
||||
definitions: definitions.map((definition) =>
|
||||
definition.forwardsTo.some((forwarded) => forwarded.target.kind === 'import')
|
||||
? {
|
||||
...definition,
|
||||
forwardsTo: definition.forwardsTo.map((forwarded) => ({
|
||||
...forwarded,
|
||||
target: resolve(definition.filePath, forwarded.target),
|
||||
})),
|
||||
}
|
||||
: definition,
|
||||
),
|
||||
calls: calls.map((call) =>
|
||||
call.target.kind === 'import'
|
||||
? { ...call, target: resolve(call.filePath, call.target) }
|
||||
: call,
|
||||
),
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,8 +1,19 @@
|
|||
import type Parser from 'tree-sitter';
|
||||
import { buildPositionIndex, buildScopeTree, lookupLexicalName } from 'gitnexus-shared';
|
||||
import type { ParsedFile, ParsedImport } from 'gitnexus-shared';
|
||||
import { plainString } from './data-route-table.js';
|
||||
import type { FrameworkExpression, FrameworkRouteFacts } from './framework-route-types.js';
|
||||
import {
|
||||
createLexicalBindings,
|
||||
importBindingKey,
|
||||
isCommonJsGlobal,
|
||||
isModuleExports,
|
||||
LEXICAL_FUNCTION_TYPES,
|
||||
parameterPattern,
|
||||
patternBindingNames,
|
||||
TRANSPARENT_EXPRESSION_TYPES,
|
||||
transparentInner,
|
||||
type LexicalBindings,
|
||||
} from './lexical-bindings.js';
|
||||
|
||||
type Node = Parser.SyntaxNode;
|
||||
const UNKNOWN: FrameworkExpression = { kind: 'unknown' };
|
||||
|
|
@ -15,10 +26,12 @@ const CARRIER_KINDS = new Set<FrameworkExpression['kind']>([
|
|||
'import',
|
||||
'array',
|
||||
]);
|
||||
/** Function values and declarations; methods and signatures are not values here. */
|
||||
const FUNCTION_TYPES = [
|
||||
'arrow_function',
|
||||
'function_expression',
|
||||
'function_declaration',
|
||||
'generator_function',
|
||||
'generator_function_declaration',
|
||||
];
|
||||
const METHODS = new Set(['get', 'post', 'put', 'delete', 'patch', 'all', 'route', 'use']);
|
||||
|
|
@ -45,6 +58,7 @@ export function extractFrameworkRouteFacts(
|
|||
tree: Parser.Tree,
|
||||
parsedFile: ParsedFile,
|
||||
lineOffset = 0,
|
||||
lexical: LexicalBindings = createLexicalBindings(parsedFile, lineOffset, tree.rootNode),
|
||||
): FrameworkRouteFacts {
|
||||
const filePath = parsedFile.filePath;
|
||||
const facts: FrameworkRouteFacts = {
|
||||
|
|
@ -57,8 +71,7 @@ export function extractFrameworkRouteFacts(
|
|||
calls: [],
|
||||
invocations: [],
|
||||
};
|
||||
const scopes = buildScopeTree(parsedFile.scopes);
|
||||
const positions = buildPositionIndex(parsedFile.scopes);
|
||||
const { bindingId, isGlobal, ambiguous } = lexical;
|
||||
const invalid = new Set<string>();
|
||||
const importsAtPosition = new Map<string, ParsedImport[]>();
|
||||
for (const imported of parsedFile.parsedImports) {
|
||||
|
|
@ -73,104 +86,25 @@ export function extractFrameworkRouteFacts(
|
|||
'localName' in imported ? [imported.localName] : [],
|
||||
),
|
||||
);
|
||||
const bindingKey = (scope: string, name: string): string => `${scope}\0${name}`;
|
||||
const ownership = (node: Node, name = node.text, atUse = false) => {
|
||||
const scope = positions.atPosition(
|
||||
filePath,
|
||||
node.startPosition.row + 1 + lineOffset,
|
||||
node.startPosition.column,
|
||||
);
|
||||
return scope === undefined
|
||||
? undefined
|
||||
: lookupLexicalName(
|
||||
scope,
|
||||
name,
|
||||
{ scopes },
|
||||
{
|
||||
purpose: 'value',
|
||||
...(atUse
|
||||
? {
|
||||
position: {
|
||||
startLine: node.startPosition.row + 1 + lineOffset,
|
||||
startCol: node.startPosition.column,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
};
|
||||
const bindingId = (node: Node, name = node.text, atUse = false): string | undefined => {
|
||||
const owner = ownership(node, name, atUse);
|
||||
// Pre-finalization imports and untyped parameters deliberately have no
|
||||
// BindingRef. A future binding claim, however, is a real TDZ barrier.
|
||||
if (
|
||||
atUse &&
|
||||
owner?.status === 'blocked' &&
|
||||
owner.claims.some(
|
||||
(claim) =>
|
||||
claim.kind === 'blocked' ||
|
||||
(claim.kind === 'binding' &&
|
||||
claim.availableFrom &&
|
||||
(claim.availableFrom.startLine > node.startPosition.row + 1 + lineOffset ||
|
||||
(claim.availableFrom.startLine === node.startPosition.row + 1 + lineOffset &&
|
||||
claim.availableFrom.startCol > node.startPosition.column))),
|
||||
)
|
||||
)
|
||||
return undefined;
|
||||
return owner?.scope ? bindingKey(owner.scope.id, name) : undefined;
|
||||
};
|
||||
const isGlobal = (node: Node, name: string) => ownership(node, name)?.status === 'absent';
|
||||
/** Whether a scope between `target` and `fn` declares the name `target` writes. */
|
||||
const shadowedBetween = (target: Node, fn: Node): boolean => {
|
||||
const declares = (node: Node | null | undefined) =>
|
||||
!!node &&
|
||||
(node.type === 'identifier'
|
||||
? node.text === target.text
|
||||
: node.descendantsOfType('identifier').some((id) => id.text === target.text));
|
||||
for (let scope = target.parent; scope && scope.id !== fn.id; scope = scope.parent) {
|
||||
const ownsVar = FUNCTION_TYPES.includes(scope.parent?.type ?? '');
|
||||
if (
|
||||
children(scope).some(
|
||||
(statement) =>
|
||||
(statement.type === 'lexical_declaration' ||
|
||||
(ownsVar && statement.type === 'variable_declaration')) &&
|
||||
children(statement).some((d) => declares(d.childForFieldName('name'))),
|
||||
) ||
|
||||
(FUNCTION_TYPES.includes(scope.type) &&
|
||||
(declares(scope.childForFieldName('parameter')) ||
|
||||
declares(scope.childForFieldName('parameters')))) ||
|
||||
(scope.type === 'catch_clause' && declares(scope.childForFieldName('parameter')))
|
||||
)
|
||||
return true;
|
||||
const parameterIds = new Map<number, ReadonlySet<string>>();
|
||||
const parametersOf = (fn: Node): ReadonlySet<string> => {
|
||||
let ids = parameterIds.get(fn.id);
|
||||
if (!ids) {
|
||||
ids = new Set(
|
||||
patternBindingNames(
|
||||
fn.childForFieldName('parameters') ?? fn.childForFieldName('parameter'),
|
||||
).flatMap((name) => {
|
||||
const id = bindingId(name);
|
||||
return id ? [id] : [];
|
||||
}),
|
||||
);
|
||||
parameterIds.set(fn.id, ids);
|
||||
}
|
||||
return false;
|
||||
return ids;
|
||||
};
|
||||
const functionValue = (fn: Node): FrameworkExpression => {
|
||||
const single = fn.childForFieldName('parameter');
|
||||
const params = single ? [single] : children(fn.childForFieldName('parameters'));
|
||||
// A parameter written anywhere in the body, nested closures included, is
|
||||
// not the argument any more; fail closed rather than track which write runs.
|
||||
// A write to a same-named binding a nested scope declares is not to it.
|
||||
const written = new Set(
|
||||
fn
|
||||
.descendantsOfType([
|
||||
'assignment_expression',
|
||||
'augmented_assignment_expression',
|
||||
'update_expression',
|
||||
])
|
||||
.map((write) => write.childForFieldName('left') ?? write.childForFieldName('argument'))
|
||||
// A destructuring target (`[app] = [other]`) writes each name it binds;
|
||||
// a member target (`app.locals = …`) writes a property, not the binding.
|
||||
.flatMap((target) =>
|
||||
!target || ['member_expression', 'subscript_expression'].includes(target.type)
|
||||
? []
|
||||
: target.type === 'identifier'
|
||||
? [target]
|
||||
: target.descendantsOfType(['identifier', 'shorthand_property_identifier_pattern']),
|
||||
)
|
||||
.filter((target) => !shadowedBetween(target, fn))
|
||||
.map((target) => target.text),
|
||||
);
|
||||
return {
|
||||
kind: 'handler',
|
||||
fn: `${filePath}:${fn.startIndex}`,
|
||||
|
|
@ -178,13 +112,9 @@ export function extractFrameworkRouteFacts(
|
|||
// TypeScript's `this: T` declares the receiver, not an argument position.
|
||||
.filter((param) => param.childForFieldName('pattern')?.type !== 'this')
|
||||
.map((param) => {
|
||||
let name: Node | null = param;
|
||||
if (param.type === 'required_parameter' || param.type === 'optional_parameter')
|
||||
name = param.childForFieldName('pattern');
|
||||
if (name?.type === 'assignment_pattern') name = name.childForFieldName('left');
|
||||
return (
|
||||
(name?.type === 'identifier' && !written.has(name.text) && bindingId(name)) || null
|
||||
);
|
||||
const name = parameterPattern(param);
|
||||
const id = name?.type === 'identifier' ? bindingId(name) : undefined;
|
||||
return id && !ambiguous(id) ? id : null;
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
|
@ -196,21 +126,14 @@ export function extractFrameworkRouteFacts(
|
|||
let value: FrameworkExpression = UNKNOWN;
|
||||
if (node.type === 'identifier' || node.type === 'shorthand_property_identifier') {
|
||||
const id = bindingId(node, node.text, true);
|
||||
if (id) value = { kind: 'binding', id };
|
||||
if (id && !ambiguous(id)) value = { kind: 'binding', id };
|
||||
} else if (node.type === 'array') {
|
||||
value = {
|
||||
kind: 'array',
|
||||
elements: children(node).map((child) => expression(child, depth + 1)),
|
||||
};
|
||||
} else if (
|
||||
[
|
||||
'parenthesized_expression',
|
||||
'as_expression',
|
||||
'satisfies_expression',
|
||||
'non_null_expression',
|
||||
].includes(node.type)
|
||||
) {
|
||||
value = expression(children(node)[0], depth + 1);
|
||||
} else if (TRANSPARENT_EXPRESSION_TYPES.has(node.type)) {
|
||||
value = expression(transparentInner(node), depth + 1);
|
||||
} else if (FUNCTION_TYPES.includes(node.type)) {
|
||||
value = HANDLER;
|
||||
} else if (node.type === 'member_expression') {
|
||||
|
|
@ -253,7 +176,7 @@ export function extractFrameworkRouteFacts(
|
|||
const bind = (node: Node, value: FrameworkExpression): void => {
|
||||
if (node.type === 'identifier' || node.type === 'shorthand_property_identifier_pattern') {
|
||||
const id = bindingId(node);
|
||||
if (id) facts.bindings.push({ id, value });
|
||||
if (id && !ambiguous(id)) facts.bindings.push({ id, value });
|
||||
} else if (node.type === 'object_pattern') {
|
||||
for (const part of children(node)) {
|
||||
const key = part.type === 'pair_pattern' ? part.childForFieldName('key') : part;
|
||||
|
|
@ -277,21 +200,21 @@ export function extractFrameworkRouteFacts(
|
|||
let cjsUnknownWrite = false;
|
||||
const cjsShortcutExports: { name: string; value: FrameworkExpression }[] = [];
|
||||
const cjsExports: { name: string; value: FrameworkExpression }[] = [];
|
||||
const nodes: Node[] = [tree.rootNode];
|
||||
const nodes: { node: Node; enclosingFunction?: Node }[] = [{ node: tree.rootNode }];
|
||||
while (nodes.length) {
|
||||
const node = nodes.pop()!;
|
||||
if (node.type === 'ERROR') continue;
|
||||
nodes.push(...children(node).reverse());
|
||||
if (node.type === 'import_statement') {
|
||||
const { node, enclosingFunction } = nodes.pop()!;
|
||||
const type = node.type;
|
||||
if (type === 'ERROR') continue;
|
||||
const childFunction = LEXICAL_FUNCTION_TYPES.has(type) ? node : enclosingFunction;
|
||||
for (const child of children(node).reverse())
|
||||
nodes.push({ node: child, enclosingFunction: childFunction });
|
||||
if (type === 'import_statement') {
|
||||
// ESM decomposition already carries precise aliases/type-only flags. CJS
|
||||
// imports are intentionally handled at their AST calls to guard require.
|
||||
const position = `${node.startPosition.row + 1 + lineOffset}:${node.startPosition.column}`;
|
||||
for (const imported of importsAtPosition.get(position) ?? []) {
|
||||
if (!('localName' in imported) || !('importedName' in imported)) continue;
|
||||
const id = bindingKey(
|
||||
imported.declaredAtScope ?? parsedFile.moduleScope,
|
||||
imported.localName,
|
||||
);
|
||||
const id = importBindingKey(parsedFile, imported);
|
||||
facts.bindings.push({
|
||||
id,
|
||||
value:
|
||||
|
|
@ -304,9 +227,16 @@ export function extractFrameworkRouteFacts(
|
|||
},
|
||||
});
|
||||
}
|
||||
} else if (node.type === 'variable_declarator') {
|
||||
} else if (type === 'variable_declarator') {
|
||||
const name = node.childForFieldName('name');
|
||||
const value = node.childForFieldName('value');
|
||||
if (value && enclosingFunction) {
|
||||
const parameters = parametersOf(enclosingFunction);
|
||||
for (const target of patternBindingNames(name)) {
|
||||
const id = bindingId(target);
|
||||
if (id && parameters.has(id)) invalid.add(id);
|
||||
}
|
||||
}
|
||||
// Only a named function can be called by name, so only it carries the
|
||||
// identity and parameters call-site forwarding needs.
|
||||
if (name)
|
||||
|
|
@ -314,13 +244,14 @@ export function extractFrameworkRouteFacts(
|
|||
name,
|
||||
value && FUNCTION_TYPES.includes(value.type) ? functionValue(value) : expression(value),
|
||||
);
|
||||
} else if (
|
||||
node.type === 'function_declaration' ||
|
||||
node.type === 'generator_function_declaration'
|
||||
) {
|
||||
} else if (type === 'function_declaration' || type === 'generator_function_declaration') {
|
||||
const name = node.childForFieldName('name');
|
||||
if (name && enclosingFunction) {
|
||||
const id = bindingId(name);
|
||||
if (id && parametersOf(enclosingFunction).has(id)) invalid.add(id);
|
||||
}
|
||||
if (name) bind(name, functionValue(node));
|
||||
} else if (node.type === 'export_statement') {
|
||||
} else if (type === 'export_statement') {
|
||||
const sourceNode = node.childForFieldName('source');
|
||||
const source = sourceNode && plainString(sourceNode);
|
||||
if (node.children.some((child) => child.type === 'type')) continue;
|
||||
|
|
@ -371,31 +302,26 @@ export function extractFrameworkRouteFacts(
|
|||
}
|
||||
}
|
||||
} else if (
|
||||
node.type === 'assignment_expression' ||
|
||||
node.type === 'augmented_assignment_expression' ||
|
||||
node.type === 'update_expression' ||
|
||||
node.type === 'for_in_statement' ||
|
||||
(node.type === 'unary_expression' && node.children.some((child) => child.type === 'delete'))
|
||||
type === 'assignment_expression' ||
|
||||
type === 'augmented_assignment_expression' ||
|
||||
type === 'update_expression' ||
|
||||
type === 'for_in_statement' ||
|
||||
(type === 'unary_expression' && node.children.some((child) => child.type === 'delete'))
|
||||
) {
|
||||
const left = node.childForFieldName('left') ?? node.childForFieldName('argument');
|
||||
const right = node.childForFieldName('right');
|
||||
const object = left?.childForFieldName('object');
|
||||
const property = left?.childForFieldName('property');
|
||||
if (left?.type === 'identifier' && left.text === 'exports' && isGlobal(left, 'exports'))
|
||||
cjsShortcutDetached = true;
|
||||
const moduleExports = (candidate: Node | null | undefined): boolean =>
|
||||
candidate?.type === 'member_expression' &&
|
||||
candidate.childForFieldName('object')?.text === 'module' &&
|
||||
candidate.childForFieldName('property')?.text === 'exports' &&
|
||||
isGlobal(candidate, 'module');
|
||||
if (isCommonJsGlobal(lexical, left, 'exports')) cjsShortcutDetached = true;
|
||||
const writesExportProperty =
|
||||
moduleExports(object) || (object?.text === 'exports' && isGlobal(object, 'exports'));
|
||||
isModuleExports(lexical, object) || isCommonJsGlobal(lexical, object, 'exports');
|
||||
if (
|
||||
(left?.type === 'subscript_expression' && writesExportProperty) ||
|
||||
(node.type !== 'assignment_expression' && (moduleExports(left) || writesExportProperty))
|
||||
(type !== 'assignment_expression' &&
|
||||
(isModuleExports(lexical, left) || writesExportProperty))
|
||||
)
|
||||
cjsUnknownWrite = true;
|
||||
if (node.type === 'assignment_expression' && moduleExports(left)) {
|
||||
if (type === 'assignment_expression' && isModuleExports(lexical, left)) {
|
||||
cjsDefaultAssignments++;
|
||||
cjsExports.length = 0;
|
||||
if (right?.type === 'object') {
|
||||
|
|
@ -418,7 +344,7 @@ export function extractFrameworkRouteFacts(
|
|||
}
|
||||
} else cjsExports.push({ name: 'default', value: expression(right) });
|
||||
} else if (
|
||||
node.type === 'assignment_expression' &&
|
||||
type === 'assignment_expression' &&
|
||||
left?.type === 'member_expression' &&
|
||||
property?.type === 'property_identifier' &&
|
||||
writesExportProperty
|
||||
|
|
@ -434,31 +360,54 @@ export function extractFrameworkRouteFacts(
|
|||
cjsExports.push(record);
|
||||
}
|
||||
} else if (left) {
|
||||
const invalidate = (target: Node) => {
|
||||
if (
|
||||
target.type === 'identifier' ||
|
||||
target.type === 'shorthand_property_identifier_pattern'
|
||||
) {
|
||||
const id = bindingId(target);
|
||||
if (id) invalid.add(id);
|
||||
} else if (
|
||||
target.type === 'member_expression' ||
|
||||
target.type === 'subscript_expression'
|
||||
) {
|
||||
let receiver = target.childForFieldName('object');
|
||||
while (receiver) {
|
||||
// A namespace member can resolve to an exported allocation even
|
||||
// when the namespace itself is only a module value.
|
||||
facts.mutations.push(expression(receiver));
|
||||
if (receiver.type !== 'member_expression' && receiver.type !== 'subscript_expression')
|
||||
break;
|
||||
receiver = receiver.childForFieldName('object');
|
||||
const invalidate = (root: Node) => {
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
const target = pending.pop()!;
|
||||
if (
|
||||
target.type === 'identifier' ||
|
||||
target.type === 'shorthand_property_identifier_pattern'
|
||||
) {
|
||||
const id = bindingId(target);
|
||||
if (id) invalid.add(id);
|
||||
} else if (
|
||||
target.type === 'member_expression' ||
|
||||
target.type === 'subscript_expression'
|
||||
) {
|
||||
let receiver = target.childForFieldName('object');
|
||||
while (receiver) {
|
||||
// A namespace member can resolve to an exported allocation even
|
||||
// when the namespace itself is only a module value.
|
||||
facts.mutations.push(expression(receiver));
|
||||
if (
|
||||
receiver.type !== 'member_expression' &&
|
||||
receiver.type !== 'subscript_expression'
|
||||
)
|
||||
break;
|
||||
receiver = receiver.childForFieldName('object');
|
||||
}
|
||||
} else if (target.type === 'pair_pattern') {
|
||||
const value = target.childForFieldName('value');
|
||||
if (value) pending.push(value);
|
||||
} else if (
|
||||
target.type === 'assignment_pattern' ||
|
||||
target.type === 'object_assignment_pattern'
|
||||
) {
|
||||
const value = target.childForFieldName('left');
|
||||
if (value) pending.push(value);
|
||||
} else if (['object_pattern', 'array_pattern', 'rest_pattern'].includes(target.type)) {
|
||||
// Reverse pushes keep source order for recorded mutations.
|
||||
const items = children(target);
|
||||
for (let i = items.length - 1; i >= 0; i--) pending.push(items[i]);
|
||||
} else if (TRANSPARENT_EXPRESSION_TYPES.has(target.type)) {
|
||||
const inner = transparentInner(target);
|
||||
if (inner) pending.push(inner);
|
||||
}
|
||||
} else for (const child of children(target)) invalidate(child);
|
||||
}
|
||||
};
|
||||
invalidate(left);
|
||||
}
|
||||
} else if (node.type === 'call_expression') {
|
||||
} else if (type === 'call_expression') {
|
||||
const callee = node.childForFieldName('function');
|
||||
const method = callee?.childForFieldName('property')?.text;
|
||||
if (callee?.type === 'member_expression' && method && METHODS.has(method)) {
|
||||
|
|
|
|||
279
gitnexus/src/core/ingestion/route-extractors/lexical-bindings.ts
Normal file
279
gitnexus/src/core/ingestion/route-extractors/lexical-bindings.ts
Normal file
|
|
@ -0,0 +1,279 @@
|
|||
import type Parser from 'tree-sitter';
|
||||
import { buildPositionIndex, buildScopeTree, lookupLexicalName } from 'gitnexus-shared';
|
||||
import type { NameClaimResult, ParsedFile, ParsedImport } from 'gitnexus-shared';
|
||||
import { FUNCTION_NODE_TYPES } from '../languages/typescript/captures.js';
|
||||
|
||||
type Node = Parser.SyntaxNode;
|
||||
export interface LexicalBindings {
|
||||
ownership(node: Node, name?: string, atUse?: boolean): NameClaimResult | undefined;
|
||||
bindingId(node: Node, name?: string, atUse?: boolean): string | undefined;
|
||||
isGlobal(node: Node, name: string): boolean;
|
||||
ambiguous(bindingId: string): boolean;
|
||||
}
|
||||
|
||||
/** Callable boundaries: the TypeScript function scopes, which cover JavaScript's. */
|
||||
export const LEXICAL_FUNCTION_TYPES: ReadonlySet<string> = new Set(FUNCTION_NODE_TYPES);
|
||||
const LEXICAL_FUNCTION_TYPE_LIST: string[] = [...FUNCTION_NODE_TYPES];
|
||||
|
||||
/** Expressions that wrap a value or an assignment target without changing it. */
|
||||
export const TRANSPARENT_EXPRESSION_TYPES: ReadonlySet<string> = new Set([
|
||||
'parenthesized_expression',
|
||||
'as_expression',
|
||||
'satisfies_expression',
|
||||
'non_null_expression',
|
||||
'type_assertion',
|
||||
]);
|
||||
|
||||
/** The expression a transparent wrapper holds; `<T>x` keeps it after its type arguments. */
|
||||
export const transparentInner = (node: Node): Node | null =>
|
||||
node.namedChildren.find((child) => child.type !== 'comment' && child.type !== 'type_arguments') ??
|
||||
null;
|
||||
|
||||
/** Lexical binding identity: the declaring scope and the declared name. */
|
||||
export const bindingKey = (scopeId: string, name: string): string => `${scopeId}\0${name}`;
|
||||
|
||||
/** The binding an import declares in its file. */
|
||||
export const importBindingKey = (
|
||||
parsedFile: ParsedFile,
|
||||
imported: Extract<ParsedImport, { localName: string }>,
|
||||
): string => bindingKey(imported.declaredAtScope ?? parsedFile.moduleScope, imported.localName);
|
||||
|
||||
/** An unshadowed CommonJS `module` or `exports` reference. */
|
||||
export const isCommonJsGlobal = (
|
||||
bindings: LexicalBindings,
|
||||
node: Node | null | undefined,
|
||||
name: 'module' | 'exports',
|
||||
): boolean => node?.type === 'identifier' && node.text === name && bindings.isGlobal(node, name);
|
||||
|
||||
/** `module.exports` through an unshadowed `module`. */
|
||||
export const isModuleExports = (
|
||||
bindings: LexicalBindings,
|
||||
node: Node | null | undefined,
|
||||
): boolean =>
|
||||
node?.type === 'member_expression' &&
|
||||
node.childForFieldName('property')?.text === 'exports' &&
|
||||
isCommonJsGlobal(bindings, node.childForFieldName('object'), 'module');
|
||||
|
||||
/** The pattern a formal parameter declares, without its type or default value. */
|
||||
export function parameterPattern(node: Node | null): Node | null {
|
||||
if (node?.type === 'required_parameter' || node?.type === 'optional_parameter')
|
||||
node = node.childForFieldName('pattern');
|
||||
if (node?.type === 'assignment_pattern') node = node.childForFieldName('left');
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Visit binding positions only: property keys and default RHSs are expressions. */
|
||||
export function patternBindingNames(root: Node | null): Node[] {
|
||||
const names: Node[] = [];
|
||||
const stack = root ? [root] : [];
|
||||
while (stack.length > 0) {
|
||||
const node = stack.pop()!;
|
||||
let next: readonly (Node | null)[] = [];
|
||||
if (TRANSPARENT_EXPRESSION_TYPES.has(node.type))
|
||||
// Assignment targets may be wrapped: `(app) = x`, `(app as T) = x`, `(<T>app) = x`, `app! = x`.
|
||||
next = [transparentInner(node)];
|
||||
else
|
||||
switch (node.type) {
|
||||
case 'identifier':
|
||||
case 'shorthand_property_identifier_pattern':
|
||||
names.push(node);
|
||||
break;
|
||||
case 'required_parameter':
|
||||
case 'optional_parameter':
|
||||
next = [node.childForFieldName('pattern')];
|
||||
break;
|
||||
case 'pair_pattern':
|
||||
next = [node.childForFieldName('value')];
|
||||
break;
|
||||
case 'assignment_pattern':
|
||||
case 'object_assignment_pattern':
|
||||
next = [node.childForFieldName('left')];
|
||||
break;
|
||||
case 'rest_pattern':
|
||||
next = [node.firstNamedChild];
|
||||
break;
|
||||
case 'object_pattern':
|
||||
case 'array_pattern':
|
||||
case 'formal_parameters':
|
||||
next = node.namedChildren;
|
||||
break;
|
||||
}
|
||||
// Reverse pushes keep source order.
|
||||
for (let i = next.length - 1; i >= 0; i--) {
|
||||
const child = next[i];
|
||||
if (child) stack.push(child);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
const TYPE_SUBTREES: ReadonlySet<string> = new Set([
|
||||
'type_annotation',
|
||||
'type_parameters',
|
||||
'type_arguments',
|
||||
]);
|
||||
|
||||
/** Whether formals contain a default value or computed key (ECMAScript ContainsExpression). */
|
||||
function containsParameterExpression(parameters: Node): boolean {
|
||||
// Plain identifier parameters, the common case, need no subtree search.
|
||||
if (parameters.type === 'identifier') return false;
|
||||
const plain = parameters.namedChildren.every(
|
||||
(parameter) =>
|
||||
parameter.type === 'comment' ||
|
||||
parameter.type === 'identifier' ||
|
||||
((parameter.type === 'required_parameter' || parameter.type === 'optional_parameter') &&
|
||||
parameter.childForFieldName('value') === null &&
|
||||
['identifier', 'this'].includes(parameter.childForFieldName('pattern')?.type ?? '')),
|
||||
);
|
||||
if (plain) return false;
|
||||
return (
|
||||
parameters.descendantsOfType([
|
||||
'assignment_pattern',
|
||||
'object_assignment_pattern',
|
||||
'computed_property_name',
|
||||
]).length > 0 ||
|
||||
parameters
|
||||
.descendantsOfType(['required_parameter', 'optional_parameter'])
|
||||
.some((parameter) => parameter.childForFieldName('value') !== null)
|
||||
);
|
||||
}
|
||||
|
||||
/** `var` and function declarations of one function body, excluding nested callables. */
|
||||
function bodyDeclarations(body: Node | null): Node[] {
|
||||
const declarations: Node[] = [];
|
||||
const pending = body ? [body] : [];
|
||||
while (pending.length > 0) {
|
||||
const node = pending.pop()!;
|
||||
if (node.type === 'comment' || node.type === 'ERROR') continue;
|
||||
if (LEXICAL_FUNCTION_TYPES.has(node.type)) {
|
||||
const name = node.childForFieldName('name');
|
||||
if (
|
||||
name &&
|
||||
(node.type === 'function_declaration' || node.type === 'generator_function_declaration')
|
||||
)
|
||||
declarations.push(name);
|
||||
continue;
|
||||
}
|
||||
if (node.type === 'variable_declaration') {
|
||||
for (const declarator of node.namedChildren)
|
||||
if (declarator.type === 'variable_declarator')
|
||||
// Loops, not spread arguments: a huge pattern exceeds the argument limit.
|
||||
for (const name of patternBindingNames(declarator.childForFieldName('name')))
|
||||
declarations.push(name);
|
||||
} else if (node.type === 'for_in_statement' && node.childForFieldName('kind')?.text === 'var')
|
||||
for (const name of patternBindingNames(node.childForFieldName('left')))
|
||||
declarations.push(name);
|
||||
for (const child of node.namedChildren) pending.push(child);
|
||||
}
|
||||
return declarations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-file lexical identity shared by HTTP analyses. ParsedFile owns declarations;
|
||||
* the AST only identifies the parameter/body environment collapse it cannot model.
|
||||
*/
|
||||
export function createLexicalBindings(
|
||||
parsedFile: ParsedFile,
|
||||
lineOffset: number,
|
||||
rootNode: Node,
|
||||
): LexicalBindings {
|
||||
const scopes = buildScopeTree(parsedFile.scopes);
|
||||
const positions = buildPositionIndex(parsedFile.scopes);
|
||||
const nodeScopes = new Map<number, ReturnType<typeof positions.atPosition>>();
|
||||
// Native node getters are costly; each lookup reads `id` and `startPosition` once.
|
||||
const scopeAt = (node: Node, id = node.id, start = node.startPosition) => {
|
||||
if (nodeScopes.has(id)) return nodeScopes.get(id);
|
||||
const scope = positions.atPosition(
|
||||
parsedFile.filePath,
|
||||
start.row + 1 + lineOffset,
|
||||
start.column,
|
||||
);
|
||||
nodeScopes.set(id, scope);
|
||||
return scope;
|
||||
};
|
||||
const owners = new Map<number, Map<string, NameClaimResult | undefined>>();
|
||||
const ownership: LexicalBindings['ownership'] = (node, name = node.text, atUse = false) => {
|
||||
const id = node.id;
|
||||
const key = `${atUse ? 'use' : 'owner'}\0${name}`;
|
||||
let cached = owners.get(id);
|
||||
if (cached?.has(key)) return cached.get(key);
|
||||
if (!cached) owners.set(id, (cached = new Map()));
|
||||
const start = node.startPosition;
|
||||
const scope = scopeAt(node, id, start);
|
||||
const owner =
|
||||
scope === undefined
|
||||
? undefined
|
||||
: lookupLexicalName(
|
||||
scope,
|
||||
name,
|
||||
{ scopes },
|
||||
atUse
|
||||
? {
|
||||
purpose: 'value',
|
||||
position: { startLine: start.row + 1 + lineOffset, startCol: start.column },
|
||||
}
|
||||
: { purpose: 'value' },
|
||||
);
|
||||
cached.set(key, owner);
|
||||
return owner;
|
||||
};
|
||||
// A future claim or an explicit blocked claim is a TDZ/availability barrier.
|
||||
const blockedBefore = (claims: NameClaimResult['claims'], start: Parser.Point) =>
|
||||
claims.some(
|
||||
(claim) =>
|
||||
claim.kind === 'blocked' ||
|
||||
(claim.kind === 'binding' &&
|
||||
claim.availableFrom &&
|
||||
(claim.availableFrom.startLine > start.row + 1 + lineOffset ||
|
||||
(claim.availableFrom.startLine === start.row + 1 + lineOffset &&
|
||||
claim.availableFrom.startCol > start.column))),
|
||||
);
|
||||
const bindingId: LexicalBindings['bindingId'] = (node, name = node.text, atUse = false) => {
|
||||
const owner = ownership(node, name, atUse);
|
||||
// Imports and untyped parameters can have no BindingRef. A future claim or
|
||||
// explicit blocked claim is different: it remains a TDZ/availability barrier.
|
||||
if (atUse && owner?.status === 'blocked' && blockedBefore(owner.claims, node.startPosition))
|
||||
return undefined;
|
||||
return owner?.scope ? bindingKey(owner.scope.id, name) : undefined;
|
||||
};
|
||||
|
||||
// Parameter defaults or computed keys give the body its own variable
|
||||
// environment, which the ParsedFile collapses into one function scope. Most
|
||||
// functions have neither, so a native type search finds the few that do and
|
||||
// only their formals and bodies are walked.
|
||||
const ambiguous = new Set<string>();
|
||||
for (const fn of rootNode.descendantsOfType(LEXICAL_FUNCTION_TYPE_LIST)) {
|
||||
const parameters = fn.childForFieldName('parameters') ?? fn.childForFieldName('parameter');
|
||||
if (!parameters || !containsParameterExpression(parameters)) continue;
|
||||
let functionScope = scopes.getScope(scopeAt(parameters) ?? '');
|
||||
while (functionScope && functionScope.kind !== 'Function')
|
||||
functionScope =
|
||||
functionScope.parent === null ? undefined : scopes.getScope(functionScope.parent);
|
||||
const parameterNames = new Set(patternBindingNames(parameters).map((name) => name.text));
|
||||
const uses = new Set<string>();
|
||||
const formals = [parameters];
|
||||
while (formals.length > 0) {
|
||||
const node = formals.pop()!;
|
||||
if (node.type === 'comment' || node.type === 'ERROR' || TYPE_SUBTREES.has(node.type))
|
||||
continue;
|
||||
if (node.type === 'identifier' || node.type === 'shorthand_property_identifier') {
|
||||
const id = bindingId(node);
|
||||
if (id) uses.add(id);
|
||||
}
|
||||
for (const child of node.namedChildren) formals.push(child);
|
||||
}
|
||||
for (const declaration of bodyDeclarations(fn.childForFieldName('body'))) {
|
||||
// A var in a class static block, or a block-owned function declaration,
|
||||
// does not share this function's collapsed variable environment.
|
||||
if (ownership(declaration)?.scope?.id !== functionScope?.id) continue;
|
||||
const id = bindingId(declaration);
|
||||
if (id && (parameterNames.has(declaration.text) || uses.has(id))) ambiguous.add(id);
|
||||
}
|
||||
}
|
||||
return {
|
||||
ownership,
|
||||
bindingId,
|
||||
isGlobal: (node, name) => ownership(node, name)?.status === 'absent',
|
||||
ambiguous: (id) => ambiguous.has(id),
|
||||
};
|
||||
}
|
||||
|
|
@ -540,7 +540,8 @@ export function findReceiverTypeBinding(
|
|||
options?: NameLookupOptions,
|
||||
): TypeRef | undefined {
|
||||
const claim = lookupNameClaim(startScope, receiverName, scopes, options);
|
||||
if (claim.status !== 'absent') return claim.typeBinding;
|
||||
// An absent name keeps the type an undeclared write gave it in this scope.
|
||||
if (claim.status !== 'absent' || claim.typeBinding !== undefined) return claim.typeBinding;
|
||||
const moduleScopeId = moduleScopeIdOf(startScope, scopes);
|
||||
// Fallback 1 — named namespaces accessible from this file (own + `using`d),
|
||||
// gated by `accessibleNamespacesByScope`. Consulted BEFORE the global channel
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import {
|
||||
fetchWrapperFacts,
|
||||
type FetchWrapperCall,
|
||||
type ForwardedCallee,
|
||||
type FetchWrapperFacts,
|
||||
type FetchWrapperReexport,
|
||||
} from '../route-extractors/fetch-wrapper.js';
|
||||
import { parentPort, threadId, workerData } from 'node:worker_threads';
|
||||
import {
|
||||
|
|
@ -358,15 +358,9 @@ export interface ExtractedFetchCall {
|
|||
lineNumber: number;
|
||||
}
|
||||
|
||||
export interface FetchWrapperDef {
|
||||
export interface FetchWrapperDef extends FetchWrapperFacts {
|
||||
filePath: string;
|
||||
functionName: string;
|
||||
/** Calls fetch itself; otherwise a wrapper only through `forwardsTo`. */
|
||||
seed: boolean;
|
||||
/** Its first parameter reaches the URL argument of that fetch call. */
|
||||
forwardsUrl: boolean;
|
||||
/** Callees given this function's own first parameter as their first argument. */
|
||||
forwardsTo: ForwardedCallee[];
|
||||
}
|
||||
|
||||
/** See {@link ExtractedDecoratorRoute.handlerReceiver}. */
|
||||
|
|
@ -523,6 +517,7 @@ export interface ParseWorkerResult {
|
|||
fetchWrapperDefs: FetchWrapperDef[];
|
||||
/** URL-bearing candidates, kept separate from confirmed outward-call sinks. */
|
||||
fetchWrapperCalls?: FetchWrapperCall[];
|
||||
fetchWrapperReexports?: FetchWrapperReexport[];
|
||||
decoratorRoutes: ExtractedDecoratorRoute[];
|
||||
/** JSON-safe per-file provider facts; relationships are resolved on every run. */
|
||||
routeFacts?: { filePath: string; facts: unknown; routePosition: number }[];
|
||||
|
|
@ -1877,6 +1872,19 @@ const processFileGroup = (
|
|||
// patterns overlap with the same source range.
|
||||
const processedDefinitionNodes = new Set<string>();
|
||||
const variableInfoCache = new Map<number, Map<string, VariableInfo>>();
|
||||
// HTTP facts are all or nothing per file. A throwing hook must not escape to
|
||||
// the language-group catch, which would drop every remaining file of the
|
||||
// group; it drops only this file's HTTP facts.
|
||||
const wrapperDefs: FetchWrapperDef[] = [];
|
||||
const wrapperFunctions: { name: string; node: SyntaxNode }[] = [];
|
||||
let httpFailed = false;
|
||||
const httpFailure = (err: unknown) => {
|
||||
if (!httpFailed)
|
||||
reportWarning(
|
||||
`HTTP fact extraction failed for ${file.path}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
httpFailed = true;
|
||||
};
|
||||
|
||||
for (const match of matches) {
|
||||
const captureMap: Record<string, SyntaxNode> = {};
|
||||
|
|
@ -3162,19 +3170,26 @@ const processFileGroup = (
|
|||
}
|
||||
|
||||
// ── Fetch wrapper detection: functions that call fetch() or forward their URL ──
|
||||
if (
|
||||
nodeLabel === 'Function' &&
|
||||
definitionNode &&
|
||||
nameNode &&
|
||||
(language === SupportedLanguages.TypeScript || language === SupportedLanguages.JavaScript)
|
||||
) {
|
||||
const facts = fetchWrapperFacts(definitionNode, file.path);
|
||||
if (facts.seed || facts.forwardsTo.length > 0) {
|
||||
result.fetchWrapperDefs.push({
|
||||
filePath: file.path,
|
||||
functionName: nameNode.text,
|
||||
...facts,
|
||||
});
|
||||
if (nodeLabel === 'Function' && definitionNode && provider.extractFetchWrapperFacts) {
|
||||
wrapperFunctions.push({ name: nodeName, node: definitionNode });
|
||||
if (parsedFile && !httpFailed) {
|
||||
try {
|
||||
const facts = provider.extractFetchWrapperFacts(
|
||||
definitionNode,
|
||||
nameNode,
|
||||
parsedFile,
|
||||
lineOffset,
|
||||
);
|
||||
// Keep possible wrappers and the functions other files can name; a
|
||||
// nested non-wrapper can neither be imported nor carry a URL.
|
||||
if (
|
||||
facts &&
|
||||
(facts.seed || facts.forwardsUrl || facts.forwardsTo.length > 0 || facts.moduleScope)
|
||||
)
|
||||
wrapperDefs.push({ filePath: file.path, functionName: nodeName, ...facts });
|
||||
} catch (err) {
|
||||
httpFailure(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -3252,18 +3267,40 @@ const processFileGroup = (
|
|||
}
|
||||
}
|
||||
|
||||
if (provider.extractFetchWrapperCalls) {
|
||||
const candidates = provider.extractFetchWrapperCalls(tree, file.path, lineOffset);
|
||||
for (const candidate of candidates) (result.fetchWrapperCalls ??= []).push(candidate);
|
||||
}
|
||||
|
||||
if (parsedFile && provider.extractRouteFacts) {
|
||||
(result.routeFacts ??= []).push({
|
||||
filePath: file.path,
|
||||
facts: provider.extractRouteFacts(tree, parsedFile, lineOffset),
|
||||
routePosition,
|
||||
});
|
||||
if (parsedFile && !httpFailed) {
|
||||
try {
|
||||
const calls = provider.extractFetchWrapperCalls?.(tree, parsedFile, lineOffset);
|
||||
const reexports = provider.extractFetchWrapperReexports?.(tree, parsedFile, lineOffset);
|
||||
const routeFacts = provider.extractRouteFacts?.(tree, parsedFile, lineOffset);
|
||||
for (const call of calls ?? []) (result.fetchWrapperCalls ??= []).push(call);
|
||||
for (const reexport of reexports ?? [])
|
||||
(result.fetchWrapperReexports ??= []).push(reexport);
|
||||
if (routeFacts)
|
||||
(result.routeFacts ??= []).push({
|
||||
filePath: file.path,
|
||||
facts: routeFacts,
|
||||
routePosition,
|
||||
});
|
||||
} catch (err) {
|
||||
httpFailure(err);
|
||||
}
|
||||
}
|
||||
if (parsedFile && !httpFailed) for (const def of wrapperDefs) result.fetchWrapperDefs.push(def);
|
||||
else
|
||||
// These records stand for unknown facts. With `seed` false and nothing
|
||||
// forwarded they never prove a wrapper; they only make a name-only
|
||||
// match, a barrel or an import that may reach this file decline.
|
||||
for (const { name, node } of wrapperFunctions)
|
||||
result.fetchWrapperDefs.push({
|
||||
filePath: file.path,
|
||||
functionName: name,
|
||||
definitionId: `${file.path}:${node.startPosition.row + lineOffset + 1}:${node.startPosition.column}`,
|
||||
moduleScope: true,
|
||||
exportedNames: [name],
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [],
|
||||
});
|
||||
|
||||
// Language-specific decorator route extraction via provider hook.
|
||||
// The provider's extractDecoratorRoutes walks the AST for framework-specific
|
||||
|
|
|
|||
|
|
@ -35,6 +35,8 @@ export const mergeResult = (target: ParseWorkerResult, src: ParseWorkerResult):
|
|||
appendAll(target.fetchCalls, src.fetchCalls);
|
||||
appendAll(target.fetchWrapperDefs, src.fetchWrapperDefs);
|
||||
if (src.fetchWrapperCalls) appendAll((target.fetchWrapperCalls ??= []), src.fetchWrapperCalls);
|
||||
if (src.fetchWrapperReexports)
|
||||
appendAll((target.fetchWrapperReexports ??= []), src.fetchWrapperReexports);
|
||||
for (const file of src.routeFacts ?? [])
|
||||
(target.routeFacts ??= []).push({
|
||||
...file,
|
||||
|
|
|
|||
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/cjs-member.js
vendored
Normal file
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/cjs-member.js
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
exports.memberRequest = function (url) {
|
||||
return fetch(url);
|
||||
};
|
||||
module.exports.arrowRequest = (url) => fetch(url);
|
||||
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/cjs.js
vendored
Normal file
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/cjs.js
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
function cjsRequest(url) {
|
||||
return fetch(url);
|
||||
}
|
||||
module.exports = { cjsRequest };
|
||||
6
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/default-paren.ts
vendored
Normal file
6
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/default-paren.ts
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
function parenRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
// The parentheses are the case under test.
|
||||
// prettier-ignore
|
||||
export default (parenRequest);
|
||||
3
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/destructured.ts
vendored
Normal file
3
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/destructured.ts
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export function destructuredRequest(url: string, { fetch = globalThis.fetch } = {}) {
|
||||
return fetch(url);
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
export function distinctRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
export function distinctSend(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export * from './left';
|
||||
export * from './right';
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { distinctRequest } from './http';
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { distinctSend as distinctRequest } from './http';
|
||||
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/diamond/http.ts
vendored
Normal file
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/diamond/http.ts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
function diamondRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
export { diamondRequest, diamondRequest as diamondSend };
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/diamond/index.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/diamond/index.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export * from './left';
|
||||
export * from './right';
|
||||
1
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/diamond/left.ts
vendored
Normal file
1
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/diamond/left.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export { diamondRequest } from './http';
|
||||
1
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/diamond/right.ts
vendored
Normal file
1
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/diamond/right.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export { diamondSend as diamondRequest } from './http';
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/hooks.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/hooks.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
const memoize = <T>(fn: T): T => fn;
|
||||
export const memoRequest = memoize((url: string) => fetch(url));
|
||||
7
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/http.ts
vendored
Normal file
7
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/http.ts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
export function request(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
|
||||
export function uniqueFetch(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
3
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/ipc.ts
vendored
Normal file
3
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/ipc.ts
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export function request(channel: string) {
|
||||
return channel;
|
||||
}
|
||||
5
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/keys.ts
vendored
Normal file
5
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/keys.ts
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export function keyRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
export const api = { keyRequest: (url: string) => keyRequest(url) };
|
||||
export const loadKey = () => keyRequest('/api/key');
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/multi.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/multi.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export const retries = 0,
|
||||
multiRequest = (url: string) => fetch(url);
|
||||
6
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/overloaded.ts
vendored
Normal file
6
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/lib/overloaded.ts
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export function overloaded(url: string): Promise<Response>;
|
||||
export function overloaded(url: URL): Promise<Response>;
|
||||
export function overloaded(url: string | URL) {
|
||||
return fetch(url);
|
||||
}
|
||||
export const loadLocalOverloaded = () => overloaded('/api/overload-local');
|
||||
7
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/package.json
vendored
Normal file
7
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/package.json
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"name": "wrapper-targets",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"name": "@repo/barrel",
|
||||
"exports": "./src/index.ts"
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export function importedRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import { importedRequest } from './imported';
|
||||
export { barrelRequest } from './request';
|
||||
export * from './star';
|
||||
export { importedRequest };
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export function barrelRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export function starRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"name": "@repo/http",
|
||||
"exports": "./src/index.ts"
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export function workspaceRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
30
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/server/api.ts
vendored
Normal file
30
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/server/api.ts
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import express from 'express';
|
||||
const app = express();
|
||||
app.get('/api/relative', (_req, res) => res.json({}));
|
||||
app.get('/api/alias', (_req, res) => res.json({}));
|
||||
app.get('/api/workspace', (_req, res) => res.json({}));
|
||||
app.get('/api/forwarded', (_req, res) => res.json({}));
|
||||
app.get('/api/plain', (_req, res) => res.json({}));
|
||||
app.get('/api/plain-forwarded', (_req, res) => res.json({}));
|
||||
app.get('/api/parameter', (_req, res) => res.json({}));
|
||||
app.get('/api/local', (_req, res) => res.json({}));
|
||||
app.get('/api/nested', (_req, res) => res.json({}));
|
||||
app.get('/api/sibling', (_req, res) => res.json({}));
|
||||
app.get('/api/ambiguous', (_req, res) => res.json({}));
|
||||
app.get('/api/unique', (_req, res) => res.json({}));
|
||||
app.get('/api/overload-local', (_req, res) => res.json({}));
|
||||
app.get('/api/overload-import', (_req, res) => res.json({}));
|
||||
app.get('/api/multi', (_req, res) => res.json({}));
|
||||
app.get('/api/barrel', (_req, res) => res.json({}));
|
||||
app.get('/api/barrel-star', (_req, res) => res.json({}));
|
||||
app.get('/api/barrel-imported', (_req, res) => res.json({}));
|
||||
app.get('/api/hoc', (_req, res) => res.json({}));
|
||||
app.get('/api/cjs', (_req, res) => res.json({}));
|
||||
app.get('/api/key', (_req, res) => res.json({}));
|
||||
app.get('/api/node', (_req, res) => res.json({}));
|
||||
app.get('/api/diamond', (_req, res) => res.json({}));
|
||||
app.get('/api/diamond-distinct', (_req, res) => res.json({}));
|
||||
app.get('/api/cjs-member', (_req, res) => res.json({}));
|
||||
app.get('/api/cjs-arrow', (_req, res) => res.json({}));
|
||||
app.get('/api/destructured', (_req, res) => res.json({}));
|
||||
app.get('/api/default-paren', (_req, res) => res.json({}));
|
||||
1
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/tsconfig.json
vendored
Normal file
1
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/tsconfig.json
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{ "compilerOptions": { "baseUrl": ".", "paths": { "@http": ["lib/http.ts"] } } }
|
||||
7
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/alias.ts
vendored
Normal file
7
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/alias.ts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { request as aliasSend } from '@http';
|
||||
export const loadAlias = () => aliasSend('/api/alias');
|
||||
|
||||
function forward(url: string) {
|
||||
return aliasSend(url);
|
||||
}
|
||||
export const loadForwarded = () => forward('/api/forwarded');
|
||||
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/barrel.ts
vendored
Normal file
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/barrel.ts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import { barrelRequest, importedRequest, starRequest } from '@repo/barrel';
|
||||
export const loadBarrel = () => barrelRequest('/api/barrel');
|
||||
export const loadBarrelStar = () => starRequest('/api/barrel-star');
|
||||
export const loadBarrelImported = () => importedRequest('/api/barrel-imported');
|
||||
3
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/cjs-member.js
vendored
Normal file
3
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/cjs-member.js
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
const { memberRequest, arrowRequest } = require('../lib/cjs-member');
|
||||
exports.loadMember = () => memberRequest('/api/cjs-member');
|
||||
exports.loadArrow = () => arrowRequest('/api/cjs-arrow');
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/cjs.js
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/cjs.js
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
const { cjsRequest } = require('../lib/cjs');
|
||||
exports.loadCjs = () => cjsRequest('/api/cjs');
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/default-paren.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/default-paren.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import parenRequest from '../lib/default-paren';
|
||||
export const loadDefaultParen = () => parenRequest('/api/default-paren');
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/destructured.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/destructured.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { destructuredRequest } from '../lib/destructured';
|
||||
export const loadDestructured = () => destructuredRequest('/api/destructured');
|
||||
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/diamond.ts
vendored
Normal file
4
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/diamond.ts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import { diamondRequest } from '../lib/diamond';
|
||||
import { distinctRequest } from '../lib/diamond-distinct';
|
||||
export const loadDiamond = () => diamondRequest('/api/diamond');
|
||||
export const loadDistinct = () => distinctRequest('/api/diamond-distinct');
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/hoc.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/hoc.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { memoRequest } from '../lib/hooks';
|
||||
export const loadHoc = () => memoRequest('/api/hoc');
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/multi.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/multi.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { multiRequest } from '../lib/multi';
|
||||
export const loadMulti = () => multiRequest('/api/multi');
|
||||
11
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/nested.ts
vendored
Normal file
11
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/nested.ts
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
export function owner() {
|
||||
function nestedRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
return nestedRequest('/api/nested');
|
||||
}
|
||||
|
||||
export function sibling() {
|
||||
const nestedRequest = (channel: string) => channel;
|
||||
return nestedRequest('/api/sibling');
|
||||
}
|
||||
5
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/node.ts
vendored
Normal file
5
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/node.ts
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import fetch from 'node-fetch';
|
||||
export function nodeRequest(url: string) {
|
||||
return fetch(url);
|
||||
}
|
||||
export const loadNode = () => nodeRequest('/api/node');
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/overloaded.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/overloaded.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { overloaded } from '../lib/overloaded';
|
||||
export const loadOverloaded = () => overloaded('/api/overload-import');
|
||||
7
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/plain.ts
vendored
Normal file
7
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/plain.ts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { request } from '../lib/ipc';
|
||||
export const loadPlain = () => request('/api/plain');
|
||||
|
||||
function forwardPlain(url: string) {
|
||||
return request(url);
|
||||
}
|
||||
export const loadPlainForwarded = () => forwardPlain('/api/plain-forwarded');
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/relative.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/relative.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { request as send } from '../lib/http';
|
||||
export const loadRelative = () => send('/api/relative');
|
||||
10
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/shadow.ts
vendored
Normal file
10
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/shadow.ts
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { request } from '../lib/http';
|
||||
|
||||
export function loadParameter(request: (url: string) => unknown) {
|
||||
return request('/api/parameter');
|
||||
}
|
||||
|
||||
export function loadLocal() {
|
||||
const request = (channel: string) => channel;
|
||||
return request('/api/local');
|
||||
}
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/unresolved.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/unresolved.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export const loadAmbiguous = () => request('/api/ambiguous');
|
||||
export const loadUnique = () => uniqueFetch('/api/unique');
|
||||
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/workspace.ts
vendored
Normal file
2
gitnexus/test/fixtures/lang-resolution/fetch-wrapper-target-identity/web/workspace.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { workspaceRequest as send } from '@repo/http';
|
||||
export const loadWorkspace = () => send('/api/workspace');
|
||||
|
|
@ -68,3 +68,53 @@ describe('Base-URL wrapper consumer FETCHES edge extraction', () => {
|
|||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Fetch wrapper lexical and project target identity', () => {
|
||||
it('resolves relative, alias, workspace, barrel, export-alias diamond, overload, multi-declarator, HOC, CommonJS and package-fetch targets while rejecting shadowed and ambiguous names', async () => {
|
||||
const result = await runPipelineFromRepo(
|
||||
path.join(FIXTURES, 'fetch-wrapper-target-identity'),
|
||||
() => {},
|
||||
{ skipGraphPhases: true },
|
||||
);
|
||||
const edges = getRelationships(result, 'FETCHES')
|
||||
.map((edge) => `${edge.sourceFilePath} -> ${edge.target}`)
|
||||
.sort();
|
||||
expect(edges).toEqual([
|
||||
'lib/keys.ts -> /api/key',
|
||||
'lib/overloaded.ts -> /api/overload-local',
|
||||
'web/alias.ts -> /api/alias',
|
||||
'web/alias.ts -> /api/forwarded',
|
||||
'web/barrel.ts -> /api/barrel',
|
||||
'web/barrel.ts -> /api/barrel-imported',
|
||||
'web/barrel.ts -> /api/barrel-star',
|
||||
'web/cjs-member.js -> /api/cjs-arrow',
|
||||
'web/cjs-member.js -> /api/cjs-member',
|
||||
'web/cjs.js -> /api/cjs',
|
||||
'web/default-paren.ts -> /api/default-paren',
|
||||
'web/destructured.ts -> /api/destructured',
|
||||
'web/diamond.ts -> /api/diamond',
|
||||
'web/hoc.ts -> /api/hoc',
|
||||
'web/multi.ts -> /api/multi',
|
||||
'web/nested.ts -> /api/nested',
|
||||
'web/node.ts -> /api/node',
|
||||
'web/overloaded.ts -> /api/overload-import',
|
||||
'web/relative.ts -> /api/relative',
|
||||
'web/unresolved.ts -> /api/unique',
|
||||
'web/workspace.ts -> /api/workspace',
|
||||
]);
|
||||
}, 60000);
|
||||
|
||||
it('honors explicit wrapper names through local parameter bindings', async () => {
|
||||
const result = await runPipelineFromRepo(
|
||||
path.join(FIXTURES, 'fetch-wrapper-target-identity'),
|
||||
() => {},
|
||||
{ skipGraphPhases: true, fetchWrappers: ['request'] },
|
||||
);
|
||||
const edges = getRelationships(result, 'FETCHES');
|
||||
expect(
|
||||
edges.some(
|
||||
(edge) => edge.sourceFilePath === 'web/shadow.ts' && edge.target === '/api/parameter',
|
||||
),
|
||||
).toBe(true);
|
||||
}, 60000);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -0,0 +1,231 @@
|
|||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { createWorkerPool } from '../../../src/core/ingestion/workers/worker-pool.js';
|
||||
import type { ParseWorkerResult } from '../../../src/core/ingestion/workers/parse-worker.js';
|
||||
import {
|
||||
loadParseCache,
|
||||
loadParseCacheChunk,
|
||||
pruneCache,
|
||||
saveParseCache,
|
||||
type ParseCache,
|
||||
} from '../../../src/storage/parse-cache.js';
|
||||
import {
|
||||
clearParsedFileStore,
|
||||
getDurableParsedFileDir,
|
||||
loadDurableParsedFileIndex,
|
||||
pruneAndSaveDurableParsedFileStore,
|
||||
} from '../../../src/storage/parsedfile-store.js';
|
||||
import { runtimeParseIdentity } from '../../helpers/runtime-parse-identity.js';
|
||||
import { runPipelineFromRepo, writeFixtureRepo, type PipelineResult } from './helpers.js';
|
||||
|
||||
const realWorker = new URL('../../../dist/core/ingestion/workers/parse-worker.js', import.meta.url);
|
||||
const providerModule = new URL(
|
||||
'../../../dist/core/ingestion/languages/typescript.js',
|
||||
import.meta.url,
|
||||
);
|
||||
const temporary: string[] = [];
|
||||
const tempDirectory = () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-wrapper-persistence-'));
|
||||
temporary.push(directory);
|
||||
return directory;
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of temporary.splice(0))
|
||||
fs.rmSync(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
||||
});
|
||||
|
||||
function fetchEdges(result: PipelineResult): string[] {
|
||||
return [...result.graph.iterRelationships()]
|
||||
.filter((edge) => edge.type === 'FETCHES')
|
||||
.map(
|
||||
(edge) => `${result.graph.getNode(edge.sourceId)?.properties.filePath} -> ${edge.targetId}`,
|
||||
)
|
||||
.sort();
|
||||
}
|
||||
|
||||
describe('fetch-wrapper facts across workers and persistent caches', () => {
|
||||
it('reuses raw identity facts on warm runs and re-resolves changed project aliases', async () => {
|
||||
const identity = await runtimeParseIdentity();
|
||||
const directory = tempDirectory();
|
||||
const repo = path.join(directory, 'repo');
|
||||
const storage = path.join(directory, 'storage');
|
||||
const marker = path.join(directory, 'worker.jsonl');
|
||||
const workerPath = path.join(directory, 'observed-worker.mjs');
|
||||
fs.writeFileSync(
|
||||
workerPath,
|
||||
`
|
||||
import fs from 'node:fs';
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
const send = parentPort.postMessage.bind(parentPort);
|
||||
parentPort.postMessage = (message, ...rest) => {
|
||||
if (message.type === 'result') fs.appendFileSync(${JSON.stringify(marker)}, JSON.stringify({
|
||||
definitions: message.data.fetchWrapperDefs,
|
||||
calls: message.data.fetchWrapperCalls,
|
||||
}) + '\\n');
|
||||
return send(message, ...rest);
|
||||
};
|
||||
await import(${JSON.stringify(realWorker.href)});
|
||||
`,
|
||||
);
|
||||
const config = (target: string) =>
|
||||
JSON.stringify({
|
||||
compilerOptions: { baseUrl: '.', paths: { '@http': [target] } },
|
||||
});
|
||||
const files = {
|
||||
'tsconfig.json': config('./lib/http.ts'),
|
||||
'lib/http.ts':
|
||||
'export function request(url, fetch = globalThis.fetch) { return fetch(url); }',
|
||||
'lib/plain.ts': 'export function request(url) { return url; }',
|
||||
'lib/forward.ts':
|
||||
"import { request as send } from '@http'; export function forward(url) { return send(url); }",
|
||||
'pages/client.ts':
|
||||
"import { forward as send } from '../lib/forward'; send('/api/items'); export function blocked(send) { return send('/api/blocked'); }",
|
||||
// A barrel on the warm path: its re-export facts come back from the cache.
|
||||
'lib/index.ts': "export * from './forward';",
|
||||
'pages/barrel.ts': "import { forward } from '../lib'; forward('/api/barrel');",
|
||||
'app/api/items/route.ts': 'export function GET() { return new Response(); }',
|
||||
'app/api/barrel/route.ts': 'export function GET() { return new Response(); }',
|
||||
'app/api/blocked/route.ts': 'export function GET() { return new Response(); }',
|
||||
};
|
||||
writeFixtureRepo(repo, files);
|
||||
const parsedCount = Object.keys(files).length - 1;
|
||||
const run = (parseCache: ParseCache) =>
|
||||
runPipelineFromRepo(repo, () => {}, {
|
||||
workerPoolSize: 1,
|
||||
skipGraphPhases: true,
|
||||
workerUrlForTest: pathToFileURL(workerPath),
|
||||
parseCache,
|
||||
});
|
||||
const persist = async (cache: ParseCache) => {
|
||||
pruneCache(cache, cache.usedKeys);
|
||||
const keys = await saveParseCache(storage, cache);
|
||||
await pruneAndSaveDurableParsedFileStore(
|
||||
getDurableParsedFileDir(storage),
|
||||
identity.base,
|
||||
new Set(keys),
|
||||
);
|
||||
await clearParsedFileStore(storage);
|
||||
};
|
||||
const coldCache = await loadParseCache(storage, identity, storage);
|
||||
const cold = await run(coldCache);
|
||||
expect(cold.usedWorkerPool).toBe(true);
|
||||
expect(cold.reparsedFileCount).toBe(parsedCount);
|
||||
expect(fetchEdges(cold)).toEqual([
|
||||
'pages/barrel.ts -> Route:/api/barrel',
|
||||
'pages/client.ts -> Route:/api/items',
|
||||
]);
|
||||
const observed = fs
|
||||
.readFileSync(marker, 'utf8')
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(
|
||||
(line) =>
|
||||
JSON.parse(line) as {
|
||||
definitions: ParseWorkerResult['fetchWrapperDefs'];
|
||||
calls: ParseWorkerResult['fetchWrapperCalls'];
|
||||
},
|
||||
);
|
||||
expect(observed.flatMap((part) => part.definitions)).toContainEqual(
|
||||
expect.objectContaining({
|
||||
filePath: 'lib/plain.ts',
|
||||
functionName: 'request',
|
||||
seed: false,
|
||||
definitionId: expect.any(String),
|
||||
bindingId: expect.any(String),
|
||||
}),
|
||||
);
|
||||
expect(observed.flatMap((part) => part.calls)).toContainEqual(
|
||||
expect.objectContaining({
|
||||
filePath: 'pages/client.ts',
|
||||
target: { kind: 'import', specifier: '../lib/forward', importedName: 'forward' },
|
||||
}),
|
||||
);
|
||||
await persist(coldCache);
|
||||
const durable = await loadDurableParsedFileIndex(
|
||||
getDurableParsedFileDir(storage),
|
||||
identity.base,
|
||||
);
|
||||
expect([...durable.values()].flatMap((paths) => [...paths])).toHaveLength(parsedCount);
|
||||
|
||||
const warmCache = await loadParseCache(storage, identity, storage);
|
||||
expect(warmCache.entries.size).toBe(0);
|
||||
const chunks = await Promise.all(
|
||||
[...warmCache.onDiskKeys!].map((key) => loadParseCacheChunk(warmCache, key)),
|
||||
);
|
||||
const parts = chunks.flatMap((chunk) => chunk ?? []);
|
||||
expect(parts.flatMap((part) => part.parsedFiles ?? [])).toEqual([]);
|
||||
expect(parts.flatMap((part) => part.fetchWrapperDefs ?? [])).toContainEqual(
|
||||
expect.objectContaining({
|
||||
filePath: 'lib/forward.ts',
|
||||
forwardsTo: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
target: { kind: 'import', specifier: '@http', importedName: 'request' },
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
fs.rmSync(marker);
|
||||
const warm = await run(warmCache);
|
||||
expect(warm.usedWorkerPool).toBe(false);
|
||||
expect(warm.reparsedFileCount).toBe(0);
|
||||
expect(warm.parseCacheHitFileCount).toBe(parsedCount);
|
||||
expect(fs.existsSync(marker)).toBe(false);
|
||||
expect(fetchEdges(warm)).toEqual(fetchEdges(cold));
|
||||
await persist(warmCache);
|
||||
|
||||
writeFixtureRepo(repo, { 'tsconfig.json': config('./lib/plain.ts') });
|
||||
const changed = await run(await loadParseCache(storage, identity, storage));
|
||||
expect(fetchEdges(changed)).toEqual([]);
|
||||
}, 180000);
|
||||
|
||||
it('omits scope-dependent HTTP facts when extraction fails but retains definitions and the failure receipt', async () => {
|
||||
const directory = tempDirectory();
|
||||
const workerPath = path.join(directory, 'failed-scope-worker.mjs');
|
||||
fs.writeFileSync(
|
||||
workerPath,
|
||||
`
|
||||
const { typescriptProvider } = await import(${JSON.stringify(providerModule.href)});
|
||||
typescriptProvider.emitScopeCaptures = () => { throw new Error('deliberate scope extraction failure'); };
|
||||
await import(${JSON.stringify(realWorker.href)});
|
||||
`,
|
||||
);
|
||||
const pool = createWorkerPool(pathToFileURL(workerPath), 1);
|
||||
try {
|
||||
const results = await pool.dispatch<{ path: string; content: string }, ParseWorkerResult>([
|
||||
{
|
||||
path: 'failed.ts',
|
||||
content: "export function request(url) { return fetch(url); } request('/api/items');",
|
||||
},
|
||||
]);
|
||||
expect(results.flatMap((result) => result.scopeExtractionFailures ?? [])).toEqual([
|
||||
'failed.ts',
|
||||
]);
|
||||
expect(results.flatMap((result) => result.nodes)).toContainEqual(
|
||||
expect.objectContaining({
|
||||
label: 'Function',
|
||||
properties: expect.objectContaining({ name: 'request' }),
|
||||
}),
|
||||
);
|
||||
// Without facts the function still names its export, so a name-only
|
||||
// match elsewhere declines instead of becoming unique.
|
||||
expect(results.flatMap((result) => result.fetchWrapperDefs)).toEqual([
|
||||
expect.objectContaining({
|
||||
filePath: 'failed.ts',
|
||||
functionName: 'request',
|
||||
moduleScope: true,
|
||||
exportedNames: ['request'],
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [],
|
||||
}),
|
||||
]);
|
||||
expect(results.flatMap((result) => result.fetchWrapperCalls ?? [])).toEqual([]);
|
||||
} finally {
|
||||
await pool.terminate();
|
||||
}
|
||||
}, 180000);
|
||||
});
|
||||
|
|
@ -2,21 +2,46 @@ import { describe, expect, it } from 'vitest';
|
|||
import Parser from 'tree-sitter';
|
||||
import JavaScript from 'tree-sitter-javascript';
|
||||
import TypeScript from 'tree-sitter-typescript';
|
||||
import {
|
||||
extractFetchWrapperCalls,
|
||||
fetchWrapperFacts,
|
||||
} from '../../src/core/ingestion/route-extractors/fetch-wrapper.js';
|
||||
import { createFetchWrapperContext } from '../../src/core/ingestion/route-extractors/fetch-wrapper.js';
|
||||
|
||||
for (const [name, grammar] of [
|
||||
['JavaScript', JavaScript],
|
||||
['TypeScript', TypeScript.typescript],
|
||||
['TSX', TypeScript.tsx],
|
||||
] as const) {
|
||||
import { extractParsedFile } from '../../src/core/ingestion/scope-extractor-bridge.js';
|
||||
import {
|
||||
typescriptProvider,
|
||||
javascriptProvider,
|
||||
} from '../../src/core/ingestion/languages/typescript.js';
|
||||
|
||||
const grammars = [
|
||||
['JavaScript', JavaScript, javascriptProvider],
|
||||
['TypeScript', TypeScript.typescript, typescriptProvider],
|
||||
['TSX', TypeScript.tsx, typescriptProvider],
|
||||
] as const;
|
||||
|
||||
function harness(grammar: (typeof grammars)[number][1], provider: (typeof grammars)[number][2]) {
|
||||
const parser = new Parser();
|
||||
parser.setLanguage(grammar);
|
||||
const context = (source: string, filePath = 'consumer.ts', lineOffset = 0) => {
|
||||
const fullSource = '\n'.repeat(lineOffset) + source;
|
||||
const tree = parser.parse(source);
|
||||
const parsedFile = extractParsedFile(
|
||||
provider,
|
||||
fullSource,
|
||||
filePath,
|
||||
undefined,
|
||||
parser.parse(fullSource),
|
||||
)!;
|
||||
return {
|
||||
root: tree.rootNode,
|
||||
context: createFetchWrapperContext(tree, parsedFile, lineOffset),
|
||||
};
|
||||
};
|
||||
const extract = (source: string, lineOffset = 0) =>
|
||||
context(source, 'consumer.ts', lineOffset).context.calls();
|
||||
return { context, extract };
|
||||
}
|
||||
|
||||
for (const [name, grammar, provider] of grammars) {
|
||||
describe(`${name} fetch wrapper calls`, () => {
|
||||
const parser = new Parser();
|
||||
parser.setLanguage(grammar);
|
||||
const extract = (source: string, lineOffset = 0) =>
|
||||
extractFetchWrapperCalls(parser.parse(source), 'consumer.ts', lineOffset);
|
||||
const { context, extract } = harness(grammar, provider);
|
||||
|
||||
it('preserves exact callee names and source lines, including comments and optional calls', () => {
|
||||
expect(
|
||||
|
|
@ -35,24 +60,28 @@ for (const [name, grammar] of [
|
|||
functionName: 'doRequest',
|
||||
fetchURL: '/api/one',
|
||||
lineNumber: 12,
|
||||
target: { kind: 'unresolved' },
|
||||
},
|
||||
{
|
||||
filePath: 'consumer.ts',
|
||||
functionName: 'client.doRequest',
|
||||
fetchURL: '/api/two',
|
||||
lineNumber: 13,
|
||||
target: { kind: 'member' },
|
||||
},
|
||||
{
|
||||
filePath: 'consumer.ts',
|
||||
functionName: 'api.client.doRequest',
|
||||
fetchURL: '/api/three',
|
||||
lineNumber: 14,
|
||||
target: { kind: 'member' },
|
||||
},
|
||||
{
|
||||
filePath: 'consumer.ts',
|
||||
functionName: 'cafédoRequest',
|
||||
fetchURL: '/api/four',
|
||||
lineNumber: 15,
|
||||
target: { kind: 'unresolved' },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
|
@ -66,12 +95,20 @@ for (const [name, grammar] of [
|
|||
source: `async function load(url) {
|
||||
try { for (;;) { if (url) { const r = await fetch(url); return r; } } } catch (e) {}
|
||||
}`,
|
||||
facts: { seed: true, forwardsUrl: true, forwardsTo: [{ callee: 'fetch', module: null }] },
|
||||
facts: {
|
||||
seed: true,
|
||||
forwardsUrl: true,
|
||||
forwardsTo: [{ callee: 'fetch', kind: 'unresolved' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
shape: 'an exported arrow const',
|
||||
source: 'export const load = async (url) => { const r = await fetch(url); return r; };',
|
||||
facts: { seed: true, forwardsUrl: true, forwardsTo: [{ callee: 'fetch', module: null }] },
|
||||
facts: {
|
||||
seed: true,
|
||||
forwardsUrl: true,
|
||||
forwardsTo: [{ callee: 'fetch', kind: 'unresolved' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
shape: 'an alias of globalThis.fetch',
|
||||
|
|
@ -82,7 +119,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: true,
|
||||
forwardsUrl: true,
|
||||
forwardsTo: [{ callee: 'fetchImpl', module: null }],
|
||||
forwardsTo: [{ callee: 'fetchImpl', kind: 'binding' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -91,7 +128,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: true,
|
||||
forwardsUrl: true,
|
||||
forwardsTo: [{ callee: 'window.fetch', module: null }],
|
||||
forwardsTo: [{ callee: 'window.fetch', kind: 'member' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -107,7 +144,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: true,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [{ callee: 'JSON.stringify', module: null }],
|
||||
forwardsTo: [{ callee: 'JSON.stringify', kind: 'member' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -118,7 +155,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [{ callee: 'resilientFetch', module: null }],
|
||||
forwardsTo: [{ callee: 'resilientFetch', kind: 'unresolved' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -145,7 +182,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [{ callee: 'fetchImpl', module: null }],
|
||||
forwardsTo: [{ callee: 'fetchImpl', kind: 'binding' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -157,7 +194,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [{ callee: 'send', module: null }],
|
||||
forwardsTo: [{ callee: 'send', kind: 'unresolved' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -170,7 +207,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [{ callee: 'fetchImpl', module: null }],
|
||||
forwardsTo: [{ callee: 'fetchImpl', kind: 'binding' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -187,7 +224,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [{ callee: 'window.fetch', module: null }],
|
||||
forwardsTo: [{ callee: 'window.fetch', kind: 'member' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -199,7 +236,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [{ callee: 'register', module: null }],
|
||||
forwardsTo: [{ callee: 'register', kind: 'unresolved' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -214,7 +251,7 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [{ callee: 'request', module: 'src/desktop/ipc' }],
|
||||
forwardsTo: [{ callee: 'send', kind: 'import' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -224,29 +261,31 @@ for (const [name, grammar] of [
|
|||
facts: {
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [{ callee: 'request', module: 'src/web/client' }],
|
||||
forwardsTo: [{ callee: 'request', kind: 'binding' }],
|
||||
},
|
||||
},
|
||||
])('reads wrapper facts from $shape', ({ source, facts }) => {
|
||||
const root = parser.parse(source).rootNode;
|
||||
expect(fetchWrapperFacts(root.namedChildren.at(-1)!, 'src/web/client.ts')).toEqual(facts);
|
||||
const { root, context: wrapper } = context(source, 'src/web/client.ts');
|
||||
const actual = wrapper.facts(root.namedChildren[root.namedChildren.length - 1]);
|
||||
// Exact facts, with each forwarded callee's target kind.
|
||||
expect({
|
||||
seed: actual?.seed,
|
||||
forwardsUrl: actual?.forwardsUrl,
|
||||
forwardsTo: actual?.forwardsTo.map(({ callee, target }) => ({ callee, kind: target.kind })),
|
||||
}).toEqual(facts);
|
||||
});
|
||||
|
||||
it('records the module declaring a bare callee', () => {
|
||||
expect(
|
||||
extractFetchWrapperCalls(
|
||||
parser.parse(`import { request as send } from './api';
|
||||
send('/api/one');
|
||||
local('/api/two');
|
||||
api.request('/api/three');
|
||||
function local(u) {}`),
|
||||
'src/web/page.ts',
|
||||
0,
|
||||
).map(({ functionName, module, declaredName }) => ({ functionName, module, declaredName })),
|
||||
).toEqual([
|
||||
{ functionName: 'send', module: 'src/web/api', declaredName: 'request' },
|
||||
{ functionName: 'local', module: 'src/web/page', declaredName: undefined },
|
||||
{ functionName: 'api.request', module: undefined, declaredName: undefined },
|
||||
it('records lexical and import identity of bare callees', () => {
|
||||
const source = `import { request as send } from './api';
|
||||
send('/api/one'); local('/api/two'); api.request('/api/three'); function local(u) {}`;
|
||||
const calls = context(source, 'src/web/page.ts').context.calls();
|
||||
expect(calls.map(({ functionName, target }) => ({ functionName, target }))).toEqual([
|
||||
{
|
||||
functionName: 'send',
|
||||
target: { kind: 'import', specifier: './api', importedName: 'request' },
|
||||
},
|
||||
{ functionName: 'local', target: { kind: 'binding', bindingId: expect.any(String) } },
|
||||
{ functionName: 'api.request', target: { kind: 'member' } },
|
||||
]);
|
||||
});
|
||||
|
||||
|
|
@ -290,40 +329,45 @@ for (const [name, grammar] of [
|
|||
])('does not invent a candidate for %s', (source) => {
|
||||
expect(extract(source)).toEqual([]);
|
||||
});
|
||||
|
||||
if (name !== 'JavaScript') {
|
||||
it.each([
|
||||
'Array<{ result: Promise<string> }>',
|
||||
'(value: string) => Promise<{ kind: "thing" }>',
|
||||
'{ compare: ">"; callback: () => void }',
|
||||
'[string, number]',
|
||||
'T extends string ? Array<T> : never',
|
||||
])('accepts type arguments %s', (types) => {
|
||||
expect(extract(`doRequest<${types}>('/api/things')`)).toMatchObject([
|
||||
{ functionName: 'doRequest', fetchURL: '/api/things' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles awaited generic calls in the installed grammar', () => {
|
||||
expect(
|
||||
extract(`async function load() {
|
||||
await /* request */ doRequest<string[]>('/api/one');
|
||||
await client.doRequest<() => void>('/api/two');
|
||||
}`).map((call) => [call.functionName, call.fetchURL]),
|
||||
).toEqual([
|
||||
['doRequest', '/api/one'],
|
||||
['client.doRequest', '/api/two'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('captures only the actual callee after generic references', () => {
|
||||
expect(
|
||||
extract(`
|
||||
const typed = doRequest<string>;
|
||||
const load: typeof doRequest<string> = makeLoader<string>('/api/things');
|
||||
`).map((call) => call.functionName),
|
||||
).toEqual(['makeLoader']);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Type arguments exist only in the TypeScript grammars.
|
||||
for (const [name, grammar, provider] of grammars.slice(1)) {
|
||||
describe(`${name} typed fetch wrapper calls`, () => {
|
||||
const { extract } = harness(grammar, provider);
|
||||
|
||||
it.each([
|
||||
'Array<{ result: Promise<string> }>',
|
||||
'(value: string) => Promise<{ kind: "thing" }>',
|
||||
'{ compare: ">"; callback: () => void }',
|
||||
'[string, number]',
|
||||
'T extends string ? Array<T> : never',
|
||||
])('accepts type arguments %s', (types) => {
|
||||
expect(extract(`doRequest<${types}>('/api/things')`)).toMatchObject([
|
||||
{ functionName: 'doRequest', fetchURL: '/api/things' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles awaited generic calls in the installed grammar', () => {
|
||||
expect(
|
||||
extract(`async function load() {
|
||||
await /* request */ doRequest<string[]>('/api/one');
|
||||
await client.doRequest<() => void>('/api/two');
|
||||
}`).map((call) => [call.functionName, call.fetchURL]),
|
||||
).toEqual([
|
||||
['doRequest', '/api/one'],
|
||||
['client.doRequest', '/api/two'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('captures only the actual callee after generic references', () => {
|
||||
expect(
|
||||
extract(`
|
||||
const typed = doRequest<string>;
|
||||
const load: typeof doRequest<string> = makeLoader<string>('/api/things');
|
||||
`).map((call) => call.functionName),
|
||||
).toEqual(['makeLoader']);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
|||
516
gitnexus/test/unit/fetch-wrapper-index.test.ts
Normal file
516
gitnexus/test/unit/fetch-wrapper-index.test.ts
Normal file
|
|
@ -0,0 +1,516 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildFetchWrapperIndex,
|
||||
resolveFetchWrapperTargets,
|
||||
} from '../../src/core/ingestion/route-extractors/fetch-wrapper-index.js';
|
||||
import type {
|
||||
CalleeTarget,
|
||||
FetchWrapperCall,
|
||||
FetchWrapperReexport,
|
||||
} from '../../src/core/ingestion/route-extractors/fetch-wrapper.js';
|
||||
import type { FetchWrapperDef } from '../../src/core/ingestion/workers/parse-worker.js';
|
||||
|
||||
function definition(id: string, overrides: Partial<FetchWrapperDef> = {}): FetchWrapperDef {
|
||||
return {
|
||||
filePath: 'client.ts',
|
||||
functionName: 'request',
|
||||
definitionId: id,
|
||||
bindingId: id,
|
||||
moduleScope: true,
|
||||
exportedNames: ['request'],
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function call(target: CalleeTarget, functionName = 'request'): FetchWrapperCall {
|
||||
return { filePath: 'client.ts', functionName, target, fetchURL: '/api/items', lineNumber: 1 };
|
||||
}
|
||||
|
||||
describe('fetch wrapper target classification', () => {
|
||||
it('uses the local binding rather than a same-named wrapper elsewhere', () => {
|
||||
const index = buildFetchWrapperIndex([
|
||||
definition('wrapper', { seed: true }),
|
||||
definition('plain', { moduleScope: false, exportedNames: [] }),
|
||||
]);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'wrapper' }))).toBe(true);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'plain' }))).toBe(false);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'parameter' }))).toBe(false);
|
||||
expect(index.isWrapperCall(call({ kind: 'blocked' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('includes file identity when classifying bindings', () => {
|
||||
const index = buildFetchWrapperIndex([
|
||||
definition('same', { filePath: 'other.ts', seed: true }),
|
||||
]);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'same' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('requires one declaration for a binding, independently of duplicate captures', () => {
|
||||
const wrapper = definition('one', { seed: true });
|
||||
expect(
|
||||
buildFetchWrapperIndex([wrapper, { ...wrapper }]).isWrapperCall(
|
||||
call({ kind: 'binding', bindingId: 'one' }),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
buildFetchWrapperIndex([
|
||||
wrapper,
|
||||
definition('two', { bindingId: 'one', seed: true }),
|
||||
]).isWrapperCall(call({ kind: 'binding', bindingId: 'one' })),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('resolves renamed imports to the exported name in the actual module', () => {
|
||||
const index = buildFetchWrapperIndex([
|
||||
definition('wrapper', {
|
||||
filePath: 'http.ts',
|
||||
functionName: 'send',
|
||||
exportedNames: ['request', 'default'],
|
||||
seed: true,
|
||||
}),
|
||||
definition('nested', {
|
||||
filePath: 'http.ts',
|
||||
moduleScope: false,
|
||||
exportedNames: [],
|
||||
seed: true,
|
||||
}),
|
||||
definition('plain', { filePath: 'ipc.ts' }),
|
||||
]);
|
||||
expect(
|
||||
index.isWrapperCall(
|
||||
call({ kind: 'resolved-import', filePath: 'http.ts', importedName: 'request' }, 'renamed'),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
index.isWrapperCall(
|
||||
call(
|
||||
{ kind: 'resolved-import', filePath: 'http.ts', importedName: 'default' },
|
||||
'defaultClient',
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
index.isWrapperCall(
|
||||
call({ kind: 'resolved-import', filePath: 'http.ts', importedName: 'send' }),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
index.isWrapperCall(
|
||||
call({ kind: 'resolved-import', filePath: 'ipc.ts', importedName: 'request' }),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
index.isWrapperCall(
|
||||
call({ kind: 'resolved-import', filePath: 'missing.ts', importedName: 'request' }),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('does not mistake a nested homonym for a module export', () => {
|
||||
const index = buildFetchWrapperIndex([
|
||||
definition('nested', { moduleScope: false, exportedNames: ['request'], seed: true }),
|
||||
]);
|
||||
expect(
|
||||
index.isWrapperCall(
|
||||
call({ kind: 'resolved-import', filePath: 'client.ts', importedName: 'request' }),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'declines unresolved names with two definitions, second seed=%s',
|
||||
(seed) => {
|
||||
const index = buildFetchWrapperIndex([
|
||||
definition('one', { seed: true }),
|
||||
definition('two', { filePath: 'other.ts', seed }),
|
||||
]);
|
||||
expect(index.isWrapperCall(call({ kind: 'unresolved' }))).toBe(false);
|
||||
expect(
|
||||
index.isWrapperCall(
|
||||
call({ kind: 'import', specifier: 'missing', importedName: 'request' }, 'renamed'),
|
||||
),
|
||||
).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it('permits unique unresolved fallback while duplicate captures remain one definition', () => {
|
||||
const wrapper = definition('one', { seed: true });
|
||||
const index = buildFetchWrapperIndex([wrapper, { ...wrapper }]);
|
||||
expect(index.isWrapperCall(call({ kind: 'unresolved' }))).toBe(true);
|
||||
expect(
|
||||
index.isWrapperCall(
|
||||
call({ kind: 'import', specifier: 'missing', importedName: 'request' }, 'renamed'),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(index.isWrapperCall(call({ kind: 'unresolved' }, 'missing'))).toBe(false);
|
||||
});
|
||||
|
||||
it('matches configured names before checking local or blocked bindings', () => {
|
||||
const index = buildFetchWrapperIndex([], ['request']);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'parameter' }))).toBe(true);
|
||||
expect(index.isWrapperCall(call({ kind: 'blocked' }))).toBe(true);
|
||||
expect(
|
||||
buildFetchWrapperIndex([]).isWrapperCall(call({ kind: 'binding', bindingId: 'parameter' })),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('preserves member-call name matching across duplicate names', () => {
|
||||
const index = buildFetchWrapperIndex([
|
||||
definition('one', { functionName: 'api.request', seed: true }),
|
||||
definition('two', { functionName: 'api.request' }),
|
||||
]);
|
||||
expect(index.isWrapperCall(call({ kind: 'member' }, 'api.request'))).toBe(true);
|
||||
expect(index.isWrapperCall(call({ kind: 'member' }, 'api.other'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetch wrapper forwarding propagation', () => {
|
||||
it('distinguishes a seed from a URL carrier', () => {
|
||||
const index = buildFetchWrapperIndex([
|
||||
definition('track', { functionName: 'track', seed: true }),
|
||||
definition('outer', {
|
||||
forwardsTo: [{ callee: 'track', target: { kind: 'binding', bindingId: 'track' } }],
|
||||
}),
|
||||
]);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'track' }, 'track'))).toBe(true);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'outer' }))).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a unique carrier', [], true],
|
||||
['a same-named collision', [definition('other', { functionName: 'send' })], false],
|
||||
])('uses the same unique fallback for forwarding with %s', (_shape, collisions, expected) => {
|
||||
const index = buildFetchWrapperIndex([
|
||||
definition('carrier', { functionName: 'send', forwardsUrl: true }),
|
||||
definition('outer', { forwardsTo: [{ callee: 'send', target: { kind: 'unresolved' } }] }),
|
||||
...collisions,
|
||||
]);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'outer' }))).toBe(expected);
|
||||
});
|
||||
|
||||
it('propagates imported identity and configured overrides through forwarding', () => {
|
||||
const index = buildFetchWrapperIndex(
|
||||
[
|
||||
definition('carrier', {
|
||||
filePath: 'http.ts',
|
||||
functionName: 'send',
|
||||
exportedNames: ['request'],
|
||||
forwardsUrl: true,
|
||||
}),
|
||||
definition('imported', {
|
||||
forwardsTo: [
|
||||
{
|
||||
callee: 'renamed',
|
||||
target: { kind: 'resolved-import', filePath: 'http.ts', importedName: 'request' },
|
||||
},
|
||||
],
|
||||
}),
|
||||
definition('configured', {
|
||||
forwardsTo: [{ callee: 'custom', target: { kind: 'binding', bindingId: 'parameter' } }],
|
||||
}),
|
||||
definition('blocked', { forwardsTo: [{ callee: 'request', target: { kind: 'blocked' } }] }),
|
||||
],
|
||||
['custom'],
|
||||
);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'imported' }))).toBe(true);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'configured' }))).toBe(true);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'blocked' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('propagates a reversed long chain without recursion and excludes unrooted cycles', () => {
|
||||
const count = 5000;
|
||||
const defs = Array.from({ length: count }, (_, i) =>
|
||||
definition(String(i), {
|
||||
functionName: `request${i}`,
|
||||
forwardsUrl: i === count - 1,
|
||||
forwardsTo:
|
||||
i === count - 1
|
||||
? []
|
||||
: [
|
||||
{
|
||||
callee: `request${i + 1}`,
|
||||
target: { kind: 'binding', bindingId: String(i + 1) },
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
defs.push(
|
||||
definition('cycleA', {
|
||||
forwardsTo: [{ callee: 'request', target: { kind: 'binding', bindingId: 'cycleB' } }],
|
||||
}),
|
||||
definition('cycleB', {
|
||||
forwardsTo: [{ callee: 'request', target: { kind: 'binding', bindingId: 'cycleA' } }],
|
||||
}),
|
||||
);
|
||||
const index = buildFetchWrapperIndex(defs);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: '0' }, 'request0'))).toBe(true);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'cycleA' }))).toBe(false);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'cycleB' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('preserves the all-carriers requirement for member forwarding', () => {
|
||||
const wrapper = definition('outer', {
|
||||
forwardsTo: [{ callee: 'api.send', target: { kind: 'member' } }],
|
||||
});
|
||||
const defs = [
|
||||
wrapper,
|
||||
definition('one', { functionName: 'api.send', forwardsUrl: true }),
|
||||
definition('two', { functionName: 'api.send', forwardsUrl: true }),
|
||||
];
|
||||
expect(
|
||||
buildFetchWrapperIndex(defs).isWrapperCall(call({ kind: 'binding', bindingId: 'outer' })),
|
||||
).toBe(true);
|
||||
defs[2] = { ...defs[2], forwardsUrl: false, seed: true };
|
||||
const index = buildFetchWrapperIndex(defs);
|
||||
expect(index.isWrapperCall(call({ kind: 'binding', bindingId: 'outer' }))).toBe(false);
|
||||
// A member call still matches by name: one definition of `api.send` is a wrapper.
|
||||
expect(index.isWrapperCall(call({ kind: 'member' }, 'api.send'))).toBe(true);
|
||||
});
|
||||
|
||||
// An unresolvable import can only name some module's export, and an undeclared
|
||||
// global only a top-level function; other same-named functions cannot be it.
|
||||
it.each<[string, Partial<FetchWrapperDef>, boolean, boolean]>([
|
||||
['a nested helper', { moduleScope: false, exportedNames: [] }, true, true],
|
||||
['an unexported top-level helper', { exportedNames: [] }, true, false],
|
||||
['another exported function', {}, false, false],
|
||||
])('limits name-only fallbacks beside %s', (_shape, twin, importMatches, globalMatches) => {
|
||||
const index = buildFetchWrapperIndex([
|
||||
definition('http.ts:request', { filePath: 'http.ts', seed: true }),
|
||||
definition('twin.ts:request', { filePath: 'twin.ts', ...twin }),
|
||||
]);
|
||||
expect(
|
||||
index.isWrapperCall(
|
||||
call({ kind: 'import', specifier: '~/lib/http', importedName: 'request' }),
|
||||
),
|
||||
).toBe(importMatches);
|
||||
expect(index.isWrapperCall(call({ kind: 'unresolved' }))).toBe(globalMatches);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetch wrapper import target resolution', () => {
|
||||
it('resolves each file/specifier once across calls and forwarding facts', () => {
|
||||
const target = { kind: 'import', specifier: '@http', importedName: 'request' } as const;
|
||||
const defs = [definition('outer', { forwardsTo: [{ callee: 'send', target }] })];
|
||||
const calls = [call(target, 'send'), call(target, 'send')];
|
||||
const resolved: string[] = [];
|
||||
const result = resolveFetchWrapperTargets(defs, calls, (fromFile, specifier) => {
|
||||
resolved.push(`${fromFile}:${specifier}`);
|
||||
return ['http.ts'];
|
||||
});
|
||||
expect(resolved).toEqual(['client.ts:@http']);
|
||||
const expected = { kind: 'resolved-import', filePath: 'http.ts', importedName: 'request' };
|
||||
expect(result.calls.map((candidate) => candidate.target)).toEqual([expected, expected]);
|
||||
expect(result.definitions[0].forwardsTo[0].target).toEqual(expected);
|
||||
expect(calls.map((candidate) => candidate.target)).toEqual([target, target]);
|
||||
expect(defs[0].forwardsTo[0].target).toEqual(target);
|
||||
});
|
||||
|
||||
it('preserves unavailable targets for unique fallback and blocks ambiguous modules', () => {
|
||||
const calls = [
|
||||
call({ kind: 'import', specifier: 'missing', importedName: 'request' }),
|
||||
call({ kind: 'import', specifier: 'ambiguous', importedName: 'request' }),
|
||||
call({ kind: 'binding', bindingId: 'local' }),
|
||||
];
|
||||
const result = resolveFetchWrapperTargets([], calls, (_fromFile, specifier) =>
|
||||
specifier === 'missing' ? [] : ['a.ts', 'b.ts'],
|
||||
);
|
||||
expect(result.calls.map((candidate) => candidate.target)).toEqual([
|
||||
{ kind: 'import', specifier: 'missing', importedName: 'request' },
|
||||
{ kind: 'blocked' },
|
||||
{ kind: 'binding', bindingId: 'local' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetch wrapper barrel resolution', () => {
|
||||
const declares = (filePath: string, name: string) =>
|
||||
definition(`${filePath}:${name}`, {
|
||||
filePath,
|
||||
functionName: name,
|
||||
exportedNames: [name],
|
||||
seed: true,
|
||||
});
|
||||
const forward = (
|
||||
filePath: string,
|
||||
exportedName: string,
|
||||
specifier?: string,
|
||||
importedName = exportedName,
|
||||
): FetchWrapperReexport => ({
|
||||
filePath,
|
||||
exportedName,
|
||||
...(specifier ? { from: { specifier, importedName } } : {}),
|
||||
});
|
||||
const resolveIn = (
|
||||
reexports: FetchWrapperReexport[],
|
||||
name = 'request',
|
||||
defs = [
|
||||
declares('request.ts', 'request'),
|
||||
declares('other.ts', 'request'),
|
||||
declares('send.ts', 'send'),
|
||||
],
|
||||
) =>
|
||||
resolveFetchWrapperTargets(
|
||||
defs,
|
||||
[call({ kind: 'import', specifier: '@pkg', importedName: name }, name)],
|
||||
(fromFile, specifier) =>
|
||||
specifier === '@pkg' ? ['index.ts'] : [specifier.replace(/^\.\//, '') + '.ts'],
|
||||
reexports,
|
||||
).calls[0].target;
|
||||
const at = (filePath: string, importedName = 'request') => ({
|
||||
kind: 'resolved-import',
|
||||
filePath,
|
||||
importedName,
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a named re-export', [forward('index.ts', 'request', './request')], at('request.ts')],
|
||||
[
|
||||
'a renamed re-export',
|
||||
[forward('index.ts', 'request', './send', 'send')],
|
||||
at('send.ts', 'send'),
|
||||
],
|
||||
['a star re-export', [forward('index.ts', '*', './request', '*')], at('request.ts')],
|
||||
[
|
||||
'a chain of barrels',
|
||||
[forward('index.ts', '*', './mid', '*'), forward('mid.ts', 'request', './request')],
|
||||
at('request.ts'),
|
||||
],
|
||||
[
|
||||
'a named re-export shadowing a star export',
|
||||
[forward('index.ts', 'request', './request'), forward('index.ts', '*', './other', '*')],
|
||||
at('request.ts'),
|
||||
],
|
||||
[
|
||||
'two star exports reaching one declaration',
|
||||
[
|
||||
forward('index.ts', '*', './left', '*'),
|
||||
forward('index.ts', '*', './right', '*'),
|
||||
forward('left.ts', '*', './request', '*'),
|
||||
forward('right.ts', '*', './request', '*'),
|
||||
],
|
||||
at('request.ts'),
|
||||
],
|
||||
[
|
||||
'conflicting star exports',
|
||||
[forward('index.ts', '*', './request', '*'), forward('index.ts', '*', './other', '*')],
|
||||
{ kind: 'blocked' },
|
||||
],
|
||||
[
|
||||
'a star export conflicting with a non-callable export',
|
||||
[
|
||||
forward('index.ts', '*', './request', '*'),
|
||||
forward('index.ts', '*', './constants', '*'),
|
||||
forward('constants.ts', 'request'),
|
||||
],
|
||||
{ kind: 'blocked' },
|
||||
],
|
||||
[
|
||||
'a local export shadowing a star export',
|
||||
[forward('index.ts', 'request'), forward('index.ts', '*', './request', '*')],
|
||||
at('index.ts'),
|
||||
],
|
||||
[
|
||||
'a re-export cycle',
|
||||
[forward('index.ts', '*', './loop', '*'), forward('loop.ts', '*', './index', '*')],
|
||||
at('index.ts'),
|
||||
],
|
||||
])('resolves %s', (_shape, reexports, expected) => {
|
||||
expect(resolveIn(reexports)).toEqual(expected);
|
||||
});
|
||||
|
||||
// `export * from './left'; export * from './right'`, where left re-exports
|
||||
// `request` and right re-exports `send as request` from the same module.
|
||||
const diamond = [
|
||||
forward('index.ts', '*', './left', '*'),
|
||||
forward('index.ts', '*', './right', '*'),
|
||||
forward('left.ts', 'request', './http'),
|
||||
forward('right.ts', 'request', './http', 'send'),
|
||||
];
|
||||
it.each([
|
||||
[
|
||||
'two export names of one declaration',
|
||||
[{ ...declares('http.ts', 'request'), exportedNames: ['request', 'send'] }],
|
||||
at('http.ts'),
|
||||
],
|
||||
[
|
||||
'two declarations',
|
||||
[declares('http.ts', 'request'), declares('http.ts', 'send')],
|
||||
{ kind: 'blocked' },
|
||||
],
|
||||
])('resolves a star-export diamond over %s by binding identity', (_shape, defs, expected) => {
|
||||
expect(resolveIn(diamond, 'request', defs)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('never forwards default through a star export', () => {
|
||||
expect(
|
||||
resolveIn([forward('index.ts', '*', './request', '*')], 'default', [
|
||||
declares('request.ts', 'default'),
|
||||
]),
|
||||
).toEqual(at('index.ts', 'default'));
|
||||
});
|
||||
|
||||
it('classifies a call through a barrel as the declaring wrapper', () => {
|
||||
const defs = [declares('request.ts', 'request')];
|
||||
const resolved = resolveFetchWrapperTargets(
|
||||
defs,
|
||||
[call({ kind: 'import', specifier: '@pkg', importedName: 'request' })],
|
||||
(_fromFile, specifier) => (specifier === '@pkg' ? ['index.ts'] : ['request.ts']),
|
||||
[forward('index.ts', 'request', './request')],
|
||||
);
|
||||
expect(buildFetchWrapperIndex(resolved.definitions).isWrapperCall(resolved.calls[0])).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetch wrapper barrel resolution depth', () => {
|
||||
it('resolves calls entering one re-export chain at every hop to the same declaration', () => {
|
||||
const length = 200;
|
||||
const reexports: FetchWrapperReexport[] = Array.from({ length }, (_, i) => ({
|
||||
filePath: `b${i}.ts`,
|
||||
exportedName: '*',
|
||||
from: { specifier: `./b${i + 1}`, importedName: '*' },
|
||||
}));
|
||||
const calls = Array.from({ length }, (_, i) =>
|
||||
call({ kind: 'import', specifier: `@b${i}`, importedName: 'request' }),
|
||||
);
|
||||
const resolved = resolveFetchWrapperTargets(
|
||||
[definition('end', { filePath: `b${length}.ts`, seed: true })],
|
||||
calls,
|
||||
(_fromFile, specifier) => [`${specifier.replace(/^[@.]\/?/, '')}.ts`],
|
||||
reexports,
|
||||
);
|
||||
expect(new Set(resolved.calls.map((candidate) => JSON.stringify(candidate.target)))).toEqual(
|
||||
new Set([
|
||||
JSON.stringify({
|
||||
kind: 'resolved-import',
|
||||
filePath: `b${length}.ts`,
|
||||
importedName: 'request',
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('resolves a 50,000-module re-export chain without recursion', () => {
|
||||
const length = 50_000;
|
||||
const reexports: FetchWrapperReexport[] = Array.from({ length }, (_, i) => ({
|
||||
filePath: `b${i}.ts`,
|
||||
exportedName: '*',
|
||||
from: { specifier: `./b${i + 1}`, importedName: '*' },
|
||||
}));
|
||||
const resolved = resolveFetchWrapperTargets(
|
||||
[definition('end', { filePath: `b${length}.ts`, seed: true })],
|
||||
[call({ kind: 'import', specifier: '@pkg', importedName: 'request' })],
|
||||
(_fromFile, specifier) => [specifier === '@pkg' ? 'b0.ts' : `${specifier.slice(2)}.ts`],
|
||||
reexports,
|
||||
);
|
||||
expect(resolved.calls[0].target).toEqual({
|
||||
kind: 'resolved-import',
|
||||
filePath: `b${length}.ts`,
|
||||
importedName: 'request',
|
||||
});
|
||||
});
|
||||
});
|
||||
718
gitnexus/test/unit/fetch-wrapper-provenance.test.ts
Normal file
718
gitnexus/test/unit/fetch-wrapper-provenance.test.ts
Normal file
|
|
@ -0,0 +1,718 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import Parser from 'tree-sitter';
|
||||
import JavaScript from 'tree-sitter-javascript';
|
||||
import TypeScript from 'tree-sitter-typescript';
|
||||
import { createFetchWrapperContext } from '../../src/core/ingestion/route-extractors/fetch-wrapper.js';
|
||||
|
||||
import { buildFetchWrapperIndex } from '../../src/core/ingestion/route-extractors/fetch-wrapper-index.js';
|
||||
import { extractParsedFile } from '../../src/core/ingestion/scope-extractor-bridge.js';
|
||||
import {
|
||||
typescriptProvider,
|
||||
javascriptProvider,
|
||||
} from '../../src/core/ingestion/languages/typescript.js';
|
||||
|
||||
for (const [language, grammar] of [
|
||||
['JavaScript', JavaScript],
|
||||
['TypeScript', TypeScript.typescript],
|
||||
['TSX', TypeScript.tsx],
|
||||
] as const) {
|
||||
describe(`${language} wrapper provenance`, () => {
|
||||
const parser = new Parser();
|
||||
parser.setLanguage(grammar);
|
||||
const analyze = (source: string, lineOffset = 0) => {
|
||||
const tree = parser.parse(source);
|
||||
const fullSource = '\n'.repeat(lineOffset) + source;
|
||||
const parsedFile = extractParsedFile(
|
||||
language === 'JavaScript' ? javascriptProvider : typescriptProvider,
|
||||
fullSource,
|
||||
language === 'TSX' ? 'source.tsx' : 'source.ts',
|
||||
undefined,
|
||||
parser.parse(fullSource),
|
||||
)!;
|
||||
return { tree, parsedFile, context: createFetchWrapperContext(tree, parsedFile, lineOffset) };
|
||||
};
|
||||
it.each([
|
||||
['injected fetch', 'function load(url, fetch) { fetch(url); }', false, false],
|
||||
[
|
||||
'platform default',
|
||||
'function load(url, fetch = globalThis.fetch) { fetch(url); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
// A destructuring default is alias evidence for its leaf binding, counted once.
|
||||
[
|
||||
'destructured platform default',
|
||||
'function load(url, { fetch = globalThis.fetch } = {}) { fetch(url); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'renamed destructured platform default',
|
||||
'function load(url, { fetch: send = globalThis.fetch } = {}) { send(url); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'array destructured platform default',
|
||||
'function load(url, [send = globalThis.fetch] = []) { send(url); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'destructured local default',
|
||||
'function load(url, options) { const { fetch = globalThis.fetch } = options; fetch(url); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'destructured unknown default',
|
||||
'function load(url, { fetch = other } = {}) { fetch(url); }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
['self default', 'function load(url, fetch = fetch) { fetch(url); }', false, false],
|
||||
[
|
||||
'shadowed default root',
|
||||
'function load(url, globalThis, fetch = globalThis.fetch) { fetch(url); }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
[
|
||||
'sibling URL shadow',
|
||||
'function load(url) { { const url = "fixed"; } fetch(url); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'sibling platform shadow',
|
||||
'function load(url) { { const globalThis = {}; } globalThis.fetch(url); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'sibling alias shadow',
|
||||
'function load(url) { const send = globalThis.fetch; { const send = other; } send(url); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'alias reassignment',
|
||||
'function load(url) { let send = globalThis.fetch; send = other; send(url); }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
['URL reassignment', 'function load(url) { url = "fixed"; fetch(url); }', true, false],
|
||||
[
|
||||
'parenthesized alias reassignment',
|
||||
'function load(url) { let send = globalThis.fetch; (send) = other; send(url); }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
[
|
||||
'parenthesized URL reassignment',
|
||||
'function load(url) { (url) = "fixed"; fetch(url); }',
|
||||
true,
|
||||
false,
|
||||
],
|
||||
[
|
||||
'unused recursive helper',
|
||||
'function load(url) { function helper() { fetch(url); helper(); } }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
[
|
||||
'unused mutual recursion',
|
||||
'function load(url) { function a() { b(); } function b() { fetch(url); a(); } }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
[
|
||||
'rooted recursion',
|
||||
'function load(url) { function a() { b(); } function b() { fetch(url); a(); } a(); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
['IIFE', 'function load(url) { (() => fetch(url))(); }', true, true],
|
||||
['inline callback', 'function load(url) { retry(() => fetch(url)); }', true, true],
|
||||
['escaping anonymous', 'function load(url) { return () => fetch(url); }', true, true],
|
||||
[
|
||||
'stored anonymous property',
|
||||
'function load(url) { object.callback = () => fetch(url); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
['unused arrow', 'function load(url) { const later = () => fetch(url); }', false, false],
|
||||
[
|
||||
'unused wrapped arrow',
|
||||
'function load(url) { const later = (() => fetch(url)); }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
[
|
||||
'referenced arrow',
|
||||
'function load(url) { const later = () => fetch(url); return later; }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'class static block',
|
||||
'function load(url) { class C { static { fetch(url); } } }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'class static field',
|
||||
'function load(url) { class C { static x = fetch(url); } }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
['class computed key', 'function load(url) { class C { [fetch(url)]() {} } }', true, true],
|
||||
[
|
||||
'class heritage',
|
||||
'function load(url) { class C extends factory(fetch(url)) {} }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'deferred method',
|
||||
'function load(url) { class C { method() { fetch(url); } } }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
[
|
||||
'deferred instance field',
|
||||
'function load(url) { class C { x = fetch(url); } }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
[
|
||||
'referenced class',
|
||||
'function load(url) { class C { method() { fetch(url); } } return new C(); }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'class expression static',
|
||||
'function load(url) { const C = class { static x = fetch(url); }; }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'class expression deferred',
|
||||
'function load(url) { const C = class { x = fetch(url); }; }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
[
|
||||
'referenced class expression',
|
||||
'function load(url) { const C = class { x = fetch(url); }; return C; }',
|
||||
true,
|
||||
true,
|
||||
],
|
||||
[
|
||||
'collapsed parameter environments',
|
||||
'function load(url, send = () => fetch(url)) { var fetch = () => 0; return send(); }',
|
||||
false,
|
||||
false,
|
||||
],
|
||||
])('%s', (_shape, source, seed, forwardsUrl) => {
|
||||
const tree = parser.parse(source);
|
||||
const parsedFile = extractParsedFile(
|
||||
language === 'JavaScript' ? javascriptProvider : typescriptProvider,
|
||||
source,
|
||||
language === 'TSX' ? 'source.tsx' : 'source.ts',
|
||||
undefined,
|
||||
tree,
|
||||
)!;
|
||||
expect(
|
||||
createFetchWrapperContext(tree, parsedFile).facts(tree.rootNode.firstNamedChild!),
|
||||
).toMatchObject({ seed, forwardsUrl });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['parameter', 'function load(request) { request("/api/x"); }', 'binding'],
|
||||
['local nonwrapper', 'const request = custom; request("/api/x");', 'binding'],
|
||||
['future local', 'request("/api/x"); const request = custom;', 'blocked'],
|
||||
[
|
||||
'mutated wrapper',
|
||||
'function request(url) { return fetch(url); } request = custom; request("/api/x");',
|
||||
'blocked',
|
||||
],
|
||||
[
|
||||
'mutated import',
|
||||
'import { request } from "./api"; request = custom; request("/api/x");',
|
||||
'blocked',
|
||||
],
|
||||
[
|
||||
'namespace member behavior',
|
||||
'import * as api from "./api"; api.request = custom; api.request("/api/x");',
|
||||
'member',
|
||||
],
|
||||
])('retains contradictory target evidence: %s', (_shape, source, kind) => {
|
||||
const { context } = analyze(source);
|
||||
expect(context.calls()).toMatchObject([{ target: { kind } }]);
|
||||
});
|
||||
|
||||
it('records bare import targets while preserving member-call behavior', () => {
|
||||
const { context } = analyze(
|
||||
'import request from "@workspace/api"; import { load as send } from "@/service"; import * as api from "./client.js"; request("/a"); send("/b"); api.load("/c");',
|
||||
);
|
||||
expect(context.calls().map((call) => call.target)).toEqual([
|
||||
{ kind: 'import', specifier: '@workspace/api', importedName: 'default' },
|
||||
{ kind: 'import', specifier: '@/service', importedName: 'load' },
|
||||
{ kind: 'member' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps negative definitions, exports and declaration identities across serialization', () => {
|
||||
const { tree, context } = analyze(
|
||||
'export function request(url) { return fetch(url); } export { request as send }; export default request; function outer() { function request(value) { return value; } }',
|
||||
);
|
||||
const functions = tree.rootNode.descendantsOfType('function_declaration');
|
||||
const facts = functions.map((fn) => context.facts(fn)!);
|
||||
expect(facts).toHaveLength(3);
|
||||
expect(facts[0]).toMatchObject({
|
||||
moduleScope: true,
|
||||
exportedNames: ['request', 'send', 'default'],
|
||||
seed: true,
|
||||
});
|
||||
expect(facts[2]).toMatchObject({
|
||||
moduleScope: false,
|
||||
exportedNames: [],
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
});
|
||||
expect(facts[0].bindingId).not.toBe(facts[2].bindingId);
|
||||
expect(new Set(facts.map((fact) => fact.definitionId)).size).toBe(3);
|
||||
expect(JSON.parse(JSON.stringify(facts))).toEqual(facts);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'after a non-callable initializer',
|
||||
'const base = 0, request = (url) => fetch(url);',
|
||||
'request',
|
||||
true,
|
||||
],
|
||||
[
|
||||
'after another callable',
|
||||
'const first = (value) => value, request = (url) => fetch(url);',
|
||||
'request',
|
||||
true,
|
||||
],
|
||||
[
|
||||
'for the first of several callables',
|
||||
'const first = (value) => value, request = (url) => fetch(url);',
|
||||
'first',
|
||||
false,
|
||||
],
|
||||
])('selects the captured declarator %s', (_shape, source, name, wraps) => {
|
||||
const { tree, context } = analyze(source);
|
||||
const declaration = tree.rootNode.firstNamedChild!;
|
||||
const nameNode = declaration
|
||||
.descendantsOfType('identifier')
|
||||
.find((node) => node.text === name)!;
|
||||
const facts = context.facts(declaration, nameNode);
|
||||
expect(facts).toMatchObject({ seed: wraps, forwardsUrl: wraps });
|
||||
expect(facts?.bindingId).toBe(context.bindings.bindingId(nameNode));
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a hook callback', 'const load = useCallback((url) => fetch(url), []); load("/api/x");'],
|
||||
['a curried wrapper', 'const load = wrap(other((url) => fetch(url))); load("/api/x");'],
|
||||
])('follows the callable inside %s', (_shape, source) => {
|
||||
const { tree, context } = analyze(source);
|
||||
const declaration = tree.rootNode.firstNamedChild!;
|
||||
const nameNode = declaration.descendantsOfType('identifier')[0];
|
||||
const facts = context.facts(declaration, nameNode);
|
||||
expect(facts).toMatchObject({ seed: true, forwardsUrl: true });
|
||||
expect(facts?.bindingId).toBe(context.bindings.bindingId(nameNode));
|
||||
expect(context.calls()).toMatchObject([
|
||||
{ target: { kind: 'binding', bindingId: facts?.bindingId } },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an object-literal key', 'const api = { request: (url) => request(url) };', 'pair'],
|
||||
['a class method name', 'class Api { request(url) { return url; } }', 'method_definition'],
|
||||
])('keeps %s out of lexical binding identity', (_shape, other, nodeType) => {
|
||||
const { tree, parsedFile, context } = analyze(
|
||||
`export function request(url) { return fetch(url); }\n${other}\nrequest("/api/x");`,
|
||||
);
|
||||
const wrapper = tree.rootNode.descendantsOfType('function_declaration')[0];
|
||||
const owner = tree.rootNode.descendantsOfType(nodeType)[0];
|
||||
const key = owner.childForFieldName('key') ?? owner.childForFieldName('name')!;
|
||||
const facts = [context.facts(wrapper)!, context.facts(owner, key)!];
|
||||
expect(facts[1]).toMatchObject({ moduleScope: false, exportedNames: [] });
|
||||
expect(facts[1].bindingId).toBeUndefined();
|
||||
const index = buildFetchWrapperIndex(
|
||||
facts.map((fact) => ({ filePath: parsedFile.filePath, functionName: 'request', ...fact })),
|
||||
);
|
||||
expect(context.calls().map((call) => index.isWrapperCall(call))).toEqual([true]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'object, member and nested member forms',
|
||||
'function request(url) { return fetch(url); }\nmodule.exports = { request, send: request };\nexports.other = request;\nmodule.exports.third = request;',
|
||||
['request', 'send', 'other', 'third'],
|
||||
],
|
||||
[
|
||||
'a whole-module export',
|
||||
'function request(url) { return fetch(url); }\nmodule.exports = request;',
|
||||
['default'],
|
||||
],
|
||||
[
|
||||
'a shadowed module object',
|
||||
'function request(url) { return fetch(url); }\nfunction install(module) { module.exports = { request }; }',
|
||||
[],
|
||||
],
|
||||
])('records CommonJS exports of a declaration: %s', (_shape, source, names) => {
|
||||
const { tree, context } = analyze(source);
|
||||
expect(context.facts(tree.rootNode.firstNamedChild!)?.exportedNames.sort()).toEqual(
|
||||
[...names].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
// The query captures these wrappers as their assignment, not as the function.
|
||||
it.each([
|
||||
[
|
||||
'an exports member',
|
||||
'exports.request = function (url) { return fetch(url); };',
|
||||
['request'],
|
||||
],
|
||||
['a module.exports member', 'module.exports.request = (url) => fetch(url);', ['request']],
|
||||
[
|
||||
'the whole module',
|
||||
'module.exports = async function (url) { return fetch(url); };',
|
||||
['default'],
|
||||
],
|
||||
])('records a wrapper captured as its CommonJS assignment: %s', (_shape, source, names) => {
|
||||
const { tree, context } = analyze(source);
|
||||
const assignment = tree.rootNode.descendantsOfType('assignment_expression')[0];
|
||||
const property = assignment.childForFieldName('left')?.childForFieldName('property');
|
||||
expect(context.facts(assignment, property ?? undefined)).toMatchObject({
|
||||
moduleScope: true,
|
||||
exportedNames: names,
|
||||
seed: true,
|
||||
forwardsUrl: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'an aliased export reassigned later',
|
||||
'function request(url) { return fetch(url); } export { request as send }; request = JSON.stringify;',
|
||||
['send'],
|
||||
],
|
||||
[
|
||||
'a reassigned let export',
|
||||
'export let request = (url) => fetch(url); request = String;',
|
||||
['request'],
|
||||
],
|
||||
[
|
||||
'a declaration rebound by a var initializer',
|
||||
'function request(url) { return fetch(url); } var request = ipc.send;',
|
||||
[],
|
||||
],
|
||||
])('keeps a rebound binding from proving a wrapper: %s', (_shape, source, names) => {
|
||||
const { tree, context } = analyze(source);
|
||||
const [callable] = tree.rootNode.descendantsOfType([
|
||||
'function_declaration',
|
||||
'arrow_function',
|
||||
]);
|
||||
expect(context.facts(callable)).toMatchObject({
|
||||
exportedNames: names,
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
forwardsTo: [],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'inside recovered syntax',
|
||||
'import { request } from "./http";\nfoo(() => { request("/api/a"); }, ',
|
||||
{ kind: 'import', specifier: './http', importedName: 'request' },
|
||||
],
|
||||
[
|
||||
'in an instance field initializer before the declaration',
|
||||
'export class Store { data = request("/api/a"); }\nconst request = (url) => fetch(url);',
|
||||
{ kind: 'binding' },
|
||||
],
|
||||
[
|
||||
'in a static field initializer before the declaration',
|
||||
'export class Store { static data = request("/api/a"); }\nconst request = (url) => fetch(url);',
|
||||
{ kind: 'blocked' },
|
||||
],
|
||||
])('resolves a call %s', (_shape, source, target) => {
|
||||
const { context } = analyze(source);
|
||||
expect(context.calls()).toMatchObject([{ fetchURL: '/api/a', target }]);
|
||||
});
|
||||
|
||||
it('keys cached facts by the name node as well as the callable', () => {
|
||||
const { tree, context } = analyze('function request(url) { return fetch(url); }');
|
||||
const fn = tree.rootNode.descendantsOfType('function_declaration')[0];
|
||||
const [parameter] = fn.descendantsOfType('identifier').filter((node) => node.text === 'url');
|
||||
const byName = context.facts(fn);
|
||||
expect(byName?.bindingId).toBeDefined();
|
||||
expect(context.facts(fn, parameter)?.bindingId).not.toBe(byName?.bindingId);
|
||||
expect(context.facts(fn)).toBe(byName);
|
||||
});
|
||||
|
||||
it('records a function defined inline in a CommonJS export object', () => {
|
||||
const { tree, context } = analyze('module.exports = { inline: (url) => fetch(url) };');
|
||||
const pair = tree.rootNode.descendantsOfType('pair')[0];
|
||||
expect(context.facts(pair, pair.childForFieldName('key')!)).toMatchObject({
|
||||
moduleScope: true,
|
||||
exportedNames: ['inline'],
|
||||
seed: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a default node-fetch import', 'import fetch from "node-fetch";', 'fetch', true],
|
||||
['a named undici fetch', 'import { fetch as get } from "undici";', 'get', true],
|
||||
['a required cross-fetch module', 'const nf = require("cross-fetch");', 'nf', true],
|
||||
[
|
||||
'a whatwg-fetch member',
|
||||
'import { fetch as polyfill } from "whatwg-fetch";',
|
||||
'polyfill',
|
||||
true,
|
||||
],
|
||||
['a local module named fetch', 'import fetch from "./local-fetch";', 'fetch', false],
|
||||
[
|
||||
'another member of a fetch package',
|
||||
'import { Headers as fetch } from "node-fetch";',
|
||||
'fetch',
|
||||
false,
|
||||
],
|
||||
])(
|
||||
'treats %s as fetch evidence only for known fetch exports',
|
||||
(_shape, header, local, wraps) => {
|
||||
const { tree, context } = analyze(
|
||||
`${header}\nfunction load(url) { return ${local}(url); }`,
|
||||
);
|
||||
expect(context.facts(tree.rootNode.lastNamedChild!)).toMatchObject({
|
||||
seed: wraps,
|
||||
forwardsUrl: wraps,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps distinct declarations even when a binding is shared', () => {
|
||||
const { tree, context } = analyze(
|
||||
'function request(url) { return fetch(url); } function request(url) { return custom(url); }',
|
||||
);
|
||||
const facts = tree.rootNode.namedChildren.map((fn) => context.facts(fn)!);
|
||||
expect(facts[0].bindingId).toBe(facts[1].bindingId);
|
||||
expect(facts[0].definitionId).not.toBe(facts[1].definitionId);
|
||||
});
|
||||
|
||||
it('retains source offsets and provider context identity', () => {
|
||||
const { tree, parsedFile, context } = analyze(
|
||||
'export function request(url) { return fetch(url); }\nrequest("/api/x");',
|
||||
12,
|
||||
);
|
||||
const definition = tree.rootNode.firstNamedChild!;
|
||||
const provider = language === 'JavaScript' ? javascriptProvider : typescriptProvider;
|
||||
const first = provider.extractFetchWrapperFacts!(definition, undefined, parsedFile, 12);
|
||||
expect(provider.extractFetchWrapperFacts!(definition, undefined, parsedFile, 12)).toBe(first);
|
||||
expect(context.facts(definition)).toEqual(first);
|
||||
expect(first!.definitionId).toContain(':13:');
|
||||
expect(context.calls()).toMatchObject([
|
||||
{ lineNumber: 14, target: { kind: 'binding', bindingId: first!.bindingId } },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a plain', 'function request(url) { return fetch(url); }\nexport default request;'],
|
||||
[
|
||||
'a parenthesized',
|
||||
'function request(url) { return fetch(url); }\nexport default (request);',
|
||||
],
|
||||
])('records %s default export of a declaration', (_shape, source) => {
|
||||
const { tree, context } = analyze(source);
|
||||
const request = tree.rootNode.descendantsOfType('function_declaration')[0];
|
||||
expect(context.facts(request)).toMatchObject({ exportedNames: ['default'], seed: true });
|
||||
});
|
||||
|
||||
it('recognizes an anonymous default export', () => {
|
||||
const { tree, context } = analyze('export default function (url) { return fetch(url); }');
|
||||
expect(context.facts(tree.rootNode.firstNamedChild!)).toMatchObject({
|
||||
moduleScope: true,
|
||||
exportedNames: ['default'],
|
||||
seed: true,
|
||||
forwardsUrl: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
it.each(['deep', 'deep-arrow', 'wide'] as const)(
|
||||
'keeps native AST traversal bounded for %s helpers',
|
||||
(shape) => {
|
||||
const count = 128;
|
||||
const source = (
|
||||
shape !== 'wide'
|
||||
? [
|
||||
'function load(url) {',
|
||||
...Array.from({ length: count }, (_, i) =>
|
||||
shape === 'deep' ? `function helper${i}() {` : `const helper${i} = () => {`,
|
||||
),
|
||||
'return fetch(url);',
|
||||
...Array.from({ length: count }, (_, i) => `}; return helper${count - i - 1}();`),
|
||||
'}',
|
||||
]
|
||||
: [
|
||||
'function load(url) {',
|
||||
...Array.from({ length: count }, (_, i) => `function helper${i}() { fetch(url); }`),
|
||||
...Array.from({ length: count }, (_, i) => `helper${i}();`),
|
||||
'}',
|
||||
]
|
||||
).join('\n');
|
||||
const parser = new Parser();
|
||||
parser.setLanguage(TypeScript.typescript);
|
||||
const tree = parser.parse(source);
|
||||
const parsedFile = extractParsedFile(typescriptProvider, source, 'nested.ts', undefined, tree)!;
|
||||
const functions = tree.rootNode.descendantsOfType(['function_declaration', 'arrow_function']);
|
||||
const depths = new Map<number, number>();
|
||||
const pending = [{ node: tree.rootNode, depth: 0 }];
|
||||
while (pending.length) {
|
||||
const { node, depth } = pending.pop()!;
|
||||
depths.set(node.id, depth);
|
||||
for (const child of node.namedChildren) pending.push({ node: child, depth: depth + 1 });
|
||||
}
|
||||
let prototype = Object.getPrototypeOf(tree.rootNode);
|
||||
while (!Object.hasOwn(prototype, 'parent')) prototype = Object.getPrototypeOf(prototype);
|
||||
const descriptor = Object.getOwnPropertyDescriptor(prototype, 'parent')!;
|
||||
const childDescriptor = Object.getOwnPropertyDescriptor(prototype, 'namedChild')!;
|
||||
let parentTraversalSteps = 0;
|
||||
let childTraversalSteps = 0;
|
||||
// tree-sitter's native ts_node_parent descends from the root on every call.
|
||||
// Count that depth-weighted work only after parsing and scope extraction.
|
||||
Object.defineProperty(prototype, 'parent', {
|
||||
...descriptor,
|
||||
get(this: Parser.SyntaxNode) {
|
||||
parentTraversalSteps += depths.get(this.id) ?? 0;
|
||||
return descriptor.get!.call(this);
|
||||
},
|
||||
});
|
||||
// ts_node__child starts its sibling iterator at zero for every indexed read.
|
||||
Object.defineProperty(prototype, 'namedChild', {
|
||||
...childDescriptor,
|
||||
value(this: Parser.SyntaxNode, index: number) {
|
||||
childTraversalSteps += index + 1;
|
||||
return childDescriptor.value.call(this, index);
|
||||
},
|
||||
});
|
||||
try {
|
||||
// The instruments must fire before a zero count can mean anything.
|
||||
void functions[0].parent;
|
||||
void functions[0].namedChild(0);
|
||||
expect(parentTraversalSteps).toBeGreaterThan(0);
|
||||
expect(childTraversalSteps).toBeGreaterThan(0);
|
||||
parentTraversalSteps = 0;
|
||||
childTraversalSteps = 0;
|
||||
const context = createFetchWrapperContext(tree, parsedFile);
|
||||
const facts = functions.map((fn) =>
|
||||
context.facts(fn, fn.childForFieldName('name') ?? undefined),
|
||||
);
|
||||
expect(facts.every((fact) => fact?.seed)).toBe(true);
|
||||
expect(facts[0]?.forwardsUrl).toBe(true);
|
||||
expect(parentTraversalSteps).toBeLessThanOrEqual(32 * count);
|
||||
expect(childTraversalSteps).toBeLessThanOrEqual(64 * count);
|
||||
} finally {
|
||||
Object.defineProperty(prototype, 'parent', descriptor);
|
||||
Object.defineProperty(prototype, 'namedChild', childDescriptor);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
describe.each([
|
||||
['TypeScript', TypeScript.typescript, 'source.ts'],
|
||||
['TSX', TypeScript.tsx, 'source.tsx'],
|
||||
] as const)('%s-only wrapper syntax', (_language, grammar, filePath) => {
|
||||
const analyze = (source: string) => {
|
||||
const parser = new Parser();
|
||||
parser.setLanguage(grammar);
|
||||
const tree = parser.parse(source);
|
||||
const parsedFile = extractParsedFile(typescriptProvider, source, filePath, undefined, tree)!;
|
||||
return { tree, context: createFetchWrapperContext(tree, parsedFile) };
|
||||
};
|
||||
|
||||
it('associates bodyless overload signatures with their implementation', () => {
|
||||
const { tree, context } = analyze(
|
||||
'export function request(url: string): Promise<Response>;\nexport function request(url: URL): Promise<Response>;\nexport function request(url: any) { return fetch(url); }\nrequest("/api/x");',
|
||||
);
|
||||
const signatures = tree.rootNode.descendantsOfType('function_signature');
|
||||
const implementation = tree.rootNode.descendantsOfType('function_declaration')[0];
|
||||
expect(signatures.map((signature) => context.facts(signature))).toEqual([undefined, undefined]);
|
||||
const facts = context.facts(implementation)!;
|
||||
expect(facts).toMatchObject({ seed: true, forwardsUrl: true, exportedNames: ['request'] });
|
||||
expect(context.calls()).toMatchObject([
|
||||
{ target: { kind: 'binding', bindingId: facts.bindingId } },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'keeps stored asserted callbacks deferred',
|
||||
'function load(url) { const later = (() => fetch(url)) as () => unknown; }',
|
||||
false,
|
||||
],
|
||||
[
|
||||
'evaluates supported decorator expressions while deferring methods',
|
||||
'function load(url) { @decorate(fetch(url)) class C { @decorate(fetch(url)) method() { return custom(url); } } }',
|
||||
true,
|
||||
],
|
||||
])('%s', (_shape, source, wraps) => {
|
||||
const { tree, context } = analyze(source);
|
||||
expect(context.facts(tree.rootNode.firstNamedChild!)).toMatchObject({
|
||||
seed: wraps,
|
||||
forwardsUrl: wraps,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps a nested overloaded helper reachable through its one implementation', () => {
|
||||
const { tree, context } = analyze(
|
||||
'function load(url: string) { function helper(u: string): void; function helper(u: any) { fetch(u); } helper(url); }',
|
||||
);
|
||||
const facts = context.facts(tree.rootNode.firstNamedChild!)!;
|
||||
expect(facts.seed).toBe(true);
|
||||
expect(facts.forwardsTo).toMatchObject([{ callee: 'helper', target: { kind: 'binding' } }]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'an asserted alias write invalidates the alias',
|
||||
'function load(url: string) { let send = globalThis.fetch; (send as unknown) = other; send(url); }',
|
||||
false,
|
||||
],
|
||||
[
|
||||
'a non-null asserted alias write invalidates the alias',
|
||||
'function load(url: string) { let send = globalThis.fetch; send! = other; send(url); }',
|
||||
false,
|
||||
],
|
||||
])('%s', (_shape, source, wraps) => {
|
||||
const { tree, context } = analyze(source);
|
||||
expect(context.facts(tree.rootNode.firstNamedChild!)).toMatchObject({
|
||||
seed: wraps,
|
||||
forwardsUrl: wraps,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('invalidates an alias written through an angle-bracket assertion', () => {
|
||||
const source =
|
||||
'function load(url: string) { let send = globalThis.fetch; (<any>send) = other; send(url); }';
|
||||
const parser = new Parser();
|
||||
parser.setLanguage(TypeScript.typescript);
|
||||
const tree = parser.parse(source);
|
||||
const parsedFile = extractParsedFile(typescriptProvider, source, 'source.ts', undefined, tree);
|
||||
const load = tree.rootNode.descendantsOfType('function_declaration')[0];
|
||||
expect(parsedFile && createFetchWrapperContext(tree, parsedFile).facts(load)).toMatchObject({
|
||||
seed: false,
|
||||
forwardsUrl: false,
|
||||
});
|
||||
});
|
||||
|
|
@ -244,6 +244,70 @@ function handler() {} function other() {}`);
|
|||
).toEqual(['POST /direct']);
|
||||
});
|
||||
|
||||
it('invalidates a module binding written by a constructor assignment in a closure', () => {
|
||||
expect(
|
||||
urls(`import express from 'express';
|
||||
let app = express(); function replace() { app = new Map(); }
|
||||
app.get('/let-closure', handler);`),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a default expression', '[target = app] = values;', ['GET /retained']],
|
||||
['a computed key', '({ [app]: target } = values);', ['GET /retained']],
|
||||
['a destructured property write', '({ get: app.get } = values);', []],
|
||||
])('invalidates only assignment targets in %s', (_shape, write, expected) => {
|
||||
expect(
|
||||
urls(`import express from 'express'; const app = express(); let target;
|
||||
${write} app.get('/retained', handler);`),
|
||||
).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['parenthesized', '(app) = new Map();'],
|
||||
['asserted', '(app as unknown) = new Map();'],
|
||||
['angle-bracket asserted', '(<any>app) = new Map();'],
|
||||
['non-null asserted', 'app! = new Map();'],
|
||||
])('invalidates a wrapped assignment target: %s', (_shape, write) => {
|
||||
expect(
|
||||
urls(`import express from 'express'; let app = express();
|
||||
${write} app.get('/not-http', handler);`),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['initialized var', 'app', 'var app = storage;', []],
|
||||
['initialized var with another default', 'app, other = 1', 'var app = storage;', []],
|
||||
['uninitialized var', 'app', 'var app;', ['GET /forwarded']],
|
||||
[
|
||||
'nested parameter write',
|
||||
'app',
|
||||
'function inner(app) { app = new Map(); }',
|
||||
['GET /forwarded'],
|
||||
],
|
||||
// A parameter expression gives the body its own variable environment, which
|
||||
// the scope model collapses, so inference declines a parameter that a body
|
||||
// `var` redeclares (the documented boundary); runtime would keep its value.
|
||||
['nested destructuring default', 'app, { value = 1 }', 'var app;', []],
|
||||
['computed pattern key', 'app, { [key]: value }', 'var app;', []],
|
||||
['rest parameter alone', 'app, ...rest', 'var app;', ['GET /forwarded']],
|
||||
['loop var over the parameter', 'app', 'for (var app of values) {}', []],
|
||||
['body function overwrites parameter', 'app', 'function app() {}', []],
|
||||
['body function with default', 'app, other = 1', 'function app() {}', []],
|
||||
[
|
||||
'nested body declaration',
|
||||
'app, other = 1',
|
||||
'function inner() { var app = storage; }',
|
||||
['GET /forwarded'],
|
||||
],
|
||||
])('uses binding identity for helper forwarding: %s', (_shape, parameters, body, expected) => {
|
||||
expect(
|
||||
urls(`import express from 'express';
|
||||
function mount(${parameters}) { ${body} app.get('/forwarded', handler); }
|
||||
mount(express());`),
|
||||
).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
shape: 'a literal mount path forwarded to a helper',
|
||||
|
|
|
|||
|
|
@ -70,6 +70,21 @@ describe('Express group provider provenance', () => {
|
|||
expect(providers(await extractor.extract(null, root, repo()))).toEqual([]);
|
||||
});
|
||||
|
||||
it('uses lexical ownership for closure writes and parameter redeclarations', async () => {
|
||||
write({
|
||||
'server.ts': `import express from 'express';
|
||||
let app = express(); function replace() { app = new Map(); }
|
||||
app.get('/let-closure', handler);
|
||||
function overwritten(app) { var app = storage; app.get('/overwritten', handler); }
|
||||
function ambiguous(app, { value = 1 }) { var app; app.get('/ambiguous', handler); }
|
||||
function retained(app) { var app; function nested(app) { app = new Map(); } app.get('/retained', handler); }
|
||||
overwritten(express()); ambiguous(express()); retained(express());`,
|
||||
});
|
||||
expect(providers(await extractor.extract(null, root, repo()))).toEqual([
|
||||
'http::GET::/retained',
|
||||
]);
|
||||
});
|
||||
|
||||
it('agrees with ingestion across mixed extensions, aliases and multiple mounts while preserving consumers and other providers', async () => {
|
||||
write({
|
||||
'tsconfig.json': JSON.stringify({
|
||||
|
|
|
|||
|
|
@ -58,8 +58,20 @@ describe('mergeResult', () => {
|
|||
|
||||
it('retains wrapper candidates across sub-batches without treating them as HTTP sinks', () => {
|
||||
const target = emptyResult();
|
||||
const first = { filePath: 'a.ts', functionName: 'request', fetchURL: '/a', lineNumber: 1 };
|
||||
const second = { filePath: 'b.ts', functionName: 'client.get', fetchURL: '/b', lineNumber: 2 };
|
||||
const first = {
|
||||
filePath: 'a.ts',
|
||||
functionName: 'request',
|
||||
fetchURL: '/a',
|
||||
lineNumber: 1,
|
||||
target: { kind: 'unresolved' as const },
|
||||
};
|
||||
const second = {
|
||||
filePath: 'b.ts',
|
||||
functionName: 'client.get',
|
||||
fetchURL: '/b',
|
||||
lineNumber: 2,
|
||||
target: { kind: 'member' as const },
|
||||
};
|
||||
mergeResult(target, { ...emptyResult(), fetchWrapperCalls: [first] });
|
||||
mergeResult(target, emptyResult());
|
||||
mergeResult(target, { ...emptyResult(), fetchWrapperCalls: [second] });
|
||||
|
|
@ -67,6 +79,24 @@ describe('mergeResult', () => {
|
|||
expect(target.fetchCalls).toEqual([]);
|
||||
});
|
||||
|
||||
it('retains barrel re-export facts across sub-batches', () => {
|
||||
const target = emptyResult();
|
||||
const named = {
|
||||
filePath: 'index.ts',
|
||||
exportedName: 'request',
|
||||
from: { specifier: './request', importedName: 'request' },
|
||||
};
|
||||
const star = {
|
||||
filePath: 'index.ts',
|
||||
exportedName: '*',
|
||||
from: { specifier: './star', importedName: '*' },
|
||||
};
|
||||
mergeResult(target, { ...emptyResult(), fetchWrapperReexports: [named] });
|
||||
mergeResult(target, emptyResult());
|
||||
mergeResult(target, { ...emptyResult(), fetchWrapperReexports: [star] });
|
||||
expect(target.fetchWrapperReexports).toEqual([named, star]);
|
||||
});
|
||||
|
||||
it('sums every CFG skip bucket by language across worker sub-batches', () => {
|
||||
const target = emptyResult();
|
||||
const first = {
|
||||
|
|
|
|||
156
gitnexus/test/unit/route-lexical-bindings.test.ts
Normal file
156
gitnexus/test/unit/route-lexical-bindings.test.ts
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import Parser from 'tree-sitter';
|
||||
import TypeScript from 'tree-sitter-typescript';
|
||||
import JavaScript from 'tree-sitter-javascript';
|
||||
import {
|
||||
typescriptProvider,
|
||||
javascriptProvider,
|
||||
} from '../../src/core/ingestion/languages/typescript.js';
|
||||
import { extractParsedFile } from '../../src/core/ingestion/scope-extractor-bridge.js';
|
||||
import {
|
||||
createLexicalBindings,
|
||||
patternBindingNames,
|
||||
} from '../../src/core/ingestion/route-extractors/lexical-bindings.js';
|
||||
import { getTreeSitterBufferSize } from '../../src/core/ingestion/constants.js';
|
||||
|
||||
function analyze(source: string, javascript = false, lineOffset = 0) {
|
||||
const parser = new Parser();
|
||||
parser.setLanguage(javascript ? JavaScript : TypeScript.typescript);
|
||||
const tree = parser.parse(source);
|
||||
const fullSource = '\n'.repeat(lineOffset) + source;
|
||||
const parsed = extractParsedFile(
|
||||
javascript ? javascriptProvider : typescriptProvider,
|
||||
fullSource,
|
||||
javascript ? 'source.js' : 'source.ts',
|
||||
undefined,
|
||||
lineOffset ? parser.parse(fullSource) : tree,
|
||||
);
|
||||
expect(parsed).toBeDefined();
|
||||
return {
|
||||
root: tree.rootNode,
|
||||
bindings: createLexicalBindings(parsed!, lineOffset, tree.rootNode),
|
||||
};
|
||||
}
|
||||
|
||||
describe.each([false, true])('HTTP lexical bindings (JavaScript: %s)', (javascript) => {
|
||||
it.each([
|
||||
['parameter default', 'app = fallback', 'var app;', 'app', true],
|
||||
['another parameter default', 'app, other = 1', 'var app;', 'app', true],
|
||||
['nested object default', 'app, { nested: { value = 1 } }', 'var app;', 'app', true],
|
||||
['nested array default', 'app, [value = 1]', 'var app;', 'app', true],
|
||||
['computed pattern key', 'app, { [key]: value }', 'var app;', 'app', true],
|
||||
['referenced computed key', '{ [app]: value }', 'var app;', 'app', true],
|
||||
[
|
||||
'default closure reference',
|
||||
'send = () => fetch(url)',
|
||||
'var fetch = replacement;',
|
||||
'fetch',
|
||||
true,
|
||||
],
|
||||
['body function reference', 'send = () => fetch(url)', 'function fetch() {}', 'fetch', true],
|
||||
[
|
||||
'loop var declaration',
|
||||
'send = () => fetch(url)',
|
||||
'for (var fetch of values) {}',
|
||||
'fetch',
|
||||
true,
|
||||
],
|
||||
['empty pattern default', '{} = globalThis.fetch(url)', 'var globalThis;', 'globalThis', true],
|
||||
['rest alone', 'app, ...rest', 'var app;', 'app', false],
|
||||
['nested function body', 'app, other = 1', 'function nested() { var app; }', 'app', false],
|
||||
[
|
||||
'nested method body',
|
||||
'app, other = 1',
|
||||
'const object = { method() { var app; } };',
|
||||
'app',
|
||||
false,
|
||||
],
|
||||
['property name', 'send = () => ({ fetch: 1 })', 'var fetch;', 'fetch', false],
|
||||
['default closure parameter', 'send = (fetch) => 1', 'var fetch;', 'fetch', false],
|
||||
[
|
||||
'default closure parameter reference',
|
||||
'url, fallback = (send) => send',
|
||||
'var send = globalThis.fetch;',
|
||||
'send',
|
||||
false,
|
||||
],
|
||||
['bound property name', '{ fetch: other = 1 }', 'var fetch;', 'fetch', false],
|
||||
])('marks only collapsed environments: %s', (_shape, parameters, body, name, expected) => {
|
||||
const { root, bindings } = analyze(
|
||||
`function load(${parameters}) { ${body} ${name}; }`,
|
||||
javascript,
|
||||
);
|
||||
const read = root
|
||||
.descendantsOfType('identifier')
|
||||
.filter((node) => node.text === name)
|
||||
.at(-1)!;
|
||||
const id = bindings.bindingId(read);
|
||||
expect(id).toBeDefined();
|
||||
expect(bindings.ambiguous(id!)).toBe(expected);
|
||||
});
|
||||
|
||||
it('shares outer ownership across closures and keeps shadowing and global identity separate', () => {
|
||||
const { root, bindings } = analyze(
|
||||
`let app = factory();
|
||||
function outer() { app = new Map(); app; }
|
||||
function shadow(app) { app; fetch('/global'); }
|
||||
function local(fetch) { fetch('/local'); }`,
|
||||
javascript,
|
||||
);
|
||||
const apps = root.descendantsOfType('identifier').filter((node) => node.text === 'app');
|
||||
expect(bindings.bindingId(apps[1])).toBe(bindings.bindingId(apps[0]));
|
||||
expect(bindings.bindingId(apps[2], 'app', true)).toBe(bindings.bindingId(apps[0]));
|
||||
expect(bindings.bindingId(apps[3])).not.toBe(bindings.bindingId(apps[0]));
|
||||
const fetches = root.descendantsOfType('identifier').filter((node) => node.text === 'fetch');
|
||||
expect(bindings.isGlobal(fetches[0], 'fetch')).toBe(true);
|
||||
expect(bindings.isGlobal(fetches.at(-1)!, 'fetch')).toBe(false);
|
||||
const closureWrite = bindings.ownership(apps[2], 'app', true);
|
||||
expect(closureWrite?.scope).toBeDefined();
|
||||
expect(closureWrite?.scope).toBe(bindings.ownership(apps[0])?.scope);
|
||||
expect(bindings.ownership(apps[3])?.scope).not.toBe(closureWrite?.scope);
|
||||
// Repeated lookups are memoized per node, name and position mode.
|
||||
expect(bindings.ownership(apps[2], 'app', true)).toBe(closureWrite);
|
||||
});
|
||||
|
||||
it('preserves TDZ barriers and offset-adjusted lookups', () => {
|
||||
const { root, bindings } = analyze('app; let app = factory(); app;', javascript, 12);
|
||||
const apps = root.descendantsOfType('identifier').filter((node) => node.text === 'app');
|
||||
expect(bindings.bindingId(apps[0], 'app', true)).toBeUndefined();
|
||||
expect(bindings.bindingId(apps[2], 'app', true)).toBe(bindings.bindingId(apps[1]));
|
||||
expect(bindings.ownership(apps[2])?.scope).toBeDefined();
|
||||
});
|
||||
|
||||
it('does not mistake destructuring keys or default expressions for bound names', () => {
|
||||
const { root } = analyze(
|
||||
'function f({ key: value = fallback, [computed]: alias, short = rhs }, ...rest) {}',
|
||||
javascript,
|
||||
);
|
||||
const parameters = root.descendantsOfType('formal_parameters')[0];
|
||||
expect(patternBindingNames(parameters).map((node) => node.text)).toEqual([
|
||||
'value',
|
||||
'alias',
|
||||
'short',
|
||||
'rest',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it('walks a 20,000-deep destructuring pattern without recursion', () => {
|
||||
const depth = 20_000;
|
||||
const source = `const ${'['.repeat(depth)}x${']'.repeat(depth)} = v;`;
|
||||
const parser = new Parser();
|
||||
parser.setLanguage(JavaScript);
|
||||
const tree = parser.parse(source, undefined, { bufferSize: getTreeSitterBufferSize(source) });
|
||||
const pattern = tree.rootNode
|
||||
.descendantsOfType('variable_declarator')[0]
|
||||
.childForFieldName('name');
|
||||
expect(patternBindingNames(pattern).map((node) => node.text)).toEqual(['x']);
|
||||
});
|
||||
|
||||
it('reads the target of an angle-bracket assertion, not its type arguments', () => {
|
||||
const { root } = analyze('let app = 1; (<any>app) = 2;');
|
||||
const assignment = root.descendantsOfType('assignment_expression')[0];
|
||||
expect(
|
||||
patternBindingNames(assignment.childForFieldName('left')).map((node) => node.text),
|
||||
).toEqual(['app']);
|
||||
});
|
||||
|
|
@ -120,25 +120,264 @@ describe('lexical name ownership', () => {
|
|||
const inner = scope('fn', 'module', { lexicalNames: new Set(['helper']) });
|
||||
expect(findCallableBindingInScope('fn', 'helper', indexes(inner))).toBeUndefined();
|
||||
});
|
||||
it('treats inferred reassignment as a read of the outer binding only with complete claims', () => {
|
||||
const outer = scope('module', null, { bindings: new Map([['helper', [binding]]]) });
|
||||
it.each([
|
||||
['assignment-inferred', undefined],
|
||||
['constructor-inferred', 'other'],
|
||||
] as const)(
|
||||
'treats %s reassignment as a read of the outer binding only with complete claims',
|
||||
(source, carried) => {
|
||||
const outer = scope('module', null, { bindings: new Map([['helper', [binding]]]) });
|
||||
const inner = scope('fn', outer.id, {
|
||||
nameClaims: [],
|
||||
typeBindings: new Map([['helper', { rawName: 'other', source, declaredAtScope: 'fn' }]]),
|
||||
});
|
||||
expect(lexical(inner, outer, 5).scope?.id).toBe(inner.id);
|
||||
const complete = { ...inner, lookupPolicy: { nameClaimsComplete: true } };
|
||||
expect(lexical(complete, outer, 5).bindings).toEqual([binding]);
|
||||
// Only a constructor fact describes the value the write stores.
|
||||
expect(lexical(complete, outer, 5).typeBinding?.rawName).toBe(carried);
|
||||
const parameter = {
|
||||
...complete,
|
||||
typeBindings: new Map<string, TypeRef>([
|
||||
[
|
||||
'helper',
|
||||
{ rawName: 'Callback', source: 'parameter-annotation', declaredAtScope: 'fn' },
|
||||
],
|
||||
]),
|
||||
};
|
||||
expect(lexical(parameter, outer, 5).scope?.id).toBe(inner.id);
|
||||
expect(lexical(parameter, outer, 5).typeBinding?.rawName).toBe('Callback');
|
||||
},
|
||||
);
|
||||
it.each([
|
||||
'annotation',
|
||||
'parameter-annotation',
|
||||
'return-annotation',
|
||||
'self',
|
||||
'decorator-unknown',
|
||||
] as const)('preserves the complete owner %s over a nested constructor fact', (source) => {
|
||||
const declared: TypeRef = {
|
||||
rawName: 'Declared',
|
||||
source,
|
||||
declaredAtScope: 'type-producer',
|
||||
lookupPurpose: 'type',
|
||||
lookupPosition: at(2),
|
||||
bindingRange: at(4),
|
||||
};
|
||||
const outer = scope('module', null, {
|
||||
nameClaims: [{ name: 'helper', kind: 'binding', range: at(4) }],
|
||||
typeBindings: new Map([['helper', declared]]),
|
||||
});
|
||||
const inner = scope('fn', outer.id, {
|
||||
nameClaims: [],
|
||||
lookupPolicy: { nameClaimsComplete: true },
|
||||
typeBindings: new Map([
|
||||
['helper', { rawName: 'other', source: 'assignment-inferred', declaredAtScope: 'fn' }],
|
||||
[
|
||||
'helper',
|
||||
{
|
||||
rawName: 'Inferred',
|
||||
source: 'constructor-inferred',
|
||||
declaredAtScope: 'fn',
|
||||
lookupPurpose: 'value',
|
||||
lookupPosition: at(5),
|
||||
bindingRange: at(5),
|
||||
},
|
||||
],
|
||||
]),
|
||||
});
|
||||
expect(lexical(inner, outer, 5).scope?.id).toBe(inner.id);
|
||||
const complete = { ...inner, lookupPolicy: { nameClaimsComplete: true } };
|
||||
expect(lexical(complete, outer, 5).bindings).toEqual([binding]);
|
||||
const parameter = {
|
||||
...complete,
|
||||
typeBindings: new Map<string, TypeRef>([
|
||||
['helper', { rawName: 'Callback', source: 'parameter-annotation', declaredAtScope: 'fn' }],
|
||||
]),
|
||||
const selected = lexical(inner, outer, 6);
|
||||
expect(selected.scope).toBe(outer);
|
||||
expect(selected.typeBinding).toBe(declared);
|
||||
});
|
||||
it.each([
|
||||
undefined,
|
||||
'assignment-inferred',
|
||||
'constructor-inferred',
|
||||
'receiver-propagated',
|
||||
] as const)('carries the complete constructor fact when the owner fact is %s', (source) => {
|
||||
const carried: TypeRef = {
|
||||
rawName: 'User',
|
||||
source: 'constructor-inferred',
|
||||
declaredAtScope: 'constructor-producer',
|
||||
lookupPurpose: 'value',
|
||||
lookupPosition: at(7),
|
||||
bindingRange: at(5),
|
||||
};
|
||||
expect(lexical(parameter, outer, 5).scope?.id).toBe(inner.id);
|
||||
expect(lexical(parameter, outer, 5).typeBinding?.rawName).toBe('Callback');
|
||||
const outer = scope('module', null, {
|
||||
bindings: new Map([['helper', [binding]]]),
|
||||
typeBindings: new Map(
|
||||
source === undefined
|
||||
? []
|
||||
: [['helper', { rawName: 'Other', source, declaredAtScope: 'module' }]],
|
||||
),
|
||||
});
|
||||
const inner = scope('fn', outer.id, {
|
||||
lookupPolicy: { nameClaimsComplete: true },
|
||||
typeBindings: new Map([['helper', carried]]),
|
||||
});
|
||||
const selected = lexical(inner, outer, 8);
|
||||
expect(selected.scope).toBe(outer);
|
||||
expect(selected.bindings).toEqual([binding]);
|
||||
expect(selected.typeBinding).toBe(carried);
|
||||
});
|
||||
it.each([
|
||||
{ innerLine: 5, outerLine: 9 },
|
||||
{ innerLine: 9, outerLine: 5 },
|
||||
])('carries the nearest skipped fact regardless of positions: %j', ({ innerLine, outerLine }) => {
|
||||
const fact = (name: string, line: number): TypeRef => ({
|
||||
rawName: name,
|
||||
source: 'constructor-inferred',
|
||||
declaredAtScope: name,
|
||||
bindingRange: at(line),
|
||||
});
|
||||
const nearest = fact('Nearest', innerLine);
|
||||
const owner = scope('module', null, { bindings: new Map([['helper', [binding]]]) });
|
||||
const middle = scope('middle', owner.id, {
|
||||
lookupPolicy: { nameClaimsComplete: true },
|
||||
typeBindings: new Map([['helper', fact('Farther', outerLine)]]),
|
||||
});
|
||||
const inner = scope('fn', middle.id, {
|
||||
lookupPolicy: { nameClaimsComplete: true },
|
||||
typeBindings: new Map([['helper', nearest]]),
|
||||
});
|
||||
const selected = lookupLexicalName(inner.id, 'helper', {
|
||||
scopes: { getScope: (id) => [inner, middle, owner].find((entry) => entry.id === id) },
|
||||
});
|
||||
expect(selected.scope).toBe(owner);
|
||||
expect(selected.typeBinding).toBe(nearest);
|
||||
});
|
||||
it('keeps a genuinely declared constructor binding local with complete claims', () => {
|
||||
const typeRef: TypeRef = {
|
||||
rawName: 'Local',
|
||||
source: 'constructor-inferred',
|
||||
declaredAtScope: 'fn',
|
||||
bindingRange: at(4),
|
||||
};
|
||||
const inner = scope('fn', 'module', {
|
||||
lookupPolicy: { nameClaimsComplete: true },
|
||||
nameClaims: [{ name: 'helper', kind: 'binding', range: at(4) }],
|
||||
typeBindings: new Map([['helper', typeRef]]),
|
||||
});
|
||||
const selected = lexical(inner, scope('module', null), 5);
|
||||
expect(selected.scope).toBe(inner);
|
||||
expect(selected.typeBinding).toBe(typeRef);
|
||||
});
|
||||
it('filters a mismatched owner fact before choosing a carried constructor fact', () => {
|
||||
const carried: TypeRef = {
|
||||
rawName: 'User',
|
||||
source: 'constructor-inferred',
|
||||
declaredAtScope: 'fn',
|
||||
bindingRange: at(6),
|
||||
};
|
||||
const outer = scope('module', null, {
|
||||
nameClaims: [{ name: 'helper', kind: 'binding', range: at(4) }],
|
||||
typeBindings: new Map([
|
||||
[
|
||||
'helper',
|
||||
{
|
||||
rawName: 'Other',
|
||||
source: 'annotation',
|
||||
declaredAtScope: 'module',
|
||||
bindingRange: at(8),
|
||||
},
|
||||
],
|
||||
]),
|
||||
});
|
||||
const inner = scope('fn', outer.id, {
|
||||
lookupPolicy: { nameClaimsComplete: true },
|
||||
typeBindings: new Map([['helper', carried]]),
|
||||
});
|
||||
expect(lexical(inner, outer, 7).typeBinding).toBe(carried);
|
||||
});
|
||||
it('does not carry a declaration fact from another namespace', () => {
|
||||
const outer = scope('module', null, { bindings: new Map([['helper', [binding]]]) });
|
||||
const inner = scope('fn', outer.id, {
|
||||
lookupPolicy: { nameClaimsComplete: true },
|
||||
nameClaims: [{ name: 'helper', kind: 'binding', purpose: 'type', range: at(4) }],
|
||||
typeBindings: new Map([
|
||||
['helper', { rawName: 'Other', source: 'constructor-inferred', declaredAtScope: 'fn' }],
|
||||
]),
|
||||
});
|
||||
const selected = lexical(inner, outer, 6);
|
||||
expect(selected.bindings).toEqual([binding]);
|
||||
expect(selected.typeBinding).toBeUndefined();
|
||||
});
|
||||
it('does not invent a binding for a write to an absent name, but keeps its type', () => {
|
||||
const inner = scope('fn', 'module', {
|
||||
lookupPolicy: { nameClaimsComplete: true },
|
||||
typeBindings: new Map([
|
||||
['helper', { rawName: 'User', source: 'constructor-inferred', declaredAtScope: 'fn' }],
|
||||
]),
|
||||
});
|
||||
const outer = scope('module', null);
|
||||
const selected = lexical(inner, outer, 6);
|
||||
expect(selected.status).toBe('absent');
|
||||
expect(selected.bindings).toEqual([]);
|
||||
expect(selected.typeBinding?.rawName).toBe('User');
|
||||
// `function init() { client = new ApiClient(); client.connect(); }` keeps
|
||||
// its receiver type although no scope declares `client`.
|
||||
expect(findReceiverTypeBinding(inner.id, 'helper', indexes(inner, outer))?.rawName).toBe(
|
||||
'User',
|
||||
);
|
||||
});
|
||||
it('preserves source-position write identity only when explicitly requested', () => {
|
||||
const imported: ImportEdge = {
|
||||
localName: 'helper',
|
||||
kind: 'named',
|
||||
targetFile: 'outer.ts',
|
||||
targetExportedName: 'helper',
|
||||
atRange: at(1),
|
||||
};
|
||||
const importedBinding = { ...binding, via: imported };
|
||||
const outer = scope('module', null, {
|
||||
imports: [imported],
|
||||
bindings: new Map([['helper', [importedBinding]]]),
|
||||
nameClaims: [
|
||||
{ name: 'helper', kind: 'import', range: at(1), hoisted: true },
|
||||
{ name: 'helper', kind: 'blocked', range: at(5), availableFrom: at(6) },
|
||||
],
|
||||
});
|
||||
const inner = scope('fn', outer.id, {
|
||||
lookupPolicy: { nameClaimsComplete: true, deferParentActivation: true },
|
||||
typeBindings: new Map([
|
||||
['helper', { rawName: 'User', source: 'constructor-inferred', declaredAtScope: 'fn' }],
|
||||
]),
|
||||
});
|
||||
const sources = {
|
||||
scopes: { getScope: (id: string) => [inner, outer].find((entry) => entry.id === id) },
|
||||
};
|
||||
const ordinary = lookupLexicalName(inner.id, 'helper', sources, { position: at(5) });
|
||||
expect(ordinary.status).toBe('blocked');
|
||||
expect(ordinary.bindings).toEqual([]);
|
||||
const write = lookupLexicalName(inner.id, 'helper', sources, {
|
||||
position: at(5),
|
||||
preservePosition: true,
|
||||
});
|
||||
expect(write.scope).toBe(outer);
|
||||
expect(write.bindings).toEqual([importedBinding]);
|
||||
});
|
||||
it('keeps the write position across a module redirect only when requested', () => {
|
||||
const declared: BindingRef = { def: target, origin: 'local', declarationRange: at(6) };
|
||||
const outer = scope('module', null, {
|
||||
bindings: new Map([['helper', [declared]]]),
|
||||
nameClaims: [{ name: 'helper', kind: 'binding', range: at(6), availableFrom: at(7) }],
|
||||
});
|
||||
const inner = scope('fn', outer.id, {
|
||||
lookupPolicy: { deferParentActivation: true },
|
||||
nameClaims: [
|
||||
{ name: 'helper', kind: 'binding', range: at(8), availableFrom: at(9), inactive: 'module' },
|
||||
],
|
||||
});
|
||||
const sources = {
|
||||
scopes: { getScope: (id: string) => [inner, outer].find((entry) => entry.id === id) },
|
||||
};
|
||||
const deferred = lookupLexicalName(inner.id, 'helper', sources, { position: at(5) });
|
||||
expect(deferred.status).toBe('resolved');
|
||||
expect(deferred.bindings).toEqual([declared]);
|
||||
const write = lookupLexicalName(inner.id, 'helper', sources, {
|
||||
position: at(5),
|
||||
preservePosition: true,
|
||||
});
|
||||
expect(write.status).toBe('blocked');
|
||||
});
|
||||
it('joins a hoisted return annotation to the selected declaration anchor', () => {
|
||||
const method: SymbolDefinition = {
|
||||
|
|
|
|||
|
|
@ -199,6 +199,36 @@ describe('buildPositionIndex', () => {
|
|||
});
|
||||
|
||||
describe('robustness', () => {
|
||||
it.each(['siblings', 'nested'] as const)(
|
||||
'bounds range checks for outer reads after completed %s',
|
||||
(shape) => {
|
||||
const count = 256;
|
||||
let endChecks = 0;
|
||||
const scopes = [mkScope('module', 'a.ts', 'Module', r(1, 0, count * 4, 0))];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const endLine = shape === 'nested' ? count * 2 - i : i + 2;
|
||||
scopes.push(
|
||||
mkScope(`scope:${i}`, 'a.ts', 'Function', {
|
||||
startLine: i + 2,
|
||||
startCol: 0,
|
||||
get endLine() {
|
||||
endChecks++;
|
||||
return endLine;
|
||||
},
|
||||
endCol: 0,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const index = buildPositionIndex(scopes);
|
||||
endChecks = 0;
|
||||
for (let i = 0; i < count; i++)
|
||||
expect(index.atPosition('a.ts', count * 2 + i + 1, 0)).toBe('module');
|
||||
// Count comparisons rather than elapsed time: expired scopes must not
|
||||
// all be visited again for every outer read, even with deep nesting.
|
||||
expect(endChecks).toBeLessThan(count * 8 * Math.ceil(Math.log2(scopes.length)));
|
||||
},
|
||||
);
|
||||
|
||||
it('deduplicates scopes with the same id', () => {
|
||||
const s = mkScope('scope:dup', 'a.ts', 'Module', r(1, 0, 10, 0));
|
||||
const idx = buildPositionIndex([s, s, s]);
|
||||
|
|
|
|||
|
|
@ -7,6 +7,104 @@ import {
|
|||
import { lookupLexicalName } from 'gitnexus-shared';
|
||||
|
||||
describe('lexical type fact ownership', () => {
|
||||
describe.each([
|
||||
{ provider: typescriptProvider, extension: 'ts' },
|
||||
{ provider: javascriptProvider, extension: 'js' },
|
||||
])('$extension inferred writes', ({ provider, extension }) => {
|
||||
it.each([
|
||||
{
|
||||
shape: 'an unresolved assignment',
|
||||
source: 'function f(a) { const swap = () => { a = evil; a.m(); }; }',
|
||||
inferred: undefined,
|
||||
},
|
||||
{
|
||||
shape: 'a chained constructor assignment',
|
||||
source:
|
||||
'const evil = new Map(); function f(a) { const swap = () => { a = evil; a.m(); }; }',
|
||||
inferred: 'Map',
|
||||
},
|
||||
{
|
||||
shape: 'a direct constructor assignment',
|
||||
source: 'function f(a) { const swap = () => { a = new Foo(); a.m(); }; }',
|
||||
inferred: 'Foo',
|
||||
},
|
||||
{
|
||||
shape: 'a module binding assignment',
|
||||
source: 'let a; const swap = () => { a = new Map(); a.m(); };',
|
||||
inferred: 'Map',
|
||||
},
|
||||
])('resolves $shape to its declaration', ({ source, inferred }) => {
|
||||
const parsed = extractParsedFile(provider, source, `app.${extension}`)!;
|
||||
const site = parsed.referenceSites.find((entry) => entry.name === 'm')!;
|
||||
const owner = parsed.scopes.find((entry) =>
|
||||
entry.nameClaims?.some((claim) => claim.name === 'a'),
|
||||
)!;
|
||||
const selected = lookupLexicalName(
|
||||
site.inScope,
|
||||
'a',
|
||||
{ scopes: { getScope: (id) => parsed.scopes.find((entry) => entry.id === id) } },
|
||||
{ position: site.atRange, purpose: 'value' },
|
||||
);
|
||||
expect(selected.scope).toBe(owner);
|
||||
expect(selected.typeBinding?.rawName).toBe(inferred);
|
||||
});
|
||||
|
||||
it('does not promote a closure write into an outer receiver fact', () => {
|
||||
const parsed = extractParsedFile(
|
||||
provider,
|
||||
'function f(a) { const swap = () => { a = new Foo(); }; a.m(); }',
|
||||
`app.${extension}`,
|
||||
)!;
|
||||
const site = parsed.referenceSites.find((entry) => entry.name === 'm')!;
|
||||
const selected = lookupLexicalName(
|
||||
site.inScope,
|
||||
'a',
|
||||
{ scopes: { getScope: (id) => parsed.scopes.find((entry) => entry.id === id) } },
|
||||
{ position: site.atRange, purpose: 'value' },
|
||||
);
|
||||
expect(selected.scope?.id).toBe(site.inScope);
|
||||
expect(selected.typeBinding).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ provider: typescriptProvider, extension: 'ts', declaration: 'function f(a: Base)' },
|
||||
{
|
||||
provider: javascriptProvider,
|
||||
extension: 'js',
|
||||
declaration: '/** @param {Base} a */ function f(a)',
|
||||
},
|
||||
])(
|
||||
'preserves the $extension declared receiver type across a closure write',
|
||||
({ provider, extension, declaration }) => {
|
||||
const parsed = extractParsedFile(
|
||||
provider,
|
||||
`${declaration} { const swap = () => { a = new Foo(); a.inner(); }; a.outer(); }`,
|
||||
`app.${extension}`,
|
||||
)!;
|
||||
const owner = parsed.scopes.find((entry) =>
|
||||
entry.nameClaims?.some((claim) => claim.name === 'a'),
|
||||
)!;
|
||||
const declared = owner.typeBindings.get('a');
|
||||
expect(declared).toMatchObject({
|
||||
rawName: 'Base',
|
||||
source: 'parameter-annotation',
|
||||
lookupPurpose: 'type',
|
||||
});
|
||||
for (const name of ['inner', 'outer']) {
|
||||
const site = parsed.referenceSites.find((entry) => entry.name === name)!;
|
||||
const selected = lookupLexicalName(
|
||||
site.inScope,
|
||||
'a',
|
||||
{ scopes: { getScope: (id) => parsed.scopes.find((entry) => entry.id === id) } },
|
||||
{ position: site.atRange, purpose: 'value' },
|
||||
);
|
||||
expect(selected.scope).toBe(owner);
|
||||
expect(selected.typeBinding).toBe(declared);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps JSDoc parameter types in their declaring functions', () => {
|
||||
const parsed = extractParsedFile(
|
||||
javascriptProvider,
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ import { FUNCTION_NODE_TYPES as TS_FUNCTION_NODE_TYPES } from '../../src/core/in
|
|||
import { FUNCTION_NODE_TYPES as JS_FUNCTION_NODE_TYPES } from '../../src/core/ingestion/languages/javascript/captures.js';
|
||||
import { THIS_REBINDING_BOUNDARY_TYPES } from '../../src/core/ingestion/languages/typescript/receiver-binding.js';
|
||||
import { THIS_BOUNDARY_NODE_TYPES } from '../../src/core/ingestion/type-extractors/typescript.js';
|
||||
import { LEXICAL_FUNCTION_TYPES } from '../../src/core/ingestion/route-extractors/lexical-bindings.js';
|
||||
|
||||
/**
|
||||
* Node types of every single-line `(node_type) @capture …` pattern in a query
|
||||
|
|
@ -79,6 +80,13 @@ describe('the @scope.function patterns and FUNCTION_NODE_TYPES agree', () => {
|
|||
expect(fromQuery.size).toBeGreaterThan(0);
|
||||
expect(sorted(fromQuery)).toEqual(sorted(JS_FUNCTION_NODE_TYPES));
|
||||
});
|
||||
|
||||
it('HTTP lexical bindings use the TypeScript function scopes, which cover JavaScript', () => {
|
||||
expect(sorted(LEXICAL_FUNCTION_TYPES)).toEqual(sorted(TS_FUNCTION_NODE_TYPES));
|
||||
expect([...JS_FUNCTION_NODE_TYPES].filter((type) => !LEXICAL_FUNCTION_TYPES.has(type))).toEqual(
|
||||
[],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the @receiver-owner.this markers and THIS_REBINDING_BOUNDARY_TYPES agree', () => {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue