Skip to content
Merged
Prev Previous commit
Next Next commit
fix(javascript): resolve source map references with URL semantics
  • Loading branch information
morluto committed Oct 9, 2026
commit c2a9dde0cc3d98a465beb238927f016ac4b9e396
62 changes: 62 additions & 0 deletions src/domain/javascript/javascriptSourceMapPaths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { posix } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";

interface SourceMapPath {
readonly value: string;
readonly scope: "artifact-relative" | "suffix";
}

/** Resolve a source-map URL reference without changing its recorded identity. */
export const resolveJavaScriptSourceMapPath = (
source: string,
mapPath?: string,
): SourceMapPath | null => {
const portable = source.replaceAll("\\", "/");
const windowsPath = /^[a-z]:\//iu.test(portable);
Comment thread
morluto marked this conversation as resolved.
Resolved
// Preserve parent traversal rather than letting URL resolution clamp at '/'.
const anchor = `/${"source/".repeat(portable.split("/").length + 1)}`;
const directory = posix.join(
anchor,
posix.dirname(mapPath?.replaceAll("\\", "/") ?? "."),
);
const base = pathToFileURL(`${directory}/`, { windows: false });
const absolute = windowsPath
? pathToFileURL(source, { windows: true })
: URL.parse(source);
const resolved = windowsPath ? absolute : URL.parse(source, base);
if (
resolved === null ||
!resolved.pathname.startsWith("/") ||
resolved.pathname.endsWith("/")
)
return null;
const relative =
absolute === null
? !portable.startsWith("/")
: absolute.href !== resolved.href;
const path = decodedUrlPath(resolved);
if (path === null) return null;
const value = relative
? posix.relative(anchor, path)
: path.replace(/^\/+/, "");
if (value === "" || value === ".." || value.startsWith("../")) return null;
return {
value,
scope: relative && mapPath !== undefined ? "artifact-relative" : "suffix",
};
};

const decodedUrlPath = (url: URL): string | null => {
// Encoded separators must not manufacture a different filesystem hierarchy.
if (/%(?:2f|5c)/iu.test(url.pathname)) return null;
try {
if (url.protocol === "file:")
return fileURLToPath(url, {
windows: url.hostname !== "" && url.hostname !== "localhost",
}).replaceAll("\\", "/");
return `${url.host}${decodeURIComponent(url.pathname)}`;
} catch (cause: unknown) {
if (cause instanceof URIError || cause instanceof TypeError) return null;
throw cause;
}
};
63 changes: 21 additions & 42 deletions src/domain/javascript/sourceToBundleSignals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
type SourceToBundleSignal,
} from "./sourceToBundleComparisonSchemas.js";
import { isDigest } from "../digests.js";
import { resolveJavaScriptSourceMapPath } from "./javascriptSourceMapPaths.js";

