mirror of
https://github.com/morluto/rea.git
synced 2026-11-17 04:04:25 +00:00
fix(reference): preserve source scope and loader authority
Share parser-owned package and runtime facts across dependency consumers. Preserve uncertain loader requests and explicit wrapper bindings without inventing unbound require authority in known modules. Cover selected source grammar through the public MCP boundary and retain ambient/type dependencies. Open each selected directory before loading its scoped policy, retaining partial directory failures and cleanup ownership. Preserve explicit caller negation precedence and source diagnostics across inventory projections. Clarify how version comparison retains container provenance without claiming semantic drift. Use independent unknown source inputs to keep candidate-limit fixtures meaningful as conditional branch evaluation becomes more precise. Fixes #6891 Fixes #6882 Fixes #6883 Fixes #6859
This commit is contained in:
1 parent
52aeeee764
commit
d5df7fd944
24 files changed
+813
-143
No files matched your search
@@ -162,7 +162,7 @@ it("resolves declared package mains and index fallback from source-owned fields"
|
||||
'require("./pkg");\nrequire("./dep");\nrequire("./fallback");\n',
|
||||
],
|
||||
[
|
||||
"main.ts",
|
||||
"main.cts",
|
||||
'import dep = require("./typed");\n' +
|
||||
'require("./typed");\n' +
|
||||
'import data = require("./json-package");\n' +
|
||||
@@ -239,28 +239,28 @@ it("resolves declared package mains and index fallback from source-owned fields"
|
||||
parse_state: "parsed",
|
||||
});
|
||||
expect(parsed.relationships).toContainEqual({
|
||||
from_path: "main.ts",
|
||||
from_path: "main.cts",
|
||||
to: "typed/index.ts",
|
||||
kind: "requires",
|
||||
resolution: "internal",
|
||||
parse_state: "parsed",
|
||||
});
|
||||
expect(parsed.relationships).toContainEqual({
|
||||
from_path: "main.ts",
|
||||
from_path: "main.cts",
|
||||
to: "typed.js",
|
||||
kind: "requires",
|
||||
resolution: "internal",
|
||||
parse_state: "parsed",
|
||||
});
|
||||
expect(parsed.relationships).toContainEqual({
|
||||
from_path: "main.ts",
|
||||
from_path: "main.cts",
|
||||
to: "json-package/data.json",
|
||||
kind: "requires",
|
||||
resolution: "internal",
|
||||
parse_state: "parsed",
|
||||
});
|
||||
expect(parsed.relationships).toContainEqual({
|
||||
from_path: "main.ts",
|
||||
from_path: "main.cts",
|
||||
to: "emitted.ts",
|
||||
kind: "requires",
|
||||
resolution: "internal",
|
||||
|
||||
@@ -2,7 +2,7 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { posix } from "node:path";
|
||||
|
||||
import type { ReferenceSourcePackageType } from "../domain/referenceSourceRequireBindings.js";
|
||||
import type { JavaScriptPackageType } from "../domain/javascript/javascriptSourceParser.js";
|
||||
import { decodeJavaScriptModuleUrlPath } from "../domain/javascript/javascriptModuleSpecifier.js";
|
||||
import { logicalPathEscapesRoot } from "../domain/artifactIdentity.js";
|
||||
import {
|
||||
@@ -113,7 +113,7 @@ type PackageMain =
|
||||
|
||||
interface PackageMetadata {
|
||||
readonly main: PackageMain;
|
||||
readonly type: ReferenceSourcePackageType;
|
||||
readonly type: JavaScriptPackageType;
|
||||
}
|
||||
const UNKNOWN_PACKAGE: PackageMetadata = {
|
||||
main: { state: "unknown" },
|
||||
@@ -409,7 +409,7 @@ type ReadFile = Extract<ReferenceSourceEntry, { status: "read"; kind: "file" }>;
|
||||
const packageTypeForFile = (
|
||||
path: string,
|
||||
context: SpecifierContext,
|
||||
): ReferenceSourcePackageType => {
|
||||
): JavaScriptPackageType => {
|
||||
let directory = posix.dirname(path);
|
||||
while (true) {
|
||||
const manifest = packageMainForDirectory(directory, context);
|
||||
|
||||
@@ -289,7 +289,9 @@ const buildIgnored = async (
|
||||
ignored: {
|
||||
test: (path) => {
|
||||
const mandatoryMatch = mandatory.test(path);
|
||||
if (mandatoryMatch.ignored) return mandatoryMatch;
|
||||
// Caller negations override project rules just as caller exclusions do.
|
||||
if (mandatoryMatch.ignored || mandatoryMatch.unignored)
|
||||
return mandatoryMatch;
|
||||
let result = mandatoryMatch;
|
||||
const pieces = path.replace(/\/$/u, "").split("/");
|
||||
for (let depth = 0; depth < pieces.length; depth += 1) {
|
||||
|
||||
@@ -347,7 +347,7 @@ describe("JavaScript semantic analysis: dataflow 2", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed on assignment ambiguity and alias cycles", () => {
|
||||
it("preserves initializer uncertainty, assignment ambiguity and alias cycles", () => {
|
||||
const ambiguous = analyzeJavaScriptSemantics(`
|
||||
let current = "first";
|
||||
current = "second";
|
||||
@@ -358,7 +358,8 @@ describe("JavaScript semantic analysis: dataflow 2", () => {
|
||||
status: "ambiguous",
|
||||
});
|
||||
expect(topLevelBinding(ambiguous, "left").value).toMatchObject({
|
||||
status: "cycle",
|
||||
status: "unknown",
|
||||
reason: "Binding right has no proven initializer at this read.",
|
||||
});
|
||||
expect(topLevelBinding(ambiguous, "right").provenance).toMatchObject({
|
||||
status: "cycle",
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as t from "@babel/types";
|
||||
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
|
||||
|
||||
import { BUILTIN_RESOURCE_METHODS } from "./javascriptBuiltinResourceMethods.js";
|
||||
import { javaScriptRuntimeContext } from "./javascriptSourceParser.js";
|
||||
import type { JavaScriptModuleOrigin } from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
resolveSemanticBindingState,
|
||||
@@ -163,7 +164,11 @@ const requireLoaderValueAt = (
|
||||
return "create-require";
|
||||
if (loader.name !== "require") return "local";
|
||||
if (binding === undefined) {
|
||||
if (semanticResolutionBlocked(state, loader, "require")) return "unknown";
|
||||
if (
|
||||
javaScriptRuntimeContext(state.program) === "module" ||
|
||||
semanticResolutionBlocked(state, loader, "require")
|
||||
)
|
||||
return "unknown";
|
||||
return (state.ambientBindingWrites.get("require") ?? []).some(
|
||||
(write) => semanticEffectTiming(node, write, state) !== "after",
|
||||
)
|
||||
@@ -1525,7 +1530,8 @@ export const semanticRequireOrigin = (
|
||||
!isUnmodifiedCommonJsWrapperBinding(current.callee, "require", state) &&
|
||||
!isWrapperRequireInitializerCall(requireBinding, current, state)) ||
|
||||
(requireBinding === undefined &&
|
||||
semanticResolutionBlocked(state, current.callee, "require")) ||
|
||||
(javaScriptRuntimeContext(state.program) === "module" ||
|
||||
semanticResolutionBlocked(state, current.callee, "require"))) ||
|
||||
(state.ambientBindingWrites.get("require") ?? []).some(
|
||||
(write) =>
|
||||
!semanticTopLevelEffectFollowsCapture(
|
||||
|
||||
@@ -602,16 +602,13 @@ export const semanticBindingHasPriorValueWrite = (
|
||||
);
|
||||
};
|
||||
|
||||
/** Program `var` redeclarations retain wrapper identity until a source write. */
|
||||
/** Explicit wrapper facts and program `var` redeclarations retain their lexical identity. */
|
||||
export const commonJsWrapperBindingDeclaration = (
|
||||
node: t.Node,
|
||||
name: string,
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): JavaScriptSemanticBindingState | undefined => {
|
||||
// Parser sourceType separates explicit modules from script/CommonJS source;
|
||||
// specifier resolution mode does not establish that distinction.
|
||||
if (
|
||||
state.program.sourceType !== "script" ||
|
||||
!["module", "exports", "require", "__dirname", "__filename"].includes(
|
||||
name,
|
||||
) ||
|
||||
@@ -621,9 +618,17 @@ export const commonJsWrapperBindingDeclaration = (
|
||||
const binding = resolveSemanticBindingState(state, node, name);
|
||||
if (binding === undefined) return undefined;
|
||||
const scope = state.scopesById.get(binding.scopeId);
|
||||
return scope?.kind === "program" &&
|
||||
binding.declarationKinds.size > 0 &&
|
||||
[...binding.declarationKinds].every((kind) => kind === "var")
|
||||
if (
|
||||
scope?.kind !== "program" ||
|
||||
![...binding.declarationKinds].every((kind) => kind === "var")
|
||||
)
|
||||
return undefined;
|
||||
// The index owns explicit wrapper parameters, including ones with no source
|
||||
// redeclaration. Babel's module classification does not invalidate that fact.
|
||||
if (binding.hostOrigin === "commonjs-wrapper") return binding;
|
||||
// Without an explicit host fact, preserve the legacy script-var inference.
|
||||
return state.program.sourceType === "script" &&
|
||||
binding.declarationKinds.size > 0
|
||||
? binding
|
||||
: undefined;
|
||||
};
|
||||
@@ -15,6 +15,13 @@ export type ParsedJavaScriptSource = ReturnType<typeof parse>;
|
||||
// Babel's module classification includes erased TypeScript syntax. Keep the
|
||||
// runtime proof separate, including explicit filename mode, for every parser entry.
|
||||
type JavaScriptRuntimeContext = "module" | "commonjs" | "unknown";
|
||||
/** Package scope observed inside a source inventory; missing scope is unknown. */
|
||||
export type JavaScriptPackageType =
|
||||
| "module"
|
||||
| "commonjs"
|
||||
| "unspecified"
|
||||
| "unknown";
|
||||
|
||||
const runtimeContextByProgram = new WeakMap<
|
||||
t.Program,
|
||||
JavaScriptRuntimeContext
|
||||
@@ -53,6 +60,7 @@ const parseWithRuntimeContext = (
|
||||
source: string,
|
||||
sourcePath: string | undefined,
|
||||
options: ParserOptions,
|
||||
packageContext?: JavaScriptPackageType,
|
||||
): ParsedJavaScriptSource => {
|
||||
const file = parse(source, options);
|
||||
runtimeContextByProgram.set(
|
||||
@@ -63,13 +71,19 @@ const parseWithRuntimeContext = (
|
||||
: "commonjs"
|
||||
: isExplicitModuleSourcePath(sourcePath)
|
||||
? "module"
|
||||
: file.program.body.some((node) => t.isTSExportAssignment(node))
|
||||
? // CommonJS isolation does not establish strict ESM semantics.
|
||||
"commonjs"
|
||||
: file.program.sourceType === "module" &&
|
||||
hasRuntimeModuleDeclaration(file.program)
|
||||
? "module"
|
||||
: "unknown",
|
||||
: packageContext === "module" || packageContext === "commonjs"
|
||||
? packageContext
|
||||
: packageContext === "unspecified" && /\.js$/iu.test(sourcePath ?? "")
|
||||
? file.program.sourceType === "module"
|
||||
? "module"
|
||||
: "commonjs"
|
||||
: file.program.body.some((node) => t.isTSExportAssignment(node))
|
||||
? // CommonJS isolation does not establish strict ESM semantics.
|
||||
"commonjs"
|
||||
: file.program.sourceType === "module" &&
|
||||
hasRuntimeModuleDeclaration(file.program)
|
||||
? "module"
|
||||
: "unknown",
|
||||
);
|
||||
return file;
|
||||
};
|
||||
@@ -141,8 +155,25 @@ export const parseRecoveredJavaScript = (
|
||||
source: string,
|
||||
sourcePath: string | undefined,
|
||||
options: Omit<ParserOptions, "sourceType" | "errorRecovery">,
|
||||
observedPackageType?: JavaScriptPackageType,
|
||||
): RecoveredJavaScriptParse => {
|
||||
const sourceType = runtimeSourceTypeForPath(sourcePath);
|
||||
const filenameType = runtimeSourceTypeForPath(sourcePath);
|
||||
// Node package facts apply to .js/.ts sources, not explicit suffixes,
|
||||
// declaration wrappers, or an unknown JSX compilation pipeline.
|
||||
const packageContext =
|
||||
/\.(?:js|ts)$/iu.test(sourcePath ?? "") &&
|
||||
!/\.d\.ts$/iu.test(sourcePath ?? "")
|
||||
? observedPackageType
|
||||
: undefined;
|
||||
// Retain TypeScript import syntax for later CommonJS compilation.
|
||||
const sourceType =
|
||||
filenameType !== "unambiguous"
|
||||
? filenameType
|
||||
: packageContext === "module"
|
||||
? "module"
|
||||
: packageContext === "commonjs" && /\.js$/iu.test(sourcePath ?? "")
|
||||
? "commonjs"
|
||||
: "unambiguous";
|
||||
if (sourceType !== "unambiguous") {
|
||||
const normalizedOptions = { ...options };
|
||||
if (sourceType === "commonjs") {
|
||||
@@ -153,32 +184,50 @@ export const parseRecoveredJavaScript = (
|
||||
delete normalizedOptions.allowNewTargetOutsideFunction;
|
||||
}
|
||||
return {
|
||||
file: parseWithRuntimeContext(source, sourcePath, {
|
||||
...normalizedOptions,
|
||||
sourceType,
|
||||
errorRecovery: true,
|
||||
}),
|
||||
file: parseWithRuntimeContext(
|
||||
source,
|
||||
sourcePath,
|
||||
{
|
||||
...normalizedOptions,
|
||||
sourceType,
|
||||
errorRecovery: true,
|
||||
},
|
||||
packageContext,
|
||||
),
|
||||
moduleOnlyErrors: [],
|
||||
};
|
||||
}
|
||||
const file = parseWithRuntimeContext(source, sourcePath, {
|
||||
...options,
|
||||
sourceType: "unambiguous",
|
||||
errorRecovery: true,
|
||||
});
|
||||
const file = parseWithRuntimeContext(
|
||||
source,
|
||||
sourcePath,
|
||||
{
|
||||
...options,
|
||||
sourceType: "unambiguous",
|
||||
errorRecovery: true,
|
||||
},
|
||||
packageContext,
|
||||
);
|
||||
if (file.program.sourceType !== "script" || file.errors.length === 0)
|
||||
return { file, moduleOnlyErrors: [] };
|
||||
const script = parseWithRuntimeContext(source, sourcePath, {
|
||||
...options,
|
||||
sourceType: "script",
|
||||
errorRecovery: true,
|
||||
});
|
||||
const script = parseWithRuntimeContext(
|
||||
source,
|
||||
sourcePath,
|
||||
{
|
||||
...options,
|
||||
sourceType: "script",
|
||||
errorRecovery: true,
|
||||
},
|
||||
packageContext,
|
||||
);
|
||||
const scriptErrors = new Set(script.errors.map((error) => error.message));
|
||||
return {
|
||||
file: script,
|
||||
moduleOnlyErrors: file.errors
|
||||
.map((error) => error.message)
|
||||
.filter((message) => !scriptErrors.has(message)),
|
||||
moduleOnlyErrors:
|
||||
javaScriptRuntimeContext(script.program) === "commonjs"
|
||||
? []
|
||||
: file.errors
|
||||
.map((error) => error.message)
|
||||
.filter((message) => !scriptErrors.has(message)),
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { expect, it } from "vitest";
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import {
|
||||
analyzeParsedJavaScriptSemantics,
|
||||
indexJavaScriptBindingsWithReceiversSteps,
|
||||
} from "./javascriptSemanticAnalysis.js";
|
||||
import {
|
||||
semanticRequireLoaderAt,
|
||||
semanticRequireOrigin,
|
||||
} from "./javascriptSemanticRequireOrigin.js";
|
||||
import {
|
||||
completeSemanticSteps,
|
||||
traverseJavaScriptAst,
|
||||
} from "./javascriptSemanticTraversal.js";
|
||||
import { referenceSourceRequireCalls } from "../referenceSourceRequireBindings.js";
|
||||
|
||||
import {
|
||||
javaScriptRuntimeContext,
|
||||
parseRecoveredJavaScript,
|
||||
parserPluginsForPath,
|
||||
} from "./javascriptSourceParser.js";
|
||||
|
||||
it.each([
|
||||
["entry.cjs", "module", "commonjs"],
|
||||
["entry.cts", "module", "commonjs"],
|
||||
["entry.mjs", "commonjs", "module"],
|
||||
["entry.mts", "commonjs", "module"],
|
||||
["entry.d.cts", "module", "unknown"],
|
||||
["entry.d.ts", "commonjs", "unknown"],
|
||||
["entry.d.mts", "commonjs", "module"],
|
||||
["entry.jsx", "commonjs", "unknown"],
|
||||
["entry.tsx", "commonjs", "unknown"],
|
||||
["entry.js", "module", "module"],
|
||||
["entry.ts", "commonjs", "commonjs"],
|
||||
["entry.js", "unspecified", "commonjs"],
|
||||
["entry.ts", "unspecified", "unknown"],
|
||||
["entry.js", "unknown", "unknown"],
|
||||
] as const)(
|
||||
"preserves parser-owned %s context over an observed %s package type",
|
||||
(path, observed, expected) => {
|
||||
const parsed = parseRecoveredJavaScript(
|
||||
"",
|
||||
path,
|
||||
{
|
||||
plugins: parserPluginsForPath(path),
|
||||
},
|
||||
observed,
|
||||
);
|
||||
expect(parsed.file.errors).toEqual([]);
|
||||
expect(parsed.moduleOnlyErrors).toEqual([]);
|
||||
expect(javaScriptRuntimeContext(parsed.file.program)).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not derive factory authority from an ambient require in a proven module", () => {
|
||||
const source = [
|
||||
'const { createRequire } = require("node:module");',
|
||||
'const load = createRequire(import.meta.url); load("./dep.cjs");',
|
||||
].join("\n");
|
||||
const { file } = parseRecoveredJavaScript(source, "entry.js", {}, "module");
|
||||
expect(file.errors).toEqual([]);
|
||||
expect(analyzeParsedJavaScriptSemantics(file).moduleLinks).toEqual([]);
|
||||
expect([...referenceSourceRequireCalls(file, "entry.js")]).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["without source redeclarations", "", "", true],
|
||||
["with a var redeclaration", "var require;\n", "", true],
|
||||
["after a prior write", "require = custom;\n", "", false],
|
||||
["before a later write", "", "\nrequire = custom;", true],
|
||||
["behind a lexical declaration", "const require = custom;\n", "", false],
|
||||
["behind a nested parameter", "function shadow(require) {\n", "\n}", false],
|
||||
] as const)(
|
||||
"uses the seeded wrapper fact consistently %s",
|
||||
(_name, prefix, suffix, expected) => {
|
||||
const source =
|
||||
prefix +
|
||||
[
|
||||
'const { createRequire } = require("node:module");',
|
||||
'const load = createRequire(import.meta.url); load("./dep.cjs");',
|
||||
].join("\n") +
|
||||
suffix;
|
||||
const { file } = parseRecoveredJavaScript(source, "entry.js", {});
|
||||
expect(file.errors).toEqual([]);
|
||||
expect(file.program.sourceType).toBe("module");
|
||||
expect(javaScriptRuntimeContext(file.program)).toBe("unknown");
|
||||
const index = completeSemanticSteps(
|
||||
indexJavaScriptBindingsWithReceiversSteps(
|
||||
file.program,
|
||||
"commonjs-wrapper",
|
||||
),
|
||||
);
|
||||
completeSemanticSteps(index.indexMemberMutationFactsSteps());
|
||||
let required: t.CallExpression | undefined;
|
||||
let loaded: t.CallExpression | undefined;
|
||||
traverseJavaScriptAst(file.program, {
|
||||
enter: (node) => {
|
||||
if (!t.isCallExpression(node)) return;
|
||||
if (t.isIdentifier(node.callee, { name: "require" })) required = node;
|
||||
if (t.isIdentifier(node.callee, { name: "load" })) loaded = node;
|
||||
},
|
||||
});
|
||||
if (required === undefined || loaded === undefined)
|
||||
throw new Error("Expected loader fixture calls");
|
||||
expect(
|
||||
semanticRequireOrigin(required, index.bindings)?.origin.specifier,
|
||||
).toBe(expected ? "node:module" : undefined);
|
||||
expect(semanticRequireLoaderAt(loaded, index.bindings, new Set())).toBe(
|
||||
expected ? "create-require" : "local",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("detects JavaScript module syntax within an observed unspecified package", () => {
|
||||
const { file } = parseRecoveredJavaScript(
|
||||
"void import.meta.url;",
|
||||
"entry.js",
|
||||
{},
|
||||
"unspecified",
|
||||
);
|
||||
expect(file.errors).toEqual([]);
|
||||
expect(javaScriptRuntimeContext(file.program)).toBe("module");
|
||||
});
|
||||
@@ -9,11 +9,11 @@ import { readExactJavaScriptLiteral } from "./javascript/javascriptAstValues.js"
|
||||
import {
|
||||
parseRecoveredJavaScript,
|
||||
parserPluginsForPath,
|
||||
type JavaScriptPackageType,
|
||||
} from "./javascript/javascriptSourceParser.js";
|
||||
import {
|
||||
referenceSourceRequireCalls,
|
||||
type ReferenceSourceRequireCall,
|
||||
type ReferenceSourcePackageType,
|
||||
} from "./referenceSourceRequireBindings.js";
|
||||
import { isRelativeJavaScriptModuleSpecifier } from "./javascript/javascriptModuleSpecifier.js";
|
||||
import {
|
||||
@@ -198,6 +198,11 @@ const extractImports = (
|
||||
if (requireCall === undefined) return;
|
||||
const specifier = exactStringModuleName(requireCall.arguments?.[0]);
|
||||
if (specifier === undefined) return;
|
||||
if (
|
||||
requireCall.limitation !== undefined &&
|
||||
!limitations.includes(requireCall.limitation)
|
||||
)
|
||||
limitations.push(requireCall.limitation);
|
||||
const uncertainResolution = requireCall.resolutionBase === "unknown";
|
||||
appendRelationship(relationships, limitations, {
|
||||
fromPath: from_path,
|
||||
@@ -220,16 +225,13 @@ const extractImports = (
|
||||
const parseWithBabel = (
|
||||
path: string,
|
||||
source: string,
|
||||
language: string | null,
|
||||
packageType: JavaScriptPackageType | undefined,
|
||||
): {
|
||||
ast: File | undefined;
|
||||
reasons: readonly string[];
|
||||
moduleOnlyErrors: readonly string[];
|
||||
} => {
|
||||
// Single parser-mode owner: path-driven plugins (dts/JSX/mts) shared with
|
||||
// the semantic pipeline. `language` only gates non-JS/TS callers upstream;
|
||||
// TypeScript syntax must parse identically here and in semantic analysis.
|
||||
void language;
|
||||
// The shared parser owns filename precedence and observed package context.
|
||||
const plugins = parserPluginsForPath(path);
|
||||
|
||||
try {
|
||||
@@ -242,6 +244,7 @@ const parseWithBabel = (
|
||||
allowUndeclaredExports: true,
|
||||
plugins,
|
||||
},
|
||||
packageType,
|
||||
);
|
||||
return {
|
||||
ast,
|
||||
@@ -262,7 +265,7 @@ export const parseReferenceSourceImports = (
|
||||
path: string,
|
||||
bytes: Uint8Array,
|
||||
language: string | null,
|
||||
packageType?: ReferenceSourcePackageType,
|
||||
packageType?: JavaScriptPackageType,
|
||||
): ReferenceSourceImportParseResult => {
|
||||
if (language !== null && !PARSEABLE_REFERENCE_SOURCE_LANGUAGES.has(language))
|
||||
return { relationships: [], parse_failures: [], limitations: [] };
|
||||
@@ -287,7 +290,7 @@ export const parseReferenceSourceImports = (
|
||||
const { ast, reasons, moduleOnlyErrors } = parseWithBabel(
|
||||
path,
|
||||
source,
|
||||
language,
|
||||
packageType,
|
||||
);
|
||||
const limitations =
|
||||
moduleOnlyErrors.length === 0
|
||||
@@ -315,7 +318,7 @@ export const parseReferenceSourceImports = (
|
||||
path,
|
||||
relationships,
|
||||
limitations,
|
||||
referenceSourceRequireCalls(ast, path, packageType),
|
||||
referenceSourceRequireCalls(ast, path),
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -18,18 +18,10 @@ import {
|
||||
traverseJavaScriptAst,
|
||||
} from "./javascript/javascriptSemanticTraversal.js";
|
||||
import {
|
||||
isExplicitModuleSourcePath,
|
||||
javaScriptRuntimeContext,
|
||||
type ParsedJavaScriptSource,
|
||||
} from "./javascript/javascriptSourceParser.js";
|
||||
|
||||
/** Package scope observed inside the selected inventory; missing scope stays unknown. */
|
||||
export type ReferenceSourcePackageType =
|
||||
| "module"
|
||||
| "commonjs"
|
||||
| "unspecified"
|
||||
| "unknown";
|
||||
|
||||
export type ReferenceSourceRequireResolutionBase =
|
||||
| "source-file"
|
||||
| { readonly kind: "source-relative-file"; readonly path: string }
|
||||
@@ -38,24 +30,24 @@ export type ReferenceSourceRequireResolutionBase =
|
||||
export interface ReferenceSourceRequireCall {
|
||||
readonly arguments: JavaScriptRequireCallFact["arguments"];
|
||||
readonly resolutionBase: ReferenceSourceRequireResolutionBase;
|
||||
readonly limitation?: string;
|
||||
}
|
||||
|
||||
/** Identify exact calls through a source-owned Node loader and their resolver base. */
|
||||
export const referenceSourceRequireCalls = (
|
||||
file: Pick<ParsedJavaScriptSource, "program">,
|
||||
path: string,
|
||||
packageType: ReferenceSourcePackageType = "unknown",
|
||||
): ReadonlyMap<
|
||||
t.CallExpression | t.OptionalCallExpression,
|
||||
ReferenceSourceRequireCall
|
||||
> => {
|
||||
// Unmarked paths depend on package scope or compiler options. Preserve their
|
||||
// candidate CommonJS edges; explicit module paths have no wrapper loader.
|
||||
const wrapperMode = commonJsWrapperMode(path, file.program, packageType);
|
||||
const runtimeContext = javaScriptRuntimeContext(file.program);
|
||||
const index = completeSemanticSteps(
|
||||
indexJavaScriptBindingsWithReceiversSteps(
|
||||
file.program,
|
||||
wrapperMode === "absent" ? undefined : "commonjs-wrapper",
|
||||
runtimeContext === "module" ? undefined : "commonjs-wrapper",
|
||||
),
|
||||
);
|
||||
const factoryBindings: ReadonlySet<string> = new Set();
|
||||
@@ -64,6 +56,7 @@ export const referenceSourceRequireCalls = (
|
||||
readonly identifier: t.Identifier;
|
||||
readonly arguments: JavaScriptRequireCallFact["arguments"];
|
||||
readonly resolutionBase: ReferenceSourceRequireResolutionBase;
|
||||
readonly limitation?: string;
|
||||
}[] = [];
|
||||
traverseJavaScriptAst(file.program, {
|
||||
enter: (node) => {
|
||||
@@ -85,7 +78,6 @@ export const referenceSourceRequireCalls = (
|
||||
);
|
||||
if (callFact === undefined || callFact.loader === "local") return;
|
||||
if (fact !== "create-require" && fact !== "commonjs-loader") return;
|
||||
if (fact === "commonjs-loader" && wrapperMode === "absent") return;
|
||||
const sourceRelativePath = callFact.sourceRelativePath;
|
||||
const normalizedSourceRelativePath =
|
||||
sourceRelativePath === undefined
|
||||
@@ -94,38 +86,45 @@ export const referenceSourceRequireCalls = (
|
||||
posix.join(posix.dirname(path), sourceRelativePath),
|
||||
);
|
||||
const base: ReferenceSourceRequireResolutionBase =
|
||||
callFact.loader === "create-require"
|
||||
? sourceRelativePath === undefined
|
||||
? callFact.sourceRelative === true
|
||||
? "source-file"
|
||||
: "unknown"
|
||||
: normalizedSourceRelativePath === undefined ||
|
||||
normalizedSourceRelativePath === ".." ||
|
||||
normalizedSourceRelativePath.startsWith("../")
|
||||
? "unknown"
|
||||
: normalizedSourceRelativePath === path
|
||||
runtimeContext === "unknown"
|
||||
? "unknown"
|
||||
: callFact.loader === "create-require"
|
||||
? sourceRelativePath === undefined
|
||||
? callFact.sourceRelative === true
|
||||
? "source-file"
|
||||
: {
|
||||
kind: "source-relative-file",
|
||||
path: normalizedSourceRelativePath,
|
||||
}
|
||||
: fact === "commonjs-loader" && callFact.loader === "commonjs-loader"
|
||||
? path.endsWith(".js") && wrapperMode === "unknown"
|
||||
? "unknown"
|
||||
: "source-file"
|
||||
: "unknown";
|
||||
: "unknown"
|
||||
: normalizedSourceRelativePath === undefined ||
|
||||
normalizedSourceRelativePath === ".." ||
|
||||
normalizedSourceRelativePath.startsWith("../")
|
||||
? "unknown"
|
||||
: normalizedSourceRelativePath === path
|
||||
? "source-file"
|
||||
: {
|
||||
kind: "source-relative-file",
|
||||
path: normalizedSourceRelativePath,
|
||||
}
|
||||
: fact === "commonjs-loader" &&
|
||||
callFact.loader === "commonjs-loader" &&
|
||||
runtimeContext === "commonjs"
|
||||
? "source-file"
|
||||
: "unknown";
|
||||
const searchBase = requireResolveSearchBase(
|
||||
callFact.operation,
|
||||
callFact.arguments,
|
||||
index.bindings,
|
||||
base,
|
||||
wrapperMode === "present",
|
||||
runtimeContext === "commonjs",
|
||||
);
|
||||
candidates.push({
|
||||
call: node,
|
||||
identifier,
|
||||
arguments: callFact.arguments,
|
||||
resolutionBase: searchBase,
|
||||
...(runtimeContext === "unknown"
|
||||
? {
|
||||
limitation: `Module context is unknown in ${path}; the requested dependency was retained without a proven loader base.`,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -133,11 +132,18 @@ export const referenceSourceRequireCalls = (
|
||||
completeSemanticSteps(index.indexMemberMutationFactsSteps());
|
||||
return new Map(
|
||||
candidates.map(
|
||||
({ call, identifier, arguments: callArguments, resolutionBase }) =>
|
||||
({
|
||||
call,
|
||||
identifier,
|
||||
arguments: callArguments,
|
||||
resolutionBase,
|
||||
limitation,
|
||||
}) =>
|
||||
[
|
||||
call,
|
||||
{
|
||||
arguments: callArguments,
|
||||
...(limitation === undefined ? {} : { limitation }),
|
||||
resolutionBase:
|
||||
!t.isIdentifier(call.callee) &&
|
||||
hasPriorMemberMutation(index, call, identifier)
|
||||
@@ -179,25 +185,6 @@ const requireResolveSearchBase = (
|
||||
: "unknown";
|
||||
};
|
||||
|
||||
type CommonJsWrapperMode = "present" | "absent" | "unknown";
|
||||
|
||||
const commonJsWrapperMode = (
|
||||
path: string,
|
||||
program: t.Program,
|
||||
packageType: ReferenceSourcePackageType,
|
||||
): CommonJsWrapperMode => {
|
||||
if (path.endsWith(".cjs")) return "present";
|
||||
if (isExplicitModuleSourcePath(path)) return "absent";
|
||||
if (path.endsWith(".js")) {
|
||||
if (packageType === "module") return "absent";
|
||||
if (packageType === "commonjs") return "present";
|
||||
if (packageType === "unknown") return "unknown";
|
||||
if (javaScriptRuntimeContext(program) === "module") return "absent";
|
||||
return "present";
|
||||
}
|
||||
return "unknown";
|
||||
};
|
||||
|
||||
const hasPriorMemberMutation = (
|
||||
index: JavaScriptReceiverIndex,
|
||||
site: t.CallExpression | t.OptionalCallExpression,
|
||||
|
||||
@@ -76,11 +76,6 @@ export const traverseDirectory = async (
|
||||
);
|
||||
return { ok: true, value: undefined };
|
||||
}
|
||||
const policy = await state.beforeDirectory?.(
|
||||
pathFromRoot(state.root, current.path),
|
||||
);
|
||||
if (policy !== undefined && !policy.ok) return policy;
|
||||
if (isAborted(state.signal)) return err(cancelled());
|
||||
const directories: PendingDirectory[] = [];
|
||||
let readFailure: FilesystemFailureDetail | undefined;
|
||||
let unrepresentableNameCount = 0;
|
||||
@@ -101,7 +96,15 @@ export const traverseDirectory = async (
|
||||
let result: ReferenceSourceResult<undefined> = ok(undefined);
|
||||
let cleanup: ArtifactCleanupAttempt;
|
||||
try {
|
||||
for (;;) {
|
||||
// A directory that cannot be opened retains its ordinary partial-entry
|
||||
// failure; only an opened directory needs policy before enumeration.
|
||||
result = isAborted(state.signal)
|
||||
? err(cancelled())
|
||||
: ((await state.beforeDirectory?.(
|
||||
pathFromRoot(state.root, current.path),
|
||||
)) ?? ok(undefined));
|
||||
if (result.ok && isAborted(state.signal)) result = err(cancelled());
|
||||
while (result.ok) {
|
||||
let child: Dirent | null;
|
||||
try {
|
||||
child = await handle.read();
|
||||
@@ -123,7 +126,6 @@ export const traverseDirectory = async (
|
||||
continue;
|
||||
}
|
||||
result = await processEntry(state, current, decoded.name, directories);
|
||||
if (!result.ok) break;
|
||||
}
|
||||
} finally {
|
||||
cleanup = await state.resources.release({
|
||||
|
||||
@@ -18,7 +18,7 @@ export type ReferenceSourceExclusionKind = ReferenceSourceEntryKind | "unknown";
|
||||
|
||||
export interface ReferenceSourceReaderOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
/** Prepare directory-scoped policy after directory identity admission, before enumeration. */
|
||||
/** Prepare policy after identity admission and opening, before enumeration; refusal closes the owned handle. */
|
||||
readonly beforeDirectory?: (
|
||||
path: string,
|
||||
) => Promise<ReferenceSourceResult<undefined>>;
|
||||
@@ -101,7 +101,7 @@ export type TraversalState = {
|
||||
readonly root: string;
|
||||
readonly rootIdentity: BigIntStats;
|
||||
readonly signal?: AbortSignal;
|
||||
/** Prepare directory-scoped policy after directory identity admission, before enumeration. */
|
||||
/** Prepare policy after identity admission and opening, before enumeration; refusal closes the owned handle. */
|
||||
readonly beforeDirectory?: (
|
||||
path: string,
|
||||
) => Promise<ReferenceSourceResult<undefined>>;
|
||||
|
||||
Reference in new issue
Block a user