merge: integrate main and retain per-slice FAT alignment
This commit is contained in:
@@ -78,7 +78,9 @@ export const readJsonObjectFile = (
|
||||
value === null ||
|
||||
Array.isArray(value)
|
||||
)
|
||||
throw new TypeError("JSON document root must be an object");
|
||||
return err(
|
||||
invalidJson(operation, "JSON document root must be an object"),
|
||||
);
|
||||
for (const members of scans)
|
||||
for (const [key, member] of members) {
|
||||
if (!Object.hasOwn(value, key)) continue;
|
||||
@@ -177,7 +179,9 @@ export const readJsonObjectFile = (
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
if (!rootObject)
|
||||
throw new TypeError("JSON document root must be an object");
|
||||
return err(
|
||||
invalidJson(operation, "JSON document root must be an object"),
|
||||
);
|
||||
const digest = hash.digest("hex");
|
||||
if (previousDigest !== undefined && digest !== previousDigest)
|
||||
throw new RegularFileChangedError(path);
|
||||
|
||||
@@ -23,7 +23,7 @@ export const createProgressReporter = (
|
||||
} = {},
|
||||
): ProgressReporter => {
|
||||
const minimumIntervalMs = options.minimumIntervalMs ?? 100;
|
||||
const now = options.now ?? Date.now;
|
||||
const now = options.now ?? (() => performance.now());
|
||||
let lastCompleted = -1;
|
||||
let lastSentAt = Number.NEGATIVE_INFINITY;
|
||||
let sequence = 0;
|
||||
|
||||
@@ -104,7 +104,11 @@ const resolveInternalSpecifier = (
|
||||
]);
|
||||
// Retain present runtime files first; substitute only a missing counterpart.
|
||||
// Counterparts cover explicit filenames, not directory/index resolution.
|
||||
candidates.push(...typescriptEmittedSourceCandidates(fromPath, normalized));
|
||||
candidates.push(
|
||||
...typescriptEmittedSourceCandidates(fromPath, normalized).map(
|
||||
({ path }) => path,
|
||||
),
|
||||
);
|
||||
const match = lookupPath.resolveCandidates(candidates);
|
||||
return match === undefined
|
||||
? { to: normalized, resolution: "unresolved" }
|
||||
|
||||
@@ -8,6 +8,11 @@ const EMITTED_SUFFIXES: ReadonlyArray<
|
||||
[".jsx", [".tsx", ".d.ts"]],
|
||||
];
|
||||
|
||||
export interface TypeScriptEmittedSourceCandidate {
|
||||
readonly path: string;
|
||||
readonly kind: "implementation" | "declaration";
|
||||
}
|
||||
|
||||
/**
|
||||
* Return TypeScript source counterparts for an explicit emitted filename.
|
||||
* Callers retain exact runtime-file precedence and must not use these for
|
||||
@@ -16,7 +21,7 @@ const EMITTED_SUFFIXES: ReadonlyArray<
|
||||
export const typescriptEmittedSourceCandidates = (
|
||||
sourcePath: string,
|
||||
candidate: string,
|
||||
): readonly string[] => {
|
||||
): readonly TypeScriptEmittedSourceCandidate[] => {
|
||||
if (!/\.(?:ts|tsx|mts|cts)$/u.test(sourcePath)) return [];
|
||||
const emitted = EMITTED_SUFFIXES.find(([suffix]) =>
|
||||
candidate.endsWith(suffix),
|
||||
@@ -25,5 +30,8 @@ export const typescriptEmittedSourceCandidates = (
|
||||
// Strip the matched suffix by length. posix.extname would miss dotfile
|
||||
// names such as ".js", whose whole basename is the emitted suffix itself.
|
||||
const stem = candidate.slice(0, candidate.length - emitted[0].length);
|
||||
return emitted[1].map((suffix) => `${stem}${suffix}`);
|
||||
return emitted[1].map((suffix) => ({
|
||||
path: `${stem}${suffix}`,
|
||||
kind: suffix.startsWith(".d.") ? "declaration" : "implementation",
|
||||
}));
|
||||
};
|
||||
|
||||
@@ -22,6 +22,7 @@ export interface WebModuleArtifacts extends SelectedWebScriptArtifacts {
|
||||
|
||||
/** Read selected local artifacts without refetching website assets. */
|
||||
export interface WebModuleArtifactPort {
|
||||
close?(): Promise<void>;
|
||||
load(
|
||||
input: WebModuleTraceInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { closeOwnedWebResources } from "./closeOwnedWebResources.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { z } from "zod";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
@@ -70,7 +71,13 @@ export class WebModuleTraceService {
|
||||
) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.resolver.close?.() ?? Promise.resolve();
|
||||
return closeOwnedWebResources(
|
||||
[
|
||||
this.artifacts.close?.bind(this.artifacts),
|
||||
this.resolver.close?.bind(this.resolver),
|
||||
],
|
||||
"Web module trace cleanup failed",
|
||||
);
|
||||
}
|
||||
|
||||
async trace(
|
||||
|
||||
@@ -12,4 +12,6 @@ export interface WebNetworkCapturePort {
|
||||
input: InspectWebNetworkCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<WebNetworkCapture, AnalysisError>>;
|
||||
/** Retry retained reader/runtime cleanup when the owning service shuts down. */
|
||||
close?(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,11 @@ const OPERATION = "inspect_web_network_capture";
|
||||
export class WebNetworkCaptureService {
|
||||
constructor(readonly port: WebNetworkCapturePort) {}
|
||||
|
||||
/** Release resources retained by the selected capture adapter. */
|
||||
close(): Promise<void> {
|
||||
return this.port.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** Return selected complete records inline, without inventing live browser attribution. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
|
||||
/** Read the caller-selected capture export and verify the selected source identity. */
|
||||
export interface WebScriptArtifactPort {
|
||||
close?(): Promise<void>;
|
||||
load(
|
||||
input: SelectedWebScriptInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface WebSourceLocationArtifacts extends SelectedWebScriptArtifacts {
|
||||
|
||||
/** Replaceable artifact acquisition boundary for a caller-selected pairing. */
|
||||
export interface WebSourceLocationArtifactPort {
|
||||
close?(): Promise<void>;
|
||||
load(
|
||||
input: WebSourceLocationInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { closeOwnedWebResources } from "./closeOwnedWebResources.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { z } from "zod";
|
||||
@@ -71,7 +72,13 @@ export class WebSourceLocationService {
|
||||
) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.decoder.close?.() ?? Promise.resolve();
|
||||
return closeOwnedWebResources(
|
||||
[
|
||||
this.artifacts.close?.bind(this.artifacts),
|
||||
this.decoder.close?.bind(this.decoder),
|
||||
],
|
||||
"Web source-location cleanup failed",
|
||||
);
|
||||
}
|
||||
|
||||
/** Shared CLI/MCP workflow preserves raw declarations and every equal-position match. */
|
||||
@@ -174,6 +181,7 @@ export class WebSourceLocationService {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const invalidOutput = (message: string): Result<never, AnalysisError> =>
|
||||
err(new AnalysisOutputError(OPERATION, message));
|
||||
const invalid = (
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { Result } from "../../domain/result.js";
|
||||
/** Stable read and PE decoding boundary, independent of an active disassembler session. */
|
||||
export interface PeResourcesPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectPeResourcesInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -21,6 +21,10 @@ import { err, ok, type Result } from "../../domain/result.js";
|
||||
export class PeResourcesService {
|
||||
constructor(readonly provider: PeResourcesPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Attempt every web workflow cleanup owner and report all failures. */
|
||||
export const closeOwnedWebResources = async (
|
||||
close: readonly ((() => Promise<void>) | undefined)[],
|
||||
message: string,
|
||||
): Promise<void> => {
|
||||
const results = await Promise.allSettled(
|
||||
close.flatMap((owner) =>
|
||||
owner === undefined ? [] : [Promise.resolve().then(owner)],
|
||||
),
|
||||
);
|
||||
const failures = results.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason] : [],
|
||||
);
|
||||
if (failures.length > 0) throw new AggregateError(failures, message);
|
||||
};
|
||||
@@ -12,6 +12,7 @@ import type { Result } from "../../domain/result.js";
|
||||
/** Replaceable offline build-information reader with no target-execution authority. */
|
||||
export interface GoBinaryPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectGoBinaryInput,
|
||||
options?: ExecutionOptions,
|
||||
|
||||
@@ -34,6 +34,10 @@ const architectureForSubject = (architecture: string) => {
|
||||
export class GoBinaryService {
|
||||
constructor(readonly provider: GoBinaryPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
/** Inspect one explicitly selected file without acquiring a binary session. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { moduleKindForJavaScriptReference } from "./JavaScriptArtifactPathResolution.js";
|
||||
import { moduleResolutionModeForJavaScriptReference } from "../../domain/javascript/javascriptModuleResolutionMode.js";
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
|
||||
import { resolveJavaScriptSourceMapReferences } from "../../domain/javascript/javascriptSourceMapPaths.js";
|
||||
@@ -384,7 +384,10 @@ function* analyzeArtifactFileSteps<
|
||||
analysis.parse_status === "complete" || analysis.parse_status === "partial"
|
||||
? yield* analyzeParsedJavaScriptSemanticsSteps(
|
||||
parsed,
|
||||
moduleKindForJavaScriptReference(file.path, "static-import"),
|
||||
moduleResolutionModeForJavaScriptReference(
|
||||
file.path,
|
||||
"static-import",
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const projected =
|
||||
|
||||
@@ -66,6 +66,7 @@ export interface AstEdgeInput {
|
||||
|
||||
/** Inferred static relationship edge values. */
|
||||
export interface InferenceEdgeInput extends AstEdgeInput {
|
||||
readonly limitations?: readonly string[];
|
||||
readonly relation:
|
||||
| "imports"
|
||||
| "loads"
|
||||
@@ -162,6 +163,9 @@ export const addStaticInferenceEdge = (
|
||||
range: input.range,
|
||||
operation: "map-static-relationship",
|
||||
coverage: input.coverage,
|
||||
...(input.limitations === undefined
|
||||
? {}
|
||||
: { limitations: input.limitations }),
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -347,7 +351,7 @@ export const resolveArtifactPath = (
|
||||
specifier: string,
|
||||
sourcePath: string,
|
||||
files: ReadonlyMap<string, JavaScriptArtifactFile>,
|
||||
moduleKind?: "import" | "require",
|
||||
moduleKind?: "import" | "require" | "compiler-dependent",
|
||||
): string | null =>
|
||||
resolveArtifactPathByContext({
|
||||
declaredPath: specifier,
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
javascriptAnalysisCoverage,
|
||||
linkElectronRoleToAsset,
|
||||
moduleLookupKey,
|
||||
resolveArtifactPath,
|
||||
selfReferenceOmissions,
|
||||
sourceNodeFor,
|
||||
type JavaScriptArtifactGraphContext,
|
||||
@@ -23,9 +22,11 @@ import {
|
||||
staticInferenceEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import {
|
||||
moduleKindForJavaScriptReference,
|
||||
artifactPathResolutionProperties,
|
||||
resolveArtifactPathByContext,
|
||||
type ArtifactPathResolution,
|
||||
} from "./JavaScriptArtifactPathResolution.js";
|
||||
import { moduleResolutionModeForJavaScriptReference } from "../../domain/javascript/javascriptModuleResolutionMode.js";
|
||||
|
||||
type StaticReference = JavaScriptStaticAnalysis["references"][number];
|
||||
type StaticEndpoint = JavaScriptStaticAnalysis["endpoints"][number];
|
||||
@@ -41,9 +42,12 @@ interface FindingInput<Value> {
|
||||
}
|
||||
|
||||
interface ResolvedReference {
|
||||
readonly path: string;
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly path: string | null;
|
||||
readonly file: JavaScriptArtifactFile | null;
|
||||
readonly node: ApplicationNode;
|
||||
readonly limitations: readonly string[];
|
||||
readonly resolutionStatus?: string;
|
||||
readonly resolution?: ArtifactPathResolution;
|
||||
}
|
||||
|
||||
/** Project imports, workers, roles, endpoints, storage, and source-map links. */
|
||||
@@ -90,7 +94,7 @@ const addReference = (
|
||||
const resolved =
|
||||
input.value.specifier === null
|
||||
? null
|
||||
: resolveReference(context, input.file.path, input.value);
|
||||
: resolveReference(context, input.file.path, input.value, input.coverage);
|
||||
if (input.value.kind === "worker" || input.value.kind === "service-worker") {
|
||||
const worker = context.accumulator.addNode({
|
||||
kind: input.value.kind === "worker" ? "worker" : "service-worker",
|
||||
@@ -126,7 +130,7 @@ const addReference = (
|
||||
relation: "loads",
|
||||
properties: { kind: input.value.kind },
|
||||
});
|
||||
if (resolved !== null)
|
||||
if (resolved !== null && resolved.path !== null)
|
||||
addStaticInferenceEdge(context, {
|
||||
source: worker,
|
||||
target: resolved.node,
|
||||
@@ -135,6 +139,7 @@ const addReference = (
|
||||
coverage: input.coverage,
|
||||
relation: "maps_to",
|
||||
properties: { resolved_path: resolved.path },
|
||||
limitations: resolved.limitations,
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -154,13 +159,25 @@ const addReference = (
|
||||
file: input.file,
|
||||
range: input.value.location,
|
||||
coverage: input.coverage,
|
||||
relation: resolved?.file.kind === "native-addon" ? "loads" : "imports",
|
||||
relation: resolved?.file?.kind === "native-addon" ? "loads" : "imports",
|
||||
properties: {
|
||||
kind: input.value.kind,
|
||||
specifier: input.value.specifier,
|
||||
expression: input.value.expression,
|
||||
resolution_mode:
|
||||
input.value.kind === "static-import" ||
|
||||
input.value.kind === "dynamic-import" ||
|
||||
input.value.kind === "require"
|
||||
? moduleResolutionModeForJavaScriptReference(
|
||||
input.file.path,
|
||||
input.value.kind,
|
||||
)
|
||||
: null,
|
||||
resolved_path: resolved?.path ?? null,
|
||||
resolution_status: resolved?.resolutionStatus ?? null,
|
||||
...artifactPathResolutionProperties(resolved?.resolution),
|
||||
},
|
||||
...(resolved === null ? {} : { limitations: resolved.limitations }),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -373,6 +390,7 @@ const resolveReference = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
sourcePath: string,
|
||||
reference: StaticReference,
|
||||
coverage: JavaScriptArtifactGraphCoverage,
|
||||
): ResolvedReference | null => {
|
||||
const specifier = reference.specifier;
|
||||
if (specifier === null) return null;
|
||||
@@ -392,30 +410,70 @@ const resolveReference = (
|
||||
const file = context.filesByPath.get(sourcePath);
|
||||
return file === undefined
|
||||
? null
|
||||
: { path: `${sourcePath}#module:${specifier}`, file, node: module };
|
||||
: {
|
||||
path: `${sourcePath}#module:${specifier}`,
|
||||
file,
|
||||
node: module,
|
||||
limitations: [],
|
||||
};
|
||||
}
|
||||
// Worker scripts are URLs relative to the script, not module specifiers.
|
||||
const path = isWorker
|
||||
const resolution = isWorker
|
||||
? resolveArtifactPathByContext({
|
||||
declaredPath: specifier,
|
||||
sourcePath,
|
||||
context: "url-reference",
|
||||
files: context.filesByPath,
|
||||
}).resolved_path
|
||||
: resolveArtifactPath(
|
||||
specifier,
|
||||
})
|
||||
: resolveArtifactPathByContext({
|
||||
declaredPath: specifier,
|
||||
sourcePath,
|
||||
context.filesByPath,
|
||||
reference.kind === "require" ||
|
||||
reference.kind === "static-import" ||
|
||||
reference.kind === "dynamic-import"
|
||||
? moduleKindForJavaScriptReference(sourcePath, reference.kind)
|
||||
: undefined,
|
||||
);
|
||||
if (path === null) return null;
|
||||
context: "module-specifier",
|
||||
files: context.filesByPath,
|
||||
...("require" === reference.kind ||
|
||||
"static-import" === reference.kind ||
|
||||
"dynamic-import" === reference.kind
|
||||
? {
|
||||
moduleKind: moduleResolutionModeForJavaScriptReference(
|
||||
sourcePath,
|
||||
reference.kind,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
const path = resolution.resolved_path;
|
||||
if (path === null) {
|
||||
if (isWorker) return null;
|
||||
const source = context.filesByPath.get(sourcePath);
|
||||
return source === undefined
|
||||
? null
|
||||
: {
|
||||
path: null,
|
||||
file: null,
|
||||
node: unresolvedReferenceNode(
|
||||
context,
|
||||
source,
|
||||
reference,
|
||||
coverage,
|
||||
resolution,
|
||||
),
|
||||
limitations: resolution.limitations,
|
||||
resolutionStatus: resolution.resolution_status,
|
||||
resolution,
|
||||
};
|
||||
}
|
||||
const file = context.filesByPath.get(path);
|
||||
const node = context.fileNodes.get(path);
|
||||
return file === undefined || node === undefined ? null : { path, file, node };
|
||||
return file === undefined || node === undefined
|
||||
? null
|
||||
: {
|
||||
path,
|
||||
file,
|
||||
node,
|
||||
limitations: resolution.limitations,
|
||||
resolutionStatus: resolution.resolution_status,
|
||||
resolution,
|
||||
};
|
||||
};
|
||||
|
||||
const resolveBundlerChunkReference = (
|
||||
@@ -453,7 +511,7 @@ const resolveBundlerChunkReference = (
|
||||
const node = unique[0];
|
||||
return node === undefined
|
||||
? null
|
||||
: { path: `${sourcePath}#chunk:${key}`, file, node };
|
||||
: { path: `${sourcePath}#chunk:${key}`, file, node, limitations: [] };
|
||||
};
|
||||
|
||||
const unresolvedReferenceNode = (
|
||||
@@ -461,6 +519,7 @@ const unresolvedReferenceNode = (
|
||||
file: JavaScriptArtifactFile,
|
||||
reference: StaticReference,
|
||||
coverage: JavaScriptArtifactGraphCoverage,
|
||||
resolution?: ArtifactPathResolution,
|
||||
): ApplicationNode =>
|
||||
context.accumulator.addNode({
|
||||
kind: "javascript-module",
|
||||
@@ -477,6 +536,10 @@ const unresolvedReferenceNode = (
|
||||
specifier: reference.specifier,
|
||||
expression: reference.expression,
|
||||
resolution: "unresolved",
|
||||
...(resolution === undefined
|
||||
? {}
|
||||
: { resolution_status: resolution.resolution_status }),
|
||||
...artifactPathResolutionProperties(resolution),
|
||||
},
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: file.sha256,
|
||||
@@ -487,6 +550,7 @@ const unresolvedReferenceNode = (
|
||||
confidence: "low",
|
||||
limitations: [
|
||||
"The static reference could not be resolved within the inventoried artifact.",
|
||||
...(resolution?.limitations ?? []),
|
||||
],
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -1890,21 +1890,40 @@ describe("TypeScript NodeNext emitted-extension resolution", () => {
|
||||
).toMatchObject({ resolution_status: "resolved", resolved_path: target });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("TypeScript declaration fallback ownership", () => {
|
||||
const container = "container";
|
||||
|
||||
it.each([
|
||||
["./dep.js", "src/dep.d.ts"],
|
||||
["./cfg.mjs", "src/cfg.d.mts"],
|
||||
["./legacy.cjs", "src/legacy.d.cts"],
|
||||
] as const)(
|
||||
"resolves %s to a declaration counterpart",
|
||||
"retains %s as compile-time evidence without inventing a runtime target",
|
||||
(specifier, target) => {
|
||||
const files = fileMap([
|
||||
file("src/main.ts", container),
|
||||
file(target, container, "export const value = 1;"),
|
||||
]);
|
||||
for (const moduleKind of ["import", "require"] as const) {
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: specifier,
|
||||
sourcePath: "src/main.ts",
|
||||
context: "module-specifier",
|
||||
moduleKind,
|
||||
files,
|
||||
}),
|
||||
).toMatchObject({
|
||||
resolution_status: "unavailable",
|
||||
resolved_path: null,
|
||||
candidate_path: target,
|
||||
});
|
||||
}
|
||||
expect(
|
||||
resolve({
|
||||
declaredPath: specifier,
|
||||
declaredPath: "./" + target.slice(4),
|
||||
sourcePath: "src/main.ts",
|
||||
context: "module-specifier",
|
||||
moduleKind: "import",
|
||||
|
||||
@@ -19,8 +19,13 @@ import {
|
||||
classifyPackageImportTargetString,
|
||||
lookupExactPackageImport,
|
||||
} from "../../domain/javascript/javascriptPackageImportAliases.js";
|
||||
import { typescriptEmittedSourceCandidates } from "../TypeScriptEmittedSourceCandidates.js";
|
||||
import {
|
||||
typescriptEmittedSourceCandidates,
|
||||
type TypeScriptEmittedSourceCandidate,
|
||||
} from "../TypeScriptEmittedSourceCandidates.js";
|
||||
import { isRelativeJavaScriptModuleSpecifier } from "../../domain/javascript/javascriptModuleSpecifier.js";
|
||||
import type { JavaScriptModuleResolutionMode } from "../../domain/javascript/javascriptModuleResolutionMode.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
|
||||
type ArtifactPathResolutionContext =
|
||||
| "package-entrypoint"
|
||||
@@ -39,6 +44,16 @@ interface ArtifactPathResolutionBase {
|
||||
readonly declared_path: string;
|
||||
readonly resolution_context: ArtifactPathResolutionContext;
|
||||
readonly limitations: readonly string[];
|
||||
readonly conditional_resolutions?: readonly ConditionalModuleResolution[];
|
||||
readonly candidate_path?: string;
|
||||
}
|
||||
|
||||
export interface ConditionalModuleResolution {
|
||||
readonly mode: "import" | "require";
|
||||
readonly resolution_status: UnresolvedArtifactPathStatus | "resolved";
|
||||
readonly resolved_path: string | null;
|
||||
readonly candidate_path?: string;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Explicit outcome of artifact-confined path resolution. */
|
||||
@@ -62,26 +77,13 @@ export interface ResolveArtifactPathInput {
|
||||
readonly files: ReadonlyMap<string, JavaScriptArtifactFile>;
|
||||
readonly htmlBaseHref?: string | null;
|
||||
/** Import/require semantics; runtime resource paths omit this provenance. */
|
||||
readonly moduleKind?: "import" | "require";
|
||||
readonly moduleKind?: JavaScriptModuleResolutionMode;
|
||||
}
|
||||
|
||||
/** Loader selected by a source-level JavaScript module reference. */
|
||||
export const moduleKindForJavaScriptReference = (
|
||||
sourcePath: string,
|
||||
referenceKind: "static-import" | "dynamic-import" | "require",
|
||||
resolutionMode?: "import" | "require",
|
||||
): "import" | "require" =>
|
||||
resolutionMode ??
|
||||
(referenceKind === "require" ||
|
||||
(referenceKind === "static-import" &&
|
||||
posix.extname(sourcePath).toLowerCase() === ".cts")
|
||||
? "require"
|
||||
: "import");
|
||||
|
||||
/** Preserve an explicitly retained loader mode on graph relationships. */
|
||||
export const moduleResolutionModeProperties = (
|
||||
mode: "import" | "require" | undefined,
|
||||
): Readonly<Record<string, "import" | "require">> =>
|
||||
mode: JavaScriptModuleResolutionMode | undefined,
|
||||
): Readonly<Record<string, JavaScriptModuleResolutionMode>> =>
|
||||
mode === undefined ? {} : { resolution_mode: mode };
|
||||
|
||||
const EXTENSIONS = [
|
||||
@@ -110,43 +112,116 @@ interface PackageFileTarget {
|
||||
readonly url: URL;
|
||||
}
|
||||
|
||||
type CandidateResolution =
|
||||
| {
|
||||
readonly resolvedPath: string;
|
||||
readonly status: "resolved";
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
type CandidateResolution = {
|
||||
readonly limitations: readonly string[];
|
||||
readonly candidatePath?: string;
|
||||
readonly conditionalResolutions?: readonly ConditionalModuleResolution[];
|
||||
} & (
|
||||
| { readonly resolvedPath: string; readonly status: "resolved" }
|
||||
| {
|
||||
readonly resolvedPath: null;
|
||||
readonly status: UnresolvedArtifactPathStatus;
|
||||
readonly limitations: readonly string[];
|
||||
/** A truthy package main failed, so Node must not try ancestor packages. */
|
||||
readonly stopsAncestorLookup?: true;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
/** Resolve one declaration while preserving its original input identity. */
|
||||
export const resolveArtifactPathByContext = (
|
||||
input: ResolveArtifactPathInput,
|
||||
): ArtifactPathResolution => {
|
||||
const resolution = resolvePath(input);
|
||||
const facts = {
|
||||
declared_path: input.declaredPath,
|
||||
resolution_context: input.context,
|
||||
limitations: resolution.limitations,
|
||||
...(resolution.candidatePath === undefined
|
||||
? {}
|
||||
: { candidate_path: resolution.candidatePath }),
|
||||
...(resolution.conditionalResolutions === undefined
|
||||
? {}
|
||||
: { conditional_resolutions: resolution.conditionalResolutions }),
|
||||
};
|
||||
return resolution.status === "resolved"
|
||||
? {
|
||||
declared_path: input.declaredPath,
|
||||
resolution_context: input.context,
|
||||
...facts,
|
||||
resolved_path: resolution.resolvedPath,
|
||||
resolution_status: resolution.status,
|
||||
limitations: resolution.limitations,
|
||||
}
|
||||
: {
|
||||
declared_path: input.declaredPath,
|
||||
resolution_context: input.context,
|
||||
resolved_path: null,
|
||||
resolution_status: resolution.status,
|
||||
limitations: resolution.limitations,
|
||||
};
|
||||
: { ...facts, resolved_path: null, resolution_status: resolution.status };
|
||||
};
|
||||
|
||||
/** Project retained conditional identities without flattening them into display text. */
|
||||
export const artifactPathResolutionProperties = (
|
||||
resolution: ArtifactPathResolution | undefined,
|
||||
): Readonly<Record<string, JsonValue>> => ({
|
||||
...(resolution?.candidate_path === undefined
|
||||
? {}
|
||||
: { candidate_path: resolution.candidate_path }),
|
||||
...(resolution?.conditional_resolutions === undefined
|
||||
? {}
|
||||
: {
|
||||
conditional_resolutions: resolution.conditional_resolutions.map(
|
||||
(branch) => ({
|
||||
mode: branch.mode,
|
||||
resolution_status: branch.resolution_status,
|
||||
resolved_path: branch.resolved_path,
|
||||
limitations: [...branch.limitations],
|
||||
...(branch.candidate_path === undefined
|
||||
? {}
|
||||
: { candidate_path: branch.candidate_path }),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
});
|
||||
|
||||
const conditionalResolution = (
|
||||
mode: "import" | "require",
|
||||
result: CandidateResolution,
|
||||
): ConditionalModuleResolution => ({
|
||||
mode,
|
||||
resolution_status: result.status,
|
||||
resolved_path: result.resolvedPath,
|
||||
limitations: result.limitations,
|
||||
...(result.candidatePath === undefined
|
||||
? {}
|
||||
: { candidate_path: result.candidatePath }),
|
||||
});
|
||||
|
||||
const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
|
||||
if (input.moduleKind === "compiler-dependent") {
|
||||
const imported = resolvePath({ ...input, moduleKind: "import" });
|
||||
const required = resolvePath({ ...input, moduleKind: "require" });
|
||||
const sameOutcome =
|
||||
imported.status === required.status &&
|
||||
imported.resolvedPath === required.resolvedPath &&
|
||||
imported.candidatePath === required.candidatePath;
|
||||
const limitation =
|
||||
"Static TypeScript loader mode is compiler-dependent without retained compiler options. " +
|
||||
(sameOutcome
|
||||
? "Node import and require resolution agree on this outcome."
|
||||
: "Node import and require resolution disagree; neither branch is an established target.");
|
||||
return sameOutcome
|
||||
? {
|
||||
...imported,
|
||||
limitations: [
|
||||
...new Set([
|
||||
...imported.limitations,
|
||||
...required.limitations,
|
||||
limitation,
|
||||
]),
|
||||
],
|
||||
}
|
||||
: {
|
||||
resolvedPath: null,
|
||||
status: "unavailable",
|
||||
limitations: [limitation],
|
||||
conditionalResolutions: [
|
||||
conditionalResolution("import", imported),
|
||||
conditionalResolution("require", required),
|
||||
],
|
||||
};
|
||||
}
|
||||
// Package import keys are literal lookup identities, not artifact paths.
|
||||
// The selected target is admitted separately by resolveExportTarget.
|
||||
if (
|
||||
@@ -176,12 +251,47 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
|
||||
: [];
|
||||
if (isModuleUrlPath && input.moduleKind === "import")
|
||||
return (
|
||||
resolveFileCandidates(input, [confined, ...emittedSourceCandidates]) ??
|
||||
notFoundCandidate()
|
||||
resolveRuntimeSourceCandidates(
|
||||
input,
|
||||
confined,
|
||||
emittedSourceCandidates,
|
||||
) ?? notFoundCandidate()
|
||||
);
|
||||
return resolveCandidate(input, confined, new Set(), emittedSourceCandidates);
|
||||
};
|
||||
|
||||
const resolveRuntimeSourceCandidates = (
|
||||
input: ResolveArtifactPathInput,
|
||||
exactPath: string,
|
||||
sourceCandidates: readonly TypeScriptEmittedSourceCandidate[],
|
||||
): CandidateResolution | null => {
|
||||
const source = input.files.get(input.sourcePath);
|
||||
const exactCandidate: TypeScriptEmittedSourceCandidate = {
|
||||
path: exactPath,
|
||||
kind: "implementation",
|
||||
};
|
||||
for (const candidate of [exactCandidate, ...sourceCandidates]) {
|
||||
const target = input.files.get(candidate.path);
|
||||
if (
|
||||
target === undefined ||
|
||||
(source !== undefined &&
|
||||
target.container_sha256 !== source.container_sha256)
|
||||
)
|
||||
continue;
|
||||
return candidate.kind === "declaration"
|
||||
? {
|
||||
resolvedPath: null,
|
||||
status: "unavailable",
|
||||
candidatePath: candidate.path,
|
||||
limitations: [
|
||||
"Only a TypeScript declaration fallback was found; it does not establish the requested runtime module.",
|
||||
],
|
||||
}
|
||||
: { resolvedPath: candidate.path, status: "resolved", limitations: [] };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const rejectDeclaration = (declared: string): CandidateResolution | null => {
|
||||
if (declared.length === 0)
|
||||
return unresolvedCandidate("rejected", ["The declared path is empty."]);
|
||||
@@ -849,12 +959,10 @@ const resolveCandidate = (
|
||||
input: ResolveArtifactPathInput,
|
||||
candidate: string,
|
||||
packageChain: ReadonlySet<string>,
|
||||
emittedSourceCandidates: readonly string[] = [],
|
||||
emittedSourceCandidates: readonly TypeScriptEmittedSourceCandidate[] = [],
|
||||
): CandidateResolution =>
|
||||
resolveFileCandidates(input, [
|
||||
...fileCandidates(candidate, input.moduleKind),
|
||||
...emittedSourceCandidates,
|
||||
]) ??
|
||||
resolveFileCandidates(input, fileCandidates(candidate, input.moduleKind)) ??
|
||||
resolveRuntimeSourceCandidates(input, candidate, emittedSourceCandidates) ??
|
||||
resolveDirectory(
|
||||
input,
|
||||
candidate,
|
||||
@@ -940,11 +1048,26 @@ const resolveFileCandidates = (
|
||||
(source === undefined ||
|
||||
target.container_sha256 === source.container_sha256)
|
||||
)
|
||||
return { resolvedPath: path, status: "resolved", limitations: [] };
|
||||
return isRuntimeDeclarationPath(input, path)
|
||||
? {
|
||||
resolvedPath: null,
|
||||
status: "unavailable",
|
||||
candidatePath: path,
|
||||
limitations: [
|
||||
`The TypeScript declaration ${path} is compile-time evidence and cannot identify a runtime module implementation.`,
|
||||
],
|
||||
}
|
||||
: { resolvedPath: path, status: "resolved", limitations: [] };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const isRuntimeDeclarationPath = (
|
||||
input: ResolveArtifactPathInput,
|
||||
path: string,
|
||||
): boolean =>
|
||||
input.moduleKind !== undefined && /\.d\.(?:ts|mts|cts)$/iu.test(path);
|
||||
|
||||
const NODE_MODULE_EXTENSIONS = [".js", ".json", ".node"] as const;
|
||||
|
||||
const fileCandidates = (
|
||||
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticModuleLink,
|
||||
} from "../../domain/javascript/javascriptSemanticIr.js";
|
||||
import { moduleResolutionModeForJavaScriptReference } from "../../domain/javascript/javascriptModuleResolutionMode.js";
|
||||
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
|
||||
import {
|
||||
addAstContainsEdge,
|
||||
@@ -30,7 +31,7 @@ import {
|
||||
staticInferenceEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import {
|
||||
moduleKindForJavaScriptReference,
|
||||
artifactPathResolutionProperties,
|
||||
moduleResolutionModeProperties,
|
||||
resolveArtifactPathByContext,
|
||||
type ArtifactPathResolution,
|
||||
@@ -54,6 +55,7 @@ interface RelationshipInput {
|
||||
type ResolvedModuleTarget = {
|
||||
readonly node: ApplicationNode;
|
||||
readonly limitations: readonly string[];
|
||||
readonly resolution?: ArtifactPathResolution;
|
||||
} & (
|
||||
| {
|
||||
readonly path: string;
|
||||
@@ -287,7 +289,7 @@ const resolveModuleTarget = (
|
||||
sourcePath: input.file.path,
|
||||
context: "module-specifier",
|
||||
files: input.context.filesByPath,
|
||||
moduleKind: moduleKindForJavaScriptReference(
|
||||
moduleKind: moduleResolutionModeForJavaScriptReference(
|
||||
input.file.path,
|
||||
input.link.kind === "require" || input.link.kind === "commonjs-export"
|
||||
? "require"
|
||||
@@ -297,15 +299,12 @@ const resolveModuleTarget = (
|
||||
});
|
||||
if (resolution.resolution_status !== "resolved")
|
||||
return {
|
||||
node: unresolvedModuleNode(
|
||||
input,
|
||||
specifier,
|
||||
resolution.resolution_status,
|
||||
),
|
||||
node: unresolvedModuleNode(input, specifier, resolution),
|
||||
path: null,
|
||||
file: null,
|
||||
status: resolution.resolution_status,
|
||||
limitations: resolution.limitations,
|
||||
resolution,
|
||||
};
|
||||
const path = resolution.resolved_path;
|
||||
const file = input.context.filesByPath.get(path);
|
||||
@@ -322,20 +321,24 @@ const resolveModuleTarget = (
|
||||
file,
|
||||
status: "resolved",
|
||||
limitations: resolution.limitations,
|
||||
resolution,
|
||||
};
|
||||
};
|
||||
|
||||
const unresolvedModuleNode = (
|
||||
input: RelationshipInput,
|
||||
specifier: string,
|
||||
status: Exclude<ResolvedModuleTarget["status"], "resolved">,
|
||||
resolution: Extract<
|
||||
ArtifactPathResolution,
|
||||
{ resolution_status: Exclude<ResolvedModuleTarget["status"], "resolved"> }
|
||||
>,
|
||||
): ApplicationNode =>
|
||||
input.context.accumulator.addNode({
|
||||
kind: "javascript-module",
|
||||
identity: artifactLocalIdentity(
|
||||
input.file.sha256,
|
||||
"unresolved-semantic-module",
|
||||
`${status}:${specifier}`,
|
||||
`${resolution.resolution_status}:${specifier}`,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
@@ -343,7 +346,8 @@ const unresolvedModuleNode = (
|
||||
properties: {
|
||||
semantic_role: "module-reference",
|
||||
declared_specifier: specifier,
|
||||
resolution_status: status,
|
||||
resolution_status: resolution.resolution_status,
|
||||
...artifactPathResolutionProperties(resolution),
|
||||
},
|
||||
evidence: staticInferenceEvidence({
|
||||
sha256: input.file.sha256,
|
||||
@@ -364,6 +368,9 @@ const moduleOriginForExport = (
|
||||
): JavaScriptModuleOrigin | null => {
|
||||
if (link.specifier !== null)
|
||||
return {
|
||||
...(link.resolutionMode === undefined
|
||||
? {}
|
||||
: { resolutionMode: link.resolutionMode }),
|
||||
specifier: link.specifier,
|
||||
importedPath: link.importedName === null ? [] : [link.importedName],
|
||||
};
|
||||
@@ -393,6 +400,7 @@ const relationshipProperties = (
|
||||
exported_name: link.exportedName,
|
||||
resolved_path: target?.path ?? null,
|
||||
resolution_status: target?.status ?? null,
|
||||
...artifactPathResolutionProperties(target?.resolution),
|
||||
target_file_kind: target?.file?.kind ?? null,
|
||||
target_json_status:
|
||||
target?.file?.kind === "json" || target?.file?.kind === "package-json"
|
||||
@@ -441,6 +449,7 @@ const moduleFormat = (
|
||||
const extension = posix.extname(path).toLowerCase();
|
||||
if (extension === ".mjs" || extension === ".mts") return "esm";
|
||||
if (extension === ".cjs" || extension === ".cts") return "commonjs";
|
||||
if (extension === ".ts" || extension === ".tsx") return "unknown";
|
||||
const esm = ir.moduleLinks.some(({ kind }) =>
|
||||
["import", "export", "re-export"].includes(kind),
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user