@ctrl/dom 0.1.3 → 0.1.5

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 (59) hide show
  1. package/dist/aria/_chunks/roles-list-BXCvPLJT.cjs +4 -0
  2. package/dist/aria/_chunks/roles-list-rVVxaIPs.js +4 -0
  3. package/dist/aria/index.cjs +1 -232
  4. package/dist/aria/index.js +1 -198
  5. package/dist/aria/internal.cjs +1 -69
  6. package/dist/aria/internal.js +1 -30
  7. package/dist/cli/_chunks/report-z52LF7nA.js +12 -0
  8. package/dist/cli/_chunks/rolldown-runtime-H3fMLYWS.js +1 -0
  9. package/dist/cli/ctrl-dom.js +2 -181
  10. package/dist/cli/jest-reporter.js +2 -54
  11. package/dist/cli/vitest-reporter.js +2 -81
  12. package/dist/dom/_chunks/src-sZY6a2LC.js +49 -0
  13. package/dist/dom/index.js +1 -3
  14. package/dist/dom/internal.js +1 -434
  15. package/dist/dom/types/window/clock.d.ts +10 -2
  16. package/dist/jest-dom/_chunks/matchers-CGTk9GX9.cjs +31 -0
  17. package/dist/jest-dom/_chunks/matchers-Chf0yHoo.js +31 -0
  18. package/dist/jest-dom/index.cjs +1 -5
  19. package/dist/jest-dom/index.js +1 -6
  20. package/dist/jest-dom/jest-globals.cjs +1 -6
  21. package/dist/jest-dom/jest-globals.js +1 -7
  22. package/dist/jest-dom/matchers.cjs +1 -53
  23. package/dist/jest-dom/matchers.js +1 -3
  24. package/dist/jest-dom/vitest.cjs +1 -6
  25. package/dist/jest-dom/vitest.js +1 -7
  26. package/dist/react/_chunks/pure-CCeTO5Mk.js +1 -0
  27. package/dist/react/_chunks/pure-DQzwul4s.cjs +1 -0
  28. package/dist/react/dont-cleanup-after-each.cjs +1 -3
  29. package/dist/react/dont-cleanup-after-each.js +1 -4
  30. package/dist/react/index.cjs +1 -47
  31. package/dist/react/index.js +1 -35
  32. package/dist/react/pure.cjs +1 -17
  33. package/dist/react/pure.js +1 -5
  34. package/dist/register/index.js +1 -11
  35. package/dist/register/pure.js +1 -147
  36. package/dist/testing-library/_chunks/aria-snapshot-diff-80G4meO2.cjs +14 -0
  37. package/dist/testing-library/_chunks/aria-snapshot-diff-B1L8s_sM.js +14 -0
  38. package/dist/testing-library/agent.cjs +10 -720
  39. package/dist/testing-library/agent.js +10 -712
  40. package/dist/testing-library/index.cjs +19 -2459
  41. package/dist/testing-library/index.js +19 -2380
  42. package/dist/user-event/index.cjs +33 -3924
  43. package/dist/user-event/index.js +33 -3899
  44. package/dist/user-event/types/ctrl-dom.d.ts +1 -1
  45. package/dist/vitest-environment/_chunks/rolldown-runtime-BhWHdk3m.js +1 -0
  46. package/dist/vitest-environment/failure-snapshot.js +1 -42
  47. package/dist/vitest-environment/index.js +1 -185
  48. package/dist/vitest-environment/plugin.js +1 -90
  49. package/package.json +1 -1
  50. package/dist/aria/_chunks/roles-list-CYZF-l9K.js +0 -1503
  51. package/dist/aria/_chunks/roles-list-D4WCyRO_.cjs +0 -1754
  52. package/dist/cli/_chunks/report-DdncYfuJ.js +0 -93
  53. package/dist/dom/_chunks/src-Bwp4p8ko.js +0 -47601
  54. package/dist/jest-dom/_chunks/matchers-CDnnXUfG.js +0 -2211
  55. package/dist/jest-dom/_chunks/matchers-D988Ducb.cjs +0 -2516
  56. package/dist/react/_chunks/pure-DZ97z2oT.cjs +0 -498
  57. package/dist/react/_chunks/pure-PtE2hivW.js +0 -420
  58. package/dist/testing-library/_chunks/aria-snapshot-diff-D7PzpXew.cjs +0 -1170
  59. package/dist/testing-library/_chunks/aria-snapshot-diff-Q8Wj33K0.js +0 -985
