Merge remote-tracking branch 'origin/main' into fix/managed-comparison-undecoded-signatures
# Conflicts: # docs/product-catalog.json # docs/verification/managed-conformance-manifest.json # skills/reverse-engineer-anything/SKILL.md # src/generatedMcpToolCatalog.ts
This commit is contained in:
@@ -14,6 +14,7 @@ export class ArtifactOperationError extends AnalysisError {
|
||||
| "inspect_keyed_archive"
|
||||
| "export_web_scripts"
|
||||
| "trace_web_module_imports"
|
||||
| "trace_web_source_location"
|
||||
| "analyze_javascript_application",
|
||||
readonly reason:
|
||||
| "cancelled"
|
||||
|
||||
@@ -356,18 +356,81 @@ const XHR_METHODS = new Set([
|
||||
"TRACE",
|
||||
]);
|
||||
|
||||
/** An absolute HTTP(S)/WebSocket URL, or an absolute or relative path. */
|
||||
const isRequestUrlLiteral = (value: string): boolean =>
|
||||
/^(?:https?|wss?):\/\//iu.test(value) ||
|
||||
value.startsWith("/") ||
|
||||
value.startsWith("./") ||
|
||||
value.startsWith("../");
|
||||
|
||||
/**
|
||||
* Require a literal HTTP method: `fs.open(path, "r")` and
|
||||
* `window.open(url, "_blank")` share the callee name but take no URL second.
|
||||
* XHR normalizes the standard methods' case; extension methods such as
|
||||
* WebDAV `PROPFIND` are conventionally uppercase tokens.
|
||||
* Browsing-context and document `open` take a URL or type first and a target
|
||||
* name second. The name is only a spelling, since `parent` or `self` may be a
|
||||
* local XHR binding, so it never overrides a literal HTTP method.
|
||||
*/
|
||||
const isXhrMethodArgument = (node: t.Node | null | undefined): boolean => {
|
||||
const value = stringValue(node);
|
||||
return (
|
||||
value !== undefined &&
|
||||
(XHR_METHODS.has(value.toUpperCase()) || /^[A-Z][A-Z-]*$/u.test(value))
|
||||
);
|
||||
const WINDOW_OPEN_CALL =
|
||||
/(?:^|\.)(?:window|self|globalThis|top|parent|opener|frames|document)\.open$/u;
|
||||
|
||||
/** Node `fs.open` flag strings, which are never request URLs. */
|
||||
const FS_OPEN_FLAGS = new Set([
|
||||
"a",
|
||||
"a+",
|
||||
"as",
|
||||
"as+",
|
||||
"ax",
|
||||
"ax+",
|
||||
"r",
|
||||
"r+",
|
||||
"rs",
|
||||
"rs+",
|
||||
"sa",
|
||||
"sa+",
|
||||
"sr",
|
||||
"sr+",
|
||||
"w",
|
||||
"w+",
|
||||
"wx",
|
||||
"wx+",
|
||||
"xa",
|
||||
"xa+",
|
||||
"xw",
|
||||
"xw+",
|
||||
]);
|
||||
|
||||
/** Reserved browsing-context names (ASCII case-insensitive). */
|
||||
const BROWSING_CONTEXT_KEYWORDS = new Set([
|
||||
"_blank",
|
||||
"_parent",
|
||||
"_self",
|
||||
"_top",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Read `XMLHttpRequest.open(method, url)`. `fs.open(path, "r")` and
|
||||
* `window.open(url, "_blank")` share the callee name. A literal method must
|
||||
* be an HTTP method; with a computed method, the second literal is a URL
|
||||
* unless it is provably an fs flag or a browsing-context keyword, or the
|
||||
* receiver is spelled as a browsing context. XHR normalizes the standard
|
||||
* methods' case; extension methods such as WebDAV `PROPFIND` are
|
||||
* conventionally uppercase tokens.
|
||||
*/
|
||||
const xhrOpenUrl = (
|
||||
name: string,
|
||||
methodNode: t.Node | null | undefined,
|
||||
urlNode: t.Node | null | undefined,
|
||||
): string | undefined => {
|
||||
const url = stringValue(urlNode);
|
||||
if (url === undefined) return undefined;
|
||||
const method = stringValue(methodNode);
|
||||
if (method === undefined)
|
||||
return WINDOW_OPEN_CALL.test(name) ||
|
||||
FS_OPEN_FLAGS.has(url) ||
|
||||
BROWSING_CONTEXT_KEYWORDS.has(url.toLowerCase())
|
||||
? undefined
|
||||
: url;
|
||||
return XHR_METHODS.has(method.toUpperCase()) || /^[A-Z][A-Z-]*$/u.test(method)
|
||||
? url
|
||||
: undefined;
|
||||
};
|
||||
|
||||
const KEYED_COLLECTION_CONSTRUCTORS = new Set([
|
||||
@@ -381,10 +444,10 @@ const KEYED_COLLECTION_CONSTRUCTORS = new Set([
|
||||
]);
|
||||
|
||||
/**
|
||||
* Whether a get/delete receiver is provably a keyed collection rather than an
|
||||
* HTTP client: a constructed Map, Set, Headers, FormData, or URLSearchParams,
|
||||
* or the platform `headers`/`searchParams` properties of a request, response,
|
||||
* or URL. Other receivers stay possible clients.
|
||||
* Whether a get/delete receiver is spelled as a keyed collection: a
|
||||
* constructed Map, Set, Headers, FormData, or URLSearchParams, or a
|
||||
* `headers`/`searchParams` property. Spelling alone does not prove the
|
||||
* binding, so callers keep URL and path literals as requests.
|
||||
*/
|
||||
const isKeyedCollectionReceiver = (callee: t.Node): boolean => {
|
||||
if (!t.isMemberExpression(callee) && !t.isOptionalMemberExpression(callee))
|
||||
@@ -420,18 +483,21 @@ export const endpointArgument = (
|
||||
): string | undefined => {
|
||||
if (name === "fetch" || name.endsWith(".fetch") || name === "WebSocket")
|
||||
return stringValue(args[0]);
|
||||
// `XMLHttpRequest.open(method, url)`.
|
||||
if (name.endsWith(".open") && isXhrMethodArgument(args[0]))
|
||||
return stringValue(args[1]);
|
||||
if (name.endsWith(".open")) return xhrOpenUrl(name, args[0], args[1]);
|
||||
const method = ["get", "post", "put", "patch", "delete", "request"].find(
|
||||
(candidate) => name === candidate || name.endsWith(`.${candidate}`),
|
||||
);
|
||||
if (method !== undefined)
|
||||
// Only get and delete also belong to the keyed-collection APIs.
|
||||
return (method === "get" || method === "delete") &&
|
||||
if (method !== undefined) {
|
||||
const value = stringValue(args[0]);
|
||||
// Only get and delete also belong to the keyed-collection APIs, whose
|
||||
// keys are header, field, and parameter names rather than URLs or paths.
|
||||
return value !== undefined &&
|
||||
(method === "get" || method === "delete") &&
|
||||
!isRequestUrlLiteral(value) &&
|
||||
isKeyedCollectionReceiver(callee)
|
||||
? undefined
|
||||
: stringValue(args[0]);
|
||||
: value;
|
||||
}
|
||||
if (name.endsWith("loadURL")) return stringValue(args[0]);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
omitPrototypeKeys,
|
||||
omittedPrototypeKeysLimitation,
|
||||
parseXmlPropertyList,
|
||||
} from "./propertyListKeys.js";
|
||||
|
||||
const plist = (body: string) =>
|
||||
`<?xml version="1.0" encoding="UTF-8"?><plist version="1.0">${body}</plist>`;
|
||||
|
||||
it.each([
|
||||
"<key>__proto__</key>",
|
||||
"<key><![CDATA[__proto__]]></key>",
|
||||
"<key>__proto__</key>",
|
||||
])("omits and counts a dictionary keyed %s", (key) => {
|
||||
const parsed = parseXmlPropertyList(
|
||||
plist(
|
||||
`<dict><key>CFBundleExecutable</key><string>App</string>${key}<dict><key>polluted</key><true/></dict><key>list</key><array><dict>${key}<string>x</string><key>kept</key><integer>1</integer></dict></array></dict>`,
|
||||
),
|
||||
);
|
||||
expect(parsed).toEqual({
|
||||
value: { CFBundleExecutable: "App", list: [{ kept: 1 }] },
|
||||
omittedPrototypeKeys: 2,
|
||||
});
|
||||
expect(Object.getPrototypeOf(parsed.value)).toBe(Object.prototype);
|
||||
});
|
||||
|
||||
it("keeps __proto__ text in strings, comments, and similar keys", () => {
|
||||
const text = plist(
|
||||
"<dict><!-- <key>__proto__</key> --><key> __proto__ </key><string><![CDATA[<key>__proto__</key>]]></string><key>__rea_prototype_key__</key><string>__proto__</string></dict>",
|
||||
);
|
||||
expect(parseXmlPropertyList(text)).toEqual({
|
||||
value: {
|
||||
" __proto__ ": "<key>__proto__</key>",
|
||||
__rea_prototype_key__: "__proto__",
|
||||
},
|
||||
omittedPrototypeKeys: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("omits own __proto__ entries that JSON decoding creates", () => {
|
||||
const decoded: unknown = JSON.parse(
|
||||
'{"__proto__":{"x":1},"a":[{"__proto__":2,"b":3}]}',
|
||||
);
|
||||
expect(omitPrototypeKeys(decoded)).toEqual({
|
||||
value: { a: [{ b: 3 }] },
|
||||
omittedPrototypeKeys: 2,
|
||||
});
|
||||
expect(omittedPrototypeKeysLimitation(1)).toBe(
|
||||
"1 dictionary entry keyed __proto__ was omitted because REA results cannot represent that key.",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { parse } from "plist";
|
||||
|
||||
/** The dictionary key REA results cannot carry: validation strips it. */
|
||||
const PROTOTYPE_KEY = "__proto__";
|
||||
|
||||
/** A decoded plist without `__proto__` entries, and how many were omitted. */
|
||||
export interface PropertyListWithoutPrototypeKeys {
|
||||
readonly value: unknown;
|
||||
readonly omittedPrototypeKeys: number;
|
||||
}
|
||||
|
||||
/** Limitation for results whose source plist held `__proto__` entries. */
|
||||
export const omittedPrototypeKeysLimitation = (count: number): string =>
|
||||
`${String(count)} dictionary ${count === 1 ? "entry" : "entries"} keyed __proto__ ${count === 1 ? "was" : "were"} omitted because REA results cannot represent that key.`;
|
||||
|
||||
const withoutKey = (
|
||||
value: unknown,
|
||||
key: string,
|
||||
): PropertyListWithoutPrototypeKeys => {
|
||||
let omitted = 0;
|
||||
const strip = (item: unknown): unknown => {
|
||||
if (Array.isArray(item)) return item.map(strip);
|
||||
if (
|
||||
item === null ||
|
||||
typeof item !== "object" ||
|
||||
item instanceof Date ||
|
||||
item instanceof Uint8Array
|
||||
)
|
||||
return item;
|
||||
return Object.fromEntries(
|
||||
Object.entries(item).flatMap(([name, entry]) => {
|
||||
if (name !== key) return [[name, strip(entry)]];
|
||||
omitted += 1;
|
||||
return [];
|
||||
}),
|
||||
);
|
||||
};
|
||||
const stripped = strip(value);
|
||||
return { value: stripped, omittedPrototypeKeys: omitted };
|
||||
};
|
||||
|
||||
/** Remove own `__proto__` entries, such as JSON.parse creates, and count them. */
|
||||
export const omitPrototypeKeys = (
|
||||
value: unknown,
|
||||
): PropertyListWithoutPrototypeKeys => withoutKey(value, PROTOTYPE_KEY);
|
||||
|
||||
// Comments and CDATA text are consumed whole so only element keys match.
|
||||
const KEY_TOKEN =
|
||||
/<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<key>([^<]*)<\/key>|<key><!\[CDATA\[([\s\S]*?)\]\]><\/key>/gu;
|
||||
|
||||
const XML_ENTITIES: Readonly<Record<string, string>> = {
|
||||
amp: "&",
|
||||
apos: "'",
|
||||
gt: ">",
|
||||
lt: "<",
|
||||
quot: '"',
|
||||
};
|
||||
|
||||
const decodeXmlText = (text: string): string =>
|
||||
text.replace(
|
||||
/&(?:#x([\da-f]+)|#(\d+)|([a-z]+));/giu,
|
||||
(entity, hex?: string, decimal?: string, name?: string) => {
|
||||
if (hex !== undefined) return String.fromCodePoint(parseInt(hex, 16));
|
||||
if (decimal !== undefined)
|
||||
return String.fromCodePoint(parseInt(decimal, 10));
|
||||
return (name === undefined ? undefined : XML_ENTITIES[name]) ?? entity;
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Decode an XML plist whose dictionaries may use the legal key `__proto__`,
|
||||
* which the `plist` decoder rejects outright. Those entries are omitted and
|
||||
* counted so callers can report them instead of failing the whole document.
|
||||
*/
|
||||
export const parseXmlPropertyList = (
|
||||
text: string,
|
||||
): PropertyListWithoutPrototypeKeys => {
|
||||
let placeholder = "__rea_prototype_key__";
|
||||
while (text.includes(placeholder)) placeholder = `_${placeholder}`;
|
||||
const substituted = text.replace(
|
||||
KEY_TOKEN,
|
||||
(token, plain?: string, cdata?: string) =>
|
||||
(plain === undefined ? cdata : decodeXmlText(plain)) === PROTOTYPE_KEY
|
||||
? `<key>${placeholder}</key>`
|
||||
: token,
|
||||
);
|
||||
return withoutKey(parse(substituted), placeholder);
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { ProviderCleanupError } from "./providerCleanupError.js";
|
||||
import { projectAnalysisError } from "./analysisErrorProjection.js";
|
||||
it("preserves the binary cleanup default and an explicitly owned nonbinary operation", () => {
|
||||
expect(new ProviderCleanupError("ghidra", ["database"], {}).operation).toBe(
|
||||
"close_binary",
|
||||
);
|
||||
const error = new ProviderCleanupError(
|
||||
"source-map-decoder",
|
||||
["runtime"],
|
||||
{ reason: "cleanup failed" },
|
||||
{ operation: "trace_web_source_location" },
|
||||
);
|
||||
expect(error.operation).toBe("trace_web_source_location");
|
||||
expect(projectAnalysisError(error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { operation: "trace_web_source_location" },
|
||||
});
|
||||
});
|
||||
@@ -12,9 +12,11 @@ export class ProviderCleanupError extends ProviderAdapterError {
|
||||
providerId: string,
|
||||
resources: readonly string[],
|
||||
diagnostics: Readonly<Record<string, JsonValue>>,
|
||||
options?: ErrorOptions,
|
||||
/** Identify the operation owning these resources; binary callers retain their default. */
|
||||
options?: ErrorOptions & { readonly operation?: string },
|
||||
) {
|
||||
super(providerId, "close_binary", { ...options, diagnostics });
|
||||
const { operation = "close_binary", ...errorOptions } = options ?? {};
|
||||
super(providerId, operation, { ...errorOptions, diagnostics });
|
||||
this.cleanupResources = [...resources];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,11 +183,29 @@ describe("web bundle static-analysis parity", () => {
|
||||
fs.open("/tmp/data.txt", "r", done);
|
||||
window.open("https://help.example.test/", "_blank");
|
||||
xhr.open(method, "/dynamic-method");
|
||||
fs.open(path, "r", done);
|
||||
window.open(url, "_blank");
|
||||
window.open(url, "/preview");
|
||||
globalThis.open(url, "./frame");
|
||||
document.open("text/html", "/replace");
|
||||
parent.open("GET", "/parent-xhr");
|
||||
self.open("post", "/self-xhr");
|
||||
xhr.open(method, "api/relative");
|
||||
fs.open(path, "w+", done);
|
||||
popup.open(url, "_TOP");
|
||||
`),
|
||||
);
|
||||
expect(
|
||||
result.observations.endpoints.map(({ value }) => value).sort(),
|
||||
).toEqual(["/dav/", "/xhr-get", "https://xhr.example.test/submit"]);
|
||||
).toEqual([
|
||||
"/dav/",
|
||||
"/dynamic-method",
|
||||
"/parent-xhr",
|
||||
"/self-xhr",
|
||||
"/xhr-get",
|
||||
"api/relative",
|
||||
"https://xhr.example.test/submit",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps HTTP-method-named reads of provable keyed collections out of endpoints", () => {
|
||||
@@ -205,14 +223,20 @@ describe("web bundle static-analysis parity", () => {
|
||||
new URL(location.href).searchParams.get("page");
|
||||
api.headers.post("/v1/headers");
|
||||
api.searchParams.request("/search");
|
||||
new Headers().get("/users");
|
||||
api.headers.get("https://api.example.test/headers");
|
||||
api.searchParams.delete("../search");
|
||||
`),
|
||||
);
|
||||
expect(
|
||||
result.observations.endpoints.map(({ value }) => value).sort(),
|
||||
).toEqual([
|
||||
"../search",
|
||||
"/search",
|
||||
"/users",
|
||||
"/v1/headers",
|
||||
"cache-key",
|
||||
"https://api.example.test/headers",
|
||||
"https://api.example.test/users",
|
||||
"users",
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { z } from "zod";
|
||||
import { digestSchema } from "./digests.js";
|
||||
import { webScriptExportManifestSchema } from "./webScriptExport.js";
|
||||
|
||||
/** Select one source from an existing captured-script export. */
|
||||
export const selectedWebScriptInputSchema = z.strictObject({
|
||||
manifest_path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Absolute export_web_scripts manifest path"),
|
||||
script_index: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.describe("Zero-based index in manifest.scripts"),
|
||||
});
|
||||
export type SelectedWebScriptInput = z.output<
|
||||
typeof selectedWebScriptInputSchema
|
||||
>;
|
||||
|
||||
/** Exact identity of one local file, independently read as bytes. */
|
||||
export const webArtifactFileSchema = z.strictObject({
|
||||
path: z.string().min(1),
|
||||
sha256: digestSchema,
|
||||
bytes: z.number().int().min(0),
|
||||
});
|
||||
|
||||
/** Artifact-port report shared by capture-derived analyses. */
|
||||
export const selectedWebScriptArtifactsSchema = z.strictObject({
|
||||
manifest: webScriptExportManifestSchema,
|
||||
manifestFile: webArtifactFileSchema,
|
||||
sourceFile: webArtifactFileSchema,
|
||||
source: z.string(),
|
||||
});
|
||||
export type SelectedWebScriptArtifacts = z.output<
|
||||
typeof selectedWebScriptArtifactsSchema
|
||||
>;
|
||||
|
||||
/** Preserve original capture authority and completeness alongside the actual manifest identity. */
|
||||
export const capturedWebManifestIdentitySchema = webArtifactFileSchema.extend({
|
||||
reported_output_directory: z.string(),
|
||||
...webScriptExportManifestSchema.pick({
|
||||
capture_path: true,
|
||||
capture_sha256: true,
|
||||
capture_kind: true,
|
||||
capture_completeness: true,
|
||||
source_evidence_id: true,
|
||||
}).shape,
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { z } from "zod";
|
||||
import { digestSchema } from "./digests.js";
|
||||
import { exportedWebScriptSchema } from "./webScriptExport.js";
|
||||
import {
|
||||
capturedWebManifestIdentitySchema,
|
||||
selectedWebScriptInputSchema,
|
||||
webArtifactFileSchema,
|
||||
} from "./webScriptArtifacts.js";
|
||||
|
||||
/** JavaScript source-map positions use UTF-16 columns and one-based lines. */
|
||||
export const webSourcePositionSchema = z.strictObject({
|
||||
line: z.number().int().min(1),
|
||||
column: z.number().int().min(0),
|
||||
});
|
||||
|
||||
/** Trace one explicit generated position through an explicitly paired local map. */
|
||||
export const webSourceLocationInputSchema = selectedWebScriptInputSchema.extend(
|
||||
{
|
||||
source_map: z.strictObject({
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Absolute local source-map path; no fetch"),
|
||||
url: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe(
|
||||
"Explicit source-map URL context used to resolve original source names",
|
||||
),
|
||||
}),
|
||||
generated_position: webSourcePositionSchema,
|
||||
},
|
||||
);
|
||||
export type WebSourceLocationInput = z.output<
|
||||
typeof webSourceLocationInputSchema
|
||||
>;
|
||||
|
||||
const originalContentSchema = z.discriminatedUnion("state", [
|
||||
z.strictObject({
|
||||
state: z.literal("embedded"),
|
||||
text: z.string(),
|
||||
utf8_sha256: digestSchema,
|
||||
utf8_bytes: z.number().int().min(0),
|
||||
representation: z.literal("UTF-8 encoding of decoded sourcesContent text"),
|
||||
}),
|
||||
z.strictObject({
|
||||
state: z.literal("unavailable"),
|
||||
reason: z.literal("sourcesContent-not-retained"),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Keep every matching segment, including anonymous mappings and duplicate URLs. */
|
||||
export const webSourceMapMatchSchema = z.discriminatedUnion("state", [
|
||||
z.strictObject({ state: z.literal("generated-only") }),
|
||||
z.strictObject({
|
||||
state: z.literal("mapped"),
|
||||
flattened_source_index: z.number().int().min(0),
|
||||
section_path: z.array(z.number().int().min(0)),
|
||||
source_index: z.number().int().min(0),
|
||||
reported_source: z.string().nullable(),
|
||||
reported_source_root: z.string().nullable(),
|
||||
resolved_url: z.string().nullable(),
|
||||
ignored: z.boolean(),
|
||||
content: originalContentSchema,
|
||||
original_position: webSourcePositionSchema.extend({
|
||||
offset: z.number().int().min(0).nullable(),
|
||||
content_position: z.enum([
|
||||
"verified-in-embedded-text",
|
||||
"outside-embedded-text",
|
||||
"content-unavailable",
|
||||
]),
|
||||
}),
|
||||
name: z.string().nullable(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Codec observations; map association and deployment authenticity remain selected context. */
|
||||
export const webSourceMapReportSchema = z.strictObject({
|
||||
source_map_sha256: digestSchema,
|
||||
url_context: z.string().min(1),
|
||||
engine: z.strictObject({ id: z.string().min(1), version: z.string().min(1) }),
|
||||
runtime: z.strictObject({
|
||||
id: z.string().min(1),
|
||||
version: z.string().min(1),
|
||||
v8_heap_limit_bytes: z.number().int().min(1),
|
||||
}),
|
||||
format: z.enum(["regular", "indexed"]),
|
||||
reported_file: z.string().nullable(),
|
||||
lookup: z.strictObject({
|
||||
requested: webSourcePositionSchema,
|
||||
matched_generated_position: webSourcePositionSchema.nullable(),
|
||||
semantics: z.literal(
|
||||
"greatest generated position <= requested, across lines; all equal-position segments",
|
||||
),
|
||||
location_units: z.literal("one-based lines; zero-based UTF-16 columns"),
|
||||
}),
|
||||
matches: z.array(webSourceMapMatchSchema),
|
||||
diagnostics: z.array(z.string()),
|
||||
});
|
||||
|
||||
/** Bounds for complete source-map evidence and upstream decoded layouts. */
|
||||
export const WEB_SOURCE_MAP_LIMITS = {
|
||||
mapBytes: 4 * 1024 * 1024,
|
||||
outputBytes: 32 * 1024 * 1024,
|
||||
decodedRows: 262144,
|
||||
decodedSegments: 262144,
|
||||
sectionDepth: 64,
|
||||
decodeTimeoutMs: 20000,
|
||||
} as const;
|
||||
export type WebSourceMapReport = z.output<typeof webSourceMapReportSchema>;
|
||||
|
||||
/** Selected capture/map byte identities and complete point attribution inline. */
|
||||
export const webSourceLocationResultSchema = webSourceMapReportSchema.extend({
|
||||
manifest: capturedWebManifestIdentitySchema,
|
||||
source: webArtifactFileSchema.extend({
|
||||
script_index: z.number().int().min(0),
|
||||
script: exportedWebScriptSchema,
|
||||
}),
|
||||
source_map: webArtifactFileSchema.extend({
|
||||
url: z.string().min(1),
|
||||
association: z.literal("caller-selected"),
|
||||
}),
|
||||
generated_offset: z.number().int().min(0),
|
||||
source_authenticity: z.literal("unknown"),
|
||||
execution: z.literal("unknown"),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { webSourceOffset } from "./webSourcePosition.js";
|
||||
|
||||
it("uses UTF-16 columns and actual JavaScript line terminators", () => {
|
||||
const text = "🎋a\r\nb\rc\nd\u2028e\u2029";
|
||||
expect(webSourceOffset(text, { line: 1, column: 2 })).toBe(2);
|
||||
expect(webSourceOffset(text, { line: 1, column: 3 })).toBe(3);
|
||||
expect(webSourceOffset(text, { line: 1, column: 4 })).toBeUndefined();
|
||||
expect(webSourceOffset(text, { line: 2, column: 0 })).toBe(5);
|
||||
expect(webSourceOffset(text, { line: 6, column: 0 })).toBe(13);
|
||||
expect(webSourceOffset(text, { line: 7, column: 0 })).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ line: 0, column: 0 },
|
||||
{ line: 1, column: -1 },
|
||||
{ line: 1.5, column: 0 },
|
||||
])("rejects invalid source positions: %j", (position) => {
|
||||
expect(webSourceOffset("", position)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("retains the empty source and the final empty line", () => {
|
||||
expect(webSourceOffset("", { line: 1, column: 0 })).toBe(0);
|
||||
expect(webSourceOffset("a\r\n", { line: 2, column: 0 })).toBe(3);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
/** JavaScript positions use one-based lines and zero-based UTF-16 columns. */
|
||||
export interface WebSourcePosition {
|
||||
readonly line: number;
|
||||
readonly column: number;
|
||||
}
|
||||
|
||||
/** Verify a selected position against actual text without splitting the whole source. */
|
||||
export const webSourceOffset = (
|
||||
text: string,
|
||||
position: WebSourcePosition,
|
||||
): number | undefined => {
|
||||
if (
|
||||
!Number.isSafeInteger(position.line) ||
|
||||
position.line < 1 ||
|
||||
!Number.isSafeInteger(position.column) ||
|
||||
position.column < 0
|
||||
)
|
||||
return undefined;
|
||||
let line = 1;
|
||||
let start = 0;
|
||||
for (const boundary of text.matchAll(/\r\n?|\n|\u2028|\u2029/gu)) {
|
||||
if (line === position.line)
|
||||
return position.column <= boundary.index - start
|
||||
? start + position.column
|
||||
: undefined;
|
||||
line += 1;
|
||||
start = boundary.index + boundary[0].length;
|
||||
}
|
||||
return line === position.line && position.column <= text.length - start
|
||||
? start + position.column
|
||||
: undefined;
|
||||
};
|
||||
Reference in New Issue
Block a user