Files
reverse-engineering-anything/src/browser/WebSourceMapFetcher.ts
T
69a2faa120 feat: add FreeBuff agent support for REA setup (#2736)
* feat: add FreeBuff agent support for REA setup

Register FreeBuff as a supported setup client using the shared user
agents directory (~/.agents/mcp.json with mcpServers, skills in
~/.agents/skills), which matches what FreeBuff Desktop loads. Adds the
client definition, boundary tests, supported-agent docs, and the skill
reference client list.

* fix(freebuff): detect FreeBuff from its profile directory, not shared .agents

The ~/.agents marker made FreeBuff appear installed for any home where
REA had installed shared skills (the default skill destination, also
Gemini CLI's), producing false doctor failures. Detect FreeBuff from
its own fixed profile directory ~/.config/freebuff-desktop instead,
and add a regression test covering a home with only the shared agents
skill directory.

* fix(setup): require product evidence for FreeBuff discovery

Address review findings at their producing boundaries and preserve directly affected consumers. Source inspection and git diff --check completed. Tests and automated checks were not run at the user’s explicit request.

* fix(uninstall): retain unverified shared client configuration

* fix(clients): preserve scoped removal evidence

* fix(doctor): omit undefined selectedClientIds under exactOptionalPropertyTypes

Passing selectedClientIds explicitly as undefined fails typecheck on this
branch (TS2379), which blocks the focused test workflow before any test
can run. Spread the option only when defined.

* fix(update): separate ownership evidence from product applicability

rea update's maintenance scope inspected only product applicability
evidence, so when a FreeBuff profile was absent but REA already owned a
version-pinned row in the shared ~/.agents/mcp.json, the plan omitted
freebuff and left the integration stale. FreeBuff now declares its
registration storage as shared, which proves ownership of an owned row
but never product applicability, and maintenance requests ownership
evidence through that declaration instead of reinterpreting the shared
paths. Doctor and setup keep readiness evidence, foreign rows stay out
of maintenance, and the Doctor exactOptionalPropertyTypes fix makes the
focused test workflow runnable.

* test(dotnet): split oversized operand extent diagnostics describe

The describe callback reached 162 lines (max 150), failing
max-lines-per-function and blocking the pre-push check for this branch.
Move the single-case extent scenarios into their own describe; no test
content or order changes.

* fix(update): preserve ZCode's disabled shared registration during maintenance

The shared user agents file doubles as ZCode's fallback, where
`enable: false` disables the registration. Ownership-based maintenance
read that row as a FreeBuff registration, whose format does not
recognize the flag, so the row was selected and the emitted setup
command rewrote it, dropping the flag and silently re-enabling a
registration the user had disabled.

registrationActivation now honors `enable: false` for any client whose
registration storage is shared, because the activation fact binds every
reader of that storage. Maintenance leaves such rows out; doctor
reports them as stale, matching ZCode's own treatment.

* fix(doctor): let explicit client selection authorize the config read

When an ACL or an inaccessible shared parent made every access probe
fail, a client selected by name was omitted before the configuration
read could return its unreadable-config detail, so doctor reported it
as not detected with installation remediation: an unresolved selected
path collapsed to absence.

An explicit selection now authorizes the read outright and the probes
serve automatic discovery only. A selected client with an unreadable
config reports invalid with the read failure; one with no config
reports missing; automatic discovery still probes before inspecting.

* fix(uninstall): share shared-storage checks between ZCode and FreeBuff

clients() queued ~/.agents/mcp.json twice: once as zcode_fallback and once
as freebuff. ZCode has no discoveryPaths, so its strict read still blocked
uninstall on malformed shared text, despite FreeBuff's new retain-and-continue
behavior. For a valid owned entry, ZCode removed it first, so FreeBuff reported
skipped rather than removed.

Make the shared file's checks and removal one shared decision:
- Add zcodeDiscoveryPaths to ZCode so it has its own applicability evidence.
- Gate zcode_fallback push on applicable, not just zcodeFallbackPath presence.
- Report shared storage ownership as one decision for both clients:
  FreeBuff and ZCode now use clientOwnershipEvidencePaths together, so a
  recognizable REA-owned row proves ownership once for the shared storage, and
  both clients report the same result consistently.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(uninstall): merge duplicated host and prove shared ownership from owned rows

Uninstall.ts declared systemUninstallHost twice, preventing module load,
with the exported copy returning only clients and the second copy missing
clientWriteBlocker. Merge into one exported host carrying both blockers.

hasOwnershipEvidence used access() existence, so an unrelated malformed
~/.agents/mcp.json established ownership and blocked every removal.
Ownership now requires a readable, recognizable REA-owned row via the
injected filesystem, so unrelated shared data stays retained.

Also cover ZCode discoveryPaths in its path test.

* fix(uninstall): keep denied product-local configurations fail-closed

Unproven product applicability marked every configuration path of that client unverified, so a denied ZCode profile turned an unreadable product-local config into a retained item: uninstall continued and could report complete with REA still registered. The retain-and-continue exception now applies only to storage REA does not own, classified once by clientSharedRegistrationPaths (shared configuration plus another product's same-scope fallback).

Covers the Greptile P1 on Uninstall.ts. Validation: the new test fails on the pre-fix Uninstall and passes after it; freebuff/zcode/updateMaintenance/bom/dsh suites green; clientLifecycle, clientRegistrationStatus and claudeDesktop keep the same 8 host failures as the pre-merge baseline (symlink EPERM, stale-vs-aligned on Windows).

* fix(update): retain FreeBuff when ZCode reads the shared fallback

Maintenance deduplicated clients on the path each inspection read, so ZCode's fallback view of ~/.agents/mcp.json marked that file "covered" and dropped FreeBuff from the scope. ZCode setup writes ~/.zcode/cli/config.json and deliberately leaves the fallback untouched (docs/client-configuration.md), so the emitted command refreshed only ZCode while the shared row both products load stayed pinned to the old package version. Each setup action rewrites only its own configuration path and no other action rewrites the shared row, so every selected client keeps its own maintenance action; the read-path covered/deduped filter is removed.

Covers the Codex P2 on UpdateMaintenance.ts:104. Validation: the new regression fails on e2fdec384 with {clients:["zcode"]} and passes with {clients:["freebuff","zcode"]}; updateMaintenance 31/31, setupClientConfigCleanupOwnership, cliUpdateAlias, updateOutput, cliStartupImports green; tsc --noEmit, oxlint (0 errors) and oxfmt --check clean; clientRegistrationStatus keeps the same 4 symlink/stale-vs-aligned failures this Windows host has on base e2fdec384 (verified by stashing the change).

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): preserve completed reads as shared ownership evidence

hasOwnershipEvidence caught every read failure and kept scanning, so a handle-close failure after a successful read — a RegularFileCleanupFailure whose completed outcome still contains the exact shared-file text — was discarded as "no proof". FreeBuff's applicability-unverified storage therefore never got its ownership fact, and once the retained handle blocked later reads, readClientConfiguration downgraded them to retained: inspection passed, removals soft-failed, and runUninstall(true) could purge REA data while the active shared registration remained. The catch now parses the completed outcome for the ownership text while missing or unreadable storage and malformed data keep their proves-nothing semantics, so ownership holds and every later read failure stays blocking.

Covers the Codex P2 on Uninstall.ts:252. Validation: the new regression fails on 4dbfdf1a9 (freebuff reports no blocking failure while the poisoned-scope error lands on claude_code) and passes after; setupClientConfigCleanupOwnership 25/25; the other 21 Uninstall-consumer suites are byte-identical to base 4dbfdf1a9 (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same 6 warnings) and oxfmt --check clean.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): keep owned-row proof through removal refusals

hasOwnershipEvidence treated any clientRegistrationRemoval refusal as no ownership: an effective REA-owned rea member shadowed by an earlier foreign duplicate (shadowed_unowned_member), or an owned native row beside a foreign V1 fallback (foreign_legacy_fallback), discarded the already-parsed positive row fact. With FreeBuff unverified and close failures recurring on the preflight/removal rereads, those failures were then downgraded to retained, so runUninstall(true) removed the skill and purged REA data while the active owned row remained. The refusal now carries the owned rows that motivated it — the refusal only refuses the edit — and hasOwnershipEvidence evaluates that fact on both paths; preflight and removal keep refusing the unsafe edit exactly as before.

Covers the Codex P2 on Uninstall.ts:269. Validation: the new regression fails on 225cb214a (freebuff reports no blocking failure while the poisoned-scope error lands on claude_code) and passes after; setupClientConfigCleanupOwnership 26/26; the 21 Uninstall-consumer suites are byte-identical to the recorded 225cb214a baseline (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same 6 warnings) and oxfmt --check clean.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): keep unresolved discovery probes from softening shared failures

