saffron-ai 1.3.0 → 1.3.2
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.
- package/CHANGELOG.md +788 -0
- package/dist-pkg/cli.js +396 -376
- package/package.json +1 -1
- package/skills/saffron/SKILL.md +13 -2
- package/skills/saffron/references/config.md +3 -2
- package/skills/saffron/references/syntax.md +9 -0
- package/templates/playwright/saffron-helpers.ts +399 -74
|
@@ -51,27 +51,43 @@ export function env(name: string): string {
|
|
|
51
51
|
return value;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
/** Every credential the API handed out in this worker (isCredentialCapture), name
|
|
55
|
-
const CREDENTIALS
|
|
54
|
+
/** Every credential the API handed out in this worker (isCredentialCapture), name and value, an earlier value a rotation replaced kept too: masked like an {env:...} value. Which a request may send is the Run's own. */
|
|
55
|
+
const CREDENTIALS: [string, string][] = [];
|
|
56
56
|
|
|
57
|
-
/**
|
|
57
|
+
/** A credential the API handed out, kept once however often a poll reads it. */
|
|
58
|
+
const remember = (name: string, value: string): void => {
|
|
59
|
+
if (!CREDENTIALS.some(([n, v]) => n === name && v === value)) CREDENTIALS.push([name, value]);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** Text with every {env:...} value and captured credential written back as its token, longest first, as written, as JSON escapes it and as a URL encodes it (found in review). */
|
|
58
63
|
function mask(text: string): string {
|
|
59
|
-
const values = [...[...SECRETS].map(([name, value]) => [`{env:${name}}`, value]), ...
|
|
64
|
+
const values = [...[...SECRETS].map(([name, value]) => [`{env:${name}}`, value]), ...CREDENTIALS.map(([name, value]) => [`{captured:${name}}`, value])];
|
|
60
65
|
for (const [token, value] of values.sort((a, b) => b[1].length - a[1].length)) {
|
|
61
66
|
if (value.length < 3) continue;
|
|
62
|
-
text = text.replaceAll(
|
|
63
|
-
const escaped = JSON.stringify(value).slice(1, -1);
|
|
64
|
-
if (escaped !== value) text = text.replaceAll(escaped, token);
|
|
67
|
+
for (const spelling of new Set([value, JSON.stringify(value).slice(1, -1), encodeURIComponent(value), urlValue(value, true), urlValue(value, false)])) text = text.replaceAll(spelling, token);
|
|
65
68
|
}
|
|
66
69
|
return text;
|
|
67
70
|
}
|
|
68
71
|
|
|
72
|
+
/** What `run` returns, any error it throws masked: a check's message quotes the resolved value it compares with (found in review). */
|
|
73
|
+
function masked<T>(run: () => T): T {
|
|
74
|
+
try {
|
|
75
|
+
return run();
|
|
76
|
+
} catch (err) {
|
|
77
|
+
if (err instanceof Error) err.message = mask(err.message);
|
|
78
|
+
throw err;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
69
82
|
/** Words a name ends in when what it holds is a credential: a login's token, a session id, a key, a code. */
|
|
70
83
|
const CREDENTIAL_WORDS = new Set(["token", "secret", "password", "passwd", "pwd", "passphrase", "apikey", "accesskey", "privatekey", "session", "credential", "credentials", "auth", "authorization", "jwt", "bearer", "cookie", "otp", "pin", "csrf", "xsrf", "signature", "nonce", "refresh"]);
|
|
71
84
|
|
|
72
85
|
/** Words after a credential's that say how it is held, never what it is. */
|
|
73
86
|
const HELD_AS = new Set(["code", "value", "pem", "encrypted", "json", "data", "string", "raw", "b64", "base64"]);
|
|
74
87
|
|
|
88
|
+
/** Credential words a name may end in written as one word: only ones no ordinary word ends in. */
|
|
89
|
+
const JOINED_SUFFIXES = ["token", "secret", "password", "passwd", "passphrase", "apikey", "accesskey", "privatekey", "credential", "credentials", "cookie", "sessionid", "sessid"];
|
|
90
|
+
|
|
75
91
|
/**
|
|
76
92
|
* Whether a name (a capture's, a field's, a header's) names a credential, by its last word, a version or a number
|
|
77
93
|
* after it aside (`accessToken`, `api_key`, `X-Session-Id`, `X-Hub-Signature-256`, `Set-Cookie`), never one it only
|
|
@@ -86,7 +102,8 @@ export function namesSecret(name: string): boolean {
|
|
|
86
102
|
const before = words.at(-2) ?? "";
|
|
87
103
|
if (last === "key") return ["api", "access", "private", "secret", "signing", "session", "encryption", "client", "subscription"].includes(before);
|
|
88
104
|
if (last === "id") return before === "session" || before === "key";
|
|
89
|
-
|
|
105
|
+
// Written as one word (`authtoken`, `JSESSIONID`), and `sid` (`connect.sid`) only whole.
|
|
106
|
+
return CREDENTIAL_WORDS.has(last) || (last === "sid" && (words.length === 1 || before === "connect" || before === "session")) || JOINED_SUFFIXES.some((w) => last.endsWith(w));
|
|
90
107
|
}
|
|
91
108
|
|
|
92
109
|
/**
|
|
@@ -113,7 +130,7 @@ export function nestedCredentials(value: unknown, at = ""): [string, string][] {
|
|
|
113
130
|
const words = key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
114
131
|
const code = words.some((w) => w === "otp" || w === "pin");
|
|
115
132
|
// A password is one at any length a password takes (a test user's "abc123").
|
|
116
|
-
const password = words.some((w) => ["password", "passwd", "pwd", "passphrase", "secret"].
|
|
133
|
+
const password = words.some((w) => ["password", "passwd", "pwd", "passphrase", "secret"].some((p) => w === p || w.endsWith(p)));
|
|
117
134
|
const secret = (v: unknown): string | undefined =>
|
|
118
135
|
typeof v === "string" && (v.length >= 8 || (password && v.length >= 3)) ? v
|
|
119
136
|
: code && (typeof v === "string" || typeof v === "number") && /^\d{4,8}$/.test(String(v)) ? String(v) : undefined;
|
|
@@ -162,22 +179,31 @@ export function projectFile(file: string): string {
|
|
|
162
179
|
}
|
|
163
180
|
|
|
164
181
|
const LETTER = String.raw`[\p{L}\p{N}\p{M}]`;
|
|
182
|
+
// A script written without spaces (Chinese, Japanese, Thai...): an edge of it is not bounded, as in replay, but for
|
|
183
|
+
// a negating prefix before it ("成功" is not in "不成功").
|
|
184
|
+
const SPACELESS = /[\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}\p{sc=Thai}\p{sc=Lao}\p{sc=Khmer}\p{sc=Myanmar}]/u;
|
|
185
|
+
const NEGATING = "无法|無法|不能|没有|沒有|未能|ไม่ได้|不|未|非|無|无|没|沒|ไม่";
|
|
165
186
|
|
|
166
187
|
/**
|
|
167
|
-
* Text that must appear inside a longer text
|
|
168
|
-
*
|
|
169
|
-
*
|
|
188
|
+
* Text that must appear inside a longer text, never inside a longer word or
|
|
189
|
+
* number: "Order 1" never matches "Order 12", nor "5" "12.5". After a number
|
|
190
|
+
* the step wrote, a zero decimal part may follow ("$10" is in "$10.00", not
|
|
191
|
+
* "$10.50"); after a row or data value (`rows` "end"), none.
|
|
170
192
|
*/
|
|
171
|
-
export function bounded(text: string, edges: "start" | "end" | "both", flags = "u"): RegExp {
|
|
193
|
+
export function bounded(text: string, edges: "start" | "end" | "both", flags = "u", rows: "" | "end" = ""): RegExp {
|
|
172
194
|
text = said(normalize(text), "the expected text");
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
const
|
|
177
|
-
const
|
|
195
|
+
const first = [...text][0];
|
|
196
|
+
// An amount ("$5.00") is never the negative one after a minus ("-$5.00"), as replay reads it.
|
|
197
|
+
const amount = /^\p{Sc}\s?\p{N}/u.test(text);
|
|
198
|
+
const start = edges !== "end" && (amount || (new RegExp(`^${LETTER}`, "u").test(text) && !(SPACELESS.test(first) && new RegExp(`^(?:${NEGATING})`, "u").test(text))));
|
|
199
|
+
const end = edges !== "start" && new RegExp(`${LETTER}$`, "u").test(text) && !SPACELESS.test([...text].at(-1)!);
|
|
200
|
+
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})`;
|
|
201
|
+
const after = !/\p{N}$/u.test(text) ? `(?!${LETTER})` : rows === "end" ? `(?!${LETTER}|[.,]\\p{N})` : `(?!${LETTER}|[.,](?!0{1,2}(?!\\p{N}|[.,]\\p{N}))\\p{N})`;
|
|
178
202
|
// Quotes and `>` as hex, so Playwright reads no string or chain in the regex; any whitespace as replay's label match allows.
|
|
179
203
|
const body = escapeRegExp(text).replace(/ /g, "\\s+").replace(/["'`>]/g, (c) => `\\x${c.charCodeAt(0).toString(16)}`);
|
|
180
|
-
|
|
204
|
+
// After a number's point or comma ("$10."), no more digits, as replay reads it.
|
|
205
|
+
const point = edges !== "start" && /\p{N}[.,]$/u.test(text) ? "(?!\\p{N})" : "";
|
|
206
|
+
return new RegExp(`${start ? before : ""}${body}${end ? after : point}`, flags);
|
|
181
207
|
}
|
|
182
208
|
|
|
183
209
|
const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
@@ -190,6 +216,14 @@ export function pattern(source: string, flags = ""): RegExp {
|
|
|
190
216
|
return new RegExp(source, flags);
|
|
191
217
|
}
|
|
192
218
|
|
|
219
|
+
/** A value as one piece of a URL, as replay encodes it in a request's path (a copy of src/http/replay.ts urlValue). */
|
|
220
|
+
/*URL_VALUE*/
|
|
221
|
+
export function urlValue(value: string, query: boolean): string {
|
|
222
|
+
const unsafe = query ? /%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$'()*,;:@/%?]/gu : /%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@/%]/gu;
|
|
223
|
+
return value.replace(unsafe, (c) => encodeURIComponent(c));
|
|
224
|
+
}
|
|
225
|
+
/*END*/
|
|
226
|
+
|
|
193
227
|
// --- dates ----------------------------------------------------------------
|
|
194
228
|
|
|
195
229
|
const DATE_TOKEN_RE = /\{date(?:([+-]\d+)(?:([^\d{}:]+?)([+-]\d+))?)?(?::([^}]+))?\}/g;
|
|
@@ -412,7 +446,8 @@ function isLinkLocal(hostname: string): boolean {
|
|
|
412
446
|
const host = hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
413
447
|
if (/^169\.254\.\d{1,3}\.\d{1,3}$/.test(host)) return true;
|
|
414
448
|
if (/^fe[89ab][0-9a-f]?:/.test(host) || host === "fd00:ec2::254") return true;
|
|
415
|
-
|
|
449
|
+
// IPv4-compatible (::a9fe:a9fe) and NAT64 (64:ff9b::a9fe:a9fe) reach it too, as replay reads them.
|
|
450
|
+
const mapped = /^(?:::(?:ffff:)?|64:ff9b::)(?:(\d{1,3}(?:\.\d{1,3}){3})|([0-9a-f]{1,4}):[0-9a-f]{1,4})$/.exec(host);
|
|
416
451
|
if (mapped) return mapped[1] ? /^169\.254\./.test(mapped[1]) : parseInt(mapped[2], 16) === 0xa9fe;
|
|
417
452
|
return false;
|
|
418
453
|
}
|
|
@@ -724,9 +759,11 @@ export class Run {
|
|
|
724
759
|
.toBe(true);
|
|
725
760
|
}
|
|
726
761
|
|
|
727
|
-
captured
|
|
762
|
+
/** A captured value; `checked`: in a text a check compares, where a blank one would hold for more than it means, as replay refuses it. */
|
|
763
|
+
captured(name: string, checked = false): string {
|
|
728
764
|
const value = this.vars.get(name);
|
|
729
765
|
if (value === undefined) throw new Error(`no captured value named "${name}"`);
|
|
766
|
+
if (checked && value.trim() === "") throw new Error(`{captured:${name}} is blank, so the check would hold for more than it means`);
|
|
730
767
|
return value;
|
|
731
768
|
}
|
|
732
769
|
|
|
@@ -738,21 +775,32 @@ export class Run {
|
|
|
738
775
|
*/
|
|
739
776
|
async expectDiffers(compareTo: string, target?: Locator, left?: string, same = false): Promise<void> {
|
|
740
777
|
const right = this.captured(compareTo);
|
|
778
|
+
// Amounts compare as amounts, as replay's valuesDiffer does: "$10" is "$10.00", two currencies are a problem.
|
|
741
779
|
if (!target) {
|
|
742
|
-
|
|
780
|
+
const verdict = valuesDiffer(this.captured(left ?? ""), right);
|
|
781
|
+
if ("problem" in verdict) throw new Error(`the differs check: ${verdict.problem}`);
|
|
782
|
+
expect(verdict.differ, `"${left}" to differ from "${compareTo}"`).toBe(true);
|
|
743
783
|
return;
|
|
744
784
|
}
|
|
745
785
|
let element: ElementHandle | undefined = same ? this.captures.get(compareTo) : undefined;
|
|
786
|
+
/** The latest look's reason the two cannot be compared: said only if no look passes. */
|
|
787
|
+
let problem: string | undefined;
|
|
746
788
|
await expect
|
|
747
789
|
.poll(async () => {
|
|
748
790
|
element ??= (await target.first().elementHandle({ timeout: 1000 }).catch(() => null)) ?? undefined;
|
|
749
791
|
if (!element) return false;
|
|
750
792
|
const text = await drawn(element);
|
|
751
|
-
if (text === ""
|
|
793
|
+
if (text === "") return false;
|
|
794
|
+
const verdict = valuesDiffer(text, right);
|
|
795
|
+
problem = "problem" in verdict ? verdict.problem : undefined;
|
|
796
|
+
if (!("differ" in verdict) || !verdict.differ) return false;
|
|
752
797
|
// The element must still be one the target names.
|
|
753
798
|
return target.evaluateAll((els, el) => els.includes(el as Element), element).catch(() => false);
|
|
754
799
|
}, { message: `target text to differ from "${compareTo}" (${right})`, timeout: SETTINGS.timeoutMs })
|
|
755
|
-
.toBe(true)
|
|
800
|
+
.toBe(true)
|
|
801
|
+
.catch((err) => {
|
|
802
|
+
throw problem ? new Error(`the differs check: ${problem}`) : err;
|
|
803
|
+
});
|
|
756
804
|
}
|
|
757
805
|
|
|
758
806
|
/** A response matching the recorded request has been seen (a wait) or was answered since the latest action (a check). */
|
|
@@ -763,7 +811,7 @@ export class Run {
|
|
|
763
811
|
if (match.json) {
|
|
764
812
|
const malformed = responseJsonProblem(match.json);
|
|
765
813
|
if (malformed) throw new Error(`Response json ${malformed}`);
|
|
766
|
-
jsonChecksReadable(match.json);
|
|
814
|
+
masked(() => jsonChecksReadable(match.json!));
|
|
767
815
|
}
|
|
768
816
|
const net = this.lane.net;
|
|
769
817
|
await expect
|
|
@@ -774,7 +822,7 @@ export class Run {
|
|
|
774
822
|
(url.test(e.url) || url.test(decode(e.url))) &&
|
|
775
823
|
(!match.method || e.method.toUpperCase() === match.method.toUpperCase()) &&
|
|
776
824
|
statusMatches(e.status, match.status) &&
|
|
777
|
-
(!match.json || checkResponseJson(e.body, match.json) === undefined) &&
|
|
825
|
+
(!match.json || masked(() => checkResponseJson(e.body, match.json!)) === undefined) &&
|
|
778
826
|
(!body || (e.body !== undefined && body.test(e.body))),
|
|
779
827
|
),
|
|
780
828
|
{ 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 },
|
|
@@ -805,6 +853,8 @@ export class Run {
|
|
|
805
853
|
async send(spec: RequestSpec): Promise<void> {
|
|
806
854
|
const method = spec.method.toUpperCase();
|
|
807
855
|
const where = spec.service === undefined ? "api.baseURL" : `api.services.${spec.service}.baseURL`;
|
|
856
|
+
// A value that comes out blank ({captured:code} as "") is refused, as replay refuses it, never read as any 2xx.
|
|
857
|
+
if (spec.status !== undefined && spec.status.trim() === "") throw new Error(`${method} ${mask(spec.path)} expects a status that is blank, so it would hold for any 2xx`);
|
|
808
858
|
if (spec.until !== undefined && !(spec.idempotent ?? IDEMPOTENT_METHODS.has(method))) {
|
|
809
859
|
throw new Error(`${method} ${spec.path} polls (until), and a ${method} may not be sent twice: poll with a GET that reads the state, or mark the request idempotent`);
|
|
810
860
|
}
|
|
@@ -853,7 +903,28 @@ export class Run {
|
|
|
853
903
|
// A poll is a wait for a state, as replay bounds it: every 100 ms at the fastest, 10 minutes at the longest.
|
|
854
904
|
if (until && until.intervalMs < 100) throw new Error(`${method} ${spec.path} polls every ${until.intervalMs} ms, faster than the 100 ms a poll may`);
|
|
855
905
|
if (until && (spec.until!.timeoutMs ?? 30_000) > 600_000) throw new Error(`${method} ${spec.path} polls for ${spec.until!.timeoutMs} ms, longer than the 10 minutes a poll may wait`);
|
|
856
|
-
if (until) jsonChecksReadable(until.checks);
|
|
906
|
+
if (until) masked(() => jsonChecksReadable(until.checks));
|
|
907
|
+
// Every response hands out its credentials as it comes, one polled past (a token it rotates) too, and an error
|
|
908
|
+
// quotes a body: they are known before anything is shown (found in review).
|
|
909
|
+
const learn = (got: Exchange): void => {
|
|
910
|
+
for (const [name, pointer] of Object.entries(spec.extract ?? {})) {
|
|
911
|
+
const header = /^header:(.+)$/i.exec(pointer);
|
|
912
|
+
let value: unknown;
|
|
913
|
+
try {
|
|
914
|
+
value = header ? headerOf(got.headers, header[1]) : at(JSON.parse(got.body ?? ""), pointer);
|
|
915
|
+
} catch {
|
|
916
|
+
value = undefined;
|
|
917
|
+
}
|
|
918
|
+
// An object holding one is a credential too, and its token is masked on its own.
|
|
919
|
+
const nested = nestedCredentials(value);
|
|
920
|
+
if (value !== undefined && (isCredentialCapture(name, pointer) || nested.length > 0)) {
|
|
921
|
+
const kept = typeof value === "string" ? value : JSON.stringify(value);
|
|
922
|
+
this.credentials.set(name, kept);
|
|
923
|
+
remember(name, kept);
|
|
924
|
+
}
|
|
925
|
+
for (const [path, secret] of nested) remember(`${name}${path}`, secret);
|
|
926
|
+
}
|
|
927
|
+
};
|
|
857
928
|
const lane = this.lane;
|
|
858
929
|
const attempt = async (): Promise<Exchange> => {
|
|
859
930
|
const started = Date.now();
|
|
@@ -875,11 +946,17 @@ export class Run {
|
|
|
875
946
|
throw new Error(mask(`${method} ${url} got no response: ${reason}`));
|
|
876
947
|
}
|
|
877
948
|
const body = await response.text().catch(() => undefined);
|
|
878
|
-
|
|
949
|
+
const status = response.status();
|
|
950
|
+
const headers = response.headers();
|
|
951
|
+
// Its body copied, the response is let go, as replay does.
|
|
952
|
+
await response.dispose?.().catch(() => undefined);
|
|
953
|
+
const got: Exchange = (lane.last = { method, url, status, headers, body, durationMs: Date.now() - started });
|
|
954
|
+
learn(got);
|
|
955
|
+
return got;
|
|
879
956
|
};
|
|
880
957
|
const notYet = (exchange: Exchange): string | undefined => {
|
|
881
958
|
if (!statusMatches(exchange.status, spec.status)) return `returned ${exchange.status}, expected ${spec.status ?? "2xx"}${excerpt(exchange.body)}`;
|
|
882
|
-
const problem = until && until.checks.length > 0 ? checkResponseJson(exchange.body, until.checks) : undefined;
|
|
959
|
+
const problem = until && until.checks.length > 0 ? masked(() => checkResponseJson(exchange.body, until.checks)) : undefined;
|
|
883
960
|
return problem ? `${problem}${excerpt(exchange.body)}` : undefined;
|
|
884
961
|
};
|
|
885
962
|
let exchange = await attempt();
|
|
@@ -887,24 +964,6 @@ export class Run {
|
|
|
887
964
|
await new Promise<void>((r) => setTimeout(r, until.intervalMs));
|
|
888
965
|
exchange = await attempt();
|
|
889
966
|
}
|
|
890
|
-
// A response the step fails on still hands out its credentials, and the error quotes its body: they are known first.
|
|
891
|
-
for (const [name, pointer] of Object.entries(spec.extract ?? {})) {
|
|
892
|
-
const header = /^header:(.+)$/i.exec(pointer);
|
|
893
|
-
let value: unknown;
|
|
894
|
-
try {
|
|
895
|
-
value = header ? headerOf(exchange.headers, header[1]) : at(JSON.parse(exchange.body ?? ""), pointer);
|
|
896
|
-
} catch {
|
|
897
|
-
value = undefined;
|
|
898
|
-
}
|
|
899
|
-
// An object holding one is a credential too, and its token is masked on its own.
|
|
900
|
-
const nested = nestedCredentials(value);
|
|
901
|
-
if (value !== undefined && (isCredentialCapture(name, pointer) || nested.length > 0)) {
|
|
902
|
-
const kept = typeof value === "string" ? value : JSON.stringify(value);
|
|
903
|
-
this.credentials.set(name, kept);
|
|
904
|
-
CREDENTIALS.set(name, kept);
|
|
905
|
-
}
|
|
906
|
-
for (const [path, secret] of nested) CREDENTIALS.set(`${name}${path}`, secret);
|
|
907
|
-
}
|
|
908
967
|
const problem = notYet(exchange);
|
|
909
968
|
if (problem !== undefined) throw new Error(mask(until === undefined ? `${method} ${url} ${problem}` : `${method} ${url} still ${problem} after ${spec.until!.timeoutMs ?? 30_000} ms of polling`));
|
|
910
969
|
for (const [name, pointer] of Object.entries(spec.extract ?? {})) {
|
|
@@ -917,7 +976,7 @@ export class Run {
|
|
|
917
976
|
}
|
|
918
977
|
let parsed: unknown;
|
|
919
978
|
try {
|
|
920
|
-
parsed =
|
|
979
|
+
parsed = parseExact(exchange.body ?? "");
|
|
921
980
|
} catch {
|
|
922
981
|
throw new Error(mask(`${method} ${url} returned no JSON body, so "${name}" (${pointer || "/"}) cannot be extracted${excerpt(exchange.body)}`));
|
|
923
982
|
}
|
|
@@ -944,8 +1003,10 @@ export class Run {
|
|
|
944
1003
|
const last = this.latest();
|
|
945
1004
|
const malformed = responseJsonProblem(checks);
|
|
946
1005
|
if (malformed) throw new Error(`Response json ${malformed}`);
|
|
947
|
-
|
|
948
|
-
|
|
1006
|
+
const problem = masked(() => {
|
|
1007
|
+
jsonChecksReadable(checks);
|
|
1008
|
+
return checkResponseJson(last.body, checks);
|
|
1009
|
+
});
|
|
949
1010
|
if (problem) throw new Error(mask(`${last.method} ${last.url}: ${problem}`));
|
|
950
1011
|
}
|
|
951
1012
|
|
|
@@ -960,7 +1021,7 @@ export class Run {
|
|
|
960
1021
|
} else if (expected.pattern !== undefined) {
|
|
961
1022
|
let re: RegExp;
|
|
962
1023
|
try {
|
|
963
|
-
re =
|
|
1024
|
+
re = patternRegex(expected.pattern);
|
|
964
1025
|
} catch {
|
|
965
1026
|
throw new Error(`expectHeader: /${expected.pattern}/ is not a regular expression`);
|
|
966
1027
|
}
|
|
@@ -1024,11 +1085,11 @@ export class Run {
|
|
|
1024
1085
|
|
|
1025
1086
|
// --- checks on elements ---------------------------------------------------
|
|
1026
1087
|
|
|
1027
|
-
/** The text the
|
|
1028
|
-
async function shown(target: Locator): Promise<string> {
|
|
1088
|
+
/** The text the match replay reads shows (theMatch), whitespace collapsed; "" when it is not visible. */
|
|
1089
|
+
async function shown(target: Locator, by: "text" | "runs" = "text"): Promise<string> {
|
|
1029
1090
|
try {
|
|
1030
|
-
const element = await target
|
|
1031
|
-
return element ? normalize((await read(element))
|
|
1091
|
+
const element = await (await theMatch(target)).elementHandle({ timeout: 1000 });
|
|
1092
|
+
return element ? normalize((await read(element))[by]) : "";
|
|
1032
1093
|
} catch {
|
|
1033
1094
|
return "";
|
|
1034
1095
|
}
|
|
@@ -1045,7 +1106,7 @@ const drawn = async (element: ElementHandle) => normalize((await read(element).c
|
|
|
1045
1106
|
const DRAWN_TEXT: string = /*DRAWN_TEXT*/ "" /*END*/;
|
|
1046
1107
|
|
|
1047
1108
|
/** The element's drawn text and its lines; nothing when it draws none. */
|
|
1048
|
-
async function read(element: ElementHandle): Promise<{ text: string; pieces: string[] }> {
|
|
1109
|
+
async function read(element: ElementHandle): Promise<{ text: string; pieces: string[]; runs: string }> {
|
|
1049
1110
|
return element.evaluate((el, src) => (0, eval)(`(${src})`)(el, true), DRAWN_TEXT);
|
|
1050
1111
|
}
|
|
1051
1112
|
|
|
@@ -1054,13 +1115,43 @@ async function lines(element: ElementHandle): Promise<string[]> {
|
|
|
1054
1115
|
return (await read(element)).pieces;
|
|
1055
1116
|
}
|
|
1056
1117
|
|
|
1118
|
+
// A copy of the runner's choice of the match a check reads (src/replay/index.ts), kept the same by a test.
|
|
1119
|
+
/*PICK_DISPLAYED*/
|
|
1120
|
+
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
|
|
1121
|
+
function pickDisplayed(els: any[], [limit, src]: [number, string]): number {
|
|
1122
|
+
const drawn = (0, eval)("(" + src + ")");
|
|
1123
|
+
const gone = (e: any): boolean => {
|
|
1124
|
+
for (let at = e; at; at = at.parentElement ?? at.getRootNode().host) {
|
|
1125
|
+
if (at.hidden || at.ownerDocument.defaultView.getComputedStyle(at).display === "none") return true;
|
|
1126
|
+
}
|
|
1127
|
+
return false;
|
|
1128
|
+
};
|
|
1129
|
+
const text = (e: any) => String(e.textContent ?? "").replace(/\s+/g, " ").trim();
|
|
1130
|
+
// An element the browser says is visible draws its text: the full walk only for one it does not (visibility:hidden, a closed <details>).
|
|
1131
|
+
const visible = (e: any) => e.checkVisibility?.({ visibilityProperty: true, contentVisibilityAuto: false }) === true;
|
|
1132
|
+
const undrawn = (e: any) => gone(e) || (text(e) !== "" && !visible(e) && !/\S/.test(drawn(e).text));
|
|
1133
|
+
if (els.length === 0 || !undrawn(els[0])) return 0;
|
|
1134
|
+
for (let i = 1; i < Math.min(els.length, limit); i++) {
|
|
1135
|
+
if (!undrawn(els[i])) return text(els[i]) === text(els[0]) ? i : 0;
|
|
1136
|
+
}
|
|
1137
|
+
return 0;
|
|
1138
|
+
}
|
|
1139
|
+
/*END*/
|
|
1140
|
+
|
|
1141
|
+
/** The match replay reads for a target: its first, or a displayed copy with the same text after a hidden first one (a mobile menu's). */
|
|
1142
|
+
async function theMatch(target: Locator): Promise<Locator> {
|
|
1143
|
+
const at = await target.evaluateAll(pickDisplayed, [20, DRAWN_TEXT] as [number, string]).catch(() => 0);
|
|
1144
|
+
return at > 0 ? target.nth(at) : target.first();
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1057
1147
|
const poll = (check: () => Promise<boolean>, message: string) =>
|
|
1058
1148
|
expect.poll(check, { message, timeout: SETTINGS.timeoutMs }).toBe(true);
|
|
1059
1149
|
|
|
1060
1150
|
/** The target shows `text` (a string is a plain substring; see bounded). */
|
|
1061
1151
|
export async function expectText(target: Locator, text: string | RegExp): Promise<void> {
|
|
1062
1152
|
const needle = said(typeof text === "string" ? normalize(text) : text, "the expected text");
|
|
1063
|
-
|
|
1153
|
+
// Read by runs, as replay reads it: a value never spans a block, a cell or a <br>.
|
|
1154
|
+
await poll(async () => contains(await shown(target, "runs"), needle), `target text to contain ${text}`);
|
|
1064
1155
|
}
|
|
1065
1156
|
|
|
1066
1157
|
/** The target's text matches the recorded pattern, in any case. */
|
|
@@ -1080,15 +1171,36 @@ export async function expectAttribute(target: Locator, name: string, source: str
|
|
|
1080
1171
|
const re = pattern(source);
|
|
1081
1172
|
const absentHolds = re.test("") && re.test("false") && !re.test("true");
|
|
1082
1173
|
await poll(async () => {
|
|
1083
|
-
const
|
|
1174
|
+
const element = await theMatch(target);
|
|
1175
|
+
// Shown, unless the attribute is what hides it, as replay checks it.
|
|
1176
|
+
if (!["hidden", "aria-hidden", "inert", "class", "style", "open", "data-state"].includes(name.toLowerCase()) && !(await element.isVisible())) return false;
|
|
1177
|
+
const found = await element.getAttribute(name, { timeout: 1000 }).catch(() => undefined);
|
|
1084
1178
|
if (found === undefined) return false;
|
|
1085
1179
|
return found === null ? absentHolds : re.test(found);
|
|
1086
1180
|
}, `attribute ${name} to match /${source}/`);
|
|
1087
1181
|
}
|
|
1088
1182
|
|
|
1183
|
+
/** The target's computed CSS `property` is `expected` as the browser computes it, or matches it. */
|
|
1184
|
+
export async function expectStyle(target: Locator, property: string, expected: string | RegExp): Promise<void> {
|
|
1185
|
+
said(expected, "the expected style");
|
|
1186
|
+
const wanted = typeof expected === "string" ? normalize(expected) : expected;
|
|
1187
|
+
await poll(async () => {
|
|
1188
|
+
const element = await theMatch(target);
|
|
1189
|
+
// Shown, unless the property is what hides it, as replay checks it.
|
|
1190
|
+
if (!["display", "visibility", "opacity", "content-visibility", "height", "max-height", "width", "max-width", "transform", "clip-path", "clip"].includes(property.toLowerCase()) && !(await element.isVisible())) return false;
|
|
1191
|
+
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);
|
|
1192
|
+
if (found === undefined) return false;
|
|
1193
|
+
return typeof wanted === "string" ? normalize(found) === wanted : wanted.test(normalize(found));
|
|
1194
|
+
}, `${property} to be ${expected}`);
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1089
1197
|
/** Every match of every locator the recording names is hidden. */
|
|
1090
1198
|
export async function expectNotVisible(...targets: Locator[]): Promise<void> {
|
|
1091
|
-
|
|
1199
|
+
// All hidden at the same look, as replay checks them: one gone, then another, while the first came back, is not a pass.
|
|
1200
|
+
await poll(async () => {
|
|
1201
|
+
for (const target of targets) if ((await target.filter({ visible: true }).count()) > 0) return false;
|
|
1202
|
+
return true;
|
|
1203
|
+
}, `every match of every recorded locator to be hidden (${targets.length} locator(s))`);
|
|
1092
1204
|
}
|
|
1093
1205
|
|
|
1094
1206
|
/** Each value is shown in the container, as a whole line of its text. */
|
|
@@ -1104,19 +1216,155 @@ export async function expectEach(container: Locator, values: string[]): Promise<
|
|
|
1104
1216
|
}
|
|
1105
1217
|
|
|
1106
1218
|
async function shownLines(target: Locator): Promise<string[]> {
|
|
1107
|
-
const element = await target
|
|
1219
|
+
const element = await (await theMatch(target)).elementHandle({ timeout: 1000 }).catch(() => null);
|
|
1108
1220
|
return element ? lines(element).catch(() => []) : [];
|
|
1109
1221
|
}
|
|
1110
1222
|
|
|
1111
|
-
/**
|
|
1112
|
-
|
|
1223
|
+
/** As replay's urlContains: a path outside the query unless the text names one, and never inside a longer word or number. */
|
|
1224
|
+
function urlContains(url: string, expected: string | RegExp): boolean {
|
|
1225
|
+
const text = typeof expected === "string" ? expected : expected.source;
|
|
1226
|
+
// Cut on the URL as sent: decoded, a "%23" in a query value reads as a fragment; a query value that is a path is no part of the page's own.
|
|
1227
|
+
const asked = /[?=&]/.test(text) ? url : text.includes("/") ? url.replace(/\?[^#]*/, "").replace(/([?&#][^=&#/]*=)[^&#]*(?:\/|%2F)[^&#]*/gi, "$1") : url.replace(/([?&#][^=&#/]*=)[^&#]*(?:\/|%2F)[^&#]*/gi, "$1");
|
|
1228
|
+
// A letter or digit written percent-encoded is part of the word beside it, an encoded "?", "&", "=" or "#" is not; beside a number, no decimal part.
|
|
1229
|
+
const encoded = "%(?!3[Ff]|26|3[Dd]|23)[0-9A-Fa-f]{2}";
|
|
1230
|
+
const before = /^[\p{L}\p{N}]/u.test(text) ? String.raw`(?<![\p{L}\p{N}]|${encoded}${/^\p{N}/u.test(text) ? String.raw`|\p{N}[.,]` : ""})` : "";
|
|
1231
|
+
const after = /[\p{L}\p{N}]$/u.test(text) ? String.raw`(?![\p{L}\p{N}]|${encoded}${/\p{N}$/u.test(text) ? String.raw`|[.,]\p{N}` : ""})` : "";
|
|
1232
|
+
if (typeof expected !== "string") return [asked, decode(asked), decode(asked.replace(/\+/g, "%20"))].some((u) => expected.test(u));
|
|
1233
|
+
const re = new RegExp(`${before}${expected.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}${after}`, "gu");
|
|
1234
|
+
// A text naming a query starts at the URL's own, as replay reads it.
|
|
1235
|
+
const mark = expected.indexOf("?");
|
|
1236
|
+
const hash = expected.indexOf("#");
|
|
1237
|
+
const atQuery = (u: string, at: number) => {
|
|
1238
|
+
const section = u.lastIndexOf("#", at) + 1;
|
|
1239
|
+
const query = u.indexOf("?", section);
|
|
1240
|
+
if (mark >= 0) return query === at + mark;
|
|
1241
|
+
// Its "#" is the URL's own fragment: "#tab=settings" and "/app#tab=settings" name the fragment's fields.
|
|
1242
|
+
if (hash >= 0) return u.indexOf("#") === at + hash;
|
|
1243
|
+
if (!/=/.test(expected) || /^[?&]/.test(expected)) return true;
|
|
1244
|
+
// A field follows a query's "?", else a fragment's "#", or an "&" after either.
|
|
1245
|
+
const start = query >= 0 && query < at ? query : section > 0 ? section - 1 : query;
|
|
1246
|
+
return start >= 0 && start < at && (u[at - 1] === "&" || at - 1 === start) && u.slice(start + 1, at).split("&").every((field) => !/[?#]/.test(field));
|
|
1247
|
+
};
|
|
1248
|
+
// Each part decoded on its own: a "?", "&", "=" or "#" a value encodes stays encoded.
|
|
1249
|
+
const parts = (u: string) => u.replace(/[^?&=#]+/g, (part) => decode(part).replace(/[?&=#]/g, encodeURIComponent));
|
|
1250
|
+
return [asked, parts(asked), parts(asked.replace(/\+/g, "%20"))].some((u) => [...u.matchAll(re)].some((m) => atQuery(u, m.index)));
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/** The URL contains `expected` (raw, decoded, or with + read as a space); with "excludes", it does not; with "path", its path is exactly `expected`. */
|
|
1254
|
+
export async function expectUrl(page: Page, expected: string | RegExp, match?: "excludes" | "path"): Promise<void> {
|
|
1113
1255
|
said(expected, "the expected URL");
|
|
1114
1256
|
await poll(async () => {
|
|
1115
1257
|
const url = page.url();
|
|
1116
|
-
|
|
1117
|
-
|
|
1258
|
+
if (match === "path") {
|
|
1259
|
+
const path = new URL(url).pathname;
|
|
1260
|
+
return [path, decode(path)].some((p) => (typeof expected === "string" ? p === expected : expected.test(p)));
|
|
1261
|
+
}
|
|
1262
|
+
const spellings = [url, decode(url), decode(url.replace(/\+/g, "%20"))];
|
|
1263
|
+
return match === "excludes" ? !spellings.some((u) => contains(u, expected)) : urlContains(url, expected);
|
|
1264
|
+
}, match === "excludes" ? `URL not containing ${expected} on the active page` : match === "path" ? `URL path ${expected} on the active page` : `URL containing ${expected} on the active page`);
|
|
1118
1265
|
}
|
|
1119
1266
|
|
|
1267
|
+
// --- amounts ---------------------------------------------------------------
|
|
1268
|
+
|
|
1269
|
+
// A copy of the runner's amount reading (src/util/amount.ts), so a differs check
|
|
1270
|
+
// compares "$10" and "$10.00" as replay does: as one amount.
|
|
1271
|
+
/*AMOUNT*/
|
|
1272
|
+
const currencies = new Set(Intl.supportedValuesOf("currency"));
|
|
1273
|
+
/** Currency notation without a symbol of its own in Unicode: Rs 500, 5,00 zł, 5.00 Kč, Ft 500. */
|
|
1274
|
+
const LOCAL_CURRENCIES = new Set(["kr", "rs", "zł", "kč", "ft", "lei", "lv", "лв", "din", "ден", "дин"]);
|
|
1275
|
+
// An ISO code in capitals; in lower case only beside decimals ("(usd 5.00)"):
|
|
1276
|
+
// "(2 pen)" and "(3 all)" are counts, not Peruvian soles or Albanian lek.
|
|
1277
|
+
const isCurrency = (s: string) => /\p{Sc}/u.test(s) || currencies.has(s) || LOCAL_CURRENCIES.has(s.toLowerCase().replace(/\.$/, ""));
|
|
1278
|
+
|
|
1279
|
+
/** Digits grouped by a space, a no-break space or an apostrophe, as one number ("1 234", "1'234"). */
|
|
1280
|
+
const joinGroups = (text: string) => text.replace(/(\d)[\s\u00a0\u202f'\u2019](?=\d{3}(?!\d))/g, "$1");
|
|
1281
|
+
|
|
1282
|
+
export function parseAmount(text: string): number | undefined {
|
|
1283
|
+
// Digits grouped by a space, a no-break space or an apostrophe are one number.
|
|
1284
|
+
const joined = joinGroups(text);
|
|
1285
|
+
const runs = [...joined.matchAll(/[-\u2212\u2013]?\d(?:[\d.,]*\d)?/g)];
|
|
1286
|
+
if (runs.length !== 1) return undefined;
|
|
1287
|
+
const [found] = runs;
|
|
1288
|
+
const before = joined.slice(0, found.index);
|
|
1289
|
+
const after = joined.slice(found.index + found[0].length);
|
|
1290
|
+
// A decimal with no whole part ("$.50", "€,99"): the separator before it is
|
|
1291
|
+
// the decimal point, and the sign is judged by what comes before that ("-.50", "($.50)").
|
|
1292
|
+
const bare = /[.,]$/.test(before) && !/\d[.,]$/.test(before) && /^\d+$/.test(found[0]);
|
|
1293
|
+
const lead = bare ? before.slice(0, -1) : before;
|
|
1294
|
+
const opening = /\(\s*([^\d\s.,()]{0,4})\s*$/.exec(lead);
|
|
1295
|
+
const closing = /^\s*([^\d\s.,()]{0,4})\s*\)/.exec(after);
|
|
1296
|
+
const labels = [opening?.[1], closing?.[1]].filter((s): s is string => !!s);
|
|
1297
|
+
// An unknown label keeps a decimal amount accounting only when it holds no letter: a unit (Weight (1.5 kg)) or a word (Guests (2.5 pax)) does not.
|
|
1298
|
+
const separated = /[.,]/.test(found[0]);
|
|
1299
|
+
const accounting = opening && closing && (labels.length === 0 ? separated : labels.every((l) => isCurrency(l) || (separated && currencies.has(l.toUpperCase()))) || (separated && !labels.some((l) => /\p{L}/u.test(l))));
|
|
1300
|
+
// A dash glued to a letter or digit before it is a hyphen ("ID-123"),
|
|
1301
|
+
// never a sign; after a currency it is the sign ("CHF-5.00", as de-CH writes -5).
|
|
1302
|
+
const glued = /([\p{L}\p{N}]+)$/u.exec(before)?.[1];
|
|
1303
|
+
const hyphen = glued !== undefined && !(/^\p{L}+$/u.test(glued) && (isCurrency(glued) || currencies.has(glued.toUpperCase())));
|
|
1304
|
+
const negative =
|
|
1305
|
+
(/^[-\u2212\u2013]/.test(found[0]) && !hyphen) ||
|
|
1306
|
+
// A minus spaced off at the very start, before the currency or the number ("- €5.00", "- 5,00 €").
|
|
1307
|
+
/^\s*[-\u2212\u2013]\s*(?:[^\d\s.,()\-\u2212\u2013]{1,4}\s*)?$/u.test(lead) ||
|
|
1308
|
+
(bare && /[-\u2212\u2013]$/.test(lead)) ||
|
|
1309
|
+
// Attached to the currency, not spaced off like the dash in "Breakfast - $5.00".
|
|
1310
|
+
/(?:^|[\s(:])[-\u2212\u2013][^\d\s.,()\-\u2212\u2013]{1,4}\s?$/.test(lead) ||
|
|
1311
|
+
/^[-\u2212\u2013](?!\d)/.test(after) ||
|
|
1312
|
+
// Parentheses denote a negative amount only with currency notation or an unlabelled decimal.
|
|
1313
|
+
accounting;
|
|
1314
|
+
|
|
1315
|
+
const digits = bare ? `0${before.slice(-1)}${found[0]}` : found[0].replace(/^[-\u2212\u2013]/, "");
|
|
1316
|
+
const last = Math.max(digits.lastIndexOf("."), digits.lastIndexOf(","));
|
|
1317
|
+
const head = last < 0 ? digits : digits.slice(0, last);
|
|
1318
|
+
const tail = last < 0 ? "" : digits.slice(last + 1);
|
|
1319
|
+
const decimal = last >= 0 && (tail.length !== 3 || /^0?$/.test(head) || (head.includes(digits[last] === "." ? "," : ".")));
|
|
1320
|
+
const whole = decimal ? head : digits;
|
|
1321
|
+
// Grouping: one separator, every group after the first three digits long, not the decimal one.
|
|
1322
|
+
const groups = whole.split(/[.,]/);
|
|
1323
|
+
const grouping = new Set(whole.match(/[.,]/g) ?? []);
|
|
1324
|
+
if (grouping.size > 1 || (decimal && grouping.has(digits[last])) || groups[0] === "" || groups.slice(1).some((g) => g.length !== 3)) return undefined;
|
|
1325
|
+
const amount = Number(`${negative ? "-" : ""}${groups.join("")}${decimal ? `.${tail}` : ""}`);
|
|
1326
|
+
return Number.isFinite(amount) ? amount : undefined;
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
/** What an amount's text says besides its number ("NOK", "kr", "Book now for NOK"), lower case, sign and parentheses left out. */
|
|
1330
|
+
const amountUnit = (text: string): string =>
|
|
1331
|
+
joinGroups(text).replace(/[-\u2212\u2013]?\d(?:[\d.,]*\d)?/, " ").replace(/[()\-\u2212\u2013]/g, " ").replace(/\s+/g, " ").trim().toLowerCase();
|
|
1332
|
+
|
|
1333
|
+
/**
|
|
1334
|
+
* Whether two displayed values differ, for an expectDiffers check. Two
|
|
1335
|
+
* amounts compare as numbers ("NOK 1 295" and "NOK 1,295.00" are equal), and
|
|
1336
|
+
* only when they say the same besides the number: "SEK 1,295" and "NOK 1,347"
|
|
1337
|
+
* differ by currency alone, and "Book now for NOK 1,295" against "NOK 1,295"
|
|
1338
|
+
* by its label, so either is a problem with the recording, not a pass.
|
|
1339
|
+
* Anything else compares as text.
|
|
1340
|
+
*/
|
|
1341
|
+
export function valuesDiffer(left: string, right: string): { differ: boolean } | { problem: string } {
|
|
1342
|
+
// A bare number in parentheses is a negative one in a ledger, as "-5" is: "(5)" and "-5" are equal.
|
|
1343
|
+
const signed = (text: string, n: number | undefined) => (n !== undefined && /^\s*\(\s*[\d.,\s\u00a0]+\)\s*$/.test(text) ? -Math.abs(n) : n);
|
|
1344
|
+
const [a, b] = [signed(left, parseAmount(left)), signed(right, parseAmount(right))];
|
|
1345
|
+
if (a === undefined || b === undefined) return { differ: left !== right };
|
|
1346
|
+
const [ua, ub] = [amountUnit(left), amountUnit(right)];
|
|
1347
|
+
if (ua !== ub) {
|
|
1348
|
+
const currency = (unit: string) => unit !== "" && (isCurrency(unit) || isCurrency(unit.toUpperCase()));
|
|
1349
|
+
const words = (unit: string) => unit.split(/\s+/);
|
|
1350
|
+
// Two currencies, or a price against a label holding that price's currency ("Book now for NOK 1,295"):
|
|
1351
|
+
// a change no amount explains. Any other two (references, counts: "ABC-123", "1 night") compare as text.
|
|
1352
|
+
if (currency(ua) && currency(ub)) {
|
|
1353
|
+
return { problem: `"${left}" and "${right}" are amounts in different currencies, so they differ whatever the amount does. Capture both in one currency.` };
|
|
1354
|
+
}
|
|
1355
|
+
if ((currency(ua) && words(ub).includes(ua)) || (currency(ub) && words(ua).includes(ub))) {
|
|
1356
|
+
return { problem: `"${left}" and "${right}" are not the same kind of value (one says more than the amount), so they differ whatever the amount does. Capture both from the same kind of element: the amount alone.` };
|
|
1357
|
+
}
|
|
1358
|
+
if (ua === "" || ub === "") return { differ: !sameAmount(a, b) };
|
|
1359
|
+
return { differ: left !== right };
|
|
1360
|
+
}
|
|
1361
|
+
return { differ: !sameAmount(a, b) };
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
/** Equal to the cent, so 0.1 + 0.2 is 0.3. */
|
|
1365
|
+
export const sameAmount = (a: number, b: number): boolean => Math.abs(a - b) < 0.005;
|
|
1366
|
+
/*END*/
|
|
1367
|
+
|
|
1120
1368
|
// --- JSON field checks ----------------------------------------------------
|
|
1121
1369
|
|
|
1122
1370
|
/** A JSON field check, as a recording holds one (ResponseJsonCheck in saffron-ai). */
|
|
@@ -1230,8 +1478,53 @@ function jsonPattern(check: ResponseJsonCheck): RegExp {
|
|
|
1230
1478
|
}
|
|
1231
1479
|
}
|
|
1232
1480
|
|
|
1233
|
-
|
|
1234
|
-
|
|
1481
|
+
/**
|
|
1482
|
+
* A number JavaScript cannot hold as written, as a check reads it (an int64
|
|
1483
|
+
* id, 9007199254740991.1, 1e400): a number, written exactly as the API sent
|
|
1484
|
+
* it, so a pattern or a string check never takes it for text and a bound
|
|
1485
|
+
* compares it exactly (found in review). Its digits are no field a JSON
|
|
1486
|
+
* Pointer reaches.
|
|
1487
|
+
*/
|
|
1488
|
+
class ExactNumber {
|
|
1489
|
+
readonly #written: string;
|
|
1490
|
+
constructor(written: string) { this.#written = written; }
|
|
1491
|
+
toString(): string { return this.#written; }
|
|
1492
|
+
// As a capture keeps it (parseExact): its digits, so a differs check sees the same object as the same (found in review).
|
|
1493
|
+
toJSON(): string { return this.#written; }
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
/** A decimal as written (`-12.50`, `9.007199254740993e15`), exactly: its sign, its digits and where its point falls before them (0.125 x 10^2). */
|
|
1497
|
+
const decimal = (text: string): { sign: number; digits: string; point: number } | undefined => {
|
|
1498
|
+
const m = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(text.trim());
|
|
1499
|
+
if (!m) return undefined;
|
|
1500
|
+
const all = `${m[2]}${m[3] ?? ""}`;
|
|
1501
|
+
const leading = all.length - all.replace(/^0+/, "").length;
|
|
1502
|
+
const digits = all.slice(leading).replace(/0+$/, "");
|
|
1503
|
+
return { sign: digits === "" ? 0 : m[1] === "-" ? -1 : 1, digits, point: m[2].length - leading + Number(m[4] ?? 0) };
|
|
1504
|
+
};
|
|
1505
|
+
|
|
1506
|
+
/** -1, 0 or 1 as one decimal is below, at or above another, by sign, magnitude and digits: no exponent is ever expanded. */
|
|
1507
|
+
const compareDecimal = (a: NonNullable<ReturnType<typeof decimal>>, b: NonNullable<ReturnType<typeof decimal>>): number => {
|
|
1508
|
+
if (a.sign !== b.sign) return a.sign < b.sign ? -1 : 1;
|
|
1509
|
+
const width = Math.max(a.digits.length, b.digits.length);
|
|
1510
|
+
const [x, y] = [a.digits.padEnd(width, "0"), b.digits.padEnd(width, "0")];
|
|
1511
|
+
const magnitude = a.sign === 0 ? 0 : a.point !== b.point ? (a.point < b.point ? -1 : 1) : x < y ? -1 : x > y ? 1 : 0;
|
|
1512
|
+
return a.sign * magnitude;
|
|
1513
|
+
};
|
|
1514
|
+
|
|
1515
|
+
/** Whether a number parsed is the number written: 9007199254740991.1 is read as 9007199254740991, and 1e400 as Infinity. */
|
|
1516
|
+
const heldAsWritten = (written: string, value: number): boolean => {
|
|
1517
|
+
const [a, b] = [decimal(written), decimal(String(value))];
|
|
1518
|
+
return a !== undefined && b !== undefined && compareDecimal(a, b) === 0;
|
|
1519
|
+
};
|
|
1520
|
+
|
|
1521
|
+
/** JSON as a check reads it: a number JavaScript cannot hold as written, or any integer beyond its safe range (an id an equals check reads by its digits), as an ExactNumber. */
|
|
1522
|
+
const parseChecked = (text: string): unknown =>
|
|
1523
|
+
JSON.parse(text, (_key, value: unknown, context?: { source?: string }) =>
|
|
1524
|
+
typeof value === "number" && context?.source !== undefined && (Math.abs(value) > Number.MAX_SAFE_INTEGER || !heldAsWritten(context.source, value)) ? new ExactNumber(context.source) : value);
|
|
1525
|
+
|
|
1526
|
+
const kind = (value: unknown) => value === null ? "null" : Array.isArray(value) ? "array" : value instanceof ExactNumber ? "number" : typeof value;
|
|
1527
|
+
const describe = (value: unknown) => `${kind(value)}${value instanceof ExactNumber ? ` ${value}` : value === null || typeof value !== "object" ? ` ${JSON.stringify(value)}` : ""}`;
|
|
1235
1528
|
|
|
1236
1529
|
/** The value at a JSON Pointer: own properties and array indexes only, undefined when missing. */
|
|
1237
1530
|
function at(json: unknown, path: string): unknown {
|
|
@@ -1283,7 +1576,11 @@ function checkValue(json: unknown, checks: ResponseJsonCheck[], prefix = ""): st
|
|
|
1283
1576
|
const other = jsonExpected(check, check.differs);
|
|
1284
1577
|
if (value === undefined) return `${field}: expected a value other than ${describe(other)}, got missing`;
|
|
1285
1578
|
// Untyped, the text is compared as written: a number 5 is the same as "5" (a captured id is kept as text).
|
|
1286
|
-
|
|
1579
|
+
// A list, an object or null is compared as its JSON text: [{"sku":"a"}] is the same as itself written out.
|
|
1580
|
+
// Keys in any order and any spacing: {"b":2,"a":1} is the same as {"a": 1, "b": 2}.
|
|
1581
|
+
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));
|
|
1582
|
+
const written = (text: unknown) => { try { return canonical(parseChecked(String(text))); } catch { return String(text); } };
|
|
1583
|
+
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`;
|
|
1287
1584
|
} else if (check.pattern !== undefined) {
|
|
1288
1585
|
const re = jsonPattern(check);
|
|
1289
1586
|
if (typeof value !== "string") return `${field}: expected text matching /${check.pattern}/, got ${got}`;
|
|
@@ -1291,30 +1588,58 @@ function checkValue(json: unknown, checks: ResponseJsonCheck[], prefix = ""): st
|
|
|
1291
1588
|
} else if (check.min !== undefined || check.max !== undefined) {
|
|
1292
1589
|
const min = check.min === undefined ? undefined : jsonNumber(check, "min");
|
|
1293
1590
|
const max = check.max === undefined ? undefined : jsonNumber(check, "max");
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1591
|
+
// Each bound as written when it reads exactly: "9007199254740993" is no 9007199254740992.
|
|
1592
|
+
const shown = (written: string, read: number) => (decimal(written) ? written.trim() : read);
|
|
1593
|
+
const bounds = [min !== undefined ? `at least ${shown(check.min!, min)}` : "", max !== undefined ? `at most ${shown(check.max!, max)}` : ""].filter(Boolean).join(" and ");
|
|
1594
|
+
const number = value instanceof ExactNumber ? Number(String(value)) : value;
|
|
1595
|
+
if (typeof number !== "number") return `${field}: expected a number ${bounds}, got ${got}`;
|
|
1596
|
+
// Compared exactly, the value as the API wrote it and the bound as the check does, never rounded onto each
|
|
1597
|
+
// other beyond JavaScript's precision (found in review); a bound in another notation (0x10) as a number.
|
|
1598
|
+
const exact = decimal(String(value));
|
|
1599
|
+
const beyond = (written: string, read: number, side: number) => {
|
|
1600
|
+
const bound = decimal(written);
|
|
1601
|
+
return exact && bound ? compareDecimal(exact, bound) === side : side < 0 ? number < read : number > read;
|
|
1602
|
+
};
|
|
1603
|
+
const under = min !== undefined && beyond(check.min!, min, -1);
|
|
1604
|
+
const over = max !== undefined && beyond(check.max!, max, 1);
|
|
1605
|
+
if (under || over) return `${field}: expected a number ${bounds}, got ${value}`;
|
|
1297
1606
|
} else {
|
|
1298
1607
|
const expected = jsonExpected(check);
|
|
1299
|
-
|
|
1608
|
+
// Too large to compare as a number, it is checked as a string of its digits (jsonExpected says so).
|
|
1609
|
+
const same = value instanceof ExactNumber ? (check.type === undefined || check.type === "string") && String(value) === expected : value === expected;
|
|
1610
|
+
if (!same) return `${field}: expected ${describe(expected)}, got ${got}`;
|
|
1300
1611
|
}
|
|
1301
1612
|
}
|
|
1302
1613
|
return undefined;
|
|
1303
1614
|
}
|
|
1304
1615
|
|
|
1616
|
+
/**
|
|
1617
|
+
* JSON with an integer beyond JavaScript's precision (a snowflake or int64
|
|
1618
|
+
* id) kept as the digits the API sent, never rounded into another id, as a
|
|
1619
|
+
* capture keeps it: a differs check then sees the same id (found in review).
|
|
1620
|
+
*/
|
|
1621
|
+
export function parseExact(text: string): unknown {
|
|
1622
|
+
return JSON.parse(text, (_key, value: unknown, context?: { source?: string }) =>
|
|
1623
|
+
typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value) && context?.source !== undefined ? context.source : value);
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1305
1626
|
/** A missing property is different from a property whose value is null. */
|
|
1306
1627
|
export function checkResponseJson(body: string | undefined, checks: ResponseJsonCheck[]): string | undefined {
|
|
1307
1628
|
if (body === undefined) return "response body is pending, unreadable or not a supported text content type";
|
|
1308
1629
|
let json: unknown;
|
|
1309
|
-
try { json =
|
|
1630
|
+
try { json = parseChecked(body); } catch { return "response body is not valid JSON"; }
|
|
1310
1631
|
return checkValue(json, checks);
|
|
1311
1632
|
}
|
|
1312
1633
|
|
|
1313
1634
|
/** Unicode boundaries need unicode mode; preserve legacy flags on patterns without them. */
|
|
1635
|
+
// `\x27` as the secret masker spells it; `\u{...}` past one byte.
|
|
1636
|
+
const hexEscape = (code: number) => (code < 0x100 ? `\\x${code.toString(16).padStart(2, "0")}` : `\\u{${code.toString(16)}}`);
|
|
1637
|
+
|
|
1314
1638
|
export function patternRegex(source: string, flags = ""): RegExp {
|
|
1315
1639
|
if (/[uv]/.test(flags) || source.includes(String.raw`[\p{L}\p{N}\p{M}]`)) {
|
|
1316
|
-
//
|
|
1317
|
-
|
|
1640
|
+
// Unicode mode allows only syntax characters and `/` escaped: Playwright's
|
|
1641
|
+
// escaped quotes and chain separators, and an agent's harmless `\#` or `\:`, become code point escapes.
|
|
1642
|
+
source = source.replace(/\\[\s\S]|[\s\S]/gu, part => /^\\[^\p{L}\p{N}^$\\.*+?()[\]{}|/]$/u.test(part) ? hexEscape(part.codePointAt(1)!) : part);
|
|
1318
1643
|
if (!/[uv]/.test(flags)) flags += "u";
|
|
1319
1644
|
}
|
|
1320
1645
|
return new RegExp(source, flags);
|