fix(electron): resolve package and dirname entrypoints by context

This commit is contained in:
N0zoM1z0
2026-07-17 21:30:24 +08:00
parent a6f02a05a4
commit 1ac9a09ce1
158 changed files with 1654 additions and 493 deletions
+31 -12
View File
@@ -2,7 +2,7 @@ import type { ElectronIpcFinding } from "../domain/electronStaticAnalysisTypes.j
import type { ElectronBoundarySummary } from "../domain/javascriptApplicationAnalysis.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import { resolveArtifactPath } from "./JavaScriptArtifactGraphContext.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
/** One IPC fact retaining its exact owning artifact for graph projection. */
export interface ElectronIpcRecord {
@@ -152,11 +152,22 @@ export const summarizeElectronBoundaries = (
sender_validation_observations: validations.length,
utility_processes: utilities.length,
resolved_utility_entrypoints: utilities.filter(({ file, finding }) =>
resolvesToFile(file, finding.module_path, files),
resolvesToFile({
file,
specifier: finding.module_path,
context: finding.module_resolution_context ?? "module-specifier",
files,
}),
).length,
native_addon_bindings: nativeBindings.length,
resolved_native_addon_bindings: nativeBindings.filter(({ file, finding }) =>
resolvesToFile(file, finding.specifier, files, "native-addon"),
resolvesToFile({
file,
specifier: finding.specifier,
context: "module-specifier",
files,
kind: "native-addon",
}),
).length,
};
};
@@ -182,17 +193,25 @@ const isMainHandler = ({ finding }: ElectronIpcRecord): boolean =>
finding.side === "main" &&
(finding.mode === "listen" || finding.mode === "handle");
const resolvesToFile = (
file: JavaScriptArtifactFile,
specifier: string | null,
files: ReadonlyMap<string, JavaScriptArtifactFile>,
kind?: JavaScriptArtifactFile["kind"],
): boolean => {
if (specifier === null) return false;
const resolved = resolveArtifactPath(specifier, file.path, files);
interface ResolveToFileInput {
readonly file: JavaScriptArtifactFile;
readonly specifier: string | null;
readonly context: "module-specifier" | "filesystem-expression";
readonly files: ReadonlyMap<string, JavaScriptArtifactFile>;
readonly kind?: JavaScriptArtifactFile["kind"];
}
const resolvesToFile = (input: ResolveToFileInput): boolean => {
if (input.specifier === null) return false;
const resolved = resolveArtifactPathByContext({
declaredPath: input.specifier,
sourcePath: input.file.path,
context: input.context,
files: input.files,
}).resolved_path;
return (
resolved !== null &&
(kind === undefined || files.get(resolved)?.kind === kind)
(input.kind === undefined || input.files.get(resolved)?.kind === input.kind)
);
};
+31 -16
View File
@@ -10,7 +10,6 @@ import {
createElectronRoleNode,
javascriptAnalysisCoverage,
linkElectronRoleToAsset,
resolveArtifactPath,
type JavaScriptArtifactGraphContext,
type JavaScriptArtifactGraphCoverage,
} from "./JavaScriptArtifactGraphContext.js";
@@ -21,6 +20,7 @@ import {
electronFindingSourceNode,
electronRangeKey,
} from "./ElectronBoundaryGraphContext.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
interface FindingInput<Value> {
readonly context: JavaScriptArtifactGraphContext;
@@ -77,6 +77,7 @@ const addBrowserWindow = (
web_preferences: value.web_preferences,
omitted_web_preferences: value.omitted_web_preferences,
preload_path: value.preload_path,
preload_resolution_context: value.preload_resolution_context,
absence_means_default: false,
},
evidence: astObservationEvidence({
@@ -111,16 +112,16 @@ const addWindowPreload = (
): void => {
const declared = input.value.preload_path;
if (declared === null) return;
const resolved = resolveArtifactPath(
declared,
input.file.path,
input.context.filesByPath,
);
const resolution = resolveArtifactPathByContext({
declaredPath: declared,
sourcePath: input.file.path,
context: input.value.preload_resolution_context ?? "module-specifier",
files: input.context.filesByPath,
});
const role = createElectronRoleNode(input.context, {
kind: "electron-preload",
anchor: input.file,
declaredPath: declared,
resolvedPath: resolved,
resolution,
mechanism: "BrowserWindow:webPreferences.preload",
range: input.value.location,
coverage: input.coverage,
@@ -133,12 +134,18 @@ const addWindowPreload = (
coverage: input.coverage,
relation: "loads",
operation: "associate-browser-window-preload",
properties: { declared_path: declared, resolved_path: resolved },
properties: {
declared_path: declared,
resolution_context: resolution.resolution_context,
resolved_path: resolution.resolved_path,
resolution_status: resolution.resolution_status,
limitations: resolution.limitations,
},
});
linkElectronRoleToAsset(input.context, {
role,
anchor: input.file,
path: resolved,
resolution,
range: input.value.location,
coverage: input.coverage,
});
@@ -210,6 +217,7 @@ const addUtilityProcess = (
label: value.service_name ?? value.module_path,
properties: {
module_path: value.module_path,
module_resolution_context: value.module_resolution_context,
module_expression: value.module_expression,
service_name: value.service_name,
},
@@ -237,11 +245,13 @@ const addUtilityProcess = (
},
});
if (value.module_path === null) return;
const resolved = resolveArtifactPath(
value.module_path,
file.path,
context.filesByPath,
);
const resolution = resolveArtifactPathByContext({
declaredPath: value.module_path,
sourcePath: file.path,
context: value.module_resolution_context ?? "module-specifier",
files: context.filesByPath,
});
const resolved = resolution.resolved_path;
const target =
resolved === null
? undefined
@@ -255,6 +265,11 @@ const addUtilityProcess = (
coverage,
relation: "maps_to",
operation: "resolve-utility-process-entrypoint",
properties: { resolved_path: resolved },
properties: {
declared_path: value.module_path,
resolution_context: resolution.resolution_context,
resolved_path: resolved,
resolution_status: resolution.resolution_status,
},
});
};
@@ -237,6 +237,7 @@ const parseHtmlScripts = (
maximum: number,
): JavaScriptHtmlScriptObservation[] => {
const scripts: JavaScriptHtmlScriptObservation[] = [];
const baseHref = htmlBaseHref(text);
const pattern = /<script\b[^>]*\bsrc\s*=\s*(["'])([^"']+)\1[^>]*>/giu;
for (const match of text.matchAll(pattern)) {
const script = match[2]?.slice(0, 4_096);
@@ -245,12 +246,18 @@ const parseHtmlScripts = (
scripts.push({
html_path: path,
script_path: script,
base_href: baseHref,
location: rangeForOffsets(text, start, start + match[0].length),
});
}
return scripts;
};
const htmlBaseHref = (text: string): string | null => {
const match = /<base\b[^>]*\bhref\s*=\s*(["'])([^"']+)\1[^>]*>/iu.exec(text);
return match?.[2]?.slice(0, 4_096) ?? null;
};
const parseSourceMap = (
file: JavaScriptArtifactFile,
context: {
@@ -20,6 +20,7 @@ export interface JavaScriptPackageObservation {
export interface JavaScriptHtmlScriptObservation {
readonly html_path: string;
readonly script_path: string;
readonly base_href: string | null;
readonly location: JavaScriptSourceRange;
}
@@ -1,5 +1,3 @@
import { posix } from "node:path";
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js";
import type { ApplicationGraphEvidence } from "../domain/javascriptApplicationEvidenceSchemas.js";
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
@@ -19,6 +17,10 @@ import {
unavailableAstEvidence,
} from "./JavaScriptArtifactGraphEvidence.js";
import type { JavaScriptArtifactReconstructionInput } from "./JavaScriptArtifactReconstructionInput.js";
import {
resolveArtifactPathByContext,
type ArtifactPathResolution,
} from "./JavaScriptArtifactPathResolution.js";
/** Mutable graph-construction state scoped to one reconstruction. */
export interface JavaScriptArtifactGraphContext {
@@ -72,8 +74,7 @@ export interface InferenceEdgeInput extends AstEdgeInput {
export interface RoleNodeInput {
readonly kind: "electron-main" | "electron-preload" | "electron-renderer";
readonly anchor: JavaScriptArtifactFile;
readonly declaredPath: string;
readonly resolvedPath: string | null;
readonly resolution: ArtifactPathResolution;
readonly mechanism: string;
readonly range?: JavaScriptSourceRange;
readonly coverage?: JavaScriptArtifactGraphCoverage;
@@ -83,7 +84,7 @@ export interface RoleNodeInput {
export interface RoleAssetLinkInput {
readonly role: ApplicationNode;
readonly anchor: JavaScriptArtifactFile;
readonly path: string | null;
readonly resolution: ArtifactPathResolution;
readonly range?: JavaScriptSourceRange;
readonly coverage?: JavaScriptArtifactGraphCoverage;
}
@@ -241,14 +242,17 @@ export const createElectronRoleNode = (
identity: artifactLocalIdentity(
input.anchor.sha256,
"electron-role",
`${input.kind}:${input.resolvedPath ?? input.declaredPath}`,
`${input.kind}:${input.resolution.resolution_context}:${input.resolution.resolved_path ?? input.resolution.declared_path}`,
),
observations: [
{
label: input.resolvedPath ?? input.declaredPath,
label: input.resolution.resolved_path ?? input.resolution.declared_path,
properties: {
declared_path: input.declaredPath,
resolved_path: input.resolvedPath,
declared_path: input.resolution.declared_path,
resolution_context: input.resolution.resolution_context,
resolved_path: input.resolution.resolved_path,
resolution_status: input.resolution.resolution_status,
limitations: input.resolution.limitations,
mechanism: input.mechanism,
},
evidence: staticInferenceEvidence({
@@ -256,6 +260,7 @@ export const createElectronRoleNode = (
path: input.anchor.path,
operation: "discover-electron-entrypoint",
coverage: input.coverage ?? completeReconstructionCoverage(),
limitations: input.resolution.limitations,
...(input.range === undefined ? {} : { range: input.range }),
}),
},
@@ -267,20 +272,26 @@ export const linkElectronRoleToAsset = (
context: JavaScriptArtifactGraphContext,
input: RoleAssetLinkInput,
): void => {
if (input.path === null) return;
const asset =
context.assetNodes.get(input.path) ?? context.fileNodes.get(input.path);
const path = input.resolution.resolved_path;
if (path === null) return;
const asset = context.assetNodes.get(path) ?? context.fileNodes.get(path);
if (asset === undefined) return;
context.accumulator.addEdge({
source_node_id: input.role.node_id,
target_node_id: asset.node_id,
relation: "maps_to",
properties: { resolved_path: input.path },
properties: {
declared_path: input.resolution.declared_path,
resolution_context: input.resolution.resolution_context,
resolved_path: path,
resolution_status: input.resolution.resolution_status,
},
evidence: staticInferenceEvidence({
sha256: input.anchor.sha256,
path: input.anchor.path,
operation: "resolve-electron-entrypoint",
coverage: input.coverage ?? completeReconstructionCoverage(),
limitations: input.resolution.limitations,
...(input.range === undefined ? {} : { range: input.range }),
}),
});
@@ -295,20 +306,13 @@ export const resolveArtifactPath = (
specifier: string,
sourcePath: string,
files: ReadonlyMap<string, JavaScriptArtifactFile>,
): string | null => {
const clean = specifier.split("#", 1)[0]?.split("?", 1)[0] ?? "";
if (clean === "" || /^[A-Za-z][A-Za-z+.-]*:/u.test(clean)) return null;
if (!clean.startsWith(".") && !clean.startsWith("/")) return null;
const candidate = posix.normalize(
clean.startsWith("/")
? clean.slice(1)
: posix.join(posix.dirname(sourcePath), clean),
);
if (candidate === ".." || candidate.startsWith("../")) return null;
for (const path of pathCandidates(candidate))
if (files.has(path)) return path;
return null;
};
): string | null =>
resolveArtifactPathByContext({
declaredPath: specifier,
sourcePath,
context: "module-specifier",
files,
}).resolved_path;
/** Locate the recovered module that owns a static finding. */
export const sourceNodeFor = (
@@ -320,18 +324,6 @@ export const sourceNodeFor = (
? undefined
: context.moduleNodes.get(moduleLookupKey(path, moduleKey));
const pathCandidates = (path: string): readonly string[] => [
path,
`${path}.js`,
`${path}.mjs`,
`${path}.cjs`,
`${path}.ts`,
`${path}.tsx`,
`${path}.node`,
posix.join(path, "index.js"),
posix.join(path, "index.ts"),
];
/** Named AST budgets committed to graph evidence coverage. */
export const javaScriptAnalysisLimits = (
input: JavaScriptArtifactReconstructionInput,
@@ -2,7 +2,7 @@ import {
addArtifactContainsEdge,
addStaticInferenceEdge,
createElectronRoleNode,
resolveArtifactPath,
linkElectronRoleToAsset,
type JavaScriptArtifactGraphContext,
} from "./JavaScriptArtifactGraphContext.js";
import {
@@ -10,6 +10,7 @@ import {
completeReconstructionCoverage,
partialReconstructionCoverage,
} from "./JavaScriptArtifactGraphEvidence.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
/** Project HTML renderer entrypoints and their local script assets. */
export const addJavaScriptHtmlRoles = (
@@ -26,11 +27,17 @@ export const addJavaScriptHtmlRoles = (
for (const [htmlPath, scripts] of byHtml) {
const html = context.filesByPath.get(htmlPath);
if (html === undefined) continue;
const roleResolution = {
declared_path: html.path,
resolution_context: "html-reference" as const,
resolved_path: html.path,
resolution_status: "resolved" as const,
limitations: [],
};
const role = createElectronRoleNode(context, {
kind: "electron-renderer",
anchor: html,
declaredPath: html.path,
resolvedPath: html.path,
resolution: roleResolution,
mechanism: "html-script-entrypoint",
});
addArtifactContainsEdge(context, {
@@ -39,12 +46,20 @@ export const addJavaScriptHtmlRoles = (
file: html,
operation: "discover-html-renderer",
});
linkElectronRoleToAsset(context, {
role,
anchor: html,
resolution: roleResolution,
});
for (const script of scripts) {
const resolvedPath = resolveArtifactPath(
script.script_path,
html.path,
context.filesByPath,
);
const resolution = resolveArtifactPathByContext({
declaredPath: script.script_path,
sourcePath: html.path,
context: "html-reference",
files: context.filesByPath,
htmlBaseHref: script.base_href,
});
const resolvedPath = resolution.resolved_path;
if (resolvedPath === null) continue;
const resolved = context.fileNodes.get(resolvedPath);
if (resolved === undefined) continue;
@@ -57,7 +72,11 @@ export const addJavaScriptHtmlRoles = (
relation: "loads",
properties: {
script_path: script.script_path,
base_href: script.base_href,
resolution_context: resolution.resolution_context,
resolved_path: resolvedPath,
resolution_status: resolution.resolution_status,
limitations: resolution.limitations,
},
});
}
@@ -17,6 +17,7 @@ import {
astObservationEvidence,
staticInferenceEvidence,
} from "./JavaScriptArtifactGraphEvidence.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
type StaticReference = JavaScriptStaticAnalysis["references"][number];
type StaticEndpoint = JavaScriptStaticAnalysis["endpoints"][number];
@@ -226,17 +227,17 @@ const addDiscoveredRole = (
context: JavaScriptArtifactGraphContext,
input: FindingInput<StaticRolePath>,
): void => {
const resolvedPath = resolveArtifactPath(
input.value.path,
input.file.path,
context.filesByPath,
);
const resolution = resolveArtifactPathByContext({
declaredPath: input.value.path,
sourcePath: input.file.path,
context: input.value.resolution_context,
files: context.filesByPath,
});
const role = createElectronRoleNode(context, {
kind:
input.value.role === "preload" ? "electron-preload" : "electron-renderer",
anchor: input.file,
declaredPath: input.value.path,
resolvedPath,
resolution,
mechanism: input.value.mechanism,
range: input.value.location,
coverage: input.coverage,
@@ -256,7 +257,7 @@ const addDiscoveredRole = (
linkElectronRoleToAsset(context, {
role,
anchor: input.file,
path: resolvedPath,
resolution,
range: input.value.location,
coverage: input.coverage,
});
@@ -16,7 +16,6 @@ import {
javascriptAnalysisCoverage,
linkElectronRoleToAsset,
moduleLookupKey,
resolveArtifactPath,
type JavaScriptArtifactGraphContext,
} from "./JavaScriptArtifactGraphContext.js";
import {
@@ -25,6 +24,7 @@ import {
completeReconstructionCoverage,
staticInferenceEvidence,
} from "./JavaScriptArtifactGraphEvidence.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
interface PackageRoleInput {
readonly packageNode: ApplicationNode;
@@ -456,16 +456,16 @@ const addPackageRole = (
input: PackageRoleInput,
): void => {
if (input.declaredPath === null) return;
const resolvedPath = resolveArtifactPath(
input.declaredPath,
input.packageFile.path,
context.filesByPath,
);
const resolution = resolveArtifactPathByContext({
declaredPath: input.declaredPath,
sourcePath: input.packageFile.path,
context: "package-entrypoint",
files: context.filesByPath,
});
const role = createElectronRoleNode(context, {
kind: input.kind,
anchor: input.packageFile,
declaredPath: input.declaredPath,
resolvedPath,
resolution,
mechanism:
input.kind === "electron-main"
? "package.json:main"
@@ -477,19 +477,23 @@ const addPackageRole = (
relation: "loads",
properties: {
declared_path: input.declaredPath,
resolved_path: resolvedPath,
resolution_context: resolution.resolution_context,
resolved_path: resolution.resolved_path,
resolution_status: resolution.resolution_status,
limitations: resolution.limitations,
},
evidence: staticInferenceEvidence({
sha256: input.packageFile.sha256,
path: input.packageFile.path,
operation: "discover-package-entrypoint",
coverage: completeReconstructionCoverage(),
limitations: resolution.limitations,
}),
});
linkElectronRoleToAsset(context, {
role,
anchor: input.packageFile,
path: resolvedPath,
resolution,
});
};
@@ -0,0 +1,295 @@
import { posix } from "node:path";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
/** Explicit outcome of bounded, artifact-confined path resolution. */
export interface ArtifactPathResolution {
readonly declared_path: string;
readonly resolution_context:
| "package-entrypoint"
| "filesystem-expression"
| "module-specifier"
| "html-reference";
readonly resolved_path: string | null;
readonly resolution_status:
| "resolved"
| "not-found"
| "unavailable"
| "external"
| "rejected";
readonly limitations: readonly string[];
}
/** Values needed to resolve a declaration without filesystem access. */
export interface ResolveArtifactPathInput {
readonly declaredPath: string;
readonly sourcePath: string;
readonly context:
| "package-entrypoint"
| "filesystem-expression"
| "module-specifier"
| "html-reference";
readonly files: ReadonlyMap<string, JavaScriptArtifactFile>;
readonly htmlBaseHref?: string | null;
}
const EXTENSIONS = [
".js",
".cjs",
".mjs",
".ts",
".tsx",
".json",
".html",
".node",
];
const MAX_PACKAGE_DEPTH = 4;
interface CandidateResolution {
readonly resolvedPath: string | null;
readonly status: ArtifactPathResolution["resolution_status"];
readonly limitations: readonly string[];
}
/** Resolve one declaration under its exact syntax/metadata context. */
export const resolveArtifactPathByContext = (
input: ResolveArtifactPathInput,
): ArtifactPathResolution => resolveAtDepth(input, 0);
const resolveAtDepth = (
input: ResolveArtifactPathInput,
packageDepth: number,
): ArtifactPathResolution => {
const rejected = rejectDeclaration(input);
if (rejected !== null) return rejected;
const candidate = contextualCandidate(input);
if (typeof candidate !== "string") return candidate;
const confined = confineCandidate(input, candidate);
if (typeof confined !== "string") return confined;
const resolved = resolveCandidate(input, confined, packageDepth);
return outcome(
input,
resolved.status,
resolved.resolvedPath,
resolved.limitations,
);
};
const rejectDeclaration = (
input: ResolveArtifactPathInput,
): ArtifactPathResolution | null => {
const declared = input.declaredPath;
if (declared.length === 0)
return outcome(input, "rejected", null, ["The declared path is empty."]);
if (declared.length > 4_096)
return outcome(input, "rejected", null, [
"The declared path exceeds the 4096-character resolution bound.",
]);
if (declared.includes("\0") || declared.includes("\\"))
return outcome(input, "rejected", null, [
"NUL and backslash path syntax are not admitted for canonical artifact paths.",
]);
if (/%(?:2e|2f|5c)/iu.test(declared))
return outcome(input, "rejected", null, [
"Encoded dot or separator bytes are rejected before artifact path resolution.",
]);
return null;
};
const contextualCandidate = (
input: ResolveArtifactPathInput,
): string | ArtifactPathResolution => {
const { context } = input;
const declared =
context === "module-specifier" || context === "html-reference"
? stripQueryAndFragment(input.declaredPath)
: input.declaredPath;
if (context === "html-reference") return htmlCandidate(input);
if (context === "module-specifier") {
const fileUrl = fileUrlPath(declared);
if (fileUrl !== undefined) return fileUrl;
if (hasScheme(declared))
return outcome(input, "external", null, [
"URL and Node builtin schemes are outside static artifact module resolution.",
]);
if (!declared.startsWith(".") && !declared.startsWith("/"))
return outcome(input, "external", null, [
"Bare package and Node builtin specifiers are not artifact entrypoints.",
]);
} else if (hasScheme(declared))
return outcome(input, "external", null, [
"URL schemes are outside this local artifact path context.",
]);
const relative = declared.startsWith("/") ? declared.slice(1) : declared;
return declared.startsWith("/")
? relative
: posix.join(posix.dirname(input.sourcePath), relative);
};
const htmlCandidate = (
input: ResolveArtifactPathInput,
): string | ArtifactPathResolution => {
const declared = stripQueryAndFragment(input.declaredPath);
if (hasScheme(declared))
return outcome(input, "external", null, [
"External HTML references are not mapped to local artifact assets.",
]);
if (declared.startsWith("/")) return declared.slice(1);
const base = input.htmlBaseHref;
if (base === undefined || base === null || base === "")
return posix.join(posix.dirname(input.sourcePath), declared);
if (hasScheme(base))
return outcome(input, "external", null, [
"The document base href is external, so its script reference is not a local artifact path.",
]);
const basePath = base.startsWith("/")
? base.slice(1)
: posix.join(posix.dirname(input.sourcePath), base);
const baseDirectory = base.endsWith("/") ? basePath : posix.dirname(basePath);
return posix.join(baseDirectory, declared);
};
const confineCandidate = (
input: ResolveArtifactPathInput,
candidate: string,
): string | ArtifactPathResolution => {
const normalized = posix.normalize(candidate);
if (
normalized === ".." ||
normalized.startsWith("../") ||
normalized.startsWith("/")
)
return outcome(input, "rejected", null, [
"The resolved candidate escapes the canonical artifact root.",
]);
return normalized === "." ? "" : normalized;
};
const resolveCandidate = (
input: ResolveArtifactPathInput,
candidate: string,
packageDepth: number,
): CandidateResolution => {
const source = input.files.get(input.sourcePath);
for (const path of directCandidates(candidate)) {
const target = input.files.get(path);
if (
target !== undefined &&
(source === undefined ||
target.container_sha256 === source.container_sha256)
)
return { resolvedPath: path, status: "resolved", limitations: [] };
}
if (packageDepth >= MAX_PACKAGE_DEPTH)
return {
resolvedPath: null,
status: "unavailable",
limitations: [
`Directory package resolution exceeded its ${String(MAX_PACKAGE_DEPTH)}-package recursion bound.`,
],
};
const packagePath = posix.join(candidate, "package.json");
const packageFile = input.files.get(packagePath);
if (
packageFile === undefined ||
(source !== undefined &&
packageFile.container_sha256 !== source.container_sha256)
)
return notFoundCandidate();
if (!packageFile.text.included)
return {
resolvedPath: null,
status: "unavailable",
limitations: [
`Directory package metadata ${packagePath} was inventoried but its text is unavailable: ${packageFile.text.reason}.`,
],
};
const main = packageMain(packageFile.text.value);
if (main.status === "invalid")
return {
resolvedPath: null,
status: "unavailable",
limitations: [
`Directory package metadata ${packagePath} is not valid bounded package JSON.`,
],
};
if (main.status === "missing") return notFoundCandidate();
const nested = resolveAtDepth(
{
declaredPath: main.value,
sourcePath: packagePath,
context: "package-entrypoint",
files: input.files,
},
packageDepth + 1,
);
return {
resolvedPath: nested.resolved_path,
status: nested.resolution_status,
limitations: nested.limitations,
};
};
const directCandidates = (candidate: string): readonly string[] => [
candidate,
...EXTENSIONS.map((extension) => `${candidate}${extension}`),
...EXTENSIONS.map((extension) => posix.join(candidate, `index${extension}`)),
];
const packageMain = (
text: string,
):
| { readonly status: "value"; readonly value: string }
| { readonly status: "missing" }
| { readonly status: "invalid" } => {
try {
const value: unknown = JSON.parse(text);
if (typeof value !== "object" || value === null)
return { status: "invalid" };
const main = Reflect.get(value, "main");
if (main === undefined) return { status: "missing" };
return typeof main === "string" && main.length <= 4_096
? { status: "value", value: main }
: { status: "invalid" };
} catch {
return { status: "invalid" };
}
};
const notFoundCandidate = (): CandidateResolution => ({
resolvedPath: null,
status: "not-found",
limitations: [
"No bounded extension, directory package, or index candidate exists in the inventoried artifact container.",
],
});
const hasScheme = (value: string): boolean =>
/^[A-Za-z][A-Za-z+.-]*:/u.test(value);
const fileUrlPath = (value: string): string | undefined => {
if (!value.startsWith("file://")) return undefined;
try {
const url = new URL(value);
if (url.protocol !== "file:" || url.hostname !== "") return undefined;
return decodeURIComponent(url.pathname).replace(/^\/+/, "");
} catch {
return undefined;
}
};
const stripQueryAndFragment = (value: string): string =>
value.split("#", 1)[0]?.split("?", 1)[0] ?? "";
const outcome = (
input: ResolveArtifactPathInput,
status: ArtifactPathResolution["resolution_status"],
resolvedPath: string | null,
limitations: readonly string[],
): ArtifactPathResolution => ({
declared_path: input.declaredPath,
resolution_context: input.context,
resolved_path: resolvedPath,
resolution_status: status,
limitations,
});