The discovery probe swallowed every stat failure, so a FreeBuff profile denied with EACCES/EIO was indistinguishable from an absent profile: shared storage was marked applicability-unverified and, when ~/.agents/mcp.json also remained unreadable, the ownership and removal reads softened to retained. runUninstall(true) then removed the skill and purged REA data while an installed FreeBuff could still hold an active registration — the regression even reports complete. Absence (ENOENT) is now the only state that leaves shared paths unverified; any other probe failure leaves applicability unresolved, and shared-config failures stay blocking.

Covers the Codex P2 on Uninstall.ts:318. Validation: the new regression fails on 7572a7082 with status complete and purged data and passes after; freebuffClientConfiguration 13/13; the Uninstall-consumer batches are byte-identical to the recorded baselines (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same warning rules) and oxfmt --check clean.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): retain completed configuration reads as removal evidence

A close failure after a completed read discarded the text that read
produced, so an owned registration row the text proves softened to
retained. The completed text now drives removal, keeping shared-config
failures blocking when ownership evidence exists.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(uninstall): stop removal when a cleanup retry leaves a handle unreleased

A completed reread whose handle the cleanup retry cannot release now fails
blockingly instead of serving the text: with no owned row, the soft path
let removeAll purge managed data before close() reported the incomplete
cleanup. The completed text is served only after the retry releases the
handle; an unreleased handle is REA's own failure, never applicability
uncertainty, so it bypasses the retained softening.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(uninstall): keep the ZCode fallback when its profile probe is unresolved

A denied or failed profile probe leaves ZCode's applicability unresolved,
never absent, but the fallback branch dropped the shared row on
applicability alone: with the native config and FreeBuff's profile both
absent, an installed ZCode kept its uninspected registration while
uninstall purged skill and data. Unresolved probes now keep the fallback
in scope with the same fail-closed treatment as other unresolved shared
paths; definitive absence still keeps ZCode out of another product's
primary storage.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(setup): preserve a shared row's enable:false during FreeBuff repair

The shared agents file doubles as ZCode's fallback, so its `enable: false`
binds every reader: doctor now reports the disabled row as stale for
FreeBuff, but following that remediation rebuilt the generic JSON entry
without the flag and silently re-enabled a registration ZCode disabled.
Repairs of shared storage now carry the activation fact forward, while a
client's own native storage keeps its established single-reader repair
contract; the denied-profile uninstall regression also pins the
fallback's new fail-closed inspection beside the denied read.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* test(uninstall): retarget the completed-reread regression to a released retry

The concurrent-writer regression held the reread handle open forever,
which the fail-closed path now serves: it duplicated the unreleased-handle
regression while documenting the opposite contract. The fixture's close
spy gains a failure limit so the cleanup retry releases the handle, and
the test again proves the completed text drives removal of the
concurrently added owned row, with purge verified against the cache
layout purge actually removes.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(doctor): report a preserved shared disable as a manual conflict

Preserving a shared row's enable:false left doctor recommending a setup
run that registrationCurrent correctly treats as already current, so the
scoped doctor returned needs_human forever. The shared-enable
interpretation now has one owner, sharedEnableFlagBinds, used by both
the activation rule and the remediation: a row disabled through the
shared flag reports the manual conflict and states that rea setup will
not change it, instead of an endlessly ineffective repair.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(doctor): keep a native ZCode disable on the setup repair path

The manual-conflict remediation matched a native zcode row through
sharedEnableFlagBinds, but setup drops enable:false on single-reader
storage, so a native disabled registration was told setup would not
change it. The remediation now reads setup's own writer rule,
exported as setupPreservesDisabledActivation: shared storage and the
zcode fallback view keep the manual-conflict message, while a native
row keeps the working rea setup instruction. Regressions pin both
remediations.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* revert: drop the unrelated managed-CIL describe split

The split does not belong to FreeBuff client support and only widens this
PR's diff.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): remove the shared agent registration once for both clients

ZCode's ~/.agents/mcp.json fallback and FreeBuff's own configuration queued the
same physical file twice, so ZCode removed the row and FreeBuff then reported
it absent, losing the outcome for the client that owns the file.

Resolve every configuration path to one owner -- the client whose
configuration it is -- and project that single inspection and removal to each
client that loads it. A fallback reader still contributes its discovery probe,
so an installed or unresolved reader keeps the shared file fail-closed.

Discovery also accepted a dangling ~/.config/freebuff-desktop link, which setup
and doctor reject because they follow the target, so an unrelated malformed
shared file blocked every other removal. Resolve the link before treating the
profile as installation evidence, keeping lstat for removal safety.

Also date the FreeBuff release wording against the published 6.7.0 package.

* fix(uninstall): keep a row per client when two clients own one file