@@ -1,713 +1,11 @@
1
- import { S as yamlValue, b as resetBodySnapshot, d as ariaSnapshotTree, f as budgetLines, g as lastBodySnapshot, l as ariaSnapshot, m as envMaxLines, n as diffLines, s as prettyDOM, t as diffAriaSnapshots, u as ariaSnapshotLines, w as envDebugFormat, x as truncate, y as quote } from "./_chunks/aria-snapshot-diff-Q8Wj33K0.js";
2
- import { $impl } from "@ctrl/dom/internal";
3
- import { roleSupportsProp } from "@ctrl/dom/aria";
1
+ import{S as e,b as t,d as n,f as r,g as i,l as a,m as o,n as s,s as c,t as l,u,w as d,x as f,y as p}from"./_chunks/aria-snapshot-diff-B1L8s_sM.js";import{$impl as m}from"@ctrl/dom/internal";import{roleSupportsProp as h}from"@ctrl/dom/aria";var AriaTemplateError=class extends Error{constructor(e,t,n,r=-1){super(`${e} (template line ${t+1}):\n\n${n}${r>=0?`\n${` `.repeat(r)}^`:``}`),this.name=`AriaTemplateError`}};function normalizeWhitespace(e){return e.replace(/[​­]/g,``).replace(/[\r\n\s\t]+/g,` `).trim()}function textValue(e){let t=null;if(e.length>1&&e.startsWith(`/`)&&e.endsWith(`/`))try{t=new RegExp(e.slice(1,-1))}catch{t=null}return{raw:e,normalized:normalizeWhitespace(e),regex:t}}const g=/* @__PURE__ */ new Set([`disabled`,`expanded`,`active`,`selected`,`busy`,`hidden`]);function parseAriaTemplate(e){let t=e.split(/\r?\n/),n=1/0;for(let e=0;e<t.length;e++){let r=t[e],i=r.trim();if(i===``||i.startsWith(`#`))continue;let a=r.length-r.trimStart().length;if(r.slice(0,a).includes(` `))throw new AriaTemplateError(`Tabs cannot be used for indentation`,e,r);a<n&&(n=a)}let r={kind:`role`,role:`fragment`,name:null,attrs:[],url:null,mode:null,children:[]};if(n===1/0)throw new AriaTemplateError(`The aria snapshot template is empty`,0,e);let i=[{indent:-1,node:r,line:-1}];for(let e=0;e<t.length;e++){let r=t[e],a=r.trim();if(a===``||a.startsWith(`#`))continue;let o=r.length-r.trimStart().length-n;if(a!==`-`&&!a.startsWith(`- `))throw new AriaTemplateError(`Aria snapshot must be a YAML sequence, elements starting with "-"`,e,r,o+n);for(;i[i.length-1].indent>=o;)i.pop();let s=i[i.length-1];if(s.node===null)throw new AriaTemplateError(`"- text:" on line ${s.line+1} cannot have children`,e,r,o+n);let c=a.slice(2).trimStart(),l=r.length-c.length,u=parseItem(c,s.node,e,r,l);u!==void 0&&i.push({indent:o,node:u,line:e})}return r.children.length===1&&(r.mode===null||r.mode===`contain`)&&r.url===null?r.children[0]:r}function parseItem(e,t,n,r,i){let fail=(e,t)=>{throw new AriaTemplateError(e,n,r,i+t)};if(e===``&&fail(`Empty sequence item`,0),e.startsWith(`/`)){let n=e.indexOf(`:`);n<0&&fail("Property should be written `/name: value`",e.length);let r=e.slice(1,n).trim(),i=parseScalar(e.slice(n+1),fail,n+1);r===`children`?(i!==`contain`&&i!==`equal`&&i!==`deep-equal`&&fail(`Value of "/children" should be "contain", "equal" or "deep-equal"`,n+1),t.mode=i):r===`url`&&(t.url=textValue(i));return}let a,o=null;try{if(e[0]===`"`||e[0]===`'`){let[n,r]=readQuoted(e,0,fail),i=e.slice(r).trimStart();if(i!==``&&i[0]!==`:`&&fail(`Unexpected input after the quoted key`,r),i!==``&&(o=i.slice(1)),n===`text`&&o!==null)return textItem(t,o,fail,e.length-o.length);a=new KeyParser(n).parse(!1)}else{if(/^text:(\s|$)/.test(e))return textItem(t,e.slice(5),fail,5);let n=new KeyParser(e);a=n.parse(!0),n.pos<e.length&&(o=e.slice(n.pos+1))}}catch(t){throw t instanceof KeyError&&fail(t.message,e[0]===`"`||e[0]===`'`?0:t.pos),t}return o!==null&&o.trim()!==``&&a.children.push({kind:`text`,text:textValue(parseScalar(o,fail,e.length-o.length))}),t.children.push(a),a}function textItem(e,t,n,r){return e.children.push({kind:`text`,text:textValue(parseScalar(t,n,r))}),null}function parseScalar(e,t,n){let r=e.length-e.trimStart().length,i=e.trim();if(i[0]===`"`||i[0]===`'`){let[e,a]=readQuoted(i,0,(e,i)=>t(e,n+r+i)),o=i.slice(a).trim();return o!==``&&!o.startsWith(`#`)&&t(`Unexpected input after the quoted value`,n+r+a),e}(i===`|`||i===`>`||i.startsWith(`|`)||i.startsWith(`>`))&&t(`Block scalars are not supported in aria snapshot templates`,n+r);let a=i.search(/\s#/);return a>=0?i.slice(0,a).trim():i}function readQuoted(e,t,n){let r=e[t],i=``;for(let n=t+1;n<e.length;n++){let t=e[n];if(r===`'`){if(t===`'`){if(e[n+1]===`'`){i+=`'`,n++;continue}return[i,n+1]}i+=t}else{if(t===`"`)return[i,n+1];if(t===`\\`){let t=e[++n];t===`n`?i+=`
2
+ `:t===`t`?i+=` `:t===`u`?(i+=String.fromCharCode(parseInt(e.slice(n+1,n+5),16)),n+=4):i+=t??``}else i+=t}}return n(`Unterminated string`,e.length)}var KeyError=class extends Error{pos;constructor(e,t){super(e),this.pos=t}},KeyParser=class{pos=0;input;constructor(e){this.input=e}peek(){return this.input[this.pos]??``}eof(){return this.pos>=this.input.length}skipWhitespace(){for(;!this.eof()&&/\s/.test(this.peek());)this.pos++}atColon(){return this.peek()===`:`&&(this.pos+1>=this.input.length||/\s/.test(this.input[this.pos+1]))}readIdentifier(e){if(this.eof())throw new KeyError(`Unexpected end of input when expecting ${e}`,this.pos);let t=this.pos;for(;!this.eof()&&/[a-zA-Z]/.test(this.peek());)this.pos++;if(this.pos===t)throw new KeyError(`Expected ${e}`,this.pos);return this.input.slice(t,this.pos)}readString(){let e=``;for(;!this.eof();){let t=this.input[this.pos++];if(t===`\\`){let t=this.input[this.pos++]??``;t===`n`?e+=`
3
+ `:t===`t`?e+=` `:t===`u`?(e+=String.fromCharCode(parseInt(this.input.slice(this.pos,this.pos+4),16)),this.pos+=4):e+=t}else if(t===`"`)return e;else e+=t}throw new KeyError(`Unterminated string`,this.pos)}readRegex(){let e=this.pos,t=``,n=!1,r=!1;for(;!this.eof();){let i=this.input[this.pos++];if(n)t+=i,n=!1;else if(i===`\\`)n=!0,t+=i;else if(i===`/`&&!r)try{return new RegExp(t)}catch(t){throw new KeyError(`Invalid regular expression: ${t.message}`,e)}else i===`[`?(r=!0,t+=i):i===`]`&&r?(t+=i,r=!1):t+=i}throw new KeyError(`Unterminated regex`,this.pos)}parse(e){this.skipWhitespace();let t=this.readIdentifier(`role`);this.skipWhitespace();let n=null;this.peek()===`"`?(this.pos++,n=normalizeWhitespace(this.readString())):this.peek()===`/`&&(this.pos++,n=this.readRegex());let r={kind:`role`,role:t,name:n===``?null:n,attrs:[],url:null,mode:null,children:[]};for(;this.skipWhitespace(),this.peek()===`[`;){this.pos++,this.skipWhitespace();let e=this.pos,t=this.readIdentifier(`attribute`);this.skipWhitespace();let n=``;if(this.peek()===`=`)for(this.pos++,this.skipWhitespace();this.peek()!==`]`&&!/\s/.test(this.peek())&&!this.eof();)n+=this.input[this.pos++];if(this.skipWhitespace(),this.peek()!==`]`)throw new KeyError(`Expected ]`,this.pos);this.pos++,r.attrs.push([t,checkAttribute(t,n||`true`,e)])}if(this.skipWhitespace(),e&&this.atColon())return r;if(!this.eof())throw new KeyError(e?`Unexpected input (a key ends with ":" and a space)`:`Unexpected input`,this.pos);return r}};function checkAttribute(e,t,n){if(e===`checked`||e===`pressed`){if(t!==`true`&&t!==`false`&&t!==`mixed`)throw new KeyError(`Value of "${e}" attribute must be a boolean or "mixed"`,n);return t}if(g.has(e)){if(t!==`true`&&t!==`false`)throw new KeyError(`Value of "${e}" attribute must be a boolean`,n);return t}if(e===`level`){if(Number.isNaN(Number(t)))throw new KeyError(`Value of "level" attribute must be a number`,n);return String(Number(t))}if(e===`current`)return t;throw new KeyError(`Unsupported attribute [${e}]`,n)}function toMatchNode(e){let t=[];e.value!==null&&e.value!==``&&t.push(normalizeWhitespace(e.value));for(let n=0;n<e.children.length;n++){let r=e.children[n];t.push(typeof r==`string`?normalizeWhitespace(r):toMatchNode(r))}let n=/* @__PURE__ */ new Map;for(let t=0;t<e.props.length;t++){let r=e.props[t].slice(1,-1),i=r.indexOf(`=`);i<0?n.set(r,`true`):n.set(r.slice(0,i),r.slice(i+1))}return{role:e.role,name:normalizeWhitespace(e.name),states:n,url:e.url,children:t,props:e.props}}function stateOf(e,t){let n=e.states.get(t);if(n!==void 0)return n;switch(t){case`checked`:return h(e.role,`aria-checked`)?`false`:void 0;case`disabled`:case`selected`:case`active`:case`busy`:case`hidden`:case`current`:return`false`}}function attrsMatch(e,t){for(let n=0;n<t.attrs.length;n++){let[r,i]=t.attrs[n],a=stateOf(e,r);if(r===`current`&&i===`true`){if(a===void 0||a===`false`)return!1}else if(a!==i)return!1}return!0}function matchesName(e,t){return t===null?!0:e===``?!1:typeof t==`string`?e===t:t.test(e)}function matchesText(e,t){return t===null||t.normalized===``?!0:e?e===t.normalized||e===t.raw||t.regex!==null&&t.regex.test(e):!1}function headerMatches(e,t){return(t.role===`fragment`||t.role===e.role)&&attrsMatch(e,t)&&matchesName(e.name,t.name)&&matchesText(e.url,t.url)}function matchesNode(e,t,n){return typeof e==`string`?t.kind===`text`&&matchesText(e,t.text):t.kind!==`role`||!headerMatches(e,t)?!1:t.mode===`contain`?containsList(e.children,t.children):t.mode===`equal`?listEqual(e.children,t.children,!1):t.mode===`deep-equal`||n?listEqual(e.children,t.children,!0):containsList(e.children,t.children)}function listEqual(e,t,n){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!matchesNode(e[r],t[r],n))return!1;return!0}function containsList(e,t){if(t.length>e.length)return!1;let n=0;for(let r=0;r<t.length;r++){for(;n<e.length&&!matchesNode(e[n],t[r],!1);)n++;if(n===e.length)return!1;n++}return!0}function matchesDeep(e,t){if(matchesNode(e,t,!1))return!0;if(typeof e==`string`)return!1;for(let n=0;n<e.children.length;n++)if(matchesDeep(e.children[n],t))return!0;return!1}function textRepr(t){return t.regex===null?e(t.normalized):t.raw}function templateKey(e){let t=e.role;typeof e.name==`string`?t+=` `+p(e.name):e.name!==null&&(t+=` /${e.name.source}/`);for(let n=0;n<e.attrs.length;n++)t+=e.attrs[n][1]===`true`?` [${e.attrs[n][0]}]`:` [${e.attrs[n][0]}=${e.attrs[n][1]}]`;return t}function receivedKey(e){let t=e.role;e.name!==``&&(t+=` `+p(f(e.name,100)));for(let n=0;n<e.props.length;n++)t+=` `+e.props[n];return t}function isInline(e){return e.url===null&&e.mode===null&&e.children.length===1&&e.children[0].kind===`text`}function renderTemplate(e,t,n){if(e.kind===`text`){n.push(`${t}- text: ${textRepr(e.text)}`);return}let r=templateKey(e);if(isInline(e)){n.push(`${t}- ${r}: ${textRepr(e.children[0].text)}`);return}if(e.children.length===0&&e.url===null&&e.mode===null){n.push(`${t}- ${r}`);return}n.push(`${t}- ${r}:`);let i=t+` `;e.url!==null&&n.push(`${i}- /url: ${textRepr(e.url)}`),e.mode!==null&&n.push(`${i}- /children: ${e.mode}`);for(let t=0;t<e.children.length;t++)renderTemplate(e.children[t],i,n)}var Scorer=class{memo=/* @__PURE__ */ new Map;score(e,t){if(e.kind===`text`)return typeof t==`string`?matchesText(t,e.text)?3:1:0;if(typeof t==`string`||e.role!==`fragment`&&e.role!==t.role)return 0;let n=this.memo.get(e);n===void 0&&this.memo.set(e,n=/* @__PURE__ */ new Map);let r=n.get(t);if(r!==void 0)return r;let i=2;return i+=e.name===null?1:matchesName(t.name,e.name)?2:0,attrsMatch(t,e)&&(i+=1),e.url!==null&&matchesText(t.url,e.url)&&(i+=1),i+=this.scoreList(e.children,t.children),n.set(t,i),i}scoreList(e,t){let n=this.align(e,t),r=0;for(let t=0;t<e.length;t++)n[t]!==null&&(r+=this.score(e[t],n[t]));return r}align(e,t){let n=[],r=0;for(let i=0;i<e.length;i++){let a=-1,o=0;for(let n=r;n<t.length;n++){let r=this.score(e[i],t[n]);r>o&&(a=n,o=r)}a<0?n.push(null):(n.push(t[a]),r=a+1)}return n}project(t,n,r,i){if(t.kind===`text`){let a=n;i.push(`${r}- text: ${matchesText(a,t.text)?textRepr(t.text):e(f(a,100))}`);return}let a=n,o=headerMatches(a,t)?templateKey(t):receivedKey(a),s=this.align(t.children,a.children);if(isInline(t)){let n=s[0],a=t.children[0].text;i.push(n===null?`${r}- ${o}`:`${r}- ${o}: ${matchesText(n,a)?textRepr(a):e(f(n,100))}`);return}if(t.children.length===0&&t.url===null&&t.mode===null){i.push(`${r}- ${o}`);return}i.push(`${r}- ${o}:`);let c=r+` `;t.url!==null&&i.push(`${c}- /url: ${matchesText(a.url,t.url)?textRepr(t.url):e(a.url??``)}`),t.mode!==null&&i.push(`${c}- /children: ${t.mode}`);for(let e=0;e<t.children.length;e++)s[e]!==null&&this.project(t.children[e],s[e],c,i)}};function forEachNode(e,t){t(e);for(let n=0;n<e.children.length;n++){let r=e.children[n];typeof r==`string`?t(r):forEachNode(r,t)}}function closestLines(e,t){let n=new Scorer,r=[];if(t.kind===`role`&&t.role===`fragment`){let i=null,a=0;if(forEachNode(e,e=>{if(typeof e==`string`)return;let r=n.scoreList(t.children,e.children);r>a&&(i=e,a=r)}),i!==null){let e=n.align(t.children,i.children);for(let i=0;i<t.children.length;i++)e[i]!==null&&n.project(t.children[i],e[i],``,r)}return r}let i=null,a=0;return forEachNode(e,e=>{let r=n.score(t,e);r>a&&(i=e,a=r)}),i!==null&&n.project(t,i,``,r),r}function pairChanges(e){let t=[];for(let n=0;n<e.length;){if(e[n].kind===`=`){t.push(e[n++]);continue}let r=n;for(;r<e.length&&e[r].kind===`-`;)r++;let i=r;for(;i<e.length&&e[i].kind===`+`;)i++;if(r-n===i-r)for(let i=0;i<r-n;i++)t.push(e[n+i],e[r+i]);else for(let r=n;r<i;r++)t.push(e[r]);n=i}return t}function matchAriaSnapshot(e,t){let r=parseAriaTemplate(t),i=n(e,{urls:!0}),c=[];for(let e=0;e<i.length;e++){let t=i[e];c.push(typeof t==`string`?normalizeWhitespace(t):toMatchNode(t))}let l={role:`fragment`,name:``,states:/* @__PURE__ */ new Map,url:null,children:c,props:[]},u=matchesDeep(l,r),expectedLines=()=>{let e=[];if(r.kind===`role`&&r.role===`fragment`){r.mode!==null&&e.push(`- /children: ${r.mode}`);for(let t=0;t<r.children.length;t++)renderTemplate(r.children[t],``,e)}else renderTemplate(r,``,e);return e};return{pass:u,expected:()=>expectedLines().join(`
4
+ `),diff:()=>pairChanges(s(expectedLines(),closestLines(l,r))),received:()=>a(e,{collapseAfter:1/0,maxLines:o()??100})}}function resetFailureSnapshot(e){t(e)}function captureFailureSnapshot(e){let t=d(),n=e?.body;if(t===null||n==null||n[m]===void 0)return null;if(t===`compact`){let e=c(n,void 0,{format:`compact`});return{format:t,text:String(e),full:``,previous:void 0}}let a=i(e),{lines:s,empty:l}=u(n),f=l??s.join(`
5
+ `);return{format:t,text:l??r(s,o()??100).join(`
6
+ `),full:f,previous:a}}function formatFailureSnapshot(e,t){if(e.format===`compact`)return`DOM of <body> when the test failed (CTRL_DOM_DEBUG=compact):\n${e.text}`;if(t.includes(e.text))return`Accessibility snapshot of <body> when the test failed: the same as above.`;let n=`Accessibility snapshot of <body> when the test failed (CTRL_DOM_DEBUG=aria):\n${e.text}`;return e.previous!==void 0&&(e.previous===e.full?n+=`
4
7
 