type SourceFile = Extract<
HistoricalSourceGraph["entries"][number],
Expand Down Expand Up @@ -306,54 +307,32 @@ const addPath = (
raw: string,
mapPath?: string,
): void => {
const portable = raw.replaceAll("\\", "/");
const windowsPath = /^[a-z]:\//iu.test(portable);
const sourceMapReference =
kind === "source-map-original" || mapPath !== undefined;
const scheme = windowsPath
? undefined
: (sourceMapReference ? URI_SCHEME : AUTHORITY_URI_SCHEME).exec(
portable,
)?.[0];
// Opaque URI payloads do not establish a filesystem path, even with slash text.
if (scheme !== undefined && !raw.slice(scheme.length).startsWith("/")) return;
const reference =
scheme !== undefined || sourceMapReference
? (portable.split(/[?#]/u, 1)[0] ?? "")
: portable;
if (
reference === "" ||
reference.endsWith("/") ||
/(?:^|\/)\.{1,2}$/u.test(reference)
)
if (kind === "source-map-original" || mapPath !== undefined) {
const resolved = resolveJavaScriptSourceMapPath(raw, mapPath);
if (resolved !== null)
paths.push({
kind,
value: resolved.value,
allowSuffix: resolved.scope === "suffix",
});
return;
const relative =
scheme === undefined && !reference.startsWith("/") && !windowsPath;
const resolved =
mapPath !== undefined && relative
? posix.join(posix.dirname(mapPath.replaceAll("\\", "/")), reference)
: reference;
const value = normalizeCurrentPath(
scheme === undefined
? resolved
: resolved.slice(scheme.length).replace(/^\/+/u, ""),
);
if (value !== null)
paths.push({
kind,
value,
allowSuffix: mapPath === undefined || !relative,
});
}
const value = normalizeCurrentPath(raw);
if (value !== null) paths.push({ kind, value, allowSuffix: true });
};

/** Recognize URI schemes even when the URI has no authority component. */
const URI_SCHEME = /^[a-z][a-z0-9+.-]*:/iu;
/** Outside source maps, only an explicit authority distinguishes URLs from paths. */
const AUTHORITY_URI_SCHEME = /^[a-z][a-z0-9+.-]*:(?=\/\/)/iu;
const SCHEME_URL = /^[a-z][a-z0-9+.-]*:\/\//iu;
const SCHEME_URL_PREFIX = /^[a-z][a-z0-9+.-]*:\/\/+/iu;

const normalizeCurrentPath = (raw: string): string | null => {
const withoutQuery = SCHEME_URL.test(raw)
? (raw.split(/[?#]/u, 1)[0] ?? "")
: raw;
const portable = withoutQuery
.replace(SCHEME_URL_PREFIX, "")
.replaceAll("\\", "/");
const parts: string[] = [];
for (const part of raw.split("/")) {
for (const part of portable.split("/")) {
if (part === "" || part === ".") continue;
if (part === "..") {
if (parts.length === 0) return null;
Expand Down
62 changes: 56 additions & 6 deletions tests/boundary/filesystem/sourceToBundlePaths.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,20 +127,60 @@ it.each([
source: "src/a.js",
expected: "pkg/maps/src/a.js",
},
{
mapPath: "pkg/maps/main.js.map",
source: "../actual/%2e%2e/src/a.js",
expected: "pkg/src/a.js",
decoy: "pkg/actual/%2e%2e/src/a.js",
},
{
mapPath: "pkg/maps/main.js.map",
sourceRoot: "../actual/.%2E",
source: "src/a.js",
expected: "pkg/src/a.js",
decoy: "pkg/actual/.%2E/src/a.js",
},
{
mapPath: "pkg#name?/maps/main.js.map",
source: "../src/a.js",
expected: "pkg#name?/src/a.js",
},
{
mapPath: "pkg/maps/main.js.map",
source: "modules/a%20b.js",
expected: "pkg/maps/modules/a b.js",
},
{
mapPath: "pkg/maps/main.js.map",
source: "modules/a%23b.js",
expected: "pkg/maps/modules/a#b.js",
},
{
mapPath: "pkg/maps/main.js.map",
source: "../actual/%252e%252e/src/a.js",
expected: "pkg/actual/%2e%2e/src/a.js",
decoy: "pkg/src/a.js",
},
])(
"resolves $source against $mapPath without selecting a same-basename decoy",
async ({ mapPath, source, sourceRoot, expected }) => {
async ({
mapPath,
source,
sourceRoot,
expected,
decoy: decoyPath = "src/a.js",
}) => {
const root = await createTestTempDirectory("rea-nested-map-");
const previous = join(root, "previous");
const current = join(root, "current");
await Promise.all([
mkdir(join(previous, expected, ".."), { recursive: true }),
mkdir(join(previous, "src"), { recursive: true }),
mkdir(join(previous, decoyPath, ".."), { recursive: true }),
mkdir(join(current, mapPath, ".."), { recursive: true }),
]);
await Promise.all([
writeFile(join(previous, expected), "export const value = 1;"),
writeFile(join(previous, "src/a.js"), "export const decoy = 99;"),
writeFile(join(previous, decoyPath), "export const decoy = 99;"),
writeFile(
join(current, mapPath),
JSON.stringify({
Expand Down Expand Up @@ -170,7 +210,7 @@ it.each([
}),
);
const decoy = comparison.items.find(
({ source_path }) => source_path === "src/a.js",
({ source_path }) => source_path === decoyPath,
);
expect(decoy?.current_node_ids).toEqual([]);
expect(
Expand Down Expand Up @@ -231,6 +271,10 @@ it("retains every map location when identical map artifacts merge", async () =>

it.each([
{ source: "file:/repo/src/a.js", hasPath: true },
{ source: "file:C:/repo/src/a.js", hasPath: true },
{ source: "file:C:\\repo\\src\\a.js", hasPath: true },
{ source: "C:\\repo\\src\\a.js", hasPath: true },
{ source: "file://server/share/src/a.js", hasPath: true },
{ source: "file:/repo/src/a.js?version=2#original", hasPath: true },
{ source: "webpack:///src/a.js", hasPath: true },
{ source: "https://example.com/src/a.js#original", hasPath: true },
Expand All @@ -239,7 +283,7 @@ it.each([
{ source: "data:text/javascript,virtual/../src/a.js", hasPath: false },
{ source: "data:\\src\\a.js", hasPath: false },
])(
"projects a filesystem path from $source only when it is hierarchical",
"projects source references from $source only when they name a file",
async ({ source, hasPath }) => {
const root = await createTestTempDirectory("rea-source-map-uri-");
const previous = join(root, "previous");
Expand Down Expand Up @@ -343,8 +387,14 @@ it.each([
{ source: "#original.js", historicalPath: "maps.js" },
{ source: "?version.js", historicalPath: "maps.js" },
{ source: "./?version.js", historicalPath: "maps.js" },
{ source: "%2e", historicalPath: "maps.js" },
{ source: "%2e%2e", historicalPath: "maps.js" },
{ source: "child%2fpart.js", historicalPath: "maps.js/child/part.js" },
{ source: "child%5cpart.js", historicalPath: "maps.js/child/part.js" },
{ source: "bad%zz.js", historicalPath: "maps.js/bad%zz.js" },
{ source: "../../outside/a.js", historicalPath: "outside/a.js" },
])(
"keeps the directory-only source name $source out of file path indices",
"declines source references without a trustworthy file path: $source",
async ({ source, historicalPath }) => {
const root = await createTestTempDirectory("rea-source-map-empty-");
const previous = join(root, "previous");
Expand Down
Loading