OPENCODE_CONFIG can point OpenCode at FreeBuff's configuration file, where
OpenCode writes `mcp.rea` and FreeBuff writes `mcpServers.rea`. Grouping by
filename gave that path a single owner, so uninstall removed only OpenCode's
row, reported that removal for FreeBuff, and could purge managed data with
FreeBuff's registration still active.

Share the decision only through a fallback view of another client's row: every
client that declares the path as its own configuration keeps its own
inspection and removal, and the fallback reader reports each of them.

* fix(clients): preserve discovery and fallback registration identity

Follow product discovery link targets without losing configuration entry
presence or explicitly selected inspections. Associate fallback readers with
the format owner's registration table and project outcomes by owner and path,
so OpenCode removal cannot be reported as a ZCode fallback removal.

All three new boundary regressions fail against the previous source and pass
with the fixes. Validation: check:fast; 217 focused tests passed; the two
changed test files were rerun with 50 passing tests. No installed FreeBuff
client was launched.

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: Codebuff <noreply@codebuff.com>
2026-10-25 11:29:17 +08:00

1271 lines
41 KiB
TypeScript

import * as t from "@babel/types";
import { createHash } from "node:crypto";
import { decodeValidatedSourceMapLeaves } from "../javascript/sourceMaps/DecodedSourceMap.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import {
AnalysisCancelledError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import { isUrlLikeModuleSpecifier } from "../domain/webBundleAnalyzerAst.js";
import { analyzeParsedJavaScriptReferences } from "../domain/javascript/javascriptSemanticAnalysis.js";
import { traverseJavaScriptAst } from "../domain/javascript/javascriptSemanticTraversal.js";
import { parseJavaScriptSource } from "../domain/javascript/javascriptSourceParser.js";
import {
isTypeOnlyExportDeclaration,
isTypeOnlyImportDeclaration,
semanticImportEqualsSpecifier,
} from "../domain/javascript/javascriptModuleDeclaration.js";
import { stringValue } from "../domain/javascript/javascriptStaticAnalysisHelpers.js";
import type {
AnalyzeWebBundleInput,
WebSourceMapItem,
WebSourceMaps,
} from "../domain/webBundleAnalysis.js";
import {
webSourceMapsSchema,
DEFAULT_SOURCE_MAP_FETCH_TIMEOUT_MS,
} from "../domain/webBundleAnalysis.js";
import {
createWebTextArtifact,
type WebTextArtifact,
} from "../domain/webContentArtifact.js";
import { safeParseJson } from "../domain/safeJson.js";
import { sourceMapJsonText } from "../domain/sourceMapEnvelope.js";
import { resolveJavaScriptSourceMapUrl } from "../domain/javascript/javascriptSourceMapPaths.js";
import { jsonByteLength } from "../domain/jsonSerialization.js";
import {
inspectSourceMapValue,
SourceMapFormatFailure,
type SourceMapLeaf,
} from "../javascript/sourceMaps/SourceMapFormat.js";
import {
noRuntimeOverrideSentence,
selectedBrowserDeadlineMs,
} from "../domain/browserDeadline.js";
import { WEB_SOURCE_MAP_LIMITS } from "../domain/webSourceLocation.js";
export interface WebSourceMapRequest {
readonly scriptKey: string;
readonly declaredUrl: string;
readonly fetchUrl: string;
}
interface SourceMapFetchHost {
readonly fetch: typeof fetch;
/** Fetch-operation deadline; injectable so boundary regressions stay fast. */
readonly timeoutMs?: number;
/** Maximum response bytes retained across this operation. */
readonly maxResponseBytes?: number;
}
// Source maps are normally fetched as a small part of a larger inspection.
// Bound a stalled server to 30 seconds and bound raw map input retained for
// parsing to 64 MiB per inspection. Both limits apply at the network boundary;
// hitting either produces an explicit fetch_failed item, never truncated data.
const SOURCE_MAP_FETCH_TIMEOUT_MS = DEFAULT_SOURCE_MAP_FETCH_TIMEOUT_MS;
const sourceMapFetchDeadlineLimitation = (timeoutMs: number): string =>
`Source-map fetch exceeded its ${String(timeoutMs)} ms source_map_fetch_timeout_ms deadline (fetch_failed). This is an item limitation, not a thrown analysis timeout, and not the source-map decode deadline. ${noRuntimeOverrideSentence(`The ${String(SOURCE_MAP_RESPONSE_BYTES)}-byte response budget stays fixed.`, "source_map_fetch_timeout_ms")}`;
const SOURCE_MAP_RESPONSE_BYTES = 64 * 1024 * 1024;
const SOURCE_MAP_OUTPUT_BYTES = WEB_SOURCE_MAP_LIMITS.outputBytes;
const SOURCE_MAP_FAILURE_LIMITATION_RESERVE = 512;
const SOURCE_MAP_COLLECTION_ENVELOPE_RESERVE = 1_024;
type ParsedSourceMapItem = Extract<
WebSourceMapItem,
{ status: "included" | "partial" }
>;
type ResponseIdentity = {
readonly sha256: string;
readonly bytes: number;
readonly representation: "fetch-response-body-bytes";
};
type FailedSourceMapStatus = "fetch_failed" | "invalid" | "policy_filtered";
interface SourceMapDecodeContext {
readonly signal: AbortSignal | undefined;
readonly deadlineAt: number;
readonly deadlineLimitation: string;
readonly budget: {
records: number;
expandedBytes: number;
resolvedSourceBytes: number;
};
}
/** Fetch and validate approved source maps without browser credentials. */
export const fetchWebSourceMaps = async (
requests: readonly WebSourceMapRequest[],
input: AnalyzeWebBundleInput,
signal?: AbortSignal,
host: SourceMapFetchHost = { fetch: globalThis.fetch },
): Promise<Result<WebSourceMaps, AnalysisError>> => {
if (signalIsAborted(signal))
return err(
new AnalysisCancelledError("analyze_web_bundle", {
cause: signal?.reason,
}),
);
if (requests.length === 0)
return ok(
webSourceMapsSchema.parse({
status: "not_requested",
requested: 0,
processed: 0,
items: [],
}),
);
const items: WebSourceMapItem[] = [];
const operationController = new AbortController();
const fetchTimeoutMs =
host.timeoutMs ??
selectedBrowserDeadlineMs(
input.source_map_fetch_timeout_ms,
SOURCE_MAP_FETCH_TIMEOUT_MS,
);
const fetchDeadlineLimitation =
sourceMapFetchDeadlineLimitation(fetchTimeoutMs);
const timeout = setTimeout(
() =>
operationController.abort(
new SourceMapDeadlineError(fetchDeadlineLimitation),
),
fetchTimeoutMs,
);
const abortFromCaller = (): void => operationController.abort(signal?.reason);
signal?.addEventListener("abort", abortFromCaller, { once: true });
const operationSignal = operationController.signal;
const deadlineAt = performance.now() + fetchTimeoutMs;
const budget = {
retainedBytes: 0,
deadlineAt,
deadlineLimitation: fetchDeadlineLimitation,
decodedRecords: {
records: 0,
expandedBytes: SOURCE_MAP_COLLECTION_ENVELOPE_RESERVE,
resolvedSourceBytes: 0,
},
};
let limitation: string | undefined;
const completedMaps = (): WebSourceMaps => {
const unprocessed = requests.length - items.length;
const stoppedLimitation =
unprocessed === 0
? undefined
: `Source-map acquisition stopped with ${String(unprocessed)} requested map${unprocessed === 1 ? "" : "s"} unprocessed; their results are unknown.`;
const retainedLimitation = [limitation, stoppedLimitation]
.filter((value) => value !== undefined)
.join(" ");
return webSourceMapsSchema.parse({
status: sourceMapsStatus(
items,
unprocessed > 0 || limitation !== undefined,
),
requested: requests.length,
processed: items.length,
items,
...(retainedLimitation.length === 0
? {}
: { limitation: retainedLimitation }),
});
};
const retainCompleted = (error: AnalysisError): AnalysisError =>
error.retainPartialObservation({
kind: "web-source-map-fetch",
source_maps: completedMaps(),
});
try {
for (const request of requests) {
if (signal?.aborted === true) throw signal.reason;
const reservation = sourceMapFailureReservation(request) + 1;
if (
reservation >
SOURCE_MAP_OUTPUT_BYTES - budget.decodedRecords.expandedBytes
) {
limitation = sourceMapOutputLimitation(requests.length - items.length);
break;
}
const expandedBytesBeforeItem = budget.decodedRecords.expandedBytes;
budget.decodedRecords.expandedBytes += reservation;
if (operationSignal.aborted || performance.now() >= deadlineAt) {
items.push(
emptySourceMapItem(request, "fetch_failed", fetchDeadlineLimitation),
);
continue;
}
const item = await fetchOne(
request,
input,
operationSignal,
host,
budget,
);
if (item.status !== "included" && item.status !== "partial") {
const failureBytes = jsonByteLength(item) + 1;
if (failureBytes > SOURCE_MAP_OUTPUT_BYTES - expandedBytesBeforeItem) {
limitation = sourceMapOutputLimitation(
requests.length - items.length,
);
break;
}
budget.decodedRecords.expandedBytes =
expandedBytesBeforeItem + failureBytes;
}
items.push(item);
}
} catch (cause: unknown) {
if (signal?.aborted === true && cause === signal.reason)
return err(
retainCompleted(
new AnalysisCancelledError("analyze_web_bundle", {
cause: signal.reason,
}),
),
);
if (cause instanceof AnalysisError) return err(retainCompleted(cause));
if (signal?.aborted === true)
return err(
retainCompleted(
new AnalysisCancelledError("analyze_web_bundle", {
cause: signal.reason,
}),
),
);
if (cause instanceof SourceMapFormatFailure && cause.reason === "limit")
limitation = sourceMapOutputLimitation(requests.length - items.length);
else throw cause;
} finally {
clearTimeout(timeout);
signal?.removeEventListener("abort", abortFromCaller);
}
if (signal?.aborted === true)
return err(
retainCompleted(
new AnalysisCancelledError("analyze_web_bundle", {
cause: signal.reason,
}),
),
);
return ok(
webSourceMapsSchema.parse({
status: sourceMapsStatus(items, limitation !== undefined),
requested: requests.length,
processed: items.length,
items,
...(limitation === undefined ? {} : { limitation }),
}),
);
};
const sourceMapOutputLimitation = (unprocessed: number): string =>
`source-map output budget could not retain results for ${String(unprocessed)} requested map${unprocessed === 1 ? "" : "s"}. their results are unknown.`;
const sourceMapsStatus = (
items: readonly WebSourceMapItem[],
omitted: boolean,
): WebSourceMaps["status"] => {
const retained = items.filter(
({ status }) => status === "included" || status === "partial",
).length;
if (items.length === 0 || retained === 0) return "unavailable";
if (omitted) return "partial";
return retained === items.length &&
!items.some(({ status }) => status === "partial")
? "included"
: "partial";
};
class SourceMapDeadlineError extends Error {
constructor(message: string) {
super(message);
this.name = "SourceMapDeadlineError";
}
}
class SourceMapSizeLimitError extends Error {
constructor() {
super(
`Source-map response exceeded the ${String(SOURCE_MAP_RESPONSE_BYTES)}-byte retained budget. ${noRuntimeOverrideSentence("That response budget stays fixed.", "source_map_fetch_timeout_ms")}`,
);
this.name = "SourceMapSizeLimitError";
}
}
class SourceMapEncodingError extends Error {
constructor(readonly responseIdentity: ResponseIdentity) {
super("Source-map response is not valid UTF-8.");
this.name = "SourceMapEncodingError";
}
}
class SourceMapRedirectLocationError extends Error {
constructor(url: string, location: string) {
super(
`Source-map redirect from ${JSON.stringify(url)} supplied an invalid Location URL: ${JSON.stringify(location)}.`,
);
this.name = "SourceMapRedirectLocationError";
}
}
const fetchOne = async (
request: WebSourceMapRequest,
input: AnalyzeWebBundleInput,
signal: AbortSignal | undefined,
host: SourceMapFetchHost,
budget: {
retainedBytes: number;
deadlineAt: number;
deadlineLimitation: string;
decodedRecords: {
records: number;
expandedBytes: number;
resolvedSourceBytes: number;
};
},
): Promise<WebSourceMapItem> => {
if (!approvedUrl(request.fetchUrl, input.allowed_origins))
return emptySourceMapItem(
request,
"policy_filtered",
"Declared source-map URL is outside the approved exact origins.",
);
let effectiveUrl: string | null = null;
let completedResponseIdentity: ResponseIdentity | undefined;
try {
const fetched = await fetchFollowingApprovedRedirects(
request.fetchUrl,
input.allowed_origins,
signal,
host,
(url) => {
effectiveUrl = url;
},
);
if (fetched === undefined)
return emptySourceMapItem(
request,
"policy_filtered",
"A source-map redirect left the approved exact origins.",
effectiveUrl,
);
const { response, fetchedUrl } = fetched;
try {
// Admit the resolution identity before reading or retaining its body.
consumeExpandedBytes(
budget.decodedRecords,
jsonByteLength(fetchedUrl) - 4,
);
} catch (cause: unknown) {
try {
await response.body?.cancel();
} catch (cleanupCause: unknown) {
if (cause instanceof SourceMapFormatFailure && cause.reason === "limit")
throw sourceMapOutputError(cause, {
cause: new AggregateError(
[cause, cleanupCause],
"Source-map response cleanup failed after its output exceeded capacity.",
),
cleanup: {
reason:
"Source-map response cancellation failed after its output exceeded capacity.",
resources: ["source-map-response"],
},
});
throw cause;
}
throw cause;
}
if (!response.ok) {
await response.body?.cancel();
return emptySourceMapItem(
request,
"fetch_failed",
`Source-map server returned HTTP ${String(response.status)}.`,
fetchedUrl,
);
}
checkOperation(
undefined,
signal,
budget.deadlineAt,
budget.deadlineLimitation,
);
const body = await readBoundedText(
response,
budget,
host.maxResponseBytes ?? SOURCE_MAP_RESPONSE_BYTES,
signal,
);
completedResponseIdentity = body.responseIdentity;
return normalizeSourceMap(
request,
body.text,
body.responseIdentity,
fetchedUrl,
{
signal,
deadlineAt: budget.deadlineAt,
deadlineLimitation: budget.deadlineLimitation,
budget: budget.decodedRecords,
},
);
} catch (cause: unknown) {
if (cause instanceof AnalysisResourceConstraintError) throw cause;
if (cause instanceof SourceMapFormatFailure && cause.reason === "limit")
throw cause;
if (
signal?.aborted === true &&
!(signal.reason instanceof SourceMapDeadlineError)
)
throw cause;
if (cause instanceof SourceMapEncodingError)
return emptySourceMapItem(
request,
"invalid",
cause.message,
effectiveUrl,
cause.responseIdentity,
);
return emptySourceMapItem(
request,
"fetch_failed",
cause instanceof SourceMapRedirectLocationError ||
cause instanceof SourceMapSizeLimitError ||
cause instanceof SourceMapDeadlineError
? cause.message
: "Source-map fetch or validation failed.",
effectiveUrl,
completedResponseIdentity,
);
}
};
/**
* Fetch redirect statuses per WHATWG Fetch (redirect status list:
* 301, 302, 303, 307, 308). Single owner for redirect decisions.
* 300/304/305/306 carry `Location` without being redirects — following
* them would replace the observed failure with an unrelated map.
* See https://fetch.spec.whatwg.org/#redirect-status
*/
export const isFetchRedirectStatus = (status: number): boolean =>
status === 301 ||
status === 302 ||
status === 303 ||
status === 307 ||
status === 308;
const fetchFollowingApprovedRedirects = async (
initialUrl: string,
allowedOrigins: readonly string[],
signal: AbortSignal | undefined,
host: SourceMapFetchHost,
observeResponse: (url: string) => void,
): Promise<{ response: Response; fetchedUrl: string } | undefined> => {
let current = initialUrl;
const visited = new Set<string>();
for (;;) {
if (signal?.aborted === true) throw signal.reason;
if (!approvedUrl(current, allowedOrigins)) return undefined;
if (visited.has(current)) throw new Error("source_map_redirect_loop");
visited.add(current);
const response = await promiseWithAbort(
host.fetch(current, {
method: "GET",
headers: {
Accept: "application/json, application/source-map+json;q=0.9",
},
redirect: "manual",
credentials: "omit",
referrerPolicy: "no-referrer",
...(signal === undefined ? {} : { signal }),
}),
signal,
);
observeResponse(current);
if (signal !== undefined && signalIsAborted(signal)) {
await response.body?.cancel(signal.reason).catch(() => undefined);
throw signal.reason;
}
// `Location` is a redirect target only for Fetch redirect statuses.
// Other 3xx responses retain their own HTTP failure (strict identity:
// never replace the observed failure with an unrelated map).
if (!isFetchRedirectStatus(response.status))
return { response, fetchedUrl: current };
const location = response.headers.get("location");
if (location === null) return { response, fetchedUrl: current };
await response.body?.cancel();
try {
current = new URL(location, current).href;
} catch {
throw new SourceMapRedirectLocationError(current, location);
}
}
};
const readBoundedText = async (
response: Response,
budget: { retainedBytes: number },
maxBytes: number,
signal: AbortSignal | undefined,
): Promise<{ text: string; responseIdentity: ResponseIdentity }> => {
if (response.body === null)
return {
text: "",
responseIdentity: {
sha256: createHash("sha256").digest("hex"),
bytes: 0,
representation: "fetch-response-body-bytes",
},
};
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let bytes = 0;
try {
for (;;) {
if (signal?.aborted === true) throw signal.reason;
const { done, value } = await readWithAbort(reader, signal);
if (done) break;
const nextBytes = value?.byteLength ?? 0;
if (budget.retainedBytes + bytes + nextBytes > maxBytes) {
await reader.cancel(new SourceMapSizeLimitError());
throw new SourceMapSizeLimitError();
}
if (value !== undefined) chunks.push(value);
bytes += nextBytes;
}
} finally {
// Aborting cancels the reader in readWithAbort. It owns the pending read
// until that cancellation settles, so releasing the lock here can throw.
if (signal?.aborted !== true) reader.releaseLock();
}
budget.retainedBytes += bytes;
const joined = new Uint8Array(bytes);
let offset = 0;
for (const chunk of chunks) {
joined.set(chunk, offset);
offset += chunk.byteLength;
}
const responseIdentity: ResponseIdentity = {
sha256: createHash("sha256").update(joined).digest("hex"),
bytes,
representation: "fetch-response-body-bytes",
};
try {
return {
text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
joined,
),
responseIdentity,
};
} catch {
throw new SourceMapEncodingError(responseIdentity);
}
};
const readWithAbort = <T>(
reader: ReadableStreamDefaultReader<T>,
signal: AbortSignal | undefined,
): Promise<Awaited<ReturnType<ReadableStreamDefaultReader<T>["read"]>>> => {
if (signal === undefined) return reader.read();
if (signal.aborted) return Promise.reject(signal.reason);
return new Promise((resolve, reject) => {
let settled = false;
const cleanup = (): void => signal.removeEventListener("abort", abort);
const abort = (): void => {
if (settled) return;
settled = true;
cleanup();
void reader.cancel(signal.reason).catch(() => undefined);
reject(signal.reason);
};
signal.addEventListener("abort", abort, { once: true });
void reader.read().then(
(value) => {
if (settled) return;
settled = true;
cleanup();
resolve(value);
},
(cause: unknown) => {
if (settled) return;
settled = true;
cleanup();
void reader.cancel(cause).catch(() => undefined);
reject(cause);
},
);
});
};
const signalIsAborted = (signal: AbortSignal | undefined): boolean =>
signal?.aborted === true;
const promiseWithAbort = (
promise: Promise<Response>,
signal: AbortSignal | undefined,
): Promise<Response> => {
if (signal === undefined) return promise;
return new Promise((resolve, reject) => {
let settled = false;
const cleanup = (): void => signal.removeEventListener("abort", abort);
const abort = (): void => {
if (settled) return;
settled = true;
cleanup();
reject(signal.reason);
};
signal.addEventListener("abort", abort, { once: true });
void promise.then(
(response) => {
if (settled || signal.aborted) {
void response.body?.cancel(signal.reason).catch(() => undefined);
if (!settled) {
settled = true;
cleanup();
reject(signal.reason);
}
return;
}
settled = true;
cleanup();
resolve(response);
},
(cause: unknown) => {
if (settled) return;
settled = true;
cleanup();
reject(cause);
},
);
if (signal.aborted) abort();
});
};
const normalizeSourceMap = (
request: WebSourceMapRequest,
text: string,
responseIdentity: ResponseIdentity,
fetchedUrl: string,
context: SourceMapDecodeContext,
): WebSourceMapItem => {
const retainedBytesBeforeMap = context.budget.expandedBytes;
const textBytes =
jsonByteLength(text) +
artifactMetadataBytes("application/source-map+json", text) -
4;
const successBytes =
retainedBytesBeforeMap -
SOURCE_MAP_FAILURE_ENVELOPE_BYTES +
SOURCE_MAP_SUCCESS_ENVELOPE_BYTES +
textBytes;
if (successBytes > SOURCE_MAP_OUTPUT_BYTES)
return emptySourceMapItem(
request,
"fetch_failed",
"Source-map response text exceeds the 32 MiB source-map output budget; JSON parsing and source-map decoding were not attempted.",
fetchedUrl,
responseIdentity,
);
const parsedJson = safeParseJson(sourceMapJsonText(text));
if (!parsedJson.ok)
return emptySourceMapItem(
request,
"invalid",
"Source-map JSON is not a version 3 map.",
fetchedUrl,
responseIdentity,
);
context.budget.expandedBytes = successBytes;
try {
const check = (): void =>
checkOperation(
undefined,
context.signal,
context.deadlineAt,
context.deadlineLimitation,
);
const inspected = inspectSourceMapValue(parsedJson.value, {
profile: "browser-collection",
budget: context.budget,
check,
});
const sourcesByRaw = new Map<string, string>();
const resolvedByRoot = prepareResolvedSources(
inspected.leaves,
fetchedUrl,
context.budget,
sourcesByRaw,
check,
);
check();
const decoded = decodeValidatedSourceMapLeaves(
inspected.leaves,
fetchedUrl,
check,
);
const sourceJsonBytes = new Map<string, number>();
const nameJsonBytes = new Map<string, number>();
const originalSources: ParsedSourceMapItem["original_sources"] = [];
let declarationIndex = 0;
for (const { leaf } of decoded) {
const resolvedSources = resolvedByRoot.get(leaf.map.sourceRoot ?? null);
for (const [index, rawSource] of leaf.map.sources.entries()) {
if ((index & 255) === 0) check();
const resolved =
rawSource === null ? null : (resolvedSources?.get(rawSource) ?? null);
const sanitized =
resolved === null ? null : cachedSanitized(sourcesByRaw, resolved);
const content = leaf.map.sourcesContent?.[index] ?? null;
const mediaType = sourceMediaType(resolved ?? rawSource);
consumeExpandedBytes(
context.budget,
(sanitized === null
? 4
: cachedJsonBytes(sourceJsonBytes, sanitized)) +
sourceEntryOverheadBytes(index, declarationIndex) +
(originalSources.length === 0 ? 0 : 1) +
(content === null
? 0
: jsonByteLength(content) +
artifactMetadataBytes(mediaType, content) -
4),
);
originalSources.push({
source_index: index,
declaration_index: declarationIndex++,
source: sanitized,
artifact:
content === null ? null : createWebTextArtifact(content, mediaType),
});
}
}
const mappings: ParsedSourceMapItem["mappings"] = [];
declarationIndex = 0;
for (const { leaf, rows } of decoded) {
const resolvedSources = resolvedByRoot.get(leaf.map.sourceRoot ?? null);
const declarationBase = declarationIndex;
declarationIndex += leaf.map.sources.length;
for (const [line, row] of rows.entries()) {
if ((line & 255) === 0) check();
for (const segment of row) {
if (segment.length === 1) continue;
const rawSource = leaf.map.sources[segment[1]];
if (rawSource === undefined) continue;
const resolved =
rawSource === null
? null
: (resolvedSources?.get(rawSource) ?? null);
const source =
resolved === null ? null : cachedSanitized(sourcesByRaw, resolved);
const name =
segment.length === 5 ? (leaf.map.names[segment[4]] ?? null) : null;
const generatedLine = leaf.offset.line + line + 1;
const generatedColumn =
segment[0] + (line === 0 ? leaf.offset.column : 0);
consumeExpandedBytes(
context.budget,
(source === null ? 4 : cachedJsonBytes(sourceJsonBytes, source)) +
(name === null ? 4 : cachedJsonBytes(nameJsonBytes, name)) +
mappingRowBytes(
segment[1],
declarationBase + segment[1],
generatedLine,
generatedColumn,
segment[2] + 1,
segment[3],
) +
(mappings.length === 0 ? 0 : 1),
);
mappings.push({
source_index: segment[1],
declaration_index: declarationBase + segment[1],
generated_line: generatedLine,
generated_column: generatedColumn,
source,
original_line: segment[2] + 1,
original_column: segment[3],
name,
});
}
}
}
const modules = originalModuleEdges(originalSources, check, (edge) =>
consumeExpandedBytes(
context.budget,
Buffer.byteLength(JSON.stringify(edge)) + 1,
),
);
check();
if (modules.incomplete.length > 0)
consumeExpandedBytes(
context.budget,
jsonByteLength(
`Module edges are incomplete: ${modules.incomplete.length} of ${originalSources.filter(({ artifact }) => artifact !== null).length} original sources could not be parsed in full (${modules.incomplete.join(", ")}).`,
) - 4,
);
const parsed = {
...sourceMapContext(request, fetchedUrl),
artifact: sourceMapTextArtifact(text, responseIdentity),
original_sources: originalSources,
original_module_edges: modules.edges,
mappings,
};
check();
return modules.incomplete.length === 0
? { ...parsed, status: "included", limitation: null }
: {
...parsed,
status: "partial",
limitation: `Module edges are incomplete: ${modules.incomplete.length} of ${originalSources.filter(({ artifact }) => artifact !== null).length} original sources could not be parsed in full (${modules.incomplete.join(", ")}).`,
};
} catch (cause: unknown) {
// Failed interpretations retain completed body identity without consuming
// the collection budget needed for later valid maps.
context.budget.expandedBytes = retainedBytesBeforeMap;
if (cause instanceof SourceMapFormatFailure && cause.reason === "limit") {
return emptySourceMapItem(
request,
"fetch_failed",
cause.message,
fetchedUrl,
responseIdentity,
);
}
if (
context.signal?.aborted === true ||
cause instanceof SourceMapDeadlineError
)
throw cause;
return emptySourceMapItem(
request,
"invalid",
cause instanceof SourceMapFormatFailure &&
cause.reason === "section-overlap"
? cause.message
: "Source-map JSON mappings could not be decoded safely.",
fetchedUrl,
responseIdentity,
);
}
};
interface OriginalModuleEdges {
readonly edges: ParsedSourceMapItem["original_module_edges"];
/** Original sources whose dependency edges may be incomplete. */
readonly incomplete: readonly string[];
}
const originalModuleEdges = (
sources: ParsedSourceMapItem["original_sources"],
check: () => void,
beforeEdge: (
edge: ParsedSourceMapItem["original_module_edges"][number],
) => void,
): OriginalModuleEdges => {
const edges: ParsedSourceMapItem["original_module_edges"] = [];
const seen = new Set<string>();
const incomplete: string[] = [];
for (const source of sources) {
check();
if (source.artifact === null) continue;
const sourceName = source.source;
if (sourceName === null) {
incomplete.push(
`unnamed source at declaration ${String(source.declaration_index)}`,
);
continue;
}
const parsed = parseJavaScriptSource(
source.artifact.text,
originalSourcePath(sourceName),
);
check();
if (parsed === null) {
incomplete.push(sourceName);
continue;
}
// A recovered program still yields the imports it did parse, but nodes
// after an unrecoverable point are missing, so the edges are a subset.
if (parsed.errors.length > 0) incomplete.push(sourceName);
let unboundRequires: ReadonlySet<string> | undefined;
traverseJavaScriptAst(parsed, {
enter: (node) => {
check();
const dependency = originalDependency(node);
if (dependency === null) return;
const { kind, specifier, requireCallee } = dependency;
if (requireCallee !== undefined) {
unboundRequires ??= new Set(
analyzeParsedJavaScriptReferences(parsed, "require")
.filter(
({ role, resolution }) =>
role === "read" && resolution === "unbound",
)
.map(
({ location }) =>
`${String(location.start.line)}:${String(location.start.column)}`,
),
);
const location = requireCallee.loc?.start;
if (
location === undefined ||
!unboundRequires.has(
`${String(location.line)}:${String(location.column)}`,
)
)
return;
}
const key = `${sourceName}\0${kind}\0${specifier}`;
if (seen.has(key)) return;
seen.add(key);
const edge = {
from_source: sourceName,
kind,
specifier,
resolved_source: resolveOriginalSource(specifier, sourceName),
};
beforeEdge(edge);
edges.push(edge);
},
});
}
return { edges, incomplete };
};
/** Select source language from the URL path, excluding query/fragment. */
const originalSourcePath = (source: string): string => {
try {
return new URL(source).pathname;
} catch (cause: unknown) {
// Unresolved source identities can still carry a useful relative path.
void cause;
return source;
}
};
const checkOperation = (
callerSignal: AbortSignal | undefined,
operationSignal: AbortSignal | undefined,
deadlineAt: number,
deadlineLimitation: string,
): void => {
if (callerSignal?.aborted === true) throw callerSignal.reason;
if (operationSignal?.aborted === true) throw operationSignal.reason;
if (performance.now() >= deadlineAt)
throw new SourceMapDeadlineError(deadlineLimitation);
};
const approvedUrl = (
value: string,
allowedOrigins: readonly string[],
): boolean => {
try {
const parsed = new URL(value);
return (
(parsed.protocol === "http:" || parsed.protocol === "https:") &&
parsed.username === "" &&
parsed.password === "" &&
allowedOrigins.includes(parsed.origin)
);
} catch (cause: unknown) {
// Non-URL input is not an approved source-map URL.
void cause;
return false;
}
};
const sourceMapContext = (
request: WebSourceMapRequest,
effectiveUrl: string | null = null,
) => ({
script_key: request.scriptKey,
declared_url: request.declaredUrl,
effective_url: effectiveUrl,
});
const emptySourceMapItem = (
request: WebSourceMapRequest,
status: FailedSourceMapStatus,
limitation: string,
effectiveUrl: string | null = null,
responseIdentity?: ResponseIdentity,
): WebSourceMapItem => {
const base = {
...sourceMapContext(request, effectiveUrl),
artifact: null,
original_sources: [],
original_module_edges: [],
mappings: [],
limitation:
responseIdentity === undefined
? limitation
: `${limitation} Response text was not retained; completed response body identity is available.`,
};
return status === "policy_filtered"
? { ...base, status }
: {
...base,
status,
...(responseIdentity === undefined
? {}
: { response_identity: responseIdentity }),
};
};
const sourceMapTextArtifact = (
text: string,
responseIdentity: ResponseIdentity,
): WebTextArtifact => ({
sha256: responseIdentity.sha256,
bytes: responseIdentity.bytes,
media_type: "application/source-map+json",
charset: "utf-8",
text,
});
const sanitizeSource = (value: string): string => {
try {
return sanitizeBrowserUrl(new URL(value).href).url;
} catch (cause: unknown) {
// Non-URL sources are preserved verbatim.
void cause;
return value;
}
};
/** Resolve and admit source identities once, before allocating public mapping rows. */
const prepareResolvedSources = (
leaves: readonly SourceMapLeaf[],
mapUrl: string,
budget: { readonly expandedBytes: number; resolvedSourceBytes: number },
sanitizedByResolved: Map<string, string>,
check: () => void,
): ReadonlyMap<string | null, ReadonlyMap<string, string>> => {
const resolvedByRoot = new Map<string | null, Map<string, string>>();
let estimate = budget.expandedBytes;
let resolvedBytes = budget.resolvedSourceBytes;
for (const { map } of leaves) {
let sourcesForRoot = resolvedByRoot.get(map.sourceRoot ?? null);
if (sourcesForRoot === undefined) {
sourcesForRoot = new Map();
resolvedByRoot.set(map.sourceRoot ?? null, sourcesForRoot);
}
for (const source of map.sources) {
check();
if (source === null) continue;
const sourceKey = source;
let resolved = sourcesForRoot.get(sourceKey);
if (resolved === undefined) {
const candidate = resolveJavaScriptSourceMapUrl(
source,
map.sourceRoot,
mapUrl,
);
if (candidate === null) continue;
resolved = candidate;
}
const bytes = Buffer.byteLength(resolved, "utf8");
if (bytes > SOURCE_MAP_RESPONSE_BYTES - resolvedBytes)
throw resolvedSourceLimitFailure();
resolvedBytes += bytes;
sourcesForRoot.set(sourceKey, resolved);
const sanitized = cachedSanitized(sanitizedByResolved, resolved);
estimate += jsonByteLength(sanitized);
if (estimate > WEB_SOURCE_MAP_LIMITS.outputBytes)
throw expandedOutputFailure();
}
}
budget.resolvedSourceBytes = resolvedBytes;
return resolvedByRoot;
};
const consumeExpandedBytes = (
budget: { expandedBytes: number },
bytes: number,
): void => {
if (bytes > WEB_SOURCE_MAP_LIMITS.outputBytes - budget.expandedBytes)
throw expandedOutputFailure();
budget.expandedBytes += bytes;
};
const expandedOutputFailure = (): SourceMapFormatFailure =>
new SourceMapFormatFailure(
"limit",
`Expanded source-map evidence exceeds the ${String(WEB_SOURCE_MAP_LIMITS.outputBytes)}-byte public representation budget. ${noRuntimeOverrideSentence("That representation budget stays fixed.", "source_map_fetch_timeout_ms")}`,
);
const sourceMapOutputError = (
cause: SourceMapFormatFailure,
options?: AnalysisErrorOptions,
): AnalysisResourceConstraintError =>
new AnalysisResourceConstraintError(
"analyze_web_bundle",
"transport",
cause.message,
{ maximum_source_map_output_bytes: SOURCE_MAP_OUTPUT_BYTES },
{ cause, ...options },
);
const resolvedSourceLimitFailure = (): SourceMapFormatFailure =>
new SourceMapFormatFailure(
"limit",
`Resolved source-map identities exceed the ${String(SOURCE_MAP_RESPONSE_BYTES / (1024 * 1024))} MiB decoder representation budget. ${noRuntimeOverrideSentence("That representation budget stays fixed.", "source_map_fetch_timeout_ms")}`,
);
const artifactMetadataBytes = (mediaType: string, text: string): number =>
Buffer.byteLength(
JSON.stringify({
sha256: "0".repeat(64),
bytes: Buffer.byteLength(text),
media_type: mediaType,
charset: "utf-8",
text: "",
}),
) - 2;
// Price invariant envelopes once using the producer's representation. Dynamic
// identities keep their own charges when the map's envelope changes.
const EMPTY_SOURCE_MAP_FAILURE = emptySourceMapItem(
{ scriptKey: "", declaredUrl: "", fetchUrl: "" },
"fetch_failed",
"x".repeat(SOURCE_MAP_FAILURE_LIMITATION_RESERVE),
);
const SOURCE_MAP_FAILURE_ENVELOPE_BYTES =
Buffer.byteLength(JSON.stringify(EMPTY_SOURCE_MAP_FAILURE)) - 4;
const SOURCE_MAP_SUCCESS_ENVELOPE_BYTES =
Buffer.byteLength(
JSON.stringify({
...EMPTY_SOURCE_MAP_FAILURE,
status: "included",
limitation: null,
}),
) - 4;
const sourceMapFailureReservation = (
request: WebSourceMapRequest,
effectiveUrl: string | null = null,
limitation?: string,
status: FailedSourceMapStatus = "fetch_failed",
): number =>
SOURCE_MAP_FAILURE_ENVELOPE_BYTES +
jsonByteLength(request.declaredUrl) +
jsonByteLength(request.scriptKey) +
(effectiveUrl === null ? 0 : jsonByteLength(effectiveUrl) - 4) +
Math.max(
0,
(limitation === undefined ? 0 : jsonByteLength(limitation)) -
SOURCE_MAP_FAILURE_LIMITATION_RESERVE -
2,
) +
jsonByteLength(status) -
jsonByteLength("fetch_failed");
const sourceEntryOverheadBytes = (
sourceIndex: number,
declarationIndex: number,
): number =>
Buffer.byteLength(
`{"source_index":${String(sourceIndex)},"declaration_index":${String(declarationIndex)},"source":,"artifact":null}`,
);
const cachedJsonBytes = (cache: Map<string, number>, value: string): number => {
const cached = cache.get(value);
if (cached !== undefined) return cached;
const bytes = jsonByteLength(value);
cache.set(value, bytes);
return bytes;
};
const cachedSanitized = (cache: Map<string, string>, value: string): string => {
const cached = cache.get(value);
if (cached !== undefined) return cached;
const sanitized = sanitizeSource(value);
cache.set(value, sanitized);
return sanitized;
};
const mappingRowBytes = (
sourceIndex: number,
declarationIndex: number,
generatedLine: number,
generatedColumn: number,
originalLine: number,
originalColumn: number,
): number =>
Buffer.byteLength(
`{"source_index":${String(sourceIndex)},"declaration_index":${String(declarationIndex)},"generated_line":${String(generatedLine)},"generated_column":${String(generatedColumn)},"source":,"original_line":${String(originalLine)},"original_column":${String(originalColumn)},"name":}`,
);
const resolveOriginalSource = (
specifier: string,
base: string,
): string | null => {
if (!isUrlLikeModuleSpecifier(specifier)) return null;
try {
return sanitizeSource(new URL(specifier, base).href);
} catch (cause: unknown) {
// Unresolvable source specifiers are represented by null.
void cause;
return null;
}
};
const sourceMediaType = (source: string | null): string => {
const path = source === null ? null : originalSourcePath(source);
return path?.endsWith(".ts") ||
path?.endsWith(".tsx") ||
path?.endsWith(".mts") ||
path?.endsWith(".cts")
? "text/typescript"
: "text/javascript";
};
const originalDependency = (
node: t.Node,
): {
readonly kind: ParsedSourceMapItem["original_module_edges"][number]["kind"];
readonly specifier: string;
readonly requireCallee?: t.Identifier;
} | null => {
if (
t.isImportDeclaration(node) ||
t.isExportAllDeclaration(node) ||
t.isExportNamedDeclaration(node)
)
return node.source === null ||
node.source === undefined ||
(t.isImportDeclaration(node)
? isTypeOnlyImportDeclaration(node)
: isTypeOnlyExportDeclaration(node))
? null
: { kind: "static_import", specifier: node.source.value };
if (t.isImportExpression(node)) {
const specifier = stringValue(node.source);
return specifier === undefined
? null
: { kind: "dynamic_import", specifier };
}
if (
(t.isCallExpression(node) || t.isOptionalCallExpression(node)) &&
t.isIdentifier(node.callee, { name: "require" })
) {
const specifier = stringValue(node.arguments[0]);
return specifier === undefined
? null
: { kind: "require", specifier, requireCallee: node.callee };
}
// `import x = require("m")` is only legal at module top level and always
// refers to the host loader, so it needs no unbound-`require` check. An
// entity-name alias or an erased `import type` declares no dependency.
if (t.isTSImportEqualsDeclaration(node)) {
const specifier = semanticImportEqualsSpecifier(node);
return specifier === null ? null : { kind: "require", specifier };
}
return null;
};