5
- // src/aria-snapshot-match.ts
6
- /** A template that is not valid aria snapshot YAML; the message names the line. */
7
- var AriaTemplateError = class extends Error {
8
- constructor(message, line, source, column = -1) {
9
- super(`${message} (template line ${line + 1}):\n\n${source}${column >= 0 ? `\n${" ".repeat(column)}^` : ""}`);
10
- this.name = "AriaTemplateError";
11
- }
12
- };
13
- function normalizeWhitespace(text) {
14
- return text.replace(/[​­]/g, "").replace(/[\r\n\s\t]+/g, " ").trim();
15
- }
16
- function textValue(raw) {
17
- let regex = null;
18
- if (raw.length > 1 && raw.startsWith("/") && raw.endsWith("/")) try {
19
- regex = new RegExp(raw.slice(1, -1));
20
- } catch {
21
- regex = null;
22
- }
23
- return {
24
- raw,
25
- normalized: normalizeWhitespace(raw),
26
- regex
27
- };
28
- }
29
- const BOOLEAN_ATTRS = /* @__PURE__ */ new Set([
30
- "disabled",
31
- "expanded",
32
- "active",
33
- "selected",
34
- "busy",
35
- "hidden"
36
- ]);
37
- /**
38
- * Parses a template: a YAML sequence of `- role "name" [attr]` items, `key: text` values, nested
39
- * sequences under `key:`, `- text: …` runs and `- /url:` / `- /children:` properties. A common
40
- * indentation (template literals) is ignored, as are blank lines and `#` comments.
41
- */
42
- function parseAriaTemplate(text) {
43
- const source = text.split(/\r?\n/);
44
- let minIndent = Infinity;
45
- for (let i = 0; i < source.length; i++) {
46
- const line = source[i];
47
- const trimmed = line.trim();
48
- if (trimmed === "" || trimmed.startsWith("#")) continue;
49
- const indent = line.length - line.trimStart().length;
50
- if (line.slice(0, indent).includes(" ")) throw new AriaTemplateError("Tabs cannot be used for indentation", i, line);
51
- if (indent < minIndent) minIndent = indent;
52
- }
53
- const fragment = {
54
- kind: "role",
55
- role: "fragment",
56
- name: null,
57
- attrs: [],
58
- url: null,
59
- mode: null,
60
- children: []
61
- };
62
- if (minIndent === Infinity) throw new AriaTemplateError("The aria snapshot template is empty", 0, text);
63
- const stack = [{
64
- indent: -1,
65
- node: fragment,
66
- line: -1
67
- }];
68
- for (let i = 0; i < source.length; i++) {
69
- const line = source[i];
70
- const trimmed = line.trim();
71
- if (trimmed === "" || trimmed.startsWith("#")) continue;
72
- const indent = line.length - line.trimStart().length - minIndent;
73
- if (trimmed !== "-" && !trimmed.startsWith("- ")) throw new AriaTemplateError("Aria snapshot must be a YAML sequence, elements starting with \"-\"", i, line, indent + minIndent);
74
- while (stack[stack.length - 1].indent >= indent) stack.pop();
75
- const parent = stack[stack.length - 1];
76
- if (parent.node === null) throw new AriaTemplateError(`"- text:" on line ${parent.line + 1} cannot have children`, i, line, indent + minIndent);
77
- const item = trimmed.slice(2).trimStart();
78
- const column = line.length - item.length;
79
- const child = parseItem(item, parent.node, i, line, column);
80
- if (child !== void 0) stack.push({
81
- indent,
82
- node: child,
83
- line: i
84
- });
85
- }
86
- if (fragment.children.length === 1 && (fragment.mode === null || fragment.mode === "contain") && fragment.url === null) return fragment.children[0];
87
- return fragment;
88
- }
89
- /** One sequence item; returns the node that following deeper items nest under (null: a text item). */
90
- function parseItem(item, parent, lineNo, line, column) {
91
- const fail = (message, offset) => {
92
- throw new AriaTemplateError(message, lineNo, line, column + offset);
93
- };
94
- if (item === "") fail("Empty sequence item", 0);
95
- if (item.startsWith("/")) {
96
- const colon = item.indexOf(":");
97
- if (colon < 0) fail("Property should be written `/name: value`", item.length);
98
- const prop = item.slice(1, colon).trim();
99
- const value = parseScalar(item.slice(colon + 1), fail, colon + 1);
100
- if (prop === "children") {
101
- if (value !== "contain" && value !== "equal" && value !== "deep-equal") fail("Value of \"/children\" should be \"contain\", \"equal\" or \"deep-equal\"", colon + 1);
102
- parent.mode = value;
103
- } else if (prop === "url") parent.url = textValue(value);
104
- return;
105
- }
106
- let node;
107
- let rest = null;
108
- try {
109
- if (item[0] === "\"" || item[0] === "'") {
110
- const [key, end] = readQuoted(item, 0, fail);
111
- const after = item.slice(end).trimStart();
112
- if (after !== "" && after[0] !== ":") fail("Unexpected input after the quoted key", end);
113
- if (after !== "") rest = after.slice(1);
114
- if (key === "text" && rest !== null) return textItem(parent, rest, fail, item.length - rest.length);
115
- node = new KeyParser(key).parse(false);
116
- } else {
117
- if (/^text:(\s|$)/.test(item)) return textItem(parent, item.slice(5), fail, 5);
118
- const parser = new KeyParser(item);
119
- node = parser.parse(true);
120
- if (parser.pos < item.length) rest = item.slice(parser.pos + 1);
121
- }
122
- } catch (error) {
123
- if (error instanceof KeyError) fail(error.message, item[0] === "\"" || item[0] === "'" ? 0 : error.pos);
124
- throw error;
125
- }
126
- if (rest !== null && rest.trim() !== "") node.children.push({
127
- kind: "text",
128
- text: textValue(parseScalar(rest, fail, item.length - rest.length))
129
- });
130
- parent.children.push(node);
131
- return node;
132
- }
133
- function textItem(parent, rest, fail, offset) {
134
- parent.children.push({
135
- kind: "text",
136
- text: textValue(parseScalar(rest, fail, offset))
137
- });
138
- return null;
139
- }
140
- /** A YAML scalar after `key:`: double- or single-quoted, or plain (to a ` #` comment). */
141
- function parseScalar(text, fail, offset) {
142
- const lead = text.length - text.trimStart().length;
143
- const value = text.trim();
144
- if (value[0] === "\"" || value[0] === "'") {
145
- const [unquoted, end] = readQuoted(value, 0, (m, o) => fail(m, offset + lead + o));
146
- const after = value.slice(end).trim();
147
- if (after !== "" && !after.startsWith("#")) fail("Unexpected input after the quoted value", offset + lead + end);
148
- return unquoted;
149
- }
150
- if (value === "|" || value === ">" || value.startsWith("|") || value.startsWith(">")) fail("Block scalars are not supported in aria snapshot templates", offset + lead);
151
- const comment = value.search(/\s#/);
152
- return comment >= 0 ? value.slice(0, comment).trim() : value;
153
- }
154
- /** A YAML double-quoted (JSON-like escapes) or single-quoted (`''`) scalar starting at `start`. */
155
- function readQuoted(text, start, fail) {
156
- const q = text[start];
157
- let out = "";
158
- for (let i = start + 1; i < text.length; i++) {
159
- const ch = text[i];
160
- if (q === "'") {
161
- if (ch === "'") {
162
- if (text[i + 1] === "'") {
163
- out += "'";
164
- i++;
165
- continue;
166
- }
167
- return [out, i + 1];
168
- }
169
- out += ch;
170
- continue;
171
- }
172
- if (ch === "\"") return [out, i + 1];
173
- if (ch === "\\") {
174
- const next = text[++i];
175
- if (next === "n") out += "\n";
176
- else if (next === "t") out += " ";
177
- else if (next === "u") {
178
- out += String.fromCharCode(parseInt(text.slice(i + 1, i + 5), 16));
179
- i += 4;
180
- } else out += next ?? "";
181
- continue;
182
- }
183
- out += ch;
184
- }
185
- return fail("Unterminated string", text.length);
186
- }
187
- var KeyError = class extends Error {
188
- pos;
189
- constructor(message, pos) {
190
- super(message);
191
- this.pos = pos;
192
- }
193
- };
194
- var KeyParser = class {
195
- pos = 0;
196
- input;
197
- constructor(input) {
198
- this.input = input;
199
- }
200
- peek() {
201
- return this.input[this.pos] ?? "";
202
- }
203
- eof() {
204
- return this.pos >= this.input.length;
205
- }
206
- skipWhitespace() {
207
- while (!this.eof() && /\s/.test(this.peek())) this.pos++;
208
- }
209
- atColon() {
210
- return this.peek() === ":" && (this.pos + 1 >= this.input.length || /\s/.test(this.input[this.pos + 1]));
211
- }
212
- readIdentifier(type) {
213
- if (this.eof()) throw new KeyError(`Unexpected end of input when expecting ${type}`, this.pos);
214
- const start = this.pos;
215
- while (!this.eof() && /[a-zA-Z]/.test(this.peek())) this.pos++;
216
- if (this.pos === start) throw new KeyError(`Expected ${type}`, this.pos);
217
- return this.input.slice(start, this.pos);
218
- }
219
- readString() {
220
- let result = "";
221
- while (!this.eof()) {
222
- const ch = this.input[this.pos++];
223
- if (ch === "\\") {
224
- const next = this.input[this.pos++] ?? "";
225
- if (next === "n") result += "\n";
226
- else if (next === "t") result += " ";
227
- else if (next === "u") {
228
- result += String.fromCharCode(parseInt(this.input.slice(this.pos, this.pos + 4), 16));
229
- this.pos += 4;
230
- } else result += next;
231
- } else if (ch === "\"") return result;
232
- else result += ch;
233
- }
234
- throw new KeyError("Unterminated string", this.pos);
235
- }
236
- readRegex() {
237
- const start = this.pos;
238
- let result = "";
239
- let escaped = false;
240
- let insideClass = false;
241
- while (!this.eof()) {
242
- const ch = this.input[this.pos++];
243
- if (escaped) {
244
- result += ch;
245
- escaped = false;
246
- } else if (ch === "\\") {
247
- escaped = true;
248
- result += ch;
249
- } else if (ch === "/" && !insideClass) try {
250
- return new RegExp(result);
251
- } catch (error) {
252
- throw new KeyError(`Invalid regular expression: ${error.message}`, start);
253
- }
254
- else if (ch === "[") {
255
- insideClass = true;
256
- result += ch;
257
- } else if (ch === "]" && insideClass) {
258
- result += ch;
259
- insideClass = false;
260
- } else result += ch;
261
- }
262
- throw new KeyError("Unterminated regex", this.pos);
263
- }
264
- parse(stopAtColon) {
265
- this.skipWhitespace();
266
- const role = this.readIdentifier("role");
267
- this.skipWhitespace();
268
- let name = null;
269
- if (this.peek() === "\"") {
270
- this.pos++;
271
- name = normalizeWhitespace(this.readString());
272
- } else if (this.peek() === "/") {
273
- this.pos++;
274
- name = this.readRegex();
275
- }
276
- const node = {
277
- kind: "role",
278
- role,
279
- name: name === "" ? null : name,
280
- attrs: [],
281
- url: null,
282
- mode: null,
283
- children: []
284
- };
285
- for (;;) {
286
- this.skipWhitespace();
287
- if (this.peek() !== "[") break;
288
- this.pos++;
289
- this.skipWhitespace();
290
- const errorPos = this.pos;
291
- const attr = this.readIdentifier("attribute");
292
- this.skipWhitespace();
293
- let value = "";
294
- if (this.peek() === "=") {
295
- this.pos++;
296
- this.skipWhitespace();
297
- while (this.peek() !== "]" && !/\s/.test(this.peek()) && !this.eof()) value += this.input[this.pos++];
298
- }
299
- this.skipWhitespace();
300
- if (this.peek() !== "]") throw new KeyError("Expected ]", this.pos);
301
- this.pos++;
302
- node.attrs.push([attr, checkAttribute(attr, value || "true", errorPos)]);
303
- }
304
- this.skipWhitespace();
305
- if (stopAtColon && this.atColon()) return node;
306
- if (!this.eof()) throw new KeyError(stopAtColon ? "Unexpected input (a key ends with \":\" and a space)" : "Unexpected input", this.pos);
307
- return node;
308
- }
309
- };
310
- /** Playwright's `_applyAttribute` checks, plus our snapshot's `current`, `busy` and `hidden`. */
311
- function checkAttribute(attr, value, pos) {
312
- if (attr === "checked" || attr === "pressed") {
313
- if (value !== "true" && value !== "false" && value !== "mixed") throw new KeyError(`Value of "${attr}" attribute must be a boolean or "mixed"`, pos);
314
- return value;
315
- }
316
- if (BOOLEAN_ATTRS.has(attr)) {
317
- if (value !== "true" && value !== "false") throw new KeyError(`Value of "${attr}" attribute must be a boolean`, pos);
318
- return value;
319
- }
320
- if (attr === "level") {
321
- if (Number.isNaN(Number(value))) throw new KeyError("Value of \"level\" attribute must be a number", pos);
322
- return String(Number(value));
323
- }
324
- if (attr === "current") return value;
325
- throw new KeyError(`Unsupported attribute [${attr}]`, pos);
326
- }
327
- function toMatchNode(node) {
328
- const children = [];
329
- if (node.value !== null && node.value !== "") children.push(normalizeWhitespace(node.value));
330
- for (let i = 0; i < node.children.length; i++) {
331
- const c = node.children[i];
332
- children.push(typeof c === "string" ? normalizeWhitespace(c) : toMatchNode(c));
333
- }
334
- const states = /* @__PURE__ */ new Map();
335
- for (let i = 0; i < node.props.length; i++) {
336
- const prop = node.props[i].slice(1, -1);
337
- const eq = prop.indexOf("=");
338
- if (eq < 0) states.set(prop, "true");
339
- else states.set(prop.slice(0, eq), prop.slice(eq + 1));
340
- }
341
- return {
342
- role: node.role,
343
- name: normalizeWhitespace(node.name),
344
- states,
345
- url: node.url,
346
- children,
347
- props: node.props
348
- };
349
- }
350
- /** A state's value when the snapshot omits it: what the omission means for that role. */
351
- function stateOf(node, attr) {
352
- const value = node.states.get(attr);
353
- if (value !== void 0) return value;
354
- switch (attr) {
355
- case "checked": return roleSupportsProp(node.role, "aria-checked") ? "false" : void 0;
356
- case "disabled":
357
- case "selected":
358
- case "active":
359
- case "busy":
360
- case "hidden":
361
- case "current": return "false";
362
- }
363
- }
364
- function attrsMatch(node, t) {
365
- for (let i = 0; i < t.attrs.length; i++) {
366
- const [attr, expected] = t.attrs[i];
367
- const actual = stateOf(node, attr);
368
- if (attr === "current" && expected === "true") {
369
- if (actual === void 0 || actual === "false") return false;
370
- } else if (actual !== expected) return false;
371
- }
372
- return true;
373
- }
374
- function matchesName(name, template) {
375
- if (template === null) return true;
376
- if (name === "") return false;
377
- if (typeof template === "string") return name === template;
378
- return template.test(name);
379
- }
380
- function matchesText(text, template) {
381
- if (template === null || template.normalized === "") return true;
382
- if (!text) return false;
383
- if (text === template.normalized || text === template.raw) return true;
384
- return template.regex !== null && template.regex.test(text);
385
- }
386
- function headerMatches(node, t) {
387
- return (t.role === "fragment" || t.role === node.role) && attrsMatch(node, t) && matchesName(node.name, t.name) && matchesText(node.url, t.url);
388
- }
389
- function matchesNode(node, t, deepEqual) {
390
- if (typeof node === "string") return t.kind === "text" && matchesText(node, t.text);
391
- if (t.kind !== "role" || !headerMatches(node, t)) return false;
392
- if (t.mode === "contain") return containsList(node.children, t.children);
393
- if (t.mode === "equal") return listEqual(node.children, t.children, false);
394
- if (t.mode === "deep-equal" || deepEqual) return listEqual(node.children, t.children, true);
395
- return containsList(node.children, t.children);
396
- }
397
- function listEqual(children, templates, deepEqual) {
398
- if (templates.length !== children.length) return false;
399
- for (let i = 0; i < templates.length; i++) if (!matchesNode(children[i], templates[i], deepEqual)) return false;
400
- return true;
401
- }
402
- function containsList(children, templates) {
403
- if (templates.length > children.length) return false;
404
- let c = 0;
405
- for (let i = 0; i < templates.length; i++) {
406
- while (c < children.length && !matchesNode(children[c], templates[i], false)) c++;
407
- if (c === children.length) return false;
408
- c++;
409
- }
410
- return true;
411
- }
412
- function matchesDeep(node, t) {
413
- if (matchesNode(node, t, false)) return true;
414
- if (typeof node === "string") return false;
415
- for (let i = 0; i < node.children.length; i++) if (matchesDeep(node.children[i], t)) return true;
416
- return false;
417
- }
418
- const MAX_TEXT = 100;
419
- function textRepr(value) {
420
- return value.regex !== null ? value.raw : yamlValue(value.normalized);
421
- }
422
- function templateKey(t) {
423
- let key = t.role;
424
- if (typeof t.name === "string") key += " " + quote(t.name);
425
- else if (t.name !== null) key += ` /${t.name.source}/`;
426
- for (let i = 0; i < t.attrs.length; i++) key += t.attrs[i][1] === "true" ? ` [${t.attrs[i][0]}]` : ` [${t.attrs[i][0]}=${t.attrs[i][1]}]`;
427
- return key;
428
- }
429
- function receivedKey(node) {
430
- let key = node.role;
431
- if (node.name !== "") key += " " + quote(truncate(node.name, MAX_TEXT));
432
- for (let i = 0; i < node.props.length; i++) key += " " + node.props[i];
433
- return key;
434
- }
435
- function isInline(t) {
436
- return t.url === null && t.mode === null && t.children.length === 1 && t.children[0].kind === "text";
437
- }
438
- /** The template in canonical form, one line per node. */
439
- function renderTemplate(t, indent, lines) {
440
- if (t.kind === "text") {
441
- lines.push(`${indent}- text: ${textRepr(t.text)}`);
442
- return;
443
- }
444
- const key = templateKey(t);
445
- if (isInline(t)) {
446
- lines.push(`${indent}- ${key}: ${textRepr(t.children[0].text)}`);
447
- return;
448
- }
449
- if (t.children.length === 0 && t.url === null && t.mode === null) {
450
- lines.push(`${indent}- ${key}`);
451
- return;
452
- }
453
- lines.push(`${indent}- ${key}:`);
454
- const inner = indent + " ";
455
- if (t.url !== null) lines.push(`${inner}- /url: ${textRepr(t.url)}`);
456
- if (t.mode !== null) lines.push(`${inner}- /children: ${t.mode}`);
457
- for (let i = 0; i < t.children.length; i++) renderTemplate(t.children[i], inner, lines);
458
- }
459
- /** Scores how well tree nodes fit template nodes, to pick what a failing template is compared with. */
460
- var Scorer = class {
461
- memo = /* @__PURE__ */ new Map();
462
- score(t, node) {
463
- if (t.kind === "text") return typeof node === "string" ? matchesText(node, t.text) ? 3 : 1 : 0;
464
- if (typeof node === "string" || t.role !== "fragment" && t.role !== node.role) return 0;
465
- let byNode = this.memo.get(t);
466
- if (byNode === void 0) this.memo.set(t, byNode = /* @__PURE__ */ new Map());
467
- const cached = byNode.get(node);
468
- if (cached !== void 0) return cached;
469
- let score = 2;
470
- score += t.name === null ? 1 : matchesName(node.name, t.name) ? 2 : 0;
471
- if (attrsMatch(node, t)) score += 1;
472
- if (t.url !== null && matchesText(node.url, t.url)) score += 1;
473
- score += this.scoreList(t.children, node.children);
474
- byNode.set(node, score);
475
- return score;
476
- }
477
- scoreList(templates, children) {
478
- const aligned = this.align(templates, children);
479
- let score = 0;
480
- for (let i = 0; i < templates.length; i++) if (aligned[i] !== null) score += this.score(templates[i], aligned[i]);
481
- return score;
482
- }
483
- /** For each template, in order, the best-scoring child after the previous one's (or null). */
484
- align(templates, children) {
485
- const out = [];
486
- let from = 0;
487
- for (let i = 0; i < templates.length; i++) {
488
- let best = -1;
489
- let bestScore = 0;
490
- for (let j = from; j < children.length; j++) {
491
- const s = this.score(templates[i], children[j]);
492
- if (s > bestScore) {
493
- best = j;
494
- bestScore = s;
495
- }
496
- }
497
- if (best < 0) out.push(null);
498
- else {
499
- out.push(children[best]);
500
- from = best + 1;
501
- }
502
- }
503
- return out;
504
- }
505
- /** The tree node rendered in the template's shape: matching parts print as the template does. */
506
- project(t, node, indent, lines) {
507
- if (t.kind === "text") {
508
- const text = node;
509
- lines.push(`${indent}- text: ${matchesText(text, t.text) ? textRepr(t.text) : yamlValue(truncate(text, MAX_TEXT))}`);
510
- return;
511
- }
512
- const n = node;
513
- const key = headerMatches(n, t) ? templateKey(t) : receivedKey(n);
514
- const aligned = this.align(t.children, n.children);
515
- if (isInline(t)) {
516
- const text = aligned[0];
517
- const tt = t.children[0].text;
518
- lines.push(text === null ? `${indent}- ${key}` : `${indent}- ${key}: ${matchesText(text, tt) ? textRepr(tt) : yamlValue(truncate(text, MAX_TEXT))}`);
519
- return;
520
- }
521
- if (t.children.length === 0 && t.url === null && t.mode === null) {
522
- lines.push(`${indent}- ${key}`);
523
- return;
524
- }
525
- lines.push(`${indent}- ${key}:`);
526
- const inner = indent + " ";
527
- if (t.url !== null) lines.push(`${inner}- /url: ${matchesText(n.url, t.url) ? textRepr(t.url) : yamlValue(n.url ?? "")}`);
528
- if (t.mode !== null) lines.push(`${inner}- /children: ${t.mode}`);
529
- for (let i = 0; i < t.children.length; i++) if (aligned[i] !== null) this.project(t.children[i], aligned[i], inner, lines);
530
- }
531
- };
532
- function forEachNode(node, visit) {
533
- visit(node);
534
- for (let i = 0; i < node.children.length; i++) {
535
- const c = node.children[i];
536
- if (typeof c === "string") visit(c);
537
- else forEachNode(c, visit);
538
- }
539
- }
540
- /** The closest part of the tree to `t`, projected onto its shape. */
541
- function closestLines(root, t) {
542
- const scorer = new Scorer();
543
- const lines = [];
544
- if (t.kind === "role" && t.role === "fragment") {
545
- let best = null;
546
- let bestScore = 0;
547
- forEachNode(root, (node) => {
548
- if (typeof node === "string") return;
549
- const s = scorer.scoreList(t.children, node.children);
550
- if (s > bestScore) {
551
- best = node;
552
- bestScore = s;
553
- }
554
- });
555
- if (best !== null) {
556
- const aligned = scorer.align(t.children, best.children);
557
- for (let i = 0; i < t.children.length; i++) if (aligned[i] !== null) scorer.project(t.children[i], aligned[i], "", lines);
558
- }
559
- return lines;
560
- }
561
- let best = null;
562
- let bestScore = 0;
563
- forEachNode(root, (node) => {
564
- const s = scorer.score(t, node);
565
- if (s > bestScore) {
566
- best = node;
567
- bestScore = s;
568
- }
569
- });
570
- if (best !== null) scorer.project(t, best, "", lines);
571
- return lines;
572
- }
573
- /**
574
- * A run of N removed lines followed by N added ones becomes N `-`/`+` pairs: the projection has
575
- * the template's shape, so the i-th removed and added lines are the same template node.
576
- */
577
- function pairChanges(ops) {
578
- const out = [];
579
- for (let i = 0; i < ops.length;) {
580
- if (ops[i].kind === "=") {
581
- out.push(ops[i++]);
582
- continue;
583
- }
584
- let r = i;
585
- while (r < ops.length && ops[r].kind === "-") r++;
586
- let a = r;
587
- while (a < ops.length && ops[a].kind === "+") a++;
588
- if (r - i === a - r) for (let k = 0; k < r - i; k++) out.push(ops[i + k], ops[r + k]);
589
- else for (let k = i; k < a; k++) out.push(ops[k]);
590
- i = a;
591
- }
592
- return out;
593
- }
594
- /** Line budget for the received snapshot in a failure message. */
595
- const RECEIVED_MAX_LINES = 100;
596
- /**
597
- * Matches the accessibility tree of `container` (an element prints itself, a body, document or
598
- * fragment its children) against an aria snapshot template, with Playwright's partial matching.
599
- * Throws AriaTemplateError for an invalid template.
600
- */
601
- function matchAriaSnapshot(container, template) {
602
- const t = parseAriaTemplate(template);
603
- const tree = ariaSnapshotTree(container, { urls: true });
604
- const children = [];
605
- for (let i = 0; i < tree.length; i++) {
606
- const c = tree[i];
607
- children.push(typeof c === "string" ? normalizeWhitespace(c) : toMatchNode(c));
608
- }
609
- const root = {
610
- role: "fragment",
611
- name: "",
612
- states: /* @__PURE__ */ new Map(),
613
- url: null,
614
- children,
615
- props: []
616
- };
617
- const pass = matchesDeep(root, t);
618
- const expectedLines = () => {
619
- const lines = [];
620
- if (t.kind === "role" && t.role === "fragment") {
621
- if (t.mode !== null) lines.push(`- /children: ${t.mode}`);
622
- for (let i = 0; i < t.children.length; i++) renderTemplate(t.children[i], "", lines);
623
- } else renderTemplate(t, "", lines);
624
- return lines;
625
- };
626
- return {
627
- pass,
628
- expected: () => expectedLines().join("\n"),
629
- diff: () => pairChanges(diffLines(expectedLines(), closestLines(root, t))),
630
- received: () => ariaSnapshot(container, {
631
- collapseAfter: Infinity,
632
- maxLines: envMaxLines() ?? RECEIVED_MAX_LINES
633
- })
634
- };
635
- }
636
-
637
- // src/agent.ts
638
- /** Line budget for "what changed" in a failure report. */
639
- const CHANGES_MAX_LINES = 40;
640
- /** Forget the previous snapshot: call when a test starts. */
641
- function resetFailureSnapshot(document) {
642
- resetBodySnapshot(document);
643
- }
644
- /** Snapshot `document.body` for a failure report; null when `CTRL_DOM_DEBUG` is unset or there is no body. */
645
- function captureFailureSnapshot(document) {
646
- const format = envDebugFormat();
647
- const body = document?.body;
648
- if (format === null || body == null || body[$impl] === void 0) return null;
649
- if (format === "compact") {
650
- const html = prettyDOM(body, void 0, { format: "compact" });
651
- return {
652
- format,
653
- text: String(html),
654
- full: "",
655
- previous: void 0
656
- };
657
- }
658
- const previous = lastBodySnapshot(document);
659
- const { lines, empty } = ariaSnapshotLines(body);
660
- const full = empty ?? lines.join("\n");
661
- return {
662
- format,
663
- text: empty ?? budgetLines(lines, envMaxLines() ?? 100).join("\n"),
664
- full,
665
- previous
666
- };
667
- }
668
- /**
669
- * The report appended to a failing test's error. A snapshot the error message already contains
670
- * (a failed query under `CTRL_DOM_DEBUG=aria` prints one) is not repeated.
671
- */
672
- function formatFailureSnapshot(snapshot, errorMessage) {
673
- if (snapshot.format === "compact") return `DOM of <body> when the test failed (CTRL_DOM_DEBUG=compact):\n${snapshot.text}`;
674
- if (errorMessage.includes(snapshot.text)) return "Accessibility snapshot of <body> when the test failed: the same as above.";
675
- let report = `Accessibility snapshot of <body> when the test failed (CTRL_DOM_DEBUG=aria):\n${snapshot.text}`;
676
- if (snapshot.previous !== void 0) {
677
- if (snapshot.previous === snapshot.full) report += "\n\nUnchanged since the previous snapshot in this test.";
678
- else report += `\n\nChanges since the previous snapshot in this test:\n${budgetLines(diffAriaSnapshots(snapshot.previous, snapshot.full).split("\n"), CHANGES_MAX_LINES).join("\n")}`;
679
- }
680
- return report;
681
- }
682
- /**
683
- * Append `text` to an error's message (and to its `stack`, which V8 formats with the message
684
- * once read). Works on Error objects and on the plain serialized errors test runners keep.
685
- */
686
- function appendToErrorMessage(error, text) {
687
- if (error === null || typeof error !== "object") return false;
688
- const e = error;
689
- const message = typeof e.message === "string" ? e.message : "";
690
- let stack;
691
- try {
692
- stack = e.stack;
693
- } catch {
694
- stack = void 0;
695
- }
696
- const next = message === "" ? text : `${message}\n\n${text}`;
697
- try {
698
- e.message = next;
699
- if (typeof stack === "string") {
700
- const at = message === "" ? -1 : stack.indexOf(message);
701
- if (at >= 0) e.stack = stack.slice(0, at) + next + stack.slice(at + message.length);
702
- else {
703
- const eol = stack.indexOf("\n");
704
- e.stack = eol < 0 ? `${stack}\n\n${text}` : `${stack.slice(0, eol)}\n\n${text}${stack.slice(eol)}`;
705
- }
706
- }
707
- } catch {
708
- return false;
709
- }
710
- return true;
711
- }
712
-
713
- export { AriaTemplateError, appendToErrorMessage, captureFailureSnapshot, envDebugFormat, formatFailureSnapshot, matchAriaSnapshot, parseAriaTemplate, resetFailureSnapshot };
8
+ Unchanged since the previous snapshot in this test.`:n+=`\n\nChanges since the previous snapshot in this test:\n${r(l(e.previous,e.full).split(`
9
+ `),40).join(`
10
+ `)}`),n}function appendToErrorMessage(e,t){if(typeof e!=`object`||!e)return!1;let n=e,r=typeof n.message==`string`?n.message:``,i;try{i=n.stack}catch{i=void 0}let a=r===``?t:`${r}\n\n${t}`;try{if(n.message=a,typeof i==`string`){let e=r===``?-1:i.indexOf(r);if(e>=0)n.stack=i.slice(0,e)+a+i.slice(e+r.length);else{let e=i.indexOf(`
11
+ `);n.stack=e<0?`${i}\n\n${t}`:`${i.slice(0,e)}\n\n${t}${i.slice(e)}`}}}catch{return!1}return!0}export{AriaTemplateError,appendToErrorMessage,captureFailureSnapshot,d as envDebugFormat,formatFailureSnapshot,matchAriaSnapshot,parseAriaTemplate,resetFailureSnapshot};