@vielzeug/assay 26.10.6 → 26.10.9
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/README.md +6 -0
- package/dist/assay.cjs +1 -1
- package/dist/assay.cjs.map +1 -1
- package/dist/assay.iife.js +1 -1
- package/dist/assay.iife.js.map +1 -1
- package/dist/assay.js +1 -1
- package/dist/assay.js.map +1 -1
- package/dist/dom.cjs +2 -0
- package/dist/dom.cjs.map +1 -0
- package/dist/dom.d.ts +22 -0
- package/dist/dom.d.ts.map +1 -0
- package/dist/dom.js +2 -0
- package/dist/dom.js.map +1 -0
- package/dist/form-internals.cjs +2 -0
- package/dist/form-internals.cjs.map +1 -0
- package/dist/form-internals.d.ts +19 -0
- package/dist/form-internals.d.ts.map +1 -0
- package/dist/form-internals.js +2 -0
- package/dist/form-internals.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -25,6 +25,12 @@ await eventually(() => expect(view.get('.status').textContent).toBe('Saved'), {
|
|
|
25
25
|
});
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
- `walkFlatTree()` traverses descendants across slot boundaries in jsdom.
|
|
31
|
+
- `installFormInternalsPolyfill()` supplies jsdom form-association behavior and returns a cleanup function.
|
|
32
|
+
- `within()`, event helpers, and async waits work with framework-rendered or vanilla DOM.
|
|
33
|
+
|
|
28
34
|
## Documentation
|
|
29
35
|
|
|
30
36
|
- [Overview](https://vielzeug.dev/assay/)
|
package/dist/assay.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/arsenal");var AssayError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},AssayQueryError=class extends AssayError{},AssayTimeoutError=class extends AssayError{},dispatch=(e,t)=>e.dispatchEvent(t),fireBlur=(e,t={})=>dispatch(e,new FocusEvent(`blur`,t)),fireChange=(e,t={})=>dispatch(e,new Event(`change`,{bubbles:!0,...t})),fireClick=(e,t={})=>dispatch(e,new MouseEvent(`click`,{bubbles:!0,cancelable:!0,...t})),fireCustom=(e,t,n={})=>dispatch(e,new CustomEvent(t,{bubbles:!0,cancelable:!0,composed:!1,...n})),fireFocus=(e,t={})=>dispatch(e,new FocusEvent(`focus`,t)),fireInput=(e,t={})=>dispatch(e,new InputEvent(`input`,{bubbles:!0,...t})),fireKeyDown=(e,t={})=>dispatch(e,new KeyboardEvent(`keydown`,{bubbles:!0,cancelable:!0,...t})),fireKeyUp=(e,t={})=>dispatch(e,new KeyboardEvent(`keyup`,{bubbles:!0,cancelable:!0,...t})),fireSubmit=(e,t={})=>dispatch(e,new SubmitEvent(`submit`,{bubbles:!0,cancelable:!0,...t})),describeRoot=e=>e instanceof Element?e.outerHTML.slice(0,500):e instanceof ShadowRoot?`<shadow-root>${e.innerHTML.slice(0,500)}</shadow-root>`:e.nodeName,requireMatch=(e,t,n)=>{if(e)return e;throw new AssayQueryError(`Unable to find ${t} within ${describeRoot(n)}.`)},query=(e,t)=>e.querySelector(t),queryAll=(e,t)=>Array.from(e.querySelectorAll(t)),queryByTestId=(e,t)=>queryAll(e,`[data-testid]`).find(e=>e.getAttribute(`data-testid`)===t)??null,queryAllByTestId=(e,t)=>queryAll(e,`[data-testid]`).filter(e=>e.getAttribute(`data-testid`)===t),queryByText=(e,t,n=`*`)=>{for(let r of e.querySelectorAll(n))if(r.textContent?.trim()===t)return r;return null},queryAllByText=(e,t,n=`*`)=>queryAll(e,n).filter(e=>e.textContent?.trim()===t);function queryInShadow(e,t){return e.shadowRoot?query(e.shadowRoot,t):null}function queryAllInShadow(e,t){return e.shadowRoot?queryAll(e.shadowRoot,t):[]}function queryPart(e,t){return queryAllInShadow(e,`[part]`).find(e=>e.getAttribute(`part`)?.split(/\s+/).includes(t))??null}function getSlotted(e,t){return Array.from(e.children).filter(e=>t===void 0?!e.getAttribute(`slot`):e.getAttribute(`slot`)===t)}function within(e){return{get:t=>requireMatch(query(e,t),`"${t}"`,e),getByTestId:t=>requireMatch(queryByTestId(e,t),`data-testid "${t}"`,e),getByText:(t,n=`*`)=>requireMatch(queryByText(e,t,n),`text "${t}" matching "${n}"`,e),query:t=>query(e,t),queryAll:t=>queryAll(e,t),queryAllByTestId:t=>queryAllByTestId(e,t),queryAllByText:(t,n=`*`)=>queryAllByText(e,t,n),queryByTestId:t=>queryByTestId(e,t),queryByText:(t,n=`*`)=>queryByText(e,t,n)}}var t=Symbol(`assay.deadline`),n=2147483647,now=()=>performance.now(),validateDuration=(e,t,r)=>{if(!Number.isFinite(t)||t>n||(r?t<0:t<=0))throw RangeError(`${e} must be a ${r?`non-negative`:`positive`} finite number no greater than ${n}`)},validateWait=(e,t)=>{validateDuration(`interval`,e,!1),validateDuration(`timeout`,t,!0)},runBounded=(n,r,i)=>new Promise((a,o)=>{if(i?.aborted){o((0,e.abortError)(i,`The operation was aborted.`));return}let s=!1,cleanup=()=>!s&&(s=!0,clearTimeout(c),i?.removeEventListener(`abort`,abort),!0),resolveOnce=e=>{cleanup()&&a(e)},rejectOnce=e=>{cleanup()&&o(e)},c=setTimeout(()=>rejectOnce(t),Math.max(0,r-now())),abort=()=>rejectOnce((0,e.abortError)(i,`The operation was aborted.`));i?.addEventListener(`abort`,abort,{once:!0});try{Promise.resolve(n()).then(resolveOnce,rejectOnce)}catch(e){rejectOnce(e)}}),delay=(t=0,n={})=>(validateDuration(`ms`,t,!0),(0,e.sleep)(t,n.signal));async function waitUntil(n,{interval:r=50,signal:i,timeout:a=1e3}={}){validateWait(r,a);let o=now()+a,s=!0;for(;;){if(i?.aborted)throw(0,e.abortError)(i,`The operation was aborted.`);if(!s&&now()>=o)throw new AssayTimeoutError(`waitUntil timed out after ${a}ms`);s=!1;let c;try{c=await runBounded(n,o,i)}catch(e){throw e===t?new AssayTimeoutError(`waitUntil timed out after ${a}ms`):e}if(c)return;let l=o-now();if(l<=0)throw new AssayTimeoutError(`waitUntil timed out after ${a}ms`);await(0,e.sleep)(Math.min(r,l),i)}}async function eventually(n,{interval:r=50,message:i,signal:a,timeout:o=1e3}={}){validateWait(r,o);let s=now()+o,c=!0,l;for(;;){if(a?.aborted)throw(0,e.abortError)(a,`The operation was aborted.`);if(!c&&now()>=s)break;c=!1;try{await runBounded(n,s,a);return}catch(n){if(a?.aborted)throw(0,e.abortError)(a,`The operation was aborted.`);if(n===t)break;l=n}let i=s-now();if(i<=0)break;await(0,e.sleep)(Math.min(r,i),a)}let u=`eventually timed out after ${o}ms`,d=i?`${i} (${u})`:u,f=l instanceof Error?l.message:l==null?``:String(l);throw new AssayTimeoutError(f?`${d}\n${f}`:d,{cause:l})}function waitForEvent(t,n,{signal:r,timeout:i=1e3}={}){return validateDuration(`timeout`,i,!0),new Promise((a,o)=>{if(r?.aborted){o((0,e.abortError)(r,`The operation was aborted.`));return}let dispose=()=>{clearTimeout(s),r?.removeEventListener(`abort`,onAbort),t.removeEventListener(n,onEvent)},onEvent=e=>{dispose(),a(e)},s=setTimeout(()=>{dispose(),o(new AssayTimeoutError(`waitForEvent: "${n}" timed out after ${i}ms`))},i),onAbort=()=>{dispose(),o((0,e.abortError)(r,`The operation was aborted.`))};t.addEventListener(n,onEvent,{once:!0}),r?.addEventListener(`abort`,onAbort,{once:!0})})}exports.AssayError=AssayError,exports.AssayQueryError=AssayQueryError,exports.AssayTimeoutError=AssayTimeoutError,exports.delay=delay,exports.dispatch=dispatch,exports.eventually=eventually,exports.fireBlur=fireBlur,exports.fireChange=fireChange,exports.fireClick=fireClick,exports.fireCustom=fireCustom,exports.fireFocus=fireFocus,exports.fireInput=fireInput,exports.fireKeyDown=fireKeyDown,exports.fireKeyUp=fireKeyUp,exports.fireSubmit=fireSubmit,exports.getSlotted=getSlotted,exports.queryAllInShadow=queryAllInShadow,exports.queryInShadow=queryInShadow,exports.queryPart=queryPart,exports.waitForEvent=waitForEvent,exports.waitUntil=waitUntil,exports.within=within;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/arsenal");var walkFlatTree=(e,t)=>{let n=e instanceof HTMLSlotElement?e.assignedElements({flatten:!0}):e.children;for(let e of Array.from(n))e instanceof HTMLSlotElement||t(e),walkFlatTree(e,t)},AssayError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},AssayQueryError=class extends AssayError{},AssayTimeoutError=class extends AssayError{},dispatch=(e,t)=>e.dispatchEvent(t),fireBlur=(e,t={})=>dispatch(e,new FocusEvent(`blur`,t)),fireChange=(e,t={})=>dispatch(e,new Event(`change`,{bubbles:!0,...t})),fireClick=(e,t={})=>dispatch(e,new MouseEvent(`click`,{bubbles:!0,cancelable:!0,...t})),fireCustom=(e,t,n={})=>dispatch(e,new CustomEvent(t,{bubbles:!0,cancelable:!0,composed:!1,...n})),fireFocus=(e,t={})=>dispatch(e,new FocusEvent(`focus`,t)),fireInput=(e,t={})=>dispatch(e,new InputEvent(`input`,{bubbles:!0,...t})),fireKeyDown=(e,t={})=>dispatch(e,new KeyboardEvent(`keydown`,{bubbles:!0,cancelable:!0,...t})),fireKeyUp=(e,t={})=>dispatch(e,new KeyboardEvent(`keyup`,{bubbles:!0,cancelable:!0,...t})),fireSubmit=(e,t={})=>dispatch(e,new SubmitEvent(`submit`,{bubbles:!0,cancelable:!0,...t})),installFormInternalsPolyfill=()=>{if(typeof ElementInternals>`u`)return()=>{};let e=Symbol.for(`vielzeug.assay.formInternalsPolyfillInstalled`),t=globalThis;if(t[e])return()=>{};t[e]=!0;let n=[],r=ElementInternals.prototype,i=new WeakMap,a=new WeakMap,o=new WeakMap,patchProto=(e,t)=>{e in r||(Object.defineProperty(r,e,t),n.push(()=>delete r[e]))},isValid=e=>{let t=i.get(e);return!t||!Object.values(t.flags).some(Boolean)};patchProto(`setFormValue`,{configurable:!0,value:function(e){let t=o.get(this);t&&a.set(t,e)},writable:!0}),patchProto(`setValidity`,{configurable:!0,value:function(e={},t=``){if(Object.values(e).some(Boolean)&&!t)throw TypeError(`Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if one or more flags in the first argument are true.`);i.set(this,{flags:e,message:t})},writable:!0}),patchProto(`checkValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`reportValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`validationMessage`,{configurable:!0,get(){return isValid(this)?``:i.get(this)?.message??``}}),patchProto(`validity`,{configurable:!0,get(){let e=i.get(this);return{badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:isValid(this),valueMissing:!1,...e?.flags??{}}}}),patchProto(`states`,{configurable:!0,get:function(){return this._states??=new Set,this._states}});let s=HTMLElement.prototype.attachInternals;HTMLElement.prototype.attachInternals=function(...e){let t=s.apply(this,e);return o.set(t,this),Object.defineProperties(this,{checkValidity:{configurable:!0,value:()=>t.checkValidity()},reportValidity:{configurable:!0,value:()=>t.reportValidity()},validationMessage:{configurable:!0,get:()=>t.validationMessage},validity:{configurable:!0,get:()=>t.validity}}),t},n.push(()=>{HTMLElement.prototype.attachInternals=s});let appendFormValue=(e,t,n)=>{if(n instanceof FormData){for(let[t,r]of n.entries())e.append(t,r);return}e.append(t,n)},c=globalThis.FormData;globalThis.FormData=class FormDataWithFormAssociatedElements extends c{constructor(e,t){super(e,t),e instanceof HTMLFormElement&&walkFlatTree(e,e=>{let t=e.getAttribute(`name`),n=a.get(e);t&&n!=null&&!e.hasAttribute(`disabled`)&&appendFormValue(this,t,n)})}},n.push(()=>{globalThis.FormData=c});let l=HTMLFormElement.prototype.reset;return HTMLFormElement.prototype.reset=function(...e){l.apply(this,e),walkFlatTree(this,e=>{e.formResetCallback?.()})},n.push(()=>{HTMLFormElement.prototype.reset=l}),()=>{for(let e of n)e();n.length=0,t[e]=!1}},describeRoot=e=>e instanceof Element?e.outerHTML.slice(0,500):e instanceof ShadowRoot?`<shadow-root>${e.innerHTML.slice(0,500)}</shadow-root>`:e.nodeName,requireMatch=(e,t,n)=>{if(e)return e;throw new AssayQueryError(`Unable to find ${t} within ${describeRoot(n)}.`)},query=(e,t)=>e.querySelector(t),queryAll=(e,t)=>Array.from(e.querySelectorAll(t)),queryByTestId=(e,t)=>queryAll(e,`[data-testid]`).find(e=>e.getAttribute(`data-testid`)===t)??null,queryAllByTestId=(e,t)=>queryAll(e,`[data-testid]`).filter(e=>e.getAttribute(`data-testid`)===t),queryByText=(e,t,n=`*`)=>{for(let r of e.querySelectorAll(n))if(r.textContent?.trim()===t)return r;return null},queryAllByText=(e,t,n=`*`)=>queryAll(e,n).filter(e=>e.textContent?.trim()===t);function queryInShadow(e,t){return e.shadowRoot?query(e.shadowRoot,t):null}function queryAllInShadow(e,t){return e.shadowRoot?queryAll(e.shadowRoot,t):[]}function queryPart(e,t){return queryAllInShadow(e,`[part]`).find(e=>e.getAttribute(`part`)?.split(/\s+/).includes(t))??null}function getSlotted(e,t){return Array.from(e.children).filter(e=>t===void 0?!e.getAttribute(`slot`):e.getAttribute(`slot`)===t)}function within(e){return{get:t=>requireMatch(query(e,t),`"${t}"`,e),getByTestId:t=>requireMatch(queryByTestId(e,t),`data-testid "${t}"`,e),getByText:(t,n=`*`)=>requireMatch(queryByText(e,t,n),`text "${t}" matching "${n}"`,e),query:t=>query(e,t),queryAll:t=>queryAll(e,t),queryAllByTestId:t=>queryAllByTestId(e,t),queryAllByText:(t,n=`*`)=>queryAllByText(e,t,n),queryByTestId:t=>queryByTestId(e,t),queryByText:(t,n=`*`)=>queryByText(e,t,n)}}var t=Symbol(`assay.deadline`),n=2147483647,now=()=>performance.now(),validateDuration=(e,t,r)=>{if(!Number.isFinite(t)||t>n||(r?t<0:t<=0))throw RangeError(`${e} must be a ${r?`non-negative`:`positive`} finite number no greater than ${n}`)},validateWait=(e,t)=>{validateDuration(`interval`,e,!1),validateDuration(`timeout`,t,!0)},runBounded=(n,r,i)=>new Promise((a,o)=>{if(i?.aborted){o((0,e.abortError)(i,`The operation was aborted.`));return}let s=!1,cleanup=()=>!s&&(s=!0,clearTimeout(c),i?.removeEventListener(`abort`,abort),!0),resolveOnce=e=>{cleanup()&&a(e)},rejectOnce=e=>{cleanup()&&o(e)},c=setTimeout(()=>rejectOnce(t),Math.max(0,r-now())),abort=()=>rejectOnce((0,e.abortError)(i,`The operation was aborted.`));i?.addEventListener(`abort`,abort,{once:!0});try{Promise.resolve(n()).then(resolveOnce,rejectOnce)}catch(e){rejectOnce(e)}}),delay=(t=0,n={})=>(validateDuration(`ms`,t,!0),(0,e.sleep)(t,n.signal));async function waitUntil(n,{interval:r=50,signal:i,timeout:a=1e3}={}){validateWait(r,a);let o=now()+a,s=!0;for(;;){if(i?.aborted)throw(0,e.abortError)(i,`The operation was aborted.`);if(!s&&now()>=o)throw new AssayTimeoutError(`waitUntil timed out after ${a}ms`);s=!1;let c;try{c=await runBounded(n,o,i)}catch(e){throw e===t?new AssayTimeoutError(`waitUntil timed out after ${a}ms`):e}if(c)return;let l=o-now();if(l<=0)throw new AssayTimeoutError(`waitUntil timed out after ${a}ms`);await(0,e.sleep)(Math.min(r,l),i)}}async function eventually(n,{interval:r=50,message:i,signal:a,timeout:o=1e3}={}){validateWait(r,o);let s=now()+o,c=!0,l;for(;;){if(a?.aborted)throw(0,e.abortError)(a,`The operation was aborted.`);if(!c&&now()>=s)break;c=!1;try{await runBounded(n,s,a);return}catch(n){if(a?.aborted)throw(0,e.abortError)(a,`The operation was aborted.`);if(n===t)break;l=n}let i=s-now();if(i<=0)break;await(0,e.sleep)(Math.min(r,i),a)}let u=`eventually timed out after ${o}ms`,d=i?`${i} (${u})`:u,f=l instanceof Error?l.message:l==null?``:String(l);throw new AssayTimeoutError(f?`${d}\n${f}`:d,{cause:l})}function waitForEvent(t,n,{signal:r,timeout:i=1e3}={}){return validateDuration(`timeout`,i,!0),new Promise((a,o)=>{if(r?.aborted){o((0,e.abortError)(r,`The operation was aborted.`));return}let dispose=()=>{clearTimeout(s),r?.removeEventListener(`abort`,onAbort),t.removeEventListener(n,onEvent)},onEvent=e=>{dispose(),a(e)},s=setTimeout(()=>{dispose(),o(new AssayTimeoutError(`waitForEvent: "${n}" timed out after ${i}ms`))},i),onAbort=()=>{dispose(),o((0,e.abortError)(r,`The operation was aborted.`))};t.addEventListener(n,onEvent,{once:!0}),r?.addEventListener(`abort`,onAbort,{once:!0})})}exports.AssayError=AssayError,exports.AssayQueryError=AssayQueryError,exports.AssayTimeoutError=AssayTimeoutError,exports.delay=delay,exports.dispatch=dispatch,exports.eventually=eventually,exports.fireBlur=fireBlur,exports.fireChange=fireChange,exports.fireClick=fireClick,exports.fireCustom=fireCustom,exports.fireFocus=fireFocus,exports.fireInput=fireInput,exports.fireKeyDown=fireKeyDown,exports.fireKeyUp=fireKeyUp,exports.fireSubmit=fireSubmit,exports.getSlotted=getSlotted,exports.installFormInternalsPolyfill=installFormInternalsPolyfill,exports.queryAllInShadow=queryAllInShadow,exports.queryInShadow=queryInShadow,exports.queryPart=queryPart,exports.waitForEvent=waitForEvent,exports.waitUntil=waitUntil,exports.walkFlatTree=walkFlatTree,exports.within=within;
|
|
2
2
|
//# sourceMappingURL=assay.cjs.map
|
package/dist/assay.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assay.cjs","names":[],"sources":["../src/errors.ts","../src/events.ts","../src/query.ts","../src/wait.ts"],"sourcesContent":["/** Base class for all Assay errors. Use `instanceof AssayError` to catch any Assay-originated error. */\nexport class AssayError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a required query has no match. */\nexport class AssayQueryError extends AssayError {}\n\n/** Thrown when an Assay wait reaches its timeout. */\nexport class AssayTimeoutError extends AssayError {}\n","/**\n * # Confidence boundary: read first\n *\n * `dispatch` is a **low-level synthetic-event dispatch API**. It fires a caller-\n * supplied DOM `Event` synchronously and returns the `dispatchEvent`\n * result. It does **not** model real user interaction: there is no focus/blur\n * sequencing, no input-event coordination, no keyboard layout, no pointer\n * hit-testing, and no trust flag (`event.isTrusted` is always `false`).\n *\n * Use it to drive event handlers in unit/integration tests where you control\n * the exact event shape. For **behavioral confidence**, that a real click\n * actually activates a control, that focus management works end-to-end, that\n * keyboard shortcuts fire under a real input device: write Playwright tests.\n * Assay deliberately stops at the dispatch boundary; anything that depends on\n * the browser's interaction semantics belongs in a browser-driven suite.\n */\n\n/** Dispatch a pre-built `Event` instance unchanged. Returns the `dispatchEvent` result. */\nexport const dispatch = (target: EventTarget, event: Event): boolean => target.dispatchEvent(event);\n\n/** Synthetic convenience dispatchers. They share the same confidence boundary as `dispatch()`. */\nexport const fireBlur = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('blur', init));\n\nexport const fireChange = (target: EventTarget, init: EventInit = {}): boolean =>\n dispatch(target, new Event('change', { bubbles: true, ...init }));\n\nexport const fireClick = (target: EventTarget, init: MouseEventInit = {}): boolean =>\n dispatch(target, new MouseEvent('click', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireCustom = <T>(target: EventTarget, type: string, init: CustomEventInit<T> = {}): boolean =>\n dispatch(target, new CustomEvent(type, { bubbles: true, cancelable: true, composed: false, ...init }));\n\nexport const fireFocus = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('focus', init));\n\nexport const fireInput = (target: EventTarget, init: InputEventInit = {}): boolean =>\n dispatch(target, new InputEvent('input', { bubbles: true, ...init }));\n\nexport const fireKeyDown = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireKeyUp = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keyup', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireSubmit = (target: EventTarget, init: SubmitEventInit = {}): boolean =>\n dispatch(target, new SubmitEvent('submit', { bubbles: true, cancelable: true, ...init }));\n","import { AssayQueryError } from './errors';\n\n/** DOM query helpers for test environments. */\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Scoped query helpers for any queryable DOM root: see {@link within}. */\nexport interface QueryScope {\n get<E extends Element = Element>(selector: string): E;\n getByTestId<E extends Element = Element>(testId: string): E;\n getByText<E extends Element = Element>(text: string, selector?: string): E;\n query<E extends Element = Element>(selector: string): E | null;\n queryAll<E extends Element = Element>(selector: string): E[];\n queryAllByTestId<E extends Element = Element>(testId: string): E[];\n queryAllByText<E extends Element = Element>(text: string, selector?: string): E[];\n queryByTestId<E extends Element = Element>(testId: string): E | null;\n queryByText<E extends Element = Element>(text: string, selector?: string): E | null;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\ntype QueryRoot = ParentNode;\n\nconst describeRoot = (root: QueryRoot): string => {\n if (root instanceof Element) return root.outerHTML.slice(0, 500);\n\n if (root instanceof ShadowRoot) return `<shadow-root>${root.innerHTML.slice(0, 500)}</shadow-root>`;\n\n return root.nodeName;\n};\n\nconst requireMatch = <E extends Element>(element: E | null, description: string, root: QueryRoot): E => {\n if (element) return element;\n\n throw new AssayQueryError(`Unable to find ${description} within ${describeRoot(root)}.`);\n};\n\nconst query = <E extends Element = Element>(root: QueryRoot, selector: string): E | null =>\n root.querySelector<E>(selector);\n\nconst queryAll = <E extends Element = Element>(root: QueryRoot, selector: string): E[] => {\n return Array.from(root.querySelectorAll<E>(selector));\n};\n\nconst queryByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E | null =>\n queryAll<E>(root, '[data-testid]').find((element) => element.getAttribute('data-testid') === testId) ?? null;\n\nconst queryAllByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E[] =>\n queryAll<E>(root, '[data-testid]').filter((element) => element.getAttribute('data-testid') === testId);\n\nconst queryByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E | null => {\n for (const element of root.querySelectorAll<E>(selector)) {\n if (element.textContent?.trim() === text) return element;\n }\n\n return null;\n};\n\nconst queryAllByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E[] =>\n queryAll<E>(root, selector).filter((element) => element.textContent?.trim() === text);\n\n/**\n * Queries the shadow root of a custom element for a matching CSS selector.\n * Returns `null` if the element has no shadow root or no match is found: safe to call on\n * both open-shadow custom elements and plain elements without checking `shadowRoot` first.\n */\nexport function queryInShadow<E extends Element = Element>(host: Element, selector: string): E | null {\n return host.shadowRoot ? query<E>(host.shadowRoot, selector) : null;\n}\n\n/** Queries all matching elements inside the shadow root of a custom element. */\nexport function queryAllInShadow<E extends Element = Element>(host: Element, selector: string): E[] {\n return host.shadowRoot ? queryAll<E>(host.shadowRoot, selector) : [];\n}\n\n/**\n * Queries a shadow DOM element by its CSS `part` attribute: shorthand for\n * `queryInShadow(host, '[part=\"name\"]')`.\n *\n * @example\n * const btn = queryPart(carousel, 'prev-btn');\n * expect(btn).not.toBeNull();\n */\nexport function queryPart<E extends Element = Element>(host: Element, part: string): E | null {\n return (\n queryAllInShadow<E>(host, '[part]').find((element) => element.getAttribute('part')?.split(/\\s+/).includes(part)) ??\n null\n );\n}\n\n/**\n * Returns the light-DOM children assigned to a named slot, or every child assigned to the\n * default slot when no name is given.\n *\n * @example\n * const slides = getSlotted(carousel);\n * expect(slides).toHaveLength(3);\n */\nexport function getSlotted<E extends Element = Element>(host: Element, slotName?: string): E[] {\n return Array.from(host.children).filter((element) =>\n slotName === undefined ? !element.getAttribute('slot') : element.getAttribute('slot') === slotName,\n ) as E[];\n}\n\n// ─── API ─────────────────────────────────────────────────────────────────────\n\n/**\n * Create query helpers scoped to a DOM root: useful for light DOM and shadow roots.\n *\n * @example\n * const view = within(fixture.shadow!);\n * expect(view.get('.title').textContent).toBe('Hello');\n */\nexport function within(root: QueryRoot): QueryScope {\n return {\n get: <E extends Element = Element>(selector: string) =>\n requireMatch(query<E>(root, selector), `\"${selector}\"`, root),\n getByTestId: <E extends Element = Element>(testId: string) =>\n requireMatch(queryByTestId<E>(root, testId), `data-testid \"${testId}\"`, root),\n getByText: <E extends Element = Element>(text: string, selector = '*') =>\n requireMatch(queryByText<E>(root, text, selector), `text \"${text}\" matching \"${selector}\"`, root),\n query: <E extends Element = Element>(selector: string) => query<E>(root, selector),\n queryAll: <E extends Element = Element>(selector: string) => queryAll<E>(root, selector),\n queryAllByTestId: <E extends Element = Element>(testId: string) => queryAllByTestId<E>(root, testId),\n queryAllByText: <E extends Element = Element>(text: string, selector = '*') =>\n queryAllByText<E>(root, text, selector),\n queryByTestId: <E extends Element = Element>(testId: string) => queryByTestId<E>(root, testId),\n queryByText: <E extends Element = Element>(text: string, selector = '*') => queryByText<E>(root, text, selector),\n };\n}\n","import { abortError, sleep } from '@vielzeug/arsenal';\n\nimport { AssayTimeoutError } from './errors';\n\nexport interface DelayOptions {\n signal?: AbortSignal;\n}\n\nexport interface WaitOptions {\n /** Polling interval in ms (default: 50). */\n interval?: number;\n /** Cancel the pending wait. */\n signal?: AbortSignal;\n /** Maximum wait time in ms (default: 1000). */\n timeout?: number;\n}\n\nexport interface EventuallyOptions extends WaitOptions {\n /** Context included in the timeout error. */\n message?: string;\n}\n\nconst DEADLINE = Symbol('assay.deadline');\nconst MAX_TIMER_MS = 2_147_483_647;\nconst now = (): number => performance.now();\n\nconst validateDuration = (name: string, value: number, allowZero: boolean): void => {\n if (!Number.isFinite(value) || value > MAX_TIMER_MS || (allowZero ? value < 0 : value <= 0)) {\n throw new RangeError(\n `${name} must be a ${allowZero ? 'non-negative' : 'positive'} finite number no greater than ${MAX_TIMER_MS}`,\n );\n }\n};\n\nconst validateWait = (interval: number, timeout: number): void => {\n validateDuration('interval', interval, false);\n validateDuration('timeout', timeout, true);\n};\n\nconst runBounded = <T>(run: () => T | Promise<T>, deadline: number, signal?: AbortSignal): Promise<T> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n let settled = false;\n const cleanup = (): boolean => {\n if (settled) return false;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n return true;\n };\n const resolveOnce = (value: T): void => {\n if (cleanup()) resolve(value);\n };\n const rejectOnce = (error: unknown): void => {\n if (cleanup()) reject(error);\n };\n const timer = setTimeout(() => rejectOnce(DEADLINE), Math.max(0, deadline - now()));\n const abort = () => rejectOnce(abortError(signal, 'The operation was aborted.'));\n\n signal?.addEventListener('abort', abort, { once: true });\n\n try {\n Promise.resolve(run()).then(resolveOnce, rejectOnce);\n } catch (error) {\n rejectOnce(error);\n }\n });\n\nexport const delay = (ms = 0, options: DelayOptions = {}): Promise<void> => {\n validateDuration('ms', ms, true);\n return sleep(ms, options.signal);\n};\n\nexport async function waitUntil(\n predicate: () => boolean | Promise<boolean>,\n { interval = 50, signal, timeout = 1000 }: WaitOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n first = false;\n\n let matched: boolean;\n try {\n matched = await runBounded(predicate, deadline, signal);\n } catch (error) {\n if (error === DEADLINE) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n throw error;\n }\n if (matched) return;\n\n const remaining = deadline - now();\n if (remaining <= 0) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n await sleep(Math.min(interval, remaining), signal);\n }\n}\n\n/**\n * Retry an assertion until it stops throwing or the timeout elapses.\n *\n * Polls the assertion on a fixed interval and preserves the last failure as the\n * timeout cause. Pending asynchronous assertions remain bounded by the same\n * deadline. Use `waitUntil()` for boolean conditions, `delay()` for explicit\n * timer dependencies, and `nextTick()` for one queued microtask boundary.\n *\n * @example\n * await eventually(() => expect(region.textContent).toBe('Saved'));\n */\nexport async function eventually(\n assertion: () => void | Promise<void>,\n { interval = 50, message, signal, timeout = 1000 }: EventuallyOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n let lastError: unknown;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) break;\n first = false;\n\n try {\n await runBounded(assertion, deadline, signal);\n return;\n } catch (error) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (error === DEADLINE) break;\n lastError = error;\n }\n\n const remaining = deadline - now();\n if (remaining <= 0) break;\n await sleep(Math.min(interval, remaining), signal);\n }\n\n const timing = `eventually timed out after ${timeout}ms`;\n const context = message ? `${message} (${timing})` : timing;\n const detail = lastError instanceof Error ? lastError.message : lastError == null ? '' : String(lastError);\n\n throw new AssayTimeoutError(detail ? `${context}\\n${detail}` : context, { cause: lastError });\n}\n\n/** Resolve with the next event of `type`, or reject when it times out or is aborted. */\nexport function waitForEvent<T extends Event = Event>(\n target: EventTarget,\n type: string,\n { signal, timeout = 1000 }: Omit<WaitOptions, 'interval'> = {},\n): Promise<T> {\n validateDuration('timeout', timeout, true);\n\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n const dispose = () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n target.removeEventListener(type, onEvent);\n };\n const onEvent = (event: Event): void => {\n dispose();\n resolve(event as T);\n };\n const timer = setTimeout(() => {\n dispose();\n reject(new AssayTimeoutError(`waitForEvent: \"${type}\" timed out after ${timeout}ms`));\n }, timeout);\n const onAbort = () => {\n dispose();\n reject(abortError(signal, 'The operation was aborted.'));\n };\n\n target.addEventListener(type, onEvent, { once: true });\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n"],"mappings":"sGACA,IAA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SAAS,EAAS,IAAW,CACtC,GAAI,GAAQ,QAAS,CACnB,GAAA,EAAO,EAAA,WAAA,CAAW,EAAQ,4BAA4B,CAAC,EACvD,MACF,CAEA,IAAM,YAAgB,CACpB,aAAa,CAAK,EAClB,GAAQ,oBAAoB,QAAS,OAAO,EAC5C,EAAO,oBAAoB,EAAM,OAAO,CAC1C,EACM,QAAW,GAAuB,CACtC,QAAQ,EACR,EAAQ,CAAU,CACpB,EACM,EAAQ,eAAiB,CAC7B,QAAQ,EACR,EAAO,IAAI,kBAAkB,kBAAkB,EAAK,oBAAoB,EAAQ,GAAG,CAAC,CACtF,EAAG,CAAO,EACJ,YAAgB,CACpB,QAAQ,EACR,GAAA,EAAO,EAAA,WAAA,CAAW,EAAQ,4BAA4B,CAAC,CACzD,EAEA,EAAO,iBAAiB,EAAM,QAAS,CAAE,KAAM,EAAK,CAAC,EACrD,GAAQ,iBAAiB,QAAS,QAAS,CAAE,KAAM,EAAK,CAAC,CAC3D,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"assay.cjs","names":[],"sources":["../src/dom.ts","../src/errors.ts","../src/events.ts","../src/form-internals.ts","../src/query.ts","../src/wait.ts"],"sourcesContent":["/**\n * DOM traversal helpers for tests running under jsdom, which only implements the *light* DOM\n * tree: `Element.children`/`querySelectorAll()` never cross a `<slot>` into its assigned\n * elements. Real browsers use the *flat tree* (light DOM with each `<slot>` transparently\n * replaced by what's actually assigned to it) for this: it's what \"form owner\" resolution,\n * `:has()`, and plenty of other DOM algorithms are specified against.\n */\n\n/**\n * Walks the flat tree starting at `root`, calling `visit` for every element encountered :\n * expanding each `<slot>` via `assignedElements()` instead of descending into its (always\n * empty, in jsdom) literal children.\n *\n * @example\n * ```ts\n * // Find every form-associated element slotted (possibly through nested slots) under `form`,\n * // something `form.querySelectorAll('[name]')` can't do once a shadow boundary is involved.\n * const named: HTMLElement[] = [];\n * walkFlatTree(form, (el) => { if (el.hasAttribute('name')) named.push(el); });\n * ```\n */\nexport const walkFlatTree = (root: Element, visit: (element: HTMLElement) => void): void => {\n const children = root instanceof HTMLSlotElement ? root.assignedElements({ flatten: true }) : root.children;\n\n for (const child of Array.from(children)) {\n if (!(child instanceof HTMLSlotElement)) visit(child as HTMLElement);\n\n walkFlatTree(child, visit);\n }\n};\n","/** Base class for all Assay errors. Use `instanceof AssayError` to catch any Assay-originated error. */\nexport class AssayError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a required query has no match. */\nexport class AssayQueryError extends AssayError {}\n\n/** Thrown when an Assay wait reaches its timeout. */\nexport class AssayTimeoutError extends AssayError {}\n","/**\n * # Confidence boundary: read first\n *\n * `dispatch` is a **low-level synthetic-event dispatch API**. It fires a caller-\n * supplied DOM `Event` synchronously and returns the `dispatchEvent`\n * result. It does **not** model real user interaction: there is no focus/blur\n * sequencing, no input-event coordination, no keyboard layout, no pointer\n * hit-testing, and no trust flag (`event.isTrusted` is always `false`).\n *\n * Use it to drive event handlers in unit/integration tests where you control\n * the exact event shape. For **behavioral confidence**, that a real click\n * actually activates a control, that focus management works end-to-end, that\n * keyboard shortcuts fire under a real input device: write Playwright tests.\n * Assay deliberately stops at the dispatch boundary; anything that depends on\n * the browser's interaction semantics belongs in a browser-driven suite.\n */\n\n/** Dispatch a pre-built `Event` instance unchanged. Returns the `dispatchEvent` result. */\nexport const dispatch = (target: EventTarget, event: Event): boolean => target.dispatchEvent(event);\n\n/** Synthetic convenience dispatchers. They share the same confidence boundary as `dispatch()`. */\nexport const fireBlur = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('blur', init));\n\nexport const fireChange = (target: EventTarget, init: EventInit = {}): boolean =>\n dispatch(target, new Event('change', { bubbles: true, ...init }));\n\nexport const fireClick = (target: EventTarget, init: MouseEventInit = {}): boolean =>\n dispatch(target, new MouseEvent('click', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireCustom = <T>(target: EventTarget, type: string, init: CustomEventInit<T> = {}): boolean =>\n dispatch(target, new CustomEvent(type, { bubbles: true, cancelable: true, composed: false, ...init }));\n\nexport const fireFocus = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('focus', init));\n\nexport const fireInput = (target: EventTarget, init: InputEventInit = {}): boolean =>\n dispatch(target, new InputEvent('input', { bubbles: true, ...init }));\n\nexport const fireKeyDown = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireKeyUp = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keyup', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireSubmit = (target: EventTarget, init: SubmitEventInit = {}): boolean =>\n dispatch(target, new SubmitEvent('submit', { bubbles: true, cancelable: true, ...init }));\n","import { walkFlatTree } from './dom';\n\n/**\n * jsdom implements none of the `ElementInternals` form-association API: not `setFormValue`,\n * not `setValidity`, not the `checkValidity`/`reportValidity`/`validity`/`validationMessage`\n * mixin real browsers put on every `formAssociated: true` element, not even `FormData`\n * collecting a form-associated element's set value, or `<form>.reset()` invoking\n * `formResetCallback()`. Every one of those gaps is exercised by `useField()` (`@vielzeug/ore`),\n * so any package testing a form-associated component needs all of them, not just one.\n *\n * Call this directly from a test setup when the suite tests form-associated components:\n * the patches are global monkey-patches, so suites without them shouldn't pay for them.\n * Returns an `uninstall()` that restores every patched global.\n *\n * Lives in Assay because it patches the DOM environment itself: the gap is in jsdom, not in\n * any package's feature, and Assay is the repo's home for DOM test-environment helpers.\n * `walkFlatTree` handles form-associated custom elements across shadow boundaries, so\n * consumer packages do not need package-local copies of this polyfill.\n */\nexport const installFormInternalsPolyfill = (): (() => void) => {\n // Checked *before* consuming the flag below: an environment without `ElementInternals`\n // installs nothing and should stay eligible to install for real later (e.g. a differently\n // configured environment in the same process), not get marked \"already installed\" for having\n // done nothing.\n if (typeof ElementInternals === 'undefined') return () => {};\n\n const INSTALLED_FLAG = Symbol.for('vielzeug.assay.formInternalsPolyfillInstalled');\n const flagHost = globalThis as Record<symbol, boolean | undefined>;\n\n if (flagHost[INSTALLED_FLAG]) return () => {};\n\n flagHost[INSTALLED_FLAG] = true;\n\n // Every patch pushes its inverse here, so uninstall() restores the environment exactly.\n const restorers: Array<() => void> = [];\n\n const proto = ElementInternals.prototype as unknown as Record<string, unknown>;\n const validityState = new WeakMap<ElementInternals, { flags: ValidityStateFlags; message: string }>();\n const formValueByHost = new WeakMap<HTMLElement, File | FormData | string | null>();\n const hostByInternals = new WeakMap<ElementInternals, HTMLElement>();\n\n const patchProto = (name: string, descriptor: PropertyDescriptor): void => {\n if (name in proto) return;\n\n Object.defineProperty(proto, name, descriptor);\n restorers.push(() => delete proto[name]);\n };\n\n const isValid = (internals: ElementInternals): boolean => {\n const state = validityState.get(internals);\n\n return !state || !Object.values(state.flags).some(Boolean);\n };\n\n patchProto('setFormValue', {\n configurable: true,\n value: function (this: ElementInternals, value: File | FormData | string | null) {\n const host = hostByInternals.get(this);\n\n if (host) formValueByHost.set(host, value);\n },\n writable: true,\n });\n\n patchProto('setValidity', {\n configurable: true,\n // Matches the real platform contract: throws if any flag is true and message is empty.\n // `useField()` itself already guards against triggering this: see forms/field.ts, but\n // the polyfill enforcing it too means a test would still catch a *different* caller doing\n // the same thing wrong, instead of that bug only surfacing in a real browser.\n value: function (this: ElementInternals, flags: ValidityStateFlags = {}, message = '') {\n if (Object.values(flags).some(Boolean) && !message) {\n throw new TypeError(\n \"Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if \" +\n 'one or more flags in the first argument are true.',\n );\n }\n\n validityState.set(this, { flags, message });\n },\n writable: true,\n });\n\n patchProto('checkValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('reportValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('validationMessage', {\n configurable: true,\n get(this: ElementInternals) {\n return isValid(this) ? '' : (validityState.get(this)?.message ?? '');\n },\n });\n\n // A ValidityState-shaped view of the flags passed to setValidity: every known\n // flag defaults to false, `valid` reflects whether any flag is set.\n patchProto('validity', {\n configurable: true,\n get(this: ElementInternals): ValidityState {\n const state = validityState.get(this);\n\n return {\n badInput: false,\n customError: false,\n patternMismatch: false,\n rangeOverflow: false,\n rangeUnderflow: false,\n stepMismatch: false,\n tooLong: false,\n tooShort: false,\n typeMismatch: false,\n valid: isValid(this),\n valueMissing: false,\n ...(state?.flags ?? {}),\n } as ValidityState;\n },\n });\n\n patchProto('states', {\n configurable: true,\n get: function (this: ElementInternals & { _states?: Set<string> }) {\n this._states ??= new Set();\n\n return this._states;\n },\n });\n\n // Real browsers mix `checkValidity`/`reportValidity`/`validity`/`validationMessage` onto any\n // `formAssociated: true` custom element itself (delegating to its internals): not just onto\n // `ElementInternals`. jsdom does neither; mirror it here so a component's own\n // `checkValidity()`/`reportValidity()`, and a test asserting against the element directly,\n // behave the same as they would in a real browser.\n const originalAttachInternals = HTMLElement.prototype.attachInternals;\n\n HTMLElement.prototype.attachInternals = function (this: HTMLElement, ...args: []): ElementInternals {\n const internals = originalAttachInternals.apply(this, args);\n\n hostByInternals.set(internals, this);\n\n Object.defineProperties(this, {\n checkValidity: { configurable: true, value: () => internals.checkValidity() },\n reportValidity: { configurable: true, value: () => internals.reportValidity() },\n validationMessage: { configurable: true, get: () => internals.validationMessage },\n validity: { configurable: true, get: () => internals.validity },\n });\n\n return internals;\n };\n restorers.push(() => {\n HTMLElement.prototype.attachInternals = originalAttachInternals;\n });\n\n const appendFormValue = (formData: FormData, name: string, value: File | FormData | string): void => {\n if (value instanceof FormData) {\n for (const [entryName, entryValue] of value.entries()) formData.append(entryName, entryValue);\n\n return;\n }\n\n formData.append(name, value);\n };\n\n // jsdom's `FormData` constructor never collects a form-associated custom element's set form\n // value: real browsers walk the flat tree for every form-associated element with a `name`.\n const NativeFormData = globalThis.FormData;\n\n globalThis.FormData = class FormDataWithFormAssociatedElements extends NativeFormData {\n constructor(form?: HTMLFormElement, submitter?: HTMLElement | null) {\n super(form as HTMLFormElement | undefined, submitter as HTMLElement | null | undefined);\n\n if (!(form instanceof HTMLFormElement)) return;\n\n walkFlatTree(form, (element) => {\n const name = element.getAttribute('name');\n const value = formValueByHost.get(element);\n\n if (!name || value == null || element.hasAttribute('disabled')) return;\n\n appendFormValue(this, name, value);\n });\n }\n };\n restorers.push(() => {\n globalThis.FormData = NativeFormData;\n });\n\n // jsdom never invokes the native `formResetCallback` lifecycle method on form-associated\n // custom elements when their form resets: patch `reset()` to do it (via the same flat-tree\n // walk, since a reset field can be nested behind a shadow boundary too), so `onFormReset()`\n // (see `@vielzeug/ore`'s runtime.ts) is testable against a real `<form>.reset()` call instead\n // of only by calling `element.formResetCallback()` directly.\n const originalReset = HTMLFormElement.prototype.reset;\n\n HTMLFormElement.prototype.reset = function (this: HTMLFormElement, ...args: []) {\n originalReset.apply(this, args);\n\n walkFlatTree(this, (element) => {\n (element as Partial<{ formResetCallback: () => void }>).formResetCallback?.();\n });\n };\n restorers.push(() => {\n HTMLFormElement.prototype.reset = originalReset;\n });\n\n return () => {\n for (const restore of restorers) restore();\n\n restorers.length = 0;\n flagHost[INSTALLED_FLAG] = false;\n };\n};\n","import { AssayQueryError } from './errors';\n\n/** DOM query helpers for test environments. */\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Scoped query helpers for any queryable DOM root: see {@link within}. */\nexport interface QueryScope {\n get<E extends Element = Element>(selector: string): E;\n getByTestId<E extends Element = Element>(testId: string): E;\n getByText<E extends Element = Element>(text: string, selector?: string): E;\n query<E extends Element = Element>(selector: string): E | null;\n queryAll<E extends Element = Element>(selector: string): E[];\n queryAllByTestId<E extends Element = Element>(testId: string): E[];\n queryAllByText<E extends Element = Element>(text: string, selector?: string): E[];\n queryByTestId<E extends Element = Element>(testId: string): E | null;\n queryByText<E extends Element = Element>(text: string, selector?: string): E | null;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\ntype QueryRoot = ParentNode;\n\nconst describeRoot = (root: QueryRoot): string => {\n if (root instanceof Element) return root.outerHTML.slice(0, 500);\n\n if (root instanceof ShadowRoot) return `<shadow-root>${root.innerHTML.slice(0, 500)}</shadow-root>`;\n\n return root.nodeName;\n};\n\nconst requireMatch = <E extends Element>(element: E | null, description: string, root: QueryRoot): E => {\n if (element) return element;\n\n throw new AssayQueryError(`Unable to find ${description} within ${describeRoot(root)}.`);\n};\n\nconst query = <E extends Element = Element>(root: QueryRoot, selector: string): E | null =>\n root.querySelector<E>(selector);\n\nconst queryAll = <E extends Element = Element>(root: QueryRoot, selector: string): E[] => {\n return Array.from(root.querySelectorAll<E>(selector));\n};\n\nconst queryByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E | null =>\n queryAll<E>(root, '[data-testid]').find((element) => element.getAttribute('data-testid') === testId) ?? null;\n\nconst queryAllByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E[] =>\n queryAll<E>(root, '[data-testid]').filter((element) => element.getAttribute('data-testid') === testId);\n\nconst queryByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E | null => {\n for (const element of root.querySelectorAll<E>(selector)) {\n if (element.textContent?.trim() === text) return element;\n }\n\n return null;\n};\n\nconst queryAllByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E[] =>\n queryAll<E>(root, selector).filter((element) => element.textContent?.trim() === text);\n\n/**\n * Queries the shadow root of a custom element for a matching CSS selector.\n * Returns `null` if the element has no shadow root or no match is found: safe to call on\n * both open-shadow custom elements and plain elements without checking `shadowRoot` first.\n */\nexport function queryInShadow<E extends Element = Element>(host: Element, selector: string): E | null {\n return host.shadowRoot ? query<E>(host.shadowRoot, selector) : null;\n}\n\n/** Queries all matching elements inside the shadow root of a custom element. */\nexport function queryAllInShadow<E extends Element = Element>(host: Element, selector: string): E[] {\n return host.shadowRoot ? queryAll<E>(host.shadowRoot, selector) : [];\n}\n\n/**\n * Queries a shadow DOM element by its CSS `part` attribute: shorthand for\n * `queryInShadow(host, '[part=\"name\"]')`.\n *\n * @example\n * const btn = queryPart(carousel, 'prev-btn');\n * expect(btn).not.toBeNull();\n */\nexport function queryPart<E extends Element = Element>(host: Element, part: string): E | null {\n return (\n queryAllInShadow<E>(host, '[part]').find((element) => element.getAttribute('part')?.split(/\\s+/).includes(part)) ??\n null\n );\n}\n\n/**\n * Returns the light-DOM children assigned to a named slot, or every child assigned to the\n * default slot when no name is given.\n *\n * @example\n * const slides = getSlotted(carousel);\n * expect(slides).toHaveLength(3);\n */\nexport function getSlotted<E extends Element = Element>(host: Element, slotName?: string): E[] {\n return Array.from(host.children).filter((element) =>\n slotName === undefined ? !element.getAttribute('slot') : element.getAttribute('slot') === slotName,\n ) as E[];\n}\n\n// ─── API ─────────────────────────────────────────────────────────────────────\n\n/**\n * Create query helpers scoped to a DOM root: useful for light DOM and shadow roots.\n *\n * @example\n * const view = within(fixture.shadow!);\n * expect(view.get('.title').textContent).toBe('Hello');\n */\nexport function within(root: QueryRoot): QueryScope {\n return {\n get: <E extends Element = Element>(selector: string) =>\n requireMatch(query<E>(root, selector), `\"${selector}\"`, root),\n getByTestId: <E extends Element = Element>(testId: string) =>\n requireMatch(queryByTestId<E>(root, testId), `data-testid \"${testId}\"`, root),\n getByText: <E extends Element = Element>(text: string, selector = '*') =>\n requireMatch(queryByText<E>(root, text, selector), `text \"${text}\" matching \"${selector}\"`, root),\n query: <E extends Element = Element>(selector: string) => query<E>(root, selector),\n queryAll: <E extends Element = Element>(selector: string) => queryAll<E>(root, selector),\n queryAllByTestId: <E extends Element = Element>(testId: string) => queryAllByTestId<E>(root, testId),\n queryAllByText: <E extends Element = Element>(text: string, selector = '*') =>\n queryAllByText<E>(root, text, selector),\n queryByTestId: <E extends Element = Element>(testId: string) => queryByTestId<E>(root, testId),\n queryByText: <E extends Element = Element>(text: string, selector = '*') => queryByText<E>(root, text, selector),\n };\n}\n","import { abortError, sleep } from '@vielzeug/arsenal';\n\nimport { AssayTimeoutError } from './errors';\n\nexport interface DelayOptions {\n signal?: AbortSignal;\n}\n\nexport interface WaitOptions {\n /** Polling interval in ms (default: 50). */\n interval?: number;\n /** Cancel the pending wait. */\n signal?: AbortSignal;\n /** Maximum wait time in ms (default: 1000). */\n timeout?: number;\n}\n\nexport interface EventuallyOptions extends WaitOptions {\n /** Context included in the timeout error. */\n message?: string;\n}\n\nconst DEADLINE = Symbol('assay.deadline');\nconst MAX_TIMER_MS = 2_147_483_647;\nconst now = (): number => performance.now();\n\nconst validateDuration = (name: string, value: number, allowZero: boolean): void => {\n if (!Number.isFinite(value) || value > MAX_TIMER_MS || (allowZero ? value < 0 : value <= 0)) {\n throw new RangeError(\n `${name} must be a ${allowZero ? 'non-negative' : 'positive'} finite number no greater than ${MAX_TIMER_MS}`,\n );\n }\n};\n\nconst validateWait = (interval: number, timeout: number): void => {\n validateDuration('interval', interval, false);\n validateDuration('timeout', timeout, true);\n};\n\nconst runBounded = <T>(run: () => T | Promise<T>, deadline: number, signal?: AbortSignal): Promise<T> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n let settled = false;\n const cleanup = (): boolean => {\n if (settled) return false;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n return true;\n };\n const resolveOnce = (value: T): void => {\n if (cleanup()) resolve(value);\n };\n const rejectOnce = (error: unknown): void => {\n if (cleanup()) reject(error);\n };\n const timer = setTimeout(() => rejectOnce(DEADLINE), Math.max(0, deadline - now()));\n const abort = () => rejectOnce(abortError(signal, 'The operation was aborted.'));\n\n signal?.addEventListener('abort', abort, { once: true });\n\n try {\n Promise.resolve(run()).then(resolveOnce, rejectOnce);\n } catch (error) {\n rejectOnce(error);\n }\n });\n\nexport const delay = (ms = 0, options: DelayOptions = {}): Promise<void> => {\n validateDuration('ms', ms, true);\n return sleep(ms, options.signal);\n};\n\nexport async function waitUntil(\n predicate: () => boolean | Promise<boolean>,\n { interval = 50, signal, timeout = 1000 }: WaitOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n first = false;\n\n let matched: boolean;\n try {\n matched = await runBounded(predicate, deadline, signal);\n } catch (error) {\n if (error === DEADLINE) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n throw error;\n }\n if (matched) return;\n\n const remaining = deadline - now();\n if (remaining <= 0) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n await sleep(Math.min(interval, remaining), signal);\n }\n}\n\n/**\n * Retry an assertion until it stops throwing or the timeout elapses.\n *\n * Polls the assertion on a fixed interval and preserves the last failure as the\n * timeout cause. Pending asynchronous assertions remain bounded by the same\n * deadline. Use `waitUntil()` for boolean conditions, `delay()` for explicit\n * timer dependencies, and `nextTick()` for one queued microtask boundary.\n *\n * @example\n * await eventually(() => expect(region.textContent).toBe('Saved'));\n */\nexport async function eventually(\n assertion: () => void | Promise<void>,\n { interval = 50, message, signal, timeout = 1000 }: EventuallyOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n let lastError: unknown;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) break;\n first = false;\n\n try {\n await runBounded(assertion, deadline, signal);\n return;\n } catch (error) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (error === DEADLINE) break;\n lastError = error;\n }\n\n const remaining = deadline - now();\n if (remaining <= 0) break;\n await sleep(Math.min(interval, remaining), signal);\n }\n\n const timing = `eventually timed out after ${timeout}ms`;\n const context = message ? `${message} (${timing})` : timing;\n const detail = lastError instanceof Error ? lastError.message : lastError == null ? '' : String(lastError);\n\n throw new AssayTimeoutError(detail ? `${context}\\n${detail}` : context, { cause: lastError });\n}\n\n/** Resolve with the next event of `type`, or reject when it times out or is aborted. */\nexport function waitForEvent<T extends Event = Event>(\n target: EventTarget,\n type: string,\n { signal, timeout = 1000 }: Omit<WaitOptions, 'interval'> = {},\n): Promise<T> {\n validateDuration('timeout', timeout, true);\n\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n const dispose = () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n target.removeEventListener(type, onEvent);\n };\n const onEvent = (event: Event): void => {\n dispose();\n resolve(event as T);\n };\n const timer = setTimeout(() => {\n dispose();\n reject(new AssayTimeoutError(`waitForEvent: \"${type}\" timed out after ${timeout}ms`));\n }, timeout);\n const onAbort = () => {\n dispose();\n reject(abortError(signal, 'The operation was aborted.'));\n };\n\n target.addEventListener(type, onEvent, { once: true });\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n"],"mappings":"sGAqBA,IAAa,cAAgB,EAAe,IAAgD,CAC1F,IAAM,EAAW,aAAgB,gBAAkB,EAAK,iBAAiB,CAAE,QAAS,EAAK,CAAC,EAAI,EAAK,SAEnG,IAAK,IAAM,KAAS,MAAM,KAAK,CAAQ,EAC/B,aAAiB,iBAAkB,EAAM,CAAoB,EAEnE,aAAa,EAAO,CAAK,CAE7B,EC5Ba,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,UAAW,CAAC,EAGpC,kBAAb,cAAuC,UAAW,CAAC,ECKtC,UAAY,EAAqB,IAA0B,EAAO,cAAc,CAAK,EAGrF,UAAY,EAAqB,EAAuB,CAAC,IACpE,SAAS,EAAQ,IAAI,WAAW,OAAQ,CAAI,CAAC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aAAqB,MAAQ,EAAU,QAAU,GAAa,KAAO,GAAK,OAAO,CAAS,EAEzG,MAAM,IAAI,kBAAkB,EAAS,GAAG,EAAQ,IAAI,IAAW,EAAS,CAAE,MAAO,CAAU,CAAC,CAC9F,CAGA,SAAgB,aACd,EACA,EACA,CAAE,SAAQ,UAAU,KAAwC,CAAC,EACjD,CAGZ,OAFA,iBAAiB,UAAW,EAAS,EAAI,EAElC,IAAI,SAAS,EAAS,IAAW,CACtC,GAAI,GAAQ,QAAS,CACnB,GAAA,EAAO,EAAA,WAAA,CAAW,EAAQ,4BAA4B,CAAC,EACvD,MACF,CAEA,IAAM,YAAgB,CACpB,aAAa,CAAK,EAClB,GAAQ,oBAAoB,QAAS,OAAO,EAC5C,EAAO,oBAAoB,EAAM,OAAO,CAC1C,EACM,QAAW,GAAuB,CACtC,QAAQ,EACR,EAAQ,CAAU,CACpB,EACM,EAAQ,eAAiB,CAC7B,QAAQ,EACR,EAAO,IAAI,kBAAkB,kBAAkB,EAAK,oBAAoB,EAAQ,GAAG,CAAC,CACtF,EAAG,CAAO,EACJ,YAAgB,CACpB,QAAQ,EACR,GAAA,EAAO,EAAA,WAAA,CAAW,EAAQ,4BAA4B,CAAC,CACzD,EAEA,EAAO,iBAAiB,EAAM,QAAS,CAAE,KAAM,EAAK,CAAC,EACrD,GAAQ,iBAAiB,QAAS,QAAS,CAAE,KAAM,EAAK,CAAC,CAC3D,CAAC,CACH"}
|
package/dist/assay.iife.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Assay=(function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var AssayError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},AssayQueryError=class extends AssayError{},AssayTimeoutError=class extends AssayError{},dispatch=(e,t)=>e.dispatchEvent(t),fireBlur=(e,t={})=>dispatch(e,new FocusEvent(`blur`,t)),fireChange=(e,t={})=>dispatch(e,new Event(`change`,{bubbles:!0,...t})),fireClick=(e,t={})=>dispatch(e,new MouseEvent(`click`,{bubbles:!0,cancelable:!0,...t})),fireCustom=(e,t,n={})=>dispatch(e,new CustomEvent(t,{bubbles:!0,cancelable:!0,composed:!1,...n})),fireFocus=(e,t={})=>dispatch(e,new FocusEvent(`focus`,t)),fireInput=(e,t={})=>dispatch(e,new InputEvent(`input`,{bubbles:!0,...t})),fireKeyDown=(e,t={})=>dispatch(e,new KeyboardEvent(`keydown`,{bubbles:!0,cancelable:!0,...t})),fireKeyUp=(e,t={})=>dispatch(e,new KeyboardEvent(`keyup`,{bubbles:!0,cancelable:!0,...t})),fireSubmit=(e,t={})=>dispatch(e,new SubmitEvent(`submit`,{bubbles:!0,cancelable:!0,...t})),describeRoot=e=>e instanceof Element?e.outerHTML.slice(0,500):e instanceof ShadowRoot?`<shadow-root>${e.innerHTML.slice(0,500)}</shadow-root>`:e.nodeName,requireMatch=(e,t,n)=>{if(e)return e;throw new AssayQueryError(`Unable to find ${t} within ${describeRoot(n)}.`)},query=(e,t)=>e.querySelector(t),queryAll=(e,t)=>Array.from(e.querySelectorAll(t)),queryByTestId=(e,t)=>queryAll(e,`[data-testid]`).find(e=>e.getAttribute(`data-testid`)===t)??null,queryAllByTestId=(e,t)=>queryAll(e,`[data-testid]`).filter(e=>e.getAttribute(`data-testid`)===t),queryByText=(e,t,n=`*`)=>{for(let r of e.querySelectorAll(n))if(r.textContent?.trim()===t)return r;return null},queryAllByText=(e,t,n=`*`)=>queryAll(e,n).filter(e=>e.textContent?.trim()===t);function queryInShadow(e,t){return e.shadowRoot?query(e.shadowRoot,t):null}function queryAllInShadow(e,t){return e.shadowRoot?queryAll(e.shadowRoot,t):[]}function queryPart(e,t){return queryAllInShadow(e,`[part]`).find(e=>e.getAttribute(`part`)?.split(/\s+/).includes(t))??null}function getSlotted(e,t){return Array.from(e.children).filter(e=>t===void 0?!e.getAttribute(`slot`):e.getAttribute(`slot`)===t)}function within(e){return{get:t=>requireMatch(query(e,t),`"${t}"`,e),getByTestId:t=>requireMatch(queryByTestId(e,t),`data-testid "${t}"`,e),getByText:(t,n=`*`)=>requireMatch(queryByText(e,t,n),`text "${t}" matching "${n}"`,e),query:t=>query(e,t),queryAll:t=>queryAll(e,t),queryAllByTestId:t=>queryAllByTestId(e,t),queryAllByText:(t,n=`*`)=>queryAllByText(e,t,n),queryByTestId:t=>queryByTestId(e,t),queryByText:(t,n=`*`)=>queryByText(e,t,n)}}var n=Symbol(`assay.deadline`),r=2147483647,now=()=>performance.now(),validateDuration=(e,t,n)=>{if(!Number.isFinite(t)||t>r||(n?t<0:t<=0))throw RangeError(`${e} must be a ${n?`non-negative`:`positive`} finite number no greater than ${r}`)},validateWait=(e,t)=>{validateDuration(`interval`,e,!1),validateDuration(`timeout`,t,!0)},runBounded=(e,r,i)=>new Promise((a,o)=>{if(i?.aborted){o((0,t.abortError)(i,`The operation was aborted.`));return}let s=!1,cleanup=()=>!s&&(s=!0,clearTimeout(c),i?.removeEventListener(`abort`,abort),!0),resolveOnce=e=>{cleanup()&&a(e)},rejectOnce=e=>{cleanup()&&o(e)},c=setTimeout(()=>rejectOnce(n),Math.max(0,r-now())),abort=()=>rejectOnce((0,t.abortError)(i,`The operation was aborted.`));i?.addEventListener(`abort`,abort,{once:!0});try{Promise.resolve(e()).then(resolveOnce,rejectOnce)}catch(e){rejectOnce(e)}}),delay=(e=0,n={})=>(validateDuration(`ms`,e,!0),(0,t.sleep)(e,n.signal));async function waitUntil(e,{interval:r=50,signal:i,timeout:a=1e3}={}){validateWait(r,a);let o=now()+a,s=!0;for(;;){if(i?.aborted)throw(0,t.abortError)(i,`The operation was aborted.`);if(!s&&now()>=o)throw new AssayTimeoutError(`waitUntil timed out after ${a}ms`);s=!1;let c;try{c=await runBounded(e,o,i)}catch(e){throw e===n?new AssayTimeoutError(`waitUntil timed out after ${a}ms`):e}if(c)return;let l=o-now();if(l<=0)throw new AssayTimeoutError(`waitUntil timed out after ${a}ms`);await(0,t.sleep)(Math.min(r,l),i)}}async function eventually(e,{interval:r=50,message:i,signal:a,timeout:o=1e3}={}){validateWait(r,o);let s=now()+o,c=!0,l;for(;;){if(a?.aborted)throw(0,t.abortError)(a,`The operation was aborted.`);if(!c&&now()>=s)break;c=!1;try{await runBounded(e,s,a);return}catch(e){if(a?.aborted)throw(0,t.abortError)(a,`The operation was aborted.`);if(e===n)break;l=e}let i=s-now();if(i<=0)break;await(0,t.sleep)(Math.min(r,i),a)}let u=`eventually timed out after ${o}ms`,d=i?`${i} (${u})`:u,f=l instanceof Error?l.message:l==null?``:String(l);throw new AssayTimeoutError(f?`${d}\n${f}`:d,{cause:l})}function waitForEvent(e,n,{signal:r,timeout:i=1e3}={}){return validateDuration(`timeout`,i,!0),new Promise((a,o)=>{if(r?.aborted){o((0,t.abortError)(r,`The operation was aborted.`));return}let dispose=()=>{clearTimeout(s),r?.removeEventListener(`abort`,onAbort),e.removeEventListener(n,onEvent)},onEvent=e=>{dispose(),a(e)},s=setTimeout(()=>{dispose(),o(new AssayTimeoutError(`waitForEvent: "${n}" timed out after ${i}ms`))},i),onAbort=()=>{dispose(),o((0,t.abortError)(r,`The operation was aborted.`))};e.addEventListener(n,onEvent,{once:!0}),r?.addEventListener(`abort`,onAbort,{once:!0})})}return e.AssayError=AssayError,e.AssayQueryError=AssayQueryError,e.AssayTimeoutError=AssayTimeoutError,e.delay=delay,e.dispatch=dispatch,e.eventually=eventually,e.fireBlur=fireBlur,e.fireChange=fireChange,e.fireClick=fireClick,e.fireCustom=fireCustom,e.fireFocus=fireFocus,e.fireInput=fireInput,e.fireKeyDown=fireKeyDown,e.fireKeyUp=fireKeyUp,e.fireSubmit=fireSubmit,e.getSlotted=getSlotted,e.queryAllInShadow=queryAllInShadow,e.queryInShadow=queryInShadow,e.queryPart=queryPart,e.waitForEvent=waitForEvent,e.waitUntil=waitUntil,e.within=within,e})({},Arsenal);
|
|
1
|
+
var Assay=(function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var walkFlatTree=(e,t)=>{let n=e instanceof HTMLSlotElement?e.assignedElements({flatten:!0}):e.children;for(let e of Array.from(n))e instanceof HTMLSlotElement||t(e),walkFlatTree(e,t)},AssayError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},AssayQueryError=class extends AssayError{},AssayTimeoutError=class extends AssayError{},dispatch=(e,t)=>e.dispatchEvent(t),fireBlur=(e,t={})=>dispatch(e,new FocusEvent(`blur`,t)),fireChange=(e,t={})=>dispatch(e,new Event(`change`,{bubbles:!0,...t})),fireClick=(e,t={})=>dispatch(e,new MouseEvent(`click`,{bubbles:!0,cancelable:!0,...t})),fireCustom=(e,t,n={})=>dispatch(e,new CustomEvent(t,{bubbles:!0,cancelable:!0,composed:!1,...n})),fireFocus=(e,t={})=>dispatch(e,new FocusEvent(`focus`,t)),fireInput=(e,t={})=>dispatch(e,new InputEvent(`input`,{bubbles:!0,...t})),fireKeyDown=(e,t={})=>dispatch(e,new KeyboardEvent(`keydown`,{bubbles:!0,cancelable:!0,...t})),fireKeyUp=(e,t={})=>dispatch(e,new KeyboardEvent(`keyup`,{bubbles:!0,cancelable:!0,...t})),fireSubmit=(e,t={})=>dispatch(e,new SubmitEvent(`submit`,{bubbles:!0,cancelable:!0,...t})),installFormInternalsPolyfill=()=>{if(typeof ElementInternals>`u`)return()=>{};let e=Symbol.for(`vielzeug.assay.formInternalsPolyfillInstalled`),t=globalThis;if(t[e])return()=>{};t[e]=!0;let n=[],r=ElementInternals.prototype,i=new WeakMap,a=new WeakMap,o=new WeakMap,patchProto=(e,t)=>{e in r||(Object.defineProperty(r,e,t),n.push(()=>delete r[e]))},isValid=e=>{let t=i.get(e);return!t||!Object.values(t.flags).some(Boolean)};patchProto(`setFormValue`,{configurable:!0,value:function(e){let t=o.get(this);t&&a.set(t,e)},writable:!0}),patchProto(`setValidity`,{configurable:!0,value:function(e={},t=``){if(Object.values(e).some(Boolean)&&!t)throw TypeError(`Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if one or more flags in the first argument are true.`);i.set(this,{flags:e,message:t})},writable:!0}),patchProto(`checkValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`reportValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`validationMessage`,{configurable:!0,get(){return isValid(this)?``:i.get(this)?.message??``}}),patchProto(`validity`,{configurable:!0,get(){let e=i.get(this);return{badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:isValid(this),valueMissing:!1,...e?.flags??{}}}}),patchProto(`states`,{configurable:!0,get:function(){return this._states??=new Set,this._states}});let s=HTMLElement.prototype.attachInternals;HTMLElement.prototype.attachInternals=function(...e){let t=s.apply(this,e);return o.set(t,this),Object.defineProperties(this,{checkValidity:{configurable:!0,value:()=>t.checkValidity()},reportValidity:{configurable:!0,value:()=>t.reportValidity()},validationMessage:{configurable:!0,get:()=>t.validationMessage},validity:{configurable:!0,get:()=>t.validity}}),t},n.push(()=>{HTMLElement.prototype.attachInternals=s});let appendFormValue=(e,t,n)=>{if(n instanceof FormData){for(let[t,r]of n.entries())e.append(t,r);return}e.append(t,n)},c=globalThis.FormData;globalThis.FormData=class FormDataWithFormAssociatedElements extends c{constructor(e,t){super(e,t),e instanceof HTMLFormElement&&walkFlatTree(e,e=>{let t=e.getAttribute(`name`),n=a.get(e);t&&n!=null&&!e.hasAttribute(`disabled`)&&appendFormValue(this,t,n)})}},n.push(()=>{globalThis.FormData=c});let l=HTMLFormElement.prototype.reset;return HTMLFormElement.prototype.reset=function(...e){l.apply(this,e),walkFlatTree(this,e=>{e.formResetCallback?.()})},n.push(()=>{HTMLFormElement.prototype.reset=l}),()=>{for(let e of n)e();n.length=0,t[e]=!1}},describeRoot=e=>e instanceof Element?e.outerHTML.slice(0,500):e instanceof ShadowRoot?`<shadow-root>${e.innerHTML.slice(0,500)}</shadow-root>`:e.nodeName,requireMatch=(e,t,n)=>{if(e)return e;throw new AssayQueryError(`Unable to find ${t} within ${describeRoot(n)}.`)},query=(e,t)=>e.querySelector(t),queryAll=(e,t)=>Array.from(e.querySelectorAll(t)),queryByTestId=(e,t)=>queryAll(e,`[data-testid]`).find(e=>e.getAttribute(`data-testid`)===t)??null,queryAllByTestId=(e,t)=>queryAll(e,`[data-testid]`).filter(e=>e.getAttribute(`data-testid`)===t),queryByText=(e,t,n=`*`)=>{for(let r of e.querySelectorAll(n))if(r.textContent?.trim()===t)return r;return null},queryAllByText=(e,t,n=`*`)=>queryAll(e,n).filter(e=>e.textContent?.trim()===t);function queryInShadow(e,t){return e.shadowRoot?query(e.shadowRoot,t):null}function queryAllInShadow(e,t){return e.shadowRoot?queryAll(e.shadowRoot,t):[]}function queryPart(e,t){return queryAllInShadow(e,`[part]`).find(e=>e.getAttribute(`part`)?.split(/\s+/).includes(t))??null}function getSlotted(e,t){return Array.from(e.children).filter(e=>t===void 0?!e.getAttribute(`slot`):e.getAttribute(`slot`)===t)}function within(e){return{get:t=>requireMatch(query(e,t),`"${t}"`,e),getByTestId:t=>requireMatch(queryByTestId(e,t),`data-testid "${t}"`,e),getByText:(t,n=`*`)=>requireMatch(queryByText(e,t,n),`text "${t}" matching "${n}"`,e),query:t=>query(e,t),queryAll:t=>queryAll(e,t),queryAllByTestId:t=>queryAllByTestId(e,t),queryAllByText:(t,n=`*`)=>queryAllByText(e,t,n),queryByTestId:t=>queryByTestId(e,t),queryByText:(t,n=`*`)=>queryByText(e,t,n)}}var n=Symbol(`assay.deadline`),r=2147483647,now=()=>performance.now(),validateDuration=(e,t,n)=>{if(!Number.isFinite(t)||t>r||(n?t<0:t<=0))throw RangeError(`${e} must be a ${n?`non-negative`:`positive`} finite number no greater than ${r}`)},validateWait=(e,t)=>{validateDuration(`interval`,e,!1),validateDuration(`timeout`,t,!0)},runBounded=(e,r,i)=>new Promise((a,o)=>{if(i?.aborted){o((0,t.abortError)(i,`The operation was aborted.`));return}let s=!1,cleanup=()=>!s&&(s=!0,clearTimeout(c),i?.removeEventListener(`abort`,abort),!0),resolveOnce=e=>{cleanup()&&a(e)},rejectOnce=e=>{cleanup()&&o(e)},c=setTimeout(()=>rejectOnce(n),Math.max(0,r-now())),abort=()=>rejectOnce((0,t.abortError)(i,`The operation was aborted.`));i?.addEventListener(`abort`,abort,{once:!0});try{Promise.resolve(e()).then(resolveOnce,rejectOnce)}catch(e){rejectOnce(e)}}),delay=(e=0,n={})=>(validateDuration(`ms`,e,!0),(0,t.sleep)(e,n.signal));async function waitUntil(e,{interval:r=50,signal:i,timeout:a=1e3}={}){validateWait(r,a);let o=now()+a,s=!0;for(;;){if(i?.aborted)throw(0,t.abortError)(i,`The operation was aborted.`);if(!s&&now()>=o)throw new AssayTimeoutError(`waitUntil timed out after ${a}ms`);s=!1;let c;try{c=await runBounded(e,o,i)}catch(e){throw e===n?new AssayTimeoutError(`waitUntil timed out after ${a}ms`):e}if(c)return;let l=o-now();if(l<=0)throw new AssayTimeoutError(`waitUntil timed out after ${a}ms`);await(0,t.sleep)(Math.min(r,l),i)}}async function eventually(e,{interval:r=50,message:i,signal:a,timeout:o=1e3}={}){validateWait(r,o);let s=now()+o,c=!0,l;for(;;){if(a?.aborted)throw(0,t.abortError)(a,`The operation was aborted.`);if(!c&&now()>=s)break;c=!1;try{await runBounded(e,s,a);return}catch(e){if(a?.aborted)throw(0,t.abortError)(a,`The operation was aborted.`);if(e===n)break;l=e}let i=s-now();if(i<=0)break;await(0,t.sleep)(Math.min(r,i),a)}let u=`eventually timed out after ${o}ms`,d=i?`${i} (${u})`:u,f=l instanceof Error?l.message:l==null?``:String(l);throw new AssayTimeoutError(f?`${d}\n${f}`:d,{cause:l})}function waitForEvent(e,n,{signal:r,timeout:i=1e3}={}){return validateDuration(`timeout`,i,!0),new Promise((a,o)=>{if(r?.aborted){o((0,t.abortError)(r,`The operation was aborted.`));return}let dispose=()=>{clearTimeout(s),r?.removeEventListener(`abort`,onAbort),e.removeEventListener(n,onEvent)},onEvent=e=>{dispose(),a(e)},s=setTimeout(()=>{dispose(),o(new AssayTimeoutError(`waitForEvent: "${n}" timed out after ${i}ms`))},i),onAbort=()=>{dispose(),o((0,t.abortError)(r,`The operation was aborted.`))};e.addEventListener(n,onEvent,{once:!0}),r?.addEventListener(`abort`,onAbort,{once:!0})})}return e.AssayError=AssayError,e.AssayQueryError=AssayQueryError,e.AssayTimeoutError=AssayTimeoutError,e.delay=delay,e.dispatch=dispatch,e.eventually=eventually,e.fireBlur=fireBlur,e.fireChange=fireChange,e.fireClick=fireClick,e.fireCustom=fireCustom,e.fireFocus=fireFocus,e.fireInput=fireInput,e.fireKeyDown=fireKeyDown,e.fireKeyUp=fireKeyUp,e.fireSubmit=fireSubmit,e.getSlotted=getSlotted,e.installFormInternalsPolyfill=installFormInternalsPolyfill,e.queryAllInShadow=queryAllInShadow,e.queryInShadow=queryInShadow,e.queryPart=queryPart,e.waitForEvent=waitForEvent,e.waitUntil=waitUntil,e.walkFlatTree=walkFlatTree,e.within=within,e})({},Arsenal);
|
|
2
2
|
//# sourceMappingURL=assay.iife.js.map
|
package/dist/assay.iife.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assay.iife.js","names":[],"sources":["../src/errors.ts","../src/events.ts","../src/query.ts","../src/wait.ts"],"sourcesContent":["/** Base class for all Assay errors. Use `instanceof AssayError` to catch any Assay-originated error. */\nexport class AssayError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a required query has no match. */\nexport class AssayQueryError extends AssayError {}\n\n/** Thrown when an Assay wait reaches its timeout. */\nexport class AssayTimeoutError extends AssayError {}\n","/**\n * # Confidence boundary: read first\n *\n * `dispatch` is a **low-level synthetic-event dispatch API**. It fires a caller-\n * supplied DOM `Event` synchronously and returns the `dispatchEvent`\n * result. It does **not** model real user interaction: there is no focus/blur\n * sequencing, no input-event coordination, no keyboard layout, no pointer\n * hit-testing, and no trust flag (`event.isTrusted` is always `false`).\n *\n * Use it to drive event handlers in unit/integration tests where you control\n * the exact event shape. For **behavioral confidence**, that a real click\n * actually activates a control, that focus management works end-to-end, that\n * keyboard shortcuts fire under a real input device: write Playwright tests.\n * Assay deliberately stops at the dispatch boundary; anything that depends on\n * the browser's interaction semantics belongs in a browser-driven suite.\n */\n\n/** Dispatch a pre-built `Event` instance unchanged. Returns the `dispatchEvent` result. */\nexport const dispatch = (target: EventTarget, event: Event): boolean => target.dispatchEvent(event);\n\n/** Synthetic convenience dispatchers. They share the same confidence boundary as `dispatch()`. */\nexport const fireBlur = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('blur', init));\n\nexport const fireChange = (target: EventTarget, init: EventInit = {}): boolean =>\n dispatch(target, new Event('change', { bubbles: true, ...init }));\n\nexport const fireClick = (target: EventTarget, init: MouseEventInit = {}): boolean =>\n dispatch(target, new MouseEvent('click', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireCustom = <T>(target: EventTarget, type: string, init: CustomEventInit<T> = {}): boolean =>\n dispatch(target, new CustomEvent(type, { bubbles: true, cancelable: true, composed: false, ...init }));\n\nexport const fireFocus = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('focus', init));\n\nexport const fireInput = (target: EventTarget, init: InputEventInit = {}): boolean =>\n dispatch(target, new InputEvent('input', { bubbles: true, ...init }));\n\nexport const fireKeyDown = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireKeyUp = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keyup', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireSubmit = (target: EventTarget, init: SubmitEventInit = {}): boolean =>\n dispatch(target, new SubmitEvent('submit', { bubbles: true, cancelable: true, ...init }));\n","import { AssayQueryError } from './errors';\n\n/** DOM query helpers for test environments. */\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Scoped query helpers for any queryable DOM root: see {@link within}. */\nexport interface QueryScope {\n get<E extends Element = Element>(selector: string): E;\n getByTestId<E extends Element = Element>(testId: string): E;\n getByText<E extends Element = Element>(text: string, selector?: string): E;\n query<E extends Element = Element>(selector: string): E | null;\n queryAll<E extends Element = Element>(selector: string): E[];\n queryAllByTestId<E extends Element = Element>(testId: string): E[];\n queryAllByText<E extends Element = Element>(text: string, selector?: string): E[];\n queryByTestId<E extends Element = Element>(testId: string): E | null;\n queryByText<E extends Element = Element>(text: string, selector?: string): E | null;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\ntype QueryRoot = ParentNode;\n\nconst describeRoot = (root: QueryRoot): string => {\n if (root instanceof Element) return root.outerHTML.slice(0, 500);\n\n if (root instanceof ShadowRoot) return `<shadow-root>${root.innerHTML.slice(0, 500)}</shadow-root>`;\n\n return root.nodeName;\n};\n\nconst requireMatch = <E extends Element>(element: E | null, description: string, root: QueryRoot): E => {\n if (element) return element;\n\n throw new AssayQueryError(`Unable to find ${description} within ${describeRoot(root)}.`);\n};\n\nconst query = <E extends Element = Element>(root: QueryRoot, selector: string): E | null =>\n root.querySelector<E>(selector);\n\nconst queryAll = <E extends Element = Element>(root: QueryRoot, selector: string): E[] => {\n return Array.from(root.querySelectorAll<E>(selector));\n};\n\nconst queryByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E | null =>\n queryAll<E>(root, '[data-testid]').find((element) => element.getAttribute('data-testid') === testId) ?? null;\n\nconst queryAllByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E[] =>\n queryAll<E>(root, '[data-testid]').filter((element) => element.getAttribute('data-testid') === testId);\n\nconst queryByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E | null => {\n for (const element of root.querySelectorAll<E>(selector)) {\n if (element.textContent?.trim() === text) return element;\n }\n\n return null;\n};\n\nconst queryAllByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E[] =>\n queryAll<E>(root, selector).filter((element) => element.textContent?.trim() === text);\n\n/**\n * Queries the shadow root of a custom element for a matching CSS selector.\n * Returns `null` if the element has no shadow root or no match is found: safe to call on\n * both open-shadow custom elements and plain elements without checking `shadowRoot` first.\n */\nexport function queryInShadow<E extends Element = Element>(host: Element, selector: string): E | null {\n return host.shadowRoot ? query<E>(host.shadowRoot, selector) : null;\n}\n\n/** Queries all matching elements inside the shadow root of a custom element. */\nexport function queryAllInShadow<E extends Element = Element>(host: Element, selector: string): E[] {\n return host.shadowRoot ? queryAll<E>(host.shadowRoot, selector) : [];\n}\n\n/**\n * Queries a shadow DOM element by its CSS `part` attribute: shorthand for\n * `queryInShadow(host, '[part=\"name\"]')`.\n *\n * @example\n * const btn = queryPart(carousel, 'prev-btn');\n * expect(btn).not.toBeNull();\n */\nexport function queryPart<E extends Element = Element>(host: Element, part: string): E | null {\n return (\n queryAllInShadow<E>(host, '[part]').find((element) => element.getAttribute('part')?.split(/\\s+/).includes(part)) ??\n null\n );\n}\n\n/**\n * Returns the light-DOM children assigned to a named slot, or every child assigned to the\n * default slot when no name is given.\n *\n * @example\n * const slides = getSlotted(carousel);\n * expect(slides).toHaveLength(3);\n */\nexport function getSlotted<E extends Element = Element>(host: Element, slotName?: string): E[] {\n return Array.from(host.children).filter((element) =>\n slotName === undefined ? !element.getAttribute('slot') : element.getAttribute('slot') === slotName,\n ) as E[];\n}\n\n// ─── API ─────────────────────────────────────────────────────────────────────\n\n/**\n * Create query helpers scoped to a DOM root: useful for light DOM and shadow roots.\n *\n * @example\n * const view = within(fixture.shadow!);\n * expect(view.get('.title').textContent).toBe('Hello');\n */\nexport function within(root: QueryRoot): QueryScope {\n return {\n get: <E extends Element = Element>(selector: string) =>\n requireMatch(query<E>(root, selector), `\"${selector}\"`, root),\n getByTestId: <E extends Element = Element>(testId: string) =>\n requireMatch(queryByTestId<E>(root, testId), `data-testid \"${testId}\"`, root),\n getByText: <E extends Element = Element>(text: string, selector = '*') =>\n requireMatch(queryByText<E>(root, text, selector), `text \"${text}\" matching \"${selector}\"`, root),\n query: <E extends Element = Element>(selector: string) => query<E>(root, selector),\n queryAll: <E extends Element = Element>(selector: string) => queryAll<E>(root, selector),\n queryAllByTestId: <E extends Element = Element>(testId: string) => queryAllByTestId<E>(root, testId),\n queryAllByText: <E extends Element = Element>(text: string, selector = '*') =>\n queryAllByText<E>(root, text, selector),\n queryByTestId: <E extends Element = Element>(testId: string) => queryByTestId<E>(root, testId),\n queryByText: <E extends Element = Element>(text: string, selector = '*') => queryByText<E>(root, text, selector),\n };\n}\n","import { abortError, sleep } from '@vielzeug/arsenal';\n\nimport { AssayTimeoutError } from './errors';\n\nexport interface DelayOptions {\n signal?: AbortSignal;\n}\n\nexport interface WaitOptions {\n /** Polling interval in ms (default: 50). */\n interval?: number;\n /** Cancel the pending wait. */\n signal?: AbortSignal;\n /** Maximum wait time in ms (default: 1000). */\n timeout?: number;\n}\n\nexport interface EventuallyOptions extends WaitOptions {\n /** Context included in the timeout error. */\n message?: string;\n}\n\nconst DEADLINE = Symbol('assay.deadline');\nconst MAX_TIMER_MS = 2_147_483_647;\nconst now = (): number => performance.now();\n\nconst validateDuration = (name: string, value: number, allowZero: boolean): void => {\n if (!Number.isFinite(value) || value > MAX_TIMER_MS || (allowZero ? value < 0 : value <= 0)) {\n throw new RangeError(\n `${name} must be a ${allowZero ? 'non-negative' : 'positive'} finite number no greater than ${MAX_TIMER_MS}`,\n );\n }\n};\n\nconst validateWait = (interval: number, timeout: number): void => {\n validateDuration('interval', interval, false);\n validateDuration('timeout', timeout, true);\n};\n\nconst runBounded = <T>(run: () => T | Promise<T>, deadline: number, signal?: AbortSignal): Promise<T> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n let settled = false;\n const cleanup = (): boolean => {\n if (settled) return false;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n return true;\n };\n const resolveOnce = (value: T): void => {\n if (cleanup()) resolve(value);\n };\n const rejectOnce = (error: unknown): void => {\n if (cleanup()) reject(error);\n };\n const timer = setTimeout(() => rejectOnce(DEADLINE), Math.max(0, deadline - now()));\n const abort = () => rejectOnce(abortError(signal, 'The operation was aborted.'));\n\n signal?.addEventListener('abort', abort, { once: true });\n\n try {\n Promise.resolve(run()).then(resolveOnce, rejectOnce);\n } catch (error) {\n rejectOnce(error);\n }\n });\n\nexport const delay = (ms = 0, options: DelayOptions = {}): Promise<void> => {\n validateDuration('ms', ms, true);\n return sleep(ms, options.signal);\n};\n\nexport async function waitUntil(\n predicate: () => boolean | Promise<boolean>,\n { interval = 50, signal, timeout = 1000 }: WaitOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n first = false;\n\n let matched: boolean;\n try {\n matched = await runBounded(predicate, deadline, signal);\n } catch (error) {\n if (error === DEADLINE) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n throw error;\n }\n if (matched) return;\n\n const remaining = deadline - now();\n if (remaining <= 0) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n await sleep(Math.min(interval, remaining), signal);\n }\n}\n\n/**\n * Retry an assertion until it stops throwing or the timeout elapses.\n *\n * Polls the assertion on a fixed interval and preserves the last failure as the\n * timeout cause. Pending asynchronous assertions remain bounded by the same\n * deadline. Use `waitUntil()` for boolean conditions, `delay()` for explicit\n * timer dependencies, and `nextTick()` for one queued microtask boundary.\n *\n * @example\n * await eventually(() => expect(region.textContent).toBe('Saved'));\n */\nexport async function eventually(\n assertion: () => void | Promise<void>,\n { interval = 50, message, signal, timeout = 1000 }: EventuallyOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n let lastError: unknown;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) break;\n first = false;\n\n try {\n await runBounded(assertion, deadline, signal);\n return;\n } catch (error) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (error === DEADLINE) break;\n lastError = error;\n }\n\n const remaining = deadline - now();\n if (remaining <= 0) break;\n await sleep(Math.min(interval, remaining), signal);\n }\n\n const timing = `eventually timed out after ${timeout}ms`;\n const context = message ? `${message} (${timing})` : timing;\n const detail = lastError instanceof Error ? lastError.message : lastError == null ? '' : String(lastError);\n\n throw new AssayTimeoutError(detail ? `${context}\\n${detail}` : context, { cause: lastError });\n}\n\n/** Resolve with the next event of `type`, or reject when it times out or is aborted. */\nexport function waitForEvent<T extends Event = Event>(\n target: EventTarget,\n type: string,\n { signal, timeout = 1000 }: Omit<WaitOptions, 'interval'> = {},\n): Promise<T> {\n validateDuration('timeout', timeout, true);\n\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n const dispose = () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n target.removeEventListener(type, onEvent);\n };\n const onEvent = (event: Event): void => {\n dispose();\n resolve(event as T);\n };\n const timer = setTimeout(() => {\n dispose();\n reject(new AssayTimeoutError(`waitForEvent: \"${type}\" timed out after ${timeout}ms`));\n }, timeout);\n const onAbort = () => {\n dispose();\n reject(abortError(signal, 'The operation was aborted.'));\n };\n\n target.addEventListener(type, onEvent, { once: true });\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n"],"mappings":"sFACA,IAAa,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,UAAW,CAAC,EAG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AO,EAC5C,EAAO,oBAAoB,EAAM,OAAO,CAC1C,EACM,QAAW,GAAuB,CACtC,QAAQ,EACR,EAAQ,CAAU,CACpB,EACM,EAAQ,eAAiB,CAC7B,QAAQ,EACR,EAAO,IAAI,kBAAkB,kBAAkB,EAAK,oBAAoB,EAAQ,GAAG,CAAC,CACtF,EAAG,CAAO,EACJ,YAAgB,CACpB,QAAQ,EACR,GAAA,EAAO,EAAA,WAAA,CAAW,EAAQ,4BAA4B,CAAC,CACzD,EAEA,EAAO,iBAAiB,EAAM,QAAS,CAAE,KAAM,EAAK,CAAC,EACrD,GAAQ,iBAAiB,QAAS,QAAS,CAAE,KAAM,EAAK,CAAC,CAC3D,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"assay.iife.js","names":[],"sources":["../src/dom.ts","../src/errors.ts","../src/events.ts","../src/form-internals.ts","../src/query.ts","../src/wait.ts"],"sourcesContent":["/**\n * DOM traversal helpers for tests running under jsdom, which only implements the *light* DOM\n * tree: `Element.children`/`querySelectorAll()` never cross a `<slot>` into its assigned\n * elements. Real browsers use the *flat tree* (light DOM with each `<slot>` transparently\n * replaced by what's actually assigned to it) for this: it's what \"form owner\" resolution,\n * `:has()`, and plenty of other DOM algorithms are specified against.\n */\n\n/**\n * Walks the flat tree starting at `root`, calling `visit` for every element encountered :\n * expanding each `<slot>` via `assignedElements()` instead of descending into its (always\n * empty, in jsdom) literal children.\n *\n * @example\n * ```ts\n * // Find every form-associated element slotted (possibly through nested slots) under `form`,\n * // something `form.querySelectorAll('[name]')` can't do once a shadow boundary is involved.\n * const named: HTMLElement[] = [];\n * walkFlatTree(form, (el) => { if (el.hasAttribute('name')) named.push(el); });\n * ```\n */\nexport const walkFlatTree = (root: Element, visit: (element: HTMLElement) => void): void => {\n const children = root instanceof HTMLSlotElement ? root.assignedElements({ flatten: true }) : root.children;\n\n for (const child of Array.from(children)) {\n if (!(child instanceof HTMLSlotElement)) visit(child as HTMLElement);\n\n walkFlatTree(child, visit);\n }\n};\n","/** Base class for all Assay errors. Use `instanceof AssayError` to catch any Assay-originated error. */\nexport class AssayError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a required query has no match. */\nexport class AssayQueryError extends AssayError {}\n\n/** Thrown when an Assay wait reaches its timeout. */\nexport class AssayTimeoutError extends AssayError {}\n","/**\n * # Confidence boundary: read first\n *\n * `dispatch` is a **low-level synthetic-event dispatch API**. It fires a caller-\n * supplied DOM `Event` synchronously and returns the `dispatchEvent`\n * result. It does **not** model real user interaction: there is no focus/blur\n * sequencing, no input-event coordination, no keyboard layout, no pointer\n * hit-testing, and no trust flag (`event.isTrusted` is always `false`).\n *\n * Use it to drive event handlers in unit/integration tests where you control\n * the exact event shape. For **behavioral confidence**, that a real click\n * actually activates a control, that focus management works end-to-end, that\n * keyboard shortcuts fire under a real input device: write Playwright tests.\n * Assay deliberately stops at the dispatch boundary; anything that depends on\n * the browser's interaction semantics belongs in a browser-driven suite.\n */\n\n/** Dispatch a pre-built `Event` instance unchanged. Returns the `dispatchEvent` result. */\nexport const dispatch = (target: EventTarget, event: Event): boolean => target.dispatchEvent(event);\n\n/** Synthetic convenience dispatchers. They share the same confidence boundary as `dispatch()`. */\nexport const fireBlur = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('blur', init));\n\nexport const fireChange = (target: EventTarget, init: EventInit = {}): boolean =>\n dispatch(target, new Event('change', { bubbles: true, ...init }));\n\nexport const fireClick = (target: EventTarget, init: MouseEventInit = {}): boolean =>\n dispatch(target, new MouseEvent('click', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireCustom = <T>(target: EventTarget, type: string, init: CustomEventInit<T> = {}): boolean =>\n dispatch(target, new CustomEvent(type, { bubbles: true, cancelable: true, composed: false, ...init }));\n\nexport const fireFocus = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('focus', init));\n\nexport const fireInput = (target: EventTarget, init: InputEventInit = {}): boolean =>\n dispatch(target, new InputEvent('input', { bubbles: true, ...init }));\n\nexport const fireKeyDown = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireKeyUp = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keyup', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireSubmit = (target: EventTarget, init: SubmitEventInit = {}): boolean =>\n dispatch(target, new SubmitEvent('submit', { bubbles: true, cancelable: true, ...init }));\n","import { walkFlatTree } from './dom';\n\n/**\n * jsdom implements none of the `ElementInternals` form-association API: not `setFormValue`,\n * not `setValidity`, not the `checkValidity`/`reportValidity`/`validity`/`validationMessage`\n * mixin real browsers put on every `formAssociated: true` element, not even `FormData`\n * collecting a form-associated element's set value, or `<form>.reset()` invoking\n * `formResetCallback()`. Every one of those gaps is exercised by `useField()` (`@vielzeug/ore`),\n * so any package testing a form-associated component needs all of them, not just one.\n *\n * Call this directly from a test setup when the suite tests form-associated components:\n * the patches are global monkey-patches, so suites without them shouldn't pay for them.\n * Returns an `uninstall()` that restores every patched global.\n *\n * Lives in Assay because it patches the DOM environment itself: the gap is in jsdom, not in\n * any package's feature, and Assay is the repo's home for DOM test-environment helpers.\n * `walkFlatTree` handles form-associated custom elements across shadow boundaries, so\n * consumer packages do not need package-local copies of this polyfill.\n */\nexport const installFormInternalsPolyfill = (): (() => void) => {\n // Checked *before* consuming the flag below: an environment without `ElementInternals`\n // installs nothing and should stay eligible to install for real later (e.g. a differently\n // configured environment in the same process), not get marked \"already installed\" for having\n // done nothing.\n if (typeof ElementInternals === 'undefined') return () => {};\n\n const INSTALLED_FLAG = Symbol.for('vielzeug.assay.formInternalsPolyfillInstalled');\n const flagHost = globalThis as Record<symbol, boolean | undefined>;\n\n if (flagHost[INSTALLED_FLAG]) return () => {};\n\n flagHost[INSTALLED_FLAG] = true;\n\n // Every patch pushes its inverse here, so uninstall() restores the environment exactly.\n const restorers: Array<() => void> = [];\n\n const proto = ElementInternals.prototype as unknown as Record<string, unknown>;\n const validityState = new WeakMap<ElementInternals, { flags: ValidityStateFlags; message: string }>();\n const formValueByHost = new WeakMap<HTMLElement, File | FormData | string | null>();\n const hostByInternals = new WeakMap<ElementInternals, HTMLElement>();\n\n const patchProto = (name: string, descriptor: PropertyDescriptor): void => {\n if (name in proto) return;\n\n Object.defineProperty(proto, name, descriptor);\n restorers.push(() => delete proto[name]);\n };\n\n const isValid = (internals: ElementInternals): boolean => {\n const state = validityState.get(internals);\n\n return !state || !Object.values(state.flags).some(Boolean);\n };\n\n patchProto('setFormValue', {\n configurable: true,\n value: function (this: ElementInternals, value: File | FormData | string | null) {\n const host = hostByInternals.get(this);\n\n if (host) formValueByHost.set(host, value);\n },\n writable: true,\n });\n\n patchProto('setValidity', {\n configurable: true,\n // Matches the real platform contract: throws if any flag is true and message is empty.\n // `useField()` itself already guards against triggering this: see forms/field.ts, but\n // the polyfill enforcing it too means a test would still catch a *different* caller doing\n // the same thing wrong, instead of that bug only surfacing in a real browser.\n value: function (this: ElementInternals, flags: ValidityStateFlags = {}, message = '') {\n if (Object.values(flags).some(Boolean) && !message) {\n throw new TypeError(\n \"Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if \" +\n 'one or more flags in the first argument are true.',\n );\n }\n\n validityState.set(this, { flags, message });\n },\n writable: true,\n });\n\n patchProto('checkValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('reportValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('validationMessage', {\n configurable: true,\n get(this: ElementInternals) {\n return isValid(this) ? '' : (validityState.get(this)?.message ?? '');\n },\n });\n\n // A ValidityState-shaped view of the flags passed to setValidity: every known\n // flag defaults to false, `valid` reflects whether any flag is set.\n patchProto('validity', {\n configurable: true,\n get(this: ElementInternals): ValidityState {\n const state = validityState.get(this);\n\n return {\n badInput: false,\n customError: false,\n patternMismatch: false,\n rangeOverflow: false,\n rangeUnderflow: false,\n stepMismatch: false,\n tooLong: false,\n tooShort: false,\n typeMismatch: false,\n valid: isValid(this),\n valueMissing: false,\n ...(state?.flags ?? {}),\n } as ValidityState;\n },\n });\n\n patchProto('states', {\n configurable: true,\n get: function (this: ElementInternals & { _states?: Set<string> }) {\n this._states ??= new Set();\n\n return this._states;\n },\n });\n\n // Real browsers mix `checkValidity`/`reportValidity`/`validity`/`validationMessage` onto any\n // `formAssociated: true` custom element itself (delegating to its internals): not just onto\n // `ElementInternals`. jsdom does neither; mirror it here so a component's own\n // `checkValidity()`/`reportValidity()`, and a test asserting against the element directly,\n // behave the same as they would in a real browser.\n const originalAttachInternals = HTMLElement.prototype.attachInternals;\n\n HTMLElement.prototype.attachInternals = function (this: HTMLElement, ...args: []): ElementInternals {\n const internals = originalAttachInternals.apply(this, args);\n\n hostByInternals.set(internals, this);\n\n Object.defineProperties(this, {\n checkValidity: { configurable: true, value: () => internals.checkValidity() },\n reportValidity: { configurable: true, value: () => internals.reportValidity() },\n validationMessage: { configurable: true, get: () => internals.validationMessage },\n validity: { configurable: true, get: () => internals.validity },\n });\n\n return internals;\n };\n restorers.push(() => {\n HTMLElement.prototype.attachInternals = originalAttachInternals;\n });\n\n const appendFormValue = (formData: FormData, name: string, value: File | FormData | string): void => {\n if (value instanceof FormData) {\n for (const [entryName, entryValue] of value.entries()) formData.append(entryName, entryValue);\n\n return;\n }\n\n formData.append(name, value);\n };\n\n // jsdom's `FormData` constructor never collects a form-associated custom element's set form\n // value: real browsers walk the flat tree for every form-associated element with a `name`.\n const NativeFormData = globalThis.FormData;\n\n globalThis.FormData = class FormDataWithFormAssociatedElements extends NativeFormData {\n constructor(form?: HTMLFormElement, submitter?: HTMLElement | null) {\n super(form as HTMLFormElement | undefined, submitter as HTMLElement | null | undefined);\n\n if (!(form instanceof HTMLFormElement)) return;\n\n walkFlatTree(form, (element) => {\n const name = element.getAttribute('name');\n const value = formValueByHost.get(element);\n\n if (!name || value == null || element.hasAttribute('disabled')) return;\n\n appendFormValue(this, name, value);\n });\n }\n };\n restorers.push(() => {\n globalThis.FormData = NativeFormData;\n });\n\n // jsdom never invokes the native `formResetCallback` lifecycle method on form-associated\n // custom elements when their form resets: patch `reset()` to do it (via the same flat-tree\n // walk, since a reset field can be nested behind a shadow boundary too), so `onFormReset()`\n // (see `@vielzeug/ore`'s runtime.ts) is testable against a real `<form>.reset()` call instead\n // of only by calling `element.formResetCallback()` directly.\n const originalReset = HTMLFormElement.prototype.reset;\n\n HTMLFormElement.prototype.reset = function (this: HTMLFormElement, ...args: []) {\n originalReset.apply(this, args);\n\n walkFlatTree(this, (element) => {\n (element as Partial<{ formResetCallback: () => void }>).formResetCallback?.();\n });\n };\n restorers.push(() => {\n HTMLFormElement.prototype.reset = originalReset;\n });\n\n return () => {\n for (const restore of restorers) restore();\n\n restorers.length = 0;\n flagHost[INSTALLED_FLAG] = false;\n };\n};\n","import { AssayQueryError } from './errors';\n\n/** DOM query helpers for test environments. */\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Scoped query helpers for any queryable DOM root: see {@link within}. */\nexport interface QueryScope {\n get<E extends Element = Element>(selector: string): E;\n getByTestId<E extends Element = Element>(testId: string): E;\n getByText<E extends Element = Element>(text: string, selector?: string): E;\n query<E extends Element = Element>(selector: string): E | null;\n queryAll<E extends Element = Element>(selector: string): E[];\n queryAllByTestId<E extends Element = Element>(testId: string): E[];\n queryAllByText<E extends Element = Element>(text: string, selector?: string): E[];\n queryByTestId<E extends Element = Element>(testId: string): E | null;\n queryByText<E extends Element = Element>(text: string, selector?: string): E | null;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\ntype QueryRoot = ParentNode;\n\nconst describeRoot = (root: QueryRoot): string => {\n if (root instanceof Element) return root.outerHTML.slice(0, 500);\n\n if (root instanceof ShadowRoot) return `<shadow-root>${root.innerHTML.slice(0, 500)}</shadow-root>`;\n\n return root.nodeName;\n};\n\nconst requireMatch = <E extends Element>(element: E | null, description: string, root: QueryRoot): E => {\n if (element) return element;\n\n throw new AssayQueryError(`Unable to find ${description} within ${describeRoot(root)}.`);\n};\n\nconst query = <E extends Element = Element>(root: QueryRoot, selector: string): E | null =>\n root.querySelector<E>(selector);\n\nconst queryAll = <E extends Element = Element>(root: QueryRoot, selector: string): E[] => {\n return Array.from(root.querySelectorAll<E>(selector));\n};\n\nconst queryByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E | null =>\n queryAll<E>(root, '[data-testid]').find((element) => element.getAttribute('data-testid') === testId) ?? null;\n\nconst queryAllByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E[] =>\n queryAll<E>(root, '[data-testid]').filter((element) => element.getAttribute('data-testid') === testId);\n\nconst queryByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E | null => {\n for (const element of root.querySelectorAll<E>(selector)) {\n if (element.textContent?.trim() === text) return element;\n }\n\n return null;\n};\n\nconst queryAllByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E[] =>\n queryAll<E>(root, selector).filter((element) => element.textContent?.trim() === text);\n\n/**\n * Queries the shadow root of a custom element for a matching CSS selector.\n * Returns `null` if the element has no shadow root or no match is found: safe to call on\n * both open-shadow custom elements and plain elements without checking `shadowRoot` first.\n */\nexport function queryInShadow<E extends Element = Element>(host: Element, selector: string): E | null {\n return host.shadowRoot ? query<E>(host.shadowRoot, selector) : null;\n}\n\n/** Queries all matching elements inside the shadow root of a custom element. */\nexport function queryAllInShadow<E extends Element = Element>(host: Element, selector: string): E[] {\n return host.shadowRoot ? queryAll<E>(host.shadowRoot, selector) : [];\n}\n\n/**\n * Queries a shadow DOM element by its CSS `part` attribute: shorthand for\n * `queryInShadow(host, '[part=\"name\"]')`.\n *\n * @example\n * const btn = queryPart(carousel, 'prev-btn');\n * expect(btn).not.toBeNull();\n */\nexport function queryPart<E extends Element = Element>(host: Element, part: string): E | null {\n return (\n queryAllInShadow<E>(host, '[part]').find((element) => element.getAttribute('part')?.split(/\\s+/).includes(part)) ??\n null\n );\n}\n\n/**\n * Returns the light-DOM children assigned to a named slot, or every child assigned to the\n * default slot when no name is given.\n *\n * @example\n * const slides = getSlotted(carousel);\n * expect(slides).toHaveLength(3);\n */\nexport function getSlotted<E extends Element = Element>(host: Element, slotName?: string): E[] {\n return Array.from(host.children).filter((element) =>\n slotName === undefined ? !element.getAttribute('slot') : element.getAttribute('slot') === slotName,\n ) as E[];\n}\n\n// ─── API ─────────────────────────────────────────────────────────────────────\n\n/**\n * Create query helpers scoped to a DOM root: useful for light DOM and shadow roots.\n *\n * @example\n * const view = within(fixture.shadow!);\n * expect(view.get('.title').textContent).toBe('Hello');\n */\nexport function within(root: QueryRoot): QueryScope {\n return {\n get: <E extends Element = Element>(selector: string) =>\n requireMatch(query<E>(root, selector), `\"${selector}\"`, root),\n getByTestId: <E extends Element = Element>(testId: string) =>\n requireMatch(queryByTestId<E>(root, testId), `data-testid \"${testId}\"`, root),\n getByText: <E extends Element = Element>(text: string, selector = '*') =>\n requireMatch(queryByText<E>(root, text, selector), `text \"${text}\" matching \"${selector}\"`, root),\n query: <E extends Element = Element>(selector: string) => query<E>(root, selector),\n queryAll: <E extends Element = Element>(selector: string) => queryAll<E>(root, selector),\n queryAllByTestId: <E extends Element = Element>(testId: string) => queryAllByTestId<E>(root, testId),\n queryAllByText: <E extends Element = Element>(text: string, selector = '*') =>\n queryAllByText<E>(root, text, selector),\n queryByTestId: <E extends Element = Element>(testId: string) => queryByTestId<E>(root, testId),\n queryByText: <E extends Element = Element>(text: string, selector = '*') => queryByText<E>(root, text, selector),\n };\n}\n","import { abortError, sleep } from '@vielzeug/arsenal';\n\nimport { AssayTimeoutError } from './errors';\n\nexport interface DelayOptions {\n signal?: AbortSignal;\n}\n\nexport interface WaitOptions {\n /** Polling interval in ms (default: 50). */\n interval?: number;\n /** Cancel the pending wait. */\n signal?: AbortSignal;\n /** Maximum wait time in ms (default: 1000). */\n timeout?: number;\n}\n\nexport interface EventuallyOptions extends WaitOptions {\n /** Context included in the timeout error. */\n message?: string;\n}\n\nconst DEADLINE = Symbol('assay.deadline');\nconst MAX_TIMER_MS = 2_147_483_647;\nconst now = (): number => performance.now();\n\nconst validateDuration = (name: string, value: number, allowZero: boolean): void => {\n if (!Number.isFinite(value) || value > MAX_TIMER_MS || (allowZero ? value < 0 : value <= 0)) {\n throw new RangeError(\n `${name} must be a ${allowZero ? 'non-negative' : 'positive'} finite number no greater than ${MAX_TIMER_MS}`,\n );\n }\n};\n\nconst validateWait = (interval: number, timeout: number): void => {\n validateDuration('interval', interval, false);\n validateDuration('timeout', timeout, true);\n};\n\nconst runBounded = <T>(run: () => T | Promise<T>, deadline: number, signal?: AbortSignal): Promise<T> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n let settled = false;\n const cleanup = (): boolean => {\n if (settled) return false;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n return true;\n };\n const resolveOnce = (value: T): void => {\n if (cleanup()) resolve(value);\n };\n const rejectOnce = (error: unknown): void => {\n if (cleanup()) reject(error);\n };\n const timer = setTimeout(() => rejectOnce(DEADLINE), Math.max(0, deadline - now()));\n const abort = () => rejectOnce(abortError(signal, 'The operation was aborted.'));\n\n signal?.addEventListener('abort', abort, { once: true });\n\n try {\n Promise.resolve(run()).then(resolveOnce, rejectOnce);\n } catch (error) {\n rejectOnce(error);\n }\n });\n\nexport const delay = (ms = 0, options: DelayOptions = {}): Promise<void> => {\n validateDuration('ms', ms, true);\n return sleep(ms, options.signal);\n};\n\nexport async function waitUntil(\n predicate: () => boolean | Promise<boolean>,\n { interval = 50, signal, timeout = 1000 }: WaitOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n first = false;\n\n let matched: boolean;\n try {\n matched = await runBounded(predicate, deadline, signal);\n } catch (error) {\n if (error === DEADLINE) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n throw error;\n }\n if (matched) return;\n\n const remaining = deadline - now();\n if (remaining <= 0) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n await sleep(Math.min(interval, remaining), signal);\n }\n}\n\n/**\n * Retry an assertion until it stops throwing or the timeout elapses.\n *\n * Polls the assertion on a fixed interval and preserves the last failure as the\n * timeout cause. Pending asynchronous assertions remain bounded by the same\n * deadline. Use `waitUntil()` for boolean conditions, `delay()` for explicit\n * timer dependencies, and `nextTick()` for one queued microtask boundary.\n *\n * @example\n * await eventually(() => expect(region.textContent).toBe('Saved'));\n */\nexport async function eventually(\n assertion: () => void | Promise<void>,\n { interval = 50, message, signal, timeout = 1000 }: EventuallyOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n let lastError: unknown;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) break;\n first = false;\n\n try {\n await runBounded(assertion, deadline, signal);\n return;\n } catch (error) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (error === DEADLINE) break;\n lastError = error;\n }\n\n const remaining = deadline - now();\n if (remaining <= 0) break;\n await sleep(Math.min(interval, remaining), signal);\n }\n\n const timing = `eventually timed out after ${timeout}ms`;\n const context = message ? `${message} (${timing})` : timing;\n const detail = lastError instanceof Error ? lastError.message : lastError == null ? '' : String(lastError);\n\n throw new AssayTimeoutError(detail ? `${context}\\n${detail}` : context, { cause: lastError });\n}\n\n/** Resolve with the next event of `type`, or reject when it times out or is aborted. */\nexport function waitForEvent<T extends Event = Event>(\n target: EventTarget,\n type: string,\n { signal, timeout = 1000 }: Omit<WaitOptions, 'interval'> = {},\n): Promise<T> {\n validateDuration('timeout', timeout, true);\n\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n const dispose = () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n target.removeEventListener(type, onEvent);\n };\n const onEvent = (event: Event): void => {\n dispose();\n resolve(event as T);\n };\n const timer = setTimeout(() => {\n dispose();\n reject(new AssayTimeoutError(`waitForEvent: \"${type}\" timed out after ${timeout}ms`));\n }, timeout);\n const onAbort = () => {\n dispose();\n reject(abortError(signal, 'The operation was aborted.'));\n };\n\n target.addEventListener(type, onEvent, { once: true });\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n"],"mappings":"sFAqBA,IAAa,cAAgB,EAAe,IAAgD,CAC1F,IAAM,EAAW,aAAgB,gBAAkB,EAAK,iBAAiB,CAAE,QAAS,EAAK,CAAC,EAAI,EAAK,SAEnG,IAAK,IAAM,KAAS,MAAM,KAAK,CAAQ,EAC/B,aAAiB,iBAAkB,EAAM,CAAoB,EAEnE,aAAa,EAAO,CAAK,CAE7B,EC5Ba,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,UAAW,CAAC,EAGpC,kBAAb,cAAuC,UAAW,CAAC,ECKtC,UAAY,EAAqB,IAA0B,EAAO,cAAc,CAAK,EAGrF,UAAY,EAAqB,EAAuB,CAAC,IACpE,SAAS,EAAQ,IAAI,WAAW,OAAQ,CAAI,CAAC,EAElC,YAAc,EAAqB,EAAkB,CAAC,IACjE,SAAS,EAAQ,IAAI,MAAM,SAAU,CAAE,QAAS,GAAM,GAAG,CAAK,CAAC,CAAC,EAErD,WAAa,EAAqB,EAAuB,CAAC,IACrE,SAAS,EAAQ,IAAI,WAAW,Q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A,CAAE,SAAQ,UAAU,KAAwC,CAAC,EACjD,CAGZ,OAFA,iBAAiB,UAAW,EAAS,EAAI,EAElC,IAAI,SAAS,EAAS,IAAW,CACtC,GAAI,GAAQ,QAAS,CACnB,GAAA,EAAO,EAAA,WAAA,CAAW,EAAQ,4BAA4B,CAAC,EACvD,MACF,CAEA,IAAM,YAAgB,CACpB,aAAa,CAAK,EAClB,GAAQ,oBAAoB,QAAS,OAAO,EAC5C,EAAO,oBAAoB,EAAM,OAAO,CAC1C,EACM,QAAW,GAAuB,CACtC,QAAQ,EACR,EAAQ,CAAU,CACpB,EACM,EAAQ,eAAiB,CAC7B,QAAQ,EACR,EAAO,IAAI,kBAAkB,kBAAkB,EAAK,oBAAoB,EAAQ,GAAG,CAAC,CACtF,EAAG,CAAO,EACJ,YAAgB,CACpB,QAAQ,EACR,GAAA,EAAO,EAAA,WAAA,CAAW,EAAQ,4BAA4B,CAAC,CACzD,EAEA,EAAO,iBAAiB,EAAM,QAAS,CAAE,KAAM,EAAK,CAAC,EACrD,GAAQ,iBAAiB,QAAS,QAAS,CAAE,KAAM,EAAK,CAAC,CAC3D,CAAC,CACH"}
|
package/dist/assay.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{abortError as e,sleep as t}from"@vielzeug/arsenal";var AssayError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},AssayQueryError=class extends AssayError{},AssayTimeoutError=class extends AssayError{},dispatch=(e,t)=>e.dispatchEvent(t),fireBlur=(e,t={})=>dispatch(e,new FocusEvent(`blur`,t)),fireChange=(e,t={})=>dispatch(e,new Event(`change`,{bubbles:!0,...t})),fireClick=(e,t={})=>dispatch(e,new MouseEvent(`click`,{bubbles:!0,cancelable:!0,...t})),fireCustom=(e,t,n={})=>dispatch(e,new CustomEvent(t,{bubbles:!0,cancelable:!0,composed:!1,...n})),fireFocus=(e,t={})=>dispatch(e,new FocusEvent(`focus`,t)),fireInput=(e,t={})=>dispatch(e,new InputEvent(`input`,{bubbles:!0,...t})),fireKeyDown=(e,t={})=>dispatch(e,new KeyboardEvent(`keydown`,{bubbles:!0,cancelable:!0,...t})),fireKeyUp=(e,t={})=>dispatch(e,new KeyboardEvent(`keyup`,{bubbles:!0,cancelable:!0,...t})),fireSubmit=(e,t={})=>dispatch(e,new SubmitEvent(`submit`,{bubbles:!0,cancelable:!0,...t})),describeRoot=e=>e instanceof Element?e.outerHTML.slice(0,500):e instanceof ShadowRoot?`<shadow-root>${e.innerHTML.slice(0,500)}</shadow-root>`:e.nodeName,requireMatch=(e,t,n)=>{if(e)return e;throw new AssayQueryError(`Unable to find ${t} within ${describeRoot(n)}.`)},query=(e,t)=>e.querySelector(t),queryAll=(e,t)=>Array.from(e.querySelectorAll(t)),queryByTestId=(e,t)=>queryAll(e,`[data-testid]`).find(e=>e.getAttribute(`data-testid`)===t)??null,queryAllByTestId=(e,t)=>queryAll(e,`[data-testid]`).filter(e=>e.getAttribute(`data-testid`)===t),queryByText=(e,t,n=`*`)=>{for(let r of e.querySelectorAll(n))if(r.textContent?.trim()===t)return r;return null},queryAllByText=(e,t,n=`*`)=>queryAll(e,n).filter(e=>e.textContent?.trim()===t);function queryInShadow(e,t){return e.shadowRoot?query(e.shadowRoot,t):null}function queryAllInShadow(e,t){return e.shadowRoot?queryAll(e.shadowRoot,t):[]}function queryPart(e,t){return queryAllInShadow(e,`[part]`).find(e=>e.getAttribute(`part`)?.split(/\s+/).includes(t))??null}function getSlotted(e,t){return Array.from(e.children).filter(e=>t===void 0?!e.getAttribute(`slot`):e.getAttribute(`slot`)===t)}function within(e){return{get:t=>requireMatch(query(e,t),`"${t}"`,e),getByTestId:t=>requireMatch(queryByTestId(e,t),`data-testid "${t}"`,e),getByText:(t,n=`*`)=>requireMatch(queryByText(e,t,n),`text "${t}" matching "${n}"`,e),query:t=>query(e,t),queryAll:t=>queryAll(e,t),queryAllByTestId:t=>queryAllByTestId(e,t),queryAllByText:(t,n=`*`)=>queryAllByText(e,t,n),queryByTestId:t=>queryByTestId(e,t),queryByText:(t,n=`*`)=>queryByText(e,t,n)}}var n=Symbol(`assay.deadline`),r=2147483647,now=()=>performance.now(),validateDuration=(e,t,n)=>{if(!Number.isFinite(t)||t>r||(n?t<0:t<=0))throw RangeError(`${e} must be a ${n?`non-negative`:`positive`} finite number no greater than ${r}`)},validateWait=(e,t)=>{validateDuration(`interval`,e,!1),validateDuration(`timeout`,t,!0)},runBounded=(t,r,i)=>new Promise((a,o)=>{if(i?.aborted){o(e(i,`The operation was aborted.`));return}let s=!1,cleanup=()=>!s&&(s=!0,clearTimeout(c),i?.removeEventListener(`abort`,abort),!0),resolveOnce=e=>{cleanup()&&a(e)},rejectOnce=e=>{cleanup()&&o(e)},c=setTimeout(()=>rejectOnce(n),Math.max(0,r-now())),abort=()=>rejectOnce(e(i,`The operation was aborted.`));i?.addEventListener(`abort`,abort,{once:!0});try{Promise.resolve(t()).then(resolveOnce,rejectOnce)}catch(e){rejectOnce(e)}}),delay=(e=0,n={})=>(validateDuration(`ms`,e,!0),t(e,n.signal));async function waitUntil(r,{interval:i=50,signal:a,timeout:o=1e3}={}){validateWait(i,o);let s=now()+o,c=!0;for(;;){if(a?.aborted)throw e(a,`The operation was aborted.`);if(!c&&now()>=s)throw new AssayTimeoutError(`waitUntil timed out after ${o}ms`);c=!1;let l;try{l=await runBounded(r,s,a)}catch(e){throw e===n?new AssayTimeoutError(`waitUntil timed out after ${o}ms`):e}if(l)return;let u=s-now();if(u<=0)throw new AssayTimeoutError(`waitUntil timed out after ${o}ms`);await t(Math.min(i,u),a)}}async function eventually(r,{interval:i=50,message:a,signal:o,timeout:s=1e3}={}){validateWait(i,s);let c=now()+s,l=!0,u;for(;;){if(o?.aborted)throw e(o,`The operation was aborted.`);if(!l&&now()>=c)break;l=!1;try{await runBounded(r,c,o);return}catch(t){if(o?.aborted)throw e(o,`The operation was aborted.`);if(t===n)break;u=t}let a=c-now();if(a<=0)break;await t(Math.min(i,a),o)}let d=`eventually timed out after ${s}ms`,f=a?`${a} (${d})`:d,p=u instanceof Error?u.message:u==null?``:String(u);throw new AssayTimeoutError(p?`${f}\n${p}`:f,{cause:u})}function waitForEvent(t,n,{signal:r,timeout:i=1e3}={}){return validateDuration(`timeout`,i,!0),new Promise((a,o)=>{if(r?.aborted){o(e(r,`The operation was aborted.`));return}let dispose=()=>{clearTimeout(s),r?.removeEventListener(`abort`,onAbort),t.removeEventListener(n,onEvent)},onEvent=e=>{dispose(),a(e)},s=setTimeout(()=>{dispose(),o(new AssayTimeoutError(`waitForEvent: "${n}" timed out after ${i}ms`))},i),onAbort=()=>{dispose(),o(e(r,`The operation was aborted.`))};t.addEventListener(n,onEvent,{once:!0}),r?.addEventListener(`abort`,onAbort,{once:!0})})}export{AssayError,AssayQueryError,AssayTimeoutError,delay,dispatch,eventually,fireBlur,fireChange,fireClick,fireCustom,fireFocus,fireInput,fireKeyDown,fireKeyUp,fireSubmit,getSlotted,queryAllInShadow,queryInShadow,queryPart,waitForEvent,waitUntil,within};
|
|
1
|
+
import{abortError as e,sleep as t}from"@vielzeug/arsenal";var walkFlatTree=(e,t)=>{let n=e instanceof HTMLSlotElement?e.assignedElements({flatten:!0}):e.children;for(let e of Array.from(n))e instanceof HTMLSlotElement||t(e),walkFlatTree(e,t)},AssayError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},AssayQueryError=class extends AssayError{},AssayTimeoutError=class extends AssayError{},dispatch=(e,t)=>e.dispatchEvent(t),fireBlur=(e,t={})=>dispatch(e,new FocusEvent(`blur`,t)),fireChange=(e,t={})=>dispatch(e,new Event(`change`,{bubbles:!0,...t})),fireClick=(e,t={})=>dispatch(e,new MouseEvent(`click`,{bubbles:!0,cancelable:!0,...t})),fireCustom=(e,t,n={})=>dispatch(e,new CustomEvent(t,{bubbles:!0,cancelable:!0,composed:!1,...n})),fireFocus=(e,t={})=>dispatch(e,new FocusEvent(`focus`,t)),fireInput=(e,t={})=>dispatch(e,new InputEvent(`input`,{bubbles:!0,...t})),fireKeyDown=(e,t={})=>dispatch(e,new KeyboardEvent(`keydown`,{bubbles:!0,cancelable:!0,...t})),fireKeyUp=(e,t={})=>dispatch(e,new KeyboardEvent(`keyup`,{bubbles:!0,cancelable:!0,...t})),fireSubmit=(e,t={})=>dispatch(e,new SubmitEvent(`submit`,{bubbles:!0,cancelable:!0,...t})),installFormInternalsPolyfill=()=>{if(typeof ElementInternals>`u`)return()=>{};let e=Symbol.for(`vielzeug.assay.formInternalsPolyfillInstalled`),t=globalThis;if(t[e])return()=>{};t[e]=!0;let n=[],r=ElementInternals.prototype,i=new WeakMap,a=new WeakMap,o=new WeakMap,patchProto=(e,t)=>{e in r||(Object.defineProperty(r,e,t),n.push(()=>delete r[e]))},isValid=e=>{let t=i.get(e);return!t||!Object.values(t.flags).some(Boolean)};patchProto(`setFormValue`,{configurable:!0,value:function(e){let t=o.get(this);t&&a.set(t,e)},writable:!0}),patchProto(`setValidity`,{configurable:!0,value:function(e={},t=``){if(Object.values(e).some(Boolean)&&!t)throw TypeError(`Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if one or more flags in the first argument are true.`);i.set(this,{flags:e,message:t})},writable:!0}),patchProto(`checkValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`reportValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`validationMessage`,{configurable:!0,get(){return isValid(this)?``:i.get(this)?.message??``}}),patchProto(`validity`,{configurable:!0,get(){let e=i.get(this);return{badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:isValid(this),valueMissing:!1,...e?.flags??{}}}}),patchProto(`states`,{configurable:!0,get:function(){return this._states??=new Set,this._states}});let s=HTMLElement.prototype.attachInternals;HTMLElement.prototype.attachInternals=function(...e){let t=s.apply(this,e);return o.set(t,this),Object.defineProperties(this,{checkValidity:{configurable:!0,value:()=>t.checkValidity()},reportValidity:{configurable:!0,value:()=>t.reportValidity()},validationMessage:{configurable:!0,get:()=>t.validationMessage},validity:{configurable:!0,get:()=>t.validity}}),t},n.push(()=>{HTMLElement.prototype.attachInternals=s});let appendFormValue=(e,t,n)=>{if(n instanceof FormData){for(let[t,r]of n.entries())e.append(t,r);return}e.append(t,n)},c=globalThis.FormData;globalThis.FormData=class FormDataWithFormAssociatedElements extends c{constructor(e,t){super(e,t),e instanceof HTMLFormElement&&walkFlatTree(e,e=>{let t=e.getAttribute(`name`),n=a.get(e);t&&n!=null&&!e.hasAttribute(`disabled`)&&appendFormValue(this,t,n)})}},n.push(()=>{globalThis.FormData=c});let l=HTMLFormElement.prototype.reset;return HTMLFormElement.prototype.reset=function(...e){l.apply(this,e),walkFlatTree(this,e=>{e.formResetCallback?.()})},n.push(()=>{HTMLFormElement.prototype.reset=l}),()=>{for(let e of n)e();n.length=0,t[e]=!1}},describeRoot=e=>e instanceof Element?e.outerHTML.slice(0,500):e instanceof ShadowRoot?`<shadow-root>${e.innerHTML.slice(0,500)}</shadow-root>`:e.nodeName,requireMatch=(e,t,n)=>{if(e)return e;throw new AssayQueryError(`Unable to find ${t} within ${describeRoot(n)}.`)},query=(e,t)=>e.querySelector(t),queryAll=(e,t)=>Array.from(e.querySelectorAll(t)),queryByTestId=(e,t)=>queryAll(e,`[data-testid]`).find(e=>e.getAttribute(`data-testid`)===t)??null,queryAllByTestId=(e,t)=>queryAll(e,`[data-testid]`).filter(e=>e.getAttribute(`data-testid`)===t),queryByText=(e,t,n=`*`)=>{for(let r of e.querySelectorAll(n))if(r.textContent?.trim()===t)return r;return null},queryAllByText=(e,t,n=`*`)=>queryAll(e,n).filter(e=>e.textContent?.trim()===t);function queryInShadow(e,t){return e.shadowRoot?query(e.shadowRoot,t):null}function queryAllInShadow(e,t){return e.shadowRoot?queryAll(e.shadowRoot,t):[]}function queryPart(e,t){return queryAllInShadow(e,`[part]`).find(e=>e.getAttribute(`part`)?.split(/\s+/).includes(t))??null}function getSlotted(e,t){return Array.from(e.children).filter(e=>t===void 0?!e.getAttribute(`slot`):e.getAttribute(`slot`)===t)}function within(e){return{get:t=>requireMatch(query(e,t),`"${t}"`,e),getByTestId:t=>requireMatch(queryByTestId(e,t),`data-testid "${t}"`,e),getByText:(t,n=`*`)=>requireMatch(queryByText(e,t,n),`text "${t}" matching "${n}"`,e),query:t=>query(e,t),queryAll:t=>queryAll(e,t),queryAllByTestId:t=>queryAllByTestId(e,t),queryAllByText:(t,n=`*`)=>queryAllByText(e,t,n),queryByTestId:t=>queryByTestId(e,t),queryByText:(t,n=`*`)=>queryByText(e,t,n)}}var n=Symbol(`assay.deadline`),r=2147483647,now=()=>performance.now(),validateDuration=(e,t,n)=>{if(!Number.isFinite(t)||t>r||(n?t<0:t<=0))throw RangeError(`${e} must be a ${n?`non-negative`:`positive`} finite number no greater than ${r}`)},validateWait=(e,t)=>{validateDuration(`interval`,e,!1),validateDuration(`timeout`,t,!0)},runBounded=(t,r,i)=>new Promise((a,o)=>{if(i?.aborted){o(e(i,`The operation was aborted.`));return}let s=!1,cleanup=()=>!s&&(s=!0,clearTimeout(c),i?.removeEventListener(`abort`,abort),!0),resolveOnce=e=>{cleanup()&&a(e)},rejectOnce=e=>{cleanup()&&o(e)},c=setTimeout(()=>rejectOnce(n),Math.max(0,r-now())),abort=()=>rejectOnce(e(i,`The operation was aborted.`));i?.addEventListener(`abort`,abort,{once:!0});try{Promise.resolve(t()).then(resolveOnce,rejectOnce)}catch(e){rejectOnce(e)}}),delay=(e=0,n={})=>(validateDuration(`ms`,e,!0),t(e,n.signal));async function waitUntil(r,{interval:i=50,signal:a,timeout:o=1e3}={}){validateWait(i,o);let s=now()+o,c=!0;for(;;){if(a?.aborted)throw e(a,`The operation was aborted.`);if(!c&&now()>=s)throw new AssayTimeoutError(`waitUntil timed out after ${o}ms`);c=!1;let l;try{l=await runBounded(r,s,a)}catch(e){throw e===n?new AssayTimeoutError(`waitUntil timed out after ${o}ms`):e}if(l)return;let u=s-now();if(u<=0)throw new AssayTimeoutError(`waitUntil timed out after ${o}ms`);await t(Math.min(i,u),a)}}async function eventually(r,{interval:i=50,message:a,signal:o,timeout:s=1e3}={}){validateWait(i,s);let c=now()+s,l=!0,u;for(;;){if(o?.aborted)throw e(o,`The operation was aborted.`);if(!l&&now()>=c)break;l=!1;try{await runBounded(r,c,o);return}catch(t){if(o?.aborted)throw e(o,`The operation was aborted.`);if(t===n)break;u=t}let a=c-now();if(a<=0)break;await t(Math.min(i,a),o)}let d=`eventually timed out after ${s}ms`,f=a?`${a} (${d})`:d,p=u instanceof Error?u.message:u==null?``:String(u);throw new AssayTimeoutError(p?`${f}\n${p}`:f,{cause:u})}function waitForEvent(t,n,{signal:r,timeout:i=1e3}={}){return validateDuration(`timeout`,i,!0),new Promise((a,o)=>{if(r?.aborted){o(e(r,`The operation was aborted.`));return}let dispose=()=>{clearTimeout(s),r?.removeEventListener(`abort`,onAbort),t.removeEventListener(n,onEvent)},onEvent=e=>{dispose(),a(e)},s=setTimeout(()=>{dispose(),o(new AssayTimeoutError(`waitForEvent: "${n}" timed out after ${i}ms`))},i),onAbort=()=>{dispose(),o(e(r,`The operation was aborted.`))};t.addEventListener(n,onEvent,{once:!0}),r?.addEventListener(`abort`,onAbort,{once:!0})})}export{AssayError,AssayQueryError,AssayTimeoutError,delay,dispatch,eventually,fireBlur,fireChange,fireClick,fireCustom,fireFocus,fireInput,fireKeyDown,fireKeyUp,fireSubmit,getSlotted,installFormInternalsPolyfill,queryAllInShadow,queryInShadow,queryPart,waitForEvent,waitUntil,walkFlatTree,within};
|
|
2
2
|
//# sourceMappingURL=assay.js.map
|
package/dist/assay.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assay.js","names":[],"sources":["../src/errors.ts","../src/events.ts","../src/query.ts","../src/wait.ts"],"sourcesContent":["/** Base class for all Assay errors. Use `instanceof AssayError` to catch any Assay-originated error. */\nexport class AssayError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a required query has no match. */\nexport class AssayQueryError extends AssayError {}\n\n/** Thrown when an Assay wait reaches its timeout. */\nexport class AssayTimeoutError extends AssayError {}\n","/**\n * # Confidence boundary: read first\n *\n * `dispatch` is a **low-level synthetic-event dispatch API**. It fires a caller-\n * supplied DOM `Event` synchronously and returns the `dispatchEvent`\n * result. It does **not** model real user interaction: there is no focus/blur\n * sequencing, no input-event coordination, no keyboard layout, no pointer\n * hit-testing, and no trust flag (`event.isTrusted` is always `false`).\n *\n * Use it to drive event handlers in unit/integration tests where you control\n * the exact event shape. For **behavioral confidence**, that a real click\n * actually activates a control, that focus management works end-to-end, that\n * keyboard shortcuts fire under a real input device: write Playwright tests.\n * Assay deliberately stops at the dispatch boundary; anything that depends on\n * the browser's interaction semantics belongs in a browser-driven suite.\n */\n\n/** Dispatch a pre-built `Event` instance unchanged. Returns the `dispatchEvent` result. */\nexport const dispatch = (target: EventTarget, event: Event): boolean => target.dispatchEvent(event);\n\n/** Synthetic convenience dispatchers. They share the same confidence boundary as `dispatch()`. */\nexport const fireBlur = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('blur', init));\n\nexport const fireChange = (target: EventTarget, init: EventInit = {}): boolean =>\n dispatch(target, new Event('change', { bubbles: true, ...init }));\n\nexport const fireClick = (target: EventTarget, init: MouseEventInit = {}): boolean =>\n dispatch(target, new MouseEvent('click', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireCustom = <T>(target: EventTarget, type: string, init: CustomEventInit<T> = {}): boolean =>\n dispatch(target, new CustomEvent(type, { bubbles: true, cancelable: true, composed: false, ...init }));\n\nexport const fireFocus = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('focus', init));\n\nexport const fireInput = (target: EventTarget, init: InputEventInit = {}): boolean =>\n dispatch(target, new InputEvent('input', { bubbles: true, ...init }));\n\nexport const fireKeyDown = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireKeyUp = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keyup', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireSubmit = (target: EventTarget, init: SubmitEventInit = {}): boolean =>\n dispatch(target, new SubmitEvent('submit', { bubbles: true, cancelable: true, ...init }));\n","import { AssayQueryError } from './errors';\n\n/** DOM query helpers for test environments. */\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Scoped query helpers for any queryable DOM root: see {@link within}. */\nexport interface QueryScope {\n get<E extends Element = Element>(selector: string): E;\n getByTestId<E extends Element = Element>(testId: string): E;\n getByText<E extends Element = Element>(text: string, selector?: string): E;\n query<E extends Element = Element>(selector: string): E | null;\n queryAll<E extends Element = Element>(selector: string): E[];\n queryAllByTestId<E extends Element = Element>(testId: string): E[];\n queryAllByText<E extends Element = Element>(text: string, selector?: string): E[];\n queryByTestId<E extends Element = Element>(testId: string): E | null;\n queryByText<E extends Element = Element>(text: string, selector?: string): E | null;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\ntype QueryRoot = ParentNode;\n\nconst describeRoot = (root: QueryRoot): string => {\n if (root instanceof Element) return root.outerHTML.slice(0, 500);\n\n if (root instanceof ShadowRoot) return `<shadow-root>${root.innerHTML.slice(0, 500)}</shadow-root>`;\n\n return root.nodeName;\n};\n\nconst requireMatch = <E extends Element>(element: E | null, description: string, root: QueryRoot): E => {\n if (element) return element;\n\n throw new AssayQueryError(`Unable to find ${description} within ${describeRoot(root)}.`);\n};\n\nconst query = <E extends Element = Element>(root: QueryRoot, selector: string): E | null =>\n root.querySelector<E>(selector);\n\nconst queryAll = <E extends Element = Element>(root: QueryRoot, selector: string): E[] => {\n return Array.from(root.querySelectorAll<E>(selector));\n};\n\nconst queryByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E | null =>\n queryAll<E>(root, '[data-testid]').find((element) => element.getAttribute('data-testid') === testId) ?? null;\n\nconst queryAllByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E[] =>\n queryAll<E>(root, '[data-testid]').filter((element) => element.getAttribute('data-testid') === testId);\n\nconst queryByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E | null => {\n for (const element of root.querySelectorAll<E>(selector)) {\n if (element.textContent?.trim() === text) return element;\n }\n\n return null;\n};\n\nconst queryAllByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E[] =>\n queryAll<E>(root, selector).filter((element) => element.textContent?.trim() === text);\n\n/**\n * Queries the shadow root of a custom element for a matching CSS selector.\n * Returns `null` if the element has no shadow root or no match is found: safe to call on\n * both open-shadow custom elements and plain elements without checking `shadowRoot` first.\n */\nexport function queryInShadow<E extends Element = Element>(host: Element, selector: string): E | null {\n return host.shadowRoot ? query<E>(host.shadowRoot, selector) : null;\n}\n\n/** Queries all matching elements inside the shadow root of a custom element. */\nexport function queryAllInShadow<E extends Element = Element>(host: Element, selector: string): E[] {\n return host.shadowRoot ? queryAll<E>(host.shadowRoot, selector) : [];\n}\n\n/**\n * Queries a shadow DOM element by its CSS `part` attribute: shorthand for\n * `queryInShadow(host, '[part=\"name\"]')`.\n *\n * @example\n * const btn = queryPart(carousel, 'prev-btn');\n * expect(btn).not.toBeNull();\n */\nexport function queryPart<E extends Element = Element>(host: Element, part: string): E | null {\n return (\n queryAllInShadow<E>(host, '[part]').find((element) => element.getAttribute('part')?.split(/\\s+/).includes(part)) ??\n null\n );\n}\n\n/**\n * Returns the light-DOM children assigned to a named slot, or every child assigned to the\n * default slot when no name is given.\n *\n * @example\n * const slides = getSlotted(carousel);\n * expect(slides).toHaveLength(3);\n */\nexport function getSlotted<E extends Element = Element>(host: Element, slotName?: string): E[] {\n return Array.from(host.children).filter((element) =>\n slotName === undefined ? !element.getAttribute('slot') : element.getAttribute('slot') === slotName,\n ) as E[];\n}\n\n// ─── API ─────────────────────────────────────────────────────────────────────\n\n/**\n * Create query helpers scoped to a DOM root: useful for light DOM and shadow roots.\n *\n * @example\n * const view = within(fixture.shadow!);\n * expect(view.get('.title').textContent).toBe('Hello');\n */\nexport function within(root: QueryRoot): QueryScope {\n return {\n get: <E extends Element = Element>(selector: string) =>\n requireMatch(query<E>(root, selector), `\"${selector}\"`, root),\n getByTestId: <E extends Element = Element>(testId: string) =>\n requireMatch(queryByTestId<E>(root, testId), `data-testid \"${testId}\"`, root),\n getByText: <E extends Element = Element>(text: string, selector = '*') =>\n requireMatch(queryByText<E>(root, text, selector), `text \"${text}\" matching \"${selector}\"`, root),\n query: <E extends Element = Element>(selector: string) => query<E>(root, selector),\n queryAll: <E extends Element = Element>(selector: string) => queryAll<E>(root, selector),\n queryAllByTestId: <E extends Element = Element>(testId: string) => queryAllByTestId<E>(root, testId),\n queryAllByText: <E extends Element = Element>(text: string, selector = '*') =>\n queryAllByText<E>(root, text, selector),\n queryByTestId: <E extends Element = Element>(testId: string) => queryByTestId<E>(root, testId),\n queryByText: <E extends Element = Element>(text: string, selector = '*') => queryByText<E>(root, text, selector),\n };\n}\n","import { abortError, sleep } from '@vielzeug/arsenal';\n\nimport { AssayTimeoutError } from './errors';\n\nexport interface DelayOptions {\n signal?: AbortSignal;\n}\n\nexport interface WaitOptions {\n /** Polling interval in ms (default: 50). */\n interval?: number;\n /** Cancel the pending wait. */\n signal?: AbortSignal;\n /** Maximum wait time in ms (default: 1000). */\n timeout?: number;\n}\n\nexport interface EventuallyOptions extends WaitOptions {\n /** Context included in the timeout error. */\n message?: string;\n}\n\nconst DEADLINE = Symbol('assay.deadline');\nconst MAX_TIMER_MS = 2_147_483_647;\nconst now = (): number => performance.now();\n\nconst validateDuration = (name: string, value: number, allowZero: boolean): void => {\n if (!Number.isFinite(value) || value > MAX_TIMER_MS || (allowZero ? value < 0 : value <= 0)) {\n throw new RangeError(\n `${name} must be a ${allowZero ? 'non-negative' : 'positive'} finite number no greater than ${MAX_TIMER_MS}`,\n );\n }\n};\n\nconst validateWait = (interval: number, timeout: number): void => {\n validateDuration('interval', interval, false);\n validateDuration('timeout', timeout, true);\n};\n\nconst runBounded = <T>(run: () => T | Promise<T>, deadline: number, signal?: AbortSignal): Promise<T> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n let settled = false;\n const cleanup = (): boolean => {\n if (settled) return false;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n return true;\n };\n const resolveOnce = (value: T): void => {\n if (cleanup()) resolve(value);\n };\n const rejectOnce = (error: unknown): void => {\n if (cleanup()) reject(error);\n };\n const timer = setTimeout(() => rejectOnce(DEADLINE), Math.max(0, deadline - now()));\n const abort = () => rejectOnce(abortError(signal, 'The operation was aborted.'));\n\n signal?.addEventListener('abort', abort, { once: true });\n\n try {\n Promise.resolve(run()).then(resolveOnce, rejectOnce);\n } catch (error) {\n rejectOnce(error);\n }\n });\n\nexport const delay = (ms = 0, options: DelayOptions = {}): Promise<void> => {\n validateDuration('ms', ms, true);\n return sleep(ms, options.signal);\n};\n\nexport async function waitUntil(\n predicate: () => boolean | Promise<boolean>,\n { interval = 50, signal, timeout = 1000 }: WaitOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n first = false;\n\n let matched: boolean;\n try {\n matched = await runBounded(predicate, deadline, signal);\n } catch (error) {\n if (error === DEADLINE) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n throw error;\n }\n if (matched) return;\n\n const remaining = deadline - now();\n if (remaining <= 0) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n await sleep(Math.min(interval, remaining), signal);\n }\n}\n\n/**\n * Retry an assertion until it stops throwing or the timeout elapses.\n *\n * Polls the assertion on a fixed interval and preserves the last failure as the\n * timeout cause. Pending asynchronous assertions remain bounded by the same\n * deadline. Use `waitUntil()` for boolean conditions, `delay()` for explicit\n * timer dependencies, and `nextTick()` for one queued microtask boundary.\n *\n * @example\n * await eventually(() => expect(region.textContent).toBe('Saved'));\n */\nexport async function eventually(\n assertion: () => void | Promise<void>,\n { interval = 50, message, signal, timeout = 1000 }: EventuallyOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n let lastError: unknown;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) break;\n first = false;\n\n try {\n await runBounded(assertion, deadline, signal);\n return;\n } catch (error) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (error === DEADLINE) break;\n lastError = error;\n }\n\n const remaining = deadline - now();\n if (remaining <= 0) break;\n await sleep(Math.min(interval, remaining), signal);\n }\n\n const timing = `eventually timed out after ${timeout}ms`;\n const context = message ? `${message} (${timing})` : timing;\n const detail = lastError instanceof Error ? lastError.message : lastError == null ? '' : String(lastError);\n\n throw new AssayTimeoutError(detail ? `${context}\\n${detail}` : context, { cause: lastError });\n}\n\n/** Resolve with the next event of `type`, or reject when it times out or is aborted. */\nexport function waitForEvent<T extends Event = Event>(\n target: EventTarget,\n type: string,\n { signal, timeout = 1000 }: Omit<WaitOptions, 'interval'> = {},\n): Promise<T> {\n validateDuration('timeout', timeout, true);\n\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n const dispose = () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n target.removeEventListener(type, onEvent);\n };\n const onEvent = (event: Event): void => {\n dispose();\n resolve(event as T);\n };\n const timer = setTimeout(() => {\n dispose();\n reject(new AssayTimeoutError(`waitForEvent: \"${type}\" timed out after ${timeout}ms`));\n }, timeout);\n const onAbort = () => {\n dispose();\n reject(abortError(signal, 'The operation was aborted.'));\n };\n\n target.addEventListener(type, onEvent, { once: true });\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n"],"mappings":"0DACA,IAAa,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,UAAW,CAAC,EAGpC,kBAAb,cAAuC,UAAW,CAAC,ECKtC,UAAY,EAAqB,IAA0B,EAAO,cAAc,CAAK,EAGrF,UAAY,EAAqB,EAAuB,CAAC,IACpE,SAAS,EAAQ,IAAI,WAAW,OAAQ,CAAI,CAAC,EAElC,YAAc,EAAqB,EAAkB,CAAC,IACjE,SAAS,EAAQ,IAAI,MAAM,SAAU,CAAE,QAAS,GAAM,GAAG,CAAK,CAAC,CAAC,EAErD,WAAa,EAAqB,EAAuB,CAAC,IACrE,SAAS,EAAQ,IAAI,WAAW,QAAS,CAAE,QAAS,GAAM,WAAY,GAAM,GAAG,CAAK,CAAC,CAAC,EAE3E,YAAiB,EAAqB,EAAc,EAA2B,CAAC,IAC3F,SAAS,EAAQ,IAAI,YAAY,EAAM,CAAE,QAAS,GAAM,WAAY,GAAM,SAAU,GAAO,GAAG,CAAK,CAAC,CAAC,EAE1F,WAAa,EAAqB,EAAuB,CAAC,IACrE,SAAS,EAAQ,IAAI,WAAW,QAAS,CAAI,CAAC,EAEnC,WAAa,EAAqB,EAAuB,CAAC,IACrE,SAAS,EAAQ,IAAI,WAAW,QAAS,CAAE,QAAS,GAAM,GAAG,CAAK,CAAC,CAAC,EAEzD,aAAe,EAAqB,EAA0B,CAAC,IAC1E,SAAS,EAAQ,IAAI,cAAc,UAAW,CAAE,QAAS,GAAM,WAAY,GAAM,GAAG,CAAK,CAAC,CAAC,EAEhF,WAAa,EAAqB,EA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S,EAAI,EAElC,IAAI,SAAS,EAAS,IAAW,CACtC,GAAI,GAAQ,QAAS,CACnB,EAAO,EAAW,EAAQ,4BAA4B,CAAC,EACvD,MACF,CAEA,IAAM,YAAgB,CACpB,aAAa,CAAK,EAClB,GAAQ,oBAAoB,QAAS,OAAO,EAC5C,EAAO,oBAAoB,EAAM,OAAO,CAC1C,EACM,QAAW,GAAuB,CACtC,QAAQ,EACR,EAAQ,CAAU,CACpB,EACM,EAAQ,eAAiB,CAC7B,QAAQ,EACR,EAAO,IAAI,kBAAkB,kBAAkB,EAAK,oBAAoB,EAAQ,GAAG,CAAC,CACtF,EAAG,CAAO,EACJ,YAAgB,CACpB,QAAQ,EACR,EAAO,EAAW,EAAQ,4BAA4B,CAAC,CACzD,EAEA,EAAO,iBAAiB,EAAM,QAAS,CAAE,KAAM,EAAK,CAAC,EACrD,GAAQ,iBAAiB,QAAS,QAAS,CAAE,KAAM,EAAK,CAAC,CAC3D,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"assay.js","names":[],"sources":["../src/dom.ts","../src/errors.ts","../src/events.ts","../src/form-internals.ts","../src/query.ts","../src/wait.ts"],"sourcesContent":["/**\n * DOM traversal helpers for tests running under jsdom, which only implements the *light* DOM\n * tree: `Element.children`/`querySelectorAll()` never cross a `<slot>` into its assigned\n * elements. Real browsers use the *flat tree* (light DOM with each `<slot>` transparently\n * replaced by what's actually assigned to it) for this: it's what \"form owner\" resolution,\n * `:has()`, and plenty of other DOM algorithms are specified against.\n */\n\n/**\n * Walks the flat tree starting at `root`, calling `visit` for every element encountered :\n * expanding each `<slot>` via `assignedElements()` instead of descending into its (always\n * empty, in jsdom) literal children.\n *\n * @example\n * ```ts\n * // Find every form-associated element slotted (possibly through nested slots) under `form`,\n * // something `form.querySelectorAll('[name]')` can't do once a shadow boundary is involved.\n * const named: HTMLElement[] = [];\n * walkFlatTree(form, (el) => { if (el.hasAttribute('name')) named.push(el); });\n * ```\n */\nexport const walkFlatTree = (root: Element, visit: (element: HTMLElement) => void): void => {\n const children = root instanceof HTMLSlotElement ? root.assignedElements({ flatten: true }) : root.children;\n\n for (const child of Array.from(children)) {\n if (!(child instanceof HTMLSlotElement)) visit(child as HTMLElement);\n\n walkFlatTree(child, visit);\n }\n};\n","/** Base class for all Assay errors. Use `instanceof AssayError` to catch any Assay-originated error. */\nexport class AssayError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a required query has no match. */\nexport class AssayQueryError extends AssayError {}\n\n/** Thrown when an Assay wait reaches its timeout. */\nexport class AssayTimeoutError extends AssayError {}\n","/**\n * # Confidence boundary: read first\n *\n * `dispatch` is a **low-level synthetic-event dispatch API**. It fires a caller-\n * supplied DOM `Event` synchronously and returns the `dispatchEvent`\n * result. It does **not** model real user interaction: there is no focus/blur\n * sequencing, no input-event coordination, no keyboard layout, no pointer\n * hit-testing, and no trust flag (`event.isTrusted` is always `false`).\n *\n * Use it to drive event handlers in unit/integration tests where you control\n * the exact event shape. For **behavioral confidence**, that a real click\n * actually activates a control, that focus management works end-to-end, that\n * keyboard shortcuts fire under a real input device: write Playwright tests.\n * Assay deliberately stops at the dispatch boundary; anything that depends on\n * the browser's interaction semantics belongs in a browser-driven suite.\n */\n\n/** Dispatch a pre-built `Event` instance unchanged. Returns the `dispatchEvent` result. */\nexport const dispatch = (target: EventTarget, event: Event): boolean => target.dispatchEvent(event);\n\n/** Synthetic convenience dispatchers. They share the same confidence boundary as `dispatch()`. */\nexport const fireBlur = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('blur', init));\n\nexport const fireChange = (target: EventTarget, init: EventInit = {}): boolean =>\n dispatch(target, new Event('change', { bubbles: true, ...init }));\n\nexport const fireClick = (target: EventTarget, init: MouseEventInit = {}): boolean =>\n dispatch(target, new MouseEvent('click', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireCustom = <T>(target: EventTarget, type: string, init: CustomEventInit<T> = {}): boolean =>\n dispatch(target, new CustomEvent(type, { bubbles: true, cancelable: true, composed: false, ...init }));\n\nexport const fireFocus = (target: EventTarget, init: FocusEventInit = {}): boolean =>\n dispatch(target, new FocusEvent('focus', init));\n\nexport const fireInput = (target: EventTarget, init: InputEventInit = {}): boolean =>\n dispatch(target, new InputEvent('input', { bubbles: true, ...init }));\n\nexport const fireKeyDown = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireKeyUp = (target: EventTarget, init: KeyboardEventInit = {}): boolean =>\n dispatch(target, new KeyboardEvent('keyup', { bubbles: true, cancelable: true, ...init }));\n\nexport const fireSubmit = (target: EventTarget, init: SubmitEventInit = {}): boolean =>\n dispatch(target, new SubmitEvent('submit', { bubbles: true, cancelable: true, ...init }));\n","import { walkFlatTree } from './dom';\n\n/**\n * jsdom implements none of the `ElementInternals` form-association API: not `setFormValue`,\n * not `setValidity`, not the `checkValidity`/`reportValidity`/`validity`/`validationMessage`\n * mixin real browsers put on every `formAssociated: true` element, not even `FormData`\n * collecting a form-associated element's set value, or `<form>.reset()` invoking\n * `formResetCallback()`. Every one of those gaps is exercised by `useField()` (`@vielzeug/ore`),\n * so any package testing a form-associated component needs all of them, not just one.\n *\n * Call this directly from a test setup when the suite tests form-associated components:\n * the patches are global monkey-patches, so suites without them shouldn't pay for them.\n * Returns an `uninstall()` that restores every patched global.\n *\n * Lives in Assay because it patches the DOM environment itself: the gap is in jsdom, not in\n * any package's feature, and Assay is the repo's home for DOM test-environment helpers.\n * `walkFlatTree` handles form-associated custom elements across shadow boundaries, so\n * consumer packages do not need package-local copies of this polyfill.\n */\nexport const installFormInternalsPolyfill = (): (() => void) => {\n // Checked *before* consuming the flag below: an environment without `ElementInternals`\n // installs nothing and should stay eligible to install for real later (e.g. a differently\n // configured environment in the same process), not get marked \"already installed\" for having\n // done nothing.\n if (typeof ElementInternals === 'undefined') return () => {};\n\n const INSTALLED_FLAG = Symbol.for('vielzeug.assay.formInternalsPolyfillInstalled');\n const flagHost = globalThis as Record<symbol, boolean | undefined>;\n\n if (flagHost[INSTALLED_FLAG]) return () => {};\n\n flagHost[INSTALLED_FLAG] = true;\n\n // Every patch pushes its inverse here, so uninstall() restores the environment exactly.\n const restorers: Array<() => void> = [];\n\n const proto = ElementInternals.prototype as unknown as Record<string, unknown>;\n const validityState = new WeakMap<ElementInternals, { flags: ValidityStateFlags; message: string }>();\n const formValueByHost = new WeakMap<HTMLElement, File | FormData | string | null>();\n const hostByInternals = new WeakMap<ElementInternals, HTMLElement>();\n\n const patchProto = (name: string, descriptor: PropertyDescriptor): void => {\n if (name in proto) return;\n\n Object.defineProperty(proto, name, descriptor);\n restorers.push(() => delete proto[name]);\n };\n\n const isValid = (internals: ElementInternals): boolean => {\n const state = validityState.get(internals);\n\n return !state || !Object.values(state.flags).some(Boolean);\n };\n\n patchProto('setFormValue', {\n configurable: true,\n value: function (this: ElementInternals, value: File | FormData | string | null) {\n const host = hostByInternals.get(this);\n\n if (host) formValueByHost.set(host, value);\n },\n writable: true,\n });\n\n patchProto('setValidity', {\n configurable: true,\n // Matches the real platform contract: throws if any flag is true and message is empty.\n // `useField()` itself already guards against triggering this: see forms/field.ts, but\n // the polyfill enforcing it too means a test would still catch a *different* caller doing\n // the same thing wrong, instead of that bug only surfacing in a real browser.\n value: function (this: ElementInternals, flags: ValidityStateFlags = {}, message = '') {\n if (Object.values(flags).some(Boolean) && !message) {\n throw new TypeError(\n \"Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if \" +\n 'one or more flags in the first argument are true.',\n );\n }\n\n validityState.set(this, { flags, message });\n },\n writable: true,\n });\n\n patchProto('checkValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('reportValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('validationMessage', {\n configurable: true,\n get(this: ElementInternals) {\n return isValid(this) ? '' : (validityState.get(this)?.message ?? '');\n },\n });\n\n // A ValidityState-shaped view of the flags passed to setValidity: every known\n // flag defaults to false, `valid` reflects whether any flag is set.\n patchProto('validity', {\n configurable: true,\n get(this: ElementInternals): ValidityState {\n const state = validityState.get(this);\n\n return {\n badInput: false,\n customError: false,\n patternMismatch: false,\n rangeOverflow: false,\n rangeUnderflow: false,\n stepMismatch: false,\n tooLong: false,\n tooShort: false,\n typeMismatch: false,\n valid: isValid(this),\n valueMissing: false,\n ...(state?.flags ?? {}),\n } as ValidityState;\n },\n });\n\n patchProto('states', {\n configurable: true,\n get: function (this: ElementInternals & { _states?: Set<string> }) {\n this._states ??= new Set();\n\n return this._states;\n },\n });\n\n // Real browsers mix `checkValidity`/`reportValidity`/`validity`/`validationMessage` onto any\n // `formAssociated: true` custom element itself (delegating to its internals): not just onto\n // `ElementInternals`. jsdom does neither; mirror it here so a component's own\n // `checkValidity()`/`reportValidity()`, and a test asserting against the element directly,\n // behave the same as they would in a real browser.\n const originalAttachInternals = HTMLElement.prototype.attachInternals;\n\n HTMLElement.prototype.attachInternals = function (this: HTMLElement, ...args: []): ElementInternals {\n const internals = originalAttachInternals.apply(this, args);\n\n hostByInternals.set(internals, this);\n\n Object.defineProperties(this, {\n checkValidity: { configurable: true, value: () => internals.checkValidity() },\n reportValidity: { configurable: true, value: () => internals.reportValidity() },\n validationMessage: { configurable: true, get: () => internals.validationMessage },\n validity: { configurable: true, get: () => internals.validity },\n });\n\n return internals;\n };\n restorers.push(() => {\n HTMLElement.prototype.attachInternals = originalAttachInternals;\n });\n\n const appendFormValue = (formData: FormData, name: string, value: File | FormData | string): void => {\n if (value instanceof FormData) {\n for (const [entryName, entryValue] of value.entries()) formData.append(entryName, entryValue);\n\n return;\n }\n\n formData.append(name, value);\n };\n\n // jsdom's `FormData` constructor never collects a form-associated custom element's set form\n // value: real browsers walk the flat tree for every form-associated element with a `name`.\n const NativeFormData = globalThis.FormData;\n\n globalThis.FormData = class FormDataWithFormAssociatedElements extends NativeFormData {\n constructor(form?: HTMLFormElement, submitter?: HTMLElement | null) {\n super(form as HTMLFormElement | undefined, submitter as HTMLElement | null | undefined);\n\n if (!(form instanceof HTMLFormElement)) return;\n\n walkFlatTree(form, (element) => {\n const name = element.getAttribute('name');\n const value = formValueByHost.get(element);\n\n if (!name || value == null || element.hasAttribute('disabled')) return;\n\n appendFormValue(this, name, value);\n });\n }\n };\n restorers.push(() => {\n globalThis.FormData = NativeFormData;\n });\n\n // jsdom never invokes the native `formResetCallback` lifecycle method on form-associated\n // custom elements when their form resets: patch `reset()` to do it (via the same flat-tree\n // walk, since a reset field can be nested behind a shadow boundary too), so `onFormReset()`\n // (see `@vielzeug/ore`'s runtime.ts) is testable against a real `<form>.reset()` call instead\n // of only by calling `element.formResetCallback()` directly.\n const originalReset = HTMLFormElement.prototype.reset;\n\n HTMLFormElement.prototype.reset = function (this: HTMLFormElement, ...args: []) {\n originalReset.apply(this, args);\n\n walkFlatTree(this, (element) => {\n (element as Partial<{ formResetCallback: () => void }>).formResetCallback?.();\n });\n };\n restorers.push(() => {\n HTMLFormElement.prototype.reset = originalReset;\n });\n\n return () => {\n for (const restore of restorers) restore();\n\n restorers.length = 0;\n flagHost[INSTALLED_FLAG] = false;\n };\n};\n","import { AssayQueryError } from './errors';\n\n/** DOM query helpers for test environments. */\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Scoped query helpers for any queryable DOM root: see {@link within}. */\nexport interface QueryScope {\n get<E extends Element = Element>(selector: string): E;\n getByTestId<E extends Element = Element>(testId: string): E;\n getByText<E extends Element = Element>(text: string, selector?: string): E;\n query<E extends Element = Element>(selector: string): E | null;\n queryAll<E extends Element = Element>(selector: string): E[];\n queryAllByTestId<E extends Element = Element>(testId: string): E[];\n queryAllByText<E extends Element = Element>(text: string, selector?: string): E[];\n queryByTestId<E extends Element = Element>(testId: string): E | null;\n queryByText<E extends Element = Element>(text: string, selector?: string): E | null;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\ntype QueryRoot = ParentNode;\n\nconst describeRoot = (root: QueryRoot): string => {\n if (root instanceof Element) return root.outerHTML.slice(0, 500);\n\n if (root instanceof ShadowRoot) return `<shadow-root>${root.innerHTML.slice(0, 500)}</shadow-root>`;\n\n return root.nodeName;\n};\n\nconst requireMatch = <E extends Element>(element: E | null, description: string, root: QueryRoot): E => {\n if (element) return element;\n\n throw new AssayQueryError(`Unable to find ${description} within ${describeRoot(root)}.`);\n};\n\nconst query = <E extends Element = Element>(root: QueryRoot, selector: string): E | null =>\n root.querySelector<E>(selector);\n\nconst queryAll = <E extends Element = Element>(root: QueryRoot, selector: string): E[] => {\n return Array.from(root.querySelectorAll<E>(selector));\n};\n\nconst queryByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E | null =>\n queryAll<E>(root, '[data-testid]').find((element) => element.getAttribute('data-testid') === testId) ?? null;\n\nconst queryAllByTestId = <E extends Element = Element>(root: QueryRoot, testId: string): E[] =>\n queryAll<E>(root, '[data-testid]').filter((element) => element.getAttribute('data-testid') === testId);\n\nconst queryByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E | null => {\n for (const element of root.querySelectorAll<E>(selector)) {\n if (element.textContent?.trim() === text) return element;\n }\n\n return null;\n};\n\nconst queryAllByText = <E extends Element = Element>(root: QueryRoot, text: string, selector = '*'): E[] =>\n queryAll<E>(root, selector).filter((element) => element.textContent?.trim() === text);\n\n/**\n * Queries the shadow root of a custom element for a matching CSS selector.\n * Returns `null` if the element has no shadow root or no match is found: safe to call on\n * both open-shadow custom elements and plain elements without checking `shadowRoot` first.\n */\nexport function queryInShadow<E extends Element = Element>(host: Element, selector: string): E | null {\n return host.shadowRoot ? query<E>(host.shadowRoot, selector) : null;\n}\n\n/** Queries all matching elements inside the shadow root of a custom element. */\nexport function queryAllInShadow<E extends Element = Element>(host: Element, selector: string): E[] {\n return host.shadowRoot ? queryAll<E>(host.shadowRoot, selector) : [];\n}\n\n/**\n * Queries a shadow DOM element by its CSS `part` attribute: shorthand for\n * `queryInShadow(host, '[part=\"name\"]')`.\n *\n * @example\n * const btn = queryPart(carousel, 'prev-btn');\n * expect(btn).not.toBeNull();\n */\nexport function queryPart<E extends Element = Element>(host: Element, part: string): E | null {\n return (\n queryAllInShadow<E>(host, '[part]').find((element) => element.getAttribute('part')?.split(/\\s+/).includes(part)) ??\n null\n );\n}\n\n/**\n * Returns the light-DOM children assigned to a named slot, or every child assigned to the\n * default slot when no name is given.\n *\n * @example\n * const slides = getSlotted(carousel);\n * expect(slides).toHaveLength(3);\n */\nexport function getSlotted<E extends Element = Element>(host: Element, slotName?: string): E[] {\n return Array.from(host.children).filter((element) =>\n slotName === undefined ? !element.getAttribute('slot') : element.getAttribute('slot') === slotName,\n ) as E[];\n}\n\n// ─── API ─────────────────────────────────────────────────────────────────────\n\n/**\n * Create query helpers scoped to a DOM root: useful for light DOM and shadow roots.\n *\n * @example\n * const view = within(fixture.shadow!);\n * expect(view.get('.title').textContent).toBe('Hello');\n */\nexport function within(root: QueryRoot): QueryScope {\n return {\n get: <E extends Element = Element>(selector: string) =>\n requireMatch(query<E>(root, selector), `\"${selector}\"`, root),\n getByTestId: <E extends Element = Element>(testId: string) =>\n requireMatch(queryByTestId<E>(root, testId), `data-testid \"${testId}\"`, root),\n getByText: <E extends Element = Element>(text: string, selector = '*') =>\n requireMatch(queryByText<E>(root, text, selector), `text \"${text}\" matching \"${selector}\"`, root),\n query: <E extends Element = Element>(selector: string) => query<E>(root, selector),\n queryAll: <E extends Element = Element>(selector: string) => queryAll<E>(root, selector),\n queryAllByTestId: <E extends Element = Element>(testId: string) => queryAllByTestId<E>(root, testId),\n queryAllByText: <E extends Element = Element>(text: string, selector = '*') =>\n queryAllByText<E>(root, text, selector),\n queryByTestId: <E extends Element = Element>(testId: string) => queryByTestId<E>(root, testId),\n queryByText: <E extends Element = Element>(text: string, selector = '*') => queryByText<E>(root, text, selector),\n };\n}\n","import { abortError, sleep } from '@vielzeug/arsenal';\n\nimport { AssayTimeoutError } from './errors';\n\nexport interface DelayOptions {\n signal?: AbortSignal;\n}\n\nexport interface WaitOptions {\n /** Polling interval in ms (default: 50). */\n interval?: number;\n /** Cancel the pending wait. */\n signal?: AbortSignal;\n /** Maximum wait time in ms (default: 1000). */\n timeout?: number;\n}\n\nexport interface EventuallyOptions extends WaitOptions {\n /** Context included in the timeout error. */\n message?: string;\n}\n\nconst DEADLINE = Symbol('assay.deadline');\nconst MAX_TIMER_MS = 2_147_483_647;\nconst now = (): number => performance.now();\n\nconst validateDuration = (name: string, value: number, allowZero: boolean): void => {\n if (!Number.isFinite(value) || value > MAX_TIMER_MS || (allowZero ? value < 0 : value <= 0)) {\n throw new RangeError(\n `${name} must be a ${allowZero ? 'non-negative' : 'positive'} finite number no greater than ${MAX_TIMER_MS}`,\n );\n }\n};\n\nconst validateWait = (interval: number, timeout: number): void => {\n validateDuration('interval', interval, false);\n validateDuration('timeout', timeout, true);\n};\n\nconst runBounded = <T>(run: () => T | Promise<T>, deadline: number, signal?: AbortSignal): Promise<T> =>\n new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n let settled = false;\n const cleanup = (): boolean => {\n if (settled) return false;\n settled = true;\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n return true;\n };\n const resolveOnce = (value: T): void => {\n if (cleanup()) resolve(value);\n };\n const rejectOnce = (error: unknown): void => {\n if (cleanup()) reject(error);\n };\n const timer = setTimeout(() => rejectOnce(DEADLINE), Math.max(0, deadline - now()));\n const abort = () => rejectOnce(abortError(signal, 'The operation was aborted.'));\n\n signal?.addEventListener('abort', abort, { once: true });\n\n try {\n Promise.resolve(run()).then(resolveOnce, rejectOnce);\n } catch (error) {\n rejectOnce(error);\n }\n });\n\nexport const delay = (ms = 0, options: DelayOptions = {}): Promise<void> => {\n validateDuration('ms', ms, true);\n return sleep(ms, options.signal);\n};\n\nexport async function waitUntil(\n predicate: () => boolean | Promise<boolean>,\n { interval = 50, signal, timeout = 1000 }: WaitOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n first = false;\n\n let matched: boolean;\n try {\n matched = await runBounded(predicate, deadline, signal);\n } catch (error) {\n if (error === DEADLINE) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n throw error;\n }\n if (matched) return;\n\n const remaining = deadline - now();\n if (remaining <= 0) throw new AssayTimeoutError(`waitUntil timed out after ${timeout}ms`);\n await sleep(Math.min(interval, remaining), signal);\n }\n}\n\n/**\n * Retry an assertion until it stops throwing or the timeout elapses.\n *\n * Polls the assertion on a fixed interval and preserves the last failure as the\n * timeout cause. Pending asynchronous assertions remain bounded by the same\n * deadline. Use `waitUntil()` for boolean conditions, `delay()` for explicit\n * timer dependencies, and `nextTick()` for one queued microtask boundary.\n *\n * @example\n * await eventually(() => expect(region.textContent).toBe('Saved'));\n */\nexport async function eventually(\n assertion: () => void | Promise<void>,\n { interval = 50, message, signal, timeout = 1000 }: EventuallyOptions = {},\n): Promise<void> {\n validateWait(interval, timeout);\n const deadline = now() + timeout;\n let first = true;\n let lastError: unknown;\n\n for (;;) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (!first && now() >= deadline) break;\n first = false;\n\n try {\n await runBounded(assertion, deadline, signal);\n return;\n } catch (error) {\n if (signal?.aborted) throw abortError(signal, 'The operation was aborted.');\n if (error === DEADLINE) break;\n lastError = error;\n }\n\n const remaining = deadline - now();\n if (remaining <= 0) break;\n await sleep(Math.min(interval, remaining), signal);\n }\n\n const timing = `eventually timed out after ${timeout}ms`;\n const context = message ? `${message} (${timing})` : timing;\n const detail = lastError instanceof Error ? lastError.message : lastError == null ? '' : String(lastError);\n\n throw new AssayTimeoutError(detail ? `${context}\\n${detail}` : context, { cause: lastError });\n}\n\n/** Resolve with the next event of `type`, or reject when it times out or is aborted. */\nexport function waitForEvent<T extends Event = Event>(\n target: EventTarget,\n type: string,\n { signal, timeout = 1000 }: Omit<WaitOptions, 'interval'> = {},\n): Promise<T> {\n validateDuration('timeout', timeout, true);\n\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'The operation was aborted.'));\n return;\n }\n\n const dispose = () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n target.removeEventListener(type, onEvent);\n };\n const onEvent = (event: Event): void => {\n dispose();\n resolve(event as T);\n };\n const timer = setTimeout(() => {\n dispose();\n reject(new AssayTimeoutError(`waitForEvent: \"${type}\" timed out after ${timeout}ms`));\n }, timeout);\n const onAbort = () => {\n dispose();\n reject(abortError(signal, 'The operation was aborted.'));\n };\n\n target.addEventListener(type, onEvent, { once: true });\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n"],"mappings":"0DAqBA,IAAa,cAAgB,EAAe,IAAgD,CAC1F,IAAM,EAAW,aAAgB,gBAAkB,EAAK,iBAAiB,CAAE,QAAS,EAAK,CAAC,EAAI,EAAK,SAEnG,IAAK,IAAM,KAAS,MAAM,KAAK,CAAQ,EAC/B,aAAiB,iBAAkB,EAAM,CAAoB,EAEnE,aAAa,EAAO,CAAK,CAE7B,EC5Ba,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,gBAAb,cAAqC,UAAW,CAAC,EAGpC,kBAAb,cAAuC,UAAW,CAAC,ECKtC,UAAY,EAAqB,IAA0B,EAAO,cAAc,CAAK,EAGrF,UAAY,EAAqB,EAAuB,CAAC,IACpE,SAAS,EAAQ,IAAI,WAAW,OAAQ,CAAI,CAAC,EAElC,YAAc,EAAq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B,aACd,EACA,EACA,CAAE,SAAQ,UAAU,KAAwC,CAAC,EACjD,CAGZ,OAFA,iBAAiB,UAAW,EAAS,EAAI,EAElC,IAAI,SAAS,EAAS,IAAW,CACtC,GAAI,GAAQ,QAAS,CACnB,EAAO,EAAW,EAAQ,4BAA4B,CAAC,EACvD,MACF,CAEA,IAAM,YAAgB,CACpB,aAAa,CAAK,EAClB,GAAQ,oBAAoB,QAAS,OAAO,EAC5C,EAAO,oBAAoB,EAAM,OAAO,CAC1C,EACM,QAAW,GAAuB,CACtC,QAAQ,EACR,EAAQ,CAAU,CACpB,EACM,EAAQ,eAAiB,CAC7B,QAAQ,EACR,EAAO,IAAI,kBAAkB,kBAAkB,EAAK,oBAAoB,EAAQ,GAAG,CAAC,CACtF,EAAG,CAAO,EACJ,YAAgB,CACpB,QAAQ,EACR,EAAO,EAAW,EAAQ,4BAA4B,CAAC,CACzD,EAEA,EAAO,iBAAiB,EAAM,QAAS,CAAE,KAAM,EAAK,CAAC,EACrD,GAAQ,iBAAiB,QAAS,QAAS,CAAE,KAAM,EAAK,CAAC,CAC3D,CAAC,CACH"}
|
package/dist/dom.cjs
ADDED
package/dist/dom.cjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dom.cjs","names":[],"sources":["../src/dom.ts"],"sourcesContent":["/**\n * DOM traversal helpers for tests running under jsdom, which only implements the *light* DOM\n * tree: `Element.children`/`querySelectorAll()` never cross a `<slot>` into its assigned\n * elements. Real browsers use the *flat tree* (light DOM with each `<slot>` transparently\n * replaced by what's actually assigned to it) for this: it's what \"form owner\" resolution,\n * `:has()`, and plenty of other DOM algorithms are specified against.\n */\n\n/**\n * Walks the flat tree starting at `root`, calling `visit` for every element encountered :\n * expanding each `<slot>` via `assignedElements()` instead of descending into its (always\n * empty, in jsdom) literal children.\n *\n * @example\n * ```ts\n * // Find every form-associated element slotted (possibly through nested slots) under `form`,\n * // something `form.querySelectorAll('[name]')` can't do once a shadow boundary is involved.\n * const named: HTMLElement[] = [];\n * walkFlatTree(form, (el) => { if (el.hasAttribute('name')) named.push(el); });\n * ```\n */\nexport const walkFlatTree = (root: Element, visit: (element: HTMLElement) => void): void => {\n const children = root instanceof HTMLSlotElement ? root.assignedElements({ flatten: true }) : root.children;\n\n for (const child of Array.from(children)) {\n if (!(child instanceof HTMLSlotElement)) visit(child as HTMLElement);\n\n walkFlatTree(child, visit);\n }\n};\n"],"mappings":"AAqBA,IAAa,cAAgB,EAAe,IAAgD,CAC1F,IAAM,EAAW,aAAgB,gBAAkB,EAAK,iBAAiB,CAAE,QAAS,EAAK,CAAC,EAAI,EAAK,SAEnG,IAAK,IAAM,KAAS,MAAM,KAAK,CAAQ,EAC/B,aAAiB,iBAAkB,EAAM,CAAoB,EAEnE,aAAa,EAAO,CAAK,CAE7B"}
|
package/dist/dom.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DOM traversal helpers for tests running under jsdom, which only implements the *light* DOM
|
|
3
|
+
* tree: `Element.children`/`querySelectorAll()` never cross a `<slot>` into its assigned
|
|
4
|
+
* elements. Real browsers use the *flat tree* (light DOM with each `<slot>` transparently
|
|
5
|
+
* replaced by what's actually assigned to it) for this: it's what "form owner" resolution,
|
|
6
|
+
* `:has()`, and plenty of other DOM algorithms are specified against.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Walks the flat tree starting at `root`, calling `visit` for every element encountered :
|
|
10
|
+
* expanding each `<slot>` via `assignedElements()` instead of descending into its (always
|
|
11
|
+
* empty, in jsdom) literal children.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* // Find every form-associated element slotted (possibly through nested slots) under `form`,
|
|
16
|
+
* // something `form.querySelectorAll('[name]')` can't do once a shadow boundary is involved.
|
|
17
|
+
* const named: HTMLElement[] = [];
|
|
18
|
+
* walkFlatTree(form, (el) => { if (el.hasAttribute('name')) named.push(el); });
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export declare const walkFlatTree: (root: Element, visit: (element: HTMLElement) => void) => void;
|
|
22
|
+
//# sourceMappingURL=dom.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dom.d.ts","sourceRoot":"","sources":["../src/dom.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,YAAY,GAAI,MAAM,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,KAAG,IAQnF,CAAC"}
|
package/dist/dom.js
ADDED
package/dist/dom.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dom.js","names":[],"sources":["../src/dom.ts"],"sourcesContent":["/**\n * DOM traversal helpers for tests running under jsdom, which only implements the *light* DOM\n * tree: `Element.children`/`querySelectorAll()` never cross a `<slot>` into its assigned\n * elements. Real browsers use the *flat tree* (light DOM with each `<slot>` transparently\n * replaced by what's actually assigned to it) for this: it's what \"form owner\" resolution,\n * `:has()`, and plenty of other DOM algorithms are specified against.\n */\n\n/**\n * Walks the flat tree starting at `root`, calling `visit` for every element encountered :\n * expanding each `<slot>` via `assignedElements()` instead of descending into its (always\n * empty, in jsdom) literal children.\n *\n * @example\n * ```ts\n * // Find every form-associated element slotted (possibly through nested slots) under `form`,\n * // something `form.querySelectorAll('[name]')` can't do once a shadow boundary is involved.\n * const named: HTMLElement[] = [];\n * walkFlatTree(form, (el) => { if (el.hasAttribute('name')) named.push(el); });\n * ```\n */\nexport const walkFlatTree = (root: Element, visit: (element: HTMLElement) => void): void => {\n const children = root instanceof HTMLSlotElement ? root.assignedElements({ flatten: true }) : root.children;\n\n for (const child of Array.from(children)) {\n if (!(child instanceof HTMLSlotElement)) visit(child as HTMLElement);\n\n walkFlatTree(child, visit);\n }\n};\n"],"mappings":"AAqBA,IAAa,cAAgB,EAAe,IAAgD,CAC1F,IAAM,EAAW,aAAgB,gBAAkB,EAAK,iBAAiB,CAAE,QAAS,EAAK,CAAC,EAAI,EAAK,SAEnG,IAAK,IAAM,KAAS,MAAM,KAAK,CAAQ,EAC/B,aAAiB,iBAAkB,EAAM,CAAoB,EAEnE,aAAa,EAAO,CAAK,CAE7B"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./dom.cjs");var installFormInternalsPolyfill=()=>{if(typeof ElementInternals>`u`)return()=>{};let t=Symbol.for(`vielzeug.assay.formInternalsPolyfillInstalled`),n=globalThis;if(n[t])return()=>{};n[t]=!0;let r=[],i=ElementInternals.prototype,a=new WeakMap,o=new WeakMap,s=new WeakMap,patchProto=(e,t)=>{e in i||(Object.defineProperty(i,e,t),r.push(()=>delete i[e]))},isValid=e=>{let t=a.get(e);return!t||!Object.values(t.flags).some(Boolean)};patchProto(`setFormValue`,{configurable:!0,value:function(e){let t=s.get(this);t&&o.set(t,e)},writable:!0}),patchProto(`setValidity`,{configurable:!0,value:function(e={},t=``){if(Object.values(e).some(Boolean)&&!t)throw TypeError(`Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if one or more flags in the first argument are true.`);a.set(this,{flags:e,message:t})},writable:!0}),patchProto(`checkValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`reportValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`validationMessage`,{configurable:!0,get(){return isValid(this)?``:a.get(this)?.message??``}}),patchProto(`validity`,{configurable:!0,get(){let e=a.get(this);return{badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:isValid(this),valueMissing:!1,...e?.flags??{}}}}),patchProto(`states`,{configurable:!0,get:function(){return this._states??=new Set,this._states}});let c=HTMLElement.prototype.attachInternals;HTMLElement.prototype.attachInternals=function(...e){let t=c.apply(this,e);return s.set(t,this),Object.defineProperties(this,{checkValidity:{configurable:!0,value:()=>t.checkValidity()},reportValidity:{configurable:!0,value:()=>t.reportValidity()},validationMessage:{configurable:!0,get:()=>t.validationMessage},validity:{configurable:!0,get:()=>t.validity}}),t},r.push(()=>{HTMLElement.prototype.attachInternals=c});let appendFormValue=(e,t,n)=>{if(n instanceof FormData){for(let[t,r]of n.entries())e.append(t,r);return}e.append(t,n)},l=globalThis.FormData;globalThis.FormData=class FormDataWithFormAssociatedElements extends l{constructor(t,n){super(t,n),t instanceof HTMLFormElement&&e.walkFlatTree(t,e=>{let t=e.getAttribute(`name`),n=o.get(e);t&&n!=null&&!e.hasAttribute(`disabled`)&&appendFormValue(this,t,n)})}},r.push(()=>{globalThis.FormData=l});let u=HTMLFormElement.prototype.reset;return HTMLFormElement.prototype.reset=function(...t){u.apply(this,t),e.walkFlatTree(this,e=>{e.formResetCallback?.()})},r.push(()=>{HTMLFormElement.prototype.reset=u}),()=>{for(let e of r)e();r.length=0,n[t]=!1}};exports.installFormInternalsPolyfill=installFormInternalsPolyfill;
|
|
2
|
+
//# sourceMappingURL=form-internals.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"form-internals.cjs","names":[],"sources":["../src/form-internals.ts"],"sourcesContent":["import { walkFlatTree } from './dom';\n\n/**\n * jsdom implements none of the `ElementInternals` form-association API: not `setFormValue`,\n * not `setValidity`, not the `checkValidity`/`reportValidity`/`validity`/`validationMessage`\n * mixin real browsers put on every `formAssociated: true` element, not even `FormData`\n * collecting a form-associated element's set value, or `<form>.reset()` invoking\n * `formResetCallback()`. Every one of those gaps is exercised by `useField()` (`@vielzeug/ore`),\n * so any package testing a form-associated component needs all of them, not just one.\n *\n * Call this directly from a test setup when the suite tests form-associated components:\n * the patches are global monkey-patches, so suites without them shouldn't pay for them.\n * Returns an `uninstall()` that restores every patched global.\n *\n * Lives in Assay because it patches the DOM environment itself: the gap is in jsdom, not in\n * any package's feature, and Assay is the repo's home for DOM test-environment helpers.\n * `walkFlatTree` handles form-associated custom elements across shadow boundaries, so\n * consumer packages do not need package-local copies of this polyfill.\n */\nexport const installFormInternalsPolyfill = (): (() => void) => {\n // Checked *before* consuming the flag below: an environment without `ElementInternals`\n // installs nothing and should stay eligible to install for real later (e.g. a differently\n // configured environment in the same process), not get marked \"already installed\" for having\n // done nothing.\n if (typeof ElementInternals === 'undefined') return () => {};\n\n const INSTALLED_FLAG = Symbol.for('vielzeug.assay.formInternalsPolyfillInstalled');\n const flagHost = globalThis as Record<symbol, boolean | undefined>;\n\n if (flagHost[INSTALLED_FLAG]) return () => {};\n\n flagHost[INSTALLED_FLAG] = true;\n\n // Every patch pushes its inverse here, so uninstall() restores the environment exactly.\n const restorers: Array<() => void> = [];\n\n const proto = ElementInternals.prototype as unknown as Record<string, unknown>;\n const validityState = new WeakMap<ElementInternals, { flags: ValidityStateFlags; message: string }>();\n const formValueByHost = new WeakMap<HTMLElement, File | FormData | string | null>();\n const hostByInternals = new WeakMap<ElementInternals, HTMLElement>();\n\n const patchProto = (name: string, descriptor: PropertyDescriptor): void => {\n if (name in proto) return;\n\n Object.defineProperty(proto, name, descriptor);\n restorers.push(() => delete proto[name]);\n };\n\n const isValid = (internals: ElementInternals): boolean => {\n const state = validityState.get(internals);\n\n return !state || !Object.values(state.flags).some(Boolean);\n };\n\n patchProto('setFormValue', {\n configurable: true,\n value: function (this: ElementInternals, value: File | FormData | string | null) {\n const host = hostByInternals.get(this);\n\n if (host) formValueByHost.set(host, value);\n },\n writable: true,\n });\n\n patchProto('setValidity', {\n configurable: true,\n // Matches the real platform contract: throws if any flag is true and message is empty.\n // `useField()` itself already guards against triggering this: see forms/field.ts, but\n // the polyfill enforcing it too means a test would still catch a *different* caller doing\n // the same thing wrong, instead of that bug only surfacing in a real browser.\n value: function (this: ElementInternals, flags: ValidityStateFlags = {}, message = '') {\n if (Object.values(flags).some(Boolean) && !message) {\n throw new TypeError(\n \"Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if \" +\n 'one or more flags in the first argument are true.',\n );\n }\n\n validityState.set(this, { flags, message });\n },\n writable: true,\n });\n\n patchProto('checkValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('reportValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('validationMessage', {\n configurable: true,\n get(this: ElementInternals) {\n return isValid(this) ? '' : (validityState.get(this)?.message ?? '');\n },\n });\n\n // A ValidityState-shaped view of the flags passed to setValidity: every known\n // flag defaults to false, `valid` reflects whether any flag is set.\n patchProto('validity', {\n configurable: true,\n get(this: ElementInternals): ValidityState {\n const state = validityState.get(this);\n\n return {\n badInput: false,\n customError: false,\n patternMismatch: false,\n rangeOverflow: false,\n rangeUnderflow: false,\n stepMismatch: false,\n tooLong: false,\n tooShort: false,\n typeMismatch: false,\n valid: isValid(this),\n valueMissing: false,\n ...(state?.flags ?? {}),\n } as ValidityState;\n },\n });\n\n patchProto('states', {\n configurable: true,\n get: function (this: ElementInternals & { _states?: Set<string> }) {\n this._states ??= new Set();\n\n return this._states;\n },\n });\n\n // Real browsers mix `checkValidity`/`reportValidity`/`validity`/`validationMessage` onto any\n // `formAssociated: true` custom element itself (delegating to its internals): not just onto\n // `ElementInternals`. jsdom does neither; mirror it here so a component's own\n // `checkValidity()`/`reportValidity()`, and a test asserting against the element directly,\n // behave the same as they would in a real browser.\n const originalAttachInternals = HTMLElement.prototype.attachInternals;\n\n HTMLElement.prototype.attachInternals = function (this: HTMLElement, ...args: []): ElementInternals {\n const internals = originalAttachInternals.apply(this, args);\n\n hostByInternals.set(internals, this);\n\n Object.defineProperties(this, {\n checkValidity: { configurable: true, value: () => internals.checkValidity() },\n reportValidity: { configurable: true, value: () => internals.reportValidity() },\n validationMessage: { configurable: true, get: () => internals.validationMessage },\n validity: { configurable: true, get: () => internals.validity },\n });\n\n return internals;\n };\n restorers.push(() => {\n HTMLElement.prototype.attachInternals = originalAttachInternals;\n });\n\n const appendFormValue = (formData: FormData, name: string, value: File | FormData | string): void => {\n if (value instanceof FormData) {\n for (const [entryName, entryValue] of value.entries()) formData.append(entryName, entryValue);\n\n return;\n }\n\n formData.append(name, value);\n };\n\n // jsdom's `FormData` constructor never collects a form-associated custom element's set form\n // value: real browsers walk the flat tree for every form-associated element with a `name`.\n const NativeFormData = globalThis.FormData;\n\n globalThis.FormData = class FormDataWithFormAssociatedElements extends NativeFormData {\n constructor(form?: HTMLFormElement, submitter?: HTMLElement | null) {\n super(form as HTMLFormElement | undefined, submitter as HTMLElement | null | undefined);\n\n if (!(form instanceof HTMLFormElement)) return;\n\n walkFlatTree(form, (element) => {\n const name = element.getAttribute('name');\n const value = formValueByHost.get(element);\n\n if (!name || value == null || element.hasAttribute('disabled')) return;\n\n appendFormValue(this, name, value);\n });\n }\n };\n restorers.push(() => {\n globalThis.FormData = NativeFormData;\n });\n\n // jsdom never invokes the native `formResetCallback` lifecycle method on form-associated\n // custom elements when their form resets: patch `reset()` to do it (via the same flat-tree\n // walk, since a reset field can be nested behind a shadow boundary too), so `onFormReset()`\n // (see `@vielzeug/ore`'s runtime.ts) is testable against a real `<form>.reset()` call instead\n // of only by calling `element.formResetCallback()` directly.\n const originalReset = HTMLFormElement.prototype.reset;\n\n HTMLFormElement.prototype.reset = function (this: HTMLFormElement, ...args: []) {\n originalReset.apply(this, args);\n\n walkFlatTree(this, (element) => {\n (element as Partial<{ formResetCallback: () => void }>).formResetCallback?.();\n });\n };\n restorers.push(() => {\n HTMLFormElement.prototype.reset = originalReset;\n });\n\n return () => {\n for (const restore of restorers) restore();\n\n restorers.length = 0;\n flagHost[INSTALLED_FLAG] = false;\n };\n};\n"],"mappings":"6BAmBA,IAAa,iCAAmD,CAK9D,GAAI,OAAO,iBAAqB,IAAa,UAAa,CAAC,EAE3D,IAAM,EAAiB,OAAO,IAAI,+CAA+C,EAC3E,EAAW,WAEjB,GAAI,EAAS,GAAiB,UAAa,CAAC,EAE5C,EAAS,GAAkB,GAG3B,IAAM,EAA+B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,KAAM,EAAM,CAAK,CACnC,CAAC,CACH,CACF,EACA,EAAU,SAAW,CACnB,WAAW,SAAW,CACxB,CAAC,EAOD,IAAM,EAAgB,gBAAgB,UAAU,MAahD,MAXA,iBAAgB,UAAU,MAAQ,SAAiC,GAAG,EAAU,CAC9E,EAAc,MAAM,KAAM,CAAI,EAE9B,EAAA,aAAa,KAAO,GAAY,CAC9B,EAAwD,oBAAoB,CAC9E,CAAC,CACH,EACA,EAAU,SAAW,CACnB,gBAAgB,UAAU,MAAQ,CACpC,CAAC,MAEY,CACX,IAAK,IAAM,KAAW,EAAW,EAAQ,EAEzC,EAAU,OAAS,EACnB,EAAS,GAAkB,EAC7B,CACF"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* jsdom implements none of the `ElementInternals` form-association API: not `setFormValue`,
|
|
3
|
+
* not `setValidity`, not the `checkValidity`/`reportValidity`/`validity`/`validationMessage`
|
|
4
|
+
* mixin real browsers put on every `formAssociated: true` element, not even `FormData`
|
|
5
|
+
* collecting a form-associated element's set value, or `<form>.reset()` invoking
|
|
6
|
+
* `formResetCallback()`. Every one of those gaps is exercised by `useField()` (`@vielzeug/ore`),
|
|
7
|
+
* so any package testing a form-associated component needs all of them, not just one.
|
|
8
|
+
*
|
|
9
|
+
* Call this directly from a test setup when the suite tests form-associated components:
|
|
10
|
+
* the patches are global monkey-patches, so suites without them shouldn't pay for them.
|
|
11
|
+
* Returns an `uninstall()` that restores every patched global.
|
|
12
|
+
*
|
|
13
|
+
* Lives in Assay because it patches the DOM environment itself: the gap is in jsdom, not in
|
|
14
|
+
* any package's feature, and Assay is the repo's home for DOM test-environment helpers.
|
|
15
|
+
* `walkFlatTree` handles form-associated custom elements across shadow boundaries, so
|
|
16
|
+
* consumer packages do not need package-local copies of this polyfill.
|
|
17
|
+
*/
|
|
18
|
+
export declare const installFormInternalsPolyfill: () => (() => void);
|
|
19
|
+
//# sourceMappingURL=form-internals.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"form-internals.d.ts","sourceRoot":"","sources":["../src/form-internals.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,4BAA4B,QAAO,CAAC,MAAM,IAAI,CA2M1D,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{walkFlatTree as e}from"./dom.js";var installFormInternalsPolyfill=()=>{if(typeof ElementInternals>`u`)return()=>{};let t=Symbol.for(`vielzeug.assay.formInternalsPolyfillInstalled`),n=globalThis;if(n[t])return()=>{};n[t]=!0;let r=[],i=ElementInternals.prototype,a=new WeakMap,o=new WeakMap,s=new WeakMap,patchProto=(e,t)=>{e in i||(Object.defineProperty(i,e,t),r.push(()=>delete i[e]))},isValid=e=>{let t=a.get(e);return!t||!Object.values(t.flags).some(Boolean)};patchProto(`setFormValue`,{configurable:!0,value:function(e){let t=s.get(this);t&&o.set(t,e)},writable:!0}),patchProto(`setValidity`,{configurable:!0,value:function(e={},t=``){if(Object.values(e).some(Boolean)&&!t)throw TypeError(`Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if one or more flags in the first argument are true.`);a.set(this,{flags:e,message:t})},writable:!0}),patchProto(`checkValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`reportValidity`,{configurable:!0,value:function(){return isValid(this)},writable:!0}),patchProto(`validationMessage`,{configurable:!0,get(){return isValid(this)?``:a.get(this)?.message??``}}),patchProto(`validity`,{configurable:!0,get(){let e=a.get(this);return{badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:isValid(this),valueMissing:!1,...e?.flags??{}}}}),patchProto(`states`,{configurable:!0,get:function(){return this._states??=new Set,this._states}});let c=HTMLElement.prototype.attachInternals;HTMLElement.prototype.attachInternals=function(...e){let t=c.apply(this,e);return s.set(t,this),Object.defineProperties(this,{checkValidity:{configurable:!0,value:()=>t.checkValidity()},reportValidity:{configurable:!0,value:()=>t.reportValidity()},validationMessage:{configurable:!0,get:()=>t.validationMessage},validity:{configurable:!0,get:()=>t.validity}}),t},r.push(()=>{HTMLElement.prototype.attachInternals=c});let appendFormValue=(e,t,n)=>{if(n instanceof FormData){for(let[t,r]of n.entries())e.append(t,r);return}e.append(t,n)},l=globalThis.FormData;globalThis.FormData=class FormDataWithFormAssociatedElements extends l{constructor(t,n){super(t,n),t instanceof HTMLFormElement&&e(t,e=>{let t=e.getAttribute(`name`),n=o.get(e);t&&n!=null&&!e.hasAttribute(`disabled`)&&appendFormValue(this,t,n)})}},r.push(()=>{globalThis.FormData=l});let u=HTMLFormElement.prototype.reset;return HTMLFormElement.prototype.reset=function(...t){u.apply(this,t),e(this,e=>{e.formResetCallback?.()})},r.push(()=>{HTMLFormElement.prototype.reset=u}),()=>{for(let e of r)e();r.length=0,n[t]=!1}};export{installFormInternalsPolyfill};
|
|
2
|
+
//# sourceMappingURL=form-internals.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"form-internals.js","names":[],"sources":["../src/form-internals.ts"],"sourcesContent":["import { walkFlatTree } from './dom';\n\n/**\n * jsdom implements none of the `ElementInternals` form-association API: not `setFormValue`,\n * not `setValidity`, not the `checkValidity`/`reportValidity`/`validity`/`validationMessage`\n * mixin real browsers put on every `formAssociated: true` element, not even `FormData`\n * collecting a form-associated element's set value, or `<form>.reset()` invoking\n * `formResetCallback()`. Every one of those gaps is exercised by `useField()` (`@vielzeug/ore`),\n * so any package testing a form-associated component needs all of them, not just one.\n *\n * Call this directly from a test setup when the suite tests form-associated components:\n * the patches are global monkey-patches, so suites without them shouldn't pay for them.\n * Returns an `uninstall()` that restores every patched global.\n *\n * Lives in Assay because it patches the DOM environment itself: the gap is in jsdom, not in\n * any package's feature, and Assay is the repo's home for DOM test-environment helpers.\n * `walkFlatTree` handles form-associated custom elements across shadow boundaries, so\n * consumer packages do not need package-local copies of this polyfill.\n */\nexport const installFormInternalsPolyfill = (): (() => void) => {\n // Checked *before* consuming the flag below: an environment without `ElementInternals`\n // installs nothing and should stay eligible to install for real later (e.g. a differently\n // configured environment in the same process), not get marked \"already installed\" for having\n // done nothing.\n if (typeof ElementInternals === 'undefined') return () => {};\n\n const INSTALLED_FLAG = Symbol.for('vielzeug.assay.formInternalsPolyfillInstalled');\n const flagHost = globalThis as Record<symbol, boolean | undefined>;\n\n if (flagHost[INSTALLED_FLAG]) return () => {};\n\n flagHost[INSTALLED_FLAG] = true;\n\n // Every patch pushes its inverse here, so uninstall() restores the environment exactly.\n const restorers: Array<() => void> = [];\n\n const proto = ElementInternals.prototype as unknown as Record<string, unknown>;\n const validityState = new WeakMap<ElementInternals, { flags: ValidityStateFlags; message: string }>();\n const formValueByHost = new WeakMap<HTMLElement, File | FormData | string | null>();\n const hostByInternals = new WeakMap<ElementInternals, HTMLElement>();\n\n const patchProto = (name: string, descriptor: PropertyDescriptor): void => {\n if (name in proto) return;\n\n Object.defineProperty(proto, name, descriptor);\n restorers.push(() => delete proto[name]);\n };\n\n const isValid = (internals: ElementInternals): boolean => {\n const state = validityState.get(internals);\n\n return !state || !Object.values(state.flags).some(Boolean);\n };\n\n patchProto('setFormValue', {\n configurable: true,\n value: function (this: ElementInternals, value: File | FormData | string | null) {\n const host = hostByInternals.get(this);\n\n if (host) formValueByHost.set(host, value);\n },\n writable: true,\n });\n\n patchProto('setValidity', {\n configurable: true,\n // Matches the real platform contract: throws if any flag is true and message is empty.\n // `useField()` itself already guards against triggering this: see forms/field.ts, but\n // the polyfill enforcing it too means a test would still catch a *different* caller doing\n // the same thing wrong, instead of that bug only surfacing in a real browser.\n value: function (this: ElementInternals, flags: ValidityStateFlags = {}, message = '') {\n if (Object.values(flags).some(Boolean) && !message) {\n throw new TypeError(\n \"Failed to execute 'setValidity' on 'ElementInternals': The second argument must not be empty if \" +\n 'one or more flags in the first argument are true.',\n );\n }\n\n validityState.set(this, { flags, message });\n },\n writable: true,\n });\n\n patchProto('checkValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('reportValidity', {\n configurable: true,\n value: function (this: ElementInternals) {\n return isValid(this);\n },\n writable: true,\n });\n\n patchProto('validationMessage', {\n configurable: true,\n get(this: ElementInternals) {\n return isValid(this) ? '' : (validityState.get(this)?.message ?? '');\n },\n });\n\n // A ValidityState-shaped view of the flags passed to setValidity: every known\n // flag defaults to false, `valid` reflects whether any flag is set.\n patchProto('validity', {\n configurable: true,\n get(this: ElementInternals): ValidityState {\n const state = validityState.get(this);\n\n return {\n badInput: false,\n customError: false,\n patternMismatch: false,\n rangeOverflow: false,\n rangeUnderflow: false,\n stepMismatch: false,\n tooLong: false,\n tooShort: false,\n typeMismatch: false,\n valid: isValid(this),\n valueMissing: false,\n ...(state?.flags ?? {}),\n } as ValidityState;\n },\n });\n\n patchProto('states', {\n configurable: true,\n get: function (this: ElementInternals & { _states?: Set<string> }) {\n this._states ??= new Set();\n\n return this._states;\n },\n });\n\n // Real browsers mix `checkValidity`/`reportValidity`/`validity`/`validationMessage` onto any\n // `formAssociated: true` custom element itself (delegating to its internals): not just onto\n // `ElementInternals`. jsdom does neither; mirror it here so a component's own\n // `checkValidity()`/`reportValidity()`, and a test asserting against the element directly,\n // behave the same as they would in a real browser.\n const originalAttachInternals = HTMLElement.prototype.attachInternals;\n\n HTMLElement.prototype.attachInternals = function (this: HTMLElement, ...args: []): ElementInternals {\n const internals = originalAttachInternals.apply(this, args);\n\n hostByInternals.set(internals, this);\n\n Object.defineProperties(this, {\n checkValidity: { configurable: true, value: () => internals.checkValidity() },\n reportValidity: { configurable: true, value: () => internals.reportValidity() },\n validationMessage: { configurable: true, get: () => internals.validationMessage },\n validity: { configurable: true, get: () => internals.validity },\n });\n\n return internals;\n };\n restorers.push(() => {\n HTMLElement.prototype.attachInternals = originalAttachInternals;\n });\n\n const appendFormValue = (formData: FormData, name: string, value: File | FormData | string): void => {\n if (value instanceof FormData) {\n for (const [entryName, entryValue] of value.entries()) formData.append(entryName, entryValue);\n\n return;\n }\n\n formData.append(name, value);\n };\n\n // jsdom's `FormData` constructor never collects a form-associated custom element's set form\n // value: real browsers walk the flat tree for every form-associated element with a `name`.\n const NativeFormData = globalThis.FormData;\n\n globalThis.FormData = class FormDataWithFormAssociatedElements extends NativeFormData {\n constructor(form?: HTMLFormElement, submitter?: HTMLElement | null) {\n super(form as HTMLFormElement | undefined, submitter as HTMLElement | null | undefined);\n\n if (!(form instanceof HTMLFormElement)) return;\n\n walkFlatTree(form, (element) => {\n const name = element.getAttribute('name');\n const value = formValueByHost.get(element);\n\n if (!name || value == null || element.hasAttribute('disabled')) return;\n\n appendFormValue(this, name, value);\n });\n }\n };\n restorers.push(() => {\n globalThis.FormData = NativeFormData;\n });\n\n // jsdom never invokes the native `formResetCallback` lifecycle method on form-associated\n // custom elements when their form resets: patch `reset()` to do it (via the same flat-tree\n // walk, since a reset field can be nested behind a shadow boundary too), so `onFormReset()`\n // (see `@vielzeug/ore`'s runtime.ts) is testable against a real `<form>.reset()` call instead\n // of only by calling `element.formResetCallback()` directly.\n const originalReset = HTMLFormElement.prototype.reset;\n\n HTMLFormElement.prototype.reset = function (this: HTMLFormElement, ...args: []) {\n originalReset.apply(this, args);\n\n walkFlatTree(this, (element) => {\n (element as Partial<{ formResetCallback: () => void }>).formResetCallback?.();\n });\n };\n restorers.push(() => {\n HTMLFormElement.prototype.reset = originalReset;\n });\n\n return () => {\n for (const restore of restorers) restore();\n\n restorers.length = 0;\n flagHost[INSTALLED_FLAG] = false;\n };\n};\n"],"mappings":"wCAmBA,IAAa,iCAAmD,CAK9D,GAAI,OAAO,iBAAqB,IAAa,UAAa,CAAC,EAE3D,IAAM,EAAiB,OAAO,IAAI,+CAA+C,EAC3E,EAAW,WAEjB,GAAI,EAAS,GAAiB,UAAa,CAAC,EAE5C,EAAS,GAAkB,GAG3B,IAAM,EAA+B,CAAC,EAEhC,EAAQ,iBA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CACH,CACF,EACA,EAAU,SAAW,CACnB,WAAW,SAAW,CACxB,CAAC,EAOD,IAAM,EAAgB,gBAAgB,UAAU,MAahD,MAXA,iBAAgB,UAAU,MAAQ,SAAiC,GAAG,EAAU,CAC9E,EAAc,MAAM,KAAM,CAAI,EAE9B,EAAa,KAAO,GAAY,CAC9B,EAAwD,oBAAoB,CAC9E,CAAC,CACH,EACA,EAAU,SAAW,CACnB,gBAAgB,UAAU,MAAQ,CACpC,CAAC,MAEY,CACX,IAAK,IAAM,KAAW,EAAW,EAAQ,EAEzC,EAAU,OAAS,EACnB,EAAS,GAAkB,EAC7B,CACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./dom.cjs"),t=require("./errors.cjs"),n=require("./events.cjs"),r=require("./form-internals.cjs"),i=require("./query.cjs"),a=require("./wait.cjs");exports.AssayError=t.AssayError,exports.AssayQueryError=t.AssayQueryError,exports.AssayTimeoutError=t.AssayTimeoutError,exports.delay=a.delay,exports.dispatch=n.dispatch,exports.eventually=a.eventually,exports.fireBlur=n.fireBlur,exports.fireChange=n.fireChange,exports.fireClick=n.fireClick,exports.fireCustom=n.fireCustom,exports.fireFocus=n.fireFocus,exports.fireInput=n.fireInput,exports.fireKeyDown=n.fireKeyDown,exports.fireKeyUp=n.fireKeyUp,exports.fireSubmit=n.fireSubmit,exports.getSlotted=i.getSlotted,exports.installFormInternalsPolyfill=r.installFormInternalsPolyfill,exports.queryAllInShadow=i.queryAllInShadow,exports.queryInShadow=i.queryInShadow,exports.queryPart=i.queryPart,exports.waitForEvent=a.waitForEvent,exports.waitUntil=a.waitUntil,exports.walkFlatTree=e.walkFlatTree,exports.within=i.within;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
export { walkFlatTree } from './dom';
|
|
1
2
|
export { AssayError, AssayQueryError, AssayTimeoutError } from './errors';
|
|
2
3
|
export { dispatch, fireBlur, fireChange, fireClick, fireCustom, fireFocus, fireInput, fireKeyDown, fireKeyUp, fireSubmit, } from './events';
|
|
4
|
+
export { installFormInternalsPolyfill } from './form-internals';
|
|
3
5
|
export { getSlotted, type QueryScope, queryAllInShadow, queryInShadow, queryPart, within } from './query';
|
|
4
6
|
export { type DelayOptions, delay, type EventuallyOptions, eventually, type WaitOptions, waitForEvent, waitUntil, } from './wait';
|
|
5
7
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AACrC,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC1E,OAAO,EACL,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,SAAS,EACT,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,SAAS,EACT,UAAU,GACX,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,KAAK,UAAU,EAAE,gBAAgB,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC1G,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,EACL,KAAK,iBAAiB,EACtB,UAAU,EACV,KAAK,WAAW,EAChB,YAAY,EACZ,SAAS,GACV,MAAM,QAAQ,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AssayError as
|
|
1
|
+
import{walkFlatTree as e}from"./dom.js";import{AssayError as t,AssayQueryError as n,AssayTimeoutError as r}from"./errors.js";import{dispatch as i,fireBlur as a,fireChange as o,fireClick as s,fireCustom as c,fireFocus as l,fireInput as u,fireKeyDown as d,fireKeyUp as f,fireSubmit as p}from"./events.js";import{installFormInternalsPolyfill as m}from"./form-internals.js";import{getSlotted as h,queryAllInShadow as g,queryInShadow as _,queryPart as v,within as y}from"./query.js";import{delay as b,eventually as x,waitForEvent as S,waitUntil as C}from"./wait.js";export{t as AssayError,n as AssayQueryError,r as AssayTimeoutError,b as delay,i as dispatch,x as eventually,a as fireBlur,o as fireChange,s as fireClick,c as fireCustom,l as fireFocus,u as fireInput,d as fireKeyDown,f as fireKeyUp,p as fireSubmit,h as getSlotted,m as installFormInternalsPolyfill,g as queryAllInShadow,_ as queryInShadow,v as queryPart,S as waitForEvent,C as waitUntil,e as walkFlatTree,y as within};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vielzeug/assay",
|
|
3
|
-
"version": "26.10.
|
|
3
|
+
"version": "26.10.9",
|
|
4
4
|
"description": "Framework-agnostic DOM testing primitives: scoped queries, event dispatch, async waiting",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"verify:exports": "node verify-exports.mjs"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@vielzeug/arsenal": "26.10.
|
|
44
|
+
"@vielzeug/arsenal": "26.10.9"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@types/node": "^26.6.2",
|