Files
reverse-engineering-anything/src/application/environment/environmentCompareDiff.ts
T
morluto 332dea76a6 fix(native): keep unreported value-flow and archive coverage unknown, and exempt generation caps by reason marker (#11288)
* fix(native): keep unreported value-flow truncation and archive decode coverage unknown

* test(verify): count multiline optional-fact defaults and pin the guard's exclusions

* fix(domain): keep unknown counts and costs unknown in comparison and coverage summaries (#11325)

* fix(domain): keep unknown counts and costs unknown in comparison and coverage summaries

* refactor(verify): exempt legitimate optional-fact defaults with a reasoned marker (#11355)

* refactor(verify): exempt legitimate optional-fact defaults with a reasoned marker

The optional-fact-default guard counted request defaults and absence that
is modelled elsewhere as hidden unknowns. A comment
`// optional-fact-default: <reason>` on the default's line or the line
before now exempts it; the guard reads unstripped source for the marker and
ignores matches inside comment lines.

Marked: the two evidence paging offsets and four Swift literal reads whose
absence swiftLiteralCoverage reports. Removed instead of marked: jsdiff 9
types Change.count as required, so its two `?? 0` defaults were dead; the
evidence link traversal now carries retained records, so it no longer
re-looks them up behind `?? []`. Baseline 31 -> 22.

* fix(verify): blank comment spans instead of skipping comment-led lines in the optional-fact guard

Skipping a match whose line starts like a comment hid live code after a
leading block comment and counted defaults inside a block comment without
leading stars. The counter now blanks comment text (keeping offsets and line
breaks, skipping string literals) and matches the blanked code, while
exemption markers are still read from the original lines.

* refactor(domain): mark optional-fact defaults whose absence is not an observation (#11389)

* refactor(domain): mark optional-fact defaults whose absence is not an observation

Per-site review of the remaining optional-fact-default entries. Each marked
default is a caller option (trace ignore_fields, environment rules), a list
whose producer omits the empty case (unknown_size_frames, the schema's
min-1 representation_node_ids), caveat text whose completeness another field
carries (call diagnostics, unresolved calls, semantic resource limits), or
absence that already turns the result unknown (Wasm interface inventory,
WebMCP discovery, managed ExportedType rows, legacy integrity mismatch IDs).

Left counted: webCaptureDiff redirects (2; the CDP producer always records
them, so absence is a legacy record that should compare as unknown, not
as no redirects) and HopperCallerReconciliation (2; index-miss semantics not
yet verified). Baseline 22 -> 4.

* fix(browser): compare redirects as unknown when a capture predates redirect recording (#11402)

* fix(browser): compare redirects as unknown when a capture predates redirect recording

The CDP producer records every request's redirect chain, empty when there was none; a record without one predates redirect recording (#986). Comparing it against a current capture reported the network dimension as unchanged, treating the missing chain as "no redirects". Redirects are now compared only when both captures recorded them, and the network dimension is otherwise unknown with a reason; proven membership changes are still reported.

* refactor(hopper): interpret a caller-index miss once at the lookup (#11403)

The forward index holds observations from the examined procedures only, and relationship coverage stays unknown with the scan facts as its reason. A miss therefore adds no callers without showing there are none; the lookup now says so once instead of four optional reads defaulting at each site. The optional-fact-default baseline is now empty.

* docs(javascript): state why an omitted representation list adds no nodes

* fix(verify): count optional-fact defaults from parsed TypeScript, not comment-blanked text

The guard blanked comments with a hand-written scanner and matched a regular expression on the rest, so a default quoted in a string counted and a regular expression holding /* hid the code after it. It now walks the TypeScript syntax tree for property reads defaulted with ?? 0, ?? [] or ?? false, and reads exemption markers only from comment trivia.

* fix(verify): tokenize optional-fact defaults without a compiler and count chained defaults

* fix(verify): match whole optional-fact default expressions across calls and operators

* fix(verify): count optional-fact defaults in template substitutions and after postfix updates, and tie markers to their own expression

* refactor(verify): exempt generation and sample caps from the constant-maximum-slice guard by reason marker (#11454)

* refactor(verify): exempt generation and sample caps from the constant-maximum-slice guard by reason marker

* fix(verify): read reason markers only from real line comments

* fix(verify): read reason markers from the shared source tokenizer

* fix(verify): read a regular expression after a control head as a statement start

The shared tokenizer treated every closing parenthesis as the end of an operand,
so in `if (ready) /[/*]/.test(v)` it read `/[` as division and `/*` inside the
regex as a block comment, hiding the rest of the file from the marker-aware
guards. Parentheses are now tracked: the `)` closing an if/while/for/with head
allows a regular expression, while a call's `)` still means division.

* fix(verify): keep a keyword-named member call out of control-head detection

`policy.if(ready) / (…)` was read as an if-statement head, so the division was
taken for a regular expression and the denominator's optional-fact default was
not counted. A control keyword after `.` or `?.` is a member call.

* refactor(verify): exempt budget-arithmetic cursors and tallies by a not-an-allowance marker (#11493)

* refactor(verify): exempt budget-arithmetic cursors and tallies by a not-an-allowance marker

The budget-arithmetic guard cannot tell a scan cursor, an observed total, a
string being assembled or a tail buffer's retained length from an allowance
when each is compared with a limit. A field declaration marked
`// not-an-allowance: <reason>` (read through the shared reason-marker scan)
is no longer counted. The four remaining sites carry a marker, so the
baseline is empty and removed.

* refactor(verify): exempt detail levels, lifecycle states and domain vocabularies from the completeness-enum guard by reason marker (#11510)

A zod enum containing "complete" is counted as a local coverage vocabulary. Eleven
are not coverage: a caller-chosen detail level, how far a command or session
ran, and format states (GPU decode depth, WASM name section, SQLite column
details). They now carry `// detail-level:`, `// lifecycle-state:` or
`// domain-vocabulary:` with a reason, read through the shared reason-marker
scan (which gains an optional predicate for the matches a guard counts).
local-completeness-enum: 22 -> 11 on this branch.

* fix(verify): bind a not-an-allowance marker to its own class field

Exemptions were a file-wide set of names, so a marked tally in one class hid an
unmarked allowance with the same name in another, and a marked object property
could exempt a class field. Markers now exempt only a member declaration (at
class member depth) of the top-level class that contains it, and the named-
allowance count is taken per class so the same scoping applies to it.

* fix(artifacts): keep main's resources import in the Deno standalone reader after merging main

* fix(verify): start an expression after a template substitution and a non-member keyword, and accept any marker reason

The shared tokenizer read the `/` after `${` as division, so a regular
expression holding `/*` in a substitution hid the rest of the file from
every tokenizer-based guard, and it treated property names such as
`row.return` as keywords. Tokens now record whether template text opens a
substitution and whether a name is an expression keyword (not after `.` or
`?.`), and the regular-expression rule and the optional-fact-default operand
rule read those facts. The optional-fact-default guard reads markers through
reason-marker's isReasonMarker, so any non-empty reason exempts, as for the
other reason markers.

* fix(verify): blank comments with the shared tokenizer before matching architecture guards (#11573)

* fix(verify): blank comments with the shared tokenizer before matching architecture guards

The guards stripped comments with a regular expression that took a `/*`
inside a string, template or regular expression for a comment opener and
deleted code up to the next `*/`. src/flutter/FlutterBuildProvider.ts's
"lib/*/libapp.so" text hid four --pool-policy remediation strings from
cli-option-text-outside-cli. blankComments in source-tokens.mjs now owns
comment removal for the architecture guards and the reason-marker scan: it
blanks comment tokens in place (newlines kept) and keeps strings, templates
and regular expressions. The scan behind it retains only the last tokens it
reads, and whitespace runs are skipped at once.

The cli-option-text-outside-cli baseline records FlutterBuildProvider.ts at
its true count of 4; no other baseline changed.

Fixes #11477

* fix(verify): read a regular expression after a statement block and keep comment offsets for wide characters

The tokenizer now records whether each `{` opens a statement block or an
object literal (from the token before it) and marks the `}` that closes a
block, after which a statement, and so a regular expression, can start; an
object literal's `}` still ends an operand. blankComments replaces each run
of comment text with one space per UTF-16 unit, so a surrogate pair no longer
shifts later offsets.

* chore(verify): drop the Flutter CLI-text baseline entry now that main names no option there
2026-11-16 07:40:30 +08:00

624 lines
20 KiB
TypeScript

import { ellipsisExcerpt } from "../../domain/excerpt.js";
import { escapeJsonPointerToken } from "../../domain/jsonPointer.js";
import type { JsonObject } from "../../domain/analysisView/environmentStateRules.js";
import type { FieldRule } from "../../domain/analysisView/environmentStateWriteRules.js";
import { matchesClockFormat } from "../../domain/analysisView/environmentStateWriteClockFormats.js";
import {
composedPartText,
composedValue,
} from "../../domain/analysisView/environmentStateWriteComposed.js";
import {
likeGeneratedInteger,
isUuid,
readClock,
type ClockFormat,
type ClockReading,
} from "../../domain/analysisView/environmentStateWriteValues.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import type { ReplayedBody } from "./environmentSource.js";
import {
ID_FIELD,
IDENTITY_FIELD,
keyedByLearnedIds,
pairElements,
translateValue,
type IdMap,
} from "./environmentCompareIds.js";
import { isRecord } from "../../domain/isRecord.js";
export const DIFFERENCE_CATEGORIES = [
"status",
"missing-field",
"extra-field",
"value",
"length",
"order",
"clock-format",
"refused",
"not-served",
"no-tool",
"unmapped-id",
] as const;
export type DifferenceCategory = (typeof DIFFERENCE_CATEGORIES)[number];
/** One way an environment answer differs from the live one: where, and both values cut short. */
export interface Difference {
readonly category: DifferenceCategory;
readonly pointer: string;
readonly live?: string;
readonly env?: string;
}
/** Values the comparison treated as equal although they differ: mapped ids, clocks of one format, generated values. */
export interface Normalised {
ids: number;
clocks: number;
generated: number;
/** Live bodies over the replay limit, compared by status only. */
large_bodies: number;
/** Live bodies the probe did not record, compared by status only. */
unobserved_bodies: number;
}
/** At most this many differences are kept per step. */
export const STEP_DIFFERENCE_LIMIT = 20;
const VALUE_CHARS = 120;
const TIME_FIELD =
/(?:^|[_-])(?:at|time|date|timestamp|created|updated|modified)$/iu;
const TIME_FIELD_CAMEL =
/(?:At|Time|Date|Timestamp|Created|Updated|Modified)$/u;
const ID_LIST_FIELD = /^(ids|uuids|guids)$/u;
const shown = (value: JsonValue | undefined): string => {
const text = value === undefined ? "<absent>" : JSON.stringify(value);
return ellipsisExcerpt(text, VALUE_CHARS);
};
const formatKey = (format: ClockFormat): string =>
format.kind === "epoch"
? `epoch-${format.unit}`
: `iso${format.separator}${String(format.fraction)}${format.zone === "" ? "" : format.zone === "Z" ? "Z" : "offset"}`;
/** ISO text has its own clock syntax; numeric epochs require a time-named field. */
const clockReading = (
value: JsonValue,
key: string | undefined,
): ClockReading | undefined => {
if (
typeof value === "number" &&
(key === undefined ||
(!TIME_FIELD.test(key) && !TIME_FIELD_CAMEL.test(key)))
)
return undefined;
return readClock(value);
};
const characterClasses = (text: string): string =>
[
...new Set(
text
.replaceAll(/\d/gu, "0")
.replaceAll(/[a-z]/gu, "a")
.replaceAll(/[A-Z]/gu, "A"),
),
]
.sort()
.join("");
/** A confirmed response field's rule, and the pointer within that field (`*` marks actual array traversal). */
interface Generation {
readonly rule: FieldRule;
readonly pointer: string;
}
/** Whether a confirmed generation rule applies here and both values retain its generated format. */
const generatedPair = (
live: string | number,
env: string | number,
generation: Generation | undefined,
): boolean => {
if (generation === undefined) return false;
const { rule, pointer } = generation;
if (
rule.rule === "unique" &&
pointer === "" &&
likeGeneratedInteger(live, env)
)
return true;
if (typeof live !== "string" || typeof env !== "string") return false;
if (rule.rule === "renewed")
return rule.pointers.includes(pointer) && isUuid(live) && isUuid(env);
if (pointer !== "") return false;
if (
rule.rule === "unique" ||
(rule.rule === "identity" && rule.generator === "uuid")
)
return isUuid(live) && isUuid(env);
if (rule.rule !== "sequence" && rule.rule !== "identity") return false;
return (
live.length === env.length &&
live.length >= 8 &&
/\d/u.test(live) &&
/\d/u.test(env) &&
characterClasses(live) === characterClasses(env)
);
};
class Differ {
readonly #rules: ReadonlyMap<string, FieldRule>;
readonly #composedRules: readonly Extract<FieldRule, { rule: "composed" }>[];
readonly #generatedToEnv = new Map<string, string>();
readonly #generatedToLive = new Map<string, string>();
readonly differences: Difference[] = [];
readonly normalised: Normalised = {
ids: 0,
clocks: 0,
generated: 0,
large_bodies: 0,
unobserved_bodies: 0,
};
/** The answer's own entities: where they sit (the object, or the array of them, at `at`) and the collection the call names, whose own mapping their identities compare by. `identity` marks a write that answers with only the new id, at `at`. */
constructor(
readonly map: IdMap,
readonly entity: {
readonly scope: string | undefined;
readonly at: string;
readonly identity: boolean;
/** Parsed rules of the confirmed write whose entity response is being compared. */
readonly rules: readonly FieldRule[];
},
) {
this.#rules = new Map(entity.rules.map((rule) => [rule.field, rule]));
this.#composedRules = entity.rules.filter(
(rule) => rule.rule === "composed",
);
}
add(difference: Difference): void {
this.differences.push(difference);
}
/** One answer's generated identities must rename consistently in both directions. */
#pairGenerated(
live: string | number,
env: string | number,
rule: FieldRule,
): boolean {
const uuid =
rule.rule === "unique" ||
rule.rule === "renewed" ||
(rule.rule === "identity" && rule.generator === "uuid");
const identity = (value: string | number) =>
typeof value === "number"
? `number:${String(value)}`
: uuid
? `uuid:${value.toLowerCase()}`
: `string:${value}`;
const liveKey = identity(live);
const envKey = identity(env);
const knownEnv = this.#generatedToEnv.get(liveKey);
const knownLive = this.#generatedToLive.get(envKey);
if (
(knownEnv !== undefined && knownEnv !== envKey) ||
(knownLive !== undefined && knownLive !== liveKey)
)
return false;
this.#generatedToEnv.set(liveKey, envKey);
this.#generatedToLive.set(envKey, liveKey);
return true;
}
/** Whether a value compares within the call's collection, as an entity's own identity or a create's bare id does; other ids compare by the probe's mapping. */
#inCollection(
pointer: string,
at: { readonly key?: string; readonly own?: boolean },
): boolean {
return (
(this.entity.identity && pointer === this.entity.at) ||
(at.own === true && at.key !== undefined && IDENTITY_FIELD.test(at.key))
);
}
/** Whether an identity both sides hold verbatim is one its collection's mapping gives to another environment entity; a reference's collection is unknown, so it is not judged. */
#reassigned(
value: JsonValue,
pointer: string,
at: { readonly key?: string; readonly own?: boolean },
): boolean {
if (typeof value !== "string" && typeof value !== "number") return false;
if (!this.#inCollection(pointer, at)) return false;
const mapped = this.map.env(value, this.entity.scope);
return mapped !== undefined && String(mapped) !== String(value);
}
scalar(
live: JsonValue,
env: JsonValue,
pointer: string,
at: {
readonly key?: string;
readonly own?: boolean;
readonly clockKey?: string | undefined;
} = {},
generation?: Generation,
): void {
const key = at.clockKey ?? at.key;
const liveClock = clockReading(live, key);
const envClock = clockReading(env, key);
const generatedMatch =
generation !== undefined &&
(typeof live === "string" || typeof live === "number") &&
(typeof env === "string" || typeof env === "number") &&
liveClock === undefined &&
envClock === undefined &&
!this.map.hasLive(live) &&
!this.map.hasEnv(env) &&
generatedPair(live, env, generation)
? this.#pairGenerated(live, env, generation.rule)
: undefined;
if (live === env) {
if (generatedMatch === false || this.#reassigned(live, pointer, at))
this.add({
category: "value",
pointer,
live: shown(live),
env: shown(env),
});
return;
}
const field = at.key;
if (
(typeof live === "string" || typeof live === "number") &&
(typeof env === "string" || typeof env === "number")
) {
const mapsAsId =
(field !== undefined && ID_FIELD.test(field)) ||
this.#inCollection(pointer, at) ||
(typeof live === "string" &&
field !== undefined &&
this.map.isStateReference(live, field));
const mapped = mapsAsId
? this.map.env(
live,
this.#inCollection(pointer, at) ? this.entity.scope : undefined,
)
: undefined;
if (mapped !== undefined && String(mapped) === String(env)) {
this.normalised.ids += 1;
return;
}
if (liveClock !== undefined && envClock !== undefined) {
const rule = generation?.pointer === "" ? generation.rule : undefined;
const format =
rule?.rule === "clock" || rule?.rule === "held-clock"
? rule.format
: undefined;
const matches =
format?.kind === "iso" && format.trimmed === true
? matchesClockFormat(format, liveClock) &&
matchesClockFormat(format, envClock)
: formatKey(liveClock.format) === formatKey(envClock.format);
if (matches) this.normalised.clocks += 1;
else
this.add({
category: "clock-format",
pointer,
live: shown(live),
env: shown(env),
});
return;
}
if (generatedMatch === true) {
this.normalised.generated += 1;
return;
}
}
this.add({
category: "value",
pointer,
live: shown(live),
env: shown(env),
});
}
array(
live: JsonValue[],
env: JsonValue[],
pointer: string,
clockKey: string | undefined,
generation: Generation | undefined,
): void {
const own = pointer === this.entity.at;
if (this.sameItems(live, env, pointer)) {
// Equal/reordered scalar sets still establish unchanged generated pairs;
// otherwise another field could split an alias hidden by this fast path.
if (generation !== undefined)
for (const [index, item] of live.entries())
this.scalar(
item,
item,
`${pointer}/${String(index)}`,
{ own, clockKey },
{ ...generation, pointer: `${generation.pointer}/*` },
);
return;
}
const pairs = pairElements(live, env);
if (live.length !== env.length || pairs.length !== live.length)
this.add({
category: "length",
pointer,
live: `${String(live.length)} items`,
env: `${String(env.length)} items (${String(pairs.length)} paired)`,
});
const envOrder = pairs.map(([, right]) => right);
if (
envOrder.some((right, index) => index > 0 && right < envOrder[index - 1]!)
)
this.add({ category: "order", pointer });
for (const [left, right] of pairs)
this.value(
live[left]!,
env[right]!,
`${pointer}/${String(left)}`,
{
own,
clockKey,
},
generation === undefined
? undefined
: { ...generation, pointer: `${generation.pointer}/*` },
);
}
/** Arrays of scalars holding the same items in another order differ only in order, as sets an application returns unordered do. */
sameItems(live: JsonValue[], env: JsonValue[], pointer: string): boolean {
const scalar = (item: JsonValue): boolean =>
item === null || typeof item !== "object";
if (live.length !== env.length || !live.every(scalar) || !env.every(scalar))
return false;
// Only identifier lists or known string identifiers are translated; numeric measurements stay literal.
const field = pointer.slice(pointer.lastIndexOf("/") + 1);
const mapped = live.map((item) => {
if (
(typeof item === "string" && this.map.isStateReference(item, field)) ||
((typeof item === "number" || typeof item === "string") &&
ID_LIST_FIELD.test(field))
)
return translateValue(item, this.map);
return item;
});
const key = (items: JsonValue[]): string =>
JSON.stringify(items.map((item) => JSON.stringify(item)).sort());
if (key(mapped) !== key(env)) return false;
this.normalised.ids += mapped.filter(
(item, index) => item !== live[index],
).length;
if (JSON.stringify(mapped) !== JSON.stringify(env))
this.add({ category: "order", pointer });
return true;
}
object(
live: JsonObject,
env: JsonObject,
pointer: string,
own = false,
generation?: Generation,
): void {
const self = own || pointer === this.entity.at;
// An object keyed by ids compares each member under the environment's key; any other compares field by field.
const keyed = keyedByLearnedIds(live, env, this.map);
const envKey = (key: string): string => {
const mapped = keyed
? this.map.env(key, self ? this.entity.scope : undefined)
: undefined;
return mapped !== undefined && Object.hasOwn(env, String(mapped))
? String(mapped)
: key;
};
const matched = new Set<string>();
const composed =
self && this.#composedRules.length > 0
? { agreed: new Set<string>(), fields: new Map<string, string>() }
: undefined;
for (const [key, value] of Object.entries(live)) {
const child = `${pointer}/${escapeJsonPointerToken(key)}`;
const other = envKey(key);
// A translated key and a verbatim key may name the same entry; an
// environment member can account for only one live member.
if (!Object.hasOwn(env, other) || matched.has(other))
this.add({
category: "missing-field",
pointer: child,
live: shown(value),
});
else {
matched.add(other);
const rule = self ? this.#rules.get(key) : undefined;
if (rule?.rule === "composed" && composed !== undefined) {
composed.fields.set(key, other);
continue;
}
const before = this.differences.length;
this.value(
value,
env[other]!,
child,
{
key,
own: self,
keyed: self && keyed,
},
rule !== undefined
? { rule, pointer: "" }
: generation === undefined
? undefined
: {
...generation,
pointer: `${generation.pointer}/${escapeJsonPointerToken(key)}`,
},
);
if (this.differences.length === before) composed?.agreed.add(key);
}
}
// Compare source fields once, then reuse their clock/identity decisions.
// Validate each response's spelling before normalizing its composition.
if (composed !== undefined) {
for (const rule of this.#composedRules) {
const other = composed.fields.get(rule.field);
if (other === undefined) continue;
const coherent =
composedValue(rule.parts, live) === live[rule.field] &&
composedValue(rule.parts, env) === env[other];
if (
coherent &&
rule.parts.every(
(part) =>
!("from" in part) ||
composed.agreed.has(part.from) ||
composedPartText(part, live) === composedPartText(part, env),
)
) {
composed.agreed.add(rule.field);
if (live[rule.field] !== env[other]) this.normalised.generated += 1;
} else
this.add({
category: "value",
pointer: `${pointer}/${escapeJsonPointerToken(rule.field)}`,
live: shown(live[rule.field]),
env: shown(env[other]),
});
}
}
for (const [key, value] of Object.entries(env))
if (!matched.has(key))
this.add({
category: "extra-field",
pointer: `${pointer}/${escapeJsonPointerToken(key)}`,
env: shown(value),
});
}
/** `own` marks an item of the entity array, or with `key` a field of an own entity; a field's own children are not. */
value(
live: JsonValue,
env: JsonValue,
pointer: string,
at: {
readonly key?: string;
readonly own?: boolean;
readonly keyed?: boolean;
readonly clockKey?: string | undefined;
} = {},
generation?: Generation,
): void {
if (Array.isArray(live) && Array.isArray(env))
this.array(live, env, pointer, at.clockKey ?? at.key, generation);
else if (isRecord(live) && isRecord(env))
this.object(
live,
env,
pointer,
at.own === true && (at.key === undefined || at.keyed === true),
generation,
);
else if (
Array.isArray(live) ||
Array.isArray(env) ||
isRecord(live) ||
isRecord(env)
)
this.add({
category: "value",
pointer,
live: shown(live),
env: shown(env),
});
else this.scalar(live, env, pointer, at, generation);
}
}
/** One answer: its status, and its JSON body, its text, or null without one. */
export interface Answer {
readonly status: number | null;
readonly body: ReplayedBody;
/** Set when the probe did not record the body, so only the status is known. */
readonly unobserved?: boolean;
}
/** Compare a live answer with the environment's after normalisation. */
export const compareAnswers = (
live: Answer,
env: Answer,
map: IdMap,
entity: {
readonly scope?: string;
readonly at?: string;
readonly identity?: boolean;
readonly rules?: readonly FieldRule[];
} = {},
): { readonly differences: Difference[]; readonly normalised: Normalised } => {
const differ = new Differ(map, {
scope: entity.scope,
at: entity.at ?? "",
identity: entity.identity === true,
// optional-fact-default: a caller-selected comparison option, not an observation.
rules: entity.rules ?? [],
});
if (live.status !== env.status)
differ.add({
category: "status",
pointer: "",
live: String(live.status),
env: String(env.status),
});
if (
live.body.kind === "cut" ||
(live.body.kind === "base64" && !live.body.whole)
)
differ.normalised.large_bodies += 1;
else if (live.unobserved === true) differ.normalised.unobserved_bodies += 1;
else if (
(live.body.kind === "none" &&
env.body.kind === "json" &&
env.body.value === null) ||
(env.body.kind === "none" &&
live.body.kind === "json" &&
live.body.value === null)
) {
// The existing answer contract treats an absent body and JSON null alike.
} else if (live.body.kind === "base64" || env.body.kind === "base64") {
const bytes = (body: ReplayedBody): Buffer | undefined => {
if (body.kind === "base64") return Buffer.from(body.encoded, "base64");
if (body.kind === "text") return Buffer.from(body.text, "utf8");
return undefined;
};
const liveBytes = bytes(live.body);
const envBytes = bytes(env.body);
if (
liveBytes === undefined ||
envBytes === undefined ||
!liveBytes.equals(envBytes)
)
differ.add({
category: "value",
pointer: "",
live: shown(live.body),
env: shown(env.body),
});
} else if (live.body.kind !== env.body.kind)
differ.add({
category: "value",
pointer: "",
live: shown(live.body),
env: shown(env.body),
});
else if (live.body.kind === "json" && env.body.kind === "json")
differ.value(live.body.value, env.body.value, "");
else if (live.body.kind === "text" && env.body.kind === "text")
differ.value(live.body.text, env.body.text, "");
return { differences: differ.differences, normalised: differ.normalised };
};