@unframework.dev/testing 0.0.0-stage → 0.0.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.
Files changed (131) hide show
  1. package/README.md +511 -2
  2. package/dist/browser/axe.js +34 -0
  3. package/dist/browser/behaviour.js +59 -0
  4. package/dist/browser/capabilities.js +58 -0
  5. package/dist/browser/clock.d.ts +17 -0
  6. package/dist/browser/clock.js +69 -0
  7. package/dist/browser/console.d.ts +27 -0
  8. package/dist/browser/console.js +142 -0
  9. package/dist/browser/determinism.js +108 -0
  10. package/dist/browser/element-timeout.js +28 -0
  11. package/dist/browser/events.js +68 -0
  12. package/dist/browser/geometry.js +135 -0
  13. package/dist/browser/keys.js +62 -0
  14. package/dist/browser/matchers.d.ts +39 -0
  15. package/dist/browser/matchers.js +78 -0
  16. package/dist/browser/navigation.js +38 -0
  17. package/dist/browser/parity.d.ts +10 -0
  18. package/dist/browser/parity.js +93 -0
  19. package/dist/browser/spec.d.ts +25 -0
  20. package/dist/browser/spec.js +38 -0
  21. package/dist/browser/target.d.ts +16 -0
  22. package/dist/browser/target.js +27 -0
  23. package/dist/browser/text-runs.js +68 -0
  24. package/dist/browser/thrown.js +71 -0
  25. package/dist/browser/trace.d.ts +21 -0
  26. package/dist/browser/trace.js +73 -0
  27. package/dist/browser/user.d.ts +45 -0
  28. package/dist/browser/user.js +184 -0
  29. package/dist/browser/view.d.ts +114 -0
  30. package/dist/browser/view.js +282 -0
  31. package/dist/browser/visual.d.ts +20 -0
  32. package/dist/browser/visual.js +36 -0
  33. package/dist/cli.d.ts +23 -0
  34. package/dist/cli.js +90 -0
  35. package/dist/commands.d.ts +107 -0
  36. package/dist/config/broadcast.js +29 -0
  37. package/dist/config/cases.d.ts +28 -0
  38. package/dist/config/cases.js +94 -0
  39. package/dist/config/index.d.ts +81 -0
  40. package/dist/config/index.js +275 -0
  41. package/dist/diff.d.ts +14 -0
  42. package/dist/diff.js +92 -0
  43. package/dist/dom/serialize.js +236 -0
  44. package/dist/errors.d.ts +13 -0
  45. package/dist/errors.js +38 -0
  46. package/dist/harness.d.ts +184 -0
  47. package/dist/harness.js +53 -0
  48. package/dist/index.d.ts +16 -0
  49. package/dist/index.js +12 -0
  50. package/dist/internal.d.ts +8 -0
  51. package/dist/internal.js +6 -0
  52. package/dist/layers.d.ts +183 -0
  53. package/dist/layers.js +241 -0
  54. package/dist/node/browser.d.ts +33 -0
  55. package/dist/node/browser.js +64 -0
  56. package/dist/node/commands.d.ts +137 -0
  57. package/dist/node/commands.js +139 -0
  58. package/dist/node/context.d.ts +28 -0
  59. package/dist/node/context.js +55 -0
  60. package/dist/node/events.d.ts +25 -0
  61. package/dist/node/events.js +50 -0
  62. package/dist/node/finished.d.ts +12 -0
  63. package/dist/node/finished.js +28 -0
  64. package/dist/node/index.d.ts +21 -0
  65. package/dist/node/index.js +20 -0
  66. package/dist/node/matrix.d.ts +219 -0
  67. package/dist/node/matrix.js +309 -0
  68. package/dist/node/mode.d.ts +101 -0
  69. package/dist/node/mode.js +201 -0
  70. package/dist/node/names.d.ts +4 -0
  71. package/dist/node/names.js +5 -0
  72. package/dist/node/policy.d.ts +44 -0
  73. package/dist/node/policy.js +140 -0
  74. package/dist/node/reporter.d.ts +101 -0
  75. package/dist/node/reporter.js +251 -0
  76. package/dist/node/summary.d.ts +99 -0
  77. package/dist/node/summary.js +352 -0
  78. package/dist/node/thrown.js +78 -0
  79. package/dist/node/viewport.d.ts +7 -0
  80. package/dist/node/viewport.js +8 -0
  81. package/dist/node/visual.d.ts +85 -0
  82. package/dist/node/visual.js +370 -0
  83. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/protocol.d.ts +23930 -0
  84. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/structs.d.ts +22 -0
  85. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/types.d.ts +22221 -0
  86. package/dist/normalize/display.js +309 -0
  87. package/dist/normalize/index.d.ts +34 -0
  88. package/dist/normalize/index.js +38 -0
  89. package/dist/normalize/pipeline.d.ts +19 -0
  90. package/dist/normalize/pipeline.js +45 -0
  91. package/dist/normalize/print.js +103 -0
  92. package/dist/normalize/rules/angular-hosts.js +53 -0
  93. package/dist/normalize/rules/aria-hosts.js +48 -0
  94. package/dist/normalize/rules/comments.js +16 -0
  95. package/dist/normalize/rules/control-values.js +65 -0
  96. package/dist/normalize/rules/engine-aliases.js +34 -0
  97. package/dist/normalize/rules/framework-attributes.js +85 -0
  98. package/dist/normalize/rules/generated-ids.js +64 -0
  99. package/dist/normalize/rules/ordering.js +39 -0
  100. package/dist/normalize/rules/qwik-styles.js +21 -0
  101. package/dist/normalize/rules/qwik-templates.js +20 -0
  102. package/dist/normalize/rules/values.js +125 -0
  103. package/dist/normalize/rules/whitespace.js +381 -0
  104. package/dist/normalize/style.js +121 -0
  105. package/dist/normalize/targets.d.ts +8 -0
  106. package/dist/normalize/targets.js +17 -0
  107. package/dist/normalize/tree.d.ts +1 -0
  108. package/dist/normalize/tree.js +151 -0
  109. package/dist/setup.d.ts +1 -0
  110. package/dist/setup.js +149 -0
  111. package/dist/ssr/index.d.ts +10 -0
  112. package/dist/ssr/index.js +103 -0
  113. package/dist/ssr/spec.d.ts +1 -0
  114. package/dist/ssr/spec.js +7 -0
  115. package/dist/targets/angular.d.ts +1 -0
  116. package/dist/targets/angular.js +5 -0
  117. package/dist/targets/astro.d.ts +1 -0
  118. package/dist/targets/astro.js +5 -0
  119. package/dist/targets/qwik.d.ts +1 -0
  120. package/dist/targets/qwik.js +5 -0
  121. package/dist/targets/react.d.ts +1 -0
  122. package/dist/targets/react.js +5 -0
  123. package/dist/targets/solid.d.ts +1 -0
  124. package/dist/targets/solid.js +5 -0
  125. package/dist/targets/svelte.d.ts +1 -0
  126. package/dist/targets/svelte.js +5 -0
  127. package/dist/targets/vue.d.ts +1 -0
  128. package/dist/targets/vue.js +5 -0
  129. package/dist/visual-types.d.ts +92 -0
  130. package/dist/visual-types.js +24 -0
  131. package/package.json +135 -3
