saffron-ai 1.3.4 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,8 @@ import { createHash, randomBytes } from "node:crypto";
12
12
  import dns from "node:dns";
13
13
  import fs from "node:fs";
14
14
  import path from "node:path";
15
- import { expect, test, type APIResponse, type Browser, type BrowserContext, type Dialog, type Download, type ElementHandle, type Locator, type Page, type Request, type Response } from "@playwright/test";
15
+ import vm from "node:vm";
16
+ import { expect, test, type APIResponse, type Browser, type BrowserContext, type Dialog, type Download, type ElementHandle, type Frame, type Locator, type Page, type Request, type Response } from "@playwright/test";
16
17
 
17
18
  const SETTINGS: {
18
19
  /** Locale and time zone {date...} tokens are written in. */
@@ -88,6 +89,19 @@ const HELD_AS = new Set(["code", "value", "pem", "encrypted", "json", "data", "s
88
89
  /** Credential words a name may end in written as one word: only ones no ordinary word ends in. */
89
90
  const JOINED_SUFFIXES = ["token", "secret", "password", "passwd", "passphrase", "apikey", "accesskey", "privatekey", "credential", "credentials", "cookie", "sessionid", "sessid"];
90
91
 
92
+ /** A response's body as text, as replay reads it (src/http/replay.ts responseText): in its Content-Type charset, a leading BOM dropped. */
93
+ export async function responseText(response: { text(): Promise<string>; body?(): Promise<Buffer> }, contentType: string | undefined): Promise<string | undefined> {
94
+ const charset = /;\s*charset\s*=\s*"?([^";\s]+)/i.exec(contentType ?? "")?.[1];
95
+ let decoder: TextDecoder | undefined;
96
+ try {
97
+ if (charset && !/^utf-?8$/i.test(charset)) decoder = new TextDecoder(charset);
98
+ } catch {
99
+ // A charset Node does not know: read as UTF-8.
100
+ }
101
+ const text = decoder && response.body ? await response.body().then((b) => decoder.decode(b), () => undefined) : await response.text().catch(() => undefined);
102
+ return text?.replace(/^\uFEFF/, "");
103
+ }
104
+
91
105
  /**
92
106
  * Whether a name (a capture's, a field's, a header's) names a credential, by its last word, a version or a number
93
107
  * after it aside (`accessToken`, `api_key`, `X-Session-Id`, `X-Hub-Signature-256`, `Set-Cookie`), never one it only
@@ -111,6 +125,13 @@ export function namesSecret(name: string): boolean {
111
125
  * `/data/access_token`, `sessionId`, `header:Set-Cookie`): a value the API under test handed out that must not reach
112
126
  * a transcript, a report or another host. A value's shape says nothing; `id` and `name` are plain.
113
127
  */
128
+ /** A token pair's access token (`{ refresh, access }`), as the runner's tokenPairAccess reads it. */
129
+ export function tokenPairAccess(value: unknown): string | undefined {
130
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
131
+ const { access, refresh } = value as { access?: unknown; refresh?: unknown };
132
+ return typeof access === "string" && refresh !== undefined && /^\S{16,}$/.test(access) ? access : undefined;
133
+ }
134
+
114
135
  export function isCredentialCapture(name: string, pointer: string): boolean {
115
136
  // A pointer's last segment, unescaped (`/data/id~1token` names `id/token`).
116
137
  return namesSecret(name) || namesSecret((pointer.split("/").at(-1) ?? "").replaceAll("~1", "/").replaceAll("~0", "~"));
@@ -212,7 +233,7 @@ export function uploadFile(file: string): string {
212
233
  const LETTER = String.raw`[\p{L}\p{N}\p{M}]`;
213
234
  // A script written without spaces (Chinese, Japanese, Thai...): an edge of it is not bounded, as in replay, but for
214
235
  // a negating prefix before it ("成功" is not in "不成功").
215
- const SPACELESS = /[\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}\p{sc=Thai}\p{sc=Lao}\p{sc=Khmer}\p{sc=Myanmar}]/u;
236
+ const SPACELESS = /(?!\p{N})[\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}\p{sc=Thai}\p{sc=Lao}\p{sc=Khmer}\p{sc=Myanmar}]/u;
216
237
  const NEGATING = "无法|無法|不能|没有|沒有|未能|ไม่ได้|不|未|非|無|无|没|沒|ไม่";
217
238
 
218
239
  /**
@@ -221,26 +242,76 @@ const NEGATING = "无法|無法|不能|没有|沒有|未能|ไม่ได้|
221
242
  * the step wrote, a zero decimal part may follow ("$10" is in "$10.00", not
222
243
  * "$10.50"); after a row or data value (`rows` "end"), none.
223
244
  */
224
- export function bounded(text: string, edges: "start" | "end" | "both", flags = "u", rows: "" | "end" = ""): RegExp {
245
+ export function bounded(text: string, edges: "start" | "end" | "both", flags = "u", rows: "" | "end" = "", grouped = true): RegExp {
225
246
  text = said(normalize(text), "the expected text");
226
247
  const first = [...text][0];
227
248
  // An amount ("$5.00") is never the negative one after a minus ("-$5.00"), as replay reads it.
228
249
  const amount = /^\p{Sc}\s?\p{N}/u.test(text);
229
250
  const start = edges !== "end" && (amount || (new RegExp(`^${LETTER}`, "u").test(text) && !(SPACELESS.test(first) && new RegExp(`^(?:${NEGATING})`, "u").test(text))));
230
251
  const end = edges !== "start" && new RegExp(`${LETTER}$`, "u").test(text) && !SPACELESS.test([...text].at(-1)!);
231
- const before = SPACELESS.test(first) ? `(?<!${NEGATING})` : /^\p{N}/u.test(text) ? `(?<!${LETTER}|\\p{N}[.,]|(?:^|[^\\p{L}\\p{N}])[-\\u2212\\u2013])` : amount ? `(?<!(?:^|[^\\p{L}\\p{N}])[-\\u2212\\u2013])` : `(?<!${LETTER})`;
232
- const after = !/\p{N}$/u.test(text) ? `(?!${LETTER})` : rows === "end" ? `(?!${LETTER}|[.,]\\p{N})` : `(?!${LETTER}|[.,](?!0{1,2}(?!\\p{N}|[.,]\\p{N}))\\p{N})`;
252
+ // Thousands grouped by a space or an apostrophe ("1 250 kr") are one number, and a currency symbol after a letter ("R$") another currency, as replay reads them.
253
+ // Not for "not shown" (grouped false): there a number that might run on into the next ("15 128") counts as shown.
254
+ const group = "[\\x20\\u00a0\\u202f\\u2007\\u2009\\u200a\\u0027\\u2019]";
255
+ // For "not shown", only a decimal point joins two numbers: "2" counts as shown in "1,2,3", as replay reads it.
256
+ const point = grouped ? "[.,\\u066b\\u066c]" : "[.\\u066b]";
257
+ const groupAfter = grouped && /(?:^|[^\p{L}\p{N}\p{M}])\p{N}{1,3}$/u.test(text) ? `|${group}\\p{N}{3}(?!\\p{N})` : "";
258
+ // An invisible format character (a soft hyphen, a zero-width space) between the text and its neighbour is no boundary, as replay reads it:
259
+ // "saved" is not in "Un\u00adsaved", nor "1" in "Order 1\u200b2".
260
+ const cf = "\\p{Cf}*";
261
+ const before = SPACELESS.test(first) ? `(?<!${NEGATING})` : /^\p{N}/u.test(text) ? `(?<!(?:${LETTER}|\\p{N}${point}|(?:^|[^\\p{L}\\p{N}])[-\\u2212\\u2013]${grouped && /^\p{N}{3}(?!\p{N})/u.test(text) ? `|(?:^|[^\\p{L}\\p{N}\\p{M}])\\p{N}{1,3}${group}` : ""})${cf})` : amount ? `(?<!(?:${grouped ? "\\p{L}|" : ""}(?:^|[^\\p{L}\\p{N}])[-\\u2212\\u2013])${cf})` : `(?<!${LETTER}${cf})`;
262
+ const after = !/\p{N}$/u.test(text) ? `(?!${cf}${LETTER})` : rows === "end" ? `(?!${cf}(?:${LETTER}|${point}\\p{N}${groupAfter}))` : `(?!${cf}(?:${LETTER}|${point}(?!0{1,2}(?!\\p{N}|${point}\\p{N}))\\p{N}${groupAfter}))`;
233
263
  // Quotes and `>` as hex, so Playwright reads no string or chain in the regex; any whitespace as replay's label match allows.
234
- const body = escapeRegExp(text).replace(/ /g, "\\s+").replace(/["'`>]/g, (c) => `\\x${c.charCodeAt(0).toString(16)}`);
264
+ const literal = (s: string) => escapeRegExp(s).replace(/ /g, "\\s+").replace(/["'`>]/g, (c) => `\\x${c.charCodeAt(0).toString(16)}`);
265
+ // For "not shown", the text with invisible format characters in it (a bidi isolate, a soft hyphen) is shown, as replay reads it.
266
+ // A straight or typographic quote is any of them there: "Can't save" is shown as "Can\u2019t save", as replay reads it.
267
+ const body = grouped ? literal(text) : [...text].map((c) => anyQuote(c) ?? literal(c)).join("\\p{Cf}*");
235
268
  // After a number's point or comma ("$10."), no more digits, as replay reads it.
236
- const point = edges !== "start" && /\p{N}[.,]$/u.test(text) ? "(?!\\p{N})" : "";
237
- return new RegExp(`${start ? before : ""}${body}${end ? after : point}`, flags);
269
+ const pointEnd = /\p{N}[.,\u066b\u066c]$/u.test(text) ? "(?!\\p{N})" : "";
270
+ return new RegExp(`${start ? before : ""}${body}${end ? after : pointEnd}`, flags);
238
271
  }
239
272
 
240
273
  const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
274
+ /** A quote as a class of its straight and typographic forms, written as escapes so Playwright reads no string in it. */
275
+ const anyQuote = (c: string) => (/['\u2018\u2019]/.test(c) ? "[\\x27\\u2018\\u2019]" : /["\u201c\u201d]/.test(c) ? "[\\x22\\u201c\\u201d]" : undefined);
241
276
  const normalize = (s: string) => s.replace(/\s+/g, " ").trim();
242
277
  const contains = (haystack: string, needle: string | RegExp) => (typeof needle === "string" ? haystack.includes(needle) : needle.test(haystack));
243
278
 
279
+ /** For "not shown": a role's name in any case and with invisible format characters in it, as replay reads it. */
280
+ export function shownName(name: string): RegExp {
281
+ const text = said(normalize(name), "the expected name");
282
+ return new RegExp(`^[\\s\\p{Cf}]*${[...text].map((c) => (c === " " ? "\\s+" : anyQuote(c) ?? escapeRegExp(c))).join("\\p{Cf}*")}[\\s\\p{Cf}]*$`, "iu");
283
+ }
284
+
285
+ /** A recorded pattern that backtracks on what it is checked against: the check fails with this, never freezes the run, as in replay. */
286
+ class Backtracks extends Error {
287
+ constructor() {
288
+ super("the pattern takes too long on the text (it backtracks): write it without a repeat inside a repeat, such as (a+)+");
289
+ }
290
+ }
291
+
292
+ // One context for every match: a new one per call costs more than the match on each response of a poll.
293
+ const regexContext = vm.createContext({});
294
+ const regexAll = new vm.Script("Array.from(t.matchAll(re), (m) => Object.assign(Array.from(m), { index: m.index }))");
295
+ /** Every match of `re` (global) in `text`, or undefined when it takes more than `ms`: run where V8 can stop it, as src/util/capture.ts matchesWithin. */
296
+ export function matchesWithin(re: RegExp, text: string, ms = 200): RegExpMatchArray[] | undefined {
297
+ Object.assign(regexContext, { re, t: text });
298
+ try {
299
+ return regexAll.runInContext(regexContext, { timeout: ms }) as RegExpMatchArray[];
300
+ } catch (err) {
301
+ if ((err as { code?: string }).code === "ERR_SCRIPT_EXECUTION_TIMEOUT") return undefined;
302
+ throw err;
303
+ } finally {
304
+ Object.assign(regexContext, { re: undefined, t: undefined });
305
+ }
306
+ }
307
+ const matchesAt = (re: RegExp, text: string): RegExpMatchArray[] => {
308
+ const found = matchesWithin(new RegExp(re.source, re.flags.replace(/[gy]/g, "") + "g"), text);
309
+ if (found === undefined) throw new Backtracks();
310
+ return found;
311
+ };
312
+ /** Whether a recorded pattern matches, as replay's testsWithin: one that backtracks throws Backtracks. */
313
+ const testsWithin = (re: RegExp, text: string): boolean => matchesAt(re, text).length > 0;
314
+
244
315
  /** A recorded regular expression; unicode mode when it needs one. */
245
316
  export function pattern(source: string, flags = ""): RegExp {
246
317
  if (source.includes(`[\\p{L}\\p{N}\\p{M}]`) && !/[uv]/.test(flags)) flags += "u";
@@ -381,8 +452,9 @@ class ResponseLog {
381
452
  status: response.status(),
382
453
  };
383
454
  this.entries.push(entry);
384
- if (/json|text|xml/i.test(response.headers()["content-type"] ?? "")) {
385
- void response.text().then((body) => (entry.body = body), () => undefined);
455
+ const type = response.headers()["content-type"] ?? "";
456
+ if (/json|text|xml/i.test(type)) {
457
+ void responseText(response, type).then((body) => (entry.body = body), () => undefined);
386
458
  }
387
459
  });
388
460
  }
@@ -415,6 +487,10 @@ const decode = (url: string) => {
415
487
  }
416
488
  };
417
489
 
490
+ /** Raw, a match ending on a letter or digit written percent-encoded is part of a longer word ("Jos" in "Jos%C3%A9"), as replay reads it. */
491
+ const rawUrlMatch = (re: RegExp, url: string) =>
492
+ matchesAt(re, url).some((m) => !/^%(?!3[Ff]|26|3[Dd]|23|2[Ff])[0-9A-Fa-f]{2}/.test(url.slice(m.index! + m[0].length)));
493
+
418
494
  function statusMatches(observed: number, expected?: string): boolean {
419
495
  if (!expected) return observed >= 200 && observed < 300;
420
496
  const cls = /^([1-5])xx$/i.exec(expected.trim());
@@ -429,6 +505,8 @@ interface Lane {
429
505
  active: Page;
430
506
  opened: Page[];
431
507
  net: ResponseLog;
508
+ /** The open tabs in order when last looked at: where the active one was, should it close itself. */
509
+ tabs: Page[];
432
510
  /** The latest response the session's request client got (see Run.send). */
433
511
  last?: Exchange;
434
512
  }
@@ -563,28 +641,41 @@ export class Run {
563
641
  /** What capture() read, and from which element, for expectDiffers. */
564
642
  private captures = new Map<string, ElementHandle>();
565
643
 
566
- private constructor(private browser: Browser, private baseURL: string | undefined) {}
644
+ private constructor(private browser: Browser, private baseURL: string | undefined, private followsAnyTab: boolean) {}
567
645
 
568
- static async start({ page, browser, baseURL }: { page: Page; browser: Browser; baseURL?: string }): Promise<Run> {
569
- const run = new Run(browser, baseURL);
646
+ /** `followsAnyTab`: an older recording that uses tabs without tab marks, where replay follows any tab that opens. */
647
+ static async start({ page, browser, baseURL, followsAnyTab = false }: { page: Page; browser: Browser; baseURL?: string; followsAnyTab?: boolean }): Promise<Run> {
648
+ const run = new Run(browser, baseURL, followsAnyTab);
570
649
  run.lane = run.track(page.context(), page);
571
650
  run.lanes.set("", run.lane);
572
651
  return run;
573
652
  }
574
653
 
575
654
  private track(context: BrowserContext, active: Page): Lane {
576
- const lane: Lane = { context, active, opened: [], net: new ResponseLog(context) };
655
+ const lane: Lane = { context, active, opened: [], net: new ResponseLog(context), tabs: context.pages() };
577
656
  context.on("page", (p) => lane.opened.push(p));
578
657
  return lane;
579
658
  }
580
659
 
581
- /** The tab the scenario acts on: a tab an action opened is followed, as replay follows it. */
660
+ /**
661
+ * The tab the scenario acts on. A tab opens without moving it, as in replay: only tabs() follows the tab an action
662
+ * was recorded opening (an older recording without tab marks follows any).
663
+ */
582
664
  get page(): Page {
583
665
  const lane = this.lane;
584
666
  while (lane.opened.length > 0) {
585
667
  const fresh = lane.opened.shift()!;
586
- if (!fresh.isClosed()) lane.active = fresh;
668
+ if (!fresh.isClosed() && this.followsAnyTab) lane.active = fresh;
669
+ }
670
+ // The tab closed itself (a sign-in popup that closes when done): the tab that slid into its place, else the last,
671
+ // as replay falls back (Playwright MCP's rule).
672
+ const open = this.openPages();
673
+ if (lane.active.isClosed() && open.length > 0) {
674
+ const at = lane.tabs.indexOf(lane.active);
675
+ const before = at < 0 ? open.length : lane.tabs.slice(0, at).filter((p) => !p.isClosed()).length;
676
+ lane.active = open[Math.min(before, open.length - 1)];
587
677
  }
678
+ lane.tabs = open;
588
679
  return lane.active;
589
680
  }
590
681
 
@@ -689,12 +780,6 @@ export class Run {
689
780
  */
690
781
  async tabs(opens = false, background = false): Promise<void> {
691
782
  const lane = this.lane;
692
- if (background) {
693
- // Opened behind the page clicked: noted, not followed.
694
- await lane.context.waitForEvent("page", { timeout: 150 }).catch(() => undefined);
695
- lane.opened.length = 0;
696
- return;
697
- }
698
783
  if (lane.opened.length === 0) {
699
784
  await lane.context.waitForEvent("page", { timeout: opens ? SETTINGS.timeoutMs : 150 }).catch(() => undefined);
700
785
  }
@@ -702,14 +787,19 @@ export class Run {
702
787
  while (lane.opened.length > 0) {
703
788
  const fresh = lane.opened.shift()!;
704
789
  await fresh.waitForLoadState("domcontentloaded").catch(() => undefined);
790
+ // Opened behind the page clicked: noted, not followed (waited for like any recorded tab, as replay waits).
705
791
  if (!background) lane.active = fresh;
706
792
  }
707
793
  }
708
794
 
709
- private openPages = () => this.lane.context.pages().filter((p) => !p.isClosed());
795
+ private openPages(): Page[] {
796
+ return this.lane.context.pages().filter((p) => !p.isClosed());
797
+ }
710
798
 
711
799
  /** Act on tab `index` (0-based, in the order they opened). */
712
800
  async switchTab(index: number): Promise<void> {
801
+ // A tab that opened already is taken first, as replay follows one before every action: the switch then holds.
802
+ void this.page;
713
803
  await expect.poll(() => this.openPages().length > index, { message: `tab ${index} to exist`, timeout: SETTINGS.timeoutMs }).toBe(true);
714
804
  const target = this.openPages()[index];
715
805
  await target.bringToFront();
@@ -724,15 +814,22 @@ export class Run {
724
814
  this.lane.active = fresh;
725
815
  }
726
816
 
727
- /** Close tab `index`, or the active one; the newest tab left becomes active. */
817
+ /**
818
+ * Close tab `index`, or the active one, where the recording's browser went: another tab closed leaves the active
819
+ * one, and the active one closed moves to the tab that took its place, else the last.
820
+ */
728
821
  async closeTab(index?: number): Promise<void> {
729
822
  this.act();
730
- const target = index === undefined ? this.lane.active : this.openPages()[index];
823
+ // From the tab replay is on: one that opened already is followed first, as replay does before every action.
824
+ const active = this.page;
825
+ const pages = this.openPages();
826
+ const target = index === undefined ? active : pages[index];
731
827
  if (!target) throw new Error(`tab ${index} does not exist`);
828
+ const at = pages.indexOf(target);
732
829
  await target.close();
733
830
  const remaining = this.openPages();
734
831
  if (remaining.length === 0) throw new Error("closed the last tab; nothing left to drive");
735
- this.lane.active = remaining[remaining.length - 1];
832
+ if (target === active || active.isClosed()) this.lane.active = remaining[Math.min(at, remaining.length - 1)];
736
833
  }
737
834
 
738
835
  /** Run `action`, which must start `count` downloads; the latest is the one expectDownload reads. */
@@ -768,6 +865,66 @@ export class Run {
768
865
  await (await chooser).setFiles(files.map(uploadFile));
769
866
  }
770
867
 
868
+ /**
869
+ * Nothing the recording names is shown, in the page and (`ownFrames`) the app's own frames that are shown, once
870
+ * open requests are answered and the hidden state has held for half a second, as replay checks a "not shown":
871
+ * an error drawn 300 ms after the click is shown (found in the 1.3.5 review).
872
+ */
873
+ async expectNotShown(build: (root: Page | Frame) => Locator[], ownFrames = true): Promise<void> {
874
+ await this.settled(async () => {
875
+ for (const root of [this.page, ...(ownFrames ? await shownOwnFrames(this.page) : [])]) {
876
+ for (const target of build(root)) {
877
+ // A shown closed single select shows its selected option, which Playwright calls hidden, as replay reads it.
878
+ const selected = () =>
879
+ target.evaluateAll((els) =>
880
+ els.some((o) => {
881
+ const owner = o instanceof HTMLOptionElement && o.selected ? o.closest("select") : null;
882
+ if (!owner || owner.multiple || owner.size > 1) return false;
883
+ const box = owner.getBoundingClientRect();
884
+ return box.width > 0 && box.height > 0 && getComputedStyle(owner).visibility !== "hidden";
885
+ }),
886
+ );
887
+ if ((await target.filter({ visible: true }).count()) > 0 || (await selected())) return false;
888
+ }
889
+ }
890
+ return true;
891
+ }, "every match of every recorded locator to be hidden, and to stay hidden");
892
+ }
893
+
894
+ /**
895
+ * As replay's pollSettled: open requests answered first, then `check` must hold for half a second, so a passing
896
+ * moment (a list still growing, a navigation on its way, a request answered again) is not the verdict.
897
+ */
898
+ async settled(check: () => Promise<boolean>, message: string): Promise<void> {
899
+ await this.lane.net.quiet(Math.min(SETTINGS.timeoutMs / 2, 3000));
900
+ const settle = Math.min(500, SETTINGS.timeoutMs / 4);
901
+ let since: number | undefined;
902
+ const stop = stopsOnBacktrack(check);
903
+ await expect
904
+ .poll(
905
+ async () => {
906
+ if (!(await stop.check().catch(() => false))) {
907
+ since = undefined;
908
+ return false;
909
+ }
910
+ if (stop.backtracked()) return true;
911
+ since ??= Date.now();
912
+ return Date.now() - since >= settle;
913
+ },
914
+ { message, timeout: SETTINGS.timeoutMs + settle },
915
+ )
916
+ .toBe(true);
917
+ stop.rethrow(message);
918
+ }
919
+
920
+ /** The target shows exactly `n` elements, held once the page settles, as replay counts them. */
921
+ async expectCount(target: Locator, n: number): Promise<void> {
922
+ let seen = 0;
923
+ await this.settled(async () => (seen = await target.filter({ visible: true }).count()) === n, `the target to show ${n} element(s)`).catch((err) => {
924
+ throw new Error(`${err instanceof Error ? err.message : String(err)}; it shows ${seen}`);
925
+ });
926
+ }
927
+
771
928
  /** The text `target` shows, once open requests are answered and the text has held for half a second. */
772
929
  async capture(name: string, target: Locator): Promise<void> {
773
930
  await this.lane.net.quiet(Math.min(SETTINGS.timeoutMs / 2, 3000));
@@ -782,7 +939,7 @@ export class Run {
782
939
  const at = Date.now();
783
940
  if (seen?.text !== text) seen = { text, since: at };
784
941
  if (at - seen.since < settle && at < deadline) return false;
785
- const element = await target.first().elementHandle({ timeout: 1000 }).catch(() => null);
942
+ const element = await (await theMatch(target)).elementHandle({ timeout: 1000 }).catch(() => null);
786
943
  if (!element) return false;
787
944
  await this.captures.get(name)?.dispose().catch(() => undefined);
788
945
  this.captures.set(name, element);
@@ -820,9 +977,10 @@ export class Run {
820
977
  let element: ElementHandle | undefined = same ? this.captures.get(compareTo) : undefined;
821
978
  /** The latest look's reason the two cannot be compared: said only if no look passes. */
822
979
  let problem: string | undefined;
823
- await expect
824
- .poll(async () => {
825
- element ??= (await target.first().elementHandle({ timeout: 1000 }).catch(() => null)) ?? undefined;
980
+ // Held once the page settles, as replay checks it: a placeholder drawn during a refresh is not the verdict.
981
+ await this
982
+ .settled(async () => {
983
+ element ??= (await (await theMatch(target)).elementHandle({ timeout: 1000 }).catch(() => null)) ?? undefined;
826
984
  if (!element) return false;
827
985
  const text = await drawn(element);
828
986
  if (text === "") return false;
@@ -830,9 +988,8 @@ export class Run {
830
988
  problem = "problem" in verdict ? verdict.problem : undefined;
831
989
  if (!("differ" in verdict) || !verdict.differ) return false;
832
990
  // The element must still be one the target names.
833
- return target.evaluateAll((els, el) => els.includes(el as Element), element).catch(() => false);
834
- }, { message: `target text to differ from "${compareTo}" (${right})`, timeout: SETTINGS.timeoutMs })
835
- .toBe(true)
991
+ return target.evaluateAll((els, el) => els.includes(el as HTMLElement), element).catch(() => false);
992
+ }, `target text to differ from "${compareTo}" (${right})`)
836
993
  .catch((err) => {
837
994
  throw problem ? new Error(`the differs check: ${problem}`) : err;
838
995
  });
@@ -849,20 +1006,25 @@ export class Run {
849
1006
  masked(() => jsonChecksReadable(match.json!));
850
1007
  }
851
1008
  const net = this.lane.net;
852
- await expect
853
- .poll(
854
- () =>
855
- (kind === "check" ? net.sinceAction() : net.sincePreviousStep()).some(
856
- (e) =>
857
- (url.test(e.url) || url.test(decode(e.url))) &&
858
- (!match.method || e.method.toUpperCase() === match.method.toUpperCase()) &&
859
- statusMatches(e.status, match.status) &&
860
- (!match.json || masked(() => checkResponseJson(e.body, match.json!)) === undefined) &&
861
- (!body || (e.body !== undefined && body.test(e.body))),
862
- ),
863
- { message: `a ${match.method ?? ""} response from /${match.url}/ with status ${match.status ?? "2xx"}${match.body ? ` and a body matching /${match.body}/` : ""}${match.json ? ` whose JSON fields pass ${match.json.length} check(s)` : ""}`, timeout: SETTINGS.timeoutMs },
864
- )
865
- .toBe(true);
1009
+ const matches = (e: Observed) =>
1010
+ (rawUrlMatch(url, e.url) || testsWithin(url, decode(e.url))) &&
1011
+ (!match.method || e.method.toUpperCase() === match.method.toUpperCase()) &&
1012
+ statusMatches(e.status, match.status) &&
1013
+ (!match.json || masked(() => checkResponseJson(e.body, match.json!)) === undefined) &&
1014
+ (!body || (e.body !== undefined && testsWithin(body, e.body)));
1015
+ const seenNow = async () => {
1016
+ const seen = kind === "check" ? net.sinceAction() : net.sincePreviousStep();
1017
+ const first = seen.find(matches);
1018
+ if (!first || kind === "wait") return first !== undefined;
1019
+ // As replay: the same request (URL and method, and the body the check names) answered again after it with a
1020
+ // status the check rejects fails the check; a POST answered 200 and then 500 failed (found in review).
1021
+ const same = (e: Observed) =>
1022
+ e.url === first.url && e.method === first.method && (!match.json || masked(() => checkResponseJson(e.body, match.json!)) === undefined) && (!body || (e.body !== undefined && testsWithin(body, e.body)));
1023
+ return !seen.some((e) => e.seq > first.seq && same(e) && !matches(e));
1024
+ };
1025
+ const message = `a ${match.method ?? ""} response from /${match.url}/ with status ${match.status ?? "2xx"}${match.body ? ` and a body matching /${match.body}/` : ""}${match.json ? ` whose JSON fields pass ${match.json.length} check(s)` : ""}`;
1026
+ // A check, once the page's requests settle, as replay checks it; a wait takes the first that matches.
1027
+ await (kind === "check" ? this.settled(seenNow, message) : poll(seenNow, message));
866
1028
  }
867
1029
 
868
1030
  /**
@@ -980,9 +1142,9 @@ export class Run {
980
1142
  const reason = (err instanceof Error ? err.message : String(err)).split("\n")[0].replace(/^apiRequestContext\.fetch:\s*/, "").trim();
981
1143
  throw new Error(mask(`${method} ${url} got no response: ${reason}`));
982
1144
  }
983
- const body = await response.text().catch(() => undefined);
984
1145
  const status = response.status();
985
1146
  const headers = response.headers();
1147
+ const body = await responseText(response, headers["content-type"]);
986
1148
  // Its body copied, the response is let go, as replay does.
987
1149
  await response.dispose?.().catch(() => undefined);
988
1150
  const got: Exchange = (lane.last = { method, url, status, headers, body, durationMs: Date.now() - started });
@@ -1017,7 +1179,12 @@ export class Run {
1017
1179
  }
1018
1180
  const value = at(parsed, pointer);
1019
1181
  if (value === undefined) throw new Error(mask(`${method} ${url}: the response has no ${pointer || "/"} to extract as "${name}"${excerpt(exchange.body)}`));
1020
- this.vars.set(name, typeof value === "string" ? value : JSON.stringify(value));
1182
+ // A list or object keeps its numbers as the API wrote them, numbers still, as replay keeps them (found in the 1.3.5 review).
1183
+ const raw = (JSON as unknown as { rawJSON(source: string): unknown }).rawJSON;
1184
+ const kept = value !== null && typeof value === "object" && !(value instanceof ExactNumber)
1185
+ ? JSON.stringify(at(JSON.parse(exchange.body ?? "", (_key, v: unknown, context?: { source?: string }) => (typeof v === "number" && context?.source !== undefined ? raw(context.source) : v)), pointer))
1186
+ : JSON.stringify(value);
1187
+ this.vars.set(name, typeof value === "string" ? value : kept);
1021
1188
  }
1022
1189
  }
1023
1190
 
@@ -1141,13 +1308,13 @@ const drawn = async (element: ElementHandle) => normalize((await read(element).c
1141
1308
  const DRAWN_TEXT: string = /*DRAWN_TEXT*/ "" /*END*/;
1142
1309
 
1143
1310
  /** The element's drawn text and its lines; nothing when it draws none. */
1144
- async function read(element: ElementHandle): Promise<{ text: string; pieces: string[]; runs: string }> {
1145
- return element.evaluate((el, src) => (0, eval)(`(${src})`)(el, true), DRAWN_TEXT);
1311
+ async function read(element: ElementHandle, how: true | "each" = true): Promise<{ text: string; pieces: string[]; runs: string }> {
1312
+ return element.evaluate((el, [src, mode]) => (0, eval)(`(${src})`)(el, mode), [DRAWN_TEXT, how] as const);
1146
1313
  }
1147
1314
 
1148
- /** The lines an element shows, as replay's expectEach reads them. */
1315
+ /** The lines an element shows, as replay's expectEach reads them: every option of a closed dropdown too. */
1149
1316
  async function lines(element: ElementHandle): Promise<string[]> {
1150
- return (await read(element)).pieces;
1317
+ return (await read(element, "each")).pieces;
1151
1318
  }
1152
1319
 
1153
1320
  // A copy of the runner's choice of the match a check reads (src/replay/index.ts), kept the same by a test.
@@ -1179,8 +1346,32 @@ async function theMatch(target: Locator): Promise<Locator> {
1179
1346
  return at > 0 ? target.nth(at) : target.first();
1180
1347
  }
1181
1348
 
1182
- const poll = (check: () => Promise<boolean>, message: string) =>
1183
- expect.poll(check, { message, timeout: SETTINGS.timeoutMs }).toBe(true);
1349
+ const poll = async (check: () => Promise<boolean>, message: string): Promise<void> => {
1350
+ const stop = stopsOnBacktrack(check);
1351
+ await expect.poll(stop.check, { message, timeout: SETTINGS.timeoutMs }).toBe(true);
1352
+ stop.rethrow(message);
1353
+ };
1354
+
1355
+ /** A check that ends its poll on a pattern that backtracks; rethrow then fails with why, as replay's pollEvery does. */
1356
+ function stopsOnBacktrack(check: () => Promise<boolean>): { check: () => Promise<boolean>; backtracked: () => boolean; rethrow: (message: string) => void } {
1357
+ let caught: Backtracks | undefined;
1358
+ return {
1359
+ check: async () => {
1360
+ if (caught) return true;
1361
+ try {
1362
+ return await check();
1363
+ } catch (err) {
1364
+ if (!(err instanceof Backtracks)) throw err;
1365
+ caught = err;
1366
+ return true;
1367
+ }
1368
+ },
1369
+ backtracked: () => caught !== undefined,
1370
+ rethrow: (message) => {
1371
+ if (caught) throw new Error(`${message}: ${caught.message}`);
1372
+ },
1373
+ };
1374
+ }
1184
1375
 
1185
1376
  /** The target shows `text` (a string is a plain substring; see bounded). */
1186
1377
  export async function expectText(target: Locator, text: string | RegExp): Promise<void> {
@@ -1189,6 +1380,14 @@ export async function expectText(target: Locator, text: string | RegExp): Promis
1189
1380
  await poll(async () => contains(await shown(target, "runs"), needle), `target text to contain ${text}`);
1190
1381
  }
1191
1382
 
1383
+ /** The match replay reads is shown and holds `value`, both in one look, as replay checks it. */
1384
+ export async function expectValue(target: Locator, value: string): Promise<void> {
1385
+ await poll(async () => {
1386
+ const match = await theMatch(target);
1387
+ return (await match.isVisible()) && (await match.inputValue({ timeout: 1000 })) === value;
1388
+ }, `a shown input with value "${value}"`);
1389
+ }
1390
+
1192
1391
  /** The target's text matches the recorded pattern, in any case. */
1193
1392
  export async function expectMatches(target: Locator, source: string): Promise<void> {
1194
1393
  const re = pattern(source, "i");
@@ -1209,9 +1408,17 @@ export async function expectAttribute(target: Locator, name: string, source: str
1209
1408
  const element = await theMatch(target);
1210
1409
  // Shown, unless the attribute is what hides it, as replay checks it.
1211
1410
  if (!["hidden", "aria-hidden", "inert", "class", "style", "open", "data-state"].includes(name.toLowerCase()) && !(await element.isVisible())) return false;
1212
- const found = await element.getAttribute(name, { timeout: 1000 }).catch(() => undefined);
1411
+ // A form control's state as it is now, as replay reads it: a box the app unticked has no `checked`.
1412
+ const live = /^(?:checked|selected|value)$/i.test(name)
1413
+ ? await element.evaluate((control: any, key: string): string | null | undefined => {
1414
+ if (!(key in control) || (key === "value" && !/^(?:INPUT|TEXTAREA|SELECT|OPTION|BUTTON)$/.test(control.tagName))) return undefined;
1415
+ if (key === "value") return String(control.value);
1416
+ return control[key] ? "" : null;
1417
+ }, name.toLowerCase()).catch(() => undefined)
1418
+ : undefined;
1419
+ const found = live !== undefined ? live : await element.getAttribute(name, { timeout: 1000 }).catch(() => undefined);
1213
1420
  if (found === undefined) return false;
1214
- return found === null ? absentHolds : re.test(found);
1421
+ return found === null ? absentHolds : testsWithin(re, found);
1215
1422
  }, `attribute ${name} to match /${source}/`);
1216
1423
  }
1217
1424
 
@@ -1225,10 +1432,30 @@ export async function expectStyle(target: Locator, property: string, expected: s
1225
1432
  if (!["display", "visibility", "opacity", "content-visibility", "height", "max-height", "width", "max-width", "transform", "clip-path", "clip"].includes(property.toLowerCase()) && !(await element.isVisible())) return false;
1226
1433
  const found = await element.evaluate((el, name) => (globalThis as unknown as { getComputedStyle(e: unknown): { getPropertyValue(n: string): string } }).getComputedStyle(el).getPropertyValue(name), property, { timeout: 1000 }).catch(() => undefined);
1227
1434
  if (found === undefined) return false;
1228
- return typeof wanted === "string" ? normalize(found) === wanted : wanted.test(normalize(found));
1435
+ return typeof wanted === "string" ? normalize(found) === wanted : testsWithin(wanted, normalize(found));
1229
1436
  }, `${property} to be ${expected}`);
1230
1437
  }
1231
1438
 
1439
+ /**
1440
+ * Selects the recorded options as replay does: an option that is one option's label and another's value is taken
1441
+ * as the label (Playwright MCP's form fill picks by label but writes a plain string).
1442
+ */
1443
+ export async function selectOption(target: Locator, options: string[]): Promise<void> {
1444
+ const plain = options.length > 1 ? options : options[0];
1445
+ const norm = (t: string) => t.replace(/[​­]/g, "").trim().replace(/\s+/g, " ");
1446
+ const listed: [string, string][] = await target
1447
+ .evaluate((el: any) => {
1448
+ const select = el.localName === "label" ? el.control : el;
1449
+ return select?.localName === "select" ? [...select.options].map((o: any): [string, string] => [o.value, o.label]) : [];
1450
+ }, undefined, { timeout: SETTINGS.timeoutMs })
1451
+ .catch(() => []);
1452
+ const labels = new Set(listed.map(([, label]) => norm(label)));
1453
+ const values = new Set(listed.map(([v]) => v));
1454
+ const byLabel =
1455
+ options.some((o) => labels.has(norm(o)) && values.has(o)) && options.every((o) => labels.has(norm(o)) || values.has(o));
1456
+ await target.selectOption(byLabel ? options.map((o) => (labels.has(norm(o)) ? { label: o } : { value: o })) : plain);
1457
+ }
1458
+
1232
1459
  /** Every match of every locator the recording names is hidden. */
1233
1460
  export async function expectNotVisible(...targets: Locator[]): Promise<void> {
1234
1461
  // All hidden at the same look, as replay checks them: one gone, then another, while the first came back, is not a pass.
@@ -1238,6 +1465,20 @@ export async function expectNotVisible(...targets: Locator[]): Promise<void> {
1238
1465
  }, `every match of every recorded locator to be hidden (${targets.length} locator(s))`);
1239
1466
  }
1240
1467
 
1468
+ async function shownOwnFrames(page: Page): Promise<Frame[]> {
1469
+ const origin = (url: string) => { try { return new URL(url).origin; } catch { return undefined; } };
1470
+ const own = origin(page.mainFrame().url());
1471
+ const frames: Frame[] = [];
1472
+ for (const frame of page.frames()) {
1473
+ if (frame === page.mainFrame() || !(/^about:(?:srcdoc|blank)$|^$/.test(frame.url()) || origin(frame.url()) === own)) continue;
1474
+ const element = await frame.frameElement().catch(() => undefined);
1475
+ const box = element && (await element.isVisible().catch(() => false)) ? await element.boundingBox().catch(() => null) : null;
1476
+ await element?.dispose().catch(() => {});
1477
+ if (box && box.width > 1 && box.height > 1 && box.x + box.width > 0 && box.y + box.height > 0) frames.push(frame);
1478
+ }
1479
+ return frames;
1480
+ }
1481
+
1241
1482
  /** Each value is shown in the container, as a whole line of its text. */
1242
1483
  export async function expectEach(container: Locator, values: string[]): Promise<void> {
1243
1484
  let missing = values;
@@ -1293,9 +1534,11 @@ export function urlContains(url: string, expected: string | RegExp): boolean {
1293
1534
  }
1294
1535
 
1295
1536
  /** The URL contains `expected` (raw, decoded, or with + read as a space); with "excludes", it does not; with "path", its path is exactly `expected`. */
1296
- export async function expectUrl(page: Page, expected: string | RegExp, match?: "excludes" | "path"): Promise<void> {
1537
+ export async function expectUrl(page: Page, expected: string | RegExp, match?: "excludes" | "path", run?: Run): Promise<void> {
1297
1538
  said(expected, "the expected URL");
1298
- await poll(async () => {
1539
+ // A URL that does not hold the text only once a navigation the action started has had its moment, as replay checks it.
1540
+ if (match === "excludes" && !run) throw new Error("a URL check with \"excludes\" needs the run, to wait for the page to settle");
1541
+ await (match === "excludes" ? run!.settled.bind(run) : poll)(async () => {
1299
1542
  const url = page.url();
1300
1543
  if (match === "path") {
1301
1544
  const path = new URL(url).pathname;
@@ -1329,6 +1572,8 @@ export function parseAmount(text: string): number | undefined {
1329
1572
  const [found] = runs;
1330
1573
  const before = joined.slice(0, found.index);
1331
1574
  const after = joined.slice(found.index + found[0].length);
1575
+ // Abbreviated ("€1.5M", "$1.2K", "2.5bn", "1,5 Mio. €", "3 million"): not the amount its digits say, and "1.5k" is not "1.5M".
1576
+ if (/^(?:[kKmMbB]|\s?(?:bn|mn|mio|mrd|million|billion|lakh|crore)s?\.?)(?!\p{L})/iu.test(after)) return undefined;
1332
1577
  // A decimal with no whole part ("$.50", "€,99"): the separator before it is
1333
1578
  // the decimal point, and the sign is judged by what comes before that ("-.50", "($.50)").
1334
1579
  const bare = /[.,]$/.test(before) && !/\d[.,]$/.test(before) && /^\d+$/.test(found[0]);
@@ -1363,7 +1608,9 @@ export function parseAmount(text: string): number | undefined {
1363
1608
  // Grouping: one separator, every group after the first three digits long, not the decimal one.
1364
1609
  const groups = whole.split(/[.,]/);
1365
1610
  const grouping = new Set(whole.match(/[.,]/g) ?? []);
1366
- if (grouping.size > 1 || (decimal && grouping.has(digits[last])) || groups[0] === "" || groups.slice(1).some((g) => g.length !== 3)) return undefined;
1611
+ // Or Indian lakh grouping by commas: twos before the last three ("1,23,456").
1612
+ const lakh = grouping.has(",") && groups.length > 2 && groups[0].length <= 2 && groups.at(-1)!.length === 3 && groups.slice(1, -1).every((g) => g.length === 2);
1613
+ if (grouping.size > 1 || (decimal && grouping.has(digits[last])) || groups[0] === "" || (!lakh && groups.slice(1).some((g) => g.length !== 3))) return undefined;
1367
1614
  const amount = Number(`${negative ? "-" : ""}${groups.join("")}${decimal ? `.${tail}` : ""}`);
1368
1615
  return Number.isFinite(amount) ? amount : undefined;
1369
1616
  }
@@ -1442,6 +1689,10 @@ export function valuesDiffer(left: string, right: string): { differ: boolean } |
1442
1689
  // Two currencies, or a price against a label holding that price's currency ("Book now for NOK 1,295"):
1443
1690
  // a change no amount explains. Any other two (references, counts: "ABC-123", "1 night") compare as text.
1444
1691
  if (currency(ua) && currency(ub)) {
1692
+ // "$5" and "5 USD" are one currency written two ways.
1693
+ const [ca, cb] = [amountCurrency(left), amountCurrency(right)];
1694
+ // Cents against dollars ("50¢" and "$0.50") is one amount in two units: refused as before.
1695
+ if (ca && cb && !otherCurrency(ca, cb) && (ca.is === "¢") === (cb.is === "¢")) return { differ: !sameAmount(a, b) };
1445
1696
  return { problem: `"${left}" and "${right}" are amounts in different currencies, so they differ whatever the amount does. Capture both in one currency.` };
1446
1697
  }
1447
1698
  if ((currency(ua) && words(ub).includes(ua)) || (currency(ub) && words(ua).includes(ub))) {
@@ -1647,7 +1898,9 @@ export function exactValueKey(body: string, read: (json: unknown) => unknown): s
1647
1898
  }
1648
1899
 
1649
1900
  const kind = (value: unknown) => value === null ? "null" : Array.isArray(value) ? "array" : value instanceof ExactNumber ? "number" : typeof value;
1650
- const describe = (value: unknown) => `${kind(value)}${value instanceof ExactNumber ? ` ${value}` : value === null || typeof value !== "object" ? ` ${JSON.stringify(value)}` : ""}`;
1901
+ const describeValue = (value: unknown) => `${kind(value)}${value instanceof ExactNumber ? ` ${value}` : value === null || typeof value !== "object" ? ` ${JSON.stringify(value)}` : ""}`;
1902
+
1903
+ const CREDENTIAL_NOT_KEPT = "[credential, not kept]";
1651
1904
 
1652
1905
  /** The value at a JSON Pointer: own properties and array indexes only, undefined when missing. */
1653
1906
  function at(json: unknown, path: string): unknown {
@@ -1677,6 +1930,11 @@ function checkValue(json: unknown, checks: ResponseJsonCheck[], prefix = ""): st
1677
1930
  for (const check of checks) {
1678
1931
  const value = at(json, check.path);
1679
1932
  const field = `JSON field ${JSON.stringify(prefix + check.path)}`;
1933
+ // A field named as a credential, or under one (`session: { id }`), as hideCredentialFields reads it: its value never reaches the message.
1934
+ const secret = value !== undefined && ([prefix + check.path, (prefix + check.path).replace(/\/[^/]*$/, "")].some((p) => p !== "" && isCredentialCapture("", p)) ||
1935
+ // A token pair's access token, as nestedCredentials reads it.
1936
+ (/\/access$/.test(check.path) && tokenPairAccess(at(json, check.path.replace(/\/access$/, ""))) === value));
1937
+ const describe = (v: unknown) => (secret ? CREDENTIAL_NOT_KEPT : describeValue(v));
1680
1938
  const got = value === undefined ? "missing" : describe(value);
1681
1939
  if (check.item) {
1682
1940
  if (!Array.isArray(value)) return `${field}: expected a list, got ${got}`;
@@ -1697,17 +1955,30 @@ function checkValue(json: unknown, checks: ResponseJsonCheck[], prefix = ""): st
1697
1955
  if ((value !== undefined) !== check.exists) return `${field}: expected ${check.exists ? "present, got missing" : `absent, got ${describe(value)}`}`;
1698
1956
  } else if (check.differs !== undefined) {
1699
1957
  const other = jsonExpected(check, check.differs);
1700
- if (value === undefined) return `${field}: expected a value other than ${describe(other)}, got missing`;
1958
+ if (value === undefined) return `${field}: expected a value other than ${describeValue(other)}, got missing`;
1701
1959
  // Untyped, the text is compared as written: a number 5 is the same as "5" (a captured id is kept as text).
1702
1960
  // A list, an object or null is compared as its JSON text: [{"sku":"a"}] is the same as itself written out.
1703
1961
  // Keys in any order and any spacing: {"b":2,"a":1} is the same as {"a": 1, "b": 2}.
1704
1962
  const canonical = (v: unknown) => JSON.stringify(v, (_key, x: unknown) => (x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : x));
1705
1963
  const written = (text: unknown) => { try { return canonical(parseChecked(String(text))); } catch { return String(text); } };
1706
- if (value === other || (check.type === undefined && (value !== null && typeof value === "object" ? canonical(value) === written(other) : String(value) === other))) return `${field}: expected a value other than ${describe(other)}, got the same`;
1964
+ // A number is the same however the step writes it: 10.5 is "10.50" and 100 is "1e2" (found in the 1.3.5 review).
1965
+ const sameNumber = (v: unknown) => {
1966
+ const [a, b] = [typeof v === "number" || v instanceof ExactNumber ? decimal(String(v)) : undefined, typeof other === "string" ? decimal(other) : undefined];
1967
+ return a !== undefined && b !== undefined && compareDecimal(a, b) === 0;
1968
+ };
1969
+ // Checked as a string, a number, true or null is its text, as equals reads it: "differs" on the same id fails (found in the 1.3.5 review).
1970
+ if (value === other || (check.type === "string" && (value === null || typeof value !== "object" || value instanceof ExactNumber) && String(value) === other) || (check.type === undefined && (value !== null && typeof value === "object" && !(value instanceof ExactNumber) ? canonical(value) === written(other) : String(value) === other || sameNumber(value)))) return `${field}: expected a value other than ${describe(other)}, got the same`;
1707
1971
  } else if (check.pattern !== undefined) {
1708
1972
  const re = jsonPattern(check);
1973
+ // "A non-empty field" holds on a number too: an id is often one (found in the 1.3.5 review). Any other
1974
+ // pattern reads text only, so "1" never passes on the number 10.
1975
+ const nonEmptyNumber = check.pattern === NON_EMPTY && (typeof value === "number" || value instanceof ExactNumber);
1976
+ if (nonEmptyNumber) continue;
1709
1977
  if (typeof value !== "string") return `${field}: expected text matching /${check.pattern}/, got ${got}`;
1710
- if (!re.test(value)) return `${field}: expected text matching /${check.pattern}/, got ${JSON.stringify(value)}`;
1978
+ // Run where V8 can stop it: a recorded pattern that backtracks (`(a+)+$`) on a long value fails, never freezes the run (found in the 1.4.0 review).
1979
+ const found = matchesWithin(new RegExp(re.source, re.flags.replace(/[gy]/g, "") + "g"), value);
1980
+ if (found === undefined) return `${field}: the pattern /${check.pattern}/ takes too long on the text (it backtracks): write it without a repeat inside a repeat, such as (a+)+`;
1981
+ if (found.length === 0) return `${field}: expected text matching /${check.pattern}/, got ${secret ? CREDENTIAL_NOT_KEPT : JSON.stringify(value)}`;
1711
1982
  } else if (check.min !== undefined || check.max !== undefined) {
1712
1983
  const min = check.min === undefined ? undefined : jsonNumber(check, "min");
1713
1984
  const max = check.max === undefined ? undefined : jsonNumber(check, "max");
@@ -1725,25 +1996,31 @@ function checkValue(json: unknown, checks: ResponseJsonCheck[], prefix = ""): st
1725
1996
  };
1726
1997
  const under = min !== undefined && beyond(check.min!, min, -1);
1727
1998
  const over = max !== undefined && beyond(check.max!, max, 1);
1728
- if (under || over) return `${field}: expected a number ${bounds}, got ${value}`;
1999
+ if (under || over) return `${field}: expected a number ${bounds}, got ${secret ? CREDENTIAL_NOT_KEPT : value}`;
1729
2000
  } else {
1730
2001
  const expected = jsonExpected(check);
1731
2002
  // Too large to compare as a number, it is checked as a string of its digits (jsonExpected says so).
1732
2003
  const same = value instanceof ExactNumber ? (check.type === undefined || check.type === "string") && String(value) === expected : value === expected;
1733
- if (!same) return `${field}: expected ${describe(expected)}, got ${got}`;
2004
+ if (!same) return `${field}: expected ${describeValue(expected)}, got ${got}`;
1734
2005
  }
1735
2006
  }
1736
2007
  return undefined;
1737
2008
  }
1738
2009
 
2010
+ /** The pattern "should have a non-empty field" compiles to: text with a character other than a space, or any number. */
2011
+ export const NON_EMPTY = "\\S";
2012
+
1739
2013
  /**
1740
2014
  * JSON with an integer beyond JavaScript's precision (a snowflake or int64
1741
- * id) kept as the digits the API sent, never rounded into another id, as a
2015
+ * id), or a decimal it cannot hold, kept as the digits the API sent, never rounded into another id, as a
1742
2016
  * capture keeps it: a differs check then sees the same id (found in review).
1743
2017
  */
2018
+
1744
2019
  export function parseExact(text: string): unknown {
2020
+ // As a check reads it (parseChecked): a decimal JavaScript would round keeps its digits too, so a differs check
2021
+ // never passes on an unchanged balance, nor a later request send another number (found in the 1.3.5 review).
1745
2022
  return JSON.parse(text, (_key, value: unknown, context?: { source?: string }) =>
1746
- typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value) && context?.source !== undefined ? context.source : value);
2023
+ typeof value === "number" && context?.source !== undefined && (Math.abs(value) > Number.MAX_SAFE_INTEGER || !heldAsWritten(context.source, value)) ? context.source : value);
1747
2024
  }
1748
2025
 
1749
2026
  /** A missing property is different from a property whose value is null. */