@gjsify/example-dom-three-geometry-teapot 0.25.1 → 0.26.1

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/dist/gjs.node.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import{createRequire as e}from"node:module";import"@gjsify/node-gi/globals";import t from"@gjsify/node-gi/cairo";import n from"@gjsify/node-gi/system";import{Blob as r,Buffer as i,File as a}from"node:buffer";import o,{PassThrough as s,Readable as c,Stream as l,pipeline as u}from"node:stream";import{isIP as d}from"node:net";var f=Object.create,p=Object.defineProperty,__name$1=(e,t)=>p(e,`name`,{value:t,configurable:!0}),m=Object.getOwnPropertyDescriptor,h=Object.getOwnPropertyNames,g=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty,__esmMin=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},__commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),__exportAll$1=(e,t)=>{let n={};for(var r in e)p(n,r,{get:e[r],enumerable:!0});return t||p(n,Symbol.toStringTag,{value:`Module`}),n},__copyProps=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=h(t),a=0,o=i.length,s;a<o;a++)s=i[a],!_.call(e,s)&&s!==n&&p(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=m(t,s))||r.enumerable});return e},__toESM=(e,t,n)=>(n=e==null?{}:f(g(e)),__copyProps(t||!e||!e.__esModule?p(n,`default`,{value:e,enumerable:!0}):n,e));for(let e of[`Headers`,`Request`,`Response`,`fetch`])try{delete globalThis[e]}catch{}var v=Object.defineProperty,__exportAll=(e,t)=>{let n={};for(var r in e)v(n,r,{get:e[r],enumerable:!0});return t||v(n,Symbol.toStringTag,{value:`Module`}),n};__exportAll({attributes:()=>O,childNodesList:()=>x,elementChildren:()=>S,isConnected:()=>C,localName:()=>T,name:()=>A,namespaceURI:()=>E,nodeType:()=>y,ownerElement:()=>te,parentNode:()=>b,prefix:()=>D,propertyEventListeners:()=>k,tagName:()=>w,value:()=>ee});const y=Symbol(`nodeType`),b=Symbol(`parentNode`),x=Symbol(`childNodesList`),S=Symbol(`elementChildren`),C=Symbol(`isConnected`),w=Symbol(`tagName`),T=Symbol(`localName`),E=Symbol(`namespaceURI`),D=Symbol(`prefix`),O=Symbol(`attributes`),k=Symbol(`propertyEventListeners`),A=Symbol(`name`),ee=Symbol(`value`),te=Symbol(`ownerElement`),j={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11};var NodeList=class{constructor(e){this._items=e}get length(){return this._items.length}item(e){return this._items[e]??null}forEach(e,t){for(let n=0;n<this._items.length;n++)e.call(t,this._items[n],n,this)}entries(){return this._items.entries()}keys(){return this._items.keys()}values(){return this._items.values()}[Symbol.iterator](){return this._items[Symbol.iterator]()}get[Symbol.toStringTag](){return`NodeList`}};const ne=globalThis.DOMException,re=Symbol(`type`),ie=Symbol(`bubbles`),ae=Symbol(`cancelable`),oe=Symbol(`composed`),se=Symbol(`target`),ce=Symbol(`currentTarget`),le=Symbol(`eventPhase`),ue=Symbol(`defaultPrevented`),de=Symbol(`isTrusted`),fe=Symbol(`timeStamp`),pe=Symbol(`stop`),me=Symbol(`immediateStop`),he=Symbol(`dispatching`),ge=Symbol(`inPassiveListener`);var Event=class{[re];[ie];[ae];[oe];[se]=null;[ce]=null;[le]=0;[ue]=!1;[de]=!1;[fe];[pe]=!1;[me]=!1;[he]=!1;[ge]=!1;get type(){return this[re]}get bubbles(){return this[ie]}get cancelable(){return this[ae]}get composed(){return this[oe]}get target(){return this[se]}get currentTarget(){return this[ce]}get eventPhase(){return this[le]}get defaultPrevented(){return this[ue]}get timeStamp(){return this[fe]}get cancelBubble(){return this[pe]}set cancelBubble(e){e&&this.stopPropagation()}get returnValue(){return!this[ue]}set returnValue(e){e||this.preventDefault()}get srcElement(){return this[se]}static NONE=0;static CAPTURING_PHASE=1;static AT_TARGET=2;static BUBBLING_PHASE=3;get[Symbol.toStringTag](){return`Event`}constructor(e,t){this[re]=e,this[ie]=t?.bubbles??!1,this[ae]=t?.cancelable??!1,this[oe]=t?.composed??!1,this[fe]=Date.now(),Object.defineProperty(this,"isTrusted",{get:()=>this[de],enumerable:!0,configurable:!1})}composedPath(){return this[ce]?[this[ce]]:[]}preventDefault(){this[ae]&&!this[ge]&&(this[ue]=!0)}stopPropagation(){this[pe]=!0}stopImmediatePropagation(){this[pe]=!0,this[me]=!0}},CustomEvent$1=class extends Event{static{__name$1(this,`CustomEvent`)}detail;constructor(e,t){super(e,t),this.detail=t?.detail}},MessageEvent=class extends Event{data;origin;lastEventId;source;ports;constructor(e,t){super(e,t),this.data=t?.data??null,this.origin=t?.origin??``,this.lastEventId=t?.lastEventId??``,this.source=t?.source??null,this.ports=t?.ports??[]}get[Symbol.toStringTag](){return`MessageEvent`}},ErrorEvent=class extends Event{message;filename;lineno;colno;error;constructor(e,t){super(e,t),this.message=t?.message??``,this.filename=t?.filename??``,this.lineno=t?.lineno??0,this.colno=t?.colno??0,this.error=t?.error??null}get[Symbol.toStringTag](){return`ErrorEvent`}},CloseEvent=class extends Event{code;reason;wasClean;constructor(e,t){super(e,t),this.code=t?.code??0,this.reason=t?.reason??``,this.wasClean=t?.wasClean??!1}get[Symbol.toStringTag](){return`CloseEvent`}},ProgressEvent$1=class extends Event{static{__name$1(this,`ProgressEvent`)}lengthComputable;loaded;total;constructor(e,t){super(e,t),this.lengthComputable=t?.lengthComputable??!1,this.loaded=t?.loaded??0,this.total=t?.total??0}get[Symbol.toStringTag](){return`ProgressEvent`}},EventTarget=class{_listeners=new Map;get[Symbol.toStringTag](){return`EventTarget`}addEventListener(e,t,n){if(t===null)return;let r=typeof n==`boolean`?n:n?.capture??!1,i=typeof n==`object`?n?.once??!1:!1,a=typeof n==`object`?n?.passive??!1:!1,o=this._listeners.get(e);o||(o=[],this._listeners.set(e,o));for(let e of o)if(e.listener===t&&e.capture===r)return;let s={listener:t,capture:r,once:i,passive:a,removed:!1};o.push(s),typeof n==`object`&&n?.signal&&n.signal.addEventListener(`abort`,()=>{this.removeEventListener(e,t,{capture:r})},{once:!0})}removeEventListener(e,t,n){if(t===null)return;let r=typeof n==`boolean`?n:n?.capture??!1,i=this._listeners.get(e);if(!i)return;let a=i.findIndex(e=>e.listener===t&&e.capture===r);a!==-1&&(i[a].removed=!0,i.splice(a,1),i.length===0&&this._listeners.delete(e))}dispatchEvent(e){let t=e;if(t[he])throw new ne(`The event is already being dispatched.`,`InvalidStateError`);t[he]=!0,t[se]=this,t[ce]=this,t[le]=Event.AT_TARGET;try{let n=this._listeners.get(e.type);if(n){let r=[...n];for(let n of r)if(!n.removed){if(t[me]||t[pe])break;n.once&&this.removeEventListener(e.type,n.listener,{capture:n.capture});try{n.passive&&(t[ge]=!0),typeof n.listener==`function`?n.listener.call(this,e):typeof n.listener.handleEvent==`function`&&n.listener.handleEvent.call(n.listener,e)}catch(e){reportListenerException(e)}finally{t[ge]=!1}}}}finally{t[le]=Event.NONE,t[ce]=null,t[he]=!1}return!e.defaultPrevented}};function reportListenerException(e){try{let t=globalThis;if(typeof t.reportError==`function`)t.reportError(e);else if(e instanceof Error){let t=`${e.name}: ${e.message}`;console.error(e.stack?`${t}\n${e.stack}`:t)}else console.error(String(e))}catch{}}for(let[e,t]of[[`NONE`,0],[`CAPTURING_PHASE`,1],[`AT_TARGET`,2],[`BUBBLING_PHASE`,3]])Object.defineProperty(Event.prototype,e,{value:t,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Event,e,{value:t,writable:!1,enumerable:!0,configurable:!1});var UIEvent=class extends Event{detail;view;constructor(e,t){super(e,t),this.detail=t?.detail??0,this.view=null}get[Symbol.toStringTag](){return`UIEvent`}},MouseEvent=class extends UIEvent{altKey;button;buttons;clientX;clientY;ctrlKey;metaKey;movementX;movementY;offsetX;offsetY;screenX;screenY;shiftKey;relatedTarget;get pageX(){return this.clientX}get pageY(){return this.clientY}get x(){return this.clientX}get y(){return this.clientY}constructor(e,t){super(e,t),this.altKey=t?.altKey??!1,this.button=t?.button??0,this.buttons=t?.buttons??0,this.clientX=t?.clientX??0,this.clientY=t?.clientY??0,this.ctrlKey=t?.ctrlKey??!1,this.metaKey=t?.metaKey??!1,this.movementX=t?.movementX??0,this.movementY=t?.movementY??0,this.offsetX=t?.offsetX??0,this.offsetY=t?.offsetY??0,this.screenX=t?.screenX??0,this.screenY=t?.screenY??0,this.shiftKey=t?.shiftKey??!1,this.relatedTarget=t?.relatedTarget??null}getModifierState(e){switch(e){case`Alt`:return this.altKey;case`Control`:return this.ctrlKey;case`Meta`:return this.metaKey;case`Shift`:return this.shiftKey;default:return!1}}get[Symbol.toStringTag](){return`MouseEvent`}},PointerEvent=class extends MouseEvent{pointerId;width;height;pressure;tangentialPressure;tiltX;tiltY;twist;altitudeAngle;azimuthAngle;pointerType;isPrimary;constructor(e,t){super(e,t),this.pointerId=t?.pointerId??0,this.width=t?.width??1,this.height=t?.height??1,this.pressure=t?.pressure??0,this.tangentialPressure=t?.tangentialPressure??0,this.tiltX=t?.tiltX??0,this.tiltY=t?.tiltY??0,this.twist=t?.twist??0,this.altitudeAngle=t?.altitudeAngle??Math.PI/2,this.azimuthAngle=t?.azimuthAngle??0,this.pointerType=t?.pointerType??``,this.isPrimary=t?.isPrimary??!1}getCoalescedEvents(){return[]}getPredictedEvents(){return[]}get[Symbol.toStringTag](){return`PointerEvent`}},KeyboardEvent=class extends UIEvent{altKey;code;ctrlKey;isComposing;key;location;metaKey;repeat;shiftKey;keyCode;which;static DOM_KEY_LOCATION_STANDARD=0;static DOM_KEY_LOCATION_LEFT=1;static DOM_KEY_LOCATION_RIGHT=2;static DOM_KEY_LOCATION_NUMPAD=3;constructor(e,t){super(e,t),this.altKey=t?.altKey??!1,this.code=t?.code??``,this.ctrlKey=t?.ctrlKey??!1,this.isComposing=t?.isComposing??!1,this.key=t?.key??``,this.location=t?.location??0,this.metaKey=t?.metaKey??!1,this.repeat=t?.repeat??!1,this.shiftKey=t?.shiftKey??!1,this.keyCode=t?.keyCode??0,this.which=t?.which??0}getModifierState(e){switch(e){case`Alt`:return this.altKey;case`Control`:return this.ctrlKey;case`Meta`:return this.metaKey;case`Shift`:return this.shiftKey;default:return!1}}get[Symbol.toStringTag](){return`KeyboardEvent`}},WheelEvent=class extends MouseEvent{deltaX;deltaY;deltaZ;deltaMode;static DOM_DELTA_PIXEL=0;static DOM_DELTA_LINE=1;static DOM_DELTA_PAGE=2;constructor(e,t){super(e,t),this.deltaX=t?.deltaX??0,this.deltaY=t?.deltaY??0,this.deltaZ=t?.deltaZ??0,this.deltaMode=t?.deltaMode??0}get[Symbol.toStringTag](){return`WheelEvent`}},FocusEvent=class extends UIEvent{relatedTarget;constructor(e,t){super(e,t),this.relatedTarget=t?.relatedTarget??null}get[Symbol.toStringTag](){return`FocusEvent`}};let _e,ve,ye,be,xe;var Se=class Node extends EventTarget{constructor(...e){super(...e),this.ELEMENT_NODE=j.ELEMENT_NODE,this.ATTRIBUTE_NODE=j.ATTRIBUTE_NODE,this.TEXT_NODE=j.TEXT_NODE,this.CDATA_SECTION_NODE=j.CDATA_SECTION_NODE,this.PROCESSING_INSTRUCTION_NODE=j.PROCESSING_INSTRUCTION_NODE,this.COMMENT_NODE=j.COMMENT_NODE,this.DOCUMENT_NODE=j.DOCUMENT_NODE,this.DOCUMENT_TYPE_NODE=j.DOCUMENT_TYPE_NODE,this.DOCUMENT_FRAGMENT_NODE=j.DOCUMENT_FRAGMENT_NODE,this[_e]=j.ELEMENT_NODE,this[ve]=null,this[ye]=[],this[be]=[],this[xe]=!1}static{this.ELEMENT_NODE=j.ELEMENT_NODE}static{this.ATTRIBUTE_NODE=j.ATTRIBUTE_NODE}static{this.TEXT_NODE=j.TEXT_NODE}static{this.CDATA_SECTION_NODE=j.CDATA_SECTION_NODE}static{this.PROCESSING_INSTRUCTION_NODE=j.PROCESSING_INSTRUCTION_NODE}static{this.COMMENT_NODE=j.COMMENT_NODE}static{this.DOCUMENT_NODE=j.DOCUMENT_NODE}static{this.DOCUMENT_TYPE_NODE=j.DOCUMENT_TYPE_NODE}static{this.DOCUMENT_FRAGMENT_NODE=j.DOCUMENT_FRAGMENT_NODE}static{this.DOCUMENT_POSITION_DISCONNECTED=1}static{this.DOCUMENT_POSITION_PRECEDING=2}static{this.DOCUMENT_POSITION_FOLLOWING=4}static{this.DOCUMENT_POSITION_CONTAINS=8}static{this.DOCUMENT_POSITION_CONTAINED_BY=16}static{this.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC=32}get nodeType(){return this[y]}get nodeName(){return``}get parentNode(){return this[b]}get parentElement(){let e=this[b];return e&&e[y]===j.ELEMENT_NODE?e:null}get childNodes(){return new NodeList(this[x])}get firstChild(){return this[x][0]??null}get lastChild(){let e=this[x];return e[e.length-1]??null}get previousSibling(){let e=this[b];if(!e)return null;let t=e[x],n=t.indexOf(this);return n>0?t[n-1]:null}get nextSibling(){let e=this[b];if(!e)return null;let t=e[x],n=t.indexOf(this);return n!==-1&&n<t.length-1?t[n+1]:null}get textContent(){return null}set textContent(e){}get nodeValue(){return null}set nodeValue(e){}get ownerDocument(){let e=this;for(;e[b];)e=e[b];let t=globalThis.document;return e===t?t:null}get isConnected(){return this[C]}hasChildNodes(){return this[x].length>0}contains(e){if(e===null)return!1;if(e===this)return!0;let t=e;for(;t;){if(t===this)return!0;t=t[b]}return!1}getRootNode(){let e=this;for(;e[b];)e=e[b];return e}appendChild(e){return e[b]&&e[b].removeChild(e),e[b]=this,this[x].push(e),e[y]===j.ELEMENT_NODE&&this[S].push(e),e}removeChild(e){let t=this[x],n=t.indexOf(e);if(n===-1)throw new DOMException(`Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.`,`NotFoundError`);if(t.splice(n,1),e[b]=null,e[y]===j.ELEMENT_NODE){let t=this[S].indexOf(e);t!==-1&&this[S].splice(t,1)}return e}insertBefore(e,t){if(t===null)return this.appendChild(e);let n=this[x],r=n.indexOf(t);if(r===-1)throw new DOMException(`Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.`,`NotFoundError`);if(e[b]&&e[b].removeChild(e),e[b]=this,n.splice(r,0,e),e[y]===j.ELEMENT_NODE){let t=this[S],i=t.length;for(let a=r;a<n.length;a++)if(n[a][y]===j.ELEMENT_NODE&&n[a]!==e){i=t.indexOf(n[a]);break}t.splice(i,0,e)}return e}replaceChild(e,t){return this.insertBefore(e,t),this.removeChild(t),t}cloneNode(e=!1){let t=new this.constructor;if(t[y]=this[y],e)for(let e of this[x])t.appendChild(e.cloneNode(!0));return t}dispatchEvent(e){let t=super.dispatchEvent(e);if(e.bubbles&&!e.cancelBubble){let t=this[b];for(;t&&(Object.getPrototypeOf(Node.prototype).dispatchEvent.call(t,e),!e.cancelBubble);)t=t[b]}return t}get[(_e=y,ve=b,ye=x,be=S,xe=C,Symbol.toStringTag)](){return`Node`}};const Ce={html:`http://www.w3.org/1999/xhtml`,svg:`http://www.w3.org/2000/svg`,mathML:`http://www.w3.org/1998/Math/MathML`,xml:`http://www.w3.org/XML/1998/namespace`,xmlns:`http://www.w3.org/2000/xmlns/`};var Attr=class{constructor(e,t,n=null,r=null,i=null){this.specified=!0,this[A]=e,this[ee]=t,this[te]=i,this.namespaceURI=n,this.prefix=r;let a=e.indexOf(`:`);this.localName=a===-1?e:e.slice(a+1)}get name(){return this[A]}get value(){return this[ee]}set value(e){this[ee]=e}get ownerElement(){return this[te]}get[Symbol.toStringTag](){return`Attr`}},NamedNodeMap=class{constructor(e){this._items=[],this._ownerElement=e}get length(){return this._items.length}item(e){return this._items[e]??null}getNamedItem(e){return this._findByName(e)}getNamedItemNS(e,t){let n=e===``?null:e;for(let e of this._items)if(e.namespaceURI===n&&e.localName===t)return e;return null}setNamedItem(e){return this._setAttr(e)}setNamedItemNS(e){return this._setAttr(e)}removeNamedItem(e){let t=this._findByName(e);if(!t)throw new DOMException(`Failed to execute 'removeNamedItem' on 'NamedNodeMap': No item with name '${e}' was found.`,`NotFoundError`);return this._removeAttr(t),t}removeNamedItemNS(e,t){let n=this.getNamedItemNS(e,t);if(!n)throw new DOMException(`Failed to execute 'removeNamedItemNS' on 'NamedNodeMap': No item with namespace '${e}' and localName '${t}' was found.`,`NotFoundError`);return this._removeAttr(n),n}[Symbol.iterator](){return this._items[Symbol.iterator]()}get[Symbol.toStringTag](){return`NamedNodeMap`}_setNamedItem(e,t,n=null,r=null){let i=n===null?this._findByName(e):this.getNamedItemNS(n,e.includes(`:`)?e.split(`:`)[1]:e);if(i)i.value=t;else{let i=new Attr(e,t,n,r,this._ownerElement);this._items.push(i)}}_removeNamedItem(e){let t=this._findByName(e);return t?(this._removeAttr(t),!0):!1}_removeNamedItemNS(e,t){let n=this.getNamedItemNS(e,t);return n?(this._removeAttr(n),!0):!1}_findByName(e){let t=this._ownerElement.namespaceURI===Ce.html,n=t?e.toLowerCase():e;for(let e of this._items)if((t?e.name.toLowerCase():e.name)===n)return e;return null}_setAttr(e){let t=null;if(t=e.namespaceURI===null?this._findByName(e.name):this.getNamedItemNS(e.namespaceURI,e.localName),t){let n=new Attr(t.name,t.value,t.namespaceURI,t.prefix,t.ownerElement);return t.value=e.value,n}return this._items.push(e),null}_removeAttr(e){let t=this._items.indexOf(e);t!==-1&&this._items.splice(t,1)}};let we,M,Te,Ee,N,De;var Element=class extends Se{constructor(){super(),this[we]=``,this[M]=``,this[Te]=Ce.html,this[Ee]=null,this[N]=new NamedNodeMap(this),this[De]=new Map,this._resizeSubscribers=null,this._allocatedClientWidth=0,this._allocatedClientHeight=0,this._pointerCaptures=new Set,this[y]=j.ELEMENT_NODE}get tagName(){return this[w]}get localName(){return this[T]}get namespaceURI(){return this[E]}get prefix(){return this[D]}get nodeName(){return this[w]}get attributes(){return this[O]}get id(){return this.getAttribute(`id`)??``}set id(e){this.setAttribute(`id`,e)}get className(){return this.getAttribute(`class`)??``}set className(e){this.setAttribute(`class`,e)}get children(){return this[S]}get childElementCount(){return this[S].length}get firstElementChild(){return this[S][0]??null}get lastElementChild(){let e=this[S];return e[e.length-1]??null}get previousElementSibling(){let e=this[b];if(!e)return null;let t=e[S],n=t.indexOf(this);return n>0?t[n-1]:null}get nextElementSibling(){let e=this[b];if(!e)return null;let t=e[S],n=t.indexOf(this);return n!==-1&&n<t.length-1?t[n+1]:null}get textContent(){let e=``;for(let t of this[x])t.textContent!==null&&(e+=t.textContent);return e}set textContent(e){let t=this[x];for(;t.length>0;)this.removeChild(t[0])}getAttribute(e){let t=this[O].getNamedItem(e);return t?t.value:null}getAttributeNS(e,t){let n=this[O].getNamedItemNS(e,t);return n?n.value:null}setAttribute(e,t){this[O]._setNamedItem(e,String(t))}setAttributeNS(e,t,n){let r=e===``?null:e,i=t.split(`:`),a=i.length>1?i[0]:null;this[O]._setNamedItem(t,String(n),r,a)}removeAttribute(e){this[O]._removeNamedItem(e)}removeAttributeNS(e,t){let n=e===``?null:e;this[O]._removeNamedItemNS(n,t)}hasAttribute(e){return this[O].getNamedItem(e)!==null}hasAttributeNS(e,t){return this[O].getNamedItemNS(e,t)!==null}getAttributeNode(e){return this[O].getNamedItem(e)}setAttributeNode(e){return this[O].setNamedItem(e)}removeAttributeNode(e){let t=this[O].getNamedItem(e.name);if(!t)throw new DOMException(`Failed to execute 'removeAttributeNode' on 'Element': The attribute is not owned by this element.`,`NotFoundError`);return this[O].removeNamedItem(t.name),t}toggleAttribute(e,t){return t===void 0?this.hasAttribute(e)?(this.removeAttribute(e),!1):(this.setAttribute(e,``),!0):t?(this.setAttribute(e,``),!0):(this.removeAttribute(e),!1)}hasAttributes(){return this[O].length>0}dispatchEvent(e){let t=super.dispatchEvent(e),n=this[k].get(`on`+e.type);return typeof n==`function`&&n.call(this,e),t}querySelector(e){return null}querySelectorAll(e){return[]}matches(e){return!1}closest(e){return null}getElementsByTagName(e){let t=[],n=e.toUpperCase(),walk=r=>{for(let i of r[x])if(i[y]===j.ELEMENT_NODE){let r=i;(e===`*`||r[w]===n)&&t.push(r),walk(r)}};return walk(this),t}getElementsByClassName(e){let t=[],n=e.split(/\s+/).filter(Boolean),walk=e=>{for(let r of e[x])if(r[y]===j.ELEMENT_NODE){let e=r,i=e.className.split(/\s+/);n.every(e=>i.includes(e))&&t.push(e),walk(e)}};return walk(this),t}cloneNode(e=!1){let t=super.cloneNode(!1);t[w]=this[w],t[T]=this[T],t[E]=this[E],t[D]=this[D];for(let e of this[O])t.setAttributeNS(e.namespaceURI,e.name,e.value);if(e)for(let e of this[x])t.appendChild(e.cloneNode(!0));return t}_onResize(e){let t=this._resizeSubscribers??=new Set;return t.add(e),()=>{t.delete(e),t.size===0&&(this._resizeSubscribers=null)}}_fireResizeSubscribers(e,t){let n=this._resizeSubscribers;if(!(!n||n.size===0))for(let r of[...n])try{r(e,t)}catch(e){console.error(`ResizeObserver subscriber threw:`,e)}}setPointerCapture(e){this._pointerCaptures.add(e)}releasePointerCapture(e){this._pointerCaptures.delete(e)}hasPointerCapture(e){return this._pointerCaptures.has(e)}get[(we=w,M=T,Te=E,Ee=D,N=O,De=k,Symbol.toStringTag)](){return`Element`}},CSSStyleDeclaration=class{constructor(){this._cssText=``}get cssText(){return this._cssText}set cssText(e){this._cssText=e;for(let t of e.split(`;`)){let e=t.indexOf(`:`);if(e===-1)continue;let n=t.slice(0,e).trim(),r=t.slice(e+1).trim();if(!n)continue;let i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());this[i]=r}}setProperty(e,t,n){this[e]=t}getPropertyValue(e){let t=this[e];return typeof t==`string`?t:``}removeProperty(e){let t=this[e];return delete this[e],typeof t==`string`?t:``}getPropertyPriority(e){return``}},HTMLElement=class extends Element{constructor(...e){super(...e),this.style=new CSSStyleDeclaration}get dataset(){let e=this;return new Proxy({},{get(t,n){if(typeof n!=`string`)return;let r=`data-`+n.replace(/[A-Z]/g,e=>`-`+e.toLowerCase());return e.getAttribute(r)??void 0},set(t,n,r){if(typeof n!=`string`)return!1;let i=`data-`+n.replace(/[A-Z]/g,e=>`-`+e.toLowerCase());return e.setAttribute(i,String(r)),!0},deleteProperty(t,n){if(typeof n!=`string`)return!1;let r=`data-`+n.replace(/[A-Z]/g,e=>`-`+e.toLowerCase());return e.removeAttribute(r),!0},has(t,n){if(typeof n!=`string`)return!1;let r=`data-`+n.replace(/[A-Z]/g,e=>`-`+e.toLowerCase());return e.hasAttribute(r)}})}get title(){return this.getAttribute(`title`)??``}set title(e){this.setAttribute(`title`,e)}get lang(){return this.getAttribute(`lang`)??``}set lang(e){this.setAttribute(`lang`,e)}get dir(){return this.getAttribute(`dir`)??``}set dir(e){this.setAttribute(`dir`,e)}get accessKey(){return this.getAttribute(`accesskey`)??``}set accessKey(e){this.setAttribute(`accesskey`,e)}get accessKeyLabel(){return this.getAttribute(`accesskey`)??``}get hidden(){return this.hasAttribute(`hidden`)}set hidden(e){e?this.setAttribute(`hidden`,``):this.removeAttribute(`hidden`)}get draggable(){return this.getAttribute(`draggable`)===`true`}set draggable(e){this.setAttribute(`draggable`,String(e))}get spellcheck(){let e=this.getAttribute(`spellcheck`);return e===`false`?!1:e!==null}set spellcheck(e){this.setAttribute(`spellcheck`,String(e))}get translate(){return this.getAttribute(`translate`)!==`no`}set translate(e){this.setAttribute(`translate`,e?`yes`:`no`)}get tabIndex(){let e=this.getAttribute(`tabindex`);return e===null?-1:Number(e)}set tabIndex(e){this.setAttribute(`tabindex`,String(e))}get contentEditable(){let e=this.getAttribute(`contenteditable`);return e===``||e===`true`?`true`:e===`false`?`false`:`inherit`}set contentEditable(e){e===`inherit`?this.removeAttribute(`contenteditable`):this.setAttribute(`contenteditable`,e)}get isContentEditable(){return this.contentEditable===`true`}get offsetHeight(){return this._allocatedClientHeight}get offsetWidth(){return this._allocatedClientWidth}get offsetLeft(){return 0}get offsetTop(){return 0}get offsetParent(){return null}get clientHeight(){return this._allocatedClientHeight}get clientWidth(){return this._allocatedClientWidth}get clientLeft(){return 0}get clientTop(){return 0}get scrollHeight(){return this._allocatedClientHeight}get scrollWidth(){return this._allocatedClientWidth}get scrollTop(){return 0}set scrollTop(e){}get scrollLeft(){return 0}set scrollLeft(e){}getBoundingClientRect(){let e=this.clientWidth,t=this.clientHeight;return{x:0,y:0,top:0,left:0,right:e,bottom:t,width:e,height:t,toJSON(){return this}}}click(){this.dispatchEvent(new Event(`click`,{bubbles:!0,cancelable:!0}))}blur(){this.dispatchEvent(new Event(`blur`))}focus(){this.dispatchEvent(new Event(`focus`))}get onclick(){return this[k].get(`onclick`)??null}set onclick(e){this[k].set(`onclick`,e)}get ondblclick(){return this[k].get(`ondblclick`)??null}set ondblclick(e){this[k].set(`ondblclick`,e)}get onload(){return this[k].get(`onload`)??null}set onload(e){this[k].set(`onload`,e)}get onerror(){return this[k].get(`onerror`)??null}set onerror(e){this[k].set(`onerror`,e)}get onabort(){return this[k].get(`onabort`)??null}set onabort(e){this[k].set(`onabort`,e)}get onfocus(){return this[k].get(`onfocus`)??null}set onfocus(e){this[k].set(`onfocus`,e)}get onblur(){return this[k].get(`onblur`)??null}set onblur(e){this[k].set(`onblur`,e)}get onchange(){return this[k].get(`onchange`)??null}set onchange(e){this[k].set(`onchange`,e)}get oninput(){return this[k].get(`oninput`)??null}set oninput(e){this[k].set(`oninput`,e)}get onsubmit(){return this[k].get(`onsubmit`)??null}get onreset(){return this[k].get(`onreset`)??null}set onreset(e){this[k].set(`onreset`,e)}get onscroll(){return this[k].get(`onscroll`)??null}set onscroll(e){this[k].set(`onscroll`,e)}get onresize(){return this[k].get(`onresize`)??null}set onresize(e){this[k].set(`onresize`,e)}get onmousedown(){return this[k].get(`onmousedown`)??null}set onmousedown(e){this[k].set(`onmousedown`,e)}get onmouseup(){return this[k].get(`onmouseup`)??null}set onmouseup(e){this[k].set(`onmouseup`,e)}get onmousemove(){return this[k].get(`onmousemove`)??null}set onmousemove(e){this[k].set(`onmousemove`,e)}get onmouseover(){return this[k].get(`onmouseover`)??null}set onmouseover(e){this[k].set(`onmouseover`,e)}get onmouseout(){return this[k].get(`onmouseout`)??null}set onmouseout(e){this[k].set(`onmouseout`,e)}get onmouseenter(){return this[k].get(`onmouseenter`)??null}set onmouseenter(e){this[k].set(`onmouseenter`,e)}get onmouseleave(){return this[k].get(`onmouseleave`)??null}set onmouseleave(e){this[k].set(`onmouseleave`,e)}get oncontextmenu(){return this[k].get(`oncontextmenu`)??null}set oncontextmenu(e){this[k].set(`oncontextmenu`,e)}get onwheel(){return this[k].get(`onwheel`)??null}set onwheel(e){this[k].set(`onwheel`,e)}get onkeydown(){return this[k].get(`onkeydown`)??null}set onkeydown(e){this[k].set(`onkeydown`,e)}get onkeyup(){return this[k].get(`onkeyup`)??null}set onkeyup(e){this[k].set(`onkeyup`,e)}get ontouchstart(){return this[k].get(`ontouchstart`)??null}set ontouchstart(e){this[k].set(`ontouchstart`,e)}get ontouchend(){return this[k].get(`ontouchend`)??null}set ontouchend(e){this[k].set(`ontouchend`,e)}get ontouchmove(){return this[k].get(`ontouchmove`)??null}set ontouchmove(e){this[k].set(`ontouchmove`,e)}get onpointerdown(){return this[k].get(`onpointerdown`)??null}set onpointerdown(e){this[k].set(`onpointerdown`,e)}get onpointerup(){return this[k].get(`onpointerup`)??null}set onpointerup(e){this[k].set(`onpointerup`,e)}get onpointermove(){return this[k].get(`onpointermove`)??null}set onpointermove(e){this[k].set(`onpointermove`,e)}cloneNode(e=!1){return super.cloneNode(e)}get[Symbol.toStringTag](){return`HTMLElement`}},P=class HTMLCanvasElement extends HTMLElement{constructor(...e){super(...e),this.oncontextlost=null,this.oncontextrestored=null,this.onwebglcontextcreationerror=null,this.onwebglcontextlost=null,this.onwebglcontextrestored=null}static{this._contextFactories=new Map}static registerContextFactory(e,t){HTMLCanvasElement._contextFactories.set(e,t)}get width(){let e=this.getAttribute(`width`);return e===null?300:Number(e)}set width(e){this.setAttribute(`width`,String(e))}get height(){let e=this.getAttribute(`height`);return e===null?150:Number(e)}set height(e){this.setAttribute(`height`,String(e))}getContext(e,t){let n=HTMLCanvasElement._contextFactories.get(e);return n?n(this,t):null}toDataURL(e,t){let n=this.getContext(`2d`);return n&&typeof n._toDataURL==`function`?n._toDataURL(e,t):``}toBlob(e,t,n){let r=this.toDataURL(t,n);if(!r){e(null);return}let[i,a]=r.split(`,`),o=i.split(`:`)[1].split(`;`)[0],s=atob(a),c=new Uint8Array(s.length);for(let e=0;e<s.length;e++)c[e]=s.charCodeAt(e);e(new Blob([c],{type:o}))}captureStream(e){return{}}},Oe=class DOMMatrix{constructor(e){this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0,this.m11=1,this.m12=0,this.m13=0,this.m14=0,this.m21=0,this.m22=1,this.m23=0,this.m24=0,this.m31=0,this.m32=0,this.m33=1,this.m34=0,this.m41=0,this.m42=0,this.m43=0,this.m44=1,this.is2D=!0,this.isIdentity=!0,Array.isArray(e)&&(e.length===6?(this.a=this.m11=e[0],this.b=this.m12=e[1],this.c=this.m21=e[2],this.d=this.m22=e[3],this.e=this.m41=e[4],this.f=this.m42=e[5],this.is2D=!0):e.length===16&&(this.m11=e[0],this.m12=e[1],this.m13=e[2],this.m14=e[3],this.m21=e[4],this.m22=e[5],this.m23=e[6],this.m24=e[7],this.m31=e[8],this.m32=e[9],this.m33=e[10],this.m34=e[11],this.m41=e[12],this.m42=e[13],this.m43=e[14],this.m44=e[15],this.a=this.m11,this.b=this.m12,this.c=this.m21,this.d=this.m22,this.e=this.m41,this.f=this.m42,this.is2D=!1),this.isIdentity=this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.e===0&&this.f===0)}multiply(e){let t=this.a*e.a+this.c*e.b,n=this.b*e.a+this.d*e.b,r=this.a*e.c+this.c*e.d,i=this.b*e.c+this.d*e.d,a=this.a*e.e+this.c*e.f+this.e,o=this.b*e.e+this.d*e.f+this.f;return new DOMMatrix([t,n,r,i,a,o])}multiplySelf(e){let t=this.multiply(e);return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.e=t.e,this.f=t.f,this.m11=this.a,this.m12=this.b,this.m21=this.c,this.m22=this.d,this.m41=this.e,this.m42=this.f,this.isIdentity=!1,this}inverse(){let e=this.a*this.d-this.b*this.c;if(e===0)return new DOMMatrix([1,0,0,1,0,0]);let t=1/e;return new DOMMatrix([this.d*t,-this.b*t,-this.c*t,this.a*t,(this.c*this.f-this.d*this.e)*t,(this.b*this.e-this.a*this.f)*t])}translate(e=0,t=0){return this.multiply({a:1,b:0,c:0,d:1,e,f:t})}scale(e=1,t=e){return this.multiply({a:e,b:0,c:0,d:t,e:0,f:0})}};const ke=Oe;function defineGlobal(e,t){Object.defineProperty(globalThis,e,{value:t,writable:!0,configurable:!0})}function defineGlobalIfMissing(e,t){globalThis[e]===void 0&&defineGlobal(e,t)}const Ae={aliceblue:`#f0f8ff`,antiquewhite:`#faebd7`,aqua:`#00ffff`,aquamarine:`#7fffd4`,azure:`#f0ffff`,beige:`#f5f5dc`,bisque:`#ffe4c4`,black:`#000000`,blanchedalmond:`#ffebcd`,blue:`#0000ff`,blueviolet:`#8a2be2`,brown:`#a52a2a`,burlywood:`#deb887`,cadetblue:`#5f9ea0`,chartreuse:`#7fff00`,chocolate:`#d2691e`,coral:`#ff7f50`,cornflowerblue:`#6495ed`,cornsilk:`#fff8dc`,crimson:`#dc143c`,cyan:`#00ffff`,darkblue:`#00008b`,darkcyan:`#008b8b`,darkgoldenrod:`#b8860b`,darkgray:`#a9a9a9`,darkgreen:`#006400`,darkgrey:`#a9a9a9`,darkkhaki:`#bdb76b`,darkmagenta:`#8b008b`,darkolivegreen:`#556b2f`,darkorange:`#ff8c00`,darkorchid:`#9932cc`,darkred:`#8b0000`,darksalmon:`#e9967a`,darkseagreen:`#8fbc8f`,darkslateblue:`#483d8b`,darkslategray:`#2f4f4f`,darkslategrey:`#2f4f4f`,darkturquoise:`#00ced1`,darkviolet:`#9400d3`,deeppink:`#ff1493`,deepskyblue:`#00bfff`,dimgray:`#696969`,dimgrey:`#696969`,dodgerblue:`#1e90ff`,firebrick:`#b22222`,floralwhite:`#fffaf0`,forestgreen:`#228b22`,fuchsia:`#ff00ff`,gainsboro:`#dcdcdc`,ghostwhite:`#f8f8ff`,gold:`#ffd700`,goldenrod:`#daa520`,gray:`#808080`,green:`#008000`,greenyellow:`#adff2f`,grey:`#808080`,honeydew:`#f0fff0`,hotpink:`#ff69b4`,indianred:`#cd5c5c`,indigo:`#4b0082`,ivory:`#fffff0`,khaki:`#f0e68c`,lavender:`#e6e6fa`,lavenderblush:`#fff0f5`,lawngreen:`#7cfc00`,lemonchiffon:`#fffacd`,lightblue:`#add8e6`,lightcoral:`#f08080`,lightcyan:`#e0ffff`,lightgoldenrodyellow:`#fafad2`,lightgray:`#d3d3d3`,lightgreen:`#90ee90`,lightgrey:`#d3d3d3`,lightpink:`#ffb6c1`,lightsalmon:`#ffa07a`,lightseagreen:`#20b2aa`,lightskyblue:`#87cefa`,lightslategray:`#778899`,lightslategrey:`#778899`,lightsteelblue:`#b0c4de`,lightyellow:`#ffffe0`,lime:`#00ff00`,limegreen:`#32cd32`,linen:`#faf0e6`,magenta:`#ff00ff`,maroon:`#800000`,mediumaquamarine:`#66cdaa`,mediumblue:`#0000cd`,mediumorchid:`#ba55d3`,mediumpurple:`#9370db`,mediumseagreen:`#3cb371`,mediumslateblue:`#7b68ee`,mediumspringgreen:`#00fa9a`,mediumturquoise:`#48d1cc`,mediumvioletred:`#c71585`,midnightblue:`#191970`,mintcream:`#f5fffa`,mistyrose:`#ffe4e1`,moccasin:`#ffe4b5`,navajowhite:`#ffdead`,navy:`#000080`,oldlace:`#fdf5e6`,olive:`#808000`,olivedrab:`#6b8e23`,orange:`#ffa500`,orangered:`#ff4500`,orchid:`#da70d6`,palegoldenrod:`#eee8aa`,palegreen:`#98fb98`,paleturquoise:`#afeeee`,palevioletred:`#db7093`,papayawhip:`#ffefd5`,peachpuff:`#ffdab9`,peru:`#cd853f`,pink:`#ffc0cb`,plum:`#dda0dd`,powderblue:`#b0e0e6`,purple:`#800080`,rebeccapurple:`#663399`,red:`#ff0000`,rosybrown:`#bc8f8f`,royalblue:`#4169e1`,saddlebrown:`#8b4513`,salmon:`#fa8072`,sandybrown:`#f4a460`,seagreen:`#2e8b57`,seashell:`#fff5ee`,sienna:`#a0522d`,silver:`#c0c0c0`,skyblue:`#87ceeb`,slateblue:`#6a5acd`,slategray:`#708090`,slategrey:`#708090`,snow:`#fffafa`,springgreen:`#00ff7f`,steelblue:`#4682b4`,tan:`#d2b48c`,teal:`#008080`,thistle:`#d8bfd8`,tomato:`#ff6347`,turquoise:`#40e0d0`,violet:`#ee82ee`,wheat:`#f5deb3`,white:`#ffffff`,whitesmoke:`#f5f5f5`,yellow:`#ffff00`,yellowgreen:`#9acd32`,transparent:`#00000000`};function parseColor(e){if(!e||typeof e!=`string`)return null;let t=e.trim().toLowerCase(),n=Ae[t];if(n)return parseHex(n);if(t.startsWith(`#`))return parseHex(t);let r=t.match(/^rgba?\(\s*(\d+(?:\.\d+)?%?)\s*[,\s]\s*(\d+(?:\.\d+)?%?)\s*[,\s]\s*(\d+(?:\.\d+)?%?)\s*(?:[,/]\s*(\d+(?:\.\d+)?%?))?\s*\)$/);if(r)return{r:parseComponent(r[1],255)/255,g:parseComponent(r[2],255)/255,b:parseComponent(r[3],255)/255,a:r[4]===void 0?1:parseComponent(r[4],1)};let i=t.match(/^hsla?\(\s*(\d+(?:\.\d+)?)\s*[,\s]\s*(\d+(?:\.\d+)?)(%)?\s*[,\s]\s*(\d+(?:\.\d+)?)(%)?\s*(?:[,/]\s*(\d+(?:\.\d+)?%?))?\s*\)$/);if(i){let e=parseFloat(i[1]),t=parseFloat(i[2]),n=i[3]===`%`,r=parseFloat(i[4]),a=i[5]===`%`,o=i[6]===void 0?1:parseComponent(i[6],1);return e>1&&(e/=360),(n||t>1)&&(t/=100),(a||r>1)&&(r/=100),hslToRGBA(e,t,r,Math.max(0,Math.min(1,o)))}return null}function parseHex(e){let t=e.slice(1),n,r,i,a=1;if(t.length===3)n=parseInt(t[0]+t[0],16)/255,r=parseInt(t[1]+t[1],16)/255,i=parseInt(t[2]+t[2],16)/255;else if(t.length===4)n=parseInt(t[0]+t[0],16)/255,r=parseInt(t[1]+t[1],16)/255,i=parseInt(t[2]+t[2],16)/255,a=parseInt(t[3]+t[3],16)/255;else if(t.length===6)n=parseInt(t.slice(0,2),16)/255,r=parseInt(t.slice(2,4),16)/255,i=parseInt(t.slice(4,6),16)/255;else if(t.length===8)n=parseInt(t.slice(0,2),16)/255,r=parseInt(t.slice(2,4),16)/255,i=parseInt(t.slice(4,6),16)/255,a=parseInt(t.slice(6,8),16)/255;else return null;return{r:n,g:r,b:i,a}}function parseComponent(e,t){return e.endsWith(`%`)?parseFloat(e)/100*t:parseFloat(e)}function hue2rgb$1(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}__name$1(hue2rgb$1,`hue2rgb`);function hslToRGBA(e,t,n,r){let i,a,o;if(t===0)i=a=o=n;else{let r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=hue2rgb$1(s,r,e+1/3),a=hue2rgb$1(s,r,e),o=hue2rgb$1(s,r,e-1/3)}return{r:i,g:a,b:o,a:r}}const je={r:0,g:0,b:0,a:1};var CanvasGradient=class{constructor(e,n,r,i,a,o,s){e===`radial`?this._pattern=new t.RadialGradient(n,r,o,i,a,s):this._pattern=new t.LinearGradient(n,r,i,a)}addColorStop(e,t){let n=parseColor(t);n&&this._pattern.addColorStopRGBA(e,n.r,n.g,n.b,n.a)}_getCairoPattern(){return this._pattern}};function quadraticToCubic(e,t,n,r,i,a){return{cp1x:e+2/3*(n-e),cp1y:t+2/3*(r-t),cp2x:i+2/3*(n-i),cp2y:a+2/3*(r-a)}}function computeArcTo(e,t,n,r,i,a,o){let s=e-n,c=t-r,l=i-n,u=a-r,d=Math.sqrt(s*s+c*c),f=Math.sqrt(l*l+u*u);if(d===0||f===0)return null;let p=s/d,m=c/d,h=l/f,g=u/f,_=p*g-m*h;if(Math.abs(_)<1e-10)return null;let v=p*h+m*g,y=Math.acos(Math.max(-1,Math.min(1,v)))/2,b=o/Math.tan(y),x=n+p*b,S=r+m*b,C=n+h*b,w=r+g*b,T=o/Math.sin(y),E=(p+h)/2,D=(m+g)/2,O=Math.sqrt(E*E+D*D),k=n+E/O*T,A=r+D/O*T;return{tx0:x,ty0:S,tx1:C,ty1:w,cx:k,cy:A,startAngle:Math.atan2(S-A,x-k),endAngle:Math.atan2(w-A,C-k),counterclockwise:_>0}}function cairoArcTo(e,t,n,r,i,a,o,s){let c=computeArcTo(t,n,r,i,a,o,s);if(!c){e.lineTo(r,i);return}let{tx0:l,ty0:u,cx:d,cy:f,startAngle:p,endAngle:m,counterclockwise:h}=c;e.lineTo(l,u),h?e.arcNegative(d,f,s,p,m):e.arc(d,f,s,p,m)}function cairoEllipse(e,t,n,r,i,a,o,s,c){e.save(),e.translate(t,n),e.rotate(a),e.scale(r,i),c?e.arcNegative(0,0,1,o,s):e.arc(0,0,1,o,s),e.restore()}function cairoRoundRect(e,t,n,r,i,a){let o,s,c,l;typeof a==`number`?o=s=c=l=a:a.length===1?o=s=c=l=a[0]:a.length===2?(o=c=a[0],s=l=a[1]):a.length===3?(o=a[0],s=l=a[1],c=a[2]):(o=a[0],s=a[1],c=a[2],l=a[3]);let u=Math.min(r/2,i/2);o=Math.min(o,u),s=Math.min(s,u),c=Math.min(c,u),l=Math.min(l,u);let d=Math.PI/2;e.newSubPath(),e.arc(t+o,n+o,o,Math.PI,Math.PI+d),e.arc(t+r-s,n+s,s,-d,0),e.arc(t+r-c,n+i-c,c,0,d),e.arc(t+l,n+i-l,l,d,Math.PI),e.closePath()}const Me={"source-over":2,"source-in":3,"source-out":4,"source-atop":5,"destination-over":7,"destination-in":8,"destination-out":9,"destination-atop":10,lighter:12,copy:1,xor:11,multiply:14,screen:15,overlay:16,darken:17,lighten:18,"color-dodge":19,"color-burn":20,"hard-light":21,"soft-light":22,difference:23,exclusion:24,hue:25,saturation:26,color:27,luminosity:28},Ne={butt:0,round:1,square:2},Pe={miter:0,round:1,bevel:2};var Fe=class Path2D{constructor(e){this._ops=[],e instanceof Path2D&&(this._ops=[...e._ops])}addPath(e){this._ops.push(...e._ops)}moveTo(e,t){this._ops.push({type:`moveTo`,x:e,y:t})}lineTo(e,t){this._ops.push({type:`lineTo`,x:e,y:t})}closePath(){this._ops.push({type:`closePath`})}bezierCurveTo(e,t,n,r,i,a){this._ops.push({type:`bezierCurveTo`,cp1x:e,cp1y:t,cp2x:n,cp2y:r,x:i,y:a})}quadraticCurveTo(e,t,n,r){this._ops.push({type:`quadraticCurveTo`,cpx:e,cpy:t,x:n,y:r})}arc(e,t,n,r,i,a=!1){this._ops.push({type:`arc`,x:e,y:t,radius:n,startAngle:r,endAngle:i,ccw:a})}ellipse(e,t,n,r,i,a,o,s=!1){if(n<0||r<0)throw RangeError(`The radii provided are negative`);this._ops.push({type:`ellipse`,x:e,y:t,rx:n,ry:r,rotation:i,startAngle:a,endAngle:o,ccw:s})}rect(e,t,n,r){this._ops.push({type:`rect`,x:e,y:t,w:n,h:r})}roundRect(e,t,n,r,i=0){this._ops.push({type:`roundRect`,x:e,y:t,w:n,h:r,radii:i})}_replayOnCairo(e){let t=0,n=0;for(let r of this._ops)switch(r.type){case`moveTo`:e.moveTo(r.x,r.y),t=r.x,n=r.y;break;case`lineTo`:e.lineTo(r.x,r.y),t=r.x,n=r.y;break;case`closePath`:e.closePath();break;case`bezierCurveTo`:e.curveTo(r.cp1x,r.cp1y,r.cp2x,r.cp2y,r.x,r.y),t=r.x,n=r.y;break;case`quadraticCurveTo`:{let{cp1x:i,cp1y:a,cp2x:o,cp2y:s}=quadraticToCubic(t,n,r.cpx,r.cpy,r.x,r.y);e.curveTo(i,a,o,s,r.x,r.y),t=r.x,n=r.y;break}case`arc`:r.ccw?e.arcNegative(r.x,r.y,r.radius,r.startAngle,r.endAngle):e.arc(r.x,r.y,r.radius,r.startAngle,r.endAngle);break;case`ellipse`:e.save(),e.translate(r.x,r.y),e.rotate(r.rotation),e.scale(r.rx,r.ry),r.ccw?e.arcNegative(0,0,1,r.startAngle,r.endAngle):e.arc(0,0,1,r.startAngle,r.endAngle),e.restore();break;case`rect`:e.rectangle(r.x,r.y,r.w,r.h);break;case`roundRect`:cairoRoundRect(e,r.x,r.y,r.w,r.h,r.radii);break}}};function asCairoPattern(e){if(!e)return null;let t=e;return typeof t.setFilter!=`function`||typeof t.setExtend!=`function`?null:t}function isPixbufImageSource(e){return typeof e!=`object`||!e?!1:typeof e.isPixbuf==`function`&&e.isPixbuf()}function isCanvasImageSource(e){return typeof e!=`object`||!e?!1:typeof e.getContext==`function`}let Ie=null;function setCanvasPixelBridge(e){Ie=e}function getCanvasPixelBridge(){if(!Ie)throw TypeError(`@gjsify/canvas2d-core: no pixel bridge registered — pixel operations (getImageData / putImageData / drawImage / createPattern) need a platform backend. On GJS, import '@gjsify/canvas2d-core/gdk' (or use '@gjsify/dom-elements' / '@gjsify/canvas2d', which register it for you).`);return Ie}var Le=class CanvasPattern{constructor(e,n){let r=asCairoPattern(new t.SurfacePattern(e));if(!r)throw TypeError(`CanvasPattern: cairo SurfacePattern is missing setExtend at runtime — incompatible Cairo binding`);switch(this._pattern=r,n){case`repeat`:case``:case null:r.setExtend(t.Extend.REPEAT);break;case`repeat-x`:case`repeat-y`:r.setExtend(t.Extend.REPEAT);break;case`no-repeat`:r.setExtend(t.Extend.NONE);break}}static create(e,n){if(isPixbufImageSource(e)){let r=e._pixbuf,i=r.get_width(),a=r.get_height(),o=new t.ImageSurface(t.Format.ARGB32,i,a),s=new t.Context(o);return getCanvasPixelBridge().setSourceImage(s,r,0,0),s.paint(),s.$dispose(),new CanvasPattern(o,n)}if(isCanvasImageSource(e)){let r=e.getContext(`2d`);if(r&&typeof r._getSurface==`function`){let e=r._getSurface(),i=e.getWidth(),a=e.getHeight(),o=new t.ImageSurface(t.Format.ARGB32,i,a),s=new t.Context(o);return s.setSourceSurface(e,0,0),s.paint(),s.$dispose(),new CanvasPattern(o,n)}}return null}_getCairoPattern(){return this._pattern}},OurImageData=class{constructor(e,t,n){if(this.colorSpace=`srgb`,typeof e==`number`)this.width=e,this.height=t,this.data=new Uint8ClampedArray(this.width*this.height*4);else if(this.data=e,this.width=t,this.height=n??this.data.length/(4*this.width),this.data.length!==this.width*this.height*4)throw RangeError(`Source data length ${this.data.length} is not a multiple of (4 * width=${this.width})`)}};const Re={translate(e,t){this._ensureSurface(),this._ctx.translate(e,t)},rotate(e){this._ensureSurface(),this._ctx.rotate(e)},scale(e,t){this._ensureSurface(),this._ctx.scale(e,t)},transform(e,t,n,r,i,a){if(this._ensureSurface(),!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(a))return;let o=i,s=a,c=Math.hypot(e,t),l=Math.hypot(n,r),u=Math.atan2(t,e);this._ctx.translate(o,s),u!==0&&this._ctx.rotate(u),(c!==1||l!==1)&&this._ctx.scale(c,l)},setTransform(e,t,n,r,i,a){if(this._ensureSurface(),typeof e==`object`&&e){let t=e;this._ctx.identityMatrix(),this.transform(t.a??t.m11??1,t.b??t.m12??0,t.c??t.m21??0,t.d??t.m22??1,t.e??t.m41??0,t.f??t.m42??0)}else typeof e==`number`?(this._ctx.identityMatrix(),this.transform(e,t,n,r,i,a)):this._ctx.identityMatrix()},getTransform(){let e=this._ctx.userToDevice(0,0),t=this._ctx.userToDevice(1,0),n=this._ctx.userToDevice(0,1),r=e[0]??0,i=e[1]??0,a=(t[0]??0)-r,o=(t[1]??0)-i,s=(n[0]??0)-r,c=(n[1]??0)-i,l=globalThis.DOMMatrix;return typeof l==`function`?new l([a,o,s,c,r,i]):{a,b:o,c:s,d:c,e:r,f:i,m11:a,m12:o,m13:0,m14:0,m21:s,m22:c,m23:0,m24:0,m31:0,m32:0,m33:1,m34:0,m41:r,m42:i,m43:0,m44:1,is2D:!0,isIdentity:a===1&&o===0&&s===0&&c===1&&r===0&&i===0}},resetTransform(){this._ensureSurface(),this._ctx.identityMatrix()}};function installTransformMethods(e){Object.assign(e,Re)}const ze={beginPath(){this._ensureSurface(),this._ctx.newPath()},moveTo(e,t){this._ensureSurface(),this._ctx.moveTo(e,t)},lineTo(e,t){this._ensureSurface(),this._ctx.lineTo(e,t)},closePath(){this._ensureSurface(),this._ctx.closePath()},bezierCurveTo(e,t,n,r,i,a){this._ensureSurface(),this._ctx.curveTo(e,t,n,r,i,a)},quadraticCurveTo(e,t,n,r){this._ensureSurface();let i,a;this._ctx.hasCurrentPoint()?[i,a]=this._ctx.getCurrentPoint():(i=e,a=t);let{cp1x:o,cp1y:s,cp2x:c,cp2y:l}=quadraticToCubic(i,a,e,t,n,r);this._ctx.curveTo(o,s,c,l,n,r)},arc(e,t,n,r,i,a=!1){if(this._ensureSurface(),Math.abs(i-r)>=2*Math.PI){this._ctx.arc(e,t,n,0,2*Math.PI);return}a?this._ctx.arcNegative(e,t,n,r,i):this._ctx.arc(e,t,n,r,i)},arcTo(e,t,n,r,i){this._ensureSurface();let a,o;this._ctx.hasCurrentPoint()?[a,o]=this._ctx.getCurrentPoint():(a=e,o=t,this._ctx.moveTo(e,t)),cairoArcTo(this._ctx,a,o,e,t,n,r,i)},ellipse(e,t,n,r,i,a,o,s=!1){if(this._ensureSurface(),n<0||r<0)throw RangeError(`The radii provided are negative`);cairoEllipse(this._ctx,e,t,n,r,i,a,o,s)},rect(e,t,n,r){this._ensureSurface(),this._ctx.rectangle(e,t,n,r)},roundRect(e,t,n,r,i=0){this._ensureSurface(),cairoRoundRect(this._ctx,e,t,n,r,i)}};function installPathMethods(e){Object.assign(e,ze)}function getDrawImageSource(e){if(isPixbufImageSource(e)){let t=e._pixbuf;return{pixbuf:t,imgWidth:t.get_width(),imgHeight:t.get_height()}}if(isCanvasImageSource(e)){let t=e.width??0,n=e.height??0;if(!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0)return null;let r=e.getContext(`2d`);if(r&&typeof r._getSurface==`function`){let e=r._getSurface();e.flush();let i=getCanvasPixelBridge().imageFromSurface(e,0,0,t,n);if(i)return{pixbuf:i,imgWidth:t,imgHeight:n}}}return null}const Be={fill(e,n){this._ensureSurface(),this._applyCompositing(),this._applyFillStyle();let r;e instanceof Fe?(this._ctx.newPath(),e._replayOnCairo(this._ctx),r=n):r=e,this._ctx.setFillRule(r===`evenodd`?t.FillRule.EVEN_ODD:t.FillRule.WINDING),this._ctx.fillPreserve()},stroke(e){this._ensureSurface(),this._applyCompositing(),this._applyStrokeStyle(),this._applyLineStyle(),e instanceof Fe&&(this._ctx.newPath(),e._replayOnCairo(this._ctx)),this._ctx.strokePreserve()},fillRect(e,t,n,r){this._ensureSurface(),this._applyCompositing();let i=this._ctx.copyPath();this._hasShadow()&&this._renderShadow(()=>{this._ctx.newPath(),this._ctx.rectangle(e,t,n,r),this._ctx.fill()}),this._applyFillStyle(),this._ctx.newPath(),this._ctx.rectangle(e,t,n,r),this._ctx.fill(),this._ctx.newPath(),this._ctx.appendPath(i)},strokeRect(e,t,n,r){this._ensureSurface(),this._applyCompositing();let i=this._ctx.copyPath();this._hasShadow()&&this._renderShadow(()=>{this._ctx.newPath(),this._ctx.rectangle(e,t,n,r),this._ctx.stroke()}),this._applyStrokeStyle(),this._applyLineStyle(),this._ctx.newPath(),this._ctx.rectangle(e,t,n,r),this._ctx.stroke(),this._ctx.newPath(),this._ctx.appendPath(i)},clearRect(e,n,r,i){this._ensureSurface();let a=this._ctx.copyPath();this._ctx.save(),this._ctx.setOperator(t.Operator.CLEAR),this._ctx.newPath(),this._ctx.rectangle(e,n,r,i),this._ctx.fill(),this._ctx.restore(),this._ctx.newPath(),this._ctx.appendPath(a)},clip(e,n){this._ensureSurface();let r;e instanceof Fe?(this._ctx.newPath(),e._replayOnCairo(this._ctx),r=n):r=e,this._ctx.setFillRule(r===`evenodd`?t.FillRule.EVEN_ODD:t.FillRule.WINDING),this._ctx.clip()},isPointInPath(e,n,r,i){this._ensureSurface();let a,o,s;return e instanceof Fe?(this._ctx.newPath(),e._replayOnCairo(this._ctx),a=n,o=r,s=i):(a=e,o=n,s=r),this._ctx.setFillRule(s===`evenodd`?t.FillRule.EVEN_ODD:t.FillRule.WINDING),this._ctx.inFill(a,o)},isPointInStroke(e,t,n){return this._ensureSurface(),this._applyLineStyle(),e instanceof Fe?(this._ctx.newPath(),e._replayOnCairo(this._ctx),this._ctx.inStroke(t,n)):this._ctx.inStroke(e,t)},drawImage(e,n,r,i,a,o,s,c,l){this._ensureSurface(),this._applyCompositing();let u,d,f,p,m,h,g,_,v=getDrawImageSource(e);if(!v)return;let{pixbuf:y,imgWidth:b,imgHeight:x}=v;if(i===void 0?(u=0,d=0,f=b,p=x,m=n,h=r,g=b,_=x):o===void 0?(u=0,d=0,f=b,p=x,m=n,h=r,g=i,_=a):(u=n,d=r,f=i,p=a,m=o,h=s,g=c,_=l),!Number.isFinite(u)||!Number.isFinite(d)||!Number.isFinite(f)||!Number.isFinite(p)||!Number.isFinite(m)||!Number.isFinite(h)||!Number.isFinite(g)||!Number.isFinite(_)||f===0||p===0||g===0||_===0)return;this._ctx.save(),this._ctx.rectangle(m,h,g,_),this._ctx.clip(),this._ctx.translate(m,h),this._ctx.scale(g/f,_/p),this._ctx.translate(-u,-d),getCanvasPixelBridge().setSourceImage(this._ctx,y,0,0);let S=asCairoPattern(this._ctx.getSource?.());if(S){let e;e=this._state.imageSmoothingEnabled?this._state.imageSmoothingQuality===`high`?t.Filter.BEST:t.Filter.BILINEAR:t.Filter.NEAREST,S.setFilter(e)}this._state.globalAlpha<1?this._ctx.paintWithAlpha(this._state.globalAlpha):this._ctx.paint(),this._ctx.restore()}};function installDrawingMethods$1(e){Object.assign(e,Be)}__name$1(installDrawingMethods$1,`installDrawingMethods`);const Ve={createImageData(e,t){return typeof e==`number`?new OurImageData(Math.abs(e),Math.abs(t)):new OurImageData(e.width,e.height)},getImageData(e,t,n,r){this._ensureSurface(),this._surface.flush();let i=getCanvasPixelBridge().imageFromSurface(this._surface,e,t,n,r);if(!i)return new OurImageData(n,r);let a=i.get_pixels(),o=i.get_has_alpha(),s=i.get_rowstride(),c=i.get_n_channels(),l=new Uint8ClampedArray(n*r*4);for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=e*s+t*c,i=(e*n+t)*4;l[i]=a[r],l[i+1]=a[r+1],l[i+2]=a[r+2],l[i+3]=o?a[r+3]:255}return new OurImageData(l,n,r)},putImageData(e,n,r,i,a,o,s){this._ensureSurface();let c=i??0,l=a??0,u=o??e.width,d=s??e.height,f=e.data,p=e.width,m=new Uint8Array(u*d*4);for(let e=0;e<d;e++)for(let t=0;t<u;t++){let n=((l+e)*p+(c+t))*4,r=(e*u+t)*4;m[r]=f[n],m[r+1]=f[n+1],m[r+2]=f[n+2],m[r+3]=f[n+3]}this._ctx.save(),this._ctx.setOperator(t.Operator.SOURCE),getCanvasPixelBridge().setSourcePixels(this._ctx,m,u,d,n+c,r+l),this._ctx.rectangle(n+c,r+l,u,d),this._ctx.fill(),this._ctx.restore()}};function installPixelMethods(e){Object.assign(e,Ve)}const He=e(import.meta.url);let Ue;function load$16(){return Ue===void 0&&(Ue=He(`@gjsify/node-gi/gi`).requireGi(`Pango`)),Ue}__name$1(load$16,`load`);var We=new Proxy(Object.create(null),{get(e,t){return load$16()[t]},has(e,t){return t in load$16()}});const Ge=e(import.meta.url);let Ke;function load$15(){return Ke===void 0&&(Ke=Ge(`@gjsify/node-gi/gi`).requireGi(`PangoCairo`)),Ke}__name$1(load$15,`load`);var qe=new Proxy(Object.create(null),{get(e,t){return load$15()[t]},has(e,t){return t in load$15()}});function parseFontToDescription(e){let t=e.match(/^\s*(italic|oblique|normal)?\s*(small-caps|normal)?\s*(bold|bolder|lighter|[1-9]00|normal)?\s*(\d+(?:\.\d+)?)(px|pt|em|rem|%)?\s*(?:\/\S+)?\s*(.+)?$/i);if(!t)return We.font_description_from_string(e);let n=t[1]||``,r=t[3]||``,i=parseFloat(t[4])||10,a=(t[5]||`px`).toLowerCase(),o=(t[6]||`sans-serif`).replace(/['"]/g,``).trim();a===`pt`?i=i*96/72:a===`em`||a===`rem`?i*=16:a===`%`&&(i=i/100*16);let s=o;n===`italic`?s+=` Italic`:n===`oblique`&&(s+=` Oblique`),r===`bold`||r===`bolder`||parseInt(r)>=600?s+=` Bold`:(r===`lighter`||parseInt(r)>0&&parseInt(r)<=300)&&(s+=` Light`);let c=We.font_description_from_string(s);return c.set_absolute_size(i*We.SCALE),c}function createTextLayout(e,t){let n=qe.create_layout(e._ctx);n.set_text(t,-1),n.get_context().set_base_dir(We.Direction.LTR),n.context_changed();let r=parseFontToDescription(e._state.font);return n.set_font_description(r),n}function getTextAlignOffset(e,t){let[,n]=t.get_pixel_extents(),r=n.width;switch(e._state.textAlign){case`center`:return-r/2;case`right`:case`end`:return-r;default:return 0}}function getTextBaselineOffset(e,t){let n=t.get_font_description()||parseFontToDescription(e._state.font),r=t.get_context().get_metrics(n,null),i=r.get_ascent()/We.SCALE,a=r.get_descent()/We.SCALE,o=i+a;switch(e._state.textBaseline){case`top`:return 0;case`hanging`:return-(i*.2);case`middle`:return-(o/2);case`alphabetic`:return-i;case`ideographic`:return-(i+a*.5);case`bottom`:return-o;default:return-i}}const Je={fillText(e,n,r,i){this._ensureSurface(),this._applyCompositing();let a=createTextLayout(this,e),o=getTextAlignOffset(this,a),s=getTextBaselineOffset(this,a);if(this._hasShadow()){let e=parseColor(this._state.shadowColor);if(e){let[i,c]=this._deviceToUserDistance(this._state.shadowOffsetX,this._state.shadowOffsetY),l=this._state.shadowBlur,u;if(l>0){let[t]=this._deviceToUserDistance(l,0),[,n]=this._deviceToUserDistance(0,l);u=[[i,c,e.a],[i+t,c,e.a*.5],[i-t,c,e.a*.5],[i,c+n,e.a*.5],[i,c-n,e.a*.5]]}else u=[[i,c,e.a]];let d=this._state.imageSmoothingEnabled?t.Antialias.DEFAULT:t.Antialias.NONE;for(let[t,i,c]of u)this._ctx.save(),this._ctx.setAntialias(d),this._ctx.setSourceRGBA(e.r,e.g,e.b,c),this._ctx.moveTo(n+o+t,r+s+i),qe.show_layout(this._ctx,a),this._ctx.restore()}}this._applyFillStyle(),this._ctx.save(),this._ctx.setAntialias(this._state.imageSmoothingEnabled?t.Antialias.DEFAULT:t.Antialias.NONE),this._ctx.moveTo(n+o,r+s),qe.show_layout(this._ctx,a),this._ctx.restore()},strokeText(e,n,r,i){this._ensureSurface(),this._applyCompositing(),this._applyStrokeStyle(),this._applyLineStyle();let a=createTextLayout(this,e),o=getTextAlignOffset(this,a),s=getTextBaselineOffset(this,a);this._ctx.save(),this._ctx.setAntialias(this._state.imageSmoothingEnabled?t.Antialias.DEFAULT:t.Antialias.NONE),this._ctx.moveTo(n+o,r+s),qe.layout_path(this._ctx,a),this._ctx.stroke(),this._ctx.restore()},measureText(e){this._ensureSurface();let t=createTextLayout(this,e),[n,r]=t.get_pixel_extents(),i=t.get_baseline()/We.SCALE,a=Math.max(0,i-n.y),o=Math.max(0,n.y+n.height-i),s=t.get_font_description()||parseFontToDescription(this._state.font),c=t.get_context().get_metrics(s,null),l=c.get_ascent()/We.SCALE,u=c.get_descent()/We.SCALE;return{width:r.width,actualBoundingBoxAscent:a,actualBoundingBoxDescent:o,actualBoundingBoxLeft:Math.max(0,-n.x),actualBoundingBoxRight:n.x+n.width,fontBoundingBoxAscent:l,fontBoundingBoxDescent:u,alphabeticBaseline:0,emHeightAscent:l,emHeightDescent:u,hangingBaseline:l*.8,ideographicBaseline:-u}}};function installTextMethods(e){Object.assign(e,Je)}const Ye={createLinearGradient(e,t,n,r){return new CanvasGradient(`linear`,e,t,n,r)},createRadialGradient(e,t,n,r,i,a){return new CanvasGradient(`radial`,e,t,r,i,n,a)},createPattern(e,t){return Le.create(e,t)}};function installFactoryMethods(e){Object.assign(e,Ye)}function installAllContextMethods$1(e){installTransformMethods(e),installPathMethods(e),installDrawingMethods$1(e),installPixelMethods(e),installTextMethods(e),installFactoryMethods(e)}__name$1(installAllContextMethods$1,`installAllContextMethods`);function createDefaultState(){return{fillStyle:`#000000`,fillColor:{...je},strokeStyle:`#000000`,strokeColor:{...je},lineWidth:1,lineCap:`butt`,lineJoin:`miter`,miterLimit:10,lineDash:[],lineDashOffset:0,globalAlpha:1,globalCompositeOperation:`source-over`,shadowColor:`rgba(0, 0, 0, 0)`,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,font:`10px sans-serif`,textAlign:`start`,textBaseline:`alphabetic`,direction:`ltr`,imageSmoothingEnabled:!0,imageSmoothingQuality:`low`}}function cloneState(e){return{...e,fillColor:{...e.fillColor},strokeColor:{...e.strokeColor},lineDash:[...e.lineDash]}}const Xe=e(import.meta.url);let Ze;function load$14(){return Ze===void 0&&(Ze=Xe(`@gjsify/node-gi/gi`).requireGi(`Gio`)),Ze}__name$1(load$14,`load`);var Qe=new Proxy(Object.create(null),{get(e,t){return load$14()[t]},has(e,t){return t in load$14()}});const $e=e(import.meta.url);let et;function load$13(){return et===void 0&&(et=$e(`@gjsify/node-gi/gi`).requireGi(`GLib`)),et}__name$1(load$13,`load`);var tt=new Proxy(Object.create(null),{get(e,t){return load$13()[t]},has(e,t){return t in load$13()}}),CanvasRenderingContext2D=class{constructor(e,n){this._stateStack=[],this.canvas=e,this._surfaceWidth=e.width||300,this._surfaceHeight=e.height||150,this._surface=new t.ImageSurface(t.Format.ARGB32,this._surfaceWidth,this._surfaceHeight),this._ctx=new t.Context(this._surface),this._state=createDefaultState()}_ensureSurface(){let e=this.canvas.width||300,n=this.canvas.height||150;(e!==this._surfaceWidth||n!==this._surfaceHeight)&&(this._ctx.$dispose(),this._surface.finish(),this._surfaceWidth=e,this._surfaceHeight=n,this._surface=new t.ImageSurface(t.Format.ARGB32,e,n),this._ctx=new t.Context(this._surface),this._stateStack=[])}_resetState(){this._state=createDefaultState(),this._stateStack=[]}_applyFillStyle(){let e=this._state.fillStyle;if(typeof e==`string`){let e=this._state.fillColor,t=e.a*this._state.globalAlpha;this._ctx.setSourceRGBA(e.r,e.g,e.b,t)}else e instanceof CanvasGradient?this._ctx.setSource(e._getCairoPattern()):e instanceof Le&&(this._ctx.setSource(e._getCairoPattern()),this._applyPatternFilter())}_applyStrokeStyle(){let e=this._state.strokeStyle;if(typeof e==`string`){let e=this._state.strokeColor,t=e.a*this._state.globalAlpha;this._ctx.setSourceRGBA(e.r,e.g,e.b,t)}else e instanceof CanvasGradient?this._ctx.setSource(e._getCairoPattern()):e instanceof Le&&(this._ctx.setSource(e._getCairoPattern()),this._applyPatternFilter())}_applyPatternFilter(){let e=asCairoPattern(this._ctx.getSource?.());if(!e)return;let n;n=this._state.imageSmoothingEnabled?this._state.imageSmoothingQuality===`high`?t.Filter.BEST:t.Filter.BILINEAR:t.Filter.NEAREST,e.setFilter(n)}_applyLineStyle(){this._ctx.setLineWidth(this._state.lineWidth),this._ctx.setLineCap(Ne[this._state.lineCap]),this._ctx.setLineJoin(Pe[this._state.lineJoin]),this._ctx.setMiterLimit(this._state.miterLimit),this._ctx.setDash(this._state.lineDash,this._state.lineDashOffset)}_applyCompositing(){let e=Me[this._state.globalCompositeOperation];e!==void 0&&this._ctx.setOperator(e)}_getSurface(){return this._surface}_hasShadow(){if(this._state.shadowBlur===0&&this._state.shadowOffsetX===0&&this._state.shadowOffsetY===0)return!1;let e=parseColor(this._state.shadowColor);return e!==null&&e.a>0}_deviceToUserDistance(e,t){let n=this._ctx.userToDevice(0,0),r=this._ctx.userToDevice(1,0),i=this._ctx.userToDevice(0,1),a=(r[0]??0)-(n[0]??0),o=(r[1]??0)-(n[1]??0),s=(i[0]??0)-(n[0]??0),c=(i[1]??0)-(n[1]??0),l=a*c-o*s;return Math.abs(l)<1e-10?[e,t]:[(c*e-s*t)/l,(-o*e+a*t)/l]}_renderShadow(e){}save(){this._ensureSurface(),this._stateStack.push(cloneState(this._state)),this._ctx.save()}restore(){this._ensureSurface();let e=this._stateStack.pop();e&&(this._state=e,this._ctx.restore())}get fillStyle(){return this._state.fillStyle}set fillStyle(e){if(typeof e==`string`){let t=parseColor(e);t&&(this._state.fillStyle=e,this._state.fillColor=t)}else this._state.fillStyle=e}get strokeStyle(){return this._state.strokeStyle}set strokeStyle(e){if(typeof e==`string`){let t=parseColor(e);t&&(this._state.strokeStyle=e,this._state.strokeColor=t)}else this._state.strokeStyle=e}get lineWidth(){return this._state.lineWidth}set lineWidth(e){e>0&&isFinite(e)&&(this._state.lineWidth=e)}get lineCap(){return this._state.lineCap}set lineCap(e){(e===`butt`||e===`round`||e===`square`)&&(this._state.lineCap=e)}get lineJoin(){return this._state.lineJoin}set lineJoin(e){(e===`miter`||e===`round`||e===`bevel`)&&(this._state.lineJoin=e)}get miterLimit(){return this._state.miterLimit}set miterLimit(e){e>0&&isFinite(e)&&(this._state.miterLimit=e)}get globalAlpha(){return this._state.globalAlpha}set globalAlpha(e){e>=0&&e<=1&&isFinite(e)&&(this._state.globalAlpha=e)}get globalCompositeOperation(){return this._state.globalCompositeOperation}set globalCompositeOperation(e){Me[e]!==void 0&&(this._state.globalCompositeOperation=e)}get imageSmoothingEnabled(){return this._state.imageSmoothingEnabled}set imageSmoothingEnabled(e){this._state.imageSmoothingEnabled=!!e}get imageSmoothingQuality(){return this._state.imageSmoothingQuality}set imageSmoothingQuality(e){(e===`low`||e===`medium`||e===`high`)&&(this._state.imageSmoothingQuality=e)}setLineDash(e){e.some(e=>e<0||!isFinite(e))||(this._state.lineDash=[...e])}getLineDash(){return[...this._state.lineDash]}get lineDashOffset(){return this._state.lineDashOffset}set lineDashOffset(e){isFinite(e)&&(this._state.lineDashOffset=e)}get shadowColor(){return this._state.shadowColor}set shadowColor(e){this._state.shadowColor=e}get shadowBlur(){return this._state.shadowBlur}set shadowBlur(e){e>=0&&isFinite(e)&&(this._state.shadowBlur=e)}get shadowOffsetX(){return this._state.shadowOffsetX}set shadowOffsetX(e){isFinite(e)&&(this._state.shadowOffsetX=e)}get shadowOffsetY(){return this._state.shadowOffsetY}set shadowOffsetY(e){isFinite(e)&&(this._state.shadowOffsetY=e)}get font(){return this._state.font}set font(e){this._state.font=e}get textAlign(){return this._state.textAlign}set textAlign(e){this._state.textAlign=e}get textBaseline(){return this._state.textBaseline}set textBaseline(e){this._state.textBaseline=e}get direction(){return this._state.direction}set direction(e){this._state.direction=e}_toDataURL(e,t){this._surface.flush();let[,n]=tt.file_open_tmp(`canvas-XXXXXX.png`);try{this._surface.writeToPNG(n);let[,e]=Qe.File.new_for_path(n).load_contents(null);return`data:image/png;base64,${tt.base64_encode(e)}`}finally{try{tt.unlink(n)}catch{}}}_dispose(){this._ctx.$dispose(),this._surface.finish()}};installAllContextMethods$1(CanvasRenderingContext2D.prototype);const nt=e(import.meta.url);let rt;function load$12(){return rt===void 0&&(rt=nt(`@gjsify/node-gi/gi`).requireGi(`Gdk`,`4.0`)),rt}__name$1(load$12,`load`);var it=new Proxy(Object.create(null),{get(e,t){return load$12()[t]},has(e,t){return t in load$12()}});const at=e(import.meta.url);let ot;function load$11(){return ot===void 0&&(ot=at(`@gjsify/node-gi/gi`).requireGi(`GdkPixbuf`)),ot}__name$1(load$11,`load`);var st=new Proxy(Object.create(null),{get(e,t){return load$11()[t]},has(e,t){return t in load$11()}});setCanvasPixelBridge({imageFromSurface(e,t,n,r,i){return it.pixbuf_get_from_surface(e,t,n,r,i)},setSourceImage(e,t,n,r){it.cairo_set_source_pixbuf(e,t,n,r)},setSourcePixels(e,t,n,r,i,a){let o=st.Pixbuf.new_from_bytes(t,st.Colorspace.RGB,!0,8,n,r,n*4);it.cairo_set_source_pixbuf(e,o,i,a)}}),defineGlobal(`HTMLCanvasElement`,P),defineGlobal(`CanvasRenderingContext2D`,CanvasRenderingContext2D),defineGlobal(`DOMMatrix`,Oe),defineGlobal(`DOMMatrixReadOnly`,ke);const ct=Symbol.for(`gjsify_canvas2d_context`);P.registerContextFactory(`2d`,(e,t)=>{let n=e,r=n[ct];if(r)return r;let i=new CanvasRenderingContext2D(e,t);return n[ct]=i,i});var CharacterData=class extends Se{constructor(e=``){super(),this[y]=j.TEXT_NODE,this._data=e}get data(){return this._data}set data(e){this._data=e}get textContent(){return this._data}set textContent(e){this._data=e}get nodeValue(){return this._data}set nodeValue(e){this._data=e}get length(){return this._data.length}appendData(e){this._data+=e}deleteData(e,t){this._data=this._data.substring(0,e)+this._data.substring(e+t)}insertData(e,t){this._data=this._data.substring(0,e)+t+this._data.substring(e)}replaceData(e,t,n){this._data=this._data.substring(0,e)+n+this._data.substring(e+t)}substringData(e,t){return this._data.substring(e,e+t)}cloneNode(e=!1){return new this.constructor(this._data)}get[Symbol.toStringTag](){return`CharacterData`}},lt=class Comment extends CharacterData{constructor(e=``){super(e),this[y]=j.COMMENT_NODE}get nodeName(){return`#comment`}cloneNode(e=!1){return new Comment(this.data)}get[Symbol.toStringTag](){return`Comment`}},ut=class Text extends CharacterData{constructor(e=``){super(e),this[y]=j.TEXT_NODE}get nodeName(){return`#text`}get wholeText(){let e=this.data,t=this.previousSibling;for(;t&&t instanceof Text;)e=t.data+e,t=t.previousSibling;let n=this.nextSibling;for(;n&&n instanceof Text;)e+=n.data,n=n.nextSibling;return e}splitText(e){let t=this.data.substring(e);this.data=this.data.substring(0,e);let n=new Text(t);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}cloneNode(e=!1){return new Text(this.data)}get[Symbol.toStringTag](){return`Text`}},dt=class DocumentFragment extends Se{constructor(){super(),this[y]=j.DOCUMENT_FRAGMENT_NODE}get nodeName(){return`#document-fragment`}get children(){return this[S]}get childElementCount(){return this[S].length}get firstElementChild(){return this[S][0]??null}get lastElementChild(){let e=this[S];return e[e.length-1]??null}get textContent(){let e=``;for(let t of this.childNodes)t.textContent!==null&&(e+=t.textContent);return e}set textContent(e){for(;this.firstChild;)this.removeChild(this.firstChild);e&&this.appendChild(new ut(e))}append(...e){for(let t of e)typeof t==`string`?this.appendChild(new ut(t)):this.appendChild(t)}prepend(...e){let t=this.firstChild;for(let n of e)typeof n==`string`?this.insertBefore(new ut(n),t):this.insertBefore(n,t)}replaceChildren(...e){for(;this.firstChild;)this.removeChild(this.firstChild);this.append(...e)}getElementById(e){for(let t of this.children){if(t.id===e)return t;let n=this._findById(t,e);if(n)return n}return null}_findById(e,t){for(let n of e.children){if(n.id===t)return n;let e=this._findById(n,t);if(e)return e}return null}cloneNode(e=!1){let t=new DocumentFragment;if(e)for(let e of this.childNodes)t.appendChild(e.cloneNode(!0));return t}get[Symbol.toStringTag](){return`DocumentFragment`}};const ft=e(import.meta.url);let pt;function load$10(){return pt===void 0&&(pt=ft(`@gjsify/node-gi/gi`).requireGi(`GLib`,`2.0`)),pt}__name$1(load$10,`load`);var mt=new Proxy(Object.create(null),{get(e,t){return load$10()[t]},has(e,t){return t in load$10()}}),ht=mt;const gt=e(import.meta.url);let _t;function load$9(){return _t===void 0&&(_t=gt(`@gjsify/node-gi/gi`).requireGi(`Gio`,`2.0`)),_t}__name$1(load$9,`load`);var vt=new Proxy(Object.create(null),{get(e,t){return load$9()[t]},has(e,t){return t in load$9()}}),yt=vt;const bt=e(import.meta.url);let xt;function load$8(){return xt===void 0&&(xt=bt(`@gjsify/node-gi/gi`).requireGi(`GdkPixbuf`,`2.0`)),xt}__name$1(load$8,`load`);var St=new Proxy(Object.create(null),{get(e,t){return load$8()[t]},has(e,t){return t in load$8()}}),Ct=St,HTMLImageElement$1=class extends HTMLElement{static{__name$1(this,`HTMLImageElement`)}constructor(){super(),this._complete=!1,this._naturalHeight=0,this._naturalWidth=0,this[w]=`IMG`,this[T]=`img`,this[E]=Ce.html}get complete(){return this._complete}get naturalHeight(){return this._naturalHeight}get naturalWidth(){return this._naturalWidth}get currentSrc(){return this.src}get x(){return 0}get y(){return 0}get alt(){return this.getAttribute(`alt`)??``}set alt(e){this.setAttribute(`alt`,e)}get crossOrigin(){return this.getAttribute(`crossorigin`)}set crossOrigin(e){e===null?this.removeAttribute(`crossorigin`):this.setAttribute(`crossorigin`,e)}get decoding(){return this.getAttribute(`decoding`)??`auto`}set decoding(e){this.setAttribute(`decoding`,e)}get loading(){let e=this.getAttribute(`loading`);return e===`lazy`||e===`eager`?e:`auto`}set loading(e){this.setAttribute(`loading`,e)}get referrerPolicy(){return this.getAttribute(`referrerpolicy`)??``}set referrerPolicy(e){this.setAttribute(`referrerpolicy`,e)}get sizes(){return this.getAttribute(`sizes`)??``}set sizes(e){this.setAttribute(`sizes`,e)}get src(){return this.getAttribute(`src`)??``}set src(e){this.setAttribute(`src`,e);let t=globalThis.__GJSIFY_DEBUG_IMG===!0;if(e.startsWith(`data:`)){let n=e.indexOf(`,`);if(n===-1){this._complete=!0,this.dispatchEvent(new Event(`error`));return}let r=e.slice(5,n),i=e.slice(n+1),a=r.includes(`;base64`);try{let e;e=a?ht.base64_decode(i):new TextEncoder().encode(decodeURIComponent(i));let n=ht.Bytes.new(e),r=yt.MemoryInputStream.new_from_bytes(n);this._pixbuf=Ct.Pixbuf.new_from_stream(r,null),this._naturalWidth=this._pixbuf.get_width(),this._naturalHeight=this._pixbuf.get_height(),this._complete=!0,t&&console.log(`[img] ok data: (${this._naturalWidth}x${this._naturalHeight})`),this.dispatchEvent(new Event(`load`))}catch(e){t&&console.warn(`[img] error data:: ${e instanceof Error?e.message:String(e)}`),this._complete=!0,this.dispatchEvent(new Event(`error`))}return}let r;if(e.startsWith(`file://`))r=ht.filename_from_uri(e)[0];else if(e.startsWith(`http://`)||e.startsWith(`https://`)){this._complete=!0,this.dispatchEvent(new Event(`error`));return}else{let t=ht.path_get_dirname(n.programInvocationName);r=ht.build_filenamev([t,e])}try{t&&console.log(`[img] load ${r}`),this._pixbuf=Ct.Pixbuf.new_from_file(r),this._naturalWidth=this._pixbuf.get_width(),this._naturalHeight=this._pixbuf.get_height(),this._complete=!0,t&&console.log(`[img] ok ${r} (${this._naturalWidth}x${this._naturalHeight})`),this.dispatchEvent(new Event(`load`))}catch(e){t&&console.warn(`[img] error ${r}: ${e instanceof Error?e.message:String(e)}`),this._complete=!0,this.dispatchEvent(new Event(`error`))}}get srcset(){return this.getAttribute(`srcset`)??``}set srcset(e){this.setAttribute(`srcset`,e)}get useMap(){return this.getAttribute(`usemap`)??``}set useMap(e){this.setAttribute(`usemap`,e)}get height(){if(this._pixbuf)return this._pixbuf.get_height();let e=this.getAttribute(`height`);return e===null?0:Number(e)}set height(e){this.setAttribute(`height`,String(e))}get width(){if(this._pixbuf)return this._pixbuf.get_width();let e=this.getAttribute(`width`);return e===null?0:Number(e)}set width(e){this.setAttribute(`width`,String(e))}get isMap(){return this.hasAttribute(`ismap`)}set isMap(e){e?this.setAttribute(`ismap`,``):this.removeAttribute(`ismap`)}decode(){return Promise.resolve()}cloneNode(e=!1){return super.cloneNode(e)}getImageData(){if(!this._pixbuf)return null;let e=this._pixbuf.get_has_alpha()?this._pixbuf:this._pixbuf.add_alpha(!1,0,0,0)??this._pixbuf;return{colorSpace:`srgb`,data:new Uint8ClampedArray(e.get_pixels()),height:e.get_height(),width:e.get_width()}}isPixbuf(){return!!this._pixbuf}get[Symbol.toStringTag](){return`HTMLImageElement`}},HTMLMediaElement=class extends HTMLElement{constructor(...e){super(...e),this._src=``,this._srcObject=null,this.currentTime=0,this.duration=NaN,this.paused=!0,this.ended=!1,this.volume=1,this.muted=!1,this.defaultMuted=!1,this.loop=!1,this.autoplay=!1,this.preload=``,this.playbackRate=1,this.defaultPlaybackRate=1,this.readyState=0,this.networkState=0}get buffered(){return{length:0,start:()=>0,end:()=>0}}get seekable(){return{length:0,start:()=>0,end:()=>0}}get played(){return{length:0,start:()=>0,end:()=>0}}get src(){return this._src}set src(e){this._src=e,this._srcObject=null,this.dispatchEvent(new Event(`srcchange`))}get srcObject(){return this._srcObject}set srcObject(e){this._srcObject=e,this._src=``,this.dispatchEvent(new Event(`srcobjectchange`))}play(){return this.paused=!1,this.ended=!1,this.dispatchEvent(new Event(`play`)),Promise.resolve()}pause(){this.paused=!0,this.dispatchEvent(new Event(`pause`))}load(){this.readyState=0,this.networkState=2,this.dispatchEvent(new Event(`loadstart`))}canPlayType(e){return``}static{this.HAVE_NOTHING=0}static{this.HAVE_METADATA=1}static{this.HAVE_CURRENT_DATA=2}static{this.HAVE_FUTURE_DATA=3}static{this.HAVE_ENOUGH_DATA=4}static{this.NETWORK_EMPTY=0}static{this.NETWORK_IDLE=1}static{this.NETWORK_LOADING=2}static{this.NETWORK_NO_SOURCE=3}get[Symbol.toStringTag](){return`HTMLMediaElement`}};const wt=1e9;function secondsToGstTime(e){return BigInt(Math.round(e*wt))}function gstTimeToSeconds(e){return Number(e)/wt}var HTMLVideoElement$1=class extends HTMLMediaElement{static{__name$1(this,`HTMLVideoElement`)}constructor(){super(),this._pipeline=null,this._videoWidth=0,this._videoHeight=0,this.poster=``,this[w]=`VIDEO`,this[T]=`video`,this[E]=Ce.html;let e=this;Object.defineProperty(this,"paused",{get(){if(!e._pipeline)return!0;let[,t]=e._pipeline.get_state(0n);return t!==4},configurable:!0,enumerable:!0}),Object.defineProperty(this,"currentTime",{get(){if(!e._pipeline)return 0;let[t,n]=e._pipeline.query_position(3);return t?gstTimeToSeconds(n):0},set(t){e._pipeline?.seek(1,3,5,1,secondsToGstTime(t),0,-1n)},configurable:!0,enumerable:!0}),Object.defineProperty(this,"duration",{get(){if(!e._pipeline)return NaN;let[t,n]=e._pipeline.query_duration(3);return t&&Number(n)>0?gstTimeToSeconds(n):NaN},configurable:!0,enumerable:!0}),Object.defineProperty(this,"volume",{get(){return e._playbin()?.volume??1},set(t){let n=e._playbin();n&&(n.volume=Math.max(0,Math.min(1,t)))},configurable:!0,enumerable:!0}),Object.defineProperty(this,"muted",{get(){return e._playbin()?.mute??!1},set(t){let n=e._playbin();n&&(n.mute=t)},configurable:!0,enumerable:!0})}async play(){this._pipeline?.set_state(4),this.dispatchEvent(new Event(`play`)),this.dispatchEvent(new Event(`playing`))}pause(){this._pipeline?.set_state(3),this.dispatchEvent(new Event(`pause`))}get videoWidth(){return this._videoWidth}set videoWidth(e){this._videoWidth=e}get videoHeight(){return this._videoHeight}set videoHeight(e){this._videoHeight=e}get[Symbol.toStringTag](){return`HTMLVideoElement`}_playbin(){return this._pipeline?.get_by_name(`playbin`)??null}};const Tt=new class Document extends Se{static{this._elementFactories=new Map}constructor(){super(),this.body=new HTMLElement,this.head=new HTMLElement,this.documentElement=new HTMLElement,this.appendChild(this.documentElement),this.documentElement.appendChild(this.body)}static registerElementFactory(e,t){Document._elementFactories.set(e.toLowerCase(),t)}createElementNS(e,t){let n=t.toLowerCase();switch(n){case`img`:return new HTMLImageElement$1;case`video`:return new HTMLVideoElement$1;case`canvas`:return new P;default:{let e=Document._elementFactories.get(n);return e?e():new HTMLElement}}}createElement(e){return this.createElementNS(`http://www.w3.org/1999/xhtml`,e)}createTextNode(e){return new ut(e)}createComment(e){return new lt(e)}createDocumentFragment(){return new dt}createEvent(e){return new Event(e)}getElementById(e){return this._findById(this.body,e)}_findById(e,t){if(e.id===t)return e;for(let n of e.children){let e=this._findById(n,t);if(e)return e}return null}get[Symbol.toStringTag](){return`Document`}};var DOMTokenList=class{constructor(e,t){this._ownerElement=e,this._attributeName=t}_getTokens(){let e=this._ownerElement.getAttribute(this._attributeName);return e?e.split(/\s+/).filter(e=>e.length>0):[]}_setTokens(e){let t=e.join(` `);t?this._ownerElement.setAttribute(this._attributeName,t):this._ownerElement.removeAttribute(this._attributeName)}get length(){return this._getTokens().length}get value(){return this._ownerElement.getAttribute(this._attributeName)??``}set value(e){e?this._ownerElement.setAttribute(this._attributeName,e):this._ownerElement.removeAttribute(this._attributeName)}item(e){let t=this._getTokens();return e>=0&&e<t.length?t[e]:null}contains(e){return this._getTokens().includes(e)}add(...e){let t=this._getTokens();for(let n of e)n&&!t.includes(n)&&t.push(n);this._setTokens(t)}remove(...e){let t=this._getTokens().filter(t=>!e.includes(t));this._setTokens(t)}toggle(e,t){let n=this.contains(e);return t===void 0?n?(this.remove(e),!1):(this.add(e),!0):t?(this.add(e),!0):(this.remove(e),!1)}replace(e,t){let n=this._getTokens(),r=n.indexOf(e);return r===-1?!1:(n[r]=t,this._setTokens(n),!0)}supports(e){return!0}forEach(e){let t=this._getTokens();for(let n=0;n<t.length;n++)e(t[n],n,this)}keys(){return this._getTokens().keys()}values(){return this._getTokens().values()}entries(){return this._getTokens().entries()}[Symbol.iterator](){return this._getTokens().values()}toString(){return this.value}get[Symbol.toStringTag](){return`DOMTokenList`}};function installWindowEventBus(e){if(e.__gjsify_globalEventTarget)return e.__gjsify_globalEventTarget;let t=new EventTarget,n=typeof e.addEventListener==`function`?e.addEventListener.bind(e):null,r=typeof e.removeEventListener==`function`?e.removeEventListener.bind(e):null;e.__gjsify_globalEventTarget=t;let define=(t,n)=>Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0});return define(`addEventListener`,(e,r,i)=>{t.addEventListener(e,r,i),n?.(e,r,i)}),define(`removeEventListener`,(e,n,i)=>{t.removeEventListener(e,n,i),r?.(e,n,i)}),define(`dispatchEvent`,e=>t.dispatchEvent(e)),t}defineGlobal(`Text`,ut),defineGlobal(`Comment`,lt),defineGlobal(`DocumentFragment`,dt),defineGlobal(`DOMTokenList`,DOMTokenList),defineGlobal(`document`,Tt),defineGlobalIfMissing(`self`,globalThis);var Window=class{};defineGlobalIfMissing(`Window`,Window),defineGlobalIfMissing(`window`,globalThis),defineGlobalIfMissing(`focus`,()=>{}),defineGlobalIfMissing(`blur`,()=>{}),installWindowEventBus(globalThis),defineGlobalIfMissing(`devicePixelRatio`,1),defineGlobalIfMissing(`scrollX`,0),defineGlobalIfMissing(`scrollY`,0),defineGlobalIfMissing(`pageXOffset`,0),defineGlobalIfMissing(`pageYOffset`,0),defineGlobalIfMissing(`alert`,(...e)=>console.error(`alert:`,...e)),globalThis.top===void 0&&Object.defineProperty(globalThis,"top",{get:()=>globalThis,configurable:!0});var Et=__exportAll$1({default:()=>kt});function load$7(){return Ot===void 0&&(Ot=Dt(`@gjsify/node-gi/gi`).requireGi(`PangoCairo`,`1.0`)),Ot}var Dt,Ot,kt,At=__esmMin((()=>{Dt=e(import.meta.url),__name$1(load$7,`load`),kt=new Proxy(Object.create(null),{get(e,t){return load$7()[t]},has(e,t){return t in load$7()}})})),FontFace=class{constructor(e,t,n){this.status=`unloaded`,this.display=`auto`,this.style=`normal`,this.weight=`normal`,this.stretch=`normal`,this.unicodeRange=`U+0-10FFFF`,this.variant=`normal`,this.featureSettings=`normal`,this.family=e,this.source=typeof t==`string`?t:`[binary]`,this.loaded=Promise.resolve(this)}_extractFilePath(){let e=this.source.match(/url\s*\(\s*["']?(file:\/\/\/[^"')]+)["']?\s*\)/i);return e?e[1].replace(/^file:\/\//,``):null}async load(){this.status=`loading`;let e=this._extractFilePath();if(e)try{let{default:t}=await Promise.resolve().then(()=>(At(),Et));t.font_map_get_default().add_font_file(e)}catch{}return this.status=`loaded`,this}},FontFaceSet=class{constructor(){this.status=`loaded`,this.ready=Promise.resolve(this),this._faces=new Set}addEventListener(e,t){}removeEventListener(e,t){}dispatchEvent(e){return!0}add(e){return this._faces.add(e),this}delete(e){return this._faces.delete(e)}clear(){this._faces.clear()}has(e){return this._faces.has(e)}check(e,t){return!1}load(e,t){return Promise.resolve([])}forEach(e){this._faces.forEach(t=>e(t,t,this))}values(){return this._faces.values()}keys(){return this._faces.values()}entries(){return Array.from(this._faces).map(e=>[e,e])[Symbol.iterator]()}[Symbol.iterator](){return this._faces[Symbol.iterator]()}get size(){return this._faces.size}};const jt=globalThis;defineGlobalIfMissing(`FontFace`,FontFace),jt.FontFace===void 0&&(jt.FontFace=FontFace);const Mt=jt.document;Mt&&Mt.fonts===void 0&&Object.defineProperty(Mt,"fonts",{value:new FontFaceSet,configurable:!0,writable:!0});var Image=class extends HTMLImageElement$1{constructor(e=null,t=null){super(),e!==null&&(this.width=e),t!==null&&(this.height=t)}};defineGlobal(`HTMLImageElement`,HTMLImageElement$1),defineGlobal(`Image`,Image),defineGlobalIfMissing(`location`,{href:`file://`,origin:`file://`,protocol:`file:`,host:``,hostname:``,port:``,pathname:`/`,search:``,hash:``,assign(e){},replace(e){},reload(){},toString(){return this.href},ancestorOrigins:{length:0,item:()=>null,contains:()=>!1,[Symbol.iterator]:function*(){}}});var MediaQueryList=class extends EventTarget{constructor(e){super(),this.onchange=null,this.media=e,this.matches=!1}addListener(e){}removeListener(e){}};function matchMedia(e){return new MediaQueryList(e)}defineGlobalIfMissing(`matchMedia`,matchMedia),globalThis.navigator===void 0&&(globalThis.navigator={});var MutationObserver=class{constructor(e){}observe(e,t){}disconnect(){}takeRecords(){return[]}};const Nt=new Set;let Pt=!1;function scheduleFlush(){Pt||(Pt=!0,queueMicrotask(()=>{Pt=!1;let e=Array.from(Nt);Nt.clear();for(let t of e)t._deliver()}))}var ResizeObserver=class{constructor(e){this._observed=new Map,this._pending=new Map,this._callback=e}observe(e,t){if(this._observed.has(e))return;let n=e._onResize((t,n)=>{this._enqueue(e,t,n)});this._observed.set(e,n),queueMicrotask(()=>{if(!this._observed.has(e))return;let t=readClientRect(e);this._enqueue(e,t.width,t.height)})}unobserve(e){let t=this._observed.get(e);t&&(t(),this._observed.delete(e),this._pending.delete(e))}disconnect(){for(let e of this._observed.values())e();this._observed.clear(),this._pending.clear(),Nt.delete(this)}_deliver(){if(this._pending.size===0)return;let e=Array.from(this._pending.values());this._pending.clear();try{this._callback(e,this)}catch(e){console.error(`ResizeObserver callback threw:`,e)}}_enqueue(e,t,n){let r={inlineSize:t,blockSize:n};this._pending.set(e,{target:e,contentRect:{x:0,y:0,width:t,height:n,top:0,right:t,bottom:n,left:0},borderBoxSize:[r],contentBoxSize:[r],devicePixelContentBoxSize:[r]}),Nt.add(this),scheduleFlush()}};function readClientRect(e){let t=e.getBoundingClientRect;if(typeof t==`function`){let n=t.call(e);return{width:n.width??0,height:n.height??0}}return{width:0,height:0}}var IntersectionObserver=class{constructor(e,t){this.root=t?.root??null,this.rootMargin=t?.rootMargin??`0px`,this.thresholds=Array.isArray(t?.threshold)?t.threshold:[t?.threshold??0]}observe(e){}unobserve(e){}disconnect(){}takeRecords(){return[]}};defineGlobal(`MutationObserver`,MutationObserver),defineGlobal(`ResizeObserver`,ResizeObserver),defineGlobal(`IntersectionObserver`,IntersectionObserver);const Ft={CustomEvent:CustomEvent$1,MessageEvent,ErrorEvent,CloseEvent,ProgressEvent:ProgressEvent$1};for(let[e,t]of Object.entries(Ft))globalThis[e]===void 0&&Object.defineProperty(globalThis,e,{value:t,writable:!0,configurable:!0});const It={UIEvent,MouseEvent,PointerEvent,KeyboardEvent,WheelEvent,FocusEvent};for(let[e,t]of Object.entries(It))globalThis[e]===void 0&&Object.defineProperty(globalThis,e,{value:t,writable:!0,configurable:!0});var Lt,__name,Rt=__esmMin((()=>{Lt=Object.defineProperty,__name=(e,t)=>Lt(e,`name`,{value:t,configurable:!0})}));const zt=e(import.meta.url);let Bt;function load$6(){return Bt===void 0&&(Bt=zt(`@gjsify/node-gi/gi`).requireGi(`Soup`,`3.0`)),Bt}__name$1(load$6,`load`);var Vt=new Proxy(Object.create(null),{get(e,t){return load$6()[t]},has(e,t){return t in load$6()}});function validateHeaderName(e){if(typeof e!=`string`||!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token ["${e}"]`);throw Object.defineProperty(t,"code",{value:`ERR_INVALID_HTTP_TOKEN`}),t}}function validateHeaderValue(e,t){if(t===void 0){let t=TypeError(`Header "${e}" value must not be undefined`);throw Object.defineProperty(t,"code",{value:`ERR_HTTP_INVALID_HEADER_VALUE`}),t}if(typeof t==`string`&&/[^\t -~€-ÿ]/.test(t)){let t=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,"code",{value:`ERR_INVALID_CHAR`}),t}}const Ht=Symbol(`Headers.headers`);function isBoxedPrimitive(e){return e instanceof String||e instanceof Number||e instanceof Boolean||typeof Symbol<`u`&&e instanceof Symbol||typeof BigInt<`u`&&e instanceof BigInt}var Ut=class Headers{[Ht];constructor(e){if(this[Ht]=new Map,e!=null){if(e instanceof Headers){for(let[t,n]of e[Ht])this[Ht].set(t,[...n]);return}if(typeof e==`object`&&!isBoxedPrimitive(e)){let t=e[Symbol.iterator];if(t==null)for(let[t,n]of Object.entries(e))validateHeaderName(t),validateHeaderValue(t,String(n)),this.append(t,String(n));else{if(typeof t!=`function`)throw TypeError(`Header pairs must be iterable`);for(let t of e){if(typeof t!=`object`||isBoxedPrimitive(t))throw TypeError(`Each header pair must be an iterable object`);let e=[...t];if(e.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);validateHeaderName(e[0]),validateHeaderValue(e[0],String(e[1])),this.append(e[0],String(e[1]))}}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'`)}}append(e,t){validateHeaderName(e),validateHeaderValue(e,t);let n=String(e).toLowerCase(),r=String(t),i=this[Ht].get(n);i?i.push(r):this[Ht].set(n,[r])}set(e,t){validateHeaderName(e),validateHeaderValue(e,t);let n=String(e).toLowerCase();this[Ht].set(n,[String(t)])}delete(e){this[Ht].delete(String(e).toLowerCase())}has(e){return this[Ht].has(String(e).toLowerCase())}get(e){let t=this[Ht].get(String(e).toLowerCase());if(!t||t.length===0)return null;let n=t.join(`, `);return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}getAll(e){return this[Ht].get(String(e).toLowerCase())??[]}getSetCookie(){return this[Ht].get(`set-cookie`)??[]}forEach(e,t){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*keys(){let e=[...this[Ht].keys()].sort(),t=new Set;for(let n of e)t.has(n)||(t.add(n),yield n)}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`Headers`}toString(){return Object.prototype.toString.call(this)}raw(){let e={};for(let t of this.keys())e[t]=this.getAll(t);return e}_appendToSoupMessage(e,t=Vt.MessageHeadersType.REQUEST){let n=e?e.get_request_headers():new Vt.MessageHeaders(t);for(let[e,t]of this.entries())n.append(e,t);return n}static _newFromSoupMessage(e,t=Vt.MessageHeadersType.RESPONSE){let n=new Headers,r;return r=t===Vt.MessageHeadersType.RESPONSE?e.get_response_headers():e.get_request_headers(),r.foreach((e,t)=>{n.append(e,t)}),n}[Symbol.for(`nodejs.util.inspect.custom`)](){let e={};for(let t of this.keys()){let n=this.getAll(t);t===`host`?e[t]=n[0]:e[t]=n.length>1?n:n[0]}return e}};Object.defineProperties(Ut.prototype,[`get`,`entries`,`forEach`,`values`].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));var Wt=__esmMin((()=>{}));Wt();var FetchBaseError=class extends Error{type;constructor(e,t){super(e),typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},FetchError=class extends FetchBaseError{code;errno;erroredSysCall;constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}};const Gt=globalThis.URL,Kt=globalThis.URLSearchParams,qt=Symbol.toStringTag,isURLSearchParameters=e=>typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&typeof e.sort==`function`&&e[qt]===`URLSearchParams`,isBlob=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.arrayBuffer==`function`&&typeof t.type==`string`&&typeof t.stream==`function`&&typeof t.constructor==`function`&&/^(Blob|File)$/.test(t[qt])},isAbortSignal=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return t[qt]===`AbortSignal`||t[qt]===`EventTarget`},isDomainOrSubdomain=(e,t)=>{let n=new Gt(t).hostname,r=new Gt(e).hostname;return n===r||n.endsWith(`.${r}`)},isSameProtocol=(e,t)=>new Gt(t).protocol===new Gt(e).protocol;function formDataToBlob(e){let t=`----FormDataBoundary`+Math.random().toString(36).slice(2),n=[];for(let[r,i]of e.entries())typeof i==`string`?n.push(`--${t}\r\nContent-Disposition: form-data; name="${r}"\r\n\r\n${i}\r\n`):(n.push(`--${t}\r\nContent-Disposition: form-data; name="${r}"; filename="${i.name}"\r\nContent-Type: ${i.type||`application/octet-stream`}\r\n\r\n`),n.push(i),n.push(`\r
1
+ import{createRequire as e}from"node:module";import"@gjsify/node-gi/globals";import t from"@gjsify/node-gi/cairo";import n from"@gjsify/node-gi/system";import{Blob as r,Buffer as i,File as a}from"node:buffer";import o,{PassThrough as s,Readable as c,Stream as l,pipeline as u}from"node:stream";import{isIP as d}from"node:net";var f=Object.create,p=Object.defineProperty,__name$1=(e,t)=>p(e,`name`,{value:t,configurable:!0}),m=Object.getOwnPropertyDescriptor,h=Object.getOwnPropertyNames,g=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty,__esmMin=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},__commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),__exportAll$1=(e,t)=>{let n={};for(var r in e)p(n,r,{get:e[r],enumerable:!0});return t||p(n,Symbol.toStringTag,{value:`Module`}),n},__copyProps=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=h(t),a=0,o=i.length,s;a<o;a++)s=i[a],!_.call(e,s)&&s!==n&&p(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=m(t,s))||r.enumerable});return e},__toESM=(e,t,n)=>(n=e==null?{}:f(g(e)),__copyProps(t||!e||!e.__esModule?p(n,`default`,{value:e,enumerable:!0}):n,e));for(let e of[`Headers`,`Request`,`Response`,`fetch`])try{delete globalThis[e]}catch{}var v=Object.defineProperty,__exportAll=(e,t)=>{let n={};for(var r in e)v(n,r,{get:e[r],enumerable:!0});return t||v(n,Symbol.toStringTag,{value:`Module`}),n};__exportAll({attributes:()=>O,childNodesList:()=>x,elementChildren:()=>S,isConnected:()=>C,localName:()=>T,name:()=>A,namespaceURI:()=>E,nodeType:()=>y,ownerElement:()=>te,parentNode:()=>b,prefix:()=>D,propertyEventListeners:()=>k,tagName:()=>w,value:()=>ee});const y=Symbol(`nodeType`),b=Symbol(`parentNode`),x=Symbol(`childNodesList`),S=Symbol(`elementChildren`),C=Symbol(`isConnected`),w=Symbol(`tagName`),T=Symbol(`localName`),E=Symbol(`namespaceURI`),D=Symbol(`prefix`),O=Symbol(`attributes`),k=Symbol(`propertyEventListeners`),A=Symbol(`name`),ee=Symbol(`value`),te=Symbol(`ownerElement`),j={ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11};var NodeList=class{constructor(e){this._items=e}get length(){return this._items.length}item(e){return this._items[e]??null}forEach(e,t){for(let n=0;n<this._items.length;n++)e.call(t,this._items[n],n,this)}entries(){return this._items.entries()}keys(){return this._items.keys()}values(){return this._items.values()}[Symbol.iterator](){return this._items[Symbol.iterator]()}get[Symbol.toStringTag](){return`NodeList`}};const ne=globalThis.DOMException,re=Symbol(`type`),ie=Symbol(`bubbles`),ae=Symbol(`cancelable`),oe=Symbol(`composed`),se=Symbol(`target`),ce=Symbol(`currentTarget`),le=Symbol(`eventPhase`),ue=Symbol(`defaultPrevented`),de=Symbol(`isTrusted`),fe=Symbol(`timeStamp`),pe=Symbol(`stop`),me=Symbol(`immediateStop`),he=Symbol(`dispatching`),ge=Symbol(`inPassiveListener`);var Event=class{[re];[ie];[ae];[oe];[se]=null;[ce]=null;[le]=0;[ue]=!1;[de]=!1;[fe];[pe]=!1;[me]=!1;[he]=!1;[ge]=!1;get type(){return this[re]}get bubbles(){return this[ie]}get cancelable(){return this[ae]}get composed(){return this[oe]}get target(){return this[se]}get currentTarget(){return this[ce]}get eventPhase(){return this[le]}get defaultPrevented(){return this[ue]}get timeStamp(){return this[fe]}get cancelBubble(){return this[pe]}set cancelBubble(e){e&&this.stopPropagation()}get returnValue(){return!this[ue]}set returnValue(e){e||this.preventDefault()}get srcElement(){return this[se]}static NONE=0;static CAPTURING_PHASE=1;static AT_TARGET=2;static BUBBLING_PHASE=3;get[Symbol.toStringTag](){return`Event`}constructor(e,t){this[re]=e,this[ie]=t?.bubbles??!1,this[ae]=t?.cancelable??!1,this[oe]=t?.composed??!1,this[fe]=Date.now(),Object.defineProperty(this,"isTrusted",{get:()=>this[de],enumerable:!0,configurable:!1})}composedPath(){return this[ce]?[this[ce]]:[]}preventDefault(){this[ae]&&!this[ge]&&(this[ue]=!0)}stopPropagation(){this[pe]=!0}stopImmediatePropagation(){this[pe]=!0,this[me]=!0}},CustomEvent$1=class extends Event{static{__name$1(this,`CustomEvent`)}detail;constructor(e,t){super(e,t),this.detail=t?.detail}},MessageEvent=class extends Event{data;origin;lastEventId;source;ports;constructor(e,t){super(e,t),this.data=t?.data??null,this.origin=t?.origin??``,this.lastEventId=t?.lastEventId??``,this.source=t?.source??null,this.ports=t?.ports??[]}get[Symbol.toStringTag](){return`MessageEvent`}},ErrorEvent=class extends Event{message;filename;lineno;colno;error;constructor(e,t){super(e,t),this.message=t?.message??``,this.filename=t?.filename??``,this.lineno=t?.lineno??0,this.colno=t?.colno??0,this.error=t?.error??null}get[Symbol.toStringTag](){return`ErrorEvent`}},CloseEvent=class extends Event{code;reason;wasClean;constructor(e,t){super(e,t),this.code=t?.code??0,this.reason=t?.reason??``,this.wasClean=t?.wasClean??!1}get[Symbol.toStringTag](){return`CloseEvent`}},ProgressEvent$1=class extends Event{static{__name$1(this,`ProgressEvent`)}lengthComputable;loaded;total;constructor(e,t){super(e,t),this.lengthComputable=t?.lengthComputable??!1,this.loaded=t?.loaded??0,this.total=t?.total??0}get[Symbol.toStringTag](){return`ProgressEvent`}},EventTarget=class{_listeners=new Map;get[Symbol.toStringTag](){return`EventTarget`}addEventListener(e,t,n){if(t===null)return;let r=typeof n==`boolean`?n:n?.capture??!1,i=typeof n==`object`?n?.once??!1:!1,a=typeof n==`object`?n?.passive??!1:!1,o=this._listeners.get(e);o||(o=[],this._listeners.set(e,o));for(let e of o)if(e.listener===t&&e.capture===r)return;let s={listener:t,capture:r,once:i,passive:a,removed:!1};o.push(s),typeof n==`object`&&n?.signal&&n.signal.addEventListener(`abort`,()=>{this.removeEventListener(e,t,{capture:r})},{once:!0})}removeEventListener(e,t,n){if(t===null)return;let r=typeof n==`boolean`?n:n?.capture??!1,i=this._listeners.get(e);if(!i)return;let a=i.findIndex(e=>e.listener===t&&e.capture===r);a!==-1&&(i[a].removed=!0,i.splice(a,1),i.length===0&&this._listeners.delete(e))}dispatchEvent(e){let t=e;if(t[he])throw new ne(`The event is already being dispatched.`,`InvalidStateError`);t[he]=!0,t[se]=this,t[ce]=this,t[le]=Event.AT_TARGET;try{let n=this._listeners.get(e.type);if(n){let r=[...n];for(let n of r)if(!n.removed){if(t[me]||t[pe])break;n.once&&this.removeEventListener(e.type,n.listener,{capture:n.capture});try{n.passive&&(t[ge]=!0),typeof n.listener==`function`?n.listener.call(this,e):typeof n.listener.handleEvent==`function`&&n.listener.handleEvent.call(n.listener,e)}catch(e){reportListenerException(e)}finally{t[ge]=!1}}}}finally{t[le]=Event.NONE,t[ce]=null,t[he]=!1}return!e.defaultPrevented}};function reportListenerException(e){try{let t=globalThis;if(typeof t.reportError==`function`)t.reportError(e);else if(e instanceof Error){let t=`${e.name}: ${e.message}`;console.error(e.stack?`${t}\n${e.stack}`:t)}else console.error(String(e))}catch{}}for(let[e,t]of[[`NONE`,0],[`CAPTURING_PHASE`,1],[`AT_TARGET`,2],[`BUBBLING_PHASE`,3]])Object.defineProperty(Event.prototype,e,{value:t,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Event,e,{value:t,writable:!1,enumerable:!0,configurable:!1});var UIEvent=class extends Event{detail;view;constructor(e,t){super(e,t),this.detail=t?.detail??0,this.view=null}get[Symbol.toStringTag](){return`UIEvent`}},MouseEvent=class extends UIEvent{altKey;button;buttons;clientX;clientY;ctrlKey;metaKey;movementX;movementY;offsetX;offsetY;screenX;screenY;shiftKey;relatedTarget;get pageX(){return this.clientX}get pageY(){return this.clientY}get x(){return this.clientX}get y(){return this.clientY}constructor(e,t){super(e,t),this.altKey=t?.altKey??!1,this.button=t?.button??0,this.buttons=t?.buttons??0,this.clientX=t?.clientX??0,this.clientY=t?.clientY??0,this.ctrlKey=t?.ctrlKey??!1,this.metaKey=t?.metaKey??!1,this.movementX=t?.movementX??0,this.movementY=t?.movementY??0,this.offsetX=t?.offsetX??0,this.offsetY=t?.offsetY??0,this.screenX=t?.screenX??0,this.screenY=t?.screenY??0,this.shiftKey=t?.shiftKey??!1,this.relatedTarget=t?.relatedTarget??null}getModifierState(e){switch(e){case`Alt`:return this.altKey;case`Control`:return this.ctrlKey;case`Meta`:return this.metaKey;case`Shift`:return this.shiftKey;default:return!1}}get[Symbol.toStringTag](){return`MouseEvent`}},PointerEvent=class extends MouseEvent{pointerId;width;height;pressure;tangentialPressure;tiltX;tiltY;twist;altitudeAngle;azimuthAngle;pointerType;isPrimary;constructor(e,t){super(e,t),this.pointerId=t?.pointerId??0,this.width=t?.width??1,this.height=t?.height??1,this.pressure=t?.pressure??0,this.tangentialPressure=t?.tangentialPressure??0,this.tiltX=t?.tiltX??0,this.tiltY=t?.tiltY??0,this.twist=t?.twist??0,this.altitudeAngle=t?.altitudeAngle??Math.PI/2,this.azimuthAngle=t?.azimuthAngle??0,this.pointerType=t?.pointerType??``,this.isPrimary=t?.isPrimary??!1}getCoalescedEvents(){return[]}getPredictedEvents(){return[]}get[Symbol.toStringTag](){return`PointerEvent`}},KeyboardEvent=class extends UIEvent{altKey;code;ctrlKey;isComposing;key;location;metaKey;repeat;shiftKey;keyCode;which;static DOM_KEY_LOCATION_STANDARD=0;static DOM_KEY_LOCATION_LEFT=1;static DOM_KEY_LOCATION_RIGHT=2;static DOM_KEY_LOCATION_NUMPAD=3;constructor(e,t){super(e,t),this.altKey=t?.altKey??!1,this.code=t?.code??``,this.ctrlKey=t?.ctrlKey??!1,this.isComposing=t?.isComposing??!1,this.key=t?.key??``,this.location=t?.location??0,this.metaKey=t?.metaKey??!1,this.repeat=t?.repeat??!1,this.shiftKey=t?.shiftKey??!1,this.keyCode=t?.keyCode??0,this.which=t?.which??0}getModifierState(e){switch(e){case`Alt`:return this.altKey;case`Control`:return this.ctrlKey;case`Meta`:return this.metaKey;case`Shift`:return this.shiftKey;default:return!1}}get[Symbol.toStringTag](){return`KeyboardEvent`}},WheelEvent=class extends MouseEvent{deltaX;deltaY;deltaZ;deltaMode;static DOM_DELTA_PIXEL=0;static DOM_DELTA_LINE=1;static DOM_DELTA_PAGE=2;constructor(e,t){super(e,t),this.deltaX=t?.deltaX??0,this.deltaY=t?.deltaY??0,this.deltaZ=t?.deltaZ??0,this.deltaMode=t?.deltaMode??0}get[Symbol.toStringTag](){return`WheelEvent`}},FocusEvent=class extends UIEvent{relatedTarget;constructor(e,t){super(e,t),this.relatedTarget=t?.relatedTarget??null}get[Symbol.toStringTag](){return`FocusEvent`}};let _e,ve,ye,be,xe;var Se=class Node extends EventTarget{constructor(...e){super(...e),this.ELEMENT_NODE=j.ELEMENT_NODE,this.ATTRIBUTE_NODE=j.ATTRIBUTE_NODE,this.TEXT_NODE=j.TEXT_NODE,this.CDATA_SECTION_NODE=j.CDATA_SECTION_NODE,this.PROCESSING_INSTRUCTION_NODE=j.PROCESSING_INSTRUCTION_NODE,this.COMMENT_NODE=j.COMMENT_NODE,this.DOCUMENT_NODE=j.DOCUMENT_NODE,this.DOCUMENT_TYPE_NODE=j.DOCUMENT_TYPE_NODE,this.DOCUMENT_FRAGMENT_NODE=j.DOCUMENT_FRAGMENT_NODE,this[_e]=j.ELEMENT_NODE,this[ve]=null,this[ye]=[],this[be]=[],this[xe]=!1}static{this.ELEMENT_NODE=j.ELEMENT_NODE}static{this.ATTRIBUTE_NODE=j.ATTRIBUTE_NODE}static{this.TEXT_NODE=j.TEXT_NODE}static{this.CDATA_SECTION_NODE=j.CDATA_SECTION_NODE}static{this.PROCESSING_INSTRUCTION_NODE=j.PROCESSING_INSTRUCTION_NODE}static{this.COMMENT_NODE=j.COMMENT_NODE}static{this.DOCUMENT_NODE=j.DOCUMENT_NODE}static{this.DOCUMENT_TYPE_NODE=j.DOCUMENT_TYPE_NODE}static{this.DOCUMENT_FRAGMENT_NODE=j.DOCUMENT_FRAGMENT_NODE}static{this.DOCUMENT_POSITION_DISCONNECTED=1}static{this.DOCUMENT_POSITION_PRECEDING=2}static{this.DOCUMENT_POSITION_FOLLOWING=4}static{this.DOCUMENT_POSITION_CONTAINS=8}static{this.DOCUMENT_POSITION_CONTAINED_BY=16}static{this.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC=32}get nodeType(){return this[y]}get nodeName(){return``}get parentNode(){return this[b]}get parentElement(){let e=this[b];return e&&e[y]===j.ELEMENT_NODE?e:null}get childNodes(){return new NodeList(this[x])}get firstChild(){return this[x][0]??null}get lastChild(){let e=this[x];return e[e.length-1]??null}get previousSibling(){let e=this[b];if(!e)return null;let t=e[x],n=t.indexOf(this);return n>0?t[n-1]:null}get nextSibling(){let e=this[b];if(!e)return null;let t=e[x],n=t.indexOf(this);return n!==-1&&n<t.length-1?t[n+1]:null}get textContent(){return null}set textContent(e){}get nodeValue(){return null}set nodeValue(e){}get ownerDocument(){let e=this;for(;e[b];)e=e[b];let t=globalThis.document;return e===t?t:null}get isConnected(){return this[C]}hasChildNodes(){return this[x].length>0}contains(e){if(e===null)return!1;if(e===this)return!0;let t=e;for(;t;){if(t===this)return!0;t=t[b]}return!1}getRootNode(){let e=this;for(;e[b];)e=e[b];return e}appendChild(e){return e[b]&&e[b].removeChild(e),e[b]=this,this[x].push(e),e[y]===j.ELEMENT_NODE&&this[S].push(e),e}removeChild(e){let t=this[x],n=t.indexOf(e);if(n===-1)throw new DOMException(`Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.`,`NotFoundError`);if(t.splice(n,1),e[b]=null,e[y]===j.ELEMENT_NODE){let t=this[S].indexOf(e);t!==-1&&this[S].splice(t,1)}return e}insertBefore(e,t){if(t===null)return this.appendChild(e);let n=this[x],r=n.indexOf(t);if(r===-1)throw new DOMException(`Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.`,`NotFoundError`);if(e[b]&&e[b].removeChild(e),e[b]=this,n.splice(r,0,e),e[y]===j.ELEMENT_NODE){let t=this[S],i=t.length;for(let a=r;a<n.length;a++)if(n[a][y]===j.ELEMENT_NODE&&n[a]!==e){i=t.indexOf(n[a]);break}t.splice(i,0,e)}return e}replaceChild(e,t){return this.insertBefore(e,t),this.removeChild(t),t}cloneNode(e=!1){let t=new this.constructor;if(t[y]=this[y],e)for(let e of this[x])t.appendChild(e.cloneNode(!0));return t}dispatchEvent(e){let t=super.dispatchEvent(e);if(e.bubbles&&!e.cancelBubble){let t=this[b];for(;t&&(Object.getPrototypeOf(Node.prototype).dispatchEvent.call(t,e),!e.cancelBubble);)t=t[b]}return t}get[(_e=y,ve=b,ye=x,be=S,xe=C,Symbol.toStringTag)](){return`Node`}};const Ce={html:`http://www.w3.org/1999/xhtml`,svg:`http://www.w3.org/2000/svg`,mathML:`http://www.w3.org/1998/Math/MathML`,xml:`http://www.w3.org/XML/1998/namespace`,xmlns:`http://www.w3.org/2000/xmlns/`};var Attr=class{constructor(e,t,n=null,r=null,i=null){this.specified=!0,this[A]=e,this[ee]=t,this[te]=i,this.namespaceURI=n,this.prefix=r;let a=e.indexOf(`:`);this.localName=a===-1?e:e.slice(a+1)}get name(){return this[A]}get value(){return this[ee]}set value(e){this[ee]=e}get ownerElement(){return this[te]}get[Symbol.toStringTag](){return`Attr`}},NamedNodeMap=class{constructor(e){this._items=[],this._ownerElement=e}get length(){return this._items.length}item(e){return this._items[e]??null}getNamedItem(e){return this._findByName(e)}getNamedItemNS(e,t){let n=e===``?null:e;for(let e of this._items)if(e.namespaceURI===n&&e.localName===t)return e;return null}setNamedItem(e){return this._setAttr(e)}setNamedItemNS(e){return this._setAttr(e)}removeNamedItem(e){let t=this._findByName(e);if(!t)throw new DOMException(`Failed to execute 'removeNamedItem' on 'NamedNodeMap': No item with name '${e}' was found.`,`NotFoundError`);return this._removeAttr(t),t}removeNamedItemNS(e,t){let n=this.getNamedItemNS(e,t);if(!n)throw new DOMException(`Failed to execute 'removeNamedItemNS' on 'NamedNodeMap': No item with namespace '${e}' and localName '${t}' was found.`,`NotFoundError`);return this._removeAttr(n),n}[Symbol.iterator](){return this._items[Symbol.iterator]()}get[Symbol.toStringTag](){return`NamedNodeMap`}_setNamedItem(e,t,n=null,r=null){let i=n===null?this._findByName(e):this.getNamedItemNS(n,e.includes(`:`)?e.split(`:`)[1]:e);if(i)i.value=t;else{let i=new Attr(e,t,n,r,this._ownerElement);this._items.push(i)}}_removeNamedItem(e){let t=this._findByName(e);return t?(this._removeAttr(t),!0):!1}_removeNamedItemNS(e,t){let n=this.getNamedItemNS(e,t);return n?(this._removeAttr(n),!0):!1}_findByName(e){let t=this._ownerElement.namespaceURI===Ce.html,n=t?e.toLowerCase():e;for(let e of this._items)if((t?e.name.toLowerCase():e.name)===n)return e;return null}_setAttr(e){let t=null;if(t=e.namespaceURI===null?this._findByName(e.name):this.getNamedItemNS(e.namespaceURI,e.localName),t){let n=new Attr(t.name,t.value,t.namespaceURI,t.prefix,t.ownerElement);return t.value=e.value,n}return this._items.push(e),null}_removeAttr(e){let t=this._items.indexOf(e);t!==-1&&this._items.splice(t,1)}};let we,M,Te,Ee,N,De;var Element=class extends Se{constructor(){super(),this[we]=``,this[M]=``,this[Te]=Ce.html,this[Ee]=null,this[N]=new NamedNodeMap(this),this[De]=new Map,this._resizeSubscribers=null,this._allocatedClientWidth=0,this._allocatedClientHeight=0,this._pointerCaptures=new Set,this[y]=j.ELEMENT_NODE}get tagName(){return this[w]}get localName(){return this[T]}get namespaceURI(){return this[E]}get prefix(){return this[D]}get nodeName(){return this[w]}get attributes(){return this[O]}get id(){return this.getAttribute(`id`)??``}set id(e){this.setAttribute(`id`,e)}get className(){return this.getAttribute(`class`)??``}set className(e){this.setAttribute(`class`,e)}get children(){return this[S]}get childElementCount(){return this[S].length}get firstElementChild(){return this[S][0]??null}get lastElementChild(){let e=this[S];return e[e.length-1]??null}get previousElementSibling(){let e=this[b];if(!e)return null;let t=e[S],n=t.indexOf(this);return n>0?t[n-1]:null}get nextElementSibling(){let e=this[b];if(!e)return null;let t=e[S],n=t.indexOf(this);return n!==-1&&n<t.length-1?t[n+1]:null}get textContent(){let e=``;for(let t of this[x])t.textContent!==null&&(e+=t.textContent);return e}set textContent(e){let t=this[x];for(;t.length>0;)this.removeChild(t[0])}getAttribute(e){let t=this[O].getNamedItem(e);return t?t.value:null}getAttributeNS(e,t){let n=this[O].getNamedItemNS(e,t);return n?n.value:null}setAttribute(e,t){this[O]._setNamedItem(e,String(t))}setAttributeNS(e,t,n){let r=e===``?null:e,i=t.split(`:`),a=i.length>1?i[0]:null;this[O]._setNamedItem(t,String(n),r,a)}removeAttribute(e){this[O]._removeNamedItem(e)}removeAttributeNS(e,t){let n=e===``?null:e;this[O]._removeNamedItemNS(n,t)}hasAttribute(e){return this[O].getNamedItem(e)!==null}hasAttributeNS(e,t){return this[O].getNamedItemNS(e,t)!==null}getAttributeNode(e){return this[O].getNamedItem(e)}setAttributeNode(e){return this[O].setNamedItem(e)}removeAttributeNode(e){let t=this[O].getNamedItem(e.name);if(!t)throw new DOMException(`Failed to execute 'removeAttributeNode' on 'Element': The attribute is not owned by this element.`,`NotFoundError`);return this[O].removeNamedItem(t.name),t}toggleAttribute(e,t){return t===void 0?this.hasAttribute(e)?(this.removeAttribute(e),!1):(this.setAttribute(e,``),!0):t?(this.setAttribute(e,``),!0):(this.removeAttribute(e),!1)}hasAttributes(){return this[O].length>0}dispatchEvent(e){let t=super.dispatchEvent(e),n=this[k].get(`on`+e.type);return typeof n==`function`&&n.call(this,e),t}querySelector(e){return null}querySelectorAll(e){return[]}matches(e){return!1}closest(e){return null}getElementsByTagName(e){let t=[],n=e.toUpperCase(),walk=r=>{for(let i of r[x])if(i[y]===j.ELEMENT_NODE){let r=i;(e===`*`||r[w]===n)&&t.push(r),walk(r)}};return walk(this),t}getElementsByClassName(e){let t=[],n=e.split(/\s+/).filter(Boolean),walk=e=>{for(let r of e[x])if(r[y]===j.ELEMENT_NODE){let e=r,i=e.className.split(/\s+/);n.every(e=>i.includes(e))&&t.push(e),walk(e)}};return walk(this),t}cloneNode(e=!1){let t=super.cloneNode(!1);t[w]=this[w],t[T]=this[T],t[E]=this[E],t[D]=this[D];for(let e of this[O])t.setAttributeNS(e.namespaceURI,e.name,e.value);if(e)for(let e of this[x])t.appendChild(e.cloneNode(!0));return t}_onResize(e){let t=this._resizeSubscribers??=new Set;return t.add(e),()=>{t.delete(e),t.size===0&&(this._resizeSubscribers=null)}}_fireResizeSubscribers(e,t){let n=this._resizeSubscribers;if(!(!n||n.size===0))for(let r of[...n])try{r(e,t)}catch(e){console.error(`ResizeObserver subscriber threw:`,e)}}setPointerCapture(e){this._pointerCaptures.add(e)}releasePointerCapture(e){this._pointerCaptures.delete(e)}hasPointerCapture(e){return this._pointerCaptures.has(e)}get[(we=w,M=T,Te=E,Ee=D,N=O,De=k,Symbol.toStringTag)](){return`Element`}},CSSStyleDeclaration=class{constructor(){this._cssText=``}get cssText(){return this._cssText}set cssText(e){this._cssText=e;for(let t of e.split(`;`)){let e=t.indexOf(`:`);if(e===-1)continue;let n=t.slice(0,e).trim(),r=t.slice(e+1).trim();if(!n)continue;let i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());this[i]=r}}setProperty(e,t,n){this[e]=t}getPropertyValue(e){let t=this[e];return typeof t==`string`?t:``}removeProperty(e){let t=this[e];return delete this[e],typeof t==`string`?t:``}getPropertyPriority(e){return``}},HTMLElement=class extends Element{constructor(...e){super(...e),this.style=new CSSStyleDeclaration}get dataset(){let e=this;return new Proxy({},{get(t,n){if(typeof n!=`string`)return;let r=`data-`+n.replace(/[A-Z]/g,e=>`-`+e.toLowerCase());return e.getAttribute(r)??void 0},set(t,n,r){if(typeof n!=`string`)return!1;let i=`data-`+n.replace(/[A-Z]/g,e=>`-`+e.toLowerCase());return e.setAttribute(i,String(r)),!0},deleteProperty(t,n){if(typeof n!=`string`)return!1;let r=`data-`+n.replace(/[A-Z]/g,e=>`-`+e.toLowerCase());return e.removeAttribute(r),!0},has(t,n){if(typeof n!=`string`)return!1;let r=`data-`+n.replace(/[A-Z]/g,e=>`-`+e.toLowerCase());return e.hasAttribute(r)}})}get title(){return this.getAttribute(`title`)??``}set title(e){this.setAttribute(`title`,e)}get lang(){return this.getAttribute(`lang`)??``}set lang(e){this.setAttribute(`lang`,e)}get dir(){return this.getAttribute(`dir`)??``}set dir(e){this.setAttribute(`dir`,e)}get accessKey(){return this.getAttribute(`accesskey`)??``}set accessKey(e){this.setAttribute(`accesskey`,e)}get accessKeyLabel(){return this.getAttribute(`accesskey`)??``}get hidden(){return this.hasAttribute(`hidden`)}set hidden(e){e?this.setAttribute(`hidden`,``):this.removeAttribute(`hidden`)}get draggable(){return this.getAttribute(`draggable`)===`true`}set draggable(e){this.setAttribute(`draggable`,String(e))}get spellcheck(){let e=this.getAttribute(`spellcheck`);return e===`false`?!1:e!==null}set spellcheck(e){this.setAttribute(`spellcheck`,String(e))}get translate(){return this.getAttribute(`translate`)!==`no`}set translate(e){this.setAttribute(`translate`,e?`yes`:`no`)}get tabIndex(){let e=this.getAttribute(`tabindex`);return e===null?-1:Number(e)}set tabIndex(e){this.setAttribute(`tabindex`,String(e))}get contentEditable(){let e=this.getAttribute(`contenteditable`);return e===``||e===`true`?`true`:e===`false`?`false`:`inherit`}set contentEditable(e){e===`inherit`?this.removeAttribute(`contenteditable`):this.setAttribute(`contenteditable`,e)}get isContentEditable(){return this.contentEditable===`true`}get offsetHeight(){return this._allocatedClientHeight}get offsetWidth(){return this._allocatedClientWidth}get offsetLeft(){return 0}get offsetTop(){return 0}get offsetParent(){return null}get clientHeight(){return this._allocatedClientHeight}get clientWidth(){return this._allocatedClientWidth}get clientLeft(){return 0}get clientTop(){return 0}get scrollHeight(){return this._allocatedClientHeight}get scrollWidth(){return this._allocatedClientWidth}get scrollTop(){return 0}set scrollTop(e){}get scrollLeft(){return 0}set scrollLeft(e){}getBoundingClientRect(){let e=this.clientWidth,t=this.clientHeight;return{x:0,y:0,top:0,left:0,right:e,bottom:t,width:e,height:t,toJSON(){return this}}}click(){this.dispatchEvent(new Event(`click`,{bubbles:!0,cancelable:!0}))}blur(){this.dispatchEvent(new Event(`blur`))}focus(){this.dispatchEvent(new Event(`focus`))}get onclick(){return this[k].get(`onclick`)??null}set onclick(e){this[k].set(`onclick`,e)}get ondblclick(){return this[k].get(`ondblclick`)??null}set ondblclick(e){this[k].set(`ondblclick`,e)}get onload(){return this[k].get(`onload`)??null}set onload(e){this[k].set(`onload`,e)}get onerror(){return this[k].get(`onerror`)??null}set onerror(e){this[k].set(`onerror`,e)}get onabort(){return this[k].get(`onabort`)??null}set onabort(e){this[k].set(`onabort`,e)}get onfocus(){return this[k].get(`onfocus`)??null}set onfocus(e){this[k].set(`onfocus`,e)}get onblur(){return this[k].get(`onblur`)??null}set onblur(e){this[k].set(`onblur`,e)}get onchange(){return this[k].get(`onchange`)??null}set onchange(e){this[k].set(`onchange`,e)}get oninput(){return this[k].get(`oninput`)??null}set oninput(e){this[k].set(`oninput`,e)}get onsubmit(){return this[k].get(`onsubmit`)??null}get onreset(){return this[k].get(`onreset`)??null}set onreset(e){this[k].set(`onreset`,e)}get onscroll(){return this[k].get(`onscroll`)??null}set onscroll(e){this[k].set(`onscroll`,e)}get onresize(){return this[k].get(`onresize`)??null}set onresize(e){this[k].set(`onresize`,e)}get onmousedown(){return this[k].get(`onmousedown`)??null}set onmousedown(e){this[k].set(`onmousedown`,e)}get onmouseup(){return this[k].get(`onmouseup`)??null}set onmouseup(e){this[k].set(`onmouseup`,e)}get onmousemove(){return this[k].get(`onmousemove`)??null}set onmousemove(e){this[k].set(`onmousemove`,e)}get onmouseover(){return this[k].get(`onmouseover`)??null}set onmouseover(e){this[k].set(`onmouseover`,e)}get onmouseout(){return this[k].get(`onmouseout`)??null}set onmouseout(e){this[k].set(`onmouseout`,e)}get onmouseenter(){return this[k].get(`onmouseenter`)??null}set onmouseenter(e){this[k].set(`onmouseenter`,e)}get onmouseleave(){return this[k].get(`onmouseleave`)??null}set onmouseleave(e){this[k].set(`onmouseleave`,e)}get oncontextmenu(){return this[k].get(`oncontextmenu`)??null}set oncontextmenu(e){this[k].set(`oncontextmenu`,e)}get onwheel(){return this[k].get(`onwheel`)??null}set onwheel(e){this[k].set(`onwheel`,e)}get onkeydown(){return this[k].get(`onkeydown`)??null}set onkeydown(e){this[k].set(`onkeydown`,e)}get onkeyup(){return this[k].get(`onkeyup`)??null}set onkeyup(e){this[k].set(`onkeyup`,e)}get ontouchstart(){return this[k].get(`ontouchstart`)??null}set ontouchstart(e){this[k].set(`ontouchstart`,e)}get ontouchend(){return this[k].get(`ontouchend`)??null}set ontouchend(e){this[k].set(`ontouchend`,e)}get ontouchmove(){return this[k].get(`ontouchmove`)??null}set ontouchmove(e){this[k].set(`ontouchmove`,e)}get onpointerdown(){return this[k].get(`onpointerdown`)??null}set onpointerdown(e){this[k].set(`onpointerdown`,e)}get onpointerup(){return this[k].get(`onpointerup`)??null}set onpointerup(e){this[k].set(`onpointerup`,e)}get onpointermove(){return this[k].get(`onpointermove`)??null}set onpointermove(e){this[k].set(`onpointermove`,e)}cloneNode(e=!1){return super.cloneNode(e)}get[Symbol.toStringTag](){return`HTMLElement`}},P=class HTMLCanvasElement extends HTMLElement{constructor(...e){super(...e),this.oncontextlost=null,this.oncontextrestored=null,this.onwebglcontextcreationerror=null,this.onwebglcontextlost=null,this.onwebglcontextrestored=null}static{this._contextFactories=new Map}static registerContextFactory(e,t){HTMLCanvasElement._contextFactories.set(e,t)}get width(){let e=this.getAttribute(`width`);return e===null?300:Number(e)}set width(e){this.setAttribute(`width`,String(e))}get height(){let e=this.getAttribute(`height`);return e===null?150:Number(e)}set height(e){this.setAttribute(`height`,String(e))}getContext(e,t){let n=HTMLCanvasElement._contextFactories.get(e);return n?n(this,t):null}toDataURL(e,t){let n=this.getContext(`2d`);return n&&typeof n._toDataURL==`function`?n._toDataURL(e,t):``}toBlob(e,t,n){let r=this.toDataURL(t,n);if(!r){e(null);return}let[i,a]=r.split(`,`),o=i.split(`:`)[1].split(`;`)[0],s=atob(a),c=new Uint8Array(s.length);for(let e=0;e<s.length;e++)c[e]=s.charCodeAt(e);e(new Blob([c],{type:o}))}captureStream(e){return{}}},Oe=class DOMMatrix{constructor(e){this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0,this.m11=1,this.m12=0,this.m13=0,this.m14=0,this.m21=0,this.m22=1,this.m23=0,this.m24=0,this.m31=0,this.m32=0,this.m33=1,this.m34=0,this.m41=0,this.m42=0,this.m43=0,this.m44=1,this.is2D=!0,this.isIdentity=!0,Array.isArray(e)&&(e.length===6?(this.a=this.m11=e[0],this.b=this.m12=e[1],this.c=this.m21=e[2],this.d=this.m22=e[3],this.e=this.m41=e[4],this.f=this.m42=e[5],this.is2D=!0):e.length===16&&(this.m11=e[0],this.m12=e[1],this.m13=e[2],this.m14=e[3],this.m21=e[4],this.m22=e[5],this.m23=e[6],this.m24=e[7],this.m31=e[8],this.m32=e[9],this.m33=e[10],this.m34=e[11],this.m41=e[12],this.m42=e[13],this.m43=e[14],this.m44=e[15],this.a=this.m11,this.b=this.m12,this.c=this.m21,this.d=this.m22,this.e=this.m41,this.f=this.m42,this.is2D=!1),this.isIdentity=this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.e===0&&this.f===0)}multiply(e){let t=this.a*e.a+this.c*e.b,n=this.b*e.a+this.d*e.b,r=this.a*e.c+this.c*e.d,i=this.b*e.c+this.d*e.d,a=this.a*e.e+this.c*e.f+this.e,o=this.b*e.e+this.d*e.f+this.f;return new DOMMatrix([t,n,r,i,a,o])}multiplySelf(e){let t=this.multiply(e);return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.e=t.e,this.f=t.f,this.m11=this.a,this.m12=this.b,this.m21=this.c,this.m22=this.d,this.m41=this.e,this.m42=this.f,this.isIdentity=!1,this}inverse(){let e=this.a*this.d-this.b*this.c;if(e===0)return new DOMMatrix([1,0,0,1,0,0]);let t=1/e;return new DOMMatrix([this.d*t,-this.b*t,-this.c*t,this.a*t,(this.c*this.f-this.d*this.e)*t,(this.b*this.e-this.a*this.f)*t])}translate(e=0,t=0){return this.multiply({a:1,b:0,c:0,d:1,e,f:t})}scale(e=1,t=e){return this.multiply({a:e,b:0,c:0,d:t,e:0,f:0})}};const ke=Oe;function defineGlobal(e,t){Object.defineProperty(globalThis,e,{value:t,writable:!0,configurable:!0})}function defineGlobalIfMissing(e,t){globalThis[e]===void 0&&defineGlobal(e,t)}const Ae={aliceblue:`#f0f8ff`,antiquewhite:`#faebd7`,aqua:`#00ffff`,aquamarine:`#7fffd4`,azure:`#f0ffff`,beige:`#f5f5dc`,bisque:`#ffe4c4`,black:`#000000`,blanchedalmond:`#ffebcd`,blue:`#0000ff`,blueviolet:`#8a2be2`,brown:`#a52a2a`,burlywood:`#deb887`,cadetblue:`#5f9ea0`,chartreuse:`#7fff00`,chocolate:`#d2691e`,coral:`#ff7f50`,cornflowerblue:`#6495ed`,cornsilk:`#fff8dc`,crimson:`#dc143c`,cyan:`#00ffff`,darkblue:`#00008b`,darkcyan:`#008b8b`,darkgoldenrod:`#b8860b`,darkgray:`#a9a9a9`,darkgreen:`#006400`,darkgrey:`#a9a9a9`,darkkhaki:`#bdb76b`,darkmagenta:`#8b008b`,darkolivegreen:`#556b2f`,darkorange:`#ff8c00`,darkorchid:`#9932cc`,darkred:`#8b0000`,darksalmon:`#e9967a`,darkseagreen:`#8fbc8f`,darkslateblue:`#483d8b`,darkslategray:`#2f4f4f`,darkslategrey:`#2f4f4f`,darkturquoise:`#00ced1`,darkviolet:`#9400d3`,deeppink:`#ff1493`,deepskyblue:`#00bfff`,dimgray:`#696969`,dimgrey:`#696969`,dodgerblue:`#1e90ff`,firebrick:`#b22222`,floralwhite:`#fffaf0`,forestgreen:`#228b22`,fuchsia:`#ff00ff`,gainsboro:`#dcdcdc`,ghostwhite:`#f8f8ff`,gold:`#ffd700`,goldenrod:`#daa520`,gray:`#808080`,green:`#008000`,greenyellow:`#adff2f`,grey:`#808080`,honeydew:`#f0fff0`,hotpink:`#ff69b4`,indianred:`#cd5c5c`,indigo:`#4b0082`,ivory:`#fffff0`,khaki:`#f0e68c`,lavender:`#e6e6fa`,lavenderblush:`#fff0f5`,lawngreen:`#7cfc00`,lemonchiffon:`#fffacd`,lightblue:`#add8e6`,lightcoral:`#f08080`,lightcyan:`#e0ffff`,lightgoldenrodyellow:`#fafad2`,lightgray:`#d3d3d3`,lightgreen:`#90ee90`,lightgrey:`#d3d3d3`,lightpink:`#ffb6c1`,lightsalmon:`#ffa07a`,lightseagreen:`#20b2aa`,lightskyblue:`#87cefa`,lightslategray:`#778899`,lightslategrey:`#778899`,lightsteelblue:`#b0c4de`,lightyellow:`#ffffe0`,lime:`#00ff00`,limegreen:`#32cd32`,linen:`#faf0e6`,magenta:`#ff00ff`,maroon:`#800000`,mediumaquamarine:`#66cdaa`,mediumblue:`#0000cd`,mediumorchid:`#ba55d3`,mediumpurple:`#9370db`,mediumseagreen:`#3cb371`,mediumslateblue:`#7b68ee`,mediumspringgreen:`#00fa9a`,mediumturquoise:`#48d1cc`,mediumvioletred:`#c71585`,midnightblue:`#191970`,mintcream:`#f5fffa`,mistyrose:`#ffe4e1`,moccasin:`#ffe4b5`,navajowhite:`#ffdead`,navy:`#000080`,oldlace:`#fdf5e6`,olive:`#808000`,olivedrab:`#6b8e23`,orange:`#ffa500`,orangered:`#ff4500`,orchid:`#da70d6`,palegoldenrod:`#eee8aa`,palegreen:`#98fb98`,paleturquoise:`#afeeee`,palevioletred:`#db7093`,papayawhip:`#ffefd5`,peachpuff:`#ffdab9`,peru:`#cd853f`,pink:`#ffc0cb`,plum:`#dda0dd`,powderblue:`#b0e0e6`,purple:`#800080`,rebeccapurple:`#663399`,red:`#ff0000`,rosybrown:`#bc8f8f`,royalblue:`#4169e1`,saddlebrown:`#8b4513`,salmon:`#fa8072`,sandybrown:`#f4a460`,seagreen:`#2e8b57`,seashell:`#fff5ee`,sienna:`#a0522d`,silver:`#c0c0c0`,skyblue:`#87ceeb`,slateblue:`#6a5acd`,slategray:`#708090`,slategrey:`#708090`,snow:`#fffafa`,springgreen:`#00ff7f`,steelblue:`#4682b4`,tan:`#d2b48c`,teal:`#008080`,thistle:`#d8bfd8`,tomato:`#ff6347`,turquoise:`#40e0d0`,violet:`#ee82ee`,wheat:`#f5deb3`,white:`#ffffff`,whitesmoke:`#f5f5f5`,yellow:`#ffff00`,yellowgreen:`#9acd32`,transparent:`#00000000`};function parseColor(e){if(!e||typeof e!=`string`)return null;let t=e.trim().toLowerCase(),n=Ae[t];if(n)return parseHex(n);if(t.startsWith(`#`))return parseHex(t);let r=t.match(/^rgba?\(\s*(\d+(?:\.\d+)?%?)\s*[,\s]\s*(\d+(?:\.\d+)?%?)\s*[,\s]\s*(\d+(?:\.\d+)?%?)\s*(?:[,/]\s*(\d+(?:\.\d+)?%?))?\s*\)$/);if(r)return{r:parseComponent(r[1],255)/255,g:parseComponent(r[2],255)/255,b:parseComponent(r[3],255)/255,a:r[4]===void 0?1:parseComponent(r[4],1)};let i=t.match(/^hsla?\(\s*(\d+(?:\.\d+)?)\s*[,\s]\s*(\d+(?:\.\d+)?)(%)?\s*[,\s]\s*(\d+(?:\.\d+)?)(%)?\s*(?:[,/]\s*(\d+(?:\.\d+)?%?))?\s*\)$/);if(i){let e=parseFloat(i[1]),t=parseFloat(i[2]),n=i[3]===`%`,r=parseFloat(i[4]),a=i[5]===`%`,o=i[6]===void 0?1:parseComponent(i[6],1);return e>1&&(e/=360),(n||t>1)&&(t/=100),(a||r>1)&&(r/=100),hslToRGBA(e,t,r,Math.max(0,Math.min(1,o)))}return null}function parseHex(e){let t=e.slice(1),n,r,i,a=1;if(t.length===3)n=parseInt(t[0]+t[0],16)/255,r=parseInt(t[1]+t[1],16)/255,i=parseInt(t[2]+t[2],16)/255;else if(t.length===4)n=parseInt(t[0]+t[0],16)/255,r=parseInt(t[1]+t[1],16)/255,i=parseInt(t[2]+t[2],16)/255,a=parseInt(t[3]+t[3],16)/255;else if(t.length===6)n=parseInt(t.slice(0,2),16)/255,r=parseInt(t.slice(2,4),16)/255,i=parseInt(t.slice(4,6),16)/255;else if(t.length===8)n=parseInt(t.slice(0,2),16)/255,r=parseInt(t.slice(2,4),16)/255,i=parseInt(t.slice(4,6),16)/255,a=parseInt(t.slice(6,8),16)/255;else return null;return{r:n,g:r,b:i,a}}function parseComponent(e,t){return e.endsWith(`%`)?parseFloat(e)/100*t:parseFloat(e)}function hue2rgb$1(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}__name$1(hue2rgb$1,`hue2rgb`);function hslToRGBA(e,t,n,r){let i,a,o;if(t===0)i=a=o=n;else{let r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=hue2rgb$1(s,r,e+1/3),a=hue2rgb$1(s,r,e),o=hue2rgb$1(s,r,e-1/3)}return{r:i,g:a,b:o,a:r}}const je={r:0,g:0,b:0,a:1};var CanvasGradient=class{constructor(e,n,r,i,a,o,s){e===`radial`?this._pattern=new t.RadialGradient(n,r,o,i,a,s):this._pattern=new t.LinearGradient(n,r,i,a)}addColorStop(e,t){let n=parseColor(t);n&&this._pattern.addColorStopRGBA(e,n.r,n.g,n.b,n.a)}_getCairoPattern(){return this._pattern}};function quadraticToCubic(e,t,n,r,i,a){return{cp1x:e+2/3*(n-e),cp1y:t+2/3*(r-t),cp2x:i+2/3*(n-i),cp2y:a+2/3*(r-a)}}function computeArcTo(e,t,n,r,i,a,o){let s=e-n,c=t-r,l=i-n,u=a-r,d=Math.sqrt(s*s+c*c),f=Math.sqrt(l*l+u*u);if(d===0||f===0)return null;let p=s/d,m=c/d,h=l/f,g=u/f,_=p*g-m*h;if(Math.abs(_)<1e-10)return null;let v=p*h+m*g,y=Math.acos(Math.max(-1,Math.min(1,v)))/2,b=o/Math.tan(y),x=n+p*b,S=r+m*b,C=n+h*b,w=r+g*b,T=o/Math.sin(y),E=(p+h)/2,D=(m+g)/2,O=Math.sqrt(E*E+D*D),k=n+E/O*T,A=r+D/O*T;return{tx0:x,ty0:S,tx1:C,ty1:w,cx:k,cy:A,startAngle:Math.atan2(S-A,x-k),endAngle:Math.atan2(w-A,C-k),counterclockwise:_>0}}function cairoArcTo(e,t,n,r,i,a,o,s){let c=computeArcTo(t,n,r,i,a,o,s);if(!c){e.lineTo(r,i);return}let{tx0:l,ty0:u,cx:d,cy:f,startAngle:p,endAngle:m,counterclockwise:h}=c;e.lineTo(l,u),h?e.arcNegative(d,f,s,p,m):e.arc(d,f,s,p,m)}function cairoEllipse(e,t,n,r,i,a,o,s,c){e.save(),e.translate(t,n),e.rotate(a),e.scale(r,i),c?e.arcNegative(0,0,1,o,s):e.arc(0,0,1,o,s),e.restore()}function cairoRoundRect(e,t,n,r,i,a){let o,s,c,l;typeof a==`number`?o=s=c=l=a:a.length===1?o=s=c=l=a[0]:a.length===2?(o=c=a[0],s=l=a[1]):a.length===3?(o=a[0],s=l=a[1],c=a[2]):(o=a[0],s=a[1],c=a[2],l=a[3]);let u=Math.min(r/2,i/2);o=Math.min(o,u),s=Math.min(s,u),c=Math.min(c,u),l=Math.min(l,u);let d=Math.PI/2;e.newSubPath(),e.arc(t+o,n+o,o,Math.PI,Math.PI+d),e.arc(t+r-s,n+s,s,-d,0),e.arc(t+r-c,n+i-c,c,0,d),e.arc(t+l,n+i-l,l,d,Math.PI),e.closePath()}const Me={"source-over":2,"source-in":3,"source-out":4,"source-atop":5,"destination-over":7,"destination-in":8,"destination-out":9,"destination-atop":10,lighter:12,copy:1,xor:11,multiply:14,screen:15,overlay:16,darken:17,lighten:18,"color-dodge":19,"color-burn":20,"hard-light":21,"soft-light":22,difference:23,exclusion:24,hue:25,saturation:26,color:27,luminosity:28},Ne={butt:0,round:1,square:2},Pe={miter:0,round:1,bevel:2};var Fe=class Path2D{constructor(e){this._ops=[],e instanceof Path2D&&(this._ops=[...e._ops])}addPath(e){this._ops.push(...e._ops)}moveTo(e,t){this._ops.push({type:`moveTo`,x:e,y:t})}lineTo(e,t){this._ops.push({type:`lineTo`,x:e,y:t})}closePath(){this._ops.push({type:`closePath`})}bezierCurveTo(e,t,n,r,i,a){this._ops.push({type:`bezierCurveTo`,cp1x:e,cp1y:t,cp2x:n,cp2y:r,x:i,y:a})}quadraticCurveTo(e,t,n,r){this._ops.push({type:`quadraticCurveTo`,cpx:e,cpy:t,x:n,y:r})}arc(e,t,n,r,i,a=!1){this._ops.push({type:`arc`,x:e,y:t,radius:n,startAngle:r,endAngle:i,ccw:a})}ellipse(e,t,n,r,i,a,o,s=!1){if(n<0||r<0)throw RangeError(`The radii provided are negative`);this._ops.push({type:`ellipse`,x:e,y:t,rx:n,ry:r,rotation:i,startAngle:a,endAngle:o,ccw:s})}rect(e,t,n,r){this._ops.push({type:`rect`,x:e,y:t,w:n,h:r})}roundRect(e,t,n,r,i=0){this._ops.push({type:`roundRect`,x:e,y:t,w:n,h:r,radii:i})}_replayOnCairo(e){let t=0,n=0;for(let r of this._ops)switch(r.type){case`moveTo`:e.moveTo(r.x,r.y),t=r.x,n=r.y;break;case`lineTo`:e.lineTo(r.x,r.y),t=r.x,n=r.y;break;case`closePath`:e.closePath();break;case`bezierCurveTo`:e.curveTo(r.cp1x,r.cp1y,r.cp2x,r.cp2y,r.x,r.y),t=r.x,n=r.y;break;case`quadraticCurveTo`:{let{cp1x:i,cp1y:a,cp2x:o,cp2y:s}=quadraticToCubic(t,n,r.cpx,r.cpy,r.x,r.y);e.curveTo(i,a,o,s,r.x,r.y),t=r.x,n=r.y;break}case`arc`:r.ccw?e.arcNegative(r.x,r.y,r.radius,r.startAngle,r.endAngle):e.arc(r.x,r.y,r.radius,r.startAngle,r.endAngle);break;case`ellipse`:e.save(),e.translate(r.x,r.y),e.rotate(r.rotation),e.scale(r.rx,r.ry),r.ccw?e.arcNegative(0,0,1,r.startAngle,r.endAngle):e.arc(0,0,1,r.startAngle,r.endAngle),e.restore();break;case`rect`:e.rectangle(r.x,r.y,r.w,r.h);break;case`roundRect`:cairoRoundRect(e,r.x,r.y,r.w,r.h,r.radii);break}}};function asCairoPattern(e){if(!e)return null;let t=e;return typeof t.setFilter!=`function`||typeof t.setExtend!=`function`?null:t}function isPixbufImageSource(e){return typeof e!=`object`||!e?!1:typeof e.isPixbuf==`function`&&e.isPixbuf()}function isCanvasImageSource(e){return typeof e!=`object`||!e?!1:typeof e.getContext==`function`}let Ie=null;function setCanvasPixelBridge(e){Ie=e}function getCanvasPixelBridge(){if(!Ie)throw TypeError(`@gjsify/canvas2d-core: no pixel bridge registered — pixel operations (getImageData / putImageData / drawImage / createPattern) need a platform backend. On GJS, import '@gjsify/canvas2d-core/gdk' (or use '@gjsify/dom-elements' / '@gjsify/canvas2d', which register it for you).`);return Ie}var Le=class CanvasPattern{constructor(e,n){let r=asCairoPattern(new t.SurfacePattern(e));if(!r)throw TypeError(`CanvasPattern: cairo SurfacePattern is missing setExtend at runtime — incompatible Cairo binding`);switch(this._pattern=r,n){case`repeat`:case``:case null:r.setExtend(t.Extend.REPEAT);break;case`repeat-x`:case`repeat-y`:r.setExtend(t.Extend.REPEAT);break;case`no-repeat`:r.setExtend(t.Extend.NONE);break}}static create(e,n){if(isPixbufImageSource(e)){let r=e._pixbuf,i=r.get_width(),a=r.get_height(),o=new t.ImageSurface(t.Format.ARGB32,i,a),s=new t.Context(o);return getCanvasPixelBridge().setSourceImage(s,r,0,0),s.paint(),s.$dispose(),new CanvasPattern(o,n)}if(isCanvasImageSource(e)){let r=e.getContext(`2d`);if(r&&typeof r._getSurface==`function`){let e=r._getSurface(),i=e.getWidth(),a=e.getHeight(),o=new t.ImageSurface(t.Format.ARGB32,i,a),s=new t.Context(o);return s.setSourceSurface(e,0,0),s.paint(),s.$dispose(),new CanvasPattern(o,n)}}return null}_getCairoPattern(){return this._pattern}},OurImageData=class{constructor(e,t,n){if(this.colorSpace=`srgb`,typeof e==`number`)this.width=e,this.height=t,this.data=new Uint8ClampedArray(this.width*this.height*4);else if(this.data=e,this.width=t,this.height=n??this.data.length/(4*this.width),this.data.length!==this.width*this.height*4)throw RangeError(`Source data length ${this.data.length} is not a multiple of (4 * width=${this.width})`)}};const Re={translate(e,t){this._ensureSurface(),this._ctx.translate(e,t)},rotate(e){this._ensureSurface(),this._ctx.rotate(e)},scale(e,t){this._ensureSurface(),this._ctx.scale(e,t)},transform(e,t,n,r,i,a){if(this._ensureSurface(),!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(a))return;let o=i,s=a,c=Math.hypot(e,t),l=Math.hypot(n,r),u=Math.atan2(t,e);this._ctx.translate(o,s),u!==0&&this._ctx.rotate(u),(c!==1||l!==1)&&this._ctx.scale(c,l)},setTransform(e,t,n,r,i,a){if(this._ensureSurface(),typeof e==`object`&&e){let t=e;this._ctx.identityMatrix(),this.transform(t.a??t.m11??1,t.b??t.m12??0,t.c??t.m21??0,t.d??t.m22??1,t.e??t.m41??0,t.f??t.m42??0)}else typeof e==`number`?(this._ctx.identityMatrix(),this.transform(e,t,n,r,i,a)):this._ctx.identityMatrix()},getTransform(){let e=this._ctx.userToDevice(0,0),t=this._ctx.userToDevice(1,0),n=this._ctx.userToDevice(0,1),r=e[0]??0,i=e[1]??0,a=(t[0]??0)-r,o=(t[1]??0)-i,s=(n[0]??0)-r,c=(n[1]??0)-i,l=globalThis.DOMMatrix;return typeof l==`function`?new l([a,o,s,c,r,i]):{a,b:o,c:s,d:c,e:r,f:i,m11:a,m12:o,m13:0,m14:0,m21:s,m22:c,m23:0,m24:0,m31:0,m32:0,m33:1,m34:0,m41:r,m42:i,m43:0,m44:1,is2D:!0,isIdentity:a===1&&o===0&&s===0&&c===1&&r===0&&i===0}},resetTransform(){this._ensureSurface(),this._ctx.identityMatrix()}};function installTransformMethods(e){Object.assign(e,Re)}const ze={beginPath(){this._ensureSurface(),this._ctx.newPath()},moveTo(e,t){this._ensureSurface(),this._ctx.moveTo(e,t)},lineTo(e,t){this._ensureSurface(),this._ctx.lineTo(e,t)},closePath(){this._ensureSurface(),this._ctx.closePath()},bezierCurveTo(e,t,n,r,i,a){this._ensureSurface(),this._ctx.curveTo(e,t,n,r,i,a)},quadraticCurveTo(e,t,n,r){this._ensureSurface();let i,a;this._ctx.hasCurrentPoint()?[i,a]=this._ctx.getCurrentPoint():(i=e,a=t);let{cp1x:o,cp1y:s,cp2x:c,cp2y:l}=quadraticToCubic(i,a,e,t,n,r);this._ctx.curveTo(o,s,c,l,n,r)},arc(e,t,n,r,i,a=!1){if(this._ensureSurface(),Math.abs(i-r)>=2*Math.PI){this._ctx.arc(e,t,n,0,2*Math.PI);return}a?this._ctx.arcNegative(e,t,n,r,i):this._ctx.arc(e,t,n,r,i)},arcTo(e,t,n,r,i){this._ensureSurface();let a,o;this._ctx.hasCurrentPoint()?[a,o]=this._ctx.getCurrentPoint():(a=e,o=t,this._ctx.moveTo(e,t)),cairoArcTo(this._ctx,a,o,e,t,n,r,i)},ellipse(e,t,n,r,i,a,o,s=!1){if(this._ensureSurface(),n<0||r<0)throw RangeError(`The radii provided are negative`);cairoEllipse(this._ctx,e,t,n,r,i,a,o,s)},rect(e,t,n,r){this._ensureSurface(),this._ctx.rectangle(e,t,n,r)},roundRect(e,t,n,r,i=0){this._ensureSurface(),cairoRoundRect(this._ctx,e,t,n,r,i)}};function installPathMethods(e){Object.assign(e,ze)}function getDrawImageSource(e){if(isPixbufImageSource(e)){let t=e._pixbuf;return{pixbuf:t,imgWidth:t.get_width(),imgHeight:t.get_height()}}if(isCanvasImageSource(e)){let t=e.width??0,n=e.height??0;if(!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0)return null;let r=e.getContext(`2d`);if(r&&typeof r._getSurface==`function`){let e=r._getSurface();e.flush();let i=getCanvasPixelBridge().imageFromSurface(e,0,0,t,n);if(i)return{pixbuf:i,imgWidth:t,imgHeight:n}}}return null}const Be={fill(e,n){this._ensureSurface(),this._applyCompositing(),this._applyFillStyle();let r;e instanceof Fe?(this._ctx.newPath(),e._replayOnCairo(this._ctx),r=n):r=e,this._ctx.setFillRule(r===`evenodd`?t.FillRule.EVEN_ODD:t.FillRule.WINDING),this._ctx.fillPreserve()},stroke(e){this._ensureSurface(),this._applyCompositing(),this._applyStrokeStyle(),this._applyLineStyle(),e instanceof Fe&&(this._ctx.newPath(),e._replayOnCairo(this._ctx)),this._ctx.strokePreserve()},fillRect(e,t,n,r){this._ensureSurface(),this._applyCompositing();let i=this._ctx.copyPath();this._hasShadow()&&this._renderShadow(()=>{this._ctx.newPath(),this._ctx.rectangle(e,t,n,r),this._ctx.fill()}),this._applyFillStyle(),this._ctx.newPath(),this._ctx.rectangle(e,t,n,r),this._ctx.fill(),this._ctx.newPath(),this._ctx.appendPath(i)},strokeRect(e,t,n,r){this._ensureSurface(),this._applyCompositing();let i=this._ctx.copyPath();this._hasShadow()&&this._renderShadow(()=>{this._ctx.newPath(),this._ctx.rectangle(e,t,n,r),this._ctx.stroke()}),this._applyStrokeStyle(),this._applyLineStyle(),this._ctx.newPath(),this._ctx.rectangle(e,t,n,r),this._ctx.stroke(),this._ctx.newPath(),this._ctx.appendPath(i)},clearRect(e,n,r,i){this._ensureSurface();let a=this._ctx.copyPath();this._ctx.save(),this._ctx.setOperator(t.Operator.CLEAR),this._ctx.newPath(),this._ctx.rectangle(e,n,r,i),this._ctx.fill(),this._ctx.restore(),this._ctx.newPath(),this._ctx.appendPath(a)},clip(e,n){this._ensureSurface();let r;e instanceof Fe?(this._ctx.newPath(),e._replayOnCairo(this._ctx),r=n):r=e,this._ctx.setFillRule(r===`evenodd`?t.FillRule.EVEN_ODD:t.FillRule.WINDING),this._ctx.clip()},isPointInPath(e,n,r,i){this._ensureSurface();let a,o,s;return e instanceof Fe?(this._ctx.newPath(),e._replayOnCairo(this._ctx),a=n,o=r,s=i):(a=e,o=n,s=r),this._ctx.setFillRule(s===`evenodd`?t.FillRule.EVEN_ODD:t.FillRule.WINDING),this._ctx.inFill(a,o)},isPointInStroke(e,t,n){return this._ensureSurface(),this._applyLineStyle(),e instanceof Fe?(this._ctx.newPath(),e._replayOnCairo(this._ctx),this._ctx.inStroke(t,n)):this._ctx.inStroke(e,t)},drawImage(e,n,r,i,a,o,s,c,l){this._ensureSurface(),this._applyCompositing();let u,d,f,p,m,h,g,_,v=getDrawImageSource(e);if(!v)return;let{pixbuf:y,imgWidth:b,imgHeight:x}=v;if(i===void 0?(u=0,d=0,f=b,p=x,m=n,h=r,g=b,_=x):o===void 0?(u=0,d=0,f=b,p=x,m=n,h=r,g=i,_=a):(u=n,d=r,f=i,p=a,m=o,h=s,g=c,_=l),!Number.isFinite(u)||!Number.isFinite(d)||!Number.isFinite(f)||!Number.isFinite(p)||!Number.isFinite(m)||!Number.isFinite(h)||!Number.isFinite(g)||!Number.isFinite(_)||f===0||p===0||g===0||_===0)return;this._ctx.save(),this._ctx.rectangle(m,h,g,_),this._ctx.clip(),this._ctx.translate(m,h),this._ctx.scale(g/f,_/p),this._ctx.translate(-u,-d),getCanvasPixelBridge().setSourceImage(this._ctx,y,0,0);let S=asCairoPattern(this._ctx.getSource?.());if(S){let e;e=this._state.imageSmoothingEnabled?this._state.imageSmoothingQuality===`high`?t.Filter.BEST:t.Filter.BILINEAR:t.Filter.NEAREST,S.setFilter(e)}this._state.globalAlpha<1?this._ctx.paintWithAlpha(this._state.globalAlpha):this._ctx.paint(),this._ctx.restore()}};function installDrawingMethods$1(e){Object.assign(e,Be)}__name$1(installDrawingMethods$1,`installDrawingMethods`);const Ve={createImageData(e,t){return typeof e==`number`?new OurImageData(Math.abs(e),Math.abs(t)):new OurImageData(e.width,e.height)},getImageData(e,t,n,r){this._ensureSurface(),this._surface.flush();let i=getCanvasPixelBridge().imageFromSurface(this._surface,e,t,n,r);if(!i)return new OurImageData(n,r);let a=i.get_pixels(),o=i.get_has_alpha(),s=i.get_rowstride(),c=i.get_n_channels(),l=new Uint8ClampedArray(n*r*4);for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=e*s+t*c,i=(e*n+t)*4;l[i]=a[r],l[i+1]=a[r+1],l[i+2]=a[r+2],l[i+3]=o?a[r+3]:255}return new OurImageData(l,n,r)},putImageData(e,n,r,i,a,o,s){this._ensureSurface();let c=i??0,l=a??0,u=o??e.width,d=s??e.height,f=e.data,p=e.width,m=new Uint8Array(u*d*4);for(let e=0;e<d;e++)for(let t=0;t<u;t++){let n=((l+e)*p+(c+t))*4,r=(e*u+t)*4;m[r]=f[n],m[r+1]=f[n+1],m[r+2]=f[n+2],m[r+3]=f[n+3]}this._ctx.save(),this._ctx.setOperator(t.Operator.SOURCE),getCanvasPixelBridge().setSourcePixels(this._ctx,m,u,d,n+c,r+l),this._ctx.rectangle(n+c,r+l,u,d),this._ctx.fill(),this._ctx.restore()}};function installPixelMethods(e){Object.assign(e,Ve)}const He=e(import.meta.url);let Ue;function load$16(){return Ue===void 0&&(Ue=He(`@gjsify/node-gi/gi`).requireGi(`Pango`)),Ue}__name$1(load$16,`load`);var We=new Proxy(Object.create(null),{get(e,t){return load$16()[t]},has(e,t){return t in load$16()}});const Ge=e(import.meta.url);let Ke;function load$15(){return Ke===void 0&&(Ke=Ge(`@gjsify/node-gi/gi`).requireGi(`PangoCairo`)),Ke}__name$1(load$15,`load`);var qe=new Proxy(Object.create(null),{get(e,t){return load$15()[t]},has(e,t){return t in load$15()}});function parseFontToDescription(e){let t=e.match(/^\s*(italic|oblique|normal)?\s*(small-caps|normal)?\s*(bold|bolder|lighter|[1-9]00|normal)?\s*(\d+(?:\.\d+)?)(px|pt|em|rem|%)?\s*(?:\/\S+)?\s*(.+)?$/i);if(!t)return We.font_description_from_string(e);let n=t[1]||``,r=t[3]||``,i=parseFloat(t[4])||10,a=(t[5]||`px`).toLowerCase(),o=(t[6]||`sans-serif`).replace(/['"]/g,``).trim();a===`pt`?i=i*96/72:a===`em`||a===`rem`?i*=16:a===`%`&&(i=i/100*16);let s=o;n===`italic`?s+=` Italic`:n===`oblique`&&(s+=` Oblique`),r===`bold`||r===`bolder`||parseInt(r)>=600?s+=` Bold`:(r===`lighter`||parseInt(r)>0&&parseInt(r)<=300)&&(s+=` Light`);let c=We.font_description_from_string(s);return c.set_absolute_size(i*We.SCALE),c}function createTextLayout(e,t){let n=qe.create_layout(e._ctx);n.set_text(t,-1),n.get_context().set_base_dir(We.Direction.LTR),n.context_changed();let r=parseFontToDescription(e._state.font);return n.set_font_description(r),n}function getTextAlignOffset(e,t){let[,n]=t.get_pixel_extents(),r=n.width;switch(e._state.textAlign){case`center`:return-r/2;case`right`:case`end`:return-r;default:return 0}}function getTextBaselineOffset(e,t){let n=t.get_font_description()||parseFontToDescription(e._state.font),r=t.get_context().get_metrics(n,null),i=r.get_ascent()/We.SCALE,a=r.get_descent()/We.SCALE,o=i+a;switch(e._state.textBaseline){case`top`:return 0;case`hanging`:return-(i*.2);case`middle`:return-(o/2);case`alphabetic`:return-i;case`ideographic`:return-(i+a*.5);case`bottom`:return-o;default:return-i}}const Je={fillText(e,n,r,i){this._ensureSurface(),this._applyCompositing();let a=createTextLayout(this,e),o=getTextAlignOffset(this,a),s=getTextBaselineOffset(this,a);if(this._hasShadow()){let e=parseColor(this._state.shadowColor);if(e){let[i,c]=this._deviceToUserDistance(this._state.shadowOffsetX,this._state.shadowOffsetY),l=this._state.shadowBlur,u;if(l>0){let[t]=this._deviceToUserDistance(l,0),[,n]=this._deviceToUserDistance(0,l);u=[[i,c,e.a],[i+t,c,e.a*.5],[i-t,c,e.a*.5],[i,c+n,e.a*.5],[i,c-n,e.a*.5]]}else u=[[i,c,e.a]];let d=this._state.imageSmoothingEnabled?t.Antialias.DEFAULT:t.Antialias.NONE;for(let[t,i,c]of u)this._ctx.save(),this._ctx.setAntialias(d),this._ctx.setSourceRGBA(e.r,e.g,e.b,c),this._ctx.moveTo(n+o+t,r+s+i),qe.show_layout(this._ctx,a),this._ctx.restore()}}this._applyFillStyle(),this._ctx.save(),this._ctx.setAntialias(this._state.imageSmoothingEnabled?t.Antialias.DEFAULT:t.Antialias.NONE),this._ctx.moveTo(n+o,r+s),qe.show_layout(this._ctx,a),this._ctx.restore()},strokeText(e,n,r,i){this._ensureSurface(),this._applyCompositing(),this._applyStrokeStyle(),this._applyLineStyle();let a=createTextLayout(this,e),o=getTextAlignOffset(this,a),s=getTextBaselineOffset(this,a);this._ctx.save(),this._ctx.setAntialias(this._state.imageSmoothingEnabled?t.Antialias.DEFAULT:t.Antialias.NONE),this._ctx.moveTo(n+o,r+s),qe.layout_path(this._ctx,a),this._ctx.stroke(),this._ctx.restore()},measureText(e){this._ensureSurface();let t=createTextLayout(this,e),[n,r]=t.get_pixel_extents(),i=t.get_baseline()/We.SCALE,a=Math.max(0,i-n.y),o=Math.max(0,n.y+n.height-i),s=t.get_font_description()||parseFontToDescription(this._state.font),c=t.get_context().get_metrics(s,null),l=c.get_ascent()/We.SCALE,u=c.get_descent()/We.SCALE;return{width:r.width,actualBoundingBoxAscent:a,actualBoundingBoxDescent:o,actualBoundingBoxLeft:Math.max(0,-n.x),actualBoundingBoxRight:n.x+n.width,fontBoundingBoxAscent:l,fontBoundingBoxDescent:u,alphabeticBaseline:0,emHeightAscent:l,emHeightDescent:u,hangingBaseline:l*.8,ideographicBaseline:-u}}};function installTextMethods(e){Object.assign(e,Je)}const Ye={createLinearGradient(e,t,n,r){return new CanvasGradient(`linear`,e,t,n,r)},createRadialGradient(e,t,n,r,i,a){return new CanvasGradient(`radial`,e,t,r,i,n,a)},createPattern(e,t){return Le.create(e,t)}};function installFactoryMethods(e){Object.assign(e,Ye)}function installAllContextMethods$1(e){installTransformMethods(e),installPathMethods(e),installDrawingMethods$1(e),installPixelMethods(e),installTextMethods(e),installFactoryMethods(e)}__name$1(installAllContextMethods$1,`installAllContextMethods`);function createDefaultState(){return{fillStyle:`#000000`,fillColor:{...je},strokeStyle:`#000000`,strokeColor:{...je},lineWidth:1,lineCap:`butt`,lineJoin:`miter`,miterLimit:10,lineDash:[],lineDashOffset:0,globalAlpha:1,globalCompositeOperation:`source-over`,shadowColor:`rgba(0, 0, 0, 0)`,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,font:`10px sans-serif`,textAlign:`start`,textBaseline:`alphabetic`,direction:`ltr`,imageSmoothingEnabled:!0,imageSmoothingQuality:`low`}}function cloneState(e){return{...e,fillColor:{...e.fillColor},strokeColor:{...e.strokeColor},lineDash:[...e.lineDash]}}const Xe=e(import.meta.url);let Ze;function load$14(){return Ze===void 0&&(Ze=Xe(`@gjsify/node-gi/gi`).requireGi(`Gio`)),Ze}__name$1(load$14,`load`);var Qe=new Proxy(Object.create(null),{get(e,t){return load$14()[t]},has(e,t){return t in load$14()}});const $e=e(import.meta.url);let et;function load$13(){return et===void 0&&(et=$e(`@gjsify/node-gi/gi`).requireGi(`GLib`)),et}__name$1(load$13,`load`);var tt=new Proxy(Object.create(null),{get(e,t){return load$13()[t]},has(e,t){return t in load$13()}}),CanvasRenderingContext2D=class{constructor(e,n){this._stateStack=[],this.canvas=e,this._surfaceWidth=e.width||300,this._surfaceHeight=e.height||150,this._surface=new t.ImageSurface(t.Format.ARGB32,this._surfaceWidth,this._surfaceHeight),this._ctx=new t.Context(this._surface),this._state=createDefaultState()}_ensureSurface(){let e=this.canvas.width||300,n=this.canvas.height||150;(e!==this._surfaceWidth||n!==this._surfaceHeight)&&(this._ctx.$dispose(),this._surface.finish(),this._surfaceWidth=e,this._surfaceHeight=n,this._surface=new t.ImageSurface(t.Format.ARGB32,e,n),this._ctx=new t.Context(this._surface),this._stateStack=[])}_resetState(){this._state=createDefaultState(),this._stateStack=[]}_applyFillStyle(){let e=this._state.fillStyle;if(typeof e==`string`){let e=this._state.fillColor,t=e.a*this._state.globalAlpha;this._ctx.setSourceRGBA(e.r,e.g,e.b,t)}else e instanceof CanvasGradient?this._ctx.setSource(e._getCairoPattern()):e instanceof Le&&(this._ctx.setSource(e._getCairoPattern()),this._applyPatternFilter())}_applyStrokeStyle(){let e=this._state.strokeStyle;if(typeof e==`string`){let e=this._state.strokeColor,t=e.a*this._state.globalAlpha;this._ctx.setSourceRGBA(e.r,e.g,e.b,t)}else e instanceof CanvasGradient?this._ctx.setSource(e._getCairoPattern()):e instanceof Le&&(this._ctx.setSource(e._getCairoPattern()),this._applyPatternFilter())}_applyPatternFilter(){let e=asCairoPattern(this._ctx.getSource?.());if(!e)return;let n;n=this._state.imageSmoothingEnabled?this._state.imageSmoothingQuality===`high`?t.Filter.BEST:t.Filter.BILINEAR:t.Filter.NEAREST,e.setFilter(n)}_applyLineStyle(){this._ctx.setLineWidth(this._state.lineWidth),this._ctx.setLineCap(Ne[this._state.lineCap]),this._ctx.setLineJoin(Pe[this._state.lineJoin]),this._ctx.setMiterLimit(this._state.miterLimit),this._ctx.setDash(this._state.lineDash,this._state.lineDashOffset)}_applyCompositing(){let e=Me[this._state.globalCompositeOperation];e!==void 0&&this._ctx.setOperator(e)}_getSurface(){return this._surface}_hasShadow(){if(this._state.shadowBlur===0&&this._state.shadowOffsetX===0&&this._state.shadowOffsetY===0)return!1;let e=parseColor(this._state.shadowColor);return e!==null&&e.a>0}_deviceToUserDistance(e,t){let n=this._ctx.userToDevice(0,0),r=this._ctx.userToDevice(1,0),i=this._ctx.userToDevice(0,1),a=(r[0]??0)-(n[0]??0),o=(r[1]??0)-(n[1]??0),s=(i[0]??0)-(n[0]??0),c=(i[1]??0)-(n[1]??0),l=a*c-o*s;return Math.abs(l)<1e-10?[e,t]:[(c*e-s*t)/l,(-o*e+a*t)/l]}_renderShadow(e){}save(){this._ensureSurface(),this._stateStack.push(cloneState(this._state)),this._ctx.save()}restore(){this._ensureSurface();let e=this._stateStack.pop();e&&(this._state=e,this._ctx.restore())}get fillStyle(){return this._state.fillStyle}set fillStyle(e){if(typeof e==`string`){let t=parseColor(e);t&&(this._state.fillStyle=e,this._state.fillColor=t)}else this._state.fillStyle=e}get strokeStyle(){return this._state.strokeStyle}set strokeStyle(e){if(typeof e==`string`){let t=parseColor(e);t&&(this._state.strokeStyle=e,this._state.strokeColor=t)}else this._state.strokeStyle=e}get lineWidth(){return this._state.lineWidth}set lineWidth(e){e>0&&isFinite(e)&&(this._state.lineWidth=e)}get lineCap(){return this._state.lineCap}set lineCap(e){(e===`butt`||e===`round`||e===`square`)&&(this._state.lineCap=e)}get lineJoin(){return this._state.lineJoin}set lineJoin(e){(e===`miter`||e===`round`||e===`bevel`)&&(this._state.lineJoin=e)}get miterLimit(){return this._state.miterLimit}set miterLimit(e){e>0&&isFinite(e)&&(this._state.miterLimit=e)}get globalAlpha(){return this._state.globalAlpha}set globalAlpha(e){e>=0&&e<=1&&isFinite(e)&&(this._state.globalAlpha=e)}get globalCompositeOperation(){return this._state.globalCompositeOperation}set globalCompositeOperation(e){Me[e]!==void 0&&(this._state.globalCompositeOperation=e)}get imageSmoothingEnabled(){return this._state.imageSmoothingEnabled}set imageSmoothingEnabled(e){this._state.imageSmoothingEnabled=!!e}get imageSmoothingQuality(){return this._state.imageSmoothingQuality}set imageSmoothingQuality(e){(e===`low`||e===`medium`||e===`high`)&&(this._state.imageSmoothingQuality=e)}setLineDash(e){e.some(e=>e<0||!isFinite(e))||(this._state.lineDash=[...e])}getLineDash(){return[...this._state.lineDash]}get lineDashOffset(){return this._state.lineDashOffset}set lineDashOffset(e){isFinite(e)&&(this._state.lineDashOffset=e)}get shadowColor(){return this._state.shadowColor}set shadowColor(e){this._state.shadowColor=e}get shadowBlur(){return this._state.shadowBlur}set shadowBlur(e){e>=0&&isFinite(e)&&(this._state.shadowBlur=e)}get shadowOffsetX(){return this._state.shadowOffsetX}set shadowOffsetX(e){isFinite(e)&&(this._state.shadowOffsetX=e)}get shadowOffsetY(){return this._state.shadowOffsetY}set shadowOffsetY(e){isFinite(e)&&(this._state.shadowOffsetY=e)}get font(){return this._state.font}set font(e){this._state.font=e}get textAlign(){return this._state.textAlign}set textAlign(e){this._state.textAlign=e}get textBaseline(){return this._state.textBaseline}set textBaseline(e){this._state.textBaseline=e}get direction(){return this._state.direction}set direction(e){this._state.direction=e}_toDataURL(e,t){this._surface.flush();let[,n]=tt.file_open_tmp(`canvas-XXXXXX.png`);try{this._surface.writeToPNG(n);let[,e]=Qe.File.new_for_path(n).load_contents(null);return`data:image/png;base64,${tt.base64_encode(e)}`}finally{tt.unlink(n)}}_dispose(){this._ctx.$dispose(),this._surface.finish()}};installAllContextMethods$1(CanvasRenderingContext2D.prototype);const nt=e(import.meta.url);let rt;function load$12(){return rt===void 0&&(rt=nt(`@gjsify/node-gi/gi`).requireGi(`Gdk`,`4.0`)),rt}__name$1(load$12,`load`);var it=new Proxy(Object.create(null),{get(e,t){return load$12()[t]},has(e,t){return t in load$12()}});const at=e(import.meta.url);let ot;function load$11(){return ot===void 0&&(ot=at(`@gjsify/node-gi/gi`).requireGi(`GdkPixbuf`)),ot}__name$1(load$11,`load`);var st=new Proxy(Object.create(null),{get(e,t){return load$11()[t]},has(e,t){return t in load$11()}});setCanvasPixelBridge({imageFromSurface(e,t,n,r,i){return it.pixbuf_get_from_surface(e,t,n,r,i)},setSourceImage(e,t,n,r){it.cairo_set_source_pixbuf(e,t,n,r)},setSourcePixels(e,t,n,r,i,a){let o=st.Pixbuf.new_from_bytes(t,st.Colorspace.RGB,!0,8,n,r,n*4);it.cairo_set_source_pixbuf(e,o,i,a)}}),defineGlobal(`HTMLCanvasElement`,P),defineGlobal(`CanvasRenderingContext2D`,CanvasRenderingContext2D),defineGlobal(`DOMMatrix`,Oe),defineGlobal(`DOMMatrixReadOnly`,ke);const ct=Symbol.for(`gjsify_canvas2d_context`);P.registerContextFactory(`2d`,(e,t)=>{let n=e,r=n[ct];if(r)return r;let i=new CanvasRenderingContext2D(e,t);return n[ct]=i,i});var CharacterData=class extends Se{constructor(e=``){super(),this[y]=j.TEXT_NODE,this._data=e}get data(){return this._data}set data(e){this._data=e}get textContent(){return this._data}set textContent(e){this._data=e}get nodeValue(){return this._data}set nodeValue(e){this._data=e}get length(){return this._data.length}appendData(e){this._data+=e}deleteData(e,t){this._data=this._data.substring(0,e)+this._data.substring(e+t)}insertData(e,t){this._data=this._data.substring(0,e)+t+this._data.substring(e)}replaceData(e,t,n){this._data=this._data.substring(0,e)+n+this._data.substring(e+t)}substringData(e,t){return this._data.substring(e,e+t)}cloneNode(e=!1){return new this.constructor(this._data)}get[Symbol.toStringTag](){return`CharacterData`}},lt=class Comment extends CharacterData{constructor(e=``){super(e),this[y]=j.COMMENT_NODE}get nodeName(){return`#comment`}cloneNode(e=!1){return new Comment(this.data)}get[Symbol.toStringTag](){return`Comment`}},ut=class Text extends CharacterData{constructor(e=``){super(e),this[y]=j.TEXT_NODE}get nodeName(){return`#text`}get wholeText(){let e=this.data,t=this.previousSibling;for(;t&&t instanceof Text;)e=t.data+e,t=t.previousSibling;let n=this.nextSibling;for(;n&&n instanceof Text;)e+=n.data,n=n.nextSibling;return e}splitText(e){let t=this.data.substring(e);this.data=this.data.substring(0,e);let n=new Text(t);return this.parentNode&&this.parentNode.insertBefore(n,this.nextSibling),n}cloneNode(e=!1){return new Text(this.data)}get[Symbol.toStringTag](){return`Text`}},dt=class DocumentFragment extends Se{constructor(){super(),this[y]=j.DOCUMENT_FRAGMENT_NODE}get nodeName(){return`#document-fragment`}get children(){return this[S]}get childElementCount(){return this[S].length}get firstElementChild(){return this[S][0]??null}get lastElementChild(){let e=this[S];return e[e.length-1]??null}get textContent(){let e=``;for(let t of this.childNodes)t.textContent!==null&&(e+=t.textContent);return e}set textContent(e){for(;this.firstChild;)this.removeChild(this.firstChild);e&&this.appendChild(new ut(e))}append(...e){for(let t of e)typeof t==`string`?this.appendChild(new ut(t)):this.appendChild(t)}prepend(...e){let t=this.firstChild;for(let n of e)typeof n==`string`?this.insertBefore(new ut(n),t):this.insertBefore(n,t)}replaceChildren(...e){for(;this.firstChild;)this.removeChild(this.firstChild);this.append(...e)}getElementById(e){for(let t of this.children){if(t.id===e)return t;let n=this._findById(t,e);if(n)return n}return null}_findById(e,t){for(let n of e.children){if(n.id===t)return n;let e=this._findById(n,t);if(e)return e}return null}cloneNode(e=!1){let t=new DocumentFragment;if(e)for(let e of this.childNodes)t.appendChild(e.cloneNode(!0));return t}get[Symbol.toStringTag](){return`DocumentFragment`}};const ft=e(import.meta.url);let pt;function load$10(){return pt===void 0&&(pt=ft(`@gjsify/node-gi/gi`).requireGi(`GLib`,`2.0`)),pt}__name$1(load$10,`load`);var mt=new Proxy(Object.create(null),{get(e,t){return load$10()[t]},has(e,t){return t in load$10()}}),ht=mt;const gt=e(import.meta.url);let _t;function load$9(){return _t===void 0&&(_t=gt(`@gjsify/node-gi/gi`).requireGi(`Gio`,`2.0`)),_t}__name$1(load$9,`load`);var vt=new Proxy(Object.create(null),{get(e,t){return load$9()[t]},has(e,t){return t in load$9()}}),yt=vt;const bt=e(import.meta.url);let xt;function load$8(){return xt===void 0&&(xt=bt(`@gjsify/node-gi/gi`).requireGi(`GdkPixbuf`,`2.0`)),xt}__name$1(load$8,`load`);var St=new Proxy(Object.create(null),{get(e,t){return load$8()[t]},has(e,t){return t in load$8()}}),Ct=St,HTMLImageElement$1=class extends HTMLElement{static{__name$1(this,`HTMLImageElement`)}constructor(){super(),this._complete=!1,this._naturalHeight=0,this._naturalWidth=0,this[w]=`IMG`,this[T]=`img`,this[E]=Ce.html}get complete(){return this._complete}get naturalHeight(){return this._naturalHeight}get naturalWidth(){return this._naturalWidth}get currentSrc(){return this.src}get x(){return 0}get y(){return 0}get alt(){return this.getAttribute(`alt`)??``}set alt(e){this.setAttribute(`alt`,e)}get crossOrigin(){return this.getAttribute(`crossorigin`)}set crossOrigin(e){e===null?this.removeAttribute(`crossorigin`):this.setAttribute(`crossorigin`,e)}get decoding(){return this.getAttribute(`decoding`)??`auto`}set decoding(e){this.setAttribute(`decoding`,e)}get loading(){let e=this.getAttribute(`loading`);return e===`lazy`||e===`eager`?e:`auto`}set loading(e){this.setAttribute(`loading`,e)}get referrerPolicy(){return this.getAttribute(`referrerpolicy`)??``}set referrerPolicy(e){this.setAttribute(`referrerpolicy`,e)}get sizes(){return this.getAttribute(`sizes`)??``}set sizes(e){this.setAttribute(`sizes`,e)}get src(){return this.getAttribute(`src`)??``}set src(e){this.setAttribute(`src`,e);let t=globalThis.__GJSIFY_DEBUG_IMG===!0;if(e.startsWith(`data:`)){let n=e.indexOf(`,`);if(n===-1){this._complete=!0,this.dispatchEvent(new Event(`error`));return}let r=e.slice(5,n),i=e.slice(n+1),a=r.includes(`;base64`);try{let e;e=a?ht.base64_decode(i):new TextEncoder().encode(decodeURIComponent(i));let n=ht.Bytes.new(e),r=yt.MemoryInputStream.new_from_bytes(n);this._pixbuf=Ct.Pixbuf.new_from_stream(r,null),this._naturalWidth=this._pixbuf.get_width(),this._naturalHeight=this._pixbuf.get_height(),this._complete=!0,t&&console.log(`[img] ok data: (${this._naturalWidth}x${this._naturalHeight})`),this.dispatchEvent(new Event(`load`))}catch(e){t&&console.warn(`[img] error data:: ${e instanceof Error?e.message:String(e)}`),this._complete=!0,this.dispatchEvent(new Event(`error`))}return}let r;if(e.startsWith(`file://`))r=ht.filename_from_uri(e)[0];else if(e.startsWith(`http://`)||e.startsWith(`https://`)){this._complete=!0,this.dispatchEvent(new Event(`error`));return}else{let t=ht.path_get_dirname(n.programInvocationName);r=ht.build_filenamev([t,e])}try{t&&console.log(`[img] load ${r}`),this._pixbuf=Ct.Pixbuf.new_from_file(r),this._naturalWidth=this._pixbuf.get_width(),this._naturalHeight=this._pixbuf.get_height(),this._complete=!0,t&&console.log(`[img] ok ${r} (${this._naturalWidth}x${this._naturalHeight})`),this.dispatchEvent(new Event(`load`))}catch(e){t&&console.warn(`[img] error ${r}: ${e instanceof Error?e.message:String(e)}`),this._complete=!0,this.dispatchEvent(new Event(`error`))}}get srcset(){return this.getAttribute(`srcset`)??``}set srcset(e){this.setAttribute(`srcset`,e)}get useMap(){return this.getAttribute(`usemap`)??``}set useMap(e){this.setAttribute(`usemap`,e)}get height(){if(this._pixbuf)return this._pixbuf.get_height();let e=this.getAttribute(`height`);return e===null?0:Number(e)}set height(e){this.setAttribute(`height`,String(e))}get width(){if(this._pixbuf)return this._pixbuf.get_width();let e=this.getAttribute(`width`);return e===null?0:Number(e)}set width(e){this.setAttribute(`width`,String(e))}get isMap(){return this.hasAttribute(`ismap`)}set isMap(e){e?this.setAttribute(`ismap`,``):this.removeAttribute(`ismap`)}decode(){return Promise.resolve()}cloneNode(e=!1){return super.cloneNode(e)}getImageData(){if(!this._pixbuf)return null;let e=this._pixbuf.get_has_alpha()?this._pixbuf:this._pixbuf.add_alpha(!1,0,0,0)??this._pixbuf;return{colorSpace:`srgb`,data:new Uint8ClampedArray(e.get_pixels()),height:e.get_height(),width:e.get_width()}}isPixbuf(){return!!this._pixbuf}get[Symbol.toStringTag](){return`HTMLImageElement`}},HTMLMediaElement=class extends HTMLElement{constructor(...e){super(...e),this._src=``,this._srcObject=null,this.currentTime=0,this.duration=NaN,this.paused=!0,this.ended=!1,this.volume=1,this.muted=!1,this.defaultMuted=!1,this.loop=!1,this.autoplay=!1,this.preload=``,this.playbackRate=1,this.defaultPlaybackRate=1,this.readyState=0,this.networkState=0}get buffered(){return{length:0,start:()=>0,end:()=>0}}get seekable(){return{length:0,start:()=>0,end:()=>0}}get played(){return{length:0,start:()=>0,end:()=>0}}get src(){return this._src}set src(e){this._src=e,this._srcObject=null,this.dispatchEvent(new Event(`srcchange`))}get srcObject(){return this._srcObject}set srcObject(e){this._srcObject=e,this._src=``,this.dispatchEvent(new Event(`srcobjectchange`))}play(){return this.paused=!1,this.ended=!1,this.dispatchEvent(new Event(`play`)),Promise.resolve()}pause(){this.paused=!0,this.dispatchEvent(new Event(`pause`))}load(){this.readyState=0,this.networkState=2,this.dispatchEvent(new Event(`loadstart`))}canPlayType(e){return``}static{this.HAVE_NOTHING=0}static{this.HAVE_METADATA=1}static{this.HAVE_CURRENT_DATA=2}static{this.HAVE_FUTURE_DATA=3}static{this.HAVE_ENOUGH_DATA=4}static{this.NETWORK_EMPTY=0}static{this.NETWORK_IDLE=1}static{this.NETWORK_LOADING=2}static{this.NETWORK_NO_SOURCE=3}get[Symbol.toStringTag](){return`HTMLMediaElement`}};const wt=1e9;function secondsToGstTime(e){return BigInt(Math.round(e*wt))}function gstTimeToSeconds(e){return Number(e)/wt}var HTMLVideoElement$1=class extends HTMLMediaElement{static{__name$1(this,`HTMLVideoElement`)}constructor(){super(),this._pipeline=null,this._videoWidth=0,this._videoHeight=0,this.poster=``,this[w]=`VIDEO`,this[T]=`video`,this[E]=Ce.html;let e=this;Object.defineProperty(this,"paused",{get(){if(!e._pipeline)return!0;let[,t]=e._pipeline.get_state(0n);return t!==4},configurable:!0,enumerable:!0}),Object.defineProperty(this,"currentTime",{get(){if(!e._pipeline)return 0;let[t,n]=e._pipeline.query_position(3);return t?gstTimeToSeconds(n):0},set(t){e._pipeline?.seek(1,3,5,1,secondsToGstTime(t),0,-1n)},configurable:!0,enumerable:!0}),Object.defineProperty(this,"duration",{get(){if(!e._pipeline)return NaN;let[t,n]=e._pipeline.query_duration(3);return t&&Number(n)>0?gstTimeToSeconds(n):NaN},configurable:!0,enumerable:!0}),Object.defineProperty(this,"volume",{get(){return e._playbin()?.volume??1},set(t){let n=e._playbin();n&&(n.volume=Math.max(0,Math.min(1,t)))},configurable:!0,enumerable:!0}),Object.defineProperty(this,"muted",{get(){return e._playbin()?.mute??!1},set(t){let n=e._playbin();n&&(n.mute=t)},configurable:!0,enumerable:!0})}async play(){this._pipeline?.set_state(4),this.dispatchEvent(new Event(`play`)),this.dispatchEvent(new Event(`playing`))}pause(){this._pipeline?.set_state(3),this.dispatchEvent(new Event(`pause`))}get videoWidth(){return this._videoWidth}set videoWidth(e){this._videoWidth=e}get videoHeight(){return this._videoHeight}set videoHeight(e){this._videoHeight=e}get[Symbol.toStringTag](){return`HTMLVideoElement`}_playbin(){return this._pipeline?.get_by_name(`playbin`)??null}};const Tt=new class Document extends Se{static{this._elementFactories=new Map}constructor(){super(),this.body=new HTMLElement,this.head=new HTMLElement,this.documentElement=new HTMLElement,this.appendChild(this.documentElement),this.documentElement.appendChild(this.body)}static registerElementFactory(e,t){Document._elementFactories.set(e.toLowerCase(),t)}createElementNS(e,t){let n=t.toLowerCase();switch(n){case`img`:return new HTMLImageElement$1;case`video`:return new HTMLVideoElement$1;case`canvas`:return new P;default:{let e=Document._elementFactories.get(n);return e?e():new HTMLElement}}}createElement(e){return this.createElementNS(`http://www.w3.org/1999/xhtml`,e)}createTextNode(e){return new ut(e)}createComment(e){return new lt(e)}createDocumentFragment(){return new dt}createEvent(e){return new Event(e)}getElementById(e){return this._findById(this.body,e)}_findById(e,t){if(e.id===t)return e;for(let n of e.children){let e=this._findById(n,t);if(e)return e}return null}get[Symbol.toStringTag](){return`Document`}};var DOMTokenList=class{constructor(e,t){this._ownerElement=e,this._attributeName=t}_getTokens(){let e=this._ownerElement.getAttribute(this._attributeName);return e?e.split(/\s+/).filter(e=>e.length>0):[]}_setTokens(e){let t=e.join(` `);t?this._ownerElement.setAttribute(this._attributeName,t):this._ownerElement.removeAttribute(this._attributeName)}get length(){return this._getTokens().length}get value(){return this._ownerElement.getAttribute(this._attributeName)??``}set value(e){e?this._ownerElement.setAttribute(this._attributeName,e):this._ownerElement.removeAttribute(this._attributeName)}item(e){let t=this._getTokens();return e>=0&&e<t.length?t[e]:null}contains(e){return this._getTokens().includes(e)}add(...e){let t=this._getTokens();for(let n of e)n&&!t.includes(n)&&t.push(n);this._setTokens(t)}remove(...e){let t=this._getTokens().filter(t=>!e.includes(t));this._setTokens(t)}toggle(e,t){let n=this.contains(e);return t===void 0?n?(this.remove(e),!1):(this.add(e),!0):t?(this.add(e),!0):(this.remove(e),!1)}replace(e,t){let n=this._getTokens(),r=n.indexOf(e);return r===-1?!1:(n[r]=t,this._setTokens(n),!0)}supports(e){return!0}forEach(e){let t=this._getTokens();for(let n=0;n<t.length;n++)e(t[n],n,this)}keys(){return this._getTokens().keys()}values(){return this._getTokens().values()}entries(){return this._getTokens().entries()}[Symbol.iterator](){return this._getTokens().values()}toString(){return this.value}get[Symbol.toStringTag](){return`DOMTokenList`}};function installWindowEventBus(e){if(e.__gjsify_globalEventTarget)return e.__gjsify_globalEventTarget;let t=new EventTarget,n=typeof e.addEventListener==`function`?e.addEventListener.bind(e):null,r=typeof e.removeEventListener==`function`?e.removeEventListener.bind(e):null;e.__gjsify_globalEventTarget=t;let define=(t,n)=>Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0});return define(`addEventListener`,(e,r,i)=>{t.addEventListener(e,r,i),n?.(e,r,i)}),define(`removeEventListener`,(e,n,i)=>{t.removeEventListener(e,n,i),r?.(e,n,i)}),define(`dispatchEvent`,e=>t.dispatchEvent(e)),t}defineGlobal(`Text`,ut),defineGlobal(`Comment`,lt),defineGlobal(`DocumentFragment`,dt),defineGlobal(`DOMTokenList`,DOMTokenList),defineGlobal(`document`,Tt),defineGlobalIfMissing(`self`,globalThis);var Window=class{};defineGlobalIfMissing(`Window`,Window),defineGlobalIfMissing(`window`,globalThis),defineGlobalIfMissing(`focus`,()=>{}),defineGlobalIfMissing(`blur`,()=>{}),installWindowEventBus(globalThis),defineGlobalIfMissing(`devicePixelRatio`,1),defineGlobalIfMissing(`scrollX`,0),defineGlobalIfMissing(`scrollY`,0),defineGlobalIfMissing(`pageXOffset`,0),defineGlobalIfMissing(`pageYOffset`,0),defineGlobalIfMissing(`alert`,(...e)=>console.error(`alert:`,...e)),globalThis.top===void 0&&Object.defineProperty(globalThis,"top",{get:()=>globalThis,configurable:!0});var Et=__exportAll$1({default:()=>kt});function load$7(){return Ot===void 0&&(Ot=Dt(`@gjsify/node-gi/gi`).requireGi(`PangoCairo`,`1.0`)),Ot}var Dt,Ot,kt,At=__esmMin((()=>{Dt=e(import.meta.url),__name$1(load$7,`load`),kt=new Proxy(Object.create(null),{get(e,t){return load$7()[t]},has(e,t){return t in load$7()}})})),FontFace=class{constructor(e,t,n){this.status=`unloaded`,this.display=`auto`,this.style=`normal`,this.weight=`normal`,this.stretch=`normal`,this.unicodeRange=`U+0-10FFFF`,this.variant=`normal`,this.featureSettings=`normal`,this.family=e,this.source=typeof t==`string`?t:`[binary]`,this.loaded=Promise.resolve(this)}_extractFilePath(){let e=this.source.match(/url\s*\(\s*["']?(file:\/\/\/[^"')]+)["']?\s*\)/i);return e?e[1].replace(/^file:\/\//,``):null}async load(){this.status=`loading`;let e=this._extractFilePath();if(e)try{let{default:t}=await Promise.resolve().then(()=>(At(),Et));t.font_map_get_default().add_font_file(e)}catch{}return this.status=`loaded`,this}},FontFaceSet=class{constructor(){this.status=`loaded`,this.ready=Promise.resolve(this),this._faces=new Set}addEventListener(e,t){}removeEventListener(e,t){}dispatchEvent(e){return!0}add(e){return this._faces.add(e),this}delete(e){return this._faces.delete(e)}clear(){this._faces.clear()}has(e){return this._faces.has(e)}check(e,t){return!1}load(e,t){return Promise.resolve([])}forEach(e){this._faces.forEach(t=>e(t,t,this))}values(){return this._faces.values()}keys(){return this._faces.values()}entries(){return Array.from(this._faces).map(e=>[e,e])[Symbol.iterator]()}[Symbol.iterator](){return this._faces[Symbol.iterator]()}get size(){return this._faces.size}};const jt=globalThis;defineGlobalIfMissing(`FontFace`,FontFace),jt.FontFace===void 0&&(jt.FontFace=FontFace);const Mt=jt.document;Mt&&Mt.fonts===void 0&&Object.defineProperty(Mt,"fonts",{value:new FontFaceSet,configurable:!0,writable:!0});var Image=class extends HTMLImageElement$1{constructor(e=null,t=null){super(),e!==null&&(this.width=e),t!==null&&(this.height=t)}};defineGlobal(`HTMLImageElement`,HTMLImageElement$1),defineGlobal(`Image`,Image),defineGlobalIfMissing(`location`,{href:`file://`,origin:`file://`,protocol:`file:`,host:``,hostname:``,port:``,pathname:`/`,search:``,hash:``,assign(e){},replace(e){},reload(){},toString(){return this.href},ancestorOrigins:{length:0,item:()=>null,contains:()=>!1,[Symbol.iterator]:function*(){}}});var MediaQueryList=class extends EventTarget{constructor(e){super(),this.onchange=null,this.media=e,this.matches=!1}addListener(e){}removeListener(e){}};function matchMedia(e){return new MediaQueryList(e)}defineGlobalIfMissing(`matchMedia`,matchMedia),globalThis.navigator===void 0&&(globalThis.navigator={});var MutationObserver=class{constructor(e){}observe(e,t){}disconnect(){}takeRecords(){return[]}};const Nt=new Set;let Pt=!1;function scheduleFlush(){Pt||(Pt=!0,queueMicrotask(()=>{Pt=!1;let e=Array.from(Nt);Nt.clear();for(let t of e)t._deliver()}))}var ResizeObserver=class{constructor(e){this._observed=new Map,this._pending=new Map,this._callback=e}observe(e,t){if(this._observed.has(e))return;let n=e._onResize((t,n)=>{this._enqueue(e,t,n)});this._observed.set(e,n),queueMicrotask(()=>{if(!this._observed.has(e))return;let t=readClientRect(e);this._enqueue(e,t.width,t.height)})}unobserve(e){let t=this._observed.get(e);t&&(t(),this._observed.delete(e),this._pending.delete(e))}disconnect(){for(let e of this._observed.values())e();this._observed.clear(),this._pending.clear(),Nt.delete(this)}_deliver(){if(this._pending.size===0)return;let e=Array.from(this._pending.values());this._pending.clear();try{this._callback(e,this)}catch(e){console.error(`ResizeObserver callback threw:`,e)}}_enqueue(e,t,n){let r={inlineSize:t,blockSize:n};this._pending.set(e,{target:e,contentRect:{x:0,y:0,width:t,height:n,top:0,right:t,bottom:n,left:0},borderBoxSize:[r],contentBoxSize:[r],devicePixelContentBoxSize:[r]}),Nt.add(this),scheduleFlush()}};function readClientRect(e){let t=e.getBoundingClientRect;if(typeof t==`function`){let n=t.call(e);return{width:n.width??0,height:n.height??0}}return{width:0,height:0}}var IntersectionObserver=class{constructor(e,t){this.root=t?.root??null,this.rootMargin=t?.rootMargin??`0px`,this.thresholds=Array.isArray(t?.threshold)?t.threshold:[t?.threshold??0]}observe(e){}unobserve(e){}disconnect(){}takeRecords(){return[]}};defineGlobal(`MutationObserver`,MutationObserver),defineGlobal(`ResizeObserver`,ResizeObserver),defineGlobal(`IntersectionObserver`,IntersectionObserver);const Ft={CustomEvent:CustomEvent$1,MessageEvent,ErrorEvent,CloseEvent,ProgressEvent:ProgressEvent$1};for(let[e,t]of Object.entries(Ft))globalThis[e]===void 0&&Object.defineProperty(globalThis,e,{value:t,writable:!0,configurable:!0});const It={UIEvent,MouseEvent,PointerEvent,KeyboardEvent,WheelEvent,FocusEvent};for(let[e,t]of Object.entries(It))globalThis[e]===void 0&&Object.defineProperty(globalThis,e,{value:t,writable:!0,configurable:!0});var Lt,__name,Rt=__esmMin((()=>{Lt=Object.defineProperty,__name=(e,t)=>Lt(e,`name`,{value:t,configurable:!0})}));const zt=e(import.meta.url);let Bt;function load$6(){return Bt===void 0&&(Bt=zt(`@gjsify/node-gi/gi`).requireGi(`Soup`,`3.0`)),Bt}__name$1(load$6,`load`);var Vt=new Proxy(Object.create(null),{get(e,t){return load$6()[t]},has(e,t){return t in load$6()}});function validateHeaderName(e){if(typeof e!=`string`||!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token ["${e}"]`);throw Object.defineProperty(t,"code",{value:`ERR_INVALID_HTTP_TOKEN`}),t}}function validateHeaderValue(e,t){if(t===void 0){let t=TypeError(`Header "${e}" value must not be undefined`);throw Object.defineProperty(t,"code",{value:`ERR_HTTP_INVALID_HEADER_VALUE`}),t}if(typeof t==`string`&&/[^\t -~€-ÿ]/.test(t)){let t=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,"code",{value:`ERR_INVALID_CHAR`}),t}}const Ht=Symbol(`Headers.headers`);function isBoxedPrimitive(e){return e instanceof String||e instanceof Number||e instanceof Boolean||typeof Symbol<`u`&&e instanceof Symbol||typeof BigInt<`u`&&e instanceof BigInt}var Ut=class Headers{[Ht];constructor(e){if(this[Ht]=new Map,e!=null){if(e instanceof Headers){for(let[t,n]of e[Ht])this[Ht].set(t,[...n]);return}if(typeof e==`object`&&!isBoxedPrimitive(e)){let t=e[Symbol.iterator];if(t==null)for(let[t,n]of Object.entries(e))validateHeaderName(t),validateHeaderValue(t,String(n)),this.append(t,String(n));else{if(typeof t!=`function`)throw TypeError(`Header pairs must be iterable`);for(let t of e){if(typeof t!=`object`||isBoxedPrimitive(t))throw TypeError(`Each header pair must be an iterable object`);let e=[...t];if(e.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);validateHeaderName(e[0]),validateHeaderValue(e[0],String(e[1])),this.append(e[0],String(e[1]))}}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'`)}}append(e,t){validateHeaderName(e),validateHeaderValue(e,t);let n=String(e).toLowerCase(),r=String(t),i=this[Ht].get(n);i?i.push(r):this[Ht].set(n,[r])}set(e,t){validateHeaderName(e),validateHeaderValue(e,t);let n=String(e).toLowerCase();this[Ht].set(n,[String(t)])}delete(e){this[Ht].delete(String(e).toLowerCase())}has(e){return this[Ht].has(String(e).toLowerCase())}get(e){let t=this[Ht].get(String(e).toLowerCase());if(!t||t.length===0)return null;let n=t.join(`, `);return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}getAll(e){return this[Ht].get(String(e).toLowerCase())??[]}getSetCookie(){return this[Ht].get(`set-cookie`)??[]}forEach(e,t){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*keys(){let e=[...this[Ht].keys()].sort(),t=new Set;for(let n of e)t.has(n)||(t.add(n),yield n)}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`Headers`}toString(){return Object.prototype.toString.call(this)}raw(){let e={};for(let t of this.keys())e[t]=this.getAll(t);return e}_appendToSoupMessage(e,t=Vt.MessageHeadersType.REQUEST){let n=e?e.get_request_headers():new Vt.MessageHeaders(t);for(let[e,t]of this.entries())n.append(e,t);return n}static _newFromSoupMessage(e,t=Vt.MessageHeadersType.RESPONSE){let n=new Headers,r;return r=t===Vt.MessageHeadersType.RESPONSE?e.get_response_headers():e.get_request_headers(),r.foreach((e,t)=>{n.append(e,t)}),n}[Symbol.for(`nodejs.util.inspect.custom`)](){let e={};for(let t of this.keys()){let n=this.getAll(t);t===`host`?e[t]=n[0]:e[t]=n.length>1?n:n[0]}return e}};Object.defineProperties(Ut.prototype,[`get`,`entries`,`forEach`,`values`].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));var Wt=__esmMin((()=>{}));Wt();var FetchBaseError=class extends Error{type;constructor(e,t){super(e),typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},FetchError=class extends FetchBaseError{code;errno;erroredSysCall;constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}};const Gt=globalThis.URL,Kt=globalThis.URLSearchParams,qt=Symbol.toStringTag,isURLSearchParameters=e=>typeof e==`object`&&typeof e.append==`function`&&typeof e.delete==`function`&&typeof e.get==`function`&&typeof e.getAll==`function`&&typeof e.has==`function`&&typeof e.set==`function`&&typeof e.sort==`function`&&e[qt]===`URLSearchParams`,isBlob=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.arrayBuffer==`function`&&typeof t.type==`string`&&typeof t.stream==`function`&&typeof t.constructor==`function`&&/^(Blob|File)$/.test(t[qt])},isAbortSignal=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return t[qt]===`AbortSignal`||t[qt]===`EventTarget`},isDomainOrSubdomain=(e,t)=>{let n=new Gt(t).hostname,r=new Gt(e).hostname;return n===r||n.endsWith(`.${r}`)},isSameProtocol=(e,t)=>new Gt(t).protocol===new Gt(e).protocol;function formDataToBlob(e){let t=`----FormDataBoundary`+Math.random().toString(36).slice(2),n=[];for(let[r,i]of e.entries())typeof i==`string`?n.push(`--${t}\r\nContent-Disposition: form-data; name="${r}"\r\n\r\n${i}\r\n`):(n.push(`--${t}\r\nContent-Disposition: form-data; name="${r}"; filename="${i.name}"\r\nContent-Type: ${i.type||`application/octet-stream`}\r\n\r\n`),n.push(i),n.push(`\r
2
2
  `));return n.push(`--${t}--\r\n`),new Blob(n,{type:`multipart/form-data; boundary=${t}`})}var Jt,Yt=__esmMin((()=>{Jt=globalThis.FormData,globalThis.File})),Xt=__exportAll$1({toFormData:()=>toFormData});function _fileName(e){let t=e.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!t)return;let n=t[2]||t[3]||``,r=n.slice(n.lastIndexOf(`\\`)+1);return r=r.replace(/%22/g,`"`),r=r.replace(/&#(\d{4});/g,(e,t)=>String.fromCharCode(t)),r}async function toFormData(e,t){if(!/multipart/i.test(t))throw TypeError(`Failed to fetch`);let n=t.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw TypeError(`no or bad content-type header, no multipart boundary`);let r=new MultipartParser(n[1]||n[2]),i,o,s,c,l,u,d=[],f=new Jt,onPartData=e=>{s+=p.decode(e,{stream:!0})},appendToFile=e=>{d.push(e)},appendFileToFormData=()=>{let e=new a(d,u,{type:l});f.append(c,e)},appendEntryToFormData=()=>{f.append(c,s)},p=new TextDecoder(`utf-8`);p.decode(),r.onPartBegin=function(){r.onPartData=onPartData,r.onPartEnd=appendEntryToFormData,i=``,o=``,s=``,c=``,l=``,u=null,d.length=0},r.onHeaderField=function(e){i+=p.decode(e,{stream:!0})},r.onHeaderValue=function(e){o+=p.decode(e,{stream:!0})},r.onHeaderEnd=function(){if(o+=p.decode(),i=i.toLowerCase(),i===`content-disposition`){let e=o.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);e&&(c=e[2]||e[3]||``),u=_fileName(o),u&&(r.onPartData=appendToFile,r.onPartEnd=appendFileToFormData)}else i===`content-type`&&(l=o);o=``,i=``};for await(let t of e)r.write(t);return r.end(),f}var Zt,Qt,lower,noop,MultipartParser,$t=__esmMin((()=>{Yt(),Zt=1,Qt={PART_BOUNDARY:Zt,LAST_BOUNDARY:Zt*=2},lower=e=>e|32,noop=(...e)=>{},MultipartParser=class{index=0;flags=0;boundary;lookbehind;state=0;onHeaderEnd=noop;onHeaderField=noop;onHeadersEnd=noop;onHeaderValue=noop;onPartBegin=noop;onPartData=noop;onPartEnd=noop;boundaryChars={};constructor(e){e=`\r
3
- --`+e;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n),this.boundaryChars[t[n]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8)}write(e){let t=0,n=e.length,r=this.index,{lookbehind:i,boundary:a,boundaryChars:o,index:s,state:c,flags:l}=this,u=this.boundary.length,d=u-1,f=e.length,p,m,mark=e=>{this[e+`Mark`]=t},clear=e=>{delete this[e+`Mark`]},callback=(e,t,n,r)=>{(t===void 0||t!==n)&&this[e](r&&r.subarray(t,n))},dataCallback=(n,r=!1)=>{let i=n+`Mark`;i in this&&(r?(callback(n,this[i],t,e),delete this[i]):(callback(n,this[i],e.length,e),this[i]=0))};for(t=0;t<n;t++)switch(p=e[t],c){case 0:if(s===a.length-2){if(p===45)l|=Qt.LAST_BOUNDARY;else if(p!==13)return;s++;break}else if(s-1==a.length-2){if(l&Qt.LAST_BOUNDARY&&p===45)c=9,l=0;else if(!(l&Qt.LAST_BOUNDARY)&&p===10)s=0,callback(`onPartBegin`),c=1;else return;break}p!==a[s+2]&&(s=-2),p===a[s+2]&&s++;break;case 1:c=2,mark(`onHeaderField`),s=0;case 2:if(p===13){clear(`onHeaderField`),c=6;break}if(s++,p===45)break;if(p===58){if(s===1)return;dataCallback(`onHeaderField`,!0),c=3;break}if(m=lower(p),m<97||m>122)return;break;case 3:if(p===32)break;mark(`onHeaderValue`),c=4;case 4:p===13&&(dataCallback(`onHeaderValue`,!0),callback(`onHeaderEnd`),c=5);break;case 5:if(p!==10)return;c=1;break;case 6:if(p!==10)return;callback(`onHeadersEnd`),c=7;break;case 7:c=8,mark(`onPartData`);case 8:if(r=s,s===0){for(t+=d;t<f&&!(e[t]in o);)t+=u;t-=d,p=e[t]}if(s<a.length)a[s]===p?(s===0&&dataCallback(`onPartData`,!0),s++):s=0;else if(s===a.length)s++,p===13?l|=Qt.PART_BOUNDARY:p===45?l|=Qt.LAST_BOUNDARY:s=0;else if(s-1===a.length)if(l&Qt.PART_BOUNDARY){if(s=0,p===10){l&=~Qt.PART_BOUNDARY,callback(`onPartEnd`),callback(`onPartBegin`),c=1;break}}else l&Qt.LAST_BOUNDARY&&p===45?(callback(`onPartEnd`),c=9,l=0):s=0;if(s>0)i[s-1]=p;else if(r>0){let e=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);callback(`onPartData`,0,r,e),r=0,mark(`onPartData`),t--}break;case 9:break;default:throw Error(`Unexpected state entered: ${c}`)}dataCallback(`onHeaderField`),dataCallback(`onHeaderValue`),dataCallback(`onPartData`),this.index=s,this.state=c,this.flags=l}end(){if(this.state===1&&this.index===0||this.state===8&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==9)throw Error(`MultipartParser.end(): stream ended unexpectedly`)}}}));Rt(),Wt(),Yt(),__name((e,t)=>new Promise((n,r)=>{u(e,t,e=>{e?r(e):n()})}),`pipeline`);const en=Symbol(`Body internals`);function isAnyArrayBuffer(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}var Body=class{[en]={body:null,stream:null,boundary:``,disturbed:!1,error:null};size=0;constructor(e,t={size:0}){if(this.size=t.size||0,e==null)this[en].body=null;else if(isURLSearchParameters(e))this[en].body=i.from(e.toString());else if(isBlob(e))this[en].body=e;else if(i.isBuffer(e))this[en].body=e;else if(isAnyArrayBuffer(e))this[en].body=i.from(e);else if(ArrayBuffer.isView(e))this[en].body=i.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof c)this[en].body=e;else if(typeof ReadableStream<`u`&&e instanceof ReadableStream)this[en].body=readableStreamToReadable(e);else if(e instanceof Jt){let t=formDataToBlob(e);this[en].body=t,this[en].boundary=t.type?.split(`boundary=`)?.[1]??``}else typeof e==`string`?this[en].body=i.from(e):e instanceof Kt?this[en].body=i.from(e.toString()):(console.warn(`Unknown body type "${typeof e}", try to parse the body to string!`),this[en].body=i.from(String(e)));let n=this[en].body;i.isBuffer(n)?this[en].stream=c.from(n):isBlob(n)?this[en].stream=c.from(blobToAsyncIterable(n)):n instanceof c&&(this[en].stream=n),n instanceof l&&n.on(`error`,e=>{let t=e instanceof FetchBaseError?e:new FetchError(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,`system`,e);this[en].error=t})}get body(){let e=this[en].stream;if(!e)return null;if(typeof ReadableStream<`u`){let t=!1;return new ReadableStream({start(n){e.on(`data`,e=>{if(!t)try{n.enqueue(e instanceof Uint8Array?e:new Uint8Array(e))}catch{}}),e.on(`end`,()=>{if(!t){t=!0;try{n.close()}catch{}}}),e.on(`error`,e=>{if(!t){t=!0;try{n.error(e)}catch{}}})},cancel(){t=!0,e.destroy()}})}return null}get _stream(){return this[en].stream}get _rawBodyBuffer(){let e=this[en].body;return e===null?null:i.isBuffer(e)?e:e instanceof Uint8Array?i.from(e.buffer,e.byteOffset,e.byteLength):null}get bodyUsed(){return this[en].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await consumeBody(this);return e.slice(t,t+n)}async formData(){let e=this.headers?.get(`content-type`);if(e?.startsWith(`application/x-www-form-urlencoded`)){let e=new Jt,t=new Kt(await this.text());for(let[n,r]of t)e.append(n,r);return e}let{toFormData:t}=await Promise.resolve().then(()=>($t(),Xt));return t(this.body,e)}async blob(){let e=this.headers?.get(`content-type`)||this[en].body&&this[en].body.type||``;return new r([await this.arrayBuffer()],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await consumeBody(this);return new TextDecoder().decode(e)}};Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});async function consumeBody(e){if(e[en].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[en].disturbed=!0,e[en].error)throw e[en].error;let{_stream:t}=e;if(t===null||!(t instanceof l))return i.alloc(0);let n=[],r=0;try{for await(let i of t){if(e.size>0&&r+i.length>e.size){let n=new FetchError(`content size at ${e.url} over limit: ${e.size}`,`max-size`);throw t.destroy(n),n}r+=i.length,n.push(i)}}catch(t){let n=t instanceof Error?t:Error(String(t));throw t instanceof FetchBaseError?t:new FetchError(`Invalid response body while trying to fetch ${e.url}: ${n.message}`,`system`,n)}try{return n.every(e=>typeof e==`string`)?i.from(n.join(``)):i.concat(n,r)}catch(t){let n=t instanceof Error?t:Error(String(t));throw new FetchError(`Could not create Buffer from response body for ${e.url}: ${n.message}`,`system`,n)}}const clone=(e,t)=>{let n,r,{body:i}=e[en];if(e.bodyUsed)throw Error(`cannot clone body after it is used`);return i instanceof l&&typeof i.getBoundary!=`function`&&(n=new s({highWaterMark:t}),r=new s({highWaterMark:t}),i.pipe(n),i.pipe(r),e[en].stream=n,i=r),i},extractContentType=(e,t)=>e===null?null:typeof e==`string`?`text/plain;charset=UTF-8`:isURLSearchParameters(e)?`application/x-www-form-urlencoded;charset=UTF-8`:isBlob(e)?e.type||null:i.isBuffer(e)||isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof Jt?`multipart/form-data; boundary=${t[en].boundary}`:e instanceof l?null:`text/plain;charset=UTF-8`,getTotalBytes=e=>{let{body:t}=e[en];if(t===null)return 0;if(isBlob(t))return t.size;if(i.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==`function`){let e=t;return e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null}return null};function readableStreamToReadable(e){let t=e.getReader();return new c({async read(){try{let{done:e,value:n}=await t.read();e?this.push(null):this.push(i.from(n))}catch(e){this.destroy(e)}},destroy(e,n){t.cancel().then(()=>n(null),n)}})}async function*blobToAsyncIterable(e){if(typeof e.stream==`function`){let t=e.stream().getReader();for(;;){let{done:e,value:n}=await t.read();if(e)break;yield n}}else yield new Uint8Array(await e.arrayBuffer())}const tn=new Set([301,302,303,307,308]),isRedirect=e=>tn.has(e),nn=Symbol(`Response internals`);var rn=class Response extends Body{[nn];_inputStream=null;constructor(e=null,t={}){super(e,t);let n=t.status==null?200:t.status,r=new Ut(t.headers);if(e!==null&&!r.has(`Content-Type`)){let t=extractContentType(e,this);t&&r.append(`Content-Type`,t)}this[nn]={type:`default`,url:t.url,status:n,statusText:t.statusText||``,headers:r,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[nn].type}get url(){return this[nn].url||``}get status(){return this[nn].status}get ok(){return this[nn].status>=200&&this[nn].status<300}get redirected(){return this[nn].counter>0}get statusText(){return this[nn].statusText}get headers(){return this[nn].headers}get highWaterMark(){return this[nn].highWaterMark}clone(){return new Response(clone(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!isRedirect(t))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new Response(null,{headers:{location:new Gt(e).toString()},status:t})}static error(){let e=new Response(null,{status:0,statusText:``});return e[nn].type=`error`,e}static json(e,t){let n=JSON.stringify(e),r={...t},i=new Ut(r.headers);return i.has(`content-type`)||i.set(`content-type`,`application/json`),r.headers=i,new Response(n,r)}get[Symbol.toStringTag](){return`Response`}async text(){if(!this._inputStream)return super.text();let e=yt.MemoryOutputStream.new_resizable();await new Promise((t,n)=>{e.splice_async(this._inputStream,yt.OutputStreamSpliceFlags.CLOSE_TARGET|yt.OutputStreamSpliceFlags.CLOSE_SOURCE,ht.PRIORITY_DEFAULT,null,(r,i)=>{try{t(e.splice_finish(i))}catch(e){n(e)}})});let t=e.steal_as_bytes();return new TextDecoder().decode(t.toArray())}};Object.defineProperties(rn.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});function gbytesToUint8Array(e){return e.toArray()}const warnNotImplemented=e=>{let t=e?`Not implemented: ${e}`:`Not implemented`;return console.warn(t),t};async function readBytesAsync(e,t=4096,n=ht.PRIORITY_DEFAULT,r=null){return new Promise((i,a)=>{e.read_bytes_async(t,n,r,(t,n)=>{try{let t=e.read_bytes_finish(n);return t.get_size()===0?i(null):i(gbytesToUint8Array(t))}catch(e){let t=e;if(typeof t.matches==`function`&&(t.matches(yt.IOErrorEnum,yt.IOErrorEnum.PARTIAL_INPUT)||t.matches(yt.IOErrorEnum,yt.IOErrorEnum.CONNECTION_CLOSED)||t.matches(yt.IOErrorEnum,yt.IOErrorEnum.BROKEN_PIPE)||t.matches(yt.IOErrorEnum,yt.IOErrorEnum.CLOSED)))return i(null);a(e)}})})}async function*inputStreamAsyncIterator(e,t=4096,n=ht.PRIORITY_DEFAULT,r=null){let i;for(;(i=await readBytesAsync(e,t,n,r))!==null;)yield i}async function soupSendAsync(e,t,n=ht.PRIORITY_DEFAULT,r=null){return new Promise((i,a)=>{e.send_async(t,n,r,(t,n)=>{try{i(e.send_finish(n))}catch(e){a(e)}})})}function inputStreamToReadable(e,t={}){return c.from(inputStreamAsyncIterator(e),t)}function stripURLForUseAsAReferrer(e,t=!1){if(e==null||e===`no-referrer`)return`no-referrer`;let n=new Gt(e);return/^(about|blob|data):$/.test(n.protocol)?`no-referrer`:(n.username=``,n.password=``,n.hash=``,t&&(n.pathname=``,n.search=``),n)}const an=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]);function validateReferrerPolicy(e){if(!an.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function isOriginPotentiallyTrustworthy(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,``),n=d(t);return n===4&&t.startsWith(`127.`)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t)?!0:e.host===`localhost`||e.host.endsWith(`.localhost`)?!1:e.protocol===`file:`}function isUrlPotentiallyTrustworthy(e){return/^about:(blank|srcdoc)$/.test(e.toString())||(typeof e==`string`&&(e=new Gt(e)),e.protocol===`data:`)||/^(blob|filesystem):$/.test(e.protocol)?!0:isOriginPotentiallyTrustworthy(e)}function determineRequestsReferrer(e,t={}){let{referrerURLCallback:n,referrerOriginCallback:r}=t;if(e.referrer===`no-referrer`||e.referrerPolicy===``)return null;let i=e.referrerPolicy;if(e.referrer===`about:client`)return`no-referrer`;let a=new Gt(e.referrer),o=stripURLForUseAsAReferrer(a),s=stripURLForUseAsAReferrer(a,!0);o.toString().length>4096&&(o=s),n&&(o=n(o)),r&&(s=r(s));let c=new Gt(e.url);switch(i){case`no-referrer`:return`no-referrer`;case`origin`:return s;case`unsafe-url`:return o;case`strict-origin`:return isUrlPotentiallyTrustworthy(o)&&!isUrlPotentiallyTrustworthy(c)?`no-referrer`:s.toString();case`strict-origin-when-cross-origin`:return o.origin===c.origin?o:isUrlPotentiallyTrustworthy(o)&&!isUrlPotentiallyTrustworthy(c)?`no-referrer`:s;case`same-origin`:return o.origin===c.origin?o:`no-referrer`;case`origin-when-cross-origin`:return o.origin===c.origin?o:s;case`no-referrer-when-downgrade`:return isUrlPotentiallyTrustworthy(o)&&!isUrlPotentiallyTrustworthy(c)?`no-referrer`:o;default:throw TypeError(`Invalid referrerPolicy: ${i}`)}}function parseReferrerPolicyFromHeader(e){let t=(e.get(`referrer-policy`)||``).split(/[,\s]+/),n=``;for(let e of t)e&&an.has(e)&&(n=e);return n}const on=Symbol(`Request internals`);let sn=null;function envPositiveInt(e,t){let n=ht.getenv(e);if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function shouldAcceptAnyCert(e){return e===!1?!0:e===!0?!1:ht.getenv(`NODE_TLS_REJECT_UNAUTHORIZED`)===`0`}function getSharedSession(){if(sn===null){let e=envPositiveInt(`GJSIFY_FETCH_MAX_CONNS_PER_HOST`,16),t=Math.max(envPositiveInt(`GJSIFY_FETCH_MAX_CONNS`,64),e);sn=new Vt.Session({maxConns:t,maxConnsPerHost:e});try{sn.remove_feature_by_type(Vt.ContentDecoder.$gtype)}catch{}}return sn}const isRequest=e=>typeof e==`object`&&typeof e.url==`string`;var cn=class Request extends Body{cache;credentials;destination;get headers(){return this[on].headers}integrity;keepalive;get method(){return this[on].method}mode;get redirect(){return this[on].redirect}get referrer(){if(this[on].referrer===`no-referrer`)return``;if(this[on].referrer===`client`)return`about:client`;if(this[on].referrer)return this[on].referrer.toString()}get referrerPolicy(){return this[on].referrerPolicy}set referrerPolicy(e){this[on].referrerPolicy=validateReferrerPolicy(e)}get signal(){return this[on].signal}get url(){return this[on].parsedURL.toString()}get _uri(){return ht.Uri.parse(this.url,ht.UriFlags.ENCODED)}get _session(){return this[on].session}get _message(){return this[on].message}get _inputStream(){return this[on].inputStream}get[Symbol.toStringTag](){return`Request`}[on];follow;compress=!1;counter=0;agent=``;highWaterMark=16384;insecureHTTPParser=!1;rejectUnauthorized;constructor(e,t){let n=e,r=t||{},i,a={};if(isRequest(e)?(i=new Gt(n.url),a=n):i=new Gt(e),i.username!==``||i.password!==``)throw TypeError(`${i} is an url with embedded credentials.`);let o=r.method||a.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),(t?.body!=null||isRequest(e)&&n.body!==null)&&(o===`GET`||o===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let s=t?.body?t.body:isRequest(e)&&n.body!==null?clone(e):null;super(s,{size:r.size||0});let c=new Ut(t?.headers||n.headers||{});if(s!==null&&!c.has(`Content-Type`)){let e=extractContentType(s,this);e&&c.set(`Content-Type`,e)}let l=isRequest(e)?n.signal:null;if(t&&`signal`in t&&(l=t.signal),l!=null&&!isAbortSignal(l))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let u=t?.referrer==null?n.referrer:t.referrer;if(u===``)u=`no-referrer`;else if(u){let e=new Gt(u);u=/^about:(\/\/)?client$/.test(e.toString())?`client`:e}else u=void 0;let d=i.protocol,f=null,p=null;(d===`http:`||d===`https:`)&&(f=getSharedSession(),p=new Vt.Message({method:o,uri:ht.Uri.parse(i.toString(),ht.UriFlags.ENCODED)})),this[on]={method:o,redirect:t?.redirect||n.redirect||`follow`,headers:c,parsedURL:i,signal:l,referrer:u,referrerPolicy:``,session:f,message:p},this.follow=r.follow===void 0?n.follow===void 0?20:n.follow:r.follow,this.compress=r.compress===void 0?n.compress===void 0?!0:n.compress:r.compress,this.counter=r.counter||n.counter||0,this.agent=r.agent||n.agent,this.highWaterMark=r.highWaterMark||n.highWaterMark||16384,this.insecureHTTPParser=r.insecureHTTPParser||n.insecureHTTPParser||!1,this.rejectUnauthorized=r.rejectUnauthorized??n.rejectUnauthorized,this.referrerPolicy=t?.referrerPolicy||n.referrerPolicy||``}async _send(e){let{session:t,message:n,signal:r,parsedURL:i}=this[on];if(!t||!n)throw Error(`Cannot send request: no Soup session (non-HTTP URL?)`);e.headers._appendToSoupMessage(n);let a=this._rawBodyBuffer;if(a!==null&&a.byteLength>0){let t=e.headers.get(`content-type`)||null;n.set_request_body_from_bytes(t,new ht.Bytes(a))}i.protocol===`https:`&&shouldAcceptAnyCert(this.rejectUnauthorized)&&n.connect(`accept-certificate`,(e,t,n)=>!0);let o=new yt.Cancellable;return r&&(r.aborted?o.cancel():r.addEventListener(`abort`,()=>o.cancel(),{once:!0})),this[on].inputStream=await soupSendAsync(t,n,ht.PRIORITY_DEFAULT,o),this[on].readable=inputStreamToReadable(this[on].inputStream),{inputStream:this[on].inputStream,readable:this[on].readable,cancellable:o}}clone(){return new Request(this)}async arrayBuffer(){return super.arrayBuffer()}async blob(){return super.blob()}async formData(){return super.formData()}async json(){return super.json()}async text(){return super.text()}};Object.defineProperties(cn.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});const getSoupRequestOptions=e=>{let{parsedURL:t}=e[on],n=new Ut(e[on].headers);n.has(`Accept`)||n.set(`Accept`,`*/*`);let r=null;if(e.body===null&&/^(post|put)$/i.test(e.method)&&(r=`0`),e.body!==null){let t=getTotalBytes(e);typeof t==`number`&&!Number.isNaN(t)&&(r=String(t))}r&&n.set(`Content-Length`,r),e.referrerPolicy===``&&(e.referrerPolicy=`strict-origin-when-cross-origin`),e.referrer&&e.referrer!==`no-referrer`?e[on].referrer=determineRequestsReferrer(e):e[on].referrer=`no-referrer`,e[on].referrer instanceof Gt&&n.set(`Referer`,e.referrer),n.has(`User-Agent`)||n.set(`User-Agent`,`gjsify-fetch`),e.compress&&!n.has(`Accept-Encoding`)&&n.set(`Accept-Encoding`,`gzip, deflate`);let{agent:i}=e;return typeof i==`function`&&(i=i(t)),!n.has(`Connection`)&&!i&&n.set(`Connection`,`close`),{parsedURL:t,options:{headers:n}}};function parseDataUri(e){let t=e.match(/^data:([^,]*?)(;base64)?,(.*)$/s);if(!t)throw TypeError(`Invalid data URI: ${e.slice(0,50)}...`);let n=t[1]||`text/plain;charset=US-ASCII`,r=!!t[2],i=t[3],a;if(r){let e=atob(i);a=new Uint8Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t)}else a=new TextEncoder().encode(decodeURIComponent(i));return{buffer:a,typeFull:n}}var AbortError=class extends FetchBaseError{constructor(e,t=`aborted`){super(e,t)}};let ln=0;function guessBlobExt(e){let t=e.toLowerCase().split(`?`)[0],n=t.lastIndexOf(`.`),r=n>-1?t.slice(n):``;switch(r){case`.png`:case`.jpg`:case`.jpeg`:case`.gif`:case`.webp`:case`.svg`:case`.bmp`:case`.ttf`:case`.otf`:case`.woff`:case`.woff2`:case`.mp3`:case`.wav`:case`.ogg`:case`.flac`:case`.m4a`:case`.mp4`:case`.webm`:case`.mkv`:case`.xml`:case`.tmx`:case`.json`:return r;default:return`.bin`}}function writeBlobToTempFile(e,t){let n=mt.build_filenamev([mt.get_tmp_dir(),`gjsify-blob-${ln++}${guessBlobExt(t)}`]);return mt.file_set_contents(n,e),n}var XMLHttpRequest=class extends EventTarget{static UNSENT=0;static OPENED=1;static HEADERS_RECEIVED=2;static LOADING=3;static DONE=4;UNSENT=0;OPENED=1;HEADERS_RECEIVED=2;LOADING=3;DONE=4;readyState=0;status=0;statusText=``;responseType=``;responseText=``;response=null;responseURL=``;withCredentials=!1;timeout=0;upload=new XMLHttpRequestUpload;onreadystatechange=null;onload=null;onerror=null;onabort=null;ontimeout=null;onloadstart=null;onloadend=null;onprogress=null;_method=`GET`;_url=``;_headers=new Map;_responseHeaders=new Map;_controller=new AbortController;_aborted=!1;_timeoutId=null;open(e,t,n=!0,r,i){this._method=e.toUpperCase(),this._url=t,this._headers.clear(),this._responseHeaders.clear(),this._aborted=!1,this._controller=new AbortController,this._setReadyState(1)}setRequestHeader(e,t){if(this.readyState<1)throw new DOMException(`Must open first`,`InvalidStateError`);this._headers.set(e.toLowerCase(),t)}getResponseHeader(e){return this._responseHeaders.get(e.toLowerCase())??null}getAllResponseHeaders(){let e=[];return this._responseHeaders.forEach((t,n)=>e.push(`${n}: ${t}`)),e.join(`\r
4
- `)}send(e){if(this.readyState!==1)throw new DOMException(`Must open first`,`InvalidStateError`);if(this._aborted)return;let t={};this._headers.forEach((e,n)=>{t[n]=e});let n={method:this._method,headers:t,credentials:this.withCredentials?`include`:`omit`,signal:this._controller.signal};e!=null&&this._method!==`GET`&&this._method!==`HEAD`&&(n.body=e),this.timeout>0&&(this._timeoutId=setTimeout(()=>{this._controller.abort(),this._onTimeout()},this.timeout)),this.dispatchEvent(new Event(`loadstart`)),this.onloadstart&&this.onloadstart(new ProgressEvent$1(`loadstart`)),fetch$1(this._url,n).then(async e=>{if(!this._aborted){switch(this._timeoutId&&=(clearTimeout(this._timeoutId),null),this.status=e.status,this.statusText=e.statusText,this.responseURL=e.url,e.headers.forEach((e,t)=>{this._responseHeaders.set(t.toLowerCase(),e)}),this._setReadyState(2),this._setReadyState(3),this.responseType){case`arraybuffer`:{let t=await e.arrayBuffer();this.response=t,this.responseText=``;break}case`blob`:{let t=await e.arrayBuffer(),n=writeBlobToTempFile(new Uint8Array(t),this._url),r=new Blob([t],{type:this._responseHeaders.get(`content-type`)??``});r._tmpPath=n,this.response=r,this.responseText=``;break}case`json`:{let t=await e.text();this.responseText=``;try{this.response=t.length>0?JSON.parse(t):null}catch{this.response=null}break}case`document`:{let t=await e.text();this.responseText=t,this.response=t;break}default:{let t=await e.text(),n=t.charCodeAt(0)===65279?t.slice(1):t;this.responseText=n,this.response=n;break}}this._setReadyState(4),this.dispatchEvent(new ProgressEvent$1(`load`)),this.dispatchEvent(new ProgressEvent$1(`loadend`)),this.onload&&this.onload(new ProgressEvent$1(`load`)),this.onloadend&&this.onloadend(new ProgressEvent$1(`loadend`))}}).catch(e=>{if(this._timeoutId&&=(clearTimeout(this._timeoutId),null),this._aborted)return;this._setReadyState(4);let t=new ProgressEvent$1(`error`);this.dispatchEvent(t),this.onerror&&this.onerror(t),this.onloadend&&this.onloadend(new ProgressEvent$1(`loadend`))})}abort(){if(this._aborted)return;this._aborted=!0,this._timeoutId&&=(clearTimeout(this._timeoutId),null),this._controller.abort(),this.readyState!==0&&this.readyState!==4&&(this._setReadyState(4),this.status=0);let e=new ProgressEvent$1(`abort`);this.dispatchEvent(e),this.onabort&&this.onabort(e),this.onloadend&&this.onloadend(new ProgressEvent$1(`loadend`))}overrideMimeType(e){}_onTimeout(){if(this._aborted)return;this._aborted=!0,this._setReadyState(4);let e=new ProgressEvent$1(`timeout`);this.dispatchEvent(e),this.ontimeout&&this.ontimeout(e)}_setReadyState(e){this.readyState=e;let t=new Event(`readystatechange`);this.dispatchEvent(t),this.onreadystatechange&&this.onreadystatechange(t)}},XMLHttpRequestUpload=class extends EventTarget{onprogress=null;onloadstart=null;onloadend=null;onload=null;onerror=null;onabort=null;ontimeout=null};Wt(),Yt();const un=new Set([`data:`,`http:`,`https:`,`file:`]);function rewriteRootRelativeUrl(e){if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`))return e;let t=globalThis.__GJSIFY_DEBUG_FETCH===!0;try{let r=n.programPath??n.programInvocationName??``;if(!r)return e;let i=`file://${ht.path_get_dirname(r)}${e}`;return t&&console.log(`[fetch] rewrite ${e} → ${i}`),i}catch(n){return t&&console.warn(`[fetch] rewrite FAILED: ${n instanceof Error?n.message:String(n)}`),e}}async function fetch$1(e,t={}){e=rewriteRootRelativeUrl(e);let n=new cn(e,t),{parsedURL:i,options:a}=getSoupRequestOptions(n);if(!un.has(i.protocol))throw TypeError(`@gjsify/fetch cannot load ${e}. URL scheme "${i.protocol.replace(/:$/,``)}" is not supported.`);if(i.protocol===`data:`){let{buffer:e,typeFull:t}=parseDataUri(n.url);return new rn(Buffer.from(e),{headers:{"Content-Type":t}})}if(i.protocol===`file:`){let e=globalThis.__GJSIFY_DEBUG_FETCH===!0;e&&console.log(`[fetch] file:// ${n.url}`);try{let t=ht.filename_from_uri(n.url)[0];e&&console.log(`[fetch] file:// path=${t}`);let[r,i]=ht.file_get_contents(t);if(e&&console.log(`[fetch] file:// ok=${r} bytes=${i?.byteLength??`?`}`),!r)throw new FetchError(`Failed to read file: ${t}`,`system`);let a=i,o=new Uint8Array(a.byteLength);o.set(a);let s=new rn(o);return e&&console.log(`[fetch] file:// response created`),s}catch(t){let r=t instanceof Error?t:Error(String(t));throw e&&console.warn(`[fetch] file:// FAIL: ${r.message}`),new FetchError(`request to ${n.url} failed, reason: ${r.message}`,`system`,r)}}let{signal:s}=n;if(s&&s.aborted)throw new AbortError(`The operation was aborted.`);let c,l;try{let e=await n._send(a);c=e.readable,l=e.cancellable}catch(e){if(s&&s.aborted)throw new AbortError(`The operation was aborted.`);let t=e instanceof Error?e:Error(String(e));throw new FetchError(`request to ${n.url} failed, reason: ${t.message}`,`system`,t)}let abortHandler=()=>{l.cancel()};s&&s.addEventListener(`abort`,abortHandler,{once:!0});let finalize=()=>{s&&s.removeEventListener(`abort`,abortHandler)};l.connect(()=>{c.destroy(new AbortError(`The operation was aborted.`))}),c.on(`error`,e=>{finalize()});let u=n._message,d=Ut._newFromSoupMessage(u),f=u.status_code,p=u.get_reason_phrase();if(isRedirect(f)){let e=d.get(`Location`),r=null;try{r=e===null?null:new Gt(e,n.url)}catch{if(n.redirect!==`manual`)throw finalize(),new FetchError(`uri requested responds with an invalid redirect URL: ${e}`,`invalid-redirect`)}switch(n.redirect){case`error`:throw finalize(),new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${n.url}`,`no-redirect`);case`manual`:break;case`follow`:{if(r===null)break;if(n.counter>=n.follow)throw finalize(),new FetchError(`maximum redirect reached at: ${n.url}`,`max-redirect`);let e={headers:new Ut(n.headers),follow:n.follow,counter:n.counter+1,agent:n.agent,compress:n.compress,method:n.method,body:clone(n),signal:n.signal,size:n.size,referrer:n.referrer,referrerPolicy:n.referrerPolicy};if(!isDomainOrSubdomain(n.url,r)||!isSameProtocol(n.url,r))for(let t of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])e.headers.delete(t);if(f!==303&&n.body&&t.body instanceof o.Readable)throw finalize(),new FetchError(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`);(f===303||(f===301||f===302)&&n.method===`POST`)&&(e.method=`GET`,e.body=void 0,e.headers.delete(`content-length`));let i=parseReferrerPolicyFromHeader(d);return i&&(e.referrerPolicy=i),finalize(),fetch$1(new cn(r,e))}default:throw TypeError(`Redirect option '${n.redirect}' is not a valid value of RequestRedirect`)}}let m={url:n.url,status:f,statusText:p,headers:d,size:n.size,counter:n.counter,highWaterMark:n.highWaterMark},h=d.get(`Content-Encoding`);if(!n.compress||n.method===`HEAD`||h===null||f===204||f===304)return finalize(),new rn(c,m);if(typeof DecompressionStream<`u`){let e=null;if(h===`gzip`||h===`x-gzip`?e=`gzip`:(h===`deflate`||h===`x-deflate`)&&(e=`deflate`),e){let t=new r([await new rn(c,m).arrayBuffer()]).stream().pipeThrough(new DecompressionStream(e));return finalize(),new rn(t,m)}}return finalize(),new rn(c,m)}__name$1(fetch$1,`fetch`);const dn=globalThis;globalThis.fetch===void 0&&(dn.fetch=fetch$1),globalThis.Headers===void 0&&(dn.Headers=Ut),globalThis.Request===void 0&&(dn.Request=cn),globalThis.Response===void 0&&(dn.Response=rn),globalThis.XMLHttpRequest===void 0&&(globalThis.XMLHttpRequest=XMLHttpRequest),globalThis.XMLHttpRequestUpload===void 0&&(globalThis.XMLHttpRequestUpload=XMLHttpRequestUpload);const fn=globalThis.URL;if(fn&&fn.__gjsify_objecturl!==!0){let e=new Map,t=fn.createObjectURL?.bind(fn),n=fn.revokeObjectURL?.bind(fn);fn.createObjectURL=n=>{let r=n?._tmpPath;if(typeof r==`string`&&r.length>0){let t=`file://${r}`;return e.set(t,r),t}return t?t(n):`file:///dev/null`},fn.revokeObjectURL=t=>{let r=e.get(t);if(r){try{mt.unlink(r)}catch{}e.delete(t)}else n&&n(t)},fn.__gjsify_objecturl=!0}const pn=e(import.meta.url);let mn;function load$5(){return mn===void 0&&(mn=pn(`@gjsify/node-gi/gi`).requireGi(`Adw`,`1`)),mn}__name$1(load$5,`load`);var hn=new Proxy(Object.create(null),{get(e,t){return load$5()[t]},has(e,t){return t in load$5()}});function variantKindFor(e,t){switch(e){case`s`:case`b`:case`i`:case`u`:case`d`:return e}if(typeof t==`string`)return`s`;if(typeof t==`boolean`)return`b`;if(typeof t==`number`)return Number.isInteger(t)?`i`:`d`;throw Error(`Cannot build a GLib.Variant from ${typeof t}`)}function buildVariant(e,t){switch(variantKindFor(e?.dup_string()??null,t)){case`s`:return ht.Variant.new_string(String(t));case`b`:return ht.Variant.new_boolean(!!t);case`i`:return ht.Variant.new_int32(Number(t));case`u`:return ht.Variant.new_uint32(Number(t));case`d`:return ht.Variant.new_double(Number(t))}}function describeActions(e){return e?e.list_actions().sort((e,t)=>e.localeCompare(t)).map(t=>({name:t,enabled:e.get_action_enabled(t),parameterType:e.get_action_parameter_type(t)?.dup_string()??null,stateType:e.get_action_state_type(t)?.dup_string()??null})):[]}function activateAction(e,t,n){let r=e.get_action_parameter_type(t),i=n==null?null:buildVariant(r,n);e.activate_action(t,i)}function changeActionState(e,t,n){e.change_action_state(t,buildVariant(e.get_action_state_type(t),n))}var gn=it;const _n=e(import.meta.url);let vn;function load$4(){return vn===void 0&&(vn=_n(`@gjsify/node-gi/gi`).requireGi(`Gtk`,`4.0`)),vn}__name$1(load$4,`load`);var yn=new Proxy(Object.create(null),{get(e,t){return load$4()[t]},has(e,t){return t in load$4()}}),bn=yn;const xn=new Map;function swapCss(e,t){let n=gn.Display.get_default();if(!n)return!1;let r=xn.get(e);return r||(r=new bn.CssProvider,bn.StyleContext.add_provider_for_display(n,r,bn.STYLE_PROVIDER_PRIORITY_USER+1),xn.set(e,r)),r.load_from_string(t),!0}function dumpCss(){return{providers:[...xn.keys()]}}const Sn=`org.gjsify.Devtools`;function formatDbusErrorMessage(e,t){return`${e}: ${t}`}const Cn={GetStatus:`read-only`,Screenshot:`read-only`,ListActions:`read-only`,ActivateAction:`mutating`,ChangeActionState:`mutating`,PresentWindow:`read-only`,ResizeWindow:`mutating`,ListToplevels:`read-only`,DumpTree:`read-only`,GetProperty:`read-only`,SetProperty:`mutating`,GetFocused:`read-only`,ActivateWidget:`mutating`,EmitSignal:`mutating`,DumpGSettings:`read-only`,DumpCss:`read-only`,SwapCss:`mutating`};function buildDevtoolsIfaceXml(e=[]){return`<node>
3
+ --`+e;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n),this.boundaryChars[t[n]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8)}write(e){let t=0,n=e.length,r=this.index,{lookbehind:i,boundary:a,boundaryChars:o,index:s,state:c,flags:l}=this,u=this.boundary.length,d=u-1,f=e.length,p,m,mark=e=>{this[e+`Mark`]=t},clear=e=>{delete this[e+`Mark`]},callback=(e,t,n,r)=>{(t===void 0||t!==n)&&this[e](r&&r.subarray(t,n))},dataCallback=(n,r=!1)=>{let i=n+`Mark`;i in this&&(r?(callback(n,this[i],t,e),delete this[i]):(callback(n,this[i],e.length,e),this[i]=0))};for(t=0;t<n;t++)switch(p=e[t],c){case 0:if(s===a.length-2){if(p===45)l|=Qt.LAST_BOUNDARY;else if(p!==13)return;s++;break}else if(s-1==a.length-2){if(l&Qt.LAST_BOUNDARY&&p===45)c=9,l=0;else if(!(l&Qt.LAST_BOUNDARY)&&p===10)s=0,callback(`onPartBegin`),c=1;else return;break}p!==a[s+2]&&(s=-2),p===a[s+2]&&s++;break;case 1:c=2,mark(`onHeaderField`),s=0;case 2:if(p===13){clear(`onHeaderField`),c=6;break}if(s++,p===45)break;if(p===58){if(s===1)return;dataCallback(`onHeaderField`,!0),c=3;break}if(m=lower(p),m<97||m>122)return;break;case 3:if(p===32)break;mark(`onHeaderValue`),c=4;case 4:p===13&&(dataCallback(`onHeaderValue`,!0),callback(`onHeaderEnd`),c=5);break;case 5:if(p!==10)return;c=1;break;case 6:if(p!==10)return;callback(`onHeadersEnd`),c=7;break;case 7:c=8,mark(`onPartData`);case 8:if(r=s,s===0){for(t+=d;t<f&&!(e[t]in o);)t+=u;t-=d,p=e[t]}if(s<a.length)a[s]===p?(s===0&&dataCallback(`onPartData`,!0),s++):s=0;else if(s===a.length)s++,p===13?l|=Qt.PART_BOUNDARY:p===45?l|=Qt.LAST_BOUNDARY:s=0;else if(s-1===a.length)if(l&Qt.PART_BOUNDARY){if(s=0,p===10){l&=~Qt.PART_BOUNDARY,callback(`onPartEnd`),callback(`onPartBegin`),c=1;break}}else l&Qt.LAST_BOUNDARY&&p===45?(callback(`onPartEnd`),c=9,l=0):s=0;if(s>0)i[s-1]=p;else if(r>0){let e=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);callback(`onPartData`,0,r,e),r=0,mark(`onPartData`),t--}break;case 9:break;default:throw Error(`Unexpected state entered: ${c}`)}dataCallback(`onHeaderField`),dataCallback(`onHeaderValue`),dataCallback(`onPartData`),this.index=s,this.state=c,this.flags=l}end(){if(this.state===1&&this.index===0||this.state===8&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==9)throw Error(`MultipartParser.end(): stream ended unexpectedly`)}}}));Rt(),Wt(),Yt(),__name((e,t)=>new Promise((n,r)=>{u(e,t,e=>{e?r(e):n()})}),`pipeline`);const en=Symbol(`Body internals`);function isAnyArrayBuffer(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer}var Body=class{[en]={body:null,stream:null,boundary:``,disturbed:!1,error:null};size=0;constructor(e,t={size:0}){if(this.size=t.size||0,e==null)this[en].body=null;else if(isURLSearchParameters(e))this[en].body=i.from(e.toString());else if(isBlob(e))this[en].body=e;else if(i.isBuffer(e))this[en].body=e;else if(isAnyArrayBuffer(e))this[en].body=i.from(e);else if(ArrayBuffer.isView(e))this[en].body=i.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof c)this[en].body=e;else if(typeof ReadableStream<`u`&&e instanceof ReadableStream)this[en].body=readableStreamToReadable(e);else if(e instanceof Jt){let t=formDataToBlob(e);this[en].body=t,this[en].boundary=t.type?.split(`boundary=`)?.[1]??``}else typeof e==`string`?this[en].body=i.from(e):e instanceof Kt?this[en].body=i.from(e.toString()):(console.warn(`Unknown body type "${typeof e}", try to parse the body to string!`),this[en].body=i.from(String(e)));let n=this[en].body;i.isBuffer(n)?this[en].stream=c.from(n):isBlob(n)?this[en].stream=c.from(blobToAsyncIterable(n)):n instanceof c&&(this[en].stream=n),n instanceof l&&n.on(`error`,e=>{let t=e instanceof FetchBaseError?e:new FetchError(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,`system`,e);this[en].error=t})}get body(){let e=this[en].stream;if(!e)return null;if(typeof ReadableStream<`u`){let t=!1;return new ReadableStream({start(n){e.on(`data`,e=>{if(!t)try{n.enqueue(e instanceof Uint8Array?e:new Uint8Array(e))}catch{}}),e.on(`end`,()=>{if(!t){t=!0;try{n.close()}catch{}}}),e.on(`error`,e=>{if(!t){t=!0;try{n.error(e)}catch{}}})},cancel(){t=!0,e.destroy()}})}return null}get _stream(){return this[en].stream}get _rawBodyBuffer(){let e=this[en].body;return e===null?null:i.isBuffer(e)?e:e instanceof Uint8Array?i.from(e.buffer,e.byteOffset,e.byteLength):null}get bodyUsed(){return this[en].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await consumeBody(this);return e.slice(t,t+n)}async formData(){let e=this.headers?.get(`content-type`);if(e?.startsWith(`application/x-www-form-urlencoded`)){let e=new Jt,t=new Kt(await this.text());for(let[n,r]of t)e.append(n,r);return e}let{toFormData:t}=await Promise.resolve().then(()=>($t(),Xt));return t(this.body,e)}async blob(){let e=this.headers?.get(`content-type`)||this[en].body&&this[en].body.type||``;return new r([await this.arrayBuffer()],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await consumeBody(this);return new TextDecoder().decode(e)}};Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});async function consumeBody(e){if(e[en].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[en].disturbed=!0,e[en].error)throw e[en].error;let{_stream:t}=e;if(t===null||!(t instanceof l))return i.alloc(0);let n=[],r=0;try{for await(let i of t){if(e.size>0&&r+i.length>e.size){let n=new FetchError(`content size at ${e.url} over limit: ${e.size}`,`max-size`);throw t.destroy(n),n}r+=i.length,n.push(i)}}catch(t){let n=t instanceof Error?t:Error(String(t));throw t instanceof FetchBaseError?t:new FetchError(`Invalid response body while trying to fetch ${e.url}: ${n.message}`,`system`,n)}try{return n.every(e=>typeof e==`string`)?i.from(n.join(``)):i.concat(n,r)}catch(t){let n=t instanceof Error?t:Error(String(t));throw new FetchError(`Could not create Buffer from response body for ${e.url}: ${n.message}`,`system`,n)}}const clone=(e,t)=>{let n,r,{body:i}=e[en];if(e.bodyUsed)throw Error(`cannot clone body after it is used`);return i instanceof l&&typeof i.getBoundary!=`function`&&(n=new s({highWaterMark:t}),r=new s({highWaterMark:t}),i.pipe(n),i.pipe(r),e[en].stream=n,i=r),i},extractContentType=(e,t)=>e===null?null:typeof e==`string`?`text/plain;charset=UTF-8`:isURLSearchParameters(e)?`application/x-www-form-urlencoded;charset=UTF-8`:isBlob(e)?e.type||null:i.isBuffer(e)||isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof Jt?`multipart/form-data; boundary=${t[en].boundary}`:e instanceof l?null:`text/plain;charset=UTF-8`,getTotalBytes=e=>{let{body:t}=e[en];if(t===null)return 0;if(isBlob(t))return t.size;if(i.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==`function`){let e=t;return e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null}return null};function readableStreamToReadable(e){let t=e.getReader();return new c({async read(){try{let{done:e,value:n}=await t.read();e?this.push(null):this.push(i.from(n))}catch(e){this.destroy(e)}},destroy(e,n){t.cancel().then(()=>n(null),n)}})}async function*blobToAsyncIterable(e){if(typeof e.stream==`function`){let t=e.stream().getReader();for(;;){let{done:e,value:n}=await t.read();if(e)break;yield n}}else yield new Uint8Array(await e.arrayBuffer())}const tn=new Set([301,302,303,307,308]),isRedirect=e=>tn.has(e),nn=Symbol(`Response internals`);var rn=class Response extends Body{[nn];_inputStream=null;constructor(e=null,t={}){super(e,t);let n=t.status==null?200:t.status,r=new Ut(t.headers);if(e!==null&&!r.has(`Content-Type`)){let t=extractContentType(e,this);t&&r.append(`Content-Type`,t)}this[nn]={type:`default`,url:t.url,status:n,statusText:t.statusText||``,headers:r,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[nn].type}get url(){return this[nn].url||``}get status(){return this[nn].status}get ok(){return this[nn].status>=200&&this[nn].status<300}get redirected(){return this[nn].counter>0}get statusText(){return this[nn].statusText}get headers(){return this[nn].headers}get highWaterMark(){return this[nn].highWaterMark}clone(){return new Response(clone(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!isRedirect(t))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new Response(null,{headers:{location:new Gt(e).toString()},status:t})}static error(){let e=new Response(null,{status:0,statusText:``});return e[nn].type=`error`,e}static json(e,t){let n=JSON.stringify(e),r={...t},i=new Ut(r.headers);return i.has(`content-type`)||i.set(`content-type`,`application/json`),r.headers=i,new Response(n,r)}get[Symbol.toStringTag](){return`Response`}async text(){if(!this._inputStream)return super.text();let e=yt.MemoryOutputStream.new_resizable();await new Promise((t,n)=>{e.splice_async(this._inputStream,yt.OutputStreamSpliceFlags.CLOSE_TARGET|yt.OutputStreamSpliceFlags.CLOSE_SOURCE,ht.PRIORITY_DEFAULT,null,(r,i)=>{try{t(e.splice_finish(i))}catch(e){n(e)}})});let t=e.steal_as_bytes();return new TextDecoder().decode(t.toArray())}};Object.defineProperties(rn.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});function gbytesToUint8Array(e){return e.toArray()}const warnNotImplemented=e=>{let t=e?`Not implemented: ${e}`:`Not implemented`;return console.warn(t),t};async function readBytesAsync(e,t=4096,n=ht.PRIORITY_DEFAULT,r=null){return new Promise((i,a)=>{e.read_bytes_async(t,n,r,(t,n)=>{try{let t=e.read_bytes_finish(n);return t.get_size()===0?i(null):i(gbytesToUint8Array(t))}catch(e){let t=e;if(typeof t.matches==`function`&&(t.matches(yt.IOErrorEnum,yt.IOErrorEnum.PARTIAL_INPUT)||t.matches(yt.IOErrorEnum,yt.IOErrorEnum.CONNECTION_CLOSED)||t.matches(yt.IOErrorEnum,yt.IOErrorEnum.BROKEN_PIPE)||t.matches(yt.IOErrorEnum,yt.IOErrorEnum.CLOSED)))return i(null);a(e)}})})}async function*inputStreamAsyncIterator(e,t=4096,n=ht.PRIORITY_DEFAULT,r=null){let i;for(;(i=await readBytesAsync(e,t,n,r))!==null;)yield i}async function soupSendAsync(e,t,n=ht.PRIORITY_DEFAULT,r=null){return new Promise((i,a)=>{e.send_async(t,n,r,(t,n)=>{try{i(e.send_finish(n))}catch(e){a(e)}})})}function inputStreamToReadable(e,t={}){return c.from(inputStreamAsyncIterator(e),t)}function stripURLForUseAsAReferrer(e,t=!1){if(e==null||e===`no-referrer`)return`no-referrer`;let n=new Gt(e);return/^(about|blob|data):$/.test(n.protocol)?`no-referrer`:(n.username=``,n.password=``,n.hash=``,t&&(n.pathname=``,n.search=``),n)}const an=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]);function validateReferrerPolicy(e){if(!an.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function isOriginPotentiallyTrustworthy(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,``),n=d(t);return n===4&&t.startsWith(`127.`)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t)?!0:e.host===`localhost`||e.host.endsWith(`.localhost`)?!1:e.protocol===`file:`}function isUrlPotentiallyTrustworthy(e){return/^about:(blank|srcdoc)$/.test(e.toString())||(typeof e==`string`&&(e=new Gt(e)),e.protocol===`data:`)||/^(blob|filesystem):$/.test(e.protocol)?!0:isOriginPotentiallyTrustworthy(e)}function determineRequestsReferrer(e,t={}){let{referrerURLCallback:n,referrerOriginCallback:r}=t;if(e.referrer===`no-referrer`||e.referrerPolicy===``)return null;let i=e.referrerPolicy;if(e.referrer===`about:client`)return`no-referrer`;let a=new Gt(e.referrer),o=stripURLForUseAsAReferrer(a),s=stripURLForUseAsAReferrer(a,!0);o.toString().length>4096&&(o=s),n&&(o=n(o)),r&&(s=r(s));let c=new Gt(e.url);switch(i){case`no-referrer`:return`no-referrer`;case`origin`:return s;case`unsafe-url`:return o;case`strict-origin`:return isUrlPotentiallyTrustworthy(o)&&!isUrlPotentiallyTrustworthy(c)?`no-referrer`:s.toString();case`strict-origin-when-cross-origin`:return o.origin===c.origin?o:isUrlPotentiallyTrustworthy(o)&&!isUrlPotentiallyTrustworthy(c)?`no-referrer`:s;case`same-origin`:return o.origin===c.origin?o:`no-referrer`;case`origin-when-cross-origin`:return o.origin===c.origin?o:s;case`no-referrer-when-downgrade`:return isUrlPotentiallyTrustworthy(o)&&!isUrlPotentiallyTrustworthy(c)?`no-referrer`:o;default:throw TypeError(`Invalid referrerPolicy: ${i}`)}}function parseReferrerPolicyFromHeader(e){let t=(e.get(`referrer-policy`)||``).split(/[,\s]+/),n=``;for(let e of t)e&&an.has(e)&&(n=e);return n}const on=Symbol(`Request internals`);let sn=null;function envPositiveInt(e,t){let n=ht.getenv(e);if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function shouldAcceptAnyCert(e){return e===!1?!0:e===!0?!1:ht.getenv(`NODE_TLS_REJECT_UNAUTHORIZED`)===`0`}function getSharedSession(){if(sn===null){let e=envPositiveInt(`GJSIFY_FETCH_MAX_CONNS_PER_HOST`,16),t=Math.max(envPositiveInt(`GJSIFY_FETCH_MAX_CONNS`,64),e);sn=new Vt.Session({maxConns:t,maxConnsPerHost:e}),sn.remove_feature_by_type(Vt.ContentDecoder.$gtype)}return sn}const isRequest=e=>typeof e==`object`&&typeof e.url==`string`;var cn=class Request extends Body{cache;credentials;destination;get headers(){return this[on].headers}integrity;keepalive;get method(){return this[on].method}mode;get redirect(){return this[on].redirect}get referrer(){if(this[on].referrer===`no-referrer`)return``;if(this[on].referrer===`client`)return`about:client`;if(this[on].referrer)return this[on].referrer.toString()}get referrerPolicy(){return this[on].referrerPolicy}set referrerPolicy(e){this[on].referrerPolicy=validateReferrerPolicy(e)}get signal(){return this[on].signal}get url(){return this[on].parsedURL.toString()}get _uri(){return ht.Uri.parse(this.url,ht.UriFlags.ENCODED)}get _session(){return this[on].session}get _message(){return this[on].message}get _inputStream(){return this[on].inputStream}get[Symbol.toStringTag](){return`Request`}[on];follow;compress=!1;counter=0;agent=``;highWaterMark=16384;insecureHTTPParser=!1;rejectUnauthorized;constructor(e,t){let n=e,r=t||{},i,a={};if(isRequest(e)?(i=new Gt(n.url),a=n):i=new Gt(e),i.username!==``||i.password!==``)throw TypeError(`${i} is an url with embedded credentials.`);let o=r.method||a.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),(t?.body!=null||isRequest(e)&&n.body!==null)&&(o===`GET`||o===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let s=t?.body?t.body:isRequest(e)&&n.body!==null?clone(e):null;super(s,{size:r.size||0});let c=new Ut(t?.headers||n.headers||{});if(s!==null&&!c.has(`Content-Type`)){let e=extractContentType(s,this);e&&c.set(`Content-Type`,e)}let l=isRequest(e)?n.signal:null;if(t&&`signal`in t&&(l=t.signal),l!=null&&!isAbortSignal(l))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let u=t?.referrer==null?n.referrer:t.referrer;if(u===``)u=`no-referrer`;else if(u){let e=new Gt(u);u=/^about:(\/\/)?client$/.test(e.toString())?`client`:e}else u=void 0;let d=i.protocol,f=null,p=null;(d===`http:`||d===`https:`)&&(f=getSharedSession(),p=new Vt.Message({method:o,uri:ht.Uri.parse(i.toString(),ht.UriFlags.ENCODED)})),this[on]={method:o,redirect:t?.redirect||n.redirect||`follow`,headers:c,parsedURL:i,signal:l,referrer:u,referrerPolicy:``,session:f,message:p},this.follow=r.follow===void 0?n.follow===void 0?20:n.follow:r.follow,this.compress=r.compress===void 0?n.compress===void 0?!0:n.compress:r.compress,this.counter=r.counter||n.counter||0,this.agent=r.agent||n.agent,this.highWaterMark=r.highWaterMark||n.highWaterMark||16384,this.insecureHTTPParser=r.insecureHTTPParser||n.insecureHTTPParser||!1,this.rejectUnauthorized=r.rejectUnauthorized??n.rejectUnauthorized,this.referrerPolicy=t?.referrerPolicy||n.referrerPolicy||``}async _send(e){let{session:t,message:n,signal:r,parsedURL:i}=this[on];if(!t||!n)throw Error(`Cannot send request: no Soup session (non-HTTP URL?)`);e.headers._appendToSoupMessage(n);let a=this._rawBodyBuffer;if(a!==null&&a.byteLength>0){let t=e.headers.get(`content-type`)||null;n.set_request_body_from_bytes(t,new ht.Bytes(a))}i.protocol===`https:`&&shouldAcceptAnyCert(this.rejectUnauthorized)&&n.connect(`accept-certificate`,(e,t,n)=>!0);let o=new yt.Cancellable;return r&&(r.aborted?o.cancel():r.addEventListener(`abort`,()=>o.cancel(),{once:!0})),this[on].inputStream=await soupSendAsync(t,n,ht.PRIORITY_DEFAULT,o),this[on].readable=inputStreamToReadable(this[on].inputStream),{inputStream:this[on].inputStream,readable:this[on].readable,cancellable:o}}clone(){return new Request(this)}async arrayBuffer(){return super.arrayBuffer()}async blob(){return super.blob()}async formData(){return super.formData()}async json(){return super.json()}async text(){return super.text()}};Object.defineProperties(cn.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});const getSoupRequestOptions=e=>{let{parsedURL:t}=e[on],n=new Ut(e[on].headers);n.has(`Accept`)||n.set(`Accept`,`*/*`);let r=null;if(e.body===null&&/^(post|put)$/i.test(e.method)&&(r=`0`),e.body!==null){let t=getTotalBytes(e);typeof t==`number`&&!Number.isNaN(t)&&(r=String(t))}r&&n.set(`Content-Length`,r),e.referrerPolicy===``&&(e.referrerPolicy=`strict-origin-when-cross-origin`),e.referrer&&e.referrer!==`no-referrer`?e[on].referrer=determineRequestsReferrer(e):e[on].referrer=`no-referrer`,e[on].referrer instanceof Gt&&n.set(`Referer`,e.referrer),n.has(`User-Agent`)||n.set(`User-Agent`,`gjsify-fetch`),e.compress&&!n.has(`Accept-Encoding`)&&n.set(`Accept-Encoding`,`gzip, deflate`);let{agent:i}=e;return typeof i==`function`&&(i=i(t)),!n.has(`Connection`)&&!i&&n.set(`Connection`,`close`),{parsedURL:t,options:{headers:n}}};var AbortError=class extends FetchBaseError{constructor(e,t=`aborted`){super(e,t)}};function parseDataUri(e){let t=e.match(/^data:([^,]*?)(;base64)?,(.*)$/s);if(!t)throw TypeError(`Invalid data URI: ${e.slice(0,50)}...`);let n=t[1]||`text/plain;charset=US-ASCII`,r=!!t[2],i=t[3],a;if(r){let e=atob(i);a=new Uint8Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t)}else a=new TextEncoder().encode(decodeURIComponent(i));return{buffer:a,typeFull:n}}function rewriteRootRelativeUrl(e,t){if(!e.startsWith(`/`)||e.startsWith(`//`))return e;let n=t.lastIndexOf(`/`);return n<=0?e:`file://${t.slice(0,n)}${e}`}function resolveRootRelativeUrl(e){return rewriteRootRelativeUrl(e,n.programPath??n.programInvocationName??``)}let ln=0;function guessBlobExt(e){let t=e.toLowerCase().split(`?`)[0],n=t.lastIndexOf(`.`),r=n>-1?t.slice(n):``;switch(r){case`.png`:case`.jpg`:case`.jpeg`:case`.gif`:case`.webp`:case`.svg`:case`.bmp`:case`.ttf`:case`.otf`:case`.woff`:case`.woff2`:case`.mp3`:case`.wav`:case`.ogg`:case`.flac`:case`.m4a`:case`.mp4`:case`.webm`:case`.mkv`:case`.xml`:case`.tmx`:case`.json`:return r;default:return`.bin`}}function writeBlobToTempFile(e,t){let n=mt.build_filenamev([mt.get_tmp_dir(),`gjsify-blob-${ln++}${guessBlobExt(t)}`]);return mt.file_set_contents(n,e),n}var XMLHttpRequest=class extends EventTarget{static UNSENT=0;static OPENED=1;static HEADERS_RECEIVED=2;static LOADING=3;static DONE=4;UNSENT=0;OPENED=1;HEADERS_RECEIVED=2;LOADING=3;DONE=4;readyState=0;status=0;statusText=``;responseType=``;responseText=``;response=null;responseURL=``;withCredentials=!1;timeout=0;upload=new XMLHttpRequestUpload;onreadystatechange=null;onload=null;onerror=null;onabort=null;ontimeout=null;onloadstart=null;onloadend=null;onprogress=null;_method=`GET`;_url=``;_headers=new Map;_responseHeaders=new Map;_controller=new AbortController;_aborted=!1;_timeoutId=null;open(e,t,n=!0,r,i){this._method=e.toUpperCase(),this._url=t,this._headers.clear(),this._responseHeaders.clear(),this._aborted=!1,this._controller=new AbortController,this._setReadyState(1)}setRequestHeader(e,t){if(this.readyState<1)throw new DOMException(`Must open first`,`InvalidStateError`);this._headers.set(e.toLowerCase(),t)}getResponseHeader(e){return this._responseHeaders.get(e.toLowerCase())??null}getAllResponseHeaders(){let e=[];return this._responseHeaders.forEach((t,n)=>e.push(`${n}: ${t}`)),e.join(`\r
4
+ `)}send(e){if(this.readyState!==1)throw new DOMException(`Must open first`,`InvalidStateError`);if(this._aborted)return;let t={};this._headers.forEach((e,n)=>{t[n]=e});let n={method:this._method,headers:t,credentials:this.withCredentials?`include`:`omit`,signal:this._controller.signal};e!=null&&this._method!==`GET`&&this._method!==`HEAD`&&(n.body=e),this.timeout>0&&(this._timeoutId=setTimeout(()=>{this._controller.abort(),this._onTimeout()},this.timeout)),this.dispatchEvent(new Event(`loadstart`)),this.onloadstart&&this.onloadstart(new ProgressEvent$1(`loadstart`)),fetch$1(this._url,n).then(async e=>{if(!this._aborted){switch(this._timeoutId&&=(clearTimeout(this._timeoutId),null),this.status=e.status,this.statusText=e.statusText,this.responseURL=e.url,e.headers.forEach((e,t)=>{this._responseHeaders.set(t.toLowerCase(),e)}),this._setReadyState(2),this._setReadyState(3),this.responseType){case`arraybuffer`:{let t=await e.arrayBuffer();this.response=t,this.responseText=``;break}case`blob`:{let t=await e.arrayBuffer(),n=writeBlobToTempFile(new Uint8Array(t),this._url),r=new Blob([t],{type:this._responseHeaders.get(`content-type`)??``});r._tmpPath=n,this.response=r,this.responseText=``;break}case`json`:{let t=await e.text();this.responseText=``;try{this.response=t.length>0?JSON.parse(t):null}catch{this.response=null}break}case`document`:{let t=await e.text();this.responseText=t,this.response=t;break}default:{let t=await e.text(),n=t.charCodeAt(0)===65279?t.slice(1):t;this.responseText=n,this.response=n;break}}this._setReadyState(4),this.dispatchEvent(new ProgressEvent$1(`load`)),this.dispatchEvent(new ProgressEvent$1(`loadend`)),this.onload&&this.onload(new ProgressEvent$1(`load`)),this.onloadend&&this.onloadend(new ProgressEvent$1(`loadend`))}}).catch(e=>{if(this._timeoutId&&=(clearTimeout(this._timeoutId),null),this._aborted)return;this._setReadyState(4);let t=new ProgressEvent$1(`error`);this.dispatchEvent(t),this.onerror&&this.onerror(t),this.onloadend&&this.onloadend(new ProgressEvent$1(`loadend`))})}abort(){if(this._aborted)return;this._aborted=!0,this._timeoutId&&=(clearTimeout(this._timeoutId),null),this._controller.abort(),this.readyState!==0&&this.readyState!==4&&(this._setReadyState(4),this.status=0);let e=new ProgressEvent$1(`abort`);this.dispatchEvent(e),this.onabort&&this.onabort(e),this.onloadend&&this.onloadend(new ProgressEvent$1(`loadend`))}overrideMimeType(e){}_onTimeout(){if(this._aborted)return;this._aborted=!0,this._setReadyState(4);let e=new ProgressEvent$1(`timeout`);this.dispatchEvent(e),this.ontimeout&&this.ontimeout(e)}_setReadyState(e){this.readyState=e;let t=new Event(`readystatechange`);this.dispatchEvent(t),this.onreadystatechange&&this.onreadystatechange(t)}},XMLHttpRequestUpload=class extends EventTarget{onprogress=null;onloadstart=null;onloadend=null;onload=null;onerror=null;onabort=null;ontimeout=null};Wt(),Yt();const un=new Set([`data:`,`http:`,`https:`,`file:`]);function rewriteFetchInput(e){if(typeof e!=`string`)return e;let t=resolveRootRelativeUrl(e);return t!==e&&globalThis.__GJSIFY_DEBUG_FETCH===!0&&console.log(`[fetch] rewrite ${e} → ${t}`),t}async function fetch$1(e,t={}){e=rewriteFetchInput(e);let n=new cn(e,t),{parsedURL:i,options:a}=getSoupRequestOptions(n);if(!un.has(i.protocol))throw TypeError(`@gjsify/fetch cannot load ${e}. URL scheme "${i.protocol.replace(/:$/,``)}" is not supported.`);if(i.protocol===`data:`){let{buffer:e,typeFull:t}=parseDataUri(n.url);return new rn(Buffer.from(e),{headers:{"Content-Type":t}})}if(i.protocol===`file:`){let e=globalThis.__GJSIFY_DEBUG_FETCH===!0;e&&console.log(`[fetch] file:// ${n.url}`);try{let t=ht.filename_from_uri(n.url)[0];e&&console.log(`[fetch] file:// path=${t}`);let[r,i]=ht.file_get_contents(t);if(e&&console.log(`[fetch] file:// ok=${r} bytes=${i?.byteLength??`?`}`),!r)throw new FetchError(`Failed to read file: ${t}`,`system`);let a=i,o=new Uint8Array(a.byteLength);o.set(a);let s=new rn(o);return e&&console.log(`[fetch] file:// response created`),s}catch(t){let r=t instanceof Error?t:Error(String(t));throw e&&console.warn(`[fetch] file:// FAIL: ${r.message}`),new FetchError(`request to ${n.url} failed, reason: ${r.message}`,`system`,r)}}let{signal:s}=n;if(s&&s.aborted)throw new AbortError(`The operation was aborted.`);let c,l;try{let e=await n._send(a);c=e.readable,l=e.cancellable}catch(e){if(s&&s.aborted)throw new AbortError(`The operation was aborted.`);let t=e instanceof Error?e:Error(String(e));throw new FetchError(`request to ${n.url} failed, reason: ${t.message}`,`system`,t)}let abortHandler=()=>{l.cancel()};s&&s.addEventListener(`abort`,abortHandler,{once:!0});let finalize=()=>{s&&s.removeEventListener(`abort`,abortHandler)};l.connect(()=>{c.destroy(new AbortError(`The operation was aborted.`))}),c.on(`error`,e=>{finalize()});let u=n._message,d=Ut._newFromSoupMessage(u),f=u.status_code,p=u.get_reason_phrase();if(isRedirect(f)){let e=d.get(`Location`),r=null;try{r=e===null?null:new Gt(e,n.url)}catch{if(n.redirect!==`manual`)throw finalize(),new FetchError(`uri requested responds with an invalid redirect URL: ${e}`,`invalid-redirect`)}switch(n.redirect){case`error`:throw finalize(),new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${n.url}`,`no-redirect`);case`manual`:break;case`follow`:{if(r===null)break;if(n.counter>=n.follow)throw finalize(),new FetchError(`maximum redirect reached at: ${n.url}`,`max-redirect`);let e={headers:new Ut(n.headers),follow:n.follow,counter:n.counter+1,agent:n.agent,compress:n.compress,method:n.method,body:clone(n),signal:n.signal,size:n.size,referrer:n.referrer,referrerPolicy:n.referrerPolicy};if(!isDomainOrSubdomain(n.url,r)||!isSameProtocol(n.url,r))for(let t of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])e.headers.delete(t);if(f!==303&&n.body&&t.body instanceof o.Readable)throw finalize(),new FetchError(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`);(f===303||(f===301||f===302)&&n.method===`POST`)&&(e.method=`GET`,e.body=void 0,e.headers.delete(`content-length`));let i=parseReferrerPolicyFromHeader(d);return i&&(e.referrerPolicy=i),finalize(),fetch$1(new cn(r,e))}default:throw TypeError(`Redirect option '${n.redirect}' is not a valid value of RequestRedirect`)}}let m={url:n.url,status:f,statusText:p,headers:d,size:n.size,counter:n.counter,highWaterMark:n.highWaterMark},h=d.get(`Content-Encoding`);if(!n.compress||n.method===`HEAD`||h===null||f===204||f===304)return finalize(),new rn(c,m);if(typeof DecompressionStream<`u`){let e=null;if(h===`gzip`||h===`x-gzip`?e=`gzip`:(h===`deflate`||h===`x-deflate`)&&(e=`deflate`),e){let t=new r([await new rn(c,m).arrayBuffer()]).stream().pipeThrough(new DecompressionStream(e));return finalize(),new rn(t,m)}}return finalize(),new rn(c,m)}__name$1(fetch$1,`fetch`);const dn=globalThis;globalThis.fetch===void 0&&(dn.fetch=fetch$1),globalThis.Headers===void 0&&(dn.Headers=Ut),globalThis.Request===void 0&&(dn.Request=cn),globalThis.Response===void 0&&(dn.Response=rn),globalThis.XMLHttpRequest===void 0&&(globalThis.XMLHttpRequest=XMLHttpRequest),globalThis.XMLHttpRequestUpload===void 0&&(globalThis.XMLHttpRequestUpload=XMLHttpRequestUpload);const fn=globalThis.URL;if(fn&&fn.__gjsify_objecturl!==!0){let e=new Map,t=fn.createObjectURL?.bind(fn),n=fn.revokeObjectURL?.bind(fn);fn.createObjectURL=n=>{let r=n?._tmpPath;if(typeof r==`string`&&r.length>0){let t=`file://${r}`;return e.set(t,r),t}return t?t(n):`file:///dev/null`},fn.revokeObjectURL=t=>{let r=e.get(t);r?(mt.unlink(r),e.delete(t)):n&&n(t)},fn.__gjsify_objecturl=!0}const pn=e(import.meta.url);let mn;function load$5(){return mn===void 0&&(mn=pn(`@gjsify/node-gi/gi`).requireGi(`Adw`,`1`)),mn}__name$1(load$5,`load`);var hn=new Proxy(Object.create(null),{get(e,t){return load$5()[t]},has(e,t){return t in load$5()}});function variantKindFor(e,t){switch(e){case`s`:case`b`:case`i`:case`u`:case`d`:return e}if(typeof t==`string`)return`s`;if(typeof t==`boolean`)return`b`;if(typeof t==`number`)return Number.isInteger(t)?`i`:`d`;throw Error(`Cannot build a GLib.Variant from ${typeof t}`)}function buildVariant(e,t){switch(variantKindFor(e?.dup_string()??null,t)){case`s`:return ht.Variant.new_string(String(t));case`b`:return ht.Variant.new_boolean(!!t);case`i`:return ht.Variant.new_int32(Number(t));case`u`:return ht.Variant.new_uint32(Number(t));case`d`:return ht.Variant.new_double(Number(t))}}function describeActions(e){return e?e.list_actions().sort((e,t)=>e.localeCompare(t)).map(t=>({name:t,enabled:e.get_action_enabled(t),parameterType:e.get_action_parameter_type(t)?.dup_string()??null,stateType:e.get_action_state_type(t)?.dup_string()??null})):[]}function activateAction(e,t,n){let r=e.get_action_parameter_type(t),i=n==null?null:buildVariant(r,n);e.activate_action(t,i)}function changeActionState(e,t,n){e.change_action_state(t,buildVariant(e.get_action_state_type(t),n))}var gn=it;const _n=e(import.meta.url);let vn;function load$4(){return vn===void 0&&(vn=_n(`@gjsify/node-gi/gi`).requireGi(`Gtk`,`4.0`)),vn}__name$1(load$4,`load`);var yn=new Proxy(Object.create(null),{get(e,t){return load$4()[t]},has(e,t){return t in load$4()}}),bn=yn;const xn=new Map;function swapCss(e,t){let n=gn.Display.get_default();if(!n)return!1;let r=xn.get(e);return r||(r=new bn.CssProvider,bn.StyleContext.add_provider_for_display(n,r,bn.STYLE_PROVIDER_PRIORITY_USER+1),xn.set(e,r)),r.load_from_string(t),!0}function dumpCss(){return{providers:[...xn.keys()]}}const Sn=`org.gjsify.Devtools`;function formatDbusErrorMessage(e,t){return`${e}: ${t}`}const Cn={GetStatus:`read-only`,Screenshot:`read-only`,ListActions:`read-only`,ActivateAction:`mutating`,ChangeActionState:`mutating`,PresentWindow:`read-only`,ResizeWindow:`mutating`,ListToplevels:`read-only`,DumpTree:`read-only`,GetProperty:`read-only`,SetProperty:`mutating`,GetFocused:`read-only`,ActivateWidget:`mutating`,EmitSignal:`mutating`,DumpGSettings:`read-only`,DumpCss:`read-only`,SwapCss:`mutating`};function buildDevtoolsIfaceXml(e=[]){return`<node>
5
5
  <interface name="${Sn}">
6
6
  <method name="GetStatus">
7
7
  <arg type="s" direction="out" name="status_json"/>
@@ -64,17 +64,17 @@ import{createRequire as e}from"node:module";import"@gjsify/node-gi/globals";impo
64
64
  </method>${e.length>0?`\n${e.join(`
65
65
  `)}`:``}
66
66
  </interface>
67
- </node>`}const wn=e(import.meta.url);let Tn;function load$3(){return Tn===void 0&&(Tn=wn(`@gjsify/node-gi/gi`).requireGi(`Graphene`,`1.0`)),Tn}__name$1(load$3,`load`);var En=new Proxy(Object.create(null),{get(e,t){return load$3()[t]},has(e,t){return t in load$3()}});function captureWidgetPng(e){let t=e.get_native()?.get_renderer();if(!t)return null;let n=e.get_width(),r=e.get_height();if(n<=0||r<=0)return null;let i=bn.WidgetPaintable.new(e),a=bn.Snapshot.new();i.snapshot(a,n,r);let o=a.to_node();if(!o)return null;let s=new En.Rect;s.init(0,0,n,r);let c=t.render_texture(o,s).save_to_png_bytes().get_data();return c?new Uint8Array(c):null}function dumpGSettings(e){let t=yt.SettingsSchemaSource.get_default()?.lookup(e,!0);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`GSettings schema '${e}' is not installed`));let n=new yt.Settings({settings_schema:t}),r={};for(let e of t.list_keys())r[e]=n.get_value(e).recursiveUnpack();return r}function parseWidgetPath(e){let t=e.split(`/`).filter(e=>e.length>0);if(t.length===0)return null;let n=t[0].match(/^toplevel:(\d+)$/);if(!n)return null;let r=[];for(let e of t.slice(1)){let t=e.match(/^child:(\d+)$/);if(!t)return null;r.push(Number(t[1]))}return{toplevel:Number(n[1]),children:r}}function buildWidgetPath(e,t){return[`toplevel:${e}`,...t.map(e=>`child:${e}`)].join(`/`)}function widgetType(e){let t=e;return typeof t.$typeName==`string`&&t.$typeName.length>0?t.$typeName:t.constructor?.$gtype?.name??`GtkWidget`}function activateWidget(e){let t=e;if(typeof t.activate==`function`&&t.activate()===!0)return!0;let n=typeof t.get_parent==`function`?t.get_parent():null;if(n&&widgetType(n)===`GtkListBox`){let t=n,r=!1;return typeof t.select_row==`function`&&(t.select_row(e),r=!0),typeof t.emit==`function`&&(t.emit(`row-activated`,e),r=!0),r}return!1}function nthChild(e,t){let n=e.get_first_child(),r=0;for(;n&&r<t;)n=n.get_next_sibling(),r++;return r===t?n:null}function listToplevels(){let e=bn.Window.get_toplevels(),t=e.get_n_items(),n=[];for(let r=0;r<t;r++){let t=e.get_item(r);t&&n.push({path:`toplevel:${r}`,type:widgetType(t),title:t.get_title?.()??null,mapped:t.get_mapped(),focused:t.is_active??!1})}return n}function resolveWidgetPath(e){let t=parseWidgetPath(e);if(!t)return null;let n=bn.Window.get_toplevels().get_item(t.toplevel);if(!n)return null;for(let e of t.children)if(n=nthChild(n,e),!n)return null;return n}function dumpTree(e,t,n){let r={path:n,type:widgetType(e),name:e.get_name()||null,cssClasses:e.get_css_classes(),mapped:e.get_mapped(),visible:e.get_visible(),children:[]};if(t<=0)return r;let i=e.get_first_child(),a=0;for(;i;)r.children.push(dumpTree(i,t-1,`${n}/child:${a}`)),i=i.get_next_sibling(),a++;return r}function jsonSafe(e){let t=typeof e;return e==null||t===`string`||t===`number`||t===`boolean`?e??null:`[${t}]`}function getWidgetProperty(e,t){let n=e,r=t.replace(/-/g,`_`),i=t.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase());for(let e of[t,r,i])if(e in n)return jsonSafe(n[e])}function childIndex(e,t){let n=e.get_first_child(),r=0;for(;n;){if(n===t)return r;n=n.get_next_sibling(),r++}return-1}function pathOfWidget(e){let t=[],n=e,r=n.get_parent();for(;r;){let e=childIndex(r,n);if(e<0)return null;t.unshift(e),n=r,r=n.get_parent()}let i=bn.Window.get_toplevels(),a=i.get_n_items();for(let e=0;e<a;e++)if(i.get_item(e)===n)return buildWidgetPath(e,t);return null}function frameDelay(e){return new Promise(t=>{ht.timeout_add(ht.PRIORITY_DEFAULT,e,()=>(t(),ht.SOURCE_REMOVE))})}async function captureWidgetWhenRenderable(e,t=12,n=50){for(let r=0;r<t;r++){let t=captureWidgetPng(e);if(t)return t;await frameDelay(n)}return captureWidgetPng(e)}var DevtoolsService=class{constructor(e,t){this._app=e,this._options=t,this._exported=null,this._kinds=new Map,this._extensions=t.extend??[];for(let[e,t]of Object.entries(Cn))this._kinds.set(e,t);for(let e of this._extensions){for(let[t,n]of Object.entries(e.methodKinds))this._kinds.set(t,n);for(let[t,n]of Object.entries(e.handlers)){let e=n;this[t]=(...n)=>(this._guard(t),e(...n))}}}export(e,t){if(this._exported)return;let n=buildDevtoolsIfaceXml(this._extensions.flatMap(e=>e.methodsXml??[])),r=yt.DBusExportedObject.wrapJSObject(n,this);r.export(e,t),this._exported=r}unexport(){this._exported?.unexport(),this._exported=null}GetStatus(){let e=this._app.get_active_window(),t={appId:this._app.get_application_id()??`unknown`,instance:this._options.instance??`default`,activeWindow:e?{id:e.get_name()||`window`,title:e.get_title()??``,mapped:e.get_mapped()}:null,toplevelCount:bn.Window.get_toplevels().get_n_items(),focusedWidget:null,paused:this._isPaused()};for(let e of this._extensions){let n=e.contributeStatus?.();n&&Object.assign(t,n)}return JSON.stringify(t)}async Screenshot(e){let t=this._app.get_active_window();if(!t)return new Uint8Array;let n=captureWidgetPng(t);return n||=(t.present(),await captureWidgetWhenRenderable(t)),n??new Uint8Array}ListActions(){let e={app:describeActions(this._actionGroup(`app`)),win:describeActions(this._actionGroup(`win`))};return JSON.stringify(e)}ActivateAction(e,t,n){this._guard(`ActivateAction`);let r=this._scope(e);activateAction(this._requireGroup(r,t),t,this._parseValue(n))}ChangeActionState(e,t,n){this._guard(`ChangeActionState`);let r=this._scope(e);changeActionState(this._requireGroup(r,t),t,this._parseValue(n))}PresentWindow(){this._app.get_active_window()?.present()}ResizeWindow(e,t){this._guard(`ResizeWindow`);let n=this._app.get_active_window();if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no active window to resize`));let r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(t));return n.is_maximized()&&n.unmaximize(),n.is_fullscreen()&&n.unfullscreen(),n.set_default_size(r,i),[r,i]}ListToplevels(){return JSON.stringify(listToplevels())}DumpTree(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e||`active window`}'`));return JSON.stringify(dumpTree(n.widget,t>0?t:8,n.path))}GetProperty(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));let r=getWidgetProperty(n.widget,t);if(r===void 0)throw Error(formatDbusErrorMessage(`not-found`,`widget has no property '${t}'`));return JSON.stringify(r)}GetFocused(){let e=this._app.get_active_window(),t=e?e.get_focus():null;return JSON.stringify(t?{path:pathOfWidget(t),name:t.get_name()||null,type:widgetType(t)}:null)}ActivateWidget(e){this._guard(`ActivateWidget`);let t=this._resolveRootWidget(e);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));return activateWidget(t.widget)}DumpGSettings(e){return JSON.stringify(dumpGSettings(e))}DumpCss(){return JSON.stringify(dumpCss())}SwapCss(e,t){return this._guard(`SwapCss`),swapCss(e,t)}_resolveRootWidget(e){if(!e||e===`window`||e===`active`){let e=this._app.get_active_window();return e?{widget:e,path:pathOfWidget(e)??`toplevel:0`}:null}let t=resolveWidgetPath(e);return t?{widget:t,path:e}:null}_isPaused(){return this._options.paused?.()??!1}_guard(e){let t=this._kinds.get(e);if(!t)throw Error(formatDbusErrorMessage(`internal`,`unclassified devtools method '${e}'`));if(t===`mutating`&&this._isPaused())throw Error(formatDbusErrorMessage(`paused`,`${e} rejected — external control is paused. Read-only methods keep working.`))}_scope(e){return e===`app`?`app`:`win`}_actionGroup(e){if(e===`app`)return this._app;if(this._options.winActionGroup)return this._options.winActionGroup;let t=this._app.get_active_window();return t instanceof bn.ApplicationWindow?t:null}_requireGroup(e,t){let n=this._actionGroup(e);if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no '${e}' action group`));if(!n.has_action(t))throw Error(formatDbusErrorMessage(`not-found`,`unknown action ${e}.${t}`));return n}_parseValue(e){if(!e||e===`null`)return null;try{return JSON.parse(e)}catch{throw Error(formatDbusErrorMessage(`invalid-params`,`value_json is not valid JSON: ${e}`))}}};const Dn=new Set;function envEnabled(){let e=ht.getenv(`GJSIFY_DEVTOOLS`);if(e==null)return!1;let t=e.toLowerCase();return t!==``&&t!==`0`&&t!==`false`}function envInstance(){let e=ht.getenv(`GJSIFY_DEVTOOLS_INSTANCE`);return e&&e!==``?e:void 0}function installDevtools(e,t={}){if(!(t.enabled??envEnabled()))return null;let n=new DevtoolsService(e,{...t,instance:t.instance??envInstance()}),r=e.get_dbus_connection(),i=e.get_dbus_object_path();if(r&&i){let t=`${i}/devtools`;n.export(r,t),console.log(`[gjsify-devtools] exported ${Sn} at ${t} (dest ${e.get_application_id()??`?`})`)}else console.error(`[gjsify-devtools] no session-bus connection yet — call installDevtools() from the GtkApplication "startup" handler`);return Dn.add(n),n}const On=e(import.meta.url);let kn;function load$2(){return kn===void 0&&(kn=On(`@gjsify/node-gi/gi`).requireGi(`GObject`,`2.0`)),kn}__name$1(load$2,`load`);var An=new Proxy(Object.create(null),{get(e,t){return load$2()[t]},has(e,t){return t in load$2()}}),WebGLContextAttributes=class{constructor(e,t,n,r,i,a,o,s){this.alpha=e,this.depth=t,this.stencil=n,this.antialias=r,this.premultipliedAlpha=i,this.preserveDrawingBuffer=a,this.preferLowPowerToHighPerformance=o,this.failIfMajorPerformanceCaveat=s}},WebGLUniformLocation=class{constructor(e,t,n){this._linkCount=0,this._array=null,this._=e,this._program=t,this._linkCount=t._linkCount,this._activeInfo=n,this._array=null}},OESElementIndexUint=class{};function getOESElementIndexUint(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`OES_element_index_uint`)>=0&&(t=new OESElementIndexUint),t}var OESStandardDerivatives=class{constructor(){this.FRAGMENT_SHADER_DERIVATIVE_HINT_OES=35723}};function getOESStandardDerivatives(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`OES_standard_derivatives`)>=0&&(t=new OESStandardDerivatives),t}var OESTextureFloat=class{};function getOESTextureFloat(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`OES_texture_float`)>=0&&(t=new OESTextureFloat),t}var OESTextureFloatLinear=class{};function getOESTextureFloatLinear(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`OES_texture_float_linear`)>=0&&(t=new OESTextureFloatLinear),t}var STACKGLDestroyContext=class{constructor(e){this.destroy=e.destroy.bind(e)}};function getSTACKGLDestroyContext(e){return new STACKGLDestroyContext(e)}var STACKGLResizeDrawingBuffer=class{constructor(e){this.resize=e.resize.bind(e)}};function getSTACKGLResizeDrawingBuffer(e){return new STACKGLResizeDrawingBuffer(e)}var EXTBlendMinMax=class{constructor(){this.MIN_EXT=32775,this.MAX_EXT=32776}};function getEXTBlendMinMax(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`EXT_blend_minmax`)>=0&&(t=new EXTBlendMinMax),t}var EXTColorBufferFloat=class{};function getEXTColorBufferFloat(e){let t=e.getSupportedExtensions();return t&&t.indexOf(`EXT_color_buffer_float`)>=0?new EXTColorBufferFloat:null}var EXTColorBufferHalfFloat=class{};function getEXTColorBufferHalfFloat(e){let t=e.getSupportedExtensions();return t&&t.indexOf(`EXT_color_buffer_half_float`)>=0?new EXTColorBufferHalfFloat:null}var EXTTextureFilterAnisotropic=class{constructor(){this.TEXTURE_MAX_ANISOTROPY_EXT=34046,this.MAX_TEXTURE_MAX_ANISOTROPY_EXT=34047}};function getEXTTextureFilterAnisotropic(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`EXT_texture_filter_anisotropic`)>=0&&(t=new EXTTextureFilterAnisotropic),t}var OESTextureHalfFloat=class{constructor(){this.HALF_FLOAT_OES=36193}};function getOESTextureHalfFloat(e){let t=e.getSupportedExtensions();return t&&t.indexOf(`OES_texture_half_float`)>=0||e._native2?new OESTextureHalfFloat:null}var WebGLTextureUnit=class{constructor(e,t){this._mode=0,this._bind2D=null,this._bindCube=null,this._ctx=e,this._idx=t}},Linkable=class{constructor(e){this._=0,this._references=[],this._refCount=0,this._pendingDelete=!1,this._binding=0,this._=e,this._references=[],this._refCount=0,this._pendingDelete=!1,this._binding=0}_link(e){return this._references.push(e),e._refCount+=1,!0}_unlink(e){let t=this._references.indexOf(e);if(t<0)return!1;for(;t>=0;)this._references[t]=this._references[this._references.length-1],this._references.pop(),--e._refCount,e._checkDelete(),t=this._references.indexOf(e);return!0}_linked(e){return this._references.indexOf(e)>=0}_checkDelete(){if(this._refCount<=0&&this._pendingDelete&&this._!==0){for(;this._references.length>0;)this._unlink(this._references[0]);this._performDelete(),this._=0}}_performDelete(){}},WebGLBuffer=class extends Linkable{constructor(e,t){super(e),this._size=0,this._elements=new Uint8Array,this._ctx=t}_performDelete(){let e=this._ctx;delete e._buffers[this._|0],e._gl.deleteBuffer(this._)}},WebGLVertexArrayObjectAttribute=class{constructor(e,t){this._isPointer=!1,this._pointerBuffer=null,this._pointerOffset=0,this._pointerSize=0,this._pointerStride=0,this._pointerType=0,this._pointerNormal=!1,this._divisor=0,this._inputSize=4,this._inputStride=0,this._ctx=e,this._idx=t,this._pointerType=e.FLOAT,this._clear()}_clear(){this._isPointer=!1,this._pointerBuffer=null,this._pointerOffset=0,this._pointerSize=0,this._pointerStride=0,this._pointerType=this._ctx.FLOAT,this._pointerNormal=!1,this._divisor=0,this._inputSize=4,this._inputStride=0}},WebGLVertexArrayGlobalAttribute=class{constructor(e){this._idx=0,this._idx=e,this._data=new Float32Array([0,0,0,1])}},WebGLVertexArrayObjectState=class{constructor(e){this._elementArrayBufferBinding=null;let t=e.getParameter(e.MAX_VERTEX_ATTRIBS);this._attribs=Array.from({length:t});for(let n=0;n<t;++n)this._attribs[n]=new WebGLVertexArrayObjectAttribute(e,n);this._elementArrayBufferBinding=null}setElementArrayBuffer(e){if(e!==null&&!(e instanceof WebGLBuffer))throw TypeError(`setElementArrayBuffer(WebGLBuffer?)`);let t=this._elementArrayBufferBinding;t!==e&&(t&&(--t._refCount,t._checkDelete()),e&&(e._refCount+=1),this._elementArrayBufferBinding=e)}cleanUp(){let e=this._elementArrayBufferBinding;e&&(--e._refCount,e._checkDelete(),this._elementArrayBufferBinding=null);for(let e=0;e<this._attribs.length;++e){let t=this._attribs[e];t._pointerBuffer&&(--t._pointerBuffer._refCount,t._pointerBuffer._checkDelete()),t._clear()}}releaseArrayBuffer(e){if(e)for(let t=0;t<this._attribs.length;++t){let n=this._attribs[t];n._pointerBuffer===e&&(--n._pointerBuffer._refCount,n._pointerBuffer._checkDelete(),n._clear())}}setVertexAttribPointer(e,t,n,r,i,a,o,s,c){let l=this._attribs[t];e!==l._pointerBuffer&&(l._pointerBuffer&&(--l._pointerBuffer._refCount,l._pointerBuffer._checkDelete()),e&&(e._refCount+=1),l._pointerBuffer=e),l._pointerSize=n,l._pointerOffset=r,l._pointerStride=i,l._pointerType=a,l._pointerNormal=o,l._inputStride=s,l._inputSize=c}},WebGLVertexArrayGlobalState=class{constructor(e){this._arrayBufferBinding=null;let t=e.getParameter(e.MAX_VERTEX_ATTRIBS);this._attribs=Array.from({length:t});for(let e=0;e<t;++e)this._attribs[e]=new WebGLVertexArrayGlobalAttribute(e);this._arrayBufferBinding=null}setArrayBuffer(e){if(e!==null&&!(e instanceof WebGLBuffer))throw TypeError(`setArrayBuffer(WebGLBuffer?)`);let t=this._arrayBufferBinding;t!==e&&(t&&(--t._refCount,t._checkDelete()),e&&(e._refCount+=1),this._arrayBufferBinding=e)}},WebGLFramebuffer=class extends Linkable{constructor(e,t){if(super(e),this._binding=0,this._width=0,this._height=0,this._status=null,this._ctx=t,this._attachments={},this._attachments[t.COLOR_ATTACHMENT0]=null,this._attachments[t.DEPTH_ATTACHMENT]=null,this._attachments[t.STENCIL_ATTACHMENT]=null,this._attachments[t.DEPTH_STENCIL_ATTACHMENT]=null,this._attachmentLevel={},this._attachmentLevel[t.COLOR_ATTACHMENT0]=0,this._attachmentLevel[t.DEPTH_ATTACHMENT]=0,this._attachmentLevel[t.STENCIL_ATTACHMENT]=0,this._attachmentLevel[t.DEPTH_STENCIL_ATTACHMENT]=0,this._attachmentFace={},this._attachmentFace[t.COLOR_ATTACHMENT0]=0,this._attachmentFace[t.DEPTH_ATTACHMENT]=0,this._attachmentFace[t.STENCIL_ATTACHMENT]=0,this._attachmentFace[t.DEPTH_STENCIL_ATTACHMENT]=0,t._extensions.webgl_draw_buffers){let e=t._extensions.webgl_draw_buffers;this._attachments[e.COLOR_ATTACHMENT1_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT2_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT3_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT4_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT5_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT6_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT7_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT8_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT9_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT10_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT11_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT12_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT13_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT14_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT15_WEBGL]=null,this._attachments[t.NONE]=null,this._attachments[t.BACK]=null,this._attachmentLevel[e.COLOR_ATTACHMENT1_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT2_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT3_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT4_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT5_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT6_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT7_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT8_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT9_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT10_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT11_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT12_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT13_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT14_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT15_WEBGL]=0,this._attachmentLevel[t.NONE]=null,this._attachmentLevel[t.BACK]=null,this._attachmentFace[e.COLOR_ATTACHMENT1_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT2_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT3_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT4_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT5_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT6_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT7_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT8_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT9_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT10_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT11_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT12_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT13_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT14_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT15_WEBGL]=0,this._attachmentFace[t.NONE]=null,this._attachmentFace[t.BACK]=null}}_clearAttachment(e){let t=this._attachments[e];t&&(this._attachments[e]=null,this._unlink(t))}_setAttachment(e,t){this._attachments[t]!==e&&(this._clearAttachment(t),e&&(this._attachments[t]=e,this._link(e)))}_performDelete(){let e=this._ctx;delete e._framebuffers[this._|0],e._gl.deleteFramebuffer(this._|0)}},WebGLProgram$1=class extends Linkable{static{__name$1(this,`WebGLProgram`)}constructor(e,t){super(e),this._linkCount=0,this._linkStatus=!1,this._linkInfoLog=`not linked`,this._attributes=[],this._uniforms=[],this._ctx=t,this._linkCount=0,this._linkStatus=!1,this._linkInfoLog=`not linked`,this._attributes=[],this._uniforms=[]}_performDelete(){let e=this._ctx;delete e._programs[this._|0],e._gl.deleteProgram(this._|0)}},WebGLRenderbuffer=class extends Linkable{constructor(e,t){super(e),this._binding=0,this._width=0,this._height=0,this._format=0,this._ctx=t,this._binding=0,this._width=0,this._height=0,this._format=0}_performDelete(){let e=this._ctx;delete e._renderbuffers[this._|0],e._gl.deleteRenderbuffer(this._)}},WebGLShader$1=class extends Linkable{static{__name$1(this,`WebGLShader`)}constructor(e,t,n){super(e),this._source=``,this._compileStatus=!1,this._compileInfo=``,this._needsRecompile=!1,this._type=n,this._ctx=t,this._source=``,this._compileStatus=!1,this._compileInfo=``}_performDelete(){let e=this._ctx;delete e._shaders[this._|0],e._gl.deleteShader(this._|0)}},WebGLTexture=class extends Linkable{constructor(e,t){super(e),this._binding=0,this._levelWidth=new Int32Array(32),this._levelHeight=new Int32Array(32),this._format=0,this._type=0,this._complete=!0,this._ctx=t}_performDelete(){let e=this._ctx;delete e._textures[this._|0],e._gl.deleteTexture(this._|0)}},WebGLDrawingBufferWrapper=class{constructor(e,t,n){this._framebuffer=e,this._color=t,this._depthStencil=n}},WebGLShaderPrecisionFormat=class{constructor(e){this.rangeMin=e.rangeMin,this.rangeMax=e.rangeMax,this.precision=e.precision}},WebGLActiveInfo=class{constructor(e){this.size=e.size,this.type=e.type,this.name=e.name}};function checkObject(e){return typeof e==`object`||e===void 0}function checkUniform(e,t){return t instanceof WebGLUniformLocation&&t._program===e&&t._linkCount===e._linkCount}function isTypedArray$1(e){return e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Uint32Array||e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array}__name$1(isTypedArray$1,`isTypedArray`);function isValidString(e){let t=e.replace(/(?:\/\*(?:[\s\S]*?)\*\/)|(?:([\s;])+\/\/(?:.*)$)/gm,``);return!/["$`@\\'\0]/.test(t)}function vertexCount(e,t,n){switch(t){case e.TRIANGLES:return n-n%3;case e.LINES:return n-n%2;case e.LINE_LOOP:case e.POINTS:return n;case e.TRIANGLE_FAN:case e.LINE_STRIP:return n<2?0:n;case e.TRIANGLE_STRIP:return n<3?0:n;default:return-1}}function typeSize(e,t){switch(t){case e.UNSIGNED_BYTE:case e.BYTE:return 1;case e.UNSIGNED_SHORT:case e.SHORT:return 2;case e.UNSIGNED_INT:case e.INT:case e.FLOAT:return 4}return 0}function uniformTypeSize(e,t){switch(t){case e.BOOL_VEC4:case e.INT_VEC4:case e.FLOAT_VEC4:return 4;case e.BOOL_VEC3:case e.INT_VEC3:case e.FLOAT_VEC3:return 3;case e.BOOL_VEC2:case e.INT_VEC2:case e.FLOAT_VEC2:return 2;case e.BOOL:case e.INT:case e.FLOAT:case e.SAMPLER_2D:case e.SAMPLER_CUBE:return 1;default:return 0}}const listToArray=e=>{let t=[];for(let n of e.values())t.push(n);return t};function arrayToUint8Array(e){if(isTypedArray$1(e))return new Uint8Array(e.buffer).subarray(e.byteOffset,e.byteLength+e.byteOffset);if(Array.isArray(e)||e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof e.values==`function`)return new Uint8Array(listToArray(e));throw Error(`Can't unpack typed array!`)}function Uint8ArrayToVariant(e){return new ht.Variant(`ay`,e)}const extractImageData=e=>{let t=e.width,n=e.height;if(typeof e==`object`&&t!==void 0&&n!==void 0){if(e.data!==void 0)return e;let r=null;if(typeof e.getContext==`function`)r=e.getContext(`2d`);else if(typeof e.isPixbuf==`function`&&e.isPixbuf())return e.getImageData();else if(e.src!==void 0&&typeof document==`object`&&typeof document.createElement==`function`){let i=document.createElement(`canvas`);typeof i==`object`&&typeof i.getContext==`function`&&(i.width=t,i.height=n,r=i.getContext(`2d`),r!==null&&r.drawImage(e,0,0))}if(r!==null)return r.getImageData(0,0,t,n)}return null};function formatSize(e,t){switch(t){case e.ALPHA:case e.LUMINANCE:return 1;case e.LUMINANCE_ALPHA:return 2;case e.RGB:return 3;case e.RGBA:return 4}return 0}function convertPixels(e){if(typeof e==`object`&&e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Uint8ClampedArray||e instanceof Float32Array)return arrayToUint8Array(e);if(e instanceof Buffer)return new Uint8Array(e)}return null}function checkFormat(e,t){return t===e.ALPHA||t===e.LUMINANCE_ALPHA||t===e.LUMINANCE||t===e.RGB||t===e.RGBA}function validCubeTarget(e,t){return t===e.TEXTURE_CUBE_MAP_POSITIVE_X||t===e.TEXTURE_CUBE_MAP_NEGATIVE_X||t===e.TEXTURE_CUBE_MAP_POSITIVE_Y||t===e.TEXTURE_CUBE_MAP_NEGATIVE_Y||t===e.TEXTURE_CUBE_MAP_POSITIVE_Z||t===e.TEXTURE_CUBE_MAP_NEGATIVE_Z}function flag(e,t,n){return!e||typeof e!=`object`||!(t in e)?n:!!e[t]}function premultiplyAlpha(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=4){let r=e[n+3]/255;t[n]=Math.round(e[n]*r),t[n+1]=Math.round(e[n+1]*r),t[n+2]=Math.round(e[n+2]*r),t[n+3]=e[n+3]}return t}const jn={enable(e=0){this._gl.enable(e)},disable(e=0){if(this._gl.disable(e),e===this.TEXTURE_2D||e===this.TEXTURE_CUBE_MAP){let t=this._getActiveTextureUnit();t._mode===e&&(t._mode=0)}},cullFace(e){this._gl.cullFace(e|0)},depthFunc(e){switch(e|=0,e){case this.NEVER:case this.LESS:case this.EQUAL:case this.LEQUAL:case this.GREATER:case this.NOTEQUAL:case this.GEQUAL:case this.ALWAYS:this._gl.depthFunc(e);return;default:this.setError(this.INVALID_ENUM)}},depthMask(e){this._gl.depthMask(!!e)},depthRange(e,t){if(e=+e,t=+t,e<=t){this._gl.depthRange(e,t);return}this.setError(this.INVALID_OPERATION)},frontFace(e=0){this._gl.frontFace(e)},lineWidth(e){if(isNaN(e)){this.setError(this.INVALID_VALUE);return}this._gl.lineWidth(+e)},polygonOffset(e,t){this._gl.polygonOffset(+e,+t)},sampleCoverage(e,t){this._gl.sampleCoverage(+e,!!t)},hint(e=0,t=0){let n=this._extensions.oes_standard_derivatives;if(!(e===this.GENERATE_MIPMAP_HINT||n&&e===n.FRAGMENT_SHADER_DERIVATIVE_HINT_OES)){this.setError(this.INVALID_ENUM);return}if(t!==this.FASTEST&&t!==this.NICEST&&t!==this.DONT_CARE){this.setError(this.INVALID_ENUM);return}this._gl.hint(e,t)},finish(){this._gl.finish()},flush(){this._gl.flush()},blendColor(e=0,t=0,n=0,r=0){this._gl.blendColor(+e,+t,+n,+r)},blendEquation(e=0){if(this._validBlendMode(e)){this._gl.blendEquation(e);return}this.setError(this.INVALID_ENUM)},blendEquationSeparate(e=0,t=0){if(this._validBlendMode(e)&&this._validBlendMode(t)){this._gl.blendEquationSeparate(e,t);return}this.setError(this.INVALID_ENUM)},blendFunc(e=0,t=0){if(!this._validBlendFunc(e)||!this._validBlendFunc(t)){this.setError(this.INVALID_ENUM);return}if(this._isConstantBlendFunc(e)&&this._isConstantBlendFunc(t)){this.setError(this.INVALID_OPERATION);return}this._gl.blendFunc(e,t)},blendFuncSeparate(e=0,t=0,n=0,r=0){if(!(this._validBlendFunc(e)&&this._validBlendFunc(t)&&this._validBlendFunc(n)&&this._validBlendFunc(r))){this.setError(this.INVALID_ENUM);return}if(this._isConstantBlendFunc(e)&&this._isConstantBlendFunc(t)||this._isConstantBlendFunc(n)&&this._isConstantBlendFunc(r)){this.setError(this.INVALID_OPERATION);return}this._gl.blendFuncSeparate(e,t,n,r)},clear(e=0){this._framebufferOk()&&this._gl.clear(e)},clearColor(e,t,n,r){this._gl.clearColor(+e,+t,+n,+r)},clearDepth(e){this._gl.clearDepth(+e)},clearStencil(e=0){this._checkStencil=!1,this._gl.clearStencil(e)},colorMask(e,t,n,r){this._gl.colorMask(!!e,!!t,!!n,!!r)},stencilFunc(e,t,n){this._checkStencil=!0,this._gl.stencilFunc(e|0,t|0,n|0)},stencilFuncSeparate(e,t,n,r){this._checkStencil=!0,this._gl.stencilFuncSeparate(e|0,t|0,n|0,r|0)},stencilMask(e){this._checkStencil=!0,this._gl.stencilMask(e>>>0)},stencilMaskSeparate(e,t){this._checkStencil=!0,this._gl.stencilMaskSeparate(e|0,t>>>0)},stencilOp(e,t,n){this._checkStencil=!0,this._gl.stencilOp(e|0,t|0,n|0)},stencilOpSeparate(e,t,n,r){this._checkStencil=!0,this._gl.stencilOpSeparate(e|0,t|0,n|0,r|0)},isEnabled(e=0){return this._gl.isEnabled(e)},isContextLost(){return!1},getError(){return this._gl.getError()},setError(e){this._gl.setError(e)},isBuffer(e){return this._isObject(e,`isBuffer`,WebGLBuffer)?this._gl.isBuffer(e?._):!1},isFramebuffer(e){return this._isObject(e,`isFramebuffer`,WebGLFramebuffer)?this._gl.isFramebuffer(e?._):!1},isProgram(e){return this._isObject(e,`isProgram`,WebGLProgram$1)?this._gl.isProgram(e?._):!1},isRenderbuffer(e){return this._isObject(e,`isRenderbuffer`,WebGLRenderbuffer)?this._gl.isRenderbuffer(e?._):!1},isShader(e){return this._isObject(e,`isShader`,WebGLShader$1)?this._gl.isShader(e?._):!1},isTexture(e){return this._isObject(e,`isTexture`,WebGLTexture)?this._gl.isTexture(e?._):!1},generateMipmap(e=0){this._gl.generateMipmap(e)},_validBlendFunc(e){return e===this.ZERO||e===this.ONE||e===this.SRC_COLOR||e===this.ONE_MINUS_SRC_COLOR||e===this.DST_COLOR||e===this.ONE_MINUS_DST_COLOR||e===this.SRC_ALPHA||e===this.ONE_MINUS_SRC_ALPHA||e===this.DST_ALPHA||e===this.ONE_MINUS_DST_ALPHA||e===this.SRC_ALPHA_SATURATE||e===this.CONSTANT_COLOR||e===this.ONE_MINUS_CONSTANT_COLOR||e===this.CONSTANT_ALPHA||e===this.ONE_MINUS_CONSTANT_ALPHA},_validBlendMode(e){let t=this._extensions.ext_blend_minmax;return e===this.FUNC_ADD||e===this.FUNC_SUBTRACT||e===this.FUNC_REVERSE_SUBTRACT||!!(t&&(e===t.MIN_EXT||e===t.MAX_EXT))},_isConstantBlendFunc(e){return e===this.CONSTANT_COLOR||e===this.ONE_MINUS_CONSTANT_COLOR||e===this.CONSTANT_ALPHA||e===this.ONE_MINUS_CONSTANT_ALPHA},_saveError(){this._errorStack.push(this.getError())},_restoreError(e){let t=this._errorStack.pop();t===this.NO_ERROR?this.setError(e):t!==void 0&&this.setError(t)}};function installStateMethods(e){Object.assign(e,jn)}const Mn={bindBuffer(e=0,t){if(!checkObject(t))throw TypeError(`bindBuffer(GLenum, WebGLBuffer)`);if(e!==this.ARRAY_BUFFER&&e!==this.ELEMENT_ARRAY_BUFFER){this.setError(this.INVALID_ENUM);return}if(!t)t=null,this._gl.bindBuffer(e,0);else if(t._pendingDelete)return;else if(this._checkWrapper(t,WebGLBuffer)){if(t._binding&&t._binding!==e){this.setError(this.INVALID_OPERATION);return}t._binding=e|0,this._gl.bindBuffer(e,t._|0)}else return;e===this.ARRAY_BUFFER?this._vertexGlobalState.setArrayBuffer(t):this._vertexObjectState.setElementArrayBuffer(t)},bufferData(e=0,t,n=0){let r=0,i=null;if(typeof t==`number`?r=t:typeof t==`object`&&(i=t),n!==this.STREAM_DRAW&&n!==this.STATIC_DRAW&&n!==this.DYNAMIC_DRAW){this.setError(this.INVALID_ENUM);return}if(e!==this.ARRAY_BUFFER&&e!==this.ELEMENT_ARRAY_BUFFER){this.setError(this.INVALID_ENUM);return}let a=this._getActiveBuffer(e);if(!a){this.setError(this.INVALID_OPERATION);return}if(i){let t=null;if(isTypedArray$1(i)||i instanceof DataView||i instanceof ArrayBuffer)t=arrayToUint8Array(i);else{this.setError(this.INVALID_VALUE);return}this._saveError(),this._gl.bufferData(e,Uint8ArrayToVariant(t),n);let r=this.getError();if(this._restoreError(r),r!==this.NO_ERROR)return;a._size=t.length,e===this.ELEMENT_ARRAY_BUFFER&&(a._elements=new Uint8Array(t))}else if(typeof t==`number`){if(r<0){this.setError(this.INVALID_VALUE);return}this._saveError(),this._gl.bufferDataSizeOnly(e,r,n);let t=this.getError();if(this._restoreError(t),t!==this.NO_ERROR)return;a._size=r,e===this.ELEMENT_ARRAY_BUFFER&&(a._elements=new Uint8Array(r))}else this.setError(this.INVALID_VALUE)},bufferSubData(e=0,t=0,n){if(e!==this.ARRAY_BUFFER&&e!==this.ELEMENT_ARRAY_BUFFER){this.setError(this.INVALID_ENUM);return}if(typeof n!=`object`||!n)throw TypeError(`bufferSubData: data must be a BufferSource`);let r=this._getActiveBuffer(e);if(!r){this.setError(this.INVALID_OPERATION);return}if(t<0||t>=r._size){this.setError(this.INVALID_VALUE);return}let i=null;if(isTypedArray$1(n)||n instanceof DataView||n instanceof ArrayBuffer)i=arrayToUint8Array(n);else{this.setError(this.INVALID_VALUE);return}if(t+i.length>r._size){this.setError(this.INVALID_VALUE);return}e===this.ELEMENT_ARRAY_BUFFER&&r._elements.set(i,t),this._gl.bufferSubData(e,t,Uint8ArrayToVariant(i))},createBuffer(){let e=this._gl.createBuffer();if(!e||e<=0)return null;let t=new WebGLBuffer(e,this);return this._buffers[e]=t,t},deleteBuffer(e){if(!checkObject(e)||e!==null&&!(e instanceof WebGLBuffer))throw TypeError(`deleteBuffer(WebGLBuffer)`);if(!(e instanceof WebGLBuffer&&this._checkOwns(e))){this.setError(this.INVALID_OPERATION);return}this._vertexGlobalState._arrayBufferBinding===e&&this.bindBuffer(this.ARRAY_BUFFER,null),this._vertexObjectState._elementArrayBufferBinding===e&&this.bindBuffer(this.ELEMENT_ARRAY_BUFFER,null),this._vertexObjectState===this._defaultVertexObjectState&&this._vertexObjectState.releaseArrayBuffer(e),e._pendingDelete=!0,e._checkDelete()},getBufferParameter(e=0,t=0){if(e!==this.ARRAY_BUFFER&&e!==this.ELEMENT_ARRAY_BUFFER)return this.setError(this.INVALID_ENUM),null;switch(t){case this.BUFFER_SIZE:case this.BUFFER_USAGE:return this._gl.getBufferParameteriv(e|0,t|0)[0];default:return this.setError(this.INVALID_ENUM),null}},_getActiveBuffer(e){return e===this.ARRAY_BUFFER?this._vertexGlobalState._arrayBufferBinding:e===this.ELEMENT_ARRAY_BUFFER?this._vertexObjectState._elementArrayBufferBinding:null}};function installBufferBindingMethods(e){Object.assign(e,Mn)}const Nn={activeTexture(e=0){let t=e-this.TEXTURE0;if(t>=0&&t<this._textureUnits.length){this._activeTextureUnit=t,this._gl.activeTexture(e);return}this.setError(this.INVALID_ENUM)},bindTexture(e=0,t){if(!checkObject(t))throw TypeError(`bindTexture(GLenum, WebGLTexture)`);if(!this._validTextureTarget(e)){this.setError(this.INVALID_ENUM);return}let n=0;if(!t)t=null;else if(t instanceof WebGLTexture&&t._pendingDelete)return;else if(this._checkWrapper(t,WebGLTexture)){if(t._binding&&t._binding!==e){this.setError(this.INVALID_OPERATION);return}t._binding=e,t._complete&&(n=t._|0)}else return;this._saveError(),this._gl.bindTexture(e,n);let r=this.getError();if(this._restoreError(r),r!==this.NO_ERROR)return;let i=this._getActiveTextureUnit(),a=this._getActiveTexture(e);a!==t&&(a&&(--a._refCount,a._checkDelete()),t&&(t._refCount+=1)),e===this.TEXTURE_2D?i._bind2D=t:e===this.TEXTURE_CUBE_MAP&&(i._bindCube=t)},createTexture(){let e=this._gl.createTexture();if(e<=0)return null;let t=new WebGLTexture(e,this);return this._textures[e]=t,t},deleteTexture(e){if(!checkObject(e))throw TypeError(`deleteTexture(WebGLTexture)`);if(e instanceof WebGLTexture){if(!this._checkOwns(e)){this.setError(this.INVALID_OPERATION);return}}else return;let t=this._activeTextureUnit;for(let t=0;t<this._textureUnits.length;++t){let n=this._textureUnits[t];n._bind2D===e?(this.activeTexture(this.TEXTURE0+t),this.bindTexture(this.TEXTURE_2D,null)):n._bindCube===e&&(this.activeTexture(this.TEXTURE0+t),this.bindTexture(this.TEXTURE_CUBE_MAP,null))}this.activeTexture(this.TEXTURE0+t),this._detachTextureFromAllFramebuffers(e),e._pendingDelete=!0,e._checkDelete()},_detachTextureFromAllFramebuffers(e){let t=this._activeFramebuffer,n=this._getAttachments(),r=!1;for(let i in this._framebuffers){let a=this._framebuffers[i];if(!(!a||!a._linked(e))){a!==t&&(this._gl.bindFramebuffer(this.FRAMEBUFFER,a._|0),r=!0);for(let t=0;t<n.length;++t){let r=n[t];a._attachments[r]===e&&(this._gl.framebufferTexture2D(this.FRAMEBUFFER,r,a._attachmentFace[r]||this.TEXTURE_2D,0,a._attachmentLevel[r]||0),a._setAttachment(null,r))}}}r&&this._gl.bindFramebuffer(this.FRAMEBUFFER,t?t._|0:this._gtkFboId)},pixelStorei(e=0,t=0){if(typeof t==`boolean`&&(t=t===!1?0:1),e===this.UNPACK_ALIGNMENT)if(t===1||t===2||t===4||t===8)this._unpackAlignment=t;else{this.setError(this.INVALID_VALUE);return}else if(e===this.PACK_ALIGNMENT)if(t===1||t===2||t===4||t===8)this._packAlignment=t;else{this.setError(this.INVALID_VALUE);return}else if(e===this.UNPACK_COLORSPACE_CONVERSION_WEBGL){if(!(t===this.NONE||t===this.BROWSER_DEFAULT_WEBGL)){this.setError(this.INVALID_VALUE);return}}else if(e===this.UNPACK_FLIP_Y_WEBGL){this._unpackFlipY=!!t;return}else if(e===this.UNPACK_PREMULTIPLY_ALPHA_WEBGL){this._unpackPremultAlpha=!!t;return}this._gl.pixelStorei(e,t)}};function installTextureLifecycleMethods(e){Object.assign(e,Nn)}const Pn={texImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0,c){let l=0,u=0,d=0,f,p,m=0;if(arguments.length===6)if(s=i,d=r,a instanceof St.Pixbuf)p=a,l=p.get_width(),u=p.get_height(),c=p.get_pixels();else{f=a;let e=extractImageData(f);if(e==null)throw TypeError(`texImage2D(GLenum, GLint, GLenum, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)`);l=e.width,u=e.height,c=e.data}else arguments.length===9&&(l=r,u=i,m=a,d=o,c=c);if(typeof c!=`object`&&c!==void 0)throw TypeError(`texImage2D(GLenum, GLint, GLenum, GLint, GLint, GLint, GLenum, GLenum, Uint8Array)`);if(!checkFormat(this,d)||!checkFormat(this,n)){this.setError(this.INVALID_ENUM);return}if(s===this.FLOAT&&!this._extensions.oes_texture_float){this.setError(this.INVALID_ENUM);return}let h=this._getTexImage(e);if(!h||d!==n){this.setError(this.INVALID_OPERATION);return}let g=this._computePixelSize(s,d);if(g===0||!this._checkDimensions(e,l,u,t))return;let _=convertPixels(c),v=this._computeRowStride(l,g),y=v*u;if(_&&_.length<y){this.setError(this.INVALID_OPERATION);return}if(m!==0||validCubeTarget(this,e)&&l!==u){this.setError(this.INVALID_VALUE);return}if(this._unpackPremultAlpha&&_&&d===this.RGBA&&(_=premultiplyAlpha(_)),this._unpackFlipY&&_&&l>0&&u>0){let e=new Uint8Array(_.length);for(let t=0;t<u;t++){let n=t*v,r=(u-1-t)*v;e.set(_.subarray(n,n+v),r)}_=e}this._saveError(),this._gl.texImage2D(e,t,n,l,u,m,d,s,Uint8ArrayToVariant(_));let b=this.getError();if(this._restoreError(b),b!==this.NO_ERROR)return;h._levelWidth[t]=l,h._levelHeight[t]=u,h._format=d,h._type=s;let x=this._activeFramebuffer;if(x){let e=!1,t=this._getAttachments();for(let n=0;n<t.length;++n)if(x._attachments[t[n]]===h){e=!0;break}e&&this._activeFramebuffer&&this._updateFramebufferAttachments(this._activeFramebuffer)}},texSubImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0,c){let l=0,u=0,d=0,f,p;if(arguments.length===7)if(s=a,d=i,o instanceof St.Pixbuf)p=o,l=p.get_width(),u=p.get_height(),c=p.get_pixels();else{f=o;let e=extractImageData(f);if(e==null)throw TypeError(`texSubImage2D(GLenum, GLint, GLint, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)`);l=e.width,u=e.height,c=e.data}else l=i,u=a,d=o;if(typeof c!=`object`)throw TypeError(`texSubImage2D(GLenum, GLint, GLint, GLint, GLint, GLint, GLenum, GLenum, Uint8Array)`);if(!this._getTexImage(e)){this.setError(this.INVALID_OPERATION);return}if(s===this.FLOAT&&!this._extensions.oes_texture_float){this.setError(this.INVALID_ENUM);return}let m=this._computePixelSize(s,d);if(m===0||!this._checkDimensions(e,l,u,t))return;if(n<0||r<0){this.setError(this.INVALID_VALUE);return}let h=convertPixels(c),g=this._computeRowStride(l,m),_=g*u;if(!h||h.length<_){this.setError(this.INVALID_OPERATION);return}if(this._unpackPremultAlpha&&h&&d===this.RGBA&&(h=premultiplyAlpha(h)),this._unpackFlipY&&h&&l>0&&u>0){let e=new Uint8Array(h.length);for(let t=0;t<u;t++){let n=t*g,r=(u-1-t)*g;e.set(h.subarray(n,n+g),r)}h=e}this._gl.texSubImage2D(e,t,n,r,l,u,d,s,Uint8ArrayToVariant(h))}};function installTexImage2DMethods(e){Object.assign(e,Pn)}var Fn=__toESM(__commonJSMin((e=>{e.INT_MIN=-1<<31,e.isPow2=function(e){return!(e&e-1)&&!!e},e.log2=function(e){var t=(e>65535)<<4,n;return e>>>=t,n=(e>255)<<3,e>>>=n,t|=n,n=(e>15)<<2,e>>>=n,t|=n,n=(e>3)<<1,e>>>=n,t|=n,t|e>>1},e.nextPow2=function(e){return e+=e===0,--e,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e+1},(function(e){for(var t=0;t<256;++t){var n=t,r=t,i=7;for(n>>>=1;n;n>>>=1)r<<=1,r|=n&1,--i;e[t]=r<<i&255}})(Array(256))}))(),1);const In={copyTexImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0){let c=this._getTexImage(e);if(!c){this.setError(this.INVALID_OPERATION);return}if(n!==this.RGBA&&n!==this.RGB&&n!==this.ALPHA&&n!==this.LUMINANCE&&n!==this.LUMINANCE_ALPHA){this.setError(this.INVALID_ENUM);return}if(t<0||a<0||o<0||s!==0){this.setError(this.INVALID_VALUE);return}if(t>0&&!(Fn.isPow2(a)&&Fn.isPow2(o))){this.setError(this.INVALID_VALUE);return}this._saveError(),this._gl.copyTexImage2D(e,t,n,r,i,a,o,s);let l=this.getError();this._restoreError(l),l===this.NO_ERROR&&(c._levelWidth[t]=a,c._levelHeight[t]=o,c._format=this.RGBA,c._type=this.UNSIGNED_BYTE)},copyTexSubImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0){if(!this._getTexImage(e)){this.setError(this.INVALID_OPERATION);return}if(o<0||s<0||n<0||r<0||t<0){this.setError(this.INVALID_VALUE);return}this._gl.copyTexSubImage2D(e,t,n,r,i,a,o,s)},compressedTexImage2D(e,t,n,r,i,a,o){this._gl.compressedTexImage2D(e,t,n,r,i,a,Uint8ArrayToVariant(arrayToUint8Array(o)))},compressedTexSubImage2D(e,t,n,r,i,a,o,s){this._gl.compressedTexSubImage2D(e,t,n,r,i,a,o,Uint8ArrayToVariant(arrayToUint8Array(s)))}};function installCopyAndCompressedTextureMethods(e){Object.assign(e,In)}const Ln={texParameterf(e=0,t=0,n){if(n=+n,this._checkTextureTarget(e)){switch(this._verifyTextureCompleteness(e,t,n),t){case this.TEXTURE_MIN_FILTER:case this.TEXTURE_MAG_FILTER:case this.TEXTURE_WRAP_S:case this.TEXTURE_WRAP_T:this._gl.texParameterf(e,t,n);return}let r=this._extensions.ext_texture_filter_anisotropic;if(r&&t===r.TEXTURE_MAX_ANISOTROPY_EXT){this._gl.texParameterf(e,t,n);return}this.setError(this.INVALID_ENUM)}},texParameteri(e=0,t=0,n=0){if(this._checkTextureTarget(e)){switch(this._verifyTextureCompleteness(e,t,n),t){case this.TEXTURE_MIN_FILTER:case this.TEXTURE_MAG_FILTER:case this.TEXTURE_WRAP_S:case this.TEXTURE_WRAP_T:this._gl.texParameteri(e,t,n);return}let r=this._extensions.ext_texture_filter_anisotropic;if(r&&t===r.TEXTURE_MAX_ANISOTROPY_EXT){this._gl.texParameteri(e,t,n);return}this.setError(this.INVALID_ENUM)}},getTexParameter(e=0,t=0){if(!this._checkTextureTarget(e))return null;let n=this._getActiveTextureUnit();if(e===this.TEXTURE_2D&&!n._bind2D||e===this.TEXTURE_CUBE_MAP&&!n._bindCube)return this.setError(this.INVALID_OPERATION),null;switch(t){case this.TEXTURE_MAG_FILTER:case this.TEXTURE_MIN_FILTER:case this.TEXTURE_WRAP_S:case this.TEXTURE_WRAP_T:return this._getTexParameterDirect(e,t)}let r=this._extensions.ext_texture_filter_anisotropic;return r&&t===r.TEXTURE_MAX_ANISOTROPY_EXT?this._getTexParameterDirect(e,t):(this.setError(this.INVALID_ENUM),null)},_getTexParameterDirect(e=0,t=0){return this._gl.getTexParameterx(e,t)?.unpack()}};function installTextureParameterMethods(e){Object.assign(e,Ln)}const Rn={_getActiveTextureUnit(){return this._textureUnits[this._activeTextureUnit]},_getActiveTexture(e){let t=this._getActiveTextureUnit();return e===this.TEXTURE_2D?t._bind2D:e===this.TEXTURE_CUBE_MAP?t._bindCube:null},_getTexImage(e){let t=this._getActiveTextureUnit();return e===this.TEXTURE_2D?t._bind2D:validCubeTarget(this,e)?t._bindCube:(this.setError(this.INVALID_ENUM),null)},_checkTextureTarget(e){let t=this._getActiveTextureUnit(),n=null;if(e===this.TEXTURE_2D)n=t._bind2D;else if(e===this.TEXTURE_CUBE_MAP)n=t._bindCube;else return this.setError(this.INVALID_ENUM),!1;return n?!0:(this.setError(this.INVALID_OPERATION),!1)},_validTextureTarget(e){return e===this.TEXTURE_2D||e===this.TEXTURE_CUBE_MAP},_validCubeTarget(e){return e===this.TEXTURE_CUBE_MAP_POSITIVE_X||e===this.TEXTURE_CUBE_MAP_NEGATIVE_X||e===this.TEXTURE_CUBE_MAP_POSITIVE_Y||e===this.TEXTURE_CUBE_MAP_NEGATIVE_Y||e===this.TEXTURE_CUBE_MAP_POSITIVE_Z||e===this.TEXTURE_CUBE_MAP_NEGATIVE_Z},_verifyTextureCompleteness(e,t,n){let r=this._getActiveTextureUnit(),i=null;if(e===this.TEXTURE_2D?i=r._bind2D:this._validCubeTarget(e)&&(i=r._bindCube),this._extensions.oes_texture_float&&!this._extensions.oes_texture_float_linear&&i&&i._type===this.FLOAT&&(t===this.TEXTURE_MAG_FILTER||t===this.TEXTURE_MIN_FILTER)&&(n===this.LINEAR||n===this.LINEAR_MIPMAP_NEAREST||n===this.NEAREST_MIPMAP_LINEAR||n===this.LINEAR_MIPMAP_LINEAR)){i._complete=!1,this.bindTexture(e,i);return}i&&i._complete===!1&&(i._complete=!0,this.bindTexture(e,i))},_computePixelSize(e,t){let n=formatSize(this,t);if(n===0)return this.setError(this.INVALID_ENUM),0;switch(e){case this.UNSIGNED_BYTE:return n;case this.UNSIGNED_SHORT_5_6_5:if(t!==this.RGB){this.setError(this.INVALID_OPERATION);break}return 2;case this.UNSIGNED_SHORT_4_4_4_4:case this.UNSIGNED_SHORT_5_5_5_1:if(t!==this.RGBA){this.setError(this.INVALID_OPERATION);break}return 2;case this.FLOAT:return 1}return this.setError(this.INVALID_ENUM),0},_computeRowStride(e,t){let n=e*t;return n%this._unpackAlignment&&(n+=this._unpackAlignment-n%this._unpackAlignment),n},_checkDimensions(e,t,n,r){if(r<0||t<0||n<0)return this.setError(this.INVALID_VALUE),!1;if(e===this.TEXTURE_2D){if(t>this._maxTextureSize||n>this._maxTextureSize||r>this._maxTextureLevel)return this.setError(this.INVALID_VALUE),!1}else if(this._validCubeTarget(e)){if(t>this._maxCubeMapSize||n>this._maxCubeMapSize||r>this._maxCubeMapLevel)return this.setError(this.INVALID_VALUE),!1}else return this.setError(this.INVALID_ENUM),!1;return!0}};function installTextureIntrospectionMethods(e){Object.assign(e,Rn)}function installTextureManagementMethods(e){installTextureLifecycleMethods(e),installTexImage2DMethods(e),installCopyAndCompressedTextureMethods(e),installTextureParameterMethods(e),installTextureIntrospectionMethods(e)}const zn={bindFramebuffer(e,t){if(!checkObject(t))throw TypeError(`bindFramebuffer(GLenum, WebGLFramebuffer)`);if(e!==this.FRAMEBUFFER){this.setError(this.INVALID_ENUM);return}if(!t)this._gl.bindFramebuffer(this.FRAMEBUFFER,this._gtkFboId);else if(t._pendingDelete)return;else if(this._checkWrapper(t,WebGLFramebuffer))this._gl.bindFramebuffer(this.FRAMEBUFFER,t._|0);else return;let n=this._activeFramebuffer;n!==t&&(n&&(--n._refCount,n._checkDelete()),t&&(t._refCount+=1)),this._activeFramebuffer=t,t&&this._updateFramebufferAttachments(t)},bindRenderbuffer(e,t){if(!checkObject(t))throw TypeError(`bindRenderbuffer(GLenum, WebGLRenderbuffer)`);if(e!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}if(!t)this._gl.bindRenderbuffer(e|0,0);else if(t._pendingDelete)return;else if(this._checkWrapper(t,WebGLRenderbuffer))this._gl.bindRenderbuffer(e|0,t._|0);else return;let n=this._activeRenderbuffer;n!==t&&(n&&(--n._refCount,n._checkDelete()),t&&(t._refCount+=1)),this._activeRenderbuffer=t},framebufferRenderbuffer(e,t,n,r){if(!checkObject(r))throw TypeError(`framebufferRenderbuffer(GLenum, GLenum, GLenum, WebGLRenderbuffer)`);if(e!==this.FRAMEBUFFER||!this._validFramebufferAttachment(t)||n!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}let i=this._activeFramebuffer;if(!i){this.setError(this.INVALID_OPERATION);return}r&&!this._checkWrapper(r,WebGLRenderbuffer)||(i._setAttachment(r,t),this._updateFramebufferAttachments(i))},framebufferTexture2D(e,t,n,r,i=0){if(e|=0,t|=0,n|=0,i|=0,!checkObject(r))throw TypeError(`framebufferTexture2D(GLenum, GLenum, GLenum, WebGLTexture, GLint)`);if(e!==this.FRAMEBUFFER||!this._validFramebufferAttachment(t)){this.setError(this.INVALID_ENUM);return}if(i!==0){this.setError(this.INVALID_VALUE);return}if(r&&!this._checkWrapper(r,WebGLTexture))return;if(n===this.TEXTURE_2D){if(r&&r._binding!==this.TEXTURE_2D){this.setError(this.INVALID_OPERATION);return}}else if(this._validCubeTarget(n)){if(r&&r._binding!==this.TEXTURE_CUBE_MAP){this.setError(this.INVALID_OPERATION);return}}else{this.setError(this.INVALID_ENUM);return}let a=this._activeFramebuffer;if(!a){this.setError(this.INVALID_OPERATION);return}a._attachmentLevel[t]=i,a._attachmentFace[t]=n,a._setAttachment(r,t),this._updateFramebufferAttachments(a)},createFramebuffer(){let e=this._gl.createFramebuffer();if(e<=0)return null;let t=new WebGLFramebuffer(e,this);return this._framebuffers[e]=t,t},deleteFramebuffer(e){if(!checkObject(e))throw TypeError(`deleteFramebuffer(WebGLFramebuffer)`);if(!(e instanceof WebGLFramebuffer&&this._checkOwns(e))){this.setError(this.INVALID_OPERATION);return}this._activeFramebuffer===e&&this.bindFramebuffer(this.FRAMEBUFFER,null),e._pendingDelete=!0,e._checkDelete()},createRenderbuffer(){let e=this._gl.createRenderbuffer();if(e<=0)return null;let t=new WebGLRenderbuffer(e,this);return this._renderbuffers[e]=t,t},deleteRenderbuffer(e){if(!checkObject(e))throw TypeError(`deleteRenderbuffer(WebGLRenderbuffer)`);if(!(e instanceof WebGLRenderbuffer&&this._checkOwns(e))){this.setError(this.INVALID_OPERATION);return}this._activeRenderbuffer===e&&this.bindRenderbuffer(this.RENDERBUFFER,null),this._detachRenderbufferFromAllFramebuffers(e),e._pendingDelete=!0,e._checkDelete()},renderbufferStorage(e=0,t=0,n=0,r=0){if(e!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}let i=this._activeRenderbuffer;if(!i){this.setError(this.INVALID_OPERATION);return}if(t!==this.RGBA4&&t!==this.RGB565&&t!==this.RGB5_A1&&t!==this.DEPTH_COMPONENT16&&t!==this.STENCIL_INDEX&&t!==this.STENCIL_INDEX8&&t!==this.DEPTH_STENCIL){this.setError(this.INVALID_ENUM);return}this._saveError(),this._gl.renderbufferStorage(e,t,n,r);let a=this.getError();if(this._restoreError(a),a!==this.NO_ERROR)return;i._width=n,i._height=r,i._format=t;let o=this._activeFramebuffer;if(o){let e=!1,t=this._getAttachments();for(let n=0;n<t.length;++n)if(o._attachments[t[n]]===i){e=!0;break}e&&this._updateFramebufferAttachments(this._activeFramebuffer)}},getFramebufferAttachmentParameter(e=0,t=0,n=0){if(e!==this.FRAMEBUFFER||!this._validFramebufferAttachment(t))return this.setError(this.INVALID_ENUM),null;let r=this._activeFramebuffer;if(!r)return this.setError(this.INVALID_OPERATION),null;let i=r._attachments[t];if(i===null){if(n===this.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)return this.NONE}else if(i instanceof WebGLTexture)switch(n){case this.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:return i;case this.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:return this.TEXTURE;case this.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:return r._attachmentLevel[t];case this.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:{let e=r._attachmentFace[t];return e===this.TEXTURE_2D?0:e}}else if(i instanceof WebGLRenderbuffer)switch(n){case this.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:return i;case this.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:return this.RENDERBUFFER}return this.setError(this.INVALID_ENUM),null},getRenderbufferParameter(e=0,t=0){if(e!==this.RENDERBUFFER)return this.setError(this.INVALID_ENUM),null;let n=this._activeRenderbuffer;if(!n)return this.setError(this.INVALID_OPERATION),null;switch(t){case this.RENDERBUFFER_INTERNAL_FORMAT:return n._format;case this.RENDERBUFFER_WIDTH:return n._width;case this.RENDERBUFFER_HEIGHT:return n._height;case this.MAX_RENDERBUFFER_SIZE:return this._maxRenderbufferSize;case this.RENDERBUFFER_RED_SIZE:case this.RENDERBUFFER_GREEN_SIZE:case this.RENDERBUFFER_BLUE_SIZE:case this.RENDERBUFFER_ALPHA_SIZE:case this.RENDERBUFFER_DEPTH_SIZE:case this.RENDERBUFFER_STENCIL_SIZE:return this._gl.getRenderbufferParameter(e,t)}return this.setError(this.INVALID_ENUM),null},checkFramebufferStatus(e){if(e!==this.FRAMEBUFFER)return this.setError(this.INVALID_ENUM),0;let t=this._activeFramebuffer;return t?this._preCheckFramebufferStatus(t):this.FRAMEBUFFER_COMPLETE},_preCheckFramebufferStatus(e){let t=e._attachments,n=[],r=[],i=t[this.DEPTH_ATTACHMENT],a=t[this.DEPTH_STENCIL_ATTACHMENT],o=t[this.STENCIL_ATTACHMENT];if(a&&(o||i)||o&&i)return this.FRAMEBUFFER_UNSUPPORTED;let s=this._getColorAttachments(),c=0;for(let e in t)t[e]&&s.indexOf(Number(e))!==-1&&c++;if(c===0)return this.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;if(a instanceof WebGLTexture)return this.FRAMEBUFFER_UNSUPPORTED;if(a instanceof WebGLRenderbuffer){if(a._format!==this.DEPTH_STENCIL)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;n.push(a._width),r.push(a._height)}if(i instanceof WebGLTexture)return this.FRAMEBUFFER_UNSUPPORTED;if(i instanceof WebGLRenderbuffer){if(i._format!==this.DEPTH_COMPONENT16)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;n.push(i._width),r.push(i._height)}if(o instanceof WebGLTexture)return this.FRAMEBUFFER_UNSUPPORTED;if(o instanceof WebGLRenderbuffer){if(o._format!==this.STENCIL_INDEX8)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;n.push(o._width),r.push(o._height)}let l=!1;for(let i=0;i<s.length;++i){let a=t[s[i]];if(a instanceof WebGLTexture){if(a._format!==this.RGBA||!(a._type===this.UNSIGNED_BYTE||a._type===this.FLOAT))return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;l=!0;let t=e._attachmentLevel[this.COLOR_ATTACHMENT0];if(t===null)throw TypeError(`level is null!`);n.push(a._levelWidth[t]),r.push(a._levelHeight[t])}else if(a instanceof WebGLRenderbuffer){let e=a._format;if(e!==this.RGBA4&&e!==this.RGB565&&e!==this.RGB5_A1)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;l=!0,n.push(a._width),r.push(a._height)}}if(!l&&!o&&!i&&!a)return this.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;if(n.length<=0||r.length<=0)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;for(let e=1;e<n.length;++e)if(n[e-1]!==n[e]||r[e-1]!==r[e])return this.FRAMEBUFFER_INCOMPLETE_DIMENSIONS;return n[0]===0||r[0]===0?this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:(e._width=n[0],e._height=r[0],this.FRAMEBUFFER_COMPLETE)},_framebufferOk(){let e=this._activeFramebuffer;return e&&this._preCheckFramebufferStatus(e)!==this.FRAMEBUFFER_COMPLETE?(this.setError(this.INVALID_FRAMEBUFFER_OPERATION),!1):!0},_validFramebufferAttachment(e){switch(e){case this.DEPTH_ATTACHMENT:case this.STENCIL_ATTACHMENT:case this.DEPTH_STENCIL_ATTACHMENT:case this.COLOR_ATTACHMENT0:return!0}if(this._extensions.webgl_draw_buffers){let t=this._extensions.webgl_draw_buffers;return e<t.COLOR_ATTACHMENT0_WEBGL+t._maxDrawBuffers}return!1},_updateFramebufferAttachments(e){if(!e)return;let t=e._status,n=this._getAttachments();if(e._status=this._preCheckFramebufferStatus(e),e._status!==this.FRAMEBUFFER_COMPLETE){if(t===this.FRAMEBUFFER_COMPLETE)for(let t=0;t<n.length;++t){let r=n[t];this._gl.framebufferTexture2D(this.FRAMEBUFFER,r,e._attachmentFace[r]||0,0,e._attachmentLevel[r]||0)}return}for(let t=0;t<n.length;++t){let r=n[t];this._gl.framebufferTexture2D(this.FRAMEBUFFER,r,e._attachmentFace[r]||0,0,e._attachmentLevel[r]||0)}for(let t=0;t<n.length;++t){let r=n[t],i=e._attachments[r];i instanceof WebGLTexture?this._gl.framebufferTexture2D(this.FRAMEBUFFER,r,e._attachmentFace[r]||0,i._|0,e._attachmentLevel[r]||0):i instanceof WebGLRenderbuffer&&this._gl.framebufferRenderbuffer(this.FRAMEBUFFER,r,this.RENDERBUFFER,i._|0)}},_tryDetachFramebuffer(e,t){if(e&&e._linked(t)){let n=this._getAttachments();for(let r=0;r<n.length;++r)e._attachments[n[r]]===t&&this.framebufferTexture2D(this.FRAMEBUFFER,n[r]|0,this.TEXTURE_2D,null)}},_detachRenderbufferFromAllFramebuffers(e){let t=this._activeFramebuffer,n=this._getAttachments(),r=!1;for(let i in this._framebuffers){let a=this._framebuffers[i];if(!(!a||!a._linked(e))){a!==t&&(this._gl.bindFramebuffer(this.FRAMEBUFFER,a._|0),r=!0);for(let t=0;t<n.length;++t){let r=n[t];a._attachments[r]===e&&(this._gl.framebufferRenderbuffer(this.FRAMEBUFFER,r,this.RENDERBUFFER,0),a._setAttachment(null,r))}}}r&&this._gl.bindFramebuffer(this.FRAMEBUFFER,t?t._|0:this._gtkFboId)},_getAttachments(){return this._extensions.webgl_draw_buffers?this._extensions.webgl_draw_buffers._ALL_ATTACHMENTS:this.DEFAULT_ATTACHMENTS},_getColorAttachments(){return this._extensions.webgl_draw_buffers?this._extensions.webgl_draw_buffers._ALL_COLOR_ATTACHMENTS:this.DEFAULT_COLOR_ATTACHMENTS},_resizeDrawingBuffer(e,t){let n=this._activeFramebuffer,r=this._getActiveTexture(this.TEXTURE_2D),i=this._activeRenderbuffer,a=this._contextAttributes,o=this._drawingBuffer;o?._framebuffer&&this._gl.bindFramebuffer(this.FRAMEBUFFER,o?._framebuffer);let s=this._getAttachments();for(let e=0;e<s.length;++e)this._gl.framebufferTexture2D(this.FRAMEBUFFER,s[e],this.TEXTURE_2D,0,0);o?._color&&this._gl.bindTexture(this.TEXTURE_2D,o?._color);let c=a.alpha?this.RGBA:this.RGB;this._gl.texImage2D(this.TEXTURE_2D,0,c,e,t,0,c,this.UNSIGNED_BYTE,Uint8ArrayToVariant(null)),this._gl.texParameteri(this.TEXTURE_2D,this.TEXTURE_MIN_FILTER,this.NEAREST),this._gl.texParameteri(this.TEXTURE_2D,this.TEXTURE_MAG_FILTER,this.NEAREST),o?._color&&this._gl.framebufferTexture2D(this.FRAMEBUFFER,this.COLOR_ATTACHMENT0,this.TEXTURE_2D,o?._color,0);let l=0,u=0;a.depth&&a.stencil?(l=this.DEPTH_STENCIL,u=this.DEPTH_STENCIL_ATTACHMENT):a.depth?(l=33191,u=this.DEPTH_ATTACHMENT):a.stencil&&(l=this.STENCIL_INDEX8,u=this.STENCIL_ATTACHMENT),l&&(o?._depthStencil&&this._gl.bindRenderbuffer(this.RENDERBUFFER,o?._depthStencil),this._gl.renderbufferStorage(this.RENDERBUFFER,l,e,t),o?._depthStencil&&this._gl.framebufferRenderbuffer(this.FRAMEBUFFER,u,this.RENDERBUFFER,o?._depthStencil)),this.bindFramebuffer(this.FRAMEBUFFER,n),this.bindTexture(this.TEXTURE_2D,r),this.bindRenderbuffer(this.RENDERBUFFER,i)},_allocateDrawingBuffer(e,t){this._drawingBuffer=new WebGLDrawingBufferWrapper(this._gl.createFramebuffer(),this._gl.createTexture(),this._gl.createRenderbuffer()),this._resizeDrawingBuffer(e,t)},resize(e=0,t=0){if(e|=0,t|=0,e>0&&t>0)(e!==this.drawingBufferWidth||t!==this.drawingBufferHeight)&&this._resizeDrawingBuffer(e,t);else throw Error(`Invalid surface dimensions`)}};function installFramebufferMethods(e){Object.assign(e,zn)}var Bn=__commonJSMin(((e,t)=>{t.exports=`precision.highp.mediump.lowp.attribute.const.uniform.varying.break.continue.do.for.while.if.else.in.out.inout.float.int.uint.void.bool.true.false.discard.return.mat2.mat3.mat4.vec2.vec3.vec4.ivec2.ivec3.ivec4.bvec2.bvec3.bvec4.sampler1D.sampler2D.sampler3D.samplerCube.sampler1DShadow.sampler2DShadow.struct.asm.class.union.enum.typedef.template.this.packed.goto.switch.default.inline.noinline.volatile.public.static.extern.external.interface.long.short.double.half.fixed.unsigned.input.output.hvec2.hvec3.hvec4.dvec2.dvec3.dvec4.fvec2.fvec3.fvec4.sampler2DRect.sampler3DRect.sampler2DRectShadow.sizeof.cast.namespace.using`.split(`.`)})),Vn=__commonJSMin(((e,t)=>{t.exports=`<<= >>= ++ -- << >> <= >= == != && || += -= *= /= %= &= ^^ ^= |= ( ) [ ] . ! ~ * / % + - < > & ^ | ? : = , ; { }`.split(` `)})),Hn=__commonJSMin(((e,t)=>{t.exports=`abs.acos.all.any.asin.atan.ceil.clamp.cos.cross.dFdx.dFdy.degrees.distance.dot.equal.exp.exp2.faceforward.floor.fract.gl_BackColor.gl_BackLightModelProduct.gl_BackLightProduct.gl_BackMaterial.gl_BackSecondaryColor.gl_ClipPlane.gl_ClipVertex.gl_Color.gl_DepthRange.gl_DepthRangeParameters.gl_EyePlaneQ.gl_EyePlaneR.gl_EyePlaneS.gl_EyePlaneT.gl_Fog.gl_FogCoord.gl_FogFragCoord.gl_FogParameters.gl_FragColor.gl_FragCoord.gl_FragData.gl_FragDepth.gl_FragDepthEXT.gl_FrontColor.gl_FrontFacing.gl_FrontLightModelProduct.gl_FrontLightProduct.gl_FrontMaterial.gl_FrontSecondaryColor.gl_LightModel.gl_LightModelParameters.gl_LightModelProducts.gl_LightProducts.gl_LightSource.gl_LightSourceParameters.gl_MaterialParameters.gl_MaxClipPlanes.gl_MaxCombinedTextureImageUnits.gl_MaxDrawBuffers.gl_MaxFragmentUniformComponents.gl_MaxLights.gl_MaxTextureCoords.gl_MaxTextureImageUnits.gl_MaxTextureUnits.gl_MaxVaryingFloats.gl_MaxVertexAttribs.gl_MaxVertexTextureImageUnits.gl_MaxVertexUniformComponents.gl_ModelViewMatrix.gl_ModelViewMatrixInverse.gl_ModelViewMatrixInverseTranspose.gl_ModelViewMatrixTranspose.gl_ModelViewProjectionMatrix.gl_ModelViewProjectionMatrixInverse.gl_ModelViewProjectionMatrixInverseTranspose.gl_ModelViewProjectionMatrixTranspose.gl_MultiTexCoord0.gl_MultiTexCoord1.gl_MultiTexCoord2.gl_MultiTexCoord3.gl_MultiTexCoord4.gl_MultiTexCoord5.gl_MultiTexCoord6.gl_MultiTexCoord7.gl_Normal.gl_NormalMatrix.gl_NormalScale.gl_ObjectPlaneQ.gl_ObjectPlaneR.gl_ObjectPlaneS.gl_ObjectPlaneT.gl_Point.gl_PointCoord.gl_PointParameters.gl_PointSize.gl_Position.gl_ProjectionMatrix.gl_ProjectionMatrixInverse.gl_ProjectionMatrixInverseTranspose.gl_ProjectionMatrixTranspose.gl_SecondaryColor.gl_TexCoord.gl_TextureEnvColor.gl_TextureMatrix.gl_TextureMatrixInverse.gl_TextureMatrixInverseTranspose.gl_TextureMatrixTranspose.gl_Vertex.greaterThan.greaterThanEqual.inversesqrt.length.lessThan.lessThanEqual.log.log2.matrixCompMult.max.min.mix.mod.normalize.not.notEqual.pow.radians.reflect.refract.sign.sin.smoothstep.sqrt.step.tan.texture2D.texture2DLod.texture2DProj.texture2DProjLod.textureCube.textureCubeLod.texture2DLodEXT.texture2DProjLodEXT.textureCubeLodEXT.texture2DGradEXT.texture2DProjGradEXT.textureCubeGradEXT`.split(`.`)})),Un=__commonJSMin(((e,t)=>{t.exports=Bn().slice().concat(`layout.centroid.smooth.case.mat2x2.mat2x3.mat2x4.mat3x2.mat3x3.mat3x4.mat4x2.mat4x3.mat4x4.uvec2.uvec3.uvec4.samplerCubeShadow.sampler2DArray.sampler2DArrayShadow.isampler2D.isampler3D.isamplerCube.isampler2DArray.usampler2D.usampler3D.usamplerCube.usampler2DArray.coherent.restrict.readonly.writeonly.resource.atomic_uint.noperspective.patch.sample.subroutine.common.partition.active.filter.image1D.image2D.image3D.imageCube.iimage1D.iimage2D.iimage3D.iimageCube.uimage1D.uimage2D.uimage3D.uimageCube.image1DArray.image2DArray.iimage1DArray.iimage2DArray.uimage1DArray.uimage2DArray.image1DShadow.image2DShadow.image1DArrayShadow.image2DArrayShadow.imageBuffer.iimageBuffer.uimageBuffer.sampler1DArray.sampler1DArrayShadow.isampler1D.isampler1DArray.usampler1D.usampler1DArray.isampler2DRect.usampler2DRect.samplerBuffer.isamplerBuffer.usamplerBuffer.sampler2DMS.isampler2DMS.usampler2DMS.sampler2DMSArray.isampler2DMSArray.usampler2DMSArray`.split(`.`))})),Wn=__commonJSMin(((e,t)=>{var n=Hn();n=n.slice().filter(function(e){return!/^(gl\_|texture)/.test(e)}),t.exports=n.concat(`gl_VertexID.gl_InstanceID.gl_Position.gl_PointSize.gl_FragCoord.gl_FrontFacing.gl_FragDepth.gl_PointCoord.gl_MaxVertexAttribs.gl_MaxVertexUniformVectors.gl_MaxVertexOutputVectors.gl_MaxFragmentInputVectors.gl_MaxVertexTextureImageUnits.gl_MaxCombinedTextureImageUnits.gl_MaxTextureImageUnits.gl_MaxFragmentUniformVectors.gl_MaxDrawBuffers.gl_MinProgramTexelOffset.gl_MaxProgramTexelOffset.gl_DepthRangeParameters.gl_DepthRange.trunc.round.roundEven.isnan.isinf.floatBitsToInt.floatBitsToUint.intBitsToFloat.uintBitsToFloat.packSnorm2x16.unpackSnorm2x16.packUnorm2x16.unpackUnorm2x16.packHalf2x16.unpackHalf2x16.outerProduct.transpose.determinant.inverse.texture.textureSize.textureProj.textureLod.textureOffset.texelFetch.texelFetchOffset.textureProjOffset.textureLodOffset.textureProjLod.textureProjLodOffset.textureGrad.textureGradOffset.textureProjGrad.textureProjGradOffset`.split(`.`))})),Gn=__commonJSMin(((e,t)=>{t.exports=tokenize;var n=Bn(),r=Vn(),i=Hn(),a=Un(),o=Wn(),s=999,c=9999,l=0,u=1,d=2,f=3,p=4,m=5,h=6,g=7,_=8,v=9,y=10,b=11,x=[`block-comment`,`line-comment`,`preprocessor`,`operator`,`integer`,`float`,`ident`,`builtin`,`keyword`,`whitespace`,`eof`,`integer`];function tokenize(e){var t=0,S=0,C=s,w,T,E=[],D=[],O=1,k=0,A=0,ee=!1,te=!1,j=``,ne;e||={};var re=i,ie=n;e.version===`300 es`&&(re=o,ie=a);for(var ae={},oe={},t=0;t<re.length;t++)ae[re[t]]=!0;for(var t=0;t<ie.length;t++)oe[ie[t]]=!0;return function(e){return D=[],e===null?end():write(e)};function token(e){e.length&&D.push({type:x[C],data:e,position:A,line:O,column:k})}function write(e){t=0,e.toString&&(e=e.toString()),j+=e.replace(/\r\n/g,`
67
+ </node>`}const wn=e(import.meta.url);let Tn;function load$3(){return Tn===void 0&&(Tn=wn(`@gjsify/node-gi/gi`).requireGi(`Graphene`,`1.0`)),Tn}__name$1(load$3,`load`);var En=new Proxy(Object.create(null),{get(e,t){return load$3()[t]},has(e,t){return t in load$3()}});function captureWidgetPng(e){let t=e.get_native()?.get_renderer();if(!t)return null;let n=e.get_width(),r=e.get_height();if(n<=0||r<=0)return null;let i=bn.WidgetPaintable.new(e),a=bn.Snapshot.new();i.snapshot(a,n,r);let o=a.to_node();if(!o)return null;let s=new En.Rect;s.init(0,0,n,r);let c=t.render_texture(o,s).save_to_png_bytes().get_data();return c?new Uint8Array(c):null}function dumpGSettings(e){let t=yt.SettingsSchemaSource.get_default()?.lookup(e,!0);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`GSettings schema '${e}' is not installed`));let n=new yt.Settings({settings_schema:t}),r={};for(let e of t.list_keys())r[e]=n.get_value(e).recursiveUnpack();return r}function parseWidgetPath(e){let t=e.split(`/`).filter(e=>e.length>0);if(t.length===0)return null;let n=t[0].match(/^toplevel:(\d+)$/);if(!n)return null;let r=[];for(let e of t.slice(1)){let t=e.match(/^child:(\d+)$/);if(!t)return null;r.push(Number(t[1]))}return{toplevel:Number(n[1]),children:r}}function buildWidgetPath(e,t){return[`toplevel:${e}`,...t.map(e=>`child:${e}`)].join(`/`)}function widgetType(e){let t=e;return typeof t.$typeName==`string`&&t.$typeName.length>0?t.$typeName:t.constructor?.$gtype?.name??`GtkWidget`}function activateWidget(e){let t=e;if(typeof t.activate==`function`&&t.activate()===!0)return!0;let n=typeof t.get_parent==`function`?t.get_parent():null;if(n&&widgetType(n)===`GtkListBox`){let t=n,r=!1;return typeof t.select_row==`function`&&(t.select_row(e),r=!0),typeof t.emit==`function`&&(t.emit(`row-activated`,e),r=!0),r}return!1}function nthChild(e,t){let n=e.get_first_child(),r=0;for(;n&&r<t;)n=n.get_next_sibling(),r++;return r===t?n:null}function listToplevels(){let e=bn.Window.get_toplevels(),t=e.get_n_items(),n=[];for(let r=0;r<t;r++){let t=e.get_item(r);t&&n.push({path:`toplevel:${r}`,type:widgetType(t),title:t.get_title?.()??null,mapped:t.get_mapped(),focused:t.is_active??!1})}return n}function resolveWidgetPath(e){let t=parseWidgetPath(e);if(!t)return null;let n=bn.Window.get_toplevels().get_item(t.toplevel);if(!n)return null;for(let e of t.children)if(n=nthChild(n,e),!n)return null;return n}function dumpTree(e,t,n){let r={path:n,type:widgetType(e),name:e.get_name()||null,cssClasses:e.get_css_classes(),mapped:e.get_mapped(),visible:e.get_visible(),children:[]};if(t<=0)return r;let i=e.get_first_child(),a=0;for(;i;)r.children.push(dumpTree(i,t-1,`${n}/child:${a}`)),i=i.get_next_sibling(),a++;return r}function jsonSafe(e){let t=typeof e;return e==null||t===`string`||t===`number`||t===`boolean`?e??null:`[${t}]`}function getWidgetProperty(e,t){let n=e,r=t.replace(/-/g,`_`),i=t.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase());for(let e of[t,r,i])if(e in n)return jsonSafe(n[e])}function childIndex(e,t){let n=e.get_first_child(),r=0;for(;n;){if(n===t)return r;n=n.get_next_sibling(),r++}return-1}function pathOfWidget(e){let t=[],n=e,r=n.get_parent();for(;r;){let e=childIndex(r,n);if(e<0)return null;t.unshift(e),n=r,r=n.get_parent()}let i=bn.Window.get_toplevels(),a=i.get_n_items();for(let e=0;e<a;e++)if(i.get_item(e)===n)return buildWidgetPath(e,t);return null}function frameDelay(e){return new Promise(t=>{ht.timeout_add(ht.PRIORITY_DEFAULT,e,()=>(t(),ht.SOURCE_REMOVE))})}async function captureWidgetWhenRenderable(e,t=12,n=50){for(let r=0;r<t;r++){let t=captureWidgetPng(e);if(t)return t;await frameDelay(n)}return captureWidgetPng(e)}var DevtoolsService=class{constructor(e,t){this._app=e,this._options=t,this._exported=null,this._kinds=new Map,this._extensions=t.extend??[];for(let[e,t]of Object.entries(Cn))this._kinds.set(e,t);for(let e of this._extensions){for(let[t,n]of Object.entries(e.methodKinds))this._kinds.set(t,n);for(let[t,n]of Object.entries(e.handlers)){let e=n;this[t]=(...n)=>(this._guard(t),e(...n))}}}export(e,t){if(this._exported)return;let n=buildDevtoolsIfaceXml(this._extensions.flatMap(e=>e.methodsXml??[])),r=yt.DBusExportedObject.wrapJSObject(n,this);r.export(e,t),this._exported=r}unexport(){this._exported?.unexport(),this._exported=null}GetStatus(){let e=this._app.get_active_window(),t={appId:this._app.get_application_id()??`unknown`,instance:this._options.instance??`default`,activeWindow:e?{id:e.get_name()||`window`,title:e.get_title()??``,mapped:e.get_mapped()}:null,toplevelCount:bn.Window.get_toplevels().get_n_items(),focusedWidget:null,paused:this._isPaused()};for(let e of this._extensions){let n=e.contributeStatus?.();n&&Object.assign(t,n)}return JSON.stringify(t)}async Screenshot(e){let t=this._app.get_active_window();if(!t)return new Uint8Array;let n=captureWidgetPng(t);return n||=(t.present(),await captureWidgetWhenRenderable(t)),n??new Uint8Array}ListActions(){let e={app:describeActions(this._actionGroup(`app`)),win:describeActions(this._actionGroup(`win`))};return JSON.stringify(e)}ActivateAction(e,t,n){this._guard(`ActivateAction`);let r=this._scope(e);activateAction(this._requireGroup(r,t),t,this._parseValue(n))}ChangeActionState(e,t,n){this._guard(`ChangeActionState`);let r=this._scope(e);changeActionState(this._requireGroup(r,t),t,this._parseValue(n))}PresentWindow(){this._app.get_active_window()?.present()}ResizeWindow(e,t){this._guard(`ResizeWindow`);let n=this._app.get_active_window();if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no active window to resize`));let r=Math.max(1,Math.round(e)),i=Math.max(1,Math.round(t));return n.is_maximized()&&n.unmaximize(),n.is_fullscreen()&&n.unfullscreen(),n.set_default_size(r,i),[r,i]}ListToplevels(){return JSON.stringify(listToplevels())}DumpTree(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e||`active window`}'`));return JSON.stringify(dumpTree(n.widget,t>0?t:8,n.path))}GetProperty(e,t){let n=this._resolveRootWidget(e);if(!n)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));let r=getWidgetProperty(n.widget,t);if(r===void 0)throw Error(formatDbusErrorMessage(`not-found`,`widget has no property '${t}'`));return JSON.stringify(r)}GetFocused(){let e=this._app.get_active_window(),t=e?e.get_focus():null;return JSON.stringify(t?{path:pathOfWidget(t),name:t.get_name()||null,type:widgetType(t)}:null)}ActivateWidget(e){this._guard(`ActivateWidget`);let t=this._resolveRootWidget(e);if(!t)throw Error(formatDbusErrorMessage(`not-found`,`no widget at '${e}'`));return activateWidget(t.widget)}DumpGSettings(e){return JSON.stringify(dumpGSettings(e))}DumpCss(){return JSON.stringify(dumpCss())}SwapCss(e,t){return this._guard(`SwapCss`),swapCss(e,t)}_resolveRootWidget(e){if(!e||e===`window`||e===`active`){let e=this._app.get_active_window();return e?{widget:e,path:pathOfWidget(e)??`toplevel:0`}:null}let t=resolveWidgetPath(e);return t?{widget:t,path:e}:null}_isPaused(){return this._options.paused?.()??!1}_guard(e){let t=this._kinds.get(e);if(!t)throw Error(formatDbusErrorMessage(`internal`,`unclassified devtools method '${e}'`));if(t===`mutating`&&this._isPaused())throw Error(formatDbusErrorMessage(`paused`,`${e} rejected — external control is paused. Read-only methods keep working.`))}_scope(e){return e===`app`?`app`:`win`}_actionGroup(e){if(e===`app`)return this._app;if(this._options.winActionGroup)return this._options.winActionGroup;let t=this._app.get_active_window();return t instanceof bn.ApplicationWindow?t:null}_requireGroup(e,t){let n=this._actionGroup(e);if(!n)throw Error(formatDbusErrorMessage(`unavailable`,`no '${e}' action group`));if(!n.has_action(t))throw Error(formatDbusErrorMessage(`not-found`,`unknown action ${e}.${t}`));return n}_parseValue(e){if(!e||e===`null`)return null;try{return JSON.parse(e)}catch{throw Error(formatDbusErrorMessage(`invalid-params`,`value_json is not valid JSON: ${e}`))}}};const Dn=new Set;function envEnabled(){let e=ht.getenv(`GJSIFY_DEVTOOLS`);if(e==null)return!1;let t=e.toLowerCase();return t!==``&&t!==`0`&&t!==`false`}function envInstance(){let e=ht.getenv(`GJSIFY_DEVTOOLS_INSTANCE`);return e&&e!==``?e:void 0}function installDevtools(e,t={}){if(!(t.enabled??envEnabled()))return null;let n=new DevtoolsService(e,{...t,instance:t.instance??envInstance()}),r=e.get_dbus_connection(),i=e.get_dbus_object_path();if(r&&i){let t=`${i}/devtools`;n.export(r,t),console.log(`[gjsify-devtools] exported ${Sn} at ${t} (dest ${e.get_application_id()??`?`})`)}else console.error(`[gjsify-devtools] no session-bus connection yet — call installDevtools() from the GtkApplication "startup" handler`);return Dn.add(n),n}const On=e(import.meta.url);let kn;function load$2(){return kn===void 0&&(kn=On(`@gjsify/node-gi/gi`).requireGi(`GObject`,`2.0`)),kn}__name$1(load$2,`load`);var An=new Proxy(Object.create(null),{get(e,t){return load$2()[t]},has(e,t){return t in load$2()}}),Linkable=class{constructor(e){this._=0,this._references=[],this._refCount=0,this._pendingDelete=!1,this._binding=0,this._=e,this._references=[],this._refCount=0,this._pendingDelete=!1,this._binding=0}_link(e){return this._references.push(e),e._refCount+=1,!0}_unlink(e){let t=this._references.indexOf(e);if(t<0)return!1;for(;t>=0;)this._references[t]=this._references[this._references.length-1],this._references.pop(),--e._refCount,e._checkDelete(),t=this._references.indexOf(e);return!0}_linked(e){return this._references.indexOf(e)>=0}_checkDelete(){if(this._refCount<=0&&this._pendingDelete&&this._!==0){for(;this._references.length>0;)this._unlink(this._references[0]);this._performDelete(),this._=0}}_performDelete(){}},WebGLBuffer=class extends Linkable{constructor(e,t){super(e),this._size=0,this._elements=new Uint8Array,this._ctx=t}_performDelete(){let e=this._ctx;delete e._buffers[this._|0],e._gl.deleteBuffer(this._)}},WebGLUniformLocation=class{constructor(e,t,n){this._linkCount=0,this._array=null,this._=e,this._program=t,this._linkCount=t._linkCount,this._activeInfo=n,this._array=null}},WebGLDrawingBufferWrapper=class{constructor(e,t,n){this._framebuffer=e,this._color=t,this._depthStencil=n}},WebGLFramebuffer=class extends Linkable{constructor(e,t){if(super(e),this._binding=0,this._width=0,this._height=0,this._status=null,this._ctx=t,this._attachments={},this._attachments[t.COLOR_ATTACHMENT0]=null,this._attachments[t.DEPTH_ATTACHMENT]=null,this._attachments[t.STENCIL_ATTACHMENT]=null,this._attachments[t.DEPTH_STENCIL_ATTACHMENT]=null,this._attachmentLevel={},this._attachmentLevel[t.COLOR_ATTACHMENT0]=0,this._attachmentLevel[t.DEPTH_ATTACHMENT]=0,this._attachmentLevel[t.STENCIL_ATTACHMENT]=0,this._attachmentLevel[t.DEPTH_STENCIL_ATTACHMENT]=0,this._attachmentFace={},this._attachmentFace[t.COLOR_ATTACHMENT0]=0,this._attachmentFace[t.DEPTH_ATTACHMENT]=0,this._attachmentFace[t.STENCIL_ATTACHMENT]=0,this._attachmentFace[t.DEPTH_STENCIL_ATTACHMENT]=0,t._extensions.webgl_draw_buffers){let e=t._extensions.webgl_draw_buffers;this._attachments[e.COLOR_ATTACHMENT1_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT2_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT3_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT4_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT5_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT6_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT7_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT8_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT9_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT10_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT11_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT12_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT13_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT14_WEBGL]=null,this._attachments[e.COLOR_ATTACHMENT15_WEBGL]=null,this._attachments[t.NONE]=null,this._attachments[t.BACK]=null,this._attachmentLevel[e.COLOR_ATTACHMENT1_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT2_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT3_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT4_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT5_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT6_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT7_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT8_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT9_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT10_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT11_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT12_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT13_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT14_WEBGL]=0,this._attachmentLevel[e.COLOR_ATTACHMENT15_WEBGL]=0,this._attachmentLevel[t.NONE]=null,this._attachmentLevel[t.BACK]=null,this._attachmentFace[e.COLOR_ATTACHMENT1_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT2_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT3_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT4_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT5_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT6_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT7_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT8_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT9_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT10_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT11_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT12_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT13_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT14_WEBGL]=0,this._attachmentFace[e.COLOR_ATTACHMENT15_WEBGL]=0,this._attachmentFace[t.NONE]=null,this._attachmentFace[t.BACK]=null}}_clearAttachment(e){let t=this._attachments[e];t&&(this._attachments[e]=null,this._unlink(t))}_setAttachment(e,t){this._attachments[t]!==e&&(this._clearAttachment(t),e&&(this._attachments[t]=e,this._link(e)))}_performDelete(){let e=this._ctx;delete e._framebuffers[this._|0],e._gl.deleteFramebuffer(this._|0)}},WebGLRenderbuffer=class extends Linkable{constructor(e,t){super(e),this._binding=0,this._width=0,this._height=0,this._format=0,this._ctx=t,this._binding=0,this._width=0,this._height=0,this._format=0}_performDelete(){let e=this._ctx;delete e._renderbuffers[this._|0],e._gl.deleteRenderbuffer(this._)}},WebGLTexture=class extends Linkable{constructor(e,t){super(e),this._binding=0,this._levelWidth=new Int32Array(32),this._levelHeight=new Int32Array(32),this._format=0,this._type=0,this._complete=!0,this._ctx=t}_performDelete(){let e=this._ctx;delete e._textures[this._|0],e._gl.deleteTexture(this._|0)}},WebGLProgram$1=class extends Linkable{static{__name$1(this,`WebGLProgram`)}constructor(e,t){super(e),this._linkCount=0,this._linkStatus=!1,this._linkInfoLog=`not linked`,this._attributes=[],this._uniforms=[],this._ctx=t,this._linkCount=0,this._linkStatus=!1,this._linkInfoLog=`not linked`,this._attributes=[],this._uniforms=[]}_performDelete(){let e=this._ctx;delete e._programs[this._|0],e._gl.deleteProgram(this._|0)}},WebGLShader$1=class extends Linkable{static{__name$1(this,`WebGLShader`)}constructor(e,t,n){super(e),this._source=``,this._compileStatus=!1,this._compileInfo=``,this._needsRecompile=!1,this._type=n,this._ctx=t,this._source=``,this._compileStatus=!1,this._compileInfo=``}_performDelete(){let e=this._ctx;delete e._shaders[this._|0],e._gl.deleteShader(this._|0)}},WebGLShaderPrecisionFormat=class{constructor(e){this.rangeMin=e.rangeMin,this.rangeMax=e.rangeMax,this.precision=e.precision}},WebGLActiveInfo=class{constructor(e){this.size=e.size,this.type=e.type,this.name=e.name}},EXTBlendMinMax=class{constructor(){this.MIN_EXT=32775,this.MAX_EXT=32776}};function getEXTBlendMinMax(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`EXT_blend_minmax`)>=0&&(t=new EXTBlendMinMax),t}var EXTColorBufferFloat=class{};function getEXTColorBufferFloat(e){let t=e.getSupportedExtensions();return t&&t.indexOf(`EXT_color_buffer_float`)>=0?new EXTColorBufferFloat:null}var EXTColorBufferHalfFloat=class{};function getEXTColorBufferHalfFloat(e){let t=e.getSupportedExtensions();return t&&t.indexOf(`EXT_color_buffer_half_float`)>=0?new EXTColorBufferHalfFloat:null}var EXTTextureFilterAnisotropic=class{constructor(){this.TEXTURE_MAX_ANISOTROPY_EXT=34046,this.MAX_TEXTURE_MAX_ANISOTROPY_EXT=34047}};function getEXTTextureFilterAnisotropic(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`EXT_texture_filter_anisotropic`)>=0&&(t=new EXTTextureFilterAnisotropic),t}var OESElementIndexUint=class{};function getOESElementIndexUint(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`OES_element_index_uint`)>=0&&(t=new OESElementIndexUint),t}var OESStandardDerivatives=class{constructor(){this.FRAGMENT_SHADER_DERIVATIVE_HINT_OES=35723}};function getOESStandardDerivatives(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`OES_standard_derivatives`)>=0&&(t=new OESStandardDerivatives),t}var OESTextureFloatLinear=class{};function getOESTextureFloatLinear(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`OES_texture_float_linear`)>=0&&(t=new OESTextureFloatLinear),t}var OESTextureFloat=class{};function getOESTextureFloat(e){let t=null,n=e.getSupportedExtensions();return n&&n.indexOf(`OES_texture_float`)>=0&&(t=new OESTextureFloat),t}var OESTextureHalfFloat=class{constructor(){this.HALF_FLOAT_OES=36193}};function getOESTextureHalfFloat(e){let t=e.getSupportedExtensions();return t&&t.indexOf(`OES_texture_half_float`)>=0||e._native2?new OESTextureHalfFloat:null}var STACKGLDestroyContext=class{constructor(e){this.destroy=e.destroy.bind(e)}};function getSTACKGLDestroyContext(e){return new STACKGLDestroyContext(e)}var STACKGLResizeDrawingBuffer=class{constructor(e){this.resize=e.resize.bind(e)}};function getSTACKGLResizeDrawingBuffer(e){return new STACKGLResizeDrawingBuffer(e)}var WebGLContextAttributes=class{constructor(e,t,n,r,i,a,o,s){this.alpha=e,this.depth=t,this.stencil=n,this.antialias=r,this.premultipliedAlpha=i,this.preserveDrawingBuffer=a,this.preferLowPowerToHighPerformance=o,this.failIfMajorPerformanceCaveat=s}},WebGLTextureUnit=class{constructor(e,t){this._mode=0,this._bind2D=null,this._bindCube=null,this._ctx=e,this._idx=t}},WebGLVertexArrayObjectAttribute=class{constructor(e,t){this._isPointer=!1,this._pointerBuffer=null,this._pointerOffset=0,this._pointerSize=0,this._pointerStride=0,this._pointerType=0,this._pointerNormal=!1,this._divisor=0,this._inputSize=4,this._inputStride=0,this._ctx=e,this._idx=t,this._pointerType=e.FLOAT,this._clear()}_clear(){this._isPointer=!1,this._pointerBuffer=null,this._pointerOffset=0,this._pointerSize=0,this._pointerStride=0,this._pointerType=this._ctx.FLOAT,this._pointerNormal=!1,this._divisor=0,this._inputSize=4,this._inputStride=0}},WebGLVertexArrayGlobalAttribute=class{constructor(e){this._idx=0,this._idx=e,this._data=new Float32Array([0,0,0,1])}},WebGLVertexArrayObjectState=class{constructor(e){this._elementArrayBufferBinding=null;let t=e.getParameter(e.MAX_VERTEX_ATTRIBS);this._attribs=Array.from({length:t});for(let n=0;n<t;++n)this._attribs[n]=new WebGLVertexArrayObjectAttribute(e,n);this._elementArrayBufferBinding=null}setElementArrayBuffer(e){if(e!==null&&!(e instanceof WebGLBuffer))throw TypeError(`setElementArrayBuffer(WebGLBuffer?)`);let t=this._elementArrayBufferBinding;t!==e&&(t&&(--t._refCount,t._checkDelete()),e&&(e._refCount+=1),this._elementArrayBufferBinding=e)}cleanUp(){let e=this._elementArrayBufferBinding;e&&(--e._refCount,e._checkDelete(),this._elementArrayBufferBinding=null);for(let e=0;e<this._attribs.length;++e){let t=this._attribs[e];t._pointerBuffer&&(--t._pointerBuffer._refCount,t._pointerBuffer._checkDelete()),t._clear()}}releaseArrayBuffer(e){if(e)for(let t=0;t<this._attribs.length;++t){let n=this._attribs[t];n._pointerBuffer===e&&(--n._pointerBuffer._refCount,n._pointerBuffer._checkDelete(),n._clear())}}setVertexAttribPointer(e,t,n,r,i,a,o,s,c){let l=this._attribs[t];e!==l._pointerBuffer&&(l._pointerBuffer&&(--l._pointerBuffer._refCount,l._pointerBuffer._checkDelete()),e&&(e._refCount+=1),l._pointerBuffer=e),l._pointerSize=n,l._pointerOffset=r,l._pointerStride=i,l._pointerType=a,l._pointerNormal=o,l._inputStride=s,l._inputSize=c}},WebGLVertexArrayGlobalState=class{constructor(e){this._arrayBufferBinding=null;let t=e.getParameter(e.MAX_VERTEX_ATTRIBS);this._attribs=Array.from({length:t});for(let e=0;e<t;++e)this._attribs[e]=new WebGLVertexArrayGlobalAttribute(e);this._arrayBufferBinding=null}setArrayBuffer(e){if(e!==null&&!(e instanceof WebGLBuffer))throw TypeError(`setArrayBuffer(WebGLBuffer?)`);let t=this._arrayBufferBinding;t!==e&&(t&&(--t._refCount,t._checkDelete()),e&&(e._refCount+=1),this._arrayBufferBinding=e)}};function checkObject(e){return typeof e==`object`||e===void 0}function checkUniform(e,t){return t instanceof WebGLUniformLocation&&t._program===e&&t._linkCount===e._linkCount}function isTypedArray$1(e){return e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Uint32Array||e instanceof Int32Array||e instanceof Float32Array||e instanceof Float64Array}__name$1(isTypedArray$1,`isTypedArray`);function isValidString(e){let t=e.replace(/(?:\/\*(?:[\s\S]*?)\*\/)|(?:([\s;])+\/\/(?:.*)$)/gm,``);return!/["$`@\\'\0]/.test(t)}function vertexCount(e,t,n){switch(t){case e.TRIANGLES:return n-n%3;case e.LINES:return n-n%2;case e.LINE_LOOP:case e.POINTS:return n;case e.TRIANGLE_FAN:case e.LINE_STRIP:return n<2?0:n;case e.TRIANGLE_STRIP:return n<3?0:n;default:return-1}}function typeSize(e,t){switch(t){case e.UNSIGNED_BYTE:case e.BYTE:return 1;case e.UNSIGNED_SHORT:case e.SHORT:return 2;case e.UNSIGNED_INT:case e.INT:case e.FLOAT:return 4}return 0}function uniformTypeSize(e,t){switch(t){case e.BOOL_VEC4:case e.INT_VEC4:case e.FLOAT_VEC4:return 4;case e.BOOL_VEC3:case e.INT_VEC3:case e.FLOAT_VEC3:return 3;case e.BOOL_VEC2:case e.INT_VEC2:case e.FLOAT_VEC2:return 2;case e.BOOL:case e.INT:case e.FLOAT:case e.SAMPLER_2D:case e.SAMPLER_CUBE:return 1;default:return 0}}const listToArray=e=>{let t=[];for(let n of e.values())t.push(n);return t};function arrayToUint8Array(e){if(isTypedArray$1(e))return new Uint8Array(e.buffer).subarray(e.byteOffset,e.byteLength+e.byteOffset);if(Array.isArray(e)||e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof e.values==`function`)return new Uint8Array(listToArray(e));throw Error(`Can't unpack typed array!`)}function Uint8ArrayToVariant(e){return new ht.Variant(`ay`,e)}const extractImageData=e=>{let t=e.width,n=e.height;if(typeof e==`object`&&t!==void 0&&n!==void 0){if(e.data!==void 0)return e;let r=null;if(typeof e.getContext==`function`)r=e.getContext(`2d`);else if(typeof e.isPixbuf==`function`&&e.isPixbuf())return e.getImageData();else if(e.src!==void 0&&typeof document==`object`&&typeof document.createElement==`function`){let i=document.createElement(`canvas`);typeof i==`object`&&typeof i.getContext==`function`&&(i.width=t,i.height=n,r=i.getContext(`2d`),r!==null&&r.drawImage(e,0,0))}if(r!==null)return r.getImageData(0,0,t,n)}return null};function formatSize(e,t){switch(t){case e.ALPHA:case e.LUMINANCE:return 1;case e.LUMINANCE_ALPHA:return 2;case e.RGB:return 3;case e.RGBA:return 4}return 0}function convertPixels(e){if(typeof e==`object`&&e){if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Uint8ClampedArray||e instanceof Float32Array)return arrayToUint8Array(e);if(e instanceof Buffer)return new Uint8Array(e)}return null}function checkFormat(e,t){return t===e.ALPHA||t===e.LUMINANCE_ALPHA||t===e.LUMINANCE||t===e.RGB||t===e.RGBA}function validCubeTarget(e,t){return t===e.TEXTURE_CUBE_MAP_POSITIVE_X||t===e.TEXTURE_CUBE_MAP_NEGATIVE_X||t===e.TEXTURE_CUBE_MAP_POSITIVE_Y||t===e.TEXTURE_CUBE_MAP_NEGATIVE_Y||t===e.TEXTURE_CUBE_MAP_POSITIVE_Z||t===e.TEXTURE_CUBE_MAP_NEGATIVE_Z}function flag(e,t,n){return!e||typeof e!=`object`||!(t in e)?n:!!e[t]}function premultiplyAlpha(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=4){let r=e[n+3]/255;t[n]=Math.round(e[n]*r),t[n+1]=Math.round(e[n+1]*r),t[n+2]=Math.round(e[n+2]*r),t[n+3]=e[n+3]}return t}const jn={bindBuffer(e=0,t){if(!checkObject(t))throw TypeError(`bindBuffer(GLenum, WebGLBuffer)`);if(e!==this.ARRAY_BUFFER&&e!==this.ELEMENT_ARRAY_BUFFER){this.setError(this.INVALID_ENUM);return}if(!t)t=null,this._gl.bindBuffer(e,0);else if(t._pendingDelete)return;else if(this._checkWrapper(t,WebGLBuffer)){if(t._binding&&t._binding!==e){this.setError(this.INVALID_OPERATION);return}t._binding=e|0,this._gl.bindBuffer(e,t._|0)}else return;e===this.ARRAY_BUFFER?this._vertexGlobalState.setArrayBuffer(t):this._vertexObjectState.setElementArrayBuffer(t)},bufferData(e=0,t,n=0){let r=0,i=null;if(typeof t==`number`?r=t:typeof t==`object`&&(i=t),n!==this.STREAM_DRAW&&n!==this.STATIC_DRAW&&n!==this.DYNAMIC_DRAW){this.setError(this.INVALID_ENUM);return}if(e!==this.ARRAY_BUFFER&&e!==this.ELEMENT_ARRAY_BUFFER){this.setError(this.INVALID_ENUM);return}let a=this._getActiveBuffer(e);if(!a){this.setError(this.INVALID_OPERATION);return}if(i){let t=null;if(isTypedArray$1(i)||i instanceof DataView||i instanceof ArrayBuffer)t=arrayToUint8Array(i);else{this.setError(this.INVALID_VALUE);return}this._saveError(),this._gl.bufferData(e,Uint8ArrayToVariant(t),n);let r=this.getError();if(this._restoreError(r),r!==this.NO_ERROR)return;a._size=t.length,e===this.ELEMENT_ARRAY_BUFFER&&(a._elements=new Uint8Array(t))}else if(typeof t==`number`){if(r<0){this.setError(this.INVALID_VALUE);return}this._saveError(),this._gl.bufferDataSizeOnly(e,r,n);let t=this.getError();if(this._restoreError(t),t!==this.NO_ERROR)return;a._size=r,e===this.ELEMENT_ARRAY_BUFFER&&(a._elements=new Uint8Array(r))}else this.setError(this.INVALID_VALUE)},bufferSubData(e=0,t=0,n){if(e!==this.ARRAY_BUFFER&&e!==this.ELEMENT_ARRAY_BUFFER){this.setError(this.INVALID_ENUM);return}if(typeof n!=`object`||!n)throw TypeError(`bufferSubData: data must be a BufferSource`);let r=this._getActiveBuffer(e);if(!r){this.setError(this.INVALID_OPERATION);return}if(t<0||t>=r._size){this.setError(this.INVALID_VALUE);return}let i=null;if(isTypedArray$1(n)||n instanceof DataView||n instanceof ArrayBuffer)i=arrayToUint8Array(n);else{this.setError(this.INVALID_VALUE);return}if(t+i.length>r._size){this.setError(this.INVALID_VALUE);return}e===this.ELEMENT_ARRAY_BUFFER&&r._elements.set(i,t),this._gl.bufferSubData(e,t,Uint8ArrayToVariant(i))},createBuffer(){let e=this._gl.createBuffer();if(!e||e<=0)return null;let t=new WebGLBuffer(e,this);return this._buffers[e]=t,t},deleteBuffer(e){if(!checkObject(e)||e!==null&&!(e instanceof WebGLBuffer))throw TypeError(`deleteBuffer(WebGLBuffer)`);if(!(e instanceof WebGLBuffer&&this._checkOwns(e))){this.setError(this.INVALID_OPERATION);return}this._vertexGlobalState._arrayBufferBinding===e&&this.bindBuffer(this.ARRAY_BUFFER,null),this._vertexObjectState._elementArrayBufferBinding===e&&this.bindBuffer(this.ELEMENT_ARRAY_BUFFER,null),this._vertexObjectState===this._defaultVertexObjectState&&this._vertexObjectState.releaseArrayBuffer(e),e._pendingDelete=!0,e._checkDelete()},getBufferParameter(e=0,t=0){if(e!==this.ARRAY_BUFFER&&e!==this.ELEMENT_ARRAY_BUFFER)return this.setError(this.INVALID_ENUM),null;switch(t){case this.BUFFER_SIZE:case this.BUFFER_USAGE:return this._gl.getBufferParameteriv(e|0,t|0)[0];default:return this.setError(this.INVALID_ENUM),null}},_getActiveBuffer(e){return e===this.ARRAY_BUFFER?this._vertexGlobalState._arrayBufferBinding:e===this.ELEMENT_ARRAY_BUFFER?this._vertexObjectState._elementArrayBufferBinding:null}};function installBufferBindingMethods(e){Object.assign(e,jn)}const Mn={drawArrays(e=0,t=0,n=0){if(t<0||n<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let r=vertexCount(this,e,n);if(r<0){this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk()||n===0)return;let i=t;n>0&&(i=n+t-1>>>0),this._checkVertexAttribState(i)&&this._gl.drawArrays(e,t,r)},drawElements(e=0,t=0,n=0,r=0){if(t<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let i=this._vertexObjectState._elementArrayBufferBinding;if(!i){this.setError(this.INVALID_OPERATION);return}let a=null,o=r;if(n===this.UNSIGNED_SHORT){if(o%2){this.setError(this.INVALID_OPERATION);return}o>>=1,a=new Uint16Array(i._elements.buffer)}else if(this._extensions.oes_element_index_uint&&n===this.UNSIGNED_INT){if(o%4){this.setError(this.INVALID_OPERATION);return}o>>=2,a=new Uint32Array(i._elements.buffer)}else if(n===this.UNSIGNED_BYTE)a=i._elements;else{this.setError(this.INVALID_ENUM);return}let s=t;switch(e){case this.TRIANGLES:t%3&&(s-=t%3);break;case this.LINES:t%2&&(s-=t%2);break;case this.POINTS:break;case this.LINE_LOOP:case this.LINE_STRIP:if(t<2){this.setError(this.INVALID_OPERATION);return}break;case this.TRIANGLE_FAN:case this.TRIANGLE_STRIP:if(t<3){this.setError(this.INVALID_OPERATION);return}break;default:this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk())return;if(t===0){this._checkVertexAttribState(0);return}if(t+o>>>0>a.length){this.setError(this.INVALID_OPERATION);return}let c=-1;for(let e=o;e<o+t;++e)c=Math.max(c,a[e]);if(c<0){this._checkVertexAttribState(0);return}this._checkVertexAttribState(c)&&s>0&&this._gl.drawElements(e,s,n,r)},viewport(e,t,n,r){this._viewport[0]=e|0,this._viewport[1]=t|0,this._viewport[2]=n|0,this._viewport[3]=r|0,this._gl.viewport(e,t,n,r)},scissor(e,t,n,r){this._scissorBox[0]=e|0,this._scissorBox[1]=t|0,this._scissorBox[2]=n|0,this._scissorBox[3]=r|0,this._gl.scissor(e|0,t|0,n|0,r|0)},readPixels(e=0,t=0,n=0,r=0,i=0,a=0,o){if(!o)return;if(!(this._extensions.oes_texture_float&&a===this.FLOAT&&i===this.RGBA)){if(i===this.RGB||i===this.ALPHA||a!==this.UNSIGNED_BYTE){this.setError(this.INVALID_OPERATION);return}else if(i!==this.RGBA){this.setError(this.INVALID_ENUM);return}else if(n<0||r<0||!(o instanceof Uint8Array)){this.setError(this.INVALID_VALUE);return}}if(!this._framebufferOk()){console.error(`framebuffer is not okay!`);return}let s=n*4;s%this._packAlignment!==0&&(s+=this._packAlignment-s%this._packAlignment);let c=s*(r-1)+n*4;if(c<=0)return;if((o.length||o.byteLength||0)<c){this.setError(this.INVALID_VALUE);return}let l=this.drawingBufferWidth,u=this.drawingBufferHeight;this._activeFramebuffer&&(l=this._activeFramebuffer._width,u=this._activeFramebuffer._height);let d=arrayToUint8Array(o);if(e>=l||e+n<=0||t>=u||t+r<=0)for(let e=0;e<d.length;++e)d[e]=0;else if(e<0||e+n>l||t<0||t+r>u){for(let e=0;e<d.length;++e)d[e]=0;let o=e,c=n;e<0&&(c+=e,o=0),o+n>l&&(c=l-o);let f=t,p=r;t<0&&(p+=t,f=0),f+r>u&&(p=u-f);let m=c*4;if(m%this._packAlignment!==0&&(m+=this._packAlignment-m%this._packAlignment),c>0&&p>0){let n=new Uint8Array(m*p),r=this._gl.readPixels(o,f,c,p,i,a,Uint8ArrayToVariant(n)),l=r&&r.length>0?r:n,u=4*(o-e)+(f-t)*s;for(let e=0;e<p;++e)for(let t=0;t<c;++t)for(let n=0;n<4;++n)d[u+e*s+4*t+n]=l[e*m+4*t+n]}}else{let o=this._gl.readPixels(e,t,n,r,i,a,Uint8ArrayToVariant(d));o&&o.length>0&&d.set(o)}},enableVertexAttribArray(e){if(e<0||e>=this._vertexObjectState._attribs.length){this.setError(this.INVALID_VALUE);return}this._gl.enableVertexAttribArray(e),this._vertexObjectState._attribs[e]._isPointer=!0},disableVertexAttribArray(e=0){if(e<0||e>=this._vertexObjectState._attribs.length){this.setError(this.INVALID_VALUE);return}this._gl.disableVertexAttribArray(e),this._vertexObjectState._attribs[e]._isPointer=!1},vertexAttrib1f(e,t){if(e|=0,!this._checkVertexIndex(e))return;let n=this._vertexGlobalState._attribs[e]._data;n[3]=1,n[1]=n[2]=0,n[0]=t,this._gl.vertexAttrib1f(e|0,+t)},vertexAttrib1fv(e,t){if(e|=0,!this._checkVertexIndex(e))return;if(typeof t!=`object`||!t||t.length<1){this.setError(this.INVALID_OPERATION);return}let n=this._vertexGlobalState._attribs[e]._data;n[3]=1,n[2]=0,n[1]=0,n[0]=t[0],this._gl.vertexAttrib1f(e|0,+t[0])},vertexAttrib2f(e,t,n){if(e|=0,!this._checkVertexIndex(e))return;let r=this._vertexGlobalState._attribs[e]._data;r[3]=1,r[2]=0,r[1]=n,r[0]=t,this._gl.vertexAttrib2f(e|0,+t,+n)},vertexAttrib2fv(e,t){if(e|=0,!this._checkVertexIndex(e))return;if(typeof t!=`object`||!t||t.length<2){this.setError(this.INVALID_OPERATION);return}let n=this._vertexGlobalState._attribs[e]._data;n[3]=1,n[2]=0,n[1]=t[1],n[0]=t[0],this._gl.vertexAttrib2f(e|0,+t[0],+t[1])},vertexAttrib3f(e,t,n,r){if(e|=0,!this._checkVertexIndex(e))return;let i=this._vertexGlobalState._attribs[e]._data;i[3]=1,i[2]=r,i[1]=n,i[0]=t,this._gl.vertexAttrib3f(e|0,+t,+n,+r)},vertexAttrib3fv(e,t){if(e|=0,!this._checkVertexIndex(e))return;if(typeof t!=`object`||!t||t.length<3){this.setError(this.INVALID_OPERATION);return}let n=this._vertexGlobalState._attribs[e]._data;n[3]=1,n[2]=t[2],n[1]=t[1],n[0]=t[0],this._gl.vertexAttrib3f(e|0,+t[0],+t[1],+t[2])},vertexAttrib4f(e=0,t,n,r,i){if(!this._checkVertexIndex(e))return;let a=this._vertexGlobalState._attribs[e]._data;a[3]=i,a[2]=r,a[1]=n,a[0]=t,this._gl.vertexAttrib4f(e|0,+t,+n,+r,+i)},vertexAttrib4fv(e,t){if(e|=0,!this._checkVertexIndex(e))return;if(typeof t!=`object`||!t||t.length<4){this.setError(this.INVALID_OPERATION);return}let n=this._vertexGlobalState._attribs[e]._data;n[3]=t[3],n[2]=t[2],n[1]=t[1],n[0]=t[0],this._gl.vertexAttrib4f(e|0,+t[0],+t[1],+t[2],+t[3])},vertexAttribPointer(e=0,t=0,n=0,r=!1,i=0,a=0){if(i<0||a<0){this.setError(this.INVALID_VALUE);return}if(i<0||a<0||e<0||e>=this._vertexObjectState._attribs.length||!(t===1||t===2||t===3||t===4)){this.setError(this.INVALID_VALUE);return}if(this._vertexGlobalState._arrayBufferBinding===null){this.setError(this.INVALID_OPERATION);return}let o=typeSize(this,n);if(o===0||n===this.INT||n===this.UNSIGNED_INT){this.setError(this.INVALID_ENUM);return}if(i>255||i<0){this.setError(this.INVALID_VALUE);return}if(i%o!==0||a%o!==0){this.setError(this.INVALID_OPERATION);return}this._gl.vertexAttribPointer(e,t,n,r,i,a),this._vertexObjectState.setVertexAttribPointer(this._vertexGlobalState._arrayBufferBinding,e,t*o,a,i||t*o,n,r,i,t)},getVertexAttrib(e=0,t=0){if(e<0||e>=this._vertexObjectState._attribs.length)return this.setError(this.INVALID_VALUE),null;let n=this._vertexObjectState._attribs[e],r=this._vertexGlobalState._attribs[e]._data,i=this._extensions.angle_instanced_arrays;if(i&&t===i.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE)return n._divisor;switch(t){case this.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:return n._pointerBuffer;case this.VERTEX_ATTRIB_ARRAY_ENABLED:return n._isPointer;case this.VERTEX_ATTRIB_ARRAY_SIZE:return n._inputSize;case this.VERTEX_ATTRIB_ARRAY_STRIDE:return n._inputStride;case this.VERTEX_ATTRIB_ARRAY_TYPE:return n._pointerType;case this.VERTEX_ATTRIB_ARRAY_NORMALIZED:return n._pointerNormal;case this.CURRENT_VERTEX_ATTRIB:return new Float32Array(r);default:return this.setError(this.INVALID_ENUM),null}},getVertexAttribOffset(e=0,t=0){return e<0||e>=this._vertexObjectState._attribs.length?(this.setError(this.INVALID_VALUE),-1):t===this.VERTEX_ATTRIB_ARRAY_POINTER?this._vertexObjectState._attribs[e]._pointerOffset:(this.setError(this.INVALID_ENUM),-1)},_checkVertexAttribState(e){let t=this._activeProgram;if(!t)return this.setError(this.INVALID_OPERATION),!1;let n=this._vertexObjectState._attribs;for(let r=0;r<n.length;++r){let i=n[r];if(i._isPointer){let n=i._pointerBuffer;if(!n)return this.setError(this.INVALID_OPERATION),!1;if(t._attributes.indexOf(r)>=0){let t=0;if(t=i._divisor?i._pointerSize+i._pointerOffset:i._pointerStride*e+i._pointerSize+i._pointerOffset,t>n._size)return this.setError(this.INVALID_OPERATION),!1}}}return!0},_checkVertexIndex(e){return e<0||e>=this._vertexObjectState._attribs.length?(this.setError(this.INVALID_VALUE),!1):!0}};function installDrawingMethods(e){Object.assign(e,Mn)}const Nn={bindFramebuffer(e,t){if(!checkObject(t))throw TypeError(`bindFramebuffer(GLenum, WebGLFramebuffer)`);if(e!==this.FRAMEBUFFER){this.setError(this.INVALID_ENUM);return}if(!t)this._gl.bindFramebuffer(this.FRAMEBUFFER,this._gtkFboId);else if(t._pendingDelete)return;else if(this._checkWrapper(t,WebGLFramebuffer))this._gl.bindFramebuffer(this.FRAMEBUFFER,t._|0);else return;let n=this._activeFramebuffer;n!==t&&(n&&(--n._refCount,n._checkDelete()),t&&(t._refCount+=1)),this._activeFramebuffer=t,t&&this._updateFramebufferAttachments(t)},bindRenderbuffer(e,t){if(!checkObject(t))throw TypeError(`bindRenderbuffer(GLenum, WebGLRenderbuffer)`);if(e!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}if(!t)this._gl.bindRenderbuffer(e|0,0);else if(t._pendingDelete)return;else if(this._checkWrapper(t,WebGLRenderbuffer))this._gl.bindRenderbuffer(e|0,t._|0);else return;let n=this._activeRenderbuffer;n!==t&&(n&&(--n._refCount,n._checkDelete()),t&&(t._refCount+=1)),this._activeRenderbuffer=t},framebufferRenderbuffer(e,t,n,r){if(!checkObject(r))throw TypeError(`framebufferRenderbuffer(GLenum, GLenum, GLenum, WebGLRenderbuffer)`);if(e!==this.FRAMEBUFFER||!this._validFramebufferAttachment(t)||n!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}let i=this._activeFramebuffer;if(!i){this.setError(this.INVALID_OPERATION);return}r&&!this._checkWrapper(r,WebGLRenderbuffer)||(i._setAttachment(r,t),this._updateFramebufferAttachments(i))},framebufferTexture2D(e,t,n,r,i=0){if(e|=0,t|=0,n|=0,i|=0,!checkObject(r))throw TypeError(`framebufferTexture2D(GLenum, GLenum, GLenum, WebGLTexture, GLint)`);if(e!==this.FRAMEBUFFER||!this._validFramebufferAttachment(t)){this.setError(this.INVALID_ENUM);return}if(i!==0){this.setError(this.INVALID_VALUE);return}if(r&&!this._checkWrapper(r,WebGLTexture))return;if(n===this.TEXTURE_2D){if(r&&r._binding!==this.TEXTURE_2D){this.setError(this.INVALID_OPERATION);return}}else if(this._validCubeTarget(n)){if(r&&r._binding!==this.TEXTURE_CUBE_MAP){this.setError(this.INVALID_OPERATION);return}}else{this.setError(this.INVALID_ENUM);return}let a=this._activeFramebuffer;if(!a){this.setError(this.INVALID_OPERATION);return}a._attachmentLevel[t]=i,a._attachmentFace[t]=n,a._setAttachment(r,t),this._updateFramebufferAttachments(a)},createFramebuffer(){let e=this._gl.createFramebuffer();if(e<=0)return null;let t=new WebGLFramebuffer(e,this);return this._framebuffers[e]=t,t},deleteFramebuffer(e){if(!checkObject(e))throw TypeError(`deleteFramebuffer(WebGLFramebuffer)`);if(!(e instanceof WebGLFramebuffer&&this._checkOwns(e))){this.setError(this.INVALID_OPERATION);return}this._activeFramebuffer===e&&this.bindFramebuffer(this.FRAMEBUFFER,null),e._pendingDelete=!0,e._checkDelete()},createRenderbuffer(){let e=this._gl.createRenderbuffer();if(e<=0)return null;let t=new WebGLRenderbuffer(e,this);return this._renderbuffers[e]=t,t},deleteRenderbuffer(e){if(!checkObject(e))throw TypeError(`deleteRenderbuffer(WebGLRenderbuffer)`);if(!(e instanceof WebGLRenderbuffer&&this._checkOwns(e))){this.setError(this.INVALID_OPERATION);return}this._activeRenderbuffer===e&&this.bindRenderbuffer(this.RENDERBUFFER,null),this._detachRenderbufferFromAllFramebuffers(e),e._pendingDelete=!0,e._checkDelete()},renderbufferStorage(e=0,t=0,n=0,r=0){if(e!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}let i=this._activeRenderbuffer;if(!i){this.setError(this.INVALID_OPERATION);return}if(t!==this.RGBA4&&t!==this.RGB565&&t!==this.RGB5_A1&&t!==this.DEPTH_COMPONENT16&&t!==this.STENCIL_INDEX&&t!==this.STENCIL_INDEX8&&t!==this.DEPTH_STENCIL){this.setError(this.INVALID_ENUM);return}this._saveError(),this._gl.renderbufferStorage(e,t,n,r);let a=this.getError();if(this._restoreError(a),a!==this.NO_ERROR)return;i._width=n,i._height=r,i._format=t;let o=this._activeFramebuffer;if(o){let e=!1,t=this._getAttachments();for(let n=0;n<t.length;++n)if(o._attachments[t[n]]===i){e=!0;break}e&&this._updateFramebufferAttachments(this._activeFramebuffer)}},getFramebufferAttachmentParameter(e=0,t=0,n=0){if(e!==this.FRAMEBUFFER||!this._validFramebufferAttachment(t))return this.setError(this.INVALID_ENUM),null;let r=this._activeFramebuffer;if(!r)return this.setError(this.INVALID_OPERATION),null;let i=r._attachments[t];if(i===null){if(n===this.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)return this.NONE}else if(i instanceof WebGLTexture)switch(n){case this.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:return i;case this.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:return this.TEXTURE;case this.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:return r._attachmentLevel[t];case this.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:{let e=r._attachmentFace[t];return e===this.TEXTURE_2D?0:e}}else if(i instanceof WebGLRenderbuffer)switch(n){case this.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:return i;case this.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:return this.RENDERBUFFER}return this.setError(this.INVALID_ENUM),null},getRenderbufferParameter(e=0,t=0){if(e!==this.RENDERBUFFER)return this.setError(this.INVALID_ENUM),null;let n=this._activeRenderbuffer;if(!n)return this.setError(this.INVALID_OPERATION),null;switch(t){case this.RENDERBUFFER_INTERNAL_FORMAT:return n._format;case this.RENDERBUFFER_WIDTH:return n._width;case this.RENDERBUFFER_HEIGHT:return n._height;case this.MAX_RENDERBUFFER_SIZE:return this._maxRenderbufferSize;case this.RENDERBUFFER_RED_SIZE:case this.RENDERBUFFER_GREEN_SIZE:case this.RENDERBUFFER_BLUE_SIZE:case this.RENDERBUFFER_ALPHA_SIZE:case this.RENDERBUFFER_DEPTH_SIZE:case this.RENDERBUFFER_STENCIL_SIZE:return this._gl.getRenderbufferParameter(e,t)}return this.setError(this.INVALID_ENUM),null},checkFramebufferStatus(e){if(e!==this.FRAMEBUFFER)return this.setError(this.INVALID_ENUM),0;let t=this._activeFramebuffer;return t?this._preCheckFramebufferStatus(t):this.FRAMEBUFFER_COMPLETE},_preCheckFramebufferStatus(e){let t=e._attachments,n=[],r=[],i=t[this.DEPTH_ATTACHMENT],a=t[this.DEPTH_STENCIL_ATTACHMENT],o=t[this.STENCIL_ATTACHMENT];if(a&&(o||i)||o&&i)return this.FRAMEBUFFER_UNSUPPORTED;let s=this._getColorAttachments(),c=0;for(let e in t)t[e]&&s.indexOf(Number(e))!==-1&&c++;if(c===0)return this.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;if(a instanceof WebGLTexture)return this.FRAMEBUFFER_UNSUPPORTED;if(a instanceof WebGLRenderbuffer){if(a._format!==this.DEPTH_STENCIL)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;n.push(a._width),r.push(a._height)}if(i instanceof WebGLTexture)return this.FRAMEBUFFER_UNSUPPORTED;if(i instanceof WebGLRenderbuffer){if(i._format!==this.DEPTH_COMPONENT16)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;n.push(i._width),r.push(i._height)}if(o instanceof WebGLTexture)return this.FRAMEBUFFER_UNSUPPORTED;if(o instanceof WebGLRenderbuffer){if(o._format!==this.STENCIL_INDEX8)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;n.push(o._width),r.push(o._height)}let l=!1;for(let i=0;i<s.length;++i){let a=t[s[i]];if(a instanceof WebGLTexture){if(a._format!==this.RGBA||!(a._type===this.UNSIGNED_BYTE||a._type===this.FLOAT))return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;l=!0;let t=e._attachmentLevel[this.COLOR_ATTACHMENT0];if(t===null)throw TypeError(`level is null!`);n.push(a._levelWidth[t]),r.push(a._levelHeight[t])}else if(a instanceof WebGLRenderbuffer){let e=a._format;if(e!==this.RGBA4&&e!==this.RGB565&&e!==this.RGB5_A1)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;l=!0,n.push(a._width),r.push(a._height)}}if(!l&&!o&&!i&&!a)return this.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;if(n.length<=0||r.length<=0)return this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;for(let e=1;e<n.length;++e)if(n[e-1]!==n[e]||r[e-1]!==r[e])return this.FRAMEBUFFER_INCOMPLETE_DIMENSIONS;return n[0]===0||r[0]===0?this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:(e._width=n[0],e._height=r[0],this.FRAMEBUFFER_COMPLETE)},_framebufferOk(){let e=this._activeFramebuffer;return e&&this._preCheckFramebufferStatus(e)!==this.FRAMEBUFFER_COMPLETE?(this.setError(this.INVALID_FRAMEBUFFER_OPERATION),!1):!0},_validFramebufferAttachment(e){switch(e){case this.DEPTH_ATTACHMENT:case this.STENCIL_ATTACHMENT:case this.DEPTH_STENCIL_ATTACHMENT:case this.COLOR_ATTACHMENT0:return!0}if(this._extensions.webgl_draw_buffers){let t=this._extensions.webgl_draw_buffers;return e<t.COLOR_ATTACHMENT0_WEBGL+t._maxDrawBuffers}return!1},_updateFramebufferAttachments(e){if(!e)return;let t=e._status,n=this._getAttachments();if(e._status=this._preCheckFramebufferStatus(e),e._status!==this.FRAMEBUFFER_COMPLETE){if(t===this.FRAMEBUFFER_COMPLETE)for(let t=0;t<n.length;++t){let r=n[t];this._gl.framebufferTexture2D(this.FRAMEBUFFER,r,e._attachmentFace[r]||0,0,e._attachmentLevel[r]||0)}return}for(let t=0;t<n.length;++t){let r=n[t];this._gl.framebufferTexture2D(this.FRAMEBUFFER,r,e._attachmentFace[r]||0,0,e._attachmentLevel[r]||0)}for(let t=0;t<n.length;++t){let r=n[t],i=e._attachments[r];i instanceof WebGLTexture?this._gl.framebufferTexture2D(this.FRAMEBUFFER,r,e._attachmentFace[r]||0,i._|0,e._attachmentLevel[r]||0):i instanceof WebGLRenderbuffer&&this._gl.framebufferRenderbuffer(this.FRAMEBUFFER,r,this.RENDERBUFFER,i._|0)}},_tryDetachFramebuffer(e,t){if(e&&e._linked(t)){let n=this._getAttachments();for(let r=0;r<n.length;++r)e._attachments[n[r]]===t&&this.framebufferTexture2D(this.FRAMEBUFFER,n[r]|0,this.TEXTURE_2D,null)}},_detachRenderbufferFromAllFramebuffers(e){let t=this._activeFramebuffer,n=this._getAttachments(),r=!1;for(let i in this._framebuffers){let a=this._framebuffers[i];if(!(!a||!a._linked(e))){a!==t&&(this._gl.bindFramebuffer(this.FRAMEBUFFER,a._|0),r=!0);for(let t=0;t<n.length;++t){let r=n[t];a._attachments[r]===e&&(this._gl.framebufferRenderbuffer(this.FRAMEBUFFER,r,this.RENDERBUFFER,0),a._setAttachment(null,r))}}}r&&this._gl.bindFramebuffer(this.FRAMEBUFFER,t?t._|0:this._gtkFboId)},_getAttachments(){return this._extensions.webgl_draw_buffers?this._extensions.webgl_draw_buffers._ALL_ATTACHMENTS:this.DEFAULT_ATTACHMENTS},_getColorAttachments(){return this._extensions.webgl_draw_buffers?this._extensions.webgl_draw_buffers._ALL_COLOR_ATTACHMENTS:this.DEFAULT_COLOR_ATTACHMENTS},_resizeDrawingBuffer(e,t){let n=this._activeFramebuffer,r=this._getActiveTexture(this.TEXTURE_2D),i=this._activeRenderbuffer,a=this._contextAttributes,o=this._drawingBuffer;o?._framebuffer&&this._gl.bindFramebuffer(this.FRAMEBUFFER,o?._framebuffer);let s=this._getAttachments();for(let e=0;e<s.length;++e)this._gl.framebufferTexture2D(this.FRAMEBUFFER,s[e],this.TEXTURE_2D,0,0);o?._color&&this._gl.bindTexture(this.TEXTURE_2D,o?._color);let c=a.alpha?this.RGBA:this.RGB;this._gl.texImage2D(this.TEXTURE_2D,0,c,e,t,0,c,this.UNSIGNED_BYTE,Uint8ArrayToVariant(null)),this._gl.texParameteri(this.TEXTURE_2D,this.TEXTURE_MIN_FILTER,this.NEAREST),this._gl.texParameteri(this.TEXTURE_2D,this.TEXTURE_MAG_FILTER,this.NEAREST),o?._color&&this._gl.framebufferTexture2D(this.FRAMEBUFFER,this.COLOR_ATTACHMENT0,this.TEXTURE_2D,o?._color,0);let l=0,u=0;a.depth&&a.stencil?(l=this.DEPTH_STENCIL,u=this.DEPTH_STENCIL_ATTACHMENT):a.depth?(l=33191,u=this.DEPTH_ATTACHMENT):a.stencil&&(l=this.STENCIL_INDEX8,u=this.STENCIL_ATTACHMENT),l&&(o?._depthStencil&&this._gl.bindRenderbuffer(this.RENDERBUFFER,o?._depthStencil),this._gl.renderbufferStorage(this.RENDERBUFFER,l,e,t),o?._depthStencil&&this._gl.framebufferRenderbuffer(this.FRAMEBUFFER,u,this.RENDERBUFFER,o?._depthStencil)),this.bindFramebuffer(this.FRAMEBUFFER,n),this.bindTexture(this.TEXTURE_2D,r),this.bindRenderbuffer(this.RENDERBUFFER,i)},_allocateDrawingBuffer(e,t){this._drawingBuffer=new WebGLDrawingBufferWrapper(this._gl.createFramebuffer(),this._gl.createTexture(),this._gl.createRenderbuffer()),this._resizeDrawingBuffer(e,t)},resize(e=0,t=0){if(e|=0,t|=0,e>0&&t>0)(e!==this.drawingBufferWidth||t!==this.drawingBufferHeight)&&this._resizeDrawingBuffer(e,t);else throw Error(`Invalid surface dimensions`)}};function installFramebufferMethods(e){Object.assign(e,Nn)}const Pn={enable(e=0){this._gl.enable(e)},disable(e=0){if(this._gl.disable(e),e===this.TEXTURE_2D||e===this.TEXTURE_CUBE_MAP){let t=this._getActiveTextureUnit();t._mode===e&&(t._mode=0)}},cullFace(e){this._gl.cullFace(e|0)},depthFunc(e){switch(e|=0,e){case this.NEVER:case this.LESS:case this.EQUAL:case this.LEQUAL:case this.GREATER:case this.NOTEQUAL:case this.GEQUAL:case this.ALWAYS:this._gl.depthFunc(e);return;default:this.setError(this.INVALID_ENUM)}},depthMask(e){this._gl.depthMask(!!e)},depthRange(e,t){if(e=+e,t=+t,e<=t){this._gl.depthRange(e,t);return}this.setError(this.INVALID_OPERATION)},frontFace(e=0){this._gl.frontFace(e)},lineWidth(e){if(isNaN(e)){this.setError(this.INVALID_VALUE);return}this._gl.lineWidth(+e)},polygonOffset(e,t){this._gl.polygonOffset(+e,+t)},sampleCoverage(e,t){this._gl.sampleCoverage(+e,!!t)},hint(e=0,t=0){let n=this._extensions.oes_standard_derivatives;if(!(e===this.GENERATE_MIPMAP_HINT||n&&e===n.FRAGMENT_SHADER_DERIVATIVE_HINT_OES)){this.setError(this.INVALID_ENUM);return}if(t!==this.FASTEST&&t!==this.NICEST&&t!==this.DONT_CARE){this.setError(this.INVALID_ENUM);return}this._gl.hint(e,t)},finish(){this._gl.finish()},flush(){this._gl.flush()},blendColor(e=0,t=0,n=0,r=0){this._gl.blendColor(+e,+t,+n,+r)},blendEquation(e=0){if(this._validBlendMode(e)){this._gl.blendEquation(e);return}this.setError(this.INVALID_ENUM)},blendEquationSeparate(e=0,t=0){if(this._validBlendMode(e)&&this._validBlendMode(t)){this._gl.blendEquationSeparate(e,t);return}this.setError(this.INVALID_ENUM)},blendFunc(e=0,t=0){if(!this._validBlendFunc(e)||!this._validBlendFunc(t)){this.setError(this.INVALID_ENUM);return}if(this._isConstantBlendFunc(e)&&this._isConstantBlendFunc(t)){this.setError(this.INVALID_OPERATION);return}this._gl.blendFunc(e,t)},blendFuncSeparate(e=0,t=0,n=0,r=0){if(!(this._validBlendFunc(e)&&this._validBlendFunc(t)&&this._validBlendFunc(n)&&this._validBlendFunc(r))){this.setError(this.INVALID_ENUM);return}if(this._isConstantBlendFunc(e)&&this._isConstantBlendFunc(t)||this._isConstantBlendFunc(n)&&this._isConstantBlendFunc(r)){this.setError(this.INVALID_OPERATION);return}this._gl.blendFuncSeparate(e,t,n,r)},clear(e=0){this._framebufferOk()&&this._gl.clear(e)},clearColor(e,t,n,r){this._gl.clearColor(+e,+t,+n,+r)},clearDepth(e){this._gl.clearDepth(+e)},clearStencil(e=0){this._checkStencil=!1,this._gl.clearStencil(e)},colorMask(e,t,n,r){this._gl.colorMask(!!e,!!t,!!n,!!r)},stencilFunc(e,t,n){this._checkStencil=!0,this._gl.stencilFunc(e|0,t|0,n|0)},stencilFuncSeparate(e,t,n,r){this._checkStencil=!0,this._gl.stencilFuncSeparate(e|0,t|0,n|0,r|0)},stencilMask(e){this._checkStencil=!0,this._gl.stencilMask(e>>>0)},stencilMaskSeparate(e,t){this._checkStencil=!0,this._gl.stencilMaskSeparate(e|0,t>>>0)},stencilOp(e,t,n){this._checkStencil=!0,this._gl.stencilOp(e|0,t|0,n|0)},stencilOpSeparate(e,t,n,r){this._checkStencil=!0,this._gl.stencilOpSeparate(e|0,t|0,n|0,r|0)},isEnabled(e=0){return this._gl.isEnabled(e)},isContextLost(){return!1},getError(){return this._gl.getError()},setError(e){this._gl.setError(e)},isBuffer(e){return this._isObject(e,`isBuffer`,WebGLBuffer)?this._gl.isBuffer(e?._):!1},isFramebuffer(e){return this._isObject(e,`isFramebuffer`,WebGLFramebuffer)?this._gl.isFramebuffer(e?._):!1},isProgram(e){return this._isObject(e,`isProgram`,WebGLProgram$1)?this._gl.isProgram(e?._):!1},isRenderbuffer(e){return this._isObject(e,`isRenderbuffer`,WebGLRenderbuffer)?this._gl.isRenderbuffer(e?._):!1},isShader(e){return this._isObject(e,`isShader`,WebGLShader$1)?this._gl.isShader(e?._):!1},isTexture(e){return this._isObject(e,`isTexture`,WebGLTexture)?this._gl.isTexture(e?._):!1},generateMipmap(e=0){this._gl.generateMipmap(e)},_validBlendFunc(e){return e===this.ZERO||e===this.ONE||e===this.SRC_COLOR||e===this.ONE_MINUS_SRC_COLOR||e===this.DST_COLOR||e===this.ONE_MINUS_DST_COLOR||e===this.SRC_ALPHA||e===this.ONE_MINUS_SRC_ALPHA||e===this.DST_ALPHA||e===this.ONE_MINUS_DST_ALPHA||e===this.SRC_ALPHA_SATURATE||e===this.CONSTANT_COLOR||e===this.ONE_MINUS_CONSTANT_COLOR||e===this.CONSTANT_ALPHA||e===this.ONE_MINUS_CONSTANT_ALPHA},_validBlendMode(e){let t=this._extensions.ext_blend_minmax;return e===this.FUNC_ADD||e===this.FUNC_SUBTRACT||e===this.FUNC_REVERSE_SUBTRACT||!!(t&&(e===t.MIN_EXT||e===t.MAX_EXT))},_isConstantBlendFunc(e){return e===this.CONSTANT_COLOR||e===this.ONE_MINUS_CONSTANT_COLOR||e===this.CONSTANT_ALPHA||e===this.ONE_MINUS_CONSTANT_ALPHA},_saveError(){this._errorStack.push(this.getError())},_restoreError(e){let t=this._errorStack.pop();t===this.NO_ERROR?this.setError(e):t!==void 0&&this.setError(t)}};function installStateMethods(e){Object.assign(e,Pn)}const Fn={activeTexture(e=0){let t=e-this.TEXTURE0;if(t>=0&&t<this._textureUnits.length){this._activeTextureUnit=t,this._gl.activeTexture(e);return}this.setError(this.INVALID_ENUM)},bindTexture(e=0,t){if(!checkObject(t))throw TypeError(`bindTexture(GLenum, WebGLTexture)`);if(!this._validTextureTarget(e)){this.setError(this.INVALID_ENUM);return}let n=0;if(!t)t=null;else if(t instanceof WebGLTexture&&t._pendingDelete)return;else if(this._checkWrapper(t,WebGLTexture)){if(t._binding&&t._binding!==e){this.setError(this.INVALID_OPERATION);return}t._binding=e,t._complete&&(n=t._|0)}else return;this._saveError(),this._gl.bindTexture(e,n);let r=this.getError();if(this._restoreError(r),r!==this.NO_ERROR)return;let i=this._getActiveTextureUnit(),a=this._getActiveTexture(e);a!==t&&(a&&(--a._refCount,a._checkDelete()),t&&(t._refCount+=1)),e===this.TEXTURE_2D?i._bind2D=t:e===this.TEXTURE_CUBE_MAP&&(i._bindCube=t)},createTexture(){let e=this._gl.createTexture();if(e<=0)return null;let t=new WebGLTexture(e,this);return this._textures[e]=t,t},deleteTexture(e){if(!checkObject(e))throw TypeError(`deleteTexture(WebGLTexture)`);if(e instanceof WebGLTexture){if(!this._checkOwns(e)){this.setError(this.INVALID_OPERATION);return}}else return;let t=this._activeTextureUnit;for(let t=0;t<this._textureUnits.length;++t){let n=this._textureUnits[t];n._bind2D===e?(this.activeTexture(this.TEXTURE0+t),this.bindTexture(this.TEXTURE_2D,null)):n._bindCube===e&&(this.activeTexture(this.TEXTURE0+t),this.bindTexture(this.TEXTURE_CUBE_MAP,null))}this.activeTexture(this.TEXTURE0+t),this._detachTextureFromAllFramebuffers(e),e._pendingDelete=!0,e._checkDelete()},_detachTextureFromAllFramebuffers(e){let t=this._activeFramebuffer,n=this._getAttachments(),r=!1;for(let i in this._framebuffers){let a=this._framebuffers[i];if(!(!a||!a._linked(e))){a!==t&&(this._gl.bindFramebuffer(this.FRAMEBUFFER,a._|0),r=!0);for(let t=0;t<n.length;++t){let r=n[t];a._attachments[r]===e&&(this._gl.framebufferTexture2D(this.FRAMEBUFFER,r,a._attachmentFace[r]||this.TEXTURE_2D,0,a._attachmentLevel[r]||0),a._setAttachment(null,r))}}}r&&this._gl.bindFramebuffer(this.FRAMEBUFFER,t?t._|0:this._gtkFboId)},pixelStorei(e=0,t=0){if(typeof t==`boolean`&&(t=t===!1?0:1),e===this.UNPACK_ALIGNMENT)if(t===1||t===2||t===4||t===8)this._unpackAlignment=t;else{this.setError(this.INVALID_VALUE);return}else if(e===this.PACK_ALIGNMENT)if(t===1||t===2||t===4||t===8)this._packAlignment=t;else{this.setError(this.INVALID_VALUE);return}else if(e===this.UNPACK_COLORSPACE_CONVERSION_WEBGL){if(!(t===this.NONE||t===this.BROWSER_DEFAULT_WEBGL)){this.setError(this.INVALID_VALUE);return}}else if(e===this.UNPACK_FLIP_Y_WEBGL){this._unpackFlipY=!!t;return}else if(e===this.UNPACK_PREMULTIPLY_ALPHA_WEBGL){this._unpackPremultAlpha=!!t;return}this._gl.pixelStorei(e,t)}};function installTextureLifecycleMethods(e){Object.assign(e,Fn)}const In={texImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0,c){let l=0,u=0,d=0,f,p,m=0;if(arguments.length===6)if(s=i,d=r,a instanceof St.Pixbuf)p=a,l=p.get_width(),u=p.get_height(),c=p.get_pixels();else{f=a;let e=extractImageData(f);if(e==null)throw TypeError(`texImage2D(GLenum, GLint, GLenum, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)`);l=e.width,u=e.height,c=e.data}else arguments.length===9&&(l=r,u=i,m=a,d=o,c=c);if(typeof c!=`object`&&c!==void 0)throw TypeError(`texImage2D(GLenum, GLint, GLenum, GLint, GLint, GLint, GLenum, GLenum, Uint8Array)`);if(!checkFormat(this,d)||!checkFormat(this,n)){this.setError(this.INVALID_ENUM);return}if(s===this.FLOAT&&!this._extensions.oes_texture_float){this.setError(this.INVALID_ENUM);return}let h=this._getTexImage(e);if(!h||d!==n){this.setError(this.INVALID_OPERATION);return}let g=this._computePixelSize(s,d);if(g===0||!this._checkDimensions(e,l,u,t))return;let _=convertPixels(c),v=this._computeRowStride(l,g),y=v*u;if(_&&_.length<y){this.setError(this.INVALID_OPERATION);return}if(m!==0||validCubeTarget(this,e)&&l!==u){this.setError(this.INVALID_VALUE);return}if(this._unpackPremultAlpha&&_&&d===this.RGBA&&(_=premultiplyAlpha(_)),this._unpackFlipY&&_&&l>0&&u>0){let e=new Uint8Array(_.length);for(let t=0;t<u;t++){let n=t*v,r=(u-1-t)*v;e.set(_.subarray(n,n+v),r)}_=e}this._saveError(),this._gl.texImage2D(e,t,n,l,u,m,d,s,Uint8ArrayToVariant(_));let b=this.getError();if(this._restoreError(b),b!==this.NO_ERROR)return;h._levelWidth[t]=l,h._levelHeight[t]=u,h._format=d,h._type=s;let x=this._activeFramebuffer;if(x){let e=!1,t=this._getAttachments();for(let n=0;n<t.length;++n)if(x._attachments[t[n]]===h){e=!0;break}e&&this._activeFramebuffer&&this._updateFramebufferAttachments(this._activeFramebuffer)}},texSubImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0,c){let l=0,u=0,d=0,f,p;if(arguments.length===7)if(s=a,d=i,o instanceof St.Pixbuf)p=o,l=p.get_width(),u=p.get_height(),c=p.get_pixels();else{f=o;let e=extractImageData(f);if(e==null)throw TypeError(`texSubImage2D(GLenum, GLint, GLint, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)`);l=e.width,u=e.height,c=e.data}else l=i,u=a,d=o;if(typeof c!=`object`)throw TypeError(`texSubImage2D(GLenum, GLint, GLint, GLint, GLint, GLint, GLenum, GLenum, Uint8Array)`);if(!this._getTexImage(e)){this.setError(this.INVALID_OPERATION);return}if(s===this.FLOAT&&!this._extensions.oes_texture_float){this.setError(this.INVALID_ENUM);return}let m=this._computePixelSize(s,d);if(m===0||!this._checkDimensions(e,l,u,t))return;if(n<0||r<0){this.setError(this.INVALID_VALUE);return}let h=convertPixels(c),g=this._computeRowStride(l,m),_=g*u;if(!h||h.length<_){this.setError(this.INVALID_OPERATION);return}if(this._unpackPremultAlpha&&h&&d===this.RGBA&&(h=premultiplyAlpha(h)),this._unpackFlipY&&h&&l>0&&u>0){let e=new Uint8Array(h.length);for(let t=0;t<u;t++){let n=t*g,r=(u-1-t)*g;e.set(h.subarray(n,n+g),r)}h=e}this._gl.texSubImage2D(e,t,n,r,l,u,d,s,Uint8ArrayToVariant(h))}};function installTexImage2DMethods(e){Object.assign(e,In)}var Ln=__toESM(__commonJSMin((e=>{e.INT_MIN=-1<<31,e.isPow2=function(e){return!(e&e-1)&&!!e},e.log2=function(e){var t=(e>65535)<<4,n;return e>>>=t,n=(e>255)<<3,e>>>=n,t|=n,n=(e>15)<<2,e>>>=n,t|=n,n=(e>3)<<1,e>>>=n,t|=n,t|e>>1},e.nextPow2=function(e){return e+=e===0,--e,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e+1},(function(e){for(var t=0;t<256;++t){var n=t,r=t,i=7;for(n>>>=1;n;n>>>=1)r<<=1,r|=n&1,--i;e[t]=r<<i&255}})(Array(256))}))(),1);const Rn={copyTexImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0){let c=this._getTexImage(e);if(!c){this.setError(this.INVALID_OPERATION);return}if(n!==this.RGBA&&n!==this.RGB&&n!==this.ALPHA&&n!==this.LUMINANCE&&n!==this.LUMINANCE_ALPHA){this.setError(this.INVALID_ENUM);return}if(t<0||a<0||o<0||s!==0){this.setError(this.INVALID_VALUE);return}if(t>0&&!(Ln.isPow2(a)&&Ln.isPow2(o))){this.setError(this.INVALID_VALUE);return}this._saveError(),this._gl.copyTexImage2D(e,t,n,r,i,a,o,s);let l=this.getError();this._restoreError(l),l===this.NO_ERROR&&(c._levelWidth[t]=a,c._levelHeight[t]=o,c._format=this.RGBA,c._type=this.UNSIGNED_BYTE)},copyTexSubImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0){if(!this._getTexImage(e)){this.setError(this.INVALID_OPERATION);return}if(o<0||s<0||n<0||r<0||t<0){this.setError(this.INVALID_VALUE);return}this._gl.copyTexSubImage2D(e,t,n,r,i,a,o,s)},compressedTexImage2D(e,t,n,r,i,a,o){this._gl.compressedTexImage2D(e,t,n,r,i,a,Uint8ArrayToVariant(arrayToUint8Array(o)))},compressedTexSubImage2D(e,t,n,r,i,a,o,s){this._gl.compressedTexSubImage2D(e,t,n,r,i,a,o,Uint8ArrayToVariant(arrayToUint8Array(s)))}};function installCopyAndCompressedTextureMethods(e){Object.assign(e,Rn)}const zn={texParameterf(e=0,t=0,n){if(n=+n,this._checkTextureTarget(e)){switch(this._verifyTextureCompleteness(e,t,n),t){case this.TEXTURE_MIN_FILTER:case this.TEXTURE_MAG_FILTER:case this.TEXTURE_WRAP_S:case this.TEXTURE_WRAP_T:this._gl.texParameterf(e,t,n);return}let r=this._extensions.ext_texture_filter_anisotropic;if(r&&t===r.TEXTURE_MAX_ANISOTROPY_EXT){this._gl.texParameterf(e,t,n);return}this.setError(this.INVALID_ENUM)}},texParameteri(e=0,t=0,n=0){if(this._checkTextureTarget(e)){switch(this._verifyTextureCompleteness(e,t,n),t){case this.TEXTURE_MIN_FILTER:case this.TEXTURE_MAG_FILTER:case this.TEXTURE_WRAP_S:case this.TEXTURE_WRAP_T:this._gl.texParameteri(e,t,n);return}let r=this._extensions.ext_texture_filter_anisotropic;if(r&&t===r.TEXTURE_MAX_ANISOTROPY_EXT){this._gl.texParameteri(e,t,n);return}this.setError(this.INVALID_ENUM)}},getTexParameter(e=0,t=0){if(!this._checkTextureTarget(e))return null;let n=this._getActiveTextureUnit();if(e===this.TEXTURE_2D&&!n._bind2D||e===this.TEXTURE_CUBE_MAP&&!n._bindCube)return this.setError(this.INVALID_OPERATION),null;switch(t){case this.TEXTURE_MAG_FILTER:case this.TEXTURE_MIN_FILTER:case this.TEXTURE_WRAP_S:case this.TEXTURE_WRAP_T:return this._getTexParameterDirect(e,t)}let r=this._extensions.ext_texture_filter_anisotropic;return r&&t===r.TEXTURE_MAX_ANISOTROPY_EXT?this._getTexParameterDirect(e,t):(this.setError(this.INVALID_ENUM),null)},_getTexParameterDirect(e=0,t=0){return this._gl.getTexParameterx(e,t)?.unpack()}};function installTextureParameterMethods(e){Object.assign(e,zn)}const Bn={_getActiveTextureUnit(){return this._textureUnits[this._activeTextureUnit]},_getActiveTexture(e){let t=this._getActiveTextureUnit();return e===this.TEXTURE_2D?t._bind2D:e===this.TEXTURE_CUBE_MAP?t._bindCube:null},_getTexImage(e){let t=this._getActiveTextureUnit();return e===this.TEXTURE_2D?t._bind2D:validCubeTarget(this,e)?t._bindCube:(this.setError(this.INVALID_ENUM),null)},_checkTextureTarget(e){let t=this._getActiveTextureUnit(),n=null;if(e===this.TEXTURE_2D)n=t._bind2D;else if(e===this.TEXTURE_CUBE_MAP)n=t._bindCube;else return this.setError(this.INVALID_ENUM),!1;return n?!0:(this.setError(this.INVALID_OPERATION),!1)},_validTextureTarget(e){return e===this.TEXTURE_2D||e===this.TEXTURE_CUBE_MAP},_validCubeTarget(e){return e===this.TEXTURE_CUBE_MAP_POSITIVE_X||e===this.TEXTURE_CUBE_MAP_NEGATIVE_X||e===this.TEXTURE_CUBE_MAP_POSITIVE_Y||e===this.TEXTURE_CUBE_MAP_NEGATIVE_Y||e===this.TEXTURE_CUBE_MAP_POSITIVE_Z||e===this.TEXTURE_CUBE_MAP_NEGATIVE_Z},_verifyTextureCompleteness(e,t,n){let r=this._getActiveTextureUnit(),i=null;if(e===this.TEXTURE_2D?i=r._bind2D:this._validCubeTarget(e)&&(i=r._bindCube),this._extensions.oes_texture_float&&!this._extensions.oes_texture_float_linear&&i&&i._type===this.FLOAT&&(t===this.TEXTURE_MAG_FILTER||t===this.TEXTURE_MIN_FILTER)&&(n===this.LINEAR||n===this.LINEAR_MIPMAP_NEAREST||n===this.NEAREST_MIPMAP_LINEAR||n===this.LINEAR_MIPMAP_LINEAR)){i._complete=!1,this.bindTexture(e,i);return}i&&i._complete===!1&&(i._complete=!0,this.bindTexture(e,i))},_computePixelSize(e,t){let n=formatSize(this,t);if(n===0)return this.setError(this.INVALID_ENUM),0;switch(e){case this.UNSIGNED_BYTE:return n;case this.UNSIGNED_SHORT_5_6_5:if(t!==this.RGB){this.setError(this.INVALID_OPERATION);break}return 2;case this.UNSIGNED_SHORT_4_4_4_4:case this.UNSIGNED_SHORT_5_5_5_1:if(t!==this.RGBA){this.setError(this.INVALID_OPERATION);break}return 2;case this.FLOAT:return 1}return this.setError(this.INVALID_ENUM),0},_computeRowStride(e,t){let n=e*t;return n%this._unpackAlignment&&(n+=this._unpackAlignment-n%this._unpackAlignment),n},_checkDimensions(e,t,n,r){if(r<0||t<0||n<0)return this.setError(this.INVALID_VALUE),!1;if(e===this.TEXTURE_2D){if(t>this._maxTextureSize||n>this._maxTextureSize||r>this._maxTextureLevel)return this.setError(this.INVALID_VALUE),!1}else if(this._validCubeTarget(e)){if(t>this._maxCubeMapSize||n>this._maxCubeMapSize||r>this._maxCubeMapLevel)return this.setError(this.INVALID_VALUE),!1}else return this.setError(this.INVALID_ENUM),!1;return!0}};function installTextureIntrospectionMethods(e){Object.assign(e,Bn)}function installTextureManagementMethods(e){installTextureLifecycleMethods(e),installTexImage2DMethods(e),installCopyAndCompressedTextureMethods(e),installTextureParameterMethods(e),installTextureIntrospectionMethods(e)}var Vn=__commonJSMin(((e,t)=>{t.exports=`precision.highp.mediump.lowp.attribute.const.uniform.varying.break.continue.do.for.while.if.else.in.out.inout.float.int.uint.void.bool.true.false.discard.return.mat2.mat3.mat4.vec2.vec3.vec4.ivec2.ivec3.ivec4.bvec2.bvec3.bvec4.sampler1D.sampler2D.sampler3D.samplerCube.sampler1DShadow.sampler2DShadow.struct.asm.class.union.enum.typedef.template.this.packed.goto.switch.default.inline.noinline.volatile.public.static.extern.external.interface.long.short.double.half.fixed.unsigned.input.output.hvec2.hvec3.hvec4.dvec2.dvec3.dvec4.fvec2.fvec3.fvec4.sampler2DRect.sampler3DRect.sampler2DRectShadow.sizeof.cast.namespace.using`.split(`.`)})),Hn=__commonJSMin(((e,t)=>{t.exports=`<<= >>= ++ -- << >> <= >= == != && || += -= *= /= %= &= ^^ ^= |= ( ) [ ] . ! ~ * / % + - < > & ^ | ? : = , ; { }`.split(` `)})),Un=__commonJSMin(((e,t)=>{t.exports=`abs.acos.all.any.asin.atan.ceil.clamp.cos.cross.dFdx.dFdy.degrees.distance.dot.equal.exp.exp2.faceforward.floor.fract.gl_BackColor.gl_BackLightModelProduct.gl_BackLightProduct.gl_BackMaterial.gl_BackSecondaryColor.gl_ClipPlane.gl_ClipVertex.gl_Color.gl_DepthRange.gl_DepthRangeParameters.gl_EyePlaneQ.gl_EyePlaneR.gl_EyePlaneS.gl_EyePlaneT.gl_Fog.gl_FogCoord.gl_FogFragCoord.gl_FogParameters.gl_FragColor.gl_FragCoord.gl_FragData.gl_FragDepth.gl_FragDepthEXT.gl_FrontColor.gl_FrontFacing.gl_FrontLightModelProduct.gl_FrontLightProduct.gl_FrontMaterial.gl_FrontSecondaryColor.gl_LightModel.gl_LightModelParameters.gl_LightModelProducts.gl_LightProducts.gl_LightSource.gl_LightSourceParameters.gl_MaterialParameters.gl_MaxClipPlanes.gl_MaxCombinedTextureImageUnits.gl_MaxDrawBuffers.gl_MaxFragmentUniformComponents.gl_MaxLights.gl_MaxTextureCoords.gl_MaxTextureImageUnits.gl_MaxTextureUnits.gl_MaxVaryingFloats.gl_MaxVertexAttribs.gl_MaxVertexTextureImageUnits.gl_MaxVertexUniformComponents.gl_ModelViewMatrix.gl_ModelViewMatrixInverse.gl_ModelViewMatrixInverseTranspose.gl_ModelViewMatrixTranspose.gl_ModelViewProjectionMatrix.gl_ModelViewProjectionMatrixInverse.gl_ModelViewProjectionMatrixInverseTranspose.gl_ModelViewProjectionMatrixTranspose.gl_MultiTexCoord0.gl_MultiTexCoord1.gl_MultiTexCoord2.gl_MultiTexCoord3.gl_MultiTexCoord4.gl_MultiTexCoord5.gl_MultiTexCoord6.gl_MultiTexCoord7.gl_Normal.gl_NormalMatrix.gl_NormalScale.gl_ObjectPlaneQ.gl_ObjectPlaneR.gl_ObjectPlaneS.gl_ObjectPlaneT.gl_Point.gl_PointCoord.gl_PointParameters.gl_PointSize.gl_Position.gl_ProjectionMatrix.gl_ProjectionMatrixInverse.gl_ProjectionMatrixInverseTranspose.gl_ProjectionMatrixTranspose.gl_SecondaryColor.gl_TexCoord.gl_TextureEnvColor.gl_TextureMatrix.gl_TextureMatrixInverse.gl_TextureMatrixInverseTranspose.gl_TextureMatrixTranspose.gl_Vertex.greaterThan.greaterThanEqual.inversesqrt.length.lessThan.lessThanEqual.log.log2.matrixCompMult.max.min.mix.mod.normalize.not.notEqual.pow.radians.reflect.refract.sign.sin.smoothstep.sqrt.step.tan.texture2D.texture2DLod.texture2DProj.texture2DProjLod.textureCube.textureCubeLod.texture2DLodEXT.texture2DProjLodEXT.textureCubeLodEXT.texture2DGradEXT.texture2DProjGradEXT.textureCubeGradEXT`.split(`.`)})),Wn=__commonJSMin(((e,t)=>{t.exports=Vn().slice().concat(`layout.centroid.smooth.case.mat2x2.mat2x3.mat2x4.mat3x2.mat3x3.mat3x4.mat4x2.mat4x3.mat4x4.uvec2.uvec3.uvec4.samplerCubeShadow.sampler2DArray.sampler2DArrayShadow.isampler2D.isampler3D.isamplerCube.isampler2DArray.usampler2D.usampler3D.usamplerCube.usampler2DArray.coherent.restrict.readonly.writeonly.resource.atomic_uint.noperspective.patch.sample.subroutine.common.partition.active.filter.image1D.image2D.image3D.imageCube.iimage1D.iimage2D.iimage3D.iimageCube.uimage1D.uimage2D.uimage3D.uimageCube.image1DArray.image2DArray.iimage1DArray.iimage2DArray.uimage1DArray.uimage2DArray.image1DShadow.image2DShadow.image1DArrayShadow.image2DArrayShadow.imageBuffer.iimageBuffer.uimageBuffer.sampler1DArray.sampler1DArrayShadow.isampler1D.isampler1DArray.usampler1D.usampler1DArray.isampler2DRect.usampler2DRect.samplerBuffer.isamplerBuffer.usamplerBuffer.sampler2DMS.isampler2DMS.usampler2DMS.sampler2DMSArray.isampler2DMSArray.usampler2DMSArray`.split(`.`))})),Gn=__commonJSMin(((e,t)=>{var n=Un();n=n.slice().filter(function(e){return!/^(gl\_|texture)/.test(e)}),t.exports=n.concat(`gl_VertexID.gl_InstanceID.gl_Position.gl_PointSize.gl_FragCoord.gl_FrontFacing.gl_FragDepth.gl_PointCoord.gl_MaxVertexAttribs.gl_MaxVertexUniformVectors.gl_MaxVertexOutputVectors.gl_MaxFragmentInputVectors.gl_MaxVertexTextureImageUnits.gl_MaxCombinedTextureImageUnits.gl_MaxTextureImageUnits.gl_MaxFragmentUniformVectors.gl_MaxDrawBuffers.gl_MinProgramTexelOffset.gl_MaxProgramTexelOffset.gl_DepthRangeParameters.gl_DepthRange.trunc.round.roundEven.isnan.isinf.floatBitsToInt.floatBitsToUint.intBitsToFloat.uintBitsToFloat.packSnorm2x16.unpackSnorm2x16.packUnorm2x16.unpackUnorm2x16.packHalf2x16.unpackHalf2x16.outerProduct.transpose.determinant.inverse.texture.textureSize.textureProj.textureLod.textureOffset.texelFetch.texelFetchOffset.textureProjOffset.textureLodOffset.textureProjLod.textureProjLodOffset.textureGrad.textureGradOffset.textureProjGrad.textureProjGradOffset`.split(`.`))})),Kn=__commonJSMin(((e,t)=>{t.exports=tokenize;var n=Vn(),r=Hn(),i=Un(),a=Wn(),o=Gn(),s=999,c=9999,l=0,u=1,d=2,f=3,p=4,m=5,h=6,g=7,_=8,v=9,y=10,b=11,x=[`block-comment`,`line-comment`,`preprocessor`,`operator`,`integer`,`float`,`ident`,`builtin`,`keyword`,`whitespace`,`eof`,`integer`];function tokenize(e){var t=0,S=0,C=s,w,T,E=[],D=[],O=1,k=0,A=0,ee=!1,te=!1,j=``,ne;e||={};var re=i,ie=n;e.version===`300 es`&&(re=o,ie=a);for(var ae={},oe={},t=0;t<re.length;t++)ae[re[t]]=!0;for(var t=0;t<ie.length;t++)oe[ie[t]]=!0;return function(e){return D=[],e===null?end():write(e)};function token(e){e.length&&D.push({type:x[C],data:e,position:A,line:O,column:k})}function write(e){t=0,e.toString&&(e=e.toString()),j+=e.replace(/\r\n/g,`
68
68
  `),ne=j.length;for(var n;w=j[t],t<ne;){switch(n=t,C){case l:t=block_comment();break;case u:t=line_comment();break;case d:t=preprocessor();break;case f:t=operator();break;case p:t=integer();break;case b:t=hex();break;case m:t=decimal();break;case c:t=readtoken();break;case v:t=whitespace();break;case s:t=normal();break}if(n!==t)switch(j[n]){case`
69
69
  `:k=0,++O;break;default:++k;break}}return S+=t,j=j.slice(t),D}function end(e){return E.length&&token(E.join(``)),C=y,token(`(eof)`),D}function normal(){return E=E.length?[]:E,T===`/`&&w===`*`?(A=S+t-1,C=l,T=w,t+1):T===`/`&&w===`/`?(A=S+t-1,C=u,T=w,t+1):w===`#`?(C=d,A=S+t,t):/\s/.test(w)?(C=v,A=S+t,t):(ee=/\d/.test(w),te=/[^\w_]/.test(w),A=S+t,C=ee?p:te?f:c,t)}function whitespace(){return/[^\s]/g.test(w)?(token(E.join(``)),C=s,t):(E.push(w),T=w,t+1)}function preprocessor(){return(w===`\r`||w===`
70
- `)&&T!==`\\`?(token(E.join(``)),C=s,t):(E.push(w),T=w,t+1)}function line_comment(){return preprocessor()}function block_comment(){return w===`/`&&T===`*`?(E.push(w),token(E.join(``)),C=s,t+1):(E.push(w),T=w,t+1)}function operator(){if(T===`.`&&/\d/.test(w))return C=m,t;if(T===`/`&&w===`*`)return C=l,t;if(T===`/`&&w===`/`)return C=u,t;if(w===`.`&&E.length){for(;determine_operator(E););return C=m,t}if(w===`;`||w===`)`||w===`(`){if(E.length)for(;determine_operator(E););return token(w),C=s,t+1}var e=E.length===2&&w!==`=`;if(/[\w_\d\s]/.test(w)||e){for(;determine_operator(E););return C=s,t}return E.push(w),T=w,t+1}function determine_operator(e){var t=0,n,i;do{if(n=r.indexOf(e.slice(0,e.length+t).join(``)),i=r[n],n===-1){if(t--+e.length>0)continue;i=e.slice(0,1).join(``)}return token(i),A+=i.length,E=E.slice(i.length),E.length}while(1)}function hex(){return/[^a-fA-F0-9]/.test(w)?(token(E.join(``)),C=s,t):(E.push(w),T=w,t+1)}function integer(){return w===`.`||/[eE]/.test(w)?(E.push(w),C=m,T=w,t+1):w===`x`&&E.length===1&&E[0]===`0`?(C=b,E.push(w),T=w,t+1):/[^\d]/.test(w)?(token(E.join(``)),C=s,t):(E.push(w),T=w,t+1)}function decimal(){return w===`f`&&(E.push(w),T=w,t+=1),/[eE]/.test(w)||(w===`-`||w===`+`)&&/[eE]/.test(T)?(E.push(w),T=w,t+1):/[^\d]/.test(w)?(token(E.join(``)),C=s,t):(E.push(w),T=w,t+1)}function readtoken(){if(/[^\d\w_]/.test(w)){var e=E.join(``);return C=oe[e]?_:ae[e]?g:h,token(E.join(``)),C=s,t}return E.push(w),T=w,t+1}}})),Kn=__toESM(__commonJSMin(((e,t)=>{var n=Gn();t.exports=tokenizeString;function tokenizeString(e,t){var r=n(t),i=[];return i=i.concat(r(e)),i=i.concat(r(null)),i}}))(),1);const qn={createShader(e=0){if(e!==this.FRAGMENT_SHADER&&e!==this.VERTEX_SHADER)return this.setError(this.INVALID_ENUM),null;let t=this._gl.createShader(e);if(t<0)return null;let n=new WebGLShader$1(t,this,e);return this._shaders[t]=n,n},deleteShader(e){this._deleteLinkable(`deleteShader`,e,WebGLShader$1)},compileShader(e){if(!checkObject(e))throw TypeError(`compileShader(WebGLShader)`);if(this._checkWrapper(e,WebGLShader$1)&&this._checkShaderSource(e)){let t=this.getError();this._gl.compileShader(e._|0),e._needsRecompile=!1;let n=this.getError();e._compileStatus=!!this._gl.getShaderParameter(e._|0,this.COMPILE_STATUS),e._compileInfo=this._gl.getShaderInfoLog(e._|0)||`null`,this.getError(),this.setError(t||n)}},shaderSource(e,t){if(!checkObject(e))throw TypeError(`shaderSource(WebGLShader, String)`);if(!e||!t&&typeof t!=`string`){this.setError(this.INVALID_VALUE);return}isValidString(t)?this._checkWrapper(e,WebGLShader$1)&&(t=this._wrapShader(e._type,t),this._gl.shaderSource(e._|0,t),e._source=t,e._needsRecompile=!0):this.setError(this.INVALID_VALUE)},getShaderInfoLog(e){if(!checkObject(e))throw TypeError(`getShaderInfoLog(WebGLShader)`);return this._checkWrapper(e,WebGLShader$1)?e._compileInfo:null},getShaderParameter(e,t=0){if(!checkObject(e))throw TypeError(`getShaderParameter(WebGLShader, GLenum)`);if(this._checkWrapper(e,WebGLShader$1)){switch(t){case this.DELETE_STATUS:return e._pendingDelete;case this.COMPILE_STATUS:return e._compileStatus;case this.SHADER_TYPE:return e._type}this.setError(this.INVALID_ENUM)}return null},getShaderPrecisionFormat(e=0,t=0){if(!(e===this.FRAGMENT_SHADER||e===this.VERTEX_SHADER)||!(t===this.LOW_FLOAT||t===this.MEDIUM_FLOAT||t===this.HIGH_FLOAT||t===this.LOW_INT||t===this.MEDIUM_INT||t===this.HIGH_INT))return this.setError(this.INVALID_ENUM),null;let n=this._gl.getShaderPrecisionFormat(e,t);return n?new WebGLShaderPrecisionFormat(n):null},getShaderSource(e){if(!checkObject(e))throw TypeError(`Input to getShaderSource must be an object`);return this._checkWrapper(e,WebGLShader$1)?e._source:null},_checkShaderSource(e){let t=e._source,n=(0,Kn.default)(t),r=!1,i=[];for(let e=0;e<n.length;++e){let t=n[e];if(t)switch(t.type){case`ident`:this._validGLSLIdentifier(t.data)||(r=!0,i.push(t.line+`:`+t.column+` invalid identifier - `+t.data));break;case`preprocessor`:{let e=t.data.match(/^\s*#\s*(.*)$/);if(!e||e?.length<2)break;let n=(0,Kn.default)(e[1]);for(let e=0;e<n.length;++e){let a=n[e];(a.type===`ident`||a.type===void 0)&&(this._validGLSLIdentifier(a.data)||(r=!0,i.push(t.line+`:`+a.column+` invalid identifier - `+a.data)))}break}case`keyword`:switch(t.data){case`do`:r=!0,i.push(t.line+`:`+t.column+` do not supported`);break}break;case`builtin`:switch(t.data){case`dFdx`:case`dFdy`:case`fwidth`:!this._extensions.oes_standard_derivatives&&this._getGlslVersion(!0)===`100`&&(r=!0,i.push(t.line+`:`+t.column+` `+t.data+` not supported`));break}}}return r&&(e._compileInfo=i.join(`
70
+ `)&&T!==`\\`?(token(E.join(``)),C=s,t):(E.push(w),T=w,t+1)}function line_comment(){return preprocessor()}function block_comment(){return w===`/`&&T===`*`?(E.push(w),token(E.join(``)),C=s,t+1):(E.push(w),T=w,t+1)}function operator(){if(T===`.`&&/\d/.test(w))return C=m,t;if(T===`/`&&w===`*`)return C=l,t;if(T===`/`&&w===`/`)return C=u,t;if(w===`.`&&E.length){for(;determine_operator(E););return C=m,t}if(w===`;`||w===`)`||w===`(`){if(E.length)for(;determine_operator(E););return token(w),C=s,t+1}var e=E.length===2&&w!==`=`;if(/[\w_\d\s]/.test(w)||e){for(;determine_operator(E););return C=s,t}return E.push(w),T=w,t+1}function determine_operator(e){var t=0,n,i;do{if(n=r.indexOf(e.slice(0,e.length+t).join(``)),i=r[n],n===-1){if(t--+e.length>0)continue;i=e.slice(0,1).join(``)}return token(i),A+=i.length,E=E.slice(i.length),E.length}while(1)}function hex(){return/[^a-fA-F0-9]/.test(w)?(token(E.join(``)),C=s,t):(E.push(w),T=w,t+1)}function integer(){return w===`.`||/[eE]/.test(w)?(E.push(w),C=m,T=w,t+1):w===`x`&&E.length===1&&E[0]===`0`?(C=b,E.push(w),T=w,t+1):/[^\d]/.test(w)?(token(E.join(``)),C=s,t):(E.push(w),T=w,t+1)}function decimal(){return w===`f`&&(E.push(w),T=w,t+=1),/[eE]/.test(w)||(w===`-`||w===`+`)&&/[eE]/.test(T)?(E.push(w),T=w,t+1):/[^\d]/.test(w)?(token(E.join(``)),C=s,t):(E.push(w),T=w,t+1)}function readtoken(){if(/[^\d\w_]/.test(w)){var e=E.join(``);return C=oe[e]?_:ae[e]?g:h,token(E.join(``)),C=s,t}return E.push(w),T=w,t+1}}})),qn=__toESM(__commonJSMin(((e,t)=>{var n=Kn();t.exports=tokenizeString;function tokenizeString(e,t){var r=n(t),i=[];return i=i.concat(r(e)),i=i.concat(r(null)),i}}))(),1);const Jn={createShader(e=0){if(e!==this.FRAGMENT_SHADER&&e!==this.VERTEX_SHADER)return this.setError(this.INVALID_ENUM),null;let t=this._gl.createShader(e);if(t<0)return null;let n=new WebGLShader$1(t,this,e);return this._shaders[t]=n,n},deleteShader(e){this._deleteLinkable(`deleteShader`,e,WebGLShader$1)},compileShader(e){if(!checkObject(e))throw TypeError(`compileShader(WebGLShader)`);if(this._checkWrapper(e,WebGLShader$1)&&this._checkShaderSource(e)){let t=this.getError();this._gl.compileShader(e._|0),e._needsRecompile=!1;let n=this.getError();e._compileStatus=!!this._gl.getShaderParameter(e._|0,this.COMPILE_STATUS),e._compileInfo=this._gl.getShaderInfoLog(e._|0)||`null`,this.getError(),this.setError(t||n)}},shaderSource(e,t){if(!checkObject(e))throw TypeError(`shaderSource(WebGLShader, String)`);if(!e||!t&&typeof t!=`string`){this.setError(this.INVALID_VALUE);return}isValidString(t)?this._checkWrapper(e,WebGLShader$1)&&(t=this._wrapShader(e._type,t),this._gl.shaderSource(e._|0,t),e._source=t,e._needsRecompile=!0):this.setError(this.INVALID_VALUE)},getShaderInfoLog(e){if(!checkObject(e))throw TypeError(`getShaderInfoLog(WebGLShader)`);return this._checkWrapper(e,WebGLShader$1)?e._compileInfo:null},getShaderParameter(e,t=0){if(!checkObject(e))throw TypeError(`getShaderParameter(WebGLShader, GLenum)`);if(this._checkWrapper(e,WebGLShader$1)){switch(t){case this.DELETE_STATUS:return e._pendingDelete;case this.COMPILE_STATUS:return e._compileStatus;case this.SHADER_TYPE:return e._type}this.setError(this.INVALID_ENUM)}return null},getShaderPrecisionFormat(e=0,t=0){if(!(e===this.FRAGMENT_SHADER||e===this.VERTEX_SHADER)||!(t===this.LOW_FLOAT||t===this.MEDIUM_FLOAT||t===this.HIGH_FLOAT||t===this.LOW_INT||t===this.MEDIUM_INT||t===this.HIGH_INT))return this.setError(this.INVALID_ENUM),null;let n=this._gl.getShaderPrecisionFormat(e,t);return n?new WebGLShaderPrecisionFormat(n):null},getShaderSource(e){if(!checkObject(e))throw TypeError(`Input to getShaderSource must be an object`);return this._checkWrapper(e,WebGLShader$1)?e._source:null},_checkShaderSource(e){let t=e._source,n=(0,qn.default)(t),r=!1,i=[];for(let e=0;e<n.length;++e){let t=n[e];if(t)switch(t.type){case`ident`:this._validGLSLIdentifier(t.data)||(r=!0,i.push(t.line+`:`+t.column+` invalid identifier - `+t.data));break;case`preprocessor`:{let e=t.data.match(/^\s*#\s*(.*)$/);if(!e||e?.length<2)break;let n=(0,qn.default)(e[1]);for(let e=0;e<n.length;++e){let a=n[e];(a.type===`ident`||a.type===void 0)&&(this._validGLSLIdentifier(a.data)||(r=!0,i.push(t.line+`:`+a.column+` invalid identifier - `+a.data)))}break}case`keyword`:switch(t.data){case`do`:r=!0,i.push(t.line+`:`+t.column+` do not supported`);break}break;case`builtin`:switch(t.data){case`dFdx`:case`dFdy`:case`fwidth`:!this._extensions.oes_standard_derivatives&&this._getGlslVersion(!0)===`100`&&(r=!0,i.push(t.line+`:`+t.column+` `+t.data+` not supported`));break}}}return r&&(e._compileInfo=i.join(`
71
71
  `)),!r},_wrapShader(e,t){let n=t.startsWith(`#version`)||t.includes(`
72
72
  #version`),r=``;if(!this._extensions.oes_standard_derivatives&&/#ifdef\s+GL_OES_standard_derivatives/.test(t)&&(r+=`#undef GL_OES_standard_derivatives
73
73
  `),!this._extensions.webgl_draw_buffers&&!n&&(r+=`#define gl_MaxDrawBuffers 1
74
74
  `),n){if(r){let e=t.indexOf(`
75
75
  `);t=e===-1?t+`
76
76
  `+r:t.slice(0,e+1)+r+t.slice(e+1)}}else if(this.canvas){let e=this.canvas.getGlArea().get_use_es(),n=/\b(attribute|varying)\b/.test(t)?e?`100`:`120`:this._getGlslVersion(e);n?t=`#version `+n+`
77
- `+r+t:r&&(t=r+t)}else r&&(t=r+t);return t}};function installShaderLifecycleMethods(e){Object.assign(e,qn)}const Jn={createProgram(){let e=this._gl.createProgram();if(e<=0)return null;let t=new WebGLProgram$1(e,this);return this._programs[e]=t,t},deleteProgram(e){this._deleteLinkable(`deleteProgram`,e,WebGLProgram$1)},useProgram(e){if(!checkObject(e))throw TypeError(`useProgram(WebGLProgram)`);if(e)this._checkWrapper(e,WebGLProgram$1)&&(this._activeProgram!==e&&(this._switchActiveProgram(this._activeProgram),this._activeProgram=e,e._refCount+=1),this._gl.useProgram(e._|0));else{this._switchActiveProgram(this._activeProgram),this._activeProgram=null,this._gl.useProgram(0);return}},linkProgram(e){if(!checkObject(e))throw TypeError(`linkProgram(WebGLProgram)`);if(this._checkWrapper(e,WebGLProgram$1)){e._linkCount+=1,e._attributes=[];let t=this.getError();for(let t of e._references)t instanceof WebGLShader$1&&t._needsRecompile&&(this._gl.compileShader(t._|0),t._needsRecompile=!1);this._gl.linkProgram(e._|0);let n=this.getError();n===this.NO_ERROR&&(e._linkStatus=this._fixupLink(e)),this.getError(),this.setError(t||n)}},validateProgram(e){if(this._checkWrapper(e,WebGLProgram$1)){this._gl.validateProgram(e._|0);let t=this.getError();t===this.NO_ERROR&&(e._linkInfoLog=this._gl.getProgramInfoLog(e._|0)),this.getError(),this.setError(t)}},attachShader(e,t){if(!checkObject(e)||!checkObject(t))throw TypeError(`attachShader(WebGLProgram, WebGLShader)`);if(!e||!t){this.setError(this.INVALID_VALUE);return}else if(e instanceof WebGLProgram$1&&t instanceof WebGLShader$1&&this._checkOwns(e)&&this._checkOwns(t)&&!e._linked(t)){this._saveError(),this._gl.attachShader(e._|0,t._|0);let n=this.getError();this._restoreError(n),n===this.NO_ERROR&&e._link(t);return}this.setError(this.INVALID_OPERATION)},detachShader(e,t){if(!checkObject(e)||!checkObject(t))throw TypeError(`detachShader(WebGLProgram, WebGLShader)`);this._checkWrapper(e,WebGLProgram$1)&&this._checkWrapper(t,WebGLShader$1)&&(e._linked(t)?(this._gl.detachShader(e._,t._),e._unlink(t)):this.setError(this.INVALID_OPERATION))},bindAttribLocation(e,t,n){if(!checkObject(e)||typeof n!=`string`)throw TypeError(`bindAttribLocation(WebGLProgram, GLint, String)`);n+=``,!isValidString(n)||n.length>256?this.setError(this.INVALID_VALUE):/^_?webgl_a/.test(n)?this.setError(this.INVALID_OPERATION):this._checkWrapper(e,WebGLProgram$1)&&this._gl.bindAttribLocation(e._|0,t|0,n)},getAttachedShaders(e){if(!checkObject(e)||typeof e==`object`&&e&&!(e instanceof WebGLProgram$1))throw TypeError(`getAttachedShaders(WebGLProgram)`);if(!e)this.setError(this.INVALID_VALUE);else if(this._checkWrapper(e,WebGLProgram$1))return e._references.filter(e=>e instanceof WebGLShader$1);return null},getProgramInfoLog(e){if(!checkObject(e))throw TypeError(`getProgramInfoLog(WebGLProgram)`);return this._checkWrapper(e,WebGLProgram$1)?e._linkInfoLog:null},getProgramParameter(e,t=0){if(!checkObject(e))throw TypeError(`getProgramParameter(WebGLProgram, GLenum)`);if(this._checkWrapper(e,WebGLProgram$1)){switch(t){case this.DELETE_STATUS:return e._pendingDelete;case this.LINK_STATUS:return e._linkStatus;case this.VALIDATE_STATUS:return!!this._gl.getProgramParameter(e._,t);case this.ATTACHED_SHADERS:return this._gl.getProgramParameter(e._,t);case this.ACTIVE_ATTRIBUTES:return e._linkStatus?e._attributes.length:this._gl.getProgramParameter(e._,t);case this.ACTIVE_UNIFORMS:return e._linkStatus?e._uniforms.length:this._gl.getProgramParameter(e._,t)}this.setError(this.INVALID_ENUM)}return null},_switchActiveProgram(e){e&&(--e._refCount,e._checkDelete())},_fixupLink(e){if(!this._gl.getProgramParameter(e._,this.LINK_STATUS))return e._linkInfoLog=this._gl.getProgramInfoLog(e._),!1;let t=this.getProgramParameter(e,this.ACTIVE_ATTRIBUTES),n=Array.from({length:t});e._attributes.length=t;for(let r=0;r<t;++r)n[r]=this.getActiveAttrib(e,r)?.name,e._attributes[r]=this.getAttribLocation(e,n[r])|0;for(let t=0;t<n.length;++t)if(n[t].length>256)return e._linkInfoLog=`attribute `+n[t]+` is too long`,!1;for(let r=0;r<t;++r)e._attributes[r]<0||this._gl.bindAttribLocation(e._|0,e._attributes[r],n[r]);if(this._gl.linkProgram(e._|0),!this._gl.getProgramParameter(e._|0,this.LINK_STATUS))return e._linkInfoLog=this._gl.getProgramInfoLog(e._),!1;let r=this.getProgramParameter(e,this.ACTIVE_UNIFORMS);e._uniforms.length=r;for(let t=0;t<r;++t){let n=this.getActiveUniform(e,t);n&&(e._uniforms[t]=n)}for(let t=0;t<e._uniforms.length;++t)if(e._uniforms[t].name.length>256)return e._linkInfoLog=`uniform `+e._uniforms[t].name+` is too long`,!1;return e._linkInfoLog=``,!0},_deleteLinkable(e,t,n){if(!checkObject(t))throw TypeError(e+`(`+n.name+`)`);if(t instanceof n&&this._checkOwns(t)){t._pendingDelete=!0,t._checkDelete();return}this.setError(this.INVALID_OPERATION)}};function installProgramLifecycleMethods(e){Object.assign(e,Jn)}const Yn={getActiveAttrib(e,t){if(!checkObject(e))throw TypeError(`getActiveAttrib(WebGLProgram)`);if(!e)throw TypeError(`getActiveAttrib(WebGLProgram, GLuint)`);if(this._checkWrapper(e,WebGLProgram$1)){if(t>=(e._linkStatus?e._attributes.length:this._gl.getProgramParameter(e._|0,this.ACTIVE_ATTRIBUTES)))return this._gl.getError(),this.setError(this.INVALID_VALUE),null;let n=this._gl.getActiveAttrib(e._|0,t|0);if(n)return new WebGLActiveInfo(n)}return null},getActiveUniform(e,t){if(!checkObject(e))throw TypeError(`getActiveUniform(WebGLProgram, GLint)`);if(!e)throw TypeError(`getActiveUniform(WebGLProgram, GLuint)`);if(this._checkWrapper(e,WebGLProgram$1)){if(t>=(e._linkStatus?e._uniforms.length:this._gl.getProgramParameter(e._|0,this.ACTIVE_UNIFORMS)))return this.setError(this.INVALID_VALUE),null;let n=this._gl.getActiveUniform(e._|0,t|0);if(n)return new WebGLActiveInfo(n)}return null},getAttribLocation(e,t){if(!checkObject(e))throw TypeError(`getAttribLocation(WebGLProgram, String)`);if(t+=``,!isValidString(t)||t.length>256)this.setError(this.INVALID_VALUE);else if(this._checkWrapper(e,WebGLProgram$1))return this._gl.getAttribLocation(e._|0,t+``);return-1},getUniform(e,t){if(!checkObject(e)||!checkObject(t))throw TypeError(`getUniform(WebGLProgram, WebGLUniformLocation)`);if(!e)return this.setError(this.INVALID_VALUE),null;if(!t)return null;if(this._checkWrapper(e,WebGLProgram$1)){if(!checkUniform(e,t))return this.setError(this.INVALID_OPERATION),null;let n=this._gl.getUniform(e._|0,t._|0);if(!n)return null;switch(t._activeInfo.type){case this.FLOAT:return n[0];case this.FLOAT_VEC2:return new Float32Array(n.slice(0,2));case this.FLOAT_VEC3:return new Float32Array(n.slice(0,3));case this.FLOAT_VEC4:return new Float32Array(n.slice(0,4));case this.INT:return n[0]|0;case this.INT_VEC2:return new Int32Array(n.slice(0,2));case this.INT_VEC3:return new Int32Array(n.slice(0,3));case this.INT_VEC4:return new Int32Array(n.slice(0,4));case this.BOOL:return!!n[0];case this.BOOL_VEC2:return[!!n[0],!!n[1]];case this.BOOL_VEC3:return[!!n[0],!!n[1],!!n[2]];case this.BOOL_VEC4:return[!!n[0],!!n[1],!!n[2],!!n[3]];case this.FLOAT_MAT2:return new Float32Array(n.slice(0,4));case this.FLOAT_MAT3:return new Float32Array(n.slice(0,9));case this.FLOAT_MAT4:return new Float32Array(n.slice(0,16));case this.SAMPLER_2D:case this.SAMPLER_CUBE:return n[0]|0;default:return null}}return null},getUniformLocation(e,t){if(!checkObject(e))throw TypeError(`getUniformLocation(WebGLProgram, String)`);if(t+=``,!isValidString(t))return this.setError(this.INVALID_VALUE),null;if(this._checkWrapper(e,WebGLProgram$1)){let n=this._gl.getUniformLocation(e._|0,t);if(n!==null&&n>=0){let r=t;/\[\d+\]$/.test(t)&&(r=t.replace(/\[\d+\]$/,`[0]`));let i=r+`[0]`,a=null;for(let t=0;t<e._uniforms.length;++t){let n=e._uniforms[t];if(n.name===r||n.name===i){a={size:n.size,type:n.type,name:n.name};break}}a||={name:r,type:0,size:1};let o=new WebGLUniformLocation(n,e,a),s=t.match(/\[(\d+)\]$/),c=s?+s[1]:-1;if(a.name.endsWith(`[0]`)&&(c===-1||c===0)){let t=a.name.replace(/\[0\]$/,``),n=[];this._saveError();for(let r=0;this.getError()===this.NO_ERROR;++r){let i=this._gl.getUniformLocation(e._|0,t+`[`+r+`]`);if(this.getError()!==this.NO_ERROR||i==null||i<0)break;n.push(i)}this._restoreError(this.NO_ERROR),o._array=n}else if(c>0&&c>=a.size)return null;return o}}return null}};function installIntrospectionMethods(e){Object.assign(e,Yn)}const Xn={uniform1f(e,t){this._checkUniformValid(e,t,`uniform1f`,1,`f`)&&this._gl.uniform1f(e?._||0,t)},uniform1i(e,t){this._gl.uniform1i(e?._||0,t)},uniform2f(e,t,n){this._checkUniformValid(e,t,`uniform2f`,2,`f`)&&this._gl.uniform2f(e?._||0,t,n)},uniform2i(e,t,n){this._checkUniformValid(e,t,`uniform2i`,2,`i`)&&this._gl.uniform2i(e?._||0,t,n)},uniform3f(e,t,n,r){this._checkUniformValid(e,t,`uniform3f`,3,`f`)&&this._gl.uniform3f(e?._||0,t,n,r)},uniform3i(e,t,n,r){this._checkUniformValid(e,t,`uniform3i`,3,`i`)&&this._gl.uniform3i(e?._||0,t,n,r)},uniform4f(e,t,n,r,i){if(!this._checkUniformValid(e,t,`uniform4f`,4,`f`)){console.error(`uniform4f is not valid!`);return}this._gl.uniform4f(e?._||0,t,n,r,i)},uniform4i(e,t,n,r,i){this._checkUniformValid(e,t,`uniform4i`,4,`i`)&&this._gl.uniform4i(e?._||0,t,n,r,i)},uniform1fv(e,t){if(!(!e||!this._checkUniformValueValid(e,t,`uniform1fv`,1,`f`))){if(e?._array){let n=e._array;for(let e=0;e<n.length&&e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform1f(r,t[e])}return}this._gl.uniform1f(e?._|0,t[0])}},uniform1iv(e,t){if(this._checkUniformValueValid(e,t,`uniform1iv`,1,`i`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform1i(r,t[e])}return}this.uniform1i(e,t[0])}},uniform2fv(e,t){if(this._checkUniformValueValid(e,t,`uniform2fv`,2,`f`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&2*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform2f(r,t[2*e],t[2*e+1])}return}this._gl.uniform2f(e?._||0,t[0],t[1])}},uniform2iv(e,t){if(this._checkUniformValueValid(e,t,`uniform2iv`,2,`i`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&2*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform2i(r,t[2*e],t[2*e+1])}return}this.uniform2i(e,t[0],t[1])}},uniform3fv(e,t){if(this._checkUniformValueValid(e,t,`uniform3fv`,3,`f`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&3*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform3f(r,t[3*e],t[3*e+1],t[3*e+2])}return}this._gl.uniform3f(e?._||0,t[0],t[1],t[2])}},uniform3iv(e,t){if(this._checkUniformValueValid(e,t,`uniform3iv`,3,`i`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&3*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform3i(r,t[3*e],t[3*e+1],t[3*e+2])}return}this.uniform3i(e,t[0],t[1],t[2])}},uniform4fv(e,t){if(this._checkUniformValueValid(e,t,`uniform4fv`,4,`f`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&4*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform4f(r,t[4*e],t[4*e+1],t[4*e+2],t[4*e+3])}return}this._gl.uniform4f(e?._||0,t[0],t[1],t[2],t[3])}},uniform4iv(e,t){if(this._checkUniformValueValid(e,t,`uniform4iv`,4,`i`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&4*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform4i(r,t[4*e],t[4*e+1],t[4*e+2],t[4*e+3])}return}this.uniform4i(e,t[0],t[1],t[2],t[3])}},uniformMatrix2fv(e,t,n){if(!this._checkUniformMatrix(e,t,n,`uniformMatrix2fv`,2))return;let r=new Float32Array(n);this._gl.uniformMatrix2fv(e?._||0,!!t,listToArray(r))},uniformMatrix3fv(e,t,n){if(!this._checkUniformMatrix(e,t,n,`uniformMatrix3fv`,3))return;let r=new Float32Array(n);this._gl.uniformMatrix3fv(e?._||0,!!t,listToArray(r))},uniformMatrix4fv(e,t,n){if(!this._checkUniformMatrix(e,t,n,`uniformMatrix4fv`,4))return;let r=new Float32Array(n);this._gl.uniformMatrix4fv(e?._||0,!!t,listToArray(r))},_checkLocation(e){return e instanceof WebGLUniformLocation?e._program._ctx!==this||e._linkCount!==e._program._linkCount?(this.setError(this.INVALID_OPERATION),!1):!0:(this.setError(this.INVALID_VALUE),!1)},_checkLocationActive(e){return e&&this._checkLocation(e)?e._program===this._activeProgram?!0:(this.setError(this.INVALID_OPERATION),!1):!1},_checkUniformValid(e,t,n,r,i){if(!checkObject(e))throw TypeError(`${n}(WebGLUniformLocation, ...)`);if(!e)return!1;if(this._checkLocationActive(e)){let n=e._activeInfo.type;if(n===this.SAMPLER_2D||n===this.SAMPLER_CUBE){if(r!==1)return this.setError(this.INVALID_VALUE),!1;if(i!==`i`)return this.setError(this.INVALID_OPERATION),!1;if(t<0||t>=this._textureUnits.length)return this.setError(this.INVALID_VALUE),!1}return uniformTypeSize(this,n)>r?(this.setError(this.INVALID_OPERATION),!1):!0}return!1},_checkUniformValueValid(e,t,n,r,i){if(!checkObject(e)||!checkObject(t))throw TypeError(`${n}v(WebGLUniformLocation, Array)`);if(!e||!this._checkLocationActive(e))return!1;if(typeof t!=`object`||!t||typeof t.length!=`number`)throw TypeError(`Second argument to ${n} must be array`);return uniformTypeSize(this,e._activeInfo.type)>r?(this.setError(this.INVALID_OPERATION),!1):t.length>=r&&t.length%r===0?e._array||t.length===r?!0:(this.setError(this.INVALID_OPERATION),!1):(this.setError(this.INVALID_VALUE),!1)},_checkUniformMatrix(e,t,n,r,i){if(!checkObject(e)||typeof n!=`object`)throw TypeError(r+`(WebGLUniformLocation, Boolean, Array)`);return t||typeof n!=`object`||!n||!n.length||n.length%i*i!==0?(this.setError(this.INVALID_VALUE),!1):!e||!this._checkLocationActive(e)?!1:n.length===i*i||e._array?!0:(this.setError(this.INVALID_VALUE),!1)}};function installUniformsMethods(e){Object.assign(e,Xn)}function installShaderProgramMethods(e){installShaderLifecycleMethods(e),installProgramLifecycleMethods(e),installIntrospectionMethods(e),installUniformsMethods(e)}const Zn={drawArrays(e=0,t=0,n=0){if(t<0||n<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let r=vertexCount(this,e,n);if(r<0){this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk()||n===0)return;let i=t;n>0&&(i=n+t-1>>>0),this._checkVertexAttribState(i)&&this._gl.drawArrays(e,t,r)},drawElements(e=0,t=0,n=0,r=0){if(t<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let i=this._vertexObjectState._elementArrayBufferBinding;if(!i){this.setError(this.INVALID_OPERATION);return}let a=null,o=r;if(n===this.UNSIGNED_SHORT){if(o%2){this.setError(this.INVALID_OPERATION);return}o>>=1,a=new Uint16Array(i._elements.buffer)}else if(this._extensions.oes_element_index_uint&&n===this.UNSIGNED_INT){if(o%4){this.setError(this.INVALID_OPERATION);return}o>>=2,a=new Uint32Array(i._elements.buffer)}else if(n===this.UNSIGNED_BYTE)a=i._elements;else{this.setError(this.INVALID_ENUM);return}let s=t;switch(e){case this.TRIANGLES:t%3&&(s-=t%3);break;case this.LINES:t%2&&(s-=t%2);break;case this.POINTS:break;case this.LINE_LOOP:case this.LINE_STRIP:if(t<2){this.setError(this.INVALID_OPERATION);return}break;case this.TRIANGLE_FAN:case this.TRIANGLE_STRIP:if(t<3){this.setError(this.INVALID_OPERATION);return}break;default:this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk())return;if(t===0){this._checkVertexAttribState(0);return}if(t+o>>>0>a.length){this.setError(this.INVALID_OPERATION);return}let c=-1;for(let e=o;e<o+t;++e)c=Math.max(c,a[e]);if(c<0){this._checkVertexAttribState(0);return}this._checkVertexAttribState(c)&&s>0&&this._gl.drawElements(e,s,n,r)},viewport(e,t,n,r){this._viewport[0]=e|0,this._viewport[1]=t|0,this._viewport[2]=n|0,this._viewport[3]=r|0,this._gl.viewport(e,t,n,r)},scissor(e,t,n,r){this._scissorBox[0]=e|0,this._scissorBox[1]=t|0,this._scissorBox[2]=n|0,this._scissorBox[3]=r|0,this._gl.scissor(e|0,t|0,n|0,r|0)},readPixels(e=0,t=0,n=0,r=0,i=0,a=0,o){if(!o)return;if(!(this._extensions.oes_texture_float&&a===this.FLOAT&&i===this.RGBA)){if(i===this.RGB||i===this.ALPHA||a!==this.UNSIGNED_BYTE){this.setError(this.INVALID_OPERATION);return}else if(i!==this.RGBA){this.setError(this.INVALID_ENUM);return}else if(n<0||r<0||!(o instanceof Uint8Array)){this.setError(this.INVALID_VALUE);return}}if(!this._framebufferOk()){console.error(`framebuffer is not okay!`);return}let s=n*4;s%this._packAlignment!==0&&(s+=this._packAlignment-s%this._packAlignment);let c=s*(r-1)+n*4;if(c<=0)return;if((o.length||o.byteLength||0)<c){this.setError(this.INVALID_VALUE);return}let l=this.drawingBufferWidth,u=this.drawingBufferHeight;this._activeFramebuffer&&(l=this._activeFramebuffer._width,u=this._activeFramebuffer._height);let d=arrayToUint8Array(o);if(e>=l||e+n<=0||t>=u||t+r<=0)for(let e=0;e<d.length;++e)d[e]=0;else if(e<0||e+n>l||t<0||t+r>u){for(let e=0;e<d.length;++e)d[e]=0;let o=e,c=n;e<0&&(c+=e,o=0),o+n>l&&(c=l-o);let f=t,p=r;t<0&&(p+=t,f=0),f+r>u&&(p=u-f);let m=c*4;if(m%this._packAlignment!==0&&(m+=this._packAlignment-m%this._packAlignment),c>0&&p>0){let n=new Uint8Array(m*p),r=this._gl.readPixels(o,f,c,p,i,a,Uint8ArrayToVariant(n)),l=r&&r.length>0?r:n,u=4*(o-e)+(f-t)*s;for(let e=0;e<p;++e)for(let t=0;t<c;++t)for(let n=0;n<4;++n)d[u+e*s+4*t+n]=l[e*m+4*t+n]}}else{let o=this._gl.readPixels(e,t,n,r,i,a,Uint8ArrayToVariant(d));o&&o.length>0&&d.set(o)}},enableVertexAttribArray(e){if(e<0||e>=this._vertexObjectState._attribs.length){this.setError(this.INVALID_VALUE);return}this._gl.enableVertexAttribArray(e),this._vertexObjectState._attribs[e]._isPointer=!0},disableVertexAttribArray(e=0){if(e<0||e>=this._vertexObjectState._attribs.length){this.setError(this.INVALID_VALUE);return}this._gl.disableVertexAttribArray(e),this._vertexObjectState._attribs[e]._isPointer=!1},vertexAttrib1f(e,t){if(e|=0,!this._checkVertexIndex(e))return;let n=this._vertexGlobalState._attribs[e]._data;n[3]=1,n[1]=n[2]=0,n[0]=t,this._gl.vertexAttrib1f(e|0,+t)},vertexAttrib1fv(e,t){if(e|=0,!this._checkVertexIndex(e))return;if(typeof t!=`object`||!t||t.length<1){this.setError(this.INVALID_OPERATION);return}let n=this._vertexGlobalState._attribs[e]._data;n[3]=1,n[2]=0,n[1]=0,n[0]=t[0],this._gl.vertexAttrib1f(e|0,+t[0])},vertexAttrib2f(e,t,n){if(e|=0,!this._checkVertexIndex(e))return;let r=this._vertexGlobalState._attribs[e]._data;r[3]=1,r[2]=0,r[1]=n,r[0]=t,this._gl.vertexAttrib2f(e|0,+t,+n)},vertexAttrib2fv(e,t){if(e|=0,!this._checkVertexIndex(e))return;if(typeof t!=`object`||!t||t.length<2){this.setError(this.INVALID_OPERATION);return}let n=this._vertexGlobalState._attribs[e]._data;n[3]=1,n[2]=0,n[1]=t[1],n[0]=t[0],this._gl.vertexAttrib2f(e|0,+t[0],+t[1])},vertexAttrib3f(e,t,n,r){if(e|=0,!this._checkVertexIndex(e))return;let i=this._vertexGlobalState._attribs[e]._data;i[3]=1,i[2]=r,i[1]=n,i[0]=t,this._gl.vertexAttrib3f(e|0,+t,+n,+r)},vertexAttrib3fv(e,t){if(e|=0,!this._checkVertexIndex(e))return;if(typeof t!=`object`||!t||t.length<3){this.setError(this.INVALID_OPERATION);return}let n=this._vertexGlobalState._attribs[e]._data;n[3]=1,n[2]=t[2],n[1]=t[1],n[0]=t[0],this._gl.vertexAttrib3f(e|0,+t[0],+t[1],+t[2])},vertexAttrib4f(e=0,t,n,r,i){if(!this._checkVertexIndex(e))return;let a=this._vertexGlobalState._attribs[e]._data;a[3]=i,a[2]=r,a[1]=n,a[0]=t,this._gl.vertexAttrib4f(e|0,+t,+n,+r,+i)},vertexAttrib4fv(e,t){if(e|=0,!this._checkVertexIndex(e))return;if(typeof t!=`object`||!t||t.length<4){this.setError(this.INVALID_OPERATION);return}let n=this._vertexGlobalState._attribs[e]._data;n[3]=t[3],n[2]=t[2],n[1]=t[1],n[0]=t[0],this._gl.vertexAttrib4f(e|0,+t[0],+t[1],+t[2],+t[3])},vertexAttribPointer(e=0,t=0,n=0,r=!1,i=0,a=0){if(i<0||a<0){this.setError(this.INVALID_VALUE);return}if(i<0||a<0||e<0||e>=this._vertexObjectState._attribs.length||!(t===1||t===2||t===3||t===4)){this.setError(this.INVALID_VALUE);return}if(this._vertexGlobalState._arrayBufferBinding===null){this.setError(this.INVALID_OPERATION);return}let o=typeSize(this,n);if(o===0||n===this.INT||n===this.UNSIGNED_INT){this.setError(this.INVALID_ENUM);return}if(i>255||i<0){this.setError(this.INVALID_VALUE);return}if(i%o!==0||a%o!==0){this.setError(this.INVALID_OPERATION);return}this._gl.vertexAttribPointer(e,t,n,r,i,a),this._vertexObjectState.setVertexAttribPointer(this._vertexGlobalState._arrayBufferBinding,e,t*o,a,i||t*o,n,r,i,t)},getVertexAttrib(e=0,t=0){if(e<0||e>=this._vertexObjectState._attribs.length)return this.setError(this.INVALID_VALUE),null;let n=this._vertexObjectState._attribs[e],r=this._vertexGlobalState._attribs[e]._data,i=this._extensions.angle_instanced_arrays;if(i&&t===i.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE)return n._divisor;switch(t){case this.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:return n._pointerBuffer;case this.VERTEX_ATTRIB_ARRAY_ENABLED:return n._isPointer;case this.VERTEX_ATTRIB_ARRAY_SIZE:return n._inputSize;case this.VERTEX_ATTRIB_ARRAY_STRIDE:return n._inputStride;case this.VERTEX_ATTRIB_ARRAY_TYPE:return n._pointerType;case this.VERTEX_ATTRIB_ARRAY_NORMALIZED:return n._pointerNormal;case this.CURRENT_VERTEX_ATTRIB:return new Float32Array(r);default:return this.setError(this.INVALID_ENUM),null}},getVertexAttribOffset(e=0,t=0){return e<0||e>=this._vertexObjectState._attribs.length?(this.setError(this.INVALID_VALUE),-1):t===this.VERTEX_ATTRIB_ARRAY_POINTER?this._vertexObjectState._attribs[e]._pointerOffset:(this.setError(this.INVALID_ENUM),-1)},_checkVertexAttribState(e){let t=this._activeProgram;if(!t)return this.setError(this.INVALID_OPERATION),!1;let n=this._vertexObjectState._attribs;for(let r=0;r<n.length;++r){let i=n[r];if(i._isPointer){let n=i._pointerBuffer;if(!n)return this.setError(this.INVALID_OPERATION),!1;if(t._attributes.indexOf(r)>=0){let t=0;if(t=i._divisor?i._pointerSize+i._pointerOffset:i._pointerStride*e+i._pointerSize+i._pointerOffset,t>n._size)return this.setError(this.INVALID_OPERATION),!1}}}return!0},_checkVertexIndex(e){return e<0||e>=this._vertexObjectState._attribs.length?(this.setError(this.INVALID_VALUE),!1):!0}};function installDrawingMethods(e){Object.assign(e,Zn)}function installAllContextMethods(e){installStateMethods(e),installBufferBindingMethods(e),installTextureManagementMethods(e),installFramebufferMethods(e),installShaderProgramMethods(e),installDrawingMethods(e)}const Qn=e(import.meta.url);let $n;function load$1(){return $n===void 0&&($n=Qn(`@gjsify/node-gi/gi`).requireGi(`Gwebgl`,`0.1`)),$n}__name$1(load$1,`load`);var er=new Proxy(Object.create(null),{get(e,t){return load$1()[t]},has(e,t){return t in load$1()}});let tr=0;const nr={oes_element_index_uint:getOESElementIndexUint,oes_texture_float:getOESTextureFloat,oes_texture_float_linear:getOESTextureFloatLinear,oes_standard_derivatives:getOESStandardDerivatives,stackgl_destroy_context:getSTACKGLDestroyContext,stackgl_resize_drawingbuffer:getSTACKGLResizeDrawingBuffer,ext_blend_minmax:getEXTBlendMinMax,ext_color_buffer_float:getEXTColorBufferFloat,ext_color_buffer_half_float:getEXTColorBufferHalfFloat,ext_texture_filter_anisotropic:getEXTTextureFilterAnisotropic,oes_texture_half_float:getOESTextureHalfFloat};var WebGLContextBase=class{get drawingBufferHeight(){return this.canvas.height||0}get drawingBufferWidth(){return this.canvas.width||0}constructor(e,t={}){this.drawingBufferColorSpace=`srgb`,this.unpackColorSpace=`srgb`,this.RGBA8=32856,this.DEFAULT_ATTACHMENTS=[],this.DEFAULT_COLOR_ATTACHMENTS=[],this._=0,this._extensions={},this._programs={},this._shaders={},this._textures={},this._framebuffers={},this._renderbuffers={},this._buffers={},this._activeProgram=null,this._activeFramebuffer=null,this._activeRenderbuffer=null,this._checkStencil=!1,this._stencilState=!0,this._activeTextureUnit=0,this._errorStack=[],this._maxTextureSize=0,this._maxTextureLevel=0,this._maxCubeMapSize=0,this._maxCubeMapLevel=0,this._maxRenderbufferSize=0,this._unpackAlignment=4,this._packAlignment=4,this._unpackFlipY=!1,this._unpackPremultAlpha=!1,this._viewport=new Int32Array([0,0,0,0]),this._scissorBox=new Int32Array([0,0,0,0]),this._gtkFboId=0,this._textureUnits=[],this._drawingBuffer=null,this.canvas=e,this._contextAttributes=new WebGLContextAttributes(flag(t,`alpha`,!0),flag(t,`depth`,!0),flag(t,`stencil`,!1),!1,flag(t,`premultipliedAlpha`,!0),flag(t,`preserveDrawingBuffer`,!1),flag(t,`preferLowPowerToHighPerformance`,!1),flag(t,`failIfMajorPerformanceCaveat`,!1)),this._contextAttributes.premultipliedAlpha=this._contextAttributes.premultipliedAlpha&&this._contextAttributes.alpha}_init(){let e=this._gl.getParameterx(36006);this._gtkFboId=e?.deepUnpack()|0,this._initGLConstants(),this.DEFAULT_ATTACHMENTS=[this.COLOR_ATTACHMENT0,this.DEPTH_ATTACHMENT,this.STENCIL_ATTACHMENT,this.DEPTH_STENCIL_ATTACHMENT],this.DEFAULT_COLOR_ATTACHMENTS=[this.COLOR_ATTACHMENT0];let t=this.drawingBufferWidth||0,n=this.drawingBufferHeight||0;this._=tr++;let r=this.getParameter(this.MAX_COMBINED_TEXTURE_IMAGE_UNITS);this._textureUnits=Array.from({length:r});for(let e=0;e<r;++e)this._textureUnits[e]=new WebGLTextureUnit(this,e);this.activeTexture(this.TEXTURE0),this._defaultVertexObjectState=new WebGLVertexArrayObjectState(this),this._vertexObjectState=this._defaultVertexObjectState,this._vertexGlobalState=new WebGLVertexArrayGlobalState(this),this._maxTextureSize=this.getParameter(this.MAX_TEXTURE_SIZE),this._maxTextureLevel=Fn.log2(Fn.nextPow2(this._maxTextureSize)),this._maxCubeMapSize=this.getParameter(this.MAX_CUBE_MAP_TEXTURE_SIZE),this._maxCubeMapLevel=Fn.log2(Fn.nextPow2(this._maxCubeMapSize)),this._maxRenderbufferSize=this.getParameter(this.MAX_RENDERBUFFER_SIZE),this._unpackAlignment=4,this._packAlignment=4,this._unpackFlipY=!1,this._unpackPremultAlpha=!1,this.bindBuffer(this.ARRAY_BUFFER,null),this.bindBuffer(this.ELEMENT_ARRAY_BUFFER,null),this.bindFramebuffer(this.FRAMEBUFFER,null),this.bindRenderbuffer(this.RENDERBUFFER,null),this.viewport(0,0,t,n),this.scissor(0,0,t,n),this.clearDepth(1),this.clearColor(0,0,0,0),this.clearStencil(0),this.clear(this.COLOR_BUFFER_BIT|this.DEPTH_BUFFER_BIT|this.STENCIL_BUFFER_BIT),this.disable(this.DEPTH_TEST),this.disable(this.STENCIL_TEST),this.disable(this.BLEND),this.disable(this.CULL_FACE),this.disable(this.POLYGON_OFFSET_FILL),this.disable(this.SCISSOR_TEST),this._gl.colorMask(!0,!0,!0,!0)}_initGLConstants(){let e=new er.WebGLRenderingContextBase().get_webgl_constants();for(let[t,n]of Object.entries(e))Object.defineProperty(this,t,{value:n})}_getGlslVersion(e){return e?`100`:`120`}_checkOwns(e){return typeof e==`object`&&!!e&&e._ctx===this}_checkValid(e,t){return e instanceof t&&e._!==0}_checkWrapper(e,t){return this._checkValid(e,t)?this._checkOwns(e)?!0:(this.setError(this.INVALID_OPERATION),!1):(this.setError(this.INVALID_VALUE),!1)}_isObject(e,t,n){if(e!=null&&!(e instanceof n))throw TypeError(t+`(`+n.name+`)`);return!!(this._checkValid(e,n)&&this._checkOwns(e))}_checkStencilState(){return this._checkStencil?(this._checkStencil=!1,this._stencilState=!0,(this.getParameter(this.STENCIL_WRITEMASK)!==this.getParameter(this.STENCIL_BACK_WRITEMASK)||this.getParameter(this.STENCIL_VALUE_MASK)!==this.getParameter(this.STENCIL_BACK_VALUE_MASK)||this.getParameter(this.STENCIL_REF)!==this.getParameter(this.STENCIL_BACK_REF))&&(this.setError(this.INVALID_OPERATION),this._stencilState=!1),this._stencilState):this._stencilState}_validGLSLIdentifier(e){return!(e.indexOf(`webgl_`)===0||e.indexOf(`_webgl_`)===0||e.length>256)}_getParameterDirect(e){return this._gl.getParameterx(e)?.deepUnpack()}getContextAttributes(){return this._contextAttributes}getExtension(e){let t=e.toLowerCase();if(t in this._extensions)return this._extensions[t];let n=nr[t]?nr[t](this):null;return n&&(this._extensions[t]=n),n}getSupportedExtensions(){let e=[`ANGLE_instanced_arrays`,`STACKGL_resize_drawingbuffer`,`STACKGL_destroy_context`],t=this._gl.getSupportedExtensions();return t?(t.indexOf(`GL_OES_element_index_uint`)>=0&&e.push(`OES_element_index_uint`),t.indexOf(`GL_OES_standard_derivatives`)>=0&&e.push(`OES_standard_derivatives`),t.indexOf(`GL_OES_texture_float`)>=0&&e.push(`OES_texture_float`),t.indexOf(`GL_OES_texture_float_linear`)>=0&&e.push(`OES_texture_float_linear`),(t.indexOf(`GL_OES_texture_half_float`)>=0||t.indexOf(`GL_ARB_half_float_pixel`)>=0)&&e.push(`OES_texture_half_float`),(t.indexOf(`GL_EXT_color_buffer_float`)>=0||t.indexOf(`GL_ARB_color_buffer_float`)>=0)&&e.push(`EXT_color_buffer_float`),t.indexOf(`GL_EXT_color_buffer_half_float`)>=0&&e.push(`EXT_color_buffer_half_float`),t.indexOf(`EXT_draw_buffers`)>=0&&e.push(`WEBGL_draw_buffers`),t.indexOf(`EXT_blend_minmax`)>=0&&e.push(`EXT_blend_minmax`),t.indexOf(`EXT_texture_filter_anisotropic`)>=0&&e.push(`EXT_texture_filter_anisotropic`),t.indexOf(`GL_OES_vertex_array_object`)>=0&&e.push(`OES_vertex_array_object`),e):e}getParameter(e=0){switch(e){case this.ARRAY_BUFFER_BINDING:return this._vertexGlobalState._arrayBufferBinding;case this.ELEMENT_ARRAY_BUFFER_BINDING:return this._vertexObjectState._elementArrayBufferBinding;case this.CURRENT_PROGRAM:return this._activeProgram;case this.FRAMEBUFFER_BINDING:return this._activeFramebuffer;case this.RENDERBUFFER_BINDING:return this._activeRenderbuffer;case this.TEXTURE_BINDING_2D:return this._getActiveTextureUnit()._bind2D;case this.TEXTURE_BINDING_CUBE_MAP:return this._getActiveTextureUnit()._bindCube;case this.VERSION:return`WebGL 1.0 0.0.1`;case this.VENDOR:return``;case this.RENDERER:return`ANGLE`;case this.SHADING_LANGUAGE_VERSION:return`WebGL GLSL ES 1.0 `;case this.COMPRESSED_TEXTURE_FORMATS:return new Uint32Array;case this.SCISSOR_BOX:return new Int32Array(this._scissorBox);case this.VIEWPORT:return new Int32Array(this._viewport);case this.MAX_VIEWPORT_DIMS:return new Int32Array([32767,32767]);case this.ALIASED_LINE_WIDTH_RANGE:case this.ALIASED_POINT_SIZE_RANGE:return new Float32Array([1,1]);case this.DEPTH_RANGE:return new Float32Array([0,1]);case this.BLEND_COLOR:case this.COLOR_CLEAR_VALUE:return new Float32Array(this._gl.getParameterfv(e,4));case this.COLOR_WRITEMASK:{let t=this._gl.getParameteriv(e,4);return[!!t[0],!!t[1],!!t[2],!!t[3]]}case this.DEPTH_CLEAR_VALUE:case this.LINE_WIDTH:case this.POLYGON_OFFSET_FACTOR:case this.POLYGON_OFFSET_UNITS:case this.SAMPLE_COVERAGE_VALUE:return this._gl.getParameterf(e);case this.BLEND:case this.CULL_FACE:case this.DEPTH_TEST:case this.DEPTH_WRITEMASK:case this.DITHER:case this.POLYGON_OFFSET_FILL:case this.SAMPLE_COVERAGE_INVERT:case this.SCISSOR_TEST:case this.STENCIL_TEST:case this.UNPACK_PREMULTIPLY_ALPHA_WEBGL:return!!this._gl.getParameteri(e);case this.UNPACK_FLIP_Y_WEBGL:return this._unpackFlipY;case this.ACTIVE_TEXTURE:case this.ALPHA_BITS:case this.BLEND_DST_ALPHA:case this.BLEND_DST_RGB:case this.BLEND_EQUATION_ALPHA:case this.BLEND_EQUATION_RGB:case this.BLEND_SRC_ALPHA:case this.BLEND_SRC_RGB:case this.BLUE_BITS:case this.CULL_FACE_MODE:case this.DEPTH_BITS:case this.DEPTH_FUNC:case this.FRONT_FACE:case this.GENERATE_MIPMAP_HINT:case this.GREEN_BITS:return this._gl.getParameteri(e);case this.MAX_RENDERBUFFER_SIZE:return this._maxRenderbufferSize;case this.MAX_COMBINED_TEXTURE_IMAGE_UNITS:case this.MAX_CUBE_MAP_TEXTURE_SIZE:case this.MAX_FRAGMENT_UNIFORM_VECTORS:case this.MAX_TEXTURE_IMAGE_UNITS:case this.MAX_TEXTURE_SIZE:case this.MAX_VARYING_VECTORS:case this.MAX_VERTEX_ATTRIBS:case this.MAX_VERTEX_TEXTURE_IMAGE_UNITS:case this.MAX_VERTEX_UNIFORM_VECTORS:case this.PACK_ALIGNMENT:case this.RED_BITS:case this.SAMPLE_BUFFERS:case this.SAMPLES:case this.STENCIL_BACK_FAIL:case this.STENCIL_BACK_FUNC:case this.STENCIL_BACK_PASS_DEPTH_FAIL:case this.STENCIL_BACK_PASS_DEPTH_PASS:case this.STENCIL_BACK_REF:case this.STENCIL_BACK_VALUE_MASK:case this.STENCIL_BACK_WRITEMASK:case this.STENCIL_BITS:case this.STENCIL_CLEAR_VALUE:case this.STENCIL_FAIL:case this.STENCIL_FUNC:case this.STENCIL_PASS_DEPTH_FAIL:case this.STENCIL_PASS_DEPTH_PASS:case this.STENCIL_REF:case this.STENCIL_VALUE_MASK:case this.STENCIL_WRITEMASK:case this.SUBPIXEL_BITS:case this.UNPACK_ALIGNMENT:case this.UNPACK_COLORSPACE_CONVERSION_WEBGL:return this._gl.getParameteri(e);case this.IMPLEMENTATION_COLOR_READ_FORMAT:case this.IMPLEMENTATION_COLOR_READ_TYPE:return this._getParameterDirect(e);default:if(this._extensions.webgl_draw_buffers){let t=this._extensions.webgl_draw_buffers;switch(e){case t.DRAW_BUFFER0_WEBGL:case t.DRAW_BUFFER1_WEBGL:case t.DRAW_BUFFER2_WEBGL:case t.DRAW_BUFFER3_WEBGL:case t.DRAW_BUFFER4_WEBGL:case t.DRAW_BUFFER5_WEBGL:case t.DRAW_BUFFER6_WEBGL:case t.DRAW_BUFFER7_WEBGL:case t.DRAW_BUFFER8_WEBGL:case t.DRAW_BUFFER9_WEBGL:case t.DRAW_BUFFER10_WEBGL:case t.DRAW_BUFFER11_WEBGL:case t.DRAW_BUFFER12_WEBGL:case t.DRAW_BUFFER13_WEBGL:case t.DRAW_BUFFER14_WEBGL:case t.DRAW_BUFFER15_WEBGL:return t._buffersState.length===1&&t._buffersState[0]===this.BACK?this.BACK:this._getParameterDirect(e);case t.MAX_DRAW_BUFFERS_WEBGL:case t.MAX_COLOR_ATTACHMENTS_WEBGL:return this._getParameterDirect(e)}}let t=this._extensions.oes_standard_derivatives;if(t&&e===t.FRAGMENT_SHADER_DERIVATIVE_HINT_OES)return this._getParameterDirect(e);let n=this._extensions.ext_texture_filter_anisotropic;if(n&&e===n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)return this._getParameterDirect(e);let r=this._extensions.oes_vertex_array_object;return r&&e===r.VERTEX_ARRAY_BINDING_OES?r._activeVertexArrayObject:(this.setError(this.INVALID_ENUM),null)}}destroy(){warnNotImplemented(`destroy`)}};installAllContextMethods(WebGLContextBase.prototype);var WebGLRenderingContext$1=class extends WebGLContextBase{static{__name$1(this,`WebGLRenderingContext`)}get _gl(){return this._native}constructor(e,t={}){super(e,t),this._attrib0Buffer=null,this._native=new er.WebGLRenderingContext({}),this._init();let n=this.createBuffer();this._attrib0Buffer=n}_beginAttrib0Hack(){this._native.bindBuffer(this.ARRAY_BUFFER,this._attrib0Buffer?._||0);let e=new Uint8Array(this._vertexGlobalState._attribs[0]._data.buffer);this._native.bufferData(this.ARRAY_BUFFER,Uint8ArrayToVariant(e),this.STREAM_DRAW),this._native.enableVertexAttribArray(0),this._native.vertexAttribPointer(0,4,this.FLOAT,!1,0,0),this._native._vertexAttribDivisor(0,1)}_endAttrib0Hack(){let e=this._vertexObjectState._attribs[0];e._pointerBuffer?this._native.bindBuffer(this.ARRAY_BUFFER,e._pointerBuffer._):this._native.bindBuffer(this.ARRAY_BUFFER,0),this._native.vertexAttribPointer(0,e._inputSize,e._pointerType,e._pointerNormal,e._inputStride,e._pointerOffset),this._native._vertexAttribDivisor(0,e._divisor),this._native.disableVertexAttribArray(0),this._vertexGlobalState._arrayBufferBinding?this._native.bindBuffer(this.ARRAY_BUFFER,this._vertexGlobalState._arrayBufferBinding._):this._native.bindBuffer(this.ARRAY_BUFFER,0)}drawArrays(e=0,t=0,n=0){if(t<0||n<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let r=vertexCount(this,e,n);if(r<0){this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk()||n===0)return;let i=t;if(n>0&&(i=n+t-1>>>0),this._checkVertexAttribState(i)){let n=this._extensions.webgl_draw_buffers;if(this._vertexObjectState._attribs[0]._isPointer||n&&n._buffersState&&n._buffersState.length>0)return this._native.drawArrays(e,t,r);this._beginAttrib0Hack(),this._native._drawArraysInstanced(e,t,r,1),this._endAttrib0Hack()}}drawElements(e=0,t=0,n=0,r=0){if(t<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let i=this._vertexObjectState._elementArrayBufferBinding;if(!i){this.setError(this.INVALID_OPERATION);return}let a=null,o=r;if(n===this.UNSIGNED_SHORT){if(o%2){this.setError(this.INVALID_OPERATION);return}o>>=1,a=new Uint16Array(i._elements.buffer)}else if(this._extensions.oes_element_index_uint&&n===this.UNSIGNED_INT){if(o%4){this.setError(this.INVALID_OPERATION);return}o>>=2,a=new Uint32Array(i._elements.buffer)}else if(n===this.UNSIGNED_BYTE)a=i._elements;else{this.setError(this.INVALID_ENUM);return}let s=t;switch(e){case this.TRIANGLES:t%3&&(s-=t%3);break;case this.LINES:t%2&&(s-=t%2);break;case this.POINTS:break;case this.LINE_LOOP:case this.LINE_STRIP:if(t<2){this.setError(this.INVALID_OPERATION);return}break;case this.TRIANGLE_FAN:case this.TRIANGLE_STRIP:if(t<3){this.setError(this.INVALID_OPERATION);return}break;default:this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk())return;if(t===0){this._checkVertexAttribState(0);return}if(t+o>>>0>a.length){this.setError(this.INVALID_OPERATION);return}let c=-1;for(let e=o;e<o+t;++e)c=Math.max(c,a[e]);if(c<0){this._checkVertexAttribState(0);return}if(this._checkVertexAttribState(c)&&s>0){if(this._vertexObjectState._attribs[0]._isPointer)return this._native.drawElements(e,s,n,r);this._beginAttrib0Hack(),this._native._drawElementsInstanced(e,s,n,r,1),this._endAttrib0Hack()}}},WebGLQuery=class extends Linkable{constructor(e,t){super(e),this._ctx=t}_performDelete(){let e=this._ctx;delete e._queries[this._|0],e._native2.deleteQuery(this._|0)}},WebGLSampler=class extends Linkable{constructor(e,t){super(e),this._ctx=t}_performDelete(){let e=this._ctx;delete e._samplers[this._|0],e._native2.deleteSampler(this._|0)}},WebGLSync=class extends Linkable{constructor(e,t){super(e),this._ctx=t}_performDelete(){let e=this._ctx;delete e._syncs[this._|0],e._native2.deleteSync(this._|0)}},WebGLTransformFeedback=class extends Linkable{constructor(e,t){super(e),this._ctx=t}_performDelete(){let e=this._ctx;delete e._transformFeedbacks[this._|0],e._native2.deleteTransformFeedback(this._|0)}},WebGLVertexArrayObject=class extends Linkable{constructor(e,t){super(e),this._ctx=t,this._objectState=new WebGLVertexArrayObjectState(t)}_performDelete(){let e=this._ctx;e._vertexObjectState===this._objectState&&(e._vertexObjectState=e._defaultVertexObjectState),this._objectState.cleanUp(),delete e._vertexArrayObjects[this._|0],e._native2.deleteVertexArray(this._|0)}};const rr={createVertexArray(){let e=this._native2.createVertexArray();if(!e)return null;let t=new WebGLVertexArrayObject(e,this);return this._vertexArrayObjects[e]=t,t},deleteVertexArray(e){!e||!(e instanceof WebGLVertexArrayObject)||(e._pendingDelete=!0,e._checkDelete())},isVertexArray(e){return!e||!(e instanceof WebGLVertexArrayObject)?!1:this._native2.isVertexArray(e._)},bindVertexArray(e){e===null?(this._native2.bindVertexArray(0),this._vertexObjectState=this._defaultVertexObjectState):e instanceof WebGLVertexArrayObject?(this._native2.bindVertexArray(e._),this._vertexObjectState=e._objectState):this.setError(this.INVALID_OPERATION)},createQuery(){let e=this._native2.createQuery();if(!e)return null;let t=new WebGLQuery(e,this);return this._queries[e]=t,t},deleteQuery(e){!e||!(e instanceof WebGLQuery)||(e._pendingDelete=!0,e._checkDelete())},isQuery(e){return!e||!(e instanceof WebGLQuery)?!1:this._native2.isQuery(e._)},beginQuery(e,t){t instanceof WebGLQuery&&this._native2.beginQuery(e,t._)},endQuery(e){this._native2.endQuery(e)},getQuery(e,t){return warnNotImplemented(`WebGL2RenderingContext.getQuery`),null},getQueryParameter(e,t){return e instanceof WebGLQuery?this._native2.getQueryParameter(e._,t):null},createSampler(){let e=this._native2.createSampler();if(!e)return null;let t=new WebGLSampler(e,this);return this._samplers[e]=t,t},deleteSampler(e){!e||!(e instanceof WebGLSampler)||(e._pendingDelete=!0,e._checkDelete())},isSampler(e){return!e||!(e instanceof WebGLSampler)?!1:this._native2.isSampler(e._)},bindSampler(e,t){this._native2.bindSampler(e,t?t._:0)},samplerParameteri(e,t,n){e instanceof WebGLSampler&&this._native2.samplerParameteri(e._,t,n)},samplerParameterf(e,t,n){e instanceof WebGLSampler&&this._native2.samplerParameterf(e._,t,n)},getSamplerParameter(e,t){return e instanceof WebGLSampler?t===33082||t===33083?this._native2.getSamplerParameterf(e._,t):this._native2.getSamplerParameteri(e._,t):null},fenceSync(e,t){let n=this._native2.fenceSync(e,t);if(!n)return null;let r=new WebGLSync(n,this);return this._syncs[n]=r,r},isSync(e){return!e||!(e instanceof WebGLSync)?!1:this._native2.isSync(e._)},deleteSync(e){!e||!(e instanceof WebGLSync)||(e._pendingDelete=!0,e._checkDelete())},clientWaitSync(e,t,n){return e instanceof WebGLSync?this._native2.clientWaitSync(e._,t,n):37148},waitSync(e,t,n){e instanceof WebGLSync&&this._native2.waitSync(e._,t,n)},getSyncParameter(e,t){return e instanceof WebGLSync?this._native2.getSyncParameter(e._,t):null},createTransformFeedback(){let e=this._native2.createTransformFeedback();if(!e)return null;let t=new WebGLTransformFeedback(e,this);return this._transformFeedbacks[e]=t,t},deleteTransformFeedback(e){!e||!(e instanceof WebGLTransformFeedback)||(e._pendingDelete=!0,e._checkDelete())},isTransformFeedback(e){return!e||!(e instanceof WebGLTransformFeedback)?!1:this._native2.isTransformFeedback(e._)},bindTransformFeedback(e,t){this._native2.bindTransformFeedback(e,t?t._:0)},beginTransformFeedback(e){this._native2.beginTransformFeedback(e)},endTransformFeedback(){this._native2.endTransformFeedback()},pauseTransformFeedback(){this._native2.pauseTransformFeedback()},resumeTransformFeedback(){this._native2.resumeTransformFeedback()},transformFeedbackVaryings(e,t,n){this._native2.transformFeedbackVaryings(e._,t,n)},getTransformFeedbackVarying(e,t){let n=this._native2.getTransformFeedbackVarying(e._,t).deepUnpack();return new WebGLActiveInfo({size:n.size,type:n.type,name:n.name})}};function installObjectLifecycleMethods(e){Object.assign(e,rr)}const ir={texImage3D(e,t,n,r,i,a,o,s,c,l){l===null?this._native2.texImage3DNull(e,t,n,r,i,a,o,s,c):this._native2.texImage3D(e,t,n,r,i,a,o,s,c,Uint8ArrayToVariant(new Uint8Array(l.buffer,l.byteOffset,l.byteLength)))},texSubImage3D(e,t,n,r,i,a,o,s,c,l,u){u!==null&&this._native2.texSubImage3D(e,t,n,r,i,a,o,s,c,l,Uint8ArrayToVariant(new Uint8Array(u.buffer,u.byteOffset,u.byteLength)))},compressedTexImage3D(e,t,n,r,i,a,o,s,c){this._native2.compressedTexImage3D(e,t,n,r,i,a,o,Uint8ArrayToVariant(new Uint8Array(c.buffer,c.byteOffset,c.byteLength)))},compressedTexSubImage3D(e,t,n,r,i,a,o,s,c,l,u){this._native2.compressedTexSubImage3D(e,t,n,r,i,a,o,s,c,Uint8ArrayToVariant(new Uint8Array(u.buffer,u.byteOffset,u.byteLength)))},copyTexSubImage3D(e,t,n,r,i,a,o,s,c){this._native2.copyTexSubImage3D(e,t,n,r,i,a,o,s,c)},texStorage2D(e,t,n,r,i){this._native2.texStorage2D(e,t,n,r,i);let a=this._getTexImage(e);if(a){for(let e=0;e<t;e++)a._levelWidth[e]=Math.max(1,r>>e),a._levelHeight[e]=Math.max(1,i>>e);a._format=this.RGBA,a._type=this.UNSIGNED_BYTE}},texStorage3D(e,t,n,r,i,a){this._native2.texStorage3D(e,t,n,r,i,a)}};function installTexImage3DMethods(e){Object.assign(e,ir)}const ar={uniform1ui(e,t){e&&this._native2.uniform1ui(e._,t)},uniform2ui(e,t,n){e&&this._native2.uniform2ui(e._,t,n)},uniform3ui(e,t,n,r){e&&this._native2.uniform3ui(e._,t,n,r)},uniform4ui(e,t,n,r,i){e&&this._native2.uniform4ui(e._,t,n,r,i)},uniform1uiv(e,t,n,r){if(!e)return;let i=t instanceof Uint32Array?t:new Uint32Array(t);this._native2.uniform1uiv(e._,i.length,i)},uniform2uiv(e,t,n,r){if(!e)return;let i=t instanceof Uint32Array?t:new Uint32Array(t);this._native2.uniform2uiv(e._,i.length/2,i)},uniform3uiv(e,t,n,r){if(!e)return;let i=t instanceof Uint32Array?t:new Uint32Array(t);this._native2.uniform3uiv(e._,i.length/3,i)},uniform4uiv(e,t,n,r){if(!e)return;let i=t instanceof Uint32Array?t:new Uint32Array(t);this._native2.uniform4uiv(e._,i.length/4,i)},uniformMatrix2x3fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix2x3fv(e._,t,a)},uniformMatrix3x2fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix3x2fv(e._,t,a)},uniformMatrix2x4fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix2x4fv(e._,t,a)},uniformMatrix4x2fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix4x2fv(e._,t,a)},uniformMatrix3x4fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix3x4fv(e._,t,a)},uniformMatrix4x3fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix4x3fv(e._,t,a)}};function installUniformMethods(e){Object.assign(e,ar)}const or={clearBufferfv(e,t,n,r){let i=this._native2;if(typeof i.clearBufferfv==`function`){i.clearBufferfv(e,t,Array.from(n));return}let a=n;if(e===6144){let e=this.getParameter(this.COLOR_CLEAR_VALUE);this.clearColor(a[0]??0,a[1]??0,a[2]??0,a[3]??0),this.clear(this.COLOR_BUFFER_BIT),e&&this.clearColor(e[0],e[1],e[2],e[3])}else if(e===6145){let e=this.getParameter(this.DEPTH_CLEAR_VALUE);this.clearDepth(a[0]??1),this.clear(this.DEPTH_BUFFER_BIT),e!==null&&this.clearDepth(e)}},clearBufferiv(e,t,n,r){let i=this._native2;if(typeof i.clearBufferiv==`function`){i.clearBufferiv(e,t,Array.from(n));return}if(e===6146){let e=n,t=this.getParameter(this.STENCIL_CLEAR_VALUE);this.clearStencil(e[0]??0),this.clear(this.STENCIL_BUFFER_BIT),t!==null&&this.clearStencil(t)}},clearBufferuiv(e,t,n,r){let i=this._native2;if(typeof i.clearBufferuiv==`function`){i.clearBufferuiv(e,t,Array.from(n));return}},clearBufferfi(e,t,n,r){let i=this._native2;if(typeof i.clearBufferfi==`function`){i.clearBufferfi(e,t,n,r);return}if(e===34041){let e=this.getParameter(this.DEPTH_CLEAR_VALUE),t=this.getParameter(this.STENCIL_CLEAR_VALUE);this.clearDepth(n),this.clearStencil(r),this.clear(this.DEPTH_BUFFER_BIT|this.STENCIL_BUFFER_BIT),e!==null&&this.clearDepth(e),t!==null&&this.clearStencil(t)}}};function installClearBufferMethods(e){Object.assign(e,or)}function debugGlEnabled(){return globalThis.__GJSIFY_DEBUG_GL===!0}const sr={drawArraysInstanced(e,t,n,r){if(t<0||n<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let i=vertexCount(this,e,n);if(i<0){this.setError(this.INVALID_ENUM);return}if(this._framebufferOk()&&!(n===0||r===0)&&this._checkVertexAttribState(n+t-1>>>0)){if(debugGlEnabled()){let e=this,t=e.__drawInstCount=(e.__drawInstCount|0)+1;(t<=5||t%100==0)&&console.log(`[WebGL] drawArraysInstanced #${t} count=${i} instances=${r} fbo=${this._activeFramebuffer?._??`_gtkFbo`}`)}this._native2.drawArraysInstanced(e,t,i,r)}},drawElementsInstanced(e,t,n,r,i){if(t<0||r<0||i<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let a=this._vertexObjectState._elementArrayBufferBinding;if(!a){this.setError(this.INVALID_OPERATION);return}let o=null,s=r;if(n===this.UNSIGNED_SHORT){if(s%2){this.setError(this.INVALID_OPERATION);return}s>>=1,o=new Uint16Array(a._elements.buffer)}else if(n===this.UNSIGNED_INT){if(s%4){this.setError(this.INVALID_OPERATION);return}s>>=2,o=new Uint32Array(a._elements.buffer)}else if(n===this.UNSIGNED_BYTE)o=a._elements;else{this.setError(this.INVALID_ENUM);return}let c=t;switch(e){case this.TRIANGLES:t%3&&(c-=t%3);break;case this.LINES:t%2&&(c-=t%2);break;case this.POINTS:break;case this.LINE_LOOP:case this.LINE_STRIP:if(t<2){this.setError(this.INVALID_OPERATION);return}break;case this.TRIANGLE_FAN:case this.TRIANGLE_STRIP:if(t<3){this.setError(this.INVALID_OPERATION);return}break;default:this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk())return;if(c===0||i===0){this._checkVertexAttribState(0);return}if(c+s>>>0>o.length){this.setError(this.INVALID_OPERATION);return}let l=0;for(let e=s;e<s+c;++e)o[e]>l&&(l=o[e]);this._checkVertexAttribState(l)&&this._native2.drawElementsInstanced(e,c,n,r,i)},vertexAttribDivisor(e,t){this._native2.vertexAttribDivisor(e,t)},vertexAttribIPointer(e,t,n,r,i){this._native2.vertexAttribIPointer(e,t,n,r,i)},drawBuffers(e){let t=!1;for(let n=0;n<e.length;n++)if(e[n]===1029){t=!0;break}if(!t){this._native2.drawBuffers(e);return}this._native2.drawBuffers(e.map(e=>e===1029?this.COLOR_ATTACHMENT0:e))},drawRangeElements(e,t,n,r,i,a){if(r<0||a<0){this.setError(this.INVALID_VALUE);return}if(n<t){this.setError(this.INVALID_VALUE);return}this.drawElements(e,r,i,a)},blitFramebuffer(e,t,n,r,i,a,o,s,c,l){if(debugGlEnabled()){let e=this._gl.getError();e!==0&&console.log(`[WebGL] blitFramebuffer PRE-ERROR 0x${e.toString(16)}`)}if(this._native2.blitFramebuffer(e,t,n,r,i,a,o,s,c,l),debugGlEnabled()){let i=this._gl.getError(),a=this,o=a.__blitCount=(a.__blitCount|0)+1;o<=5&&console.log(`[WebGL] blitFramebuffer #${o} src=(${e},${t},${n},${r}) readFbo=${this._activeReadFramebuffer?._??`_gtkFbo`} err=${i===0?`OK`:`0x`+i.toString(16)}`)}},framebufferTextureLayer(e,t,n,r,i){this._native2.framebufferTextureLayer(e,t,n?n._:0,r,i)},invalidateFramebuffer(e,t){this._native2.invalidateFramebuffer(e,t)},invalidateSubFramebuffer(e,t,n,r,i,a){this._native2.invalidateSubFramebuffer(e,t,n,r,i,a)},readBuffer(e){this._native2.readBuffer(e)},renderbufferStorageMultisample(e,t,n,r,i){if(e!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}let a=this._activeRenderbuffer;if(!a){this.setError(this.INVALID_OPERATION);return}this._saveError(),this._native2.renderbufferStorageMultisample(e,t,n,r,i);let o=this.getError();this._restoreError(o),o===this.NO_ERROR&&(a._width=r,a._height=i,a._format=n)}};function installInstancedAndFramebufferOpsMethods(e){Object.assign(e,sr)}var cr=class WebGL2RenderingContext extends WebGLContextBase{get _gl(){return this._native2}constructor(e,t={}){super(e,t),this._queries={},this._samplers={},this._transformFeedbacks={},this._vertexArrayObjects={},this._syncs={},this._activeReadFramebuffer=null,this._activeDrawFramebuffer=null,this._native2=new er.WebGL2RenderingContext({}),this._init()}_getGlslVersion(e){return e?`300 es`:`130`}_validFramebufferAttachment(e){return super._validFramebufferAttachment(e)?!0:e>=36065&&e<=36079}static{this._WGL2_ALL_COLOR_ATTACHMENTS=[36064,36065,36066,36067,36068,36069,36070,36071,36072,36073,36074,36075,36076,36077,36078,36079]}_getColorAttachments(){return WebGL2RenderingContext._WGL2_ALL_COLOR_ATTACHMENTS}_preCheckFramebufferStatus(e){let t=e._attachments,n=0,r=0,i=[this.COLOR_ATTACHMENT0,this.DEPTH_ATTACHMENT,this.STENCIL_ATTACHMENT,this.DEPTH_STENCIL_ATTACHMENT,...WebGL2RenderingContext._WGL2_ALL_COLOR_ATTACHMENTS];for(let a of i){let i=t[a];if(i){if(i instanceof WebGLTexture){let t=e._attachmentLevel[a]??0,o=i._levelWidth[t]??0,s=i._levelHeight[t]??0;if(o>0&&s>0){n=o,r=s;break}}else if(i instanceof WebGLRenderbuffer&&i._width>0&&i._height>0){n=i._width,r=i._height;break}}}return n>0&&r>0?(e._width=n,e._height=r,this.FRAMEBUFFER_COMPLETE):this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT}_updateFramebufferAttachments(e){if(super._updateFramebufferAttachments(e),e)for(let t=1;t<=15;t++){let n=36064+t;if(!(n in e._attachments))continue;let r=e._attachments[n];if(r instanceof WebGLTexture){let t=e._attachmentFace[n]||this.TEXTURE_2D,i=e._attachmentLevel[n]??0;this._gl.framebufferTexture2D(this.FRAMEBUFFER,n,t,r._|0,i|0)}else r instanceof WebGLRenderbuffer?this._gl.framebufferRenderbuffer(this.FRAMEBUFFER,n,this.RENDERBUFFER,r._|0):this._gl.framebufferTexture2D(this.FRAMEBUFFER,n,this.TEXTURE_2D,0,0)}}bindBuffer(e,t){if(e===35345||e===35982||e===36662||e===36663){let n=t?t._|0:0;this._gl.bindBuffer(e,n);return}super.bindBuffer(e,t)}bindFramebuffer(e,t){if(e===36008||e===36009){if(!checkObject(t))throw TypeError(`bindFramebuffer(GLenum, WebGLFramebuffer)`);if(t&&t._pendingDelete||t&&!this._checkWrapper(t,WebGLFramebuffer))return;let n=t?t._|0:this._gtkFboId;if(this._gl.bindFramebuffer(e,n),e===36008){let e=this._activeReadFramebuffer;e!==t&&(e&&(--e._refCount,e._checkDelete()),t&&(t._refCount+=1)),this._activeReadFramebuffer=t}else{let e=this._activeDrawFramebuffer;e!==t&&(e&&(--e._refCount,e._checkDelete()),t&&(t._refCount+=1)),this._activeDrawFramebuffer=t,this._activeFramebuffer=t}return}super.bindFramebuffer(this.FRAMEBUFFER,t),this._activeReadFramebuffer=t,this._activeDrawFramebuffer=t}deleteFramebuffer(e){this._activeReadFramebuffer===e&&this.bindFramebuffer(36008,null),this._activeDrawFramebuffer===e&&this.bindFramebuffer(36009,null),super.deleteFramebuffer(e)}bufferData(e,t,n){let r=e===35345||e===35982||e===36662||e===36663,i=n===35041||n===35043||n===35045||n===35042||n===35044||n===35046?this.STATIC_DRAW:n;if(r){if(typeof t==`number`)t>=0&&this._gl.bufferDataSizeOnly(e,t,i);else if(typeof t==`object`&&t){let n=arrayToUint8Array(t);this._gl.bufferData(e,Uint8ArrayToVariant(n),i)}return}super.bufferData(e,t,i)}bufferSubData(e,t,n){if(e===35345||e===35982||e===36662||e===36663){if(t<0){this.setError(this.INVALID_VALUE);return}if(!n){this.setError(this.INVALID_VALUE);return}let r=arrayToUint8Array(n);this._gl.bufferSubData(e,t,Uint8ArrayToVariant(r));return}super.bufferSubData(e,t,n)}bindTexture(e,t){if(e===32879||e===35866){let n=t,r=n?n._|0:0;this._gl.bindTexture(e,r),n&&(n._binding=e);return}super.bindTexture(e,t)}texParameteri(e,t,n){if(e===32879||e===35866){this._gl.texParameteri(e,t,n);return}if(t===32882||t===34892||t===34893||t===33084||t===33085||t===33083||t===33082){this._gl.texParameteri(e,t,n);return}super.texParameteri(e,t,n)}drawArrays(e,t,n){if(t<0||n<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let r=vertexCount(this,e,n);if(r<0){this.setError(this.INVALID_ENUM);return}this._framebufferOk()&&n!==0&&this._checkVertexAttribState(n+t-1>>>0)&&this._native2.drawArrays(e,t,r)}drawElements(e=0,t=0,n=0,r=0){if(t<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let i=this._vertexObjectState._elementArrayBufferBinding;if(!i){this.setError(this.INVALID_OPERATION);return}let a=null,o=r;if(n===this.UNSIGNED_SHORT){if(o%2){this.setError(this.INVALID_OPERATION);return}o>>=1,a=new Uint16Array(i._elements.buffer)}else if(n===this.UNSIGNED_INT){if(o%4){this.setError(this.INVALID_OPERATION);return}o>>=2,a=new Uint32Array(i._elements.buffer)}else if(n===this.UNSIGNED_BYTE)a=i._elements;else{this.setError(this.INVALID_ENUM);return}let s=t;switch(e){case this.TRIANGLES:t%3&&(s-=t%3);break;case this.LINES:t%2&&(s-=t%2);break;case this.POINTS:break;case this.LINE_LOOP:case this.LINE_STRIP:if(t<2){this.setError(this.INVALID_OPERATION);return}break;case this.TRIANGLE_FAN:case this.TRIANGLE_STRIP:if(t<3){this.setError(this.INVALID_OPERATION);return}break;default:this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk()||t===0)return;let c=0;for(let e=o;e<o+s;++e)e<a.length&&a[e]>c&&(c=a[e]);this._checkVertexAttribState(c)&&this._native2.drawElements(e,s,n,r)}bindBufferBase(e,t,n){this._native2.bindBufferBase(e,t,n?n._:0)}bindBufferRange(e,t,n,r,i){this._native2.bindBufferRange(e,t,n?n._:0,r,i)}copyBufferSubData(e,t,n,r,i){this._native2.copyBufferSubData(e,t,n,r,i)}getBufferSubData(e,t,n,r,i){let a=i===void 0?n.byteLength-(r??0):i,o=this._native2.getBufferSubData(e,t,a),s=new Uint8Array(n.buffer,n.byteOffset+(r??0)*(n instanceof Uint8Array?1:n.BYTES_PER_ELEMENT??1));s.set(o.subarray(0,s.byteLength))}texImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0,c){let l=0,u=0,d=0,f=0;if(arguments.length===6)if(s=i,d=r,a instanceof St.Pixbuf){let e=a;l=e.get_width(),u=e.get_height(),c=e.get_pixels()}else{let e=extractImageData(a);if(e==null)throw TypeError(`texImage2D(GLenum, GLint, GLenum, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)`);l=e.width,u=e.height,c=e.data}else arguments.length>=9&&(l=r,u=i,f=a,d=o);let p=this._getTexImage(e);if(!p){this.setError(this.INVALID_OPERATION);return}let m=convertPixels(c);if(this._unpackPremultAlpha&&m&&d===this.RGBA&&(m=premultiplyAlpha(m)),this._unpackFlipY&&m&&l>0&&u>0){let e=this._computePixelSize(s,d);if(e>0){let t=this._computeRowStride(l,e),n=new Uint8Array(m.length);for(let e=0;e<u;e++){let r=e*t,i=(u-1-e)*t;n.set(m.subarray(r,r+t),i)}m=n}}this._saveError(),this._gl.texImage2D(e,t,n,l,u,f,d,s,Uint8ArrayToVariant(m));let h=this.getError();if(this._restoreError(h),h!==this.NO_ERROR)return;p._levelWidth[t]=l,p._levelHeight[t]=u,p._format=d,p._type=s;let g=this._activeFramebuffer;if(g){let e=!1,t=this._getAttachments();for(let n=0;n<t.length;++n)if(g._attachments[t[n]]===p){e=!0;break}e&&this._activeFramebuffer&&this._updateFramebufferAttachments(this._activeFramebuffer)}}texSubImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0,c){let l=0,u=0,d=0;if(arguments.length===7)if(s=a,d=i,o instanceof St.Pixbuf){let e=o;l=e.get_width(),u=e.get_height(),c=e.get_pixels()}else{let e=extractImageData(o);if(e==null)throw TypeError(`texSubImage2D(GLenum, GLint, GLint, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)`);l=e.width,u=e.height,c=e.data}else l=i,u=a,d=o;if(!this._getTexImage(e)){this.setError(this.INVALID_OPERATION);return}let f=convertPixels(c);if(!f){this.setError(this.INVALID_OPERATION);return}if(this._unpackPremultAlpha&&f&&d===this.RGBA&&(f=premultiplyAlpha(f)),this._unpackFlipY&&f&&l>0&&u>0){let e=this._computePixelSize(s,d);if(e>0){let t=this._computeRowStride(l,e),n=new Uint8Array(f.length);for(let e=0;e<u;e++){let r=e*t,i=(u-1-e)*t;n.set(f.subarray(r,r+t),i)}f=n}}this._gl.texSubImage2D(e,t,n,r,l,u,d,s,Uint8ArrayToVariant(f))}getUniform(e,t){let n=t?._activeInfo?.type,r=5125,i=36294,a=36295,o=n===r||n===i||n===a||n===36296,s=e;if(!o)return super.getUniform(s,t);if(!e||!t)return null;let c=this._native2.getUniformi(s._|0,t._|0);return c?n===r?c[0]>>>0:n===i?new Uint32Array([c[0]>>>0,c[1]>>>0]):n===a?new Uint32Array([c[0]>>>0,c[1]>>>0,c[2]>>>0]):new Uint32Array([c[0]>>>0,c[1]>>>0,c[2]>>>0,c[3]>>>0]):null}getUniformBlockIndex(e,t){return this._native2.getUniformBlockIndex(e._,t)}uniformBlockBinding(e,t,n){this._native2.uniformBlockBinding(e._,t,n)}getActiveUniformBlockName(e,t){let n=this._native2.getActiveUniformBlockName(e._,t);return n.length>0?n:null}getActiveUniformBlockParameter(e,t,n){return this._native2.getActiveUniformBlockParameter(e._,t,n)}getActiveUniforms(e,t,n){return this._native2.getActiveUniforms(e._,t,n)}getFragDataLocation(e,t){return this._native2.getFragDataLocation(e._,t)}getIndexedParameter(e,t){return this._native2.getIndexedParameteri(e,t)}getInternalformatParameter(e,t,n){return this._native2.getInternalformatParameter(e,t,n)}getParameter(e){if(e===7938)return`WebGL 2.0`;if(e===35724)return`WebGL GLSL ES 3.00`;if(e===7939)return warnNotImplemented(`WebGL2RenderingContext.getParameter(GL_EXTENSIONS)`),``;if(e===36006)return this._activeDrawFramebuffer;if(e===36010)return this._activeReadFramebuffer;switch(e){case 36183:case 35071:case 32883:case 36063:case 34852:case 36203:case 33001:case 33e3:case 37157:case 35373:case 35657:case 35077:case 35978:case 35979:case 35968:case 35376:case 35375:case 35659:case 37154:case 35371:case 35658:case 35379:case 35374:case 35377:case 35076:case 3330:case 3332:case 3331:case 35053:case 35055:case 3074:case 32874:case 35869:case 36389:case 35983:case 35368:case 35380:case 32878:case 3314:case 32877:case 3316:case 3315:case 34045:return this._native2.getParameterx(e)?.deepUnpack()|0;case 35977:case 36388:case 36387:return!!this._native2.getParameterx(e)?.deepUnpack()}return super.getParameter(e)}getStringi(e,t){let n=this._native2.getStringi(e,t);return n.length>0?n:null}renderbufferStorage(e,t,n,r){if(e!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}let i=this._activeRenderbuffer;if(!i){this.setError(this.INVALID_OPERATION);return}if(n<0||r<0){this.setError(this.INVALID_VALUE);return}for(;this._gl.getError()!==this.NO_ERROR;);if(this._gl.renderbufferStorage(e,t,n,r),this._gl.getError()!==this.NO_ERROR)return;i._width=n,i._height=r,i._format=t;let a=this._activeFramebuffer;if(a){let e=this._getAttachments(),t=!1;for(let n=0;n<e.length;++n)if(a._attachments[e[n]]===i){t=!0;break}t&&this._updateFramebufferAttachments(a)}}getSupportedExtensions(){let e=super.getSupportedExtensions();for(let t of[`EXT_color_buffer_float`,`EXT_color_buffer_half_float`,`OES_texture_half_float`])e.indexOf(t)===-1&&e.push(t);return e}readPixels(e,t,n,r,i,a,o){if(!o)return;if(n<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._framebufferOk())return;let s=i===6408||i===32856?4:i===6407?3:i===33319?2:1,c=a===5126?4:a===5131||a===36193?2:a===5125||a===5124?4:a===5123||a===5122?2:1,l=n*r*s*c,u=new Uint8Array(l);this._saveError();let d=this._gl.readPixels(e,t,n,r,i,a,Uint8ArrayToVariant(u)),f=this.getError();if(this._restoreError(f),f!==this.NO_ERROR)return;let p=d&&d.length>0?d:u;if(o instanceof Uint8Array)o.set(p);else if(o instanceof Float32Array){let e=new Float32Array(p.buffer,0,o.length);o.set(e)}}_framebufferOk(){return!0}};installObjectLifecycleMethods(cr.prototype),installTexImage3DMethods(cr.prototype),installUniformMethods(cr.prototype),installClearBufferMethods(cr.prototype),installInstancedAndFramebufferOpsMethods(cr.prototype);function notifyElementResize(e,t,n){e._allocatedClientWidth=t,e._allocatedClientHeight=n,e._fireResizeSubscribers(t,n);let r=e.parentNode;for(;r;)r instanceof Element&&(r._allocatedClientWidth=t,r._allocatedClientHeight=n,r._fireResizeSubscribers(t,n)),r=r.parentNode}var HTMLCanvasElement$1=class extends P{static{__name$1(this,`HTMLCanvasElement`)}constructor(e){super(),this.gtkGlArea=e}get width(){return this.gtkGlArea.get_allocated_width()}set width(e){}get height(){return this.gtkGlArea.get_allocated_height()}set height(e){}get clientWidth(){return this.width}get clientHeight(){return this.height}get offsetWidth(){return this.width}get offsetHeight(){return this.height}getGlArea(){return this.gtkGlArea}getContext(e,t){return e===`webgl`||e===`experimental-webgl`?(this._webgl||=(this.gtkGlArea.make_current(),new WebGLRenderingContext$1(this,t)),this._webgl):e===`webgl2`?(this._webgl2||=(this.gtkGlArea.make_current(),new cr(this,t)),this._webgl2):super.getContext(e,t)}};const lr=e(import.meta.url);let ur;function load(){return ur===void 0&&(ur=lr(`@gjsify/node-gi/gi`).requireGi(`GObject`)),ur}var dr=new Proxy(Object.create(null),{get(e,t){return load()[t]},has(e,t){return t in load()}});const fr={Return:`Enter`,KP_Enter:`Enter`,Tab:`Tab`,ISO_Left_Tab:`Tab`,BackSpace:`Backspace`,Escape:`Escape`,Delete:`Delete`,KP_Delete:`Delete`,Insert:`Insert`,KP_Insert:`Insert`,Home:`Home`,KP_Home:`Home`,End:`End`,KP_End:`End`,Page_Up:`PageUp`,KP_Page_Up:`PageUp`,Page_Down:`PageDown`,KP_Page_Down:`PageDown`,Left:`ArrowLeft`,KP_Left:`ArrowLeft`,Up:`ArrowUp`,KP_Up:`ArrowUp`,Right:`ArrowRight`,KP_Right:`ArrowRight`,Down:`ArrowDown`,KP_Down:`ArrowDown`,Shift_L:`Shift`,Shift_R:`Shift`,Control_L:`Control`,Control_R:`Control`,Alt_L:`Alt`,Alt_R:`Alt`,Super_L:`Meta`,Super_R:`Meta`,Meta_L:`Meta`,Meta_R:`Meta`,Caps_Lock:`CapsLock`,Num_Lock:`NumLock`,Scroll_Lock:`ScrollLock`,Print:`PrintScreen`,Pause:`Pause`,Menu:`ContextMenu`,space:` `,F1:`F1`,F2:`F2`,F3:`F3`,F4:`F4`,F5:`F5`,F6:`F6`,F7:`F7`,F8:`F8`,F9:`F9`,F10:`F10`,F11:`F11`,F12:`F12`,KP_Add:`+`,KP_Subtract:`-`,KP_Multiply:`*`,KP_Divide:`/`,KP_Decimal:`.`,KP_Separator:`,`,KP_0:`0`,KP_1:`1`,KP_2:`2`,KP_3:`3`,KP_4:`4`,KP_5:`5`,KP_6:`6`,KP_7:`7`,KP_8:`8`,KP_9:`9`},pr={Return:`Enter`,KP_Enter:`NumpadEnter`,Tab:`Tab`,ISO_Left_Tab:`Tab`,BackSpace:`Backspace`,Escape:`Escape`,Delete:`Delete`,KP_Delete:`NumpadDecimal`,Insert:`Insert`,KP_Insert:`Numpad0`,Home:`Home`,KP_Home:`Numpad7`,End:`End`,KP_End:`Numpad1`,Page_Up:`PageUp`,KP_Page_Up:`Numpad9`,Page_Down:`PageDown`,KP_Page_Down:`Numpad3`,Left:`ArrowLeft`,KP_Left:`Numpad4`,Up:`ArrowUp`,KP_Up:`Numpad8`,Right:`ArrowRight`,KP_Right:`Numpad6`,Down:`ArrowDown`,KP_Down:`Numpad2`,Shift_L:`ShiftLeft`,Shift_R:`ShiftRight`,Control_L:`ControlLeft`,Control_R:`ControlRight`,Alt_L:`AltLeft`,Alt_R:`AltRight`,Super_L:`MetaLeft`,Super_R:`MetaRight`,Meta_L:`MetaLeft`,Meta_R:`MetaRight`,Caps_Lock:`CapsLock`,Num_Lock:`NumLock`,Scroll_Lock:`ScrollLock`,Print:`PrintScreen`,Pause:`Pause`,Menu:`ContextMenu`,space:`Space`,F1:`F1`,F2:`F2`,F3:`F3`,F4:`F4`,F5:`F5`,F6:`F6`,F7:`F7`,F8:`F8`,F9:`F9`,F10:`F10`,F11:`F11`,F12:`F12`,KP_Add:`NumpadAdd`,KP_Subtract:`NumpadSubtract`,KP_Multiply:`NumpadMultiply`,KP_Divide:`NumpadDivide`,KP_Decimal:`NumpadDecimal`,KP_Separator:`NumpadComma`,KP_0:`Numpad0`,KP_1:`Numpad1`,KP_2:`Numpad2`,KP_3:`Numpad3`,KP_4:`Numpad4`,KP_5:`Numpad5`,KP_6:`Numpad6`,KP_7:`Numpad7`,KP_8:`Numpad8`,KP_9:`Numpad9`};function gdkKeyvalToKey(e){let t=it.keyval_name(e);if(t&&fr[t])return fr[t];let n=it.keyval_to_unicode(e);return n>0?String.fromCodePoint(n):t??`Unidentified`}function gdkKeyvalToCode(e){let t=it.keyval_name(e);if(t&&pr[t])return pr[t];let n=it.keyval_to_unicode(e);if(n>=97&&n<=122)return`Key`+String.fromCodePoint(n-32);if(n>=65&&n<=90)return`Key`+String.fromCodePoint(n);if(n>=48&&n<=57)return`Digit`+String.fromCodePoint(n);if(t){let e={minus:`Minus`,equal:`Equal`,bracketleft:`BracketLeft`,bracketright:`BracketRight`,backslash:`Backslash`,semicolon:`Semicolon`,apostrophe:`Quote`,grave:`Backquote`,comma:`Comma`,period:`Period`,slash:`Slash`};if(e[t])return e[t]}return t??`Unidentified`}function gdkKeyvalToLocation(e){let t=it.keyval_name(e);return t?t.startsWith(`KP_`)?3:t.endsWith(`_L`)?1:t.endsWith(`_R`)?2:0:0}function getGlobalEventTarget(){return globalThis.__gjsify_globalEventTarget}function extractModifiers(e){let t=e.get_current_event_state();return{shiftKey:!!(t&it.ModifierType.SHIFT_MASK),ctrlKey:!!(t&it.ModifierType.CONTROL_MASK),altKey:!!(t&it.ModifierType.ALT_MASK),metaKey:!!(t&it.ModifierType.SUPER_MASK)}}function gtkButtonToDom(e){return e===1?0:e===2?1:e===3?2:e-1}function buttonsFromModifiers(e){let t=e.get_current_event_state(),n=0;return t&it.ModifierType.BUTTON1_MASK&&(n|=1),t&it.ModifierType.BUTTON3_MASK&&(n|=2),t&it.ModifierType.BUTTON2_MASK&&(n|=4),n}function attachEventControllers(e,t,n){e.set_focusable(!0),e.set_can_focus(!0);let r={lastX:0,lastY:0,buttonsPressed:0,pressedKeys:new Set},i=new yn.EventControllerMotion;i.connect(`motion`,(n,a,o)=>{let s=t();if(!s)return;let c=e.get_allocated_width(),l=e.get_allocated_height(),u=Math.max(0,Math.min(a,c)),d=Math.max(0,Math.min(o,l)),f=u-r.lastX,p=d-r.lastY,m=extractModifiers(i),h=buttonsFromModifiers(i),g={...m,clientX:u,clientY:d,offsetX:u,offsetY:d,screenX:u,screenY:d,movementX:f,movementY:p,buttons:h,button:0,bubbles:!0,cancelable:!0};s.dispatchEvent(new PointerEvent(`pointermove`,{...g,pointerId:1,pointerType:`mouse`,isPrimary:!0})),s.dispatchEvent(new MouseEvent(`mousemove`,g)),r.lastX=u,r.lastY=d}),i.connect(`enter`,(e,n,a)=>{let o=t();if(!o)return;r.lastX=n,r.lastY=a;let s={...extractModifiers(i),clientX:n,clientY:a,offsetX:n,offsetY:a,screenX:n,screenY:a,bubbles:!1,cancelable:!1};o.dispatchEvent(new PointerEvent(`pointerenter`,{...s,pointerId:1,pointerType:`mouse`,isPrimary:!0})),o.dispatchEvent(new MouseEvent(`mouseenter`,s)),o.dispatchEvent(new MouseEvent(`mouseover`,{...s,bubbles:!0}))}),i.connect(`leave`,()=>{let e=t();if(!e)return;let n={...extractModifiers(i),clientX:r.lastX,clientY:r.lastY,bubbles:!1,cancelable:!1};e.dispatchEvent(new PointerEvent(`pointerleave`,{...n,pointerId:1,pointerType:`mouse`,isPrimary:!0})),e.dispatchEvent(new MouseEvent(`mouseleave`,n)),e.dispatchEvent(new MouseEvent(`mouseout`,{...n,bubbles:!0}))}),e.add_controller(i);let a=new yn.GestureClick;a.set_button(0),a.connect(`pressed`,(n,i,o,s)=>{let c=t();if(!c)return;let l=gtkButtonToDom(a.get_current_button()),u=extractModifiers(a);r.buttonsPressed|=1<<l;let d={...u,clientX:o,clientY:s,offsetX:o,offsetY:s,screenX:o,screenY:s,button:l,buttons:r.buttonsPressed,detail:i,bubbles:!0,cancelable:!0};c.dispatchEvent(new PointerEvent(`pointerdown`,{...d,pointerId:1,pointerType:`mouse`,isPrimary:!0})),c.dispatchEvent(new MouseEvent(`mousedown`,d)),e.grab_focus()}),a.connect(`released`,(e,n,i,o)=>{let s=t();if(!s)return;let c=gtkButtonToDom(a.get_current_button()),l=extractModifiers(a);r.buttonsPressed&=~(1<<c);let u={...l,clientX:i,clientY:o,offsetX:i,offsetY:o,screenX:i,screenY:o,button:c,buttons:r.buttonsPressed,detail:n,bubbles:!0,cancelable:!0};s.dispatchEvent(new PointerEvent(`pointerup`,{...u,pointerId:1,pointerType:`mouse`,isPrimary:!0})),s.dispatchEvent(new MouseEvent(`mouseup`,u)),c===0&&(s.dispatchEvent(new MouseEvent(`click`,u)),n===2&&s.dispatchEvent(new MouseEvent(`dblclick`,u))),c===2&&s.dispatchEvent(new MouseEvent(`contextmenu`,{...u,cancelable:!0}))}),e.add_controller(a);let o=new yn.EventControllerScroll({flags:yn.EventControllerScrollFlags.BOTH_AXES});o.connect(`scroll`,(e,n,i)=>{let a=t();if(!a)return;let s={...extractModifiers(o),clientX:r.lastX,clientY:r.lastY,offsetX:r.lastX,offsetY:r.lastY,screenX:r.lastX,screenY:r.lastY,deltaX:n*100,deltaY:i*100,deltaZ:0,deltaMode:0,bubbles:!0,cancelable:!0};return a.dispatchEvent(new WheelEvent(`wheel`,s)),!1}),e.add_controller(o);let s=new yn.EventControllerKey;s.connect(`key-pressed`,(e,i,a,o)=>{let s=t();if(!s)return!1;let c=r.pressedKeys.has(i);r.pressedKeys.add(i);let l=gdkKeyvalToKey(i),u={key:l,code:gdkKeyvalToCode(i),location:gdkKeyvalToLocation(i),repeat:c,altKey:!!(o&it.ModifierType.ALT_MASK),ctrlKey:!!(o&it.ModifierType.CONTROL_MASK),metaKey:!!(o&it.ModifierType.SUPER_MASK),shiftKey:!!(o&it.ModifierType.SHIFT_MASK),keyCode:l.length===1?l.toUpperCase().charCodeAt(0):0,which:l.length===1?l.toUpperCase().charCodeAt(0):0,bubbles:!0,cancelable:!0},d=new KeyboardEvent(`keydown`,u);return s.dispatchEvent(d),getGlobalEventTarget()?.dispatchEvent(new KeyboardEvent(`keydown`,u)),n?.captureKeys===!0}),s.connect(`key-released`,(e,n,i,a)=>{let o=t();if(!o)return;r.pressedKeys.delete(n);let s=gdkKeyvalToKey(n),c={key:s,code:gdkKeyvalToCode(n),location:gdkKeyvalToLocation(n),repeat:!1,altKey:!!(a&it.ModifierType.ALT_MASK),ctrlKey:!!(a&it.ModifierType.CONTROL_MASK),metaKey:!!(a&it.ModifierType.SUPER_MASK),shiftKey:!!(a&it.ModifierType.SHIFT_MASK),keyCode:s.length===1?s.toUpperCase().charCodeAt(0):0,which:s.length===1?s.toUpperCase().charCodeAt(0):0,bubbles:!0,cancelable:!0};o.dispatchEvent(new KeyboardEvent(`keyup`,c)),getGlobalEventTarget()?.dispatchEvent(new KeyboardEvent(`keyup`,c))}),e.add_controller(s);let c=new yn.EventControllerFocus;c.connect(`enter`,()=>{let e=t();e&&(e.dispatchEvent(new FocusEvent(`focus`,{bubbles:!1,cancelable:!1})),e.dispatchEvent(new FocusEvent(`focusin`,{bubbles:!0,cancelable:!1})))}),c.connect(`leave`,()=>{let e=t();e&&(r.pressedKeys.clear(),e.dispatchEvent(new FocusEvent(`blur`,{bubbles:!1,cancelable:!1})),e.dispatchEvent(new FocusEvent(`focusout`,{bubbles:!0,cancelable:!1})),getGlobalEventTarget()?.dispatchEvent(new FocusEvent(`blur`,{bubbles:!1,cancelable:!1})))}),e.add_controller(c)}const mr=dr.registerClass({GTypeName:`GjsifyWebGLBridge`},class WebGLBridge extends yn.GLArea{constructor(e){super(e),this._canvas=null,this._readyCallbacks=[],this._resizeCallbacks=[],this._renderTag=null,this._tickCallbackId=null,this._frameCallback=null,this._lastFrameCallback=null,this._lastFrameTime=0,this._replaying=!1,this._frameCallbackId=0,this._nextFrameId=1,this._timeOrigin=mt.get_monotonic_time(),this.set_use_es(!0),this.set_required_version(3,2),this.set_has_depth_buffer(!0),this.set_has_stencil_buffer(!0),attachEventControllers(this,()=>this._canvas,{captureKeys:!0}),this._tickCallbackId=this.add_tick_callback((e,t)=>(this._frameCallback!==null&&this.queue_render(),mt.SOURCE_CONTINUE));let t=this.connect(`render`,()=>{this.disconnect(t),this.make_current(),this._canvas=new HTMLCanvasElement$1(this);{let e=globalThis;e.document?.body&&e.document.body.appendChild(this._canvas)}this._canvas.getContext(`webgl2`);let e=this._canvas.getContext(`webgl`);if(e){for(let t of this._readyCallbacks)t(this._canvas,e);this._readyCallbacks=[]}return this._renderTag=this.connect(`render`,e=>{let t=(mt.get_monotonic_time()-this._timeOrigin)/1e3;if(this._frameCallback!==null){globalThis.__GJSIFY_DEBUG_RAF===!0&&console.log(`[rAF] frame callback fires t=${t.toFixed(1)}`);let e=this._frameCallback;this._frameCallback=null,this._frameCallbackId=0,this._lastFrameCallback=e,this._lastFrameTime=t,e(t)}else if(this._lastFrameCallback!==null){this._replaying=!0;try{this._lastFrameCallback(this._lastFrameTime)}finally{this._replaying=!1}}return!0}),!0});this.connect(`resize`,()=>{let e=this.get_allocated_width(),t=this.get_allocated_height();this._canvas&&(this._canvas.dispatchEvent(new Event(`resize`)),notifyElementResize(this._canvas,e,t));for(let n of this._resizeCallbacks)n(e,t);this._frameCallback&&this.requestAnimationFrame(this._frameCallback)}),this.connect(`unrealize`,()=>{this._renderTag!==null&&(this.disconnect(this._renderTag),this._renderTag=null),this._tickCallbackId!==null&&(this.remove_tick_callback(this._tickCallbackId),this._tickCallbackId=null),this._frameCallback=null,this._lastFrameCallback=null,this._lastFrameTime=0,this._replaying=!1,this._canvas=null})}get canvas(){return this._canvas}onReady(e){if(this._canvas){let t=this._canvas.getContext(`webgl`);if(t){e(this._canvas,t);return}}this._readyCallbacks.push(e)}onWebGLReady(e){this.onReady(e)}onResize(e){this._resizeCallbacks.push(e)}requestAnimationFrame(e){let t=this._nextFrameId++;return this._replaying?t:(this._frameCallback=e,this._frameCallbackId=t,this.queue_render(),t)}cancelAnimationFrame(e){e!==0&&e===this._frameCallbackId&&(this._frameCallback=null,this._frameCallbackId=0,this._lastFrameCallback=null,this._lastFrameTime=0)}installGlobals(){let e=globalThis;e.requestAnimationFrame=e=>this.requestAnimationFrame(e),e.cancelAnimationFrame=e=>this.cancelAnimationFrame(e),e.WebGLRenderingContext=WebGLRenderingContext$1,e.WebGL2RenderingContext=cr;let t=this._timeOrigin;e.performance={now:()=>(mt.get_monotonic_time()-t)/1e3,timeOrigin:Date.now()}}});globalThis.imports
77
+ `+r+t:r&&(t=r+t)}else r&&(t=r+t);return t}};function installShaderLifecycleMethods(e){Object.assign(e,Jn)}const Yn={createProgram(){let e=this._gl.createProgram();if(e<=0)return null;let t=new WebGLProgram$1(e,this);return this._programs[e]=t,t},deleteProgram(e){this._deleteLinkable(`deleteProgram`,e,WebGLProgram$1)},useProgram(e){if(!checkObject(e))throw TypeError(`useProgram(WebGLProgram)`);if(e)this._checkWrapper(e,WebGLProgram$1)&&(this._activeProgram!==e&&(this._switchActiveProgram(this._activeProgram),this._activeProgram=e,e._refCount+=1),this._gl.useProgram(e._|0));else{this._switchActiveProgram(this._activeProgram),this._activeProgram=null,this._gl.useProgram(0);return}},linkProgram(e){if(!checkObject(e))throw TypeError(`linkProgram(WebGLProgram)`);if(this._checkWrapper(e,WebGLProgram$1)){e._linkCount+=1,e._attributes=[];let t=this.getError();for(let t of e._references)t instanceof WebGLShader$1&&t._needsRecompile&&(this._gl.compileShader(t._|0),t._needsRecompile=!1);this._gl.linkProgram(e._|0);let n=this.getError();n===this.NO_ERROR&&(e._linkStatus=this._fixupLink(e)),this.getError(),this.setError(t||n)}},validateProgram(e){if(this._checkWrapper(e,WebGLProgram$1)){this._gl.validateProgram(e._|0);let t=this.getError();t===this.NO_ERROR&&(e._linkInfoLog=this._gl.getProgramInfoLog(e._|0)),this.getError(),this.setError(t)}},attachShader(e,t){if(!checkObject(e)||!checkObject(t))throw TypeError(`attachShader(WebGLProgram, WebGLShader)`);if(!e||!t){this.setError(this.INVALID_VALUE);return}else if(e instanceof WebGLProgram$1&&t instanceof WebGLShader$1&&this._checkOwns(e)&&this._checkOwns(t)&&!e._linked(t)){this._saveError(),this._gl.attachShader(e._|0,t._|0);let n=this.getError();this._restoreError(n),n===this.NO_ERROR&&e._link(t);return}this.setError(this.INVALID_OPERATION)},detachShader(e,t){if(!checkObject(e)||!checkObject(t))throw TypeError(`detachShader(WebGLProgram, WebGLShader)`);this._checkWrapper(e,WebGLProgram$1)&&this._checkWrapper(t,WebGLShader$1)&&(e._linked(t)?(this._gl.detachShader(e._,t._),e._unlink(t)):this.setError(this.INVALID_OPERATION))},bindAttribLocation(e,t,n){if(!checkObject(e)||typeof n!=`string`)throw TypeError(`bindAttribLocation(WebGLProgram, GLint, String)`);n+=``,!isValidString(n)||n.length>256?this.setError(this.INVALID_VALUE):/^_?webgl_a/.test(n)?this.setError(this.INVALID_OPERATION):this._checkWrapper(e,WebGLProgram$1)&&this._gl.bindAttribLocation(e._|0,t|0,n)},getAttachedShaders(e){if(!checkObject(e)||typeof e==`object`&&e&&!(e instanceof WebGLProgram$1))throw TypeError(`getAttachedShaders(WebGLProgram)`);if(!e)this.setError(this.INVALID_VALUE);else if(this._checkWrapper(e,WebGLProgram$1))return e._references.filter(e=>e instanceof WebGLShader$1);return null},getProgramInfoLog(e){if(!checkObject(e))throw TypeError(`getProgramInfoLog(WebGLProgram)`);return this._checkWrapper(e,WebGLProgram$1)?e._linkInfoLog:null},getProgramParameter(e,t=0){if(!checkObject(e))throw TypeError(`getProgramParameter(WebGLProgram, GLenum)`);if(this._checkWrapper(e,WebGLProgram$1)){switch(t){case this.DELETE_STATUS:return e._pendingDelete;case this.LINK_STATUS:return e._linkStatus;case this.VALIDATE_STATUS:return!!this._gl.getProgramParameter(e._,t);case this.ATTACHED_SHADERS:return this._gl.getProgramParameter(e._,t);case this.ACTIVE_ATTRIBUTES:return e._linkStatus?e._attributes.length:this._gl.getProgramParameter(e._,t);case this.ACTIVE_UNIFORMS:return e._linkStatus?e._uniforms.length:this._gl.getProgramParameter(e._,t)}this.setError(this.INVALID_ENUM)}return null},_switchActiveProgram(e){e&&(--e._refCount,e._checkDelete())},_fixupLink(e){if(!this._gl.getProgramParameter(e._,this.LINK_STATUS))return e._linkInfoLog=this._gl.getProgramInfoLog(e._),!1;let t=this.getProgramParameter(e,this.ACTIVE_ATTRIBUTES),n=Array.from({length:t});e._attributes.length=t;for(let r=0;r<t;++r)n[r]=this.getActiveAttrib(e,r)?.name,e._attributes[r]=this.getAttribLocation(e,n[r])|0;for(let t=0;t<n.length;++t)if(n[t].length>256)return e._linkInfoLog=`attribute `+n[t]+` is too long`,!1;for(let r=0;r<t;++r)e._attributes[r]<0||this._gl.bindAttribLocation(e._|0,e._attributes[r],n[r]);if(this._gl.linkProgram(e._|0),!this._gl.getProgramParameter(e._|0,this.LINK_STATUS))return e._linkInfoLog=this._gl.getProgramInfoLog(e._),!1;let r=this.getProgramParameter(e,this.ACTIVE_UNIFORMS);e._uniforms.length=r;for(let t=0;t<r;++t){let n=this.getActiveUniform(e,t);n&&(e._uniforms[t]=n)}for(let t=0;t<e._uniforms.length;++t)if(e._uniforms[t].name.length>256)return e._linkInfoLog=`uniform `+e._uniforms[t].name+` is too long`,!1;return e._linkInfoLog=``,!0},_deleteLinkable(e,t,n){if(!checkObject(t))throw TypeError(e+`(`+n.name+`)`);if(t instanceof n&&this._checkOwns(t)){t._pendingDelete=!0,t._checkDelete();return}this.setError(this.INVALID_OPERATION)}};function installProgramLifecycleMethods(e){Object.assign(e,Yn)}const Xn={getActiveAttrib(e,t){if(!checkObject(e))throw TypeError(`getActiveAttrib(WebGLProgram)`);if(!e)throw TypeError(`getActiveAttrib(WebGLProgram, GLuint)`);if(this._checkWrapper(e,WebGLProgram$1)){if(t>=(e._linkStatus?e._attributes.length:this._gl.getProgramParameter(e._|0,this.ACTIVE_ATTRIBUTES)))return this._gl.getError(),this.setError(this.INVALID_VALUE),null;let n=this._gl.getActiveAttrib(e._|0,t|0);if(n)return new WebGLActiveInfo(n)}return null},getActiveUniform(e,t){if(!checkObject(e))throw TypeError(`getActiveUniform(WebGLProgram, GLint)`);if(!e)throw TypeError(`getActiveUniform(WebGLProgram, GLuint)`);if(this._checkWrapper(e,WebGLProgram$1)){if(t>=(e._linkStatus?e._uniforms.length:this._gl.getProgramParameter(e._|0,this.ACTIVE_UNIFORMS)))return this.setError(this.INVALID_VALUE),null;let n=this._gl.getActiveUniform(e._|0,t|0);if(n)return new WebGLActiveInfo(n)}return null},getAttribLocation(e,t){if(!checkObject(e))throw TypeError(`getAttribLocation(WebGLProgram, String)`);if(t+=``,!isValidString(t)||t.length>256)this.setError(this.INVALID_VALUE);else if(this._checkWrapper(e,WebGLProgram$1))return this._gl.getAttribLocation(e._|0,t+``);return-1},getUniform(e,t){if(!checkObject(e)||!checkObject(t))throw TypeError(`getUniform(WebGLProgram, WebGLUniformLocation)`);if(!e)return this.setError(this.INVALID_VALUE),null;if(!t)return null;if(this._checkWrapper(e,WebGLProgram$1)){if(!checkUniform(e,t))return this.setError(this.INVALID_OPERATION),null;let n=this._gl.getUniform(e._|0,t._|0);if(!n)return null;switch(t._activeInfo.type){case this.FLOAT:return n[0];case this.FLOAT_VEC2:return new Float32Array(n.slice(0,2));case this.FLOAT_VEC3:return new Float32Array(n.slice(0,3));case this.FLOAT_VEC4:return new Float32Array(n.slice(0,4));case this.INT:return n[0]|0;case this.INT_VEC2:return new Int32Array(n.slice(0,2));case this.INT_VEC3:return new Int32Array(n.slice(0,3));case this.INT_VEC4:return new Int32Array(n.slice(0,4));case this.BOOL:return!!n[0];case this.BOOL_VEC2:return[!!n[0],!!n[1]];case this.BOOL_VEC3:return[!!n[0],!!n[1],!!n[2]];case this.BOOL_VEC4:return[!!n[0],!!n[1],!!n[2],!!n[3]];case this.FLOAT_MAT2:return new Float32Array(n.slice(0,4));case this.FLOAT_MAT3:return new Float32Array(n.slice(0,9));case this.FLOAT_MAT4:return new Float32Array(n.slice(0,16));case this.SAMPLER_2D:case this.SAMPLER_CUBE:return n[0]|0;default:return null}}return null},getUniformLocation(e,t){if(!checkObject(e))throw TypeError(`getUniformLocation(WebGLProgram, String)`);if(t+=``,!isValidString(t))return this.setError(this.INVALID_VALUE),null;if(this._checkWrapper(e,WebGLProgram$1)){let n=this._gl.getUniformLocation(e._|0,t);if(n!==null&&n>=0){let r=t;/\[\d+\]$/.test(t)&&(r=t.replace(/\[\d+\]$/,`[0]`));let i=r+`[0]`,a=null;for(let t=0;t<e._uniforms.length;++t){let n=e._uniforms[t];if(n.name===r||n.name===i){a={size:n.size,type:n.type,name:n.name};break}}a||={name:r,type:0,size:1};let o=new WebGLUniformLocation(n,e,a),s=t.match(/\[(\d+)\]$/),c=s?+s[1]:-1;if(a.name.endsWith(`[0]`)&&(c===-1||c===0)){let t=a.name.replace(/\[0\]$/,``),n=[];this._saveError();for(let r=0;this.getError()===this.NO_ERROR;++r){let i=this._gl.getUniformLocation(e._|0,t+`[`+r+`]`);if(this.getError()!==this.NO_ERROR||i==null||i<0)break;n.push(i)}this._restoreError(this.NO_ERROR),o._array=n}else if(c>0&&c>=a.size)return null;return o}}return null}};function installIntrospectionMethods(e){Object.assign(e,Xn)}const Zn={uniform1f(e,t){this._checkUniformValid(e,t,`uniform1f`,1,`f`)&&this._gl.uniform1f(e?._||0,t)},uniform1i(e,t){this._gl.uniform1i(e?._||0,t)},uniform2f(e,t,n){this._checkUniformValid(e,t,`uniform2f`,2,`f`)&&this._gl.uniform2f(e?._||0,t,n)},uniform2i(e,t,n){this._checkUniformValid(e,t,`uniform2i`,2,`i`)&&this._gl.uniform2i(e?._||0,t,n)},uniform3f(e,t,n,r){this._checkUniformValid(e,t,`uniform3f`,3,`f`)&&this._gl.uniform3f(e?._||0,t,n,r)},uniform3i(e,t,n,r){this._checkUniformValid(e,t,`uniform3i`,3,`i`)&&this._gl.uniform3i(e?._||0,t,n,r)},uniform4f(e,t,n,r,i){if(!this._checkUniformValid(e,t,`uniform4f`,4,`f`)){console.error(`uniform4f is not valid!`);return}this._gl.uniform4f(e?._||0,t,n,r,i)},uniform4i(e,t,n,r,i){this._checkUniformValid(e,t,`uniform4i`,4,`i`)&&this._gl.uniform4i(e?._||0,t,n,r,i)},uniform1fv(e,t){if(!(!e||!this._checkUniformValueValid(e,t,`uniform1fv`,1,`f`))){if(e?._array){let n=e._array;for(let e=0;e<n.length&&e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform1f(r,t[e])}return}this._gl.uniform1f(e?._|0,t[0])}},uniform1iv(e,t){if(this._checkUniformValueValid(e,t,`uniform1iv`,1,`i`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform1i(r,t[e])}return}this.uniform1i(e,t[0])}},uniform2fv(e,t){if(this._checkUniformValueValid(e,t,`uniform2fv`,2,`f`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&2*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform2f(r,t[2*e],t[2*e+1])}return}this._gl.uniform2f(e?._||0,t[0],t[1])}},uniform2iv(e,t){if(this._checkUniformValueValid(e,t,`uniform2iv`,2,`i`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&2*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform2i(r,t[2*e],t[2*e+1])}return}this.uniform2i(e,t[0],t[1])}},uniform3fv(e,t){if(this._checkUniformValueValid(e,t,`uniform3fv`,3,`f`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&3*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform3f(r,t[3*e],t[3*e+1],t[3*e+2])}return}this._gl.uniform3f(e?._||0,t[0],t[1],t[2])}},uniform3iv(e,t){if(this._checkUniformValueValid(e,t,`uniform3iv`,3,`i`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&3*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform3i(r,t[3*e],t[3*e+1],t[3*e+2])}return}this.uniform3i(e,t[0],t[1],t[2])}},uniform4fv(e,t){if(this._checkUniformValueValid(e,t,`uniform4fv`,4,`f`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&4*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform4f(r,t[4*e],t[4*e+1],t[4*e+2],t[4*e+3])}return}this._gl.uniform4f(e?._||0,t[0],t[1],t[2],t[3])}},uniform4iv(e,t){if(this._checkUniformValueValid(e,t,`uniform4iv`,4,`i`)){if(e?._array){let n=e._array;for(let e=0;e<n.length&&4*e<t.length;++e){let r=n[e];r!=null&&this._gl.uniform4i(r,t[4*e],t[4*e+1],t[4*e+2],t[4*e+3])}return}this.uniform4i(e,t[0],t[1],t[2],t[3])}},uniformMatrix2fv(e,t,n){if(!this._checkUniformMatrix(e,t,n,`uniformMatrix2fv`,2))return;let r=new Float32Array(n);this._gl.uniformMatrix2fv(e?._||0,!!t,listToArray(r))},uniformMatrix3fv(e,t,n){if(!this._checkUniformMatrix(e,t,n,`uniformMatrix3fv`,3))return;let r=new Float32Array(n);this._gl.uniformMatrix3fv(e?._||0,!!t,listToArray(r))},uniformMatrix4fv(e,t,n){if(!this._checkUniformMatrix(e,t,n,`uniformMatrix4fv`,4))return;let r=new Float32Array(n);this._gl.uniformMatrix4fv(e?._||0,!!t,listToArray(r))},_checkLocation(e){return e instanceof WebGLUniformLocation?e._program._ctx!==this||e._linkCount!==e._program._linkCount?(this.setError(this.INVALID_OPERATION),!1):!0:(this.setError(this.INVALID_VALUE),!1)},_checkLocationActive(e){return e&&this._checkLocation(e)?e._program===this._activeProgram?!0:(this.setError(this.INVALID_OPERATION),!1):!1},_checkUniformValid(e,t,n,r,i){if(!checkObject(e))throw TypeError(`${n}(WebGLUniformLocation, ...)`);if(!e)return!1;if(this._checkLocationActive(e)){let n=e._activeInfo.type;if(n===this.SAMPLER_2D||n===this.SAMPLER_CUBE){if(r!==1)return this.setError(this.INVALID_VALUE),!1;if(i!==`i`)return this.setError(this.INVALID_OPERATION),!1;if(t<0||t>=this._textureUnits.length)return this.setError(this.INVALID_VALUE),!1}return uniformTypeSize(this,n)>r?(this.setError(this.INVALID_OPERATION),!1):!0}return!1},_checkUniformValueValid(e,t,n,r,i){if(!checkObject(e)||!checkObject(t))throw TypeError(`${n}v(WebGLUniformLocation, Array)`);if(!e||!this._checkLocationActive(e))return!1;if(typeof t!=`object`||!t||typeof t.length!=`number`)throw TypeError(`Second argument to ${n} must be array`);return uniformTypeSize(this,e._activeInfo.type)>r?(this.setError(this.INVALID_OPERATION),!1):t.length>=r&&t.length%r===0?e._array||t.length===r?!0:(this.setError(this.INVALID_OPERATION),!1):(this.setError(this.INVALID_VALUE),!1)},_checkUniformMatrix(e,t,n,r,i){if(!checkObject(e)||typeof n!=`object`)throw TypeError(r+`(WebGLUniformLocation, Boolean, Array)`);return t||typeof n!=`object`||!n||!n.length||n.length%i*i!==0?(this.setError(this.INVALID_VALUE),!1):!e||!this._checkLocationActive(e)?!1:n.length===i*i||e._array?!0:(this.setError(this.INVALID_VALUE),!1)}};function installUniformsMethods(e){Object.assign(e,Zn)}function installShaderProgramMethods(e){installShaderLifecycleMethods(e),installProgramLifecycleMethods(e),installIntrospectionMethods(e),installUniformsMethods(e)}function installAllContextMethods(e){installStateMethods(e),installBufferBindingMethods(e),installTextureManagementMethods(e),installFramebufferMethods(e),installShaderProgramMethods(e),installDrawingMethods(e)}const Qn=e(import.meta.url);let $n;function load$1(){return $n===void 0&&($n=Qn(`@gjsify/node-gi/gi`).requireGi(`Gwebgl`,`0.1`)),$n}__name$1(load$1,`load`);var er=new Proxy(Object.create(null),{get(e,t){return load$1()[t]},has(e,t){return t in load$1()}});let tr=0;const nr={oes_element_index_uint:getOESElementIndexUint,oes_texture_float:getOESTextureFloat,oes_texture_float_linear:getOESTextureFloatLinear,oes_standard_derivatives:getOESStandardDerivatives,stackgl_destroy_context:getSTACKGLDestroyContext,stackgl_resize_drawingbuffer:getSTACKGLResizeDrawingBuffer,ext_blend_minmax:getEXTBlendMinMax,ext_color_buffer_float:getEXTColorBufferFloat,ext_color_buffer_half_float:getEXTColorBufferHalfFloat,ext_texture_filter_anisotropic:getEXTTextureFilterAnisotropic,oes_texture_half_float:getOESTextureHalfFloat};var WebGLContextBase=class{get drawingBufferHeight(){return this.canvas.height||0}get drawingBufferWidth(){return this.canvas.width||0}constructor(e,t={}){this.drawingBufferColorSpace=`srgb`,this.unpackColorSpace=`srgb`,this.RGBA8=32856,this.DEFAULT_ATTACHMENTS=[],this.DEFAULT_COLOR_ATTACHMENTS=[],this._=0,this._extensions={},this._programs={},this._shaders={},this._textures={},this._framebuffers={},this._renderbuffers={},this._buffers={},this._activeProgram=null,this._activeFramebuffer=null,this._activeRenderbuffer=null,this._checkStencil=!1,this._stencilState=!0,this._activeTextureUnit=0,this._errorStack=[],this._maxTextureSize=0,this._maxTextureLevel=0,this._maxCubeMapSize=0,this._maxCubeMapLevel=0,this._maxRenderbufferSize=0,this._unpackAlignment=4,this._packAlignment=4,this._unpackFlipY=!1,this._unpackPremultAlpha=!1,this._viewport=new Int32Array([0,0,0,0]),this._scissorBox=new Int32Array([0,0,0,0]),this._gtkFboId=0,this._textureUnits=[],this._drawingBuffer=null,this.canvas=e,this._contextAttributes=new WebGLContextAttributes(flag(t,`alpha`,!0),flag(t,`depth`,!0),flag(t,`stencil`,!1),!1,flag(t,`premultipliedAlpha`,!0),flag(t,`preserveDrawingBuffer`,!1),flag(t,`preferLowPowerToHighPerformance`,!1),flag(t,`failIfMajorPerformanceCaveat`,!1)),this._contextAttributes.premultipliedAlpha=this._contextAttributes.premultipliedAlpha&&this._contextAttributes.alpha}_init(){let e=this._gl.getParameterx(36006);this._gtkFboId=e?.deepUnpack()|0,this._initGLConstants(),this.DEFAULT_ATTACHMENTS=[this.COLOR_ATTACHMENT0,this.DEPTH_ATTACHMENT,this.STENCIL_ATTACHMENT,this.DEPTH_STENCIL_ATTACHMENT],this.DEFAULT_COLOR_ATTACHMENTS=[this.COLOR_ATTACHMENT0];let t=this.drawingBufferWidth||0,n=this.drawingBufferHeight||0;this._=tr++;let r=this.getParameter(this.MAX_COMBINED_TEXTURE_IMAGE_UNITS);this._textureUnits=Array.from({length:r});for(let e=0;e<r;++e)this._textureUnits[e]=new WebGLTextureUnit(this,e);this.activeTexture(this.TEXTURE0),this._defaultVertexObjectState=new WebGLVertexArrayObjectState(this),this._vertexObjectState=this._defaultVertexObjectState,this._vertexGlobalState=new WebGLVertexArrayGlobalState(this),this._maxTextureSize=this.getParameter(this.MAX_TEXTURE_SIZE),this._maxTextureLevel=Ln.log2(Ln.nextPow2(this._maxTextureSize)),this._maxCubeMapSize=this.getParameter(this.MAX_CUBE_MAP_TEXTURE_SIZE),this._maxCubeMapLevel=Ln.log2(Ln.nextPow2(this._maxCubeMapSize)),this._maxRenderbufferSize=this.getParameter(this.MAX_RENDERBUFFER_SIZE),this._unpackAlignment=4,this._packAlignment=4,this._unpackFlipY=!1,this._unpackPremultAlpha=!1,this.bindBuffer(this.ARRAY_BUFFER,null),this.bindBuffer(this.ELEMENT_ARRAY_BUFFER,null),this.bindFramebuffer(this.FRAMEBUFFER,null),this.bindRenderbuffer(this.RENDERBUFFER,null),this.viewport(0,0,t,n),this.scissor(0,0,t,n),this.clearDepth(1),this.clearColor(0,0,0,0),this.clearStencil(0),this.clear(this.COLOR_BUFFER_BIT|this.DEPTH_BUFFER_BIT|this.STENCIL_BUFFER_BIT),this.disable(this.DEPTH_TEST),this.disable(this.STENCIL_TEST),this.disable(this.BLEND),this.disable(this.CULL_FACE),this.disable(this.POLYGON_OFFSET_FILL),this.disable(this.SCISSOR_TEST),this._gl.colorMask(!0,!0,!0,!0)}_initGLConstants(){let e=new er.WebGLRenderingContextBase().get_webgl_constants();for(let[t,n]of Object.entries(e))Object.defineProperty(this,t,{value:n})}_getGlslVersion(e){return e?`100`:`120`}_checkOwns(e){return typeof e==`object`&&!!e&&e._ctx===this}_checkValid(e,t){return e instanceof t&&e._!==0}_checkWrapper(e,t){return this._checkValid(e,t)?this._checkOwns(e)?!0:(this.setError(this.INVALID_OPERATION),!1):(this.setError(this.INVALID_VALUE),!1)}_isObject(e,t,n){if(e!=null&&!(e instanceof n))throw TypeError(t+`(`+n.name+`)`);return!!(this._checkValid(e,n)&&this._checkOwns(e))}_checkStencilState(){return this._checkStencil?(this._checkStencil=!1,this._stencilState=!0,(this.getParameter(this.STENCIL_WRITEMASK)!==this.getParameter(this.STENCIL_BACK_WRITEMASK)||this.getParameter(this.STENCIL_VALUE_MASK)!==this.getParameter(this.STENCIL_BACK_VALUE_MASK)||this.getParameter(this.STENCIL_REF)!==this.getParameter(this.STENCIL_BACK_REF))&&(this.setError(this.INVALID_OPERATION),this._stencilState=!1),this._stencilState):this._stencilState}_validGLSLIdentifier(e){return!(e.indexOf(`webgl_`)===0||e.indexOf(`_webgl_`)===0||e.length>256)}_getParameterDirect(e){return this._gl.getParameterx(e)?.deepUnpack()}getContextAttributes(){return this._contextAttributes}getExtension(e){let t=e.toLowerCase();if(t in this._extensions)return this._extensions[t];let n=nr[t]?nr[t](this):null;return n&&(this._extensions[t]=n),n}getSupportedExtensions(){let e=[`ANGLE_instanced_arrays`,`STACKGL_resize_drawingbuffer`,`STACKGL_destroy_context`],t=this._gl.getSupportedExtensions();return t?(t.indexOf(`GL_OES_element_index_uint`)>=0&&e.push(`OES_element_index_uint`),t.indexOf(`GL_OES_standard_derivatives`)>=0&&e.push(`OES_standard_derivatives`),t.indexOf(`GL_OES_texture_float`)>=0&&e.push(`OES_texture_float`),t.indexOf(`GL_OES_texture_float_linear`)>=0&&e.push(`OES_texture_float_linear`),(t.indexOf(`GL_OES_texture_half_float`)>=0||t.indexOf(`GL_ARB_half_float_pixel`)>=0)&&e.push(`OES_texture_half_float`),(t.indexOf(`GL_EXT_color_buffer_float`)>=0||t.indexOf(`GL_ARB_color_buffer_float`)>=0)&&e.push(`EXT_color_buffer_float`),t.indexOf(`GL_EXT_color_buffer_half_float`)>=0&&e.push(`EXT_color_buffer_half_float`),t.indexOf(`EXT_draw_buffers`)>=0&&e.push(`WEBGL_draw_buffers`),t.indexOf(`EXT_blend_minmax`)>=0&&e.push(`EXT_blend_minmax`),t.indexOf(`EXT_texture_filter_anisotropic`)>=0&&e.push(`EXT_texture_filter_anisotropic`),t.indexOf(`GL_OES_vertex_array_object`)>=0&&e.push(`OES_vertex_array_object`),e):e}getParameter(e=0){switch(e){case this.ARRAY_BUFFER_BINDING:return this._vertexGlobalState._arrayBufferBinding;case this.ELEMENT_ARRAY_BUFFER_BINDING:return this._vertexObjectState._elementArrayBufferBinding;case this.CURRENT_PROGRAM:return this._activeProgram;case this.FRAMEBUFFER_BINDING:return this._activeFramebuffer;case this.RENDERBUFFER_BINDING:return this._activeRenderbuffer;case this.TEXTURE_BINDING_2D:return this._getActiveTextureUnit()._bind2D;case this.TEXTURE_BINDING_CUBE_MAP:return this._getActiveTextureUnit()._bindCube;case this.VERSION:return`WebGL 1.0 0.0.1`;case this.VENDOR:return``;case this.RENDERER:return`ANGLE`;case this.SHADING_LANGUAGE_VERSION:return`WebGL GLSL ES 1.0 `;case this.COMPRESSED_TEXTURE_FORMATS:return new Uint32Array;case this.SCISSOR_BOX:return new Int32Array(this._scissorBox);case this.VIEWPORT:return new Int32Array(this._viewport);case this.MAX_VIEWPORT_DIMS:return new Int32Array([32767,32767]);case this.ALIASED_LINE_WIDTH_RANGE:case this.ALIASED_POINT_SIZE_RANGE:return new Float32Array([1,1]);case this.DEPTH_RANGE:return new Float32Array([0,1]);case this.BLEND_COLOR:case this.COLOR_CLEAR_VALUE:return new Float32Array(this._gl.getParameterfv(e,4));case this.COLOR_WRITEMASK:{let t=this._gl.getParameteriv(e,4);return[!!t[0],!!t[1],!!t[2],!!t[3]]}case this.DEPTH_CLEAR_VALUE:case this.LINE_WIDTH:case this.POLYGON_OFFSET_FACTOR:case this.POLYGON_OFFSET_UNITS:case this.SAMPLE_COVERAGE_VALUE:return this._gl.getParameterf(e);case this.BLEND:case this.CULL_FACE:case this.DEPTH_TEST:case this.DEPTH_WRITEMASK:case this.DITHER:case this.POLYGON_OFFSET_FILL:case this.SAMPLE_COVERAGE_INVERT:case this.SCISSOR_TEST:case this.STENCIL_TEST:case this.UNPACK_PREMULTIPLY_ALPHA_WEBGL:return!!this._gl.getParameteri(e);case this.UNPACK_FLIP_Y_WEBGL:return this._unpackFlipY;case this.ACTIVE_TEXTURE:case this.ALPHA_BITS:case this.BLEND_DST_ALPHA:case this.BLEND_DST_RGB:case this.BLEND_EQUATION_ALPHA:case this.BLEND_EQUATION_RGB:case this.BLEND_SRC_ALPHA:case this.BLEND_SRC_RGB:case this.BLUE_BITS:case this.CULL_FACE_MODE:case this.DEPTH_BITS:case this.DEPTH_FUNC:case this.FRONT_FACE:case this.GENERATE_MIPMAP_HINT:case this.GREEN_BITS:return this._gl.getParameteri(e);case this.MAX_RENDERBUFFER_SIZE:return this._maxRenderbufferSize;case this.MAX_COMBINED_TEXTURE_IMAGE_UNITS:case this.MAX_CUBE_MAP_TEXTURE_SIZE:case this.MAX_FRAGMENT_UNIFORM_VECTORS:case this.MAX_TEXTURE_IMAGE_UNITS:case this.MAX_TEXTURE_SIZE:case this.MAX_VARYING_VECTORS:case this.MAX_VERTEX_ATTRIBS:case this.MAX_VERTEX_TEXTURE_IMAGE_UNITS:case this.MAX_VERTEX_UNIFORM_VECTORS:case this.PACK_ALIGNMENT:case this.RED_BITS:case this.SAMPLE_BUFFERS:case this.SAMPLES:case this.STENCIL_BACK_FAIL:case this.STENCIL_BACK_FUNC:case this.STENCIL_BACK_PASS_DEPTH_FAIL:case this.STENCIL_BACK_PASS_DEPTH_PASS:case this.STENCIL_BACK_REF:case this.STENCIL_BACK_VALUE_MASK:case this.STENCIL_BACK_WRITEMASK:case this.STENCIL_BITS:case this.STENCIL_CLEAR_VALUE:case this.STENCIL_FAIL:case this.STENCIL_FUNC:case this.STENCIL_PASS_DEPTH_FAIL:case this.STENCIL_PASS_DEPTH_PASS:case this.STENCIL_REF:case this.STENCIL_VALUE_MASK:case this.STENCIL_WRITEMASK:case this.SUBPIXEL_BITS:case this.UNPACK_ALIGNMENT:case this.UNPACK_COLORSPACE_CONVERSION_WEBGL:return this._gl.getParameteri(e);case this.IMPLEMENTATION_COLOR_READ_FORMAT:case this.IMPLEMENTATION_COLOR_READ_TYPE:return this._getParameterDirect(e);default:if(this._extensions.webgl_draw_buffers){let t=this._extensions.webgl_draw_buffers;switch(e){case t.DRAW_BUFFER0_WEBGL:case t.DRAW_BUFFER1_WEBGL:case t.DRAW_BUFFER2_WEBGL:case t.DRAW_BUFFER3_WEBGL:case t.DRAW_BUFFER4_WEBGL:case t.DRAW_BUFFER5_WEBGL:case t.DRAW_BUFFER6_WEBGL:case t.DRAW_BUFFER7_WEBGL:case t.DRAW_BUFFER8_WEBGL:case t.DRAW_BUFFER9_WEBGL:case t.DRAW_BUFFER10_WEBGL:case t.DRAW_BUFFER11_WEBGL:case t.DRAW_BUFFER12_WEBGL:case t.DRAW_BUFFER13_WEBGL:case t.DRAW_BUFFER14_WEBGL:case t.DRAW_BUFFER15_WEBGL:return t._buffersState.length===1&&t._buffersState[0]===this.BACK?this.BACK:this._getParameterDirect(e);case t.MAX_DRAW_BUFFERS_WEBGL:case t.MAX_COLOR_ATTACHMENTS_WEBGL:return this._getParameterDirect(e)}}let t=this._extensions.oes_standard_derivatives;if(t&&e===t.FRAGMENT_SHADER_DERIVATIVE_HINT_OES)return this._getParameterDirect(e);let n=this._extensions.ext_texture_filter_anisotropic;if(n&&e===n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)return this._getParameterDirect(e);let r=this._extensions.oes_vertex_array_object;return r&&e===r.VERTEX_ARRAY_BINDING_OES?r._activeVertexArrayObject:(this.setError(this.INVALID_ENUM),null)}}destroy(){warnNotImplemented(`destroy`)}};installAllContextMethods(WebGLContextBase.prototype);var WebGLRenderingContext$1=class extends WebGLContextBase{static{__name$1(this,`WebGLRenderingContext`)}get _gl(){return this._native}constructor(e,t={}){super(e,t),this._attrib0Buffer=null,this._native=new er.WebGLRenderingContext({}),this._init();let n=this.createBuffer();this._attrib0Buffer=n}_beginAttrib0Hack(){this._native.bindBuffer(this.ARRAY_BUFFER,this._attrib0Buffer?._||0);let e=new Uint8Array(this._vertexGlobalState._attribs[0]._data.buffer);this._native.bufferData(this.ARRAY_BUFFER,Uint8ArrayToVariant(e),this.STREAM_DRAW),this._native.enableVertexAttribArray(0),this._native.vertexAttribPointer(0,4,this.FLOAT,!1,0,0),this._native._vertexAttribDivisor(0,1)}_endAttrib0Hack(){let e=this._vertexObjectState._attribs[0];e._pointerBuffer?this._native.bindBuffer(this.ARRAY_BUFFER,e._pointerBuffer._):this._native.bindBuffer(this.ARRAY_BUFFER,0),this._native.vertexAttribPointer(0,e._inputSize,e._pointerType,e._pointerNormal,e._inputStride,e._pointerOffset),this._native._vertexAttribDivisor(0,e._divisor),this._native.disableVertexAttribArray(0),this._vertexGlobalState._arrayBufferBinding?this._native.bindBuffer(this.ARRAY_BUFFER,this._vertexGlobalState._arrayBufferBinding._):this._native.bindBuffer(this.ARRAY_BUFFER,0)}drawArrays(e=0,t=0,n=0){if(t<0||n<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let r=vertexCount(this,e,n);if(r<0){this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk()||n===0)return;let i=t;if(n>0&&(i=n+t-1>>>0),this._checkVertexAttribState(i)){let n=this._extensions.webgl_draw_buffers;if(this._vertexObjectState._attribs[0]._isPointer||n&&n._buffersState&&n._buffersState.length>0)return this._native.drawArrays(e,t,r);this._beginAttrib0Hack(),this._native._drawArraysInstanced(e,t,r,1),this._endAttrib0Hack()}}drawElements(e=0,t=0,n=0,r=0){if(t<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let i=this._vertexObjectState._elementArrayBufferBinding;if(!i){this.setError(this.INVALID_OPERATION);return}let a=null,o=r;if(n===this.UNSIGNED_SHORT){if(o%2){this.setError(this.INVALID_OPERATION);return}o>>=1,a=new Uint16Array(i._elements.buffer)}else if(this._extensions.oes_element_index_uint&&n===this.UNSIGNED_INT){if(o%4){this.setError(this.INVALID_OPERATION);return}o>>=2,a=new Uint32Array(i._elements.buffer)}else if(n===this.UNSIGNED_BYTE)a=i._elements;else{this.setError(this.INVALID_ENUM);return}let s=t;switch(e){case this.TRIANGLES:t%3&&(s-=t%3);break;case this.LINES:t%2&&(s-=t%2);break;case this.POINTS:break;case this.LINE_LOOP:case this.LINE_STRIP:if(t<2){this.setError(this.INVALID_OPERATION);return}break;case this.TRIANGLE_FAN:case this.TRIANGLE_STRIP:if(t<3){this.setError(this.INVALID_OPERATION);return}break;default:this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk())return;if(t===0){this._checkVertexAttribState(0);return}if(t+o>>>0>a.length){this.setError(this.INVALID_OPERATION);return}let c=-1;for(let e=o;e<o+t;++e)c=Math.max(c,a[e]);if(c<0){this._checkVertexAttribState(0);return}if(this._checkVertexAttribState(c)&&s>0){if(this._vertexObjectState._attribs[0]._isPointer)return this._native.drawElements(e,s,n,r);this._beginAttrib0Hack(),this._native._drawElementsInstanced(e,s,n,r,1),this._endAttrib0Hack()}}},WebGLQuery=class extends Linkable{constructor(e,t){super(e),this._ctx=t}_performDelete(){let e=this._ctx;delete e._queries[this._|0],e._native2.deleteQuery(this._|0)}},WebGLSampler=class extends Linkable{constructor(e,t){super(e),this._ctx=t}_performDelete(){let e=this._ctx;delete e._samplers[this._|0],e._native2.deleteSampler(this._|0)}},WebGLSync=class extends Linkable{constructor(e,t){super(e),this._ctx=t}_performDelete(){let e=this._ctx;delete e._syncs[this._|0],e._native2.deleteSync(this._|0)}},WebGLTransformFeedback=class extends Linkable{constructor(e,t){super(e),this._ctx=t}_performDelete(){let e=this._ctx;delete e._transformFeedbacks[this._|0],e._native2.deleteTransformFeedback(this._|0)}},WebGLVertexArrayObject=class extends Linkable{constructor(e,t){super(e),this._ctx=t,this._objectState=new WebGLVertexArrayObjectState(t)}_performDelete(){let e=this._ctx;e._vertexObjectState===this._objectState&&(e._vertexObjectState=e._defaultVertexObjectState),this._objectState.cleanUp(),delete e._vertexArrayObjects[this._|0],e._native2.deleteVertexArray(this._|0)}};const rr={createVertexArray(){let e=this._native2.createVertexArray();if(!e)return null;let t=new WebGLVertexArrayObject(e,this);return this._vertexArrayObjects[e]=t,t},deleteVertexArray(e){!e||!(e instanceof WebGLVertexArrayObject)||(e._pendingDelete=!0,e._checkDelete())},isVertexArray(e){return!e||!(e instanceof WebGLVertexArrayObject)?!1:this._native2.isVertexArray(e._)},bindVertexArray(e){e===null?(this._native2.bindVertexArray(0),this._vertexObjectState=this._defaultVertexObjectState):e instanceof WebGLVertexArrayObject?(this._native2.bindVertexArray(e._),this._vertexObjectState=e._objectState):this.setError(this.INVALID_OPERATION)},createQuery(){let e=this._native2.createQuery();if(!e)return null;let t=new WebGLQuery(e,this);return this._queries[e]=t,t},deleteQuery(e){!e||!(e instanceof WebGLQuery)||(e._pendingDelete=!0,e._checkDelete())},isQuery(e){return!e||!(e instanceof WebGLQuery)?!1:this._native2.isQuery(e._)},beginQuery(e,t){t instanceof WebGLQuery&&this._native2.beginQuery(e,t._)},endQuery(e){this._native2.endQuery(e)},getQuery(e,t){return warnNotImplemented(`WebGL2RenderingContext.getQuery`),null},getQueryParameter(e,t){return e instanceof WebGLQuery?this._native2.getQueryParameter(e._,t):null},createSampler(){let e=this._native2.createSampler();if(!e)return null;let t=new WebGLSampler(e,this);return this._samplers[e]=t,t},deleteSampler(e){!e||!(e instanceof WebGLSampler)||(e._pendingDelete=!0,e._checkDelete())},isSampler(e){return!e||!(e instanceof WebGLSampler)?!1:this._native2.isSampler(e._)},bindSampler(e,t){this._native2.bindSampler(e,t?t._:0)},samplerParameteri(e,t,n){e instanceof WebGLSampler&&this._native2.samplerParameteri(e._,t,n)},samplerParameterf(e,t,n){e instanceof WebGLSampler&&this._native2.samplerParameterf(e._,t,n)},getSamplerParameter(e,t){return e instanceof WebGLSampler?t===33082||t===33083?this._native2.getSamplerParameterf(e._,t):this._native2.getSamplerParameteri(e._,t):null},fenceSync(e,t){let n=this._native2.fenceSync(e,t);if(!n)return null;let r=new WebGLSync(n,this);return this._syncs[n]=r,r},isSync(e){return!e||!(e instanceof WebGLSync)?!1:this._native2.isSync(e._)},deleteSync(e){!e||!(e instanceof WebGLSync)||(e._pendingDelete=!0,e._checkDelete())},clientWaitSync(e,t,n){return e instanceof WebGLSync?this._native2.clientWaitSync(e._,t,n):37148},waitSync(e,t,n){e instanceof WebGLSync&&this._native2.waitSync(e._,t,n)},getSyncParameter(e,t){return e instanceof WebGLSync?this._native2.getSyncParameter(e._,t):null},createTransformFeedback(){let e=this._native2.createTransformFeedback();if(!e)return null;let t=new WebGLTransformFeedback(e,this);return this._transformFeedbacks[e]=t,t},deleteTransformFeedback(e){!e||!(e instanceof WebGLTransformFeedback)||(e._pendingDelete=!0,e._checkDelete())},isTransformFeedback(e){return!e||!(e instanceof WebGLTransformFeedback)?!1:this._native2.isTransformFeedback(e._)},bindTransformFeedback(e,t){this._native2.bindTransformFeedback(e,t?t._:0)},beginTransformFeedback(e){this._native2.beginTransformFeedback(e)},endTransformFeedback(){this._native2.endTransformFeedback()},pauseTransformFeedback(){this._native2.pauseTransformFeedback()},resumeTransformFeedback(){this._native2.resumeTransformFeedback()},transformFeedbackVaryings(e,t,n){this._native2.transformFeedbackVaryings(e._,t,n)},getTransformFeedbackVarying(e,t){let n=this._native2.getTransformFeedbackVarying(e._,t).deepUnpack();return new WebGLActiveInfo({size:n.size,type:n.type,name:n.name})}};function installObjectLifecycleMethods(e){Object.assign(e,rr)}const ir={texImage3D(e,t,n,r,i,a,o,s,c,l){l===null?this._native2.texImage3DNull(e,t,n,r,i,a,o,s,c):this._native2.texImage3D(e,t,n,r,i,a,o,s,c,Uint8ArrayToVariant(new Uint8Array(l.buffer,l.byteOffset,l.byteLength)))},texSubImage3D(e,t,n,r,i,a,o,s,c,l,u){u!==null&&this._native2.texSubImage3D(e,t,n,r,i,a,o,s,c,l,Uint8ArrayToVariant(new Uint8Array(u.buffer,u.byteOffset,u.byteLength)))},compressedTexImage3D(e,t,n,r,i,a,o,s,c){this._native2.compressedTexImage3D(e,t,n,r,i,a,o,Uint8ArrayToVariant(new Uint8Array(c.buffer,c.byteOffset,c.byteLength)))},compressedTexSubImage3D(e,t,n,r,i,a,o,s,c,l,u){this._native2.compressedTexSubImage3D(e,t,n,r,i,a,o,s,c,Uint8ArrayToVariant(new Uint8Array(u.buffer,u.byteOffset,u.byteLength)))},copyTexSubImage3D(e,t,n,r,i,a,o,s,c){this._native2.copyTexSubImage3D(e,t,n,r,i,a,o,s,c)},texStorage2D(e,t,n,r,i){this._native2.texStorage2D(e,t,n,r,i);let a=this._getTexImage(e);if(a){for(let e=0;e<t;e++)a._levelWidth[e]=Math.max(1,r>>e),a._levelHeight[e]=Math.max(1,i>>e);a._format=this.RGBA,a._type=this.UNSIGNED_BYTE}},texStorage3D(e,t,n,r,i,a){this._native2.texStorage3D(e,t,n,r,i,a)}};function installTexImage3DMethods(e){Object.assign(e,ir)}const ar={uniform1ui(e,t){e&&this._native2.uniform1ui(e._,t)},uniform2ui(e,t,n){e&&this._native2.uniform2ui(e._,t,n)},uniform3ui(e,t,n,r){e&&this._native2.uniform3ui(e._,t,n,r)},uniform4ui(e,t,n,r,i){e&&this._native2.uniform4ui(e._,t,n,r,i)},uniform1uiv(e,t,n,r){if(!e)return;let i=t instanceof Uint32Array?t:new Uint32Array(t);this._native2.uniform1uiv(e._,i.length,i)},uniform2uiv(e,t,n,r){if(!e)return;let i=t instanceof Uint32Array?t:new Uint32Array(t);this._native2.uniform2uiv(e._,i.length/2,i)},uniform3uiv(e,t,n,r){if(!e)return;let i=t instanceof Uint32Array?t:new Uint32Array(t);this._native2.uniform3uiv(e._,i.length/3,i)},uniform4uiv(e,t,n,r){if(!e)return;let i=t instanceof Uint32Array?t:new Uint32Array(t);this._native2.uniform4uiv(e._,i.length/4,i)},uniformMatrix2x3fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix2x3fv(e._,t,a)},uniformMatrix3x2fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix3x2fv(e._,t,a)},uniformMatrix2x4fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix2x4fv(e._,t,a)},uniformMatrix4x2fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix4x2fv(e._,t,a)},uniformMatrix3x4fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix3x4fv(e._,t,a)},uniformMatrix4x3fv(e,t,n,r,i){if(!e)return;let a=n instanceof Float32Array?n:new Float32Array(n);this._native2.uniformMatrix4x3fv(e._,t,a)}};function installUniformMethods(e){Object.assign(e,ar)}const or={clearBufferfv(e,t,n,r){let i=this._native2;if(typeof i.clearBufferfv==`function`){i.clearBufferfv(e,t,Array.from(n));return}let a=n;if(e===6144){let e=this.getParameter(this.COLOR_CLEAR_VALUE);this.clearColor(a[0]??0,a[1]??0,a[2]??0,a[3]??0),this.clear(this.COLOR_BUFFER_BIT),e&&this.clearColor(e[0],e[1],e[2],e[3])}else if(e===6145){let e=this.getParameter(this.DEPTH_CLEAR_VALUE);this.clearDepth(a[0]??1),this.clear(this.DEPTH_BUFFER_BIT),e!==null&&this.clearDepth(e)}},clearBufferiv(e,t,n,r){let i=this._native2;if(typeof i.clearBufferiv==`function`){i.clearBufferiv(e,t,Array.from(n));return}if(e===6146){let e=n,t=this.getParameter(this.STENCIL_CLEAR_VALUE);this.clearStencil(e[0]??0),this.clear(this.STENCIL_BUFFER_BIT),t!==null&&this.clearStencil(t)}},clearBufferuiv(e,t,n,r){let i=this._native2;if(typeof i.clearBufferuiv==`function`){i.clearBufferuiv(e,t,Array.from(n));return}},clearBufferfi(e,t,n,r){let i=this._native2;if(typeof i.clearBufferfi==`function`){i.clearBufferfi(e,t,n,r);return}if(e===34041){let e=this.getParameter(this.DEPTH_CLEAR_VALUE),t=this.getParameter(this.STENCIL_CLEAR_VALUE);this.clearDepth(n),this.clearStencil(r),this.clear(this.DEPTH_BUFFER_BIT|this.STENCIL_BUFFER_BIT),e!==null&&this.clearDepth(e),t!==null&&this.clearStencil(t)}}};function installClearBufferMethods(e){Object.assign(e,or)}function debugGlEnabled(){return globalThis.__GJSIFY_DEBUG_GL===!0}const sr={drawArraysInstanced(e,t,n,r){if(t<0||n<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let i=vertexCount(this,e,n);if(i<0){this.setError(this.INVALID_ENUM);return}if(this._framebufferOk()&&!(n===0||r===0)&&this._checkVertexAttribState(n+t-1>>>0)){if(debugGlEnabled()){let e=this,t=e.__drawInstCount=(e.__drawInstCount|0)+1;(t<=5||t%100==0)&&console.log(`[WebGL] drawArraysInstanced #${t} count=${i} instances=${r} fbo=${this._activeFramebuffer?._??`_gtkFbo`}`)}this._native2.drawArraysInstanced(e,t,i,r)}},drawElementsInstanced(e,t,n,r,i){if(t<0||r<0||i<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let a=this._vertexObjectState._elementArrayBufferBinding;if(!a){this.setError(this.INVALID_OPERATION);return}let o=null,s=r;if(n===this.UNSIGNED_SHORT){if(s%2){this.setError(this.INVALID_OPERATION);return}s>>=1,o=new Uint16Array(a._elements.buffer)}else if(n===this.UNSIGNED_INT){if(s%4){this.setError(this.INVALID_OPERATION);return}s>>=2,o=new Uint32Array(a._elements.buffer)}else if(n===this.UNSIGNED_BYTE)o=a._elements;else{this.setError(this.INVALID_ENUM);return}let c=t;switch(e){case this.TRIANGLES:t%3&&(c-=t%3);break;case this.LINES:t%2&&(c-=t%2);break;case this.POINTS:break;case this.LINE_LOOP:case this.LINE_STRIP:if(t<2){this.setError(this.INVALID_OPERATION);return}break;case this.TRIANGLE_FAN:case this.TRIANGLE_STRIP:if(t<3){this.setError(this.INVALID_OPERATION);return}break;default:this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk())return;if(c===0||i===0){this._checkVertexAttribState(0);return}if(c+s>>>0>o.length){this.setError(this.INVALID_OPERATION);return}let l=0;for(let e=s;e<s+c;++e)o[e]>l&&(l=o[e]);this._checkVertexAttribState(l)&&this._native2.drawElementsInstanced(e,c,n,r,i)},vertexAttribDivisor(e,t){this._native2.vertexAttribDivisor(e,t)},vertexAttribIPointer(e,t,n,r,i){this._native2.vertexAttribIPointer(e,t,n,r,i)},drawBuffers(e){let t=!1;for(let n=0;n<e.length;n++)if(e[n]===1029){t=!0;break}if(!t){this._native2.drawBuffers(e);return}this._native2.drawBuffers(e.map(e=>e===1029?this.COLOR_ATTACHMENT0:e))},drawRangeElements(e,t,n,r,i,a){if(r<0||a<0){this.setError(this.INVALID_VALUE);return}if(n<t){this.setError(this.INVALID_VALUE);return}this.drawElements(e,r,i,a)},blitFramebuffer(e,t,n,r,i,a,o,s,c,l){if(debugGlEnabled()){let e=this._gl.getError();e!==0&&console.log(`[WebGL] blitFramebuffer PRE-ERROR 0x${e.toString(16)}`)}if(this._native2.blitFramebuffer(e,t,n,r,i,a,o,s,c,l),debugGlEnabled()){let i=this._gl.getError(),a=this,o=a.__blitCount=(a.__blitCount|0)+1;o<=5&&console.log(`[WebGL] blitFramebuffer #${o} src=(${e},${t},${n},${r}) readFbo=${this._activeReadFramebuffer?._??`_gtkFbo`} err=${i===0?`OK`:`0x`+i.toString(16)}`)}},framebufferTextureLayer(e,t,n,r,i){this._native2.framebufferTextureLayer(e,t,n?n._:0,r,i)},invalidateFramebuffer(e,t){this._native2.invalidateFramebuffer(e,t)},invalidateSubFramebuffer(e,t,n,r,i,a){this._native2.invalidateSubFramebuffer(e,t,n,r,i,a)},readBuffer(e){this._native2.readBuffer(e)},renderbufferStorageMultisample(e,t,n,r,i){if(e!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}let a=this._activeRenderbuffer;if(!a){this.setError(this.INVALID_OPERATION);return}this._saveError(),this._native2.renderbufferStorageMultisample(e,t,n,r,i);let o=this.getError();this._restoreError(o),o===this.NO_ERROR&&(a._width=r,a._height=i,a._format=n)}};function installInstancedAndFramebufferOpsMethods(e){Object.assign(e,sr)}var cr=class WebGL2RenderingContext extends WebGLContextBase{get _gl(){return this._native2}constructor(e,t={}){super(e,t),this._queries={},this._samplers={},this._transformFeedbacks={},this._vertexArrayObjects={},this._syncs={},this._activeReadFramebuffer=null,this._activeDrawFramebuffer=null,this._native2=new er.WebGL2RenderingContext({}),this._init()}_getGlslVersion(e){return e?`300 es`:`130`}_validFramebufferAttachment(e){return super._validFramebufferAttachment(e)?!0:e>=36065&&e<=36079}static{this._WGL2_ALL_COLOR_ATTACHMENTS=[36064,36065,36066,36067,36068,36069,36070,36071,36072,36073,36074,36075,36076,36077,36078,36079]}_getColorAttachments(){return WebGL2RenderingContext._WGL2_ALL_COLOR_ATTACHMENTS}_preCheckFramebufferStatus(e){let t=e._attachments,n=0,r=0,i=[this.COLOR_ATTACHMENT0,this.DEPTH_ATTACHMENT,this.STENCIL_ATTACHMENT,this.DEPTH_STENCIL_ATTACHMENT,...WebGL2RenderingContext._WGL2_ALL_COLOR_ATTACHMENTS];for(let a of i){let i=t[a];if(i){if(i instanceof WebGLTexture){let t=e._attachmentLevel[a]??0,o=i._levelWidth[t]??0,s=i._levelHeight[t]??0;if(o>0&&s>0){n=o,r=s;break}}else if(i instanceof WebGLRenderbuffer&&i._width>0&&i._height>0){n=i._width,r=i._height;break}}}return n>0&&r>0?(e._width=n,e._height=r,this.FRAMEBUFFER_COMPLETE):this.FRAMEBUFFER_INCOMPLETE_ATTACHMENT}_updateFramebufferAttachments(e){if(super._updateFramebufferAttachments(e),e)for(let t=1;t<=15;t++){let n=36064+t;if(!(n in e._attachments))continue;let r=e._attachments[n];if(r instanceof WebGLTexture){let t=e._attachmentFace[n]||this.TEXTURE_2D,i=e._attachmentLevel[n]??0;this._gl.framebufferTexture2D(this.FRAMEBUFFER,n,t,r._|0,i|0)}else r instanceof WebGLRenderbuffer?this._gl.framebufferRenderbuffer(this.FRAMEBUFFER,n,this.RENDERBUFFER,r._|0):this._gl.framebufferTexture2D(this.FRAMEBUFFER,n,this.TEXTURE_2D,0,0)}}bindBuffer(e,t){if(e===35345||e===35982||e===36662||e===36663){let n=t?t._|0:0;this._gl.bindBuffer(e,n);return}super.bindBuffer(e,t)}bindFramebuffer(e,t){if(e===36008||e===36009){if(!checkObject(t))throw TypeError(`bindFramebuffer(GLenum, WebGLFramebuffer)`);if(t&&t._pendingDelete||t&&!this._checkWrapper(t,WebGLFramebuffer))return;let n=t?t._|0:this._gtkFboId;if(this._gl.bindFramebuffer(e,n),e===36008){let e=this._activeReadFramebuffer;e!==t&&(e&&(--e._refCount,e._checkDelete()),t&&(t._refCount+=1)),this._activeReadFramebuffer=t}else{let e=this._activeDrawFramebuffer;e!==t&&(e&&(--e._refCount,e._checkDelete()),t&&(t._refCount+=1)),this._activeDrawFramebuffer=t,this._activeFramebuffer=t}return}super.bindFramebuffer(this.FRAMEBUFFER,t),this._activeReadFramebuffer=t,this._activeDrawFramebuffer=t}deleteFramebuffer(e){this._activeReadFramebuffer===e&&this.bindFramebuffer(36008,null),this._activeDrawFramebuffer===e&&this.bindFramebuffer(36009,null),super.deleteFramebuffer(e)}bufferData(e,t,n){let r=e===35345||e===35982||e===36662||e===36663,i=n===35041||n===35043||n===35045||n===35042||n===35044||n===35046?this.STATIC_DRAW:n;if(r){if(typeof t==`number`)t>=0&&this._gl.bufferDataSizeOnly(e,t,i);else if(typeof t==`object`&&t){let n=arrayToUint8Array(t);this._gl.bufferData(e,Uint8ArrayToVariant(n),i)}return}super.bufferData(e,t,i)}bufferSubData(e,t,n){if(e===35345||e===35982||e===36662||e===36663){if(t<0){this.setError(this.INVALID_VALUE);return}if(!n){this.setError(this.INVALID_VALUE);return}let r=arrayToUint8Array(n);this._gl.bufferSubData(e,t,Uint8ArrayToVariant(r));return}super.bufferSubData(e,t,n)}bindTexture(e,t){if(e===32879||e===35866){let n=t,r=n?n._|0:0;this._gl.bindTexture(e,r),n&&(n._binding=e);return}super.bindTexture(e,t)}texParameteri(e,t,n){if(e===32879||e===35866){this._gl.texParameteri(e,t,n);return}if(t===32882||t===34892||t===34893||t===33084||t===33085||t===33083||t===33082){this._gl.texParameteri(e,t,n);return}super.texParameteri(e,t,n)}drawArrays(e,t,n){if(t<0||n<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let r=vertexCount(this,e,n);if(r<0){this.setError(this.INVALID_ENUM);return}this._framebufferOk()&&n!==0&&this._checkVertexAttribState(n+t-1>>>0)&&this._native2.drawArrays(e,t,r)}drawElements(e=0,t=0,n=0,r=0){if(t<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._checkStencilState())return;let i=this._vertexObjectState._elementArrayBufferBinding;if(!i){this.setError(this.INVALID_OPERATION);return}let a=null,o=r;if(n===this.UNSIGNED_SHORT){if(o%2){this.setError(this.INVALID_OPERATION);return}o>>=1,a=new Uint16Array(i._elements.buffer)}else if(n===this.UNSIGNED_INT){if(o%4){this.setError(this.INVALID_OPERATION);return}o>>=2,a=new Uint32Array(i._elements.buffer)}else if(n===this.UNSIGNED_BYTE)a=i._elements;else{this.setError(this.INVALID_ENUM);return}let s=t;switch(e){case this.TRIANGLES:t%3&&(s-=t%3);break;case this.LINES:t%2&&(s-=t%2);break;case this.POINTS:break;case this.LINE_LOOP:case this.LINE_STRIP:if(t<2){this.setError(this.INVALID_OPERATION);return}break;case this.TRIANGLE_FAN:case this.TRIANGLE_STRIP:if(t<3){this.setError(this.INVALID_OPERATION);return}break;default:this.setError(this.INVALID_ENUM);return}if(!this._framebufferOk()||t===0)return;let c=0;for(let e=o;e<o+s;++e)e<a.length&&a[e]>c&&(c=a[e]);this._checkVertexAttribState(c)&&this._native2.drawElements(e,s,n,r)}bindBufferBase(e,t,n){this._native2.bindBufferBase(e,t,n?n._:0)}bindBufferRange(e,t,n,r,i){this._native2.bindBufferRange(e,t,n?n._:0,r,i)}copyBufferSubData(e,t,n,r,i){this._native2.copyBufferSubData(e,t,n,r,i)}getBufferSubData(e,t,n,r,i){let a=i===void 0?n.byteLength-(r??0):i,o=this._native2.getBufferSubData(e,t,a),s=new Uint8Array(n.buffer,n.byteOffset+(r??0)*(n instanceof Uint8Array?1:n.BYTES_PER_ELEMENT??1));s.set(o.subarray(0,s.byteLength))}texImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0,c){let l=0,u=0,d=0,f=0;if(arguments.length===6)if(s=i,d=r,a instanceof St.Pixbuf){let e=a;l=e.get_width(),u=e.get_height(),c=e.get_pixels()}else{let e=extractImageData(a);if(e==null)throw TypeError(`texImage2D(GLenum, GLint, GLenum, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)`);l=e.width,u=e.height,c=e.data}else arguments.length>=9&&(l=r,u=i,f=a,d=o);let p=this._getTexImage(e);if(!p){this.setError(this.INVALID_OPERATION);return}let m=convertPixels(c);if(this._unpackPremultAlpha&&m&&d===this.RGBA&&(m=premultiplyAlpha(m)),this._unpackFlipY&&m&&l>0&&u>0){let e=this._computePixelSize(s,d);if(e>0){let t=this._computeRowStride(l,e),n=new Uint8Array(m.length);for(let e=0;e<u;e++){let r=e*t,i=(u-1-e)*t;n.set(m.subarray(r,r+t),i)}m=n}}this._saveError(),this._gl.texImage2D(e,t,n,l,u,f,d,s,Uint8ArrayToVariant(m));let h=this.getError();if(this._restoreError(h),h!==this.NO_ERROR)return;p._levelWidth[t]=l,p._levelHeight[t]=u,p._format=d,p._type=s;let g=this._activeFramebuffer;if(g){let e=!1,t=this._getAttachments();for(let n=0;n<t.length;++n)if(g._attachments[t[n]]===p){e=!0;break}e&&this._activeFramebuffer&&this._updateFramebufferAttachments(this._activeFramebuffer)}}texSubImage2D(e=0,t=0,n=0,r=0,i=0,a=0,o=0,s=0,c){let l=0,u=0,d=0;if(arguments.length===7)if(s=a,d=i,o instanceof St.Pixbuf){let e=o;l=e.get_width(),u=e.get_height(),c=e.get_pixels()}else{let e=extractImageData(o);if(e==null)throw TypeError(`texSubImage2D(GLenum, GLint, GLint, GLint, GLenum, GLenum, ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement)`);l=e.width,u=e.height,c=e.data}else l=i,u=a,d=o;if(!this._getTexImage(e)){this.setError(this.INVALID_OPERATION);return}let f=convertPixels(c);if(!f){this.setError(this.INVALID_OPERATION);return}if(this._unpackPremultAlpha&&f&&d===this.RGBA&&(f=premultiplyAlpha(f)),this._unpackFlipY&&f&&l>0&&u>0){let e=this._computePixelSize(s,d);if(e>0){let t=this._computeRowStride(l,e),n=new Uint8Array(f.length);for(let e=0;e<u;e++){let r=e*t,i=(u-1-e)*t;n.set(f.subarray(r,r+t),i)}f=n}}this._gl.texSubImage2D(e,t,n,r,l,u,d,s,Uint8ArrayToVariant(f))}getUniform(e,t){let n=t?._activeInfo?.type,r=5125,i=36294,a=36295,o=n===r||n===i||n===a||n===36296,s=e;if(!o)return super.getUniform(s,t);if(!e||!t)return null;let c=this._native2.getUniformi(s._|0,t._|0);return c?n===r?c[0]>>>0:n===i?new Uint32Array([c[0]>>>0,c[1]>>>0]):n===a?new Uint32Array([c[0]>>>0,c[1]>>>0,c[2]>>>0]):new Uint32Array([c[0]>>>0,c[1]>>>0,c[2]>>>0,c[3]>>>0]):null}getUniformBlockIndex(e,t){return this._native2.getUniformBlockIndex(e._,t)}uniformBlockBinding(e,t,n){this._native2.uniformBlockBinding(e._,t,n)}getActiveUniformBlockName(e,t){let n=this._native2.getActiveUniformBlockName(e._,t);return n.length>0?n:null}getActiveUniformBlockParameter(e,t,n){return this._native2.getActiveUniformBlockParameter(e._,t,n)}getActiveUniforms(e,t,n){return this._native2.getActiveUniforms(e._,t,n)}getFragDataLocation(e,t){return this._native2.getFragDataLocation(e._,t)}getIndexedParameter(e,t){return this._native2.getIndexedParameteri(e,t)}getInternalformatParameter(e,t,n){return this._native2.getInternalformatParameter(e,t,n)}getParameter(e){if(e===7938)return`WebGL 2.0`;if(e===35724)return`WebGL GLSL ES 3.00`;if(e===7939)return warnNotImplemented(`WebGL2RenderingContext.getParameter(GL_EXTENSIONS)`),``;if(e===36006)return this._activeDrawFramebuffer;if(e===36010)return this._activeReadFramebuffer;switch(e){case 36183:case 35071:case 32883:case 36063:case 34852:case 36203:case 33001:case 33e3:case 37157:case 35373:case 35657:case 35077:case 35978:case 35979:case 35968:case 35376:case 35375:case 35659:case 37154:case 35371:case 35658:case 35379:case 35374:case 35377:case 35076:case 3330:case 3332:case 3331:case 35053:case 35055:case 3074:case 32874:case 35869:case 36389:case 35983:case 35368:case 35380:case 32878:case 3314:case 32877:case 3316:case 3315:case 34045:return this._native2.getParameterx(e)?.deepUnpack()|0;case 35977:case 36388:case 36387:return!!this._native2.getParameterx(e)?.deepUnpack()}return super.getParameter(e)}getStringi(e,t){let n=this._native2.getStringi(e,t);return n.length>0?n:null}renderbufferStorage(e,t,n,r){if(e!==this.RENDERBUFFER){this.setError(this.INVALID_ENUM);return}let i=this._activeRenderbuffer;if(!i){this.setError(this.INVALID_OPERATION);return}if(n<0||r<0){this.setError(this.INVALID_VALUE);return}for(;this._gl.getError()!==this.NO_ERROR;);if(this._gl.renderbufferStorage(e,t,n,r),this._gl.getError()!==this.NO_ERROR)return;i._width=n,i._height=r,i._format=t;let a=this._activeFramebuffer;if(a){let e=this._getAttachments(),t=!1;for(let n=0;n<e.length;++n)if(a._attachments[e[n]]===i){t=!0;break}t&&this._updateFramebufferAttachments(a)}}getSupportedExtensions(){let e=super.getSupportedExtensions();for(let t of[`EXT_color_buffer_float`,`EXT_color_buffer_half_float`,`OES_texture_half_float`])e.indexOf(t)===-1&&e.push(t);return e}readPixels(e,t,n,r,i,a,o){if(!o)return;if(n<0||r<0){this.setError(this.INVALID_VALUE);return}if(!this._framebufferOk())return;let s=i===6408||i===32856?4:i===6407?3:i===33319?2:1,c=a===5126?4:a===5131||a===36193?2:a===5125||a===5124?4:a===5123||a===5122?2:1,l=n*r*s*c,u=new Uint8Array(l);this._saveError();let d=this._gl.readPixels(e,t,n,r,i,a,Uint8ArrayToVariant(u)),f=this.getError();if(this._restoreError(f),f!==this.NO_ERROR)return;let p=d&&d.length>0?d:u;if(o instanceof Uint8Array)o.set(p);else if(o instanceof Float32Array){let e=new Float32Array(p.buffer,0,o.length);o.set(e)}}_framebufferOk(){return!0}};installObjectLifecycleMethods(cr.prototype),installTexImage3DMethods(cr.prototype),installUniformMethods(cr.prototype),installClearBufferMethods(cr.prototype),installInstancedAndFramebufferOpsMethods(cr.prototype);function notifyElementResize(e,t,n){e._allocatedClientWidth=t,e._allocatedClientHeight=n,e._fireResizeSubscribers(t,n);let r=e.parentNode;for(;r;)r instanceof Element&&(r._allocatedClientWidth=t,r._allocatedClientHeight=n,r._fireResizeSubscribers(t,n)),r=r.parentNode}var HTMLCanvasElement$1=class extends P{static{__name$1(this,`HTMLCanvasElement`)}constructor(e){super(),this.gtkGlArea=e}get width(){return this.gtkGlArea.get_allocated_width()}set width(e){}get height(){return this.gtkGlArea.get_allocated_height()}set height(e){}get clientWidth(){return this.width}get clientHeight(){return this.height}get offsetWidth(){return this.width}get offsetHeight(){return this.height}getGlArea(){return this.gtkGlArea}getContext(e,t){return e===`webgl`||e===`experimental-webgl`?(this._webgl||=(this.gtkGlArea.make_current(),new WebGLRenderingContext$1(this,t)),this._webgl):e===`webgl2`?(this._webgl2||=(this.gtkGlArea.make_current(),new cr(this,t)),this._webgl2):super.getContext(e,t)}};const lr=e(import.meta.url);let ur;function load(){return ur===void 0&&(ur=lr(`@gjsify/node-gi/gi`).requireGi(`GObject`)),ur}var dr=new Proxy(Object.create(null),{get(e,t){return load()[t]},has(e,t){return t in load()}});const fr={Return:`Enter`,KP_Enter:`Enter`,Tab:`Tab`,ISO_Left_Tab:`Tab`,BackSpace:`Backspace`,Escape:`Escape`,Delete:`Delete`,KP_Delete:`Delete`,Insert:`Insert`,KP_Insert:`Insert`,Home:`Home`,KP_Home:`Home`,End:`End`,KP_End:`End`,Page_Up:`PageUp`,KP_Page_Up:`PageUp`,Page_Down:`PageDown`,KP_Page_Down:`PageDown`,Left:`ArrowLeft`,KP_Left:`ArrowLeft`,Up:`ArrowUp`,KP_Up:`ArrowUp`,Right:`ArrowRight`,KP_Right:`ArrowRight`,Down:`ArrowDown`,KP_Down:`ArrowDown`,Shift_L:`Shift`,Shift_R:`Shift`,Control_L:`Control`,Control_R:`Control`,Alt_L:`Alt`,Alt_R:`Alt`,Super_L:`Meta`,Super_R:`Meta`,Meta_L:`Meta`,Meta_R:`Meta`,Caps_Lock:`CapsLock`,Num_Lock:`NumLock`,Scroll_Lock:`ScrollLock`,Print:`PrintScreen`,Pause:`Pause`,Menu:`ContextMenu`,space:` `,F1:`F1`,F2:`F2`,F3:`F3`,F4:`F4`,F5:`F5`,F6:`F6`,F7:`F7`,F8:`F8`,F9:`F9`,F10:`F10`,F11:`F11`,F12:`F12`,KP_Add:`+`,KP_Subtract:`-`,KP_Multiply:`*`,KP_Divide:`/`,KP_Decimal:`.`,KP_Separator:`,`,KP_0:`0`,KP_1:`1`,KP_2:`2`,KP_3:`3`,KP_4:`4`,KP_5:`5`,KP_6:`6`,KP_7:`7`,KP_8:`8`,KP_9:`9`},pr={Return:`Enter`,KP_Enter:`NumpadEnter`,Tab:`Tab`,ISO_Left_Tab:`Tab`,BackSpace:`Backspace`,Escape:`Escape`,Delete:`Delete`,KP_Delete:`NumpadDecimal`,Insert:`Insert`,KP_Insert:`Numpad0`,Home:`Home`,KP_Home:`Numpad7`,End:`End`,KP_End:`Numpad1`,Page_Up:`PageUp`,KP_Page_Up:`Numpad9`,Page_Down:`PageDown`,KP_Page_Down:`Numpad3`,Left:`ArrowLeft`,KP_Left:`Numpad4`,Up:`ArrowUp`,KP_Up:`Numpad8`,Right:`ArrowRight`,KP_Right:`Numpad6`,Down:`ArrowDown`,KP_Down:`Numpad2`,Shift_L:`ShiftLeft`,Shift_R:`ShiftRight`,Control_L:`ControlLeft`,Control_R:`ControlRight`,Alt_L:`AltLeft`,Alt_R:`AltRight`,Super_L:`MetaLeft`,Super_R:`MetaRight`,Meta_L:`MetaLeft`,Meta_R:`MetaRight`,Caps_Lock:`CapsLock`,Num_Lock:`NumLock`,Scroll_Lock:`ScrollLock`,Print:`PrintScreen`,Pause:`Pause`,Menu:`ContextMenu`,space:`Space`,F1:`F1`,F2:`F2`,F3:`F3`,F4:`F4`,F5:`F5`,F6:`F6`,F7:`F7`,F8:`F8`,F9:`F9`,F10:`F10`,F11:`F11`,F12:`F12`,KP_Add:`NumpadAdd`,KP_Subtract:`NumpadSubtract`,KP_Multiply:`NumpadMultiply`,KP_Divide:`NumpadDivide`,KP_Decimal:`NumpadDecimal`,KP_Separator:`NumpadComma`,KP_0:`Numpad0`,KP_1:`Numpad1`,KP_2:`Numpad2`,KP_3:`Numpad3`,KP_4:`Numpad4`,KP_5:`Numpad5`,KP_6:`Numpad6`,KP_7:`Numpad7`,KP_8:`Numpad8`,KP_9:`Numpad9`};function gdkKeyvalToKey(e){let t=it.keyval_name(e);if(t&&fr[t])return fr[t];let n=it.keyval_to_unicode(e);return n>0?String.fromCodePoint(n):t??`Unidentified`}function gdkKeyvalToCode(e){let t=it.keyval_name(e);if(t&&pr[t])return pr[t];let n=it.keyval_to_unicode(e);if(n>=97&&n<=122)return`Key`+String.fromCodePoint(n-32);if(n>=65&&n<=90)return`Key`+String.fromCodePoint(n);if(n>=48&&n<=57)return`Digit`+String.fromCodePoint(n);if(t){let e={minus:`Minus`,equal:`Equal`,bracketleft:`BracketLeft`,bracketright:`BracketRight`,backslash:`Backslash`,semicolon:`Semicolon`,apostrophe:`Quote`,grave:`Backquote`,comma:`Comma`,period:`Period`,slash:`Slash`};if(e[t])return e[t]}return t??`Unidentified`}function gdkKeyvalToLocation(e){let t=it.keyval_name(e);return t?t.startsWith(`KP_`)?3:t.endsWith(`_L`)?1:t.endsWith(`_R`)?2:0:0}function getGlobalEventTarget(){return globalThis.__gjsify_globalEventTarget}function extractModifiers(e){let t=e.get_current_event_state();return{shiftKey:!!(t&it.ModifierType.SHIFT_MASK),ctrlKey:!!(t&it.ModifierType.CONTROL_MASK),altKey:!!(t&it.ModifierType.ALT_MASK),metaKey:!!(t&it.ModifierType.SUPER_MASK)}}function gtkButtonToDom(e){return e===1?0:e===2?1:e===3?2:e-1}function buttonsFromModifiers(e){let t=e.get_current_event_state(),n=0;return t&it.ModifierType.BUTTON1_MASK&&(n|=1),t&it.ModifierType.BUTTON3_MASK&&(n|=2),t&it.ModifierType.BUTTON2_MASK&&(n|=4),n}function attachEventControllers(e,t,n){e.set_focusable(!0),e.set_can_focus(!0);let r={lastX:0,lastY:0,buttonsPressed:0,pressedKeys:new Set},i=new yn.EventControllerMotion;i.connect(`motion`,(n,a,o)=>{let s=t();if(!s)return;let c=e.get_allocated_width(),l=e.get_allocated_height(),u=Math.max(0,Math.min(a,c)),d=Math.max(0,Math.min(o,l)),f=u-r.lastX,p=d-r.lastY,m=extractModifiers(i),h=buttonsFromModifiers(i),g={...m,clientX:u,clientY:d,offsetX:u,offsetY:d,screenX:u,screenY:d,movementX:f,movementY:p,buttons:h,button:0,bubbles:!0,cancelable:!0};s.dispatchEvent(new PointerEvent(`pointermove`,{...g,pointerId:1,pointerType:`mouse`,isPrimary:!0})),s.dispatchEvent(new MouseEvent(`mousemove`,g)),r.lastX=u,r.lastY=d}),i.connect(`enter`,(e,n,a)=>{let o=t();if(!o)return;r.lastX=n,r.lastY=a;let s={...extractModifiers(i),clientX:n,clientY:a,offsetX:n,offsetY:a,screenX:n,screenY:a,bubbles:!1,cancelable:!1};o.dispatchEvent(new PointerEvent(`pointerenter`,{...s,pointerId:1,pointerType:`mouse`,isPrimary:!0})),o.dispatchEvent(new MouseEvent(`mouseenter`,s)),o.dispatchEvent(new MouseEvent(`mouseover`,{...s,bubbles:!0}))}),i.connect(`leave`,()=>{let e=t();if(!e)return;let n={...extractModifiers(i),clientX:r.lastX,clientY:r.lastY,bubbles:!1,cancelable:!1};e.dispatchEvent(new PointerEvent(`pointerleave`,{...n,pointerId:1,pointerType:`mouse`,isPrimary:!0})),e.dispatchEvent(new MouseEvent(`mouseleave`,n)),e.dispatchEvent(new MouseEvent(`mouseout`,{...n,bubbles:!0}))}),e.add_controller(i);let a=new yn.GestureClick;a.set_button(0),a.connect(`pressed`,(n,i,o,s)=>{let c=t();if(!c)return;let l=gtkButtonToDom(a.get_current_button()),u=extractModifiers(a);r.buttonsPressed|=1<<l;let d={...u,clientX:o,clientY:s,offsetX:o,offsetY:s,screenX:o,screenY:s,button:l,buttons:r.buttonsPressed,detail:i,bubbles:!0,cancelable:!0};c.dispatchEvent(new PointerEvent(`pointerdown`,{...d,pointerId:1,pointerType:`mouse`,isPrimary:!0})),c.dispatchEvent(new MouseEvent(`mousedown`,d)),e.grab_focus()}),a.connect(`released`,(e,n,i,o)=>{let s=t();if(!s)return;let c=gtkButtonToDom(a.get_current_button()),l=extractModifiers(a);r.buttonsPressed&=~(1<<c);let u={...l,clientX:i,clientY:o,offsetX:i,offsetY:o,screenX:i,screenY:o,button:c,buttons:r.buttonsPressed,detail:n,bubbles:!0,cancelable:!0};s.dispatchEvent(new PointerEvent(`pointerup`,{...u,pointerId:1,pointerType:`mouse`,isPrimary:!0})),s.dispatchEvent(new MouseEvent(`mouseup`,u)),c===0&&(s.dispatchEvent(new MouseEvent(`click`,u)),n===2&&s.dispatchEvent(new MouseEvent(`dblclick`,u))),c===2&&s.dispatchEvent(new MouseEvent(`contextmenu`,{...u,cancelable:!0}))}),e.add_controller(a);let o=new yn.EventControllerScroll({flags:yn.EventControllerScrollFlags.BOTH_AXES});o.connect(`scroll`,(e,n,i)=>{let a=t();if(!a)return;let s={...extractModifiers(o),clientX:r.lastX,clientY:r.lastY,offsetX:r.lastX,offsetY:r.lastY,screenX:r.lastX,screenY:r.lastY,deltaX:n*100,deltaY:i*100,deltaZ:0,deltaMode:0,bubbles:!0,cancelable:!0};return a.dispatchEvent(new WheelEvent(`wheel`,s)),!1}),e.add_controller(o);let s=new yn.EventControllerKey;s.connect(`key-pressed`,(e,i,a,o)=>{let s=t();if(!s)return!1;let c=r.pressedKeys.has(i);r.pressedKeys.add(i);let l=gdkKeyvalToKey(i),u={key:l,code:gdkKeyvalToCode(i),location:gdkKeyvalToLocation(i),repeat:c,altKey:!!(o&it.ModifierType.ALT_MASK),ctrlKey:!!(o&it.ModifierType.CONTROL_MASK),metaKey:!!(o&it.ModifierType.SUPER_MASK),shiftKey:!!(o&it.ModifierType.SHIFT_MASK),keyCode:l.length===1?l.toUpperCase().charCodeAt(0):0,which:l.length===1?l.toUpperCase().charCodeAt(0):0,bubbles:!0,cancelable:!0},d=new KeyboardEvent(`keydown`,u);return s.dispatchEvent(d),getGlobalEventTarget()?.dispatchEvent(new KeyboardEvent(`keydown`,u)),n?.captureKeys===!0}),s.connect(`key-released`,(e,n,i,a)=>{let o=t();if(!o)return;r.pressedKeys.delete(n);let s=gdkKeyvalToKey(n),c={key:s,code:gdkKeyvalToCode(n),location:gdkKeyvalToLocation(n),repeat:!1,altKey:!!(a&it.ModifierType.ALT_MASK),ctrlKey:!!(a&it.ModifierType.CONTROL_MASK),metaKey:!!(a&it.ModifierType.SUPER_MASK),shiftKey:!!(a&it.ModifierType.SHIFT_MASK),keyCode:s.length===1?s.toUpperCase().charCodeAt(0):0,which:s.length===1?s.toUpperCase().charCodeAt(0):0,bubbles:!0,cancelable:!0};o.dispatchEvent(new KeyboardEvent(`keyup`,c)),getGlobalEventTarget()?.dispatchEvent(new KeyboardEvent(`keyup`,c))}),e.add_controller(s);let c=new yn.EventControllerFocus;c.connect(`enter`,()=>{let e=t();e&&(e.dispatchEvent(new FocusEvent(`focus`,{bubbles:!1,cancelable:!1})),e.dispatchEvent(new FocusEvent(`focusin`,{bubbles:!0,cancelable:!1})))}),c.connect(`leave`,()=>{let e=t();e&&(r.pressedKeys.clear(),e.dispatchEvent(new FocusEvent(`blur`,{bubbles:!1,cancelable:!1})),e.dispatchEvent(new FocusEvent(`focusout`,{bubbles:!0,cancelable:!1})),getGlobalEventTarget()?.dispatchEvent(new FocusEvent(`blur`,{bubbles:!1,cancelable:!1})))}),e.add_controller(c)}const mr=dr.registerClass({GTypeName:`GjsifyWebGLBridge`},class WebGLBridge extends yn.GLArea{constructor(e){super(e),this._canvas=null,this._readyCallbacks=[],this._resizeCallbacks=[],this._renderTag=null,this._tickCallbackId=null,this._frameCallback=null,this._lastFrameCallback=null,this._lastFrameTime=0,this._replaying=!1,this._frameCallbackId=0,this._nextFrameId=1,this._timeOrigin=mt.get_monotonic_time(),this.set_use_es(!0),this.set_required_version(3,2),this.set_has_depth_buffer(!0),this.set_has_stencil_buffer(!0),attachEventControllers(this,()=>this._canvas,{captureKeys:!0}),this._tickCallbackId=this.add_tick_callback((e,t)=>(this._frameCallback!==null&&this.queue_render(),mt.SOURCE_CONTINUE));let t=this.connect(`render`,()=>{this.disconnect(t),this.make_current(),this._canvas=new HTMLCanvasElement$1(this);{let e=globalThis;e.document?.body&&e.document.body.appendChild(this._canvas)}this._canvas.getContext(`webgl2`);let e=this._canvas.getContext(`webgl`);if(e){for(let t of this._readyCallbacks)t(this._canvas,e);this._readyCallbacks=[]}return this._renderTag=this.connect(`render`,e=>{let t=(mt.get_monotonic_time()-this._timeOrigin)/1e3;if(this._frameCallback!==null){globalThis.__GJSIFY_DEBUG_RAF===!0&&console.log(`[rAF] frame callback fires t=${t.toFixed(1)}`);let e=this._frameCallback;this._frameCallback=null,this._frameCallbackId=0,this._lastFrameCallback=e,this._lastFrameTime=t,e(t)}else if(this._lastFrameCallback!==null){this._replaying=!0;try{this._lastFrameCallback(this._lastFrameTime)}finally{this._replaying=!1}}return!0}),!0});this.connect(`resize`,()=>{let e=this.get_allocated_width(),t=this.get_allocated_height();this._canvas&&(this._canvas.dispatchEvent(new Event(`resize`)),notifyElementResize(this._canvas,e,t));for(let n of this._resizeCallbacks)n(e,t);this._frameCallback&&this.requestAnimationFrame(this._frameCallback)}),this.connect(`unrealize`,()=>{this._renderTag!==null&&(this.disconnect(this._renderTag),this._renderTag=null),this._tickCallbackId!==null&&(this.remove_tick_callback(this._tickCallbackId),this._tickCallbackId=null),this._frameCallback=null,this._lastFrameCallback=null,this._lastFrameTime=0,this._replaying=!1,this._canvas=null})}get canvas(){return this._canvas}onReady(e){if(this._canvas){let t=this._canvas.getContext(`webgl`);if(t){e(this._canvas,t);return}}this._readyCallbacks.push(e)}onWebGLReady(e){this.onReady(e)}onResize(e){this._resizeCallbacks.push(e)}requestAnimationFrame(e){let t=this._nextFrameId++;return this._replaying?t:(this._frameCallback=e,this._frameCallbackId=t,this.queue_render(),t)}cancelAnimationFrame(e){e!==0&&e===this._frameCallbackId&&(this._frameCallback=null,this._frameCallbackId=0,this._lastFrameCallback=null,this._lastFrameTime=0)}installGlobals(){let e=globalThis;e.requestAnimationFrame=e=>this.requestAnimationFrame(e),e.cancelAnimationFrame=e=>this.cancelAnimationFrame(e),e.WebGLRenderingContext=WebGLRenderingContext$1,e.WebGL2RenderingContext=cr;let t=this._timeOrigin;e.performance={now:()=>(mt.get_monotonic_time()-t)/1e3,timeOrigin:Date.now()}}});globalThis.imports
78
78
  /**
79
79
  * @license
80
80
  * Copyright 2010-2026 Three.js Authors