@@ -0,0 +1,58 @@
1
+ import { currentTarget } from "./target.js";
2
+ import { noOutputSkip, requiresSkip } from "../layers.js";
3
+ import { inject } from "vitest";
4
+ //#region src/browser/capabilities.ts
5
+ /** The target's capability matrix, as the project provides it. */
6
+ function capabilityCells() {
7
+ const cells = inject("ufCapabilities");
8
+ if (!cells) throw new Error("No capabilities are provided: the browser project must set test.provide.ufCapabilities to its target's capability matrix.");
9
+ return cells;
10
+ }
11
+ /** The capability's cell; throws for a name the matrix does not have. */
12
+ function capabilityCell(name, cells = capabilityCells()) {
13
+ const cell = Object.hasOwn(cells, name) ? cells[name] : void 0;
14
+ if (!cell) throw new Error(`"${name}" is not a capability: the capabilities are ${Object.keys(cells).join(", ")}.`);
15
+ return cell;
16
+ }
17
+ /**
18
+ * Why a test that requires these capabilities cannot run on the project's target: the skip
19
+ * reason of the first one whose cell is unsupported (`requires interactivity: …`), or nothing.
20
+ */
21
+ function requiredSkip(requires, cells = capabilityCells()) {
22
+ for (const name of requires) {
23
+ const cell = capabilityCell(name, cells);
24
+ if (cell.support === "unsupported") return requiresSkip(name, cell.reason);
25
+ }
26
+ }
27
+ /**
28
+ * Why a test of a case its target has no output for is skipped there, or nothing: the case
29
+ * expects an error for the target (the one it declares for a capability it lacks), so there is
30
+ * no component to render, and the project gives its spec a stand-in that loads. Each test is
31
+ * skipped with `no output: <the errors>`, a mechanical cause the summary excuses on that target
32
+ * alone, whatever the test requires.
33
+ */
34
+ function noOutputReason(caseId, cases = inject("ufNoOutput")) {
35
+ const errors = cases && Object.hasOwn(cases, caseId) ? cases[caseId] : void 0;
36
+ return errors === void 0 ? void 0 : noOutputSkip(errors);
37
+ }
38
+ /**
39
+ * Why a test of a case its target cannot compile yet runs against a stand-in, or nothing: the
40
+ * case's L3 is quarantined on the target, whose browser build type-checks its output, so the
41
+ * project gives its spec a stand-in that loads (ADR-0068). The test is not skipped: every browser
42
+ * layer fails with this cause.
43
+ */
44
+ function standInCause(caseId, cases = inject("ufStandIn")) {
45
+ return cases && Object.hasOwn(cases, caseId) ? cases[caseId] : void 0;
46
+ }
47
+ /**
48
+ * Refuses what only a target that runs client code can do: a user's action, or reading the
49
+ * events a component emitted. A test that does either declares `requires: ["interactivity"]`,
50
+ * and is skipped where it cannot run, rather than clicking inert HTML and failing later.
51
+ */
52
+ function assertInteractive(what, cells = capabilityCells(), target = currentTarget()) {
53
+ const cell = capabilityCell("interactivity", cells);
54
+ if (cell.support !== "unsupported") return;
55
+ throw new Error(`${what}: ${target} runs no client code (${cell.reason}). A test that interacts or reads emitted events declares it: it(name, { requires: ["interactivity"] }, fn).`);
56
+ }
57
+ //#endregion
58
+ export { assertInteractive, capabilityCell, capabilityCells, noOutputReason, requiredSkip, standInCause };
@@ -0,0 +1,17 @@
1
+ //#region src/browser/clock.d.ts
2
+ /** The page's fake clock, as a view mounted with `{ clock: true }` advances it. */
3
+ export interface ViewClock {
4
+ /**
5
+ * Advances the clock by `ms` milliseconds (a positive whole number) and runs every interval
6
+ * due on the way, one at a time, as real time would: each in a task of its own, through the
7
+ * adapter's `interact`, then settled as a `view.user` action is before the next is due, so a
8
+ * framework renders between two intervals. Intervals due at the same moment run one after
9
+ * another, settled between them. The tick is recorded as one step of the trace, `tick <ms>ms`,
10
+ * which holds the events every interval emitted. After the unmount there is no DOM left to
11
+ * record: it advances the clock the same way, settling the page after each interval, records
12
+ * no step, and `emitted` shows what an interval the component failed to stop emitted. It
13
+ * throws for a view mounted without a clock, and on a target that runs no client code.
14
+ */
15
+ tick(ms: number): Promise<void>;
16
+ }
17
+ //#endregion
@@ -0,0 +1,69 @@
1
+ import { vi } from "vitest";
2
+ //#region src/browser/clock.ts
3
+ /** Whether a view of the current test has installed the clock. */
4
+ let installed = false;
5
+ /**
6
+ * Fakes the page's intervals before a view's component mounts. The clock is the page's, so one
7
+ * view of a test may have it: a tick would run every view's intervals, and a step records one.
8
+ */
9
+ function installClock() {
10
+ if (installed) throw new Error("mount: a view of this test has a clock already. The clock is the page's, so one view of a test runs on it: a tick runs every view's intervals, but records a step of one view's trace.");
11
+ vi.useFakeTimers({
12
+ toFake: ["setInterval", "clearInterval"],
13
+ shouldClearNativeTimers: true
14
+ });
15
+ installed = true;
16
+ }
17
+ /** The fake clock behind the page's `setInterval`, which keeps it as its `clock`. */
18
+ function fakeClock() {
19
+ const clock = globalThis.setInterval.clock;
20
+ if (typeof clock?.now !== "number" || typeof clock.nextAsync !== "function" || typeof clock.tickAsync !== "function") throw new Error("view.clock.tick: the page's setInterval is not a fake clock the tick can read (its `clock`, with `now`, `nextAsync` and `tickAsync`): Vitest's fake timers changed.");
21
+ return clock;
22
+ }
23
+ /** When the first timer is due, or nothing when none is scheduled. */
24
+ function firstDue(clock) {
25
+ const { timers } = clock;
26
+ const scheduled = timers instanceof Map ? [...timers.values()] : Object.values(timers ?? {});
27
+ let first;
28
+ for (const { callAt } of scheduled) {
29
+ if (typeof callAt !== "number") throw new Error("view.clock.tick: a fake timer has no due time (`callAt`): Vitest's fake timers changed.");
30
+ if (first === void 0 || callAt < first) first = callAt;
31
+ }
32
+ return first;
33
+ }
34
+ /**
35
+ * Advances the clock by `ms` milliseconds, one due interval at a time: `run` gets each one to
36
+ * fire, in a native task of its own, and settles what it did before the next is due. An
37
+ * interval a callback starts or restarts is due on the way too, if its time comes before the
38
+ * end. Then the clock moves on to the end, where no interval is due.
39
+ */
40
+ async function advanceClock(ms, run) {
41
+ const clock = fakeClock();
42
+ const end = clock.now + ms;
43
+ let fired = 0;
44
+ for (let due = firstDue(clock); due !== void 0 && due <= end; due = firstDue(clock)) {
45
+ if ((fired += 1) > MAX_INTERVALS) throw new Error(`view.clock.tick: more than ${MAX_INTERVALS} intervals were due in ${ms}ms: an interval of no time, or one restarted from its own callback, never lets the clock reach the end.`);
46
+ await run(async () => {
47
+ await clock.nextAsync();
48
+ });
49
+ }
50
+ if (clock.now < end) await clock.tickAsync(end - clock.now);
51
+ }
52
+ /** The most intervals one tick runs, as Vitest's fake timers bound one advance (`loopLimit`). */
53
+ const MAX_INTERVALS = 1e3;
54
+ /**
55
+ * Gives the page its real intervals back. The setup calls it when a test ends, after the
56
+ * unmount, so a component's teardown clears its interval on the clock that set it.
57
+ */
58
+ function restoreClock() {
59
+ if (!installed) return;
60
+ installed = false;
61
+ vi.useRealTimers();
62
+ }
63
+ /** Refuses a tick that is not a positive whole number of milliseconds. */
64
+ function checkTick(ms) {
65
+ if (typeof ms === "number" && Number.isSafeInteger(ms) && ms > 0) return;
66
+ throw new TypeError(`view.clock.tick: the time to advance is a positive whole number of milliseconds, not ${typeof ms === "number" ? String(ms) : typeof ms}.`);
67
+ }
68
+ //#endregion
69
+ export { advanceClock, checkTick, installClock, restoreClock };
@@ -0,0 +1,27 @@
1
+ //#region src/browser/console.d.ts
2
+ /** A captured console message. */
3
+ export interface ConsoleEntry {
4
+ level: "warn" | "error";
5
+ message: string;
6
+ /** Where it was logged: the page, or the adapter's server-side render. */
7
+ source: "page" | "server";
8
+ /** It was logged before the test that judges it began. */
9
+ beforeTest?: true;
10
+ /** Why it is not judged: a step that fails on purpose logged it (ADR-0078). */
11
+ excused?: string;
12
+ /** The case of the spec file that had ended on this page when it was logged (ADR-0092). */
13
+ afterFile?: string;
14
+ }
15
+ /**
16
+ * Allows console messages matching `pattern` in the current test. A reason is required: it is
17
+ * the only record of why the message is acceptable.
18
+ */
19
+ export declare function allowConsole(pattern: RegExp, reason: string): void;
20
+ /** Every message the current test will be judged on, those logged before it began first. */
21
+ export declare function capturedConsole(): readonly ConsoleEntry[];
22
+ /**
23
+ * Formats console arguments as the console prints them, including printf-style substitutions,
24
+ * which React uses (`console.error("…%s", name)`), so allowlist patterns match the real text.
25
+ */
26
+ export declare function formatConsoleArgs(args: readonly unknown[]): string;
27
+ //#endregion
@@ -0,0 +1,142 @@
1
+ //#region src/browser/console.ts
2
+ const entries = [];
3
+ const allowances = [];
4
+ let installed = false;
5
+ let errorWatcher;
6
+ let endedFile;
7
+ /** A captured message, with the spec file it followed if it came between two files. */
8
+ function capture(entry) {
9
+ entries.push(endedFile === void 0 ? entry : {
10
+ ...entry,
11
+ afterFile: endedFile
12
+ });
13
+ }
14
+ /**
15
+ * Wraps console.warn and console.error once per page. The originals still print, so the run log
16
+ * keeps the messages.
17
+ */
18
+ function installConsoleCapture() {
19
+ if (installed) return;
20
+ installed = true;
21
+ for (const level of ["warn", "error"]) {
22
+ const original = console[level].bind(console);
23
+ console[level] = (...args) => {
24
+ capture({
25
+ level,
26
+ message: formatConsoleArgs(args),
27
+ source: "page"
28
+ });
29
+ for (const arg of args) errorWatcher?.(arg);
30
+ original(...args);
31
+ };
32
+ }
33
+ }
34
+ /** Records messages an adapter captured outside the page. */
35
+ function captureExternalConsole(messages) {
36
+ for (const { level, message } of messages) capture({
37
+ level,
38
+ message,
39
+ source: "server"
40
+ });
41
+ }
42
+ /**
43
+ * Allows console messages matching `pattern` in the current test. A reason is required: it is
44
+ * the only record of why the message is acceptable.
45
+ */
46
+ function allowConsole(pattern, reason) {
47
+ if (!reason.trim()) throw new Error("allowConsole needs a reason.");
48
+ allowances.push({
49
+ pattern: new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, "")),
50
+ reason
51
+ });
52
+ }
53
+ /**
54
+ * Starts a test: the messages captured since the last judgement were logged outside any test,
55
+ * and are judged with this one. The previous test's allowances end here.
56
+ */
57
+ function beginTestConsole() {
58
+ for (const entry of entries) entry.beforeTest = true;
59
+ allowances.length = 0;
60
+ }
61
+ /** Ends a judgement: the messages captured so far have been judged. */
62
+ function endTestConsole() {
63
+ entries.length = 0;
64
+ }
65
+ /**
66
+ * Ends a spec file, whose case is `caseId`: what the page logs from now on, until the next spec
67
+ * file starts, came after it.
68
+ */
69
+ function endSpecFileConsole(caseId) {
70
+ endedFile = caseId;
71
+ }
72
+ /** Starts a spec file: what the page logs from now on is this file's. */
73
+ function beginSpecFileConsole() {
74
+ endedFile = void 0;
75
+ }
76
+ /** Calls `watch` with each argument the console is given, until the returned function runs. */
77
+ function watchConsoleErrors(watch) {
78
+ errorWatcher = watch;
79
+ return () => {
80
+ errorWatcher = void 0;
81
+ };
82
+ }
83
+ /** Where the captured messages end now, for {@link excuseConsoleSince}. */
84
+ function consoleMark() {
85
+ return entries.length;
86
+ }
87
+ /**
88
+ * Excuses the messages captured since `mark`, for one step that fails on purpose. A pattern
89
+ * would not do: each framework reports the same throw in its own words, and an allowance by
90
+ * pattern would hold for the rest of the test.
91
+ */
92
+ function excuseConsoleSince(mark, reason) {
93
+ if (!reason.trim()) throw new Error("excuseConsoleSince needs a reason.");
94
+ for (const entry of entries.slice(mark)) entry.excused = reason;
95
+ }
96
+ /** Every message the current test will be judged on, those logged before it began first. */
97
+ function capturedConsole() {
98
+ return entries;
99
+ }
100
+ /** The captured messages no allowance covers. */
101
+ function unexpectedConsole() {
102
+ return entries.filter((entry) => entry.excused === void 0 && !allowances.some(({ pattern }) => pattern.test(entry.message)));
103
+ }
104
+ /** Describes unexpected messages for a failure: one line each, the first line of the message. */
105
+ function describeConsole(unexpected) {
106
+ const lines = unexpected.map((entry) => {
107
+ const where = [
108
+ ...entry.source === "server" ? ["server render"] : [],
109
+ ...entry.beforeTest ? ["before the test: module evaluation, a beforeAll hook or an earlier teardown"] : [],
110
+ ...entry.afterFile === void 0 ? [] : [`after the last test of ${entry.afterFile}, which ran earlier on this page`]
111
+ ];
112
+ return ` console.${entry.level}${where.length ? ` (${where.join("; ")})` : ""}: ${entry.message.split("\n")[0]}`;
113
+ });
114
+ return `${unexpected.length} unexpected console message(s):\n${lines.join("\n")}`;
115
+ }
116
+ /**
117
+ * Formats console arguments as the console prints them, including printf-style substitutions,
118
+ * which React uses (`console.error("…%s", name)`), so allowlist patterns match the real text.
119
+ */
120
+ function formatConsoleArgs(args) {
121
+ const text = (value) => value instanceof Error ? value.message : typeof value === "string" ? value : typeof value === "object" && value !== null ? safeJson(value) : String(value);
122
+ const [first, ...rest] = args;
123
+ if (typeof first !== "string") return args.map(text).join(" ");
124
+ let index = 0;
125
+ return [first.replace(/%[sdifoOc%]/g, (token) => {
126
+ if (token === "%%") return "%";
127
+ if (token === "%c") {
128
+ index += 1;
129
+ return "";
130
+ }
131
+ return index < rest.length ? text(rest[index++]) : token;
132
+ }), ...rest.slice(index).map(text)].join(" ");
133
+ }
134
+ function safeJson(value) {
135
+ try {
136
+ return JSON.stringify(value) ?? Object.prototype.toString.call(value);
137
+ } catch {
138
+ return Object.prototype.toString.call(value);
139
+ }
140
+ }
141
+ //#endregion
142
+ export { allowConsole, beginSpecFileConsole, beginTestConsole, captureExternalConsole, capturedConsole, consoleMark, describeConsole, endSpecFileConsole, endTestConsole, excuseConsoleSince, formatConsoleArgs, installConsoleCapture, unexpectedConsole, watchConsoleErrors };
@@ -0,0 +1,108 @@
1
+ import regular from "@fontsource/inter/files/inter-latin-400-normal.woff2?url";
2
+ import bold from "@fontsource/inter/files/inter-latin-700-normal.woff2?url";
3
+ //#region src/browser/determinism.ts
4
+ /** The only family allowed to render text in a capture. No system has a font by this name. */
5
+ const FONT_FAMILY = "UF Test Sans";
6
+ /** The attribute that marks a mount root; the reset below gives it a tight, padded box. */
7
+ const ROOT_ATTRIBUTE = "data-uf-root";
8
+ const RESET = `
9
+ :root {
10
+ color-scheme: light;
11
+ font-family: "${FONT_FAMILY}";
12
+ font-size: 16px;
13
+ line-height: 1.5;
14
+ font-kerning: normal;
15
+ -webkit-text-size-adjust: 100%;
16
+ }
17
+ html, body { margin: 0; padding: 0; background: #ffffff; color: #000000; }
18
+ /* Chromium's UA sheet does not inherit font-family into form controls, and gives the code
19
+ elements the generic monospace family; without this they render with a system font, which the
20
+ font audit rejects. They inherit the bundled family instead of bundling a monospace one: one
21
+ family, one font file per weight, and the same text on every target either way. */
22
+ button, input, select, textarea, code, kbd, listing, plaintext, pre, samp, tt, xmp {
23
+ font-family: inherit;
24
+ }
25
+ *, *::before, *::after {
26
+ animation-duration: 0s !important;
27
+ animation-delay: 0s !important;
28
+ animation-iteration-count: 1 !important;
29
+ transition: none !important;
30
+ caret-color: transparent !important;
31
+ scroll-behavior: auto !important;
32
+ }
33
+ [${ROOT_ATTRIBUTE}] { display: flow-root; width: max-content; padding: 8px; background: #ffffff; }
34
+ `;
35
+ let ready;
36
+ /**
37
+ * Checks that the browser context is the deterministic one, in the spec file's colour scheme,
38
+ * then installs the fonts and the reset if the page has none yet. The setup file calls it for
39
+ * every spec file, since files share a page (ADR-0092): each file's own scheme is checked, not
40
+ * only the first file's.
41
+ */
42
+ async function prepareSpecFile(colorScheme) {
43
+ await checkEnvironment(colorScheme);
44
+ await installDeterminism();
45
+ }
46
+ /**
47
+ * Installs the fonts and the reset once per page. Every later call returns the same promise, so
48
+ * a failure fails every test that depends on it.
49
+ */
50
+ function installDeterminism() {
51
+ ready ??= install();
52
+ return ready;
53
+ }
54
+ /** How long the startup check waits for the case's colour scheme to reach the page (ADR-0081). */
55
+ const COLOR_SCHEME_WAIT_MS = 5e3;
56
+ /** How often the startup check reads the colour scheme again while it waits. */
57
+ const COLOR_SCHEME_POLL_MS = 50;
58
+ /**
59
+ * Checks that the browser context is the deterministic one, in the case's colour scheme, and
60
+ * throws, naming every entry it does not satisfy. The colour scheme alone is read again for at
61
+ * most `COLOR_SCHEME_WAIT_MS` (ADR-0081, amending ADR-0061): in Firefox, the setup file's
62
+ * emulation can reach the tester frame after the command that set it returns. The other entries
63
+ * come from the context's options, which apply before the page loads, so they are read once.
64
+ */
65
+ async function checkEnvironment(colorScheme) {
66
+ const environment = {
67
+ "devicePixelRatio: 1": window.devicePixelRatio === 1,
68
+ "prefers-reduced-motion: reduce": matchMedia("(prefers-reduced-motion: reduce)").matches,
69
+ [`prefers-color-scheme: ${colorScheme}`]: await matchesWithin(`(prefers-color-scheme: ${colorScheme})`, COLOR_SCHEME_WAIT_MS),
70
+ "forced-colors: none": matchMedia("(forced-colors: none)").matches
71
+ };
72
+ const wrong = Object.keys(environment).filter((name) => !environment[name]);
73
+ if (wrong.length) throw new Error(`Visual determinism: the browser context does not satisfy ${wrong.join(", ")}. The project must set the provider's contextOptions (see the screenshot ADR), and the setup file emulate the case's colour scheme (ADR-0061).`);
74
+ }
75
+ /** Whether the page matches `query`, read until it does or `timeout` milliseconds pass. */
76
+ async function matchesWithin(query, timeout) {
77
+ const deadline = Date.now() + timeout;
78
+ while (!matchMedia(query).matches) {
79
+ if (Date.now() >= deadline) return false;
80
+ await new Promise((resolve) => setTimeout(resolve, COLOR_SCHEME_POLL_MS));
81
+ }
82
+ return true;
83
+ }
84
+ async function install() {
85
+ const style = document.createElement("style");
86
+ style.setAttribute("data-uf-determinism", "");
87
+ style.textContent = RESET;
88
+ document.head.append(style);
89
+ const faces = [new FontFace(FONT_FAMILY, `url(${regular}) format("woff2")`, { weight: "400" }), new FontFace(FONT_FAMILY, `url(${bold}) format("woff2")`, { weight: "700" })];
90
+ for (const face of faces) {
91
+ document.fonts.add(face);
92
+ await face.load();
93
+ }
94
+ await document.fonts.ready;
95
+ const failed = faces.filter((face) => face.status !== "loaded");
96
+ if (failed.length) throw new Error(`Visual determinism: ${failed.map((face) => `${face.family} ${face.weight}`).join(", ")} did not load.`);
97
+ }
98
+ /** Waits for what a capture depends on: the fonts, the target's settle hook and two frames. */
99
+ async function settleFrame(targetSettle) {
100
+ await installDeterminism();
101
+ await targetSettle?.();
102
+ await document.fonts.ready;
103
+ await new Promise((resolve) => {
104
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
105
+ });
106
+ }
107
+ //#endregion
108
+ export { COLOR_SCHEME_WAIT_MS, FONT_FAMILY, ROOT_ATTRIBUTE, checkEnvironment, installDeterminism, prepareSpecFile, settleFrame };
@@ -0,0 +1,28 @@
1
+ import { expect } from "vitest";
2
+ import { server } from "vitest/browser";
3
+ //#region src/browser/element-timeout.ts
4
+ // @vitest/browser 5.0.3). A locator that never matches would then hold its test for the whole
5
+ let bound = false;
6
+ /**
7
+ * Gives every `expect.element` call that names no timeout the project's poll timeout. A locator
8
+ * that never matches then fails at that deadline, mostly with the element's own error, which
9
+ * names the locator, but sometimes (53 of the L8 canary's 497 failures) with Vitest's bare
10
+ * "expect.poll() function didn't resolve in time.": `expect.element` gives the poll's timer and
11
+ * `findElement`'s retries one deadline, from the one `timeout` option, and whichever notices it
12
+ * first words the failure. No public option sets them apart, so both messages are L8 evidence
13
+ * (the L8 canary's, ADR-0043); the failure's stack names the spec's assertion either way. A
14
+ * project without a poll timeout cannot bound its assertions, so that throws.
15
+ */
16
+ function boundElementTimeout() {
17
+ if (bound) return;
18
+ const timeout = server.config.expect?.poll?.timeout;
19
+ if (timeout === void 0) throw new Error("[uf] The browser project sets no `expect.poll.timeout`: `expect.element` would wait for the whole test timeout.");
20
+ bound = true;
21
+ const element = expect.element;
22
+ expect.element = ((subject, options) => element(subject, {
23
+ timeout,
24
+ ...options
25
+ }));
26
+ }
27
+ //#endregion
28
+ export { boundElementTimeout };
@@ -0,0 +1,68 @@
1
+ import { renameGeneratedIds } from "../normalize/rules/generated-ids.js";
2
+ //#region src/browser/events.ts
3
+ /** A payload no trace can record, refused with the event's name and where in it the value was. */
4
+ var PayloadError = class extends Error {
5
+ name = "PayloadError";
6
+ };
7
+ /**
8
+ * Copies one emit's arguments as plain data, or throws a {@link PayloadError} saying why not.
9
+ * Trailing `undefined` arguments are dropped first: a JavaScript listener cannot tell
10
+ * `emit("change", value, undefined)` from `emit("change", value)`, and a watcher's `previous` is
11
+ * `undefined` on its immediate first run (semantics contract, watch semantics). An `undefined`
12
+ * before a given argument is still refused.
13
+ */
14
+ function copyPayload(event, args) {
15
+ let length = args.length;
16
+ while (length > 0 && args[length - 1] === void 0) length -= 1;
17
+ return args.slice(0, length).map((arg, index) => copyValue(arg, `argument ${index + 1}`, event));
18
+ }
19
+ function copyValue(value, path, event) {
20
+ const refuse = (what) => {
21
+ throw new PayloadError(`The payload of "${event}" holds ${what} at ${path}: an emit's arguments are plain data (strings, finite numbers, booleans, null, arrays and plain objects), which every target's listener receives alike and a trace records.`);
22
+ };
23
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
24
+ if (typeof value === "number") {
25
+ if (!Number.isFinite(value)) refuse(String(value));
26
+ return value === 0 ? 0 : value;
27
+ }
28
+ if (value === void 0) return refuse("undefined (leave the argument out, or pass null)");
29
+ if (typeof value === "function") return refuse("a function");
30
+ if (typeof value !== "object") return refuse(`a ${typeof value}`);
31
+ if (typeof Event !== "undefined" && value instanceof Event) return refuse("a DOM event");
32
+ if (typeof Node !== "undefined" && value instanceof Node) return refuse("a DOM node");
33
+ if (value instanceof Map) return refuse("a Map");
34
+ if (value instanceof Set) return refuse("a Set");
35
+ if (Array.isArray(value)) return Array.from(value, (item, index) => copyValue(item, `${path}[${index}]`, event));
36
+ const prototype = Object.getPrototypeOf(value);
37
+ if (prototype !== Object.prototype && prototype !== null) {
38
+ const constructor = prototype.constructor?.name;
39
+ return refuse(`an instance of ${constructor || "a class"}`);
40
+ }
41
+ const copy = {};
42
+ for (const key of Object.keys(value)) copy[key] = copyValue(value[key], `${path}.${key}`, event);
43
+ return copy;
44
+ }
45
+ /**
46
+ * Renames the compiler's generated ids in a payload (each `uf-id-…` in a string, as the
47
+ * normaliser reads them in the DOM) the way the step's DOM renames them (`names`, from the
48
+ * normaliser), so a payload that carries an id reads the same on every target. An id the DOM
49
+ * does not hold takes the next number.
50
+ */
51
+ function renumberIds(value, names) {
52
+ if (typeof value === "string") return renameGeneratedIds(value, names);
53
+ if (Array.isArray(value)) return value.map((item) => renumberIds(item, names));
54
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, renumberIds(item, names)]));
55
+ return value;
56
+ }
57
+ /**
58
+ * Emits grouped by event name, names sorted, each name's argument lists in the order they came:
59
+ * the relative order of different effects that one run triggers is not part of the contract
60
+ * (Vue orders by trigger, Svelte and React by declaration), so a trace never records it.
61
+ */
62
+ function groupEvents(events) {
63
+ const groups = /* @__PURE__ */ new Map();
64
+ for (const { name, args } of events) groups.set(name, [...groups.get(name) ?? [], args]);
65
+ return Object.fromEntries([...groups.keys()].sort().map((name) => [name, groups.get(name)]));
66
+ }
67
+ //#endregion
68
+ export { PayloadError, copyPayload, groupEvents, renumberIds };
@@ -0,0 +1,135 @@
1
+ //#region src/browser/geometry.ts
2
+ /** The computed properties that explain how a box looks. Width and height come from the box. */
3
+ const GEOMETRY_STYLE_PROPERTIES = [
4
+ "display",
5
+ "position",
6
+ "top",
7
+ "right",
8
+ "bottom",
9
+ "left",
10
+ "float",
11
+ "box-sizing",
12
+ "margin-top",
13
+ "margin-right",
14
+ "margin-bottom",
15
+ "margin-left",
16
+ "padding-top",
17
+ "padding-right",
18
+ "padding-bottom",
19
+ "padding-left",
20
+ "border-top-width",
21
+ "border-right-width",
22
+ "border-bottom-width",
23
+ "border-left-width",
24
+ "border-top-style",
25
+ "border-right-style",
26
+ "border-bottom-style",
27
+ "border-left-style",
28
+ "border-top-color",
29
+ "border-right-color",
30
+ "border-bottom-color",
31
+ "border-left-color",
32
+ "border-top-left-radius",
33
+ "border-top-right-radius",
34
+ "border-bottom-right-radius",
35
+ "border-bottom-left-radius",
36
+ "color",
37
+ "background-color",
38
+ "background-image",
39
+ "opacity",
40
+ "visibility",
41
+ "font-family",
42
+ "font-size",
43
+ "font-weight",
44
+ "font-style",
45
+ "line-height",
46
+ "letter-spacing",
47
+ "word-spacing",
48
+ "text-align",
49
+ "text-decoration-line",
50
+ "text-transform",
51
+ "text-shadow",
52
+ "white-space",
53
+ "vertical-align",
54
+ "overflow-x",
55
+ "overflow-y",
56
+ "z-index",
57
+ "transform",
58
+ "box-shadow",
59
+ "outline-style",
60
+ "outline-width",
61
+ "outline-color",
62
+ "outline-offset",
63
+ "list-style-type",
64
+ "flex-direction",
65
+ "flex-wrap",
66
+ "justify-content",
67
+ "align-items",
68
+ "row-gap",
69
+ "column-gap",
70
+ "grid-template-columns",
71
+ "grid-template-rows"
72
+ ];
73
+ /** The pseudo-elements captured where their computed `content` is not `none`. */
74
+ const PSEUDO_ELEMENTS = ["::before", "::after"];
75
+ /** The captured properties of a computed style. */
76
+ function styleOf(computed) {
77
+ const style = {};
78
+ for (const property of GEOMETRY_STYLE_PROPERTIES) style[property] = computed.getPropertyValue(property);
79
+ return style;
80
+ }
81
+ const toBox = (rect, origin) => [
82
+ rect.x - origin.x,
83
+ rect.y - origin.y,
84
+ rect.width,
85
+ rect.height
86
+ ];
87
+ /** Snapshots the boxes and computed styles of every element and text node under a container. */
88
+ function captureGeometry(container) {
89
+ const origin = container.getBoundingClientRect();
90
+ const nodes = {};
91
+ const visit = (parent, prefix) => {
92
+ const counters = /* @__PURE__ */ new Map();
93
+ const next = (key) => {
94
+ const index = counters.get(key) ?? 0;
95
+ counters.set(key, index + 1);
96
+ return `${prefix}${key}[${index}]`;
97
+ };
98
+ for (const child of flatten(parent)) if (child.nodeType === Node.TEXT_NODE) {
99
+ if (!child.textContent?.trim()) continue;
100
+ const range = document.createRange();
101
+ range.selectNodeContents(child);
102
+ nodes[next("#text")] = { box: [...range.getClientRects()].map((r) => toBox(r, origin)) };
103
+ } else if (child instanceof Element) {
104
+ const path = next(child.localName);
105
+ const style = styleOf(getComputedStyle(child));
106
+ nodes[path] = {
107
+ box: toBox(child.getBoundingClientRect(), origin),
108
+ style
109
+ };
110
+ for (const pseudo of PSEUDO_ELEMENTS) {
111
+ const computed = getComputedStyle(child, pseudo);
112
+ if (computed.content === "none") continue;
113
+ nodes[`${path}${pseudo}`] = { style: {
114
+ ...styleOf(computed),
115
+ content: computed.content
116
+ } };
117
+ }
118
+ if (child.localName !== "textarea") visit(child, `${path}/`);
119
+ }
120
+ };
121
+ visit(container, "");
122
+ return {
123
+ version: 1,
124
+ nodes
125
+ };
126
+ }
127
+ /** The element and text children of a node, looking through `display: contents` wrappers. */
128
+ function flatten(parent) {
129
+ const out = [];
130
+ for (const child of parent.childNodes) if (child instanceof Element && getComputedStyle(child).display === "contents") out.push(...flatten(child));
131
+ else if (child.nodeType === Node.TEXT_NODE || child instanceof Element) out.push(child);
132
+ return out;
133
+ }
134
+ //#endregion
135
+ export { GEOMETRY_STYLE_PROPERTIES, captureGeometry };