Files
rea/src/domain/referenceSourcePathIdentity.ts
T
c0d550b231 fix(reference): resolve runtime imports from their owning syntax
Distinguish call-form require from TypeScript import-equals before resolving
inventory paths. Probe CommonJS files before indexes and honor package main
without requiring an index. Retain selected manifest directory identities and
reuse the path lookup owner for canonical ambiguity.

Validated with source/reader tests and a public CLI fixture controlled by the
pinned Node loader. Windows no-follow reader behavior remains unverified.
Refs #3895, #3896, #3973, #4017.

Co-authored-by: hhang <169027046+xu91102@users.noreply.github.com>
Co-authored-by: IssueHunter Worker <issuehunter@users.noreply.github.com>
2026-10-16 05:43:04 +08:00

56 lines
2.0 KiB
TypeScript

import { posix } from "node:path";
export interface ReferenceSourcePathLookup {
/** Whether an exact or canonical identity exists, including ambiguous ones. */
readonly has: (path: string) => boolean;
readonly resolve: (path: string) => string | undefined;
readonly resolveCandidates: (paths: readonly string[]) => string | undefined;
/** Resolve a path to the closest recorded parent identity. */
readonly resolveAncestor: (path: string) => string | undefined;
}
/**
* Reference inventories retain filesystem spelling. Prefer that exact identity;
* canonical Unicode equivalence is a fallback only when it identifies one entry.
*/
export const createReferenceSourcePathLookup = (
paths: Iterable<string>,
): ReferenceSourcePathLookup => {
const exact = new Set(paths);
const canonical = new Map<string, string | null>();
for (const path of exact) {
const key = path.normalize("NFC");
canonical.set(key, canonical.has(key) ? null : path);
}
const equivalent = (path: string): string | undefined =>
canonical.get(path.normalize("NFC")) ?? undefined;
const has = (path: string): boolean =>
exact.has(path) || canonical.has(path.normalize("NFC"));
const resolve = (path: string): string | undefined =>
exact.has(path) ? path : equivalent(path);
return {
has,
resolve,
resolveCandidates: (candidates) =>
candidates.find((path) => exact.has(path)) ??
candidates.map(equivalent).find((path) => path !== undefined),
resolveAncestor: (path) => {
for (
let candidate = path;
candidate !== "." && candidate !== "/";
candidate = posix.dirname(candidate)
) {
const found = resolve(candidate);
if (found !== undefined) return found;
}
return undefined;
},
};
};
/** Symlink evidence can originate on a different OS from the graph reader. */
export const isPortableAbsoluteReferenceTarget = (target: string): boolean =>
target.startsWith("/") ||
/^[A-Za-z]:[\\/]/u.test(target) ||
/^\\\\[^\\/]+[\\/][^\\/]+/u.test(target);