@gramlot/gramlot 0.3.30 → 0.3.31
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/components/charts/__init__.py +1 -1
- package/dist/components/charts/assets/collection.js +1 -1
- package/dist/components/charts/assets/index.js +1 -1
- package/dist/components/grid/__init__.py +2 -2
- package/dist/components/grid/assets/collection.js +36 -20
- package/dist/components/grid/assets/files/0a1df3a083d0c010560aa342e87959c8c1070e6fd54545741f083f22d0c8b551-fflate.txt +21 -0
- package/dist/components/grid/assets/files/8cf9b31947daf7adb4a7a00a037459e58241af050cd0a603bfcf1756e533f75e-write-excel-file.txt +21 -0
- package/dist/components/grid/assets/index.js +1 -1
- package/dist/components/grid/assets/modules/browser-LVJHKBBV.js +19 -0
- package/dist/components/grid/assets/modules/chunk-RMRBEYTI.js +1 -0
- package/dist/components/grid/commands.json +42 -1
- package/dist/components/grid/grammar.json +384 -2
- package/dist/components/vizabi/__init__.py +1 -1
- package/dist/components/vizabi/assets/collection.js +1 -1
- package/dist/components/vizabi/assets/index.js +1 -1
- package/dist/gramlot.js +376 -21
- package/dist/gramlot.min.js +46 -46
- package/dist/standard-collections.js +1 -1
- package/package.json +3 -2
- package/src/binding/grid-struct.js +4 -1
- package/src/binding/runtime.js +2 -1
- package/src/builder/gramlot-builder.js +96 -7
- package/src/builder/source.js +18 -0
- package/src/components/grid-footer.js +120 -0
- package/src/components/grid-formulas.js +403 -0
- package/src/components/grid-grammar.json +87 -2
- package/src/components/grid-selection.js +118 -0
- package/src/components/grid-structure.js +27 -4
- package/src/components/grid-styles.js +14 -1
- package/src/components/grid-tools.js +229 -0
- package/src/components/grid.js +174 -8
- package/src/components/licenses/fflate.txt +21 -0
- package/src/components/licenses/write-excel-file.txt +21 -0
- package/src/editing-session.d.ts +2 -0
- package/src/editing-session.js +35 -3
- package/src/stores/bag-collection-store.js +14 -5
- package/src/stores/bag-collection-view.js +1 -1
package/dist/gramlot.min.js
CHANGED
|
@@ -6,38 +6,38 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
9
|
-
var kg=Object.create;var jl=Object.defineProperty;var Tg=Object.getOwnPropertyDescriptor;var Ag=Object.getOwnPropertyNames;var Dg=Object.getPrototypeOf,Sg=Object.prototype.hasOwnProperty;var sr=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Cg=(n,e)=>{for(var t in e)jl(n,t,{get:e[t],enumerable:!0})},Ng=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ag(e))!Sg.call(n,o)&&o!==t&&jl(n,o,{get:()=>e[o],enumerable:!(r=Tg(e,o))||r.enumerable});return n};var Id=(n,e,t)=>(t=n!=null?kg(Dg(n)):{},Ng(e||!n||!n.__esModule?jl(t,"default",{value:n,enumerable:!0}):t,n));var zr=sr(Me=>{"use strict";function ew(n,e,t){if(t===void 0&&(t=Array.prototype),n&&typeof t.find=="function")return t.find.call(n,e);for(var r=0;r<n.length;r++)if(Vr(n,r)){var o=n[r];if(e.call(void 0,o,r,n))return o}}function Rn(n,e){return e===void 0&&(e=Object),e&&typeof e.getOwnPropertyDescriptors=="function"&&(n=e.create(null,e.getOwnPropertyDescriptors(n))),e&&typeof e.freeze=="function"?e.freeze(n):n}function Vr(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function tw(n,e){if(n===null||typeof n!="object")throw new TypeError("target is not an object");for(var t in e)Vr(e,t)&&(n[t]=e[t]);return n}var hf=Rn({allowfullscreen:!0,async:!0,autofocus:!0,autoplay:!0,checked:!0,controls:!0,default:!0,defer:!0,disabled:!0,formnovalidate:!0,hidden:!0,ismap:!0,itemscope:!0,loop:!0,multiple:!0,muted:!0,nomodule:!0,novalidate:!0,open:!0,playsinline:!0,readonly:!0,required:!0,reversed:!0,selected:!0});function rw(n){return Vr(hf,n.toLowerCase())}var pf=Rn({area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function nw(n){return Vr(pf,n.toLowerCase())}var qo=Rn({script:!1,style:!1,textarea:!0,title:!0});function ow(n){var e=n.toLowerCase();return Vr(qo,e)&&!qo[e]}function iw(n){var e=n.toLowerCase();return Vr(qo,e)&&qo[e]}function mf(n){return n===Uo.HTML}function aw(n){return mf(n)||n===Uo.XML_XHTML_APPLICATION}var Uo=Rn({HTML:"text/html",XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),sw=Object.keys(Uo).map(function(n){return Uo[n]});function lw(n){return sw.indexOf(n)>-1}var uw=Rn({HTML:"http://www.w3.org/1999/xhtml",SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});Me.assign=tw;Me.find=ew;Me.freeze=Rn;Me.HTML_BOOLEAN_ATTRIBUTES=hf;Me.HTML_RAW_TEXT_ELEMENTS=qo;Me.HTML_VOID_ELEMENTS=pf;Me.hasDefaultHTMLNamespace=aw;Me.hasOwn=Vr;Me.isHTMLBooleanAttribute=rw;Me.isHTMLRawTextElement=ow;Me.isHTMLEscapableRawTextElement=iw;Me.isHTMLMimeType=mf;Me.isHTMLVoidElement=nw;Me.isValidMimeType=lw;Me.MIME_TYPE=Uo;Me.NAMESPACE=uw});var Wo=sr(Go=>{"use strict";var cw=zr();function bf(n,e){n.prototype=Object.create(Error.prototype,{constructor:{value:n},name:{value:n.name,enumerable:!0,writable:e}})}var zo=cw.freeze({Error:"Error",IndexSizeError:"IndexSizeError",DomstringSizeError:"DomstringSizeError",HierarchyRequestError:"HierarchyRequestError",WrongDocumentError:"WrongDocumentError",InvalidCharacterError:"InvalidCharacterError",NoDataAllowedError:"NoDataAllowedError",NoModificationAllowedError:"NoModificationAllowedError",NotFoundError:"NotFoundError",NotSupportedError:"NotSupportedError",InUseAttributeError:"InUseAttributeError",InvalidStateError:"InvalidStateError",SyntaxError:"SyntaxError",InvalidModificationError:"InvalidModificationError",NamespaceError:"NamespaceError",InvalidAccessError:"InvalidAccessError",ValidationError:"ValidationError",TypeMismatchError:"TypeMismatchError",SecurityError:"SecurityError",NetworkError:"NetworkError",AbortError:"AbortError",URLMismatchError:"URLMismatchError",QuotaExceededError:"QuotaExceededError",TimeoutError:"TimeoutError",InvalidNodeTypeError:"InvalidNodeTypeError",DataCloneError:"DataCloneError",EncodingError:"EncodingError",NotReadableError:"NotReadableError",UnknownError:"UnknownError",ConstraintError:"ConstraintError",DataError:"DataError",TransactionInactiveError:"TransactionInactiveError",ReadOnlyError:"ReadOnlyError",VersionError:"VersionError",OperationError:"OperationError",NotAllowedError:"NotAllowedError",OptOutError:"OptOutError"}),wf=Object.keys(zo);function _f(n){return typeof n=="number"&&n>=1&&n<=25}function dw(n){return typeof n=="string"&&n.substring(n.length-zo.Error.length)===zo.Error}function Ho(n,e){_f(n)?(this.name=wf[n],this.message=e||""):(this.message=n,this.name=dw(e)?e:zo.Error),Error.captureStackTrace&&Error.captureStackTrace(this,Ho)}bf(Ho,!0);Object.defineProperties(Ho.prototype,{code:{enumerable:!0,get:function(){var n=wf.indexOf(this.name);return _f(n)?n:0}}});var yf={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25},nu=Object.entries(yf);for(Vo=0;Vo<nu.length;Vo++)gf=nu[Vo][0],Ho[gf]=nu[Vo][1];var gf,Vo;function ou(n,e,t){this.message=n,this.locator=e,this.cause=t,Error.captureStackTrace&&Error.captureStackTrace(this,ou)}bf(ou);Go.DOMException=Ho;Go.DOMExceptionName=zo;Go.ExceptionCode=yf;Go.ParseError=ou});var du=sr(H=>{"use strict";function Af(n){try{typeof n!="function"&&(n=RegExp);var e=new n("\u{1D306}","u").exec("\u{1D306}");return!!e&&e[0].length===2}catch{}return!1}var Mn=Af();function pr(n){if(n.source[0]!=="[")throw new Error(n+" can not be used with chars");return n.source.slice(1,n.source.lastIndexOf("]"))}function Bn(n,e){if(n.source[0]!=="[")throw new Error("/"+n.source+"/ can not be used with chars_without");if(!e||typeof e!="string")throw new Error(JSON.stringify(e)+" is not a valid search");if(n.source.indexOf(e)===-1)throw new Error('"'+e+'" is not is /'+n.source+"/");if(e==="-"&&n.source.indexOf(e)!==1)throw new Error('"'+e+'" is not at the first postion of /'+n.source+"/");return new RegExp(n.source.replace(e,""),Mn?"u":"")}function Y(n){var e=this;return new RegExp(Array.prototype.slice.call(arguments).map(function(t){var r=typeof t=="string";if(r&&e===void 0&&t==="|")throw new Error("use regg instead of reg to wrap expressions with `|`!");return r?t:t.source}).join(""),Mn?"u":"")}function V(n){if(arguments.length===0)throw new Error("no parameters provided");return Y.apply(V,["(?:"].concat(Array.prototype.slice.call(arguments),[")"]))}var fw="\uFFFD",mr=/[-\x09\x0A\x0D\x20-\x2C\x2E-\uD7FF\uE000-\uFFFD]/;Mn&&(mr=Y("[",pr(mr),"\\u{10000}-\\u{10FFFF}","]"));var hw=new RegExp("[^"+pr(mr)+"]",Mn?"u":""),Ca=/[\x20\x09\x0D\x0A]/,pw=pr(Ca),ce=Y(Ca,"+"),ye=Y(Ca,"*"),Yo=/[:_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;Mn&&(Yo=Y("[",pr(Yo),"\\u{10000}-\\u{10FFFF}","]"));var mw=pr(Yo),su=Y("[",mw,pr(/[-.0-9\xB7]/),pr(/[\u0300-\u036F\u203F-\u2040]/),"]"),lt=Y(Yo,su,"*"),gw=Y("^",lt,"$"),vf=Y(su,"+"),bw=Y("&",lt,";"),ww=V(/&#[0-9]+;|&#x[0-9a-fA-F]+;/),Xo=V(bw,"|",ww),Zo=Y("%",lt,";"),lu=V(Y('"',V(/[^%&"]/,"|",Zo,"|",Xo),"*",'"'),"|",Y("'",V(/[^%&']/,"|",Zo,"|",Xo),"*","'")),_w=V('"',V(/[^<&"]/,"|",Xo),"*",'"',"|","'",V(/[^<&']/,"|",Xo),"*","'"),yw=Bn(Yo,":"),vw=Bn(su,":"),iu=Y(yw,vw,"*"),Ew=Y("^",iu,"$"),Ko=Y(iu,V(":",iu),"?"),xw=Y("^",Ko,"$"),kw=Y("(",Ko,")"),$n=V(/"[^"]*"|'[^']*'/),Tw=Y(/^<\?/,"(",lt,")",V(ce,"(?!",Ca,")(",mr,"*?)"),"?",/\?>/),Ef=/[\x20\x0D\x0Aa-zA-Z0-9-'()+,./:=?;!*#@$_%]/,Jo=V('"',Ef,'*"',"|","'",Bn(Ef,"'"),"*'"),Df="<!--",Sf="-->",Aw=Y(Df,V(Bn(mr,"-"),"|",Y("-",Bn(mr,"-"))),"*",Sf),xf="#PCDATA",Dw=V(Y(/\(/,ye,xf,V(ye,/\|/,ye,Ko),"*",ye,/\)\*/),"|",Y(/\(/,ye,xf,ye,/\)/)),Sw=/[?*+]?/,Cw=Y(/\([^>]+\)/,Sw),Nw=V("EMPTY","|","ANY","|",Dw,"|",Cw),Iw="<!ELEMENT",Ow=Y(Iw,ce,V(Ko,"|",Zo),ce,V(Nw,"|",Zo),ye,">"),Rw=Y("NOTATION",ce,/\(/,ye,lt,V(ye,/\|/,ye,lt),"*",ye,/\)/),Bw=Y(/\(/,ye,vf,V(ye,/\|/,ye,vf),"*",ye,/\)/),$w=V(Rw,"|",Bw),Mw=V(/CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS/,"|",$w),Pw=V(/#REQUIRED|#IMPLIED/,"|",V(V("#FIXED",ce),"?",_w)),Lw=V(ce,lt,ce,Mw,ce,Pw),Fw="<!ATTLIST",jw=Y(Fw,ce,lt,Lw,"*",ye,">"),au="about:legacy-compat",qw=V('"'+au+'"',"|","'"+au+"'"),uu="SYSTEM",Na="PUBLIC",Ia=V(V(uu,ce,$n),"|",V(Na,ce,Jo,ce,$n)),Uw=Y("^",V(V(uu,ce,"(?<SystemLiteralOnly>",$n,")"),"|",V(Na,ce,"(?<PubidLiteral>",Jo,")",ce,"(?<SystemLiteral>",$n,")"))),Vw=Y("^",Jo,"$"),zw=Y("^",$n,"$"),Hw=V(ce,"NDATA",ce,lt),Gw=V(lu,"|",V(Ia,Hw,"?")),Cf="<!ENTITY",Ww=Y(Cf,ce,lt,ce,Gw,ye,">"),Yw=V(lu,"|",Ia),Xw=Y(Cf,ce,"%",ce,lt,ce,Yw,ye,">"),Zw=V(Ww,"|",Xw),Kw=Y(Na,ce,Jo),Jw=Y("<!NOTATION",ce,lt,ce,V(Ia,"|",Kw),ye,">"),cu=Y(ye,"=",ye),kf=/1[.]\d+/,Qw=Y(ce,"version",cu,V("'",kf,"'","|",'"',kf,'"')),Tf=/[A-Za-z][-A-Za-z0-9._]*/,e_=V(ce,"encoding",cu,V('"',Tf,'"',"|","'",Tf,"'")),t_=V(ce,"standalone",cu,V("'",V("yes","|","no"),"'","|",'"',V("yes","|","no"),'"')),r_=Y(/^<\?xml/,Qw,e_,"?",t_,"?",ye,/\?>/),n_="<!DOCTYPE",o_="<![CDATA[",i_="]]>",a_=/<!\[CDATA\[/,s_=/\]\]>/,l_=Y(mr,"*?",s_),u_=Y(a_,l_);H.chars=pr;H.chars_without=Bn;H.detectUnicodeSupport=Af;H.reg=Y;H.regg=V;H.ABOUT_LEGACY_COMPAT=au;H.ABOUT_LEGACY_COMPAT_SystemLiteral=qw;H.AttlistDecl=jw;H.CDATA_START=o_;H.CDATA_END=i_;H.CDSect=u_;H.Char=mr;H.Comment=Aw;H.COMMENT_START=Df;H.COMMENT_END=Sf;H.DOCTYPE_DECL_START=n_;H.elementdecl=Ow;H.EntityDecl=Zw;H.EntityValue=lu;H.ExternalID=Ia;H.ExternalID_match=Uw;H.Name=lt;H.Name_exact=gw;H.NCName_exact=Ew;H.NotationDecl=Jw;H.Reference=Xo;H.PEReference=Zo;H.PI=Tw;H.PUBLIC=Na;H.PubidLiteral=Jo;H.PubidLiteral_match=Vw;H.QName=Ko;H.QName_exact=xw;H.QName_group=kw;H.S=ce;H.SChar_s=pw;H.S_OPT=ye;H.SYSTEM=uu;H.SystemLiteral=$n;H.SystemLiteral_match=zw;H.InvalidChar=hw;H.UNICODE_REPLACEMENT_CHARACTER=fw;H.UNICODE_SUPPORT=Mn;H.XMLDecl=r_});var vu=sr(xe=>{"use strict";var ht=zr(),$t=ht.find,c_=ht.hasDefaultHTMLNamespace,Ln=ht.hasOwn,d_=ht.isHTMLMimeType,f_=ht.isHTMLRawTextElement,h_=ht.isHTMLVoidElement,Qo=ht.MIME_TYPE,Mt=ht.NAMESPACE,Ye=Symbol(),Mf=Wo(),R=Mf.DOMException,He=Mf.DOMExceptionName,Ee=du();function nt(n){if(n!==Ye)throw new TypeError("Illegal constructor")}function p_(n){return n!==""}function m_(n){return n?n.split(/[\t\n\f\r ]+/).filter(p_):[]}function g_(n,e){return Ln(n,e)||(n[e]=!0),n}function Nf(n){if(!n)return[];var e=m_(n);return Object.keys(e.reduce(g_,{}))}function b_(n){return function(e){return n&&n.indexOf(e)!==-1}}function Pf(n){if(!Ee.QName_exact.test(n))throw new R(R.INVALID_CHARACTER_ERR,'invalid character in qualified name "'+n+'"')}function hu(n,e){Pf(e),n=n||null;var t=null,r=e;if(e.indexOf(":")>=0){var o=e.split(":");t=o[0],r=o[1]}if(t!==null&&n===null)throw new R(R.NAMESPACE_ERR,"prefix is non-null and namespace is null");if(t==="xml"&&n!==ht.NAMESPACE.XML)throw new R(R.NAMESPACE_ERR,'prefix is "xml" and namespace is not the XML namespace');if((t==="xmlns"||e==="xmlns")&&n!==ht.NAMESPACE.XMLNS)throw new R(R.NAMESPACE_ERR,'either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace');if(n===ht.NAMESPACE.XMLNS&&t!=="xmlns"&&e!=="xmlns")throw new R(R.NAMESPACE_ERR,'namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"');return[n,t,r]}function qn(n,e){for(var t in n)Ln(n,t)&&(e[t]=n[t])}function ot(n,e){var t=n.prototype;if(!(t instanceof e)){let r=function(){};r.prototype=e.prototype,r=new r,qn(t,r),n.prototype=t=r}t.constructor!=n&&(typeof n!="function"&&console.error("unknown Class:"+n),t.constructor=n)}var it={},ft=it.ELEMENT_NODE=1,Fn=it.ATTRIBUTE_NODE=2,ei=it.TEXT_NODE=3,Lf=it.CDATA_SECTION_NODE=4,Ff=it.ENTITY_REFERENCE_NODE=5,w_=it.ENTITY_NODE=6,pu=it.PROCESSING_INSTRUCTION_NODE=7,mu=it.COMMENT_NODE=8,Pn=it.DOCUMENT_NODE=9,jf=it.DOCUMENT_TYPE_NODE=10,gr=it.DOCUMENT_FRAGMENT_NODE=11,__=it.NOTATION_NODE=12,ve=ht.freeze({DOCUMENT_POSITION_DISCONNECTED:1,DOCUMENT_POSITION_PRECEDING:2,DOCUMENT_POSITION_FOLLOWING:4,DOCUMENT_POSITION_CONTAINS:8,DOCUMENT_POSITION_CONTAINED_BY:16,DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC:32});function qf(n,e){if(e.length<n.length)return qf(e,n);var t=null;for(var r in n){if(n[r]!==e[r])return t;t=n[r]}return t}function If(n){return n.guid||(n.guid=Math.random()),n.guid}function Ne(){}Ne.prototype={length:0,item:function(n){return n>=0&&n<this.length?this[n]:null},toString:function(n){var e;typeof n=="function"?e={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:n}:n?e={requireWellFormed:!!n.requireWellFormed,splitCDATASections:n.splitCDATASections!==!1,nodeFilter:n.nodeFilter||null}:e={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:null};for(var t=[],r=0;r<this.length;r++)yu(this[r],t,null,e);return t.join("")},filter:function(n){return Array.prototype.filter.call(this,n)},indexOf:function(n){return Array.prototype.indexOf.call(this,n)}};Ne.prototype[Symbol.iterator]=function(){var n=this,e=0;return{next:function(){return e<n.length?{value:n[e++],done:!1}:{done:!0}},return:function(){return{done:!0}}}};function Bt(n,e){this._node=n,this._refresh=e,$a(this)}function $a(n){var e=n._node._inc||n._node.ownerDocument._inc;if(n._inc!==e){var t=n._refresh(n._node);if(Jf(n,"length",t.length),!n.$$length||t.length<n.$$length)for(var r=t.length;r in n;r++)Ln(n,r)&&delete n[r];qn(t,n),n._inc=e}}Bt.prototype.item=function(n){return $a(this),this[n]||null};ot(Bt,Ne);function jn(){this._nsIndex=Object.create(null),this._noNsIndex=Object.create(null)}function Uf(n,e){for(var t=0;t<n.length;){if(n[t]===e)return t;t++}}function gu(n,e,t){if(!e)return n._noNsIndex;var r=n._nsIndex[e];return!r&&t&&(r=n._nsIndex[e]=Object.create(null)),r}function y_(n,e,t){var r=gu(n,e,!1),o=r&&r[t];return o||null}function v_(n,e){gu(n,e.namespaceURI,!0)[e.localName]=e}function E_(n,e){var t=gu(n,e.namespaceURI,!1);t&&delete t[e.localName]}function x_(n,e,t,r){if(r?e[Uf(e,r)]=t:(e[e.length]=t,e.length++),v_(e,t),n){t.ownerElement=n;var o=n.ownerDocument;o&&(r&&Hf(o,n,r),k_(o,n,t))}}function Of(n,e,t){var r=Uf(e,t);if(r>=0){for(var o=e.length-1;r<=o;)e[r]=e[++r];if(e.length=o,E_(e,t),n){var i=n.ownerDocument;i&&Hf(i,n,t),t.ownerElement=null}}}jn.prototype={length:0,item:Ne.prototype.item,getNamedItem:function(n){this._ownerElement&&this._ownerElement._isInHTMLDocumentAndNamespace()&&(n=n.toLowerCase());for(var e=0;e<this.length;){var t=this[e];if(t.nodeName===n)return t;e++}return null},setNamedItem:function(n){var e=n.ownerElement;if(e&&e!==this._ownerElement)throw new R(R.INUSE_ATTRIBUTE_ERR);var t=y_(this,n.namespaceURI,n.localName);return t===n?n:(x_(this._ownerElement,this,n,t),t)},setNamedItemNS:function(n){return this.setNamedItem(n)},removeNamedItem:function(n){var e=this.getNamedItem(n);if(!e)throw new R(R.NOT_FOUND_ERR,n);return Of(this._ownerElement,this,e),e},removeNamedItemNS:function(n,e){var t=this.getNamedItemNS(n,e);if(!t)throw new R(R.NOT_FOUND_ERR,n?n+" : "+e:e);return Of(this._ownerElement,this,t),t},getNamedItemNS:function(n,e){n||(n=null);for(var t=0;t<this.length;){var r=this[t];if(r.localName===e&&r.namespaceURI===n)return r;t++}return null}};jn.prototype[Symbol.iterator]=function(){var n=this,e=0;return{next:function(){return e<n.length?{value:n[e++],done:!1}:{done:!0}},return:function(){return{done:!0}}}};function Vf(){}Vf.prototype={hasFeature:function(n,e){return!0},createDocument:function(n,e,t){var r=Qo.XML_APPLICATION;n===Mt.HTML?r=Qo.XML_XHTML_APPLICATION:n===Mt.SVG&&(r=Qo.XML_SVG_IMAGE);var o=new Yt(Ye,{contentType:r});if(o.implementation=this,o.childNodes=new Ne,o.doctype=t||null,t&&o.appendChild(t),e){var i=o.createElementNS(n,e);o.appendChild(i)}return o},createDocumentType:function(n,e,t,r){Pf(n);var o=new La(Ye);return o.name=n,o.nodeName=n,o.publicId=e||"",o.systemId=t||"",o.internalSubset=r||"",o.childNodes=new Ne,o},createHTMLDocument:function(n){var e=new Yt(Ye,{contentType:Qo.HTML});if(e.implementation=this,e.childNodes=new Ne,n!==!1){e.doctype=this.createDocumentType("html"),e.doctype.ownerDocument=e,e.appendChild(e.doctype);var t=e.createElement("html");e.appendChild(t);var r=e.createElement("head");if(t.appendChild(r),typeof n=="string"){var o=e.createElement("title");o.appendChild(e.createTextNode(n)),r.appendChild(o)}t.appendChild(e.createElement("body"))}return e}};function J(n){nt(n)}J.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,parentNode:null,get parentElement(){return this.parentNode&&this.parentNode.nodeType===this.ELEMENT_NODE?this.parentNode:null},childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,baseURI:"about:blank",get isConnected(){var n=this.getRootNode();return n&&n.nodeType===n.DOCUMENT_NODE},contains:function(n){if(!n)return!1;var e=n;do{if(this===e)return!0;e=e.parentNode}while(e);return!1},getRootNode:function(n){var e=this;do{if(!e.parentNode)return e;e=e.parentNode}while(e)},isEqualNode:function(n){if(!n)return!1;for(var e=[{node:this,other:n}];e.length>0;){var t=e.pop(),r=t.node,o=t.other;if(r.nodeType!==o.nodeType)return!1;switch(r.nodeType){case r.DOCUMENT_TYPE_NODE:if(r.name!==o.name||r.publicId!==o.publicId||r.systemId!==o.systemId)return!1;break;case r.ELEMENT_NODE:if(r.namespaceURI!==o.namespaceURI||r.prefix!==o.prefix||r.localName!==o.localName||r.attributes.length!==o.attributes.length)return!1;for(var i=0;i<r.attributes.length;i++){var a=r.attributes.item(i),s=o.getAttributeNodeNS(a.namespaceURI,a.localName);if(!s)return!1;e.push({node:a,other:s})}break;case r.ATTRIBUTE_NODE:if(r.namespaceURI!==o.namespaceURI||r.localName!==o.localName||r.value!==o.value)return!1;break;case r.PROCESSING_INSTRUCTION_NODE:if(r.target!==o.target||r.data!==o.data)return!1;break;case r.TEXT_NODE:case r.CDATA_SECTION_NODE:case r.COMMENT_NODE:if(r.data!==o.data)return!1;break}if(r.childNodes.length!==o.childNodes.length)return!1;for(var i=r.childNodes.length-1;i>=0;i--)e.push({node:r.childNodes[i],other:o.childNodes[i]})}return!0},isSameNode:function(n){return this===n},insertBefore:function(n,e){return Ba(this,n,e)},replaceChild:function(n,e){Ba(this,n,e,Yf),e&&this.removeChild(e)},removeChild:function(n){return Gf(this,n)},appendChild:function(n){return this.insertBefore(n,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(n){return Kf(this.ownerDocument||this,this,n)},normalize:function(){Pe(this,null,{enter:function(n){for(var e=n.firstChild;e;){var t=e.nextSibling;if(t!==null&&t.nodeType===ei&&e.nodeType===ei){for(var r=[],o=t;o!==null&&o.nodeType===ei;)r.push(o.data),o=o.nextSibling;for(var i=e.nextSibling;i!==o;){var a=i.nextSibling;i.parentNode=null,i.previousSibling=null,i.nextSibling=null,i=a}e.nextSibling=o,o!==null?o.previousSibling=e:n.lastChild=e,e.appendData(r.join("")),bu(n.ownerDocument,n),e=o}else e=t}return!0}})},isSupported:function(n,e){return this.ownerDocument.implementation.hasFeature(n,e)},lookupPrefix:function(n){for(var e=this;e;){var t=e._nsMap;if(t){for(var r in t)if(Ln(t,r)&&t[r]===n)return r}e=e.nodeType==Fn?e.ownerDocument:e.parentNode}return null},lookupNamespaceURI:function(n){for(var e=this;e;){var t=e._nsMap;if(t&&Ln(t,n))return t[n];e=e.nodeType==Fn?e.ownerDocument:e.parentNode}return null},isDefaultNamespace:function(n){var e=this.lookupPrefix(n);return e==null},compareDocumentPosition:function(n){if(this===n)return 0;var e=n,t=this,r=null,o=null;if(e instanceof Hr&&(r=e,e=r.ownerElement),t instanceof Hr&&(o=t,t=o.ownerElement,r&&e&&t===e))for(var i=0,a;a=t.attributes[i];i++){if(a===r)return ve.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+ve.DOCUMENT_POSITION_PRECEDING;if(a===o)return ve.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+ve.DOCUMENT_POSITION_FOLLOWING}if(!e||!t||t.ownerDocument!==e.ownerDocument)return ve.DOCUMENT_POSITION_DISCONNECTED+ve.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+(If(t.ownerDocument)>If(e.ownerDocument)?ve.DOCUMENT_POSITION_FOLLOWING:ve.DOCUMENT_POSITION_PRECEDING);if(o&&e===t)return ve.DOCUMENT_POSITION_CONTAINS+ve.DOCUMENT_POSITION_PRECEDING;if(r&&e===t)return ve.DOCUMENT_POSITION_CONTAINED_BY+ve.DOCUMENT_POSITION_FOLLOWING;for(var s=[],l=e.parentNode;l;){if(!o&&l===t)return ve.DOCUMENT_POSITION_CONTAINED_BY+ve.DOCUMENT_POSITION_FOLLOWING;s.push(l),l=l.parentNode}s.reverse();for(var u=[],c=t.parentNode;c;){if(!r&&c===e)return ve.DOCUMENT_POSITION_CONTAINS+ve.DOCUMENT_POSITION_PRECEDING;u.push(c),c=c.parentNode}u.reverse();var d=qf(s,u);for(var f in d.childNodes){var h=d.childNodes[f];if(h===t)return ve.DOCUMENT_POSITION_FOLLOWING;if(h===e)return ve.DOCUMENT_POSITION_PRECEDING;if(u.indexOf(h)>=0)return ve.DOCUMENT_POSITION_FOLLOWING;if(s.indexOf(h)>=0)return ve.DOCUMENT_POSITION_PRECEDING}return 0}};function zf(n){return n=="<"&&"<"||n==">"&&">"||n=="&"&&"&"||n=='"'&&"""||"&#"+n.charCodeAt()+";"}qn(it,J);qn(it,J.prototype);qn(ve,J);qn(ve,J.prototype);function Ra(n,e){Pe(n,null,{enter:function(t){return e(t)?Pe.STOP:!0}})}function Pe(n,e,t){for(var r=[{node:n,context:e,phase:Pe.ENTER}];r.length>0;){var o=r.pop();if(o.phase===Pe.ENTER){var i=t.enter(o.node,o.context);if(i===Pe.STOP)return Pe.STOP;if(r.push({node:o.node,context:i,phase:Pe.EXIT}),i==null)continue;for(var a=o.node.lastChild;a;)r.push({node:a,context:i,phase:Pe.ENTER}),a=a.previousSibling}else t.exit&&t.exit(o.node,o.context)}}Pe.STOP=Symbol("walkDOM.STOP");Pe.ENTER=0;Pe.EXIT=1;function Yt(n,e){nt(n);var t=e||{};this.ownerDocument=this,this.contentType=t.contentType||Qo.XML_APPLICATION,this.type=d_(this.contentType)?"html":"xml"}function k_(n,e,t){n&&n._inc++;var r=t.namespaceURI;r===Mt.XMLNS&&(e._nsMap[t.prefix?t.localName:""]=t.value)}function Hf(n,e,t,r){n&&n._inc++;var o=t.namespaceURI;o===Mt.XMLNS&&delete e._nsMap[t.prefix?t.localName:""]}function bu(n,e,t){if(n&&n._inc){n._inc++;var r=e.childNodes;if(t&&!t.nextSibling)r[r.length++]=t;else{for(var o=e.firstChild,i=0;o;)r[i++]=o,o=o.nextSibling;r.length=i,delete r[r.length]}}}function Gf(n,e){if(n!==e.parentNode)throw new R(R.NOT_FOUND_ERR,"child's parent is not parent");var t=e.previousSibling,r=e.nextSibling;return t?t.nextSibling=r:n.firstChild=r,r?r.previousSibling=t:n.lastChild=t,bu(n.ownerDocument,n),e.parentNode=null,e.previousSibling=null,e.nextSibling=null,e}function T_(n){return n&&(n.nodeType===J.DOCUMENT_NODE||n.nodeType===J.DOCUMENT_FRAGMENT_NODE||n.nodeType===J.ELEMENT_NODE)}function A_(n){return n&&(n.nodeType===J.CDATA_SECTION_NODE||n.nodeType===J.COMMENT_NODE||n.nodeType===J.DOCUMENT_FRAGMENT_NODE||n.nodeType===J.DOCUMENT_TYPE_NODE||n.nodeType===J.ELEMENT_NODE||n.nodeType===J.PROCESSING_INSTRUCTION_NODE||n.nodeType===J.TEXT_NODE)}function br(n){return n&&n.nodeType===J.DOCUMENT_TYPE_NODE}function Wt(n){return n&&n.nodeType===J.ELEMENT_NODE}function Wf(n){return n&&n.nodeType===J.TEXT_NODE}function Rf(n,e){var t=n.childNodes||[];if($t(t,Wt)||br(e))return!1;var r=$t(t,br);return!(e&&r&&t.indexOf(r)>t.indexOf(e))}function Bf(n,e){var t=n.childNodes||[];function r(i){return Wt(i)&&i!==e}if($t(t,r))return!1;var o=$t(t,br);return!(e&&o&&t.indexOf(o)>t.indexOf(e))}function D_(n,e,t){if(!T_(n))throw new R(R.HIERARCHY_REQUEST_ERR,"Unexpected parent node type "+n.nodeType);if(t&&t.parentNode!==n)throw new R(R.NOT_FOUND_ERR,"child not in parent");if(!A_(e)||br(e)&&n.nodeType!==J.DOCUMENT_NODE)throw new R(R.HIERARCHY_REQUEST_ERR,"Unexpected node type "+e.nodeType+" for parent node type "+n.nodeType)}function S_(n,e,t){var r=n.childNodes||[],o=e.childNodes||[];if(e.nodeType===J.DOCUMENT_FRAGMENT_NODE){var i=o.filter(Wt);if(i.length>1||$t(o,Wf))throw new R(R.HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(i.length===1&&!Rf(n,t))throw new R(R.HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(Wt(e)&&!Rf(n,t))throw new R(R.HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(br(e)){if($t(r,br))throw new R(R.HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var a=$t(r,Wt);if(t&&r.indexOf(a)<r.indexOf(t))throw new R(R.HIERARCHY_REQUEST_ERR,"Doctype can only be inserted before an element");if(!t&&a)throw new R(R.HIERARCHY_REQUEST_ERR,"Doctype can not be appended since element is present")}}function Yf(n,e,t){var r=n.childNodes||[],o=e.childNodes||[];if(e.nodeType===J.DOCUMENT_FRAGMENT_NODE){var i=o.filter(Wt);if(i.length>1||$t(o,Wf))throw new R(R.HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(i.length===1&&!Bf(n,t))throw new R(R.HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(Wt(e)&&!Bf(n,t))throw new R(R.HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(br(e)){if($t(r,function(l){return br(l)&&l!==t}))throw new R(R.HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var a=$t(r,Wt);if(t&&r.indexOf(a)<r.indexOf(t))throw new R(R.HIERARCHY_REQUEST_ERR,"Doctype can only be inserted before an element")}}function Ba(n,e,t,r){D_(n,e,t),n.nodeType===J.DOCUMENT_NODE&&(r||S_)(n,e,t);var o=e.parentNode;if(o&&o.removeChild(e),e.nodeType===gr){var i=e.firstChild;if(i==null)return e;var a=e.lastChild}else i=a=e;var s=t?t.previousSibling:n.lastChild;i.previousSibling=s,a.nextSibling=t,s?s.nextSibling=i:n.firstChild=i,t==null?n.lastChild=a:t.previousSibling=a;do i.parentNode=n;while(i!==a&&(i=i.nextSibling));return bu(n.ownerDocument||n,n,e),e.nodeType==gr&&(e.firstChild=e.lastChild=null),e}Yt.prototype={implementation:null,nodeName:"#document",nodeType:Pn,doctype:null,documentElement:null,_inc:1,insertBefore:function(n,e){if(n.nodeType===gr){for(var t=n.firstChild;t;){var r=t.nextSibling;this.insertBefore(t,e),t=r}return n}return Ba(this,n,e),n.ownerDocument=this,this.documentElement===null&&n.nodeType===ft&&(this.documentElement=n),n},removeChild:function(n){var e=Gf(this,n);return e===this.documentElement&&(this.documentElement=null),e},replaceChild:function(n,e){Ba(this,n,e,Yf),n.ownerDocument=this,e&&this.removeChild(e),Wt(n)&&(this.documentElement=n)},importNode:function(n,e){return C_(this,n,e)},getElementById:function(n){var e=null;return Ra(this.documentElement,function(t){if(t.nodeType==ft&&t.getAttribute("id")==n)return e=t,!0}),e},createElement:function(n){var e=new Xt(Ye);e.ownerDocument=this,this.type==="html"&&(n=n.toLowerCase()),c_(this.contentType)&&(e.namespaceURI=Mt.HTML),e.nodeName=n,e.tagName=n,e.localName=n,e.childNodes=new Ne;var t=e.attributes=new jn;return t._ownerElement=e,e},createDocumentFragment:function(){var n=new Un(Ye);return n.ownerDocument=this,n.childNodes=new Ne,n},createTextNode:function(n){var e=new ti(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.appendData(n),e},createComment:function(n){var e=new Ma(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.appendData(n),e},createCDATASection:function(n){if(n.indexOf("]]>")!==-1)throw new R(R.INVALID_CHARACTER_ERR,'data contains "]]>"');var e=new Pa(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.appendData(n),e},createProcessingInstruction:function(n,e){var t=new ja(Ye);return t.ownerDocument=this,t.childNodes=new Ne,t.nodeName=t.target=n,t.nodeValue=t.data=e,t},createAttribute:function(n){if(!Ee.QName_exact.test(n))throw new R(R.INVALID_CHARACTER_ERR,'invalid character in name "'+n+'"');return this.type==="html"&&(n=n.toLowerCase()),this._createAttribute(n)},_createAttribute:function(n){var e=new Hr(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.name=n,e.nodeName=n,e.localName=n,e.specified=!0,e},createEntityReference:function(n){if(!Ee.Name_exact.test(n))throw new R(R.INVALID_CHARACTER_ERR,'not a valid xml name "'+n+'"');if(this.type==="html")throw new R("document is an html document",He.NotSupportedError);var e=new Fa(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.nodeName=n,e},createElementNS:function(n,e){var t=hu(n,e),r=new Xt(Ye),o=r.attributes=new jn;return r.childNodes=new Ne,r.ownerDocument=this,r.nodeName=e,r.tagName=e,r.namespaceURI=t[0],r.prefix=t[1],r.localName=t[2],o._ownerElement=r,r},createAttributeNS:function(n,e){var t=hu(n,e),r=new Hr(Ye);return r.ownerDocument=this,r.childNodes=new Ne,r.nodeName=e,r.name=e,r.specified=!0,r.namespaceURI=t[0],r.prefix=t[1],r.localName=t[2],r}};ot(Yt,J);function Xt(n){nt(n),this._nsMap=Object.create(null)}Xt.prototype={nodeType:ft,attributes:null,getQualifiedName:function(){return this.prefix?this.prefix+":"+this.localName:this.localName},_isInHTMLDocumentAndNamespace:function(){return this.ownerDocument.type==="html"&&this.namespaceURI===Mt.HTML},hasAttributes:function(){return!!(this.attributes&&this.attributes.length)},hasAttribute:function(n){return!!this.getAttributeNode(n)},getAttribute:function(n){var e=this.getAttributeNode(n);return e?e.value:null},getAttributeNode:function(n){return this._isInHTMLDocumentAndNamespace()&&(n=n.toLowerCase()),this.attributes.getNamedItem(n)},setAttribute:function(n,e){this._isInHTMLDocumentAndNamespace()&&(n=n.toLowerCase());var t=this.getAttributeNode(n);t?t.value=t.nodeValue=""+e:(t=this.ownerDocument._createAttribute(n),t.value=t.nodeValue=""+e,this.setAttributeNode(t))},removeAttribute:function(n){var e=this.getAttributeNode(n);e&&this.removeAttributeNode(e)},setAttributeNode:function(n){return this.attributes.setNamedItem(n)},setAttributeNodeNS:function(n){return this.attributes.setNamedItemNS(n)},removeAttributeNode:function(n){return this.attributes.removeNamedItem(n.nodeName)},removeAttributeNS:function(n,e){var t=this.getAttributeNodeNS(n,e);t&&this.removeAttributeNode(t)},hasAttributeNS:function(n,e){return this.getAttributeNodeNS(n,e)!=null},getAttributeNS:function(n,e){var t=this.getAttributeNodeNS(n,e);return t?t.value:null},setAttributeNS:function(n,e,t){var r=hu(n,e),o=r[2],i=this.getAttributeNodeNS(n,o);i?i.value=i.nodeValue=""+t:(i=this.ownerDocument.createAttributeNS(n,e),i.value=i.nodeValue=""+t,this.setAttributeNode(i))},getAttributeNodeNS:function(n,e){return this.attributes.getNamedItemNS(n,e)},getElementsByClassName:function(n){var e=Nf(n);return new Bt(this,function(t){var r=[];return e.length>0&&Ra(t,function(o){if(o!==t&&o.nodeType===ft){var i=o.getAttribute("class");if(i){var a=n===i;if(!a){var s=Nf(i);a=e.every(b_(s))}a&&r.push(o)}}}),r})},getElementsByTagName:function(n){var e=(this.nodeType===Pn?this:this.ownerDocument).type==="html",t=n.toLowerCase();return new Bt(this,function(r){var o=[];return Ra(r,function(i){if(!(i===r||i.nodeType!==ft))if(n==="*")o.push(i);else{var a=i.getQualifiedName(),s=e&&i.namespaceURI===Mt.HTML?t:n;a===s&&o.push(i)}}),o})},getElementsByTagNameNS:function(n,e){return new Bt(this,function(t){var r=[];return Ra(t,function(o){o!==t&&o.nodeType===ft&&(n==="*"||o.namespaceURI===n)&&(e==="*"||o.localName==e)&&r.push(o)}),r})}};Yt.prototype.getElementsByClassName=Xt.prototype.getElementsByClassName;Yt.prototype.getElementsByTagName=Xt.prototype.getElementsByTagName;Yt.prototype.getElementsByTagNameNS=Xt.prototype.getElementsByTagNameNS;ot(Xt,J);function Hr(n){nt(n),this.namespaceURI=null,this.prefix=null,this.ownerElement=null}Hr.prototype.nodeType=Fn;ot(Hr,J);function wr(n){nt(n)}wr.prototype={data:"",substringData:function(n,e){return this.data.substring(n,n+e)},appendData:function(n){n=this.data+n,this.nodeValue=this.data=n,this.length=n.length},insertData:function(n,e){this.replaceData(n,0,e)},deleteData:function(n,e){this.replaceData(n,e,"")},replaceData:function(n,e,t){var r=this.data.substring(0,n),o=this.data.substring(n+e);t=r+t+o,this.nodeValue=this.data=t,this.length=t.length}};ot(wr,J);function ti(n){nt(n)}ti.prototype={nodeName:"#text",nodeType:ei,splitText:function(n){var e=this.data,t=e.substring(n);e=e.substring(0,n),this.data=this.nodeValue=e,this.length=e.length;var r=this.ownerDocument.createTextNode(t);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}};ot(ti,wr);function Ma(n){nt(n)}Ma.prototype={nodeName:"#comment",nodeType:mu};ot(Ma,wr);function Pa(n){nt(n)}Pa.prototype={nodeName:"#cdata-section",nodeType:Lf};ot(Pa,ti);function La(n){nt(n)}La.prototype.nodeType=jf;ot(La,J);function wu(n){nt(n)}wu.prototype.nodeType=__;ot(wu,J);function _u(n){nt(n)}_u.prototype.nodeType=w_;ot(_u,J);function Fa(n){nt(n)}Fa.prototype.nodeType=Ff;ot(Fa,J);function Un(n){nt(n)}Un.prototype.nodeName="#document-fragment";Un.prototype.nodeType=gr;ot(Un,J);function ja(n){nt(n)}ja.prototype.nodeType=pu;ot(ja,wr);function Xf(){}Xf.prototype.serializeToString=function(n,e){return Zf.call(n,e)};J.prototype.toString=Zf;function Zf(n){var e;typeof n=="function"?e={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:n}:n!=null?e={requireWellFormed:!!n.requireWellFormed,splitCDATASections:n.splitCDATASections!==!1,nodeFilter:n.nodeFilter||null}:e={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:null};var t=[],r=this.nodeType===Pn&&this.documentElement||this,o=r.prefix,i=r.namespaceURI;if(i&&o==null){var o=r.lookupPrefix(i);if(o==null)var a=[{namespace:i,prefix:null}]}return yu(this,t,a,e),t.join("")}function $f(n,e,t){var r=n.prefix||"",o=n.namespaceURI;if(!o||r==="xml"&&o===Mt.XML||o===Mt.XMLNS)return!1;for(var i=t.length;i--;){var a=t[i];if(a.prefix===r)return a.namespace!==o}return!0}function Oa(n,e,t,r){if(r&&!Ee.QName_exact.test(e))throw new R('The attribute name "'+e+'" is not a valid XML QName',He.InvalidStateError);n.push(" ",e,'="',t.replace(/[<>&"\t\n\r]/g,zf),'"')}function yu(n,e,t,r){t||(t=[]);var o=r.nodeFilter,i=r.requireWellFormed,a=r.splitCDATASections,s=n.nodeType===Pn?n:n.ownerDocument,l=s.type==="html";Pe(n,{ns:t},{enter:function(u,c){var d=c.ns;if(o)if(u=o(u),u){if(typeof u=="string")return e.push(u),null}else return null;switch(u.nodeType){case ft:var f=u.attributes,h=f.length,p=u.tagName,m=p;if(!l&&!u.prefix&&u.namespaceURI){for(var b,w=0;w<f.length;w++)if(f.item(w).name==="xmlns"){b=f.item(w).value;break}if(!b)for(var _=d.length-1;_>=0;_--){var y=d[_];if(y.prefix===""&&y.namespace===u.namespaceURI){b=y.namespace;break}}if(b!==u.namespaceURI)for(var _=d.length-1;_>=0;_--){var y=d[_];if(y.namespace===u.namespaceURI){y.prefix&&(m=y.prefix+":"+p);break}}}if(i&&!Ee.QName_exact.test(m))throw new R('The element name "'+m+'" is not a valid XML QName',He.InvalidStateError);e.push("<",m);for(var x=d.slice(),S=0;S<h;S++){var k=f.item(S);k.prefix=="xmlns"?x.push({prefix:k.localName,namespace:k.value}):k.nodeName=="xmlns"&&x.push({prefix:"",namespace:k.value})}for(var S=0;S<h;S++){var k=f.item(S);if($f(k,l,x)){var N=k.prefix||"",O=k.namespaceURI;Oa(e,N?"xmlns:"+N:"xmlns",O,i),x.push({prefix:N,namespace:O})}var $=o?o(k):k;$&&(typeof $=="string"?e.push($):Oa(e,$.name,$.value,i))}if(p===m&&$f(u,l,x)){var ee=u.prefix||"",O=u.namespaceURI;Oa(e,ee?"xmlns:"+ee:"xmlns",O,i),x.push({prefix:ee,namespace:O})}var W=!u.firstChild;if(W&&(l||u.namespaceURI===Mt.HTML)&&(W=h_(p)),W)return e.push("/>"),null;if(e.push(">"),l&&f_(p)){for(var se=u.firstChild;se;)se.data?e.push(se.data):yu(se,e,x.slice(),r),se=se.nextSibling;return e.push("</",m,">"),null}return{ns:x,tag:m};case Pn:case gr:if(i&&u.nodeType===Pn&&u.documentElement==null)throw new R("The Document has no documentElement",He.InvalidStateError);return{ns:d};case Fn:return Oa(e,u.name,u.value,i),null;case ei:if(i&&Ee.InvalidChar.test(u.data))throw new R("The Text node data contains characters outside the XML Char production",He.InvalidStateError);return e.push(u.data.replace(/[<&>]/g,zf)),null;case Lf:if(i&&u.data.indexOf("]]>")!==-1)throw new R('The CDATASection data contains "]]>"',He.InvalidStateError);return a?e.push(Ee.CDATA_START,u.data.replace(/]]>/g,"]]]]><![CDATA[>"),Ee.CDATA_END):e.push(Ee.CDATA_START,u.data,Ee.CDATA_END),null;case mu:if(i){if(Ee.InvalidChar.test(u.data))throw new R("The comment node data contains characters outside the XML Char production",He.InvalidStateError);if(u.data.indexOf("--")!==-1||u.data[u.data.length-1]==="-")throw new R('The comment node data contains "--" or ends with "-"',He.InvalidStateError)}return e.push(Ee.COMMENT_START,u.data,Ee.COMMENT_END),null;case jf:var me=u.publicId,te=u.systemId;if(i){if(!Ee.Name_exact.test(u.name))throw new R('The doctype name "'+u.name+'" is not a valid XML Name',He.InvalidStateError);if(me&&!Ee.PubidLiteral_match.test(me))throw new R("DocumentType publicId is not a valid PubidLiteral",He.InvalidStateError);if(te&&te!=="."&&!Ee.SystemLiteral_match.test(te))throw new R("DocumentType systemId is not a valid SystemLiteral",He.InvalidStateError);if(u.internalSubset&&u.internalSubset.indexOf("]>")!==-1)throw new R('DocumentType internalSubset contains "]>"',He.InvalidStateError)}return e.push(Ee.DOCTYPE_DECL_START," ",u.name),me?(e.push(" ",Ee.PUBLIC," ",me),te&&te!=="."&&e.push(" ",te)):te&&te!=="."&&e.push(" ",Ee.SYSTEM," ",te),u.internalSubset&&e.push(" [",u.internalSubset,"]"),e.push(">"),null;case pu:if(i){if(!Ee.NCName_exact.test(u.target)||u.target.toLowerCase()==="xml")throw new R('The processing instruction target "'+u.target+'" is not a valid XML NCName or is reserved',He.InvalidStateError);if(Ee.InvalidChar.test(u.data))throw new R("The ProcessingInstruction data contains characters outside the XML Char production",He.InvalidStateError);if(u.data.indexOf("?>")!==-1)throw new R('The ProcessingInstruction data contains "?>"',He.InvalidStateError)}return e.push("<?",u.target," ",u.data,"?>"),null;case Ff:if(i&&!Ee.Name_exact.test(u.nodeName))throw new R('The entity reference name "'+u.nodeName+'" is not a valid XML Name',He.InvalidStateError);return e.push("&",u.nodeName,";"),null;default:return e.push("??",u.nodeName),null}},exit:function(u,c){c&&c.tag&&e.push("</",c.tag,">")}})}function C_(n,e,t){var r;return Pe(e,null,{enter:function(o,i){var a=o.cloneNode(!1);a.ownerDocument=n,a.parentNode=null,i===null?r=a:i.appendChild(a);var s=o.nodeType===Fn||t;return s?a:null}}),r}function Kf(n,e,t){var r;return Pe(e,null,{enter:function(o,i){var a=new o.constructor(Ye);for(var s in o)if(Ln(o,s)){var l=o[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}o.childNodes&&(a.childNodes=new Ne),a.ownerDocument=n;var u=t;switch(a.nodeType){case ft:var c=o.attributes,d=a.attributes=new jn,f=c.length;d._ownerElement=a;for(var h=0;h<f;h++)a.setAttributeNode(Kf(n,c.item(h),!0));break;case Fn:u=!0}return i!==null?i.appendChild(a):r=a,u?a:null}}),r}function Jf(n,e,t){n[e]=t}function fu(n){for(var e=[],t=n.firstChild;t;)t.nodeType===ft&&e.push(t),t=t.nextSibling;return e}try{Object.defineProperty&&(Object.defineProperty(Bt.prototype,"length",{get:function(){return $a(this),this.$$length}}),Object.defineProperty(J.prototype,"textContent",{get:function(){if(this.nodeType===ft||this.nodeType===gr){var n=[];return Pe(this,null,{enter:function(e){if(e.nodeType===ft||e.nodeType===gr)return!0;if(e.nodeType===pu||e.nodeType===mu)return null;n.push(e.nodeValue)}}),n.join("")}return this.nodeValue},set:function(n){switch(this.nodeType){case ft:case gr:for(;this.firstChild;)this.removeChild(this.firstChild);(n||String(n))&&this.appendChild(this.ownerDocument.createTextNode(n));break;default:this.data=n,this.value=n,this.nodeValue=n}}}),Object.defineProperty(wr.prototype,"data",{get:function(){return this._data!=null?this._data:""},set:function(n){this._data=n,this.length=typeof n=="string"?n.length:0}}),Object.defineProperty(wr.prototype,"nodeValue",{get:function(){return this.data},set:function(n){this.data=n},enumerable:!0,configurable:!0}),Object.defineProperty(Xt.prototype,"children",{get:function(){return new Bt(this,fu)}}),Object.defineProperty(Yt.prototype,"children",{get:function(){return new Bt(this,fu)}}),Object.defineProperty(Un.prototype,"children",{get:function(){return new Bt(this,fu)}}),Jf=function(n,e,t){n["$$"+e]=t})}catch{}xe._updateLiveList=$a;xe.Attr=Hr;xe.CDATASection=Pa;xe.CharacterData=wr;xe.Comment=Ma;xe.Document=Yt;xe.DocumentFragment=Un;xe.DocumentType=La;xe.DOMImplementation=Vf;xe.Element=Xt;xe.Entity=_u;xe.EntityReference=Fa;xe.LiveNodeList=Bt;xe.NamedNodeMap=jn;xe.Node=J;xe.NodeList=Ne;xe.Notation=wu;xe.Text=ti;xe.ProcessingInstruction=ja;xe.walkDOM=Pe;xe.XMLSerializer=Xf});var eh=sr(ri=>{"use strict";var Qf=zr().freeze;ri.XML_ENTITIES=Qf({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});ri.HTML_ENTITIES=Qf({Aacute:"\xC1",aacute:"\xE1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223E",acd:"\u223F",acE:"\u223E\u0333",Acirc:"\xC2",acirc:"\xE2",acute:"\xB4",Acy:"\u0410",acy:"\u0430",AElig:"\xC6",aelig:"\xE6",af:"\u2061",Afr:"\u{1D504}",afr:"\u{1D51E}",Agrave:"\xC0",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03B1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2A3F",AMP:"&",amp:"&",And:"\u2A53",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",Aogon:"\u0104",aogon:"\u0105",Aopf:"\u{1D538}",aopf:"\u{1D552}",ap:"\u2248",apacir:"\u2A6F",apE:"\u2A70",ape:"\u224A",apid:"\u224B",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224A",Aring:"\xC5",aring:"\xE5",Ascr:"\u{1D49C}",ascr:"\u{1D4B6}",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224D",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",Backslash:"\u2216",Barv:"\u2AE7",barvee:"\u22BD",Barwed:"\u2306",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",Because:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",Bernoullis:"\u212C",Beta:"\u0392",beta:"\u03B2",beth:"\u2136",between:"\u226C",Bfr:"\u{1D505}",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bNot:"\u2AED",bnot:"\u2310",Bopf:"\u{1D539}",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxbox:"\u29C9",boxDL:"\u2557",boxDl:"\u2556",boxdL:"\u2555",boxdl:"\u2510",boxDR:"\u2554",boxDr:"\u2553",boxdR:"\u2552",boxdr:"\u250C",boxH:"\u2550",boxh:"\u2500",boxHD:"\u2566",boxHd:"\u2564",boxhD:"\u2565",boxhd:"\u252C",boxHU:"\u2569",boxHu:"\u2567",boxhU:"\u2568",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxUL:"\u255D",boxUl:"\u255C",boxuL:"\u255B",boxul:"\u2518",boxUR:"\u255A",boxUr:"\u2559",boxuR:"\u2558",boxur:"\u2514",boxV:"\u2551",boxv:"\u2502",boxVH:"\u256C",boxVh:"\u256B",boxvH:"\u256A",boxvh:"\u253C",boxVL:"\u2563",boxVl:"\u2562",boxvL:"\u2561",boxvl:"\u2524",boxVR:"\u2560",boxVr:"\u255F",boxvR:"\u255E",boxvr:"\u251C",bprime:"\u2035",Breve:"\u02D8",breve:"\u02D8",brvbar:"\xA6",Bscr:"\u212C",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",Bumpeq:"\u224E",bumpeq:"\u224F",Cacute:"\u0106",cacute:"\u0107",Cap:"\u22D2",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",CapitalDifferentialD:"\u2145",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",Cayleys:"\u212D",ccaps:"\u2A4D",Ccaron:"\u010C",ccaron:"\u010D",Ccedil:"\xC7",ccedil:"\xE7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2A4C",ccupssm:"\u2A50",Cdot:"\u010A",cdot:"\u010B",cedil:"\xB8",Cedilla:"\xB8",cemptyv:"\u29B2",cent:"\xA2",CenterDot:"\xB7",centerdot:"\xB7",Cfr:"\u212D",cfr:"\u{1D520}",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03A7",chi:"\u03C7",cir:"\u25CB",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",CircleDot:"\u2299",circledR:"\xAE",circledS:"\u24C8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cirE:"\u29C3",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",Colon:"\u2237",colon:":",Colone:"\u2A74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",Congruent:"\u2261",Conint:"\u222F",conint:"\u222E",ContourIntegral:"\u222E",Copf:"\u2102",copf:"\u{1D554}",coprod:"\u2210",Coproduct:"\u2210",COPY:"\xA9",copy:"\xA9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21B5",Cross:"\u2A2F",cross:"\u2717",Cscr:"\u{1D49E}",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",Cup:"\u22D3",cup:"\u222A",cupbrcap:"\u2A48",CupCap:"\u224D",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",Dagger:"\u2021",dagger:"\u2020",daleth:"\u2138",Darr:"\u21A1",dArr:"\u21D3",darr:"\u2193",dash:"\u2010",Dashv:"\u2AE4",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",Dcaron:"\u010E",dcaron:"\u010F",Dcy:"\u0414",dcy:"\u0434",DD:"\u2145",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",DDotrahd:"\u2911",ddotseq:"\u2A77",deg:"\xB0",Del:"\u2207",Delta:"\u0394",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",Dfr:"\u{1D507}",dfr:"\u{1D521}",dHar:"\u2965",dharl:"\u21C3",dharr:"\u21C2",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",diam:"\u22C4",Diamond:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",DifferentialD:"\u2146",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",Dopf:"\u{1D53B}",dopf:"\u{1D555}",Dot:"\xA8",dot:"\u02D9",DotDot:"\u20DC",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",Downarrow:"\u21D3",downarrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",Dscr:"\u{1D49F}",dscr:"\u{1D4B9}",DScy:"\u0405",dscy:"\u0455",dsol:"\u29F6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",DZcy:"\u040F",dzcy:"\u045F",dzigrarr:"\u27FF",Eacute:"\xC9",eacute:"\xE9",easter:"\u2A6E",Ecaron:"\u011A",ecaron:"\u011B",ecir:"\u2256",Ecirc:"\xCA",ecirc:"\xEA",ecolon:"\u2255",Ecy:"\u042D",ecy:"\u044D",eDDot:"\u2A77",Edot:"\u0116",eDot:"\u2251",edot:"\u0117",ee:"\u2147",efDot:"\u2252",Efr:"\u{1D508}",efr:"\u{1D522}",eg:"\u2A9A",Egrave:"\xC8",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",Element:"\u2208",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25FB",emptyv:"\u2205",EmptyVerySmallSquare:"\u25AB",emsp:"\u2003",emsp13:"\u2004",emsp14:"\u2005",ENG:"\u014A",eng:"\u014B",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\u{1D53C}",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",Equal:"\u2A75",equals:"=",EqualTilde:"\u2242",equest:"\u225F",Equilibrium:"\u21CC",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erarr:"\u2971",erDot:"\u2253",Escr:"\u2130",escr:"\u212F",esdot:"\u2250",Esim:"\u2A73",esim:"\u2242",Eta:"\u0397",eta:"\u03B7",ETH:"\xD0",eth:"\xF0",Euml:"\xCB",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",ExponentialE:"\u2147",exponentiale:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",Ffr:"\u{1D509}",ffr:"\u{1D523}",filig:"\uFB01",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",Fopf:"\u{1D53D}",fopf:"\u{1D557}",ForAll:"\u2200",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",Fouriertrf:"\u2131",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",Fscr:"\u2131",fscr:"\u{1D4BB}",gacute:"\u01F5",Gamma:"\u0393",gamma:"\u03B3",Gammad:"\u03DC",gammad:"\u03DD",gap:"\u2A86",Gbreve:"\u011E",gbreve:"\u011F",Gcedil:"\u0122",Gcirc:"\u011C",gcirc:"\u011D",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",gE:"\u2267",ge:"\u2265",gEl:"\u2A8C",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",Gfr:"\u{1D50A}",gfr:"\u{1D524}",Gg:"\u22D9",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gl:"\u2277",gla:"\u2AA5",glE:"\u2A92",glj:"\u2AA4",gnap:"\u2A8A",gnapprox:"\u2A8A",gnE:"\u2269",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",Gopf:"\u{1D53E}",gopf:"\u{1D558}",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",Gt:"\u226B",GT:">",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",Hacek:"\u02C7",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",HARDcy:"\u042A",hardcy:"\u044A",hArr:"\u21D4",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",Hat:"^",hbar:"\u210F",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",Hfr:"\u210C",hfr:"\u{1D525}",HilbertSpace:"\u210B",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",Hopf:"\u210D",hopf:"\u{1D559}",horbar:"\u2015",HorizontalLine:"\u2500",Hscr:"\u210B",hscr:"\u{1D4BD}",hslash:"\u210F",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224E",HumpEqual:"\u224F",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xCD",iacute:"\xED",ic:"\u2063",Icirc:"\xCE",icirc:"\xEE",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",Ifr:"\u2111",ifr:"\u{1D526}",Igrave:"\xCC",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Im:"\u2111",Imacr:"\u012A",imacr:"\u012B",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",Implies:"\u21D2",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",Int:"\u222C",int:"\u222B",intcal:"\u22BA",integers:"\u2124",Integral:"\u222B",intercal:"\u22BA",Intersection:"\u22C2",intlarhk:"\u2A17",intprod:"\u2A3C",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012E",iogon:"\u012F",Iopf:"\u{1D540}",iopf:"\u{1D55A}",Iota:"\u0399",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",Iscr:"\u2110",iscr:"\u{1D4BE}",isin:"\u2208",isindot:"\u22F5",isinE:"\u22F9",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xCF",iuml:"\xEF",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\u{1D50D}",jfr:"\u{1D527}",jmath:"\u0237",Jopf:"\u{1D541}",jopf:"\u{1D55B}",Jscr:"\u{1D4A5}",jscr:"\u{1D4BF}",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041A",kcy:"\u043A",Kfr:"\u{1D50E}",kfr:"\u{1D528}",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040C",kjcy:"\u045C",Kopf:"\u{1D542}",kopf:"\u{1D55C}",Kscr:"\u{1D4A6}",kscr:"\u{1D4C0}",lAarr:"\u21DA",Lacute:"\u0139",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",Lambda:"\u039B",lambda:"\u03BB",Lang:"\u27EA",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",Laplacetrf:"\u2112",laquo:"\xAB",Larr:"\u219E",lArr:"\u21D0",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",lAtail:"\u291B",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lBarr:"\u290E",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",Lcaron:"\u013D",lcaron:"\u013E",Lcedil:"\u013B",lcedil:"\u013C",lceil:"\u2308",lcub:"{",Lcy:"\u041B",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",lE:"\u2266",le:"\u2264",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",Leftarrow:"\u21D0",leftarrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",leftarrowtail:"\u21A2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",LeftRightArrow:"\u2194",Leftrightarrow:"\u21D4",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",leftthreetimes:"\u22CB",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",lEg:"\u2A8B",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2AA1",lesssim:"\u2272",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",lfisht:"\u297C",lfloor:"\u230A",Lfr:"\u{1D50F}",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lHar:"\u2962",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",Ll:"\u22D8",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",Lleftarrow:"\u21DA",llhard:"\u296B",lltri:"\u25FA",Lmidot:"\u013F",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnap:"\u2A89",lnapprox:"\u2A89",lnE:"\u2268",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",LongLeftArrow:"\u27F5",Longleftarrow:"\u27F8",longleftarrow:"\u27F5",LongLeftRightArrow:"\u27F7",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",LongRightArrow:"\u27F6",Longrightarrow:"\u27F9",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",Lopf:"\u{1D543}",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",Lscr:"\u2112",lscr:"\u{1D4C1}",Lsh:"\u21B0",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",Lstrok:"\u0141",lstrok:"\u0142",Lt:"\u226A",LT:"<",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",ltrPar:"\u2996",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",Mcy:"\u041C",mcy:"\u043C",mdash:"\u2014",mDDot:"\u223A",measuredangle:"\u2221",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",MinusPlus:"\u2213",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",Mopf:"\u{1D544}",mopf:"\u{1D55E}",mp:"\u2213",Mscr:"\u2133",mscr:"\u{1D4C2}",mstpos:"\u223E",Mu:"\u039C",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",Ncy:"\u041D",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",nearhk:"\u2924",neArr:"\u21D7",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`
|
|
10
|
-
`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29BF",Ofr:"\u{1D512}",ofr:"\u{1D52C}",ogon:"\u02DB",Ograve:"\xD2",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",Omacr:"\u014C",omacr:"\u014D",Omega:"\u03A9",omega:"\u03C9",Omicron:"\u039F",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",Oopf:"\u{1D546}",oopf:"\u{1D560}",opar:"\u29B7",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",operp:"\u29B9",oplus:"\u2295",Or:"\u2A54",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oS:"\u24C8",Oscr:"\u{1D4AA}",oscr:"\u2134",Oslash:"\xD8",oslash:"\xF8",osol:"\u2298",Otilde:"\xD5",otilde:"\xF5",Otimes:"\u2A37",otimes:"\u2297",otimesas:"\u2A36",Ouml:"\xD6",ouml:"\xF6",ovbar:"\u233D",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",PartialD:"\u2202",Pcy:"\u041F",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",Pfr:"\u{1D513}",pfr:"\u{1D52D}",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",Pi:"\u03A0",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",PlusMinus:"\xB1",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",Poincareplane:"\u210C",pointint:"\u2A15",Popf:"\u2119",popf:"\u{1D561}",pound:"\xA3",Pr:"\u2ABB",pr:"\u227A",prap:"\u2AB7",prcue:"\u227C",prE:"\u2AB3",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",Prime:"\u2033",prime:"\u2032",primes:"\u2119",prnap:"\u2AB9",prnE:"\u2AB5",prnsim:"\u22E8",prod:"\u220F",Product:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",Proportion:"\u2237",Proportional:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",Pscr:"\u{1D4AB}",pscr:"\u{1D4C5}",Psi:"\u03A8",psi:"\u03C8",puncsp:"\u2008",Qfr:"\u{1D514}",qfr:"\u{1D52E}",qint:"\u2A0C",Qopf:"\u211A",qopf:"\u{1D562}",qprime:"\u2057",Qscr:"\u{1D4AC}",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",QUOT:'"',quot:'"',rAarr:"\u21DB",race:"\u223D\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",Rang:"\u27EB",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",Rarr:"\u21A0",rArr:"\u21D2",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21A3",rarrw:"\u219D",rAtail:"\u291C",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",RBarr:"\u2910",rBarr:"\u290F",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",Re:"\u211C",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",REG:"\xAE",reg:"\xAE",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",rfisht:"\u297D",rfloor:"\u230B",Rfr:"\u211C",rfr:"\u{1D52F}",rHar:"\u2964",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",Rightarrow:"\u21D2",rightarrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",rightarrowtail:"\u21A3",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",rightthreetimes:"\u22CC",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",Ropf:"\u211D",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",Rrightarrow:"\u21DB",rsaquo:"\u203A",Rscr:"\u211B",rscr:"\u{1D4C7}",Rsh:"\u21B1",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",RuleDelayed:"\u29F4",ruluhar:"\u2968",rx:"\u211E",Sacute:"\u015A",sacute:"\u015B",sbquo:"\u201A",Sc:"\u2ABC",sc:"\u227B",scap:"\u2AB8",Scaron:"\u0160",scaron:"\u0161",sccue:"\u227D",scE:"\u2AB4",sce:"\u2AB0",Scedil:"\u015E",scedil:"\u015F",Scirc:"\u015C",scirc:"\u015D",scnap:"\u2ABA",scnE:"\u2AB6",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",Scy:"\u0421",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",searhk:"\u2925",seArr:"\u21D8",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\u{1D516}",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xAD",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",SOFTcy:"\u042C",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",Sopf:"\u{1D54A}",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",Sqrt:"\u221A",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",Square:"\u25A1",square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",Sscr:"\u{1D4AE}",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",Star:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",Sub:"\u22D0",sub:"\u2282",subdot:"\u2ABD",subE:"\u2AC5",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",Subset:"\u22D0",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",SubsetEqual:"\u2286",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",SuchThat:"\u220B",Sum:"\u2211",sum:"\u2211",sung:"\u266A",Sup:"\u22D1",sup:"\u2283",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",supdot:"\u2ABE",supdsub:"\u2AD8",supE:"\u2AC6",supe:"\u2287",supedot:"\u2AC4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",Supset:"\u22D1",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swarhk:"\u2926",swArr:"\u21D9",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",Tab:" ",target:"\u2316",Tau:"\u03A4",tau:"\u03C4",tbrk:"\u23B4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",Tfr:"\u{1D517}",tfr:"\u{1D531}",there4:"\u2234",Therefore:"\u2234",therefore:"\u2234",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",ThickSpace:"\u205F\u200A",thinsp:"\u2009",ThinSpace:"\u2009",thkap:"\u2248",thksim:"\u223C",THORN:"\xDE",thorn:"\xFE",Tilde:"\u223C",tilde:"\u02DC",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",Topf:"\u{1D54B}",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",TRADE:"\u2122",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",TripleDot:"\u20DB",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",Tscr:"\u{1D4AF}",tscr:"\u{1D4C9}",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040B",tshcy:"\u045B",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Uacute:"\xDA",uacute:"\xFA",Uarr:"\u219F",uArr:"\u21D1",uarr:"\u2191",Uarrocir:"\u2949",Ubrcy:"\u040E",ubrcy:"\u045E",Ubreve:"\u016C",ubreve:"\u016D",Ucirc:"\xDB",ucirc:"\xFB",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21C5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",Ufr:"\u{1D518}",ufr:"\u{1D532}",Ugrave:"\xD9",ugrave:"\xF9",uHar:"\u2963",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",Umacr:"\u016A",umacr:"\u016B",uml:"\xA8",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",uogon:"\u0173",Uopf:"\u{1D54C}",uopf:"\u{1D566}",UpArrow:"\u2191",Uparrow:"\u21D1",uparrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",Updownarrow:"\u21D5",updownarrow:"\u2195",UpEquilibrium:"\u296E",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",upsi:"\u03C5",upsih:"\u03D2",Upsilon:"\u03A5",upsilon:"\u03C5",UpTee:"\u22A5",UpTeeArrow:"\u21A5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",Uring:"\u016E",uring:"\u016F",urtri:"\u25F9",Uscr:"\u{1D4B0}",uscr:"\u{1D4CA}",utdot:"\u22F0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",Uuml:"\xDC",uuml:"\xFC",uwangle:"\u29A7",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",vArr:"\u21D5",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",Vbar:"\u2AEB",vBar:"\u2AE8",vBarv:"\u2AE9",Vcy:"\u0412",vcy:"\u0432",VDash:"\u22AB",Vdash:"\u22A9",vDash:"\u22A8",vdash:"\u22A2",Vdashl:"\u2AE6",Vee:"\u22C1",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",Verbar:"\u2016",verbar:"|",Vert:"\u2016",vert:"|",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",Vopf:"\u{1D54D}",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",Vscr:"\u{1D4B1}",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",Vvdash:"\u22AA",vzigzag:"\u299A",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2A5F",Wedge:"\u22C0",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\u{1D51A}",wfr:"\u{1D534}",Wopf:"\u{1D54E}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\u{1D4B2}",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",Xfr:"\u{1D51B}",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",Xi:"\u039E",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",Xopf:"\u{1D54F}",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",Xscr:"\u{1D4B3}",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",Yacute:"\xDD",yacute:"\xFD",YAcy:"\u042F",yacy:"\u044F",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042B",ycy:"\u044B",yen:"\xA5",Yfr:"\u{1D51C}",yfr:"\u{1D536}",YIcy:"\u0407",yicy:"\u0457",Yopf:"\u{1D550}",yopf:"\u{1D56A}",Yscr:"\u{1D4B4}",yscr:"\u{1D4CE}",YUcy:"\u042E",yucy:"\u044E",Yuml:"\u0178",yuml:"\xFF",Zacute:"\u0179",zacute:"\u017A",Zcaron:"\u017D",zcaron:"\u017E",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017B",zdot:"\u017C",zeetrf:"\u2128",ZeroWidthSpace:"\u200B",Zeta:"\u0396",zeta:"\u03B6",Zfr:"\u2128",zfr:"\u{1D537}",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21DD",Zopf:"\u2124",zopf:"\u{1D56B}",Zscr:"\u{1D4B5}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"});ri.entityMap=ri.HTML_ENTITIES});var uh=sr(Ua=>{"use strict";var Wn=zr(),G=du(),oh=Wo(),N_=Wn.isHTMLEscapableRawTextElement,I_=Wn.isHTMLMimeType,O_=Wn.isHTMLRawTextElement,ii=Wn.hasOwn,th=Wn.NAMESPACE,R_=oh.ParseError,B_=oh.DOMException,Vn=0,_r=1,zn=2,ni=3,Hn=4,Gn=5,oi=6,qa=7;function ih(){}ih.prototype={parse:function(n,e,t){var r=this.domBuilder;r.startDocument(),L_(e,e=Object.create(null)),$_(n,e,t,r,this.errorHandler),r.endDocument()}};var Eu=/&#?\w+;?/g;function $_(n,e,t,r,o){var i=I_(r.mimeType);n.indexOf(G.UNICODE_REPLACEMENT_CHARACTER)>=0&&o.warning("Unicode replacement character detected, source encoding issues?");function a(X){if(X>65535){X-=65536;var Be=55296+(X>>10),zt=56320+(X&1023);return String.fromCharCode(Be,zt)}else return String.fromCharCode(X)}function s(X){var Be=X[X.length-1]===";"?X:X+";";if(!i&&Be!==X)return o.error("EntityRef: expecting ;"),X;var zt=G.Reference.exec(Be);if(!zt||zt[0].length!==Be.length)return o.error("entity not matching Reference production: "+X),X;var En=Be.slice(1,-1);return ii(t,En)?t[En]:En.charAt(0)==="#"?a(parseInt(En.substring(1).replace("x","0x"))):(o.error("entity not found:"+X),X)}function l(X){if(X>b){var Be=n.substring(b,X).replace(Eu,s);f&&h(b),r.characters(Be,0,X-b),b=X}}var u=0,c=0,d=/\r\n?|\n|$/g,f=r.locator;function h(X,Be){for(;X>=c&&(Be=d.exec(n));)u=c,c=Be.index+Be[0].length,f.lineNumber++;f.columnNumber=X-u+1}for(var p=[{currentNSMap:e}],m=[],b=0;;){try{var w=n.indexOf("<",b);if(w<0){if(!i&&m.length>0)return o.fatalError("unclosed xml tag(s): "+m.join(", "));if(!n.substring(b).match(/^\s*$/)){var _=r.doc,y=_.createTextNode(n.substring(b));if(_.documentElement)return o.error("Extra content at the end of the document");_.appendChild(y),r.currentElement=y}return}if(w>b){var x=n.substring(b,w);!i&&m.length===0&&(x=x.replace(new RegExp(G.S_OPT.source,"g"),""),x&&o.error("Unexpected content outside root element: '"+x+"'")),l(w)}switch(n.charAt(w+1)){case"/":var q=n.indexOf(">",w+2),S=n.substring(w+2,q>0?q:void 0);if(!S)return o.fatalError("end tag name missing");var k=G.reg("^",G.QName_group,G.S_OPT,"$"),N=q>0&&k.exec(S);if(!N){var O=q>0&&G.reg("^",G.QName_group).exec(S);if(i&&O)o.warning('end tag name contains invalid trailing characters: "'+S+'"'),N=O;else if(O&&new RegExp(k.source,k.flags+"m").test(S))o.error('end tag name is followed by a line break and trailing content: "'+S+'"'),N=O;else return o.fatalError('end tag name contains invalid characters: "'+S+'"')}if(!r.currentElement&&!r.doc.documentElement)return;var $=m[m.length-1]||r.currentElement.tagName||r.doc.documentElement.tagName||"";if($!==N[1]){var ee=N[1].toLowerCase();if(!i||$.toLowerCase()!==ee)return o.fatalError('Opening and ending tag mismatch: "'+$+'" != "'+S+'"')}var W=p.pop();m.pop();var se=W.localNSMap;if(r.endElement(W.uri,W.localName,$),se)for(var me in se)ii(se,me)&&r.endPrefixMapping(me);q++;break;case"?":f&&h(w),q=j_(n,w,r,o);break;case"!":f&&h(w),q=sh(n,w,r,o,i);break;default:f&&h(w);var te=new lh,le=p[p.length-1].currentNSMap,q=M_(n,w,te,le,s,o,i),dt=te.length;if(te.closed||(i&&Wn.isHTMLVoidElement(te.tagName)?te.closed=!0:m.push(te.tagName)),f&&dt){for(var yn=rh(f,{}),vn=0;vn<dt;vn++){var wt=te[vn];h(wt.offset),wt.locator=rh(f,{})}r.locator=yn,nh(te,r,le)&&p.push(te),r.locator=f}else nh(te,r,le)&&p.push(te);i&&!te.closed?q=P_(n,q,te.tagName,s,r):q++}}catch(X){if(X instanceof R_)throw X;if(X instanceof B_)return o.fatalError("Error constructing the DOM: "+X.name+": "+X.message,X);o.error("element parse error: "+X),q=-1}q>b?b=q:l(Math.max(w,b)+1)}}function rh(n,e){return e.lineNumber=n.lineNumber,e.columnNumber=n.columnNumber,e}function M_(n,e,t,r,o,i,a){function s(h,p,m){if(ii(t.attributeNames,h))return i.fatalError("Attribute "+h+" redefined");if(!a&&p.indexOf("<")>=0)return i.fatalError("Unescaped '<' not allowed in attributes values");t.addValue(h,p.replace(/[\t\n\r]/g," ").replace(Eu,o),m)}for(var l,u,c=++e,d=Vn;;){var f=n.charAt(c);if(d===Vn&&f==="<")throw new Error("unexpected < in tag name: "+n.slice(e,c));switch(f){case"=":if(d===_r)l=n.slice(e,c),d=ni;else if(d===zn)d=ni;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(d===ni||d===_r)if(d===_r&&(i.warning('attribute value must after "="'),l=n.slice(e,c)),e=c+1,c=n.indexOf(f,e),c>0)u=n.slice(e,c),s(l,u,e-1),d=Gn;else throw new Error("attribute value no end '"+f+"' match");else if(d==Hn)u=n.slice(e,c),s(l,u,e),i.warning('attribute "'+l+'" missed start quot('+f+")!!"),e=c+1,d=Gn;else throw new Error('attribute value must after "="');break;case"/":switch(d){case Vn:t.setTagName(n.slice(e,c));case Gn:case oi:case qa:d=qa,t.closed=!0;case Hn:case _r:break;case zn:t.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return i.error("unexpected end of input"),d==Vn&&t.setTagName(n.slice(e,c)),c;case">":switch(d){case Vn:t.setTagName(n.slice(e,c));case Gn:case oi:case qa:break;case Hn:case _r:u=n.slice(e,c),u.slice(-1)==="/"&&(t.closed=!0,u=u.slice(0,-1));case zn:d===zn&&(u=l),d==Hn?(i.warning('attribute "'+u+'" missed quot(")!'),s(l,u,e)):(a||i.warning('attribute "'+u+'" missed value!! "'+u+'" instead!!'),s(u,u,e));break;case ni:if(!a)return i.fatalError(`AttValue: ' or " expected`)}return c;case"\x80":f=" ";default:if(f<=" ")switch(d){case Vn:t.setTagName(n.slice(e,c)),d=oi;break;case _r:l=n.slice(e,c),d=zn;break;case Hn:var u=n.slice(e,c);i.warning('attribute "'+u+'" missed quot(")!!'),s(l,u,e);case Gn:d=oi;break}else switch(d){case zn:a||i.warning('attribute "'+l+'" missed value!! "'+l+'" instead2!!'),s(l,l,e),e=c,d=_r;break;case Gn:i.warning('attribute space is required"'+l+'"!!');case oi:d=_r,e=c;break;case ni:d=Hn,e=c;break;case qa:throw new Error("elements closed character '/' and '>' must be connected to")}}c++}}function nh(n,e,t){for(var r=n.tagName,o=null,d=n.length;d--;){var i=n[d],a=i.qName,s=i.value,f=a.indexOf(":");if(f>0)var l=i.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";i.localName=u,c!==!1&&(o==null&&(o=Object.create(null),t=Object.create(t)),t[c]=o[c]=s,i.uri=th.XMLNS,e.startPrefixMapping(c,s))}for(var d=n.length;d--;)i=n[d],i.prefix&&(i.prefix==="xml"&&(i.uri=th.XML),i.prefix!=="xmlns"&&(i.uri=t[i.prefix]));var f=r.indexOf(":");f>0?(l=n.prefix=r.slice(0,f),u=n.localName=r.slice(f+1)):(l=null,u=n.localName=r);var h=n.uri=t[l||""];if(e.startElement(h,u,r,n),n.closed){if(e.endElement(h,u,r),o)for(l in o)ii(o,l)&&e.endPrefixMapping(l)}else return n.currentNSMap=t,n.localNSMap=o,!0}function P_(n,e,t,r,o){var i=N_(t);if(i||O_(t)){var a=new RegExp("</"+t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+">","ig");a.lastIndex=e;var s=a.exec(n),l=s?s.index:-1;if(l<0)return e+1;var u=n.substring(e+1,l);return i&&(u=u.replace(Eu,r)),o.characters(u,0,u.length),l}return e+1}function L_(n,e){for(var t in n)ii(n,t)&&(e[t]=n[t])}function ah(n,e){var t=e;function r(c){return c=c||0,n.charAt(t+c)}function o(c){c=c||1,t+=c}function i(){for(var c=0;t<n.length;){var d=r();if(d!==" "&&d!==`
|
|
11
|
-
`&&d!==" "&&d!=="\r")return c;c++,o()}return-1}function a(){return n.substring(t)}function s(c){return n.substring(t,t+c.length)===c}function l(c){return n.substring(t,t+c.length).toUpperCase()===c.toUpperCase()}function u(c){var d=
|
|
9
|
+
var Cg=Object.create;var Ul=Object.defineProperty;var Ng=Object.getOwnPropertyDescriptor;var Ig=Object.getOwnPropertyNames;var Og=Object.getPrototypeOf,Rg=Object.prototype.hasOwnProperty;var lr=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Bg=(n,e)=>{for(var t in e)Ul(n,t,{get:e[t],enumerable:!0})},$g=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ig(e))!Rg.call(n,o)&&o!==t&&Ul(n,o,{get:()=>e[o],enumerable:!(r=Ng(e,o))||r.enumerable});return n};var Od=(n,e,t)=>(t=n!=null?Cg(Og(n)):{},$g(e||!n||!n.__esModule?Ul(t,"default",{value:n,enumerable:!0}):t,n));var Hr=lr(Me=>{"use strict";function iw(n,e,t){if(t===void 0&&(t=Array.prototype),n&&typeof t.find=="function")return t.find.call(n,e);for(var r=0;r<n.length;r++)if(zr(n,r)){var o=n[r];if(e.call(void 0,o,r,n))return o}}function Rn(n,e){return e===void 0&&(e=Object),e&&typeof e.getOwnPropertyDescriptors=="function"&&(n=e.create(null,e.getOwnPropertyDescriptors(n))),e&&typeof e.freeze=="function"?e.freeze(n):n}function zr(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function aw(n,e){if(n===null||typeof n!="object")throw new TypeError("target is not an object");for(var t in e)zr(e,t)&&(n[t]=e[t]);return n}var pf=Rn({allowfullscreen:!0,async:!0,autofocus:!0,autoplay:!0,checked:!0,controls:!0,default:!0,defer:!0,disabled:!0,formnovalidate:!0,hidden:!0,ismap:!0,itemscope:!0,loop:!0,multiple:!0,muted:!0,nomodule:!0,novalidate:!0,open:!0,playsinline:!0,readonly:!0,required:!0,reversed:!0,selected:!0});function sw(n){return zr(pf,n.toLowerCase())}var mf=Rn({area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function lw(n){return zr(mf,n.toLowerCase())}var qo=Rn({script:!1,style:!1,textarea:!0,title:!0});function uw(n){var e=n.toLowerCase();return zr(qo,e)&&!qo[e]}function cw(n){var e=n.toLowerCase();return zr(qo,e)&&qo[e]}function gf(n){return n===Uo.HTML}function dw(n){return gf(n)||n===Uo.XML_XHTML_APPLICATION}var Uo=Rn({HTML:"text/html",XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),fw=Object.keys(Uo).map(function(n){return Uo[n]});function hw(n){return fw.indexOf(n)>-1}var pw=Rn({HTML:"http://www.w3.org/1999/xhtml",SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});Me.assign=aw;Me.find=iw;Me.freeze=Rn;Me.HTML_BOOLEAN_ATTRIBUTES=pf;Me.HTML_RAW_TEXT_ELEMENTS=qo;Me.HTML_VOID_ELEMENTS=mf;Me.hasDefaultHTMLNamespace=dw;Me.hasOwn=zr;Me.isHTMLBooleanAttribute=sw;Me.isHTMLRawTextElement=uw;Me.isHTMLEscapableRawTextElement=cw;Me.isHTMLMimeType=gf;Me.isHTMLVoidElement=lw;Me.isValidMimeType=hw;Me.MIME_TYPE=Uo;Me.NAMESPACE=pw});var Wo=lr(Go=>{"use strict";var mw=Hr();function wf(n,e){n.prototype=Object.create(Error.prototype,{constructor:{value:n},name:{value:n.name,enumerable:!0,writable:e}})}var zo=mw.freeze({Error:"Error",IndexSizeError:"IndexSizeError",DomstringSizeError:"DomstringSizeError",HierarchyRequestError:"HierarchyRequestError",WrongDocumentError:"WrongDocumentError",InvalidCharacterError:"InvalidCharacterError",NoDataAllowedError:"NoDataAllowedError",NoModificationAllowedError:"NoModificationAllowedError",NotFoundError:"NotFoundError",NotSupportedError:"NotSupportedError",InUseAttributeError:"InUseAttributeError",InvalidStateError:"InvalidStateError",SyntaxError:"SyntaxError",InvalidModificationError:"InvalidModificationError",NamespaceError:"NamespaceError",InvalidAccessError:"InvalidAccessError",ValidationError:"ValidationError",TypeMismatchError:"TypeMismatchError",SecurityError:"SecurityError",NetworkError:"NetworkError",AbortError:"AbortError",URLMismatchError:"URLMismatchError",QuotaExceededError:"QuotaExceededError",TimeoutError:"TimeoutError",InvalidNodeTypeError:"InvalidNodeTypeError",DataCloneError:"DataCloneError",EncodingError:"EncodingError",NotReadableError:"NotReadableError",UnknownError:"UnknownError",ConstraintError:"ConstraintError",DataError:"DataError",TransactionInactiveError:"TransactionInactiveError",ReadOnlyError:"ReadOnlyError",VersionError:"VersionError",OperationError:"OperationError",NotAllowedError:"NotAllowedError",OptOutError:"OptOutError"}),_f=Object.keys(zo);function yf(n){return typeof n=="number"&&n>=1&&n<=25}function gw(n){return typeof n=="string"&&n.substring(n.length-zo.Error.length)===zo.Error}function Ho(n,e){yf(n)?(this.name=_f[n],this.message=e||""):(this.message=n,this.name=gw(e)?e:zo.Error),Error.captureStackTrace&&Error.captureStackTrace(this,Ho)}wf(Ho,!0);Object.defineProperties(Ho.prototype,{code:{enumerable:!0,get:function(){var n=_f.indexOf(this.name);return yf(n)?n:0}}});var vf={INDEX_SIZE_ERR:1,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,INVALID_CHARACTER_ERR:5,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:11,SYNTAX_ERR:12,INVALID_MODIFICATION_ERR:13,NAMESPACE_ERR:14,INVALID_ACCESS_ERR:15,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:17,SECURITY_ERR:18,NETWORK_ERR:19,ABORT_ERR:20,URL_MISMATCH_ERR:21,QUOTA_EXCEEDED_ERR:22,TIMEOUT_ERR:23,INVALID_NODE_TYPE_ERR:24,DATA_CLONE_ERR:25},iu=Object.entries(vf);for(Vo=0;Vo<iu.length;Vo++)bf=iu[Vo][0],Ho[bf]=iu[Vo][1];var bf,Vo;function au(n,e,t){this.message=n,this.locator=e,this.cause=t,Error.captureStackTrace&&Error.captureStackTrace(this,au)}wf(au);Go.DOMException=Ho;Go.DOMExceptionName=zo;Go.ExceptionCode=vf;Go.ParseError=au});var hu=lr(W=>{"use strict";function Df(n){try{typeof n!="function"&&(n=RegExp);var e=new n("\u{1D306}","u").exec("\u{1D306}");return!!e&&e[0].length===2}catch{}return!1}var Mn=Df();function mr(n){if(n.source[0]!=="[")throw new Error(n+" can not be used with chars");return n.source.slice(1,n.source.lastIndexOf("]"))}function Bn(n,e){if(n.source[0]!=="[")throw new Error("/"+n.source+"/ can not be used with chars_without");if(!e||typeof e!="string")throw new Error(JSON.stringify(e)+" is not a valid search");if(n.source.indexOf(e)===-1)throw new Error('"'+e+'" is not is /'+n.source+"/");if(e==="-"&&n.source.indexOf(e)!==1)throw new Error('"'+e+'" is not at the first postion of /'+n.source+"/");return new RegExp(n.source.replace(e,""),Mn?"u":"")}function X(n){var e=this;return new RegExp(Array.prototype.slice.call(arguments).map(function(t){var r=typeof t=="string";if(r&&e===void 0&&t==="|")throw new Error("use regg instead of reg to wrap expressions with `|`!");return r?t:t.source}).join(""),Mn?"u":"")}function z(n){if(arguments.length===0)throw new Error("no parameters provided");return X.apply(z,["(?:"].concat(Array.prototype.slice.call(arguments),[")"]))}var bw="\uFFFD",gr=/[-\x09\x0A\x0D\x20-\x2C\x2E-\uD7FF\uE000-\uFFFD]/;Mn&&(gr=X("[",mr(gr),"\\u{10000}-\\u{10FFFF}","]"));var ww=new RegExp("[^"+mr(gr)+"]",Mn?"u":""),Ca=/[\x20\x09\x0D\x0A]/,_w=mr(Ca),de=X(Ca,"+"),ye=X(Ca,"*"),Yo=/[:_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;Mn&&(Yo=X("[",mr(Yo),"\\u{10000}-\\u{10FFFF}","]"));var yw=mr(Yo),uu=X("[",yw,mr(/[-.0-9\xB7]/),mr(/[\u0300-\u036F\u203F-\u2040]/),"]"),lt=X(Yo,uu,"*"),vw=X("^",lt,"$"),Ef=X(uu,"+"),Ew=X("&",lt,";"),xw=z(/&#[0-9]+;|&#x[0-9a-fA-F]+;/),Xo=z(Ew,"|",xw),Zo=X("%",lt,";"),cu=z(X('"',z(/[^%&"]/,"|",Zo,"|",Xo),"*",'"'),"|",X("'",z(/[^%&']/,"|",Zo,"|",Xo),"*","'")),kw=z('"',z(/[^<&"]/,"|",Xo),"*",'"',"|","'",z(/[^<&']/,"|",Xo),"*","'"),Tw=Bn(Yo,":"),Aw=Bn(uu,":"),su=X(Tw,Aw,"*"),Dw=X("^",su,"$"),Ko=X(su,z(":",su),"?"),Sw=X("^",Ko,"$"),Cw=X("(",Ko,")"),$n=z(/"[^"]*"|'[^']*'/),Nw=X(/^<\?/,"(",lt,")",z(de,"(?!",Ca,")(",gr,"*?)"),"?",/\?>/),xf=/[\x20\x0D\x0Aa-zA-Z0-9-'()+,./:=?;!*#@$_%]/,Jo=z('"',xf,'*"',"|","'",Bn(xf,"'"),"*'"),Sf="<!--",Cf="-->",Iw=X(Sf,z(Bn(gr,"-"),"|",X("-",Bn(gr,"-"))),"*",Cf),kf="#PCDATA",Ow=z(X(/\(/,ye,kf,z(ye,/\|/,ye,Ko),"*",ye,/\)\*/),"|",X(/\(/,ye,kf,ye,/\)/)),Rw=/[?*+]?/,Bw=X(/\([^>]+\)/,Rw),$w=z("EMPTY","|","ANY","|",Ow,"|",Bw),Mw="<!ELEMENT",Pw=X(Mw,de,z(Ko,"|",Zo),de,z($w,"|",Zo),ye,">"),Lw=X("NOTATION",de,/\(/,ye,lt,z(ye,/\|/,ye,lt),"*",ye,/\)/),Fw=X(/\(/,ye,Ef,z(ye,/\|/,ye,Ef),"*",ye,/\)/),jw=z(Lw,"|",Fw),qw=z(/CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS/,"|",jw),Uw=z(/#REQUIRED|#IMPLIED/,"|",z(z("#FIXED",de),"?",kw)),Vw=z(de,lt,de,qw,de,Uw),zw="<!ATTLIST",Hw=X(zw,de,lt,Vw,"*",ye,">"),lu="about:legacy-compat",Gw=z('"'+lu+'"',"|","'"+lu+"'"),du="SYSTEM",Na="PUBLIC",Ia=z(z(du,de,$n),"|",z(Na,de,Jo,de,$n)),Ww=X("^",z(z(du,de,"(?<SystemLiteralOnly>",$n,")"),"|",z(Na,de,"(?<PubidLiteral>",Jo,")",de,"(?<SystemLiteral>",$n,")"))),Yw=X("^",Jo,"$"),Xw=X("^",$n,"$"),Zw=z(de,"NDATA",de,lt),Kw=z(cu,"|",z(Ia,Zw,"?")),Nf="<!ENTITY",Jw=X(Nf,de,lt,de,Kw,ye,">"),Qw=z(cu,"|",Ia),e_=X(Nf,de,"%",de,lt,de,Qw,ye,">"),t_=z(Jw,"|",e_),r_=X(Na,de,Jo),n_=X("<!NOTATION",de,lt,de,z(Ia,"|",r_),ye,">"),fu=X(ye,"=",ye),Tf=/1[.]\d+/,o_=X(de,"version",fu,z("'",Tf,"'","|",'"',Tf,'"')),Af=/[A-Za-z][-A-Za-z0-9._]*/,i_=z(de,"encoding",fu,z('"',Af,'"',"|","'",Af,"'")),a_=z(de,"standalone",fu,z("'",z("yes","|","no"),"'","|",'"',z("yes","|","no"),'"')),s_=X(/^<\?xml/,o_,i_,"?",a_,"?",ye,/\?>/),l_="<!DOCTYPE",u_="<![CDATA[",c_="]]>",d_=/<!\[CDATA\[/,f_=/\]\]>/,h_=X(gr,"*?",f_),p_=X(d_,h_);W.chars=mr;W.chars_without=Bn;W.detectUnicodeSupport=Df;W.reg=X;W.regg=z;W.ABOUT_LEGACY_COMPAT=lu;W.ABOUT_LEGACY_COMPAT_SystemLiteral=Gw;W.AttlistDecl=Hw;W.CDATA_START=u_;W.CDATA_END=c_;W.CDSect=p_;W.Char=gr;W.Comment=Iw;W.COMMENT_START=Sf;W.COMMENT_END=Cf;W.DOCTYPE_DECL_START=l_;W.elementdecl=Pw;W.EntityDecl=t_;W.EntityValue=cu;W.ExternalID=Ia;W.ExternalID_match=Ww;W.Name=lt;W.Name_exact=vw;W.NCName_exact=Dw;W.NotationDecl=n_;W.Reference=Xo;W.PEReference=Zo;W.PI=Nw;W.PUBLIC=Na;W.PubidLiteral=Jo;W.PubidLiteral_match=Yw;W.QName=Ko;W.QName_exact=Sw;W.QName_group=Cw;W.S=de;W.SChar_s=_w;W.S_OPT=ye;W.SYSTEM=du;W.SystemLiteral=$n;W.SystemLiteral_match=Xw;W.InvalidChar=ww;W.UNICODE_REPLACEMENT_CHARACTER=bw;W.UNICODE_SUPPORT=Mn;W.XMLDecl=s_});var xu=lr(xe=>{"use strict";var ht=Hr(),$t=ht.find,m_=ht.hasDefaultHTMLNamespace,Ln=ht.hasOwn,g_=ht.isHTMLMimeType,b_=ht.isHTMLRawTextElement,w_=ht.isHTMLVoidElement,Qo=ht.MIME_TYPE,Mt=ht.NAMESPACE,Ye=Symbol(),Pf=Wo(),R=Pf.DOMException,He=Pf.DOMExceptionName,Ee=hu();function nt(n){if(n!==Ye)throw new TypeError("Illegal constructor")}function __(n){return n!==""}function y_(n){return n?n.split(/[\t\n\f\r ]+/).filter(__):[]}function v_(n,e){return Ln(n,e)||(n[e]=!0),n}function If(n){if(!n)return[];var e=y_(n);return Object.keys(e.reduce(v_,{}))}function E_(n){return function(e){return n&&n.indexOf(e)!==-1}}function Lf(n){if(!Ee.QName_exact.test(n))throw new R(R.INVALID_CHARACTER_ERR,'invalid character in qualified name "'+n+'"')}function mu(n,e){Lf(e),n=n||null;var t=null,r=e;if(e.indexOf(":")>=0){var o=e.split(":");t=o[0],r=o[1]}if(t!==null&&n===null)throw new R(R.NAMESPACE_ERR,"prefix is non-null and namespace is null");if(t==="xml"&&n!==ht.NAMESPACE.XML)throw new R(R.NAMESPACE_ERR,'prefix is "xml" and namespace is not the XML namespace');if((t==="xmlns"||e==="xmlns")&&n!==ht.NAMESPACE.XMLNS)throw new R(R.NAMESPACE_ERR,'either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace');if(n===ht.NAMESPACE.XMLNS&&t!=="xmlns"&&e!=="xmlns")throw new R(R.NAMESPACE_ERR,'namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"');return[n,t,r]}function qn(n,e){for(var t in n)Ln(n,t)&&(e[t]=n[t])}function ot(n,e){var t=n.prototype;if(!(t instanceof e)){let r=function(){};r.prototype=e.prototype,r=new r,qn(t,r),n.prototype=t=r}t.constructor!=n&&(typeof n!="function"&&console.error("unknown Class:"+n),t.constructor=n)}var it={},ft=it.ELEMENT_NODE=1,Fn=it.ATTRIBUTE_NODE=2,ei=it.TEXT_NODE=3,Ff=it.CDATA_SECTION_NODE=4,jf=it.ENTITY_REFERENCE_NODE=5,x_=it.ENTITY_NODE=6,gu=it.PROCESSING_INSTRUCTION_NODE=7,bu=it.COMMENT_NODE=8,Pn=it.DOCUMENT_NODE=9,qf=it.DOCUMENT_TYPE_NODE=10,br=it.DOCUMENT_FRAGMENT_NODE=11,k_=it.NOTATION_NODE=12,ve=ht.freeze({DOCUMENT_POSITION_DISCONNECTED:1,DOCUMENT_POSITION_PRECEDING:2,DOCUMENT_POSITION_FOLLOWING:4,DOCUMENT_POSITION_CONTAINS:8,DOCUMENT_POSITION_CONTAINED_BY:16,DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC:32});function Uf(n,e){if(e.length<n.length)return Uf(e,n);var t=null;for(var r in n){if(n[r]!==e[r])return t;t=n[r]}return t}function Of(n){return n.guid||(n.guid=Math.random()),n.guid}function Ne(){}Ne.prototype={length:0,item:function(n){return n>=0&&n<this.length?this[n]:null},toString:function(n){var e;typeof n=="function"?e={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:n}:n?e={requireWellFormed:!!n.requireWellFormed,splitCDATASections:n.splitCDATASections!==!1,nodeFilter:n.nodeFilter||null}:e={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:null};for(var t=[],r=0;r<this.length;r++)Eu(this[r],t,null,e);return t.join("")},filter:function(n){return Array.prototype.filter.call(this,n)},indexOf:function(n){return Array.prototype.indexOf.call(this,n)}};Ne.prototype[Symbol.iterator]=function(){var n=this,e=0;return{next:function(){return e<n.length?{value:n[e++],done:!1}:{done:!0}},return:function(){return{done:!0}}}};function Bt(n,e){this._node=n,this._refresh=e,$a(this)}function $a(n){var e=n._node._inc||n._node.ownerDocument._inc;if(n._inc!==e){var t=n._refresh(n._node);if(Qf(n,"length",t.length),!n.$$length||t.length<n.$$length)for(var r=t.length;r in n;r++)Ln(n,r)&&delete n[r];qn(t,n),n._inc=e}}Bt.prototype.item=function(n){return $a(this),this[n]||null};ot(Bt,Ne);function jn(){this._nsIndex=Object.create(null),this._noNsIndex=Object.create(null)}function Vf(n,e){for(var t=0;t<n.length;){if(n[t]===e)return t;t++}}function wu(n,e,t){if(!e)return n._noNsIndex;var r=n._nsIndex[e];return!r&&t&&(r=n._nsIndex[e]=Object.create(null)),r}function T_(n,e,t){var r=wu(n,e,!1),o=r&&r[t];return o||null}function A_(n,e){wu(n,e.namespaceURI,!0)[e.localName]=e}function D_(n,e){var t=wu(n,e.namespaceURI,!1);t&&delete t[e.localName]}function S_(n,e,t,r){if(r?e[Vf(e,r)]=t:(e[e.length]=t,e.length++),A_(e,t),n){t.ownerElement=n;var o=n.ownerDocument;o&&(r&&Gf(o,n,r),C_(o,n,t))}}function Rf(n,e,t){var r=Vf(e,t);if(r>=0){for(var o=e.length-1;r<=o;)e[r]=e[++r];if(e.length=o,D_(e,t),n){var i=n.ownerDocument;i&&Gf(i,n,t),t.ownerElement=null}}}jn.prototype={length:0,item:Ne.prototype.item,getNamedItem:function(n){this._ownerElement&&this._ownerElement._isInHTMLDocumentAndNamespace()&&(n=n.toLowerCase());for(var e=0;e<this.length;){var t=this[e];if(t.nodeName===n)return t;e++}return null},setNamedItem:function(n){var e=n.ownerElement;if(e&&e!==this._ownerElement)throw new R(R.INUSE_ATTRIBUTE_ERR);var t=T_(this,n.namespaceURI,n.localName);return t===n?n:(S_(this._ownerElement,this,n,t),t)},setNamedItemNS:function(n){return this.setNamedItem(n)},removeNamedItem:function(n){var e=this.getNamedItem(n);if(!e)throw new R(R.NOT_FOUND_ERR,n);return Rf(this._ownerElement,this,e),e},removeNamedItemNS:function(n,e){var t=this.getNamedItemNS(n,e);if(!t)throw new R(R.NOT_FOUND_ERR,n?n+" : "+e:e);return Rf(this._ownerElement,this,t),t},getNamedItemNS:function(n,e){n||(n=null);for(var t=0;t<this.length;){var r=this[t];if(r.localName===e&&r.namespaceURI===n)return r;t++}return null}};jn.prototype[Symbol.iterator]=function(){var n=this,e=0;return{next:function(){return e<n.length?{value:n[e++],done:!1}:{done:!0}},return:function(){return{done:!0}}}};function zf(){}zf.prototype={hasFeature:function(n,e){return!0},createDocument:function(n,e,t){var r=Qo.XML_APPLICATION;n===Mt.HTML?r=Qo.XML_XHTML_APPLICATION:n===Mt.SVG&&(r=Qo.XML_SVG_IMAGE);var o=new Yt(Ye,{contentType:r});if(o.implementation=this,o.childNodes=new Ne,o.doctype=t||null,t&&o.appendChild(t),e){var i=o.createElementNS(n,e);o.appendChild(i)}return o},createDocumentType:function(n,e,t,r){Lf(n);var o=new La(Ye);return o.name=n,o.nodeName=n,o.publicId=e||"",o.systemId=t||"",o.internalSubset=r||"",o.childNodes=new Ne,o},createHTMLDocument:function(n){var e=new Yt(Ye,{contentType:Qo.HTML});if(e.implementation=this,e.childNodes=new Ne,n!==!1){e.doctype=this.createDocumentType("html"),e.doctype.ownerDocument=e,e.appendChild(e.doctype);var t=e.createElement("html");e.appendChild(t);var r=e.createElement("head");if(t.appendChild(r),typeof n=="string"){var o=e.createElement("title");o.appendChild(e.createTextNode(n)),r.appendChild(o)}t.appendChild(e.createElement("body"))}return e}};function ee(n){nt(n)}ee.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,parentNode:null,get parentElement(){return this.parentNode&&this.parentNode.nodeType===this.ELEMENT_NODE?this.parentNode:null},childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,baseURI:"about:blank",get isConnected(){var n=this.getRootNode();return n&&n.nodeType===n.DOCUMENT_NODE},contains:function(n){if(!n)return!1;var e=n;do{if(this===e)return!0;e=e.parentNode}while(e);return!1},getRootNode:function(n){var e=this;do{if(!e.parentNode)return e;e=e.parentNode}while(e)},isEqualNode:function(n){if(!n)return!1;for(var e=[{node:this,other:n}];e.length>0;){var t=e.pop(),r=t.node,o=t.other;if(r.nodeType!==o.nodeType)return!1;switch(r.nodeType){case r.DOCUMENT_TYPE_NODE:if(r.name!==o.name||r.publicId!==o.publicId||r.systemId!==o.systemId)return!1;break;case r.ELEMENT_NODE:if(r.namespaceURI!==o.namespaceURI||r.prefix!==o.prefix||r.localName!==o.localName||r.attributes.length!==o.attributes.length)return!1;for(var i=0;i<r.attributes.length;i++){var a=r.attributes.item(i),s=o.getAttributeNodeNS(a.namespaceURI,a.localName);if(!s)return!1;e.push({node:a,other:s})}break;case r.ATTRIBUTE_NODE:if(r.namespaceURI!==o.namespaceURI||r.localName!==o.localName||r.value!==o.value)return!1;break;case r.PROCESSING_INSTRUCTION_NODE:if(r.target!==o.target||r.data!==o.data)return!1;break;case r.TEXT_NODE:case r.CDATA_SECTION_NODE:case r.COMMENT_NODE:if(r.data!==o.data)return!1;break}if(r.childNodes.length!==o.childNodes.length)return!1;for(var i=r.childNodes.length-1;i>=0;i--)e.push({node:r.childNodes[i],other:o.childNodes[i]})}return!0},isSameNode:function(n){return this===n},insertBefore:function(n,e){return Ba(this,n,e)},replaceChild:function(n,e){Ba(this,n,e,Xf),e&&this.removeChild(e)},removeChild:function(n){return Wf(this,n)},appendChild:function(n){return this.insertBefore(n,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(n){return Jf(this.ownerDocument||this,this,n)},normalize:function(){Pe(this,null,{enter:function(n){for(var e=n.firstChild;e;){var t=e.nextSibling;if(t!==null&&t.nodeType===ei&&e.nodeType===ei){for(var r=[],o=t;o!==null&&o.nodeType===ei;)r.push(o.data),o=o.nextSibling;for(var i=e.nextSibling;i!==o;){var a=i.nextSibling;i.parentNode=null,i.previousSibling=null,i.nextSibling=null,i=a}e.nextSibling=o,o!==null?o.previousSibling=e:n.lastChild=e,e.appendData(r.join("")),_u(n.ownerDocument,n),e=o}else e=t}return!0}})},isSupported:function(n,e){return this.ownerDocument.implementation.hasFeature(n,e)},lookupPrefix:function(n){for(var e=this;e;){var t=e._nsMap;if(t){for(var r in t)if(Ln(t,r)&&t[r]===n)return r}e=e.nodeType==Fn?e.ownerDocument:e.parentNode}return null},lookupNamespaceURI:function(n){for(var e=this;e;){var t=e._nsMap;if(t&&Ln(t,n))return t[n];e=e.nodeType==Fn?e.ownerDocument:e.parentNode}return null},isDefaultNamespace:function(n){var e=this.lookupPrefix(n);return e==null},compareDocumentPosition:function(n){if(this===n)return 0;var e=n,t=this,r=null,o=null;if(e instanceof Gr&&(r=e,e=r.ownerElement),t instanceof Gr&&(o=t,t=o.ownerElement,r&&e&&t===e))for(var i=0,a;a=t.attributes[i];i++){if(a===r)return ve.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+ve.DOCUMENT_POSITION_PRECEDING;if(a===o)return ve.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+ve.DOCUMENT_POSITION_FOLLOWING}if(!e||!t||t.ownerDocument!==e.ownerDocument)return ve.DOCUMENT_POSITION_DISCONNECTED+ve.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+(Of(t.ownerDocument)>Of(e.ownerDocument)?ve.DOCUMENT_POSITION_FOLLOWING:ve.DOCUMENT_POSITION_PRECEDING);if(o&&e===t)return ve.DOCUMENT_POSITION_CONTAINS+ve.DOCUMENT_POSITION_PRECEDING;if(r&&e===t)return ve.DOCUMENT_POSITION_CONTAINED_BY+ve.DOCUMENT_POSITION_FOLLOWING;for(var s=[],l=e.parentNode;l;){if(!o&&l===t)return ve.DOCUMENT_POSITION_CONTAINED_BY+ve.DOCUMENT_POSITION_FOLLOWING;s.push(l),l=l.parentNode}s.reverse();for(var u=[],c=t.parentNode;c;){if(!r&&c===e)return ve.DOCUMENT_POSITION_CONTAINS+ve.DOCUMENT_POSITION_PRECEDING;u.push(c),c=c.parentNode}u.reverse();var d=Uf(s,u);for(var f in d.childNodes){var h=d.childNodes[f];if(h===t)return ve.DOCUMENT_POSITION_FOLLOWING;if(h===e)return ve.DOCUMENT_POSITION_PRECEDING;if(u.indexOf(h)>=0)return ve.DOCUMENT_POSITION_FOLLOWING;if(s.indexOf(h)>=0)return ve.DOCUMENT_POSITION_PRECEDING}return 0}};function Hf(n){return n=="<"&&"<"||n==">"&&">"||n=="&"&&"&"||n=='"'&&"""||"&#"+n.charCodeAt()+";"}qn(it,ee);qn(it,ee.prototype);qn(ve,ee);qn(ve,ee.prototype);function Ra(n,e){Pe(n,null,{enter:function(t){return e(t)?Pe.STOP:!0}})}function Pe(n,e,t){for(var r=[{node:n,context:e,phase:Pe.ENTER}];r.length>0;){var o=r.pop();if(o.phase===Pe.ENTER){var i=t.enter(o.node,o.context);if(i===Pe.STOP)return Pe.STOP;if(r.push({node:o.node,context:i,phase:Pe.EXIT}),i==null)continue;for(var a=o.node.lastChild;a;)r.push({node:a,context:i,phase:Pe.ENTER}),a=a.previousSibling}else t.exit&&t.exit(o.node,o.context)}}Pe.STOP=Symbol("walkDOM.STOP");Pe.ENTER=0;Pe.EXIT=1;function Yt(n,e){nt(n);var t=e||{};this.ownerDocument=this,this.contentType=t.contentType||Qo.XML_APPLICATION,this.type=g_(this.contentType)?"html":"xml"}function C_(n,e,t){n&&n._inc++;var r=t.namespaceURI;r===Mt.XMLNS&&(e._nsMap[t.prefix?t.localName:""]=t.value)}function Gf(n,e,t,r){n&&n._inc++;var o=t.namespaceURI;o===Mt.XMLNS&&delete e._nsMap[t.prefix?t.localName:""]}function _u(n,e,t){if(n&&n._inc){n._inc++;var r=e.childNodes;if(t&&!t.nextSibling)r[r.length++]=t;else{for(var o=e.firstChild,i=0;o;)r[i++]=o,o=o.nextSibling;r.length=i,delete r[r.length]}}}function Wf(n,e){if(n!==e.parentNode)throw new R(R.NOT_FOUND_ERR,"child's parent is not parent");var t=e.previousSibling,r=e.nextSibling;return t?t.nextSibling=r:n.firstChild=r,r?r.previousSibling=t:n.lastChild=t,_u(n.ownerDocument,n),e.parentNode=null,e.previousSibling=null,e.nextSibling=null,e}function N_(n){return n&&(n.nodeType===ee.DOCUMENT_NODE||n.nodeType===ee.DOCUMENT_FRAGMENT_NODE||n.nodeType===ee.ELEMENT_NODE)}function I_(n){return n&&(n.nodeType===ee.CDATA_SECTION_NODE||n.nodeType===ee.COMMENT_NODE||n.nodeType===ee.DOCUMENT_FRAGMENT_NODE||n.nodeType===ee.DOCUMENT_TYPE_NODE||n.nodeType===ee.ELEMENT_NODE||n.nodeType===ee.PROCESSING_INSTRUCTION_NODE||n.nodeType===ee.TEXT_NODE)}function wr(n){return n&&n.nodeType===ee.DOCUMENT_TYPE_NODE}function Wt(n){return n&&n.nodeType===ee.ELEMENT_NODE}function Yf(n){return n&&n.nodeType===ee.TEXT_NODE}function Bf(n,e){var t=n.childNodes||[];if($t(t,Wt)||wr(e))return!1;var r=$t(t,wr);return!(e&&r&&t.indexOf(r)>t.indexOf(e))}function $f(n,e){var t=n.childNodes||[];function r(i){return Wt(i)&&i!==e}if($t(t,r))return!1;var o=$t(t,wr);return!(e&&o&&t.indexOf(o)>t.indexOf(e))}function O_(n,e,t){if(!N_(n))throw new R(R.HIERARCHY_REQUEST_ERR,"Unexpected parent node type "+n.nodeType);if(t&&t.parentNode!==n)throw new R(R.NOT_FOUND_ERR,"child not in parent");if(!I_(e)||wr(e)&&n.nodeType!==ee.DOCUMENT_NODE)throw new R(R.HIERARCHY_REQUEST_ERR,"Unexpected node type "+e.nodeType+" for parent node type "+n.nodeType)}function R_(n,e,t){var r=n.childNodes||[],o=e.childNodes||[];if(e.nodeType===ee.DOCUMENT_FRAGMENT_NODE){var i=o.filter(Wt);if(i.length>1||$t(o,Yf))throw new R(R.HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(i.length===1&&!Bf(n,t))throw new R(R.HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(Wt(e)&&!Bf(n,t))throw new R(R.HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(wr(e)){if($t(r,wr))throw new R(R.HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var a=$t(r,Wt);if(t&&r.indexOf(a)<r.indexOf(t))throw new R(R.HIERARCHY_REQUEST_ERR,"Doctype can only be inserted before an element");if(!t&&a)throw new R(R.HIERARCHY_REQUEST_ERR,"Doctype can not be appended since element is present")}}function Xf(n,e,t){var r=n.childNodes||[],o=e.childNodes||[];if(e.nodeType===ee.DOCUMENT_FRAGMENT_NODE){var i=o.filter(Wt);if(i.length>1||$t(o,Yf))throw new R(R.HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(i.length===1&&!$f(n,t))throw new R(R.HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(Wt(e)&&!$f(n,t))throw new R(R.HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(wr(e)){if($t(r,function(l){return wr(l)&&l!==t}))throw new R(R.HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var a=$t(r,Wt);if(t&&r.indexOf(a)<r.indexOf(t))throw new R(R.HIERARCHY_REQUEST_ERR,"Doctype can only be inserted before an element")}}function Ba(n,e,t,r){O_(n,e,t),n.nodeType===ee.DOCUMENT_NODE&&(r||R_)(n,e,t);var o=e.parentNode;if(o&&o.removeChild(e),e.nodeType===br){var i=e.firstChild;if(i==null)return e;var a=e.lastChild}else i=a=e;var s=t?t.previousSibling:n.lastChild;i.previousSibling=s,a.nextSibling=t,s?s.nextSibling=i:n.firstChild=i,t==null?n.lastChild=a:t.previousSibling=a;do i.parentNode=n;while(i!==a&&(i=i.nextSibling));return _u(n.ownerDocument||n,n,e),e.nodeType==br&&(e.firstChild=e.lastChild=null),e}Yt.prototype={implementation:null,nodeName:"#document",nodeType:Pn,doctype:null,documentElement:null,_inc:1,insertBefore:function(n,e){if(n.nodeType===br){for(var t=n.firstChild;t;){var r=t.nextSibling;this.insertBefore(t,e),t=r}return n}return Ba(this,n,e),n.ownerDocument=this,this.documentElement===null&&n.nodeType===ft&&(this.documentElement=n),n},removeChild:function(n){var e=Wf(this,n);return e===this.documentElement&&(this.documentElement=null),e},replaceChild:function(n,e){Ba(this,n,e,Xf),n.ownerDocument=this,e&&this.removeChild(e),Wt(n)&&(this.documentElement=n)},importNode:function(n,e){return B_(this,n,e)},getElementById:function(n){var e=null;return Ra(this.documentElement,function(t){if(t.nodeType==ft&&t.getAttribute("id")==n)return e=t,!0}),e},createElement:function(n){var e=new Xt(Ye);e.ownerDocument=this,this.type==="html"&&(n=n.toLowerCase()),m_(this.contentType)&&(e.namespaceURI=Mt.HTML),e.nodeName=n,e.tagName=n,e.localName=n,e.childNodes=new Ne;var t=e.attributes=new jn;return t._ownerElement=e,e},createDocumentFragment:function(){var n=new Un(Ye);return n.ownerDocument=this,n.childNodes=new Ne,n},createTextNode:function(n){var e=new ti(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.appendData(n),e},createComment:function(n){var e=new Ma(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.appendData(n),e},createCDATASection:function(n){if(n.indexOf("]]>")!==-1)throw new R(R.INVALID_CHARACTER_ERR,'data contains "]]>"');var e=new Pa(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.appendData(n),e},createProcessingInstruction:function(n,e){var t=new ja(Ye);return t.ownerDocument=this,t.childNodes=new Ne,t.nodeName=t.target=n,t.nodeValue=t.data=e,t},createAttribute:function(n){if(!Ee.QName_exact.test(n))throw new R(R.INVALID_CHARACTER_ERR,'invalid character in name "'+n+'"');return this.type==="html"&&(n=n.toLowerCase()),this._createAttribute(n)},_createAttribute:function(n){var e=new Gr(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.name=n,e.nodeName=n,e.localName=n,e.specified=!0,e},createEntityReference:function(n){if(!Ee.Name_exact.test(n))throw new R(R.INVALID_CHARACTER_ERR,'not a valid xml name "'+n+'"');if(this.type==="html")throw new R("document is an html document",He.NotSupportedError);var e=new Fa(Ye);return e.ownerDocument=this,e.childNodes=new Ne,e.nodeName=n,e},createElementNS:function(n,e){var t=mu(n,e),r=new Xt(Ye),o=r.attributes=new jn;return r.childNodes=new Ne,r.ownerDocument=this,r.nodeName=e,r.tagName=e,r.namespaceURI=t[0],r.prefix=t[1],r.localName=t[2],o._ownerElement=r,r},createAttributeNS:function(n,e){var t=mu(n,e),r=new Gr(Ye);return r.ownerDocument=this,r.childNodes=new Ne,r.nodeName=e,r.name=e,r.specified=!0,r.namespaceURI=t[0],r.prefix=t[1],r.localName=t[2],r}};ot(Yt,ee);function Xt(n){nt(n),this._nsMap=Object.create(null)}Xt.prototype={nodeType:ft,attributes:null,getQualifiedName:function(){return this.prefix?this.prefix+":"+this.localName:this.localName},_isInHTMLDocumentAndNamespace:function(){return this.ownerDocument.type==="html"&&this.namespaceURI===Mt.HTML},hasAttributes:function(){return!!(this.attributes&&this.attributes.length)},hasAttribute:function(n){return!!this.getAttributeNode(n)},getAttribute:function(n){var e=this.getAttributeNode(n);return e?e.value:null},getAttributeNode:function(n){return this._isInHTMLDocumentAndNamespace()&&(n=n.toLowerCase()),this.attributes.getNamedItem(n)},setAttribute:function(n,e){this._isInHTMLDocumentAndNamespace()&&(n=n.toLowerCase());var t=this.getAttributeNode(n);t?t.value=t.nodeValue=""+e:(t=this.ownerDocument._createAttribute(n),t.value=t.nodeValue=""+e,this.setAttributeNode(t))},removeAttribute:function(n){var e=this.getAttributeNode(n);e&&this.removeAttributeNode(e)},setAttributeNode:function(n){return this.attributes.setNamedItem(n)},setAttributeNodeNS:function(n){return this.attributes.setNamedItemNS(n)},removeAttributeNode:function(n){return this.attributes.removeNamedItem(n.nodeName)},removeAttributeNS:function(n,e){var t=this.getAttributeNodeNS(n,e);t&&this.removeAttributeNode(t)},hasAttributeNS:function(n,e){return this.getAttributeNodeNS(n,e)!=null},getAttributeNS:function(n,e){var t=this.getAttributeNodeNS(n,e);return t?t.value:null},setAttributeNS:function(n,e,t){var r=mu(n,e),o=r[2],i=this.getAttributeNodeNS(n,o);i?i.value=i.nodeValue=""+t:(i=this.ownerDocument.createAttributeNS(n,e),i.value=i.nodeValue=""+t,this.setAttributeNode(i))},getAttributeNodeNS:function(n,e){return this.attributes.getNamedItemNS(n,e)},getElementsByClassName:function(n){var e=If(n);return new Bt(this,function(t){var r=[];return e.length>0&&Ra(t,function(o){if(o!==t&&o.nodeType===ft){var i=o.getAttribute("class");if(i){var a=n===i;if(!a){var s=If(i);a=e.every(E_(s))}a&&r.push(o)}}}),r})},getElementsByTagName:function(n){var e=(this.nodeType===Pn?this:this.ownerDocument).type==="html",t=n.toLowerCase();return new Bt(this,function(r){var o=[];return Ra(r,function(i){if(!(i===r||i.nodeType!==ft))if(n==="*")o.push(i);else{var a=i.getQualifiedName(),s=e&&i.namespaceURI===Mt.HTML?t:n;a===s&&o.push(i)}}),o})},getElementsByTagNameNS:function(n,e){return new Bt(this,function(t){var r=[];return Ra(t,function(o){o!==t&&o.nodeType===ft&&(n==="*"||o.namespaceURI===n)&&(e==="*"||o.localName==e)&&r.push(o)}),r})}};Yt.prototype.getElementsByClassName=Xt.prototype.getElementsByClassName;Yt.prototype.getElementsByTagName=Xt.prototype.getElementsByTagName;Yt.prototype.getElementsByTagNameNS=Xt.prototype.getElementsByTagNameNS;ot(Xt,ee);function Gr(n){nt(n),this.namespaceURI=null,this.prefix=null,this.ownerElement=null}Gr.prototype.nodeType=Fn;ot(Gr,ee);function _r(n){nt(n)}_r.prototype={data:"",substringData:function(n,e){return this.data.substring(n,n+e)},appendData:function(n){n=this.data+n,this.nodeValue=this.data=n,this.length=n.length},insertData:function(n,e){this.replaceData(n,0,e)},deleteData:function(n,e){this.replaceData(n,e,"")},replaceData:function(n,e,t){var r=this.data.substring(0,n),o=this.data.substring(n+e);t=r+t+o,this.nodeValue=this.data=t,this.length=t.length}};ot(_r,ee);function ti(n){nt(n)}ti.prototype={nodeName:"#text",nodeType:ei,splitText:function(n){var e=this.data,t=e.substring(n);e=e.substring(0,n),this.data=this.nodeValue=e,this.length=e.length;var r=this.ownerDocument.createTextNode(t);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}};ot(ti,_r);function Ma(n){nt(n)}Ma.prototype={nodeName:"#comment",nodeType:bu};ot(Ma,_r);function Pa(n){nt(n)}Pa.prototype={nodeName:"#cdata-section",nodeType:Ff};ot(Pa,ti);function La(n){nt(n)}La.prototype.nodeType=qf;ot(La,ee);function yu(n){nt(n)}yu.prototype.nodeType=k_;ot(yu,ee);function vu(n){nt(n)}vu.prototype.nodeType=x_;ot(vu,ee);function Fa(n){nt(n)}Fa.prototype.nodeType=jf;ot(Fa,ee);function Un(n){nt(n)}Un.prototype.nodeName="#document-fragment";Un.prototype.nodeType=br;ot(Un,ee);function ja(n){nt(n)}ja.prototype.nodeType=gu;ot(ja,_r);function Zf(){}Zf.prototype.serializeToString=function(n,e){return Kf.call(n,e)};ee.prototype.toString=Kf;function Kf(n){var e;typeof n=="function"?e={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:n}:n!=null?e={requireWellFormed:!!n.requireWellFormed,splitCDATASections:n.splitCDATASections!==!1,nodeFilter:n.nodeFilter||null}:e={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:null};var t=[],r=this.nodeType===Pn&&this.documentElement||this,o=r.prefix,i=r.namespaceURI;if(i&&o==null){var o=r.lookupPrefix(i);if(o==null)var a=[{namespace:i,prefix:null}]}return Eu(this,t,a,e),t.join("")}function Mf(n,e,t){var r=n.prefix||"",o=n.namespaceURI;if(!o||r==="xml"&&o===Mt.XML||o===Mt.XMLNS)return!1;for(var i=t.length;i--;){var a=t[i];if(a.prefix===r)return a.namespace!==o}return!0}function Oa(n,e,t,r){if(r&&!Ee.QName_exact.test(e))throw new R('The attribute name "'+e+'" is not a valid XML QName',He.InvalidStateError);n.push(" ",e,'="',t.replace(/[<>&"\t\n\r]/g,Hf),'"')}function Eu(n,e,t,r){t||(t=[]);var o=r.nodeFilter,i=r.requireWellFormed,a=r.splitCDATASections,s=n.nodeType===Pn?n:n.ownerDocument,l=s.type==="html";Pe(n,{ns:t},{enter:function(u,c){var d=c.ns;if(o)if(u=o(u),u){if(typeof u=="string")return e.push(u),null}else return null;switch(u.nodeType){case ft:var f=u.attributes,h=f.length,p=u.tagName,m=p;if(!l&&!u.prefix&&u.namespaceURI){for(var b,w=0;w<f.length;w++)if(f.item(w).name==="xmlns"){b=f.item(w).value;break}if(!b)for(var _=d.length-1;_>=0;_--){var y=d[_];if(y.prefix===""&&y.namespace===u.namespaceURI){b=y.namespace;break}}if(b!==u.namespaceURI)for(var _=d.length-1;_>=0;_--){var y=d[_];if(y.namespace===u.namespaceURI){y.prefix&&(m=y.prefix+":"+p);break}}}if(i&&!Ee.QName_exact.test(m))throw new R('The element name "'+m+'" is not a valid XML QName',He.InvalidStateError);e.push("<",m);for(var x=d.slice(),D=0;D<h;D++){var k=f.item(D);k.prefix=="xmlns"?x.push({prefix:k.localName,namespace:k.value}):k.nodeName=="xmlns"&&x.push({prefix:"",namespace:k.value})}for(var D=0;D<h;D++){var k=f.item(D);if(Mf(k,l,x)){var C=k.prefix||"",O=k.namespaceURI;Oa(e,C?"xmlns:"+C:"xmlns",O,i),x.push({prefix:C,namespace:O})}var $=o?o(k):k;$&&(typeof $=="string"?e.push($):Oa(e,$.name,$.value,i))}if(p===m&&Mf(u,l,x)){var F=u.prefix||"",O=u.namespaceURI;Oa(e,F?"xmlns:"+F:"xmlns",O,i),x.push({prefix:F,namespace:O})}var H=!u.firstChild;if(H&&(l||u.namespaceURI===Mt.HTML)&&(H=w_(p)),H)return e.push("/>"),null;if(e.push(">"),l&&b_(p)){for(var Q=u.firstChild;Q;)Q.data?e.push(Q.data):Eu(Q,e,x.slice(),r),Q=Q.nextSibling;return e.push("</",m,">"),null}return{ns:x,tag:m};case Pn:case br:if(i&&u.nodeType===Pn&&u.documentElement==null)throw new R("The Document has no documentElement",He.InvalidStateError);return{ns:d};case Fn:return Oa(e,u.name,u.value,i),null;case ei:if(i&&Ee.InvalidChar.test(u.data))throw new R("The Text node data contains characters outside the XML Char production",He.InvalidStateError);return e.push(u.data.replace(/[<&>]/g,Hf)),null;case Ff:if(i&&u.data.indexOf("]]>")!==-1)throw new R('The CDATASection data contains "]]>"',He.InvalidStateError);return a?e.push(Ee.CDATA_START,u.data.replace(/]]>/g,"]]]]><![CDATA[>"),Ee.CDATA_END):e.push(Ee.CDATA_START,u.data,Ee.CDATA_END),null;case bu:if(i){if(Ee.InvalidChar.test(u.data))throw new R("The comment node data contains characters outside the XML Char production",He.InvalidStateError);if(u.data.indexOf("--")!==-1||u.data[u.data.length-1]==="-")throw new R('The comment node data contains "--" or ends with "-"',He.InvalidStateError)}return e.push(Ee.COMMENT_START,u.data,Ee.COMMENT_END),null;case qf:var me=u.publicId,re=u.systemId;if(i){if(!Ee.Name_exact.test(u.name))throw new R('The doctype name "'+u.name+'" is not a valid XML Name',He.InvalidStateError);if(me&&!Ee.PubidLiteral_match.test(me))throw new R("DocumentType publicId is not a valid PubidLiteral",He.InvalidStateError);if(re&&re!=="."&&!Ee.SystemLiteral_match.test(re))throw new R("DocumentType systemId is not a valid SystemLiteral",He.InvalidStateError);if(u.internalSubset&&u.internalSubset.indexOf("]>")!==-1)throw new R('DocumentType internalSubset contains "]>"',He.InvalidStateError)}return e.push(Ee.DOCTYPE_DECL_START," ",u.name),me?(e.push(" ",Ee.PUBLIC," ",me),re&&re!=="."&&e.push(" ",re)):re&&re!=="."&&e.push(" ",Ee.SYSTEM," ",re),u.internalSubset&&e.push(" [",u.internalSubset,"]"),e.push(">"),null;case gu:if(i){if(!Ee.NCName_exact.test(u.target)||u.target.toLowerCase()==="xml")throw new R('The processing instruction target "'+u.target+'" is not a valid XML NCName or is reserved',He.InvalidStateError);if(Ee.InvalidChar.test(u.data))throw new R("The ProcessingInstruction data contains characters outside the XML Char production",He.InvalidStateError);if(u.data.indexOf("?>")!==-1)throw new R('The ProcessingInstruction data contains "?>"',He.InvalidStateError)}return e.push("<?",u.target," ",u.data,"?>"),null;case jf:if(i&&!Ee.Name_exact.test(u.nodeName))throw new R('The entity reference name "'+u.nodeName+'" is not a valid XML Name',He.InvalidStateError);return e.push("&",u.nodeName,";"),null;default:return e.push("??",u.nodeName),null}},exit:function(u,c){c&&c.tag&&e.push("</",c.tag,">")}})}function B_(n,e,t){var r;return Pe(e,null,{enter:function(o,i){var a=o.cloneNode(!1);a.ownerDocument=n,a.parentNode=null,i===null?r=a:i.appendChild(a);var s=o.nodeType===Fn||t;return s?a:null}}),r}function Jf(n,e,t){var r;return Pe(e,null,{enter:function(o,i){var a=new o.constructor(Ye);for(var s in o)if(Ln(o,s)){var l=o[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}o.childNodes&&(a.childNodes=new Ne),a.ownerDocument=n;var u=t;switch(a.nodeType){case ft:var c=o.attributes,d=a.attributes=new jn,f=c.length;d._ownerElement=a;for(var h=0;h<f;h++)a.setAttributeNode(Jf(n,c.item(h),!0));break;case Fn:u=!0}return i!==null?i.appendChild(a):r=a,u?a:null}}),r}function Qf(n,e,t){n[e]=t}function pu(n){for(var e=[],t=n.firstChild;t;)t.nodeType===ft&&e.push(t),t=t.nextSibling;return e}try{Object.defineProperty&&(Object.defineProperty(Bt.prototype,"length",{get:function(){return $a(this),this.$$length}}),Object.defineProperty(ee.prototype,"textContent",{get:function(){if(this.nodeType===ft||this.nodeType===br){var n=[];return Pe(this,null,{enter:function(e){if(e.nodeType===ft||e.nodeType===br)return!0;if(e.nodeType===gu||e.nodeType===bu)return null;n.push(e.nodeValue)}}),n.join("")}return this.nodeValue},set:function(n){switch(this.nodeType){case ft:case br:for(;this.firstChild;)this.removeChild(this.firstChild);(n||String(n))&&this.appendChild(this.ownerDocument.createTextNode(n));break;default:this.data=n,this.value=n,this.nodeValue=n}}}),Object.defineProperty(_r.prototype,"data",{get:function(){return this._data!=null?this._data:""},set:function(n){this._data=n,this.length=typeof n=="string"?n.length:0}}),Object.defineProperty(_r.prototype,"nodeValue",{get:function(){return this.data},set:function(n){this.data=n},enumerable:!0,configurable:!0}),Object.defineProperty(Xt.prototype,"children",{get:function(){return new Bt(this,pu)}}),Object.defineProperty(Yt.prototype,"children",{get:function(){return new Bt(this,pu)}}),Object.defineProperty(Un.prototype,"children",{get:function(){return new Bt(this,pu)}}),Qf=function(n,e,t){n["$$"+e]=t})}catch{}xe._updateLiveList=$a;xe.Attr=Gr;xe.CDATASection=Pa;xe.CharacterData=_r;xe.Comment=Ma;xe.Document=Yt;xe.DocumentFragment=Un;xe.DocumentType=La;xe.DOMImplementation=zf;xe.Element=Xt;xe.Entity=vu;xe.EntityReference=Fa;xe.LiveNodeList=Bt;xe.NamedNodeMap=jn;xe.Node=ee;xe.NodeList=Ne;xe.Notation=yu;xe.Text=ti;xe.ProcessingInstruction=ja;xe.walkDOM=Pe;xe.XMLSerializer=Zf});var th=lr(ri=>{"use strict";var eh=Hr().freeze;ri.XML_ENTITIES=eh({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});ri.HTML_ENTITIES=eh({Aacute:"\xC1",aacute:"\xE1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223E",acd:"\u223F",acE:"\u223E\u0333",Acirc:"\xC2",acirc:"\xE2",acute:"\xB4",Acy:"\u0410",acy:"\u0430",AElig:"\xC6",aelig:"\xE6",af:"\u2061",Afr:"\u{1D504}",afr:"\u{1D51E}",Agrave:"\xC0",agrave:"\xE0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03B1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2A3F",AMP:"&",amp:"&",And:"\u2A53",and:"\u2227",andand:"\u2A55",andd:"\u2A5C",andslope:"\u2A58",andv:"\u2A5A",ang:"\u2220",ange:"\u29A4",angle:"\u2220",angmsd:"\u2221",angmsdaa:"\u29A8",angmsdab:"\u29A9",angmsdac:"\u29AA",angmsdad:"\u29AB",angmsdae:"\u29AC",angmsdaf:"\u29AD",angmsdag:"\u29AE",angmsdah:"\u29AF",angrt:"\u221F",angrtvb:"\u22BE",angrtvbd:"\u299D",angsph:"\u2222",angst:"\xC5",angzarr:"\u237C",Aogon:"\u0104",aogon:"\u0105",Aopf:"\u{1D538}",aopf:"\u{1D552}",ap:"\u2248",apacir:"\u2A6F",apE:"\u2A70",ape:"\u224A",apid:"\u224B",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224A",Aring:"\xC5",aring:"\xE5",Ascr:"\u{1D49C}",ascr:"\u{1D4B6}",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224D",Atilde:"\xC3",atilde:"\xE3",Auml:"\xC4",auml:"\xE4",awconint:"\u2233",awint:"\u2A11",backcong:"\u224C",backepsilon:"\u03F6",backprime:"\u2035",backsim:"\u223D",backsimeq:"\u22CD",Backslash:"\u2216",Barv:"\u2AE7",barvee:"\u22BD",Barwed:"\u2306",barwed:"\u2305",barwedge:"\u2305",bbrk:"\u23B5",bbrktbrk:"\u23B6",bcong:"\u224C",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201E",becaus:"\u2235",Because:"\u2235",because:"\u2235",bemptyv:"\u29B0",bepsi:"\u03F6",bernou:"\u212C",Bernoullis:"\u212C",Beta:"\u0392",beta:"\u03B2",beth:"\u2136",between:"\u226C",Bfr:"\u{1D505}",bfr:"\u{1D51F}",bigcap:"\u22C2",bigcirc:"\u25EF",bigcup:"\u22C3",bigodot:"\u2A00",bigoplus:"\u2A01",bigotimes:"\u2A02",bigsqcup:"\u2A06",bigstar:"\u2605",bigtriangledown:"\u25BD",bigtriangleup:"\u25B3",biguplus:"\u2A04",bigvee:"\u22C1",bigwedge:"\u22C0",bkarow:"\u290D",blacklozenge:"\u29EB",blacksquare:"\u25AA",blacktriangle:"\u25B4",blacktriangledown:"\u25BE",blacktriangleleft:"\u25C2",blacktriangleright:"\u25B8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20E5",bnequiv:"\u2261\u20E5",bNot:"\u2AED",bnot:"\u2310",Bopf:"\u{1D539}",bopf:"\u{1D553}",bot:"\u22A5",bottom:"\u22A5",bowtie:"\u22C8",boxbox:"\u29C9",boxDL:"\u2557",boxDl:"\u2556",boxdL:"\u2555",boxdl:"\u2510",boxDR:"\u2554",boxDr:"\u2553",boxdR:"\u2552",boxdr:"\u250C",boxH:"\u2550",boxh:"\u2500",boxHD:"\u2566",boxHd:"\u2564",boxhD:"\u2565",boxhd:"\u252C",boxHU:"\u2569",boxHu:"\u2567",boxhU:"\u2568",boxhu:"\u2534",boxminus:"\u229F",boxplus:"\u229E",boxtimes:"\u22A0",boxUL:"\u255D",boxUl:"\u255C",boxuL:"\u255B",boxul:"\u2518",boxUR:"\u255A",boxUr:"\u2559",boxuR:"\u2558",boxur:"\u2514",boxV:"\u2551",boxv:"\u2502",boxVH:"\u256C",boxVh:"\u256B",boxvH:"\u256A",boxvh:"\u253C",boxVL:"\u2563",boxVl:"\u2562",boxvL:"\u2561",boxvl:"\u2524",boxVR:"\u2560",boxVr:"\u255F",boxvR:"\u255E",boxvr:"\u251C",bprime:"\u2035",Breve:"\u02D8",breve:"\u02D8",brvbar:"\xA6",Bscr:"\u212C",bscr:"\u{1D4B7}",bsemi:"\u204F",bsim:"\u223D",bsime:"\u22CD",bsol:"\\",bsolb:"\u29C5",bsolhsub:"\u27C8",bull:"\u2022",bullet:"\u2022",bump:"\u224E",bumpE:"\u2AAE",bumpe:"\u224F",Bumpeq:"\u224E",bumpeq:"\u224F",Cacute:"\u0106",cacute:"\u0107",Cap:"\u22D2",cap:"\u2229",capand:"\u2A44",capbrcup:"\u2A49",capcap:"\u2A4B",capcup:"\u2A47",capdot:"\u2A40",CapitalDifferentialD:"\u2145",caps:"\u2229\uFE00",caret:"\u2041",caron:"\u02C7",Cayleys:"\u212D",ccaps:"\u2A4D",Ccaron:"\u010C",ccaron:"\u010D",Ccedil:"\xC7",ccedil:"\xE7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2A4C",ccupssm:"\u2A50",Cdot:"\u010A",cdot:"\u010B",cedil:"\xB8",Cedilla:"\xB8",cemptyv:"\u29B2",cent:"\xA2",CenterDot:"\xB7",centerdot:"\xB7",Cfr:"\u212D",cfr:"\u{1D520}",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03A7",chi:"\u03C7",cir:"\u25CB",circ:"\u02C6",circeq:"\u2257",circlearrowleft:"\u21BA",circlearrowright:"\u21BB",circledast:"\u229B",circledcirc:"\u229A",circleddash:"\u229D",CircleDot:"\u2299",circledR:"\xAE",circledS:"\u24C8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cirE:"\u29C3",cire:"\u2257",cirfnint:"\u2A10",cirmid:"\u2AEF",cirscir:"\u29C2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201D",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",Colon:"\u2237",colon:":",Colone:"\u2A74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2A6D",Congruent:"\u2261",Conint:"\u222F",conint:"\u222E",ContourIntegral:"\u222E",Copf:"\u2102",copf:"\u{1D554}",coprod:"\u2210",Coproduct:"\u2210",COPY:"\xA9",copy:"\xA9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21B5",Cross:"\u2A2F",cross:"\u2717",Cscr:"\u{1D49E}",cscr:"\u{1D4B8}",csub:"\u2ACF",csube:"\u2AD1",csup:"\u2AD0",csupe:"\u2AD2",ctdot:"\u22EF",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22DE",cuesc:"\u22DF",cularr:"\u21B6",cularrp:"\u293D",Cup:"\u22D3",cup:"\u222A",cupbrcap:"\u2A48",CupCap:"\u224D",cupcap:"\u2A46",cupcup:"\u2A4A",cupdot:"\u228D",cupor:"\u2A45",cups:"\u222A\uFE00",curarr:"\u21B7",curarrm:"\u293C",curlyeqprec:"\u22DE",curlyeqsucc:"\u22DF",curlyvee:"\u22CE",curlywedge:"\u22CF",curren:"\xA4",curvearrowleft:"\u21B6",curvearrowright:"\u21B7",cuvee:"\u22CE",cuwed:"\u22CF",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232D",Dagger:"\u2021",dagger:"\u2020",daleth:"\u2138",Darr:"\u21A1",dArr:"\u21D3",darr:"\u2193",dash:"\u2010",Dashv:"\u2AE4",dashv:"\u22A3",dbkarow:"\u290F",dblac:"\u02DD",Dcaron:"\u010E",dcaron:"\u010F",Dcy:"\u0414",dcy:"\u0434",DD:"\u2145",dd:"\u2146",ddagger:"\u2021",ddarr:"\u21CA",DDotrahd:"\u2911",ddotseq:"\u2A77",deg:"\xB0",Del:"\u2207",Delta:"\u0394",delta:"\u03B4",demptyv:"\u29B1",dfisht:"\u297F",Dfr:"\u{1D507}",dfr:"\u{1D521}",dHar:"\u2965",dharl:"\u21C3",dharr:"\u21C2",DiacriticalAcute:"\xB4",DiacriticalDot:"\u02D9",DiacriticalDoubleAcute:"\u02DD",DiacriticalGrave:"`",DiacriticalTilde:"\u02DC",diam:"\u22C4",Diamond:"\u22C4",diamond:"\u22C4",diamondsuit:"\u2666",diams:"\u2666",die:"\xA8",DifferentialD:"\u2146",digamma:"\u03DD",disin:"\u22F2",div:"\xF7",divide:"\xF7",divideontimes:"\u22C7",divonx:"\u22C7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231E",dlcrop:"\u230D",dollar:"$",Dopf:"\u{1D53B}",dopf:"\u{1D555}",Dot:"\xA8",dot:"\u02D9",DotDot:"\u20DC",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22A1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222F",DoubleDot:"\xA8",DoubleDownArrow:"\u21D3",DoubleLeftArrow:"\u21D0",DoubleLeftRightArrow:"\u21D4",DoubleLeftTee:"\u2AE4",DoubleLongLeftArrow:"\u27F8",DoubleLongLeftRightArrow:"\u27FA",DoubleLongRightArrow:"\u27F9",DoubleRightArrow:"\u21D2",DoubleRightTee:"\u22A8",DoubleUpArrow:"\u21D1",DoubleUpDownArrow:"\u21D5",DoubleVerticalBar:"\u2225",DownArrow:"\u2193",Downarrow:"\u21D3",downarrow:"\u2193",DownArrowBar:"\u2913",DownArrowUpArrow:"\u21F5",DownBreve:"\u0311",downdownarrows:"\u21CA",downharpoonleft:"\u21C3",downharpoonright:"\u21C2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295E",DownLeftVector:"\u21BD",DownLeftVectorBar:"\u2956",DownRightTeeVector:"\u295F",DownRightVector:"\u21C1",DownRightVectorBar:"\u2957",DownTee:"\u22A4",DownTeeArrow:"\u21A7",drbkarow:"\u2910",drcorn:"\u231F",drcrop:"\u230C",Dscr:"\u{1D49F}",dscr:"\u{1D4B9}",DScy:"\u0405",dscy:"\u0455",dsol:"\u29F6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22F1",dtri:"\u25BF",dtrif:"\u25BE",duarr:"\u21F5",duhar:"\u296F",dwangle:"\u29A6",DZcy:"\u040F",dzcy:"\u045F",dzigrarr:"\u27FF",Eacute:"\xC9",eacute:"\xE9",easter:"\u2A6E",Ecaron:"\u011A",ecaron:"\u011B",ecir:"\u2256",Ecirc:"\xCA",ecirc:"\xEA",ecolon:"\u2255",Ecy:"\u042D",ecy:"\u044D",eDDot:"\u2A77",Edot:"\u0116",eDot:"\u2251",edot:"\u0117",ee:"\u2147",efDot:"\u2252",Efr:"\u{1D508}",efr:"\u{1D522}",eg:"\u2A9A",Egrave:"\xC8",egrave:"\xE8",egs:"\u2A96",egsdot:"\u2A98",el:"\u2A99",Element:"\u2208",elinters:"\u23E7",ell:"\u2113",els:"\u2A95",elsdot:"\u2A97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25FB",emptyv:"\u2205",EmptyVerySmallSquare:"\u25AB",emsp:"\u2003",emsp13:"\u2004",emsp14:"\u2005",ENG:"\u014A",eng:"\u014B",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\u{1D53C}",eopf:"\u{1D556}",epar:"\u22D5",eparsl:"\u29E3",eplus:"\u2A71",epsi:"\u03B5",Epsilon:"\u0395",epsilon:"\u03B5",epsiv:"\u03F5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2A96",eqslantless:"\u2A95",Equal:"\u2A75",equals:"=",EqualTilde:"\u2242",equest:"\u225F",Equilibrium:"\u21CC",equiv:"\u2261",equivDD:"\u2A78",eqvparsl:"\u29E5",erarr:"\u2971",erDot:"\u2253",Escr:"\u2130",escr:"\u212F",esdot:"\u2250",Esim:"\u2A73",esim:"\u2242",Eta:"\u0397",eta:"\u03B7",ETH:"\xD0",eth:"\xF0",Euml:"\xCB",euml:"\xEB",euro:"\u20AC",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",ExponentialE:"\u2147",exponentiale:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\uFB03",fflig:"\uFB00",ffllig:"\uFB04",Ffr:"\u{1D509}",ffr:"\u{1D523}",filig:"\uFB01",FilledSmallSquare:"\u25FC",FilledVerySmallSquare:"\u25AA",fjlig:"fj",flat:"\u266D",fllig:"\uFB02",fltns:"\u25B1",fnof:"\u0192",Fopf:"\u{1D53D}",fopf:"\u{1D557}",ForAll:"\u2200",forall:"\u2200",fork:"\u22D4",forkv:"\u2AD9",Fouriertrf:"\u2131",fpartint:"\u2A0D",frac12:"\xBD",frac13:"\u2153",frac14:"\xBC",frac15:"\u2155",frac16:"\u2159",frac18:"\u215B",frac23:"\u2154",frac25:"\u2156",frac34:"\xBE",frac35:"\u2157",frac38:"\u215C",frac45:"\u2158",frac56:"\u215A",frac58:"\u215D",frac78:"\u215E",frasl:"\u2044",frown:"\u2322",Fscr:"\u2131",fscr:"\u{1D4BB}",gacute:"\u01F5",Gamma:"\u0393",gamma:"\u03B3",Gammad:"\u03DC",gammad:"\u03DD",gap:"\u2A86",Gbreve:"\u011E",gbreve:"\u011F",Gcedil:"\u0122",Gcirc:"\u011C",gcirc:"\u011D",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",gE:"\u2267",ge:"\u2265",gEl:"\u2A8C",gel:"\u22DB",geq:"\u2265",geqq:"\u2267",geqslant:"\u2A7E",ges:"\u2A7E",gescc:"\u2AA9",gesdot:"\u2A80",gesdoto:"\u2A82",gesdotol:"\u2A84",gesl:"\u22DB\uFE00",gesles:"\u2A94",Gfr:"\u{1D50A}",gfr:"\u{1D524}",Gg:"\u22D9",gg:"\u226B",ggg:"\u22D9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gl:"\u2277",gla:"\u2AA5",glE:"\u2A92",glj:"\u2AA4",gnap:"\u2A8A",gnapprox:"\u2A8A",gnE:"\u2269",gne:"\u2A88",gneq:"\u2A88",gneqq:"\u2269",gnsim:"\u22E7",Gopf:"\u{1D53E}",gopf:"\u{1D558}",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22DB",GreaterFullEqual:"\u2267",GreaterGreater:"\u2AA2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2A7E",GreaterTilde:"\u2273",Gscr:"\u{1D4A2}",gscr:"\u210A",gsim:"\u2273",gsime:"\u2A8E",gsiml:"\u2A90",Gt:"\u226B",GT:">",gt:">",gtcc:"\u2AA7",gtcir:"\u2A7A",gtdot:"\u22D7",gtlPar:"\u2995",gtquest:"\u2A7C",gtrapprox:"\u2A86",gtrarr:"\u2978",gtrdot:"\u22D7",gtreqless:"\u22DB",gtreqqless:"\u2A8C",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\uFE00",gvnE:"\u2269\uFE00",Hacek:"\u02C7",hairsp:"\u200A",half:"\xBD",hamilt:"\u210B",HARDcy:"\u042A",hardcy:"\u044A",hArr:"\u21D4",harr:"\u2194",harrcir:"\u2948",harrw:"\u21AD",Hat:"^",hbar:"\u210F",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22B9",Hfr:"\u210C",hfr:"\u{1D525}",HilbertSpace:"\u210B",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21FF",homtht:"\u223B",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",Hopf:"\u210D",hopf:"\u{1D559}",horbar:"\u2015",HorizontalLine:"\u2500",Hscr:"\u210B",hscr:"\u{1D4BD}",hslash:"\u210F",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224E",HumpEqual:"\u224F",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xCD",iacute:"\xED",ic:"\u2063",Icirc:"\xCE",icirc:"\xEE",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xA1",iff:"\u21D4",Ifr:"\u2111",ifr:"\u{1D526}",Igrave:"\xCC",igrave:"\xEC",ii:"\u2148",iiiint:"\u2A0C",iiint:"\u222D",iinfin:"\u29DC",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Im:"\u2111",Imacr:"\u012A",imacr:"\u012B",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",imof:"\u22B7",imped:"\u01B5",Implies:"\u21D2",in:"\u2208",incare:"\u2105",infin:"\u221E",infintie:"\u29DD",inodot:"\u0131",Int:"\u222C",int:"\u222B",intcal:"\u22BA",integers:"\u2124",Integral:"\u222B",intercal:"\u22BA",Intersection:"\u22C2",intlarhk:"\u2A17",intprod:"\u2A3C",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012E",iogon:"\u012F",Iopf:"\u{1D540}",iopf:"\u{1D55A}",Iota:"\u0399",iota:"\u03B9",iprod:"\u2A3C",iquest:"\xBF",Iscr:"\u2110",iscr:"\u{1D4BE}",isin:"\u2208",isindot:"\u22F5",isinE:"\u22F9",isins:"\u22F4",isinsv:"\u22F3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xCF",iuml:"\xEF",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\u{1D50D}",jfr:"\u{1D527}",jmath:"\u0237",Jopf:"\u{1D541}",jopf:"\u{1D55B}",Jscr:"\u{1D4A5}",jscr:"\u{1D4BF}",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039A",kappa:"\u03BA",kappav:"\u03F0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041A",kcy:"\u043A",Kfr:"\u{1D50E}",kfr:"\u{1D528}",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040C",kjcy:"\u045C",Kopf:"\u{1D542}",kopf:"\u{1D55C}",Kscr:"\u{1D4A6}",kscr:"\u{1D4C0}",lAarr:"\u21DA",Lacute:"\u0139",lacute:"\u013A",laemptyv:"\u29B4",lagran:"\u2112",Lambda:"\u039B",lambda:"\u03BB",Lang:"\u27EA",lang:"\u27E8",langd:"\u2991",langle:"\u27E8",lap:"\u2A85",Laplacetrf:"\u2112",laquo:"\xAB",Larr:"\u219E",lArr:"\u21D0",larr:"\u2190",larrb:"\u21E4",larrbfs:"\u291F",larrfs:"\u291D",larrhk:"\u21A9",larrlp:"\u21AB",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21A2",lat:"\u2AAB",lAtail:"\u291B",latail:"\u2919",late:"\u2AAD",lates:"\u2AAD\uFE00",lBarr:"\u290E",lbarr:"\u290C",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298B",lbrksld:"\u298F",lbrkslu:"\u298D",Lcaron:"\u013D",lcaron:"\u013E",Lcedil:"\u013B",lcedil:"\u013C",lceil:"\u2308",lcub:"{",Lcy:"\u041B",lcy:"\u043B",ldca:"\u2936",ldquo:"\u201C",ldquor:"\u201E",ldrdhar:"\u2967",ldrushar:"\u294B",ldsh:"\u21B2",lE:"\u2266",le:"\u2264",LeftAngleBracket:"\u27E8",LeftArrow:"\u2190",Leftarrow:"\u21D0",leftarrow:"\u2190",LeftArrowBar:"\u21E4",LeftArrowRightArrow:"\u21C6",leftarrowtail:"\u21A2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27E6",LeftDownTeeVector:"\u2961",LeftDownVector:"\u21C3",LeftDownVectorBar:"\u2959",LeftFloor:"\u230A",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",leftleftarrows:"\u21C7",LeftRightArrow:"\u2194",Leftrightarrow:"\u21D4",leftrightarrow:"\u2194",leftrightarrows:"\u21C6",leftrightharpoons:"\u21CB",leftrightsquigarrow:"\u21AD",LeftRightVector:"\u294E",LeftTee:"\u22A3",LeftTeeArrow:"\u21A4",LeftTeeVector:"\u295A",leftthreetimes:"\u22CB",LeftTriangle:"\u22B2",LeftTriangleBar:"\u29CF",LeftTriangleEqual:"\u22B4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVector:"\u21BF",LeftUpVectorBar:"\u2958",LeftVector:"\u21BC",LeftVectorBar:"\u2952",lEg:"\u2A8B",leg:"\u22DA",leq:"\u2264",leqq:"\u2266",leqslant:"\u2A7D",les:"\u2A7D",lescc:"\u2AA8",lesdot:"\u2A7F",lesdoto:"\u2A81",lesdotor:"\u2A83",lesg:"\u22DA\uFE00",lesges:"\u2A93",lessapprox:"\u2A85",lessdot:"\u22D6",lesseqgtr:"\u22DA",lesseqqgtr:"\u2A8B",LessEqualGreater:"\u22DA",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2AA1",lesssim:"\u2272",LessSlantEqual:"\u2A7D",LessTilde:"\u2272",lfisht:"\u297C",lfloor:"\u230A",Lfr:"\u{1D50F}",lfr:"\u{1D529}",lg:"\u2276",lgE:"\u2A91",lHar:"\u2962",lhard:"\u21BD",lharu:"\u21BC",lharul:"\u296A",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",Ll:"\u22D8",ll:"\u226A",llarr:"\u21C7",llcorner:"\u231E",Lleftarrow:"\u21DA",llhard:"\u296B",lltri:"\u25FA",Lmidot:"\u013F",lmidot:"\u0140",lmoust:"\u23B0",lmoustache:"\u23B0",lnap:"\u2A89",lnapprox:"\u2A89",lnE:"\u2268",lne:"\u2A87",lneq:"\u2A87",lneqq:"\u2268",lnsim:"\u22E6",loang:"\u27EC",loarr:"\u21FD",lobrk:"\u27E6",LongLeftArrow:"\u27F5",Longleftarrow:"\u27F8",longleftarrow:"\u27F5",LongLeftRightArrow:"\u27F7",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",LongRightArrow:"\u27F6",Longrightarrow:"\u27F9",longrightarrow:"\u27F6",looparrowleft:"\u21AB",looparrowright:"\u21AC",lopar:"\u2985",Lopf:"\u{1D543}",lopf:"\u{1D55D}",loplus:"\u2A2D",lotimes:"\u2A34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25CA",lozenge:"\u25CA",lozf:"\u29EB",lpar:"(",lparlt:"\u2993",lrarr:"\u21C6",lrcorner:"\u231F",lrhar:"\u21CB",lrhard:"\u296D",lrm:"\u200E",lrtri:"\u22BF",lsaquo:"\u2039",Lscr:"\u2112",lscr:"\u{1D4C1}",Lsh:"\u21B0",lsh:"\u21B0",lsim:"\u2272",lsime:"\u2A8D",lsimg:"\u2A8F",lsqb:"[",lsquo:"\u2018",lsquor:"\u201A",Lstrok:"\u0141",lstrok:"\u0142",Lt:"\u226A",LT:"<",lt:"<",ltcc:"\u2AA6",ltcir:"\u2A79",ltdot:"\u22D6",lthree:"\u22CB",ltimes:"\u22C9",ltlarr:"\u2976",ltquest:"\u2A7B",ltri:"\u25C3",ltrie:"\u22B4",ltrif:"\u25C2",ltrPar:"\u2996",lurdshar:"\u294A",luruhar:"\u2966",lvertneqq:"\u2268\uFE00",lvnE:"\u2268\uFE00",macr:"\xAF",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21A6",mapsto:"\u21A6",mapstodown:"\u21A7",mapstoleft:"\u21A4",mapstoup:"\u21A5",marker:"\u25AE",mcomma:"\u2A29",Mcy:"\u041C",mcy:"\u043C",mdash:"\u2014",mDDot:"\u223A",measuredangle:"\u2221",MediumSpace:"\u205F",Mellintrf:"\u2133",Mfr:"\u{1D510}",mfr:"\u{1D52A}",mho:"\u2127",micro:"\xB5",mid:"\u2223",midast:"*",midcir:"\u2AF0",middot:"\xB7",minus:"\u2212",minusb:"\u229F",minusd:"\u2238",minusdu:"\u2A2A",MinusPlus:"\u2213",mlcp:"\u2ADB",mldr:"\u2026",mnplus:"\u2213",models:"\u22A7",Mopf:"\u{1D544}",mopf:"\u{1D55E}",mp:"\u2213",Mscr:"\u2133",mscr:"\u{1D4C2}",mstpos:"\u223E",Mu:"\u039C",mu:"\u03BC",multimap:"\u22B8",mumap:"\u22B8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20D2",nap:"\u2249",napE:"\u2A70\u0338",napid:"\u224B\u0338",napos:"\u0149",napprox:"\u2249",natur:"\u266E",natural:"\u266E",naturals:"\u2115",nbsp:"\xA0",nbump:"\u224E\u0338",nbumpe:"\u224F\u0338",ncap:"\u2A43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2A6D\u0338",ncup:"\u2A42",Ncy:"\u041D",ncy:"\u043D",ndash:"\u2013",ne:"\u2260",nearhk:"\u2924",neArr:"\u21D7",nearr:"\u2197",nearrow:"\u2197",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200B",NegativeThickSpace:"\u200B",NegativeThinSpace:"\u200B",NegativeVeryThinSpace:"\u200B",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226B",NestedLessLess:"\u226A",NewLine:`
|
|
10
|
+
`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29BF",Ofr:"\u{1D512}",ofr:"\u{1D52C}",ogon:"\u02DB",Ograve:"\xD2",ograve:"\xF2",ogt:"\u29C1",ohbar:"\u29B5",ohm:"\u03A9",oint:"\u222E",olarr:"\u21BA",olcir:"\u29BE",olcross:"\u29BB",oline:"\u203E",olt:"\u29C0",Omacr:"\u014C",omacr:"\u014D",Omega:"\u03A9",omega:"\u03C9",Omicron:"\u039F",omicron:"\u03BF",omid:"\u29B6",ominus:"\u2296",Oopf:"\u{1D546}",oopf:"\u{1D560}",opar:"\u29B7",OpenCurlyDoubleQuote:"\u201C",OpenCurlyQuote:"\u2018",operp:"\u29B9",oplus:"\u2295",Or:"\u2A54",or:"\u2228",orarr:"\u21BB",ord:"\u2A5D",order:"\u2134",orderof:"\u2134",ordf:"\xAA",ordm:"\xBA",origof:"\u22B6",oror:"\u2A56",orslope:"\u2A57",orv:"\u2A5B",oS:"\u24C8",Oscr:"\u{1D4AA}",oscr:"\u2134",Oslash:"\xD8",oslash:"\xF8",osol:"\u2298",Otilde:"\xD5",otilde:"\xF5",Otimes:"\u2A37",otimes:"\u2297",otimesas:"\u2A36",Ouml:"\xD6",ouml:"\xF6",ovbar:"\u233D",OverBar:"\u203E",OverBrace:"\u23DE",OverBracket:"\u23B4",OverParenthesis:"\u23DC",par:"\u2225",para:"\xB6",parallel:"\u2225",parsim:"\u2AF3",parsl:"\u2AFD",part:"\u2202",PartialD:"\u2202",Pcy:"\u041F",pcy:"\u043F",percnt:"%",period:".",permil:"\u2030",perp:"\u22A5",pertenk:"\u2031",Pfr:"\u{1D513}",pfr:"\u{1D52D}",Phi:"\u03A6",phi:"\u03C6",phiv:"\u03D5",phmmat:"\u2133",phone:"\u260E",Pi:"\u03A0",pi:"\u03C0",pitchfork:"\u22D4",piv:"\u03D6",planck:"\u210F",planckh:"\u210E",plankv:"\u210F",plus:"+",plusacir:"\u2A23",plusb:"\u229E",pluscir:"\u2A22",plusdo:"\u2214",plusdu:"\u2A25",pluse:"\u2A72",PlusMinus:"\xB1",plusmn:"\xB1",plussim:"\u2A26",plustwo:"\u2A27",pm:"\xB1",Poincareplane:"\u210C",pointint:"\u2A15",Popf:"\u2119",popf:"\u{1D561}",pound:"\xA3",Pr:"\u2ABB",pr:"\u227A",prap:"\u2AB7",prcue:"\u227C",prE:"\u2AB3",pre:"\u2AAF",prec:"\u227A",precapprox:"\u2AB7",preccurlyeq:"\u227C",Precedes:"\u227A",PrecedesEqual:"\u2AAF",PrecedesSlantEqual:"\u227C",PrecedesTilde:"\u227E",preceq:"\u2AAF",precnapprox:"\u2AB9",precneqq:"\u2AB5",precnsim:"\u22E8",precsim:"\u227E",Prime:"\u2033",prime:"\u2032",primes:"\u2119",prnap:"\u2AB9",prnE:"\u2AB5",prnsim:"\u22E8",prod:"\u220F",Product:"\u220F",profalar:"\u232E",profline:"\u2312",profsurf:"\u2313",prop:"\u221D",Proportion:"\u2237",Proportional:"\u221D",propto:"\u221D",prsim:"\u227E",prurel:"\u22B0",Pscr:"\u{1D4AB}",pscr:"\u{1D4C5}",Psi:"\u03A8",psi:"\u03C8",puncsp:"\u2008",Qfr:"\u{1D514}",qfr:"\u{1D52E}",qint:"\u2A0C",Qopf:"\u211A",qopf:"\u{1D562}",qprime:"\u2057",Qscr:"\u{1D4AC}",qscr:"\u{1D4C6}",quaternions:"\u210D",quatint:"\u2A16",quest:"?",questeq:"\u225F",QUOT:'"',quot:'"',rAarr:"\u21DB",race:"\u223D\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221A",raemptyv:"\u29B3",Rang:"\u27EB",rang:"\u27E9",rangd:"\u2992",range:"\u29A5",rangle:"\u27E9",raquo:"\xBB",Rarr:"\u21A0",rArr:"\u21D2",rarr:"\u2192",rarrap:"\u2975",rarrb:"\u21E5",rarrbfs:"\u2920",rarrc:"\u2933",rarrfs:"\u291E",rarrhk:"\u21AA",rarrlp:"\u21AC",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21A3",rarrw:"\u219D",rAtail:"\u291C",ratail:"\u291A",ratio:"\u2236",rationals:"\u211A",RBarr:"\u2910",rBarr:"\u290F",rbarr:"\u290D",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298C",rbrksld:"\u298E",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201D",rdquor:"\u201D",rdsh:"\u21B3",Re:"\u211C",real:"\u211C",realine:"\u211B",realpart:"\u211C",reals:"\u211D",rect:"\u25AD",REG:"\xAE",reg:"\xAE",ReverseElement:"\u220B",ReverseEquilibrium:"\u21CB",ReverseUpEquilibrium:"\u296F",rfisht:"\u297D",rfloor:"\u230B",Rfr:"\u211C",rfr:"\u{1D52F}",rHar:"\u2964",rhard:"\u21C1",rharu:"\u21C0",rharul:"\u296C",Rho:"\u03A1",rho:"\u03C1",rhov:"\u03F1",RightAngleBracket:"\u27E9",RightArrow:"\u2192",Rightarrow:"\u21D2",rightarrow:"\u2192",RightArrowBar:"\u21E5",RightArrowLeftArrow:"\u21C4",rightarrowtail:"\u21A3",RightCeiling:"\u2309",RightDoubleBracket:"\u27E7",RightDownTeeVector:"\u295D",RightDownVector:"\u21C2",RightDownVectorBar:"\u2955",RightFloor:"\u230B",rightharpoondown:"\u21C1",rightharpoonup:"\u21C0",rightleftarrows:"\u21C4",rightleftharpoons:"\u21CC",rightrightarrows:"\u21C9",rightsquigarrow:"\u219D",RightTee:"\u22A2",RightTeeArrow:"\u21A6",RightTeeVector:"\u295B",rightthreetimes:"\u22CC",RightTriangle:"\u22B3",RightTriangleBar:"\u29D0",RightTriangleEqual:"\u22B5",RightUpDownVector:"\u294F",RightUpTeeVector:"\u295C",RightUpVector:"\u21BE",RightUpVectorBar:"\u2954",RightVector:"\u21C0",RightVectorBar:"\u2953",ring:"\u02DA",risingdotseq:"\u2253",rlarr:"\u21C4",rlhar:"\u21CC",rlm:"\u200F",rmoust:"\u23B1",rmoustache:"\u23B1",rnmid:"\u2AEE",roang:"\u27ED",roarr:"\u21FE",robrk:"\u27E7",ropar:"\u2986",Ropf:"\u211D",ropf:"\u{1D563}",roplus:"\u2A2E",rotimes:"\u2A35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2A12",rrarr:"\u21C9",Rrightarrow:"\u21DB",rsaquo:"\u203A",Rscr:"\u211B",rscr:"\u{1D4C7}",Rsh:"\u21B1",rsh:"\u21B1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22CC",rtimes:"\u22CA",rtri:"\u25B9",rtrie:"\u22B5",rtrif:"\u25B8",rtriltri:"\u29CE",RuleDelayed:"\u29F4",ruluhar:"\u2968",rx:"\u211E",Sacute:"\u015A",sacute:"\u015B",sbquo:"\u201A",Sc:"\u2ABC",sc:"\u227B",scap:"\u2AB8",Scaron:"\u0160",scaron:"\u0161",sccue:"\u227D",scE:"\u2AB4",sce:"\u2AB0",Scedil:"\u015E",scedil:"\u015F",Scirc:"\u015C",scirc:"\u015D",scnap:"\u2ABA",scnE:"\u2AB6",scnsim:"\u22E9",scpolint:"\u2A13",scsim:"\u227F",Scy:"\u0421",scy:"\u0441",sdot:"\u22C5",sdotb:"\u22A1",sdote:"\u2A66",searhk:"\u2925",seArr:"\u21D8",searr:"\u2198",searrow:"\u2198",sect:"\xA7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\u{1D516}",sfr:"\u{1D530}",sfrown:"\u2322",sharp:"\u266F",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xAD",Sigma:"\u03A3",sigma:"\u03C3",sigmaf:"\u03C2",sigmav:"\u03C2",sim:"\u223C",simdot:"\u2A6A",sime:"\u2243",simeq:"\u2243",simg:"\u2A9E",simgE:"\u2AA0",siml:"\u2A9D",simlE:"\u2A9F",simne:"\u2246",simplus:"\u2A24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2A33",smeparsl:"\u29E4",smid:"\u2223",smile:"\u2323",smt:"\u2AAA",smte:"\u2AAC",smtes:"\u2AAC\uFE00",SOFTcy:"\u042C",softcy:"\u044C",sol:"/",solb:"\u29C4",solbar:"\u233F",Sopf:"\u{1D54A}",sopf:"\u{1D564}",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\uFE00",sqcup:"\u2294",sqcups:"\u2294\uFE00",Sqrt:"\u221A",sqsub:"\u228F",sqsube:"\u2291",sqsubset:"\u228F",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",squ:"\u25A1",Square:"\u25A1",square:"\u25A1",SquareIntersection:"\u2293",SquareSubset:"\u228F",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25AA",squf:"\u25AA",srarr:"\u2192",Sscr:"\u{1D4AE}",sscr:"\u{1D4C8}",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22C6",Star:"\u22C6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03F5",straightphi:"\u03D5",strns:"\xAF",Sub:"\u22D0",sub:"\u2282",subdot:"\u2ABD",subE:"\u2AC5",sube:"\u2286",subedot:"\u2AC3",submult:"\u2AC1",subnE:"\u2ACB",subne:"\u228A",subplus:"\u2ABF",subrarr:"\u2979",Subset:"\u22D0",subset:"\u2282",subseteq:"\u2286",subseteqq:"\u2AC5",SubsetEqual:"\u2286",subsetneq:"\u228A",subsetneqq:"\u2ACB",subsim:"\u2AC7",subsub:"\u2AD5",subsup:"\u2AD3",succ:"\u227B",succapprox:"\u2AB8",succcurlyeq:"\u227D",Succeeds:"\u227B",SucceedsEqual:"\u2AB0",SucceedsSlantEqual:"\u227D",SucceedsTilde:"\u227F",succeq:"\u2AB0",succnapprox:"\u2ABA",succneqq:"\u2AB6",succnsim:"\u22E9",succsim:"\u227F",SuchThat:"\u220B",Sum:"\u2211",sum:"\u2211",sung:"\u266A",Sup:"\u22D1",sup:"\u2283",sup1:"\xB9",sup2:"\xB2",sup3:"\xB3",supdot:"\u2ABE",supdsub:"\u2AD8",supE:"\u2AC6",supe:"\u2287",supedot:"\u2AC4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27C9",suphsub:"\u2AD7",suplarr:"\u297B",supmult:"\u2AC2",supnE:"\u2ACC",supne:"\u228B",supplus:"\u2AC0",Supset:"\u22D1",supset:"\u2283",supseteq:"\u2287",supseteqq:"\u2AC6",supsetneq:"\u228B",supsetneqq:"\u2ACC",supsim:"\u2AC8",supsub:"\u2AD4",supsup:"\u2AD6",swarhk:"\u2926",swArr:"\u21D9",swarr:"\u2199",swarrow:"\u2199",swnwar:"\u292A",szlig:"\xDF",Tab:" ",target:"\u2316",Tau:"\u03A4",tau:"\u03C4",tbrk:"\u23B4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20DB",telrec:"\u2315",Tfr:"\u{1D517}",tfr:"\u{1D531}",there4:"\u2234",Therefore:"\u2234",therefore:"\u2234",Theta:"\u0398",theta:"\u03B8",thetasym:"\u03D1",thetav:"\u03D1",thickapprox:"\u2248",thicksim:"\u223C",ThickSpace:"\u205F\u200A",thinsp:"\u2009",ThinSpace:"\u2009",thkap:"\u2248",thksim:"\u223C",THORN:"\xDE",thorn:"\xFE",Tilde:"\u223C",tilde:"\u02DC",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",times:"\xD7",timesb:"\u22A0",timesbar:"\u2A31",timesd:"\u2A30",tint:"\u222D",toea:"\u2928",top:"\u22A4",topbot:"\u2336",topcir:"\u2AF1",Topf:"\u{1D54B}",topf:"\u{1D565}",topfork:"\u2ADA",tosa:"\u2929",tprime:"\u2034",TRADE:"\u2122",trade:"\u2122",triangle:"\u25B5",triangledown:"\u25BF",triangleleft:"\u25C3",trianglelefteq:"\u22B4",triangleq:"\u225C",triangleright:"\u25B9",trianglerighteq:"\u22B5",tridot:"\u25EC",trie:"\u225C",triminus:"\u2A3A",TripleDot:"\u20DB",triplus:"\u2A39",trisb:"\u29CD",tritime:"\u2A3B",trpezium:"\u23E2",Tscr:"\u{1D4AF}",tscr:"\u{1D4C9}",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040B",tshcy:"\u045B",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226C",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",Uacute:"\xDA",uacute:"\xFA",Uarr:"\u219F",uArr:"\u21D1",uarr:"\u2191",Uarrocir:"\u2949",Ubrcy:"\u040E",ubrcy:"\u045E",Ubreve:"\u016C",ubreve:"\u016D",Ucirc:"\xDB",ucirc:"\xFB",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21C5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296E",ufisht:"\u297E",Ufr:"\u{1D518}",ufr:"\u{1D532}",Ugrave:"\xD9",ugrave:"\xF9",uHar:"\u2963",uharl:"\u21BF",uharr:"\u21BE",uhblk:"\u2580",ulcorn:"\u231C",ulcorner:"\u231C",ulcrop:"\u230F",ultri:"\u25F8",Umacr:"\u016A",umacr:"\u016B",uml:"\xA8",UnderBar:"_",UnderBrace:"\u23DF",UnderBracket:"\u23B5",UnderParenthesis:"\u23DD",Union:"\u22C3",UnionPlus:"\u228E",Uogon:"\u0172",uogon:"\u0173",Uopf:"\u{1D54C}",uopf:"\u{1D566}",UpArrow:"\u2191",Uparrow:"\u21D1",uparrow:"\u2191",UpArrowBar:"\u2912",UpArrowDownArrow:"\u21C5",UpDownArrow:"\u2195",Updownarrow:"\u21D5",updownarrow:"\u2195",UpEquilibrium:"\u296E",upharpoonleft:"\u21BF",upharpoonright:"\u21BE",uplus:"\u228E",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",Upsi:"\u03D2",upsi:"\u03C5",upsih:"\u03D2",Upsilon:"\u03A5",upsilon:"\u03C5",UpTee:"\u22A5",UpTeeArrow:"\u21A5",upuparrows:"\u21C8",urcorn:"\u231D",urcorner:"\u231D",urcrop:"\u230E",Uring:"\u016E",uring:"\u016F",urtri:"\u25F9",Uscr:"\u{1D4B0}",uscr:"\u{1D4CA}",utdot:"\u22F0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25B5",utrif:"\u25B4",uuarr:"\u21C8",Uuml:"\xDC",uuml:"\xFC",uwangle:"\u29A7",vangrt:"\u299C",varepsilon:"\u03F5",varkappa:"\u03F0",varnothing:"\u2205",varphi:"\u03D5",varpi:"\u03D6",varpropto:"\u221D",vArr:"\u21D5",varr:"\u2195",varrho:"\u03F1",varsigma:"\u03C2",varsubsetneq:"\u228A\uFE00",varsubsetneqq:"\u2ACB\uFE00",varsupsetneq:"\u228B\uFE00",varsupsetneqq:"\u2ACC\uFE00",vartheta:"\u03D1",vartriangleleft:"\u22B2",vartriangleright:"\u22B3",Vbar:"\u2AEB",vBar:"\u2AE8",vBarv:"\u2AE9",Vcy:"\u0412",vcy:"\u0432",VDash:"\u22AB",Vdash:"\u22A9",vDash:"\u22A8",vdash:"\u22A2",Vdashl:"\u2AE6",Vee:"\u22C1",vee:"\u2228",veebar:"\u22BB",veeeq:"\u225A",vellip:"\u22EE",Verbar:"\u2016",verbar:"|",Vert:"\u2016",vert:"|",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200A",Vfr:"\u{1D519}",vfr:"\u{1D533}",vltri:"\u22B2",vnsub:"\u2282\u20D2",vnsup:"\u2283\u20D2",Vopf:"\u{1D54D}",vopf:"\u{1D567}",vprop:"\u221D",vrtri:"\u22B3",Vscr:"\u{1D4B1}",vscr:"\u{1D4CB}",vsubnE:"\u2ACB\uFE00",vsubne:"\u228A\uFE00",vsupnE:"\u2ACC\uFE00",vsupne:"\u228B\uFE00",Vvdash:"\u22AA",vzigzag:"\u299A",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2A5F",Wedge:"\u22C0",wedge:"\u2227",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\u{1D51A}",wfr:"\u{1D534}",Wopf:"\u{1D54E}",wopf:"\u{1D568}",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\u{1D4B2}",wscr:"\u{1D4CC}",xcap:"\u22C2",xcirc:"\u25EF",xcup:"\u22C3",xdtri:"\u25BD",Xfr:"\u{1D51B}",xfr:"\u{1D535}",xhArr:"\u27FA",xharr:"\u27F7",Xi:"\u039E",xi:"\u03BE",xlArr:"\u27F8",xlarr:"\u27F5",xmap:"\u27FC",xnis:"\u22FB",xodot:"\u2A00",Xopf:"\u{1D54F}",xopf:"\u{1D569}",xoplus:"\u2A01",xotime:"\u2A02",xrArr:"\u27F9",xrarr:"\u27F6",Xscr:"\u{1D4B3}",xscr:"\u{1D4CD}",xsqcup:"\u2A06",xuplus:"\u2A04",xutri:"\u25B3",xvee:"\u22C1",xwedge:"\u22C0",Yacute:"\xDD",yacute:"\xFD",YAcy:"\u042F",yacy:"\u044F",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042B",ycy:"\u044B",yen:"\xA5",Yfr:"\u{1D51C}",yfr:"\u{1D536}",YIcy:"\u0407",yicy:"\u0457",Yopf:"\u{1D550}",yopf:"\u{1D56A}",Yscr:"\u{1D4B4}",yscr:"\u{1D4CE}",YUcy:"\u042E",yucy:"\u044E",Yuml:"\u0178",yuml:"\xFF",Zacute:"\u0179",zacute:"\u017A",Zcaron:"\u017D",zcaron:"\u017E",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017B",zdot:"\u017C",zeetrf:"\u2128",ZeroWidthSpace:"\u200B",Zeta:"\u0396",zeta:"\u03B6",Zfr:"\u2128",zfr:"\u{1D537}",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21DD",Zopf:"\u2124",zopf:"\u{1D56B}",Zscr:"\u{1D4B5}",zscr:"\u{1D4CF}",zwj:"\u200D",zwnj:"\u200C"});ri.entityMap=ri.HTML_ENTITIES});var ch=lr(Ua=>{"use strict";var Wn=Hr(),Y=hu(),ih=Wo(),$_=Wn.isHTMLEscapableRawTextElement,M_=Wn.isHTMLMimeType,P_=Wn.isHTMLRawTextElement,ii=Wn.hasOwn,rh=Wn.NAMESPACE,L_=ih.ParseError,F_=ih.DOMException,Vn=0,yr=1,zn=2,ni=3,Hn=4,Gn=5,oi=6,qa=7;function ah(){}ah.prototype={parse:function(n,e,t){var r=this.domBuilder;r.startDocument(),V_(e,e=Object.create(null)),j_(n,e,t,r,this.errorHandler),r.endDocument()}};var ku=/&#?\w+;?/g;function j_(n,e,t,r,o){var i=M_(r.mimeType);n.indexOf(Y.UNICODE_REPLACEMENT_CHARACTER)>=0&&o.warning("Unicode replacement character detected, source encoding issues?");function a(Z){if(Z>65535){Z-=65536;var Be=55296+(Z>>10),zt=56320+(Z&1023);return String.fromCharCode(Be,zt)}else return String.fromCharCode(Z)}function s(Z){var Be=Z[Z.length-1]===";"?Z:Z+";";if(!i&&Be!==Z)return o.error("EntityRef: expecting ;"),Z;var zt=Y.Reference.exec(Be);if(!zt||zt[0].length!==Be.length)return o.error("entity not matching Reference production: "+Z),Z;var En=Be.slice(1,-1);return ii(t,En)?t[En]:En.charAt(0)==="#"?a(parseInt(En.substring(1).replace("x","0x"))):(o.error("entity not found:"+Z),Z)}function l(Z){if(Z>b){var Be=n.substring(b,Z).replace(ku,s);f&&h(b),r.characters(Be,0,Z-b),b=Z}}var u=0,c=0,d=/\r\n?|\n|$/g,f=r.locator;function h(Z,Be){for(;Z>=c&&(Be=d.exec(n));)u=c,c=Be.index+Be[0].length,f.lineNumber++;f.columnNumber=Z-u+1}for(var p=[{currentNSMap:e}],m=[],b=0;;){try{var w=n.indexOf("<",b);if(w<0){if(!i&&m.length>0)return o.fatalError("unclosed xml tag(s): "+m.join(", "));if(!n.substring(b).match(/^\s*$/)){var _=r.doc,y=_.createTextNode(n.substring(b));if(_.documentElement)return o.error("Extra content at the end of the document");_.appendChild(y),r.currentElement=y}return}if(w>b){var x=n.substring(b,w);!i&&m.length===0&&(x=x.replace(new RegExp(Y.S_OPT.source,"g"),""),x&&o.error("Unexpected content outside root element: '"+x+"'")),l(w)}switch(n.charAt(w+1)){case"/":var U=n.indexOf(">",w+2),D=n.substring(w+2,U>0?U:void 0);if(!D)return o.fatalError("end tag name missing");var k=Y.reg("^",Y.QName_group,Y.S_OPT,"$"),C=U>0&&k.exec(D);if(!C){var O=U>0&&Y.reg("^",Y.QName_group).exec(D);if(i&&O)o.warning('end tag name contains invalid trailing characters: "'+D+'"'),C=O;else if(O&&new RegExp(k.source,k.flags+"m").test(D))o.error('end tag name is followed by a line break and trailing content: "'+D+'"'),C=O;else return o.fatalError('end tag name contains invalid characters: "'+D+'"')}if(!r.currentElement&&!r.doc.documentElement)return;var $=m[m.length-1]||r.currentElement.tagName||r.doc.documentElement.tagName||"";if($!==C[1]){var F=C[1].toLowerCase();if(!i||$.toLowerCase()!==F)return o.fatalError('Opening and ending tag mismatch: "'+$+'" != "'+D+'"')}var H=p.pop();m.pop();var Q=H.localNSMap;if(r.endElement(H.uri,H.localName,$),Q)for(var me in Q)ii(Q,me)&&r.endPrefixMapping(me);U++;break;case"?":f&&h(w),U=H_(n,w,r,o);break;case"!":f&&h(w),U=lh(n,w,r,o,i);break;default:f&&h(w);var re=new uh,ue=p[p.length-1].currentNSMap,U=q_(n,w,re,ue,s,o,i),dt=re.length;if(re.closed||(i&&Wn.isHTMLVoidElement(re.tagName)?re.closed=!0:m.push(re.tagName)),f&&dt){for(var yn=nh(f,{}),vn=0;vn<dt;vn++){var wt=re[vn];h(wt.offset),wt.locator=nh(f,{})}r.locator=yn,oh(re,r,ue)&&p.push(re),r.locator=f}else oh(re,r,ue)&&p.push(re);i&&!re.closed?U=U_(n,U,re.tagName,s,r):U++}}catch(Z){if(Z instanceof L_)throw Z;if(Z instanceof F_)return o.fatalError("Error constructing the DOM: "+Z.name+": "+Z.message,Z);o.error("element parse error: "+Z),U=-1}U>b?b=U:l(Math.max(w,b)+1)}}function nh(n,e){return e.lineNumber=n.lineNumber,e.columnNumber=n.columnNumber,e}function q_(n,e,t,r,o,i,a){function s(h,p,m){if(ii(t.attributeNames,h))return i.fatalError("Attribute "+h+" redefined");if(!a&&p.indexOf("<")>=0)return i.fatalError("Unescaped '<' not allowed in attributes values");t.addValue(h,p.replace(/[\t\n\r]/g," ").replace(ku,o),m)}for(var l,u,c=++e,d=Vn;;){var f=n.charAt(c);if(d===Vn&&f==="<")throw new Error("unexpected < in tag name: "+n.slice(e,c));switch(f){case"=":if(d===yr)l=n.slice(e,c),d=ni;else if(d===zn)d=ni;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(d===ni||d===yr)if(d===yr&&(i.warning('attribute value must after "="'),l=n.slice(e,c)),e=c+1,c=n.indexOf(f,e),c>0)u=n.slice(e,c),s(l,u,e-1),d=Gn;else throw new Error("attribute value no end '"+f+"' match");else if(d==Hn)u=n.slice(e,c),s(l,u,e),i.warning('attribute "'+l+'" missed start quot('+f+")!!"),e=c+1,d=Gn;else throw new Error('attribute value must after "="');break;case"/":switch(d){case Vn:t.setTagName(n.slice(e,c));case Gn:case oi:case qa:d=qa,t.closed=!0;case Hn:case yr:break;case zn:t.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return i.error("unexpected end of input"),d==Vn&&t.setTagName(n.slice(e,c)),c;case">":switch(d){case Vn:t.setTagName(n.slice(e,c));case Gn:case oi:case qa:break;case Hn:case yr:u=n.slice(e,c),u.slice(-1)==="/"&&(t.closed=!0,u=u.slice(0,-1));case zn:d===zn&&(u=l),d==Hn?(i.warning('attribute "'+u+'" missed quot(")!'),s(l,u,e)):(a||i.warning('attribute "'+u+'" missed value!! "'+u+'" instead!!'),s(u,u,e));break;case ni:if(!a)return i.fatalError(`AttValue: ' or " expected`)}return c;case"\x80":f=" ";default:if(f<=" ")switch(d){case Vn:t.setTagName(n.slice(e,c)),d=oi;break;case yr:l=n.slice(e,c),d=zn;break;case Hn:var u=n.slice(e,c);i.warning('attribute "'+u+'" missed quot(")!!'),s(l,u,e);case Gn:d=oi;break}else switch(d){case zn:a||i.warning('attribute "'+l+'" missed value!! "'+l+'" instead2!!'),s(l,l,e),e=c,d=yr;break;case Gn:i.warning('attribute space is required"'+l+'"!!');case oi:d=yr,e=c;break;case ni:d=Hn,e=c;break;case qa:throw new Error("elements closed character '/' and '>' must be connected to")}}c++}}function oh(n,e,t){for(var r=n.tagName,o=null,d=n.length;d--;){var i=n[d],a=i.qName,s=i.value,f=a.indexOf(":");if(f>0)var l=i.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";i.localName=u,c!==!1&&(o==null&&(o=Object.create(null),t=Object.create(t)),t[c]=o[c]=s,i.uri=rh.XMLNS,e.startPrefixMapping(c,s))}for(var d=n.length;d--;)i=n[d],i.prefix&&(i.prefix==="xml"&&(i.uri=rh.XML),i.prefix!=="xmlns"&&(i.uri=t[i.prefix]));var f=r.indexOf(":");f>0?(l=n.prefix=r.slice(0,f),u=n.localName=r.slice(f+1)):(l=null,u=n.localName=r);var h=n.uri=t[l||""];if(e.startElement(h,u,r,n),n.closed){if(e.endElement(h,u,r),o)for(l in o)ii(o,l)&&e.endPrefixMapping(l)}else return n.currentNSMap=t,n.localNSMap=o,!0}function U_(n,e,t,r,o){var i=$_(t);if(i||P_(t)){var a=new RegExp("</"+t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+">","ig");a.lastIndex=e;var s=a.exec(n),l=s?s.index:-1;if(l<0)return e+1;var u=n.substring(e+1,l);return i&&(u=u.replace(ku,r)),o.characters(u,0,u.length),l}return e+1}function V_(n,e){for(var t in n)ii(n,t)&&(e[t]=n[t])}function sh(n,e){var t=e;function r(c){return c=c||0,n.charAt(t+c)}function o(c){c=c||1,t+=c}function i(){for(var c=0;t<n.length;){var d=r();if(d!==" "&&d!==`
|
|
11
|
+
`&&d!==" "&&d!=="\r")return c;c++,o()}return-1}function a(){return n.substring(t)}function s(c){return n.substring(t,t+c.length)===c}function l(c){return n.substring(t,t+c.length).toUpperCase()===c.toUpperCase()}function u(c){var d=Y.reg("^",c),f=d.exec(a());return f?(o(f[0].length),f[0]):null}return{char:r,getIndex:function(){return t},getMatch:u,getSource:function(){return n},skip:o,skipBlanks:i,substringFromIndex:a,substringStartsWith:s,substringStartsWithCaseInsensitive:l}}function z_(n,e){function t(s,l){var u=Y.PI.exec(s.substringFromIndex());return u?u[1].toLowerCase()==="xml"?l.fatalError("xml declaration is only allowed at the start of the document, but found at position "+s.getIndex()):(s.skip(u[0].length),u[0]):l.fatalError("processing instruction is not well-formed at position "+s.getIndex())}var r=n.getSource();if(n.char()==="["){n.skip(1);for(var o=n.getIndex();n.getIndex()<r.length;){if(n.skipBlanks(),n.char()==="]"){var i=r.substring(o,n.getIndex());return n.skip(1),i}var a=null;if(n.char()==="<"&&n.char(1)==="!")switch(n.char(2)){case"E":n.char(3)==="L"?a=n.getMatch(Y.elementdecl):n.char(3)==="N"&&(a=n.getMatch(Y.EntityDecl));break;case"A":a=n.getMatch(Y.AttlistDecl);break;case"N":a=n.getMatch(Y.NotationDecl);break;case"-":a=n.getMatch(Y.Comment);break}else if(n.char()==="<"&&n.char(1)==="?")a=t(n,e);else if(n.char()==="%")a=n.getMatch(Y.PEReference);else return e.fatalError("Error detected in Markup declaration");if(!a)return e.fatalError("Error in internal subset at position "+n.getIndex())}return e.fatalError("doctype internal subset is not well-formed, missing ]")}}function lh(n,e,t,r,o){var i=sh(n,e);switch(o?i.char(2).toUpperCase():i.char(2)){case"-":var a=i.getMatch(Y.Comment);return a?(t.comment(a,Y.COMMENT_START.length,a.length-Y.COMMENT_START.length-Y.COMMENT_END.length),i.getIndex()):r.fatalError("comment is not well-formed at position "+i.getIndex());case"[":var s=i.getMatch(Y.CDSect);return s?!o&&!t.currentElement?r.fatalError("CDATA outside of element"):(t.startCDATA(),t.characters(s,Y.CDATA_START.length,s.length-Y.CDATA_START.length-Y.CDATA_END.length),t.endCDATA(),i.getIndex()):r.fatalError("Invalid CDATA starting at position "+e);case"D":{if(t.doc&&t.doc.documentElement)return r.fatalError("Doctype not allowed inside or after documentElement at position "+i.getIndex());if(o?!i.substringStartsWithCaseInsensitive(Y.DOCTYPE_DECL_START):!i.substringStartsWith(Y.DOCTYPE_DECL_START))return r.fatalError("Expected "+Y.DOCTYPE_DECL_START+" at position "+i.getIndex());if(i.skip(Y.DOCTYPE_DECL_START.length),i.skipBlanks()<1)return r.fatalError("Expected whitespace after "+Y.DOCTYPE_DECL_START+" at position "+i.getIndex());var l={name:void 0,publicId:void 0,systemId:void 0,internalSubset:void 0};if(l.name=i.getMatch(Y.Name),!l.name)return r.fatalError("doctype name missing or contains unexpected characters at position "+i.getIndex());if(o&&l.name.toLowerCase()!=="html"&&r.warning("Unexpected DOCTYPE in HTML document at position "+i.getIndex()),i.skipBlanks(),i.substringStartsWith(Y.PUBLIC)||i.substringStartsWith(Y.SYSTEM)){var u=Y.ExternalID_match.exec(i.substringFromIndex());if(!u)return r.fatalError("doctype external id is not well-formed at position "+i.getIndex());u.groups.SystemLiteralOnly!==void 0?l.systemId=u.groups.SystemLiteralOnly:(l.systemId=u.groups.SystemLiteral,l.publicId=u.groups.PubidLiteral),i.skip(u[0].length)}else if(o&&i.substringStartsWithCaseInsensitive(Y.SYSTEM)){if(i.skip(Y.SYSTEM.length),i.skipBlanks()<1)return r.fatalError("Expected whitespace after "+Y.SYSTEM+" at position "+i.getIndex());if(l.systemId=i.getMatch(Y.ABOUT_LEGACY_COMPAT_SystemLiteral),!l.systemId)return r.fatalError("Expected "+Y.ABOUT_LEGACY_COMPAT+" in single or double quotes after "+Y.SYSTEM+" at position "+i.getIndex())}return o&&l.systemId&&!Y.ABOUT_LEGACY_COMPAT_SystemLiteral.test(l.systemId)&&r.warning("Unexpected doctype.systemId in HTML document at position "+i.getIndex()),o||(i.skipBlanks(),l.internalSubset=z_(i,r)),i.skipBlanks(),i.char()!==">"?r.fatalError("doctype not terminated with > at position "+i.getIndex()):(i.skip(1),t.startDTD(l.name,l.publicId,l.systemId,l.internalSubset),t.endDTD(),i.getIndex())}default:return r.fatalError('Not well-formed XML starting with "<!" at position '+e)}}function H_(n,e,t,r){var o=n.substring(e).match(Y.PI);if(!o)return r.fatalError("Invalid processing instruction starting at position "+e);if(o[1].toLowerCase()==="xml"){if(e>0)return r.fatalError("processing instruction at position "+e+" is an xml declaration which is only at the start of the document");if(!Y.XMLDecl.test(n.substring(e)))return r.fatalError("xml declaration is not well-formed")}return t.processingInstruction(o[1],o[2]),e+o[0].length}function uh(){this.attributeNames=Object.create(null)}uh.prototype={setTagName:function(n){if(!Y.QName_exact.test(n))throw new Error("invalid tagName:"+n);this.tagName=n},addValue:function(n,e,t){if(!Y.QName_exact.test(n))throw new Error("invalid attribute:"+n);this.attributeNames[n]=this.length,this[this.length++]={qName:n,value:e,offset:t}},length:0,getLocalName:function(n){return this[n].localName},getLocator:function(n){return this[n].locator},getQName:function(n){return this[n].qName},getURI:function(n){return this[n].uri},getValue:function(n){return this[n].value}};Ua.XMLReader=ah;Ua.parseUtils=sh;Ua.parseDoctypeCommentOrCData=lh});var bh=lr(Xn=>{"use strict";var Wr=Hr(),G_=xu(),W_=Wo(),dh=th(),Y_=ch(),X_=G_.DOMImplementation,Z_=Wr.hasDefaultHTMLNamespace,K_=Wr.isHTMLMimeType,J_=Wr.isValidMimeType,ph=Wr.MIME_TYPE,Tu=Wr.NAMESPACE,fh=W_.ParseError,Q_=Y_.XMLReader;function mh(n){return n.replace(/\r[\n\u0085]/g,`
|
|
12
12
|
`).replace(/[\r\u0085\u2028\u2029]/g,`
|
|
13
|
-
`)}function
|
|
14
|
-
@#[line:`+n.lineNumber+",col:"+n.columnNumber+"]"}function
|
|
13
|
+
`)}function gh(n){if(n=n||{},n.locator===void 0&&(n.locator=!0),this.assign=n.assign||Wr.assign,this.domHandler=n.domHandler||za,this.onError=n.onError||n.errorHandler,n.errorHandler&&typeof n.errorHandler!="function")throw new TypeError("errorHandler object is no longer supported, switch to onError!");n.errorHandler&&n.errorHandler("warning","The `errorHandler` option has been deprecated, use `onError` instead!",this),this.normalizeLineEndings=n.normalizeLineEndings||mh,this.locator=!!n.locator,this.xmlns=this.assign(Object.create(null),n.xmlns)}gh.prototype.parseFromString=function(n,e){if(!J_(e))throw new TypeError('DOMParser.parseFromString: the provided mimeType "'+e+'" is not valid.');var t=this.assign(Object.create(null),this.xmlns),r=dh.XML_ENTITIES,o=t[""]||null;Z_(e)?(r=dh.HTML_ENTITIES,o=Tu.HTML):e===ph.XML_SVG_IMAGE&&(o=Tu.SVG),t[""]=o,t.xml=t.xml||Tu.XML;var i=new this.domHandler({mimeType:e,defaultNamespace:o,onError:this.onError}),a=this.locator?{}:void 0;this.locator&&i.setDocumentLocator(a);var s=new Q_;s.errorHandler=i,s.domBuilder=i;var l=!Wr.isHTMLMimeType(e);return l&&typeof n!="string"&&s.errorHandler.fatalError("source is not a string"),s.parse(this.normalizeLineEndings(String(n)),t,r),i.doc.documentElement||s.errorHandler.fatalError("missing root element"),i.doc};function za(n){var e=n||{};this.mimeType=e.mimeType||ph.XML_APPLICATION,this.defaultNamespace=e.defaultNamespace||null,this.cdata=!1,this.currentElement=void 0,this.doc=void 0,this.locator=void 0,this.onError=e.onError}function Yn(n,e){e.lineNumber=n.lineNumber,e.columnNumber=n.columnNumber}za.prototype={startDocument:function(){var n=new X_;this.doc=K_(this.mimeType)?n.createHTMLDocument(!1):n.createDocument(this.defaultNamespace,"")},startElement:function(n,e,t,r){var o=this.doc,i=o.createElementNS(n,t||e),a=r.length;Va(this,i),this.currentElement=i,this.locator&&Yn(this.locator,i);for(var s=0;s<a;s++){var n=r.getURI(s),l=r.getValue(s),t=r.getQName(s),u=o.createAttributeNS(n,t);this.locator&&Yn(r.getLocator(s),u),u.value=u.nodeValue=l,i.setAttributeNode(u)}},endElement:function(n,e,t){this.currentElement=this.currentElement.parentNode},startPrefixMapping:function(n,e){},endPrefixMapping:function(n){},processingInstruction:function(n,e){var t=this.doc.createProcessingInstruction(n,e);this.locator&&Yn(this.locator,t),Va(this,t)},ignorableWhitespace:function(n,e,t){},characters:function(n,e,t){if(n=hh.apply(this,arguments),n){if(this.cdata)var r=this.doc.createCDATASection(n);else var r=this.doc.createTextNode(n);this.currentElement?this.currentElement.appendChild(r):/^\s*$/.test(n)&&this.doc.appendChild(r),this.locator&&Yn(this.locator,r)}},skippedEntity:function(n){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(n){n&&(n.lineNumber=0),this.locator=n},comment:function(n,e,t){n=hh.apply(this,arguments);var r=this.doc.createComment(n);this.locator&&Yn(this.locator,r),Va(this,r)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(n,e,t,r){var o=this.doc.implementation;if(o&&o.createDocumentType){var i=o.createDocumentType(n,e,t,r);this.locator&&Yn(this.locator,i),Va(this,i),this.doc.doctype=i}},reportError:function(n,e){if(typeof this.onError=="function")try{this.onError(n,e,this)}catch(t){throw new fh("Reporting "+n+' "'+e+'" caused '+t,this.locator)}else console.error("[xmldom "+n+"] "+e,ey(this.locator))},warning:function(n){this.reportError("warning",n)},error:function(n){this.reportError("error",n)},fatalError:function(n,e){throw this.reportError("fatalError",n),new fh(n,this.locator,e)}};function ey(n){if(n)return`
|
|
14
|
+
@#[line:`+n.lineNumber+",col:"+n.columnNumber+"]"}function hh(n,e,t){return typeof n=="string"?n.substr(e,t):n.length>=e+t||e?new java.lang.String(n,e,t)+"":n}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(n){za.prototype[n]=function(){return null}});function Va(n,e){n.currentElement?n.currentElement.appendChild(e):n.doc.appendChild(e)}function ty(n){if(n==="error")throw"onErrorStopParsing"}function ry(){throw"onWarningStopParsing"}Xn.__DOMHandler=za;Xn.DOMParser=gh;Xn.normalizeLineEndings=mh;Xn.onErrorStopParsing=ty;Xn.onWarningStopParsing=ry});var Au=lr(te=>{"use strict";var Zn=Hr();te.assign=Zn.assign;te.hasDefaultHTMLNamespace=Zn.hasDefaultHTMLNamespace;te.isHTMLMimeType=Zn.isHTMLMimeType;te.isValidMimeType=Zn.isValidMimeType;te.MIME_TYPE=Zn.MIME_TYPE;te.NAMESPACE=Zn.NAMESPACE;var Ha=Wo();te.DOMException=Ha.DOMException;te.DOMExceptionName=Ha.DOMExceptionName;te.ExceptionCode=Ha.ExceptionCode;te.ParseError=Ha.ParseError;var Ie=xu();te.Attr=Ie.Attr;te.CDATASection=Ie.CDATASection;te.CharacterData=Ie.CharacterData;te.Comment=Ie.Comment;te.Document=Ie.Document;te.DocumentFragment=Ie.DocumentFragment;te.DocumentType=Ie.DocumentType;te.DOMImplementation=Ie.DOMImplementation;te.Element=Ie.Element;te.Entity=Ie.Entity;te.EntityReference=Ie.EntityReference;te.LiveNodeList=Ie.LiveNodeList;te.NamedNodeMap=Ie.NamedNodeMap;te.Node=Ie.Node;te.NodeList=Ie.NodeList;te.Notation=Ie.Notation;te.ProcessingInstruction=Ie.ProcessingInstruction;te.Text=Ie.Text;te.XMLSerializer=Ie.XMLSerializer;var Ga=bh();te.DOMParser=Ga.DOMParser;te.normalizeLineEndings=Ga.normalizeLineEndings;te.onErrorStopParsing=Ga.onErrorStopParsing;te.onWarningStopParsing=Ga.onWarningStopParsing});var fa=new WeakMap,Rd=`
|
|
15
15
|
--gramlot-toolbar-thickness:56px; --gramlot-toolbar-control-size:44px; --gramlot-toolbar-padding:6px;
|
|
16
|
-
`,
|
|
16
|
+
`,Bd=`
|
|
17
17
|
box-sizing:border-box; height:100dvh; min-height:0; overflow:auto;
|
|
18
18
|
padding:env(safe-area-inset-top) max(12px,env(safe-area-inset-right)) max(24px,env(safe-area-inset-bottom)) max(12px,env(safe-area-inset-left));
|
|
19
19
|
background:var(--gramlot-chrome-background,color-mix(in srgb,var(--gramlot-surface-subtle,Canvas) 88%,var(--gramlot-ink,CanvasText) 12%)); color:var(--gramlot-ink,CanvasText);
|
|
20
|
-
`,
|
|
20
|
+
`,Mg=`
|
|
21
21
|
[data-gramlot-viewport]{--gramlot-toolbar-thickness:42px;--gramlot-toolbar-control-size:36px;--gramlot-toolbar-padding:2px 3px;}
|
|
22
|
-
:root[data-gramlot-touch="on"] [data-gramlot-viewport]{${
|
|
23
|
-
:root[data-gramlot-touch="on"] [data-gramlot-viewport="root"]{${
|
|
22
|
+
:root[data-gramlot-touch="on"] [data-gramlot-viewport]{${Rd}}
|
|
23
|
+
:root[data-gramlot-touch="on"] [data-gramlot-viewport="root"]{${Bd}}
|
|
24
24
|
:root[data-gramlot-touch="on"] [data-gramlot-viewport="root"] > *{max-height:100%;}
|
|
25
25
|
@media(pointer:coarse){
|
|
26
|
-
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport]{${
|
|
27
|
-
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"]{${
|
|
26
|
+
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport]{${Rd}}
|
|
27
|
+
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"]{${Bd}}
|
|
28
28
|
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"] > *{max-height:100%;}
|
|
29
29
|
}
|
|
30
|
-
`,Io=class n{static install({document:e,root:t}){return fa.has(t)||fa.set(t,new n(e,t)),fa.get(t)}constructor(e,t){this.document=e,this.root=t,this.releases=[],this.closed=!1,t.setAttribute("data-gramlot-viewport",e.defaultView.parent===e.defaultView?"root":"child");let r=e.querySelector('meta[name="viewport"]');r||(r=e.createElement("meta"),r.name="viewport",r.content="width=device-width,initial-scale=1",e.head.append(r));let o=r.content.split(",").map(i=>i.trim()).filter(i=>!i.startsWith("viewport-fit="));r.content=[...o,"viewport-fit=cover"].join(","),this.style=e.createElement("style"),this.style.textContent=Ig,e.head.append(this.style)}subscribeAppearance(e){let t=this.document.defaultView,r=t.matchMedia("(prefers-color-scheme: dark)"),o=()=>{let s=t.getComputedStyle(this.document.documentElement).colorScheme;e({dark:s==="dark"||!["light","dark"].includes(s)&&r.matches})},i=new t.MutationObserver(o);i.observe(this.document.documentElement,{attributes:!0,attributeFilter:["data-theme","style","class"]}),r.addEventListener("change",o),o();let a=()=>{i.disconnect(),r.removeEventListener("change",o)};return this.releases.push(a),a}dispose(){if(!this.closed){this.closed=!0;for(let e of this.releases)e();this.style.remove(),this.root.removeAttribute("data-gramlot-viewport"),fa.delete(this.root)}}};var Oo=class{#e=new Map;registerGroup(e,t={}){if(typeof e!="string"||!e||e.includes(":"))throw new TypeError("Extension command namespace must be nonempty and unqualified");if(this.#e.has(e))throw new Error(`Duplicate command namespace: ${e}`);if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(o=>!["author","description"].includes(o))||Object.values(t).some(o=>typeof o!="string"))throw new TypeError(`Invalid command group metadata: ${e}`);let r=new Map;return this.#e.set(e,{metadata:{...t},commands:r}),Object.freeze({register(o,i){if(typeof o!="string"||!o||o.includes(":"))throw new TypeError("Invalid command name");if(r.has(o))throw new Error(`Duplicate command: ${e}:${o}`);if(!i||typeof i!="object"||Array.isArray(i)||!Object.hasOwn(i,"label")||!Object.hasOwn(i,"publish")||Object.keys(i).some(a=>!["label","publish","icon","iconSrc","tooltip"].includes(a))||Object.values(i).some(a=>typeof a!="string"))throw new TypeError(`Invalid command definition: ${e}:${o}`);r.set(o,Object.freeze({...i}))}})}get(e){let t=e.indexOf(":");return this.#e.get(e.slice(0,t))?.commands.get(e.slice(t+1))}toDocument(){return{document_format:{name:"gramlot_commands",version:"1.0"},groups:Object.fromEntries([...this.#e].map(([e,{metadata:t,commands:r}])=>[e,{...t,commands:Object.fromEntries(r)}]))}}};var Ro=class{constructor(e,{fetcher:t=globalThis.fetch?.bind(globalThis),closeUrl:r="/gramlot/close",navigator:o=globalThis.navigator,XMLHttpRequest:i=globalThis.XMLHttpRequest}={}){this.rpcUrl=e,this.fetcher=t,this.closeUrl=r,this.navigator=o,this.XMLHttpRequest=i}get supportsCallSync(){return!0}async call(e,t){let r=await this.fetcher(this.rpcUrl,{method:"POST",credentials:"same-origin",signal:t,headers:{"Content-Type":"application/json"},body:e});if(r.status!==200)throw new Error(`rpc failed: HTTP ${r.status}`);return r.text()}callSync(e){let t=new this.XMLHttpRequest;if(t.open("POST",this.rpcUrl,!1),t.setRequestHeader("Content-Type","application/json"),t.send(e),t.status!==200)throw new Error(`rpc failed: HTTP ${t.status}`);return t.responseText}close(e){if(typeof this.closeUrl!="string"||!this.closeUrl.trim())throw new TypeError("HttpTransport.closeUrl must be nonempty text");if(typeof this.navigator?.sendBeacon!="function")throw new TypeError("HttpTransport requires navigator.sendBeacon");let t=new Blob([JSON.stringify({pageId:e})],{type:"application/json"});try{this.navigator.sendBeacon(this.closeUrl,t)}catch(r){if(r.name==="TypeError")throw r}}dispose(){}};var ha=class{constructor(e,t){this.channel=e,this.closeTransport=t}get supportsCallSync(){return!1}call(e,t){return this.channel.call(e,t)}close(e,t){this.closeTransport.close(e,t)}dispose(){this.closeTransport.dispose()}};var lr=class{createTransport({rpcUrl:e,closeUrl:t,document:r,channel:o=null}){let i=r.defaultView,a=new Ro(e,{closeUrl:t,navigator:i.navigator,XMLHttpRequest:i.XMLHttpRequest});return o===null?a:new ha(o,a)}};var Nn=9e15,fr=1e9,ql="0123456789abcdef",ga="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",ba="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Ul={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Nn,maxE:Nn,crypto:!1},Pd,Gt,z=!0,_a="[DecimalError] ",dr=_a+"Invalid argument: ",Ld=_a+"Precision limit exceeded",Fd=_a+"crypto unavailable",jd="[object Decimal]",Ve=Math.floor,Ce=Math.pow,Og=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Rg=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Bg=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,qd=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,yt=1e7,j=7,$g=9007199254740991,Mg=ga.length-1,Vl=ba.length-1,D={toStringTag:jd};D.absoluteValue=D.abs=function(){var n=new this.constructor(this);return n.s<0&&(n.s=1),P(n)};D.ceil=function(){return P(new this.constructor(this),this.e+1,2)};D.clampedTo=D.clamp=function(n,e){var t,r=this,o=r.constructor;if(n=new o(n),e=new o(e),!n.s||!e.s)return new o(NaN);if(n.gt(e))throw Error(dr+e);return t=r.cmp(n),t<0?n:r.cmp(e)>0?e:new o(r)};D.comparedTo=D.cmp=function(n){var e,t,r,o,i=this,a=i.d,s=(n=new i.constructor(n)).d,l=i.s,u=n.s;if(!a||!s)return!l||!u?NaN:l!==u?l:a===s?0:!a^l<0?1:-1;if(!a[0]||!s[0])return a[0]?l:s[0]?-u:0;if(l!==u)return l;if(i.e!==n.e)return i.e>n.e^l<0?1:-1;for(r=a.length,o=s.length,e=0,t=r<o?r:o;e<t;++e)if(a[e]!==s[e])return a[e]>s[e]^l<0?1:-1;return r===o?0:r>o^l<0?1:-1};D.cosine=D.cos=function(){var n,e,t=this,r=t.constructor;return t.d?t.d[0]?(n=r.precision,e=r.rounding,r.precision=n+Math.max(t.e,t.sd())+j,r.rounding=1,t=Pg(r,Gd(r,t)),r.precision=n,r.rounding=e,P(Gt==2||Gt==3?t.neg():t,n,e,!0)):new r(1):new r(NaN)};D.cubeRoot=D.cbrt=function(){var n,e,t,r,o,i,a,s,l,u,c=this,d=c.constructor;if(!c.isFinite()||c.isZero())return new d(c);for(z=!1,i=c.s*Ce(c.s*c,1/3),!i||Math.abs(i)==1/0?(t=$e(c.d),n=c.e,(i=(n-t.length+1)%3)&&(t+=i==1||i==-2?"0":"00"),i=Ce(t,1/3),n=Ve((n+1)/3)-(n%3==(n<0?-1:2)),i==1/0?t="5e"+n:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+n),r=new d(t),r.s=c.s):r=new d(i.toString()),a=(n=d.precision)+3;;)if(s=r,l=s.times(s).times(s),u=l.plus(c),r=pe(u.plus(c).times(s),u.plus(l),a+2,1),$e(s.d).slice(0,a)===(t=$e(r.d)).slice(0,a))if(t=t.slice(a-3,a+1),t=="9999"||!o&&t=="4999"){if(!o&&(P(s,n+1,0),s.times(s).times(s).eq(c))){r=s;break}a+=4,o=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(P(r,n+1,1),e=!r.times(r).times(r).eq(c));break}return z=!0,P(r,n,d.rounding,e)};D.decimalPlaces=D.dp=function(){var n,e=this.d,t=NaN;if(e){if(n=e.length-1,t=(n-Ve(this.e/j))*j,n=e[n],n)for(;n%10==0;n/=10)t--;t<0&&(t=0)}return t};D.dividedBy=D.div=function(n){return pe(this,new this.constructor(n))};D.dividedToIntegerBy=D.divToInt=function(n){var e=this,t=e.constructor;return P(pe(e,new t(n),0,1,1),t.precision,t.rounding)};D.equals=D.eq=function(n){return this.cmp(n)===0};D.floor=function(){return P(new this.constructor(this),this.e+1,3)};D.greaterThan=D.gt=function(n){return this.cmp(n)>0};D.greaterThanOrEqualTo=D.gte=function(n){var e=this.cmp(n);return e==1||e===0};D.hyperbolicCosine=D.cosh=function(){var n,e,t,r,o,i=this,a=i.constructor,s=new a(1);if(!i.isFinite())return new a(i.s?1/0:NaN);if(i.isZero())return s;t=a.precision,r=a.rounding,a.precision=t+Math.max(i.e,i.sd())+4,a.rounding=1,o=i.d.length,o<32?(n=Math.ceil(o/3),e=(1/va(4,n)).toString()):(n=16,e="2.3283064365386962890625e-10"),i=In(a,1,i.times(e),new a(1),!0);for(var l,u=n,c=new a(8);u--;)l=i.times(i),i=s.minus(l.times(c.minus(l.times(c))));return P(i,a.precision=t,a.rounding=r,!0)};D.hyperbolicSine=D.sinh=function(){var n,e,t,r,o=this,i=o.constructor;if(!o.isFinite()||o.isZero())return new i(o);if(e=i.precision,t=i.rounding,i.precision=e+Math.max(o.e,o.sd())+4,i.rounding=1,r=o.d.length,r<3)o=In(i,2,o,o,!0);else{n=1.4*Math.sqrt(r),n=n>16?16:n|0,o=o.times(1/va(5,n)),o=In(i,2,o,o,!0);for(var a,s=new i(5),l=new i(16),u=new i(20);n--;)a=o.times(o),o=o.times(s.plus(a.times(l.times(a).plus(u))))}return i.precision=e,i.rounding=t,P(o,e,t,!0)};D.hyperbolicTangent=D.tanh=function(){var n,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(n=r.precision,e=r.rounding,r.precision=n+7,r.rounding=1,pe(t.sinh(),t.cosh(),r.precision=n,r.rounding=e)):new r(t.s)};D.inverseCosine=D.acos=function(){var n=this,e=n.constructor,t=n.abs().cmp(1),r=e.precision,o=e.rounding;return t!==-1?t===0?n.isNeg()?It(e,r,o):new e(0):new e(NaN):n.isZero()?It(e,r+4,o).times(.5):(e.precision=r+6,e.rounding=1,n=new e(1).minus(n).div(n.plus(1)).sqrt().atan(),e.precision=r,e.rounding=o,n.times(2))};D.inverseHyperbolicCosine=D.acosh=function(){var n,e,t=this,r=t.constructor;return t.lte(1)?new r(t.eq(1)?0:NaN):t.isFinite()?(n=r.precision,e=r.rounding,r.precision=n+Math.max(Math.abs(t.e),t.sd())+4,r.rounding=1,z=!1,t=t.times(t).minus(1).sqrt().plus(t),z=!0,r.precision=n,r.rounding=e,t.ln()):new r(t)};D.inverseHyperbolicSine=D.asinh=function(){var n,e,t=this,r=t.constructor;return!t.isFinite()||t.isZero()?new r(t):(n=r.precision,e=r.rounding,r.precision=n+2*Math.max(Math.abs(t.e),t.sd())+6,r.rounding=1,z=!1,t=t.times(t).plus(1).sqrt().plus(t),z=!0,r.precision=n,r.rounding=e,t.ln())};D.inverseHyperbolicTangent=D.atanh=function(){var n,e,t,r,o=this,i=o.constructor;return o.isFinite()?o.e>=0?new i(o.abs().eq(1)?o.s/0:o.isZero()?o:NaN):(n=i.precision,e=i.rounding,r=o.sd(),Math.max(r,n)<2*-o.e-1?P(new i(o),n,e,!0):(i.precision=t=r-o.e,o=pe(o.plus(1),new i(1).minus(o),t+n,1),i.precision=n+4,i.rounding=1,o=o.ln(),i.precision=n,i.rounding=e,o.times(.5))):new i(NaN)};D.inverseSine=D.asin=function(){var n,e,t,r,o=this,i=o.constructor;return o.isZero()?new i(o):(e=o.abs().cmp(1),t=i.precision,r=i.rounding,e!==-1?e===0?(n=It(i,t+4,r).times(.5),n.s=o.s,n):new i(NaN):(i.precision=t+6,i.rounding=1,o=o.div(new i(1).minus(o.times(o)).sqrt().plus(1)).atan(),i.precision=t,i.rounding=r,o.times(2)))};D.inverseTangent=D.atan=function(){var n,e,t,r,o,i,a,s,l,u=this,c=u.constructor,d=c.precision,f=c.rounding;if(u.isFinite()){if(u.isZero())return new c(u);if(u.abs().eq(1)&&d+4<=Vl)return a=It(c,d+4,f).times(.25),a.s=u.s,a}else{if(!u.s)return new c(NaN);if(d+4<=Vl)return a=It(c,d+4,f).times(.5),a.s=u.s,a}for(c.precision=s=d+10,c.rounding=1,t=Math.min(28,s/j+2|0),n=t;n;--n)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(z=!1,e=Math.ceil(s/j),r=1,l=u.times(u),a=new c(u),o=u;n!==-1;)if(o=o.times(l),i=a.minus(o.div(r+=2)),o=o.times(l),a=i.plus(o.div(r+=2)),a.d[e]!==void 0)for(n=e;a.d[n]===i.d[n]&&n--;);return t&&(a=a.times(2<<t-1)),z=!0,P(a,c.precision=d,c.rounding=f,!0)};D.isFinite=function(){return!!this.d};D.isInteger=D.isInt=function(){return!!this.d&&Ve(this.e/j)>this.d.length-2};D.isNaN=function(){return!this.s};D.isNegative=D.isNeg=function(){return this.s<0};D.isPositive=D.isPos=function(){return this.s>0};D.isZero=function(){return!!this.d&&this.d[0]===0};D.lessThan=D.lt=function(n){return this.cmp(n)<0};D.lessThanOrEqualTo=D.lte=function(n){return this.cmp(n)<1};D.logarithm=D.log=function(n){var e,t,r,o,i,a,s,l,u=this,c=u.constructor,d=c.precision,f=c.rounding,h=5;if(n==null)n=new c(10),e=!0;else{if(n=new c(n),t=n.d,n.s<0||!t||!t[0]||n.eq(1))return new c(NaN);e=n.eq(10)}if(t=u.d,u.s<0||!t||!t[0]||u.eq(1))return new c(t&&!t[0]?-1/0:u.s!=1?NaN:t?0:1/0);if(e)if(t.length>1)i=!0;else{for(o=t[0];o%10===0;)o/=10;i=o!==1}if(z=!1,s=d+h,a=cr(u,s),r=e?wa(c,s+10):cr(n,s),l=pe(a,r,s,1),Bo(l.d,o=d,f))do if(s+=10,a=cr(u,s),r=e?wa(c,s+10):cr(n,s),l=pe(a,r,s,1),!i){+$e(l.d).slice(o+1,o+15)+1==1e14&&(l=P(l,d+1,0));break}while(Bo(l.d,o+=10,f));return z=!0,P(l,d,f)};D.minus=D.sub=function(n){var e,t,r,o,i,a,s,l,u,c,d,f,h=this,p=h.constructor;if(n=new p(n),!h.d||!n.d)return!h.s||!n.s?n=new p(NaN):h.d?n.s=-n.s:n=new p(n.d||h.s!==n.s?h:NaN),n;if(h.s!=n.s)return n.s=-n.s,h.plus(n);if(u=h.d,f=n.d,s=p.precision,l=p.rounding,!u[0]||!f[0]){if(f[0])n.s=-n.s;else if(u[0])n=new p(h);else return new p(l===3?-0:0);return z?P(n,s,l):n}if(t=Ve(n.e/j),c=Ve(h.e/j),u=u.slice(),i=c-t,i){for(d=i<0,d?(e=u,i=-i,a=f.length):(e=f,t=c,a=u.length),r=Math.max(Math.ceil(s/j),a)+2,i>r&&(i=r,e.length=1),e.reverse(),r=i;r--;)e.push(0);e.reverse()}else{for(r=u.length,a=f.length,d=r<a,d&&(a=r),r=0;r<a;r++)if(u[r]!=f[r]){d=u[r]<f[r];break}i=0}for(d&&(e=u,u=f,f=e,n.s=-n.s),a=u.length,r=f.length-a;r>0;--r)u[a++]=0;for(r=f.length;r>i;){if(u[--r]<f[r]){for(o=r;o&&u[--o]===0;)u[o]=yt-1;--u[o],u[r]+=yt}u[r]-=f[r]}for(;u[--a]===0;)u.pop();for(;u[0]===0;u.shift())--t;return u[0]?(n.d=u,n.e=ya(u,t),z?P(n,s,l):n):new p(l===3?-0:0)};D.modulo=D.mod=function(n){var e,t=this,r=t.constructor;return n=new r(n),!t.d||!n.s||n.d&&!n.d[0]?new r(NaN):!n.d||t.d&&!t.d[0]?P(new r(t),r.precision,r.rounding):(z=!1,r.modulo==9?(e=pe(t,n.abs(),0,3,1),e.s*=n.s):e=pe(t,n,0,r.modulo,1),e=e.times(n),z=!0,t.minus(e))};D.naturalExponential=D.exp=function(){return zl(this)};D.naturalLogarithm=D.ln=function(){return cr(this)};D.negated=D.neg=function(){var n=new this.constructor(this);return n.s=-n.s,P(n)};D.plus=D.add=function(n){var e,t,r,o,i,a,s,l,u,c,d=this,f=d.constructor;if(n=new f(n),!d.d||!n.d)return!d.s||!n.s?n=new f(NaN):d.d||(n=new f(n.d||d.s===n.s?d:NaN)),n;if(d.s!=n.s)return n.s=-n.s,d.minus(n);if(u=d.d,c=n.d,s=f.precision,l=f.rounding,!u[0]||!c[0])return c[0]||(n=new f(d)),z?P(n,s,l):n;if(i=Ve(d.e/j),r=Ve(n.e/j),u=u.slice(),o=i-r,o){for(o<0?(t=u,o=-o,a=c.length):(t=c,r=i,a=u.length),i=Math.ceil(s/j),a=i>a?i+1:a+1,o>a&&(o=a,t.length=1),t.reverse();o--;)t.push(0);t.reverse()}for(a=u.length,o=c.length,a-o<0&&(o=a,t=c,c=u,u=t),e=0;o;)e=(u[--o]=u[o]+c[o]+e)/yt|0,u[o]%=yt;for(e&&(u.unshift(e),++r),a=u.length;u[--a]==0;)u.pop();return n.d=u,n.e=ya(u,r),z?P(n,s,l):n};D.precision=D.sd=function(n){var e,t=this;if(n!==void 0&&n!==!!n&&n!==1&&n!==0)throw Error(dr+n);return t.d?(e=Ud(t.d),n&&t.e+1>e&&(e=t.e+1)):e=NaN,e};D.round=function(){var n=this,e=n.constructor;return P(new e(n),n.e+1,e.rounding)};D.sine=D.sin=function(){var n,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(n=r.precision,e=r.rounding,r.precision=n+Math.max(t.e,t.sd())+j,r.rounding=1,t=Fg(r,Gd(r,t)),r.precision=n,r.rounding=e,P(Gt>2?t.neg():t,n,e,!0)):new r(NaN)};D.squareRoot=D.sqrt=function(){var n,e,t,r,o,i,a=this,s=a.d,l=a.e,u=a.s,c=a.constructor;if(u!==1||!s||!s[0])return new c(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);for(z=!1,u=Math.sqrt(+a),u==0||u==1/0?(e=$e(s),(e.length+l)%2==0&&(e+="0"),u=Math.sqrt(e),l=Ve((l+1)/2)-(l<0||l%2),u==1/0?e="5e"+l:(e=u.toExponential(),e=e.slice(0,e.indexOf("e")+1)+l),r=new c(e)):r=new c(u.toString()),t=(l=c.precision)+3;;)if(i=r,r=i.plus(pe(a,i,t+2,1)).times(.5),$e(i.d).slice(0,t)===(e=$e(r.d)).slice(0,t))if(e=e.slice(t-3,t+1),e=="9999"||!o&&e=="4999"){if(!o&&(P(i,l+1,0),i.times(i).eq(a))){r=i;break}t+=4,o=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(P(r,l+1,1),n=!r.times(r).eq(a));break}return z=!0,P(r,l,c.rounding,n)};D.tangent=D.tan=function(){var n,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(n=r.precision,e=r.rounding,r.precision=n+10,r.rounding=1,t=t.sin(),t.s=1,t=pe(t,new r(1).minus(t.times(t)).sqrt(),n+10,0),r.precision=n,r.rounding=e,P(Gt==2||Gt==4?t.neg():t,n,e,!0)):new r(NaN)};D.times=D.mul=function(n){var e,t,r,o,i,a,s,l,u,c=this,d=c.constructor,f=c.d,h=(n=new d(n)).d;if(n.s*=c.s,!f||!f[0]||!h||!h[0])return new d(!n.s||f&&!f[0]&&!h||h&&!h[0]&&!f?NaN:!f||!h?n.s/0:n.s*0);for(t=Ve(c.e/j)+Ve(n.e/j),l=f.length,u=h.length,l<u&&(i=f,f=h,h=i,a=l,l=u,u=a),i=[],a=l+u,r=a;r--;)i.push(0);for(r=u;--r>=0;){for(e=0,o=l+r;o>r;)s=i[o]+h[r]*f[o-r-1]+e,i[o--]=s%yt|0,e=s/yt|0;i[o]=(i[o]+e)%yt|0}for(;!i[--a];)i.pop();return e?++t:i.shift(),n.d=i,n.e=ya(i,t),z?P(n,d.precision,d.rounding):n};D.toBinary=function(n,e){return Hl(this,2,n,e)};D.toDecimalPlaces=D.toDP=function(n,e){var t=this,r=t.constructor;return t=new r(t),n===void 0?t:(rt(n,0,fr),e===void 0?e=r.rounding:rt(e,0,8),P(t,n+t.e+1,e))};D.toExponential=function(n,e){var t,r=this,o=r.constructor;return n===void 0?t=Ot(r,!0):(rt(n,0,fr),e===void 0?e=o.rounding:rt(e,0,8),r=P(new o(r),n+1,e),t=Ot(r,!0,n+1)),r.isNeg()&&!r.isZero()?"-"+t:t};D.toFixed=function(n,e){var t,r,o=this,i=o.constructor;return n===void 0?t=Ot(o):(rt(n,0,fr),e===void 0?e=i.rounding:rt(e,0,8),r=P(new i(o),n+o.e+1,e),t=Ot(r,!1,n+r.e+1)),o.isNeg()&&!o.isZero()?"-"+t:t};D.toFraction=function(n){var e,t,r,o,i,a,s,l,u,c,d,f,h=this,p=h.d,m=h.constructor;if(!p)return new m(h);if(u=t=new m(1),r=l=new m(0),e=new m(r),i=e.e=Ud(p)-h.e-1,a=i%j,e.d[0]=Ce(10,a<0?j+a:a),n==null)n=i>0?e:u;else{if(s=new m(n),!s.isInt()||s.lt(u))throw Error(dr+s);n=s.gt(e)?i>0?e:u:s}for(z=!1,s=new m($e(p)),c=m.precision,m.precision=i=p.length*j*2;d=pe(s,e,0,1,1),o=t.plus(d.times(r)),o.cmp(n)!=1;)t=r,r=o,o=u,u=l.plus(d.times(o)),l=o,o=e,e=s.minus(d.times(o)),s=o;return o=pe(n.minus(t),r,0,1,1),l=l.plus(o.times(u)),t=t.plus(o.times(r)),l.s=u.s=h.s,f=pe(u,r,i,1).minus(h).abs().cmp(pe(l,t,i,1).minus(h).abs())<1?[u,r]:[l,t],m.precision=c,z=!0,f};D.toHexadecimal=D.toHex=function(n,e){return Hl(this,16,n,e)};D.toNearest=function(n,e){var t=this,r=t.constructor;if(t=new r(t),n==null){if(!t.d)return t;n=new r(1),e=r.rounding}else{if(n=new r(n),e===void 0?e=r.rounding:rt(e,0,8),!t.d)return n.s?t:n;if(!n.d)return n.s&&(n.s=t.s),n}return n.d[0]?(z=!1,t=pe(t,n,0,e,1).times(n),z=!0,P(t)):(n.s=t.s,t=n),t};D.toNumber=function(){return+this};D.toOctal=function(n,e){return Hl(this,8,n,e)};D.toPower=D.pow=function(n){var e,t,r,o,i,a,s=this,l=s.constructor,u=+(n=new l(n));if(!s.d||!n.d||!s.d[0]||!n.d[0])return new l(Ce(+s,u));if(s=new l(s),s.eq(1))return s;if(r=l.precision,i=l.rounding,n.eq(1))return P(s,r,i);if(e=Ve(n.e/j),e>=n.d.length-1&&(t=u<0?-u:u)<=$g)return o=Vd(l,s,t,r),n.s<0?new l(1).div(o):P(o,r,i);if(a=s.s,a<0){if(e<n.d.length-1)return new l(NaN);if((n.d[e]&1)==0&&(a=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=a,s}return t=Ce(+s,u),e=t==0||!isFinite(t)?Ve(u*(Math.log("0."+$e(s.d))/Math.LN10+s.e+1)):new l(t+"").e,e>l.maxE+1||e<l.minE-1?new l(e>0?a/0:0):(z=!1,l.rounding=s.s=1,t=Math.min(12,(e+"").length),o=zl(n.times(cr(s,r+t)),r),o.d&&(o=P(o,r+5,1),Bo(o.d,r,i)&&(e=r+10,o=P(zl(n.times(cr(s,e+t)),e),e+5,1),+$e(o.d).slice(r+1,r+15)+1==1e14&&(o=P(o,r+1,0)))),o.s=a,z=!0,l.rounding=i,P(o,r,i))};D.toPrecision=function(n,e){var t,r=this,o=r.constructor;return n===void 0?t=Ot(r,r.e<=o.toExpNeg||r.e>=o.toExpPos):(rt(n,1,fr),e===void 0?e=o.rounding:rt(e,0,8),r=P(new o(r),n,e),t=Ot(r,n<=r.e||r.e<=o.toExpNeg,n)),r.isNeg()&&!r.isZero()?"-"+t:t};D.toSignificantDigits=D.toSD=function(n,e){var t=this,r=t.constructor;return n===void 0?(n=r.precision,e=r.rounding):(rt(n,1,fr),e===void 0?e=r.rounding:rt(e,0,8)),P(new r(t),n,e)};D.toString=function(){var n=this,e=n.constructor,t=Ot(n,n.e<=e.toExpNeg||n.e>=e.toExpPos);return n.isNeg()&&!n.isZero()?"-"+t:t};D.truncated=D.trunc=function(){return P(new this.constructor(this),this.e+1,1)};D.valueOf=D.toJSON=function(){var n=this,e=n.constructor,t=Ot(n,n.e<=e.toExpNeg||n.e>=e.toExpPos);return n.isNeg()?"-"+t:t};function $e(n){var e,t,r,o=n.length-1,i="",a=n[0];if(o>0){for(i+=a,e=1;e<o;e++)r=n[e]+"",t=j-r.length,t&&(i+=ur(t)),i+=r;a=n[e],r=a+"",t=j-r.length,t&&(i+=ur(t))}else if(a===0)return"0";for(;a%10===0;)a/=10;return i+a}function rt(n,e,t){if(n!==~~n||n<e||n>t)throw Error(dr+n)}function Bo(n,e,t,r){var o,i,a,s;for(i=n[0];i>=10;i/=10)--e;return--e<0?(e+=j,o=0):(o=Math.ceil((e+1)/j),e%=j),i=Ce(10,j-e),s=n[o]%i|0,r==null?e<3?(e==0?s=s/100|0:e==1&&(s=s/10|0),a=t<4&&s==99999||t>3&&s==49999||s==5e4||s==0):a=(t<4&&s+1==i||t>3&&s+1==i/2)&&(n[o+1]/i/100|0)==Ce(10,e-2)-1||(s==i/2||s==0)&&(n[o+1]/i/100|0)==0:e<4?(e==0?s=s/1e3|0:e==1?s=s/100|0:e==2&&(s=s/10|0),a=(r||t<4)&&s==9999||!r&&t>3&&s==4999):a=((r||t<4)&&s+1==i||!r&&t>3&&s+1==i/2)&&(n[o+1]/i/1e3|0)==Ce(10,e-3)-1,a}function pa(n,e,t){for(var r,o=[0],i,a=0,s=n.length;a<s;){for(i=o.length;i--;)o[i]*=e;for(o[0]+=ql.indexOf(n.charAt(a++)),r=0;r<o.length;r++)o[r]>t-1&&(o[r+1]===void 0&&(o[r+1]=0),o[r+1]+=o[r]/t|0,o[r]%=t)}return o.reverse()}function Pg(n,e){var t,r,o;if(e.isZero())return e;r=e.d.length,r<32?(t=Math.ceil(r/3),o=(1/va(4,t)).toString()):(t=16,o="2.3283064365386962890625e-10"),n.precision+=t,e=In(n,1,e.times(o),new n(1));for(var i=t;i--;){var a=e.times(e);e=a.times(a).minus(a).times(8).plus(1)}return n.precision-=t,e}var pe=(function(){function n(r,o,i){var a,s=0,l=r.length;for(r=r.slice();l--;)a=r[l]*o+s,r[l]=a%i|0,s=a/i|0;return s&&r.unshift(s),r}function e(r,o,i,a){var s,l;if(i!=a)l=i>a?1:-1;else for(s=l=0;s<i;s++)if(r[s]!=o[s]){l=r[s]>o[s]?1:-1;break}return l}function t(r,o,i,a){for(var s=0;i--;)r[i]-=s,s=r[i]<o[i]?1:0,r[i]=s*a+r[i]-o[i];for(;!r[0]&&r.length>1;)r.shift()}return function(r,o,i,a,s,l){var u,c,d,f,h,p,m,b,w,_,y,x,S,k,N,O,$,ee,W,se,me=r.constructor,te=r.s==o.s?1:-1,le=r.d,q=o.d;if(!le||!le[0]||!q||!q[0])return new me(!r.s||!o.s||(le?q&&le[0]==q[0]:!q)?NaN:le&&le[0]==0||!q?te*0:te/0);for(l?(h=1,c=r.e-o.e):(l=yt,h=j,c=Ve(r.e/h)-Ve(o.e/h)),W=q.length,$=le.length,w=new me(te),_=w.d=[],d=0;q[d]==(le[d]||0);d++);if(q[d]>(le[d]||0)&&c--,i==null?(k=i=me.precision,a=me.rounding):s?k=i+(r.e-o.e)+1:k=i,k<0)_.push(1),p=!0;else{if(k=k/h+2|0,d=0,W==1){for(f=0,q=q[0],k++;(d<$||f)&&k--;d++)N=f*l+(le[d]||0),_[d]=N/q|0,f=N%q|0;p=f||d<$}else{for(f=l/(q[0]+1)|0,f>1&&(q=n(q,f,l),le=n(le,f,l),W=q.length,$=le.length),O=W,y=le.slice(0,W),x=y.length;x<W;)y[x++]=0;se=q.slice(),se.unshift(0),ee=q[0],q[1]>=l/2&&++ee;do f=0,u=e(q,y,W,x),u<0?(S=y[0],W!=x&&(S=S*l+(y[1]||0)),f=S/ee|0,f>1?(f>=l&&(f=l-1),m=n(q,f,l),b=m.length,x=y.length,u=e(m,y,b,x),u==1&&(f--,t(m,W<b?se:q,b,l))):(f==0&&(u=f=1),m=q.slice()),b=m.length,b<x&&m.unshift(0),t(y,m,x,l),u==-1&&(x=y.length,u=e(q,y,W,x),u<1&&(f++,t(y,W<x?se:q,x,l))),x=y.length):u===0&&(f++,y=[0]),_[d++]=f,u&&y[0]?y[x++]=le[O]||0:(y=[le[O]],x=1);while((O++<$||y[0]!==void 0)&&k--);p=y[0]!==void 0}_[0]||_.shift()}if(h==1)w.e=c,Pd=p;else{for(d=1,f=_[0];f>=10;f/=10)d++;w.e=d+c*h-1,P(w,s?i+w.e+1:i,a,p)}return w}})();function P(n,e,t,r){var o,i,a,s,l,u,c,d,f,h=n.constructor;e:if(e!=null){if(d=n.d,!d)return n;for(o=1,s=d[0];s>=10;s/=10)o++;if(i=e-o,i<0)i+=j,a=e,c=d[f=0],l=c/Ce(10,o-a-1)%10|0;else if(f=Math.ceil((i+1)/j),s=d.length,f>=s)if(r){for(;s++<=f;)d.push(0);c=l=0,o=1,i%=j,a=i-j+1}else break e;else{for(c=s=d[f],o=1;s>=10;s/=10)o++;i%=j,a=i-j+o,l=a<0?0:c/Ce(10,o-a-1)%10|0}if(r=r||e<0||d[f+1]!==void 0||(a<0?c:c%Ce(10,o-a-1)),u=t<4?(l||r)&&(t==0||t==(n.s<0?3:2)):l>5||l==5&&(t==4||r||t==6&&(i>0?a>0?c/Ce(10,o-a):0:d[f-1])%10&1||t==(n.s<0?8:7)),e<1||!d[0])return d.length=0,u?(e-=n.e+1,d[0]=Ce(10,(j-e%j)%j),n.e=-e||0):d[0]=n.e=0,n;if(i==0?(d.length=f,s=1,f--):(d.length=f+1,s=Ce(10,j-i),d[f]=a>0?(c/Ce(10,o-a)%Ce(10,a)|0)*s:0),u)for(;;)if(f==0){for(i=1,a=d[0];a>=10;a/=10)i++;for(a=d[0]+=s,s=1;a>=10;a/=10)s++;i!=s&&(n.e++,d[0]==yt&&(d[0]=1));break}else{if(d[f]+=s,d[f]!=yt)break;d[f--]=0,s=1}for(i=d.length;d[--i]===0;)d.pop()}return z&&(n.e>h.maxE?(n.d=null,n.e=NaN):n.e<h.minE&&(n.e=0,n.d=[0])),n}function Ot(n,e,t){if(!n.isFinite())return Hd(n);var r,o=n.e,i=$e(n.d),a=i.length;return e?(t&&(r=t-a)>0?i=i.charAt(0)+"."+i.slice(1)+ur(r):a>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(n.e<0?"e":"e+")+n.e):o<0?(i="0."+ur(-o-1)+i,t&&(r=t-a)>0&&(i+=ur(r))):o>=a?(i+=ur(o+1-a),t&&(r=t-o-1)>0&&(i=i+"."+ur(r))):((r=o+1)<a&&(i=i.slice(0,r)+"."+i.slice(r)),t&&(r=t-a)>0&&(o+1===a&&(i+="."),i+=ur(r))),i}function ya(n,e){var t=n[0];for(e*=j;t>=10;t/=10)e++;return e}function wa(n,e,t){if(e>Mg)throw z=!0,t&&(n.precision=t),Error(Ld);return P(new n(ga),e,1,!0)}function It(n,e,t){if(e>Vl)throw Error(Ld);return P(new n(ba),e,t,!0)}function Ud(n){var e=n.length-1,t=e*j+1;if(e=n[e],e){for(;e%10==0;e/=10)t--;for(e=n[0];e>=10;e/=10)t++}return t}function ur(n){for(var e="";n--;)e+="0";return e}function Vd(n,e,t,r){var o,i=new n(1),a=Math.ceil(r/j+4);for(z=!1;;){if(t%2&&(i=i.times(e),$d(i.d,a)&&(o=!0)),t=Ve(t/2),t===0){t=i.d.length-1,o&&i.d[t]===0&&++i.d[t];break}e=e.times(e),$d(e.d,a)}return z=!0,i}function Bd(n){return n.d[n.d.length-1]&1}function zd(n,e,t){for(var r,o,i=new n(e[0]),a=0;++a<e.length;){if(o=new n(e[a]),!o.s){i=o;break}r=i.cmp(o),(r===t||r===0&&i.s===t)&&(i=o)}return i}function zl(n,e){var t,r,o,i,a,s,l,u=0,c=0,d=0,f=n.constructor,h=f.rounding,p=f.precision;if(!n.d||!n.d[0]||n.e>17)return new f(n.d?n.d[0]?n.s<0?0:1/0:1:n.s?n.s<0?0:n:NaN);for(e==null?(z=!1,l=p):l=e,s=new f(.03125);n.e>-2;)n=n.times(s),d+=5;for(r=Math.log(Ce(2,d))/Math.LN10*2+5|0,l+=r,t=i=a=new f(1),f.precision=l;;){if(i=P(i.times(n),l,1),t=t.times(++c),s=a.plus(pe(i,t,l,1)),$e(s.d).slice(0,l)===$e(a.d).slice(0,l)){for(o=d;o--;)a=P(a.times(a),l,1);if(e==null)if(u<3&&Bo(a.d,l-r,h,u))f.precision=l+=10,t=i=s=new f(1),c=0,u++;else return P(a,f.precision=p,h,z=!0);else return f.precision=p,a}a=s}}function cr(n,e){var t,r,o,i,a,s,l,u,c,d,f,h=1,p=10,m=n,b=m.d,w=m.constructor,_=w.rounding,y=w.precision;if(m.s<0||!b||!b[0]||!m.e&&b[0]==1&&b.length==1)return new w(b&&!b[0]?-1/0:m.s!=1?NaN:b?0:m);if(e==null?(z=!1,c=y):c=e,w.precision=c+=p,t=$e(b),r=t.charAt(0),Math.abs(i=m.e)<15e14){for(;r<7&&r!=1||r==1&&t.charAt(1)>3;)m=m.times(n),t=$e(m.d),r=t.charAt(0),h++;i=m.e,r>1?(m=new w("0."+t),i++):m=new w(r+"."+t.slice(1))}else return u=wa(w,c+2,y).times(i+""),m=cr(new w(r+"."+t.slice(1)),c-p).plus(u),w.precision=y,e==null?P(m,y,_,z=!0):m;for(d=m,l=a=m=pe(m.minus(1),m.plus(1),c,1),f=P(m.times(m),c,1),o=3;;){if(a=P(a.times(f),c,1),u=l.plus(pe(a,new w(o),c,1)),$e(u.d).slice(0,c)===$e(l.d).slice(0,c))if(l=l.times(2),i!==0&&(l=l.plus(wa(w,c+2,y).times(i+""))),l=pe(l,new w(h),c,1),e==null)if(Bo(l.d,c-p,_,s))w.precision=c+=p,u=a=m=pe(d.minus(1),d.plus(1),c,1),f=P(m.times(m),c,1),o=s=1;else return P(l,w.precision=y,_,z=!0);else return w.precision=y,l;l=u,o+=2}}function Hd(n){return String(n.s*n.s/0)}function ma(n,e){var t,r,o;for((t=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(t<0&&(t=r),t+=+e.slice(r+1),e=e.substring(0,r)):t<0&&(t=e.length),r=0;e.charCodeAt(r)===48;r++);for(o=e.length;e.charCodeAt(o-1)===48;--o);if(e=e.slice(r,o),e){if(o-=r,n.e=t=t-r-1,n.d=[],r=(t+1)%j,t<0&&(r+=j),r<o){for(r&&n.d.push(+e.slice(0,r)),o-=j;r<o;)n.d.push(+e.slice(r,r+=j));e=e.slice(r),r=j-e.length}else r-=o;for(;r--;)e+="0";n.d.push(+e),z&&(n.e>n.constructor.maxE?(n.d=null,n.e=NaN):n.e<n.constructor.minE&&(n.e=0,n.d=[0]))}else n.e=0,n.d=[0];return n}function Lg(n,e){var t,r,o,i,a,s,l,u,c;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),qd.test(e))return ma(n,e)}else if(e==="Infinity"||e==="NaN")return+e||(n.s=NaN),n.e=NaN,n.d=null,n;if(Rg.test(e))t=16,e=e.toLowerCase();else if(Og.test(e))t=2;else if(Bg.test(e))t=8;else throw Error(dr+e);for(i=e.search(/p/i),i>0?(l=+e.slice(i+1),e=e.substring(2,i)):e=e.slice(2),i=e.indexOf("."),a=i>=0,r=n.constructor,a&&(e=e.replace(".",""),s=e.length,i=s-i,o=Vd(r,new r(t),i,i*2)),u=pa(e,t,yt),c=u.length-1,i=c;u[i]===0;--i)u.pop();return i<0?new r(n.s*0):(n.e=ya(u,c),n.d=u,z=!1,a&&(n=pe(n,o,s*4)),l&&(n=n.times(Math.abs(l)<54?Ce(2,l):$o.pow(2,l))),z=!0,n)}function Fg(n,e){var t,r=e.d.length;if(r<3)return e.isZero()?e:In(n,2,e,e);t=1.4*Math.sqrt(r),t=t>16?16:t|0,e=e.times(1/va(5,t)),e=In(n,2,e,e);for(var o,i=new n(5),a=new n(16),s=new n(20);t--;)o=e.times(e),e=e.times(i.plus(o.times(a.times(o).minus(s))));return e}function In(n,e,t,r,o){var i,a,s,l,u=1,c=n.precision,d=Math.ceil(c/j);for(z=!1,l=t.times(t),s=new n(r);;){if(a=pe(s.times(l),new n(e++*e++),c,1),s=o?r.plus(a):r.minus(a),r=pe(a.times(l),new n(e++*e++),c,1),a=s.plus(r),a.d[d]!==void 0){for(i=d;a.d[i]===s.d[i]&&i--;);if(i==-1)break}i=s,s=r,r=a,a=i,u++}return z=!0,a.d.length=d+1,a}function va(n,e){for(var t=n;--e;)t*=n;return t}function Gd(n,e){var t,r=e.s<0,o=It(n,n.precision,1),i=o.times(.5);if(e=e.abs(),e.lte(i))return Gt=r?4:1,e;if(t=e.divToInt(o),t.isZero())Gt=r?3:2;else{if(e=e.minus(t.times(o)),e.lte(i))return Gt=Bd(t)?r?2:3:r?4:1,e;Gt=Bd(t)?r?1:4:r?3:2}return e.minus(o).abs()}function Hl(n,e,t,r){var o,i,a,s,l,u,c,d,f,h=n.constructor,p=t!==void 0;if(p?(rt(t,1,fr),r===void 0?r=h.rounding:rt(r,0,8)):(t=h.precision,r=h.rounding),!n.isFinite())c=Hd(n);else{for(c=Ot(n),a=c.indexOf("."),p?(o=2,e==16?t=t*4-3:e==8&&(t=t*3-2)):o=e,a>=0&&(c=c.replace(".",""),f=new h(1),f.e=c.length-a,f.d=pa(Ot(f),10,o),f.e=f.d.length),d=pa(c,10,o),i=l=d.length;d[--l]==0;)d.pop();if(!d[0])c=p?"0p+0":"0";else{if(a<0?i--:(n=new h(n),n.d=d,n.e=i,n=pe(n,f,t,r,0,o),d=n.d,i=n.e,u=Pd),a=d[t],s=o/2,u=u||d[t+1]!==void 0,u=r<4?(a!==void 0||u)&&(r===0||r===(n.s<0?3:2)):a>s||a===s&&(r===4||u||r===6&&d[t-1]&1||r===(n.s<0?8:7)),d.length=t,u)for(;++d[--t]>o-1;)d[t]=0,t||(++i,d.unshift(1));for(l=d.length;!d[l-1];--l);for(a=0,c="";a<l;a++)c+=ql.charAt(d[a]);if(p){if(l>1)if(e==16||e==8){for(a=e==16?4:3,--l;l%a;l++)c+="0";for(d=pa(c,o,e),l=d.length;!d[l-1];--l);for(a=1,c="1.";a<l;a++)c+=ql.charAt(d[a])}else c=c.charAt(0)+"."+c.slice(1);c=c+(i<0?"p":"p+")+i}else if(i<0){for(;++i;)c="0"+c;c="0."+c}else if(++i>l)for(i-=l;i--;)c+="0";else i<l&&(c=c.slice(0,i)+"."+c.slice(i))}c=(e==16?"0x":e==2?"0b":e==8?"0o":"")+c}return n.s<0?"-"+c:c}function $d(n,e){if(n.length>e)return n.length=e,!0}function jg(n){return new this(n).abs()}function qg(n){return new this(n).acos()}function Ug(n){return new this(n).acosh()}function Vg(n,e){return new this(n).plus(e)}function zg(n){return new this(n).asin()}function Hg(n){return new this(n).asinh()}function Gg(n){return new this(n).atan()}function Wg(n){return new this(n).atanh()}function Yg(n,e){n=new this(n),e=new this(e);var t,r=this.precision,o=this.rounding,i=r+4;return!n.s||!e.s?t=new this(NaN):!n.d&&!e.d?(t=It(this,i,1).times(e.s>0?.25:.75),t.s=n.s):!e.d||n.isZero()?(t=e.s<0?It(this,r,o):new this(0),t.s=n.s):!n.d||e.isZero()?(t=It(this,i,1).times(.5),t.s=n.s):e.s<0?(this.precision=i,this.rounding=1,t=this.atan(pe(n,e,i,1)),e=It(this,i,1),this.precision=r,this.rounding=o,t=n.s<0?t.minus(e):t.plus(e)):t=this.atan(pe(n,e,i,1)),t}function Xg(n){return new this(n).cbrt()}function Zg(n){return P(n=new this(n),n.e+1,2)}function Kg(n,e,t){return new this(n).clamp(e,t)}function Jg(n){if(!n||typeof n!="object")throw Error(_a+"Object expected");var e,t,r,o=n.defaults===!0,i=["precision",1,fr,"rounding",0,8,"toExpNeg",-Nn,0,"toExpPos",0,Nn,"maxE",0,Nn,"minE",-Nn,0,"modulo",0,9];for(e=0;e<i.length;e+=3)if(t=i[e],o&&(this[t]=Ul[t]),(r=n[t])!==void 0)if(Ve(r)===r&&r>=i[e+1]&&r<=i[e+2])this[t]=r;else throw Error(dr+t+": "+r);if(t="crypto",o&&(this[t]=Ul[t]),(r=n[t])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[t]=!0;else throw Error(Fd);else this[t]=!1;else throw Error(dr+t+": "+r);return this}function Qg(n){return new this(n).cos()}function eb(n){return new this(n).cosh()}function Wd(n){var e,t,r;function o(i){var a,s,l,u=this;if(!(u instanceof o))return new o(i);if(u.constructor=o,Md(i)){u.s=i.s,z?!i.d||i.e>o.maxE?(u.e=NaN,u.d=null):i.e<o.minE?(u.e=0,u.d=[0]):(u.e=i.e,u.d=i.d.slice()):(u.e=i.e,u.d=i.d?i.d.slice():i.d);return}if(l=typeof i,l==="number"){if(i===0){u.s=1/i<0?-1:1,u.e=0,u.d=[0];return}if(i<0?(i=-i,u.s=-1):u.s=1,i===~~i&&i<1e7){for(a=0,s=i;s>=10;s/=10)a++;z?a>o.maxE?(u.e=NaN,u.d=null):a<o.minE?(u.e=0,u.d=[0]):(u.e=a,u.d=[i]):(u.e=a,u.d=[i]);return}if(i*0!==0){i||(u.s=NaN),u.e=NaN,u.d=null;return}return ma(u,i.toString())}if(l==="string")return(s=i.charCodeAt(0))===45?(i=i.slice(1),u.s=-1):(s===43&&(i=i.slice(1)),u.s=1),qd.test(i)?ma(u,i):Lg(u,i);if(l==="bigint")return i<0?(i=-i,u.s=-1):u.s=1,ma(u,i.toString());throw Error(dr+i)}if(o.prototype=D,o.ROUND_UP=0,o.ROUND_DOWN=1,o.ROUND_CEIL=2,o.ROUND_FLOOR=3,o.ROUND_HALF_UP=4,o.ROUND_HALF_DOWN=5,o.ROUND_HALF_EVEN=6,o.ROUND_HALF_CEIL=7,o.ROUND_HALF_FLOOR=8,o.EUCLID=9,o.config=o.set=Jg,o.clone=Wd,o.isDecimal=Md,o.abs=jg,o.acos=qg,o.acosh=Ug,o.add=Vg,o.asin=zg,o.asinh=Hg,o.atan=Gg,o.atanh=Wg,o.atan2=Yg,o.cbrt=Xg,o.ceil=Zg,o.clamp=Kg,o.cos=Qg,o.cosh=eb,o.div=tb,o.exp=rb,o.floor=nb,o.hypot=ob,o.ln=ib,o.log=ab,o.log10=lb,o.log2=sb,o.max=ub,o.min=cb,o.mod=db,o.mul=fb,o.pow=hb,o.random=pb,o.round=mb,o.sign=gb,o.sin=bb,o.sinh=wb,o.sqrt=_b,o.sub=yb,o.sum=vb,o.tan=Eb,o.tanh=xb,o.trunc=kb,n===void 0&&(n={}),n&&n.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<r.length;)n.hasOwnProperty(t=r[e++])||(n[t]=this[t]);return o.config(n),o}function tb(n,e){return new this(n).div(e)}function rb(n){return new this(n).exp()}function nb(n){return P(n=new this(n),n.e+1,3)}function ob(){var n,e,t=new this(0);for(z=!1,n=0;n<arguments.length;)if(e=new this(arguments[n++]),e.d)t.d&&(t=t.plus(e.times(e)));else{if(e.s)return z=!0,new this(1/0);t=e}return z=!0,t.sqrt()}function Md(n){return n instanceof $o||n&&n.toStringTag===jd||!1}function ib(n){return new this(n).ln()}function ab(n,e){return new this(n).log(e)}function sb(n){return new this(n).log(2)}function lb(n){return new this(n).log(10)}function ub(){return zd(this,arguments,-1)}function cb(){return zd(this,arguments,1)}function db(n,e){return new this(n).mod(e)}function fb(n,e){return new this(n).mul(e)}function hb(n,e){return new this(n).pow(e)}function pb(n){var e,t,r,o,i=0,a=new this(1),s=[];if(n===void 0?n=this.precision:rt(n,1,fr),r=Math.ceil(n/j),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(r));i<r;)o=e[i],o>=429e7?e[i]=crypto.getRandomValues(new Uint32Array(1))[0]:s[i++]=o%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(r*=4);i<r;)o=e[i]+(e[i+1]<<8)+(e[i+2]<<16)+((e[i+3]&127)<<24),o>=214e7?crypto.randomBytes(4).copy(e,i):(s.push(o%1e7),i+=4);i=r/4}else throw Error(Fd);else for(;i<r;)s[i++]=Math.random()*1e7|0;for(r=s[--i],n%=j,r&&n&&(o=Ce(10,j-n),s[i]=(r/o|0)*o);s[i]===0;i--)s.pop();if(i<0)t=0,s=[0];else{for(t=-1;s[0]===0;t-=j)s.shift();for(r=1,o=s[0];o>=10;o/=10)r++;r<j&&(t-=j-r)}return a.e=t,a.d=s,a}function mb(n){return P(n=new this(n),n.e+1,this.rounding)}function gb(n){return n=new this(n),n.d?n.d[0]?n.s:0*n.s:n.s||NaN}function bb(n){return new this(n).sin()}function wb(n){return new this(n).sinh()}function _b(n){return new this(n).sqrt()}function yb(n,e){return new this(n).sub(e)}function vb(){var n=0,e=arguments,t=new this(e[n]);for(z=!1;t.s&&++n<e.length;)t=t.plus(e[n]);return z=!0,P(t,this.precision,this.rounding)}function Eb(n){return new this(n).tan()}function xb(n){return new this(n).tanh()}function kb(n){return P(n=new this(n),n.e+1,1)}D[Symbol.for("nodejs.util.inspect.custom")]=D.toString;D[Symbol.toStringTag]="Decimal";var $o=D.constructor=Wd(Ul);ga=new $o(ga);ba=new $o(ba);var Yd=$o;var Tb=20,Ab=1,Fr=1e6,Xd=1e6,Db=-7,Sb=21,Cb=!1,Mo="[big.js] ",jr=Mo+"Invalid ",Ea=jr+"decimal places",Nb=jr+"rounding mode",Zd=Mo+"Division by zero",ue={},Rt=void 0,Ib=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Kd(){function n(e){var t=this;if(!(t instanceof n))return e===Rt?Kd():new n(e);if(e instanceof n)t.s=e.s,t.e=e.e,t.c=e.c.slice();else{if(typeof e!="string"){if(n.strict===!0&&typeof e!="bigint")throw TypeError(jr+"value");e=e===0&&1/e<0?"-0":String(e)}Ob(t,e)}t.constructor=n}return n.prototype=ue,n.DP=Tb,n.RM=Ab,n.NE=Db,n.PE=Sb,n.strict=Cb,n.roundDown=0,n.roundHalfUp=1,n.roundHalfEven=2,n.roundUp=3,n}function Ob(n,e){var t,r,o;if(!Ib.test(e))throw Error(jr+"number");for(n.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(t=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(t<0&&(t=r),t+=+e.slice(r+1),e=e.substring(0,r)):t<0&&(t=e.length),o=e.length,r=0;r<o&&e.charAt(r)=="0";)++r;if(r==o)n.c=[n.e=0];else{for(;o>0&&e.charAt(--o)=="0";);for(n.e=t-r-1,n.c=[],t=0;r<=o;)n.c[t++]=+e.charAt(r++)}return n}function qr(n,e,t,r){var o=n.c;if(t===Rt&&(t=n.constructor.RM),t!==0&&t!==1&&t!==2&&t!==3)throw Error(Nb);if(e<1)r=t===3&&(r||!!o[0])||e===0&&(t===1&&o[0]>=5||t===2&&(o[0]>5||o[0]===5&&(r||o[1]!==Rt))),o.length=1,r?(n.e=n.e-e+1,o[0]=1):o[0]=n.e=0;else if(e<o.length){if(r=t===1&&o[e]>=5||t===2&&(o[e]>5||o[e]===5&&(r||o[e+1]!==Rt||o[e-1]&1))||t===3&&(r||!!o[0]),o.length=e,r){for(;++o[--e]>9;)if(o[e]=0,e===0){++n.e,o.unshift(1);break}}for(e=o.length;!o[--e];)o.pop()}return n}function Ur(n,e,t){var r=n.e,o=n.c.join(""),i=o.length;if(e)o=o.charAt(0)+(i>1?"."+o.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)o="0"+o;o="0."+o}else if(r>0)if(++r>i)for(r-=i;r--;)o+="0";else r<i&&(o=o.slice(0,r)+"."+o.slice(r));else i>1&&(o=o.charAt(0)+"."+o.slice(1));return n.s<0&&t?"-"+o:o}ue.abs=function(){var n=new this.constructor(this);return n.s=1,n};ue.cmp=function(n){var e,t=this,r=t.c,o=(n=new t.constructor(n)).c,i=t.s,a=n.s,s=t.e,l=n.e;if(!r[0]||!o[0])return r[0]?i:o[0]?-a:0;if(i!=a)return i;if(e=i<0,s!=l)return s>l^e?1:-1;for(a=(s=r.length)<(l=o.length)?s:l,i=-1;++i<a;)if(r[i]!=o[i])return r[i]>o[i]^e?1:-1;return s==l?0:s>l^e?1:-1};ue.div=function(n){var e=this,t=e.constructor,r=e.c,o=(n=new t(n)).c,i=e.s==n.s?1:-1,a=t.DP;if(a!==~~a||a<0||a>Fr)throw Error(Ea);if(!o[0])throw Error(Zd);if(!r[0])return n.s=i,n.c=[n.e=0],n;var s,l,u,c,d,f=o.slice(),h=s=o.length,p=r.length,m=r.slice(0,s),b=m.length,w=n,_=w.c=[],y=0,x=a+(w.e=e.e-n.e)+1;for(w.s=i,i=x<0?0:x,f.unshift(0);b++<s;)m.push(0);do{for(u=0;u<10;u++){if(s!=(b=m.length))c=s>b?1:-1;else for(d=-1,c=0;++d<s;)if(o[d]!=m[d]){c=o[d]>m[d]?1:-1;break}if(c<0){for(l=b==s?o:f;b;){if(m[--b]<l[b]){for(d=b;d&&!m[--d];)m[d]=9;--m[d],m[b]+=10}m[b]-=l[b]}for(;!m[0];)m.shift()}else break}_[y++]=c?u:++u,m[0]&&c?m[b]=r[h]||0:m=[r[h]]}while((h++<p||m[0]!==Rt)&&i--);return!_[0]&&y!=1&&(_.shift(),w.e--,x--),y>x&&qr(w,x,t.RM,m[0]!==Rt),w};ue.eq=function(n){return this.cmp(n)===0};ue.gt=function(n){return this.cmp(n)>0};ue.gte=function(n){return this.cmp(n)>-1};ue.lt=function(n){return this.cmp(n)<0};ue.lte=function(n){return this.cmp(n)<1};ue.minus=ue.sub=function(n){var e,t,r,o,i=this,a=i.constructor,s=i.s,l=(n=new a(n)).s;if(s!=l)return n.s=-l,i.plus(n);var u=i.c.slice(),c=i.e,d=n.c,f=n.e;if(!u[0]||!d[0])return d[0]?n.s=-l:u[0]?n=new a(i):n.s=1,n;if(s=c-f){for((o=s<0)?(s=-s,r=u):(f=c,r=d),r.reverse(),l=s;l--;)r.push(0);r.reverse()}else for(t=((o=u.length<d.length)?u:d).length,s=l=0;l<t;l++)if(u[l]!=d[l]){o=u[l]<d[l];break}if(o&&(r=u,u=d,d=r,n.s=-n.s),(l=(t=d.length)-(e=u.length))>0)for(;l--;)u[e++]=0;for(l=e;t>s;){if(u[--t]<d[t]){for(e=t;e&&!u[--e];)u[e]=9;--u[e],u[t]+=10}u[t]-=d[t]}for(;u[--l]===0;)u.pop();for(;u[0]===0;)u.shift(),--f;return u[0]||(n.s=1,u=[f=0]),n.c=u,n.e=f,n};ue.mod=function(n){var e,t=this,r=t.constructor,o=t.s,i=(n=new r(n)).s;if(!n.c[0])throw Error(Zd);return t.s=n.s=1,e=n.cmp(t)==1,t.s=o,n.s=i,e?new r(t):(o=r.DP,i=r.RM,r.DP=r.RM=0,t=t.div(n),r.DP=o,r.RM=i,this.minus(t.times(n)))};ue.neg=function(){var n=new this.constructor(this);return n.s=-n.s,n};ue.plus=ue.add=function(n){var e,t,r,o=this,i=o.constructor;if(n=new i(n),o.s!=n.s)return n.s=-n.s,o.minus(n);var a=o.e,s=o.c,l=n.e,u=n.c;if(!s[0]||!u[0])return u[0]||(s[0]?n=new i(o):n.s=o.s),n;if(s=s.slice(),e=a-l){for(e>0?(l=a,r=u):(e=-e,r=s),r.reverse();e--;)r.push(0);r.reverse()}for(s.length-u.length<0&&(r=u,u=s,s=r),e=u.length,t=0;e;s[e]%=10)t=(s[--e]=s[e]+u[e]+t)/10|0;for(t&&(s.unshift(t),++l),e=s.length;s[--e]===0;)s.pop();return n.c=s,n.e=l,n};ue.pow=function(n){var e=this,t=new e.constructor("1"),r=t,o=n<0;if(n!==~~n||n<-Xd||n>Xd)throw Error(jr+"exponent");for(o&&(n=-n);n&1&&(r=r.times(e)),n>>=1,!!n;)e=e.times(e);return o?t.div(r):r};ue.prec=function(n,e){if(n!==~~n||n<1||n>Fr)throw Error(jr+"precision");return qr(new this.constructor(this),n,e)};ue.round=function(n,e){if(n===Rt)n=0;else if(n!==~~n||n<-Fr||n>Fr)throw Error(Ea);return qr(new this.constructor(this),n+this.e+1,e)};ue.sqrt=function(){var n,e,t,r=this,o=r.constructor,i=r.s,a=r.e,s=new o("0.5");if(!r.c[0])return new o(r);if(i<0)throw Error(Mo+"No square root");i=Math.sqrt(+Ur(r,!0,!0)),i===0||i===1/0?(e=r.c.join(""),e.length+a&1||(e+="0"),i=Math.sqrt(e),a=((a+1)/2|0)-(a<0||a&1),n=new o((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+a)):n=new o(i+""),a=n.e+(o.DP+=4);do t=n,n=s.times(t.plus(r.div(t)));while(t.c.slice(0,a).join("")!==n.c.slice(0,a).join(""));return qr(n,(o.DP-=4)+n.e+1,o.RM)};ue.times=ue.mul=function(n){var e,t=this,r=t.constructor,o=t.c,i=(n=new r(n)).c,a=o.length,s=i.length,l=t.e,u=n.e;if(n.s=t.s==n.s?1:-1,!o[0]||!i[0])return n.c=[n.e=0],n;for(n.e=l+u,a<s&&(e=o,o=i,i=e,u=a,a=s,s=u),e=new Array(u=a+s);u--;)e[u]=0;for(l=s;l--;){for(s=0,u=a+l;u>l;)s=e[u]+i[l]*o[u-l-1]+s,e[u--]=s%10,s=s/10|0;e[u]=s}for(s?++n.e:e.shift(),l=e.length;!e[--l];)e.pop();return n.c=e,n};ue.toExponential=function(n,e){var t=this,r=t.c[0];if(n!==Rt){if(n!==~~n||n<0||n>Fr)throw Error(Ea);for(t=qr(new t.constructor(t),++n,e);t.c.length<n;)t.c.push(0)}return Ur(t,!0,!!r)};ue.toFixed=function(n,e){var t=this,r=t.c[0];if(n!==Rt){if(n!==~~n||n<0||n>Fr)throw Error(Ea);for(t=qr(new t.constructor(t),n+t.e+1,e),n=n+t.e+1;t.c.length<n;)t.c.push(0)}return Ur(t,!1,!!r)};ue[Symbol.for("nodejs.util.inspect.custom")]=ue.toJSON=ue.toString=function(){var n=this,e=n.constructor;return Ur(n,n.e<=e.NE||n.e>=e.PE,!!n.c[0])};ue.toNumber=function(){var n=+Ur(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(n.toString()))throw Error(Mo+"Imprecise conversion");return n};ue.toPrecision=function(n,e){var t=this,r=t.constructor,o=t.c[0];if(n!==Rt){if(n!==~~n||n<1||n>Fr)throw Error(jr+"precision");for(t=qr(new r(t),n,e);t.c.length<n;)t.c.push(0)}return Ur(t,n<=t.e||t.e<=r.NE||t.e>=r.PE,!!o)};ue.valueOf=function(){var n=this,e=n.constructor;if(e.strict===!0)throw Error(Mo+"valueOf disallowed");return Ur(n,n.e<=e.NE||n.e>=e.PE,!0)};var Rb=Kd(),Jd=Rb;var ru={};Cg(ru,{DecodeError:()=>ze,Decoder:()=>Et,EXT_TIMESTAMP:()=>Wl,Encoder:()=>On,ExtData:()=>vt,ExtensionCodec:()=>hr,decode:()=>lf,decodeArrayStream:()=>df,decodeAsync:()=>cf,decodeMulti:()=>uf,decodeMultiStream:()=>ff,decodeTimestampExtension:()=>Jl,decodeTimestampToTimeSpec:()=>Kl,encode:()=>Ta,encodeDateToTimeSpec:()=>Xl,encodeTimeSpecToTimestamp:()=>Yl,encodeTimestampExtension:()=>Zl});function Qd(n){let e=n.length,t=0,r=0;for(;r<e;){let o=n.charCodeAt(r++);if((o&4294967168)===0){t++;continue}else if((o&4294965248)===0)t+=2;else{if(o>=55296&&o<=56319&&r<e){let i=n.charCodeAt(r);(i&64512)===56320&&(++r,o=((o&1023)<<10)+(i&1023)+65536)}(o&4294901760)===0?t+=3:t+=4}}return t}function Bb(n,e,t){let r=n.length,o=t,i=0;for(;i<r;){let a=n.charCodeAt(i++);if((a&4294967168)===0){e[o++]=a;continue}else if((a&4294965248)===0)e[o++]=a>>6&31|192;else{if(a>=55296&&a<=56319&&i<r){let s=n.charCodeAt(i);(s&64512)===56320&&(++i,a=((a&1023)<<10)+(s&1023)+65536)}(a&4294901760)===0?(e[o++]=a>>12&15|224,e[o++]=a>>6&63|128):(e[o++]=a>>18&7|240,e[o++]=a>>12&63|128,e[o++]=a>>6&63|128)}e[o++]=a&63|128}}var $b=new TextEncoder,Mb=50;function Pb(n,e,t){$b.encodeInto(n,e.subarray(t))}function ef(n,e,t){n.length>Mb?Pb(n,e,t):Bb(n,e,t)}var Lb=4096;function Gl(n,e,t){let r=e,o=r+t,i=[],a="";for(;r<o;){let s=n[r++];if((s&128)===0)i.push(s);else if((s&224)===192){let l=n[r++]&63;i.push((s&31)<<6|l)}else if((s&240)===224){let l=n[r++]&63,u=n[r++]&63;i.push((s&31)<<12|l<<6|u)}else if((s&248)===240){let l=n[r++]&63,u=n[r++]&63,c=n[r++]&63,d=(s&7)<<18|l<<12|u<<6|c;d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(s);i.length>=Lb&&(a+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(a+=String.fromCharCode(...i)),a}var Fb=new TextDecoder,jb=200;function qb(n,e,t){let r=n.subarray(e,e+t);return Fb.decode(r)}function tf(n,e,t){return t>jb?qb(n,e,t):Gl(n,e,t)}var vt=class{type;data;constructor(e,t){this.type=e,this.data=t}};var ze=class n extends Error{constructor(e){super(e);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function rf(n,e,t){let r=t/4294967296,o=t;n.setUint32(e,r),n.setUint32(e+4,o)}function xa(n,e,t){let r=Math.floor(t/4294967296),o=t;n.setUint32(e,r),n.setUint32(e+4,o)}function ka(n,e){let t=n.getInt32(e),r=n.getUint32(e+4);return t*4294967296+r}function nf(n,e){let t=n.getUint32(e),r=n.getUint32(e+4);return t*4294967296+r}var Wl=-1,Ub=4294967296-1,Vb=17179869184-1;function Yl({sec:n,nsec:e}){if(n>=0&&e>=0&&n<=Vb)if(e===0&&n<=Ub){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,r=n&4294967295,o=new Uint8Array(8),i=new DataView(o.buffer);return i.setUint32(0,e<<2|t&3),i.setUint32(4,r),o}else{let t=new Uint8Array(12),r=new DataView(t.buffer);return r.setUint32(0,e),xa(r,4,n),t}}function Xl(n){let e=n.getTime(),t=Math.floor(e/1e3),r=(e-t*1e3)*1e6,o=Math.floor(r/1e9);return{sec:t+o,nsec:r-o*1e9}}function Zl(n){if(n instanceof Date){let e=Xl(n);return Yl(e)}else return null}function Kl(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),r=e.getUint32(4),o=(t&3)*4294967296+r,i=t>>>2;return{sec:o,nsec:i}}case 12:{let t=ka(e,4),r=e.getUint32(0);return{sec:t,nsec:r}}default:throw new ze(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`)}}function Jl(n){let e=Kl(n);return new Date(e.sec*1e3+e.nsec/1e6)}var of={type:Wl,encode:Zl,decode:Jl};var hr=class n{static defaultCodec=new n;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(of)}register({type:e,encode:t,decode:r}){if(e>=0)this.encoders[e]=t,this.decoders[e]=r;else{let o=-1-e;this.builtInEncoders[o]=t,this.builtInDecoders[o]=r}}tryToEncode(e,t){for(let r=0;r<this.builtInEncoders.length;r++){let o=this.builtInEncoders[r];if(o!=null){let i=o(e,t);if(i!=null){let a=-1-r;return new vt(a,i)}}}for(let r=0;r<this.encoders.length;r++){let o=this.encoders[r];if(o!=null){let i=o(e,t);if(i!=null){let a=r;return new vt(a,i)}}}return e instanceof vt?e:null}decode(e,t,r){let o=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return o?o(e,t,r):new vt(t,e)}};function zb(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function Po(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):zb(n)?new Uint8Array(n):Uint8Array.from(n)}var Hb=100,Gb=2048,On=class n{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??hr.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Hb,this.initialBufferSize=e?.initialBufferSize??Gb,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),r=new Uint8Array(t),o=new DataView(t);r.set(this.bytes),this.view=o,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=Qd(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),ef(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,t){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let r=Po(e);this.writeU8a(r)}encodeArray(e,t){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let o of e)this.doEncode(o,t+1)}countWithoutUndefined(e,t){let r=0;for(let o of t)e[o]!==void 0&&r++;return r}encodeMap(e,t){let r=Object.keys(e);this.sortKeys&&r.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let i of r){let a=e[i];this.ignoreUndefined&&a===void 0||(this.encodeString(i),this.doEncode(a,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),o=r.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(e.type),this.writeU8a(r);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),rf(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),xa(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function Ta(n,e){return new On(e).encodeSharedRef(n)}function Aa(n){return`${n<0?"-":""}0x${Math.abs(n).toString(16).padStart(2,"0")}`}var Wb=16,Yb=16,Da=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=Wb,t=Yb){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,r){let o=this.caches[r-1];e:for(let i of o){let a=i.bytes;for(let s=0;s<r;s++)if(a[s]!==e[t+s])continue e;return i.str}return null}store(e,t){let r=this.caches[e.length-1],o={bytes:e,str:t};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=o:r.push(o)}decode(e,t,r){let o=this.find(e,t,r);if(o!=null)return this.hit++,o;this.miss++;let i=Gl(e,t,r),a=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(a,i),i}};var Ql="array",jo="map_key",sf="map_value",Xb=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new ze("The type of key must be string or number but "+typeof n)},eu=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=Ql,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=jo,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Ql){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===jo||e.type===sf){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Fo=-1,tu=new DataView(new ArrayBuffer(0)),Zb=new Uint8Array(tu.buffer);try{tu.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var af=new RangeError("Insufficient data"),Kb=new Da,Et=class n{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=tu;bytes=Zb;headByte=Fo;stack=new eu;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??hr.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:Kb,this.mapKeyConverter=e?.mapKeyConverter??Xb}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Fo,this.stack.reset()}setBuffer(e){let t=Po(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Fo&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),r=Po(e),o=new Uint8Array(t.length+r.length);o.set(t),o.set(r,t.length),this.setBuffer(o)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:r}=this;return new RangeError(`Extra ${t.byteLength-r} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,r;for await(let s of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{r=this.doDecodeSync(),t=!0}catch(l){if(!(l instanceof RangeError))throw l}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:o,pos:i,totalPos:a}=this;throw new RangeError(`Insufficient data in parsing ${Aa(o)} at ${a} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let r=t,o=-1;for await(let i of e){if(t&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(o=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(a){if(!(a instanceof RangeError))throw a}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let o=e-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else t={}}else if(e<160){let o=e-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else t=[]}else{let o=e-160;t=this.decodeString(o,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let o=this.lookU8();t=this.decodeString(o,1)}else if(e===218){let o=this.lookU16();t=this.decodeString(o,2)}else if(e===219){let o=this.lookU32();t=this.decodeString(o,4)}else if(e===220){let o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else t=[]}else if(e===221){let o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else t=[]}else if(e===222){let o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else t={}}else if(e===223){let o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else t={}}else if(e===196){let o=this.lookU8();t=this.decodeBinary(o,1)}else if(e===197){let o=this.lookU16();t=this.decodeBinary(o,2)}else if(e===198){let o=this.lookU32();t=this.decodeBinary(o,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let o=this.lookU8();t=this.decodeExtension(o,1)}else if(e===200){let o=this.lookU16();t=this.decodeExtension(o,2)}else if(e===201){let o=this.lookU32();t=this.decodeExtension(o,4)}else throw new ze(`Unrecognized type byte: ${Aa(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let o=r.top();if(o.type===Ql)if(o.array[o.position]=t,o.position++,o.position===o.size)t=o.array,r.release(o);else continue e;else if(o.type===jo){if(t==="__proto__")throw new ze("The key __proto__ is not allowed");o.key=this.mapKeyConverter(t),o.type=sf;continue e}else if(o.map[o.key]=t,o.readCount++,o.readCount===o.size)t=o.map,r.release(o);else{o.key=null,o.type=jo;continue e}}return t}}readHeadByte(){return this.headByte===Fo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Fo}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new ze(`Unrecognized array type byte: ${Aa(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ze(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ze(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new ze(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw af;let r=this.pos+t,o;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?o=this.keyDecoder.decode(this.bytes,r,e):o=tf(this.bytes,r,e),this.pos+=t+e,o}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===jo:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new ze(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw af;let r=this.pos+t,o=this.bytes.subarray(r,r+e);return this.pos+=t+e,o}decodeExtension(e,t){if(e>this.maxExtLength)throw new ze(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+t),o=this.decodeBinary(e,t+1);return this.extensionCodec.decode(o,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=nf(this.view,this.pos);return this.pos+=8,e}readI64(){let e=ka(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function lf(n,e){return new Et(e).decode(n)}function uf(n,e){return new Et(e).decodeMulti(n)}function Jb(n){return n[Symbol.asyncIterator]!=null}async function*Qb(n){let e=n.getReader();try{for(;;){let{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}}function Sa(n){return Jb(n)?n:Qb(n)}async function cf(n,e){let t=Sa(n);return new Et(e).decodeAsync(t)}function df(n,e){let t=Sa(n);return new Et(e).decodeArrayStream(t)}function ff(n,e){let t=Sa(n);return new Et(e).decodeStream(t)}var Wa=Id(ku(),1),Tu=Yd,Au=Jd,Pt=ru,bh=Wa.DOMParser,wh=Wa.XMLSerializer;var _h=Pt!==null;function yh(){if(!_h)throw new Error("@msgpack/msgpack is required for MessagePack support. Install with: npm install @msgpack/msgpack")}var vh=J_();function J_(){if(!_h)return null;let n=new TextEncoder,e=new TextDecoder,t=new Pt.ExtensionCodec;return t.register({type:-1,encode:r=>{if(r instanceof Date){let o=yr(r);if(o==="D"||o==="H")return null}return Pt.encodeTimestampExtension(r)},decode:r=>Pt.decodeTimestampExtension(r)}),t.register({type:1,encode:r=>de(r)?n.encode(r.toString()):null,decode:r=>Lt(e.decode(r))}),t.register({type:2,encode:r=>{if(r instanceof Date&&yr(r)==="D"){let o=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),a=String(r.getUTCDate()).padStart(2,"0");return n.encode(`${o}-${i}-${a}`)}return null},decode:r=>new Date(e.decode(r)+"T00:00:00.000Z")}),t.register({type:3,encode:r=>{if(r instanceof Date&&yr(r)==="H"){let o=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),a=String(r.getUTCSeconds()).padStart(2,"0"),s=String(r.getUTCMilliseconds()).padStart(3,"0");return n.encode(`${o}:${i}:${a}.${s}`)}return null},decode:r=>{let o=e.decode(r),i=o.indexOf("."),a=i>=0?o.substring(0,i):o,s=i>=0?o.substring(i+1):"0",[l,u,c]=a.split(":"),d=Math.round(+s.substring(0,3));return new Date(Date.UTC(1970,0,1,+l,+u,+c,d))}}),t.register({type:4,encode:r=>{let o=Du(r);if(o!==null){let[i,a]=o;return n.encode(`${i}:${a(r)}`)}return null},decode:r=>{let o=e.decode(r),i=o.indexOf(":"),a=o.slice(0,i),s=o.slice(i+1),l=vr[a];if(l!==void 0){let[,u]=l;return u(s)}return`${s}::${a}`}}),t}function Eh(n){return yh(),Pt.encode(n,{extensionCodec:vh})}function xh(n){return yh(),Pt.decode(n,{extensionCodec:vh})}function Ya(n,e=!1){let t=Xa(n);if(t===null)return[!1,String(n)];let[r,o,i]=t;return i&&!e?[!1,String(n)]:[!0,`${o(n)}::${r}`]}function Su(n){if(!n.includes("::"))return[!1,n];let e=n.lastIndexOf("::"),t=n.slice(0,e),r=n.slice(e+2),o=vr[r];if(o===void 0)return[!1,n];let[,i]=o;return[!0,i(t)]}function Kn(n,e,t){if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let r={};for(let[o,i]of Object.entries(n))r[o]=Kn(i,e,t);return r}return Array.isArray(n)?n.map(r=>Kn(r,e,t)):t(n)?e(n):n}function Cu(n){let e=Xa(n);if(e!==null){let[t,r,o]=e;return o?[n,!1]:[`${r(n)}::${t}`,!0]}if(Array.isArray(n)){let t=!1;return[n.map(o=>{let[i,a]=Cu(o);return a&&(t=!0),i}),t]}if(n!==null&&typeof n=="object"){let t=!1,r={};for(let[o,i]of Object.entries(n)){let[a,s]=Cu(i);s&&(t=!0),r[o]=a}return[r,t]}return[n,!1]}function Q_(n,e=!1){let[t,r]=Ya(n,e);if(t)return r;let[o,i]=Cu(n),a=JSON.stringify(o);return i?`${a}::JS`:a}function ey(n){return JSON.stringify(n)}function ty(n){if(!Pt)throw new Error("@msgpack/msgpack is required for MessagePack support");return Pt.encode(n)}function L(n,e=null,{raw:t=!1,qs:r=!1,_forceSuffix:o=!1}={}){if(r)return`${Th(n)}::QS`;if(t){if(e===null||e==="json")return ey(n);if(e==="msgpack")return ty(n);throw e==="xml"?new Error("raw=true is not supported for XML transport"):new Error(`Unknown transport: ${e}`)}if(e===null||e==="json"){let i=Q_(n,o);return e==="json"?`"${i}"`:i}else{if(e==="xml")return`<?xml version="1.0" ?><tytx_root>${kh(n)}</tytx_root>`;if(e==="msgpack")return Eh(n);throw new Error(`Unknown transport: ${e}`)}}var Jn,Nu;typeof window<"u"&&window.DOMParser?(Jn=window.DOMParser,Nu=window.XMLSerializer):(Jn=bh,Nu=wh);function Ah(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let e=Object.keys(n);if(e.length!==1)return!1;let t=n[e[0]];return t!==null&&typeof t=="object"&&"value"in t}function Dh(n,e,t){let r=n.createElement(e),o=t.attrs||{},i=t.value;for(let[a,s]of Object.entries(o))r.setAttribute(a,L(s,null,{_forceSuffix:!0}));if(Array.isArray(i))for(let a of i)if(Ah(a)){let[s]=Object.keys(a),l=a[s],u=Dh(n,s,l);r.appendChild(u)}else{r.textContent=L(i);break}else r.textContent=L(i);return r}function kh(n){if(!Jn)throw new Error("XML support requires @xmldom/xmldom package in Node.js");if(Ah(n)){let[e]=Object.keys(n),t=n[e],r=new Jn().parseFromString("<root/>","text/xml"),o=Dh(r,e,t);return new Nu().serializeToString(o)}else return L(n)}function Iu(n){let e={};for(let r=0;r<n.attributes.length;r++){let o=n.attributes[r];e[o.name]=F(o.value)}let t=[];for(let r=0;r<n.childNodes.length;r++){let o=n.childNodes[r];o.nodeType===1&&t.push(o)}if(t.length>0)if(t.length===1){let r=t[0],o=Iu(r);return{attrs:e,value:{[r.tagName]:o}}}else{let r=[];for(let o of t){let i=Iu(o);r.push({[o.tagName]:i})}return{attrs:e,value:r}}return{attrs:e,value:F(n.textContent)}}function Sh(n){if(!Jn)throw new Error("XML support requires @xmldom/xmldom package in Node.js");let r=new Jn().parseFromString(n,"text/xml").documentElement;if(r.tagName==="tytx_root"){let i=null;for(let a=0;a<r.childNodes.length;a++)if(r.childNodes[a].nodeType===1){i=r.childNodes[a];break}if(!i)return F(r.textContent);r=i}let o=Iu(r);return{[r.tagName]:o}}function Ou(n){return typeof n=="string"}function ry(n){let[e,t]=Su(n);if(e)return t;let r=n;r.endsWith("::JS")&&(r=r.slice(0,-4));let o;try{o=JSON.parse(r)}catch{return n}return Kn(o,Ru,Ou)}function Ru(n){return n.includes("::")?Su(n)[1]:n}function ny(n){let e=Sh(n);return typeof e=="string"?F(e):e}function oy(n){return xh(n)}function F(n,e=null){if(n===null)return null;if(e===null||e==="json"){let t=n;return e==="json"&&n.startsWith('"')&&n.endsWith('"')&&(t=n.slice(1,-1)),ry(t)}else{if(e==="xml")return ny(n);if(e==="msgpack")return oy(n);throw new Error(`Unknown transport: ${e}`)}}function Ch(n){return Symbol.asyncIterator in n?(async function*(){for await(let t of n)yield Kn(t,Ru,Ou)})():(function*(){for(let t of n)yield Kn(t,Ru,Ou)})()}function Th(n){if(Array.isArray(n))return n.map(e=>String(e)).join("&");if(n!==null&&typeof n=="object"){let e=[];for(let[t,r]of Object.entries(n)){let[o,i]=Ya(r,!0);o?e.push(`${t}=${i}`):e.push(`${t}=${r}`)}return e.join("&")}throw new TypeError(`toQs expects object or array, got ${typeof n}`)}function Nh(n){if(!n)return[];let e=n.split("&"),t=e.map(a=>a.includes("=")),r=t.every(Boolean),o=!t.some(Boolean);if(!r&&!o)throw new Error("QS format error: mixed items with and without '='");if(o)return e.map(a=>F(a));let i={};for(let a of e){let s=a.indexOf("="),l=a.slice(0,s),u=a.slice(s+1);i[l]=F(u)}return i}var Oh=Tu||Au||Number,Rh=Tu?"decimal.js":Au?"big.js":"number";function $u(){return Rh}function Lt(n){return new Oh(n)}function de(n){return Rh==="number"?!1:n instanceof Oh}function yr(n){let e=n.getUTCFullYear()===1970&&n.getUTCMonth()===0&&n.getUTCDate()===1,t=n.getUTCHours()===0&&n.getUTCMinutes()===0&&n.getUTCSeconds()===0&&n.getUTCMilliseconds()===0;return e&&!t?"H":t&&!e?"D":"DHZ"}function iy(n){return n.toString()}function ay(n){let e=n.getUTCFullYear(),t=String(n.getUTCMonth()+1).padStart(2,"0"),r=String(n.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}function sy(n){return n.toISOString()}function ly(n){let e=String(n.getUTCHours()).padStart(2,"0"),t=String(n.getUTCMinutes()).padStart(2,"0"),r=String(n.getUTCSeconds()).padStart(2,"0"),o=String(n.getUTCMilliseconds()).padStart(3,"0");return`${e}:${t}:${r}.${o}`}function uy(n){return n?"true":"false"}function cy(n){return n.toString()}function dy(n){return n.toString()}function fy(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode.apply(null,n.subarray(t,t+32768));return btoa(e)}var Za=[],Bu=new Map;function Du(n){if(n===null||typeof n!="object")return null;for(let e=Object.getPrototypeOf(n);e!==null;e=Object.getPrototypeOf(e))for(let[t,r,o,i]of Za)if(t.prototype===e)return[r,o,i];return null}function Xa(n){if(n===null)return["NN",()=>"",!0];if(de(n))return["N",iy,!1];if(n instanceof Uint8Array)return["RAW",fy,!1];if(n instanceof Date){let e=yr(n);return e==="D"?["D",ay,!1]:e==="H"?["H",ly,!1]:["DHZ",sy,!1]}return typeof n=="boolean"?["B",uy,!0]:typeof n=="number"?Number.isInteger(n)?["L",cy,!0]:["R",dy,!0]:Du(n)}function hy(n){return Lt(n)}function py(n){let[e,t,r]=n.split("-").map(Number);return new Date(Date.UTC(e,t-1,r,0,0,0,0))}function Ih(n){return new Date(n)}function my(n){let[e,t,r]=n.split(":"),[o,i]=r.split(".");return new Date(Date.UTC(1970,0,1,Number(e),Number(t),Number(o),Number(i||0)))}function gy(n){return n.toLowerCase()==="true"}function by(n){return parseInt(n,10)}function wy(n){return parseFloat(n)}function _y(n){return n}function yy(n){return null}var vy=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Ey(n){if(!vy.test(n))throw new Error(`RAW payload is not standard padded base64: '${n}'`);let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function xy(n){return Nh(n)}var ky=/^[A-Z]+$/,vr={N:[Object,hy],D:[Date,py],DH:[Date,Ih],DHZ:[Date,Ih],H:[Date,my],L:[Number,by],R:[Number,wy],T:[String,_y],B:[Boolean,gy],QS:[Object,xy],NN:[null,yy],RAW:[Uint8Array,Ey]};function ai(n){return Object.hasOwn(vr,n)?vr[n][0]:null}function Mu(n,e,t,r,o=!1){if(typeof e!="string"||!ky.test(e))throw new Error(`TYTX suffix '${e}' is invalid: expected uppercase ASCII letters only`);let i=vr[e];if(i!==void 0&&i[0]!==n){let a=i[0]===null?"null":i[0].name;throw new Error(`TYTX suffix '${e}' is already registered for ${a}`)}Za=Za.filter(([a])=>a!==n),Za.push([n,e,t,o]),vr[e]=[n,r]}function Wr(n,e){Bu.set(n,e)}function pt(n){return Bu.has(n)?Bu.get(n):{}}function re(n){if(typeof n!="string"||!["^","="].includes(n[0])||n.startsWith("=="))return null;let e=n.indexOf(":");if(e<0)return null;let t=n[e+1]==="=";return{pointer:n.slice(0,e),expression:t,body:n.slice(e+(t?2:1))}}var Bh=/^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;function Yr(n,e){let t="",r=!1;for(let o=0;o<n.length;){if(n[o]!=="{"&&n[o]!=="}"){t+=n[o++];continue}let i=n.slice(o).match(Bh);if(!i)throw new SyntaxError("Invalid pointer template placeholder");let a=i[1]??"",s=a.startsWith("?"),l=e(s?a.slice(1):a);l==null||l===""&&!s?r=!0:t+=String(l),o+=i[0].length}return r?null:t}function si(n){let e=[],t=new Set,r="",o=!0;for(let i=0;i<n.length;){let a=i,s=n[i];if(s==='"'||s==="'"||s==="`"){for(i++;i<n.length;){if(n[i]==="\\"){i+=2;continue}if(n[i++]===s)break}r+=n.slice(a,i),o=!1;continue}if(n.startsWith("//",i)){i=n.indexOf(`
|
|
31
|
-
`,i),i<0&&(i=n.length),r+=n.slice(a,i);continue}if(n.startsWith("/*",i)){let c=n.indexOf("*/",i+2);i=c<0?n.length:c+2,r+=n.slice(a,i);continue}if(s==="/"&&o){let c=!1;for(i++;i<n.length;){let d=n[i++];if(d==="\\"){i++;continue}if(d==="[")c=!0;else if(d==="]")c=!1;else if(d==="/"&&!c)break}for(;/[a-z]/i.test(n[i]??"")&&i<n.length;)i++;r+=n.slice(a,i),o=!1;continue}let l=s==="{"?n.slice(i).match(Bh):null;if(l){let c=l[1]??"";if(c.startsWith("?"))throw new SyntaxError("Optional slots are supported in pointer templates only");r+=`_pointerValues[${e.length}]`,e.push(c),i+=l[0].length,o=!1;continue}let u=n.slice(i).match(/^[A-Za-z_$][\w$]*/);if(u){t.add(u[0]),r+=u[0],i+=u[0].length,o=["return","typeof","void","delete","new","in","instanceof","yield","await"].includes(u[0]);continue}r+=s,i++,/\s/.test(s)||(o=/[([{,:;=!?&|+*%~<>\/-]/.test(s))}return{text:r,slots:e,identifiers:t}}function $h(n,e,t=()=>null){let r=new Map,o=[],i=a=>{if(r.has(a))return r.get(a);if(!n.has(a))throw new Error(`Referenced Source attribute '${a}' does not exist`);if(o.includes(a))throw new Error(`Cyclic attribute dependency: ${[...o,a].join(" -> ")}`);o.push(a);try{let s=n.get(a),l=typeof a=="string"?re(s):null,u=e.get(a);if(l){let c=d=>d?i(d):e.get(a);if(l.expression){let d=si(l.body);u=t(a,s,d,d.slots.map(c))}else u=Yr(l.body,c),e.get(a)==null&&(u=null)}return r.set(a,u),u}finally{o.pop()}};return new Map([...n.keys()].map(a=>[a,i(a)]))}function Ft(n,e){let t=new Map([...Object.entries(n.getAttr()),...n.fixedAttrItems()]),r=new Set,o=[],i=a=>{let s=re(a);if(!s)return;let l=[];s.expression?l.push(...si(s.body).slots):Yr(s.body,u=>(l.push(u),""));for(let u of l.filter(Boolean)){if(!t.has(u))throw new Error(`Referenced Source attribute '${u}' does not exist`);if(o.includes(u))throw new Error(`Cyclic attribute dependency: ${[...o,u].join(" -> ")}`);r.has(u)||(o.push(u),i(t.get(u)),o.pop(),r.add(u))}};return i(e),r}var Mh={network:{maxAttempts:3,delay:1,backoff:2,jitter:!0,on:["TypeError","NetworkError","AbortError"]},aggressive:{maxAttempts:5,delay:.5,backoff:2,jitter:!0,on:["Error"]},gentle:{maxAttempts:2,delay:2,backoff:1.5,jitter:!1,on:["TypeError","NetworkError"]}};function Ay(n){let e=n._retryPolicy;return e==null?null:typeof e=="string"?Mh[e]||null:e}function Dy(n,e){return e.some(t=>t==="Error"?!0:n.name===t||n.constructor.name===t)}function Sy(n){return new Promise(e=>setTimeout(e,n))}async function Cy(n,e){if(!e)return n();let t=e.maxAttempts||3,r=e.delay||1,o=e.backoff||2,i=e.jitter!==!1,a=e.on||["Error"],s=null,l=r*1e3;for(let u=0;u<t;u++)try{let c=n();return c instanceof Promise?await c:c}catch(c){if(s=c,u<t-1&&Dy(c,a)){let d=l;i&&(d*=1+Math.random()*.1),await Sy(d),l*=o}else throw c}throw s}var fe=class n{static classKwargs={cacheTime:0,readOnly:!1,asBag:null,retryPolicy:null};static classArgs=[];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy"]);constructor(e={}){let r={...this.constructor.classKwargs,...e};for(let i of["interval","reactive"])if(Object.hasOwn(r,i))throw new TypeError(`Removed resolver option: ${i}. Schedule updates in the application; use reset() and read explicitly.`);this.cacheTime=r.cacheTime,this._readOnly=r.readOnly,this._asBag=r.asBag,this._retryPolicy=r.retryPolicy,this._kw={};let o=this.constructor.internalParams;for(let[i,a]of Object.entries(r))o.has(i)||(this._kw[i]=a);this._lastUpdate=null,this._node=null,this._lastEffectiveFingerprint=null,this._cachedValue=null,this.init()}init(){}setNode(e){e!==this._node&&!this.readOnly&&this._lastUpdate!==null&&this.reset(),this._node=e,this.onSetResolver(e)}onSetResolver(e){}get node(){return this._node}get cacheTime(){return this._cacheTime}set cacheTime(e){if(typeof e=="boolean")throw new TypeError("cacheTime must be numeric; use a negative value for infinite caching");this._cacheTime=e}get readOnly(){return this._readOnly}get expired(){return this._cacheTime<0?this._lastUpdate===null:this._cacheTime===0||this._lastUpdate===null?!0:(Date.now()-this._lastUpdate)/1e3>this._cacheTime}reset(...e){if(e.length)throw new TypeError("reset() takes no arguments. It invalidates the cache for the next explicit read.");this._lastUpdate=null,this._lastEffectiveFingerprint=null}get cachedValue(){return!this.readOnly&&this._node?this._node._value:this._cachedValue}set cachedValue(e){!this.readOnly&&this._node?this._node.setValue(e,!1):this._cachedValue=e}_computeEffectiveFingerprint(e){return JSON.stringify(Object.entries(e).sort())}_buildEffectiveKw(){let e={...this._kw};if(this._node&&this._node.attr)for(let t of Object.keys(this._kw))Object.hasOwn(this._node.attr,t)&&(e[t]=this._node.attr[t]);return e}resolve(e={}){let{static:t=!1,...r}=e;if(t)return this._node?this._node._value:this.cachedValue;let o=this._buildEffectiveKw();if(Object.keys(r).length>0)return this._load({...o,...r},a=>this._prepareValue(a));let i=this._computeEffectiveFingerprint(o);return i===this._lastEffectiveFingerprint&&!this.expired?this.cachedValue:(this._lastEffectiveFingerprint=i,this._load(o,a=>this._finalize(a)))}_load(e,t){let r=Ay(this),o=()=>this.load(e);if(r)return Cy(o,r).then(t);let i=o();return i&&typeof i.then=="function"?i.then(t):t(i)}_finalize(e){return e=this._prepareValue(e),this._lastUpdate=Date.now(),(!this.readOnly||this.cacheTime!==0)&&(this.cachedValue=e),e}_prepareValue(e){let t;return this._asBag===!0?t=!0:this._asBag===!1?t=!1:t=!this._readOnly,t&&e!==null&&e!==void 0&&(e=this._convertToBag(e)),e}_convertToBag(e){let t=n._BagClass;if(!t||e&&typeof e._htraverse=="function")return e;if(typeof e=="string"){if(e=e.trim(),e.startsWith("<")&&t.fromXml)return t.fromXml(e);if((e.startsWith("{")||e.startsWith("["))&&t.fromTytx)return t.fromTytx(e)}return e}static registerBagClass(e){n._BagClass=e}load(e){return null}};fe._BagClass=null;var Er=class extends fe{static classKwargs={cacheTime:0,readOnly:!1,asBag:!1,retryPolicy:null,callback:null};static classArgs=["callback"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy","callback"]);constructor(e={}){typeof e=="function"&&(e={callback:e}),super(e),this._callback=e.callback||null}load(e){return this._callback?this._callback.call(this,e):null}};var xt=class n{constructor(e,t,r=null,o=null,i=null,a=null,s=null,l=!0){this.label=t,this._value=null,this._attr={},this._parentBag=null,this._resolver=null,this._nodeSubscribers={},this._onChangedValue=null,this.nodeTag=a,this.xmlTag=s,this._compiled=null,this.parentBag=e,o&&this.setAttr(o,!1,!0,l),r!==null&&this.setValue(r,!1),i&&(this.resolver=i)}get parentBag(){return this._parentBag}set parentBag(e){e===null&&this._value?.parentNode===this&&this._value.setBackref(),this._parentBag=e,e?.backref&&this._value&&typeof this._value._htraverse=="function"&&this._value.setBackref(this,e)}get value(){return this.getValue()}set value(e){this.setValue(e)}getValue(e=!1,t=null,r={}){if(t!==null){let o=F(`${t}::QS`);if(Array.isArray(o)){let i=o.length?o:Object.keys(this._attr),a=i.map(l=>{let u=this.getAttr(l);return!e&&u instanceof fe?u.resolve():u}),s=l=>o.length===0?Object.fromEntries(i.map((u,c)=>[u,l[c]])):l.length===1?l[0]:l;return a.some(l=>l&&typeof l.then=="function")?Promise.all(a).then(s):s(a)}else{if(!this._resolver)throw new Error("Cannot use kwargs syntax without resolver");r={...r,...o}}}return this._resolver!==null?this._resolver.resolve({static:e,...r}):this._value}setValue(e,t=!0,r=null,o=null,i=!0,a=null,s=!1){e instanceof fe?(this.resolver=e,e=null):e instanceof n&&(r=r||{},Object.assign(r,e._attr),e.resolver&&(this.resolver=e.resolver),e=e._value);let l=this._value;l!==e&&l?.parentNode===this&&l.setBackref(),this._value=e;let u=l!==this._value,c=t??!0,d=null;if(r!==null){let h={...this._attr};this.setAttr(r,!1,o,i);let p=this._buildAttrDiff(h,this._attr);d=Object.keys(p).length>0?p:null}t=c&&(u||d!==null);let f=d?u?"upd_value_attr":"upd_attrs":"upd_value";if(this._onChangedValue&&this._onChangedValue(this,e,l,c),t){let h=d!==null?{oldvalue:l,attrs_diff:d}:{oldvalue:l};for(let p of Object.values(this._nodeSubscribers))p({node:this,info:h,evt:f})}this._parentBag!==null&&this._parentBag.backref&&(e&&typeof e._htraverse=="function"&&e.setBackref(this,this._parentBag),t&&this._parentBag._onNodeChanged(this,[this.label],f,l,d,a,s))}replace(e){if(!(e instanceof n))throw new TypeError("BagNode.replace expects a BagNode");if(e===this)return this;let t=e.staticValue;t&&typeof t._htraverse=="function"&&(t=t.createChildBag().replace(t));let r=null;e.resolver&&(r=Object.create(Object.getPrototypeOf(e.resolver),Object.getOwnPropertyDescriptors(e.resolver)),r._node=null,r._kw={...e.resolver._kw});let o=this._value,i={...this._attr},a=this.resolver;a&&a._node===this&&(a._node=null),this.resolver=r,this.setValue(t,!1,{...e.attr},!1,!1,null);let s=this._buildAttrDiff(i,this._attr),l=Object.keys(s).length?s:null,u=o!==t||a!==r;if(u||l){let c=l?u?"upd_value_attr":"upd_attrs":"upd_value",d=l?{oldvalue:o,attrs_diff:l}:{oldvalue:o};for(let f of Object.values(this._nodeSubscribers))f({node:this,info:d,evt:c});this._parentBag!==null&&this._parentBag.backref&&this._parentBag._onNodeChanged(this,[this.label],c,o,l)}return this}get staticValue(){return this._value}set staticValue(e){this._value=e}get resolver(){return this._resolver}set resolver(e){this._resolver=e,e&&e.setNode&&e.setNode(this)}resetResolver(){if(!this._resolver)throw new Error("Cannot reset resolver: node has no resolver");this._resolver.reset(),this.setValue(null)}get attr(){return this._attr}getAttr(e=null,t=null){return e?e in this._attr?this._attr[e]:t:this._attr}_buildAttrDiff(e,t){let r={},o=new Set([...Object.keys(e),...Object.keys(t)]);for(let i of o){let a=i in e?e[i]:null,s=i in t?t[i]:null;a!==s&&(r[i]={old:a,new:s})}return r}setAttr(e=null,t=!0,r=!0,o=!0){let i=e||{},a=Object.keys(this._nodeSubscribers).length>0,l=t&&(a||this._parentBag!==null&&this._parentBag.backref)?{...this._attr}:null;if(r?Object.assign(this._attr,i):this._attr={...i},o)for(let u of Object.keys(this._attr))this._attr[u]===null&&delete this._attr[u];if(t&&l!==null){let u=this._buildAttrDiff(l,this._attr);if(Object.keys(u).length>0&&a)for(let c of Object.values(this._nodeSubscribers))c({node:this,info:{attrs_diff:u},evt:"upd_attrs"});if(Object.keys(u).length>0&&this._parentBag!==null&&this._parentBag.backref){let c=t===!0?"true":String(t);this._parentBag._onNodeChanged(this,[this.label],"upd_attrs",null,u,c)}}}delAttr(...e){for(let t of e)if(typeof t=="string"&&t.includes(","))for(let r of t.split(","))delete this._attr[r.trim()];else delete this._attr[t]}hasAttr(e,t=null){return e in this._attr?t!==null?this._attr[e]===t:!0:!1}getInheritedAttributes(){let e={};return this._parentBag&&this._parentBag.parentNode&&(e=this._parentBag.parentNode.getInheritedAttributes()),{...e,...this._attr}}subscribe(e,t){this._nodeSubscribers[e]=t}unsubscribe(e){delete this._nodeSubscribers[e]}get compiled(){return this._compiled||(this._compiled={}),this._compiled}get isBranch(){return this._value!=null&&typeof this._value._htraverse=="function"}get position(){return this._parentBag===null?null:this._parentBag._nodes.index(this.label)}get fullpath(){if(this._parentBag!==null){let e=this._parentBag.fullpath;return e?`${e}.${this.label}`:this.label}return null}get parentNode(){return this._parentBag?this._parentBag.parentNode:null}attributeOwnerNode(e,t=null){let r=this;if(t===null)for(;r&&!(e in r._attr);)r=r.parentNode;else for(;r&&r._attr[e]!==t;)r=r.parentNode;return r}asTuple(){return[this.label,this.value,this._attr,this._resolver||null]}isEqual(e){if(!(e instanceof n)||this.label!==e.label)return!1;let t=Object.keys(this._attr),r=Object.keys(e._attr);if(t.length!==r.length)return!1;for(let o of t)if(this._attr[o]!==e._attr[o])return!1;return this._resolver!==null?this._resolver===e._resolver:this._value&&typeof this._value.equalTo=="function"?this._value.equalTo(e._value):this._value&&typeof this._value.isEqual=="function"?this._value.isEqual(e._value):this._value===e._value}diff(e){if(this.label!==e.label)return`Other label: ${e.label}`;let t=Object.keys(this._attr),r=Object.keys(e._attr);return t.length!==r.length||t.some(o=>this._attr[o]!==e._attr[o])?`attributes self:${JSON.stringify(this._attr)} --- other:${JSON.stringify(e._attr)}`:this._value!==e._value?`value self:${this._value} --- other:${e._value}`:null}toJson(e=!0){let t=this.value;return t&&typeof t.toJson=="function"&&(t=t.toJson(e,!0)),{label:this.label,value:t,attr:this._attr}}toString(){return`BagNode : ${this.label}`}};var li=class n{constructor(){this._dict=Object.create(null),this._list=[],this._parentBag=null}index(e){if(e in this._dict)return this._list.findIndex(r=>r.label===e);let t=e.match(/^#(\d+)$/);if(t){let r=parseInt(t[1],10);return r<this._list.length?r:-1}if(t=e.match(/^#(\w*)=(.*)$/),t){let[,r,o]=t,i=o.includes("::")?F(o):o;return r?this._list.findIndex(a=>a.getAttr(r)===i):this._list.findIndex(a=>a._value===i)}return-1}_parsePosition(e){let t=this._list.length;if(e==null||e===">")return t;if(typeof e=="number")return e<0&&(e=t+e),Math.max(0,Math.min(e,t));if(e==="<")return 0;if(e.startsWith("#")){let r=this._parseSharpIndex(e.slice(1),e);return Math.min(r,t)}if(e.startsWith("<")){let r=e.slice(1);if(r.startsWith("#")){let i=this._parseSharpIndex(r.slice(1),e);return Math.min(i,t)}let o=this.index(r);if(o<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return o}if(e.startsWith(">")){let r=e.slice(1);if(r.startsWith("#")){let i=this._parseSharpIndex(r.slice(1),e);return Math.min(i+1,t)}let o=this.index(r);if(o<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return o+1}throw new Error(`Invalid node_position '${e}': unrecognized syntax`)}_parseSharpIndex(e,t){if(!/^-?\d+$/.test(e))throw new Error(`Invalid node_position '${t}': '${e}' is not an integer`);let r=parseInt(e,10);if(r<0)throw new Error(`Invalid node_position '${t}': negative index not allowed in '#n' syntax`);return r}get(e){if(typeof e=="number")return e>=0&&e<this._list.length?this._list[e]:null;if(e.startsWith("#")){let t=this.index(e);return t>=0?this._list[t]:null}return this._dict[e]||null}set(e,t,r=">",o=null,i=null,a=null,s=!1,l=!0,u=null,c=!0,d=!1,f=null){let h=null;if(e.includes("?")&&([e,h]=e.split("?",2)),e==null||e.startsWith("#"))throw new Error("Cannot create new node with #n syntax");if(h){let m=h.split("&");if(m.length===1)o={[m[0]]:t};else{if(!Array.isArray(t)||t.length!==m.length)throw new Error("Wrong attributes assignment");o={};for(let b=0;b<m.length;b++)o[m[b]]=t[b]}t=null}let p=this._dict[e];if(p)f&&(p.nodeTag=f),a!==null&&(a===!1?p.resolver=null:p.resolver=a),h?p.setAttr(o,c,!0,l):p.setValue(t,c,o,s,l,u,d);else{let m=i&&i.nodeClass?i.nodeClass:xt;p=new m(i,e,h?null:t,o,a,f,null,l);let b=this._parsePosition(r);this._dict[e]=p,this._list.splice(b,0,p),c&&i&&i.backref&&i._onNodeInserted(p,b,null,u,d)}return d&&p.setValue(null,!1),p}pop(e){let t=this.get(e);if(t){delete this._dict[t.label];let r=this._list.indexOf(t);return r>=0&&this._list.splice(r,1),t}return null}has(e){return e in this._dict}get length(){return this._list.length}clear(){this._dict=Object.create(null),this._list=[]}keys(){return this._list.map(e=>e.label)}values(){return this._list.map(e=>e.getValue())}items(){return this._list.map(e=>[e.label,e.getValue()])}[Symbol.iterator](){return this._list[Symbol.iterator]()}move(e,t,r=!0){if(t<0)return;let o=Array.isArray(e)?e:[e];if(o.length===0||t>=this._list.length)return;let i=this._list[t].label;if(o.length>1){let a=[...o].sort((c,d)=>c-d),s=a[0]<t?1:0,l=[];for(let c=a.length-1;c>=0;c--){let d=a[c];if(d>=0&&d<this._list.length){let f=this._list[d];this._list.splice(d,1),l.push(f),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeDeleted(f,d)}}let u=this.index(i);u<0&&(u=this._list.length),u+=s;for(let c of l)this._list.splice(u,0,c),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(c,u)}else{let a=o[0];if(a===t||a<0||a>=this._list.length)return;let s=this._list[a];this._list.splice(a,1),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeDeleted(s,a),this._list.splice(t,0,s),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(s,t)}}isEqual(e){if(!(e instanceof n)||this._list.length!==e._list.length)return!1;for(let t=0;t<this._list.length;t++){let r=this._list[t],o=e._list[t];if(!r.isEqual(o))return!1}return!0}};var jh=Id(ku(),1);var Pu="::RSLV:",Ka=new Map,Ja=new Map,Qa=new WeakMap,Te=class extends Error{constructor(e){super(e),this.name="BagSerializationError"}},Qn=class extends fe{constructor(e){super({asBag:!1}),Qa.set(this,e)}get payload(){return Qa.get(this)}load(){throw new Te("This resolver is opaque; local execution is unavailable")}};function Lu(n,{module:e,name:t,encode:r,decode:o}){if(!(n.prototype instanceof fe)||n===Qn||typeof e!="string"||!e||typeof t!="string"||!t||typeof r!="function"||typeof o!="function")throw new TypeError("registerResolver requires a BagResolver subclass, module, name and adapters");let i=JSON.stringify([e,t]);if(Ka.has(i)&&Ka.get(i).cls!==n)throw new TypeError(`Resolver ${e}.${t} is already registered`);if(Ja.has(n)&&Ja.get(n).key!==i)throw new TypeError("A resolver class cannot own two wire identities");let a={cls:n,module:e,name:t,encode:r,decode:o,key:i};Ka.set(i,a),Ja.set(n,a)}function Ph(n){if(!n||typeof n!="object"||Array.isArray(n)||typeof n.resolver_module!="string"||typeof n.resolver_class!="string"||!Array.isArray(n.args??[])||!n.kwargs||typeof n.kwargs!="object"||Array.isArray(n.kwargs))throw new Te("Invalid resolver description")}function Lh(n,e=new Set){if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n)||!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new Te("Resolver parameters must be JSON data; callbacks cannot travel");e.add(n);for(let t of Object.values(n))Lh(t,e);e.delete(n)}}function ui(n){if(Qa.has(n))return Qa.get(n);let e=Ja.get(n.constructor);if(!e)throw new Te(`Unregistered resolver: ${n.constructor.name}`);let t=e.encode(n),r={resolver_module:e.module,resolver_class:e.name,args:t.args??[],kwargs:t.kwargs??{}};return Ph(r),Lh(r),Pu+JSON.stringify(r)}function es(n){if(typeof n!="string"||!n.startsWith(Pu))return null;let e=n.slice(Pu.length);if(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+$/.test(e))return new Qn(n);let t;try{t=JSON.parse(e)}catch{throw new Te("Invalid resolver JSON or signed token")}Ph(t);let r=Ka.get(JSON.stringify([t.resolver_module,t.resolver_class]));if(!r)return new Qn(n);let o=r.decode({args:t.args??[],kwargs:t.kwargs});if(!(o instanceof r.cls))throw new Te("Resolver decoder returned an incompatible instance");return o}function ts(n){return Object.fromEntries(Object.entries(n||{}).map(([e,t])=>[e,t instanceof fe?ui(t):t]))}function Fu(n){return Object.fromEntries(Object.entries(n||{}).map(([e,t])=>[e,es(t)??t]))}var kt="__cls";function eo(n,e){return n!==null&&n.tytxSuffix===e?n:ai(e)}function Ny(n){let e=n.tytxSuffix,t=Object.entries(pt(e)).filter(([,r])=>r===n).map(([r])=>r);if(t.length===0)throw new Te(`${n.name} is not in the TYTX subtype dictionary of '${e}'`);if(t.length>1)throw new Te(`${n.name} is in the TYTX subtype dictionary of '${e}' under several names: ${t.sort().join(", ")}`);return t[0]}function ju(n,e){let t=pt(n);if(!Object.hasOwn(t,e))throw new Te(`Unknown Bag class '${e}' for TYTX type '${n}'`);return t[e]}function qu(n,e){return n===e?null:Ny(n)}function*qh(n,e=[]){for(let t of n){let r=[...e,t.label];yield[r,t];let o=t.getValue(!0);!t.resolver&&o instanceof E&&(yield*qh(o,r))}}function Iy(n){let e=n.toISOString(),t=n.getUTCFullYear()===1970&&n.getUTCMonth()===0&&n.getUTCDate()===1,r=n.getUTCHours()===0&&n.getUTCMinutes()===0&&n.getUTCSeconds()===0&&n.getUTCMilliseconds()===0;if(r&&!t)return e.slice(0,e.indexOf("T"));let o=e.replace(/\.000Z$/,"Z");return t&&!r?o.slice(o.indexOf("T")+1):o}function to(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function xr(n){return typeof n=="string"?n.includes("::")?`${n}::T`:n:Array.isArray(n)?n.map(xr):to(n)?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,xr(t)])):n}function Uu(n){if(!to(n))throw new TypeError("Bag options must be an object");let{recursive:e=!0}=n;if(typeof e!="boolean")throw new TypeError("recursive must be a boolean");return e}var Fh=!1,E=class n{static tytxSuffix="X";constructor(e=null,t={}){this._nodes=new li,this._backref=!1,this._parent=null,this._parentNode=null,this._rootAttributes=null,this._updSubscribers={},this._insSubscribers={},this._delSubscribers={},Uu(t),e!=null&&this.fillFrom(e,t)}get parent(){return this._parent}set parent(e){this._parent=e}get parentNode(){return this._parentNode}set parentNode(e){this._parentNode=e}get backref(){return!!this._backref}get nodeClass(){return xt}createChildBag(){return new this.constructor}get fullpath(){if(this._parent!==null&&this._parentNode!==null){let e=this._parent.fullpath;return e?`${e}.${this._parentNode.label}`:this._parentNode.label}return null}relativePath(e){let t=[],r=e;for(;r!==null;){if(r.parentBag===this)return t.push(r.label),t.reverse(),t.join(".");t.push(r.label),r=r.parentNode}return null}get length(){return this._nodes.length}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}get attributes(){return this._parentNode!==null?this._parentNode.getAttr():{}}get rootAttributes(){return this._rootAttributes}set rootAttributes(e){this._rootAttributes=e!==null?{...e}:null}_htraverseBefore(e){let t=this,r;for(typeof e=="string"?(e=e.replace(/\.\.\//g,"#parent."),r=e.split(".").filter(o=>o)):r=[...e];r.length&&r[0]==="#parent"&&t!==null;)r.shift(),t=t.parent;return[t,r]}_htraverse(e,t=!1,r=!0){let[o,i]=this._htraverseBefore(e);if(o===null)return[null,null];if(i.length===0)return[o,""];for(;i.length>1&&o instanceof n;){let a=i[0];if(a==="#parent"){if(o.parent===null||o.parent===void 0)break;i.shift(),o=o.parent;continue}let s=o._nodes.get(a);if(!s)break;let l=s.getValue(r);if(l instanceof n)i.shift(),o=l;else if(t){let u=o.createChildBag();s.setValue(u,!0,null,!0,!0,"autocreate"),i.shift(),o=u}else break}if(!t)return i.length>1?[null,null]:[o,i[0]];for(;i.length>1;){let a=i.shift();if(a.startsWith("#"))throw new ci("Not existing index in #n syntax");let s=o.createChildBag();o._nodes.set(a,s,">",null,o,null,!1,!0,"autocreate"),o=s}return[o,i[0]]}get(e,t=null,r=!0,o={}){if(!e)return this;if(e==="#parent")return this.parent;let i=null;e.includes("?")&&([e,i]=e.split("?",2));let a=this._nodes.get(e);return a?a.getValue(r,i,o):t}getItem(e,t=null,r=!1,o={}){if(!e)return this;let[i,a]=this._htraverse(e,!1,r);return i instanceof n?i.get(a,t,r,o):t}setItem(e,t,r=null,o=">",i=!1,a=!0,s=null,l=!1,u=!0,c=null,d=null){if(e==="")throw new RangeError("setItem requires a non-empty path");let[f,h]=this._htraverse(e,!0);return f._nodes.set(h,t,o,r,f,c,i,a,s,u,l,d)}_pop(e,t=null){let r=this._nodes.index(e);if(r>=0){let o=this._nodes.pop(r);return this.backref&&this._onNodeDeleted(o,r,null,t),o}return null}pop(e,t=null,r=null){let o=this.popNode(e,r);return o?o.value:t}delItem(e,t=null,r=null){return this.pop(e,t,r)}popNode(e,t=null){let[r,o]=this._htraverse(e,!1,!0);if(!r||!o)return null;let i=r._nodes.get(o);if(!i)return null;try{return r._pop(o,t)}finally{i.parentBag===r&&r._nodes._dict[i.label]!==i&&(i.parentBag=null)}}clear(){let e=[...this._nodes];this._nodes.clear(),this.backref&&this._onNodeDeleted(e,-1);for(let t of e)t.parentBag=null}getNode(e,t=!0,r=!1,o=null){if(e==null||e==="")return this.parentNode;if(typeof e=="number")return this._nodes.get(e);typeof e=="string"&&(e=e.split("?",1)[0]);let[i,a]=this._htraverse(e,r,t);if(i instanceof n&&a){let s=i._nodes.get(a);if(s)return s;if(r)return i._nodes.set(a,o,">",null,i,null,!1,!0,"autocreate"),i._nodes.get(a)}return null}setBackref(e=null,t=null){let r=this._backref;if(this._backref=!0,this._parent=t,this._parentNode=e,!r){this._nodes._parentBag=this;for(let o of this)o.parentBag=this}}delParentRef(){this._parent=null,this._parentNode=null,this._backref=!1}clearBackref(){if(this._backref){this._backref=!1,this._parent=null,this._parentNode=null,this._nodes._parentBag=null;for(let e of this){e.parentBag=null;let t=e.getValue(!0);t instanceof n&&t.clearBackref()}}}_onNodeChanged(e,t,r,o=null,i=null,a=null,s=!1){for(let l of Object.values(this._updSubscribers))l({node:e,pathlist:t,oldvalue:o,attrs_diff:i,evt:r,reason:a,fired:s});this._parent&&this._parentNode&&this._parent._onNodeChanged(e,[this._parentNode.label,...t],r,o,i,a,s)}_onNodeInserted(e,t,r=null,o=null,i=!1){let a=e.parentBag,s=e.getValue(!0);a!==null&&a.backref&&s instanceof n&&s.setBackref(e,a),r===null&&(r=[]);for(let l of Object.values(this._insSubscribers))l({node:e,pathlist:r,ind:t,evt:"ins",reason:o,fired:i});this._parent&&this._parentNode&&this._parent._onNodeInserted(e,t,[this._parentNode.label,...r],o,i)}_onNodeDeleted(e,t,r=null,o=null){for(let i of Object.values(this._delSubscribers))i({node:e,pathlist:r,ind:t,evt:"del",reason:o});this._parent&&this._parentNode&&(r===null&&(r=[]),this._parent._onNodeDeleted(e,t,[this._parentNode.label,...r],o))}_subscribe(e,t,r){r!=null&&(t[e]=r)}subscribe(e,t={}){if(Object.hasOwn(t,"timer")||Object.hasOwn(t,"interval"))throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");let{update:r=null,insert:o=null,delete:i=null,any:a=null}=t;this.backref||this.setBackref(),this._subscribe(e,this._updSubscribers,r||a),this._subscribe(e,this._insSubscribers,o||a),this._subscribe(e,this._delSubscribers,i||a)}unsubscribe(e,t={}){if(Object.hasOwn(t,"timer")||Object.hasOwn(t,"interval"))throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");let{update:r=!1,insert:o=!1,delete:i=!1,any:a=!1}=t;(r||a)&&delete this._updSubscribers[e],(o||a)&&delete this._insSubscribers[e],(i||a)&&delete this._delSubscribers[e]}[Symbol.iterator](){return this._nodes[Symbol.iterator]()}keys(){return this._nodes.keys()}values(){return this._nodes.values()}items(){return[...this._nodes].map(e=>({key:e.label,value:e.getValue()}))}get nodes(){return this.getNodes()}node(e){return this._nodes.get(e)}setAttr(e=null,t=null,r=!0){let o=n.prototype.getNode.call(this,e,!0,!0);o&&o.setAttr(t,!0,!0,r)}getAttr(e=null,t=null,r=null){let o=this.getNode(e);return o?o.getAttr(t,r):r}delAttr(e=null,...t){let r=this.getNode(e);r&&r.delAttr(...t)}getInheritedAttributes(){return this._parentNode?this._parentNode.getInheritedAttributes():{}}getNodes(e=null){return e?[...this._nodes].filter(t=>e(t)):[...this._nodes]}getNodeByValue(e,t){for(let r of this._nodes){let o=r.value;if(o instanceof n){if(o.getItem(e)===t)return r}else if(o&&o.get&&o.get(e)===t)return r}return null}getNodeByAttr(e,t,r=!1,o=!1){let i=t===void 0,a=r&&typeof t=="string"?t.toLowerCase():t,s=l=>{let u=[];for(let c of l._nodes){if(e in c.attr){let d=r&&typeof c.attr[e]=="string"?c.attr[e].toLowerCase():c.attr[e];if(i||d==a)return c}if(c._value instanceof n)if(o){let d=s(c._value);if(d)return d}else u.push(c._value)}for(let c of u){let d=s(c);if(d)return d}return null};return s(this)}isEmpty(e=!1,t=!1){if(this._nodes.length===0)return!0;for(let r of this._nodes){if(r._resolver!==null)return!1;let o=r.getValue(!0);if(o!=null&&!(e&&o===0)&&!(t&&o===""))return!1}return!0}query(e=null,t=null,r=!1,o=!1,i=!0,a=!0,s=null,l=!0){e||(e="#k,#v,#a");let u=this,c;if(typeof e=="string"){if(e.includes(":")){let[h,p]=e.split(":");u=this.getItem(h),e=p}c=e.split(",").map(h=>h.trim())}else c=e;let d=(h,p,m,b,w)=>{if(p==="#k")return h.label;if(p==="#p")return m;if(p==="#n")return h;if(typeof p=="function")return p(h);if(p==="#v"){let _=w();return b&&_ instanceof n?null:_}else if(p.startsWith("#v.")){let _=p.split(".").slice(1).join("."),y=w();return y&&y.getItem?y.getItem(_):null}else{if(p==="#__v")return h.getValue(!0);if(p.startsWith("#a")){let _=p.includes(".")?p.split(".").slice(1).join("."):null;return h.getAttr(_)}else{let _=w();return _&&_.getItem?_.getItem(p):null}}};function*f(){let h=0;function*p(m,b){for(let w of m._nodes){let _=b?`${b}.${w.label}`:w.label,y=!1,x,S=()=>(y||(x=w.getValue(l),y=!0),x);if((i&&a||(S()instanceof n?a:i))&&(t===null||t(w))&&(yield c.length===1?d(w,c[0],_,o,S):c.map(N=>d(w,N,_,o,S)),h++,s!==null&&h>=s))return;if(o){let N=S();if(N instanceof n&&(yield*p(N,_),s!==null&&h>=s))return}}}yield*p(u,"")}return r?f():[...f()]}getLeaves(){let e=[],t=(r,o)=>{for(let i of r._nodes){let a=o?`${o}.${i.label}`:i.label,s=i.getValue(!1);s instanceof n?t(s,a):e.push([a,s])}};return t(this,""),e}digest(e=null,t=null,r=!1){typeof t=="boolean"&&(console.warn("Bag.digest(what, asColumns) is deprecated; use digest(what, null, asColumns)."),r=t,t=null);let o=this.query(e,t,!1,!1,!0,!0,null,!1);if(r){if(!o||o.length===0)return(typeof e=="string"?e:"#k,#v,#a").split(",").map(l=>l.trim()).map(()=>[]);let i=[...o];if(i.length&&Array.isArray(i[0])){let a=i[0].length,s=[];for(let l=0;l<a;l++)s.push(i.map(u=>u[l]));return s}return[i]}return[...o]}columns(e,t=!1){typeof e=="string"&&(e=e.split(","));let r=t?"#a.":"",o=e.map(i=>`${r}${i}`).join(",");return this.digest(o,null,!0)}sum(e="#v",t=!1,r=null){if(t!=null&&typeof t!="boolean")throw new TypeError("sum strict must be a boolean; pass condition as the third argument");if(r!=null&&typeof r!="function")throw new TypeError("sum condition must be callable; deep is no longer supported");let o=i=>{let a=0,s=!1;for(let l of this.query(i,r)){if(l==null||l===""){s=!0;continue}if(typeof l!="number"&&typeof l!="boolean"){if(t)throw new TypeError(`sum encountered non-numeric value: ${typeof l}`);continue}a+=l}return t&&s?null:a};return e.includes(",")?e.split(",").map(i=>o(i.trim())):o(e)}sort(e="#k:a"){let t=(o,i)=>o==null?[-1,""]:i&&typeof o=="string"?[0,o.toLowerCase()]:[0,o],r=(o,i)=>o[0]!==i[0]?o[0]-i[0]:o[1]<i[1]?-1:o[1]>i[1]?1:0;if(typeof e=="function")this._nodes._list.sort((o,i)=>{let a=e(o),s=e(i);return a<s?-1:a>s?1:0});else{let o=e.split(",");o.reverse();for(let i of o){let a,s;i.includes(":")?[a,s]=i.split(":",2):(a=i,s="a"),a=a.trim(),s=s.trim();let l=s==="d"||s==="D",u=s==="a"||s==="d",c;if(a.toLowerCase()==="#k")c=d=>t(d.label,u);else if(a.toLowerCase()==="#v")c=d=>t(d.value,u);else if(a.toLowerCase().startsWith("#a.")){let d=a.slice(3);c=f=>t(f.getAttr(d),u)}else c=d=>{let f=d.value,h=f instanceof n?f.getItem(a):f?f[a]:null;return t(h,u)};this._nodes._list.sort((d,f)=>{let h=r(c(d),c(f));return l?-h:h})}}return this}equalTo(e){return e instanceof n?this._nodes.isEqual(e._nodes):!1}has(e){if(typeof e=="string"){let t=null;e.includes("?")&&([e,t]=e.split("?",2));let r=this.getNode(e);return r===null?!1:t===null?!0:t.split("&").every(o=>o in r.attr)}else if(e&&e.label!==void 0)return[...this._nodes].includes(e);return!1}getResolver(e){let t=this.getNode(e);return t?t.resolver:null}setResolver(e,t){let r=this.getNode(e);r||(this.setItem(e,null),r=this.getNode(e)),r.resolver=t}setCallbackItem(e,t,r={}){let o=new Er({callback:t,...r});this.setResolver(e,o)}move(e,t,r=!0){this._nodes.move(e,t,r)}asDict(e=!1,t=!1,r=!1,o=!1){let i={};for(let a of this._nodes){let s=a.value;if(o&&s==null)continue;let l=a.label;e&&(l=String(l)),t&&(l=l.toLowerCase()),r&&s instanceof n&&(s=n.prototype.asDict.call(s,e,t,r,o)),Object.defineProperty(i,l,{value:s,enumerable:!0,writable:!0,configurable:!0})}return i}setdefault(e,t=null){let r=this.getNode(e);return r?r.value:(this.setItem(e,t),t)}deepcopy(e=!1){let t=this.createChildBag();for(let r of this._nodes){let o=r.getValue(!e);o instanceof n&&(o=o.deepcopy(e));let i=new t.nodeClass(t,r.label,o);i.setAttr({...r.attr},!1,!1,!1),i.nodeTag=r.nodeTag,i.xmlTag=r.xmlTag,t._nodes._list.push(i),t._nodes._dict[i.label]=i}return t}update(e,t=null,r=null,o=!1){if(!(e instanceof n)){for(let i in e){let a=e[i];(!o||a!==null||!this._nodes.has(i))&&this.setItem(i,a,null,">",!1,!1,r,!1,r!==!1)}return}for(let i of[...e]){let a=i.label,s=t==="static"?i.resolver:null,l=s?null:i.getValue(),u=i.attr.__replace;delete i.attr.__replace;let c=this._nodes.get(a);if(c)if(c.setAttr(i.attr,r===null?!0:r,!0,!1),i.nodeTag!=null&&(c.nodeTag=i.nodeTag),i.xmlTag!=null&&(c.xmlTag=i.xmlTag),s)c.resolver=s,c.setValue(null,r===null?!0:r,null,null,!1,r);else{i.resolver&&(c.resolver=null);let d=c.getValue();l instanceof n&&d instanceof n&&!u?d.update(l,t,r,o):(!o||l!==null)&&c.setValue(l,r===null?!0:r,null,null,!1,r)}else{let d=this.setItem(a,s||l,i.attr,">",!1,!1,r,!1,r!==!1);d.nodeTag=i.nodeTag,d.xmlTag=i.xmlTag}}}_fillFromBag(e){this.clear();for(let t of e){let r=new this.nodeClass(this,t.label);r.replace(t),r.nodeTag=t.nodeTag,r.xmlTag=t.xmlTag,this._nodes._list.push(r),this._nodes._dict[r.label]=r}}_appendLiteral(e,t,r=null,o=null,i=null){if(typeof e!="string")throw new TypeError("Bag labels must be strings");let a=new this.nodeClass(this,e,null,r,o,i,null,!1);return t instanceof fe?a.resolver=t:a._value=t,this._nodes._dict[e]=a,this._nodes._list.push(a),a}fillFrom(e=null,t={}){let r=Uu(t);if(e!=null&&!to(e)&&!Array.isArray(e))throw new TypeError("Bag source must be a dictionary, array or null");let o=this.createChildBag(),i=new Set,a=(s,l,u)=>{if(i.has(l))throw new TypeError(`Cyclic Bag source at ${u}`);i.add(l);try{let c=Array.isArray(l)?String(l.length).length+1:0,d=Array.isArray(l)?Array.from(l,(f,h)=>[`r_${String(h).padStart(c,"0")}`,f]):Object.entries(l);if(!Array.isArray(l)&&Object.getOwnPropertySymbols(l).some(f=>Object.prototype.propertyIsEnumerable.call(l,f)))throw new TypeError(`Bag labels must be strings at ${u}`);for(let[f,h]of d){let p=h;r&&(to(p)||Array.isArray(p))&&(p=this.createChildBag(),a(p,h,`${u}[${JSON.stringify(f)}]`)),s._appendLiteral(f,p)}}finally{i.delete(l)}};return e!=null&&a(o,e,"$"),this._replacePrepared(o)}_loadSource(e,t={}){return this.fillFrom(e,t)}replace(e){if(!(e instanceof n))throw new TypeError("Bag.replace expects a Bag");if(e===this)return this;let t=this.createChildBag();return t._fillFromBag(e),this._replacePrepared(t)}_replacePrepared(e){for(let r of this._nodes){r.parentBag=null;let o=r.getValue(!0);o instanceof n&&o.clearBackref()}let t=this._nodes;this._nodes=e._nodes,e._nodes=t,this._nodes._parentBag=this.backref?this:null,e._nodes._parentBag=null;for(let r of this._nodes)r.parentBag=this;for(let r of e._nodes)r._parentBag=e;return this.backref&&this.parent&&this.parentNode&&this.parent._onNodeChanged(this.parentNode,[this.parentNode.label],"upd_value",e),this}forEach(e,{static:t=!0,deep:r=!1,kwargs:o={}}={}){if(typeof e!="function")throw new TypeError("forEach requires a callback");let i=(a,s)=>{for(let l=0;l<a._nodes.length;l++){let u=a._nodes._list[l],c={...s};"_pathlist"in s&&(c._pathlist=[...s._pathlist,u.label]),"_indexlist"in s&&(c._indexlist=[...s._indexlist,l]);let d=e(u,c,l);if(d)return d;if(d==null&&r){let f=u.getValue(t);if(f instanceof n){let h=i(f,c);if(h)return h}}}return null};return i(this,o)}*traverse(){for(let e of this._nodes){yield e;let t=e.getValue(!0);t instanceof n&&(yield*t.traverse())}}*_iterNodesWithPaths(e=!0,t=""){for(let r of this._nodes){let o=t?`${t}.${r.label}`:r.label;yield[o,r];let i=r.getValue(e);i instanceof n&&(yield*i._iterNodesWithPaths(e,o))}}*_nodeFlattener(e=null){let t=e!==null,r=t?Object.create(null):null,o=0,i=new Map([["[]",this.constructor]]);for(let[a,s]of qh(this)){let l=a.slice(0,-1),u=JSON.stringify(a),c=JSON.stringify(l),d=s.getValue(!0),f,h=null;if(s.resolver)f=ui(s.resolver);else if(d instanceof n){let b=d.constructor,w=b.tytxSuffix;i.set(u,b),h=qu(b,eo(i.get(c),w)),f=`::${w}`}else d===null?f="::NN":f=xr(d);if(s.attr&&Object.hasOwn(s.attr,kt))throw new Te(`node '${a}': the attribute '${kt}' is reserved for the Bag class name`);let p=ts(xr(s.attr));h!==null&&(p[kt]=h);let m=s.nodeTag;t?(yield[l.length?r[c]:null,s.label,m,f,p],d instanceof n&&(r[u]=o,e[o]=a,o++)):yield[l,s.label,m,f,p]}}toTytx(e="json",t=!1){let r=this._toTytxPayload(t),o=this.constructor.tytxSuffix;if(e==="json")return`${r}::${o}`;if(e==="msgpack")return Ta(new vt(4,new TextEncoder().encode(`${o}:${r}`)));throw new TypeError(`Unsupported transport: ${e}`)}_toTytxPayload(e=!1){let t;if(e){let i={};t={rows:[...this._nodeFlattener(i)],paths:i}}else t={rows:[...this._nodeFlattener(null)]};let r=this.constructor,o=qu(r,eo(null,r.tytxSuffix));return o!==null&&(t[kt]=o),t.rows=t.rows.map(([i,a,s,l,u])=>[xr(i),xr(a),xr(s),l,u]),t.paths&&(t.paths=xr(t.paths)),L(t)}static fromTytx(e,t="json",r={}){if(to(t)&&(r=t,t="json"),Uu(r),typeof e!="string"&&!(e instanceof Uint8Array))throw new TypeError("fromTytx requires serialized text or bytes");if(t!=="json"&&t!=="msgpack")throw new TypeError(`Unsupported transport: ${t}`);t==="json"&&e instanceof Uint8Array&&(e=new TextDecoder().decode(e));let o=F(e,t==="json"?null:t);if(o instanceof n)return o;if(!to(o)&&!Array.isArray(o))throw new TypeError("fromTytx requires a dictionary, array or typed Bag root");return new this(o,r)}static _fromTytxPayload(e){let t=this.tytxSuffix;if(e==="")return new(eo(null,t));let r=F(e);if(!r||!Array.isArray(r.rows))throw new Te("Invalid TYTX Bag: expected rows");let o=r.paths,i=o!=null,a=Object.hasOwn(r,kt)?ju(t,r[kt]):eo(null,t),s=new a,l=new Map([["[]",s]]);for(let u of r.rows){if(!Array.isArray(u)||u.length!==5)throw new Te("Invalid TYTX Bag row");let[c,d,f,h,p]=u,m=c??"";if(i){if(c!==null&&!Object.hasOwn(o,c))throw new Te(`Unknown TYTX parent reference: ${c}`);m=c===null?"":o[c]}if(typeof m=="string"&&(m=m?m.split("."):[]),!Array.isArray(m))throw new Te("Invalid TYTX parent path");let b=JSON.stringify(m);if(!l.has(b))throw new Te(`Missing or undecodable TYTX parent branch: ${m}`);let w=l.get(b),_=JSON.stringify([...m,d]),y=h,x=es(y),S=Fu(p),k=Object.hasOwn(S,kt)?S[kt]:null;if(delete S[kt],y instanceof n){let O=y.constructor.tytxSuffix,$=k!==null?ju(O,k):eo(w.constructor,O);y=new $,l.set(_,y)}else if(k!==null)throw new Te(`node '${_}': the attribute '${kt}' is reserved for the Bag class name of a branch`);let N=w._appendLiteral(d,x?null:y,S,x);N.nodeTag=f??null}return s}toXml(e={}){let{pretty:t=!1,encoding:r="UTF-8",docHeader:o=null,selfClosedTags:i=null}=e,a=this._bagToXml(i,t);return o===!0?a=`<?xml version='1.0' encoding='${r}'?>
|
|
30
|
+
`,Io=class n{static install({document:e,root:t}){return fa.has(t)||fa.set(t,new n(e,t)),fa.get(t)}constructor(e,t){this.document=e,this.root=t,this.releases=[],this.closed=!1,t.setAttribute("data-gramlot-viewport",e.defaultView.parent===e.defaultView?"root":"child");let r=e.querySelector('meta[name="viewport"]');r||(r=e.createElement("meta"),r.name="viewport",r.content="width=device-width,initial-scale=1",e.head.append(r));let o=r.content.split(",").map(i=>i.trim()).filter(i=>!i.startsWith("viewport-fit="));r.content=[...o,"viewport-fit=cover"].join(","),this.style=e.createElement("style"),this.style.textContent=Mg,e.head.append(this.style)}subscribeAppearance(e){let t=this.document.defaultView,r=t.matchMedia("(prefers-color-scheme: dark)"),o=()=>{let s=t.getComputedStyle(this.document.documentElement).colorScheme;e({dark:s==="dark"||!["light","dark"].includes(s)&&r.matches})},i=new t.MutationObserver(o);i.observe(this.document.documentElement,{attributes:!0,attributeFilter:["data-theme","style","class"]}),r.addEventListener("change",o),o();let a=()=>{i.disconnect(),r.removeEventListener("change",o)};return this.releases.push(a),a}dispose(){if(!this.closed){this.closed=!0;for(let e of this.releases)e();this.style.remove(),this.root.removeAttribute("data-gramlot-viewport"),fa.delete(this.root)}}};var Oo=class{#e=new Map;registerGroup(e,t={}){if(typeof e!="string"||!e||e.includes(":"))throw new TypeError("Extension command namespace must be nonempty and unqualified");if(this.#e.has(e))throw new Error(`Duplicate command namespace: ${e}`);if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(o=>!["author","description"].includes(o))||Object.values(t).some(o=>typeof o!="string"))throw new TypeError(`Invalid command group metadata: ${e}`);let r=new Map;return this.#e.set(e,{metadata:{...t},commands:r}),Object.freeze({register(o,i){if(typeof o!="string"||!o||o.includes(":"))throw new TypeError("Invalid command name");if(r.has(o))throw new Error(`Duplicate command: ${e}:${o}`);if(!i||typeof i!="object"||Array.isArray(i)||!Object.hasOwn(i,"label")||!Object.hasOwn(i,"publish")||Object.keys(i).some(a=>!["label","publish","icon","iconSrc","tooltip"].includes(a))||Object.values(i).some(a=>typeof a!="string"))throw new TypeError(`Invalid command definition: ${e}:${o}`);r.set(o,Object.freeze({...i}))}})}get(e){let t=e.indexOf(":");return this.#e.get(e.slice(0,t))?.commands.get(e.slice(t+1))}toDocument(){return{document_format:{name:"gramlot_commands",version:"1.0"},groups:Object.fromEntries([...this.#e].map(([e,{metadata:t,commands:r}])=>[e,{...t,commands:Object.fromEntries(r)}]))}}};var Ro=class{constructor(e,{fetcher:t=globalThis.fetch?.bind(globalThis),closeUrl:r="/gramlot/close",navigator:o=globalThis.navigator,XMLHttpRequest:i=globalThis.XMLHttpRequest}={}){this.rpcUrl=e,this.fetcher=t,this.closeUrl=r,this.navigator=o,this.XMLHttpRequest=i}get supportsCallSync(){return!0}async call(e,t){let r=await this.fetcher(this.rpcUrl,{method:"POST",credentials:"same-origin",signal:t,headers:{"Content-Type":"application/json"},body:e});if(r.status!==200)throw new Error(`rpc failed: HTTP ${r.status}`);return r.text()}callSync(e){let t=new this.XMLHttpRequest;if(t.open("POST",this.rpcUrl,!1),t.setRequestHeader("Content-Type","application/json"),t.send(e),t.status!==200)throw new Error(`rpc failed: HTTP ${t.status}`);return t.responseText}close(e){if(typeof this.closeUrl!="string"||!this.closeUrl.trim())throw new TypeError("HttpTransport.closeUrl must be nonempty text");if(typeof this.navigator?.sendBeacon!="function")throw new TypeError("HttpTransport requires navigator.sendBeacon");let t=new Blob([JSON.stringify({pageId:e})],{type:"application/json"});try{this.navigator.sendBeacon(this.closeUrl,t)}catch(r){if(r.name==="TypeError")throw r}}dispose(){}};var ha=class{constructor(e,t){this.channel=e,this.closeTransport=t}get supportsCallSync(){return!1}call(e,t){return this.channel.call(e,t)}close(e,t){this.closeTransport.close(e,t)}dispose(){this.closeTransport.dispose()}};var ur=class{createTransport({rpcUrl:e,closeUrl:t,document:r,channel:o=null}){let i=r.defaultView,a=new Ro(e,{closeUrl:t,navigator:i.navigator,XMLHttpRequest:i.XMLHttpRequest});return o===null?a:new ha(o,a)}};var Nn=9e15,hr=1e9,Vl="0123456789abcdef",ga="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",ba="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",zl={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Nn,maxE:Nn,crypto:!1},Ld,Gt,G=!0,_a="[DecimalError] ",fr=_a+"Invalid argument: ",Fd=_a+"Precision limit exceeded",jd=_a+"crypto unavailable",qd="[object Decimal]",Ve=Math.floor,Ce=Math.pow,Pg=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Lg=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Fg=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Ud=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,yt=1e7,q=7,jg=9007199254740991,qg=ga.length-1,Hl=ba.length-1,S={toStringTag:qd};S.absoluteValue=S.abs=function(){var n=new this.constructor(this);return n.s<0&&(n.s=1),P(n)};S.ceil=function(){return P(new this.constructor(this),this.e+1,2)};S.clampedTo=S.clamp=function(n,e){var t,r=this,o=r.constructor;if(n=new o(n),e=new o(e),!n.s||!e.s)return new o(NaN);if(n.gt(e))throw Error(fr+e);return t=r.cmp(n),t<0?n:r.cmp(e)>0?e:new o(r)};S.comparedTo=S.cmp=function(n){var e,t,r,o,i=this,a=i.d,s=(n=new i.constructor(n)).d,l=i.s,u=n.s;if(!a||!s)return!l||!u?NaN:l!==u?l:a===s?0:!a^l<0?1:-1;if(!a[0]||!s[0])return a[0]?l:s[0]?-u:0;if(l!==u)return l;if(i.e!==n.e)return i.e>n.e^l<0?1:-1;for(r=a.length,o=s.length,e=0,t=r<o?r:o;e<t;++e)if(a[e]!==s[e])return a[e]>s[e]^l<0?1:-1;return r===o?0:r>o^l<0?1:-1};S.cosine=S.cos=function(){var n,e,t=this,r=t.constructor;return t.d?t.d[0]?(n=r.precision,e=r.rounding,r.precision=n+Math.max(t.e,t.sd())+q,r.rounding=1,t=Ug(r,Wd(r,t)),r.precision=n,r.rounding=e,P(Gt==2||Gt==3?t.neg():t,n,e,!0)):new r(1):new r(NaN)};S.cubeRoot=S.cbrt=function(){var n,e,t,r,o,i,a,s,l,u,c=this,d=c.constructor;if(!c.isFinite()||c.isZero())return new d(c);for(G=!1,i=c.s*Ce(c.s*c,1/3),!i||Math.abs(i)==1/0?(t=$e(c.d),n=c.e,(i=(n-t.length+1)%3)&&(t+=i==1||i==-2?"0":"00"),i=Ce(t,1/3),n=Ve((n+1)/3)-(n%3==(n<0?-1:2)),i==1/0?t="5e"+n:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+n),r=new d(t),r.s=c.s):r=new d(i.toString()),a=(n=d.precision)+3;;)if(s=r,l=s.times(s).times(s),u=l.plus(c),r=pe(u.plus(c).times(s),u.plus(l),a+2,1),$e(s.d).slice(0,a)===(t=$e(r.d)).slice(0,a))if(t=t.slice(a-3,a+1),t=="9999"||!o&&t=="4999"){if(!o&&(P(s,n+1,0),s.times(s).times(s).eq(c))){r=s;break}a+=4,o=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(P(r,n+1,1),e=!r.times(r).times(r).eq(c));break}return G=!0,P(r,n,d.rounding,e)};S.decimalPlaces=S.dp=function(){var n,e=this.d,t=NaN;if(e){if(n=e.length-1,t=(n-Ve(this.e/q))*q,n=e[n],n)for(;n%10==0;n/=10)t--;t<0&&(t=0)}return t};S.dividedBy=S.div=function(n){return pe(this,new this.constructor(n))};S.dividedToIntegerBy=S.divToInt=function(n){var e=this,t=e.constructor;return P(pe(e,new t(n),0,1,1),t.precision,t.rounding)};S.equals=S.eq=function(n){return this.cmp(n)===0};S.floor=function(){return P(new this.constructor(this),this.e+1,3)};S.greaterThan=S.gt=function(n){return this.cmp(n)>0};S.greaterThanOrEqualTo=S.gte=function(n){var e=this.cmp(n);return e==1||e===0};S.hyperbolicCosine=S.cosh=function(){var n,e,t,r,o,i=this,a=i.constructor,s=new a(1);if(!i.isFinite())return new a(i.s?1/0:NaN);if(i.isZero())return s;t=a.precision,r=a.rounding,a.precision=t+Math.max(i.e,i.sd())+4,a.rounding=1,o=i.d.length,o<32?(n=Math.ceil(o/3),e=(1/va(4,n)).toString()):(n=16,e="2.3283064365386962890625e-10"),i=In(a,1,i.times(e),new a(1),!0);for(var l,u=n,c=new a(8);u--;)l=i.times(i),i=s.minus(l.times(c.minus(l.times(c))));return P(i,a.precision=t,a.rounding=r,!0)};S.hyperbolicSine=S.sinh=function(){var n,e,t,r,o=this,i=o.constructor;if(!o.isFinite()||o.isZero())return new i(o);if(e=i.precision,t=i.rounding,i.precision=e+Math.max(o.e,o.sd())+4,i.rounding=1,r=o.d.length,r<3)o=In(i,2,o,o,!0);else{n=1.4*Math.sqrt(r),n=n>16?16:n|0,o=o.times(1/va(5,n)),o=In(i,2,o,o,!0);for(var a,s=new i(5),l=new i(16),u=new i(20);n--;)a=o.times(o),o=o.times(s.plus(a.times(l.times(a).plus(u))))}return i.precision=e,i.rounding=t,P(o,e,t,!0)};S.hyperbolicTangent=S.tanh=function(){var n,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(n=r.precision,e=r.rounding,r.precision=n+7,r.rounding=1,pe(t.sinh(),t.cosh(),r.precision=n,r.rounding=e)):new r(t.s)};S.inverseCosine=S.acos=function(){var n=this,e=n.constructor,t=n.abs().cmp(1),r=e.precision,o=e.rounding;return t!==-1?t===0?n.isNeg()?It(e,r,o):new e(0):new e(NaN):n.isZero()?It(e,r+4,o).times(.5):(e.precision=r+6,e.rounding=1,n=new e(1).minus(n).div(n.plus(1)).sqrt().atan(),e.precision=r,e.rounding=o,n.times(2))};S.inverseHyperbolicCosine=S.acosh=function(){var n,e,t=this,r=t.constructor;return t.lte(1)?new r(t.eq(1)?0:NaN):t.isFinite()?(n=r.precision,e=r.rounding,r.precision=n+Math.max(Math.abs(t.e),t.sd())+4,r.rounding=1,G=!1,t=t.times(t).minus(1).sqrt().plus(t),G=!0,r.precision=n,r.rounding=e,t.ln()):new r(t)};S.inverseHyperbolicSine=S.asinh=function(){var n,e,t=this,r=t.constructor;return!t.isFinite()||t.isZero()?new r(t):(n=r.precision,e=r.rounding,r.precision=n+2*Math.max(Math.abs(t.e),t.sd())+6,r.rounding=1,G=!1,t=t.times(t).plus(1).sqrt().plus(t),G=!0,r.precision=n,r.rounding=e,t.ln())};S.inverseHyperbolicTangent=S.atanh=function(){var n,e,t,r,o=this,i=o.constructor;return o.isFinite()?o.e>=0?new i(o.abs().eq(1)?o.s/0:o.isZero()?o:NaN):(n=i.precision,e=i.rounding,r=o.sd(),Math.max(r,n)<2*-o.e-1?P(new i(o),n,e,!0):(i.precision=t=r-o.e,o=pe(o.plus(1),new i(1).minus(o),t+n,1),i.precision=n+4,i.rounding=1,o=o.ln(),i.precision=n,i.rounding=e,o.times(.5))):new i(NaN)};S.inverseSine=S.asin=function(){var n,e,t,r,o=this,i=o.constructor;return o.isZero()?new i(o):(e=o.abs().cmp(1),t=i.precision,r=i.rounding,e!==-1?e===0?(n=It(i,t+4,r).times(.5),n.s=o.s,n):new i(NaN):(i.precision=t+6,i.rounding=1,o=o.div(new i(1).minus(o.times(o)).sqrt().plus(1)).atan(),i.precision=t,i.rounding=r,o.times(2)))};S.inverseTangent=S.atan=function(){var n,e,t,r,o,i,a,s,l,u=this,c=u.constructor,d=c.precision,f=c.rounding;if(u.isFinite()){if(u.isZero())return new c(u);if(u.abs().eq(1)&&d+4<=Hl)return a=It(c,d+4,f).times(.25),a.s=u.s,a}else{if(!u.s)return new c(NaN);if(d+4<=Hl)return a=It(c,d+4,f).times(.5),a.s=u.s,a}for(c.precision=s=d+10,c.rounding=1,t=Math.min(28,s/q+2|0),n=t;n;--n)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(G=!1,e=Math.ceil(s/q),r=1,l=u.times(u),a=new c(u),o=u;n!==-1;)if(o=o.times(l),i=a.minus(o.div(r+=2)),o=o.times(l),a=i.plus(o.div(r+=2)),a.d[e]!==void 0)for(n=e;a.d[n]===i.d[n]&&n--;);return t&&(a=a.times(2<<t-1)),G=!0,P(a,c.precision=d,c.rounding=f,!0)};S.isFinite=function(){return!!this.d};S.isInteger=S.isInt=function(){return!!this.d&&Ve(this.e/q)>this.d.length-2};S.isNaN=function(){return!this.s};S.isNegative=S.isNeg=function(){return this.s<0};S.isPositive=S.isPos=function(){return this.s>0};S.isZero=function(){return!!this.d&&this.d[0]===0};S.lessThan=S.lt=function(n){return this.cmp(n)<0};S.lessThanOrEqualTo=S.lte=function(n){return this.cmp(n)<1};S.logarithm=S.log=function(n){var e,t,r,o,i,a,s,l,u=this,c=u.constructor,d=c.precision,f=c.rounding,h=5;if(n==null)n=new c(10),e=!0;else{if(n=new c(n),t=n.d,n.s<0||!t||!t[0]||n.eq(1))return new c(NaN);e=n.eq(10)}if(t=u.d,u.s<0||!t||!t[0]||u.eq(1))return new c(t&&!t[0]?-1/0:u.s!=1?NaN:t?0:1/0);if(e)if(t.length>1)i=!0;else{for(o=t[0];o%10===0;)o/=10;i=o!==1}if(G=!1,s=d+h,a=dr(u,s),r=e?wa(c,s+10):dr(n,s),l=pe(a,r,s,1),Bo(l.d,o=d,f))do if(s+=10,a=dr(u,s),r=e?wa(c,s+10):dr(n,s),l=pe(a,r,s,1),!i){+$e(l.d).slice(o+1,o+15)+1==1e14&&(l=P(l,d+1,0));break}while(Bo(l.d,o+=10,f));return G=!0,P(l,d,f)};S.minus=S.sub=function(n){var e,t,r,o,i,a,s,l,u,c,d,f,h=this,p=h.constructor;if(n=new p(n),!h.d||!n.d)return!h.s||!n.s?n=new p(NaN):h.d?n.s=-n.s:n=new p(n.d||h.s!==n.s?h:NaN),n;if(h.s!=n.s)return n.s=-n.s,h.plus(n);if(u=h.d,f=n.d,s=p.precision,l=p.rounding,!u[0]||!f[0]){if(f[0])n.s=-n.s;else if(u[0])n=new p(h);else return new p(l===3?-0:0);return G?P(n,s,l):n}if(t=Ve(n.e/q),c=Ve(h.e/q),u=u.slice(),i=c-t,i){for(d=i<0,d?(e=u,i=-i,a=f.length):(e=f,t=c,a=u.length),r=Math.max(Math.ceil(s/q),a)+2,i>r&&(i=r,e.length=1),e.reverse(),r=i;r--;)e.push(0);e.reverse()}else{for(r=u.length,a=f.length,d=r<a,d&&(a=r),r=0;r<a;r++)if(u[r]!=f[r]){d=u[r]<f[r];break}i=0}for(d&&(e=u,u=f,f=e,n.s=-n.s),a=u.length,r=f.length-a;r>0;--r)u[a++]=0;for(r=f.length;r>i;){if(u[--r]<f[r]){for(o=r;o&&u[--o]===0;)u[o]=yt-1;--u[o],u[r]+=yt}u[r]-=f[r]}for(;u[--a]===0;)u.pop();for(;u[0]===0;u.shift())--t;return u[0]?(n.d=u,n.e=ya(u,t),G?P(n,s,l):n):new p(l===3?-0:0)};S.modulo=S.mod=function(n){var e,t=this,r=t.constructor;return n=new r(n),!t.d||!n.s||n.d&&!n.d[0]?new r(NaN):!n.d||t.d&&!t.d[0]?P(new r(t),r.precision,r.rounding):(G=!1,r.modulo==9?(e=pe(t,n.abs(),0,3,1),e.s*=n.s):e=pe(t,n,0,r.modulo,1),e=e.times(n),G=!0,t.minus(e))};S.naturalExponential=S.exp=function(){return Gl(this)};S.naturalLogarithm=S.ln=function(){return dr(this)};S.negated=S.neg=function(){var n=new this.constructor(this);return n.s=-n.s,P(n)};S.plus=S.add=function(n){var e,t,r,o,i,a,s,l,u,c,d=this,f=d.constructor;if(n=new f(n),!d.d||!n.d)return!d.s||!n.s?n=new f(NaN):d.d||(n=new f(n.d||d.s===n.s?d:NaN)),n;if(d.s!=n.s)return n.s=-n.s,d.minus(n);if(u=d.d,c=n.d,s=f.precision,l=f.rounding,!u[0]||!c[0])return c[0]||(n=new f(d)),G?P(n,s,l):n;if(i=Ve(d.e/q),r=Ve(n.e/q),u=u.slice(),o=i-r,o){for(o<0?(t=u,o=-o,a=c.length):(t=c,r=i,a=u.length),i=Math.ceil(s/q),a=i>a?i+1:a+1,o>a&&(o=a,t.length=1),t.reverse();o--;)t.push(0);t.reverse()}for(a=u.length,o=c.length,a-o<0&&(o=a,t=c,c=u,u=t),e=0;o;)e=(u[--o]=u[o]+c[o]+e)/yt|0,u[o]%=yt;for(e&&(u.unshift(e),++r),a=u.length;u[--a]==0;)u.pop();return n.d=u,n.e=ya(u,r),G?P(n,s,l):n};S.precision=S.sd=function(n){var e,t=this;if(n!==void 0&&n!==!!n&&n!==1&&n!==0)throw Error(fr+n);return t.d?(e=Vd(t.d),n&&t.e+1>e&&(e=t.e+1)):e=NaN,e};S.round=function(){var n=this,e=n.constructor;return P(new e(n),n.e+1,e.rounding)};S.sine=S.sin=function(){var n,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(n=r.precision,e=r.rounding,r.precision=n+Math.max(t.e,t.sd())+q,r.rounding=1,t=zg(r,Wd(r,t)),r.precision=n,r.rounding=e,P(Gt>2?t.neg():t,n,e,!0)):new r(NaN)};S.squareRoot=S.sqrt=function(){var n,e,t,r,o,i,a=this,s=a.d,l=a.e,u=a.s,c=a.constructor;if(u!==1||!s||!s[0])return new c(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);for(G=!1,u=Math.sqrt(+a),u==0||u==1/0?(e=$e(s),(e.length+l)%2==0&&(e+="0"),u=Math.sqrt(e),l=Ve((l+1)/2)-(l<0||l%2),u==1/0?e="5e"+l:(e=u.toExponential(),e=e.slice(0,e.indexOf("e")+1)+l),r=new c(e)):r=new c(u.toString()),t=(l=c.precision)+3;;)if(i=r,r=i.plus(pe(a,i,t+2,1)).times(.5),$e(i.d).slice(0,t)===(e=$e(r.d)).slice(0,t))if(e=e.slice(t-3,t+1),e=="9999"||!o&&e=="4999"){if(!o&&(P(i,l+1,0),i.times(i).eq(a))){r=i;break}t+=4,o=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(P(r,l+1,1),n=!r.times(r).eq(a));break}return G=!0,P(r,l,c.rounding,n)};S.tangent=S.tan=function(){var n,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(n=r.precision,e=r.rounding,r.precision=n+10,r.rounding=1,t=t.sin(),t.s=1,t=pe(t,new r(1).minus(t.times(t)).sqrt(),n+10,0),r.precision=n,r.rounding=e,P(Gt==2||Gt==4?t.neg():t,n,e,!0)):new r(NaN)};S.times=S.mul=function(n){var e,t,r,o,i,a,s,l,u,c=this,d=c.constructor,f=c.d,h=(n=new d(n)).d;if(n.s*=c.s,!f||!f[0]||!h||!h[0])return new d(!n.s||f&&!f[0]&&!h||h&&!h[0]&&!f?NaN:!f||!h?n.s/0:n.s*0);for(t=Ve(c.e/q)+Ve(n.e/q),l=f.length,u=h.length,l<u&&(i=f,f=h,h=i,a=l,l=u,u=a),i=[],a=l+u,r=a;r--;)i.push(0);for(r=u;--r>=0;){for(e=0,o=l+r;o>r;)s=i[o]+h[r]*f[o-r-1]+e,i[o--]=s%yt|0,e=s/yt|0;i[o]=(i[o]+e)%yt|0}for(;!i[--a];)i.pop();return e?++t:i.shift(),n.d=i,n.e=ya(i,t),G?P(n,d.precision,d.rounding):n};S.toBinary=function(n,e){return Wl(this,2,n,e)};S.toDecimalPlaces=S.toDP=function(n,e){var t=this,r=t.constructor;return t=new r(t),n===void 0?t:(rt(n,0,hr),e===void 0?e=r.rounding:rt(e,0,8),P(t,n+t.e+1,e))};S.toExponential=function(n,e){var t,r=this,o=r.constructor;return n===void 0?t=Ot(r,!0):(rt(n,0,hr),e===void 0?e=o.rounding:rt(e,0,8),r=P(new o(r),n+1,e),t=Ot(r,!0,n+1)),r.isNeg()&&!r.isZero()?"-"+t:t};S.toFixed=function(n,e){var t,r,o=this,i=o.constructor;return n===void 0?t=Ot(o):(rt(n,0,hr),e===void 0?e=i.rounding:rt(e,0,8),r=P(new i(o),n+o.e+1,e),t=Ot(r,!1,n+r.e+1)),o.isNeg()&&!o.isZero()?"-"+t:t};S.toFraction=function(n){var e,t,r,o,i,a,s,l,u,c,d,f,h=this,p=h.d,m=h.constructor;if(!p)return new m(h);if(u=t=new m(1),r=l=new m(0),e=new m(r),i=e.e=Vd(p)-h.e-1,a=i%q,e.d[0]=Ce(10,a<0?q+a:a),n==null)n=i>0?e:u;else{if(s=new m(n),!s.isInt()||s.lt(u))throw Error(fr+s);n=s.gt(e)?i>0?e:u:s}for(G=!1,s=new m($e(p)),c=m.precision,m.precision=i=p.length*q*2;d=pe(s,e,0,1,1),o=t.plus(d.times(r)),o.cmp(n)!=1;)t=r,r=o,o=u,u=l.plus(d.times(o)),l=o,o=e,e=s.minus(d.times(o)),s=o;return o=pe(n.minus(t),r,0,1,1),l=l.plus(o.times(u)),t=t.plus(o.times(r)),l.s=u.s=h.s,f=pe(u,r,i,1).minus(h).abs().cmp(pe(l,t,i,1).minus(h).abs())<1?[u,r]:[l,t],m.precision=c,G=!0,f};S.toHexadecimal=S.toHex=function(n,e){return Wl(this,16,n,e)};S.toNearest=function(n,e){var t=this,r=t.constructor;if(t=new r(t),n==null){if(!t.d)return t;n=new r(1),e=r.rounding}else{if(n=new r(n),e===void 0?e=r.rounding:rt(e,0,8),!t.d)return n.s?t:n;if(!n.d)return n.s&&(n.s=t.s),n}return n.d[0]?(G=!1,t=pe(t,n,0,e,1).times(n),G=!0,P(t)):(n.s=t.s,t=n),t};S.toNumber=function(){return+this};S.toOctal=function(n,e){return Wl(this,8,n,e)};S.toPower=S.pow=function(n){var e,t,r,o,i,a,s=this,l=s.constructor,u=+(n=new l(n));if(!s.d||!n.d||!s.d[0]||!n.d[0])return new l(Ce(+s,u));if(s=new l(s),s.eq(1))return s;if(r=l.precision,i=l.rounding,n.eq(1))return P(s,r,i);if(e=Ve(n.e/q),e>=n.d.length-1&&(t=u<0?-u:u)<=jg)return o=zd(l,s,t,r),n.s<0?new l(1).div(o):P(o,r,i);if(a=s.s,a<0){if(e<n.d.length-1)return new l(NaN);if((n.d[e]&1)==0&&(a=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=a,s}return t=Ce(+s,u),e=t==0||!isFinite(t)?Ve(u*(Math.log("0."+$e(s.d))/Math.LN10+s.e+1)):new l(t+"").e,e>l.maxE+1||e<l.minE-1?new l(e>0?a/0:0):(G=!1,l.rounding=s.s=1,t=Math.min(12,(e+"").length),o=Gl(n.times(dr(s,r+t)),r),o.d&&(o=P(o,r+5,1),Bo(o.d,r,i)&&(e=r+10,o=P(Gl(n.times(dr(s,e+t)),e),e+5,1),+$e(o.d).slice(r+1,r+15)+1==1e14&&(o=P(o,r+1,0)))),o.s=a,G=!0,l.rounding=i,P(o,r,i))};S.toPrecision=function(n,e){var t,r=this,o=r.constructor;return n===void 0?t=Ot(r,r.e<=o.toExpNeg||r.e>=o.toExpPos):(rt(n,1,hr),e===void 0?e=o.rounding:rt(e,0,8),r=P(new o(r),n,e),t=Ot(r,n<=r.e||r.e<=o.toExpNeg,n)),r.isNeg()&&!r.isZero()?"-"+t:t};S.toSignificantDigits=S.toSD=function(n,e){var t=this,r=t.constructor;return n===void 0?(n=r.precision,e=r.rounding):(rt(n,1,hr),e===void 0?e=r.rounding:rt(e,0,8)),P(new r(t),n,e)};S.toString=function(){var n=this,e=n.constructor,t=Ot(n,n.e<=e.toExpNeg||n.e>=e.toExpPos);return n.isNeg()&&!n.isZero()?"-"+t:t};S.truncated=S.trunc=function(){return P(new this.constructor(this),this.e+1,1)};S.valueOf=S.toJSON=function(){var n=this,e=n.constructor,t=Ot(n,n.e<=e.toExpNeg||n.e>=e.toExpPos);return n.isNeg()?"-"+t:t};function $e(n){var e,t,r,o=n.length-1,i="",a=n[0];if(o>0){for(i+=a,e=1;e<o;e++)r=n[e]+"",t=q-r.length,t&&(i+=cr(t)),i+=r;a=n[e],r=a+"",t=q-r.length,t&&(i+=cr(t))}else if(a===0)return"0";for(;a%10===0;)a/=10;return i+a}function rt(n,e,t){if(n!==~~n||n<e||n>t)throw Error(fr+n)}function Bo(n,e,t,r){var o,i,a,s;for(i=n[0];i>=10;i/=10)--e;return--e<0?(e+=q,o=0):(o=Math.ceil((e+1)/q),e%=q),i=Ce(10,q-e),s=n[o]%i|0,r==null?e<3?(e==0?s=s/100|0:e==1&&(s=s/10|0),a=t<4&&s==99999||t>3&&s==49999||s==5e4||s==0):a=(t<4&&s+1==i||t>3&&s+1==i/2)&&(n[o+1]/i/100|0)==Ce(10,e-2)-1||(s==i/2||s==0)&&(n[o+1]/i/100|0)==0:e<4?(e==0?s=s/1e3|0:e==1?s=s/100|0:e==2&&(s=s/10|0),a=(r||t<4)&&s==9999||!r&&t>3&&s==4999):a=((r||t<4)&&s+1==i||!r&&t>3&&s+1==i/2)&&(n[o+1]/i/1e3|0)==Ce(10,e-3)-1,a}function pa(n,e,t){for(var r,o=[0],i,a=0,s=n.length;a<s;){for(i=o.length;i--;)o[i]*=e;for(o[0]+=Vl.indexOf(n.charAt(a++)),r=0;r<o.length;r++)o[r]>t-1&&(o[r+1]===void 0&&(o[r+1]=0),o[r+1]+=o[r]/t|0,o[r]%=t)}return o.reverse()}function Ug(n,e){var t,r,o;if(e.isZero())return e;r=e.d.length,r<32?(t=Math.ceil(r/3),o=(1/va(4,t)).toString()):(t=16,o="2.3283064365386962890625e-10"),n.precision+=t,e=In(n,1,e.times(o),new n(1));for(var i=t;i--;){var a=e.times(e);e=a.times(a).minus(a).times(8).plus(1)}return n.precision-=t,e}var pe=(function(){function n(r,o,i){var a,s=0,l=r.length;for(r=r.slice();l--;)a=r[l]*o+s,r[l]=a%i|0,s=a/i|0;return s&&r.unshift(s),r}function e(r,o,i,a){var s,l;if(i!=a)l=i>a?1:-1;else for(s=l=0;s<i;s++)if(r[s]!=o[s]){l=r[s]>o[s]?1:-1;break}return l}function t(r,o,i,a){for(var s=0;i--;)r[i]-=s,s=r[i]<o[i]?1:0,r[i]=s*a+r[i]-o[i];for(;!r[0]&&r.length>1;)r.shift()}return function(r,o,i,a,s,l){var u,c,d,f,h,p,m,b,w,_,y,x,D,k,C,O,$,F,H,Q,me=r.constructor,re=r.s==o.s?1:-1,ue=r.d,U=o.d;if(!ue||!ue[0]||!U||!U[0])return new me(!r.s||!o.s||(ue?U&&ue[0]==U[0]:!U)?NaN:ue&&ue[0]==0||!U?re*0:re/0);for(l?(h=1,c=r.e-o.e):(l=yt,h=q,c=Ve(r.e/h)-Ve(o.e/h)),H=U.length,$=ue.length,w=new me(re),_=w.d=[],d=0;U[d]==(ue[d]||0);d++);if(U[d]>(ue[d]||0)&&c--,i==null?(k=i=me.precision,a=me.rounding):s?k=i+(r.e-o.e)+1:k=i,k<0)_.push(1),p=!0;else{if(k=k/h+2|0,d=0,H==1){for(f=0,U=U[0],k++;(d<$||f)&&k--;d++)C=f*l+(ue[d]||0),_[d]=C/U|0,f=C%U|0;p=f||d<$}else{for(f=l/(U[0]+1)|0,f>1&&(U=n(U,f,l),ue=n(ue,f,l),H=U.length,$=ue.length),O=H,y=ue.slice(0,H),x=y.length;x<H;)y[x++]=0;Q=U.slice(),Q.unshift(0),F=U[0],U[1]>=l/2&&++F;do f=0,u=e(U,y,H,x),u<0?(D=y[0],H!=x&&(D=D*l+(y[1]||0)),f=D/F|0,f>1?(f>=l&&(f=l-1),m=n(U,f,l),b=m.length,x=y.length,u=e(m,y,b,x),u==1&&(f--,t(m,H<b?Q:U,b,l))):(f==0&&(u=f=1),m=U.slice()),b=m.length,b<x&&m.unshift(0),t(y,m,x,l),u==-1&&(x=y.length,u=e(U,y,H,x),u<1&&(f++,t(y,H<x?Q:U,x,l))),x=y.length):u===0&&(f++,y=[0]),_[d++]=f,u&&y[0]?y[x++]=ue[O]||0:(y=[ue[O]],x=1);while((O++<$||y[0]!==void 0)&&k--);p=y[0]!==void 0}_[0]||_.shift()}if(h==1)w.e=c,Ld=p;else{for(d=1,f=_[0];f>=10;f/=10)d++;w.e=d+c*h-1,P(w,s?i+w.e+1:i,a,p)}return w}})();function P(n,e,t,r){var o,i,a,s,l,u,c,d,f,h=n.constructor;e:if(e!=null){if(d=n.d,!d)return n;for(o=1,s=d[0];s>=10;s/=10)o++;if(i=e-o,i<0)i+=q,a=e,c=d[f=0],l=c/Ce(10,o-a-1)%10|0;else if(f=Math.ceil((i+1)/q),s=d.length,f>=s)if(r){for(;s++<=f;)d.push(0);c=l=0,o=1,i%=q,a=i-q+1}else break e;else{for(c=s=d[f],o=1;s>=10;s/=10)o++;i%=q,a=i-q+o,l=a<0?0:c/Ce(10,o-a-1)%10|0}if(r=r||e<0||d[f+1]!==void 0||(a<0?c:c%Ce(10,o-a-1)),u=t<4?(l||r)&&(t==0||t==(n.s<0?3:2)):l>5||l==5&&(t==4||r||t==6&&(i>0?a>0?c/Ce(10,o-a):0:d[f-1])%10&1||t==(n.s<0?8:7)),e<1||!d[0])return d.length=0,u?(e-=n.e+1,d[0]=Ce(10,(q-e%q)%q),n.e=-e||0):d[0]=n.e=0,n;if(i==0?(d.length=f,s=1,f--):(d.length=f+1,s=Ce(10,q-i),d[f]=a>0?(c/Ce(10,o-a)%Ce(10,a)|0)*s:0),u)for(;;)if(f==0){for(i=1,a=d[0];a>=10;a/=10)i++;for(a=d[0]+=s,s=1;a>=10;a/=10)s++;i!=s&&(n.e++,d[0]==yt&&(d[0]=1));break}else{if(d[f]+=s,d[f]!=yt)break;d[f--]=0,s=1}for(i=d.length;d[--i]===0;)d.pop()}return G&&(n.e>h.maxE?(n.d=null,n.e=NaN):n.e<h.minE&&(n.e=0,n.d=[0])),n}function Ot(n,e,t){if(!n.isFinite())return Gd(n);var r,o=n.e,i=$e(n.d),a=i.length;return e?(t&&(r=t-a)>0?i=i.charAt(0)+"."+i.slice(1)+cr(r):a>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(n.e<0?"e":"e+")+n.e):o<0?(i="0."+cr(-o-1)+i,t&&(r=t-a)>0&&(i+=cr(r))):o>=a?(i+=cr(o+1-a),t&&(r=t-o-1)>0&&(i=i+"."+cr(r))):((r=o+1)<a&&(i=i.slice(0,r)+"."+i.slice(r)),t&&(r=t-a)>0&&(o+1===a&&(i+="."),i+=cr(r))),i}function ya(n,e){var t=n[0];for(e*=q;t>=10;t/=10)e++;return e}function wa(n,e,t){if(e>qg)throw G=!0,t&&(n.precision=t),Error(Fd);return P(new n(ga),e,1,!0)}function It(n,e,t){if(e>Hl)throw Error(Fd);return P(new n(ba),e,t,!0)}function Vd(n){var e=n.length-1,t=e*q+1;if(e=n[e],e){for(;e%10==0;e/=10)t--;for(e=n[0];e>=10;e/=10)t++}return t}function cr(n){for(var e="";n--;)e+="0";return e}function zd(n,e,t,r){var o,i=new n(1),a=Math.ceil(r/q+4);for(G=!1;;){if(t%2&&(i=i.times(e),Md(i.d,a)&&(o=!0)),t=Ve(t/2),t===0){t=i.d.length-1,o&&i.d[t]===0&&++i.d[t];break}e=e.times(e),Md(e.d,a)}return G=!0,i}function $d(n){return n.d[n.d.length-1]&1}function Hd(n,e,t){for(var r,o,i=new n(e[0]),a=0;++a<e.length;){if(o=new n(e[a]),!o.s){i=o;break}r=i.cmp(o),(r===t||r===0&&i.s===t)&&(i=o)}return i}function Gl(n,e){var t,r,o,i,a,s,l,u=0,c=0,d=0,f=n.constructor,h=f.rounding,p=f.precision;if(!n.d||!n.d[0]||n.e>17)return new f(n.d?n.d[0]?n.s<0?0:1/0:1:n.s?n.s<0?0:n:NaN);for(e==null?(G=!1,l=p):l=e,s=new f(.03125);n.e>-2;)n=n.times(s),d+=5;for(r=Math.log(Ce(2,d))/Math.LN10*2+5|0,l+=r,t=i=a=new f(1),f.precision=l;;){if(i=P(i.times(n),l,1),t=t.times(++c),s=a.plus(pe(i,t,l,1)),$e(s.d).slice(0,l)===$e(a.d).slice(0,l)){for(o=d;o--;)a=P(a.times(a),l,1);if(e==null)if(u<3&&Bo(a.d,l-r,h,u))f.precision=l+=10,t=i=s=new f(1),c=0,u++;else return P(a,f.precision=p,h,G=!0);else return f.precision=p,a}a=s}}function dr(n,e){var t,r,o,i,a,s,l,u,c,d,f,h=1,p=10,m=n,b=m.d,w=m.constructor,_=w.rounding,y=w.precision;if(m.s<0||!b||!b[0]||!m.e&&b[0]==1&&b.length==1)return new w(b&&!b[0]?-1/0:m.s!=1?NaN:b?0:m);if(e==null?(G=!1,c=y):c=e,w.precision=c+=p,t=$e(b),r=t.charAt(0),Math.abs(i=m.e)<15e14){for(;r<7&&r!=1||r==1&&t.charAt(1)>3;)m=m.times(n),t=$e(m.d),r=t.charAt(0),h++;i=m.e,r>1?(m=new w("0."+t),i++):m=new w(r+"."+t.slice(1))}else return u=wa(w,c+2,y).times(i+""),m=dr(new w(r+"."+t.slice(1)),c-p).plus(u),w.precision=y,e==null?P(m,y,_,G=!0):m;for(d=m,l=a=m=pe(m.minus(1),m.plus(1),c,1),f=P(m.times(m),c,1),o=3;;){if(a=P(a.times(f),c,1),u=l.plus(pe(a,new w(o),c,1)),$e(u.d).slice(0,c)===$e(l.d).slice(0,c))if(l=l.times(2),i!==0&&(l=l.plus(wa(w,c+2,y).times(i+""))),l=pe(l,new w(h),c,1),e==null)if(Bo(l.d,c-p,_,s))w.precision=c+=p,u=a=m=pe(d.minus(1),d.plus(1),c,1),f=P(m.times(m),c,1),o=s=1;else return P(l,w.precision=y,_,G=!0);else return w.precision=y,l;l=u,o+=2}}function Gd(n){return String(n.s*n.s/0)}function ma(n,e){var t,r,o;for((t=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(t<0&&(t=r),t+=+e.slice(r+1),e=e.substring(0,r)):t<0&&(t=e.length),r=0;e.charCodeAt(r)===48;r++);for(o=e.length;e.charCodeAt(o-1)===48;--o);if(e=e.slice(r,o),e){if(o-=r,n.e=t=t-r-1,n.d=[],r=(t+1)%q,t<0&&(r+=q),r<o){for(r&&n.d.push(+e.slice(0,r)),o-=q;r<o;)n.d.push(+e.slice(r,r+=q));e=e.slice(r),r=q-e.length}else r-=o;for(;r--;)e+="0";n.d.push(+e),G&&(n.e>n.constructor.maxE?(n.d=null,n.e=NaN):n.e<n.constructor.minE&&(n.e=0,n.d=[0]))}else n.e=0,n.d=[0];return n}function Vg(n,e){var t,r,o,i,a,s,l,u,c;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Ud.test(e))return ma(n,e)}else if(e==="Infinity"||e==="NaN")return+e||(n.s=NaN),n.e=NaN,n.d=null,n;if(Lg.test(e))t=16,e=e.toLowerCase();else if(Pg.test(e))t=2;else if(Fg.test(e))t=8;else throw Error(fr+e);for(i=e.search(/p/i),i>0?(l=+e.slice(i+1),e=e.substring(2,i)):e=e.slice(2),i=e.indexOf("."),a=i>=0,r=n.constructor,a&&(e=e.replace(".",""),s=e.length,i=s-i,o=zd(r,new r(t),i,i*2)),u=pa(e,t,yt),c=u.length-1,i=c;u[i]===0;--i)u.pop();return i<0?new r(n.s*0):(n.e=ya(u,c),n.d=u,G=!1,a&&(n=pe(n,o,s*4)),l&&(n=n.times(Math.abs(l)<54?Ce(2,l):$o.pow(2,l))),G=!0,n)}function zg(n,e){var t,r=e.d.length;if(r<3)return e.isZero()?e:In(n,2,e,e);t=1.4*Math.sqrt(r),t=t>16?16:t|0,e=e.times(1/va(5,t)),e=In(n,2,e,e);for(var o,i=new n(5),a=new n(16),s=new n(20);t--;)o=e.times(e),e=e.times(i.plus(o.times(a.times(o).minus(s))));return e}function In(n,e,t,r,o){var i,a,s,l,u=1,c=n.precision,d=Math.ceil(c/q);for(G=!1,l=t.times(t),s=new n(r);;){if(a=pe(s.times(l),new n(e++*e++),c,1),s=o?r.plus(a):r.minus(a),r=pe(a.times(l),new n(e++*e++),c,1),a=s.plus(r),a.d[d]!==void 0){for(i=d;a.d[i]===s.d[i]&&i--;);if(i==-1)break}i=s,s=r,r=a,a=i,u++}return G=!0,a.d.length=d+1,a}function va(n,e){for(var t=n;--e;)t*=n;return t}function Wd(n,e){var t,r=e.s<0,o=It(n,n.precision,1),i=o.times(.5);if(e=e.abs(),e.lte(i))return Gt=r?4:1,e;if(t=e.divToInt(o),t.isZero())Gt=r?3:2;else{if(e=e.minus(t.times(o)),e.lte(i))return Gt=$d(t)?r?2:3:r?4:1,e;Gt=$d(t)?r?1:4:r?3:2}return e.minus(o).abs()}function Wl(n,e,t,r){var o,i,a,s,l,u,c,d,f,h=n.constructor,p=t!==void 0;if(p?(rt(t,1,hr),r===void 0?r=h.rounding:rt(r,0,8)):(t=h.precision,r=h.rounding),!n.isFinite())c=Gd(n);else{for(c=Ot(n),a=c.indexOf("."),p?(o=2,e==16?t=t*4-3:e==8&&(t=t*3-2)):o=e,a>=0&&(c=c.replace(".",""),f=new h(1),f.e=c.length-a,f.d=pa(Ot(f),10,o),f.e=f.d.length),d=pa(c,10,o),i=l=d.length;d[--l]==0;)d.pop();if(!d[0])c=p?"0p+0":"0";else{if(a<0?i--:(n=new h(n),n.d=d,n.e=i,n=pe(n,f,t,r,0,o),d=n.d,i=n.e,u=Ld),a=d[t],s=o/2,u=u||d[t+1]!==void 0,u=r<4?(a!==void 0||u)&&(r===0||r===(n.s<0?3:2)):a>s||a===s&&(r===4||u||r===6&&d[t-1]&1||r===(n.s<0?8:7)),d.length=t,u)for(;++d[--t]>o-1;)d[t]=0,t||(++i,d.unshift(1));for(l=d.length;!d[l-1];--l);for(a=0,c="";a<l;a++)c+=Vl.charAt(d[a]);if(p){if(l>1)if(e==16||e==8){for(a=e==16?4:3,--l;l%a;l++)c+="0";for(d=pa(c,o,e),l=d.length;!d[l-1];--l);for(a=1,c="1.";a<l;a++)c+=Vl.charAt(d[a])}else c=c.charAt(0)+"."+c.slice(1);c=c+(i<0?"p":"p+")+i}else if(i<0){for(;++i;)c="0"+c;c="0."+c}else if(++i>l)for(i-=l;i--;)c+="0";else i<l&&(c=c.slice(0,i)+"."+c.slice(i))}c=(e==16?"0x":e==2?"0b":e==8?"0o":"")+c}return n.s<0?"-"+c:c}function Md(n,e){if(n.length>e)return n.length=e,!0}function Hg(n){return new this(n).abs()}function Gg(n){return new this(n).acos()}function Wg(n){return new this(n).acosh()}function Yg(n,e){return new this(n).plus(e)}function Xg(n){return new this(n).asin()}function Zg(n){return new this(n).asinh()}function Kg(n){return new this(n).atan()}function Jg(n){return new this(n).atanh()}function Qg(n,e){n=new this(n),e=new this(e);var t,r=this.precision,o=this.rounding,i=r+4;return!n.s||!e.s?t=new this(NaN):!n.d&&!e.d?(t=It(this,i,1).times(e.s>0?.25:.75),t.s=n.s):!e.d||n.isZero()?(t=e.s<0?It(this,r,o):new this(0),t.s=n.s):!n.d||e.isZero()?(t=It(this,i,1).times(.5),t.s=n.s):e.s<0?(this.precision=i,this.rounding=1,t=this.atan(pe(n,e,i,1)),e=It(this,i,1),this.precision=r,this.rounding=o,t=n.s<0?t.minus(e):t.plus(e)):t=this.atan(pe(n,e,i,1)),t}function eb(n){return new this(n).cbrt()}function tb(n){return P(n=new this(n),n.e+1,2)}function rb(n,e,t){return new this(n).clamp(e,t)}function nb(n){if(!n||typeof n!="object")throw Error(_a+"Object expected");var e,t,r,o=n.defaults===!0,i=["precision",1,hr,"rounding",0,8,"toExpNeg",-Nn,0,"toExpPos",0,Nn,"maxE",0,Nn,"minE",-Nn,0,"modulo",0,9];for(e=0;e<i.length;e+=3)if(t=i[e],o&&(this[t]=zl[t]),(r=n[t])!==void 0)if(Ve(r)===r&&r>=i[e+1]&&r<=i[e+2])this[t]=r;else throw Error(fr+t+": "+r);if(t="crypto",o&&(this[t]=zl[t]),(r=n[t])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[t]=!0;else throw Error(jd);else this[t]=!1;else throw Error(fr+t+": "+r);return this}function ob(n){return new this(n).cos()}function ib(n){return new this(n).cosh()}function Yd(n){var e,t,r;function o(i){var a,s,l,u=this;if(!(u instanceof o))return new o(i);if(u.constructor=o,Pd(i)){u.s=i.s,G?!i.d||i.e>o.maxE?(u.e=NaN,u.d=null):i.e<o.minE?(u.e=0,u.d=[0]):(u.e=i.e,u.d=i.d.slice()):(u.e=i.e,u.d=i.d?i.d.slice():i.d);return}if(l=typeof i,l==="number"){if(i===0){u.s=1/i<0?-1:1,u.e=0,u.d=[0];return}if(i<0?(i=-i,u.s=-1):u.s=1,i===~~i&&i<1e7){for(a=0,s=i;s>=10;s/=10)a++;G?a>o.maxE?(u.e=NaN,u.d=null):a<o.minE?(u.e=0,u.d=[0]):(u.e=a,u.d=[i]):(u.e=a,u.d=[i]);return}if(i*0!==0){i||(u.s=NaN),u.e=NaN,u.d=null;return}return ma(u,i.toString())}if(l==="string")return(s=i.charCodeAt(0))===45?(i=i.slice(1),u.s=-1):(s===43&&(i=i.slice(1)),u.s=1),Ud.test(i)?ma(u,i):Vg(u,i);if(l==="bigint")return i<0?(i=-i,u.s=-1):u.s=1,ma(u,i.toString());throw Error(fr+i)}if(o.prototype=S,o.ROUND_UP=0,o.ROUND_DOWN=1,o.ROUND_CEIL=2,o.ROUND_FLOOR=3,o.ROUND_HALF_UP=4,o.ROUND_HALF_DOWN=5,o.ROUND_HALF_EVEN=6,o.ROUND_HALF_CEIL=7,o.ROUND_HALF_FLOOR=8,o.EUCLID=9,o.config=o.set=nb,o.clone=Yd,o.isDecimal=Pd,o.abs=Hg,o.acos=Gg,o.acosh=Wg,o.add=Yg,o.asin=Xg,o.asinh=Zg,o.atan=Kg,o.atanh=Jg,o.atan2=Qg,o.cbrt=eb,o.ceil=tb,o.clamp=rb,o.cos=ob,o.cosh=ib,o.div=ab,o.exp=sb,o.floor=lb,o.hypot=ub,o.ln=cb,o.log=db,o.log10=hb,o.log2=fb,o.max=pb,o.min=mb,o.mod=gb,o.mul=bb,o.pow=wb,o.random=_b,o.round=yb,o.sign=vb,o.sin=Eb,o.sinh=xb,o.sqrt=kb,o.sub=Tb,o.sum=Ab,o.tan=Db,o.tanh=Sb,o.trunc=Cb,n===void 0&&(n={}),n&&n.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<r.length;)n.hasOwnProperty(t=r[e++])||(n[t]=this[t]);return o.config(n),o}function ab(n,e){return new this(n).div(e)}function sb(n){return new this(n).exp()}function lb(n){return P(n=new this(n),n.e+1,3)}function ub(){var n,e,t=new this(0);for(G=!1,n=0;n<arguments.length;)if(e=new this(arguments[n++]),e.d)t.d&&(t=t.plus(e.times(e)));else{if(e.s)return G=!0,new this(1/0);t=e}return G=!0,t.sqrt()}function Pd(n){return n instanceof $o||n&&n.toStringTag===qd||!1}function cb(n){return new this(n).ln()}function db(n,e){return new this(n).log(e)}function fb(n){return new this(n).log(2)}function hb(n){return new this(n).log(10)}function pb(){return Hd(this,arguments,-1)}function mb(){return Hd(this,arguments,1)}function gb(n,e){return new this(n).mod(e)}function bb(n,e){return new this(n).mul(e)}function wb(n,e){return new this(n).pow(e)}function _b(n){var e,t,r,o,i=0,a=new this(1),s=[];if(n===void 0?n=this.precision:rt(n,1,hr),r=Math.ceil(n/q),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(r));i<r;)o=e[i],o>=429e7?e[i]=crypto.getRandomValues(new Uint32Array(1))[0]:s[i++]=o%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(r*=4);i<r;)o=e[i]+(e[i+1]<<8)+(e[i+2]<<16)+((e[i+3]&127)<<24),o>=214e7?crypto.randomBytes(4).copy(e,i):(s.push(o%1e7),i+=4);i=r/4}else throw Error(jd);else for(;i<r;)s[i++]=Math.random()*1e7|0;for(r=s[--i],n%=q,r&&n&&(o=Ce(10,q-n),s[i]=(r/o|0)*o);s[i]===0;i--)s.pop();if(i<0)t=0,s=[0];else{for(t=-1;s[0]===0;t-=q)s.shift();for(r=1,o=s[0];o>=10;o/=10)r++;r<q&&(t-=q-r)}return a.e=t,a.d=s,a}function yb(n){return P(n=new this(n),n.e+1,this.rounding)}function vb(n){return n=new this(n),n.d?n.d[0]?n.s:0*n.s:n.s||NaN}function Eb(n){return new this(n).sin()}function xb(n){return new this(n).sinh()}function kb(n){return new this(n).sqrt()}function Tb(n,e){return new this(n).sub(e)}function Ab(){var n=0,e=arguments,t=new this(e[n]);for(G=!1;t.s&&++n<e.length;)t=t.plus(e[n]);return G=!0,P(t,this.precision,this.rounding)}function Db(n){return new this(n).tan()}function Sb(n){return new this(n).tanh()}function Cb(n){return P(n=new this(n),n.e+1,1)}S[Symbol.for("nodejs.util.inspect.custom")]=S.toString;S[Symbol.toStringTag]="Decimal";var $o=S.constructor=Yd(zl);ga=new $o(ga);ba=new $o(ba);var Xd=$o;var Nb=20,Ib=1,jr=1e6,Zd=1e6,Ob=-7,Rb=21,Bb=!1,Mo="[big.js] ",qr=Mo+"Invalid ",Ea=qr+"decimal places",$b=qr+"rounding mode",Kd=Mo+"Division by zero",ce={},Rt=void 0,Mb=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Jd(){function n(e){var t=this;if(!(t instanceof n))return e===Rt?Jd():new n(e);if(e instanceof n)t.s=e.s,t.e=e.e,t.c=e.c.slice();else{if(typeof e!="string"){if(n.strict===!0&&typeof e!="bigint")throw TypeError(qr+"value");e=e===0&&1/e<0?"-0":String(e)}Pb(t,e)}t.constructor=n}return n.prototype=ce,n.DP=Nb,n.RM=Ib,n.NE=Ob,n.PE=Rb,n.strict=Bb,n.roundDown=0,n.roundHalfUp=1,n.roundHalfEven=2,n.roundUp=3,n}function Pb(n,e){var t,r,o;if(!Mb.test(e))throw Error(qr+"number");for(n.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(t=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(t<0&&(t=r),t+=+e.slice(r+1),e=e.substring(0,r)):t<0&&(t=e.length),o=e.length,r=0;r<o&&e.charAt(r)=="0";)++r;if(r==o)n.c=[n.e=0];else{for(;o>0&&e.charAt(--o)=="0";);for(n.e=t-r-1,n.c=[],t=0;r<=o;)n.c[t++]=+e.charAt(r++)}return n}function Ur(n,e,t,r){var o=n.c;if(t===Rt&&(t=n.constructor.RM),t!==0&&t!==1&&t!==2&&t!==3)throw Error($b);if(e<1)r=t===3&&(r||!!o[0])||e===0&&(t===1&&o[0]>=5||t===2&&(o[0]>5||o[0]===5&&(r||o[1]!==Rt))),o.length=1,r?(n.e=n.e-e+1,o[0]=1):o[0]=n.e=0;else if(e<o.length){if(r=t===1&&o[e]>=5||t===2&&(o[e]>5||o[e]===5&&(r||o[e+1]!==Rt||o[e-1]&1))||t===3&&(r||!!o[0]),o.length=e,r){for(;++o[--e]>9;)if(o[e]=0,e===0){++n.e,o.unshift(1);break}}for(e=o.length;!o[--e];)o.pop()}return n}function Vr(n,e,t){var r=n.e,o=n.c.join(""),i=o.length;if(e)o=o.charAt(0)+(i>1?"."+o.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)o="0"+o;o="0."+o}else if(r>0)if(++r>i)for(r-=i;r--;)o+="0";else r<i&&(o=o.slice(0,r)+"."+o.slice(r));else i>1&&(o=o.charAt(0)+"."+o.slice(1));return n.s<0&&t?"-"+o:o}ce.abs=function(){var n=new this.constructor(this);return n.s=1,n};ce.cmp=function(n){var e,t=this,r=t.c,o=(n=new t.constructor(n)).c,i=t.s,a=n.s,s=t.e,l=n.e;if(!r[0]||!o[0])return r[0]?i:o[0]?-a:0;if(i!=a)return i;if(e=i<0,s!=l)return s>l^e?1:-1;for(a=(s=r.length)<(l=o.length)?s:l,i=-1;++i<a;)if(r[i]!=o[i])return r[i]>o[i]^e?1:-1;return s==l?0:s>l^e?1:-1};ce.div=function(n){var e=this,t=e.constructor,r=e.c,o=(n=new t(n)).c,i=e.s==n.s?1:-1,a=t.DP;if(a!==~~a||a<0||a>jr)throw Error(Ea);if(!o[0])throw Error(Kd);if(!r[0])return n.s=i,n.c=[n.e=0],n;var s,l,u,c,d,f=o.slice(),h=s=o.length,p=r.length,m=r.slice(0,s),b=m.length,w=n,_=w.c=[],y=0,x=a+(w.e=e.e-n.e)+1;for(w.s=i,i=x<0?0:x,f.unshift(0);b++<s;)m.push(0);do{for(u=0;u<10;u++){if(s!=(b=m.length))c=s>b?1:-1;else for(d=-1,c=0;++d<s;)if(o[d]!=m[d]){c=o[d]>m[d]?1:-1;break}if(c<0){for(l=b==s?o:f;b;){if(m[--b]<l[b]){for(d=b;d&&!m[--d];)m[d]=9;--m[d],m[b]+=10}m[b]-=l[b]}for(;!m[0];)m.shift()}else break}_[y++]=c?u:++u,m[0]&&c?m[b]=r[h]||0:m=[r[h]]}while((h++<p||m[0]!==Rt)&&i--);return!_[0]&&y!=1&&(_.shift(),w.e--,x--),y>x&&Ur(w,x,t.RM,m[0]!==Rt),w};ce.eq=function(n){return this.cmp(n)===0};ce.gt=function(n){return this.cmp(n)>0};ce.gte=function(n){return this.cmp(n)>-1};ce.lt=function(n){return this.cmp(n)<0};ce.lte=function(n){return this.cmp(n)<1};ce.minus=ce.sub=function(n){var e,t,r,o,i=this,a=i.constructor,s=i.s,l=(n=new a(n)).s;if(s!=l)return n.s=-l,i.plus(n);var u=i.c.slice(),c=i.e,d=n.c,f=n.e;if(!u[0]||!d[0])return d[0]?n.s=-l:u[0]?n=new a(i):n.s=1,n;if(s=c-f){for((o=s<0)?(s=-s,r=u):(f=c,r=d),r.reverse(),l=s;l--;)r.push(0);r.reverse()}else for(t=((o=u.length<d.length)?u:d).length,s=l=0;l<t;l++)if(u[l]!=d[l]){o=u[l]<d[l];break}if(o&&(r=u,u=d,d=r,n.s=-n.s),(l=(t=d.length)-(e=u.length))>0)for(;l--;)u[e++]=0;for(l=e;t>s;){if(u[--t]<d[t]){for(e=t;e&&!u[--e];)u[e]=9;--u[e],u[t]+=10}u[t]-=d[t]}for(;u[--l]===0;)u.pop();for(;u[0]===0;)u.shift(),--f;return u[0]||(n.s=1,u=[f=0]),n.c=u,n.e=f,n};ce.mod=function(n){var e,t=this,r=t.constructor,o=t.s,i=(n=new r(n)).s;if(!n.c[0])throw Error(Kd);return t.s=n.s=1,e=n.cmp(t)==1,t.s=o,n.s=i,e?new r(t):(o=r.DP,i=r.RM,r.DP=r.RM=0,t=t.div(n),r.DP=o,r.RM=i,this.minus(t.times(n)))};ce.neg=function(){var n=new this.constructor(this);return n.s=-n.s,n};ce.plus=ce.add=function(n){var e,t,r,o=this,i=o.constructor;if(n=new i(n),o.s!=n.s)return n.s=-n.s,o.minus(n);var a=o.e,s=o.c,l=n.e,u=n.c;if(!s[0]||!u[0])return u[0]||(s[0]?n=new i(o):n.s=o.s),n;if(s=s.slice(),e=a-l){for(e>0?(l=a,r=u):(e=-e,r=s),r.reverse();e--;)r.push(0);r.reverse()}for(s.length-u.length<0&&(r=u,u=s,s=r),e=u.length,t=0;e;s[e]%=10)t=(s[--e]=s[e]+u[e]+t)/10|0;for(t&&(s.unshift(t),++l),e=s.length;s[--e]===0;)s.pop();return n.c=s,n.e=l,n};ce.pow=function(n){var e=this,t=new e.constructor("1"),r=t,o=n<0;if(n!==~~n||n<-Zd||n>Zd)throw Error(qr+"exponent");for(o&&(n=-n);n&1&&(r=r.times(e)),n>>=1,!!n;)e=e.times(e);return o?t.div(r):r};ce.prec=function(n,e){if(n!==~~n||n<1||n>jr)throw Error(qr+"precision");return Ur(new this.constructor(this),n,e)};ce.round=function(n,e){if(n===Rt)n=0;else if(n!==~~n||n<-jr||n>jr)throw Error(Ea);return Ur(new this.constructor(this),n+this.e+1,e)};ce.sqrt=function(){var n,e,t,r=this,o=r.constructor,i=r.s,a=r.e,s=new o("0.5");if(!r.c[0])return new o(r);if(i<0)throw Error(Mo+"No square root");i=Math.sqrt(+Vr(r,!0,!0)),i===0||i===1/0?(e=r.c.join(""),e.length+a&1||(e+="0"),i=Math.sqrt(e),a=((a+1)/2|0)-(a<0||a&1),n=new o((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+a)):n=new o(i+""),a=n.e+(o.DP+=4);do t=n,n=s.times(t.plus(r.div(t)));while(t.c.slice(0,a).join("")!==n.c.slice(0,a).join(""));return Ur(n,(o.DP-=4)+n.e+1,o.RM)};ce.times=ce.mul=function(n){var e,t=this,r=t.constructor,o=t.c,i=(n=new r(n)).c,a=o.length,s=i.length,l=t.e,u=n.e;if(n.s=t.s==n.s?1:-1,!o[0]||!i[0])return n.c=[n.e=0],n;for(n.e=l+u,a<s&&(e=o,o=i,i=e,u=a,a=s,s=u),e=new Array(u=a+s);u--;)e[u]=0;for(l=s;l--;){for(s=0,u=a+l;u>l;)s=e[u]+i[l]*o[u-l-1]+s,e[u--]=s%10,s=s/10|0;e[u]=s}for(s?++n.e:e.shift(),l=e.length;!e[--l];)e.pop();return n.c=e,n};ce.toExponential=function(n,e){var t=this,r=t.c[0];if(n!==Rt){if(n!==~~n||n<0||n>jr)throw Error(Ea);for(t=Ur(new t.constructor(t),++n,e);t.c.length<n;)t.c.push(0)}return Vr(t,!0,!!r)};ce.toFixed=function(n,e){var t=this,r=t.c[0];if(n!==Rt){if(n!==~~n||n<0||n>jr)throw Error(Ea);for(t=Ur(new t.constructor(t),n+t.e+1,e),n=n+t.e+1;t.c.length<n;)t.c.push(0)}return Vr(t,!1,!!r)};ce[Symbol.for("nodejs.util.inspect.custom")]=ce.toJSON=ce.toString=function(){var n=this,e=n.constructor;return Vr(n,n.e<=e.NE||n.e>=e.PE,!!n.c[0])};ce.toNumber=function(){var n=+Vr(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(n.toString()))throw Error(Mo+"Imprecise conversion");return n};ce.toPrecision=function(n,e){var t=this,r=t.constructor,o=t.c[0];if(n!==Rt){if(n!==~~n||n<1||n>jr)throw Error(qr+"precision");for(t=Ur(new r(t),n,e);t.c.length<n;)t.c.push(0)}return Vr(t,n<=t.e||t.e<=r.NE||t.e>=r.PE,!!o)};ce.valueOf=function(){var n=this,e=n.constructor;if(e.strict===!0)throw Error(Mo+"valueOf disallowed");return Vr(n,n.e<=e.NE||n.e>=e.PE,!0)};var Lb=Jd(),Qd=Lb;var ou={};Bg(ou,{DecodeError:()=>ze,Decoder:()=>Et,EXT_TIMESTAMP:()=>Xl,Encoder:()=>On,ExtData:()=>vt,ExtensionCodec:()=>pr,decode:()=>uf,decodeArrayStream:()=>ff,decodeAsync:()=>df,decodeMulti:()=>cf,decodeMultiStream:()=>hf,decodeTimestampExtension:()=>eu,decodeTimestampToTimeSpec:()=>Ql,encode:()=>Ta,encodeDateToTimeSpec:()=>Kl,encodeTimeSpecToTimestamp:()=>Zl,encodeTimestampExtension:()=>Jl});function ef(n){let e=n.length,t=0,r=0;for(;r<e;){let o=n.charCodeAt(r++);if((o&4294967168)===0){t++;continue}else if((o&4294965248)===0)t+=2;else{if(o>=55296&&o<=56319&&r<e){let i=n.charCodeAt(r);(i&64512)===56320&&(++r,o=((o&1023)<<10)+(i&1023)+65536)}(o&4294901760)===0?t+=3:t+=4}}return t}function Fb(n,e,t){let r=n.length,o=t,i=0;for(;i<r;){let a=n.charCodeAt(i++);if((a&4294967168)===0){e[o++]=a;continue}else if((a&4294965248)===0)e[o++]=a>>6&31|192;else{if(a>=55296&&a<=56319&&i<r){let s=n.charCodeAt(i);(s&64512)===56320&&(++i,a=((a&1023)<<10)+(s&1023)+65536)}(a&4294901760)===0?(e[o++]=a>>12&15|224,e[o++]=a>>6&63|128):(e[o++]=a>>18&7|240,e[o++]=a>>12&63|128,e[o++]=a>>6&63|128)}e[o++]=a&63|128}}var jb=new TextEncoder,qb=50;function Ub(n,e,t){jb.encodeInto(n,e.subarray(t))}function tf(n,e,t){n.length>qb?Ub(n,e,t):Fb(n,e,t)}var Vb=4096;function Yl(n,e,t){let r=e,o=r+t,i=[],a="";for(;r<o;){let s=n[r++];if((s&128)===0)i.push(s);else if((s&224)===192){let l=n[r++]&63;i.push((s&31)<<6|l)}else if((s&240)===224){let l=n[r++]&63,u=n[r++]&63;i.push((s&31)<<12|l<<6|u)}else if((s&248)===240){let l=n[r++]&63,u=n[r++]&63,c=n[r++]&63,d=(s&7)<<18|l<<12|u<<6|c;d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(s);i.length>=Vb&&(a+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(a+=String.fromCharCode(...i)),a}var zb=new TextDecoder,Hb=200;function Gb(n,e,t){let r=n.subarray(e,e+t);return zb.decode(r)}function rf(n,e,t){return t>Hb?Gb(n,e,t):Yl(n,e,t)}var vt=class{type;data;constructor(e,t){this.type=e,this.data=t}};var ze=class n extends Error{constructor(e){super(e);let t=Object.create(n.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:n.name})}};function nf(n,e,t){let r=t/4294967296,o=t;n.setUint32(e,r),n.setUint32(e+4,o)}function xa(n,e,t){let r=Math.floor(t/4294967296),o=t;n.setUint32(e,r),n.setUint32(e+4,o)}function ka(n,e){let t=n.getInt32(e),r=n.getUint32(e+4);return t*4294967296+r}function of(n,e){let t=n.getUint32(e),r=n.getUint32(e+4);return t*4294967296+r}var Xl=-1,Wb=4294967296-1,Yb=17179869184-1;function Zl({sec:n,nsec:e}){if(n>=0&&e>=0&&n<=Yb)if(e===0&&n<=Wb){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{let t=n/4294967296,r=n&4294967295,o=new Uint8Array(8),i=new DataView(o.buffer);return i.setUint32(0,e<<2|t&3),i.setUint32(4,r),o}else{let t=new Uint8Array(12),r=new DataView(t.buffer);return r.setUint32(0,e),xa(r,4,n),t}}function Kl(n){let e=n.getTime(),t=Math.floor(e/1e3),r=(e-t*1e3)*1e6,o=Math.floor(r/1e9);return{sec:t+o,nsec:r-o*1e9}}function Jl(n){if(n instanceof Date){let e=Kl(n);return Zl(e)}else return null}function Ql(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),r=e.getUint32(4),o=(t&3)*4294967296+r,i=t>>>2;return{sec:o,nsec:i}}case 12:{let t=ka(e,4),r=e.getUint32(0);return{sec:t,nsec:r}}default:throw new ze(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`)}}function eu(n){let e=Ql(n);return new Date(e.sec*1e3+e.nsec/1e6)}var af={type:Xl,encode:Jl,decode:eu};var pr=class n{static defaultCodec=new n;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(af)}register({type:e,encode:t,decode:r}){if(e>=0)this.encoders[e]=t,this.decoders[e]=r;else{let o=-1-e;this.builtInEncoders[o]=t,this.builtInDecoders[o]=r}}tryToEncode(e,t){for(let r=0;r<this.builtInEncoders.length;r++){let o=this.builtInEncoders[r];if(o!=null){let i=o(e,t);if(i!=null){let a=-1-r;return new vt(a,i)}}}for(let r=0;r<this.encoders.length;r++){let o=this.encoders[r];if(o!=null){let i=o(e,t);if(i!=null){let a=r;return new vt(a,i)}}}return e instanceof vt?e:null}decode(e,t,r){let o=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return o?o(e,t,r):new vt(t,e)}};function Xb(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function Po(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Xb(n)?new Uint8Array(n):Uint8Array.from(n)}var Zb=100,Kb=2048,On=class n{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??pr.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Zb,this.initialBufferSize=e?.initialBufferSize??Kb,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){let t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){let t=new ArrayBuffer(e),r=new Uint8Array(t),o=new DataView(t);r.set(this.bytes),this.view=o,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=ef(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),tf(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,t){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);let r=Po(e);this.writeU8a(r)}encodeArray(e,t){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let o of e)this.doEncode(o,t+1)}countWithoutUndefined(e,t){let r=0;for(let o of t)e[o]!==void 0&&r++;return r}encodeMap(e,t){let r=Object.keys(e);this.sortKeys&&r.sort();let o=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(let i of r){let a=e[i];this.ignoreUndefined&&a===void 0||(this.encodeString(i),this.doEncode(a,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),o=r.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(e.type),this.writeU8a(r);return}let t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),nf(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),xa(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function Ta(n,e){return new On(e).encodeSharedRef(n)}function Aa(n){return`${n<0?"-":""}0x${Math.abs(n).toString(16).padStart(2,"0")}`}var Jb=16,Qb=16,Da=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=Jb,t=Qb){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,r){let o=this.caches[r-1];e:for(let i of o){let a=i.bytes;for(let s=0;s<r;s++)if(a[s]!==e[t+s])continue e;return i.str}return null}store(e,t){let r=this.caches[e.length-1],o={bytes:e,str:t};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=o:r.push(o)}decode(e,t,r){let o=this.find(e,t,r);if(o!=null)return this.hit++,o;this.miss++;let i=Yl(e,t,r),a=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(a,i),i}};var tu="array",jo="map_key",lf="map_value",ew=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new ze("The type of key must be string or number but "+typeof n)},ru=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=tu,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=jo,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===tu){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===jo||e.type===lf){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Fo=-1,nu=new DataView(new ArrayBuffer(0)),tw=new Uint8Array(nu.buffer);try{nu.getInt8(0)}catch(n){if(!(n instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var sf=new RangeError("Insufficient data"),rw=new Da,Et=class n{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=nu;bytes=tw;headByte=Fo;stack=new ru;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??pr.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:rw,this.mapKeyConverter=e?.mapKeyConverter??ew}clone(){return new n({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Fo,this.stack.reset()}setBuffer(e){let t=Po(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Fo&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),r=Po(e),o=new Uint8Array(t.length+r.length);o.set(t),o.set(r,t.length),this.setBuffer(o)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:t,pos:r}=this;return new RangeError(`Extra ${t.byteLength-r} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,r;for await(let s of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{r=this.doDecodeSync(),t=!0}catch(l){if(!(l instanceof RangeError))throw l}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:o,pos:i,totalPos:a}=this;throw new RangeError(`Insufficient data in parsing ${Aa(o)} at ${a} (${i} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let r=t,o=-1;for await(let i of e){if(t&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(o=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(a){if(!(a instanceof RangeError))throw a}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){let o=e-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else t={}}else if(e<160){let o=e-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else t=[]}else{let o=e-160;t=this.decodeString(o,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){let o=this.lookU8();t=this.decodeString(o,1)}else if(e===218){let o=this.lookU16();t=this.decodeString(o,2)}else if(e===219){let o=this.lookU32();t=this.decodeString(o,4)}else if(e===220){let o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else t=[]}else if(e===221){let o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else t=[]}else if(e===222){let o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else t={}}else if(e===223){let o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else t={}}else if(e===196){let o=this.lookU8();t=this.decodeBinary(o,1)}else if(e===197){let o=this.lookU16();t=this.decodeBinary(o,2)}else if(e===198){let o=this.lookU32();t=this.decodeBinary(o,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){let o=this.lookU8();t=this.decodeExtension(o,1)}else if(e===200){let o=this.lookU16();t=this.decodeExtension(o,2)}else if(e===201){let o=this.lookU32();t=this.decodeExtension(o,4)}else throw new ze(`Unrecognized type byte: ${Aa(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let o=r.top();if(o.type===tu)if(o.array[o.position]=t,o.position++,o.position===o.size)t=o.array,r.release(o);else continue e;else if(o.type===jo){if(t==="__proto__")throw new ze("The key __proto__ is not allowed");o.key=this.mapKeyConverter(t),o.type=lf;continue e}else if(o.map[o.key]=t,o.readCount++,o.readCount===o.size)t=o.map,r.release(o);else{o.key=null,o.type=jo;continue e}}return t}}readHeadByte(){return this.headByte===Fo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Fo}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new ze(`Unrecognized array type byte: ${Aa(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ze(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ze(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new ze(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw sf;let r=this.pos+t,o;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?o=this.keyDecoder.decode(this.bytes,r,e):o=rf(this.bytes,r,e),this.pos+=t+e,o}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===jo:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new ze(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw sf;let r=this.pos+t,o=this.bytes.subarray(r,r+e);return this.pos+=t+e,o}decodeExtension(e,t){if(e>this.maxExtLength)throw new ze(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+t),o=this.decodeBinary(e,t+1);return this.extensionCodec.decode(o,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=of(this.view,this.pos);return this.pos+=8,e}readI64(){let e=ka(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function uf(n,e){return new Et(e).decode(n)}function cf(n,e){return new Et(e).decodeMulti(n)}function nw(n){return n[Symbol.asyncIterator]!=null}async function*ow(n){let e=n.getReader();try{for(;;){let{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}}function Sa(n){return nw(n)?n:ow(n)}async function df(n,e){let t=Sa(n);return new Et(e).decodeAsync(t)}function ff(n,e){let t=Sa(n);return new Et(e).decodeArrayStream(t)}function hf(n,e){let t=Sa(n);return new Et(e).decodeStream(t)}var Wa=Od(Au(),1),Du=Xd,Su=Qd,Pt=ou,wh=Wa.DOMParser,_h=Wa.XMLSerializer;var yh=Pt!==null;function vh(){if(!yh)throw new Error("@msgpack/msgpack is required for MessagePack support. Install with: npm install @msgpack/msgpack")}var Eh=ny();function ny(){if(!yh)return null;let n=new TextEncoder,e=new TextDecoder,t=new Pt.ExtensionCodec;return t.register({type:-1,encode:r=>{if(r instanceof Date){let o=vr(r);if(o==="D"||o==="H")return null}return Pt.encodeTimestampExtension(r)},decode:r=>Pt.decodeTimestampExtension(r)}),t.register({type:1,encode:r=>le(r)?n.encode(r.toString()):null,decode:r=>Lt(e.decode(r))}),t.register({type:2,encode:r=>{if(r instanceof Date&&vr(r)==="D"){let o=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),a=String(r.getUTCDate()).padStart(2,"0");return n.encode(`${o}-${i}-${a}`)}return null},decode:r=>new Date(e.decode(r)+"T00:00:00.000Z")}),t.register({type:3,encode:r=>{if(r instanceof Date&&vr(r)==="H"){let o=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),a=String(r.getUTCSeconds()).padStart(2,"0"),s=String(r.getUTCMilliseconds()).padStart(3,"0");return n.encode(`${o}:${i}:${a}.${s}`)}return null},decode:r=>{let o=e.decode(r),i=o.indexOf("."),a=i>=0?o.substring(0,i):o,s=i>=0?o.substring(i+1):"0",[l,u,c]=a.split(":"),d=Math.round(+s.substring(0,3));return new Date(Date.UTC(1970,0,1,+l,+u,+c,d))}}),t.register({type:4,encode:r=>{let o=Cu(r);if(o!==null){let[i,a]=o;return n.encode(`${i}:${a(r)}`)}return null},decode:r=>{let o=e.decode(r),i=o.indexOf(":"),a=o.slice(0,i),s=o.slice(i+1),l=Er[a];if(l!==void 0){let[,u]=l;return u(s)}return`${s}::${a}`}}),t}function xh(n){return vh(),Pt.encode(n,{extensionCodec:Eh})}function kh(n){return vh(),Pt.decode(n,{extensionCodec:Eh})}function Ya(n,e=!1){let t=Xa(n);if(t===null)return[!1,String(n)];let[r,o,i]=t;return i&&!e?[!1,String(n)]:[!0,`${o(n)}::${r}`]}function Nu(n){if(!n.includes("::"))return[!1,n];let e=n.lastIndexOf("::"),t=n.slice(0,e),r=n.slice(e+2),o=Er[r];if(o===void 0)return[!1,n];let[,i]=o;return[!0,i(t)]}function Kn(n,e,t){if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let r={};for(let[o,i]of Object.entries(n))r[o]=Kn(i,e,t);return r}return Array.isArray(n)?n.map(r=>Kn(r,e,t)):t(n)?e(n):n}function Iu(n){let e=Xa(n);if(e!==null){let[t,r,o]=e;return o?[n,!1]:[`${r(n)}::${t}`,!0]}if(Array.isArray(n)){let t=!1;return[n.map(o=>{let[i,a]=Iu(o);return a&&(t=!0),i}),t]}if(n!==null&&typeof n=="object"){let t=!1,r={};for(let[o,i]of Object.entries(n)){let[a,s]=Iu(i);s&&(t=!0),r[o]=a}return[r,t]}return[n,!1]}function oy(n,e=!1){let[t,r]=Ya(n,e);if(t)return r;let[o,i]=Iu(n),a=JSON.stringify(o);return i?`${a}::JS`:a}function iy(n){return JSON.stringify(n)}function ay(n){if(!Pt)throw new Error("@msgpack/msgpack is required for MessagePack support");return Pt.encode(n)}function L(n,e=null,{raw:t=!1,qs:r=!1,_forceSuffix:o=!1}={}){if(r)return`${Ah(n)}::QS`;if(t){if(e===null||e==="json")return iy(n);if(e==="msgpack")return ay(n);throw e==="xml"?new Error("raw=true is not supported for XML transport"):new Error(`Unknown transport: ${e}`)}if(e===null||e==="json"){let i=oy(n,o);return e==="json"?`"${i}"`:i}else{if(e==="xml")return`<?xml version="1.0" ?><tytx_root>${Th(n)}</tytx_root>`;if(e==="msgpack")return xh(n);throw new Error(`Unknown transport: ${e}`)}}var Jn,Ou;typeof window<"u"&&window.DOMParser?(Jn=window.DOMParser,Ou=window.XMLSerializer):(Jn=wh,Ou=_h);function Dh(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;let e=Object.keys(n);if(e.length!==1)return!1;let t=n[e[0]];return t!==null&&typeof t=="object"&&"value"in t}function Sh(n,e,t){let r=n.createElement(e),o=t.attrs||{},i=t.value;for(let[a,s]of Object.entries(o))r.setAttribute(a,L(s,null,{_forceSuffix:!0}));if(Array.isArray(i))for(let a of i)if(Dh(a)){let[s]=Object.keys(a),l=a[s],u=Sh(n,s,l);r.appendChild(u)}else{r.textContent=L(i);break}else r.textContent=L(i);return r}function Th(n){if(!Jn)throw new Error("XML support requires @xmldom/xmldom package in Node.js");if(Dh(n)){let[e]=Object.keys(n),t=n[e],r=new Jn().parseFromString("<root/>","text/xml"),o=Sh(r,e,t);return new Ou().serializeToString(o)}else return L(n)}function Ru(n){let e={};for(let r=0;r<n.attributes.length;r++){let o=n.attributes[r];e[o.name]=j(o.value)}let t=[];for(let r=0;r<n.childNodes.length;r++){let o=n.childNodes[r];o.nodeType===1&&t.push(o)}if(t.length>0)if(t.length===1){let r=t[0],o=Ru(r);return{attrs:e,value:{[r.tagName]:o}}}else{let r=[];for(let o of t){let i=Ru(o);r.push({[o.tagName]:i})}return{attrs:e,value:r}}return{attrs:e,value:j(n.textContent)}}function Ch(n){if(!Jn)throw new Error("XML support requires @xmldom/xmldom package in Node.js");let r=new Jn().parseFromString(n,"text/xml").documentElement;if(r.tagName==="tytx_root"){let i=null;for(let a=0;a<r.childNodes.length;a++)if(r.childNodes[a].nodeType===1){i=r.childNodes[a];break}if(!i)return j(r.textContent);r=i}let o=Ru(r);return{[r.tagName]:o}}function Bu(n){return typeof n=="string"}function sy(n){let[e,t]=Nu(n);if(e)return t;let r=n;r.endsWith("::JS")&&(r=r.slice(0,-4));let o;try{o=JSON.parse(r)}catch{return n}return Kn(o,$u,Bu)}function $u(n){return n.includes("::")?Nu(n)[1]:n}function ly(n){let e=Ch(n);return typeof e=="string"?j(e):e}function uy(n){return kh(n)}function j(n,e=null){if(n===null)return null;if(e===null||e==="json"){let t=n;return e==="json"&&n.startsWith('"')&&n.endsWith('"')&&(t=n.slice(1,-1)),sy(t)}else{if(e==="xml")return ly(n);if(e==="msgpack")return uy(n);throw new Error(`Unknown transport: ${e}`)}}function Nh(n){return Symbol.asyncIterator in n?(async function*(){for await(let t of n)yield Kn(t,$u,Bu)})():(function*(){for(let t of n)yield Kn(t,$u,Bu)})()}function Ah(n){if(Array.isArray(n))return n.map(e=>String(e)).join("&");if(n!==null&&typeof n=="object"){let e=[];for(let[t,r]of Object.entries(n)){let[o,i]=Ya(r,!0);o?e.push(`${t}=${i}`):e.push(`${t}=${r}`)}return e.join("&")}throw new TypeError(`toQs expects object or array, got ${typeof n}`)}function Ih(n){if(!n)return[];let e=n.split("&"),t=e.map(a=>a.includes("=")),r=t.every(Boolean),o=!t.some(Boolean);if(!r&&!o)throw new Error("QS format error: mixed items with and without '='");if(o)return e.map(a=>j(a));let i={};for(let a of e){let s=a.indexOf("="),l=a.slice(0,s),u=a.slice(s+1);i[l]=j(u)}return i}var Rh=Du||Su||Number,Bh=Du?"decimal.js":Su?"big.js":"number";function Ka(){return Bh}function Lt(n){return new Rh(n)}function le(n){return Bh==="number"?!1:n instanceof Rh}function vr(n){let e=n.getUTCFullYear()===1970&&n.getUTCMonth()===0&&n.getUTCDate()===1,t=n.getUTCHours()===0&&n.getUTCMinutes()===0&&n.getUTCSeconds()===0&&n.getUTCMilliseconds()===0;return e&&!t?"H":t&&!e?"D":"DHZ"}function cy(n){return n.toString()}function dy(n){let e=n.getUTCFullYear(),t=String(n.getUTCMonth()+1).padStart(2,"0"),r=String(n.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}function fy(n){return n.toISOString()}function hy(n){let e=String(n.getUTCHours()).padStart(2,"0"),t=String(n.getUTCMinutes()).padStart(2,"0"),r=String(n.getUTCSeconds()).padStart(2,"0"),o=String(n.getUTCMilliseconds()).padStart(3,"0");return`${e}:${t}:${r}.${o}`}function py(n){return n?"true":"false"}function my(n){return n.toString()}function gy(n){return n.toString()}function by(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode.apply(null,n.subarray(t,t+32768));return btoa(e)}var Za=[],Mu=new Map;function Cu(n){if(n===null||typeof n!="object")return null;for(let e=Object.getPrototypeOf(n);e!==null;e=Object.getPrototypeOf(e))for(let[t,r,o,i]of Za)if(t.prototype===e)return[r,o,i];return null}function Xa(n){if(n===null)return["NN",()=>"",!0];if(le(n))return["N",cy,!1];if(n instanceof Uint8Array)return["RAW",by,!1];if(n instanceof Date){let e=vr(n);return e==="D"?["D",dy,!1]:e==="H"?["H",hy,!1]:["DHZ",fy,!1]}return typeof n=="boolean"?["B",py,!0]:typeof n=="number"?Number.isInteger(n)?["L",my,!0]:["R",gy,!0]:Cu(n)}function wy(n){return Lt(n)}function _y(n){let[e,t,r]=n.split("-").map(Number);return new Date(Date.UTC(e,t-1,r,0,0,0,0))}function Oh(n){return new Date(n)}function yy(n){let[e,t,r]=n.split(":"),[o,i]=r.split(".");return new Date(Date.UTC(1970,0,1,Number(e),Number(t),Number(o),Number(i||0)))}function vy(n){return n.toLowerCase()==="true"}function Ey(n){return parseInt(n,10)}function xy(n){return parseFloat(n)}function ky(n){return n}function Ty(n){return null}var Ay=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Dy(n){if(!Ay.test(n))throw new Error(`RAW payload is not standard padded base64: '${n}'`);let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Sy(n){return Ih(n)}var Cy=/^[A-Z]+$/,Er={N:[Object,wy],D:[Date,_y],DH:[Date,Oh],DHZ:[Date,Oh],H:[Date,yy],L:[Number,Ey],R:[Number,xy],T:[String,ky],B:[Boolean,vy],QS:[Object,Sy],NN:[null,Ty],RAW:[Uint8Array,Dy]};function ai(n){return Object.hasOwn(Er,n)?Er[n][0]:null}function Pu(n,e,t,r,o=!1){if(typeof e!="string"||!Cy.test(e))throw new Error(`TYTX suffix '${e}' is invalid: expected uppercase ASCII letters only`);let i=Er[e];if(i!==void 0&&i[0]!==n){let a=i[0]===null?"null":i[0].name;throw new Error(`TYTX suffix '${e}' is already registered for ${a}`)}Za=Za.filter(([a])=>a!==n),Za.push([n,e,t,o]),Er[e]=[n,r]}function Yr(n,e){Mu.set(n,e)}function pt(n){return Mu.has(n)?Mu.get(n):{}}function ne(n){if(typeof n!="string"||!["^","="].includes(n[0])||n.startsWith("=="))return null;let e=n.indexOf(":");if(e<0)return null;let t=n[e+1]==="=";return{pointer:n.slice(0,e),expression:t,body:n.slice(e+(t?2:1))}}var $h=/^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;function Xr(n,e){let t="",r=!1;for(let o=0;o<n.length;){if(n[o]!=="{"&&n[o]!=="}"){t+=n[o++];continue}let i=n.slice(o).match($h);if(!i)throw new SyntaxError("Invalid pointer template placeholder");let a=i[1]??"",s=a.startsWith("?"),l=e(s?a.slice(1):a);l==null||l===""&&!s?r=!0:t+=String(l),o+=i[0].length}return r?null:t}function si(n){let e=[],t=new Set,r="",o=!0;for(let i=0;i<n.length;){let a=i,s=n[i];if(s==='"'||s==="'"||s==="`"){for(i++;i<n.length;){if(n[i]==="\\"){i+=2;continue}if(n[i++]===s)break}r+=n.slice(a,i),o=!1;continue}if(n.startsWith("//",i)){i=n.indexOf(`
|
|
31
|
+
`,i),i<0&&(i=n.length),r+=n.slice(a,i);continue}if(n.startsWith("/*",i)){let c=n.indexOf("*/",i+2);i=c<0?n.length:c+2,r+=n.slice(a,i);continue}if(s==="/"&&o){let c=!1;for(i++;i<n.length;){let d=n[i++];if(d==="\\"){i++;continue}if(d==="[")c=!0;else if(d==="]")c=!1;else if(d==="/"&&!c)break}for(;/[a-z]/i.test(n[i]??"")&&i<n.length;)i++;r+=n.slice(a,i),o=!1;continue}let l=s==="{"?n.slice(i).match($h):null;if(l){let c=l[1]??"";if(c.startsWith("?"))throw new SyntaxError("Optional slots are supported in pointer templates only");r+=`_pointerValues[${e.length}]`,e.push(c),i+=l[0].length,o=!1;continue}let u=n.slice(i).match(/^[A-Za-z_$][\w$]*/);if(u){t.add(u[0]),r+=u[0],i+=u[0].length,o=["return","typeof","void","delete","new","in","instanceof","yield","await"].includes(u[0]);continue}r+=s,i++,/\s/.test(s)||(o=/[([{,:;=!?&|+*%~<>\/-]/.test(s))}return{text:r,slots:e,identifiers:t}}function Mh(n,e,t=()=>null){let r=new Map,o=[],i=a=>{if(r.has(a))return r.get(a);if(!n.has(a))throw new Error(`Referenced Source attribute '${a}' does not exist`);if(o.includes(a))throw new Error(`Cyclic attribute dependency: ${[...o,a].join(" -> ")}`);o.push(a);try{let s=n.get(a),l=typeof a=="string"?ne(s):null,u=e.get(a);if(l){let c=d=>d?i(d):e.get(a);if(l.expression){let d=si(l.body);u=t(a,s,d,d.slots.map(c))}else u=Xr(l.body,c),e.get(a)==null&&(u=null)}return r.set(a,u),u}finally{o.pop()}};return new Map([...n.keys()].map(a=>[a,i(a)]))}function Ft(n,e){let t=new Map([...Object.entries(n.getAttr()),...n.fixedAttrItems()]),r=new Set,o=[],i=a=>{let s=ne(a);if(!s)return;let l=[];s.expression?l.push(...si(s.body).slots):Xr(s.body,u=>(l.push(u),""));for(let u of l.filter(Boolean)){if(!t.has(u))throw new Error(`Referenced Source attribute '${u}' does not exist`);if(o.includes(u))throw new Error(`Cyclic attribute dependency: ${[...o,u].join(" -> ")}`);r.has(u)||(o.push(u),i(t.get(u)),o.pop(),r.add(u))}};return i(e),r}var Ph={network:{maxAttempts:3,delay:1,backoff:2,jitter:!0,on:["TypeError","NetworkError","AbortError"]},aggressive:{maxAttempts:5,delay:.5,backoff:2,jitter:!0,on:["Error"]},gentle:{maxAttempts:2,delay:2,backoff:1.5,jitter:!1,on:["TypeError","NetworkError"]}};function Iy(n){let e=n._retryPolicy;return e==null?null:typeof e=="string"?Ph[e]||null:e}function Oy(n,e){return e.some(t=>t==="Error"?!0:n.name===t||n.constructor.name===t)}function Ry(n){return new Promise(e=>setTimeout(e,n))}async function By(n,e){if(!e)return n();let t=e.maxAttempts||3,r=e.delay||1,o=e.backoff||2,i=e.jitter!==!1,a=e.on||["Error"],s=null,l=r*1e3;for(let u=0;u<t;u++)try{let c=n();return c instanceof Promise?await c:c}catch(c){if(s=c,u<t-1&&Oy(c,a)){let d=l;i&&(d*=1+Math.random()*.1),await Ry(d),l*=o}else throw c}throw s}var fe=class n{static classKwargs={cacheTime:0,readOnly:!1,asBag:null,retryPolicy:null};static classArgs=[];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy"]);constructor(e={}){let r={...this.constructor.classKwargs,...e};for(let i of["interval","reactive"])if(Object.hasOwn(r,i))throw new TypeError(`Removed resolver option: ${i}. Schedule updates in the application; use reset() and read explicitly.`);this.cacheTime=r.cacheTime,this._readOnly=r.readOnly,this._asBag=r.asBag,this._retryPolicy=r.retryPolicy,this._kw={};let o=this.constructor.internalParams;for(let[i,a]of Object.entries(r))o.has(i)||(this._kw[i]=a);this._lastUpdate=null,this._node=null,this._lastEffectiveFingerprint=null,this._cachedValue=null,this.init()}init(){}setNode(e){e!==this._node&&!this.readOnly&&this._lastUpdate!==null&&this.reset(),this._node=e,this.onSetResolver(e)}onSetResolver(e){}get node(){return this._node}get cacheTime(){return this._cacheTime}set cacheTime(e){if(typeof e=="boolean")throw new TypeError("cacheTime must be numeric; use a negative value for infinite caching");this._cacheTime=e}get readOnly(){return this._readOnly}get expired(){return this._cacheTime<0?this._lastUpdate===null:this._cacheTime===0||this._lastUpdate===null?!0:(Date.now()-this._lastUpdate)/1e3>this._cacheTime}reset(...e){if(e.length)throw new TypeError("reset() takes no arguments. It invalidates the cache for the next explicit read.");this._lastUpdate=null,this._lastEffectiveFingerprint=null}get cachedValue(){return!this.readOnly&&this._node?this._node._value:this._cachedValue}set cachedValue(e){!this.readOnly&&this._node?this._node.setValue(e,!1):this._cachedValue=e}_computeEffectiveFingerprint(e){return JSON.stringify(Object.entries(e).sort())}_buildEffectiveKw(){let e={...this._kw};if(this._node&&this._node.attr)for(let t of Object.keys(this._kw))Object.hasOwn(this._node.attr,t)&&(e[t]=this._node.attr[t]);return e}resolve(e={}){let{static:t=!1,...r}=e;if(t)return this._node?this._node._value:this.cachedValue;let o=this._buildEffectiveKw();if(Object.keys(r).length>0)return this._load({...o,...r},a=>this._prepareValue(a));let i=this._computeEffectiveFingerprint(o);return i===this._lastEffectiveFingerprint&&!this.expired?this.cachedValue:(this._lastEffectiveFingerprint=i,this._load(o,a=>this._finalize(a)))}_load(e,t){let r=Iy(this),o=()=>this.load(e);if(r)return By(o,r).then(t);let i=o();return i&&typeof i.then=="function"?i.then(t):t(i)}_finalize(e){return e=this._prepareValue(e),this._lastUpdate=Date.now(),(!this.readOnly||this.cacheTime!==0)&&(this.cachedValue=e),e}_prepareValue(e){let t;return this._asBag===!0?t=!0:this._asBag===!1?t=!1:t=!this._readOnly,t&&e!==null&&e!==void 0&&(e=this._convertToBag(e)),e}_convertToBag(e){let t=n._BagClass;if(!t||e&&typeof e._htraverse=="function")return e;if(typeof e=="string"){if(e=e.trim(),e.startsWith("<")&&t.fromXml)return t.fromXml(e);if((e.startsWith("{")||e.startsWith("["))&&t.fromTytx)return t.fromTytx(e)}return e}static registerBagClass(e){n._BagClass=e}load(e){return null}};fe._BagClass=null;var xr=class extends fe{static classKwargs={cacheTime:0,readOnly:!1,asBag:!1,retryPolicy:null,callback:null};static classArgs=["callback"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy","callback"]);constructor(e={}){typeof e=="function"&&(e={callback:e}),super(e),this._callback=e.callback||null}load(e){return this._callback?this._callback.call(this,e):null}};var xt=class n{constructor(e,t,r=null,o=null,i=null,a=null,s=null,l=!0){this.label=t,this._value=null,this._attr={},this._parentBag=null,this._resolver=null,this._nodeSubscribers={},this._onChangedValue=null,this.nodeTag=a,this.xmlTag=s,this._compiled=null,this.parentBag=e,o&&this.setAttr(o,!1,!0,l),r!==null&&this.setValue(r,!1),i&&(this.resolver=i)}get parentBag(){return this._parentBag}set parentBag(e){e===null&&this._value?.parentNode===this&&this._value.setBackref(),this._parentBag=e,e?.backref&&this._value&&typeof this._value._htraverse=="function"&&this._value.setBackref(this,e)}get value(){return this.getValue()}set value(e){this.setValue(e)}getValue(e=!1,t=null,r={}){if(t!==null){let o=j(`${t}::QS`);if(Array.isArray(o)){let i=o.length?o:Object.keys(this._attr),a=i.map(l=>{let u=this.getAttr(l);return!e&&u instanceof fe?u.resolve():u}),s=l=>o.length===0?Object.fromEntries(i.map((u,c)=>[u,l[c]])):l.length===1?l[0]:l;return a.some(l=>l&&typeof l.then=="function")?Promise.all(a).then(s):s(a)}else{if(!this._resolver)throw new Error("Cannot use kwargs syntax without resolver");r={...r,...o}}}return this._resolver!==null?this._resolver.resolve({static:e,...r}):this._value}setValue(e,t=!0,r=null,o=null,i=!0,a=null,s=!1){e instanceof fe?(this.resolver=e,e=null):e instanceof n&&(r=r||{},Object.assign(r,e._attr),e.resolver&&(this.resolver=e.resolver),e=e._value);let l=this._value;l!==e&&l?.parentNode===this&&l.setBackref(),this._value=e;let u=l!==this._value,c=t??!0,d=null;if(r!==null){let h={...this._attr};this.setAttr(r,!1,o,i);let p=this._buildAttrDiff(h,this._attr);d=Object.keys(p).length>0?p:null}t=c&&(u||d!==null);let f=d?u?"upd_value_attr":"upd_attrs":"upd_value";if(this._onChangedValue&&this._onChangedValue(this,e,l,c),t){let h=d!==null?{oldvalue:l,attrs_diff:d}:{oldvalue:l};for(let p of Object.values(this._nodeSubscribers))p({node:this,info:h,evt:f})}this._parentBag!==null&&this._parentBag.backref&&(e&&typeof e._htraverse=="function"&&e.setBackref(this,this._parentBag),t&&this._parentBag._onNodeChanged(this,[this.label],f,l,d,a,s))}replace(e){if(!(e instanceof n))throw new TypeError("BagNode.replace expects a BagNode");if(e===this)return this;let t=e.staticValue;t&&typeof t._htraverse=="function"&&(t=t.createChildBag().replace(t));let r=null;e.resolver&&(r=Object.create(Object.getPrototypeOf(e.resolver),Object.getOwnPropertyDescriptors(e.resolver)),r._node=null,r._kw={...e.resolver._kw});let o=this._value,i={...this._attr},a=this.resolver;a&&a._node===this&&(a._node=null),this.resolver=r,this.setValue(t,!1,{...e.attr},!1,!1,null);let s=this._buildAttrDiff(i,this._attr),l=Object.keys(s).length?s:null,u=o!==t||a!==r;if(u||l){let c=l?u?"upd_value_attr":"upd_attrs":"upd_value",d=l?{oldvalue:o,attrs_diff:l}:{oldvalue:o};for(let f of Object.values(this._nodeSubscribers))f({node:this,info:d,evt:c});this._parentBag!==null&&this._parentBag.backref&&this._parentBag._onNodeChanged(this,[this.label],c,o,l)}return this}get staticValue(){return this._value}set staticValue(e){this._value=e}get resolver(){return this._resolver}set resolver(e){this._resolver=e,e&&e.setNode&&e.setNode(this)}resetResolver(){if(!this._resolver)throw new Error("Cannot reset resolver: node has no resolver");this._resolver.reset(),this.setValue(null)}get attr(){return this._attr}getAttr(e=null,t=null){return e?e in this._attr?this._attr[e]:t:this._attr}_buildAttrDiff(e,t){let r={},o=new Set([...Object.keys(e),...Object.keys(t)]);for(let i of o){let a=i in e?e[i]:null,s=i in t?t[i]:null;a!==s&&(r[i]={old:a,new:s})}return r}setAttr(e=null,t=!0,r=!0,o=!0){let i=e||{},a=Object.keys(this._nodeSubscribers).length>0,l=t&&(a||this._parentBag!==null&&this._parentBag.backref)?{...this._attr}:null;if(r?Object.assign(this._attr,i):this._attr={...i},o)for(let u of Object.keys(this._attr))this._attr[u]===null&&delete this._attr[u];if(t&&l!==null){let u=this._buildAttrDiff(l,this._attr);if(Object.keys(u).length>0&&a)for(let c of Object.values(this._nodeSubscribers))c({node:this,info:{attrs_diff:u},evt:"upd_attrs"});if(Object.keys(u).length>0&&this._parentBag!==null&&this._parentBag.backref){let c=t===!0?"true":String(t);this._parentBag._onNodeChanged(this,[this.label],"upd_attrs",null,u,c)}}}delAttr(...e){for(let t of e)if(typeof t=="string"&&t.includes(","))for(let r of t.split(","))delete this._attr[r.trim()];else delete this._attr[t]}hasAttr(e,t=null){return e in this._attr?t!==null?this._attr[e]===t:!0:!1}getInheritedAttributes(){let e={};return this._parentBag&&this._parentBag.parentNode&&(e=this._parentBag.parentNode.getInheritedAttributes()),{...e,...this._attr}}subscribe(e,t){this._nodeSubscribers[e]=t}unsubscribe(e){delete this._nodeSubscribers[e]}get compiled(){return this._compiled||(this._compiled={}),this._compiled}get isBranch(){return this._value!=null&&typeof this._value._htraverse=="function"}get position(){return this._parentBag===null?null:this._parentBag._nodes.index(this.label)}get fullpath(){if(this._parentBag!==null){let e=this._parentBag.fullpath;return e?`${e}.${this.label}`:this.label}return null}get parentNode(){return this._parentBag?this._parentBag.parentNode:null}attributeOwnerNode(e,t=null){let r=this;if(t===null)for(;r&&!(e in r._attr);)r=r.parentNode;else for(;r&&r._attr[e]!==t;)r=r.parentNode;return r}asTuple(){return[this.label,this.value,this._attr,this._resolver||null]}isEqual(e){if(!(e instanceof n)||this.label!==e.label)return!1;let t=Object.keys(this._attr),r=Object.keys(e._attr);if(t.length!==r.length)return!1;for(let o of t)if(this._attr[o]!==e._attr[o])return!1;return this._resolver!==null?this._resolver===e._resolver:this._value&&typeof this._value.equalTo=="function"?this._value.equalTo(e._value):this._value&&typeof this._value.isEqual=="function"?this._value.isEqual(e._value):this._value===e._value}diff(e){if(this.label!==e.label)return`Other label: ${e.label}`;let t=Object.keys(this._attr),r=Object.keys(e._attr);return t.length!==r.length||t.some(o=>this._attr[o]!==e._attr[o])?`attributes self:${JSON.stringify(this._attr)} --- other:${JSON.stringify(e._attr)}`:this._value!==e._value?`value self:${this._value} --- other:${e._value}`:null}toJson(e=!0){let t=this.value;return t&&typeof t.toJson=="function"&&(t=t.toJson(e,!0)),{label:this.label,value:t,attr:this._attr}}toString(){return`BagNode : ${this.label}`}};var li=class n{constructor(){this._dict=Object.create(null),this._list=[],this._parentBag=null}index(e){if(e in this._dict)return this._list.findIndex(r=>r.label===e);let t=e.match(/^#(\d+)$/);if(t){let r=parseInt(t[1],10);return r<this._list.length?r:-1}if(t=e.match(/^#(\w*)=(.*)$/),t){let[,r,o]=t,i=o.includes("::")?j(o):o;return r?this._list.findIndex(a=>a.getAttr(r)===i):this._list.findIndex(a=>a._value===i)}return-1}_parsePosition(e){let t=this._list.length;if(e==null||e===">")return t;if(typeof e=="number")return e<0&&(e=t+e),Math.max(0,Math.min(e,t));if(e==="<")return 0;if(e.startsWith("#")){let r=this._parseSharpIndex(e.slice(1),e);return Math.min(r,t)}if(e.startsWith("<")){let r=e.slice(1);if(r.startsWith("#")){let i=this._parseSharpIndex(r.slice(1),e);return Math.min(i,t)}let o=this.index(r);if(o<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return o}if(e.startsWith(">")){let r=e.slice(1);if(r.startsWith("#")){let i=this._parseSharpIndex(r.slice(1),e);return Math.min(i+1,t)}let o=this.index(r);if(o<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return o+1}throw new Error(`Invalid node_position '${e}': unrecognized syntax`)}_parseSharpIndex(e,t){if(!/^-?\d+$/.test(e))throw new Error(`Invalid node_position '${t}': '${e}' is not an integer`);let r=parseInt(e,10);if(r<0)throw new Error(`Invalid node_position '${t}': negative index not allowed in '#n' syntax`);return r}get(e){if(typeof e=="number")return e>=0&&e<this._list.length?this._list[e]:null;if(e.startsWith("#")){let t=this.index(e);return t>=0?this._list[t]:null}return this._dict[e]||null}set(e,t,r=">",o=null,i=null,a=null,s=!1,l=!0,u=null,c=!0,d=!1,f=null){let h=null;if(e.includes("?")&&([e,h]=e.split("?",2)),e==null||e.startsWith("#"))throw new Error("Cannot create new node with #n syntax");if(h){let m=h.split("&");if(m.length===1)o={[m[0]]:t};else{if(!Array.isArray(t)||t.length!==m.length)throw new Error("Wrong attributes assignment");o={};for(let b=0;b<m.length;b++)o[m[b]]=t[b]}t=null}let p=this._dict[e];if(p)f&&(p.nodeTag=f),a!==null&&(a===!1?p.resolver=null:p.resolver=a),h?p.setAttr(o,c,!0,l):p.setValue(t,c,o,s,l,u,d);else{let m=i&&i.nodeClass?i.nodeClass:xt;p=new m(i,e,h?null:t,o,a,f,null,l);let b=this._parsePosition(r);this._dict[e]=p,this._list.splice(b,0,p),c&&i&&i.backref&&i._onNodeInserted(p,b,null,u,d)}return d&&p.setValue(null,!1),p}pop(e){let t=this.get(e);if(t){delete this._dict[t.label];let r=this._list.indexOf(t);return r>=0&&this._list.splice(r,1),t}return null}has(e){return e in this._dict}get length(){return this._list.length}clear(){this._dict=Object.create(null),this._list=[]}keys(){return this._list.map(e=>e.label)}values(){return this._list.map(e=>e.getValue())}items(){return this._list.map(e=>[e.label,e.getValue()])}[Symbol.iterator](){return this._list[Symbol.iterator]()}move(e,t,r=!0){if(t<0)return;let o=Array.isArray(e)?e:[e];if(o.length===0||t>=this._list.length)return;let i=this._list[t].label;if(o.length>1){let a=[...o].sort((c,d)=>c-d),s=a[0]<t?1:0,l=[];for(let c=a.length-1;c>=0;c--){let d=a[c];if(d>=0&&d<this._list.length){let f=this._list[d];this._list.splice(d,1),l.push(f),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeDeleted(f,d)}}let u=this.index(i);u<0&&(u=this._list.length),u+=s;for(let c of l)this._list.splice(u,0,c),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(c,u)}else{let a=o[0];if(a===t||a<0||a>=this._list.length)return;let s=this._list[a];this._list.splice(a,1),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeDeleted(s,a),this._list.splice(t,0,s),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(s,t)}}isEqual(e){if(!(e instanceof n)||this._list.length!==e._list.length)return!1;for(let t=0;t<this._list.length;t++){let r=this._list[t],o=e._list[t];if(!r.isEqual(o))return!1}return!0}};var qh=Od(Au(),1);var Lu="::RSLV:",Ja=new Map,Qa=new Map,es=new WeakMap,Te=class extends Error{constructor(e){super(e),this.name="BagSerializationError"}},Qn=class extends fe{constructor(e){super({asBag:!1}),es.set(this,e)}get payload(){return es.get(this)}load(){throw new Te("This resolver is opaque; local execution is unavailable")}};function Fu(n,{module:e,name:t,encode:r,decode:o}){if(!(n.prototype instanceof fe)||n===Qn||typeof e!="string"||!e||typeof t!="string"||!t||typeof r!="function"||typeof o!="function")throw new TypeError("registerResolver requires a BagResolver subclass, module, name and adapters");let i=JSON.stringify([e,t]);if(Ja.has(i)&&Ja.get(i).cls!==n)throw new TypeError(`Resolver ${e}.${t} is already registered`);if(Qa.has(n)&&Qa.get(n).key!==i)throw new TypeError("A resolver class cannot own two wire identities");let a={cls:n,module:e,name:t,encode:r,decode:o,key:i};Ja.set(i,a),Qa.set(n,a)}function Lh(n){if(!n||typeof n!="object"||Array.isArray(n)||typeof n.resolver_module!="string"||typeof n.resolver_class!="string"||!Array.isArray(n.args??[])||!n.kwargs||typeof n.kwargs!="object"||Array.isArray(n.kwargs))throw new Te("Invalid resolver description")}function Fh(n,e=new Set){if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(typeof n!="object"||e.has(n)||!Array.isArray(n)&&Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw new Te("Resolver parameters must be JSON data; callbacks cannot travel");e.add(n);for(let t of Object.values(n))Fh(t,e);e.delete(n)}}function ui(n){if(es.has(n))return es.get(n);let e=Qa.get(n.constructor);if(!e)throw new Te(`Unregistered resolver: ${n.constructor.name}`);let t=e.encode(n),r={resolver_module:e.module,resolver_class:e.name,args:t.args??[],kwargs:t.kwargs??{}};return Lh(r),Fh(r),Lu+JSON.stringify(r)}function ts(n){if(typeof n!="string"||!n.startsWith(Lu))return null;let e=n.slice(Lu.length);if(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+$/.test(e))return new Qn(n);let t;try{t=JSON.parse(e)}catch{throw new Te("Invalid resolver JSON or signed token")}Lh(t);let r=Ja.get(JSON.stringify([t.resolver_module,t.resolver_class]));if(!r)return new Qn(n);let o=r.decode({args:t.args??[],kwargs:t.kwargs});if(!(o instanceof r.cls))throw new Te("Resolver decoder returned an incompatible instance");return o}function rs(n){return Object.fromEntries(Object.entries(n||{}).map(([e,t])=>[e,t instanceof fe?ui(t):t]))}function ju(n){return Object.fromEntries(Object.entries(n||{}).map(([e,t])=>[e,ts(t)??t]))}var kt="__cls";function eo(n,e){return n!==null&&n.tytxSuffix===e?n:ai(e)}function $y(n){let e=n.tytxSuffix,t=Object.entries(pt(e)).filter(([,r])=>r===n).map(([r])=>r);if(t.length===0)throw new Te(`${n.name} is not in the TYTX subtype dictionary of '${e}'`);if(t.length>1)throw new Te(`${n.name} is in the TYTX subtype dictionary of '${e}' under several names: ${t.sort().join(", ")}`);return t[0]}function qu(n,e){let t=pt(n);if(!Object.hasOwn(t,e))throw new Te(`Unknown Bag class '${e}' for TYTX type '${n}'`);return t[e]}function Uu(n,e){return n===e?null:$y(n)}function*Uh(n,e=[]){for(let t of n){let r=[...e,t.label];yield[r,t];let o=t.getValue(!0);!t.resolver&&o instanceof E&&(yield*Uh(o,r))}}function My(n){let e=n.toISOString(),t=n.getUTCFullYear()===1970&&n.getUTCMonth()===0&&n.getUTCDate()===1,r=n.getUTCHours()===0&&n.getUTCMinutes()===0&&n.getUTCSeconds()===0&&n.getUTCMilliseconds()===0;if(r&&!t)return e.slice(0,e.indexOf("T"));let o=e.replace(/\.000Z$/,"Z");return t&&!r?o.slice(o.indexOf("T")+1):o}function to(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function kr(n){return typeof n=="string"?n.includes("::")?`${n}::T`:n:Array.isArray(n)?n.map(kr):to(n)?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,kr(t)])):n}function Vu(n){if(!to(n))throw new TypeError("Bag options must be an object");let{recursive:e=!0}=n;if(typeof e!="boolean")throw new TypeError("recursive must be a boolean");return e}var jh=!1,E=class n{static tytxSuffix="X";constructor(e=null,t={}){this._nodes=new li,this._backref=!1,this._parent=null,this._parentNode=null,this._rootAttributes=null,this._updSubscribers={},this._insSubscribers={},this._delSubscribers={},Vu(t),e!=null&&this.fillFrom(e,t)}get parent(){return this._parent}set parent(e){this._parent=e}get parentNode(){return this._parentNode}set parentNode(e){this._parentNode=e}get backref(){return!!this._backref}get nodeClass(){return xt}createChildBag(){return new this.constructor}get fullpath(){if(this._parent!==null&&this._parentNode!==null){let e=this._parent.fullpath;return e?`${e}.${this._parentNode.label}`:this._parentNode.label}return null}relativePath(e){let t=[],r=e;for(;r!==null;){if(r.parentBag===this)return t.push(r.label),t.reverse(),t.join(".");t.push(r.label),r=r.parentNode}return null}get length(){return this._nodes.length}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}get attributes(){return this._parentNode!==null?this._parentNode.getAttr():{}}get rootAttributes(){return this._rootAttributes}set rootAttributes(e){this._rootAttributes=e!==null?{...e}:null}_htraverseBefore(e){let t=this,r;for(typeof e=="string"?(e=e.replace(/\.\.\//g,"#parent."),r=e.split(".").filter(o=>o)):r=[...e];r.length&&r[0]==="#parent"&&t!==null;)r.shift(),t=t.parent;return[t,r]}_htraverse(e,t=!1,r=!0){let[o,i]=this._htraverseBefore(e);if(o===null)return[null,null];if(i.length===0)return[o,""];for(;i.length>1&&o instanceof n;){let a=i[0];if(a==="#parent"){if(o.parent===null||o.parent===void 0)break;i.shift(),o=o.parent;continue}let s=o._nodes.get(a);if(!s)break;let l=s.getValue(r);if(l instanceof n)i.shift(),o=l;else if(t){let u=o.createChildBag();s.setValue(u,!0,null,!0,!0,"autocreate"),i.shift(),o=u}else break}if(!t)return i.length>1?[null,null]:[o,i[0]];for(;i.length>1;){let a=i.shift();if(a.startsWith("#"))throw new ci("Not existing index in #n syntax");let s=o.createChildBag();o._nodes.set(a,s,">",null,o,null,!1,!0,"autocreate"),o=s}return[o,i[0]]}get(e,t=null,r=!0,o={}){if(!e)return this;if(e==="#parent")return this.parent;let i=null;e.includes("?")&&([e,i]=e.split("?",2));let a=this._nodes.get(e);return a?a.getValue(r,i,o):t}getItem(e,t=null,r=!1,o={}){if(!e)return this;let[i,a]=this._htraverse(e,!1,r);return i instanceof n?i.get(a,t,r,o):t}setItem(e,t,r=null,o=">",i=!1,a=!0,s=null,l=!1,u=!0,c=null,d=null){if(e==="")throw new RangeError("setItem requires a non-empty path");let[f,h]=this._htraverse(e,!0);return f._nodes.set(h,t,o,r,f,c,i,a,s,u,l,d)}_pop(e,t=null){let r=this._nodes.index(e);if(r>=0){let o=this._nodes.pop(r);return this.backref&&this._onNodeDeleted(o,r,null,t),o}return null}pop(e,t=null,r=null){let o=this.popNode(e,r);return o?o.value:t}delItem(e,t=null,r=null){return this.pop(e,t,r)}popNode(e,t=null){let[r,o]=this._htraverse(e,!1,!0);if(!r||!o)return null;let i=r._nodes.get(o);if(!i)return null;try{return r._pop(o,t)}finally{i.parentBag===r&&r._nodes._dict[i.label]!==i&&(i.parentBag=null)}}clear(){let e=[...this._nodes];this._nodes.clear(),this.backref&&this._onNodeDeleted(e,-1);for(let t of e)t.parentBag=null}getNode(e,t=!0,r=!1,o=null){if(e==null||e==="")return this.parentNode;if(typeof e=="number")return this._nodes.get(e);typeof e=="string"&&(e=e.split("?",1)[0]);let[i,a]=this._htraverse(e,r,t);if(i instanceof n&&a){let s=i._nodes.get(a);if(s)return s;if(r)return i._nodes.set(a,o,">",null,i,null,!1,!0,"autocreate"),i._nodes.get(a)}return null}setBackref(e=null,t=null){let r=this._backref;if(this._backref=!0,this._parent=t,this._parentNode=e,!r){this._nodes._parentBag=this;for(let o of this)o.parentBag=this}}delParentRef(){this._parent=null,this._parentNode=null,this._backref=!1}clearBackref(){if(this._backref){this._backref=!1,this._parent=null,this._parentNode=null,this._nodes._parentBag=null;for(let e of this){e.parentBag=null;let t=e.getValue(!0);t instanceof n&&t.clearBackref()}}}_onNodeChanged(e,t,r,o=null,i=null,a=null,s=!1){for(let l of Object.values(this._updSubscribers))l({node:e,pathlist:t,oldvalue:o,attrs_diff:i,evt:r,reason:a,fired:s});this._parent&&this._parentNode&&this._parent._onNodeChanged(e,[this._parentNode.label,...t],r,o,i,a,s)}_onNodeInserted(e,t,r=null,o=null,i=!1){let a=e.parentBag,s=e.getValue(!0);a!==null&&a.backref&&s instanceof n&&s.setBackref(e,a),r===null&&(r=[]);for(let l of Object.values(this._insSubscribers))l({node:e,pathlist:r,ind:t,evt:"ins",reason:o,fired:i});this._parent&&this._parentNode&&this._parent._onNodeInserted(e,t,[this._parentNode.label,...r],o,i)}_onNodeDeleted(e,t,r=null,o=null){for(let i of Object.values(this._delSubscribers))i({node:e,pathlist:r,ind:t,evt:"del",reason:o});this._parent&&this._parentNode&&(r===null&&(r=[]),this._parent._onNodeDeleted(e,t,[this._parentNode.label,...r],o))}_subscribe(e,t,r){r!=null&&(t[e]=r)}subscribe(e,t={}){if(Object.hasOwn(t,"timer")||Object.hasOwn(t,"interval"))throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");let{update:r=null,insert:o=null,delete:i=null,any:a=null}=t;this.backref||this.setBackref(),this._subscribe(e,this._updSubscribers,r||a),this._subscribe(e,this._insSubscribers,o||a),this._subscribe(e,this._delSubscribers,i||a)}unsubscribe(e,t={}){if(Object.hasOwn(t,"timer")||Object.hasOwn(t,"interval"))throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");let{update:r=!1,insert:o=!1,delete:i=!1,any:a=!1}=t;(r||a)&&delete this._updSubscribers[e],(o||a)&&delete this._insSubscribers[e],(i||a)&&delete this._delSubscribers[e]}[Symbol.iterator](){return this._nodes[Symbol.iterator]()}keys(){return this._nodes.keys()}values(){return this._nodes.values()}items(){return[...this._nodes].map(e=>({key:e.label,value:e.getValue()}))}get nodes(){return this.getNodes()}node(e){return this._nodes.get(e)}setAttr(e=null,t=null,r=!0){let o=n.prototype.getNode.call(this,e,!0,!0);o&&o.setAttr(t,!0,!0,r)}getAttr(e=null,t=null,r=null){let o=this.getNode(e);return o?o.getAttr(t,r):r}delAttr(e=null,...t){let r=this.getNode(e);r&&r.delAttr(...t)}getInheritedAttributes(){return this._parentNode?this._parentNode.getInheritedAttributes():{}}getNodes(e=null){return e?[...this._nodes].filter(t=>e(t)):[...this._nodes]}getNodeByValue(e,t){for(let r of this._nodes){let o=r.value;if(o instanceof n){if(o.getItem(e)===t)return r}else if(o&&o.get&&o.get(e)===t)return r}return null}getNodeByAttr(e,t,r=!1,o=!1){let i=t===void 0,a=r&&typeof t=="string"?t.toLowerCase():t,s=l=>{let u=[];for(let c of l._nodes){if(e in c.attr){let d=r&&typeof c.attr[e]=="string"?c.attr[e].toLowerCase():c.attr[e];if(i||d==a)return c}if(c._value instanceof n)if(o){let d=s(c._value);if(d)return d}else u.push(c._value)}for(let c of u){let d=s(c);if(d)return d}return null};return s(this)}isEmpty(e=!1,t=!1){if(this._nodes.length===0)return!0;for(let r of this._nodes){if(r._resolver!==null)return!1;let o=r.getValue(!0);if(o!=null&&!(e&&o===0)&&!(t&&o===""))return!1}return!0}query(e=null,t=null,r=!1,o=!1,i=!0,a=!0,s=null,l=!0){e||(e="#k,#v,#a");let u=this,c;if(typeof e=="string"){if(e.includes(":")){let[h,p]=e.split(":");u=this.getItem(h),e=p}c=e.split(",").map(h=>h.trim())}else c=e;let d=(h,p,m,b,w)=>{if(p==="#k")return h.label;if(p==="#p")return m;if(p==="#n")return h;if(typeof p=="function")return p(h);if(p==="#v"){let _=w();return b&&_ instanceof n?null:_}else if(p.startsWith("#v.")){let _=p.split(".").slice(1).join("."),y=w();return y&&y.getItem?y.getItem(_):null}else{if(p==="#__v")return h.getValue(!0);if(p.startsWith("#a")){let _=p.includes(".")?p.split(".").slice(1).join("."):null;return h.getAttr(_)}else{let _=w();return _&&_.getItem?_.getItem(p):null}}};function*f(){let h=0;function*p(m,b){for(let w of m._nodes){let _=b?`${b}.${w.label}`:w.label,y=!1,x,D=()=>(y||(x=w.getValue(l),y=!0),x);if((i&&a||(D()instanceof n?a:i))&&(t===null||t(w))&&(yield c.length===1?d(w,c[0],_,o,D):c.map(C=>d(w,C,_,o,D)),h++,s!==null&&h>=s))return;if(o){let C=D();if(C instanceof n&&(yield*p(C,_),s!==null&&h>=s))return}}}yield*p(u,"")}return r?f():[...f()]}getLeaves(){let e=[],t=(r,o)=>{for(let i of r._nodes){let a=o?`${o}.${i.label}`:i.label,s=i.getValue(!1);s instanceof n?t(s,a):e.push([a,s])}};return t(this,""),e}digest(e=null,t=null,r=!1){typeof t=="boolean"&&(console.warn("Bag.digest(what, asColumns) is deprecated; use digest(what, null, asColumns)."),r=t,t=null);let o=this.query(e,t,!1,!1,!0,!0,null,!1);if(r){if(!o||o.length===0)return(typeof e=="string"?e:"#k,#v,#a").split(",").map(l=>l.trim()).map(()=>[]);let i=[...o];if(i.length&&Array.isArray(i[0])){let a=i[0].length,s=[];for(let l=0;l<a;l++)s.push(i.map(u=>u[l]));return s}return[i]}return[...o]}columns(e,t=!1){typeof e=="string"&&(e=e.split(","));let r=t?"#a.":"",o=e.map(i=>`${r}${i}`).join(",");return this.digest(o,null,!0)}sum(e="#v",t=!1,r=null){if(t!=null&&typeof t!="boolean")throw new TypeError("sum strict must be a boolean; pass condition as the third argument");if(r!=null&&typeof r!="function")throw new TypeError("sum condition must be callable; deep is no longer supported");let o=i=>{let a=0,s=!1;for(let l of this.query(i,r)){if(l==null||l===""){s=!0;continue}if(typeof l!="number"&&typeof l!="boolean"){if(t)throw new TypeError(`sum encountered non-numeric value: ${typeof l}`);continue}a+=l}return t&&s?null:a};return e.includes(",")?e.split(",").map(i=>o(i.trim())):o(e)}sort(e="#k:a"){let t=(o,i)=>o==null?[-1,""]:i&&typeof o=="string"?[0,o.toLowerCase()]:[0,o],r=(o,i)=>o[0]!==i[0]?o[0]-i[0]:o[1]<i[1]?-1:o[1]>i[1]?1:0;if(typeof e=="function")this._nodes._list.sort((o,i)=>{let a=e(o),s=e(i);return a<s?-1:a>s?1:0});else{let o=e.split(",");o.reverse();for(let i of o){let a,s;i.includes(":")?[a,s]=i.split(":",2):(a=i,s="a"),a=a.trim(),s=s.trim();let l=s==="d"||s==="D",u=s==="a"||s==="d",c;if(a.toLowerCase()==="#k")c=d=>t(d.label,u);else if(a.toLowerCase()==="#v")c=d=>t(d.value,u);else if(a.toLowerCase().startsWith("#a.")){let d=a.slice(3);c=f=>t(f.getAttr(d),u)}else c=d=>{let f=d.value,h=f instanceof n?f.getItem(a):f?f[a]:null;return t(h,u)};this._nodes._list.sort((d,f)=>{let h=r(c(d),c(f));return l?-h:h})}}return this}equalTo(e){return e instanceof n?this._nodes.isEqual(e._nodes):!1}has(e){if(typeof e=="string"){let t=null;e.includes("?")&&([e,t]=e.split("?",2));let r=this.getNode(e);return r===null?!1:t===null?!0:t.split("&").every(o=>o in r.attr)}else if(e&&e.label!==void 0)return[...this._nodes].includes(e);return!1}getResolver(e){let t=this.getNode(e);return t?t.resolver:null}setResolver(e,t){let r=this.getNode(e);r||(this.setItem(e,null),r=this.getNode(e)),r.resolver=t}setCallbackItem(e,t,r={}){let o=new xr({callback:t,...r});this.setResolver(e,o)}move(e,t,r=!0){this._nodes.move(e,t,r)}asDict(e=!1,t=!1,r=!1,o=!1){let i={};for(let a of this._nodes){let s=a.value;if(o&&s==null)continue;let l=a.label;e&&(l=String(l)),t&&(l=l.toLowerCase()),r&&s instanceof n&&(s=n.prototype.asDict.call(s,e,t,r,o)),Object.defineProperty(i,l,{value:s,enumerable:!0,writable:!0,configurable:!0})}return i}setdefault(e,t=null){let r=this.getNode(e);return r?r.value:(this.setItem(e,t),t)}deepcopy(e=!1){let t=this.createChildBag();for(let r of this._nodes){let o=r.getValue(!e);o instanceof n&&(o=o.deepcopy(e));let i=new t.nodeClass(t,r.label,o);i.setAttr({...r.attr},!1,!1,!1),i.nodeTag=r.nodeTag,i.xmlTag=r.xmlTag,t._nodes._list.push(i),t._nodes._dict[i.label]=i}return t}update(e,t=null,r=null,o=!1){if(!(e instanceof n)){for(let i in e){let a=e[i];(!o||a!==null||!this._nodes.has(i))&&this.setItem(i,a,null,">",!1,!1,r,!1,r!==!1)}return}for(let i of[...e]){let a=i.label,s=t==="static"?i.resolver:null,l=s?null:i.getValue(),u=i.attr.__replace;delete i.attr.__replace;let c=this._nodes.get(a);if(c)if(c.setAttr(i.attr,r===null?!0:r,!0,!1),i.nodeTag!=null&&(c.nodeTag=i.nodeTag),i.xmlTag!=null&&(c.xmlTag=i.xmlTag),s)c.resolver=s,c.setValue(null,r===null?!0:r,null,null,!1,r);else{i.resolver&&(c.resolver=null);let d=c.getValue();l instanceof n&&d instanceof n&&!u?d.update(l,t,r,o):(!o||l!==null)&&c.setValue(l,r===null?!0:r,null,null,!1,r)}else{let d=this.setItem(a,s||l,i.attr,">",!1,!1,r,!1,r!==!1);d.nodeTag=i.nodeTag,d.xmlTag=i.xmlTag}}}_fillFromBag(e){this.clear();for(let t of e){let r=new this.nodeClass(this,t.label);r.replace(t),r.nodeTag=t.nodeTag,r.xmlTag=t.xmlTag,this._nodes._list.push(r),this._nodes._dict[r.label]=r}}_appendLiteral(e,t,r=null,o=null,i=null){if(typeof e!="string")throw new TypeError("Bag labels must be strings");let a=new this.nodeClass(this,e,null,r,o,i,null,!1);return t instanceof fe?a.resolver=t:a._value=t,this._nodes._dict[e]=a,this._nodes._list.push(a),a}fillFrom(e=null,t={}){let r=Vu(t);if(e!=null&&!to(e)&&!Array.isArray(e))throw new TypeError("Bag source must be a dictionary, array or null");let o=this.createChildBag(),i=new Set,a=(s,l,u)=>{if(i.has(l))throw new TypeError(`Cyclic Bag source at ${u}`);i.add(l);try{let c=Array.isArray(l)?String(l.length).length+1:0,d=Array.isArray(l)?Array.from(l,(f,h)=>[`r_${String(h).padStart(c,"0")}`,f]):Object.entries(l);if(!Array.isArray(l)&&Object.getOwnPropertySymbols(l).some(f=>Object.prototype.propertyIsEnumerable.call(l,f)))throw new TypeError(`Bag labels must be strings at ${u}`);for(let[f,h]of d){let p=h;r&&(to(p)||Array.isArray(p))&&(p=this.createChildBag(),a(p,h,`${u}[${JSON.stringify(f)}]`)),s._appendLiteral(f,p)}}finally{i.delete(l)}};return e!=null&&a(o,e,"$"),this._replacePrepared(o)}_loadSource(e,t={}){return this.fillFrom(e,t)}replace(e){if(!(e instanceof n))throw new TypeError("Bag.replace expects a Bag");if(e===this)return this;let t=this.createChildBag();return t._fillFromBag(e),this._replacePrepared(t)}_replacePrepared(e){for(let r of this._nodes){r.parentBag=null;let o=r.getValue(!0);o instanceof n&&o.clearBackref()}let t=this._nodes;this._nodes=e._nodes,e._nodes=t,this._nodes._parentBag=this.backref?this:null,e._nodes._parentBag=null;for(let r of this._nodes)r.parentBag=this;for(let r of e._nodes)r._parentBag=e;return this.backref&&this.parent&&this.parentNode&&this.parent._onNodeChanged(this.parentNode,[this.parentNode.label],"upd_value",e),this}forEach(e,{static:t=!0,deep:r=!1,kwargs:o={}}={}){if(typeof e!="function")throw new TypeError("forEach requires a callback");let i=(a,s)=>{for(let l=0;l<a._nodes.length;l++){let u=a._nodes._list[l],c={...s};"_pathlist"in s&&(c._pathlist=[...s._pathlist,u.label]),"_indexlist"in s&&(c._indexlist=[...s._indexlist,l]);let d=e(u,c,l);if(d)return d;if(d==null&&r){let f=u.getValue(t);if(f instanceof n){let h=i(f,c);if(h)return h}}}return null};return i(this,o)}*traverse(){for(let e of this._nodes){yield e;let t=e.getValue(!0);t instanceof n&&(yield*t.traverse())}}*_iterNodesWithPaths(e=!0,t=""){for(let r of this._nodes){let o=t?`${t}.${r.label}`:r.label;yield[o,r];let i=r.getValue(e);i instanceof n&&(yield*i._iterNodesWithPaths(e,o))}}*_nodeFlattener(e=null){let t=e!==null,r=t?Object.create(null):null,o=0,i=new Map([["[]",this.constructor]]);for(let[a,s]of Uh(this)){let l=a.slice(0,-1),u=JSON.stringify(a),c=JSON.stringify(l),d=s.getValue(!0),f,h=null;if(s.resolver)f=ui(s.resolver);else if(d instanceof n){let b=d.constructor,w=b.tytxSuffix;i.set(u,b),h=Uu(b,eo(i.get(c),w)),f=`::${w}`}else d===null?f="::NN":f=kr(d);if(s.attr&&Object.hasOwn(s.attr,kt))throw new Te(`node '${a}': the attribute '${kt}' is reserved for the Bag class name`);let p=rs(kr(s.attr));h!==null&&(p[kt]=h);let m=s.nodeTag;t?(yield[l.length?r[c]:null,s.label,m,f,p],d instanceof n&&(r[u]=o,e[o]=a,o++)):yield[l,s.label,m,f,p]}}toTytx(e="json",t=!1){let r=this._toTytxPayload(t),o=this.constructor.tytxSuffix;if(e==="json")return`${r}::${o}`;if(e==="msgpack")return Ta(new vt(4,new TextEncoder().encode(`${o}:${r}`)));throw new TypeError(`Unsupported transport: ${e}`)}_toTytxPayload(e=!1){let t;if(e){let i={};t={rows:[...this._nodeFlattener(i)],paths:i}}else t={rows:[...this._nodeFlattener(null)]};let r=this.constructor,o=Uu(r,eo(null,r.tytxSuffix));return o!==null&&(t[kt]=o),t.rows=t.rows.map(([i,a,s,l,u])=>[kr(i),kr(a),kr(s),l,u]),t.paths&&(t.paths=kr(t.paths)),L(t)}static fromTytx(e,t="json",r={}){if(to(t)&&(r=t,t="json"),Vu(r),typeof e!="string"&&!(e instanceof Uint8Array))throw new TypeError("fromTytx requires serialized text or bytes");if(t!=="json"&&t!=="msgpack")throw new TypeError(`Unsupported transport: ${t}`);t==="json"&&e instanceof Uint8Array&&(e=new TextDecoder().decode(e));let o=j(e,t==="json"?null:t);if(o instanceof n)return o;if(!to(o)&&!Array.isArray(o))throw new TypeError("fromTytx requires a dictionary, array or typed Bag root");return new this(o,r)}static _fromTytxPayload(e){let t=this.tytxSuffix;if(e==="")return new(eo(null,t));let r=j(e);if(!r||!Array.isArray(r.rows))throw new Te("Invalid TYTX Bag: expected rows");let o=r.paths,i=o!=null,a=Object.hasOwn(r,kt)?qu(t,r[kt]):eo(null,t),s=new a,l=new Map([["[]",s]]);for(let u of r.rows){if(!Array.isArray(u)||u.length!==5)throw new Te("Invalid TYTX Bag row");let[c,d,f,h,p]=u,m=c??"";if(i){if(c!==null&&!Object.hasOwn(o,c))throw new Te(`Unknown TYTX parent reference: ${c}`);m=c===null?"":o[c]}if(typeof m=="string"&&(m=m?m.split("."):[]),!Array.isArray(m))throw new Te("Invalid TYTX parent path");let b=JSON.stringify(m);if(!l.has(b))throw new Te(`Missing or undecodable TYTX parent branch: ${m}`);let w=l.get(b),_=JSON.stringify([...m,d]),y=h,x=ts(y),D=ju(p),k=Object.hasOwn(D,kt)?D[kt]:null;if(delete D[kt],y instanceof n){let O=y.constructor.tytxSuffix,$=k!==null?qu(O,k):eo(w.constructor,O);y=new $,l.set(_,y)}else if(k!==null)throw new Te(`node '${_}': the attribute '${kt}' is reserved for the Bag class name of a branch`);let C=w._appendLiteral(d,x?null:y,D,x);C.nodeTag=f??null}return s}toXml(e={}){let{pretty:t=!1,encoding:r="UTF-8",docHeader:o=null,selfClosedTags:i=null}=e,a=this._bagToXml(i,t);return o===!0?a=`<?xml version='1.0' encoding='${r}'?>
|
|
32
32
|
${a}`:typeof o=="string"&&(a=`${o}
|
|
33
33
|
${a}`),a}_bagToXml(e=null,t=!1,r=0){let o=[];for(let i of this._nodes)o.push((t?" ".repeat(r):"")+this._nodeToXml(i,e,t,r));return o.join(t?`
|
|
34
|
-
`:"")}_nodeToXml(e,t=null,r=!1,o=0){let i=e.xmlTag||e.nodeTag||e.label,a=this._sanitizeTag(i),s=[];if(a!==i&&s.push(`_tag="${this._escapeAttr(i)}"`),e.resolver&&s.push(`_resolver="${this._escapeAttr(ui(e.resolver))}"`),e.attr)for(let[f,h]of Object.entries(
|
|
34
|
+
`:"")}_nodeToXml(e,t=null,r=!1,o=0){let i=e.xmlTag||e.nodeTag||e.label,a=this._sanitizeTag(i),s=[];if(a!==i&&s.push(`_tag="${this._escapeAttr(i)}"`),e.resolver&&s.push(`_resolver="${this._escapeAttr(ui(e.resolver))}"`),e.attr)for(let[f,h]of Object.entries(rs(e.attr)))h!==null&&h!==!1&&h!==void 0&&s.push(`${f}="${this._escapeAttr(String(h))}"`);let l=s.length?" "+s.join(" "):"",u=e.resolver?null:e.getValue(!0);if(u&&typeof u._bagToXml=="function"){r=r&&e.attr?.["xml:space"]!=="preserve";let f=u._bagToXml(t,r,o+1);return f?r?`<${a}${l}>
|
|
35
35
|
${f}
|
|
36
|
-
${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}${l}/>`:`<${a}${l}></${a}>`}if(u==null||u==="")return t===null||t.includes(a)?`<${a}${l}/>`:`<${a}${l}></${a}>`;let c=u instanceof Date&&!Number.isNaN(u.getTime())?
|
|
36
|
+
${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}${l}/>`:`<${a}${l}></${a}>`}if(u==null||u==="")return t===null||t.includes(a)?`<${a}${l}/>`:`<${a}${l}></${a}>`;let c=u instanceof Date&&!Number.isNaN(u.getTime())?My(u):String(u),d=this._escapeXml(c);return`<${a}${l}>${d}</${a}>`}_sanitizeTag(e){return e?e.replace(/[^a-zA-Z0-9_\-.:]/g,"_"):"_none_"}_escapeXml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}_escapeAttr(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}static fromXml(e,t={}){let{tagAttribute:r=null}=t,o;if(typeof DOMParser<"u"){o=new DOMParser().parseFromString(e,"application/xml");let a=o.querySelector("parsererror");if(a)throw new Error(`XML parse error: ${a.textContent}`)}else o=new qh.DOMParser().parseFromString(e,"application/xml");return this._xmlElementToBag(o.documentElement,r)}static _xmlElementToBag(e,t=null){let r=new this,o=Array.from(e.childNodes).filter(i=>i.nodeType===1);for(let i of o){let a=i.tagName,s={};for(let m=0;m<i.attributes.length;m++){let b=i.attributes[m];s[b.name]=b.value}let l=ts(s._resolver);l&&delete s._resolver;let u=String(s._T||"").toUpperCase()==="BAG";Object.assign(s,ju(s));let c=a;"_tag"in s&&(c=s._tag,delete s._tag),t&&t in s&&(c=s[t],delete s[t]);let d=c,f=1;for(;r.getNode(c);)c=`${d}_${f++}`;let h=Array.from(i.childNodes).filter(m=>m.nodeType===1),p;if(h.length>0||u){let m=this._xmlElementToBag(i,t);p=r.setItem(c,m,Object.keys(s).length>0?s:null)}else{let m=i.textContent||"";p=r.setItem(c,m,Object.keys(s).length>0?s:null)}l&&(p.resolver=l),p.xmlTag=a}return r}static async fromUrl(e,t={}){let{timeout:r=30}=t,o={};r&&(o.signal=AbortSignal.timeout(r*1e3));let i=await fetch(e,o),a=i.headers.get("content-type")||"",s=await i.text();if(a.includes("json"))return n.fromTytx(s);if(a.includes("xml"))return n.fromXml(s);let l=s.trim();if(l.startsWith("<"))return n.fromXml(s);if(l.startsWith("{")||l.startsWith("["))return n.fromTytx(s);throw new ci(`Unsupported content-type: ${a}`)}toJson(e=!0){let t=[];for(let r of this._nodes)t.push(this._nodeToJsonDict(r,e));return e?L(t):JSON.stringify(t)}_nodeToJsonDict(e,t){let r=e.resolver?null:e.getValue(!0);if(r&&typeof r._nodeToJsonDict=="function"){let i=[];for(let a of r._nodes)i.push(r._nodeToJsonDict(a,t));r=i}let o={label:e.label,value:r,attr:rs(e.attr)};return e.nodeTag!==null&&(o.tag=e.nodeTag),e.resolver&&(o.resolver=ui(e.resolver)),o}static fromJson(e,t={}){return jh||(console.warn("Bag.fromJson is deprecated; use Bag.fromTytx"),jh=!0),this.fromTytx(e,"json",t)}toStringTree(e=!0,t=null,r="",o=!0){t===null&&(t=new Map);let i=[],a=[...this._nodes];for(let s=0;s<a.length;s++){let l=a[s],u=s===a.length-1,c=l.getValue(e),d=l.getAttr(),f="",h=Object.keys(d);h.length>0&&(f=" ["+h.map(w=>`${w}=${JSON.stringify(d[w])}`).join(", ")+"]");let p=u?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",m=r+(u?" ":"\u2502 ");if(c instanceof n){let b=l,w=c.backref?"(*)":"";if(t.has(b))i.push(`${r}${p}${l.label}${w}${f} \u2192 (circular ref)`);else{t.set(b,l.label),i.push(`${r}${p}${l.label}${w}${f}`);let _=c.toStringTree(e,t,m,u);_&&i.push(_)}}else{let b;if(c===null)b="null";else if(c===void 0)b="undefined";else if(c instanceof ArrayBuffer||c instanceof Uint8Array){let w=new TextDecoder("utf-8",{fatal:!1}),_=c instanceof ArrayBuffer?new Uint8Array(c):c;b=w.decode(_)}else typeof c=="string"?c.length>50?b=JSON.stringify(c.slice(0,47)+"..."):b=JSON.stringify(c):b=String(c);i.push(`${r}${p}${l.label}: ${b}${f}`)}}return i.join(`
|
|
37
37
|
`)}toString(e=!0,t=null,r=""){t||(t=new Set);let o=[],i=[...this._nodes];for(let a=0;a<i.length;a++){let s=i[a],l=a===i.length-1,u=s.getValue(e),c="",d=s.attr;d&&Object.keys(d).length>0&&(c=` [${Object.entries(d).map(([m,b])=>`${m}=${JSON.stringify(b)}`).join(", ")}]`);let f=l?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",h=r+(l?" ":"\u2502 ");if(u&&typeof u._htraverse=="function"){let p=s;if(t.has(p))o.push(`${r}${f}${s.label}${c} \u2192 (circular ref)`);else{t.add(p),o.push(`${r}${f}${s.label}${c}`);let m=u.toString(e,t,h);m&&o.push(m)}}else{let p;u==null?p="null":typeof u=="string"&&u.length>50?p=JSON.stringify(u.slice(0,47)+"..."):typeof u=="string"?p=JSON.stringify(u):p=String(u),o.push(`${r}${f}${s.label}: ${p}${c}`)}}return o.join(`
|
|
38
|
-
`)}},ci=class extends Error{constructor(e){super(e),this.name="BagException"}};fe.registerBagClass(E);Mu(E,"X",n=>n._toTytxPayload(),n=>E._fromTytxPayload(n));Wr(E.tytxSuffix,{...pt(E.tytxSuffix),Bag:E});var Uh=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield"]);function Vh(n){return n.endsWith("_")&&Uh.has(n.slice(0,-1))?n.slice(0,-1):n}function zh(n){let e=Vh(n);return e!==n?e:n.startsWith("_")&&Uh.has(n.slice(1))?n.slice(1):n}function di(n,{renderTag:e=null,ns:t=null,dialectName:r=null}={}){let o=e||n;if(!o)return o;if(o=Vh(o),t&&!e){let i=`${r}_`;o.startsWith(i)&&(o=o.slice(i.length)),o=`${t}:${o}`}return o}var ro=Symbol("value"),Xr=new Set(["_meta","datapath","nodeId","ns","form","formId","_anchor","updateOn"]);function Le(n){return Object.entries(n||{}).filter(([e])=>!Xr.has(e)).map(([e,t])=>[zh(e),t])}var Xe=class extends xt{constructor(e,t,r=null,o=null,i=null,a=null,s=null){super(e,t,r,o,i,a,s),this._builder=e?._insertingBuilder??e?._builder??null,this._targetId=null}get builder(){if(this._builder)return this._builder;let e=this.parentBag;return e?e._builder:null}get data(){return this.builder.data}get rootBuilder(){return this.parentBag.root._builder}_getMeta(e){let t=this.getAttr("_meta")||{},r=e.split(",").map(o=>o.trim());return r.length===1?t[r[0]]!==void 0?t[r[0]]:null:r.map(o=>t[o]!==void 0?t[o]:null)}pointerType(e){return typeof e=="string"&&(e[0]==="^"||e[0]==="=")&&!e.startsWith("==")?e[0]:null}pointers(){this.builder.validateCustomTypes(this);let e=[];for(let[t,r]of Object.entries(this.getAttr()||{}))this.pointerType(r)==="^"&&e.push([t,r.split(":",1)[0]]);return this.pointerType(this.value)==="^"&&e.push(["",this.value.split(":",1)[0]]),e}fixedAttrItems(){return Le(this.getAttr())}runtimeToEvaluate(){let e=new Map(this.fixedAttrItems());return e.set(ro,this.value),e}absDatapath(e){let t=e;this.pointerType(e)&&(e=(re(e)?.pointer??e).slice(1));let r=null;return e.includes("?")&&([e,r]=e.split("?",2)),e.startsWith("#")?this._finalizeAbsPath(this._resolveSymbolicDatapath(e,t),r):(e.startsWith(".")&&(e=this._composeRelativeDatapath(e,t)),this._finalizeAbsPath(e,r))}_finalizeAbsPath(e,t){return e=this._collapseParentDatapath(e,e),t?`${e}?${t}`:e}_composeRelativeDatapath(e,t){let r=this;for(;r!==null&&e.startsWith(".");){let o=r.getAttr("datapath");o!=null&&(e=e==="."?o:o+e),r=r.parentNode}if(e.startsWith("."))throw new Error(`unresolved relative datapath: ${t}`);return e}_collapseParentDatapath(e,t){let r=[];for(let o of e.split("."))if(o==="#parent"){if(r.length===0)throw new Error(`#parent has no segment to cancel: ${t}`);r.pop()}else r.push(o);return r.join(".")}_resolveSymbolicDatapath(e,t){let r=e.slice(1),o=r.indexOf("."),i=o===-1?r:r.slice(0,o),a=o===-1?"":r.slice(o+1),s;if(i==="FORM")s=this._findMarkedDatapathAncestor(!0,!1,t);else if(i==="ANCHOR")s=this._findMarkedDatapathAncestor(!1,!0,t);else{let l=this.rootBuilder;if(!l)throw new Error(`#<id>: cannot resolve ${t} on a node without builder`);if(s=l.source.getNodeByAttr("nodeId",i),s==null)throw new Error(`#<id>: cannot resolve ${t}`)}return s.absDatapath(a?`.${a}`:".")}_findMarkedDatapathAncestor(e,t,r){let o=this;for(;o!=null;){let a=o.getAttr()||{};if(e&&(a.formId!=null||a.form===!0)||t&&"_anchor"in a)return o;o=o.parentNode}let i=e?"FORM":"ANCHOR";throw new Error(`#${i}: no marked ancestor found for ${r}`)}getRelativeData(e,t=null,{autocreate:r=!1}={}){let o=this.data,i=this.absDatapath(e);return r&&o.getItem(i)==null&&o.setItem(i,t),o.getItem(i,t)}setRelativeData(e,t,{attributes:r=null,fired:o=!1,reason:i=null}={}){let a=this.data,s=this.absDatapath(e);a.setItem(s,t,r,">",!1,!0,i===null?!0:i,o)}fireEvent(e,t=!0,{attributes:r=null,reason:o=null}={}){this.setRelativeData(e,t,{attributes:r,fired:!0,reason:o})}SET(e,t){this.setRelativeData(e,t)}GET(e){return this.getRelativeData(e)}PUT(e,t){this.setRelativeData(e,t,{reason:!1})}FIRE(e,t=!0){this.setRelativeData(e,t,{fired:!0})}},I=class n extends E{constructor(e=null,t=null){super(e),this._builder=t,this._insertingBuilder=null}get nodeClass(){return Xe}_setBuilderItem(e,t,r,...o){let i=t?.map(([s])=>[s,s._builder])||null;if(t)for(let[s,l]of t)s._builder=l;let a=this._insertingBuilder;this._insertingBuilder=e;try{return this.setItem(r,...o)}catch(s){if(this.node(r)==null&&i)for(let[l,u]of i)l._builder=u;throw s}finally{this._insertingBuilder=a}}bindBuilder(e){if(!e)throw new Error("SourceBag.bindBuilder requires a builder");let t=this._builderBindingPlan(e);for(let[r,o]of t)r._builder=o;return this.setBackref(),this}_builderBindingPlan(e){let t=[],r=new WeakSet,o=(i,a)=>{if(r.has(i))throw new Error("source contains a cyclic or shared SourceBag branch");r.add(i),t.push([i,a]);for(let s of i.getNodes()){let l=a,u=s._getMeta("subbuilder");u!=null&&(l=a._resolveSubbuilderReference(u,s.getAttr()||{},s.nodeTag)),t.push([s,l]);let c=s.getValue(!0);c instanceof n&&o(c,l)}};return o(this,e),t}};if((pt(I.tytxSuffix).SourceBag??I)!==I)throw new Error("TYTX subtype name 'SourceBag' is already registered for another class");Wr(I.tytxSuffix,{...pt(I.tytxSuffix),SourceBag:I});function $y(n){if(n.length===0)return{value:null,attrs:{}};let e=n[0];if(e!==null&&typeof e=="object"){let t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null)return{value:null,attrs:e}}return{value:e,attrs:n[1]||{}}}var My=new Set(["then","toJSON"]),Gh=new WeakMap;function ie(n){return Gh.get(n)||n}function fi(n){if(n==null)return n;n=ie(n);let e=n._builder||n.parentBag&&n.parentBag._builder;return e?e.wrapSource(n):n}function Wh(n,e){let t=e instanceof E,r=new Proxy(e,{get(o,i){if(typeof i=="symbol"||i.startsWith("_")||My.has(i))return Reflect.get(o,i,o);let a=n.schemaTag(i);if(t&&a)return Hh(n,o,a,t);if(i in o){let l=Reflect.get(o,i,o);return typeof l=="function"?l.bind(o):l}if(a)return Hh(n,o,a,t);let s=n.containerMethod(i);if(s)return(...l)=>n[s](n.wrapSource(o),...l)}});return Gh.set(r,e),r}function Hh(n,e,t,r){return(...o)=>{let{value:i,attrs:a}=$y(o),s=r?n.bagCall(e,t,i,a):n.commandOnNode(e,t,i,a);return s.builder.wrapSource(s)}}function Vu(n,e,{transport:t="json"}={}){let r=F(n,t==="json"?null:t);if(!(r instanceof I))throw new TypeError("TYTX payload did not decode to SourceBag");return r.bindBuilder(e)}var Xh=/^[A-Za-z_][A-Za-z0-9_]*$/,Py=new Set(["positional_only","positional_or_keyword","keyword_only","var_positional","var_keyword"]),Ly=new Set(["framework","value","attribute"]),Fy=new Map([["builtins.str",n=>typeof n=="string"],["builtins.int",n=>Number.isInteger(n)],["builtins.float",n=>typeof n=="number"&&Number.isFinite(n)],["builtins.bool",n=>typeof n=="boolean"],["builtins.list",n=>Array.isArray(n)],["builtins.dict",n=>n!==null&&typeof n=="object"&&!Array.isArray(n)],["builtins.tuple",n=>Array.isArray(n)],["builtins.set",n=>Array.isArray(n)||n instanceof Set],["builtins.NoneType",n=>n===null],["builtins.object",n=>!0]]);function Kr(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function B(n,e){throw new TypeError(`${n}: ${e}`)}function jt(n,e,t,r){Kr(n)||B(r,"must be an object");for(let o of Object.keys(n))e.includes(o)||B(r,`unknown field '${o}'`);for(let o of t)Object.hasOwn(n,o)||B(r,`missing field '${o}'`)}function Jr(n,e){if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(Array.isArray(n))return n.forEach((t,r)=>Jr(t,`${e}[${r}]`));if(Kr(n))return Object.entries(n).forEach(([t,r])=>Jr(r,`${e}.${t}`));B(e,"must be lossless JSON data")}}function jy(n,e){let t="",r=!1;for(let o=0;o<n.length;o++){let i=n[o];if(i==="\\"){t+=i+(n[++o]??"");continue}i==="["&&(r=!0),!r&&i==="."&&!(e&16)?t+="[^\\n]":!r&&i==="^"&&e&8?t+="(?:^|(?<=\\n))":!r&&i==="$"?t+=e&8?"(?=\\n|(?![\\s\\S]))":"(?=\\n?(?![\\s\\S]))":t+=i,i==="]"&&(r=!1)}return t}function Zr(n,e,t=!1,r=null){if(n===null)return null;switch(jt(n,["kind","dtype","module","name","origin","arguments","items","values","base","metadata","pattern","flags","ge","le","gt","lt","value"],["kind"],e),n.kind){case"custom":return jt(n,["kind","name"],["kind","name"],e),r||B(e,"custom references require a catalog; nested catalog references are unsupported"),r.resolve(n.name,e);case"dtype":{jt(n,["kind","dtype"],["kind","dtype"],e);let o=n.dtype;typeof o!="string"&&B(e,"dtype must be a string");let i=ai(o);return!i&&o!=="NN"&&B(e,`unknown dtype '${o}'`),{...n,test:s=>o==="NN"?s===null:o==="N"?de(s)&&!["NaN","Infinity","-Infinity"].includes(s.toString()):i===Number?typeof s=="number"&&Number.isFinite(s)&&(o!=="L"||Number.isInteger(s)):i===String?typeof s=="string":i===Boolean?typeof s=="boolean":i===Date?s instanceof Date&&Number.isFinite(s.getTime()):i===Object?Kr(s)&&[Object.prototype,null].includes(Object.getPrototypeOf(s)):s instanceof i}}case"any":return{...n,test:o=>!0};case"type":{(typeof n.module!="string"||typeof n.name!="string")&&B(e,"type requires string module/name");let o=`${n.module}.${n.name}`;if(o==="collections.abc.Callable")return{...n,test:a=>typeof a=="function",portable:!1};let i=Fy.get(o);return i||B(e,`unsupported type '${o}'`),{...n,test:i}}case"union":{(!Array.isArray(n.items)||!n.items.length)&&B(e,"union items must be non-empty");let o=n.items.map((i,a)=>Zr(i,`${e}.items[${a}]`,!0,r));return{...n,items:o,inputConstraint:o.some(i=>i.inputConstraint),test:i=>o.some(a=>a.test&&a.test(i))}}case"literal":return Array.isArray(n.values)||B(e,"literal values must be an array"),n.values.forEach((o,i)=>Jr(o,`${e}.values[${i}]`)),{...n,test:o=>n.values.some(i=>Object.is(i,o))};case"annotated":{Array.isArray(n.metadata)||B(e,"annotated metadata must be an array"),n.metadata.some(a=>!["regex","range","value"].includes(a?.kind))&&B(e,"unsupported annotation metadata kind");let o=Zr(n.base,`${e}.base`,!0,r),i=n.metadata.map((a,s)=>Zr(a,`${e}.metadata[${s}]`,!0,r));return{...n,base:o,metadata:i,inputConstraint:o.inputConstraint,test:a=>o.test(a)&&i.every(s=>!s.test||s.test(a))}}case"range":{for(let o of["ge","le","gt","lt"])Object.hasOwn(n,o)||B(e,`range missing '${o}'`);for(let o of["ge","le","gt","lt"])n[o]!==null&&(typeof n[o]!="number"||!Number.isFinite(n[o]))&&B(e,`${o} must be finite number or null`);return{...n,test:o=>typeof o=="number"&&(n.ge===null||o>=n.ge)&&(n.le===null||o<=n.le)&&(n.gt===null||o>n.gt)&&(n.lt===null||o<n.lt)}}case"regex":{(typeof n.pattern!="string"||!Number.isInteger(n.flags)||n.flags<0)&&B(e,"regex requires pattern and non-negative integer flags");let o=n.flags&-59;o&&B(e,`unsupported Python regex flags ${o}`),n.flags&2&&B(e,"IGNORECASE is not portable across Python and JavaScript Unicode rules"),/\\[AZzUwWdDsSabBN0-9]|\(\?P[<=!]|\(\?\(|\(\?>|\(\?#|\(\?[aiLmsux-]|[+*?}]\+|\{,/.test(n.pattern.replaceAll(String.raw`[\s\S]`,"."))&&B(e,"regex uses a non-portable construct or character class");let i="uy";n.flags&16&&(i+="s");let a;try{a=new RegExp(`(?:${jy(n.pattern,n.flags)})(?![\\s\\S])`,i)}catch(s){B(e,`invalid portable regex: ${s.message}`)}return{...n,test:s=>typeof s!="string"?!1:(a.lastIndex=0,a.test(s))}}case"value":return Jr(n.value,`${e}.value`),{...n};case"generic":{let o=Zr(n.origin,`${e}.origin`,!0,r);(n.origin?.kind!=="type"||n.origin.module!=="builtins"||!["list","dict","tuple","set"].includes(n.origin.name))&&B(e,"only list, dict, tuple and set generic origins are supported"),Array.isArray(n.arguments)||B(e,"generic arguments must be an array");let i=n.arguments.map((a,s)=>Zr(a,`${e}.arguments[${s}]`,!0,r));return{...n,origin:o,arguments:i,inputConstraint:i.some(a=>a.inputConstraint),test:a=>o.test(a)&&qy(n.origin,i,a)}}case"arguments":B(e,"Callable argument-list descriptors are not supported by Python validation");case"ellipsis":return t||B(e,"ellipsis is only valid as a nested descriptor"),{...n};default:B(e,`unknown annotation kind '${n.kind}'`)}}function qy(n,e,t){let r=`${n.module}.${n.name}`;return r==="builtins.tuple"&&e.length&&e[1]?.kind!=="ellipsis"?t.length===e.length&&t.every((o,i)=>e[i].test(o)):r==="builtins.list"||r==="builtins.set"||r==="builtins.tuple"?[...t].every(o=>!e[0]?.test||e[0].test(o)):r==="builtins.dict"?Object.entries(t).every(([o,i])=>(!e[0]?.test||e[0].test(o))&&(!e[1]?.test||e[1].test(i))):!1}function Zh(n,e){if(n===null)return null;if(typeof n!="string"&&B(e,"must be string or null"),n==="")return new Map;let t=new Map;for(let r of n.split(",")){let o=r.trim();/^[A-Za-z_][A-Za-z0-9_]*\[\]$/.test(o)&&B(e,`invalid cardinality item '${r}'`);let i=o.match(/^([A-Za-z_][A-Za-z0-9_]*|\*)(?:\[(?:(\d+)|(?:(\d*):(\d*)))\])?$/);i||B(e,`invalid cardinality item '${r}'`);let[,a,s,l,u]=i;t.has(a)&&B(e,`duplicate tag '${a}'`);let c=0,d=1/0;o.includes("[")&&(o.includes(":")?(c=l?Number(l):0,d=u?Number(u):1/0):c=d=Number(s)),d<c&&B(e,`maximum ${d} is below minimum ${c}`),t.set(a,{min:c,max:d})}return t.has("*")&&t.size>1&&B(e,"wildcard '*' cannot be combined with named tags"),t}function Kh(n,e){if(n===null)return null;typeof n!="string"&&B(e,"must be string or null");let t=new Set;for(let r of n.split(",")){let o=r.trim();o&&((!Xh.test(o)||t.has(o))&&B(e,`invalid or duplicate parent '${r}'`),t.add(o))}return t}function Uy(n,e,t){if(n===null)return null;jt(n,["parameters","accepts_var_keyword","accepts_var_positional"],[],e);let r=n.parameters??[];Array.isArray(r)||B(e,"parameters must be an array"),n={parameters:r,accepts_var_keyword:r.some(l=>l.kind==="var_keyword"),accepts_var_positional:r.some(l=>l.kind==="var_positional"),...n},(!Array.isArray(n.parameters)||typeof n.accepts_var_keyword!="boolean"||typeof n.accepts_var_positional!="boolean")&&B(e,"invalid signature descriptor");let o=new Set,i=!1,a=!1,s=n.parameters.map((l,u)=>{let c=`${e}.parameters[${u}]`;return jt(l,["name","kind","role","annotation","has_default","default"],["name","kind","role","annotation","has_default"],c),(typeof l.name!="string"||!Xh.test(l.name)||o.has(l.name))&&B(c,"invalid or duplicate parameter name"),o.add(l.name),(!Py.has(l.kind)||!Ly.has(l.role)||typeof l.has_default!="boolean")&&B(c,"invalid kind, role, or has_default"),l.has_default!==Object.hasOwn(l,"default")&&B(c,"default presence must equal has_default"),l.has_default&&Jr(l.default,`${c}.default`),i||=l.kind==="var_keyword",a||=l.kind==="var_positional",{...l,annotation:Zr(l.annotation,`${c}.annotation`,!1,t)}});return(i!==n.accepts_var_keyword||a!==n.accepts_var_positional)&&B(e,"variadic summary flags do not match parameters"),{...n,parameters:s}}function Yh(n,e,t,r){let o=["doc","sub_tags","parent_tags","inherits_from","ns","attributes",...t?["node_label","collection_key"]:[],"_meta"];jt(n,o,[],e),n={...Object.fromEntries(o.map(i=>[i,null])),...n};for(let i of["doc","inherits_from","ns",...t?["node_label","collection_key"]:[]])n[i]!==null&&typeof n[i]!="string"&&B(e,`${i} must be string or null`);return n._meta!==null&&(Kr(n._meta)||B(e,"_meta must be object or null"),Jr(n._meta,`${e}._meta`)),Zh(n.sub_tags,`${e}.sub_tags`),Kh(n.parent_tags,`${e}.parent_tags`),{...n,attributes:Uy(n.attributes,`${e}.attributes`,r)}}function Jh(n){return n?n.split(",").map(e=>e.trim()).filter(Boolean):[]}function Qh(n,e){let t={...e};for(let[r,o]of Object.entries(n))r==="inherits_from"||r.startsWith("_")||t[r]||(t[r]=o);return t._meta={...n._meta||{},...e._meta||{}},t}function ep(n){let e={...n};return e._subSpec=Object.hasOwn(e,"sub_tags")?Zh(e.sub_tags,"resolved.sub_tags"):null,e._parentSpec=Object.hasOwn(e,"parent_tags")?Kh(e.parent_tags,"resolved.parent_tags"):null,e}function tp(n,e,t,r){if(t.get(n)===1&&B(r,`inheritance cycle at '${n}'`),t.get(n)===2)return e[n];let o=e[n];o||B(r,`unknown abstract '${n}'`),t.set(n,1);let i={...o};for(let a of Jh(o.inherits_from))i=Qh(tp(a,e,t,r),i);return i=ep(i),t.set(n,2),e[n]=i,i}function zu({abstracts:n={},elements:e={}}){let t={...n},r=new Map;for(let i of Object.keys(t))tp(i,t,r,`abstracts.${i}.inherits_from`);let o={};for(let[i,a]of Object.entries(e)){let s={...a};for(let l of Jh(a.inherits_from)){let u=t[l];u||B(`elements.${i}.inherits_from`,`unknown abstract '${l}'`),s=Qh(u,s)}o[i]=ep(s)}return{abstracts:t,elements:o}}function Hu(n){jt(n,["document_format","grammar","abstracts","elements","custom_types"],["document_format","grammar","abstracts","elements"],"grammar document"),jt(n.document_format,["name","version"],["name","version"],"document_format"),(n.document_format.name!=="builder_grammar"||!["1.1","1.2"].includes(n.document_format.version))&&B("document_format","expected builder_grammar version 1.1 or 1.2"),jt(n.grammar,["name","version","title","description"],["name","version","title","description"],"grammar"),(typeof n.grammar.name!="string"||!n.grammar.name)&&B("grammar.name","must be non-empty string");for(let o of["version","title","description"])n.grammar[o]!==null&&typeof n.grammar[o]!="string"&&B(`grammar.${o}`,"must be string or null");(!Kr(n.abstracts)||!Kr(n.elements))&&B("grammar document","abstracts/elements must be objects"),Object.hasOwn(n,"custom_types")&&n.document_format.version!=="1.2"&&B("custom_types","requires version 1.2");let e=no.fromJSON(n.custom_types??{}),t={};for(let[o,i]of Object.entries(n.abstracts))(!o||o.startsWith("_"))&&B("abstracts",`invalid public name '${o}'`),t[o]=Yh(i,`abstracts.${o}`,!1,e);let r={};for(let[o,i]of Object.entries(n.elements))(!o||o.startsWith("_"))&&B("elements",`invalid public name '${o}'`),r[o]=Yh(i,`elements.${o}`,!0,e);return{grammar:structuredClone(n.grammar),abstracts:t,elements:r}}function rp(n,e,t,r){let o=e.attributes;if(!o)return;let i={...r};t!=null&&(i.node_value=t);let a=new Set(o.parameters.filter(u=>u.role==="attribute").map(u=>u.name)),s=new Set(["node_label","node_position","nodeId","target_id","datapath","iterate","store","_tag","_meta","ns"]);if(!o.accepts_var_keyword)for(let u of Object.keys(r))!a.has(u)&&!s.has(u)&&B(n,`unknown attribute '${u}'`);let l=e._meta?.component?o.parameters.find(u=>u.role!=="framework"&&["positional_only","positional_or_keyword"].includes(u.kind))?.name:null;for(let u of o.parameters){if(u.name===l||u.role==="framework"||u.kind.startsWith("var_"))continue;let c=Object.hasOwn(i,u.name);!c&&!u.has_default&&B(n,`missing required ${u.role} '${u.name}'`),c&&u.annotation!==null&&(!u.annotation.test||!u.annotation.test(i[u.name]))&&B(n,`invalid value for ${u.role} '${u.name}'`)}}var no=class n{#e=new Map;#t=new Map;register(e,t,r){let o=new Map([[String,"str"],[Number,"float"],["string","str"],["integer","int"],["number","float"]]),i=o.has(t)?{kind:"type",module:"builtins",name:o.get(t)}:t;return this.#r(e,{kind:"annotated",base:i,metadata:[r]})}#r(e,t){(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/.test(e)||e in this||["to_dict","from_dict"].includes(e)||Vy.has(e))&&B("custom_types",`invalid, reserved or duplicate name '${e}'`),jt(t,["kind","base","metadata"],["kind","base","metadata"],`custom_types.${e}`),(t.kind!=="annotated"||!Array.isArray(t.metadata)||t.metadata.length!==1||!["regex","range"].includes(t.metadata[0]?.kind))&&B(`custom_types.${e}`,"requires an annotated base with one Regex or Range validator");let r=t.metadata[0].kind==="regex"?["str"]:["int","float"];(t.base?.kind!=="type"||t.base.module!=="builtins"||!r.includes(t.base.name))&&B(`custom_types.${e}`,"portable Regex requires str; portable Range requires int or float"),Jr(t,`custom_types.${e}`);let o=structuredClone(t),i=Zr(o,`custom_types.${e}`),a=Object.freeze({kind:"custom",name:e});return Object.defineProperty(this,e,{value:a,enumerable:!0}),this.#e.set(e,o),this.#t.set(e,{...a,inputConstraint:!0,test:i.test}),a}resolve(e,t="custom_types"){return this.#t.has(e)||B(t,`unknown custom type '${e}'`),{...this.#t.get(e)}}validate(e,t){return this.resolve(e).test(t)||B(`custom_types.${e}`,"invalid input value"),!0}toJSON(){return structuredClone(Object.fromEntries(this.#e))}static fromJSON(e){Kr(e)||B("custom_types","must be an object");let t=new n;for(let[r,o]of Object.entries(e))t.#r(r,o);return t}},Vy=new Set("False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield".split(" "));function np(n,e,t,r){let o=e?.attributes;if(o)for(let i of o.parameters){if(!i.annotation?.inputConstraint||i.role==="framework"||["var_keyword","var_positional"].includes(i.kind))continue;let a=i.role==="value"?t:r[i.name];a!==void 0&&(i.annotation.test(a)||B(n,`invalid input for '${i.name}' (custom type)`))}}function op(n,e,t=[]){if(e===null)return structuredClone(n);if(t.length===2&&t[0]==="custom_types"&&n!==void 0){if(!Gu(n,e))throw new TypeError(`conflicting custom type '${t[1]}'`);return structuredClone(n)}if(t.length===2&&["abstracts","elements"].includes(t[0]))return structuredClone(e);if(Zt(n)&&Zt(e)){let r=structuredClone(n);for(let[o,i]of Object.entries(e))i!==null&&Object.defineProperty(r,o,{value:op(r[o],i,[...t,o]),enumerable:!0,writable:!0,configurable:!0});return r}return structuredClone(e)}function Gu(n,e){return Object.is(n,e)?!0:Array.isArray(n)&&Array.isArray(e)?n.length===e.length&&n.every((t,r)=>Gu(t,e[r])):Zt(n)&&Zt(e)?Object.keys(n).length===Object.keys(e).length&&Object.keys(n).every(t=>Object.hasOwn(e,t)&&Gu(n[t],e[t])):!1}function Zt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype}function Wu(n){if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(Array.isArray(n)){n.forEach(Wu);return}if(Zt(n)){Object.values(n).forEach(Wu);return}throw new TypeError("collection must contain only finite JSON values")}}var Kt=class n{#e;constructor(e){Wu(e);let t=["document_format","grammar","abstracts","elements"];if(!Zt(e)||Object.keys(e).some(o=>![...t,"custom_types"].includes(o))||t.some(o=>!Object.hasOwn(e,o)))throw new TypeError("collection requires document_format, grammar, abstracts and elements");let r=e.document_format;if(!Zt(r)||Object.keys(r).length!==2||r.name!=="builder_grammar"||!["1.1","1.2"].includes(r.version))throw new TypeError("expected builder_grammar version 1.1 or 1.2");for(let o of["grammar","abstracts","elements"])if(!Zt(e[o]))throw new TypeError(`${o} must be an object`);if(Object.hasOwn(e,"custom_types")&&(r.version!=="1.2"||!Zt(e.custom_types)))throw new TypeError("custom_types requires an object catalog and version 1.2");this.#e=structuredClone(e)}update(e){let t=new n(e),r=op(this.#e,t.#e);return(this.#e.document_format.version==="1.2"||t.#e.document_format.version==="1.2")&&(r.document_format.version="1.2"),this.#e=r,this}toDocument(){return structuredClone(this.#e)}};var Qr=class{static renderType="string";static mode=null;constructor(e){this._builder=e,this.renders=new Map([[e,this]])}get builder(){return this._builder}get renderType(){return this.constructor.renderType}get mode(){return this.constructor.mode}addRender(e,t){this.renders.set(e,t)}getRender(e){let t=this.renders.get(e);if(t!==void 0)return t;let r=e.getRenderer();return this.renders.set(e,r),r}render(e,t={}){let r=e.builder,[o,i]=r.runtimeValues(e);if(e._getMeta("data_element"))return null;if(e._getMeta("component"))return this._renderComponent(e,i,t);let a=this.getRender(r),s;return[s,i]=a._handleMeta(e,i),e._getMeta("subbuilder")||(i=a.adaptAttrs(i)),e.value instanceof I&&(o=this.renderChildren(e.value,t)),a.renderedItem(e,o,i,{tag:s,...t})}renderChildren(e,t={}){let r=[];for(let o of e.getNodes()){let i=this.render(o,t);i!==null&&(Array.isArray(i)?r.push(...i):r.push(i))}return r}_renderComponent(e,t,r){let[o,i,a,s]=this._expansionInputs(e,t);if(!Object.hasOwn(e.getAttr(),"iterate"))return this._expandBlock(e,o,a,s,r);if(i==null)return[];if(!(i instanceof E))throw new TypeError(`component '${e.nodeTag}': iterate must resolve to a Bag, got ${i?.constructor?.name||typeof i}`);return i.getNodes().map(l=>this._expandBlock(e,o,a,{node_label:l.label},r))}_expansionInputs(e,t){let r=e.builder,o=r.componentMethod(e.nodeTag),i=o&&r[o];if(typeof i!="function")throw new Error(`component '${e.nodeTag}' has no implementation`);let a=t.iterate;delete t.iterate,delete t.store;let s=e.getAttr("iterate")||e.getAttr("store");s!=null?(e.pointerType(s)&&(s=s.slice(1)),s.startsWith(".")&&(s=e._composeRelativeDatapath(s,s))):s=null;for(let l of Object.keys(t)){let u=e.getAttr(l);e.pointerType(u)==="^"&&(t[l]=`^${e.absDatapath(u)}`)}return[i,a,s,t]}_expandBlock(e,t,r,o,i){let a=e.builder._expansionRoot(r);t.call(e.builder,fi(a),o);let s=a.getNodes();if(s.length!==1)throw new Error(`component '${e.nodeTag}' must build a tree, not a forest: ${s.length} root nodes`);let l={...i,depthOffset:this._nodeDepth(e,i.depthOffset||0)};return this.render(s[0],l)}preprocess(e){return e}renderedItem(e,t,r,o){throw new Error(`${this.constructor.name} does not implement renderedItem`)}_handleMeta(e,t){let[r,o]=e._getMeta("render_tag,render_attributes"),i=di(e.nodeTag,{renderTag:r,ns:e.getAttr("ns"),dialectName:e.builder?.constructor._name});if(!i)throw new Error(`node ${e.label} has no tag to render (no render_tag, no node_tag)`);return o&&(t={...t,...o}),[i,t]}adaptAttrs(e){return e}adapt(e){let t=`${this.builder.constructor._name}_`;return e.startsWith(t)?e.slice(t.length):e}finalize(e,t=null,r={}){let o=this._composeStringFragments(e);if(t==null)return o;if(typeof t=="string")throw new TypeError("string render targets require filesystem support, which is unavailable in the portable renderer; pass a callable or writable target instead");if(typeof t.full=="function"&&typeof t.write!="function")return t.full(o),null;if(typeof t.write=="function")return t.write(o),null;if(typeof t=="function")return t(o),null;throw new TypeError("render target must be writable (.write), callable, or expose .full")}_composeStringFragments(e){if(!Array.isArray(e))return e;if(e.some(t=>typeof t!="string"))throw new TypeError("String composition requires string fragments; object renderers must define their own composition");return e.join("")}_escapeText(e){return String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}_escapeAttr(e){return this._escapeText(e).replaceAll('"',""")}_nodeDepth(e,t=0){let o=((e.fullpath||"").match(/\./g)||[]).length;return Math.max(o-1,0)+t}};var en=class extends Qr{static mode="xml";renderedItem(e,t,r,{tag:o,pretty:i=!1,depthOffset:a=0}={}){let s=this._formatAttrs(r),l=i?" ".repeat(this._nodeDepth(e,a)):"",u=i?`
|
|
39
|
-
`:"";if(Array.isArray(t)){let c=this._composeStringFragments(t);return`${l}<${o}${s}>${u}${c}${l}</${o}>${u}`}return t==null?`${l}<${o}${s}></${o}>${u}`:`${l}<${o}${s}>${this._escapeText(t)}</${o}>${u}`}finalize(e,t=null,{docHeader:r=null}={}){let o=this._composeStringFragments(e);return r===!0?o=`<?xml version='1.0' encoding='UTF-8'?>${o}`:typeof r=="string"&&(o=r+o),super.finalize(o,t)}_formatAttrs(e){return Object.entries(e||{}).map(([t,r])=>` ${t.startsWith("xmlns_")?`xmlns:${t.slice(6)}`:t}="${this._escapeAttr(r)}"`).join("")}};var ip={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"base",version:null,title:null,description:null},abstracts:{},elements:{dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};function ap(n){let e=[];for(;n&&n!==Function.prototype;)e.push(n),n=Object.getPrototypeOf(n);return e.reverse()}function Hy(n){let e=Object.create(null),t=(r,o)=>{let i=r.toLowerCase(),a=e[i];if(a!==void 0&&a!==o)throw new Error(`container '${r}' is already tied to implementation method '${a}' (cannot rebind to '${o}')`);e[i]=o};for(let r of ap(n))if(Object.hasOwn(r,"containers"))for(let o of r.containers||[])t(o,o);return e}function hi(n){let e=Object.create(null);for(let t of Object.keys(n)){let r=t.toLowerCase();if(Object.hasOwn(e,r))throw new Error(`element declaration '${t}' has a case-insensitive collision with '${e[r]}'`);e[r]=t}return e}var pi="_root_",mi="_root_",sp=new Set(["destination","func","value","_on_start"]),Ze=class n{static _sourceClass=I;static registerBuilder(e){if(typeof e!="function"||!(e.prototype instanceof n))throw new TypeError("registerBuilder requires a BuilderBase subclass");let t=e._name;if(typeof t!="string"||!t)throw new TypeError("registered builders require a non-empty static _name");let r=n._registry.get(t);if(r&&r!==e)throw new Error(`Builder name '${t}' is already registered to ${r.name}; cannot register ${e.name}`);return n._registry.set(t,e),e}static getBuilderClass(e){let t=n._registry.get(e);if(!t)throw new Error(`No builder registered with name '${e}'`);return t}constructor(e=null){this.name=e||this.constructor._name,this._dataroot=new E,this._dataroot.setBackref(),this._dataroot.setItem(mi,new E),this.data=this._dataroot.getItem(mi),this._defaultTargets=new Map,this.materialized=Object.create(null),this._collection=null,this._schemaOverride=null,this._tagNamesOverride=null,this._componentMap=null,this._targetSerial=0,this._subbuilders=new Map,this._sourceHandles=new WeakMap;let t=this.constructor._sourceClass;this._sourceroot=new t(null,this),this._sourceroot.setBackref(),this._sourceroot.setItem(pi,new t(null,this)),this.source=this._sourceroot.getItem(pi)}wrapSource(e){if(e=ie(e),!(e instanceof I)&&!(e instanceof Xe))throw new TypeError("wrapSource requires a SourceBag or SourceBagNode");let t=this._sourceHandles.get(e);return t||(t=Wh(this,e),this._sourceHandles.set(e,t)),t}get root(){return this.wrapSource(this.source)}getSubbuilder(e){if(typeof e!="string"||!e||e.includes(":"))throw new Error(`unsupported subbuilder reference '${e}'`);let t=this._subbuilders.get(e);if(!t){let r=n.getBuilderClass(e);t=new r,this._subbuilders.set(e,t)}return t._dataroot=this._dataroot,t.data=this.data,t}_resolveSubbuilderReference(e,t,r){if(typeof e!="string"||!e)throw new Error(`'${r}': subbuilder declaration must be a non-empty string`);if(e.includes(":"))throw new Error(`'${r}': runtime subbuilder reference '${e}' is unsupported`);return this.getSubbuilder(e)}static defineGrammar(e){let t=this._classCollection,r=t?new Kt(t.toDocument()).update(e):new Kt(e),o=Hu(r.toDocument()),i=zu(o),a=hi(i.elements);this._classCollection=r,this._classSchema=i.elements,this._abstracts=i.abstracts,this._tagNames=a}static{this.defineGrammar(ip)}get _containers(){return Hy(this.constructor)}containerMethod(e){return this._containers[e.toLowerCase()]||null}componentMethod(e){return this._componentMap?.[e.toLowerCase()]||null}get schema(){return this._schemaOverride||this.constructor._classSchema||{}}get schemaTagNames(){return this._schemaOverride?this._tagNamesOverride??=hi(this.schema):this.constructor._tagNames??=hi(this.schema)}schemaTag(e){let t=e.toLowerCase(),r=this.schemaTagNames[t];if(r)return r;let o=`${this.constructor._name}_`;return t.startsWith(o)&&this.schemaTagNames[t.slice(o.length)]||null}loadGrammar(e,{replace:t=!1}={}){let r=this._collection||this.constructor._classCollection,o=t?new Kt(e):new Kt(r.toDocument()).update(e),i=Hu(o.toDocument()),a=zu(i),s=hi(a.elements);return this._collection=o,this._schemaOverride=a.elements,this._tagNamesOverride=s,this}validateCustomTypes(e){let t=e.parentBag?.parentNode?.builder||e.parentBag?._builder,r=t&&t!==this&&t.schema[e.nodeTag]?._meta?.subbuilder?t:this;np(e.nodeTag,r.schema[e.nodeTag],e.value,e.getAttr()||{})}validateNodeValues(e,t,r={}){let o=this.schemaTag(e);if(!o)throw new Error(`unknown element '${e}'`);return rp(o,this.schema[o],t,r),!0}validateNode(e,{value:t,attrs:r,childTags:o}={}){if(!e||typeof e.nodeTag!="string")throw new TypeError("validateNode requires a source node");let i=t!==void 0?t:e.value instanceof I?null:e.value;this.validateNodeValues(e.nodeTag,i,r||e.getAttr?.()||{});let a=this.schema[this.schemaTag(e.nodeTag)],s=o||(e.value instanceof I?e.value.getNodes().map(l=>l.nodeTag):null);return s&&this._validateChildren(e.nodeTag,a,s,!1),!0}validateChildren(e,t,{includeMinimum:r=!1}={}){let o=this.schemaTag(e);if(!o)throw new Error(`unknown element '${e}'`);if(!Array.isArray(t)||t.some(i=>typeof i!="string"))throw new TypeError("childTags must be an array of strings");return this._validateChildren(o,this.schema[o],t,r)}validateParent(e,t=null){let r=this.schemaTag(e);if(!r)throw new Error(`unknown element '${e}'`);let o=this.schema[r];if(!this._countsForGrammar(o))return!0;let i=o._parentSpec;if(i==null||i.has("*"))return!0;if(t===null)throw new Error(`'${r}' requires a declared parent`);let a=this.schemaTag(t);if(!a)throw new Error(`unknown parent element '${t}'`);return this._validateParent(r,o,a),!0}bagCall(e,t,r,o){return this.setChild(e,t,r,o)}commandOnNode(e,t,r,o){if(e=ie(e),e.value instanceof I)return this.setChild(e.value,t,r,o);let i=e.value,a=new e.parentBag.constructor(null,e.builder||this),s=this.setChild(a,t,r,o,e);return this.promoteNodeValue(e,i,a),s}promoteNodeValue(e,t,r){e.setValue(r)}setChild(e,t,r,o,i=null){let a={...o},s=this.schema[t];if(!s)throw new Error(`unknown element '${t}'`);this.validateNodeValues(t,r,a);let l=s._meta?.subbuilder,c=(l==null?null:this._resolveSubbuilderReference(l,a,t))||this,d=r instanceof I?r._builderBindingPlan(c):null,f=i?.rootBuilder||e.root._builder||this;if(a.nodeId!=null&&f.source.getNodeByAttr("nodeId",a.nodeId))throw new Error(`Duplicate nodeId '${a.nodeId}'`);r instanceof I&&this._validateChildren(t,s,r.getNodes().map(y=>y.nodeTag),!1);let h=i||e.parentNode,p=h?.nodeTag?this.schema[h.nodeTag]:null;if(p&&!h._getMeta("subbuilder")&&this._countsForGrammar(s))this._validateParent(t,s,h.nodeTag),this._validateChildren(h.nodeTag,p,[...e.getNodes().map(y=>y.nodeTag),t],!1);else if(!p&&!h?._getMeta("subbuilder")&&s._parentSpec!=null&&this._countsForGrammar(s))throw new Error(`'${t}' requires a declared parent`);s._meta&&!("_meta"in a)&&(a._meta=s._meta),s.ns&&!("ns"in a)&&(a.ns=s.ns);let m=a.node_position;delete a.node_position;let b=a.node_label;delete a.node_label;let w;if(p?.collection_key){if(b!=null)throw new Error(`'${t}': node_label is not allowed in a collection`);w=this._collectionLabel(p.collection_key,t,a)}else{let y=p?._subSpec?.get(t);if(y&&y.max===1){if(b!=null)throw new Error(`'${t}': node_label is not allowed on a singleton`);w=t}else w=b||s.node_label||this._autoLabel(e,t)}if(e.node(w)!=null)throw new Error(`duplicate node label '${w}'`);return e._setBuilderItem(c,d,w,r,a,m||">",!1,!0,null,!1,!0,null,t)}_countsForGrammar(e){let t=e?._meta||{};return!(t.data_element||t.subbuilder||t.component)}_validateParent(e,t,r){let o=t._parentSpec;if(!(o==null||o.has("*")||!this._countsForGrammar(t))&&!o.has(r))throw new Error(`'${e}' not allowed as child of '${r}'`)}_validateChildren(e,t,r,o){let i=t._subSpec;if(i==null||i.has("*")||t._meta?.subbuilder)return[];let a=new Map;for(let s of r){let l=this.schema[s];if(l&&!this._countsForGrammar(l))continue;let u=i.get(s);if(!u)throw new Error(`'${s}' not allowed as child of '${e}'`);let c=(a.get(s)||0)+1;if(a.set(s,c),c>u.max)throw new Error(`too many '${s}' in '${e}'`)}return o?[...i].filter(([s,l])=>(a.get(s)||0)<l.min).map(([s])=>s):[]}_collectionLabel(e,t,r){let o=i=>{if(r[i]===null||r[i]===void 0)throw new Error(`'${t}': collection key needs attribute '${i}'`);return String(r[i])};return e.includes("${")?e.replace(/\$\{([^}]+)\}/g,(i,a)=>o(a)):o(e)}validateSource(){let e=[],t=(r,o="")=>{for(let i of r.getNodes()){let a=o?`${o}.${i.label}`:i.label,s=i.builder;s.validateCustomTypes(i);let l=s.schema[i.nodeTag];if(l&&!i._getMeta("data_element,subbuilder,component").some(Boolean)){let u=i.value instanceof I?i.value.getNodes().map(d=>d.nodeTag):[],c=s._validateChildren(i.nodeTag,l,u,!0);c.length&&e.push([a,c])}i.value instanceof I&&t(i.value,a)}};return t(this.source),e}_autoLabel(e,t){let r=0;for(;e.node(`${t}_${r}`)!==null&&e.node(`${t}_${r}`)!==void 0;)r+=1;return`${t}_${r}`}nodeById(e){let t=this.source.getNodeByAttr("nodeId",e);if(t==null)throw new Error(`nodeId not found: ${e}`);return t.builder.wrapSource(t)}runtimeValues(e){e.builder.validateCustomTypes(e);let t=new Map,r={},o=e.runtimeToEvaluate(),i=new Set(o.keys()),a=new Map([...Object.entries(e.getAttr()),...e.fixedAttrItems()]);for(let[c,d]of[...o])if(!(typeof c!="string"||!re(d)))for(let f of Ft(e,d))o.has(f)||o.set(f,a.get(f));let s=e._getMeta("data_element");for(let[c,d]of o){if(d instanceof fe){t.set(c,d.resolve());continue}let f=typeof c=="string"?re(d)?.pointer??d:d;if(!e.pointerType(f)){t.set(c,typeof c=="string"&&typeof d=="string"&&d.startsWith("==")?null:d);continue}let h=e.absDatapath(f);if(t.set(c,this.data.getItem(h)),!s&&!h.includes("?")&&c===ro){let p=this.data.getNode(h);p&&Object.assign(r,p.getAttr("_wdg"))}}let l=$h(o,t,(c,d,f,h)=>this.evaluatePointerExpression(e,c,d,f,h)),u=l.get(ro);l.delete(ro);for(let c of l.keys())i.has(c)||l.delete(c);return[u,{...Object.fromEntries(l),...r}]}evaluatePointerExpression(e,t,r,o,i){return null}targetId(e){if(e._targetId)return e._targetId;let t=e.rootBuilder;return e.parentBag.root!==t.source.root?null:(t._targetSerial+=1,e._targetId=`n${t._targetSerial}`,e._targetId)}get dataLogic(){if(!this._dataLogic){let e=this._buildDataLogic();this._dataLogic=Array.isArray(e)?e:[e]}return this._dataLogic}_buildDataLogic(){return this}_resolveLogicFunc(e){if(typeof e=="function")return e;if(typeof e!="string")throw new Error("data-element func must be a name or a function");for(let t of this.dataLogic){let o=(typeof t=="function"?t:t.constructor)[e];if(typeof o=="function")return o}throw new Error(`data-element func '${e}' not found on any data_logic source`)}_bindings(e){let[,t]=this.runtimeValues(e),r={};for(let[o,i]of Object.entries(t))sp.has(o)||(r[o]=i);return r}computeLogic(e){for(let t of e)this._computeNode(t)}_computeNode(e){let t=e.getAttr()||{};if(e.nodeTag==="dataSetter"){let r={};for(let[o,i]of Object.entries(t))o!=="destination"&&o!=="value"&&!o.startsWith("_")&&(r[o]=i);e.setRelativeData(t.destination,t.value,{attributes:Object.keys(r).length?r:null})}else if(e.nodeTag==="dataFormula"){let r=this._resolveLogicFunc(t.func);e.setRelativeData(t.destination,r(this._bindings(e)))}else e.nodeTag==="dataController"&&this._resolveLogicFunc(t.func)(e,this._bindings(e))}_dataElementNodes(){let e=[],t=r=>{for(let o of r.getNodes())o._getMeta("data_element")&&e.push(o),o.value instanceof I&&t(o.value)};return t(this.source),e}setup(e){}main(e){throw new Error(`${this.constructor.name}.main() not implemented: a bare builder is grammar, not a renderable page`)}_resolveComponents(){let e={};for(let s of ap(this.constructor))if(Object.hasOwn(s,"components"))for(let l of s.components||[])e[l]=l;if(!Object.keys(e).length)return;let t={...this.schema},r={};for(let[s,l]of Object.entries(e))t[s]={sub_tags:"",_meta:{component:!0}},r[s.toLowerCase()]=l;let o=hi(t),i=this._collection||this.constructor._classCollection,a=i.toDocument();a.abstracts={},a.elements=Object.fromEntries(Object.keys(e).map(s=>[s,t[s]])),this._collection=new Kt(i.toDocument()).update(a),this._schemaOverride=t,this._componentMap=r,this._tagNamesOverride=o}_expansionRoot(e=null){let t=this.constructor._sourceClass,r=new t(null,this);return r.setBackref(),r.setItem(pi,new t(null,this),e?{datapath:e}:null),r.getItem(pi)}create(){this.setup(this.data),this._resolveComponents(),this.main(this.root),this.computeLogic(this._dataElementNodes())}get renderer_xml(){return new en(this)}getRenderer(e=null){e??=this.constructor._defaultRenderMode;let t=this[`renderer_${e}`];if(!t)throw new Error(`${this.constructor.name} does not expose renderer_${e}`);return t}materialize(e=null,t={}){e??=this.constructor._defaultRenderMode;let r=this.getRenderer(e),o=r.renderChildren(r.preprocess(this.source),t);return this.materialized[e]=o,o}setRenderTarget(e,t=null){t??=this.constructor._defaultRenderMode,this._defaultTargets.set(t,e)}render({mode:e=null,target:t=null,...r}={}){e??=this.constructor._defaultRenderMode;let o=this.getRenderer(e);if(t===!1&&o.renderType!=="string")throw new TypeError("target=false is not valid for an object renderer");let i=t===!1?null:t||this._defaultTargets.get(o.mode)||null,a={...i?.renderOpts,...r};return o.finalize(this.materialize(e,a),i,a)}};Ze._registry=new Map;var Gy=new Set(["short","medium","long","full"]),Wy=/('(?:[^']|'')*'|[a-zA-Z]+|[^a-zA-Z']+)/g;function Yy(n,e){if(!(n instanceof Date))throw new TypeError("Temporal formats require a typed Date value");if(!Number.isFinite(n.getTime()))throw new RangeError("Invalid date");let t=e||L(n).split("::").at(-1);if(!["D","H","DH","DHZ"].includes(t))throw new RangeError(`Unsupported temporal dtype: ${t}`);return t}function Xy(n,e,t,r){let o=e.match(Wy)||[];if(o.join("")!==e)throw new RangeError("Unclosed format literal");let i=(c,d=2)=>String(c).padStart(d,"0"),a=c=>new Intl.DateTimeFormat(t,{timeZone:"UTC",...c}).format(n),u={...r==="H"?{}:{y:()=>String(n.getUTCFullYear()),yy:()=>i(n.getUTCFullYear()%100),yyyy:()=>i(n.getUTCFullYear(),4),M:()=>String(n.getUTCMonth()+1),MM:()=>i(n.getUTCMonth()+1),MMM:()=>a({month:"short"}),MMMM:()=>a({month:"long"}),d:()=>String(n.getUTCDate()),dd:()=>i(n.getUTCDate()),EEE:()=>a({weekday:"short"}),EEEE:()=>a({weekday:"long"})},...r==="D"?{}:{H:()=>String(n.getUTCHours()),HH:()=>i(n.getUTCHours()),h:()=>String(n.getUTCHours()%12||12),hh:()=>i(n.getUTCHours()%12||12),m:()=>String(n.getUTCMinutes()),mm:()=>i(n.getUTCMinutes()),s:()=>String(n.getUTCSeconds()),ss:()=>i(n.getUTCSeconds()),a:()=>new Intl.DateTimeFormat(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(n).find(c=>c.type==="dayPeriod").value}};return o.map(c=>{if(c.startsWith("'"))return c==="''"?"'":c.slice(1,-1).replaceAll("''","'");if(!/^[a-zA-Z]/.test(c))return c;if(!u[c])throw new RangeError(`Unsupported date format token: ${c}`);return u[c]()}).join("")}function lp(n,{format:e,mask:t,locale:r,dtype:o,places:i}={}){let a=n==null?"":String(n);if(n!=null&&n!==""&&(e!=null&&e!==""||i!=null))if(typeof n=="number"||de(n))a=Ky(n,{format:e,locale:r,places:i});else{let s=Yy(n,o);if(Gy.has(e)){let l={timeZone:"UTC"};s!=="H"&&(l.dateStyle=e),s!=="D"&&(l.timeStyle=e),a=new Intl.DateTimeFormat(r||void 0,l).format(n)}else a=Xy(n,String(e),r||void 0,s)}return t==null?a:String(t).replaceAll("%s",()=>a)}function Zy({format:n="decimal",places:e}={}){let t={maximumFractionDigits:20};if(!n||n==="decimal")t.style="decimal";else if(n==="percent")t.style="percent";else if(n==="scientific")t.notation="scientific";else{let r=/^(0|#,##0)(?:\.(0*)(#*))?$/.exec(n);if(!r||n.includes(".")&&!r[2]&&!r[3])throw new RangeError(`Unsupported number format: ${n}`);t.useGrouping=r[1].includes(","),t.minimumFractionDigits=(r[2]||"").length,t.maximumFractionDigits=(r[2]||"").length+(r[3]||"").length}if(e!=null&&e!==""){let r=Number(e);if(!Number.isInteger(r)||r<0||r>20)throw new RangeError("places must be an integer from 0 to 20");t.minimumFractionDigits=r,t.maximumFractionDigits=r}return t}function Ky(n,e={}){if(typeof n!="number"&&!de(n))throw new TypeError("Number formatting requires a Number or Decimal");if(!Number.isFinite(Number(n)))throw new RangeError("Number must be finite");let t=new Intl.NumberFormat(e.locale||void 0,Zy(e));if(de(n)&&new Intl.NumberFormat("en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal values without precision loss");return t.format(de(n)?n.toString():n)}var Jy=new Set(["style","script"]),Qy=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),up=new Set(["width","height","top","left","right","bottom","padding","margin","border","position","display","overflow","float","clear","resize","z_index","min_width","min_height","max_width","max_height","color","background","font","text","line_height","white_space","vertical_align","flex","gap","row_gap","column_gap","grid","align_content","justify_content","align_items","justify_items","visibility","opacity","cursor"]),gi=new Set(["rounded","gradient","shadow","transform","transition","zoom","filter"]),cp=n=>n===!0?"true":n===!1?"false":String(n),rs=n=>typeof n=="number"&&Number.isFinite(n)?`${n}px`:String(n);function ev(n){if(up.has(n))return!0;for(let e of up)if(n.startsWith(`${e}_`))return!0;return!1}function tv(n){let e=new Map;if(!n)return e;let t=[],r=0,o=null,i=!1,a=!1,s=0,l=String(n);for(let u=0;u<l.length;u+=1){let c=l[u],d=l[u+1];if(a){c==="*"&&d==="/"&&(a=!1,u+=1);continue}if(i){i=!1;continue}if(c==="\\"){i=!0;continue}if(o){c===o&&(o=null);continue}c==='"'||c==="'"?o=c:c==="/"&&d==="*"?(a=!0,u+=1):"([{".includes(c)?s+=1:")]}".includes(c)&&s>0?s-=1:c===";"&&s===0&&(t.push(l.slice(r,u)),r=u+1)}t.push(l.slice(r));for(let u of t){let c=u.trim();if(!c)continue;let d=c.indexOf(":");if(d<0)throw new TypeError(`malformed style declaration '${c}'`);e.set(c.slice(0,d).trim(),c.slice(d+1).trim())}return e}var tn=class extends Qr{static mode="html";renderedItem(e,t,r,{tag:o,xml:i=!0,pretty:a=!1,depthOffset:s=0,includeDatapath:l=!1}={}){e.parentNode?._getMeta("subbuilder")==="html"&&(r={xmlns:"http://www.w3.org/1999/xhtml",...r});let{format:c,mask:d,locale:f,places:h,dtype:p,...m}=r;!Array.isArray(t)&&(c!=null||d!=null||h!=null)&&(t=lp(t,{format:c,mask:d,places:h,dtype:p,locale:this._displayLocale(e,f)}));let b=this._formatAttrs(m);if(l){if(!Object.hasOwn(r,"id")){let x=this.builder.targetId(e);x!==null&&(b+=` id="${this._htmlAttrValue(x)}"`)}for(let[x,S]of Object.entries(e.getAttr()))e.pointerType(S)&&(b+=` data-${this.adapt(x)}-pointer="${this._htmlAttrValue(e.absDatapath(S))}"`)}let w=a?" ".repeat(this._nodeDepth(e,s)):"",_=a?`
|
|
40
|
-
`:"";if(e._getMeta("void"))return`${w}<${o}${b}${i?"/":""}>${_}`;if(Array.isArray(t)){let x=this._composeStringFragments(t);return`${w}<${o}${b}>${_}${x}${w}</${o}>${_}`}if(t==null)return`${w}<${o}${b}></${o}>${_}`;let y=typeof t=="string"&&t.endsWith("::HTML")?t.slice(0,-6):Jy.has(o)?String(t):this._escapeText(t);return`${w}<${o}${b}>${y}</${o}>${_}`}_displayLocale(e,t){if(t)return t;for(let r=e.parentNode;r;r=r.parentNode){let o=r.getAttr("locale");if(o==null)continue;let i=r.pointerType(o)?r.data.getItem(r.absDatapath(o)):o;if(i)return i}}adaptAttrs(e){let t={},r={};for(let[i,a]of Object.entries(e||{}))if(i.startsWith(`${this.builder.constructor._name}_`))t[this.adapt(i)]=a;else if(i==="dtype")t.dtype=a;else{if(this.builder.constructor.retainedAttrPrefixes.some(s=>i.startsWith(s)))continue;this._isStyleContribution(i)?r[i]=a:t[i]=a}let o=this._adaptStyle(r);return o&&(t.style=o),t}_isStyleContribution(e){if(e==="style"||e.startsWith("style_")||gi.has(e))return!0;let t=e.includes("_")?e.slice(0,e.indexOf("_")):null;return t!==null&&gi.has(t)||ev(e)}_adaptStyle(e){let t=tv(e.style),r=new Map,o=new Map;for(let[i,a]of Object.entries(e))if(i!=="style")if(i.startsWith("style_"))t.set(i.slice(6).replaceAll("_","-"),cp(a));else if(gi.has(i))r.set(i,a);else{let s=i.indexOf("_"),l=s<0?i:i.slice(0,s);s>=0&&gi.has(l)?(o.has(l)||o.set(l,{}),o.get(l)[i.slice(s+1)]=a):t.set(i.replaceAll("_","-"),cp(a))}for(let i of gi)(r.has(i)||o.has(i))&&this[`_macro_${i}`](r.get(i),o.get(i)||{},t);return[...t].map(([i,a])=>`${i}: ${a}`).join("; ")}_formatAttrs(e){let t=[];for(let[r,o]of Object.entries(e||{}))Qy.has(r)?o&&t.push(` ${r}`):t.push(` ${r}="${this._htmlAttrValue(o)}"`);return t.join("")}_htmlAttrValue(e){return(e===!0?"true":e===!1?"false":String(e)).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}_macro_rounded(e,t,r){let o=e===void 0?{}:{top_left:e,top_right:e,bottom_left:e,bottom_right:e};for(let[i,a]of Object.entries(t))if(i==="top"||i==="bottom")o[`${i}_left`]=a,o[`${i}_right`]=a;else if(i==="left"||i==="right")o[`top_${i}`]=a,o[`bottom_${i}`]=a;else if(["top_left","top_right","bottom_left","bottom_right"].includes(i))o[i]=a;else throw new TypeError(`rounded: unknown sub-kwarg '${i}'`);for(let[i,a]of Object.entries(o))r.set(`border-${i.replaceAll("_","-")}-radius`,rs(a))}_macro_transform(e,t,r){let o=e===void 0?[]:[String(e)];for(let[i,a]of Object.entries(t))i==="rotate"?o.push(`rotate(${a}deg)`):i==="scale"||i==="translate"?o.push(`${i}(${a})`):i==="translate_x"?o.push(`translateX(${rs(a)})`):i==="translate_y"?o.push(`translateY(${rs(a)})`):i==="skew_x"?o.push(`skewX(${a}deg)`):i==="skew_y"?o.push(`skewY(${a}deg)`):o.push(`${i.replaceAll("_","-")}(${a})`);o.length&&r.set("transform",o.join(" "))}_macro_filter(e,t,r){let o=e===void 0?[]:[String(e)];for(let[i,a]of Object.entries(t))i==="rotate"?o.push(`hue-rotate(${a}deg)`):i==="blur"?o.push(`blur(${rs(a)})`):i==="drop_shadow"?o.push(`drop-shadow(${a})`):o.push(`${i.replaceAll("_","-")}(${a})`);o.length&&r.set("filter",o.join(" "))}_macro_transition(e,t,r){e!==void 0&&r.set("transition",String(e));for(let[o,i]of Object.entries(t))r.set(`transition-${o.replaceAll("_","-")}`,String(i))}_macro_zoom(e,t,r){e!==void 0&&r.set("zoom",String(e))}_macro_shadow(e,t,r){e!==void 0&&r.set("box-shadow",String(e));for(let[o,i]of Object.entries(t))r.set(`box-shadow-${o.replaceAll("_","-")}`,String(i))}_macro_gradient(e,t,r){e!==void 0&&r.set("background-image",String(e))}};var rv=new Set(["alignment_baseline","baseline_shift","clip_path","clip_rule","color_interpolation","color_interpolation_filters","dominant_baseline","fill_opacity","fill_rule","flood_color","flood_opacity","font_family","font_size","font_size_adjust","font_stretch","font_style","font_variant","font_weight","glyph_orientation_horizontal","glyph_orientation_vertical","image_rendering","letter_spacing","lighting_color","marker_end","marker_mid","marker_start","overline_position","overline_thickness","paint_order","pointer_events","shape_rendering","stop_color","stop_opacity","strikethrough_position","strikethrough_thickness","stroke_dasharray","stroke_dashoffset","stroke_linecap","stroke_linejoin","stroke_miterlimit","stroke_opacity","stroke_width","text_anchor","text_decoration","text_rendering","underline_position","underline_thickness","unicode_bidi","word_spacing","writing_mode"]);function ns(n){return Object.fromEntries(Object.entries(n||{}).map(([e,t])=>[rv.has(e)?e.replaceAll("_","-"):e,t]))}var rn=class extends en{static mode="svg";adaptAttrs(e){return ns(e)}};var dp={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"html",version:null,title:null,description:null},abstracts:{},elements:{svg:{doc:"Switch to the SVG dialect from this node down (BLD.2).\n\n A sub-builder element: ``_meta['subbuilder']`` switches the active\n dialect to SVG from this node down. No ``render_tag``: ``<svg>`` is\n emitted verbatim (HTML5 has a native ``<svg>`` tag).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{subbuilder:"svg"}},a:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},abbr:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},address:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},area:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},article:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},aside:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},audio:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},b:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},base:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},bdi:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},bdo:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},blockquote:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},body:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},br:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},button:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},canvas:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},caption:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},cite:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},code:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},col:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},colgroup:{doc:null,sub_tags:"col,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},data:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},datalist:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,option,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dd:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},del_:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},details:{doc:null,sub_tags:"summary[0:1],a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dfn:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dialog:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},div:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dl:{doc:null,sub_tags:"dd,div,dt,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dt:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},em:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},embed:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},fieldset:{doc:null,sub_tags:"legend[0:1],a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},figcaption:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},figure:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figcaption[0:1],figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},footer:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},form:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h1:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h2:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h3:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h4:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h5:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h6:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},head:{doc:null,sub_tags:"base[0:1],link,meta,noscript,script,style,template,title[0:1]",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},header:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},hgroup:{doc:null,sub_tags:"h1,h2,h3,h4,h5,h6,p,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},hr:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},html:{doc:null,sub_tags:"head[0:1],body[0:1]",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},i:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},iframe:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},img:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},input:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},ins:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},kbd:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},label:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},legend:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,h1,h2,h3,h4,h5,h6,hgroup,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},li:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},link:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},main:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},map:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},mark:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},menu:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},meta:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},meter:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},nav:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},noscript:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},object:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ol:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},optgroup:{doc:null,sub_tags:"div,legend,noscript,option,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},option:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,div,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},output:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},p:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},picture:{doc:null,sub_tags:"img[0:1],script,source,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},pre:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},progress:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},q:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rp:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rt:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ruby:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},s:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},samp:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},script:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},search:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},section:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},select:{doc:null,sub_tags:"button,div,hr,noscript,optgroup,option,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},slot:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},small:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},source:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},span:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},strong:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},style:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},sub:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},summary:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,h1,h2,h3,h4,h5,h6,hgroup,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},sup:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},table:{doc:null,sub_tags:"caption[0:1],colgroup,script,tbody,template,tfoot[0:1],thead[0:1],tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tbody:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},td:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},template:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,del_,details,dfn,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,legend,li,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,optgroup,option,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,tr,track,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},textarea:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tfoot:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},th:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},thead:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},time:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},title:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tr:{doc:null,sub_tags:"script,td,template,th",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},track:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},u:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ul:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},var:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},video:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},wbr:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},selectedcontent:{doc:"Mirror of the selected option for Customizable Select (HTML 2024).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};var qt=class extends Ze{static _name="html";static _defaultRenderMode="html";static retainedAttrPrefixes=["validate_","dtype"];static{this.defineGrammar(dp)}get renderer_html(){return new tn(this)}};Ze.registerBuilder(qt);var fp={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"svg",version:null,title:null,description:null},abstracts:{graphics:{doc:"SVG graphics content: any graphical element.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:null},containerElement:{doc:"SVG container content: elements that can hold children.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:null}},elements:{html:{doc:"Switch to the HTML dialect from this node down (BLD.2).\n\n A sub-builder element: ``_meta['subbuilder']`` switches the active\n dialect to HTML from this node down. The source tag ``html`` is\n rendered as ``_meta['render_tag']`` (``<foreignObject>``) carrying\n ``_meta['render_attributes']`` (the SVG namespace). The immediate\n HTML child declares XHTML so both sides of the XML boundary retain\n their native namespace.\n ",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{subbuilder:"html",render_tag:"foreignObject",render_attributes:{xmlns:"http://www.w3.org/2000/svg"}}},svg:{doc:"Root SVG container or nested SVG viewport.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},g:{doc:"Group container for applying transforms and styles.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},defs:{doc:"Container for referenced elements (gradients, patterns, etc.).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},symbol:{doc:"Reusable graphical template, rendered only when referenced by <use>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},use:{doc:"Reference and render a <symbol> or other element.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rect:{doc:"Rectangle.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},circle:{doc:"Circle.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ellipse:{doc:"Ellipse.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},line:{doc:"Line segment between two points.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},polyline:{doc:"Open shape of connected line segments.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},polygon:{doc:"Closed shape of connected line segments.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},path:{doc:"Arbitrary shape defined by path commands (d attribute).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},image:{doc:"Embedded raster image.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},text:{doc:"Text block. Contains text content and optional <tspan>/<textPath>.",sub_tags:"tspan,textPath",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tspan:{doc:"Inline text span within <text>.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},textPath:{doc:"Text rendered along a path shape.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},linearGradient:{doc:"Linear gradient definition. Place inside <defs>.",sub_tags:"stop",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},radialGradient:{doc:"Radial gradient definition. Place inside <defs>.",sub_tags:"stop",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},stop:{doc:"Gradient stop (color and offset).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},pattern:{doc:"Tile pattern definition. Place inside <defs>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},clipPath:{doc:"Clipping path definition.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},mask:{doc:"Alpha mask definition.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},marker:{doc:"Marker symbol for line endpoints or vertices.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},filter:{doc:"Filter effect container. Place inside <defs>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feGaussianBlur:{doc:"Gaussian blur filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feOffset:{doc:"Offset filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feBlend:{doc:"Blend filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feColorMatrix:{doc:"Color matrix filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feComposite:{doc:"Composite filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feFlood:{doc:"Flood fill filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMerge:{doc:"Merge filter primitive (container for feMergeNode).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMergeNode:{doc:"Single input for feMerge.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDropShadow:{doc:"Drop shadow filter primitive (SVG 2).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDiffuseLighting:{doc:"Diffuse lighting filter primitive.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feSpecularLighting:{doc:"Specular lighting filter primitive.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},fePointLight:{doc:"Point light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDistantLight:{doc:"Distant light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feSpotLight:{doc:"Spot light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMorphology:{doc:"Morphology filter primitive (erode/dilate).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feTurbulence:{doc:"Turbulence noise filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDisplacementMap:{doc:"Displacement map filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feConvolveMatrix:{doc:"Convolution matrix filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feImage:{doc:"Image filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feTile:{doc:"Tile filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animate:{doc:"Animate an attribute over time.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animateTransform:{doc:"Animate a transform attribute.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animateMotion:{doc:"Animate motion along a path.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},set:{doc:"Set an attribute to a value for a duration.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},title:{doc:"Accessible title (tooltip in browsers).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},desc:{doc:"Accessible description.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},metadata:{doc:"Metadata container (RDF, Dublin Core, etc.).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},a:{doc:"Hyperlink wrapper.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},foreignObject:{doc:"Container for non-SVG content (HTML, MathML).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},switch:{doc:"Conditional processing (renders first matching child).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};var kr=class extends Ze{static _name="svg";static _defaultRenderMode="svg";static{this.defineGrammar(fp)}get renderer_svg(){return new rn(this)}};Ze.registerBuilder(kr);function Tt(n,e=new Set){if(!n||typeof n!="object")return;let t=n.ownerDocument?.defaultView?.Node??n.defaultView?.Node;if(ie(n)instanceof Xe||t&&n instanceof t)throw new TypeError("Live Source/DOM references cannot cross a transport boundary");if(e.has(n))throw new TypeError("Transport data cannot contain circular references");e.add(n);let r=n instanceof E?n.getNodes().flatMap(o=>[o.staticValue,o.getAttr()]):Object.values(n);for(let o of r)Tt(o,e);e.delete(n)}var bi=class{constructor(e=null){this.entries=new Map,this.sourceRoot=e}validate(e,t=new Set){let r=new Map,o=i=>{for(let a of i.getNodes()){let s=a.getAttr("__ref");if(s){if(r.has(s))throw new Error("Duplicate Source reference");let l=this.entries.get(s);if(e!==this.sourceRoot&&l&&l.node!==a&&!t.has(l.node))throw new Error("Duplicate Source reference");r.set(s,a)}a.value instanceof I&&o(a.value)}};o(e)}register(e,t){let r=e.getAttr("__ref");if(r){if(this.entries.has(r))throw new Error(`Duplicate Source reference: ${r}`);this.entries.set(r,{node:e,dom:t})}}remove(e){for(let[t,r]of this.entries)r.node===e&&this.entries.delete(t)}resolveArguments(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r&&typeof r=="object"&&Object.hasOwn(r,"$gramlotRef")?this.resolve(r):r]))}resolve(e){if(!e||!["node","dom"].includes(e.kind))throw new TypeError("Expected a node or DOM reference");let t=this.entries.get(e.$gramlotRef);if(!t)throw new Error("Source reference is not mounted");return t[e.kind]}};function K(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),n=>n.toString(16).padStart(2,"0")).join("")}var Ke=class{constructor(e){this.gramlot=e}};var nn=class extends Error{name="RpcError";constructor({code:e,name:t,message:r,details:o}){super(r),this.code=e,this.remoteName=t,o!==void 0&&(this.details=o)}},wi=class extends Ke{constructor(e,{rpcUrl:t,closeUrl:r,document:o,transport:i}){super(e),this.transport=i===!1?null:i??e.serverAdapter.createTransport({rpcUrl:t,closeUrl:r,document:o,channel:e._pageStore}),this.remoteRequests=new Map}get supportsCallSync(){return this.transport?.supportsCallSync===!0}callSync(e,t,r={}){if(!this.supportsCallSync)throw new Error(`rpc '${t}': the transport of this page has no synchronous call`);if(Tt(r),this.gramlot.abort.signal.aborted)throw this.gramlot.abort.signal.reason;let o=K(),i=F(this.transport.callSync(L({id:o,pageId:this.gramlot.pageId,contentType:e,name:t,params:r})));if(i.id!==o)throw new Error("rpc response id mismatch");if(i.error)throw new nn(i.error);return i.value}async call(e,t,r={},o={}){return(await this.callEnvelope(e,t,r,o)).value}async callEnvelope(e,t,r={},{signal:o=null}={}){if(!this.transport?.call)throw new Error(`rpc '${t}' is unavailable without a server transport`);Tt(r);let i=K(),a=L({id:i,pageId:this.gramlot.pageId,contentType:e,name:t,params:r}),s=o?[this.gramlot.abort.signal,o]:[this.gramlot.abort.signal],l=s.find(f=>f.aborted);if(l)throw l.reason;let u=new AbortController,c=f=>u.abort(f.target.reason);for(let f of s)f.addEventListener("abort",c,{once:!0});let d=new Promise((f,h)=>{u.signal.addEventListener("abort",()=>{this.remoteRequests.delete(i),h(u.signal.reason)},{once:!0})});this.remoteRequests.set(i,u);try{let f=F(await Promise.race([this.transport.call(a,u.signal),d]));if(f.id!==i)throw new Error("rpc response id mismatch");if(f.error)throw new nn(f.error);return f}finally{this.remoteRequests.delete(i);for(let f of s)f.removeEventListener("abort",c)}}};var os=class{constructor(e,t,r){this.gramlot=e,this.window=r.defaultView,this.frames=e._frames,this.binders=new Map,this.calls=new Map,this.routes=new Map,this.error=null,this.closed=!1,this.ready=!1,this.socket=null;let o=new URL(t,r.baseURI);o.protocol=o.protocol==="https:"?"wss:":"ws:",this.endpoint=o.href,this.origin=this.window.location.origin,this.parent=this.frames.parent?.window??null,this.frames.registerChannel("server",{changed:i=>this.peerChanged(i),disconnected:i=>{i.parent?this.fail(new Error("PageStore parent disconnected")):this.forget(i.window)},receive:(i,a)=>{try{this.receive(i,a)}catch(s){this.fail(s)}}},{endpoint:this.endpoint,ready:!1}),!this.parent&&(o.searchParams.set("pageId",e.pageId),this.socket=new this.window.WebSocket(o.href),this.socket.addEventListener("open",()=>this.connected()),this.socket.addEventListener("message",i=>{try{this.deliver(i.data)}catch(a){this.fail(a)}}),this.socket.addEventListener("error",()=>this.fail(new Error("PageStore WebSocket failed"))),this.socket.addEventListener("close",i=>{this.closed||this.fail(new Error("PageStore disconnected ("+i.code+")"))}))}peerChanged(e){if(this.closed||!e.parent)return;let t=e.channels.server;e.origin!==this.origin||t?.endpoint!==this.endpoint?this.fail(new Error("Parent does not provide the same PageStore endpoint")):t.ready?this.connected():this.ready&&this.fail(new Error("PageStore parent channel closed"))}connected(){if(!(this.closed||this.ready)){this.ready=!0,this.parent&&this.upstream({op:"attach",pageId:this.gramlot.pageId});for(let e of this.binders.values())this.subscribe(e);for(let e of this.calls.values())this.sendCall(e);this.frames.setChannelState("server",{endpoint:this.endpoint,ready:!0})}}receive(e,t){if(this.closed||e.origin!==this.origin||e.channels.server?.endpoint!==this.endpoint)return;if(e.parent){this.deliver(L(t));return}if(!this.ready)return;let r=t?.pageId;if(!(typeof r!="string"||!r||r===this.gramlot.pageId)){if(t.op==="attach"){if(this.routes.has(r))return;this.routes.set(r,e.window)}else if(this.routes.get(r)!==e.window)return;t.op==="detach"&&this.routes.delete(r),this.upstream(t)}}forget(e){for(let[t,r]of this.routes)r===e&&(this.routes.delete(t),this.ready&&!this.closed&&this.upstream({op:"detach",pageId:t}))}upstream(e){if(this.closed||!this.ready)throw new Error("PageStore is not connected");this.parent?this.frames.send(this.parent,"server",e):this.socket.send(L(e))}deliver(e){if(this.closed)return;let t=F(e);if(t.pageId===this.gramlot.pageId){if(t.op==="closed"){this.fail(new Error("PageStore page closed on the server"));return}if(!Object.hasOwn(t,"op")&&Object.hasOwn(t,"id")){this.calls.get(t.id)?.finish(null,e);return}if(t.op==="publish"){try{this.gramlot._subscriptions.publish(t.topic,t.payload,t.metadata)}catch(o){this.window.console.error("PageStore publication subscriber failed",o)}return}let r=this.binders.get(t.binderId);r&&r.apply(t)}else{let r=this.routes.get(t.pageId);r&&this.frames.send(r,"server",t)}}register(e){if(this.closed)throw new Error("PageStore connection is closed");this.binders.set(e.id,e),this.ready&&this.subscribe(e)}subscribe(e){this.send({op:"subscribe",binderId:e.id,path:e.serverPath})}unregister(e){this.binders.delete(e.id)&&!this.closed&&this.ready&&this.send({op:"unsubscribe",binderId:e.id})}send(e){this.upstream({...e,pageId:this.gramlot.pageId})}preparePublish(e,t){if(this.closed||!this.ready)throw new Error("PageStore is not connected");Tt(t);let r={op:"publish",id:K(),pageId:this.gramlot.pageId,topic:e.topic,payload:t};e.pageId!==void 0&&(r.targetPageId=e.pageId);let o=L(r);return async()=>{let i=F(await this.call(o));if(i.error)throw new nn(i.error);return i.value}}call(e,t){if(this.closed)return Promise.reject(this.error??new Error("PageStore connection is closed"));if(t?.aborted)return Promise.reject(t.reason);let r=F(e);return r.pageId!==this.gramlot.pageId||typeof r.id!="string"||!r.id||Object.hasOwn(r,"op")&&r.op!=="publish"||this.calls.has(r.id)?Promise.reject(new Error("Invalid or duplicate RPC identity")):new Promise((o,i)=>{let a={message:r,sent:!1,finish:(l,u)=>{this.calls.delete(r.id)&&(t?.removeEventListener("abort",s),u===void 0?i(l):o(u))}},s=()=>{if(a.finish(t.reason),a.sent&&this.ready&&!this.closed)try{this.send({op:"cancel",id:r.id})}catch(l){this.fail(l)}};this.calls.set(r.id,a),t?.addEventListener("abort",s,{once:!0}),this.ready&&this.sendCall(a)})}sendCall(e){try{this.upstream(e.message),e.sent=!0}catch(t){e.finish(t),this.fail(t)}}fail(e){this.error=e,this.close(),this.window.console.error("PageStore channel failed",e)}close(){if(!this.closed){if(this.closed=!0,this.parent&&this.ready&&this.frames.isConnected(this.parent))for(let e of[...this.routes.keys(),this.gramlot.pageId])this.frames.send(this.parent,"server",{op:"detach",pageId:e});this.ready=!1;for(let e of this.calls.values())e.finish(this.error??new Error("PageStore connection is closed"));this.binders.clear(),this.routes.clear(),this.frames.unregisterChannel("server"),this.socket?.close()}}};var hp="gramlot:message",is=class{#e;#t;#r;#n=K();#o=new Map;#i=new Map;#a=!1;#s;#l;#u;#c;#d;constructor(e,t){this.#e=e,this.#r=t,this.#t=t.defaultView,this.#s=r=>this.#g(r),this.#l=r=>{if(r.target?.localName!=="iframe")return;let o=this.#v(r.target);o&&this.#w(o)},this.#u=r=>{r.persisted||this.#e.dispose({beacon:!0})},this.#c=()=>this.ready(),this.#t.addEventListener("message",this.#s),this.#t.addEventListener("pagehide",this.#u),this.#t.addEventListener("pageshow",this.#c),t.addEventListener("load",this.#l,!0)}#f(){this.#d===void 0&&(this.#d=this.#t.setInterval(()=>{if(this.parent?.window.closed){this.#p();return}for(let e of this.children)e.window.closed?this.#h(e.window):e.node&&!this.#v(this.#e.dom.getDomNode(e.node))&&this.#h(e.window,!0)},500))}get parent(){let e=this.#t.parent!==this.#t,t=e?this.#t.parent:this.#t.opener;return t?{window:t,parent:!0,kind:e?"iframe":"popup",origin:this.#E(this.#r.referrer||this.#r.baseURI)}:null}get children(){return[...this.#o.values()].filter(e=>!e.parent)}isConnected(e){return!this.#a&&this.#o.has(e)}connect(){this.parent&&(this.#f(),this.#w(this.parent));for(let e of this.#r.getElementsByTagName("iframe")){let t=this.#v(e);t&&this.#w(t)}}ready(){if(!this.#a){this.connect();for(let e of this.#o.values())this.#_(e)}}registerChannel(e,t,r){if(this.#a||e==="publish"||this.#i.has(e))throw new Error("Invalid family channel");this.#i.set(e,{handler:t,state:r});for(let o of this.#o.values())t.changed(o)}setChannelState(e,t){this.#i.get(e).state=t;for(let r of this.#o.values())this.#_(r)}unregisterChannel(e){if(this.#i.delete(e),this.#e.state!=="disposed")for(let t of this.#o.values())this.#_(t)}send(e,t,r){let o=this.#o.get(e);if(this.#a||!o)throw new Error("Destination page is not connected");Tt(r),this.#y(o,{kind:"message",recipient:o.session,channel:t,wire:L(r)})}prepare(e,t){let r=[];if(e.parent){if(!this.parent)throw new Error("This page has no parent frame or opener");r.push(this.parent)}if(e.iframe!==void 0){let a=e.iframe,s=ie(a),l=typeof a=="string"?this.#r.getElementById(a):s instanceof Xe?this.#e.dom.getDomNode(s):null,u=this.#v(l);if(!u)throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");r.push(u)}if(e.pageId!==void 0){let a=this.children.find(s=>s.pageId===e.pageId);if(!a)throw new Error("pageId destination must be a registered direct Gramlot child");r.push(a)}let o=r.map(a=>{let s=this.#o.get(a.window);if(!s?.ready||s.origin!==a.origin)throw new Error("Destination page is not ready");return{...a,session:s.session}});Tt(t);let i=L({topic:e.topic,payload:t});return()=>{if(!this.#a)for(let a of o){let s=this.#k(a.window);if(!s||s.origin!==a.origin||this.#o.get(a.window)?.session!==a.session)throw new Error("Destination page disconnected before publication");this.#y(a,{kind:"message",recipient:a.session,channel:"publish",wire:i})}}}dispose(){if(this.#a)return;for(let t of this.children)this.#h(t.window,!0);let e=this.parent;e&&this.#o.has(e.window)&&(this.#y(this.#o.get(e.window),{kind:"close"}),this.#h(e.window)),this.#a=!0,this.#i.clear(),this.#t.removeEventListener("message",this.#s),this.#t.removeEventListener("pagehide",this.#u),this.#t.removeEventListener("pageshow",this.#c),this.#t.clearInterval(this.#d),this.#r.removeEventListener("load",this.#l,!0)}#p(){this.#e.dispose({beacon:!0}),this.#t.parent===this.#t&&this.#t.opener&&this.#t.close()}#h(e,t=!1){let r=this.#o.get(e);if(r){t&&this.#y(r,{kind:"close"}),this.#o.delete(e),r.release?.();for(let{handler:o}of this.#i.values())o.disconnected(r);t&&r.kind==="popup"&&!r.parent&&e.close()}}#m(e,t){let r=this.#o.get(e.window),o=r?.session!==t.session;o&&this.#h(e.window);let i=o?{...e,session:t.session}:r;Object.assign(i,{ready:t.ready===!0,pageId:t.pageId,channels:t.channels}),this.#o.set(e.window,i),this.#f(),o&&e.node&&(i.release=this.#e.src.binding.bindingFor(e.node).track(()=>{this.#h(e.window,!0)}));for(let{handler:a}of this.#i.values())a.changed(i);return o}#g(e){if(this.#a||e.data?.type!==hp)return;let t=this.#k(e.source);if(!t||e.origin!==t.origin)return;let r=e.data;if(typeof r.session!="string"||!r.session)return;if(r.kind==="hello"||r.kind==="ready"){if(r.kind==="ready"&&r.recipient!==this.#n||!r.channels||typeof r.channels!="object"||Array.isArray(r.channels))return;let i=this.#m(t,r);(r.kind==="hello"||i)&&this.#_(this.#o.get(t.window));return}let o=this.#o.get(t.window);if(!(!o||o.session!==r.session||r.recipient!==this.#n)){if(r.kind==="close")t.parent?this.#p():this.#h(t.window);else if(r.kind==="message"&&typeof r.wire=="string"){let i=F(r.wire);if(r.channel==="publish"){if(this.#e.state!=="started"||!o.ready||typeof i.topic!="string"||!i.topic)return;this.#e.publish(i.topic,i.payload)}else this.#i.get(r.channel)?.handler.receive(o,i)}}}#b(){return{pageId:this.#e.pageId,ready:this.#e.state==="started",channels:Object.fromEntries([...this.#i].map(([e,t])=>[e,t.state]))}}#w(e){this.#y(e,{kind:"hello",...this.#b()})}#_(e){this.#y(e,{kind:"ready",recipient:e.session,...this.#b()})}#y(e,t){e.window.postMessage({type:hp,session:this.#n,recipient:e.session,...t},e.origin==="null"?"*":e.origin)}#v(e){if(e?.localName!=="iframe"||!e.isConnected||!e.contentWindow)return null;let t=this.#e.dom.getBaseSourceNode(e);if(!t||!this.#e.src.binding.bindingFor(t)||this.#e.dom.getDomNode(t)!==e)return null;let r=e.getAttribute("sandbox"),i=r!==null&&!r.split(/\s+/).includes("allow-same-origin")?"null":this.#E(e.hasAttribute("srcdoc")?this.#r.baseURI:e.getAttribute("src")||this.#r.baseURI);return{window:e.contentWindow,origin:i,node:t,parent:!1,kind:"iframe"}}#E(e){let t=new URL(e,this.#r.baseURI);return t.protocol==="file:"?"null":t.origin}#k(e){let t=this.parent;if(t?.window===e)return t;for(let r of this.#r.getElementsByTagName("iframe")){let o=this.#v(r);if(o?.window===e)return o}try{if(e&&e!==this.#t&&e.opener===this.#t&&e.location.origin===this.#t.location.origin)return{window:e,origin:this.#E(this.#r.baseURI),parent:!1,kind:"popup"}}catch{}return null}};var on=class n{#e;constructor(e,t=0){this.pattern=e,this.flags=t,this.#e=no.fromJSON({nameSyntax:{kind:"annotated",base:{kind:"type",module:"builtins",name:"str"},metadata:[this.toJSON()]}}).resolve("nameSyntax").test,Object.freeze(this)}static fromJSON(e){if((e!==null&&typeof e=="object"?Object.keys(e).sort():[]).join()!=="flags,kind,pattern"||e.kind!=="regex")throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(e)}`);return new n(e.pattern,e.flags)}toJSON(){return{kind:"regex",pattern:this.pattern,flags:this.flags}}matches(e){return this.#e(e)}},_i=new on(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);function oo(n,e=","){if(typeof e!="string"||!e)throw new TypeError("separator must be a nonempty string");if(n==="")return[];let t=new Set;return n.split(e).map(r=>{let o=r.indexOf(":"),i=o<0?r:r.slice(0,o),a=o<0?r:r.slice(o+1);if(!i||t.has(i))throw new Error("Invalid or duplicate choice code");return t.add(i),{id:i,caption:a}})}function as(n,e,t=""){return n.find(r=>r.id===e)?.caption??t??""}var ss=class{constructor(e,t){this.layout=e;let r=e.box.ownerDocument;this.button=r.createElement("button"),this.button.type="button",this.button.className="label-menu-trigger",this.button.setAttribute("aria-haspopup","menu"),this.button.setAttribute("aria-expanded","false"),this.menu=r.createElement("gramlot-menu"),this.menu.projectAttributes({}),e.labelBox.append(this.button,this.menu),this.button.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),this.menu.opened?this.menu.close():this.menu.open(this.button)}),this.button.addEventListener("keydown",o=>{["ArrowDown","ArrowUp"].includes(o.key)&&(o.preventDefault(),o.stopPropagation(),this.menu.open(this.button,o.key==="ArrowUp"))}),this.choose=t}project({lbl:e,lbl_value:t,lbl_values:r,disabled:o,readonly:i},a){let s=oo(r);if(this.values!==r){this.menu.close(!1);for(let u of this.menu.items)u.releaseCommand();this.menu.replaceChildren(...s.map(({id:u,caption:c})=>{let d=this.menu.ownerDocument.createElement("gramlot-menu-line");return d.projectAttributes({code:u,caption:c},a),d.activateCommand=f=>{d.prepareCommand(f)&&this.choose(u)},d.control.addEventListener("click",f=>d.activateCommand(f)),d})),this.values=r}let l=as(s,t,e);this.button.textContent=l,this.button.disabled=!!(o||i||!s.length),this.button.disabled&&this.menu.close(!1);for(let u of this.menu.items)u.projectAttributes({...u.parameters,checked:u.parameters.code===t},a);this.layout.fieldLabel.textContent=l,this.layout.fieldLabel.hidden=!0,this.layout.labelBox.hidden=!1}dispose(){this.menu.close(!1);for(let e of this.menu.items)e.releaseCommand();this.menu.remove(),this.button.remove(),this.layout.fieldLabel.hidden=!1}};var Yu=["TL","TC","TR","L","R","BL","BC","BR"],pp=`.gramlot-labelbox>.label-box>.label-menu-trigger{font:inherit;color:inherit;background:transparent;border:0;padding:0;min-width:0;min-height:var(--gramlot-touch-target,0px);height:auto;display:inline-flex;align-items:center;gap:.4em;cursor:pointer;text-align:inherit;line-height:inherit}
|
|
38
|
+
`)}},ci=class extends Error{constructor(e){super(e),this.name="BagException"}};fe.registerBagClass(E);Pu(E,"X",n=>n._toTytxPayload(),n=>E._fromTytxPayload(n));Yr(E.tytxSuffix,{...pt(E.tytxSuffix),Bag:E});var Vh=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield"]);function zh(n){return n.endsWith("_")&&Vh.has(n.slice(0,-1))?n.slice(0,-1):n}function Hh(n){let e=zh(n);return e!==n?e:n.startsWith("_")&&Vh.has(n.slice(1))?n.slice(1):n}function di(n,{renderTag:e=null,ns:t=null,dialectName:r=null}={}){let o=e||n;if(!o)return o;if(o=zh(o),t&&!e){let i=`${r}_`;o.startsWith(i)&&(o=o.slice(i.length)),o=`${t}:${o}`}return o}var ro=Symbol("value"),Zt=new Set(["_meta","datapath","nodeId","ns","form","formId","_anchor","updateOn"]);function Le(n){return Object.entries(n||{}).filter(([e])=>!Zt.has(e)).map(([e,t])=>[Hh(e),t])}var Xe=class extends xt{constructor(e,t,r=null,o=null,i=null,a=null,s=null){super(e,t,r,o,i,a,s),this._builder=e?._insertingBuilder??e?._builder??null,this._targetId=null}get builder(){if(this._builder)return this._builder;let e=this.parentBag;return e?e._builder:null}get data(){return this.builder.data}get rootBuilder(){return this.parentBag.root._builder}_getMeta(e){let t=this.getAttr("_meta")||{},r=e.split(",").map(o=>o.trim());return r.length===1?t[r[0]]!==void 0?t[r[0]]:null:r.map(o=>t[o]!==void 0?t[o]:null)}pointerType(e){return typeof e=="string"&&(e[0]==="^"||e[0]==="=")&&!e.startsWith("==")?e[0]:null}pointers(){this.builder.validateCustomTypes(this);let e=[];for(let[t,r]of Object.entries(this.getAttr()||{}))this.pointerType(r)==="^"&&e.push([t,r.split(":",1)[0]]);return this.pointerType(this.value)==="^"&&e.push(["",this.value.split(":",1)[0]]),e}fixedAttrItems(){return Le(this.getAttr())}runtimeToEvaluate(){let e=new Map(this.fixedAttrItems());return e.set(ro,this.value),e}absDatapath(e){let t=e;this.pointerType(e)&&(e=(ne(e)?.pointer??e).slice(1));let r=null;return e.includes("?")&&([e,r]=e.split("?",2)),e.startsWith("#")?this._finalizeAbsPath(this._resolveSymbolicDatapath(e,t),r):(e.startsWith(".")&&(e=this._composeRelativeDatapath(e,t)),this._finalizeAbsPath(e,r))}_finalizeAbsPath(e,t){return e=this._collapseParentDatapath(e,e),t?`${e}?${t}`:e}_composeRelativeDatapath(e,t){let r=this;for(;r!==null&&e.startsWith(".");){let o=r.getAttr("datapath");o!=null&&(e=e==="."?o:o+e),r=r.parentNode}if(e.startsWith("."))throw new Error(`unresolved relative datapath: ${t}`);return e}_collapseParentDatapath(e,t){let r=[];for(let o of e.split("."))if(o==="#parent"){if(r.length===0)throw new Error(`#parent has no segment to cancel: ${t}`);r.pop()}else r.push(o);return r.join(".")}_resolveSymbolicDatapath(e,t){let r=e.slice(1),o=r.indexOf("."),i=o===-1?r:r.slice(0,o),a=o===-1?"":r.slice(o+1),s;if(i==="FORM")s=this._findMarkedDatapathAncestor(!0,!1,t);else if(i==="ANCHOR")s=this._findMarkedDatapathAncestor(!1,!0,t);else{let l=this.rootBuilder;if(!l)throw new Error(`#<id>: cannot resolve ${t} on a node without builder`);if(s=l.source.getNodeByAttr("nodeId",i),s==null)throw new Error(`#<id>: cannot resolve ${t}`)}return s.absDatapath(a?`.${a}`:".")}_findMarkedDatapathAncestor(e,t,r){let o=this;for(;o!=null;){let a=o.getAttr()||{};if(e&&(a.formId!=null||a.form===!0)||t&&"_anchor"in a)return o;o=o.parentNode}let i=e?"FORM":"ANCHOR";throw new Error(`#${i}: no marked ancestor found for ${r}`)}getRelativeData(e,t=null,{autocreate:r=!1}={}){let o=this.data,i=this.absDatapath(e);return r&&o.getItem(i)==null&&o.setItem(i,t),o.getItem(i,t)}setRelativeData(e,t,{attributes:r=null,fired:o=!1,reason:i=null}={}){let a=this.data,s=this.absDatapath(e);a.setItem(s,t,r,">",!1,!0,i===null?!0:i,o)}fireEvent(e,t=!0,{attributes:r=null,reason:o=null}={}){this.setRelativeData(e,t,{attributes:r,fired:!0,reason:o})}SET(e,t){this.setRelativeData(e,t)}GET(e){return this.getRelativeData(e)}PUT(e,t){this.setRelativeData(e,t,{reason:!1})}FIRE(e,t=!0){this.setRelativeData(e,t,{fired:!0})}},I=class n extends E{constructor(e=null,t=null){super(e),this._builder=t,this._insertingBuilder=null}get nodeClass(){return Xe}_setBuilderItem(e,t,r,...o){let i=t?.map(([s])=>[s,s._builder])||null;if(t)for(let[s,l]of t)s._builder=l;let a=this._insertingBuilder;this._insertingBuilder=e;try{return this.setItem(r,...o)}catch(s){if(this.node(r)==null&&i)for(let[l,u]of i)l._builder=u;throw s}finally{this._insertingBuilder=a}}bindBuilder(e){if(!e)throw new Error("SourceBag.bindBuilder requires a builder");let t=this._builderBindingPlan(e);for(let[r,o]of t)r._builder=o;return this.setBackref(),this}_builderBindingPlan(e){let t=[],r=new WeakSet,o=(i,a)=>{if(r.has(i))throw new Error("source contains a cyclic or shared SourceBag branch");r.add(i),t.push([i,a]);for(let s of i.getNodes()){let l=a,u=s._getMeta("subbuilder");u!=null&&(l=a._resolveSubbuilderReference(u,s.getAttr()||{},s.nodeTag)),t.push([s,l]);let c=s.getValue(!0);c instanceof n&&o(c,l)}};return o(this,e),t}};if((pt(I.tytxSuffix).SourceBag??I)!==I)throw new Error("TYTX subtype name 'SourceBag' is already registered for another class");Yr(I.tytxSuffix,{...pt(I.tytxSuffix),SourceBag:I});function jy(n){if(n.length===0)return{value:null,attrs:{}};let e=n[0];if(e!==null&&typeof e=="object"){let t=Object.getPrototypeOf(e);if(t===Object.prototype||t===null)return{value:null,attrs:e}}return{value:e,attrs:n[1]||{}}}var qy=new Set(["then","toJSON"]),Wh=new WeakMap;function ae(n){return Wh.get(n)||n}function fi(n){if(n==null)return n;n=ae(n);let e=n._builder||n.parentBag&&n.parentBag._builder;return e?e.wrapSource(n):n}function Yh(n,e){let t=e instanceof E,r=new Proxy(e,{get(o,i){if(typeof i=="symbol"||i.startsWith("_")||qy.has(i))return Reflect.get(o,i,o);let a=n.schemaTag(i);if(t&&a)return Gh(n,o,a,t);if(i in o){let l=Reflect.get(o,i,o);return typeof l=="function"?l.bind(o):l}if(a)return Gh(n,o,a,t);let s=n.containerMethod(i);if(s)return(...l)=>n[s](n.wrapSource(o),...l)}});return Wh.set(r,e),r}function Gh(n,e,t,r){return(...o)=>{let{value:i,attrs:a}=jy(o),s=r?n.bagCall(e,t,i,a):n.commandOnNode(e,t,i,a);return s.builder.wrapSource(s)}}function zu(n,e,{transport:t="json"}={}){let r=j(n,t==="json"?null:t);if(!(r instanceof I))throw new TypeError("TYTX payload did not decode to SourceBag");return r.bindBuilder(e)}var Zh=/^[A-Za-z_][A-Za-z0-9_]*$/,Uy=new Set(["positional_only","positional_or_keyword","keyword_only","var_positional","var_keyword"]),Vy=new Set(["framework","value","attribute"]),zy=new Map([["builtins.str",n=>typeof n=="string"],["builtins.int",n=>Number.isInteger(n)],["builtins.float",n=>typeof n=="number"&&Number.isFinite(n)],["builtins.bool",n=>typeof n=="boolean"],["builtins.list",n=>Array.isArray(n)],["builtins.dict",n=>n!==null&&typeof n=="object"&&!Array.isArray(n)],["builtins.tuple",n=>Array.isArray(n)],["builtins.set",n=>Array.isArray(n)||n instanceof Set],["builtins.NoneType",n=>n===null],["builtins.object",n=>!0]]);function Kr(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function B(n,e){throw new TypeError(`${n}: ${e}`)}function jt(n,e,t,r){Kr(n)||B(r,"must be an object");for(let o of Object.keys(n))e.includes(o)||B(r,`unknown field '${o}'`);for(let o of t)Object.hasOwn(n,o)||B(r,`missing field '${o}'`)}function Jr(n,e){if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(Array.isArray(n))return n.forEach((t,r)=>Jr(t,`${e}[${r}]`));if(Kr(n))return Object.entries(n).forEach(([t,r])=>Jr(r,`${e}.${t}`));B(e,"must be lossless JSON data")}}function Hy(n,e){let t="",r=!1;for(let o=0;o<n.length;o++){let i=n[o];if(i==="\\"){t+=i+(n[++o]??"");continue}i==="["&&(r=!0),!r&&i==="."&&!(e&16)?t+="[^\\n]":!r&&i==="^"&&e&8?t+="(?:^|(?<=\\n))":!r&&i==="$"?t+=e&8?"(?=\\n|(?![\\s\\S]))":"(?=\\n?(?![\\s\\S]))":t+=i,i==="]"&&(r=!1)}return t}function Zr(n,e,t=!1,r=null){if(n===null)return null;switch(jt(n,["kind","dtype","module","name","origin","arguments","items","values","base","metadata","pattern","flags","ge","le","gt","lt","value"],["kind"],e),n.kind){case"custom":return jt(n,["kind","name"],["kind","name"],e),r||B(e,"custom references require a catalog; nested catalog references are unsupported"),r.resolve(n.name,e);case"dtype":{jt(n,["kind","dtype"],["kind","dtype"],e);let o=n.dtype;typeof o!="string"&&B(e,"dtype must be a string");let i=ai(o);return!i&&o!=="NN"&&B(e,`unknown dtype '${o}'`),{...n,test:s=>o==="NN"?s===null:o==="N"?le(s)&&!["NaN","Infinity","-Infinity"].includes(s.toString()):i===Number?typeof s=="number"&&Number.isFinite(s)&&(o!=="L"||Number.isInteger(s)):i===String?typeof s=="string":i===Boolean?typeof s=="boolean":i===Date?s instanceof Date&&Number.isFinite(s.getTime()):i===Object?Kr(s)&&[Object.prototype,null].includes(Object.getPrototypeOf(s)):s instanceof i}}case"any":return{...n,test:o=>!0};case"type":{(typeof n.module!="string"||typeof n.name!="string")&&B(e,"type requires string module/name");let o=`${n.module}.${n.name}`;if(o==="collections.abc.Callable")return{...n,test:a=>typeof a=="function",portable:!1};let i=zy.get(o);return i||B(e,`unsupported type '${o}'`),{...n,test:i}}case"union":{(!Array.isArray(n.items)||!n.items.length)&&B(e,"union items must be non-empty");let o=n.items.map((i,a)=>Zr(i,`${e}.items[${a}]`,!0,r));return{...n,items:o,inputConstraint:o.some(i=>i.inputConstraint),test:i=>o.some(a=>a.test&&a.test(i))}}case"literal":return Array.isArray(n.values)||B(e,"literal values must be an array"),n.values.forEach((o,i)=>Jr(o,`${e}.values[${i}]`)),{...n,test:o=>n.values.some(i=>Object.is(i,o))};case"annotated":{Array.isArray(n.metadata)||B(e,"annotated metadata must be an array"),n.metadata.some(a=>!["regex","range","value"].includes(a?.kind))&&B(e,"unsupported annotation metadata kind");let o=Zr(n.base,`${e}.base`,!0,r),i=n.metadata.map((a,s)=>Zr(a,`${e}.metadata[${s}]`,!0,r));return{...n,base:o,metadata:i,inputConstraint:o.inputConstraint,test:a=>o.test(a)&&i.every(s=>!s.test||s.test(a))}}case"range":{for(let o of["ge","le","gt","lt"])Object.hasOwn(n,o)||B(e,`range missing '${o}'`);for(let o of["ge","le","gt","lt"])n[o]!==null&&(typeof n[o]!="number"||!Number.isFinite(n[o]))&&B(e,`${o} must be finite number or null`);return{...n,test:o=>typeof o=="number"&&(n.ge===null||o>=n.ge)&&(n.le===null||o<=n.le)&&(n.gt===null||o>n.gt)&&(n.lt===null||o<n.lt)}}case"regex":{(typeof n.pattern!="string"||!Number.isInteger(n.flags)||n.flags<0)&&B(e,"regex requires pattern and non-negative integer flags");let o=n.flags&-59;o&&B(e,`unsupported Python regex flags ${o}`),n.flags&2&&B(e,"IGNORECASE is not portable across Python and JavaScript Unicode rules"),/\\[AZzUwWdDsSabBN0-9]|\(\?P[<=!]|\(\?\(|\(\?>|\(\?#|\(\?[aiLmsux-]|[+*?}]\+|\{,/.test(n.pattern.replaceAll(String.raw`[\s\S]`,"."))&&B(e,"regex uses a non-portable construct or character class");let i="uy";n.flags&16&&(i+="s");let a;try{a=new RegExp(`(?:${Hy(n.pattern,n.flags)})(?![\\s\\S])`,i)}catch(s){B(e,`invalid portable regex: ${s.message}`)}return{...n,test:s=>typeof s!="string"?!1:(a.lastIndex=0,a.test(s))}}case"value":return Jr(n.value,`${e}.value`),{...n};case"generic":{let o=Zr(n.origin,`${e}.origin`,!0,r);(n.origin?.kind!=="type"||n.origin.module!=="builtins"||!["list","dict","tuple","set"].includes(n.origin.name))&&B(e,"only list, dict, tuple and set generic origins are supported"),Array.isArray(n.arguments)||B(e,"generic arguments must be an array");let i=n.arguments.map((a,s)=>Zr(a,`${e}.arguments[${s}]`,!0,r));return{...n,origin:o,arguments:i,inputConstraint:i.some(a=>a.inputConstraint),test:a=>o.test(a)&&Gy(n.origin,i,a)}}case"arguments":B(e,"Callable argument-list descriptors are not supported by Python validation");case"ellipsis":return t||B(e,"ellipsis is only valid as a nested descriptor"),{...n};default:B(e,`unknown annotation kind '${n.kind}'`)}}function Gy(n,e,t){let r=`${n.module}.${n.name}`;return r==="builtins.tuple"&&e.length&&e[1]?.kind!=="ellipsis"?t.length===e.length&&t.every((o,i)=>e[i].test(o)):r==="builtins.list"||r==="builtins.set"||r==="builtins.tuple"?[...t].every(o=>!e[0]?.test||e[0].test(o)):r==="builtins.dict"?Object.entries(t).every(([o,i])=>(!e[0]?.test||e[0].test(o))&&(!e[1]?.test||e[1].test(i))):!1}function Kh(n,e){if(n===null)return null;if(typeof n!="string"&&B(e,"must be string or null"),n==="")return new Map;let t=new Map;for(let r of n.split(",")){let o=r.trim();/^[A-Za-z_][A-Za-z0-9_]*\[\]$/.test(o)&&B(e,`invalid cardinality item '${r}'`);let i=o.match(/^([A-Za-z_][A-Za-z0-9_]*|\*)(?:\[(?:(\d+)|(?:(\d*):(\d*)))\])?$/);i||B(e,`invalid cardinality item '${r}'`);let[,a,s,l,u]=i;t.has(a)&&B(e,`duplicate tag '${a}'`);let c=0,d=1/0;o.includes("[")&&(o.includes(":")?(c=l?Number(l):0,d=u?Number(u):1/0):c=d=Number(s)),d<c&&B(e,`maximum ${d} is below minimum ${c}`),t.set(a,{min:c,max:d})}return t.has("*")&&t.size>1&&B(e,"wildcard '*' cannot be combined with named tags"),t}function Jh(n,e){if(n===null)return null;typeof n!="string"&&B(e,"must be string or null");let t=new Set;for(let r of n.split(",")){let o=r.trim();o&&((!Zh.test(o)||t.has(o))&&B(e,`invalid or duplicate parent '${r}'`),t.add(o))}return t}function Wy(n,e,t){if(n===null)return null;jt(n,["parameters","accepts_var_keyword","accepts_var_positional"],[],e);let r=n.parameters??[];Array.isArray(r)||B(e,"parameters must be an array"),n={parameters:r,accepts_var_keyword:r.some(l=>l.kind==="var_keyword"),accepts_var_positional:r.some(l=>l.kind==="var_positional"),...n},(!Array.isArray(n.parameters)||typeof n.accepts_var_keyword!="boolean"||typeof n.accepts_var_positional!="boolean")&&B(e,"invalid signature descriptor");let o=new Set,i=!1,a=!1,s=n.parameters.map((l,u)=>{let c=`${e}.parameters[${u}]`;return jt(l,["name","kind","role","annotation","has_default","default"],["name","kind","role","annotation","has_default"],c),(typeof l.name!="string"||!Zh.test(l.name)||o.has(l.name))&&B(c,"invalid or duplicate parameter name"),o.add(l.name),(!Uy.has(l.kind)||!Vy.has(l.role)||typeof l.has_default!="boolean")&&B(c,"invalid kind, role, or has_default"),l.has_default!==Object.hasOwn(l,"default")&&B(c,"default presence must equal has_default"),l.has_default&&Jr(l.default,`${c}.default`),i||=l.kind==="var_keyword",a||=l.kind==="var_positional",{...l,annotation:Zr(l.annotation,`${c}.annotation`,!1,t)}});return(i!==n.accepts_var_keyword||a!==n.accepts_var_positional)&&B(e,"variadic summary flags do not match parameters"),{...n,parameters:s}}function Xh(n,e,t,r){let o=["doc","sub_tags","parent_tags","inherits_from","ns","attributes",...t?["node_label","collection_key"]:[],"_meta"];jt(n,o,[],e),n={...Object.fromEntries(o.map(i=>[i,null])),...n};for(let i of["doc","inherits_from","ns",...t?["node_label","collection_key"]:[]])n[i]!==null&&typeof n[i]!="string"&&B(e,`${i} must be string or null`);return n._meta!==null&&(Kr(n._meta)||B(e,"_meta must be object or null"),Jr(n._meta,`${e}._meta`)),Kh(n.sub_tags,`${e}.sub_tags`),Jh(n.parent_tags,`${e}.parent_tags`),{...n,attributes:Wy(n.attributes,`${e}.attributes`,r)}}function Qh(n){return n?n.split(",").map(e=>e.trim()).filter(Boolean):[]}function ep(n,e){let t={...e};for(let[r,o]of Object.entries(n))r==="inherits_from"||r.startsWith("_")||t[r]||(t[r]=o);return t._meta={...n._meta||{},...e._meta||{}},t}function tp(n){let e={...n};return e._subSpec=Object.hasOwn(e,"sub_tags")?Kh(e.sub_tags,"resolved.sub_tags"):null,e._parentSpec=Object.hasOwn(e,"parent_tags")?Jh(e.parent_tags,"resolved.parent_tags"):null,e}function rp(n,e,t,r){if(t.get(n)===1&&B(r,`inheritance cycle at '${n}'`),t.get(n)===2)return e[n];let o=e[n];o||B(r,`unknown abstract '${n}'`),t.set(n,1);let i={...o};for(let a of Qh(o.inherits_from))i=ep(rp(a,e,t,r),i);return i=tp(i),t.set(n,2),e[n]=i,i}function Hu({abstracts:n={},elements:e={}}){let t={...n},r=new Map;for(let i of Object.keys(t))rp(i,t,r,`abstracts.${i}.inherits_from`);let o={};for(let[i,a]of Object.entries(e)){let s={...a};for(let l of Qh(a.inherits_from)){let u=t[l];u||B(`elements.${i}.inherits_from`,`unknown abstract '${l}'`),s=ep(u,s)}o[i]=tp(s)}return{abstracts:t,elements:o}}function Gu(n){jt(n,["document_format","grammar","abstracts","elements","custom_types"],["document_format","grammar","abstracts","elements"],"grammar document"),jt(n.document_format,["name","version"],["name","version"],"document_format"),(n.document_format.name!=="builder_grammar"||!["1.1","1.2"].includes(n.document_format.version))&&B("document_format","expected builder_grammar version 1.1 or 1.2"),jt(n.grammar,["name","version","title","description"],["name","version","title","description"],"grammar"),(typeof n.grammar.name!="string"||!n.grammar.name)&&B("grammar.name","must be non-empty string");for(let o of["version","title","description"])n.grammar[o]!==null&&typeof n.grammar[o]!="string"&&B(`grammar.${o}`,"must be string or null");(!Kr(n.abstracts)||!Kr(n.elements))&&B("grammar document","abstracts/elements must be objects"),Object.hasOwn(n,"custom_types")&&n.document_format.version!=="1.2"&&B("custom_types","requires version 1.2");let e=no.fromJSON(n.custom_types??{}),t={};for(let[o,i]of Object.entries(n.abstracts))(!o||o.startsWith("_"))&&B("abstracts",`invalid public name '${o}'`),t[o]=Xh(i,`abstracts.${o}`,!1,e);let r={};for(let[o,i]of Object.entries(n.elements))(!o||o.startsWith("_"))&&B("elements",`invalid public name '${o}'`),r[o]=Xh(i,`elements.${o}`,!0,e);return{grammar:structuredClone(n.grammar),abstracts:t,elements:r}}function np(n,e,t,r){let o=e.attributes;if(!o)return;let i={...r};t!=null&&(i.node_value=t);let a=new Set(o.parameters.filter(u=>u.role==="attribute").map(u=>u.name)),s=new Set(["node_label","node_position","nodeId","target_id","datapath","iterate","store","_tag","_meta","ns"]);if(!o.accepts_var_keyword)for(let u of Object.keys(r))!a.has(u)&&!s.has(u)&&B(n,`unknown attribute '${u}'`);let l=e._meta?.component?o.parameters.find(u=>u.role!=="framework"&&["positional_only","positional_or_keyword"].includes(u.kind))?.name:null;for(let u of o.parameters){if(u.name===l||u.role==="framework"||u.kind.startsWith("var_"))continue;let c=Object.hasOwn(i,u.name);!c&&!u.has_default&&B(n,`missing required ${u.role} '${u.name}'`),c&&u.annotation!==null&&(!u.annotation.test||!u.annotation.test(i[u.name]))&&B(n,`invalid value for ${u.role} '${u.name}'`)}}var no=class n{#e=new Map;#t=new Map;register(e,t,r){let o=new Map([[String,"str"],[Number,"float"],["string","str"],["integer","int"],["number","float"]]),i=o.has(t)?{kind:"type",module:"builtins",name:o.get(t)}:t;return this.#r(e,{kind:"annotated",base:i,metadata:[r]})}#r(e,t){(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/.test(e)||e in this||["to_dict","from_dict"].includes(e)||Yy.has(e))&&B("custom_types",`invalid, reserved or duplicate name '${e}'`),jt(t,["kind","base","metadata"],["kind","base","metadata"],`custom_types.${e}`),(t.kind!=="annotated"||!Array.isArray(t.metadata)||t.metadata.length!==1||!["regex","range"].includes(t.metadata[0]?.kind))&&B(`custom_types.${e}`,"requires an annotated base with one Regex or Range validator");let r=t.metadata[0].kind==="regex"?["str"]:["int","float"];(t.base?.kind!=="type"||t.base.module!=="builtins"||!r.includes(t.base.name))&&B(`custom_types.${e}`,"portable Regex requires str; portable Range requires int or float"),Jr(t,`custom_types.${e}`);let o=structuredClone(t),i=Zr(o,`custom_types.${e}`),a=Object.freeze({kind:"custom",name:e});return Object.defineProperty(this,e,{value:a,enumerable:!0}),this.#e.set(e,o),this.#t.set(e,{...a,inputConstraint:!0,test:i.test}),a}resolve(e,t="custom_types"){return this.#t.has(e)||B(t,`unknown custom type '${e}'`),{...this.#t.get(e)}}validate(e,t){return this.resolve(e).test(t)||B(`custom_types.${e}`,"invalid input value"),!0}toJSON(){return structuredClone(Object.fromEntries(this.#e))}static fromJSON(e){Kr(e)||B("custom_types","must be an object");let t=new n;for(let[r,o]of Object.entries(e))t.#r(r,o);return t}},Yy=new Set("False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield".split(" "));function op(n,e,t,r){let o=e?.attributes;if(o)for(let i of o.parameters){if(!i.annotation?.inputConstraint||i.role==="framework"||["var_keyword","var_positional"].includes(i.kind))continue;let a=i.role==="value"?t:r[i.name];a!==void 0&&(i.annotation.test(a)||B(n,`invalid input for '${i.name}' (custom type)`))}}function ip(n,e,t=[]){if(e===null)return structuredClone(n);if(t.length===2&&t[0]==="custom_types"&&n!==void 0){if(!Wu(n,e))throw new TypeError(`conflicting custom type '${t[1]}'`);return structuredClone(n)}if(t.length===2&&["abstracts","elements"].includes(t[0]))return structuredClone(e);if(Kt(n)&&Kt(e)){let r=structuredClone(n);for(let[o,i]of Object.entries(e))i!==null&&Object.defineProperty(r,o,{value:ip(r[o],i,[...t,o]),enumerable:!0,writable:!0,configurable:!0});return r}return structuredClone(e)}function Wu(n,e){return Object.is(n,e)?!0:Array.isArray(n)&&Array.isArray(e)?n.length===e.length&&n.every((t,r)=>Wu(t,e[r])):Kt(n)&&Kt(e)?Object.keys(n).length===Object.keys(e).length&&Object.keys(n).every(t=>Object.hasOwn(e,t)&&Wu(n[t],e[t])):!1}function Kt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype}function Yu(n){if(!(n===null||typeof n=="string"||typeof n=="boolean")&&!(typeof n=="number"&&Number.isFinite(n))){if(Array.isArray(n)){n.forEach(Yu);return}if(Kt(n)){Object.values(n).forEach(Yu);return}throw new TypeError("collection must contain only finite JSON values")}}var Jt=class n{#e;constructor(e){Yu(e);let t=["document_format","grammar","abstracts","elements"];if(!Kt(e)||Object.keys(e).some(o=>![...t,"custom_types"].includes(o))||t.some(o=>!Object.hasOwn(e,o)))throw new TypeError("collection requires document_format, grammar, abstracts and elements");let r=e.document_format;if(!Kt(r)||Object.keys(r).length!==2||r.name!=="builder_grammar"||!["1.1","1.2"].includes(r.version))throw new TypeError("expected builder_grammar version 1.1 or 1.2");for(let o of["grammar","abstracts","elements"])if(!Kt(e[o]))throw new TypeError(`${o} must be an object`);if(Object.hasOwn(e,"custom_types")&&(r.version!=="1.2"||!Kt(e.custom_types)))throw new TypeError("custom_types requires an object catalog and version 1.2");this.#e=structuredClone(e)}update(e){let t=new n(e),r=ip(this.#e,t.#e);return(this.#e.document_format.version==="1.2"||t.#e.document_format.version==="1.2")&&(r.document_format.version="1.2"),this.#e=r,this}toDocument(){return structuredClone(this.#e)}};var Qr=class{static renderType="string";static mode=null;constructor(e){this._builder=e,this.renders=new Map([[e,this]])}get builder(){return this._builder}get renderType(){return this.constructor.renderType}get mode(){return this.constructor.mode}addRender(e,t){this.renders.set(e,t)}getRender(e){let t=this.renders.get(e);if(t!==void 0)return t;let r=e.getRenderer();return this.renders.set(e,r),r}render(e,t={}){let r=e.builder,[o,i]=r.runtimeValues(e);if(e._getMeta("data_element"))return null;if(e._getMeta("component"))return this._renderComponent(e,i,t);let a=this.getRender(r),s;return[s,i]=a._handleMeta(e,i),e._getMeta("subbuilder")||(i=a.adaptAttrs(i)),e.value instanceof I&&(o=this.renderChildren(e.value,t)),a.renderedItem(e,o,i,{tag:s,...t})}renderChildren(e,t={}){let r=[];for(let o of e.getNodes()){let i=this.render(o,t);i!==null&&(Array.isArray(i)?r.push(...i):r.push(i))}return r}_renderComponent(e,t,r){let[o,i,a,s]=this._expansionInputs(e,t);if(!Object.hasOwn(e.getAttr(),"iterate"))return this._expandBlock(e,o,a,s,r);if(i==null)return[];if(!(i instanceof E))throw new TypeError(`component '${e.nodeTag}': iterate must resolve to a Bag, got ${i?.constructor?.name||typeof i}`);return i.getNodes().map(l=>this._expandBlock(e,o,a,{node_label:l.label},r))}_expansionInputs(e,t){let r=e.builder,o=r.componentMethod(e.nodeTag),i=o&&r[o];if(typeof i!="function")throw new Error(`component '${e.nodeTag}' has no implementation`);let a=t.iterate;delete t.iterate,delete t.store;let s=e.getAttr("iterate")||e.getAttr("store");s!=null?(e.pointerType(s)&&(s=s.slice(1)),s.startsWith(".")&&(s=e._composeRelativeDatapath(s,s))):s=null;for(let l of Object.keys(t)){let u=e.getAttr(l);e.pointerType(u)==="^"&&(t[l]=`^${e.absDatapath(u)}`)}return[i,a,s,t]}_expandBlock(e,t,r,o,i){let a=e.builder._expansionRoot(r);t.call(e.builder,fi(a),o);let s=a.getNodes();if(s.length!==1)throw new Error(`component '${e.nodeTag}' must build a tree, not a forest: ${s.length} root nodes`);let l={...i,depthOffset:this._nodeDepth(e,i.depthOffset||0)};return this.render(s[0],l)}preprocess(e){return e}renderedItem(e,t,r,o){throw new Error(`${this.constructor.name} does not implement renderedItem`)}_handleMeta(e,t){let[r,o]=e._getMeta("render_tag,render_attributes"),i=di(e.nodeTag,{renderTag:r,ns:e.getAttr("ns"),dialectName:e.builder?.constructor._name});if(!i)throw new Error(`node ${e.label} has no tag to render (no render_tag, no node_tag)`);return o&&(t={...t,...o}),[i,t]}adaptAttrs(e){return e}adapt(e){let t=`${this.builder.constructor._name}_`;return e.startsWith(t)?e.slice(t.length):e}finalize(e,t=null,r={}){let o=this._composeStringFragments(e);if(t==null)return o;if(typeof t=="string")throw new TypeError("string render targets require filesystem support, which is unavailable in the portable renderer; pass a callable or writable target instead");if(typeof t.full=="function"&&typeof t.write!="function")return t.full(o),null;if(typeof t.write=="function")return t.write(o),null;if(typeof t=="function")return t(o),null;throw new TypeError("render target must be writable (.write), callable, or expose .full")}_composeStringFragments(e){if(!Array.isArray(e))return e;if(e.some(t=>typeof t!="string"))throw new TypeError("String composition requires string fragments; object renderers must define their own composition");return e.join("")}_escapeText(e){return String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}_escapeAttr(e){return this._escapeText(e).replaceAll('"',""")}_nodeDepth(e,t=0){let o=((e.fullpath||"").match(/\./g)||[]).length;return Math.max(o-1,0)+t}};var en=class extends Qr{static mode="xml";renderedItem(e,t,r,{tag:o,pretty:i=!1,depthOffset:a=0}={}){let s=this._formatAttrs(r),l=i?" ".repeat(this._nodeDepth(e,a)):"",u=i?`
|
|
39
|
+
`:"";if(Array.isArray(t)){let c=this._composeStringFragments(t);return`${l}<${o}${s}>${u}${c}${l}</${o}>${u}`}return t==null?`${l}<${o}${s}></${o}>${u}`:`${l}<${o}${s}>${this._escapeText(t)}</${o}>${u}`}finalize(e,t=null,{docHeader:r=null}={}){let o=this._composeStringFragments(e);return r===!0?o=`<?xml version='1.0' encoding='UTF-8'?>${o}`:typeof r=="string"&&(o=r+o),super.finalize(o,t)}_formatAttrs(e){return Object.entries(e||{}).map(([t,r])=>` ${t.startsWith("xmlns_")?`xmlns:${t.slice(6)}`:t}="${this._escapeAttr(r)}"`).join("")}};var ap={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"base",version:null,title:null,description:null},abstracts:{},elements:{dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};function sp(n){let e=[];for(;n&&n!==Function.prototype;)e.push(n),n=Object.getPrototypeOf(n);return e.reverse()}function Zy(n){let e=Object.create(null),t=(r,o)=>{let i=r.toLowerCase(),a=e[i];if(a!==void 0&&a!==o)throw new Error(`container '${r}' is already tied to implementation method '${a}' (cannot rebind to '${o}')`);e[i]=o};for(let r of sp(n))if(Object.hasOwn(r,"containers"))for(let o of r.containers||[])t(o,o);return e}function hi(n){let e=Object.create(null);for(let t of Object.keys(n)){let r=t.toLowerCase();if(Object.hasOwn(e,r))throw new Error(`element declaration '${t}' has a case-insensitive collision with '${e[r]}'`);e[r]=t}return e}var pi="_root_",mi="_root_",lp=new Set(["destination","func","value","_on_start"]),Ze=class n{static _sourceClass=I;static registerBuilder(e){if(typeof e!="function"||!(e.prototype instanceof n))throw new TypeError("registerBuilder requires a BuilderBase subclass");let t=e._name;if(typeof t!="string"||!t)throw new TypeError("registered builders require a non-empty static _name");let r=n._registry.get(t);if(r&&r!==e)throw new Error(`Builder name '${t}' is already registered to ${r.name}; cannot register ${e.name}`);return n._registry.set(t,e),e}static getBuilderClass(e){let t=n._registry.get(e);if(!t)throw new Error(`No builder registered with name '${e}'`);return t}constructor(e=null){this.name=e||this.constructor._name,this._dataroot=new E,this._dataroot.setBackref(),this._dataroot.setItem(mi,new E),this.data=this._dataroot.getItem(mi),this._defaultTargets=new Map,this.materialized=Object.create(null),this._collection=null,this._schemaOverride=null,this._tagNamesOverride=null,this._componentMap=null,this._targetSerial=0,this._subbuilders=new Map,this._sourceHandles=new WeakMap;let t=this.constructor._sourceClass;this._sourceroot=new t(null,this),this._sourceroot.setBackref(),this._sourceroot.setItem(pi,new t(null,this)),this.source=this._sourceroot.getItem(pi)}wrapSource(e){if(e=ae(e),!(e instanceof I)&&!(e instanceof Xe))throw new TypeError("wrapSource requires a SourceBag or SourceBagNode");let t=this._sourceHandles.get(e);return t||(t=Yh(this,e),this._sourceHandles.set(e,t)),t}get root(){return this.wrapSource(this.source)}getSubbuilder(e){if(typeof e!="string"||!e||e.includes(":"))throw new Error(`unsupported subbuilder reference '${e}'`);let t=this._subbuilders.get(e);if(!t){let r=n.getBuilderClass(e);t=new r,this._subbuilders.set(e,t)}return t._dataroot=this._dataroot,t.data=this.data,t}_resolveSubbuilderReference(e,t,r){if(typeof e!="string"||!e)throw new Error(`'${r}': subbuilder declaration must be a non-empty string`);if(e.includes(":"))throw new Error(`'${r}': runtime subbuilder reference '${e}' is unsupported`);return this.getSubbuilder(e)}static defineGrammar(e){let t=this._classCollection,r=t?new Jt(t.toDocument()).update(e):new Jt(e),o=Gu(r.toDocument()),i=Hu(o),a=hi(i.elements);this._classCollection=r,this._classSchema=i.elements,this._abstracts=i.abstracts,this._tagNames=a}static{this.defineGrammar(ap)}get _containers(){return Zy(this.constructor)}containerMethod(e){return this._containers[e.toLowerCase()]||null}componentMethod(e){return this._componentMap?.[e.toLowerCase()]||null}get schema(){return this._schemaOverride||this.constructor._classSchema||{}}get schemaTagNames(){return this._schemaOverride?this._tagNamesOverride??=hi(this.schema):this.constructor._tagNames??=hi(this.schema)}schemaTag(e){let t=e.toLowerCase(),r=this.schemaTagNames[t];if(r)return r;let o=`${this.constructor._name}_`;return t.startsWith(o)&&this.schemaTagNames[t.slice(o.length)]||null}loadGrammar(e,{replace:t=!1}={}){let r=this._collection||this.constructor._classCollection,o=t?new Jt(e):new Jt(r.toDocument()).update(e),i=Gu(o.toDocument()),a=Hu(i),s=hi(a.elements);return this._collection=o,this._schemaOverride=a.elements,this._tagNamesOverride=s,this}validateCustomTypes(e){let t=e.parentBag?.parentNode?.builder||e.parentBag?._builder,r=t&&t!==this&&t.schema[e.nodeTag]?._meta?.subbuilder?t:this;op(e.nodeTag,r.schema[e.nodeTag],e.value,e.getAttr()||{})}validateNodeValues(e,t,r={}){let o=this.schemaTag(e);if(!o)throw new Error(`unknown element '${e}'`);return np(o,this.schema[o],t,r),!0}validateNode(e,{value:t,attrs:r,childTags:o}={}){if(!e||typeof e.nodeTag!="string")throw new TypeError("validateNode requires a source node");let i=t!==void 0?t:e.value instanceof I?null:e.value;this.validateNodeValues(e.nodeTag,i,r||e.getAttr?.()||{});let a=this.schema[this.schemaTag(e.nodeTag)],s=o||(e.value instanceof I?e.value.getNodes().map(l=>l.nodeTag):null);return s&&this._validateChildren(e.nodeTag,a,s,!1),!0}validateChildren(e,t,{includeMinimum:r=!1}={}){let o=this.schemaTag(e);if(!o)throw new Error(`unknown element '${e}'`);if(!Array.isArray(t)||t.some(i=>typeof i!="string"))throw new TypeError("childTags must be an array of strings");return this._validateChildren(o,this.schema[o],t,r)}validateParent(e,t=null){let r=this.schemaTag(e);if(!r)throw new Error(`unknown element '${e}'`);let o=this.schema[r];if(!this._countsForGrammar(o))return!0;let i=o._parentSpec;if(i==null||i.has("*"))return!0;if(t===null)throw new Error(`'${r}' requires a declared parent`);let a=this.schemaTag(t);if(!a)throw new Error(`unknown parent element '${t}'`);return this._validateParent(r,o,a),!0}bagCall(e,t,r,o){return this.setChild(e,t,r,o)}commandOnNode(e,t,r,o){if(e=ae(e),e.value instanceof I)return this.setChild(e.value,t,r,o);let i=e.value,a=new e.parentBag.constructor(null,e.builder||this),s=this.setChild(a,t,r,o,e);return this.promoteNodeValue(e,i,a),s}promoteNodeValue(e,t,r){e.setValue(r)}setChild(e,t,r,o,i=null){let a={...o},s=this.schema[t];if(!s)throw new Error(`unknown element '${t}'`);this.validateNodeValues(t,r,a);let l=s._meta?.subbuilder,c=(l==null?null:this._resolveSubbuilderReference(l,a,t))||this,d=r instanceof I?r._builderBindingPlan(c):null,f=i?.rootBuilder||e.root._builder||this;if(a.nodeId!=null&&f.source.getNodeByAttr("nodeId",a.nodeId))throw new Error(`Duplicate nodeId '${a.nodeId}'`);r instanceof I&&this._validateChildren(t,s,r.getNodes().map(y=>y.nodeTag),!1);let h=i||e.parentNode,p=h?.nodeTag?this.schema[h.nodeTag]:null;if(p&&!h._getMeta("subbuilder")&&this._countsForGrammar(s))this._validateParent(t,s,h.nodeTag),this._validateChildren(h.nodeTag,p,[...e.getNodes().map(y=>y.nodeTag),t],!1);else if(!p&&!h?._getMeta("subbuilder")&&s._parentSpec!=null&&this._countsForGrammar(s))throw new Error(`'${t}' requires a declared parent`);s._meta&&!("_meta"in a)&&(a._meta=s._meta),s.ns&&!("ns"in a)&&(a.ns=s.ns);let m=a.node_position;delete a.node_position;let b=a.node_label;delete a.node_label;let w;if(p?.collection_key){if(b!=null)throw new Error(`'${t}': node_label is not allowed in a collection`);w=this._collectionLabel(p.collection_key,t,a)}else{let y=p?._subSpec?.get(t);if(y&&y.max===1){if(b!=null)throw new Error(`'${t}': node_label is not allowed on a singleton`);w=t}else w=b||s.node_label||this._autoLabel(e,t)}if(e.node(w)!=null)throw new Error(`duplicate node label '${w}'`);return e._setBuilderItem(c,d,w,r,a,m||">",!1,!0,null,!1,!0,null,t)}_countsForGrammar(e){let t=e?._meta||{};return!(t.data_element||t.subbuilder||t.component)}_validateParent(e,t,r){let o=t._parentSpec;if(!(o==null||o.has("*")||!this._countsForGrammar(t))&&!o.has(r))throw new Error(`'${e}' not allowed as child of '${r}'`)}_validateChildren(e,t,r,o){let i=t._subSpec;if(i==null||i.has("*")||t._meta?.subbuilder)return[];let a=new Map;for(let s of r){let l=this.schema[s];if(l&&!this._countsForGrammar(l))continue;let u=i.get(s);if(!u)throw new Error(`'${s}' not allowed as child of '${e}'`);let c=(a.get(s)||0)+1;if(a.set(s,c),c>u.max)throw new Error(`too many '${s}' in '${e}'`)}return o?[...i].filter(([s,l])=>(a.get(s)||0)<l.min).map(([s])=>s):[]}_collectionLabel(e,t,r){let o=i=>{if(r[i]===null||r[i]===void 0)throw new Error(`'${t}': collection key needs attribute '${i}'`);return String(r[i])};return e.includes("${")?e.replace(/\$\{([^}]+)\}/g,(i,a)=>o(a)):o(e)}validateSource(){let e=[],t=(r,o="")=>{for(let i of r.getNodes()){let a=o?`${o}.${i.label}`:i.label,s=i.builder;s.validateCustomTypes(i);let l=s.schema[i.nodeTag];if(l&&!i._getMeta("data_element,subbuilder,component").some(Boolean)){let u=i.value instanceof I?i.value.getNodes().map(d=>d.nodeTag):[],c=s._validateChildren(i.nodeTag,l,u,!0);c.length&&e.push([a,c])}i.value instanceof I&&t(i.value,a)}};return t(this.source),e}_autoLabel(e,t){let r=0;for(;e.node(`${t}_${r}`)!==null&&e.node(`${t}_${r}`)!==void 0;)r+=1;return`${t}_${r}`}nodeById(e){let t=this.source.getNodeByAttr("nodeId",e);if(t==null)throw new Error(`nodeId not found: ${e}`);return t.builder.wrapSource(t)}runtimeValues(e){e.builder.validateCustomTypes(e);let t=new Map,r={},o=e.runtimeToEvaluate(),i=new Set(o.keys()),a=new Map([...Object.entries(e.getAttr()),...e.fixedAttrItems()]);for(let[c,d]of[...o])if(!(typeof c!="string"||!ne(d)))for(let f of Ft(e,d))o.has(f)||o.set(f,a.get(f));let s=e._getMeta("data_element");for(let[c,d]of o){if(d instanceof fe){t.set(c,d.resolve());continue}let f=typeof c=="string"?ne(d)?.pointer??d:d;if(!e.pointerType(f)){t.set(c,typeof c=="string"&&typeof d=="string"&&d.startsWith("==")?null:d);continue}let h=e.absDatapath(f);if(t.set(c,this.data.getItem(h)),!s&&!h.includes("?")&&c===ro){let p=this.data.getNode(h);p&&Object.assign(r,p.getAttr("_wdg"))}}let l=Mh(o,t,(c,d,f,h)=>this.evaluatePointerExpression(e,c,d,f,h)),u=l.get(ro);l.delete(ro);for(let c of l.keys())i.has(c)||l.delete(c);return[u,{...Object.fromEntries(l),...r}]}evaluatePointerExpression(e,t,r,o,i){return null}targetId(e){if(e._targetId)return e._targetId;let t=e.rootBuilder;return e.parentBag.root!==t.source.root?null:(t._targetSerial+=1,e._targetId=`n${t._targetSerial}`,e._targetId)}get dataLogic(){if(!this._dataLogic){let e=this._buildDataLogic();this._dataLogic=Array.isArray(e)?e:[e]}return this._dataLogic}_buildDataLogic(){return this}_resolveLogicFunc(e){if(typeof e=="function")return e;if(typeof e!="string")throw new Error("data-element func must be a name or a function");for(let t of this.dataLogic){let o=(typeof t=="function"?t:t.constructor)[e];if(typeof o=="function")return o}throw new Error(`data-element func '${e}' not found on any data_logic source`)}_bindings(e){let[,t]=this.runtimeValues(e),r={};for(let[o,i]of Object.entries(t))lp.has(o)||(r[o]=i);return r}computeLogic(e){for(let t of e)this._computeNode(t)}_computeNode(e){let t=e.getAttr()||{};if(e.nodeTag==="dataSetter"){let r={};for(let[o,i]of Object.entries(t))o!=="destination"&&o!=="value"&&!o.startsWith("_")&&(r[o]=i);e.setRelativeData(t.destination,t.value,{attributes:Object.keys(r).length?r:null})}else if(e.nodeTag==="dataFormula"){let r=this._resolveLogicFunc(t.func);e.setRelativeData(t.destination,r(this._bindings(e)))}else e.nodeTag==="dataController"&&this._resolveLogicFunc(t.func)(e,this._bindings(e))}_dataElementNodes(){let e=[],t=r=>{for(let o of r.getNodes())o._getMeta("data_element")&&e.push(o),o.value instanceof I&&t(o.value)};return t(this.source),e}setup(e){}main(e){throw new Error(`${this.constructor.name}.main() not implemented: a bare builder is grammar, not a renderable page`)}_resolveComponents(){let e={};for(let s of sp(this.constructor))if(Object.hasOwn(s,"components"))for(let l of s.components||[])e[l]=l;if(!Object.keys(e).length)return;let t={...this.schema},r={};for(let[s,l]of Object.entries(e))t[s]={sub_tags:"",_meta:{component:!0}},r[s.toLowerCase()]=l;let o=hi(t),i=this._collection||this.constructor._classCollection,a=i.toDocument();a.abstracts={},a.elements=Object.fromEntries(Object.keys(e).map(s=>[s,t[s]])),this._collection=new Jt(i.toDocument()).update(a),this._schemaOverride=t,this._componentMap=r,this._tagNamesOverride=o}_expansionRoot(e=null){let t=this.constructor._sourceClass,r=new t(null,this);return r.setBackref(),r.setItem(pi,new t(null,this),e?{datapath:e}:null),r.getItem(pi)}create(){this.setup(this.data),this._resolveComponents(),this.main(this.root),this.computeLogic(this._dataElementNodes())}get renderer_xml(){return new en(this)}getRenderer(e=null){e??=this.constructor._defaultRenderMode;let t=this[`renderer_${e}`];if(!t)throw new Error(`${this.constructor.name} does not expose renderer_${e}`);return t}materialize(e=null,t={}){e??=this.constructor._defaultRenderMode;let r=this.getRenderer(e),o=r.renderChildren(r.preprocess(this.source),t);return this.materialized[e]=o,o}setRenderTarget(e,t=null){t??=this.constructor._defaultRenderMode,this._defaultTargets.set(t,e)}render({mode:e=null,target:t=null,...r}={}){e??=this.constructor._defaultRenderMode;let o=this.getRenderer(e);if(t===!1&&o.renderType!=="string")throw new TypeError("target=false is not valid for an object renderer");let i=t===!1?null:t||this._defaultTargets.get(o.mode)||null,a={...i?.renderOpts,...r};return o.finalize(this.materialize(e,a),i,a)}};Ze._registry=new Map;var Ky=new Set(["short","medium","long","full"]),Jy=/('(?:[^']|'')*'|[a-zA-Z]+|[^a-zA-Z']+)/g;function Qy(n,e){if(!(n instanceof Date))throw new TypeError("Temporal formats require a typed Date value");if(!Number.isFinite(n.getTime()))throw new RangeError("Invalid date");let t=e||L(n).split("::").at(-1);if(!["D","H","DH","DHZ"].includes(t))throw new RangeError(`Unsupported temporal dtype: ${t}`);return t}function ev(n,e,t,r){let o=e.match(Jy)||[];if(o.join("")!==e)throw new RangeError("Unclosed format literal");let i=(c,d=2)=>String(c).padStart(d,"0"),a=c=>new Intl.DateTimeFormat(t,{timeZone:"UTC",...c}).format(n),u={...r==="H"?{}:{y:()=>String(n.getUTCFullYear()),yy:()=>i(n.getUTCFullYear()%100),yyyy:()=>i(n.getUTCFullYear(),4),M:()=>String(n.getUTCMonth()+1),MM:()=>i(n.getUTCMonth()+1),MMM:()=>a({month:"short"}),MMMM:()=>a({month:"long"}),d:()=>String(n.getUTCDate()),dd:()=>i(n.getUTCDate()),EEE:()=>a({weekday:"short"}),EEEE:()=>a({weekday:"long"})},...r==="D"?{}:{H:()=>String(n.getUTCHours()),HH:()=>i(n.getUTCHours()),h:()=>String(n.getUTCHours()%12||12),hh:()=>i(n.getUTCHours()%12||12),m:()=>String(n.getUTCMinutes()),mm:()=>i(n.getUTCMinutes()),s:()=>String(n.getUTCSeconds()),ss:()=>i(n.getUTCSeconds()),a:()=>new Intl.DateTimeFormat(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(n).find(c=>c.type==="dayPeriod").value}};return o.map(c=>{if(c.startsWith("'"))return c==="''"?"'":c.slice(1,-1).replaceAll("''","'");if(!/^[a-zA-Z]/.test(c))return c;if(!u[c])throw new RangeError(`Unsupported date format token: ${c}`);return u[c]()}).join("")}function up(n,{format:e,mask:t,locale:r,dtype:o,places:i}={}){let a=n==null?"":String(n);if(n!=null&&n!==""&&(e!=null&&e!==""||i!=null))if(typeof n=="number"||le(n))a=rv(n,{format:e,locale:r,places:i});else{let s=Qy(n,o);if(Ky.has(e)){let l={timeZone:"UTC"};s!=="H"&&(l.dateStyle=e),s!=="D"&&(l.timeStyle=e),a=new Intl.DateTimeFormat(r||void 0,l).format(n)}else a=ev(n,String(e),r||void 0,s)}return t==null?a:String(t).replaceAll("%s",()=>a)}function tv({format:n="decimal",places:e}={}){let t={maximumFractionDigits:20};if(!n||n==="decimal")t.style="decimal";else if(n==="percent")t.style="percent";else if(n==="scientific")t.notation="scientific";else{let r=/^(0|#,##0)(?:\.(0*)(#*))?$/.exec(n);if(!r||n.includes(".")&&!r[2]&&!r[3])throw new RangeError(`Unsupported number format: ${n}`);t.useGrouping=r[1].includes(","),t.minimumFractionDigits=(r[2]||"").length,t.maximumFractionDigits=(r[2]||"").length+(r[3]||"").length}if(e!=null&&e!==""){let r=Number(e);if(!Number.isInteger(r)||r<0||r>20)throw new RangeError("places must be an integer from 0 to 20");t.minimumFractionDigits=r,t.maximumFractionDigits=r}return t}function rv(n,e={}){if(typeof n!="number"&&!le(n))throw new TypeError("Number formatting requires a Number or Decimal");if(!Number.isFinite(Number(n)))throw new RangeError("Number must be finite");let t=new Intl.NumberFormat(e.locale||void 0,tv(e));if(le(n)&&new Intl.NumberFormat("en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal values without precision loss");return t.format(le(n)?n.toString():n)}var nv=new Set(["style","script"]),ov=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"]),cp=new Set(["width","height","top","left","right","bottom","padding","margin","border","position","display","overflow","float","clear","resize","z_index","min_width","min_height","max_width","max_height","color","background","font","text","line_height","white_space","vertical_align","flex","gap","row_gap","column_gap","grid","align_content","justify_content","align_items","justify_items","visibility","opacity","cursor"]),gi=new Set(["rounded","gradient","shadow","transform","transition","zoom","filter"]),dp=n=>n===!0?"true":n===!1?"false":String(n),ns=n=>typeof n=="number"&&Number.isFinite(n)?`${n}px`:String(n);function iv(n){if(cp.has(n))return!0;for(let e of cp)if(n.startsWith(`${e}_`))return!0;return!1}function av(n){let e=new Map;if(!n)return e;let t=[],r=0,o=null,i=!1,a=!1,s=0,l=String(n);for(let u=0;u<l.length;u+=1){let c=l[u],d=l[u+1];if(a){c==="*"&&d==="/"&&(a=!1,u+=1);continue}if(i){i=!1;continue}if(c==="\\"){i=!0;continue}if(o){c===o&&(o=null);continue}c==='"'||c==="'"?o=c:c==="/"&&d==="*"?(a=!0,u+=1):"([{".includes(c)?s+=1:")]}".includes(c)&&s>0?s-=1:c===";"&&s===0&&(t.push(l.slice(r,u)),r=u+1)}t.push(l.slice(r));for(let u of t){let c=u.trim();if(!c)continue;let d=c.indexOf(":");if(d<0)throw new TypeError(`malformed style declaration '${c}'`);e.set(c.slice(0,d).trim(),c.slice(d+1).trim())}return e}var tn=class extends Qr{static mode="html";renderedItem(e,t,r,{tag:o,xml:i=!0,pretty:a=!1,depthOffset:s=0,includeDatapath:l=!1}={}){e.parentNode?._getMeta("subbuilder")==="html"&&(r={xmlns:"http://www.w3.org/1999/xhtml",...r});let{format:c,mask:d,locale:f,places:h,dtype:p,...m}=r;!Array.isArray(t)&&(c!=null||d!=null||h!=null)&&(t=up(t,{format:c,mask:d,places:h,dtype:p,locale:this._displayLocale(e,f)}));let b=this._formatAttrs(m);if(l){if(!Object.hasOwn(r,"id")){let x=this.builder.targetId(e);x!==null&&(b+=` id="${this._htmlAttrValue(x)}"`)}for(let[x,D]of Object.entries(e.getAttr()))e.pointerType(D)&&(b+=` data-${this.adapt(x)}-pointer="${this._htmlAttrValue(e.absDatapath(D))}"`)}let w=a?" ".repeat(this._nodeDepth(e,s)):"",_=a?`
|
|
40
|
+
`:"";if(e._getMeta("void"))return`${w}<${o}${b}${i?"/":""}>${_}`;if(Array.isArray(t)){let x=this._composeStringFragments(t);return`${w}<${o}${b}>${_}${x}${w}</${o}>${_}`}if(t==null)return`${w}<${o}${b}></${o}>${_}`;let y=typeof t=="string"&&t.endsWith("::HTML")?t.slice(0,-6):nv.has(o)?String(t):this._escapeText(t);return`${w}<${o}${b}>${y}</${o}>${_}`}_displayLocale(e,t){if(t)return t;for(let r=e.parentNode;r;r=r.parentNode){let o=r.getAttr("locale");if(o==null)continue;let i=r.pointerType(o)?r.data.getItem(r.absDatapath(o)):o;if(i)return i}}adaptAttrs(e){let t={},r={};for(let[i,a]of Object.entries(e||{}))if(i.startsWith(`${this.builder.constructor._name}_`))t[this.adapt(i)]=a;else if(i==="dtype")t.dtype=a;else{if(this.builder.constructor.retainedAttrPrefixes.some(s=>i.startsWith(s)))continue;this._isStyleContribution(i)?r[i]=a:t[i]=a}let o=this._adaptStyle(r);return o&&(t.style=o),t}_isStyleContribution(e){if(e==="style"||e.startsWith("style_")||gi.has(e))return!0;let t=e.includes("_")?e.slice(0,e.indexOf("_")):null;return t!==null&&gi.has(t)||iv(e)}_adaptStyle(e){let t=av(e.style),r=new Map,o=new Map;for(let[i,a]of Object.entries(e))if(i!=="style")if(i.startsWith("style_"))t.set(i.slice(6).replaceAll("_","-"),dp(a));else if(gi.has(i))r.set(i,a);else{let s=i.indexOf("_"),l=s<0?i:i.slice(0,s);s>=0&&gi.has(l)?(o.has(l)||o.set(l,{}),o.get(l)[i.slice(s+1)]=a):t.set(i.replaceAll("_","-"),dp(a))}for(let i of gi)(r.has(i)||o.has(i))&&this[`_macro_${i}`](r.get(i),o.get(i)||{},t);return[...t].map(([i,a])=>`${i}: ${a}`).join("; ")}_formatAttrs(e){let t=[];for(let[r,o]of Object.entries(e||{}))ov.has(r)?o&&t.push(` ${r}`):t.push(` ${r}="${this._htmlAttrValue(o)}"`);return t.join("")}_htmlAttrValue(e){return(e===!0?"true":e===!1?"false":String(e)).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}_macro_rounded(e,t,r){let o=e===void 0?{}:{top_left:e,top_right:e,bottom_left:e,bottom_right:e};for(let[i,a]of Object.entries(t))if(i==="top"||i==="bottom")o[`${i}_left`]=a,o[`${i}_right`]=a;else if(i==="left"||i==="right")o[`top_${i}`]=a,o[`bottom_${i}`]=a;else if(["top_left","top_right","bottom_left","bottom_right"].includes(i))o[i]=a;else throw new TypeError(`rounded: unknown sub-kwarg '${i}'`);for(let[i,a]of Object.entries(o))r.set(`border-${i.replaceAll("_","-")}-radius`,ns(a))}_macro_transform(e,t,r){let o=e===void 0?[]:[String(e)];for(let[i,a]of Object.entries(t))i==="rotate"?o.push(`rotate(${a}deg)`):i==="scale"||i==="translate"?o.push(`${i}(${a})`):i==="translate_x"?o.push(`translateX(${ns(a)})`):i==="translate_y"?o.push(`translateY(${ns(a)})`):i==="skew_x"?o.push(`skewX(${a}deg)`):i==="skew_y"?o.push(`skewY(${a}deg)`):o.push(`${i.replaceAll("_","-")}(${a})`);o.length&&r.set("transform",o.join(" "))}_macro_filter(e,t,r){let o=e===void 0?[]:[String(e)];for(let[i,a]of Object.entries(t))i==="rotate"?o.push(`hue-rotate(${a}deg)`):i==="blur"?o.push(`blur(${ns(a)})`):i==="drop_shadow"?o.push(`drop-shadow(${a})`):o.push(`${i.replaceAll("_","-")}(${a})`);o.length&&r.set("filter",o.join(" "))}_macro_transition(e,t,r){e!==void 0&&r.set("transition",String(e));for(let[o,i]of Object.entries(t))r.set(`transition-${o.replaceAll("_","-")}`,String(i))}_macro_zoom(e,t,r){e!==void 0&&r.set("zoom",String(e))}_macro_shadow(e,t,r){e!==void 0&&r.set("box-shadow",String(e));for(let[o,i]of Object.entries(t))r.set(`box-shadow-${o.replaceAll("_","-")}`,String(i))}_macro_gradient(e,t,r){e!==void 0&&r.set("background-image",String(e))}};var sv=new Set(["alignment_baseline","baseline_shift","clip_path","clip_rule","color_interpolation","color_interpolation_filters","dominant_baseline","fill_opacity","fill_rule","flood_color","flood_opacity","font_family","font_size","font_size_adjust","font_stretch","font_style","font_variant","font_weight","glyph_orientation_horizontal","glyph_orientation_vertical","image_rendering","letter_spacing","lighting_color","marker_end","marker_mid","marker_start","overline_position","overline_thickness","paint_order","pointer_events","shape_rendering","stop_color","stop_opacity","strikethrough_position","strikethrough_thickness","stroke_dasharray","stroke_dashoffset","stroke_linecap","stroke_linejoin","stroke_miterlimit","stroke_opacity","stroke_width","text_anchor","text_decoration","text_rendering","underline_position","underline_thickness","unicode_bidi","word_spacing","writing_mode"]);function os(n){return Object.fromEntries(Object.entries(n||{}).map(([e,t])=>[sv.has(e)?e.replaceAll("_","-"):e,t]))}var rn=class extends en{static mode="svg";adaptAttrs(e){return os(e)}};var fp={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"html",version:null,title:null,description:null},abstracts:{},elements:{svg:{doc:"Switch to the SVG dialect from this node down (BLD.2).\n\n A sub-builder element: ``_meta['subbuilder']`` switches the active\n dialect to SVG from this node down. No ``render_tag``: ``<svg>`` is\n emitted verbatim (HTML5 has a native ``<svg>`` tag).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{subbuilder:"svg"}},a:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},abbr:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},address:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},area:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},article:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},aside:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},audio:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},b:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},base:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},bdi:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},bdo:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},blockquote:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},body:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},br:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},button:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},canvas:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},caption:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},cite:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},code:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},col:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},colgroup:{doc:null,sub_tags:"col,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},data:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},datalist:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,option,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dd:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},del_:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},details:{doc:null,sub_tags:"summary[0:1],a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dfn:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dialog:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},div:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dl:{doc:null,sub_tags:"dd,div,dt,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dt:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},em:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},embed:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},fieldset:{doc:null,sub_tags:"legend[0:1],a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},figcaption:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},figure:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figcaption[0:1],figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},footer:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},form:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h1:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h2:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h3:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h4:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h5:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},h6:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},head:{doc:null,sub_tags:"base[0:1],link,meta,noscript,script,style,template,title[0:1]",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},header:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},hgroup:{doc:null,sub_tags:"h1,h2,h3,h4,h5,h6,p,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},hr:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},html:{doc:null,sub_tags:"head[0:1],body[0:1]",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},i:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},iframe:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},img:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},input:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},ins:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},kbd:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},label:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},legend:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,h1,h2,h3,h4,h5,h6,hgroup,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},li:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},link:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},main:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},map:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},mark:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},menu:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},meta:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},meter:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},nav:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},noscript:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},object:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ol:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},optgroup:{doc:null,sub_tags:"div,legend,noscript,option,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},option:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,div,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},output:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},p:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},picture:{doc:null,sub_tags:"img[0:1],script,source,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},pre:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},progress:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},q:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rp:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rt:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ruby:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},s:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},samp:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},script:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},search:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},section:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},select:{doc:null,sub_tags:"button,div,hr,noscript,optgroup,option,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},slot:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},small:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},source:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},span:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},strong:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},style:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},sub:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},summary:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,h1,h2,h3,h4,h5,h6,hgroup,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},sup:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},table:{doc:null,sub_tags:"caption[0:1],colgroup,script,tbody,template,tfoot[0:1],thead[0:1],tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tbody:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},td:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},template:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,del_,details,dfn,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,legend,li,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,optgroup,option,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,tr,track,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},textarea:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tfoot:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},th:{doc:null,sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},thead:{doc:null,sub_tags:"script,template,tr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},time:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},title:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tr:{doc:null,sub_tags:"script,td,template,th",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},track:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},u:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ul:{doc:null,sub_tags:"li,script,template",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},var:{doc:null,sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},video:{doc:null,sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},wbr:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{void:!0}},selectedcontent:{doc:"Mirror of the selected option for Customizable Select (HTML 2024).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};var qt=class extends Ze{static _name="html";static _defaultRenderMode="html";static retainedAttrPrefixes=["validate_","dtype"];static{this.defineGrammar(fp)}get renderer_html(){return new tn(this)}};Ze.registerBuilder(qt);var hp={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"svg",version:null,title:null,description:null},abstracts:{graphics:{doc:"SVG graphics content: any graphical element.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:null},containerElement:{doc:"SVG container content: elements that can hold children.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:null}},elements:{html:{doc:"Switch to the HTML dialect from this node down (BLD.2).\n\n A sub-builder element: ``_meta['subbuilder']`` switches the active\n dialect to HTML from this node down. The source tag ``html`` is\n rendered as ``_meta['render_tag']`` (``<foreignObject>``) carrying\n ``_meta['render_attributes']`` (the SVG namespace). The immediate\n HTML child declares XHTML so both sides of the XML boundary retain\n their native namespace.\n ",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{subbuilder:"html",render_tag:"foreignObject",render_attributes:{xmlns:"http://www.w3.org/2000/svg"}}},svg:{doc:"Root SVG container or nested SVG viewport.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},g:{doc:"Group container for applying transforms and styles.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},defs:{doc:"Container for referenced elements (gradients, patterns, etc.).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},symbol:{doc:"Reusable graphical template, rendered only when referenced by <use>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},use:{doc:"Reference and render a <symbol> or other element.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},rect:{doc:"Rectangle.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},circle:{doc:"Circle.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},ellipse:{doc:"Ellipse.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},line:{doc:"Line segment between two points.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},polyline:{doc:"Open shape of connected line segments.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},polygon:{doc:"Closed shape of connected line segments.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},path:{doc:"Arbitrary shape defined by path commands (d attribute).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},image:{doc:"Embedded raster image.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},text:{doc:"Text block. Contains text content and optional <tspan>/<textPath>.",sub_tags:"tspan,textPath",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},tspan:{doc:"Inline text span within <text>.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},textPath:{doc:"Text rendered along a path shape.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},linearGradient:{doc:"Linear gradient definition. Place inside <defs>.",sub_tags:"stop",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},radialGradient:{doc:"Radial gradient definition. Place inside <defs>.",sub_tags:"stop",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},stop:{doc:"Gradient stop (color and offset).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},pattern:{doc:"Tile pattern definition. Place inside <defs>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},clipPath:{doc:"Clipping path definition.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},mask:{doc:"Alpha mask definition.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},marker:{doc:"Marker symbol for line endpoints or vertices.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},filter:{doc:"Filter effect container. Place inside <defs>.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feGaussianBlur:{doc:"Gaussian blur filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feOffset:{doc:"Offset filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feBlend:{doc:"Blend filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feColorMatrix:{doc:"Color matrix filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feComposite:{doc:"Composite filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feFlood:{doc:"Flood fill filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMerge:{doc:"Merge filter primitive (container for feMergeNode).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMergeNode:{doc:"Single input for feMerge.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDropShadow:{doc:"Drop shadow filter primitive (SVG 2).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDiffuseLighting:{doc:"Diffuse lighting filter primitive.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feSpecularLighting:{doc:"Specular lighting filter primitive.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},fePointLight:{doc:"Point light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDistantLight:{doc:"Distant light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feSpotLight:{doc:"Spot light source for lighting filters.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feMorphology:{doc:"Morphology filter primitive (erode/dilate).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feTurbulence:{doc:"Turbulence noise filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feDisplacementMap:{doc:"Displacement map filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feConvolveMatrix:{doc:"Convolution matrix filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feImage:{doc:"Image filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},feTile:{doc:"Tile filter primitive.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animate:{doc:"Animate an attribute over time.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animateTransform:{doc:"Animate a transform attribute.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},animateMotion:{doc:"Animate motion along a path.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},set:{doc:"Set an attribute to a value for a duration.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},title:{doc:"Accessible title (tooltip in browsers).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},desc:{doc:"Accessible description.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},metadata:{doc:"Metadata container (RDF, Dublin Core, etc.).",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},a:{doc:"Hyperlink wrapper.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},foreignObject:{doc:"Container for non-SVG content (HTML, MathML).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},switch:{doc:"Conditional processing (renders first matching child).",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null},dataSetter:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:null,sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"collections.abc",name:"Callable"}]},has_default:!1},{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}}}};var Tr=class extends Ze{static _name="svg";static _defaultRenderMode="svg";static{this.defineGrammar(hp)}get renderer_svg(){return new rn(this)}};Ze.registerBuilder(Tr);function Tt(n,e=new Set){if(!n||typeof n!="object")return;let t=n.ownerDocument?.defaultView?.Node??n.defaultView?.Node;if(ae(n)instanceof Xe||t&&n instanceof t)throw new TypeError("Live Source/DOM references cannot cross a transport boundary");if(e.has(n))throw new TypeError("Transport data cannot contain circular references");e.add(n);let r=n instanceof E?n.getNodes().flatMap(o=>[o.staticValue,o.getAttr()]):Object.values(n);for(let o of r)Tt(o,e);e.delete(n)}var bi=class{constructor(e=null){this.entries=new Map,this.sourceRoot=e}validate(e,t=new Set){let r=new Map,o=i=>{for(let a of i.getNodes()){let s=a.getAttr("__ref");if(s){if(r.has(s))throw new Error("Duplicate Source reference");let l=this.entries.get(s);if(e!==this.sourceRoot&&l&&l.node!==a&&!t.has(l.node))throw new Error("Duplicate Source reference");r.set(s,a)}a.value instanceof I&&o(a.value)}};o(e)}register(e,t){let r=e.getAttr("__ref");if(r){if(this.entries.has(r))throw new Error(`Duplicate Source reference: ${r}`);this.entries.set(r,{node:e,dom:t})}}remove(e){for(let[t,r]of this.entries)r.node===e&&this.entries.delete(t)}resolveArguments(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r&&typeof r=="object"&&Object.hasOwn(r,"$gramlotRef")?this.resolve(r):r]))}resolve(e){if(!e||!["node","dom"].includes(e.kind))throw new TypeError("Expected a node or DOM reference");let t=this.entries.get(e.$gramlotRef);if(!t)throw new Error("Source reference is not mounted");return t[e.kind]}};function J(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),n=>n.toString(16).padStart(2,"0")).join("")}var Ke=class{constructor(e){this.gramlot=e}};var nn=class extends Error{name="RpcError";constructor({code:e,name:t,message:r,details:o}){super(r),this.code=e,this.remoteName=t,o!==void 0&&(this.details=o)}},wi=class extends Ke{constructor(e,{rpcUrl:t,closeUrl:r,document:o,transport:i}){super(e),this.transport=i===!1?null:i??e.serverAdapter.createTransport({rpcUrl:t,closeUrl:r,document:o,channel:e._pageStore}),this.remoteRequests=new Map}get supportsCallSync(){return this.transport?.supportsCallSync===!0}callSync(e,t,r={}){if(!this.supportsCallSync)throw new Error(`rpc '${t}': the transport of this page has no synchronous call`);if(Tt(r),this.gramlot.abort.signal.aborted)throw this.gramlot.abort.signal.reason;let o=J(),i=j(this.transport.callSync(L({id:o,pageId:this.gramlot.pageId,contentType:e,name:t,params:r})));if(i.id!==o)throw new Error("rpc response id mismatch");if(i.error)throw new nn(i.error);return i.value}async call(e,t,r={},o={}){return(await this.callEnvelope(e,t,r,o)).value}async callEnvelope(e,t,r={},{signal:o=null}={}){if(!this.transport?.call)throw new Error(`rpc '${t}' is unavailable without a server transport`);Tt(r);let i=J(),a=L({id:i,pageId:this.gramlot.pageId,contentType:e,name:t,params:r}),s=o?[this.gramlot.abort.signal,o]:[this.gramlot.abort.signal],l=s.find(f=>f.aborted);if(l)throw l.reason;let u=new AbortController,c=f=>u.abort(f.target.reason);for(let f of s)f.addEventListener("abort",c,{once:!0});let d=new Promise((f,h)=>{u.signal.addEventListener("abort",()=>{this.remoteRequests.delete(i),h(u.signal.reason)},{once:!0})});this.remoteRequests.set(i,u);try{let f=j(await Promise.race([this.transport.call(a,u.signal),d]));if(f.id!==i)throw new Error("rpc response id mismatch");if(f.error)throw new nn(f.error);return f}finally{this.remoteRequests.delete(i);for(let f of s)f.removeEventListener("abort",c)}}};var is=class{constructor(e,t,r){this.gramlot=e,this.window=r.defaultView,this.frames=e._frames,this.binders=new Map,this.calls=new Map,this.routes=new Map,this.error=null,this.closed=!1,this.ready=!1,this.socket=null;let o=new URL(t,r.baseURI);o.protocol=o.protocol==="https:"?"wss:":"ws:",this.endpoint=o.href,this.origin=this.window.location.origin,this.parent=this.frames.parent?.window??null,this.frames.registerChannel("server",{changed:i=>this.peerChanged(i),disconnected:i=>{i.parent?this.fail(new Error("PageStore parent disconnected")):this.forget(i.window)},receive:(i,a)=>{try{this.receive(i,a)}catch(s){this.fail(s)}}},{endpoint:this.endpoint,ready:!1}),!this.parent&&(o.searchParams.set("pageId",e.pageId),this.socket=new this.window.WebSocket(o.href),this.socket.addEventListener("open",()=>this.connected()),this.socket.addEventListener("message",i=>{try{this.deliver(i.data)}catch(a){this.fail(a)}}),this.socket.addEventListener("error",()=>this.fail(new Error("PageStore WebSocket failed"))),this.socket.addEventListener("close",i=>{this.closed||this.fail(new Error("PageStore disconnected ("+i.code+")"))}))}peerChanged(e){if(this.closed||!e.parent)return;let t=e.channels.server;e.origin!==this.origin||t?.endpoint!==this.endpoint?this.fail(new Error("Parent does not provide the same PageStore endpoint")):t.ready?this.connected():this.ready&&this.fail(new Error("PageStore parent channel closed"))}connected(){if(!(this.closed||this.ready)){this.ready=!0,this.parent&&this.upstream({op:"attach",pageId:this.gramlot.pageId});for(let e of this.binders.values())this.subscribe(e);for(let e of this.calls.values())this.sendCall(e);this.frames.setChannelState("server",{endpoint:this.endpoint,ready:!0})}}receive(e,t){if(this.closed||e.origin!==this.origin||e.channels.server?.endpoint!==this.endpoint)return;if(e.parent){this.deliver(L(t));return}if(!this.ready)return;let r=t?.pageId;if(!(typeof r!="string"||!r||r===this.gramlot.pageId)){if(t.op==="attach"){if(this.routes.has(r))return;this.routes.set(r,e.window)}else if(this.routes.get(r)!==e.window)return;t.op==="detach"&&this.routes.delete(r),this.upstream(t)}}forget(e){for(let[t,r]of this.routes)r===e&&(this.routes.delete(t),this.ready&&!this.closed&&this.upstream({op:"detach",pageId:t}))}upstream(e){if(this.closed||!this.ready)throw new Error("PageStore is not connected");this.parent?this.frames.send(this.parent,"server",e):this.socket.send(L(e))}deliver(e){if(this.closed)return;let t=j(e);if(t.pageId===this.gramlot.pageId){if(t.op==="closed"){this.fail(new Error("PageStore page closed on the server"));return}if(!Object.hasOwn(t,"op")&&Object.hasOwn(t,"id")){this.calls.get(t.id)?.finish(null,e);return}if(t.op==="publish"){try{this.gramlot._subscriptions.publish(t.topic,t.payload,t.metadata)}catch(o){this.window.console.error("PageStore publication subscriber failed",o)}return}let r=this.binders.get(t.binderId);r&&r.apply(t)}else{let r=this.routes.get(t.pageId);r&&this.frames.send(r,"server",t)}}register(e){if(this.closed)throw new Error("PageStore connection is closed");this.binders.set(e.id,e),this.ready&&this.subscribe(e)}subscribe(e){this.send({op:"subscribe",binderId:e.id,path:e.serverPath})}unregister(e){this.binders.delete(e.id)&&!this.closed&&this.ready&&this.send({op:"unsubscribe",binderId:e.id})}send(e){this.upstream({...e,pageId:this.gramlot.pageId})}preparePublish(e,t){if(this.closed||!this.ready)throw new Error("PageStore is not connected");Tt(t);let r={op:"publish",id:J(),pageId:this.gramlot.pageId,topic:e.topic,payload:t};e.pageId!==void 0&&(r.targetPageId=e.pageId);let o=L(r);return async()=>{let i=j(await this.call(o));if(i.error)throw new nn(i.error);return i.value}}call(e,t){if(this.closed)return Promise.reject(this.error??new Error("PageStore connection is closed"));if(t?.aborted)return Promise.reject(t.reason);let r=j(e);return r.pageId!==this.gramlot.pageId||typeof r.id!="string"||!r.id||Object.hasOwn(r,"op")&&r.op!=="publish"||this.calls.has(r.id)?Promise.reject(new Error("Invalid or duplicate RPC identity")):new Promise((o,i)=>{let a={message:r,sent:!1,finish:(l,u)=>{this.calls.delete(r.id)&&(t?.removeEventListener("abort",s),u===void 0?i(l):o(u))}},s=()=>{if(a.finish(t.reason),a.sent&&this.ready&&!this.closed)try{this.send({op:"cancel",id:r.id})}catch(l){this.fail(l)}};this.calls.set(r.id,a),t?.addEventListener("abort",s,{once:!0}),this.ready&&this.sendCall(a)})}sendCall(e){try{this.upstream(e.message),e.sent=!0}catch(t){e.finish(t),this.fail(t)}}fail(e){this.error=e,this.close(),this.window.console.error("PageStore channel failed",e)}close(){if(!this.closed){if(this.closed=!0,this.parent&&this.ready&&this.frames.isConnected(this.parent))for(let e of[...this.routes.keys(),this.gramlot.pageId])this.frames.send(this.parent,"server",{op:"detach",pageId:e});this.ready=!1;for(let e of this.calls.values())e.finish(this.error??new Error("PageStore connection is closed"));this.binders.clear(),this.routes.clear(),this.frames.unregisterChannel("server"),this.socket?.close()}}};var pp="gramlot:message",as=class{#e;#t;#r;#n=J();#o=new Map;#i=new Map;#a=!1;#s;#l;#u;#c;#d;constructor(e,t){this.#e=e,this.#r=t,this.#t=t.defaultView,this.#s=r=>this.#g(r),this.#l=r=>{if(r.target?.localName!=="iframe")return;let o=this.#v(r.target);o&&this.#w(o)},this.#u=r=>{r.persisted||this.#e.dispose({beacon:!0})},this.#c=()=>this.ready(),this.#t.addEventListener("message",this.#s),this.#t.addEventListener("pagehide",this.#u),this.#t.addEventListener("pageshow",this.#c),t.addEventListener("load",this.#l,!0)}#f(){this.#d===void 0&&(this.#d=this.#t.setInterval(()=>{if(this.parent?.window.closed){this.#p();return}for(let e of this.children)e.window.closed?this.#h(e.window):e.node&&!this.#v(this.#e.dom.getDomNode(e.node))&&this.#h(e.window,!0)},500))}get parent(){let e=this.#t.parent!==this.#t,t=e?this.#t.parent:this.#t.opener;return t?{window:t,parent:!0,kind:e?"iframe":"popup",origin:this.#E(this.#r.referrer||this.#r.baseURI)}:null}get children(){return[...this.#o.values()].filter(e=>!e.parent)}isConnected(e){return!this.#a&&this.#o.has(e)}connect(){this.parent&&(this.#f(),this.#w(this.parent));for(let e of this.#r.getElementsByTagName("iframe")){let t=this.#v(e);t&&this.#w(t)}}ready(){if(!this.#a){this.connect();for(let e of this.#o.values())this.#_(e)}}registerChannel(e,t,r){if(this.#a||e==="publish"||this.#i.has(e))throw new Error("Invalid family channel");this.#i.set(e,{handler:t,state:r});for(let o of this.#o.values())t.changed(o)}setChannelState(e,t){this.#i.get(e).state=t;for(let r of this.#o.values())this.#_(r)}unregisterChannel(e){if(this.#i.delete(e),this.#e.state!=="disposed")for(let t of this.#o.values())this.#_(t)}send(e,t,r){let o=this.#o.get(e);if(this.#a||!o)throw new Error("Destination page is not connected");Tt(r),this.#y(o,{kind:"message",recipient:o.session,channel:t,wire:L(r)})}prepare(e,t){let r=[];if(e.parent){if(!this.parent)throw new Error("This page has no parent frame or opener");r.push(this.parent)}if(e.iframe!==void 0){let a=e.iframe,s=ae(a),l=typeof a=="string"?this.#r.getElementById(a):s instanceof Xe?this.#e.dom.getDomNode(s):null,u=this.#v(l);if(!u)throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");r.push(u)}if(e.pageId!==void 0){let a=this.children.find(s=>s.pageId===e.pageId);if(!a)throw new Error("pageId destination must be a registered direct Gramlot child");r.push(a)}let o=r.map(a=>{let s=this.#o.get(a.window);if(!s?.ready||s.origin!==a.origin)throw new Error("Destination page is not ready");return{...a,session:s.session}});Tt(t);let i=L({topic:e.topic,payload:t});return()=>{if(!this.#a)for(let a of o){let s=this.#k(a.window);if(!s||s.origin!==a.origin||this.#o.get(a.window)?.session!==a.session)throw new Error("Destination page disconnected before publication");this.#y(a,{kind:"message",recipient:a.session,channel:"publish",wire:i})}}}dispose(){if(this.#a)return;for(let t of this.children)this.#h(t.window,!0);let e=this.parent;e&&this.#o.has(e.window)&&(this.#y(this.#o.get(e.window),{kind:"close"}),this.#h(e.window)),this.#a=!0,this.#i.clear(),this.#t.removeEventListener("message",this.#s),this.#t.removeEventListener("pagehide",this.#u),this.#t.removeEventListener("pageshow",this.#c),this.#t.clearInterval(this.#d),this.#r.removeEventListener("load",this.#l,!0)}#p(){this.#e.dispose({beacon:!0}),this.#t.parent===this.#t&&this.#t.opener&&this.#t.close()}#h(e,t=!1){let r=this.#o.get(e);if(r){t&&this.#y(r,{kind:"close"}),this.#o.delete(e),r.release?.();for(let{handler:o}of this.#i.values())o.disconnected(r);t&&r.kind==="popup"&&!r.parent&&e.close()}}#m(e,t){let r=this.#o.get(e.window),o=r?.session!==t.session;o&&this.#h(e.window);let i=o?{...e,session:t.session}:r;Object.assign(i,{ready:t.ready===!0,pageId:t.pageId,channels:t.channels}),this.#o.set(e.window,i),this.#f(),o&&e.node&&(i.release=this.#e.src.binding.bindingFor(e.node).track(()=>{this.#h(e.window,!0)}));for(let{handler:a}of this.#i.values())a.changed(i);return o}#g(e){if(this.#a||e.data?.type!==pp)return;let t=this.#k(e.source);if(!t||e.origin!==t.origin)return;let r=e.data;if(typeof r.session!="string"||!r.session)return;if(r.kind==="hello"||r.kind==="ready"){if(r.kind==="ready"&&r.recipient!==this.#n||!r.channels||typeof r.channels!="object"||Array.isArray(r.channels))return;let i=this.#m(t,r);(r.kind==="hello"||i)&&this.#_(this.#o.get(t.window));return}let o=this.#o.get(t.window);if(!(!o||o.session!==r.session||r.recipient!==this.#n)){if(r.kind==="close")t.parent?this.#p():this.#h(t.window);else if(r.kind==="message"&&typeof r.wire=="string"){let i=j(r.wire);if(r.channel==="publish"){if(this.#e.state!=="started"||!o.ready||typeof i.topic!="string"||!i.topic)return;this.#e.publish(i.topic,i.payload)}else this.#i.get(r.channel)?.handler.receive(o,i)}}}#b(){return{pageId:this.#e.pageId,ready:this.#e.state==="started",channels:Object.fromEntries([...this.#i].map(([e,t])=>[e,t.state]))}}#w(e){this.#y(e,{kind:"hello",...this.#b()})}#_(e){this.#y(e,{kind:"ready",recipient:e.session,...this.#b()})}#y(e,t){e.window.postMessage({type:pp,session:this.#n,recipient:e.session,...t},e.origin==="null"?"*":e.origin)}#v(e){if(e?.localName!=="iframe"||!e.isConnected||!e.contentWindow)return null;let t=this.#e.dom.getBaseSourceNode(e);if(!t||!this.#e.src.binding.bindingFor(t)||this.#e.dom.getDomNode(t)!==e)return null;let r=e.getAttribute("sandbox"),i=r!==null&&!r.split(/\s+/).includes("allow-same-origin")?"null":this.#E(e.hasAttribute("srcdoc")?this.#r.baseURI:e.getAttribute("src")||this.#r.baseURI);return{window:e.contentWindow,origin:i,node:t,parent:!1,kind:"iframe"}}#E(e){let t=new URL(e,this.#r.baseURI);return t.protocol==="file:"?"null":t.origin}#k(e){let t=this.parent;if(t?.window===e)return t;for(let r of this.#r.getElementsByTagName("iframe")){let o=this.#v(r);if(o?.window===e)return o}try{if(e&&e!==this.#t&&e.opener===this.#t&&e.location.origin===this.#t.location.origin)return{window:e,origin:this.#E(this.#r.baseURI),parent:!1,kind:"popup"}}catch{}return null}};var on=class n{#e;constructor(e,t=0){this.pattern=e,this.flags=t,this.#e=no.fromJSON({nameSyntax:{kind:"annotated",base:{kind:"type",module:"builtins",name:"str"},metadata:[this.toJSON()]}}).resolve("nameSyntax").test,Object.freeze(this)}static fromJSON(e){if((e!==null&&typeof e=="object"?Object.keys(e).sort():[]).join()!=="flags,kind,pattern"||e.kind!=="regex")throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(e)}`);return new n(e.pattern,e.flags)}toJSON(){return{kind:"regex",pattern:this.pattern,flags:this.flags}}matches(e){return this.#e(e)}},_i=new on(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);function oo(n,e=","){if(typeof e!="string"||!e)throw new TypeError("separator must be a nonempty string");if(n==="")return[];let t=new Set;return n.split(e).map(r=>{let o=r.indexOf(":"),i=o<0?r:r.slice(0,o),a=o<0?r:r.slice(o+1);if(!i||t.has(i))throw new Error("Invalid or duplicate choice code");return t.add(i),{id:i,caption:a}})}function ss(n,e,t=""){return n.find(r=>r.id===e)?.caption??t??""}var ls=class{constructor(e,t){this.layout=e;let r=e.box.ownerDocument;this.button=r.createElement("button"),this.button.type="button",this.button.className="label-menu-trigger",this.button.setAttribute("aria-haspopup","menu"),this.button.setAttribute("aria-expanded","false"),this.menu=r.createElement("gramlot-menu"),this.menu.projectAttributes({}),e.labelBox.append(this.button,this.menu),this.button.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),this.menu.opened?this.menu.close():this.menu.open(this.button)}),this.button.addEventListener("keydown",o=>{["ArrowDown","ArrowUp"].includes(o.key)&&(o.preventDefault(),o.stopPropagation(),this.menu.open(this.button,o.key==="ArrowUp"))}),this.choose=t}project({lbl:e,lbl_value:t,lbl_values:r,disabled:o,readonly:i},a){let s=oo(r);if(this.values!==r){this.menu.close(!1);for(let u of this.menu.items)u.releaseCommand();this.menu.replaceChildren(...s.map(({id:u,caption:c})=>{let d=this.menu.ownerDocument.createElement("gramlot-menu-line");return d.projectAttributes({code:u,caption:c},a),d.activateCommand=f=>{d.prepareCommand(f)&&this.choose(u)},d.control.addEventListener("click",f=>d.activateCommand(f)),d})),this.values=r}let l=ss(s,t,e);this.button.textContent=l,this.button.disabled=!!(o||i||!s.length),this.button.disabled&&this.menu.close(!1);for(let u of this.menu.items)u.projectAttributes({...u.parameters,checked:u.parameters.code===t},a);this.layout.fieldLabel.textContent=l,this.layout.fieldLabel.hidden=!0,this.layout.labelBox.hidden=!1}dispose(){this.menu.close(!1);for(let e of this.menu.items)e.releaseCommand();this.menu.remove(),this.button.remove(),this.layout.fieldLabel.hidden=!1}};var Xu=["TL","TC","TR","L","R","BL","BC","BR"],mp=`.gramlot-labelbox>.label-box>.label-menu-trigger{font:inherit;color:inherit;background:transparent;border:0;padding:0;min-width:0;min-height:var(--gramlot-touch-target,0px);height:auto;display:inline-flex;align-items:center;gap:.4em;cursor:pointer;text-align:inherit;line-height:inherit}
|
|
41
41
|
.gramlot-labelbox>.label-box>.label-menu-trigger::after{content:'';width:.35em;height:.35em;border-right:1.5px solid currentColor;border-bottom:1.5px solid currentColor;transform:translateY(-.1em) rotate(45deg);flex:none}
|
|
42
42
|
.gramlot-labelbox>.label-box>.label-menu-trigger:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:3px;border-radius:2px}
|
|
43
43
|
.gramlot-labelbox>.label-box>.label-menu-trigger:disabled{opacity:.5;cursor:default}
|
|
@@ -89,7 +89,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
89
89
|
.gramlot-labelbox>.tray-resize[hidden]{display:none}
|
|
90
90
|
.gramlot-labelbox>.tray-resize svg{width:16px;height:16px;pointer-events:none}
|
|
91
91
|
.gramlot-labelbox>.tray-resize:hover,.gramlot-labelbox>.tray-resize:focus-visible{opacity:1}
|
|
92
|
-
.gramlot-labelbox>.tray-resize:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}`;function
|
|
92
|
+
.gramlot-labelbox>.tray-resize:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}`;function gp(n,e){let t=n.createElement("div"),r=n.createElement("div"),o=n.createElement("label");r.append(o),t.append(r,e);let i={box:t,labelBox:r,fieldLabel:o,controlBox:e,previous:{box:{},label:{},labelBox:{},controlBox:{}}};return t.labelbox=i,i}function bp(n,e,t){let{lbl:r,lbl_value:o,lbl_values:i,lbl_variant:a,lbl_position:s=a==="card"?"TC":"TL",...l}=e;if(!Xu.includes(s))throw new TypeError(`Invalid lbl_position: ${s}`);let u={box:{},label:{},labelBox:{},controlBox:{}},c=[["box_l_","labelBox"],["box_c_","controlBox"],["lbl_","label"],["box_","box"]];for(let[f,h]of Object.entries(l)){let p=c.find(([m])=>f.startsWith(m));p&&(u[p[1]][f.slice(p[0].length)]=h,delete l[f])}let d={box:n.box,label:n.fieldLabel,labelBox:n.labelBox,controlBox:n.controlBox};for(let[f,h]of Object.entries(d)){let p=t(u[f]),m=n.previous[f];for(let b of new Set([...Object.keys(m),...Object.keys(p)]))p[b]==null?h.removeAttribute(b):h.setAttribute(b,String(p[b]));n.previous[f]=p}return e.lbl_width==null?n.box.style.removeProperty("--gramlot-label-width"):n.box.style.setProperty("--gramlot-label-width",e.lbl_width),n.box.classList.add("labelbox","gramlot-labelbox"),n.labelBox.classList.add("label-box"),n.controlBox.classList.add("control-box"),n.box.dataset.position=s,a==null?delete n.box.dataset.variant:n.box.dataset.variant=a,n.fieldLabel.textContent=r??"",n.labelBox.hidden=r==null||r==="",i!=null?(n.menu??=new ls(n,f=>n.choose(f)),n.menu.project(e,t)):n.menu&&(n.menu.dispose(),n.menu=null),n.box.dispatchEvent(new n.box.ownerDocument.defaultView.Event("gramlot-label-layout",{bubbles:!0})),l}function Je(n){return n?.labelbox?n.labelbox.controlBox.firstElementChild:n}function an(n){let e=n?.parentElement?.parentElement;return e?.labelbox&&Je(e)===n?e:n}var wp=`
|
|
93
93
|
.choice-field{position:relative;min-width:0}
|
|
94
94
|
.choice-field>input{box-sizing:border-box;width:100%;padding-inline-end:calc(var(--gramlot-choice-toggle-width,1.6em) + .4em)}
|
|
95
95
|
.choice-field>.choice-toggle{position:absolute;inset-inline-end:1px;inset-block:1px;
|
|
@@ -101,7 +101,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
101
101
|
.choice-toggle:disabled{opacity:.5;cursor:default}
|
|
102
102
|
.choice-toggle:focus-visible{outline:1px solid var(--gramlot-focus-ring,Highlight);outline-offset:-3px}
|
|
103
103
|
.choice-field>input::-webkit-calendar-picker-indicator{opacity:0}
|
|
104
|
-
`;var
|
|
104
|
+
`;var cv=/^[a-z][.0-9_a-z\-\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]*$/u,dv=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]);function Qt(n){let e=n.code;if(typeof e!="string"||cv.exec(e)?.[0]!==e||!e.includes("-")||dv.has(e))throw new TypeError("webcomponent: code must be a literal custom-element name");return e}function Zu(n){for(let e of Object.values(n))e&&typeof e=="object"&&Zu(e);return Object.freeze(n)}function _p(n){if(!n.annotation&&typeof n.dtype!="string"&&!Array.isArray(n.dtype))throw new TypeError("Component parameter requires dtype");let e=n.annotation?[structuredClone(n.annotation)]:(Array.isArray(n.dtype)?n.dtype:[n.dtype]).map(t=>({kind:"dtype",dtype:t}));return n.nullable&&e.push({kind:"dtype",dtype:"NN"}),n.binding&&n.dtype!=="T"&&e.push({kind:"annotated",base:{kind:"dtype",dtype:"T"},metadata:[{kind:"regex",pattern:"^[\\^=].+",flags:0}]}),e.length===1?e[0]:{kind:"union",items:e}}function Dr({name:n,tag:e,base:t,mixins:r=[],parameters:o={},subTags:i="",presentationDefaults:a=[],dataScope:s=!1,command:l=!1,childParameters:u={},sourceContext:c=!1,bagStore:d=!1,bagStruct:f=!1,dragSource:h=!1,implementation:p}){if(Qt({code:e}),!/^[a-zA-Z][a-zA-Z0-9]*$/.test(n))throw new TypeError("Invalid component authoring name");let m={...t.parameters};for(let b of r)for(let[w,_]of Object.entries(b.parameters)){if(Object.hasOwn(m,w))throw new Error(`Duplicate mixin parameter: ${w}`);m[w]=_}Object.assign(m,o);for(let b of Object.values(m))_p(b);return Object.freeze({name:n,tag:e,base:t,subTags:i,presentationDefaults:Object.freeze([...a]),dataScope:s,command:l,bagStore:d,bagStruct:f,mixins:Object.freeze([...r]),labelbox:r.some(b=>b.labelbox===!0),parameters:Zu(structuredClone(m)),childParameters:Zu(structuredClone(u)),sourceContext:c,dragSource:h,implementation:p})}var Ar=class n{#e=new WeakMap;constructor({name:e,components:t,dependencies:r=[],css:o=[],assets:i={},registerCommands:a=()=>{}}){if(typeof e!="string"||!e)throw new TypeError("Collection name must be nonempty");if(!Array.isArray(r)||r.some(u=>!(u instanceof n)))throw new TypeError("Collection dependencies must be collection objects");if(!Array.isArray(o)||o.some(u=>!(u instanceof URL))||!i||typeof i!="object"||Array.isArray(i)||Object.values(i).some(u=>!(u instanceof URL)))throw new TypeError("Collection css/assets require URL objects");if(typeof a!="function")throw new TypeError("registerCommands must be a function");this.dependencies=Object.freeze([...r]),this.css=Object.freeze([...o]),this.assets=Object.freeze({...i}),this.registerCommands=a,this.name=e,this.components=Object.freeze([...t]);let s=new Set,l=new Set;for(let u of t){if(s.has(u.name.toLowerCase())||l.has(u.tag))throw new Error(`Duplicate component: ${u.name}`);s.add(u.name.toLowerCase()),l.add(u.tag)}}toDocument(){return{document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:this.name,version:null,title:this.name,description:null},abstracts:{},elements:Object.fromEntries(this.components.map(e=>[e.name,{doc:null,sub_tags:e.subTags,parent_tags:null,inherits_from:null,ns:null,node_label:null,collection_key:null,attributes:{parameters:[...Object.entries(e.parameters).map(([t,r])=>({name:t,kind:"keyword_only",role:"attribute",annotation:_p(r),has_default:!0,default:r.default??null})),{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},_meta:{render_tag:e.tag,gramlot_component:{parameters:structuredClone(e.parameters),presentationDefaults:[...e.presentationDefaults],dataScope:e.dataScope,command:e.command,...Object.keys(e.childParameters).length?{childParameters:structuredClone(e.childParameters)}:{},...e.sourceContext?{sourceContext:!0}:{},...e.labelbox?{labelbox:!0}:{},...e.dragSource?{dragSource:!0}:{},...e.bagStore?{bagStore:!0}:{},...e.bagStruct?{bagStruct:!0}:{}}}}]))}}register(e){if(this.#e.has(e))return;let t=[];for(let r of this.components){if(e.customElements.get(r.tag))throw new Error(`Custom element already registered: ${r.tag}`);let o=r.base(e.HTMLElement);for(let a of r.mixins)o=a(o);let i=r.implementation(o);Object.defineProperty(i,"gramlotComponent",{value:r}),t.push([r.tag,i])}for(let[r,o]of t)e.customElements.define(r,o);this.#e.set(e,t)}};function Ku(n){return new Ar(n)}function io(n,e){return n.parameters=Ju(n.constructor.gramlotComponent,e),Object.fromEntries(Object.entries(e).filter(([t])=>!Object.hasOwn(n.parameters,t)))}function Ju(n,e){return Object.fromEntries(Object.entries(n.parameters).map(([t,r])=>[t,Object.hasOwn(e,t)?e[t]:r.default]))}function us(n){return class extends n{constructor(){super();let e=this.attachShadow({mode:"open"}),t=this.ownerDocument.createElement("style");t.textContent=`:host{display:inline-block;font:inherit} *,*::before,*::after{box-sizing:border-box}
|
|
105
105
|
input,textarea{font:inherit;max-width:100%} .control-box{min-width:0;color:var(--gramlot-ink,CanvasText)}
|
|
106
106
|
input:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea{
|
|
107
107
|
appearance:none;box-sizing:border-box;width:100%;border:1px solid var(--gramlot-border-control,#7a8798);
|
|
@@ -117,7 +117,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
117
117
|
input[type=range],input[type=color],button{min-width:var(--gramlot-touch-target,0px);min-height:var(--gramlot-touch-target,0px)}
|
|
118
118
|
input[type=checkbox],input[type=radio]{min-width:calc(var(--gramlot-touch-target,0px) / 2);min-height:calc(var(--gramlot-touch-target,0px) / 2)}
|
|
119
119
|
.options{display:grid;gap:.3em .8em} .option{display:flex;align-items:center;gap:.35em;min-width:var(--gramlot-touch-target,0px);min-height:var(--gramlot-touch-target,0px)}
|
|
120
|
-
.caption:empty{display:none}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",e.append(t,this.controlBox)}projectAttributes(e){return io(this,e)}setPageContext(e){this.pageContext=e}connectedCallback(){}releaseControl(){}get liveWrites(){return this.control.localName==="textarea"||["text","password","range","color"].includes(this.control.type)}validateCandidate(e,t){return t(e),{ok:!0,value:e,isCurrent:()=>this.pageContext.isActive()}}finishValidation(){}validationValueCheck(){return this.constructor.validationValueCheck(this.pageContext)}static validationValueCheck(){let e=this.gramlotComponent.parameters.value.nullable;return(t,r)=>{if(t==null&&!e)throw new TypeError("This component requires a non-null value.");if(t!=null&&r!=null&&typeof t!=typeof r)throw new TypeError("Validation must preserve the component value type.")}}validationSelection(){return this.constructor.validationSelection(this.parameters,this.pageContext)}static validationSelection(){return()=>{throw new TypeError("validate_select requires a constrained choice editor.")}}validateSelection(e){return this.validationSelection()(e)}shouldProjectControlValue(){return!0}acceptControlValue(){let e=this.readControlValue();return this.validateCandidate(e,t=>{this.validationValueCheck()(t,e),this.sameControlValue(e,t)||this.writeControlValue(t)})}restoreFormDraft(e){this.control.value=e}restoreFormValue(e){this.writeControlValue(e)}sameControlValue(e,t){return Object.is(e,t)}focus(e){this.control.focus(e)}}}function _p(n){return class extends ls(n){constructor(){super(),this.control=this.createControl(),(this.control.localName==="textarea"||this.control.localName==="input"&&["text","password"].includes(this.control.type))&&(this.control.setAttribute("autocomplete","off"),this.control.setAttribute("autocorrect","off"),this.control.setAttribute("autocapitalize","off"),this.control.setAttribute("spellcheck","false")),this.control.id="control";let e=this.ownerDocument.createElement("label");e.className="option",this.optionCaption=this.ownerDocument.createElement("span"),this.optionCaption.className="caption",e.append(this.control,this.optionCaption),this.controlBox.append(e)}projectAttributes(e,t){let r=super.projectAttributes(e,t),{disabled:o,readonly:i}=this.parameters;this.control.disabled=!!o,this.control.readOnly=!!i;for(let[a,s]of Object.entries(this.constructor.gramlotComponent.parameters)){if(s.target==="control"){let l=this.parameters[a]??"";String(this.control[a])!==String(l)&&(this.control[a]=l)}s.target==="optionCaption"&&(this.optionCaption.textContent=this.parameters[a]??"")}return r}}}_p.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"},live:{dtype:"B",default:!1,binding:"read"}};function yp(n){return class extends ls(n){#e=new Map;#t;#r=null;constructor(){super(),this.control=this.ownerDocument.createElement("div"),this.control.className="options",this.control.id="control",this.control.setAttribute("role",this.multiple?"group":"radiogroup"),this.controlBox.append(this.control),this.control.addEventListener("keydown",e=>{if(!this.multiple||!["ArrowDown","ArrowUp","ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;let t=[...this.control.querySelectorAll("input:not(:disabled)")],r=t.indexOf(e.target);if(r<0)return;e.preventDefault();let o=e.key==="Home"?0:e.key==="End"?t.length-1:Math.max(0,Math.min(t.length-1,r+(["ArrowDown","ArrowRight"].includes(e.key)?1:-1)));t[o].focus()})}choiceOptions(){return oo(this.parameters.values??"")}projectAttributes(e,t){let r=super.projectAttributes(e,t),o=this.choiceOptions(),i=JSON.stringify(o);if(i!==this.#t){let s=o,l=new Set,u=null;for(let{id:c,caption:d}of s){let f=this.#e.get(c);if(!f){let p=this.ownerDocument.createElement("label");p.className="option";let m=this.ownerDocument.createElement("input");m.type=this.choiceType,m.name="choice",m.value=c;let b=this.ownerDocument.createElement("span");p.append(m,b),f={label:p,input:m,text:b},this.#e.set(c,f)}f.text.textContent=d;let h=u?u.nextSibling:this.control.firstChild;h!==f.label&&this.control.insertBefore(f.label,h),u=f.label,l.add(c)}for(let[c,d]of this.#e)l.has(c)||(d.label.remove(),this.#e.delete(c));this.#t=i}let a=this.parameters.cols;if(!Number.isInteger(a)||a<1)throw new TypeError("cols must be a positive integer");this.control.style.gridTemplateColumns=`repeat(${a}, minmax(0, 1fr))`,this.control.disabled=!!this.parameters.disabled,this.control.readOnly=!!this.parameters.readonly;for(let{input:s}of this.#e.values())s.disabled=this.control.disabled||this.control.readOnly;return r}readControlValue(){if(this.multiple){let t=(this.#r?this.#r.split(","):[]).filter(r=>!this.#e.has(r)||this.#e.get(r).input.checked);for(let[r,{input:o}]of this.#e)o.checked&&!t.includes(r)&&t.push(r);return t.join(",")||null}for(let[e,{input:t}]of this.#e)if(t.checked)return e;return null}writeControlValue(e){this.#r=e;let t=this.multiple?new Set(e?e.split(","):[]):null;for(let[r,{input:o}]of this.#e)o.checked=this.multiple?t.has(r):r===e}acceptControlValue(){let e=this.readControlValue();return this.validateCandidate(e,t=>this.writeControlValue(t))}focus(e){let t=[...this.#e.values()];(t.find(({input:r})=>r.checked&&!r.disabled)??t.find(({input:r})=>!r.disabled))?.input.focus(e)}}}yp.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"}};function ao(n,e,{align:t="start",matchWidth:r=!1,inset:o=0,placement:i="bottom",point:a=null}={}){let s=e.ownerDocument.defaultView,l=a?{left:a.x,right:a.x,top:a.y,bottom:a.y,width:0}:e.getBoundingClientRect(),u=Math.max(0,s.innerWidth-16);n.style.setProperty("--gramlot-popup-available-width",`${u}px`),r&&(n.style.width=`${Math.min(Math.max(0,l.width-2*o),u)}px`),n.style.removeProperty("--gramlot-popup-available-height");let c=n.getBoundingClientRect();if(i==="side"){let w=Math.max(0,s.innerWidth-8-l.right-3),_=Math.max(0,l.left-8-3),y=c.width>w&&_>w;n.style.setProperty("--gramlot-popup-available-width",`${y?_:w}px`),n.style.setProperty("--gramlot-popup-available-height",`${Math.max(0,s.innerHeight-16)}px`);let x=n.getBoundingClientRect(),S=y?l.left-x.width-3:l.right+3;n.style.left=`${Math.max(8,Math.min(S,s.innerWidth-x.width-8))}px`,n.style.top=`${Math.max(8,Math.min(l.top,s.innerHeight-x.height-8))}px`;return}let d=Math.max(0,s.innerHeight-8-l.bottom-3),f=Math.max(0,l.top-8-3),h=c.height>d&&f>d;n.style.setProperty("--gramlot-popup-available-height",`${h?f:d}px`);let p=n.getBoundingClientRect(),m=t==="end"?l.right-p.width-o:l.left+o,b=h?l.top-p.height-3:l.bottom+3;n.style.left=`${Math.max(8,Math.min(m,s.innerWidth-p.width-8))}px`,n.style.top=`${Math.max(8,Math.min(b,s.innerHeight-p.height-8))}px`}var so=new Map;function us(n,e,t){let r=JSON.stringify([n,e,t]),o=so.get(r);if(o)so.delete(r);else{let i=n?Intl.DateTimeFormat:Intl.NumberFormat;if(!i.supportedLocalesOf([e]).length)throw new RangeError(`Unsupported format locale: ${e}`);o=new i(e,t),so.size===64&&so.delete(so.keys().next().value)}return so.set(r,o),o}function vp(n){if(n!=null&&(typeof n!="string"||/[{}]/.test(n.replaceAll("{}",""))))throw new RangeError("This formatter mask supports only {} placeholders")}function ds(n,e){return vp(e),e==null?n:e.replaceAll("{}",()=>n)}function sv(n){if(n instanceof Date)return yr(n);if(de(n))return"N";if(typeof n=="number")return Number.isInteger(n)?"L":"R";throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects")}function lv(n,e,{pattern:t="short",locale:r,timeZone:o}){if(!["short","medium","long","full"].includes(t))throw new RangeError("Temporal formatting currently supports short, medium, long and full only");if(e==="DHZ"&&(typeof o!="string"||!o))throw new TypeError("DHZ formatting currently requires an explicit timeZone");let i={timeZone:e==="DHZ"?o:"UTC"};return e!=="H"&&(i.dateStyle=t),e!=="D"&&(i.timeStyle=t),us(!0,r,i).format(n)}function cs(n){let e=/^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(n);if(!e||e[1]==="("!=(e[4]===")")||n.endsWith("."))throw new RangeError(`Unsupported numeric pattern section: ${n}`);let t=e[3]??"";return{prefix:e[1]??"",suffix:e[4]??"",intl:{useGrouping:e[2].startsWith("#,##")?"always":!1,minimumIntegerDigits:e[2].replace("#,##","").length,minimumFractionDigits:t.replaceAll("#","").length,maximumFractionDigits:t.length}}}function uv(n){let e=n.split(";");if(e.length>3)throw new RangeError("Numeric patterns support at most three sections");let t=cs(e[0]);if(t.prefix||t.suffix)throw new RangeError("Positive-section affixes are not implemented");let r=e.length===3?e[1]:null;r!==null&&r!==""&&r!=="-"&&cs(r);let o=e.length>1?cs(e.at(-1)):null;return{positive:t,zero:r,negative:o}}function fs(n,e={},t={}){if(n===null)return"";if(typeof e=="string"&&(e={pattern:e}),!e||typeof e!="object"||Array.isArray(e))throw new TypeError("Format options must be a pattern string or an options object");for(let b of Object.keys(e))if(!["pattern","locale","mask","dtype","timeZone"].includes(b))throw new RangeError(`Unsupported format option: ${b}`);e={...e,locale:e.locale??t.locale,timeZone:e.timeZone??t.timeZone};let r=e.dtype===void 0?sv(n):e.dtype,o=["D","H","DHZ"].includes(r);if(!o&&!["L","R","N"].includes(r))throw new RangeError(`Unsupported format dtype: ${r}`);if(o){if(!(n instanceof Date)||!Number.isFinite(n.getTime()))throw new TypeError(`${r} requires a valid Date object`)}else if(!(typeof n=="number"&&Number.isFinite(n))&&!(de(n)&&!["NaN","Infinity","-Infinity"].includes(n.toString())))throw new TypeError(`${r} formatting requires finite JavaScript numbers or TYTX Decimal values`);if(r==="L"&&!Number.isInteger(n))throw new TypeError("L formatting requires an integer");let{pattern:i,locale:a,mask:s}=e;if(!o&&typeof i!="string")throw new TypeError("Numeric formatting currently requires an explicit pattern");if(typeof a!="string"||!a)throw new TypeError("Formatting currently requires an explicit locale");if(vp(s),o){let b=lv(n,r,e);return ds(b,s)}let{positive:l,zero:u,negative:c}=uv(i),d=us(!1,a,l.intl),f=de(n),h=f?n.eq(0):n===0,p=f?n.lt(0):n<0;if(f&&us(!1,"en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal without precision loss");let m;if(h&&u!==null){if(u==="")return"";if(u==="-")m="-";else{let b=cs(u);m=b.prefix+us(!1,a,b.intl).format(0)+b.suffix}}else{let b=p&&c?c:l,w=f?(p&&c?n.abs():n).toString():p&&c?-n:n===0?0:n;m=b.prefix+d.format(w)+b.suffix}return ds(m,s)}var Fe="http://www.w3.org/1999/xhtml",Dr="http://www.w3.org/2000/svg",cv=new Set(["default","default_value","live","group","visible","action","fire","ask","_ask","_ask_if","_ask_title","_ask_onCancel","if","else","_init","_onStart","_onBuilt","_delay","_timing","_userChanges","remote","_cachedRemote","_onRemote","_onCalling","onComplete","onClose","onEnd","onChecked","onDrag","onDrop","dropTargetCb","onDragEnd","dropTarget","dropTypes","dragTags","dropTags","effectAllowed","dropEffect","dragClass"]),dv=["default_","attr_","fire_","connect_on","subscribe_","selfsubscribe_","formsubscribe_","remote_"],fv={table:["width","border"],editor:["height"],embed:["width","height"],img:["width","height"],canvas:["width","height"]},hv=["format","mask","locale","timeZone","places","dtype"],pv=new Set(["href","src","data","action","formaction","xlink:href","xlink_href"]);function Sr(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>!(t&&typeof t=="object"&&Object.hasOwn(t,"$gramlotRef"))&&!cv.has(e)&&!dv.some(r=>e.startsWith(r))))}function uo(n,e,t=[]){for(let[r,o]of Object.entries(e)){let i=t.find(s=>r.startsWith(s))??"",a=r.slice(i.length);if(["style","class","_class"].includes(a)&&o!=null&&typeof o!="string")throw new TypeError(`${n.nodeTag} '${n.label}': '${r}' must be a string or null`)}}function co(n,e,t=[]){if(n.nodeTag==="script"){let r=[["",n.staticValue],...Le(n.getAttr()).filter(([o])=>["src","href","xlink:href","xlink_href","_text"].includes(o.slice((t.find(i=>o.startsWith(i))??"").length).toLowerCase()))];for(let[o,i]of r)if(n.pointerType(i)||mt(i))throw new Error(`script '${n.label}': '${o}' must be literal Source; script code and URLs cannot come from Data`)}if(e.onEnd!=null&&(n.nodeTag.toLowerCase()!=="transformpane"||!n._getMeta("gramlot_component")?.parameters?.onEnd))throw new Error("onEnd is only supported on transformPane");if(e.onChecked!=null&&!n._getMeta("gramlot_component")?.parameters?.onChecked)throw new Error("onChecked is only supported on a component that declares it");if(e.onComplete!=null&&!["uploader","imageUploader"].includes(n.nodeTag))throw new Error("onComplete is only supported on an uploader or imageUploader");if(e.onClose!=null&&!n.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose)throw new Error("onClose is only supported on a tab/stack panel");for(let[r,o]of Object.entries(fo(Sr(e)))){let i=t.find(s=>r.startsWith(s)),a=i?r.slice(i.length):r;if(/^on./i.test(a))throw new Error(`${n.nodeTag} '${n.label}': '${r}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${a} for an event, or rename the attribute`);if(pv.has(a.toLowerCase())&&mv(o))throw new Error(`${n.nodeTag} '${n.label}': '${r}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`)}}function mv(n){return typeof n=="string"&&/^javascript:/i.test(n.replace(/[\t\n\r]/g,"").replace(/^[\u0000-\u0020]+/,""))}function Ep(n,e,t=[]){if(n.nodeTag!=="iframe")return e;let r=s=>{let l=t.find(u=>s.startsWith(u))??"";return[l,s.slice(l.length).toLowerCase()]},o=Object.fromEntries(Le(n.getAttr())),i=[...Object.keys(o),...Object.keys(e)].find(s=>r(s)[1]==="srcdoc");if(i===void 0||Object.keys(o).some(s=>r(s)[1]==="sandbox")||n.pointerType(n.value)===null&&!(Object.hasOwn(o,i)&&(n.pointerType(o[i])!==null||mt(o[i]))))return e;let a=Object.fromEntries(Object.entries(e).filter(([s])=>r(s)[1]!=="sandbox"));return{[`${r(i)[0]}sandbox`]:"",...a}}function fo(n){return Object.fromEntries(Object.entries(n).filter(([,e])=>e!=null))}function yi(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>e.startsWith("xmlns_")?[`xmlns:${e.slice(6)}`,t]:e.startsWith("data_")||e.startsWith("aria_")?[e.replaceAll("_","-"),t]:[e,t]))}function hs(n){let{_meta:e,...t}=n;return yi(fo(Sr(t)))}function xp(n,e){let t=fv[String(n).toLowerCase()]??[],r={},o={};for(let[i,a]of Object.entries(e))t.includes(i)?o[i]=a:r[i]=a;return[r,o]}function lo(n){return String(n)}function vi(n,e,t=null){let r={...e},{mask:o,format:i,locale:a,timeZone:s,dtype:l,places:u}=r;for(let d of hv)delete r[d];let c=d=>{if(t&&i!=null){if(u!=null)throw new RangeError("places is not implemented; specify precision in format");return t(d,{pattern:i,mask:o,...a==null?{}:{locale:a},...s==null?{}:{timeZone:s},...l==null?{}:{dtype:l}})}if(typeof d=="boolean"&&(d=lo(d)),o==null)return d;let f=d==null?"":lo(d);return f===""?f:ds(f,o)};return Array.isArray(n)?(Object.hasOwn(r,"_text")&&(r._text=c(r._text)),[n,r]):[c(n),r]}function mt(n){return typeof n=="string"&&n.startsWith("==")}var ps=class{#e;#t;#r;#n;#o;#i;#a;#s=null;#l=!1;#u=[];#c=new Set;constructor(e,t){this.#e=e;let r=e.ownerDocument;this.#t=r.createElement("div"),this.#t.className="toolbar-viewport",this.#t.append(t),this.#n=r.createElement("button"),this.#n.type="button",this.#n.className="toolbar-more",this.#n.hidden=!0,this.#n.title="More commands";let o=r.createElementNS(Dr,"svg");o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("aria-hidden","true"),o.setAttribute("focusable","false");let i=r.createElementNS(Dr,"path");i.setAttribute("d","m5 6 6 6-6 6m8-12 6 6-6 6"),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","1.8"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-linejoin","round"),o.append(i),this.#n.append(o),this.#n.setAttribute("aria-label","More commands"),this.#n.setAttribute("aria-haspopup","menu"),this.#n.setAttribute("aria-expanded","false"),this.#r=r.createElement("div"),this.#r.className="toolbar-overflow",this.#r.setAttribute("popover","manual"),this.#r.setAttribute("role","menu"),this.#r.tabIndex=-1;let a=r.createElement("slot");a.name="overflow",this.#r.append(a),this.#n.addEventListener("click",()=>this.#l?this.close():this.open()),this.#n.addEventListener("keydown",l=>{["ArrowDown","ArrowRight"].includes(l.key)&&(l.preventDefault(),l.stopPropagation(),this.open())}),this.#r.addEventListener("keydown",l=>{l.key==="Escape"&&!l.composedPath().some(u=>u.localName==="gramlot-menu"&&u!==e)&&(l.preventDefault(),l.stopPropagation(),this.close())});let s=r.createElement("style");s.textContent=`
|
|
120
|
+
.caption:empty{display:none}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",e.append(t,this.controlBox)}projectAttributes(e){return io(this,e)}setPageContext(e){this.pageContext=e}connectedCallback(){}releaseControl(){}get liveWrites(){return this.control.localName==="textarea"||["text","password","range","color"].includes(this.control.type)}validateCandidate(e,t){return t(e),{ok:!0,value:e,isCurrent:()=>this.pageContext.isActive()}}finishValidation(){}validationValueCheck(){return this.constructor.validationValueCheck(this.pageContext)}static validationValueCheck(){let e=this.gramlotComponent.parameters.value.nullable;return(t,r)=>{if(t==null&&!e)throw new TypeError("This component requires a non-null value.");if(t!=null&&r!=null&&typeof t!=typeof r)throw new TypeError("Validation must preserve the component value type.")}}validationSelection(){return this.constructor.validationSelection(this.parameters,this.pageContext)}static validationSelection(){return()=>{throw new TypeError("validate_select requires a constrained choice editor.")}}validateSelection(e){return this.validationSelection()(e)}shouldProjectControlValue(){return!0}acceptControlValue(){let e=this.readControlValue();return this.validateCandidate(e,t=>{this.validationValueCheck()(t,e),this.sameControlValue(e,t)||this.writeControlValue(t)})}restoreFormDraft(e){this.control.value=e}restoreFormValue(e){this.writeControlValue(e)}sameControlValue(e,t){return Object.is(e,t)}focus(e){this.control.focus(e)}}}function yp(n){return class extends us(n){constructor(){super(),this.control=this.createControl(),(this.control.localName==="textarea"||this.control.localName==="input"&&["text","password"].includes(this.control.type))&&(this.control.setAttribute("autocomplete","off"),this.control.setAttribute("autocorrect","off"),this.control.setAttribute("autocapitalize","off"),this.control.setAttribute("spellcheck","false")),this.control.id="control";let e=this.ownerDocument.createElement("label");e.className="option",this.optionCaption=this.ownerDocument.createElement("span"),this.optionCaption.className="caption",e.append(this.control,this.optionCaption),this.controlBox.append(e)}projectAttributes(e,t){let r=super.projectAttributes(e,t),{disabled:o,readonly:i}=this.parameters;this.control.disabled=!!o,this.control.readOnly=!!i;for(let[a,s]of Object.entries(this.constructor.gramlotComponent.parameters)){if(s.target==="control"){let l=this.parameters[a]??"";String(this.control[a])!==String(l)&&(this.control[a]=l)}s.target==="optionCaption"&&(this.optionCaption.textContent=this.parameters[a]??"")}return r}}}yp.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"},live:{dtype:"B",default:!1,binding:"read"}};function vp(n){return class extends us(n){#e=new Map;#t;#r=null;constructor(){super(),this.control=this.ownerDocument.createElement("div"),this.control.className="options",this.control.id="control",this.control.setAttribute("role",this.multiple?"group":"radiogroup"),this.controlBox.append(this.control),this.control.addEventListener("keydown",e=>{if(!this.multiple||!["ArrowDown","ArrowUp","ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;let t=[...this.control.querySelectorAll("input:not(:disabled)")],r=t.indexOf(e.target);if(r<0)return;e.preventDefault();let o=e.key==="Home"?0:e.key==="End"?t.length-1:Math.max(0,Math.min(t.length-1,r+(["ArrowDown","ArrowRight"].includes(e.key)?1:-1)));t[o].focus()})}choiceOptions(){return oo(this.parameters.values??"")}projectAttributes(e,t){let r=super.projectAttributes(e,t),o=this.choiceOptions(),i=JSON.stringify(o);if(i!==this.#t){let s=o,l=new Set,u=null;for(let{id:c,caption:d}of s){let f=this.#e.get(c);if(!f){let p=this.ownerDocument.createElement("label");p.className="option";let m=this.ownerDocument.createElement("input");m.type=this.choiceType,m.name="choice",m.value=c;let b=this.ownerDocument.createElement("span");p.append(m,b),f={label:p,input:m,text:b},this.#e.set(c,f)}f.text.textContent=d;let h=u?u.nextSibling:this.control.firstChild;h!==f.label&&this.control.insertBefore(f.label,h),u=f.label,l.add(c)}for(let[c,d]of this.#e)l.has(c)||(d.label.remove(),this.#e.delete(c));this.#t=i}let a=this.parameters.cols;if(!Number.isInteger(a)||a<1)throw new TypeError("cols must be a positive integer");this.control.style.gridTemplateColumns=`repeat(${a}, minmax(0, 1fr))`,this.control.disabled=!!this.parameters.disabled,this.control.readOnly=!!this.parameters.readonly;for(let{input:s}of this.#e.values())s.disabled=this.control.disabled||this.control.readOnly;return r}readControlValue(){if(this.multiple){let t=(this.#r?this.#r.split(","):[]).filter(r=>!this.#e.has(r)||this.#e.get(r).input.checked);for(let[r,{input:o}]of this.#e)o.checked&&!t.includes(r)&&t.push(r);return t.join(",")||null}for(let[e,{input:t}]of this.#e)if(t.checked)return e;return null}writeControlValue(e){this.#r=e;let t=this.multiple?new Set(e?e.split(","):[]):null;for(let[r,{input:o}]of this.#e)o.checked=this.multiple?t.has(r):r===e}acceptControlValue(){let e=this.readControlValue();return this.validateCandidate(e,t=>this.writeControlValue(t))}focus(e){let t=[...this.#e.values()];(t.find(({input:r})=>r.checked&&!r.disabled)??t.find(({input:r})=>!r.disabled))?.input.focus(e)}}}vp.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"}};function ao(n,e,{align:t="start",matchWidth:r=!1,inset:o=0,placement:i="bottom",point:a=null}={}){let s=e.ownerDocument.defaultView,l=a?{left:a.x,right:a.x,top:a.y,bottom:a.y,width:0}:e.getBoundingClientRect(),u=Math.max(0,s.innerWidth-16);n.style.setProperty("--gramlot-popup-available-width",`${u}px`),r&&(n.style.width=`${Math.min(Math.max(0,l.width-2*o),u)}px`),n.style.removeProperty("--gramlot-popup-available-height");let c=n.getBoundingClientRect();if(i==="side"){let w=Math.max(0,s.innerWidth-8-l.right-3),_=Math.max(0,l.left-8-3),y=c.width>w&&_>w;n.style.setProperty("--gramlot-popup-available-width",`${y?_:w}px`),n.style.setProperty("--gramlot-popup-available-height",`${Math.max(0,s.innerHeight-16)}px`);let x=n.getBoundingClientRect(),D=y?l.left-x.width-3:l.right+3;n.style.left=`${Math.max(8,Math.min(D,s.innerWidth-x.width-8))}px`,n.style.top=`${Math.max(8,Math.min(l.top,s.innerHeight-x.height-8))}px`;return}let d=Math.max(0,s.innerHeight-8-l.bottom-3),f=Math.max(0,l.top-8-3),h=c.height>d&&f>d;n.style.setProperty("--gramlot-popup-available-height",`${h?f:d}px`);let p=n.getBoundingClientRect(),m=t==="end"?l.right-p.width-o:l.left+o,b=h?l.top-p.height-3:l.bottom+3;n.style.left=`${Math.max(8,Math.min(m,s.innerWidth-p.width-8))}px`,n.style.top=`${Math.max(8,Math.min(b,s.innerHeight-p.height-8))}px`}var so=new Map;function cs(n,e,t){let r=JSON.stringify([n,e,t]),o=so.get(r);if(o)so.delete(r);else{let i=n?Intl.DateTimeFormat:Intl.NumberFormat;if(!i.supportedLocalesOf([e]).length)throw new RangeError(`Unsupported format locale: ${e}`);o=new i(e,t),so.size===64&&so.delete(so.keys().next().value)}return so.set(r,o),o}function Ep(n){if(n!=null&&(typeof n!="string"||/[{}]/.test(n.replaceAll("{}",""))))throw new RangeError("This formatter mask supports only {} placeholders")}function fs(n,e){return Ep(e),e==null?n:e.replaceAll("{}",()=>n)}function fv(n){if(n instanceof Date)return vr(n);if(le(n))return"N";if(typeof n=="number")return Number.isInteger(n)?"L":"R";throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects")}function hv(n,e,{pattern:t="short",locale:r,timeZone:o}){if(!["short","medium","long","full"].includes(t))throw new RangeError("Temporal formatting currently supports short, medium, long and full only");if(e==="DHZ"&&(typeof o!="string"||!o))throw new TypeError("DHZ formatting currently requires an explicit timeZone");let i={timeZone:e==="DHZ"?o:"UTC"};return e!=="H"&&(i.dateStyle=t),e!=="D"&&(i.timeStyle=t),cs(!0,r,i).format(n)}function ds(n){let e=/^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(n);if(!e||e[1]==="("!=(e[4]===")")||n.endsWith("."))throw new RangeError(`Unsupported numeric pattern section: ${n}`);let t=e[3]??"";return{prefix:e[1]??"",suffix:e[4]??"",intl:{useGrouping:e[2].startsWith("#,##")?"always":!1,minimumIntegerDigits:e[2].replace("#,##","").length,minimumFractionDigits:t.replaceAll("#","").length,maximumFractionDigits:t.length}}}function pv(n){let e=n.split(";");if(e.length>3)throw new RangeError("Numeric patterns support at most three sections");let t=ds(e[0]);if(t.prefix||t.suffix)throw new RangeError("Positive-section affixes are not implemented");let r=e.length===3?e[1]:null;r!==null&&r!==""&&r!=="-"&&ds(r);let o=e.length>1?ds(e.at(-1)):null;return{positive:t,zero:r,negative:o}}function hs(n,e={},t={}){if(n===null)return"";if(typeof e=="string"&&(e={pattern:e}),!e||typeof e!="object"||Array.isArray(e))throw new TypeError("Format options must be a pattern string or an options object");for(let b of Object.keys(e))if(!["pattern","locale","mask","dtype","timeZone"].includes(b))throw new RangeError(`Unsupported format option: ${b}`);e={...e,locale:e.locale??t.locale,timeZone:e.timeZone??t.timeZone};let r=e.dtype===void 0?fv(n):e.dtype,o=["D","H","DHZ"].includes(r);if(!o&&!["L","R","N"].includes(r))throw new RangeError(`Unsupported format dtype: ${r}`);if(o){if(!(n instanceof Date)||!Number.isFinite(n.getTime()))throw new TypeError(`${r} requires a valid Date object`)}else if(!(typeof n=="number"&&Number.isFinite(n))&&!(le(n)&&!["NaN","Infinity","-Infinity"].includes(n.toString())))throw new TypeError(`${r} formatting requires finite JavaScript numbers or TYTX Decimal values`);if(r==="L"&&!Number.isInteger(n))throw new TypeError("L formatting requires an integer");let{pattern:i,locale:a,mask:s}=e;if(!o&&typeof i!="string")throw new TypeError("Numeric formatting currently requires an explicit pattern");if(typeof a!="string"||!a)throw new TypeError("Formatting currently requires an explicit locale");if(Ep(s),o){let b=hv(n,r,e);return fs(b,s)}let{positive:l,zero:u,negative:c}=pv(i),d=cs(!1,a,l.intl),f=le(n),h=f?n.eq(0):n===0,p=f?n.lt(0):n<0;if(f&&cs(!1,"en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal without precision loss");let m;if(h&&u!==null){if(u==="")return"";if(u==="-")m="-";else{let b=ds(u);m=b.prefix+cs(!1,a,b.intl).format(0)+b.suffix}}else{let b=p&&c?c:l,w=f?(p&&c?n.abs():n).toString():p&&c?-n:n===0?0:n;m=b.prefix+d.format(w)+b.suffix}return fs(m,s)}var Fe="http://www.w3.org/1999/xhtml",Sr="http://www.w3.org/2000/svg",mv=new Set(["default","default_value","live","group","visible","action","fire","ask","_ask","_ask_if","_ask_title","_ask_onCancel","if","else","_init","_onStart","_onBuilt","_delay","_timing","_userChanges","remote","_cachedRemote","_onRemote","_onCalling","onComplete","onClose","onEnd","onChecked","onDrag","onDrop","dropTargetCb","onDragEnd","dropTarget","dropTypes","dragTags","dropTags","effectAllowed","dropEffect","dragClass"]),gv=["default_","attr_","fire_","connect_on","subscribe_","selfsubscribe_","formsubscribe_","remote_"],bv={table:["width","border"],editor:["height"],embed:["width","height"],img:["width","height"],canvas:["width","height"]},wv=["format","mask","locale","timeZone","places","dtype"],_v=new Set(["href","src","data","action","formaction","xlink:href","xlink_href"]);function Cr(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>!(t&&typeof t=="object"&&Object.hasOwn(t,"$gramlotRef"))&&!mv.has(e)&&!gv.some(r=>e.startsWith(r))))}function uo(n,e,t=[]){for(let[r,o]of Object.entries(e)){let i=t.find(s=>r.startsWith(s))??"",a=r.slice(i.length);if(["style","class","_class"].includes(a)&&o!=null&&typeof o!="string")throw new TypeError(`${n.nodeTag} '${n.label}': '${r}' must be a string or null`)}}function co(n,e,t=[]){if(n.nodeTag==="script"){let r=[["",n.staticValue],...Le(n.getAttr()).filter(([o])=>["src","href","xlink:href","xlink_href","_text"].includes(o.slice((t.find(i=>o.startsWith(i))??"").length).toLowerCase()))];for(let[o,i]of r)if(n.pointerType(i)||mt(i))throw new Error(`script '${n.label}': '${o}' must be literal Source; script code and URLs cannot come from Data`)}if(e.onEnd!=null&&(n.nodeTag.toLowerCase()!=="transformpane"||!n._getMeta("gramlot_component")?.parameters?.onEnd))throw new Error("onEnd is only supported on transformPane");if(e.onChecked!=null&&!n._getMeta("gramlot_component")?.parameters?.onChecked)throw new Error("onChecked is only supported on a component that declares it");if(e.onComplete!=null&&!["uploader","imageUploader"].includes(n.nodeTag))throw new Error("onComplete is only supported on an uploader or imageUploader");if(e.onClose!=null&&!n.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose)throw new Error("onClose is only supported on a tab/stack panel");for(let[r,o]of Object.entries(fo(Cr(e)))){let i=t.find(s=>r.startsWith(s)),a=i?r.slice(i.length):r;if(/^on./i.test(a))throw new Error(`${n.nodeTag} '${n.label}': '${r}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${a} for an event, or rename the attribute`);if(_v.has(a.toLowerCase())&&yv(o))throw new Error(`${n.nodeTag} '${n.label}': '${r}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`)}}function yv(n){return typeof n=="string"&&/^javascript:/i.test(n.replace(/[\t\n\r]/g,"").replace(/^[\u0000-\u0020]+/,""))}function xp(n,e,t=[]){if(n.nodeTag!=="iframe")return e;let r=s=>{let l=t.find(u=>s.startsWith(u))??"";return[l,s.slice(l.length).toLowerCase()]},o=Object.fromEntries(Le(n.getAttr())),i=[...Object.keys(o),...Object.keys(e)].find(s=>r(s)[1]==="srcdoc");if(i===void 0||Object.keys(o).some(s=>r(s)[1]==="sandbox")||n.pointerType(n.value)===null&&!(Object.hasOwn(o,i)&&(n.pointerType(o[i])!==null||mt(o[i]))))return e;let a=Object.fromEntries(Object.entries(e).filter(([s])=>r(s)[1]!=="sandbox"));return{[`${r(i)[0]}sandbox`]:"",...a}}function fo(n){return Object.fromEntries(Object.entries(n).filter(([,e])=>e!=null))}function yi(n){return Object.fromEntries(Object.entries(n).map(([e,t])=>e.startsWith("xmlns_")?[`xmlns:${e.slice(6)}`,t]:e.startsWith("data_")||e.startsWith("aria_")?[e.replaceAll("_","-"),t]:[e,t]))}function ps(n){let{_meta:e,...t}=n;return yi(fo(Cr(t)))}function kp(n,e){let t=bv[String(n).toLowerCase()]??[],r={},o={};for(let[i,a]of Object.entries(e))t.includes(i)?o[i]=a:r[i]=a;return[r,o]}function lo(n){return String(n)}function vi(n,e,t=null){let r={...e},{mask:o,format:i,locale:a,timeZone:s,dtype:l,places:u}=r;for(let d of wv)delete r[d];let c=d=>{if(t&&i!=null){if(u!=null)throw new RangeError("places is not implemented; specify precision in format");return t(d,{pattern:i,mask:o,...a==null?{}:{locale:a},...s==null?{}:{timeZone:s},...l==null?{}:{dtype:l}})}if(typeof d=="boolean"&&(d=lo(d)),o==null)return d;let f=d==null?"":lo(d);return f===""?f:fs(f,o)};return Array.isArray(n)?(Object.hasOwn(r,"_text")&&(r._text=c(r._text)),[n,r]):[c(n),r]}function mt(n){return typeof n=="string"&&n.startsWith("==")}var ms=class{#e;#t;#r;#n;#o;#i;#a;#s=null;#l=!1;#u=[];#c=new Set;constructor(e,t){this.#e=e;let r=e.ownerDocument;this.#t=r.createElement("div"),this.#t.className="toolbar-viewport",this.#t.append(t),this.#n=r.createElement("button"),this.#n.type="button",this.#n.className="toolbar-more",this.#n.hidden=!0,this.#n.title="More commands";let o=r.createElementNS(Sr,"svg");o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("aria-hidden","true"),o.setAttribute("focusable","false");let i=r.createElementNS(Sr,"path");i.setAttribute("d","m5 6 6 6-6 6m8-12 6 6-6 6"),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","1.8"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-linejoin","round"),o.append(i),this.#n.append(o),this.#n.setAttribute("aria-label","More commands"),this.#n.setAttribute("aria-haspopup","menu"),this.#n.setAttribute("aria-expanded","false"),this.#r=r.createElement("div"),this.#r.className="toolbar-overflow",this.#r.setAttribute("popover","manual"),this.#r.setAttribute("role","menu"),this.#r.tabIndex=-1;let a=r.createElement("slot");a.name="overflow",this.#r.append(a),this.#n.addEventListener("click",()=>this.#l?this.close():this.open()),this.#n.addEventListener("keydown",l=>{["ArrowDown","ArrowRight"].includes(l.key)&&(l.preventDefault(),l.stopPropagation(),this.open())}),this.#r.addEventListener("keydown",l=>{l.key==="Escape"&&!l.composedPath().some(u=>u.localName==="gramlot-menu"&&u!==e)&&(l.preventDefault(),l.stopPropagation(),this.close())});let s=r.createElement("style");s.textContent=`
|
|
121
121
|
:host([role=toolbar]){min-width:0;min-height:0;max-width:100%;width:100%;flex-shrink:1;gap:0}
|
|
122
122
|
:host([role=toolbar][aria-orientation=vertical]){width:auto;height:100%;max-height:100%}
|
|
123
123
|
.toolbar-viewport{display:contents}
|
|
@@ -134,7 +134,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
134
134
|
max-width:var(--gramlot-popup-available-width);max-height:var(--gramlot-popup-available-height);overflow:auto;
|
|
135
135
|
background:var(--gramlot-field-background,Canvas);color:var(--gramlot-ink,CanvasText);border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-lg,9px);box-shadow:0 8px 28px #0004}
|
|
136
136
|
.toolbar-overflow ::slotted([role=separator]){margin:5px 7px;border-top:1px solid var(--gramlot-border-control,#888)}
|
|
137
|
-
`,e.shadowRoot.append(s,this.#t,this.#n,this.#r)}get opened(){return this.#l}get button(){return this.#n}get panel(){return this.#r}contains(e){let t=e;for(;t&&t.parentElement!==this.#e;)t=t.parentElement;return this.#c.has(t)}connect(){if(!this.#e.permanent||this.#o)return;let e=this.#e.ownerDocument.defaultView;this.#i=new e.AbortController,this.#o=new e.ResizeObserver(()=>this.schedule()),this.#o.observe(this.#e),this.#e.ownerDocument.fonts.addEventListener("loadingdone",()=>this.schedule(),{signal:this.#i.signal}),this.schedule()}disconnect(){this.close(!1),this.#o?.disconnect(),this.#o=null,this.#i?.abort(),this.#s!==null&&this.#e.ownerDocument.defaultView.cancelAnimationFrame(this.#s),this.#s=null,this.#u=[]}schedule(){if(this.#e.isConnected){if(!this.#e.permanent){this.disconnect();for(let e of this.#e.children)e.removeAttribute("slot"),e.removeAttribute("data-menu-overflow");this.#c.clear(),this.#n.hidden=!0;return}this.#o||this.connect(),this.#s===null&&(this.#s=this.#e.ownerDocument.defaultView.requestAnimationFrame(()=>{this.#s=null,this.layout()}))}}layout(){let e=this.#e,t=e.ownerDocument.defaultView;if(!e.permanent||!e.isConnected)return;let r=e.parameters.orientation==="vertical",o=r?"height":"width",i=t.getComputedStyle(e),a=(r?e.clientHeight:e.clientWidth)-parseFloat(i[r?"paddingTop":"paddingLeft"]||0)-parseFloat(i[r?"paddingBottom":"paddingRight"]||0);if(a<=0)return;let s=e.ownerDocument.activeElement;for(;s?.shadowRoot?.activeElement;)s=s.shadowRoot.activeElement;let l=[...e.children].filter(b=>!b.hidden&&(Je(b).localName!=="gramlot-menu"||Je(b).permanent));for(let b of this.#u)l.includes(b)||(this.#o.unobserve(b),b.removeAttribute("slot"),b.removeAttribute("data-menu-overflow"));for(let b of l)this.#u.includes(b)||this.#o.observe(b);this.#u=l;for(let b of l)b.removeAttribute("slot"),b.removeAttribute("data-menu-overflow");this.#c.clear(),e.refreshItems();for(let b of e.items)b.refreshAvailability();this.#t.setAttribute("data-measuring","");let u=parseFloat(t.getComputedStyle(this.#t).gap)||0,c=new Map(l.map(b=>{let w=t.getComputedStyle(b),_=Je(b).localName==="gramlot-spacer"?Je(b).parameters.size??0:b.getBoundingClientRect()[o];return[b,_+(parseFloat(w[r?"marginTop":"marginLeft"])||0)+(parseFloat(w[r?"marginBottom":"marginRight"])||0)]}));this.#t.removeAttribute("data-measuring");let d=b=>Je(b).getAttribute("role")==="separator",f=b=>b.filter((w,_)=>!d(w)||b.slice(0,_).some(y=>Je(y).localName!=="gramlot-spacer"&&!d(y))&&b.slice(_+1).find(y=>Je(y).localName!=="gramlot-spacer")&&!d(b.slice(_+1).find(y=>Je(y).localName!=="gramlot-spacer"))),h=b=>b.reduce((w,_)=>w+c.get(_),0)+Math.max(0,b.length-1)*u,p=f(l);if(h(p)>a){let b=l.length;for(;b>0&&h(p)>a-32;)b--,p=f(l.slice(0,b));let w=f(l.slice(b).filter(_=>Je(_).localName!=="gramlot-spacer"));for(let _ of w)this.#c.add(_)}for(let b of l)!p.includes(b)&&!this.#c.has(b)&&(b.slot="suppressed");for(let b of this.#c)b.slot="overflow",b.setAttribute("data-menu-overflow","");this.#n.hidden=this.#c.size===0;for(let b of e.items)b.refreshAvailability();e.refreshItems();let m=l.find(b=>{let w=s;for(;w;){if(w===b)return!0;w=w.parentNode??w.host}return!1});this.#c.size===0?this.close(!1):m&&this.#c.has(m)?this.open(!1):this.#l&&this.#d(),m&&s?.isConnected&&s.focus({preventScroll:!0}),e.refreshItems()}#d(){ao(this.#r,this.#n,{placement:this.#e.parameters.orientation==="vertical"?"side":"bottom"})}open(e=!0){if(this.#c.size){if(!this.#l){this.#r.showPopover(),this.#l=!0,this.#n.setAttribute("aria-expanded","true"),this.#a=new this.#e.ownerDocument.defaultView.AbortController;let t={signal:this.#a.signal};this.#e.ownerDocument.addEventListener("pointerdown",r=>{!r.composedPath().includes(this.#r)&&!r.composedPath().includes(this.#n)&&this.close(!1)},t),this.#e.ownerDocument.addEventListener("scroll",()=>this.#d(),{...t,capture:!0})}if(this.#e.refreshItems(),this.#d(),e){let t=o=>{if(o.hidden||o.disabled)return null;if(o.localName==="gramlot-menu-line"&&!o.parameters.group)return o.getAttribute("role")==="separator"?null:o;if(o.matches('input:not([type=hidden]),textarea,select,button,[tabindex="0"]'))return o;for(let i of o.children){let a=t(i);if(a)return a}return null};([...this.#e.children].filter(o=>this.#c.has(o)).map(t).find(Boolean)??this.#r).focus()}}}close(e=!0){if(this.#l){for(let t of this.#c)for(let r of t.querySelectorAll("gramlot-menu"))r.permanent||r.close(!1);this.#r.hidePopover(),this.#l=!1,this.#a?.abort(),this.#n.setAttribute("aria-expanded","false"),e&&!this.#n.hidden&&this.#n.focus()}}};function
|
|
137
|
+
`,e.shadowRoot.append(s,this.#t,this.#n,this.#r)}get opened(){return this.#l}get button(){return this.#n}get panel(){return this.#r}contains(e){let t=e;for(;t&&t.parentElement!==this.#e;)t=t.parentElement;return this.#c.has(t)}connect(){if(!this.#e.permanent||this.#o)return;let e=this.#e.ownerDocument.defaultView;this.#i=new e.AbortController,this.#o=new e.ResizeObserver(()=>this.schedule()),this.#o.observe(this.#e),this.#e.ownerDocument.fonts.addEventListener("loadingdone",()=>this.schedule(),{signal:this.#i.signal}),this.schedule()}disconnect(){this.close(!1),this.#o?.disconnect(),this.#o=null,this.#i?.abort(),this.#s!==null&&this.#e.ownerDocument.defaultView.cancelAnimationFrame(this.#s),this.#s=null,this.#u=[]}schedule(){if(this.#e.isConnected){if(!this.#e.permanent){this.disconnect();for(let e of this.#e.children)e.removeAttribute("slot"),e.removeAttribute("data-menu-overflow");this.#c.clear(),this.#n.hidden=!0;return}this.#o||this.connect(),this.#s===null&&(this.#s=this.#e.ownerDocument.defaultView.requestAnimationFrame(()=>{this.#s=null,this.layout()}))}}layout(){let e=this.#e,t=e.ownerDocument.defaultView;if(!e.permanent||!e.isConnected)return;let r=e.parameters.orientation==="vertical",o=r?"height":"width",i=t.getComputedStyle(e),a=(r?e.clientHeight:e.clientWidth)-parseFloat(i[r?"paddingTop":"paddingLeft"]||0)-parseFloat(i[r?"paddingBottom":"paddingRight"]||0);if(a<=0)return;let s=e.ownerDocument.activeElement;for(;s?.shadowRoot?.activeElement;)s=s.shadowRoot.activeElement;let l=[...e.children].filter(b=>!b.hidden&&(Je(b).localName!=="gramlot-menu"||Je(b).permanent));for(let b of this.#u)l.includes(b)||(this.#o.unobserve(b),b.removeAttribute("slot"),b.removeAttribute("data-menu-overflow"));for(let b of l)this.#u.includes(b)||this.#o.observe(b);this.#u=l;for(let b of l)b.removeAttribute("slot"),b.removeAttribute("data-menu-overflow");this.#c.clear(),e.refreshItems();for(let b of e.items)b.refreshAvailability();this.#t.setAttribute("data-measuring","");let u=parseFloat(t.getComputedStyle(this.#t).gap)||0,c=new Map(l.map(b=>{let w=t.getComputedStyle(b),_=Je(b).localName==="gramlot-spacer"?Je(b).parameters.size??0:b.getBoundingClientRect()[o];return[b,_+(parseFloat(w[r?"marginTop":"marginLeft"])||0)+(parseFloat(w[r?"marginBottom":"marginRight"])||0)]}));this.#t.removeAttribute("data-measuring");let d=b=>Je(b).getAttribute("role")==="separator",f=b=>b.filter((w,_)=>!d(w)||b.slice(0,_).some(y=>Je(y).localName!=="gramlot-spacer"&&!d(y))&&b.slice(_+1).find(y=>Je(y).localName!=="gramlot-spacer")&&!d(b.slice(_+1).find(y=>Je(y).localName!=="gramlot-spacer"))),h=b=>b.reduce((w,_)=>w+c.get(_),0)+Math.max(0,b.length-1)*u,p=f(l);if(h(p)>a){let b=l.length;for(;b>0&&h(p)>a-32;)b--,p=f(l.slice(0,b));let w=f(l.slice(b).filter(_=>Je(_).localName!=="gramlot-spacer"));for(let _ of w)this.#c.add(_)}for(let b of l)!p.includes(b)&&!this.#c.has(b)&&(b.slot="suppressed");for(let b of this.#c)b.slot="overflow",b.setAttribute("data-menu-overflow","");this.#n.hidden=this.#c.size===0;for(let b of e.items)b.refreshAvailability();e.refreshItems();let m=l.find(b=>{let w=s;for(;w;){if(w===b)return!0;w=w.parentNode??w.host}return!1});this.#c.size===0?this.close(!1):m&&this.#c.has(m)?this.open(!1):this.#l&&this.#d(),m&&s?.isConnected&&s.focus({preventScroll:!0}),e.refreshItems()}#d(){ao(this.#r,this.#n,{placement:this.#e.parameters.orientation==="vertical"?"side":"bottom"})}open(e=!0){if(this.#c.size){if(!this.#l){this.#r.showPopover(),this.#l=!0,this.#n.setAttribute("aria-expanded","true"),this.#a=new this.#e.ownerDocument.defaultView.AbortController;let t={signal:this.#a.signal};this.#e.ownerDocument.addEventListener("pointerdown",r=>{!r.composedPath().includes(this.#r)&&!r.composedPath().includes(this.#n)&&this.close(!1)},t),this.#e.ownerDocument.addEventListener("scroll",()=>this.#d(),{...t,capture:!0})}if(this.#e.refreshItems(),this.#d(),e){let t=o=>{if(o.hidden||o.disabled)return null;if(o.localName==="gramlot-menu-line"&&!o.parameters.group)return o.getAttribute("role")==="separator"?null:o;if(o.matches('input:not([type=hidden]),textarea,select,button,[tabindex="0"]'))return o;for(let i of o.children){let a=t(i);if(a)return a}return null};([...this.#e.children].filter(o=>this.#c.has(o)).map(t).find(Boolean)??this.#r).focus()}}}close(e=!0){if(this.#l){for(let t of this.#c)for(let r of t.querySelectorAll("gramlot-menu"))r.permanent||r.close(!1);this.#r.hidePopover(),this.#l=!1,this.#a?.abort(),this.#n.setAttribute("aria-expanded","false"),e&&!this.#n.hidden&&this.#n.focus()}}};function Tp(n){return class extends n{#e;#t;#r=null;#n=[];#o=null;#i;#a;#s;#l;#u=!1;#c;#d;constructor(){super();let e=this.ownerDocument,t=this.attachShadow({mode:"open"}),r=e.createElement("style");r.textContent=`:host{box-sizing:border-box;color:var(--gramlot-ink,CanvasText)}
|
|
138
138
|
:host([role=menu]){position:fixed;inset:auto;margin:0;padding:3px;min-width:0;width:max-content;font:inherit;
|
|
139
139
|
max-width:min(28rem,var(--gramlot-popup-available-width));max-height:var(--gramlot-popup-available-height);overflow:auto;
|
|
140
140
|
background:var(--gramlot-field-background,Canvas);border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,5px);box-shadow:0 4px 14px #0003}
|
|
@@ -143,7 +143,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
143
143
|
:host([role=menu]) ::slotted([role=separator]){margin:5px 7px 5px 2.5rem;border-top:1px solid var(--gramlot-border-control,#888)}
|
|
144
144
|
:host([role=toolbar][aria-orientation=horizontal]) ::slotted([role=separator]){border-top:0;border-left:1px solid var(--gramlot-border-control,#888);align-self:stretch;margin:4px}
|
|
145
145
|
:host([hidden]){display:none!important} slot{display:contents} .status{padding:.4em;opacity:.75}
|
|
146
|
-
.status:empty{display:none} button{font:inherit}`,this.#l=e.createElement("slot"),this.#a=e.createElement("span"),this.#a.className="status",this.#a.setAttribute("role","status"),this.#s=e.createElement("button"),this.#s.textContent="Riprova",this.#s.hidden=!0,this.#s.addEventListener("click",o=>{o.stopPropagation(),this.menuBinding.load(!0)}),t.append(r,this.#l,this.#a,this.#s),this.#i=new
|
|
146
|
+
.status:empty{display:none} button{font:inherit}`,this.#l=e.createElement("slot"),this.#a=e.createElement("span"),this.#a.className="status",this.#a.setAttribute("role","status"),this.#s=e.createElement("button"),this.#s.textContent="Riprova",this.#s.hidden=!0,this.#s.addEventListener("click",o=>{o.stopPropagation(),this.menuBinding.load(!0)}),t.append(r,this.#l,this.#a,this.#s),this.#i=new ms(this,this.#l),this.addEventListener("keydown",o=>this.#h(o)),this.addEventListener("focusin",o=>{let i=o.composedPath().find(a=>this.items.includes(a));i&&(this.#r=i,this.refreshItems())})}get permanent(){return this.parameters.presentation==="bar"}get opened(){return this.permanent||this.#u}get items(){return[...this.querySelectorAll("gramlot-menu-line")].filter(e=>e.menuOwner===this&&!e.parameters.group)}get overflow(){return this.#i}isOverflowed(e){return this.#i.contains(e)}get visibleItems(){return this.items.filter(e=>an(e).slot!=="suppressed"&&!e.hidden&&!e.closest("[hidden]")&&e.getAttribute("role")!=="separator")}get usableItems(){return this.visibleItems.filter(e=>!e.disabled)}get parentMenu(){return this.parentElement?.closest("gramlot-menu")??null}connectedCallback(){this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>{this.refreshItems(),this.#i.schedule()}),this.#t.observe(this,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["hidden","disabled"]}),this.refreshItems(),this.#p(),this.#i.connect(),this.permanent&&this.menuBinding?.load()}disconnectedCallback(){this.#i.disconnect(),this.#t?.disconnect(),this.#e?.abort(),this.#d?.abort(),this.#c=null,this.#u=!1}projectAttributes(e){let t=io(this,e);if(this.#f(),!Number.isFinite(this.parameters.iconSize)||this.parameters.iconSize<=0)throw new TypeError("menu iconSize must be positive");return this.setAttribute("role",this.permanent?"toolbar":"menu"),this.setAttribute("aria-orientation",this.permanent?this.parameters.orientation:"vertical"),this.tabIndex=-1,this.permanent?this.removeAttribute("popover"):this.setAttribute("popover","manual"),this.refreshItems(),this.#i.schedule(),t}#f(){let e=this.parameters.modifiers;if(e==null)return null;if(e==="*")return[];let t=e.trim().toLowerCase().split(/[,\s]+/);if(!t.length||t.some(r=>!["shift","ctrl","alt","meta"].includes(r))||new Set(t).size!==t.length)throw new TypeError("Menu modifiers require *, or a combination of Shift, Ctrl, Alt and Meta");return t}#p(){let e=an(this).parentElement;if(this.permanent||!e)return;if(["gramlot-menu-line","gramlot-drop-down-button"].includes(e.localName)){an(this).slot="menu";return}if(e.localName==="gramlot-grouplet-card"){an(this).slot="card-menu";return}if(an(this).removeAttribute("slot"),e.localName==="gramlot-menu")return;this.#c=e,this.#d=new this.ownerDocument.defaultView.AbortController;let t={signal:this.#d.signal},r=i=>!i.composedPath().some(a=>a.localName==="gramlot-menu"),o=i=>{if(this.hidden||this.permanent||!r(i)||i.composedPath().some(u=>u instanceof this.ownerDocument.defaultView.Element&&(u.disabled===!0||u.getAttribute("aria-disabled")==="true")))return;let a=this.#f();if(i.type==="click"){if(a===null||i.button!==0||["shift","ctrl","alt","meta"].some(u=>!!i[u+"Key"]!==a.includes(u)))return}else if(a!==null)return;i.preventDefault(),i.stopPropagation();let s=i.type==="keydown",l=s?e.getBoundingClientRect():null;this.open(e,!1,s?{x:l.left+8,y:l.top+8}:{x:i.clientX,y:i.clientY})};e.addEventListener("click",o,t),e.addEventListener("contextmenu",o,t),e.addEventListener("keydown",i=>{(i.key==="ContextMenu"||i.key==="F10"&&i.shiftKey&&!i.ctrlKey&&!i.altKey&&!i.metaKey)&&o(i)},t)}setStatus(e){this.status=e,this.#a.textContent={loading:"Caricamento\u2026",empty:"Nessuna voce",error:"Impossibile caricare"}[e]??"",this.#s.hidden=e!=="error",this.setAttribute("aria-busy",String(e==="loading"));for(let t of this.items)t.refreshAvailability();this.refreshItems()}refreshItems(){for(let r of this.querySelectorAll("gramlot-menu-line"))r.menuOwner===this&&r.parameters.group&&r.refreshAvailability();for(let r of this.items)r.refreshAvailability();let e=this.usableItems;for(let[r,o,i]of[["check",this.visibleItems.some(a=>a.parameters.checked!=null),"1.4em"],["icon",this.visibleItems.some(a=>a.entryIcon||a.entryIconSrc),"1.5em"],["arrow",this.visibleItems.some(a=>a.submenu),".9em"]])this.style.setProperty(`--gramlot-menu-${r}-track`,o?i:"0px");if(this.#r&&!e.includes(this.#r)){let r=this.#n.indexOf(this.#r),o=this.#n.slice(r+1).find(i=>e.includes(i))??this.#n.slice(0,r).reverse().find(i=>e.includes(i));this.#r=o??null,this.opened&&this.status!=="loading"&&(o?o.focus():this.permanent?this.focus():this.close())}let t=e.filter(r=>!this.isOverflowed(r));for(let r of this.items)r.control.tabIndex=this.permanent&&r===(t.includes(this.#r)?this.#r:t[0])?0:-1;this.#n=this.items}open(e,t=!1,r=null){if(this.permanent)return;this.#o=e,this.#u||(this.showPopover(),this.#u=!0),e.setAttribute("aria-expanded","true"),this.#e?.abort(),this.#e=new this.ownerDocument.defaultView.AbortController;let o={signal:this.#e.signal},i=()=>ao(this,e,{point:r,placement:this.parentMenu&&(!this.parentMenu.permanent||this.parentMenu.parameters.orientation==="vertical"||this.parentMenu.isOverflowed(this.parentElement))?"side":"bottom"});i(),this.ownerDocument.defaultView.addEventListener("resize",i,o),this.ownerDocument.addEventListener("scroll",i,{...o,capture:!0}),this.ownerDocument.addEventListener("pointerdown",a=>{!a.composedPath().includes(this)&&(e===this.#c||!a.composedPath().includes(e))&&this.closeChain(!1)},o),this.menuBinding?.load().then(()=>{this.#u&&(this.ownerDocument.activeElement===this||!this.contains(this.ownerDocument.activeElement))&&this.focusEntry(t),this.#u&&i()}),this.focusEntry(t)}focusEntry(e=!1){let t=this.usableItems,r=t[e?t.length-1:0];r?(this.#r=r,r.focus()):this.focus()}close(e=!0){for(let t of this.querySelectorAll("gramlot-menu"))t.permanent||t.close(!1);if(this.permanent){this.#i.close(e);return}this.#u&&(this.hidePopover(),this.#u=!1,this.#e?.abort(),this.#o?.setAttribute("aria-expanded","false"),e&&this.#o?.isConnected&&this.#o.focus())}closeChain(e=!0){let t=this.parentMenu;this.close(e&&!t),t&&!t.permanent?t.closeChain(e):t?.isOverflowed(this.parentElement)?t.overflow.close(e):e&&this.#o?.isConnected&&this.#o.focus()}#h(e){if(e.defaultPrevented||e.composedPath().find(u=>u.localName==="gramlot-menu")!==this)return;let t=e.composedPath().find(u=>this.items.includes(u));if(!t&&e.target!==this)return;let r=t&&this.isOverflowed(t),o=this.usableItems.filter(u=>this.isOverflowed(u)===!!r),i=o.indexOf(t),a=this.permanent&&!r&&this.parameters.orientation==="horizontal"?"ArrowRight":"ArrowDown",s=this.permanent&&!r&&this.parameters.orientation==="horizontal"?"ArrowLeft":"ArrowUp",l;if(e.key===a&&(l=Math.min(o.length-1,i+1)),e.key===s&&(l=Math.max(0,i-1)),e.key==="Home"&&(l=0),e.key==="End"&&(l=o.length-1),l!==void 0){e.preventDefault(),e.stopPropagation(),o[l]?.focus();return}(!this.permanent||r)&&e.key==="ArrowRight"&&t?.submenu?(e.preventDefault(),e.stopPropagation(),t.openSubmenu()):e.key==="Escape"&&(!this.permanent||this.overflow.opened||this.items.some(u=>u.submenu?.opened))||!this.permanent&&e.key==="ArrowLeft"&&this.parentMenu?(e.preventDefault(),e.stopPropagation(),this.close()):e.key==="Tab"&&this.closeChain(!1)}}}function Ap(n){return class extends n{#e;#t;#r;#n;#o;#i;#a=null;#s=!1;constructor(){super();let e=this.ownerDocument;this.#r=e.createElement("span"),this.#n=e.createElement("span"),this.#r.className="menu-caption",this.#n.className="menu-check",this.#o=e.createElement("span"),this.#o.className="menu-arrow",this.#o.setAttribute("aria-hidden","true"),this.#n.setAttribute("aria-hidden","true"),this.control.prepend(this.#n),this.control.append(this.#r,this.#o);let t=e.createElement("style");t.textContent=`:host{color:var(--gramlot-ink,CanvasText)} .control-box{color:inherit;height:100%} :host button{color:inherit}
|
|
147
147
|
.menu-check:empty,.menu-arrow:empty{display:none}
|
|
148
148
|
button.menu-row{display:grid;grid-template-columns:var(--gramlot-menu-check-track,0px) var(--gramlot-menu-icon-track,0px) minmax(0,1fr) var(--gramlot-menu-arrow-track,0px);column-gap:0;
|
|
149
149
|
align-items:center;width:100%;min-height:max(24px,var(--gramlot-touch-target,0px));padding:2px 7px;
|
|
@@ -180,7 +180,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
180
180
|
:host([data-menu-overflow]) .menu-group,:host([data-menu-group-rows]) .menu-group{flex-direction:column;align-items:stretch;padding:3px 0}
|
|
181
181
|
:host([data-menu-overflow][role=group]){border-block-end:1px solid var(--gramlot-border-control,#888);margin-block-end:4px}
|
|
182
182
|
:host([role=group][aria-disabled=true]) .menu-group{opacity:.45;pointer-events:none}
|
|
183
|
-
:host([hidden]){display:none!important}`,this.caption.name="command-caption",this.#t=e.createElement("div"),this.#t.className="menu-group",this.#t.append(e.createElement("slot")),this.#t.hidden=!0,this.shadowRoot.append(t,this.#t);let r=e.createElement("slot");r.name="menu",this.shadowRoot.append(r),this.addEventListener("pointerenter",()=>{this.menuOwner&&(!this.menuOwner.permanent||this.menuOwner.isOverflowed(this))&&!this.disabled&&(clearTimeout(this.#i),this.#i=setTimeout(()=>{if(!(!this.isConnected||this.disabled||!this.menuOwner.opened))if(this.control.focus({preventScroll:!0}),this.submenu)this.openSubmenu();else for(let o of this.menuOwner.items)o.submenu?.close(!1)},180))}),this.addEventListener("pointerleave",()=>clearTimeout(this.#i))}get menuOwner(){return this.parentElement?.closest("gramlot-menu")??null}get submenu(){return[...this.children].map(Je).find(e=>e?.localName==="gramlot-menu")??null}get entryCaption(){return this.parameters.caption??this.#a?.label??""}get entryIcon(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.icon:this.#a?.icon}get entryIconSrc(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.iconSrc:this.#a?.iconSrc}get occurrence(){return this.parameters.code??this.sourceLabel}setCommandDefinition(e,t){this.#a=e,this.sourceLabel=t,this.#l()}projectAttributes(e,t){let r=super.projectAttributes(e,t);if(this.#e=e["aria-label"],this.parameters.iconSize!=null&&(!Number.isFinite(this.parameters.iconSize)||this.parameters.iconSize<=0))throw new TypeError("menuline iconSize must be positive");return this.#s=!!this.parameters.disabled,this.#l(),this.menuOwner?.refreshItems(),this.menuOwner?.overflow.schedule(),r}#l(){let e=[...this.childNodes].filter(r=>r.nodeType===3).map(r=>r.textContent).join("").trim()==="-"&&!this.parameters.command;this.setAttribute("role",this.parameters.group?"group":e?"separator":this.parameters.checked==null?"menuitem":"menuitemcheckbox"),this.#t.hidden=!this.parameters.group,this.setAttribute("aria-disabled",String(this.#s)),this.parameters.checked!=null?(this.setAttribute("aria-checked",String(this.parameters.checked)),this.control.setAttribute("aria-checked",String(this.parameters.checked))):(this.removeAttribute("aria-checked"),this.control.removeAttribute("aria-checked")),this.#n.textContent=this.parameters.checked?"\u2713":"",this.#r.textContent=this.parameters.command&&!this.#a?"???":this.entryCaption,this.caption.hidden=!0,this.renderIcon(this.entryIcon,this.entryIconSrc);let t=this.parameters.tooltip??this.#a?.tooltip??this.entryCaption;this.control.title=t,this.control.setAttribute("aria-label",this.#e??(this.entryCaption||t)),this.submenu?this.control.setAttribute("aria-haspopup","menu"):this.control.removeAttribute("aria-haspopup"),this.refreshAvailability()}refreshAvailability(){let e=this.menuOwner,t=e&&(!e.permanent||e.isOverflowed(this)),r=s=>{for(let l=this;l&&l!==e;l=l.parentElement)if(l.localName==="gramlot-menu-line"&&l.parameters[s]!=null)return l.parameters[s];return e?.parameters[s]},o=!!(e?.permanent&&!t),i=r("labelPosition");this.control.classList.toggle("toolbar-button",o),this.control.classList.toggle("toolbar-below",o&&i==="below"),this.control.classList.toggle("toolbar-tooltip",o&&i==="tooltip"),o?this.control.style.setProperty("--gramlot-toolbar-icon-size",`${r("iconSize")}px`):this.control.style.removeProperty("--gramlot-toolbar-icon-size"),this.toggleAttribute("data-menu-group-rows",!!(t||e?.parameters.orientation==="vertical")),this.control.classList.toggle("menu-row",t),this.#o.textContent=this.submenu?o&&i==="tooltip"?"\u2304":t||e?.parameters.orientation==="vertical"?"\u203A":"\u25BE":"";let a=this.#s||this.getAttribute("role")==="separator"||!!(this.parameters.command&&!this.#a)||["loading","error"].includes(e?.status)||!!this.closest("gramlot-drop-down-button")?.parameters.disabled;this.control.disabled!==a&&(this.control.disabled=a),this.refreshIconOnly()}get disabled(){for(let e=this.parentElement;e&&e!==this.menuOwner;e=e.parentElement)if(e.localName==="gramlot-menu-line"&&e.parameters.disabled)return!0;return this.control.disabled||!!this.closest("gramlot-drop-down-button")?.parameters.disabled}set disabled(e){this.control.disabled=!!e}attachCommand(){this.#l()}releaseCommand(){clearTimeout(this.#i),this.submenu?.close(!1)}openSubmenu(){if(!(this.disabled||!this.submenu)){for(let e of this.menuOwner.items)e!==this&&e.submenu?.close(!1);this.submenu.open(this.control)}}prepareCommand(e){if(this.parameters.group||this.disabled||this.hidden)return!1;if(this.submenu)return e.stopPropagation(),this.submenu.opened?this.submenu.close():this.openSubmenu(),!1;let t=an(this.menuOwner)?.parentElement;return t?.localName==="gramlot-drop-down-button"?t.selectCommand(this,e.shiftKey):this.menuOwner.closeChain(),!0}}}function Ei(n){return class extends
|
|
183
|
+
:host([hidden]){display:none!important}`,this.caption.name="command-caption",this.#t=e.createElement("div"),this.#t.className="menu-group",this.#t.append(e.createElement("slot")),this.#t.hidden=!0,this.shadowRoot.append(t,this.#t);let r=e.createElement("slot");r.name="menu",this.shadowRoot.append(r),this.addEventListener("pointerenter",()=>{this.menuOwner&&(!this.menuOwner.permanent||this.menuOwner.isOverflowed(this))&&!this.disabled&&(clearTimeout(this.#i),this.#i=setTimeout(()=>{if(!(!this.isConnected||this.disabled||!this.menuOwner.opened))if(this.control.focus({preventScroll:!0}),this.submenu)this.openSubmenu();else for(let o of this.menuOwner.items)o.submenu?.close(!1)},180))}),this.addEventListener("pointerleave",()=>clearTimeout(this.#i))}get menuOwner(){return this.parentElement?.closest("gramlot-menu")??null}get submenu(){return[...this.children].map(Je).find(e=>e?.localName==="gramlot-menu")??null}get entryCaption(){return this.parameters.caption??this.#a?.label??""}get entryIcon(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.icon:this.#a?.icon}get entryIconSrc(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.iconSrc:this.#a?.iconSrc}get occurrence(){return this.parameters.code??this.sourceLabel}setCommandDefinition(e,t){this.#a=e,this.sourceLabel=t,this.#l()}projectAttributes(e,t){let r=super.projectAttributes(e,t);if(this.#e=e["aria-label"],this.parameters.iconSize!=null&&(!Number.isFinite(this.parameters.iconSize)||this.parameters.iconSize<=0))throw new TypeError("menuline iconSize must be positive");return this.#s=!!this.parameters.disabled,this.#l(),this.menuOwner?.refreshItems(),this.menuOwner?.overflow.schedule(),r}#l(){let e=[...this.childNodes].filter(r=>r.nodeType===3).map(r=>r.textContent).join("").trim()==="-"&&!this.parameters.command;this.setAttribute("role",this.parameters.group?"group":e?"separator":this.parameters.checked==null?"menuitem":"menuitemcheckbox"),this.#t.hidden=!this.parameters.group,this.setAttribute("aria-disabled",String(this.#s)),this.parameters.checked!=null?(this.setAttribute("aria-checked",String(this.parameters.checked)),this.control.setAttribute("aria-checked",String(this.parameters.checked))):(this.removeAttribute("aria-checked"),this.control.removeAttribute("aria-checked")),this.#n.textContent=this.parameters.checked?"\u2713":"",this.#r.textContent=this.parameters.command&&!this.#a?"???":this.entryCaption,this.caption.hidden=!0,this.renderIcon(this.entryIcon,this.entryIconSrc);let t=this.parameters.tooltip??this.#a?.tooltip??this.entryCaption;this.control.title=t,this.control.setAttribute("aria-label",this.#e??(this.entryCaption||t)),this.submenu?this.control.setAttribute("aria-haspopup","menu"):this.control.removeAttribute("aria-haspopup"),this.refreshAvailability()}refreshAvailability(){let e=this.menuOwner,t=e&&(!e.permanent||e.isOverflowed(this)),r=s=>{for(let l=this;l&&l!==e;l=l.parentElement)if(l.localName==="gramlot-menu-line"&&l.parameters[s]!=null)return l.parameters[s];return e?.parameters[s]},o=!!(e?.permanent&&!t),i=r("labelPosition");this.control.classList.toggle("toolbar-button",o),this.control.classList.toggle("toolbar-below",o&&i==="below"),this.control.classList.toggle("toolbar-tooltip",o&&i==="tooltip"),o?this.control.style.setProperty("--gramlot-toolbar-icon-size",`${r("iconSize")}px`):this.control.style.removeProperty("--gramlot-toolbar-icon-size"),this.toggleAttribute("data-menu-group-rows",!!(t||e?.parameters.orientation==="vertical")),this.control.classList.toggle("menu-row",t),this.#o.textContent=this.submenu?o&&i==="tooltip"?"\u2304":t||e?.parameters.orientation==="vertical"?"\u203A":"\u25BE":"";let a=this.#s||this.getAttribute("role")==="separator"||!!(this.parameters.command&&!this.#a)||["loading","error"].includes(e?.status)||!!this.closest("gramlot-drop-down-button")?.parameters.disabled;this.control.disabled!==a&&(this.control.disabled=a),this.refreshIconOnly()}get disabled(){for(let e=this.parentElement;e&&e!==this.menuOwner;e=e.parentElement)if(e.localName==="gramlot-menu-line"&&e.parameters.disabled)return!0;return this.control.disabled||!!this.closest("gramlot-drop-down-button")?.parameters.disabled}set disabled(e){this.control.disabled=!!e}attachCommand(){this.#l()}releaseCommand(){clearTimeout(this.#i),this.submenu?.close(!1)}openSubmenu(){if(!(this.disabled||!this.submenu)){for(let e of this.menuOwner.items)e!==this&&e.submenu?.close(!1);this.submenu.open(this.control)}}prepareCommand(e){if(this.parameters.group||this.disabled||this.hidden)return!1;if(this.submenu)return e.stopPropagation(),this.submenu.opened?this.submenu.close():this.openSubmenu(),!1;let t=an(this.menuOwner)?.parentElement;return t?.localName==="gramlot-drop-down-button"?t.selectCommand(this,e.shiftKey):this.menuOwner.closeChain(),!0}}}function Ei(n){return class extends us(n){#e=null;#t;constructor(){super();let e=this.ownerDocument;this.control=e.createElement("button"),this.control.type="button",this.control.id="control",this.icon=e.createElement("span"),this.icon.className="icon",this.icon.setAttribute("aria-hidden","true"),this.caption=e.createElement("slot"),this.control.append(this.icon,this.caption),this.controlBox.append(this.control);let t=e.createElement("style");t.textContent=`:host{vertical-align:middle} :host([hidden]){display:none} .control-box{display:flex;align-items:stretch}
|
|
184
184
|
button{display:inline-flex;align-items:center;justify-content:center;gap:var(--gramlot-button-gap,.35em);font:inherit;
|
|
185
185
|
color:var(--gramlot-button-color,var(--gramlot-ink,CanvasText));background:var(--gramlot-button-background,var(--gramlot-field-background,Canvas));
|
|
186
186
|
border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
|
|
@@ -220,33 +220,33 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
220
220
|
#control.icon-only .led{display:none}
|
|
221
221
|
@media(forced-colors:active){#control.icon-only{background:ButtonFace;color:ButtonText;border-color:ButtonText}
|
|
222
222
|
#control.icon-only:is([aria-pressed=true],[aria-checked=true],[aria-expanded=true]){background:Highlight;color:HighlightText}}
|
|
223
|
-
`,this.shadowRoot.append(t),this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>this.refreshIconOnly())}connectedCallback(){super.connectedCallback();let e={childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["hidden","slot"]};this.#t.observe(this,e),this.#t.observe(this.control,e),this.refreshIconOnly()}disconnectedCallback(){this.#t.disconnect()}releaseControl(){this.#t.disconnect(),super.releaseControl()}refreshIconOnly(){let e=o=>o.nodeType===3?!!o.textContent.trim():o.nodeType===1&&!o.hidden&&o.getAttribute("slot")!=="menu",t=!this.caption.hidden&&this.caption.assignedNodes().some(e),r=[...this.control.children].some(o=>o!==this.icon&&o!==this.caption&&!o.hidden&&!o.matches(".led,.menu-check,.menu-arrow")&&!(o.matches(".menu-caption")&&this.control.classList.contains("toolbar-tooltip"))&&!!o.textContent.trim());this.control.classList.toggle("icon-only",!this.control.classList.contains("menu-row")&&!!(this.icon.textContent||this.icon.firstElementChild)&&!t&&!r)}get disabled(){return this.control.disabled}set disabled(e){this.control.disabled=!!e}projectAttributes(e,t){let r=super.projectAttributes(e,t);return this.control.disabled=!!this.parameters.disabled,this.control.readOnly=!!this.parameters.readonly,this.renderIcon(this.parameters.icon,this.parameters.iconSrc),e["aria-label"]!=null?this.control.setAttribute("aria-label",e["aria-label"]):this.control.removeAttribute("aria-label"),this.#e&&this.setActionPresentation(this.#e),r}renderIcon(e,t){if(!t){this.icon.textContent=e??"",this.refreshIconOnly();return}let r=this.icon.firstElementChild;r||(r=this.ownerDocument.createElement("img"),r.alt="",r.draggable=!1,this.icon.replaceChildren(r)),r.getAttribute("src")!==t&&r.setAttribute("src",t),this.refreshIconOnly()}get entryIcon(){return this.parameters.icon}get entryIconSrc(){return this.parameters.iconSrc}setActionPresentation(e){this.#e=e,this.hidden=e.hidden,this.icon.textContent=e.icon,this.title=e.title,this.control.setAttribute("aria-label",e.title),this.refreshIconOnly()}attachCommand(){}releaseCommand(){}commandTarget(){return this}prepareCommand(){return!this.disabled}}}Ei.parameters={action:{dtype:"T",nullable:!0},disabled:{dtype:"B",default:!1,binding:"read"},icon:{dtype:"T",default:"",binding:"read"},iconSrc:{dtype:"T",default:"",binding:"read"}};var gv=Ar({name:"button",tag:"gramlot-button",base:Ei,command:!0,subTags:"*",implementation:n=>class extends n{}}),bv=Ar({name:"toggleButton",tag:"gramlot-toggle-button",base:Ei,command:!0,subTags:"*",parameters:{value:{dtype:"B",default:!1,binding:"twoWay"},readonly:{dtype:"B",default:!1,binding:"read"}},implementation:n=>class extends n{#e=!1;constructor(){super();let e=this.ownerDocument.createElement("span");e.className="led",e.setAttribute("aria-hidden","true"),this.control.prepend(e),this.writeControlValue(!1)}get commitOnChange(){return!0}readControlValue(){return this.#e}writeControlValue(e){this.#e=e,this.control.setAttribute("aria-pressed",String(e))}prepareCommand(e){return!super.prepareCommand(e)||this.control.readOnly?!1:(this.writeControlValue(!this.#e),this.control.dispatchEvent(new this.ownerDocument.defaultView.Event("change")),!0)}}}),wv=Ar({name:"menu",tag:"gramlot-menu",base:kp,subTags:"menuline,spacer,contentPane",parameters:{presentation:{dtype:"T",default:"popup",enum:["popup","bar"]},orientation:{dtype:"T",default:"horizontal",enum:["horizontal","vertical"]},modifiers:{dtype:"T",nullable:!0},labelPosition:{dtype:"T",binding:"read",default:"beside",enum:["beside","below","tooltip"]},iconSize:{dtype:"R",binding:"read",default:24},resolver:{dtype:"T",nullable:!0},cacheTime:{dtype:"R",default:-1},sync:{dtype:"B",default:!1}},implementation:n=>class extends n{}}),_v=Ar({name:"menuline",tag:"gramlot-menu-line",base:Ei,command:!0,subTags:"*",parameters:{command:{dtype:"T",nullable:!0},caption:{dtype:"T",nullable:!0},code:{dtype:"T",nullable:!0},checked:{dtype:"B",nullable:!0,binding:"read"},tooltip:{dtype:"T",nullable:!0},labelPosition:{dtype:"T",binding:"read",nullable:!0,enum:["beside","below","tooltip"]},iconSize:{dtype:"R",binding:"read",nullable:!0},group:{dtype:"B",default:!1},parameters:{annotation:{kind:"type",module:"builtins",name:"dict"},nullable:!0},favorite:{dtype:"B",default:!1}},implementation:Tp}),yv=Ar({name:"spacer",tag:"gramlot-spacer",base:n=>class extends n{projectAttributes(e){let t=io(this,e),{size:r,flex:o}=this.parameters;if(r!=null&&o!=null)throw new TypeError("spacer accepts size or flex, not both");if(r!=null&&(!Number.isFinite(r)||r<0)||o!=null&&(!Number.isFinite(o)||o<=0))throw new TypeError("Invalid spacer size/flex");return this.style.flex=o!=null?`${o} 1 0px`:`0 0 ${r??0}px`,this.setAttribute("aria-hidden","true"),t}},parameters:{size:{dtype:"R",nullable:!0},flex:{dtype:"R",nullable:!0}},implementation:n=>class extends n{}}),vv=Ar({name:"dropDownButton",tag:"gramlot-drop-down-button",base:Ei,command:!0,subTags:"*",parameters:{persist:{dtype:"B",default:!1}},implementation:n=>class extends n{#e=null;#t;#r=null;#n;#o;constructor(){super();let e=this.ownerDocument;this.control.classList.add("split"),this.controlBox.classList.add("choice-field");let t=e.createElement("style");t.textContent=bp+".split{border-radius:var(--gramlot-radius-sm,4px);padding-inline-end:calc(var(--gramlot-choice-toggle-width,1.6em) + .5em)}",this.shadowRoot.append(t),this.#o=e.createElement("span"),this.#o.hidden=!0,this.control.append(this.#o),this.#n=e.createElement("button"),this.#n.type="button",this.#n.className="arrow choice-toggle",this.#n.setAttribute("aria-label","Open menu"),this.#n.setAttribute("aria-haspopup","menu"),this.#n.setAttribute("aria-expanded","false"),this.controlBox.append(this.#n);let r=e.createElement("slot");r.name="menu",this.shadowRoot.append(r),this.#n.addEventListener("click",o=>{o.stopPropagation(),this.menu.opened?this.closeMenu():this.openMenu()}),this.#n.addEventListener("keydown",o=>{["ArrowDown","ArrowUp"].includes(o.key)&&(o.preventDefault(),this.openMenu(o.key==="ArrowUp"))})}get menu(){return[...this.children].map(Je).find(e=>e.localName==="gramlot-menu")}get menuItems(){return this.menu?.items??[]}projectAttributes(e,t){let r=super.projectAttributes(e,t);return this.#n.disabled=this.disabled,this.disabled&&this.menu?.close(!1),this.#i(),r}attachCommand(){if(this.parameters.persist){if(!this.id)throw new TypeError("dropDownButton persist requires an explicit id");this.#r=`gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;try{this.#e=this.ownerDocument.defaultView.localStorage.getItem(this.#r)}catch{}}this.#i(),this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>this.#i()),this.#t.observe(this,{childList:!0,subtree:!0,characterData:!0})}releaseCommand(){this.#t?.disconnect(),this.menu?.close(!1)}commandTarget(e){return e?.composedPath().includes(this.menu)?null:this.menuItems.find(t=>t.occurrence===this.#e)??this}selectCommand(e,t){if(t){if(this.#e=e.occurrence,this.#r)try{this.ownerDocument.defaultView.localStorage.setItem(this.#r,this.#e)}catch{}this.#i()}this.closeMenu()}#i(){let e=this.menuItems.map(o=>o.occurrence).filter(Boolean);if(new Set(e).size!==e.length)throw new TypeError("Dropdown menu codes must be unique");let t=this.commandTarget(),r=t!==this;this.caption.hidden=r,this.#o.hidden=!r,this.#o.textContent=r?t.entryCaption:"",this.renderIcon(t.entryIcon,t.entryIconSrc)}openMenu(e=!1){this.disabled||this.menu?.open(this.#n,e)}closeMenu(){this.menu?.close()}}}),ms=Zu({name:"buttons",components:[gv,bv,vv,wv,_v,yv]});var ho=class{epoch=0;controller=null;cancel(){this.epoch++,this.controller?.abort(),this.controller=null}start(e,t,r,o,i,a=()=>{}){this.cancel();let s=new AbortController,l=this.epoch;this.controller=s;let u=r.validationCurrent(),c=()=>l===this.epoch&&!s.signal.aborted&&u(),d=m=>({value:e,modified:!1,error:m.message,warnings:[],issues:[],datachanges:[]}),f=!1,h=m=>{if(f||!c())return{ok:!1};f=!0,this.controller=null;let b={ok:!m.error,value:m.value,result:m,rules:t,isCurrent:c};return i(b),b},p;try{if(t.validate_timeout!=null&&(!Number.isInteger(t.validate_timeout)||t.validate_timeout<=0))throw new TypeError("validate_timeout must be a positive integer in milliseconds.");p=o(e,t,{...r,signal:s.signal})}catch(m){return h(d(m))}return p instanceof Promise?(a(),new Promise(m=>{let b,w=()=>{clearTimeout(b),m({ok:!1})};s.signal.addEventListener("abort",w,{once:!0});let _=y=>{clearTimeout(b),s.signal.removeEventListener("abort",w);try{m(h(y))}catch(x){r.reportError(x,"Validation completion failed"),m({ok:!1})}};t.validate_timeout!=null&&(b=setTimeout(()=>{_(d(new Error("Validation timed out."))),s.abort()},t.validate_timeout)),p.then(_,y=>_(d(y)))})):h(p)}};function xi(n){return typeof n=="string"&&!["null","true","false"].includes(n)&&/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)}function Qt(n,e,t,r){let{group:o,method:i}=n.logicRegistry.resolve(t,e);return i.call(o,e,r)}function Ut(n,e,t,r,o,i=Object.keys(o)){return xi(r)?Qt(n,e,r,o):n.inlineCompiler.compile(e,t,r,i)(o)}function gs(n){let e=n.node,t=n.runtime.gramlot,r=(o,i,a,s=!1)=>s?n.runtime.inlineCompiler.compile(e,o,i,Object.keys(a),`return (${i});`)(a):Ut(n.runtime,e,o,i,a);return{isDecimal:de,invoke:r,callLogic:(o,i)=>Qt(n.runtime,e,o,i),remote:(o,i,a)=>t.rpc.call("data",o,i,{signal:a}),reportError:(o,i)=>{n.closed||n.runtime.reportError(o,i)},validationCurrent:()=>{let o=e.getAttr("value"),i=e.pointerType(o)?e.absDatapath(o):null;return()=>!n.closed&&e.getAttr("value")===o&&(i===null||e.absDatapath(o)===i)},finishValidation:({ok:o,result:i,rules:a})=>{if(n.closed)return;if(o)for(let l of i.datachanges)e.getRelativeData(".").update(l);let s=o?"validate_onAccept":"validate_onReject";if(a[s]){let l=u=>{n.closed||n.runtime.reportError(u,"Validation callback failed")};try{let u=Object.fromEntries(Object.entries(a).map(([d,f])=>[d.slice(9),f])),c=r(s,a[s],{value:i.value,result:i,validations:u,userChange:!0});c instanceof Promise&&c.catch(l)}catch(u){l(u)}}},checkDataPatch:o=>{if(!(o instanceof E))throw new TypeError("Validation data changes must be a Bag.");if(!(e.getRelativeData(".")instanceof E))throw new TypeError("Validation data changes require a Bag datapath.")}}}var Cr=n=>F(L(n)),sn=(n,e)=>L(n)===L(e),ki=n=>n.absDatapath(n.getAttr("value")),gt=n=>encodeURIComponent(n).replaceAll(".","%2E"),Nr=n=>gt(ki(n)),Ap=(n,e)=>gt(n.fullpath)+":"+e,Ti=class{constructor(e,t,r=e.absDatapath(".")){if(this.node=e,this.runtime=t,this.registers=new E,this.validationQueue=new Set,this.fields=new Map,this.validations=new Map,this.disposed=!1,this.scheduled=!1,this.writing=0,this.path=r,this.retainedFields=new Map,this.listeners=new Set,this.navigators=new Set,this.validationSources=new Set,this.validationDependencies=new Map,this.validationRevision=0,this.validatedRevision=-1,this.fullValidation=null,!(this.data instanceof E))throw new TypeError("A form requires a Bag at its datapath.");this.registers.setItem("baseline",Cr(this.data));for(let o of["changes","errors","pending","drafts"])this.registers.setItem(o,new E);this.subscription=t.router.register({path:this.path,recipient:this,subtree:!0}),t.bindingFor(e).track(()=>this.dispose())}rebind(){let e=this.node.absDatapath(".");if(e!==this.path){if(!(this.data instanceof E))throw new TypeError("A form requires a Bag at its datapath.");this.subscription.close();for(let t of["errors","pending","drafts"])this.registers.setItem(t,new E);this.path=e,this.subscription=this.runtime.router.register({path:e,recipient:this,subtree:!0}),this.updateChanges();for(let t of this.fields.values())t.element.cancelValidation(),this.clearDraft(t.node),this.scheduleValidation(t)}}get data(){return this.runtime.gramlot.data.getItem(this.path)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get errorEntries(){return this.registers.getItem("errors").getNodes().map(e=>({path:decodeURIComponent(e.label),message:e.value.getNodes().map(t=>t.value).join(`
|
|
224
|
-
`)}))}get changeEntries(){let e=[];for(let t of this.registers.getItem("changes").getNodes()){let r=t.value,o=[this.path,r.getItem("path")].filter(Boolean).join("."),i=r.getItem("existed"),a=r.getItem("exists"),s=r.getItem("previous"),l=r.getItem("current");if((!i||!a||!sn(s,l))&&e.push({path:o,previous:s,current:l,existed:i,exists:a}),i&&a){let u=r.getItem("previousAttributes"),c=r.getItem("currentAttributes");for(let d of new Set([...u.getNodes(),...c.getNodes()].map(f=>f.label))){let f=u.getNode(d)!==null,h=c.getNode(d)!==null;(f!==h||!sn(u.getItem(d),c.getItem(d)))&&e.push({path:o+"?"+d,previous:u.getItem(d),current:c.getItem(d),existed:f,exists:h})}}}return e}registerNavigator(e){return this.navigators.add(e),()=>this.navigators.delete(e)}focusField(e){if(this.disposed)return!1;for(let t of this.fields.values())if(ki(t.node)===e&&t.element.isConnected)return t.element.control.focus(),!0;for(let t of this.navigators)if(t(e))return!0;return!1}retainField(e){this.retainedFields.set(e,(this.retainedFields.get(e)??0)+1)}releaseField(e){let t=this.retainedFields.get(e);if(t>1){this.retainedFields.set(e,t-1);return}if(this.retainedFields.delete(e),![...this.validations.values()].some(r=>r.path===e)){for(let r of["errors","pending","drafts"]){let o=this.registers.getItem(r),i=gt(e);o.getNode(i)&&o.popNode(i)}this.notify()}}fieldStatus(e){let t=gt(e);return{error:this.registers.getItem("errors").getItem(t),pending:this.registers.getItem("pending").getItem(t),draft:this.registers.getItem("drafts").getItem(t)}}get status(){let e=this.registers.getItem("changes").length>0,t=this.fullValidation!==null||this.registers.getItem("pending").length>0,r=this.registers.getItem("errors").length>0,o=this.registers.getItem("drafts").length>0;return{dirty:e,pending:t,valid:!r&&!o,canSave:e&&!r&&!o&&!t,status:r?"error":t||o?"pending":e?"changed":"ok"}}register(e){let t=e.node;this.fields.set(t,e);let r=this.registerField(t,e.element.constructor);return r.selection=e.element.validationSelection(),this.schedule(()=>{if(this.fields.get(t)!==e)return;let o=this.registers.getItem("drafts").getNode(
|
|
225
|
-
`)),e.element.setFieldState({invalid:!!i,pending:!!this.fieldStatus(r.path).pending})}),()=>{this.fields.delete(t)}}registerField(e,t,r=!0){let o=this.validations.get(e);if(o)return o;if(!t.validationExecutor)throw new TypeError("Grid editors require shared input validation.");let i=this.runtime.bindingFor(e),a=gs(i);return o={node:e,binding:i,context:a,component:t,run:new ho,execute:t.validationExecutor,checkValue:t.validationValueCheck(a),path:ki(e),rules:null,value:void 0,target:null,result:null,selection:null},this.validations.set(e,o),i.editingSession=this,o.release=i.track(()=>this.forgetField(e)),this.refreshField(e,r),o}registerValidationSource(e){return this.validationSources.add(e),this.invalidateValidation(),()=>{this.validationSources.delete(e),this.invalidateValidation()}}invalidateValidation(){if(this.validationRevision++,this.fullValidation)for(let e of this.fullValidation.active)this.cancelValidation(e)}trackValidationDependency(e){if(e===null||this.validationDependencies.has(e))return;let[t,r=null]=e.split("?",2);this.validationDependencies.set(e,this.runtime.router.register({path:t,attr:r,subtree:!0,recipient:{receive:()=>this.invalidateValidation()}}))}clearValidationDependencies(){for(let e of this.validationDependencies.values())e.close();this.validationDependencies.clear()}validate(){if(this.disposed)return Promise.resolve(!1);if(this.fullValidation)return this.fullValidation.promise;for(let a of this.fields.values())Object.hasOwn(a.node,"formDraft")&&a.commit();this.clearValidationDependencies();let e={revision:this.validationRevision,promise:null,active:new Set,failed:!1,complete:!0};this.fullValidation=e,this.notify();let t=this.validationFields(),r=()=>!this.disposed&&!e.failed&&e.revision===this.validationRevision,o=new WeakSet,i=async()=>{let a=0;for(;r();){let s=t.next();if(s.done)return;let{node:l,release:u}=s.value;try{if(o.has(l))continue;o.add(l);for(let[d,f]of l.pointers())d!=="value"&&this.trackValidationDependency((d==="datapath"?l.parentNode:l).absDatapath(f));e.active.add(l),(await this.validateField(l))?.ok||(e.complete=!1)}finally{e.active.delete(l),u()}++a%20===0&&await new Promise(c=>setTimeout(c,0))}};return e.promise=Promise.resolve().then(async()=>{let s=(await Promise.allSettled(Array.from({length:8},()=>i().catch(u=>{e.failed=!0;for(let c of e.active)this.cancelValidation(c);throw u})))).find(u=>u.status==="rejected");if(s)throw s.reason;if(!r())return!1;let l=e.complete&&this.status.valid&&this.registers.getItem("pending").length===0;return l&&(this.validatedRevision=this.validationRevision),l}).finally(()=>{t.return(),this.fullValidation=null,this.notify()}),e.promise}*validationFields(){let e=[...this.validations.keys()];for(let t of this.validationSources)yield*t();for(let t of e)this.validations.has(t)&&(yield{node:t,release:()=>{}})}forgetField(e){let t=this.validations.get(e);if(t){t.run.cancel(),t.release(),t.binding.editingSession===this&&(t.binding.editingSession=null),this.validations.delete(e),this.validationQueue.delete(e);for(let r of["errors","pending"]){let o=this.registers.getItem(r).getItem(gt(t.path));if(o){for(let i of[...o.getNodes()])i.label.startsWith(gt(e.fullpath)+":")&&o.popNode(i.label);o.length||this.registers.getItem(r).popNode(gt(t.path))}}if(![...this.validations.values()].some(r=>r.path===t.path)){let r=this.registers.getItem("drafts");r.getNode(gt(t.path))&&r.popNode(gt(t.path))}delete e.formDraft,this.notify()}}refreshField(e,t=!0){let r=this.validations.get(e);if(!r||this.disposed||this.writing)return;let[,o]=e.rootBuilder.runtimeValues(e),i=r.component.validationParameters(this.runtime.renderer.evaluateExpressions(e,o)),a=Object.fromEntries(Object.entries(i).filter(([f])=>f.startsWith("validate_"))),s=L(Object.fromEntries(Object.entries(i).filter(([f])=>f!=="value"))),l=ki(e),u=this.runtime.gramlot.data.getNode(l.split("?")[0]),c=e.getRelativeData(e.getAttr("value")),d=r.path!==l||r.target!==u||!sn(r.value,c);if(!(!d&&r.configuration===s)){if(r.rules!==null&&this.invalidateValidation(),this.cancelValidation(e),r.path!==l)for(let f of["errors","pending","drafts"]){let h=this.registers.getItem(f);h.getNode(gt(r.path))&&h.popNode(gt(r.path))}Object.assign(r,{path:l,target:u,value:c,rules:a,configuration:s,result:null,selection:r.component.validationSelection(i,r.context)}),d&&this.clearDraft(e),t&&this.scheduleField(e)}}cancelValidation(e){this.validations.get(e)?.run.cancel(),this.validationQueue.delete(e),this.pendingPart(e,"validation",null)}writeCandidate(e,t){this.clearDraft(e),this.writing++;try{this.runtime.renderer.html.writeParameter(e,"value",t)}finally{this.writing--}let r=this.validations.get(e);r&&(r.value=e.getRelativeData(e.getAttr("value")),r.target=this.runtime.gramlot.data.getNode(r.path.split("?")[0]));for(let o of this.validations.keys())o!==e&&this.refreshField(o)}validateCandidate(e,t,r){this.invalidateValidation(),this.cancelValidation(e),this.writeCandidate(e,t);let o=this.validations.get(e);return o.selection=r,this.validateField(e,!1)}scheduleField(e){this.disposed||!this.validations.has(e)||this.validationQueue.has(e)||this.registers.getItem("drafts").getNode(Nr(e))||(this.validationQueue.add(e),this.pendingPart(e,"validation","scheduled"),this.schedule(()=>{this.validationQueue.delete(e)&&this.validateField(e)}))}scheduleValidation(e){this.refreshField(e.node);let t=this.validations.get(e.node);t&&!t.result&&!t.run.controller&&this.scheduleField(e.node)}validateField(e,t=!0){let r=this.validations.get(e);if(!r||this.disposed||r.binding.closed||(this.validationQueue.delete(e),this.registers.getItem("drafts").getNode(Nr(e)))||this.registers.getItem("pending").getItem(Nr(e))?.getItem(Ap(e,"selection")))return;let o=e.getRelativeData(e.getAttr("value")),i=this.fields.get(e);t&&i&&(r.selection=i.element.validationSelection());let a=r.selection,s=r.target,l=r.context.validationCurrent();return r.run.start(o,r.rules,{...r.context,validationCurrent:()=>()=>!this.disposed&&l()&&this.validations.get(e)===r&&this.runtime.gramlot.data.getNode(r.path.split("?")[0])===s,selection:a},r.execute,u=>{if(u.ok)try{r.checkValue(u.value,o)}catch(d){u.ok=!1,u.result.error=d.message}this.result(e,u.result),r.result=u.result,u.ok&&this.writeCandidate(e,u.value);let c=this.fields.get(e);c&&c.element.presentValidation(u.result),r.context.finishValidation(u)},()=>{this.pendingPart(e,"validation","active"),this.fields.get(e)?.element.setFieldState({pending:!0})})}remove(e,t){let r=this.registers.getItem(e),o=Nr(t);r.getNode(o)&&r.popNode(o)}set(e,t,r){r==null?this.remove(e,t):this.registers.getItem(e).setItem(Nr(t),r),this.notify()}draft(e,t){this.invalidateValidation(),this.cancelValidation(e),e.formDraft=t,this.set("drafts",e,t)}clearDraft(e){delete e.formDraft,this.set("drafts",e,null),this.issue(e,"parse",null)}result(e,t){this.pendingPart(e,"validation",null),this.issue(e,"validation",t.error||null)}part(e,t,r,o){r=Ap(t,r);let i=this.registers.getItem(e),a=Nr(t),s=i.getItem(a);!s&&o!=null&&(s=new E,i.setItem(a,s)),s&&(o==null?s.getNode(r)&&s.popNode(r):s.setItem(r,o),s.length||this.remove(e,t)),this.notify()}issue(e,t,r){this.part("errors",e,t,r||null)}pendingPart(e,t,r){this.part("pending",e,t,r)}parseError(e,t){this.issue(e,"parse",t)}schedule(e){queueMicrotask(()=>{this.disposed||e()})}receive(e){if(!this.disposed&&(this.updateChanges(e.path),!this.writing)){this.invalidateValidation();for(let t of this.validations.keys())this.refreshField(t)}}updateChanges(e=null){let t=this.registers.getItem("changes"),r=e===this.path?"":e?.startsWith(this.path+".")?e.slice(this.path.length+1).split("?")[0]:"",o=(l,u,c)=>{if(l&&u&&l.value instanceof E&&u.value instanceof E&&sn(l.attr,u.attr)){let d=new Set([...l.value.getNodes(),...u.value.getNodes()].map(f=>f.label));for(let f of d)o(l.value.getNode(f),u.value.getNode(f),c?c+"."+f:f)}else(!l||!u||!sn([l.value,l.attr],[u.value,u.attr]))&&t.setItem(gt(c),new E({path:c,existed:!!l,exists:!!u,previous:l?Cr(l.value):null,current:u?Cr(u.value):null,previousAttributes:l?Cr(l.attr):null,currentAttributes:u?Cr(u.attr):null}))},i=this.registers.getItem("baseline"),a=r;for(let l of t.getNodes()){let u=l.value.getItem("path");a.startsWith(u+".")&&(a=u)}let s=a;for(;s.includes(".");){s=s.slice(0,s.lastIndexOf("."));let l=i.getNode(s),u=this.data.getNode(s);(!l||!u||!sn(l.attr,u.attr))&&(a=s)}for(let l of[...t.getNodes()]){let u=l.value.getItem("path");(!a||u===a||u.startsWith(a+"."))&&t.popNode(l.label)}a?o(i.getNode(a),this.data.getNode(a),a):o({value:i,attr:{}},{value:this.data,attr:{}},""),this.notify()}notify(){this.disposed||this.scheduled||(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1;let e=this.status,t=this.registers.getItem("status");(!t||!sn(t,new E(e)))&&(this.registers.setItem("status",new E(e)),this.node.publish("formStatus",e));for(let r of this.listeners)r()}))}commitField(e){for(let t of this.fields.values())ki(t.node)===e&&Object.hasOwn(t.node,"formDraft")&&t.commit()}accept(){if(this.disposed)return!1;for(let e of this.fields.values())Object.hasOwn(e.node,"formDraft")&&e.commit();return!this.status.valid||this.status.pending||this.validationSources.size&&this.validatedRevision!==this.validationRevision?!1:(this.registers.setItem("baseline",Cr(this.data)),this.updateChanges(),!0)}load(e){if(!(e instanceof E))throw new TypeError("Editing load requires a Bag.");this.disposed||(this.registers.setItem("baseline",Cr(e)),this.restore())}restore(){if(!this.disposed){this.invalidateValidation();for(let e of this.validations.keys())this.cancelValidation(e);for(let e of this.fields.values())e.element.cancelValidation(),this.clearDraft(e.node),e.element.restoreFormValue(this.registers.getItem("baseline").getItem(e.node.absDatapath(e.node.getAttr("value")).slice(this.path?this.path.length+1:0)));this.runtime.gramlot.data.setItem(this.path,Cr(this.registers.getItem("baseline")));for(let e of["errors","pending","drafts"])this.registers.setItem(e,new E);this.updateChanges();for(let e of this.validations.keys())this.scheduleField(e)}}dispose(){if(!this.disposed){this.disposed=!0,this.subscription.close();for(let e of this.validations.keys())this.forgetField(e);this.fields.clear(),this.validationQueue.clear(),this.retainedFields.clear(),this.listeners.clear(),this.navigators.clear(),this.validationSources.clear(),this.clearValidationDependencies()}}};function Ev(n,e,t=n){let r=new Map,o=new Set,i=new Map;for(let[s,l]of e){if(typeof s!="string")continue;let u=re(l)?.pointer??l;i.set(s,u instanceof fe?u.resolve():n.pointerType(u)?t.getRelativeData(u):mt(u)?null:u)}let a=s=>{if(r.has(s))return r.get(s);if(!e.has(s))throw new Error(`Source attribute '${s}' does not exist`);if(o.has(s))throw new Error(`cyclic attribute dependency: ${[...o,s].join(" -> ")}`);o.add(s);let l=e.get(s),u=re(l),c=u?i.get(s):null,d,f=h=>h?a(h):c;try{if(u)if(u.expression){let h=si(u.body),p=h.slots.map(f);d=n.rootBuilder.evaluatePointerExpression(n,s,l,h,p)}else d=Yr(u.body,f),c==null&&(d=null);else d=i.get(s);return r.set(s,d),d}finally{o.delete(s)}};return{resolve:a}}function Ir(n,e,t=n){let r=new Map([...Object.entries(n.getAttr()),...Le(n.getAttr())]);return Ev(n,r,t).resolve(e)}var xv={dataFormula:["formula","_if","_else","_ask_if","_ask_onCancel"],dataController:["script","_if","_else","_ask_if","_ask_onCancel"],dataRpc:["_ask_if","_ask_onCancel","_if","_else","_onCalling","_onResult","_onError"],dataRemote:["_if","_else","_onCalling"]},Ju=["_cachedRemote","_if","_else","_onRemote","_onCalling","_delay","_timing","_userChanges"],kv=["_if","_else","_onRemote","_onCalling"],Qu=class{#e;#t=null;#r=null;#n=!1;constructor(e){this.#e=e}get inflight(){return this.#t?.view??null}get pending(){let e=this.#r;return e?Object.freeze({method:e.method,get params(){return F(e.text)}}):null}calling(e){if(!e)return!0;let t=!1,r=this.#n;this.#n=!0;try{t=e()!==!1}finally{this.#n=r,!t&&!this.#t&&this.#o()}return t}submit(e,t,r){try{let o=L(t);return this.#t?this.#r?Promise.resolve(void 0):new Promise((i,a)=>{this.#r={method:e,text:o,perform:r,resolve:i,reject:a}}):(this.#r?.resolve(void 0),this.#r=null,this.#i(e,t,o,r))}catch(o){return Promise.reject(o)}}submitSync(e,t){if(this.#t)throw new Error("A synchronous call cannot start while a request of the node is in flight");if(!this.#e.matches(e))throw new TypeError(`Method name must match ${this.#e.pattern}, not ${JSON.stringify(e)}`);return t()}#o(){let e=this.#r;if(!e)return;this.#r=null;let t;try{t=this.#i(e.method,F(e.text),e.text,e.perform)}catch(r){t=Promise.reject(r)}t.then(e.resolve,e.reject)}#i(e,t,r,o){if(!this.#e.matches(e))return Promise.reject(new TypeError(`Method name must match ${this.#e.pattern}, not ${JSON.stringify(e)}`));let i=new AbortController,a={method:e,params:t,text:r,controller:i,ignored:!1};a.view=Object.freeze({method:e,get params(){return F(r)},sentAt:Date.now(),cancel:()=>this.#s(a)}),this.#t=a,i.signal.addEventListener("abort",()=>this.#a(a),{once:!0});let s;try{s=Promise.resolve(o(a))}catch(l){s=Promise.reject(l)}return s.then(()=>this.#a(a),()=>this.#a(a)),s}#a(e){this.#t===e&&(this.#t=null,this.#o())}#s(e){this.#t===e&&(e.ignored=!0,this.#t=null,this.#n||this.#o())}};function Dp(n){return typeof n=="string"&&n.startsWith("==")}var ln=class extends Xe{#e=null;#t=null;get treeStore(){return this.#t}setTreeStore(e){if(this.nodeTag!=="tree")throw new TypeError("setTreeStore requires a tree Source node");if(e!==null&&!(e instanceof E))throw new TypeError("setTreeStore requires a Bag or null");if(e===this.#t)return;this.#t=e;let t=this.rootBuilder.binding,r=t?.bindingFor(this);r&&!r.closed&&(r.rebind(),t.renderer.attached(this)&&t.renderer.project(this))}get formState(){for(let e=this;e;e=e.parentNode){if(e.#e&&e._getMeta("gramlot_component")?.bagStore)return e.#e;if(e.getAttr("formId")!=null||e.getAttr("form")===!0){let t=e.#e??=new Ti(e,this.rootBuilder.binding);return t.rebind(),t}}return null}editCollection(e){let t=this.parentNode?.formState;if(t){if(e!==t.path&&!e.startsWith(t.path+"."))throw new Error("An edited grid in a form must use data within that form.");return t}if(this.#e&&this.#e.path!==e)throw new Error("An active grid editing session cannot change its storepath.");return this.#e??=new Ti(this,this.rootBuilder.binding,e)}get frame(){if(!["dialog","floatingPane"].includes(this.nodeTag))throw new TypeError("frame accessor requires a window");let e=this.value instanceof I?this.value.getNodes():[];if(e.length){if(e.length!==1||e[0].nodeTag!=="framePane")throw new TypeError("A window requires exactly one framePane");return this.builder.wrapSource(e[0])}return this.builder.wrapSource(this.builder.commandOnNode(this,"framePane",null,{node_label:"frame"}))}requestClose(e="application"){if(!["dialog","floatingPane"].includes(this.nodeTag))throw new TypeError("requestClose requires a window");return this.rootBuilder.binding.gramlot.dom.getDomNode(this).requestClose(e)}get grid(){if(this.nodeTag==="framePane"){let e=this.staticValue instanceof I?this.staticValue.getNode("center.grid"):null;if(!e||e.nodeTag!=="grid")throw new TypeError("This frame has no central grid");return this.builder.wrapSource(e)}return(e={})=>this.builder.wrapSource(this.builder.commandOnNode(this,"grid",null,e))}get toolbar(){if(this.nodeTag!=="framePane")throw new TypeError("toolbar accessor requires framePane");let e=this.staticValue instanceof I?this.staticValue.getNode("top.bar"):null;if(!e||e.nodeTag!=="menu")throw new TypeError("This frame has no toolbar");return this.builder.wrapSource(e)}get top(){return this.frameRegion("top")}get bottom(){return this.frameRegion("bottom")}get left(){return this.frameRegion("left")}get right(){return this.frameRegion("right")}get center(){return this.frameRegion("center")}frameRegion(e){if(this.nodeTag!=="framePane")throw new TypeError("Region accessors require framePane");let t=this.value instanceof I?this.value.getNodes().find(o=>o.getAttr("region")===e):null;if(t)return this.builder.wrapSource(t);let r={region:e,node_label:e};return e!=="center"&&Object.assign(r,{display:"flex",flex_direction:["top","bottom"].includes(e)?"column":"row"}),this.builder.wrapSource(this.builder.commandOnNode(this,"contentPane",null,r))}#r=new Set;#n=null;#o=null;get requests(){return this.#o??=new Qu(this.rootBuilder.nameSyntax)}codeAttributes(){let e=[...xv[this.nodeTag]??[],...Object.entries(this.parentNode?._getMeta("gramlot_component")?.childParameters??{}).filter(([,r])=>r.inline).map(([r])=>r),...this._getMeta("gramlot_component")?.command?["action","_ask_if"]:[],...typeof this.getAttr("remote")=="string"?kv:[]],t=[];for(let[r,o]of Object.entries(this.getAttr()??{}))typeof o=="string"&&(e.includes(r)||r==="validate_call"||r==="validate__onResult"||r==="validate_onAccept"||r==="validate_onReject"||/^validate_\w+_if$/.test(r)||r.startsWith("connect_on")||r.startsWith("subscribe_")||r.startsWith("selfsubscribe_"))&&t.push([r,o]);for(let r of["ask","_ask"]){let o=this.getAttr(r);if(o&&typeof o=="object")for(let i of["_if","askIf"])typeof o[i]=="string"&&t.push([`${r}.${i}`,o[i]])}for(let[r,o]of Le(this.getAttr()))if(Dp(o)&&t.push([r,o]),this.nodeTag==="script"&&typeof o=="string"){let i=this.builder.constructor.dialectPrefixes.find(a=>r.startsWith(a))??"";["src","href","xlink:href","xlink_href","_text"].includes(r.slice(i.length).toLowerCase())&&t.push([r,o])}return(Dp(this.staticValue)||this.nodeTag==="script"&&typeof this.staticValue=="string")&&t.push(["",this.staticValue]),t}activateCode(){let e=new Map;for(let[t,r]of this.codeAttributes()){if(this.pointerType(r))throw new Error(`${this.nodeTag} '${this.label}': '${t}' is inline code and cannot be the pointer '${r}'; inline code is never read from Data`);e.set(t,r)}for(let[t,r]of[...Le(this.getAttr()),["datapath",this.getAttr("datapath")]])re(r)?.expression&&e.set(t,r);this.#n=e}activatedCode(e){return this.#n?.get(e)??null}remote(e,t={}){let r=this.rootBuilder.nameSyntax;if(typeof e!="string"||!(this.pointerType(e)||r.matches(e)))throw new TypeError(`${this.nodeTag} '${this.label}': remote name must be a pointer or match ${r.pattern}, not ${JSON.stringify(e)}`);let o=Object.keys(t).find(a=>a.startsWith("_")&&!Ju.includes(a));if(o)throw new TypeError(`${this.nodeTag} '${this.label}': remote parameter '${o}' is not accepted; the control attributes are ${Ju.join(", ")}`);let i={remote:e};for(let[a,s]of Object.entries(t))i[Ju.includes(a)?a:`remote_${a}`]=s;return this.setAttr(i),fi(this)}publish(e,t={}){return this.rootBuilder.binding.subscriptions.publishNode(this,e,t)}pointers(){let e=this.getAttr("datapath"),t=re(e)?Ft(this,e):new Set,r=super.pointers().filter(([o,i])=>!(this.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(o))&&!t.has(o)&&!this.#s(o,i)).map(([o,i])=>[o,re(i)?.pointer??i]);for(let o of t){let i=this.getAttr(o);this.pointerType(i)==="^"&&r.push(["datapath",re(i)?.pointer??i])}return r}runtimeToEvaluate(){let e=super.runtimeToEvaluate();for(let[t,r]of e){if(this.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(t)){e.set(t,new Er(()=>r));continue}if(this.pointerType(r)){if(re(r)){if(typeof t!="string")throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);this.absDatapath(r)===null&&e.set(t,new Er(()=>Ir(this,t)));continue}this.#s(t,r)?e.set(t,r.slice(1)):this.absDatapath(r)===null&&e.set(t,null)}}return e}pathAttribute(e){let t=this.getAttr(e);return re(t)?Ir(this,e):this.pointerType(t)&&this.#s(e,t)?t.slice(1):t}getRelativeData(e,t=null,r={}){return this.absDatapath(e)===null?null:super.getRelativeData(e,t,r)}setRelativeData(e,t,r={}){this.#l(e),super.setRelativeData(e,t,r)}PUT(e,t){this.#l(e),this.data.setItem(this.absDatapath(e),t,null,">",!1,!0,this,!1,!1)}FIRE(e,t=!0,r=null){t===null&&(t=!0),this.#l(e);let o=this.absDatapath(e);if(o.includes("?")){this.#i(o,t);return}this.data.getNode(o)?.setValue(null,!1);try{this.fireEvent(e,t,{attributes:r})}finally{this.data.getNode(o)?.setValue(null,!1)}}#i(e,t){let[r,o]=e.split("?",2),i=this.data;i.getNode(r)?.setAttr({[o]:null},!1);try{let a=i.getNode(r);a?a.setValue(a.staticValue,!0,{[o]:t},!0,!0,!0,!0):i.setItem(r,null,{[o]:t},">",!0,!0,!0,!0)}finally{i.getNode(r)?.setAttr({[o]:null},!1)}}FIRE_AFTER(e,t=!0,r=10){this.#l(e);let o=this.rootBuilder?.binding?.bindingFor(this)??null,i=null,a=setTimeout(()=>{i?.(),this.FIRE(e,t)},r);return i=o?.track(()=>clearTimeout(a))??null,()=>{clearTimeout(a),i?.()}}absDatapath(e){e=re(e)?.pointer??e;let t=this.pointerType(e)?e.slice(1):e;if(t.startsWith("#")&&t.includes("?")){let[r,o]=t.split("?",2),i=super.absDatapath(r);return i===null?null:`${i}?${o}`}return super.absDatapath(e)}_composeRelativeDatapath(e,t){let r=this;for(;r!==null&&e.startsWith(".");){let o=r.getAttr("datapath");if(this.pointerType(o)&&(o=this.#a(r,o),o===null))return null;if(o!=null&&(e=e==="."?o:o+e),e.startsWith("#"))return r.parentNode._resolveSymbolicDatapath(e,t);r=r.parentNode}if(e.startsWith("."))throw new Error(`unresolved relative datapath: ${t}`);return e}_finalizeAbsPath(e,t){return e===null?null:super._finalizeAbsPath(e,t)}_resolveSymbolicDatapath(e,t){let r=e.slice(1).split(".",1)[0];if(r==="FORM"||r==="ANCHOR")return super._resolveSymbolicDatapath(e,t);let o=this.rootBuilder?.binding;if(!o)return super._resolveSymbolicDatapath(e,t);let i=o.nodeIds.get(r);if(!i)throw new Error(`#<id>: cannot resolve ${t}`);let a=e.slice(r.length+2);return i.absDatapath(a?`.${a}`:".")}#a(e,t){if(re(t)){let i=Ir(e,"datapath",e.parentNode);return i==null||i===""?null:i}let r=e.parentNode.absDatapath(t);if(r===null)return null;let o=this.data.getItem(r);return o==null||o===""?null:o}#s(e,t){return re(t)||typeof e!="string"||!e.endsWith("_path")?!1:(this.#r.has(e)||(this.#r.add(e),console.warn(`${this.nodeTag} '${this.label}': '${e}' holds a bare Data path; the pointer symbol of '${t}' is removed`)),!0)}#l(e){if(this.absDatapath(e)===null)throw new Error(`${this.nodeTag} '${this.label}': write on a null path: '${e}'`)}},Ae=class n extends I{get nodeClass(){return ln}authorizedCopy(e){let t=new this.constructor;for(let r of this.getNodes()){let o=r.getAttr("auth")??null;if(o!==null){if(typeof o!="string")throw new TypeError(`${r.nodeTag} '${r.label}': 'auth' must be a string rule, not ${typeof o}`);if(e(o)!==null)continue}let i=r.staticValue;i instanceof n&&(i=i.authorizedCopy(e));let{auth:a,...s}=r.getAttr(),l=t.setItem(r.label,i,s,">",!1,!1,null,!1,!0,null,r.nodeTag);l.xmlTag=r.xmlTag}return t}activateCode(){for(let e of this.getNodes())e.activateCode(),e.staticValue instanceof n&&e.staticValue.activateCode();return this}};if((pt(Ae.tytxSuffix).GramlotBuilderBag??Ae)!==Ae)throw new Error("TYTX subtype name 'GramlotBuilderBag' is already registered for another class");Wr(Ae.tytxSuffix,{...pt(Ae.tytxSuffix),GramlotBuilderBag:Ae});var Tv=new Set(["animate","animateMotion","animateTransform","circle","ellipse","feBlend","feColorMatrix","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feGaussianBlur","feImage","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","image","line","metadata","path","polygon","polyline","rect","set","stop","use"]),Ai=class extends rn{constructor(e,t){super(e),this._owner=t}get owner(){return this._owner}_handleMeta(e,t){let r=this.owner.evaluateExpressions(e,t);co(e,r);let[o,i]=super._handleMeta(e,r);return uo(e,i),e._getMeta("subbuilder")?[o,ns(hs(i))]:[o,i]}adaptAttrs(e){let{_meta:t,...r}=e;return yi(super.adaptAttrs(fo(Sr(r))))}renderedItem(e,t,r,o={}){if(this.owner.renderType==="object")return this.owner.renderedItem(e,t,r,o);let{_text:i,...a}=r;return t=this.owner.expressionValue(e,t),Array.isArray(t)&&i!=null&&(t=[this._escapeText(lo(i)),...t]),Tv.has(o.tag)?`${o.pretty?" ".repeat(this._nodeDepth(e,o.depthOffset??0)):""}<${o.tag}${this._formatAttrs(a)} />${o.pretty?`
|
|
226
|
-
`:""}`:super.renderedItem(e,t,a,o)}};var un=class extends tn{#e=new WeakMap;#t=new WeakMap;get inlineCompiler(){return null}getRender(e){return this.renders.has(e)||(e instanceof qt?this.addRender(e,this):e instanceof kr&&this.addRender(e,new Ai(e,this))),super.getRender(e)}render(e,t={}){if(e._getMeta("data_element"))return null;let[r,o]=e.rootBuilder.runtimeValues(e),i=this.getRender(e.builder),[a,s]=i._handleMeta(e,o);return e._getMeta("subbuilder")||(s=i.adaptAttrs(s)),i.renderedItem(e,e.value instanceof I?this.renderChildren(e.value,t):r,s,{tag:a,...t})}_handleMeta(e,t){let r=this.builder.constructor.dialectPrefixes,o=this.evaluateExpressions(e,t);co(e,o,r);let[i,a]=super._handleMeta(e,Ep(e,o,r));if(uo(e,a,r),e.nodeTag==="webcomponent"){i=Jt(e.getAttr());let{code:u,...c}=a;a=c}if(e._getMeta("subbuilder")){let u=hs(a);return e._getMeta("subbuilder")==="html"&&(u.xmlns=Dr),[i,u]}let[s,l]=xp(i,a);return Object.keys(l).length&&this.#e.set(e,l),[i,s]}evaluateExpressions(e,t){let r=this.inlineCompiler,o=(a,s)=>r?r.compileExpression(e,a,s)(t):null,i={...t};for(let[a,s]of Le(e.getAttr()))e.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(a)||mt(s)&&Object.hasOwn(i,a)&&(i[a]=o(a,s));return mt(e.value)&&this.#t.set(e,o("",e.value)),i}expressionValue(e,t){return mt(e.value)?this.#t.get(e)??null:t}restoreNativeAttributes(e,t){let r=this.#e.get(e);return r?(this.#e.delete(e),{...t,...fo(r)}):t}adaptAttrs(e){let{_meta:t,...r}=e,o=`${this.builder.constructor._name}_`,i=this.builder.constructor.dialectPrefixes,a={},s={};for(let[l,u]of Object.entries(Sr(r))){if(u==null)continue;if(l.startsWith(o))throw new Error(`${l}: the attribute prefix '${o}' is not accepted; use the prefix '${i[0]}'`);let c=i.find(d=>l.startsWith(d));c?a[l.slice(c.length)]=u:s[l]=u}return yi({...super.adaptAttrs(s),...a})}renderedItem(e,t,r,o={}){let i;[t,i]=vi(this.expressionValue(e,t),this.restoreNativeAttributes(e,r));let{_text:a,...s}=i;Array.isArray(t)&&a!=null&&(t=[this._escapeText(lo(a)),...t]);let l=e.parentNode?._getMeta("subbuilder")==="html"?{xmlns:Fe,...s}:s;return super.renderedItem(e,t,l,o)}finalize(e,t=null,r={}){if(!r.doctype)return super.finalize(e,t,r);let o=this._composeStringFragments(e),i=this.builder.source.getNodes().filter(a=>!a._getMeta("data_element"));return i.length===1&&i[0].nodeTag==="html"||(o=`<html>${o}</html>`),super.finalize(`<!doctype html>${o}`,t,r)}};var Sp={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"binding",version:null,title:"Gramlot binding",description:"Gramlot Data declarations and the plain HTML button; loaded after the HTML grammar."},abstracts:{},elements:{dataBinder:{doc:"Bidirectional subscription between a client Data branch and its page's server store.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"server_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataSetter:{doc:"Initial Data value, written literally at destination_path.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!0,default:null},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:"Computed Data value written at result_path; formula is inline, func is a name.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"result_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"formula",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:"Side effects on Data; script is inline, func is a name.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"script",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataRpc:{doc:"Server endpoint called through gramlot.rpc; the value is written at result_path when given.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"method",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"result_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"timeout",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"int"},{kind:"type",module:"builtins",name:"float"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataRemote:{doc:"Data node resolved by a server endpoint through gramlot.rpc, on first read and again when cacheTime expires; with sync (default) the read waits for the answer when the transport supports it.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"method",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"cacheTime",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"int"},{kind:"type",module:"builtins",name:"float"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"sync",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"bool"},has_default:!0,default:!0},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},html_button:{doc:"Plain native HTML button without Gramlot click mechanisms.",sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{render_tag:"button"}},html_dialog:{doc:"Native HTML dialog, distinct from the layout window component.",sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{render_tag:"dialog"}}}};var Cp={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"webcomponent",version:null,title:"Gramlot webcomponent",description:"An explicitly loaded autonomous custom element."},abstracts:{},elements:{webcomponent:{doc:"Create the custom-element tag named by literal code.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"code",kind:"keyword_only",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null}}};var Sv="data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element",Cv=new Set,Nv=new Set(["serverpath","dbenv","shared_id"]),Iv=["formsubscribe_"],Ov={dataSetter:"destination_path",dataFormula:"result_path",dataRpc:"result_path",dataRemote:"destination_path"},Rv={dataFormula:"formula",dataController:"script"};function Np(n,e){if(["input","textarea","select","webcomponent"].includes(n)&&re(e.value))return"'value' does not accept pointer suffixes; use an ordinary value pointer";if(n==="html_button"&&Object.keys(e).some(o=>["action","ask","_delay","fire"].includes(o)||o.startsWith("fire_")))return"plain HTML button: use button for action, ask, fire or _delay";if(Object.hasOwn(e,"ask")&&!["button","toggleButton","dropDownButton","menuline"].includes(n))return"'ask' is supported on buttons";if(Object.hasOwn(e,"_ask")&&!["dataController","dataFormula","dataRpc"].includes(n))return"'_ask' requires a controller, formula or RPC";if(["dataSetter","dataRemote"].includes(n)&&Object.keys(e).some(o=>o.startsWith("subscribe_")||o.startsWith("selfsubscribe_")))return"topic subscriptions are supported on controllers, formulas, RPCs and rendered elements";let t=Ov[n];if(t&&String(e[t]??"").includes("?"))return`'${t}' does not accept '?attr': '${e[t]}'`;let r=Rv[n];return r&&e[r]!=null&&e.func!=null?`'func' and '${r}' cannot be declared on the same node`:r&&e._if!=null&&e.func!=null?"'_if' is inline and cannot be declared with 'func': write the condition in the method":null}function Ip(n){return Object.keys(n).find(e=>Nv.has(e)||Iv.some(t=>e.startsWith(t)))}var Oe=class n extends qt{static _name="gramlot";static containers=["frameGrid"];static _sourceClass=Ae;static{this.defineGrammar(Sp)}static{this.defineGrammar(Cp)}static{this.defineGrammar(ms.toDocument())}frameGrid(e,{storepath:t,rowMode:r,structpath:o,searchOn:i=!1,searchHelp:a=!1,chart:s=!1,...l}={}){for(let h of["framePane","grid"])if(!this.schemaTag(h))throw new TypeError(`frameGrid requires the ${h} collection`);let u={};for(let h of Object.keys(l))h.startsWith("chart_")&&(u[h.slice(6)]=l[h],delete l[h]);if(s!==!1){if(s!==!0&&(typeof s!="string"||!s))throw new TypeError("chart requires a boolean or chart type");if(!l.datapath)throw new TypeError("A chart frameGrid requires its own datapath");if(!this.schemaTag("chartPane"))throw new TypeError("frameGrid requires the chartPane collection");typeof s=="string"&&(u.chartType=s)}else if(Object.keys(u).length)throw new TypeError("chart_* options require chart");let c={storepath:t,rowMode:r,...o==null?{}:{structpath:o},node_label:"grid",frameTarget:!0,height:"100%",width:"100%"};s!==!1&&(c.nodeId=K()),this.validateNodeValues("grid",null,c),i!==!1&&this.validateNodeValues("searchBox",null,{searchOn:i,searchHelp:a});let d=e.framePane(l);d.center.grid(c);let f=d.top.menu({presentation:"bar",node_label:"bar",aria_label:"Grid toolbar",class:"gramlot-grid-toolbar"});return i!==!1&&f.menuline({group:!0,node_label:"search",class:"gramlot-grid-search"}).searchBox({searchOn:i,searchHelp:a}),s!==!1&&(f.menuline({caption:"Chart",icon:"\u25A5",labelPosition:"tooltip",node_label:"chart",action:"this.SET('._chart.open',true)"}),d.center.floatingPane({title:"Chart",open:"^._chart.open",width:"820px",height:"560px",movable:!0,resizable:!0,maximizable:!0,node_label:"chartWindow"}).frame.center.chartPane({storepath:t,rowMode:r,gridId:c.nodeId,configpath:"._chart",configDefaults:new E(u),height:"100%"})),d}static get dialectPrefixes(){let e=[];for(let t=Object.getPrototypeOf(n);t&&t!==Function.prototype;t=Object.getPrototypeOf(t))Object.hasOwn(t,"_name")&&t._name&&e.push(`${t._name}_`);return e}constructor(e=null,{collections:t=[],auth:r=null,nameSyntax:o=_i}={}){if(!(o instanceof on))throw new TypeError(`nameSyntax must be a NameSyntax, not ${o}`);super(e),this._binding=null,this._auth=r,this._nameSyntax=o;for(let i of t)this.loadCollection(i)}get auth(){return this._auth}get nameSyntax(){return this._nameSyntax}get binding(){return this._binding}set binding(e){this._binding=e}evaluatePointerExpression(e,t,r,o,i){return this.binding?this.binding.inlineCompiler.compilePointerExpression(e,t,r,o.text)(i):null}nodeById(e){if(!this.binding)return super.nodeById(e);let t=this.binding.nodeIds.get(e);if(!t)throw new Error(`nodeId not found: ${e}`);return t.builder.wrapSource(t)}loadCollection(e){return this.loadGrammar(e instanceof Tr?e.toDocument():e),this}schemaTag(e){let t=e.toLowerCase(),r=n.dialectPrefixes;if(t.startsWith(`${n._name}_`))throw new Error(`${e}: the tag prefix '${n._name}_' is not accepted; use the prefix '${r[0]}'`);if(Cv.has(t))throw new Error(`${e}: excluded from Gramlot`);let o=this.schemaTagNames[t];if(o)return o;for(let i of r)if(t.startsWith(i)&&this.schemaTagNames[t.slice(i.length)])return t;return null}bagCall(e,t,r,o){return t=this.#e(t),[r,o]=this.menuArguments(t,r,o),super.bagCall(e,t,r,o)}commandOnNode(e,t,r,o){return t=this.#e(t),[r,o]=this.menuArguments(t,r,o),super.commandOnNode(e,t,r,o)}menuArguments(e,t,r={}){if(e==="menu"&&t==null)return[new Ae(null,this),r];if(e==="menuline"&&t!=null&&t!=="-"){if(Object.hasOwn(r,"command"))throw new TypeError("menuline command must be declared once");return[null,{...r,command:t}]}return[t,r]}validateNodeValues(e,t,r={}){if(this.schema[e]?._meta?.gramlot_component&&re(r.value))throw new Error("'value' does not accept pointer suffixes");e==="webcomponent"&&Jt(r);let o=Ip(r);if(o)throw new Error(`${e}: attribute '${o}' is excluded from Gramlot`);let i=Np(e,r);if(i)throw new Error(`${e}: ${i}`);return super.validateNodeValues(e,t,r)}validateNode(e,t={}){if(e._getMeta("gramlot_component")&&re((t.attrs??e.getAttr()).value))throw new Error("'value' does not accept pointer suffixes");e.nodeTag==="webcomponent"&&Jt(t.attrs??e.getAttr());let r=Ip(t.attrs??e.getAttr());if(r)throw new Error(`${e.nodeTag} '${e.label}': attribute '${r}' is excluded from Gramlot`);let o=Np(e.nodeTag,t.attrs??e.getAttr());if(o)throw new Error(`${e.nodeTag} '${e.label}': ${o}`);return super.validateNode(e,t)}_validateChildren(e,t,r,o){return super._validateChildren(e,t,r.map(i=>i==="html_button"?"button":i==="html_dialog"?"dialog":i),o)}_countsForGrammar(e){return e===this.schema.button||!e?._meta?.gramlot_component&&e!==this.schema.webcomponent&&super._countsForGrammar(e)}setChild(e,t,r,o,i=null){o=Object.fromEntries(Object.entries(o??{}).map(([l,u])=>[l,ie(u)instanceof Xe?this.reference(u):u]));let s=t==="dataSetter"&&o?.value!==null&&typeof o?.value=="object"&&Object.getPrototypeOf(o.value)===Object.prototype?{...o,value:new E(o.value)}:o;return super.setChild(e,t,r,s,i)}#e(e){if(e==="data")throw new Error(Sv);if(this.schemaTagNames[e.toLowerCase()]===e)return e;let t=n.dialectPrefixes.find(r=>e.startsWith(r));return this.schemaTagNames[e.slice(t.length)]}get renderer_html(){return new un(this)}create(){this.setup(this.data),this.main(this.root)}computeLogic(){}promoteNodeValue(e,t,r){let o=t!=null?{_text:t}:null;e.setValue(r,!0,o,!0)}reference(e,t="node"){if(e=ie(e),!(e instanceof Xe)||!["node","dom"].includes(t))throw new TypeError("Reference requires an element and node/dom kind");let r=e.getAttr("__ref");return r==null&&(r=K(),e.setAttr({__ref:r})),{$gramlotRef:r,kind:t}}toTytx(){return L(this.auth===null?this.source:this.source.authorizedCopy(this.auth))}};function ec(n){for(let e=n.parentNode;e;e=e.parentNode)if(e.nodeTag==="framePane")return e;return null}function bs(n){if(!n||!(n.value instanceof I))return null;let e=n.value.getNodes().find(o=>o.getAttr("region")==="center"),t=[];function r(o){if(o.nodeTag!=="framePane"&&(o.getAttr("frameTarget")===!0&&t.push(o),o.value instanceof I))for(let i of o.value.getNodes())r(i)}return e&&r(e),t.length===1?t[0]:null}function Bv(n){if(n.closed||!n.runtime.renderer.attached(n.node))return!1;for(let e=n.node;e;e=e.parentNode){let[,t]=e.rootBuilder.runtimeValues(e);if(t.hidden===!0||t.disabled===!0)return!1}return!0}function Op(n){if(n&&typeof n=="object"){for(let e of Object.values(n))Op(e);Object.freeze(n)}return n}function Rp(n,e){let t=n.node,r=t.getAttr("command"),o=n.runtime.gramlot.commands.get(r),i=ec(t),a=bs(i);if(!o||!a)return console.warn(`Cannot dispatch command '${r}' at '${t.label}': missing or duplicate frame recipient`),null;let s=t.getAttr("parameters")??{};if(typeof s!="object"||Array.isArray(s))throw new TypeError("Command parameters require a mapping");let l=Object.fromEntries(Object.entries(s).map(([m,b])=>[m,t.pointerType(b)?t.getRelativeData(b):b])),u=Op(F(L(l))),c=Object.freeze(Object.fromEntries(["shift","ctrl","alt","meta"].map(m=>[m,!!e[`${m}Key`]]))),d=Object.freeze({sender:t,target:a,command:r,parameters:u,modifiers:c}),f=!1,h=n.runtime.bindingFor(a).track(()=>{f=!0}),p=()=>!f&&Bv(n)&&bs(i)===a&&n.runtime.renderer.attached(a)&&t.getAttr("command")===r;return{message:d,current:p,release:h,cancel(){f=!0},deliver(){p()&&a.publish(o.publish,d)}}}var $v=new Set(["input","select","textarea"]),Mv=["type","multiple"];function Bp(n,e){let t=n.node,r=t.getAttr(e);return t.pointerType(r)?t.getRelativeData(r):n.resolved[e]}var je=class n{static liveWrites=!1;static writesDefault=!0;static preservesUnchangedValue=!1;#e;#t=!1;#r;#n;#o=!1;#i=!1;#a=!1;static for(e,t){let r=n.classFor(t.element,t.attrs);return r?new r(e,t):null}static classFor(e,t){if(e.namespaceURI!==Fe)return null;if(e.constructor.gramlotComponent)return e.constructor.gramlotComponent.parameters.value?.binding!=="twoWay"?null:e.control.type==="radio"?ic:tc;if(e.localName==="textarea")return Vt;if(e.localName==="select")return Di;if(e.localName!=="input")return null;let r=t.type==null?"text":String(t.type).toLowerCase();return Object.hasOwn($p,r)?$p[r]:Vt}static shape(e,t){return e?.constructor.gramlotComponent?.parameters.value?.binding==="twoWay"&&e.control.type==="radio"?JSON.stringify([]):e?.namespaceURI!==Fe||!$v.has(e.localName)?null:JSON.stringify(Mv.filter(r=>(r!=="type"||e.localName!=="input")&&(r!=="multiple"||!["input","select"].includes(e.localName))).map(r=>t[r]??null))}constructor(e,t){this.#r=e,this.#n=t}get binding(){return this.#r}get element(){return this.#n.element}get node(){return this.binding.node}get eventElement(){return this.element}get resolved(){return this.#n.resolved}get live(){return!!this.resolved.live}get writeEvent(){return this.constructor.liveWrites&&this.live?"input":"change"}project(e,t){if(this.#i){this.#a=!0;return}this.constructor.preservesUnchangedValue&&this.#t&&this.same(this.#e,e)&&(!this.#o||this.same(this.read(),e))||(this.#e=e,this.#t=!0,!(this.#o&&this.same(this.read(),e))&&(this.constructor.writesDefault&&!this.node.pointerType(this.node.getAttr("value"))&&this.writeDefault(e),this.write(e)))}read(){return this.element.value}write(e){let t=e==null?"":String(e);this.element.value!==t&&(this.element.value=t)}writeDefault(e){let t=e==null?"":String(e);this.element.localName==="textarea"?this.#n.text.data!==t&&(this.#n.text.data=t):this.element.defaultValue!==t&&(this.element.defaultValue=t)}same(e,t){return Object.is(e,t)}commit(e,t=this.read()){if(!this.binding.closed){this.#o=!0;try{this.binding.runtime.renderer.html.writeParameter(this.node,"value",t)}finally{this.#o=!1}}}attach(){for(let e of["input","change","compositionstart","compositionend"])this.eventElement.addEventListener(e,this)}detach(){for(let e of["input","change","compositionstart","compositionend"])this.eventElement.removeEventListener(e,this);this.#a=!1}refresh(){}handleEvent(e){if(!this.binding.closed){if(e.type==="compositionstart"){this.#i=!0;return}if(e.type==="compositionend"){this.#i=!1,this.writeEvent==="input"&&this.commit(e),this.#a&&(this.#a=!1,this.binding.runtime.renderer.project(this.node));return}this.#i||e.isComposing||e.type===this.writeEvent&&this.commit(e)}}},tc=class extends je{#e;form=null;static writesDefault=!1;static preservesUnchangedValue=!0;get eventElement(){return this.element.control}attach(){this.form=this.element.supportsFormValidation&&this.node.pointerType(this.node.getAttr("value"))==="^"?this.node.formState:null,this.element.setPageContext(sc(this)),this.form&&this.node.pointerType(this.node.getAttr("value"))==="^"&&(this.#e=this.form.register(this)),super.attach()}refresh(){let e=this.element.supportsFormValidation&&this.node.pointerType(this.node.getAttr("value"))==="^"?this.node.formState:null;e!==this.form&&(this.#e?.(),this.form=e,this.element.setPageContext(sc(this)),this.#e=e?e.register(this):null)}project(e,t){this.element.shouldProjectControlValue(e)&&super.project(e,t)}same(e,t){return this.element.sameControlValue(e,t)}detach(){this.element.releaseControl(),this.#e?.(),super.detach()}commit(e){if(this.binding.closed||this.element.control.disabled||this.element.control.readOnly)return;let t=this.element.acceptControlValue();this.form||Mp(this.element,t,r=>super.commit(e,r.value))}get writeEvent(){return this.element.commitOnChange?"change":(this.resolved.live??this.element.parameters.live)&&this.element.liveWrites?"input":"change"}read(){return this.element.readControlValue()}write(e){this.element.writeControlValue(e)}handleEvent(e){if(e.type==="input"&&this.form&&!this.binding.closed&&!this.element.control.disabled&&!this.element.control.readOnly&&this.form.draft(this.node,this.element.control.value??""),super.handleEvent(e),!e.composed&&!this.binding.closed&&["input","change"].includes(e.type)){let t=this.element.ownerDocument.defaultView.Event;this.element.dispatchEvent(new t(e.type,{bubbles:!0,composed:!0}))}}},Vt=class extends je{static liveWrites=!0},rc=class extends je{static liveWrites=!0;read(){return this.element.value===""?null:Number(this.element.value)}commit(e){this.element.validity.badInput||super.commit(e)}},nc=class extends je{static liveWrites=!0;read(){return Number(this.element.value)}},Di=class extends je{static writesDefault=!1;read(){return this.element.multiple?[...this.element.selectedOptions].map(e=>e.value):this.element.selectedIndex===-1?null:this.element.value}write(e){let t=this.element;if(t.multiple){if(e!=null&&!Array.isArray(e))throw new TypeError(`${this.node.nodeTag} '${this.node.label}': a multiple select requires an array`);let r=new Set((e??[]).map(String));for(let o of t.options){let i=r.has(o.value);o.selected!==i&&(o.selected=i)}}else e==null?t.selectedIndex!==-1&&(t.selectedIndex=-1):(t.selectedIndex===-1||t.value!==String(e))&&(t.value=String(e))}same(e,t){return Array.isArray(e)?Array.isArray(t)&&t.length===e.length&&t.every((r,o)=>Object.is(r,e[o])):super.same(e,t)}},cn=class extends je{read(){return this.element.value===""?null:this.element.value}},oc=class extends je{},ws=class extends je{static writesDefault=!1;read(){return this.element.checked}write(e){let t=!!e;this.element.checked!==t&&(this.element.checked=t)}same(e,t){return e===!!t}attach(){let e=this.node;if(e.getAttr("checked")!=null&&e.pointerType(e.getAttr("value"))==="^")throw new TypeError(`${e.nodeTag} '${e.label}': checked and a ^ value are two sources`);super.attach()}},po=class extends ws{#e=null;#t=!1;get groups(){return this.binding.runtime.renderer.radioGroups}attach(){let e=this.node,t=this.resolved.group??null,r=ac(e);if(t!=null){if(e.getAttr("name")!=null)throw new TypeError(`${e.nodeTag} '${e.label}': name and group are two names`);this.#r(t,r)}super.attach(),t!=null&&(this.#e=this.groups.join(this,t,r),this.element.setAttribute("name",this.#e))}detach(){this.#e!==null&&(this.groups.leave(this),this.element.removeAttribute("name"),this.#e=null),super.detach()}refresh(e=this.resolved.group){let t=this.resolved.group??null,r=ac(this.node);if(!Object.is(e??null,t)){let o=new Set([this,...this.groups.peers(this),...t===null?[]:this.groups.peersOf(t,r)]);this.groups.leave(this),this.#e=t===null?null:this.groups.join(this,t,r),this.#e===null?this.element.removeAttribute("name"):this.element.setAttribute("name",this.#e);for(let i of o){if(this.binding.closed||!this.binding.runtime.renderer.attached(this.node))return;i.binding.closed||!i.binding.runtime.renderer.attached(i.node)||i.binding.runtime.renderer.html.writeParameter(i.node,"value",!1)}return}this.#e!==null&&this.groups.nameOf(t,r)!==this.#e&&(this.#r(t,r),this.groups.leave(this),this.#e=this.groups.join(this,t,r),this.element.setAttribute("name",this.#e))}#r(e,t){let r=this.node;if(Bp(this,"value")&&this.groups.peersOf(e,t).some(o=>!o.binding.closed&&o.read()))throw new Error(`${r.nodeTag} '${r.label}': several true values in radio group '${e}'`)}project(e,t){let r=!this.#t;this.#t=!0;let o=this.read();super.project(e,t),!r&&!o&&this.read()&&this.turnOffPeers()}commit(e){let t=this.read();super.commit(e),t&&!this.binding.closed&&this.turnOffPeers()}turnOffPeers(){if(this.#e!==null)for(let e of this.groups.peers(this)){if(this.binding.closed)return;e.binding.closed||(e.element.checked&&(e.element.checked=!1),Bp(e,"value")&&e.commit(null))}}},ic=class extends po{static writesDefault=!1;get host(){return super.element}get element(){return this.host.control}project(e,t){this.host.shouldProjectControlValue(e)&&super.project(e,t)}commit(e){this.binding.closed||this.element.disabled||this.element.readOnly||Mp(this.host,this.host.acceptControlValue(),()=>super.commit(e))}read(){return this.host.readControlValue()}write(e){this.host.writeControlValue(e)}attach(){this.host.setPageContext(sc(this)),super.attach(),this.element.addEventListener("keydown",this)}detach(){this.host.releaseControl(),this.element.removeEventListener("keydown",this),super.detach()}handleEvent(e){if(!this.binding.closed){if(e.type==="keydown"){if(this.resolved.group==null||!["ArrowLeft","ArrowUp","ArrowRight","ArrowDown"].includes(e.key))return;let t=this.groups.peersOf(this.resolved.group,ac(this.node)).filter(a=>!a.binding.closed&&!a.element.disabled),r=t.indexOf(this);if(r<0)return;e.preventDefault();let o=["ArrowLeft","ArrowUp"].includes(e.key)?-1:1,i=t[(r+o+t.length)%t.length];i.element.focus(),i.element.click();return}if(super.handleEvent(e),!e.composed&&!this.binding.closed&&["input","change"].includes(e.type)){let t=this.host.ownerDocument.defaultView.Event;this.host.dispatchEvent(new t(e.type,{bubbles:!0,composed:!0}))}}}},_s=class{#e;#t=new Map;#r=new Map;#n=new WeakMap;#o=0;constructor(e){this.#e=e}join(e,t,r){let o=this.nameOf(t,r);return this.#t.has(o)||this.#t.set(o,new Set),this.#t.get(o).add(e),this.#r.set(e,o),o}leave(e){let t=this.#r.get(e);this.#r.delete(e);let r=this.#t.get(t);r?.delete(e),r?.size===0&&this.#t.delete(t)}peers(e){let t=this.#r.get(e);return[...this.#t.get(t)??[]].filter(r=>r!==e)}peersOf(e,t){return[...this.#t.get(this.nameOf(e,t))??[]]}nameOf(e,t){t!==null&&!this.#n.has(t)&&this.#n.set(t,this.#o++);let r=t===null?"page":`form${this.#n.get(t)}`;return`gramlot-${this.#e.instanceId}-${r}-${e}`}};function ac(n){for(let e=n;e;e=e.parentNode){let t=e.getAttr()??{};if(t.formId!=null||t.form===!0)return e}return null}var $p={text:Vt,password:Vt,email:Vt,url:Vt,tel:Vt,search:Vt,number:rc,range:nc,color:oc,date:cn,time:cn,month:cn,week:cn,"datetime-local":cn,checkbox:ws,radio:po,hidden:null,file:null,button:null,submit:null,reset:null,image:null};function sc(n){let{binding:e,node:t}=n,r=e.runtime.gramlot;return{locale:r.locale,timeZone:r.timeZone,createDecimal:Lt,isDecimal:de,getDecimalLibrary:$u,form:n.form,formCancelValidation:()=>n.form?.cancelValidation(t),formValidateCandidate:(o,i)=>n.form.validateCandidate(t,o,i),formValidate:()=>n.form?.scheduleValidation(n),formSelectionPending:o=>n.form?.pendingPart(t,"selection",o?"active":null),formSelectionError:o=>n.form?.issue(t,"selection",o),formParseError:o=>n.form?.parseError(t,o),formClearDraft:()=>n.form?.clearDraft(t),publish:(o,i)=>t.publish(o,i),isActive:()=>!e.closed,reportError:(o,i)=>{e.closed||e.runtime.reportError(o,i)},callLogic:(o,i)=>Qt(e.runtime,t,o,i),format:(o,i)=>r.format(o,i),...gs(e),selectionDisplay:(o,i)=>{if(e.closed)return;let a=t.getAttr("value");if(t.pointerType(a)!=="^"||a.includes("?")||!Object.is(t.getRelativeData(a),i))return;let s=a.slice(1)+"?_displayedValue";t.getRelativeData(s)!==o&&t.setRelativeData(s,o)},periodOutput:(o,i)=>t.setRelativeData(o,i),selectionOutputs:({selectedCaption:o,selectedRecord:i,fields:a},s)=>{if(!e.closed){o&&t.setRelativeData(o,s?.caption??null),i&&t.setRelativeData(i,s?new E(s.record):null);for(let[l,u]of Object.entries(a))t.setRelativeData(u,s?.record[l.slice(9)]??null)}}}}function Mp(n,e,t){let r=n.pageContext,o=i=>{i.ok&&i.isCurrent()&&(t(i),n.finishValidation(i))};if(e instanceof Promise)e.then(o).catch(i=>r.reportError(i,"Field update failed"));else try{o(e)}catch(i){r.reportError(i,"Field update failed")}}var lc=Symbol("source text"),Pp={xmlns:"http://www.w3.org/2000/xmlns/",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},Pv=new Set(["allowFullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formNoValidate","hidden","inert","isMap","itemscope","loop","multiple","muted","noModule","noValidate","open","playsInline","readOnly","required","reversed","selected"]),Lv=new Set(["checked","muted","selected","value"]),Fv=new Map([["allowfullscreen","allowFullscreen"],["formnovalidate","formNoValidate"],["ismap","isMap"],["nomodule","noModule"],["novalidate","noValidate"],["playsinline","playsInline"],["readonly","readOnly"]]);function jv(n){let e=n.replace(/-([a-z])/g,(t,r)=>r.toUpperCase());return Fv.get(e.toLowerCase())??e}var ys=class{constructor({format:e,metadataAttributes:t=[],invokeScript:r=null,callLogic:o=null,reportError:i=null,uploadContext:a=null}={}){this.format=e,this.uploadContext=a,this.invokeScript=r,this.callLogic=o,this.reportError=i,this.metadataAttributes=new Set([...Xr,"_text",...t])}definition(e){let t=e.builder,o={...t.schema[t.schemaTag(e.nodeTag)]._meta,...e.getAttr("_meta")},i=e.nodeTag==="webcomponent"?Jt(e.getAttr()):di(e.nodeTag,{renderTag:o.render_tag,ns:e.getAttr("ns"),dialectName:t.constructor._name}),a=i==="foreignObject"?Dr:o.render_attributes?.xmlns??e.getAttr("xmlns")??(t instanceof kr?Dr:Fe);return{meta:o,namespace:a,tag:i}}validate(e,t=e.builder){this.validateLabelbox(e);let r=e.value instanceof I,o=r?e.getAttr("_text"):e.value;if(o!=null&&!["string","number","boolean"].includes(typeof o))throw new TypeError("HTML text must be scalar");let i=this.definition(e).meta.gramlot_component;for(let[l,u]of Object.entries(e.attr))if(!(i&&Object.hasOwn(i.parameters,l))&&!(e.nodeTag==="menuline"&&l==="parameters")&&!(this.metadataAttributes.has(l)||["ask","_ask"].includes(l)||u&&typeof u=="object"&&Object.hasOwn(u,"$gramlotRef"))&&u!=null&&!["string","number","boolean"].includes(typeof u))throw new TypeError(`HTML attribute ${l} must be scalar`);let a=Object.fromEntries(Object.entries(e.attr).filter(([l])=>!this.metadataAttributes.has(l))),s=r?e.value.getNodes().map(l=>l.nodeTag).filter(Boolean):[];t.validateNode(e,{value:o,attrs:a,childTags:s})}hasLabelbox(e){let t=this.definition(e).meta.gramlot_component;return t?.labelbox?!0:t?.presentationDefaults.length?Object.hasOwn(e.attr,"lbl"):Object.keys(e.attr).some(r=>r==="lbl"||r.startsWith("lbl_")||r.startsWith("box_"))}validateLabelbox(e){if(!this.hasLabelbox(e))return;let{tag:t,namespace:r}=this.definition(e);if(r!==Fe&&t!=="svg"||["html","head","body","style","script","link","meta","title","base","tr","td","th","thead","tbody","tfoot","col","colgroup","caption","option","optgroup","li","dt","dd","source","track","param","area"].includes(t))throw new TypeError("Labelbox requires content that can be placed in an HTML flow container");let o=e.parentNode;if(o?.nodeTag){let i=this.definition(o);if(i.namespace!==Fe&&i.tag!=="foreignObject"||["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","ul","ol","dl","p","button","label"].includes(i.tag))throw new TypeError("Labelbox requires an HTML flow container")}}create(e,t,r=null,o=e.attr,i=null){let{tag:a,namespace:s,meta:l}=this.definition(e);r??=a;let u=s===Fe?t.createElement(r):t.createElementNS(s,r);if(l.gramlot_component&&u.constructor.gramlotComponent?.tag!==r)throw new Error(`Component collection must be activated before rendering ${r}`);l.gramlot_component?.dataScope&&(u.readDataScope=()=>{if(!e.getAttr("datapath"))throw new Error("Data scope requires an explicit datapath");return e.getRelativeData(".")}),l.gramlot_component?.sourceContext&&u.setSourceContext({sourceNode:e,frameRecipient:()=>bs(ec(e)),locale:e.rootBuilder.binding.gramlot.locale,timeZone:e.rootBuilder.binding.gramlot.timeZone,collectionView:(f,h)=>e.rootBuilder.binding.collectionView(e,f,h),format:this.format,upload:()=>this.uploadContext(),reportError:(f,h)=>this.reportError(e,f,h),publish:(f,h)=>e.publish(f,h),writeParameter:(f,h)=>this.writeParameter(e,f,h),callLogic:(f,h)=>this.callLogic(e,f,h)});let c=t.createTextNode(this.text(e));(s!==Fe||!l.void)&&u.append(c);let d={element:u,text:c,tag:r,presentation:u};if(this.hasLabelbox(e)){this.validateLabelbox(e);let f=t.createElement("div");f.append(u),d.labelbox=mp(t,f),d.labelbox.choose=p=>{e.pointerType(e.getAttr("lbl_value"))?this.writeParameter(e,"lbl_value",p):e.setAttr({lbl_value:p})},d.presentation=d.labelbox.box,d.labelId=`gramlot-label-${K()}`,d.controlId=`gramlot-control-${K()}`;let h=t.createElement("style");h.textContent=pp,d.presentation.prepend(h),l.gramlot_component?.labelbox&&u.setLabelbox(d.labelbox)}return this.update(d,e,o,lc,i),d}matches(e,t){let{tag:r,namespace:o}=this.definition(t);return(o===Fe?e.tag.toLowerCase()===r.toLowerCase():e.tag===r)&&e.element.namespaceURI===o}writeParameter(e,t,r){let o=e.getAttr(t);e.pointerType(o)==="^"&&!re(o)&&!Object.is(e.getRelativeData(o.slice(1)),r)&&e.setRelativeData(o.slice(1),r)}compose(e,t,r){e.text.data=t??"";for(let o of r)e.element.append(o)}update(e,t,r=t.attr,o=lc,i=null,a=null){if(t.nodeTag==="script"){for(let[w,_]of t.codeAttributes())if(t.activatedCode(w)!==_)throw new Error(`script '${t.label}': '${w}' runs only as received with the Source`)}let{element:s,text:l}=e;if(this.hasLabelbox(t)&&!e.labelbox)throw new TypeError("Declare lbl or box_* when creating an experimental HTML labelbox");let u=s.namespaceURI===Fe,c=this.definition(t).meta.render_attributes??{},d=e.attrs??{},f=w=>(co(t,w,t.builder.constructor.dialectPrefixes),uo(t,w,t.builder.constructor.dialectPrefixes),t.builder.renderer_html.adaptAttrs(w)),h=t.parentNode;if(h?._getMeta("gramlot_component")?.childParameters&&(r=s.ownerDocument.defaultView.customElements.get(h._getMeta("render_tag")).projectChild(e.presentation,r,{label:t.label,adapt:f,invoke:(_,y,x)=>this.invokeScript(t,_,y,x),reportError:(_,y)=>this.reportError(t,_,y),publish:(_,y)=>t.publish(_,y),publishParent:(_,y)=>h.publish(_,y),writeParameter:(_,y)=>this.writeParameter(t,_,y),remove:()=>t.parentBag.popNode(t.label)})),e.labelbox){e.labelbox.box.style.visibility="";let w=this.definition(t).meta.gramlot_component?.parameters??{},_=Object.fromEntries(Object.entries(w).filter(([y,x])=>y.startsWith("lbl_")&&Object.hasOwn(x,"default")).map(([y,x])=>[y,x.default]));r.lbl_variant==="card"&&r.lbl_position==null&&delete _.lbl_position,gp(e.labelbox,{..._,...r},f)}if(this.definition(t).meta.gramlot_component){if(this.definition(t).meta.gramlot_component.bagStore)if(t.nodeTag==="tree")s.setStoreBag(t.rootBuilder.binding.treeStore(t));else{let w=t.absDatapath(t.getAttr("storepath"));(!a||a.path===w||a.path.startsWith(`${w}.`)||w.startsWith(`${a.path}.`))&&s.setStoreBag(t.getRelativeData(t.getAttr("storepath")))}if(this.definition(t).meta.gramlot_component.bagStruct){let w=t.absDatapath(t.getAttr("structpath"));(!a||a.path===w||a.path.startsWith(`${w}.`)||w.startsWith(`${a.path}.`))&&s.setStructBag(t.getRelativeData(t.getAttr("structpath")))}r=s.projectAttributes(r,f)}e.labelbox&&(r=Object.fromEntries(Object.entries(r).filter(([w])=>w!=="lbl"&&!w.startsWith("lbl_")&&!w.startsWith("box_"))),r.slot!=null?e.presentation.setAttribute("slot",r.slot):e.presentationSlot!=null&&e.presentation.removeAttribute("slot"),e.presentationSlot=r.slot,delete r.slot),r=Object.fromEntries(Le({...r,...c}));let p=je.classFor(s,r)!==null;o===lc&&(o=this.text(t));let m=o==null?"":String(o);l.data!==m&&(l.data=m);let b=[...new Set([...Object.keys(d),...Object.keys(r)])];b.sort((w,_)=>(_==="sandbox")-(w==="sandbox")||(u&&s.localName==="input"?(_==="type")-(w==="type"):0));for(let w of b){if(this.metadataAttributes.has(w)||["ask","_ask"].includes(w)||p&&w==="value")continue;let _=r[w];if(u&&w==="multiple"&&["input","select"].includes(s.localName)){s.multiple!==!!_&&(s.multiple=!!_);continue}if(u&&s.localName==="input"&&w==="type"){Object.is(d.type,_)||(_==null?s.removeAttribute("type"):s.type=String(_));continue}let y=w,x=jv(y),S=u&&Pv.has(x)&&typeof s[x]=="boolean",k=y==="xmlns"?"xmlns":y.includes(":")?y.split(":")[0]:"",N=Object.hasOwn(Pp,k)?Pp[k]:null;if(Object.is(d[w],_)||(_==null||S&&!_?N?s.removeAttributeNS(N,y.split(":").at(-1)):s.removeAttribute(y):N?s.setAttributeNS(N,y,String(_)):s.setAttribute(y,S?"":String(_))),u&&(S||Lv.has(x))&&x in s){let O=x==="value"?_==null?"":String(_):!!_;s[x]!==O&&(s[x]=O)}}if(i===!1?s.style.visibility!=="hidden"&&(s.style.visibility="hidden"):e.visible===!1&&(r.style==null?s.removeAttribute("style"):s.setAttribute("style",String(r.style))),e.visible=i,e.labelbox){let{fieldLabel:w,labelBox:_,box:y}=e.labelbox;["input","textarea","select","button","output","meter","progress"].includes(e.tag)?(s.id||(s.id=e.controlId),w.htmlFor=s.id):(w.id=e.labelId,this.definition(t).meta.gramlot_component?.labelbox||(y.setAttribute("role","group"),_.hidden?y.removeAttribute("aria-labelledby"):y.setAttribute("aria-labelledby",w.id))),y.hidden=!!r.hidden,i===!1&&(y.style.visibility="hidden")}e.attrs=r}text(e){return e.value instanceof I?e.getAttr("_text")==null?"":String(e.attr._text):e.value==null?"":String(e.value)}};var vs=class n{#e;#t;#r=null;#n=0;#o=new Set;#i=null;static for(e,t){return t.element?.constructor.gramlotComponent?.command?new n(e,t):null}constructor(e,t){this.#e=e,this.#t=t}get binding(){return this.#e}get node(){return this.binding.node}get element(){return this.#t.element}get controllers(){let e=this.node.value;return e?.getNodes?e.getNodes().filter(t=>t.nodeTag==="dataController"||t.nodeTag==="dataRpc"):[]}get mechanism(){let e=this.node,t=this.controllers;if(t.length>1)throw new Error(`${e.nodeTag} '${e.label}': several dataController or dataRpc children; a button has one click mechanism`);let r=e.getAttr()??{},o=[];if(t.length&&o.push("controller"),r.action!=null&&o.push("action"),e.nodeTag==="menuline"&&r.command!=null&&o.push("registered"),Lp(r).length&&o.push("fire"),e.nodeTag==="menuline"&&e.value instanceof I&&e.value.getNodes().some(i=>i.nodeTag==="menu")&&o.length)throw new Error(`menuline '${e.label}': a submenu cannot also execute a command`);if(e.nodeTag==="menuline"&&r.group&&o.length)throw new Error(`menuline '${e.label}': a group cannot execute a command`);if(o.length>1)throw new Error(`${e.nodeTag} '${e.label}': ${o.join(" and ")} together; a button has one click mechanism`);return o[0]??null}attach(){this.refresh(),this.element.activateCommand=e=>this.onClick(e),this.element.attachCommand(),this.element.addEventListener("click",this)}refresh(){if(this.node.nodeTag==="menuline"){let t=this.node.getAttr("command"),r=t?this.binding.runtime.gramlot.commands.get(t):null;this.element.setCommandDefinition(r,this.node.label),t&&!r&&this.#i!==t&&(console.warn(`Unknown command '${t}' in menu '${this.node.parentNode?.label}', entry '${this.node.label}'`),this.#i=t)}for(let t of this.#o)t.current()||t.cancel();this.mechanism&&this.node.getAttr("type")==null&&this.element.getAttribute("type")!=="button"&&this.element.setAttribute("type","button")}detach(){this.element.removeEventListener("click",this),this.element.releaseCommand(),delete this.element.activateCommand,this.#r?.();for(let e of this.#o)e.cancel(),e.release();this.#o.clear()}handleEvent(e){this.onClick(e)}onClick(e){if(this.binding.closed||this.element.disabled)return;let t=this.element.commandTarget(e);if(t===null)return;if(t!==this.element)return e.stopPropagation(),t.activateCommand(e);let r=this.element.closest("gramlot-row-actions"),o=r?r.getRowContext():null;if(r&&o===null||!this.element.prepareCommand(e))return;let i=this.mechanism;if(!i||(e.stopPropagation(),this.element.disabled))return;let a=i==="registered"?Rp(this.binding,e):null;if(i==="registered"&&!a)return;a&&this.#o.add(a);let s=this.binding.countClick(),l=this.node;for(;l&&l.getAttr("_delay")==null;)l=l.parentNode;let u=l?l.rootBuilder.runtimeValues(l)[1]._delay:0;if(u>0){let c=this.#n+1;this.#r?.(),this.#n=c;let d=setTimeout(()=>{f(),this.#r=null,this.#n=0,this.#s(e,c,a,o)},u),f=this.binding.track(()=>this.#r?.());this.#r=()=>{clearTimeout(d),a&&(a.cancel(),a.release(),this.#o.delete(a)),f(),this.#r=null,this.#n=0};return}return this.#r?.(),this.#s(e,s,a,o)}async#a(e){try{if(!e.current())return;let t=this.node.getAttr("ask"),r=this.binding.runtime.askDialog,o={...e.message.parameters};if(t&&r.required(this.binding,t,o,"ask")&&await r.show(this.binding,t,o)===null)return;e.deliver()}finally{e.release(),this.#o.delete(e)}}#s(e,t,r=null,o=null){if(r)return this.#a(r);if(this.binding.closed||this.element.disabled)return;let i=this.mechanism;if(!i)return;let a=this.node,s=qv(e);if(i==="controller")this.binding.runtime.bindingFor(this.controllers[0])?.providers[0]?.invoke({kind:"click",event:e,counter:t,rowContext:o});else if(i==="action"){let l=()=>{let[,f]=a.rootBuilder.runtimeValues(a),h=Object.fromEntries(Object.entries(f).filter(([p])=>p!=="ask"));return{...this.binding.runtime.renderer.references.resolveArguments(h),...o,event:e,_counter:t,modifiers:s}},u=f=>{if(this.binding.closed||this.element.disabled||f===null)return;let h={...l(),...f};f&&(h._askResult=f),Ut(this.binding.runtime,a,"action",a.getAttr("action"),h)},c=a.getAttr("ask"),d=this.binding.runtime.askDialog;if(c&&d.required(this.binding,c,l(),"ask"))return d.show(this.binding,c,l()).then(u);u(void 0)}else{let l={modifier:s,_counter:t},u=a.getAttr("fire");if(u!=null){a.FIRE(u,s||!0,l);return}for(let[c,d]of Lp(a.getAttr())){if(this.binding.closed)return;a.FIRE(d,c.slice(5),l)}}}};function Lp(n){return Object.entries(n??{}).filter(([e,t])=>t!=null&&(e==="fire"||e.startsWith("fire_")))}function qv(n){return["shift","ctrl","alt","meta"].filter(e=>n[`${e}Key`]).map(e=>e[0].toUpperCase()+e.slice(1)).join("")}var At=class extends fe{static classKwargs={...fe.classKwargs,asBag:!1};constructor({cacheTime:e,onError:t}){super({cacheTime:e??-1}),this.onError=t,this.loading=null,this.loaded=!1,this.writing=!1}resolve({static:e=!1}={}){return!e&&!this.closed&&!this.loading&&!this.writing&&this.expired&&this.refresh(),this.cachedValue}refresh(){if(this.closed)return null;let e=this.startLoad(r=>this.#e(r));if(e===null)return null;let t=()=>{this.loading===e&&(this.loading=null)};return e.then(t,t),this.loading=e,e.catch(r=>{r?.name!=="AbortError"&&this.onError(r)}),e}resolveSync(e){return super.resolve(e)}prepareValue(e){return e}async#e(e){if(this.closed)return;let t=this._computeEffectiveFingerprint(this._buildEffectiveKw()),r=await this.loadAsync(e);if(this.closed||e.ignored)return;let o=this.prepareValue(r);this._lastUpdate=Date.now(),this._lastEffectiveFingerprint=t,this.loaded=!0,this.writing=!0;try{this.node?this.node.setValue(o,this.cacheTime!==0):this.cachedValue=o}finally{this.writing=!1}return o}};var mo=class extends At{static internalParams=new Set([...At.internalParams,"binding","method","params","onCalling","onError","sync"]);constructor({binding:e,method:t,params:r,cacheTime:o,onCalling:i=null,onError:a,sync:s=!1}){super({cacheTime:o,onError:a}),this.binding=e,this.sync=s,this.method=t,this.params=r,this.onCalling=i}get closed(){return this.binding.closed}resolve(e={}){return this.sync?e.static||this.loading||this.writing?this.cachedValue:this.expired&&!this.binding.node.requests.calling(this.onCalling)?this.cachedValue:super.resolveSync(e):super.resolve(e)}load(){let e;try{e=this.binding.callSync("data",this.method,this.params)}catch(t){this.onError(t)}return this.loaded=!0,e}startLoad(e){let t=this.binding.node.requests;return t.calling(this.onCalling)?t.submit(this.method,this.params,e):null}loadAsync(e){return this.binding.call("data",e)}};var Fp=new Set(["kind","command","caption","icon","iconSrc","tooltip","disabled","hidden","checked","favorite","parameters","resolver","cacheTime","sync"]);function jp(n,e=new Set){if(!(n instanceof E)||e.has(n))throw new TypeError("Menu resolver must return an acyclic Bag");let t=new Set([...e,n]);return n.getNodes().map(r=>{let o=r.attr,i=o.kind,a=r.staticValue;if(Object.keys(o).some(l=>!Fp.has(l)&&!l.startsWith("resolver_")))throw new TypeError(`Unsupported menu record field: ${r.label}`);if(!["command","separator","submenu"].includes(i))throw new TypeError(`Invalid menu kind: ${r.label}`);for(let l of["disabled","hidden","checked"])if(o[l]!=null&&typeof o[l]!="boolean"&&!(typeof o[l]=="string"&&o[l].startsWith("^")))throw new TypeError(`Invalid menu ${l}`);if(o.favorite!=null&&typeof o.favorite!="boolean")throw new TypeError("favorite must be boolean");if(o.caption!=null&&typeof o.caption!="string")throw new TypeError("Menu caption must be text");if(o.parameters!=null&&(typeof o.parameters!="object"||Array.isArray(o.parameters)))throw new TypeError("Menu parameters must be a mapping");if(i==="command"&&(typeof o.command!="string"||!o.command||a!=null||o.resolver!=null))throw new TypeError("Command record requires a command and no children/resolver");if(i==="separator"&&(a!=null||Object.keys(o).length!==1))throw new TypeError("Separator record accepts kind only");if(i==="submenu"&&(typeof o.caption!="string"||o.command!=null||a instanceof E==(o.resolver!=null)||!(a instanceof E)&&a!=null))throw new TypeError("Submenu requires caption and exactly one content source");let s=a instanceof E?jp(a,t):null;return{label:r.label,attrs:{...o},children:s}})}function qp(n,e){let t=n.builder.wrapSource(n),r=n.value instanceof I?n.value.getNodes():[],o=new Set(e.map(i=>i.label));for(let i of r)o.has(i.label)||n.value.popNode(i.label);for(let[i,a]of e.entries()){let{kind:s,...l}=a.attrs,u=Object.fromEntries(Object.entries(l).filter(([p])=>p==="resolver"||p==="cacheTime"||p==="sync"||p.startsWith("resolver_")));for(let p of Object.keys(u))delete l[p];let c=s==="separator"?"-":null,d=n.value instanceof I?n.value.getNodes().find(p=>p.label===a.label):null,f=d?.value instanceof I;if(d&&(f!==(s==="submenu")||d.value==="-"!=(s==="separator"))&&(n.value.popNode(d.label),d=null),!d)d=ie(t.menuline(c,{...l,node_label:a.label}));else{let p=Object.keys(d.attr).filter(m=>Fp.has(m)&&!Object.hasOwn(l,m));d.setAttr({...Object.fromEntries(p.map(m=>[m,null])),...l})}if(s==="submenu"){let p=d.value instanceof I?d.value.getNodes().find(m=>m.nodeTag==="menu"):null;p?p.setAttr({...Object.fromEntries(Object.keys(p.attr).filter(m=>m==="resolver"||m==="cacheTime"||m==="sync"||m.startsWith("resolver_")).map(m=>[m,null])),...u}):p=ie(d.builder.wrapSource(d).menu({...u,node_label:"menu"})),a.children&&qp(p,a.children)}let h=n.value.getNodes().indexOf(d);h!==i&&n.value.move(h,i)}}var Es=class{#e=null;#t=null;#r=0;#n=!1;#o=null;constructor(e,t){this.binding=e,this.element=t}get node(){return this.binding.node}attach(){this.element.menuBinding=this,this.refresh()}detach(){this.#n=!0,this.#r++,this.node.requests.inflight?.cancel(),delete this.element.menuBinding,this.element.close(!1)}refresh(){let[,e]=this.node.rootBuilder.runtimeValues(this.node),t=Object.fromEntries(Object.entries(e).filter(([o])=>o.startsWith("resolver_")).map(([o,i])=>[o.slice(9),i])),r=L([e.resolver,t,e.cacheTime,e.sync]);r!==this.#e&&(this.#e=r,this.#r++,this.#o=null,this.#t=e.resolver?new mo({binding:this.binding,method:e.resolver,params:t,cacheTime:e.cacheTime??-1,sync:e.sync??!1,onError:()=>{}}):null,this.#t?(this.element.setStatus("loading"),this.element.opened&&this.element.isConnected&&this.load()):this.element.setStatus(null))}async load(e=!1){if(this.#n||!this.#t)return;let t=this.#t,r=this.#r;try{if(e?t.refresh():t.resolve(),t.loading&&(this.element.setStatus("loading"),await t.loading),this.#n||r!==this.#r)return;let o=t.cachedValue,i=jp(o),a=L(o);this.#o!==a&&(qp(this.node,i),this.#o=a),this.element.setStatus(i.length?null:"empty")}catch(o){if(this.#n||r!==this.#r)return;this.element.setStatus("error"),console.warn(`Menu '${this.node.label}' failed to load`,o)}}};var xs=class{#e=!1;#t=!1;constructor(e,t){this.binding=e,this.element=t}attach(){this.element.cardActions=this}detach(){this.#e=!0,delete this.element.cardActions}async clear(){let{binding:e,element:t}=this,r=()=>!this.#e&&!e.closed&&t.isConnected&&t.parameters.delitem===!0;if(this.#t||!r())return;let o=e.node,i=o.value,a=o.absDatapath(".");if(!(a===null||!(i instanceof I))){this.#t=!0;try{if(await e.runtime.askDialog.show(e,{title:"Clear card fields",msg:`Clear the fields of \u201C${t.parameters.title}\u201D? This cannot be undone.`},{})===null||!r()||o.value!==i||o.absDatapath(".")!==a)return;let l=new Map,u=new Set,c=f=>{for(let h of["collapsed","checkbox"]){let p=f.getAttr(h);f.pointerType(p)&&u.add(f.absDatapath(p))}};c(o);let d=f=>{for(let h of f.getNodes()){h.nodeTag==="groupletCard"&&c(h);let p=h.getAttr("value");if(!h._getMeta("data_element")&&h.pointerType(p)==="^"&&!re(p)){let m=h.absDatapath(p);m!==null&&(a===""||m.startsWith(`${a}.`))&&l.set(m,{child:h,pointer:p})}h.staticValue instanceof I&&d(h.staticValue)}};d(i);for(let[f,{child:h,pointer:p}]of l){if(!r()||o.value!==i||o.absDatapath(".")!==a)break;u.has(f)||h.getAttr("value")!==p||h.absDatapath(p)!==f||e.runtime.renderer.html.writeParameter(h,"value",null)}}finally{this.#t=!1}}}};var ks="connect_on",Si=class{#e;#t;#r;#n;#o;static declared(e){return Object.entries(e.getAttr()??{}).filter(([t,r])=>t.startsWith(ks)&&t.length>ks.length&&r!=null).map(([t,r])=>[t,t.slice(ks.length).toLowerCase(),r])}constructor(e,t,r,o,i=`${ks}${r}`){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.#o=i}get binding(){return this.#e}get node(){return this.binding.node}get element(){return this.#t.element}get eventName(){return this.#r}get handler(){return this.#n}get attribute(){return this.#o}attach(){this.element.addEventListener(this.eventName,this)}detach(){this.element.removeEventListener(this.eventName,this)}handleEvent(e){if(this.binding.closed)return;let t=this.node,r=this.binding.runtime;if(xi(this.handler))return Qt(r,t,this.handler,e);r.inlineCompiler.compile(t,this.attribute,this.handler,["event"])({event:e})}};function uc(n){if(n==null||n==="")return null;if(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)||n instanceof Date&&Number.isFinite(n.getTime())||de(n)&&n.isFinite())return n;throw new TypeError("Column filters require loaded scalar values")}function dn(n){return L(uc(n))}function Up(n){if(!Array.isArray(n))throw new TypeError("Column selection requires an array or null");return Object.freeze([...new Map(n.map(e=>{let t=dn(e);return[t,F(t)]})).values()])}function Vp(n){if(n===null)return null;let{from:e,to:t,dtype:r,timeZone:o}=n;if(!["D","DH","DHZ"].includes(r))throw new TypeError("Date range requires a date column");for(let i of[e,t])if(i!==null&&(!(i instanceof Date)||!Number.isFinite(i.getTime())||i.getUTCHours()||i.getUTCMinutes()||i.getUTCSeconds()||i.getUTCMilliseconds()))throw new TypeError("Date bounds require civil dates");if(e&&t&&e>t)throw new RangeError("From must not be after To.");if(r==="DHZ"&&!o)throw new TypeError("DHZ requires a timeZone");return e||t?Object.freeze({from:e?.toISOString().slice(0,10)??null,to:t?.toISOString().slice(0,10)??null,dtype:r,timeZone:o}):null}function Ts(n,e){if(!e)return!0;if(n==null||n==="")return!1;if(!(n instanceof Date)||!Number.isFinite(n.getTime()))throw new TypeError("Date range requires date values");let t;if(e.dtype==="DHZ"){let r=new Intl.DateTimeFormat("en",{timeZone:e.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),o=i=>r.find(a=>a.type===i).value;t=`${o("year")}-${o("month")}-${o("day")}`}else t=n.toISOString().slice(0,10);return(!e.from||t>=e.from)&&(!e.to||t<=e.to)}function fn(n,e){return e===2?n%4===0&&(n%100!==0||n%400===0)?29:28:[4,6,9,11].includes(e)?30:31}function ut(n,e,t){if(![n,e,t].every(Number.isInteger)||n<1||n>9999||e<1||e>12||t<1||t>fn(n,e))throw new RangeError("Date must exist in Gregorian years 0001\u20139999.");return`${String(n).padStart(4,"0")}-${String(e).padStart(2,"0")}-${String(t).padStart(2,"0")}`}function hn(n){if(typeof n!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(n))throw new RangeError("Expected a civil date in YYYY-MM-DD format.");let e=n.split("-").map(Number);return ut(...e),e}function Ci(n,e,t){let r=n-1,o=365*r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400)+t-1;for(let i=1;i<e;i++)o+=fn(n,i);return o}function Ni(n,e){let t=Ci(...hn(n))+e;if(!Number.isSafeInteger(t)||t<0||t>Ci(9999,12,31))throw new RangeError("Date offset exceeds Gregorian years 0001\u20139999.");let r=1,o=1e4;for(;o-r>1;){let a=Math.floor((r+o)/2);Ci(a,1,1)<=t?r=a:o=a}t-=Ci(r,1,1);let i=1;for(;t>=fn(r,i);)t-=fn(r,i++);return ut(r,i,t+1)}function cc(n){return Ni(n,-(Ci(...hn(n))%7))}function zp(n,e,t=0,r=1){let o=n*12+e-1+t,i=Math.floor(o/12),a=(o%12+12)%12+1,s=o+r-1,l=Math.floor(s/12),u=(s%12+12)%12+1;return{start:ut(i,a,1),end:ut(l,u,fn(l,u))}}var As={en:{months:{january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12,jan:1,feb:2,mar:3,apr:4,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12},weekdays:{monday:0,tuesday:1,wednesday:2,thursday:3,friday:4,saturday:5,sunday:6,mon:0,tue:1,wed:2,thu:3,fri:4,sat:5,sun:6},quarters:{"1st quarter":1,"2nd quarter":2,"3rd quarter":3,"4th quarter":4,q1:1,q2:2,q3:3,q4:4},keywords:{today:["today"],yesterday:["yesterday"],tomorrow:["tomorrow"],this_week:["this week","week"],last_week:["last week"],next_week:["next week"],this_month:["this month","month"],last_month:["last month"],next_month:["next month"],last:["last"],next:["next"],articles:["the"],from:["from","between"],to:["to","and"],no_period:["no period","always"]},date_order:{default:"MDY",GB:"DMY",AU:"DMY",IE:"DMY",NZ:"DMY",IN:"DMY"}},it:{months:{gennaio:1,febbraio:2,marzo:3,aprile:4,maggio:5,giugno:6,luglio:7,agosto:8,settembre:9,ottobre:10,novembre:11,dicembre:12,gen:1,feb:2,mar:3,apr:4,mag:5,giu:6,lug:7,ago:8,set:9,ott:10,nov:11,dic:12},weekdays:{luned\u00EC:0,marted\u00EC:1,mercoled\u00EC:2,gioved\u00EC:3,venerd\u00EC:4,sabato:5,domenica:6,lun:0,mar:1,mer:2,gio:3,ven:4,sab:5,dom:6},quarters:{"1\xBA trimestre":1,"2\xBA trimestre":2,"3\xBA trimestre":3,"4\xBA trimestre":4,"1\xB0 trimestre":1,"2\xB0 trimestre":2,"3\xB0 trimestre":3,"4\xB0 trimestre":4,t1:1,t2:2,t3:3,t4:4,q1:1,q2:2,q3:3,q4:4},keywords:{today:["oggi"],yesterday:["ieri"],tomorrow:["domani"],this_week:["questa settimana","settimana"],last_week:["settimana scorsa"],next_week:["settimana prossima"],this_month:["questo mese","mese"],last_month:["mese scorso"],next_month:["mese prossimo"],last:["scorso","scorsa"],next:["prossimo","prossima"],articles:["il","lo","la"],from:["da","dal","dalla","tra","fra"],to:["a","al","alla","e"],no_period:["-","senza periodo","sempre"]},date_order:{default:"DMY"}}};function Hp(n){if(typeof n!="string")throw new RangeError("A supported locale is required.");let e=n.replaceAll("-","_"),t=e.indexOf("_"),r=(t<0?e:e.slice(0,t)).toLowerCase(),o=(t<0?"":e.slice(t+1)).toUpperCase();if(!Object.hasOwn(As,r))throw new RangeError(`Unsupported locale: ${n}`);let i=As[r];return{dictionary:i,phrases:s=>[...new Set([...i.keywords[s],...As.en.keywords[s]])],order:i.date_order[o]??i.date_order.default}}var pn=/^(?:\d{4}|\d{2})$/,Gp=/^\d{1,2}$/,Ii=(n,e)=>({ok:!1,error:{code:n,message:e}}),gn=(n="UNRECOGNIZED_EXPRESSION",e="Text is not a supported date expression.")=>{throw Object.assign(new SyntaxError(e),{code:n})},Xp=(n,e)=>Object.hasOwn(n,e);function mn(n,e){if(n.length===4)return Number(n);let t=e.year+e.twoDigitYearAhead-100;return t+((Number(n)-t)%100+100)%100}function Uv(n,e){if(n.includes(";")){let o=n.split(";").map(i=>i.trim());return o.length!==2?gn("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:o,range:!0}}if(e.phrases("no_period").includes(n))return{bounds:["",""],range:!0};let t=e.phrases("to"),r=e.phrases("from");for(let o of t)if(n.startsWith(`${o} `))return{bounds:["",n.slice(o.length+1).trim()],range:!0};for(let o of t){let i=` ${o} `;if(!n.includes(i))continue;for(let s of r)if(n.startsWith(`${s} `)){n=n.slice(s.length+1);break}let a=n.split(i).map(s=>s.trim());return a.length!==2?gn("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:a,range:!0}}for(let o of r)if(n.startsWith(`${o} `))return{bounds:[n.slice(o.length+1).trim(),""],range:!0};return{bounds:[n,n],range:!1}}function Vv(n,e,t){let r=[[n,0]],o=/^(.+?)\s*([+-])\s*(\d+)$/.exec(n);o&&r.push([o[1],Number(o[2]+o[3])]);let i={today:0,yesterday:-1,tomorrow:1,this_week:0,last_week:-1,next_week:1,this_month:0,last_month:-1,next_month:1};for(let[a,s]of r)for(let[l,u]of Object.entries(i))if(e.phrases(l).includes(a)){if(l.endsWith("_week"))return Ni(cc(e.workdate),(u+s)*7+(t?6:0));if(l.endsWith("_month")){let c=zp(e.year,e.month,u+s);return t?c.end:c.start}return Ni(e.workdate,u+s)}return null}function zv(n,e,t){let r=Object.entries(e.dictionary.quarters).sort((o,i)=>i[0].length-o[0].length);for(let[o,i]of r){let a;if(n===o)a=null;else if(n.startsWith(o)&&pn.test(n.slice(o.length).trim()))a=mn(n.slice(o.length).trim(),e);else if(n.endsWith(o)&&pn.test(n.slice(0,-o.length).trim()))a=mn(n.slice(0,-o.length).trim(),e);else continue;return{year:a,month:t?i*3:i*3-2}}return null}function Wp(n,e){if(Xp(e.months,n))return e.months[n];let t=/^m(\d{1,2})$/.exec(n);return t&&Number(t[1])>=1&&Number(t[1])<=12?Number(t[1]):null}function Hv(n,e){let t=n.split(/\s+/),r=t.map((u,c)=>Wp(u,e.dictionary)?c:-1).filter(u=>u>=0);if(!r.length)return null;if(r.length!==1)return gn();let o=r[0],i=Wp(t[o],e.dictionary),a=t.slice(0,o),s=t.slice(o+1),l=[...a,...s];if(l.length===1&&e.phrases("last").includes(l[0]))return{year:e.year-(i>e.month?1:0),month:i};if(l.length===1&&e.phrases("next").includes(l[0]))return{year:e.year+(i<e.month?1:0),month:i};if(!l.length)return{year:null,month:i};if(!a.length&&s.length===1&&pn.test(s[0]))return{year:mn(s[0],e),month:i};if(a.length===1&&Gp.test(a[0])){if(!s.length)return ut(e.year,i,Number(a[0]));if(s.length===1&&pn.test(s[0]))return ut(mn(s[0],e),i,Number(a[0]))}return!a.length&&s.length===2&&Gp.test(s[0])&&pn.test(s[1])?ut(mn(s[1],e),i,Number(s[0])):gn()}function Gv(n,e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);if(t)return ut(...t.slice(1).map(Number));let r=/^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(n),o={};if(r)e.order.split("").forEach((s,l)=>{o[s]=r[l+1]});else if(/^(?:\d{6}|\d{8})$/.test(n)){let s=n.length===8?4:2;for(let l of e.order){let u=l==="Y"?s:2;o[l]=n.slice(0,u),n=n.slice(u)}}else return null;if(!pn.test(o.Y)||o.D.length>2||o.M.length>2)return gn();let i=Number(o.D),a=Number(o.M);return r&&a>12&&i<=12&&([i,a]=[a,i]),ut(mn(o.Y,e),a,i)}function Yp(n,e,t){if(!n)return null;let r=e.phrases("articles");if(n=n.split(/\s+/).filter(i=>!r.includes(i)).join(" "),!n)return gn();if(pn.test(n))return ut(mn(n,e),t?12:1,t?31:1);let o=Vv(n,e,t)??zv(n,e,t)??Hv(n,e);return o!==null?o:Xp(e.dictionary.weekdays,n)?Ni(cc(e.workdate),e.dictionary.weekdays[n]):Gv(n,e)??gn()}function Wv(n,e,t){if(n===null||typeof n=="string")return n;let r=n.year??t.year,o=typeof e=="string"?hn(e)[0]:e?.year,i=typeof e=="string"?hn(e)[1]:e?.month;return o&&(r>o&&(r=o),r===o&&n.month>i&&r--),ut(r,n.month,1)}function Yv(n,e,t){if(n===null||typeof n=="string")return n;let r=n.year??t.year;if(e!==null){let[o,i]=hn(e);r<o&&(r=o),r===o&&i>n.month&&r++}return ut(r,n.month,fn(r,n.month))}function Ds(n,e={}){if(!e||typeof e!="object"||Array.isArray(e))return Ii("INVALID_CONTEXT","Options must provide a civil workdate and supported locale.");let t;try{let{locale:r="it-IT",workdate:o,twoDigitYearAhead:i=20}=e,[a,s]=hn(o);if(!Number.isInteger(i)||i<0||i>99)throw new RangeError("twoDigitYearAhead must be an integer from 0 to 99.");t={...Hp(r),workdate:o,year:a,month:s,twoDigitYearAhead:i}}catch(r){return Ii("INVALID_CONTEXT",r.message)}if(typeof n!="string")return Ii("INVALID_INPUT","Expression must be a string.");try{let r=n.toLowerCase().trim().replaceAll(",",""),{bounds:o,range:i}=Uv(r,t),a=Yp(o[1],t,!0),s=Yp(o[0],t,!1),l=Wv(s,a,t),u=Yv(a,l,t);return!i&&typeof s=="string"&&l===u?{ok:!0,kind:"date",date:l}:{ok:!0,kind:"period",start:l,end:u}}catch(r){if(r instanceof RangeError)return Ii("INVALID_DATE",r.message);if(r instanceof SyntaxError)return Ii(r.code,r.message);throw r}}function Zp(n){if(n===null)return null;let{value:e,columns:t,dtype:r,locale:o}=n;if(typeof e!="string"||!Array.isArray(t)||!t.length||t.some(u=>typeof u!="string"||!u||u==="rowidx")||!["T","L","R","N","D"].includes(r))throw new TypeError("Invalid collection filter");if(!e.trim())return null;if(r==="T"){let u=n.literal===!0?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e,c=new RegExp(u,"i");return d=>c.test(t.map(f=>Xv(d(f),o,n.timeZone)).join(" "))}if(t.length!==1)throw new TypeError("Typed filters require one column");let i=/^\s*(<=|>=|==|!=|[<>=!#])\s*(.+?)\s*$/.exec(e);if(!i)throw new Error("Enter a comparison, for example > 100 or = 12.");let[,a,s]=i,l;if(r==="D"){let u=new Date,c=`${u.getFullYear()}-${String(u.getMonth()+1).padStart(2,"0")}-${String(u.getDate()).padStart(2,"0")}`,d=Ds(s,{locale:o,workdate:c});if(!d.ok||d.kind!=="date")throw new Error("Enter one complete date after the comparison.");l=new Date(`${d.date}T00:00:00Z`)}else l=Zv(s,o);return u=>{let c=u(t[0]);if(c==null)return!1;if(r==="D"?!(c instanceof Date)||!Number.isFinite(c.getTime()):!(typeof c=="number"&&Number.isFinite(c)||de(c)&&c.isFinite()))throw new TypeError(`Filter value does not match ${r}`);let d=de(l)?-l.comparedTo(c):c<l?-1:c>l?1:0;switch(a){case"=":case"==":return d===0;case"!":case"#":case"!=":return d!==0;case"<":return d<0;case">":return d>0;case"<=":return d<=0;case">=":return d>=0}}}function Xv(n,e,t){return n==null?"":typeof n=="string"||typeof n=="boolean"?String(n):fs(n,{pattern:n instanceof Date?"short":"#,##0.####################"},{locale:e,timeZone:t})}function Zv(n,e){let t=new Intl.NumberFormat(e).formatToParts(-12345.6),r=t.find(l=>l.type==="decimal").value,o=t.find(l=>l.type==="group")?.value,i=t.find(l=>l.type==="minusSign").value,a=n.replaceAll(i,"-");if(o&&a.includes(o)){let u=a.split(r)[0].replace(/^[+-]/,"").split(o),c=new Intl.NumberFormat(e).formatToParts(1234567890123).filter(h=>h.type==="integer").map(h=>h.value.length),d=c.at(-1),f=c.at(-2);if(a.split(r).slice(1).some(h=>h.includes(o))||!/^\d+$/.test(u[0])||u[0].length>f||u.slice(1).some((h,p)=>!/^\d+$/.test(h)||h.length!==(p===u.length-2?d:f)))throw new Error("Invalid numeric grouping.");a=a.replaceAll(o,"")}if(a=a.replace(r,"."),!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(a))throw new Error("Enter a complete number.");let s=Lt(a);if(!de(s)||!s.isFinite())throw new Error("A finite Decimal backend is required.");return s}function Kp(n,e){return(","+n+",").includes(","+e+",")}function Jp(n){if(typeof n!="string")throw new TypeError("grid checked must refer to a string (empty string for an empty set)");return n}function Qp(n){if(typeof n!="string"||!n||n.includes(","))throw new TypeError("grid checkedField requires nonempty text IDs without commas");return n}var Ss=class{#e=new Set;constructor(e,t){if(!(e instanceof E))throw new TypeError("collection store requires a Bag");if(!["values","attributes"].includes(t))throw new TypeError("collection store rowMode must explicitly be values or attributes");if(!e.parentNode)throw new TypeError("collection store requires a Bag attached to Data");this.bag=e,this.rowMode=t}subscribe(e){return this.#e.add(e),()=>this.#e.delete(e)}receiveData(e,t=null){Cs(this.#e,{full:t===null,rows:t?[t]:[]})}getRows(){let e=this.bag.getNodes();for(let t of e){if(t.resolver)throw new TypeError("collection store requires loaded rows");if(this.rowMode==="values"&&!(t.staticValue instanceof E))throw new TypeError(`collection store row ${t.label} must contain a Bag`)}return e}value(e,t){if(e.resolver)throw new TypeError("collection store requires loaded rows");if(this.rowMode==="attributes")return e.getAttr(t);let r=e.staticValue;if(!(r instanceof E))throw new TypeError(`collection store row ${e.label} must contain a Bag`);let o=r.getNode(t);if(o?.resolver)throw new TypeError("collection store requires loaded cells");return o?.staticValue}};function Cs(n,e){let t=[],r=Object.freeze({full:e.full,rows:Object.freeze([...e.rows])});for(let o of[...n])if(n.has(o))try{o(r)}catch(i){t.push(i)}if(t.length)throw new AggregateError(t,"Collection notification failed")}var Ns=class{#e;#t=null;#r=new Set;#n=new Map;#o="";#i=new Map;#a=null;constructor(e){this.bindStore(e)}get bag(){return this.#e.bag}get rowMode(){return this.#e.rowMode}get sortedBy(){return this.#o}get criteria(){return em(this.#o)}get filter(){return this.#i.get("search")?.definition??null}get filterSignature(){return JSON.stringify([...this.#i].map(([e,{definition:t}])=>[e,t]))}get filterContributions(){return Object.freeze([...this.#i].map(([e,t])=>Object.freeze([e,Object.freeze({...t})])))}copyFiltersFrom(e){this.filterSignature!==e.filterSignature&&this.#u(this.#s(),this.#o,new Map(e.filterContributions))}get filtered(){return this.#a===null?null:[...this.#a]}isFiltered(){return this.#a!==null}value(e,t){return this.#e.value(e,t)}subscribe(e){return this.#r.add(e),()=>this.#r.delete(e)}connect(){this.#t||(this.synchronize(),this.#t=this.#e.subscribe(e=>this.synchronize(e)))}disconnect(){this.#t?.(),this.#t=null}bindStore(e){if(this.#e===e)return;let t=this.#t!==null;this.disconnect(),this.#e=e,this.#n.clear(),t?this.connect():this.synchronize()}getRows(e=!0){let t=this.#s();return e&&this.#a!==null?this.#a.map(r=>t[r]):t}#s(){return this.#e.getRows().toSorted((e,t)=>(this.#n.get(e)??1/0)-(this.#n.get(t)??1/0))}synchronize(e={full:!0,rows:[]}){if(!e.full&&!this.#o&&!this.#i.size){Cs(this.#r,e);return}this.#u(this.#c(this.#s(),this.criteria),this.#o,this.#i,e)}sort(e){let t=this.#c(this.#s(),em(e));this.#u(t,e,this.#i)}moveRow(e,t,r=!1){if(e===t||e.parentBag!==this.bag||t.parentBag!==this.bag)return;let o=this.getRows(!1);o.splice(o.indexOf(e),1),o.splice(o.indexOf(t)+Number(r),0,e),this.#u(o,"",this.#i)}applyFilter(e,t="search"){if(!["base","search"].includes(t))throw new TypeError("Unknown collection filter contribution");let r=e===null?null:Object.freeze({...e,columns:Object.freeze([...e.columns])});this.#l(t,r,Zp(r))}applySetFilter(e){let t=e===null?null:Object.freeze(e.map(({field:o,value:i})=>{if(typeof o!="string"||!o)throw new TypeError("Set filter requires an identity field");return Jp(i),Object.freeze({field:o,value:i})})),r=t===null?null:o=>t.every(({field:i,value:a})=>Kp(a,Qp(o(i))));this.#l("sets",t,r)}columnFilter(e){return this.#i.get(`column:${e}`)?.definition.values??null}columnRange(e){let t=this.#i.get(`column:${e}`)?.definition.range;return t?{...t,from:t.from&&new Date(t.from+"T00:00:00Z"),to:t.to&&new Date(t.to+"T00:00:00Z")}:null}applyColumnFilter(e,t,r=this.columnRange(e)){if(r=Vp(r),typeof e!="string"||!e)throw new TypeError("Column filter requires a field");let o=t===null?null:Up(t),i=o?.map(dn),a=o===null&&r===null?null:Object.freeze({field:e,values:o,keys:i&&Object.freeze(i),range:r}),s=a===null?null:l=>Ts(l(e),r)&&(i===void 0||i.includes(dn(l(e))));this.#l(`column:${e}`,a,s)}columnFacets(e){let t=new Map,r=this.#i.get(`column:${e}`)?.definition.range??null,o=this.columnFilter(e),i=o?.map(dn),a=[...this.#i].filter(([s])=>s!==`column:${e}`).map(([,s])=>s.predicate).filter(s=>s!==null);for(let s of this.#s()){let l=uc(this.value(s,e)),u=dn(l);t.has(u)||t.set(u,{key:u,value:l,count:0,selected:Ts(l,r)&&(i===void 0||i.includes(u))}),a.every(c=>c(d=>this.value(s,d)))&&t.get(u).count++}for(let s of o??[]){let l=dn(s);t.has(l)||t.set(l,{key:l,value:s,count:0,selected:!0})}return[...t.values()].filter(s=>Ts(s.value,r))}#l(e,t,r){if(JSON.stringify(this.#i.get(e)?.definition??null)===JSON.stringify(t))return;let o=new Map(this.#i);t===null?o.delete(e):o.set(e,{definition:t,predicate:r}),this.#u(this.#s(),this.#o,o)}#u(e,t,r,o={full:!1,rows:[]}){let i=[...r.values()].map(c=>c.predicate).filter(c=>c!==null),a=i.length?e.flatMap((c,d)=>i.every(f=>f(h=>this.value(c,h)))?[d]:[]):null,s=o.full||t!==this.#o||r!==this.#i||e.length!==this.#n.size||e.some((c,d)=>this.#n.get(c)!==d)||JSON.stringify(a)!==JSON.stringify(this.#a);this.#n=new Map(e.map((c,d)=>[c,d])),this.#o=t,this.#i=r,this.#a=a;let l=a===null?null:new Set(a),u=s?[]:o.rows.filter(c=>this.#n.has(c)&&(l===null||l.has(this.#n.get(c))));(s||u.length||o.rows.length)&&Cs(this.#r,{full:s,rows:u})}#c(e,t){if(!t.length)return e;let r=e.map(o=>({node:o,keys:t.map(({field:i})=>this.value(o,i))}));for(let o=0;o<t.length;o++)if(new Set(r.map(a=>Kv(a.keys[o])).filter(a=>a!==null)).size>1)throw new TypeError(`collection view cannot compare mixed types in ${t[o].field}`);return r.sort((o,i)=>{for(let[a,{direction:s}]of t.entries()){let l=Jv(o.keys[a],i.keys[a]);if(l)return s==="a"?l:-l}return 0}).map(o=>o.node)}};function em(n){if(typeof n!="string")throw new TypeError("collection view sortedBy must be a string");if(n==="")return[];let e=new Set;return n.split(",").map(t=>{let r=/^([^,:]+):([ad])$/.exec(t);if(!r||e.has(r[1]))throw new TypeError(`Invalid collection view sort criterion: ${t}`);return e.add(r[1]),{field:r[1],direction:r[2]}})}function Kv(n){if(n==null)return null;if(typeof n=="number"&&Number.isFinite(n)||de(n)&&n.isFinite())return"number";if(n instanceof Date&&Number.isFinite(n.getTime()))return"date";if(typeof n=="string"||typeof n=="boolean")return typeof n;throw new TypeError("collection view sort requires loaded finite scalar values")}function Jv(n,e){return n==null||e==null?n==null?e==null?0:-1:1:de(n)?n.comparedTo(e):de(e)?-e.comparedTo(n):n<e?-1:n>e?1:0}var Is=class{constructor(e=null,t=null){this.parent=e,this.segment=t,this.children=new Map,this.registrations=new Set}},dc=class{#e;#t;#r;#n;#o;#i=!0;#a;constructor(e,{path:t,attr:r,recipient:o,order:i,subtree:a=!1}){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.#o=i,this.#a=a}get router(){return this.#e}get path(){return this.#t}get attr(){return this.#r}get recipient(){return this.#n}get subtree(){return this.#a}get active(){return this.#i}get order(){return this.#o}close(){this.active&&(this.#i=!1,this.router.unregister(this))}},fc=class{constructor({evt:e,node:t,path:r,oldvalue:o,attrsDiff:i,reason:a,fired:s,level:l,registration:u,index:c}){this.evt=e,this.node=t,this.path=r,this.oldvalue=o,this.attrsDiff=i,this.reason=a,this.fired=s,this.level=l,this.registration=u,this.index=c}},Os=class{#e;#t=new Is;#r=new Map;#n=0;#o=0;constructor(e){this.#e=e}get runtime(){return this.#e}get size(){return this.#n}register({path:e,attr:t=null,recipient:r,subtree:o=!1}){if(typeof e!="string"||e==="")throw new TypeError(`A Data registration requires a path: ${e}`);let i=this.#t;for(let s of e.split(".")){let l=i.children.get(s);l||(l=new Is(i,s),i.children.set(s,l)),i=l}this.#o+=1;let a=new dc(this,{path:e,attr:t,recipient:r,order:this.#o,subtree:o});return i.registrations.add(a),this.#r.set(a,i),this.#n+=1,a}unregister(e){let t=this.#r.get(e);if(t)for(this.#r.delete(e),t.registrations.delete(e),this.#n-=1;t.parent&&!t.children.size&&!t.registrations.size;)t.parent.children.delete(t.segment),t=t.parent}deliver(e){let{pathlist:t}=e;if(!t?.length||t[0]!==mi||e.reason==="autocreate")return;let r=t.slice(1),o=e.evt==="ins"||e.evt==="del";for(let i of Array.isArray(e.node)?e.node:[e.node]){let a=o?[...r,i.label]:r,s=a.join(".");for(let[l,u]of this.#i(a,e))l.active&&l.recipient.receive(new fc({evt:e.evt,node:i,path:s,oldvalue:e.oldvalue??null,attrsDiff:e.attrs_diff??null,reason:e.reason??null,fired:e.fired??!1,level:u,registration:l,index:e.ind??null}))}}#i(e,t){let r=[],o=this.#t;for(let a of e){for(let s of o.registrations)o!==this.#t&&this.#a(s,"child",t)&&r.push([s,"child"]);if(o=o.children.get(a),!o)return r.sort(([s],[l])=>s.order-l.order)}for(let a of o.registrations)this.#a(a,"node",t)&&r.push([a,"node"]);let i=[...o.children.values()];for(;i.length;){let a=i.pop();for(let s of a.registrations)this.#a(s,"container",t)&&r.push([s,"container"]);i.push(...a.children.values())}return r.sort(([a],[s])=>a.order-s.order)}#a(e,t,r){let{evt:o}=r;return e.subtree?t!=="container"||o!=="upd_attrs":e.attr===null?o==="upd_attrs"?!1:!(t==="child"&&r.fired):t==="child"?!1:t==="container"?o!=="upd_attrs":o==="ins"||o==="del"?!0:Object.hasOwn(r.attrs_diff??{},e.attr)}};var Qv=new Set(["T","B","L","R","N","D","H","DHZ"]),e2=new Set(["tag","field","name","title","dtype","width","align","format","columnset","white_space","max_height","edit","check","checked","checkedField"]),t2=new Set(["tag","code","name","background","color"]),Oi=class{#e=new Map;constructor(e){if(!(e instanceof E))throw new TypeError("grid structpath must resolve to a Bag");let t=Rs(e,"view_0"),r=Rs(e,"info"),o=Rs(t,"rows_0"),i=Rs(r,"columnsets"),a=new Set,s=new Map;for(let l of i.getNodes()){let u=l.getAttr();if(tm(u,t2),hc(u.code,"colgroup code"),u.tag!=="columnset"||l.resolver||l.staticValue!=null||l.label!==u.code)throw new TypeError("grid columnset requires a scalar definition labelled by code");if(s.has(u.code))throw new TypeError(`Duplicate grid colgroup: ${u.code}`);if(u.name!=null&&typeof u.name!="string")throw new TypeError("grid group name must be text");for(let c of["background","color"])if(u[c]!=null&&typeof u[c]!="string")throw new TypeError(`grid ${c} must be text`);s.set(u.code,{...u,name:u.name??u.code})}this.columns=[],this.groups=[];for(let l of o.getNodes()){let u=l.getAttr();if(tm(u,e2),u.tag!=="cell"||l.staticValue!=null||l.resolver)throw new TypeError("grid cell must be a scalar declaration");if(hc(u.field,"field"),a.has(u.field))throw new TypeError(`Duplicate grid field: ${u.field}`);if(a.add(u.field),this.#e.set(u.field,l),u.columnset!=null&&!s.has(u.columnset))throw new TypeError(`Unknown grid columnset: ${u.columnset}`);if(u.dtype!=null&&!Qv.has(u.dtype))throw new TypeError(`Unsupported grid dtype: ${u.dtype}`);if(u.align!=null&&!["start","center","end"].includes(u.align))throw new TypeError("grid align requires start, center or end");if(u.width!=null&&(typeof u.width!="string"||!/^(?:\d+(?:\.\d+)?)(?:px|em|rem|ch|%)$/.test(u.width)))throw new TypeError("grid width requires a nonnegative CSS length (px, em, rem, ch or %)");if(u.max_height!=null&&(typeof u.max_height!="string"||!/^(?:\d+(?:\.\d+)?)(?:px|em|rem)$/.test(u.max_height)))throw new TypeError("grid max_height requires a nonnegative CSS length (px, em or rem)");if(u.white_space!=null&&!["normal","nowrap","pre-wrap"].includes(u.white_space))throw new TypeError("grid white_space requires normal, nowrap or pre-wrap");for(let h of["name","title","format"])if(u[h]!=null&&typeof u[h]!="string")throw new TypeError(`grid ${h} must be text`);if(u.edit!=null&&typeof u.edit!="boolean"&&(typeof u.edit!="object"||Array.isArray(u.edit)))throw new TypeError("grid edit requires a boolean or editor options");if(u.check!=null||u.checked!=null||u.checkedField!=null){if(!["multiple","single"].includes(u.check)||typeof u.checked!="string"||!u.checked.startsWith("^")||u.checked.length<2||u.checked.includes("?"))throw new TypeError("grid check requires single or multiple and checked=^DataPath");if(hc(u.checkedField,"checkedField"),u.edit)throw new TypeError("external check sets cannot edit row fields")}let c=Object.freeze({...u,name:u.name??u.field,align:u.align??(["L","R","N"].includes(u.dtype)?"end":"start")});this.columns.push(c);let d=u.columnset??null,f=this.groups.at(-1);(!f||f.code!==d)&&(f={code:d,...d===null?{name:null}:s.get(d),columns:[]},this.groups.push(f)),f.columns.push(c)}if(!this.columns.length)throw new TypeError("grid struct requires at least one column");for(let l of this.groups)Object.freeze(l.columns),Object.freeze(l);Object.freeze(this.columns),Object.freeze(this.groups),Object.freeze(this)}columnNode(e){return this.#e.get(e)}moveColumn(e,t,r=!1){let o=this.#e.get(e),i=this.#e.get(t);if(!o||!i||o===i)return;let a=o.parentBag,s=a.getNodes(),l=s.indexOf(o),u=s.indexOf(i),c=u+Number(r)-+(l<u);c!==l&&a.move(l,c)}setColumnWidth(e,t){if(!Number.isFinite(t)||t<=0)throw new TypeError("grid resized width must be positive pixels");this.#e.get(e).setAttr({width:`${Math.round(t)}px`})}};function Rs(n,e){let t=n.getNode(e);if(!t||t.resolver||!(t.staticValue instanceof E))throw new TypeError(`grid struct requires Bag ${e}`);return t.staticValue}function tm(n,e){for(let t of Object.keys(n))if(!e.has(t))throw new TypeError(`Unsupported grid struct attribute: ${t}`)}function hc(n,e){if(typeof n!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw new TypeError(`grid ${e} requires a simple field identifier`)}function rm(n){let e=new E,t=new E,r=new E;e.setItem("view_0",new E,{tag:"view"}),e.getItem("view_0").setItem("rows_0",t,{tag:"rows"}),e.setItem("info",new E),e.getItem("info").setItem("columnsets",r);let o=(i,a=null)=>{if(i.builder.validateNode(i),i.nodeTag!=="column"||i.staticValue!=null)throw new TypeError("grid column must be a scalar declaration");let s={tag:"cell"};for(let u of["field","name","title","dtype","width","align","format","white_space","max_height","edit","check","checked","checkedField"])i.getAttr(u)!=null&&(s[u]=i.getAttr(u));let l=`cell_${s.field}`;if(t.getNode(l))throw new TypeError(`Duplicate grid field: ${s.field}`);a!==null&&(s.columnset=a),t.setItem(l,null,s)};for(let i of n.getNodes())if(i.nodeTag==="column")o(i);else if(i.nodeTag==="colgroup"){if(i.builder.validateNode(i),!(i.staticValue instanceof I))throw new TypeError("grid colgroup requires column declarations");let a=i.getAttr("code");if(r.getNode(a))throw new TypeError(`Duplicate grid colgroup: ${a}`);let s={tag:"columnset",code:a,name:i.getAttr("name")??a};for(let l of["background","color"])i.getAttr(l)!=null&&(s[l]=i.getAttr(l));r.setItem(a,null,s);for(let l of i.staticValue.getNodes())o(l,a)}else throw new TypeError("grid struct accepts column and colgroup only");return e}function nm(n){if(n._getMeta("gramlot_component")?.bagStruct){let e=n.staticValue instanceof I?n.staticValue.getNodes():[];if(e.some(t=>!t._getMeta("gridStruct"))||e.length>1)throw new TypeError("grid accepts one struct declaration");if(e.length&&n.getAttr("structpath")!=null)throw new TypeError("grid requires structpath or nested struct, not both");if(!e.length&&!n.getAttr("structpath"))throw new TypeError("grid requires structpath or nested struct");if(!["values","attributes"].includes(n.getAttr("rowMode")))throw new TypeError("grid rowMode must explicitly be values or attributes")}if(n._getMeta("gridStruct")){if(!n.parentNode?._getMeta("gramlot_component")?.bagStruct)throw new TypeError("struct requires a grid parent");if(!(n.staticValue instanceof I))throw new TypeError("grid struct requires column declarations");new Oi(rm(n.staticValue))}}function om(n,e){let t=rm(n.staticValue);new Oi(t);let r=`_gramlot.grid.${crypto.randomUUID().replaceAll("-","")}.struct`;e.setItem(r,t,null,">",!1,!0,n),n.parentNode.setAttr({structpath:r},!1),n.setValue(null,!1)}var Bs=class{#e;constructor(e){this.#e=e}get runtime(){return this.#e}install(e){let t=Ri(e),r=this.setterNodes(e);mc(e);for(let o of r)o._getMeta("gridStruct")?om(o,this.runtime.data):this.applySetter(o),this.runtime.closeBranch(o),o.parentBag&&o.parentBag.popNode(o.label);this.applyDefaults(t.filter(o=>o.nodeTag&&!o._getMeta("data_element")))}setterNodes(e){return Ri(e).filter(t=>t.nodeTag==="dataSetter"||t._getMeta("gridStruct"))}applySetter(e){let t=e.absDatapath(e.pathAttribute("destination_path"));if(t===null)return;let r=e.getAttr("value")??null,o=n2(e.getAttr()),i=this.runtime.data;if(r!==null)i.setItem(t,r,o,">",!1,!0,e),r instanceof E&&e.setAttr({value:null},!1);else{let a=i.getNode(t);a?o&&a.setAttr(o,!0):i.setItem(t,null,o,">",!1,!0,e)}}applyDefaults(e){for(let t of e){let r=t.getAttr();for(let[o,i]of Object.entries(r)){if(!r2(t,o,i))continue;let a=o==="value"?r.default_value??r.default:r[`default_${o}`];a!=null&&this.#t(t,i,a)}this.#r(t,r)}}#t(e,t,r){let o=e.absDatapath(t);if(o===null)return;let[i,a=null]=o.split("?",2),s=this.runtime.data,l=s.getNode(i);if(a===null){if(l&&l.value!==null&&l.value!==void 0)return;s.setItem(i,r,null,">",!1,!0,e)}else if(l){let u=l.getAttr(a);u==null&&l.setAttr({[a]:r},!0)}else s.setItem(i,null,{[a]:r},">",!1,!0,e)}#r(e,t){let r={};for(let[a,s]of Object.entries(t))a.startsWith("attr_")&&(r[a.slice(5)]=re(s)?Ir(e,a):e.pointerType(s)?e.getRelativeData(s):s);if(!Object.keys(r).length)return;let o=[t.value,t.src].find(a=>e.pointerType(a));if(!o)return;let i=e.absDatapath(o);i!==null&&this.runtime.data.getNode(i.split("?",1)[0])?.setAttr(r,!0,!0,!1)}};function r2(n,e,t){return e==="_meta"||Xr.has(e)||e==="default"||e.startsWith("default_")||e.startsWith("attr_")||e.endsWith("_path")?!1:n.pointerType(t)!==null}function n2(n){let e={};for(let[t,r]of Object.entries(Sr(n??{})))Xr.has(t)||t.startsWith("_")||t==="destination_path"||t==="value"||r!=null&&(e[t]=r);return Object.keys(e).length?e:null}function o2(n){let e=n.builder;if(!(e instanceof Oe))throw new Error(`dataSetter '${n.label}': dataSetter is not supported inside ${e.constructor._name}`)}function mc(n){for(let e of Ri(n))nm(e),e.nodeTag==="dataSetter"&&o2(e),u2(e)}var i2=["_init","_onStart","_onBuilt","_delay","_timing","_userChanges"],a2=new Set(["dataFormula","dataController","dataRpc","dataRemote"]),s2=["_onCalling","_onResult","_onError"],l2=["_delay","_timing","_userChanges"],pc=["_init","_onBuilt","_onStart"];function u2(n){let e=i=>n.getAttr(i)!==null&&n.getAttr(i)!==void 0,t=!n._getMeta("data_element")&&typeof n.getAttr("remote")=="string";if(n.nodeTag!=="dataRpc"){let i=s2.find(a=>e(a)&&!(a==="_onCalling"&&(n.nodeTag==="dataRemote"||t)));if(i){let a=i==="_onCalling"?"dataRpc, dataRemote and remote":"dataRpc";throw new Error(`${n.nodeTag??"fragment"} '${n.label}': '${i}' is allowed only on ${a}`)}}if(a2.has(n.nodeTag)){let i=Object.entries(n.getAttr()).find(([,s])=>mt(s));if(i)throw new Error(`${n.nodeTag} '${n.label}': '${i[0]}' is a == expression, not accepted on ${n.nodeTag}`);let a=n.nodeTag==="dataRemote"?pc.find(e):null;if(a)throw new Error(`dataRemote '${n.label}': '${a}' is not accepted on dataRemote, its resolver loads when the Data is read`);for(let s of pc){let l=n.getAttr(s);if(!(l==null||typeof l=="boolean"||typeof l=="number"))throw new Error(`${n.nodeTag} '${n.label}': '${s}' accepts true, false, null or a number, not ${JSON.stringify(l)}`)}return}let r=i2.find(i=>e(i)&&!(i==="_delay"&&!n._getMeta("data_element")&&n.nodeTag!=="html_button")&&!(t&&l2.includes(i)));if(!r)return;let o=pc.includes(r)?"dataFormula, dataController and dataRpc":"dataFormula, dataController, dataRpc and dataRemote";throw new Error(`${n.nodeTag??"fragment"} '${n.label}': '${r}' is allowed only on ${o}`)}function Ri(n){if(n instanceof I)return n.getNodes().flatMap(t=>Ri(t));let e=[n];return n.value instanceof I&&e.push(...Ri(n.value)),e}var c2=new Set(["destination_path","result_path","func","formula","script","if","else","_init","_onStart","_onBuilt","_delay","_timing","_userChanges","_ask","_ask_if","_ask_title","_ask_onCancel","method","timeout","_onCalling","_onResult","_onError","cacheTime","sync"]),Bi=class{#e;#t=null;#r=null;constructor(e){this.#e=e}get binding(){return this.#e}debounce(e,t){this.#r?.();let r=null,o=setTimeout(()=>{r(),this.#r=null,t()},e);r=this.binding.track(()=>clearTimeout(o)),this.#r=()=>{clearTimeout(o),r(),this.#r=null}}startTiming(e,t){if(this.#t?.(),!(e>0))return;let r=setInterval(t,e*1e3),o=this.binding.track(()=>clearInterval(r));this.#t=()=>{clearInterval(r),o(),this.#t=null}}cancel(){this.#r?.(),this.#t?.()}},go=class{#e;#t=[];#r=new Set;#n;#o=null;#i=!1;constructor(e){this.#e=e,this.#n=new Bi(e),e.track(()=>{this.cancel(),this.#p(),this.#f()})}get binding(){return this.#e}get node(){return this.binding.node}get kind(){throw new Error("Provider.kind is defined by FormulaProvider, ControllerProvider, RpcProvider and RemoteProvider")}register(){let e=this.node,t=e.getAttr("_onStart");if(typeof t=="number"&&!(Number.isFinite(t)&&t>=0))throw new Error(`${e.nodeTag} '${e.label}': _onStart must be true or a delay in ms not below 0: ${t}`);this.#p();let r=this.binding.runtime.router,o=Ft(e,e.getAttr("_timing"));for(let[i,a]of e.pointers()){if(i==="datapath")continue;let s=e.absDatapath(a);if(s===null)continue;let[l,u=null]=s.split("?",2),c=r.register({path:l,attr:u,recipient:this});this.#t.push(c),(i==="_timing"||o.has(i))&&this.#r.add(c)}this.#t.push(...this.binding.runtime.subscriptions.subscribeNode(e,(i,a,s)=>(l,u)=>{let c={kind:"subscription",topic:s,payload:l,metadata:u};if(this.#s("_userChanges")&&s!=="node")return;let d=this.#s("_delay");d>0?this.#n.debounce(d,()=>this.invoke(c)):this.invoke(c)})),this.#a(),this.kind==="remote"&&this.invoke({kind:"install",change:null})}receive(e){if(this.#r.has(e.registration)){this.#a();return}if(this.#s("_userChanges")&&e.level!=="node")return;let t={kind:"data",change:e},r=this.#s("_delay");r>0?this.#n.debounce(r,()=>this.invoke(t)):this.invoke(t)}invoke(e){if(this.binding.closed)return;let t=this.node,r=this.kind==="formula",o=this.kind==="rpc",i=this.kind==="remote",a=this.readArguments(e);e.askResult&&(Object.assign(a,e.askResult),a._askResult=e.askResult);let s=t.getAttr("_ask"),l=this.binding.runtime.askDialog;if(s&&!e.askDone&&l.required(this.binding,s,a,"_ask"))return l.show(this.binding,s,a,t.getAttr("_ask_title")??"Warning").then(p=>{if(!this.binding.closed){if(p===null){let m=t.getAttr("_ask_onCancel");m&&this.#l("_ask_onCancel",m,m,a,!0);return}return this.invoke({...e,askDone:!0,askResult:p})}});let[u,c]=[r?"formula":"script",t.getAttr(r?"formula":"script")],d=t.getAttr("_if");if(d&&!this.#l("_if",d,`return (${d})`,a,!1)){if(i&&this.#f(),[u,c]=["_else",t.getAttr("_else")],!c)return;if(o||i){this.#l(u,c,c,a,!0);return}}if(o)return this.#u(a);if(i)return this.#d(a);let f=t.getAttr("func"),h;if(c)h=this.#l(u,c,r?`return ${c}`:c,a,!0);else if(f==null){if(!r)return;h=new E($s(a))}else{let{group:p,method:m}=this.binding.runtime.logicRegistry.resolve(f,t);h=r?m.call(p,a):m.call(p,t,a)}r&&t.setRelativeData(t.pathAttribute("result_path"),h)}readArguments(e){let t=this.node,[,r]=t.rootBuilder.runtimeValues(t),o=Object.fromEntries(Object.entries(r).filter(([l])=>!c2.has(l)&&!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),i={...e.kind==="subscription"?e.payload:{},...this.binding.runtime.renderer.references.resolveArguments(o)};e.kind==="subscription"&&(i._subscription_kwargs=e.payload,i._subscription_metadata=e.metadata);let a=e.change??null,s=a?a.level:e.kind==="subscription"?e.topic:e.kind;return i._node=a?a.node:null,i._triggerpars={kw:a,trigger_reason:s},i._reason=s,e.kind==="click"&&(Object.assign(i,d2(e)),e.rowContext&&Object.assign(i,e.rowContext,{event:e.event})),i}cancel(){this.#n.cancel()}#a(){this.#n.startTiming(this.#s("_timing"),()=>this.invoke({kind:"timing",change:null}))}#s(e){let t=this.node,r=t.getAttr(e);return re(r)?Ir(t,e):t.pointerType(r)?t.getRelativeData(r):r??null}#l(e,t,r,o,i){let a=[...i?["_kwargs"]:[],...im,...am,...Object.keys($s(o))];return["_onCalling","_onResult","_onError","_ask_onCancel"].includes(e)?Ut(this.binding.runtime,this.node,e,t,{...o,_kwargs:o},a):this.binding.runtime.inlineCompiler.compile(this.node,e,t,a,r)({...o,_kwargs:o})}async#u(e){let t=this.node,[r,o,i]=["_onCalling","_onResult","_onError"].map(s=>t.getAttr(s)),a=t.requests;if(a.calling(r?()=>this.#l("_onCalling",r,r,e,!0):null))return a.submit(this.#s("method"),$s(e),s=>this.#c(s,e,o,i))}async#c(e,t,r,o){if(this.binding.closed)return;let i=this.node,a=this.#s("timeout"),s=a>0?setTimeout(()=>{let c=new Error(`${i.nodeTag} '${i.label}': no answer within ${a} ms`);c.name="TimeoutError",e.controller.abort(c)},a):null,l;try{l={result:await this.binding.call("data",e)}}catch(c){l={error:c}}if(clearTimeout(s),this.binding.closed||e.ignored)return;if("error"in l){if(!o)throw l.error;this.#l("_onError",o,o,{...t,error:l.error},!0);return}let{result:u}=l;i.getAttr("result_path")!=null&&i.setRelativeData(i.pathAttribute("result_path"),u),r&&this.#l("_onResult",r,r,{...t,result:u},!0)}#d(e){this.#f();let t=this.#i;this.#i=!1;let r=this.node,o=r.absDatapath(r.pathAttribute("destination_path"));if(o===null)return;let i=r.getAttr("_onCalling"),a=new mo({binding:this.binding,method:this.#s("method"),params:$s(e),cacheTime:this.#s("cacheTime"),sync:this.#s("sync")!==!1&&this.binding.runtime.gramlot.rpc.supportsCallSync,onCalling:i?()=>this.#l("_onCalling",i,i,e,!0):null,onError:s=>{throw new Error(`${r.nodeTag} '${r.label}': dataRemote '${a.method}' failed: ${s.message}`,{cause:s})}});this.binding.runtime.data.setResolver(o,a),this.#o={path:o,resolver:a},t&&a.refresh()}#f(){if(!this.#o)return;let{path:e,resolver:t}=this.#o;this.#o=null,this.#i=t.loaded||t.loading!==null;let r=this.binding.runtime.data.getNode(e);r?.resolver===t&&(r.resolver=null)}#p(){for(let e of this.#t.splice(0))e.close();this.#r.clear()}},Ms=class extends go{get kind(){return"formula"}},Ps=class extends go{get kind(){return"controller"}},Ls=class extends go{get kind(){return"rpc"}},Fs=class extends go{get kind(){return"remote"}},im=["_node","_triggerpars","_reason","_subscription_kwargs","_subscription_metadata","_askResult"],am=["_evt","button_counter","button_shift","button_ctrl","button_alt","button_meta"];function $s(n){let e={...n};for(let t of[...im,...am])delete e[t];return e}function d2({event:n,counter:e}){return{_evt:n,button_counter:e,button_shift:!!n.shiftKey,button_ctrl:!!n.ctrlKey,button_alt:!!n.altKey,button_meta:!!n.metaKey}}var f2=[[null,/(\W|^)GET (?:\s*)(\^?[\w.#@$?-]+)/g,"$1this.GET('$2')"],[/;SET/g,/(\W|^)SET (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm,"$1this.SET('$2', $3)$4 "],[/;PUT/g,/(\W|^)PUT (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm,"$1this.PUT('$2', $3)$4 "],[/;FIRE_AFTER/g,/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g,"$1this.FIRE_AFTER('$2', $3)$4 "],[/;FIRE_AFTER/g,/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g,"$1this.FIRE_AFTER('$2')$3 "],[/;FIRE/g,/(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g,"$1this.FIRE('$2', $3)$4 "],[/;FIRE/g,/(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g,"$1this.FIRE('$2')$3 "]],h2=/(\W|^)PUBLISH (?:\s*)(\^?[\w.#@$?-]+)/,p2=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),js=class{#e;#t=new Map;constructor(e){this.#e=e}get runtime(){return this.#e}get size(){return[...this.#t.values()].reduce((e,t)=>e+t.size,0)}preprocess(e,t,r){let o=r.trim();if(h2.test(o))throw new Error(`${$i(e,t)}: the PUBLISH macro is excluded from Gramlot`);let i=o.replace(/\$(\d+)/g,(a,s)=>`arguments[${parseInt(s,10)-1}]`);for(let[a,s,l]of f2)a&&(i=i.replace(a,`; ${a.source.slice(1)}`)),i=i.replace(s,l);return i!==o&&console.warn(`${$i(e,t)}: legacy macros are deprecated; write this.GET(path), this.SET(path, value), this.PUT(path, value), this.FIRE(path, value), this.FIRE_AFTER(path, value) and arguments[n] in place of GET, SET, PUT, FIRE, FIRE_AFTER and $n`),i}compile(e,t,r,o,i=r){if(e.activatedCode(t)!==r)throw new Error(`${$i(e,t)}: inline code runs only as received with the Source (main or a remote Source); a text written later is not run: use named logic`);let a=this.#t.get(e);a||(a=new Map,this.#t.set(e,a),this.runtime.bindingFor(e).track(()=>this.release(e)));let s=a.get(t);s?.source!==i&&(s={source:i,text:this.preprocess(e,t,i),key:null,run:null},a.set(t,s));let l=o.filter(m2),u=l.join(",");if(s.key!==u){let c=g2(e,t,s.text,l);s.key=u,s.run=d=>c.apply(e,l.map(f=>d[f]))}return s.run}compileExpression(e,t,r){let o=r.slice(2).trim(),i=Le(e.getAttr()).filter(([,s])=>!mt(s)),a=this.compile(e,t,r,[...i.map(([s])=>s).filter(s=>s!=="_F"),"_F"],`return ${o}`);return s=>{let l={};for(let[u,c]of i)Object.hasOwn(s,u)?l[u]=s[u]:l[u]=e.pointerType(c)?e.getRelativeData(c):c;return a({...l,_F:(u,c)=>this.runtime.gramlot.format(u,c)})}}compilePointerExpression(e,t,r,o){let i=this.compile(e,t,r,["_pointerValues","_F"],`return (${o}
|
|
227
|
-
)`);return a=>i({_pointerValues:a,_F:(s,l)=>this.runtime.gramlot.format(s,l)})}release(e,t=null){if(t===null){this.#t.delete(e);return}let r=this.#t.get(e);if(r)for(let o of t){r.delete(o);for(let[i]of Le({[o]:null}))r.delete(i)}}};function
|
|
223
|
+
`,this.shadowRoot.append(t),this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>this.refreshIconOnly())}connectedCallback(){super.connectedCallback();let e={childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["hidden","slot"]};this.#t.observe(this,e),this.#t.observe(this.control,e),this.refreshIconOnly()}disconnectedCallback(){this.#t.disconnect()}releaseControl(){this.#t.disconnect(),super.releaseControl()}refreshIconOnly(){let e=o=>o.nodeType===3?!!o.textContent.trim():o.nodeType===1&&!o.hidden&&o.getAttribute("slot")!=="menu",t=!this.caption.hidden&&this.caption.assignedNodes().some(e),r=[...this.control.children].some(o=>o!==this.icon&&o!==this.caption&&!o.hidden&&!o.matches(".led,.menu-check,.menu-arrow")&&!(o.matches(".menu-caption")&&this.control.classList.contains("toolbar-tooltip"))&&!!o.textContent.trim());this.control.classList.toggle("icon-only",!this.control.classList.contains("menu-row")&&!!(this.icon.textContent||this.icon.firstElementChild)&&!t&&!r)}get disabled(){return this.control.disabled}set disabled(e){this.control.disabled=!!e}projectAttributes(e,t){let r=super.projectAttributes(e,t);return this.control.disabled=!!this.parameters.disabled,this.control.readOnly=!!this.parameters.readonly,this.renderIcon(this.parameters.icon,this.parameters.iconSrc),e["aria-label"]!=null?this.control.setAttribute("aria-label",e["aria-label"]):this.control.removeAttribute("aria-label"),this.#e&&this.setActionPresentation(this.#e),r}renderIcon(e,t){if(!t){this.icon.textContent=e??"",this.refreshIconOnly();return}let r=this.icon.firstElementChild;r||(r=this.ownerDocument.createElement("img"),r.alt="",r.draggable=!1,this.icon.replaceChildren(r)),r.getAttribute("src")!==t&&r.setAttribute("src",t),this.refreshIconOnly()}get entryIcon(){return this.parameters.icon}get entryIconSrc(){return this.parameters.iconSrc}setActionPresentation(e){this.#e=e,this.hidden=e.hidden,this.icon.textContent=e.icon,this.title=e.title,this.control.setAttribute("aria-label",e.title),this.refreshIconOnly()}attachCommand(){}releaseCommand(){}commandTarget(){return this}prepareCommand(){return!this.disabled}}}Ei.parameters={action:{dtype:"T",nullable:!0},disabled:{dtype:"B",default:!1,binding:"read"},icon:{dtype:"T",default:"",binding:"read"},iconSrc:{dtype:"T",default:"",binding:"read"}};var vv=Dr({name:"button",tag:"gramlot-button",base:Ei,command:!0,subTags:"*",implementation:n=>class extends n{}}),Ev=Dr({name:"toggleButton",tag:"gramlot-toggle-button",base:Ei,command:!0,subTags:"*",parameters:{value:{dtype:"B",default:!1,binding:"twoWay"},readonly:{dtype:"B",default:!1,binding:"read"}},implementation:n=>class extends n{#e=!1;constructor(){super();let e=this.ownerDocument.createElement("span");e.className="led",e.setAttribute("aria-hidden","true"),this.control.prepend(e),this.writeControlValue(!1)}get commitOnChange(){return!0}readControlValue(){return this.#e}writeControlValue(e){this.#e=e,this.control.setAttribute("aria-pressed",String(e))}prepareCommand(e){return!super.prepareCommand(e)||this.control.readOnly?!1:(this.writeControlValue(!this.#e),this.control.dispatchEvent(new this.ownerDocument.defaultView.Event("change")),!0)}}}),xv=Dr({name:"menu",tag:"gramlot-menu",base:Tp,subTags:"menuline,spacer,contentPane",parameters:{presentation:{dtype:"T",default:"popup",enum:["popup","bar"]},orientation:{dtype:"T",default:"horizontal",enum:["horizontal","vertical"]},modifiers:{dtype:"T",nullable:!0},labelPosition:{dtype:"T",binding:"read",default:"beside",enum:["beside","below","tooltip"]},iconSize:{dtype:"R",binding:"read",default:24},resolver:{dtype:"T",nullable:!0},cacheTime:{dtype:"R",default:-1},sync:{dtype:"B",default:!1}},implementation:n=>class extends n{}}),kv=Dr({name:"menuline",tag:"gramlot-menu-line",base:Ei,command:!0,subTags:"*",parameters:{command:{dtype:"T",nullable:!0},caption:{dtype:"T",nullable:!0},code:{dtype:"T",nullable:!0},checked:{dtype:"B",nullable:!0,binding:"read"},tooltip:{dtype:"T",nullable:!0},labelPosition:{dtype:"T",binding:"read",nullable:!0,enum:["beside","below","tooltip"]},iconSize:{dtype:"R",binding:"read",nullable:!0},group:{dtype:"B",default:!1},parameters:{annotation:{kind:"type",module:"builtins",name:"dict"},nullable:!0},favorite:{dtype:"B",default:!1}},implementation:Ap}),Tv=Dr({name:"spacer",tag:"gramlot-spacer",base:n=>class extends n{projectAttributes(e){let t=io(this,e),{size:r,flex:o}=this.parameters;if(r!=null&&o!=null)throw new TypeError("spacer accepts size or flex, not both");if(r!=null&&(!Number.isFinite(r)||r<0)||o!=null&&(!Number.isFinite(o)||o<=0))throw new TypeError("Invalid spacer size/flex");return this.style.flex=o!=null?`${o} 1 0px`:`0 0 ${r??0}px`,this.setAttribute("aria-hidden","true"),t}},parameters:{size:{dtype:"R",nullable:!0},flex:{dtype:"R",nullable:!0}},implementation:n=>class extends n{}}),Av=Dr({name:"dropDownButton",tag:"gramlot-drop-down-button",base:Ei,command:!0,subTags:"*",parameters:{persist:{dtype:"B",default:!1}},implementation:n=>class extends n{#e=null;#t;#r=null;#n;#o;constructor(){super();let e=this.ownerDocument;this.control.classList.add("split"),this.controlBox.classList.add("choice-field");let t=e.createElement("style");t.textContent=wp+".split{border-radius:var(--gramlot-radius-sm,4px);padding-inline-end:calc(var(--gramlot-choice-toggle-width,1.6em) + .5em)}",this.shadowRoot.append(t),this.#o=e.createElement("span"),this.#o.hidden=!0,this.control.append(this.#o),this.#n=e.createElement("button"),this.#n.type="button",this.#n.className="arrow choice-toggle",this.#n.setAttribute("aria-label","Open menu"),this.#n.setAttribute("aria-haspopup","menu"),this.#n.setAttribute("aria-expanded","false"),this.controlBox.append(this.#n);let r=e.createElement("slot");r.name="menu",this.shadowRoot.append(r),this.#n.addEventListener("click",o=>{o.stopPropagation(),this.menu.opened?this.closeMenu():this.openMenu()}),this.#n.addEventListener("keydown",o=>{["ArrowDown","ArrowUp"].includes(o.key)&&(o.preventDefault(),this.openMenu(o.key==="ArrowUp"))})}get menu(){return[...this.children].map(Je).find(e=>e.localName==="gramlot-menu")}get menuItems(){return this.menu?.items??[]}projectAttributes(e,t){let r=super.projectAttributes(e,t);return this.#n.disabled=this.disabled,this.disabled&&this.menu?.close(!1),this.#i(),r}attachCommand(){if(this.parameters.persist){if(!this.id)throw new TypeError("dropDownButton persist requires an explicit id");this.#r=`gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;try{this.#e=this.ownerDocument.defaultView.localStorage.getItem(this.#r)}catch{}}this.#i(),this.#t=new this.ownerDocument.defaultView.MutationObserver(()=>this.#i()),this.#t.observe(this,{childList:!0,subtree:!0,characterData:!0})}releaseCommand(){this.#t?.disconnect(),this.menu?.close(!1)}commandTarget(e){return e?.composedPath().includes(this.menu)?null:this.menuItems.find(t=>t.occurrence===this.#e)??this}selectCommand(e,t){if(t){if(this.#e=e.occurrence,this.#r)try{this.ownerDocument.defaultView.localStorage.setItem(this.#r,this.#e)}catch{}this.#i()}this.closeMenu()}#i(){let e=this.menuItems.map(o=>o.occurrence).filter(Boolean);if(new Set(e).size!==e.length)throw new TypeError("Dropdown menu codes must be unique");let t=this.commandTarget(),r=t!==this;this.caption.hidden=r,this.#o.hidden=!r,this.#o.textContent=r?t.entryCaption:"",this.renderIcon(t.entryIcon,t.entryIconSrc)}openMenu(e=!1){this.disabled||this.menu?.open(this.#n,e)}closeMenu(){this.menu?.close()}}}),gs=Ku({name:"buttons",components:[vv,Ev,Av,xv,kv,Tv]});var ho=class{epoch=0;controller=null;cancel(){this.epoch++,this.controller?.abort(),this.controller=null}start(e,t,r,o,i,a=()=>{}){this.cancel();let s=new AbortController,l=this.epoch;this.controller=s;let u=r.validationCurrent(),c=()=>l===this.epoch&&!s.signal.aborted&&u(),d=m=>({value:e,modified:!1,error:m.message,warnings:[],issues:[],datachanges:[]}),f=!1,h=m=>{if(f||!c())return{ok:!1};f=!0,this.controller=null;let b={ok:!m.error,value:m.value,result:m,rules:t,isCurrent:c};return i(b),b},p;try{if(t.validate_timeout!=null&&(!Number.isInteger(t.validate_timeout)||t.validate_timeout<=0))throw new TypeError("validate_timeout must be a positive integer in milliseconds.");p=o(e,t,{...r,signal:s.signal})}catch(m){return h(d(m))}return p instanceof Promise?(a(),new Promise(m=>{let b,w=()=>{clearTimeout(b),m({ok:!1})};s.signal.addEventListener("abort",w,{once:!0});let _=y=>{clearTimeout(b),s.signal.removeEventListener("abort",w);try{m(h(y))}catch(x){r.reportError(x,"Validation completion failed"),m({ok:!1})}};t.validate_timeout!=null&&(b=setTimeout(()=>{_(d(new Error("Validation timed out."))),s.abort()},t.validate_timeout)),p.then(_,y=>_(d(y)))})):h(p)}};function xi(n){return typeof n=="string"&&!["null","true","false"].includes(n)&&/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(n)}function er(n,e,t,r){let{group:o,method:i}=n.logicRegistry.resolve(t,e);return i.call(o,e,r)}function Ut(n,e,t,r,o,i=Object.keys(o)){return xi(r)?er(n,e,r,o):n.inlineCompiler.compile(e,t,r,i)(o)}function bs(n){let e=n.node,t=n.runtime.gramlot,r=(o,i,a,s=!1)=>s?n.runtime.inlineCompiler.compile(e,o,i,Object.keys(a),`return (${i});`)(a):Ut(n.runtime,e,o,i,a);return{isDecimal:le,invoke:r,callLogic:(o,i)=>er(n.runtime,e,o,i),remote:(o,i,a)=>t.rpc.call("data",o,i,{signal:a}),reportError:(o,i)=>{n.closed||n.runtime.reportError(o,i)},validationCurrent:()=>{let o=e.getAttr("value"),i=e.pointerType(o)?e.absDatapath(o):null;return()=>!n.closed&&e.getAttr("value")===o&&(i===null||e.absDatapath(o)===i)},finishValidation:({ok:o,result:i,rules:a})=>{if(n.closed)return;if(o)for(let l of i.datachanges)e.getRelativeData(".").update(l);let s=o?"validate_onAccept":"validate_onReject";if(a[s]){let l=u=>{n.closed||n.runtime.reportError(u,"Validation callback failed")};try{let u=Object.fromEntries(Object.entries(a).map(([d,f])=>[d.slice(9),f])),c=r(s,a[s],{value:i.value,result:i,validations:u,userChange:!0});c instanceof Promise&&c.catch(l)}catch(u){l(u)}}},checkDataPatch:o=>{if(!(o instanceof E))throw new TypeError("Validation data changes must be a Bag.");if(!(e.getRelativeData(".")instanceof E))throw new TypeError("Validation data changes require a Bag datapath.")}}}var Nr=n=>j(L(n)),sn=(n,e)=>L(n)===L(e),ki=n=>n.absDatapath(n.getAttr("value")),gt=n=>encodeURIComponent(n).replaceAll(".","%2E"),Ir=n=>gt(ki(n)),Dp=(n,e)=>gt(n.fullpath)+":"+e,Ti=class{constructor(e,t,r=e.absDatapath(".")){if(this.node=e,this.runtime=t,this.registers=new E,this.validationQueue=new Set,this.fields=new Map,this.validations=new Map,this.disposed=!1,this.scheduled=!1,this.writing=0,this.path=r,this.retainedFields=new Map,this.listeners=new Set,this.navigators=new Set,this.validationSources=new Set,this.validationDependencies=new Map,this.validationRevision=0,this.validatedRevision=-1,this.fullValidation=null,this.derived=new Set,!(this.data instanceof E))throw new TypeError("A form requires a Bag at its datapath.");this.registers.setItem("baseline",Nr(this.data));for(let o of["changes","errors","pending","drafts"])this.registers.setItem(o,new E);this.subscription=t.router.register({path:this.path,recipient:this,subtree:!0}),t.bindingFor(e).track(()=>this.dispose())}rebind(){let e=this.node.absDatapath(".");if(e!==this.path){if(!(this.data instanceof E))throw new TypeError("A form requires a Bag at its datapath.");this.subscription.close();for(let t of["errors","pending","drafts"])this.registers.setItem(t,new E);this.path=e,this.subscription=this.runtime.router.register({path:e,recipient:this,subtree:!0}),this.updateChanges();for(let t of this.fields.values())t.element.cancelValidation(),this.clearDraft(t.node),this.scheduleValidation(t)}}get data(){return this.runtime.gramlot.data.getItem(this.path)}registerDerived(e){return this.derived.add(e),this.updateChanges(),()=>{this.derived.delete(e)}}isDerived(e){for(let t of this.derived)if(t(e))return!0;return!1}ownAttributes(e,t){return Object.fromEntries(Object.entries(e.attr).filter(([r])=>!this.isDerived(`${t}?${r}`)))}onlyDerived(e,t){return e?Object.keys(this.ownAttributes(e,t)).length?!1:e.value instanceof E?e.value.getNodes().every(r=>this.onlyDerived(r,t?`${t}.${r.label}`:r.label)):this.isDerived(t):!0}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get errorEntries(){return this.registers.getItem("errors").getNodes().map(e=>({path:decodeURIComponent(e.label),message:e.value.getNodes().map(t=>t.value).join(`
|
|
224
|
+
`)}))}get changeEntries(){let e=[];for(let t of this.registers.getItem("changes").getNodes()){let r=t.value,o=[this.path,r.getItem("path")].filter(Boolean).join("."),i=r.getItem("existed"),a=r.getItem("exists"),s=r.getItem("previous"),l=r.getItem("current");if((!i||!a||!sn(s,l))&&e.push({path:o,previous:s,current:l,existed:i,exists:a}),i&&a){let u=r.getItem("previousAttributes"),c=r.getItem("currentAttributes");for(let d of new Set([...u.getNodes(),...c.getNodes()].map(f=>f.label))){let f=u.getNode(d)!==null,h=c.getNode(d)!==null;(f!==h||!sn(u.getItem(d),c.getItem(d)))&&e.push({path:o+"?"+d,previous:u.getItem(d),current:c.getItem(d),existed:f,exists:h})}}}return e}registerNavigator(e){return this.navigators.add(e),()=>this.navigators.delete(e)}focusField(e){if(this.disposed)return!1;for(let t of this.fields.values())if(ki(t.node)===e&&t.element.isConnected)return t.element.control.focus(),!0;for(let t of this.navigators)if(t(e))return!0;return!1}retainField(e){this.retainedFields.set(e,(this.retainedFields.get(e)??0)+1)}releaseField(e){let t=this.retainedFields.get(e);if(t>1){this.retainedFields.set(e,t-1);return}if(this.retainedFields.delete(e),![...this.validations.values()].some(r=>r.path===e)){for(let r of["errors","pending","drafts"]){let o=this.registers.getItem(r),i=gt(e);o.getNode(i)&&o.popNode(i)}this.notify()}}fieldStatus(e){let t=gt(e);return{error:this.registers.getItem("errors").getItem(t),pending:this.registers.getItem("pending").getItem(t),draft:this.registers.getItem("drafts").getItem(t)}}get status(){let e=this.registers.getItem("changes").length>0,t=this.fullValidation!==null||this.registers.getItem("pending").length>0,r=this.registers.getItem("errors").length>0,o=this.registers.getItem("drafts").length>0;return{dirty:e,pending:t,valid:!r&&!o,canSave:e&&!r&&!o&&!t,status:r?"error":t||o?"pending":e?"changed":"ok"}}register(e){let t=e.node;this.fields.set(t,e);let r=this.registerField(t,e.element.constructor);return r.selection=e.element.validationSelection(),this.schedule(()=>{if(this.fields.get(t)!==e)return;let o=this.registers.getItem("drafts").getNode(Ir(t));o&&(t.formDraft=o.value,e.element.restoreFormDraft(o.value)),r.result&&e.element.presentValidation(r.result);let i=this.registers.getItem("errors").getItem(Ir(t));i&&e.element.error(i.getNodes().map(a=>a.value).join(`
|
|
225
|
+
`)),e.element.setFieldState({invalid:!!i,pending:!!this.fieldStatus(r.path).pending})}),()=>{this.fields.delete(t)}}registerField(e,t,r=!0){let o=this.validations.get(e);if(o)return o;if(!t.validationExecutor)throw new TypeError("Grid editors require shared input validation.");let i=this.runtime.bindingFor(e),a=bs(i);return o={node:e,binding:i,context:a,component:t,run:new ho,execute:t.validationExecutor,checkValue:t.validationValueCheck(a),path:ki(e),rules:null,value:void 0,target:null,result:null,selection:null},this.validations.set(e,o),i.editingSession=this,o.release=i.track(()=>this.forgetField(e)),this.refreshField(e,r),o}registerValidationSource(e){return this.validationSources.add(e),this.invalidateValidation(),()=>{this.validationSources.delete(e),this.invalidateValidation()}}invalidateValidation(){if(this.validationRevision++,this.fullValidation)for(let e of this.fullValidation.active)this.cancelValidation(e)}trackValidationDependency(e){if(e===null||this.validationDependencies.has(e))return;let[t,r=null]=e.split("?",2);this.validationDependencies.set(e,this.runtime.router.register({path:t,attr:r,subtree:!0,recipient:{receive:()=>this.invalidateValidation()}}))}clearValidationDependencies(){for(let e of this.validationDependencies.values())e.close();this.validationDependencies.clear()}validate(){if(this.disposed)return Promise.resolve(!1);if(this.fullValidation)return this.fullValidation.promise;for(let a of this.fields.values())Object.hasOwn(a.node,"formDraft")&&a.commit();this.clearValidationDependencies();let e={revision:this.validationRevision,promise:null,active:new Set,failed:!1,complete:!0};this.fullValidation=e,this.notify();let t=this.validationFields(),r=()=>!this.disposed&&!e.failed&&e.revision===this.validationRevision,o=new WeakSet,i=async()=>{let a=0;for(;r();){let s=t.next();if(s.done)return;let{node:l,release:u}=s.value;try{if(o.has(l))continue;o.add(l);for(let[d,f]of l.pointers())d!=="value"&&this.trackValidationDependency((d==="datapath"?l.parentNode:l).absDatapath(f));e.active.add(l),(await this.validateField(l))?.ok||(e.complete=!1)}finally{e.active.delete(l),u()}++a%20===0&&await new Promise(c=>setTimeout(c,0))}};return e.promise=Promise.resolve().then(async()=>{let s=(await Promise.allSettled(Array.from({length:8},()=>i().catch(u=>{e.failed=!0;for(let c of e.active)this.cancelValidation(c);throw u})))).find(u=>u.status==="rejected");if(s)throw s.reason;if(!r())return!1;let l=e.complete&&this.status.valid&&this.registers.getItem("pending").length===0;return l&&(this.validatedRevision=this.validationRevision),l}).finally(()=>{t.return(),this.fullValidation=null,this.notify()}),e.promise}*validationFields(){let e=[...this.validations.keys()];for(let t of this.validationSources)yield*t();for(let t of e)this.validations.has(t)&&(yield{node:t,release:()=>{}})}forgetField(e){let t=this.validations.get(e);if(t){t.run.cancel(),t.release(),t.binding.editingSession===this&&(t.binding.editingSession=null),this.validations.delete(e),this.validationQueue.delete(e);for(let r of["errors","pending"]){let o=this.registers.getItem(r).getItem(gt(t.path));if(o){for(let i of[...o.getNodes()])i.label.startsWith(gt(e.fullpath)+":")&&o.popNode(i.label);o.length||this.registers.getItem(r).popNode(gt(t.path))}}if(![...this.validations.values()].some(r=>r.path===t.path)){let r=this.registers.getItem("drafts");r.getNode(gt(t.path))&&r.popNode(gt(t.path))}delete e.formDraft,this.notify()}}refreshField(e,t=!0){let r=this.validations.get(e);if(!r||this.disposed||this.writing)return;let[,o]=e.rootBuilder.runtimeValues(e),i=r.component.validationParameters(this.runtime.renderer.evaluateExpressions(e,o)),a=Object.fromEntries(Object.entries(i).filter(([f])=>f.startsWith("validate_"))),s=L(Object.fromEntries(Object.entries(i).filter(([f])=>f!=="value"))),l=ki(e),u=this.runtime.gramlot.data.getNode(l.split("?")[0]),c=e.getRelativeData(e.getAttr("value")),d=r.path!==l||r.target!==u||!sn(r.value,c);if(!(!d&&r.configuration===s)){if(r.rules!==null&&this.invalidateValidation(),this.cancelValidation(e),r.path!==l)for(let f of["errors","pending","drafts"]){let h=this.registers.getItem(f);h.getNode(gt(r.path))&&h.popNode(gt(r.path))}Object.assign(r,{path:l,target:u,value:c,rules:a,configuration:s,result:null,selection:r.component.validationSelection(i,r.context)}),d&&this.clearDraft(e),t&&this.scheduleField(e)}}cancelValidation(e){this.validations.get(e)?.run.cancel(),this.validationQueue.delete(e),this.pendingPart(e,"validation",null)}writeCandidate(e,t){this.clearDraft(e),this.writing++;try{this.runtime.renderer.html.writeParameter(e,"value",t)}finally{this.writing--}let r=this.validations.get(e);r&&(r.value=e.getRelativeData(e.getAttr("value")),r.target=this.runtime.gramlot.data.getNode(r.path.split("?")[0]));for(let o of this.validations.keys())o!==e&&this.refreshField(o)}validateCandidate(e,t,r){this.invalidateValidation(),this.cancelValidation(e),this.writeCandidate(e,t);let o=this.validations.get(e);return o.selection=r,this.validateField(e,!1)}scheduleField(e){this.disposed||!this.validations.has(e)||this.validationQueue.has(e)||this.registers.getItem("drafts").getNode(Ir(e))||(this.validationQueue.add(e),this.pendingPart(e,"validation","scheduled"),this.schedule(()=>{this.validationQueue.delete(e)&&this.validateField(e)}))}scheduleValidation(e){this.refreshField(e.node);let t=this.validations.get(e.node);t&&!t.result&&!t.run.controller&&this.scheduleField(e.node)}validateField(e,t=!0){let r=this.validations.get(e);if(!r||this.disposed||r.binding.closed||(this.validationQueue.delete(e),this.registers.getItem("drafts").getNode(Ir(e)))||this.registers.getItem("pending").getItem(Ir(e))?.getItem(Dp(e,"selection")))return;let o=e.getRelativeData(e.getAttr("value")),i=this.fields.get(e);t&&i&&(r.selection=i.element.validationSelection());let a=r.selection,s=r.target,l=r.context.validationCurrent();return r.run.start(o,r.rules,{...r.context,validationCurrent:()=>()=>!this.disposed&&l()&&this.validations.get(e)===r&&this.runtime.gramlot.data.getNode(r.path.split("?")[0])===s,selection:a},r.execute,u=>{if(u.ok)try{r.checkValue(u.value,o)}catch(d){u.ok=!1,u.result.error=d.message}this.result(e,u.result),r.result=u.result,u.ok&&this.writeCandidate(e,u.value);let c=this.fields.get(e);c&&c.element.presentValidation(u.result),r.context.finishValidation(u)},()=>{this.pendingPart(e,"validation","active"),this.fields.get(e)?.element.setFieldState({pending:!0})})}remove(e,t){let r=this.registers.getItem(e),o=Ir(t);r.getNode(o)&&r.popNode(o)}set(e,t,r){r==null?this.remove(e,t):this.registers.getItem(e).setItem(Ir(t),r),this.notify()}draft(e,t){this.invalidateValidation(),this.cancelValidation(e),e.formDraft=t,this.set("drafts",e,t)}clearDraft(e){delete e.formDraft,this.set("drafts",e,null),this.issue(e,"parse",null)}result(e,t){this.pendingPart(e,"validation",null),this.issue(e,"validation",t.error||null)}part(e,t,r,o){r=Dp(t,r);let i=this.registers.getItem(e),a=Ir(t),s=i.getItem(a);!s&&o!=null&&(s=new E,i.setItem(a,s)),s&&(o==null?s.getNode(r)&&s.popNode(r):s.setItem(r,o),s.length||this.remove(e,t)),this.notify()}issue(e,t,r){this.part("errors",e,t,r||null)}pendingPart(e,t,r){this.part("pending",e,t,r)}parseError(e,t){this.issue(e,"parse",t)}schedule(e){queueMicrotask(()=>{this.disposed||e()})}receive(e){if(!this.disposed&&(this.updateChanges(e.path),!this.writing)){this.invalidateValidation();for(let t of this.validations.keys())this.refreshField(t)}}updateChanges(e=null){let t=this.registers.getItem("changes"),r=e===this.path?"":e?.startsWith(this.path+".")?e.slice(this.path.length+1).split("?")[0]:"",o=(l,u,c)=>{if(c&&this.isDerived(c))return;let d=l&&this.ownAttributes(l,c),f=u&&this.ownAttributes(u,c);if(l&&u&&l.value instanceof E&&u.value instanceof E&&sn(d,f)){let h=new Set([...l.value.getNodes(),...u.value.getNodes()].map(p=>p.label));for(let p of h)o(l.value.getNode(p),u.value.getNode(p),c?c+"."+p:p)}else(l&&u?!sn([l.value,d],[u.value,f]):!(this.onlyDerived(l,c)&&this.onlyDerived(u,c)))&&t.setItem(gt(c),new E({path:c,existed:!!l,exists:!!u,previous:l?Nr(l.value):null,current:u?Nr(u.value):null,previousAttributes:l?Nr(d):null,currentAttributes:u?Nr(f):null}))},i=this.registers.getItem("baseline"),a=r;for(let l of t.getNodes()){let u=l.value.getItem("path");a.startsWith(u+".")&&(a=u)}let s=a;for(;s.includes(".");){s=s.slice(0,s.lastIndexOf("."));let l=i.getNode(s),u=this.data.getNode(s);(!l||!u||!sn(l.attr,u.attr))&&(a=s)}for(let l of[...t.getNodes()]){let u=l.value.getItem("path");(!a||u===a||u.startsWith(a+"."))&&t.popNode(l.label)}a?o(i.getNode(a),this.data.getNode(a),a):o({value:i,attr:{}},{value:this.data,attr:{}},""),this.notify()}notify(){this.disposed||this.scheduled||(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1;let e=this.status,t=this.registers.getItem("status");(!t||!sn(t,new E(e)))&&(this.registers.setItem("status",new E(e)),this.node.publish("formStatus",e));for(let r of this.listeners)r()}))}commitField(e){for(let t of this.fields.values())ki(t.node)===e&&Object.hasOwn(t.node,"formDraft")&&t.commit()}accept(){if(this.disposed)return!1;for(let e of this.fields.values())Object.hasOwn(e.node,"formDraft")&&e.commit();return!this.status.valid||this.status.pending||this.validationSources.size&&this.validatedRevision!==this.validationRevision?!1:(this.registers.setItem("baseline",Nr(this.data)),this.updateChanges(),!0)}load(e){if(!(e instanceof E))throw new TypeError("Editing load requires a Bag.");this.disposed||(this.registers.setItem("baseline",Nr(e)),this.restore())}restore(){if(!this.disposed){this.invalidateValidation();for(let e of this.validations.keys())this.cancelValidation(e);for(let e of this.fields.values())e.element.cancelValidation(),this.clearDraft(e.node),e.element.restoreFormValue(this.registers.getItem("baseline").getItem(e.node.absDatapath(e.node.getAttr("value")).slice(this.path?this.path.length+1:0)));this.runtime.gramlot.data.setItem(this.path,Nr(this.registers.getItem("baseline")));for(let e of["errors","pending","drafts"])this.registers.setItem(e,new E);this.updateChanges();for(let e of this.validations.keys())this.scheduleField(e)}}dispose(){if(!this.disposed){this.disposed=!0,this.subscription.close();for(let e of this.validations.keys())this.forgetField(e);this.fields.clear(),this.validationQueue.clear(),this.retainedFields.clear(),this.listeners.clear(),this.navigators.clear(),this.validationSources.clear(),this.clearValidationDependencies()}}};function Dv(n,e,t=n){let r=new Map,o=new Set,i=new Map;for(let[s,l]of e){if(typeof s!="string")continue;let u=ne(l)?.pointer??l;i.set(s,u instanceof fe?u.resolve():n.pointerType(u)?t.getRelativeData(u):mt(u)?null:u)}let a=s=>{if(r.has(s))return r.get(s);if(!e.has(s))throw new Error(`Source attribute '${s}' does not exist`);if(o.has(s))throw new Error(`cyclic attribute dependency: ${[...o,s].join(" -> ")}`);o.add(s);let l=e.get(s),u=ne(l),c=u?i.get(s):null,d,f=h=>h?a(h):c;try{if(u)if(u.expression){let h=si(u.body),p=h.slots.map(f);d=n.rootBuilder.evaluatePointerExpression(n,s,l,h,p)}else d=Xr(u.body,f),c==null&&(d=null);else d=i.get(s);return r.set(s,d),d}finally{o.delete(s)}};return{resolve:a}}function Or(n,e,t=n){let r=new Map([...Object.entries(n.getAttr()),...Le(n.getAttr())]);return Dv(n,r,t).resolve(e)}var Sv={dataFormula:["formula","_if","_else","_ask_if","_ask_onCancel"],dataController:["script","_if","_else","_ask_if","_ask_onCancel"],dataRpc:["_ask_if","_ask_onCancel","_if","_else","_onCalling","_onResult","_onError"],dataRemote:["_if","_else","_onCalling"]},Qu=["_cachedRemote","_if","_else","_onRemote","_onCalling","_delay","_timing","_userChanges"],Cv=["_if","_else","_onRemote","_onCalling"],ec=class{#e;#t=null;#r=null;#n=!1;constructor(e){this.#e=e}get inflight(){return this.#t?.view??null}get pending(){let e=this.#r;return e?Object.freeze({method:e.method,get params(){return j(e.text)}}):null}calling(e){if(!e)return!0;let t=!1,r=this.#n;this.#n=!0;try{t=e()!==!1}finally{this.#n=r,!t&&!this.#t&&this.#o()}return t}submit(e,t,r){try{let o=L(t);return this.#t?this.#r?Promise.resolve(void 0):new Promise((i,a)=>{this.#r={method:e,text:o,perform:r,resolve:i,reject:a}}):(this.#r?.resolve(void 0),this.#r=null,this.#i(e,t,o,r))}catch(o){return Promise.reject(o)}}submitSync(e,t){if(this.#t)throw new Error("A synchronous call cannot start while a request of the node is in flight");if(!this.#e.matches(e))throw new TypeError(`Method name must match ${this.#e.pattern}, not ${JSON.stringify(e)}`);return t()}#o(){let e=this.#r;if(!e)return;this.#r=null;let t;try{t=this.#i(e.method,j(e.text),e.text,e.perform)}catch(r){t=Promise.reject(r)}t.then(e.resolve,e.reject)}#i(e,t,r,o){if(!this.#e.matches(e))return Promise.reject(new TypeError(`Method name must match ${this.#e.pattern}, not ${JSON.stringify(e)}`));let i=new AbortController,a={method:e,params:t,text:r,controller:i,ignored:!1};a.view=Object.freeze({method:e,get params(){return j(r)},sentAt:Date.now(),cancel:()=>this.#s(a)}),this.#t=a,i.signal.addEventListener("abort",()=>this.#a(a),{once:!0});let s;try{s=Promise.resolve(o(a))}catch(l){s=Promise.reject(l)}return s.then(()=>this.#a(a),()=>this.#a(a)),s}#a(e){this.#t===e&&(this.#t=null,this.#o())}#s(e){this.#t===e&&(e.ignored=!0,this.#t=null,this.#n||this.#o())}};function Sp(n){return typeof n=="string"&&n.startsWith("==")}function Nv(n){let e=[],t=r=>{for(let o of r.getNodes())o.nodeTag==="column"&&typeof o.getAttr("formula")=="string"?e.push([`struct.${o.getAttr("field")}.formula`,o.getAttr("formula")]):(o._getMeta("gridStruct")||o.nodeTag==="colgroup")&&o.staticValue instanceof I&&t(o.staticValue)};return n.staticValue instanceof I&&t(n.staticValue),e}var ln=class extends Xe{#e=null;#t=null;get treeStore(){return this.#t}setTreeStore(e){if(this.nodeTag!=="tree")throw new TypeError("setTreeStore requires a tree Source node");if(e!==null&&!(e instanceof E))throw new TypeError("setTreeStore requires a Bag or null");if(e===this.#t)return;this.#t=e;let t=this.rootBuilder.binding,r=t?.bindingFor(this);r&&!r.closed&&(r.rebind(),t.renderer.attached(this)&&t.renderer.project(this))}get formState(){for(let e=this;e;e=e.parentNode){if(e.#e&&e._getMeta("gramlot_component")?.bagStore)return e.#e;if(e.getAttr("formId")!=null||e.getAttr("form")===!0){let t=e.#e??=new Ti(e,this.rootBuilder.binding);return t.rebind(),t}}return null}editCollection(e){let t=this.parentNode?.formState;if(t){if(e!==t.path&&!e.startsWith(t.path+"."))throw new Error("An edited grid in a form must use data within that form.");return t}if(this.#e&&this.#e.path!==e)throw new Error("An active grid editing session cannot change its storepath.");return this.#e??=new Ti(this,this.rootBuilder.binding,e)}get frame(){if(!["dialog","floatingPane"].includes(this.nodeTag))throw new TypeError("frame accessor requires a window");let e=this.value instanceof I?this.value.getNodes():[];if(e.length){if(e.length!==1||e[0].nodeTag!=="framePane")throw new TypeError("A window requires exactly one framePane");return this.builder.wrapSource(e[0])}return this.builder.wrapSource(this.builder.commandOnNode(this,"framePane",null,{node_label:"frame"}))}requestClose(e="application"){if(!["dialog","floatingPane"].includes(this.nodeTag))throw new TypeError("requestClose requires a window");return this.rootBuilder.binding.gramlot.dom.getDomNode(this).requestClose(e)}get grid(){if(this.nodeTag==="framePane"){let e=this.staticValue instanceof I?this.staticValue.getNode("center.grid"):null;if(!e||e.nodeTag!=="grid")throw new TypeError("This frame has no central grid");return this.builder.wrapSource(e)}return(e={})=>this.builder.wrapSource(this.builder.commandOnNode(this,"grid",null,e))}get toolbar(){if(this.nodeTag!=="framePane")throw new TypeError("toolbar accessor requires framePane");let e=this.staticValue instanceof I?this.staticValue.getNode("top.bar"):null;if(!e||e.nodeTag!=="menu")throw new TypeError("This frame has no toolbar");return this.builder.wrapSource(e)}get top(){return this.frameRegion("top")}get bottom(){return this.frameRegion("bottom")}get left(){return this.frameRegion("left")}get right(){return this.frameRegion("right")}get center(){return this.frameRegion("center")}frameRegion(e){if(this.nodeTag!=="framePane")throw new TypeError("Region accessors require framePane");let t=this.value instanceof I?this.value.getNodes().find(o=>o.getAttr("region")===e):null;if(t)return this.builder.wrapSource(t);let r={region:e,node_label:e};return e!=="center"&&Object.assign(r,{display:"flex",flex_direction:["top","bottom"].includes(e)?"column":"row"}),this.builder.wrapSource(this.builder.commandOnNode(this,"contentPane",null,r))}#r=new Set;#n=null;#o=null;get requests(){return this.#o??=new ec(this.rootBuilder.nameSyntax)}codeAttributes(){let e=[...Sv[this.nodeTag]??[],...Object.entries(this.parentNode?._getMeta("gramlot_component")?.childParameters??{}).filter(([,r])=>r.inline).map(([r])=>r),...this._getMeta("gramlot_component")?.command?["action","_ask_if"]:[],...typeof this.getAttr("remote")=="string"?Cv:[]],t=[];for(let[r,o]of Object.entries(this.getAttr()??{}))typeof o=="string"&&(e.includes(r)||r==="validate_call"||r==="validate__onResult"||r==="validate_onAccept"||r==="validate_onReject"||/^validate_\w+_if$/.test(r)||r.startsWith("connect_on")||r.startsWith("subscribe_")||r.startsWith("selfsubscribe_"))&&t.push([r,o]);for(let r of["ask","_ask"]){let o=this.getAttr(r);if(o&&typeof o=="object")for(let i of["_if","askIf"])typeof o[i]=="string"&&t.push([`${r}.${i}`,o[i]])}for(let[r,o]of Le(this.getAttr()))if(Sp(o)&&t.push([r,o]),this.nodeTag==="script"&&typeof o=="string"){let i=this.builder.constructor.dialectPrefixes.find(a=>r.startsWith(a))??"";["src","href","xlink:href","xlink_href","_text"].includes(r.slice(i.length).toLowerCase())&&t.push([r,o])}return(Sp(this.staticValue)||this.nodeTag==="script"&&typeof this.staticValue=="string")&&t.push(["",this.staticValue]),this._getMeta("gramlot_component")?.bagStruct&&t.push(...Nv(this)),t}activateCode(){let e=new Map;for(let[t,r]of this.codeAttributes()){if(this.pointerType(r))throw new Error(`${this.nodeTag} '${this.label}': '${t}' is inline code and cannot be the pointer '${r}'; inline code is never read from Data`);e.set(t,r)}for(let[t,r]of[...Le(this.getAttr()),["datapath",this.getAttr("datapath")]])ne(r)?.expression&&e.set(t,r);this.#n=e}activatedCode(e){return this.#n?.get(e)??null}remote(e,t={}){let r=this.rootBuilder.nameSyntax;if(typeof e!="string"||!(this.pointerType(e)||r.matches(e)))throw new TypeError(`${this.nodeTag} '${this.label}': remote name must be a pointer or match ${r.pattern}, not ${JSON.stringify(e)}`);let o=Object.keys(t).find(a=>a.startsWith("_")&&!Qu.includes(a));if(o)throw new TypeError(`${this.nodeTag} '${this.label}': remote parameter '${o}' is not accepted; the control attributes are ${Qu.join(", ")}`);let i={remote:e};for(let[a,s]of Object.entries(t))i[Qu.includes(a)?a:`remote_${a}`]=s;return this.setAttr(i),fi(this)}publish(e,t={}){return this.rootBuilder.binding.subscriptions.publishNode(this,e,t)}pointers(){let e=this.getAttr("datapath"),t=ne(e)?Ft(this,e):new Set,r=super.pointers().filter(([o,i])=>!(this.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(o))&&!t.has(o)&&!this.#s(o,i)).map(([o,i])=>[o,ne(i)?.pointer??i]);for(let o of t){let i=this.getAttr(o);this.pointerType(i)==="^"&&r.push(["datapath",ne(i)?.pointer??i])}return r}runtimeToEvaluate(){let e=super.runtimeToEvaluate();for(let[t,r]of e){if(this.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(t)){e.set(t,new xr(()=>r));continue}if(this.pointerType(r)){if(ne(r)){if(typeof t!="string")throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);this.absDatapath(r)===null&&e.set(t,new xr(()=>Or(this,t)));continue}this.#s(t,r)?e.set(t,r.slice(1)):this.absDatapath(r)===null&&e.set(t,null)}}return e}pathAttribute(e){let t=this.getAttr(e);return ne(t)?Or(this,e):this.pointerType(t)&&this.#s(e,t)?t.slice(1):t}getRelativeData(e,t=null,r={}){return this.absDatapath(e)===null?null:super.getRelativeData(e,t,r)}setRelativeData(e,t,r={}){this.#l(e),super.setRelativeData(e,t,r)}PUT(e,t){this.#l(e),this.data.setItem(this.absDatapath(e),t,null,">",!1,!0,this,!1,!1)}FIRE(e,t=!0,r=null){t===null&&(t=!0),this.#l(e);let o=this.absDatapath(e);if(o.includes("?")){this.#i(o,t);return}this.data.getNode(o)?.setValue(null,!1);try{this.fireEvent(e,t,{attributes:r})}finally{this.data.getNode(o)?.setValue(null,!1)}}#i(e,t){let[r,o]=e.split("?",2),i=this.data;i.getNode(r)?.setAttr({[o]:null},!1);try{let a=i.getNode(r);a?a.setValue(a.staticValue,!0,{[o]:t},!0,!0,!0,!0):i.setItem(r,null,{[o]:t},">",!0,!0,!0,!0)}finally{i.getNode(r)?.setAttr({[o]:null},!1)}}FIRE_AFTER(e,t=!0,r=10){this.#l(e);let o=this.rootBuilder?.binding?.bindingFor(this)??null,i=null,a=setTimeout(()=>{i?.(),this.FIRE(e,t)},r);return i=o?.track(()=>clearTimeout(a))??null,()=>{clearTimeout(a),i?.()}}absDatapath(e){e=ne(e)?.pointer??e;let t=this.pointerType(e)?e.slice(1):e;if(t.startsWith("#")&&t.includes("?")){let[r,o]=t.split("?",2),i=super.absDatapath(r);return i===null?null:`${i}?${o}`}return super.absDatapath(e)}_composeRelativeDatapath(e,t){let r=this;for(;r!==null&&e.startsWith(".");){let o=r.getAttr("datapath");if(this.pointerType(o)&&(o=this.#a(r,o),o===null))return null;if(o!=null&&(e=e==="."?o:o+e),e.startsWith("#"))return r.parentNode._resolveSymbolicDatapath(e,t);r=r.parentNode}if(e.startsWith("."))throw new Error(`unresolved relative datapath: ${t}`);return e}_finalizeAbsPath(e,t){return e===null?null:super._finalizeAbsPath(e,t)}_resolveSymbolicDatapath(e,t){let r=e.slice(1).split(".",1)[0];if(r==="FORM"||r==="ANCHOR")return super._resolveSymbolicDatapath(e,t);let o=this.rootBuilder?.binding;if(!o)return super._resolveSymbolicDatapath(e,t);let i=o.nodeIds.get(r);if(!i)throw new Error(`#<id>: cannot resolve ${t}`);let a=e.slice(r.length+2);return i.absDatapath(a?`.${a}`:".")}#a(e,t){if(ne(t)){let i=Or(e,"datapath",e.parentNode);return i==null||i===""?null:i}let r=e.parentNode.absDatapath(t);if(r===null)return null;let o=this.data.getItem(r);return o==null||o===""?null:o}#s(e,t){return ne(t)||typeof e!="string"||!e.endsWith("_path")?!1:(this.#r.has(e)||(this.#r.add(e),console.warn(`${this.nodeTag} '${this.label}': '${e}' holds a bare Data path; the pointer symbol of '${t}' is removed`)),!0)}#l(e){if(this.absDatapath(e)===null)throw new Error(`${this.nodeTag} '${this.label}': write on a null path: '${e}'`)}},Ae=class n extends I{get nodeClass(){return ln}authorizedCopy(e){let t=new this.constructor;for(let r of this.getNodes()){let o=r.getAttr("auth")??null;if(o!==null){if(typeof o!="string")throw new TypeError(`${r.nodeTag} '${r.label}': 'auth' must be a string rule, not ${typeof o}`);if(e(o)!==null)continue}let i=r.staticValue;i instanceof n&&(i=i.authorizedCopy(e));let{auth:a,...s}=r.getAttr(),l=t.setItem(r.label,i,s,">",!1,!1,null,!1,!0,null,r.nodeTag);l.xmlTag=r.xmlTag}return t}activateCode(){for(let e of this.getNodes())e.activateCode(),e.staticValue instanceof n&&e.staticValue.activateCode();return this}};if((pt(Ae.tytxSuffix).GramlotBuilderBag??Ae)!==Ae)throw new Error("TYTX subtype name 'GramlotBuilderBag' is already registered for another class");Yr(Ae.tytxSuffix,{...pt(Ae.tytxSuffix),GramlotBuilderBag:Ae});var Iv=new Set(["animate","animateMotion","animateTransform","circle","ellipse","feBlend","feColorMatrix","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feGaussianBlur","feImage","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","image","line","metadata","path","polygon","polyline","rect","set","stop","use"]),Ai=class extends rn{constructor(e,t){super(e),this._owner=t}get owner(){return this._owner}_handleMeta(e,t){let r=this.owner.evaluateExpressions(e,t);co(e,r);let[o,i]=super._handleMeta(e,r);return uo(e,i),e._getMeta("subbuilder")?[o,os(ps(i))]:[o,i]}adaptAttrs(e){let{_meta:t,...r}=e;return yi(super.adaptAttrs(fo(Cr(r))))}renderedItem(e,t,r,o={}){if(this.owner.renderType==="object")return this.owner.renderedItem(e,t,r,o);let{_text:i,...a}=r;return t=this.owner.expressionValue(e,t),Array.isArray(t)&&i!=null&&(t=[this._escapeText(lo(i)),...t]),Iv.has(o.tag)?`${o.pretty?" ".repeat(this._nodeDepth(e,o.depthOffset??0)):""}<${o.tag}${this._formatAttrs(a)} />${o.pretty?`
|
|
226
|
+
`:""}`:super.renderedItem(e,t,a,o)}};var un=class extends tn{#e=new WeakMap;#t=new WeakMap;get inlineCompiler(){return null}getRender(e){return this.renders.has(e)||(e instanceof qt?this.addRender(e,this):e instanceof Tr&&this.addRender(e,new Ai(e,this))),super.getRender(e)}render(e,t={}){if(e._getMeta("data_element"))return null;let[r,o]=e.rootBuilder.runtimeValues(e),i=this.getRender(e.builder),[a,s]=i._handleMeta(e,o);return e._getMeta("subbuilder")||(s=i.adaptAttrs(s)),i.renderedItem(e,e.value instanceof I?this.renderChildren(e.value,t):r,s,{tag:a,...t})}_handleMeta(e,t){let r=this.builder.constructor.dialectPrefixes,o=this.evaluateExpressions(e,t);co(e,o,r);let[i,a]=super._handleMeta(e,xp(e,o,r));if(uo(e,a,r),e.nodeTag==="webcomponent"){i=Qt(e.getAttr());let{code:u,...c}=a;a=c}if(e._getMeta("subbuilder")){let u=ps(a);return e._getMeta("subbuilder")==="html"&&(u.xmlns=Sr),[i,u]}let[s,l]=kp(i,a);return Object.keys(l).length&&this.#e.set(e,l),[i,s]}evaluateExpressions(e,t){let r=this.inlineCompiler,o=(a,s)=>r?r.compileExpression(e,a,s)(t):null,i={...t};for(let[a,s]of Le(e.getAttr()))e.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(a)||mt(s)&&Object.hasOwn(i,a)&&(i[a]=o(a,s));return mt(e.value)&&this.#t.set(e,o("",e.value)),i}expressionValue(e,t){return mt(e.value)?this.#t.get(e)??null:t}restoreNativeAttributes(e,t){let r=this.#e.get(e);return r?(this.#e.delete(e),{...t,...fo(r)}):t}adaptAttrs(e){let{_meta:t,...r}=e,o=`${this.builder.constructor._name}_`,i=this.builder.constructor.dialectPrefixes,a={},s={};for(let[l,u]of Object.entries(Cr(r))){if(u==null)continue;if(l.startsWith(o))throw new Error(`${l}: the attribute prefix '${o}' is not accepted; use the prefix '${i[0]}'`);let c=i.find(d=>l.startsWith(d));c?a[l.slice(c.length)]=u:s[l]=u}return yi({...super.adaptAttrs(s),...a})}renderedItem(e,t,r,o={}){let i;[t,i]=vi(this.expressionValue(e,t),this.restoreNativeAttributes(e,r));let{_text:a,...s}=i;Array.isArray(t)&&a!=null&&(t=[this._escapeText(lo(a)),...t]);let l=e.parentNode?._getMeta("subbuilder")==="html"?{xmlns:Fe,...s}:s;return super.renderedItem(e,t,l,o)}finalize(e,t=null,r={}){if(!r.doctype)return super.finalize(e,t,r);let o=this._composeStringFragments(e),i=this.builder.source.getNodes().filter(a=>!a._getMeta("data_element"));return i.length===1&&i[0].nodeTag==="html"||(o=`<html>${o}</html>`),super.finalize(`<!doctype html>${o}`,t,r)}};var Cp={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"binding",version:null,title:"Gramlot binding",description:"Gramlot Data declarations and the plain HTML button; loaded after the HTML grammar."},abstracts:{},elements:{dataBinder:{doc:"Bidirectional subscription between a client Data branch and its page's server store.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"server_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataSetter:{doc:"Initial Data value, written literally at destination_path.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"value",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"any"},has_default:!0,default:null},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataFormula:{doc:"Computed Data value written at result_path; formula is inline, func is a name.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"result_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"formula",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataController:{doc:"Side effects on Data; script is inline, func is a name.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"script",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"func",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataRpc:{doc:"Server endpoint called through gramlot.rpc; the value is written at result_path when given.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"method",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"result_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"str"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"timeout",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"int"},{kind:"type",module:"builtins",name:"float"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},dataRemote:{doc:"Data node resolved by a server endpoint through gramlot.rpc, on first read and again when cacheTime expires; with sync (default) the read waits for the answer when the transport supports it.",sub_tags:"",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"destination_path",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"method",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"cacheTime",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"union",items:[{kind:"type",module:"builtins",name:"int"},{kind:"type",module:"builtins",name:"float"},{kind:"type",module:"builtins",name:"NoneType"}]},has_default:!0,default:null},{name:"sync",kind:"positional_or_keyword",role:"attribute",annotation:{kind:"type",module:"builtins",name:"bool"},has_default:!0,default:!0},{name:"params",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{data_element:!0}},html_button:{doc:"Plain native HTML button without Gramlot click mechanisms.",sub_tags:"a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{render_tag:"button"}},html_dialog:{doc:"Native HTML dialog, distinct from the layout window component.",sub_tags:"a,abbr,address,area,article,aside,audio,b,bdi,bdo,blockquote,br,button,canvas,cite,code,data,datalist,del_,details,dfn,dialog,div,dl,em,embed,fieldset,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,i,iframe,img,input,ins,kbd,label,link,main,map,mark,menu,meta,meter,nav,noscript,object,ol,output,p,picture,pre,progress,q,ruby,s,samp,script,search,section,select,selectedcontent,slot,small,span,strong,style,sub,sup,table,template,textarea,time,u,ul,var,video,wbr",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"kwargs",kind:"var_keyword",role:"attribute",annotation:null,has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:{render_tag:"dialog"}}}};var Np={document_format:{name:"builder_grammar",version:"1.1"},grammar:{name:"webcomponent",version:null,title:"Gramlot webcomponent",description:"An explicitly loaded autonomous custom element."},abstracts:{},elements:{webcomponent:{doc:"Create the custom-element tag named by literal code.",sub_tags:"*",parent_tags:null,inherits_from:null,ns:null,attributes:{parameters:[{name:"code",kind:"keyword_only",role:"attribute",annotation:{kind:"type",module:"builtins",name:"str"},has_default:!1},{name:"attr",kind:"var_keyword",role:"attribute",annotation:{kind:"any"},has_default:!1}],accepts_var_keyword:!0,accepts_var_positional:!1},node_label:null,collection_key:null,_meta:null}}};var Bv="data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element",$v=new Set,Mv=new Set(["serverpath","dbenv","shared_id"]),Pv=["formsubscribe_"],Lv={dataSetter:"destination_path",dataFormula:"result_path",dataRpc:"result_path",dataRemote:"destination_path"},Fv={dataFormula:"formula",dataController:"script"},$p=new Set(["node_label","node_position","nodeId","target_id","datapath","iterate","store","_tag","_meta","ns"]),ws={csv:"CSV",json:"JSON",tytx:"TYTX",xml:"XML",xlsx:"Excel"},Ip=new Set(["node_label","frameTarget","nodeId"]),jv=new Set(["storepath","rowMode","structpath"]);function Op(n,e){let t=n?._meta?.keywordPattern;if(!t)return null;let r=new Set(n.attributes.parameters.filter(i=>!i.kind.startsWith("var_")).map(i=>i.name)),o=Object.keys(e).find(i=>!r.has(i)&&!$p.has(i)&&!new RegExp(t).test(i));return o===void 0?null:`unknown attribute '${o}'`}function qv(n){if(typeof n=="boolean")return n?Object.keys(ws):[];if(typeof n!="string"||!n.trim())throw new TypeError("frameGrid export requires a boolean or a list of formats");let e=n.split(",").map(r=>r.trim()),t=e.find(r=>!Object.hasOwn(ws,r));if(t!==void 0)throw new TypeError(`frameGrid export format '${t}' is not one of ${Object.keys(ws).join(", ")}`);return e}function Rp(n,e){if(["input","textarea","select","webcomponent"].includes(n)&&ne(e.value))return"'value' does not accept pointer suffixes; use an ordinary value pointer";if(n==="html_button"&&Object.keys(e).some(o=>["action","ask","_delay","fire"].includes(o)||o.startsWith("fire_")))return"plain HTML button: use button for action, ask, fire or _delay";if(Object.hasOwn(e,"ask")&&!["button","toggleButton","dropDownButton","menuline"].includes(n))return"'ask' is supported on buttons";if(Object.hasOwn(e,"_ask")&&!["dataController","dataFormula","dataRpc"].includes(n))return"'_ask' requires a controller, formula or RPC";if(["dataSetter","dataRemote"].includes(n)&&Object.keys(e).some(o=>o.startsWith("subscribe_")||o.startsWith("selfsubscribe_")))return"topic subscriptions are supported on controllers, formulas, RPCs and rendered elements";let t=Lv[n];if(t&&String(e[t]??"").includes("?"))return`'${t}' does not accept '?attr': '${e[t]}'`;let r=Fv[n];return r&&e[r]!=null&&e.func!=null?`'func' and '${r}' cannot be declared on the same node`:r&&e._if!=null&&e.func!=null?"'_if' is inline and cannot be declared with 'func': write the condition in the method":null}function Bp(n){return Object.keys(n).find(e=>Mv.has(e)||Pv.some(t=>e.startsWith(t)))}var Oe=class n extends qt{static _name="gramlot";static containers=["frameGrid"];static _sourceClass=Ae;static{this.defineGrammar(Cp)}static{this.defineGrammar(Np)}static{this.defineGrammar(gs.toDocument())}frameGrid(e,{storepath:t,rowMode:r,structpath:o,searchOn:i=!1,searchHelp:a=!1,chart:s=!1,export:l=!1,printRows:u=!1,advancedTools:c=!1,addrow:d=!1,addrow_defaults:f=null,duprow:h=!1,delrow:p=!1,gridsemaphore:m=!1,...b}={}){for(let F of["framePane","grid"])if(!this.schemaTag(F))throw new TypeError(`frameGrid requires the ${F} collection`);let w={};for(let F of Object.keys(b))F.startsWith("chart_")&&(w[F.slice(6)]=b[F],delete b[F]);let[_,y]=this.frameGridRoute(b),x=Object.keys(y).find(F=>["storepath","rowMode"].includes(F)||F==="structpath"&&o!=null);if(x!==void 0)throw new TypeError(`frameGrid: '${x}' is given twice`);if(s!==!1){if(s!==!0&&(typeof s!="string"||!s))throw new TypeError("chart requires a boolean or chart type");if(!_.datapath)throw new TypeError("A chart frameGrid requires its own datapath");if(!this.schemaTag("chartPane"))throw new TypeError("frameGrid requires the chartPane collection");typeof s=="string"&&(w.chartType=s)}else if(Object.keys(w).length)throw new TypeError("chart_* options require chart");let D=qv(l);for(let[F,H]of Object.entries({printRows:u,advancedTools:c,addrow:d,duprow:h,delrow:p,gridsemaphore:m}))if(typeof H!="boolean")throw new TypeError(`frameGrid ${F} requires a boolean`);if(f!==null&&(!d||typeof f!="object"||Array.isArray(f)))throw new TypeError("addrow_defaults requires addrow and a mapping");if(m){if(!_.datapath)throw new TypeError("A gridsemaphore frameGrid requires its own datapath");if(!this.schemaTag("editingStatus"))throw new TypeError("frameGrid requires the editingStatus collection");_.form=!0}let k={storepath:t,rowMode:r,...o==null?{}:{structpath:o},node_label:"grid",frameTarget:!0,height:"100%",width:"100%",..._.datapath?{selectedId:"^.selectedId"}:{},...y};s!==!1&&(k.nodeId=J()),this.validateNodeValues("grid",null,k),i!==!1&&this.validateNodeValues("searchBox",null,{searchOn:i,searchHelp:a});let C=e.framePane(_);C.center.grid(k);let O=C.top.menu({presentation:"bar",node_label:"bar",aria_label:"Grid toolbar",class:"gramlot-grid-toolbar"});i!==!1&&O.menuline({group:!0,node_label:"search",class:"gramlot-grid-search"}).searchBox({searchOn:i,searchHelp:a}),d&&O.menuline({command:"grid:addrow",node_label:"addrow",...f===null?{}:{parameters:{defaults:f}}}),h&&O.menuline({command:"grid:duprow",node_label:"duprow"}),p&&O.menuline({command:"grid:delrow",node_label:"delrow"});let $=F=>{let H=F.menuline({caption:"Export",icon:"\u21E9",labelPosition:"tooltip",node_label:"export"}).menu();for(let Q of D)H.menuline({command:"grid:export",caption:ws[Q],parameters:{format:Q},node_label:Q})};if(D.length&&$(O),u&&O.menuline({command:"grid:printRows",node_label:"printRows"}),c){let F=O.menuline({caption:"Advanced tools",icon:"\u2026",labelPosition:"tooltip",node_label:"advancedTools"}).menu();F.menuline({command:"grid:lineNumbers",node_label:"lineNumbers"}),D.length&&$(F),u&&F.menuline({command:"grid:printRows",node_label:"printRows"})}return m&&O.menuline({group:!0,node_label:"semaphore"}).editingStatus(),s!==!1&&(O.menuline({caption:"Chart",icon:"\u25A5",labelPosition:"tooltip",node_label:"chart",action:"this.SET('._chart.open',true)"}),C.center.floatingPane({title:"Chart",open:"^._chart.open",width:"820px",height:"560px",movable:!0,resizable:!0,maximizable:!0,node_label:"chartWindow"}).frame.center.chartPane({storepath:t,rowMode:r,gridId:k.nodeId,configpath:"._chart",configDefaults:new E(w),height:"100%"})),C}frameGridRoute(e){let t=c=>new Set(this.schema[c].attributes.parameters.filter(d=>!d.kind.startsWith("var_")).map(d=>d.name)),r=new Set([...$p,...Zt]),o=t("grid"),i=t("framePane"),a=new RegExp(this.schema.grid._meta.parameterPattern),s=c=>(o.has(c)||a.test(c))&&!i.has(c)&&!r.has(c)&&!Ip.has(c)&&!jv.has(c),l={},u={};for(let[c,d]of Object.entries(e)){let f,h;if(c.startsWith("grid_")){if(f=c.slice(5),h=u,Ip.has(f))throw new TypeError(`frameGrid: '${c}' is composed by frameGrid`)}else c.startsWith("frame_")?(f=c.slice(6),h=l):(f=c,h=s(c)?u:l);if(Object.hasOwn(h,f))throw new TypeError(`frameGrid: '${f}' is given twice`);h[f]=d}return[l,u]}static get dialectPrefixes(){let e=[];for(let t=Object.getPrototypeOf(n);t&&t!==Function.prototype;t=Object.getPrototypeOf(t))Object.hasOwn(t,"_name")&&t._name&&e.push(`${t._name}_`);return e}constructor(e=null,{collections:t=[],auth:r=null,nameSyntax:o=_i}={}){if(!(o instanceof on))throw new TypeError(`nameSyntax must be a NameSyntax, not ${o}`);super(e),this._binding=null,this._auth=r,this._nameSyntax=o;for(let i of t)this.loadCollection(i)}get auth(){return this._auth}get nameSyntax(){return this._nameSyntax}get binding(){return this._binding}set binding(e){this._binding=e}evaluatePointerExpression(e,t,r,o,i){return this.binding?this.binding.inlineCompiler.compilePointerExpression(e,t,r,o.text)(i):null}nodeById(e){if(!this.binding)return super.nodeById(e);let t=this.binding.nodeIds.get(e);if(!t)throw new Error(`nodeId not found: ${e}`);return t.builder.wrapSource(t)}loadCollection(e){return this.loadGrammar(e instanceof Ar?e.toDocument():e),this}schemaTag(e){let t=e.toLowerCase(),r=n.dialectPrefixes;if(t.startsWith(`${n._name}_`))throw new Error(`${e}: the tag prefix '${n._name}_' is not accepted; use the prefix '${r[0]}'`);if($v.has(t))throw new Error(`${e}: excluded from Gramlot`);let o=this.schemaTagNames[t];if(o)return o;for(let i of r)if(t.startsWith(i)&&this.schemaTagNames[t.slice(i.length)])return t;return null}bagCall(e,t,r,o){return t=this.#e(t),[r,o]=this.menuArguments(t,r,o),super.bagCall(e,t,r,o)}commandOnNode(e,t,r,o){return t=this.#e(t),[r,o]=this.menuArguments(t,r,o),super.commandOnNode(e,t,r,o)}menuArguments(e,t,r={}){if(e==="menu"&&t==null)return[new Ae(null,this),r];if(e==="menuline"&&t!=null&&t!=="-"){if(Object.hasOwn(r,"command"))throw new TypeError("menuline command must be declared once");return[null,{...r,command:t}]}return[t,r]}validateNodeValues(e,t,r={}){if(this.schema[e]?._meta?.gramlot_component&&ne(r.value))throw new Error("'value' does not accept pointer suffixes");e==="webcomponent"&&Qt(r);let o=Bp(r);if(o)throw new Error(`${e}: attribute '${o}' is excluded from Gramlot`);let i=Rp(e,r)??Op(this.schema[e],r);if(i)throw new Error(`${e}: ${i}`);return super.validateNodeValues(e,t,r)}validateNode(e,t={}){if(e._getMeta("gramlot_component")&&ne((t.attrs??e.getAttr()).value))throw new Error("'value' does not accept pointer suffixes");e.nodeTag==="webcomponent"&&Qt(t.attrs??e.getAttr());let r=Bp(t.attrs??e.getAttr());if(r)throw new Error(`${e.nodeTag} '${e.label}': attribute '${r}' is excluded from Gramlot`);let o=Rp(e.nodeTag,t.attrs??e.getAttr())??Op(this.schema[e.nodeTag],t.attrs??e.getAttr());if(o)throw new Error(`${e.nodeTag} '${e.label}': ${o}`);return super.validateNode(e,t)}_validateChildren(e,t,r,o){return super._validateChildren(e,t,r.map(i=>i==="html_button"?"button":i==="html_dialog"?"dialog":i),o)}_countsForGrammar(e){return e===this.schema.button||!e?._meta?.gramlot_component&&e!==this.schema.webcomponent&&super._countsForGrammar(e)}setChild(e,t,r,o,i=null){o=Object.fromEntries(Object.entries(o??{}).map(([l,u])=>[l,ae(u)instanceof Xe?this.reference(u):u]));let s=t==="dataSetter"&&o?.value!==null&&typeof o?.value=="object"&&Object.getPrototypeOf(o.value)===Object.prototype?{...o,value:new E(o.value)}:o;return super.setChild(e,t,r,s,i)}#e(e){if(e==="data")throw new Error(Bv);if(this.schemaTagNames[e.toLowerCase()]===e)return e;let t=n.dialectPrefixes.find(r=>e.startsWith(r));return this.schemaTagNames[e.slice(t.length)]}get renderer_html(){return new un(this)}create(){this.setup(this.data),this.main(this.root)}computeLogic(){}promoteNodeValue(e,t,r){let o=t!=null?{_text:t}:null;e.setValue(r,!0,o,!0)}reference(e,t="node"){if(e=ae(e),!(e instanceof Xe)||!["node","dom"].includes(t))throw new TypeError("Reference requires an element and node/dom kind");let r=e.getAttr("__ref");return r==null&&(r=J(),e.setAttr({__ref:r})),{$gramlotRef:r,kind:t}}toTytx(){return L(this.auth===null?this.source:this.source.authorizedCopy(this.auth))}};function tc(n){for(let e=n.parentNode;e;e=e.parentNode)if(e.nodeTag==="framePane")return e;return null}function _s(n){if(!n||!(n.value instanceof I))return null;let e=n.value.getNodes().find(o=>o.getAttr("region")==="center"),t=[];function r(o){if(o.nodeTag!=="framePane"&&(o.getAttr("frameTarget")===!0&&t.push(o),o.value instanceof I))for(let i of o.value.getNodes())r(i)}return e&&r(e),t.length===1?t[0]:null}function Uv(n){if(n.closed||!n.runtime.renderer.attached(n.node))return!1;for(let e=n.node;e;e=e.parentNode){let[,t]=e.rootBuilder.runtimeValues(e);if(t.hidden===!0||t.disabled===!0)return!1}return!0}function Mp(n){if(n&&typeof n=="object"){for(let e of Object.values(n))Mp(e);Object.freeze(n)}return n}function Pp(n,e){let t=n.node,r=t.getAttr("command"),o=n.runtime.gramlot.commands.get(r),i=tc(t),a=_s(i);if(!o||!a)return console.warn(`Cannot dispatch command '${r}' at '${t.label}': missing or duplicate frame recipient`),null;let s=t.getAttr("parameters")??{};if(typeof s!="object"||Array.isArray(s))throw new TypeError("Command parameters require a mapping");let l=Object.fromEntries(Object.entries(s).map(([m,b])=>[m,t.pointerType(b)?t.getRelativeData(b):b])),u=Mp(j(L(l))),c=Object.freeze(Object.fromEntries(["shift","ctrl","alt","meta"].map(m=>[m,!!e[`${m}Key`]]))),d=Object.freeze({sender:t,target:a,command:r,parameters:u,modifiers:c}),f=!1,h=n.runtime.bindingFor(a).track(()=>{f=!0}),p=()=>!f&&Uv(n)&&_s(i)===a&&n.runtime.renderer.attached(a)&&t.getAttr("command")===r;return{message:d,current:p,release:h,cancel(){f=!0},deliver(){p()&&a.publish(o.publish,d)}}}var Vv=new Set(["input","select","textarea"]),zv=["type","multiple"];function Lp(n,e){let t=n.node,r=t.getAttr(e);return t.pointerType(r)?t.getRelativeData(r):n.resolved[e]}var je=class n{static liveWrites=!1;static writesDefault=!0;static preservesUnchangedValue=!1;#e;#t=!1;#r;#n;#o=!1;#i=!1;#a=!1;static for(e,t){let r=n.classFor(t.element,t.attrs);return r?new r(e,t):null}static classFor(e,t){if(e.namespaceURI!==Fe)return null;if(e.constructor.gramlotComponent)return e.constructor.gramlotComponent.parameters.value?.binding!=="twoWay"?null:e.control.type==="radio"?ac:rc;if(e.localName==="textarea")return Vt;if(e.localName==="select")return Di;if(e.localName!=="input")return null;let r=t.type==null?"text":String(t.type).toLowerCase();return Object.hasOwn(Fp,r)?Fp[r]:Vt}static shape(e,t){return e?.constructor.gramlotComponent?.parameters.value?.binding==="twoWay"&&e.control.type==="radio"?JSON.stringify([]):e?.namespaceURI!==Fe||!Vv.has(e.localName)?null:JSON.stringify(zv.filter(r=>(r!=="type"||e.localName!=="input")&&(r!=="multiple"||!["input","select"].includes(e.localName))).map(r=>t[r]??null))}constructor(e,t){this.#r=e,this.#n=t}get binding(){return this.#r}get element(){return this.#n.element}get node(){return this.binding.node}get eventElement(){return this.element}get resolved(){return this.#n.resolved}get live(){return!!this.resolved.live}get writeEvent(){return this.constructor.liveWrites&&this.live?"input":"change"}project(e,t){if(this.#i){this.#a=!0;return}this.constructor.preservesUnchangedValue&&this.#t&&this.same(this.#e,e)&&(!this.#o||this.same(this.read(),e))||(this.#e=e,this.#t=!0,!(this.#o&&this.same(this.read(),e))&&(this.constructor.writesDefault&&!this.node.pointerType(this.node.getAttr("value"))&&this.writeDefault(e),this.write(e)))}read(){return this.element.value}write(e){let t=e==null?"":String(e);this.element.value!==t&&(this.element.value=t)}writeDefault(e){let t=e==null?"":String(e);this.element.localName==="textarea"?this.#n.text.data!==t&&(this.#n.text.data=t):this.element.defaultValue!==t&&(this.element.defaultValue=t)}same(e,t){return Object.is(e,t)}commit(e,t=this.read()){if(!this.binding.closed){this.#o=!0;try{this.binding.runtime.renderer.html.writeParameter(this.node,"value",t)}finally{this.#o=!1}}}attach(){for(let e of["input","change","compositionstart","compositionend"])this.eventElement.addEventListener(e,this)}detach(){for(let e of["input","change","compositionstart","compositionend"])this.eventElement.removeEventListener(e,this);this.#a=!1}refresh(){}handleEvent(e){if(!this.binding.closed){if(e.type==="compositionstart"){this.#i=!0;return}if(e.type==="compositionend"){this.#i=!1,this.writeEvent==="input"&&this.commit(e),this.#a&&(this.#a=!1,this.binding.runtime.renderer.project(this.node));return}this.#i||e.isComposing||e.type===this.writeEvent&&this.commit(e)}}},rc=class extends je{#e;form=null;static writesDefault=!1;static preservesUnchangedValue=!0;get eventElement(){return this.element.control}attach(){this.form=this.element.supportsFormValidation&&this.node.pointerType(this.node.getAttr("value"))==="^"?this.node.formState:null,this.element.setPageContext(lc(this)),this.form&&this.node.pointerType(this.node.getAttr("value"))==="^"&&(this.#e=this.form.register(this)),super.attach()}refresh(){let e=this.element.supportsFormValidation&&this.node.pointerType(this.node.getAttr("value"))==="^"?this.node.formState:null;e!==this.form&&(this.#e?.(),this.form=e,this.element.setPageContext(lc(this)),this.#e=e?e.register(this):null)}project(e,t){this.element.shouldProjectControlValue(e)&&super.project(e,t)}same(e,t){return this.element.sameControlValue(e,t)}detach(){this.element.releaseControl(),this.#e?.(),super.detach()}commit(e){if(this.binding.closed||this.element.control.disabled||this.element.control.readOnly)return;let t=this.element.acceptControlValue();this.form||jp(this.element,t,r=>super.commit(e,r.value))}get writeEvent(){return this.element.commitOnChange?"change":(this.resolved.live??this.element.parameters.live)&&this.element.liveWrites?"input":"change"}read(){return this.element.readControlValue()}write(e){this.element.writeControlValue(e)}handleEvent(e){if(e.type==="input"&&this.form&&!this.binding.closed&&!this.element.control.disabled&&!this.element.control.readOnly&&this.form.draft(this.node,this.element.control.value??""),super.handleEvent(e),!e.composed&&!this.binding.closed&&["input","change"].includes(e.type)){let t=this.element.ownerDocument.defaultView.Event;this.element.dispatchEvent(new t(e.type,{bubbles:!0,composed:!0}))}}},Vt=class extends je{static liveWrites=!0},nc=class extends je{static liveWrites=!0;read(){return this.element.value===""?null:Number(this.element.value)}commit(e){this.element.validity.badInput||super.commit(e)}},oc=class extends je{static liveWrites=!0;read(){return Number(this.element.value)}},Di=class extends je{static writesDefault=!1;read(){return this.element.multiple?[...this.element.selectedOptions].map(e=>e.value):this.element.selectedIndex===-1?null:this.element.value}write(e){let t=this.element;if(t.multiple){if(e!=null&&!Array.isArray(e))throw new TypeError(`${this.node.nodeTag} '${this.node.label}': a multiple select requires an array`);let r=new Set((e??[]).map(String));for(let o of t.options){let i=r.has(o.value);o.selected!==i&&(o.selected=i)}}else e==null?t.selectedIndex!==-1&&(t.selectedIndex=-1):(t.selectedIndex===-1||t.value!==String(e))&&(t.value=String(e))}same(e,t){return Array.isArray(e)?Array.isArray(t)&&t.length===e.length&&t.every((r,o)=>Object.is(r,e[o])):super.same(e,t)}},cn=class extends je{read(){return this.element.value===""?null:this.element.value}},ic=class extends je{},ys=class extends je{static writesDefault=!1;read(){return this.element.checked}write(e){let t=!!e;this.element.checked!==t&&(this.element.checked=t)}same(e,t){return e===!!t}attach(){let e=this.node;if(e.getAttr("checked")!=null&&e.pointerType(e.getAttr("value"))==="^")throw new TypeError(`${e.nodeTag} '${e.label}': checked and a ^ value are two sources`);super.attach()}},po=class extends ys{#e=null;#t=!1;get groups(){return this.binding.runtime.renderer.radioGroups}attach(){let e=this.node,t=this.resolved.group??null,r=sc(e);if(t!=null){if(e.getAttr("name")!=null)throw new TypeError(`${e.nodeTag} '${e.label}': name and group are two names`);this.#r(t,r)}super.attach(),t!=null&&(this.#e=this.groups.join(this,t,r),this.element.setAttribute("name",this.#e))}detach(){this.#e!==null&&(this.groups.leave(this),this.element.removeAttribute("name"),this.#e=null),super.detach()}refresh(e=this.resolved.group){let t=this.resolved.group??null,r=sc(this.node);if(!Object.is(e??null,t)){let o=new Set([this,...this.groups.peers(this),...t===null?[]:this.groups.peersOf(t,r)]);this.groups.leave(this),this.#e=t===null?null:this.groups.join(this,t,r),this.#e===null?this.element.removeAttribute("name"):this.element.setAttribute("name",this.#e);for(let i of o){if(this.binding.closed||!this.binding.runtime.renderer.attached(this.node))return;i.binding.closed||!i.binding.runtime.renderer.attached(i.node)||i.binding.runtime.renderer.html.writeParameter(i.node,"value",!1)}return}this.#e!==null&&this.groups.nameOf(t,r)!==this.#e&&(this.#r(t,r),this.groups.leave(this),this.#e=this.groups.join(this,t,r),this.element.setAttribute("name",this.#e))}#r(e,t){let r=this.node;if(Lp(this,"value")&&this.groups.peersOf(e,t).some(o=>!o.binding.closed&&o.read()))throw new Error(`${r.nodeTag} '${r.label}': several true values in radio group '${e}'`)}project(e,t){let r=!this.#t;this.#t=!0;let o=this.read();super.project(e,t),!r&&!o&&this.read()&&this.turnOffPeers()}commit(e){let t=this.read();super.commit(e),t&&!this.binding.closed&&this.turnOffPeers()}turnOffPeers(){if(this.#e!==null)for(let e of this.groups.peers(this)){if(this.binding.closed)return;e.binding.closed||(e.element.checked&&(e.element.checked=!1),Lp(e,"value")&&e.commit(null))}}},ac=class extends po{static writesDefault=!1;get host(){return super.element}get element(){return this.host.control}project(e,t){this.host.shouldProjectControlValue(e)&&super.project(e,t)}commit(e){this.binding.closed||this.element.disabled||this.element.readOnly||jp(this.host,this.host.acceptControlValue(),()=>super.commit(e))}read(){return this.host.readControlValue()}write(e){this.host.writeControlValue(e)}attach(){this.host.setPageContext(lc(this)),super.attach(),this.element.addEventListener("keydown",this)}detach(){this.host.releaseControl(),this.element.removeEventListener("keydown",this),super.detach()}handleEvent(e){if(!this.binding.closed){if(e.type==="keydown"){if(this.resolved.group==null||!["ArrowLeft","ArrowUp","ArrowRight","ArrowDown"].includes(e.key))return;let t=this.groups.peersOf(this.resolved.group,sc(this.node)).filter(a=>!a.binding.closed&&!a.element.disabled),r=t.indexOf(this);if(r<0)return;e.preventDefault();let o=["ArrowLeft","ArrowUp"].includes(e.key)?-1:1,i=t[(r+o+t.length)%t.length];i.element.focus(),i.element.click();return}if(super.handleEvent(e),!e.composed&&!this.binding.closed&&["input","change"].includes(e.type)){let t=this.host.ownerDocument.defaultView.Event;this.host.dispatchEvent(new t(e.type,{bubbles:!0,composed:!0}))}}}},vs=class{#e;#t=new Map;#r=new Map;#n=new WeakMap;#o=0;constructor(e){this.#e=e}join(e,t,r){let o=this.nameOf(t,r);return this.#t.has(o)||this.#t.set(o,new Set),this.#t.get(o).add(e),this.#r.set(e,o),o}leave(e){let t=this.#r.get(e);this.#r.delete(e);let r=this.#t.get(t);r?.delete(e),r?.size===0&&this.#t.delete(t)}peers(e){let t=this.#r.get(e);return[...this.#t.get(t)??[]].filter(r=>r!==e)}peersOf(e,t){return[...this.#t.get(this.nameOf(e,t))??[]]}nameOf(e,t){t!==null&&!this.#n.has(t)&&this.#n.set(t,this.#o++);let r=t===null?"page":`form${this.#n.get(t)}`;return`gramlot-${this.#e.instanceId}-${r}-${e}`}};function sc(n){for(let e=n;e;e=e.parentNode){let t=e.getAttr()??{};if(t.formId!=null||t.form===!0)return e}return null}var Fp={text:Vt,password:Vt,email:Vt,url:Vt,tel:Vt,search:Vt,number:nc,range:oc,color:ic,date:cn,time:cn,month:cn,week:cn,"datetime-local":cn,checkbox:ys,radio:po,hidden:null,file:null,button:null,submit:null,reset:null,image:null};function lc(n){let{binding:e,node:t}=n,r=e.runtime.gramlot;return{locale:r.locale,timeZone:r.timeZone,createDecimal:Lt,isDecimal:le,getDecimalLibrary:Ka,form:n.form,formCancelValidation:()=>n.form?.cancelValidation(t),formValidateCandidate:(o,i)=>n.form.validateCandidate(t,o,i),formValidate:()=>n.form?.scheduleValidation(n),formSelectionPending:o=>n.form?.pendingPart(t,"selection",o?"active":null),formSelectionError:o=>n.form?.issue(t,"selection",o),formParseError:o=>n.form?.parseError(t,o),formClearDraft:()=>n.form?.clearDraft(t),publish:(o,i)=>t.publish(o,i),isActive:()=>!e.closed,reportError:(o,i)=>{e.closed||e.runtime.reportError(o,i)},callLogic:(o,i)=>er(e.runtime,t,o,i),format:(o,i)=>r.format(o,i),...bs(e),selectionDisplay:(o,i)=>{if(e.closed)return;let a=t.getAttr("value");if(t.pointerType(a)!=="^"||a.includes("?")||!Object.is(t.getRelativeData(a),i))return;let s=a.slice(1)+"?_displayedValue";t.getRelativeData(s)!==o&&t.setRelativeData(s,o)},periodOutput:(o,i)=>t.setRelativeData(o,i),selectionOutputs:({selectedCaption:o,selectedRecord:i,fields:a},s)=>{if(!e.closed){o&&t.setRelativeData(o,s?.caption??null),i&&t.setRelativeData(i,s?new E(s.record):null);for(let[l,u]of Object.entries(a))t.setRelativeData(u,s?.record[l.slice(9)]??null)}}}}function jp(n,e,t){let r=n.pageContext,o=i=>{i.ok&&i.isCurrent()&&(t(i),n.finishValidation(i))};if(e instanceof Promise)e.then(o).catch(i=>r.reportError(i,"Field update failed"));else try{o(e)}catch(i){r.reportError(i,"Field update failed")}}var uc=Symbol("source text"),qp={xmlns:"http://www.w3.org/2000/xmlns/",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},Hv=new Set(["allowFullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formNoValidate","hidden","inert","isMap","itemscope","loop","multiple","muted","noModule","noValidate","open","playsInline","readOnly","required","reversed","selected"]),Gv=new Set(["checked","muted","selected","value"]),Wv=new Map([["allowfullscreen","allowFullscreen"],["formnovalidate","formNoValidate"],["ismap","isMap"],["nomodule","noModule"],["novalidate","noValidate"],["playsinline","playsInline"],["readonly","readOnly"]]);function Yv(n){let e=n.replace(/-([a-z])/g,(t,r)=>r.toUpperCase());return Wv.get(e.toLowerCase())??e}var Es=class{constructor({format:e,metadataAttributes:t=[],invokeScript:r=null,callLogic:o=null,reportError:i=null,uploadContext:a=null}={}){this.format=e,this.uploadContext=a,this.invokeScript=r,this.callLogic=o,this.reportError=i,this.metadataAttributes=new Set([...Zt,"_text",...t])}definition(e){let t=e.builder,o={...t.schema[t.schemaTag(e.nodeTag)]._meta,...e.getAttr("_meta")},i=e.nodeTag==="webcomponent"?Qt(e.getAttr()):di(e.nodeTag,{renderTag:o.render_tag,ns:e.getAttr("ns"),dialectName:t.constructor._name}),a=i==="foreignObject"?Sr:o.render_attributes?.xmlns??e.getAttr("xmlns")??(t instanceof Tr?Sr:Fe);return{meta:o,namespace:a,tag:i}}validate(e,t=e.builder){this.validateLabelbox(e);let r=e.value instanceof I,o=r?e.getAttr("_text"):e.value;if(o!=null&&!["string","number","boolean"].includes(typeof o))throw new TypeError("HTML text must be scalar");let i=this.definition(e).meta.gramlot_component;for(let[l,u]of Object.entries(e.attr))if(!(i&&Object.hasOwn(i.parameters,l))&&!(e.nodeTag==="menuline"&&l==="parameters")&&!(this.metadataAttributes.has(l)||["ask","_ask"].includes(l)||u&&typeof u=="object"&&Object.hasOwn(u,"$gramlotRef"))&&u!=null&&!["string","number","boolean"].includes(typeof u))throw new TypeError(`HTML attribute ${l} must be scalar`);let a=Object.fromEntries(Object.entries(e.attr).filter(([l])=>!this.metadataAttributes.has(l))),s=r?e.value.getNodes().map(l=>l.nodeTag).filter(Boolean):[];t.validateNode(e,{value:o,attrs:a,childTags:s})}hasLabelbox(e){let t=this.definition(e).meta.gramlot_component;return t?.labelbox?!0:t?.presentationDefaults.length?Object.hasOwn(e.attr,"lbl"):Object.keys(e.attr).some(r=>r==="lbl"||r.startsWith("lbl_")||r.startsWith("box_"))}validateLabelbox(e){if(!this.hasLabelbox(e))return;let{tag:t,namespace:r}=this.definition(e);if(r!==Fe&&t!=="svg"||["html","head","body","style","script","link","meta","title","base","tr","td","th","thead","tbody","tfoot","col","colgroup","caption","option","optgroup","li","dt","dd","source","track","param","area"].includes(t))throw new TypeError("Labelbox requires content that can be placed in an HTML flow container");let o=e.parentNode;if(o?.nodeTag){let i=this.definition(o);if(i.namespace!==Fe&&i.tag!=="foreignObject"||["table","thead","tbody","tfoot","tr","colgroup","select","optgroup","ul","ol","dl","p","button","label"].includes(i.tag))throw new TypeError("Labelbox requires an HTML flow container")}}create(e,t,r=null,o=e.attr,i=null){let{tag:a,namespace:s,meta:l}=this.definition(e);r??=a;let u=s===Fe?t.createElement(r):t.createElementNS(s,r);if(l.gramlot_component&&u.constructor.gramlotComponent?.tag!==r)throw new Error(`Component collection must be activated before rendering ${r}`);l.gramlot_component?.dataScope&&(u.readDataScope=()=>{if(!e.getAttr("datapath"))throw new Error("Data scope requires an explicit datapath");return e.getRelativeData(".")}),l.gramlot_component?.sourceContext&&u.setSourceContext({sourceNode:e,frameRecipient:()=>_s(tc(e)),locale:e.rootBuilder.binding.gramlot.locale,timeZone:e.rootBuilder.binding.gramlot.timeZone,collectionView:(f,h)=>e.rootBuilder.binding.collectionView(e,f,h),format:this.format,upload:()=>this.uploadContext(),reportError:(f,h)=>this.reportError(e,f,h),publish:(f,h)=>e.publish(f,h),writeParameter:(f,h)=>this.writeParameter(e,f,h),callLogic:(f,h)=>this.callLogic(e,f,h)});let c=t.createTextNode(this.text(e));(s!==Fe||!l.void)&&u.append(c);let d={element:u,text:c,tag:r,presentation:u};if(this.hasLabelbox(e)){this.validateLabelbox(e);let f=t.createElement("div");f.append(u),d.labelbox=gp(t,f),d.labelbox.choose=p=>{e.pointerType(e.getAttr("lbl_value"))?this.writeParameter(e,"lbl_value",p):e.setAttr({lbl_value:p})},d.presentation=d.labelbox.box,d.labelId=`gramlot-label-${J()}`,d.controlId=`gramlot-control-${J()}`;let h=t.createElement("style");h.textContent=mp,d.presentation.prepend(h),l.gramlot_component?.labelbox&&u.setLabelbox(d.labelbox)}return this.update(d,e,o,uc,i),d}matches(e,t){let{tag:r,namespace:o}=this.definition(t);return(o===Fe?e.tag.toLowerCase()===r.toLowerCase():e.tag===r)&&e.element.namespaceURI===o}writeParameter(e,t,r){let o=e.getAttr(t);e.pointerType(o)==="^"&&!ne(o)&&!Object.is(e.getRelativeData(o.slice(1)),r)&&e.setRelativeData(o.slice(1),r)}compose(e,t,r){e.text.data=t??"";for(let o of r)e.element.append(o)}update(e,t,r=t.attr,o=uc,i=null,a=null){if(t.nodeTag==="script"){for(let[w,_]of t.codeAttributes())if(t.activatedCode(w)!==_)throw new Error(`script '${t.label}': '${w}' runs only as received with the Source`)}let{element:s,text:l}=e;if(this.hasLabelbox(t)&&!e.labelbox)throw new TypeError("Declare lbl or box_* when creating an experimental HTML labelbox");let u=s.namespaceURI===Fe,c=this.definition(t).meta.render_attributes??{},d=e.attrs??{},f=w=>(co(t,w,t.builder.constructor.dialectPrefixes),uo(t,w,t.builder.constructor.dialectPrefixes),t.builder.renderer_html.adaptAttrs(w)),h=t.parentNode;if(h?._getMeta("gramlot_component")?.childParameters&&(r=s.ownerDocument.defaultView.customElements.get(h._getMeta("render_tag")).projectChild(e.presentation,r,{label:t.label,adapt:f,invoke:(_,y,x)=>this.invokeScript(t,_,y,x),reportError:(_,y)=>this.reportError(t,_,y),publish:(_,y)=>t.publish(_,y),publishParent:(_,y)=>h.publish(_,y),writeParameter:(_,y)=>this.writeParameter(t,_,y),remove:()=>t.parentBag.popNode(t.label)})),e.labelbox){e.labelbox.box.style.visibility="";let w=this.definition(t).meta.gramlot_component?.parameters??{},_=Object.fromEntries(Object.entries(w).filter(([y,x])=>y.startsWith("lbl_")&&Object.hasOwn(x,"default")).map(([y,x])=>[y,x.default]));r.lbl_variant==="card"&&r.lbl_position==null&&delete _.lbl_position,bp(e.labelbox,{..._,...r},f)}if(this.definition(t).meta.gramlot_component){if(this.definition(t).meta.gramlot_component.bagStore)if(t.nodeTag==="tree")s.setStoreBag(t.rootBuilder.binding.treeStore(t));else{let w=t.absDatapath(t.getAttr("storepath"));(!a||a.path===w||a.path.startsWith(`${w}.`)||w.startsWith(`${a.path}.`))&&s.setStoreBag(t.getRelativeData(t.getAttr("storepath")))}if(this.definition(t).meta.gramlot_component.bagStruct){let w=t.absDatapath(t.getAttr("structpath"));(!a||a.path===w||a.path.startsWith(`${w}.`)||w.startsWith(`${a.path}.`))&&s.setStructBag(t.getRelativeData(t.getAttr("structpath")))}r=s.projectAttributes(r,f)}e.labelbox&&(r=Object.fromEntries(Object.entries(r).filter(([w])=>w!=="lbl"&&!w.startsWith("lbl_")&&!w.startsWith("box_"))),r.slot!=null?e.presentation.setAttribute("slot",r.slot):e.presentationSlot!=null&&e.presentation.removeAttribute("slot"),e.presentationSlot=r.slot,delete r.slot),r=Object.fromEntries(Le({...r,...c}));let p=je.classFor(s,r)!==null;o===uc&&(o=this.text(t));let m=o==null?"":String(o);l.data!==m&&(l.data=m);let b=[...new Set([...Object.keys(d),...Object.keys(r)])];b.sort((w,_)=>(_==="sandbox")-(w==="sandbox")||(u&&s.localName==="input"?(_==="type")-(w==="type"):0));for(let w of b){if(this.metadataAttributes.has(w)||["ask","_ask"].includes(w)||p&&w==="value")continue;let _=r[w];if(u&&w==="multiple"&&["input","select"].includes(s.localName)){s.multiple!==!!_&&(s.multiple=!!_);continue}if(u&&s.localName==="input"&&w==="type"){Object.is(d.type,_)||(_==null?s.removeAttribute("type"):s.type=String(_));continue}let y=w,x=Yv(y),D=u&&Hv.has(x)&&typeof s[x]=="boolean",k=y==="xmlns"?"xmlns":y.includes(":")?y.split(":")[0]:"",C=Object.hasOwn(qp,k)?qp[k]:null;if(Object.is(d[w],_)||(_==null||D&&!_?C?s.removeAttributeNS(C,y.split(":").at(-1)):s.removeAttribute(y):C?s.setAttributeNS(C,y,String(_)):s.setAttribute(y,D?"":String(_))),u&&(D||Gv.has(x))&&x in s){let O=x==="value"?_==null?"":String(_):!!_;s[x]!==O&&(s[x]=O)}}if(i===!1?s.style.visibility!=="hidden"&&(s.style.visibility="hidden"):e.visible===!1&&(r.style==null?s.removeAttribute("style"):s.setAttribute("style",String(r.style))),e.visible=i,e.labelbox){let{fieldLabel:w,labelBox:_,box:y}=e.labelbox;["input","textarea","select","button","output","meter","progress"].includes(e.tag)?(s.id||(s.id=e.controlId),w.htmlFor=s.id):(w.id=e.labelId,this.definition(t).meta.gramlot_component?.labelbox||(y.setAttribute("role","group"),_.hidden?y.removeAttribute("aria-labelledby"):y.setAttribute("aria-labelledby",w.id))),y.hidden=!!r.hidden,i===!1&&(y.style.visibility="hidden")}e.attrs=r}text(e){return e.value instanceof I?e.getAttr("_text")==null?"":String(e.attr._text):e.value==null?"":String(e.value)}};var xs=class n{#e;#t;#r=null;#n=0;#o=new Set;#i=null;static for(e,t){return t.element?.constructor.gramlotComponent?.command?new n(e,t):null}constructor(e,t){this.#e=e,this.#t=t}get binding(){return this.#e}get node(){return this.binding.node}get element(){return this.#t.element}get controllers(){let e=this.node.value;return e?.getNodes?e.getNodes().filter(t=>t.nodeTag==="dataController"||t.nodeTag==="dataRpc"):[]}get mechanism(){let e=this.node,t=this.controllers;if(t.length>1)throw new Error(`${e.nodeTag} '${e.label}': several dataController or dataRpc children; a button has one click mechanism`);let r=e.getAttr()??{},o=[];if(t.length&&o.push("controller"),r.action!=null&&o.push("action"),e.nodeTag==="menuline"&&r.command!=null&&o.push("registered"),Up(r).length&&o.push("fire"),e.nodeTag==="menuline"&&e.value instanceof I&&e.value.getNodes().some(i=>i.nodeTag==="menu")&&o.length)throw new Error(`menuline '${e.label}': a submenu cannot also execute a command`);if(e.nodeTag==="menuline"&&r.group&&o.length)throw new Error(`menuline '${e.label}': a group cannot execute a command`);if(o.length>1)throw new Error(`${e.nodeTag} '${e.label}': ${o.join(" and ")} together; a button has one click mechanism`);return o[0]??null}attach(){this.refresh(),this.element.activateCommand=e=>this.onClick(e),this.element.attachCommand(),this.element.addEventListener("click",this)}refresh(){if(this.node.nodeTag==="menuline"){let t=this.node.getAttr("command"),r=t?this.binding.runtime.gramlot.commands.get(t):null;this.element.setCommandDefinition(r,this.node.label),t&&!r&&this.#i!==t&&(console.warn(`Unknown command '${t}' in menu '${this.node.parentNode?.label}', entry '${this.node.label}'`),this.#i=t)}for(let t of this.#o)t.current()||t.cancel();this.mechanism&&this.node.getAttr("type")==null&&this.element.getAttribute("type")!=="button"&&this.element.setAttribute("type","button")}detach(){this.element.removeEventListener("click",this),this.element.releaseCommand(),delete this.element.activateCommand,this.#r?.();for(let e of this.#o)e.cancel(),e.release();this.#o.clear()}handleEvent(e){this.onClick(e)}onClick(e){if(this.binding.closed||this.element.disabled)return;let t=this.element.commandTarget(e);if(t===null)return;if(t!==this.element)return e.stopPropagation(),t.activateCommand(e);let r=this.element.closest("gramlot-row-actions"),o=r?r.getRowContext():null;if(r&&o===null||!this.element.prepareCommand(e))return;let i=this.mechanism;if(!i||(e.stopPropagation(),this.element.disabled))return;let a=i==="registered"?Pp(this.binding,e):null;if(i==="registered"&&!a)return;a&&this.#o.add(a);let s=this.binding.countClick(),l=this.node;for(;l&&l.getAttr("_delay")==null;)l=l.parentNode;let u=l?l.rootBuilder.runtimeValues(l)[1]._delay:0;if(u>0){let c=this.#n+1;this.#r?.(),this.#n=c;let d=setTimeout(()=>{f(),this.#r=null,this.#n=0,this.#s(e,c,a,o)},u),f=this.binding.track(()=>this.#r?.());this.#r=()=>{clearTimeout(d),a&&(a.cancel(),a.release(),this.#o.delete(a)),f(),this.#r=null,this.#n=0};return}return this.#r?.(),this.#s(e,s,a,o)}async#a(e){try{if(!e.current())return;let t=this.node.getAttr("ask"),r=this.binding.runtime.askDialog,o={...e.message.parameters};if(t&&r.required(this.binding,t,o,"ask")&&await r.show(this.binding,t,o)===null)return;e.deliver()}finally{e.release(),this.#o.delete(e)}}#s(e,t,r=null,o=null){if(r)return this.#a(r);if(this.binding.closed||this.element.disabled)return;let i=this.mechanism;if(!i)return;let a=this.node,s=Xv(e);if(i==="controller")this.binding.runtime.bindingFor(this.controllers[0])?.providers[0]?.invoke({kind:"click",event:e,counter:t,rowContext:o});else if(i==="action"){let l=()=>{let[,f]=a.rootBuilder.runtimeValues(a),h=Object.fromEntries(Object.entries(f).filter(([p])=>p!=="ask"));return{...this.binding.runtime.renderer.references.resolveArguments(h),...o,event:e,_counter:t,modifiers:s}},u=f=>{if(this.binding.closed||this.element.disabled||f===null)return;let h={...l(),...f};f&&(h._askResult=f),Ut(this.binding.runtime,a,"action",a.getAttr("action"),h)},c=a.getAttr("ask"),d=this.binding.runtime.askDialog;if(c&&d.required(this.binding,c,l(),"ask"))return d.show(this.binding,c,l()).then(u);u(void 0)}else{let l={modifier:s,_counter:t},u=a.getAttr("fire");if(u!=null){a.FIRE(u,s||!0,l);return}for(let[c,d]of Up(a.getAttr())){if(this.binding.closed)return;a.FIRE(d,c.slice(5),l)}}}};function Up(n){return Object.entries(n??{}).filter(([e,t])=>t!=null&&(e==="fire"||e.startsWith("fire_")))}function Xv(n){return["shift","ctrl","alt","meta"].filter(e=>n[`${e}Key`]).map(e=>e[0].toUpperCase()+e.slice(1)).join("")}var At=class extends fe{static classKwargs={...fe.classKwargs,asBag:!1};constructor({cacheTime:e,onError:t}){super({cacheTime:e??-1}),this.onError=t,this.loading=null,this.loaded=!1,this.writing=!1}resolve({static:e=!1}={}){return!e&&!this.closed&&!this.loading&&!this.writing&&this.expired&&this.refresh(),this.cachedValue}refresh(){if(this.closed)return null;let e=this.startLoad(r=>this.#e(r));if(e===null)return null;let t=()=>{this.loading===e&&(this.loading=null)};return e.then(t,t),this.loading=e,e.catch(r=>{r?.name!=="AbortError"&&this.onError(r)}),e}resolveSync(e){return super.resolve(e)}prepareValue(e){return e}async#e(e){if(this.closed)return;let t=this._computeEffectiveFingerprint(this._buildEffectiveKw()),r=await this.loadAsync(e);if(this.closed||e.ignored)return;let o=this.prepareValue(r);this._lastUpdate=Date.now(),this._lastEffectiveFingerprint=t,this.loaded=!0,this.writing=!0;try{this.node?this.node.setValue(o,this.cacheTime!==0):this.cachedValue=o}finally{this.writing=!1}return o}};var mo=class extends At{static internalParams=new Set([...At.internalParams,"binding","method","params","onCalling","onError","sync"]);constructor({binding:e,method:t,params:r,cacheTime:o,onCalling:i=null,onError:a,sync:s=!1}){super({cacheTime:o,onError:a}),this.binding=e,this.sync=s,this.method=t,this.params=r,this.onCalling=i}get closed(){return this.binding.closed}resolve(e={}){return this.sync?e.static||this.loading||this.writing?this.cachedValue:this.expired&&!this.binding.node.requests.calling(this.onCalling)?this.cachedValue:super.resolveSync(e):super.resolve(e)}load(){let e;try{e=this.binding.callSync("data",this.method,this.params)}catch(t){this.onError(t)}return this.loaded=!0,e}startLoad(e){let t=this.binding.node.requests;return t.calling(this.onCalling)?t.submit(this.method,this.params,e):null}loadAsync(e){return this.binding.call("data",e)}};var Vp=new Set(["kind","command","caption","icon","iconSrc","tooltip","disabled","hidden","checked","favorite","parameters","resolver","cacheTime","sync"]);function zp(n,e=new Set){if(!(n instanceof E)||e.has(n))throw new TypeError("Menu resolver must return an acyclic Bag");let t=new Set([...e,n]);return n.getNodes().map(r=>{let o=r.attr,i=o.kind,a=r.staticValue;if(Object.keys(o).some(l=>!Vp.has(l)&&!l.startsWith("resolver_")))throw new TypeError(`Unsupported menu record field: ${r.label}`);if(!["command","separator","submenu"].includes(i))throw new TypeError(`Invalid menu kind: ${r.label}`);for(let l of["disabled","hidden","checked"])if(o[l]!=null&&typeof o[l]!="boolean"&&!(typeof o[l]=="string"&&o[l].startsWith("^")))throw new TypeError(`Invalid menu ${l}`);if(o.favorite!=null&&typeof o.favorite!="boolean")throw new TypeError("favorite must be boolean");if(o.caption!=null&&typeof o.caption!="string")throw new TypeError("Menu caption must be text");if(o.parameters!=null&&(typeof o.parameters!="object"||Array.isArray(o.parameters)))throw new TypeError("Menu parameters must be a mapping");if(i==="command"&&(typeof o.command!="string"||!o.command||a!=null||o.resolver!=null))throw new TypeError("Command record requires a command and no children/resolver");if(i==="separator"&&(a!=null||Object.keys(o).length!==1))throw new TypeError("Separator record accepts kind only");if(i==="submenu"&&(typeof o.caption!="string"||o.command!=null||a instanceof E==(o.resolver!=null)||!(a instanceof E)&&a!=null))throw new TypeError("Submenu requires caption and exactly one content source");let s=a instanceof E?zp(a,t):null;return{label:r.label,attrs:{...o},children:s}})}function Hp(n,e){let t=n.builder.wrapSource(n),r=n.value instanceof I?n.value.getNodes():[],o=new Set(e.map(i=>i.label));for(let i of r)o.has(i.label)||n.value.popNode(i.label);for(let[i,a]of e.entries()){let{kind:s,...l}=a.attrs,u=Object.fromEntries(Object.entries(l).filter(([p])=>p==="resolver"||p==="cacheTime"||p==="sync"||p.startsWith("resolver_")));for(let p of Object.keys(u))delete l[p];let c=s==="separator"?"-":null,d=n.value instanceof I?n.value.getNodes().find(p=>p.label===a.label):null,f=d?.value instanceof I;if(d&&(f!==(s==="submenu")||d.value==="-"!=(s==="separator"))&&(n.value.popNode(d.label),d=null),!d)d=ae(t.menuline(c,{...l,node_label:a.label}));else{let p=Object.keys(d.attr).filter(m=>Vp.has(m)&&!Object.hasOwn(l,m));d.setAttr({...Object.fromEntries(p.map(m=>[m,null])),...l})}if(s==="submenu"){let p=d.value instanceof I?d.value.getNodes().find(m=>m.nodeTag==="menu"):null;p?p.setAttr({...Object.fromEntries(Object.keys(p.attr).filter(m=>m==="resolver"||m==="cacheTime"||m==="sync"||m.startsWith("resolver_")).map(m=>[m,null])),...u}):p=ae(d.builder.wrapSource(d).menu({...u,node_label:"menu"})),a.children&&Hp(p,a.children)}let h=n.value.getNodes().indexOf(d);h!==i&&n.value.move(h,i)}}var ks=class{#e=null;#t=null;#r=0;#n=!1;#o=null;constructor(e,t){this.binding=e,this.element=t}get node(){return this.binding.node}attach(){this.element.menuBinding=this,this.refresh()}detach(){this.#n=!0,this.#r++,this.node.requests.inflight?.cancel(),delete this.element.menuBinding,this.element.close(!1)}refresh(){let[,e]=this.node.rootBuilder.runtimeValues(this.node),t=Object.fromEntries(Object.entries(e).filter(([o])=>o.startsWith("resolver_")).map(([o,i])=>[o.slice(9),i])),r=L([e.resolver,t,e.cacheTime,e.sync]);r!==this.#e&&(this.#e=r,this.#r++,this.#o=null,this.#t=e.resolver?new mo({binding:this.binding,method:e.resolver,params:t,cacheTime:e.cacheTime??-1,sync:e.sync??!1,onError:()=>{}}):null,this.#t?(this.element.setStatus("loading"),this.element.opened&&this.element.isConnected&&this.load()):this.element.setStatus(null))}async load(e=!1){if(this.#n||!this.#t)return;let t=this.#t,r=this.#r;try{if(e?t.refresh():t.resolve(),t.loading&&(this.element.setStatus("loading"),await t.loading),this.#n||r!==this.#r)return;let o=t.cachedValue,i=zp(o),a=L(o);this.#o!==a&&(Hp(this.node,i),this.#o=a),this.element.setStatus(i.length?null:"empty")}catch(o){if(this.#n||r!==this.#r)return;this.element.setStatus("error"),console.warn(`Menu '${this.node.label}' failed to load`,o)}}};var Ts=class{#e=!1;#t=!1;constructor(e,t){this.binding=e,this.element=t}attach(){this.element.cardActions=this}detach(){this.#e=!0,delete this.element.cardActions}async clear(){let{binding:e,element:t}=this,r=()=>!this.#e&&!e.closed&&t.isConnected&&t.parameters.delitem===!0;if(this.#t||!r())return;let o=e.node,i=o.value,a=o.absDatapath(".");if(!(a===null||!(i instanceof I))){this.#t=!0;try{if(await e.runtime.askDialog.show(e,{title:"Clear card fields",msg:`Clear the fields of \u201C${t.parameters.title}\u201D? This cannot be undone.`},{})===null||!r()||o.value!==i||o.absDatapath(".")!==a)return;let l=new Map,u=new Set,c=f=>{for(let h of["collapsed","checkbox"]){let p=f.getAttr(h);f.pointerType(p)&&u.add(f.absDatapath(p))}};c(o);let d=f=>{for(let h of f.getNodes()){h.nodeTag==="groupletCard"&&c(h);let p=h.getAttr("value");if(!h._getMeta("data_element")&&h.pointerType(p)==="^"&&!ne(p)){let m=h.absDatapath(p);m!==null&&(a===""||m.startsWith(`${a}.`))&&l.set(m,{child:h,pointer:p})}h.staticValue instanceof I&&d(h.staticValue)}};d(i);for(let[f,{child:h,pointer:p}]of l){if(!r()||o.value!==i||o.absDatapath(".")!==a)break;u.has(f)||h.getAttr("value")!==p||h.absDatapath(p)!==f||e.runtime.renderer.html.writeParameter(h,"value",null)}}finally{this.#t=!1}}}};var As="connect_on",Si=class{#e;#t;#r;#n;#o;static declared(e){return Object.entries(e.getAttr()??{}).filter(([t,r])=>t.startsWith(As)&&t.length>As.length&&r!=null).map(([t,r])=>[t,t.slice(As.length).toLowerCase(),r])}constructor(e,t,r,o,i=`${As}${r}`){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.#o=i}get binding(){return this.#e}get node(){return this.binding.node}get element(){return this.#t.element}get eventName(){return this.#r}get handler(){return this.#n}get attribute(){return this.#o}attach(){this.element.addEventListener(this.eventName,this)}detach(){this.element.removeEventListener(this.eventName,this)}handleEvent(e){if(this.binding.closed)return;let t=this.node,r=this.binding.runtime;if(xi(this.handler))return er(r,t,this.handler,e);r.inlineCompiler.compile(t,this.attribute,this.handler,["event"])({event:e})}};function cc(n){if(n==null||n==="")return null;if(typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)||n instanceof Date&&Number.isFinite(n.getTime())||le(n)&&n.isFinite())return n;throw new TypeError("Column filters require loaded scalar values")}function dn(n){return L(cc(n))}function Gp(n){if(!Array.isArray(n))throw new TypeError("Column selection requires an array or null");return Object.freeze([...new Map(n.map(e=>{let t=dn(e);return[t,j(t)]})).values()])}function Wp(n){if(n===null)return null;let{from:e,to:t,dtype:r,timeZone:o}=n;if(!["D","DH","DHZ"].includes(r))throw new TypeError("Date range requires a date column");for(let i of[e,t])if(i!==null&&(!(i instanceof Date)||!Number.isFinite(i.getTime())||i.getUTCHours()||i.getUTCMinutes()||i.getUTCSeconds()||i.getUTCMilliseconds()))throw new TypeError("Date bounds require civil dates");if(e&&t&&e>t)throw new RangeError("From must not be after To.");if(r==="DHZ"&&!o)throw new TypeError("DHZ requires a timeZone");return e||t?Object.freeze({from:e?.toISOString().slice(0,10)??null,to:t?.toISOString().slice(0,10)??null,dtype:r,timeZone:o}):null}function Ds(n,e){if(!e)return!0;if(n==null||n==="")return!1;if(!(n instanceof Date)||!Number.isFinite(n.getTime()))throw new TypeError("Date range requires date values");let t;if(e.dtype==="DHZ"){let r=new Intl.DateTimeFormat("en",{timeZone:e.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),o=i=>r.find(a=>a.type===i).value;t=`${o("year")}-${o("month")}-${o("day")}`}else t=n.toISOString().slice(0,10);return(!e.from||t>=e.from)&&(!e.to||t<=e.to)}function fn(n,e){return e===2?n%4===0&&(n%100!==0||n%400===0)?29:28:[4,6,9,11].includes(e)?30:31}function ut(n,e,t){if(![n,e,t].every(Number.isInteger)||n<1||n>9999||e<1||e>12||t<1||t>fn(n,e))throw new RangeError("Date must exist in Gregorian years 0001\u20139999.");return`${String(n).padStart(4,"0")}-${String(e).padStart(2,"0")}-${String(t).padStart(2,"0")}`}function hn(n){if(typeof n!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(n))throw new RangeError("Expected a civil date in YYYY-MM-DD format.");let e=n.split("-").map(Number);return ut(...e),e}function Ci(n,e,t){let r=n-1,o=365*r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400)+t-1;for(let i=1;i<e;i++)o+=fn(n,i);return o}function Ni(n,e){let t=Ci(...hn(n))+e;if(!Number.isSafeInteger(t)||t<0||t>Ci(9999,12,31))throw new RangeError("Date offset exceeds Gregorian years 0001\u20139999.");let r=1,o=1e4;for(;o-r>1;){let a=Math.floor((r+o)/2);Ci(a,1,1)<=t?r=a:o=a}t-=Ci(r,1,1);let i=1;for(;t>=fn(r,i);)t-=fn(r,i++);return ut(r,i,t+1)}function dc(n){return Ni(n,-(Ci(...hn(n))%7))}function Yp(n,e,t=0,r=1){let o=n*12+e-1+t,i=Math.floor(o/12),a=(o%12+12)%12+1,s=o+r-1,l=Math.floor(s/12),u=(s%12+12)%12+1;return{start:ut(i,a,1),end:ut(l,u,fn(l,u))}}var Ss={en:{months:{january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12,jan:1,feb:2,mar:3,apr:4,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12},weekdays:{monday:0,tuesday:1,wednesday:2,thursday:3,friday:4,saturday:5,sunday:6,mon:0,tue:1,wed:2,thu:3,fri:4,sat:5,sun:6},quarters:{"1st quarter":1,"2nd quarter":2,"3rd quarter":3,"4th quarter":4,q1:1,q2:2,q3:3,q4:4},keywords:{today:["today"],yesterday:["yesterday"],tomorrow:["tomorrow"],this_week:["this week","week"],last_week:["last week"],next_week:["next week"],this_month:["this month","month"],last_month:["last month"],next_month:["next month"],last:["last"],next:["next"],articles:["the"],from:["from","between"],to:["to","and"],no_period:["no period","always"]},date_order:{default:"MDY",GB:"DMY",AU:"DMY",IE:"DMY",NZ:"DMY",IN:"DMY"}},it:{months:{gennaio:1,febbraio:2,marzo:3,aprile:4,maggio:5,giugno:6,luglio:7,agosto:8,settembre:9,ottobre:10,novembre:11,dicembre:12,gen:1,feb:2,mar:3,apr:4,mag:5,giu:6,lug:7,ago:8,set:9,ott:10,nov:11,dic:12},weekdays:{luned\u00EC:0,marted\u00EC:1,mercoled\u00EC:2,gioved\u00EC:3,venerd\u00EC:4,sabato:5,domenica:6,lun:0,mar:1,mer:2,gio:3,ven:4,sab:5,dom:6},quarters:{"1\xBA trimestre":1,"2\xBA trimestre":2,"3\xBA trimestre":3,"4\xBA trimestre":4,"1\xB0 trimestre":1,"2\xB0 trimestre":2,"3\xB0 trimestre":3,"4\xB0 trimestre":4,t1:1,t2:2,t3:3,t4:4,q1:1,q2:2,q3:3,q4:4},keywords:{today:["oggi"],yesterday:["ieri"],tomorrow:["domani"],this_week:["questa settimana","settimana"],last_week:["settimana scorsa"],next_week:["settimana prossima"],this_month:["questo mese","mese"],last_month:["mese scorso"],next_month:["mese prossimo"],last:["scorso","scorsa"],next:["prossimo","prossima"],articles:["il","lo","la"],from:["da","dal","dalla","tra","fra"],to:["a","al","alla","e"],no_period:["-","senza periodo","sempre"]},date_order:{default:"DMY"}}};function Xp(n){if(typeof n!="string")throw new RangeError("A supported locale is required.");let e=n.replaceAll("-","_"),t=e.indexOf("_"),r=(t<0?e:e.slice(0,t)).toLowerCase(),o=(t<0?"":e.slice(t+1)).toUpperCase();if(!Object.hasOwn(Ss,r))throw new RangeError(`Unsupported locale: ${n}`);let i=Ss[r];return{dictionary:i,phrases:s=>[...new Set([...i.keywords[s],...Ss.en.keywords[s]])],order:i.date_order[o]??i.date_order.default}}var pn=/^(?:\d{4}|\d{2})$/,Zp=/^\d{1,2}$/,Ii=(n,e)=>({ok:!1,error:{code:n,message:e}}),gn=(n="UNRECOGNIZED_EXPRESSION",e="Text is not a supported date expression.")=>{throw Object.assign(new SyntaxError(e),{code:n})},Qp=(n,e)=>Object.hasOwn(n,e);function mn(n,e){if(n.length===4)return Number(n);let t=e.year+e.twoDigitYearAhead-100;return t+((Number(n)-t)%100+100)%100}function Zv(n,e){if(n.includes(";")){let o=n.split(";").map(i=>i.trim());return o.length!==2?gn("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:o,range:!0}}if(e.phrases("no_period").includes(n))return{bounds:["",""],range:!0};let t=e.phrases("to"),r=e.phrases("from");for(let o of t)if(n.startsWith(`${o} `))return{bounds:["",n.slice(o.length+1).trim()],range:!0};for(let o of t){let i=` ${o} `;if(!n.includes(i))continue;for(let s of r)if(n.startsWith(`${s} `)){n=n.slice(s.length+1);break}let a=n.split(i).map(s=>s.trim());return a.length!==2?gn("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:a,range:!0}}for(let o of r)if(n.startsWith(`${o} `))return{bounds:[n.slice(o.length+1).trim(),""],range:!0};return{bounds:[n,n],range:!1}}function Kv(n,e,t){let r=[[n,0]],o=/^(.+?)\s*([+-])\s*(\d+)$/.exec(n);o&&r.push([o[1],Number(o[2]+o[3])]);let i={today:0,yesterday:-1,tomorrow:1,this_week:0,last_week:-1,next_week:1,this_month:0,last_month:-1,next_month:1};for(let[a,s]of r)for(let[l,u]of Object.entries(i))if(e.phrases(l).includes(a)){if(l.endsWith("_week"))return Ni(dc(e.workdate),(u+s)*7+(t?6:0));if(l.endsWith("_month")){let c=Yp(e.year,e.month,u+s);return t?c.end:c.start}return Ni(e.workdate,u+s)}return null}function Jv(n,e,t){let r=Object.entries(e.dictionary.quarters).sort((o,i)=>i[0].length-o[0].length);for(let[o,i]of r){let a;if(n===o)a=null;else if(n.startsWith(o)&&pn.test(n.slice(o.length).trim()))a=mn(n.slice(o.length).trim(),e);else if(n.endsWith(o)&&pn.test(n.slice(0,-o.length).trim()))a=mn(n.slice(0,-o.length).trim(),e);else continue;return{year:a,month:t?i*3:i*3-2}}return null}function Kp(n,e){if(Qp(e.months,n))return e.months[n];let t=/^m(\d{1,2})$/.exec(n);return t&&Number(t[1])>=1&&Number(t[1])<=12?Number(t[1]):null}function Qv(n,e){let t=n.split(/\s+/),r=t.map((u,c)=>Kp(u,e.dictionary)?c:-1).filter(u=>u>=0);if(!r.length)return null;if(r.length!==1)return gn();let o=r[0],i=Kp(t[o],e.dictionary),a=t.slice(0,o),s=t.slice(o+1),l=[...a,...s];if(l.length===1&&e.phrases("last").includes(l[0]))return{year:e.year-(i>e.month?1:0),month:i};if(l.length===1&&e.phrases("next").includes(l[0]))return{year:e.year+(i<e.month?1:0),month:i};if(!l.length)return{year:null,month:i};if(!a.length&&s.length===1&&pn.test(s[0]))return{year:mn(s[0],e),month:i};if(a.length===1&&Zp.test(a[0])){if(!s.length)return ut(e.year,i,Number(a[0]));if(s.length===1&&pn.test(s[0]))return ut(mn(s[0],e),i,Number(a[0]))}return!a.length&&s.length===2&&Zp.test(s[0])&&pn.test(s[1])?ut(mn(s[1],e),i,Number(s[0])):gn()}function e2(n,e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);if(t)return ut(...t.slice(1).map(Number));let r=/^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(n),o={};if(r)e.order.split("").forEach((s,l)=>{o[s]=r[l+1]});else if(/^(?:\d{6}|\d{8})$/.test(n)){let s=n.length===8?4:2;for(let l of e.order){let u=l==="Y"?s:2;o[l]=n.slice(0,u),n=n.slice(u)}}else return null;if(!pn.test(o.Y)||o.D.length>2||o.M.length>2)return gn();let i=Number(o.D),a=Number(o.M);return r&&a>12&&i<=12&&([i,a]=[a,i]),ut(mn(o.Y,e),a,i)}function Jp(n,e,t){if(!n)return null;let r=e.phrases("articles");if(n=n.split(/\s+/).filter(i=>!r.includes(i)).join(" "),!n)return gn();if(pn.test(n))return ut(mn(n,e),t?12:1,t?31:1);let o=Kv(n,e,t)??Jv(n,e,t)??Qv(n,e);return o!==null?o:Qp(e.dictionary.weekdays,n)?Ni(dc(e.workdate),e.dictionary.weekdays[n]):e2(n,e)??gn()}function t2(n,e,t){if(n===null||typeof n=="string")return n;let r=n.year??t.year,o=typeof e=="string"?hn(e)[0]:e?.year,i=typeof e=="string"?hn(e)[1]:e?.month;return o&&(r>o&&(r=o),r===o&&n.month>i&&r--),ut(r,n.month,1)}function r2(n,e,t){if(n===null||typeof n=="string")return n;let r=n.year??t.year;if(e!==null){let[o,i]=hn(e);r<o&&(r=o),r===o&&i>n.month&&r++}return ut(r,n.month,fn(r,n.month))}function Cs(n,e={}){if(!e||typeof e!="object"||Array.isArray(e))return Ii("INVALID_CONTEXT","Options must provide a civil workdate and supported locale.");let t;try{let{locale:r="it-IT",workdate:o,twoDigitYearAhead:i=20}=e,[a,s]=hn(o);if(!Number.isInteger(i)||i<0||i>99)throw new RangeError("twoDigitYearAhead must be an integer from 0 to 99.");t={...Xp(r),workdate:o,year:a,month:s,twoDigitYearAhead:i}}catch(r){return Ii("INVALID_CONTEXT",r.message)}if(typeof n!="string")return Ii("INVALID_INPUT","Expression must be a string.");try{let r=n.toLowerCase().trim().replaceAll(",",""),{bounds:o,range:i}=Zv(r,t),a=Jp(o[1],t,!0),s=Jp(o[0],t,!1),l=t2(s,a,t),u=r2(a,l,t);return!i&&typeof s=="string"&&l===u?{ok:!0,kind:"date",date:l}:{ok:!0,kind:"period",start:l,end:u}}catch(r){if(r instanceof RangeError)return Ii("INVALID_DATE",r.message);if(r instanceof SyntaxError)return Ii(r.code,r.message);throw r}}function em(n){if(n===null)return null;let{value:e,columns:t,dtype:r,locale:o}=n;if(typeof e!="string"||!Array.isArray(t)||!t.length||t.some(u=>typeof u!="string"||!u||u==="rowidx")||!["T","L","R","N","D"].includes(r))throw new TypeError("Invalid collection filter");if(!e.trim())return null;if(r==="T"){let u=n.literal===!0?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e,c=new RegExp(u,"i");return d=>c.test(t.map(f=>n2(d(f),o,n.timeZone)).join(" "))}if(t.length!==1)throw new TypeError("Typed filters require one column");let i=/^\s*(<=|>=|==|!=|[<>=!#])\s*(.+?)\s*$/.exec(e);if(!i)throw new Error("Enter a comparison, for example > 100 or = 12.");let[,a,s]=i,l;if(r==="D"){let u=new Date,c=`${u.getFullYear()}-${String(u.getMonth()+1).padStart(2,"0")}-${String(u.getDate()).padStart(2,"0")}`,d=Cs(s,{locale:o,workdate:c});if(!d.ok||d.kind!=="date")throw new Error("Enter one complete date after the comparison.");l=new Date(`${d.date}T00:00:00Z`)}else l=o2(s,o);return u=>{let c=u(t[0]);if(c==null)return!1;if(r==="D"?!(c instanceof Date)||!Number.isFinite(c.getTime()):!(typeof c=="number"&&Number.isFinite(c)||le(c)&&c.isFinite()))throw new TypeError(`Filter value does not match ${r}`);let d=le(l)?-l.comparedTo(c):c<l?-1:c>l?1:0;switch(a){case"=":case"==":return d===0;case"!":case"#":case"!=":return d!==0;case"<":return d<0;case">":return d>0;case"<=":return d<=0;case">=":return d>=0}}}function n2(n,e,t){return n==null?"":typeof n=="string"||typeof n=="boolean"?String(n):hs(n,{pattern:n instanceof Date?"short":"#,##0.####################"},{locale:e,timeZone:t})}function o2(n,e){let t=new Intl.NumberFormat(e).formatToParts(-12345.6),r=t.find(l=>l.type==="decimal").value,o=t.find(l=>l.type==="group")?.value,i=t.find(l=>l.type==="minusSign").value,a=n.replaceAll(i,"-");if(o&&a.includes(o)){let u=a.split(r)[0].replace(/^[+-]/,"").split(o),c=new Intl.NumberFormat(e).formatToParts(1234567890123).filter(h=>h.type==="integer").map(h=>h.value.length),d=c.at(-1),f=c.at(-2);if(a.split(r).slice(1).some(h=>h.includes(o))||!/^\d+$/.test(u[0])||u[0].length>f||u.slice(1).some((h,p)=>!/^\d+$/.test(h)||h.length!==(p===u.length-2?d:f)))throw new Error("Invalid numeric grouping.");a=a.replaceAll(o,"")}if(a=a.replace(r,"."),!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(a))throw new Error("Enter a complete number.");let s=Lt(a);if(!le(s)||!s.isFinite())throw new Error("A finite Decimal backend is required.");return s}function tm(n,e){return(","+n+",").includes(","+e+",")}function rm(n){if(typeof n!="string")throw new TypeError("grid checked must refer to a string (empty string for an empty set)");return n}function nm(n){if(typeof n!="string"||!n||n.includes(","))throw new TypeError("grid checkedField requires nonempty text IDs without commas");return n}var Ns=class{#e=new Set;constructor(e,t){if(!(e instanceof E))throw new TypeError("collection store requires a Bag");if(!["values","attributes"].includes(t))throw new TypeError("collection store rowMode must explicitly be values or attributes");if(!e.parentNode)throw new TypeError("collection store requires a Bag attached to Data");this.bag=e,this.rowMode=t}subscribe(e){return this.#e.add(e),()=>this.#e.delete(e)}receiveData(e,t=null,r=null){Is(this.#e,{full:t===null,rows:t?[t]:[],event:e,field:r})}getRows(){let e=this.bag.getNodes();for(let t of e){if(t.resolver)throw new TypeError("collection store requires loaded rows");if(this.rowMode==="values"&&!(t.staticValue instanceof E))throw new TypeError(`collection store row ${t.label} must contain a Bag`)}return e}value(e,t){if(e.resolver)throw new TypeError("collection store requires loaded rows");if(this.rowMode==="attributes")return e.getAttr(t);let r=e.staticValue;if(!(r instanceof E))throw new TypeError(`collection store row ${e.label} must contain a Bag`);let o=r.getNode(t);if(o?.resolver)throw new TypeError("collection store requires loaded cells");return o?.staticValue}};function Is(n,e){let t=[],r=Object.freeze({full:e.full,rows:Object.freeze([...e.rows]),event:e.event??null,field:e.field??null});for(let o of[...n])if(n.has(o))try{o(r)}catch(i){t.push(i)}if(t.length)throw new AggregateError(t,"Collection notification failed")}var Os=class{#e;#t=null;#r=new Set;#n=new Map;#o="";#i=new Map;#a=null;constructor(e){this.bindStore(e)}get bag(){return this.#e.bag}get rowMode(){return this.#e.rowMode}get sortedBy(){return this.#o}get criteria(){return om(this.#o)}get filter(){return this.#i.get("search")?.definition??null}get filterSignature(){return JSON.stringify([...this.#i].map(([e,{definition:t}])=>[e,t]))}get filterContributions(){return Object.freeze([...this.#i].map(([e,t])=>Object.freeze([e,Object.freeze({...t})])))}copyFiltersFrom(e){this.filterSignature!==e.filterSignature&&this.#u(this.#s(),this.#o,new Map(e.filterContributions))}get filtered(){return this.#a===null?null:[...this.#a]}isFiltered(){return this.#a!==null}value(e,t){return this.#e.value(e,t)}subscribe(e){return this.#r.add(e),()=>this.#r.delete(e)}connect(){this.#t||(this.synchronize(),this.#t=this.#e.subscribe(e=>this.synchronize(e)))}disconnect(){this.#t?.(),this.#t=null}bindStore(e){if(this.#e===e)return;let t=this.#t!==null;this.disconnect(),this.#e=e,this.#n.clear(),t?this.connect():this.synchronize()}getRows(e=!0){let t=this.#s();return e&&this.#a!==null?this.#a.map(r=>t[r]):t}#s(){return this.#e.getRows().toSorted((e,t)=>(this.#n.get(e)??1/0)-(this.#n.get(t)??1/0))}synchronize(e={full:!0,rows:[]}){if(!e.full&&!this.#o&&!this.#i.size){Is(this.#r,{full:e.full,rows:e.rows});return}this.#u(this.#c(this.#s(),this.criteria),this.#o,this.#i,e)}sort(e){let t=this.#c(this.#s(),om(e));this.#u(t,e,this.#i)}moveRow(e,t,r=!1){if(e===t||e.parentBag!==this.bag||t.parentBag!==this.bag)return;let o=this.getRows(!1);o.splice(o.indexOf(e),1),o.splice(o.indexOf(t)+Number(r),0,e),this.#u(o,"",this.#i)}applyFilter(e,t="search"){if(!["base","search"].includes(t))throw new TypeError("Unknown collection filter contribution");let r=e===null?null:Object.freeze({...e,columns:Object.freeze([...e.columns])});this.#l(t,r,em(r))}applySetFilter(e){let t=e===null?null:Object.freeze(e.map(({field:o,value:i})=>{if(typeof o!="string"||!o)throw new TypeError("Set filter requires an identity field");return rm(i),Object.freeze({field:o,value:i})})),r=t===null?null:o=>t.every(({field:i,value:a})=>tm(a,nm(o(i))));this.#l("sets",t,r)}columnFilter(e){return this.#i.get(`column:${e}`)?.definition.values??null}columnRange(e){let t=this.#i.get(`column:${e}`)?.definition.range;return t?{...t,from:t.from&&new Date(t.from+"T00:00:00Z"),to:t.to&&new Date(t.to+"T00:00:00Z")}:null}applyColumnFilter(e,t,r=this.columnRange(e)){if(r=Wp(r),typeof e!="string"||!e)throw new TypeError("Column filter requires a field");let o=t===null?null:Gp(t),i=o?.map(dn),a=o===null&&r===null?null:Object.freeze({field:e,values:o,keys:i&&Object.freeze(i),range:r}),s=a===null?null:l=>Ds(l(e),r)&&(i===void 0||i.includes(dn(l(e))));this.#l(`column:${e}`,a,s)}columnFacets(e){let t=new Map,r=this.#i.get(`column:${e}`)?.definition.range??null,o=this.columnFilter(e),i=o?.map(dn),a=[...this.#i].filter(([s])=>s!==`column:${e}`).map(([,s])=>s.predicate).filter(s=>s!==null);for(let s of this.#s()){let l=cc(this.value(s,e)),u=dn(l);t.has(u)||t.set(u,{key:u,value:l,count:0,selected:Ds(l,r)&&(i===void 0||i.includes(u))}),a.every(c=>c(d=>this.value(s,d)))&&t.get(u).count++}for(let s of o??[]){let l=dn(s);t.has(l)||t.set(l,{key:l,value:s,count:0,selected:!0})}return[...t.values()].filter(s=>Ds(s.value,r))}#l(e,t,r){if(JSON.stringify(this.#i.get(e)?.definition??null)===JSON.stringify(t))return;let o=new Map(this.#i);t===null?o.delete(e):o.set(e,{definition:t,predicate:r}),this.#u(this.#s(),this.#o,o)}#u(e,t,r,o={full:!1,rows:[]}){let i=[...r.values()].map(c=>c.predicate).filter(c=>c!==null),a=i.length?e.flatMap((c,d)=>i.every(f=>f(h=>this.value(c,h)))?[d]:[]):null,s=o.full||t!==this.#o||r!==this.#i||e.length!==this.#n.size||e.some((c,d)=>this.#n.get(c)!==d)||JSON.stringify(a)!==JSON.stringify(this.#a);this.#n=new Map(e.map((c,d)=>[c,d])),this.#o=t,this.#i=r,this.#a=a;let l=a===null?null:new Set(a),u=s?[]:o.rows.filter(c=>this.#n.has(c)&&(l===null||l.has(this.#n.get(c))));(s||u.length||o.rows.length)&&Is(this.#r,{full:s,rows:u})}#c(e,t){if(!t.length)return e;let r=e.map(o=>({node:o,keys:t.map(({field:i})=>this.value(o,i))}));for(let o=0;o<t.length;o++)if(new Set(r.map(a=>i2(a.keys[o])).filter(a=>a!==null)).size>1)throw new TypeError(`collection view cannot compare mixed types in ${t[o].field}`);return r.sort((o,i)=>{for(let[a,{direction:s}]of t.entries()){let l=a2(o.keys[a],i.keys[a]);if(l)return s==="a"?l:-l}return 0}).map(o=>o.node)}};function om(n){if(typeof n!="string")throw new TypeError("collection view sortedBy must be a string");if(n==="")return[];let e=new Set;return n.split(",").map(t=>{let r=/^([^,:]+):([ad])$/.exec(t);if(!r||e.has(r[1]))throw new TypeError(`Invalid collection view sort criterion: ${t}`);return e.add(r[1]),{field:r[1],direction:r[2]}})}function i2(n){if(n==null)return null;if(typeof n=="number"&&Number.isFinite(n)||le(n)&&n.isFinite())return"number";if(n instanceof Date&&Number.isFinite(n.getTime()))return"date";if(typeof n=="string"||typeof n=="boolean")return typeof n;throw new TypeError("collection view sort requires loaded finite scalar values")}function a2(n,e){return n==null||e==null?n==null?e==null?0:-1:1:le(n)?n.comparedTo(e):le(e)?-e.comparedTo(n):n<e?-1:n>e?1:0}var Rs=class{constructor(e=null,t=null){this.parent=e,this.segment=t,this.children=new Map,this.registrations=new Set}},fc=class{#e;#t;#r;#n;#o;#i=!0;#a;constructor(e,{path:t,attr:r,recipient:o,order:i,subtree:a=!1}){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.#o=i,this.#a=a}get router(){return this.#e}get path(){return this.#t}get attr(){return this.#r}get recipient(){return this.#n}get subtree(){return this.#a}get active(){return this.#i}get order(){return this.#o}close(){this.active&&(this.#i=!1,this.router.unregister(this))}},hc=class{constructor({evt:e,node:t,path:r,oldvalue:o,attrsDiff:i,reason:a,fired:s,level:l,registration:u,index:c}){this.evt=e,this.node=t,this.path=r,this.oldvalue=o,this.attrsDiff=i,this.reason=a,this.fired=s,this.level=l,this.registration=u,this.index=c}},Bs=class{#e;#t=new Rs;#r=new Map;#n=0;#o=0;constructor(e){this.#e=e}get runtime(){return this.#e}get size(){return this.#n}register({path:e,attr:t=null,recipient:r,subtree:o=!1}){if(typeof e!="string"||e==="")throw new TypeError(`A Data registration requires a path: ${e}`);let i=this.#t;for(let s of e.split(".")){let l=i.children.get(s);l||(l=new Rs(i,s),i.children.set(s,l)),i=l}this.#o+=1;let a=new fc(this,{path:e,attr:t,recipient:r,order:this.#o,subtree:o});return i.registrations.add(a),this.#r.set(a,i),this.#n+=1,a}unregister(e){let t=this.#r.get(e);if(t)for(this.#r.delete(e),t.registrations.delete(e),this.#n-=1;t.parent&&!t.children.size&&!t.registrations.size;)t.parent.children.delete(t.segment),t=t.parent}deliver(e){let{pathlist:t}=e;if(!t?.length||t[0]!==mi||e.reason==="autocreate")return;let r=t.slice(1),o=e.evt==="ins"||e.evt==="del";for(let i of Array.isArray(e.node)?e.node:[e.node]){let a=o?[...r,i.label]:r,s=a.join(".");for(let[l,u]of this.#i(a,e))l.active&&l.recipient.receive(new hc({evt:e.evt,node:i,path:s,oldvalue:e.oldvalue??null,attrsDiff:e.attrs_diff??null,reason:e.reason??null,fired:e.fired??!1,level:u,registration:l,index:e.ind??null}))}}#i(e,t){let r=[],o=this.#t;for(let a of e){for(let s of o.registrations)o!==this.#t&&this.#a(s,"child",t)&&r.push([s,"child"]);if(o=o.children.get(a),!o)return r.sort(([s],[l])=>s.order-l.order)}for(let a of o.registrations)this.#a(a,"node",t)&&r.push([a,"node"]);let i=[...o.children.values()];for(;i.length;){let a=i.pop();for(let s of a.registrations)this.#a(s,"container",t)&&r.push([s,"container"]);i.push(...a.children.values())}return r.sort(([a],[s])=>a.order-s.order)}#a(e,t,r){let{evt:o}=r;return e.subtree?t!=="container"||o!=="upd_attrs":e.attr===null?o==="upd_attrs"?!1:!(t==="child"&&r.fired):t==="child"?!1:t==="container"?o!=="upd_attrs":o==="ins"||o==="del"?!0:Object.hasOwn(r.attrs_diff??{},e.attr)}};var s2="#",l2=/[A-Za-z_$][\w$]*/g;function im(n){let e=new Map;for(let u of n){if(u.formula==null)continue;let c=u.formula.trim(),d=c===s2?{kind:"index",field:null}:c.startsWith("+=")?{kind:"running",field:c.slice(2).trim()}:c.startsWith("%=")?{kind:"percent",field:c.slice(2).trim()}:null;if(d&&d.kind!=="index"&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(d.field))throw new TypeError(`grid formula '${c}' requires a field`);let f=new Map;for(let[m,b]of Object.entries(u))m.startsWith("formula_")&&f.set(m.slice(8),b);let h=null;if(!d)try{h=u2(c)}catch{}let p=d?new Set(d.field?[d.field]:[]):new Set(c.match(l2)??[]);e.set(u.field,{field:u.field,formula:u.formula,special:d,arithmetic:h,parameters:f,references:p,calculated:u.calculated===!0,column:u})}let t=new Map;for(let u of e.values())for(let c of u.references)t.has(c)||t.set(c,new Set),t.get(c).add(u.field);let r=new Set,o=new Set,i=[],a=u=>{if(!o.has(u)){if(r.has(u))throw new TypeError(`grid formula dependency cycle at '${u}'`);r.add(u);for(let c of e.get(u).references)e.has(c)&&a(c);r.delete(u),o.add(u),i.push(u)}};for(let u of e.keys())a(u);let s=new Set;for(let u of i){let c=e.get(u);(["index","running"].includes(c.special?.kind)||[...c.references].some(d=>s.has(d)))&&s.add(u)}let l=new Map([...e].map(([u,c])=>[u,Object.freeze({...c,view:s.has(u)})]));return Object.freeze({definitions:l,triggered:t,order:Object.freeze(i),viewFields:s})}function u2(n){let e=c2(n),t=0,r=()=>e[t],o=u=>{if(r().value!==u)throw new SyntaxError(`expected '${u}' in arithmetic formula`);return e[t++]},i={"+":1,"-":1,"*":2,"/":2,"%":2,"**":3},a=()=>{let u=r();if(u.type==="number")return t++,{kind:"number",value:u.value};if(u.type==="name")return t++,{kind:"name",value:u.value};if(u.value==="("){t++;let c=s(0);return o(")"),c}if(u.value==="+"||u.value==="-")return t++,{kind:"unary",operator:u.value,child:a()};throw new SyntaxError(`unexpected '${u.value||"end"}' in arithmetic formula`)},s=u=>{let c=a();for(;i[r().value]>=u;){let d=e[t++].value,f=s(i[d]+(d==="**"?0:1));c={kind:"binary",operator:d,left:c,right:f}}return c},l=s(0);if(r().type!=="eof")throw new SyntaxError(`unexpected '${r().value}' in arithmetic formula`);return l}function c2(n){let e=[],t=0;for(;t<n.length;){let r=n.slice(t),o=/^\s+/.exec(r);if(o){t+=o[0].length;continue}let i=/^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(r);if(i){e.push({type:"number",value:i[0]}),t+=i[0].length;continue}let a=/^[A-Za-z_$][\w$]*/.exec(r);if(a){e.push({type:"name",value:a[0]}),t+=a[0].length;continue}let s=/^(?:\*\*|[()+\-*/%])/.exec(r);if(s){e.push({type:"operator",value:s[0]}),t+=s[0].length;continue}throw new SyntaxError(`unsupported arithmetic formula token at ${t}`)}return e.push({type:"eof",value:""}),e}var d2=new Set(["T","B","L","R","N","D","H","DHZ"]),f2=new Set(["tag","field","name","title","dtype","width","align","format","columnset","white_space","max_height","edit","check","checked","checkedField","formula","calculated","hidden","totalize","footer_value","footer_format"]),h2=/^formula_[A-Za-z_$][\w$]*$/,p2=new Set(["tag","code","name","background","color"]),Oi=class{#e=new Map;constructor(e){if(!(e instanceof E))throw new TypeError("grid structpath must resolve to a Bag");let t=$s(e,"view_0"),r=$s(e,"info"),o=$s(t,"rows_0"),i=$s(r,"columnsets"),a=new Set,s=new Map;for(let u of i.getNodes()){let c=u.getAttr();if(am(c,p2),pc(c.code,"colgroup code"),c.tag!=="columnset"||u.resolver||u.staticValue!=null||u.label!==c.code)throw new TypeError("grid columnset requires a scalar definition labelled by code");if(s.has(c.code))throw new TypeError(`Duplicate grid colgroup: ${c.code}`);if(c.name!=null&&typeof c.name!="string")throw new TypeError("grid group name must be text");for(let d of["background","color"])if(c[d]!=null&&typeof c[d]!="string")throw new TypeError(`grid ${d} must be text`);s.set(c.code,{...c,name:c.name??c.code})}this.columns=[],this.groups=[];let l=[];for(let u of o.getNodes()){let c=u.getAttr();if(am(c,f2,h2),c.tag!=="cell"||u.staticValue!=null||u.resolver)throw new TypeError("grid cell must be a scalar declaration");if(pc(c.field,"field"),a.has(c.field))throw new TypeError(`Duplicate grid field: ${c.field}`);if(a.add(c.field),this.#e.set(c.field,u),c.columnset!=null&&!s.has(c.columnset))throw new TypeError(`Unknown grid columnset: ${c.columnset}`);if(c.dtype!=null&&!d2.has(c.dtype))throw new TypeError(`Unsupported grid dtype: ${c.dtype}`);if(c.align!=null&&!["start","center","end"].includes(c.align))throw new TypeError("grid align requires start, center or end");if(c.width!=null&&(typeof c.width!="string"||!/^(?:\d+(?:\.\d+)?)(?:px|em|rem|ch|%)$/.test(c.width)))throw new TypeError("grid width requires a nonnegative CSS length (px, em, rem, ch or %)");if(c.max_height!=null&&(typeof c.max_height!="string"||!/^(?:\d+(?:\.\d+)?)(?:px|em|rem)$/.test(c.max_height)))throw new TypeError("grid max_height requires a nonnegative CSS length (px, em or rem)");if(c.white_space!=null&&!["normal","nowrap","pre-wrap"].includes(c.white_space))throw new TypeError("grid white_space requires normal, nowrap or pre-wrap");for(let p of["name","title","format"])if(c[p]!=null&&typeof c[p]!="string")throw new TypeError(`grid ${p} must be text`);if(c.edit!=null&&typeof c.edit!="boolean"&&(typeof c.edit!="object"||Array.isArray(c.edit)))throw new TypeError("grid edit requires a boolean or editor options");if(c.check!=null||c.checked!=null||c.checkedField!=null){if(!["multiple","single"].includes(c.check)||typeof c.checked!="string"||!c.checked.startsWith("^")||c.checked.length<2||c.checked.includes("?"))throw new TypeError("grid check requires single or multiple and checked=^DataPath");if(pc(c.checkedField,"checkedField"),c.edit)throw new TypeError("external check sets cannot edit row fields")}m2(c);let d=Object.freeze({...c,name:c.name??c.field,align:c.align??(["L","R","N"].includes(c.dtype)?"end":"start")});if(l.push(d),c.hidden)continue;this.columns.push(d);let f=c.columnset??null,h=this.groups.at(-1);(!h||h.code!==f)&&(h={code:f,...f===null?{name:null}:s.get(f),columns:[]},this.groups.push(h)),h.columns.push(d)}if(!this.columns.length)throw new TypeError("grid struct requires at least one column");this.fields=Object.freeze([...a]),this.formulas=im(l);for(let u of this.groups)Object.freeze(u.columns),Object.freeze(u);Object.freeze(this.columns),Object.freeze(this.groups),Object.freeze(this)}columnNode(e){return this.#e.get(e)}moveColumn(e,t,r=!1){let o=this.#e.get(e),i=this.#e.get(t);if(!o||!i||o===i)return;let a=o.parentBag,s=a.getNodes(),l=s.indexOf(o),u=s.indexOf(i),c=u+Number(r)-+(l<u);c!==l&&a.move(l,c)}setColumnWidth(e,t){if(!Number.isFinite(t)||t<=0)throw new TypeError("grid resized width must be positive pixels");this.#e.get(e).setAttr({width:`${Math.round(t)}px`})}};function $s(n,e){let t=n.getNode(e);if(!t||t.resolver||!(t.staticValue instanceof E))throw new TypeError(`grid struct requires Bag ${e}`);return t.staticValue}function am(n,e,t=null){for(let r of Object.keys(n))if(!e.has(r)&&!t?.test(r))throw new TypeError(`Unsupported grid struct attribute: ${r}`)}function m2(n){if(n.formula!=null&&(typeof n.formula!="string"||!n.formula.trim()))throw new TypeError("grid formula must be nonempty text");if(n.formula==null&&(n.calculated!=null||Object.keys(n).some(e=>e.startsWith("formula_"))))throw new TypeError(`grid ${n.field}: calculated and formula_<name> require a formula`);for(let e of["calculated","hidden"])if(n[e]!=null&&typeof n[e]!="boolean")throw new TypeError(`grid ${e} must be a boolean`);if(n.totalize!=null&&typeof n.totalize!="boolean"&&(typeof n.totalize!="string"||!n.totalize))throw new TypeError("grid totalize requires a boolean or a Data path");for(let e of["footer_value","footer_format"])if(n[e]!=null&&typeof n[e]!="string")throw new TypeError(`grid ${e} must be text`)}function pc(n,e){if(typeof n!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw new TypeError(`grid ${e} requires a simple field identifier`)}function sm(n){let e=new E,t=new E,r=new E;e.setItem("view_0",new E,{tag:"view"}),e.getItem("view_0").setItem("rows_0",t,{tag:"rows"}),e.setItem("info",new E),e.getItem("info").setItem("columnsets",r);let o=(i,a=null)=>{if(i.builder.validateNode(i),i.nodeTag!=="column"||i.staticValue!=null)throw new TypeError("grid column must be a scalar declaration");let s={tag:"cell"},l=["field","name","title","dtype","width","align","format","white_space","max_height","edit","check","checked","checkedField","formula","calculated","hidden","totalize","footer_value","footer_format",...Object.keys(i.getAttr()).filter(c=>c.startsWith("formula_"))];for(let c of l)i.getAttr(c)!=null&&(s[c]=i.getAttr(c));let u=`cell_${s.field}`;if(t.getNode(u))throw new TypeError(`Duplicate grid field: ${s.field}`);a!==null&&(s.columnset=a),t.setItem(u,null,s)};for(let i of n.getNodes())if(i.nodeTag==="column")o(i);else if(i.nodeTag==="colgroup"){if(i.builder.validateNode(i),!(i.staticValue instanceof I))throw new TypeError("grid colgroup requires column declarations");let a=i.getAttr("code");if(r.getNode(a))throw new TypeError(`Duplicate grid colgroup: ${a}`);let s={tag:"columnset",code:a,name:i.getAttr("name")??a};for(let l of["background","color"])i.getAttr(l)!=null&&(s[l]=i.getAttr(l));r.setItem(a,null,s);for(let l of i.staticValue.getNodes())o(l,a)}else throw new TypeError("grid struct accepts column and colgroup only");return e}function lm(n){if(n._getMeta("gramlot_component")?.bagStruct){let e=n.staticValue instanceof I?n.staticValue.getNodes():[];if(e.some(t=>!t._getMeta("gridStruct"))||e.length>1)throw new TypeError("grid accepts one struct declaration");if(e.length&&n.getAttr("structpath")!=null)throw new TypeError("grid requires structpath or nested struct, not both");if(!e.length&&!n.getAttr("structpath"))throw new TypeError("grid requires structpath or nested struct");if(!["values","attributes"].includes(n.getAttr("rowMode")))throw new TypeError("grid rowMode must explicitly be values or attributes")}if(n._getMeta("gridStruct")){if(!n.parentNode?._getMeta("gramlot_component")?.bagStruct)throw new TypeError("struct requires a grid parent");if(!(n.staticValue instanceof I))throw new TypeError("grid struct requires column declarations");new Oi(sm(n.staticValue))}}function um(n,e){let t=sm(n.staticValue);new Oi(t);let r=`_gramlot.grid.${crypto.randomUUID().replaceAll("-","")}.struct`;e.setItem(r,t,null,">",!1,!0,n),n.parentNode.setAttr({structpath:r},!1),n.setValue(null,!1)}var Ms=class{#e;constructor(e){this.#e=e}get runtime(){return this.#e}install(e){let t=Ri(e),r=this.setterNodes(e);gc(e);for(let o of r)o._getMeta("gridStruct")?um(o,this.runtime.data):this.applySetter(o),this.runtime.closeBranch(o),o.parentBag&&o.parentBag.popNode(o.label);this.applyDefaults(t.filter(o=>o.nodeTag&&!o._getMeta("data_element")))}setterNodes(e){return Ri(e).filter(t=>t.nodeTag==="dataSetter"||t._getMeta("gridStruct"))}applySetter(e){let t=e.absDatapath(e.pathAttribute("destination_path"));if(t===null)return;let r=e.getAttr("value")??null,o=b2(e.getAttr()),i=this.runtime.data;if(r!==null)i.setItem(t,r,o,">",!1,!0,e),r instanceof E&&e.setAttr({value:null},!1);else{let a=i.getNode(t);a?o&&a.setAttr(o,!0):i.setItem(t,null,o,">",!1,!0,e)}}applyDefaults(e){for(let t of e){let r=t.getAttr();for(let[o,i]of Object.entries(r)){if(!g2(t,o,i))continue;let a=o==="value"?r.default_value??r.default:r[`default_${o}`];a!=null&&this.#t(t,i,a)}this.#r(t,r)}}#t(e,t,r){let o=e.absDatapath(t);if(o===null)return;let[i,a=null]=o.split("?",2),s=this.runtime.data,l=s.getNode(i);if(a===null){if(l&&l.value!==null&&l.value!==void 0)return;s.setItem(i,r,null,">",!1,!0,e)}else if(l){let u=l.getAttr(a);u==null&&l.setAttr({[a]:r},!0)}else s.setItem(i,null,{[a]:r},">",!1,!0,e)}#r(e,t){let r={};for(let[a,s]of Object.entries(t))a.startsWith("attr_")&&(r[a.slice(5)]=ne(s)?Or(e,a):e.pointerType(s)?e.getRelativeData(s):s);if(!Object.keys(r).length)return;let o=[t.value,t.src].find(a=>e.pointerType(a));if(!o)return;let i=e.absDatapath(o);i!==null&&this.runtime.data.getNode(i.split("?",1)[0])?.setAttr(r,!0,!0,!1)}};function g2(n,e,t){return e==="_meta"||Zt.has(e)||e==="default"||e.startsWith("default_")||e.startsWith("attr_")||e.endsWith("_path")?!1:n.pointerType(t)!==null}function b2(n){let e={};for(let[t,r]of Object.entries(Cr(n??{})))Zt.has(t)||t.startsWith("_")||t==="destination_path"||t==="value"||r!=null&&(e[t]=r);return Object.keys(e).length?e:null}function w2(n){let e=n.builder;if(!(e instanceof Oe))throw new Error(`dataSetter '${n.label}': dataSetter is not supported inside ${e.constructor._name}`)}function gc(n){for(let e of Ri(n))lm(e),e.nodeTag==="dataSetter"&&w2(e),x2(e)}var _2=["_init","_onStart","_onBuilt","_delay","_timing","_userChanges"],y2=new Set(["dataFormula","dataController","dataRpc","dataRemote"]),v2=["_onCalling","_onResult","_onError"],E2=["_delay","_timing","_userChanges"],mc=["_init","_onBuilt","_onStart"];function x2(n){let e=i=>n.getAttr(i)!==null&&n.getAttr(i)!==void 0,t=!n._getMeta("data_element")&&typeof n.getAttr("remote")=="string";if(n.nodeTag!=="dataRpc"){let i=v2.find(a=>e(a)&&!(a==="_onCalling"&&(n.nodeTag==="dataRemote"||t)));if(i){let a=i==="_onCalling"?"dataRpc, dataRemote and remote":"dataRpc";throw new Error(`${n.nodeTag??"fragment"} '${n.label}': '${i}' is allowed only on ${a}`)}}if(y2.has(n.nodeTag)){let i=Object.entries(n.getAttr()).find(([,s])=>mt(s));if(i)throw new Error(`${n.nodeTag} '${n.label}': '${i[0]}' is a == expression, not accepted on ${n.nodeTag}`);let a=n.nodeTag==="dataRemote"?mc.find(e):null;if(a)throw new Error(`dataRemote '${n.label}': '${a}' is not accepted on dataRemote, its resolver loads when the Data is read`);for(let s of mc){let l=n.getAttr(s);if(!(l==null||typeof l=="boolean"||typeof l=="number"))throw new Error(`${n.nodeTag} '${n.label}': '${s}' accepts true, false, null or a number, not ${JSON.stringify(l)}`)}return}let r=_2.find(i=>e(i)&&!(i==="_delay"&&!n._getMeta("data_element")&&n.nodeTag!=="html_button")&&!(t&&E2.includes(i)));if(!r)return;let o=mc.includes(r)?"dataFormula, dataController and dataRpc":"dataFormula, dataController, dataRpc and dataRemote";throw new Error(`${n.nodeTag??"fragment"} '${n.label}': '${r}' is allowed only on ${o}`)}function Ri(n){if(n instanceof I)return n.getNodes().flatMap(t=>Ri(t));let e=[n];return n.value instanceof I&&e.push(...Ri(n.value)),e}var k2=new Set(["destination_path","result_path","func","formula","script","if","else","_init","_onStart","_onBuilt","_delay","_timing","_userChanges","_ask","_ask_if","_ask_title","_ask_onCancel","method","timeout","_onCalling","_onResult","_onError","cacheTime","sync"]),Bi=class{#e;#t=null;#r=null;constructor(e){this.#e=e}get binding(){return this.#e}debounce(e,t){this.#r?.();let r=null,o=setTimeout(()=>{r(),this.#r=null,t()},e);r=this.binding.track(()=>clearTimeout(o)),this.#r=()=>{clearTimeout(o),r(),this.#r=null}}startTiming(e,t){if(this.#t?.(),!(e>0))return;let r=setInterval(t,e*1e3),o=this.binding.track(()=>clearInterval(r));this.#t=()=>{clearInterval(r),o(),this.#t=null}}cancel(){this.#r?.(),this.#t?.()}},go=class{#e;#t=[];#r=new Set;#n;#o=null;#i=!1;constructor(e){this.#e=e,this.#n=new Bi(e),e.track(()=>{this.cancel(),this.#p(),this.#f()})}get binding(){return this.#e}get node(){return this.binding.node}get kind(){throw new Error("Provider.kind is defined by FormulaProvider, ControllerProvider, RpcProvider and RemoteProvider")}register(){let e=this.node,t=e.getAttr("_onStart");if(typeof t=="number"&&!(Number.isFinite(t)&&t>=0))throw new Error(`${e.nodeTag} '${e.label}': _onStart must be true or a delay in ms not below 0: ${t}`);this.#p();let r=this.binding.runtime.router,o=Ft(e,e.getAttr("_timing"));for(let[i,a]of e.pointers()){if(i==="datapath")continue;let s=e.absDatapath(a);if(s===null)continue;let[l,u=null]=s.split("?",2),c=r.register({path:l,attr:u,recipient:this});this.#t.push(c),(i==="_timing"||o.has(i))&&this.#r.add(c)}this.#t.push(...this.binding.runtime.subscriptions.subscribeNode(e,(i,a,s)=>(l,u)=>{let c={kind:"subscription",topic:s,payload:l,metadata:u};if(this.#s("_userChanges")&&s!=="node")return;let d=this.#s("_delay");d>0?this.#n.debounce(d,()=>this.invoke(c)):this.invoke(c)})),this.#a(),this.kind==="remote"&&this.invoke({kind:"install",change:null})}receive(e){if(this.#r.has(e.registration)){this.#a();return}if(this.#s("_userChanges")&&e.level!=="node")return;let t={kind:"data",change:e},r=this.#s("_delay");r>0?this.#n.debounce(r,()=>this.invoke(t)):this.invoke(t)}invoke(e){if(this.binding.closed)return;let t=this.node,r=this.kind==="formula",o=this.kind==="rpc",i=this.kind==="remote",a=this.readArguments(e);e.askResult&&(Object.assign(a,e.askResult),a._askResult=e.askResult);let s=t.getAttr("_ask"),l=this.binding.runtime.askDialog;if(s&&!e.askDone&&l.required(this.binding,s,a,"_ask"))return l.show(this.binding,s,a,t.getAttr("_ask_title")??"Warning").then(p=>{if(!this.binding.closed){if(p===null){let m=t.getAttr("_ask_onCancel");m&&this.#l("_ask_onCancel",m,m,a,!0);return}return this.invoke({...e,askDone:!0,askResult:p})}});let[u,c]=[r?"formula":"script",t.getAttr(r?"formula":"script")],d=t.getAttr("_if");if(d&&!this.#l("_if",d,`return (${d})`,a,!1)){if(i&&this.#f(),[u,c]=["_else",t.getAttr("_else")],!c)return;if(o||i){this.#l(u,c,c,a,!0);return}}if(o)return this.#u(a);if(i)return this.#d(a);let f=t.getAttr("func"),h;if(c)h=this.#l(u,c,r?`return ${c}`:c,a,!0);else if(f==null){if(!r)return;h=new E(Ps(a))}else{let{group:p,method:m}=this.binding.runtime.logicRegistry.resolve(f,t);h=r?m.call(p,a):m.call(p,t,a)}r&&t.setRelativeData(t.pathAttribute("result_path"),h)}readArguments(e){let t=this.node,[,r]=t.rootBuilder.runtimeValues(t),o=Object.fromEntries(Object.entries(r).filter(([l])=>!k2.has(l)&&!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),i={...e.kind==="subscription"?e.payload:{},...this.binding.runtime.renderer.references.resolveArguments(o)};e.kind==="subscription"&&(i._subscription_kwargs=e.payload,i._subscription_metadata=e.metadata);let a=e.change??null,s=a?a.level:e.kind==="subscription"?e.topic:e.kind;return i._node=a?a.node:null,i._triggerpars={kw:a,trigger_reason:s},i._reason=s,e.kind==="click"&&(Object.assign(i,T2(e)),e.rowContext&&Object.assign(i,e.rowContext,{event:e.event})),i}cancel(){this.#n.cancel()}#a(){this.#n.startTiming(this.#s("_timing"),()=>this.invoke({kind:"timing",change:null}))}#s(e){let t=this.node,r=t.getAttr(e);return ne(r)?Or(t,e):t.pointerType(r)?t.getRelativeData(r):r??null}#l(e,t,r,o,i){let a=[...i?["_kwargs"]:[],...cm,...dm,...Object.keys(Ps(o))];return["_onCalling","_onResult","_onError","_ask_onCancel"].includes(e)?Ut(this.binding.runtime,this.node,e,t,{...o,_kwargs:o},a):this.binding.runtime.inlineCompiler.compile(this.node,e,t,a,r)({...o,_kwargs:o})}async#u(e){let t=this.node,[r,o,i]=["_onCalling","_onResult","_onError"].map(s=>t.getAttr(s)),a=t.requests;if(a.calling(r?()=>this.#l("_onCalling",r,r,e,!0):null))return a.submit(this.#s("method"),Ps(e),s=>this.#c(s,e,o,i))}async#c(e,t,r,o){if(this.binding.closed)return;let i=this.node,a=this.#s("timeout"),s=a>0?setTimeout(()=>{let c=new Error(`${i.nodeTag} '${i.label}': no answer within ${a} ms`);c.name="TimeoutError",e.controller.abort(c)},a):null,l;try{l={result:await this.binding.call("data",e)}}catch(c){l={error:c}}if(clearTimeout(s),this.binding.closed||e.ignored)return;if("error"in l){if(!o)throw l.error;this.#l("_onError",o,o,{...t,error:l.error},!0);return}let{result:u}=l;i.getAttr("result_path")!=null&&i.setRelativeData(i.pathAttribute("result_path"),u),r&&this.#l("_onResult",r,r,{...t,result:u},!0)}#d(e){this.#f();let t=this.#i;this.#i=!1;let r=this.node,o=r.absDatapath(r.pathAttribute("destination_path"));if(o===null)return;let i=r.getAttr("_onCalling"),a=new mo({binding:this.binding,method:this.#s("method"),params:Ps(e),cacheTime:this.#s("cacheTime"),sync:this.#s("sync")!==!1&&this.binding.runtime.gramlot.rpc.supportsCallSync,onCalling:i?()=>this.#l("_onCalling",i,i,e,!0):null,onError:s=>{throw new Error(`${r.nodeTag} '${r.label}': dataRemote '${a.method}' failed: ${s.message}`,{cause:s})}});this.binding.runtime.data.setResolver(o,a),this.#o={path:o,resolver:a},t&&a.refresh()}#f(){if(!this.#o)return;let{path:e,resolver:t}=this.#o;this.#o=null,this.#i=t.loaded||t.loading!==null;let r=this.binding.runtime.data.getNode(e);r?.resolver===t&&(r.resolver=null)}#p(){for(let e of this.#t.splice(0))e.close();this.#r.clear()}},Ls=class extends go{get kind(){return"formula"}},Fs=class extends go{get kind(){return"controller"}},js=class extends go{get kind(){return"rpc"}},qs=class extends go{get kind(){return"remote"}},cm=["_node","_triggerpars","_reason","_subscription_kwargs","_subscription_metadata","_askResult"],dm=["_evt","button_counter","button_shift","button_ctrl","button_alt","button_meta"];function Ps(n){let e={...n};for(let t of[...cm,...dm])delete e[t];return e}function T2({event:n,counter:e}){return{_evt:n,button_counter:e,button_shift:!!n.shiftKey,button_ctrl:!!n.ctrlKey,button_alt:!!n.altKey,button_meta:!!n.metaKey}}var A2=[[null,/(\W|^)GET (?:\s*)(\^?[\w.#@$?-]+)/g,"$1this.GET('$2')"],[/;SET/g,/(\W|^)SET (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm,"$1this.SET('$2', $3)$4 "],[/;PUT/g,/(\W|^)PUT (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm,"$1this.PUT('$2', $3)$4 "],[/;FIRE_AFTER/g,/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g,"$1this.FIRE_AFTER('$2', $3)$4 "],[/;FIRE_AFTER/g,/(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g,"$1this.FIRE_AFTER('$2')$3 "],[/;FIRE/g,/(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g,"$1this.FIRE('$2', $3)$4 "],[/;FIRE/g,/(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g,"$1this.FIRE('$2')$3 "]],D2=/(\W|^)PUBLISH (?:\s*)(\^?[\w.#@$?-]+)/,S2=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),Us=class{#e;#t=new Map;constructor(e){this.#e=e}get runtime(){return this.#e}get size(){return[...this.#t.values()].reduce((e,t)=>e+t.size,0)}preprocess(e,t,r){let o=r.trim();if(D2.test(o))throw new Error(`${$i(e,t)}: the PUBLISH macro is excluded from Gramlot`);let i=o.replace(/\$(\d+)/g,(a,s)=>`arguments[${parseInt(s,10)-1}]`);for(let[a,s,l]of A2)a&&(i=i.replace(a,`; ${a.source.slice(1)}`)),i=i.replace(s,l);return i!==o&&console.warn(`${$i(e,t)}: legacy macros are deprecated; write this.GET(path), this.SET(path, value), this.PUT(path, value), this.FIRE(path, value), this.FIRE_AFTER(path, value) and arguments[n] in place of GET, SET, PUT, FIRE, FIRE_AFTER and $n`),i}compile(e,t,r,o,i=r){if(e.activatedCode(t)!==r)throw new Error(`${$i(e,t)}: inline code runs only as received with the Source (main or a remote Source); a text written later is not run: use named logic`);let a=this.#t.get(e);a||(a=new Map,this.#t.set(e,a),this.runtime.bindingFor(e).track(()=>this.release(e)));let s=a.get(t);s?.source!==i&&(s={source:i,text:this.preprocess(e,t,i),key:null,run:null},a.set(t,s));let l=o.filter(C2),u=l.join(",");if(s.key!==u){let c=N2(e,t,s.text,l);s.key=u,s.run=d=>c.apply(e,l.map(f=>d[f]))}return s.run}compileExpression(e,t,r){let o=r.slice(2).trim(),i=Le(e.getAttr()).filter(([,s])=>!mt(s)),a=this.compile(e,t,r,[...i.map(([s])=>s).filter(s=>s!=="_F"),"_F"],`return ${o}`);return s=>{let l={};for(let[u,c]of i)Object.hasOwn(s,u)?l[u]=s[u]:l[u]=e.pointerType(c)?e.getRelativeData(c):c;return a({...l,_F:(u,c)=>this.runtime.gramlot.format(u,c)})}}compilePointerExpression(e,t,r,o){let i=this.compile(e,t,r,["_pointerValues","_F"],`return (${o}
|
|
227
|
+
)`);return a=>i({_pointerValues:a,_F:(s,l)=>this.runtime.gramlot.format(s,l)})}release(e,t=null){if(t===null){this.#t.delete(e);return}let r=this.#t.get(e);if(r)for(let o of t){r.delete(o);for(let[i]of Le({[o]:null}))r.delete(i)}}};function C2(n){return/^[A-Za-z_$][\w$]*$/.test(n)&&!S2.has(n)}function $i(n,e){return`${n.nodeTag} '${n.label}' ${e?`'${e}'`:"node value"}`}function N2(n,e,t,r){try{return t.startsWith("function")?new Function(`return (${t}
|
|
228
228
|
)`)():new Function(...r,`${t}
|
|
229
229
|
`)}catch(o){throw o instanceof EvalError?new EvalError(`${$i(n,e)}: inline code blocked by the Content Security Policy of the page (no 'unsafe-eval'); move the code to named logic (a method of the page's class Logic) or serve the page with the permissive CSP profile, which allows 'unsafe-eval'`,{cause:o}):new SyntaxError(`${$i(n,e)}: ${o.message} in the inline code:
|
|
230
|
-
${t}`,{cause:o})}}var
|
|
230
|
+
${t}`,{cause:o})}}var Vs=class{#e;#t;#r=!1;#n=null;#o=null;constructor(e){this.#e=e,this.#t=new Bi(e)}get binding(){return this.#e}get node(){return this.binding.node}get closed(){return this.#r||this.binding.closed}close(){this.#r=!0,this.#t.cancel()}register(){this.#t.startTiming(this.#a("_timing"),()=>this.trigger())}receive(e){if(this.#a("_userChanges")&&e.level!=="node")return;let t=this.#a("_delay");t>0?this.#t.debounce(t,()=>this.trigger()):this.trigger()}trigger(){this.update().catch(e=>{this.closed||this.binding.runtime.reportError(e,"Content could not be loaded")})}async update(){if(this.closed||!this.binding.hasStamp("start"))return;let e=this.node,[,t]=e.rootBuilder.runtimeValues(e),r=t.remote,o={};for(let[l,u]of Object.entries(t))l.startsWith("remote_")&&(o[l.slice(7)]=u);let i=e.getAttr("_if");if(i&&!this.#s("_if",i,`return (${i})`,o)){let l=e.getAttr("_else");l&&this.#s("_else",l,l,o);return}let a;try{let l=L(o);if(t._cachedRemote&&this.#i(r,l))return;let u=e.getAttr("_onCalling");if(!e.requests.calling(u?()=>this.#s("_onCalling",u,u,o):null))return;a=await this.binding.runtime.gramlot.src.remoteSource(e,r,o)}catch(l){throw new Error(`${e.nodeTag} '${e.label}': remote '${r}' failed: ${l.message}`,{cause:l})}let s=e.getAttr("_onRemote");!this.closed&&a&&s&&await this.#s("_onRemote",s,s,o)}fragmentMounted(e,t){this.#n=e,this.#o=t}#i(e,t){let r=this.node.requests.inflight;return r?r.method===e&&L(r.params)===t:e===this.#n&&t===this.#o}#a(e){let[,t]=this.node.rootBuilder.runtimeValues(this.node);return t[e]??null}#s(e,t,r,o){return e==="_onRemote"?Ut(this.binding.runtime,this.node,e,t,o):this.binding.runtime.inlineCompiler.compile(this.node,e,t,Object.keys(o),r)(o)}};var bo="gramlot-page-store-remote",zs=class{constructor(e){this.binding=e,this.registration=null,this.ready=!1}register(){let{runtime:e,node:t}=this.binding;if(this.connection=e.gramlot._pageStore,!this.connection)throw new Error("dataBinder requires a PageStore WebSocket");if(this.clientPath=t.absDatapath(t.pathAttribute("destination_path")),this.serverPath=t.getAttr("server_path"),typeof this.clientPath!="string"||!this.clientPath||this.clientPath.includes("?"))throw new TypeError("dataBinder requires a nonempty client Data path");if(typeof this.serverPath!="string"||!/^[^.?#\[\]!:]+(?:\.[^.?#\[\]!:]+)*$/.test(this.serverPath))throw new TypeError("dataBinder requires a literal server path");this.id=J(),this.ready=!1,this.registration=e.router.register({path:this.clientPath,recipient:this,subtree:!0});try{this.connection.register(this)}catch(r){throw this.registration.close(),this.registration=null,r}}receive(e){if(!this.ready||e.reason===bo)return;if(e.fired)throw new Error("Fired events are outside the first PageStore PoC");let{data:t}=this.binding.runtime,r=e.level==="container",o=r?t.getNode(this.clientPath):e.node;this.connection.send({op:"change",binderId:this.id,path:r||e.path===this.clientPath?"":e.path.slice(this.clientPath.length+1),evt:r?o?"upd_value":"del":e.evt,value:o?.value??null,attr:{...o?.attr},index:e.index,fired:!1})}apply(e){if(!this.registration?.active)return;let{data:t}=this.binding.runtime,r=e.path?this.clientPath+"."+e.path:this.clientPath;if(this.ready=!0,e.op==="snapshot")e.exists?t.setItem(this.clientPath,e.value,e.attr,">",!1,!1,bo):t.popNode(this.clientPath,bo);else if(e.op==="change")e.evt==="del"?t.popNode(r,bo):e.evt==="upd_attrs"?t.getNode(r).setAttr(e.attr,bo,!1,!1):t.setItem(r,e.value,e.attr,e.index??">",!1,!1,bo);else throw new Error("Unknown PageStore delivery")}unregister(){this.ready=!1,this.registration?.close(),this.registration=null,this.connection?.unregister(this)}};var I2=new Set(["title","msg","fields","_if","askIf"]),O2=new Set(["name","lbl","tag","type","default_value","required","min","max","step","placeholder"]),Hs=class{#e;#t=null;#r=new Map;constructor(e){this.#e=e}get runtime(){return this.#e}required(e,t,r,o){let i=(a,s)=>typeof s=="boolean"?s:e.runtime.inlineCompiler.compile(e.node,a,s,Object.keys(r),`return (${s});`)(r);if(typeof t=="string"){let a=e.node.getAttr("_ask_if");return!a||!!i("_ask_if",a)}return t?.askIf&&i(`${o}.askIf`,t.askIf),!t?._if||!!i(`${o}._if`,t._if)}show(e,t,r,o="Parameters"){let i=typeof t=="string"?{msg:t,title:o}:t;if(!i||typeof i!="object"||Array.isArray(i))throw new TypeError("ask requires text or a parameter description");for(let d of Object.keys(i))if(!I2.has(d))throw new Error(`Unsupported ask option: ${d}`);let a=i.fields??[];if(!Array.isArray(a))throw new TypeError("ask fields must be an array");let s=new Set;for(let d of a){if(!d||!/^[A-Za-z_]\w*$/.test(d.name)||s.has(d.name))throw new Error("ask fields require distinct simple names");s.add(d.name);for(let f of Object.keys(d))if(!O2.has(f))throw new Error(`Unsupported ask field option: ${f}`);if(d.tag&&!["input","textarea"].includes(d.tag))throw new Error(`Unsupported ask widget: ${d.tag}`);if(d.type&&!["text","number","date","checkbox","email","password","url","tel"].includes(d.type))throw new Error(`Unsupported ask input type: ${d.type}`)}let l=this.runtime.gramlot,u=this.#n(),c=this.#r;return new Promise((d,f)=>{let h=`ask_${J()}`,p=!1,m=()=>{},b=(w,_=null)=>{if(p)return;p=!0;let y=w?Object.fromEntries(a.map(x=>[x.name,l.data.getItem(`${h}.${x.name}`)])):null;c.delete(h),m();try{l.src.source.popNode(h),l.data.getNode(h)&&l.data.popNode(h),_?f(_):d(y)}catch(x){f(x)}};c.set(h,{finish:b}),m=e.track(()=>b(!1));try{let w=new Oe,_=w.root.html_dialog({nodeId:h,datapath:h,request:h,connect_oncancel:`${u}.cancel`,connect_onclose:`${u}.cancel`,class:"gramlot-ask","aria-labelledby":`${h}_title`,style:"border:1px solid #aab4c2;border-radius:8px;padding:16px;max-width:32rem;width:calc(100% - 48px);font:inherit;"});_.h2(i.title??o,{id:`${h}_title`,style:"font-size:1.1em;margin:0 0 12px;"}),i.msg&&_.p(i.msg);let y=_.form({request:h,connect_onsubmit:`${u}.confirm`});for(let k of a){y.dataSetter({destination_path:`.${k.name}`,value:Object.hasOwn(r,k.name)?r[k.name]:k.default_value??(k.type==="checkbox"?!1:"")});let C=y.div({style:"margin:8px 0;"});C.html_label(k.lbl??k.name,{for:`${h}_${k.name}`,style:"display:block;margin-bottom:4px;"});let O={id:`${h}_${k.name}`,value:`^.${k.name}`,live:!0};for(let $ of["required","min","max","step","placeholder"])k[$]!==void 0&&(O[$]=k[$]);k.tag==="textarea"?C.textarea(O):C.input({...O,type:k.type??"text"})}let x=y.div({style:"display:flex;justify-content:flex-end;gap:8px;margin-top:16px;"});x.html_button("Cancel",{type:"button",request:h,connect_onclick:`${u}.cancel`}),x.html_button("Confirm",{type:"submit",autofocus:a.length===0}),l.src.source.setItem(h,l.src.prepareSource(w.source));let D=l.src.binding.nodeIds.get(h);l.dom.getDomNode(D).showModal()}catch(w){b(!1,w)}})}#n(){if(this.#t===null){let e=`ask_${J()}`,t=this.#r;class r{confirm(i,a){a.preventDefault(),t.get(i.getAttr("request"))?.finish(!0)}cancel(i,a){a.preventDefault(),t.get(i.getAttr("request"))?.finish(!1)}}this.runtime.logicRegistry.register(r,{group:e,resource:"gramlot:ask"}),this.#t=e}return this.#t}};var Gs=class{#e;#t=`errors_${J()}`;#r=null;#n=new Map;#o=new Set;#i=0;constructor(e){this.#e=e}show(e,t){let r=new Set,o=[];for(let a=e;a!==null&&typeof a=="object"&&!r.has(a);a=a.cause){if(a.name==="AbortError")return;r.add(a),o.push(a.stack??a.message)}let i=typeof e?.message=="string"?e.message:String(e);queueMicrotask(()=>{this.#e.disposed||this.#a(i,t,o.join(`
|
|
231
231
|
Caused by:
|
|
232
|
-
`))})}#a(e,t,r){let o=this.#e.gramlot,i=JSON.stringify([t,e]);if(this.#o.has(i))return;let a=this.#e.nodeIds.get(this.#t);if(!a){if(this.#n.clear(),this.#i=0,this.#r===null){let p=this;class m{close(w){p.#s(w.getAttr("notice"))}}this.#r=`errors_${K()}`,this.#e.logicRegistry.register(m,{group:this.#r,resource:"gramlot:error-notifications"})}let h=new Oe;h.root.aside({nodeId:this.#t,class:"gramlot-error-notifications",popover:"manual","aria-label":"Error notifications",style:"position:fixed;inset:auto max(12px,env(safe-area-inset-right)) max(12px,env(safe-area-inset-bottom)) auto;margin:0;width:360px;max-width:calc(100vw - 24px);max-height:50vh;overflow:auto;box-sizing:border-box;padding:0;border:1px solid var(--gramlot-border-control,#aab4c2);border-radius:8px;background:var(--gramlot-surface,#fff);color:var(--gramlot-ink,#222);font:13px/1.4 system-ui;box-shadow:0 6px 24px #0003;"}),o.src.source.setItem(this.#t,o.src.prepareSource(h.source)),a=this.#e.nodeIds.get(this.#t)}if(this.#n.has(i))return;if(this.#n.size===5){let h=`${++this.#i} additional errors`,p=a.value.getNode("overflow");p?p.setValue(h):o.src.builder.wrapSource(a).p(h,{node_label:"overflow",role:"status",style:"margin:0;padding:12px;"});return}let s=`notice_${K()}`,l=new Oe,u=l.root.article({role:"alert",style:"color:inherit;padding:12px;border-bottom:1px solid var(--gramlot-border,#ddd);"}),c=u.div({style:"display:flex;align-items:start;gap:12px;"});c.strong(`==${JSON.stringify(t)}`,{style:"flex:1;color:var(--gramlot-error,#b13d48);"}),c.html_button("\xD7",{type:"button",notice:s,connect_onclick:`${this.#r}.close`,"aria-label":"Dismiss notification",title:"Dismiss notification",style:"border:0;background:transparent;color:inherit;font:18px/1 system-ui;width:24px;height:24px;flex:0 0 24px;padding:0;cursor:pointer;"}),u.p(`==${JSON.stringify(e)}`,{style:"margin:6px 0;overflow-wrap:anywhere;"});let d=u.details({style:"border:0;padding:0;margin:8px 0 0;background:transparent;"});d.summary("Details",{style:"cursor:pointer;"}),d.pre(`==${JSON.stringify(r)}`,{style:"font:11px/1.4 monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:6px 0 0;padding:8px;border:0;border-radius:4px;background:var(--gramlot-surface-subtle,#f2f4f6);"});let f=o.src.builder.wrapSource(a).div({node_label:s});ie(f).setValue(o.src.prepareSource(l.source)),this.#n.set(i,s),o.dom.getDomNode(a).showPopover()}#s(e){this.#e.nodeIds.get(this.#t).value.popNode(e);for(let[r,o]of this.#n)o===e&&(this.#n.delete(r),this.#o.add(r));this.#n.size||this.#e.gramlot.src.source.popNode(this.#t)}};var sm={dataFormula:Ms,dataController:Ps,dataRpc:Ls,dataRemote:Fs},_2=["datapath","_anchor","nodeId","form","formId"],wo=class{#e;#t=new Map;#r=new Map;#n;#o;#i;#a;#s;#l;#u=`gramlot-data-${K()}`;#c=!1;#d=new Set;#f=new Set;#p=new WeakMap;constructor(e,{subscriptions:t}){this.#e=e,this.#l=t,this.#n=new Os(this),this.#o=new Bs(this),this.#i=new js(this),this.#a=new Vs(this),this.#s=new zs(this)}get gramlot(){return this.#e}reportError(e,t){this.disposed||this.#s.show(e,t)}get subscriptions(){return this.#l}get builder(){return this.gramlot.src.builder}get renderer(){return this.gramlot.src.renderer}get logicRegistry(){return this.gramlot.src.logicRegistry}get data(){return this.builder.data}treeStore(e){if(e.treeStore!==null)return e.treeStore;let t=e.getAttr("storepath");if(t==="*S"||t.startsWith("*S.")){let r=this.renderer.source.getItem("main");return t==="*S"?r:r.getItem(t.slice(3))}return t==="*D"||t.startsWith("*D.")?t==="*D"?this.data:this.data.getItem(t.slice(3)):e.getRelativeData(t)}registerTreeRoot(e,t){let r=t?this.#d:this.#f;return r.add(e),{close:()=>r.delete(e)}}refreshSourceTrees(){for(let e of[...this.#d])!e.closed&&this.renderer.attached(e.node)&&this.renderer.project(e.node)}get root(){return this.data.parent}get size(){return this.#t.size}get disposed(){return this.#c}get router(){return this.#n}get installer(){return this.#o}get inlineCompiler(){return this.#i}get askDialog(){return this.#a}get nodeIds(){return this.#r}collectionStore(e,t){if(this.disposed)throw new Error("BindingRuntime is disposed");let r=this.#p.get(e);if(!r)r=new Ss(e,t),this.#p.set(e,r);else if(r.rowMode!==t)throw new TypeError("A shared collection store requires one rowMode");return r}collectionView(e,t,r){let o=this.collectionStore(t,r);return Object.hasOwn(e,"gridCollectionView")?e.gridCollectionView.bindStore(o):Object.defineProperty(e,"gridCollectionView",{value:new Ns(o),configurable:!0}),e.gridCollectionView}attach(){this.root.subscribe(this.#u,{any:e=>this.receiveData(e)})}receiveData(e){let t=this.root;for(let[r,o]of(e.pathlist??[]).entries()){let i=t.node(o)?.staticValue;if(!(i instanceof E))break;this.#p.get(i)?.receiveData(e,r+1<e.pathlist.length?i.node(e.pathlist[r+1]):null),t=i}this.router.deliver(e);for(let r of[...this.#f])!r.closed&&this.renderer.attached(r.node)&&this.renderer.project(r.node)}bindingFor(e){return this.#t.get(e)??null}openBinding(e){if(this.disposed)throw new Error("BindingRuntime is disposed");let t=this.bindingFor(e);return t||(t=new gc(this,e),this.#t.set(e,t)),t}closeBranch(e){let t=[];if(e.value instanceof I)for(let o of e.value.getNodes())try{this.closeBranch(o)}catch(i){t.push(i)}let r=this.bindingFor(e);if(r){this.#t.delete(e);let o=e.getAttr("nodeId");this.nodeIds.get(o)===e&&this.nodeIds.delete(o);try{r.close()}catch(i){t.push(i)}}if(t.length)throw new AggregateError(t,"Source branch close failed")}rebindBranch(e){let t=this.#_(e);for(let r of t)this.bindingFor(r)?.rebind();for(let r of t)this.renderer.project(r);for(let r of t)this.bindingFor(r)?.remote?.trigger()}handleSourceEvent(e){let{evt:t,node:r}=e,o=[],i=a=>{try{this.closeBranch(a)}catch(s){o.push(s)}};try{if(t==="ins")this.#h(r);else if(t==="del")for(let a of Array.isArray(r)?r:[r])i(a);else if(t==="upd_value"||t==="upd_value_attr"){if(e.oldvalue instanceof I)for(let a of e.oldvalue.getNodes())i(a);this.inlineCompiler.release(r,[""]),t==="upd_value_attr"?this.#b(r,e.attrs_diff):this.#w(r).rebind(),r.value instanceof I&&this.#h(r.value)}else if(t==="upd_attrs")this.#b(r,e.attrs_diff);else throw new Error(`Unsupported Source event: ${t}`)}catch(a){throw o.length?new AggregateError([...o,a],"Source event failed"):a}return o}branchBuilt(e){let t=[];for(let r of this.#_(e)){let o=this.bindingFor(r);!o||o.hasStamp("built")||!this.renderer.attached(r)||(o.stamp("built"),t.push(o))}for(let r of t)this.renderer.attached(r.node)&&this.#g(r,"built","_onBuilt");if(this.gramlot.state==="started")for(let r of t)this.renderer.attached(r.node)&&this.#m(r)}pageStarted(){for(let e of[...this.#t.values()])!e.closed&&e.hasStamp("built")&&this.#m(e)}dispose(){if(this.disposed)return;this.#c=!0,this.root.unsubscribe(this.#u,{any:!0}),this.nodeIds.clear(),this.#p=new WeakMap;let e=[];for(let[t,r]of[...this.#t.entries()].reverse()){this.#t.delete(t);try{r.close()}catch(o){e.push(o)}}if(e.length)throw new AggregateError(e,"Binding cleanup failed")}#h(e){if(!(e instanceof I)&&this.bindingFor(e))return;let t=e instanceof I?e.getNodes().flatMap(i=>this.#_(i)):this.#_(e),r=new Set(t.filter(i=>this.bindingFor(i))),o=new Map;for(let i of t){let a=i.getAttr("nodeId");if(a!=null){if(o.has(a)||this.nodeIds.has(a)&&this.nodeIds.get(a)!==i)throw new Error(`Duplicate nodeId '${a}'`);o.set(a,i)}}for(let[i,a]of o)this.nodeIds.set(i,a);try{for(let i of t)this.openBinding(i);this.installer.install(e);for(let i of t)this.renderer.attached(i)&&this.bindingFor(i).registerPointers()}catch(i){let a=[i];for(let s of t.filter(l=>!r.has(l)).reverse()){let l=s.getAttr("nodeId");o.get(l)===s&&this.nodeIds.get(l)===s&&this.nodeIds.delete(l);let u=this.bindingFor(s);if(u){this.#t.delete(s);try{u.close()}catch(c){a.push(c)}}}throw a.length>1?new AggregateError(a,"Source branch installation failed"):i}for(let i of t){let a=this.bindingFor(i);if(!(!a||a.hasStamp("init")||!this.renderer.attached(i))&&(a.stamp("init"),lm(i.getAttr("_init"))))for(let s of a.providers)s.invoke({kind:"init",change:null})}}#m(e){e.hasStamp("start")||(e.stamp("start"),this.#g(e,"start","_onStart"),e.remote?.trigger())}#g(e,t,r){let o=e.node.getAttr(r);if(lm(o))for(let i of e.providers){if(typeof o!="number"||o<=0){i.invoke({kind:t,change:null});continue}let a=null,s=setTimeout(()=>{a(),i.invoke({kind:t,change:null})},o);a=e.track(()=>clearTimeout(s))}}#b(e,t){let r=this.#w(e);if(this.inlineCompiler.release(e,Object.keys(t)),Object.hasOwn(t,"nodeId")){let{old:o,new:i}=t.nodeId;if(i!=null&&this.nodeIds.has(i)&&this.nodeIds.get(i)!==e)throw new Error(`Duplicate nodeId '${i}'`);this.nodeIds.get(o)===e&&this.nodeIds.delete(o),i!=null&&this.nodeIds.set(i,e)}_2.some(o=>Object.hasOwn(t,o))?this.rebindBranch(e):r.rebind()}#w(e){let t=this.bindingFor(e);if(!t)throw new Error(`${e.nodeTag??"fragment"} '${e.label}': the node has no NodeBinding (its installation failed); remove it from the Source and insert it again`);return t}#_(e){let t=[e];if(e.value instanceof I)for(let r of e.value.getNodes())t.push(...this.#_(r));return t}};function lm(n){return n===!0||typeof n=="number"}var gc=class{#e;#t;#r=!1;#n=[];#o=[];#i=new Set;#a=null;#s=null;#l=null;#u=new Set;#c=new Set;#d=0;#f=new Set;#p=null;editingSession=null;constructor(e,t){this.#e=e,this.#t=t}get runtime(){return this.#e}get node(){return this.#t}get closed(){return this.#r}get registrations(){return[...this.#o]}get providers(){return this.#a?[this.#a]:[]}get remote(){return this.#l}get clickCount(){return this.#d}countClick(){return++this.#d}hasStamp(e){return this.#i.has(e)}stamp(e){this.#i.add(e)}registerPointers(){this.node._getMeta("data_element")&&(this.runtime.renderer.references.remove(this.node),this.runtime.renderer.references.register(this.node,null));let e=this.node,t=e._getMeta("data_element");if(t&&!sm[e.nodeTag]&&e.nodeTag!=="dataBinder")return;!t&&typeof e.getAttr("remote")=="string"?this.#l??=new qs(this):this.#l&&(this.#l.close(),this.#l=null);let r=new Set,o=e._getMeta("gramlot_component");for(let[a,s]of[["bagStore","storepath"],["bagStruct","structpath"]]){if(!o?.[a])continue;if(a==="bagStore"&&e.nodeTag==="tree"&&e.treeStore!==null){let d=e.treeStore,f=`gramlot-tree-${K()}`;d.subscribe(f,{any:()=>{!this.closed&&this.runtime.renderer.attached(e)&&this.runtime.renderer.project(e)}}),this.#o.push({close:()=>d.unsubscribe(f,{any:!0})});continue}let l=e.getAttr(s);if(typeof l!="string"||!l||/^[\^=]/.test(l)||l.includes("?"))throw new TypeError(`${s} requires a plain Bag data path`);if(a==="bagStore"&&e.nodeTag==="tree"&&(l==="*S"||l.startsWith("*S."))){this.#o.push(this.runtime.registerTreeRoot(this,!0));continue}if(a==="bagStore"&&e.nodeTag==="tree"&&l==="*D"){this.#o.push(this.runtime.registerTreeRoot(this,!1));continue}let u=a==="bagStore"&&e.nodeTag==="tree"&&l.startsWith("*D.")?l.slice(3):e.absDatapath(l),c=this.runtime.router.register({path:u,recipient:this,subtree:!0});this.#o.push(c),a==="bagStore"&&o.bagStruct&&(this.#p=c)}let i=this.remote?Ft(e,e.getAttr("_timing")):new Set;if(this.remote){for(let[a,s]of Object.entries(e.getAttr()))if(a.startsWith("remote_"))for(let l of Ft(e,s))r.add(l)}for(let[a,s]of e.pointers()){if(t&&a!=="datapath")continue;let u=(a==="datapath"?e.parentNode:e).absDatapath(s);if(u===null)continue;let[c,d=null]=u.split("?",2),f=this.runtime.router.register({path:c,attr:d,recipient:this});this.#o.push(f),a==="datapath"&&this.#f.add(f),this.remote&&(a==="remote"||a.startsWith("remote_")||r.has(a))&&this.#u.add(f),this.remote&&(a==="_timing"||i.has(a))&&this.#c.add(f)}if(!t){this.#h(),this.remote?.register();return}if(e.nodeTag==="dataBinder"){this.#s??=new Us(this),this.#s.register();return}this.#a??=new sm[e.nodeTag](this),this.#a.register()}#h(){let e=this.node;this.#o.push(...this.runtime.subscriptions.subscribeNode(e,(t,r)=>{if(typeof r!="string"||!r)throw new TypeError(`${t} requires a handler`);return o=>{if(this.closed)return;if(xi(r))return Qt(this.runtime,e,r,o);let[,i]=e.rootBuilder.runtimeValues(e),a=Object.fromEntries(Object.entries(i).filter(([l])=>!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),s={...this.runtime.renderer.references.resolveArguments(a),p_0:o};return this.runtime.inlineCompiler.compile(e,t,r,Object.keys(s))(s)}}))}rebind(){this.#m(),this.registerPointers(),this.editingSession?.refreshField(this.node)}receive(e){if(!(e.registration===this.#p&&(e.level==="child"||e.evt==="upd_attrs"))){if(this.#f.has(e.registration)){this.runtime.rebindBranch(this.node);return}this.#u.has(e.registration)&&this.remote.receive(e),this.#c.has(e.registration)&&this.remote.register(),this.editingSession?.refreshField(this.node),this.runtime.renderer.project(this.node,e)}}track(e){if(this.closed)throw new Error(`NodeBinding of '${this.node.label}' is closed`);return this.#n.push(e),()=>{let t=this.#n.indexOf(e);t!==-1&&this.#n.splice(t,1)}}async call(e,t){let{controller:r}=t,o=this.track(()=>r.abort());try{let i=await this.runtime.gramlot.rpc.call(e,t.method,t.params,{signal:r.signal});if(r.signal.aborted)throw r.signal.reason;return i}finally{o()}}callSync(e,t,r){return this.node.requests.submitSync(t,()=>this.runtime.gramlot.rpc.callSync(e,t,r))}close(){if(this.closed)return;this.#r=!0,this.#l?.close(),this.node._getMeta("data_element")&&this.runtime.renderer.references.remove(this.node),this.#m();let e=[];for(let t of this.#n.splice(0).reverse())try{t()}catch(r){e.push(r)}if(e.length)throw new AggregateError(e,`NodeBinding of '${this.node.label}' cleanup failed`)}#m(){this.#s?.unregister();for(let e of this.#o.splice(0))e.close();this.#p=null,this.#f.clear(),this.#u.clear(),this.#c.clear()}};var Hs=class{constructor(e){this.renderer=e}prepare(e,t){let r=this.renderer.records.get(e);if(!r||r.resolved.draggable!==!0)return null;let o=e._getMeta("gramlot_component")?.dragSource?r.element.getDragContext(t):{dragValues:{},item:void 0,path:void 0};if(o===null)return null;let{dragValues:i,item:a,path:s}=o;if(r.resolved.onDrag){let u=this.renderer.html.callLogic(e,r.resolved.onDrag,{dragValues:i,item:a,path:s});if(u&&typeof u.then=="function")throw new TypeError("onDrag must run synchronously");if(u===!1)return null}return Tt(i),{dragValues:Object.fromEntries(Object.entries(i).map(([u,c])=>{if(u.startsWith("text/")||u==="dragTags"){if(typeof c!="string")throw new TypeError(`${u} drag data must be text`);return[u,c]}return[u,F(L(c))]})),item:a,path:s}}};var Or=class{static isTarget(e){return e.dropTarget===!0||!!e.dropTargetCb||Object.entries(e).some(([t,r])=>t.startsWith("dropTargetCb_")&&!!r)}static acceptedTypes(e,t="",r=[]){let o=t.split(",").map(i=>i.trim()).filter(Boolean).map(i=>{let a=i.split("*").map(s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return new RegExp(`^${a.join(".*")}$`)});return e.filter(i=>i!=="dragTags"&&(r.includes(i)||o.some(a=>a.test(i))))}static acceptsTags(e="",t=""){if(!t.trim())return!0;let r=new Set(e.split(",").map(o=>o.trim()).filter(Boolean));return r.size?t.split(",").some(o=>o.split(" AND ").every(i=>(i=i.trim(),!i||i==="!"?!1:i.startsWith("!")?!r.has(i.slice(1)):r.has(i)))):!1}static acceptsEffect(e="all",t="move"){let r={all:["copy","move","link"],none:[],copy:["copy"],move:["move"],link:["link"],copyMove:["copy","move"],copyLink:["copy","link"],linkMove:["link","move"]};if(!Object.hasOwn(r,e))throw new TypeError(`Invalid effectAllowed: ${e}`);if(!["copy","move","link"].includes(t))throw new TypeError(`Invalid dropEffect: ${t}`);return r[e].includes(t)}static evaluate(e,t,r,o,i=[]){let a=this.acceptedTypes(e,o.dropTypes,i),s=o.dropEffect??"move",l=this.isTarget(o)&&a.length>0&&this.acceptsTags(t,o.dropTags)&&this.acceptsEffect(r,s);return{accepted:l,types:a,dropEffect:l?s:"none"}}};var um=["dragstart","dragover","dragleave","drop","dragend"],Gs=class{#e;#t;#r=null;#n=null;#o=null;#i;constructor(e){this.#e=e,this.#t=e.destination.ownerDocument;for(let t of um)this.#t.addEventListener(t,this);this.#i=()=>this.#b("none"),this.#t.defaultView.addEventListener("pagehide",this.#i)}handleEvent(e){e.type==="dragstart"?this.#l(e):e.type==="dragend"?this.#b(e.dataTransfer.dropEffect):e.type==="dragleave"?this.#h():e.type==="dragover"?this.#d(e):e.type==="drop"&&this.#f(e)}#a(e,t){for(let r of e.composedPath()){let o=this.#e.elements.get(r);if(o&&t(o.resolved))return o}return null}#s(e,t){return e.node._getMeta("gramlot_component")?.dragSource?e.element.getDragContext(t):{element:e.element,item:void 0,path:void 0}}#l(e){let t=this.#a(e,r=>r.draggable===!0);if(t){this.#b("none");try{let r=this.#e.prepareDrag(t.node,e);if(!r||!t.element.isConnected||this.#e.records.get(t.node)!==t){e.preventDefault();return}let o=this.#s(t,e);if(!o){e.preventDefault();return}let i=new Map(Object.entries(r.dragValues).filter(([u])=>u!=="dragTags").map(([u,c])=>[u,u.startsWith("text/")?c:L(c)]));if(!i.size){e.preventDefault();return}let a=t.resolved.effectAllowed??"all";Or.acceptsEffect(a,"move");let s="";for(let u=t;u;u=u.parent)if(u.resolved?.dragTags!=null){s=u.resolved.dragTags;break}let l=this.#r={record:t,wires:i,effectAllowed:a,phase:"active",tags:[s,r.dragValues.dragTags].filter(Boolean).join(","),endTopic:this.#e.binding.subscriptions.topicFor(t.node,"endDrag"),source:{pageId:this.#e.binding.gramlot.pageId??null,sourcePath:t.node.fullpath,itemPath:r.path??null},preview:null,release:null};e.dataTransfer.clearData();for(let[u,c]of i)e.dataTransfer.setData(u,c);e.dataTransfer.effectAllowed=a,this.#o=this.#t.createElement("style"),this.#o.textContent=".canBeDropped{outline:2px solid var(--gramlot-brand-blue,#3766b5);outline-offset:-2px}.cannotBeDropped{outline:2px dashed currentColor;outline-offset:-2px}.draggedItem{opacity:.75}",this.#t.head.append(this.#o),this.#u(l,o.element,e.dataTransfer),l.release=this.#e.onDispose(t.node,()=>this.#b("none"))}catch(r){e.preventDefault(),this.#g(),this.#w(r)}}}#u(e,t,r){let o=t.cloneNode(!0);o.removeAttribute("id");for(let i of o.querySelectorAll("[id]"))i.removeAttribute("id");o.setAttribute("aria-hidden","true"),o.classList.add(...(e.record.resolved.dragClass??"draggedItem").split(/\s+/).filter(Boolean)),Object.assign(o.style,{position:"fixed",left:"-10000px",top:"0",width:`${t.getBoundingClientRect().width}px`,pointerEvents:"none"}),t.parentNode.append(o),e.preview=o,r.setDragImage(o,0,0)}#c(e){let t=this.#r,r=this.#a(e,u=>Or.isTarget(u));if(!r)return null;let o=this.#s(r,e);if(!o)return{record:r,element:r.element,accepted:!1};let i=Or.evaluate([...t.wires.keys()],t.tags,t.effectAllowed,r.resolved),s={dropValues:Object.fromEntries(i.types.map(u=>[u,u.startsWith("text/")?t.wires.get(u):F(t.wires.get(u))])),item:o.item,path:o.path,source:{...t.source},selfdrop:r===t.record,dropEffect:i.dropEffect,dataAvailable:!0};o.placement!==void 0&&(s.placement=o.placement);let l=i.accepted&&this.#e.checkDropTarget(r.node,s)&&this.#e.records.get(r.node)===r&&o.element.isConnected;return{record:r,element:o.element,accepted:l,context:s}}#d(e){if(!this.#r){this.#a(e,t=>Or.isTarget(t))&&(e.preventDefault(),e.dataTransfer.dropEffect="none");return}if(e.preventDefault(),this.#r.phase!=="active"){e.dataTransfer.dropEffect="none";return}try{let t=this.#r,r=this.#c(e);if(this.#r!==t){e.dataTransfer.dropEffect="none";return}e.dataTransfer.dropEffect=r?.accepted?r.context.dropEffect:"none",this.#h(),r&&this.#p(r.element,r.accepted)}catch(t){e.dataTransfer.dropEffect="none",this.#r&&(this.#r.phase="rejected"),this.#m(),this.#w(t)}}async#f(e){if(!this.#r){this.#a(e,o=>Or.isTarget(o))&&e.preventDefault();return}if(e.preventDefault(),this.#r.phase!=="active")return;let t=this.#r,r;try{if(r=this.#c(e),this.#r!==t){e.dataTransfer.dropEffect="none";return}if(t.phase="dropped",this.#m(),!r?.accepted){e.dataTransfer.dropEffect="none";return}e.dataTransfer.dropEffect=r.context.dropEffect,r.record.node.publish("onDrop",r.context),await this.#e.invokeDrop(r.record.node,r.context)}catch(o){this.#r===t&&(t.phase="rejected",this.#m()),(!r||this.#e.records.has(r.record.node))&&this.#w(o)}}#p(e,t){let r=t?"canBeDropped":"cannotBeDropped",o=(e.getAttribute("part")??"").split(/\s+/).filter(Boolean);this.#n={element:e,name:r,hadClass:e.classList.contains(r),hadPart:o.includes(r)},e.classList.add(r),o.includes(r)||e.setAttribute("part",[...o,r].join(" "))}#h(){if(!this.#n)return;let{element:e,name:t,hadClass:r,hadPart:o}=this.#n;r||e.classList.remove(t),o||e.setAttribute("part",(e.getAttribute("part")??"").split(/\s+/).filter(i=>i!==t).join(" ")),this.#n=null}#m(){this.#h(),this.#r&&(this.#r.preview?.remove(),this.#r.preview=null,this.#r.wires.clear())}#g(){let e=this.#r;return this.#m(),this.#r=null,e?.release?.(),this.#o?.remove(),this.#o=null,e}#b(e){let t=this.#g();!t||this.#e.disposed||this.#e.endDrag(t.record.node,{source:{...t.source},dropEffect:e},t.endTopic).catch(r=>this.#w(r))}#w(e){this.#e.binding.reportError(e,"Drag and drop failed")}dispose(){this.#g();for(let e of um)this.#t.removeEventListener(e,this);this.#t.defaultView.removeEventListener("pagehide",this.#i)}};var Mi=class extends un{static renderType="object";#e=new Set;#t=new WeakSet;#r=new WeakMap;#n=new WeakMap;#o=new WeakMap;constructor(e,t,r,{binding:o}={}){if(super(e),!(e instanceof Ze)||!(t instanceof Ae)||r?.nodeType!==1)throw new TypeError("GramlotRenderer requires a BuilderBase, GramlotBuilderBag and HTML destination");if(!(o instanceof wo))throw new TypeError("GramlotRenderer requires a BindingRuntime");if(!(t._builder instanceof Ze))throw new TypeError("SourceBag requires builder ownership");this._binding=o,this.source=t,this.destination=r,this.html=new ys({uploadContext:()=>({gramlot:o.gramlot,window:r.ownerDocument.defaultView}),metadataAttributes:["__ref"],format:(i,a)=>o.gramlot.format(i,a),reportError:(i,a,s)=>{this.records.has(i)&&o.reportError(a,s)},callLogic:(i,a,s)=>{let{group:l,method:u}=o.gramlot.src.logicRegistry.resolve(a,i);return u.call(l,i,s)},invokeScript:(i,a,s,l)=>Ut(o,i,a,s,l,i.parentNode._getMeta("gramlot_component").childParameters[a].inline)}),this.records=new Map,this.references=new bi(t),this.pending=[],this.building=!1,this.disposed=!1,this.elements=new WeakMap,this.dragPreparation=new Hs(this),this.instanceId=K(),this.radioGroups=new _s(this),this.dragDrop=new Gs(this),this.subscription=`html-source-renderer-${this.instanceId}`,t.subscribe(this.subscription,{any:i=>this.receive(i)})}get binding(){return this._binding}prepareDrag(e,t){return this.dragPreparation.prepare(e,t)}checkDropTarget(e,{dropValues:t,item:r,path:o,source:i,selfdrop:a,dropEffect:s,dataAvailable:l,placement:u}){let c=this.records.get(e);if(!c)return!1;if(!c.resolved.dropTargetCb)return!0;let d=this.html.callLogic(e,c.resolved.dropTargetCb,{dropValues:t,item:r,path:o,source:i,selfdrop:a,dropEffect:s,dataAvailable:l,...u===void 0?{}:{placement:u}});if(typeof d!="boolean")throw new TypeError("dropTargetCb must return a boolean synchronously");return d}async invokeDrop(e,{dropValues:t,item:r,path:o,source:i,selfdrop:a,dropEffect:s,dataAvailable:l,placement:u}){let c=this.records.get(e);!c||!c.resolved.onDrop||Object.keys(t).length===0||await this.html.callLogic(e,c.resolved.onDrop,{dropValues:t,item:r,path:o,source:i,selfdrop:a,dropEffect:s,dataAvailable:l,...u===void 0?{}:{placement:u}})}async endDrag(e,{source:t,dropEffect:r},o){let i={source:t,dropEffect:r},a=[],s=this.records.get(e);try{s&&!s.binding.closed&&s.resolved.onDragEnd&&await this.html.callLogic(e,s.resolved.onDragEnd,i)}catch(l){a.push(l)}try{this.binding.gramlot.publish(o,i)}catch(l){a.push(l)}if(a.length)throw new AggregateError(a,"Drag completion notification failed")}get inlineCompiler(){return this.binding.inlineCompiler}evaluateExpressions(e,t){let r=this.#n.get(e)??super.evaluateExpressions(e,t),o=e._getMeta("gramlot_component");if(o?.presentationDefaults.length){let i=e.getAttr();this.#o.set(e,Object.fromEntries(Object.entries(r).filter(([a])=>Object.hasOwn(i,a)&&o.presentationDefaults.some(s=>a.startsWith(s)))))}if(this.html.hasLabelbox(e)||o?.presentationDefaults.length){let i=[];for(let a=e.parentNode;a;a=a.parentNode)this.#o.has(a)&&i.unshift(this.#o.get(a));r=Object.assign({},...i,r)}return this.#n.delete(e),this.#r.set(e,r),r}render(e,t={}){if(!(e instanceof ln))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(e._getMeta("data_element")||this.#t.has(e)||!this.binding.bindingFor(e)&&this.#l(e))return null;if(e.nodeTag)this.html.validate(e,e._getMeta("subbuilder")?e.parentBag._builder:e.builder);else if(!(e.value instanceof I))throw new TypeError("Source fragments must contain child SourceBags");return e.nodeTag?super.render(e,t):this.renderFragment(e,t)}renderFragment(e,{document:t=this.destination.ownerDocument,...r}={}){let o=t.createDocumentFragment(),i={node:e,binding:this.#m(e),container:null,parent:null,children:new Set,cleanup:[],start:t.createComment("source-fragment"),end:t.createComment("/source-fragment")};this.records.set(e,i),this.elements.set(o,i),o.append(i.start);for(let a of e.value.getNodes()){let s=this.render(a,{document:t,...r});if(s===null)continue;o.append(s);let l=this.elements.get(s);l&&(l.parent=i,i.children.add(a))}return o.append(i.end),o}renderedItem(e,t,r,{tag:o,document:i=this.destination.ownerDocument}={}){let a=r;t=this.expressionValue(e,t),this.getRender(e.builder)===this&&(a=this.restoreNativeAttributes(e,r),e._getMeta("gramlot_component")||([t,a]=vi(t,a,(h,p)=>this._binding.gramlot.format(h,p)))),a=this.componentAttributes(e,a);let s=Array.isArray(t)?t:[],l=Array.isArray(t)?a._text:t,u=this.#r.get(e),c={node:e,binding:this.#m(e),container:null,parent:null,children:new Set,cleanup:[],resolved:u,...this.html.create(e,i,o,a,u.visible??null)};this.html.compose(c,l,s),c.labelbox&&c.cleanup.push(()=>c.labelbox.menu?.dispose()),c.shape=je.shape(c.element,u),this.records.set(e,c),this.elements.set(c.element,c),this.elements.set(c.presentation,c);let d=je.for(c.binding,c);(d||c.element.namespaceURI===Fe&&c.element.localName==="input")&&c.cleanup.push(()=>c.control?.detach()),d&&(c.control=d,d.attach(),this.#f(c,e,a,null));let f=vs.for(c.binding,c);if(f&&(c.button=f,f.attach(),c.cleanup.push(()=>f.detach())),e.nodeTag==="menu"&&(c.menu=new Es(c.binding,c.element),c.menu.attach(),c.cleanup.push(()=>c.menu.detach())),e.nodeTag==="groupletCard"){let h=new xs(c.binding,c.element);h.attach(),c.cleanup.push(()=>h.detach())}this.#p(c),this.references?.register(e,c.element);for(let h of s){let p=this.elements.get(h);p&&(p.parent=c,p.container=c.element,c.children.add(p.node))}return c.presentation}validateCandidate(e,{replacingNode:t=null}={}){if(!(e instanceof Ae))throw new TypeError("Source values must be GramlotBuilderBags");let r=new Set,o=s=>{if(!r.has(s)){r.add(s);for(let l of this.records.get(s)?.children??[])o(l);if(s.value instanceof I)for(let l of s.value.getNodes())o(l)}};for(let s of this.records.get(t)?.children??[])o(s);if(t?.value instanceof I)for(let s of t.value.getNodes())o(s);this.#i(e,t?t.nodeTag:null),mc(e),this.references?.validate(e,r);let i=new Set,a=s=>{for(let l of s.getNodes()){let u=l.getAttr("nodeId");if(u!=null){let c=this.binding.nodeIds.get(u);if(i.has(u)||c&&c!==l&&!r.has(c))throw new Error(`Duplicate nodeId '${u}'`);i.add(u)}l.value instanceof I&&a(l.value)}};return a(e),e}#i(e,t=null){let r=new Set,o=(i,a=null)=>{if(!(i instanceof Ae)||r.has(i))throw new TypeError("Source values must be unshared, acyclic GramlotBuilderBags");if(!(i._builder instanceof Ze))throw new TypeError("SourceBag requires builder ownership");r.add(i);for(let s of i.getNodes()){if(!(s instanceof ln))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(!(s.builder instanceof Ze))throw new TypeError("SourceBagNode requires builder ownership");if(s.resolver)throw new TypeError("Source resolvers are outside this port");if(s._getMeta("data_element"))s.builder.validateNode(s);else if(s.nodeTag){let l=s._getMeta("subbuilder")?i._builder:s.builder;this.html.validate(s,l),s._getMeta("subbuilder")||s.builder.validateParent(s.nodeTag,a)}else{if(!(s.value instanceof I))throw new TypeError("Source fragments must contain child SourceBags");if(Object.keys(s.attr).some(l=>l!=="_meta"))throw new TypeError("Fragment attributes are unsupported")}s.value instanceof I&&o(s.value,s._getMeta("subbuilder")?null:s.nodeTag??a)}};o(e,t)}freeze(e){e=ie(e);let t=this.records.get(e);if(!t||this.disposed)throw new Error("Freeze requires a mounted Source node");t.frozen=!0}unfreeze(e){e=ie(e);let t=this.records.get(e);if(!t||this.disposed)throw new Error("Unfreeze requires a mounted Source node");let r=o=>{delete o.frozen;for(let i of o.children)r(this.records.get(i))};r(t),!this.#a(e)&&(this.attached(e)?this.#g(e):this.remove(e))}#a(e){for(;e;){let t=this.records.get(e);if(t?.frozen)return!0;e=e.parentBag?.parentNode??t?.parent?.node}return!1}receive(e){if(this.disposed)return;let t=r=>this.#e.has(r)||e.evt==="del"&&r.nodeTag==="dataSetter";if(Array.isArray(e.node)){let r=e.node.filter(o=>!t(o));if(!r.length)return;e={...e,node:r}}else if(t(e.node))return;if(this.pending.push(e),!this.building){this.building=!0;try{for(;this.pending.length;){let r=this.pending.shift();if(r.evt!=="del"&&!this.attached(r.node))continue;r.evt!=="del"&&r.evt!=="upd_attrs"&&this.#u(r);let o=this.binding.handleSourceEvent(r);try{this.#s(r,o)}catch(i){if(!o.length)throw i;o.push(i)}if(this.binding.refreshSourceTrees(),o.length)throw o.length===1?o[0]:new AggregateError(o,"Source cleanup failed")}}catch(r){throw this.pending.length=0,r}finally{this.building=!1}}}#s(e,t){if(e.evt==="del"){for(let r of Array.isArray(e.node)?e.node:[e.node]){if(this.#a(r))continue;let o=this.records.get(r)?.parent??null;try{this.remove(r)}catch(i){t.push(i)}this.#h(o)}return}if(!this.#a(e.node))if(e.evt==="ins")this.insert(e.node);else if(e.evt.startsWith("upd_"))this.update(e.node,e.evt);else throw new Error(`Unsupported Source event: ${e.evt}`)}attached(e){let t=e.parentBag;for(;t&&t!==this.source;)t=t.parentNode?.parentBag;return t===this.source}#l(e){let t=new Set(this.pending.flatMap(r=>Array.isArray(r.node)?r.node:[r.node]));for(let r=e;r;r=r.parentBag?.parentNode)if(t.has(r))return!0;return!1}#u(e){let t=r=>{if(!(r instanceof ln))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(r.value instanceof I){if(!(r.value instanceof Ae))throw new TypeError("Source values must be GramlotBuilderBags");for(let o of r.value.getNodes())t(o)}};t(e.node)}unmountView(e){this.#t.add(e),this.remove(e)}mountView(e){this.#t.delete(e),this.insert(e)}insert(e){if(!this.attached(e)||this.records.has(e))return;for(let a=e;a;a=a.parentNode)if(this.#t.has(a))return;if(e._getMeta("data_element")){this.records.get(e.parentBag?.parentNode)?.button?.refresh(),this.binding.branchBuilt(e);return}let t=this.records.get(e.parentBag?.parentNode),r=t?.element??t?.container??this.destination,o=e.parentBag.getNodes(),i=t?.end??null;for(let a=o.indexOf(e)+1;a<o.length;a++){let s=this.records.get(o[a]);if(s){i=s.presentation??s.start;break}}this.buildNode(e,r,i,t)}buildNode(e,t,r=null,o=null){this.#e.add(e);let i;try{i=this.render(e,{document:t.ownerDocument})}catch(s){this.#c(e,s)}finally{this.#e.delete(e)}let a=this.records.get(e);return t.insertBefore(i,r),a.parent=o,this.assignContainer(a,t),o?.children.add(e),this.#h(o),this.binding.branchBuilt(e),a}#c(e,t){let r=[t],o=[],i=a=>{if(o.push(a),a.value instanceof I)for(let s of a.value.getNodes())i(s)};i(e);for(let a of o.reverse())try{this.remove(a)}catch(s){r.push(s)}throw r.length===1?t:new AggregateError(r,"Source build and cleanup failed")}mountDestination(e,t){let r=this.records.get(e);if(!r?.presentation||t?.nodeType!==1)throw new TypeError("mountDestination requires a mounted element and an HTML destination");if(r.presentation.contains(t))throw new Error("Destination cannot be inside the moved presentation");let o=r.parent;return this.remove(e),this.buildNode(e,t,null,o)}assignContainer(e,t){e.container=t;let r=e.element??t;for(let o of e.children){let i=this.records.get(o);i&&this.assignContainer(i,r)}}update(e,t){let r=this.records.get(e);if(!r){this.insert(e);return}let o=e.value==null||["string","number","boolean"].includes(typeof e.value),i=t==="upd_value"&&o&&r.element&&r.children.size===0&&this.html.matches(r,e);(t==="upd_attrs"||i)&&r.element&&this.html.matches(r,e)?(e.nodeTag&&this.html.validate(e,e._getMeta("subbuilder")?e.parentBag._builder:e.builder),this.project(e),t==="upd_attrs"&&this.records.get(e)===r&&(this.references?.remove(e),this.references?.register(e,r.element))):this.#g(e)}project(e,t=null){let r=this.records.get(e);if(!r?.element||!this.attached(e))return;let o=this.getRender(e.builder),i=this.#o.get(e),[a,s]=e.rootBuilder.runtimeValues(e),[,l]=o._handleMeta(e,s),u=this.#r.get(e),c=r.element.namespaceURI===Fe&&r.element.localName==="input"&&!Object.is(r.resolved.type,u.type),d=r.element.namespaceURI===Fe&&["input","select"].includes(r.element.localName)&&!!r.resolved.multiple!=!!u.multiple,f=r.resolved.group,h=r.control instanceof po&&!Object.is(f??null,u.group??null);if((c||d||h)&&this.#a(e))return;if(r.shape!==je.shape(r.element,u)){if(this.#a(e))return;this.#n.set(e,u);try{this.#g(e)}finally{this.#n.delete(e)}return}let p=c?je.classFor(r.element,u):null,m=c&&(r.control?.constructor??null)!==p,b=(c||d&&r.element.localName==="input")&&!m&&r.control&&Object.is(r.resolved.value,u.value);if(m&&(r.control?.detach(),r.control=null),h&&!m&&u.group!=null&&e.getAttr("name")!=null)throw new TypeError(`${e.nodeTag} '${e.label}': name and group are two names`);r.resolved=u;let w=e._getMeta("subbuilder")?l:o.adaptAttrs(l),_=e.value instanceof I,y=_?[]:this.expressionValue(e,a);if(o===this&&(w=this.restoreNativeAttributes(e,w),e._getMeta("gramlot_component")||([y,w]=vi(y,w,(S,k)=>this._binding.gramlot.format(S,k)))),w=this.componentAttributes(e,w),this.html.update(r,e,w,_?w._text:y,u.visible??null,t),m&&p&&(r.control=new p(r.binding,r),r.control.attach()),h&&!m){r.control.refresh(f??null),this.records.get(e)===r&&!r.binding.closed&&this.project(e);return}b||this.#f(r,e,w,t),r.control?.refresh(),r.button?.refresh(),r.menu?.refresh(),this.#p(r);let x=this.#o.get(e);if(x){let S=new Set([...Object.keys(i??{}),...Object.keys(x)].filter(k=>!Object.is(i?.[k],x[k])));S.size&&this.#d(e,S)}(r.element.localName==="option"||r.element.localName==="optgroup")&&this.#h(r.parent)}#d(e,t){if(e.value instanceof I)for(let r of e.value.getNodes()){let o=r._getMeta("gramlot_component"),i=r.getAttr(),a=t;o?.presentationDefaults.length?a=new Set([...t].filter(s=>!Object.hasOwn(i,s))):this.html.hasLabelbox(r)&&[...t].some(s=>!Object.hasOwn(i,s))&&this.project(r),a.size&&this.#d(r,a)}}componentAttributes(e,t){let r=e._getMeta("gramlot_component"),o=e.parentNode?._getMeta("gramlot_component")?.childParameters;if(!r&&!o)return t;let i=this.#r.get(e),a=Object.fromEntries([...new Set([...Object.keys(r?.parameters??{}),...Object.keys(o??{}),...Object.keys(i).filter(s=>s.startsWith("validate_"))])].filter(s=>Object.hasOwn(i,s)).map(s=>[s,i[s]]));return{...t,...a}}#f(e,t,r,o){if(!e.control)return;let i=t.getAttr("value")!=null;(i||e.valueDeclared)&&e.control.project(r.value??null,o),e.valueDeclared=i}#p(e){let t=new Map(Si.declared(e.node).map(r=>[r[0],r]));if(!e.events){if(!t.size)return;e.events=new Map,e.cleanup.push(()=>{for(let r of e.events.values())r.detach();e.events.clear()})}for(let[r,o]of[...e.events])t.get(r)?.[2]!==o.handler&&(o.detach(),e.events.delete(r));for(let[r,[,o,i]]of t){if(e.events.has(r))continue;let a=new Si(e.binding,e,o,i,r);a.attach(),e.events.set(r,a)}}#h(e){for(let t=e;t;t=t.parent){if(t.control instanceof Di){this.project(t.node);return}if(t.element&&t.element.localName!=="optgroup")return}}getDomNode(e){let t=ie(e),r=this.records.get(t);return r&&this.attached(t)?r.element??null:null}getBaseSourceNode(e){for(let t=e;t;t=t.parentNode){let r=t.nodeType===1?this.elements.get(t):null;if(r)return this.attached(r.node)?r.node:null}return null}#m(e){let t=this.binding.bindingFor(e);if(!t)throw new Error(`${e.nodeTag??"fragment"} '${e.label}': rendered without an open NodeBinding`);return t}#g(e){let t=this.records.get(e),r=t.presentation?.nextSibling??t.end?.nextSibling??null,o=t.container,i=t.parent,a=null;try{this.remove(e)}catch(s){a=s}try{this.buildNode(e,o,r,i)}catch(s){throw a?new AggregateError([a,s],"Source replacement cleanup and commit failed"):s}if(a)throw a}onDispose(e,t){let r=this.records.get(e);if(!r)throw new Error("Source node is not mounted");return r.cleanup.push(t),()=>{let o=r.cleanup.indexOf(t);o!==-1&&r.cleanup.splice(o,1)}}remove(e){let t=this.records.get(e);if(!t)return;let r=[];for(let o of[...t.children])try{this.remove(o)}catch(i){r.push(i)}for(let o of t.cleanup.splice(0).reverse())try{o()}catch(i){r.push(i)}if(this.references?.remove(e),t.element&&this.elements.delete(t.element),t.presentation&&this.elements.delete(t.presentation),t.presentation?.remove(),t.start?.remove(),t.end?.remove(),t.parent?.children.delete(e),this.records.delete(e),this.#r.delete(e),this.#o.delete(e),r.length)throw new AggregateError(r,"Source cleanup failed")}dispose(){if(this.disposed)return;this.disposed=!0,this.dragDrop.dispose(),this.source.unsubscribe(this.subscription,{any:!0}),this.pending.length=0;let e=[],t=[...this.records.entries()].filter(([,r])=>!r.parent).map(([r])=>r);for(let r of t)try{this.remove(r)}catch(o){e.push(o)}if(e.length)throw new AggregateError(e,"Renderer cleanup failed")}};var y2=new Set(["page","constructor"]);function cm(n,e){if(n===null)return[];let t=n.split("/");for(let r of t)if(y2.has(r))throw new Error(`${e}: a logic group cannot be named '${r}' (group '${n}')`);return t}var v2=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]);function E2(n){return/^[\w$]/.test(n)?v2.has(n):n!==")"&&n!=="]"}function x2(n,e){let t=!1;for(let r=e+1;r<n.length;r++){let o=n[r];if(o===`
|
|
233
|
-
`)return-1;if(o==="\\"){r++;continue}if(o==="[")t=!0;else if(o==="]")t=!1;else if(o==="/"&&!t)return r}return-1}function
|
|
234
|
-
`,o),o<0)break;continue}if(i==="/"&&n[o+1]==="*"){let a=n.indexOf("*/",o+2);if(a>=0){o=a+1;continue}}if(i==="/"&&E2(r)){let a=x2(n,o);if(a>=0){o=a,r=")";continue}}if(i==='"'||i==="'"||i==="`"){let a=o+1;for(;a<n.length&&n[a]!==i;)a+=n[a]==="\\"?2:1;e===1&&(t+=n.slice(o+1,a)==="constructor"?" constructor":' ""'),o=a,r=")";continue}if(/[\w$]/.test(i)){let a=o+1;for(;a<n.length&&/[\w$]/.test(n[a]);)a++;e===1&&(t+=n.slice(o,a)),r=n.slice(o,a),o=a-1;continue}if(/\s/.test(i)||(r=i),i==="{"){++e===2&&(t+=" {}");continue}if(i==="}"){e--;continue}e===1&&(t+=i)}return/(?<![\w$.#])(?<!\bstatic\s+)constructor\s*\(/.test(t)}function dm(n,e){if(n===void 0)return[];if(typeof n!="function"||!/^class\b/.test(Function.prototype.toString.call(n)))throw new Error(`${e}: the module exports no class Logic`);if(Object.getPrototypeOf(n)!==Function.prototype||Object.getPrototypeOf(n.prototype)!==Object.prototype)throw new Error(`${e}: class Logic cannot extend another class`);if(k2(Function.prototype.toString.call(n)))throw new Error(`${e}: class Logic cannot declare a constructor; state lives on the group or the page`);let t=[];for(let r of Reflect.ownKeys(n.prototype)){if(r==="constructor")continue;if(typeof r=="symbol")throw new Error(`${e}: class Logic cannot declare symbol keys (${String(r)})`);let o=Object.getOwnPropertyDescriptor(n.prototype,r);if(o.get||o.set)throw new Error(`${e}: class Logic cannot declare the accessor '${r}'`);if(typeof o.value!="function")throw new Error(`${e}: Logic.prototype.${r} is not a method`);if(r==="page")throw new Error(`${e}: a logic method cannot be named 'page'`);t.push([r,o.value])}return t}function fm(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}var bn=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get page(){return this.#t}},_o=class{#e;#t=new Map;constructor(e){this.#e=e,e.logic=new bn(this,e)}get gramlot(){return this.#e}static check(e){let t=new Map;for(let{group:r,resource:o}of e){let i=cm(r,o);for(let a=0;a<i.length;a++){let s=i.slice(0,a).join("/");t.has(s)||t.set(s,new Set),t.get(s).add(i[a])}}for(let{logicClass:r,group:o,resource:i}of e){let a=t.get(o??"")??new Set;for(let[s]of dm(r,i))if(a.has(s))throw new Error(`${i}: the logic method '${s}' has the name of a child group`)}}register(e,{group:t=null,resource:r}){let o=cm(t,r),i=dm(e,r),a=this.#e.logic;for(let s of o){let l=Object.getOwnPropertyDescriptor(a,s)?.value;if(l===void 0){let u=new bn(this,this.#e);fm(a,s,u),a=u}else if(l instanceof bn)a=l;else throw new Error(`${r}: the group '${s}' has the name of a logic method`)}for(let[s,l]of i){if(Object.getOwnPropertyDescriptor(a,s)?.value instanceof bn)throw new Error(`${r}: the logic method '${s}' has the name of a child group`);fm(a,s,l)}this.#t.has(a)||this.#t.set(a,[]),this.#t.get(a).push(r)}resolve(e,t){let r=e.split("."),o=r.pop(),i=this.#e.logic;for(let s=0;s<r.length;s++)if(i=Object.getOwnPropertyDescriptor(i,r[s])?.value,!(i instanceof bn))throw new Error(`${t.nodeTag} '${t.label}': named logic '${e}' not found: no resource was registered for the group '${r.slice(0,s+1).join("/")}'`);let a=Object.getOwnPropertyDescriptor(i,o)?.value;if(typeof a!="function"){let s=this.#t.get(i)??[],l=r.length?`the group '${r.join("/")}'`:"the page logic";throw new Error(`${t.nodeTag} '${t.label}': named logic '${e}' not found: ${l} has no method '${o}' (resources: ${s.join(", ")||"none"})`)}return{group:i,method:a}}};var Pi=class extends Ke{constructor(e,{collections:t,destination:r,subscriptions:o,nameSyntax:i}){super(e),e.src=this,this.logicRegistry=new _o(e),this.builder=new Oe(null,{collections:t,nameSyntax:i}),this.binding=new wo(e,{subscriptions:o}),this.builder.binding=this.binding,this.binding.attach(),this.source=this.builder.source,this.renderer=new Mi(this.builder,this.source,r,{binding:this.binding})}startSource(e){if(!["ready","failed"].includes(this.gramlot.state))throw new Error(`Cannot start embedded Source while Gramlot is ${this.gramlot.state}`);try{return this.mountMainSource(e)}catch(t){throw this.gramlot.state="failed",t}}mountMainSource(e,t=null){let r=this.prepareSource(e);if(this.renderer.validateCandidate(r),t!==null){if(!(t instanceof E)||t instanceof I)throw new TypeError("Initial page data must be a Data Bag");for(let o of t.getNodes())this.builder.data.setItem([o.label],o.getValue(),o.attr,">",!1,!1)}try{this.source.setItem("main",r)}catch(o){throw this.binding.bindingFor(this.source.getNode("main"))||this.source.popNode("main"),o}return this.gramlot.state="started",this.binding.pageStarted(),this.binding.subscriptions.ready(),this.gramlot}prepareSource(e,t=this.builder){if(e instanceof I){if(!(e instanceof Ae))throw new TypeError("Source values must be GramlotBuilderBags");return e.bindBuilder(t).activateCode()}if(typeof e!="string")throw new TypeError("Source value did not decode to SourceBag");let r=Vu(e,t);if(!(r instanceof Ae))throw new TypeError("Source values must be GramlotBuilderBags");return r.activateCode()}async remoteSource(e,t,r={}){if(!this.gramlot.rpc.transport?.call)throw new Error("Remote Source is unavailable without a server transport");let i=this.binding.bindingFor(e);if(this.gramlot.state!=="started"||!i)throw new Error("Remote Source target is not mounted");return await e.requests.submit(t,r,a=>this.#e(e,i,a))??!1}async#e(e,t,r){if(t.closed||this.gramlot.state==="disposed")return!1;let o=!1,i=()=>this.gramlot.state!=="disposed"&&!r.ignored&&!t.closed;try{let a=await t.call("source",r);if(!i())return!1;let s=this.prepareSource(a,e.builder);return i()?(this.renderer.validateCandidate(s,{replacingNode:e}),o=!0,e.setValue(s,!0,{_text:null},!0),t.remote?.fragmentMounted(r.method,r.text),!0):!1}catch(a){if(!o&&!i())return!1;throw a}}};var Li=class extends Ke{setTouchMode(e="auto"){if(!["auto","on","off"].includes(e))throw new TypeError(`Invalid touch mode: ${e}`);let t=this.gramlot.src.renderer.destination.ownerDocument.documentElement;e==="auto"?t.removeAttribute("data-gramlot-touch"):t.setAttribute("data-gramlot-touch",e)}navigate(e){if(typeof e!="string"||!e)throw new TypeError("Navigation requires an absolute HTTP(S) URL");let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw new TypeError("Navigation requires an HTTP(S) URL without credentials");this.gramlot.src.renderer.destination.ownerDocument.defaultView.location.assign(t.href)}reference(e){return this.gramlot.src.renderer.references.resolve(e)}getBaseSourceNode(e){return this.gramlot.src.renderer.getBaseSourceNode(e)}getDomNode(e){return this.gramlot.src.renderer.getDomNode(e)}};var Ws=class extends Ke{#e=new Map;#t=new WeakSet;#r=new WeakMap;#n=0;#o=!1;ready(){this.gramlot._frames.ready()}subscribe(e,t){if(this.#s(),this.#a(e),typeof t!="function")throw new TypeError("subscribe requires a callback");let r=Object.freeze({});return this.#t.add(r),this.#e.has(e)||this.#e.set(e,new Map),this.#e.get(e).set(r,t),r}unsubscribe(e){if(!this.#t.has(e))throw new TypeError("Unknown subscription registration");for(let[t,r]of this.#e)r.delete(e)&&!r.size&&this.#e.delete(t)}publish(e,t={},r={}){if(this.#s(),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("publish requires one object of named data");if(typeof e=="string")return this.#i(e,t,r);if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("publish requires a topic string or descriptor");if(Object.keys(e).some(a=>!["topic","nodeId","parent","iframe","pageId","server"].includes(a)))throw new Error("This publication route is not implemented yet");if(this.#a(e.topic),e.parent!==void 0&&typeof e.parent!="boolean")throw new TypeError("parent must be boolean");if(e.server!==void 0&&typeof e.server!="boolean")throw new TypeError("server must be boolean");if(e.iframe==="*")throw new Error("Recursive iframe broadcast is not implemented yet");if(e.pageId!==void 0&&(typeof e.pageId!="string"||!e.pageId))throw new TypeError("pageId must be a nonempty string");if((e.parent||e.iframe!==void 0||e.pageId!==void 0)&&Object.hasOwn(e,"nodeId"))throw new Error("Interframe node addressing is not implemented yet");let i=null;if(e.server===!0){if(["parent","iframe","nodeId"].some(a=>Object.hasOwn(e,a)))throw new Error("Server publication cannot combine window or node selectors");if(!this.gramlot._pageStore)throw new Error("Server publication requires a WebSocket channel");i=this.gramlot._pageStore.preparePublish(e,t)}else(e.parent||e.iframe!==void 0||e.pageId!==void 0)&&(i=this.gramlot._frames.prepare(e,t));if(Object.hasOwn(e,"nodeId")){let a=this.gramlot.src.binding.nodeIds.get(e.nodeId);if(!a)throw new Error(`nodeId not found: ${e.nodeId}`);return this.publishNode(a,e.topic,t)}return this.#i(e.topic,t),i?.()}topicFor(e,t){this.#a(t),e=ie(e);let r=this.gramlot.src.binding.bindingFor(e);if(!r||r.closed)throw new Error("Topic target is not an active Source node of this page");let o=e.getAttr("nodeId");return o==null&&(this.#r.has(e)||this.#r.set(e,`gramlot-self-${++this.#n}`),o=this.#r.get(e)),`${o}_${t}`}publishNode(e,t,r={}){return this.publish(this.topicFor(e,t),r)}subscribeNode(e,t){let r=[];for(let[o,i]of Object.entries(e.getAttr())){let a=o.startsWith("selfsubscribe_")?"selfsubscribe_":o.startsWith("subscribe_")?"subscribe_":null;if(!a)continue;let s=a==="selfsubscribe_"?this.topicFor(e,o.slice(a.length)):o.slice(a.length);this.#a(s),r.push([s,t(o,i,s)])}return this.#s(),r.map(([o,i])=>{let a=this.subscribe(o,i);return{close:()=>this.unsubscribe(a)}})}dispose(){this.#o=!0,this.#e.clear()}#i(e,t,r={}){this.#a(e);let o=this.#e.get(e);if(o)for(let[i,a]of[...o]){if(this.#o)break;o.has(i)&&a(t,{...r})}}#a(e){if(typeof e!="string"||!e)throw new TypeError("A topic must be a nonempty string")}#s(){if(this.#o)throw new Error("Gramlot subscriptions are disposed")}};var Ys=class extends fe{constructor(e,t,r){super({cacheTime:r}),this.handler=e,this.name=t,this.failed=!1,this.writing=!1,this.request=null,this.revision=0,this.received=0}resolve({static:e=!1}={}){return!e&&!this.handler.disposed&&!this.writing&&!this.request&&!this.failed&&!this._node.attr.watching&&this.expired&&this.handler.refresh(this.name),this.cachedValue}reset(){super.reset(),this.failed=!1,this.revision++}};var hm=["appinfo","location"],pm={UNAVAILABLE:"unavailable",PERMISSION_DENIED:"denied",TIMEOUT:"error",FAILED:"error",CANCELLED:"cancelled"};function ne(n){let e=Object.hasOwn(pm,n?.code)?n.code:"FAILED";return{status:pm[e],error:e==="CANCELLED"?null:{code:e,message:String(n?.message??"Device operation failed")}}}var Fi=class extends Ke{#e=null;#t=null;#r=null;#n=null;#o=null;#i=null;#a=new Map;#s=new Map;#l=null;#u=null;#c=null;#d=null;#f=null;#p=null;#h=null;constructor(e){super(e),this.provider=null,this.disposed=!1,this.monitor=null,this.retiring=null,this.resolvers=new Map,this.cleanup=Promise.resolve()}installData(){let{gramlot:e}=this;e.data.setItem("_gramlot.device.database",null,{status:"idle",error:null}),e.data.setItem("_gramlot.device.orientation",null,{status:"idle",error:null,listening:!1});for(let m of["gyroscope","accelerometer"])e.data.setItem(`_gramlot.device.${m}`,null,{enabled:!1,watching:!1,status:"idle",error:null}),e.data.getNode(`_gramlot.device.${m}`).setAttr({error:null},!1,!0,!1),this.#s.set(m,{node:e.data.getNode(`_gramlot.device.${m}`),stream:null,cleanup:Promise.resolve()});for(let m of hm){let b=`_gramlot.device.${m}`,w={status:"idle",error:null,cacheTime:m==="appinfo"?-1:5};m==="location"&&Object.assign(w,{enabled:!1,watching:!1}),e.data.setItem(b,null);let _=e.data.getNode(b);_.setAttr(w,!1,!0,!1);let y=new Ys(this,m,w.cacheTime);_.resolver=y,this.resolvers.set(m,y)}e.data.setItem("_gramlot.device.clipboard",null,{status:"idle",error:null,text:"",copy:null,paste:null,operation:null});let t=e.data.getNode("_gramlot.device.clipboard");e.data.setItem("_gramlot.device.camera",null,{status:"idle",error:null,capture:null,choose:null});let r=e.data.getNode("_gramlot.device.camera");e.data.setItem("_gramlot.device.barcode",null,{status:"idle",error:null,scan:null});let o=e.data.getNode("_gramlot.device.barcode");e.data.setItem("_gramlot.device.biometrics",null,{status:"idle",error:null,verify:null});let i=e.data.getNode("_gramlot.device.biometrics"),a=new E;a.setItem("request",new E);for(let m of["scheduled","received","action"])a.setItem(m,null);e.data.setItem("_gramlot.device.notifications",a,{status:"idle",error:null,schedule:null,listening:!1,listenerError:null});let s=e.data.getNode("_gramlot.device.notifications"),l=new E;for(let m of["registration","received","action"])l.setItem(m,null);e.data.setItem("_gramlot.device.push",l,{status:"idle",error:null,register:null,listening:!1,listenerError:null});let u=e.data.getNode("_gramlot.device.push"),c=new E;c.setItem("request",null),e.data.setItem("_gramlot.device.links",c,{listening:!1,listenerError:null});let d=new E;d.setItem("request",null),e.data.setItem("_gramlot.device.shortcuts",d,{listening:!1,listenerError:null}),e.data.setItem("_gramlot.device.network",null,{status:"idle",error:null,listening:!1});let f=new E;f.setItem("active",null),f.setItem("event",null),f.setItem("sequence",0),e.data.setItem("_gramlot.device.lifecycle",f,{status:"idle",error:null,listening:!1}),e.data.setItem("_gramlot.device.haptics",null,{status:"idle",error:null,impact:null,style:"medium",vibrate:null,duration:600});let h=e.data.getNode("_gramlot.device.haptics");e.data.setItem("_gramlot.device.audio",null,{status:"idle",error:null,recording:!1,start:null,stop:null,cancel:null,share:null,shareStatus:"idle",shareError:null,shareActivity:null});let p=e.data.getNode("_gramlot.device.audio");e.data.subscribe("gramlot.device",{update:m=>{if(!this.disposed){for(let[b,w]of this.#s)if(m.node===w.node&&m.attrs_diff?.enabled){if(typeof w.node.attr.enabled!="boolean")throw new TypeError("Device enabled must be boolean");this.#g(b,w)}m.node===t&&m.fired&&(m.attrs_diff?.copy?.new===!0&&this.#v(t,"copy"),m.attrs_diff?.paste?.new===!0&&this.#v(t,"paste")),m.node===p&&m.fired&&(m.attrs_diff?.start?.new===!0&&this.#b(p),m.attrs_diff?.stop?.new===!0&&this.#w(p),m.attrs_diff?.cancel?.new===!0&&this.#y(p),m.attrs_diff?.share?.new===!0&&this.#_(p)),m.node===h&&m.fired&&m.attrs_diff?.impact?.new===!0&&this.#k(h),m.node===h&&m.fired&&m.attrs_diff?.vibrate?.new===!0&&this.#E(h),m.node===o&&m.fired&&m.attrs_diff?.scan?.new===!0&&this.#S(o),m.node===r&&m.fired&&m.attrs_diff?.choose?.new===!0&&this.#T(r,"choose"),m.node===r&&m.fired&&m.attrs_diff?.capture?.new===!0&&this.#T(r,"capture"),m.node===i&&m.fired&&m.attrs_diff?.verify?.new===!0&&this.#C(i),m.node===s&&m.fired&&m.attrs_diff?.schedule?.new===!0&&this.#N(s),m.node===u&&m.fired&&m.attrs_diff?.register?.new===!0&&this.#O(u);for(let b of this.resolvers.values()){if(m.node!==b._node)continue;let{cacheTime:w}=m.node.attr;if(typeof w!="number"||!Number.isFinite(w)||w<0&&w!==-1)throw new TypeError("Device cacheTime must be -1 or a nonnegative number of seconds");if(b.cacheTime=w,b.name==="location"){if(typeof m.node.attr.enabled!="boolean")throw new TypeError("Device enabled must be boolean");this.reconcile()}}}}})}attach(e,{dispose:t=null}={}){if(this.assertLive(),this.provider)throw new Error("A device provider is already attached");if(!Array.isArray(e.capabilities)||e.capabilities.some(r=>![...hm,"camera","biometrics","notifications","push","shortcuts","barcode","network","lifecycle","haptics","audio","clipboard","links","orientation","gyroscope","accelerometer","database"].includes(r)))throw new TypeError("Unknown device provider capability");if(t!==null&&typeof t!="function")throw new TypeError("Device attachment dispose must be a function");this.releaseProvider=t,this.provider=e,this.installData(),this.reconcile(),this.#m("orientation",(r,o)=>e.startOrientationEvents(r,o),(r,o)=>{if(!["portrait","landscape"].includes(o?.type)||!["primary","secondary"].includes(o.direction)||!Number.isFinite(o.timestamp))throw new TypeError("Invalid screen orientation from device provider");let i=new E;for(let a of["type","direction","timestamp"])i.setItem(a,o[a]);r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("network",(r,o)=>e.startNetworkEvents(r,o),(r,o)=>{if(typeof o?.connected!="boolean"||!["none","unknown","wifi","cellular"].includes(o.type))throw new TypeError("Invalid network state from device provider");let i=new E;i.setItem("connected",o.connected),i.setItem("type",o.type),r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("lifecycle",(r,o)=>e.startLifecycleEvents(r,o),(r,o)=>{if(o?.kind==="state"&&typeof o.active=="boolean")r.staticValue.setItem("active",o.active);else if(o?.kind==="pause"||o?.kind==="resume")r.staticValue.setItem("event",o.kind),r.staticValue.setItem("sequence",r.staticValue.getItem("sequence")+1);else throw new TypeError("Invalid lifecycle event from device provider");r.setAttr({status:"success",error:null},!0,!0,!1)}),e.capabilities.includes("links")&&this.#B(this.gramlot.data.getNode("_gramlot.device.links")),e.capabilities.includes("shortcuts")&&this.#R(this.gramlot.data.getNode("_gramlot.device.shortcuts")),e.capabilities.includes("push")&&this.#D(this.gramlot.data.getNode("_gramlot.device.push")),e.capabilities.includes("notifications")&&this.#A(this.gramlot.data.getNode("_gramlot.device.notifications"))}assertLive(){if(this.disposed)throw new Error("DeviceHandler is disposed")}resolver(e){if(this.assertLive(),!this.resolvers.has(e))throw new TypeError(`Unknown device value: ${e}`);return this.resolvers.get(e)}invalidate(e){this.resolver(e).reset()}refresh(e){let t=this.resolver(e);if(t.request)return;let r={revision:t.revision,received:t.received};t.request=r,this.attributes(t,{status:"pending",error:null}),Promise.resolve().then(()=>{if(!(this.disposed||t.request!==r))return this.requireCapability(e),e==="appinfo"?this.provider.readAppInfo():this.provider.readLocation()}).then(o=>{this.disposed||t.request!==r||(this.accept(t,o),t.revision!==r.revision&&(t._lastUpdate=null))}).catch(o=>{!this.disposed&&t.request===r&&t.received===r.received&&this.failure(t,o)}).finally(()=>{t.request===r&&(t.request=null)})}#m(e,t,r){let o=this.gramlot.data.getNode(`_gramlot.device.${e}`);if(!this.provider.capabilities.includes(e)){o.setAttr(ne({code:"UNAVAILABLE",message:`${e} is unavailable`}),!0,!0,!1);return}let i={controller:new AbortController};this.#a.set(e,i),o.setAttr({status:"pending",error:null},!0,!0,!1),i.start=Promise.resolve().then(()=>i.controller.signal.aborted?async()=>{}:t(a=>{if(!i.controller.signal.aborted)try{r(o,a)}catch(s){o.setAttr(ne(s),!0,!0,!1)}},i.controller.signal)).then(a=>(i.controller.signal.aborted||o.setAttr({listening:!0},!0,!0,!1),a)),i.start.catch(a=>{let s=i.controller.signal.aborted;i.controller.abort(),s||o.setAttr({...ne(a),listening:!1},!0,!0,!1)})}#g(e,t){let{node:r}=t;if(!r.attr.enabled){let i=t.stream;if(!i)return;t.stream=null,i.controller.abort(),t.cleanup=i.start.then(a=>a(),()=>{}).then(()=>{!this.disposed&&!t.stream&&r.setAttr({watching:!1,status:"idle",error:null},!0,!0,!1)}),t.cleanup.catch(a=>{this.disposed||r.setAttr(ne(a),!0,!0,!1)});return}if(t.stream)return;let o={controller:new AbortController};t.stream=o,o.start=t.cleanup.then(()=>{if(o.controller.signal.aborted)return async()=>{};this.requireCapability(e);let i=a=>{if(!(this.disposed||o.controller.signal.aborted))try{if(a?.kind==="state"&&typeof a.watching=="boolean")r.setAttr({watching:a.watching,status:a.watching?"pending":"idle",error:null},!0,!0,!1);else if(a?.kind==="sample"){for(let l of["x","y","z","timestamp"])if(!Number.isFinite(a[l]))throw new TypeError(`Invalid ${e}.${l}`);if(!r.attr.watching||r.staticValue&&a.timestamp<r.staticValue.getItem("timestamp"))return;let s=new E;for(let l of["x","y","z","timestamp"])s.setItem(l,a[l]);r.setValue(s,!0,{status:"success",error:null},!0,!1)}else if(a?.kind==="error"&&a.error instanceof Error)r.setAttr({...ne(a.error),watching:!1},!0,!0,!1);else throw new TypeError(`Invalid ${e} event`)}catch(s){r.setAttr(ne(s),!0,!0,!1)}};return e==="gyroscope"?this.provider.startGyroscopeUpdates(i,o.controller.signal):this.provider.startAccelerometerUpdates(i,o.controller.signal)}),o.start.catch(i=>{!this.disposed&&!o.controller.signal.aborted&&r.setAttr({...ne(i),watching:!1},!0,!0,!1)}),r.setAttr({status:"pending",error:null},!0,!0,!1)}#b(e){let t=this.#n;if(t){if(t.phase!=="complete")return;t.phase="replacing",e.setValue(null,!0,{status:"pending",error:null,recording:!1,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),t.close=t.start.then(o=>o.dispose()).then(()=>{this.disposed||t.controller.signal.aborted||this.#n!==t||(this.#n=null,this.#b(e))}).catch(o=>{!this.disposed&&this.#n===t&&(t.phase="failed",e.setAttr(ne(o),!0,!0,!1))});return}let r={controller:new AbortController,phase:"starting"};this.#n=r,e.setValue(null,!0,{status:"pending",error:null,recording:!1,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),r.start=Promise.resolve().then(async()=>r.controller.signal.aborted?null:(this.requireCapability("audio"),this.provider.startAudioRecording(o=>{this.#n===r&&!r.controller.signal.aborted&&this.#y(e,o)},r.controller.signal))),r.start.then(o=>{!o||r.controller.signal.aborted||this.disposed||(r.phase="recording",e.setAttr({status:"recording",error:null,recording:!0},!0,!0,!1))}).catch(o=>{r.controller.signal.aborted||this.disposed||(this.#n===r&&(this.#n=null),e.setAttr({...ne(o),recording:!1},!0,!0,!1))})}#w(e){let t=this.#n;!t||t.phase!=="recording"||(t.phase="stopping",e.setAttr({status:"pending",error:null},!0,!0,!1),t.stop=t.start.then(r=>r.stop()).then(r=>{if(t.controller.signal.aborted||this.disposed)return;if(typeof r?.url!="string"||!r.url||typeof r.mimeType!="string"||!r.mimeType.startsWith("audio/")||!Number.isFinite(r.duration)||r.duration<0)throw new TypeError("Invalid audio result from device provider");let o=new E;for(let i of["url","mimeType","duration"])o.setItem(i,r[i]);t.phase="complete",e.setValue(o,!0,{status:"success",error:null,recording:!1},!0,!1)}).catch(r=>{!t.controller.signal.aborted&&!this.disposed&&this.#y(e,r)}))}#_(e){let t=this.#n;if(t?.phase!=="sharing"){if(!t||t.phase!=="complete"){let r=ne(new Error("Record and stop audio before sharing"));e.setAttr({shareStatus:r.status,shareError:r.error,shareActivity:null},!0,!0,!1);return}t.phase="sharing",e.setAttr({shareStatus:"pending",shareError:null,shareActivity:null},!0,!0,!1),t.share=t.start.then(r=>r.share(t.controller.signal)).then(r=>{if(!(t.controller.signal.aborted||this.disposed)){if(typeof r?.activity!="string")throw new TypeError("Invalid audio share result from device provider");e.setAttr({shareStatus:"success",shareError:null,shareActivity:r.activity},!0,!0,!1)}}).catch(r=>{if(t.controller.signal.aborted||this.disposed)return;let o=ne(r);e.setAttr({shareStatus:o.status,shareError:o.error,shareActivity:null},!0,!0,!1)}).finally(()=>{this.#n===t&&!t.controller.signal.aborted&&(t.phase="complete")})}}#y(e,t={code:"CANCELLED",message:"Audio recording cancelled"}){let r=this.#n;!r||r.phase==="closing"||r.phase==="sharing"||(r.phase="closing",r.controller.abort(),e.setValue(null,!0,{status:"pending",error:null,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),r.close=r.start.then(o=>o===null?void 0:o.dispose(),o=>{if(o?.code!=="CANCELLED")throw o}).then(()=>{this.disposed||this.#n!==r||(this.#n=null,e.setAttr({...ne(t),recording:!1},!0,!0,!1))}).catch(o=>{!this.disposed&&this.#n===r&&(r.phase="failed",e.setAttr(ne(o),!0,!0,!1))}))}#v(e,t){if(this.#t)return;let r=new AbortController;this.#t=r;let o=e.attr.text;e.setValue(null,!0,{status:"pending",error:null,operation:t},!0,!1),Promise.resolve().then(async()=>{if(r.signal.aborted)return;this.requireCapability("clipboard");let i;if(t==="copy"){if(typeof o!="string")throw new TypeError("Clipboard text must be a string");await this.provider.copyText(o,r.signal),i={text:o}}else i=await this.provider.pasteText(r.signal);if(r.signal.aborted)return;if(typeof i?.text!="string")throw new TypeError("Invalid clipboard text from device provider");let a=new E;a.setItem("text",i.text),e.setValue(a,!0,{status:"success",error:null},!0,!1)}).catch(i=>{r.signal.aborted||e.setAttr(ne(i),!0,!0,!1)}).finally(()=>{this.#t===r&&(this.#t=null)})}#E(e){if(this.#i)return;let t=new AbortController;this.#i=t;let{duration:r}=e.attr;e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(async()=>{if(t.signal.aborted)return;if(this.requireCapability("haptics"),!Number.isInteger(r)||r<1||r>5e3)throw new TypeError("Vibration duration must be an integer from 1 to 5000 milliseconds");if(await this.provider.vibrate(r,t.signal),t.signal.aborted)return;let o=new E;o.setItem("duration",r),o.setItem("acknowledged",!0),e.setValue(o,!0,{status:"success",error:null},!0,!1)}).catch(o=>{t.signal.aborted||e.setAttr(ne(o),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#k(e){if(this.#i)return;let t=new AbortController;this.#i=t;let{style:r}=e.attr;e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(async()=>{if(t.signal.aborted)return;if(this.requireCapability("haptics"),!["light","medium","heavy"].includes(r))throw new TypeError("Invalid haptic style");if(await this.provider.impact(r,t.signal),t.signal.aborted)return;let o=new E;o.setItem("style",r),o.setItem("acknowledged",!0),e.setValue(o,!0,{status:"success",error:null},!0,!1)}).catch(o=>{t.signal.aborted||e.setAttr(ne(o),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#S(e){if(this.#o)return;let t=new AbortController;this.#o=t,e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(()=>{if(!t.signal.aborted)return this.requireCapability("barcode"),this.provider.scanBarcode(t.signal)}).then(r=>{if(t.signal.aborted)return;if(typeof r?.text!="string"||!r.text||typeof r.format!="string"||!r.format)throw new TypeError("Invalid barcode result from device provider");let o=new E;o.setItem("text",r.text),o.setItem("format",r.format),e.setValue(o,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setAttr(ne(r),!0,!0,!1)}).finally(()=>{this.#o===t&&(this.#o=null)})}#T(e,t){if(this.#r)return;let r=new AbortController;this.#r=r,e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(()=>{if(!r.signal.aborted)return this.requireCapability("camera"),t==="choose"?this.provider.choosePhoto(r.signal):this.provider.takePhoto(r.signal)}).then(o=>{if(r.signal.aborted)return;if(typeof o?.url!="string"||!o.url||typeof o.format!="string"||!o.format)throw new TypeError("Invalid camera photo from device provider");let i=new E;i.setItem("url",o.url),i.setItem("format",o.format),e.setValue(i,!0,{status:"success",error:null},!0,!1)}).catch(o=>{r.signal.aborted||e.setAttr(ne(o),!0,!0,!1)}).finally(()=>{this.#r===r&&(this.#r=null)})}#C(e){if(this.#l)return;let t=new AbortController;this.#l=t,e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(()=>{if(!t.signal.aborted)return this.requireCapability("biometrics"),this.provider.verifyBiometrics(t.signal)}).then(()=>{if(t.signal.aborted)return;let r=new E;r.setItem("verified",!0),e.setValue(r,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setValue(null,!0,ne(r),!0,!1)}).finally(()=>{this.#l===t&&(this.#l=null)})}#A(e){if(this.#c)return this.#c.start;let t={controller:new AbortController};return this.#c=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startNotificationEvents(r=>{if(!t.controller.signal.aborted)try{if(!["received","action"].includes(r.kind)||!Number.isInteger(r.id)||typeof r.title!="string"||typeof r.body!="string"||r.kind==="action"&&typeof r.actionId!="string")throw new TypeError("Invalid notification event from device provider");let o=new E;for(let i of["id","title","body"])o.setItem(i,r[i]);r.kind==="action"&&o.setItem("actionId",r.actionId),e.staticValue.setItem(r.kind,o)}catch(o){e.setAttr({listenerError:ne(o).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let o=t.controller.signal.aborted;t.controller.abort(),this.#c===t&&(this.#c=null),o||e.setAttr({listening:!1,listenerError:ne(r).error},!0,!0,!1)}),e.setAttr({listenerError:null},!0,!0,!1),t.start}#N(e){if(this.#u)return;let t=new AbortController;this.#u=t;let r=e.staticValue.getItem("request"),o=r instanceof E?Object.fromEntries(["id","title","body","delay"].map(i=>[i,r.getItem(i)])):null;e.staticValue.setItem("scheduled",null),e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(async()=>{if(!t.signal.aborted){if(this.requireCapability("notifications"),!o||!Number.isInteger(o.id)||o.id<1||o.id>2147483647||typeof o.title!="string"||!o.title.trim()||typeof o.body!="string"||!o.body.trim()||typeof o.delay!="number"||!Number.isFinite(o.delay)||o.delay<=0)throw new TypeError("Notification requires a positive 32-bit id, title, body and positive delay in seconds");if(await this.#A(e),!t.signal.aborted)return this.provider.scheduleNotification(o,t.signal)}}).then(i=>{if(t.signal.aborted)return;if(i?.id!==o.id||typeof i.at!="number"||!Number.isFinite(i.at))throw new TypeError("Invalid notification scheduling acknowledgement");let a=new E;a.setItem("id",i.id),a.setItem("at",i.at),e.staticValue.setItem("scheduled",a),e.setAttr({status:"success",error:null},!0,!0,!1)}).catch(i=>{t.signal.aborted||e.setAttr(ne(i),!0,!0,!1)}).finally(()=>{this.#u===t&&(this.#u=null)})}#x(){let e=this.#d;return this.#d=null,e&&clearTimeout(e.timer),e}#I(e,t){if(t.kind==="registration"){if(typeof t.token!="string"||!t.token)throw new TypeError("Invalid push registration token");this.#x();let r=new E;r.setItem("token",t.token),e.staticValue.setItem("registration",r),e.setAttr({status:"success",error:null},!0,!0,!1)}else if(t.kind==="registrationError")this.#x(),e.staticValue.setItem("registration",null),e.setAttr(ne(t.error),!0,!0,!1);else{if(!["received","action"].includes(t.kind))throw new TypeError("Invalid push event kind");let r=["id","title","body","messageId","destination"];t.kind==="action"&&r.push("actionId");let o=new E;for(let i of r){if(typeof t[i]!="string")throw new TypeError(`Invalid push event ${i}`);o.setItem(i,t[i])}e.staticValue.setItem(t.kind,o)}}#D(e){if(this.#f)return this.#f.start;let t={controller:new AbortController};return this.#f=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startPushEvents(r=>{if(!t.controller.signal.aborted)try{this.#I(e,r)}catch(o){e.setAttr({listenerError:ne(o).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let o=t.controller.signal.aborted;t.controller.abort(),this.#f===t&&(this.#f=null),o||e.setAttr({listening:!1,listenerError:ne(r).error},!0,!0,!1)}),e.setAttr({listenerError:null},!0,!0,!1),t.start}#O(e){if(this.#d)return;let t={controller:new AbortController,timer:null};this.#d=t,t.timer=setTimeout(()=>{this.disposed||this.#d!==t||(this.#x(),t.controller.abort(),e.setAttr(ne({code:"TIMEOUT",message:"Push registration has not returned a token"}),!0,!0,!1))},3e4),e.staticValue.setItem("registration",null),e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(async()=>{t.controller.signal.aborted||(this.requireCapability("push"),await this.#D(e),!(t.controller.signal.aborted||this.#d!==t)&&await this.provider.registerPush(t.controller.signal))}).catch(r=>{this.disposed||this.#d!==t||(this.#x(),t.controller.abort(),e.setAttr(ne(r),!0,!0,!1))})}#R(e){let t={controller:new AbortController};this.#p=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startShortcutEvents((r,o=null)=>{if(!t.controller.signal.aborted)try{if(o)throw o;for(let a of["id","destination"])if(typeof r?.[a]!="string"||!r[a])throw new TypeError(`Invalid shortcut request ${a}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new E;i.setItem("id",r.id),i.setItem("destination",r.destination),e.setAttr({listenerError:null},!0,!0,!1),e.staticValue.setItem("request",i)}catch(i){e.setAttr({listenerError:ne(i).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let o=t.controller.signal.aborted;t.controller.abort(),o||e.setAttr({listening:!1,listenerError:ne(r).error},!0,!0,!1)})}#B(e){let t={controller:new AbortController};this.#h=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startLinkEvents((r,o=null)=>{if(!t.controller.signal.aborted)try{if(o)throw o;for(let a of["id","url"])if(typeof r?.[a]!="string"||!r[a])throw new TypeError(`Invalid link request ${a}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new E;i.setItem("id",r.id),i.setItem("url",r.url),e.setAttr({listenerError:null},!0,!0,!1),e.staticValue.setItem("request",i)}catch(i){e.setAttr({listenerError:ne(i).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let o=t.controller.signal.aborted;t.controller.abort(),o||e.setAttr({listening:!1,listenerError:ne(r).error},!0,!0,!1)})}requireCapability(e){if(!this.provider||!this.provider.capabilities.includes(e))throw Object.assign(new Error(`${e} is unavailable in this environment`),{code:"UNAVAILABLE"})}attributes(e,t){let r=e.writing;e.writing=!0;try{e._node.setAttr(t,!0,!0,!1)}finally{e.writing=r}}accept(e,t){let r=e.name==="appinfo"?["id","name","version","build"]:["latitude","longitude","accuracy","timestamp"],o=e.name==="appinfo"?"string":"number";for(let l of r)if(typeof t[l]!==o||o==="number"&&!Number.isFinite(t[l]))throw new TypeError(`Invalid ${e.name}.${l} from device provider`);let i=e.cachedValue;if(e.name==="location"&&i&&t.timestamp<i.getItem("timestamp")){this.attributes(e,{status:"success",error:null});return}let a=new E;for(let l of r)a.setItem(l,t[l]);e._lastUpdate=Date.now(),e.failed=!1,e.received++;let s=e.writing;e.writing=!0;try{e._node.setValue(a,!0,{status:"success",error:null},!0,!1)}finally{e.writing=s}}failure(e,t){e.failed=!0,this.attributes(e,ne(t))}reconcile(){let e=this.resolvers.get("location");if(e._node.attr.enabled){if(this.monitor)return;let t={stop:null,controller:new AbortController};this.monitor=t,t.start=Promise.resolve(this.cleanup).then(()=>this.disposed||this.monitor!==t?null:(this.requireCapability("location"),this.provider.startLocationUpdates((r,o)=>{if(!(this.disposed||this.monitor!==t))if(o)this.failure(e,o);else try{this.accept(e,r)}catch(i){this.failure(e,i)}},t.controller.signal))),t.start.then(r=>{r===null||this.disposed||this.monitor!==t||(t.stop=r,this.attributes(e,{watching:!0}))}).catch(r=>{!this.disposed&&this.monitor===t&&(this.attributes(e,{watching:!1}),this.failure(e,r))}),this.attributes(e,{status:"pending",error:null})}else if(this.monitor){let t=this.monitor;this.monitor=null,t.controller.abort(),this.retiring=t,this.cleanup=t.start.then(r=>r===null?void 0:r(),()=>{}).then(()=>{if(this.retiring===t&&(this.retiring=null),!this.disposed){let r={watching:!1};!this.monitor&&!e.request&&e._node.attr.status==="pending"&&Object.assign(r,{status:"cancelled",error:null}),this.attributes(e,r)}}),this.cleanup.catch(r=>{this.disposed||this.failure(e,r)})}}async openDatabase(e){if(this.assertLive(),!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(e)||typeof e!="string")throw new TypeError("Invalid database name");if(this.#e)throw new Error("This page already owns a database connection");let t=this.gramlot.data.getNode("_gramlot.device.database"),r=(i,a=null)=>{this.disposed||t.setAttr({status:i,error:a},!0,!0,!1)};if(!this.provider.capabilities.includes("database")){let i=Object.assign(new Error("Native database unavailable"),{code:"UNAVAILABLE"});throw r("unavailable",{code:i.code,message:i.message}),i}let o={controller:new AbortController,close:null,start:null};this.#e=o,r("pending"),o.start=this.provider.openDatabase(e,o.controller.signal);try{let i=await o.start,a=!1,s=null,l=()=>s||(a=!0,s=i.close().then(()=>{r("closed")},c=>{throw r("error",{code:"FAILED",message:c.message}),c}).finally(()=>{this.#e===o&&(this.#e=null)}),s);if(o.close=l,this.disposed||o.controller.signal.aborted)throw await l(),Object.assign(new Error("Page closed"),{code:"CANCELLED"});let u=async(c,d,f)=>{if(this.assertLive(),a)throw new Error("Database connection is closed");r("pending");try{let h=await i[c](d,f);return r("success"),h}catch(h){throw r("error",{code:"FAILED",message:h.message}),h}};return r("success"),{query:(c,d=[])=>u("query",c,d),execute:(c,d=[])=>u("execute",c,d),close:l}}catch(i){throw this.#e===o&&(this.#e=null),this.disposed||t.setAttr(ne(i),!0,!0,!1),i}}dispose(){if(this.disposed)return;this.disposed=!0;let e=this.#e;e?.controller.abort(),e&&(this.cleanup=Promise.all([this.cleanup,e.start.then(()=>e.close?.(),()=>{})]).then(()=>{}));let t=[...this.#s.values()].map(c=>{let d=c.stream;return c.stream=null,d?.controller.abort(),d?d.start.then(f=>f(),()=>{}):c.cleanup});this.#t?.abort(),this.#t=null;let r=this.#n;this.#n=null,r?.controller.abort(),this.#i?.abort(),this.#i=null;let o=[...this.#a.values()];this.#a.clear();for(let c of o)c.controller.abort();let i=this.#h;this.#h=null,i?.controller.abort();let a=this.#p;this.#p=null,a?.controller.abort(),this.#x()?.controller.abort();let s=this.#f;this.#f=null,s?.controller.abort(),this.#o?.abort(),this.#o=null,this.#r?.abort(),this.#r=null,this.#l?.abort(),this.#l=null,this.#u?.abort(),this.#u=null;let l=this.#c;this.#c=null,l?.controller.abort(),this.gramlot.data.unsubscribe("gramlot.device",{any:!0});let u=this.monitor;if(this.monitor=null,u?.controller.abort(),u)this.cleanup=u.start.then(c=>c===null?void 0:c(),()=>{});else if(this.retiring?.stop){let c=this.retiring;this.cleanup=this.cleanup.catch(()=>c.stop())}l&&(this.cleanup=Promise.all([this.cleanup,l.start.then(c=>c(),()=>{})]).then(()=>{})),s&&(this.cleanup=Promise.all([this.cleanup,s.start.then(c=>c(),()=>{})]).then(()=>{})),i&&(this.cleanup=Promise.all([this.cleanup,i.start.then(c=>c(),()=>{})]).then(()=>{})),a&&(this.cleanup=Promise.all([this.cleanup,a.start.then(c=>c(),()=>{})]).then(()=>{})),this.cleanup=Promise.all([this.cleanup,...t,...o.map(c=>c.start.then(d=>d(),()=>{}))]).then(()=>{}),r&&(this.cleanup=Promise.all([this.cleanup,r.start.then(c=>c===null?void 0:c.dispose(),c=>{if(c?.code!=="CANCELLED")throw c})]).then(()=>{})),this.cleanup=this.cleanup.finally(()=>this.releaseProvider?.()),this.cleanup.catch(c=>{this.cleanupError=c});for(let c of this.resolvers.values())c.request=null}};var mm=2e3;function T2(n){if(!(n instanceof Date))return String(n??"");let e=n.toISOString();return e.endsWith("T00:00:00.000Z")?e.slice(0,10):e}var ji=class{constructor(e,t){this.gramlot=e,this.document=t}branch(e){let t=this.gramlot.data.getItem(e);if(!(t instanceof E))throw new Error(`gramlot.utl.inout: no data Bag at '${e}'`);return t}mailText(e){let t=[],r=(o,i)=>{for(let a of o.getNodes()){let s=i+a.label;a.value instanceof E?r(a.value,`${s}.`):t.push(`${s}: ${T2(a.value)}`)}};return r(this.branch(e),""),t.join(`
|
|
235
|
-
`)}mailtoUrl(e,t){let r=`mailto:${encodeURIComponent(t)}?subject=${encodeURIComponent(this.document.title)}&body=${encodeURIComponent(this.mailText(e))}`;if(r.length>
|
|
236
|
-
<${i}>${o.toXml()}</${i}>`,t,"application/xml")}}async copyText(e){if(typeof e!="string")throw new TypeError("gramlot.utl.inout.copyText: text must be a string");await this.document.defaultView.navigator.clipboard.writeText(e)}saveText(e,t,r){let o=this.document.defaultView,i=o.URL.createObjectURL(new o.Blob([e],{type:r}));this.open(i,t),o.setTimeout(()=>o.URL.revokeObjectURL(i),1e3)}open(e,t=null){let r=this.document.createElement("a");r.href=e,t!==null&&(r.download=t),r.click()}};var qi=class extends Ke{constructor(e,t){super(e),this.inout=new ji(e,t)}};var Ui=class{#e;#t;constructor({pageId:e,uploadUrl:t=null,rpcUrl:r="/gramlot/rpc",closeUrl:o="/gramlot/close",rootId:i="gramlot-root",capabilities:a=[],element:s=null,document:l=s?.ownerDocument??globalThis.document,transport:u=null,collections:c=[],locale:d=null,timeZone:f=null,devices:h=[],serverAdapter:p=new lr,nameSyntax:m=null,websocketUrl:b=null}={}){this.#t=[ms,...c.filter(_=>_ instanceof Tr)],this.registerDocument(l),this.commands=new Oo,this.pageId=e,this.uploadUrl=t;let w=d==null||f==null?l.defaultView.Intl.DateTimeFormat().resolvedOptions():null;this.devices=Object.freeze([...h]),this.locale=d??w.locale,this.timeZone=f??w.timeZone,Object.defineProperty(this,"_subscriptions",{value:new Ws(this)}),this.capabilities=Object.freeze([...a]),this.serverAdapter=p,this.src=new Pi(this,{collections:c,destination:s??l.getElementById(i),subscriptions:this._subscriptions,nameSyntax:m===null?_i:on.fromJSON(m)}),this.#e=Io.install({document:l,root:this.src.renderer.destination}),this.data=this.src.builder.data,this.dvc=new Fi(this),this.dom=new Li(this),this.utl=new qi(this,l),this.state="ready",this.abort=new AbortController,Object.defineProperty(this,"_frames",{value:new is(this,l)}),b!==null&&(this._pageStore=new os(this,b,l)),this.rpc=new wi(this,{rpcUrl:r,closeUrl:o,document:l,transport:u}),this._frames.connect(),this.rpc.transport&&(this.pagehide=_=>{_.persisted||this.dispose()},l.defaultView.addEventListener("pagehide",this.pagehide),this.window=l.defaultView)}publish(e,t={}){return this._subscriptions.publish(e,t)}registerDocument(e){for(let t of this.#t)t.register(e.defaultView)}getCollection(e){return this.#t.find(t=>t.name===e)}subscribe(e,t){return this._subscriptions.subscribe(e,t)}unsubscribe(e){this._subscriptions.unsubscribe(e)}format(e,t){return fs(e,t,{locale:this.locale,timeZone:this.timeZone})}start(){return this.state==="disposed"?Promise.reject(new Error("Gramlot is disposed")):this.rpc.transport?this.loading?this.loading:this.state==="started"?Promise.resolve(this):(this.state="loading",this.loading=this.loadMain().finally(()=>{this.loading=null}),this.loading):Promise.reject(new Error("This Gramlot instance has no server transport"))}async loadMain(){let e;try{e=await this.rpc.callEnvelope("source","main")}catch(t){throw this.state==="disposed"?new Error("Gramlot was disposed during main",{cause:t}):(this.state="failed",t)}if(this.state==="disposed")throw new Error("Gramlot was disposed during main");try{return this.src.mountMainSource(e.value,e.data)}catch(t){throw this.state!=="disposed"&&(this.state="failed"),t}}dispose(){if(this.state!=="disposed"){this.state="disposed",this.dvc.dispose(),this.#e.dispose(),this._subscriptions.dispose(),this.pagehide&&this.window.removeEventListener("pagehide",this.pagehide),this.abort.abort();try{try{this.src.binding.dispose()}finally{this.src.renderer.dispose()}}finally{if(this._pageStore?.close(),this._frames.dispose(),this.rpc.transport)try{this.rpc.transport.close(this.pageId)}finally{this.rpc.transport.dispose()}}}}};var bc=class{constructor({config:e,resources:t,document:r=globalThis.document}){this.config=e,this.resources=t,this.document=r,this.serverAdapter=new lr}async run(){let{config:e,resources:t,document:r}=this,o=r.defaultView;t.serverAdapter!==void 0&&(this.serverAdapter=await this.loadServerAdapter(t.serverAdapter));let i=!1,a,s,l=[],u=new Promise(d=>{a=d}),c=d=>{if(!(d.persisted||i)){i=!0;try{this.closePage()}finally{a(null)}}};o.addEventListener("pagehide",c);try{let d=t.css.map(_=>new Promise((y,x)=>{let S=r.createElement("link");S.rel="stylesheet",S.href=_;let k=()=>{S.removeEventListener("load",N),S.removeEventListener("error",O)};l.push(k);let N=()=>{k(),y()},O=()=>{k(),x(new Error(`${_}: stylesheet load failed`))};S.addEventListener("load",N),S.addEventListener("error",O),r.head.append(S)})),f=t.js.map(async({url:_,group:y})=>{try{return{logicClass:(await import(new URL(_,r.baseURI).href)).Logic,group:y,resource:_}}catch(x){throw new Error(`${_}: import failed: ${x.message}`,{cause:x})}}),h=new Set,p=(t.collections??[]).map(async _=>{if(!_||typeof _!="object"||Object.keys(_).sort().join(",")!=="buildId,name,url"||typeof _.name!="string"||typeof _.url!="string"||typeof _.buildId!="string"||!/^sha256:[0-9a-f]{64}$/.test(_.buildId)||h.has(_.name))throw new TypeError("Invalid or duplicate collection bootstrap record");h.add(_.name);let{name:y,url:x,buildId:S}=_,k;try{k=await import(new URL(x,r.baseURI).href)}catch(N){throw new Error(`${y}: collection import failed: ${N.message}`,{cause:N})}if(k.default?.name!==y||k.buildId!==S)throw new Error(`${y}: collection identity mismatch; expected ${S}, received ${k.buildId}`);return k.default}),m=await Promise.race([Promise.all([Promise.all(d),Promise.all(f),Promise.all(p)]),u]);if(i)return null;let[,b,w]=m;_o.check(b);for(let _ of w)_.register(o);s=new Ui({...e,document:r,serverAdapter:this.serverAdapter,collections:[...e.collections??[],...w]}),o.removeEventListener("pagehide",c);for(let _ of w)_.registerCommands(s);for(let{logicClass:_,group:y,resource:x}of b)s.src.logicRegistry.register(_,{group:y,resource:x});return o.gramlot=s,await s.start(),s}catch(d){throw s?s.dispose():i||this.closePage(),d}finally{for(let d of l)d();o.removeEventListener("pagehide",c)}}async loadServerAdapter(e){let t;try{t=await import(new URL(e,this.document.baseURI).href)}catch(r){throw new Error(`${e}: server adapter import failed: ${r.message}`,{cause:r})}return new t.default}closePage(){let e=this.serverAdapter.createTransport({...this.config,document:this.document});try{e.close(this.config.pageId)}finally{e.dispose()}}};var Xs=Symbol("gramlot.source"),Zs=Symbol("gramlot.endpoint"),Vi=Symbol("gramlot.upload"),A2=new Map([[Xs,"registerSource"],[Zs,"registerEndpoint"],[Vi,"registerUpload"]]);function wc(n,e,t,r){let o=A2.get(t);if(e==="main")throw new TypeError(`${o} cannot declare main`);let i=Object.getOwnPropertyDescriptor(n.prototype,e)?.value;if(typeof i!="function")throw new TypeError(`${o} requires an own method of ${n.name}: ${String(e)}`);if(i[t])throw new TypeError(`${t===Xs?"Source method":t===Zs?"Endpoint":"Upload operation"} already registered: ${e}`);if([Xs,Zs,Vi].some(a=>i[a])){let a=t!==Vi&&!i[Vi]?`${e} is declared both as Source method and endpoint`:`${e} has conflicting declarations`;throw new TypeError(a)}i[t]={auth:r}}var Ks=class{static registerSource(e,{auth:t=null}={}){wc(this,e,Xs,t)}static registerEndpoint(e,{auth:t=null}={}){wc(this,e,Zs,t)}static registerUpload(e,{auth:t=null}={}){wc(this,e,Vi,t)}},zi=class extends Ks{static gramlots=[];static title="Gramlot";static devices=[];static locale=null;static timeZone=null;static installable=!1;static appIcon=null;manifest({baseUrl:e="./"}={}){let{title:t,appIcon:r}=this.constructor;if(typeof r!="string"||!r)throw new TypeError("An installable Page needs appIcon");return{id:e,name:t,short_name:t,start_url:e,scope:e,display:"standalone",icons:[{src:e+r.replace(/^\/+/,""),sizes:"512x512",type:"image/png"}]}}static css=[];static css_theme=null;static css_requires="";static js_requires="";static sourceBuilder=Oe;main(e){throw new Error("Page.main(root) must be implemented")}};var yo=class extends zi{static shellId="frame";static datapath=null;main(e){let t=e.div({id:this.constructor.shellId,datapath:this.constructor.datapath,class:"frame-page",height:"100vh",display:"flex",flex_direction:"column",min_height:0}),r=t.borderContainer({node_label:"frame",height:"100%",flex:"1",min_height:0});for(let o of["top","bottom","left","right","center"])if(this[o]!==void 0){let i=r.contentPane({region:o,node_label:o});this[o](i)}this.behavior(t)}center(e){}behavior(e){}};var Hi=class extends yo{static title="Application";static shellId="index";static datapath="index";static navigation=null;main(e){let{navigation:t,datapath:r}=this.constructor;if(!(t instanceof E))throw new TypeError("IndexPage.navigation must be a Bag");e.dataSetter({destination_path:`${r}.navigation`,value:t}),e.dataSetter({destination_path:`${r}.navigationSelection`,value:null}),e.dataSetter({destination_path:`${r}.active`,value:null}),e.dataSetter({destination_path:`${r}.opened`,value:new E}),super.main(e)}left(e){e.setAttr({width:"240px",splitter:!0,drawer:!0,drawer_label:"Navigation"}),e.tree({node_label:"tree",storepath:".navigation",labelAttribute:"title",hideValues:!0,selectedPath:"^.navigationSelection"})}center(e){e.tabContainer({node_label:"tabs",height:"100%",selectedPage:"^.active"})}behavior(e){e.dataController({func:"indexMount",_onStart:!0})}index_panel(e,{selection:t}){this.panel(e,t.getNode("#0"))}panel(e,t){e.iframe({src:t.attr.url,title:t.attr.title??t.label,width:"100%",height:"100%",border:0})}};Hi.registerSource("index_panel");function _c(n,e,t=()=>{},r=()=>{},{state:o=e.getRelativeData("."),createEntry:i=null,onLoad:a=()=>{}}={}){let s=o.getItem("navigation");if(!(s instanceof E))throw new TypeError("IndexPage navigation must be a Bag");let l=e.value.getNode("frame.center.tabs"),u=e.builder,c=new Map,d={entries:c,disposed:!1,selecting:!1,sequence:0,requested:null};Object.defineProperty(e,"indexContext",{value:d,configurable:!0});let f=o.getItem("opened");for(let k of f.getNodes()){let{url:N,path:O,title:$}=k.attr,ee=l.value.getNode(k.label),W={url:N,path:O,title:$,pane:ee,node:s.getNode(O),loading:!1};r(W),c.set(N,W),d.sequence++}let h=(k,N,O)=>{try{a(k.url,N,O)}catch($){n.binding.reportError($,"Page load callback failed")}},p=(k,N,O)=>{k.loading&&(k.loading=!1,h(k,N,O))},m=k=>{if(!d.disposed){d.selecting=!0;try{o.setItem("active",k.url),o.setItem("navigationSelection",k.path),t(c,k.url)}finally{d.selecting=!1}}};function b(k){w(k).catch(N=>{d.disposed||n.binding.reportError(N,"Page could not be opened")})}async function w(k){let N=s.getNode(k);if(!N)throw new Error(`Unknown index navigation path: ${k}`);let O=N.attr.url;if(O==null)return;if(typeof O!="string"||!O)throw new TypeError("IndexPage URL must be nonempty text");d.requested=O;let $=c.get(O);if($){$.path=k,m($);return}for(;l.value!==null&&l.value.getNode(`page${d.sequence}`);)d.sequence++;let ee=ie(u.wrapSource(l).contentPane({node_label:`page${d.sequence++}`,title:N.attr.title??N.label,pageName:O,height:"100%",closable:!0})),W=o.getItem("active");$={url:O,path:k,node:N,pane:ee,title:N.attr.title??N.label,loading:!0},c.set(O,$);try{if(h($,"loading"),d.disposed||c.get(O)!==$||(m($),d.disposed||c.get(O)!==$))return;if(i)await i($);else{let se=new E;if(se.setItem(N.label,null,{...N.attr}),!await n.binding.gramlot.src.remoteSource(ee,"index_panel",{selection:se}))throw new Error("Panel loading was cancelled")}if(d.disposed||c.get(O)!==$)return;f.setItem(ee.label,null,{url:O,path:$.path,title:$.title}),r($)}catch(se){if(d.disposed||c.get(O)!==$)return;try{if(n.binding.reportError(se,"Page could not be opened"),c.delete(O),f.getNode(ee.label)&&f.popNode(ee.label),ee.parentBag&&ee.parentBag.popNode(ee.label),!d.disposed&&d.requested===O){let me=c.get(W);if(d.requested=me?.url??null,me)m(me);else{d.selecting=!0;try{o.setItem("active",null),o.setItem("navigationSelection",null),t(c,null)}finally{d.selecting=!1}}}}finally{p($,"error",se)}return}d.disposed||c.get(O)!==$||(p($,"ready"),!d.disposed&&c.get(O)===$&&d.requested===O&&m($))}let _=`${e.getAttr("id")}-page-close`;e.value.subscribe(_,{any:k=>{if(k.evt!=="del")return;let N=[...c.values()].find(ee=>ee.pane===k.node);if(!N)return;let{url:O,pane:$}=N;if(!(d.disposed||n.disposed||c.get(O)!==N)){c.delete(O),f.getNode($.label)&&f.popNode($.label);try{if(o.getItem("active")===O){let ee=[...c.values()].at(-1);if(d.requested=ee?.url??null,ee)m(ee);else{d.selecting=!0;try{o.setItem("active",null),o.setItem("navigationSelection",null),t(c,null)}finally{d.selecting=!1}}}else t(c,o.getItem("active"))}finally{p(N,"cancelled")}}}});let y=`${e.getAttr("id")}-selection`;o.subscribe(y,{any:k=>{if(!(d.selecting||d.disposed)){if(k.node===o.getNode("navigationSelection")){let N=o.getItem("navigationSelection");N!==null&&b(N)}else if(k.node===o.getNode("active")){let N=c.get(o.getItem("active"));N&&(d.requested=N.url,m(N))}}}});let x=()=>{if(!d.disposed){d.disposed=!0,o.unsubscribe(y,{any:!0}),e.value.unsubscribe(_,{any:!0});for(let k of c.values())k.loading&&(k.pane.parentBag&&k.pane.parentBag.popNode(k.pane.label),p(k,"cancelled"));c.clear(),e.indexContext===d&&delete e.indexContext}};d.dispose=x,n.onDispose(e,x);let S=c.get(o.getItem("active"));return S?m(S):o.getItem("navigationSelection")!==null&&b(o.getItem("navigationSelection")),d}var Js=class{indexMount(e){_c(this.page.src.renderer,e.parentNode)}};function Qs(n,{datapath:e,value:t,language:r="text",height:o="420px",...i}){if(!e)throw new TypeError("codeMirrorWithOptions requires datapath");let a=n.borderContainer({datapath:e,height:o,class:"gramlot-editor-options"}),s={language:r,indentUnit:4,fontSize:14,fontFamily:"monospace",lineNumbers:!0,lineWrapping:!0,folding:!0,bracketMatching:!0,autoCloseBrackets:!0,autoIndent:!0,autocompletion:!0,highlightActiveLine:!0,highlightSelectionMatches:!0};for(let[d,f]of Object.entries(s))a.dataSetter({destination_path:`.settings.${d}`,value:f});let l=a.contentPane({region:"right",width:"250px",drawer:"close",drawer_label:"Options",drawer_icon:"\u2699",drawer_minimize:!1,padding:"12px",overflow:"auto",class:"gramlot-editor-settings"});l.h3("Editor options"),l.filteringSelect({value:"^.settings.language",lbl:"Language",values:"text:Plain text,python:Python,javascript:JavaScript,typescript:TypeScript,json:JSON,html:HTML,css:CSS,xml:XML,markdown:Markdown,sql:SQL,typst:Typst"}),l.numberTextBox({value:"^.settings.indentUnit",lbl:"Indent spaces",min:1,max:16,dtype:"L",validate_notnull:!0}),l.numberTextBox({value:"^.settings.fontSize",lbl:"Font size",min:8,max:48,dtype:"L",validate_notnull:!0}),l.textbox({value:"^.settings.fontFamily",lbl:"Font family"});let u={lineNumbers:"Line numbers",lineWrapping:"Wrap lines",folding:"Code folding",bracketMatching:"Match brackets",autoCloseBrackets:"Close brackets and quotes",autoIndent:"Automatic indentation",autocompletion:"Local completion",highlightActiveLine:"Highlight current line",highlightSelectionMatches:"Highlight matching selections"};for(let[d,f]of Object.entries(u))l.checkbox({value:`^.settings.${d}`,label:f,display:"block",margin_top:"8px"});return a.contentPane({region:"center",min_height:0}).codeMirror({...i,value:t,height:"100%",...Object.fromEntries(Object.keys(s).map(d=>[d,`^.settings.${d}`]))}),a}var Gi=class n extends At{static internalParams=new Set([...At.internalParams,"gramlot","method","params","onError"]);#e=!1;#t=null;constructor({gramlot:e,root:t,path:r="",onError:o}){super({cacheTime:-1,onError:o}),this.gramlot=e,this.method="directory_tree",this.params={root:t,path:r},this.children=new Set}get closed(){return this.#e}startLoad(e){if(this.loading)return this.loading;let t=new AbortController;return this.#t=t,e({controller:t,method:this.method,params:this.params,ignored:!1})}async loadAsync({controller:e,method:t,params:r}){let{signal:o}=e,i,a=new Promise((s,l)=>{i=()=>l(o.reason),o.addEventListener("abort",i,{once:!0})});try{let s=await Promise.race([this.gramlot.rpc.call("data",t,r,{signal:o}),a]);if(o.aborted)throw o.reason;return s}finally{o.removeEventListener("abort",i),this.#t===e&&(this.#t=null)}}prepareValue(e){if(!(e instanceof E))throw new TypeError("directory_tree must return a Bag");for(let t of this.children)t.abort();this.children.clear();for(let t of e.getNodes())if(t.attr.is_directory){let r=new n({gramlot:this.gramlot,root:this.params.root,path:t.attr.path,onError:this.onError});this.children.add(r),e.setResolver(t.label,r)}return e}abort(){this.#e=!0,this.#t?.abort();for(let e of this.children)e.abort();this.children.clear()}},Wi=class{constructor(e,t){this.gramlot=e,this.source=t,this.request=null,this.resolver=null,this.disposed=!1}get state(){return this.source.getRelativeData(".")}async open(e){this.request?.abort();let t=this.request=new AbortController;this.state.setItem("status","Opening directory\u2026");try{let r=await this.gramlot.rpc.call("data","workspace_open",{root:e},{signal:t.signal});if(this.disposed||t.signal.aborted)return null;let o=new Gi({gramlot:this.gramlot,root:r.root,onError:a=>this.state.setItem("status",a.message)}),i=o.prepareValue(r.entries);return this.resolver?.abort(),this.resolver=o,this.state.setItem("selectedPath",null),this.state.setItem("store",i),this.state.setItem("writable",r.writable),this.state.setItem("root",r.root),this.state.setItem("status",""),r.root}catch(r){return!this.disposed&&!t.signal.aborted&&this.state.setItem("status",r.message),null}finally{this.request===t&&(this.request=null)}}dispose(){this.disposed=!0,this.request?.abort(),this.resolver?.abort()}},wn=class{fileSystemMount(e){let t=e.parentNode,r=new Wi(this.page,t);Object.defineProperty(t,"fileSystemController",{value:r,configurable:!0}),this.page.src.renderer.onDispose(t,()=>r.dispose())}fileSystemOpen(e,{root:t}){if(t)return e.parentNode.fileSystemController.open(t)}};function gm(n,{datapath:e,...t}){let r=n.div({datapath:e,class:"gramlot-filesystem",...t});return r.dataSetter({destination_path:".store",value:new E}),r.dataSetter({destination_path:".root",value:null}),r.dataSetter({destination_path:".requestedRoot",value:null}),r.dataSetter({destination_path:".selectedPath",value:null}),r.dataSetter({destination_path:".status",value:""}),r.dataController({func:"fileSystemMount",_onBuilt:!0}),r.dataController({func:"fileSystemOpen",root:"^.requestedRoot"}),r.tree({storepath:".store",selectedPath:"^.selectedPath",labelAttribute:"caption",hideValues:!0,class:"gramlot-filesystem-tree"}),r.div("^.status",{role:"status",class:"gramlot-filesystem-status"}),r}var D2=(n,e)=>"d_"+[...new TextEncoder().encode(JSON.stringify([n,e]))].map(t=>t.toString(16).padStart(2,"0")).join(""),el=class{constructor(e,t){this.gramlot=e,this.source=t,this.pending=new Map,this.disposed=!1}get state(){return this.source.getRelativeData(".")}get documents(){return this.state.getItem("documents")}async open(e,t){if(!/\.(?:py|js|mjs|ts|json|html|css|xml|md|markdown|sql|typ|txt|png|jpg|jpeg|webp)$/i.test(t))return null;let r=D2(e,t),o=this.documents.getNodes().find(s=>!s.value.getItem("isNew")&&s.value.getItem("root")===e&&s.value.getItem("path")===t);if(o)return o.label;if(this.pending.has(r))return this.pending.get(r).promise;let i=new AbortController,a=this.gramlot.rpc.call("data","document_read",{root:e,path:t},{signal:i.signal}).then(s=>{if(this.disposed||i.signal.aborted)return null;let l=new E,u=s.language==="image"?s.content.toTytx():s.content;for(let[c,d]of Object.entries({...s,content:u,root:e,saved:u,busy:!1}))l.setItem(c,d);if(s.language==="image"){let c=s.content;l.setItem("annotations",c),c.subscribe("ide-annotations",{any:()=>l.setItem("content",c.toTytx())})}return this.documents.setItem(r,l),r}).finally(()=>this.pending.delete(r));return this.pending.set(r,{request:i,promise:a}),a}newDocument(e,t,r=""){let o=`new_${K()}`,i=new E;for(let[a,s]of Object.entries({language:e,root:r,path:`Untitled${t}`,content:"",saved:"",writable:!0,busy:!1,isNew:!0,createHidden:!0,saveRoot:r,savePath:`Untitled${t}`}))i.setItem(a,s);return this.documents.setItem(o,i),o}async create(e){let t=this.documents.getItem(e);if(!t||!t.getItem("isNew")||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("saveRoot"),o=t.getItem("savePath");if(t.getItem("path").endsWith(".typ.py")!==o.endsWith(".typ.py"))throw new Error("The .typ.py extension is required for the Typst Python recipe document type.");let i=t.getItem("content"),a=new AbortController;t.setItem("busy",!0);let s=this.gramlot.rpc.call("data","document_create",{root:r,path:o,content:i},{signal:a.signal}).then(l=>this.disposed||a.signal.aborted?!1:(t.setItem("root",l.root),t.setItem("path",l.path),t.setItem("revision",l.revision),t.setItem("saved",i),t.setItem("isNew",!1),t.setItem("createHidden",!0),!0)).finally(()=>{this.pending.delete(e),this.disposed||t.setItem("busy",!1)});return this.pending.set(e,{request:a,promise:s}),s}invalidateRecipe(e){let t=this.documents.getItem(e);t.getItem("path").endsWith(".typ.py")&&(t.getItem("rendering")&&this.pending.get(e)?.request.abort(),t.setItem("previewHidden",!0),t.setItem("typstSource",""),t.setItem("renderStatus","Generate preview to render the current Python recipe."))}async renderRecipe(e){let t=this.documents.getItem(e);if(!t||!t.getItem("path").endsWith(".typ.py")||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("content"),o=new AbortController;t.setItem("busy",!0),t.setItem("rendering",!0),t.setItem("previewHidden",!0),t.setItem("typstSource",""),t.setItem("renderStatus","Generating Typst on the server\u2026");let i=this.gramlot.rpc.call("data","document_render_typst",{content:r},{signal:o.signal}).then(a=>this.disposed||o.signal.aborted||t.getItem("content")!==r?!1:(t.setItem("typstSource",a.source),t.setItem("previewHidden",!1),t.setItem("renderStatus","Typst generated from the current recipe."),!0)).catch(a=>(!this.disposed&&!o.signal.aborted&&t.setItem("renderStatus",a.message),!1)).finally(()=>{this.pending.delete(e),this.disposed||(t.setItem("rendering",!1),t.setItem("busy",!1))});return this.pending.set(e,{request:o,promise:i}),i}dirty(e){let t=this.documents.getItem(e);return t&&t.getItem("content")!==t.getItem("saved")}async save(e){let t=this.documents.getItem(e);if(!t||t.getItem("isNew")||!this.dirty(e)||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("content"),o=new AbortController;t.setItem("busy",!0);let i=t.getItem("language")==="image",a=i?t.getItem("annotationPath"):t.getItem("path"),s=i&&t.getItem("revision")===null,l=this.gramlot.rpc.call("data",s?"document_create":"document_save",{root:t.getItem("root"),path:a,content:i?E.fromTytx(r):r,...s?{}:{revision:t.getItem("revision")}},{signal:o.signal}).then(u=>this.disposed||o.signal.aborted?!1:(t.setItem("revision",u.revision),t.setItem("saved",r),!0)).finally(()=>{this.pending.delete(e),this.disposed||t.setItem("busy",!1)});return this.pending.set(e,{request:o,promise:l}),l}revert(e){let t=this.documents.getItem(e);return!t||!this.dirty(e)||this.pending.has(e)?!1:(t.setItem("content",t.getItem("saved")),t.getItem("language")==="image"&&(t.getItem("annotations").replace(E.fromTytx(t.getItem("saved"))),t.setItem("content",t.getItem("saved"))),!0)}canClose(e,t=!1){return!this.pending.has(e)&&(t||!this.dirty(e))}close(e,t=!1){return this.canClose(e,t)?(this.documents.popNode(e),this.state.getItem("active")===e&&this.state.setItem("active",this.documents.getNodes()[0]?.label??null),!0):!1}dispose(){this.disposed=!0;for(let{request:e}of this.pending.values())e.abort()}},tl=class{constructor(e){this.storage=e,this.key="gramlot.ide.recentWorkspaces"}read(){let e=this.storage.getItem(this.key),t=e===null?[]:JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"||!r))throw new TypeError("Invalid recent workspace preference");return t.slice(0,6)}remember(e){let t=[e,...this.read().filter(r=>r!==e)].slice(0,6);return this.storage.setItem(this.key,JSON.stringify(t)),t}choices(e=this.read()){let t=new E;return e.forEach((r,o)=>t.setItem(`r${o}`,r,{caption:r})),t}};function at(n){for(let e=n;e;e=e.parentNode){let t=e.ideContext;if(t)return t}throw new Error("IDE operation requires a node inside a mounted IDE")}var rl=class{fileSystemMount(e){return wn.prototype.fileSystemMount.call(this,e)}fileSystemOpen(e,t){return wn.prototype.fileSystemOpen.call(this,e,t)}ideMount(e){let t=e.parentNode,r={scope:t,documents:new el(this.page,t),requested:0,editorPrefix:`ide_${K()}`,recent:new tl(this.page.src.renderer.destination.ownerDocument.defaultView.sessionStorage)};Object.defineProperty(t,"ideContext",{value:r,configurable:!0});let{documents:o,recent:i}=r,a=t.getRelativeData("."),s=i.read();a.setItem("recent",i.choices(s)),a.setItem("workspace",s[0]??"");let l=a.getItem("browser");l.subscribe("ide-browser",{any:c=>{if(c.node===l.getNode("root")){let d=l.getItem("root");a.setItem("workspace",d),a.setItem("recent",i.choices(i.remember(d))),a.setItem("status",`Workspace: ${d}`)}else if(c.node===l.getNode("selectedPath")){let d=l.getItem("selectedPath"),f=d===null?null:l.getItem("store").getNode(d);f&&!f.attr.is_directory&&this.ideOpenDocument(t,l.getItem("root"),f.attr.path)}}});let u=o.documents;u.subscribe("ide-documents",{any:c=>{if(["content","saved","busy","writable","view","isNew","path","root"].includes(c.node.label))for(let d of t.value.getNode("frame.center.tabs").value?.getNodes()??[]){let f=d.getAttr("documentKey"),h=o.documents.getItem(f);h&&(c.node===h.getNode("content")&&o.invalidateRecipe(f),this.ideDocumentState(t,f),d.setAttr({title:`${o.dirty(f)?"\u25CF ":""}${h.getItem("path")}`}))}}}),this.page.src.renderer.onDispose(r.scope,()=>{l.unsubscribe("ide-browser",{any:!0}),u.unsubscribe("ide-documents",{any:!0}),o.dispose()})}ideOpenWorkspace(e){let r=at(e).scope.getRelativeData("."),o=r.getItem("workspace");o&&o!==r.getItem("browser.root")&&r.setItem("browser.requestedRoot",o)}async ideUploadCompleted(e,{result:t}){let r=at(e),o=r.scope.getRelativeData(".");if(o.getItem("browser.root")!==t.root)return;o.setItem("upload.open",!1);let i=r.scope.value.getNode("frame.left.browser").fileSystemController;if(i.request)return;await i.open(t.root)===t.root&&!r.documents.disposed&&o.getItem("browser.root")===t.root&&await this.ideOpenDocument(r.scope,t.root,t.path)}ideDocumentState(e,t){let r=at(e),{documents:o}=r,i=o.documents.getItem(t),a=!o.dirty(t)&&!i.getItem("isNew")||i.getItem("busy");i.setItem("saveDisabled",!!(a||!i.getItem("writable"))),i.setItem("revertDisabled",!!(!o.dirty(t)||i.getItem("busy"))),i.setItem("displayPath",i.getItem("isNew")?i.getItem("path"):`${i.getItem("root")}/${i.getItem("path")}`),i.setItem("pdfFilename",i.getItem("path").split("/").at(-1).replace(/\.typ(?:\.py)?$/i,".pdf")),i.setItem("renderDisabled",!!(i.getItem("busy")||!i.getItem("writable"))),this.ideHistoryState(i)}async ideOpenDocument(e,t,r){let o=at(e),{documents:i}=o,a=o.scope.getRelativeData("."),s=++o.requested;try{let l=await i.open(t,r);if(l===null||i.disposed)return;this.ideShowDocument(e,l),s===o.requested&&(a.setItem("active",l),a.setItem("status",`${r}${i.documents.getItem(l).getItem("writable")?"":" (draft only \u2014 Remote Edit is disabled)"}`))}catch(l){i.disposed||a.setItem("status",l.message)}}ideNew(e){let t=at(e),{documents:r}=t,o=t.scope.getRelativeData("."),i=o.getItem("newType"),a=i==="typstRecipe"?"python":i,s={typstRecipe:".typ.py",typst:".typ",markdown:".md",html:".html",python:".py",javascript:".js",typescript:".ts",json:".json",css:".css",sql:".sql",xml:".xml",text:".txt"},l=r.newDocument(a,s[i],o.getItem("workspace"));r.documents.getItem(l).setItem("writable",o.getItem("browser.writable")===!0),++t.requested,this.ideShowDocument(e,l),o.setItem("active",l),o.setItem("status","New document. Choose directory and name when saving.")}ideShowDocument(e,t){let r=at(e),{documents:o}=r,a=o.documents.getItem(t).getItem("path"),s=r.scope.value.getNode("frame.center.tabs");if(!s.value?.getNode(t)){let l=o.documents.getItem(t),u=a.endsWith(".typ.py");u&&o.invalidateRecipe(t),l.setItem("readonly",!1),this.ideDocumentState(e,t),l.setItem("view","code"),l.setItem("createHidden",!0),l.setItem("undoDisabled",!0),l.setItem("redoDisabled",!0);let c=ie(s.builder.wrapSource(s).contentPane({node_label:t,title:a,pageName:t,documentKey:t,closable:!0,onClose:"ideClose",height:"100%"})),d=c.builder.wrapSource(c).div({display:"flex",flex_direction:"column",height:"100%"}),f=d.div({datapath:`.documents.${t}`,display:"flex",align_items:"center",gap:"6px",padding:"4px 12px",height:"40px",flex_shrink:0,box_sizing:"border-box",class:"gramlot-ide-document-toolbar",role:"toolbar","aria-label":`Commands for ${a}`});for(let[m,b,w,_]of[["save","M5 3h12l4 4v14H3V3h2 M7 3v6h10V3 M7 21v-8h10v8","Save","ideSave"],["revert","M3 10a9 9 0 1 1 2 8 M3 4v6h6 M12 7v5l3 2","Revert to saved","ideRevert"],["undo","M9 5 3 11l6 6 M3 11h12a6 6 0 0 1 6 6v2","Undo","ideUndo"],["redo","m15 5 6 6-6 6 M21 11H9a6 6 0 0 0-6 6v2","Redo","ideRedo"]]){let y=f.button({title:w,"aria-label":w,disabled:`^.${m}Disabled`,class:`button--quiet gramlot-ide-${m}`});y.svg({viewBox:"0 0 24 24",width:18,height:18,fill:"none",stroke:"currentColor",stroke_width:1.7,stroke_linecap:"round",stroke_linejoin:"round","aria-hidden":"true"}).path({d:b}),y.dataController({func:_,documentKey:t})}u&&f.button("Generate preview",{disabled:"^.renderDisabled",class:"button--quiet"}).dataController({func:"ideRenderRecipe",documentKey:t}),f.div("^.displayPath",{class:"gramlot-ide-document-path",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap",min_width:0,flex:"1"});let h=d.div({datapath:`.documents.${t}`,hidden:"^.createHidden",padding:"8px 12px",display:"flex",gap:"8px",align_items:"end",flex_shrink:0});h.textbox({value:"^.saveRoot",lbl:"Directory",flex:"1",disabled:"^.busy"}),h.textbox({value:"^.savePath",lbl:"File name",flex:"1",disabled:"^.busy"}),h.button("Create file",{disabled:"^.busy"}).dataController({func:"ideCreate",documentKey:t}),h.button("Cancel",{disabled:"^.busy",class:"button--quiet"}).dataController({func:"ideCancelCreate",documentKey:t});let p=d.div({flex:"1",min_height:0});if(l.getItem("language")==="image")p.drawingPane({image:`^.documents.${t}.image`,annotations:`^.documents.${t}.annotations`,height:"100%"});else{let m=l.getItem("language")==="html",b=l.getItem("language")==="markdown",w=m||b,_=l.getItem("language")==="typst",y=w||_||u,x=y?p.tabContainer({height:"100%",selectedPage:`^.documents.${t}.view`}):null,S=y?x.contentPane({title:"Code",pageName:"code",height:"100%"}):p;if(Qs(S,{datapath:`.documents.${t}`,value:"^.content",language:l.getItem("language"),height:"100%",readonly:"^.readonly",nodeId:`${r.editorPrefix}_editor_${t}`,editorView:"code",selfsubscribe_historyChanged:"ideHistoryChanged"}),d.dataController({func:"ideSave",documentKey:t,[`subscribe_${r.editorPrefix}_editor_${t}_save`]:!0}),_&&x.contentPane({title:"Preview",pageName:"preview",height:"100%"}).typstPreview({value:`^.documents.${t}.content`,filename:`^.documents.${t}.pdfFilename`,height:"100%"}),u){let k=x.contentPane({title:"Preview",pageName:"preview",height:"100%",display:"flex",flex_direction:"column"});k.div(`^.documents.${t}.renderStatus`,{role:"status",padding:"8px 12px",white_space:"pre-wrap",overflow:"auto",max_height:"30%"}),k.typstPreview({value:`^.documents.${t}.typstSource`,filename:`^.documents.${t}.pdfFilename`,hidden:`^.documents.${t}.previewHidden`,flex:"1",min_height:0}),x.contentPane({title:"Generated Typst",pageName:"generated",height:"100%"}).codeMirror({value:`^.documents.${t}.typstSource`,language:"typst",readonly:!0,height:"100%"})}if(w){let k=x.contentPane({title:"Preview",pageName:"preview",height:"100%",display:"flex",flex_direction:"column"});b&&(l.setItem("allowHtml",!1),k.checkbox({value:`^.documents.${t}.allowHtml`,label:"Allow embedded HTML",class:"gramlot-ide-allow-html",padding:"8px 12px",flex_shrink:0})),k[m?"htmlPreview":"markdownPreview"]({value:`^.documents.${t}.content`,flex:"1",min_height:0,...b?{allowHtml:`^.documents.${t}.allowHtml`}:{}}),x.contentPane({title:"Rich text",pageName:"rich",height:"100%"})[m?"htmlEditor":"markdownEditor"]({datapath:`.documents.${t}`,value:"^.content",readonly:"^.readonly",height:"100%",nodeId:`${r.editorPrefix}_rich_editor_${t}`,editorView:"rich",selfsubscribe_historyChanged:"ideHistoryChanged"}),d.dataController({func:"ideSave",documentKey:t,[`subscribe_${r.editorPrefix}_rich_editor_${t}_save`]:!0})}}}}async ideRenderRecipe(e,{documentKey:t}){let r=at(e),{documents:o}=r;o.documents.getItem(t).setItem("view","preview"),await o.renderRecipe(t)}ideCancelCreate(e,{documentKey:t}){let r=at(e),{documents:o}=r;o.documents.getItem(t).setItem("createHidden",!0)}async ideCreate(e,{documentKey:t}){let r=at(e),{documents:o}=r,i=r.scope.getRelativeData(".");i.setItem("status","Creating file\u2026");try{let a=await o.create(t);if(!o.disposed&&a){i.setItem("status","File created.");let s=i.getItem("browser");s.getItem("root")&&await r.scope.value.getNode("frame.left.browser").fileSystemController.open(s.getItem("root"))}}catch(a){o.disposed||i.setItem("status",a.message)}}async ideSave(e,{documentKey:t=null}={}){let r=at(e),{documents:o}=r,i=r.scope.getRelativeData("."),a=t??i.getItem("active");if(!a||o.documents.getItem(a).getItem("saveDisabled"))return;let s=o.documents.getItem(a);if(s.getItem("isNew")){s.setItem("createHidden",!1);return}i.setItem("status","Saving\u2026");try{let l=await o.save(a);o.disposed||i.setItem("status",l?"Saved.":"Document is read only or a request is pending.")}catch(l){o.disposed||i.setItem("status",l.message)}}ideRevert(e,{documentKey:t}){let r=at(e),{documents:o}=r,i=r.scope.getRelativeData(".");o.revert(t)&&i.setItem("status","Restored the last saved version.")}ideHistoryChanged(e,{canUndo:t,canRedo:r}){let o=e.getRelativeData("."),i=e.getAttr("editorView");o.setItem(`${i}CanUndo`,t),o.setItem(`${i}CanRedo`,r),this.ideHistoryState(o)}ideHistoryState(e){let t=e.getItem("view");e.setItem("undoDisabled",!e.getItem(`${t}CanUndo`)),e.setItem("redoDisabled",!e.getItem(`${t}CanRedo`))}ideEditor(e,t){let r=at(e),{documents:o}=r,i=o.documents.getItem(t).getItem("view")==="rich",a=this.page.src.binding.nodeIds.get(`${r.editorPrefix}_${i?"rich_":""}editor_${t}`);return this.page.src.renderer.records.get(a).element}ideUndo(e,{documentKey:t}){this.ideEditor(e,t).undo()}ideRedo(e,{documentKey:t}){this.ideEditor(e,t).redo()}ideClose(e){let t=at(e),{documents:r}=t,o=t.scope.getRelativeData("."),i=e.getAttr("documentKey");return r.canClose(i)?!0:(o.setItem("status","Save or revert your changes before closing. Pending operations must finish first."),!1)}ideClosed(e,{pageName:t}){this.ideForgetDocument(e,t)}ideForgetDocument(e,t,r=!1){let o=at(e),{documents:i}=o,a=o.scope.getRelativeData("."),s=i.documents.getItem(t),l=a.getItem("browser"),u=l.getItem("selectedPath"),c=u===null?null:l.getItem("store").getNode(u);s&&l.getItem("root")===s.getItem("root")&&c?.attr.path===s.getItem("path")&&l.setItem("selectedPath",null),i.close(t,r)}};var Rr=class extends fe{constructor({readOnly:e=!1}={}){super({cacheTime:-1,readOnly:e}),this.store=null,this.path=null,this.pending=null}bind(e,t){if(this.store!==null)throw new Error("TreeStoreResolver is already bound");this.store=e,this.path=t}load(){if(this.store===null)throw new Error("TreeStoreResolver is not bound to a store");if(this.pending!==null)return this.pending;let e=this.node,t=this.path?this.store.pathFor(e):"",r=this.store.load(t,t?e.label:null,t?{...e.attr}:{});return this.pending=r,r.finally(()=>{this.pending===r&&(this.pending=null)}).catch(()=>{}),r}};Lu(Rr,{module:"gramlot.tree_store",name:"TreeStoreResolver",encode:()=>({args:[],kwargs:{}}),decode:()=>new Rr});var Yi=class{constructor({gramlot:e,method:t,params:r={}}){if(!e||typeof t!="string"||!t)throw new TypeError("TreeStore requires a page and method");for(let o of["path","label","attributes"])if(Object.hasOwn(r,o))throw new TypeError(`TreeStore params reserves ${o}`);this.gramlot=e,this.method=t,this.params={...r},this.controller=new AbortController,this.root=null}pathFor(e){let t=[];for(;e&&e.parentBag!==this.root;)t.unshift(e.label),e=e.parentNode;if(!e||this.root===null)throw new Error("TreeStore node is outside its root");return t.unshift(e.label),t.join(".")}async load(e="",t=null,r={}){if(this.controller.signal.aborted)throw this.controller.signal.reason;let o=await this.gramlot.rpc.call("data",this.method,{...this.params,path:e,label:t,attributes:r},{signal:this.controller.signal});if(this.controller.signal.aborted)throw this.controller.signal.reason;if(!(o instanceof E))throw new TypeError("TreeStore method must return a Bag");e||(this.root=o,o.setBackref());let i=(a,s)=>{for(let l of a.getNodes()){let u=s?`${s}.${l.label}`:l.label;l.resolver instanceof Rr&&l.resolver.bind(this,u),l.staticValue instanceof E&&i(l.staticValue,u)}};return i(o,e),o}dispose(){this.controller.abort()}},nl=class{treeFavoriteActionState(e,{item:t,state:r}){let o=t.resolver!==null||t.staticValue instanceof E;if(t.getAttr("favoriteEntry")===!0)return{hidden:!1,icon:"\u2715",title:"Remove favorite"};let i=!o&&r.getNodes().some(a=>a.getAttr("fieldpath")===t.getAttr("fieldpath"));return{hidden:o,icon:i?"\u2665":"\u2661",title:i?"Remove favorite":"Add favorite"}}treeFavoritesMount(e,{favoriteKey:t}){let o=this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.getItem(t);this.setTreeFavorites(e.getRelativeData("."),o===null?[]:F(o))}setTreeFavorites(e,t){if(!Array.isArray(t))throw new TypeError("Tree favorites must be an array");let r=new E;t.forEach((o,i)=>{if(!o||typeof o.fieldpath!="string"||typeof o.path!="string"||typeof o.caption!="string"||!o.attrs||typeof o.attrs!="object")throw new TypeError("Invalid tree favorite");let a={...o.attrs};for(let s of["caption","fullcaption"])typeof a[s]=="string"&&(a[s]=a[s].replace(/(^|\.)!!(?:\[[^\]]+\])?/g,"$1"));r.setItem(`favorite_${i}`,null,{...a,favoriteEntry:!0,originalPath:o.path})}),e.setItem("favorites",r)}treeFavoriteToggle(e,{item:t,path:r,favoriteKey:o}){if(t.resolver||t.staticValue instanceof E)return;let i=t.getAttr(),a=e.getRelativeData("."),s=a.getItem("favorites").getNodes().map(c=>{let{favoriteEntry:d,originalPath:f,...h}=c.getAttr();return{fieldpath:h.fieldpath,path:f,caption:h.caption,attrs:h}}),l=s.findIndex(c=>c.fieldpath===i.fieldpath);l===-1?s.push({fieldpath:i.fieldpath,path:r,caption:i.caption,attrs:{...i}}):s.splice(l,1),this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.setItem(o,L(s)),this.setTreeFavorites(a,s)}treeStoreMount(e,{storeMethod:t,storeParams:r}){let o=e.parentNode,i=e.getRelativeData("."),a=new Yi({gramlot:this.page,method:t,params:r});this.page.src.renderer.onDispose(o,()=>a.dispose());let s=new Rr({readOnly:!0});return s.bind(a,""),i.setResolver("store",s),Promise.resolve(i.getItem("store")).then(l=>{a.controller.signal.aborted||i.setItem("store",l)})}treeInspect(e,{item:t,path:r}){let o=this.page.src.binding.bindingFor(e),i=!1,a=`tree_inspect_${K()}`,s=()=>{},l=()=>{i||(i=!0,s(),this.page.src.source.getNode(a)&&this.page.src.source.popNode(a))};s=o.track(l);try{let u=new Oe,c=u.root.html_dialog({nodeId:a,request:a,connect_oncancel:"treeInspectClose",connect_onclose:"treeInspectClose","aria-labelledby":`${a}_title`,style:"width:min(36rem,calc(100% - 48px));max-height:80vh;overflow:auto;"});c.h2("Attributes",{id:`${a}_title`}),c.p(`==${JSON.stringify(r)}`),c.html_button("Close",{type:"button",autofocus:!0,request:a,connect_onclick:"treeInspectClose"});let d=c.table();for(let[h,p]of Object.entries(t.getAttr())){let m=d.tr();m.th(`==${JSON.stringify(h)}`,{scope:"row"});let b=typeof p=="string"?p:p===void 0?"undefined":L(p);m.td(`==${JSON.stringify(b)}`)}this.page.src.source.setItem(a,this.page.src.prepareSource(u.source));let f=this.page.src.binding.nodeIds.get(a);Object.defineProperty(f,"treeInspectClose",{value:l,configurable:!0}),this.page.src.renderer.onDispose(f,()=>{l(),delete f.treeInspectClose}),this.page.dom.getDomNode(f).showModal()}catch(u){throw l(),u}}treeInspectClose(e,t){t.preventDefault();let r=this.page.src.binding.nodeIds.get(e.getAttr("request"));r&&r.treeInspectClose()}};var vo=class{constructor({maxBytes:e}){if(!Number.isSafeInteger(e)||e<0)throw new TypeError("maxBytes must be a nonnegative safe integer");this.maxBytes=e}write(e){throw new Error("UploadTarget.write must be implemented")}finish(){throw new Error("UploadTarget.finish must be implemented")}abort(){throw new Error("UploadTarget.abort must be implemented")}status(){throw new Error("UploadTarget.status must be implemented")}};var S2=new Set(Object.entries(new qt().schema).filter(([,n])=>!n._meta?.data_element&&!n._meta?.subbuilder&&!n._meta?.container).map(([n])=>n));function Eo(n){if(!(n==null||n==="html")){if(!Array.isArray(n)||n.some(e=>typeof e!="string"||!e||e.trim()!==e))throw new TypeError('catalogue must be "html" or a list of tag names');if(!n.includes("div"))throw new Error("catalogue must include div for pageRoot")}}function xo(n,e,t={}){return n==null?!0:Array.isArray(n)?n.includes(e):!t.gramlot_component&&!t.data_element&&!t.subbuilder&&!t.container&&S2.has(t.render_tag??e)}function Dt(n,e){if(n==null)return;let t=(r,o)=>{for(let i of r.getNodes()){let a=o?`${o}.${i.label}`:i.label;if(!xo(n,i.nodeTag,i.getAttr("_meta")??{}))throw new Error(`Tag ${i.nodeTag} is outside the editor catalogue at ${a}`);if(i.resolver)throw new Error(`Catalogue scope requires materialized Source at ${a}`);let s=i.getValue(!0);s instanceof I&&t(s,a)}};t(e,"")}var Ge={navigation:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%224%22%20width%3D%2218%22%20height%3D%2216%22%20rx%3D%222%22%2F%3E%3Cpath%20d%3D%22M9%204v16M5.5%208h1M5.5%2012h1%22%2F%3E%3C%2Fsvg%3E",catalogue:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%223%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Crect%20x%3D%2214%22%20y%3D%223%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Crect%20x%3D%223%22%20y%3D%2214%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Cpath%20d%3D%22M14%2017.5h7M17.5%2014v7%22%2F%3E%3C%2Fsvg%3E",properties:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M4%206h16M4%2012h16M4%2018h16%22%2F%3E%3Ccircle%20cx%3D%228%22%20cy%3D%226%22%20r%3D%222%22%2F%3E%3Ccircle%20cx%3D%2216%22%20cy%3D%2212%22%20r%3D%222%22%2F%3E%3Ccircle%20cx%3D%2210%22%20cy%3D%2218%22%20r%3D%222%22%2F%3E%3C%2Fsvg%3E",new:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M14%202H6a2%202%200%200%200-2%202v16a2%202%200%200%200%202%202h12a2%202%200%200%200%202-2V8Z%20M14%202v6h6%20M8%2015h8%20M12%2011v8%22%2F%3E%3C%2Fsvg%3E",download:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M12%203v12m-5-5%205%205%205-5%20M4%2016v4a1%201%200%200%200%201%201h14a1%201%200%200%200%201-1v-4%22%2F%3E%3C%2Fsvg%3E",copy:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%228%22%20y%3D%228%22%20width%3D%2212%22%20height%3D%2213%22%20rx%3D%222%22%2F%3E%3Cpath%20d%3D%22M16%208V5a2%202%200%200%200-2-2H5a2%202%200%200%200-2%202v9a2%202%200%200%200%202%202h3%22%2F%3E%3C%2Fsvg%3E"};Ge.open="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M3%207V5a2%202%200%200%201%202-2h5l2%202h7a2%202%200%200%201%202%202v2M3%209h18l-2%2011H4z%22%2F%3E%3C%2Fsvg%3E";Ge.cut="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Ccircle%20cx%3D%226%22%20cy%3D%226%22%20r%3D%223%22%2F%3E%3Ccircle%20cx%3D%226%22%20cy%3D%2218%22%20r%3D%223%22%2F%3E%3Cpath%20d%3D%22m8%208%2012%2012M8%2016%2020%204%22%2F%3E%3C%2Fsvg%3E";Ge.paste="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%225%22%20y%3D%225%22%20width%3D%2214%22%20height%3D%2216%22%20rx%3D%222%22%2F%3E%3Crect%20x%3D%229%22%20y%3D%222%22%20width%3D%226%22%20height%3D%225%22%20rx%3D%221%22%2F%3E%3Cpath%20d%3D%22M9%2012h6m-6%204h6%22%2F%3E%3C%2Fsvg%3E";Ge.appearance="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%3E%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%228%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%2F%3E%3Cpath%20d%3D%22M12%204a8%208%200%200%201%200%2016z%22%20fill%3D%22black%22%2F%3E%3C%2Fsvg%3E";var ol=class{constructor(e,{datapath:t="__editor",dataRoot:r="",editorId:o="visual",uploadOperation:i="import_source",codeDocument:a=null,catalogue:s=null,fileCommands:l=!0,canvasCss:u=null,...c}={}){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(o))throw new Error("editorId must be a literal identifier");if(!r&&t!=="__editor"&&!t.startsWith("__editor."))throw new Error("Root Data editing requires an __editor datapath");if(Eo(s),u!=null&&(!Array.isArray(u)||u.some(X=>typeof X!="string")))throw new TypeError("canvasCss must be a list of CSS texts");this.dataRoot=r;let d=this.pane=e.main({node_label:o,datapath:t,visualEditorId:o,...c,nodeId:`${o}Editor`,class:`visual-editor-shell ${c.class??""}`,overflow:"hidden",tabindex:0,connect_onkeydown:"clipboardShortcut"});d.dataSetter({destination_path:".catalogueScope",value:s}),d.dataSetter({destination_path:".canvasCss",value:u}),d.dataSetter({destination_path:".uploadQueue",value:new E}),d.dataController({func:"initializeEditor",dataRoot:this.dataRoot,_init:!0}),d.dataController({func:"showProperties",path:"^.selection",_init:!0}),d.dataController({func:"initializeCanvasSelection",_onBuilt:!0}),d.dataController({func:"initializeDocument",_onBuilt:!0}),d.dataController({func:"highlightSelection",path:"^.selection",_init:!0}),d.style("^.appearanceCss"),d.dataController({func:"initializeEditorAppearance",_onBuilt:!0}),d.dataController({func:"applyEditorAppearance",profile:"^.appearanceProfile",palette:"^.appearancePalette",mode:"^.appearanceMode"});let f=this.rail=d.menu({presentation:"bar",orientation:"vertical",aria_label:"Editor panels",class:"visual-editor-rail"});this.toolButton(f.menuline({group:!0}),"Source / Data","toggleNavigation",Ge.navigation),this.toolButton(f.menuline({group:!0}),"Catalogue","openCatalogue",Ge.catalogue),this.toolButton(f.menuline({group:!0}),"Properties","openProperties",Ge.properties),this.toolButton(f.menuline({group:!0}),"Clipboard","this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))",Ge.paste,{dropTarget:!0,dropTypes:"app/source",dropTags:`${o}Source`,dropEffect:"^.clipboardDropEffect",connect_ondragover:"clipboardModifiers",connect_ondrop:"clipboardModifiers",onDrop:"dropClipboard"}),f.spacer({flex:1}),this.toolButton(f.menuline({group:!0}),"Appearance","this.SET('.appearanceOpen', !this.GET('.appearanceOpen'))",Ge.appearance);let h=d.framePane({node_label:"layout",height:"100%",id:`${o}-editor-frame`,class:"visual-editor-layout"});h.top.setAttr({height:"30px"});let p=h.top.menu({presentation:"bar",aria_label:"Editor tools",class:"visual-editor-toolbar"});p.menuline({group:!0}).span("Source editor",{class:"visual-editor-brand"});let m=p.menuline({group:!0,gap:"4px",hidden:!l});for(let[X,Be,zt]of[["New","newPage","new"],["Open","openUpload","open"],["Download","downloadPage","download"],["Copy Source","copySource","copy"]])this.toolButton(m,X,Be,Ge[zt],{id:`${o}-${zt}`});p.menuline({group:!0}).span({class:"visual-toolbar-divider",aria_hidden:"true"});let b=p.menuline({group:!0,gap:"2px"});this.toolButton(b,"Cut branch","cutBranch",Ge.cut,{title:"Cut branch (F8)"}),this.toolButton(b,"Copy branch","copyBranch",Ge.copy),this.toolButton(b,"Paste branch","pasteBranch",Ge.paste,{title:"Paste branch (F9)"}),p.spacer({flex:1}),p.menuline({group:!0,hidden:"^.modified:=!{}"}).span("Unsaved changes",{role:"status",class:"visual-editor-hint"}),p.menuline({group:!0}).span("^.fileStatus",{role:"status",class:"visual-editor-file-status"}),p.menuline({group:!0}).span("^.filename",{class:"visual-editor-filename"});let w=h.left;w.setAttr({width:"min(240px, 34vw)",splitter:!0,drawer:"^.navigationOpen",default_drawer:!0,drawer_label:"Source / Data",drawer_onclick:"this.SET('.navigationOpen', show ? true : 'close')",display:"flex",flex_direction:"column",min_height:0,class:"visual-editor-sidebar"});let _=w.borderContainer({height:"100%",flex:1,min_height:0}),y=_.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),x=y.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),S=x.contentPane({node_label:"source",region:"center",title:"Source",detachable:!0,display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"});this.search(S,"sourceSearch","Search Source"),S.tree({storepath:`*S.${ie(d).fullpath.split(".").slice(1).join(".")}.layout.center.design`,hideValues:!0,getLabel:"sourceLabel",searchText:"^.sourceSearch",selectedPath:"^.selection",draggable:!0,dragTags:`${o}Source`,effectAllowed:"all",onDrag:"prepareSource",dropTarget:!0,dropTypes:"app/widget,app/source,app/clipboard",dropTags:`widget,${o}Source,${o}Clipboard`,dropEffect:"^.sourceDropEffect",onDrop:"dropNode",id:`${o}-source-tree`,class:"visual-source-tree",flex:1,min_height:0});let k=x.contentPane({node_label:"clipboard",region:"bottom",height:"112px",splitter:!0,minSize:80,title:"Clipboard",detachable:!0,hidden:"^.clipboardVisible:=!{}",display:"flex",flex_direction:"column",min_height:0,overflow:"hidden",dropTarget:!0,dropTypes:"app/source",dropTags:`${o}Source`,dropEffect:"^.clipboardDropEffect",connect_ondragover:"clipboardModifiers",connect_ondrop:"clipboardModifiers",onDrop:"dropClipboard",class:"visual-clipboard"});k.span("Drop a branch here \xB7 Option to copy",{class:"visual-editor-hint"}),k.tree({storepath:".clipboard",hideValues:!0,labelAttribute:"name",selectedPath:"^.clipboardSelection",draggable:!0,dragTags:`${o}Clipboard`,effectAllowed:"copy",onDrag:"prepareClipboard",id:`${o}-clipboard-tree`,class:"visual-clipboard-tree",flex:1,min_height:0}),k.p("^.error",{role:"alert",class:"visual-editor-hint"});let N=y.contentPane({node_label:"data",region:"bottom",title:"Data",detachable:!0,height:"108px",splitter:!0,minSize:80,display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"});this.search(N,"dataSearch","Search Data"),N.tree({storepath:this.dataRoot?`*D.${this.dataRoot}`:"*D",excludeRoot:this.dataRoot?null:"__editor",searchText:"^.dataSearch",id:`${o}-data-tree`,flex:1,min_height:0});let O=h.center;O.setAttr({overflow:"auto",class:"visual-editor-workspace"});let $=O.div({node_label:"design",class:"visual-editor-canvas"});$.div({node_label:"pageRoot",...this.dataRoot?{datapath:this.dataRoot}:{}});let ee=d.floatingPane({title:"Widget catalogue",open:"^.catalogueOpen",default_open:!1,width:"280px",height:"400px",class:"visual-editor-popup",movable:!0,resizable:!0});this.search(ee.frame.top,"catalogueSearch","Search widgets"),ee.frame.center.tree({storepath:".catalogue",hideValues:!0,labelAttribute:"caption",searchText:"^.catalogueSearch",draggable:!0,dragTags:"widget",effectAllowed:"all",onDrag:"prepareWidget",id:`${o}-widget-tree`});let W=_.contentPane({region:"bottom",height:"^.propertiesHeight",default_height:"200px",minSize:140,splitter:!0,title:"^.propertiesTitle",detachable:!0,hidden:"^.propertiesOpen:=!{}",display:"flex",flex_direction:"column",overflow:"hidden",min_height:0});W.div({nodeId:`${o}EditorFields`,class:"visual-editor-fields",display:"flex",flex_direction:"column",flex:1,min_height:0}).span(""),W.p("^.propertyError",{role:"alert",class:"visual-editor-hint",margin:"3px"}),d.dialog({class:"visual-editor-popup",title:"Open Source",open:"^.uploadOpen",width:"480px",height:"300px",movable:!0,resizable:!0}).frame.center.uploader({operation:i,storepath:".uploadQueue",accept:".grmlt",multiple:!1,autoUpload:!0,onComplete:"sourceUploaded",id:`${o}-uploader`});let me=d.dialog({class:"visual-editor-popup",title:"Save branch to clipboard",open:"^.clipboardOpen",width:"380px",height:"210px"});me.frame.center.textbox({value:"^.clipboardDraft.name",lbl:"Name",margin:"12px"}),me.frame.center.p("^.error",{role:"alert",margin:"12px"});let te=me.frame.bottom.menu({presentation:"bar",aria_label:"Clipboard commands",padding:"3px 6px"});te.spacer({flex:1});let le=te.menuline({group:!0,gap:"8px"});le.button("Cancel",{action:"this.SET('.clipboardOpen', false)"}),le.button("Save branch",{action:"saveClipboard"});let q=d.dialog({class:"visual-editor-popup",title:"Required parameters",open:"^.insertionOpen",width:"400px",height:"280px",movable:!0,resizable:!0});q.frame.center.div({nodeId:`${o}InsertFields`,class:"visual-editor-fields",padding:"6px"}).span(""),q.frame.center.p("^.error",{role:"alert"});let dt=q.frame.bottom.menu({presentation:"bar",aria_label:"Insertion commands",padding:"3px 6px",border_top:"1px solid var(--gramlot-border)"});dt.spacer({flex:1});let yn=dt.menuline({group:!0,gap:"8px"});yn.button("Cancel",{action:"this.SET('.insertionOpen', false)"}),yn.button("Insert",{action:"insertWidget"});let wt=d.floatingPane({class:"visual-editor-popup",title:"Appearance",open:"^.appearanceOpen",default_open:!1,width:"280px",height:"260px",movable:!0,resizable:!0}).frame.center.formlet({columns:1,lbl_position:"TL",gap:"4px",padding:"6px"});wt.filteringSelect({validate_notnull:!0,lbl:"Theme",value:"^.appearanceProfile",values:"base:Base,compact:Compact,mimi:Mimi,joanna:Joanna,mela:Mela"}),wt.filteringSelect({validate_notnull:!0,lbl:"Colors",value:"^.appearancePalette",values:"default:Theme default,compact:Blue & slate,mimi:Sage & green,joanna:Warm gray & blue"}),wt.filteringSelect({validate_notnull:!0,lbl:"Mode",value:"^.appearanceMode",values:"light:Light,dark:Dark"}),d.p("^.error",{role:"alert",class:"visual-editor-error",hidden:"^.error:=!{}"}),this.frame=h,this.toolbar=p,this.design=$,a!==null&&this.codeDocument(a)}toolButton(e,t,r,o,i={}){let a=e.button({aria_label:t,title:t,action:r,class:"button--quiet visual-editor-tool",...i});return a.span({class:"visual-tool-icon",aria_hidden:"true",style:`mask-image:url("${o}")`}),a}codeDocument(e,t=this.frame){if(!["python","javascript"].includes(e.language))throw new TypeError("Expected a Python or JavaScript page document");let r=this.pane;r.setAttr({codeDocumentKey:e.key}),r.dataSetter({destination_path:".codeDocument",value:new E({...e,saved:e.content,busy:!1,status:""})});let o=`#${r.getAttr("visualEditorId")}Editor`;(t===this.frame?this.toolbar:t.top.menu({presentation:"bar",aria_label:"Code drawer"})).menuline({group:!0}).button("Code",{action:"openCode",class:"button--quiet"});let a=t.right;a.setAttr({class:"visual-editor-code",datapath:o,title:"Page code",detachable:!0,width:"60%",minSize:240,splitter:!0,drawer:"^.codeOpen",default_drawer:"close",drawer_label:"Code",drawer_minimize:!1,drawer_onclick:"this.SET('.codeOpen', show ? true : 'close')",min_height:0,overflow:"hidden"});let s=a.framePane({height:"100%",width:"100%",min_width:0,flex:1});s.top.setAttr({height:"26px"}),s.bottom.setAttr({height:"48px"}),s.center.setAttr({display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"}),s.top.div(e.path,{padding:"3px 6px",font_size:"12px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),s.center.codeMirror({value:"^.codeDocument.content",language:e.language,live:!0,readonly:"^.codeDocument.writable:=!{}",height:"100%",box_height:"100%",box_c_height:"100%",box_min_height:0,box_c_min_height:0,fontSize:13,flex:1,min_height:0}),s.bottom.div("^.codeDocument.status",{role:"status",font_size:"12px",padding:"4px 10px"});let l=s.bottom.menu({presentation:"bar",aria_label:"Page code commands",padding:"3px 6px"});l.spacer({flex:1});let u=l.menuline({group:!0,gap:"6px"});u.button("Close",{action:"this.SET('.codeOpen', 'close')"}),u.button("Preview saved",{action:"codePreview",disabled:"^.codeDocument.busy"}),u.button("Save",{action:"codeSave",disabled:"^.codeSaveDisabled"}),r.dataFormula({result_path:".codeSaveDisabled",formula:"!writable || busy || content === saved",writable:"^.codeDocument.writable",busy:"^.codeDocument.busy",content:"^.codeDocument.content",saved:"^.codeDocument.saved",_init:!0})}search(e,t,r){let i=e.menu({presentation:"bar",aria_label:r,class:"visual-search-toolbar"}).menuline({group:!0,flex:1,min_width:0}).div({class:"visual-search-field"});i.span({class:"visual-search-icon",aria_hidden:"true"}),i.input({type:"search",value:`^.${t}`,default:"",live:!0,placeholder:r,aria_label:r}),i.html_button({type:"button",class:"visual-search-clear",aria_label:`Clear ${r.toLowerCase()}`,hidden:`^.${t}:={} === ''`,connect_onclick:`this.SET('.${t}', '')`})}};var il=class extends vo{constructor({catalogue:e=null}={}){super({maxBytes:5*1024*1024}),Eo(e),this.catalogue=e,this.decoder=new TextDecoder("utf-8",{fatal:!0}),this.parts=[],this.outcome={state:"pending"}}write(e){this.parts.push(this.decoder.decode(e,{stream:!0}))}finish(){this.parts.push(this.decoder.decode());let e=this.parts.join("");this.parts=[];let t=F(e);if(!(t instanceof I)||t.length!==1||t.getNodes()[0].label!=="pageRoot")throw new TypeError("Expected one pageRoot Source");return Dt(this.catalogue,t),this.outcome={state:"completed",result:e},this.outcome}abort(){return this.outcome.state!=="completed"&&(this.parts=[],this.outcome={state:"unsaved"}),this.outcome}status(){return this.outcome}};function C2(n,e){this.v=n,this.k=e}function bm(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,r=Array(e);t<e;t++)r[t]=n[t];return r}function N2(n){if(Array.isArray(n))return n}function I2(n,e){var t=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(t!=null){var r,o,i,a,s=[],l=!0,u=!1;try{if(i=(t=t.call(n)).next,e===0){if(Object(t)!==t)return;l=!1}else for(;!(l=(r=i.call(t)).done)&&(s.push(r.value),s.length!==e);l=!0);}catch(c){u=!0,o=c}finally{try{if(!l&&t.return!=null&&(a=t.return(),Object(a)!==a))return}finally{if(u)throw o}}return s}}function O2(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
237
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function R2(n,e){return N2(n)||I2(n,e)||B2(n,e)||O2()}function B2(n,e){if(n){if(typeof n=="string")return bm(n,e);var t={}.toString.call(n).slice(8,-1);return t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set"?Array.from(n):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?bm(n,e):void 0}}function al(n){var e,t;function r(i,a){try{var s=n[i](a),l=s.value,u=l instanceof C2;Promise.resolve(u?l.v:l).then(function(c){if(u){var d=i==="return"&&l.k?i:"next";if(!l.k||c.done)return r(d,c);c=n[d](c).value}o(!!s.done,c)},function(c){r("throw",c)})}catch(c){o(2,c)}}function o(i,a){i===2?e.reject(a):e.resolve({value:a,done:i}),(e=e.next)?r(e.key,e.arg):t=null}this._invoke=function(i,a){return new Promise(function(s,l){var u={key:i,arg:a,resolve:s,reject:l,next:null};t?t=t.next=u:(e=t=u,r(i,a))})},typeof n.return!="function"&&(this.return=void 0)}al.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},al.prototype.next=function(n){return this._invoke("next",n)},al.prototype.throw=function(n){return this._invoke("throw",n)},al.prototype.return=function(n){return this._invoke("return",n)};var Om=Object.entries,wm=Object.setPrototypeOf,$2=Object.isFrozen,Rm=Object.getPrototypeOf,Bm=Object.getOwnPropertyDescriptor,Re=Object.freeze,Ue=Object.seal,ko=Object.create,$m=typeof Reflect<"u"&&Reflect,Cc=$m.apply,Nc=$m.construct;Re||(Re=function(e){return e});Ue||(Ue=function(e){return e});Cc||(Cc=function(e,t){for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];return e.apply(t,o)});Nc||(Nc=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];return new e(...r)});var er=_e(Array.prototype.forEach);Array.prototype.indexOf;var M2=_e(Array.prototype.lastIndexOf),_m=_e(Array.prototype.pop),Xi=_e(Array.prototype.push),P2=_e(Array.prototype.slice),L2=_e(Array.prototype.splice),To=Array.isArray,yc=Mm(Set),vc=_e(Set.prototype.add),Zi=_e(Set.prototype.has),_n=_e(String.prototype.toLowerCase),Ec=_e(String.prototype.toString),ym=_e(String.prototype.match),Ki=_e(String.prototype.replace),vm=_e(String.prototype.indexOf),F2=_e(String.prototype.trim),j2=_e(Number.prototype.toString),q2=_e(Boolean.prototype.toString),Em=typeof BigInt>"u"?null:_e(BigInt.prototype.toString),xm=typeof Symbol>"u"?null:_e(Symbol.prototype.toString),st=_e(Object.prototype.hasOwnProperty),Ji=_e(Object.prototype.toString),qe=_e(RegExp.prototype.test),tr=Mm(TypeError);function _e(n){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,r=new Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];return Cc(n,e,r)}}function Mm(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return Nc(n,t)}}function oe(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:_n;if(wm&&wm(n,null),!To(e))return n;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let i=t(o);i!==o&&($2(e)||(e[r]=i),o=i)}n[o]=!0}return n}function U2(n){for(let e=0;e<n.length;e++)st(n,e)||(n[e]=null);return n}function ct(n){let e=ko(null);for(let r of Om(n)){var t=R2(r,2);let o=t[0],i=t[1];st(n,o)&&(To(i)?e[o]=U2(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=ct(i):e[o]=i)}return e}function V2(n){switch(typeof n){case"string":return n;case"number":return j2(n);case"boolean":return q2(n);case"bigint":return Em?Em(n):"0";case"symbol":return xm?xm(n):"Symbol()";case"undefined":return Ji(n);case"function":case"object":{if(n===null)return Ji(n);let e=n,t=bt(e,"toString");if(typeof t=="function"){let r=t(e);return typeof r=="string"?r:Ji(r)}return Ji(n)}default:return Ji(n)}}function bt(n,e){for(;n!==null;){let r=Bm(n,e);if(r){if(r.get)return _e(r.get);if(typeof r.value=="function")return _e(r.value)}n=Rm(n)}function t(){return null}return t}function z2(n,e){for(;n!==null;){let t=Bm(n,e);if(t)return t.get?_e(t.get):null;n=Rm(n)}return null}function H2(n){try{return qe(n,""),!0}catch{return!1}}var km=Re(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),xc=Re(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),kc=Re(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),G2=Re(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Tc=Re(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),W2=Re(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Tm=Re(["#text"]),Am=Re(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Ac=Re(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Dm=Re(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),sl=Re(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Y2=Ue(/{{[\w\W]*|^[\w\W]*}}/g),X2=Ue(/<%[\w\W]*|^[\w\W]*%>/g),Z2=Ue(/\${[\w\W]*/g),K2=Ue(/^data-[\-\w.\u00B7-\uFFFF]+$/),J2=Ue(/^aria-[\-\w]+$/),Sm=Ue(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Q2=Ue(/^(?:\w+script|data):/i),e0=Ue(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),t0=Ue(/^html$/i),r0=Ue(/^[a-z][.\w]*(-[.\w]+)+$/i),Dc=Ue(/<[/\w!]/g),Cm=Ue(/<[/\w]/g),n0=Ue(/<\/no(script|embed|frames)/i),Nm=Ue(/\/>/i),De={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},o0=Re(oe({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),i0=function(){return typeof window>"u"?null:window},a0=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(r=t.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Im=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Br=function(e,t,r,o){return st(e,t)&&To(e[t])?oe(o.base?ct(o.base):{},e[t],o.transform):r},Sc=function(e,t,r){let o=st(e,t)?e[t]:void 0;return o&&typeof o=="object"?ct(o):r()};function Pm(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:i0(),e=C=>Pm(C);if(e.version="3.4.17",e.removed=[],!n||!n.document||n.document.nodeType!==De.document||!n.Element)return e.isSupported=!1,e;let t=n.document,r=t,o=r.currentScript;n.DocumentFragment;let i=n.HTMLTemplateElement,a=n.Node,s=n.Element,l=n.NodeFilter;n.NamedNodeMap===void 0&&(n.NamedNodeMap||n.MozNamedAttrMap),n.HTMLFormElement;let u=n.DOMParser,c=n.trustedTypes,d=s.prototype,f=bt(d,"cloneNode"),h=bt(d,"remove"),p=bt(d,"removeAttributeNode"),m=bt(d,"nextSibling"),b=bt(d,"childNodes"),w=bt(d,"parentNode"),_=bt(d,"shadowRoot"),y=bt(d,"attributes"),x=a&&a.prototype?bt(a.prototype,"nodeType"):null,S=a&&a.prototype?bt(a.prototype,"nodeName"):null,k=a&&a.prototype?bt(a.prototype,"ownerDocument"):null,N=function(g){return x?x(g):g.nodeType},O=function(g){return S?S(g):g.nodeName},$=z2(d,"namespaceURI"),ee=function(g){return $?$(g):g.namespaceURI};if(typeof i=="function"){let C=t.createElement("template");C.content&&C.content.ownerDocument&&(t=C.content.ownerDocument)}let W,se="",me,te=!1,le=0,q=function(){if(le>0)throw tr('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},dt=function(g){q(),le++;try{return W.createHTML(g)}finally{le--}},yn=function(g){q(),le++;try{return W.createScriptURL(g)}finally{le--}},vn=function(){return te||(me=a0(c,o),te=!0),me},wt=t,X=wt.implementation,Be=wt.createNodeIterator,zt=wt.createDocumentFragment,En=wt.getElementsByTagName,Zm=r.importNode,ge=Im();e.isSupported=typeof Om=="function"&&typeof w=="function"&&X&&X.createHTMLDocument!==void 0;let Km=Y2,Jm=X2,Qm=Z2,eg=K2,tg=J2,rg=Q2,rd=e0,ng=r0,nd=Sm,be=null,wl=oe({},[...km,...xc,...kc,...Tc,...Tm]),we=null,_l=oe({},[...Am,...Ac,...Dm,...sl]),St=Object.seal(ko(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Do=null,od=null,or=Object.seal(ko(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),id=!0,yl=!0,ad=!1,vl=!0,Ht=!1,$r=!0,Mr=!1,El=!1,na=null,oa=null,xl=!1,xn=!1,ia=!1,aa=!1,sd=!0,ld=!1,ud="user-content-",kl=!0,Tl=!1,Pr=null,kn={},Lr=null,cd=oe({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),dd=null,fd=oe({},["audio","video","img","source","image","track"]),hd=null,pd=oe({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),sa="http://www.w3.org/1998/Math/MathML",la="http://www.w3.org/2000/svg",Ct="http://www.w3.org/1999/xhtml",Tn=Ct,Al=!1,Dl=null,og=oe({},[sa,la,Ct],Ec),md=Re(["mi","mo","mn","ms","mtext"]),Sl=oe({},md),gd=Re(["annotation-xml"]),Cl=oe({},gd),ig=oe({},["title","style","font","a","script"]),So=null,ag=["application/xhtml+xml","text/html"],sg="text/html",ke=null,An=null,lg=t.createElement("form"),bd=function(g){return g instanceof RegExp||g instanceof Function},Nl=function(){let g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(An&&An===g)return;(!g||typeof g!="object")&&(g={}),g=ct(g),So=ag.indexOf(g.PARSER_MEDIA_TYPE)===-1?sg:g.PARSER_MEDIA_TYPE,ke=So==="application/xhtml+xml"?Ec:_n,be=Br(g,"ALLOWED_TAGS",wl,{transform:ke}),we=Br(g,"ALLOWED_ATTR",_l,{transform:ke}),Dl=Br(g,"ALLOWED_NAMESPACES",og,{transform:Ec}),hd=Br(g,"ADD_URI_SAFE_ATTR",pd,{transform:ke,base:pd}),dd=Br(g,"ADD_DATA_URI_TAGS",fd,{transform:ke,base:fd}),Lr=Br(g,"FORBID_CONTENTS",cd,{transform:ke}),Do=Br(g,"FORBID_TAGS",ct({}),{transform:ke}),od=Br(g,"FORBID_ATTR",ct({}),{transform:ke}),kn=st(g,"USE_PROFILES")?g.USE_PROFILES&&typeof g.USE_PROFILES=="object"?ct(g.USE_PROFILES):g.USE_PROFILES:!1,id=g.ALLOW_ARIA_ATTR!==!1,yl=g.ALLOW_DATA_ATTR!==!1,ad=g.ALLOW_UNKNOWN_PROTOCOLS||!1,vl=g.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ht=g.SAFE_FOR_TEMPLATES||!1,$r=g.SAFE_FOR_XML!==!1,Mr=g.WHOLE_DOCUMENT||!1,xn=g.RETURN_DOM||!1,ia=g.RETURN_DOM_FRAGMENT||!1,aa=g.RETURN_TRUSTED_TYPE||!1,xl=g.FORCE_BODY||!1,sd=g.SANITIZE_DOM!==!1,ld=g.SANITIZE_NAMED_PROPS||!1,kl=g.KEEP_CONTENT!==!1,Tl=g.IN_PLACE||!1,nd=H2(g.ALLOWED_URI_REGEXP)?g.ALLOWED_URI_REGEXP:Sm,Tn=typeof g.NAMESPACE=="string"?g.NAMESPACE:Ct,Sl=Sc(g,"MATHML_TEXT_INTEGRATION_POINTS",()=>oe({},md)),Cl=Sc(g,"HTML_INTEGRATION_POINTS",()=>oe({},gd));let v=Sc(g,"CUSTOM_ELEMENT_HANDLING",()=>ko(null));if(St=ko(null),st(v,"tagNameCheck")&&bd(v.tagNameCheck)&&(St.tagNameCheck=v.tagNameCheck),st(v,"attributeNameCheck")&&bd(v.attributeNameCheck)&&(St.attributeNameCheck=v.attributeNameCheck),st(v,"allowCustomizedBuiltInElements")&&typeof v.allowCustomizedBuiltInElements=="boolean"&&(St.allowCustomizedBuiltInElements=v.allowCustomizedBuiltInElements),Ue(St),Ht&&(yl=!1),ia&&(xn=!0),kn&&(be=oe({},Tm),we=ko(null),kn.html===!0&&(oe(be,km),oe(we,Am)),kn.svg===!0&&(oe(be,xc),oe(we,Ac),oe(we,sl)),kn.svgFilters===!0&&(oe(be,kc),oe(we,Ac),oe(we,sl)),kn.mathMl===!0&&(oe(be,Tc),oe(we,Dm),oe(we,sl))),or.tagCheck=null,or.attributeCheck=null,st(g,"ADD_TAGS")&&(typeof g.ADD_TAGS=="function"?or.tagCheck=g.ADD_TAGS:To(g.ADD_TAGS)&&(be===wl&&(be=ct(be)),oe(be,g.ADD_TAGS,ke))),st(g,"ADD_ATTR")&&(typeof g.ADD_ATTR=="function"?or.attributeCheck=g.ADD_ATTR:To(g.ADD_ATTR)&&(we===_l&&(we=ct(we)),oe(we,g.ADD_ATTR,ke))),st(g,"ADD_FORBID_CONTENTS")&&To(g.ADD_FORBID_CONTENTS)&&(Lr===cd&&(Lr=ct(Lr)),oe(Lr,g.ADD_FORBID_CONTENTS,ke)),kl&&(be["#text"]=!0),Mr&&oe(be,["html","head","body"]),be.table&&(oe(be,["tbody"]),delete Do.tbody),g.TRUSTED_TYPES_POLICY){if(typeof g.TRUSTED_TYPES_POLICY.createHTML!="function")throw tr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof g.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw tr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let T=W;W=g.TRUSTED_TYPES_POLICY;try{se=dt("")}catch(A){throw W=T,A}}else g.TRUSTED_TYPES_POLICY===null?(W=void 0,se=""):(W===void 0&&(W=vn()),W&&typeof se=="string"&&(se=dt("")));Re&&Re(g),An=g},wd=oe({},[...xc,...kc,...G2]),_d=oe({},[...Tc,...W2]),ug=function(g,v,T){return v.namespaceURI===Ct?g==="svg":v.namespaceURI===sa?g==="svg"&&(T==="annotation-xml"||Sl[T]):!!wd[g]},cg=function(g,v,T){return v.namespaceURI===Ct?g==="math":v.namespaceURI===la?g==="math"&&Cl[T]:!!_d[g]},dg=function(g,v,T){return v.namespaceURI===la&&!Cl[T]||v.namespaceURI===sa&&!Sl[T]?!1:!_d[g]&&(ig[g]||!wd[g])},fg=function(g){let v=ee(g),T=_n(O(g)),A=w(g),M,U;return A&&N(A)===De.element?(M={namespaceURI:ee(A)},U=_n(O(A))):(M={namespaceURI:Tn},U="template"),Dl[v]?v===la?ug(T,M,U):v===sa?cg(T,M,U):v===Ct?dg(T,M,U):!!(So==="application/xhtml+xml"&&Dl[v]):!1},ir=function(g){Xi(e.removed,{element:g});try{w(g).removeChild(g)}catch{if(h(g),!w(g))throw tr("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},yd=function(g,v,T){try{p(g,v)}catch{try{g.removeAttribute(T)}catch{}}},Il=function(g){Rl(g);let v=b(g);v&&er(P2(v),A=>{try{h(A)}catch{}});let T=N(g)===De.element?y(g):null;if(T)for(let A=T.length-1;A>=0;--A){let M=T[A],U=M&&M.name;typeof U=="string"&&yd(g,M,U)}},Dn=function(g,v,T){if(!T)try{T=v.getAttributeNode(g)}catch{T=null}Xi(e.removed,{attribute:T||null,from:v});try{T?p(v,T):v.removeAttribute(g)}catch{try{v.removeAttribute(g)}catch{}}if(g==="is")if(xn||ia)try{ir(v)}catch{}else try{v.setAttribute(g,"")}catch{}},vd=function(g){let v=y(g);if(v)for(let T=v.length-1;T>=0;--T){let A=v[T],M=A&&A.name;typeof M!="string"||we[ke(M)]||yd(g,A,M)}},Ol=function(g,v){let T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,A=[g];for(;A.length>0;){let M=A.pop();if(v(M)===!1)continue;if(T&&N(M)===De.element){let Z=_(M);ar(Z)&&A.push(Z)}let U=b(M);if(U)for(let Z=U.length-1;Z>=0;--Z)A.push(U[Z])}},Rl=function(g){Ol(g,v=>{N(v)===De.element&&vd(v)})},Bl=function(g){let v=[];return Ol(g,T=>{v.push(T)},!0),v},hg=function(g,v){let T=yc();er(Bl(g),A=>{N(A)===De.element&&vc(T,A)}),er(v,A=>{N(A)===De.element&&!Zi(T,A)&&vd(A)})},Ed=function(g,v){let T=!1;return er(e.removed,A=>{A.element&&(T=T||A.element===g,Rl(A.element))}),hg(g,v),T},pg=8,mg=function(g,v){let T=Pr,A=null,M=()=>(A||(A=yc(),er(v,U=>{vc(A,U)})),A);for(let U=0;;U++){let Z=Bl(g),Se=[g],Nt=!1;if(er(Z,We=>{N(We)===De.documentFragment?Xi(Se,We):!Nt&&!Zi(T,We)&&(Nt=Zi(M(),We))}),!Nt)return;if(U>=pg)throw tr("the tree kept changing during in-place sanitization; refusing to return it");er(Se,(We,et)=>{gg(We,et>0,g,M())})}},gg=function(g,v,T,A){let M=$l(g),U;for(;U=M.nextNode();)!Zi(A,U)||Zi(Pr,U)||(v&&_t(ge.uponSanitizeShadowNode,U,null),Pl(U,T),Ll(U,T),ar(U.content)&&No(U.content))},bg=function(g){Pr&&vc(Pr,g)},xd=function(g,v){return $r?g==="patchsrc"?!0:g==="for"&&v!=="label"&&v!=="output":!1},wg=function(g){$r&&Ol(g,v=>{let T=N(v);if(T===De.processingInstruction||T===De.comment&&qe(Cm,v.data)){try{h(v)}catch{}return!1}if(T===De.element){let A=v,M=ke(O(v));try{A.hasAttribute&&A.hasAttribute("patchsrc")&&A.removeAttribute("patchsrc"),A.hasAttribute&&A.hasAttribute("for")&&xd("for",M)&&A.removeAttribute("for")}catch{}}return!0})},kd=function(g){let v=null,T=null;if(xl)g="<remove></remove>"+g;else{let U=ym(g,/^[\r\n\t ]+/);T=U&&U[0]}So==="application/xhtml+xml"&&Tn===Ct&&(g='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+g+"</body></html>");let A=W?dt(g):g;if(Tn===Ct)try{v=new u().parseFromString(A,So)}catch{}if(!v||!v.documentElement){v=X.createDocument(Tn,"template",null);try{v.documentElement.innerHTML=Al?se:A}catch{}}let M=v.body||v.documentElement;return g&&T&&M.insertBefore(t.createTextNode(T),M.childNodes[0]||null),Tn===Ct?En.call(v,Mr?"html":"body")[0]:Mr?v.documentElement:M},$l=function(g){let v=k?k(g):g.ownerDocument;return Be.call(v||g,g,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},ua=function(g){return g=Ki(g,Km," "),g=Ki(g,Jm," "),g=Ki(g,Qm," "),g},Ml=function(g){var v;Td(g);let T=(v=g.querySelectorAll)===null||v===void 0?void 0:v.call(g,"template");T&&er(T,A=>{ar(A.content)&&Ml(A.content)})},Td=function(g){g.normalize();let v=k?k(g):g.ownerDocument,T=Be.call(v||g,g,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),A=T.nextNode();for(;A;)A.data=ua(A.data),A=T.nextNode()},ca=function(g){let v=S?S(g):null;return typeof v!="string"||ke(v)!=="form"?!1:typeof g.nodeName!="string"||typeof g.textContent!="string"||typeof g.removeChild!="function"||g.attributes!==y(g)||typeof g.removeAttribute!="function"||typeof g.removeAttributeNode!="function"||typeof g.getAttributeNode!="function"||typeof g.setAttribute!="function"||typeof g.namespaceURI!="string"||typeof g.insertBefore!="function"||typeof g.hasChildNodes!="function"||g.nodeType!==x(g)||g.childNodes!==b(g)},ar=function(g){if(!x||typeof g!="object"||g===null)return!1;try{return x(g)===De.documentFragment}catch{return!1}},Co=function(g){if(!x||typeof g!="object"||g===null)return!1;try{return typeof x(g)=="number"}catch{return!1}};function _t(C,g,v){C.length!==0&&er(C,T=>{T.call(e,g,v,An)})}let _g=function(g,v){return!!($r&&g.hasChildNodes()&&!Co(g.firstElementChild)&&qe(Dc,g.textContent)&&qe(Dc,g.innerHTML)||$r&&o0[v]&&N(g)===De.element&&ee(g)===Ct&&(Co(g.firstElementChild)||typeof g.textContent=="string"&&qe(Dc,g.textContent))||g.nodeType===De.processingInstruction||$r&&g.nodeType===De.comment&&qe(Cm,g.data))},da=function(g,v){if(g instanceof RegExp)return qe(g,v);if(g instanceof Function){for(var T=arguments.length,A=new Array(T>2?T-2:0),M=2;M<T;M++)A[M-2]=arguments[M];return!!g(v,...A)}return!1},yg=function(g,v,T){if(!Do[v]&&Sd(v)&&da(St.tagNameCheck,v))return!1;if(kl&&!Lr[v]&&!Lr[_n(v)]){let A=w(g),M=b(g);if(M&&A){let U=M.length;for(let Z=U-1;Z>=0;--Z){let Se=g===T?f(M[Z],!0):M[Z];A.insertBefore(Se,m(g))}}}return ir(g),!0},Ad=function(g,v,T,A){return g.length===0?v:v===T||v===A?ct(v):v},Sn=function(g,v){return g===v||w(g)!==null?!1:(Tl&&Rl(g),!0)},Pl=function(g,v){if(bg(g),_t(ge.beforeSanitizeElements,g,null),Sn(g,v))return!0;if(ca(g))return ir(g),!0;let T=ke(O(g));if(be=Ad(ge.uponSanitizeElement,be,wl,na),_t(ge.uponSanitizeElement,g,{tagName:T,allowedTags:be}),Sn(g,v))return!0;if(_g(g,T))return ir(g),!0;if(Do[T]||!(or.tagCheck instanceof Function&&or.tagCheck(T))&&!be[T]){let A=yg(g,T,v);return A===!1&&(_t(ge.afterSanitizeElements,g,null),Sn(g,v))?!0:A}if(N(g)===De.element&&!fg(g)||(T==="noscript"||T==="noembed"||T==="noframes")&&qe(n0,g.innerHTML))return ir(g),!0;if(Ht&&g.nodeType===De.text){let A=ua(g.textContent);g.textContent!==A&&(Xi(e.removed,{element:g.cloneNode()}),g.textContent=A)}return _t(ge.afterSanitizeElements,g,null),Sn(g,v)},Dd=function(g,v,T){if(od[v]||xd(v,g)||sd&&(v==="id"||v==="name")&&(T in t||T in lg))return!1;let A=we[v]||or.attributeCheck instanceof Function&&or.attributeCheck(v,g);return yl&&qe(eg,v)||id&&qe(tg,v)?!0:A?hd[v]||qe(nd,Ki(T,rd,""))||(v==="src"||v==="xlink:href"||v==="href")&&g!=="script"&&vm(T,"data:")===0&&dd[g]||ad&&!qe(rg,Ki(T,rd,""))?!0:!T:Sd(g)&&da(St.tagNameCheck,g)&&da(St.attributeNameCheck,v,g)||v==="is"&&St.allowCustomizedBuiltInElements&&da(St.tagNameCheck,T)},vg=oe({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Sd=function(g){return!vg[_n(g)]&&qe(ng,g)},Eg=function(g,v,T,A){if(W&&typeof c=="object"&&typeof c.getAttributeType=="function"&&!T)switch(c.getAttributeType(g,v)){case"TrustedHTML":return dt(A);case"TrustedScriptURL":return yn(A)}return A},xg=function(g,v,T,A){try{return T?g.setAttributeNS(T,v,A):g.setAttribute(v,A),ca(g)?(ir(g),!1):!0}catch{return Dn(v,g),!1}},Cd=function(g,v){return $r&&qe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,v)?!0:_n(g)==="attributename"&&ym(v,"href")!==null},Ll=function(g,v){if(_t(ge.beforeSanitizeAttributes,g,null),Sn(g,v))return;let T=g.attributes;if(!T||ca(g))return;we=Ad(ge.uponSanitizeAttribute,we,_l,oa);let A={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:we,forceKeepAttr:void 0},M=T.length,U=ke(g.nodeName);for(;M--;){let Z=T[M],Se=Z.name,Nt=Z.namespaceURI,We=Z.value,et=ke(Se),Cn=We,tt=Se==="value"?Cn:F2(Cn),Nd=!1;if(A.attrName=et,A.attrValue=tt,A.keepAttr=!0,A.forceKeepAttr=void 0,_t(ge.uponSanitizeAttribute,g,A),tt=A.attrValue,ld&&(et==="id"||et==="name")&&vm(tt,ud)!==0&&(Dn(Se,g,Z),tt=ud+tt,Nd=!0),Cd(Se,tt)){Dn(Se,g,Z);continue}if(!A.forceKeepAttr){if(!A.keepAttr){Dn(Se,g,Z);continue}if(!vl&&qe(Nm,tt)){Dn(Se,g,Z);continue}if(Ht&&(tt=ua(tt)),!Dd(U,et,tt)){Dn(Se,g,Z);continue}tt=Eg(U,et,Nt,tt),tt!==Cn&&xg(g,Se,Nt,tt)&&Nd&&_m(e.removed)}}_t(ge.afterSanitizeAttributes,g,null),Sn(g,v)},No=function(g){let v=null,T=$l(g);for(_t(ge.beforeSanitizeShadowDOM,g,null);v=T.nextNode();)if(_t(ge.uponSanitizeShadowNode,v,null),Pl(v,g),Ll(v,g),ar(v.content)&&No(v.content),N(v)===De.element){let A=_(v);ar(A)&&(Fl(A),No(A))}Ht&&Td(g),_t(ge.afterSanitizeShadowDOM,g,null)},Fl=function(g){let v=[{node:g,shadow:null}];for(;v.length>0;){let T=v.pop();if(T.shadow){No(T.shadow);continue}let A=T.node,M=N(A)===De.element,U=b(A);if(U)for(let Z=U.length-1;Z>=0;--Z)v.push({node:U[Z],shadow:null});if(M){let Z=S?S(A):null;if(typeof Z=="string"&&ke(Z)==="template"){let Se=A.content;ar(Se)&&v.push({node:Se,shadow:null})}}if(M){let Z=_(A);ar(Z)&&v.push({node:null,shadow:Z},{node:Z,shadow:null})}}};return e.sanitize=function(C){let g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},v=null,T=null,A=null,M=null;if(Al=!C,Al&&(C="<!-->"),typeof C!="string"&&!Co(C)&&(C=V2(C),typeof C!="string"))throw tr("dirty is not a string, aborting");if(!e.isSupported)return C;El?(be=na,we=oa):Nl(g),(ge.uponSanitizeElement.length>0||ge.uponSanitizeAttribute.length>0)&&(be=ct(be)),ge.uponSanitizeAttribute.length>0&&(we=ct(we)),e.removed=[];let U=Tl&&typeof C!="string"&&Co(C),Z=[],Se=Pr;if(U){wg(C);let et=O(C);if(typeof et=="string"){let Cn=ke(et);if(!be[Cn]||Do[Cn])throw Il(C),tr("root node is forbidden and cannot be sanitized in-place")}if(ca(C))throw Il(C),tr("root node is clobbered and cannot be sanitized in-place");Z=Bl(C),Pr=yc()}else if(Co(C))v=kd("<!---->"),T=v.ownerDocument.importNode(C,!0),T.nodeType===De.element&&T.nodeName==="BODY"||T.nodeName==="HTML"?v=T:v.appendChild(T),Fl(v);else{if(!xn&&!Ht&&!Mr&&C.indexOf("<")===-1)return W&&aa?dt(C):C;if(v=kd(C),!v)return xn?null:aa?se:""}v&&xl&&ir(v.firstChild);let Nt=U?C:v;try{U&&Fl(C);let et=$l(Nt);for(;A=et.nextNode();)Pl(A,Nt),Ll(A,Nt),ar(A.content)&&No(A.content);U&&mg(C,Z)}catch(et){throw U&&(Il(C),Ed(C,Z)),et}finally{Pr=Se}if(U){if(Ed(C,Z))throw tr("a node selected for removal could not be safely returned; refusing to sanitize in place");return Ht&&Ml(C),C}if(xn){if(Ht&&Ml(v),ia)for(M=zt.call(v.ownerDocument);v.firstChild;)M.appendChild(v.firstChild);else M=v;return(we.shadowroot||we.shadowrootmode)&&(M=Zm.call(r,M,!0)),M}let We=Mr?v.outerHTML:v.innerHTML;return Mr&&be["!doctype"]&&v.ownerDocument&&v.ownerDocument.doctype&&v.ownerDocument.doctype.name&&qe(t0,v.ownerDocument.doctype.name)&&(We="<!DOCTYPE "+v.ownerDocument.doctype.name+`>
|
|
238
|
-
`+We),Ht&&(We=ua(We)),
|
|
232
|
+
`))})}#a(e,t,r){let o=this.#e.gramlot,i=JSON.stringify([t,e]);if(this.#o.has(i))return;let a=this.#e.nodeIds.get(this.#t);if(!a){if(this.#n.clear(),this.#i=0,this.#r===null){let p=this;class m{close(w){p.#s(w.getAttr("notice"))}}this.#r=`errors_${J()}`,this.#e.logicRegistry.register(m,{group:this.#r,resource:"gramlot:error-notifications"})}let h=new Oe;h.root.aside({nodeId:this.#t,class:"gramlot-error-notifications",popover:"manual","aria-label":"Error notifications",style:"position:fixed;inset:auto max(12px,env(safe-area-inset-right)) max(12px,env(safe-area-inset-bottom)) auto;margin:0;width:360px;max-width:calc(100vw - 24px);max-height:50vh;overflow:auto;box-sizing:border-box;padding:0;border:1px solid var(--gramlot-border-control,#aab4c2);border-radius:8px;background:var(--gramlot-surface,#fff);color:var(--gramlot-ink,#222);font:13px/1.4 system-ui;box-shadow:0 6px 24px #0003;"}),o.src.source.setItem(this.#t,o.src.prepareSource(h.source)),a=this.#e.nodeIds.get(this.#t)}if(this.#n.has(i))return;if(this.#n.size===5){let h=`${++this.#i} additional errors`,p=a.value.getNode("overflow");p?p.setValue(h):o.src.builder.wrapSource(a).p(h,{node_label:"overflow",role:"status",style:"margin:0;padding:12px;"});return}let s=`notice_${J()}`,l=new Oe,u=l.root.article({role:"alert",style:"color:inherit;padding:12px;border-bottom:1px solid var(--gramlot-border,#ddd);"}),c=u.div({style:"display:flex;align-items:start;gap:12px;"});c.strong(`==${JSON.stringify(t)}`,{style:"flex:1;color:var(--gramlot-error,#b13d48);"}),c.html_button("\xD7",{type:"button",notice:s,connect_onclick:`${this.#r}.close`,"aria-label":"Dismiss notification",title:"Dismiss notification",style:"border:0;background:transparent;color:inherit;font:18px/1 system-ui;width:24px;height:24px;flex:0 0 24px;padding:0;cursor:pointer;"}),u.p(`==${JSON.stringify(e)}`,{style:"margin:6px 0;overflow-wrap:anywhere;"});let d=u.details({style:"border:0;padding:0;margin:8px 0 0;background:transparent;"});d.summary("Details",{style:"cursor:pointer;"}),d.pre(`==${JSON.stringify(r)}`,{style:"font:11px/1.4 monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:6px 0 0;padding:8px;border:0;border-radius:4px;background:var(--gramlot-surface-subtle,#f2f4f6);"});let f=o.src.builder.wrapSource(a).div({node_label:s});ae(f).setValue(o.src.prepareSource(l.source)),this.#n.set(i,s),o.dom.getDomNode(a).showPopover()}#s(e){this.#e.nodeIds.get(this.#t).value.popNode(e);for(let[r,o]of this.#n)o===e&&(this.#n.delete(r),this.#o.add(r));this.#n.size||this.#e.gramlot.src.source.popNode(this.#t)}};var fm={dataFormula:Ls,dataController:Fs,dataRpc:js,dataRemote:qs},R2=["datapath","_anchor","nodeId","form","formId"],wo=class{#e;#t=new Map;#r=new Map;#n;#o;#i;#a;#s;#l;#u=`gramlot-data-${J()}`;#c=!1;#d=new Set;#f=new Set;#p=new WeakMap;constructor(e,{subscriptions:t}){this.#e=e,this.#l=t,this.#n=new Bs(this),this.#o=new Ms(this),this.#i=new Us(this),this.#a=new Hs(this),this.#s=new Gs(this)}get gramlot(){return this.#e}reportError(e,t){this.disposed||this.#s.show(e,t)}get subscriptions(){return this.#l}get builder(){return this.gramlot.src.builder}get renderer(){return this.gramlot.src.renderer}get logicRegistry(){return this.gramlot.src.logicRegistry}get data(){return this.builder.data}treeStore(e){if(e.treeStore!==null)return e.treeStore;let t=e.getAttr("storepath");if(t==="*S"||t.startsWith("*S.")){let r=this.renderer.source.getItem("main");return t==="*S"?r:r.getItem(t.slice(3))}return t==="*D"||t.startsWith("*D.")?t==="*D"?this.data:this.data.getItem(t.slice(3)):e.getRelativeData(t)}registerTreeRoot(e,t){let r=t?this.#d:this.#f;return r.add(e),{close:()=>r.delete(e)}}refreshSourceTrees(){for(let e of[...this.#d])!e.closed&&this.renderer.attached(e.node)&&this.renderer.project(e.node)}get root(){return this.data.parent}get size(){return this.#t.size}get disposed(){return this.#c}get router(){return this.#n}get installer(){return this.#o}get inlineCompiler(){return this.#i}get askDialog(){return this.#a}get nodeIds(){return this.#r}collectionStore(e,t){if(this.disposed)throw new Error("BindingRuntime is disposed");let r=this.#p.get(e);if(!r)r=new Ns(e,t),this.#p.set(e,r);else if(r.rowMode!==t)throw new TypeError("A shared collection store requires one rowMode");return r}collectionView(e,t,r){let o=this.collectionStore(t,r);return Object.hasOwn(e,"gridCollectionView")?e.gridCollectionView.bindStore(o):Object.defineProperty(e,"gridCollectionView",{value:new Os(o),configurable:!0}),e.gridCollectionView}attach(){this.root.subscribe(this.#u,{any:e=>this.receiveData(e)})}receiveData(e){let t=this.root;for(let[r,o]of(e.pathlist??[]).entries()){let i=t.node(o)?.staticValue;if(!(i instanceof E))break;this.#p.get(i)?.receiveData(e,r+1<e.pathlist.length?i.node(e.pathlist[r+1]):null,e.pathlist[r+2]??null),t=i}this.router.deliver(e);for(let r of[...this.#f])!r.closed&&this.renderer.attached(r.node)&&this.renderer.project(r.node)}bindingFor(e){return this.#t.get(e)??null}openBinding(e){if(this.disposed)throw new Error("BindingRuntime is disposed");let t=this.bindingFor(e);return t||(t=new bc(this,e),this.#t.set(e,t)),t}closeBranch(e){let t=[];if(e.value instanceof I)for(let o of e.value.getNodes())try{this.closeBranch(o)}catch(i){t.push(i)}let r=this.bindingFor(e);if(r){this.#t.delete(e);let o=e.getAttr("nodeId");this.nodeIds.get(o)===e&&this.nodeIds.delete(o);try{r.close()}catch(i){t.push(i)}}if(t.length)throw new AggregateError(t,"Source branch close failed")}rebindBranch(e){let t=this.#_(e);for(let r of t)this.bindingFor(r)?.rebind();for(let r of t)this.renderer.project(r);for(let r of t)this.bindingFor(r)?.remote?.trigger()}handleSourceEvent(e){let{evt:t,node:r}=e,o=[],i=a=>{try{this.closeBranch(a)}catch(s){o.push(s)}};try{if(t==="ins")this.#h(r);else if(t==="del")for(let a of Array.isArray(r)?r:[r])i(a);else if(t==="upd_value"||t==="upd_value_attr"){if(e.oldvalue instanceof I)for(let a of e.oldvalue.getNodes())i(a);this.inlineCompiler.release(r,[""]),t==="upd_value_attr"?this.#b(r,e.attrs_diff):this.#w(r).rebind(),r.value instanceof I&&this.#h(r.value)}else if(t==="upd_attrs")this.#b(r,e.attrs_diff);else throw new Error(`Unsupported Source event: ${t}`)}catch(a){throw o.length?new AggregateError([...o,a],"Source event failed"):a}return o}branchBuilt(e){let t=[];for(let r of this.#_(e)){let o=this.bindingFor(r);!o||o.hasStamp("built")||!this.renderer.attached(r)||(o.stamp("built"),t.push(o))}for(let r of t)this.renderer.attached(r.node)&&this.#g(r,"built","_onBuilt");if(this.gramlot.state==="started")for(let r of t)this.renderer.attached(r.node)&&this.#m(r)}pageStarted(){for(let e of[...this.#t.values()])!e.closed&&e.hasStamp("built")&&this.#m(e)}dispose(){if(this.disposed)return;this.#c=!0,this.root.unsubscribe(this.#u,{any:!0}),this.nodeIds.clear(),this.#p=new WeakMap;let e=[];for(let[t,r]of[...this.#t.entries()].reverse()){this.#t.delete(t);try{r.close()}catch(o){e.push(o)}}if(e.length)throw new AggregateError(e,"Binding cleanup failed")}#h(e){if(!(e instanceof I)&&this.bindingFor(e))return;let t=e instanceof I?e.getNodes().flatMap(i=>this.#_(i)):this.#_(e),r=new Set(t.filter(i=>this.bindingFor(i))),o=new Map;for(let i of t){let a=i.getAttr("nodeId");if(a!=null){if(o.has(a)||this.nodeIds.has(a)&&this.nodeIds.get(a)!==i)throw new Error(`Duplicate nodeId '${a}'`);o.set(a,i)}}for(let[i,a]of o)this.nodeIds.set(i,a);try{for(let i of t)this.openBinding(i);this.installer.install(e);for(let i of t)this.renderer.attached(i)&&this.bindingFor(i).registerPointers()}catch(i){let a=[i];for(let s of t.filter(l=>!r.has(l)).reverse()){let l=s.getAttr("nodeId");o.get(l)===s&&this.nodeIds.get(l)===s&&this.nodeIds.delete(l);let u=this.bindingFor(s);if(u){this.#t.delete(s);try{u.close()}catch(c){a.push(c)}}}throw a.length>1?new AggregateError(a,"Source branch installation failed"):i}for(let i of t){let a=this.bindingFor(i);if(!(!a||a.hasStamp("init")||!this.renderer.attached(i))&&(a.stamp("init"),hm(i.getAttr("_init"))))for(let s of a.providers)s.invoke({kind:"init",change:null})}}#m(e){e.hasStamp("start")||(e.stamp("start"),this.#g(e,"start","_onStart"),e.remote?.trigger())}#g(e,t,r){let o=e.node.getAttr(r);if(hm(o))for(let i of e.providers){if(typeof o!="number"||o<=0){i.invoke({kind:t,change:null});continue}let a=null,s=setTimeout(()=>{a(),i.invoke({kind:t,change:null})},o);a=e.track(()=>clearTimeout(s))}}#b(e,t){let r=this.#w(e);if(this.inlineCompiler.release(e,Object.keys(t)),Object.hasOwn(t,"nodeId")){let{old:o,new:i}=t.nodeId;if(i!=null&&this.nodeIds.has(i)&&this.nodeIds.get(i)!==e)throw new Error(`Duplicate nodeId '${i}'`);this.nodeIds.get(o)===e&&this.nodeIds.delete(o),i!=null&&this.nodeIds.set(i,e)}R2.some(o=>Object.hasOwn(t,o))?this.rebindBranch(e):r.rebind()}#w(e){let t=this.bindingFor(e);if(!t)throw new Error(`${e.nodeTag??"fragment"} '${e.label}': the node has no NodeBinding (its installation failed); remove it from the Source and insert it again`);return t}#_(e){let t=[e];if(e.value instanceof I)for(let r of e.value.getNodes())t.push(...this.#_(r));return t}};function hm(n){return n===!0||typeof n=="number"}var bc=class{#e;#t;#r=!1;#n=[];#o=[];#i=new Set;#a=null;#s=null;#l=null;#u=new Set;#c=new Set;#d=0;#f=new Set;#p=null;editingSession=null;constructor(e,t){this.#e=e,this.#t=t}get runtime(){return this.#e}get node(){return this.#t}get closed(){return this.#r}get registrations(){return[...this.#o]}get providers(){return this.#a?[this.#a]:[]}get remote(){return this.#l}get clickCount(){return this.#d}countClick(){return++this.#d}hasStamp(e){return this.#i.has(e)}stamp(e){this.#i.add(e)}registerPointers(){this.node._getMeta("data_element")&&(this.runtime.renderer.references.remove(this.node),this.runtime.renderer.references.register(this.node,null));let e=this.node,t=e._getMeta("data_element");if(t&&!fm[e.nodeTag]&&e.nodeTag!=="dataBinder")return;!t&&typeof e.getAttr("remote")=="string"?this.#l??=new Vs(this):this.#l&&(this.#l.close(),this.#l=null);let r=new Set,o=e._getMeta("gramlot_component");for(let[a,s]of[["bagStore","storepath"],["bagStruct","structpath"]]){if(!o?.[a])continue;if(a==="bagStore"&&e.nodeTag==="tree"&&e.treeStore!==null){let d=e.treeStore,f=`gramlot-tree-${J()}`;d.subscribe(f,{any:()=>{!this.closed&&this.runtime.renderer.attached(e)&&this.runtime.renderer.project(e)}}),this.#o.push({close:()=>d.unsubscribe(f,{any:!0})});continue}let l=e.getAttr(s);if(typeof l!="string"||!l||/^[\^=]/.test(l)||l.includes("?"))throw new TypeError(`${s} requires a plain Bag data path`);if(a==="bagStore"&&e.nodeTag==="tree"&&(l==="*S"||l.startsWith("*S."))){this.#o.push(this.runtime.registerTreeRoot(this,!0));continue}if(a==="bagStore"&&e.nodeTag==="tree"&&l==="*D"){this.#o.push(this.runtime.registerTreeRoot(this,!1));continue}let u=a==="bagStore"&&e.nodeTag==="tree"&&l.startsWith("*D.")?l.slice(3):e.absDatapath(l),c=this.runtime.router.register({path:u,recipient:this,subtree:!0});this.#o.push(c),a==="bagStore"&&o.bagStruct&&(this.#p=c)}let i=this.remote?Ft(e,e.getAttr("_timing")):new Set;if(this.remote){for(let[a,s]of Object.entries(e.getAttr()))if(a.startsWith("remote_"))for(let l of Ft(e,s))r.add(l)}for(let[a,s]of e.pointers()){if(t&&a!=="datapath")continue;let u=(a==="datapath"?e.parentNode:e).absDatapath(s);if(u===null)continue;let[c,d=null]=u.split("?",2),f=this.runtime.router.register({path:c,attr:d,recipient:this});this.#o.push(f),a==="datapath"&&this.#f.add(f),this.remote&&(a==="remote"||a.startsWith("remote_")||r.has(a))&&this.#u.add(f),this.remote&&(a==="_timing"||i.has(a))&&this.#c.add(f)}if(!t){this.#h(),this.remote?.register();return}if(e.nodeTag==="dataBinder"){this.#s??=new zs(this),this.#s.register();return}this.#a??=new fm[e.nodeTag](this),this.#a.register()}#h(){let e=this.node;this.#o.push(...this.runtime.subscriptions.subscribeNode(e,(t,r)=>{if(typeof r!="string"||!r)throw new TypeError(`${t} requires a handler`);return o=>{if(this.closed)return;if(xi(r))return er(this.runtime,e,r,o);let[,i]=e.rootBuilder.runtimeValues(e),a=Object.fromEntries(Object.entries(i).filter(([l])=>!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),s={...this.runtime.renderer.references.resolveArguments(a),p_0:o};return this.runtime.inlineCompiler.compile(e,t,r,Object.keys(s))(s)}}))}rebind(){this.#m(),this.registerPointers(),this.editingSession?.refreshField(this.node)}receive(e){if(!(e.registration===this.#p&&(e.level==="child"||e.evt==="upd_attrs"))){if(this.#f.has(e.registration)){this.runtime.rebindBranch(this.node);return}this.#u.has(e.registration)&&this.remote.receive(e),this.#c.has(e.registration)&&this.remote.register(),this.editingSession?.refreshField(this.node),this.runtime.renderer.project(this.node,e)}}track(e){if(this.closed)throw new Error(`NodeBinding of '${this.node.label}' is closed`);return this.#n.push(e),()=>{let t=this.#n.indexOf(e);t!==-1&&this.#n.splice(t,1)}}async call(e,t){let{controller:r}=t,o=this.track(()=>r.abort());try{let i=await this.runtime.gramlot.rpc.call(e,t.method,t.params,{signal:r.signal});if(r.signal.aborted)throw r.signal.reason;return i}finally{o()}}callSync(e,t,r){return this.node.requests.submitSync(t,()=>this.runtime.gramlot.rpc.callSync(e,t,r))}close(){if(this.closed)return;this.#r=!0,this.#l?.close(),this.node._getMeta("data_element")&&this.runtime.renderer.references.remove(this.node),this.#m();let e=[];for(let t of this.#n.splice(0).reverse())try{t()}catch(r){e.push(r)}if(e.length)throw new AggregateError(e,`NodeBinding of '${this.node.label}' cleanup failed`)}#m(){this.#s?.unregister();for(let e of this.#o.splice(0))e.close();this.#p=null,this.#f.clear(),this.#u.clear(),this.#c.clear()}};var Ws=class{constructor(e){this.renderer=e}prepare(e,t){let r=this.renderer.records.get(e);if(!r||r.resolved.draggable!==!0)return null;let o=e._getMeta("gramlot_component")?.dragSource?r.element.getDragContext(t):{dragValues:{},item:void 0,path:void 0};if(o===null)return null;let{dragValues:i,item:a,path:s}=o;if(r.resolved.onDrag){let u=this.renderer.html.callLogic(e,r.resolved.onDrag,{dragValues:i,item:a,path:s});if(u&&typeof u.then=="function")throw new TypeError("onDrag must run synchronously");if(u===!1)return null}return Tt(i),{dragValues:Object.fromEntries(Object.entries(i).map(([u,c])=>{if(u.startsWith("text/")||u==="dragTags"){if(typeof c!="string")throw new TypeError(`${u} drag data must be text`);return[u,c]}return[u,j(L(c))]})),item:a,path:s}}};var Rr=class{static isTarget(e){return e.dropTarget===!0||!!e.dropTargetCb||Object.entries(e).some(([t,r])=>t.startsWith("dropTargetCb_")&&!!r)}static acceptedTypes(e,t="",r=[]){let o=t.split(",").map(i=>i.trim()).filter(Boolean).map(i=>{let a=i.split("*").map(s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return new RegExp(`^${a.join(".*")}$`)});return e.filter(i=>i!=="dragTags"&&(r.includes(i)||o.some(a=>a.test(i))))}static acceptsTags(e="",t=""){if(!t.trim())return!0;let r=new Set(e.split(",").map(o=>o.trim()).filter(Boolean));return r.size?t.split(",").some(o=>o.split(" AND ").every(i=>(i=i.trim(),!i||i==="!"?!1:i.startsWith("!")?!r.has(i.slice(1)):r.has(i)))):!1}static acceptsEffect(e="all",t="move"){let r={all:["copy","move","link"],none:[],copy:["copy"],move:["move"],link:["link"],copyMove:["copy","move"],copyLink:["copy","link"],linkMove:["link","move"]};if(!Object.hasOwn(r,e))throw new TypeError(`Invalid effectAllowed: ${e}`);if(!["copy","move","link"].includes(t))throw new TypeError(`Invalid dropEffect: ${t}`);return r[e].includes(t)}static evaluate(e,t,r,o,i=[]){let a=this.acceptedTypes(e,o.dropTypes,i),s=o.dropEffect??"move",l=this.isTarget(o)&&a.length>0&&this.acceptsTags(t,o.dropTags)&&this.acceptsEffect(r,s);return{accepted:l,types:a,dropEffect:l?s:"none"}}};var pm=["dragstart","dragover","dragleave","drop","dragend"],Ys=class{#e;#t;#r=null;#n=null;#o=null;#i;constructor(e){this.#e=e,this.#t=e.destination.ownerDocument;for(let t of pm)this.#t.addEventListener(t,this);this.#i=()=>this.#b("none"),this.#t.defaultView.addEventListener("pagehide",this.#i)}handleEvent(e){e.type==="dragstart"?this.#l(e):e.type==="dragend"?this.#b(e.dataTransfer.dropEffect):e.type==="dragleave"?this.#h():e.type==="dragover"?this.#d(e):e.type==="drop"&&this.#f(e)}#a(e,t){for(let r of e.composedPath()){let o=this.#e.elements.get(r);if(o&&t(o.resolved))return o}return null}#s(e,t){return e.node._getMeta("gramlot_component")?.dragSource?e.element.getDragContext(t):{element:e.element,item:void 0,path:void 0}}#l(e){let t=this.#a(e,r=>r.draggable===!0);if(t){this.#b("none");try{let r=this.#e.prepareDrag(t.node,e);if(!r||!t.element.isConnected||this.#e.records.get(t.node)!==t){e.preventDefault();return}let o=this.#s(t,e);if(!o){e.preventDefault();return}let i=new Map(Object.entries(r.dragValues).filter(([u])=>u!=="dragTags").map(([u,c])=>[u,u.startsWith("text/")?c:L(c)]));if(!i.size){e.preventDefault();return}let a=t.resolved.effectAllowed??"all";Rr.acceptsEffect(a,"move");let s="";for(let u=t;u;u=u.parent)if(u.resolved?.dragTags!=null){s=u.resolved.dragTags;break}let l=this.#r={record:t,wires:i,effectAllowed:a,phase:"active",tags:[s,r.dragValues.dragTags].filter(Boolean).join(","),endTopic:this.#e.binding.subscriptions.topicFor(t.node,"endDrag"),source:{pageId:this.#e.binding.gramlot.pageId??null,sourcePath:t.node.fullpath,itemPath:r.path??null},preview:null,release:null};e.dataTransfer.clearData();for(let[u,c]of i)e.dataTransfer.setData(u,c);e.dataTransfer.effectAllowed=a,this.#o=this.#t.createElement("style"),this.#o.textContent=".canBeDropped{outline:2px solid var(--gramlot-brand-blue,#3766b5);outline-offset:-2px}.cannotBeDropped{outline:2px dashed currentColor;outline-offset:-2px}.draggedItem{opacity:.75}",this.#t.head.append(this.#o),this.#u(l,o.element,e.dataTransfer),l.release=this.#e.onDispose(t.node,()=>this.#b("none"))}catch(r){e.preventDefault(),this.#g(),this.#w(r)}}}#u(e,t,r){let o=t.cloneNode(!0);o.removeAttribute("id");for(let i of o.querySelectorAll("[id]"))i.removeAttribute("id");o.setAttribute("aria-hidden","true"),o.classList.add(...(e.record.resolved.dragClass??"draggedItem").split(/\s+/).filter(Boolean)),Object.assign(o.style,{position:"fixed",left:"-10000px",top:"0",width:`${t.getBoundingClientRect().width}px`,pointerEvents:"none"}),t.parentNode.append(o),e.preview=o,r.setDragImage(o,0,0)}#c(e){let t=this.#r,r=this.#a(e,u=>Rr.isTarget(u));if(!r)return null;let o=this.#s(r,e);if(!o)return{record:r,element:r.element,accepted:!1};let i=Rr.evaluate([...t.wires.keys()],t.tags,t.effectAllowed,r.resolved),s={dropValues:Object.fromEntries(i.types.map(u=>[u,u.startsWith("text/")?t.wires.get(u):j(t.wires.get(u))])),item:o.item,path:o.path,source:{...t.source},selfdrop:r===t.record,dropEffect:i.dropEffect,dataAvailable:!0};o.placement!==void 0&&(s.placement=o.placement);let l=i.accepted&&this.#e.checkDropTarget(r.node,s)&&this.#e.records.get(r.node)===r&&o.element.isConnected;return{record:r,element:o.element,accepted:l,context:s}}#d(e){if(!this.#r){this.#a(e,t=>Rr.isTarget(t))&&(e.preventDefault(),e.dataTransfer.dropEffect="none");return}if(e.preventDefault(),this.#r.phase!=="active"){e.dataTransfer.dropEffect="none";return}try{let t=this.#r,r=this.#c(e);if(this.#r!==t){e.dataTransfer.dropEffect="none";return}e.dataTransfer.dropEffect=r?.accepted?r.context.dropEffect:"none",this.#h(),r&&this.#p(r.element,r.accepted)}catch(t){e.dataTransfer.dropEffect="none",this.#r&&(this.#r.phase="rejected"),this.#m(),this.#w(t)}}async#f(e){if(!this.#r){this.#a(e,o=>Rr.isTarget(o))&&e.preventDefault();return}if(e.preventDefault(),this.#r.phase!=="active")return;let t=this.#r,r;try{if(r=this.#c(e),this.#r!==t){e.dataTransfer.dropEffect="none";return}if(t.phase="dropped",this.#m(),!r?.accepted){e.dataTransfer.dropEffect="none";return}e.dataTransfer.dropEffect=r.context.dropEffect,r.record.node.publish("onDrop",r.context),await this.#e.invokeDrop(r.record.node,r.context)}catch(o){this.#r===t&&(t.phase="rejected",this.#m()),(!r||this.#e.records.has(r.record.node))&&this.#w(o)}}#p(e,t){let r=t?"canBeDropped":"cannotBeDropped",o=(e.getAttribute("part")??"").split(/\s+/).filter(Boolean);this.#n={element:e,name:r,hadClass:e.classList.contains(r),hadPart:o.includes(r)},e.classList.add(r),o.includes(r)||e.setAttribute("part",[...o,r].join(" "))}#h(){if(!this.#n)return;let{element:e,name:t,hadClass:r,hadPart:o}=this.#n;r||e.classList.remove(t),o||e.setAttribute("part",(e.getAttribute("part")??"").split(/\s+/).filter(i=>i!==t).join(" ")),this.#n=null}#m(){this.#h(),this.#r&&(this.#r.preview?.remove(),this.#r.preview=null,this.#r.wires.clear())}#g(){let e=this.#r;return this.#m(),this.#r=null,e?.release?.(),this.#o?.remove(),this.#o=null,e}#b(e){let t=this.#g();!t||this.#e.disposed||this.#e.endDrag(t.record.node,{source:{...t.source},dropEffect:e},t.endTopic).catch(r=>this.#w(r))}#w(e){this.#e.binding.reportError(e,"Drag and drop failed")}dispose(){this.#g();for(let e of pm)this.#t.removeEventListener(e,this);this.#t.defaultView.removeEventListener("pagehide",this.#i)}};var Mi=class extends un{static renderType="object";#e=new Set;#t=new WeakSet;#r=new WeakMap;#n=new WeakMap;#o=new WeakMap;constructor(e,t,r,{binding:o}={}){if(super(e),!(e instanceof Ze)||!(t instanceof Ae)||r?.nodeType!==1)throw new TypeError("GramlotRenderer requires a BuilderBase, GramlotBuilderBag and HTML destination");if(!(o instanceof wo))throw new TypeError("GramlotRenderer requires a BindingRuntime");if(!(t._builder instanceof Ze))throw new TypeError("SourceBag requires builder ownership");this._binding=o,this.source=t,this.destination=r,this.html=new Es({uploadContext:()=>({gramlot:o.gramlot,window:r.ownerDocument.defaultView}),metadataAttributes:["__ref"],format:(i,a)=>o.gramlot.format(i,a),reportError:(i,a,s)=>{this.records.has(i)&&o.reportError(a,s)},callLogic:(i,a,s)=>{let{group:l,method:u}=o.gramlot.src.logicRegistry.resolve(a,i);return u.call(l,i,s)},invokeScript:(i,a,s,l)=>Ut(o,i,a,s,l,i.parentNode._getMeta("gramlot_component").childParameters[a].inline)}),this.records=new Map,this.references=new bi(t),this.pending=[],this.building=!1,this.disposed=!1,this.elements=new WeakMap,this.dragPreparation=new Ws(this),this.instanceId=J(),this.radioGroups=new vs(this),this.dragDrop=new Ys(this),this.subscription=`html-source-renderer-${this.instanceId}`,t.subscribe(this.subscription,{any:i=>this.receive(i)})}get binding(){return this._binding}prepareDrag(e,t){return this.dragPreparation.prepare(e,t)}checkDropTarget(e,{dropValues:t,item:r,path:o,source:i,selfdrop:a,dropEffect:s,dataAvailable:l,placement:u}){let c=this.records.get(e);if(!c)return!1;if(!c.resolved.dropTargetCb)return!0;let d=this.html.callLogic(e,c.resolved.dropTargetCb,{dropValues:t,item:r,path:o,source:i,selfdrop:a,dropEffect:s,dataAvailable:l,...u===void 0?{}:{placement:u}});if(typeof d!="boolean")throw new TypeError("dropTargetCb must return a boolean synchronously");return d}async invokeDrop(e,{dropValues:t,item:r,path:o,source:i,selfdrop:a,dropEffect:s,dataAvailable:l,placement:u}){let c=this.records.get(e);!c||!c.resolved.onDrop||Object.keys(t).length===0||await this.html.callLogic(e,c.resolved.onDrop,{dropValues:t,item:r,path:o,source:i,selfdrop:a,dropEffect:s,dataAvailable:l,...u===void 0?{}:{placement:u}})}async endDrag(e,{source:t,dropEffect:r},o){let i={source:t,dropEffect:r},a=[],s=this.records.get(e);try{s&&!s.binding.closed&&s.resolved.onDragEnd&&await this.html.callLogic(e,s.resolved.onDragEnd,i)}catch(l){a.push(l)}try{this.binding.gramlot.publish(o,i)}catch(l){a.push(l)}if(a.length)throw new AggregateError(a,"Drag completion notification failed")}get inlineCompiler(){return this.binding.inlineCompiler}evaluateExpressions(e,t){let r=this.#n.get(e)??super.evaluateExpressions(e,t),o=e._getMeta("gramlot_component");if(o?.presentationDefaults.length){let i=e.getAttr();this.#o.set(e,Object.fromEntries(Object.entries(r).filter(([a])=>Object.hasOwn(i,a)&&o.presentationDefaults.some(s=>a.startsWith(s)))))}if(this.html.hasLabelbox(e)||o?.presentationDefaults.length){let i=[];for(let a=e.parentNode;a;a=a.parentNode)this.#o.has(a)&&i.unshift(this.#o.get(a));r=Object.assign({},...i,r)}return this.#n.delete(e),this.#r.set(e,r),r}render(e,t={}){if(!(e instanceof ln))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(e._getMeta("data_element")||this.#t.has(e)||!this.binding.bindingFor(e)&&this.#l(e))return null;if(e.nodeTag)this.html.validate(e,e._getMeta("subbuilder")?e.parentBag._builder:e.builder);else if(!(e.value instanceof I))throw new TypeError("Source fragments must contain child SourceBags");return e.nodeTag?super.render(e,t):this.renderFragment(e,t)}renderFragment(e,{document:t=this.destination.ownerDocument,...r}={}){let o=t.createDocumentFragment(),i={node:e,binding:this.#m(e),container:null,parent:null,children:new Set,cleanup:[],start:t.createComment("source-fragment"),end:t.createComment("/source-fragment")};this.records.set(e,i),this.elements.set(o,i),o.append(i.start);for(let a of e.value.getNodes()){let s=this.render(a,{document:t,...r});if(s===null)continue;o.append(s);let l=this.elements.get(s);l&&(l.parent=i,i.children.add(a))}return o.append(i.end),o}renderedItem(e,t,r,{tag:o,document:i=this.destination.ownerDocument}={}){let a=r;t=this.expressionValue(e,t),this.getRender(e.builder)===this&&(a=this.restoreNativeAttributes(e,r),e._getMeta("gramlot_component")||([t,a]=vi(t,a,(h,p)=>this._binding.gramlot.format(h,p)))),a=this.componentAttributes(e,a);let s=Array.isArray(t)?t:[],l=Array.isArray(t)?a._text:t,u=this.#r.get(e),c={node:e,binding:this.#m(e),container:null,parent:null,children:new Set,cleanup:[],resolved:u,...this.html.create(e,i,o,a,u.visible??null)};this.html.compose(c,l,s),c.labelbox&&c.cleanup.push(()=>c.labelbox.menu?.dispose()),c.shape=je.shape(c.element,u),this.records.set(e,c),this.elements.set(c.element,c),this.elements.set(c.presentation,c);let d=je.for(c.binding,c);(d||c.element.namespaceURI===Fe&&c.element.localName==="input")&&c.cleanup.push(()=>c.control?.detach()),d&&(c.control=d,d.attach(),this.#f(c,e,a,null));let f=xs.for(c.binding,c);if(f&&(c.button=f,f.attach(),c.cleanup.push(()=>f.detach())),e.nodeTag==="menu"&&(c.menu=new ks(c.binding,c.element),c.menu.attach(),c.cleanup.push(()=>c.menu.detach())),e.nodeTag==="groupletCard"){let h=new Ts(c.binding,c.element);h.attach(),c.cleanup.push(()=>h.detach())}this.#p(c),this.references?.register(e,c.element);for(let h of s){let p=this.elements.get(h);p&&(p.parent=c,p.container=c.element,c.children.add(p.node))}return c.presentation}validateCandidate(e,{replacingNode:t=null}={}){if(!(e instanceof Ae))throw new TypeError("Source values must be GramlotBuilderBags");let r=new Set,o=s=>{if(!r.has(s)){r.add(s);for(let l of this.records.get(s)?.children??[])o(l);if(s.value instanceof I)for(let l of s.value.getNodes())o(l)}};for(let s of this.records.get(t)?.children??[])o(s);if(t?.value instanceof I)for(let s of t.value.getNodes())o(s);this.#i(e,t?t.nodeTag:null),gc(e),this.references?.validate(e,r);let i=new Set,a=s=>{for(let l of s.getNodes()){let u=l.getAttr("nodeId");if(u!=null){let c=this.binding.nodeIds.get(u);if(i.has(u)||c&&c!==l&&!r.has(c))throw new Error(`Duplicate nodeId '${u}'`);i.add(u)}l.value instanceof I&&a(l.value)}};return a(e),e}#i(e,t=null){let r=new Set,o=(i,a=null)=>{if(!(i instanceof Ae)||r.has(i))throw new TypeError("Source values must be unshared, acyclic GramlotBuilderBags");if(!(i._builder instanceof Ze))throw new TypeError("SourceBag requires builder ownership");r.add(i);for(let s of i.getNodes()){if(!(s instanceof ln))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(!(s.builder instanceof Ze))throw new TypeError("SourceBagNode requires builder ownership");if(s.resolver)throw new TypeError("Source resolvers are outside this port");if(s._getMeta("data_element"))s.builder.validateNode(s);else if(s.nodeTag){let l=s._getMeta("subbuilder")?i._builder:s.builder;this.html.validate(s,l),s._getMeta("subbuilder")||s.builder.validateParent(s.nodeTag,a)}else{if(!(s.value instanceof I))throw new TypeError("Source fragments must contain child SourceBags");if(Object.keys(s.attr).some(l=>l!=="_meta"))throw new TypeError("Fragment attributes are unsupported")}s.value instanceof I&&o(s.value,s._getMeta("subbuilder")?null:s.nodeTag??a)}};o(e,t)}freeze(e){e=ae(e);let t=this.records.get(e);if(!t||this.disposed)throw new Error("Freeze requires a mounted Source node");t.frozen=!0}unfreeze(e){e=ae(e);let t=this.records.get(e);if(!t||this.disposed)throw new Error("Unfreeze requires a mounted Source node");let r=o=>{delete o.frozen;for(let i of o.children)r(this.records.get(i))};r(t),!this.#a(e)&&(this.attached(e)?this.#g(e):this.remove(e))}#a(e){for(;e;){let t=this.records.get(e);if(t?.frozen)return!0;e=e.parentBag?.parentNode??t?.parent?.node}return!1}receive(e){if(this.disposed)return;let t=r=>this.#e.has(r)||e.evt==="del"&&r.nodeTag==="dataSetter";if(Array.isArray(e.node)){let r=e.node.filter(o=>!t(o));if(!r.length)return;e={...e,node:r}}else if(t(e.node))return;if(this.pending.push(e),!this.building){this.building=!0;try{for(;this.pending.length;){let r=this.pending.shift();if(r.evt!=="del"&&!this.attached(r.node))continue;r.evt!=="del"&&r.evt!=="upd_attrs"&&this.#u(r);let o=this.binding.handleSourceEvent(r);try{this.#s(r,o)}catch(i){if(!o.length)throw i;o.push(i)}if(this.binding.refreshSourceTrees(),o.length)throw o.length===1?o[0]:new AggregateError(o,"Source cleanup failed")}}catch(r){throw this.pending.length=0,r}finally{this.building=!1}}}#s(e,t){if(e.evt==="del"){for(let r of Array.isArray(e.node)?e.node:[e.node]){if(this.#a(r))continue;let o=this.records.get(r)?.parent??null;try{this.remove(r)}catch(i){t.push(i)}this.#h(o)}return}if(!this.#a(e.node))if(e.evt==="ins")this.insert(e.node);else if(e.evt.startsWith("upd_"))this.update(e.node,e.evt);else throw new Error(`Unsupported Source event: ${e.evt}`)}attached(e){let t=e.parentBag;for(;t&&t!==this.source;)t=t.parentNode?.parentBag;return t===this.source}#l(e){let t=new Set(this.pending.flatMap(r=>Array.isArray(r.node)?r.node:[r.node]));for(let r=e;r;r=r.parentBag?.parentNode)if(t.has(r))return!0;return!1}#u(e){let t=r=>{if(!(r instanceof ln))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(r.value instanceof I){if(!(r.value instanceof Ae))throw new TypeError("Source values must be GramlotBuilderBags");for(let o of r.value.getNodes())t(o)}};t(e.node)}unmountView(e){this.#t.add(e),this.remove(e)}mountView(e){this.#t.delete(e),this.insert(e)}insert(e){if(!this.attached(e)||this.records.has(e))return;for(let a=e;a;a=a.parentNode)if(this.#t.has(a))return;if(e._getMeta("data_element")){this.records.get(e.parentBag?.parentNode)?.button?.refresh(),this.binding.branchBuilt(e);return}let t=this.records.get(e.parentBag?.parentNode),r=t?.element??t?.container??this.destination,o=e.parentBag.getNodes(),i=t?.end??null;for(let a=o.indexOf(e)+1;a<o.length;a++){let s=this.records.get(o[a]);if(s){i=s.presentation??s.start;break}}this.buildNode(e,r,i,t)}buildNode(e,t,r=null,o=null){this.#e.add(e);let i;try{i=this.render(e,{document:t.ownerDocument})}catch(s){this.#c(e,s)}finally{this.#e.delete(e)}let a=this.records.get(e);return t.insertBefore(i,r),a.parent=o,this.assignContainer(a,t),o?.children.add(e),this.#h(o),this.binding.branchBuilt(e),a}#c(e,t){let r=[t],o=[],i=a=>{if(o.push(a),a.value instanceof I)for(let s of a.value.getNodes())i(s)};i(e);for(let a of o.reverse())try{this.remove(a)}catch(s){r.push(s)}throw r.length===1?t:new AggregateError(r,"Source build and cleanup failed")}mountDestination(e,t){let r=this.records.get(e);if(!r?.presentation||t?.nodeType!==1)throw new TypeError("mountDestination requires a mounted element and an HTML destination");if(r.presentation.contains(t))throw new Error("Destination cannot be inside the moved presentation");let o=r.parent;return this.remove(e),this.buildNode(e,t,null,o)}assignContainer(e,t){e.container=t;let r=e.element??t;for(let o of e.children){let i=this.records.get(o);i&&this.assignContainer(i,r)}}update(e,t){let r=this.records.get(e);if(!r){this.insert(e);return}let o=e.value==null||["string","number","boolean"].includes(typeof e.value),i=t==="upd_value"&&o&&r.element&&r.children.size===0&&this.html.matches(r,e);(t==="upd_attrs"||i)&&r.element&&this.html.matches(r,e)?(e.nodeTag&&this.html.validate(e,e._getMeta("subbuilder")?e.parentBag._builder:e.builder),this.project(e),t==="upd_attrs"&&this.records.get(e)===r&&(this.references?.remove(e),this.references?.register(e,r.element))):this.#g(e)}project(e,t=null){let r=this.records.get(e);if(!r?.element||!this.attached(e))return;let o=this.getRender(e.builder),i=this.#o.get(e),[a,s]=e.rootBuilder.runtimeValues(e),[,l]=o._handleMeta(e,s),u=this.#r.get(e),c=r.element.namespaceURI===Fe&&r.element.localName==="input"&&!Object.is(r.resolved.type,u.type),d=r.element.namespaceURI===Fe&&["input","select"].includes(r.element.localName)&&!!r.resolved.multiple!=!!u.multiple,f=r.resolved.group,h=r.control instanceof po&&!Object.is(f??null,u.group??null);if((c||d||h)&&this.#a(e))return;if(r.shape!==je.shape(r.element,u)){if(this.#a(e))return;this.#n.set(e,u);try{this.#g(e)}finally{this.#n.delete(e)}return}let p=c?je.classFor(r.element,u):null,m=c&&(r.control?.constructor??null)!==p,b=(c||d&&r.element.localName==="input")&&!m&&r.control&&Object.is(r.resolved.value,u.value);if(m&&(r.control?.detach(),r.control=null),h&&!m&&u.group!=null&&e.getAttr("name")!=null)throw new TypeError(`${e.nodeTag} '${e.label}': name and group are two names`);r.resolved=u;let w=e._getMeta("subbuilder")?l:o.adaptAttrs(l),_=e.value instanceof I,y=_?[]:this.expressionValue(e,a);if(o===this&&(w=this.restoreNativeAttributes(e,w),e._getMeta("gramlot_component")||([y,w]=vi(y,w,(D,k)=>this._binding.gramlot.format(D,k)))),w=this.componentAttributes(e,w),this.html.update(r,e,w,_?w._text:y,u.visible??null,t),m&&p&&(r.control=new p(r.binding,r),r.control.attach()),h&&!m){r.control.refresh(f??null),this.records.get(e)===r&&!r.binding.closed&&this.project(e);return}b||this.#f(r,e,w,t),r.control?.refresh(),r.button?.refresh(),r.menu?.refresh(),this.#p(r);let x=this.#o.get(e);if(x){let D=new Set([...Object.keys(i??{}),...Object.keys(x)].filter(k=>!Object.is(i?.[k],x[k])));D.size&&this.#d(e,D)}(r.element.localName==="option"||r.element.localName==="optgroup")&&this.#h(r.parent)}#d(e,t){if(e.value instanceof I)for(let r of e.value.getNodes()){let o=r._getMeta("gramlot_component"),i=r.getAttr(),a=t;o?.presentationDefaults.length?a=new Set([...t].filter(s=>!Object.hasOwn(i,s))):this.html.hasLabelbox(r)&&[...t].some(s=>!Object.hasOwn(i,s))&&this.project(r),a.size&&this.#d(r,a)}}componentAttributes(e,t){let r=e._getMeta("gramlot_component"),o=e.parentNode?._getMeta("gramlot_component")?.childParameters;if(!r&&!o)return t;let i=this.#r.get(e),a=Object.fromEntries([...new Set([...Object.keys(r?.parameters??{}),...Object.keys(o??{}),...Object.keys(i).filter(s=>s.startsWith("validate_"))])].filter(s=>Object.hasOwn(i,s)).map(s=>[s,i[s]]));return{...t,...a}}#f(e,t,r,o){if(!e.control)return;let i=t.getAttr("value")!=null;(i||e.valueDeclared)&&e.control.project(r.value??null,o),e.valueDeclared=i}#p(e){let t=new Map(Si.declared(e.node).map(r=>[r[0],r]));if(!e.events){if(!t.size)return;e.events=new Map,e.cleanup.push(()=>{for(let r of e.events.values())r.detach();e.events.clear()})}for(let[r,o]of[...e.events])t.get(r)?.[2]!==o.handler&&(o.detach(),e.events.delete(r));for(let[r,[,o,i]]of t){if(e.events.has(r))continue;let a=new Si(e.binding,e,o,i,r);a.attach(),e.events.set(r,a)}}#h(e){for(let t=e;t;t=t.parent){if(t.control instanceof Di){this.project(t.node);return}if(t.element&&t.element.localName!=="optgroup")return}}getDomNode(e){let t=ae(e),r=this.records.get(t);return r&&this.attached(t)?r.element??null:null}getBaseSourceNode(e){for(let t=e;t;t=t.parentNode){let r=t.nodeType===1?this.elements.get(t):null;if(r)return this.attached(r.node)?r.node:null}return null}#m(e){let t=this.binding.bindingFor(e);if(!t)throw new Error(`${e.nodeTag??"fragment"} '${e.label}': rendered without an open NodeBinding`);return t}#g(e){let t=this.records.get(e),r=t.presentation?.nextSibling??t.end?.nextSibling??null,o=t.container,i=t.parent,a=null;try{this.remove(e)}catch(s){a=s}try{this.buildNode(e,o,r,i)}catch(s){throw a?new AggregateError([a,s],"Source replacement cleanup and commit failed"):s}if(a)throw a}onDispose(e,t){let r=this.records.get(e);if(!r)throw new Error("Source node is not mounted");return r.cleanup.push(t),()=>{let o=r.cleanup.indexOf(t);o!==-1&&r.cleanup.splice(o,1)}}remove(e){let t=this.records.get(e);if(!t)return;let r=[];for(let o of[...t.children])try{this.remove(o)}catch(i){r.push(i)}for(let o of t.cleanup.splice(0).reverse())try{o()}catch(i){r.push(i)}if(this.references?.remove(e),t.element&&this.elements.delete(t.element),t.presentation&&this.elements.delete(t.presentation),t.presentation?.remove(),t.start?.remove(),t.end?.remove(),t.parent?.children.delete(e),this.records.delete(e),this.#r.delete(e),this.#o.delete(e),r.length)throw new AggregateError(r,"Source cleanup failed")}dispose(){if(this.disposed)return;this.disposed=!0,this.dragDrop.dispose(),this.source.unsubscribe(this.subscription,{any:!0}),this.pending.length=0;let e=[],t=[...this.records.entries()].filter(([,r])=>!r.parent).map(([r])=>r);for(let r of t)try{this.remove(r)}catch(o){e.push(o)}if(e.length)throw new AggregateError(e,"Renderer cleanup failed")}};var B2=new Set(["page","constructor"]);function mm(n,e){if(n===null)return[];let t=n.split("/");for(let r of t)if(B2.has(r))throw new Error(`${e}: a logic group cannot be named '${r}' (group '${n}')`);return t}var $2=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]);function M2(n){return/^[\w$]/.test(n)?$2.has(n):n!==")"&&n!=="]"}function P2(n,e){let t=!1;for(let r=e+1;r<n.length;r++){let o=n[r];if(o===`
|
|
233
|
+
`)return-1;if(o==="\\"){r++;continue}if(o==="[")t=!0;else if(o==="]")t=!1;else if(o==="/"&&!t)return r}return-1}function L2(n){let e=0,t="",r="";for(let o=n.indexOf("{");o<n.length;o++){let i=n[o];if(i==="/"&&n[o+1]==="/"){if(o=n.indexOf(`
|
|
234
|
+
`,o),o<0)break;continue}if(i==="/"&&n[o+1]==="*"){let a=n.indexOf("*/",o+2);if(a>=0){o=a+1;continue}}if(i==="/"&&M2(r)){let a=P2(n,o);if(a>=0){o=a,r=")";continue}}if(i==='"'||i==="'"||i==="`"){let a=o+1;for(;a<n.length&&n[a]!==i;)a+=n[a]==="\\"?2:1;e===1&&(t+=n.slice(o+1,a)==="constructor"?" constructor":' ""'),o=a,r=")";continue}if(/[\w$]/.test(i)){let a=o+1;for(;a<n.length&&/[\w$]/.test(n[a]);)a++;e===1&&(t+=n.slice(o,a)),r=n.slice(o,a),o=a-1;continue}if(/\s/.test(i)||(r=i),i==="{"){++e===2&&(t+=" {}");continue}if(i==="}"){e--;continue}e===1&&(t+=i)}return/(?<![\w$.#])(?<!\bstatic\s+)constructor\s*\(/.test(t)}function gm(n,e){if(n===void 0)return[];if(typeof n!="function"||!/^class\b/.test(Function.prototype.toString.call(n)))throw new Error(`${e}: the module exports no class Logic`);if(Object.getPrototypeOf(n)!==Function.prototype||Object.getPrototypeOf(n.prototype)!==Object.prototype)throw new Error(`${e}: class Logic cannot extend another class`);if(L2(Function.prototype.toString.call(n)))throw new Error(`${e}: class Logic cannot declare a constructor; state lives on the group or the page`);let t=[];for(let r of Reflect.ownKeys(n.prototype)){if(r==="constructor")continue;if(typeof r=="symbol")throw new Error(`${e}: class Logic cannot declare symbol keys (${String(r)})`);let o=Object.getOwnPropertyDescriptor(n.prototype,r);if(o.get||o.set)throw new Error(`${e}: class Logic cannot declare the accessor '${r}'`);if(typeof o.value!="function")throw new Error(`${e}: Logic.prototype.${r} is not a method`);if(r==="page")throw new Error(`${e}: a logic method cannot be named 'page'`);t.push([r,o.value])}return t}function bm(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}var bn=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get page(){return this.#t}},_o=class{#e;#t=new Map;constructor(e){this.#e=e,e.logic=new bn(this,e)}get gramlot(){return this.#e}static check(e){let t=new Map;for(let{group:r,resource:o}of e){let i=mm(r,o);for(let a=0;a<i.length;a++){let s=i.slice(0,a).join("/");t.has(s)||t.set(s,new Set),t.get(s).add(i[a])}}for(let{logicClass:r,group:o,resource:i}of e){let a=t.get(o??"")??new Set;for(let[s]of gm(r,i))if(a.has(s))throw new Error(`${i}: the logic method '${s}' has the name of a child group`)}}register(e,{group:t=null,resource:r}){let o=mm(t,r),i=gm(e,r),a=this.#e.logic;for(let s of o){let l=Object.getOwnPropertyDescriptor(a,s)?.value;if(l===void 0){let u=new bn(this,this.#e);bm(a,s,u),a=u}else if(l instanceof bn)a=l;else throw new Error(`${r}: the group '${s}' has the name of a logic method`)}for(let[s,l]of i){if(Object.getOwnPropertyDescriptor(a,s)?.value instanceof bn)throw new Error(`${r}: the logic method '${s}' has the name of a child group`);bm(a,s,l)}this.#t.has(a)||this.#t.set(a,[]),this.#t.get(a).push(r)}resolve(e,t){let r=e.split("."),o=r.pop(),i=this.#e.logic;for(let s=0;s<r.length;s++)if(i=Object.getOwnPropertyDescriptor(i,r[s])?.value,!(i instanceof bn))throw new Error(`${t.nodeTag} '${t.label}': named logic '${e}' not found: no resource was registered for the group '${r.slice(0,s+1).join("/")}'`);let a=Object.getOwnPropertyDescriptor(i,o)?.value;if(typeof a!="function"){let s=this.#t.get(i)??[],l=r.length?`the group '${r.join("/")}'`:"the page logic";throw new Error(`${t.nodeTag} '${t.label}': named logic '${e}' not found: ${l} has no method '${o}' (resources: ${s.join(", ")||"none"})`)}return{group:i,method:a}}};var Pi=class extends Ke{constructor(e,{collections:t,destination:r,subscriptions:o,nameSyntax:i}){super(e),e.src=this,this.logicRegistry=new _o(e),this.builder=new Oe(null,{collections:t,nameSyntax:i}),this.binding=new wo(e,{subscriptions:o}),this.builder.binding=this.binding,this.binding.attach(),this.source=this.builder.source,this.renderer=new Mi(this.builder,this.source,r,{binding:this.binding})}startSource(e){if(!["ready","failed"].includes(this.gramlot.state))throw new Error(`Cannot start embedded Source while Gramlot is ${this.gramlot.state}`);try{return this.mountMainSource(e)}catch(t){throw this.gramlot.state="failed",t}}mountMainSource(e,t=null){let r=this.prepareSource(e);if(this.renderer.validateCandidate(r),t!==null){if(!(t instanceof E)||t instanceof I)throw new TypeError("Initial page data must be a Data Bag");for(let o of t.getNodes())this.builder.data.setItem([o.label],o.getValue(),o.attr,">",!1,!1)}try{this.source.setItem("main",r)}catch(o){throw this.binding.bindingFor(this.source.getNode("main"))||this.source.popNode("main"),o}return this.gramlot.state="started",this.binding.pageStarted(),this.binding.subscriptions.ready(),this.gramlot}prepareSource(e,t=this.builder){if(e instanceof I){if(!(e instanceof Ae))throw new TypeError("Source values must be GramlotBuilderBags");return e.bindBuilder(t).activateCode()}if(typeof e!="string")throw new TypeError("Source value did not decode to SourceBag");let r=zu(e,t);if(!(r instanceof Ae))throw new TypeError("Source values must be GramlotBuilderBags");return r.activateCode()}async remoteSource(e,t,r={}){if(!this.gramlot.rpc.transport?.call)throw new Error("Remote Source is unavailable without a server transport");let i=this.binding.bindingFor(e);if(this.gramlot.state!=="started"||!i)throw new Error("Remote Source target is not mounted");return await e.requests.submit(t,r,a=>this.#e(e,i,a))??!1}async#e(e,t,r){if(t.closed||this.gramlot.state==="disposed")return!1;let o=!1,i=()=>this.gramlot.state!=="disposed"&&!r.ignored&&!t.closed;try{let a=await t.call("source",r);if(!i())return!1;let s=this.prepareSource(a,e.builder);return i()?(this.renderer.validateCandidate(s,{replacingNode:e}),o=!0,e.setValue(s,!0,{_text:null},!0),t.remote?.fragmentMounted(r.method,r.text),!0):!1}catch(a){if(!o&&!i())return!1;throw a}}};var Li=class extends Ke{setTouchMode(e="auto"){if(!["auto","on","off"].includes(e))throw new TypeError(`Invalid touch mode: ${e}`);let t=this.gramlot.src.renderer.destination.ownerDocument.documentElement;e==="auto"?t.removeAttribute("data-gramlot-touch"):t.setAttribute("data-gramlot-touch",e)}navigate(e){if(typeof e!="string"||!e)throw new TypeError("Navigation requires an absolute HTTP(S) URL");let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw new TypeError("Navigation requires an HTTP(S) URL without credentials");this.gramlot.src.renderer.destination.ownerDocument.defaultView.location.assign(t.href)}reference(e){return this.gramlot.src.renderer.references.resolve(e)}getBaseSourceNode(e){return this.gramlot.src.renderer.getBaseSourceNode(e)}getDomNode(e){return this.gramlot.src.renderer.getDomNode(e)}};var Xs=class extends Ke{#e=new Map;#t=new WeakSet;#r=new WeakMap;#n=0;#o=!1;ready(){this.gramlot._frames.ready()}subscribe(e,t){if(this.#s(),this.#a(e),typeof t!="function")throw new TypeError("subscribe requires a callback");let r=Object.freeze({});return this.#t.add(r),this.#e.has(e)||this.#e.set(e,new Map),this.#e.get(e).set(r,t),r}unsubscribe(e){if(!this.#t.has(e))throw new TypeError("Unknown subscription registration");for(let[t,r]of this.#e)r.delete(e)&&!r.size&&this.#e.delete(t)}publish(e,t={},r={}){if(this.#s(),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("publish requires one object of named data");if(typeof e=="string")return this.#i(e,t,r);if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("publish requires a topic string or descriptor");if(Object.keys(e).some(a=>!["topic","nodeId","parent","iframe","pageId","server"].includes(a)))throw new Error("This publication route is not implemented yet");if(this.#a(e.topic),e.parent!==void 0&&typeof e.parent!="boolean")throw new TypeError("parent must be boolean");if(e.server!==void 0&&typeof e.server!="boolean")throw new TypeError("server must be boolean");if(e.iframe==="*")throw new Error("Recursive iframe broadcast is not implemented yet");if(e.pageId!==void 0&&(typeof e.pageId!="string"||!e.pageId))throw new TypeError("pageId must be a nonempty string");if((e.parent||e.iframe!==void 0||e.pageId!==void 0)&&Object.hasOwn(e,"nodeId"))throw new Error("Interframe node addressing is not implemented yet");let i=null;if(e.server===!0){if(["parent","iframe","nodeId"].some(a=>Object.hasOwn(e,a)))throw new Error("Server publication cannot combine window or node selectors");if(!this.gramlot._pageStore)throw new Error("Server publication requires a WebSocket channel");i=this.gramlot._pageStore.preparePublish(e,t)}else(e.parent||e.iframe!==void 0||e.pageId!==void 0)&&(i=this.gramlot._frames.prepare(e,t));if(Object.hasOwn(e,"nodeId")){let a=this.gramlot.src.binding.nodeIds.get(e.nodeId);if(!a)throw new Error(`nodeId not found: ${e.nodeId}`);return this.publishNode(a,e.topic,t)}return this.#i(e.topic,t),i?.()}topicFor(e,t){this.#a(t),e=ae(e);let r=this.gramlot.src.binding.bindingFor(e);if(!r||r.closed)throw new Error("Topic target is not an active Source node of this page");let o=e.getAttr("nodeId");return o==null&&(this.#r.has(e)||this.#r.set(e,`gramlot-self-${++this.#n}`),o=this.#r.get(e)),`${o}_${t}`}publishNode(e,t,r={}){return this.publish(this.topicFor(e,t),r)}subscribeNode(e,t){let r=[];for(let[o,i]of Object.entries(e.getAttr())){let a=o.startsWith("selfsubscribe_")?"selfsubscribe_":o.startsWith("subscribe_")?"subscribe_":null;if(!a)continue;let s=a==="selfsubscribe_"?this.topicFor(e,o.slice(a.length)):o.slice(a.length);this.#a(s),r.push([s,t(o,i,s)])}return this.#s(),r.map(([o,i])=>{let a=this.subscribe(o,i);return{close:()=>this.unsubscribe(a)}})}dispose(){this.#o=!0,this.#e.clear()}#i(e,t,r={}){this.#a(e);let o=this.#e.get(e);if(o)for(let[i,a]of[...o]){if(this.#o)break;o.has(i)&&a(t,{...r})}}#a(e){if(typeof e!="string"||!e)throw new TypeError("A topic must be a nonempty string")}#s(){if(this.#o)throw new Error("Gramlot subscriptions are disposed")}};var Zs=class extends fe{constructor(e,t,r){super({cacheTime:r}),this.handler=e,this.name=t,this.failed=!1,this.writing=!1,this.request=null,this.revision=0,this.received=0}resolve({static:e=!1}={}){return!e&&!this.handler.disposed&&!this.writing&&!this.request&&!this.failed&&!this._node.attr.watching&&this.expired&&this.handler.refresh(this.name),this.cachedValue}reset(){super.reset(),this.failed=!1,this.revision++}};var wm=["appinfo","location"],_m={UNAVAILABLE:"unavailable",PERMISSION_DENIED:"denied",TIMEOUT:"error",FAILED:"error",CANCELLED:"cancelled"};function oe(n){let e=Object.hasOwn(_m,n?.code)?n.code:"FAILED";return{status:_m[e],error:e==="CANCELLED"?null:{code:e,message:String(n?.message??"Device operation failed")}}}var Fi=class extends Ke{#e=null;#t=null;#r=null;#n=null;#o=null;#i=null;#a=new Map;#s=new Map;#l=null;#u=null;#c=null;#d=null;#f=null;#p=null;#h=null;constructor(e){super(e),this.provider=null,this.disposed=!1,this.monitor=null,this.retiring=null,this.resolvers=new Map,this.cleanup=Promise.resolve()}installData(){let{gramlot:e}=this;e.data.setItem("_gramlot.device.database",null,{status:"idle",error:null}),e.data.setItem("_gramlot.device.orientation",null,{status:"idle",error:null,listening:!1});for(let m of["gyroscope","accelerometer"])e.data.setItem(`_gramlot.device.${m}`,null,{enabled:!1,watching:!1,status:"idle",error:null}),e.data.getNode(`_gramlot.device.${m}`).setAttr({error:null},!1,!0,!1),this.#s.set(m,{node:e.data.getNode(`_gramlot.device.${m}`),stream:null,cleanup:Promise.resolve()});for(let m of wm){let b=`_gramlot.device.${m}`,w={status:"idle",error:null,cacheTime:m==="appinfo"?-1:5};m==="location"&&Object.assign(w,{enabled:!1,watching:!1}),e.data.setItem(b,null);let _=e.data.getNode(b);_.setAttr(w,!1,!0,!1);let y=new Zs(this,m,w.cacheTime);_.resolver=y,this.resolvers.set(m,y)}e.data.setItem("_gramlot.device.clipboard",null,{status:"idle",error:null,text:"",copy:null,paste:null,operation:null});let t=e.data.getNode("_gramlot.device.clipboard");e.data.setItem("_gramlot.device.camera",null,{status:"idle",error:null,capture:null,choose:null});let r=e.data.getNode("_gramlot.device.camera");e.data.setItem("_gramlot.device.barcode",null,{status:"idle",error:null,scan:null});let o=e.data.getNode("_gramlot.device.barcode");e.data.setItem("_gramlot.device.biometrics",null,{status:"idle",error:null,verify:null});let i=e.data.getNode("_gramlot.device.biometrics"),a=new E;a.setItem("request",new E);for(let m of["scheduled","received","action"])a.setItem(m,null);e.data.setItem("_gramlot.device.notifications",a,{status:"idle",error:null,schedule:null,listening:!1,listenerError:null});let s=e.data.getNode("_gramlot.device.notifications"),l=new E;for(let m of["registration","received","action"])l.setItem(m,null);e.data.setItem("_gramlot.device.push",l,{status:"idle",error:null,register:null,listening:!1,listenerError:null});let u=e.data.getNode("_gramlot.device.push"),c=new E;c.setItem("request",null),e.data.setItem("_gramlot.device.links",c,{listening:!1,listenerError:null});let d=new E;d.setItem("request",null),e.data.setItem("_gramlot.device.shortcuts",d,{listening:!1,listenerError:null}),e.data.setItem("_gramlot.device.network",null,{status:"idle",error:null,listening:!1});let f=new E;f.setItem("active",null),f.setItem("event",null),f.setItem("sequence",0),e.data.setItem("_gramlot.device.lifecycle",f,{status:"idle",error:null,listening:!1}),e.data.setItem("_gramlot.device.haptics",null,{status:"idle",error:null,impact:null,style:"medium",vibrate:null,duration:600});let h=e.data.getNode("_gramlot.device.haptics");e.data.setItem("_gramlot.device.audio",null,{status:"idle",error:null,recording:!1,start:null,stop:null,cancel:null,share:null,shareStatus:"idle",shareError:null,shareActivity:null});let p=e.data.getNode("_gramlot.device.audio");e.data.subscribe("gramlot.device",{update:m=>{if(!this.disposed){for(let[b,w]of this.#s)if(m.node===w.node&&m.attrs_diff?.enabled){if(typeof w.node.attr.enabled!="boolean")throw new TypeError("Device enabled must be boolean");this.#g(b,w)}m.node===t&&m.fired&&(m.attrs_diff?.copy?.new===!0&&this.#v(t,"copy"),m.attrs_diff?.paste?.new===!0&&this.#v(t,"paste")),m.node===p&&m.fired&&(m.attrs_diff?.start?.new===!0&&this.#b(p),m.attrs_diff?.stop?.new===!0&&this.#w(p),m.attrs_diff?.cancel?.new===!0&&this.#y(p),m.attrs_diff?.share?.new===!0&&this.#_(p)),m.node===h&&m.fired&&m.attrs_diff?.impact?.new===!0&&this.#k(h),m.node===h&&m.fired&&m.attrs_diff?.vibrate?.new===!0&&this.#E(h),m.node===o&&m.fired&&m.attrs_diff?.scan?.new===!0&&this.#S(o),m.node===r&&m.fired&&m.attrs_diff?.choose?.new===!0&&this.#T(r,"choose"),m.node===r&&m.fired&&m.attrs_diff?.capture?.new===!0&&this.#T(r,"capture"),m.node===i&&m.fired&&m.attrs_diff?.verify?.new===!0&&this.#C(i),m.node===s&&m.fired&&m.attrs_diff?.schedule?.new===!0&&this.#N(s),m.node===u&&m.fired&&m.attrs_diff?.register?.new===!0&&this.#O(u);for(let b of this.resolvers.values()){if(m.node!==b._node)continue;let{cacheTime:w}=m.node.attr;if(typeof w!="number"||!Number.isFinite(w)||w<0&&w!==-1)throw new TypeError("Device cacheTime must be -1 or a nonnegative number of seconds");if(b.cacheTime=w,b.name==="location"){if(typeof m.node.attr.enabled!="boolean")throw new TypeError("Device enabled must be boolean");this.reconcile()}}}}})}attach(e,{dispose:t=null}={}){if(this.assertLive(),this.provider)throw new Error("A device provider is already attached");if(!Array.isArray(e.capabilities)||e.capabilities.some(r=>![...wm,"camera","biometrics","notifications","push","shortcuts","barcode","network","lifecycle","haptics","audio","clipboard","links","orientation","gyroscope","accelerometer","database"].includes(r)))throw new TypeError("Unknown device provider capability");if(t!==null&&typeof t!="function")throw new TypeError("Device attachment dispose must be a function");this.releaseProvider=t,this.provider=e,this.installData(),this.reconcile(),this.#m("orientation",(r,o)=>e.startOrientationEvents(r,o),(r,o)=>{if(!["portrait","landscape"].includes(o?.type)||!["primary","secondary"].includes(o.direction)||!Number.isFinite(o.timestamp))throw new TypeError("Invalid screen orientation from device provider");let i=new E;for(let a of["type","direction","timestamp"])i.setItem(a,o[a]);r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("network",(r,o)=>e.startNetworkEvents(r,o),(r,o)=>{if(typeof o?.connected!="boolean"||!["none","unknown","wifi","cellular"].includes(o.type))throw new TypeError("Invalid network state from device provider");let i=new E;i.setItem("connected",o.connected),i.setItem("type",o.type),r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("lifecycle",(r,o)=>e.startLifecycleEvents(r,o),(r,o)=>{if(o?.kind==="state"&&typeof o.active=="boolean")r.staticValue.setItem("active",o.active);else if(o?.kind==="pause"||o?.kind==="resume")r.staticValue.setItem("event",o.kind),r.staticValue.setItem("sequence",r.staticValue.getItem("sequence")+1);else throw new TypeError("Invalid lifecycle event from device provider");r.setAttr({status:"success",error:null},!0,!0,!1)}),e.capabilities.includes("links")&&this.#B(this.gramlot.data.getNode("_gramlot.device.links")),e.capabilities.includes("shortcuts")&&this.#R(this.gramlot.data.getNode("_gramlot.device.shortcuts")),e.capabilities.includes("push")&&this.#D(this.gramlot.data.getNode("_gramlot.device.push")),e.capabilities.includes("notifications")&&this.#A(this.gramlot.data.getNode("_gramlot.device.notifications"))}assertLive(){if(this.disposed)throw new Error("DeviceHandler is disposed")}resolver(e){if(this.assertLive(),!this.resolvers.has(e))throw new TypeError(`Unknown device value: ${e}`);return this.resolvers.get(e)}invalidate(e){this.resolver(e).reset()}refresh(e){let t=this.resolver(e);if(t.request)return;let r={revision:t.revision,received:t.received};t.request=r,this.attributes(t,{status:"pending",error:null}),Promise.resolve().then(()=>{if(!(this.disposed||t.request!==r))return this.requireCapability(e),e==="appinfo"?this.provider.readAppInfo():this.provider.readLocation()}).then(o=>{this.disposed||t.request!==r||(this.accept(t,o),t.revision!==r.revision&&(t._lastUpdate=null))}).catch(o=>{!this.disposed&&t.request===r&&t.received===r.received&&this.failure(t,o)}).finally(()=>{t.request===r&&(t.request=null)})}#m(e,t,r){let o=this.gramlot.data.getNode(`_gramlot.device.${e}`);if(!this.provider.capabilities.includes(e)){o.setAttr(oe({code:"UNAVAILABLE",message:`${e} is unavailable`}),!0,!0,!1);return}let i={controller:new AbortController};this.#a.set(e,i),o.setAttr({status:"pending",error:null},!0,!0,!1),i.start=Promise.resolve().then(()=>i.controller.signal.aborted?async()=>{}:t(a=>{if(!i.controller.signal.aborted)try{r(o,a)}catch(s){o.setAttr(oe(s),!0,!0,!1)}},i.controller.signal)).then(a=>(i.controller.signal.aborted||o.setAttr({listening:!0},!0,!0,!1),a)),i.start.catch(a=>{let s=i.controller.signal.aborted;i.controller.abort(),s||o.setAttr({...oe(a),listening:!1},!0,!0,!1)})}#g(e,t){let{node:r}=t;if(!r.attr.enabled){let i=t.stream;if(!i)return;t.stream=null,i.controller.abort(),t.cleanup=i.start.then(a=>a(),()=>{}).then(()=>{!this.disposed&&!t.stream&&r.setAttr({watching:!1,status:"idle",error:null},!0,!0,!1)}),t.cleanup.catch(a=>{this.disposed||r.setAttr(oe(a),!0,!0,!1)});return}if(t.stream)return;let o={controller:new AbortController};t.stream=o,o.start=t.cleanup.then(()=>{if(o.controller.signal.aborted)return async()=>{};this.requireCapability(e);let i=a=>{if(!(this.disposed||o.controller.signal.aborted))try{if(a?.kind==="state"&&typeof a.watching=="boolean")r.setAttr({watching:a.watching,status:a.watching?"pending":"idle",error:null},!0,!0,!1);else if(a?.kind==="sample"){for(let l of["x","y","z","timestamp"])if(!Number.isFinite(a[l]))throw new TypeError(`Invalid ${e}.${l}`);if(!r.attr.watching||r.staticValue&&a.timestamp<r.staticValue.getItem("timestamp"))return;let s=new E;for(let l of["x","y","z","timestamp"])s.setItem(l,a[l]);r.setValue(s,!0,{status:"success",error:null},!0,!1)}else if(a?.kind==="error"&&a.error instanceof Error)r.setAttr({...oe(a.error),watching:!1},!0,!0,!1);else throw new TypeError(`Invalid ${e} event`)}catch(s){r.setAttr(oe(s),!0,!0,!1)}};return e==="gyroscope"?this.provider.startGyroscopeUpdates(i,o.controller.signal):this.provider.startAccelerometerUpdates(i,o.controller.signal)}),o.start.catch(i=>{!this.disposed&&!o.controller.signal.aborted&&r.setAttr({...oe(i),watching:!1},!0,!0,!1)}),r.setAttr({status:"pending",error:null},!0,!0,!1)}#b(e){let t=this.#n;if(t){if(t.phase!=="complete")return;t.phase="replacing",e.setValue(null,!0,{status:"pending",error:null,recording:!1,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),t.close=t.start.then(o=>o.dispose()).then(()=>{this.disposed||t.controller.signal.aborted||this.#n!==t||(this.#n=null,this.#b(e))}).catch(o=>{!this.disposed&&this.#n===t&&(t.phase="failed",e.setAttr(oe(o),!0,!0,!1))});return}let r={controller:new AbortController,phase:"starting"};this.#n=r,e.setValue(null,!0,{status:"pending",error:null,recording:!1,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),r.start=Promise.resolve().then(async()=>r.controller.signal.aborted?null:(this.requireCapability("audio"),this.provider.startAudioRecording(o=>{this.#n===r&&!r.controller.signal.aborted&&this.#y(e,o)},r.controller.signal))),r.start.then(o=>{!o||r.controller.signal.aborted||this.disposed||(r.phase="recording",e.setAttr({status:"recording",error:null,recording:!0},!0,!0,!1))}).catch(o=>{r.controller.signal.aborted||this.disposed||(this.#n===r&&(this.#n=null),e.setAttr({...oe(o),recording:!1},!0,!0,!1))})}#w(e){let t=this.#n;!t||t.phase!=="recording"||(t.phase="stopping",e.setAttr({status:"pending",error:null},!0,!0,!1),t.stop=t.start.then(r=>r.stop()).then(r=>{if(t.controller.signal.aborted||this.disposed)return;if(typeof r?.url!="string"||!r.url||typeof r.mimeType!="string"||!r.mimeType.startsWith("audio/")||!Number.isFinite(r.duration)||r.duration<0)throw new TypeError("Invalid audio result from device provider");let o=new E;for(let i of["url","mimeType","duration"])o.setItem(i,r[i]);t.phase="complete",e.setValue(o,!0,{status:"success",error:null,recording:!1},!0,!1)}).catch(r=>{!t.controller.signal.aborted&&!this.disposed&&this.#y(e,r)}))}#_(e){let t=this.#n;if(t?.phase!=="sharing"){if(!t||t.phase!=="complete"){let r=oe(new Error("Record and stop audio before sharing"));e.setAttr({shareStatus:r.status,shareError:r.error,shareActivity:null},!0,!0,!1);return}t.phase="sharing",e.setAttr({shareStatus:"pending",shareError:null,shareActivity:null},!0,!0,!1),t.share=t.start.then(r=>r.share(t.controller.signal)).then(r=>{if(!(t.controller.signal.aborted||this.disposed)){if(typeof r?.activity!="string")throw new TypeError("Invalid audio share result from device provider");e.setAttr({shareStatus:"success",shareError:null,shareActivity:r.activity},!0,!0,!1)}}).catch(r=>{if(t.controller.signal.aborted||this.disposed)return;let o=oe(r);e.setAttr({shareStatus:o.status,shareError:o.error,shareActivity:null},!0,!0,!1)}).finally(()=>{this.#n===t&&!t.controller.signal.aborted&&(t.phase="complete")})}}#y(e,t={code:"CANCELLED",message:"Audio recording cancelled"}){let r=this.#n;!r||r.phase==="closing"||r.phase==="sharing"||(r.phase="closing",r.controller.abort(),e.setValue(null,!0,{status:"pending",error:null,shareStatus:"idle",shareError:null,shareActivity:null},!0,!1),r.close=r.start.then(o=>o===null?void 0:o.dispose(),o=>{if(o?.code!=="CANCELLED")throw o}).then(()=>{this.disposed||this.#n!==r||(this.#n=null,e.setAttr({...oe(t),recording:!1},!0,!0,!1))}).catch(o=>{!this.disposed&&this.#n===r&&(r.phase="failed",e.setAttr(oe(o),!0,!0,!1))}))}#v(e,t){if(this.#t)return;let r=new AbortController;this.#t=r;let o=e.attr.text;e.setValue(null,!0,{status:"pending",error:null,operation:t},!0,!1),Promise.resolve().then(async()=>{if(r.signal.aborted)return;this.requireCapability("clipboard");let i;if(t==="copy"){if(typeof o!="string")throw new TypeError("Clipboard text must be a string");await this.provider.copyText(o,r.signal),i={text:o}}else i=await this.provider.pasteText(r.signal);if(r.signal.aborted)return;if(typeof i?.text!="string")throw new TypeError("Invalid clipboard text from device provider");let a=new E;a.setItem("text",i.text),e.setValue(a,!0,{status:"success",error:null},!0,!1)}).catch(i=>{r.signal.aborted||e.setAttr(oe(i),!0,!0,!1)}).finally(()=>{this.#t===r&&(this.#t=null)})}#E(e){if(this.#i)return;let t=new AbortController;this.#i=t;let{duration:r}=e.attr;e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(async()=>{if(t.signal.aborted)return;if(this.requireCapability("haptics"),!Number.isInteger(r)||r<1||r>5e3)throw new TypeError("Vibration duration must be an integer from 1 to 5000 milliseconds");if(await this.provider.vibrate(r,t.signal),t.signal.aborted)return;let o=new E;o.setItem("duration",r),o.setItem("acknowledged",!0),e.setValue(o,!0,{status:"success",error:null},!0,!1)}).catch(o=>{t.signal.aborted||e.setAttr(oe(o),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#k(e){if(this.#i)return;let t=new AbortController;this.#i=t;let{style:r}=e.attr;e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(async()=>{if(t.signal.aborted)return;if(this.requireCapability("haptics"),!["light","medium","heavy"].includes(r))throw new TypeError("Invalid haptic style");if(await this.provider.impact(r,t.signal),t.signal.aborted)return;let o=new E;o.setItem("style",r),o.setItem("acknowledged",!0),e.setValue(o,!0,{status:"success",error:null},!0,!1)}).catch(o=>{t.signal.aborted||e.setAttr(oe(o),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#S(e){if(this.#o)return;let t=new AbortController;this.#o=t,e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(()=>{if(!t.signal.aborted)return this.requireCapability("barcode"),this.provider.scanBarcode(t.signal)}).then(r=>{if(t.signal.aborted)return;if(typeof r?.text!="string"||!r.text||typeof r.format!="string"||!r.format)throw new TypeError("Invalid barcode result from device provider");let o=new E;o.setItem("text",r.text),o.setItem("format",r.format),e.setValue(o,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setAttr(oe(r),!0,!0,!1)}).finally(()=>{this.#o===t&&(this.#o=null)})}#T(e,t){if(this.#r)return;let r=new AbortController;this.#r=r,e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(()=>{if(!r.signal.aborted)return this.requireCapability("camera"),t==="choose"?this.provider.choosePhoto(r.signal):this.provider.takePhoto(r.signal)}).then(o=>{if(r.signal.aborted)return;if(typeof o?.url!="string"||!o.url||typeof o.format!="string"||!o.format)throw new TypeError("Invalid camera photo from device provider");let i=new E;i.setItem("url",o.url),i.setItem("format",o.format),e.setValue(i,!0,{status:"success",error:null},!0,!1)}).catch(o=>{r.signal.aborted||e.setAttr(oe(o),!0,!0,!1)}).finally(()=>{this.#r===r&&(this.#r=null)})}#C(e){if(this.#l)return;let t=new AbortController;this.#l=t,e.setValue(null,!0,{status:"pending",error:null},!0,!1),Promise.resolve().then(()=>{if(!t.signal.aborted)return this.requireCapability("biometrics"),this.provider.verifyBiometrics(t.signal)}).then(()=>{if(t.signal.aborted)return;let r=new E;r.setItem("verified",!0),e.setValue(r,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setValue(null,!0,oe(r),!0,!1)}).finally(()=>{this.#l===t&&(this.#l=null)})}#A(e){if(this.#c)return this.#c.start;let t={controller:new AbortController};return this.#c=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startNotificationEvents(r=>{if(!t.controller.signal.aborted)try{if(!["received","action"].includes(r.kind)||!Number.isInteger(r.id)||typeof r.title!="string"||typeof r.body!="string"||r.kind==="action"&&typeof r.actionId!="string")throw new TypeError("Invalid notification event from device provider");let o=new E;for(let i of["id","title","body"])o.setItem(i,r[i]);r.kind==="action"&&o.setItem("actionId",r.actionId),e.staticValue.setItem(r.kind,o)}catch(o){e.setAttr({listenerError:oe(o).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let o=t.controller.signal.aborted;t.controller.abort(),this.#c===t&&(this.#c=null),o||e.setAttr({listening:!1,listenerError:oe(r).error},!0,!0,!1)}),e.setAttr({listenerError:null},!0,!0,!1),t.start}#N(e){if(this.#u)return;let t=new AbortController;this.#u=t;let r=e.staticValue.getItem("request"),o=r instanceof E?Object.fromEntries(["id","title","body","delay"].map(i=>[i,r.getItem(i)])):null;e.staticValue.setItem("scheduled",null),e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(async()=>{if(!t.signal.aborted){if(this.requireCapability("notifications"),!o||!Number.isInteger(o.id)||o.id<1||o.id>2147483647||typeof o.title!="string"||!o.title.trim()||typeof o.body!="string"||!o.body.trim()||typeof o.delay!="number"||!Number.isFinite(o.delay)||o.delay<=0)throw new TypeError("Notification requires a positive 32-bit id, title, body and positive delay in seconds");if(await this.#A(e),!t.signal.aborted)return this.provider.scheduleNotification(o,t.signal)}}).then(i=>{if(t.signal.aborted)return;if(i?.id!==o.id||typeof i.at!="number"||!Number.isFinite(i.at))throw new TypeError("Invalid notification scheduling acknowledgement");let a=new E;a.setItem("id",i.id),a.setItem("at",i.at),e.staticValue.setItem("scheduled",a),e.setAttr({status:"success",error:null},!0,!0,!1)}).catch(i=>{t.signal.aborted||e.setAttr(oe(i),!0,!0,!1)}).finally(()=>{this.#u===t&&(this.#u=null)})}#x(){let e=this.#d;return this.#d=null,e&&clearTimeout(e.timer),e}#I(e,t){if(t.kind==="registration"){if(typeof t.token!="string"||!t.token)throw new TypeError("Invalid push registration token");this.#x();let r=new E;r.setItem("token",t.token),e.staticValue.setItem("registration",r),e.setAttr({status:"success",error:null},!0,!0,!1)}else if(t.kind==="registrationError")this.#x(),e.staticValue.setItem("registration",null),e.setAttr(oe(t.error),!0,!0,!1);else{if(!["received","action"].includes(t.kind))throw new TypeError("Invalid push event kind");let r=["id","title","body","messageId","destination"];t.kind==="action"&&r.push("actionId");let o=new E;for(let i of r){if(typeof t[i]!="string")throw new TypeError(`Invalid push event ${i}`);o.setItem(i,t[i])}e.staticValue.setItem(t.kind,o)}}#D(e){if(this.#f)return this.#f.start;let t={controller:new AbortController};return this.#f=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startPushEvents(r=>{if(!t.controller.signal.aborted)try{this.#I(e,r)}catch(o){e.setAttr({listenerError:oe(o).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let o=t.controller.signal.aborted;t.controller.abort(),this.#f===t&&(this.#f=null),o||e.setAttr({listening:!1,listenerError:oe(r).error},!0,!0,!1)}),e.setAttr({listenerError:null},!0,!0,!1),t.start}#O(e){if(this.#d)return;let t={controller:new AbortController,timer:null};this.#d=t,t.timer=setTimeout(()=>{this.disposed||this.#d!==t||(this.#x(),t.controller.abort(),e.setAttr(oe({code:"TIMEOUT",message:"Push registration has not returned a token"}),!0,!0,!1))},3e4),e.staticValue.setItem("registration",null),e.setAttr({status:"pending",error:null},!0,!0,!1),Promise.resolve().then(async()=>{t.controller.signal.aborted||(this.requireCapability("push"),await this.#D(e),!(t.controller.signal.aborted||this.#d!==t)&&await this.provider.registerPush(t.controller.signal))}).catch(r=>{this.disposed||this.#d!==t||(this.#x(),t.controller.abort(),e.setAttr(oe(r),!0,!0,!1))})}#R(e){let t={controller:new AbortController};this.#p=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startShortcutEvents((r,o=null)=>{if(!t.controller.signal.aborted)try{if(o)throw o;for(let a of["id","destination"])if(typeof r?.[a]!="string"||!r[a])throw new TypeError(`Invalid shortcut request ${a}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new E;i.setItem("id",r.id),i.setItem("destination",r.destination),e.setAttr({listenerError:null},!0,!0,!1),e.staticValue.setItem("request",i)}catch(i){e.setAttr({listenerError:oe(i).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let o=t.controller.signal.aborted;t.controller.abort(),o||e.setAttr({listening:!1,listenerError:oe(r).error},!0,!0,!1)})}#B(e){let t={controller:new AbortController};this.#h=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startLinkEvents((r,o=null)=>{if(!t.controller.signal.aborted)try{if(o)throw o;for(let a of["id","url"])if(typeof r?.[a]!="string"||!r[a])throw new TypeError(`Invalid link request ${a}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new E;i.setItem("id",r.id),i.setItem("url",r.url),e.setAttr({listenerError:null},!0,!0,!1),e.staticValue.setItem("request",i)}catch(i){e.setAttr({listenerError:oe(i).error},!0,!0,!1)}},t.controller.signal)).then(r=>(t.controller.signal.aborted||e.setAttr({listening:!0},!0,!0,!1),r)),t.start.catch(r=>{let o=t.controller.signal.aborted;t.controller.abort(),o||e.setAttr({listening:!1,listenerError:oe(r).error},!0,!0,!1)})}requireCapability(e){if(!this.provider||!this.provider.capabilities.includes(e))throw Object.assign(new Error(`${e} is unavailable in this environment`),{code:"UNAVAILABLE"})}attributes(e,t){let r=e.writing;e.writing=!0;try{e._node.setAttr(t,!0,!0,!1)}finally{e.writing=r}}accept(e,t){let r=e.name==="appinfo"?["id","name","version","build"]:["latitude","longitude","accuracy","timestamp"],o=e.name==="appinfo"?"string":"number";for(let l of r)if(typeof t[l]!==o||o==="number"&&!Number.isFinite(t[l]))throw new TypeError(`Invalid ${e.name}.${l} from device provider`);let i=e.cachedValue;if(e.name==="location"&&i&&t.timestamp<i.getItem("timestamp")){this.attributes(e,{status:"success",error:null});return}let a=new E;for(let l of r)a.setItem(l,t[l]);e._lastUpdate=Date.now(),e.failed=!1,e.received++;let s=e.writing;e.writing=!0;try{e._node.setValue(a,!0,{status:"success",error:null},!0,!1)}finally{e.writing=s}}failure(e,t){e.failed=!0,this.attributes(e,oe(t))}reconcile(){let e=this.resolvers.get("location");if(e._node.attr.enabled){if(this.monitor)return;let t={stop:null,controller:new AbortController};this.monitor=t,t.start=Promise.resolve(this.cleanup).then(()=>this.disposed||this.monitor!==t?null:(this.requireCapability("location"),this.provider.startLocationUpdates((r,o)=>{if(!(this.disposed||this.monitor!==t))if(o)this.failure(e,o);else try{this.accept(e,r)}catch(i){this.failure(e,i)}},t.controller.signal))),t.start.then(r=>{r===null||this.disposed||this.monitor!==t||(t.stop=r,this.attributes(e,{watching:!0}))}).catch(r=>{!this.disposed&&this.monitor===t&&(this.attributes(e,{watching:!1}),this.failure(e,r))}),this.attributes(e,{status:"pending",error:null})}else if(this.monitor){let t=this.monitor;this.monitor=null,t.controller.abort(),this.retiring=t,this.cleanup=t.start.then(r=>r===null?void 0:r(),()=>{}).then(()=>{if(this.retiring===t&&(this.retiring=null),!this.disposed){let r={watching:!1};!this.monitor&&!e.request&&e._node.attr.status==="pending"&&Object.assign(r,{status:"cancelled",error:null}),this.attributes(e,r)}}),this.cleanup.catch(r=>{this.disposed||this.failure(e,r)})}}async openDatabase(e){if(this.assertLive(),!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(e)||typeof e!="string")throw new TypeError("Invalid database name");if(this.#e)throw new Error("This page already owns a database connection");let t=this.gramlot.data.getNode("_gramlot.device.database"),r=(i,a=null)=>{this.disposed||t.setAttr({status:i,error:a},!0,!0,!1)};if(!this.provider.capabilities.includes("database")){let i=Object.assign(new Error("Native database unavailable"),{code:"UNAVAILABLE"});throw r("unavailable",{code:i.code,message:i.message}),i}let o={controller:new AbortController,close:null,start:null};this.#e=o,r("pending"),o.start=this.provider.openDatabase(e,o.controller.signal);try{let i=await o.start,a=!1,s=null,l=()=>s||(a=!0,s=i.close().then(()=>{r("closed")},c=>{throw r("error",{code:"FAILED",message:c.message}),c}).finally(()=>{this.#e===o&&(this.#e=null)}),s);if(o.close=l,this.disposed||o.controller.signal.aborted)throw await l(),Object.assign(new Error("Page closed"),{code:"CANCELLED"});let u=async(c,d,f)=>{if(this.assertLive(),a)throw new Error("Database connection is closed");r("pending");try{let h=await i[c](d,f);return r("success"),h}catch(h){throw r("error",{code:"FAILED",message:h.message}),h}};return r("success"),{query:(c,d=[])=>u("query",c,d),execute:(c,d=[])=>u("execute",c,d),close:l}}catch(i){throw this.#e===o&&(this.#e=null),this.disposed||t.setAttr(oe(i),!0,!0,!1),i}}dispose(){if(this.disposed)return;this.disposed=!0;let e=this.#e;e?.controller.abort(),e&&(this.cleanup=Promise.all([this.cleanup,e.start.then(()=>e.close?.(),()=>{})]).then(()=>{}));let t=[...this.#s.values()].map(c=>{let d=c.stream;return c.stream=null,d?.controller.abort(),d?d.start.then(f=>f(),()=>{}):c.cleanup});this.#t?.abort(),this.#t=null;let r=this.#n;this.#n=null,r?.controller.abort(),this.#i?.abort(),this.#i=null;let o=[...this.#a.values()];this.#a.clear();for(let c of o)c.controller.abort();let i=this.#h;this.#h=null,i?.controller.abort();let a=this.#p;this.#p=null,a?.controller.abort(),this.#x()?.controller.abort();let s=this.#f;this.#f=null,s?.controller.abort(),this.#o?.abort(),this.#o=null,this.#r?.abort(),this.#r=null,this.#l?.abort(),this.#l=null,this.#u?.abort(),this.#u=null;let l=this.#c;this.#c=null,l?.controller.abort(),this.gramlot.data.unsubscribe("gramlot.device",{any:!0});let u=this.monitor;if(this.monitor=null,u?.controller.abort(),u)this.cleanup=u.start.then(c=>c===null?void 0:c(),()=>{});else if(this.retiring?.stop){let c=this.retiring;this.cleanup=this.cleanup.catch(()=>c.stop())}l&&(this.cleanup=Promise.all([this.cleanup,l.start.then(c=>c(),()=>{})]).then(()=>{})),s&&(this.cleanup=Promise.all([this.cleanup,s.start.then(c=>c(),()=>{})]).then(()=>{})),i&&(this.cleanup=Promise.all([this.cleanup,i.start.then(c=>c(),()=>{})]).then(()=>{})),a&&(this.cleanup=Promise.all([this.cleanup,a.start.then(c=>c(),()=>{})]).then(()=>{})),this.cleanup=Promise.all([this.cleanup,...t,...o.map(c=>c.start.then(d=>d(),()=>{}))]).then(()=>{}),r&&(this.cleanup=Promise.all([this.cleanup,r.start.then(c=>c===null?void 0:c.dispose(),c=>{if(c?.code!=="CANCELLED")throw c})]).then(()=>{})),this.cleanup=this.cleanup.finally(()=>this.releaseProvider?.()),this.cleanup.catch(c=>{this.cleanupError=c});for(let c of this.resolvers.values())c.request=null}};var ym=2e3;function F2(n){if(!(n instanceof Date))return String(n??"");let e=n.toISOString();return e.endsWith("T00:00:00.000Z")?e.slice(0,10):e}var ji=class{constructor(e,t){this.gramlot=e,this.document=t}branch(e){let t=this.gramlot.data.getItem(e);if(!(t instanceof E))throw new Error(`gramlot.utl.inout: no data Bag at '${e}'`);return t}mailText(e){let t=[],r=(o,i)=>{for(let a of o.getNodes()){let s=i+a.label;a.value instanceof E?r(a.value,`${s}.`):t.push(`${s}: ${F2(a.value)}`)}};return r(this.branch(e),""),t.join(`
|
|
235
|
+
`)}mailtoUrl(e,t){let r=`mailto:${encodeURIComponent(t)}?subject=${encodeURIComponent(this.document.title)}&body=${encodeURIComponent(this.mailText(e))}`;if(r.length>ym)throw new Error(`gramlot.utl.inout.sendMail: the email of '${e}' is ${r.length} characters long, over the mailto: limit of ${ym}; send it with sendHttp or save it as a file`);return r}sendMail(e,t){this.open(this.mailtoUrl(e,t))}async sendHttp(e,t){let r=JSON.stringify(this.branch(e).asDict(!1,!1,!0)),o=await this.document.defaultView.fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:r});if(!o.ok)throw new Error(`gramlot.utl.inout.sendHttp: ${t} answered ${o.status}`);return o}save(e,t){this.saveText(this.branch(e).toTytx(),t,"application/json")}restore(e){let t=this.document.createElement("input");return t.type="file",t.accept=".json,application/json",new Promise((r,o)=>{let i=()=>o(new this.document.defaultView.DOMException("File selection cancelled","AbortError"));t.addEventListener("cancel",i,{once:!0}),t.addEventListener("change",async()=>{if(t.removeEventListener("cancel",i),!t.files.length){i();return}try{let a=j(await t.files[0].text());if(!(a instanceof E))throw new TypeError("the file must contain a typed Bag");this.gramlot.data.setItem(e,a),r(a)}catch(a){o(new Error(`gramlot.utl.inout.restore: the file is not a saved Gramlot branch: ${a.message}`,{cause:a}))}},{once:!0}),t.click()})}download(e,t,r){if(!["json","xml"].includes(r))throw new Error(`gramlot.utl.inout.download: format '${r}' is not 'json' or 'xml'`);let o=this.branch(e);if(r==="json")this.saveText(o.toJson(!1),t,"application/json");else{let i=e.split(".").at(-1);this.saveText(`<?xml version='1.0' encoding='UTF-8'?>
|
|
236
|
+
<${i}>${o.toXml()}</${i}>`,t,"application/xml")}}async copyText(e){if(typeof e!="string")throw new TypeError("gramlot.utl.inout.copyText: text must be a string");await this.document.defaultView.navigator.clipboard.writeText(e)}saveText(e,t,r){let o=this.document.defaultView,i=o.URL.createObjectURL(new o.Blob([e],{type:r}));this.open(i,t),o.setTimeout(()=>o.URL.revokeObjectURL(i),1e3)}open(e,t=null){let r=this.document.createElement("a");r.href=e,t!==null&&(r.download=t),r.click()}};var qi=class extends Ke{constructor(e,t){super(e),this.inout=new ji(e,t)}};var Ui=class{#e;#t;constructor({pageId:e,uploadUrl:t=null,rpcUrl:r="/gramlot/rpc",closeUrl:o="/gramlot/close",rootId:i="gramlot-root",capabilities:a=[],element:s=null,document:l=s?.ownerDocument??globalThis.document,transport:u=null,collections:c=[],locale:d=null,timeZone:f=null,devices:h=[],serverAdapter:p=new ur,nameSyntax:m=null,websocketUrl:b=null}={}){this.#t=[gs,...c.filter(_=>_ instanceof Ar)],this.registerDocument(l),this.commands=new Oo,this.pageId=e,this.uploadUrl=t;let w=d==null||f==null?l.defaultView.Intl.DateTimeFormat().resolvedOptions():null;this.devices=Object.freeze([...h]),this.locale=d??w.locale,this.timeZone=f??w.timeZone,Object.defineProperty(this,"_subscriptions",{value:new Xs(this)}),this.capabilities=Object.freeze([...a]),this.serverAdapter=p,this.src=new Pi(this,{collections:c,destination:s??l.getElementById(i),subscriptions:this._subscriptions,nameSyntax:m===null?_i:on.fromJSON(m)}),this.#e=Io.install({document:l,root:this.src.renderer.destination}),this.data=this.src.builder.data,this.dvc=new Fi(this),this.dom=new Li(this),this.utl=new qi(this,l),this.state="ready",this.abort=new AbortController,Object.defineProperty(this,"_frames",{value:new as(this,l)}),b!==null&&(this._pageStore=new is(this,b,l)),this.rpc=new wi(this,{rpcUrl:r,closeUrl:o,document:l,transport:u}),this._frames.connect(),this.rpc.transport&&(this.pagehide=_=>{_.persisted||this.dispose()},l.defaultView.addEventListener("pagehide",this.pagehide),this.window=l.defaultView)}publish(e,t={}){return this._subscriptions.publish(e,t)}registerDocument(e){for(let t of this.#t)t.register(e.defaultView)}getCollection(e){return this.#t.find(t=>t.name===e)}subscribe(e,t){return this._subscriptions.subscribe(e,t)}unsubscribe(e){this._subscriptions.unsubscribe(e)}format(e,t){return hs(e,t,{locale:this.locale,timeZone:this.timeZone})}start(){return this.state==="disposed"?Promise.reject(new Error("Gramlot is disposed")):this.rpc.transport?this.loading?this.loading:this.state==="started"?Promise.resolve(this):(this.state="loading",this.loading=this.loadMain().finally(()=>{this.loading=null}),this.loading):Promise.reject(new Error("This Gramlot instance has no server transport"))}async loadMain(){let e;try{e=await this.rpc.callEnvelope("source","main")}catch(t){throw this.state==="disposed"?new Error("Gramlot was disposed during main",{cause:t}):(this.state="failed",t)}if(this.state==="disposed")throw new Error("Gramlot was disposed during main");try{return this.src.mountMainSource(e.value,e.data)}catch(t){throw this.state!=="disposed"&&(this.state="failed"),t}}dispose(){if(this.state!=="disposed"){this.state="disposed",this.dvc.dispose(),this.#e.dispose(),this._subscriptions.dispose(),this.pagehide&&this.window.removeEventListener("pagehide",this.pagehide),this.abort.abort();try{try{this.src.binding.dispose()}finally{this.src.renderer.dispose()}}finally{if(this._pageStore?.close(),this._frames.dispose(),this.rpc.transport)try{this.rpc.transport.close(this.pageId)}finally{this.rpc.transport.dispose()}}}}};var wc=class{constructor({config:e,resources:t,document:r=globalThis.document}){this.config=e,this.resources=t,this.document=r,this.serverAdapter=new ur}async run(){let{config:e,resources:t,document:r}=this,o=r.defaultView;t.serverAdapter!==void 0&&(this.serverAdapter=await this.loadServerAdapter(t.serverAdapter));let i=!1,a,s,l=[],u=new Promise(d=>{a=d}),c=d=>{if(!(d.persisted||i)){i=!0;try{this.closePage()}finally{a(null)}}};o.addEventListener("pagehide",c);try{let d=t.css.map(_=>new Promise((y,x)=>{let D=r.createElement("link");D.rel="stylesheet",D.href=_;let k=()=>{D.removeEventListener("load",C),D.removeEventListener("error",O)};l.push(k);let C=()=>{k(),y()},O=()=>{k(),x(new Error(`${_}: stylesheet load failed`))};D.addEventListener("load",C),D.addEventListener("error",O),r.head.append(D)})),f=t.js.map(async({url:_,group:y})=>{try{return{logicClass:(await import(new URL(_,r.baseURI).href)).Logic,group:y,resource:_}}catch(x){throw new Error(`${_}: import failed: ${x.message}`,{cause:x})}}),h=new Set,p=(t.collections??[]).map(async _=>{if(!_||typeof _!="object"||Object.keys(_).sort().join(",")!=="buildId,name,url"||typeof _.name!="string"||typeof _.url!="string"||typeof _.buildId!="string"||!/^sha256:[0-9a-f]{64}$/.test(_.buildId)||h.has(_.name))throw new TypeError("Invalid or duplicate collection bootstrap record");h.add(_.name);let{name:y,url:x,buildId:D}=_,k;try{k=await import(new URL(x,r.baseURI).href)}catch(C){throw new Error(`${y}: collection import failed: ${C.message}`,{cause:C})}if(k.default?.name!==y||k.buildId!==D)throw new Error(`${y}: collection identity mismatch; expected ${D}, received ${k.buildId}`);return k.default}),m=await Promise.race([Promise.all([Promise.all(d),Promise.all(f),Promise.all(p)]),u]);if(i)return null;let[,b,w]=m;_o.check(b);for(let _ of w)_.register(o);s=new Ui({...e,document:r,serverAdapter:this.serverAdapter,collections:[...e.collections??[],...w]}),o.removeEventListener("pagehide",c);for(let _ of w)_.registerCommands(s);for(let{logicClass:_,group:y,resource:x}of b)s.src.logicRegistry.register(_,{group:y,resource:x});return o.gramlot=s,await s.start(),s}catch(d){throw s?s.dispose():i||this.closePage(),d}finally{for(let d of l)d();o.removeEventListener("pagehide",c)}}async loadServerAdapter(e){let t;try{t=await import(new URL(e,this.document.baseURI).href)}catch(r){throw new Error(`${e}: server adapter import failed: ${r.message}`,{cause:r})}return new t.default}closePage(){let e=this.serverAdapter.createTransport({...this.config,document:this.document});try{e.close(this.config.pageId)}finally{e.dispose()}}};var Ks=Symbol("gramlot.source"),Js=Symbol("gramlot.endpoint"),Vi=Symbol("gramlot.upload"),j2=new Map([[Ks,"registerSource"],[Js,"registerEndpoint"],[Vi,"registerUpload"]]);function _c(n,e,t,r){let o=j2.get(t);if(e==="main")throw new TypeError(`${o} cannot declare main`);let i=Object.getOwnPropertyDescriptor(n.prototype,e)?.value;if(typeof i!="function")throw new TypeError(`${o} requires an own method of ${n.name}: ${String(e)}`);if(i[t])throw new TypeError(`${t===Ks?"Source method":t===Js?"Endpoint":"Upload operation"} already registered: ${e}`);if([Ks,Js,Vi].some(a=>i[a])){let a=t!==Vi&&!i[Vi]?`${e} is declared both as Source method and endpoint`:`${e} has conflicting declarations`;throw new TypeError(a)}i[t]={auth:r}}var Qs=class{static registerSource(e,{auth:t=null}={}){_c(this,e,Ks,t)}static registerEndpoint(e,{auth:t=null}={}){_c(this,e,Js,t)}static registerUpload(e,{auth:t=null}={}){_c(this,e,Vi,t)}},zi=class extends Qs{static gramlots=[];static title="Gramlot";static devices=[];static locale=null;static timeZone=null;static installable=!1;static appIcon=null;manifest({baseUrl:e="./"}={}){let{title:t,appIcon:r}=this.constructor;if(typeof r!="string"||!r)throw new TypeError("An installable Page needs appIcon");return{id:e,name:t,short_name:t,start_url:e,scope:e,display:"standalone",icons:[{src:e+r.replace(/^\/+/,""),sizes:"512x512",type:"image/png"}]}}static css=[];static css_theme=null;static css_requires="";static js_requires="";static sourceBuilder=Oe;main(e){throw new Error("Page.main(root) must be implemented")}};var yo=class extends zi{static shellId="frame";static datapath=null;main(e){let t=e.div({id:this.constructor.shellId,datapath:this.constructor.datapath,class:"frame-page",height:"100vh",display:"flex",flex_direction:"column",min_height:0}),r=t.borderContainer({node_label:"frame",height:"100%",flex:"1",min_height:0});for(let o of["top","bottom","left","right","center"])if(this[o]!==void 0){let i=r.contentPane({region:o,node_label:o});this[o](i)}this.behavior(t)}center(e){}behavior(e){}};var Hi=class extends yo{static title="Application";static shellId="index";static datapath="index";static navigation=null;main(e){let{navigation:t,datapath:r}=this.constructor;if(!(t instanceof E))throw new TypeError("IndexPage.navigation must be a Bag");e.dataSetter({destination_path:`${r}.navigation`,value:t}),e.dataSetter({destination_path:`${r}.navigationSelection`,value:null}),e.dataSetter({destination_path:`${r}.active`,value:null}),e.dataSetter({destination_path:`${r}.opened`,value:new E}),super.main(e)}left(e){e.setAttr({width:"240px",splitter:!0,drawer:!0,drawer_label:"Navigation"}),e.tree({node_label:"tree",storepath:".navigation",labelAttribute:"title",hideValues:!0,selectedPath:"^.navigationSelection"})}center(e){e.tabContainer({node_label:"tabs",height:"100%",selectedPage:"^.active"})}behavior(e){e.dataController({func:"indexMount",_onStart:!0})}index_panel(e,{selection:t}){this.panel(e,t.getNode("#0"))}panel(e,t){e.iframe({src:t.attr.url,title:t.attr.title??t.label,width:"100%",height:"100%",border:0})}};Hi.registerSource("index_panel");function yc(n,e,t=()=>{},r=()=>{},{state:o=e.getRelativeData("."),createEntry:i=null,onLoad:a=()=>{}}={}){let s=o.getItem("navigation");if(!(s instanceof E))throw new TypeError("IndexPage navigation must be a Bag");let l=e.value.getNode("frame.center.tabs"),u=e.builder,c=new Map,d={entries:c,disposed:!1,selecting:!1,sequence:0,requested:null};Object.defineProperty(e,"indexContext",{value:d,configurable:!0});let f=o.getItem("opened");for(let k of f.getNodes()){let{url:C,path:O,title:$}=k.attr,F=l.value.getNode(k.label),H={url:C,path:O,title:$,pane:F,node:s.getNode(O),loading:!1};r(H),c.set(C,H),d.sequence++}let h=(k,C,O)=>{try{a(k.url,C,O)}catch($){n.binding.reportError($,"Page load callback failed")}},p=(k,C,O)=>{k.loading&&(k.loading=!1,h(k,C,O))},m=k=>{if(!d.disposed){d.selecting=!0;try{o.setItem("active",k.url),o.setItem("navigationSelection",k.path),t(c,k.url)}finally{d.selecting=!1}}};function b(k){w(k).catch(C=>{d.disposed||n.binding.reportError(C,"Page could not be opened")})}async function w(k){let C=s.getNode(k);if(!C)throw new Error(`Unknown index navigation path: ${k}`);let O=C.attr.url;if(O==null)return;if(typeof O!="string"||!O)throw new TypeError("IndexPage URL must be nonempty text");d.requested=O;let $=c.get(O);if($){$.path=k,m($);return}for(;l.value!==null&&l.value.getNode(`page${d.sequence}`);)d.sequence++;let F=ae(u.wrapSource(l).contentPane({node_label:`page${d.sequence++}`,title:C.attr.title??C.label,pageName:O,height:"100%",closable:!0})),H=o.getItem("active");$={url:O,path:k,node:C,pane:F,title:C.attr.title??C.label,loading:!0},c.set(O,$);try{if(h($,"loading"),d.disposed||c.get(O)!==$||(m($),d.disposed||c.get(O)!==$))return;if(i)await i($);else{let Q=new E;if(Q.setItem(C.label,null,{...C.attr}),!await n.binding.gramlot.src.remoteSource(F,"index_panel",{selection:Q}))throw new Error("Panel loading was cancelled")}if(d.disposed||c.get(O)!==$)return;f.setItem(F.label,null,{url:O,path:$.path,title:$.title}),r($)}catch(Q){if(d.disposed||c.get(O)!==$)return;try{if(n.binding.reportError(Q,"Page could not be opened"),c.delete(O),f.getNode(F.label)&&f.popNode(F.label),F.parentBag&&F.parentBag.popNode(F.label),!d.disposed&&d.requested===O){let me=c.get(H);if(d.requested=me?.url??null,me)m(me);else{d.selecting=!0;try{o.setItem("active",null),o.setItem("navigationSelection",null),t(c,null)}finally{d.selecting=!1}}}}finally{p($,"error",Q)}return}d.disposed||c.get(O)!==$||(p($,"ready"),!d.disposed&&c.get(O)===$&&d.requested===O&&m($))}let _=`${e.getAttr("id")}-page-close`;e.value.subscribe(_,{any:k=>{if(k.evt!=="del")return;let C=[...c.values()].find(F=>F.pane===k.node);if(!C)return;let{url:O,pane:$}=C;if(!(d.disposed||n.disposed||c.get(O)!==C)){c.delete(O),f.getNode($.label)&&f.popNode($.label);try{if(o.getItem("active")===O){let F=[...c.values()].at(-1);if(d.requested=F?.url??null,F)m(F);else{d.selecting=!0;try{o.setItem("active",null),o.setItem("navigationSelection",null),t(c,null)}finally{d.selecting=!1}}}else t(c,o.getItem("active"))}finally{p(C,"cancelled")}}}});let y=`${e.getAttr("id")}-selection`;o.subscribe(y,{any:k=>{if(!(d.selecting||d.disposed)){if(k.node===o.getNode("navigationSelection")){let C=o.getItem("navigationSelection");C!==null&&b(C)}else if(k.node===o.getNode("active")){let C=c.get(o.getItem("active"));C&&(d.requested=C.url,m(C))}}}});let x=()=>{if(!d.disposed){d.disposed=!0,o.unsubscribe(y,{any:!0}),e.value.unsubscribe(_,{any:!0});for(let k of c.values())k.loading&&(k.pane.parentBag&&k.pane.parentBag.popNode(k.pane.label),p(k,"cancelled"));c.clear(),e.indexContext===d&&delete e.indexContext}};d.dispose=x,n.onDispose(e,x);let D=c.get(o.getItem("active"));return D?m(D):o.getItem("navigationSelection")!==null&&b(o.getItem("navigationSelection")),d}var el=class{indexMount(e){yc(this.page.src.renderer,e.parentNode)}};function tl(n,{datapath:e,value:t,language:r="text",height:o="420px",...i}){if(!e)throw new TypeError("codeMirrorWithOptions requires datapath");let a=n.borderContainer({datapath:e,height:o,class:"gramlot-editor-options"}),s={language:r,indentUnit:4,fontSize:14,fontFamily:"monospace",lineNumbers:!0,lineWrapping:!0,folding:!0,bracketMatching:!0,autoCloseBrackets:!0,autoIndent:!0,autocompletion:!0,highlightActiveLine:!0,highlightSelectionMatches:!0};for(let[d,f]of Object.entries(s))a.dataSetter({destination_path:`.settings.${d}`,value:f});let l=a.contentPane({region:"right",width:"250px",drawer:"close",drawer_label:"Options",drawer_icon:"\u2699",drawer_minimize:!1,padding:"12px",overflow:"auto",class:"gramlot-editor-settings"});l.h3("Editor options"),l.filteringSelect({value:"^.settings.language",lbl:"Language",values:"text:Plain text,python:Python,javascript:JavaScript,typescript:TypeScript,json:JSON,html:HTML,css:CSS,xml:XML,markdown:Markdown,sql:SQL,typst:Typst"}),l.numberTextBox({value:"^.settings.indentUnit",lbl:"Indent spaces",min:1,max:16,dtype:"L",validate_notnull:!0}),l.numberTextBox({value:"^.settings.fontSize",lbl:"Font size",min:8,max:48,dtype:"L",validate_notnull:!0}),l.textbox({value:"^.settings.fontFamily",lbl:"Font family"});let u={lineNumbers:"Line numbers",lineWrapping:"Wrap lines",folding:"Code folding",bracketMatching:"Match brackets",autoCloseBrackets:"Close brackets and quotes",autoIndent:"Automatic indentation",autocompletion:"Local completion",highlightActiveLine:"Highlight current line",highlightSelectionMatches:"Highlight matching selections"};for(let[d,f]of Object.entries(u))l.checkbox({value:`^.settings.${d}`,label:f,display:"block",margin_top:"8px"});return a.contentPane({region:"center",min_height:0}).codeMirror({...i,value:t,height:"100%",...Object.fromEntries(Object.keys(s).map(d=>[d,`^.settings.${d}`]))}),a}var Gi=class n extends At{static internalParams=new Set([...At.internalParams,"gramlot","method","params","onError"]);#e=!1;#t=null;constructor({gramlot:e,root:t,path:r="",onError:o}){super({cacheTime:-1,onError:o}),this.gramlot=e,this.method="directory_tree",this.params={root:t,path:r},this.children=new Set}get closed(){return this.#e}startLoad(e){if(this.loading)return this.loading;let t=new AbortController;return this.#t=t,e({controller:t,method:this.method,params:this.params,ignored:!1})}async loadAsync({controller:e,method:t,params:r}){let{signal:o}=e,i,a=new Promise((s,l)=>{i=()=>l(o.reason),o.addEventListener("abort",i,{once:!0})});try{let s=await Promise.race([this.gramlot.rpc.call("data",t,r,{signal:o}),a]);if(o.aborted)throw o.reason;return s}finally{o.removeEventListener("abort",i),this.#t===e&&(this.#t=null)}}prepareValue(e){if(!(e instanceof E))throw new TypeError("directory_tree must return a Bag");for(let t of this.children)t.abort();this.children.clear();for(let t of e.getNodes())if(t.attr.is_directory){let r=new n({gramlot:this.gramlot,root:this.params.root,path:t.attr.path,onError:this.onError});this.children.add(r),e.setResolver(t.label,r)}return e}abort(){this.#e=!0,this.#t?.abort();for(let e of this.children)e.abort();this.children.clear()}},Wi=class{constructor(e,t){this.gramlot=e,this.source=t,this.request=null,this.resolver=null,this.disposed=!1}get state(){return this.source.getRelativeData(".")}async open(e){this.request?.abort();let t=this.request=new AbortController;this.state.setItem("status","Opening directory\u2026");try{let r=await this.gramlot.rpc.call("data","workspace_open",{root:e},{signal:t.signal});if(this.disposed||t.signal.aborted)return null;let o=new Gi({gramlot:this.gramlot,root:r.root,onError:a=>this.state.setItem("status",a.message)}),i=o.prepareValue(r.entries);return this.resolver?.abort(),this.resolver=o,this.state.setItem("selectedPath",null),this.state.setItem("store",i),this.state.setItem("writable",r.writable),this.state.setItem("root",r.root),this.state.setItem("status",""),r.root}catch(r){return!this.disposed&&!t.signal.aborted&&this.state.setItem("status",r.message),null}finally{this.request===t&&(this.request=null)}}dispose(){this.disposed=!0,this.request?.abort(),this.resolver?.abort()}},wn=class{fileSystemMount(e){let t=e.parentNode,r=new Wi(this.page,t);Object.defineProperty(t,"fileSystemController",{value:r,configurable:!0}),this.page.src.renderer.onDispose(t,()=>r.dispose())}fileSystemOpen(e,{root:t}){if(t)return e.parentNode.fileSystemController.open(t)}};function vm(n,{datapath:e,...t}){let r=n.div({datapath:e,class:"gramlot-filesystem",...t});return r.dataSetter({destination_path:".store",value:new E}),r.dataSetter({destination_path:".root",value:null}),r.dataSetter({destination_path:".requestedRoot",value:null}),r.dataSetter({destination_path:".selectedPath",value:null}),r.dataSetter({destination_path:".status",value:""}),r.dataController({func:"fileSystemMount",_onBuilt:!0}),r.dataController({func:"fileSystemOpen",root:"^.requestedRoot"}),r.tree({storepath:".store",selectedPath:"^.selectedPath",labelAttribute:"caption",hideValues:!0,class:"gramlot-filesystem-tree"}),r.div("^.status",{role:"status",class:"gramlot-filesystem-status"}),r}var q2=(n,e)=>"d_"+[...new TextEncoder().encode(JSON.stringify([n,e]))].map(t=>t.toString(16).padStart(2,"0")).join(""),rl=class{constructor(e,t){this.gramlot=e,this.source=t,this.pending=new Map,this.disposed=!1}get state(){return this.source.getRelativeData(".")}get documents(){return this.state.getItem("documents")}async open(e,t){if(!/\.(?:py|js|mjs|ts|json|html|css|xml|md|markdown|sql|typ|txt|png|jpg|jpeg|webp)$/i.test(t))return null;let r=q2(e,t),o=this.documents.getNodes().find(s=>!s.value.getItem("isNew")&&s.value.getItem("root")===e&&s.value.getItem("path")===t);if(o)return o.label;if(this.pending.has(r))return this.pending.get(r).promise;let i=new AbortController,a=this.gramlot.rpc.call("data","document_read",{root:e,path:t},{signal:i.signal}).then(s=>{if(this.disposed||i.signal.aborted)return null;let l=new E,u=s.language==="image"?s.content.toTytx():s.content;for(let[c,d]of Object.entries({...s,content:u,root:e,saved:u,busy:!1}))l.setItem(c,d);if(s.language==="image"){let c=s.content;l.setItem("annotations",c),c.subscribe("ide-annotations",{any:()=>l.setItem("content",c.toTytx())})}return this.documents.setItem(r,l),r}).finally(()=>this.pending.delete(r));return this.pending.set(r,{request:i,promise:a}),a}newDocument(e,t,r=""){let o=`new_${J()}`,i=new E;for(let[a,s]of Object.entries({language:e,root:r,path:`Untitled${t}`,content:"",saved:"",writable:!0,busy:!1,isNew:!0,createHidden:!0,saveRoot:r,savePath:`Untitled${t}`}))i.setItem(a,s);return this.documents.setItem(o,i),o}async create(e){let t=this.documents.getItem(e);if(!t||!t.getItem("isNew")||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("saveRoot"),o=t.getItem("savePath");if(t.getItem("path").endsWith(".typ.py")!==o.endsWith(".typ.py"))throw new Error("The .typ.py extension is required for the Typst Python recipe document type.");let i=t.getItem("content"),a=new AbortController;t.setItem("busy",!0);let s=this.gramlot.rpc.call("data","document_create",{root:r,path:o,content:i},{signal:a.signal}).then(l=>this.disposed||a.signal.aborted?!1:(t.setItem("root",l.root),t.setItem("path",l.path),t.setItem("revision",l.revision),t.setItem("saved",i),t.setItem("isNew",!1),t.setItem("createHidden",!0),!0)).finally(()=>{this.pending.delete(e),this.disposed||t.setItem("busy",!1)});return this.pending.set(e,{request:a,promise:s}),s}invalidateRecipe(e){let t=this.documents.getItem(e);t.getItem("path").endsWith(".typ.py")&&(t.getItem("rendering")&&this.pending.get(e)?.request.abort(),t.setItem("previewHidden",!0),t.setItem("typstSource",""),t.setItem("renderStatus","Generate preview to render the current Python recipe."))}async renderRecipe(e){let t=this.documents.getItem(e);if(!t||!t.getItem("path").endsWith(".typ.py")||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("content"),o=new AbortController;t.setItem("busy",!0),t.setItem("rendering",!0),t.setItem("previewHidden",!0),t.setItem("typstSource",""),t.setItem("renderStatus","Generating Typst on the server\u2026");let i=this.gramlot.rpc.call("data","document_render_typst",{content:r},{signal:o.signal}).then(a=>this.disposed||o.signal.aborted||t.getItem("content")!==r?!1:(t.setItem("typstSource",a.source),t.setItem("previewHidden",!1),t.setItem("renderStatus","Typst generated from the current recipe."),!0)).catch(a=>(!this.disposed&&!o.signal.aborted&&t.setItem("renderStatus",a.message),!1)).finally(()=>{this.pending.delete(e),this.disposed||(t.setItem("rendering",!1),t.setItem("busy",!1))});return this.pending.set(e,{request:o,promise:i}),i}dirty(e){let t=this.documents.getItem(e);return t&&t.getItem("content")!==t.getItem("saved")}async save(e){let t=this.documents.getItem(e);if(!t||t.getItem("isNew")||!this.dirty(e)||!t.getItem("writable")||this.pending.has(e))return!1;let r=t.getItem("content"),o=new AbortController;t.setItem("busy",!0);let i=t.getItem("language")==="image",a=i?t.getItem("annotationPath"):t.getItem("path"),s=i&&t.getItem("revision")===null,l=this.gramlot.rpc.call("data",s?"document_create":"document_save",{root:t.getItem("root"),path:a,content:i?E.fromTytx(r):r,...s?{}:{revision:t.getItem("revision")}},{signal:o.signal}).then(u=>this.disposed||o.signal.aborted?!1:(t.setItem("revision",u.revision),t.setItem("saved",r),!0)).finally(()=>{this.pending.delete(e),this.disposed||t.setItem("busy",!1)});return this.pending.set(e,{request:o,promise:l}),l}revert(e){let t=this.documents.getItem(e);return!t||!this.dirty(e)||this.pending.has(e)?!1:(t.setItem("content",t.getItem("saved")),t.getItem("language")==="image"&&(t.getItem("annotations").replace(E.fromTytx(t.getItem("saved"))),t.setItem("content",t.getItem("saved"))),!0)}canClose(e,t=!1){return!this.pending.has(e)&&(t||!this.dirty(e))}close(e,t=!1){return this.canClose(e,t)?(this.documents.popNode(e),this.state.getItem("active")===e&&this.state.setItem("active",this.documents.getNodes()[0]?.label??null),!0):!1}dispose(){this.disposed=!0;for(let{request:e}of this.pending.values())e.abort()}},nl=class{constructor(e){this.storage=e,this.key="gramlot.ide.recentWorkspaces"}read(){let e=this.storage.getItem(this.key),t=e===null?[]:JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"||!r))throw new TypeError("Invalid recent workspace preference");return t.slice(0,6)}remember(e){let t=[e,...this.read().filter(r=>r!==e)].slice(0,6);return this.storage.setItem(this.key,JSON.stringify(t)),t}choices(e=this.read()){let t=new E;return e.forEach((r,o)=>t.setItem(`r${o}`,r,{caption:r})),t}};function at(n){for(let e=n;e;e=e.parentNode){let t=e.ideContext;if(t)return t}throw new Error("IDE operation requires a node inside a mounted IDE")}var ol=class{fileSystemMount(e){return wn.prototype.fileSystemMount.call(this,e)}fileSystemOpen(e,t){return wn.prototype.fileSystemOpen.call(this,e,t)}ideMount(e){let t=e.parentNode,r={scope:t,documents:new rl(this.page,t),requested:0,editorPrefix:`ide_${J()}`,recent:new nl(this.page.src.renderer.destination.ownerDocument.defaultView.sessionStorage)};Object.defineProperty(t,"ideContext",{value:r,configurable:!0});let{documents:o,recent:i}=r,a=t.getRelativeData("."),s=i.read();a.setItem("recent",i.choices(s)),a.setItem("workspace",s[0]??"");let l=a.getItem("browser");l.subscribe("ide-browser",{any:c=>{if(c.node===l.getNode("root")){let d=l.getItem("root");a.setItem("workspace",d),a.setItem("recent",i.choices(i.remember(d))),a.setItem("status",`Workspace: ${d}`)}else if(c.node===l.getNode("selectedPath")){let d=l.getItem("selectedPath"),f=d===null?null:l.getItem("store").getNode(d);f&&!f.attr.is_directory&&this.ideOpenDocument(t,l.getItem("root"),f.attr.path)}}});let u=o.documents;u.subscribe("ide-documents",{any:c=>{if(["content","saved","busy","writable","view","isNew","path","root"].includes(c.node.label))for(let d of t.value.getNode("frame.center.tabs").value?.getNodes()??[]){let f=d.getAttr("documentKey"),h=o.documents.getItem(f);h&&(c.node===h.getNode("content")&&o.invalidateRecipe(f),this.ideDocumentState(t,f),d.setAttr({title:`${o.dirty(f)?"\u25CF ":""}${h.getItem("path")}`}))}}}),this.page.src.renderer.onDispose(r.scope,()=>{l.unsubscribe("ide-browser",{any:!0}),u.unsubscribe("ide-documents",{any:!0}),o.dispose()})}ideOpenWorkspace(e){let r=at(e).scope.getRelativeData("."),o=r.getItem("workspace");o&&o!==r.getItem("browser.root")&&r.setItem("browser.requestedRoot",o)}async ideUploadCompleted(e,{result:t}){let r=at(e),o=r.scope.getRelativeData(".");if(o.getItem("browser.root")!==t.root)return;o.setItem("upload.open",!1);let i=r.scope.value.getNode("frame.left.browser").fileSystemController;if(i.request)return;await i.open(t.root)===t.root&&!r.documents.disposed&&o.getItem("browser.root")===t.root&&await this.ideOpenDocument(r.scope,t.root,t.path)}ideDocumentState(e,t){let r=at(e),{documents:o}=r,i=o.documents.getItem(t),a=!o.dirty(t)&&!i.getItem("isNew")||i.getItem("busy");i.setItem("saveDisabled",!!(a||!i.getItem("writable"))),i.setItem("revertDisabled",!!(!o.dirty(t)||i.getItem("busy"))),i.setItem("displayPath",i.getItem("isNew")?i.getItem("path"):`${i.getItem("root")}/${i.getItem("path")}`),i.setItem("pdfFilename",i.getItem("path").split("/").at(-1).replace(/\.typ(?:\.py)?$/i,".pdf")),i.setItem("renderDisabled",!!(i.getItem("busy")||!i.getItem("writable"))),this.ideHistoryState(i)}async ideOpenDocument(e,t,r){let o=at(e),{documents:i}=o,a=o.scope.getRelativeData("."),s=++o.requested;try{let l=await i.open(t,r);if(l===null||i.disposed)return;this.ideShowDocument(e,l),s===o.requested&&(a.setItem("active",l),a.setItem("status",`${r}${i.documents.getItem(l).getItem("writable")?"":" (draft only \u2014 Remote Edit is disabled)"}`))}catch(l){i.disposed||a.setItem("status",l.message)}}ideNew(e){let t=at(e),{documents:r}=t,o=t.scope.getRelativeData("."),i=o.getItem("newType"),a=i==="typstRecipe"?"python":i,s={typstRecipe:".typ.py",typst:".typ",markdown:".md",html:".html",python:".py",javascript:".js",typescript:".ts",json:".json",css:".css",sql:".sql",xml:".xml",text:".txt"},l=r.newDocument(a,s[i],o.getItem("workspace"));r.documents.getItem(l).setItem("writable",o.getItem("browser.writable")===!0),++t.requested,this.ideShowDocument(e,l),o.setItem("active",l),o.setItem("status","New document. Choose directory and name when saving.")}ideShowDocument(e,t){let r=at(e),{documents:o}=r,a=o.documents.getItem(t).getItem("path"),s=r.scope.value.getNode("frame.center.tabs");if(!s.value?.getNode(t)){let l=o.documents.getItem(t),u=a.endsWith(".typ.py");u&&o.invalidateRecipe(t),l.setItem("readonly",!1),this.ideDocumentState(e,t),l.setItem("view","code"),l.setItem("createHidden",!0),l.setItem("undoDisabled",!0),l.setItem("redoDisabled",!0);let c=ae(s.builder.wrapSource(s).contentPane({node_label:t,title:a,pageName:t,documentKey:t,closable:!0,onClose:"ideClose",height:"100%"})),d=c.builder.wrapSource(c).div({display:"flex",flex_direction:"column",height:"100%"}),f=d.div({datapath:`.documents.${t}`,display:"flex",align_items:"center",gap:"6px",padding:"4px 12px",height:"40px",flex_shrink:0,box_sizing:"border-box",class:"gramlot-ide-document-toolbar",role:"toolbar","aria-label":`Commands for ${a}`});for(let[m,b,w,_]of[["save","M5 3h12l4 4v14H3V3h2 M7 3v6h10V3 M7 21v-8h10v8","Save","ideSave"],["revert","M3 10a9 9 0 1 1 2 8 M3 4v6h6 M12 7v5l3 2","Revert to saved","ideRevert"],["undo","M9 5 3 11l6 6 M3 11h12a6 6 0 0 1 6 6v2","Undo","ideUndo"],["redo","m15 5 6 6-6 6 M21 11H9a6 6 0 0 0-6 6v2","Redo","ideRedo"]]){let y=f.button({title:w,"aria-label":w,disabled:`^.${m}Disabled`,class:`button--quiet gramlot-ide-${m}`});y.svg({viewBox:"0 0 24 24",width:18,height:18,fill:"none",stroke:"currentColor",stroke_width:1.7,stroke_linecap:"round",stroke_linejoin:"round","aria-hidden":"true"}).path({d:b}),y.dataController({func:_,documentKey:t})}u&&f.button("Generate preview",{disabled:"^.renderDisabled",class:"button--quiet"}).dataController({func:"ideRenderRecipe",documentKey:t}),f.div("^.displayPath",{class:"gramlot-ide-document-path",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap",min_width:0,flex:"1"});let h=d.div({datapath:`.documents.${t}`,hidden:"^.createHidden",padding:"8px 12px",display:"flex",gap:"8px",align_items:"end",flex_shrink:0});h.textbox({value:"^.saveRoot",lbl:"Directory",flex:"1",disabled:"^.busy"}),h.textbox({value:"^.savePath",lbl:"File name",flex:"1",disabled:"^.busy"}),h.button("Create file",{disabled:"^.busy"}).dataController({func:"ideCreate",documentKey:t}),h.button("Cancel",{disabled:"^.busy",class:"button--quiet"}).dataController({func:"ideCancelCreate",documentKey:t});let p=d.div({flex:"1",min_height:0});if(l.getItem("language")==="image")p.drawingPane({image:`^.documents.${t}.image`,annotations:`^.documents.${t}.annotations`,height:"100%"});else{let m=l.getItem("language")==="html",b=l.getItem("language")==="markdown",w=m||b,_=l.getItem("language")==="typst",y=w||_||u,x=y?p.tabContainer({height:"100%",selectedPage:`^.documents.${t}.view`}):null,D=y?x.contentPane({title:"Code",pageName:"code",height:"100%"}):p;if(tl(D,{datapath:`.documents.${t}`,value:"^.content",language:l.getItem("language"),height:"100%",readonly:"^.readonly",nodeId:`${r.editorPrefix}_editor_${t}`,editorView:"code",selfsubscribe_historyChanged:"ideHistoryChanged"}),d.dataController({func:"ideSave",documentKey:t,[`subscribe_${r.editorPrefix}_editor_${t}_save`]:!0}),_&&x.contentPane({title:"Preview",pageName:"preview",height:"100%"}).typstPreview({value:`^.documents.${t}.content`,filename:`^.documents.${t}.pdfFilename`,height:"100%"}),u){let k=x.contentPane({title:"Preview",pageName:"preview",height:"100%",display:"flex",flex_direction:"column"});k.div(`^.documents.${t}.renderStatus`,{role:"status",padding:"8px 12px",white_space:"pre-wrap",overflow:"auto",max_height:"30%"}),k.typstPreview({value:`^.documents.${t}.typstSource`,filename:`^.documents.${t}.pdfFilename`,hidden:`^.documents.${t}.previewHidden`,flex:"1",min_height:0}),x.contentPane({title:"Generated Typst",pageName:"generated",height:"100%"}).codeMirror({value:`^.documents.${t}.typstSource`,language:"typst",readonly:!0,height:"100%"})}if(w){let k=x.contentPane({title:"Preview",pageName:"preview",height:"100%",display:"flex",flex_direction:"column"});b&&(l.setItem("allowHtml",!1),k.checkbox({value:`^.documents.${t}.allowHtml`,label:"Allow embedded HTML",class:"gramlot-ide-allow-html",padding:"8px 12px",flex_shrink:0})),k[m?"htmlPreview":"markdownPreview"]({value:`^.documents.${t}.content`,flex:"1",min_height:0,...b?{allowHtml:`^.documents.${t}.allowHtml`}:{}}),x.contentPane({title:"Rich text",pageName:"rich",height:"100%"})[m?"htmlEditor":"markdownEditor"]({datapath:`.documents.${t}`,value:"^.content",readonly:"^.readonly",height:"100%",nodeId:`${r.editorPrefix}_rich_editor_${t}`,editorView:"rich",selfsubscribe_historyChanged:"ideHistoryChanged"}),d.dataController({func:"ideSave",documentKey:t,[`subscribe_${r.editorPrefix}_rich_editor_${t}_save`]:!0})}}}}async ideRenderRecipe(e,{documentKey:t}){let r=at(e),{documents:o}=r;o.documents.getItem(t).setItem("view","preview"),await o.renderRecipe(t)}ideCancelCreate(e,{documentKey:t}){let r=at(e),{documents:o}=r;o.documents.getItem(t).setItem("createHidden",!0)}async ideCreate(e,{documentKey:t}){let r=at(e),{documents:o}=r,i=r.scope.getRelativeData(".");i.setItem("status","Creating file\u2026");try{let a=await o.create(t);if(!o.disposed&&a){i.setItem("status","File created.");let s=i.getItem("browser");s.getItem("root")&&await r.scope.value.getNode("frame.left.browser").fileSystemController.open(s.getItem("root"))}}catch(a){o.disposed||i.setItem("status",a.message)}}async ideSave(e,{documentKey:t=null}={}){let r=at(e),{documents:o}=r,i=r.scope.getRelativeData("."),a=t??i.getItem("active");if(!a||o.documents.getItem(a).getItem("saveDisabled"))return;let s=o.documents.getItem(a);if(s.getItem("isNew")){s.setItem("createHidden",!1);return}i.setItem("status","Saving\u2026");try{let l=await o.save(a);o.disposed||i.setItem("status",l?"Saved.":"Document is read only or a request is pending.")}catch(l){o.disposed||i.setItem("status",l.message)}}ideRevert(e,{documentKey:t}){let r=at(e),{documents:o}=r,i=r.scope.getRelativeData(".");o.revert(t)&&i.setItem("status","Restored the last saved version.")}ideHistoryChanged(e,{canUndo:t,canRedo:r}){let o=e.getRelativeData("."),i=e.getAttr("editorView");o.setItem(`${i}CanUndo`,t),o.setItem(`${i}CanRedo`,r),this.ideHistoryState(o)}ideHistoryState(e){let t=e.getItem("view");e.setItem("undoDisabled",!e.getItem(`${t}CanUndo`)),e.setItem("redoDisabled",!e.getItem(`${t}CanRedo`))}ideEditor(e,t){let r=at(e),{documents:o}=r,i=o.documents.getItem(t).getItem("view")==="rich",a=this.page.src.binding.nodeIds.get(`${r.editorPrefix}_${i?"rich_":""}editor_${t}`);return this.page.src.renderer.records.get(a).element}ideUndo(e,{documentKey:t}){this.ideEditor(e,t).undo()}ideRedo(e,{documentKey:t}){this.ideEditor(e,t).redo()}ideClose(e){let t=at(e),{documents:r}=t,o=t.scope.getRelativeData("."),i=e.getAttr("documentKey");return r.canClose(i)?!0:(o.setItem("status","Save or revert your changes before closing. Pending operations must finish first."),!1)}ideClosed(e,{pageName:t}){this.ideForgetDocument(e,t)}ideForgetDocument(e,t,r=!1){let o=at(e),{documents:i}=o,a=o.scope.getRelativeData("."),s=i.documents.getItem(t),l=a.getItem("browser"),u=l.getItem("selectedPath"),c=u===null?null:l.getItem("store").getNode(u);s&&l.getItem("root")===s.getItem("root")&&c?.attr.path===s.getItem("path")&&l.setItem("selectedPath",null),i.close(t,r)}};var Br=class extends fe{constructor({readOnly:e=!1}={}){super({cacheTime:-1,readOnly:e}),this.store=null,this.path=null,this.pending=null}bind(e,t){if(this.store!==null)throw new Error("TreeStoreResolver is already bound");this.store=e,this.path=t}load(){if(this.store===null)throw new Error("TreeStoreResolver is not bound to a store");if(this.pending!==null)return this.pending;let e=this.node,t=this.path?this.store.pathFor(e):"",r=this.store.load(t,t?e.label:null,t?{...e.attr}:{});return this.pending=r,r.finally(()=>{this.pending===r&&(this.pending=null)}).catch(()=>{}),r}};Fu(Br,{module:"gramlot.tree_store",name:"TreeStoreResolver",encode:()=>({args:[],kwargs:{}}),decode:()=>new Br});var Yi=class{constructor({gramlot:e,method:t,params:r={}}){if(!e||typeof t!="string"||!t)throw new TypeError("TreeStore requires a page and method");for(let o of["path","label","attributes"])if(Object.hasOwn(r,o))throw new TypeError(`TreeStore params reserves ${o}`);this.gramlot=e,this.method=t,this.params={...r},this.controller=new AbortController,this.root=null}pathFor(e){let t=[];for(;e&&e.parentBag!==this.root;)t.unshift(e.label),e=e.parentNode;if(!e||this.root===null)throw new Error("TreeStore node is outside its root");return t.unshift(e.label),t.join(".")}async load(e="",t=null,r={}){if(this.controller.signal.aborted)throw this.controller.signal.reason;let o=await this.gramlot.rpc.call("data",this.method,{...this.params,path:e,label:t,attributes:r},{signal:this.controller.signal});if(this.controller.signal.aborted)throw this.controller.signal.reason;if(!(o instanceof E))throw new TypeError("TreeStore method must return a Bag");e||(this.root=o,o.setBackref());let i=(a,s)=>{for(let l of a.getNodes()){let u=s?`${s}.${l.label}`:l.label;l.resolver instanceof Br&&l.resolver.bind(this,u),l.staticValue instanceof E&&i(l.staticValue,u)}};return i(o,e),o}dispose(){this.controller.abort()}},il=class{treeFavoriteActionState(e,{item:t,state:r}){let o=t.resolver!==null||t.staticValue instanceof E;if(t.getAttr("favoriteEntry")===!0)return{hidden:!1,icon:"\u2715",title:"Remove favorite"};let i=!o&&r.getNodes().some(a=>a.getAttr("fieldpath")===t.getAttr("fieldpath"));return{hidden:o,icon:i?"\u2665":"\u2661",title:i?"Remove favorite":"Add favorite"}}treeFavoritesMount(e,{favoriteKey:t}){let o=this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.getItem(t);this.setTreeFavorites(e.getRelativeData("."),o===null?[]:j(o))}setTreeFavorites(e,t){if(!Array.isArray(t))throw new TypeError("Tree favorites must be an array");let r=new E;t.forEach((o,i)=>{if(!o||typeof o.fieldpath!="string"||typeof o.path!="string"||typeof o.caption!="string"||!o.attrs||typeof o.attrs!="object")throw new TypeError("Invalid tree favorite");let a={...o.attrs};for(let s of["caption","fullcaption"])typeof a[s]=="string"&&(a[s]=a[s].replace(/(^|\.)!!(?:\[[^\]]+\])?/g,"$1"));r.setItem(`favorite_${i}`,null,{...a,favoriteEntry:!0,originalPath:o.path})}),e.setItem("favorites",r)}treeFavoriteToggle(e,{item:t,path:r,favoriteKey:o}){if(t.resolver||t.staticValue instanceof E)return;let i=t.getAttr(),a=e.getRelativeData("."),s=a.getItem("favorites").getNodes().map(c=>{let{favoriteEntry:d,originalPath:f,...h}=c.getAttr();return{fieldpath:h.fieldpath,path:f,caption:h.caption,attrs:h}}),l=s.findIndex(c=>c.fieldpath===i.fieldpath);l===-1?s.push({fieldpath:i.fieldpath,path:r,caption:i.caption,attrs:{...i}}):s.splice(l,1),this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.setItem(o,L(s)),this.setTreeFavorites(a,s)}treeStoreMount(e,{storeMethod:t,storeParams:r}){let o=e.parentNode,i=e.getRelativeData("."),a=new Yi({gramlot:this.page,method:t,params:r});this.page.src.renderer.onDispose(o,()=>a.dispose());let s=new Br({readOnly:!0});return s.bind(a,""),i.setResolver("store",s),Promise.resolve(i.getItem("store")).then(l=>{a.controller.signal.aborted||i.setItem("store",l)})}treeInspect(e,{item:t,path:r}){let o=this.page.src.binding.bindingFor(e),i=!1,a=`tree_inspect_${J()}`,s=()=>{},l=()=>{i||(i=!0,s(),this.page.src.source.getNode(a)&&this.page.src.source.popNode(a))};s=o.track(l);try{let u=new Oe,c=u.root.html_dialog({nodeId:a,request:a,connect_oncancel:"treeInspectClose",connect_onclose:"treeInspectClose","aria-labelledby":`${a}_title`,style:"width:min(36rem,calc(100% - 48px));max-height:80vh;overflow:auto;"});c.h2("Attributes",{id:`${a}_title`}),c.p(`==${JSON.stringify(r)}`),c.html_button("Close",{type:"button",autofocus:!0,request:a,connect_onclick:"treeInspectClose"});let d=c.table();for(let[h,p]of Object.entries(t.getAttr())){let m=d.tr();m.th(`==${JSON.stringify(h)}`,{scope:"row"});let b=typeof p=="string"?p:p===void 0?"undefined":L(p);m.td(`==${JSON.stringify(b)}`)}this.page.src.source.setItem(a,this.page.src.prepareSource(u.source));let f=this.page.src.binding.nodeIds.get(a);Object.defineProperty(f,"treeInspectClose",{value:l,configurable:!0}),this.page.src.renderer.onDispose(f,()=>{l(),delete f.treeInspectClose}),this.page.dom.getDomNode(f).showModal()}catch(u){throw l(),u}}treeInspectClose(e,t){t.preventDefault();let r=this.page.src.binding.nodeIds.get(e.getAttr("request"));r&&r.treeInspectClose()}};var vo=class{constructor({maxBytes:e}){if(!Number.isSafeInteger(e)||e<0)throw new TypeError("maxBytes must be a nonnegative safe integer");this.maxBytes=e}write(e){throw new Error("UploadTarget.write must be implemented")}finish(){throw new Error("UploadTarget.finish must be implemented")}abort(){throw new Error("UploadTarget.abort must be implemented")}status(){throw new Error("UploadTarget.status must be implemented")}};var U2=new Set(Object.entries(new qt().schema).filter(([,n])=>!n._meta?.data_element&&!n._meta?.subbuilder&&!n._meta?.container).map(([n])=>n));function Eo(n){if(!(n==null||n==="html")){if(!Array.isArray(n)||n.some(e=>typeof e!="string"||!e||e.trim()!==e))throw new TypeError('catalogue must be "html" or a list of tag names');if(!n.includes("div"))throw new Error("catalogue must include div for pageRoot")}}function xo(n,e,t={}){return n==null?!0:Array.isArray(n)?n.includes(e):!t.gramlot_component&&!t.data_element&&!t.subbuilder&&!t.container&&U2.has(t.render_tag??e)}function Dt(n,e){if(n==null)return;let t=(r,o)=>{for(let i of r.getNodes()){let a=o?`${o}.${i.label}`:i.label;if(!xo(n,i.nodeTag,i.getAttr("_meta")??{}))throw new Error(`Tag ${i.nodeTag} is outside the editor catalogue at ${a}`);if(i.resolver)throw new Error(`Catalogue scope requires materialized Source at ${a}`);let s=i.getValue(!0);s instanceof I&&t(s,a)}};t(e,"")}var Ge={navigation:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%224%22%20width%3D%2218%22%20height%3D%2216%22%20rx%3D%222%22%2F%3E%3Cpath%20d%3D%22M9%204v16M5.5%208h1M5.5%2012h1%22%2F%3E%3C%2Fsvg%3E",catalogue:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%223%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Crect%20x%3D%2214%22%20y%3D%223%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Crect%20x%3D%223%22%20y%3D%2214%22%20width%3D%227%22%20height%3D%227%22%20rx%3D%221%22%2F%3E%3Cpath%20d%3D%22M14%2017.5h7M17.5%2014v7%22%2F%3E%3C%2Fsvg%3E",properties:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M4%206h16M4%2012h16M4%2018h16%22%2F%3E%3Ccircle%20cx%3D%228%22%20cy%3D%226%22%20r%3D%222%22%2F%3E%3Ccircle%20cx%3D%2216%22%20cy%3D%2212%22%20r%3D%222%22%2F%3E%3Ccircle%20cx%3D%2210%22%20cy%3D%2218%22%20r%3D%222%22%2F%3E%3C%2Fsvg%3E",new:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M14%202H6a2%202%200%200%200-2%202v16a2%202%200%200%200%202%202h12a2%202%200%200%200%202-2V8Z%20M14%202v6h6%20M8%2015h8%20M12%2011v8%22%2F%3E%3C%2Fsvg%3E",download:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M12%203v12m-5-5%205%205%205-5%20M4%2016v4a1%201%200%200%200%201%201h14a1%201%200%200%200%201-1v-4%22%2F%3E%3C%2Fsvg%3E",copy:"data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%228%22%20y%3D%228%22%20width%3D%2212%22%20height%3D%2213%22%20rx%3D%222%22%2F%3E%3Cpath%20d%3D%22M16%208V5a2%202%200%200%200-2-2H5a2%202%200%200%200-2%202v9a2%202%200%200%200%202%202h3%22%2F%3E%3C%2Fsvg%3E"};Ge.open="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M3%207V5a2%202%200%200%201%202-2h5l2%202h7a2%202%200%200%201%202%202v2M3%209h18l-2%2011H4z%22%2F%3E%3C%2Fsvg%3E";Ge.cut="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Ccircle%20cx%3D%226%22%20cy%3D%226%22%20r%3D%223%22%2F%3E%3Ccircle%20cx%3D%226%22%20cy%3D%2218%22%20r%3D%223%22%2F%3E%3Cpath%20d%3D%22m8%208%2012%2012M8%2016%2020%204%22%2F%3E%3C%2Fsvg%3E";Ge.paste="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%237b8795%22%20stroke-width%3D%221.7%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%225%22%20y%3D%225%22%20width%3D%2214%22%20height%3D%2216%22%20rx%3D%222%22%2F%3E%3Crect%20x%3D%229%22%20y%3D%222%22%20width%3D%226%22%20height%3D%225%22%20rx%3D%221%22%2F%3E%3Cpath%20d%3D%22M9%2012h6m-6%204h6%22%2F%3E%3C%2Fsvg%3E";Ge.appearance="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%3E%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%228%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.7%22%2F%3E%3Cpath%20d%3D%22M12%204a8%208%200%200%201%200%2016z%22%20fill%3D%22black%22%2F%3E%3C%2Fsvg%3E";var al=class{constructor(e,{datapath:t="__editor",dataRoot:r="",editorId:o="visual",uploadOperation:i="import_source",codeDocument:a=null,catalogue:s=null,fileCommands:l=!0,canvasCss:u=null,...c}={}){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(o))throw new Error("editorId must be a literal identifier");if(!r&&t!=="__editor"&&!t.startsWith("__editor."))throw new Error("Root Data editing requires an __editor datapath");if(Eo(s),u!=null&&(!Array.isArray(u)||u.some(Z=>typeof Z!="string")))throw new TypeError("canvasCss must be a list of CSS texts");this.dataRoot=r;let d=this.pane=e.main({node_label:o,datapath:t,visualEditorId:o,...c,nodeId:`${o}Editor`,class:`visual-editor-shell ${c.class??""}`,overflow:"hidden",tabindex:0,connect_onkeydown:"clipboardShortcut"});d.dataSetter({destination_path:".catalogueScope",value:s}),d.dataSetter({destination_path:".canvasCss",value:u}),d.dataSetter({destination_path:".uploadQueue",value:new E}),d.dataController({func:"initializeEditor",dataRoot:this.dataRoot,_init:!0}),d.dataController({func:"showProperties",path:"^.selection",_init:!0}),d.dataController({func:"initializeCanvasSelection",_onBuilt:!0}),d.dataController({func:"initializeDocument",_onBuilt:!0}),d.dataController({func:"highlightSelection",path:"^.selection",_init:!0}),d.style("^.appearanceCss"),d.dataController({func:"initializeEditorAppearance",_onBuilt:!0}),d.dataController({func:"applyEditorAppearance",profile:"^.appearanceProfile",palette:"^.appearancePalette",mode:"^.appearanceMode"});let f=this.rail=d.menu({presentation:"bar",orientation:"vertical",aria_label:"Editor panels",class:"visual-editor-rail"});this.toolButton(f.menuline({group:!0}),"Source / Data","toggleNavigation",Ge.navigation),this.toolButton(f.menuline({group:!0}),"Catalogue","openCatalogue",Ge.catalogue),this.toolButton(f.menuline({group:!0}),"Properties","openProperties",Ge.properties),this.toolButton(f.menuline({group:!0}),"Clipboard","this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))",Ge.paste,{dropTarget:!0,dropTypes:"app/source",dropTags:`${o}Source`,dropEffect:"^.clipboardDropEffect",connect_ondragover:"clipboardModifiers",connect_ondrop:"clipboardModifiers",onDrop:"dropClipboard"}),f.spacer({flex:1}),this.toolButton(f.menuline({group:!0}),"Appearance","this.SET('.appearanceOpen', !this.GET('.appearanceOpen'))",Ge.appearance);let h=d.framePane({node_label:"layout",height:"100%",id:`${o}-editor-frame`,class:"visual-editor-layout"});h.top.setAttr({height:"30px"});let p=h.top.menu({presentation:"bar",aria_label:"Editor tools",class:"visual-editor-toolbar"});p.menuline({group:!0}).span("Source editor",{class:"visual-editor-brand"});let m=p.menuline({group:!0,gap:"4px",hidden:!l});for(let[Z,Be,zt]of[["New","newPage","new"],["Open","openUpload","open"],["Download","downloadPage","download"],["Copy Source","copySource","copy"]])this.toolButton(m,Z,Be,Ge[zt],{id:`${o}-${zt}`});p.menuline({group:!0}).span({class:"visual-toolbar-divider",aria_hidden:"true"});let b=p.menuline({group:!0,gap:"2px"});this.toolButton(b,"Cut branch","cutBranch",Ge.cut,{title:"Cut branch (F8)"}),this.toolButton(b,"Copy branch","copyBranch",Ge.copy),this.toolButton(b,"Paste branch","pasteBranch",Ge.paste,{title:"Paste branch (F9)"}),p.spacer({flex:1}),p.menuline({group:!0,hidden:"^.modified:=!{}"}).span("Unsaved changes",{role:"status",class:"visual-editor-hint"}),p.menuline({group:!0}).span("^.fileStatus",{role:"status",class:"visual-editor-file-status"}),p.menuline({group:!0}).span("^.filename",{class:"visual-editor-filename"});let w=h.left;w.setAttr({width:"min(240px, 34vw)",splitter:!0,drawer:"^.navigationOpen",default_drawer:!0,drawer_label:"Source / Data",drawer_onclick:"this.SET('.navigationOpen', show ? true : 'close')",display:"flex",flex_direction:"column",min_height:0,class:"visual-editor-sidebar"});let _=w.borderContainer({height:"100%",flex:1,min_height:0}),y=_.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),x=y.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),D=x.contentPane({node_label:"source",region:"center",title:"Source",detachable:!0,display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"});this.search(D,"sourceSearch","Search Source"),D.tree({storepath:`*S.${ae(d).fullpath.split(".").slice(1).join(".")}.layout.center.design`,hideValues:!0,getLabel:"sourceLabel",searchText:"^.sourceSearch",selectedPath:"^.selection",draggable:!0,dragTags:`${o}Source`,effectAllowed:"all",onDrag:"prepareSource",dropTarget:!0,dropTypes:"app/widget,app/source,app/clipboard",dropTags:`widget,${o}Source,${o}Clipboard`,dropEffect:"^.sourceDropEffect",onDrop:"dropNode",id:`${o}-source-tree`,class:"visual-source-tree",flex:1,min_height:0});let k=x.contentPane({node_label:"clipboard",region:"bottom",height:"112px",splitter:!0,minSize:80,title:"Clipboard",detachable:!0,hidden:"^.clipboardVisible:=!{}",display:"flex",flex_direction:"column",min_height:0,overflow:"hidden",dropTarget:!0,dropTypes:"app/source",dropTags:`${o}Source`,dropEffect:"^.clipboardDropEffect",connect_ondragover:"clipboardModifiers",connect_ondrop:"clipboardModifiers",onDrop:"dropClipboard",class:"visual-clipboard"});k.span("Drop a branch here \xB7 Option to copy",{class:"visual-editor-hint"}),k.tree({storepath:".clipboard",hideValues:!0,labelAttribute:"name",selectedPath:"^.clipboardSelection",draggable:!0,dragTags:`${o}Clipboard`,effectAllowed:"copy",onDrag:"prepareClipboard",id:`${o}-clipboard-tree`,class:"visual-clipboard-tree",flex:1,min_height:0}),k.p("^.error",{role:"alert",class:"visual-editor-hint"});let C=y.contentPane({node_label:"data",region:"bottom",title:"Data",detachable:!0,height:"108px",splitter:!0,minSize:80,display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"});this.search(C,"dataSearch","Search Data"),C.tree({storepath:this.dataRoot?`*D.${this.dataRoot}`:"*D",excludeRoot:this.dataRoot?null:"__editor",searchText:"^.dataSearch",id:`${o}-data-tree`,flex:1,min_height:0});let O=h.center;O.setAttr({overflow:"auto",class:"visual-editor-workspace"});let $=O.div({node_label:"design",class:"visual-editor-canvas"});$.div({node_label:"pageRoot",...this.dataRoot?{datapath:this.dataRoot}:{}});let F=d.floatingPane({title:"Widget catalogue",open:"^.catalogueOpen",default_open:!1,width:"280px",height:"400px",class:"visual-editor-popup",movable:!0,resizable:!0});this.search(F.frame.top,"catalogueSearch","Search widgets"),F.frame.center.tree({storepath:".catalogue",hideValues:!0,labelAttribute:"caption",searchText:"^.catalogueSearch",draggable:!0,dragTags:"widget",effectAllowed:"all",onDrag:"prepareWidget",id:`${o}-widget-tree`});let H=_.contentPane({region:"bottom",height:"^.propertiesHeight",default_height:"200px",minSize:140,splitter:!0,title:"^.propertiesTitle",detachable:!0,hidden:"^.propertiesOpen:=!{}",display:"flex",flex_direction:"column",overflow:"hidden",min_height:0});H.div({nodeId:`${o}EditorFields`,class:"visual-editor-fields",display:"flex",flex_direction:"column",flex:1,min_height:0}).span(""),H.p("^.propertyError",{role:"alert",class:"visual-editor-hint",margin:"3px"}),d.dialog({class:"visual-editor-popup",title:"Open Source",open:"^.uploadOpen",width:"480px",height:"300px",movable:!0,resizable:!0}).frame.center.uploader({operation:i,storepath:".uploadQueue",accept:".grmlt",multiple:!1,autoUpload:!0,onComplete:"sourceUploaded",id:`${o}-uploader`});let me=d.dialog({class:"visual-editor-popup",title:"Save branch to clipboard",open:"^.clipboardOpen",width:"380px",height:"210px"});me.frame.center.textbox({value:"^.clipboardDraft.name",lbl:"Name",margin:"12px"}),me.frame.center.p("^.error",{role:"alert",margin:"12px"});let re=me.frame.bottom.menu({presentation:"bar",aria_label:"Clipboard commands",padding:"3px 6px"});re.spacer({flex:1});let ue=re.menuline({group:!0,gap:"8px"});ue.button("Cancel",{action:"this.SET('.clipboardOpen', false)"}),ue.button("Save branch",{action:"saveClipboard"});let U=d.dialog({class:"visual-editor-popup",title:"Required parameters",open:"^.insertionOpen",width:"400px",height:"280px",movable:!0,resizable:!0});U.frame.center.div({nodeId:`${o}InsertFields`,class:"visual-editor-fields",padding:"6px"}).span(""),U.frame.center.p("^.error",{role:"alert"});let dt=U.frame.bottom.menu({presentation:"bar",aria_label:"Insertion commands",padding:"3px 6px",border_top:"1px solid var(--gramlot-border)"});dt.spacer({flex:1});let yn=dt.menuline({group:!0,gap:"8px"});yn.button("Cancel",{action:"this.SET('.insertionOpen', false)"}),yn.button("Insert",{action:"insertWidget"});let wt=d.floatingPane({class:"visual-editor-popup",title:"Appearance",open:"^.appearanceOpen",default_open:!1,width:"280px",height:"260px",movable:!0,resizable:!0}).frame.center.formlet({columns:1,lbl_position:"TL",gap:"4px",padding:"6px"});wt.filteringSelect({validate_notnull:!0,lbl:"Theme",value:"^.appearanceProfile",values:"base:Base,compact:Compact,mimi:Mimi,joanna:Joanna,mela:Mela"}),wt.filteringSelect({validate_notnull:!0,lbl:"Colors",value:"^.appearancePalette",values:"default:Theme default,compact:Blue & slate,mimi:Sage & green,joanna:Warm gray & blue"}),wt.filteringSelect({validate_notnull:!0,lbl:"Mode",value:"^.appearanceMode",values:"light:Light,dark:Dark"}),d.p("^.error",{role:"alert",class:"visual-editor-error",hidden:"^.error:=!{}"}),this.frame=h,this.toolbar=p,this.design=$,a!==null&&this.codeDocument(a)}toolButton(e,t,r,o,i={}){let a=e.button({aria_label:t,title:t,action:r,class:"button--quiet visual-editor-tool",...i});return a.span({class:"visual-tool-icon",aria_hidden:"true",style:`mask-image:url("${o}")`}),a}codeDocument(e,t=this.frame){if(!["python","javascript"].includes(e.language))throw new TypeError("Expected a Python or JavaScript page document");let r=this.pane;r.setAttr({codeDocumentKey:e.key}),r.dataSetter({destination_path:".codeDocument",value:new E({...e,saved:e.content,busy:!1,status:""})});let o=`#${r.getAttr("visualEditorId")}Editor`;(t===this.frame?this.toolbar:t.top.menu({presentation:"bar",aria_label:"Code drawer"})).menuline({group:!0}).button("Code",{action:"openCode",class:"button--quiet"});let a=t.right;a.setAttr({class:"visual-editor-code",datapath:o,title:"Page code",detachable:!0,width:"60%",minSize:240,splitter:!0,drawer:"^.codeOpen",default_drawer:"close",drawer_label:"Code",drawer_minimize:!1,drawer_onclick:"this.SET('.codeOpen', show ? true : 'close')",min_height:0,overflow:"hidden"});let s=a.framePane({height:"100%",width:"100%",min_width:0,flex:1});s.top.setAttr({height:"26px"}),s.bottom.setAttr({height:"48px"}),s.center.setAttr({display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"}),s.top.div(e.path,{padding:"3px 6px",font_size:"12px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),s.center.codeMirror({value:"^.codeDocument.content",language:e.language,live:!0,readonly:"^.codeDocument.writable:=!{}",height:"100%",box_height:"100%",box_c_height:"100%",box_min_height:0,box_c_min_height:0,fontSize:13,flex:1,min_height:0}),s.bottom.div("^.codeDocument.status",{role:"status",font_size:"12px",padding:"4px 10px"});let l=s.bottom.menu({presentation:"bar",aria_label:"Page code commands",padding:"3px 6px"});l.spacer({flex:1});let u=l.menuline({group:!0,gap:"6px"});u.button("Close",{action:"this.SET('.codeOpen', 'close')"}),u.button("Preview saved",{action:"codePreview",disabled:"^.codeDocument.busy"}),u.button("Save",{action:"codeSave",disabled:"^.codeSaveDisabled"}),r.dataFormula({result_path:".codeSaveDisabled",formula:"!writable || busy || content === saved",writable:"^.codeDocument.writable",busy:"^.codeDocument.busy",content:"^.codeDocument.content",saved:"^.codeDocument.saved",_init:!0})}search(e,t,r){let i=e.menu({presentation:"bar",aria_label:r,class:"visual-search-toolbar"}).menuline({group:!0,flex:1,min_width:0}).div({class:"visual-search-field"});i.span({class:"visual-search-icon",aria_hidden:"true"}),i.input({type:"search",value:`^.${t}`,default:"",live:!0,placeholder:r,aria_label:r}),i.html_button({type:"button",class:"visual-search-clear",aria_label:`Clear ${r.toLowerCase()}`,hidden:`^.${t}:={} === ''`,connect_onclick:`this.SET('.${t}', '')`})}};var sl=class extends vo{constructor({catalogue:e=null}={}){super({maxBytes:5*1024*1024}),Eo(e),this.catalogue=e,this.decoder=new TextDecoder("utf-8",{fatal:!0}),this.parts=[],this.outcome={state:"pending"}}write(e){this.parts.push(this.decoder.decode(e,{stream:!0}))}finish(){this.parts.push(this.decoder.decode());let e=this.parts.join("");this.parts=[];let t=j(e);if(!(t instanceof I)||t.length!==1||t.getNodes()[0].label!=="pageRoot")throw new TypeError("Expected one pageRoot Source");return Dt(this.catalogue,t),this.outcome={state:"completed",result:e},this.outcome}abort(){return this.outcome.state!=="completed"&&(this.parts=[],this.outcome={state:"unsaved"}),this.outcome}status(){return this.outcome}};function V2(n,e){this.v=n,this.k=e}function Em(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,r=Array(e);t<e;t++)r[t]=n[t];return r}function z2(n){if(Array.isArray(n))return n}function H2(n,e){var t=n==null?null:typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(t!=null){var r,o,i,a,s=[],l=!0,u=!1;try{if(i=(t=t.call(n)).next,e===0){if(Object(t)!==t)return;l=!1}else for(;!(l=(r=i.call(t)).done)&&(s.push(r.value),s.length!==e);l=!0);}catch(c){u=!0,o=c}finally{try{if(!l&&t.return!=null&&(a=t.return(),Object(a)!==a))return}finally{if(u)throw o}}return s}}function G2(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
237
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function W2(n,e){return z2(n)||H2(n,e)||Y2(n,e)||G2()}function Y2(n,e){if(n){if(typeof n=="string")return Em(n,e);var t={}.toString.call(n).slice(8,-1);return t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set"?Array.from(n):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Em(n,e):void 0}}function ll(n){var e,t;function r(i,a){try{var s=n[i](a),l=s.value,u=l instanceof V2;Promise.resolve(u?l.v:l).then(function(c){if(u){var d=i==="return"&&l.k?i:"next";if(!l.k||c.done)return r(d,c);c=n[d](c).value}o(!!s.done,c)},function(c){r("throw",c)})}catch(c){o(2,c)}}function o(i,a){i===2?e.reject(a):e.resolve({value:a,done:i}),(e=e.next)?r(e.key,e.arg):t=null}this._invoke=function(i,a){return new Promise(function(s,l){var u={key:i,arg:a,resolve:s,reject:l,next:null};t?t=t.next=u:(e=t=u,r(i,a))})},typeof n.return!="function"&&(this.return=void 0)}ll.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},ll.prototype.next=function(n){return this._invoke("next",n)},ll.prototype.throw=function(n){return this._invoke("throw",n)},ll.prototype.return=function(n){return this._invoke("return",n)};var Pm=Object.entries,xm=Object.setPrototypeOf,X2=Object.isFrozen,Lm=Object.getPrototypeOf,Fm=Object.getOwnPropertyDescriptor,Re=Object.freeze,Ue=Object.seal,ko=Object.create,jm=typeof Reflect<"u"&&Reflect,Nc=jm.apply,Ic=jm.construct;Re||(Re=function(e){return e});Ue||(Ue=function(e){return e});Nc||(Nc=function(e,t){for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];return e.apply(t,o)});Ic||(Ic=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];return new e(...r)});var tr=_e(Array.prototype.forEach);Array.prototype.indexOf;var Z2=_e(Array.prototype.lastIndexOf),km=_e(Array.prototype.pop),Xi=_e(Array.prototype.push),K2=_e(Array.prototype.slice),J2=_e(Array.prototype.splice),To=Array.isArray,vc=qm(Set),Ec=_e(Set.prototype.add),Zi=_e(Set.prototype.has),_n=_e(String.prototype.toLowerCase),xc=_e(String.prototype.toString),Tm=_e(String.prototype.match),Ki=_e(String.prototype.replace),Am=_e(String.prototype.indexOf),Q2=_e(String.prototype.trim),e0=_e(Number.prototype.toString),t0=_e(Boolean.prototype.toString),Dm=typeof BigInt>"u"?null:_e(BigInt.prototype.toString),Sm=typeof Symbol>"u"?null:_e(Symbol.prototype.toString),st=_e(Object.prototype.hasOwnProperty),Ji=_e(Object.prototype.toString),qe=_e(RegExp.prototype.test),rr=qm(TypeError);function _e(n){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,r=new Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];return Nc(n,e,r)}}function qm(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return Ic(n,t)}}function ie(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:_n;if(xm&&xm(n,null),!To(e))return n;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let i=t(o);i!==o&&(X2(e)||(e[r]=i),o=i)}n[o]=!0}return n}function r0(n){for(let e=0;e<n.length;e++)st(n,e)||(n[e]=null);return n}function ct(n){let e=ko(null);for(let r of Pm(n)){var t=W2(r,2);let o=t[0],i=t[1];st(n,o)&&(To(i)?e[o]=r0(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=ct(i):e[o]=i)}return e}function n0(n){switch(typeof n){case"string":return n;case"number":return e0(n);case"boolean":return t0(n);case"bigint":return Dm?Dm(n):"0";case"symbol":return Sm?Sm(n):"Symbol()";case"undefined":return Ji(n);case"function":case"object":{if(n===null)return Ji(n);let e=n,t=bt(e,"toString");if(typeof t=="function"){let r=t(e);return typeof r=="string"?r:Ji(r)}return Ji(n)}default:return Ji(n)}}function bt(n,e){for(;n!==null;){let r=Fm(n,e);if(r){if(r.get)return _e(r.get);if(typeof r.value=="function")return _e(r.value)}n=Lm(n)}function t(){return null}return t}function o0(n,e){for(;n!==null;){let t=Fm(n,e);if(t)return t.get?_e(t.get):null;n=Lm(n)}return null}function i0(n){try{return qe(n,""),!0}catch{return!1}}var Cm=Re(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),kc=Re(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Tc=Re(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),a0=Re(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ac=Re(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),s0=Re(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Nm=Re(["#text"]),Im=Re(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Dc=Re(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Om=Re(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),ul=Re(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),l0=Ue(/{{[\w\W]*|^[\w\W]*}}/g),u0=Ue(/<%[\w\W]*|^[\w\W]*%>/g),c0=Ue(/\${[\w\W]*/g),d0=Ue(/^data-[\-\w.\u00B7-\uFFFF]+$/),f0=Ue(/^aria-[\-\w]+$/),Rm=Ue(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),h0=Ue(/^(?:\w+script|data):/i),p0=Ue(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),m0=Ue(/^html$/i),g0=Ue(/^[a-z][.\w]*(-[.\w]+)+$/i),Sc=Ue(/<[/\w!]/g),Bm=Ue(/<[/\w]/g),b0=Ue(/<\/no(script|embed|frames)/i),$m=Ue(/\/>/i),De={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},w0=Re(ie({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),_0=function(){return typeof window>"u"?null:window},y0=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(r=t.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Mm=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},$r=function(e,t,r,o){return st(e,t)&&To(e[t])?ie(o.base?ct(o.base):{},e[t],o.transform):r},Cc=function(e,t,r){let o=st(e,t)?e[t]:void 0;return o&&typeof o=="object"?ct(o):r()};function Um(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_0(),e=N=>Um(N);if(e.version="3.4.17",e.removed=[],!n||!n.document||n.document.nodeType!==De.document||!n.Element)return e.isSupported=!1,e;let t=n.document,r=t,o=r.currentScript;n.DocumentFragment;let i=n.HTMLTemplateElement,a=n.Node,s=n.Element,l=n.NodeFilter;n.NamedNodeMap===void 0&&(n.NamedNodeMap||n.MozNamedAttrMap),n.HTMLFormElement;let u=n.DOMParser,c=n.trustedTypes,d=s.prototype,f=bt(d,"cloneNode"),h=bt(d,"remove"),p=bt(d,"removeAttributeNode"),m=bt(d,"nextSibling"),b=bt(d,"childNodes"),w=bt(d,"parentNode"),_=bt(d,"shadowRoot"),y=bt(d,"attributes"),x=a&&a.prototype?bt(a.prototype,"nodeType"):null,D=a&&a.prototype?bt(a.prototype,"nodeName"):null,k=a&&a.prototype?bt(a.prototype,"ownerDocument"):null,C=function(g){return x?x(g):g.nodeType},O=function(g){return D?D(g):g.nodeName},$=o0(d,"namespaceURI"),F=function(g){return $?$(g):g.namespaceURI};if(typeof i=="function"){let N=t.createElement("template");N.content&&N.content.ownerDocument&&(t=N.content.ownerDocument)}let H,Q="",me,re=!1,ue=0,U=function(){if(ue>0)throw rr('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},dt=function(g){U(),ue++;try{return H.createHTML(g)}finally{ue--}},yn=function(g){U(),ue++;try{return H.createScriptURL(g)}finally{ue--}},vn=function(){return re||(me=y0(c,o),re=!0),me},wt=t,Z=wt.implementation,Be=wt.createNodeIterator,zt=wt.createDocumentFragment,En=wt.getElementsByTagName,tg=r.importNode,ge=Mm();e.isSupported=typeof Pm=="function"&&typeof w=="function"&&Z&&Z.createHTMLDocument!==void 0;let rg=l0,ng=u0,og=c0,ig=d0,ag=f0,sg=h0,nd=p0,lg=g0,od=Rm,be=null,yl=ie({},[...Cm,...kc,...Tc,...Ac,...Nm]),we=null,vl=ie({},[...Im,...Dc,...Om,...ul]),St=Object.seal(ko(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Do=null,id=null,ir=Object.seal(ko(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ad=!0,El=!0,sd=!1,xl=!0,Ht=!1,Mr=!0,Pr=!1,kl=!1,na=null,oa=null,Tl=!1,xn=!1,ia=!1,aa=!1,ld=!0,ud=!1,cd="user-content-",Al=!0,Dl=!1,Lr=null,kn={},Fr=null,dd=ie({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),fd=null,hd=ie({},["audio","video","img","source","image","track"]),pd=null,md=ie({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),sa="http://www.w3.org/1998/Math/MathML",la="http://www.w3.org/2000/svg",Ct="http://www.w3.org/1999/xhtml",Tn=Ct,Sl=!1,Cl=null,ug=ie({},[sa,la,Ct],xc),gd=Re(["mi","mo","mn","ms","mtext"]),Nl=ie({},gd),bd=Re(["annotation-xml"]),Il=ie({},bd),cg=ie({},["title","style","font","a","script"]),So=null,dg=["application/xhtml+xml","text/html"],fg="text/html",ke=null,An=null,hg=t.createElement("form"),wd=function(g){return g instanceof RegExp||g instanceof Function},Ol=function(){let g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(An&&An===g)return;(!g||typeof g!="object")&&(g={}),g=ct(g),So=dg.indexOf(g.PARSER_MEDIA_TYPE)===-1?fg:g.PARSER_MEDIA_TYPE,ke=So==="application/xhtml+xml"?xc:_n,be=$r(g,"ALLOWED_TAGS",yl,{transform:ke}),we=$r(g,"ALLOWED_ATTR",vl,{transform:ke}),Cl=$r(g,"ALLOWED_NAMESPACES",ug,{transform:xc}),pd=$r(g,"ADD_URI_SAFE_ATTR",md,{transform:ke,base:md}),fd=$r(g,"ADD_DATA_URI_TAGS",hd,{transform:ke,base:hd}),Fr=$r(g,"FORBID_CONTENTS",dd,{transform:ke}),Do=$r(g,"FORBID_TAGS",ct({}),{transform:ke}),id=$r(g,"FORBID_ATTR",ct({}),{transform:ke}),kn=st(g,"USE_PROFILES")?g.USE_PROFILES&&typeof g.USE_PROFILES=="object"?ct(g.USE_PROFILES):g.USE_PROFILES:!1,ad=g.ALLOW_ARIA_ATTR!==!1,El=g.ALLOW_DATA_ATTR!==!1,sd=g.ALLOW_UNKNOWN_PROTOCOLS||!1,xl=g.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ht=g.SAFE_FOR_TEMPLATES||!1,Mr=g.SAFE_FOR_XML!==!1,Pr=g.WHOLE_DOCUMENT||!1,xn=g.RETURN_DOM||!1,ia=g.RETURN_DOM_FRAGMENT||!1,aa=g.RETURN_TRUSTED_TYPE||!1,Tl=g.FORCE_BODY||!1,ld=g.SANITIZE_DOM!==!1,ud=g.SANITIZE_NAMED_PROPS||!1,Al=g.KEEP_CONTENT!==!1,Dl=g.IN_PLACE||!1,od=i0(g.ALLOWED_URI_REGEXP)?g.ALLOWED_URI_REGEXP:Rm,Tn=typeof g.NAMESPACE=="string"?g.NAMESPACE:Ct,Nl=Cc(g,"MATHML_TEXT_INTEGRATION_POINTS",()=>ie({},gd)),Il=Cc(g,"HTML_INTEGRATION_POINTS",()=>ie({},bd));let v=Cc(g,"CUSTOM_ELEMENT_HANDLING",()=>ko(null));if(St=ko(null),st(v,"tagNameCheck")&&wd(v.tagNameCheck)&&(St.tagNameCheck=v.tagNameCheck),st(v,"attributeNameCheck")&&wd(v.attributeNameCheck)&&(St.attributeNameCheck=v.attributeNameCheck),st(v,"allowCustomizedBuiltInElements")&&typeof v.allowCustomizedBuiltInElements=="boolean"&&(St.allowCustomizedBuiltInElements=v.allowCustomizedBuiltInElements),Ue(St),Ht&&(El=!1),ia&&(xn=!0),kn&&(be=ie({},Nm),we=ko(null),kn.html===!0&&(ie(be,Cm),ie(we,Im)),kn.svg===!0&&(ie(be,kc),ie(we,Dc),ie(we,ul)),kn.svgFilters===!0&&(ie(be,Tc),ie(we,Dc),ie(we,ul)),kn.mathMl===!0&&(ie(be,Ac),ie(we,Om),ie(we,ul))),ir.tagCheck=null,ir.attributeCheck=null,st(g,"ADD_TAGS")&&(typeof g.ADD_TAGS=="function"?ir.tagCheck=g.ADD_TAGS:To(g.ADD_TAGS)&&(be===yl&&(be=ct(be)),ie(be,g.ADD_TAGS,ke))),st(g,"ADD_ATTR")&&(typeof g.ADD_ATTR=="function"?ir.attributeCheck=g.ADD_ATTR:To(g.ADD_ATTR)&&(we===vl&&(we=ct(we)),ie(we,g.ADD_ATTR,ke))),st(g,"ADD_FORBID_CONTENTS")&&To(g.ADD_FORBID_CONTENTS)&&(Fr===dd&&(Fr=ct(Fr)),ie(Fr,g.ADD_FORBID_CONTENTS,ke)),Al&&(be["#text"]=!0),Pr&&ie(be,["html","head","body"]),be.table&&(ie(be,["tbody"]),delete Do.tbody),g.TRUSTED_TYPES_POLICY){if(typeof g.TRUSTED_TYPES_POLICY.createHTML!="function")throw rr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof g.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw rr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let T=H;H=g.TRUSTED_TYPES_POLICY;try{Q=dt("")}catch(A){throw H=T,A}}else g.TRUSTED_TYPES_POLICY===null?(H=void 0,Q=""):(H===void 0&&(H=vn()),H&&typeof Q=="string"&&(Q=dt("")));Re&&Re(g),An=g},_d=ie({},[...kc,...Tc,...a0]),yd=ie({},[...Ac,...s0]),pg=function(g,v,T){return v.namespaceURI===Ct?g==="svg":v.namespaceURI===sa?g==="svg"&&(T==="annotation-xml"||Nl[T]):!!_d[g]},mg=function(g,v,T){return v.namespaceURI===Ct?g==="math":v.namespaceURI===la?g==="math"&&Il[T]:!!yd[g]},gg=function(g,v,T){return v.namespaceURI===la&&!Il[T]||v.namespaceURI===sa&&!Nl[T]?!1:!yd[g]&&(cg[g]||!_d[g])},bg=function(g){let v=F(g),T=_n(O(g)),A=w(g),M,V;return A&&C(A)===De.element?(M={namespaceURI:F(A)},V=_n(O(A))):(M={namespaceURI:Tn},V="template"),Cl[v]?v===la?pg(T,M,V):v===sa?mg(T,M,V):v===Ct?gg(T,M,V):!!(So==="application/xhtml+xml"&&Cl[v]):!1},ar=function(g){Xi(e.removed,{element:g});try{w(g).removeChild(g)}catch{if(h(g),!w(g))throw rr("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},vd=function(g,v,T){try{p(g,v)}catch{try{g.removeAttribute(T)}catch{}}},Rl=function(g){$l(g);let v=b(g);v&&tr(K2(v),A=>{try{h(A)}catch{}});let T=C(g)===De.element?y(g):null;if(T)for(let A=T.length-1;A>=0;--A){let M=T[A],V=M&&M.name;typeof V=="string"&&vd(g,M,V)}},Dn=function(g,v,T){if(!T)try{T=v.getAttributeNode(g)}catch{T=null}Xi(e.removed,{attribute:T||null,from:v});try{T?p(v,T):v.removeAttribute(g)}catch{try{v.removeAttribute(g)}catch{}}if(g==="is")if(xn||ia)try{ar(v)}catch{}else try{v.setAttribute(g,"")}catch{}},Ed=function(g){let v=y(g);if(v)for(let T=v.length-1;T>=0;--T){let A=v[T],M=A&&A.name;typeof M!="string"||we[ke(M)]||vd(g,A,M)}},Bl=function(g,v){let T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,A=[g];for(;A.length>0;){let M=A.pop();if(v(M)===!1)continue;if(T&&C(M)===De.element){let K=_(M);sr(K)&&A.push(K)}let V=b(M);if(V)for(let K=V.length-1;K>=0;--K)A.push(V[K])}},$l=function(g){Bl(g,v=>{C(v)===De.element&&Ed(v)})},Ml=function(g){let v=[];return Bl(g,T=>{v.push(T)},!0),v},wg=function(g,v){let T=vc();tr(Ml(g),A=>{C(A)===De.element&&Ec(T,A)}),tr(v,A=>{C(A)===De.element&&!Zi(T,A)&&Ed(A)})},xd=function(g,v){let T=!1;return tr(e.removed,A=>{A.element&&(T=T||A.element===g,$l(A.element))}),wg(g,v),T},_g=8,yg=function(g,v){let T=Lr,A=null,M=()=>(A||(A=vc(),tr(v,V=>{Ec(A,V)})),A);for(let V=0;;V++){let K=Ml(g),Se=[g],Nt=!1;if(tr(K,We=>{C(We)===De.documentFragment?Xi(Se,We):!Nt&&!Zi(T,We)&&(Nt=Zi(M(),We))}),!Nt)return;if(V>=_g)throw rr("the tree kept changing during in-place sanitization; refusing to return it");tr(Se,(We,et)=>{vg(We,et>0,g,M())})}},vg=function(g,v,T,A){let M=Pl(g),V;for(;V=M.nextNode();)!Zi(A,V)||Zi(Lr,V)||(v&&_t(ge.uponSanitizeShadowNode,V,null),Fl(V,T),jl(V,T),sr(V.content)&&No(V.content))},Eg=function(g){Lr&&Ec(Lr,g)},kd=function(g,v){return Mr?g==="patchsrc"?!0:g==="for"&&v!=="label"&&v!=="output":!1},xg=function(g){Mr&&Bl(g,v=>{let T=C(v);if(T===De.processingInstruction||T===De.comment&&qe(Bm,v.data)){try{h(v)}catch{}return!1}if(T===De.element){let A=v,M=ke(O(v));try{A.hasAttribute&&A.hasAttribute("patchsrc")&&A.removeAttribute("patchsrc"),A.hasAttribute&&A.hasAttribute("for")&&kd("for",M)&&A.removeAttribute("for")}catch{}}return!0})},Td=function(g){let v=null,T=null;if(Tl)g="<remove></remove>"+g;else{let V=Tm(g,/^[\r\n\t ]+/);T=V&&V[0]}So==="application/xhtml+xml"&&Tn===Ct&&(g='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+g+"</body></html>");let A=H?dt(g):g;if(Tn===Ct)try{v=new u().parseFromString(A,So)}catch{}if(!v||!v.documentElement){v=Z.createDocument(Tn,"template",null);try{v.documentElement.innerHTML=Sl?Q:A}catch{}}let M=v.body||v.documentElement;return g&&T&&M.insertBefore(t.createTextNode(T),M.childNodes[0]||null),Tn===Ct?En.call(v,Pr?"html":"body")[0]:Pr?v.documentElement:M},Pl=function(g){let v=k?k(g):g.ownerDocument;return Be.call(v||g,g,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},ua=function(g){return g=Ki(g,rg," "),g=Ki(g,ng," "),g=Ki(g,og," "),g},Ll=function(g){var v;Ad(g);let T=(v=g.querySelectorAll)===null||v===void 0?void 0:v.call(g,"template");T&&tr(T,A=>{sr(A.content)&&Ll(A.content)})},Ad=function(g){g.normalize();let v=k?k(g):g.ownerDocument,T=Be.call(v||g,g,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),A=T.nextNode();for(;A;)A.data=ua(A.data),A=T.nextNode()},ca=function(g){let v=D?D(g):null;return typeof v!="string"||ke(v)!=="form"?!1:typeof g.nodeName!="string"||typeof g.textContent!="string"||typeof g.removeChild!="function"||g.attributes!==y(g)||typeof g.removeAttribute!="function"||typeof g.removeAttributeNode!="function"||typeof g.getAttributeNode!="function"||typeof g.setAttribute!="function"||typeof g.namespaceURI!="string"||typeof g.insertBefore!="function"||typeof g.hasChildNodes!="function"||g.nodeType!==x(g)||g.childNodes!==b(g)},sr=function(g){if(!x||typeof g!="object"||g===null)return!1;try{return x(g)===De.documentFragment}catch{return!1}},Co=function(g){if(!x||typeof g!="object"||g===null)return!1;try{return typeof x(g)=="number"}catch{return!1}};function _t(N,g,v){N.length!==0&&tr(N,T=>{T.call(e,g,v,An)})}let kg=function(g,v){return!!(Mr&&g.hasChildNodes()&&!Co(g.firstElementChild)&&qe(Sc,g.textContent)&&qe(Sc,g.innerHTML)||Mr&&w0[v]&&C(g)===De.element&&F(g)===Ct&&(Co(g.firstElementChild)||typeof g.textContent=="string"&&qe(Sc,g.textContent))||g.nodeType===De.processingInstruction||Mr&&g.nodeType===De.comment&&qe(Bm,g.data))},da=function(g,v){if(g instanceof RegExp)return qe(g,v);if(g instanceof Function){for(var T=arguments.length,A=new Array(T>2?T-2:0),M=2;M<T;M++)A[M-2]=arguments[M];return!!g(v,...A)}return!1},Tg=function(g,v,T){if(!Do[v]&&Cd(v)&&da(St.tagNameCheck,v))return!1;if(Al&&!Fr[v]&&!Fr[_n(v)]){let A=w(g),M=b(g);if(M&&A){let V=M.length;for(let K=V-1;K>=0;--K){let Se=g===T?f(M[K],!0):M[K];A.insertBefore(Se,m(g))}}}return ar(g),!0},Dd=function(g,v,T,A){return g.length===0?v:v===T||v===A?ct(v):v},Sn=function(g,v){return g===v||w(g)!==null?!1:(Dl&&$l(g),!0)},Fl=function(g,v){if(Eg(g),_t(ge.beforeSanitizeElements,g,null),Sn(g,v))return!0;if(ca(g))return ar(g),!0;let T=ke(O(g));if(be=Dd(ge.uponSanitizeElement,be,yl,na),_t(ge.uponSanitizeElement,g,{tagName:T,allowedTags:be}),Sn(g,v))return!0;if(kg(g,T))return ar(g),!0;if(Do[T]||!(ir.tagCheck instanceof Function&&ir.tagCheck(T))&&!be[T]){let A=Tg(g,T,v);return A===!1&&(_t(ge.afterSanitizeElements,g,null),Sn(g,v))?!0:A}if(C(g)===De.element&&!bg(g)||(T==="noscript"||T==="noembed"||T==="noframes")&&qe(b0,g.innerHTML))return ar(g),!0;if(Ht&&g.nodeType===De.text){let A=ua(g.textContent);g.textContent!==A&&(Xi(e.removed,{element:g.cloneNode()}),g.textContent=A)}return _t(ge.afterSanitizeElements,g,null),Sn(g,v)},Sd=function(g,v,T){if(id[v]||kd(v,g)||ld&&(v==="id"||v==="name")&&(T in t||T in hg))return!1;let A=we[v]||ir.attributeCheck instanceof Function&&ir.attributeCheck(v,g);return El&&qe(ig,v)||ad&&qe(ag,v)?!0:A?pd[v]||qe(od,Ki(T,nd,""))||(v==="src"||v==="xlink:href"||v==="href")&&g!=="script"&&Am(T,"data:")===0&&fd[g]||sd&&!qe(sg,Ki(T,nd,""))?!0:!T:Cd(g)&&da(St.tagNameCheck,g)&&da(St.attributeNameCheck,v,g)||v==="is"&&St.allowCustomizedBuiltInElements&&da(St.tagNameCheck,T)},Ag=ie({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Cd=function(g){return!Ag[_n(g)]&&qe(lg,g)},Dg=function(g,v,T,A){if(H&&typeof c=="object"&&typeof c.getAttributeType=="function"&&!T)switch(c.getAttributeType(g,v)){case"TrustedHTML":return dt(A);case"TrustedScriptURL":return yn(A)}return A},Sg=function(g,v,T,A){try{return T?g.setAttributeNS(T,v,A):g.setAttribute(v,A),ca(g)?(ar(g),!1):!0}catch{return Dn(v,g),!1}},Nd=function(g,v){return Mr&&qe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,v)?!0:_n(g)==="attributename"&&Tm(v,"href")!==null},jl=function(g,v){if(_t(ge.beforeSanitizeAttributes,g,null),Sn(g,v))return;let T=g.attributes;if(!T||ca(g))return;we=Dd(ge.uponSanitizeAttribute,we,vl,oa);let A={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:we,forceKeepAttr:void 0},M=T.length,V=ke(g.nodeName);for(;M--;){let K=T[M],Se=K.name,Nt=K.namespaceURI,We=K.value,et=ke(Se),Cn=We,tt=Se==="value"?Cn:Q2(Cn),Id=!1;if(A.attrName=et,A.attrValue=tt,A.keepAttr=!0,A.forceKeepAttr=void 0,_t(ge.uponSanitizeAttribute,g,A),tt=A.attrValue,ud&&(et==="id"||et==="name")&&Am(tt,cd)!==0&&(Dn(Se,g,K),tt=cd+tt,Id=!0),Nd(Se,tt)){Dn(Se,g,K);continue}if(!A.forceKeepAttr){if(!A.keepAttr){Dn(Se,g,K);continue}if(!xl&&qe($m,tt)){Dn(Se,g,K);continue}if(Ht&&(tt=ua(tt)),!Sd(V,et,tt)){Dn(Se,g,K);continue}tt=Dg(V,et,Nt,tt),tt!==Cn&&Sg(g,Se,Nt,tt)&&Id&&km(e.removed)}}_t(ge.afterSanitizeAttributes,g,null),Sn(g,v)},No=function(g){let v=null,T=Pl(g);for(_t(ge.beforeSanitizeShadowDOM,g,null);v=T.nextNode();)if(_t(ge.uponSanitizeShadowNode,v,null),Fl(v,g),jl(v,g),sr(v.content)&&No(v.content),C(v)===De.element){let A=_(v);sr(A)&&(ql(A),No(A))}Ht&&Ad(g),_t(ge.afterSanitizeShadowDOM,g,null)},ql=function(g){let v=[{node:g,shadow:null}];for(;v.length>0;){let T=v.pop();if(T.shadow){No(T.shadow);continue}let A=T.node,M=C(A)===De.element,V=b(A);if(V)for(let K=V.length-1;K>=0;--K)v.push({node:V[K],shadow:null});if(M){let K=D?D(A):null;if(typeof K=="string"&&ke(K)==="template"){let Se=A.content;sr(Se)&&v.push({node:Se,shadow:null})}}if(M){let K=_(A);sr(K)&&v.push({node:null,shadow:K},{node:K,shadow:null})}}};return e.sanitize=function(N){let g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},v=null,T=null,A=null,M=null;if(Sl=!N,Sl&&(N="<!-->"),typeof N!="string"&&!Co(N)&&(N=n0(N),typeof N!="string"))throw rr("dirty is not a string, aborting");if(!e.isSupported)return N;kl?(be=na,we=oa):Ol(g),(ge.uponSanitizeElement.length>0||ge.uponSanitizeAttribute.length>0)&&(be=ct(be)),ge.uponSanitizeAttribute.length>0&&(we=ct(we)),e.removed=[];let V=Dl&&typeof N!="string"&&Co(N),K=[],Se=Lr;if(V){xg(N);let et=O(N);if(typeof et=="string"){let Cn=ke(et);if(!be[Cn]||Do[Cn])throw Rl(N),rr("root node is forbidden and cannot be sanitized in-place")}if(ca(N))throw Rl(N),rr("root node is clobbered and cannot be sanitized in-place");K=Ml(N),Lr=vc()}else if(Co(N))v=Td("<!---->"),T=v.ownerDocument.importNode(N,!0),T.nodeType===De.element&&T.nodeName==="BODY"||T.nodeName==="HTML"?v=T:v.appendChild(T),ql(v);else{if(!xn&&!Ht&&!Pr&&N.indexOf("<")===-1)return H&&aa?dt(N):N;if(v=Td(N),!v)return xn?null:aa?Q:""}v&&Tl&&ar(v.firstChild);let Nt=V?N:v;try{V&&ql(N);let et=Pl(Nt);for(;A=et.nextNode();)Fl(A,Nt),jl(A,Nt),sr(A.content)&&No(A.content);V&&yg(N,K)}catch(et){throw V&&(Rl(N),xd(N,K)),et}finally{Lr=Se}if(V){if(xd(N,K))throw rr("a node selected for removal could not be safely returned; refusing to sanitize in place");return Ht&&Ll(N),N}if(xn){if(Ht&&Ll(v),ia)for(M=zt.call(v.ownerDocument);v.firstChild;)M.appendChild(v.firstChild);else M=v;return(we.shadowroot||we.shadowrootmode)&&(M=tg.call(r,M,!0)),M}let We=Pr?v.outerHTML:v.innerHTML;return Pr&&be["!doctype"]&&v.ownerDocument&&v.ownerDocument.doctype&&v.ownerDocument.doctype.name&&qe(m0,v.ownerDocument.doctype.name)&&(We="<!DOCTYPE "+v.ownerDocument.doctype.name+`>
|
|
238
|
+
`+We),Ht&&(We=ua(We)),H&&aa?dt(We):We},e.setConfig=function(){let N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ol(N),kl=!0,na=be,oa=we},e.clearConfig=function(){An=null,kl=!1,na=null,oa=null,H=me,Q=""},e.isValidAttribute=function(N,g,v){An||Ol({});let T=ke(N),A=ke(g);return typeof v=="string"&&(Nd(g,v)||!xl&&qe($m,v))?!1:Sd(T,A,v)},e.addHook=function(N,g){typeof g=="function"&&st(ge,N)&&Xi(ge[N],g)},e.removeHook=function(N,g){if(st(ge,N)){if(g!==void 0){let v=Z2(ge[N],g);return v===-1?void 0:J2(ge[N],v,1)[0]}return km(ge[N])}},e.removeHooks=function(N){st(ge,N)&&(ge[N]=[])},e.removeAllHooks=function(){ge=Mm()},e}var v0=Um();function E0(){return import("@gramlot/gramlot/markdown")}var Oc=class n extends At{static internalParams=new Set([...At.internalParams,"gramlot","method","params","onError"]);#e=!1;#t=null;constructor({gramlot:e,method:t,directory:r,onError:o}){super({cacheTime:-1,onError:o}),this.gramlot=e,this.method=t,this.params={directory:r},this.children=new Set}get closed(){return this.#e}startLoad(e){if(this.loading)return this.loading;let t=new AbortController;return this.#t=t,e({controller:t,method:this.method,params:this.params,ignored:!1})}async loadAsync({controller:e,method:t,params:r}){let{signal:o}=e,i,a=new Promise((s,l)=>{i=()=>l(o.reason),o.addEventListener("abort",i,{once:!0})});try{let s=await Promise.race([this.gramlot.rpc.call("data",t,r,{signal:o}),a]);if(o.aborted)throw o.reason;return s}finally{o.removeEventListener("abort",i),this.#t===e&&(this.#t=null)}}prepareValue(e){if(!(e instanceof E))throw new TypeError("Directory navigation must return a Bag");for(let t of this.children)t.abort();this.children.clear();for(let t of e.getNodes())if(t.attr.directory!==void 0){let r=new n({gramlot:this.gramlot,method:this.method,directory:t.attr.directory,onError:this.onError});this.children.add(r),e.setResolver(t.label,r)}return e}abort(){this.#e=!0,this.#t?.abort();for(let e of this.children)e.abort();this.children.clear()}};function Rc(n){return class extends n{setLabelbox(e){let{box:t,labelBox:r,fieldLabel:o}=e;Object.assign(this,{box:t,labelBox:r,fieldLabel:o}),o.addEventListener("click",()=>{this.control.focus(),this.control.localName==="input"&&["checkbox","radio"].includes(this.control.type)&&this.control.click()})}projectAttributes(e,t){let r=super.projectAttributes(e,t),{lbl:o,lbl_value:i,lbl_values:a}=this.parameters,s=a==null?o??"":ss(oo(a),i,o);return s?this.control.setAttribute("aria-label",s):this.control.removeAttribute("aria-label"),r}}}Rc.labelbox=!0;Rc.parameters={lbl:{dtype:"T",qualification:"intl_str",nullable:!0,binding:"read"},lbl_value:{dtype:"T",nullable:!0,binding:"twoWay"},lbl_values:{dtype:"T",nullable:!0,binding:"read"},lbl_position:{dtype:"T",default:"TL",binding:"read",enum:Xu}};var Mc=["select","notnull","empty","case","len","min","max","email","regex","call","remote"],x0=["nodup","exist","gridnodup"],cl=n=>n==null||n==="",Bc=(n,e)=>n instanceof Promise?n.then(e):e(n);function Pc(n,e,t={}){let r={value:n,modified:!1,error:null,warnings:[],issues:[],datachanges:[]},o=Object.fromEntries(Object.entries(e).map(([u,c])=>[u.slice(9),c])),i=u=>Object.hasOwn(e,`validate_${u}`)&&e[`validate_${u}`]!=null;for(let u of x0)if(i(u))throw new Error(`validate_${u} requires the DB/grid integration.`);let a=(u,c,d=!1)=>t.invoke(u,e[u],{...o,value:c,result:r,validations:o,userChange:!0,signal:t.signal},d),s=(u,c)=>{if(c==null||c===!0)return;if(typeof c!="boolean"&&typeof c!="string"&&(typeof c!="object"||Array.isArray(c)))throw new TypeError("A validator returns true, false, null, an error code, or a result object/Bag.");let d=`validate_${u}`,f=c instanceof E?Object.fromEntries(c.getNodes().map(w=>[w.label,w.value])):typeof c=="object"?c:{errorcode:c===!1?"error":c};if(Object.hasOwn(f,"value")&&(r.modified||=!Object.is(r.value,f.value),r.value=f.value),f.data!=null&&(t.checkDataPatch(f.data),r.datachanges.push(f.data)),!f.errorcode)return;let h=e[`${d}_iswarning`]??f.iswarning??!!(e[`${d}_warning`]&&!e[`${d}_error`]),p=e[`${d}_${f.errorcode}`]||e[`${d}_${h?"warning":"error"}`]||f.message||e[`${d}_${h?"error":"warning"}`]||String(f.errorcode),m=Xr(p,w=>w?{...o,...f,value:r.value}[w]:r.value);if(m==null)throw new Error("A validation message references a missing value.");let b={rule:u,code:f.errorcode,severity:h?"warning":"error",message:m};r.issues.push(b),h?r.warnings.push(m):(r.error=m,r.required=!!f.required)},l=u=>{if(t.signal?.aborted)throw t.signal.reason;if(r.error||u===Mc.length)return r;let c=Mc[u],d=`validate_${c}`,f=e[d];if(!i(c)||f===!1&&c!=="empty")return l(u+1);let h=m=>{if(!m)return l(u+1);let b;return c==="remote"&&r.value==null?l(u+1):(c==="call"?b=a(d,r.value):c==="remote"?b=t.remote(f,{...k0(e),value:r.value},t.signal):b=T0(c,f,r.value,t),Bc(b,w=>{if(t.signal?.aborted)throw t.signal.reason;let _=()=>(s(c,w),l(u+1));return c==="remote"&&e.validate__onResult?Bc(t.invoke("validate__onResult",e.validate__onResult,{result:w,value:r.value,validations:o,signal:t.signal}),_):_()}))},p=e[`${d}_if`];return Bc(p==null?!0:typeof p=="boolean"?p:a(`${d}_if`,r.value,!0),h)};return l(0)}function k0(n){let e=new Set(["if","error","warning","iswarning"]);return Object.fromEntries(Object.entries(n).filter(([t])=>t.startsWith("validate_remote_")&&!e.has(t.slice(16))).map(([t,r])=>[t.slice(16),r]))}function Qi(n,e,t={}){return{errorcode:n,message:e,...t}}function T0(n,e,t,r){if(n==="select")return r.selection(t,r.signal);if(n==="notnull")return cl(t)&&e?Qi("notnull","A value is required.",{required:!0}):null;if(n==="empty")return cl(t)?{value:e}:null;if(n==="len"){if(typeof e!="string"||!/^(?:\d+|\d+:\d*|:\d+)$/.test(e))throw new Error("Invalid validate_len: use a length or min:max.");let[o,i]=e.split(":"),a=Number(o||0),s=i===void 0?a:i===""?1/0:Number(i);if(a>s)throw new Error("Invalid validate_len: minimum exceeds maximum.");if(cl(t))return;if(typeof t!="string")throw new TypeError("validate_len requires a text value.");return t.length<a||t.length>s?Qi(a===s?"wrong length":t.length<a?"too short":"too long",a===s?`Enter exactly ${a} characters.`:s===1/0?`Enter at least ${a} characters.`:a===0?`Enter no more than ${s} characters.`:`Enter between ${a} and ${s} characters.`):void 0}if(!cl(t)){if(n==="case"){if(typeof t!="string")throw new TypeError("validate_case requires a text value.");switch(e){case"upper":case"u":return{value:t.toUpperCase()};case"lower":case"l":return{value:t.toLowerCase()};case"title":case"t":return{value:t.replace(/\p{L}[\p{L}\p{M}]*/gu,o=>o[0].toUpperCase()+o.slice(1).toLowerCase())};case"capitalize":case"c":return{value:t[0].toUpperCase()+t.slice(1).toLowerCase()};default:throw new Error("Invalid validate_case: use upper, lower, title or capitalize.")}}if(n==="min"||n==="max"){let o;if(r.isDecimal?.(t))o=t.comparedTo(e);else if(t instanceof Date&&e instanceof Date)o=t.getTime()-e.getTime();else if(typeof t=="number"&&Number.isFinite(t)&&typeof e=="number"&&Number.isFinite(e))o=t-e;else throw new TypeError(`validate_${n} requires matching numeric or date/time values.`);return(n==="min"?o<0:o>0)?Qi(n,`Value must be ${n==="min"?"at least":"at most"} ${e}.`):void 0}if(n==="email"){if(typeof t!="string")throw new TypeError("validate_email requires a text value.");return/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(t)?null:Qi("email","Check email format.",{iswarning:!0})}if(n==="regex"){if(typeof t!="string"||typeof e!="string")throw new TypeError("validate_regex requires text.");let o=e.trim(),i=o.startsWith("!");return new RegExp(i?o.slice(1):o,"u").test(t)!==i?null:Qi("regex","The value does not match the required pattern.")}}}var ea={dtype:"T",nullable:!0,binding:"read"},dl={dtype:"B",nullable:!0,binding:"read"},$c={dtype:["T","L","N","R","B","D","H","DH","DHZ"],nullable:!0,binding:"read"},Vm={validate_select:dl,validate_notnull:{...dl,default:!1},validate_empty:$c,validate_case:{...ea,enum:["upper","lower","title","capitalize","u","l","t","c"]},validate_len:ea,validate_min:$c,validate_max:$c,validate_email:dl,validate_regex:ea,validate_call:{dtype:"T",nullable:!0},validate_remote:ea,validate_onAccept:{dtype:"T",nullable:!0},validate_onReject:{dtype:"T",nullable:!0},validate__onResult:{dtype:"T",nullable:!0},validate_timeout:{dtype:"L",nullable:!0,binding:"read"},...Object.fromEntries(Mc.flatMap(n=>[[`validate_${n}_if`,{dtype:["T","B"],nullable:!0}],[`validate_${n}_iswarning`,dl],...["error","warning"].map(e=>[`validate_${n}_${e}`,{...ea,qualification:"intl_str"}])]))};var A0=1800,zm=200;function Hm(n){return class extends n{get supportsFormValidation(){return!0}static validationParameters(e){let t={...Ju(this.gramlotComponent,e),...e};return this.constrained&&t.validate_select==null&&(t.validate_select=!0),t}static get validationExecutor(){return Pc}get validationExecutor(){return this.constructor.validationExecutor}connectedCallback(){super.connectedCallback(),this.pageContext?.form&&this.pageContext.formValidate()}#e=!1;#t;#r;#n;#o=new ho;#i;#a={};validationResult=null;constructor(){super(),this.message=this.ownerDocument.createElement("small"),this.message.id="field-message",this.message.hidden=!0,this.message.setAttribute("aria-live","polite"),this.message.setAttribute("popover","manual"),this.message.setAttribute("role","tooltip");let e=this.ownerDocument.createElement("style");e.textContent=`#control[aria-invalid="true"]{background:var(--gramlot-error-background,#fff1f0)}
|
|
239
239
|
input#control[aria-invalid="true"],textarea#control[aria-invalid="true"]{color:var(--gramlot-error,#8c1d18)}
|
|
240
240
|
#field-message{position:fixed;inset:auto;margin:0;padding:.4em .65em;border:1px solid var(--gramlot-error,#b3261e);border-radius:var(--gramlot-radius-sm,4px);
|
|
241
241
|
color:var(--gramlot-error,#8c1d18);background:var(--gramlot-error-background,#fff1f0);font:inherit;font-size:.85em;box-shadow:var(--gramlot-shadow,0 2px 8px #0003);
|
|
242
|
-
max-width:min(28em,var(--gramlot-popup-available-width,100vw));max-height:var(--gramlot-popup-available-height,100vh);overflow:auto;overflow-wrap:anywhere;opacity:1;transition:opacity ${
|
|
242
|
+
max-width:min(28em,var(--gramlot-popup-available-width,100vw));max-height:var(--gramlot-popup-available-height,100vh);overflow:auto;overflow-wrap:anywhere;opacity:1;transition:opacity ${zm}ms ease-out}
|
|
243
243
|
#field-message[data-severity="warning"]{color:var(--gramlot-warning,#805600);border-color:var(--gramlot-warning,#805600);background:var(--gramlot-warning-background,#fff8df)}
|
|
244
244
|
#field-message[data-fading]{opacity:0}
|
|
245
|
-
@media(prefers-reduced-motion:reduce){#field-message{transition:none}}`,this.shadowRoot.append(e),this.control.setAttribute("aria-describedby",this.message.id),this.controlBox.append(this.message),this.control.addEventListener("input",()=>this.cancelValidation()),this.control.addEventListener("compositionstart",()=>this.cancelValidation()),this.control.addEventListener("focusin",()=>this.#l()),this.control.addEventListener("mouseenter",()=>this.#l()),this.control.addEventListener("keydown",t=>{t.key==="Escape"&&(this.cancelValidation(),this.#s())})}#s(){this.ownerDocument.defaultView.clearTimeout(this.#r),this.#n?.abort(),this.#n=null,this.message.hidden||this.message.hidePopover(),this.message.hidden=!0,this.message.removeAttribute("data-fading")}#l(){if(!this.message.textContent||!this.isConnected)return;this.#s();let e=this.ownerDocument.defaultView;this.message.hidden=!1,this.message.showPopover(),ao(this.message,this.control),this.#r=e.setTimeout(()=>{this.message.hidden||(this.message.setAttribute("data-fading",""),this.#r=e.setTimeout(()=>this.#s(),
|
|
246
|
-
`),this.#l())}validateCandidate(e,t){if(this.pageContext.form){let r=this.validationSelection();return t(e),this.pageContext.formValidateCandidate(e,r)}return this.cancelValidation(),this.#i=this.pageContext.validationCurrent(),this.#o.start(e,this.#a,{...this.pageContext,selection:r=>this.validateSelection(r)},
|
|
245
|
+
@media(prefers-reduced-motion:reduce){#field-message{transition:none}}`,this.shadowRoot.append(e),this.control.setAttribute("aria-describedby",this.message.id),this.controlBox.append(this.message),this.control.addEventListener("input",()=>this.cancelValidation()),this.control.addEventListener("compositionstart",()=>this.cancelValidation()),this.control.addEventListener("focusin",()=>this.#l()),this.control.addEventListener("mouseenter",()=>this.#l()),this.control.addEventListener("keydown",t=>{t.key==="Escape"&&(this.cancelValidation(),this.#s())})}#s(){this.ownerDocument.defaultView.clearTimeout(this.#r),this.#n?.abort(),this.#n=null,this.message.hidden||this.message.hidePopover(),this.message.hidden=!0,this.message.removeAttribute("data-fading")}#l(){if(!this.message.textContent||!this.isConnected)return;this.#s();let e=this.ownerDocument.defaultView;this.message.hidden=!1,this.message.showPopover(),ao(this.message,this.control),this.#r=e.setTimeout(()=>{this.message.hidden||(this.message.setAttribute("data-fading",""),this.#r=e.setTimeout(()=>this.#s(),zm))},A0),this.#n=new e.AbortController;let t={capture:!0,signal:this.#n.signal};e.addEventListener("scroll",()=>this.#s(),t),e.addEventListener("resize",()=>this.#s(),t)}releaseControl(){this.#o.cancel(),this.#s(),super.releaseControl()}disconnectedCallback(){this.releaseControl()}setFieldState({invalid:e=!1,pending:t=!1}={}){this.control.setAttribute("aria-invalid",String(e)),this.control.setAttribute("aria-busy",String(t))}error(e){this.#e=!1,["input","textarea"].includes(this.control.localName)&&this.control.setCustomValidity(e),this.control.setAttribute("aria-invalid",String(!!e)),this.message.textContent=e,e?this.#l():this.#s()}restoreFormValue(e){this.error(""),this.#e=!1,super.restoreFormValue(e)}cancelValidation(){this.pageContext?.form&&this.pageContext.formCancelValidation(),this.#o.cancel(),this.#i=null,this.control.setAttribute("aria-busy","false")}presentValidation(e){this.validationResult=e,this.control.setAttribute("aria-busy","false"),this.error(e.error||""),this.message.dataset.severity=e.error?"error":"warning",this.#e=!!e.error,!e.error&&e.warnings.length&&(this.message.textContent=e.warnings.join(`
|
|
246
|
+
`),this.#l())}validateCandidate(e,t){if(this.pageContext.form){let r=this.validationSelection();return t(e),this.pageContext.formValidateCandidate(e,r)}return this.cancelValidation(),this.#i=this.pageContext.validationCurrent(),this.#o.start(e,this.#a,{...this.pageContext,selection:r=>this.validateSelection(r)},Pc,r=>{if(this.#i=null,r.ok)try{t(r.value)}catch(o){r.ok=!1,r.result.error=o.message}this.presentValidation(r.result),r.ok||this.finishValidation(r)},()=>this.control.setAttribute("aria-busy","true"))}finishValidation(e){e.result&&this.pageContext.finishValidation(e)}shouldProjectControlValue(e){!this.pageContext?.form&&this.#i&&!this.#i()&&this.cancelValidation();let t=this.sameControlValue(e,this.#t);return t&&this.#e?!1:(!t&&!this.pageContext?.form&&this.cancelValidation(),this.#t=e,!t&&this.#e&&this.error(""),!0)}projectAttributes(e,t){let r=super.projectAttributes(e,t),o=Object.fromEntries(Object.entries(e).filter(([l])=>l.startsWith("validate_"))),i=new Set([...Object.keys(o),...Object.keys(this.#a)]);!this.pageContext?.form&&([...i].some(l=>!Object.is(o[l],this.#a[l]))||e.disabled||e.readonly)&&this.cancelValidation();let a=[...i].some(l=>!Object.is(o[l],this.#a[l]));this.#a=o,a&&this.pageContext?.form&&this.pageContext.formValidate();for(let l of Object.keys(o))delete r[l];let s=!!this.parameters.validate_notnull;return this.control.setAttribute("aria-required",String(s)),(this.control.localName==="textarea"||this.control.localName==="input"&&["text","password"].includes(this.control.type))&&(this.control.required=s),r}}}Hm.parameters=Vm;var Ao=new TextEncoder,Gm=n=>`export {default} from "./collection.js";
|
|
247
247
|
export * from "./collection.js";
|
|
248
248
|
export const buildId = "${n}";
|
|
249
|
-
`,
|
|
249
|
+
`,Lc=n=>typeof n=="string"&&n.length>0&&!/[\\\x00-\x1f:?#%]/.test(n)&&!n.split("/").some(e=>!e||e==="."||e==="..");function Wm(n,e){if(!n||typeof n.name!="string"||!n.name||!["grammar","commands","module"].every(t=>Lc(n[t]))||!Array.isArray(n.css)||!n.css.every(Lc)||!Array.isArray(n.dependencies)||!n.dependencies.every(t=>typeof t=="string"&&t.length>0)||!Array.isArray(n.files)||!n.files.every(Lc)||new Set(n.files).size!==n.files.length||!(e instanceof Map)||e.size!==n.files.length||n.files.some(t=>!(e.get(t)instanceof Uint8Array))||[n.grammar,n.commands,n.module,...n.css].some(t=>!e.has(t)))throw new TypeError("Invalid collection artifact metadata or file inventory")}async function Ym(n,e){Wm(n,e);let t=[Ao.encode("gramlot-build-v1\0")],r=(l,u)=>{let c=typeof u=="string"?Ao.encode(u):u;t.push(Ao.encode(`${l}\0${c.length}\0`),c)};for(let l of["name","grammar","commands","module"])r(l,n[l]);for(let l of n.css)r("css",l);for(let l of n.dependencies)r("dependency",l);let o=(l,u)=>{let c=Ao.encode(l),d=Ao.encode(u);for(let f=0;f<Math.min(c.length,d.length);f++)if(c[f]!==d[f])return c[f]-d[f];return c.length-d.length};for(let l of[...n.files].sort(o))r("path",l),r("content",l===n.module?Gm("__GRAMLOT_BUILD_ID__"):e.get(l));let i=new Uint8Array(t.reduce((l,u)=>l+u.length,0)),a=0;for(let l of t)i.set(l,a),a+=l.length;let s=await crypto.subtle.digest("SHA-256",i);return"sha256:"+[...new Uint8Array(s)].map(l=>l.toString(16).padStart(2,"0")).join("")}async function D0(n,e){if(Wm(n,e),typeof n.buildId!="string"||!/^sha256:[a-f0-9]{64}$/.test(n.buildId))throw new TypeError("Invalid collection buildId");let t=Ao.encode(Gm(n.buildId)),r=e.get(n.module);if(r.length!==t.length||r.some((o,i)=>o!==t[i]))throw new Error("Invalid collection wrapper");if(await Ym(n,e)!==n.buildId)throw new Error(`Collection fingerprint mismatch: ${n.name}`)}function Xm(n,e){if(!e.videoWidth||!e.videoHeight)throw new Error("Video image is not ready");let t=n.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;let r=t.getContext("2d");if(!r)throw new Error("Video image is unavailable");return r.drawImage(e,0,0),t}function nr(n,e,t){return Object.assign(new Error(e,t?{cause:t}:void 0),{code:n})}function fl(n){return n.name==="NotAllowedError"||n.name==="SecurityError"?nr("PERMISSION_DENIED","Camera permission was denied",n):n.name==="NotFoundError"||n.name==="OverconstrainedError"?nr("UNAVAILABLE","Camera is unavailable",n):nr("FAILED",n.message||"Camera failed",n)}var hl=()=>nr("CANCELLED","Photo capture cancelled"),Fc=class{constructor({document:e}){if(!e?.defaultView)throw new TypeError("BrowserCameraProvider requires a document");this.document=e,this.capabilities=Object.freeze(e.defaultView.navigator.mediaDevices?.getUserMedia?["camera"]:[])}takePhoto(e){if(e.aborted)return Promise.reject(hl());if(!this.capabilities.includes("camera"))return Promise.reject(nr("UNAVAILABLE","Camera is unavailable"));let t=this.document,r=t.defaultView;return new Promise((o,i)=>{let a=!1,s=null,l=new r.AbortController,u={signal:l.signal},c=t.createElement("dialog");c.className="gramlot-camera-dialog",c.setAttribute("aria-label","Take photo");let d=t.createElement("style");d.textContent=`
|
|
250
250
|
.gramlot-camera-dialog{max-width:calc(100vw - 2rem);max-height:calc(100vh - 2rem);border:1px solid var(--gramlot-border,#d5dde6);
|
|
251
251
|
border-radius:14px;padding:20px;color:var(--gramlot-ink,#202a35);background:var(--gramlot-surface,#fff);
|
|
252
252
|
box-shadow:0 24px 64px #14243a42;font:14px/1.4 system-ui,sans-serif}
|
|
@@ -256,8 +256,8 @@ export const buildId = "${n}";
|
|
|
256
256
|
.gramlot-camera-dialog .actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px}
|
|
257
257
|
.gramlot-camera-dialog button{font:inherit;cursor:pointer;padding:.4em .8em;border:1px solid var(--gramlot-border-control,#aab4c0);border-radius:6px;background:var(--gramlot-button-background,#fff);color:var(--gramlot-button-color,#202a35)}
|
|
258
258
|
.gramlot-camera-dialog button.primary{background:var(--gramlot-action,#3766b5);color:#fff}.gramlot-camera-dialog button:disabled{opacity:.55}
|
|
259
|
-
`;let f=t.createElement("h2");f.textContent="Take photo";let h=t.createElement("video");h.muted=!0,h.autoplay=!0,h.playsInline=!0;let p=t.createElement("p");p.setAttribute("role","status"),p.textContent="Waiting for camera\u2026";let m=t.createElement("div");m.className="actions";let b=t.createElement("button");b.type="button",b.textContent="Cancel";let w=t.createElement("button");w.type="button",w.textContent="Capture",w.className="primary",w.disabled=!0,m.append(b,w),c.append(d,f,h,p,m);let _=k=>{for(let N of k.getTracks())N.stop()},y=(k,N)=>{a||(a=!0,l.abort(),e.removeEventListener("abort",x),s&&(_(s),s=null),h.srcObject=null,c.open&&c.close(),c.remove(),k?i(k):o(N))},x=()=>y(dl());e.addEventListener("abort",x,{once:!0}),b.addEventListener("click",x,u),c.addEventListener("cancel",k=>{k.preventDefault(),x()},u),c.addEventListener("close",()=>{a||x()},u);let S=()=>{!a&&h.videoWidth>0&&h.videoHeight>0&&(w.disabled=!1,p.textContent="")};h.addEventListener("loadedmetadata",S,u),w.addEventListener("click",()=>{try{let N=zm(t,h).toDataURL("image/jpeg",.9);if(!N.startsWith("data:image/jpeg;"))throw new Error("Camera image encoding failed");y(null,{url:N,format:"jpeg"})}catch(k){y(cl(k))}},u),t.body.append(c);try{c.showModal()}catch(k){y(cl(k));return}if(e.aborted){x();return}Promise.resolve().then(()=>a?null:r.navigator.mediaDevices.getUserMedia({video:!0,audio:!1})).then(async k=>{if(k){if(a){_(k);return}s=k,h.srcObject=s;for(let N of s.getTracks())N.addEventListener("ended",()=>y(rr("UNAVAILABLE","Camera stopped")),u);try{await h.play(),S()}catch(N){y(cl(N))}}},k=>y(cl(k)))})}choosePhoto(e){if(e.aborted)return Promise.reject(dl());let t=this.document,r=t.defaultView;return new Promise((o,i)=>{let a=!1,s=null,l=new r.AbortController,u={signal:l.signal},c=t.createElement("input");c.type="file",c.accept="image/png,image/jpeg,image/webp",c.hidden=!0;let d=(h,p)=>{a||(a=!0,l.abort(),e.removeEventListener("abort",f),s&&s.readyState===1&&s.abort(),c.remove(),h?i(h):o(p))},f=()=>d(dl());if(e.addEventListener("abort",f,{once:!0}),c.addEventListener("cancel",f,u),c.addEventListener("change",()=>{let h=c.files[0];if(!h||!["image/png","image/jpeg","image/webp"].includes(h.type)){d(rr("FAILED","Select a PNG, JPEG or WebP image"));return}s=new r.FileReader,s.onload=()=>d(null,{url:s.result,format:h.type.slice(6)}),s.onerror=()=>d(rr("FAILED","Photo could not be read",s.error)),s.readAsDataURL(h)},u),t.body.append(c),e.aborted){f();return}try{c.click()}catch(h){d(rr("FAILED","Photo selection failed",h))}})}};var Fc=new WeakMap,p0=/^m_[a-f0-9]+$/;function qc(n,e,{messages:t}){if(!(t instanceof E)||t instanceof I)throw new TypeError("Chat messages require a Data Bag");let r=e.parentNode,o=n.dom.getDomNode(r);if(!o)return;let i=Fc.get(r);i||(i={rows:new Map,active:!0},Fc.set(r,i),n.src.renderer.onDispose(r,()=>{i.active=!1;for(let c of i.rows.keys())r.getRelativeData(".messageData").popNode(c);i.rows.clear(),Fc.delete(r)}));let a=t.getNodes();for(let c of a)if(!p0.test(c.label)||!["user","assistant"].includes(c.attr.role)||typeof c.attr.author!="string"||!(typeof c.staticValue=="string"||c.staticValue instanceof Ae))throw new TypeError("Chat messages require a stable label, role, author and string or Gramlot Source");let s=o.scrollHeight-o.clientHeight-o.scrollTop<48,l=[];for(let c of a){let d=i.rows.get(c.label);if(d&&d.value===c.staticValue&&d.role===c.attr.role&&d.author===c.attr.author)continue;let f=new Oe,h=f.root.article({node_label:c.label,datapath:r.absDatapath(".messageData."+c.label),"data-role":c.attr.role,"aria-label":c.attr.author}),p=ie(h.div());typeof c.staticValue=="string"?f.wrapSource(p).div("=="+JSON.stringify(c.staticValue),{white_space:"pre-wrap"}):p.setValue(n.src.prepareSource(c.staticValue.toTytx()));let m=n.src.prepareSource(f.source);n.src.renderer.validateCandidate(m),l.push({message:c,old:d,child:m.getNode(c.label)})}let u=new Set(a.map(c=>c.label));for(let[c]of i.rows)u.has(c)||(r.value.popNode(c),r.getRelativeData(".messageData").popNode(c),i.rows.delete(c));for(let{message:c,old:d,child:f}of l)d&&r.value.popNode(c.label),d||r.setRelativeData(".messageData."+c.label,new E),n.src.builder.setChild(r.value,f.nodeTag,f.value,{...f.attr,node_label:c.label}),i.rows.set(c.label,{value:c.staticValue,role:c.attr.role,author:c.attr.author});s&&queueMicrotask(()=>{i.active&&(o.scrollTop=o.scrollHeight)})}function Gm(n,e,t=null){if(n.getRelativeData(".pending")||n.getRelativeData(".picking")||!n.getRelativeData(".conversation.ready"))return;let r=K();n.SET(".requestId",r),n.SET(".pending",!0),n.SET(".error",""),n.SET(".conversation.request",new E({id:r,action:e,text:t,attachments:F(L(n.getRelativeData(".attachments")))}))}function Uc(n,e){let t=e.getRelativeData(".draft");typeof t!="string"||!t.trim()&&!e.getRelativeData(".attachments").length||Gm(e,"send",t)}function Vc(n,e){Gm(e,"reset")}function zc(n,e,{response:t}){if(t!==null){if(!(t instanceof E))throw new TypeError("Chat response requires a Data Bag");t.getItem("id")===e.getRelativeData(".requestId")&&(t.getItem("accepted")&&t.getItem("submitted")===e.getRelativeData(".draft")&&e.SET(".draft",""),t.getItem("accepted")&&t.getItem("submitted")!==null&&e.SET(".attachments",new E),e.SET(".pending",!1),e.SET(".error",t.getItem("error")))}}var jc=new WeakMap;function Hc(n,e){let t=e.parentNode,r=jc.get(t);if(!r){let o=n.dom.getDomNode(t);if(!o)return;let i=o.closest("[data-chat-composer]"),a=o.querySelector("textarea"),s=i.querySelector("[data-chat-top]"),l=i.querySelector("[data-chat-toolbar]"),u=o.ownerDocument.defaultView,c=0,d=!0,f=()=>{if(c=0,!d)return;a.style.height="0px";let m=u.getComputedStyle(a),b=parseFloat(m.borderTopWidth)+parseFloat(m.borderBottomWidth),w=Math.max(44,Math.min(180,a.scrollHeight+b));a.style.height=w+"px",a.style.overflowY=a.scrollHeight+b>w?"auto":"hidden";let _=Math.ceil(o.getBoundingClientRect().height+s.getBoundingClientRect().height+l.getBoundingClientRect().height+2);e.getRelativeData(".composerHeight")!==_&&e.SET(".composerHeight",_)},h=()=>{d&&!c&&(c=u.requestAnimationFrame(f))},p=new u.ResizeObserver(h);for(let m of[o,s,l])p.observe(m);n.src.renderer.onDispose(t,()=>{d=!1,p.disconnect(),c&&u.cancelAnimationFrame(c),jc.delete(t)}),r={schedule:h},jc.set(t,r)}r.schedule()}var m0=["txt","md","csv","json","py","js","ts","jsx","tsx","html","css","sql","yaml","yml","xml","sh","toml","log"],Hm={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",pdf:"application/pdf",...Object.fromEntries(m0.map(n=>[n,"text/plain"]))};function g0(n,e){return new Promise((t,r)=>{let o=new e.FileReader;o.onload=()=>t(o.result.slice(o.result.indexOf(",")+1)),o.onerror=()=>r(new Error("Could not read the selected file.")),o.readAsDataURL(n)})}async function Gc(n,e){if(e.getRelativeData(".pending")||e.getRelativeData(".picking"))return;let t=n.dom.getDomNode(e.parentNode).ownerDocument,r=t.createElement("input");r.type="file",r.multiple=!0,r.accept=Object.keys(Hm).map(s=>"."+s).join(","),r.style.display="none",t.body.append(r);let o=!0,i,a=n.src.renderer.onDispose(e.parentNode,()=>{o=!1,r.remove(),i([])});e.SET(".picking",!0),e.SET(".error","");try{let s=await new Promise(c=>{i=c,r.addEventListener("cancel",()=>c([]),{once:!0}),r.addEventListener("change",()=>c([...r.files]),{once:!0}),r.click()});if(!o||!s.length)return;let l=F(L(e.getRelativeData(".attachments")));if(l.length+s.length>5)throw new Error("Choose at most 5 files.");let u=l.getNodes().reduce((c,d)=>c+d.staticValue.getItem("size"),0);for(let c of s){let d=Hm[c.name.split(".").pop().toLowerCase()];if(!d)throw new Error("Supported files: PNG, JPEG, WebP, PDF and UTF-8 text/code.");let f=d==="text/plain"?1024*1024:2*1024*1024;if(u+=c.size,!c.size||c.size>f||u>4*1024*1024)throw new Error("Limits: 2 MiB per file, 1 MiB for text, 4 MiB total.");let h=await g0(c,t.defaultView);if(d==="text/plain"){let p=Uint8Array.from(atob(h),m=>m.charCodeAt(0));if(new TextDecoder("utf-8",{fatal:!0}).decode(p),p.includes(0))throw new Error("The selected file is not UTF-8 text.")}l.setItem("a_"+K(),new E({name:c.name,mediaType:d,size:c.size,data:h}))}o&&e.SET(".attachments",l)}catch(s){o&&e.SET(".error",s.message)}finally{a(),r.remove(),o&&e.SET(".picking",!1)}}function Wc(n,e){e.getRelativeData(".pending")||e.getRelativeData(".attachments").popNode(e.getAttr("attachment_id"))}function Yc(n,e,{attachments:t}){let r=e.parentNode;for(let a of[...r.value.getNodes()])a.label.startsWith("a_")&&r.value.popNode(a.label);let o=new Oe;for(let a of t.getNodes()){let s=a.staticValue,l=o.root.div({node_label:a.label,display:"flex",align_items:"center",gap:"6px",padding:"4px 8px",border:"1px solid var(--gramlot-border-control,#aaa)",border_radius:"10px",flex_shrink:0});s.getItem("mediaType").startsWith("image/")&&l.img({src:"data:"+s.getItem("mediaType")+";base64,"+s.getItem("data"),alt:"Attachment preview",width:"36px",height:"36px",object_fit:"cover",border_radius:"6px"}),l.span("=="+JSON.stringify(s.getItem("name")),{font_size:"12px",max_width:"180px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),l.button({icon:"\xD7","aria-label":"Remove "+s.getItem("name"),disabled:"^.pending",class:"button--quiet"}).dataController({func:"chatRemoveAttachment",attachment_id:a.label})}let i=n.src.prepareSource(o.source);n.src.renderer.validateCandidate(i);for(let a of i.getNodes())n.src.builder.setChild(r.value,a.nodeTag,a.value,{...a.attr,node_label:a.label})}var fl=class{constructor({app:e,editor:t,design:r}){this.renderer=e.src.renderer,this.design=r;let o=this.renderer.records.get(r).presentation;this.frame=o.ownerDocument.createElement("iframe"),this.frame.title="Page canvas",this.frame.className="visual-editor-canvas-frame",this.frame.style.cssText="display:block;width:100%;height:100%;min-height:240px;border:0;background:white",o.before(this.frame);let i=this.frame.contentDocument;e.registerDocument(i);let a=i.createElement("style");a.textContent="html,body{margin:0;min-height:100%;} .visual-editor-canvas{min-height:100vh;}",this.styles=i.createElement("style");let s=i.createElement("style");s.textContent=".gramlot-source-selected{outline:2px solid #8ab4f8!important;outline-offset:-2px!important;}",i.head.append(a,this.styles,s),this.body=i.body,this.renderer.mountDestination(r,this.body),this.release=this.renderer.onDispose(t,()=>this.dispose())}setCss(e){this.styles.textContent=e.join(`
|
|
260
|
-
`)}dispose(){this.release?.(),this.release=null,this.frame.remove()}};var
|
|
259
|
+
`;let f=t.createElement("h2");f.textContent="Take photo";let h=t.createElement("video");h.muted=!0,h.autoplay=!0,h.playsInline=!0;let p=t.createElement("p");p.setAttribute("role","status"),p.textContent="Waiting for camera\u2026";let m=t.createElement("div");m.className="actions";let b=t.createElement("button");b.type="button",b.textContent="Cancel";let w=t.createElement("button");w.type="button",w.textContent="Capture",w.className="primary",w.disabled=!0,m.append(b,w),c.append(d,f,h,p,m);let _=k=>{for(let C of k.getTracks())C.stop()},y=(k,C)=>{a||(a=!0,l.abort(),e.removeEventListener("abort",x),s&&(_(s),s=null),h.srcObject=null,c.open&&c.close(),c.remove(),k?i(k):o(C))},x=()=>y(hl());e.addEventListener("abort",x,{once:!0}),b.addEventListener("click",x,u),c.addEventListener("cancel",k=>{k.preventDefault(),x()},u),c.addEventListener("close",()=>{a||x()},u);let D=()=>{!a&&h.videoWidth>0&&h.videoHeight>0&&(w.disabled=!1,p.textContent="")};h.addEventListener("loadedmetadata",D,u),w.addEventListener("click",()=>{try{let C=Xm(t,h).toDataURL("image/jpeg",.9);if(!C.startsWith("data:image/jpeg;"))throw new Error("Camera image encoding failed");y(null,{url:C,format:"jpeg"})}catch(k){y(fl(k))}},u),t.body.append(c);try{c.showModal()}catch(k){y(fl(k));return}if(e.aborted){x();return}Promise.resolve().then(()=>a?null:r.navigator.mediaDevices.getUserMedia({video:!0,audio:!1})).then(async k=>{if(k){if(a){_(k);return}s=k,h.srcObject=s;for(let C of s.getTracks())C.addEventListener("ended",()=>y(nr("UNAVAILABLE","Camera stopped")),u);try{await h.play(),D()}catch(C){y(fl(C))}}},k=>y(fl(k)))})}choosePhoto(e){if(e.aborted)return Promise.reject(hl());let t=this.document,r=t.defaultView;return new Promise((o,i)=>{let a=!1,s=null,l=new r.AbortController,u={signal:l.signal},c=t.createElement("input");c.type="file",c.accept="image/png,image/jpeg,image/webp",c.hidden=!0;let d=(h,p)=>{a||(a=!0,l.abort(),e.removeEventListener("abort",f),s&&s.readyState===1&&s.abort(),c.remove(),h?i(h):o(p))},f=()=>d(hl());if(e.addEventListener("abort",f,{once:!0}),c.addEventListener("cancel",f,u),c.addEventListener("change",()=>{let h=c.files[0];if(!h||!["image/png","image/jpeg","image/webp"].includes(h.type)){d(nr("FAILED","Select a PNG, JPEG or WebP image"));return}s=new r.FileReader,s.onload=()=>d(null,{url:s.result,format:h.type.slice(6)}),s.onerror=()=>d(nr("FAILED","Photo could not be read",s.error)),s.readAsDataURL(h)},u),t.body.append(c),e.aborted){f();return}try{c.click()}catch(h){d(nr("FAILED","Photo selection failed",h))}})}};var jc=new WeakMap,S0=/^m_[a-f0-9]+$/;function Uc(n,e,{messages:t}){if(!(t instanceof E)||t instanceof I)throw new TypeError("Chat messages require a Data Bag");let r=e.parentNode,o=n.dom.getDomNode(r);if(!o)return;let i=jc.get(r);i||(i={rows:new Map,active:!0},jc.set(r,i),n.src.renderer.onDispose(r,()=>{i.active=!1;for(let c of i.rows.keys())r.getRelativeData(".messageData").popNode(c);i.rows.clear(),jc.delete(r)}));let a=t.getNodes();for(let c of a)if(!S0.test(c.label)||!["user","assistant"].includes(c.attr.role)||typeof c.attr.author!="string"||!(typeof c.staticValue=="string"||c.staticValue instanceof Ae))throw new TypeError("Chat messages require a stable label, role, author and string or Gramlot Source");let s=o.scrollHeight-o.clientHeight-o.scrollTop<48,l=[];for(let c of a){let d=i.rows.get(c.label);if(d&&d.value===c.staticValue&&d.role===c.attr.role&&d.author===c.attr.author)continue;let f=new Oe,h=f.root.article({node_label:c.label,datapath:r.absDatapath(".messageData."+c.label),"data-role":c.attr.role,"aria-label":c.attr.author}),p=ae(h.div());typeof c.staticValue=="string"?f.wrapSource(p).div("=="+JSON.stringify(c.staticValue),{white_space:"pre-wrap"}):p.setValue(n.src.prepareSource(c.staticValue.toTytx()));let m=n.src.prepareSource(f.source);n.src.renderer.validateCandidate(m),l.push({message:c,old:d,child:m.getNode(c.label)})}let u=new Set(a.map(c=>c.label));for(let[c]of i.rows)u.has(c)||(r.value.popNode(c),r.getRelativeData(".messageData").popNode(c),i.rows.delete(c));for(let{message:c,old:d,child:f}of l)d&&r.value.popNode(c.label),d||r.setRelativeData(".messageData."+c.label,new E),n.src.builder.setChild(r.value,f.nodeTag,f.value,{...f.attr,node_label:c.label}),i.rows.set(c.label,{value:c.staticValue,role:c.attr.role,author:c.attr.author});s&&queueMicrotask(()=>{i.active&&(o.scrollTop=o.scrollHeight)})}function Km(n,e,t=null){if(n.getRelativeData(".pending")||n.getRelativeData(".picking")||!n.getRelativeData(".conversation.ready"))return;let r=J();n.SET(".requestId",r),n.SET(".pending",!0),n.SET(".error",""),n.SET(".conversation.request",new E({id:r,action:e,text:t,attachments:j(L(n.getRelativeData(".attachments")))}))}function Vc(n,e){let t=e.getRelativeData(".draft");typeof t!="string"||!t.trim()&&!e.getRelativeData(".attachments").length||Km(e,"send",t)}function zc(n,e){Km(e,"reset")}function Hc(n,e,{response:t}){if(t!==null){if(!(t instanceof E))throw new TypeError("Chat response requires a Data Bag");t.getItem("id")===e.getRelativeData(".requestId")&&(t.getItem("accepted")&&t.getItem("submitted")===e.getRelativeData(".draft")&&e.SET(".draft",""),t.getItem("accepted")&&t.getItem("submitted")!==null&&e.SET(".attachments",new E),e.SET(".pending",!1),e.SET(".error",t.getItem("error")))}}var qc=new WeakMap;function Gc(n,e){let t=e.parentNode,r=qc.get(t);if(!r){let o=n.dom.getDomNode(t);if(!o)return;let i=o.closest("[data-chat-composer]"),a=o.querySelector("textarea"),s=i.querySelector("[data-chat-top]"),l=i.querySelector("[data-chat-toolbar]"),u=o.ownerDocument.defaultView,c=0,d=!0,f=()=>{if(c=0,!d)return;a.style.height="0px";let m=u.getComputedStyle(a),b=parseFloat(m.borderTopWidth)+parseFloat(m.borderBottomWidth),w=Math.max(44,Math.min(180,a.scrollHeight+b));a.style.height=w+"px",a.style.overflowY=a.scrollHeight+b>w?"auto":"hidden";let _=Math.ceil(o.getBoundingClientRect().height+s.getBoundingClientRect().height+l.getBoundingClientRect().height+2);e.getRelativeData(".composerHeight")!==_&&e.SET(".composerHeight",_)},h=()=>{d&&!c&&(c=u.requestAnimationFrame(f))},p=new u.ResizeObserver(h);for(let m of[o,s,l])p.observe(m);n.src.renderer.onDispose(t,()=>{d=!1,p.disconnect(),c&&u.cancelAnimationFrame(c),qc.delete(t)}),r={schedule:h},qc.set(t,r)}r.schedule()}var C0=["txt","md","csv","json","py","js","ts","jsx","tsx","html","css","sql","yaml","yml","xml","sh","toml","log"],Zm={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",pdf:"application/pdf",...Object.fromEntries(C0.map(n=>[n,"text/plain"]))};function N0(n,e){return new Promise((t,r)=>{let o=new e.FileReader;o.onload=()=>t(o.result.slice(o.result.indexOf(",")+1)),o.onerror=()=>r(new Error("Could not read the selected file.")),o.readAsDataURL(n)})}async function Wc(n,e){if(e.getRelativeData(".pending")||e.getRelativeData(".picking"))return;let t=n.dom.getDomNode(e.parentNode).ownerDocument,r=t.createElement("input");r.type="file",r.multiple=!0,r.accept=Object.keys(Zm).map(s=>"."+s).join(","),r.style.display="none",t.body.append(r);let o=!0,i,a=n.src.renderer.onDispose(e.parentNode,()=>{o=!1,r.remove(),i([])});e.SET(".picking",!0),e.SET(".error","");try{let s=await new Promise(c=>{i=c,r.addEventListener("cancel",()=>c([]),{once:!0}),r.addEventListener("change",()=>c([...r.files]),{once:!0}),r.click()});if(!o||!s.length)return;let l=j(L(e.getRelativeData(".attachments")));if(l.length+s.length>5)throw new Error("Choose at most 5 files.");let u=l.getNodes().reduce((c,d)=>c+d.staticValue.getItem("size"),0);for(let c of s){let d=Zm[c.name.split(".").pop().toLowerCase()];if(!d)throw new Error("Supported files: PNG, JPEG, WebP, PDF and UTF-8 text/code.");let f=d==="text/plain"?1024*1024:2*1024*1024;if(u+=c.size,!c.size||c.size>f||u>4*1024*1024)throw new Error("Limits: 2 MiB per file, 1 MiB for text, 4 MiB total.");let h=await N0(c,t.defaultView);if(d==="text/plain"){let p=Uint8Array.from(atob(h),m=>m.charCodeAt(0));if(new TextDecoder("utf-8",{fatal:!0}).decode(p),p.includes(0))throw new Error("The selected file is not UTF-8 text.")}l.setItem("a_"+J(),new E({name:c.name,mediaType:d,size:c.size,data:h}))}o&&e.SET(".attachments",l)}catch(s){o&&e.SET(".error",s.message)}finally{a(),r.remove(),o&&e.SET(".picking",!1)}}function Yc(n,e){e.getRelativeData(".pending")||e.getRelativeData(".attachments").popNode(e.getAttr("attachment_id"))}function Xc(n,e,{attachments:t}){let r=e.parentNode;for(let a of[...r.value.getNodes()])a.label.startsWith("a_")&&r.value.popNode(a.label);let o=new Oe;for(let a of t.getNodes()){let s=a.staticValue,l=o.root.div({node_label:a.label,display:"flex",align_items:"center",gap:"6px",padding:"4px 8px",border:"1px solid var(--gramlot-border-control,#aaa)",border_radius:"10px",flex_shrink:0});s.getItem("mediaType").startsWith("image/")&&l.img({src:"data:"+s.getItem("mediaType")+";base64,"+s.getItem("data"),alt:"Attachment preview",width:"36px",height:"36px",object_fit:"cover",border_radius:"6px"}),l.span("=="+JSON.stringify(s.getItem("name")),{font_size:"12px",max_width:"180px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),l.button({icon:"\xD7","aria-label":"Remove "+s.getItem("name"),disabled:"^.pending",class:"button--quiet"}).dataController({func:"chatRemoveAttachment",attachment_id:a.label})}let i=n.src.prepareSource(o.source);n.src.renderer.validateCandidate(i);for(let a of i.getNodes())n.src.builder.setChild(r.value,a.nodeTag,a.value,{...a.attr,node_label:a.label})}var pl=class{constructor({app:e,editor:t,design:r}){this.renderer=e.src.renderer,this.design=r;let o=this.renderer.records.get(r).presentation;this.frame=o.ownerDocument.createElement("iframe"),this.frame.title="Page canvas",this.frame.className="visual-editor-canvas-frame",this.frame.style.cssText="display:block;width:100%;height:100%;min-height:240px;border:0;background:white",o.before(this.frame);let i=this.frame.contentDocument;e.registerDocument(i);let a=i.createElement("style");a.textContent="html,body{margin:0;min-height:100%;} .visual-editor-canvas{min-height:100vh;}",this.styles=i.createElement("style");let s=i.createElement("style");s.textContent=".gramlot-source-selected{outline:2px solid #8ab4f8!important;outline-offset:-2px!important;}",i.head.append(a,this.styles,s),this.body=i.body,this.renderer.mountDestination(r,this.body),this.release=this.renderer.onDispose(t,()=>this.dispose())}setCss(e){this.styles.textContent=e.join(`
|
|
260
|
+
`)}dispose(){this.release?.(),this.release=null,this.frame.remove()}};var Jm=["string","number","integer","boolean","date","time","datetime","null"];function Zc(n){if(n===null)return"null";if(["string","boolean"].includes(typeof n))return typeof n;if(typeof n=="number"&&Number.isFinite(n))return Number.isSafeInteger(n)?"integer":"number";if(n instanceof Date&&Number.isFinite(n.getTime())){let e=n.toISOString();return e.slice(0,10)==="1970-01-01"?"time":e.endsWith("T00:00:00.000Z")?"date":"datetime"}return null}function ml(n,e){if(e==="null")return"";if(n instanceof Date){let t=n.toISOString();return e==="date"?t.slice(0,10):e==="time"?t.slice(11,23):t}return String(n)}function Kc(n,e){if(n==="string")return e;if(n==="null")return null;if(n==="boolean"&&["true","false"].includes(e))return e==="true";if((n==="number"||n==="integer")&&/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e.trim())){let t=Number(e);if(Number.isFinite(t)&&(n!=="integer"||Number.isSafeInteger(t)))return t}if(["date","time","datetime"].includes(n)&&(n==="date"?/^\d{4}-\d{2}-\d{2}$/:n==="time"?/^\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/:/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?Z$/).test(e)){let r=n==="date"?`${e}T00:00:00Z`:n==="time"?`1970-01-01T${e}Z`:e,o=new Date(r);if(Number.isFinite(o.getTime())){let i=o.toISOString(),a=r.replace(/Z$/,"").split(/[T:.]/),s=i.replace(/Z$/,"").split(/[T:.]/);if(a.every((l,u)=>u===4?Number(l.padEnd(3,"0"))===Number(s[u]):l===s[u]))return o}}throw new Error(`Invalid ${n} value: ${e||"(empty)"}`)}var ta=class{#e;#t;#r;#n;#o;#i=null;#a=null;#s=null;#l=!1;constructor({renderer:e,root:t,onSelect:r,canvas:o=e.records.get(t.parentNode)?.presentation}){if(!t?.parentNode||typeof r!="function")throw new TypeError("SourcePicker requires a mounted Source root and onSelect");if(!o||o.nodeType!==1)throw new TypeError("SourcePicker requires a mounted preview");this.#e=e,this.#t=t,this.#r=o,this.#n=r,o.addEventListener("pointerdown",this,!0),o.addEventListener("click",this,!0),this.#o=new o.ownerDocument.defaultView.MutationObserver(()=>this.#u()),this.#o.observe(o,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["class"]}),this.#s=e.onDispose(t.parentNode,()=>this.dispose())}handleEvent(e){if(this.#l)return;let t=this.#t.fullpath+".",r=e.composedPath().map(i=>this.#e.elements.get(i)).find(i=>i?.node.fullpath.startsWith(t));if(!r)return;e.composedPath().some(i=>i.nodeType===1&&(i.matches("input:not([type=button]):not([type=submit]):not([type=reset]):not([type=image]), textarea, select, label")||i.isContentEditable))||(e.preventDefault(),e.stopImmediatePropagation()),this.#n(r.node)}select(e){if(!this.#l){if(e===null)this.#i=null;else{let t=this.#t.fullpath+".";if(!e.fullpath.startsWith(t))throw new TypeError("Selected node must be inside the preview Source root");this.#i=e.fullpath.slice(t.length)}this.#u()}}#u(){if(this.#l)return;let e=this.#i?this.#t.staticValue.getNode(this.#i):null,t=e?this.#e.records.get(e)?.presentation:null,r=t?.nodeType===1?t:null;this.#a!==r&&(this.#a?.classList.remove("gramlot-source-selected"),this.#a=r),r&&!r.classList.contains("gramlot-source-selected")&&r.classList.add("gramlot-source-selected")}dispose(){this.#l||(this.#l=!0,this.#o.disconnect(),this.#r.removeEventListener("pointerdown",this,!0),this.#r.removeEventListener("click",this,!0),this.#a?.classList.remove("gramlot-source-selected"),this.#s?.(),this.#s=null,this.#a=null)}};var Jc={base:"",compact:`/* gramlot-compact: professional density profile; load after Base. */
|
|
261
261
|
@layer gramlot.tokens {
|
|
262
262
|
:root {
|
|
263
263
|
color-scheme: light;
|
|
@@ -1505,7 +1505,7 @@ export const buildId = "${n}";
|
|
|
1505
1505
|
:where([role="toolbar"]) { background:Canvas; color:CanvasText; backdrop-filter:none; }
|
|
1506
1506
|
}
|
|
1507
1507
|
}
|
|
1508
|
-
`},
|
|
1508
|
+
`},Qc={default:"",compact:`/* Color-only override: load after the chosen appearance profile. */
|
|
1509
1509
|
@layer gramlot.tokens {
|
|
1510
1510
|
:root {
|
|
1511
1511
|
color-scheme: light;
|
|
@@ -1781,8 +1781,8 @@ export const buildId = "${n}";
|
|
|
1781
1781
|
--gramlot-warning-background: #413820;
|
|
1782
1782
|
}
|
|
1783
1783
|
}
|
|
1784
|
-
`};function ae(n){for(let e=n;e;e=e.parentNode)if(e.getAttr("visualEditorId"))return e;throw new Error("Operation requires a VisualEditor Source ancestor")}function he(n){return ae(n).fullpath.split(".").slice(1).join(".")+".layout.center.design"}function Qe(n){return ae(n).absDatapath(".")}function pl(n,e){return n.rootBuilder.binding.nodeIds.get(ae(n).getAttr("visualEditorId")+e)}var Ym=[["html.structure","Structure","main header footer nav section article aside div address search"],["html.text","Text and headings","h1 h2 h3 h4 h5 h6 hgroup p span a b strong i em small s u mark abbr cite code pre blockquote q br wbr hr time data dfn kbd samp var bdi bdo ruby rt rp sub sup ins del_"],["html.lists","Lists","ul ol li dl dt dd"],["html.forms","Forms","form input textarea select selectedcontent option optgroup datalist label fieldset legend output progress meter html_button"],["html.tables","Tables","table caption colgroup col thead tbody tfoot tr th td"],["html.media","Media and embedded content","img picture source audio video track canvas iframe embed object param map area"],["html.interaction","Disclosure and menus","details summary html_dialog html_menu"],["html.document","Document and metadata","html head body title base meta link style script noscript template slot"],["components.layout.containers","Containers","borderContainer contentPane framePane stackContainer tabContainer"],["components.layout.windows","Windows","dialog floatingPane"],["components.layout.composition","Composition","formlet groupBox trayPane transformPane"],["components.inputs.text","Text","textbox textBoxArea passwordbox"],["components.inputs.choices","Choices","checkbox radioButton radioButtonText checkBoxText filteringSelect comboBox callbackSelect dbSelect dbComboBox"],["components.inputs.numbers","Numbers and colors","numberTextBox horizontalSlider verticalSlider colorpicker"],["components.inputs.dates","Dates and times","dateTextBox timeTextBox dateCalendar"],["components.commands","Buttons and menus","button toggleButton dropDownButton menu menuline spacer"],["components.data","Trees and grids","tree grid searchBox"],["components.editors","Editors and previews","codeMirror htmlEditor htmlPreview markdownEditor markdownPreview typstPreview"]],b0={html:"HTML",components:"Gramlot","components.layout":"Layout","components.inputs":"Inputs"},bl=Object.fromEntries(["class","style","width","height","padding","margin","color","background"].map(n=>[n,{dtype:"T",nullable:!0}])),Xm=Object.fromEntries(["lbl_","box_"].flatMap(n=>Object.entries(bl).map(([e,t])=>[n+e,t]))),Qc=[["general","General"],["behaviour","Behaviour"],["validation","Validation"],["styles","Styles"],["container","Container"]],ml=["T","B","L","R","N","D","H"];function ed(n,e){return/^(lbl|box)(_|$)/.test(n)?"general":e.has(n)?"container":n.startsWith("validate_")?"validation":Object.hasOwn(bl,n)||/^(icon|tab)/.test(n)||["design","labelPosition","switch_color","orientation"].includes(n)?"styles":/^(on[A-Z]|get[A-Z]|drag|drop)/.test(n)||["action","command","disabled","readonly","live","beforeClose","open","collapsed","closable","movable","resizable","collapsible","maximizable","maximized","persist","autoCollapse","openOnClick"].includes(n)?"behaviour":"general"}var nr=(n,e,t=null)=>{let r=n.builder.schema[e];if(!r)throw new Error(`Unknown widget: ${e}`);let o=r._meta?.gramlot_component;return{...(!t||!(t.getValue(!0)instanceof t.builder.source.constructor))&&(!o||o.command&&!Object.hasOwn(o.parameters,"caption"))?{_text:{dtype:"T",nullable:!0}}:{},...bl,...o?.labelbox?Xm:{},...o?.parameters??{},...n._getMeta("gramlot_component")?.childParameters??{}}},gl=new WeakMap,ra=new WeakMap,td=class{chatRender(e,t){return qc(this.page,e,t)}chatCompleted(e,t){zc(this.page,e,t),e.GET(`${Qe(e)}.assistant.active`)&&e.SET(".pending",!0)}chatReset(e){return Vc(this.page,e)}chatResize(e){return Hc(this.page,e)}chatPickAttachments(e){return Gc(this.page,e)}chatRenderAttachments(e,t){return Yc(this.page,e,t)}chatRemoveAttachment(e){return Wc(this.page,e)}chatSend(e){if(e.GET(".pending")||!e.GET(".conversation.ready")||!e.GET(".draft")?.trim())return;let t=ae(e),r=t.GET(".editingMode"),o=e.builder.source.getNode(he(e)).value.toTytx(),i=r==="code"?t.GET(".codeDocument.content"):o;if(r==="code"&&!t.GET(".codeDocument.writable")){e.SET(".error","Page code editing is disabled by the host");return}let a=(t.GET(".assistantRun.run")??0)+1,s=t.GET(".catalogueScope"),l={commonParameters:bl,labelboxParameters:Xm,widgets:{}};for(let[u,c]of Object.entries(e.builder.schema)){if(!xo(s,u,c._meta??{})||c._meta?.data_element||c._meta?.subbuilder||c._meta?.container)continue;let d=c._meta?.gramlot_component;l.widgets[u]={parameters:d?.parameters??{},labelbox:!!d?.labelbox,childParameters:d?.childParameters??{}}}return t.SET(".assistantRun",new E({run:a,mode:r,next:0,expected:i,blocked:!1})),t.SET(".assistantStatus","Waiting for editing instructions\u2026"),t.SET(".assistant.context",new E({run:a,mode:r,language:t.GET(".codeDocument.language")??null,codeWritable:t.GET(".codeDocument.writable")===!0,code:r==="code"?i:null,source:o,selected:t.GET(".selection"),schema:JSON.stringify(l)})),Uc(this.page,e)}assistantState(e,{active:t}){if(t===!1){e.SET(`${Qe(e)}.chat.pending`,!1);let r=ae(e);r.GET(".assistantRun.next")===0&&r.SET(".assistantStatus","")}}assistantApply(e,{operations:t}){if(!(t instanceof E))return;let r=ae(e);for(let o of t.getNodes()){if(o.attr.run!==r.GET(".assistantRun.run")||o.attr.index<r.GET(".assistantRun.next"))continue;let i=e.builder.source.getNode(he(e)).value,a=r.GET(".assistantRun.mode"),s=a==="code"?r.GET(".codeDocument.content"):i.toTytx(),l=!1,u=!1,c="";try{if(r.GET(".assistantRun.blocked"))throw u=!0,new Error("The document was replaced during editing");if(o.attr.index!==r.GET(".assistantRun.next"))throw u=!0,new Error("Editing sequence is incomplete");if(s!==r.GET(".assistantRun.expected"))throw u=!0,new Error("Source changed during the request. Remaining edits stopped; send a new instruction.");let d=JSON.parse(o.value);if(a==="code"){if(d.operation!=="replace_code"||typeof d.content!="string")throw new Error("Expected a Page code draft operation");if(!r.GET(".codeDocument.writable")||r.GET(".codeDocument.busy"))throw new Error("Page code draft is not editable now");r.SET(".codeDocument.content",d.content),r.SET(".codeDocument.status","AI draft \xB7 Save to apply"),r.SET(".codeOpen",!0)}else this.applySourceEdit(r,d);l=!0,r.SET(".assistantRun.expected",a==="code"?r.GET(".codeDocument.content"):i.toTytx()),r.SET(".assistantStatus",`Applied ${o.attr.index+1}: ${a==="code"?"Page code draft":d.operation+" "+d.path}`)}catch(d){c=d.message,(a==="code"?r.GET(".codeDocument.content"):i.toTytx())!==s&&(u=!0),r.SET(".assistantRun.blocked",u),r.SET(".assistantStatus",`${u?"Editing stopped":"Rejected"}: ${c}`)}r.SET(".assistantRun.next",o.attr.index+1),r.SET(".assistant.ack",new E({run:o.attr.run,index:o.attr.index,applied:l,stop:u,error:c,mode:a,code:a==="code"?r.GET(".codeDocument.content"):null,source:i.toTytx(),selected:r.GET(".selection")}))}}applySourceEdit(e,t){let{operation:r,path:o,parent:i,tag:a,label:s,attributes:l={},text:u}=t,c=y=>typeof y=="string"&&/^pageRoot(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(y);if(!c(o)||r==="move"&&!c(i))throw new Error(`Use dot-separated paths inside pageRoot: ${JSON.stringify(o)}`);if(!["insert","update","remove","move"].includes(r))throw new Error("Unknown Source editing operation");if(["remove","move"].includes(r)&&o==="pageRoot")throw new Error("The page root is protected");if(r==="insert"&&(typeof s!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)))throw new Error("Choose an explicit node label");if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Expected scalar attributes");for(let[y,x]of Object.entries(l))if(y.startsWith("_")||/^(connect_|on[A-Z]|script$|formula$|action$|func$|remote_)/.test(y)||["constructor","prototype"].includes(y)||x!==null&&typeof x=="object"||typeof x=="string"&&(x.startsWith("==")||x.includes(":=")))throw new Error(`Unsupported generated attribute: ${y}`);if(u!==void 0&&typeof u!="string")throw new Error("Text must be literal text");let d=e.builder.source.getNode(he(e)),f=e.rootBuilder.binding.gramlot,h=f.src.prepareSource(d.value.toTytx(),d.builder),p=h.getNode(o);if(!p)throw new Error("The Source target no longer exists");let m=p;if(r==="insert"){if(!e.builder.schema[a]||["script","style","iframe","object","embed"].includes(a)||e.builder.schema[a]._meta?.data_element)throw new Error("Choose a visual widget from the catalogue");if(p.value instanceof h.constructor&&p.value.getNode(s))throw new Error("This node label is already in use");m=p.builder.commandOnNode(p,a,u??null,{...l,node_label:s})}else if(r==="update"){if(u!==void 0&&p.value instanceof h.constructor)throw new Error("Text cannot replace a populated container");let y={...p.getAttr()};for(let[x,S]of Object.entries(l))S===null?delete y[x]:y[x]=S;p.setAttr(y,!0,!1,!1),u!==void 0&&p.setValue(u)}else if(r==="remove")p.parentBag.popNode(p.label);else{if(Object.keys(l).length||u!==void 0)throw new Error("Move and property edits must be separate operations");if(i===o||i.startsWith(o+"."))throw new Error("Cannot move a node into itself");let y=h.getNode(i);if(!y)throw new Error("The destination no longer exists");if(y.value instanceof h.constructor&&y.value.getNode(p.label))throw new Error("The destination already contains this label");m=this.appendBranch(y,p,p.label)}let b=y=>{if(y.value instanceof h.constructor){y.builder.validateChildren(y.nodeTag,y.value.getNodes().map(x=>x.nodeTag));for(let x of y.value.getNodes()){for(let[S,k]of Object.entries(nr(y,x.nodeTag,x)))this.validateParameter(y,x,S,k,x.getAttr(S));b(x)}}};h.getNodes().forEach(b),Dt(ae(e).GET(".catalogueScope"),h),f.src.renderer.validateCandidate(h,{replacingNode:d});let w=e.builder.source.getNode(`${he(e)}.${o}`),_=o;r==="insert"?(this.appendBranch(w,m,s),_=`${o}.${s}`):r==="update"?(w.setAttr({...m.getAttr()},!0,!1,!1),u!==void 0&&w.setValue(u)):r==="remove"?(_=o.slice(0,o.lastIndexOf(".")),w.parentBag.popNode(w.label)):(this.applyDrop(e,{item:e.builder.source.getNode(`${he(e)}.${i}`),path:i,dropValues:{"app/source":{path:o}}}),_=`${i}.${w.label}`),e.SET(".sourceSearch",""),e.SET(".selection",_)}initializeCanvasSelection(e){let t=e.rootBuilder.binding.renderer,r=e.builder.source.getNode(he(e)),o=ae(e),i=o.GET(".canvasCss");i!=null&&this.applyCanvasCss(o,i);let a=gl.get(r);a?.dispose();let s=new ta({renderer:t,root:r,...ra.has(r)?{canvas:ra.get(r).body}:{},onSelect:l=>{e.SET(".sourceSearch",""),e.SET(".selection",l.fullpath.slice(r.fullpath.length+1))}});gl.set(r,s),a||t.onDispose(r.parentNode,()=>{gl.delete(r),ra.delete(r)}),this.highlightSelection(e)}applyCanvasCss(e,t){if(!Array.isArray(t)||t.some(a=>typeof a!="string"))throw new TypeError("canvas CSS must be a list of CSS texts");let r=ae(e),o=r.builder.source.getNode(he(r)),i=ra.get(o);i||(i=new fl({app:r.rootBuilder.binding.gramlot,editor:r,design:o}),ra.set(o,i)),i.setCss(t)}setCanvasCss(e,t){let r=ae(e);this.applyCanvasCss(r,t),r.SET(".canvasCss",t),this.initializeCanvasSelection(r)}highlightSelection(e){let t=e.builder.source.getNode(he(e)),r=e.GET(".selection");gl.get(t)?.select(r?t.staticValue.getNode(r):null)}clipboardShortcut(e,t){if(t.defaultPrevented||t.repeat||e.GET(".clipboardOpen")||e.GET(".insertionOpen")||e.GET(".uploadOpen")||t.composedPath().some(i=>i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)))return;let r=t.key.toLowerCase(),o=r==="f8"?"cutBranch":r==="f9"?"pasteBranch":null;!o||t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),this[o](e))}clipboardModifiers(e,t){e.SET(".clipboardDropEffect",t.altKey?"copy":"move")}cutBranch(e){this.beginClipboard(e,e.GET(".selection"),!1)}copyBranch(e){this.beginClipboard(e,e.GET(".selection"),!0)}dropClipboard(e,{dropValues:t,dropEffect:r}){this.beginClipboard(e,t["app/source"].path,r==="copy")}prepareClipboard(e,{path:t,dragValues:r}){e.SET(".sourceDropEffect","copy"),r["app/clipboard"]={path:t}}branchSnapshot(e,t){let r=e.builder.source.getNode(he(e)),i=e.rootBuilder.binding.gramlot.src.prepareSource(r.getValue(!0).toTytx(),r.builder).getNode(t);if(!i)throw new Error("The Source branch no longer exists");let a=l=>{if(l.resolver)throw new Error("Resolver-backed branches cannot be stored in this trial");l.value instanceof e.builder.source.constructor&&l.value.getNodes().forEach(a)};a(i);let s=new e.builder.source.constructor(null,i.builder);return i.parentBag.popNode(i.label),s.setItem(i.label,i.getValue(!0),{...i.getAttr()},">",!1,!1,"editor",!1,!0,null,i.nodeTag),s.toTytx()}beginClipboard(e,t,r){e.SET(".error","");try{if(!t||t==="pageRoot")throw new Error("Choose a branch below the page root");let o=e.builder.source.getNode(`${he(e)}.${t}`);if(!o)throw new Error("The Source branch no longer exists");let i=this.branchSnapshot(e,t);e.SET(".clipboardDraft",new E({path:t,copy:r,name:o.label,wire:i,parentTag:o.parentNode.nodeTag})),e.SET(".clipboardOpen",!0)}catch(o){e.SET(".error",o.message)}}saveClipboard(e){e.SET(".error","");try{let t=e.GET(".clipboardDraft.name")?.trim();if(!t)throw new Error("Choose a name for the branch");let r=e.GET(".clipboardDraft.path"),o=e.GET(".clipboardDraft.wire"),i=e.GET(".clipboardDraft.copy"),a=e.builder.source.getNode(`${he(e)}.${r}`);if(!i&&(!a||this.branchSnapshot(e,r)!==o))throw new Error("The branch changed; select it again before cutting");let s=e.GET(".clipboard"),l=1;for(;s.getNode(`branch_${l}`);)l++;let u=`branch_${l}`;s.setItem(u,o,{name:t,parentTag:e.GET(".clipboardDraft.parentTag")}),e.SET(".clipboardSelection",u),e.SET(".clipboardVisible",!0),i||(e.SET(".selection",r.slice(0,r.lastIndexOf("."))),a.parentBag.popNode(a.label)),e.SET(".clipboardOpen",!1),e.SET(".fileStatus",`${i?"Copied":"Cut"}: ${t}`)}catch(t){e.SET(".error",t.message)}}pasteBranch(e){e.SET(".error","");try{this.beginPaste(e,e.GET(".clipboardSelection"),e.GET(".selection"))}catch(t){e.SET(".error",t.message)}}beginPaste(e,t,r){let o=t?e.GET(".clipboard").getNode(t):null;if(!o)throw new Error("Choose a saved branch in the clipboard");let i=r?e.builder.source.getNode(`${he(e)}.${r}`):null;if(!i)throw new Error("Choose a destination in the Source tree");let a=e.rootBuilder.binding.gramlot.src.prepareSource(o.getValue(!0),i.builder);Dt(ae(e).GET(".catalogueScope"),a);let s=a.getNodes()[0];i.builder.validateParent(s.nodeTag,i.nodeTag);let l=i.getValue(!0);i.builder.validateChildren(i.nodeTag,[...l instanceof e.builder.source.constructor?l.getNodes().map(w=>w.nodeTag):[],s.nodeTag]);let u={...s.getAttr()},c=i.builder.schema[s.nodeTag]._meta?.gramlot_component?.parameters??{},d=i.builder.schema[o.getAttr("parentTag")]?._meta?.gramlot_component?.childParameters??{};for(let w of Object.keys(d))w in c||delete u[w];s.setAttr(u,!0,!1,!1),e.SET(".insertion",new E({parentPath:r,tag:s.nodeTag,clipboard:a.toTytx()}));let f=nr(i,s.nodeTag),h=Object.entries(f).filter(([w,_])=>_.required&&(u[w]==null||u[w]===""||_.unique));if(!h.length){this.finishPaste(e);return}let p=pl(e,"InsertFields");p.getValue(!0).clear();let m=e.builder.wrapSource(p);m.p(`Paste ${o.getAttr("name")} into ${i.label} [${i.nodeTag}]`,{class:"visual-editor-hint"});let b=m.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});for(let[w,_]of h)this.parameterField(e,b,s.nodeTag,w,_,"insertion",_.default);e.SET(".insertionOpen",!0)}appendBranch(e,t,r){let o=e.builder.source.constructor,i=e.getValue(!0);if(!(i instanceof o)){let a=i;i=new o(null,e.builder),e.builder.promoteNodeValue(e,a,i)}return t.parentBag.popNode(t.label),i.setItem(r,t.getValue(!0),{...t.getAttr()},">",!1,!1,"editor",!1,!0,null,t.nodeTag),i.getNode(r)}finishPaste(e){let t=e.GET(".insertion.parentPath"),r=e.builder.source.getNode(`${he(e)}.${t}`);if(!r)throw new Error("The destination no longer exists");let o=e.rootBuilder.binding.gramlot,i=o.src.prepareSource(e.GET(".insertion.clipboard"),r.builder);Dt(ae(e).GET(".catalogueScope"),i);let a=i.getNodes()[0],s={...a.getAttr()};for(let[b,w]of Object.entries(nr(r,a.nodeTag))){if(!w.required)continue;let _=e.GET(`.insertion.types.${b}`),y=e.GET(`.insertion.parameters.${b}${w.enum?"":_?"."+_:""}`);y!=null&&(s[b]=y),this.validateParameter(r,null,b,w,s[b])}a.setAttr(s,!0,!1,!1);let l=r.getValue(!0),u=a.label,c=1;for(;l instanceof e.builder.source.constructor&&l.getNode(u);)u=`${a.label}_${c++}`;let d=e.builder.source.getNode(he(e)),f=o.src.prepareSource(d.getValue(!0).toTytx(),d.builder),h=f.getNode(t);h.builder.validateParent(a.nodeTag,h.nodeTag);let p=h.getValue(!0);h.builder.validateChildren(h.nodeTag,[...p instanceof e.builder.source.constructor?p.getNodes().map(b=>b.nodeTag):[],a.nodeTag]);let m=this.appendBranch(h,a,u);Dt(ae(e).GET(".catalogueScope"),f),o.src.renderer.validateCandidate(f,{replacingNode:d}),this.appendBranch(r,m,u),e.SET(".insertionOpen",!1),e.SET(".sourceSearch",""),e.SET(".selection",`${t}.${u}`),e.SET(".fileStatus","Branch pasted")}openCode(e){let t=ae(e);t.SET(".codeOpen",!0),t.SET(".editingMode","code")}async codeSave(e){let t=ae(e),r=t.GET(".codeDocument");if(r.getItem("busy")||!r.getItem("writable"))return;let o=r.getItem("content"),i=r.getItem("revision"),a=!1;if(o===r.getItem("saved"))return;let s=new AbortController,l=this.page.src.renderer.onDispose(t,()=>s.abort());r.setItem("busy",!0),r.setItem("status","Saving Page code\u2026");let u=t.value.getNode("layout.center.design"),c=u.value.toTytx();try{let d=await this.page.rpc.call("data","editor_document_save",{key:t.getAttr("codeDocumentKey"),content:o,revision:i},{signal:s.signal});if(s.signal.aborted)return;r.setItem("revision",d.revision),r.setItem("saved",o),a=!0,r.setItem("status","Page code saved"),c!==u.value.toTytx()?r.setItem("status","Page code saved; Source changed meanwhile. Use Preview saved to replace it."):await this.codeLoadPreview(t,s)}catch(d){s.signal.aborted||r.setItem("status",`${a?"Page code saved; preview failed":"Save failed"}: ${d.message}`)}finally{l(),s.signal.aborted||r.setItem("busy",!1)}}async codePreview(e){let t=ae(e),r=t.GET(".codeDocument");if(r.getItem("busy"))return;let o=new AbortController,i=this.page.src.renderer.onDispose(t,()=>o.abort());r.setItem("busy",!0);try{await this.codeLoadPreview(t,o)}catch(a){o.signal.aborted||r.setItem("status",`Preview failed: ${a.message}`)}finally{i(),o.signal.aborted||r.setItem("busy",!1)}}async codeLoadPreview(e,t){let r=e.GET(".codeDocument"),o=e.value.getNode("layout.center.design"),i=o.value.toTytx(),a=await this.page.rpc.call("source","editor_document_preview",{key:e.getAttr("codeDocumentKey"),revision:r.getItem("revision"),data_root:e.GET(".dataRoot")},{signal:t.signal});if(t.signal.aborted)return;if(o.value.toTytx()!==i)throw new Error("Source changed while preparing preview; it was retained");let s=this.page.src.prepareSource(a,o.builder);Dt(e.GET(".catalogueScope"),s),this.page.src.renderer.validateCandidate(s,{replacingNode:o}),e.GET(".assistantRun")&&e.SET(".assistantRun.blocked",!0),e.SET(".selection",null),o.setValue(s,!0,{_text:null},!0),e.SET(".selection","pageRoot"),r.setItem("status",r.getItem("content")===r.getItem("saved")?"Saved Page code \xB7 preview updated":"Preview updated from saved page code; newer draft retained")}newPage(e){e.GET(".assistantRun")&&e.SET(".assistantRun.blocked",!0),e.SET(".selection",null),e.SET(".insertionOpen",!1),e.SET(".error","");let t=e.builder.source.getNode(he(e));t.getValue(!0).clear();let r=e.GET(".dataRoot");if(r)e.SET(r,new E);else for(let o of e.rootBuilder.data.getNodes())o.label!=="__editor"&&e.rootBuilder.data.popNode(o.label);e.builder.wrapSource(t).div({node_label:"pageRoot",...r?{datapath:r}:{}}),e.SET(".filename","page.grmlt"),e.SET(".fileStatus",""),e.SET(".sourceSearch",""),e.SET(".dataSearch",""),e.SET(".selection","pageRoot")}async copySource(e){e.SET(".fileStatus","");try{await e.rootBuilder.binding.gramlot.utl.inout.copyText(this.currentSource(e)),e.SET(".fileStatus","Source copied")}catch(t){e.SET(".fileStatus",`Copy failed: ${t.message}`)}}downloadPage(e){e.rootBuilder.binding.gramlot.utl.inout.saveText(this.currentSource(e),e.GET(".filename"),"application/json")}openUpload(e){e.SET(".uploadOpen",!0)}sourceUploaded(e,{item:t,result:r}){try{this.loadSource(e,{source:r,filename:t.value.getItem("name")}),e.SET(".fileStatus","Source opened"),e.SET(".uploadOpen",!1)}catch(o){throw e.SET(".fileStatus",`Open failed: ${o.message}`),o}}initializeDocument(e){let t=ae(e),r=t.builder.source,o=he(t).split("."),i=`${t.getAttr("visualEditorId")}-document`;t.SET(".modified",!1),r.subscribe(i,{any:a=>{o.every((s,l)=>a.pathlist[l]===s)&&t.SET(".modified",!0)}}),t.rootBuilder.binding.renderer.onDispose(t,()=>r.unsubscribe(i,{any:!0}))}currentSource(e){let t=ae(e);return t.builder.source.getNode(he(t)).getValue(!0).toTytx()}markSaved(e){ae(e).SET(".modified",!1)}loadSource(e,{source:t,filename:r}){let o=ae(e);if(typeof t!="string")throw new TypeError("source must be Source TYTX");if(typeof r!="string"||!r.trim())throw new TypeError("filename must be a non-empty string");let i=o.rootBuilder.binding.gramlot,a=o.builder.source.getNode(he(o)),s=i.src.prepareSource(t,a.builder),l=s.getNodes();if(l.length!==1||l[0].label!=="pageRoot")throw new Error("Expected one pageRoot Source");Dt(o.GET(".catalogueScope"),s),i.src.renderer.validateCandidate(s,{replacingNode:a}),o.GET(".assistantRun")&&o.SET(".assistantRun.blocked",!0),o.SET(".selection",null),a.setValue(s,!0,{_text:null},!0),o.SET(".filename",r),o.SET(".insertionOpen",!1),o.SET(".sourceSearch",""),o.SET(".selection","pageRoot"),this.markSaved(o)}toggleNavigation(e){e.SET(".navigationOpen",e.GET(".navigationOpen")==="close"?!0:"close")}openCatalogue(e){e.SET(`${Qe(e)}.catalogueOpen`,!0)}openProperties(e){this.showProperties(e,{path:e.GET(".selection")})}sourceLabel(e,{item:t}){return{text:`${t.label} [${t.nodeTag}]`}}dropNode(e,t){e.SET(".error","");try{this.applyDrop(e,t)}catch(r){e.SET(".error",r.message)}}insertWidget(e){e.SET(".error","");try{this.applyInsert(e)}catch(t){e.SET(".error",t.message)}}initializeEditorAppearance(e){let t=ae(e),r=e.rootBuilder.binding.renderer.destination.ownerDocument;t.SET(".appearanceProfile","compact"),t.SET(".appearancePalette","joanna"),t.SET(".appearanceMode",r.documentElement.getAttribute("data-theme")||"dark")}applyEditorAppearance(e,{profile:t,palette:r,mode:o}){if(!t||!r||!o)return;if(!Object.hasOwn(Kc,t)||!Object.hasOwn(Jc,r)||!["light","dark"].includes(o))throw new Error("Choose a declared theme, palette and color mode");ae(e).SET(".appearanceCss",Kc[t]+`
|
|
1785
|
-
`+Jc[r]),e.rootBuilder.binding.renderer.destination.ownerDocument.documentElement.setAttribute("data-theme",o)}initializeEditor(e,{dataRoot:t}){let r=e.GET(".catalogueScope");if(Eo(r),Array.isArray(r)){for(let s of r)if(!e.builder.schema[s])throw new Error(`Unknown catalogue tag: ${s}`)}if(e.SET(".editingMode","source"),e.SET(".clipboard",new E),e.SET(".clipboardVisible",!1),e.SET(".clipboardDropEffect","move"),e.SET(".sourceDropEffect","move"),e.SET(".dataRoot",t),e.SET(".filename","page.grmlt"),e.SET(".fileStatus",""),e.SET(".selection","pageRoot"),t)e.GET(t)==null&&e.SET(t,new E);else{let s=Qe(e),l=s.split(".").map(()=>"#parent").join(".");e.builder.source.getNode(he(e)).setAttr({datapath:`${s}.${l}`})}let o=new E,i=new Map([["",o]]),a=(s,l)=>{if(i.has(s))return i.get(s);let u=s.split("."),c=u.pop(),d=u.join("."),f=a(d,b0[d]),h=new E;return f.setItem(c,h,{caption:l}),i.set(s,h),h};for(let[s,l,u]of Ym)u.split(" ").some(c=>e.builder.schema[c]&&xo(r,c,e.builder.schema[c]._meta??{}))&&a(s,l);for(let[s,l]of Object.entries(e.builder.schema).sort(([u],[c])=>u.localeCompare(c))){if(!xo(r,s,l._meta??{})||l._meta?.data_element||l._meta?.subbuilder||l._meta?.container)continue;let u=l._meta?.gramlot_component?"components":"html",c=Ym.find(([f,,h])=>f.startsWith(u+".")&&h.split(" ").includes(s)),d=c?c[0]:`${u}.other`;a(d,c?c[1]:"Other elements").setItem(s,null,{caption:s,tag:s})}e.SET(".catalogue",o)}prepareWidget(e,{item:t,dragValues:r}){if(e.SET(".sourceDropEffect","copy"),!t.attr.tag)return!1;r["app/widget"]={tag:t.attr.tag}}prepareSource(e,{path:t,dragValues:r}){e.SET(".sourceDropEffect","move"),r["app/source"]={path:t}}applyDrop(e,{item:t,path:r,dropValues:o}){if(o["app/clipboard"]){this.beginPaste(e,o["app/clipboard"].path,r);return}if(o["app/source"]){let f=`${he(e)}.${o["app/source"].path}`,h=`${he(e)}.${r}`,p=e.builder.source.getNode(f);if(!p||f===`${he(e)}.pageRoot`)throw new Error("The page root cannot be moved");if(Dt(ae(e).GET(".catalogueScope"),p.parentBag),p.resolver)throw new Error("Resolver-backed Source nodes cannot be moved in this trial");if(f===h||h.startsWith(f+"."))throw new Error("A node cannot be moved into itself");let m=t,b=p.parentBag,w=e.builder.source.constructor;if(p.builder!==m.builder)throw new Error("Nodes cannot cross builder dialects");let _=m.getValue(!0),y=_ instanceof w?_.getNodes().filter(S=>S!==p):[];if(_ instanceof w&&_!==b&&_.getNode(p.label))throw new Error("The target already contains this label");let x=m._getMeta("gramlot_component")?.childParameters??{};for(let[S,k]of Object.entries(x)){let N=p.getAttr(S);if(k.required&&N==null)throw new Error(`The moved node requires ${S}`);if(k.enum&&N!=null&&!k.enum.includes(N))throw new Error(`Invalid ${S}`);if(k.unique&&N!=null&&y.some(O=>O.getAttr(S)===N))throw new Error(`${S} is already in use`)}if(m.builder.validateParent(p.nodeTag,m.nodeTag),m.builder.validateChildren(m.nodeTag,[...y.map(S=>S.nodeTag),p.nodeTag]),_===b)b.move(b.getNodes().indexOf(p),y.length);else{let S=_ instanceof w?_:new w(null,m.builder);_ instanceof w||m.builder.promoteNodeValue(m,_,S);let k={label:p.label,tag:p.nodeTag,value:p.getValue(!0),attrs:{...p.getAttr()}};b.popNode(k.label),S.setItem(k.label,k.value,k.attrs,S.getNodes().length,!1,!1,"editor",!1,!0,null,k.tag)}e.SET(".selection",`${r}.${p.label}`);return}let i=o["app/widget"].tag;this.validateCatalogueTag(e,i),t.builder.validateParent(i,t.nodeTag);let a=t.getValue(!0);t.builder.validateChildren(t.nodeTag,[...a instanceof e.builder.source.constructor?a.getNodes().map(f=>f.nodeTag):[],i]);let s=nr(t,i),l=Object.entries(s).filter(([,f])=>f.required);if(e.SET(".insertion",new E),e.SET(".insertion.parentPath",r),e.SET(".insertion.tag",i),!l.length){this.applyInsert(e);return}let u=pl(e,"InsertFields");u.getValue(!0).clear();let c=e.builder.wrapSource(u);c.p(`Insert ${i} into ${t.label} [${t.nodeTag}]`,{class:"visual-editor-hint"});let d=c.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});for(let[f,h]of l)this.parameterField(e,d,i,f,h,"insertion",h.default);e.SET(".insertionOpen",!0)}showProperties(e,{path:t}){let r=pl(e,"EditorFields");if(r.getValue(!0).clear(),e.SET(".propertyError",""),e.SET(".properties",new E),!t){e.SET(".propertiesOpen",!1);return}let o=e.builder.source.getNode(`${he(e)}.${t}`);if(!o){e.SET(".propertiesOpen",!1);return}let i=o.parentNode,a=nr(i,o.nodeTag,o);e.SET(".properties.path",t),this.attributeRows(e,o),e.SET(".propertiesTitle",`${o.label} [${o.nodeTag}]`),e.SET(".propertiesHeight",`${Math.min(300,Math.max(180,80+Math.ceil(Object.keys(a).filter(f=>ed(f,new Set)==="general").length/2)*38))}px`);let s=e.builder.wrapSource(r);t!=="pageRoot"&&s.p(t,{class:"visual-editor-destination"});let l=new Set(Object.keys(i._getMeta("gramlot_component")?.childParameters??{})),u=new Map(Qc.map(([f])=>[f,[]]));for(let f of Object.entries(a))u.get(ed(f[0],l)).push(f);e.SET(".parameterTab",Qc.find(([f])=>u.get(f).length)[0]);let c=s.tabContainer({selectedPage:`^${Qe(e)}.parameterTab`,class:"visual-parameter-tabs",tabMode:"underline",height:"100%",min_height:0,flex:1});for(let[f,h]of Qc){if(!u.get(f).length)continue;let p=c.contentPane({pageName:f,title:h,overflow:"auto",padding:"4px",min_height:0,...f==="styles"?{nodeId:ae(e).getAttr("visualEditorId")+"StyleAttributes"}:{}});if(f==="styles"){this.attributeFields(e,p,o,"styles");continue}f==="container"&&p.p(`Child parameters of ${i.nodeTag}`,{class:"visual-editor-hint"}),f==="behaviour"&&Object.hasOwn(a,"action")&&p.p("action: use a named Logic method, for example openCatalogue.",{class:"visual-editor-hint"}),f==="behaviour"&&o.nodeTag==="borderContainer"&&p.p("persist remembers splitter sizes and requires a stable container id.",{class:"visual-editor-hint"});let m=p.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});f==="general"&&o._getMeta("gramlot_component")?.labelbox&&this.labelboxFields(e,m,o,a);let b,w=([,_])=>{let y=Array.isArray(_.dtype)?_.dtype:[_.dtype];return!_.enum&&!y.some(x=>ml.includes(x))?2:_.dtype==="B"?1:0};for(let[_,y]of[...u.get(f)].sort((x,S)=>w(x)-w(S))){if(o._getMeta("gramlot_component")?.labelbox&&/^(lbl|box)(_|$)/.test(_))continue;let x=m;if(f==="validation"&&/(_if|_error|_warning|_iswarning)$/.test(_)){if(!b){let k=p.details({class:"visual-validation-advanced"});k.summary("Conditions and messages"),b=k.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"})}x=b}let S=_==="_text"?o.getValue(!0):o.getAttr(_);this.parameterField(e,x,o.nodeTag,_,y,"properties",S??y.default)}}let d=c.contentPane({nodeId:ae(e).getAttr("visualEditorId")+"MoreAttributes",pageName:"attributes",title:"More attributes",overflow:"auto",padding:"4px",min_height:0});this.attributeFields(e,d,o),e.SET(".propertiesOpen",!0)}attributeRows(e,t){let r=new E;for(let[o,i]of Object.entries(t.getAttr())){if(o==="_meta")continue;let a=Xc(i),s=a?hl(i,a):"[non-scalar value]";r.setItem(`r${r.length}`,new E({name:o,type:a??"readonly",text:s,original:s}))}e.SET(".properties.attributeRows",r),e.SET(".properties.attributeDraft",new E({name:"",type:"string",text:""})),e.SET(".properties.attributeDraftHidden",!0)}attributeFields(e,t,r,o="attributes"){let i=e.GET(".properties.path"),a=`${Qe(e)}.properties`,s=e.rootBuilder.binding.gramlot.src.renderer,l=new Set(Object.keys(r.parentNode._getMeta("gramlot_component")?.childParameters??{})),u=t.div({class:"visual-editor-attribute-list","aria-label":o==="styles"?"Style attributes":"Node attributes"}),c=u.div({class:"visual-editor-attribute-row visual-editor-attribute-heading"});c.span("Attribute",{class:"visual-editor-attribute-name"});let d=c.div({class:"visual-editor-attribute-value"});d.span("Value"),d.button("+",{action:"beginAttribute",editingPath:i,"aria-label":o==="styles"?"Add style attribute":"Add attribute",title:"Add attribute",class:"visual-editor-attribute-command"});for(let b of e.GET(".properties.attributeRows").getNodes()){let w=b.value.getItem("name"),_=b.value.getItem("type"),y=b.label;if(o==="styles"&&ed(w,l)!=="styles"&&!s._isStyleContribution(w))continue;let x=_!=="readonly",S=u.div({class:"visual-editor-attribute-row"});S.span(w,{class:"visual-editor-attribute-name",title:w});let k=S.div({class:"visual-editor-attribute-value"});k.input({value:`^${a}.attributeRows.${y}.text`,disabled:!x,"aria-label":`${w} attribute value`,title:x?_:"Non-scalar values are read-only"}),k.button("\xD7",{action:"removeAttribute",attributeRow:y,editingPath:i,disabled:!x,"aria-label":`Remove ${w} attribute`,title:`Remove ${w}`,class:"visual-editor-attribute-command"}),x&&o==="attributes"&&S.dataController({func:"changeAttribute",value:`^${a}.attributeRows.${y}.text`,attributeRow:y,editingPath:i,_userChanges:!0})}let f=u.div({class:"visual-editor-attribute-row",hidden:`^${a}.attributeDraftHidden`,connect_onkeydown:"attributeDraftKey"});f.div({class:"visual-editor-attribute-name"}).input({value:`^${a}.attributeDraft.name`,live:!0,"aria-label":"New attribute name",placeholder:"Attribute name"});let p=f.div({class:"visual-editor-attribute-value"});p.input({value:`^${a}.attributeDraft.text`,live:!0,"aria-label":"New attribute value",placeholder:"Value"});let m=p.select({value:`^${a}.attributeDraft.type`,"aria-label":"New attribute type"});for(let b of Wm)m.option(b,{value:b});p.button("\u2713",{action:"addAttribute",editingPath:i,"aria-label":"Apply new attribute",title:"Apply (Enter)",class:"visual-editor-attribute-command"}),p.button("\xD7",{action:"cancelAttribute","aria-label":"Cancel new attribute",title:"Cancel (Escape)",class:"visual-editor-attribute-command"})}beginAttribute(e,{editingPath:t}){let r=ae(e);t===r.GET(".selection")&&(r.SET(".properties.attributeDraft",new E({name:"",type:"string",text:""})),r.SET(".properties.attributeDraftHidden",!1),r.SET(".propertyError",""))}cancelAttribute(e){ae(e).SET(".properties.attributeDraftHidden",!0)}attributeDraftKey(e,t){if(t.isComposing||!["Enter","Escape"].includes(t.key))return;t.preventDefault(),t.stopPropagation();let r=ae(e);t.key==="Escape"?this.cancelAttribute(r):this.addAttribute(r,{editingPath:r.GET(".properties.path")})}addAttribute(e,{editingPath:t}){let r=ae(e);if(t===r.GET(".selection")){r.SET(".propertyError","");try{let o=r.GET(".properties.attributeDraft"),i=o.getItem("name");if(!i||!/^[^\s"'<>/=]+$/.test(i))throw new Error("Enter a valid attribute name.");if(["_meta","__proto__","constructor","prototype"].includes(i))throw new Error("Unsupported attribute name.");let a=r.builder.source.getNode(`${he(r)}.${t}`);if(!a)throw new Error("The selected Source node no longer exists");if(Object.hasOwn(a.getAttr(),i))throw new Error(`Duplicate attribute: ${i}`);let s=Zc(o.getItem("type"),String(o.getItem("text")??""));this.writeAttribute(r,a,t,i,s,!1)}catch(o){r.SET(".propertyError",o.message)}}}changeAttribute(e,{attributeRow:t,editingPath:r,value:o}){this.editAttribute(e,{attributeRow:t,editingPath:r,value:o,remove:!1})}removeAttribute(e,{attributeRow:t,editingPath:r}){this.editAttribute(e,{attributeRow:t,editingPath:r,remove:!0})}editAttribute(e,{attributeRow:t,editingPath:r,value:o,remove:i}){let a=ae(e);if(r===a.GET(".selection")){a.SET(".propertyError","");try{let s=a.GET(".properties.attributeRows").getItem(t);if(!s||s.getItem("type")==="readonly")throw new Error("This attribute is not editable");let l=s.getItem("name");if(["_meta","__proto__","constructor","prototype"].includes(l))throw new Error("Unsupported attribute name.");let u=a.builder.source.getNode(`${he(a)}.${r}`);if(!u)throw new Error("The selected Source node no longer exists");let c=u.getAttr(),d=Xc(c[l]);if(!Object.hasOwn(c,l)||d!==s.getItem("type")||hl(c[l],d)!==s.getItem("original"))throw new Error("Attribute changed; select the node again before editing.");let f=i?null:Zc(d,String(o??""));this.writeAttribute(a,u,r,l,f,i,s)}catch(s){a.SET(".propertyError",s.message)}}}writeAttribute(e,t,r,o,i,a,s=null){let l={...t.getAttr()};a?delete l[o]:l[o]=i;let u=nr(t.parentNode,t.nodeTag,t);u[o]&&this.validateParameter(t.parentNode,t,o,u[o],a?null:i);let c=e.builder.source.getNode(he(e)),d=e.rootBuilder.binding.gramlot,f=d.src.prepareSource(c.getValue(!0).toTytx(),c.builder);if(f.getNode(r).setAttr(l,!0,!1,!1),Dt(e.GET(".catalogueScope"),f),d.src.renderer.validateCandidate(f,{replacingNode:c}),t.setAttr(l,!0,!1,!1),s&&!a){let h=hl(i,s.getItem("type"));s.setItem("original",h),s.setItem("text",h);let p=e.GET(`.properties.types.${o}`);u[o]?.enum?e.SET(`.properties.parameters.${o}`,i):p&&e.SET(`.properties.parameters.${o}.${p}`,i)}else{let h=e.GET(".parameterTab")==="styles"?"styles":"attributes";this.showProperties(e,{path:r}),e.SET(".parameterTab",h)}}toggleLabelboxAttributes(e,{prefix:t}){e.SET(`.properties.${t}Hidden`,!e.GET(`.properties.${t}Hidden`))}labelboxFields(e,t,r,o){for(let i of["lbl","box"]){let a=i==="lbl"?"Label":"Box",s=t.div({class:"visual-labelbox-section",grid_column:"1 / -1"}),l=s.div({class:"visual-labelbox-heading"});i==="lbl"?this.parameterField(e,l,r.nodeTag,"lbl",o.lbl,"properties",r.getAttr("lbl")):l.span(a,{class:"visual-labelbox-title"}),l.button({iconSrc:Ge.properties,title:`Edit ${a.toLowerCase()} attributes`,"aria-label":`Edit ${a.toLowerCase()} attributes`,class:"button--quiet",action:"toggleLabelboxAttributes",prefix:i});let u=Object.entries(o).filter(([f])=>f.startsWith(i+"_"));e.SET(`.properties.${i}Hidden`,!0),e.SET(`.properties.${i}Attribute`,"");let c=s.div({class:"visual-labelbox-attribute",hidden:`^${Qe(e)}.properties.${i}Hidden`}),d=c.select({"aria-label":`${a} attribute`,value:`^${Qe(e)}.properties.${i}Attribute`});d.option("Which attribute?",{value:""});for(let[f]of u)d.option(f.slice(i.length+1),{value:f});c.div({node_label:"attributeValue"}).span(""),c.dataController({func:"renderLabelboxAttribute",_init:!0,parameterName:`^${Qe(e)}.properties.${i}Attribute`,editingPath:e.GET(".properties.path")})}}renderLabelboxAttribute(e,{parameterName:t,editingPath:r}){let o=e.parentBag.getNode("attributeValue");if(o.getValue(!0).clear(),!t||r!==e.GET(".selection"))return;let i=e.builder.source.getNode(`${he(e)}.${r}`),a=nr(i.parentNode,i.nodeTag,i)[t];this.parameterField(e,e.builder.wrapSource(o),i.nodeTag,t,a,"properties",i.getAttr(t)??a.default,!0)}parameterField(e,t,r,o,i,a,s,l=!1){let u=o==="lbl"?"Label":o==="_text"&&e.builder.schema[r]._meta?.gramlot_component?.command?"caption":o==="_text"?"Text":o,c=`${Qe(e)}.${a}.parameters.${o}`;if(i.enum){e.SET(c,s??"");let b=t.select({lbl:l?null:u,lbl_position:"TL",value:`^${c}`,"aria-label":o});b.option("",{value:""});for(let w of i.enum)b.option(String(w),{value:w});a==="properties"&&t.dataController({func:"changeProperty",value:`^${c}`,_userChanges:!0,parameterName:o,editingPath:e.GET(".properties.path")});return}let d=Array.isArray(i.dtype)?i.dtype:i.dtype?[i.dtype]:[],f=d.filter(b=>ml.includes(b));if(!f.length){t.p(`${u}: no editor is available for this declared type`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}let h="";if(s==null?h=f.length===1?f[0]:"":typeof s=="boolean"&&f.includes("B")?h="B":typeof s=="string"&&f.includes("T")?h="T":typeof s=="number"?h=f.find(b=>["L","R","N"].includes(b))??"":s instanceof Date?h=f.find(b=>["D","H"].includes(b))??"":f.length===1&&f[0]==="N"&&(h="N"),s!=null&&!h){t.p(`${u}: the current value is not editable with these scalar types`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}e.SET(`${Qe(e)}.${a}.types.${o}`,h);for(let b of f)e.SET(`${c}.${b}`,b===h?s??null:null);let p=!l&&(d.length>1||/^(tooltip|_text|action|placeholder|value)$|(_error|_warning|_if)$/.test(o)),m=t.div({class:"visual-parameter-field",grid_column:p?"1 / -1":"auto",grid_template_columns:d.length>1?"minmax(100px, 1fr) minmax(0, 2fr)":"minmax(0, 1fr)",align_items:"start"});if(d.length>1){let b=m.select({lbl:`${u} type`,lbl_position:"TL",value:`^${Qe(e)}.${a}.types.${o}`,"aria-label":`${o} type`});b.option("Not set",{value:""});for(let w of d)b.option(ml.includes(w)?w:`${w} (unavailable)`,{value:w,disabled:!ml.includes(w)});a==="properties"&&m.dataController({func:"changePropertyType",type:`^${Qe(e)}.${a}.types.${o}`,_userChanges:!0,parameterName:o,editingPath:e.GET(".properties.path")})}m.div({node_label:"input"}).span(""),m.dataController({func:"renderParameterInput",_init:!0,type:`^${Qe(e)}.${a}.types.${o}`,parameterName:o,parameterLabel:u,scope:a,compact:l,multiple:d.length>1})}renderParameterInput(e,{type:t,parameterName:r,parameterLabel:o,scope:i,multiple:a,compact:s}){let l=e.parentBag.getNode("input");if(l.getValue(!0).clear(),!t)return;let u=e.builder.wrapSource(l),c=a?`${o} (${t})`:o,d=`^${Qe(e)}.${i}.parameters.${r}.${t}`,f={lbl:s?null:c,lbl_position:"TL",value:d,"aria-label":c};if(t==="B")u.checkbox(f);else if(["L","R","N"].includes(t))u.numberTextBox({...f,dtype:t});else if(t==="D")u.dateTextBox(f);else if(t==="H")u.timeTextBox(f);else if(t==="T"&&/^(lbl|box)_color$/.test(r))u.colorpicker(f);else if(t==="T")u.textbox(f);else throw new Error(`No parameter editor for ${t}`);i==="properties"&&u.dataController({func:"changeProperty",value:d,_userChanges:!0,parameterName:r,editingPath:e.GET(".properties.path")})}changePropertyType(e,{type:t,parameterName:r,editingPath:o}){this.changeProperty(e,{parameterName:r,editingPath:o,value:t?e.GET(`.properties.parameters.${r}.${t}`):null})}changeProperty(e,{value:t,parameterName:r,editingPath:o}){if(o===e.GET(".selection")){e.SET(".propertyError","");try{let i=e.builder.source.getNode(`${he(e)}.${o}`);if(!i)throw new Error("The selected Source node no longer exists");if(r!=="_text"&&Object.is(i.getAttr(r),t))return;let s=nr(i.parentNode,i.nodeTag,i)[r];if(!s)throw new Error(`Unknown parameter: ${r}`);if(this.validateParameter(i.parentNode,i,r,s,t),r==="_text")i.setValue(t??"");else{let l={...i.getAttr()};t==null||t===""?delete l[r]:l[r]=t,i.setAttr(l,!0,!1,!1)}this.attributeRows(e,i);for(let[l,u]of[["MoreAttributes","attributes"],["StyleAttributes","styles"]]){let c=pl(e,l);c.getValue(!0).clear(),this.attributeFields(e,e.builder.wrapSource(c),i,u)}}catch(i){e.SET(".propertyError",i.message)}}}validateParameter(e,t,r,o,i){let a=i==null||i==="";if(o.required&&a)throw new Error(`Choose ${r}`);if(!a&&o.enum&&!o.enum.includes(i))throw new Error(`Invalid ${r}`);let s=e.getValue(!0);if(!a&&o.unique&&s instanceof e.builder.source.constructor&&s.getNodes().some(l=>l!==t&&l.getAttr(r)===i))throw new Error(`${r} is already in use`)}validateCatalogueTag(e,t){let r=ae(e).GET(".catalogueScope");if(!xo(r,t,e.builder.schema[t]?._meta??{}))throw new Error(`Tag ${t} is outside the editor catalogue`)}applyInsert(e){if(e.GET(".insertion.clipboard")){this.finishPaste(e);return}let t=e.GET(".insertion.parentPath"),r=e.builder.source.getNode(`${he(e)}.${t}`);if(!r)throw new Error("The target Source node is no longer available");let o=e.GET(".insertion.tag");this.validateCatalogueTag(e,o);let i={};for(let[s,l]of Object.entries(nr(r,o)).filter(([,u])=>u.required)){let u=e.GET(`.insertion.types.${s}`),c=e.GET(`.insertion.parameters.${s}${l.enum?"":u?"."+u:""}`);this.validateParameter(r,null,s,l,c),i[s]=c}let a=r.builder.commandOnNode(r,o,null,i);e.SET(".insertionOpen",!1),e.SET(".selection",`${t}.${a.label}`)}};export{E as Bag,xt as BagNode,Lc as BrowserCameraProvider,yp as ChoiceGroup,Oo as CommandRegistry,Tr as ComponentCollection,Fi as DeviceHandler,Gi as DirectoryResolver,Li as DomHandler,Ks as Exposed,jm as FieldState,Wi as FileSystemController,wn as FileSystemLogic,yo as FramePage,Ui as Gramlot,Oe as GramlotBuilder,un as GramlotHtmlRenderer,Mi as GramlotRenderer,Ai as GramlotSvgRenderer,Ke as Handler,Ro as HttpTransport,rl as IdeLogic,ji as InOut,Js as IndexLogic,Hi as IndexPage,Oc as Labelbox,Io as MobileEnvironment,_p as NativeControl,Ic as NavigationResolver,zi as Page,bc as PageBootstrap,bi as References,nn as RpcError,wi as RpcHandler,lr as ServerAdapter,Pi as SourceHandler,il as SourceImport,ta as SourcePicker,Yi as TreeStore,nl as TreeStoreLogic,Rr as TreeStoreResolver,vo as UploadTarget,qi as UtilitiesHandler,ol as VisualEditor,td as VisualEditorLogic,zc as chatCompleted,Gc as chatPickAttachments,Wc as chatRemoveAttachment,qc as chatRender,Yc as chatRenderAttachments,Vc as chatReset,Hc as chatResize,Uc as chatSend,Qs as codeMirrorWithOptions,Vm as collectionBuildId,s0 as createDOMPurify,Lt as createDecimal,Zu as defineCollection,Ar as defineComponent,gm as fileSystemTree,F as fromTytx,Ch as fromTytxIter,l0 as loadMarkdown,_c as mountIndexPage,Ds as parseDateExpression,ie as sourceTarget,L as toTytx,h0 as verifyCollectionArtifact,ae as visualEditorScope};
|
|
1784
|
+
`};function se(n){for(let e=n;e;e=e.parentNode)if(e.getAttr("visualEditorId"))return e;throw new Error("Operation requires a VisualEditor Source ancestor")}function he(n){return se(n).fullpath.split(".").slice(1).join(".")+".layout.center.design"}function Qe(n){return se(n).absDatapath(".")}function gl(n,e){return n.rootBuilder.binding.nodeIds.get(se(n).getAttr("visualEditorId")+e)}var Qm=[["html.structure","Structure","main header footer nav section article aside div address search"],["html.text","Text and headings","h1 h2 h3 h4 h5 h6 hgroup p span a b strong i em small s u mark abbr cite code pre blockquote q br wbr hr time data dfn kbd samp var bdi bdo ruby rt rp sub sup ins del_"],["html.lists","Lists","ul ol li dl dt dd"],["html.forms","Forms","form input textarea select selectedcontent option optgroup datalist label fieldset legend output progress meter html_button"],["html.tables","Tables","table caption colgroup col thead tbody tfoot tr th td"],["html.media","Media and embedded content","img picture source audio video track canvas iframe embed object param map area"],["html.interaction","Disclosure and menus","details summary html_dialog html_menu"],["html.document","Document and metadata","html head body title base meta link style script noscript template slot"],["components.layout.containers","Containers","borderContainer contentPane framePane stackContainer tabContainer"],["components.layout.windows","Windows","dialog floatingPane"],["components.layout.composition","Composition","formlet groupBox trayPane transformPane"],["components.inputs.text","Text","textbox textBoxArea passwordbox"],["components.inputs.choices","Choices","checkbox radioButton radioButtonText checkBoxText filteringSelect comboBox callbackSelect dbSelect dbComboBox"],["components.inputs.numbers","Numbers and colors","numberTextBox horizontalSlider verticalSlider colorpicker"],["components.inputs.dates","Dates and times","dateTextBox timeTextBox dateCalendar"],["components.commands","Buttons and menus","button toggleButton dropDownButton menu menuline spacer"],["components.data","Trees and grids","tree grid searchBox"],["components.editors","Editors and previews","codeMirror htmlEditor htmlPreview markdownEditor markdownPreview typstPreview"]],I0={html:"HTML",components:"Gramlot","components.layout":"Layout","components.inputs":"Inputs"},_l=Object.fromEntries(["class","style","width","height","padding","margin","color","background"].map(n=>[n,{dtype:"T",nullable:!0}])),eg=Object.fromEntries(["lbl_","box_"].flatMap(n=>Object.entries(_l).map(([e,t])=>[n+e,t]))),ed=[["general","General"],["behaviour","Behaviour"],["validation","Validation"],["styles","Styles"],["container","Container"]],bl=["T","B","L","R","N","D","H"];function td(n,e){return/^(lbl|box)(_|$)/.test(n)?"general":e.has(n)?"container":n.startsWith("validate_")?"validation":Object.hasOwn(_l,n)||/^(icon|tab)/.test(n)||["design","labelPosition","switch_color","orientation"].includes(n)?"styles":/^(on[A-Z]|get[A-Z]|drag|drop)/.test(n)||["action","command","disabled","readonly","live","beforeClose","open","collapsed","closable","movable","resizable","collapsible","maximizable","maximized","persist","autoCollapse","openOnClick"].includes(n)?"behaviour":"general"}var or=(n,e,t=null)=>{let r=n.builder.schema[e];if(!r)throw new Error(`Unknown widget: ${e}`);let o=r._meta?.gramlot_component;return{...(!t||!(t.getValue(!0)instanceof t.builder.source.constructor))&&(!o||o.command&&!Object.hasOwn(o.parameters,"caption"))?{_text:{dtype:"T",nullable:!0}}:{},..._l,...o?.labelbox?eg:{},...o?.parameters??{},...n._getMeta("gramlot_component")?.childParameters??{}}},wl=new WeakMap,ra=new WeakMap,rd=class{chatRender(e,t){return Uc(this.page,e,t)}chatCompleted(e,t){Hc(this.page,e,t),e.GET(`${Qe(e)}.assistant.active`)&&e.SET(".pending",!0)}chatReset(e){return zc(this.page,e)}chatResize(e){return Gc(this.page,e)}chatPickAttachments(e){return Wc(this.page,e)}chatRenderAttachments(e,t){return Xc(this.page,e,t)}chatRemoveAttachment(e){return Yc(this.page,e)}chatSend(e){if(e.GET(".pending")||!e.GET(".conversation.ready")||!e.GET(".draft")?.trim())return;let t=se(e),r=t.GET(".editingMode"),o=e.builder.source.getNode(he(e)).value.toTytx(),i=r==="code"?t.GET(".codeDocument.content"):o;if(r==="code"&&!t.GET(".codeDocument.writable")){e.SET(".error","Page code editing is disabled by the host");return}let a=(t.GET(".assistantRun.run")??0)+1,s=t.GET(".catalogueScope"),l={commonParameters:_l,labelboxParameters:eg,widgets:{}};for(let[u,c]of Object.entries(e.builder.schema)){if(!xo(s,u,c._meta??{})||c._meta?.data_element||c._meta?.subbuilder||c._meta?.container)continue;let d=c._meta?.gramlot_component;l.widgets[u]={parameters:d?.parameters??{},labelbox:!!d?.labelbox,childParameters:d?.childParameters??{}}}return t.SET(".assistantRun",new E({run:a,mode:r,next:0,expected:i,blocked:!1})),t.SET(".assistantStatus","Waiting for editing instructions\u2026"),t.SET(".assistant.context",new E({run:a,mode:r,language:t.GET(".codeDocument.language")??null,codeWritable:t.GET(".codeDocument.writable")===!0,code:r==="code"?i:null,source:o,selected:t.GET(".selection"),schema:JSON.stringify(l)})),Vc(this.page,e)}assistantState(e,{active:t}){if(t===!1){e.SET(`${Qe(e)}.chat.pending`,!1);let r=se(e);r.GET(".assistantRun.next")===0&&r.SET(".assistantStatus","")}}assistantApply(e,{operations:t}){if(!(t instanceof E))return;let r=se(e);for(let o of t.getNodes()){if(o.attr.run!==r.GET(".assistantRun.run")||o.attr.index<r.GET(".assistantRun.next"))continue;let i=e.builder.source.getNode(he(e)).value,a=r.GET(".assistantRun.mode"),s=a==="code"?r.GET(".codeDocument.content"):i.toTytx(),l=!1,u=!1,c="";try{if(r.GET(".assistantRun.blocked"))throw u=!0,new Error("The document was replaced during editing");if(o.attr.index!==r.GET(".assistantRun.next"))throw u=!0,new Error("Editing sequence is incomplete");if(s!==r.GET(".assistantRun.expected"))throw u=!0,new Error("Source changed during the request. Remaining edits stopped; send a new instruction.");let d=JSON.parse(o.value);if(a==="code"){if(d.operation!=="replace_code"||typeof d.content!="string")throw new Error("Expected a Page code draft operation");if(!r.GET(".codeDocument.writable")||r.GET(".codeDocument.busy"))throw new Error("Page code draft is not editable now");r.SET(".codeDocument.content",d.content),r.SET(".codeDocument.status","AI draft \xB7 Save to apply"),r.SET(".codeOpen",!0)}else this.applySourceEdit(r,d);l=!0,r.SET(".assistantRun.expected",a==="code"?r.GET(".codeDocument.content"):i.toTytx()),r.SET(".assistantStatus",`Applied ${o.attr.index+1}: ${a==="code"?"Page code draft":d.operation+" "+d.path}`)}catch(d){c=d.message,(a==="code"?r.GET(".codeDocument.content"):i.toTytx())!==s&&(u=!0),r.SET(".assistantRun.blocked",u),r.SET(".assistantStatus",`${u?"Editing stopped":"Rejected"}: ${c}`)}r.SET(".assistantRun.next",o.attr.index+1),r.SET(".assistant.ack",new E({run:o.attr.run,index:o.attr.index,applied:l,stop:u,error:c,mode:a,code:a==="code"?r.GET(".codeDocument.content"):null,source:i.toTytx(),selected:r.GET(".selection")}))}}applySourceEdit(e,t){let{operation:r,path:o,parent:i,tag:a,label:s,attributes:l={},text:u}=t,c=y=>typeof y=="string"&&/^pageRoot(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(y);if(!c(o)||r==="move"&&!c(i))throw new Error(`Use dot-separated paths inside pageRoot: ${JSON.stringify(o)}`);if(!["insert","update","remove","move"].includes(r))throw new Error("Unknown Source editing operation");if(["remove","move"].includes(r)&&o==="pageRoot")throw new Error("The page root is protected");if(r==="insert"&&(typeof s!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)))throw new Error("Choose an explicit node label");if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Expected scalar attributes");for(let[y,x]of Object.entries(l))if(y.startsWith("_")||/^(connect_|on[A-Z]|script$|formula$|action$|func$|remote_)/.test(y)||["constructor","prototype"].includes(y)||x!==null&&typeof x=="object"||typeof x=="string"&&(x.startsWith("==")||x.includes(":=")))throw new Error(`Unsupported generated attribute: ${y}`);if(u!==void 0&&typeof u!="string")throw new Error("Text must be literal text");let d=e.builder.source.getNode(he(e)),f=e.rootBuilder.binding.gramlot,h=f.src.prepareSource(d.value.toTytx(),d.builder),p=h.getNode(o);if(!p)throw new Error("The Source target no longer exists");let m=p;if(r==="insert"){if(!e.builder.schema[a]||["script","style","iframe","object","embed"].includes(a)||e.builder.schema[a]._meta?.data_element)throw new Error("Choose a visual widget from the catalogue");if(p.value instanceof h.constructor&&p.value.getNode(s))throw new Error("This node label is already in use");m=p.builder.commandOnNode(p,a,u??null,{...l,node_label:s})}else if(r==="update"){if(u!==void 0&&p.value instanceof h.constructor)throw new Error("Text cannot replace a populated container");let y={...p.getAttr()};for(let[x,D]of Object.entries(l))D===null?delete y[x]:y[x]=D;p.setAttr(y,!0,!1,!1),u!==void 0&&p.setValue(u)}else if(r==="remove")p.parentBag.popNode(p.label);else{if(Object.keys(l).length||u!==void 0)throw new Error("Move and property edits must be separate operations");if(i===o||i.startsWith(o+"."))throw new Error("Cannot move a node into itself");let y=h.getNode(i);if(!y)throw new Error("The destination no longer exists");if(y.value instanceof h.constructor&&y.value.getNode(p.label))throw new Error("The destination already contains this label");m=this.appendBranch(y,p,p.label)}let b=y=>{if(y.value instanceof h.constructor){y.builder.validateChildren(y.nodeTag,y.value.getNodes().map(x=>x.nodeTag));for(let x of y.value.getNodes()){for(let[D,k]of Object.entries(or(y,x.nodeTag,x)))this.validateParameter(y,x,D,k,x.getAttr(D));b(x)}}};h.getNodes().forEach(b),Dt(se(e).GET(".catalogueScope"),h),f.src.renderer.validateCandidate(h,{replacingNode:d});let w=e.builder.source.getNode(`${he(e)}.${o}`),_=o;r==="insert"?(this.appendBranch(w,m,s),_=`${o}.${s}`):r==="update"?(w.setAttr({...m.getAttr()},!0,!1,!1),u!==void 0&&w.setValue(u)):r==="remove"?(_=o.slice(0,o.lastIndexOf(".")),w.parentBag.popNode(w.label)):(this.applyDrop(e,{item:e.builder.source.getNode(`${he(e)}.${i}`),path:i,dropValues:{"app/source":{path:o}}}),_=`${i}.${w.label}`),e.SET(".sourceSearch",""),e.SET(".selection",_)}initializeCanvasSelection(e){let t=e.rootBuilder.binding.renderer,r=e.builder.source.getNode(he(e)),o=se(e),i=o.GET(".canvasCss");i!=null&&this.applyCanvasCss(o,i);let a=wl.get(r);a?.dispose();let s=new ta({renderer:t,root:r,...ra.has(r)?{canvas:ra.get(r).body}:{},onSelect:l=>{e.SET(".sourceSearch",""),e.SET(".selection",l.fullpath.slice(r.fullpath.length+1))}});wl.set(r,s),a||t.onDispose(r.parentNode,()=>{wl.delete(r),ra.delete(r)}),this.highlightSelection(e)}applyCanvasCss(e,t){if(!Array.isArray(t)||t.some(a=>typeof a!="string"))throw new TypeError("canvas CSS must be a list of CSS texts");let r=se(e),o=r.builder.source.getNode(he(r)),i=ra.get(o);i||(i=new pl({app:r.rootBuilder.binding.gramlot,editor:r,design:o}),ra.set(o,i)),i.setCss(t)}setCanvasCss(e,t){let r=se(e);this.applyCanvasCss(r,t),r.SET(".canvasCss",t),this.initializeCanvasSelection(r)}highlightSelection(e){let t=e.builder.source.getNode(he(e)),r=e.GET(".selection");wl.get(t)?.select(r?t.staticValue.getNode(r):null)}clipboardShortcut(e,t){if(t.defaultPrevented||t.repeat||e.GET(".clipboardOpen")||e.GET(".insertionOpen")||e.GET(".uploadOpen")||t.composedPath().some(i=>i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)))return;let r=t.key.toLowerCase(),o=r==="f8"?"cutBranch":r==="f9"?"pasteBranch":null;!o||t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),this[o](e))}clipboardModifiers(e,t){e.SET(".clipboardDropEffect",t.altKey?"copy":"move")}cutBranch(e){this.beginClipboard(e,e.GET(".selection"),!1)}copyBranch(e){this.beginClipboard(e,e.GET(".selection"),!0)}dropClipboard(e,{dropValues:t,dropEffect:r}){this.beginClipboard(e,t["app/source"].path,r==="copy")}prepareClipboard(e,{path:t,dragValues:r}){e.SET(".sourceDropEffect","copy"),r["app/clipboard"]={path:t}}branchSnapshot(e,t){let r=e.builder.source.getNode(he(e)),i=e.rootBuilder.binding.gramlot.src.prepareSource(r.getValue(!0).toTytx(),r.builder).getNode(t);if(!i)throw new Error("The Source branch no longer exists");let a=l=>{if(l.resolver)throw new Error("Resolver-backed branches cannot be stored in this trial");l.value instanceof e.builder.source.constructor&&l.value.getNodes().forEach(a)};a(i);let s=new e.builder.source.constructor(null,i.builder);return i.parentBag.popNode(i.label),s.setItem(i.label,i.getValue(!0),{...i.getAttr()},">",!1,!1,"editor",!1,!0,null,i.nodeTag),s.toTytx()}beginClipboard(e,t,r){e.SET(".error","");try{if(!t||t==="pageRoot")throw new Error("Choose a branch below the page root");let o=e.builder.source.getNode(`${he(e)}.${t}`);if(!o)throw new Error("The Source branch no longer exists");let i=this.branchSnapshot(e,t);e.SET(".clipboardDraft",new E({path:t,copy:r,name:o.label,wire:i,parentTag:o.parentNode.nodeTag})),e.SET(".clipboardOpen",!0)}catch(o){e.SET(".error",o.message)}}saveClipboard(e){e.SET(".error","");try{let t=e.GET(".clipboardDraft.name")?.trim();if(!t)throw new Error("Choose a name for the branch");let r=e.GET(".clipboardDraft.path"),o=e.GET(".clipboardDraft.wire"),i=e.GET(".clipboardDraft.copy"),a=e.builder.source.getNode(`${he(e)}.${r}`);if(!i&&(!a||this.branchSnapshot(e,r)!==o))throw new Error("The branch changed; select it again before cutting");let s=e.GET(".clipboard"),l=1;for(;s.getNode(`branch_${l}`);)l++;let u=`branch_${l}`;s.setItem(u,o,{name:t,parentTag:e.GET(".clipboardDraft.parentTag")}),e.SET(".clipboardSelection",u),e.SET(".clipboardVisible",!0),i||(e.SET(".selection",r.slice(0,r.lastIndexOf("."))),a.parentBag.popNode(a.label)),e.SET(".clipboardOpen",!1),e.SET(".fileStatus",`${i?"Copied":"Cut"}: ${t}`)}catch(t){e.SET(".error",t.message)}}pasteBranch(e){e.SET(".error","");try{this.beginPaste(e,e.GET(".clipboardSelection"),e.GET(".selection"))}catch(t){e.SET(".error",t.message)}}beginPaste(e,t,r){let o=t?e.GET(".clipboard").getNode(t):null;if(!o)throw new Error("Choose a saved branch in the clipboard");let i=r?e.builder.source.getNode(`${he(e)}.${r}`):null;if(!i)throw new Error("Choose a destination in the Source tree");let a=e.rootBuilder.binding.gramlot.src.prepareSource(o.getValue(!0),i.builder);Dt(se(e).GET(".catalogueScope"),a);let s=a.getNodes()[0];i.builder.validateParent(s.nodeTag,i.nodeTag);let l=i.getValue(!0);i.builder.validateChildren(i.nodeTag,[...l instanceof e.builder.source.constructor?l.getNodes().map(w=>w.nodeTag):[],s.nodeTag]);let u={...s.getAttr()},c=i.builder.schema[s.nodeTag]._meta?.gramlot_component?.parameters??{},d=i.builder.schema[o.getAttr("parentTag")]?._meta?.gramlot_component?.childParameters??{};for(let w of Object.keys(d))w in c||delete u[w];s.setAttr(u,!0,!1,!1),e.SET(".insertion",new E({parentPath:r,tag:s.nodeTag,clipboard:a.toTytx()}));let f=or(i,s.nodeTag),h=Object.entries(f).filter(([w,_])=>_.required&&(u[w]==null||u[w]===""||_.unique));if(!h.length){this.finishPaste(e);return}let p=gl(e,"InsertFields");p.getValue(!0).clear();let m=e.builder.wrapSource(p);m.p(`Paste ${o.getAttr("name")} into ${i.label} [${i.nodeTag}]`,{class:"visual-editor-hint"});let b=m.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});for(let[w,_]of h)this.parameterField(e,b,s.nodeTag,w,_,"insertion",_.default);e.SET(".insertionOpen",!0)}appendBranch(e,t,r){let o=e.builder.source.constructor,i=e.getValue(!0);if(!(i instanceof o)){let a=i;i=new o(null,e.builder),e.builder.promoteNodeValue(e,a,i)}return t.parentBag.popNode(t.label),i.setItem(r,t.getValue(!0),{...t.getAttr()},">",!1,!1,"editor",!1,!0,null,t.nodeTag),i.getNode(r)}finishPaste(e){let t=e.GET(".insertion.parentPath"),r=e.builder.source.getNode(`${he(e)}.${t}`);if(!r)throw new Error("The destination no longer exists");let o=e.rootBuilder.binding.gramlot,i=o.src.prepareSource(e.GET(".insertion.clipboard"),r.builder);Dt(se(e).GET(".catalogueScope"),i);let a=i.getNodes()[0],s={...a.getAttr()};for(let[b,w]of Object.entries(or(r,a.nodeTag))){if(!w.required)continue;let _=e.GET(`.insertion.types.${b}`),y=e.GET(`.insertion.parameters.${b}${w.enum?"":_?"."+_:""}`);y!=null&&(s[b]=y),this.validateParameter(r,null,b,w,s[b])}a.setAttr(s,!0,!1,!1);let l=r.getValue(!0),u=a.label,c=1;for(;l instanceof e.builder.source.constructor&&l.getNode(u);)u=`${a.label}_${c++}`;let d=e.builder.source.getNode(he(e)),f=o.src.prepareSource(d.getValue(!0).toTytx(),d.builder),h=f.getNode(t);h.builder.validateParent(a.nodeTag,h.nodeTag);let p=h.getValue(!0);h.builder.validateChildren(h.nodeTag,[...p instanceof e.builder.source.constructor?p.getNodes().map(b=>b.nodeTag):[],a.nodeTag]);let m=this.appendBranch(h,a,u);Dt(se(e).GET(".catalogueScope"),f),o.src.renderer.validateCandidate(f,{replacingNode:d}),this.appendBranch(r,m,u),e.SET(".insertionOpen",!1),e.SET(".sourceSearch",""),e.SET(".selection",`${t}.${u}`),e.SET(".fileStatus","Branch pasted")}openCode(e){let t=se(e);t.SET(".codeOpen",!0),t.SET(".editingMode","code")}async codeSave(e){let t=se(e),r=t.GET(".codeDocument");if(r.getItem("busy")||!r.getItem("writable"))return;let o=r.getItem("content"),i=r.getItem("revision"),a=!1;if(o===r.getItem("saved"))return;let s=new AbortController,l=this.page.src.renderer.onDispose(t,()=>s.abort());r.setItem("busy",!0),r.setItem("status","Saving Page code\u2026");let u=t.value.getNode("layout.center.design"),c=u.value.toTytx();try{let d=await this.page.rpc.call("data","editor_document_save",{key:t.getAttr("codeDocumentKey"),content:o,revision:i},{signal:s.signal});if(s.signal.aborted)return;r.setItem("revision",d.revision),r.setItem("saved",o),a=!0,r.setItem("status","Page code saved"),c!==u.value.toTytx()?r.setItem("status","Page code saved; Source changed meanwhile. Use Preview saved to replace it."):await this.codeLoadPreview(t,s)}catch(d){s.signal.aborted||r.setItem("status",`${a?"Page code saved; preview failed":"Save failed"}: ${d.message}`)}finally{l(),s.signal.aborted||r.setItem("busy",!1)}}async codePreview(e){let t=se(e),r=t.GET(".codeDocument");if(r.getItem("busy"))return;let o=new AbortController,i=this.page.src.renderer.onDispose(t,()=>o.abort());r.setItem("busy",!0);try{await this.codeLoadPreview(t,o)}catch(a){o.signal.aborted||r.setItem("status",`Preview failed: ${a.message}`)}finally{i(),o.signal.aborted||r.setItem("busy",!1)}}async codeLoadPreview(e,t){let r=e.GET(".codeDocument"),o=e.value.getNode("layout.center.design"),i=o.value.toTytx(),a=await this.page.rpc.call("source","editor_document_preview",{key:e.getAttr("codeDocumentKey"),revision:r.getItem("revision"),data_root:e.GET(".dataRoot")},{signal:t.signal});if(t.signal.aborted)return;if(o.value.toTytx()!==i)throw new Error("Source changed while preparing preview; it was retained");let s=this.page.src.prepareSource(a,o.builder);Dt(e.GET(".catalogueScope"),s),this.page.src.renderer.validateCandidate(s,{replacingNode:o}),e.GET(".assistantRun")&&e.SET(".assistantRun.blocked",!0),e.SET(".selection",null),o.setValue(s,!0,{_text:null},!0),e.SET(".selection","pageRoot"),r.setItem("status",r.getItem("content")===r.getItem("saved")?"Saved Page code \xB7 preview updated":"Preview updated from saved page code; newer draft retained")}newPage(e){e.GET(".assistantRun")&&e.SET(".assistantRun.blocked",!0),e.SET(".selection",null),e.SET(".insertionOpen",!1),e.SET(".error","");let t=e.builder.source.getNode(he(e));t.getValue(!0).clear();let r=e.GET(".dataRoot");if(r)e.SET(r,new E);else for(let o of e.rootBuilder.data.getNodes())o.label!=="__editor"&&e.rootBuilder.data.popNode(o.label);e.builder.wrapSource(t).div({node_label:"pageRoot",...r?{datapath:r}:{}}),e.SET(".filename","page.grmlt"),e.SET(".fileStatus",""),e.SET(".sourceSearch",""),e.SET(".dataSearch",""),e.SET(".selection","pageRoot")}async copySource(e){e.SET(".fileStatus","");try{await e.rootBuilder.binding.gramlot.utl.inout.copyText(this.currentSource(e)),e.SET(".fileStatus","Source copied")}catch(t){e.SET(".fileStatus",`Copy failed: ${t.message}`)}}downloadPage(e){e.rootBuilder.binding.gramlot.utl.inout.saveText(this.currentSource(e),e.GET(".filename"),"application/json")}openUpload(e){e.SET(".uploadOpen",!0)}sourceUploaded(e,{item:t,result:r}){try{this.loadSource(e,{source:r,filename:t.value.getItem("name")}),e.SET(".fileStatus","Source opened"),e.SET(".uploadOpen",!1)}catch(o){throw e.SET(".fileStatus",`Open failed: ${o.message}`),o}}initializeDocument(e){let t=se(e),r=t.builder.source,o=he(t).split("."),i=`${t.getAttr("visualEditorId")}-document`;t.SET(".modified",!1),r.subscribe(i,{any:a=>{o.every((s,l)=>a.pathlist[l]===s)&&t.SET(".modified",!0)}}),t.rootBuilder.binding.renderer.onDispose(t,()=>r.unsubscribe(i,{any:!0}))}currentSource(e){let t=se(e);return t.builder.source.getNode(he(t)).getValue(!0).toTytx()}markSaved(e){se(e).SET(".modified",!1)}loadSource(e,{source:t,filename:r}){let o=se(e);if(typeof t!="string")throw new TypeError("source must be Source TYTX");if(typeof r!="string"||!r.trim())throw new TypeError("filename must be a non-empty string");let i=o.rootBuilder.binding.gramlot,a=o.builder.source.getNode(he(o)),s=i.src.prepareSource(t,a.builder),l=s.getNodes();if(l.length!==1||l[0].label!=="pageRoot")throw new Error("Expected one pageRoot Source");Dt(o.GET(".catalogueScope"),s),i.src.renderer.validateCandidate(s,{replacingNode:a}),o.GET(".assistantRun")&&o.SET(".assistantRun.blocked",!0),o.SET(".selection",null),a.setValue(s,!0,{_text:null},!0),o.SET(".filename",r),o.SET(".insertionOpen",!1),o.SET(".sourceSearch",""),o.SET(".selection","pageRoot"),this.markSaved(o)}toggleNavigation(e){e.SET(".navigationOpen",e.GET(".navigationOpen")==="close"?!0:"close")}openCatalogue(e){e.SET(`${Qe(e)}.catalogueOpen`,!0)}openProperties(e){this.showProperties(e,{path:e.GET(".selection")})}sourceLabel(e,{item:t}){return{text:`${t.label} [${t.nodeTag}]`}}dropNode(e,t){e.SET(".error","");try{this.applyDrop(e,t)}catch(r){e.SET(".error",r.message)}}insertWidget(e){e.SET(".error","");try{this.applyInsert(e)}catch(t){e.SET(".error",t.message)}}initializeEditorAppearance(e){let t=se(e),r=e.rootBuilder.binding.renderer.destination.ownerDocument;t.SET(".appearanceProfile","compact"),t.SET(".appearancePalette","joanna"),t.SET(".appearanceMode",r.documentElement.getAttribute("data-theme")||"dark")}applyEditorAppearance(e,{profile:t,palette:r,mode:o}){if(!t||!r||!o)return;if(!Object.hasOwn(Jc,t)||!Object.hasOwn(Qc,r)||!["light","dark"].includes(o))throw new Error("Choose a declared theme, palette and color mode");se(e).SET(".appearanceCss",Jc[t]+`
|
|
1785
|
+
`+Qc[r]),e.rootBuilder.binding.renderer.destination.ownerDocument.documentElement.setAttribute("data-theme",o)}initializeEditor(e,{dataRoot:t}){let r=e.GET(".catalogueScope");if(Eo(r),Array.isArray(r)){for(let s of r)if(!e.builder.schema[s])throw new Error(`Unknown catalogue tag: ${s}`)}if(e.SET(".editingMode","source"),e.SET(".clipboard",new E),e.SET(".clipboardVisible",!1),e.SET(".clipboardDropEffect","move"),e.SET(".sourceDropEffect","move"),e.SET(".dataRoot",t),e.SET(".filename","page.grmlt"),e.SET(".fileStatus",""),e.SET(".selection","pageRoot"),t)e.GET(t)==null&&e.SET(t,new E);else{let s=Qe(e),l=s.split(".").map(()=>"#parent").join(".");e.builder.source.getNode(he(e)).setAttr({datapath:`${s}.${l}`})}let o=new E,i=new Map([["",o]]),a=(s,l)=>{if(i.has(s))return i.get(s);let u=s.split("."),c=u.pop(),d=u.join("."),f=a(d,I0[d]),h=new E;return f.setItem(c,h,{caption:l}),i.set(s,h),h};for(let[s,l,u]of Qm)u.split(" ").some(c=>e.builder.schema[c]&&xo(r,c,e.builder.schema[c]._meta??{}))&&a(s,l);for(let[s,l]of Object.entries(e.builder.schema).sort(([u],[c])=>u.localeCompare(c))){if(!xo(r,s,l._meta??{})||l._meta?.data_element||l._meta?.subbuilder||l._meta?.container)continue;let u=l._meta?.gramlot_component?"components":"html",c=Qm.find(([f,,h])=>f.startsWith(u+".")&&h.split(" ").includes(s)),d=c?c[0]:`${u}.other`;a(d,c?c[1]:"Other elements").setItem(s,null,{caption:s,tag:s})}e.SET(".catalogue",o)}prepareWidget(e,{item:t,dragValues:r}){if(e.SET(".sourceDropEffect","copy"),!t.attr.tag)return!1;r["app/widget"]={tag:t.attr.tag}}prepareSource(e,{path:t,dragValues:r}){e.SET(".sourceDropEffect","move"),r["app/source"]={path:t}}applyDrop(e,{item:t,path:r,dropValues:o}){if(o["app/clipboard"]){this.beginPaste(e,o["app/clipboard"].path,r);return}if(o["app/source"]){let f=`${he(e)}.${o["app/source"].path}`,h=`${he(e)}.${r}`,p=e.builder.source.getNode(f);if(!p||f===`${he(e)}.pageRoot`)throw new Error("The page root cannot be moved");if(Dt(se(e).GET(".catalogueScope"),p.parentBag),p.resolver)throw new Error("Resolver-backed Source nodes cannot be moved in this trial");if(f===h||h.startsWith(f+"."))throw new Error("A node cannot be moved into itself");let m=t,b=p.parentBag,w=e.builder.source.constructor;if(p.builder!==m.builder)throw new Error("Nodes cannot cross builder dialects");let _=m.getValue(!0),y=_ instanceof w?_.getNodes().filter(D=>D!==p):[];if(_ instanceof w&&_!==b&&_.getNode(p.label))throw new Error("The target already contains this label");let x=m._getMeta("gramlot_component")?.childParameters??{};for(let[D,k]of Object.entries(x)){let C=p.getAttr(D);if(k.required&&C==null)throw new Error(`The moved node requires ${D}`);if(k.enum&&C!=null&&!k.enum.includes(C))throw new Error(`Invalid ${D}`);if(k.unique&&C!=null&&y.some(O=>O.getAttr(D)===C))throw new Error(`${D} is already in use`)}if(m.builder.validateParent(p.nodeTag,m.nodeTag),m.builder.validateChildren(m.nodeTag,[...y.map(D=>D.nodeTag),p.nodeTag]),_===b)b.move(b.getNodes().indexOf(p),y.length);else{let D=_ instanceof w?_:new w(null,m.builder);_ instanceof w||m.builder.promoteNodeValue(m,_,D);let k={label:p.label,tag:p.nodeTag,value:p.getValue(!0),attrs:{...p.getAttr()}};b.popNode(k.label),D.setItem(k.label,k.value,k.attrs,D.getNodes().length,!1,!1,"editor",!1,!0,null,k.tag)}e.SET(".selection",`${r}.${p.label}`);return}let i=o["app/widget"].tag;this.validateCatalogueTag(e,i),t.builder.validateParent(i,t.nodeTag);let a=t.getValue(!0);t.builder.validateChildren(t.nodeTag,[...a instanceof e.builder.source.constructor?a.getNodes().map(f=>f.nodeTag):[],i]);let s=or(t,i),l=Object.entries(s).filter(([,f])=>f.required);if(e.SET(".insertion",new E),e.SET(".insertion.parentPath",r),e.SET(".insertion.tag",i),!l.length){this.applyInsert(e);return}let u=gl(e,"InsertFields");u.getValue(!0).clear();let c=e.builder.wrapSource(u);c.p(`Insert ${i} into ${t.label} [${t.nodeTag}]`,{class:"visual-editor-hint"});let d=c.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});for(let[f,h]of l)this.parameterField(e,d,i,f,h,"insertion",h.default);e.SET(".insertionOpen",!0)}showProperties(e,{path:t}){let r=gl(e,"EditorFields");if(r.getValue(!0).clear(),e.SET(".propertyError",""),e.SET(".properties",new E),!t){e.SET(".propertiesOpen",!1);return}let o=e.builder.source.getNode(`${he(e)}.${t}`);if(!o){e.SET(".propertiesOpen",!1);return}let i=o.parentNode,a=or(i,o.nodeTag,o);e.SET(".properties.path",t),this.attributeRows(e,o),e.SET(".propertiesTitle",`${o.label} [${o.nodeTag}]`),e.SET(".propertiesHeight",`${Math.min(300,Math.max(180,80+Math.ceil(Object.keys(a).filter(f=>td(f,new Set)==="general").length/2)*38))}px`);let s=e.builder.wrapSource(r);t!=="pageRoot"&&s.p(t,{class:"visual-editor-destination"});let l=new Set(Object.keys(i._getMeta("gramlot_component")?.childParameters??{})),u=new Map(ed.map(([f])=>[f,[]]));for(let f of Object.entries(a))u.get(td(f[0],l)).push(f);e.SET(".parameterTab",ed.find(([f])=>u.get(f).length)[0]);let c=s.tabContainer({selectedPage:`^${Qe(e)}.parameterTab`,class:"visual-parameter-tabs",tabMode:"underline",height:"100%",min_height:0,flex:1});for(let[f,h]of ed){if(!u.get(f).length)continue;let p=c.contentPane({pageName:f,title:h,overflow:"auto",padding:"4px",min_height:0,...f==="styles"?{nodeId:se(e).getAttr("visualEditorId")+"StyleAttributes"}:{}});if(f==="styles"){this.attributeFields(e,p,o,"styles");continue}f==="container"&&p.p(`Child parameters of ${i.nodeTag}`,{class:"visual-editor-hint"}),f==="behaviour"&&Object.hasOwn(a,"action")&&p.p("action: use a named Logic method, for example openCatalogue.",{class:"visual-editor-hint"}),f==="behaviour"&&o.nodeTag==="borderContainer"&&p.p("persist remembers splitter sizes and requires a stable container id.",{class:"visual-editor-hint"});let m=p.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"});f==="general"&&o._getMeta("gramlot_component")?.labelbox&&this.labelboxFields(e,m,o,a);let b,w=([,_])=>{let y=Array.isArray(_.dtype)?_.dtype:[_.dtype];return!_.enum&&!y.some(x=>bl.includes(x))?2:_.dtype==="B"?1:0};for(let[_,y]of[...u.get(f)].sort((x,D)=>w(x)-w(D))){if(o._getMeta("gramlot_component")?.labelbox&&/^(lbl|box)(_|$)/.test(_))continue;let x=m;if(f==="validation"&&/(_if|_error|_warning|_iswarning)$/.test(_)){if(!b){let k=p.details({class:"visual-validation-advanced"});k.summary("Conditions and messages"),b=k.formlet({columns:2,gap:"4px 6px",lbl_position:"TL",box_c_width:"100%",align_items:"start"})}x=b}let D=_==="_text"?o.getValue(!0):o.getAttr(_);this.parameterField(e,x,o.nodeTag,_,y,"properties",D??y.default)}}let d=c.contentPane({nodeId:se(e).getAttr("visualEditorId")+"MoreAttributes",pageName:"attributes",title:"More attributes",overflow:"auto",padding:"4px",min_height:0});this.attributeFields(e,d,o),e.SET(".propertiesOpen",!0)}attributeRows(e,t){let r=new E;for(let[o,i]of Object.entries(t.getAttr())){if(o==="_meta")continue;let a=Zc(i),s=a?ml(i,a):"[non-scalar value]";r.setItem(`r${r.length}`,new E({name:o,type:a??"readonly",text:s,original:s}))}e.SET(".properties.attributeRows",r),e.SET(".properties.attributeDraft",new E({name:"",type:"string",text:""})),e.SET(".properties.attributeDraftHidden",!0)}attributeFields(e,t,r,o="attributes"){let i=e.GET(".properties.path"),a=`${Qe(e)}.properties`,s=e.rootBuilder.binding.gramlot.src.renderer,l=new Set(Object.keys(r.parentNode._getMeta("gramlot_component")?.childParameters??{})),u=t.div({class:"visual-editor-attribute-list","aria-label":o==="styles"?"Style attributes":"Node attributes"}),c=u.div({class:"visual-editor-attribute-row visual-editor-attribute-heading"});c.span("Attribute",{class:"visual-editor-attribute-name"});let d=c.div({class:"visual-editor-attribute-value"});d.span("Value"),d.button("+",{action:"beginAttribute",editingPath:i,"aria-label":o==="styles"?"Add style attribute":"Add attribute",title:"Add attribute",class:"visual-editor-attribute-command"});for(let b of e.GET(".properties.attributeRows").getNodes()){let w=b.value.getItem("name"),_=b.value.getItem("type"),y=b.label;if(o==="styles"&&td(w,l)!=="styles"&&!s._isStyleContribution(w))continue;let x=_!=="readonly",D=u.div({class:"visual-editor-attribute-row"});D.span(w,{class:"visual-editor-attribute-name",title:w});let k=D.div({class:"visual-editor-attribute-value"});k.input({value:`^${a}.attributeRows.${y}.text`,disabled:!x,"aria-label":`${w} attribute value`,title:x?_:"Non-scalar values are read-only"}),k.button("\xD7",{action:"removeAttribute",attributeRow:y,editingPath:i,disabled:!x,"aria-label":`Remove ${w} attribute`,title:`Remove ${w}`,class:"visual-editor-attribute-command"}),x&&o==="attributes"&&D.dataController({func:"changeAttribute",value:`^${a}.attributeRows.${y}.text`,attributeRow:y,editingPath:i,_userChanges:!0})}let f=u.div({class:"visual-editor-attribute-row",hidden:`^${a}.attributeDraftHidden`,connect_onkeydown:"attributeDraftKey"});f.div({class:"visual-editor-attribute-name"}).input({value:`^${a}.attributeDraft.name`,live:!0,"aria-label":"New attribute name",placeholder:"Attribute name"});let p=f.div({class:"visual-editor-attribute-value"});p.input({value:`^${a}.attributeDraft.text`,live:!0,"aria-label":"New attribute value",placeholder:"Value"});let m=p.select({value:`^${a}.attributeDraft.type`,"aria-label":"New attribute type"});for(let b of Jm)m.option(b,{value:b});p.button("\u2713",{action:"addAttribute",editingPath:i,"aria-label":"Apply new attribute",title:"Apply (Enter)",class:"visual-editor-attribute-command"}),p.button("\xD7",{action:"cancelAttribute","aria-label":"Cancel new attribute",title:"Cancel (Escape)",class:"visual-editor-attribute-command"})}beginAttribute(e,{editingPath:t}){let r=se(e);t===r.GET(".selection")&&(r.SET(".properties.attributeDraft",new E({name:"",type:"string",text:""})),r.SET(".properties.attributeDraftHidden",!1),r.SET(".propertyError",""))}cancelAttribute(e){se(e).SET(".properties.attributeDraftHidden",!0)}attributeDraftKey(e,t){if(t.isComposing||!["Enter","Escape"].includes(t.key))return;t.preventDefault(),t.stopPropagation();let r=se(e);t.key==="Escape"?this.cancelAttribute(r):this.addAttribute(r,{editingPath:r.GET(".properties.path")})}addAttribute(e,{editingPath:t}){let r=se(e);if(t===r.GET(".selection")){r.SET(".propertyError","");try{let o=r.GET(".properties.attributeDraft"),i=o.getItem("name");if(!i||!/^[^\s"'<>/=]+$/.test(i))throw new Error("Enter a valid attribute name.");if(["_meta","__proto__","constructor","prototype"].includes(i))throw new Error("Unsupported attribute name.");let a=r.builder.source.getNode(`${he(r)}.${t}`);if(!a)throw new Error("The selected Source node no longer exists");if(Object.hasOwn(a.getAttr(),i))throw new Error(`Duplicate attribute: ${i}`);let s=Kc(o.getItem("type"),String(o.getItem("text")??""));this.writeAttribute(r,a,t,i,s,!1)}catch(o){r.SET(".propertyError",o.message)}}}changeAttribute(e,{attributeRow:t,editingPath:r,value:o}){this.editAttribute(e,{attributeRow:t,editingPath:r,value:o,remove:!1})}removeAttribute(e,{attributeRow:t,editingPath:r}){this.editAttribute(e,{attributeRow:t,editingPath:r,remove:!0})}editAttribute(e,{attributeRow:t,editingPath:r,value:o,remove:i}){let a=se(e);if(r===a.GET(".selection")){a.SET(".propertyError","");try{let s=a.GET(".properties.attributeRows").getItem(t);if(!s||s.getItem("type")==="readonly")throw new Error("This attribute is not editable");let l=s.getItem("name");if(["_meta","__proto__","constructor","prototype"].includes(l))throw new Error("Unsupported attribute name.");let u=a.builder.source.getNode(`${he(a)}.${r}`);if(!u)throw new Error("The selected Source node no longer exists");let c=u.getAttr(),d=Zc(c[l]);if(!Object.hasOwn(c,l)||d!==s.getItem("type")||ml(c[l],d)!==s.getItem("original"))throw new Error("Attribute changed; select the node again before editing.");let f=i?null:Kc(d,String(o??""));this.writeAttribute(a,u,r,l,f,i,s)}catch(s){a.SET(".propertyError",s.message)}}}writeAttribute(e,t,r,o,i,a,s=null){let l={...t.getAttr()};a?delete l[o]:l[o]=i;let u=or(t.parentNode,t.nodeTag,t);u[o]&&this.validateParameter(t.parentNode,t,o,u[o],a?null:i);let c=e.builder.source.getNode(he(e)),d=e.rootBuilder.binding.gramlot,f=d.src.prepareSource(c.getValue(!0).toTytx(),c.builder);if(f.getNode(r).setAttr(l,!0,!1,!1),Dt(e.GET(".catalogueScope"),f),d.src.renderer.validateCandidate(f,{replacingNode:c}),t.setAttr(l,!0,!1,!1),s&&!a){let h=ml(i,s.getItem("type"));s.setItem("original",h),s.setItem("text",h);let p=e.GET(`.properties.types.${o}`);u[o]?.enum?e.SET(`.properties.parameters.${o}`,i):p&&e.SET(`.properties.parameters.${o}.${p}`,i)}else{let h=e.GET(".parameterTab")==="styles"?"styles":"attributes";this.showProperties(e,{path:r}),e.SET(".parameterTab",h)}}toggleLabelboxAttributes(e,{prefix:t}){e.SET(`.properties.${t}Hidden`,!e.GET(`.properties.${t}Hidden`))}labelboxFields(e,t,r,o){for(let i of["lbl","box"]){let a=i==="lbl"?"Label":"Box",s=t.div({class:"visual-labelbox-section",grid_column:"1 / -1"}),l=s.div({class:"visual-labelbox-heading"});i==="lbl"?this.parameterField(e,l,r.nodeTag,"lbl",o.lbl,"properties",r.getAttr("lbl")):l.span(a,{class:"visual-labelbox-title"}),l.button({iconSrc:Ge.properties,title:`Edit ${a.toLowerCase()} attributes`,"aria-label":`Edit ${a.toLowerCase()} attributes`,class:"button--quiet",action:"toggleLabelboxAttributes",prefix:i});let u=Object.entries(o).filter(([f])=>f.startsWith(i+"_"));e.SET(`.properties.${i}Hidden`,!0),e.SET(`.properties.${i}Attribute`,"");let c=s.div({class:"visual-labelbox-attribute",hidden:`^${Qe(e)}.properties.${i}Hidden`}),d=c.select({"aria-label":`${a} attribute`,value:`^${Qe(e)}.properties.${i}Attribute`});d.option("Which attribute?",{value:""});for(let[f]of u)d.option(f.slice(i.length+1),{value:f});c.div({node_label:"attributeValue"}).span(""),c.dataController({func:"renderLabelboxAttribute",_init:!0,parameterName:`^${Qe(e)}.properties.${i}Attribute`,editingPath:e.GET(".properties.path")})}}renderLabelboxAttribute(e,{parameterName:t,editingPath:r}){let o=e.parentBag.getNode("attributeValue");if(o.getValue(!0).clear(),!t||r!==e.GET(".selection"))return;let i=e.builder.source.getNode(`${he(e)}.${r}`),a=or(i.parentNode,i.nodeTag,i)[t];this.parameterField(e,e.builder.wrapSource(o),i.nodeTag,t,a,"properties",i.getAttr(t)??a.default,!0)}parameterField(e,t,r,o,i,a,s,l=!1){let u=o==="lbl"?"Label":o==="_text"&&e.builder.schema[r]._meta?.gramlot_component?.command?"caption":o==="_text"?"Text":o,c=`${Qe(e)}.${a}.parameters.${o}`;if(i.enum){e.SET(c,s??"");let b=t.select({lbl:l?null:u,lbl_position:"TL",value:`^${c}`,"aria-label":o});b.option("",{value:""});for(let w of i.enum)b.option(String(w),{value:w});a==="properties"&&t.dataController({func:"changeProperty",value:`^${c}`,_userChanges:!0,parameterName:o,editingPath:e.GET(".properties.path")});return}let d=Array.isArray(i.dtype)?i.dtype:i.dtype?[i.dtype]:[],f=d.filter(b=>bl.includes(b));if(!f.length){t.p(`${u}: no editor is available for this declared type`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}let h="";if(s==null?h=f.length===1?f[0]:"":typeof s=="boolean"&&f.includes("B")?h="B":typeof s=="string"&&f.includes("T")?h="T":typeof s=="number"?h=f.find(b=>["L","R","N"].includes(b))??"":s instanceof Date?h=f.find(b=>["D","H"].includes(b))??"":f.length===1&&f[0]==="N"&&(h="N"),s!=null&&!h){t.p(`${u}: the current value is not editable with these scalar types`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}e.SET(`${Qe(e)}.${a}.types.${o}`,h);for(let b of f)e.SET(`${c}.${b}`,b===h?s??null:null);let p=!l&&(d.length>1||/^(tooltip|_text|action|placeholder|value)$|(_error|_warning|_if)$/.test(o)),m=t.div({class:"visual-parameter-field",grid_column:p?"1 / -1":"auto",grid_template_columns:d.length>1?"minmax(100px, 1fr) minmax(0, 2fr)":"minmax(0, 1fr)",align_items:"start"});if(d.length>1){let b=m.select({lbl:`${u} type`,lbl_position:"TL",value:`^${Qe(e)}.${a}.types.${o}`,"aria-label":`${o} type`});b.option("Not set",{value:""});for(let w of d)b.option(bl.includes(w)?w:`${w} (unavailable)`,{value:w,disabled:!bl.includes(w)});a==="properties"&&m.dataController({func:"changePropertyType",type:`^${Qe(e)}.${a}.types.${o}`,_userChanges:!0,parameterName:o,editingPath:e.GET(".properties.path")})}m.div({node_label:"input"}).span(""),m.dataController({func:"renderParameterInput",_init:!0,type:`^${Qe(e)}.${a}.types.${o}`,parameterName:o,parameterLabel:u,scope:a,compact:l,multiple:d.length>1})}renderParameterInput(e,{type:t,parameterName:r,parameterLabel:o,scope:i,multiple:a,compact:s}){let l=e.parentBag.getNode("input");if(l.getValue(!0).clear(),!t)return;let u=e.builder.wrapSource(l),c=a?`${o} (${t})`:o,d=`^${Qe(e)}.${i}.parameters.${r}.${t}`,f={lbl:s?null:c,lbl_position:"TL",value:d,"aria-label":c};if(t==="B")u.checkbox(f);else if(["L","R","N"].includes(t))u.numberTextBox({...f,dtype:t});else if(t==="D")u.dateTextBox(f);else if(t==="H")u.timeTextBox(f);else if(t==="T"&&/^(lbl|box)_color$/.test(r))u.colorpicker(f);else if(t==="T")u.textbox(f);else throw new Error(`No parameter editor for ${t}`);i==="properties"&&u.dataController({func:"changeProperty",value:d,_userChanges:!0,parameterName:r,editingPath:e.GET(".properties.path")})}changePropertyType(e,{type:t,parameterName:r,editingPath:o}){this.changeProperty(e,{parameterName:r,editingPath:o,value:t?e.GET(`.properties.parameters.${r}.${t}`):null})}changeProperty(e,{value:t,parameterName:r,editingPath:o}){if(o===e.GET(".selection")){e.SET(".propertyError","");try{let i=e.builder.source.getNode(`${he(e)}.${o}`);if(!i)throw new Error("The selected Source node no longer exists");if(r!=="_text"&&Object.is(i.getAttr(r),t))return;let s=or(i.parentNode,i.nodeTag,i)[r];if(!s)throw new Error(`Unknown parameter: ${r}`);if(this.validateParameter(i.parentNode,i,r,s,t),r==="_text")i.setValue(t??"");else{let l={...i.getAttr()};t==null||t===""?delete l[r]:l[r]=t,i.setAttr(l,!0,!1,!1)}this.attributeRows(e,i);for(let[l,u]of[["MoreAttributes","attributes"],["StyleAttributes","styles"]]){let c=gl(e,l);c.getValue(!0).clear(),this.attributeFields(e,e.builder.wrapSource(c),i,u)}}catch(i){e.SET(".propertyError",i.message)}}}validateParameter(e,t,r,o,i){let a=i==null||i==="";if(o.required&&a)throw new Error(`Choose ${r}`);if(!a&&o.enum&&!o.enum.includes(i))throw new Error(`Invalid ${r}`);let s=e.getValue(!0);if(!a&&o.unique&&s instanceof e.builder.source.constructor&&s.getNodes().some(l=>l!==t&&l.getAttr(r)===i))throw new Error(`${r} is already in use`)}validateCatalogueTag(e,t){let r=se(e).GET(".catalogueScope");if(!xo(r,t,e.builder.schema[t]?._meta??{}))throw new Error(`Tag ${t} is outside the editor catalogue`)}applyInsert(e){if(e.GET(".insertion.clipboard")){this.finishPaste(e);return}let t=e.GET(".insertion.parentPath"),r=e.builder.source.getNode(`${he(e)}.${t}`);if(!r)throw new Error("The target Source node is no longer available");let o=e.GET(".insertion.tag");this.validateCatalogueTag(e,o);let i={};for(let[s,l]of Object.entries(or(r,o)).filter(([,u])=>u.required)){let u=e.GET(`.insertion.types.${s}`),c=e.GET(`.insertion.parameters.${s}${l.enum?"":u?"."+u:""}`);this.validateParameter(r,null,s,l,c),i[s]=c}let a=r.builder.commandOnNode(r,o,null,i);e.SET(".insertionOpen",!1),e.SET(".selection",`${t}.${a.label}`)}};export{E as Bag,xt as BagNode,Fc as BrowserCameraProvider,vp as ChoiceGroup,Oo as CommandRegistry,Ar as ComponentCollection,Fi as DeviceHandler,Gi as DirectoryResolver,Li as DomHandler,Qs as Exposed,Hm as FieldState,Wi as FileSystemController,wn as FileSystemLogic,yo as FramePage,Ui as Gramlot,Oe as GramlotBuilder,un as GramlotHtmlRenderer,Mi as GramlotRenderer,Ai as GramlotSvgRenderer,Ke as Handler,Ro as HttpTransport,ol as IdeLogic,ji as InOut,el as IndexLogic,Hi as IndexPage,Rc as Labelbox,Io as MobileEnvironment,yp as NativeControl,Oc as NavigationResolver,zi as Page,wc as PageBootstrap,bi as References,nn as RpcError,wi as RpcHandler,ur as ServerAdapter,Pi as SourceHandler,sl as SourceImport,ta as SourcePicker,Yi as TreeStore,il as TreeStoreLogic,Br as TreeStoreResolver,vo as UploadTarget,qi as UtilitiesHandler,al as VisualEditor,rd as VisualEditorLogic,Hc as chatCompleted,Wc as chatPickAttachments,Yc as chatRemoveAttachment,Uc as chatRender,Xc as chatRenderAttachments,zc as chatReset,Gc as chatResize,Vc as chatSend,tl as codeMirrorWithOptions,Ym as collectionBuildId,v0 as createDOMPurify,Lt as createDecimal,Ku as defineCollection,Dr as defineComponent,vm as fileSystemTree,j as fromTytx,Nh as fromTytxIter,E0 as loadMarkdown,yc as mountIndexPage,Cs as parseDateExpression,ae as sourceTarget,L as toTytx,D0 as verifyCollectionArtifact,se as visualEditorScope};
|
|
1786
1786
|
/*! Bundled license information:
|
|
1787
1787
|
|
|
1788
1788
|
decimal.js/decimal.mjs:
|