@gramlot/gramlot 0.3.33 → 0.3.35
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/collections/typst.js +3 -0
- package/dist/components/audio/__init__.py +1 -1
- package/dist/components/audio/assets/collection.js +2 -2
- package/dist/components/audio/assets/index.js +1 -1
- package/dist/components/charts/__init__.py +2 -2
- package/dist/components/charts/assets/collection.js +10 -44
- package/dist/components/charts/assets/index.js +1 -1
- package/dist/components/charts/assets/modules/chunk-USZCUBTC.js +1 -0
- package/dist/components/charts/assets/modules/echarts-gl.min-N6L67H2M.js +4282 -0
- package/dist/components/charts/assets/modules/echarts.esm.min-VHLRZDVQ.js +61 -0
- package/dist/components/charts/assets/modules/{plotly.min-4LB7HE7P.js → plotly.min-SSDU2DOH.js} +1 -1
- package/dist/components/charts/assets/modules/{uPlot.esm-5JJNHHRF.js → uPlot.esm-Q2UYUQHJ.js} +1 -1
- package/dist/components/charts/assets/modules/{uPlot.min-N3E3FA74.js → uPlot.min-XXHNQFXH.js} +1 -1
- package/dist/components/charts/assets/modules/{vega.module-2QCOVQ3A.js → vega.module-Y5CWNSZO.js} +1 -1
- package/dist/components/chat/__init__.py +1 -1
- package/dist/components/chat/assets/collection.js +3 -3
- package/dist/components/chat/assets/index.js +1 -1
- package/dist/components/drawing/__init__.py +1 -1
- package/dist/components/drawing/assets/collection.js +3 -24
- package/dist/components/drawing/assets/index.js +1 -1
- package/dist/components/editors/__init__.py +2 -2
- package/dist/components/editors/assets/collection.js +2 -47
- package/dist/components/editors/assets/index.js +1 -1
- package/dist/components/editors/assets/modules/{jodit-engine-MTSA4GZ3.js → jodit-engine-CXRSFV47.js} +6 -6
- package/dist/components/grid/__init__.py +2 -2
- package/dist/components/grid/assets/collection.js +6 -28
- package/dist/components/grid/assets/index.js +1 -1
- package/dist/components/grid/assets/modules/{browser-LVJHKBBV.js → browser-Y2BRNI3P.js} +1 -1
- package/dist/components/grid/assets/modules/chunk-BLMUM44K.js +1 -0
- package/dist/components/grouplets/__init__.py +1 -1
- package/dist/components/grouplets/assets/collection.js +3 -3
- package/dist/components/grouplets/assets/index.js +1 -1
- package/dist/components/inputs/__init__.py +1 -1
- package/dist/components/inputs/assets/collection.js +8 -65
- package/dist/components/inputs/assets/index.js +1 -1
- package/dist/components/layout/__init__.py +1 -1
- package/dist/components/layout/assets/collection.js +9 -30
- package/dist/components/layout/assets/index.js +1 -1
- package/dist/components/selection_trial/__init__.py +1 -1
- package/dist/components/selection_trial/assets/collection.js +3 -3
- package/dist/components/selection_trial/assets/index.js +1 -1
- package/dist/components/tree/__init__.py +1 -1
- package/dist/components/tree/assets/collection.js +6 -27
- package/dist/components/tree/assets/index.js +1 -1
- package/dist/components/typst/__init__.py +1 -1
- package/dist/components/typst/assets/collection.js +3 -3
- package/dist/components/typst/assets/index.js +1 -1
- package/dist/components/uploads/__init__.py +1 -1
- package/dist/components/uploads/assets/collection.js +3 -30
- package/dist/components/uploads/assets/index.js +1 -1
- package/dist/components/vizabi/__init__.py +1 -1
- package/dist/components/vizabi/assets/collection.js +3 -21
- package/dist/components/vizabi/assets/index.js +1 -1
- package/dist/declared-collections.js +2 -0
- package/dist/gramlot.js +1057 -6999
- package/dist/gramlot.min.js +48 -52
- package/dist/libraries.json +126 -0
- package/dist/runtime-notices.json +0 -8
- package/dist/standard-collections.js +1 -1
- package/package.json +3 -2
- package/src/components/chart-engines/echarts.js +10 -4
- package/src/components/chart-engines/plotly.js +3 -2
- package/src/components/chart-engines/uplot.js +5 -3
- package/src/components/chart-engines/vega.js +2 -1
- package/src/components/chart-gauge.js +7 -3
- package/src/components/chart-renderer.js +1 -1
- package/src/components/code-mirror.js +2 -1
- package/src/components/grid-tools.js +2 -1
- package/src/components/html-editor.js +2 -1
- package/src/components/markdown-editor.js +2 -1
- package/src/components/typst-preview.js +2 -1
- package/src/index.d.ts +16 -0
- package/src/index.js +5 -0
- package/src/libraries.js +83 -0
- package/src/server/assets.d.ts +3 -2
- package/src/server/assets.js +6 -3
- package/src/server/gramlot-server.d.ts +8 -0
- package/src/server/gramlot-server.js +45 -4
- package/src/server/index.d.ts +1 -1
- package/src/server/index.js +1 -1
- package/src/shared-modules.js +76 -0
- package/dist/components/charts/assets/modules/chunk-2CCTLZE7.js +0 -76
- package/dist/components/charts/assets/modules/chunk-RMRBEYTI.js +0 -1
- package/dist/components/charts/assets/modules/echarts-gl-CXVTZA6G.js +0 -4409
- package/dist/components/grid/assets/modules/chunk-RMRBEYTI.js +0 -1
package/dist/gramlot.min.js
CHANGED
|
@@ -6,38 +6,33 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
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
|
-
`).replace(/[\r\u0085\u2028\u2029]/g,`
|
|
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=`
|
|
9
|
+
var tp=Object.defineProperty;var ee=(o,e)=>{for(var t in e)tp(o,t,{get:e[t],enumerable:!0})};var ai=new WeakMap,Iu=`
|
|
15
10
|
--gramlot-toolbar-thickness:56px; --gramlot-toolbar-control-size:44px; --gramlot-toolbar-padding:6px;
|
|
16
|
-
`,
|
|
11
|
+
`,Cu=`
|
|
17
12
|
box-sizing:border-box; height:100dvh; min-height:0; overflow:auto;
|
|
18
13
|
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
14
|
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
|
-
`,
|
|
15
|
+
`,rp=`
|
|
21
16
|
[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"]{${
|
|
17
|
+
:root[data-gramlot-touch="on"] [data-gramlot-viewport]{${Iu}}
|
|
18
|
+
:root[data-gramlot-touch="on"] [data-gramlot-viewport="root"]{${Cu}}
|
|
24
19
|
:root[data-gramlot-touch="on"] [data-gramlot-viewport="root"] > *{max-height:100%;}
|
|
25
20
|
@media(pointer:coarse){
|
|
26
|
-
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport]{${
|
|
27
|
-
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"]{${
|
|
21
|
+
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport]{${Iu}}
|
|
22
|
+
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"]{${Cu}}
|
|
28
23
|
:root:not([data-gramlot-touch="off"]) [data-gramlot-viewport="root"] > *{max-height:100%;}
|
|
29
24
|
}
|
|
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
|
-
${
|
|
33
|
-
${
|
|
34
|
-
`:"")}_nodeToXml(e,t=null,r=!1,
|
|
25
|
+
`,Cn=class o{static install({document:e,root:t}){return ai.has(t)||ai.set(t,new o(e,t)),ai.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 n=r.content.split(",").map(i=>i.trim()).filter(i=>!i.startsWith("viewport-fit="));r.content=[...n,"viewport-fit=cover"].join(","),this.style=e.createElement("style"),this.style.textContent=rp,e.head.append(this.style)}subscribeAppearance(e){let t=this.document.defaultView,r=t.matchMedia("(prefers-color-scheme: dark)"),n=()=>{let a=t.getComputedStyle(this.document.documentElement).colorScheme;e({dark:a==="dark"||!["light","dark"].includes(a)&&r.matches})},i=new t.MutationObserver(n);i.observe(this.document.documentElement,{attributes:!0,attributeFilter:["data-theme","style","class"]}),r.addEventListener("change",n),n();let s=()=>{i.disconnect(),r.removeEventListener("change",n)};return this.releases.push(s),s}dispose(){if(!this.closed){this.closed=!0;for(let e of this.releases)e();this.style.remove(),this.root.removeAttribute("data-gramlot-viewport"),ai.delete(this.root)}}};var Dn=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(n=>!["author","description"].includes(n))||Object.values(t).some(n=>typeof n!="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(n,i){if(typeof n!="string"||!n||n.includes(":"))throw new TypeError("Invalid command name");if(r.has(n))throw new Error(`Duplicate command: ${e}:${n}`);if(!i||typeof i!="object"||Array.isArray(i)||!Object.hasOwn(i,"label")||!Object.hasOwn(i,"publish")||Object.keys(i).some(s=>!["label","publish","icon","iconSrc","tooltip"].includes(s))||Object.values(i).some(s=>typeof s!="string"))throw new TypeError(`Invalid command definition: ${e}:${n}`);r.set(n,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 Nn=class{constructor(e,{fetcher:t=globalThis.fetch?.bind(globalThis),closeUrl:r="/gramlot/close",navigator:n=globalThis.navigator,XMLHttpRequest:i=globalThis.XMLHttpRequest}={}){this.rpcUrl=e,this.fetcher=t,this.closeUrl=r,this.navigator=n,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 li=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 Rt=class{createTransport({rpcUrl:e,closeUrl:t,document:r,channel:n=null}){let i=r.defaultView,s=new Nn(e,{closeUrl:t,navigator:i.navigator,XMLHttpRequest:i.XMLHttpRequest});return n===null?s:new li(n,s)}};var Ua={};ee(Ua,{CONTENT_TYPES:()=>za,__version__:()=>Um,createDecimal:()=>Ye,fetchTytx:()=>Ai,fromTytx:()=>j,fromTytxIter:()=>La,getDateType:()=>bt,getDecimalLibrary:()=>Zr,getRegisteredType:()=>Kr,getSubtypeDict:()=>Pe,getTransport:()=>qa,isDecimal:()=>U,registerClass:()=>yd,registerSubtype:()=>vd,registerType:()=>Vn,setDecimalLibrary:()=>_d,setSubtypeDict:()=>wt,toTytx:()=>R,toTytxIter:()=>dd});var xa={};ee(xa,{Decimal:()=>Wr,default:()=>va});var Ur=9e15,Mt=1e9,ga="0123456789abcdef",di="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",fi="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",ba={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Ur,maxE:Ur,crypto:!1},$u,gt,q=!0,pi="[DecimalError] ",Bt=pi+"Invalid argument: ",Ru=pi+"Precision limit exceeded",ju=pi+"crypto unavailable",Pu="[object Decimal]",Ee=Math.floor,pe=Math.pow,np=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,op=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,ip=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Bu=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Ge=1e7,M=7,sp=9007199254740991,ap=di.length-1,wa=fi.length-1,A={toStringTag:Pu};A.absoluteValue=A.abs=function(){var o=new this.constructor(this);return o.s<0&&(o.s=1),B(o)};A.ceil=function(){return B(new this.constructor(this),this.e+1,2)};A.clampedTo=A.clamp=function(o,e){var t,r=this,n=r.constructor;if(o=new n(o),e=new n(e),!o.s||!e.s)return new n(NaN);if(o.gt(e))throw Error(Bt+e);return t=r.cmp(o),t<0?o:r.cmp(e)>0?e:new n(r)};A.comparedTo=A.cmp=function(o){var e,t,r,n,i=this,s=i.d,a=(o=new i.constructor(o)).d,l=i.s,c=o.s;if(!s||!a)return!l||!c?NaN:l!==c?l:s===a?0:!s^l<0?1:-1;if(!s[0]||!a[0])return s[0]?l:a[0]?-c:0;if(l!==c)return l;if(i.e!==o.e)return i.e>o.e^l<0?1:-1;for(r=s.length,n=a.length,e=0,t=r<n?r:n;e<t;++e)if(s[e]!==a[e])return s[e]>a[e]^l<0?1:-1;return r===n?0:r>n^l<0?1:-1};A.cosine=A.cos=function(){var o,e,t=this,r=t.constructor;return t.d?t.d[0]?(o=r.precision,e=r.rounding,r.precision=o+Math.max(t.e,t.sd())+M,r.rounding=1,t=lp(r,qu(r,t)),r.precision=o,r.rounding=e,B(gt==2||gt==3?t.neg():t,o,e,!0)):new r(1):new r(NaN)};A.cubeRoot=A.cbrt=function(){var o,e,t,r,n,i,s,a,l,c,u=this,d=u.constructor;if(!u.isFinite()||u.isZero())return new d(u);for(q=!1,i=u.s*pe(u.s*u,1/3),!i||Math.abs(i)==1/0?(t=ye(u.d),o=u.e,(i=(o-t.length+1)%3)&&(t+=i==1||i==-2?"0":"00"),i=pe(t,1/3),o=Ee((o+1)/3)-(o%3==(o<0?-1:2)),i==1/0?t="5e"+o:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+o),r=new d(t),r.s=u.s):r=new d(i.toString()),s=(o=d.precision)+3;;)if(a=r,l=a.times(a).times(a),c=l.plus(u),r=re(c.plus(u).times(a),c.plus(l),s+2,1),ye(a.d).slice(0,s)===(t=ye(r.d)).slice(0,s))if(t=t.slice(s-3,s+1),t=="9999"||!n&&t=="4999"){if(!n&&(B(a,o+1,0),a.times(a).times(a).eq(u))){r=a;break}s+=4,n=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(B(r,o+1,1),e=!r.times(r).times(r).eq(u));break}return q=!0,B(r,o,d.rounding,e)};A.decimalPlaces=A.dp=function(){var o,e=this.d,t=NaN;if(e){if(o=e.length-1,t=(o-Ee(this.e/M))*M,o=e[o],o)for(;o%10==0;o/=10)t--;t<0&&(t=0)}return t};A.dividedBy=A.div=function(o){return re(this,new this.constructor(o))};A.dividedToIntegerBy=A.divToInt=function(o){var e=this,t=e.constructor;return B(re(e,new t(o),0,1,1),t.precision,t.rounding)};A.equals=A.eq=function(o){return this.cmp(o)===0};A.floor=function(){return B(new this.constructor(this),this.e+1,3)};A.greaterThan=A.gt=function(o){return this.cmp(o)>0};A.greaterThanOrEqualTo=A.gte=function(o){var e=this.cmp(o);return e==1||e===0};A.hyperbolicCosine=A.cosh=function(){var o,e,t,r,n,i=this,s=i.constructor,a=new s(1);if(!i.isFinite())return new s(i.s?1/0:NaN);if(i.isZero())return a;t=s.precision,r=s.rounding,s.precision=t+Math.max(i.e,i.sd())+4,s.rounding=1,n=i.d.length,n<32?(o=Math.ceil(n/3),e=(1/gi(4,o)).toString()):(o=16,e="2.3283064365386962890625e-10"),i=Vr(s,1,i.times(e),new s(1),!0);for(var l,c=o,u=new s(8);c--;)l=i.times(i),i=a.minus(l.times(u.minus(l.times(u))));return B(i,s.precision=t,s.rounding=r,!0)};A.hyperbolicSine=A.sinh=function(){var o,e,t,r,n=this,i=n.constructor;if(!n.isFinite()||n.isZero())return new i(n);if(e=i.precision,t=i.rounding,i.precision=e+Math.max(n.e,n.sd())+4,i.rounding=1,r=n.d.length,r<3)n=Vr(i,2,n,n,!0);else{o=1.4*Math.sqrt(r),o=o>16?16:o|0,n=n.times(1/gi(5,o)),n=Vr(i,2,n,n,!0);for(var s,a=new i(5),l=new i(16),c=new i(20);o--;)s=n.times(n),n=n.times(a.plus(s.times(l.times(s).plus(c))))}return i.precision=e,i.rounding=t,B(n,e,t,!0)};A.hyperbolicTangent=A.tanh=function(){var o,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+7,r.rounding=1,re(t.sinh(),t.cosh(),r.precision=o,r.rounding=e)):new r(t.s)};A.inverseCosine=A.acos=function(){var o=this,e=o.constructor,t=o.abs().cmp(1),r=e.precision,n=e.rounding;return t!==-1?t===0?o.isNeg()?it(e,r,n):new e(0):new e(NaN):o.isZero()?it(e,r+4,n).times(.5):(e.precision=r+6,e.rounding=1,o=new e(1).minus(o).div(o.plus(1)).sqrt().atan(),e.precision=r,e.rounding=n,o.times(2))};A.inverseHyperbolicCosine=A.acosh=function(){var o,e,t=this,r=t.constructor;return t.lte(1)?new r(t.eq(1)?0:NaN):t.isFinite()?(o=r.precision,e=r.rounding,r.precision=o+Math.max(Math.abs(t.e),t.sd())+4,r.rounding=1,q=!1,t=t.times(t).minus(1).sqrt().plus(t),q=!0,r.precision=o,r.rounding=e,t.ln()):new r(t)};A.inverseHyperbolicSine=A.asinh=function(){var o,e,t=this,r=t.constructor;return!t.isFinite()||t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+2*Math.max(Math.abs(t.e),t.sd())+6,r.rounding=1,q=!1,t=t.times(t).plus(1).sqrt().plus(t),q=!0,r.precision=o,r.rounding=e,t.ln())};A.inverseHyperbolicTangent=A.atanh=function(){var o,e,t,r,n=this,i=n.constructor;return n.isFinite()?n.e>=0?new i(n.abs().eq(1)?n.s/0:n.isZero()?n:NaN):(o=i.precision,e=i.rounding,r=n.sd(),Math.max(r,o)<2*-n.e-1?B(new i(n),o,e,!0):(i.precision=t=r-n.e,n=re(n.plus(1),new i(1).minus(n),t+o,1),i.precision=o+4,i.rounding=1,n=n.ln(),i.precision=o,i.rounding=e,n.times(.5))):new i(NaN)};A.inverseSine=A.asin=function(){var o,e,t,r,n=this,i=n.constructor;return n.isZero()?new i(n):(e=n.abs().cmp(1),t=i.precision,r=i.rounding,e!==-1?e===0?(o=it(i,t+4,r).times(.5),o.s=n.s,o):new i(NaN):(i.precision=t+6,i.rounding=1,n=n.div(new i(1).minus(n.times(n)).sqrt().plus(1)).atan(),i.precision=t,i.rounding=r,n.times(2)))};A.inverseTangent=A.atan=function(){var o,e,t,r,n,i,s,a,l,c=this,u=c.constructor,d=u.precision,f=u.rounding;if(c.isFinite()){if(c.isZero())return new u(c);if(c.abs().eq(1)&&d+4<=wa)return s=it(u,d+4,f).times(.25),s.s=c.s,s}else{if(!c.s)return new u(NaN);if(d+4<=wa)return s=it(u,d+4,f).times(.5),s.s=c.s,s}for(u.precision=a=d+10,u.rounding=1,t=Math.min(28,a/M+2|0),o=t;o;--o)c=c.div(c.times(c).plus(1).sqrt().plus(1));for(q=!1,e=Math.ceil(a/M),r=1,l=c.times(c),s=new u(c),n=c;o!==-1;)if(n=n.times(l),i=s.minus(n.div(r+=2)),n=n.times(l),s=i.plus(n.div(r+=2)),s.d[e]!==void 0)for(o=e;s.d[o]===i.d[o]&&o--;);return t&&(s=s.times(2<<t-1)),q=!0,B(s,u.precision=d,u.rounding=f,!0)};A.isFinite=function(){return!!this.d};A.isInteger=A.isInt=function(){return!!this.d&&Ee(this.e/M)>this.d.length-2};A.isNaN=function(){return!this.s};A.isNegative=A.isNeg=function(){return this.s<0};A.isPositive=A.isPos=function(){return this.s>0};A.isZero=function(){return!!this.d&&this.d[0]===0};A.lessThan=A.lt=function(o){return this.cmp(o)<0};A.lessThanOrEqualTo=A.lte=function(o){return this.cmp(o)<1};A.logarithm=A.log=function(o){var e,t,r,n,i,s,a,l,c=this,u=c.constructor,d=u.precision,f=u.rounding,h=5;if(o==null)o=new u(10),e=!0;else{if(o=new u(o),t=o.d,o.s<0||!t||!t[0]||o.eq(1))return new u(NaN);e=o.eq(10)}if(t=c.d,c.s<0||!t||!t[0]||c.eq(1))return new u(t&&!t[0]?-1/0:c.s!=1?NaN:t?0:1/0);if(e)if(t.length>1)i=!0;else{for(n=t[0];n%10===0;)n/=10;i=n!==1}if(q=!1,a=d+h,s=Pt(c,a),r=e?hi(u,a+10):Pt(o,a),l=re(s,r,a,1),On(l.d,n=d,f))do if(a+=10,s=Pt(c,a),r=e?hi(u,a+10):Pt(o,a),l=re(s,r,a,1),!i){+ye(l.d).slice(n+1,n+15)+1==1e14&&(l=B(l,d+1,0));break}while(On(l.d,n+=10,f));return q=!0,B(l,d,f)};A.minus=A.sub=function(o){var e,t,r,n,i,s,a,l,c,u,d,f,h=this,p=h.constructor;if(o=new p(o),!h.d||!o.d)return!h.s||!o.s?o=new p(NaN):h.d?o.s=-o.s:o=new p(o.d||h.s!==o.s?h:NaN),o;if(h.s!=o.s)return o.s=-o.s,h.plus(o);if(c=h.d,f=o.d,a=p.precision,l=p.rounding,!c[0]||!f[0]){if(f[0])o.s=-o.s;else if(c[0])o=new p(h);else return new p(l===3?-0:0);return q?B(o,a,l):o}if(t=Ee(o.e/M),u=Ee(h.e/M),c=c.slice(),i=u-t,i){for(d=i<0,d?(e=c,i=-i,s=f.length):(e=f,t=u,s=c.length),r=Math.max(Math.ceil(a/M),s)+2,i>r&&(i=r,e.length=1),e.reverse(),r=i;r--;)e.push(0);e.reverse()}else{for(r=c.length,s=f.length,d=r<s,d&&(s=r),r=0;r<s;r++)if(c[r]!=f[r]){d=c[r]<f[r];break}i=0}for(d&&(e=c,c=f,f=e,o.s=-o.s),s=c.length,r=f.length-s;r>0;--r)c[s++]=0;for(r=f.length;r>i;){if(c[--r]<f[r]){for(n=r;n&&c[--n]===0;)c[n]=Ge-1;--c[n],c[r]+=Ge}c[r]-=f[r]}for(;c[--s]===0;)c.pop();for(;c[0]===0;c.shift())--t;return c[0]?(o.d=c,o.e=mi(c,t),q?B(o,a,l):o):new p(l===3?-0:0)};A.modulo=A.mod=function(o){var e,t=this,r=t.constructor;return o=new r(o),!t.d||!o.s||o.d&&!o.d[0]?new r(NaN):!o.d||t.d&&!t.d[0]?B(new r(t),r.precision,r.rounding):(q=!1,r.modulo==9?(e=re(t,o.abs(),0,3,1),e.s*=o.s):e=re(t,o,0,r.modulo,1),e=e.times(o),q=!0,t.minus(e))};A.naturalExponential=A.exp=function(){return _a(this)};A.naturalLogarithm=A.ln=function(){return Pt(this)};A.negated=A.neg=function(){var o=new this.constructor(this);return o.s=-o.s,B(o)};A.plus=A.add=function(o){var e,t,r,n,i,s,a,l,c,u,d=this,f=d.constructor;if(o=new f(o),!d.d||!o.d)return!d.s||!o.s?o=new f(NaN):d.d||(o=new f(o.d||d.s===o.s?d:NaN)),o;if(d.s!=o.s)return o.s=-o.s,d.minus(o);if(c=d.d,u=o.d,a=f.precision,l=f.rounding,!c[0]||!u[0])return u[0]||(o=new f(d)),q?B(o,a,l):o;if(i=Ee(d.e/M),r=Ee(o.e/M),c=c.slice(),n=i-r,n){for(n<0?(t=c,n=-n,s=u.length):(t=u,r=i,s=c.length),i=Math.ceil(a/M),s=i>s?i+1:s+1,n>s&&(n=s,t.length=1),t.reverse();n--;)t.push(0);t.reverse()}for(s=c.length,n=u.length,s-n<0&&(n=s,t=u,u=c,c=t),e=0;n;)e=(c[--n]=c[n]+u[n]+e)/Ge|0,c[n]%=Ge;for(e&&(c.unshift(e),++r),s=c.length;c[--s]==0;)c.pop();return o.d=c,o.e=mi(c,r),q?B(o,a,l):o};A.precision=A.sd=function(o){var e,t=this;if(o!==void 0&&o!==!!o&&o!==1&&o!==0)throw Error(Bt+o);return t.d?(e=Mu(t.d),o&&t.e+1>e&&(e=t.e+1)):e=NaN,e};A.round=function(){var o=this,e=o.constructor;return B(new e(o),o.e+1,e.rounding)};A.sine=A.sin=function(){var o,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+Math.max(t.e,t.sd())+M,r.rounding=1,t=up(r,qu(r,t)),r.precision=o,r.rounding=e,B(gt>2?t.neg():t,o,e,!0)):new r(NaN)};A.squareRoot=A.sqrt=function(){var o,e,t,r,n,i,s=this,a=s.d,l=s.e,c=s.s,u=s.constructor;if(c!==1||!a||!a[0])return new u(!c||c<0&&(!a||a[0])?NaN:a?s:1/0);for(q=!1,c=Math.sqrt(+s),c==0||c==1/0?(e=ye(a),(e.length+l)%2==0&&(e+="0"),c=Math.sqrt(e),l=Ee((l+1)/2)-(l<0||l%2),c==1/0?e="5e"+l:(e=c.toExponential(),e=e.slice(0,e.indexOf("e")+1)+l),r=new u(e)):r=new u(c.toString()),t=(l=u.precision)+3;;)if(i=r,r=i.plus(re(s,i,t+2,1)).times(.5),ye(i.d).slice(0,t)===(e=ye(r.d)).slice(0,t))if(e=e.slice(t-3,t+1),e=="9999"||!n&&e=="4999"){if(!n&&(B(i,l+1,0),i.times(i).eq(s))){r=i;break}t+=4,n=1}else{(!+e||!+e.slice(1)&&e.charAt(0)=="5")&&(B(r,l+1,1),o=!r.times(r).eq(s));break}return q=!0,B(r,l,u.rounding,o)};A.tangent=A.tan=function(){var o,e,t=this,r=t.constructor;return t.isFinite()?t.isZero()?new r(t):(o=r.precision,e=r.rounding,r.precision=o+10,r.rounding=1,t=t.sin(),t.s=1,t=re(t,new r(1).minus(t.times(t)).sqrt(),o+10,0),r.precision=o,r.rounding=e,B(gt==2||gt==4?t.neg():t,o,e,!0)):new r(NaN)};A.times=A.mul=function(o){var e,t,r,n,i,s,a,l,c,u=this,d=u.constructor,f=u.d,h=(o=new d(o)).d;if(o.s*=u.s,!f||!f[0]||!h||!h[0])return new d(!o.s||f&&!f[0]&&!h||h&&!h[0]&&!f?NaN:!f||!h?o.s/0:o.s*0);for(t=Ee(u.e/M)+Ee(o.e/M),l=f.length,c=h.length,l<c&&(i=f,f=h,h=i,s=l,l=c,c=s),i=[],s=l+c,r=s;r--;)i.push(0);for(r=c;--r>=0;){for(e=0,n=l+r;n>r;)a=i[n]+h[r]*f[n-r-1]+e,i[n--]=a%Ge|0,e=a/Ge|0;i[n]=(i[n]+e)%Ge|0}for(;!i[--s];)i.pop();return e?++t:i.shift(),o.d=i,o.e=mi(i,t),q?B(o,d.precision,d.rounding):o};A.toBinary=function(o,e){return ya(this,2,o,e)};A.toDecimalPlaces=A.toDP=function(o,e){var t=this,r=t.constructor;return t=new r(t),o===void 0?t:(je(o,0,Mt),e===void 0?e=r.rounding:je(e,0,8),B(t,o+t.e+1,e))};A.toExponential=function(o,e){var t,r=this,n=r.constructor;return o===void 0?t=st(r,!0):(je(o,0,Mt),e===void 0?e=n.rounding:je(e,0,8),r=B(new n(r),o+1,e),t=st(r,!0,o+1)),r.isNeg()&&!r.isZero()?"-"+t:t};A.toFixed=function(o,e){var t,r,n=this,i=n.constructor;return o===void 0?t=st(n):(je(o,0,Mt),e===void 0?e=i.rounding:je(e,0,8),r=B(new i(n),o+n.e+1,e),t=st(r,!1,o+r.e+1)),n.isNeg()&&!n.isZero()?"-"+t:t};A.toFraction=function(o){var e,t,r,n,i,s,a,l,c,u,d,f,h=this,p=h.d,m=h.constructor;if(!p)return new m(h);if(c=t=new m(1),r=l=new m(0),e=new m(r),i=e.e=Mu(p)-h.e-1,s=i%M,e.d[0]=pe(10,s<0?M+s:s),o==null)o=i>0?e:c;else{if(a=new m(o),!a.isInt()||a.lt(c))throw Error(Bt+a);o=a.gt(e)?i>0?e:c:a}for(q=!1,a=new m(ye(p)),u=m.precision,m.precision=i=p.length*M*2;d=re(a,e,0,1,1),n=t.plus(d.times(r)),n.cmp(o)!=1;)t=r,r=n,n=c,c=l.plus(d.times(n)),l=n,n=e,e=a.minus(d.times(n)),a=n;return n=re(o.minus(t),r,0,1,1),l=l.plus(n.times(c)),t=t.plus(n.times(r)),l.s=c.s=h.s,f=re(c,r,i,1).minus(h).abs().cmp(re(l,t,i,1).minus(h).abs())<1?[c,r]:[l,t],m.precision=u,q=!0,f};A.toHexadecimal=A.toHex=function(o,e){return ya(this,16,o,e)};A.toNearest=function(o,e){var t=this,r=t.constructor;if(t=new r(t),o==null){if(!t.d)return t;o=new r(1),e=r.rounding}else{if(o=new r(o),e===void 0?e=r.rounding:je(e,0,8),!t.d)return o.s?t:o;if(!o.d)return o.s&&(o.s=t.s),o}return o.d[0]?(q=!1,t=re(t,o,0,e,1).times(o),q=!0,B(t)):(o.s=t.s,t=o),t};A.toNumber=function(){return+this};A.toOctal=function(o,e){return ya(this,8,o,e)};A.toPower=A.pow=function(o){var e,t,r,n,i,s,a=this,l=a.constructor,c=+(o=new l(o));if(!a.d||!o.d||!a.d[0]||!o.d[0])return new l(pe(+a,c));if(a=new l(a),a.eq(1))return a;if(r=l.precision,i=l.rounding,o.eq(1))return B(a,r,i);if(e=Ee(o.e/M),e>=o.d.length-1&&(t=c<0?-c:c)<=sp)return n=Lu(l,a,t,r),o.s<0?new l(1).div(n):B(n,r,i);if(s=a.s,s<0){if(e<o.d.length-1)return new l(NaN);if((o.d[e]&1)==0&&(s=1),a.e==0&&a.d[0]==1&&a.d.length==1)return a.s=s,a}return t=pe(+a,c),e=t==0||!isFinite(t)?Ee(c*(Math.log("0."+ye(a.d))/Math.LN10+a.e+1)):new l(t+"").e,e>l.maxE+1||e<l.minE-1?new l(e>0?s/0:0):(q=!1,l.rounding=a.s=1,t=Math.min(12,(e+"").length),n=_a(o.times(Pt(a,r+t)),r),n.d&&(n=B(n,r+5,1),On(n.d,r,i)&&(e=r+10,n=B(_a(o.times(Pt(a,e+t)),e),e+5,1),+ye(n.d).slice(r+1,r+15)+1==1e14&&(n=B(n,r+1,0)))),n.s=s,q=!0,l.rounding=i,B(n,r,i))};A.toPrecision=function(o,e){var t,r=this,n=r.constructor;return o===void 0?t=st(r,r.e<=n.toExpNeg||r.e>=n.toExpPos):(je(o,1,Mt),e===void 0?e=n.rounding:je(e,0,8),r=B(new n(r),o,e),t=st(r,o<=r.e||r.e<=n.toExpNeg,o)),r.isNeg()&&!r.isZero()?"-"+t:t};A.toSignificantDigits=A.toSD=function(o,e){var t=this,r=t.constructor;return o===void 0?(o=r.precision,e=r.rounding):(je(o,1,Mt),e===void 0?e=r.rounding:je(e,0,8)),B(new r(t),o,e)};A.toString=function(){var o=this,e=o.constructor,t=st(o,o.e<=e.toExpNeg||o.e>=e.toExpPos);return o.isNeg()&&!o.isZero()?"-"+t:t};A.truncated=A.trunc=function(){return B(new this.constructor(this),this.e+1,1)};A.valueOf=A.toJSON=function(){var o=this,e=o.constructor,t=st(o,o.e<=e.toExpNeg||o.e>=e.toExpPos);return o.isNeg()?"-"+t:t};function ye(o){var e,t,r,n=o.length-1,i="",s=o[0];if(n>0){for(i+=s,e=1;e<n;e++)r=o[e]+"",t=M-r.length,t&&(i+=jt(t)),i+=r;s=o[e],r=s+"",t=M-r.length,t&&(i+=jt(t))}else if(s===0)return"0";for(;s%10===0;)s/=10;return i+s}function je(o,e,t){if(o!==~~o||o<e||o>t)throw Error(Bt+o)}function On(o,e,t,r){var n,i,s,a;for(i=o[0];i>=10;i/=10)--e;return--e<0?(e+=M,n=0):(n=Math.ceil((e+1)/M),e%=M),i=pe(10,M-e),a=o[n]%i|0,r==null?e<3?(e==0?a=a/100|0:e==1&&(a=a/10|0),s=t<4&&a==99999||t>3&&a==49999||a==5e4||a==0):s=(t<4&&a+1==i||t>3&&a+1==i/2)&&(o[n+1]/i/100|0)==pe(10,e-2)-1||(a==i/2||a==0)&&(o[n+1]/i/100|0)==0:e<4?(e==0?a=a/1e3|0:e==1?a=a/100|0:e==2&&(a=a/10|0),s=(r||t<4)&&a==9999||!r&&t>3&&a==4999):s=((r||t<4)&&a+1==i||!r&&t>3&&a+1==i/2)&&(o[n+1]/i/1e3|0)==pe(10,e-3)-1,s}function ci(o,e,t){for(var r,n=[0],i,s=0,a=o.length;s<a;){for(i=n.length;i--;)n[i]*=e;for(n[0]+=ga.indexOf(o.charAt(s++)),r=0;r<n.length;r++)n[r]>t-1&&(n[r+1]===void 0&&(n[r+1]=0),n[r+1]+=n[r]/t|0,n[r]%=t)}return n.reverse()}function lp(o,e){var t,r,n;if(e.isZero())return e;r=e.d.length,r<32?(t=Math.ceil(r/3),n=(1/gi(4,t)).toString()):(t=16,n="2.3283064365386962890625e-10"),o.precision+=t,e=Vr(o,1,e.times(n),new o(1));for(var i=t;i--;){var s=e.times(e);e=s.times(s).minus(s).times(8).plus(1)}return o.precision-=t,e}var re=(function(){function o(r,n,i){var s,a=0,l=r.length;for(r=r.slice();l--;)s=r[l]*n+a,r[l]=s%i|0,a=s/i|0;return a&&r.unshift(a),r}function e(r,n,i,s){var a,l;if(i!=s)l=i>s?1:-1;else for(a=l=0;a<i;a++)if(r[a]!=n[a]){l=r[a]>n[a]?1:-1;break}return l}function t(r,n,i,s){for(var a=0;i--;)r[i]-=a,a=r[i]<n[i]?1:0,r[i]=a*s+r[i]-n[i];for(;!r[0]&&r.length>1;)r.shift()}return function(r,n,i,s,a,l){var c,u,d,f,h,p,m,b,w,_,v,E,D,k,C,O,L,z,V,le,_e=r.constructor,ht=r.s==n.s?1:-1,ne=r.d,X=n.d;if(!ne||!ne[0]||!X||!X[0])return new _e(!r.s||!n.s||(ne?X&&ne[0]==X[0]:!X)?NaN:ne&&ne[0]==0||!X?ht*0:ht/0);for(l?(h=1,u=r.e-n.e):(l=Ge,h=M,u=Ee(r.e/h)-Ee(n.e/h)),V=X.length,L=ne.length,w=new _e(ht),_=w.d=[],d=0;X[d]==(ne[d]||0);d++);if(X[d]>(ne[d]||0)&&u--,i==null?(k=i=_e.precision,s=_e.rounding):a?k=i+(r.e-n.e)+1:k=i,k<0)_.push(1),p=!0;else{if(k=k/h+2|0,d=0,V==1){for(f=0,X=X[0],k++;(d<L||f)&&k--;d++)C=f*l+(ne[d]||0),_[d]=C/X|0,f=C%X|0;p=f||d<L}else{for(f=l/(X[0]+1)|0,f>1&&(X=o(X,f,l),ne=o(ne,f,l),V=X.length,L=ne.length),O=V,v=ne.slice(0,V),E=v.length;E<V;)v[E++]=0;le=X.slice(),le.unshift(0),z=X[0],X[1]>=l/2&&++z;do f=0,c=e(X,v,V,E),c<0?(D=v[0],V!=E&&(D=D*l+(v[1]||0)),f=D/z|0,f>1?(f>=l&&(f=l-1),m=o(X,f,l),b=m.length,E=v.length,c=e(m,v,b,E),c==1&&(f--,t(m,V<b?le:X,b,l))):(f==0&&(c=f=1),m=X.slice()),b=m.length,b<E&&m.unshift(0),t(v,m,E,l),c==-1&&(E=v.length,c=e(X,v,V,E),c<1&&(f++,t(v,V<E?le:X,E,l))),E=v.length):c===0&&(f++,v=[0]),_[d++]=f,c&&v[0]?v[E++]=ne[O]||0:(v=[ne[O]],E=1);while((O++<L||v[0]!==void 0)&&k--);p=v[0]!==void 0}_[0]||_.shift()}if(h==1)w.e=u,$u=p;else{for(d=1,f=_[0];f>=10;f/=10)d++;w.e=d+u*h-1,B(w,a?i+w.e+1:i,s,p)}return w}})();function B(o,e,t,r){var n,i,s,a,l,c,u,d,f,h=o.constructor;e:if(e!=null){if(d=o.d,!d)return o;for(n=1,a=d[0];a>=10;a/=10)n++;if(i=e-n,i<0)i+=M,s=e,u=d[f=0],l=u/pe(10,n-s-1)%10|0;else if(f=Math.ceil((i+1)/M),a=d.length,f>=a)if(r){for(;a++<=f;)d.push(0);u=l=0,n=1,i%=M,s=i-M+1}else break e;else{for(u=a=d[f],n=1;a>=10;a/=10)n++;i%=M,s=i-M+n,l=s<0?0:u/pe(10,n-s-1)%10|0}if(r=r||e<0||d[f+1]!==void 0||(s<0?u:u%pe(10,n-s-1)),c=t<4?(l||r)&&(t==0||t==(o.s<0?3:2)):l>5||l==5&&(t==4||r||t==6&&(i>0?s>0?u/pe(10,n-s):0:d[f-1])%10&1||t==(o.s<0?8:7)),e<1||!d[0])return d.length=0,c?(e-=o.e+1,d[0]=pe(10,(M-e%M)%M),o.e=-e||0):d[0]=o.e=0,o;if(i==0?(d.length=f,a=1,f--):(d.length=f+1,a=pe(10,M-i),d[f]=s>0?(u/pe(10,n-s)%pe(10,s)|0)*a:0),c)for(;;)if(f==0){for(i=1,s=d[0];s>=10;s/=10)i++;for(s=d[0]+=a,a=1;s>=10;s/=10)a++;i!=a&&(o.e++,d[0]==Ge&&(d[0]=1));break}else{if(d[f]+=a,d[f]!=Ge)break;d[f--]=0,a=1}for(i=d.length;d[--i]===0;)d.pop()}return q&&(o.e>h.maxE?(o.d=null,o.e=NaN):o.e<h.minE&&(o.e=0,o.d=[0])),o}function st(o,e,t){if(!o.isFinite())return zu(o);var r,n=o.e,i=ye(o.d),s=i.length;return e?(t&&(r=t-s)>0?i=i.charAt(0)+"."+i.slice(1)+jt(r):s>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(o.e<0?"e":"e+")+o.e):n<0?(i="0."+jt(-n-1)+i,t&&(r=t-s)>0&&(i+=jt(r))):n>=s?(i+=jt(n+1-s),t&&(r=t-n-1)>0&&(i=i+"."+jt(r))):((r=n+1)<s&&(i=i.slice(0,r)+"."+i.slice(r)),t&&(r=t-s)>0&&(n+1===s&&(i+="."),i+=jt(r))),i}function mi(o,e){var t=o[0];for(e*=M;t>=10;t/=10)e++;return e}function hi(o,e,t){if(e>ap)throw q=!0,t&&(o.precision=t),Error(Ru);return B(new o(di),e,1,!0)}function it(o,e,t){if(e>wa)throw Error(Ru);return B(new o(fi),e,t,!0)}function Mu(o){var e=o.length-1,t=e*M+1;if(e=o[e],e){for(;e%10==0;e/=10)t--;for(e=o[0];e>=10;e/=10)t++}return t}function jt(o){for(var e="";o--;)e+="0";return e}function Lu(o,e,t,r){var n,i=new o(1),s=Math.ceil(r/M+4);for(q=!1;;){if(t%2&&(i=i.times(e),Nu(i.d,s)&&(n=!0)),t=Ee(t/2),t===0){t=i.d.length-1,n&&i.d[t]===0&&++i.d[t];break}e=e.times(e),Nu(e.d,s)}return q=!0,i}function Du(o){return o.d[o.d.length-1]&1}function Fu(o,e,t){for(var r,n,i=new o(e[0]),s=0;++s<e.length;){if(n=new o(e[s]),!n.s){i=n;break}r=i.cmp(n),(r===t||r===0&&i.s===t)&&(i=n)}return i}function _a(o,e){var t,r,n,i,s,a,l,c=0,u=0,d=0,f=o.constructor,h=f.rounding,p=f.precision;if(!o.d||!o.d[0]||o.e>17)return new f(o.d?o.d[0]?o.s<0?0:1/0:1:o.s?o.s<0?0:o:NaN);for(e==null?(q=!1,l=p):l=e,a=new f(.03125);o.e>-2;)o=o.times(a),d+=5;for(r=Math.log(pe(2,d))/Math.LN10*2+5|0,l+=r,t=i=s=new f(1),f.precision=l;;){if(i=B(i.times(o),l,1),t=t.times(++u),a=s.plus(re(i,t,l,1)),ye(a.d).slice(0,l)===ye(s.d).slice(0,l)){for(n=d;n--;)s=B(s.times(s),l,1);if(e==null)if(c<3&&On(s.d,l-r,h,c))f.precision=l+=10,t=i=a=new f(1),u=0,c++;else return B(s,f.precision=p,h,q=!0);else return f.precision=p,s}s=a}}function Pt(o,e){var t,r,n,i,s,a,l,c,u,d,f,h=1,p=10,m=o,b=m.d,w=m.constructor,_=w.rounding,v=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?(q=!1,u=v):u=e,w.precision=u+=p,t=ye(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(o),t=ye(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 c=hi(w,u+2,v).times(i+""),m=Pt(new w(r+"."+t.slice(1)),u-p).plus(c),w.precision=v,e==null?B(m,v,_,q=!0):m;for(d=m,l=s=m=re(m.minus(1),m.plus(1),u,1),f=B(m.times(m),u,1),n=3;;){if(s=B(s.times(f),u,1),c=l.plus(re(s,new w(n),u,1)),ye(c.d).slice(0,u)===ye(l.d).slice(0,u))if(l=l.times(2),i!==0&&(l=l.plus(hi(w,u+2,v).times(i+""))),l=re(l,new w(h),u,1),e==null)if(On(l.d,u-p,_,a))w.precision=u+=p,c=s=m=re(d.minus(1),d.plus(1),u,1),f=B(m.times(m),u,1),n=a=1;else return B(l,w.precision=v,_,q=!0);else return w.precision=v,l;l=c,n+=2}}function zu(o){return String(o.s*o.s/0)}function ui(o,e){var t,r,n;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(n=e.length;e.charCodeAt(n-1)===48;--n);if(e=e.slice(r,n),e){if(n-=r,o.e=t=t-r-1,o.d=[],r=(t+1)%M,t<0&&(r+=M),r<n){for(r&&o.d.push(+e.slice(0,r)),n-=M;r<n;)o.d.push(+e.slice(r,r+=M));e=e.slice(r),r=M-e.length}else r-=n;for(;r--;)e+="0";o.d.push(+e),q&&(o.e>o.constructor.maxE?(o.d=null,o.e=NaN):o.e<o.constructor.minE&&(o.e=0,o.d=[0]))}else o.e=0,o.d=[0];return o}function cp(o,e){var t,r,n,i,s,a,l,c,u;if(e.indexOf("_")>-1){if(e=e.replace(/(\d)_(?=\d)/g,"$1"),Bu.test(e))return ui(o,e)}else if(e==="Infinity"||e==="NaN")return+e||(o.s=NaN),o.e=NaN,o.d=null,o;if(op.test(e))t=16,e=e.toLowerCase();else if(np.test(e))t=2;else if(ip.test(e))t=8;else throw Error(Bt+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("."),s=i>=0,r=o.constructor,s&&(e=e.replace(".",""),a=e.length,i=a-i,n=Lu(r,new r(t),i,i*2)),c=ci(e,t,Ge),u=c.length-1,i=u;c[i]===0;--i)c.pop();return i<0?new r(o.s*0):(o.e=mi(c,u),o.d=c,q=!1,s&&(o=re(o,n,a*4)),l&&(o=o.times(Math.abs(l)<54?pe(2,l):Wr.pow(2,l))),q=!0,o)}function up(o,e){var t,r=e.d.length;if(r<3)return e.isZero()?e:Vr(o,2,e,e);t=1.4*Math.sqrt(r),t=t>16?16:t|0,e=e.times(1/gi(5,t)),e=Vr(o,2,e,e);for(var n,i=new o(5),s=new o(16),a=new o(20);t--;)n=e.times(e),e=e.times(i.plus(n.times(s.times(n).minus(a))));return e}function Vr(o,e,t,r,n){var i,s,a,l,c=1,u=o.precision,d=Math.ceil(u/M);for(q=!1,l=t.times(t),a=new o(r);;){if(s=re(a.times(l),new o(e++*e++),u,1),a=n?r.plus(s):r.minus(s),r=re(s.times(l),new o(e++*e++),u,1),s=a.plus(r),s.d[d]!==void 0){for(i=d;s.d[i]===a.d[i]&&i--;);if(i==-1)break}i=a,a=r,r=s,s=i,c++}return q=!0,s.d.length=d+1,s}function gi(o,e){for(var t=o;--e;)t*=o;return t}function qu(o,e){var t,r=e.s<0,n=it(o,o.precision,1),i=n.times(.5);if(e=e.abs(),e.lte(i))return gt=r?4:1,e;if(t=e.divToInt(n),t.isZero())gt=r?3:2;else{if(e=e.minus(t.times(n)),e.lte(i))return gt=Du(t)?r?2:3:r?4:1,e;gt=Du(t)?r?1:4:r?3:2}return e.minus(n).abs()}function ya(o,e,t,r){var n,i,s,a,l,c,u,d,f,h=o.constructor,p=t!==void 0;if(p?(je(t,1,Mt),r===void 0?r=h.rounding:je(r,0,8)):(t=h.precision,r=h.rounding),!o.isFinite())u=zu(o);else{for(u=st(o),s=u.indexOf("."),p?(n=2,e==16?t=t*4-3:e==8&&(t=t*3-2)):n=e,s>=0&&(u=u.replace(".",""),f=new h(1),f.e=u.length-s,f.d=ci(st(f),10,n),f.e=f.d.length),d=ci(u,10,n),i=l=d.length;d[--l]==0;)d.pop();if(!d[0])u=p?"0p+0":"0";else{if(s<0?i--:(o=new h(o),o.d=d,o.e=i,o=re(o,f,t,r,0,n),d=o.d,i=o.e,c=$u),s=d[t],a=n/2,c=c||d[t+1]!==void 0,c=r<4?(s!==void 0||c)&&(r===0||r===(o.s<0?3:2)):s>a||s===a&&(r===4||c||r===6&&d[t-1]&1||r===(o.s<0?8:7)),d.length=t,c)for(;++d[--t]>n-1;)d[t]=0,t||(++i,d.unshift(1));for(l=d.length;!d[l-1];--l);for(s=0,u="";s<l;s++)u+=ga.charAt(d[s]);if(p){if(l>1)if(e==16||e==8){for(s=e==16?4:3,--l;l%s;l++)u+="0";for(d=ci(u,n,e),l=d.length;!d[l-1];--l);for(s=1,u="1.";s<l;s++)u+=ga.charAt(d[s])}else u=u.charAt(0)+"."+u.slice(1);u=u+(i<0?"p":"p+")+i}else if(i<0){for(;++i;)u="0"+u;u="0."+u}else if(++i>l)for(i-=l;i--;)u+="0";else i<l&&(u=u.slice(0,i)+"."+u.slice(i))}u=(e==16?"0x":e==2?"0b":e==8?"0o":"")+u}return o.s<0?"-"+u:u}function Nu(o,e){if(o.length>e)return o.length=e,!0}function dp(o){return new this(o).abs()}function fp(o){return new this(o).acos()}function hp(o){return new this(o).acosh()}function pp(o,e){return new this(o).plus(e)}function mp(o){return new this(o).asin()}function gp(o){return new this(o).asinh()}function bp(o){return new this(o).atan()}function wp(o){return new this(o).atanh()}function _p(o,e){o=new this(o),e=new this(e);var t,r=this.precision,n=this.rounding,i=r+4;return!o.s||!e.s?t=new this(NaN):!o.d&&!e.d?(t=it(this,i,1).times(e.s>0?.25:.75),t.s=o.s):!e.d||o.isZero()?(t=e.s<0?it(this,r,n):new this(0),t.s=o.s):!o.d||e.isZero()?(t=it(this,i,1).times(.5),t.s=o.s):e.s<0?(this.precision=i,this.rounding=1,t=this.atan(re(o,e,i,1)),e=it(this,i,1),this.precision=r,this.rounding=n,t=o.s<0?t.minus(e):t.plus(e)):t=this.atan(re(o,e,i,1)),t}function yp(o){return new this(o).cbrt()}function vp(o){return B(o=new this(o),o.e+1,2)}function xp(o,e,t){return new this(o).clamp(e,t)}function kp(o){if(!o||typeof o!="object")throw Error(pi+"Object expected");var e,t,r,n=o.defaults===!0,i=["precision",1,Mt,"rounding",0,8,"toExpNeg",-Ur,0,"toExpPos",0,Ur,"maxE",0,Ur,"minE",-Ur,0,"modulo",0,9];for(e=0;e<i.length;e+=3)if(t=i[e],n&&(this[t]=ba[t]),(r=o[t])!==void 0)if(Ee(r)===r&&r>=i[e+1]&&r<=i[e+2])this[t]=r;else throw Error(Bt+t+": "+r);if(t="crypto",n&&(this[t]=ba[t]),(r=o[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(ju);else this[t]=!1;else throw Error(Bt+t+": "+r);return this}function Ep(o){return new this(o).cos()}function Tp(o){return new this(o).cosh()}function Uu(o){var e,t,r;function n(i){var s,a,l,c=this;if(!(c instanceof n))return new n(i);if(c.constructor=n,Ou(i)){c.s=i.s,q?!i.d||i.e>n.maxE?(c.e=NaN,c.d=null):i.e<n.minE?(c.e=0,c.d=[0]):(c.e=i.e,c.d=i.d.slice()):(c.e=i.e,c.d=i.d?i.d.slice():i.d);return}if(l=typeof i,l==="number"){if(i===0){c.s=1/i<0?-1:1,c.e=0,c.d=[0];return}if(i<0?(i=-i,c.s=-1):c.s=1,i===~~i&&i<1e7){for(s=0,a=i;a>=10;a/=10)s++;q?s>n.maxE?(c.e=NaN,c.d=null):s<n.minE?(c.e=0,c.d=[0]):(c.e=s,c.d=[i]):(c.e=s,c.d=[i]);return}if(i*0!==0){i||(c.s=NaN),c.e=NaN,c.d=null;return}return ui(c,i.toString())}if(l==="string")return(a=i.charCodeAt(0))===45?(i=i.slice(1),c.s=-1):(a===43&&(i=i.slice(1)),c.s=1),Bu.test(i)?ui(c,i):cp(c,i);if(l==="bigint")return i<0?(i=-i,c.s=-1):c.s=1,ui(c,i.toString());throw Error(Bt+i)}if(n.prototype=A,n.ROUND_UP=0,n.ROUND_DOWN=1,n.ROUND_CEIL=2,n.ROUND_FLOOR=3,n.ROUND_HALF_UP=4,n.ROUND_HALF_DOWN=5,n.ROUND_HALF_EVEN=6,n.ROUND_HALF_CEIL=7,n.ROUND_HALF_FLOOR=8,n.EUCLID=9,n.config=n.set=kp,n.clone=Uu,n.isDecimal=Ou,n.abs=dp,n.acos=fp,n.acosh=hp,n.add=pp,n.asin=mp,n.asinh=gp,n.atan=bp,n.atanh=wp,n.atan2=_p,n.cbrt=yp,n.ceil=vp,n.clamp=xp,n.cos=Ep,n.cosh=Tp,n.div=Sp,n.exp=Ap,n.floor=Ip,n.hypot=Cp,n.ln=Dp,n.log=Np,n.log10=$p,n.log2=Op,n.max=Rp,n.min=jp,n.mod=Pp,n.mul=Bp,n.pow=Mp,n.random=Lp,n.round=Fp,n.sign=zp,n.sin=qp,n.sinh=Up,n.sqrt=Vp,n.sub=Wp,n.sum=Gp,n.tan=Hp,n.tanh=Xp,n.trunc=Yp,o===void 0&&(o={}),o&&o.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],e=0;e<r.length;)o.hasOwnProperty(t=r[e++])||(o[t]=this[t]);return n.config(o),n}function Sp(o,e){return new this(o).div(e)}function Ap(o){return new this(o).exp()}function Ip(o){return B(o=new this(o),o.e+1,3)}function Cp(){var o,e,t=new this(0);for(q=!1,o=0;o<arguments.length;)if(e=new this(arguments[o++]),e.d)t.d&&(t=t.plus(e.times(e)));else{if(e.s)return q=!0,new this(1/0);t=e}return q=!0,t.sqrt()}function Ou(o){return o instanceof Wr||o&&o.toStringTag===Pu||!1}function Dp(o){return new this(o).ln()}function Np(o,e){return new this(o).log(e)}function Op(o){return new this(o).log(2)}function $p(o){return new this(o).log(10)}function Rp(){return Fu(this,arguments,-1)}function jp(){return Fu(this,arguments,1)}function Pp(o,e){return new this(o).mod(e)}function Bp(o,e){return new this(o).mul(e)}function Mp(o,e){return new this(o).pow(e)}function Lp(o){var e,t,r,n,i=0,s=new this(1),a=[];if(o===void 0?o=this.precision:je(o,1,Mt),r=Math.ceil(o/M),this.crypto)if(crypto.getRandomValues)for(e=crypto.getRandomValues(new Uint32Array(r));i<r;)n=e[i],n>=429e7?e[i]=crypto.getRandomValues(new Uint32Array(1))[0]:a[i++]=n%1e7;else if(crypto.randomBytes){for(e=crypto.randomBytes(r*=4);i<r;)n=e[i]+(e[i+1]<<8)+(e[i+2]<<16)+((e[i+3]&127)<<24),n>=214e7?crypto.randomBytes(4).copy(e,i):(a.push(n%1e7),i+=4);i=r/4}else throw Error(ju);else for(;i<r;)a[i++]=Math.random()*1e7|0;for(r=a[--i],o%=M,r&&o&&(n=pe(10,M-o),a[i]=(r/n|0)*n);a[i]===0;i--)a.pop();if(i<0)t=0,a=[0];else{for(t=-1;a[0]===0;t-=M)a.shift();for(r=1,n=a[0];n>=10;n/=10)r++;r<M&&(t-=M-r)}return s.e=t,s.d=a,s}function Fp(o){return B(o=new this(o),o.e+1,this.rounding)}function zp(o){return o=new this(o),o.d?o.d[0]?o.s:0*o.s:o.s||NaN}function qp(o){return new this(o).sin()}function Up(o){return new this(o).sinh()}function Vp(o){return new this(o).sqrt()}function Wp(o,e){return new this(o).sub(e)}function Gp(){var o=0,e=arguments,t=new this(e[o]);for(q=!1;t.s&&++o<e.length;)t=t.plus(e[o]);return q=!0,B(t,this.precision,this.rounding)}function Hp(o){return new this(o).tan()}function Xp(o){return new this(o).tanh()}function Yp(o){return B(o=new this(o),o.e+1,1)}A[Symbol.for("nodejs.util.inspect.custom")]=A.toString;A[Symbol.toStringTag]="Decimal";var Wr=A.constructor=Uu(ba);di=new Wr(di);fi=new Wr(fi);var va=Wr;var $n=class{constructor(){throw new Error("The Gramlot browser runtime has no big.js: decimals use decimal.js")}};var Mn={};ee(Mn,{DecodeError:()=>Te,Decoder:()=>Xe,EXT_TIMESTAMP:()=>Ea,Encoder:()=>Gr,ExtData:()=>He,ExtensionCodec:()=>Lt,decode:()=>Ju,decodeArrayStream:()=>td,decodeAsync:()=>ed,decodeMulti:()=>Qu,decodeMultiStream:()=>rd,decodeTimestampExtension:()=>Ca,decodeTimestampToTimeSpec:()=>Ia,encode:()=>_i,encodeDateToTimeSpec:()=>Sa,encodeTimeSpecToTimestamp:()=>Ta,encodeTimestampExtension:()=>Aa});function Vu(o){let e=o.length,t=0,r=0;for(;r<e;){let n=o.charCodeAt(r++);if((n&4294967168)===0){t++;continue}else if((n&4294965248)===0)t+=2;else{if(n>=55296&&n<=56319&&r<e){let i=o.charCodeAt(r);(i&64512)===56320&&(++r,n=((n&1023)<<10)+(i&1023)+65536)}(n&4294901760)===0?t+=3:t+=4}}return t}function Zp(o,e,t){let r=o.length,n=t,i=0;for(;i<r;){let s=o.charCodeAt(i++);if((s&4294967168)===0){e[n++]=s;continue}else if((s&4294965248)===0)e[n++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&i<r){let a=o.charCodeAt(i);(a&64512)===56320&&(++i,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?(e[n++]=s>>12&15|224,e[n++]=s>>6&63|128):(e[n++]=s>>18&7|240,e[n++]=s>>12&63|128,e[n++]=s>>6&63|128)}e[n++]=s&63|128}}var Kp=new TextEncoder,Jp=50;function Qp(o,e,t){Kp.encodeInto(o,e.subarray(t))}function Wu(o,e,t){o.length>Jp?Qp(o,e,t):Zp(o,e,t)}var em=4096;function ka(o,e,t){let r=e,n=r+t,i=[],s="";for(;r<n;){let a=o[r++];if((a&128)===0)i.push(a);else if((a&224)===192){let l=o[r++]&63;i.push((a&31)<<6|l)}else if((a&240)===224){let l=o[r++]&63,c=o[r++]&63;i.push((a&31)<<12|l<<6|c)}else if((a&248)===240){let l=o[r++]&63,c=o[r++]&63,u=o[r++]&63,d=(a&7)<<18|l<<12|c<<6|u;d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|d&1023),i.push(d)}else i.push(a);i.length>=em&&(s+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(s+=String.fromCharCode(...i)),s}var tm=new TextDecoder,rm=200;function nm(o,e,t){let r=o.subarray(e,e+t);return tm.decode(r)}function Gu(o,e,t){return t>rm?nm(o,e,t):ka(o,e,t)}var He=class{type;data;constructor(e,t){this.type=e,this.data=t}};var Te=class o extends Error{constructor(e){super(e);let t=Object.create(o.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:o.name})}};function Hu(o,e,t){let r=t/4294967296,n=t;o.setUint32(e,r),o.setUint32(e+4,n)}function bi(o,e,t){let r=Math.floor(t/4294967296),n=t;o.setUint32(e,r),o.setUint32(e+4,n)}function wi(o,e){let t=o.getInt32(e),r=o.getUint32(e+4);return t*4294967296+r}function Xu(o,e){let t=o.getUint32(e),r=o.getUint32(e+4);return t*4294967296+r}var Ea=-1,om=4294967296-1,im=17179869184-1;function Ta({sec:o,nsec:e}){if(o>=0&&e>=0&&o<=im)if(e===0&&o<=om){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,o),t}else{let t=o/4294967296,r=o&4294967295,n=new Uint8Array(8),i=new DataView(n.buffer);return i.setUint32(0,e<<2|t&3),i.setUint32(4,r),n}else{let t=new Uint8Array(12),r=new DataView(t.buffer);return r.setUint32(0,e),bi(r,4,o),t}}function Sa(o){let e=o.getTime(),t=Math.floor(e/1e3),r=(e-t*1e3)*1e6,n=Math.floor(r/1e9);return{sec:t+n,nsec:r-n*1e9}}function Aa(o){if(o instanceof Date){let e=Sa(o);return Ta(e)}else return null}function Ia(o){let e=new DataView(o.buffer,o.byteOffset,o.byteLength);switch(o.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let t=e.getUint32(0),r=e.getUint32(4),n=(t&3)*4294967296+r,i=t>>>2;return{sec:n,nsec:i}}case 12:{let t=wi(e,4),r=e.getUint32(0);return{sec:t,nsec:r}}default:throw new Te(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${o.length}`)}}function Ca(o){let e=Ia(o);return new Date(e.sec*1e3+e.nsec/1e6)}var Yu={type:Ea,encode:Aa,decode:Ca};var Lt=class o{static defaultCodec=new o;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Yu)}register({type:e,encode:t,decode:r}){if(e>=0)this.encoders[e]=t,this.decoders[e]=r;else{let n=-1-e;this.builtInEncoders[n]=t,this.builtInDecoders[n]=r}}tryToEncode(e,t){for(let r=0;r<this.builtInEncoders.length;r++){let n=this.builtInEncoders[r];if(n!=null){let i=n(e,t);if(i!=null){let s=-1-r;return new He(s,i)}}}for(let r=0;r<this.encoders.length;r++){let n=this.encoders[r];if(n!=null){let i=n(e,t);if(i!=null){let s=r;return new He(s,i)}}}return e instanceof He?e:null}decode(e,t,r){let n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,r):new He(t,e)}};function sm(o){return o instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&o instanceof SharedArrayBuffer}function Rn(o){return o instanceof Uint8Array?o:ArrayBuffer.isView(o)?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):sm(o)?new Uint8Array(o):Uint8Array.from(o)}var am=100,lm=2048,Gr=class o{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Lt.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??am,this.initialBufferSize=e?.initialBufferSize??lm,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 o({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),n=new DataView(t);r.set(this.bytes),this.view=n,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=Vu(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Wu(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=Rn(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 n of e)this.doEncode(n,t+1)}countWithoutUndefined(e,t){let r=0;for(let n of t)e[n]!==void 0&&r++;return r}encodeMap(e,t){let r=Object.keys(e);this.sortKeys&&r.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let i of r){let s=e[i];this.ignoreUndefined&&s===void 0||(this.encodeString(i),this.doEncode(s,t+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),n=r.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),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),Hu(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),bi(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 _i(o,e){return new Gr(e).encodeSharedRef(o)}function yi(o){return`${o<0?"-":""}0x${Math.abs(o).toString(16).padStart(2,"0")}`}var cm=16,um=16,vi=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=cm,t=um){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 n=this.caches[r-1];e:for(let i of n){let s=i.bytes;for(let a=0;a<r;a++)if(s[a]!==e[t+a])continue e;return i.str}return null}store(e,t){let r=this.caches[e.length-1],n={bytes:e,str:t};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=n:r.push(n)}decode(e,t,r){let n=this.find(e,t,r);if(n!=null)return this.hit++,n;this.miss++;let i=ka(e,t,r),s=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(s,i),i}};var Da="array",Bn="map_key",Ku="map_value",dm=o=>{if(typeof o=="string"||typeof o=="number")return o;throw new Te("The type of key must be string or number but "+typeof o)},Na=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let t=this.getUninitializedStateFromPool();t.type=Da,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){let t=this.getUninitializedStateFromPool();t.type=Bn,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===Da){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===Bn||e.type===Ku){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}},Pn=-1,Oa=new DataView(new ArrayBuffer(0)),fm=new Uint8Array(Oa.buffer);try{Oa.getInt8(0)}catch(o){if(!(o 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 Zu=new RangeError("Insufficient data"),hm=new vi,Xe=class o{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Oa;bytes=fm;headByte=Pn;stack=new Na;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Lt.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:hm,this.mapKeyConverter=e?.mapKeyConverter??dm}clone(){return new o({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=Pn,this.stack.reset()}setBuffer(e){let t=Rn(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Pn&&!this.hasRemaining(1))this.setBuffer(e);else{let t=this.bytes.subarray(this.pos),r=Rn(e),n=new Uint8Array(t.length+r.length);n.set(t),n.set(r,t.length),this.setBuffer(n)}}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 a of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);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:n,pos:i,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${yi(n)} at ${s} (${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,n=-1;for await(let i of e){if(t&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(n=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(s){if(!(s instanceof RangeError))throw s}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 n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{let n=e-160;t=this.decodeString(n,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 n=this.lookU8();t=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();t=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();t=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){let n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();t=this.decodeBinary(n,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 n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();t=this.decodeExtension(n,4)}else throw new Te(`Unrecognized type byte: ${yi(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let n=r.top();if(n.type===Da)if(n.array[n.position]=t,n.position++,n.position===n.size)t=n.array,r.release(n);else continue e;else if(n.type===Bn){if(t==="__proto__")throw new Te("The key __proto__ is not allowed");n.key=this.mapKeyConverter(t),n.type=Ku;continue e}else if(n.map[n.key]=t,n.readCount++,n.readCount===n.size)t=n.map,r.release(n);else{n.key=null,n.type=Bn;continue e}}return t}}readHeadByte(){return this.headByte===Pn&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Pn}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 Te(`Unrecognized array type byte: ${yi(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Te(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Te(`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 Te(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Zu;let r=this.pos+t,n;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?n=this.keyDecoder.decode(this.bytes,r,e):n=Gu(this.bytes,r,e),this.pos+=t+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Bn:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new Te(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Zu;let r=this.pos+t,n=this.bytes.subarray(r,r+e);return this.pos+=t+e,n}decodeExtension(e,t){if(e>this.maxExtLength)throw new Te(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let r=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,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=Xu(this.view,this.pos);return this.pos+=8,e}readI64(){let e=wi(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 Ju(o,e){return new Xe(e).decode(o)}function Qu(o,e){return new Xe(e).decodeMulti(o)}function pm(o){return o[Symbol.asyncIterator]!=null}async function*mm(o){let e=o.getReader();try{for(;;){let{done:t,value:r}=await e.read();if(t)return;yield r}}finally{e.releaseLock()}}function xi(o){return pm(o)?o:mm(o)}async function ed(o,e){let t=xi(o);return new Xe(e).decodeAsync(t)}function td(o,e){let t=xi(o);return new Xe(e).decodeArrayStream(t)}function rd(o,e){let t=xi(o);return new Xe(e).decodeStream(t)}var nd=()=>{throw new Error("The Gramlot browser runtime has no @xmldom/xmldom: XML uses the native DOMParser")},Hr=class{constructor(){nd()}},ki=class{constructor(){nd()}};var Ln=va,Fn=$n,at=Mn,od=Hr,id=ki;var sd=at!==null;function ad(){if(!sd)throw new Error("@msgpack/msgpack is required for MessagePack support. Install with: npm install @msgpack/msgpack")}var ld=gm();function gm(){if(!sd)return null;let o=new TextEncoder,e=new TextDecoder,t=new at.ExtensionCodec;return t.register({type:-1,encode:r=>{if(r instanceof Date){let n=bt(r);if(n==="D"||n==="H")return null}return at.encodeTimestampExtension(r)},decode:r=>at.decodeTimestampExtension(r)}),t.register({type:1,encode:r=>U(r)?o.encode(r.toString()):null,decode:r=>Ye(e.decode(r))}),t.register({type:2,encode:r=>{if(r instanceof Date&&bt(r)==="D"){let n=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),s=String(r.getUTCDate()).padStart(2,"0");return o.encode(`${n}-${i}-${s}`)}return null},decode:r=>new Date(e.decode(r)+"T00:00:00.000Z")}),t.register({type:3,encode:r=>{if(r instanceof Date&&bt(r)==="H"){let n=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=String(r.getUTCMilliseconds()).padStart(3,"0");return o.encode(`${n}:${i}:${s}.${a}`)}return null},decode:r=>{let n=e.decode(r),i=n.indexOf("."),s=i>=0?n.substring(0,i):n,a=i>=0?n.substring(i+1):"0",[l,c,u]=s.split(":"),d=Math.round(+a.substring(0,3));return new Date(Date.UTC(1970,0,1,+l,+c,+u,d))}}),t.register({type:4,encode:r=>{let n=$a(r);if(n!==null){let[i,s]=n;return o.encode(`${i}:${s(r)}`)}return null},decode:r=>{let n=e.decode(r),i=n.indexOf(":"),s=n.slice(0,i),a=n.slice(i+1),l=Ft[s];if(l!==void 0){let[,c]=l;return c(a)}return`${a}::${s}`}}),t}function cd(o){return ad(),at.encode(o,{extensionCodec:ld})}function ud(o){return ad(),at.decode(o,{extensionCodec:ld})}function Ei(o,e=!1){let t=Ti(o);if(t===null)return[!1,String(o)];let[r,n,i]=t;return i&&!e?[!1,String(o)]:[!0,`${n(o)}::${r}`]}function Ra(o){if(!o.includes("::"))return[!1,o];let e=o.lastIndexOf("::"),t=o.slice(0,e),r=o.slice(e+2),n=Ft[r];if(n===void 0)return[!1,o];let[,i]=n;return[!0,i(t)]}function Xr(o,e,t){if(o!==null&&typeof o=="object"&&!Array.isArray(o)){let r={};for(let[n,i]of Object.entries(o))r[n]=Xr(i,e,t);return r}return Array.isArray(o)?o.map(r=>Xr(r,e,t)):t(o)?e(o):o}function zn(o){let e=Ti(o);if(e!==null){let[t,r,n]=e;return n?[o,!1]:[`${r(o)}::${t}`,!0]}if(Array.isArray(o)){let t=!1;return[o.map(n=>{let[i,s]=zn(n);return s&&(t=!0),i}),t]}if(o!==null&&typeof o=="object"){let t=!1,r={};for(let[n,i]of Object.entries(o)){let[s,a]=zn(i);a&&(t=!0),r[n]=s}return[r,t]}return[o,!1]}function bm(o,e=!1){let[t,r]=Ei(o,e);if(t)return r;let[n,i]=zn(o),s=JSON.stringify(n);return i?`${s}::JS`:s}function wm(o){return JSON.stringify(o)}function _m(o){if(!at)throw new Error("@msgpack/msgpack is required for MessagePack support");return at.encode(o)}function R(o,e=null,{raw:t=!1,qs:r=!1,_forceSuffix:n=!1}={}){if(r)return`${hd(o)}::QS`;if(t){if(e===null||e==="json")return wm(o);if(e==="msgpack")return _m(o);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=bm(o,n);return e==="json"?`"${i}"`:i}else{if(e==="xml")return`<?xml version="1.0" ?><tytx_root>${fd(o)}</tytx_root>`;if(e==="msgpack")return cd(o);throw new Error(`Unknown transport: ${e}`)}}function dd(o){return Symbol.asyncIterator in o?(async function*(){for await(let t of o)yield zn(t)[0]})():(function*(){for(let t of o)yield zn(t)[0]})()}var Yr,ja;typeof window<"u"&&window.DOMParser?(Yr=window.DOMParser,ja=window.XMLSerializer):(Yr=od,ja=id);function pd(o){if(o===null||typeof o!="object"||Array.isArray(o))return!1;let e=Object.keys(o);if(e.length!==1)return!1;let t=o[e[0]];return t!==null&&typeof t=="object"&&"value"in t}function md(o,e,t){let r=o.createElement(e),n=t.attrs||{},i=t.value;for(let[s,a]of Object.entries(n))r.setAttribute(s,R(a,null,{_forceSuffix:!0}));if(Array.isArray(i))for(let s of i)if(pd(s)){let[a]=Object.keys(s),l=s[a],c=md(o,a,l);r.appendChild(c)}else{r.textContent=R(i);break}else r.textContent=R(i);return r}function fd(o){if(!Yr)throw new Error("XML support requires @xmldom/xmldom package in Node.js");if(pd(o)){let[e]=Object.keys(o),t=o[e],r=new Yr().parseFromString("<root/>","text/xml"),n=md(r,e,t);return new ja().serializeToString(n)}else return R(o)}function Pa(o){let e={};for(let r=0;r<o.attributes.length;r++){let n=o.attributes[r];e[n.name]=j(n.value)}let t=[];for(let r=0;r<o.childNodes.length;r++){let n=o.childNodes[r];n.nodeType===1&&t.push(n)}if(t.length>0)if(t.length===1){let r=t[0],n=Pa(r);return{attrs:e,value:{[r.tagName]:n}}}else{let r=[];for(let n of t){let i=Pa(n);r.push({[n.tagName]:i})}return{attrs:e,value:r}}return{attrs:e,value:j(o.textContent)}}function gd(o){if(!Yr)throw new Error("XML support requires @xmldom/xmldom package in Node.js");let r=new Yr().parseFromString(o,"text/xml").documentElement;if(r.tagName==="tytx_root"){let i=null;for(let s=0;s<r.childNodes.length;s++)if(r.childNodes[s].nodeType===1){i=r.childNodes[s];break}if(!i)return j(r.textContent);r=i}let n=Pa(r);return{[r.tagName]:n}}function Ba(o){return typeof o=="string"}function ym(o){let[e,t]=Ra(o);if(e)return t;let r=o;r.endsWith("::JS")&&(r=r.slice(0,-4));let n;try{n=JSON.parse(r)}catch{return o}return Xr(n,Ma,Ba)}function Ma(o){return o.includes("::")?Ra(o)[1]:o}function vm(o){let e=gd(o);return typeof e=="string"?j(e):e}function xm(o){return ud(o)}function j(o,e=null){if(o===null)return null;if(e===null||e==="json"){let t=o;return e==="json"&&o.startsWith('"')&&o.endsWith('"')&&(t=o.slice(1,-1)),ym(t)}else{if(e==="xml")return vm(o);if(e==="msgpack")return xm(o);throw new Error(`Unknown transport: ${e}`)}}function La(o){return Symbol.asyncIterator in o?(async function*(){for await(let t of o)yield Xr(t,Ma,Ba)})():(function*(){for(let t of o)yield Xr(t,Ma,Ba)})()}function hd(o){if(Array.isArray(o))return o.map(e=>String(e)).join("&");if(o!==null&&typeof o=="object"){let e=[];for(let[t,r]of Object.entries(o)){let[n,i]=Ei(r,!0);n?e.push(`${t}=${i}`):e.push(`${t}=${r}`)}return e.join("&")}throw new TypeError(`toQs expects object or array, got ${typeof o}`)}function bd(o){if(!o)return[];let e=o.split("&"),t=e.map(s=>s.includes("=")),r=t.every(Boolean),n=!t.some(Boolean);if(!r&&!n)throw new Error("QS format error: mixed items with and without '='");if(n)return e.map(s=>j(s));let i={};for(let s of e){let a=s.indexOf("="),l=s.slice(0,a),c=s.slice(a+1);i[l]=j(c)}return i}var qn=Ln||Fn||Number,Un=Ln?"decimal.js":Fn?"big.js":"number";function _d(o){o==="decimal.js"&&Ln?(qn=Ln,Un="decimal.js"):o==="big.js"&&Fn?(qn=Fn,Un="big.js"):(qn=Number,Un="number")}function Zr(){return Un}function Ye(o){return new qn(o)}function U(o){return Un==="number"?!1:o instanceof qn}function bt(o){let e=o.getUTCFullYear()===1970&&o.getUTCMonth()===0&&o.getUTCDate()===1,t=o.getUTCHours()===0&&o.getUTCMinutes()===0&&o.getUTCSeconds()===0&&o.getUTCMilliseconds()===0;return e&&!t?"H":t&&!e?"D":"DHZ"}function km(o){return o.toString()}function Em(o){let e=o.getUTCFullYear(),t=String(o.getUTCMonth()+1).padStart(2,"0"),r=String(o.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}function Tm(o){return o.toISOString()}function Sm(o){let e=String(o.getUTCHours()).padStart(2,"0"),t=String(o.getUTCMinutes()).padStart(2,"0"),r=String(o.getUTCSeconds()).padStart(2,"0"),n=String(o.getUTCMilliseconds()).padStart(3,"0");return`${e}:${t}:${r}.${n}`}function Am(o){return o?"true":"false"}function Im(o){return o.toString()}function Cm(o){return o.toString()}function Dm(o){let e="";for(let t=0;t<o.length;t+=32768)e+=String.fromCharCode.apply(null,o.subarray(t,t+32768));return btoa(e)}var Si=[],Fa=new Map;function $a(o){if(o===null||typeof o!="object")return null;for(let e=Object.getPrototypeOf(o);e!==null;e=Object.getPrototypeOf(e))for(let[t,r,n,i]of Si)if(t.prototype===e)return[r,n,i];return null}function Ti(o){if(o===null)return["NN",()=>"",!0];if(U(o))return["N",km,!1];if(o instanceof Uint8Array)return["RAW",Dm,!1];if(o instanceof Date){let e=bt(o);return e==="D"?["D",Em,!1]:e==="H"?["H",Sm,!1]:["DHZ",Tm,!1]}return typeof o=="boolean"?["B",Am,!0]:typeof o=="number"?Number.isInteger(o)?["L",Im,!0]:["R",Cm,!0]:$a(o)}function Nm(o){return Ye(o)}function Om(o){let[e,t,r]=o.split("-").map(Number);return new Date(Date.UTC(e,t-1,r,0,0,0,0))}function wd(o){return new Date(o)}function $m(o){let[e,t,r]=o.split(":"),[n,i]=r.split(".");return new Date(Date.UTC(1970,0,1,Number(e),Number(t),Number(n),Number(i||0)))}function Rm(o){return o.toLowerCase()==="true"}function jm(o){return parseInt(o,10)}function Pm(o){return parseFloat(o)}function Bm(o){return o}function Mm(o){return null}var Lm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Fm(o){if(!Lm.test(o))throw new Error(`RAW payload is not standard padded base64: '${o}'`);let e=atob(o),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function zm(o){return bd(o)}var qm=/^[A-Z]+$/,Ft={N:[Object,Nm],D:[Date,Om],DH:[Date,wd],DHZ:[Date,wd],H:[Date,$m],L:[Number,jm],R:[Number,Pm],T:[String,Bm],B:[Boolean,Rm],QS:[Object,zm],NN:[null,Mm],RAW:[Uint8Array,Fm]};function Kr(o){return Object.hasOwn(Ft,o)?Ft[o][0]:null}function Vn(o,e,t,r,n=!1){if(typeof e!="string"||!qm.test(e))throw new Error(`TYTX suffix '${e}' is invalid: expected uppercase ASCII letters only`);let i=Ft[e];if(i!==void 0&&i[0]!==o){let s=i[0]===null?"null":i[0].name;throw new Error(`TYTX suffix '${e}' is already registered for ${s}`)}Si=Si.filter(([s])=>s!==o),Si.push([o,e,t,n]),Ft[e]=[o,r]}function yd(o){if(!o.tytxSuffix)throw new Error(`registerClass: ${o.name} is missing a static tytxSuffix`);if(typeof o.prototype?.toTytx!="function")throw new Error(`registerClass: ${o.name} is missing a toTytx method`);if(typeof o.fromTytx!="function")throw new Error(`registerClass: ${o.name} is missing a static fromTytx method`);return Vn(o,o.tytxSuffix,e=>e.toTytx(),e=>o.fromTytx(e),o.tytxJsonNative||!1),o}function wt(o,e){Fa.set(o,e)}function Pe(o){return Fa.has(o)?Fa.get(o):{}}function vd(o,e,t=e.name){let r=Pe(o);if((r[t]??e)!==e)throw new Error(`TYTX subtype name '${t}' is already registered for suffix '${o}' by ${r[t].name}`);wt(o,{...r,[t]:e})}var za={json:"application/json",xml:"application/xml",msgpack:"application/msgpack"};function qa(o){if(!o)return null;let e=o.toLowerCase();return e.includes("jsonl")?"jsonl":e.includes("json")?"json":e.includes("xml")?"xml":e.includes("msgpack")?"msgpack":null}async function Ai(o,e={}){let{body:t,transport:r="json",method:n=t!==void 0?"POST":"GET",headers:i={},...s}=e,a={"X-TYTX-Transport":r,...i},l;if(t!==void 0){a["Content-Type"]=za[r];let h=R(t,r);l=h}let c=await fetch(o,{method:n,headers:a,body:l,...s});if(!c.ok)throw new Error(`HTTP ${c.status}: ${c.statusText}`);let u=c.headers.get("Content-Type")||"",d=qa(u)||r,f;if(d==="msgpack"){let h=await c.arrayBuffer();f=j(Buffer.from(h),d)}else{let h=await c.text();f=j(h,d)}return f}var Um="0.16.4";var rl={};ee(rl,{BuilderBase:()=>Ae,Collection:()=>ut,CustomTypes:()=>hr,DATA_ELEMENT_FIELDS:()=>tl,DATA_ROOT:()=>an,HtmlBuilder:()=>Je,HtmlRenderer:()=>Wt,META_ATTRS:()=>lt,RendererBase:()=>Ut,SOURCE_ROOT:()=>sn,SourceBag:()=>N,SourceBagNode:()=>Se,SvgBuilder:()=>vt,SvgRenderer:()=>Gt,VALUE:()=>cr,XmlRenderer:()=>Vt,pointerDependencies:()=>Ze,pointerExpression:()=>Jr,pointerTemplate:()=>zt,pointerTransform:()=>H,resolveRenderTag:()=>nn,sourceAttributeItems:()=>ge,sourceBagFromTytx:()=>Ri,sourceBagToTytx:()=>Rd,sourceTarget:()=>Z,svgAttributes:()=>Kn,wrapSource:()=>on});function H(o){if(typeof o!="string"||!["^","="].includes(o[0])||o.startsWith("=="))return null;let e=o.indexOf(":");if(e<0)return null;let t=o[e+1]==="=";return{pointer:o.slice(0,e),expression:t,body:o.slice(e+(t?2:1))}}var xd=/^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;function zt(o,e){let t="",r=!1;for(let n=0;n<o.length;){if(o[n]!=="{"&&o[n]!=="}"){t+=o[n++];continue}let i=o.slice(n).match(xd);if(!i)throw new SyntaxError("Invalid pointer template placeholder");let s=i[1]??"",a=s.startsWith("?"),l=e(a?s.slice(1):s);l==null||l===""&&!a?r=!0:t+=String(l),n+=i[0].length}return r?null:t}function Jr(o){let e=[],t=new Set,r="",n=!0;for(let i=0;i<o.length;){let s=i,a=o[i];if(a==='"'||a==="'"||a==="`"){for(i++;i<o.length;){if(o[i]==="\\"){i+=2;continue}if(o[i++]===a)break}r+=o.slice(s,i),n=!1;continue}if(o.startsWith("//",i)){i=o.indexOf(`
|
|
26
|
+
`,i),i<0&&(i=o.length),r+=o.slice(s,i);continue}if(o.startsWith("/*",i)){let u=o.indexOf("*/",i+2);i=u<0?o.length:u+2,r+=o.slice(s,i);continue}if(a==="/"&&n){let u=!1;for(i++;i<o.length;){let d=o[i++];if(d==="\\"){i++;continue}if(d==="[")u=!0;else if(d==="]")u=!1;else if(d==="/"&&!u)break}for(;/[a-z]/i.test(o[i]??"")&&i<o.length;)i++;r+=o.slice(s,i),n=!1;continue}let l=a==="{"?o.slice(i).match(xd):null;if(l){let u=l[1]??"";if(u.startsWith("?"))throw new SyntaxError("Optional slots are supported in pointer templates only");r+=`_pointerValues[${e.length}]`,e.push(u),i+=l[0].length,n=!1;continue}let c=o.slice(i).match(/^[A-Za-z_$][\w$]*/);if(c){t.add(c[0]),r+=c[0],i+=c[0].length,n=["return","typeof","void","delete","new","in","instanceof","yield","await"].includes(c[0]);continue}r+=a,i++,/\s/.test(a)||(n=/[([{,:;=!?&|+*%~<>\/-]/.test(a))}return{text:r,slots:e,identifiers:t}}function kd(o,e,t=()=>null){let r=new Map,n=[],i=s=>{if(r.has(s))return r.get(s);if(!o.has(s))throw new Error(`Referenced Source attribute '${s}' does not exist`);if(n.includes(s))throw new Error(`Cyclic attribute dependency: ${[...n,s].join(" -> ")}`);n.push(s);try{let a=o.get(s),l=typeof s=="string"?H(a):null,c=e.get(s);if(l){let u=d=>d?i(d):e.get(s);if(l.expression){let d=Jr(l.body);c=t(s,a,d,d.slots.map(u))}else c=zt(l.body,u),e.get(s)==null&&(c=null)}return r.set(s,c),c}finally{n.pop()}};return new Map([...o.keys()].map(s=>[s,i(s)]))}function Ze(o,e){let t=new Map([...Object.entries(o.getAttr()),...o.fixedAttrItems()]),r=new Set,n=[],i=s=>{let a=H(s);if(!a)return;let l=[];a.expression?l.push(...Jr(a.body).slots):zt(a.body,c=>(l.push(c),""));for(let c of l.filter(Boolean)){if(!t.has(c))throw new Error(`Referenced Source attribute '${c}' does not exist`);if(n.includes(c))throw new Error(`Cyclic attribute dependency: ${[...n,c].join(" -> ")}`);r.has(c)||(n.push(c),i(t.get(c)),n.pop(),r.add(c))}};return i(e),r}var Za={};ee(Za,{Bag:()=>x,BagCbResolver:()=>_t,BagException:()=>rn,BagNode:()=>qe,BagNodeContainer:()=>Qr,BagResolver:()=>Y,BagSerializationError:()=>ce,OpaqueResolver:()=>lr,RETRY_POLICIES:()=>Va,StorageResolver:()=>Xn,UrlResolver:()=>Gn,UuidResolver:()=>Hn,registerResolver:()=>Ni});var Va={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 Vm(o){let e=o._retryPolicy;return e==null?null:typeof e=="string"?Va[e]||null:e}function Wm(o,e){return e.some(t=>t==="Error"?!0:o.name===t||o.constructor.name===t)}function Gm(o){return new Promise(e=>setTimeout(e,o))}async function Hm(o,e){if(!e)return o();let t=e.maxAttempts||3,r=e.delay||1,n=e.backoff||2,i=e.jitter!==!1,s=e.on||["Error"],a=null,l=r*1e3;for(let c=0;c<t;c++)try{let u=o();return u instanceof Promise?await u:u}catch(u){if(a=u,c<t-1&&Wm(u,s)){let d=l;i&&(d*=1+Math.random()*.1),await Gm(d),l*=n}else throw u}throw a}var Y=class o{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 n=this.constructor.internalParams;for(let[i,s]of Object.entries(r))n.has(i)||(this._kw[i]=s);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 n=this._buildEffectiveKw();if(Object.keys(r).length>0)return this._load({...n,...r},s=>this._prepareValue(s));let i=this._computeEffectiveFingerprint(n);return i===this._lastEffectiveFingerprint&&!this.expired?this.cachedValue:(this._lastEffectiveFingerprint=i,this._load(n,s=>this._finalize(s)))}_load(e,t){let r=Vm(this),n=()=>this.load(e);if(r)return Hm(n,r).then(t);let i=n();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=o._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){o._BagClass=e}load(e){return null}};Y._BagClass=null;var _t=class extends Y{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 qe=class o{constructor(e,t,r=null,n=null,i=null,s=null,a=null,l=!0){this.label=t,this._value=null,this._attr={},this._parentBag=null,this._resolver=null,this._nodeSubscribers={},this._onChangedValue=null,this.nodeTag=s,this.xmlTag=a,this._compiled=null,this.parentBag=e,n&&this.setAttr(n,!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 n=j(`${t}::QS`);if(Array.isArray(n)){let i=n.length?n:Object.keys(this._attr),s=i.map(l=>{let c=this.getAttr(l);return!e&&c instanceof Y?c.resolve():c}),a=l=>n.length===0?Object.fromEntries(i.map((c,u)=>[c,l[u]])):l.length===1?l[0]:l;return s.some(l=>l&&typeof l.then=="function")?Promise.all(s).then(a):a(s)}else{if(!this._resolver)throw new Error("Cannot use kwargs syntax without resolver");r={...r,...n}}}return this._resolver!==null?this._resolver.resolve({static:e,...r}):this._value}setValue(e,t=!0,r=null,n=null,i=!0,s=null,a=!1){e instanceof Y?(this.resolver=e,e=null):e instanceof o&&(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 c=l!==this._value,u=t??!0,d=null;if(r!==null){let h={...this._attr};this.setAttr(r,!1,n,i);let p=this._buildAttrDiff(h,this._attr);d=Object.keys(p).length>0?p:null}t=u&&(c||d!==null);let f=d?c?"upd_value_attr":"upd_attrs":"upd_value";if(this._onChangedValue&&this._onChangedValue(this,e,l,u),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,s,a))}replace(e){if(!(e instanceof o))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 n=this._value,i={...this._attr},s=this.resolver;s&&s._node===this&&(s._node=null),this.resolver=r,this.setValue(t,!1,{...e.attr},!1,!1,null);let a=this._buildAttrDiff(i,this._attr),l=Object.keys(a).length?a:null,c=n!==t||s!==r;if(c||l){let u=l?c?"upd_value_attr":"upd_attrs":"upd_value",d=l?{oldvalue:n,attrs_diff:l}:{oldvalue:n};for(let f of Object.values(this._nodeSubscribers))f({node:this,info:d,evt:u});this._parentBag!==null&&this._parentBag.backref&&this._parentBag._onNodeChanged(this,[this.label],u,n,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={},n=new Set([...Object.keys(e),...Object.keys(t)]);for(let i of n){let s=i in e?e[i]:null,a=i in t?t[i]:null;s!==a&&(r[i]={old:s,new:a})}return r}setAttr(e=null,t=!0,r=!0,n=!0){let i=e||{},s=Object.keys(this._nodeSubscribers).length>0,l=t&&(s||this._parentBag!==null&&this._parentBag.backref)?{...this._attr}:null;if(r?Object.assign(this._attr,i):this._attr={...i},n)for(let c of Object.keys(this._attr))this._attr[c]===null&&delete this._attr[c];if(t&&l!==null){let c=this._buildAttrDiff(l,this._attr);if(Object.keys(c).length>0&&s)for(let u of Object.values(this._nodeSubscribers))u({node:this,info:{attrs_diff:c},evt:"upd_attrs"});if(Object.keys(c).length>0&&this._parentBag!==null&&this._parentBag.backref){let u=t===!0?"true":String(t);this._parentBag._onNodeChanged(this,[this.label],"upd_attrs",null,c,u)}}}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 o)||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 n of t)if(this._attr[n]!==e._attr[n])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(n=>this._attr[n]!==e._attr[n])?`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 Qr=class o{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,n]=t,i=n.includes("::")?j(n):n;return r?this._list.findIndex(s=>s.getAttr(r)===i):this._list.findIndex(s=>s._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 n=this.index(r);if(n<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return n}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 n=this.index(r);if(n<0)throw new Error(`Invalid node_position '${e}': label '${r}' not found`);return n+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=">",n=null,i=null,s=null,a=!1,l=!0,c=null,u=!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)n={[m[0]]:t};else{if(!Array.isArray(t)||t.length!==m.length)throw new Error("Wrong attributes assignment");n={};for(let b=0;b<m.length;b++)n[m[b]]=t[b]}t=null}let p=this._dict[e];if(p)f&&(p.nodeTag=f),s!==null&&(s===!1?p.resolver=null:p.resolver=s),h?p.setAttr(n,u,!0,l):p.setValue(t,u,n,a,l,c,d);else{let m=i&&i.nodeClass?i.nodeClass:qe;p=new m(i,e,h?null:t,n,s,f,null,l);let b=this._parsePosition(r);this._dict[e]=p,this._list.splice(b,0,p),u&&i&&i.backref&&i._onNodeInserted(p,b,null,c,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 n=Array.isArray(e)?e:[e];if(n.length===0||t>=this._list.length)return;let i=this._list[t].label;if(n.length>1){let s=[...n].sort((u,d)=>u-d),a=s[0]<t?1:0,l=[];for(let u=s.length-1;u>=0;u--){let d=s[u];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 c=this.index(i);c<0&&(c=this._list.length),c+=a;for(let u of l)this._list.splice(c,0,u),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(u,c)}else{let s=n[0];if(s===t||s<0||s>=this._list.length)return;let a=this._list[s];this._list.splice(s,1),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeDeleted(a,s),this._list.splice(t,0,a),r&&this._parentBag&&this._parentBag.backref&&this._parentBag._onNodeInserted(a,t)}}isEqual(e){if(!(e instanceof o)||this._list.length!==e._list.length)return!1;for(let t=0;t<this._list.length;t++){let r=this._list[t],n=e._list[t];if(!r.isEqual(n))return!1}return!0}};var Wa="::RSLV:",Ii=new Map,Ci=new Map,Di=new WeakMap,ce=class extends Error{constructor(e){super(e),this.name="BagSerializationError"}},lr=class extends Y{constructor(e){super({asBag:!1}),Di.set(this,e)}get payload(){return Di.get(this)}load(){throw new ce("This resolver is opaque; local execution is unavailable")}};function Ni(o,{module:e,name:t,encode:r,decode:n}){if(!(o.prototype instanceof Y)||o===lr||typeof e!="string"||!e||typeof t!="string"||!t||typeof r!="function"||typeof n!="function")throw new TypeError("registerResolver requires a BagResolver subclass, module, name and adapters");let i=JSON.stringify([e,t]);if(Ii.has(i)&&Ii.get(i).cls!==o)throw new TypeError(`Resolver ${e}.${t} is already registered`);if(Ci.has(o)&&Ci.get(o).key!==i)throw new TypeError("A resolver class cannot own two wire identities");let s={cls:o,module:e,name:t,encode:r,decode:n,key:i};Ii.set(i,s),Ci.set(o,s)}function Ed(o){if(!o||typeof o!="object"||Array.isArray(o)||typeof o.resolver_module!="string"||typeof o.resolver_class!="string"||!Array.isArray(o.args??[])||!o.kwargs||typeof o.kwargs!="object"||Array.isArray(o.kwargs))throw new ce("Invalid resolver description")}function Td(o,e=new Set){if(!(o===null||typeof o=="string"||typeof o=="boolean")&&!(typeof o=="number"&&Number.isFinite(o))){if(typeof o!="object"||e.has(o)||!Array.isArray(o)&&Object.getPrototypeOf(o)!==Object.prototype&&Object.getPrototypeOf(o)!==null)throw new ce("Resolver parameters must be JSON data; callbacks cannot travel");e.add(o);for(let t of Object.values(o))Td(t,e);e.delete(o)}}function Wn(o){if(Di.has(o))return Di.get(o);let e=Ci.get(o.constructor);if(!e)throw new ce(`Unregistered resolver: ${o.constructor.name}`);let t=e.encode(o),r={resolver_module:e.module,resolver_class:e.name,args:t.args??[],kwargs:t.kwargs??{}};return Ed(r),Td(r),Wa+JSON.stringify(r)}function Oi(o){if(typeof o!="string"||!o.startsWith(Wa))return null;let e=o.slice(Wa.length);if(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+$/.test(e))return new lr(o);let t;try{t=JSON.parse(e)}catch{throw new ce("Invalid resolver JSON or signed token")}Ed(t);let r=Ii.get(JSON.stringify([t.resolver_module,t.resolver_class]));if(!r)return new lr(o);let n=r.decode({args:t.args??[],kwargs:t.kwargs});if(!(n instanceof r.cls))throw new ce("Resolver decoder returned an incompatible instance");return n}function $i(o){return Object.fromEntries(Object.entries(o||{}).map(([e,t])=>[e,t instanceof Y?Wn(t):t]))}function Ga(o){return Object.fromEntries(Object.entries(o||{}).map(([e,t])=>[e,Oi(t)??t]))}var Ke="__cls";function en(o,e){return o!==null&&o.tytxSuffix===e?o:Kr(e)}function Xm(o){let e=o.tytxSuffix,t=Object.entries(Pe(e)).filter(([,r])=>r===o).map(([r])=>r);if(t.length===0)throw new ce(`${o.name} is not in the TYTX subtype dictionary of '${e}'`);if(t.length>1)throw new ce(`${o.name} is in the TYTX subtype dictionary of '${e}' under several names: ${t.sort().join(", ")}`);return t[0]}function Ha(o,e){let t=Pe(o);if(!Object.hasOwn(t,e))throw new ce(`Unknown Bag class '${e}' for TYTX type '${o}'`);return t[e]}function Xa(o,e){return o===e?null:Xm(o)}function*Ad(o,e=[]){for(let t of o){let r=[...e,t.label];yield[r,t];let n=t.getValue(!0);!t.resolver&&n instanceof x&&(yield*Ad(n,r))}}function Ym(o){let e=o.toISOString(),t=o.getUTCFullYear()===1970&&o.getUTCMonth()===0&&o.getUTCDate()===1,r=o.getUTCHours()===0&&o.getUTCMinutes()===0&&o.getUTCSeconds()===0&&o.getUTCMilliseconds()===0;if(r&&!t)return e.slice(0,e.indexOf("T"));let n=e.replace(/\.000Z$/,"Z");return t&&!r?n.slice(n.indexOf("T")+1):n}function tn(o){if(o===null||typeof o!="object")return!1;let e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function qt(o){return typeof o=="string"?o.includes("::")?`${o}::T`:o:Array.isArray(o)?o.map(qt):tn(o)?Object.fromEntries(Object.entries(o).map(([e,t])=>[e,qt(t)])):o}function Ya(o){if(!tn(o))throw new TypeError("Bag options must be an object");let{recursive:e=!0}=o;if(typeof e!="boolean")throw new TypeError("recursive must be a boolean");return e}var Sd=!1,x=class o{static tytxSuffix="X";constructor(e=null,t={}){this._nodes=new Qr,this._backref=!1,this._parent=null,this._parentNode=null,this._rootAttributes=null,this._updSubscribers={},this._insSubscribers={},this._delSubscribers={},Ya(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 qe}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(n=>n)):r=[...e];r.length&&r[0]==="#parent"&&t!==null;)r.shift(),t=t.parent;return[t,r]}_htraverse(e,t=!1,r=!0){let[n,i]=this._htraverseBefore(e);if(n===null)return[null,null];if(i.length===0)return[n,""];for(;i.length>1&&n instanceof o;){let s=i[0];if(s==="#parent"){if(n.parent===null||n.parent===void 0)break;i.shift(),n=n.parent;continue}let a=n._nodes.get(s);if(!a)break;let l=a.getValue(r);if(l instanceof o)i.shift(),n=l;else if(t){let c=n.createChildBag();a.setValue(c,!0,null,!0,!0,"autocreate"),i.shift(),n=c}else break}if(!t)return i.length>1?[null,null]:[n,i[0]];for(;i.length>1;){let s=i.shift();if(s.startsWith("#"))throw new rn("Not existing index in #n syntax");let a=n.createChildBag();n._nodes.set(s,a,">",null,n,null,!1,!0,"autocreate"),n=a}return[n,i[0]]}get(e,t=null,r=!0,n={}){if(!e)return this;if(e==="#parent")return this.parent;let i=null;e.includes("?")&&([e,i]=e.split("?",2));let s=this._nodes.get(e);return s?s.getValue(r,i,n):t}getItem(e,t=null,r=!1,n={}){if(!e)return this;let[i,s]=this._htraverse(e,!1,r);return i instanceof o?i.get(s,t,r,n):t}setItem(e,t,r=null,n=">",i=!1,s=!0,a=null,l=!1,c=!0,u=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,n,r,f,u,i,s,a,c,l,d)}_pop(e,t=null){let r=this._nodes.index(e);if(r>=0){let n=this._nodes.pop(r);return this.backref&&this._onNodeDeleted(n,r,null,t),n}return null}pop(e,t=null,r=null){let n=this.popNode(e,r);return n?n.value:t}delItem(e,t=null,r=null){return this.pop(e,t,r)}popNode(e,t=null){let[r,n]=this._htraverse(e,!1,!0);if(!r||!n)return null;let i=r._nodes.get(n);if(!i)return null;try{return r._pop(n,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,n=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,s]=this._htraverse(e,r,t);if(i instanceof o&&s){let a=i._nodes.get(s);if(a)return a;if(r)return i._nodes.set(s,n,">",null,i,null,!1,!0,"autocreate"),i._nodes.get(s)}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 n of this)n.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 o&&t.clearBackref()}}}_onNodeChanged(e,t,r,n=null,i=null,s=null,a=!1){for(let l of Object.values(this._updSubscribers))l({node:e,pathlist:t,oldvalue:n,attrs_diff:i,evt:r,reason:s,fired:a});this._parent&&this._parentNode&&this._parent._onNodeChanged(e,[this._parentNode.label,...t],r,n,i,s,a)}_onNodeInserted(e,t,r=null,n=null,i=!1){let s=e.parentBag,a=e.getValue(!0);s!==null&&s.backref&&a instanceof o&&a.setBackref(e,s),r===null&&(r=[]);for(let l of Object.values(this._insSubscribers))l({node:e,pathlist:r,ind:t,evt:"ins",reason:n,fired:i});this._parent&&this._parentNode&&this._parent._onNodeInserted(e,t,[this._parentNode.label,...r],n,i)}_onNodeDeleted(e,t,r=null,n=null){for(let i of Object.values(this._delSubscribers))i({node:e,pathlist:r,ind:t,evt:"del",reason:n});this._parent&&this._parentNode&&(r===null&&(r=[]),this._parent._onNodeDeleted(e,t,[this._parentNode.label,...r],n))}_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:n=null,delete:i=null,any:s=null}=t;this.backref||this.setBackref(),this._subscribe(e,this._updSubscribers,r||s),this._subscribe(e,this._insSubscribers,n||s),this._subscribe(e,this._delSubscribers,i||s)}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:n=!1,delete:i=!1,any:s=!1}=t;(r||s)&&delete this._updSubscribers[e],(n||s)&&delete this._insSubscribers[e],(i||s)&&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 n=o.prototype.getNode.call(this,e,!0,!0);n&&n.setAttr(t,!0,!0,r)}getAttr(e=null,t=null,r=null){let n=this.getNode(e);return n?n.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 n=r.value;if(n instanceof o){if(n.getItem(e)===t)return r}else if(n&&n.get&&n.get(e)===t)return r}return null}getNodeByAttr(e,t,r=!1,n=!1){let i=t===void 0,s=r&&typeof t=="string"?t.toLowerCase():t,a=l=>{let c=[];for(let u of l._nodes){if(e in u.attr){let d=r&&typeof u.attr[e]=="string"?u.attr[e].toLowerCase():u.attr[e];if(i||d==s)return u}if(u._value instanceof o)if(n){let d=a(u._value);if(d)return d}else c.push(u._value)}for(let u of c){let d=a(u);if(d)return d}return null};return a(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 n=r.getValue(!0);if(n!=null&&!(e&&n===0)&&!(t&&n===""))return!1}return!0}query(e=null,t=null,r=!1,n=!1,i=!0,s=!0,a=null,l=!0){e||(e="#k,#v,#a");let c=this,u;if(typeof e=="string"){if(e.includes(":")){let[h,p]=e.split(":");c=this.getItem(h),e=p}u=e.split(",").map(h=>h.trim())}else u=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 o?null:_}else if(p.startsWith("#v.")){let _=p.split(".").slice(1).join("."),v=w();return v&&v.getItem?v.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,v=!1,E,D=()=>(v||(E=w.getValue(l),v=!0),E);if((i&&s||(D()instanceof o?s:i))&&(t===null||t(w))&&(yield u.length===1?d(w,u[0],_,n,D):u.map(C=>d(w,C,_,n,D)),h++,a!==null&&h>=a))return;if(n){let C=D();if(C instanceof o&&(yield*p(C,_),a!==null&&h>=a))return}}}yield*p(c,"")}return r?f():[...f()]}getLeaves(){let e=[],t=(r,n)=>{for(let i of r._nodes){let s=n?`${n}.${i.label}`:i.label,a=i.getValue(!1);a instanceof o?t(a,s):e.push([s,a])}};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 n=this.query(e,t,!1,!1,!0,!0,null,!1);if(r){if(!n||n.length===0)return(typeof e=="string"?e:"#k,#v,#a").split(",").map(l=>l.trim()).map(()=>[]);let i=[...n];if(i.length&&Array.isArray(i[0])){let s=i[0].length,a=[];for(let l=0;l<s;l++)a.push(i.map(c=>c[l]));return a}return[i]}return[...n]}columns(e,t=!1){typeof e=="string"&&(e=e.split(","));let r=t?"#a.":"",n=e.map(i=>`${r}${i}`).join(",");return this.digest(n,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 n=i=>{let s=0,a=!1;for(let l of this.query(i,r)){if(l==null||l===""){a=!0;continue}if(typeof l!="number"&&typeof l!="boolean"){if(t)throw new TypeError(`sum encountered non-numeric value: ${typeof l}`);continue}s+=l}return t&&a?null:s};return e.includes(",")?e.split(",").map(i=>n(i.trim())):n(e)}sort(e="#k:a"){let t=(n,i)=>n==null?[-1,""]:i&&typeof n=="string"?[0,n.toLowerCase()]:[0,n],r=(n,i)=>n[0]!==i[0]?n[0]-i[0]:n[1]<i[1]?-1:n[1]>i[1]?1:0;if(typeof e=="function")this._nodes._list.sort((n,i)=>{let s=e(n),a=e(i);return s<a?-1:s>a?1:0});else{let n=e.split(",");n.reverse();for(let i of n){let s,a;i.includes(":")?[s,a]=i.split(":",2):(s=i,a="a"),s=s.trim(),a=a.trim();let l=a==="d"||a==="D",c=a==="a"||a==="d",u;if(s.toLowerCase()==="#k")u=d=>t(d.label,c);else if(s.toLowerCase()==="#v")u=d=>t(d.value,c);else if(s.toLowerCase().startsWith("#a.")){let d=s.slice(3);u=f=>t(f.getAttr(d),c)}else u=d=>{let f=d.value,h=f instanceof o?f.getItem(s):f?f[s]:null;return t(h,c)};this._nodes._list.sort((d,f)=>{let h=r(u(d),u(f));return l?-h:h})}}return this}equalTo(e){return e instanceof o?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(n=>n 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 n=new _t({callback:t,...r});this.setResolver(e,n)}move(e,t,r=!0){this._nodes.move(e,t,r)}asDict(e=!1,t=!1,r=!1,n=!1){let i={};for(let s of this._nodes){let a=s.value;if(n&&a==null)continue;let l=s.label;e&&(l=String(l)),t&&(l=l.toLowerCase()),r&&a instanceof o&&(a=o.prototype.asDict.call(a,e,t,r,n)),Object.defineProperty(i,l,{value:a,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 n=r.getValue(!e);n instanceof o&&(n=n.deepcopy(e));let i=new t.nodeClass(t,r.label,n);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,n=!1){if(!(e instanceof o)){for(let i in e){let s=e[i];(!n||s!==null||!this._nodes.has(i))&&this.setItem(i,s,null,">",!1,!1,r,!1,r!==!1)}return}for(let i of[...e]){let s=i.label,a=t==="static"?i.resolver:null,l=a?null:i.getValue(),c=i.attr.__replace;delete i.attr.__replace;let u=this._nodes.get(s);if(u)if(u.setAttr(i.attr,r===null?!0:r,!0,!1),i.nodeTag!=null&&(u.nodeTag=i.nodeTag),i.xmlTag!=null&&(u.xmlTag=i.xmlTag),a)u.resolver=a,u.setValue(null,r===null?!0:r,null,null,!1,r);else{i.resolver&&(u.resolver=null);let d=u.getValue();l instanceof o&&d instanceof o&&!c?d.update(l,t,r,n):(!n||l!==null)&&u.setValue(l,r===null?!0:r,null,null,!1,r)}else{let d=this.setItem(s,a||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,n=null,i=null){if(typeof e!="string")throw new TypeError("Bag labels must be strings");let s=new this.nodeClass(this,e,null,r,n,i,null,!1);return t instanceof Y?s.resolver=t:s._value=t,this._nodes._dict[e]=s,this._nodes._list.push(s),s}fillFrom(e=null,t={}){let r=Ya(t);if(e!=null&&!tn(e)&&!Array.isArray(e))throw new TypeError("Bag source must be a dictionary, array or null");let n=this.createChildBag(),i=new Set,s=(a,l,c)=>{if(i.has(l))throw new TypeError(`Cyclic Bag source at ${c}`);i.add(l);try{let u=Array.isArray(l)?String(l.length).length+1:0,d=Array.isArray(l)?Array.from(l,(f,h)=>[`r_${String(h).padStart(u,"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 ${c}`);for(let[f,h]of d){let p=h;r&&(tn(p)||Array.isArray(p))&&(p=this.createChildBag(),s(p,h,`${c}[${JSON.stringify(f)}]`)),a._appendLiteral(f,p)}}finally{i.delete(l)}};return e!=null&&s(n,e,"$"),this._replacePrepared(n)}_loadSource(e,t={}){return this.fillFrom(e,t)}replace(e){if(!(e instanceof o))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 n=r.getValue(!0);n instanceof o&&n.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:n={}}={}){if(typeof e!="function")throw new TypeError("forEach requires a callback");let i=(s,a)=>{for(let l=0;l<s._nodes.length;l++){let c=s._nodes._list[l],u={...a};"_pathlist"in a&&(u._pathlist=[...a._pathlist,c.label]),"_indexlist"in a&&(u._indexlist=[...a._indexlist,l]);let d=e(c,u,l);if(d)return d;if(d==null&&r){let f=c.getValue(t);if(f instanceof o){let h=i(f,u);if(h)return h}}}return null};return i(this,n)}*traverse(){for(let e of this._nodes){yield e;let t=e.getValue(!0);t instanceof o&&(yield*t.traverse())}}*_iterNodesWithPaths(e=!0,t=""){for(let r of this._nodes){let n=t?`${t}.${r.label}`:r.label;yield[n,r];let i=r.getValue(e);i instanceof o&&(yield*i._iterNodesWithPaths(e,n))}}*_nodeFlattener(e=null){let t=e!==null,r=t?Object.create(null):null,n=0,i=new Map([["[]",this.constructor]]);for(let[s,a]of Ad(this)){let l=s.slice(0,-1),c=JSON.stringify(s),u=JSON.stringify(l),d=a.getValue(!0),f,h=null;if(a.resolver)f=Wn(a.resolver);else if(d instanceof o){let b=d.constructor,w=b.tytxSuffix;i.set(c,b),h=Xa(b,en(i.get(u),w)),f=`::${w}`}else d===null?f="::NN":f=qt(d);if(a.attr&&Object.hasOwn(a.attr,Ke))throw new ce(`node '${s}': the attribute '${Ke}' is reserved for the Bag class name`);let p=$i(qt(a.attr));h!==null&&(p[Ke]=h);let m=a.nodeTag;t?(yield[l.length?r[u]:null,a.label,m,f,p],d instanceof o&&(r[c]=n,e[n]=s,n++)):yield[l,a.label,m,f,p]}}toTytx(e="json",t=!1){let r=this._toTytxPayload(t),n=this.constructor.tytxSuffix;if(e==="json")return`${r}::${n}`;if(e==="msgpack")return _i(new He(4,new TextEncoder().encode(`${n}:${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,n=Xa(r,en(null,r.tytxSuffix));return n!==null&&(t[Ke]=n),t.rows=t.rows.map(([i,s,a,l,c])=>[qt(i),qt(s),qt(a),l,c]),t.paths&&(t.paths=qt(t.paths)),R(t)}static fromTytx(e,t="json",r={}){if(tn(t)&&(r=t,t="json"),Ya(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 n=j(e,t==="json"?null:t);if(n instanceof o)return n;if(!tn(n)&&!Array.isArray(n))throw new TypeError("fromTytx requires a dictionary, array or typed Bag root");return new this(n,r)}static _fromTytxPayload(e){let t=this.tytxSuffix;if(e==="")return new(en(null,t));let r=j(e);if(!r||!Array.isArray(r.rows))throw new ce("Invalid TYTX Bag: expected rows");let n=r.paths,i=n!=null,s=Object.hasOwn(r,Ke)?Ha(t,r[Ke]):en(null,t),a=new s,l=new Map([["[]",a]]);for(let c of r.rows){if(!Array.isArray(c)||c.length!==5)throw new ce("Invalid TYTX Bag row");let[u,d,f,h,p]=c,m=u??"";if(i){if(u!==null&&!Object.hasOwn(n,u))throw new ce(`Unknown TYTX parent reference: ${u}`);m=u===null?"":n[u]}if(typeof m=="string"&&(m=m?m.split("."):[]),!Array.isArray(m))throw new ce("Invalid TYTX parent path");let b=JSON.stringify(m);if(!l.has(b))throw new ce(`Missing or undecodable TYTX parent branch: ${m}`);let w=l.get(b),_=JSON.stringify([...m,d]),v=h,E=Oi(v),D=Ga(p),k=Object.hasOwn(D,Ke)?D[Ke]:null;if(delete D[Ke],v instanceof o){let O=v.constructor.tytxSuffix,L=k!==null?Ha(O,k):en(w.constructor,O);v=new L,l.set(_,v)}else if(k!==null)throw new ce(`node '${_}': the attribute '${Ke}' is reserved for the Bag class name of a branch`);let C=w._appendLiteral(d,E?null:v,D,E);C.nodeTag=f??null}return a}toXml(e={}){let{pretty:t=!1,encoding:r="UTF-8",docHeader:n=null,selfClosedTags:i=null}=e,s=this._bagToXml(i,t);return n===!0?s=`<?xml version='1.0' encoding='${r}'?>
|
|
27
|
+
${s}`:typeof n=="string"&&(s=`${n}
|
|
28
|
+
${s}`),s}_bagToXml(e=null,t=!1,r=0){let n=[];for(let i of this._nodes)n.push((t?" ".repeat(r):"")+this._nodeToXml(i,e,t,r));return n.join(t?`
|
|
29
|
+
`:"")}_nodeToXml(e,t=null,r=!1,n=0){let i=e.xmlTag||e.nodeTag||e.label,s=this._sanitizeTag(i),a=[];if(s!==i&&a.push(`_tag="${this._escapeAttr(i)}"`),e.resolver&&a.push(`_resolver="${this._escapeAttr(Wn(e.resolver))}"`),e.attr)for(let[f,h]of Object.entries($i(e.attr)))h!==null&&h!==!1&&h!==void 0&&a.push(`${f}="${this._escapeAttr(String(h))}"`);let l=a.length?" "+a.join(" "):"",c=e.resolver?null:e.getValue(!0);if(c&&typeof c._bagToXml=="function"){r=r&&e.attr?.["xml:space"]!=="preserve";let f=c._bagToXml(t,r,n+1);return f?r?`<${s}${l}>
|
|
35
30
|
${f}
|
|
36
|
-
${" ".repeat(
|
|
37
|
-
`)}toString(e=!0,t=null,r=""){t||(t=new Set);let
|
|
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.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.address=o,this.parent||this.open()}open(){let e=this.address;e.searchParams.set("pageId",this.gramlot.pageId),this.socket=new this.window.WebSocket(e.href),this.socket.addEventListener("open",()=>this.connected()),this.socket.addEventListener("message",t=>{try{this.deliver(t.data)}catch(r){this.fail(r)}}),this.socket.addEventListener("error",()=>this.fail(new Error("PageStore WebSocket failed"))),this.socket.addEventListener("close",t=>{this.closed||this.fail(new Error("PageStore disconnected ("+t.code+")"))})}peerChanged(e){if(this.closed||!e.parent||!this.parent)return;let t=e.channels.server;t?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")):(this.parent=null,this.open())}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}
|
|
31
|
+
${" ".repeat(n)}</${s}>`:`<${s}${l}>${f}</${s}>`:t===null||t.includes(s)?`<${s}${l}/>`:`<${s}${l}></${s}>`}if(c==null||c==="")return t===null||t.includes(s)?`<${s}${l}/>`:`<${s}${l}></${s}>`;let u=c instanceof Date&&!Number.isNaN(c.getTime())?Ym(c):String(c),d=this._escapeXml(u);return`<${s}${l}>${d}</${s}>`}_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,n;if(typeof DOMParser<"u"){n=new DOMParser().parseFromString(e,"application/xml");let s=n.querySelector("parsererror");if(s)throw new Error(`XML parse error: ${s.textContent}`)}else n=new Hr().parseFromString(e,"application/xml");return this._xmlElementToBag(n.documentElement,r)}static _xmlElementToBag(e,t=null){let r=new this,n=Array.from(e.childNodes).filter(i=>i.nodeType===1);for(let i of n){let s=i.tagName,a={};for(let m=0;m<i.attributes.length;m++){let b=i.attributes[m];a[b.name]=b.value}let l=Oi(a._resolver);l&&delete a._resolver;let c=String(a._T||"").toUpperCase()==="BAG";Object.assign(a,Ga(a));let u=s;"_tag"in a&&(u=a._tag,delete a._tag),t&&t in a&&(u=a[t],delete a[t]);let d=u,f=1;for(;r.getNode(u);)u=`${d}_${f++}`;let h=Array.from(i.childNodes).filter(m=>m.nodeType===1),p;if(h.length>0||c){let m=this._xmlElementToBag(i,t);p=r.setItem(u,m,Object.keys(a).length>0?a:null)}else{let m=i.textContent||"";p=r.setItem(u,m,Object.keys(a).length>0?a:null)}l&&(p.resolver=l),p.xmlTag=s}return r}static async fromUrl(e,t={}){let{timeout:r=30}=t,n={};r&&(n.signal=AbortSignal.timeout(r*1e3));let i=await fetch(e,n),s=i.headers.get("content-type")||"",a=await i.text();if(s.includes("json"))return o.fromTytx(a);if(s.includes("xml"))return o.fromXml(a);let l=a.trim();if(l.startsWith("<"))return o.fromXml(a);if(l.startsWith("{")||l.startsWith("["))return o.fromTytx(a);throw new rn(`Unsupported content-type: ${s}`)}toJson(e=!0){let t=[];for(let r of this._nodes)t.push(this._nodeToJsonDict(r,e));return e?R(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 s of r._nodes)i.push(r._nodeToJsonDict(s,t));r=i}let n={label:e.label,value:r,attr:$i(e.attr)};return e.nodeTag!==null&&(n.tag=e.nodeTag),e.resolver&&(n.resolver=Wn(e.resolver)),n}static fromJson(e,t={}){return Sd||(console.warn("Bag.fromJson is deprecated; use Bag.fromTytx"),Sd=!0),this.fromTytx(e,"json",t)}toStringTree(e=!0,t=null,r="",n=!0){t===null&&(t=new Map);let i=[],s=[...this._nodes];for(let a=0;a<s.length;a++){let l=s[a],c=a===s.length-1,u=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=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",m=r+(c?" ":"\u2502 ");if(u instanceof o){let b=l,w=u.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 _=u.toStringTree(e,t,m,c);_&&i.push(_)}}else{let b;if(u===null)b="null";else if(u===void 0)b="undefined";else if(u instanceof ArrayBuffer||u instanceof Uint8Array){let w=new TextDecoder("utf-8",{fatal:!1}),_=u instanceof ArrayBuffer?new Uint8Array(u):u;b=w.decode(_)}else typeof u=="string"?u.length>50?b=JSON.stringify(u.slice(0,47)+"..."):b=JSON.stringify(u):b=String(u);i.push(`${r}${p}${l.label}: ${b}${f}`)}}return i.join(`
|
|
32
|
+
`)}toString(e=!0,t=null,r=""){t||(t=new Set);let n=[],i=[...this._nodes];for(let s=0;s<i.length;s++){let a=i[s],l=s===i.length-1,c=a.getValue(e),u="",d=a.attr;d&&Object.keys(d).length>0&&(u=` [${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(c&&typeof c._htraverse=="function"){let p=a;if(t.has(p))n.push(`${r}${f}${a.label}${u} \u2192 (circular ref)`);else{t.add(p),n.push(`${r}${f}${a.label}${u}`);let m=c.toString(e,t,h);m&&n.push(m)}}else{let p;c==null?p="null":typeof c=="string"&&c.length>50?p=JSON.stringify(c.slice(0,47)+"..."):typeof c=="string"?p=JSON.stringify(c):p=String(c),n.push(`${r}${f}${a.label}: ${p}${u}`)}}return n.join(`
|
|
33
|
+
`)}},rn=class extends Error{constructor(e){super(e),this.name="BagException"}};Y.registerBagClass(x);Vn(x,"X",o=>o._toTytxPayload(),o=>x._fromTytxPayload(o));wt(x.tytxSuffix,{...Pe(x.tytxSuffix),Bag:x});var Gn=class extends Y{static classKwargs={cacheTime:300,readOnly:!0,retryPolicy:{maxAttempts:3,delay:1,backoff:2,jitter:!0,on:["TypeError","NetworkError","AbortError"]},asBag:!1,url:null,method:"get",qs:null,body:null,timeout:5,transport:"json"};static classArgs=["url"];static internalParams=new Set(["cacheTime","readOnly","retryPolicy","asBag"]);constructor(e,t={}){typeof e=="string"?t={...t,url:e}:t=e||{},super(t)}async load(e){let t=e.url,r=e.method,n=e.qs,i=e.timeout,s=e.transport,a=e.body;e._body!==void 0&&(a=e._body);let l=[],c={};for(let[h,p]of Object.entries(e))if(h.startsWith("arg_")&&p!==null&&p!==void 0){let m=parseInt(h.slice(4),10);if(!isNaN(m)){for(;l.length<=m;)l.push(null);l[m]=p}}else!this.constructor.classKwargs.hasOwnProperty(h)&&!this.constructor.internalParams.has(h)&&!h.startsWith("_")&&p!=null&&(c[h]=p);l.length>0&&t.includes("{")&&(t.match(/\{([^}]+)\}/g)||[]).forEach((p,m)=>{m<l.length&&l[m]!==null&&(t=t.replace(p,String(l[m])))});let u={};if(n&&Object.assign(u,this._qsToDict(n)),Object.assign(u,c),Object.keys(u).length>0){let h=new URLSearchParams;for(let[m,b]of Object.entries(u))b!=null&&h.append(m,String(b));let p=t.includes("?")?"&":"?";t=`${t}${p}${h.toString()}`}let d={method:r.toUpperCase(),transport:s};return i&&(d.signal=AbortSignal.timeout(i*1e3)),a!=null&&(d.body=a),await Ai(t,d)}_qsToDict(e){if(!e)return{};if(typeof e.keys=="function"&&typeof e.getItem=="function"){let r={};for(let n of e.keys()){let i=e.getItem(n);i!=null&&(r[n]=i)}return r}let t={};for(let[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}};var Hn=class extends Y{static classKwargs={cacheTime:-1,readOnly:!1,asBag:!1,retryPolicy:null,version:"uuid4"};static classArgs=["version"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy","version"]);load(){return globalThis.crypto.randomUUID()}};var Xn=class extends Y{static classKwargs={cacheTime:-1,readOnly:!0,asBag:!1,retryPolicy:null,key:null,storageType:"local",defaultValue:null,dtype:null};static classArgs=["key"];static internalParams=new Set(["cacheTime","readOnly","asBag","retryPolicy"]);constructor(e,t={}){typeof e=="string"?t={...t,key:e}:t=e||{},super(t)}_getStorage(e){return(e.storageType||"local")==="session"?typeof sessionStorage<"u"?sessionStorage:null:typeof localStorage<"u"?localStorage:null}load(e){let t=e.key,r=e.defaultValue,n=t?this._getStorage(e):null,i=n?n.getItem(t):null,s=i!==null?i:r;if(e.dtype==null||s==null)return s;let a=String(s);if(e.dtype==="L"&&!/^[+-]?\d+(?:_\d+)*$/.test(a.trim()))throw new TypeError(`Invalid integer in Web Storage: ${a}`);if(e.dtype==="R"&&!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(a.trim()))throw new TypeError(`Invalid real number in Web Storage: ${a}`);let l=e.dtype==="L"?a.replaceAll("_",""):a,c=j(`${l}::${e.dtype}`);if(typeof c=="number"&&Number.isNaN(c)||c instanceof Date&&Number.isNaN(c.getTime()))throw new TypeError(`Invalid ${e.dtype} value in Web Storage: ${a}`);return c}};var Id=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 Cd(o){return o.endsWith("_")&&Id.has(o.slice(0,-1))?o.slice(0,-1):o}function Dd(o){let e=Cd(o);return e!==o?e:o.startsWith("_")&&Id.has(o.slice(1))?o.slice(1):o}function nn(o,{renderTag:e=null,ns:t=null,dialectName:r=null}={}){let n=e||o;if(!n)return n;if(n=Cd(n),t&&!e){let i=`${r}_`;n.startsWith(i)&&(n=n.slice(i.length)),n=`${t}:${n}`}return n}var cr=Symbol("value"),lt=new Set(["_meta","datapath","nodeId","ns","form","formId","_anchor","updateOn"]);function ge(o){return Object.entries(o||{}).filter(([e])=>!lt.has(e)).map(([e,t])=>[Dd(e),t])}var Se=class extends qe{constructor(e,t,r=null,n=null,i=null,s=null,a=null){super(e,t,r,n,i,s,a),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(n=>n.trim());return r.length===1?t[r[0]]!==void 0?t[r[0]]:null:r.map(n=>t[n]!==void 0?t[n]: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 ge(this.getAttr())}runtimeToEvaluate(){let e=new Map(this.fixedAttrItems());return e.set(cr,this.value),e}absDatapath(e){let t=e;this.pointerType(e)&&(e=(H(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 n=r.getAttr("datapath");n!=null&&(e=e==="."?n:n+e),r=r.parentNode}if(e.startsWith("."))throw new Error(`unresolved relative datapath: ${t}`);return e}_collapseParentDatapath(e,t){let r=[];for(let n of e.split("."))if(n==="#parent"){if(r.length===0)throw new Error(`#parent has no segment to cancel: ${t}`);r.pop()}else r.push(n);return r.join(".")}_resolveSymbolicDatapath(e,t){let r=e.slice(1),n=r.indexOf("."),i=n===-1?r:r.slice(0,n),s=n===-1?"":r.slice(n+1),a;if(i==="FORM")a=this._findMarkedDatapathAncestor(!0,!1,t);else if(i==="ANCHOR")a=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(a=l.source.getNodeByAttr("nodeId",i),a==null)throw new Error(`#<id>: cannot resolve ${t}`)}return a.absDatapath(s?`.${s}`:".")}_findMarkedDatapathAncestor(e,t,r){let n=this;for(;n!=null;){let s=n.getAttr()||{};if(e&&(s.formId!=null||s.form===!0)||t&&"_anchor"in s)return n;n=n.parentNode}let i=e?"FORM":"ANCHOR";throw new Error(`#${i}: no marked ancestor found for ${r}`)}getRelativeData(e,t=null,{autocreate:r=!1}={}){let n=this.data,i=this.absDatapath(e);return r&&n.getItem(i)==null&&n.setItem(i,t),n.getItem(i,t)}setRelativeData(e,t,{attributes:r=null,fired:n=!1,reason:i=null}={}){let s=this.data,a=this.absDatapath(e);s.setItem(a,t,r,">",!1,!0,i===null?!0:i,n)}fireEvent(e,t=!0,{attributes:r=null,reason:n=null}={}){this.setRelativeData(e,t,{attributes:r,fired:!0,reason:n})}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})}},N=class o extends x{constructor(e=null,t=null){super(e),this._builder=t,this._insertingBuilder=null}get nodeClass(){return Se}_setBuilderItem(e,t,r,...n){let i=t?.map(([a])=>[a,a._builder])||null;if(t)for(let[a,l]of t)a._builder=l;let s=this._insertingBuilder;this._insertingBuilder=e;try{return this.setItem(r,...n)}catch(a){if(this.node(r)==null&&i)for(let[l,c]of i)l._builder=c;throw a}finally{this._insertingBuilder=s}}bindBuilder(e){if(!e)throw new Error("SourceBag.bindBuilder requires a builder");let t=this._builderBindingPlan(e);for(let[r,n]of t)r._builder=n;return this.setBackref(),this}_builderBindingPlan(e){let t=[],r=new WeakSet,n=(i,s)=>{if(r.has(i))throw new Error("source contains a cyclic or shared SourceBag branch");r.add(i),t.push([i,s]);for(let a of i.getNodes()){let l=s,c=a._getMeta("subbuilder");c!=null&&(l=s._resolveSubbuilderReference(c,a.getAttr()||{},a.nodeTag)),t.push([a,l]);let u=a.getValue(!0);u instanceof o&&n(u,l)}};return n(this,e),t}};if((Pe(N.tytxSuffix).SourceBag??N)!==N)throw new Error("TYTX subtype name 'SourceBag' is already registered for another class");wt(N.tytxSuffix,{...Pe(N.tytxSuffix),SourceBag:N});function Zm(o){if(o.length===0)return{value:null,attrs:{}};let e=o[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:o[1]||{}}}var Km=new Set(["then","toJSON"]),Od=new WeakMap;function Z(o){return Od.get(o)||o}function on(o){if(o==null)return o;o=Z(o);let e=o._builder||o.parentBag&&o.parentBag._builder;return e?e.wrapSource(o):o}function $d(o,e){let t=e instanceof x,r=new Proxy(e,{get(n,i){if(typeof i=="symbol"||i.startsWith("_")||Km.has(i))return Reflect.get(n,i,n);let s=o.schemaTag(i);if(t&&s)return Nd(o,n,s,t);if(i in n){let l=Reflect.get(n,i,n);return typeof l=="function"?l.bind(n):l}if(s)return Nd(o,n,s,t);let a=o.containerMethod(i);if(a)return(...l)=>o[a](o.wrapSource(n),...l)}});return Od.set(r,e),r}function Nd(o,e,t,r){return(...n)=>{let{value:i,attrs:s}=Zm(n),a=r?o.bagCall(e,t,i,s):o.commandOnNode(e,t,i,s);return a.builder.wrapSource(a)}}function Rd(o,{transport:e="json"}={}){if(!(o instanceof N))throw new TypeError("sourceBagToTytx requires a SourceBag");return R(o,e==="json"?null:e)}function Ri(o,e,{transport:t="json"}={}){let r=j(o,t==="json"?null:t);if(!(r instanceof N))throw new TypeError("TYTX payload did not decode to SourceBag");return r.bindBuilder(e)}var Pd=/^[A-Za-z_][A-Za-z0-9_]*$/,Jm=new Set(["positional_only","positional_or_keyword","keyword_only","var_positional","var_keyword"]),Qm=new Set(["framework","value","attribute"]),eg=new Map([["builtins.str",o=>typeof o=="string"],["builtins.int",o=>Number.isInteger(o)],["builtins.float",o=>typeof o=="number"&&Number.isFinite(o)],["builtins.bool",o=>typeof o=="boolean"],["builtins.list",o=>Array.isArray(o)],["builtins.dict",o=>o!==null&&typeof o=="object"&&!Array.isArray(o)],["builtins.tuple",o=>Array.isArray(o)],["builtins.set",o=>Array.isArray(o)||o instanceof Set],["builtins.NoneType",o=>o===null],["builtins.object",o=>!0]]);function dr(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}function $(o,e){throw new TypeError(`${o}: ${e}`)}function ct(o,e,t,r){dr(o)||$(r,"must be an object");for(let n of Object.keys(o))e.includes(n)||$(r,`unknown field '${n}'`);for(let n of t)Object.hasOwn(o,n)||$(r,`missing field '${n}'`)}function fr(o,e){if(!(o===null||typeof o=="string"||typeof o=="boolean")&&!(typeof o=="number"&&Number.isFinite(o))){if(Array.isArray(o))return o.forEach((t,r)=>fr(t,`${e}[${r}]`));if(dr(o))return Object.entries(o).forEach(([t,r])=>fr(r,`${e}.${t}`));$(e,"must be lossless JSON data")}}function tg(o,e){let t="",r=!1;for(let n=0;n<o.length;n++){let i=o[n];if(i==="\\"){t+=i+(o[++n]??"");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 ur(o,e,t=!1,r=null){if(o===null)return null;switch(ct(o,["kind","dtype","module","name","origin","arguments","items","values","base","metadata","pattern","flags","ge","le","gt","lt","value"],["kind"],e),o.kind){case"custom":return ct(o,["kind","name"],["kind","name"],e),r||$(e,"custom references require a catalog; nested catalog references are unsupported"),r.resolve(o.name,e);case"dtype":{ct(o,["kind","dtype"],["kind","dtype"],e);let n=o.dtype;typeof n!="string"&&$(e,"dtype must be a string");let i=Kr(n);return!i&&n!=="NN"&&$(e,`unknown dtype '${n}'`),{...o,test:a=>n==="NN"?a===null:n==="N"?U(a)&&!["NaN","Infinity","-Infinity"].includes(a.toString()):i===Number?typeof a=="number"&&Number.isFinite(a)&&(n!=="L"||Number.isInteger(a)):i===String?typeof a=="string":i===Boolean?typeof a=="boolean":i===Date?a instanceof Date&&Number.isFinite(a.getTime()):i===Object?dr(a)&&[Object.prototype,null].includes(Object.getPrototypeOf(a)):a instanceof i}}case"any":return{...o,test:n=>!0};case"type":{(typeof o.module!="string"||typeof o.name!="string")&&$(e,"type requires string module/name");let n=`${o.module}.${o.name}`;if(n==="collections.abc.Callable")return{...o,test:s=>typeof s=="function",portable:!1};let i=eg.get(n);return i||$(e,`unsupported type '${n}'`),{...o,test:i}}case"union":{(!Array.isArray(o.items)||!o.items.length)&&$(e,"union items must be non-empty");let n=o.items.map((i,s)=>ur(i,`${e}.items[${s}]`,!0,r));return{...o,items:n,inputConstraint:n.some(i=>i.inputConstraint),test:i=>n.some(s=>s.test&&s.test(i))}}case"literal":return Array.isArray(o.values)||$(e,"literal values must be an array"),o.values.forEach((n,i)=>fr(n,`${e}.values[${i}]`)),{...o,test:n=>o.values.some(i=>Object.is(i,n))};case"annotated":{Array.isArray(o.metadata)||$(e,"annotated metadata must be an array"),o.metadata.some(s=>!["regex","range","value"].includes(s?.kind))&&$(e,"unsupported annotation metadata kind");let n=ur(o.base,`${e}.base`,!0,r),i=o.metadata.map((s,a)=>ur(s,`${e}.metadata[${a}]`,!0,r));return{...o,base:n,metadata:i,inputConstraint:n.inputConstraint,test:s=>n.test(s)&&i.every(a=>!a.test||a.test(s))}}case"range":{for(let n of["ge","le","gt","lt"])Object.hasOwn(o,n)||$(e,`range missing '${n}'`);for(let n of["ge","le","gt","lt"])o[n]!==null&&(typeof o[n]!="number"||!Number.isFinite(o[n]))&&$(e,`${n} must be finite number or null`);return{...o,test:n=>typeof n=="number"&&(o.ge===null||n>=o.ge)&&(o.le===null||n<=o.le)&&(o.gt===null||n>o.gt)&&(o.lt===null||n<o.lt)}}case"regex":{(typeof o.pattern!="string"||!Number.isInteger(o.flags)||o.flags<0)&&$(e,"regex requires pattern and non-negative integer flags");let n=o.flags&-59;n&&$(e,`unsupported Python regex flags ${n}`),o.flags&2&&$(e,"IGNORECASE is not portable across Python and JavaScript Unicode rules"),/\\[AZzUwWdDsSabBN0-9]|\(\?P[<=!]|\(\?\(|\(\?>|\(\?#|\(\?[aiLmsux-]|[+*?}]\+|\{,/.test(o.pattern.replaceAll(String.raw`[\s\S]`,"."))&&$(e,"regex uses a non-portable construct or character class");let i="uy";o.flags&16&&(i+="s");let s;try{s=new RegExp(`(?:${tg(o.pattern,o.flags)})(?![\\s\\S])`,i)}catch(a){$(e,`invalid portable regex: ${a.message}`)}return{...o,test:a=>typeof a!="string"?!1:(s.lastIndex=0,s.test(a))}}case"value":return fr(o.value,`${e}.value`),{...o};case"generic":{let n=ur(o.origin,`${e}.origin`,!0,r);(o.origin?.kind!=="type"||o.origin.module!=="builtins"||!["list","dict","tuple","set"].includes(o.origin.name))&&$(e,"only list, dict, tuple and set generic origins are supported"),Array.isArray(o.arguments)||$(e,"generic arguments must be an array");let i=o.arguments.map((s,a)=>ur(s,`${e}.arguments[${a}]`,!0,r));return{...o,origin:n,arguments:i,inputConstraint:i.some(s=>s.inputConstraint),test:s=>n.test(s)&&rg(o.origin,i,s)}}case"arguments":$(e,"Callable argument-list descriptors are not supported by Python validation");case"ellipsis":return t||$(e,"ellipsis is only valid as a nested descriptor"),{...o};default:$(e,`unknown annotation kind '${o.kind}'`)}}function rg(o,e,t){let r=`${o.module}.${o.name}`;return r==="builtins.tuple"&&e.length&&e[1]?.kind!=="ellipsis"?t.length===e.length&&t.every((n,i)=>e[i].test(n)):r==="builtins.list"||r==="builtins.set"||r==="builtins.tuple"?[...t].every(n=>!e[0]?.test||e[0].test(n)):r==="builtins.dict"?Object.entries(t).every(([n,i])=>(!e[0]?.test||e[0].test(n))&&(!e[1]?.test||e[1].test(i))):!1}function Bd(o,e){if(o===null)return null;if(typeof o!="string"&&$(e,"must be string or null"),o==="")return new Map;let t=new Map;for(let r of o.split(",")){let n=r.trim();/^[A-Za-z_][A-Za-z0-9_]*\[\]$/.test(n)&&$(e,`invalid cardinality item '${r}'`);let i=n.match(/^([A-Za-z_][A-Za-z0-9_]*|\*)(?:\[(?:(\d+)|(?:(\d*):(\d*)))\])?$/);i||$(e,`invalid cardinality item '${r}'`);let[,s,a,l,c]=i;t.has(s)&&$(e,`duplicate tag '${s}'`);let u=0,d=1/0;n.includes("[")&&(n.includes(":")?(u=l?Number(l):0,d=c?Number(c):1/0):u=d=Number(a)),d<u&&$(e,`maximum ${d} is below minimum ${u}`),t.set(s,{min:u,max:d})}return t.has("*")&&t.size>1&&$(e,"wildcard '*' cannot be combined with named tags"),t}function Md(o,e){if(o===null)return null;typeof o!="string"&&$(e,"must be string or null");let t=new Set;for(let r of o.split(",")){let n=r.trim();n&&((!Pd.test(n)||t.has(n))&&$(e,`invalid or duplicate parent '${r}'`),t.add(n))}return t}function ng(o,e,t){if(o===null)return null;ct(o,["parameters","accepts_var_keyword","accepts_var_positional"],[],e);let r=o.parameters??[];Array.isArray(r)||$(e,"parameters must be an array"),o={parameters:r,accepts_var_keyword:r.some(l=>l.kind==="var_keyword"),accepts_var_positional:r.some(l=>l.kind==="var_positional"),...o},(!Array.isArray(o.parameters)||typeof o.accepts_var_keyword!="boolean"||typeof o.accepts_var_positional!="boolean")&&$(e,"invalid signature descriptor");let n=new Set,i=!1,s=!1,a=o.parameters.map((l,c)=>{let u=`${e}.parameters[${c}]`;return ct(l,["name","kind","role","annotation","has_default","default"],["name","kind","role","annotation","has_default"],u),(typeof l.name!="string"||!Pd.test(l.name)||n.has(l.name))&&$(u,"invalid or duplicate parameter name"),n.add(l.name),(!Jm.has(l.kind)||!Qm.has(l.role)||typeof l.has_default!="boolean")&&$(u,"invalid kind, role, or has_default"),l.has_default!==Object.hasOwn(l,"default")&&$(u,"default presence must equal has_default"),l.has_default&&fr(l.default,`${u}.default`),i||=l.kind==="var_keyword",s||=l.kind==="var_positional",{...l,annotation:ur(l.annotation,`${u}.annotation`,!1,t)}});return(i!==o.accepts_var_keyword||s!==o.accepts_var_positional)&&$(e,"variadic summary flags do not match parameters"),{...o,parameters:a}}function jd(o,e,t,r){let n=["doc","sub_tags","parent_tags","inherits_from","ns","attributes",...t?["node_label","collection_key"]:[],"_meta"];ct(o,n,[],e),o={...Object.fromEntries(n.map(i=>[i,null])),...o};for(let i of["doc","inherits_from","ns",...t?["node_label","collection_key"]:[]])o[i]!==null&&typeof o[i]!="string"&&$(e,`${i} must be string or null`);return o._meta!==null&&(dr(o._meta)||$(e,"_meta must be object or null"),fr(o._meta,`${e}._meta`)),Bd(o.sub_tags,`${e}.sub_tags`),Md(o.parent_tags,`${e}.parent_tags`),{...o,attributes:ng(o.attributes,`${e}.attributes`,r)}}function Ld(o){return o?o.split(",").map(e=>e.trim()).filter(Boolean):[]}function Fd(o,e){let t={...e};for(let[r,n]of Object.entries(o))r==="inherits_from"||r.startsWith("_")||t[r]||(t[r]=n);return t._meta={...o._meta||{},...e._meta||{}},t}function zd(o){let e={...o};return e._subSpec=Object.hasOwn(e,"sub_tags")?Bd(e.sub_tags,"resolved.sub_tags"):null,e._parentSpec=Object.hasOwn(e,"parent_tags")?Md(e.parent_tags,"resolved.parent_tags"):null,e}function qd(o,e,t,r){if(t.get(o)===1&&$(r,`inheritance cycle at '${o}'`),t.get(o)===2)return e[o];let n=e[o];n||$(r,`unknown abstract '${o}'`),t.set(o,1);let i={...n};for(let s of Ld(n.inherits_from))i=Fd(qd(s,e,t,r),i);return i=zd(i),t.set(o,2),e[o]=i,i}function Ka({abstracts:o={},elements:e={}}){let t={...o},r=new Map;for(let i of Object.keys(t))qd(i,t,r,`abstracts.${i}.inherits_from`);let n={};for(let[i,s]of Object.entries(e)){let a={...s};for(let l of Ld(s.inherits_from)){let c=t[l];c||$(`elements.${i}.inherits_from`,`unknown abstract '${l}'`),a=Fd(c,a)}n[i]=zd(a)}return{abstracts:t,elements:n}}function Ja(o){ct(o,["document_format","grammar","abstracts","elements","custom_types"],["document_format","grammar","abstracts","elements"],"grammar document"),ct(o.document_format,["name","version"],["name","version"],"document_format"),(o.document_format.name!=="builder_grammar"||!["1.1","1.2"].includes(o.document_format.version))&&$("document_format","expected builder_grammar version 1.1 or 1.2"),ct(o.grammar,["name","version","title","description"],["name","version","title","description"],"grammar"),(typeof o.grammar.name!="string"||!o.grammar.name)&&$("grammar.name","must be non-empty string");for(let n of["version","title","description"])o.grammar[n]!==null&&typeof o.grammar[n]!="string"&&$(`grammar.${n}`,"must be string or null");(!dr(o.abstracts)||!dr(o.elements))&&$("grammar document","abstracts/elements must be objects"),Object.hasOwn(o,"custom_types")&&o.document_format.version!=="1.2"&&$("custom_types","requires version 1.2");let e=hr.fromJSON(o.custom_types??{}),t={};for(let[n,i]of Object.entries(o.abstracts))(!n||n.startsWith("_"))&&$("abstracts",`invalid public name '${n}'`),t[n]=jd(i,`abstracts.${n}`,!1,e);let r={};for(let[n,i]of Object.entries(o.elements))(!n||n.startsWith("_"))&&$("elements",`invalid public name '${n}'`),r[n]=jd(i,`elements.${n}`,!0,e);return{grammar:structuredClone(o.grammar),abstracts:t,elements:r}}function Ud(o,e,t,r){let n=e.attributes;if(!n)return;let i={...r};t!=null&&(i.node_value=t);let s=new Set(n.parameters.filter(c=>c.role==="attribute").map(c=>c.name)),a=new Set(["node_label","node_position","nodeId","target_id","datapath","iterate","store","_tag","_meta","ns"]);if(!n.accepts_var_keyword)for(let c of Object.keys(r))!s.has(c)&&!a.has(c)&&$(o,`unknown attribute '${c}'`);let l=e._meta?.component?n.parameters.find(c=>c.role!=="framework"&&["positional_only","positional_or_keyword"].includes(c.kind))?.name:null;for(let c of n.parameters){if(c.name===l||c.role==="framework"||c.kind.startsWith("var_"))continue;let u=Object.hasOwn(i,c.name);!u&&!c.has_default&&$(o,`missing required ${c.role} '${c.name}'`),u&&c.annotation!==null&&(!c.annotation.test||!c.annotation.test(i[c.name]))&&$(o,`invalid value for ${c.role} '${c.name}'`)}}var hr=class o{#e=new Map;#t=new Map;register(e,t,r){let n=new Map([[String,"str"],[Number,"float"],["string","str"],["integer","int"],["number","float"]]),i=n.has(t)?{kind:"type",module:"builtins",name:n.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)||og.has(e))&&$("custom_types",`invalid, reserved or duplicate name '${e}'`),ct(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))&&$(`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))&&$(`custom_types.${e}`,"portable Regex requires str; portable Range requires int or float"),fr(t,`custom_types.${e}`);let n=structuredClone(t),i=ur(n,`custom_types.${e}`),s=Object.freeze({kind:"custom",name:e});return Object.defineProperty(this,e,{value:s,enumerable:!0}),this.#e.set(e,n),this.#t.set(e,{...s,inputConstraint:!0,test:i.test}),s}resolve(e,t="custom_types"){return this.#t.has(e)||$(t,`unknown custom type '${e}'`),{...this.#t.get(e)}}validate(e,t){return this.resolve(e).test(t)||$(`custom_types.${e}`,"invalid input value"),!0}toJSON(){return structuredClone(Object.fromEntries(this.#e))}static fromJSON(e){dr(e)||$("custom_types","must be an object");let t=new o;for(let[r,n]of Object.entries(e))t.#r(r,n);return t}},og=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 Vd(o,e,t,r){let n=e?.attributes;if(n)for(let i of n.parameters){if(!i.annotation?.inputConstraint||i.role==="framework"||["var_keyword","var_positional"].includes(i.kind))continue;let s=i.role==="value"?t:r[i.name];s!==void 0&&(i.annotation.test(s)||$(o,`invalid input for '${i.name}' (custom type)`))}}function Wd(o,e,t=[]){if(e===null)return structuredClone(o);if(t.length===2&&t[0]==="custom_types"&&o!==void 0){if(!Qa(o,e))throw new TypeError(`conflicting custom type '${t[1]}'`);return structuredClone(o)}if(t.length===2&&["abstracts","elements"].includes(t[0]))return structuredClone(e);if(yt(o)&&yt(e)){let r=structuredClone(o);for(let[n,i]of Object.entries(e))i!==null&&Object.defineProperty(r,n,{value:Wd(r[n],i,[...t,n]),enumerable:!0,writable:!0,configurable:!0});return r}return structuredClone(e)}function Qa(o,e){return Object.is(o,e)?!0:Array.isArray(o)&&Array.isArray(e)?o.length===e.length&&o.every((t,r)=>Qa(t,e[r])):yt(o)&&yt(e)?Object.keys(o).length===Object.keys(e).length&&Object.keys(o).every(t=>Object.hasOwn(e,t)&&Qa(o[t],e[t])):!1}function yt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)&&Object.getPrototypeOf(o)===Object.prototype}function el(o){if(!(o===null||typeof o=="string"||typeof o=="boolean")&&!(typeof o=="number"&&Number.isFinite(o))){if(Array.isArray(o)){o.forEach(el);return}if(yt(o)){Object.values(o).forEach(el);return}throw new TypeError("collection must contain only finite JSON values")}}var ut=class o{#e;constructor(e){el(e);let t=["document_format","grammar","abstracts","elements"];if(!yt(e)||Object.keys(e).some(n=>![...t,"custom_types"].includes(n))||t.some(n=>!Object.hasOwn(e,n)))throw new TypeError("collection requires document_format, grammar, abstracts and elements");let r=e.document_format;if(!yt(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 n of["grammar","abstracts","elements"])if(!yt(e[n]))throw new TypeError(`${n} must be an object`);if(Object.hasOwn(e,"custom_types")&&(r.version!=="1.2"||!yt(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 o(e),r=Wd(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 Ut=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,[n,i]=r.runtimeValues(e);if(e._getMeta("data_element"))return null;if(e._getMeta("component"))return this._renderComponent(e,i,t);let s=this.getRender(r),a;return[a,i]=s._handleMeta(e,i),e._getMeta("subbuilder")||(i=s.adaptAttrs(i)),e.value instanceof N&&(n=this.renderChildren(e.value,t)),s.renderedItem(e,n,i,{tag:a,...t})}renderChildren(e,t={}){let r=[];for(let n of e.getNodes()){let i=this.render(n,t);i!==null&&(Array.isArray(i)?r.push(...i):r.push(i))}return r}_renderComponent(e,t,r){let[n,i,s,a]=this._expansionInputs(e,t);if(!Object.hasOwn(e.getAttr(),"iterate"))return this._expandBlock(e,n,s,a,r);if(i==null)return[];if(!(i instanceof x))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,n,s,{node_label:l.label},r))}_expansionInputs(e,t){let r=e.builder,n=r.componentMethod(e.nodeTag),i=n&&r[n];if(typeof i!="function")throw new Error(`component '${e.nodeTag}' has no implementation`);let s=t.iterate;delete t.iterate,delete t.store;let a=e.getAttr("iterate")||e.getAttr("store");a!=null?(e.pointerType(a)&&(a=a.slice(1)),a.startsWith(".")&&(a=e._composeRelativeDatapath(a,a))):a=null;for(let l of Object.keys(t)){let c=e.getAttr(l);e.pointerType(c)==="^"&&(t[l]=`^${e.absDatapath(c)}`)}return[i,s,a,t]}_expandBlock(e,t,r,n,i){let s=e.builder._expansionRoot(r);t.call(e.builder,on(s),n);let a=s.getNodes();if(a.length!==1)throw new Error(`component '${e.nodeTag}' must build a tree, not a forest: ${a.length} root nodes`);let l={...i,depthOffset:this._nodeDepth(e,i.depthOffset||0)};return this.render(a[0],l)}preprocess(e){return e}renderedItem(e,t,r,n){throw new Error(`${this.constructor.name} does not implement renderedItem`)}_handleMeta(e,t){let[r,n]=e._getMeta("render_tag,render_attributes"),i=nn(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 n&&(t={...t,...n}),[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 n=this._composeStringFragments(e);if(t==null)return n;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(n),null;if(typeof t.write=="function")return t.write(n),null;if(typeof t=="function")return t(n),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 n=((e.fullpath||"").match(/\./g)||[]).length;return Math.max(n-1,0)+t}};var Vt=class extends Ut{static mode="xml";renderedItem(e,t,r,{tag:n,pretty:i=!1,depthOffset:s=0}={}){let a=this._formatAttrs(r),l=i?" ".repeat(this._nodeDepth(e,s)):"",c=i?`
|
|
34
|
+
`:"";if(Array.isArray(t)){let u=this._composeStringFragments(t);return`${l}<${n}${a}>${c}${u}${l}</${n}>${c}`}return t==null?`${l}<${n}${a}></${n}>${c}`:`${l}<${n}${a}>${this._escapeText(t)}</${n}>${c}`}finalize(e,t=null,{docHeader:r=null}={}){let n=this._composeStringFragments(e);return r===!0?n=`<?xml version='1.0' encoding='UTF-8'?>${n}`:typeof r=="string"&&(n=r+n),super.finalize(n,t)}_formatAttrs(e){return Object.entries(e||{}).map(([t,r])=>` ${t.startsWith("xmlns_")?`xmlns:${t.slice(6)}`:t}="${this._escapeAttr(r)}"`).join("")}};var Gd={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 Hd(o){let e=[];for(;o&&o!==Function.prototype;)e.push(o),o=Object.getPrototypeOf(o);return e.reverse()}function sg(o){let e=Object.create(null),t=(r,n)=>{let i=r.toLowerCase(),s=e[i];if(s!==void 0&&s!==n)throw new Error(`container '${r}' is already tied to implementation method '${s}' (cannot rebind to '${n}')`);e[i]=n};for(let r of Hd(o))if(Object.hasOwn(r,"containers"))for(let n of r.containers||[])t(n,n);return e}function Yn(o){let e=Object.create(null);for(let t of Object.keys(o)){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 sn="_root_",an="_root_",tl=new Set(["destination","func","value","_on_start"]),Ae=class o{static _sourceClass=N;static registerBuilder(e){if(typeof e!="function"||!(e.prototype instanceof o))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=o._registry.get(t);if(r&&r!==e)throw new Error(`Builder name '${t}' is already registered to ${r.name}; cannot register ${e.name}`);return o._registry.set(t,e),e}static getBuilderClass(e){let t=o._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 x,this._dataroot.setBackref(),this._dataroot.setItem(an,new x),this.data=this._dataroot.getItem(an),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(sn,new t(null,this)),this.source=this._sourceroot.getItem(sn)}wrapSource(e){if(e=Z(e),!(e instanceof N)&&!(e instanceof Se))throw new TypeError("wrapSource requires a SourceBag or SourceBagNode");let t=this._sourceHandles.get(e);return t||(t=$d(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=o.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 ut(t.toDocument()).update(e):new ut(e),n=Ja(r.toDocument()),i=Ka(n),s=Yn(i.elements);this._classCollection=r,this._classSchema=i.elements,this._abstracts=i.abstracts,this._tagNames=s}static{this.defineGrammar(Gd)}get _containers(){return sg(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??=Yn(this.schema):this.constructor._tagNames??=Yn(this.schema)}schemaTag(e){let t=e.toLowerCase(),r=this.schemaTagNames[t];if(r)return r;let n=`${this.constructor._name}_`;return t.startsWith(n)&&this.schemaTagNames[t.slice(n.length)]||null}loadGrammar(e,{replace:t=!1}={}){let r=this._collection||this.constructor._classCollection,n=t?new ut(e):new ut(r.toDocument()).update(e),i=Ja(n.toDocument()),s=Ka(i),a=Yn(s.elements);return this._collection=n,this._schemaOverride=s.elements,this._tagNamesOverride=a,this}validateCustomTypes(e){let t=e.parentBag?.parentNode?.builder||e.parentBag?._builder,r=t&&t!==this&&t.schema[e.nodeTag]?._meta?.subbuilder?t:this;Vd(e.nodeTag,r.schema[e.nodeTag],e.value,e.getAttr()||{})}validateNodeValues(e,t,r={}){let n=this.schemaTag(e);if(!n)throw new Error(`unknown element '${e}'`);return Ud(n,this.schema[n],t,r),!0}validateNode(e,{value:t,attrs:r,childTags:n}={}){if(!e||typeof e.nodeTag!="string")throw new TypeError("validateNode requires a source node");let i=t!==void 0?t:e.value instanceof N?null:e.value;this.validateNodeValues(e.nodeTag,i,r||e.getAttr?.()||{});let s=this.schema[this.schemaTag(e.nodeTag)],a=n||(e.value instanceof N?e.value.getNodes().map(l=>l.nodeTag):null);return a&&this._validateChildren(e.nodeTag,s,a,!1),!0}validateChildren(e,t,{includeMinimum:r=!1}={}){let n=this.schemaTag(e);if(!n)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(n,this.schema[n],t,r)}validateParent(e,t=null){let r=this.schemaTag(e);if(!r)throw new Error(`unknown element '${e}'`);let n=this.schema[r];if(!this._countsForGrammar(n))return!0;let i=n._parentSpec;if(i==null||i.has("*"))return!0;if(t===null)throw new Error(`'${r}' requires a declared parent`);let s=this.schemaTag(t);if(!s)throw new Error(`unknown parent element '${t}'`);return this._validateParent(r,n,s),!0}bagCall(e,t,r,n){return this.setChild(e,t,r,n)}commandOnNode(e,t,r,n){if(e=Z(e),e.value instanceof N)return this.setChild(e.value,t,r,n);let i=e.value,s=new e.parentBag.constructor(null,e.builder||this),a=this.setChild(s,t,r,n,e);return this.promoteNodeValue(e,i,s),a}promoteNodeValue(e,t,r){e.setValue(r)}setChild(e,t,r,n,i=null){let s={...n},a=this.schema[t];if(!a)throw new Error(`unknown element '${t}'`);this.validateNodeValues(t,r,s);let l=a._meta?.subbuilder,u=(l==null?null:this._resolveSubbuilderReference(l,s,t))||this,d=r instanceof N?r._builderBindingPlan(u):null,f=i?.rootBuilder||e.root._builder||this;if(s.nodeId!=null&&f.source.getNodeByAttr("nodeId",s.nodeId))throw new Error(`Duplicate nodeId '${s.nodeId}'`);r instanceof N&&this._validateChildren(t,a,r.getNodes().map(v=>v.nodeTag),!1);let h=i||e.parentNode,p=h?.nodeTag?this.schema[h.nodeTag]:null;if(p&&!h._getMeta("subbuilder")&&this._countsForGrammar(a))this._validateParent(t,a,h.nodeTag),this._validateChildren(h.nodeTag,p,[...e.getNodes().map(v=>v.nodeTag),t],!1);else if(!p&&!h?._getMeta("subbuilder")&&a._parentSpec!=null&&this._countsForGrammar(a))throw new Error(`'${t}' requires a declared parent`);a._meta&&!("_meta"in s)&&(s._meta=a._meta),a.ns&&!("ns"in s)&&(s.ns=a.ns);let m=s.node_position;delete s.node_position;let b=s.node_label;delete s.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,s)}else{let v=p?._subSpec?.get(t);if(v&&v.max===1){if(b!=null)throw new Error(`'${t}': node_label is not allowed on a singleton`);w=t}else w=b||a.node_label||this._autoLabel(e,t)}if(e.node(w)!=null)throw new Error(`duplicate node label '${w}'`);return e._setBuilderItem(u,d,w,r,s,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 n=t._parentSpec;if(!(n==null||n.has("*")||!this._countsForGrammar(t))&&!n.has(r))throw new Error(`'${e}' not allowed as child of '${r}'`)}_validateChildren(e,t,r,n){let i=t._subSpec;if(i==null||i.has("*")||t._meta?.subbuilder)return[];let s=new Map;for(let a of r){let l=this.schema[a];if(l&&!this._countsForGrammar(l))continue;let c=i.get(a);if(!c)throw new Error(`'${a}' not allowed as child of '${e}'`);let u=(s.get(a)||0)+1;if(s.set(a,u),u>c.max)throw new Error(`too many '${a}' in '${e}'`)}return n?[...i].filter(([a,l])=>(s.get(a)||0)<l.min).map(([a])=>a):[]}_collectionLabel(e,t,r){let n=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,s)=>n(s)):n(e)}validateSource(){let e=[],t=(r,n="")=>{for(let i of r.getNodes()){let s=n?`${n}.${i.label}`:i.label,a=i.builder;a.validateCustomTypes(i);let l=a.schema[i.nodeTag];if(l&&!i._getMeta("data_element,subbuilder,component").some(Boolean)){let c=i.value instanceof N?i.value.getNodes().map(d=>d.nodeTag):[],u=a._validateChildren(i.nodeTag,l,c,!0);u.length&&e.push([s,u])}i.value instanceof N&&t(i.value,s)}};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={},n=e.runtimeToEvaluate(),i=new Set(n.keys()),s=new Map([...Object.entries(e.getAttr()),...e.fixedAttrItems()]);for(let[u,d]of[...n])if(!(typeof u!="string"||!H(d)))for(let f of Ze(e,d))n.has(f)||n.set(f,s.get(f));let a=e._getMeta("data_element");for(let[u,d]of n){if(d instanceof Y){t.set(u,d.resolve());continue}let f=typeof u=="string"?H(d)?.pointer??d:d;if(!e.pointerType(f)){t.set(u,typeof u=="string"&&typeof d=="string"&&d.startsWith("==")?null:d);continue}let h=e.absDatapath(f);if(t.set(u,this.data.getItem(h)),!a&&!h.includes("?")&&u===cr){let p=this.data.getNode(h);p&&Object.assign(r,p.getAttr("_wdg"))}}let l=kd(n,t,(u,d,f,h)=>this.evaluatePointerExpression(e,u,d,f,h)),c=l.get(cr);l.delete(cr);for(let u of l.keys())i.has(u)||l.delete(u);return[c,{...Object.fromEntries(l),...r}]}evaluatePointerExpression(e,t,r,n,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 n=(typeof t=="function"?t:t.constructor)[e];if(typeof n=="function")return n}throw new Error(`data-element func '${e}' not found on any data_logic source`)}_bindings(e){let[,t]=this.runtimeValues(e),r={};for(let[n,i]of Object.entries(t))tl.has(n)||(r[n]=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[n,i]of Object.entries(t))n!=="destination"&&n!=="value"&&!n.startsWith("_")&&(r[n]=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 n of r.getNodes())n._getMeta("data_element")&&e.push(n),n.value instanceof N&&t(n.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 a of Hd(this.constructor))if(Object.hasOwn(a,"components"))for(let l of a.components||[])e[l]=l;if(!Object.keys(e).length)return;let t={...this.schema},r={};for(let[a,l]of Object.entries(e))t[a]={sub_tags:"",_meta:{component:!0}},r[a.toLowerCase()]=l;let n=Yn(t),i=this._collection||this.constructor._classCollection,s=i.toDocument();s.abstracts={},s.elements=Object.fromEntries(Object.keys(e).map(a=>[a,t[a]])),this._collection=new ut(i.toDocument()).update(s),this._schemaOverride=t,this._componentMap=r,this._tagNamesOverride=n}_expansionRoot(e=null){let t=this.constructor._sourceClass,r=new t(null,this);return r.setBackref(),r.setItem(sn,new t(null,this),e?{datapath:e}:null),r.getItem(sn)}create(){this.setup(this.data),this._resolveComponents(),this.main(this.root),this.computeLogic(this._dataElementNodes())}get renderer_xml(){return new Vt(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),n=r.renderChildren(r.preprocess(this.source),t);return this.materialized[e]=n,n}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 n=this.getRenderer(e);if(t===!1&&n.renderType!=="string")throw new TypeError("target=false is not valid for an object renderer");let i=t===!1?null:t||this._defaultTargets.get(n.mode)||null,s={...i?.renderOpts,...r};return n.finalize(this.materialize(e,s),i,s)}};Ae._registry=new Map;var ag=new Set(["short","medium","long","full"]),lg=/('(?:[^']|'')*'|[a-zA-Z]+|[^a-zA-Z']+)/g;function cg(o,e){if(!(o instanceof Date))throw new TypeError("Temporal formats require a typed Date value");if(!Number.isFinite(o.getTime()))throw new RangeError("Invalid date");let t=e||R(o).split("::").at(-1);if(!["D","H","DH","DHZ"].includes(t))throw new RangeError(`Unsupported temporal dtype: ${t}`);return t}function ug(o,e,t,r){let n=e.match(lg)||[];if(n.join("")!==e)throw new RangeError("Unclosed format literal");let i=(u,d=2)=>String(u).padStart(d,"0"),s=u=>new Intl.DateTimeFormat(t,{timeZone:"UTC",...u}).format(o),c={...r==="H"?{}:{y:()=>String(o.getUTCFullYear()),yy:()=>i(o.getUTCFullYear()%100),yyyy:()=>i(o.getUTCFullYear(),4),M:()=>String(o.getUTCMonth()+1),MM:()=>i(o.getUTCMonth()+1),MMM:()=>s({month:"short"}),MMMM:()=>s({month:"long"}),d:()=>String(o.getUTCDate()),dd:()=>i(o.getUTCDate()),EEE:()=>s({weekday:"short"}),EEEE:()=>s({weekday:"long"})},...r==="D"?{}:{H:()=>String(o.getUTCHours()),HH:()=>i(o.getUTCHours()),h:()=>String(o.getUTCHours()%12||12),hh:()=>i(o.getUTCHours()%12||12),m:()=>String(o.getUTCMinutes()),mm:()=>i(o.getUTCMinutes()),s:()=>String(o.getUTCSeconds()),ss:()=>i(o.getUTCSeconds()),a:()=>new Intl.DateTimeFormat(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(o).find(u=>u.type==="dayPeriod").value}};return n.map(u=>{if(u.startsWith("'"))return u==="''"?"'":u.slice(1,-1).replaceAll("''","'");if(!/^[a-zA-Z]/.test(u))return u;if(!c[u])throw new RangeError(`Unsupported date format token: ${u}`);return c[u]()}).join("")}function Xd(o,{format:e,mask:t,locale:r,dtype:n,places:i}={}){let s=o==null?"":String(o);if(o!=null&&o!==""&&(e!=null&&e!==""||i!=null))if(typeof o=="number"||U(o))s=fg(o,{format:e,locale:r,places:i});else{let a=cg(o,n);if(ag.has(e)){let l={timeZone:"UTC"};a!=="H"&&(l.dateStyle=e),a!=="D"&&(l.timeStyle=e),s=new Intl.DateTimeFormat(r||void 0,l).format(o)}else s=ug(o,String(e),r||void 0,a)}return t==null?s:String(t).replaceAll("%s",()=>s)}function dg({format:o="decimal",places:e}={}){let t={maximumFractionDigits:20};if(!o||o==="decimal")t.style="decimal";else if(o==="percent")t.style="percent";else if(o==="scientific")t.notation="scientific";else{let r=/^(0|#,##0)(?:\.(0*)(#*))?$/.exec(o);if(!r||o.includes(".")&&!r[2]&&!r[3])throw new RangeError(`Unsupported number format: ${o}`);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 fg(o,e={}){if(typeof o!="number"&&!U(o))throw new TypeError("Number formatting requires a Number or Decimal");if(!Number.isFinite(Number(o)))throw new RangeError("Number must be finite");let t=new Intl.NumberFormat(e.locale||void 0,dg(e));if(U(o)&&new Intl.NumberFormat("en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal values without precision loss");return t.format(U(o)?o.toString():o)}var hg=new Set(["style","script"]),pg=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"]),Yd=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"]),Zn=new Set(["rounded","gradient","shadow","transform","transition","zoom","filter"]),Zd=o=>o===!0?"true":o===!1?"false":String(o),ji=o=>typeof o=="number"&&Number.isFinite(o)?`${o}px`:String(o);function mg(o){if(Yd.has(o))return!0;for(let e of Yd)if(o.startsWith(`${e}_`))return!0;return!1}function gg(o){let e=new Map;if(!o)return e;let t=[],r=0,n=null,i=!1,s=!1,a=0,l=String(o);for(let c=0;c<l.length;c+=1){let u=l[c],d=l[c+1];if(s){u==="*"&&d==="/"&&(s=!1,c+=1);continue}if(i){i=!1;continue}if(u==="\\"){i=!0;continue}if(n){u===n&&(n=null);continue}u==='"'||u==="'"?n=u:u==="/"&&d==="*"?(s=!0,c+=1):"([{".includes(u)?a+=1:")]}".includes(u)&&a>0?a-=1:u===";"&&a===0&&(t.push(l.slice(r,c)),r=c+1)}t.push(l.slice(r));for(let c of t){let u=c.trim();if(!u)continue;let d=u.indexOf(":");if(d<0)throw new TypeError(`malformed style declaration '${u}'`);e.set(u.slice(0,d).trim(),u.slice(d+1).trim())}return e}var Wt=class extends Ut{static mode="html";renderedItem(e,t,r,{tag:n,xml:i=!0,pretty:s=!1,depthOffset:a=0,includeDatapath:l=!1}={}){e.parentNode?._getMeta("subbuilder")==="html"&&(r={xmlns:"http://www.w3.org/1999/xhtml",...r});let{format:u,mask:d,locale:f,places:h,dtype:p,...m}=r;!Array.isArray(t)&&(u!=null||d!=null||h!=null)&&(t=Xd(t,{format:u,mask:d,places:h,dtype:p,locale:this._displayLocale(e,f)}));let b=this._formatAttrs(m);if(l){if(!Object.hasOwn(r,"id")){let E=this.builder.targetId(e);E!==null&&(b+=` id="${this._htmlAttrValue(E)}"`)}for(let[E,D]of Object.entries(e.getAttr()))e.pointerType(D)&&(b+=` data-${this.adapt(E)}-pointer="${this._htmlAttrValue(e.absDatapath(D))}"`)}let w=s?" ".repeat(this._nodeDepth(e,a)):"",_=s?`
|
|
35
|
+
`:"";if(e._getMeta("void"))return`${w}<${n}${b}${i?"/":""}>${_}`;if(Array.isArray(t)){let E=this._composeStringFragments(t);return`${w}<${n}${b}>${_}${E}${w}</${n}>${_}`}if(t==null)return`${w}<${n}${b}></${n}>${_}`;let v=typeof t=="string"&&t.endsWith("::HTML")?t.slice(0,-6):hg.has(n)?String(t):this._escapeText(t);return`${w}<${n}${b}>${v}</${n}>${_}`}_displayLocale(e,t){if(t)return t;for(let r=e.parentNode;r;r=r.parentNode){let n=r.getAttr("locale");if(n==null)continue;let i=r.pointerType(n)?r.data.getItem(r.absDatapath(n)):n;if(i)return i}}adaptAttrs(e){let t={},r={};for(let[i,s]of Object.entries(e||{}))if(i.startsWith(`${this.builder.constructor._name}_`))t[this.adapt(i)]=s;else if(i==="dtype")t.dtype=s;else{if(this.builder.constructor.retainedAttrPrefixes.some(a=>i.startsWith(a)))continue;this._isStyleContribution(i)?r[i]=s:t[i]=s}let n=this._adaptStyle(r);return n&&(t.style=n),t}_isStyleContribution(e){if(e==="style"||e.startsWith("style_")||Zn.has(e))return!0;let t=e.includes("_")?e.slice(0,e.indexOf("_")):null;return t!==null&&Zn.has(t)||mg(e)}_adaptStyle(e){let t=gg(e.style),r=new Map,n=new Map;for(let[i,s]of Object.entries(e))if(i!=="style")if(i.startsWith("style_"))t.set(i.slice(6).replaceAll("_","-"),Zd(s));else if(Zn.has(i))r.set(i,s);else{let a=i.indexOf("_"),l=a<0?i:i.slice(0,a);a>=0&&Zn.has(l)?(n.has(l)||n.set(l,{}),n.get(l)[i.slice(a+1)]=s):t.set(i.replaceAll("_","-"),Zd(s))}for(let i of Zn)(r.has(i)||n.has(i))&&this[`_macro_${i}`](r.get(i),n.get(i)||{},t);return[...t].map(([i,s])=>`${i}: ${s}`).join("; ")}_formatAttrs(e){let t=[];for(let[r,n]of Object.entries(e||{}))pg.has(r)?n&&t.push(` ${r}`):t.push(` ${r}="${this._htmlAttrValue(n)}"`);return t.join("")}_htmlAttrValue(e){return(e===!0?"true":e===!1?"false":String(e)).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}_macro_rounded(e,t,r){let n=e===void 0?{}:{top_left:e,top_right:e,bottom_left:e,bottom_right:e};for(let[i,s]of Object.entries(t))if(i==="top"||i==="bottom")n[`${i}_left`]=s,n[`${i}_right`]=s;else if(i==="left"||i==="right")n[`top_${i}`]=s,n[`bottom_${i}`]=s;else if(["top_left","top_right","bottom_left","bottom_right"].includes(i))n[i]=s;else throw new TypeError(`rounded: unknown sub-kwarg '${i}'`);for(let[i,s]of Object.entries(n))r.set(`border-${i.replaceAll("_","-")}-radius`,ji(s))}_macro_transform(e,t,r){let n=e===void 0?[]:[String(e)];for(let[i,s]of Object.entries(t))i==="rotate"?n.push(`rotate(${s}deg)`):i==="scale"||i==="translate"?n.push(`${i}(${s})`):i==="translate_x"?n.push(`translateX(${ji(s)})`):i==="translate_y"?n.push(`translateY(${ji(s)})`):i==="skew_x"?n.push(`skewX(${s}deg)`):i==="skew_y"?n.push(`skewY(${s}deg)`):n.push(`${i.replaceAll("_","-")}(${s})`);n.length&&r.set("transform",n.join(" "))}_macro_filter(e,t,r){let n=e===void 0?[]:[String(e)];for(let[i,s]of Object.entries(t))i==="rotate"?n.push(`hue-rotate(${s}deg)`):i==="blur"?n.push(`blur(${ji(s)})`):i==="drop_shadow"?n.push(`drop-shadow(${s})`):n.push(`${i.replaceAll("_","-")}(${s})`);n.length&&r.set("filter",n.join(" "))}_macro_transition(e,t,r){e!==void 0&&r.set("transition",String(e));for(let[n,i]of Object.entries(t))r.set(`transition-${n.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[n,i]of Object.entries(t))r.set(`box-shadow-${n.replaceAll("_","-")}`,String(i))}_macro_gradient(e,t,r){e!==void 0&&r.set("background-image",String(e))}};var bg=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 Kn(o){return Object.fromEntries(Object.entries(o||{}).map(([e,t])=>[bg.has(e)?e.replaceAll("_","-"):e,t]))}var Gt=class extends Vt{static mode="svg";adaptAttrs(e){return Kn(e)}};var Kd={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 Je=class extends Ae{static _name="html";static _defaultRenderMode="html";static retainedAttrPrefixes=["validate_","dtype"];static{this.defineGrammar(Kd)}get renderer_html(){return new Wt(this)}};Ae.registerBuilder(Je);var Jd={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 vt=class extends Ae{static _name="svg";static _defaultRenderMode="svg";static{this.defineGrammar(Jd)}get renderer_svg(){return new Gt(this)}};Ae.registerBuilder(vt);function Qe(o,e=new Set){if(!o||typeof o!="object")return;let t=o.ownerDocument?.defaultView?.Node??o.defaultView?.Node;if(Z(o)instanceof Se||t&&o instanceof t)throw new TypeError("Live Source/DOM references cannot cross a transport boundary");if(e.has(o))throw new TypeError("Transport data cannot contain circular references");e.add(o);let r=o instanceof x?o.getNodes().flatMap(n=>[n.staticValue,n.getAttr()]):Object.values(o);for(let n of r)Qe(n,e);e.delete(o)}var Jn=class{constructor(e=null){this.entries=new Map,this.sourceRoot=e}validate(e,t=new Set){let r=new Map,n=i=>{for(let s of i.getNodes()){let a=s.getAttr("__ref");if(a){if(r.has(a))throw new Error("Duplicate Source reference");let l=this.entries.get(a);if(e!==this.sourceRoot&&l&&l.node!==s&&!t.has(l.node))throw new Error("Duplicate Source reference");r.set(a,s)}s.value instanceof N&&n(s.value)}};n(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]}};var nl={};ee(nl,{randomId:()=>G});function G(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),o=>o.toString(16).padStart(2,"0")).join("")}var Ne=class{constructor(e){this.gramlot=e}};var pr=class extends Error{name="RpcError";constructor({code:e,name:t,message:r,details:n}){super(r),this.code=e,this.remoteName=t,n!==void 0&&(this.details=n)}},Qn=class extends Ne{constructor(e,{rpcUrl:t,closeUrl:r,document:n,transport:i}){super(e),this.transport=i===!1?null:i??e.serverAdapter.createTransport({rpcUrl:t,closeUrl:r,document:n,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(Qe(r),this.gramlot.abort.signal.aborted)throw this.gramlot.abort.signal.reason;let n=G(),i=j(this.transport.callSync(R({id:n,pageId:this.gramlot.pageId,contentType:e,name:t,params:r})));if(i.id!==n)throw new Error("rpc response id mismatch");if(i.error)throw new pr(i.error);return i.value}async call(e,t,r={},n={}){return(await this.callEnvelope(e,t,r,n)).value}async callEnvelope(e,t,r={},{signal:n=null}={}){if(!this.transport?.call)throw new Error(`rpc '${t}' is unavailable without a server transport`);Qe(r);let i=G(),s=R({id:i,pageId:this.gramlot.pageId,contentType:e,name:t,params:r}),a=n?[this.gramlot.abort.signal,n]:[this.gramlot.abort.signal],l=a.find(f=>f.aborted);if(l)throw l.reason;let c=new AbortController,u=f=>c.abort(f.target.reason);for(let f of a)f.addEventListener("abort",u,{once:!0});let d=new Promise((f,h)=>{c.signal.addEventListener("abort",()=>{this.remoteRequests.delete(i),h(c.signal.reason)},{once:!0})});this.remoteRequests.set(i,c);try{let f=j(await Promise.race([this.transport.call(s,c.signal),d]));if(f.id!==i)throw new Error("rpc response id mismatch");if(f.error)throw new pr(f.error);return f}finally{this.remoteRequests.delete(i);for(let f of a)f.removeEventListener("abort",u)}}};var Pi=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 n=new URL(t,r.baseURI);n.protocol=n.protocol==="https:"?"wss:":"ws:",this.endpoint=n.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.parent?this.fail(new Error("PageStore parent disconnected")):this.forget(i.window)},receive:(i,s)=>{try{this.receive(i,s)}catch(a){this.fail(a)}}},{endpoint:this.endpoint,ready:!1}),this.address=n,this.parent||this.open()}open(){let e=this.address;e.searchParams.set("pageId",this.gramlot.pageId),this.socket=new this.window.WebSocket(e.href),this.socket.addEventListener("open",()=>this.connected()),this.socket.addEventListener("message",t=>{try{this.deliver(t.data)}catch(r){this.fail(r)}}),this.socket.addEventListener("error",()=>this.fail(new Error("PageStore WebSocket failed"))),this.socket.addEventListener("close",t=>{this.closed||this.fail(new Error("PageStore disconnected ("+t.code+")"))})}peerChanged(e){if(this.closed||!e.parent||!this.parent)return;let t=e.channels.server;t?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")):(this.parent=null,this.open())}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(R(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(R(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(n){this.window.console.error("PageStore publication subscriber failed",n)}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");Qe(t);let r={op:"publish",id:G(),pageId:this.gramlot.pageId,topic:e.topic,payload:t};e.pageId!==void 0&&(r.targetPageId=e.pageId);let n=R(r);return async()=>{let i=j(await this.call(n));if(i.error)throw new pr(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((n,i)=>{let s={message:r,sent:!1,finish:(l,c)=>{this.calls.delete(r.id)&&(t?.removeEventListener("abort",a),c===void 0?i(l):n(c))}},a=()=>{if(s.finish(t.reason),s.sent&&this.ready&&!this.closed)try{this.send({op:"cancel",id:r.id})}catch(l){this.fail(l)}};this.calls.set(r.id,s),t?.addEventListener("abort",a,{once:!0}),this.ready&&this.sendCall(s)})}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 Qd="gramlot:message",Bi=class{#e;#t;#r;#n=G();#o=new Map;#i=new Map;#s=!1;#a;#l;#c;#u;#d;constructor(e,t){this.#e=e,this.#r=t,this.#t=t.defaultView,this.#a=r=>this.#g(r),this.#l=r=>{if(r.target?.localName!=="iframe")return;let n=this.#v(r.target);n&&this.#w(n)},this.#c=r=>{r.persisted||this.#e.dispose({beacon:!0})},this.#u=()=>this.ready(),this.#t.addEventListener("message",this.#a),this.#t.addEventListener("pagehide",this.#c),this.#t.addEventListener("pageshow",this.#u),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.#x(this.#r.referrer||this.#r.baseURI)}:null}get children(){return[...this.#o.values()].filter(e=>!e.parent)}isConnected(e){return!this.#s&&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.#s){this.connect();for(let e of this.#o.values())this.#_(e)}}registerChannel(e,t,r){if(this.#s||e==="publish"||this.#i.has(e))throw new Error("Invalid family channel");this.#i.set(e,{handler:t,state:r});for(let n of this.#o.values())t.changed(n)}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 n=this.#o.get(e);if(this.#s||!n)throw new Error("Destination page is not connected");Qe(r),this.#y(n,{kind:"message",recipient:n.session,channel:t,wire:R(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 s=e.iframe,a=Z(s),l=typeof s=="string"?this.#r.getElementById(s):a instanceof Se?this.#e.dom.getDomNode(a):null,c=this.#v(l);if(!c)throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");r.push(c)}if(e.pageId!==void 0){let s=this.children.find(a=>a.pageId===e.pageId);if(!s)throw new Error("pageId destination must be a registered direct Gramlot child");r.push(s)}let n=r.map(s=>{let a=this.#o.get(s.window);if(!a?.ready||a.origin!==s.origin)throw new Error("Destination page is not ready");return{...s,session:a.session}});Qe(t);let i=R({topic:e.topic,payload:t});return()=>{if(!this.#s)for(let s of n){let a=this.#E(s.window);if(!a||a.origin!==s.origin||this.#o.get(s.window)?.session!==s.session)throw new Error("Destination page disconnected before publication");this.#y(s,{kind:"message",recipient:s.session,channel:"publish",wire:i})}}}dispose(){if(this.#s)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.#s=!0,this.#i.clear(),this.#t.removeEventListener("message",this.#a),this.#t.removeEventListener("pagehide",this.#c),this.#t.removeEventListener("pageshow",this.#u),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:n}of this.#i.values())n.disconnected(r);t&&r.kind==="popup"&&!r.parent&&e.close()}}#m(e,t){let r=this.#o.get(e.window),n=r?.session!==t.session;n&&this.#h(e.window);let i=n?{...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(),n&&e.node&&(i.release=this.#e.src.binding.bindingFor(e.node).track(()=>{this.#h(e.window,!0)}));for(let{handler:s}of this.#i.values())s.changed(i);return n}#g(e){if(this.#s||e.data?.type!==Qd)return;let t=this.#E(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 n=this.#o.get(t.window);if(!(!n||n.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"||!n.ready||typeof i.topic!="string"||!i.topic)return;this.#e.publish(i.topic,i.payload)}else this.#i.get(r.channel)?.handler.receive(n,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:Qd,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.#x(e.hasAttribute("srcdoc")?this.#r.baseURI:e.getAttribute("src")||this.#r.baseURI);return{window:e.contentWindow,origin:i,node:t,parent:!1,kind:"iframe"}}#x(e){let t=new URL(e,this.#r.baseURI);return t.protocol==="file:"?"null":t.origin}#E(e){let t=this.parent;if(t?.window===e)return t;for(let r of this.#r.getElementsByTagName("iframe")){let n=this.#v(r);if(n?.window===e)return n}try{if(e&&e!==this.#t&&e.opener===this.#t&&e.location.origin===this.#t.location.origin)return{window:e,origin:this.#x(this.#r.baseURI),parent:!1,kind:"popup"}}catch{}return null}};var mr=class o{#e;constructor(e,t=0){this.pattern=e,this.flags=t,this.#e=hr.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 o(e.pattern,e.flags)}toJSON(){return{kind:"regex",pattern:this.pattern,flags:this.flags}}matches(e){return this.#e(e)}},eo=new mr(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);var ll={};ee(ll,{createLabelbox:()=>sl,labelboxContent:()=>Ie,labelboxPositions:()=>Li,labelboxPresentation:()=>Ht,labelboxStyle:()=>il,projectLabelbox:()=>al});var ol={};ee(ol,{choiceCaption:()=>to,parseChoices:()=>gr});function gr(o,e=","){if(typeof e!="string"||!e)throw new TypeError("separator must be a nonempty string");if(o==="")return[];let t=new Set;return o.split(e).map(r=>{let n=r.indexOf(":"),i=n<0?r:r.slice(0,n),s=n<0?r:r.slice(n+1);if(!i||t.has(i))throw new Error("Invalid or duplicate choice code");return t.add(i),{id:i,caption:s}})}function to(o,e,t=""){return o.find(r=>r.id===e)?.caption??t??""}var Mi=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",n=>{n.preventDefault(),n.stopPropagation(),this.menu.opened?this.menu.close():this.menu.open(this.button)}),this.button.addEventListener("keydown",n=>{["ArrowDown","ArrowUp"].includes(n.key)&&(n.preventDefault(),n.stopPropagation(),this.menu.open(this.button,n.key==="ArrowUp"))}),this.choose=t}project({lbl:e,lbl_value:t,lbl_values:r,disabled:n,readonly:i},s){let a=gr(r);if(this.values!==r){this.menu.close(!1);for(let c of this.menu.items)c.releaseCommand();this.menu.replaceChildren(...a.map(({id:c,caption:u})=>{let d=this.menu.ownerDocument.createElement("gramlot-menu-line");return d.projectAttributes({code:c,caption:u},s),d.activateCommand=f=>{d.prepareCommand(f)&&this.choose(c)},d.control.addEventListener("click",f=>d.activateCommand(f)),d})),this.values=r}let l=to(a,t,e);this.button.textContent=l,this.button.disabled=!!(n||i||!a.length),this.button.disabled&&this.menu.close(!1);for(let c of this.menu.items)c.projectAttributes({...c.parameters,checked:c.parameters.code===t},s);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 Li=["TL","TC","TR","L","R","BL","BC","BR"],il=`.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
36
|
.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
37
|
.gramlot-labelbox>.label-box>.label-menu-trigger:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:3px;border-radius:2px}
|
|
43
38
|
.gramlot-labelbox>.label-box>.label-menu-trigger:disabled{opacity:.5;cursor:default}
|
|
@@ -89,7 +84,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
89
84
|
.gramlot-labelbox>.tray-resize[hidden]{display:none}
|
|
90
85
|
.gramlot-labelbox>.tray-resize svg{width:16px;height:16px;pointer-events:none}
|
|
91
86
|
.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
|
|
87
|
+
.gramlot-labelbox>.tray-resize:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}`;function sl(o,e){let t=o.createElement("div"),r=o.createElement("div"),n=o.createElement("label");r.append(n),t.append(r,e);let i={box:t,labelBox:r,fieldLabel:n,controlBox:e,previous:{box:{},label:{},labelBox:{},controlBox:{}}};return t.labelbox=i,i}function al(o,e,t){let{lbl:r,lbl_value:n,lbl_values:i,lbl_variant:s,lbl_position:a=s==="card"?"TC":"TL",...l}=e;if(!Li.includes(a))throw new TypeError(`Invalid lbl_position: ${a}`);let c={box:{},label:{},labelBox:{},controlBox:{}},u=[["box_l_","labelBox"],["box_c_","controlBox"],["lbl_","label"],["box_","box"]];for(let[f,h]of Object.entries(l)){let p=u.find(([m])=>f.startsWith(m));p&&(c[p[1]][f.slice(p[0].length)]=h,delete l[f])}let d={box:o.box,label:o.fieldLabel,labelBox:o.labelBox,controlBox:o.controlBox};for(let[f,h]of Object.entries(d)){let p=t(c[f]),m=o.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]));o.previous[f]=p}return e.lbl_width==null?o.box.style.removeProperty("--gramlot-label-width"):o.box.style.setProperty("--gramlot-label-width",e.lbl_width),o.box.classList.add("labelbox","gramlot-labelbox"),o.labelBox.classList.add("label-box"),o.controlBox.classList.add("control-box"),o.box.dataset.position=a,s==null?delete o.box.dataset.variant:o.box.dataset.variant=s,o.fieldLabel.textContent=r??"",o.labelBox.hidden=r==null||r==="",i!=null?(o.menu??=new Mi(o,f=>o.choose(f)),o.menu.project(e,t)):o.menu&&(o.menu.dispose(),o.menu=null),o.box.dispatchEvent(new o.box.ownerDocument.defaultView.Event("gramlot-label-layout",{bubbles:!0})),l}function Ie(o){return o?.labelbox?o.labelbox.controlBox.firstElementChild:o}function Ht(o){let e=o?.parentElement?.parentElement;return e?.labelbox&&Ie(e)===o?e:o}var ul={};ee(ul,{choiceFieldStyles:()=>cl});var cl=`
|
|
93
88
|
.choice-field{position:relative;min-width:0}
|
|
94
89
|
.choice-field>input{box-sizing:border-box;width:100%;padding-inline-end:calc(var(--gramlot-choice-toggle-width,1.6em) + .4em)}
|
|
95
90
|
.choice-field>.choice-toggle{position:absolute;inset-inline-end:1px;inset-block:1px;
|
|
@@ -101,7 +96,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
101
96
|
.choice-toggle:disabled{opacity:.5;cursor:default}
|
|
102
97
|
.choice-toggle:focus-visible{outline:1px solid var(--gramlot-focus-ring,Highlight);outline-offset:-3px}
|
|
103
98
|
.choice-field>input::-webkit-calendar-picker-indicator{opacity:0}
|
|
104
|
-
`;var
|
|
99
|
+
`;var yg=/^[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,vg=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]);function xt(o){let e=o.code;if(typeof e!="string"||yg.exec(e)?.[0]!==e||!e.includes("-")||vg.has(e))throw new TypeError("webcomponent: code must be a literal custom-element name");return e}function dl(o){for(let e of Object.values(o))e&&typeof e=="object"&&dl(e);return Object.freeze(o)}function ef(o){if(!o.annotation&&typeof o.dtype!="string"&&!Array.isArray(o.dtype))throw new TypeError("Component parameter requires dtype");let e=o.annotation?[structuredClone(o.annotation)]:(Array.isArray(o.dtype)?o.dtype:[o.dtype]).map(t=>({kind:"dtype",dtype:t}));return o.nullable&&e.push({kind:"dtype",dtype:"NN"}),o.binding&&o.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 Yt({name:o,tag:e,base:t,doc:r=null,mixins:n=[],parameters:i={},subTags:s="",presentationDefaults:a=[],dataScope:l=!1,command:c=!1,childParameters:u={},sourceContext:d=!1,bagStore:f=!1,bagStruct:h=!1,dragSource:p=!1,implementation:m}){if(xt({code:e}),!/^[a-zA-Z][a-zA-Z0-9]*$/.test(o))throw new TypeError("Invalid component authoring name");let b={...t.parameters};for(let w of n)for(let[_,v]of Object.entries(w.parameters)){if(Object.hasOwn(b,_))throw new Error(`Duplicate mixin parameter: ${_}`);b[_]=v}Object.assign(b,i);for(let w of Object.values(b))if(ef(w),w.required!==void 0&&(w.required!==!0||Object.hasOwn(w,"default")))throw new TypeError("A required component parameter is true and has no default");return Object.freeze({name:o,tag:e,base:t,doc:r,subTags:s,presentationDefaults:Object.freeze([...a]),dataScope:l,command:c,bagStore:f,bagStruct:h,mixins:Object.freeze([...n]),labelbox:n.some(w=>w.labelbox===!0),parameters:dl(structuredClone(b)),childParameters:dl(structuredClone(u)),sourceContext:d,dragSource:p,implementation:m})}var Xt=class o{#e=new WeakMap;constructor({name:e,components:t,dependencies:r=[],css:n=[],assets:i={},registerCommands:s=()=>{}}){if(typeof e!="string"||!e)throw new TypeError("Collection name must be nonempty");if(!Array.isArray(r)||r.some(c=>!(c instanceof o)))throw new TypeError("Collection dependencies must be collection objects");if(!Array.isArray(n)||n.some(c=>!(c instanceof URL))||!i||typeof i!="object"||Array.isArray(i)||Object.values(i).some(c=>!(c instanceof URL)))throw new TypeError("Collection css/assets require URL objects");if(typeof s!="function")throw new TypeError("registerCommands must be a function");this.dependencies=Object.freeze([...r]),this.css=Object.freeze([...n]),this.assets=Object.freeze({...i}),this.registerCommands=s,this.name=e,this.components=Object.freeze([...t]);let a=new Set,l=new Set;for(let c of t){if(a.has(c.name.toLowerCase())||l.has(c.tag))throw new Error(`Duplicate component: ${c.name}`);a.add(c.name.toLowerCase()),l.add(c.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:e.doc,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:ef(r),...r.required?{has_default:!1}:{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 n=r.base(e.HTMLElement);for(let s of r.mixins)n=s(n);let i=r.implementation(n);Object.defineProperty(i,"gramlotComponent",{value:r}),t.push([r.tag,i])}for(let[r,n]of t)e.customElements.define(r,n);this.#e.set(e,t)}};function fl(o){return new Xt(o)}var gl={};ee(gl,{ChoiceGroup:()=>ml,NativeControl:()=>pl,controlElement:()=>ro});var hl={};ee(hl,{parameterValues:()=>Fi,projectParameters:()=>br});function br(o,e){return o.parameters=Fi(o.constructor.gramlotComponent,e),Object.fromEntries(Object.entries(e).filter(([t])=>!Object.hasOwn(o.parameters,t)))}function Fi(o,e){return Object.fromEntries(Object.entries(o.parameters).map(([t,r])=>[t,Object.hasOwn(e,t)?e[t]:r.default]))}function ro(o){return class extends o{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
100
|
input,textarea{font:inherit;max-width:100%} .control-box{min-width:0;color:var(--gramlot-ink,CanvasText)}
|
|
106
101
|
input:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea{
|
|
107
102
|
appearance:none;box-sizing:border-box;width:100%;border:1px solid var(--gramlot-border-control,#7a8798);
|
|
@@ -117,7 +112,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
117
112
|
input[type=range],input[type=color],button{min-width:var(--gramlot-touch-target,0px);min-height:var(--gramlot-touch-target,0px)}
|
|
118
113
|
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
114
|
.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 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=`
|
|
115
|
+
.caption:empty{display:none}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",e.append(t,this.controlBox)}projectAttributes(e){return br(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 pl(o){return class extends ro(o){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:n,readonly:i}=this.parameters;this.control.disabled=!!n,this.control.readOnly=!!i;for(let[s,a]of Object.entries(this.constructor.gramlotComponent.parameters)){if(a.target==="control"){let l=this.parameters[s]??"";String(this.control[s])!==String(l)&&(this.control[s]=l)}a.target==="optionCaption"&&(this.optionCaption.textContent=this.parameters[s]??"")}return r}}}pl.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"},live:{dtype:"B",default:!1,binding:"read"}};function ml(o){return class extends ro(o){#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 n=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[n].focus()})}choiceOptions(){return gr(this.parameters.values??"")}projectAttributes(e,t){let r=super.projectAttributes(e,t),n=this.choiceOptions(),i=JSON.stringify(n);if(i!==this.#t){let a=n,l=new Set,c=null;for(let{id:u,caption:d}of a){let f=this.#e.get(u);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=u;let b=this.ownerDocument.createElement("span");p.append(m,b),f={label:p,input:m,text:b},this.#e.set(u,f)}f.text.textContent=d;let h=c?c.nextSibling:this.control.firstChild;h!==f.label&&this.control.insertBefore(f.label,h),c=f.label,l.add(u)}for(let[u,d]of this.#e)l.has(u)||(d.label.remove(),this.#e.delete(u));this.#t=i}let s=this.parameters.cols;if(!Number.isInteger(s)||s<1)throw new TypeError("cols must be a positive integer");this.control.style.gridTemplateColumns=`repeat(${s}, minmax(0, 1fr))`,this.control.disabled=!!this.parameters.disabled,this.control.readOnly=!!this.parameters.readonly;for(let{input:a}of this.#e.values())a.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:n}]of this.#e)n.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:n}]of this.#e)n.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)}}}ml.parameters={disabled:{dtype:"B",default:!1,binding:"read"},readonly:{dtype:"B",default:!1,binding:"read"}};var bl={};ee(bl,{positionPopup:()=>wr});function wr(o,e,{align:t="start",matchWidth:r=!1,inset:n=0,placement:i="bottom",point:s=null}={}){let a=e.ownerDocument.defaultView,l=s?{left:s.x,right:s.x,top:s.y,bottom:s.y,width:0}:e.getBoundingClientRect(),c=Math.max(0,a.innerWidth-16);o.style.setProperty("--gramlot-popup-available-width",`${c}px`),r&&(o.style.width=`${Math.min(Math.max(0,l.width-2*n),c)}px`),o.style.removeProperty("--gramlot-popup-available-height");let u=o.getBoundingClientRect();if(i==="side"){let w=Math.max(0,a.innerWidth-8-l.right-3),_=Math.max(0,l.left-8-3),v=u.width>w&&_>w;o.style.setProperty("--gramlot-popup-available-width",`${v?_:w}px`),o.style.setProperty("--gramlot-popup-available-height",`${Math.max(0,a.innerHeight-16)}px`);let E=o.getBoundingClientRect(),D=v?l.left-E.width-3:l.right+3;o.style.left=`${Math.max(8,Math.min(D,a.innerWidth-E.width-8))}px`,o.style.top=`${Math.max(8,Math.min(l.top,a.innerHeight-E.height-8))}px`;return}let d=Math.max(0,a.innerHeight-8-l.bottom-3),f=Math.max(0,l.top-8-3),h=u.height>d&&f>d;o.style.setProperty("--gramlot-popup-available-height",`${h?f:d}px`);let p=o.getBoundingClientRect(),m=t==="end"?l.right-p.width-n:l.left+n,b=h?l.top-p.height-3:l.bottom+3;o.style.left=`${Math.max(8,Math.min(m,a.innerWidth-p.width-8))}px`,o.style.top=`${Math.max(8,Math.min(b,a.innerHeight-p.height-8))}px`}var xl={};ee(xl,{SVG_NS:()=>kt,XHTML_NS:()=>be,boundaryAttributes:()=>io,displayItem:()=>un,domNames:()=>cn,isExpression:()=>Le,requireNoScriptAttributes:()=>vr,requireStyleClassAttributes:()=>yr,splitNativeAttributes:()=>vl,textValue:()=>_r,withDataSrcdocSandbox:()=>yl,withoutBindingAttributes:()=>Et,withoutNullValues:()=>xr});var _l={};ee(_l,{applyMask:()=>no,formatValue:()=>oo,validateMask:()=>wl});var ln=new Map;function zi(o,e,t){let r=JSON.stringify([o,e,t]),n=ln.get(r);if(n)ln.delete(r);else{let i=o?Intl.DateTimeFormat:Intl.NumberFormat;if(!i.supportedLocalesOf([e]).length)throw new RangeError(`Unsupported format locale: ${e}`);n=new i(e,t),ln.size===64&&ln.delete(ln.keys().next().value)}return ln.set(r,n),n}function wl(o){if(o!=null&&(typeof o!="string"||/[{}]/.test(o.replaceAll("{}",""))))throw new RangeError("This formatter mask supports only {} placeholders")}function no(o,e){return wl(e),e==null?o:e.replaceAll("{}",()=>o)}function xg(o){if(o instanceof Date)return bt(o);if(U(o))return"N";if(typeof o=="number")return Number.isInteger(o)?"L":"R";throw new TypeError("Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects")}function kg(o,e,{pattern:t="short",locale:r,timeZone:n}){if(!["short","medium","long","full"].includes(t))throw new RangeError("Temporal formatting currently supports short, medium, long and full only");if(e==="DHZ"&&(typeof n!="string"||!n))throw new TypeError("DHZ formatting currently requires an explicit timeZone");let i={timeZone:e==="DHZ"?n:"UTC"};return e!=="H"&&(i.dateStyle=t),e!=="D"&&(i.timeStyle=t),zi(!0,r,i).format(o)}function qi(o){let e=/^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(o);if(!e||e[1]==="("!=(e[4]===")")||o.endsWith("."))throw new RangeError(`Unsupported numeric pattern section: ${o}`);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 Eg(o){let e=o.split(";");if(e.length>3)throw new RangeError("Numeric patterns support at most three sections");let t=qi(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!=="-"&&qi(r);let n=e.length>1?qi(e.at(-1)):null;return{positive:t,zero:r,negative:n}}function oo(o,e={},t={}){if(o===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?xg(o):e.dtype,n=["D","H","DHZ"].includes(r);if(!n&&!["L","R","N"].includes(r))throw new RangeError(`Unsupported format dtype: ${r}`);if(n){if(!(o instanceof Date)||!Number.isFinite(o.getTime()))throw new TypeError(`${r} requires a valid Date object`)}else if(!(typeof o=="number"&&Number.isFinite(o))&&!(U(o)&&!["NaN","Infinity","-Infinity"].includes(o.toString())))throw new TypeError(`${r} formatting requires finite JavaScript numbers or TYTX Decimal values`);if(r==="L"&&!Number.isInteger(o))throw new TypeError("L formatting requires an integer");let{pattern:i,locale:s,mask:a}=e;if(!n&&typeof i!="string")throw new TypeError("Numeric formatting currently requires an explicit pattern");if(typeof s!="string"||!s)throw new TypeError("Formatting currently requires an explicit locale");if(wl(a),n){let b=kg(o,r,e);return no(b,a)}let{positive:l,zero:c,negative:u}=Eg(i),d=zi(!1,s,l.intl),f=U(o),h=f?o.eq(0):o===0,p=f?o.lt(0):o<0;if(f&&zi(!1,"en",{useGrouping:!1}).format("9007199254740993")!=="9007199254740993")throw new Error("This browser cannot format Decimal without precision loss");let m;if(h&&c!==null){if(c==="")return"";if(c==="-")m="-";else{let b=qi(c);m=b.prefix+zi(!1,s,b.intl).format(0)+b.suffix}}else{let b=p&&u?u:l,w=f?(p&&u?o.abs():o).toString():p&&u?-o:o===0?0:o;m=b.prefix+d.format(w)+b.suffix}return no(m,a)}var be="http://www.w3.org/1999/xhtml",kt="http://www.w3.org/2000/svg",Tg=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"]),Sg=["default_","attr_","fire_","connect_on","subscribe_","selfsubscribe_","formsubscribe_","remote_"],Ag={table:["width","border"],editor:["height"],embed:["width","height"],img:["width","height"],canvas:["width","height"]},Ig=["format","mask","locale","timeZone","places","dtype"],Cg=new Set(["href","src","data","action","formaction","xlink:href","xlink_href"]);function Et(o){return Object.fromEntries(Object.entries(o).filter(([e,t])=>!(t&&typeof t=="object"&&Object.hasOwn(t,"$gramlotRef"))&&!Tg.has(e)&&!Sg.some(r=>e.startsWith(r))))}function yr(o,e,t=[]){for(let[r,n]of Object.entries(e)){let i=t.find(a=>r.startsWith(a))??"",s=r.slice(i.length);if(["style","class","_class"].includes(s)&&n!=null&&typeof n!="string")throw new TypeError(`${o.nodeTag} '${o.label}': '${r}' must be a string or null`)}}function vr(o,e,t=[]){if(o.nodeTag==="script"){let r=[["",o.staticValue],...ge(o.getAttr()).filter(([n])=>["src","href","xlink:href","xlink_href","_text"].includes(n.slice((t.find(i=>n.startsWith(i))??"").length).toLowerCase()))];for(let[n,i]of r)if(o.pointerType(i)||Le(i))throw new Error(`script '${o.label}': '${n}' must be literal Source; script code and URLs cannot come from Data`)}if(e.onEnd!=null&&(o.nodeTag.toLowerCase()!=="transformpane"||!o._getMeta("gramlot_component")?.parameters?.onEnd))throw new Error("onEnd is only supported on transformPane");if(e.onChecked!=null&&!o._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(o.nodeTag))throw new Error("onComplete is only supported on an uploader or imageUploader");if(e.onClose!=null&&!o.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose)throw new Error("onClose is only supported on a tab/stack panel");for(let[r,n]of Object.entries(xr(Et(e)))){let i=t.find(a=>r.startsWith(a)),s=i?r.slice(i.length):r;if(/^on./i.test(s))throw new Error(`${o.nodeTag} '${o.label}': '${r}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${s} for an event, or rename the attribute`);if(Cg.has(s.toLowerCase())&&Dg(n))throw new Error(`${o.nodeTag} '${o.label}': '${r}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`)}}function Dg(o){return typeof o=="string"&&/^javascript:/i.test(o.replace(/[\t\n\r]/g,"").replace(/^[\u0000-\u0020]+/,""))}function yl(o,e,t=[]){if(o.nodeTag!=="iframe")return e;let r=a=>{let l=t.find(c=>a.startsWith(c))??"";return[l,a.slice(l.length).toLowerCase()]},n=Object.fromEntries(ge(o.getAttr())),i=[...Object.keys(n),...Object.keys(e)].find(a=>r(a)[1]==="srcdoc");if(i===void 0||Object.keys(n).some(a=>r(a)[1]==="sandbox")||o.pointerType(o.value)===null&&!(Object.hasOwn(n,i)&&(o.pointerType(n[i])!==null||Le(n[i]))))return e;let s=Object.fromEntries(Object.entries(e).filter(([a])=>r(a)[1]!=="sandbox"));return{[`${r(i)[0]}sandbox`]:"",...s}}function xr(o){return Object.fromEntries(Object.entries(o).filter(([,e])=>e!=null))}function cn(o){return Object.fromEntries(Object.entries(o).map(([e,t])=>e.startsWith("xmlns_")?[`xmlns:${e.slice(6)}`,t]:e.startsWith("data_")||e.startsWith("aria_")?[e.replaceAll("_","-"),t]:[e,t]))}function io(o){let{_meta:e,...t}=o;return cn(xr(Et(t)))}function vl(o,e){let t=Ag[String(o).toLowerCase()]??[],r={},n={};for(let[i,s]of Object.entries(e))t.includes(i)?n[i]=s:r[i]=s;return[r,n]}function _r(o){return String(o)}function un(o,e,t=null){let r={...e},{mask:n,format:i,locale:s,timeZone:a,dtype:l,places:c}=r;for(let d of Ig)delete r[d];let u=d=>{if(t&&i!=null){if(c!=null)throw new RangeError("places is not implemented; specify precision in format");return t(d,{pattern:i,mask:n,...s==null?{}:{locale:s},...a==null?{}:{timeZone:a},...l==null?{}:{dtype:l}})}if(typeof d=="boolean"&&(d=_r(d)),n==null)return d;let f=d==null?"":_r(d);return f===""?f:no(f,n)};return Array.isArray(o)?(Object.hasOwn(r,"_text")&&(r._text=u(r._text)),[o,r]):[u(o),r]}function Le(o){return typeof o=="string"&&o.startsWith("==")}var Ui=class{#e;#t;#r;#n;#o;#i;#s;#a=null;#l=!1;#c=[];#u=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 n=r.createElementNS(kt,"svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let i=r.createElementNS(kt,"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"),n.append(i),this.#n.append(n),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 s=r.createElement("slot");s.name="overflow",this.#r.append(s),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(c=>c.localName==="gramlot-menu"&&c!==e)&&(l.preventDefault(),l.stopPropagation(),this.close())});let a=r.createElement("style");a.textContent=`
|
|
121
116
|
:host([role=toolbar]){min-width:0;min-height:0;max-width:100%;width:100%;flex-shrink:1;gap:0}
|
|
122
117
|
:host([role=toolbar][aria-orientation=vertical]){width:auto;height:100%;max-height:100%}
|
|
123
118
|
.toolbar-viewport{display:contents}
|
|
@@ -134,7 +129,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
134
129
|
max-width:var(--gramlot-popup-available-width);max-height:var(--gramlot-popup-available-height);overflow:auto;
|
|
135
130
|
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
131
|
.toolbar-overflow ::slotted([role=separator]){margin:5px 7px;border-top:1px solid var(--gramlot-border-control,#888)}
|
|
137
|
-
`,e.shadowRoot.append(
|
|
132
|
+
`,e.shadowRoot.append(a,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.#u.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.#a!==null&&this.#e.ownerDocument.defaultView.cancelAnimationFrame(this.#a),this.#a=null,this.#c=[]}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.#u.clear(),this.#n.hidden=!0;return}this.#o||this.connect(),this.#a===null&&(this.#a=this.#e.ownerDocument.defaultView.requestAnimationFrame(()=>{this.#a=null,this.layout()}))}}layout(){let e=this.#e,t=e.ownerDocument.defaultView;if(!e.permanent||!e.isConnected)return;let r=e.parameters.orientation==="vertical",n=r?"height":"width",i=t.getComputedStyle(e),s=(r?e.clientHeight:e.clientWidth)-parseFloat(i[r?"paddingTop":"paddingLeft"]||0)-parseFloat(i[r?"paddingBottom":"paddingRight"]||0);if(s<=0)return;let a=e.ownerDocument.activeElement;for(;a?.shadowRoot?.activeElement;)a=a.shadowRoot.activeElement;let l=[...e.children].filter(b=>!b.hidden&&(Ie(b).localName!=="gramlot-menu"||Ie(b).permanent));for(let b of this.#c)l.includes(b)||(this.#o.unobserve(b),b.removeAttribute("slot"),b.removeAttribute("data-menu-overflow"));for(let b of l)this.#c.includes(b)||this.#o.observe(b);this.#c=l;for(let b of l)b.removeAttribute("slot"),b.removeAttribute("data-menu-overflow");this.#u.clear(),e.refreshItems();for(let b of e.items)b.refreshAvailability();this.#t.setAttribute("data-measuring","");let c=parseFloat(t.getComputedStyle(this.#t).gap)||0,u=new Map(l.map(b=>{let w=t.getComputedStyle(b),_=Ie(b).localName==="gramlot-spacer"?Ie(b).parameters.size??0:b.getBoundingClientRect()[n];return[b,_+(parseFloat(w[r?"marginTop":"marginLeft"])||0)+(parseFloat(w[r?"marginBottom":"marginRight"])||0)]}));this.#t.removeAttribute("data-measuring");let d=b=>Ie(b).getAttribute("role")==="separator",f=b=>b.filter((w,_)=>!d(w)||b.slice(0,_).some(v=>Ie(v).localName!=="gramlot-spacer"&&!d(v))&&b.slice(_+1).find(v=>Ie(v).localName!=="gramlot-spacer")&&!d(b.slice(_+1).find(v=>Ie(v).localName!=="gramlot-spacer"))),h=b=>b.reduce((w,_)=>w+u.get(_),0)+Math.max(0,b.length-1)*c,p=f(l);if(h(p)>s){let b=l.length;for(;b>0&&h(p)>s-32;)b--,p=f(l.slice(0,b));let w=f(l.slice(b).filter(_=>Ie(_).localName!=="gramlot-spacer"));for(let _ of w)this.#u.add(_)}for(let b of l)!p.includes(b)&&!this.#u.has(b)&&(b.slot="suppressed");for(let b of this.#u)b.slot="overflow",b.setAttribute("data-menu-overflow","");this.#n.hidden=this.#u.size===0;for(let b of e.items)b.refreshAvailability();e.refreshItems();let m=l.find(b=>{let w=a;for(;w;){if(w===b)return!0;w=w.parentNode??w.host}return!1});this.#u.size===0?this.close(!1):m&&this.#u.has(m)?this.open(!1):this.#l&&this.#d(),m&&a?.isConnected&&a.focus({preventScroll:!0}),e.refreshItems()}#d(){wr(this.#r,this.#n,{placement:this.#e.parameters.orientation==="vertical"?"side":"bottom"})}open(e=!0){if(this.#u.size){if(!this.#l){this.#r.showPopover(),this.#l=!0,this.#n.setAttribute("aria-expanded","true"),this.#s=new this.#e.ownerDocument.defaultView.AbortController;let t={signal:this.#s.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=n=>{if(n.hidden||n.disabled)return null;if(n.localName==="gramlot-menu-line"&&!n.parameters.group)return n.getAttribute("role")==="separator"?null:n;if(n.matches('input:not([type=hidden]),textarea,select,button,[tabindex="0"]'))return n;for(let i of n.children){let s=t(i);if(s)return s}return null};([...this.#e.children].filter(n=>this.#u.has(n)).map(t).find(Boolean)??this.#r).focus()}}}close(e=!0){if(this.#l){for(let t of this.#u)for(let r of t.querySelectorAll("gramlot-menu"))r.permanent||r.close(!1);this.#r.hidePopover(),this.#l=!1,this.#s?.abort(),this.#n.setAttribute("aria-expanded","false"),e&&!this.#n.hidden&&this.#n.focus()}}};function tf(o){return class extends o{#e;#t;#r=null;#n=[];#o=null;#i;#s;#a;#l;#c=!1;#u;#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
133
|
:host([role=menu]){position:fixed;inset:auto;margin:0;padding:3px;min-width:0;width:max-content;font:inherit;
|
|
139
134
|
max-width:min(28rem,var(--gramlot-popup-available-width));max-height:var(--gramlot-popup-available-height);overflow:auto;
|
|
140
135
|
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 +138,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
143
138
|
:host([role=menu]) ::slotted([role=separator]){margin:5px 7px 5px 2.5rem;border-top:1px solid var(--gramlot-border-control,#888)}
|
|
144
139
|
: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
140
|
: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.#
|
|
141
|
+
.status:empty{display:none} button{font:inherit}`,this.#l=e.createElement("slot"),this.#s=e.createElement("span"),this.#s.className="status",this.#s.setAttribute("role","status"),this.#a=e.createElement("button"),this.#a.textContent="Riprova",this.#a.hidden=!0,this.#a.addEventListener("click",n=>{n.stopPropagation(),this.menuBinding.load(!0)}),t.append(r,this.#l,this.#s,this.#a),this.#i=new Ui(this,this.#l),this.addEventListener("keydown",n=>this.#h(n)),this.addEventListener("focusin",n=>{let i=n.composedPath().find(s=>this.items.includes(s));i&&(this.#r=i,this.refreshItems())})}get permanent(){return this.parameters.presentation==="bar"}get opened(){return this.permanent||this.#c}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=>Ht(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.#u=null,this.#c=!1}projectAttributes(e){let t=br(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=Ht(this).parentElement;if(this.permanent||!e)return;if(["gramlot-menu-line","gramlot-drop-down-button"].includes(e.localName)){Ht(this).slot="menu";return}if(e.localName==="gramlot-grouplet-card"){Ht(this).slot="card-menu";return}if(Ht(this).removeAttribute("slot"),e.localName==="gramlot-menu")return;this.#u=e,this.#d=new this.ownerDocument.defaultView.AbortController;let t={signal:this.#d.signal},r=i=>!i.composedPath().some(s=>s.localName==="gramlot-menu"),n=i=>{if(this.hidden||this.permanent||!r(i)||i.composedPath().some(c=>c instanceof this.ownerDocument.defaultView.Element&&(c.disabled===!0||c.getAttribute("aria-disabled")==="true")))return;let s=this.#f();if(i.type==="click"){if(s===null||i.button!==0||["shift","ctrl","alt","meta"].some(c=>!!i[c+"Key"]!==s.includes(c)))return}else if(s!==null)return;i.preventDefault(),i.stopPropagation();let a=i.type==="keydown",l=a?e.getBoundingClientRect():null;this.open(e,!1,a?{x:l.left+8,y:l.top+8}:{x:i.clientX,y:i.clientY})};e.addEventListener("click",n,t),e.addEventListener("contextmenu",n,t),e.addEventListener("keydown",i=>{(i.key==="ContextMenu"||i.key==="F10"&&i.shiftKey&&!i.ctrlKey&&!i.altKey&&!i.metaKey)&&n(i)},t)}setStatus(e){this.status=e,this.#s.textContent={loading:"Caricamento\u2026",empty:"Nessuna voce",error:"Impossibile caricare"}[e]??"",this.#a.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,n,i]of[["check",this.visibleItems.some(s=>s.parameters.checked!=null),"1.4em"],["icon",this.visibleItems.some(s=>s.entryIcon||s.entryIconSrc),"1.5em"],["arrow",this.visibleItems.some(s=>s.submenu),".9em"]])this.style.setProperty(`--gramlot-menu-${r}-track`,n?i:"0px");if(this.#r&&!e.includes(this.#r)){let r=this.#n.indexOf(this.#r),n=this.#n.slice(r+1).find(i=>e.includes(i))??this.#n.slice(0,r).reverse().find(i=>e.includes(i));this.#r=n??null,this.opened&&this.status!=="loading"&&(n?n.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.#c||(this.showPopover(),this.#c=!0),e.setAttribute("aria-expanded","true"),this.#e?.abort(),this.#e=new this.ownerDocument.defaultView.AbortController;let n={signal:this.#e.signal},i=()=>wr(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,n),this.ownerDocument.addEventListener("scroll",i,{...n,capture:!0}),this.ownerDocument.addEventListener("pointerdown",s=>{!s.composedPath().includes(this)&&(e===this.#u||!s.composedPath().includes(e))&&this.closeChain(!1)},n),this.menuBinding?.load().then(()=>{this.#c&&(this.ownerDocument.activeElement===this||!this.contains(this.ownerDocument.activeElement))&&this.focusEntry(t),this.#c&&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.#c&&(this.hidePopover(),this.#c=!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(c=>c.localName==="gramlot-menu")!==this)return;let t=e.composedPath().find(c=>this.items.includes(c));if(!t&&e.target!==this)return;let r=t&&this.isOverflowed(t),n=this.usableItems.filter(c=>this.isOverflowed(c)===!!r),i=n.indexOf(t),s=this.permanent&&!r&&this.parameters.orientation==="horizontal"?"ArrowRight":"ArrowDown",a=this.permanent&&!r&&this.parameters.orientation==="horizontal"?"ArrowLeft":"ArrowUp",l;if(e.key===s&&(l=Math.min(n.length-1,i+1)),e.key===a&&(l=Math.max(0,i-1)),e.key==="Home"&&(l=0),e.key==="End"&&(l=n.length-1),l!==void 0){e.preventDefault(),e.stopPropagation(),n[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(c=>c.submenu?.opened))||!this.permanent&&e.key==="ArrowLeft"&&this.parentMenu?(e.preventDefault(),e.stopPropagation(),this.close()):e.key==="Tab"&&this.closeChain(!1)}}}function rf(o){return class extends o{#e;#t;#r;#n;#o;#i;#s=null;#a=!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
142
|
.menu-check:empty,.menu-arrow:empty{display:none}
|
|
148
143
|
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
144
|
align-items:center;width:100%;min-height:max(24px,var(--gramlot-touch-target,0px));padding:2px 7px;
|
|
@@ -180,7 +175,7 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
180
175
|
:host([data-menu-overflow]) .menu-group,:host([data-menu-group-rows]) .menu-group{flex-direction:column;align-items:stretch;padding:3px 0}
|
|
181
176
|
:host([data-menu-overflow][role=group]){border-block-end:1px solid var(--gramlot-border-control,#888);margin-block-end:4px}
|
|
182
177
|
: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
|
|
178
|
+
: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 n of this.menuOwner.items)n.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(Ie).find(e=>e?.localName==="gramlot-menu")??null}get entryCaption(){return this.parameters.caption??this.#s?.label??""}get entryIcon(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.icon:this.#s?.icon}get entryIconSrc(){return this.parameters.icon||this.parameters.iconSrc?this.parameters.iconSrc:this.#s?.iconSrc}get occurrence(){return this.parameters.code??this.sourceLabel}setCommandDefinition(e,t){this.#s=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.#a=!!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.#a)),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.#s?"???":this.entryCaption,this.caption.hidden=!0,this.renderIcon(this.entryIcon,this.entryIconSrc);let t=this.parameters.tooltip??this.#s?.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=a=>{for(let l=this;l&&l!==e;l=l.parentElement)if(l.localName==="gramlot-menu-line"&&l.parameters[a]!=null)return l.parameters[a];return e?.parameters[a]},n=!!(e?.permanent&&!t),i=r("labelPosition");this.control.classList.toggle("toolbar-button",n),this.control.classList.toggle("toolbar-below",n&&i==="below"),this.control.classList.toggle("toolbar-tooltip",n&&i==="tooltip"),n?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?n&&i==="tooltip"?"\u2304":t||e?.parameters.orientation==="vertical"?"\u203A":"\u25BE":"";let s=this.#a||this.getAttribute("role")==="separator"||!!(this.parameters.command&&!this.#s)||["loading","error"].includes(e?.status)||!!this.closest("gramlot-drop-down-button")?.parameters.disabled;this.control.disabled!==s&&(this.control.disabled=s),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=Ht(this.menuOwner)?.parentElement;return t?.localName==="gramlot-drop-down-button"?t.selectCommand(this,e.shiftKey):this.menuOwner.closeChain(),!0}}}function so(o){return class extends ro(o){#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
179
|
button{display:inline-flex;align-items:center;justify-content:center;gap:var(--gramlot-button-gap,.35em);font:inherit;
|
|
185
180
|
color:var(--gramlot-button-color,var(--gramlot-ink,CanvasText));background:var(--gramlot-button-background,var(--gramlot-field-background,Canvas));
|
|
186
181
|
border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
|
|
@@ -220,33 +215,34 @@ ${" ".repeat(o)}</${a}>`:`<${a}${l}>${f}</${a}>`:t===null||t.includes(a)?`<${a}
|
|
|
220
215
|
#control.icon-only .led{display:none}
|
|
221
216
|
@media(forced-colors:active){#control.icon-only{background:ButtonFace;color:ButtonText;border-color:ButtonText}
|
|
222
217
|
#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 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,
|
|
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}
|
|
218
|
+
`,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=n=>n.nodeType===3?!!n.textContent.trim():n.nodeType===1&&!n.hidden&&n.getAttribute("slot")!=="menu",t=!this.caption.hidden&&this.caption.assignedNodes().some(e),r=[...this.control.children].some(n=>n!==this.icon&&n!==this.caption&&!n.hidden&&!n.matches(".led,.menu-check,.menu-arrow")&&!(n.matches(".menu-caption")&&this.control.classList.contains("toolbar-tooltip"))&&!!n.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}}}so.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 Ng=Yt({name:"button",tag:"gramlot-button",base:so,command:!0,subTags:"*",implementation:o=>class extends o{}}),Og=Yt({name:"toggleButton",tag:"gramlot-toggle-button",base:so,command:!0,subTags:"*",parameters:{value:{dtype:"B",default:!1,binding:"twoWay"},readonly:{dtype:"B",default:!1,binding:"read"}},implementation:o=>class extends o{#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)}}}),$g=Yt({name:"menu",tag:"gramlot-menu",base:tf,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:o=>class extends o{}}),Rg=Yt({name:"menuline",tag:"gramlot-menu-line",base:so,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:rf}),jg=Yt({name:"spacer",tag:"gramlot-spacer",base:o=>class extends o{projectAttributes(e){let t=br(this,e),{size:r,flex:n}=this.parameters;if(r!=null&&n!=null)throw new TypeError("spacer accepts size or flex, not both");if(r!=null&&(!Number.isFinite(r)||r<0)||n!=null&&(!Number.isFinite(n)||n<=0))throw new TypeError("Invalid spacer size/flex");return this.style.flex=n!=null?`${n} 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:o=>class extends o{}}),Pg=Yt({name:"dropDownButton",tag:"gramlot-drop-down-button",base:so,command:!0,subTags:"*",parameters:{persist:{dtype:"B",default:!1}},implementation:o=>class extends o{#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=cl+".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",n=>{n.stopPropagation(),this.menu.opened?this.closeMenu():this.openMenu()}),this.#n.addEventListener("keydown",n=>{["ArrowDown","ArrowUp"].includes(n.key)&&(n.preventDefault(),this.openMenu(n.key==="ArrowUp"))})}get menu(){return[...this.children].map(Ie).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(n=>n.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()}}}),Vi=fl({name:"buttons",components:[Ng,Og,Pg,$g,Rg,jg]});var kl={};ee(kl,{ValidationRun:()=>kr});var kr=class{epoch=0;controller=null;cancel(){this.epoch++,this.controller?.abort(),this.controller=null}start(e,t,r,n,i,s=()=>{}){this.cancel();let a=new AbortController,l=this.epoch;this.controller=a;let c=r.validationCurrent(),u=()=>l===this.epoch&&!a.signal.aborted&&c(),d=m=>({value:e,modified:!1,error:m.message,warnings:[],issues:[],datachanges:[]}),f=!1,h=m=>{if(f||!u())return{ok:!1};f=!0,this.controller=null;let b={ok:!m.error,value:m.value,result:m,rules:t,isCurrent:u};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=n(e,t,{...r,signal:a.signal})}catch(m){return h(d(m))}return p instanceof Promise?(s(),new Promise(m=>{let b,w=()=>{clearTimeout(b),m({ok:!1})};a.signal.addEventListener("abort",w,{once:!0});let _=v=>{clearTimeout(b),a.signal.removeEventListener("abort",w);try{m(h(v))}catch(E){r.reportError(E,"Validation completion failed"),m({ok:!1})}};t.validate_timeout!=null&&(b=setTimeout(()=>{_(d(new Error("Validation timed out."))),a.abort()},t.validate_timeout)),p.then(_,v=>_(d(v)))})):h(p)}};function ao(o){return typeof o=="string"&&!["null","true","false"].includes(o)&&/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(o)}function Tt(o,e,t,r){let{group:n,method:i}=o.logicRegistry.resolve(t,e);return i.call(n,e,r)}function dt(o,e,t,r,n,i=Object.keys(n)){return ao(r)?Tt(o,e,r,n):o.inlineCompiler.compile(e,t,r,i)(n)}function Wi(o){let e=o.node,t=o.runtime.gramlot,r=(n,i,s,a=!1)=>a?o.runtime.inlineCompiler.compile(e,n,i,Object.keys(s),`return (${i});`)(s):dt(o.runtime,e,n,i,s);return{isDecimal:U,invoke:r,callLogic:(n,i)=>Tt(o.runtime,e,n,i),remote:(n,i,s)=>t.rpc.call("data",n,i,{signal:s}),reportError:(n,i)=>{o.closed||o.runtime.reportError(n,i)},validationCurrent:()=>{let n=e.getAttr("value"),i=e.pointerType(n)?e.absDatapath(n):null;return()=>!o.closed&&e.getAttr("value")===n&&(i===null||e.absDatapath(n)===i)},finishValidation:({ok:n,result:i,rules:s})=>{if(o.closed)return;if(n)for(let l of i.datachanges)e.getRelativeData(".").update(l);let a=n?"validate_onAccept":"validate_onReject";if(s[a]){let l=c=>{o.closed||o.runtime.reportError(c,"Validation callback failed")};try{let c=Object.fromEntries(Object.entries(s).map(([d,f])=>[d.slice(9),f])),u=r(a,s[a],{value:i.value,result:i,validations:c,userChange:!0});u instanceof Promise&&u.catch(l)}catch(c){l(c)}}},checkDataPatch:n=>{if(!(n instanceof x))throw new TypeError("Validation data changes must be a Bag.");if(!(e.getRelativeData(".")instanceof x))throw new TypeError("Validation data changes require a Bag datapath.")}}}var Zt=o=>j(R(o)),Er=(o,e)=>R(o)===R(e),lo=o=>o.absDatapath(o.getAttr("value")),Ue=o=>encodeURIComponent(o).replaceAll(".","%2E"),Kt=o=>Ue(lo(o)),nf=(o,e)=>Ue(o.fullpath)+":"+e,co=class{constructor(e,t,r=e.absDatapath(".")){if(this.node=e,this.runtime=t,this.registers=new x,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 x))throw new TypeError("A form requires a Bag at its datapath.");this.registers.setItem("baseline",Zt(this.data));for(let n of["changes","errors","pending","drafts"])this.registers.setItem(n,new x);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 x))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 x);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 x?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(`
|
|
219
|
+
`)}))}get changeEntries(){let e=[];for(let t of this.registers.getItem("changes").getNodes()){let r=t.value,n=[this.path,r.getItem("path")].filter(Boolean).join("."),i=r.getItem("existed"),s=r.getItem("exists"),a=r.getItem("previous"),l=r.getItem("current");if((!i||!s||!Er(a,l))&&e.push({path:n,previous:a,current:l,existed:i,exists:s}),i&&s){let c=r.getItem("previousAttributes"),u=r.getItem("currentAttributes");for(let d of new Set([...c.getNodes(),...u.getNodes()].map(f=>f.label))){let f=c.getNode(d)!==null,h=u.getNode(d)!==null;(f!==h||!Er(c.getItem(d),u.getItem(d)))&&e.push({path:n+"?"+d,previous:c.getItem(d),current:u.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(lo(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 n=this.registers.getItem(r),i=Ue(e);n.getNode(i)&&n.popNode(i)}this.notify()}}fieldStatus(e){let t=Ue(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,n=this.registers.getItem("drafts").length>0;return{dirty:e,pending:t,valid:!r&&!n,canSave:e&&!r&&!n&&!t,status:r?"error":t||n?"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 n=this.registers.getItem("drafts").getNode(Kt(t));n&&(t.formDraft=n.value,e.element.restoreFormDraft(n.value)),r.result&&e.element.presentValidation(r.result);let i=this.registers.getItem("errors").getItem(Kt(t));i&&e.element.error(i.getNodes().map(s=>s.value).join(`
|
|
220
|
+
`)),e.element.setFieldState({invalid:!!i,pending:!!this.fieldStatus(r.path).pending})}),()=>{this.fields.delete(t)}}registerField(e,t,r=!0){let n=this.validations.get(e);if(n)return n;if(!t.validationExecutor)throw new TypeError("Grid editors require shared input validation.");let i=this.runtime.bindingFor(e),s=Wi(i);return n={node:e,binding:i,context:s,component:t,run:new kr,execute:t.validationExecutor,checkValue:t.validationValueCheck(s),path:lo(e),rules:null,value:void 0,target:null,result:null,selection:null},this.validations.set(e,n),i.editingSession=this,n.release=i.track(()=>this.forgetField(e)),this.refreshField(e,r),n}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 s of this.fields.values())Object.hasOwn(s.node,"formDraft")&&s.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,n=new WeakSet,i=async()=>{let s=0;for(;r();){let a=t.next();if(a.done)return;let{node:l,release:c}=a.value;try{if(n.has(l))continue;n.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),c()}++s%20===0&&await new Promise(u=>setTimeout(u,0))}};return e.promise=Promise.resolve().then(async()=>{let a=(await Promise.allSettled(Array.from({length:8},()=>i().catch(c=>{e.failed=!0;for(let u of e.active)this.cancelValidation(u);throw c})))).find(c=>c.status==="rejected");if(a)throw a.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 n=this.registers.getItem(r).getItem(Ue(t.path));if(n){for(let i of[...n.getNodes()])i.label.startsWith(Ue(e.fullpath)+":")&&n.popNode(i.label);n.length||this.registers.getItem(r).popNode(Ue(t.path))}}if(![...this.validations.values()].some(r=>r.path===t.path)){let r=this.registers.getItem("drafts");r.getNode(Ue(t.path))&&r.popNode(Ue(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[,n]=e.rootBuilder.runtimeValues(e),i=r.component.validationParameters(this.runtime.renderer.evaluateExpressions(e,n)),s=Object.fromEntries(Object.entries(i).filter(([f])=>f.startsWith("validate_"))),a=R(Object.fromEntries(Object.entries(i).filter(([f])=>f!=="value"))),l=lo(e),c=this.runtime.gramlot.data.getNode(l.split("?")[0]),u=e.getRelativeData(e.getAttr("value")),d=r.path!==l||r.target!==c||!Er(r.value,u);if(!(!d&&r.configuration===a)){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(Ue(r.path))&&h.popNode(Ue(r.path))}Object.assign(r,{path:l,target:c,value:u,rules:s,configuration:a,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 n of this.validations.keys())n!==e&&this.refreshField(n)}validateCandidate(e,t,r){this.invalidateValidation(),this.cancelValidation(e),this.writeCandidate(e,t);let n=this.validations.get(e);return n.selection=r,this.validateField(e,!1)}scheduleField(e){this.disposed||!this.validations.has(e)||this.validationQueue.has(e)||this.registers.getItem("drafts").getNode(Kt(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(Kt(e)))||this.registers.getItem("pending").getItem(Kt(e))?.getItem(nf(e,"selection")))return;let n=e.getRelativeData(e.getAttr("value")),i=this.fields.get(e);t&&i&&(r.selection=i.element.validationSelection());let s=r.selection,a=r.target,l=r.context.validationCurrent();return r.run.start(n,r.rules,{...r.context,validationCurrent:()=>()=>!this.disposed&&l()&&this.validations.get(e)===r&&this.runtime.gramlot.data.getNode(r.path.split("?")[0])===a,selection:s},r.execute,c=>{if(c.ok)try{r.checkValue(c.value,n)}catch(d){c.ok=!1,c.result.error=d.message}this.result(e,c.result),r.result=c.result,c.ok&&this.writeCandidate(e,c.value);let u=this.fields.get(e);u&&u.element.presentValidation(c.result),r.context.finishValidation(c)},()=>{this.pendingPart(e,"validation","active"),this.fields.get(e)?.element.setFieldState({pending:!0})})}remove(e,t){let r=this.registers.getItem(e),n=Kt(t);r.getNode(n)&&r.popNode(n)}set(e,t,r){r==null?this.remove(e,t):this.registers.getItem(e).setItem(Kt(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,n){r=nf(t,r);let i=this.registers.getItem(e),s=Kt(t),a=i.getItem(s);!a&&n!=null&&(a=new x,i.setItem(s,a)),a&&(n==null?a.getNode(r)&&a.popNode(r):a.setItem(r,n),a.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]:"",n=(l,c,u)=>{if(u&&this.isDerived(u))return;let d=l&&this.ownAttributes(l,u),f=c&&this.ownAttributes(c,u);if(l&&c&&l.value instanceof x&&c.value instanceof x&&Er(d,f)){let h=new Set([...l.value.getNodes(),...c.value.getNodes()].map(p=>p.label));for(let p of h)n(l.value.getNode(p),c.value.getNode(p),u?u+"."+p:p)}else(l&&c?!Er([l.value,d],[c.value,f]):!(this.onlyDerived(l,u)&&this.onlyDerived(c,u)))&&t.setItem(Ue(u),new x({path:u,existed:!!l,exists:!!c,previous:l?Zt(l.value):null,current:c?Zt(c.value):null,previousAttributes:l?Zt(d):null,currentAttributes:c?Zt(f):null}))},i=this.registers.getItem("baseline"),s=r;for(let l of t.getNodes()){let c=l.value.getItem("path");s.startsWith(c+".")&&(s=c)}let a=s;for(;a.includes(".");){a=a.slice(0,a.lastIndexOf("."));let l=i.getNode(a),c=this.data.getNode(a);(!l||!c||!Er(l.attr,c.attr))&&(s=a)}for(let l of[...t.getNodes()]){let c=l.value.getItem("path");(!s||c===s||c.startsWith(s+"."))&&t.popNode(l.label)}s?n(i.getNode(s),this.data.getNode(s),s):n({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||!Er(t,new x(e)))&&(this.registers.setItem("status",new x(e)),this.node.publish("formStatus",e));for(let r of this.listeners)r()}))}commitField(e){for(let t of this.fields.values())lo(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",Zt(this.data)),this.updateChanges(),!0)}load(e){if(!(e instanceof x))throw new TypeError("Editing load requires a Bag.");this.disposed||(this.registers.setItem("baseline",Zt(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,Zt(this.registers.getItem("baseline")));for(let e of["errors","pending","drafts"])this.registers.setItem(e,new x);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 Bg(o,e,t=o){let r=new Map,n=new Set,i=new Map;for(let[a,l]of e){if(typeof a!="string")continue;let c=H(l)?.pointer??l;i.set(a,c instanceof Y?c.resolve():o.pointerType(c)?t.getRelativeData(c):Le(c)?null:c)}let s=a=>{if(r.has(a))return r.get(a);if(!e.has(a))throw new Error(`Source attribute '${a}' does not exist`);if(n.has(a))throw new Error(`cyclic attribute dependency: ${[...n,a].join(" -> ")}`);n.add(a);let l=e.get(a),c=H(l),u=c?i.get(a):null,d,f=h=>h?s(h):u;try{if(c)if(c.expression){let h=Jr(c.body),p=h.slots.map(f);d=o.rootBuilder.evaluatePointerExpression(o,a,l,h,p)}else d=zt(c.body,f),u==null&&(d=null);else d=i.get(a);return r.set(a,d),d}finally{n.delete(a)}};return{resolve:s}}function Jt(o,e,t=o){let r=new Map([...Object.entries(o.getAttr()),...ge(o.getAttr())]);return Bg(o,r,t).resolve(e)}var Mg={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"]},El=["_cachedRemote","_if","_else","_onRemote","_onCalling","_delay","_timing","_userChanges"],Lg=["_if","_else","_onRemote","_onCalling"],Tl=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 n=R(t);return this.#t?this.#r?Promise.resolve(void 0):new Promise((i,s)=>{this.#r={method:e,text:n,perform:r,resolve:i,reject:s}}):(this.#r?.resolve(void 0),this.#r=null,this.#i(e,t,n,r))}catch(n){return Promise.reject(n)}}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,n){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,s={method:e,params:t,text:r,controller:i,ignored:!1};s.view=Object.freeze({method:e,get params(){return j(r)},sentAt:Date.now(),cancel:()=>this.#a(s)}),this.#t=s,i.signal.addEventListener("abort",()=>this.#s(s),{once:!0});let a;try{a=Promise.resolve(n(s))}catch(l){a=Promise.reject(l)}return a.then(()=>this.#s(s),()=>this.#s(s)),a}#s(e){this.#t===e&&(this.#t=null,this.#o())}#a(e){this.#t===e&&(e.ignored=!0,this.#t=null,this.#n||this.#o())}};function of(o){return typeof o=="string"&&o.startsWith("==")}function Fg(o){let e=[],t=r=>{for(let n of r.getNodes())n.nodeTag==="column"&&typeof n.getAttr("formula")=="string"?e.push([`struct.${n.getAttr("field")}.formula`,n.getAttr("formula")]):(n._getMeta("gridStruct")||n.nodeTag==="colgroup")&&n.staticValue instanceof N&&t(n.staticValue)};return o.staticValue instanceof N&&t(o.staticValue),e}var Tr=class extends Se{#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 x))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 co(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 co(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 N?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 N?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 N?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 N?this.value.getNodes().find(n=>n.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 Tl(this.rootBuilder.nameSyntax)}codeAttributes(){let e=[...Mg[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"?Lg:[]],t=[];for(let[r,n]of Object.entries(this.getAttr()??{}))typeof n=="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,n]);for(let r of["ask","_ask"]){let n=this.getAttr(r);if(n&&typeof n=="object")for(let i of["_if","askIf"])typeof n[i]=="string"&&t.push([`${r}.${i}`,n[i]])}for(let[r,n]of ge(this.getAttr()))if(of(n)&&t.push([r,n]),this.nodeTag==="script"&&typeof n=="string"){let i=this.builder.constructor.dialectPrefixes.find(s=>r.startsWith(s))??"";["src","href","xlink:href","xlink_href","_text"].includes(r.slice(i.length).toLowerCase())&&t.push([r,n])}return(of(this.staticValue)||this.nodeTag==="script"&&typeof this.staticValue=="string")&&t.push(["",this.staticValue]),this._getMeta("gramlot_component")?.bagStruct&&t.push(...Fg(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[...ge(this.getAttr()),["datapath",this.getAttr("datapath")]])H(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 n=Object.keys(t).find(s=>s.startsWith("_")&&!El.includes(s));if(n)throw new TypeError(`${this.nodeTag} '${this.label}': remote parameter '${n}' is not accepted; the control attributes are ${El.join(", ")}`);let i={remote:e};for(let[s,a]of Object.entries(t))i[El.includes(s)?s:`remote_${s}`]=a;return this.setAttr(i),on(this)}publish(e,t={}){return this.rootBuilder.binding.subscriptions.publishNode(this,e,t)}pointers(){let e=this.getAttr("datapath"),t=H(e)?Ze(this,e):new Set,r=super.pointers().filter(([n,i])=>!(this.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(n))&&!t.has(n)&&!this.#a(n,i)).map(([n,i])=>[n,H(i)?.pointer??i]);for(let n of t){let i=this.getAttr(n);this.pointerType(i)==="^"&&r.push(["datapath",H(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 _t(()=>r));continue}if(this.pointerType(r)){if(H(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 _t(()=>Jt(this,t)));continue}this.#a(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 H(t)?Jt(this,e):this.pointerType(t)&&this.#a(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 n=this.absDatapath(e);if(n.includes("?")){this.#i(n,t);return}this.data.getNode(n)?.setValue(null,!1);try{this.fireEvent(e,t,{attributes:r})}finally{this.data.getNode(n)?.setValue(null,!1)}}#i(e,t){let[r,n]=e.split("?",2),i=this.data;i.getNode(r)?.setAttr({[n]:null},!1);try{let s=i.getNode(r);s?s.setValue(s.staticValue,!0,{[n]:t},!0,!0,!0,!0):i.setItem(r,null,{[n]:t},">",!0,!0,!0,!0)}finally{i.getNode(r)?.setAttr({[n]:null},!1)}}FIRE_AFTER(e,t=!0,r=10){this.#l(e);let n=this.rootBuilder?.binding?.bindingFor(this)??null,i=null,s=setTimeout(()=>{i?.(),this.FIRE(e,t)},r);return i=n?.track(()=>clearTimeout(s))??null,()=>{clearTimeout(s),i?.()}}absDatapath(e){e=H(e)?.pointer??e;let t=this.pointerType(e)?e.slice(1):e;if(t.startsWith("#")&&t.includes("?")){let[r,n]=t.split("?",2),i=super.absDatapath(r);return i===null?null:`${i}?${n}`}return super.absDatapath(e)}_composeRelativeDatapath(e,t){let r=this;for(;r!==null&&e.startsWith(".");){let n=r.getAttr("datapath");if(this.pointerType(n)&&(n=this.#s(r,n),n===null))return null;if(n!=null&&(e=e==="."?n:n+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 n=this.rootBuilder?.binding;if(!n)return super._resolveSymbolicDatapath(e,t);let i=n.nodeIds.get(r);if(!i)throw new Error(`#<id>: cannot resolve ${t}`);let s=e.slice(r.length+2);return i.absDatapath(s?`.${s}`:".")}#s(e,t){if(H(t)){let i=Jt(e,"datapath",e.parentNode);return i==null||i===""?null:i}let r=e.parentNode.absDatapath(t);if(r===null)return null;let n=this.data.getItem(r);return n==null||n===""?null:n}#a(e,t){return H(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}'`)}},de=class o extends N{get nodeClass(){return Tr}authorizedCopy(e){let t=new this.constructor;for(let r of this.getNodes()){let n=r.getAttr("auth")??null;if(n!==null){if(typeof n!="string")throw new TypeError(`${r.nodeTag} '${r.label}': 'auth' must be a string rule, not ${typeof n}`);if(e(n)!==null)continue}let i=r.staticValue;i instanceof o&&(i=i.authorizedCopy(e));let{auth:s,...a}=r.getAttr(),l=t.setItem(r.label,i,a,">",!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 o&&e.staticValue.activateCode();return this}};if((Pe(de.tytxSuffix).GramlotBuilderBag??de)!==de)throw new Error("TYTX subtype name 'GramlotBuilderBag' is already registered for another class");wt(de.tytxSuffix,{...Pe(de.tytxSuffix),GramlotBuilderBag:de});var zg=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"]),uo=class extends Gt{constructor(e,t){super(e),this._owner=t}get owner(){return this._owner}_handleMeta(e,t){let r=this.owner.evaluateExpressions(e,t);vr(e,r);let[n,i]=super._handleMeta(e,r);return yr(e,i),e._getMeta("subbuilder")?[n,Kn(io(i))]:[n,i]}adaptAttrs(e){let{_meta:t,...r}=e;return cn(super.adaptAttrs(xr(Et(r))))}renderedItem(e,t,r,n={}){if(this.owner.renderType==="object")return this.owner.renderedItem(e,t,r,n);let{_text:i,...s}=r;return t=this.owner.expressionValue(e,t),Array.isArray(t)&&i!=null&&(t=[this._escapeText(_r(i)),...t]),zg.has(n.tag)?`${n.pretty?" ".repeat(this._nodeDepth(e,n.depthOffset??0)):""}<${n.tag}${this._formatAttrs(s)} />${n.pretty?`
|
|
221
|
+
`:""}`:super.renderedItem(e,t,s,n)}};var Sr=class extends Wt{#e=new WeakMap;#t=new WeakMap;get inlineCompiler(){return null}getRender(e){return this.renders.has(e)||(e instanceof Je?this.addRender(e,this):e instanceof vt&&this.addRender(e,new uo(e,this))),super.getRender(e)}render(e,t={}){if(e._getMeta("data_element"))return null;let[r,n]=e.rootBuilder.runtimeValues(e),i=this.getRender(e.builder),[s,a]=i._handleMeta(e,n);return e._getMeta("subbuilder")||(a=i.adaptAttrs(a)),i.renderedItem(e,e.value instanceof N?this.renderChildren(e.value,t):r,a,{tag:s,...t})}_handleMeta(e,t){let r=this.builder.constructor.dialectPrefixes,n=this.evaluateExpressions(e,t);vr(e,n,r);let[i,s]=super._handleMeta(e,yl(e,n,r));if(yr(e,s,r),e.nodeTag==="webcomponent"){i=xt(e.getAttr());let{code:c,...u}=s;s=u}if(e._getMeta("subbuilder")){let c=io(s);return e._getMeta("subbuilder")==="html"&&(c.xmlns=kt),[i,c]}let[a,l]=vl(i,s);return Object.keys(l).length&&this.#e.set(e,l),[i,a]}evaluateExpressions(e,t){let r=this.inlineCompiler,n=(s,a)=>r?r.compileExpression(e,s,a)(t):null,i={...t};for(let[s,a]of ge(e.getAttr()))e.nodeTag==="menuline"&&["caption","icon","tooltip","command"].includes(s)||Le(a)&&Object.hasOwn(i,s)&&(i[s]=n(s,a));return Le(e.value)&&this.#t.set(e,n("",e.value)),i}expressionValue(e,t){return Le(e.value)?this.#t.get(e)??null:t}restoreNativeAttributes(e,t){let r=this.#e.get(e);return r?(this.#e.delete(e),{...t,...xr(r)}):t}adaptAttrs(e){let{_meta:t,...r}=e,n=`${this.builder.constructor._name}_`,i=this.builder.constructor.dialectPrefixes,s={},a={};for(let[l,c]of Object.entries(Et(r))){if(c==null)continue;if(l.startsWith(n))throw new Error(`${l}: the attribute prefix '${n}' is not accepted; use the prefix '${i[0]}'`);let u=i.find(d=>l.startsWith(d));u?s[l.slice(u.length)]=c:a[l]=c}return cn({...super.adaptAttrs(a),...s})}renderedItem(e,t,r,n={}){let i;[t,i]=un(this.expressionValue(e,t),this.restoreNativeAttributes(e,r));let{_text:s,...a}=i;Array.isArray(t)&&s!=null&&(t=[this._escapeText(_r(s)),...t]);let l=e.parentNode?._getMeta("subbuilder")==="html"?{xmlns:be,...a}:a;return super.renderedItem(e,t,l,n)}finalize(e,t=null,r={}){if(!r.doctype)return super.finalize(e,t,r);let n=this._composeStringFragments(e),i=this.builder.source.getNodes().filter(s=>!s._getMeta("data_element"));return i.length===1&&i[0].nodeTag==="html"||(n=`<html>${n}</html>`),super.finalize(`<!doctype html>${n}`,t,r)}};var sf={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 af={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 Vg="data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element",Wg=new Set,Gg=new Set(["serverpath","dbenv","shared_id"]),Hg=["formsubscribe_"],Xg={dataSetter:"destination_path",dataFormula:"result_path",dataRpc:"result_path",dataRemote:"destination_path"},Yg={dataFormula:"formula",dataController:"script"},ff=new Set(["node_label","node_position","nodeId","target_id","datapath","iterate","store","_tag","_meta","ns"]),Gi={csv:"CSV",json:"JSON",tytx:"TYTX",xml:"XML",xlsx:"Excel"},lf=new Set(["node_label","frameTarget","nodeId"]),Zg=new Set(["storepath","rowMode","structpath"]);function cf(o,e){let t=o?._meta?.keywordPattern;if(!t)return null;let r=new Set(o.attributes.parameters.filter(i=>!i.kind.startsWith("var_")).map(i=>i.name)),n=Object.keys(e).find(i=>!r.has(i)&&!ff.has(i)&&!new RegExp(t).test(i));return n===void 0?null:`unknown attribute '${n}'`}function Kg(o){if(typeof o=="boolean")return o?Object.keys(Gi):[];if(typeof o!="string"||!o.trim())throw new TypeError("frameGrid export requires a boolean or a list of formats");let e=o.split(",").map(r=>r.trim()),t=e.find(r=>!Object.hasOwn(Gi,r));if(t!==void 0)throw new TypeError(`frameGrid export format '${t}' is not one of ${Object.keys(Gi).join(", ")}`);return e}function uf(o,e){if(["input","textarea","select","webcomponent"].includes(o)&&H(e.value))return"'value' does not accept pointer suffixes; use an ordinary value pointer";if(o==="html_button"&&Object.keys(e).some(n=>["action","ask","_delay","fire"].includes(n)||n.startsWith("fire_")))return"plain HTML button: use button for action, ask, fire or _delay";if(Object.hasOwn(e,"ask")&&!["button","toggleButton","dropDownButton","menuline"].includes(o))return"'ask' is supported on buttons";if(Object.hasOwn(e,"_ask")&&!["dataController","dataFormula","dataRpc"].includes(o))return"'_ask' requires a controller, formula or RPC";if(["dataSetter","dataRemote"].includes(o)&&Object.keys(e).some(n=>n.startsWith("subscribe_")||n.startsWith("selfsubscribe_")))return"topic subscriptions are supported on controllers, formulas, RPCs and rendered elements";let t=Xg[o];if(t&&String(e[t]??"").includes("?"))return`'${t}' does not accept '?attr': '${e[t]}'`;let r=Yg[o];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 df(o){return Object.keys(o).find(e=>Gg.has(e)||Hg.some(t=>e.startsWith(t)))}var me=class o extends Je{static _name="gramlot";static containers=["frameGrid"];static _sourceClass=de;static{this.defineGrammar(sf)}static{this.defineGrammar(af)}static{this.defineGrammar(Vi.toDocument())}frameGrid(e,{storepath:t,rowMode:r,structpath:n,searchOn:i=!1,searchHelp:s=!1,chart:a=!1,export:l=!1,printRows:c=!1,advancedTools:u=!1,addrow:d=!1,addrow_defaults:f=null,duprow:h=!1,delrow:p=!1,gridsemaphore:m=!1,...b}={}){for(let z of["framePane","grid"])if(!this.schemaTag(z))throw new TypeError(`frameGrid requires the ${z} collection`);let w={};for(let z of Object.keys(b))z.startsWith("chart_")&&(w[z.slice(6)]=b[z],delete b[z]);let[_,v]=this.frameGridRoute(b),E=Object.keys(v).find(z=>["storepath","rowMode"].includes(z)||z==="structpath"&&n!=null);if(E!==void 0)throw new TypeError(`frameGrid: '${E}' is given twice`);if(a!==!1){if(a!==!0&&(typeof a!="string"||!a))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 a=="string"&&(w.chartType=a)}else if(Object.keys(w).length)throw new TypeError("chart_* options require chart");let D=Kg(l);for(let[z,V]of Object.entries({printRows:c,advancedTools:u,addrow:d,duprow:h,delrow:p,gridsemaphore:m}))if(typeof V!="boolean")throw new TypeError(`frameGrid ${z} 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,...n==null?{}:{structpath:n},node_label:"grid",frameTarget:!0,height:"100%",width:"100%",..._.datapath?{selectedId:"^.selectedId"}:{},...v};a!==!1&&(k.nodeId=G()),this.validateNodeValues("grid",null,k),i!==!1&&this.validateNodeValues("searchBox",null,{searchOn:i,searchHelp:s});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:s}),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 L=z=>{let V=z.menuline({caption:"Export",icon:"\u21E9",labelPosition:"tooltip",node_label:"export"}).menu();for(let le of D)V.menuline({command:"grid:export",caption:Gi[le],parameters:{format:le},node_label:le})};if(D.length&&L(O),c&&O.menuline({command:"grid:printRows",node_label:"printRows"}),u){let z=O.menuline({caption:"Advanced tools",icon:"\u2026",labelPosition:"tooltip",node_label:"advancedTools"}).menu();z.menuline({command:"grid:lineNumbers",node_label:"lineNumbers"}),D.length&&L(z),c&&z.menuline({command:"grid:printRows",node_label:"printRows"})}return m&&O.menuline({group:!0,node_label:"semaphore"}).editingStatus(),a!==!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 x(w),height:"100%"})),C}frameGridRoute(e){let t=u=>new Set(this.schema[u].attributes.parameters.filter(d=>!d.kind.startsWith("var_")).map(d=>d.name)),r=new Set([...ff,...lt]),n=t("grid"),i=t("framePane"),s=new RegExp(this.schema.grid._meta.parameterPattern),a=u=>(n.has(u)||s.test(u))&&!i.has(u)&&!r.has(u)&&!lf.has(u)&&!Zg.has(u),l={},c={};for(let[u,d]of Object.entries(e)){let f,h;if(u.startsWith("grid_")){if(f=u.slice(5),h=c,lf.has(f))throw new TypeError(`frameGrid: '${u}' is composed by frameGrid`)}else u.startsWith("frame_")?(f=u.slice(6),h=l):(f=u,h=a(u)?c:l);if(Object.hasOwn(h,f))throw new TypeError(`frameGrid: '${f}' is given twice`);h[f]=d}return[l,c]}static get dialectPrefixes(){let e=[];for(let t=Object.getPrototypeOf(o);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:n=eo}={}){if(!(n instanceof mr))throw new TypeError(`nameSyntax must be a NameSyntax, not ${n}`);super(e),this._binding=null,this._auth=r,this._nameSyntax=n;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,n,i){return this.binding?this.binding.inlineCompiler.compilePointerExpression(e,t,r,n.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 Xt?e.toDocument():e),this}schemaTag(e){let t=e.toLowerCase(),r=o.dialectPrefixes;if(t.startsWith(`${o._name}_`))throw new Error(`${e}: the tag prefix '${o._name}_' is not accepted; use the prefix '${r[0]}'`);if(Wg.has(t))throw new Error(`${e}: excluded from Gramlot`);let n=this.schemaTagNames[t];if(n)return n;for(let i of r)if(t.startsWith(i)&&this.schemaTagNames[t.slice(i.length)])return t;return null}bagCall(e,t,r,n){return t=this.#e(t),[r,n]=this.menuArguments(t,r,n),super.bagCall(e,t,r,n)}commandOnNode(e,t,r,n){return t=this.#e(t),[r,n]=this.menuArguments(t,r,n),super.commandOnNode(e,t,r,n)}menuArguments(e,t,r={}){if(e==="menu"&&t==null)return[new de(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&&H(r.value))throw new Error("'value' does not accept pointer suffixes");e==="webcomponent"&&xt(r);let n=df(r);if(n)throw new Error(`${e}: attribute '${n}' is excluded from Gramlot`);let i=uf(e,r)??cf(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")&&H((t.attrs??e.getAttr()).value))throw new Error("'value' does not accept pointer suffixes");e.nodeTag==="webcomponent"&&xt(t.attrs??e.getAttr());let r=df(t.attrs??e.getAttr());if(r)throw new Error(`${e.nodeTag} '${e.label}': attribute '${r}' is excluded from Gramlot`);let n=uf(e.nodeTag,t.attrs??e.getAttr())??cf(this.schema[e.nodeTag],t.attrs??e.getAttr());if(n)throw new Error(`${e.nodeTag} '${e.label}': ${n}`);return super.validateNode(e,t)}_validateChildren(e,t,r,n){return super._validateChildren(e,t,r.map(i=>i==="html_button"?"button":i==="html_dialog"?"dialog":i),n)}_countsForGrammar(e){return e===this.schema.button||!e?._meta?.gramlot_component&&e!==this.schema.webcomponent&&super._countsForGrammar(e)}setChild(e,t,r,n,i=null){n=Object.fromEntries(Object.entries(n??{}).map(([l,c])=>[l,Z(c)instanceof Se?this.reference(c):c]));let a=t==="dataSetter"&&n?.value!==null&&typeof n?.value=="object"&&Object.getPrototypeOf(n.value)===Object.prototype?{...n,value:new x(n.value)}:n;return super.setChild(e,t,r,a,i)}#e(e){if(e==="data")throw new Error(Vg);if(this.schemaTagNames[e.toLowerCase()]===e)return e;let t=o.dialectPrefixes.find(r=>e.startsWith(r));return this.schemaTagNames[e.slice(t.length)]}get renderer_html(){return new Sr(this)}create(){this.setup(this.data),this.main(this.root)}computeLogic(){}promoteNodeValue(e,t,r){let n=t!=null?{_text:t}:null;e.setValue(r,!0,n,!0)}reference(e,t="node"){if(e=Z(e),!(e instanceof Se)||!["node","dom"].includes(t))throw new TypeError("Reference requires an element and node/dom kind");let r=e.getAttr("__ref");return r==null&&(r=G(),e.setAttr({__ref:r})),{$gramlotRef:r,kind:t}}toTytx(){return R(this.auth===null?this.source:this.source.authorizedCopy(this.auth))}};function Sl(o){for(let e=o.parentNode;e;e=e.parentNode)if(e.nodeTag==="framePane")return e;return null}function Hi(o){if(!o||!(o.value instanceof N))return null;let e=o.value.getNodes().find(n=>n.getAttr("region")==="center"),t=[];function r(n){if(n.nodeTag!=="framePane"&&(n.getAttr("frameTarget")===!0&&t.push(n),n.value instanceof N))for(let i of n.value.getNodes())r(i)}return e&&r(e),t.length===1?t[0]:null}function Jg(o){if(o.closed||!o.runtime.renderer.attached(o.node))return!1;for(let e=o.node;e;e=e.parentNode){let[,t]=e.rootBuilder.runtimeValues(e);if(t.hidden===!0||t.disabled===!0)return!1}return!0}function hf(o){if(o&&typeof o=="object"){for(let e of Object.values(o))hf(e);Object.freeze(o)}return o}function pf(o,e){let t=o.node,r=t.getAttr("command"),n=o.runtime.gramlot.commands.get(r),i=Sl(t),s=Hi(i);if(!n||!s)return console.warn(`Cannot dispatch command '${r}' at '${t.label}': missing or duplicate frame recipient`),null;let a=t.getAttr("parameters")??{};if(typeof a!="object"||Array.isArray(a))throw new TypeError("Command parameters require a mapping");let l=Object.fromEntries(Object.entries(a).map(([m,b])=>[m,t.pointerType(b)?t.getRelativeData(b):b])),c=hf(j(R(l))),u=Object.freeze(Object.fromEntries(["shift","ctrl","alt","meta"].map(m=>[m,!!e[`${m}Key`]]))),d=Object.freeze({sender:t,target:s,command:r,parameters:c,modifiers:u}),f=!1,h=o.runtime.bindingFor(s).track(()=>{f=!0}),p=()=>!f&&Jg(o)&&Hi(i)===s&&o.runtime.renderer.attached(s)&&t.getAttr("command")===r;return{message:d,current:p,release:h,cancel(){f=!0},deliver(){p()&&s.publish(n.publish,d)}}}var Qg=new Set(["input","select","textarea"]),eb=["type","multiple"];function mf(o,e){let t=o.node,r=t.getAttr(e);return t.pointerType(r)?t.getRelativeData(r):o.resolved[e]}var ve=class o{static liveWrites=!1;static writesDefault=!0;static preservesUnchangedValue=!1;#e;#t=!1;#r;#n;#o=!1;#i=!1;#s=!1;static for(e,t){let r=o.classFor(t.element,t.attrs);return r?new r(e,t):null}static classFor(e,t){if(e.namespaceURI!==be)return null;if(e.constructor.gramlotComponent)return e.constructor.gramlotComponent.parameters.value?.binding!=="twoWay"?null:e.control.type==="radio"?Nl:Al;if(e.localName==="textarea")return ft;if(e.localName==="select")return fo;if(e.localName!=="input")return null;let r=t.type==null?"text":String(t.type).toLowerCase();return Object.hasOwn(gf,r)?gf[r]:ft}static shape(e,t){return e?.constructor.gramlotComponent?.parameters.value?.binding==="twoWay"&&e.control.type==="radio"?JSON.stringify([]):e?.namespaceURI!==be||!Qg.has(e.localName)?null:JSON.stringify(eb.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.#s=!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.#s=!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.#s&&(this.#s=!1,this.binding.runtime.renderer.project(this.node));return}this.#i||e.isComposing||e.type===this.writeEvent&&this.commit(e)}}},Al=class extends ve{#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($l(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($l(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||bf(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}))}}},ft=class extends ve{static liveWrites=!0},Il=class extends ve{static liveWrites=!0;read(){return this.element.value===""?null:Number(this.element.value)}commit(e){this.element.validity.badInput||super.commit(e)}},Cl=class extends ve{static liveWrites=!0;read(){return Number(this.element.value)}},fo=class extends ve{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 n of t.options){let i=r.has(n.value);n.selected!==i&&(n.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,n)=>Object.is(r,e[n])):super.same(e,t)}},Ar=class extends ve{read(){return this.element.value===""?null:this.element.value}},Dl=class extends ve{},Xi=class extends ve{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()}},dn=class extends Xi{#e=null;#t=!1;get groups(){return this.binding.runtime.renderer.radioGroups}attach(){let e=this.node,t=this.resolved.group??null,r=Ol(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=Ol(this.node);if(!Object.is(e??null,t)){let n=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 n){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(mf(this,"value")&&this.groups.peersOf(e,t).some(n=>!n.binding.closed&&n.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 n=this.read();super.project(e,t),!r&&!n&&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),mf(e,"value")&&e.commit(null))}}},Nl=class extends dn{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||bf(this.host,this.host.acceptControlValue(),()=>super.commit(e))}read(){return this.host.readControlValue()}write(e){this.host.writeControlValue(e)}attach(){this.host.setPageContext($l(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,Ol(this.node)).filter(s=>!s.binding.closed&&!s.element.disabled),r=t.indexOf(this);if(r<0)return;e.preventDefault();let n=["ArrowLeft","ArrowUp"].includes(e.key)?-1:1,i=t[(r+n+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}))}}}},Yi=class{#e;#t=new Map;#r=new Map;#n=new WeakMap;#o=0;constructor(e){this.#e=e}join(e,t,r){let n=this.nameOf(t,r);return this.#t.has(n)||this.#t.set(n,new Set),this.#t.get(n).add(e),this.#r.set(e,n),n}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 Ol(o){for(let e=o;e;e=e.parentNode){let t=e.getAttr()??{};if(t.formId!=null||t.form===!0)return e}return null}var gf={text:ft,password:ft,email:ft,url:ft,tel:ft,search:ft,number:Il,range:Cl,color:Dl,date:Ar,time:Ar,month:Ar,week:Ar,"datetime-local":Ar,checkbox:Xi,radio:dn,hidden:null,file:null,button:null,submit:null,reset:null,image:null};function $l(o){let{binding:e,node:t}=o,r=e.runtime.gramlot;return{locale:r.locale,timeZone:r.timeZone,createDecimal:Ye,isDecimal:U,getDecimalLibrary:Zr,form:o.form,formCancelValidation:()=>o.form?.cancelValidation(t),formValidateCandidate:(n,i)=>o.form.validateCandidate(t,n,i),formValidate:()=>o.form?.scheduleValidation(o),formSelectionPending:n=>o.form?.pendingPart(t,"selection",n?"active":null),formSelectionError:n=>o.form?.issue(t,"selection",n),formParseError:n=>o.form?.parseError(t,n),formClearDraft:()=>o.form?.clearDraft(t),publish:(n,i)=>t.publish(n,i),isActive:()=>!e.closed,reportError:(n,i)=>{e.closed||e.runtime.reportError(n,i)},callLogic:(n,i)=>Tt(e.runtime,t,n,i),format:(n,i)=>r.format(n,i),...Wi(e),selectionDisplay:(n,i)=>{if(e.closed)return;let s=t.getAttr("value");if(t.pointerType(s)!=="^"||s.includes("?")||!Object.is(t.getRelativeData(s),i))return;let a=s.slice(1)+"?_displayedValue";t.getRelativeData(a)!==n&&t.setRelativeData(a,n)},periodOutput:(n,i)=>t.setRelativeData(n,i),selectionOutputs:({selectedCaption:n,selectedRecord:i,fields:s},a)=>{if(!e.closed){n&&t.setRelativeData(n,a?.caption??null),i&&t.setRelativeData(i,a?new x(a.record):null);for(let[l,c]of Object.entries(s))t.setRelativeData(c,a?.record[l.slice(9)]??null)}}}}function bf(o,e,t){let r=o.pageContext,n=i=>{i.ok&&i.isCurrent()&&(t(i),o.finishValidation(i))};if(e instanceof Promise)e.then(n).catch(i=>r.reportError(i,"Field update failed"));else try{n(e)}catch(i){r.reportError(i,"Field update failed")}}var Rl=Symbol("source text"),wf={xmlns:"http://www.w3.org/2000/xmlns/",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},tb=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"]),rb=new Set(["checked","muted","selected","value"]),nb=new Map([["allowfullscreen","allowFullscreen"],["formnovalidate","formNoValidate"],["ismap","isMap"],["nomodule","noModule"],["novalidate","noValidate"],["playsinline","playsInline"],["readonly","readOnly"]]);function ob(o){let e=o.replace(/-([a-z])/g,(t,r)=>r.toUpperCase());return nb.get(e.toLowerCase())??e}var Zi=class{constructor({format:e,metadataAttributes:t=[],invokeScript:r=null,callLogic:n=null,reportError:i=null,uploadContext:s=null}={}){this.format=e,this.uploadContext=s,this.invokeScript=r,this.callLogic=n,this.reportError=i,this.metadataAttributes=new Set([...lt,"_text",...t])}definition(e){let t=e.builder,n={...t.schema[t.schemaTag(e.nodeTag)]._meta,...e.getAttr("_meta")},i=e.nodeTag==="webcomponent"?xt(e.getAttr()):nn(e.nodeTag,{renderTag:n.render_tag,ns:e.getAttr("ns"),dialectName:t.constructor._name}),s=i==="foreignObject"?kt:n.render_attributes?.xmlns??e.getAttr("xmlns")??(t instanceof vt?kt:be);return{meta:n,namespace:s,tag:i}}validate(e,t=e.builder){this.validateLabelbox(e);let r=e.value instanceof N,n=r?e.getAttr("_text"):e.value;if(n!=null&&!["string","number","boolean"].includes(typeof n))throw new TypeError("HTML text must be scalar");let i=this.definition(e).meta.gramlot_component;for(let[l,c]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)||c&&typeof c=="object"&&Object.hasOwn(c,"$gramlotRef"))&&c!=null&&!["string","number","boolean"].includes(typeof c))throw new TypeError(`HTML attribute ${l} must be scalar`);let s=Object.fromEntries(Object.entries(e.attr).filter(([l])=>!this.metadataAttributes.has(l))),a=r?e.value.getNodes().map(l=>l.nodeTag).filter(Boolean):[];t.validateNode(e,{value:n,attrs:s,childTags:a})}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!==be&&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 n=e.parentNode;if(n?.nodeTag){let i=this.definition(n);if(i.namespace!==be&&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,n=e.attr,i=null){let{tag:s,namespace:a,meta:l}=this.definition(e);r??=s;let c=a===be?t.createElement(r):t.createElementNS(a,r);if(l.gramlot_component&&c.constructor.gramlotComponent?.tag!==r)throw new Error(`Component collection must be activated before rendering ${r}`);l.gramlot_component?.dataScope&&(c.readDataScope=()=>{if(!e.getAttr("datapath"))throw new Error("Data scope requires an explicit datapath");return e.getRelativeData(".")}),l.gramlot_component?.sourceContext&&c.setSourceContext({sourceNode:e,frameRecipient:()=>Hi(Sl(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 u=t.createTextNode(this.text(e));(a!==be||!l.void)&&c.append(u);let d={element:c,text:u,tag:r,presentation:c};if(this.hasLabelbox(e)){this.validateLabelbox(e);let f=t.createElement("div");f.append(c),d.labelbox=sl(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-${G()}`,d.controlId=`gramlot-control-${G()}`;let h=t.createElement("style");h.textContent=il,d.presentation.prepend(h),l.gramlot_component?.labelbox&&c.setLabelbox(d.labelbox)}return this.update(d,e,n,Rl,i),d}matches(e,t){let{tag:r,namespace:n}=this.definition(t);return(n===be?e.tag.toLowerCase()===r.toLowerCase():e.tag===r)&&e.element.namespaceURI===n}writeParameter(e,t,r){let n=e.getAttr(t);e.pointerType(n)==="^"&&!H(n)&&!Object.is(e.getRelativeData(n.slice(1)),r)&&e.setRelativeData(n.slice(1),r)}compose(e,t,r){e.text.data=t??"";for(let n of r)e.element.append(n)}update(e,t,r=t.attr,n=Rl,i=null,s=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:a,text:l}=e;if(this.hasLabelbox(t)&&!e.labelbox)throw new TypeError("Declare lbl or box_* when creating an experimental HTML labelbox");let c=a.namespaceURI===be,u=this.definition(t).meta.render_attributes??{},d=e.attrs??{},f=w=>(vr(t,w,t.builder.constructor.dialectPrefixes),yr(t,w,t.builder.constructor.dialectPrefixes),t.builder.renderer_html.adaptAttrs(w)),h=t.parentNode;if(h?._getMeta("gramlot_component")?.childParameters&&(r=a.ownerDocument.defaultView.customElements.get(h._getMeta("render_tag")).projectChild(e.presentation,r,{label:t.label,adapt:f,invoke:(_,v,E)=>this.invokeScript(t,_,v,E),reportError:(_,v)=>this.reportError(t,_,v),publish:(_,v)=>t.publish(_,v),publishParent:(_,v)=>h.publish(_,v),writeParameter:(_,v)=>this.writeParameter(t,_,v),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(([v,E])=>v.startsWith("lbl_")&&Object.hasOwn(E,"default")).map(([v,E])=>[v,E.default]));r.lbl_variant==="card"&&r.lbl_position==null&&delete _.lbl_position,al(e.labelbox,{..._,...r},f)}if(this.definition(t).meta.gramlot_component){if(this.definition(t).meta.gramlot_component.bagStore)if(t.nodeTag==="tree")a.setStoreBag(t.rootBuilder.binding.treeStore(t));else{let w=t.absDatapath(t.getAttr("storepath"));(!s||s.path===w||s.path.startsWith(`${w}.`)||w.startsWith(`${s.path}.`))&&a.setStoreBag(t.getRelativeData(t.getAttr("storepath")))}if(this.definition(t).meta.gramlot_component.bagStruct){let w=t.absDatapath(t.getAttr("structpath"));(!s||s.path===w||s.path.startsWith(`${w}.`)||w.startsWith(`${s.path}.`))&&a.setStructBag(t.getRelativeData(t.getAttr("structpath")))}r=a.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(ge({...r,...u}));let p=ve.classFor(a,r)!==null;n===Rl&&(n=this.text(t));let m=n==null?"":String(n);l.data!==m&&(l.data=m);let b=[...new Set([...Object.keys(d),...Object.keys(r)])];b.sort((w,_)=>(_==="sandbox")-(w==="sandbox")||(c&&a.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(c&&w==="multiple"&&["input","select"].includes(a.localName)){a.multiple!==!!_&&(a.multiple=!!_);continue}if(c&&a.localName==="input"&&w==="type"){Object.is(d.type,_)||(_==null?a.removeAttribute("type"):a.type=String(_));continue}let v=w,E=ob(v),D=c&&tb.has(E)&&typeof a[E]=="boolean",k=v==="xmlns"?"xmlns":v.includes(":")?v.split(":")[0]:"",C=Object.hasOwn(wf,k)?wf[k]:null;if(Object.is(d[w],_)||(_==null||D&&!_?C?a.removeAttributeNS(C,v.split(":").at(-1)):a.removeAttribute(v):C?a.setAttributeNS(C,v,String(_)):a.setAttribute(v,D?"":String(_))),c&&(D||rb.has(E))&&E in a){let O=E==="value"?_==null?"":String(_):!!_;a[E]!==O&&(a[E]=O)}}if(i===!1?a.style.visibility!=="hidden"&&(a.style.visibility="hidden"):e.visible===!1&&(r.style==null?a.removeAttribute("style"):a.setAttribute("style",String(r.style))),e.visible=i,e.labelbox){let{fieldLabel:w,labelBox:_,box:v}=e.labelbox;["input","textarea","select","button","output","meter","progress"].includes(e.tag)?(a.id||(a.id=e.controlId),w.htmlFor=a.id):(w.id=e.labelId,this.definition(t).meta.gramlot_component?.labelbox||(v.setAttribute("role","group"),_.hidden?v.removeAttribute("aria-labelledby"):v.setAttribute("aria-labelledby",w.id))),v.hidden=!!r.hidden,i===!1&&(v.style.visibility="hidden")}e.attrs=r}text(e){return e.value instanceof N?e.getAttr("_text")==null?"":String(e.attr._text):e.value==null?"":String(e.value)}};var Ki=class o{#e;#t;#r=null;#n=0;#o=new Set;#i=null;static for(e,t){return t.element?.constructor.gramlotComponent?.command?new o(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()??{},n=[];if(t.length&&n.push("controller"),r.action!=null&&n.push("action"),e.nodeTag==="menuline"&&r.command!=null&&n.push("registered"),_f(r).length&&n.push("fire"),e.nodeTag==="menuline"&&e.value instanceof N&&e.value.getNodes().some(i=>i.nodeTag==="menu")&&n.length)throw new Error(`menuline '${e.label}': a submenu cannot also execute a command`);if(e.nodeTag==="menuline"&&r.group&&n.length)throw new Error(`menuline '${e.label}': a group cannot execute a command`);if(n.length>1)throw new Error(`${e.nodeTag} '${e.label}': ${n.join(" and ")} together; a button has one click mechanism`);return n[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"),n=r?r.getRowContext():null;if(r&&n===null||!this.element.prepareCommand(e))return;let i=this.mechanism;if(!i||(e.stopPropagation(),this.element.disabled))return;let s=i==="registered"?pf(this.binding,e):null;if(i==="registered"&&!s)return;s&&this.#o.add(s);let a=this.binding.countClick(),l=this.node;for(;l&&l.getAttr("_delay")==null;)l=l.parentNode;let c=l?l.rootBuilder.runtimeValues(l)[1]._delay:0;if(c>0){let u=this.#n+1;this.#r?.(),this.#n=u;let d=setTimeout(()=>{f(),this.#r=null,this.#n=0,this.#a(e,u,s,n)},c),f=this.binding.track(()=>this.#r?.());this.#r=()=>{clearTimeout(d),s&&(s.cancel(),s.release(),this.#o.delete(s)),f(),this.#r=null,this.#n=0};return}return this.#r?.(),this.#a(e,a,s,n)}async#s(e){try{if(!e.current())return;let t=this.node.getAttr("ask"),r=this.binding.runtime.askDialog,n={...e.message.parameters};if(t&&r.required(this.binding,t,n,"ask")&&await r.show(this.binding,t,n)===null)return;e.deliver()}finally{e.release(),this.#o.delete(e)}}#a(e,t,r=null,n=null){if(r)return this.#s(r);if(this.binding.closed||this.element.disabled)return;let i=this.mechanism;if(!i)return;let s=this.node,a=ib(e);if(i==="controller")this.binding.runtime.bindingFor(this.controllers[0])?.providers[0]?.invoke({kind:"click",event:e,counter:t,rowContext:n});else if(i==="action"){let l=()=>{let[,f]=s.rootBuilder.runtimeValues(s),h=Object.fromEntries(Object.entries(f).filter(([p])=>p!=="ask"));return{...this.binding.runtime.renderer.references.resolveArguments(h),...n,event:e,_counter:t,modifiers:a}},c=f=>{if(this.binding.closed||this.element.disabled||f===null)return;let h={...l(),...f};f&&(h._askResult=f),dt(this.binding.runtime,s,"action",s.getAttr("action"),h)},u=s.getAttr("ask"),d=this.binding.runtime.askDialog;if(u&&d.required(this.binding,u,l(),"ask"))return d.show(this.binding,u,l()).then(c);c(void 0)}else{let l={modifier:a,_counter:t},c=s.getAttr("fire");if(c!=null){s.FIRE(c,a||!0,l);return}for(let[u,d]of _f(s.getAttr())){if(this.binding.closed)return;s.FIRE(d,u.slice(5),l)}}}};function _f(o){return Object.entries(o??{}).filter(([e,t])=>t!=null&&(e==="fire"||e.startsWith("fire_")))}function ib(o){return["shift","ctrl","alt","meta"].filter(e=>o[`${e}Key`]).map(e=>e[0].toUpperCase()+e.slice(1)).join("")}var et=class extends Y{static classKwargs={...Y.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 n=this.prepareValue(r);this._lastUpdate=Date.now(),this._lastEffectiveFingerprint=t,this.loaded=!0,this.writing=!0;try{this.node?this.node.setValue(n,this.cacheTime!==0):this.cachedValue=n}finally{this.writing=!1}return n}};var fn=class extends et{static internalParams=new Set([...et.internalParams,"binding","method","params","onCalling","onError","sync"]);constructor({binding:e,method:t,params:r,cacheTime:n,onCalling:i=null,onError:s,sync:a=!1}){super({cacheTime:n,onError:s}),this.binding=e,this.sync=a,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 yf=new Set(["kind","command","caption","icon","iconSrc","tooltip","disabled","hidden","checked","favorite","parameters","resolver","cacheTime","sync"]);function vf(o,e=new Set){if(!(o instanceof x)||e.has(o))throw new TypeError("Menu resolver must return an acyclic Bag");let t=new Set([...e,o]);return o.getNodes().map(r=>{let n=r.attr,i=n.kind,s=r.staticValue;if(Object.keys(n).some(l=>!yf.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(n[l]!=null&&typeof n[l]!="boolean"&&!(typeof n[l]=="string"&&n[l].startsWith("^")))throw new TypeError(`Invalid menu ${l}`);if(n.favorite!=null&&typeof n.favorite!="boolean")throw new TypeError("favorite must be boolean");if(n.caption!=null&&typeof n.caption!="string")throw new TypeError("Menu caption must be text");if(n.parameters!=null&&(typeof n.parameters!="object"||Array.isArray(n.parameters)))throw new TypeError("Menu parameters must be a mapping");if(i==="command"&&(typeof n.command!="string"||!n.command||s!=null||n.resolver!=null))throw new TypeError("Command record requires a command and no children/resolver");if(i==="separator"&&(s!=null||Object.keys(n).length!==1))throw new TypeError("Separator record accepts kind only");if(i==="submenu"&&(typeof n.caption!="string"||n.command!=null||s instanceof x==(n.resolver!=null)||!(s instanceof x)&&s!=null))throw new TypeError("Submenu requires caption and exactly one content source");let a=s instanceof x?vf(s,t):null;return{label:r.label,attrs:{...n},children:a}})}function xf(o,e){let t=o.builder.wrapSource(o),r=o.value instanceof N?o.value.getNodes():[],n=new Set(e.map(i=>i.label));for(let i of r)n.has(i.label)||o.value.popNode(i.label);for(let[i,s]of e.entries()){let{kind:a,...l}=s.attrs,c=Object.fromEntries(Object.entries(l).filter(([p])=>p==="resolver"||p==="cacheTime"||p==="sync"||p.startsWith("resolver_")));for(let p of Object.keys(c))delete l[p];let u=a==="separator"?"-":null,d=o.value instanceof N?o.value.getNodes().find(p=>p.label===s.label):null,f=d?.value instanceof N;if(d&&(f!==(a==="submenu")||d.value==="-"!=(a==="separator"))&&(o.value.popNode(d.label),d=null),!d)d=Z(t.menuline(u,{...l,node_label:s.label}));else{let p=Object.keys(d.attr).filter(m=>yf.has(m)&&!Object.hasOwn(l,m));d.setAttr({...Object.fromEntries(p.map(m=>[m,null])),...l})}if(a==="submenu"){let p=d.value instanceof N?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])),...c}):p=Z(d.builder.wrapSource(d).menu({...c,node_label:"menu"})),s.children&&xf(p,s.children)}let h=o.value.getNodes().indexOf(d);h!==i&&o.value.move(h,i)}}var Ji=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(([n])=>n.startsWith("resolver_")).map(([n,i])=>[n.slice(9),i])),r=R([e.resolver,t,e.cacheTime,e.sync]);r!==this.#e&&(this.#e=r,this.#r++,this.#o=null,this.#t=e.resolver?new fn({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 n=t.cachedValue,i=vf(n),s=R(n);this.#o!==s&&(xf(this.node,i),this.#o=s),this.element.setStatus(i.length?null:"empty")}catch(n){if(this.#n||r!==this.#r)return;this.element.setStatus("error"),console.warn(`Menu '${this.node.label}' failed to load`,n)}}};var Qi=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 n=e.node,i=n.value,s=n.absDatapath(".");if(!(s===null||!(i instanceof N))){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()||n.value!==i||n.absDatapath(".")!==s)return;let l=new Map,c=new Set,u=f=>{for(let h of["collapsed","checkbox"]){let p=f.getAttr(h);f.pointerType(p)&&c.add(f.absDatapath(p))}};u(n);let d=f=>{for(let h of f.getNodes()){h.nodeTag==="groupletCard"&&u(h);let p=h.getAttr("value");if(!h._getMeta("data_element")&&h.pointerType(p)==="^"&&!H(p)){let m=h.absDatapath(p);m!==null&&(s===""||m.startsWith(`${s}.`))&&l.set(m,{child:h,pointer:p})}h.staticValue instanceof N&&d(h.staticValue)}};d(i);for(let[f,{child:h,pointer:p}]of l){if(!r()||n.value!==i||n.absDatapath(".")!==s)break;c.has(f)||h.getAttr("value")!==p||h.absDatapath(p)!==f||e.runtime.renderer.html.writeParameter(h,"value",null)}}finally{this.#t=!1}}}};var es="connect_on",ho=class{#e;#t;#r;#n;#o;static declared(e){return Object.entries(e.getAttr()??{}).filter(([t,r])=>t.startsWith(es)&&t.length>es.length&&r!=null).map(([t,r])=>[t,t.slice(es.length).toLowerCase(),r])}constructor(e,t,r,n,i=`${es}${r}`){this.#e=e,this.#t=t,this.#r=r,this.#n=n,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(ao(this.handler))return Tt(r,t,this.handler,e);r.inlineCompiler.compile(t,this.attribute,this.handler,["event"])({event:e})}};var Xl={};ee(Xl,{BagCollectionView:()=>vo,parseSort:()=>Hl});var Bl={};ee(Bl,{columnDateMatches:()=>po,columnDateRange:()=>Pl,columnSelection:()=>jl,columnValue:()=>ts,columnValueKey:()=>Qt});function ts(o){if(o==null||o==="")return null;if(typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||o instanceof Date&&Number.isFinite(o.getTime())||U(o)&&o.isFinite())return o;throw new TypeError("Column filters require loaded scalar values")}function Qt(o){return R(ts(o))}function jl(o){if(!Array.isArray(o))throw new TypeError("Column selection requires an array or null");return Object.freeze([...new Map(o.map(e=>{let t=Qt(e);return[t,j(t)]})).values()])}function Pl(o){if(o===null)return null;let{from:e,to:t,dtype:r,timeZone:n}=o;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"&&!n)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:n}):null}function po(o,e){if(!e)return!0;if(o==null||o==="")return!1;if(!(o instanceof Date)||!Number.isFinite(o.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(o),n=i=>r.find(s=>s.type===i).value;t=`${n("year")}-${n("month")}-${n("day")}`}else t=o.toISOString().slice(0,10);return(!e.from||t>=e.from)&&(!e.to||t<=e.to)}var zl={};ee(zl,{compileFilter:()=>Fl});var Ll={};ee(Ll,{parseDateExpression:()=>wo});function Ir(o,e){return e===2?o%4===0&&(o%100!==0||o%400===0)?29:28:[4,6,9,11].includes(e)?30:31}function Fe(o,e,t){if(![o,e,t].every(Number.isInteger)||o<1||o>9999||e<1||e>12||t<1||t>Ir(o,e))throw new RangeError("Date must exist in Gregorian years 0001\u20139999.");return`${String(o).padStart(4,"0")}-${String(e).padStart(2,"0")}-${String(t).padStart(2,"0")}`}function Cr(o){if(typeof o!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(o))throw new RangeError("Expected a civil date in YYYY-MM-DD format.");let e=o.split("-").map(Number);return Fe(...e),e}function mo(o,e,t){let r=o-1,n=365*r+Math.floor(r/4)-Math.floor(r/100)+Math.floor(r/400)+t-1;for(let i=1;i<e;i++)n+=Ir(o,i);return n}function go(o,e){let t=mo(...Cr(o))+e;if(!Number.isSafeInteger(t)||t<0||t>mo(9999,12,31))throw new RangeError("Date offset exceeds Gregorian years 0001\u20139999.");let r=1,n=1e4;for(;n-r>1;){let s=Math.floor((r+n)/2);mo(s,1,1)<=t?r=s:n=s}t-=mo(r,1,1);let i=1;for(;t>=Ir(r,i);)t-=Ir(r,i++);return Fe(r,i,t+1)}function Ml(o){return go(o,-(mo(...Cr(o))%7))}function kf(o,e,t=0,r=1){let n=o*12+e-1+t,i=Math.floor(n/12),s=(n%12+12)%12+1,a=n+r-1,l=Math.floor(a/12),c=(a%12+12)%12+1;return{start:Fe(i,s,1),end:Fe(l,c,Ir(l,c))}}var rs={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 Ef(o){if(typeof o!="string")throw new RangeError("A supported locale is required.");let e=o.replaceAll("-","_"),t=e.indexOf("_"),r=(t<0?e:e.slice(0,t)).toLowerCase(),n=(t<0?"":e.slice(t+1)).toUpperCase();if(!Object.hasOwn(rs,r))throw new RangeError(`Unsupported locale: ${o}`);let i=rs[r];return{dictionary:i,phrases:a=>[...new Set([...i.keywords[a],...rs.en.keywords[a]])],order:i.date_order[n]??i.date_order.default}}var Dr=/^(?:\d{4}|\d{2})$/,Tf=/^\d{1,2}$/,bo=(o,e)=>({ok:!1,error:{code:o,message:e}}),Or=(o="UNRECOGNIZED_EXPRESSION",e="Text is not a supported date expression.")=>{throw Object.assign(new SyntaxError(e),{code:o})},If=(o,e)=>Object.hasOwn(o,e);function Nr(o,e){if(o.length===4)return Number(o);let t=e.year+e.twoDigitYearAhead-100;return t+((Number(o)-t)%100+100)%100}function sb(o,e){if(o.includes(";")){let n=o.split(";").map(i=>i.trim());return n.length!==2?Or("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:n,range:!0}}if(e.phrases("no_period").includes(o))return{bounds:["",""],range:!0};let t=e.phrases("to"),r=e.phrases("from");for(let n of t)if(o.startsWith(`${n} `))return{bounds:["",o.slice(n.length+1).trim()],range:!0};for(let n of t){let i=` ${n} `;if(!o.includes(i))continue;for(let a of r)if(o.startsWith(`${a} `)){o=o.slice(a.length+1);break}let s=o.split(i).map(a=>a.trim());return s.length!==2?Or("INVALID_RANGE","A range must have exactly two endpoints."):{bounds:s,range:!0}}for(let n of r)if(o.startsWith(`${n} `))return{bounds:[o.slice(n.length+1).trim(),""],range:!0};return{bounds:[o,o],range:!1}}function ab(o,e,t){let r=[[o,0]],n=/^(.+?)\s*([+-])\s*(\d+)$/.exec(o);n&&r.push([n[1],Number(n[2]+n[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[s,a]of r)for(let[l,c]of Object.entries(i))if(e.phrases(l).includes(s)){if(l.endsWith("_week"))return go(Ml(e.workdate),(c+a)*7+(t?6:0));if(l.endsWith("_month")){let u=kf(e.year,e.month,c+a);return t?u.end:u.start}return go(e.workdate,c+a)}return null}function lb(o,e,t){let r=Object.entries(e.dictionary.quarters).sort((n,i)=>i[0].length-n[0].length);for(let[n,i]of r){let s;if(o===n)s=null;else if(o.startsWith(n)&&Dr.test(o.slice(n.length).trim()))s=Nr(o.slice(n.length).trim(),e);else if(o.endsWith(n)&&Dr.test(o.slice(0,-n.length).trim()))s=Nr(o.slice(0,-n.length).trim(),e);else continue;return{year:s,month:t?i*3:i*3-2}}return null}function Sf(o,e){if(If(e.months,o))return e.months[o];let t=/^m(\d{1,2})$/.exec(o);return t&&Number(t[1])>=1&&Number(t[1])<=12?Number(t[1]):null}function cb(o,e){let t=o.split(/\s+/),r=t.map((c,u)=>Sf(c,e.dictionary)?u:-1).filter(c=>c>=0);if(!r.length)return null;if(r.length!==1)return Or();let n=r[0],i=Sf(t[n],e.dictionary),s=t.slice(0,n),a=t.slice(n+1),l=[...s,...a];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(!s.length&&a.length===1&&Dr.test(a[0]))return{year:Nr(a[0],e),month:i};if(s.length===1&&Tf.test(s[0])){if(!a.length)return Fe(e.year,i,Number(s[0]));if(a.length===1&&Dr.test(a[0]))return Fe(Nr(a[0],e),i,Number(s[0]))}return!s.length&&a.length===2&&Tf.test(a[0])&&Dr.test(a[1])?Fe(Nr(a[1],e),i,Number(a[0])):Or()}function ub(o,e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);if(t)return Fe(...t.slice(1).map(Number));let r=/^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(o),n={};if(r)e.order.split("").forEach((a,l)=>{n[a]=r[l+1]});else if(/^(?:\d{6}|\d{8})$/.test(o)){let a=o.length===8?4:2;for(let l of e.order){let c=l==="Y"?a:2;n[l]=o.slice(0,c),o=o.slice(c)}}else return null;if(!Dr.test(n.Y)||n.D.length>2||n.M.length>2)return Or();let i=Number(n.D),s=Number(n.M);return r&&s>12&&i<=12&&([i,s]=[s,i]),Fe(Nr(n.Y,e),s,i)}function Af(o,e,t){if(!o)return null;let r=e.phrases("articles");if(o=o.split(/\s+/).filter(i=>!r.includes(i)).join(" "),!o)return Or();if(Dr.test(o))return Fe(Nr(o,e),t?12:1,t?31:1);let n=ab(o,e,t)??lb(o,e,t)??cb(o,e);return n!==null?n:If(e.dictionary.weekdays,o)?go(Ml(e.workdate),e.dictionary.weekdays[o]):ub(o,e)??Or()}function db(o,e,t){if(o===null||typeof o=="string")return o;let r=o.year??t.year,n=typeof e=="string"?Cr(e)[0]:e?.year,i=typeof e=="string"?Cr(e)[1]:e?.month;return n&&(r>n&&(r=n),r===n&&o.month>i&&r--),Fe(r,o.month,1)}function fb(o,e,t){if(o===null||typeof o=="string")return o;let r=o.year??t.year;if(e!==null){let[n,i]=Cr(e);r<n&&(r=n),r===n&&i>o.month&&r++}return Fe(r,o.month,Ir(r,o.month))}function wo(o,e={}){if(!e||typeof e!="object"||Array.isArray(e))return bo("INVALID_CONTEXT","Options must provide a civil workdate and supported locale.");let t;try{let{locale:r="it-IT",workdate:n,twoDigitYearAhead:i=20}=e,[s,a]=Cr(n);if(!Number.isInteger(i)||i<0||i>99)throw new RangeError("twoDigitYearAhead must be an integer from 0 to 99.");t={...Ef(r),workdate:n,year:s,month:a,twoDigitYearAhead:i}}catch(r){return bo("INVALID_CONTEXT",r.message)}if(typeof o!="string")return bo("INVALID_INPUT","Expression must be a string.");try{let r=o.toLowerCase().trim().replaceAll(",",""),{bounds:n,range:i}=sb(r,t),s=Af(n[1],t,!0),a=Af(n[0],t,!1),l=db(a,s,t),c=fb(s,l,t);return!i&&typeof a=="string"&&l===c?{ok:!0,kind:"date",date:l}:{ok:!0,kind:"period",start:l,end:c}}catch(r){if(r instanceof RangeError)return bo("INVALID_DATE",r.message);if(r instanceof SyntaxError)return bo(r.code,r.message);throw r}}function Fl(o){if(o===null)return null;let{value:e,columns:t,dtype:r,locale:n}=o;if(typeof e!="string"||!Array.isArray(t)||!t.length||t.some(c=>typeof c!="string"||!c||c==="rowidx")||!["T","L","R","N","D"].includes(r))throw new TypeError("Invalid collection filter");if(!e.trim())return null;if(r==="T"){let c=o.literal===!0?e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):e,u=new RegExp(c,"i");return d=>u.test(t.map(f=>hb(d(f),n,o.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[,s,a]=i,l;if(r==="D"){let c=new Date,u=`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}-${String(c.getDate()).padStart(2,"0")}`,d=wo(a,{locale:n,workdate:u});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=pb(a,n);return c=>{let u=c(t[0]);if(u==null)return!1;if(r==="D"?!(u instanceof Date)||!Number.isFinite(u.getTime()):!(typeof u=="number"&&Number.isFinite(u)||U(u)&&u.isFinite()))throw new TypeError(`Filter value does not match ${r}`);let d=U(l)?-l.comparedTo(u):u<l?-1:u>l?1:0;switch(s){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 hb(o,e,t){return o==null?"":typeof o=="string"||typeof o=="boolean"?String(o):oo(o,{pattern:o instanceof Date?"short":"#,##0.####################"},{locale:e,timeZone:t})}function pb(o,e){let t=new Intl.NumberFormat(e).formatToParts(-12345.6),r=t.find(l=>l.type==="decimal").value,n=t.find(l=>l.type==="group")?.value,i=t.find(l=>l.type==="minusSign").value,s=o.replaceAll(i,"-");if(n&&s.includes(n)){let c=s.split(r)[0].replace(/^[+-]/,"").split(n),u=new Intl.NumberFormat(e).formatToParts(1234567890123).filter(h=>h.type==="integer").map(h=>h.value.length),d=u.at(-1),f=u.at(-2);if(s.split(r).slice(1).some(h=>h.includes(n))||!/^\d+$/.test(c[0])||c[0].length>f||c.slice(1).some((h,p)=>!/^\d+$/.test(h)||h.length!==(p===c.length-2?d:f)))throw new Error("Invalid numeric grouping.");s=s.replaceAll(n,"")}if(s=s.replace(r,"."),!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(s))throw new Error("Enter a complete number.");let a=Ye(s);if(!U(a)||!a.isFinite())throw new Error("A finite Decimal backend is required.");return a}var Wl={};ee(Wl,{containsId:()=>ql,requireId:()=>Vl,requireIdSet:()=>Ul});function ql(o,e){return(","+o+",").includes(","+e+",")}function Ul(o){if(typeof o!="string")throw new TypeError("grid checked must refer to a string (empty string for an empty set)");return o}function Vl(o){if(typeof o!="string"||!o||o.includes(","))throw new TypeError("grid checkedField requires nonempty text IDs without commas");return o}var Gl={};ee(Gl,{BagCollectionStore:()=>_o,publishCollection:()=>yo});var _o=class{#e=new Set;constructor(e,t){if(!(e instanceof x))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){yo(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 x))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 x))throw new TypeError(`collection store row ${e.label} must contain a Bag`);let n=r.getNode(t);if(n?.resolver)throw new TypeError("collection store requires loaded cells");return n?.staticValue}};function yo(o,e){let t=[],r=Object.freeze({full:e.full,rows:Object.freeze([...e.rows]),event:e.event??null,field:e.field??null});for(let n of[...o])if(o.has(n))try{n(r)}catch(i){t.push(i)}if(t.length)throw new AggregateError(t,"Collection notification failed")}var vo=class{#e;#t=null;#r=new Set;#n=new Map;#o="";#i=new Map;#s=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 Hl(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.#c(this.#a(),this.#o,new Map(e.filterContributions))}get filtered(){return this.#s===null?null:[...this.#s]}isFiltered(){return this.#s!==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.#a();return e&&this.#s!==null?this.#s.map(r=>t[r]):t}#a(){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){yo(this.#r,{full:e.full,rows:e.rows});return}this.#c(this.#u(this.#a(),this.criteria),this.#o,this.#i,e)}sort(e){let t=this.#u(this.#a(),Hl(e));this.#c(t,e,this.#i)}moveRow(e,t,r=!1){if(e===t||e.parentBag!==this.bag||t.parentBag!==this.bag)return;let n=this.getRows(!1);n.splice(n.indexOf(e),1),n.splice(n.indexOf(t)+Number(r),0,e),this.#c(n,"",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,Fl(r))}applySetFilter(e){let t=e===null?null:Object.freeze(e.map(({field:n,value:i})=>{if(typeof n!="string"||!n)throw new TypeError("Set filter requires an identity field");return Ul(i),Object.freeze({field:n,value:i})})),r=t===null?null:n=>t.every(({field:i,value:s})=>ql(s,Vl(n(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=Pl(r),typeof e!="string"||!e)throw new TypeError("Column filter requires a field");let n=t===null?null:jl(t),i=n?.map(Qt),s=n===null&&r===null?null:Object.freeze({field:e,values:n,keys:i&&Object.freeze(i),range:r}),a=s===null?null:l=>po(l(e),r)&&(i===void 0||i.includes(Qt(l(e))));this.#l(`column:${e}`,s,a)}columnFacets(e){let t=new Map,r=this.#i.get(`column:${e}`)?.definition.range??null,n=this.columnFilter(e),i=n?.map(Qt),s=[...this.#i].filter(([a])=>a!==`column:${e}`).map(([,a])=>a.predicate).filter(a=>a!==null);for(let a of this.#a()){let l=ts(this.value(a,e)),c=Qt(l);t.has(c)||t.set(c,{key:c,value:l,count:0,selected:po(l,r)&&(i===void 0||i.includes(c))}),s.every(u=>u(d=>this.value(a,d)))&&t.get(c).count++}for(let a of n??[]){let l=Qt(a);t.has(l)||t.set(l,{key:l,value:a,count:0,selected:!0})}return[...t.values()].filter(a=>po(a.value,r))}#l(e,t,r){if(JSON.stringify(this.#i.get(e)?.definition??null)===JSON.stringify(t))return;let n=new Map(this.#i);t===null?n.delete(e):n.set(e,{definition:t,predicate:r}),this.#c(this.#a(),this.#o,n)}#c(e,t,r,n={full:!1,rows:[]}){let i=[...r.values()].map(u=>u.predicate).filter(u=>u!==null),s=i.length?e.flatMap((u,d)=>i.every(f=>f(h=>this.value(u,h)))?[d]:[]):null,a=n.full||t!==this.#o||r!==this.#i||e.length!==this.#n.size||e.some((u,d)=>this.#n.get(u)!==d)||JSON.stringify(s)!==JSON.stringify(this.#s);this.#n=new Map(e.map((u,d)=>[u,d])),this.#o=t,this.#i=r,this.#s=s;let l=s===null?null:new Set(s),c=a?[]:n.rows.filter(u=>this.#n.has(u)&&(l===null||l.has(this.#n.get(u))));(a||c.length||n.rows.length)&&yo(this.#r,{full:a,rows:c})}#u(e,t){if(!t.length)return e;let r=e.map(n=>({node:n,keys:t.map(({field:i})=>this.value(n,i))}));for(let n=0;n<t.length;n++)if(new Set(r.map(s=>mb(s.keys[n])).filter(s=>s!==null)).size>1)throw new TypeError(`collection view cannot compare mixed types in ${t[n].field}`);return r.sort((n,i)=>{for(let[s,{direction:a}]of t.entries()){let l=gb(n.keys[s],i.keys[s]);if(l)return a==="a"?l:-l}return 0}).map(n=>n.node)}};function Hl(o){if(typeof o!="string")throw new TypeError("collection view sortedBy must be a string");if(o==="")return[];let e=new Set;return o.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 mb(o){if(o==null)return null;if(typeof o=="number"&&Number.isFinite(o)||U(o)&&o.isFinite())return"number";if(o instanceof Date&&Number.isFinite(o.getTime()))return"date";if(typeof o=="string"||typeof o=="boolean")return typeof o;throw new TypeError("collection view sort requires loaded finite scalar values")}function gb(o,e){return o==null||e==null?o==null?e==null?0:-1:1:U(o)?o.comparedTo(e):U(e)?-e.comparedTo(o):o<e?-1:o>e?1:0}var ns=class{constructor(e=null,t=null){this.parent=e,this.segment=t,this.children=new Map,this.registrations=new Set}},Yl=class{#e;#t;#r;#n;#o;#i=!0;#s;constructor(e,{path:t,attr:r,recipient:n,order:i,subtree:s=!1}){this.#e=e,this.#t=t,this.#r=r,this.#n=n,this.#o=i,this.#s=s}get router(){return this.#e}get path(){return this.#t}get attr(){return this.#r}get recipient(){return this.#n}get subtree(){return this.#s}get active(){return this.#i}get order(){return this.#o}close(){this.active&&(this.#i=!1,this.router.unregister(this))}},Zl=class{constructor({evt:e,node:t,path:r,oldvalue:n,attrsDiff:i,reason:s,fired:a,level:l,registration:c,index:u}){this.evt=e,this.node=t,this.path=r,this.oldvalue=n,this.attrsDiff=i,this.reason=s,this.fired=a,this.level=l,this.registration=c,this.index=u}},os=class{#e;#t=new ns;#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:n=!1}){if(typeof e!="string"||e==="")throw new TypeError(`A Data registration requires a path: ${e}`);let i=this.#t;for(let a of e.split(".")){let l=i.children.get(a);l||(l=new ns(i,a),i.children.set(a,l)),i=l}this.#o+=1;let s=new Yl(this,{path:e,attr:t,recipient:r,order:this.#o,subtree:n});return i.registrations.add(s),this.#r.set(s,i),this.#n+=1,s}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]!==an||e.reason==="autocreate")return;let r=t.slice(1),n=e.evt==="ins"||e.evt==="del";for(let i of Array.isArray(e.node)?e.node:[e.node]){let s=n?[...r,i.label]:r,a=s.join(".");for(let[l,c]of this.#i(s,e))l.active&&l.recipient.receive(new Zl({evt:e.evt,node:i,path:a,oldvalue:e.oldvalue??null,attrsDiff:e.attrs_diff??null,reason:e.reason??null,fired:e.fired??!1,level:c,registration:l,index:e.ind??null}))}}#i(e,t){let r=[],n=this.#t;for(let s of e){for(let a of n.registrations)n!==this.#t&&this.#s(a,"child",t)&&r.push([a,"child"]);if(n=n.children.get(s),!n)return r.sort(([a],[l])=>a.order-l.order)}for(let s of n.registrations)this.#s(s,"node",t)&&r.push([s,"node"]);let i=[...n.children.values()];for(;i.length;){let s=i.pop();for(let a of s.registrations)this.#s(a,"container",t)&&r.push([a,"container"]);i.push(...s.children.values())}return r.sort(([s],[a])=>s.order-a.order)}#s(e,t,r){let{evt:n}=r;return e.subtree?t!=="container"||n!=="upd_attrs":e.attr===null?n==="upd_attrs"?!1:!(t==="child"&&r.fired):t==="child"?!1:t==="container"?n!=="upd_attrs":n==="ins"||n==="del"?!0:Object.hasOwn(r.attrs_diff??{},e.attr)}};var tc={};ee(tc,{GridStructure:()=>hn});var Ql={};ee(Ql,{GridFormulas:()=>Jl,addNumeric:()=>Kl,formulaDefinitions:()=>ko,parseArithmetic:()=>Cf,sameValue:()=>Nf});var bb="#",wb=/[A-Za-z_$][\w$]*/g;function ko(o){let e=new Map;for(let c of o){if(c.formula==null)continue;let u=c.formula.trim(),d=u===bb?{kind:"index",field:null}:u.startsWith("+=")?{kind:"running",field:u.slice(2).trim()}:u.startsWith("%=")?{kind:"percent",field:u.slice(2).trim()}:null;if(d&&d.kind!=="index"&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(d.field))throw new TypeError(`grid formula '${u}' requires a field`);let f=new Map;for(let[m,b]of Object.entries(c))m.startsWith("formula_")&&f.set(m.slice(8),b);let h=null;if(!d)try{h=Cf(u)}catch{}let p=d?new Set(d.field?[d.field]:[]):new Set(u.match(wb)??[]);e.set(c.field,{field:c.field,formula:c.formula,special:d,arithmetic:h,parameters:f,references:p,calculated:c.calculated===!0,column:c})}let t=new Map;for(let c of e.values())for(let u of c.references)t.has(u)||t.set(u,new Set),t.get(u).add(c.field);let r=new Set,n=new Set,i=[],s=c=>{if(!n.has(c)){if(r.has(c))throw new TypeError(`grid formula dependency cycle at '${c}'`);r.add(c);for(let u of e.get(c).references)e.has(u)&&s(u);r.delete(c),n.add(c),i.push(c)}};for(let c of e.keys())s(c);let a=new Set;for(let c of i){let u=e.get(c);(["index","running"].includes(u.special?.kind)||[...u.references].some(d=>a.has(d)))&&a.add(c)}let l=new Map([...e].map(([c,u])=>[c,Object.freeze({...u,view:a.has(c)})]));return Object.freeze({definitions:l,triggered:t,order:Object.freeze(i),viewFields:a})}function Cf(o){let e=_b(o),t=0,r=()=>e[t],n=c=>{if(r().value!==c)throw new SyntaxError(`expected '${c}' in arithmetic formula`);return e[t++]},i={"+":1,"-":1,"*":2,"/":2,"%":2,"**":3},s=()=>{let c=r();if(c.type==="number")return t++,{kind:"number",value:c.value};if(c.type==="name")return t++,{kind:"name",value:c.value};if(c.value==="("){t++;let u=a(0);return n(")"),u}if(c.value==="+"||c.value==="-")return t++,{kind:"unary",operator:c.value,child:s()};throw new SyntaxError(`unexpected '${c.value||"end"}' in arithmetic formula`)},a=c=>{let u=s();for(;i[r().value]>=c;){let d=e[t++].value,f=a(i[d]+(d==="**"?0:1));u={kind:"binary",operator:d,left:u,right:f}}return u},l=a(0);if(r().type!=="eof")throw new SyntaxError(`unexpected '${r().value}' in arithmetic formula`);return l}function _b(o){let e=[],t=0;for(;t<o.length;){let r=o.slice(t),n=/^\s+/.exec(r);if(n){t+=n[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 s=/^[A-Za-z_$][\w$]*/.exec(r);if(s){e.push({type:"name",value:s[0]}),t+=s[0].length;continue}let a=/^(?:\*\*|[()+\-*/%])/.exec(r);if(a){e.push({type:"operator",value:a[0]}),t+=a[0].length;continue}throw new SyntaxError(`unsupported arithmetic formula token at ${t}`)}return e.push({type:"eof",value:""}),e}function Df(){if(Zr()==="number")throw new Error("A Decimal backend is required for exact grid formulas")}function Eo(o,e){if(U(o))return o;if(o==null||o==="")return null;if(typeof o!="number"&&typeof o!="string")throw new TypeError("Decimal arithmetic requires numeric values");return new e(String(o))}var yb={"+":(o,e)=>o+e,"-":(o,e)=>o-e,"*":(o,e)=>o*e,"/":(o,e)=>o/e,"%":(o,e)=>o%e,"**":(o,e)=>o**e};function xo(o,e){if(o.kind==="number")return Number(o.value);if(o.kind==="name"){if(!Object.hasOwn(e,o.value))throw new ReferenceError(`${o.value} is not defined`);return e[o.value]}return o.kind==="unary"?o.operator==="-"?-xo(o.child,e):+xo(o.child,e):yb[o.operator](xo(o.left,e),xo(o.right,e))}function is(o,e,t){if(o.kind==="number")return new t(o.value);if(o.kind==="name"){if(!Object.hasOwn(e,o.value))throw new ReferenceError(`${o.value} is not defined`);return Eo(e[o.value],t)}if(o.kind==="unary"){let s=is(o.child,e,t);return s==null?null:o.operator==="-"?s.neg():s}let r=is(o.left,e,t),n=is(o.right,e,t);if(r==null||n==null)return null;if(o.operator==="**")return r.pow(Number(n.toString()));let i={"+":"plus","-":"minus","*":"times","/":"div","%":"mod"}[o.operator];return r[i](n)}function Nf(o,e){return Object.is(o,e)?!0:U(o)&&U(e)&&o.eq(e)}function Kl(o,e){if(e==null||e==="")return o;if(U(o)||U(e)){Df();let t=U(o)?o.constructor:e.constructor;return Eo(o,t).plus(Eo(e,t))}if(typeof e!="number"||!Number.isFinite(e))throw new TypeError("Grid aggregate formulas require numeric values");return o+e}function vb(o,e){let t=U(e)?e.eq(0):Object.is(e,0);if(o==null||o===""||e==null||t)return null;if(U(o)||U(e)){let r=U(o)?o.constructor:e.constructor;return Eo(o,r).div(Eo(e,r)).times(new r(100))}if(typeof o!="number"||typeof e!="number")throw new TypeError("Percentage formulas require numeric values");return o/e*100}var Jl=class{#e;#t=ko([]);#r=new Set;#n=null;#o=null;#i=[];#s=[];#a=!1;#l=new Map;#c=null;constructor(e){this.#e=e}get source(){return this.#e}get runtime(){return this.source.rootBuilder.binding}get errors(){return new Map(this.#l)}get formulas(){return this.#t}get dataFields(){return new Set(this.formulas.order.filter(e=>!this.viewFields.has(e)))}get viewFields(){return this.formulas.viewFields}configure(e,t,r){if(!(e.formulas===this.#t&&r===this.#n&&t===this.#o&&this.#i.length)&&(this.disconnect(),this.#t=e.formulas,this.#r=new Set(e.fields),this.#n=r,this.#o=t,this.#l.clear(),!!this.formulas.definitions.size)){this.#i=[r.subscribe(n=>this.#f(n)),t.subscribe(()=>{this.#c=null})];for(let n of this.formulas.definitions.values())for(let i of n.parameters.values()){if(typeof i!="string"||!i.startsWith("^"))continue;let[s,a=null]=this.source.absDatapath(i).split("?");this.#s.push(this.runtime.router.register({path:s,attr:a,recipient:{receive:()=>{this.#c=null,this.recalculate(this.#d([n.field]))}}}))}this.recalculate(this.#d(this.#u(n=>n.calculated)))}}disconnect(){for(let e of this.#i)e();for(let e of this.#s)e.close();this.#i=[],this.#s=[],this.#n=null,this.#o=null,this.#c=null,this.#t=ko([])}value(e,t){if(!this.viewFields.has(t))return this.#n.value(e,t);let r=this.#b().get(e);return r===void 0?null:r[t]}#u(e){return[...this.formulas.definitions.values()].filter(e).map(t=>t.field)}#d(e){let t=new Set(e),r=[...e];for(;r.length;)for(let n of this.formulas.triggered.get(r.shift())??[])t.has(n)||(t.add(n),r.push(n));return t}#f({full:e,rows:t,event:r,field:n}){if(this.#c=null,this.#a)return;if(e){this.recalculate(this.#d(this.#u(u=>u.calculated||u.special)));return}let[i]=t,s;n!==null?s=[n]:r.node===i?s=r.evt==="upd_attrs"?Object.keys(r.attrs_diff):[...this.formulas.triggered.keys()]:s=(Array.isArray(r.node)?r.node:[r.node]).map(u=>u.label);let a=new Set;for(let u of s)for(let d of this.formulas.triggered.get(u)??[])a.add(d);let l=this.#d(a),c=[...l].some(u=>this.formulas.definitions.get(u).special?.kind==="percent");this.recalculate(l,c?null:[i])}#p(e){let t={};for(let[r,n]of e.parameters)t[r]=typeof n=="string"&&(n.startsWith("^")||n.startsWith("="))?this.source.getRelativeData(n):n;return t}#h(e,t,r,n,i){if(e.special?.kind==="index")return r;if(e.special?.kind==="running")return Kl(n,i(t,e.special.field));if(e.special?.kind==="percent")return vb(i(t,e.special.field),n);let s=this.#p(e),a={};for(let d of e.references)Object.hasOwn(s,d)?a[d]=s[d]:(this.#r.has(d)||this.#m(t).has(d))&&(a[d]=i(t,d)??null);if(Object.values(a).some(d=>d==null))return null;let l=Object.values(a).find(U);if(e.arithmetic)return l===void 0?xo(e.arithmetic,a):(Df(),is(e.arithmetic,a,l.constructor));if(l!==void 0)throw new Error("Decimal grid formulas support arithmetic expressions only");let c=[...Object.keys(a),"_currcell","_rowNode"];return this.runtime.inlineCompiler.compile(this.source,`struct.${e.field}.formula`,e.formula,c,`return (${e.formula}
|
|
222
|
+
);`)({...a,_currcell:e.column,_rowNode:t})}#m(e){return this.#n.rowMode==="attributes"?new Set(Object.keys(e.getAttr())):new Set(e.staticValue.keys())}#g(e,t,r){Nf(this.#n.value(e,t),r)||(this.#n.rowMode==="attributes"?e.setAttr({[t]:r}):e.staticValue.setItem(t,r))}recalculate(e,t=null){if(this.#a||!e.size||this.#n===null)return;this.#a=!0;let r=(n,i)=>this.#n.value(n,i);try{let n=this.#n.getRows();for(let i of this.formulas.order){let s=this.formulas.definitions.get(i);if(!e.has(i)||s.view)continue;let a=null,l=null;if(s.special?.kind==="percent")try{a=0;for(let c of n)a=Kl(a,r(c,s.special.field))}catch(c){a=null,l=c}for(let c of t??n){let u=null;try{u=this.#h(s,c,null,a,r)}catch(d){l=d}this.#g(c,i,u)}l?this.#l.set(i,l):this.#l.delete(i)}}finally{this.#a=!1}}#b(){if(this.#c!==null)return this.#c;let e=this.#o.getRows(),t=new Map(e.map(n=>[n,{}])),r=(n,i)=>this.viewFields.has(i)?t.get(n)[i]:this.#n.value(n,i);for(let n of this.formulas.order){let i=this.formulas.definitions.get(n);if(!i.view)continue;let s=0,a=null;for(let[l,c]of e.entries()){let u=null;try{u=this.#h(i,c,l+1,s,r),i.special?.kind==="running"&&(s=u)}catch(d){a=d}t.get(c)[n]=u}a?this.#l.set(n,a):this.#l.delete(n)}return this.#c=t,t}};var xb=new Set(["T","B","L","R","N","D","H","DHZ"]),kb=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"]),Eb=/^formula_[A-Za-z_$][\w$]*$/,Tb=new Set(["tag","code","name","background","color"]),hn=class{#e=new Map;constructor(e){if(!(e instanceof x))throw new TypeError("grid structpath must resolve to a Bag");let t=ss(e,"view_0"),r=ss(e,"info"),n=ss(t,"rows_0"),i=ss(r,"columnsets"),s=new Set,a=new Map;for(let c of i.getNodes()){let u=c.getAttr();if(Of(u,Tb),ec(u.code,"colgroup code"),u.tag!=="columnset"||c.resolver||c.staticValue!=null||c.label!==u.code)throw new TypeError("grid columnset requires a scalar definition labelled by code");if(a.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 d of["background","color"])if(u[d]!=null&&typeof u[d]!="string")throw new TypeError(`grid ${d} must be text`);a.set(u.code,{...u,name:u.name??u.code})}this.columns=[],this.groups=[];let l=[];for(let c of n.getNodes()){let u=c.getAttr();if(Of(u,kb,Eb),u.tag!=="cell"||c.staticValue!=null||c.resolver)throw new TypeError("grid cell must be a scalar declaration");if(ec(u.field,"field"),s.has(u.field))throw new TypeError(`Duplicate grid field: ${u.field}`);if(s.add(u.field),this.#e.set(u.field,c),u.columnset!=null&&!a.has(u.columnset))throw new TypeError(`Unknown grid columnset: ${u.columnset}`);if(u.dtype!=null&&!xb.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 p of["name","title","format"])if(u[p]!=null&&typeof u[p]!="string")throw new TypeError(`grid ${p} 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(ec(u.checkedField,"checkedField"),u.edit)throw new TypeError("external check sets cannot edit row fields")}Sb(u);let d=Object.freeze({...u,name:u.name??u.field,align:u.align??(["L","R","N"].includes(u.dtype)?"end":"start")});if(l.push(d),u.hidden)continue;this.columns.push(d);let f=u.columnset??null,h=this.groups.at(-1);(!h||h.code!==f)&&(h={code:f,...f===null?{name:null}:a.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([...s]),this.formulas=ko(l);for(let c of this.groups)Object.freeze(c.columns),Object.freeze(c);Object.freeze(this.columns),Object.freeze(this.groups),Object.freeze(this)}columnNode(e){return this.#e.get(e)}moveColumn(e,t,r=!1){let n=this.#e.get(e),i=this.#e.get(t);if(!n||!i||n===i)return;let s=n.parentBag,a=s.getNodes(),l=a.indexOf(n),c=a.indexOf(i),u=c+Number(r)-+(l<c);u!==l&&s.move(l,u)}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 ss(o,e){let t=o.getNode(e);if(!t||t.resolver||!(t.staticValue instanceof x))throw new TypeError(`grid struct requires Bag ${e}`);return t.staticValue}function Of(o,e,t=null){for(let r of Object.keys(o))if(!e.has(r)&&!t?.test(r))throw new TypeError(`Unsupported grid struct attribute: ${r}`)}function Sb(o){if(o.formula!=null&&(typeof o.formula!="string"||!o.formula.trim()))throw new TypeError("grid formula must be nonempty text");if(o.formula==null&&(o.calculated!=null||Object.keys(o).some(e=>e.startsWith("formula_"))))throw new TypeError(`grid ${o.field}: calculated and formula_<name> require a formula`);for(let e of["calculated","hidden"])if(o[e]!=null&&typeof o[e]!="boolean")throw new TypeError(`grid ${e} must be a boolean`);if(o.totalize!=null&&typeof o.totalize!="boolean"&&(typeof o.totalize!="string"||!o.totalize))throw new TypeError("grid totalize requires a boolean or a Data path");for(let e of["footer_value","footer_format"])if(o[e]!=null&&typeof o[e]!="string")throw new TypeError(`grid ${e} must be text`)}function ec(o,e){if(typeof o!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))throw new TypeError(`grid ${e} requires a simple field identifier`)}function $f(o){let e=new x,t=new x,r=new x;e.setItem("view_0",new x,{tag:"view"}),e.getItem("view_0").setItem("rows_0",t,{tag:"rows"}),e.setItem("info",new x),e.getItem("info").setItem("columnsets",r);let n=(i,s=null)=>{if(i.builder.validateNode(i),i.nodeTag!=="column"||i.staticValue!=null)throw new TypeError("grid column must be a scalar declaration");let a={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(u=>u.startsWith("formula_"))];for(let u of l)i.getAttr(u)!=null&&(a[u]=i.getAttr(u));let c=`cell_${a.field}`;if(t.getNode(c))throw new TypeError(`Duplicate grid field: ${a.field}`);s!==null&&(a.columnset=s),t.setItem(c,null,a)};for(let i of o.getNodes())if(i.nodeTag==="column")n(i);else if(i.nodeTag==="colgroup"){if(i.builder.validateNode(i),!(i.staticValue instanceof N))throw new TypeError("grid colgroup requires column declarations");let s=i.getAttr("code");if(r.getNode(s))throw new TypeError(`Duplicate grid colgroup: ${s}`);let a={tag:"columnset",code:s,name:i.getAttr("name")??s};for(let l of["background","color"])i.getAttr(l)!=null&&(a[l]=i.getAttr(l));r.setItem(s,null,a);for(let l of i.staticValue.getNodes())n(l,s)}else throw new TypeError("grid struct accepts column and colgroup only");return e}function Rf(o){if(o._getMeta("gramlot_component")?.bagStruct){let e=o.staticValue instanceof N?o.staticValue.getNodes():[];if(e.some(t=>!t._getMeta("gridStruct"))||e.length>1)throw new TypeError("grid accepts one struct declaration");if(e.length&&o.getAttr("structpath")!=null)throw new TypeError("grid requires structpath or nested struct, not both");if(!e.length&&!o.getAttr("structpath"))throw new TypeError("grid requires structpath or nested struct");if(!["values","attributes"].includes(o.getAttr("rowMode")))throw new TypeError("grid rowMode must explicitly be values or attributes")}if(o._getMeta("gridStruct")){if(!o.parentNode?._getMeta("gramlot_component")?.bagStruct)throw new TypeError("struct requires a grid parent");if(!(o.staticValue instanceof N))throw new TypeError("grid struct requires column declarations");new hn($f(o.staticValue))}}function jf(o,e){let t=$f(o.staticValue);new hn(t);let r=`_gramlot.grid.${crypto.randomUUID().replaceAll("-","")}.struct`;e.setItem(r,t,null,">",!1,!0,o),o.parentNode.setAttr({structpath:r},!1),o.setValue(null,!1)}var as=class{#e;constructor(e){this.#e=e}get runtime(){return this.#e}install(e){let t=To(e),r=this.setterNodes(e);nc(e);for(let n of r)n._getMeta("gridStruct")?jf(n,this.runtime.data):this.applySetter(n),this.runtime.closeBranch(n),n.parentBag&&n.parentBag.popNode(n.label);this.applyDefaults(t.filter(n=>n.nodeTag&&!n._getMeta("data_element")))}setterNodes(e){return To(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,n=Ib(e.getAttr()),i=this.runtime.data;if(r!==null)i.setItem(t,r,n,">",!1,!0,e),r instanceof x&&e.setAttr({value:null},!1);else{let s=i.getNode(t);s?n&&s.setAttr(n,!0):i.setItem(t,null,n,">",!1,!0,e)}}applyDefaults(e){for(let t of e){let r=t.getAttr();for(let[n,i]of Object.entries(r)){if(!Ab(t,n,i))continue;let s=n==="value"?r.default_value??r.default:r[`default_${n}`];s!=null&&this.#t(t,i,s)}this.#r(t,r)}}#t(e,t,r){let n=e.absDatapath(t);if(n===null)return;let[i,s=null]=n.split("?",2),a=this.runtime.data,l=a.getNode(i);if(s===null){if(l&&l.value!==null&&l.value!==void 0)return;a.setItem(i,r,null,">",!1,!0,e)}else if(l){let c=l.getAttr(s);c==null&&l.setAttr({[s]:r},!0)}else a.setItem(i,null,{[s]:r},">",!1,!0,e)}#r(e,t){let r={};for(let[s,a]of Object.entries(t))s.startsWith("attr_")&&(r[s.slice(5)]=H(a)?Jt(e,s):e.pointerType(a)?e.getRelativeData(a):a);if(!Object.keys(r).length)return;let n=[t.value,t.src].find(s=>e.pointerType(s));if(!n)return;let i=e.absDatapath(n);i!==null&&this.runtime.data.getNode(i.split("?",1)[0])?.setAttr(r,!0,!0,!1)}};function Ab(o,e,t){return e==="_meta"||lt.has(e)||e==="default"||e.startsWith("default_")||e.startsWith("attr_")||e.endsWith("_path")?!1:o.pointerType(t)!==null}function Ib(o){let e={};for(let[t,r]of Object.entries(Et(o??{})))lt.has(t)||t.startsWith("_")||t==="destination_path"||t==="value"||r!=null&&(e[t]=r);return Object.keys(e).length?e:null}function Cb(o){let e=o.builder;if(!(e instanceof me))throw new Error(`dataSetter '${o.label}': dataSetter is not supported inside ${e.constructor._name}`)}function nc(o){for(let e of To(o))Rf(e),e.nodeTag==="dataSetter"&&Cb(e),Rb(e)}var Db=["_init","_onStart","_onBuilt","_delay","_timing","_userChanges"],Nb=new Set(["dataFormula","dataController","dataRpc","dataRemote"]),Ob=["_onCalling","_onResult","_onError"],$b=["_delay","_timing","_userChanges"],rc=["_init","_onBuilt","_onStart"];function Rb(o){let e=i=>o.getAttr(i)!==null&&o.getAttr(i)!==void 0,t=!o._getMeta("data_element")&&typeof o.getAttr("remote")=="string";if(o.nodeTag!=="dataRpc"){let i=Ob.find(s=>e(s)&&!(s==="_onCalling"&&(o.nodeTag==="dataRemote"||t)));if(i){let s=i==="_onCalling"?"dataRpc, dataRemote and remote":"dataRpc";throw new Error(`${o.nodeTag??"fragment"} '${o.label}': '${i}' is allowed only on ${s}`)}}if(Nb.has(o.nodeTag)){let i=Object.entries(o.getAttr()).find(([,a])=>Le(a));if(i)throw new Error(`${o.nodeTag} '${o.label}': '${i[0]}' is a == expression, not accepted on ${o.nodeTag}`);let s=o.nodeTag==="dataRemote"?rc.find(e):null;if(s)throw new Error(`dataRemote '${o.label}': '${s}' is not accepted on dataRemote, its resolver loads when the Data is read`);for(let a of rc){let l=o.getAttr(a);if(!(l==null||typeof l=="boolean"||typeof l=="number"))throw new Error(`${o.nodeTag} '${o.label}': '${a}' accepts true, false, null or a number, not ${JSON.stringify(l)}`)}return}let r=Db.find(i=>e(i)&&!(i==="_delay"&&!o._getMeta("data_element")&&o.nodeTag!=="html_button")&&!(t&&$b.includes(i)));if(!r)return;let n=rc.includes(r)?"dataFormula, dataController and dataRpc":"dataFormula, dataController, dataRpc and dataRemote";throw new Error(`${o.nodeTag??"fragment"} '${o.label}': '${r}' is allowed only on ${n}`)}function To(o){if(o instanceof N)return o.getNodes().flatMap(t=>To(t));let e=[o];return o.value instanceof N&&e.push(...To(o.value)),e}var jb=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"]),So=class{#e;#t=null;#r=null;constructor(e){this.#e=e}get binding(){return this.#e}debounce(e,t){this.#r?.();let r=null,n=setTimeout(()=>{r(),this.#r=null,t()},e);r=this.binding.track(()=>clearTimeout(n)),this.#r=()=>{clearTimeout(n),r(),this.#r=null}}startTiming(e,t){if(this.#t?.(),!(e>0))return;let r=setInterval(t,e*1e3),n=this.binding.track(()=>clearInterval(r));this.#t=()=>{clearInterval(r),n(),this.#t=null}}cancel(){this.#r?.(),this.#t?.()}},pn=class{#e;#t=[];#r=new Set;#n;#o=null;#i=!1;constructor(e){this.#e=e,this.#n=new So(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,n=Ze(e,e.getAttr("_timing"));for(let[i,s]of e.pointers()){if(i==="datapath")continue;let a=e.absDatapath(s);if(a===null)continue;let[l,c=null]=a.split("?",2),u=r.register({path:l,attr:c,recipient:this});this.#t.push(u),(i==="_timing"||n.has(i))&&this.#r.add(u)}this.#t.push(...this.binding.runtime.subscriptions.subscribeNode(e,(i,s,a)=>(l,c)=>{let u={kind:"subscription",topic:a,payload:l,metadata:c};if(this.#a("_userChanges")&&a!=="node")return;let d=this.#a("_delay");d>0?this.#n.debounce(d,()=>this.invoke(u)):this.invoke(u)})),this.#s(),this.kind==="remote"&&this.invoke({kind:"install",change:null})}receive(e){if(this.#r.has(e.registration)){this.#s();return}if(this.#a("_userChanges")&&e.level!=="node")return;let t={kind:"data",change:e},r=this.#a("_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",n=this.kind==="rpc",i=this.kind==="remote",s=this.readArguments(e);e.askResult&&(Object.assign(s,e.askResult),s._askResult=e.askResult);let a=t.getAttr("_ask"),l=this.binding.runtime.askDialog;if(a&&!e.askDone&&l.required(this.binding,a,s,"_ask"))return l.show(this.binding,a,s,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,s,!0);return}return this.invoke({...e,askDone:!0,askResult:p})}});let[c,u]=[r?"formula":"script",t.getAttr(r?"formula":"script")],d=t.getAttr("_if");if(d&&!this.#l("_if",d,`return (${d})`,s,!1)){if(i&&this.#f(),[c,u]=["_else",t.getAttr("_else")],!u)return;if(n||i){this.#l(c,u,u,s,!0);return}}if(n)return this.#c(s);if(i)return this.#d(s);let f=t.getAttr("func"),h;if(u)h=this.#l(c,u,r?`return ${u}`:u,s,!0);else if(f==null){if(!r)return;h=new x(ls(s))}else{let{group:p,method:m}=this.binding.runtime.logicRegistry.resolve(f,t);h=r?m.call(p,s):m.call(p,t,s)}r&&t.setRelativeData(t.pathAttribute("result_path"),h)}readArguments(e){let t=this.node,[,r]=t.rootBuilder.runtimeValues(t),n=Object.fromEntries(Object.entries(r).filter(([l])=>!jb.has(l)&&!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),i={...e.kind==="subscription"?e.payload:{},...this.binding.runtime.renderer.references.resolveArguments(n)};e.kind==="subscription"&&(i._subscription_kwargs=e.payload,i._subscription_metadata=e.metadata);let s=e.change??null,a=s?s.level:e.kind==="subscription"?e.topic:e.kind;return i._node=s?s.node:null,i._triggerpars={kw:s,trigger_reason:a},i._reason=a,e.kind==="click"&&(Object.assign(i,Pb(e)),e.rowContext&&Object.assign(i,e.rowContext,{event:e.event})),i}cancel(){this.#n.cancel()}#s(){this.#n.startTiming(this.#a("_timing"),()=>this.invoke({kind:"timing",change:null}))}#a(e){let t=this.node,r=t.getAttr(e);return H(r)?Jt(t,e):t.pointerType(r)?t.getRelativeData(r):r??null}#l(e,t,r,n,i){let s=[...i?["_kwargs"]:[],...Pf,...Bf,...Object.keys(ls(n))];return["_onCalling","_onResult","_onError","_ask_onCancel"].includes(e)?dt(this.binding.runtime,this.node,e,t,{...n,_kwargs:n},s):this.binding.runtime.inlineCompiler.compile(this.node,e,t,s,r)({...n,_kwargs:n})}async#c(e){let t=this.node,[r,n,i]=["_onCalling","_onResult","_onError"].map(a=>t.getAttr(a)),s=t.requests;if(s.calling(r?()=>this.#l("_onCalling",r,r,e,!0):null))return s.submit(this.#a("method"),ls(e),a=>this.#u(a,e,n,i))}async#u(e,t,r,n){if(this.binding.closed)return;let i=this.node,s=this.#a("timeout"),a=s>0?setTimeout(()=>{let u=new Error(`${i.nodeTag} '${i.label}': no answer within ${s} ms`);u.name="TimeoutError",e.controller.abort(u)},s):null,l;try{l={result:await this.binding.call("data",e)}}catch(u){l={error:u}}if(clearTimeout(a),this.binding.closed||e.ignored)return;if("error"in l){if(!n)throw l.error;this.#l("_onError",n,n,{...t,error:l.error},!0);return}let{result:c}=l;i.getAttr("result_path")!=null&&i.setRelativeData(i.pathAttribute("result_path"),c),r&&this.#l("_onResult",r,r,{...t,result:c},!0)}#d(e){this.#f();let t=this.#i;this.#i=!1;let r=this.node,n=r.absDatapath(r.pathAttribute("destination_path"));if(n===null)return;let i=r.getAttr("_onCalling"),s=new fn({binding:this.binding,method:this.#a("method"),params:ls(e),cacheTime:this.#a("cacheTime"),sync:this.#a("sync")!==!1&&this.binding.runtime.gramlot.rpc.supportsCallSync,onCalling:i?()=>this.#l("_onCalling",i,i,e,!0):null,onError:a=>{throw new Error(`${r.nodeTag} '${r.label}': dataRemote '${s.method}' failed: ${a.message}`,{cause:a})}});this.binding.runtime.data.setResolver(n,s),this.#o={path:n,resolver:s},t&&s.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()}},cs=class extends pn{get kind(){return"formula"}},us=class extends pn{get kind(){return"controller"}},ds=class extends pn{get kind(){return"rpc"}},fs=class extends pn{get kind(){return"remote"}},Pf=["_node","_triggerpars","_reason","_subscription_kwargs","_subscription_metadata","_askResult"],Bf=["_evt","button_counter","button_shift","button_ctrl","button_alt","button_meta"];function ls(o){let e={...o};for(let t of[...Pf,...Bf])delete e[t];return e}function Pb({event:o,counter:e}){return{_evt:o,button_counter:e,button_shift:!!o.shiftKey,button_ctrl:!!o.ctrlKey,button_alt:!!o.altKey,button_meta:!!o.metaKey}}var Bb=[[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 "]],Mb=/(\W|^)PUBLISH (?:\s*)(\^?[\w.#@$?-]+)/,Lb=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"]),hs=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 n=r.trim();if(Mb.test(n))throw new Error(`${Ao(e,t)}: the PUBLISH macro is excluded from Gramlot`);let i=n.replace(/\$(\d+)/g,(s,a)=>`arguments[${parseInt(a,10)-1}]`);for(let[s,a,l]of Bb)s&&(i=i.replace(s,`; ${s.source.slice(1)}`)),i=i.replace(a,l);return i!==n&&console.warn(`${Ao(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,n,i=r){if(e.activatedCode(t)!==r)throw new Error(`${Ao(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 s=this.#t.get(e);s||(s=new Map,this.#t.set(e,s),this.runtime.bindingFor(e).track(()=>this.release(e)));let a=s.get(t);a?.source!==i&&(a={source:i,text:this.preprocess(e,t,i),key:null,run:null},s.set(t,a));let l=n.filter(Fb),c=l.join(",");if(a.key!==c){let u=zb(e,t,a.text,l);a.key=c,a.run=d=>u.apply(e,l.map(f=>d[f]))}return a.run}compileExpression(e,t,r){let n=r.slice(2).trim(),i=ge(e.getAttr()).filter(([,a])=>!Le(a)),s=this.compile(e,t,r,[...i.map(([a])=>a).filter(a=>a!=="_F"),"_F"],`return ${n}`);return a=>{let l={};for(let[c,u]of i)Object.hasOwn(a,c)?l[c]=a[c]:l[c]=e.pointerType(u)?e.getRelativeData(u):u;return s({...l,_F:(c,u)=>this.runtime.gramlot.format(c,u)})}}compilePointerExpression(e,t,r,n){let i=this.compile(e,t,r,["_pointerValues","_F"],`return (${n}
|
|
223
|
+
)`);return s=>i({_pointerValues:s,_F:(a,l)=>this.runtime.gramlot.format(a,l)})}release(e,t=null){if(t===null){this.#t.delete(e);return}let r=this.#t.get(e);if(r)for(let n of t){r.delete(n);for(let[i]of ge({[n]:null}))r.delete(i)}}};function Fb(o){return/^[A-Za-z_$][\w$]*$/.test(o)&&!Lb.has(o)}function Ao(o,e){return`${o.nodeTag} '${o.label}' ${e?`'${e}'`:"node value"}`}function zb(o,e,t,r){try{return t.startsWith("function")?new Function(`return (${t}
|
|
228
224
|
)`)():new Function(...r,`${t}
|
|
229
|
-
`)}catch(
|
|
230
|
-
${t}`,{cause:
|
|
225
|
+
`)}catch(n){throw n instanceof EvalError?new EvalError(`${Ao(o,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:n}):new SyntaxError(`${Ao(o,e)}: ${n.message} in the inline code:
|
|
226
|
+
${t}`,{cause:n})}}var ps=class{#e;#t;#r=!1;#n=null;#o=null;constructor(e){this.#e=e,this.#t=new So(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.#s("_timing"),()=>this.trigger())}receive(e){if(this.#s("_userChanges")&&e.level!=="node")return;let t=this.#s("_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,n={};for(let[l,c]of Object.entries(t))l.startsWith("remote_")&&(n[l.slice(7)]=c);let i=e.getAttr("_if");if(i&&!this.#a("_if",i,`return (${i})`,n)){let l=e.getAttr("_else");l&&this.#a("_else",l,l,n);return}let s;try{let l=R(n);if(t._cachedRemote&&this.#i(r,l))return;let c=e.getAttr("_onCalling");if(!e.requests.calling(c?()=>this.#a("_onCalling",c,c,n):null))return;s=await this.binding.runtime.gramlot.src.remoteSource(e,r,n)}catch(l){throw new Error(`${e.nodeTag} '${e.label}': remote '${r}' failed: ${l.message}`,{cause:l})}let a=e.getAttr("_onRemote");!this.closed&&s&&a&&await this.#a("_onRemote",a,a,n)}fragmentMounted(e,t){this.#n=e,this.#o=t}#i(e,t){let r=this.node.requests.inflight;return r?r.method===e&&R(r.params)===t:e===this.#n&&t===this.#o}#s(e){let[,t]=this.node.rootBuilder.runtimeValues(this.node);return t[e]??null}#a(e,t,r,n){return e==="_onRemote"?dt(this.binding.runtime,this.node,e,t,n):this.binding.runtime.inlineCompiler.compile(this.node,e,t,Object.keys(n),r)(n)}};var mn="gramlot-page-store-remote",ms=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=G(),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===mn)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",n=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?n?"upd_value":"del":e.evt,value:n?.value??null,attr:{...n?.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,mn):t.popNode(this.clientPath,mn);else if(e.op==="change")e.evt==="del"?t.popNode(r,mn):e.evt==="upd_attrs"?t.getNode(r).setAttr(e.attr,mn,!1,!1):t.setItem(r,e.value,e.attr,e.index??">",!1,!1,mn);else throw new Error("Unknown PageStore delivery")}unregister(){this.ready=!1,this.registration?.close(),this.registration=null,this.connection?.unregister(this)}};var qb=new Set(["title","msg","fields","_if","askIf"]),Ub=new Set(["name","lbl","tag","type","default_value","required","min","max","step","placeholder"]),gs=class{#e;#t=null;#r=new Map;constructor(e){this.#e=e}get runtime(){return this.#e}required(e,t,r,n){let i=(s,a)=>typeof a=="boolean"?a:e.runtime.inlineCompiler.compile(e.node,s,a,Object.keys(r),`return (${a});`)(r);if(typeof t=="string"){let s=e.node.getAttr("_ask_if");return!s||!!i("_ask_if",s)}return t?.askIf&&i(`${n}.askIf`,t.askIf),!t?._if||!!i(`${n}._if`,t._if)}show(e,t,r,n="Parameters"){let i=typeof t=="string"?{msg:t,title:n}: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(!qb.has(d))throw new Error(`Unsupported ask option: ${d}`);let s=i.fields??[];if(!Array.isArray(s))throw new TypeError("ask fields must be an array");let a=new Set;for(let d of s){if(!d||!/^[A-Za-z_]\w*$/.test(d.name)||a.has(d.name))throw new Error("ask fields require distinct simple names");a.add(d.name);for(let f of Object.keys(d))if(!Ub.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,c=this.#n(),u=this.#r;return new Promise((d,f)=>{let h=`ask_${G()}`,p=!1,m=()=>{},b=(w,_=null)=>{if(p)return;p=!0;let v=w?Object.fromEntries(s.map(E=>[E.name,l.data.getItem(`${h}.${E.name}`)])):null;u.delete(h),m();try{l.src.source.popNode(h),l.data.getNode(h)&&l.data.popNode(h),_?f(_):d(v)}catch(E){f(E)}};u.set(h,{finish:b}),m=e.track(()=>b(!1));try{let w=new me,_=w.root.html_dialog({nodeId:h,datapath:h,request:h,connect_oncancel:`${c}.cancel`,connect_onclose:`${c}.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??n,{id:`${h}_title`,style:"font-size:1.1em;margin:0 0 12px;"}),i.msg&&_.p(i.msg);let v=_.form({request:h,connect_onsubmit:`${c}.confirm`});for(let k of s){v.dataSetter({destination_path:`.${k.name}`,value:Object.hasOwn(r,k.name)?r[k.name]:k.default_value??(k.type==="checkbox"?!1:"")});let C=v.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 L of["required","min","max","step","placeholder"])k[L]!==void 0&&(O[L]=k[L]);k.tag==="textarea"?C.textarea(O):C.input({...O,type:k.type??"text"})}let E=v.div({style:"display:flex;justify-content:flex-end;gap:8px;margin-top:16px;"});E.html_button("Cancel",{type:"button",request:h,connect_onclick:`${c}.cancel`}),E.html_button("Confirm",{type:"submit",autofocus:s.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_${G()}`,t=this.#r;class r{confirm(i,s){s.preventDefault(),t.get(i.getAttr("request"))?.finish(!0)}cancel(i,s){s.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 bs=class{#e;#t=`errors_${G()}`;#r=null;#n=new Map;#o=new Set;#i=0;constructor(e){this.#e=e}show(e,t){let r=new Set,n=[];for(let s=e;s!==null&&typeof s=="object"&&!r.has(s);s=s.cause){if(s.name==="AbortError")return;r.add(s),n.push(s.stack??s.message)}let i=typeof e?.message=="string"?e.message:String(e);queueMicrotask(()=>{this.#e.disposed||this.#s(i,t,n.join(`
|
|
231
227
|
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_${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(
|
|
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>
|
|
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
|
-
`+
|
|
228
|
+
`))})}#s(e,t,r){let n=this.#e.gramlot,i=JSON.stringify([t,e]);if(this.#o.has(i))return;let s=this.#e.nodeIds.get(this.#t);if(!s){if(this.#n.clear(),this.#i=0,this.#r===null){let p=this;class m{close(w){p.#a(w.getAttr("notice"))}}this.#r=`errors_${G()}`,this.#e.logicRegistry.register(m,{group:this.#r,resource:"gramlot:error-notifications"})}let h=new me;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;"}),n.src.source.setItem(this.#t,n.src.prepareSource(h.source)),s=this.#e.nodeIds.get(this.#t)}if(this.#n.has(i))return;if(this.#n.size===5){let h=`${++this.#i} additional errors`,p=s.value.getNode("overflow");p?p.setValue(h):n.src.builder.wrapSource(s).p(h,{node_label:"overflow",role:"status",style:"margin:0;padding:12px;"});return}let a=`notice_${G()}`,l=new me,c=l.root.article({role:"alert",style:"color:inherit;padding:12px;border-bottom:1px solid var(--gramlot-border,#ddd);"}),u=c.div({style:"display:flex;align-items:start;gap:12px;"});u.strong(`==${JSON.stringify(t)}`,{style:"flex:1;color:var(--gramlot-error,#b13d48);"}),u.html_button("\xD7",{type:"button",notice:a,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;"}),c.p(`==${JSON.stringify(e)}`,{style:"margin:6px 0;overflow-wrap:anywhere;"});let d=c.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=n.src.builder.wrapSource(s).div({node_label:a});Z(f).setValue(n.src.prepareSource(l.source)),this.#n.set(i,a),n.dom.getDomNode(s).showPopover()}#a(e){this.#e.nodeIds.get(this.#t).value.popNode(e);for(let[r,n]of this.#n)n===e&&(this.#n.delete(r),this.#o.add(r));this.#n.size||this.#e.gramlot.src.source.popNode(this.#t)}};var Mf={dataFormula:cs,dataController:us,dataRpc:ds,dataRemote:fs},Vb=["datapath","_anchor","nodeId","form","formId"],gn=class{#e;#t=new Map;#r=new Map;#n;#o;#i;#s;#a;#l;#c=`gramlot-data-${G()}`;#u=!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 as(this),this.#i=new hs(this),this.#s=new gs(this),this.#a=new bs(this)}get gramlot(){return this.#e}reportError(e,t){this.disposed||this.#a.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.#u}get router(){return this.#n}get installer(){return this.#o}get inlineCompiler(){return this.#i}get askDialog(){return this.#s}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 _o(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 n=this.collectionStore(t,r);return Object.hasOwn(e,"gridCollectionView")?e.gridCollectionView.bindStore(n):Object.defineProperty(e,"gridCollectionView",{value:new vo(n),configurable:!0}),e.gridCollectionView}attach(){this.root.subscribe(this.#c,{any:e=>this.receiveData(e)})}receiveData(e){let t=this.root;for(let[r,n]of(e.pathlist??[]).entries()){let i=t.node(n)?.staticValue;if(!(i instanceof x))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 oc(this,e),this.#t.set(e,t)),t}closeBranch(e){let t=[];if(e.value instanceof N)for(let n of e.value.getNodes())try{this.closeBranch(n)}catch(i){t.push(i)}let r=this.bindingFor(e);if(r){this.#t.delete(e);let n=e.getAttr("nodeId");this.nodeIds.get(n)===e&&this.nodeIds.delete(n);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,n=[],i=s=>{try{this.closeBranch(s)}catch(a){n.push(a)}};try{if(t==="ins")this.#h(r);else if(t==="del")for(let s of Array.isArray(r)?r:[r])i(s);else if(t==="upd_value"||t==="upd_value_attr"){if(e.oldvalue instanceof N)for(let s of e.oldvalue.getNodes())i(s);this.inlineCompiler.release(r,[""]),t==="upd_value_attr"?this.#b(r,e.attrs_diff):this.#w(r).rebind(),r.value instanceof N&&this.#h(r.value)}else if(t==="upd_attrs")this.#b(r,e.attrs_diff);else throw new Error(`Unsupported Source event: ${t}`)}catch(s){throw n.length?new AggregateError([...n,s],"Source event failed"):s}return n}branchBuilt(e){let t=[];for(let r of this.#_(e)){let n=this.bindingFor(r);!n||n.hasStamp("built")||!this.renderer.attached(r)||(n.stamp("built"),t.push(n))}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.#u=!0,this.root.unsubscribe(this.#c,{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(n){e.push(n)}}if(e.length)throw new AggregateError(e,"Binding cleanup failed")}#h(e){if(!(e instanceof N)&&this.bindingFor(e))return;let t=e instanceof N?e.getNodes().flatMap(i=>this.#_(i)):this.#_(e),r=new Set(t.filter(i=>this.bindingFor(i))),n=new Map;for(let i of t){let s=i.getAttr("nodeId");if(s!=null){if(n.has(s)||this.nodeIds.has(s)&&this.nodeIds.get(s)!==i)throw new Error(`Duplicate nodeId '${s}'`);n.set(s,i)}}for(let[i,s]of n)this.nodeIds.set(i,s);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 s=[i];for(let a of t.filter(l=>!r.has(l)).reverse()){let l=a.getAttr("nodeId");n.get(l)===a&&this.nodeIds.get(l)===a&&this.nodeIds.delete(l);let c=this.bindingFor(a);if(c){this.#t.delete(a);try{c.close()}catch(u){s.push(u)}}}throw s.length>1?new AggregateError(s,"Source branch installation failed"):i}for(let i of t){let s=this.bindingFor(i);if(!(!s||s.hasStamp("init")||!this.renderer.attached(i))&&(s.stamp("init"),Lf(i.getAttr("_init"))))for(let a of s.providers)a.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 n=e.node.getAttr(r);if(Lf(n))for(let i of e.providers){if(typeof n!="number"||n<=0){i.invoke({kind:t,change:null});continue}let s=null,a=setTimeout(()=>{s(),i.invoke({kind:t,change:null})},n);s=e.track(()=>clearTimeout(a))}}#b(e,t){let r=this.#w(e);if(this.inlineCompiler.release(e,Object.keys(t)),Object.hasOwn(t,"nodeId")){let{old:n,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(n)===e&&this.nodeIds.delete(n),i!=null&&this.nodeIds.set(i,e)}Vb.some(n=>Object.hasOwn(t,n))?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 N)for(let r of e.value.getNodes())t.push(...this.#_(r));return t}};function Lf(o){return o===!0||typeof o=="number"}var oc=class{#e;#t;#r=!1;#n=[];#o=[];#i=new Set;#s=null;#a=null;#l=null;#c=new Set;#u=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.#s?[this.#s]:[]}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&&!Mf[e.nodeTag]&&e.nodeTag!=="dataBinder")return;!t&&typeof e.getAttr("remote")=="string"?this.#l??=new ps(this):this.#l&&(this.#l.close(),this.#l=null);let r=new Set,n=e._getMeta("gramlot_component");for(let[s,a]of[["bagStore","storepath"],["bagStruct","structpath"]]){if(!n?.[s])continue;if(s==="bagStore"&&e.nodeTag==="tree"&&e.treeStore!==null){let d=e.treeStore,f=`gramlot-tree-${G()}`;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(a);if(typeof l!="string"||!l||/^[\^=]/.test(l)||l.includes("?"))throw new TypeError(`${a} requires a plain Bag data path`);if(s==="bagStore"&&e.nodeTag==="tree"&&(l==="*S"||l.startsWith("*S."))){this.#o.push(this.runtime.registerTreeRoot(this,!0));continue}if(s==="bagStore"&&e.nodeTag==="tree"&&l==="*D"){this.#o.push(this.runtime.registerTreeRoot(this,!1));continue}let c=s==="bagStore"&&e.nodeTag==="tree"&&l.startsWith("*D.")?l.slice(3):e.absDatapath(l),u=this.runtime.router.register({path:c,recipient:this,subtree:!0});this.#o.push(u),s==="bagStore"&&n.bagStruct&&(this.#p=u)}let i=this.remote?Ze(e,e.getAttr("_timing")):new Set;if(this.remote){for(let[s,a]of Object.entries(e.getAttr()))if(s.startsWith("remote_"))for(let l of Ze(e,a))r.add(l)}for(let[s,a]of e.pointers()){if(t&&s!=="datapath")continue;let c=(s==="datapath"?e.parentNode:e).absDatapath(a);if(c===null)continue;let[u,d=null]=c.split("?",2),f=this.runtime.router.register({path:u,attr:d,recipient:this});this.#o.push(f),s==="datapath"&&this.#f.add(f),this.remote&&(s==="remote"||s.startsWith("remote_")||r.has(s))&&this.#c.add(f),this.remote&&(s==="_timing"||i.has(s))&&this.#u.add(f)}if(!t){this.#h(),this.remote?.register();return}if(e.nodeTag==="dataBinder"){this.#a??=new ms(this),this.#a.register();return}this.#s??=new Mf[e.nodeTag](this),this.#s.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 n=>{if(this.closed)return;if(ao(r))return Tt(this.runtime,e,r,n);let[,i]=e.rootBuilder.runtimeValues(e),s=Object.fromEntries(Object.entries(i).filter(([l])=>!l.startsWith("subscribe_")&&!l.startsWith("selfsubscribe_"))),a={...this.runtime.renderer.references.resolveArguments(s),p_0:n};return this.runtime.inlineCompiler.compile(e,t,r,Object.keys(a))(a)}}))}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.#c.has(e.registration)&&this.remote.receive(e),this.#u.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,n=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{n()}}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.#a?.unregister();for(let e of this.#o.splice(0))e.close();this.#p=null,this.#f.clear(),this.#c.clear(),this.#u.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 n=e._getMeta("gramlot_component")?.dragSource?r.element.getDragContext(t):{dragValues:{},item:void 0,path:void 0};if(n===null)return null;let{dragValues:i,item:s,path:a}=n;if(r.resolved.onDrag){let c=this.renderer.html.callLogic(e,r.resolved.onDrag,{dragValues:i,item:s,path:a});if(c&&typeof c.then=="function")throw new TypeError("onDrag must run synchronously");if(c===!1)return null}return Qe(i),{dragValues:Object.fromEntries(Object.entries(i).map(([c,u])=>{if(c.startsWith("text/")||c==="dragTags"){if(typeof u!="string")throw new TypeError(`${c} drag data must be text`);return[c,u]}return[c,j(R(u))]})),item:s,path:a}}};var er=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 n=t.split(",").map(i=>i.trim()).filter(Boolean).map(i=>{let s=i.split("*").map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return new RegExp(`^${s.join(".*")}$`)});return e.filter(i=>i!=="dragTags"&&(r.includes(i)||n.some(s=>s.test(i))))}static acceptsTags(e="",t=""){if(!t.trim())return!0;let r=new Set(e.split(",").map(n=>n.trim()).filter(Boolean));return r.size?t.split(",").some(n=>n.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,n,i=[]){let s=this.acceptedTypes(e,n.dropTypes,i),a=n.dropEffect??"move",l=this.isTarget(n)&&s.length>0&&this.acceptsTags(t,n.dropTags)&&this.acceptsEffect(r,a);return{accepted:l,types:s,dropEffect:l?a:"none"}}};var Ff=["dragstart","dragover","dragleave","drop","dragend"],_s=class{#e;#t;#r=null;#n=null;#o=null;#i;constructor(e){this.#e=e,this.#t=e.destination.ownerDocument;for(let t of Ff)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)}#s(e,t){for(let r of e.composedPath()){let n=this.#e.elements.get(r);if(n&&t(n.resolved))return n}return null}#a(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.#s(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 n=this.#a(t,e);if(!n){e.preventDefault();return}let i=new Map(Object.entries(r.dragValues).filter(([c])=>c!=="dragTags").map(([c,u])=>[c,c.startsWith("text/")?u:R(u)]));if(!i.size){e.preventDefault();return}let s=t.resolved.effectAllowed??"all";er.acceptsEffect(s,"move");let a="";for(let c=t;c;c=c.parent)if(c.resolved?.dragTags!=null){a=c.resolved.dragTags;break}let l=this.#r={record:t,wires:i,effectAllowed:s,phase:"active",tags:[a,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[c,u]of i)e.dataTransfer.setData(c,u);e.dataTransfer.effectAllowed=s,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.#c(l,n.element,e.dataTransfer),l.release=this.#e.onDispose(t.node,()=>this.#b("none"))}catch(r){e.preventDefault(),this.#g(),this.#w(r)}}}#c(e,t,r){let n=t.cloneNode(!0);n.removeAttribute("id");for(let i of n.querySelectorAll("[id]"))i.removeAttribute("id");n.setAttribute("aria-hidden","true"),n.classList.add(...(e.record.resolved.dragClass??"draggedItem").split(/\s+/).filter(Boolean)),Object.assign(n.style,{position:"fixed",left:"-10000px",top:"0",width:`${t.getBoundingClientRect().width}px`,pointerEvents:"none"}),t.parentNode.append(n),e.preview=n,r.setDragImage(n,0,0)}#u(e){let t=this.#r,r=this.#s(e,c=>er.isTarget(c));if(!r)return null;let n=this.#a(r,e);if(!n)return{record:r,element:r.element,accepted:!1};let i=er.evaluate([...t.wires.keys()],t.tags,t.effectAllowed,r.resolved),a={dropValues:Object.fromEntries(i.types.map(c=>[c,c.startsWith("text/")?t.wires.get(c):j(t.wires.get(c))])),item:n.item,path:n.path,source:{...t.source},selfdrop:r===t.record,dropEffect:i.dropEffect,dataAvailable:!0};n.placement!==void 0&&(a.placement=n.placement);let l=i.accepted&&this.#e.checkDropTarget(r.node,a)&&this.#e.records.get(r.node)===r&&n.element.isConnected;return{record:r,element:n.element,accepted:l,context:a}}#d(e){if(!this.#r){this.#s(e,t=>er.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.#u(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.#s(e,n=>er.isTarget(n))&&e.preventDefault();return}if(e.preventDefault(),this.#r.phase!=="active")return;let t=this.#r,r;try{if(r=this.#u(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(n){this.#r===t&&(t.phase="rejected",this.#m()),(!r||this.#e.records.has(r.record.node))&&this.#w(n)}}#p(e,t){let r=t?"canBeDropped":"cannotBeDropped",n=(e.getAttribute("part")??"").split(/\s+/).filter(Boolean);this.#n={element:e,name:r,hadClass:e.classList.contains(r),hadPart:n.includes(r)},e.classList.add(r),n.includes(r)||e.setAttribute("part",[...n,r].join(" "))}#h(){if(!this.#n)return;let{element:e,name:t,hadClass:r,hadPart:n}=this.#n;r||e.classList.remove(t),n||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 Ff)this.#t.removeEventListener(e,this);this.#t.defaultView.removeEventListener("pagehide",this.#i)}};var Io=class extends Sr{static renderType="object";#e=new Set;#t=new WeakSet;#r=new WeakMap;#n=new WeakMap;#o=new WeakMap;constructor(e,t,r,{binding:n}={}){if(super(e),!(e instanceof Ae)||!(t instanceof de)||r?.nodeType!==1)throw new TypeError("GramlotRenderer requires a BuilderBase, GramlotBuilderBag and HTML destination");if(!(n instanceof gn))throw new TypeError("GramlotRenderer requires a BindingRuntime");if(!(t._builder instanceof Ae))throw new TypeError("SourceBag requires builder ownership");this._binding=n,this.source=t,this.destination=r,this.html=new Zi({uploadContext:()=>({gramlot:n.gramlot,window:r.ownerDocument.defaultView}),metadataAttributes:["__ref"],format:(i,s)=>n.gramlot.format(i,s),reportError:(i,s,a)=>{this.records.has(i)&&n.reportError(s,a)},callLogic:(i,s,a)=>{let{group:l,method:c}=n.gramlot.src.logicRegistry.resolve(s,i);return c.call(l,i,a)},invokeScript:(i,s,a,l)=>dt(n,i,s,a,l,i.parentNode._getMeta("gramlot_component").childParameters[s].inline)}),this.records=new Map,this.references=new Jn(t),this.pending=[],this.building=!1,this.disposed=!1,this.elements=new WeakMap,this.dragPreparation=new ws(this),this.instanceId=G(),this.radioGroups=new Yi(this),this.dragDrop=new _s(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:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,placement:c}){let u=this.records.get(e);if(!u)return!1;if(!u.resolved.dropTargetCb)return!0;let d=this.html.callLogic(e,u.resolved.dropTargetCb,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,...c===void 0?{}:{placement:c}});if(typeof d!="boolean")throw new TypeError("dropTargetCb must return a boolean synchronously");return d}async invokeDrop(e,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,placement:c}){let u=this.records.get(e);!u||!u.resolved.onDrop||Object.keys(t).length===0||await this.html.callLogic(e,u.resolved.onDrop,{dropValues:t,item:r,path:n,source:i,selfdrop:s,dropEffect:a,dataAvailable:l,...c===void 0?{}:{placement:c}})}async endDrag(e,{source:t,dropEffect:r},n){let i={source:t,dropEffect:r},s=[],a=this.records.get(e);try{a&&!a.binding.closed&&a.resolved.onDragEnd&&await this.html.callLogic(e,a.resolved.onDragEnd,i)}catch(l){s.push(l)}try{this.binding.gramlot.publish(n,i)}catch(l){s.push(l)}if(s.length)throw new AggregateError(s,"Drag completion notification failed")}get inlineCompiler(){return this.binding.inlineCompiler}evaluateExpressions(e,t){let r=this.#n.get(e)??super.evaluateExpressions(e,t),n=e._getMeta("gramlot_component");if(n?.presentationDefaults.length){let i=e.getAttr();this.#o.set(e,Object.fromEntries(Object.entries(r).filter(([s])=>Object.hasOwn(i,s)&&n.presentationDefaults.some(a=>s.startsWith(a)))))}if(this.html.hasLabelbox(e)||n?.presentationDefaults.length){let i=[];for(let s=e.parentNode;s;s=s.parentNode)this.#o.has(s)&&i.unshift(this.#o.get(s));r=Object.assign({},...i,r)}return this.#n.delete(e),this.#r.set(e,r),r}render(e,t={}){if(!(e instanceof Tr))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 N))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 n=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(n,i),n.append(i.start);for(let s of e.value.getNodes()){let a=this.render(s,{document:t,...r});if(a===null)continue;n.append(a);let l=this.elements.get(a);l&&(l.parent=i,i.children.add(s))}return n.append(i.end),n}renderedItem(e,t,r,{tag:n,document:i=this.destination.ownerDocument}={}){let s=r;t=this.expressionValue(e,t),this.getRender(e.builder)===this&&(s=this.restoreNativeAttributes(e,r),e._getMeta("gramlot_component")||([t,s]=un(t,s,(h,p)=>this._binding.gramlot.format(h,p)))),s=this.componentAttributes(e,s);let a=Array.isArray(t)?t:[],l=Array.isArray(t)?s._text:t,c=this.#r.get(e),u={node:e,binding:this.#m(e),container:null,parent:null,children:new Set,cleanup:[],resolved:c,...this.html.create(e,i,n,s,c.visible??null)};this.html.compose(u,l,a),u.labelbox&&u.cleanup.push(()=>u.labelbox.menu?.dispose()),u.shape=ve.shape(u.element,c),this.records.set(e,u),this.elements.set(u.element,u),this.elements.set(u.presentation,u);let d=ve.for(u.binding,u);(d||u.element.namespaceURI===be&&u.element.localName==="input")&&u.cleanup.push(()=>u.control?.detach()),d&&(u.control=d,d.attach(),this.#f(u,e,s,null));let f=Ki.for(u.binding,u);if(f&&(u.button=f,f.attach(),u.cleanup.push(()=>f.detach())),e.nodeTag==="menu"&&(u.menu=new Ji(u.binding,u.element),u.menu.attach(),u.cleanup.push(()=>u.menu.detach())),e.nodeTag==="groupletCard"){let h=new Qi(u.binding,u.element);h.attach(),u.cleanup.push(()=>h.detach())}this.#p(u),this.references?.register(e,u.element);for(let h of a){let p=this.elements.get(h);p&&(p.parent=u,p.container=u.element,u.children.add(p.node))}return u.presentation}validateCandidate(e,{replacingNode:t=null}={}){if(!(e instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");let r=new Set,n=a=>{if(!r.has(a)){r.add(a);for(let l of this.records.get(a)?.children??[])n(l);if(a.value instanceof N)for(let l of a.value.getNodes())n(l)}};for(let a of this.records.get(t)?.children??[])n(a);if(t?.value instanceof N)for(let a of t.value.getNodes())n(a);this.#i(e,t?t.nodeTag:null),nc(e),this.references?.validate(e,r);let i=new Set,s=a=>{for(let l of a.getNodes()){let c=l.getAttr("nodeId");if(c!=null){let u=this.binding.nodeIds.get(c);if(i.has(c)||u&&u!==l&&!r.has(u))throw new Error(`Duplicate nodeId '${c}'`);i.add(c)}l.value instanceof N&&s(l.value)}};return s(e),e}#i(e,t=null){let r=new Set,n=(i,s=null)=>{if(!(i instanceof de)||r.has(i))throw new TypeError("Source values must be unshared, acyclic GramlotBuilderBags");if(!(i._builder instanceof Ae))throw new TypeError("SourceBag requires builder ownership");r.add(i);for(let a of i.getNodes()){if(!(a instanceof Tr))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(!(a.builder instanceof Ae))throw new TypeError("SourceBagNode requires builder ownership");if(a.resolver)throw new TypeError("Source resolvers are outside this port");if(a._getMeta("data_element"))a.builder.validateNode(a);else if(a.nodeTag){let l=a._getMeta("subbuilder")?i._builder:a.builder;this.html.validate(a,l),a._getMeta("subbuilder")||a.builder.validateParent(a.nodeTag,s)}else{if(!(a.value instanceof N))throw new TypeError("Source fragments must contain child SourceBags");if(Object.keys(a.attr).some(l=>l!=="_meta"))throw new TypeError("Fragment attributes are unsupported")}a.value instanceof N&&n(a.value,a._getMeta("subbuilder")?null:a.nodeTag??s)}};n(e,t)}freeze(e){e=Z(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=Z(e);let t=this.records.get(e);if(!t||this.disposed)throw new Error("Unfreeze requires a mounted Source node");let r=n=>{delete n.frozen;for(let i of n.children)r(this.records.get(i))};r(t),!this.#s(e)&&(this.attached(e)?this.#g(e):this.remove(e))}#s(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(n=>!t(n));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.#c(r);let n=this.binding.handleSourceEvent(r);try{this.#a(r,n)}catch(i){if(!n.length)throw i;n.push(i)}if(this.binding.refreshSourceTrees(),n.length)throw n.length===1?n[0]:new AggregateError(n,"Source cleanup failed")}}catch(r){throw this.pending.length=0,r}finally{this.building=!1}}}#a(e,t){if(e.evt==="del"){for(let r of Array.isArray(e.node)?e.node:[e.node]){if(this.#s(r))continue;let n=this.records.get(r)?.parent??null;try{this.remove(r)}catch(i){t.push(i)}this.#h(n)}return}if(!this.#s(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}#c(e){let t=r=>{if(!(r instanceof Tr))throw new TypeError("Source children must be GramlotBuilderBagNodes");if(r.value instanceof N){if(!(r.value instanceof de))throw new TypeError("Source values must be GramlotBuilderBags");for(let n of r.value.getNodes())t(n)}};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 s=e;s;s=s.parentNode)if(this.#t.has(s))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,n=e.parentBag.getNodes(),i=t?.end??null;for(let s=n.indexOf(e)+1;s<n.length;s++){let a=this.records.get(n[s]);if(a){i=a.presentation??a.start;break}}this.buildNode(e,r,i,t)}buildNode(e,t,r=null,n=null){this.#e.add(e);let i;try{i=this.render(e,{document:t.ownerDocument})}catch(a){this.#u(e,a)}finally{this.#e.delete(e)}let s=this.records.get(e);return t.insertBefore(i,r),s.parent=n,this.assignContainer(s,t),n?.children.add(e),this.#h(n),this.binding.branchBuilt(e),s}#u(e,t){let r=[t],n=[],i=s=>{if(n.push(s),s.value instanceof N)for(let a of s.value.getNodes())i(a)};i(e);for(let s of n.reverse())try{this.remove(s)}catch(a){r.push(a)}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 n=r.parent;return this.remove(e),this.buildNode(e,t,null,n)}assignContainer(e,t){e.container=t;let r=e.element??t;for(let n of e.children){let i=this.records.get(n);i&&this.assignContainer(i,r)}}update(e,t){let r=this.records.get(e);if(!r){this.insert(e);return}let n=e.value==null||["string","number","boolean"].includes(typeof e.value),i=t==="upd_value"&&n&&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 n=this.getRender(e.builder),i=this.#o.get(e),[s,a]=e.rootBuilder.runtimeValues(e),[,l]=n._handleMeta(e,a),c=this.#r.get(e),u=r.element.namespaceURI===be&&r.element.localName==="input"&&!Object.is(r.resolved.type,c.type),d=r.element.namespaceURI===be&&["input","select"].includes(r.element.localName)&&!!r.resolved.multiple!=!!c.multiple,f=r.resolved.group,h=r.control instanceof dn&&!Object.is(f??null,c.group??null);if((u||d||h)&&this.#s(e))return;if(r.shape!==ve.shape(r.element,c)){if(this.#s(e))return;this.#n.set(e,c);try{this.#g(e)}finally{this.#n.delete(e)}return}let p=u?ve.classFor(r.element,c):null,m=u&&(r.control?.constructor??null)!==p,b=(u||d&&r.element.localName==="input")&&!m&&r.control&&Object.is(r.resolved.value,c.value);if(m&&(r.control?.detach(),r.control=null),h&&!m&&c.group!=null&&e.getAttr("name")!=null)throw new TypeError(`${e.nodeTag} '${e.label}': name and group are two names`);r.resolved=c;let w=e._getMeta("subbuilder")?l:n.adaptAttrs(l),_=e.value instanceof N,v=_?[]:this.expressionValue(e,s);if(n===this&&(w=this.restoreNativeAttributes(e,w),e._getMeta("gramlot_component")||([v,w]=un(v,w,(D,k)=>this._binding.gramlot.format(D,k)))),w=this.componentAttributes(e,w),this.html.update(r,e,w,_?w._text:v,c.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 E=this.#o.get(e);if(E){let D=new Set([...Object.keys(i??{}),...Object.keys(E)].filter(k=>!Object.is(i?.[k],E[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 N)for(let r of e.value.getNodes()){let n=r._getMeta("gramlot_component"),i=r.getAttr(),s=t;n?.presentationDefaults.length?s=new Set([...t].filter(a=>!Object.hasOwn(i,a))):this.html.hasLabelbox(r)&&[...t].some(a=>!Object.hasOwn(i,a))&&this.project(r),s.size&&this.#d(r,s)}}componentAttributes(e,t){let r=e._getMeta("gramlot_component"),n=e.parentNode?._getMeta("gramlot_component")?.childParameters;if(!r&&!n)return t;let i=this.#r.get(e),s=Object.fromEntries([...new Set([...Object.keys(r?.parameters??{}),...Object.keys(n??{}),...Object.keys(i).filter(a=>a.startsWith("validate_"))])].filter(a=>Object.hasOwn(i,a)).map(a=>[a,i[a]]));return{...t,...s}}#f(e,t,r,n){if(!e.control)return;let i=t.getAttr("value")!=null;(i||e.valueDeclared)&&e.control.project(r.value??null,n),e.valueDeclared=i}#p(e){let t=new Map(ho.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,n]of[...e.events])t.get(r)?.[2]!==n.handler&&(n.detach(),e.events.delete(r));for(let[r,[,n,i]]of t){if(e.events.has(r))continue;let s=new ho(e.binding,e,n,i,r);s.attach(),e.events.set(r,s)}}#h(e){for(let t=e;t;t=t.parent){if(t.control instanceof fo){this.project(t.node);return}if(t.element&&t.element.localName!=="optgroup")return}}getDomNode(e){let t=Z(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,n=t.container,i=t.parent,s=null;try{this.remove(e)}catch(a){s=a}try{this.buildNode(e,n,r,i)}catch(a){throw s?new AggregateError([s,a],"Source replacement cleanup and commit failed"):a}if(s)throw s}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 n=r.cleanup.indexOf(t);n!==-1&&r.cleanup.splice(n,1)}}remove(e){let t=this.records.get(e);if(!t)return;let r=[];for(let n of[...t.children])try{this.remove(n)}catch(i){r.push(i)}for(let n of t.cleanup.splice(0).reverse())try{n()}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(n){e.push(n)}if(e.length)throw new AggregateError(e,"Renderer cleanup failed")}};var Wb=new Set(["page","constructor"]);function zf(o,e){if(o===null)return[];let t=o.split("/");for(let r of t)if(Wb.has(r))throw new Error(`${e}: a logic group cannot be named '${r}' (group '${o}')`);return t}var Gb=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]);function Hb(o){return/^[\w$]/.test(o)?Gb.has(o):o!==")"&&o!=="]"}function Xb(o,e){let t=!1;for(let r=e+1;r<o.length;r++){let n=o[r];if(n===`
|
|
229
|
+
`)return-1;if(n==="\\"){r++;continue}if(n==="[")t=!0;else if(n==="]")t=!1;else if(n==="/"&&!t)return r}return-1}function Yb(o){let e=0,t="",r="";for(let n=o.indexOf("{");n<o.length;n++){let i=o[n];if(i==="/"&&o[n+1]==="/"){if(n=o.indexOf(`
|
|
230
|
+
`,n),n<0)break;continue}if(i==="/"&&o[n+1]==="*"){let s=o.indexOf("*/",n+2);if(s>=0){n=s+1;continue}}if(i==="/"&&Hb(r)){let s=Xb(o,n);if(s>=0){n=s,r=")";continue}}if(i==='"'||i==="'"||i==="`"){let s=n+1;for(;s<o.length&&o[s]!==i;)s+=o[s]==="\\"?2:1;e===1&&(t+=o.slice(n+1,s)==="constructor"?" constructor":' ""'),n=s,r=")";continue}if(/[\w$]/.test(i)){let s=n+1;for(;s<o.length&&/[\w$]/.test(o[s]);)s++;e===1&&(t+=o.slice(n,s)),r=o.slice(n,s),n=s-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 qf(o,e){if(o===void 0)return[];if(typeof o!="function"||!/^class\b/.test(Function.prototype.toString.call(o)))throw new Error(`${e}: the module exports no class Logic`);if(Object.getPrototypeOf(o)!==Function.prototype||Object.getPrototypeOf(o.prototype)!==Object.prototype)throw new Error(`${e}: class Logic cannot extend another class`);if(Yb(Function.prototype.toString.call(o)))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(o.prototype)){if(r==="constructor")continue;if(typeof r=="symbol")throw new Error(`${e}: class Logic cannot declare symbol keys (${String(r)})`);let n=Object.getOwnPropertyDescriptor(o.prototype,r);if(n.get||n.set)throw new Error(`${e}: class Logic cannot declare the accessor '${r}'`);if(typeof n.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,n.value])}return t}function Uf(o,e,t){Object.defineProperty(o,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}var $r=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get page(){return this.#t}},bn=class{#e;#t=new Map;constructor(e){this.#e=e,e.logic=new $r(this,e)}get gramlot(){return this.#e}static check(e){let t=new Map;for(let{group:r,resource:n}of e){let i=zf(r,n);for(let s=0;s<i.length;s++){let a=i.slice(0,s).join("/");t.has(a)||t.set(a,new Set),t.get(a).add(i[s])}}for(let{logicClass:r,group:n,resource:i}of e){let s=t.get(n??"")??new Set;for(let[a]of qf(r,i))if(s.has(a))throw new Error(`${i}: the logic method '${a}' has the name of a child group`)}}register(e,{group:t=null,resource:r}){let n=zf(t,r),i=qf(e,r),s=this.#e.logic;for(let a of n){let l=Object.getOwnPropertyDescriptor(s,a)?.value;if(l===void 0){let c=new $r(this,this.#e);Uf(s,a,c),s=c}else if(l instanceof $r)s=l;else throw new Error(`${r}: the group '${a}' has the name of a logic method`)}for(let[a,l]of i){if(Object.getOwnPropertyDescriptor(s,a)?.value instanceof $r)throw new Error(`${r}: the logic method '${a}' has the name of a child group`);Uf(s,a,l)}this.#t.has(s)||this.#t.set(s,[]),this.#t.get(s).push(r)}resolve(e,t){let r=e.split("."),n=r.pop(),i=this.#e.logic;for(let a=0;a<r.length;a++)if(i=Object.getOwnPropertyDescriptor(i,r[a])?.value,!(i instanceof $r))throw new Error(`${t.nodeTag} '${t.label}': named logic '${e}' not found: no resource was registered for the group '${r.slice(0,a+1).join("/")}'`);let s=Object.getOwnPropertyDescriptor(i,n)?.value;if(typeof s!="function"){let a=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 '${n}' (resources: ${a.join(", ")||"none"})`)}return{group:i,method:s}}};var Co=class extends Ne{constructor(e,{collections:t,destination:r,subscriptions:n,nameSyntax:i}){super(e),e.src=this,this.logicRegistry=new bn(e),this.builder=new me(null,{collections:t,nameSyntax:i}),this.binding=new gn(e,{subscriptions:n}),this.builder.binding=this.binding,this.binding.attach(),this.source=this.builder.source,this.renderer=new Io(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 x)||t instanceof N)throw new TypeError("Initial page data must be a Data Bag");for(let n of t.getNodes())this.builder.data.setItem([n.label],n.getValue(),n.attr,">",!1,!1)}try{this.source.setItem("main",r)}catch(n){throw this.binding.bindingFor(this.source.getNode("main"))||this.source.popNode("main"),n}return this.gramlot.state="started",this.binding.pageStarted(),this.binding.subscriptions.ready(),this.gramlot}prepareSource(e,t=this.builder){if(e instanceof N){if(!(e instanceof de))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=Ri(e,t);if(!(r instanceof de))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,s=>this.#e(e,i,s))??!1}async#e(e,t,r){if(t.closed||this.gramlot.state==="disposed")return!1;let n=!1,i=()=>this.gramlot.state!=="disposed"&&!r.ignored&&!t.closed;try{let s=await t.call("source",r);if(!i())return!1;let a=this.prepareSource(s,e.builder);return i()?(this.renderer.validateCandidate(a,{replacingNode:e}),n=!0,e.setValue(a,!0,{_text:null},!0),t.remote?.fragmentMounted(r.method,r.text),!0):!1}catch(s){if(!n&&!i())return!1;throw s}}};var Do=class extends Ne{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 ys=class extends Ne{#e=new Map;#t=new WeakSet;#r=new WeakMap;#n=0;#o=!1;ready(){this.gramlot._frames.ready()}subscribe(e,t){if(this.#a(),this.#s(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.#a(),!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(s=>!["topic","nodeId","parent","iframe","pageId","server"].includes(s)))throw new Error("This publication route is not implemented yet");if(this.#s(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(s=>Object.hasOwn(e,s)))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 s=this.gramlot.src.binding.nodeIds.get(e.nodeId);if(!s)throw new Error(`nodeId not found: ${e.nodeId}`);return this.publishNode(s,e.topic,t)}return this.#i(e.topic,t),i?.()}topicFor(e,t){this.#s(t),e=Z(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 n=e.getAttr("nodeId");return n==null&&(this.#r.has(e)||this.#r.set(e,`gramlot-self-${++this.#n}`),n=this.#r.get(e)),`${n}_${t}`}publishNode(e,t,r={}){return this.publish(this.topicFor(e,t),r)}subscribeNode(e,t){let r=[];for(let[n,i]of Object.entries(e.getAttr())){let s=n.startsWith("selfsubscribe_")?"selfsubscribe_":n.startsWith("subscribe_")?"subscribe_":null;if(!s)continue;let a=s==="selfsubscribe_"?this.topicFor(e,n.slice(s.length)):n.slice(s.length);this.#s(a),r.push([a,t(n,i,a)])}return this.#a(),r.map(([n,i])=>{let s=this.subscribe(n,i);return{close:()=>this.unsubscribe(s)}})}dispose(){this.#o=!0,this.#e.clear()}#i(e,t,r={}){this.#s(e);let n=this.#e.get(e);if(n)for(let[i,s]of[...n]){if(this.#o)break;n.has(i)&&s(t,{...r})}}#s(e){if(typeof e!="string"||!e)throw new TypeError("A topic must be a nonempty string")}#a(){if(this.#o)throw new Error("Gramlot subscriptions are disposed")}};var vs=class extends Y{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 Vf=["appinfo","location"],Wf={UNAVAILABLE:"unavailable",PERMISSION_DENIED:"denied",TIMEOUT:"error",FAILED:"error",CANCELLED:"cancelled"};function K(o){let e=Object.hasOwn(Wf,o?.code)?o.code:"FAILED";return{status:Wf[e],error:e==="CANCELLED"?null:{code:e,message:String(o?.message??"Device operation failed")}}}var No=class extends Ne{#e=null;#t=null;#r=null;#n=null;#o=null;#i=null;#s=new Map;#a=new Map;#l=null;#c=null;#u=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.#a.set(m,{node:e.data.getNode(`_gramlot.device.${m}`),stream:null,cleanup:Promise.resolve()});for(let m of Vf){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 v=new vs(this,m,w.cacheTime);_.resolver=v,this.resolvers.set(m,v)}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 n=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"),s=new x;s.setItem("request",new x);for(let m of["scheduled","received","action"])s.setItem(m,null);e.data.setItem("_gramlot.device.notifications",s,{status:"idle",error:null,schedule:null,listening:!1,listenerError:null});let a=e.data.getNode("_gramlot.device.notifications"),l=new x;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 c=e.data.getNode("_gramlot.device.push"),u=new x;u.setItem("request",null),e.data.setItem("_gramlot.device.links",u,{listening:!1,listenerError:null});let d=new x;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 x;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.#a)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.#E(h),m.node===h&&m.fired&&m.attrs_diff?.vibrate?.new===!0&&this.#x(h),m.node===n&&m.fired&&m.attrs_diff?.scan?.new===!0&&this.#I(n),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===a&&m.fired&&m.attrs_diff?.schedule?.new===!0&&this.#D(a),m.node===c&&m.fired&&m.attrs_diff?.register?.new===!0&&this.#O(c);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=>![...Vf,"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,n)=>e.startOrientationEvents(r,n),(r,n)=>{if(!["portrait","landscape"].includes(n?.type)||!["primary","secondary"].includes(n.direction)||!Number.isFinite(n.timestamp))throw new TypeError("Invalid screen orientation from device provider");let i=new x;for(let s of["type","direction","timestamp"])i.setItem(s,n[s]);r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("network",(r,n)=>e.startNetworkEvents(r,n),(r,n)=>{if(typeof n?.connected!="boolean"||!["none","unknown","wifi","cellular"].includes(n.type))throw new TypeError("Invalid network state from device provider");let i=new x;i.setItem("connected",n.connected),i.setItem("type",n.type),r.setValue(i,!0,{status:"success",error:null},!0,!1)}),this.#m("lifecycle",(r,n)=>e.startLifecycleEvents(r,n),(r,n)=>{if(n?.kind==="state"&&typeof n.active=="boolean")r.staticValue.setItem("active",n.active);else if(n?.kind==="pause"||n?.kind==="resume")r.staticValue.setItem("event",n.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.#R(this.gramlot.data.getNode("_gramlot.device.links")),e.capabilities.includes("shortcuts")&&this.#$(this.gramlot.data.getNode("_gramlot.device.shortcuts")),e.capabilities.includes("push")&&this.#A(this.gramlot.data.getNode("_gramlot.device.push")),e.capabilities.includes("notifications")&&this.#S(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(n=>{this.disposed||t.request!==r||(this.accept(t,n),t.revision!==r.revision&&(t._lastUpdate=null))}).catch(n=>{!this.disposed&&t.request===r&&t.received===r.received&&this.failure(t,n)}).finally(()=>{t.request===r&&(t.request=null)})}#m(e,t,r){let n=this.gramlot.data.getNode(`_gramlot.device.${e}`);if(!this.provider.capabilities.includes(e)){n.setAttr(K({code:"UNAVAILABLE",message:`${e} is unavailable`}),!0,!0,!1);return}let i={controller:new AbortController};this.#s.set(e,i),n.setAttr({status:"pending",error:null},!0,!0,!1),i.start=Promise.resolve().then(()=>i.controller.signal.aborted?async()=>{}:t(s=>{if(!i.controller.signal.aborted)try{r(n,s)}catch(a){n.setAttr(K(a),!0,!0,!1)}},i.controller.signal)).then(s=>(i.controller.signal.aborted||n.setAttr({listening:!0},!0,!0,!1),s)),i.start.catch(s=>{let a=i.controller.signal.aborted;i.controller.abort(),a||n.setAttr({...K(s),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(s=>s(),()=>{}).then(()=>{!this.disposed&&!t.stream&&r.setAttr({watching:!1,status:"idle",error:null},!0,!0,!1)}),t.cleanup.catch(s=>{this.disposed||r.setAttr(K(s),!0,!0,!1)});return}if(t.stream)return;let n={controller:new AbortController};t.stream=n,n.start=t.cleanup.then(()=>{if(n.controller.signal.aborted)return async()=>{};this.requireCapability(e);let i=s=>{if(!(this.disposed||n.controller.signal.aborted))try{if(s?.kind==="state"&&typeof s.watching=="boolean")r.setAttr({watching:s.watching,status:s.watching?"pending":"idle",error:null},!0,!0,!1);else if(s?.kind==="sample"){for(let l of["x","y","z","timestamp"])if(!Number.isFinite(s[l]))throw new TypeError(`Invalid ${e}.${l}`);if(!r.attr.watching||r.staticValue&&s.timestamp<r.staticValue.getItem("timestamp"))return;let a=new x;for(let l of["x","y","z","timestamp"])a.setItem(l,s[l]);r.setValue(a,!0,{status:"success",error:null},!0,!1)}else if(s?.kind==="error"&&s.error instanceof Error)r.setAttr({...K(s.error),watching:!1},!0,!0,!1);else throw new TypeError(`Invalid ${e} event`)}catch(a){r.setAttr(K(a),!0,!0,!1)}};return e==="gyroscope"?this.provider.startGyroscopeUpdates(i,n.controller.signal):this.provider.startAccelerometerUpdates(i,n.controller.signal)}),n.start.catch(i=>{!this.disposed&&!n.controller.signal.aborted&&r.setAttr({...K(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(n=>n.dispose()).then(()=>{this.disposed||t.controller.signal.aborted||this.#n!==t||(this.#n=null,this.#b(e))}).catch(n=>{!this.disposed&&this.#n===t&&(t.phase="failed",e.setAttr(K(n),!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(n=>{this.#n===r&&!r.controller.signal.aborted&&this.#y(e,n)},r.controller.signal))),r.start.then(n=>{!n||r.controller.signal.aborted||this.disposed||(r.phase="recording",e.setAttr({status:"recording",error:null,recording:!0},!0,!0,!1))}).catch(n=>{r.controller.signal.aborted||this.disposed||(this.#n===r&&(this.#n=null),e.setAttr({...K(n),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 n=new x;for(let i of["url","mimeType","duration"])n.setItem(i,r[i]);t.phase="complete",e.setValue(n,!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=K(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 n=K(r);e.setAttr({shareStatus:n.status,shareError:n.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(n=>n===null?void 0:n.dispose(),n=>{if(n?.code!=="CANCELLED")throw n}).then(()=>{this.disposed||this.#n!==r||(this.#n=null,e.setAttr({...K(t),recording:!1},!0,!0,!1))}).catch(n=>{!this.disposed&&this.#n===r&&(r.phase="failed",e.setAttr(K(n),!0,!0,!1))}))}#v(e,t){if(this.#t)return;let r=new AbortController;this.#t=r;let n=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 n!="string")throw new TypeError("Clipboard text must be a string");await this.provider.copyText(n,r.signal),i={text:n}}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 s=new x;s.setItem("text",i.text),e.setValue(s,!0,{status:"success",error:null},!0,!1)}).catch(i=>{r.signal.aborted||e.setAttr(K(i),!0,!0,!1)}).finally(()=>{this.#t===r&&(this.#t=null)})}#x(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 n=new x;n.setItem("duration",r),n.setItem("acknowledged",!0),e.setValue(n,!0,{status:"success",error:null},!0,!1)}).catch(n=>{t.signal.aborted||e.setAttr(K(n),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#E(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 n=new x;n.setItem("style",r),n.setItem("acknowledged",!0),e.setValue(n,!0,{status:"success",error:null},!0,!1)}).catch(n=>{t.signal.aborted||e.setAttr(K(n),!0,!0,!1)}).finally(()=>{this.#i===t&&(this.#i=null)})}#I(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 n=new x;n.setItem("text",r.text),n.setItem("format",r.format),e.setValue(n,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setAttr(K(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(n=>{if(r.signal.aborted)return;if(typeof n?.url!="string"||!n.url||typeof n.format!="string"||!n.format)throw new TypeError("Invalid camera photo from device provider");let i=new x;i.setItem("url",n.url),i.setItem("format",n.format),e.setValue(i,!0,{status:"success",error:null},!0,!1)}).catch(n=>{r.signal.aborted||e.setAttr(K(n),!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 x;r.setItem("verified",!0),e.setValue(r,!0,{status:"success",error:null},!0,!1)}).catch(r=>{t.signal.aborted||e.setValue(null,!0,K(r),!0,!1)}).finally(()=>{this.#l===t&&(this.#l=null)})}#S(e){if(this.#u)return this.#u.start;let t={controller:new AbortController};return this.#u=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 n=new x;for(let i of["id","title","body"])n.setItem(i,r[i]);r.kind==="action"&&n.setItem("actionId",r.actionId),e.staticValue.setItem(r.kind,n)}catch(n){e.setAttr({listenerError:K(n).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 n=t.controller.signal.aborted;t.controller.abort(),this.#u===t&&(this.#u=null),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)}),e.setAttr({listenerError:null},!0,!0,!1),t.start}#D(e){if(this.#c)return;let t=new AbortController;this.#c=t;let r=e.staticValue.getItem("request"),n=r instanceof x?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"),!n||!Number.isInteger(n.id)||n.id<1||n.id>2147483647||typeof n.title!="string"||!n.title.trim()||typeof n.body!="string"||!n.body.trim()||typeof n.delay!="number"||!Number.isFinite(n.delay)||n.delay<=0)throw new TypeError("Notification requires a positive 32-bit id, title, body and positive delay in seconds");if(await this.#S(e),!t.signal.aborted)return this.provider.scheduleNotification(n,t.signal)}}).then(i=>{if(t.signal.aborted)return;if(i?.id!==n.id||typeof i.at!="number"||!Number.isFinite(i.at))throw new TypeError("Invalid notification scheduling acknowledgement");let s=new x;s.setItem("id",i.id),s.setItem("at",i.at),e.staticValue.setItem("scheduled",s),e.setAttr({status:"success",error:null},!0,!0,!1)}).catch(i=>{t.signal.aborted||e.setAttr(K(i),!0,!0,!1)}).finally(()=>{this.#c===t&&(this.#c=null)})}#k(){let e=this.#d;return this.#d=null,e&&clearTimeout(e.timer),e}#N(e,t){if(t.kind==="registration"){if(typeof t.token!="string"||!t.token)throw new TypeError("Invalid push registration token");this.#k();let r=new x;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.#k(),e.staticValue.setItem("registration",null),e.setAttr(K(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 n=new x;for(let i of r){if(typeof t[i]!="string")throw new TypeError(`Invalid push event ${i}`);n.setItem(i,t[i])}e.staticValue.setItem(t.kind,n)}}#A(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.#N(e,r)}catch(n){e.setAttr({listenerError:K(n).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 n=t.controller.signal.aborted;t.controller.abort(),this.#f===t&&(this.#f=null),n||e.setAttr({listening:!1,listenerError:K(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.#k(),t.controller.abort(),e.setAttr(K({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.#A(e),!(t.controller.signal.aborted||this.#d!==t)&&await this.provider.registerPush(t.controller.signal))}).catch(r=>{this.disposed||this.#d!==t||(this.#k(),t.controller.abort(),e.setAttr(K(r),!0,!0,!1))})}#$(e){let t={controller:new AbortController};this.#p=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startShortcutEvents((r,n=null)=>{if(!t.controller.signal.aborted)try{if(n)throw n;for(let s of["id","destination"])if(typeof r?.[s]!="string"||!r[s])throw new TypeError(`Invalid shortcut request ${s}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new x;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:K(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 n=t.controller.signal.aborted;t.controller.abort(),n||e.setAttr({listening:!1,listenerError:K(r).error},!0,!0,!1)})}#R(e){let t={controller:new AbortController};this.#h=t,t.start=Promise.resolve().then(()=>t.controller.signal.aborted?async()=>{}:this.provider.startLinkEvents((r,n=null)=>{if(!t.controller.signal.aborted)try{if(n)throw n;for(let s of["id","url"])if(typeof r?.[s]!="string"||!r[s])throw new TypeError(`Invalid link request ${s}`);if(e.staticValue.getItem("request")?.getItem("id")===r.id)return;let i=new x;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:K(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 n=t.controller.signal.aborted;t.controller.abort(),n||e.setAttr({listening:!1,listenerError:K(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"],n=e.name==="appinfo"?"string":"number";for(let l of r)if(typeof t[l]!==n||n==="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 s=new x;for(let l of r)s.setItem(l,t[l]);e._lastUpdate=Date.now(),e.failed=!1,e.received++;let a=e.writing;e.writing=!0;try{e._node.setValue(s,!0,{status:"success",error:null},!0,!1)}finally{e.writing=a}}failure(e,t){e.failed=!0,this.attributes(e,K(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,n)=>{if(!(this.disposed||this.monitor!==t))if(n)this.failure(e,n);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,s=null)=>{this.disposed||t.setAttr({status:i,error:s},!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 n={controller:new AbortController,close:null,start:null};this.#e=n,r("pending"),n.start=this.provider.openDatabase(e,n.controller.signal);try{let i=await n.start,s=!1,a=null,l=()=>a||(s=!0,a=i.close().then(()=>{r("closed")},u=>{throw r("error",{code:"FAILED",message:u.message}),u}).finally(()=>{this.#e===n&&(this.#e=null)}),a);if(n.close=l,this.disposed||n.controller.signal.aborted)throw await l(),Object.assign(new Error("Page closed"),{code:"CANCELLED"});let c=async(u,d,f)=>{if(this.assertLive(),s)throw new Error("Database connection is closed");r("pending");try{let h=await i[u](d,f);return r("success"),h}catch(h){throw r("error",{code:"FAILED",message:h.message}),h}};return r("success"),{query:(u,d=[])=>c("query",u,d),execute:(u,d=[])=>c("execute",u,d),close:l}}catch(i){throw this.#e===n&&(this.#e=null),this.disposed||t.setAttr(K(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.#a.values()].map(u=>{let d=u.stream;return u.stream=null,d?.controller.abort(),d?d.start.then(f=>f(),()=>{}):u.cleanup});this.#t?.abort(),this.#t=null;let r=this.#n;this.#n=null,r?.controller.abort(),this.#i?.abort(),this.#i=null;let n=[...this.#s.values()];this.#s.clear();for(let u of n)u.controller.abort();let i=this.#h;this.#h=null,i?.controller.abort();let s=this.#p;this.#p=null,s?.controller.abort(),this.#k()?.controller.abort();let a=this.#f;this.#f=null,a?.controller.abort(),this.#o?.abort(),this.#o=null,this.#r?.abort(),this.#r=null,this.#l?.abort(),this.#l=null,this.#c?.abort(),this.#c=null;let l=this.#u;this.#u=null,l?.controller.abort(),this.gramlot.data.unsubscribe("gramlot.device",{any:!0});let c=this.monitor;if(this.monitor=null,c?.controller.abort(),c)this.cleanup=c.start.then(u=>u===null?void 0:u(),()=>{});else if(this.retiring?.stop){let u=this.retiring;this.cleanup=this.cleanup.catch(()=>u.stop())}l&&(this.cleanup=Promise.all([this.cleanup,l.start.then(u=>u(),()=>{})]).then(()=>{})),a&&(this.cleanup=Promise.all([this.cleanup,a.start.then(u=>u(),()=>{})]).then(()=>{})),i&&(this.cleanup=Promise.all([this.cleanup,i.start.then(u=>u(),()=>{})]).then(()=>{})),s&&(this.cleanup=Promise.all([this.cleanup,s.start.then(u=>u(),()=>{})]).then(()=>{})),this.cleanup=Promise.all([this.cleanup,...t,...n.map(u=>u.start.then(d=>d(),()=>{}))]).then(()=>{}),r&&(this.cleanup=Promise.all([this.cleanup,r.start.then(u=>u===null?void 0:u.dispose(),u=>{if(u?.code!=="CANCELLED")throw u})]).then(()=>{})),this.cleanup=this.cleanup.finally(()=>this.releaseProvider?.()),this.cleanup.catch(u=>{this.cleanupError=u});for(let u of this.resolvers.values())u.request=null}};var Gf=2e3;function Zb(o){if(!(o instanceof Date))return String(o??"");let e=o.toISOString();return e.endsWith("T00:00:00.000Z")?e.slice(0,10):e}var Oo=class{constructor(e,t){this.gramlot=e,this.document=t}branch(e){let t=this.gramlot.data.getItem(e);if(!(t instanceof x))throw new Error(`gramlot.utl.inout: no data Bag at '${e}'`);return t}mailText(e){let t=[],r=(n,i)=>{for(let s of n.getNodes()){let a=i+s.label;s.value instanceof x?r(s.value,`${a}.`):t.push(`${a}: ${Zb(s.value)}`)}};return r(this.branch(e),""),t.join(`
|
|
231
|
+
`)}mailtoUrl(e,t){let r=`mailto:${encodeURIComponent(t)}?subject=${encodeURIComponent(this.document.title)}&body=${encodeURIComponent(this.mailText(e))}`;if(r.length>Gf)throw new Error(`gramlot.utl.inout.sendMail: the email of '${e}' is ${r.length} characters long, over the mailto: limit of ${Gf}; 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)),n=await this.document.defaultView.fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:r});if(!n.ok)throw new Error(`gramlot.utl.inout.sendHttp: ${t} answered ${n.status}`);return n}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,n)=>{let i=()=>n(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 s=j(await t.files[0].text());if(!(s instanceof x))throw new TypeError("the file must contain a typed Bag");this.gramlot.data.setItem(e,s),r(s)}catch(s){n(new Error(`gramlot.utl.inout.restore: the file is not a saved Gramlot branch: ${s.message}`,{cause:s}))}},{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 n=this.branch(e);if(r==="json")this.saveText(n.toJson(!1),t,"application/json");else{let i=e.split(".").at(-1);this.saveText(`<?xml version='1.0' encoding='UTF-8'?>
|
|
232
|
+
<${i}>${n.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 n=this.document.defaultView,i=n.URL.createObjectURL(new n.Blob([e],{type:r}));this.open(i,t),n.setTimeout(()=>n.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 $o=class extends Ne{constructor(e,t){super(e),this.inout=new Oo(e,t)}};var Ro=class{#e;#t;constructor({pageId:e,uploadUrl:t=null,rpcUrl:r="/gramlot/rpc",closeUrl:n="/gramlot/close",rootId:i="gramlot-root",capabilities:s=[],element:a=null,document:l=a?.ownerDocument??globalThis.document,transport:c=null,collections:u=[],locale:d=null,timeZone:f=null,devices:h=[],serverAdapter:p=new Rt,nameSyntax:m=null,websocketUrl:b=null}={}){this.#t=[Vi,...u.filter(_=>_ instanceof Xt)],this.registerDocument(l),this.commands=new Dn,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 ys(this)}),this.capabilities=Object.freeze([...s]),this.serverAdapter=p,this.src=new Co(this,{collections:u,destination:a??l.getElementById(i),subscriptions:this._subscriptions,nameSyntax:m===null?eo:mr.fromJSON(m)}),this.#e=Cn.install({document:l,root:this.src.renderer.destination}),this.data=this.src.builder.data,this.dvc=new No(this),this.dom=new Do(this),this.utl=new $o(this,l),this.state="ready",this.abort=new AbortController,Object.defineProperty(this,"_frames",{value:new Bi(this,l)}),b!==null&&(this._pageStore=new Pi(this,b,l)),this.rpc=new Qn(this,{rpcUrl:r,closeUrl:n,document:l,transport:c}),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 oo(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 ic=class{constructor({config:e,resources:t,document:r=globalThis.document}){this.config=e,this.resources=t,this.document=r,this.serverAdapter=new Rt}async run(){let{config:e,resources:t,document:r}=this,n=r.defaultView;t.serverAdapter!==void 0&&(this.serverAdapter=await this.loadServerAdapter(t.serverAdapter));let i=!1,s,a,l=[],c=new Promise(d=>{s=d}),u=d=>{if(!(d.persisted||i)){i=!0;try{this.closePage()}finally{s(null)}}};n.addEventListener("pagehide",u);try{let d=t.css.map(_=>new Promise((v,E)=>{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(),v()},O=()=>{k(),E(new Error(`${_}: stylesheet load failed`))};D.addEventListener("load",C),D.addEventListener("error",O),r.head.append(D)})),f=t.js.map(async({url:_,group:v})=>{try{return{logicClass:(await import(new URL(_,r.baseURI).href)).Logic,group:v,resource:_}}catch(E){throw new Error(`${_}: import failed: ${E.message}`,{cause:E})}}),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:v,url:E,buildId:D}=_,k;try{k=await import(new URL(E,r.baseURI).href)}catch(C){throw new Error(`${v}: collection import failed: ${C.message}`,{cause:C})}if(k.default?.name!==v||k.buildId!==D)throw new Error(`${v}: 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)]),c]);if(i)return null;let[,b,w]=m;bn.check(b);for(let _ of w)_.register(n);a=new Ro({...e,document:r,serverAdapter:this.serverAdapter,collections:[...e.collections??[],...w]}),n.removeEventListener("pagehide",u);for(let _ of w)_.registerCommands(a);for(let{logicClass:_,group:v,resource:E}of b)a.src.logicRegistry.register(_,{group:v,resource:E});return n.gramlot=a,await a.start(),a}catch(d){throw a?a.dispose():i||this.closePage(),d}finally{for(let d of l)d();n.removeEventListener("pagehide",u)}}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"),ks=Symbol("gramlot.endpoint"),jo=Symbol("gramlot.upload"),Kb=new Map([[xs,"registerSource"],[ks,"registerEndpoint"],[jo,"registerUpload"]]);function sc(o,e,t,r){let n=Kb.get(t);if(e==="main")throw new TypeError(`${n} cannot declare main`);let i=Object.getOwnPropertyDescriptor(o.prototype,e)?.value;if(typeof i!="function")throw new TypeError(`${n} requires an own method of ${o.name}: ${String(e)}`);if(i[t])throw new TypeError(`${t===xs?"Source method":t===ks?"Endpoint":"Upload operation"} already registered: ${e}`);if([xs,ks,jo].some(s=>i[s])){let s=t!==jo&&!i[jo]?`${e} is declared both as Source method and endpoint`:`${e} has conflicting declarations`;throw new TypeError(s)}i[t]={auth:r}}var Es=class{static registerSource(e,{auth:t=null}={}){sc(this,e,xs,t)}static registerEndpoint(e,{auth:t=null}={}){sc(this,e,ks,t)}static registerUpload(e,{auth:t=null}={}){sc(this,e,jo,t)}},Po=class extends Es{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=me;main(e){throw new Error("Page.main(root) must be implemented")}};var wn=class extends Po{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 n of["top","bottom","left","right","center"])if(this[n]!==void 0){let i=r.contentPane({region:n,node_label:n});this[n](i)}this.behavior(t)}center(e){}behavior(e){}};var Bo=class extends wn{static title="Application";static shellId="index";static datapath="index";static navigation=null;main(e){let{navigation:t,datapath:r}=this.constructor;if(!(t instanceof x))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 x}),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})}};Bo.registerSource("index_panel");function ac(o,e,t=()=>{},r=()=>{},{state:n=e.getRelativeData("."),createEntry:i=null,onLoad:s=()=>{}}={}){let a=n.getItem("navigation");if(!(a instanceof x))throw new TypeError("IndexPage navigation must be a Bag");let l=e.value.getNode("frame.center.tabs"),c=e.builder,u=new Map,d={entries:u,disposed:!1,selecting:!1,sequence:0,requested:null};Object.defineProperty(e,"indexContext",{value:d,configurable:!0});let f=n.getItem("opened");for(let k of f.getNodes()){let{url:C,path:O,title:L}=k.attr,z=l.value.getNode(k.label),V={url:C,path:O,title:L,pane:z,node:a.getNode(O),loading:!1};r(V),u.set(C,V),d.sequence++}let h=(k,C,O)=>{try{s(k.url,C,O)}catch(L){o.binding.reportError(L,"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{n.setItem("active",k.url),n.setItem("navigationSelection",k.path),t(u,k.url)}finally{d.selecting=!1}}};function b(k){w(k).catch(C=>{d.disposed||o.binding.reportError(C,"Page could not be opened")})}async function w(k){let C=a.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 L=u.get(O);if(L){L.path=k,m(L);return}for(;l.value!==null&&l.value.getNode(`page${d.sequence}`);)d.sequence++;let z=Z(c.wrapSource(l).contentPane({node_label:`page${d.sequence++}`,title:C.attr.title??C.label,pageName:O,height:"100%",closable:!0})),V=n.getItem("active");L={url:O,path:k,node:C,pane:z,title:C.attr.title??C.label,loading:!0},u.set(O,L);try{if(h(L,"loading"),d.disposed||u.get(O)!==L||(m(L),d.disposed||u.get(O)!==L))return;if(i)await i(L);else{let le=new x;if(le.setItem(C.label,null,{...C.attr}),!await o.binding.gramlot.src.remoteSource(z,"index_panel",{selection:le}))throw new Error("Panel loading was cancelled")}if(d.disposed||u.get(O)!==L)return;f.setItem(z.label,null,{url:O,path:L.path,title:L.title}),r(L)}catch(le){if(d.disposed||u.get(O)!==L)return;try{if(o.binding.reportError(le,"Page could not be opened"),u.delete(O),f.getNode(z.label)&&f.popNode(z.label),z.parentBag&&z.parentBag.popNode(z.label),!d.disposed&&d.requested===O){let _e=u.get(V);if(d.requested=_e?.url??null,_e)m(_e);else{d.selecting=!0;try{n.setItem("active",null),n.setItem("navigationSelection",null),t(u,null)}finally{d.selecting=!1}}}}finally{p(L,"error",le)}return}d.disposed||u.get(O)!==L||(p(L,"ready"),!d.disposed&&u.get(O)===L&&d.requested===O&&m(L))}let _=`${e.getAttr("id")}-page-close`;e.value.subscribe(_,{any:k=>{if(k.evt!=="del")return;let C=[...u.values()].find(z=>z.pane===k.node);if(!C)return;let{url:O,pane:L}=C;if(!(d.disposed||o.disposed||u.get(O)!==C)){u.delete(O),f.getNode(L.label)&&f.popNode(L.label);try{if(n.getItem("active")===O){let z=[...u.values()].at(-1);if(d.requested=z?.url??null,z)m(z);else{d.selecting=!0;try{n.setItem("active",null),n.setItem("navigationSelection",null),t(u,null)}finally{d.selecting=!1}}}else t(u,n.getItem("active"))}finally{p(C,"cancelled")}}}});let v=`${e.getAttr("id")}-selection`;n.subscribe(v,{any:k=>{if(!(d.selecting||d.disposed)){if(k.node===n.getNode("navigationSelection")){let C=n.getItem("navigationSelection");C!==null&&b(C)}else if(k.node===n.getNode("active")){let C=u.get(n.getItem("active"));C&&(d.requested=C.url,m(C))}}}});let E=()=>{if(!d.disposed){d.disposed=!0,n.unsubscribe(v,{any:!0}),e.value.unsubscribe(_,{any:!0});for(let k of u.values())k.loading&&(k.pane.parentBag&&k.pane.parentBag.popNode(k.pane.label),p(k,"cancelled"));u.clear(),e.indexContext===d&&delete e.indexContext}};d.dispose=E,o.onDispose(e,E);let D=u.get(n.getItem("active"));return D?m(D):n.getItem("navigationSelection")!==null&&b(n.getItem("navigationSelection")),d}var Ts=class{indexMount(e){ac(this.page.src.renderer,e.parentNode)}};function Ss(o,{datapath:e,value:t,language:r="text",height:n="420px",...i}){if(!e)throw new TypeError("codeMirrorWithOptions requires datapath");let s=o.borderContainer({datapath:e,height:n,class:"gramlot-editor-options"}),a={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(a))s.dataSetter({destination_path:`.settings.${d}`,value:f});let l=s.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 c={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(c))l.checkbox({value:`^.settings.${d}`,label:f,display:"block",margin_top:"8px"});return s.contentPane({region:"center",min_height:0}).codeMirror({...i,value:t,height:"100%",...Object.fromEntries(Object.keys(a).map(d=>[d,`^.settings.${d}`]))}),s}var Mo=class o extends et{static internalParams=new Set([...et.internalParams,"gramlot","method","params","onError"]);#e=!1;#t=null;constructor({gramlot:e,root:t,path:r="",onError:n}){super({cacheTime:-1,onError:n}),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:n}=e,i,s=new Promise((a,l)=>{i=()=>l(n.reason),n.addEventListener("abort",i,{once:!0})});try{let a=await Promise.race([this.gramlot.rpc.call("data",t,r,{signal:n}),s]);if(n.aborted)throw n.reason;return a}finally{n.removeEventListener("abort",i),this.#t===e&&(this.#t=null)}}prepareValue(e){if(!(e instanceof x))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 o({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()}},Lo=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 n=new Mo({gramlot:this.gramlot,root:r.root,onError:s=>this.state.setItem("status",s.message)}),i=n.prepareValue(r.entries);return this.resolver?.abort(),this.resolver=n,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()}},Rr=class{fileSystemMount(e){let t=e.parentNode,r=new Lo(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 Hf(o,{datapath:e,...t}){let r=o.div({datapath:e,class:"gramlot-filesystem",...t});return r.dataSetter({destination_path:".store",value:new x}),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 Jb=(o,e)=>"d_"+[...new TextEncoder().encode(JSON.stringify([o,e]))].map(t=>t.toString(16).padStart(2,"0")).join(""),As=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=Jb(e,t),n=this.documents.getNodes().find(a=>!a.value.getItem("isNew")&&a.value.getItem("root")===e&&a.value.getItem("path")===t);if(n)return n.label;if(this.pending.has(r))return this.pending.get(r).promise;let i=new AbortController,s=this.gramlot.rpc.call("data","document_read",{root:e,path:t},{signal:i.signal}).then(a=>{if(this.disposed||i.signal.aborted)return null;let l=new x,c=a.language==="image"?a.content.toTytx():a.content;for(let[u,d]of Object.entries({...a,content:c,root:e,saved:c,busy:!1}))l.setItem(u,d);if(a.language==="image"){let u=a.content;l.setItem("annotations",u),u.subscribe("ide-annotations",{any:()=>l.setItem("content",u.toTytx())})}return this.documents.setItem(r,l),r}).finally(()=>this.pending.delete(r));return this.pending.set(r,{request:i,promise:s}),s}newDocument(e,t,r=""){let n=`new_${G()}`,i=new x;for(let[s,a]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(s,a);return this.documents.setItem(n,i),n}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"),n=t.getItem("savePath");if(t.getItem("path").endsWith(".typ.py")!==n.endsWith(".typ.py"))throw new Error("The .typ.py extension is required for the Typst Python recipe document type.");let i=t.getItem("content"),s=new AbortController;t.setItem("busy",!0);let a=this.gramlot.rpc.call("data","document_create",{root:r,path:n,content:i},{signal:s.signal}).then(l=>this.disposed||s.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:s,promise:a}),a}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"),n=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:n.signal}).then(s=>this.disposed||n.signal.aborted||t.getItem("content")!==r?!1:(t.setItem("typstSource",s.source),t.setItem("previewHidden",!1),t.setItem("renderStatus","Typst generated from the current recipe."),!0)).catch(s=>(!this.disposed&&!n.signal.aborted&&t.setItem("renderStatus",s.message),!1)).finally(()=>{this.pending.delete(e),this.disposed||(t.setItem("rendering",!1),t.setItem("busy",!1))});return this.pending.set(e,{request:n,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"),n=new AbortController;t.setItem("busy",!0);let i=t.getItem("language")==="image",s=i?t.getItem("annotationPath"):t.getItem("path"),a=i&&t.getItem("revision")===null,l=this.gramlot.rpc.call("data",a?"document_create":"document_save",{root:t.getItem("root"),path:s,content:i?x.fromTytx(r):r,...a?{}:{revision:t.getItem("revision")}},{signal:n.signal}).then(c=>this.disposed||n.signal.aborted?!1:(t.setItem("revision",c.revision),t.setItem("saved",r),!0)).finally(()=>{this.pending.delete(e),this.disposed||t.setItem("busy",!1)});return this.pending.set(e,{request:n,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(x.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()}},Is=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 x;return e.forEach((r,n)=>t.setItem(`r${n}`,r,{caption:r})),t}};function Be(o){for(let e=o;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 Cs=class{fileSystemMount(e){return Rr.prototype.fileSystemMount.call(this,e)}fileSystemOpen(e,t){return Rr.prototype.fileSystemOpen.call(this,e,t)}ideMount(e){let t=e.parentNode,r={scope:t,documents:new As(this.page,t),requested:0,editorPrefix:`ide_${G()}`,recent:new Is(this.page.src.renderer.destination.ownerDocument.defaultView.sessionStorage)};Object.defineProperty(t,"ideContext",{value:r,configurable:!0});let{documents:n,recent:i}=r,s=t.getRelativeData("."),a=i.read();s.setItem("recent",i.choices(a)),s.setItem("workspace",a[0]??"");let l=s.getItem("browser");l.subscribe("ide-browser",{any:u=>{if(u.node===l.getNode("root")){let d=l.getItem("root");s.setItem("workspace",d),s.setItem("recent",i.choices(i.remember(d))),s.setItem("status",`Workspace: ${d}`)}else if(u.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 c=n.documents;c.subscribe("ide-documents",{any:u=>{if(["content","saved","busy","writable","view","isNew","path","root"].includes(u.node.label))for(let d of t.value.getNode("frame.center.tabs").value?.getNodes()??[]){let f=d.getAttr("documentKey"),h=n.documents.getItem(f);h&&(u.node===h.getNode("content")&&n.invalidateRecipe(f),this.ideDocumentState(t,f),d.setAttr({title:`${n.dirty(f)?"\u25CF ":""}${h.getItem("path")}`}))}}}),this.page.src.renderer.onDispose(r.scope,()=>{l.unsubscribe("ide-browser",{any:!0}),c.unsubscribe("ide-documents",{any:!0}),n.dispose()})}ideOpenWorkspace(e){let r=Be(e).scope.getRelativeData("."),n=r.getItem("workspace");n&&n!==r.getItem("browser.root")&&r.setItem("browser.requestedRoot",n)}async ideUploadCompleted(e,{result:t}){let r=Be(e),n=r.scope.getRelativeData(".");if(n.getItem("browser.root")!==t.root)return;n.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&&n.getItem("browser.root")===t.root&&await this.ideOpenDocument(r.scope,t.root,t.path)}ideDocumentState(e,t){let r=Be(e),{documents:n}=r,i=n.documents.getItem(t),s=!n.dirty(t)&&!i.getItem("isNew")||i.getItem("busy");i.setItem("saveDisabled",!!(s||!i.getItem("writable"))),i.setItem("revertDisabled",!!(!n.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 n=Be(e),{documents:i}=n,s=n.scope.getRelativeData("."),a=++n.requested;try{let l=await i.open(t,r);if(l===null||i.disposed)return;this.ideShowDocument(e,l),a===n.requested&&(s.setItem("active",l),s.setItem("status",`${r}${i.documents.getItem(l).getItem("writable")?"":" (draft only \u2014 Remote Edit is disabled)"}`))}catch(l){i.disposed||s.setItem("status",l.message)}}ideNew(e){let t=Be(e),{documents:r}=t,n=t.scope.getRelativeData("."),i=n.getItem("newType"),s=i==="typstRecipe"?"python":i,a={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(s,a[i],n.getItem("workspace"));r.documents.getItem(l).setItem("writable",n.getItem("browser.writable")===!0),++t.requested,this.ideShowDocument(e,l),n.setItem("active",l),n.setItem("status","New document. Choose directory and name when saving.")}ideShowDocument(e,t){let r=Be(e),{documents:n}=r,s=n.documents.getItem(t).getItem("path"),a=r.scope.value.getNode("frame.center.tabs");if(!a.value?.getNode(t)){let l=n.documents.getItem(t),c=s.endsWith(".typ.py");c&&n.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 u=Z(a.builder.wrapSource(a).contentPane({node_label:t,title:s,pageName:t,documentKey:t,closable:!0,onClose:"ideClose",height:"100%"})),d=u.builder.wrapSource(u).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 ${s}`});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 v=f.button({title:w,"aria-label":w,disabled:`^.${m}Disabled`,class:`button--quiet gramlot-ide-${m}`});v.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}),v.dataController({func:_,documentKey:t})}c&&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",v=w||_||c,E=v?p.tabContainer({height:"100%",selectedPage:`^.documents.${t}.view`}):null,D=v?E.contentPane({title:"Code",pageName:"code",height:"100%"}):p;if(Ss(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}),_&&E.contentPane({title:"Preview",pageName:"preview",height:"100%"}).typstPreview({value:`^.documents.${t}.content`,filename:`^.documents.${t}.pdfFilename`,height:"100%"}),c){let k=E.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}),E.contentPane({title:"Generated Typst",pageName:"generated",height:"100%"}).codeMirror({value:`^.documents.${t}.typstSource`,language:"typst",readonly:!0,height:"100%"})}if(w){let k=E.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`}:{}}),E.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=Be(e),{documents:n}=r;n.documents.getItem(t).setItem("view","preview"),await n.renderRecipe(t)}ideCancelCreate(e,{documentKey:t}){let r=Be(e),{documents:n}=r;n.documents.getItem(t).setItem("createHidden",!0)}async ideCreate(e,{documentKey:t}){let r=Be(e),{documents:n}=r,i=r.scope.getRelativeData(".");i.setItem("status","Creating file\u2026");try{let s=await n.create(t);if(!n.disposed&&s){i.setItem("status","File created.");let a=i.getItem("browser");a.getItem("root")&&await r.scope.value.getNode("frame.left.browser").fileSystemController.open(a.getItem("root"))}}catch(s){n.disposed||i.setItem("status",s.message)}}async ideSave(e,{documentKey:t=null}={}){let r=Be(e),{documents:n}=r,i=r.scope.getRelativeData("."),s=t??i.getItem("active");if(!s||n.documents.getItem(s).getItem("saveDisabled"))return;let a=n.documents.getItem(s);if(a.getItem("isNew")){a.setItem("createHidden",!1);return}i.setItem("status","Saving\u2026");try{let l=await n.save(s);n.disposed||i.setItem("status",l?"Saved.":"Document is read only or a request is pending.")}catch(l){n.disposed||i.setItem("status",l.message)}}ideRevert(e,{documentKey:t}){let r=Be(e),{documents:n}=r,i=r.scope.getRelativeData(".");n.revert(t)&&i.setItem("status","Restored the last saved version.")}ideHistoryChanged(e,{canUndo:t,canRedo:r}){let n=e.getRelativeData("."),i=e.getAttr("editorView");n.setItem(`${i}CanUndo`,t),n.setItem(`${i}CanRedo`,r),this.ideHistoryState(n)}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=Be(e),{documents:n}=r,i=n.documents.getItem(t).getItem("view")==="rich",s=this.page.src.binding.nodeIds.get(`${r.editorPrefix}_${i?"rich_":""}editor_${t}`);return this.page.src.renderer.records.get(s).element}ideUndo(e,{documentKey:t}){this.ideEditor(e,t).undo()}ideRedo(e,{documentKey:t}){this.ideEditor(e,t).redo()}ideClose(e){let t=Be(e),{documents:r}=t,n=t.scope.getRelativeData("."),i=e.getAttr("documentKey");return r.canClose(i)?!0:(n.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 n=Be(e),{documents:i}=n,s=n.scope.getRelativeData("."),a=i.documents.getItem(t),l=s.getItem("browser"),c=l.getItem("selectedPath"),u=c===null?null:l.getItem("store").getNode(c);a&&l.getItem("root")===a.getItem("root")&&u?.attr.path===a.getItem("path")&&l.setItem("selectedPath",null),i.close(t,r)}};var tr=class extends Y{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}};Ni(tr,{module:"gramlot.tree_store",name:"TreeStoreResolver",encode:()=>({args:[],kwargs:{}}),decode:()=>new tr});var Fo=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 n of["path","label","attributes"])if(Object.hasOwn(r,n))throw new TypeError(`TreeStore params reserves ${n}`);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 n=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(!(n instanceof x))throw new TypeError("TreeStore method must return a Bag");e||(this.root=n,n.setBackref());let i=(s,a)=>{for(let l of s.getNodes()){let c=a?`${a}.${l.label}`:l.label;l.resolver instanceof tr&&l.resolver.bind(this,c),l.staticValue instanceof x&&i(l.staticValue,c)}};return i(n,e),n}dispose(){this.controller.abort()}},Ds=class{treeFavoriteActionState(e,{item:t,state:r}){let n=t.resolver!==null||t.staticValue instanceof x;if(t.getAttr("favoriteEntry")===!0)return{hidden:!1,icon:"\u2715",title:"Remove favorite"};let i=!n&&r.getNodes().some(s=>s.getAttr("fieldpath")===t.getAttr("fieldpath"));return{hidden:n,icon:i?"\u2665":"\u2661",title:i?"Remove favorite":"Add favorite"}}treeFavoritesMount(e,{favoriteKey:t}){let n=this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.getItem(t);this.setTreeFavorites(e.getRelativeData("."),n===null?[]:j(n))}setTreeFavorites(e,t){if(!Array.isArray(t))throw new TypeError("Tree favorites must be an array");let r=new x;t.forEach((n,i)=>{if(!n||typeof n.fieldpath!="string"||typeof n.path!="string"||typeof n.caption!="string"||!n.attrs||typeof n.attrs!="object")throw new TypeError("Invalid tree favorite");let s={...n.attrs};for(let a of["caption","fullcaption"])typeof s[a]=="string"&&(s[a]=s[a].replace(/(^|\.)!!(?:\[[^\]]+\])?/g,"$1"));r.setItem(`favorite_${i}`,null,{...s,favoriteEntry:!0,originalPath:n.path})}),e.setItem("favorites",r)}treeFavoriteToggle(e,{item:t,path:r,favoriteKey:n}){if(t.resolver||t.staticValue instanceof x)return;let i=t.getAttr(),s=e.getRelativeData("."),a=s.getItem("favorites").getNodes().map(u=>{let{favoriteEntry:d,originalPath:f,...h}=u.getAttr();return{fieldpath:h.fieldpath,path:f,caption:h.caption,attrs:h}}),l=a.findIndex(u=>u.fieldpath===i.fieldpath);l===-1?a.push({fieldpath:i.fieldpath,path:r,caption:i.caption,attrs:{...i}}):a.splice(l,1),this.page.src.renderer.destination.ownerDocument.defaultView.localStorage.setItem(n,R(a)),this.setTreeFavorites(s,a)}treeStoreMount(e,{storeMethod:t,storeParams:r}){let n=e.parentNode,i=e.getRelativeData("."),s=new Fo({gramlot:this.page,method:t,params:r});this.page.src.renderer.onDispose(n,()=>s.dispose());let a=new tr({readOnly:!0});return a.bind(s,""),i.setResolver("store",a),Promise.resolve(i.getItem("store")).then(l=>{s.controller.signal.aborted||i.setItem("store",l)})}treeInspect(e,{item:t,path:r}){let n=this.page.src.binding.bindingFor(e),i=!1,s=`tree_inspect_${G()}`,a=()=>{},l=()=>{i||(i=!0,a(),this.page.src.source.getNode(s)&&this.page.src.source.popNode(s))};a=n.track(l);try{let c=new me,u=c.root.html_dialog({nodeId:s,request:s,connect_oncancel:"treeInspectClose",connect_onclose:"treeInspectClose","aria-labelledby":`${s}_title`,style:"width:min(36rem,calc(100% - 48px));max-height:80vh;overflow:auto;"});u.h2("Attributes",{id:`${s}_title`}),u.p(`==${JSON.stringify(r)}`),u.html_button("Close",{type:"button",autofocus:!0,request:s,connect_onclick:"treeInspectClose"});let d=u.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":R(p);m.td(`==${JSON.stringify(b)}`)}this.page.src.source.setItem(s,this.page.src.prepareSource(c.source));let f=this.page.src.binding.nodeIds.get(s);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(c){throw l(),c}}treeInspectClose(e,t){t.preventDefault();let r=this.page.src.binding.nodeIds.get(e.getAttr("request"));r&&r.treeInspectClose()}};var _n=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 Qb=new Set(Object.entries(new Je().schema).filter(([,o])=>!o._meta?.data_element&&!o._meta?.subbuilder&&!o._meta?.container).map(([o])=>o));function yn(o){if(!(o==null||o==="html")){if(!Array.isArray(o)||o.some(e=>typeof e!="string"||!e||e.trim()!==e))throw new TypeError('catalogue must be "html" or a list of tag names');if(!o.includes("div"))throw new Error("catalogue must include div for pageRoot")}}function vn(o,e,t={}){return o==null?!0:Array.isArray(o)?o.includes(e):!t.gramlot_component&&!t.data_element&&!t.subbuilder&&!t.container&&Qb.has(t.render_tag??e)}function tt(o,e){if(o==null)return;let t=(r,n)=>{for(let i of r.getNodes()){let s=n?`${n}.${i.label}`:i.label;if(!vn(o,i.nodeTag,i.getAttr("_meta")??{}))throw new Error(`Tag ${i.nodeTag} is outside the editor catalogue at ${s}`);if(i.resolver)throw new Error(`Catalogue scope requires materialized Source at ${s}`);let a=i.getValue(!0);a instanceof N&&t(a,s)}};t(e,"")}var Ce={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"};Ce.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";Ce.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";Ce.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";Ce.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 Ns=class{constructor(e,{datapath:t="__editor",dataRoot:r="",editorId:n="visual",uploadOperation:i="import_source",codeDocument:s=null,catalogue:a=null,fileCommands:l=!0,canvasCss:c=null,...u}={}){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test(n))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(yn(a),c!=null&&(!Array.isArray(c)||c.some(nr=>typeof nr!="string")))throw new TypeError("canvasCss must be a list of CSS texts");this.dataRoot=r;let d=this.pane=e.main({node_label:n,datapath:t,visualEditorId:n,...u,nodeId:`${n}Editor`,class:`visual-editor-shell ${u.class??""}`,overflow:"hidden",tabindex:0,connect_onkeydown:"clipboardShortcut"});d.dataSetter({destination_path:".catalogueScope",value:a}),d.dataSetter({destination_path:".canvasCss",value:c}),d.dataSetter({destination_path:".uploadQueue",value:new x}),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",Ce.navigation),this.toolButton(f.menuline({group:!0}),"Catalogue","openCatalogue",Ce.catalogue),this.toolButton(f.menuline({group:!0}),"Properties","openProperties",Ce.properties),this.toolButton(f.menuline({group:!0}),"Clipboard","this.SET('.clipboardVisible', !this.GET('.clipboardVisible'))",Ce.paste,{dropTarget:!0,dropTypes:"app/source",dropTags:`${n}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'))",Ce.appearance);let h=d.framePane({node_label:"layout",height:"100%",id:`${n}-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[nr,Zo,Ko]of[["New","newPage","new"],["Open","openUpload","open"],["Download","downloadPage","download"],["Copy Source","copySource","copy"]])this.toolButton(m,nr,Zo,Ce[Ko],{id:`${n}-${Ko}`});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",Ce.cut,{title:"Cut branch (F8)"}),this.toolButton(b,"Copy branch","copyBranch",Ce.copy),this.toolButton(b,"Paste branch","pasteBranch",Ce.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}),v=_.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),E=v.contentPane({region:"center"}).borderContainer({height:"100%",min_height:0}),D=E.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.${Z(d).fullpath.split(".").slice(1).join(".")}.layout.center.design`,hideValues:!0,getLabel:"sourceLabel",searchText:"^.sourceSearch",selectedPath:"^.selection",draggable:!0,dragTags:`${n}Source`,effectAllowed:"all",onDrag:"prepareSource",dropTarget:!0,dropTypes:"app/widget,app/source,app/clipboard",dropTags:`widget,${n}Source,${n}Clipboard`,dropEffect:"^.sourceDropEffect",onDrop:"dropNode",id:`${n}-source-tree`,class:"visual-source-tree",flex:1,min_height:0});let k=E.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:`${n}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:`${n}Clipboard`,effectAllowed:"copy",onDrag:"prepareClipboard",id:`${n}-clipboard-tree`,class:"visual-clipboard-tree",flex:1,min_height:0}),k.p("^.error",{role:"alert",class:"visual-editor-hint"});let C=v.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:`${n}-data-tree`,flex:1,min_height:0});let O=h.center;O.setAttr({overflow:"auto",class:"visual-editor-workspace"});let L=O.div({node_label:"design",class:"visual-editor-canvas"});L.div({node_label:"pageRoot",...this.dataRoot?{datapath:this.dataRoot}:{}});let z=d.floatingPane({title:"Widget catalogue",open:"^.catalogueOpen",default_open:!1,width:"280px",height:"400px",class:"visual-editor-popup",movable:!0,resizable:!0});this.search(z.frame.top,"catalogueSearch","Search widgets"),z.frame.center.tree({storepath:".catalogue",hideValues:!0,labelAttribute:"caption",searchText:"^.catalogueSearch",draggable:!0,dragTags:"widget",effectAllowed:"all",onDrag:"prepareWidget",id:`${n}-widget-tree`});let V=_.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});V.div({nodeId:`${n}EditorFields`,class:"visual-editor-fields",display:"flex",flex_direction:"column",flex:1,min_height:0}).span(""),V.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:`${n}-uploader`});let _e=d.dialog({class:"visual-editor-popup",title:"Save branch to clipboard",open:"^.clipboardOpen",width:"380px",height:"210px"});_e.frame.center.textbox({value:"^.clipboardDraft.name",lbl:"Name",margin:"12px"}),_e.frame.center.p("^.error",{role:"alert",margin:"12px"});let ht=_e.frame.bottom.menu({presentation:"bar",aria_label:"Clipboard commands",padding:"3px 6px"});ht.spacer({flex:1});let ne=ht.menuline({group:!0,gap:"8px"});ne.button("Cancel",{action:"this.SET('.clipboardOpen', false)"}),ne.button("Save branch",{action:"saveClipboard"});let X=d.dialog({class:"visual-editor-popup",title:"Required parameters",open:"^.insertionOpen",width:"400px",height:"280px",movable:!0,resizable:!0});X.frame.center.div({nodeId:`${n}InsertFields`,class:"visual-editor-fields",padding:"6px"}).span(""),X.frame.center.p("^.error",{role:"alert"});let pt=X.frame.bottom.menu({presentation:"bar",aria_label:"Insertion commands",padding:"3px 6px",border_top:"1px solid var(--gramlot-border)"});pt.spacer({flex:1});let Yo=pt.menuline({group:!0,gap:"8px"});Yo.button("Cancel",{action:"this.SET('.insertionOpen', false)"}),Yo.button("Insert",{action:"insertWidget"});let Dt=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"});Dt.filteringSelect({validate_notnull:!0,lbl:"Theme",value:"^.appearanceProfile",values:"base:Base,compact:Compact,mimi:Mimi,joanna:Joanna,mela:Mela"}),Dt.filteringSelect({validate_notnull:!0,lbl:"Colors",value:"^.appearancePalette",values:"default:Theme default,compact:Blue & slate,mimi:Sage & green,joanna:Warm gray & blue"}),Dt.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=L,s!==null&&this.codeDocument(s)}toolButton(e,t,r,n,i={}){let s=e.button({aria_label:t,title:t,action:r,class:"button--quiet visual-editor-tool",...i});return s.span({class:"visual-tool-icon",aria_hidden:"true",style:`mask-image:url("${n}")`}),s}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 x({...e,saved:e.content,busy:!1,status:""})});let n=`#${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 s=t.right;s.setAttr({class:"visual-editor-code",datapath:n,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 a=s.framePane({height:"100%",width:"100%",min_width:0,flex:1});a.top.setAttr({height:"26px"}),a.bottom.setAttr({height:"48px"}),a.center.setAttr({display:"flex",flex_direction:"column",min_height:0,overflow:"hidden"}),a.top.div(e.path,{padding:"3px 6px",font_size:"12px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),a.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}),a.bottom.div("^.codeDocument.status",{role:"status",font_size:"12px",padding:"4px 10px"});let l=a.bottom.menu({presentation:"bar",aria_label:"Page code commands",padding:"3px 6px"});l.spacer({flex:1});let c=l.menuline({group:!0,gap:"6px"});c.button("Close",{action:"this.SET('.codeOpen', 'close')"}),c.button("Preview saved",{action:"codePreview",disabled:"^.codeDocument.busy"}),c.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 Os=class extends _n{constructor({catalogue:e=null}={}){super({maxBytes:5*1024*1024}),yn(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 N)||t.length!==1||t.getNodes()[0].label!=="pageRoot")throw new TypeError("Expected one pageRoot Source");return tt(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}};var _c={};ee(_c,{default:()=>mh});function ew(o,e){this.v=o,this.k=e}function Xf(o,e){(e==null||e>o.length)&&(e=o.length);for(var t=0,r=Array(e);t<e;t++)r[t]=o[t];return r}function tw(o){if(Array.isArray(o))return o}function rw(o,e){var t=o==null?null:typeof Symbol<"u"&&o[Symbol.iterator]||o["@@iterator"];if(t!=null){var r,n,i,s,a=[],l=!0,c=!1;try{if(i=(t=t.call(o)).next,e===0){if(Object(t)!==t)return;l=!1}else for(;!(l=(r=i.call(t)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(u){c=!0,n=u}finally{try{if(!l&&t.return!=null&&(s=t.return(),Object(s)!==s))return}finally{if(c)throw n}}return a}}function nw(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
233
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ow(o,e){return tw(o)||rw(o,e)||iw(o,e)||nw()}function iw(o,e){if(o){if(typeof o=="string")return Xf(o,e);var t={}.toString.call(o).slice(8,-1);return t==="Object"&&o.constructor&&(t=o.constructor.name),t==="Map"||t==="Set"?Array.from(o):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Xf(o,e):void 0}}function $s(o){var e,t;function r(i,s){try{var a=o[i](s),l=a.value,c=l instanceof ew;Promise.resolve(c?l.v:l).then(function(u){if(c){var d=i==="return"&&l.k?i:"next";if(!l.k||u.done)return r(d,u);u=o[d](u).value}n(!!a.done,u)},function(u){r("throw",u)})}catch(u){n(2,u)}}function n(i,s){i===2?e.reject(s):e.resolve({value:s,done:i}),(e=e.next)?r(e.key,e.arg):t=null}this._invoke=function(i,s){return new Promise(function(a,l){var c={key:i,arg:s,resolve:a,reject:l,next:null};t?t=t.next=c:(e=t=c,r(i,s))})},typeof o.return!="function"&&(this.return=void 0)}$s.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},$s.prototype.next=function(o){return this._invoke("next",o)},$s.prototype.throw=function(o){return this._invoke("throw",o)},$s.prototype.return=function(o){return this._invoke("return",o)};var ch=Object.entries,Yf=Object.setPrototypeOf,sw=Object.isFrozen,uh=Object.getPrototypeOf,dh=Object.getOwnPropertyDescriptor,we=Object.freeze,ke=Object.seal,xn=Object.create,fh=typeof Reflect<"u"&&Reflect,bc=fh.apply,wc=fh.construct;we||(we=function(e){return e});ke||(ke=function(e){return e});bc||(bc=function(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];return e.apply(t,n)});wc||(wc=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return new e(...r)});var St=ae(Array.prototype.forEach);Array.prototype.indexOf;var aw=ae(Array.prototype.lastIndexOf),Zf=ae(Array.prototype.pop),zo=ae(Array.prototype.push),lw=ae(Array.prototype.slice),cw=ae(Array.prototype.splice),kn=Array.isArray,lc=hh(Set),cc=ae(Set.prototype.add),qo=ae(Set.prototype.has),jr=ae(String.prototype.toLowerCase),uc=ae(String.prototype.toString),Kf=ae(String.prototype.match),Uo=ae(String.prototype.replace),Jf=ae(String.prototype.indexOf),uw=ae(String.prototype.trim),dw=ae(Number.prototype.toString),fw=ae(Boolean.prototype.toString),Qf=typeof BigInt>"u"?null:ae(BigInt.prototype.toString),eh=typeof Symbol>"u"?null:ae(Symbol.prototype.toString),Me=ae(Object.prototype.hasOwnProperty),Vo=ae(Object.prototype.toString),xe=ae(RegExp.prototype.test),At=hh(TypeError);function ae(o){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return bc(o,e,r)}}function hh(o){return function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return wc(o,t)}}function J(o,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:jr;if(Yf&&Yf(o,null),!kn(e))return o;let r=e.length;for(;r--;){let n=e[r];if(typeof n=="string"){let i=t(n);i!==n&&(sw(e)||(e[r]=i),n=i)}o[n]=!0}return o}function hw(o){for(let e=0;e<o.length;e++)Me(o,e)||(o[e]=null);return o}function ze(o){let e=xn(null);for(let r of ch(o)){var t=ow(r,2);let n=t[0],i=t[1];Me(o,n)&&(kn(i)?e[n]=hw(i):i&&typeof i=="object"&&i.constructor===Object?e[n]=ze(i):e[n]=i)}return e}function pw(o){switch(typeof o){case"string":return o;case"number":return dw(o);case"boolean":return fw(o);case"bigint":return Qf?Qf(o):"0";case"symbol":return eh?eh(o):"Symbol()";case"undefined":return Vo(o);case"function":case"object":{if(o===null)return Vo(o);let e=o,t=Ve(e,"toString");if(typeof t=="function"){let r=t(e);return typeof r=="string"?r:Vo(r)}return Vo(o)}default:return Vo(o)}}function Ve(o,e){for(;o!==null;){let r=dh(o,e);if(r){if(r.get)return ae(r.get);if(typeof r.value=="function")return ae(r.value)}o=uh(o)}function t(){return null}return t}function mw(o,e){for(;o!==null;){let t=dh(o,e);if(t)return t.get?ae(t.get):null;o=uh(o)}return null}function gw(o){try{return xe(o,""),!0}catch{return!1}}var th=we(["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"]),dc=we(["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"]),fc=we(["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"]),bw=we(["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"]),hc=we(["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"]),ww=we(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),rh=we(["#text"]),nh=we(["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"]),pc=we(["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"]),oh=we(["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"]),Rs=we(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),_w=ke(/{{[\w\W]*|^[\w\W]*}}/g),yw=ke(/<%[\w\W]*|^[\w\W]*%>/g),vw=ke(/\${[\w\W]*/g),xw=ke(/^data-[\-\w.\u00B7-\uFFFF]+$/),kw=ke(/^aria-[\-\w]+$/),ih=ke(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ew=ke(/^(?:\w+script|data):/i),Tw=ke(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Sw=ke(/^html$/i),Aw=ke(/^[a-z][.\w]*(-[.\w]+)+$/i),mc=ke(/<[/\w!]/g),sh=ke(/<[/\w]/g),Iw=ke(/<\/no(script|embed|frames)/i),ah=ke(/\/>/i),fe={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Cw=we(J({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),Dw=function(){return typeof window>"u"?null:window},Nw=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},lh=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},rr=function(e,t,r,n){return Me(e,t)&&kn(e[t])?J(n.base?ze(n.base):{},e[t],n.transform):r},gc=function(e,t,r){let n=Me(e,t)?e[t]:void 0;return n&&typeof n=="object"?ze(n):r()};function ph(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Dw(),e=I=>ph(I);if(e.version="3.4.17",e.removed=[],!o||!o.document||o.document.nodeType!==fe.document||!o.Element)return e.isSupported=!1,e;let t=o.document,r=t,n=r.currentScript;o.DocumentFragment;let i=o.HTMLTemplateElement,s=o.Node,a=o.Element,l=o.NodeFilter;o.NamedNodeMap===void 0&&(o.NamedNodeMap||o.MozNamedAttrMap),o.HTMLFormElement;let c=o.DOMParser,u=o.trustedTypes,d=a.prototype,f=Ve(d,"cloneNode"),h=Ve(d,"remove"),p=Ve(d,"removeAttributeNode"),m=Ve(d,"nextSibling"),b=Ve(d,"childNodes"),w=Ve(d,"parentNode"),_=Ve(d,"shadowRoot"),v=Ve(d,"attributes"),E=s&&s.prototype?Ve(s.prototype,"nodeType"):null,D=s&&s.prototype?Ve(s.prototype,"nodeName"):null,k=s&&s.prototype?Ve(s.prototype,"ownerDocument"):null,C=function(g){return E?E(g):g.nodeType},O=function(g){return D?D(g):g.nodeName},L=mw(d,"namespaceURI"),z=function(g){return L?L(g):g.namespaceURI};if(typeof i=="function"){let I=t.createElement("template");I.content&&I.content.ownerDocument&&(t=I.content.ownerDocument)}let V,le="",_e,ht=!1,ne=0,X=function(){if(ne>0)throw At('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.')},pt=function(g){X(),ne++;try{return V.createHTML(g)}finally{ne--}},Yo=function(g){X(),ne++;try{return V.createScriptURL(g)}finally{ne--}},Jc=function(){return ht||(_e=Nw(u,n),ht=!0),_e},Dt=t,nr=Dt.implementation,Zo=Dt.createNodeIterator,Ko=Dt.createDocumentFragment,Sh=Dt.getElementsByTagName,Ah=r.importNode,oe=lh();e.isSupported=typeof ch=="function"&&typeof w=="function"&&nr&&nr.createHTMLDocument!==void 0;let Ih=_w,Ch=yw,Dh=vw,Nh=xw,Oh=kw,$h=Ew,Qc=Tw,Rh=Aw,eu=ih,ie=null,Xs=J({},[...th,...dc,...fc,...hc,...rh]),se=null,Ys=J({},[...nh,...pc,...oh,...Rs]),rt=Object.seal(xn(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}})),Tn=null,tu=null,Nt=Object.seal(xn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ru=!0,Zs=!0,nu=!1,Ks=!0,mt=!1,or=!0,ir=!1,Js=!1,Jo=null,Qo=null,Qs=!1,Pr=!1,ei=!1,ti=!1,ou=!0,iu=!1,su="user-content-",ea=!0,ta=!1,sr=null,Br={},ar=null,au=J({},["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"]),lu=null,cu=J({},["audio","video","img","source","image","track"]),uu=null,du=J({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ri="http://www.w3.org/1998/Math/MathML",ni="http://www.w3.org/2000/svg",nt="http://www.w3.org/1999/xhtml",Mr=nt,ra=!1,na=null,jh=J({},[ri,ni,nt],uc),fu=we(["mi","mo","mn","ms","mtext"]),oa=J({},fu),hu=we(["annotation-xml"]),ia=J({},hu),Ph=J({},["title","style","font","a","script"]),Sn=null,Bh=["application/xhtml+xml","text/html"],Mh="text/html",ue=null,Lr=null,Lh=t.createElement("form"),pu=function(g){return g instanceof RegExp||g instanceof Function},sa=function(){let g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Lr&&Lr===g)return;(!g||typeof g!="object")&&(g={}),g=ze(g),Sn=Bh.indexOf(g.PARSER_MEDIA_TYPE)===-1?Mh:g.PARSER_MEDIA_TYPE,ue=Sn==="application/xhtml+xml"?uc:jr,ie=rr(g,"ALLOWED_TAGS",Xs,{transform:ue}),se=rr(g,"ALLOWED_ATTR",Ys,{transform:ue}),na=rr(g,"ALLOWED_NAMESPACES",jh,{transform:uc}),uu=rr(g,"ADD_URI_SAFE_ATTR",du,{transform:ue,base:du}),lu=rr(g,"ADD_DATA_URI_TAGS",cu,{transform:ue,base:cu}),ar=rr(g,"FORBID_CONTENTS",au,{transform:ue}),Tn=rr(g,"FORBID_TAGS",ze({}),{transform:ue}),tu=rr(g,"FORBID_ATTR",ze({}),{transform:ue}),Br=Me(g,"USE_PROFILES")?g.USE_PROFILES&&typeof g.USE_PROFILES=="object"?ze(g.USE_PROFILES):g.USE_PROFILES:!1,ru=g.ALLOW_ARIA_ATTR!==!1,Zs=g.ALLOW_DATA_ATTR!==!1,nu=g.ALLOW_UNKNOWN_PROTOCOLS||!1,Ks=g.ALLOW_SELF_CLOSE_IN_ATTR!==!1,mt=g.SAFE_FOR_TEMPLATES||!1,or=g.SAFE_FOR_XML!==!1,ir=g.WHOLE_DOCUMENT||!1,Pr=g.RETURN_DOM||!1,ei=g.RETURN_DOM_FRAGMENT||!1,ti=g.RETURN_TRUSTED_TYPE||!1,Qs=g.FORCE_BODY||!1,ou=g.SANITIZE_DOM!==!1,iu=g.SANITIZE_NAMED_PROPS||!1,ea=g.KEEP_CONTENT!==!1,ta=g.IN_PLACE||!1,eu=gw(g.ALLOWED_URI_REGEXP)?g.ALLOWED_URI_REGEXP:ih,Mr=typeof g.NAMESPACE=="string"?g.NAMESPACE:nt,oa=gc(g,"MATHML_TEXT_INTEGRATION_POINTS",()=>J({},fu)),ia=gc(g,"HTML_INTEGRATION_POINTS",()=>J({},hu));let y=gc(g,"CUSTOM_ELEMENT_HANDLING",()=>xn(null));if(rt=xn(null),Me(y,"tagNameCheck")&&pu(y.tagNameCheck)&&(rt.tagNameCheck=y.tagNameCheck),Me(y,"attributeNameCheck")&&pu(y.attributeNameCheck)&&(rt.attributeNameCheck=y.attributeNameCheck),Me(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(rt.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),ke(rt),mt&&(Zs=!1),ei&&(Pr=!0),Br&&(ie=J({},rh),se=xn(null),Br.html===!0&&(J(ie,th),J(se,nh)),Br.svg===!0&&(J(ie,dc),J(se,pc),J(se,Rs)),Br.svgFilters===!0&&(J(ie,fc),J(se,pc),J(se,Rs)),Br.mathMl===!0&&(J(ie,hc),J(se,oh),J(se,Rs))),Nt.tagCheck=null,Nt.attributeCheck=null,Me(g,"ADD_TAGS")&&(typeof g.ADD_TAGS=="function"?Nt.tagCheck=g.ADD_TAGS:kn(g.ADD_TAGS)&&(ie===Xs&&(ie=ze(ie)),J(ie,g.ADD_TAGS,ue))),Me(g,"ADD_ATTR")&&(typeof g.ADD_ATTR=="function"?Nt.attributeCheck=g.ADD_ATTR:kn(g.ADD_ATTR)&&(se===Ys&&(se=ze(se)),J(se,g.ADD_ATTR,ue))),Me(g,"ADD_FORBID_CONTENTS")&&kn(g.ADD_FORBID_CONTENTS)&&(ar===au&&(ar=ze(ar)),J(ar,g.ADD_FORBID_CONTENTS,ue)),ea&&(ie["#text"]=!0),ir&&J(ie,["html","head","body"]),ie.table&&(J(ie,["tbody"]),delete Tn.tbody),g.TRUSTED_TYPES_POLICY){if(typeof g.TRUSTED_TYPES_POLICY.createHTML!="function")throw At('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof g.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw At('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let T=V;V=g.TRUSTED_TYPES_POLICY;try{le=pt("")}catch(S){throw V=T,S}}else g.TRUSTED_TYPES_POLICY===null?(V=void 0,le=""):(V===void 0&&(V=Jc()),V&&typeof le=="string"&&(le=pt("")));we&&we(g),Lr=g},mu=J({},[...dc,...fc,...bw]),gu=J({},[...hc,...ww]),Fh=function(g,y,T){return y.namespaceURI===nt?g==="svg":y.namespaceURI===ri?g==="svg"&&(T==="annotation-xml"||oa[T]):!!mu[g]},zh=function(g,y,T){return y.namespaceURI===nt?g==="math":y.namespaceURI===ni?g==="math"&&ia[T]:!!gu[g]},qh=function(g,y,T){return y.namespaceURI===ni&&!ia[T]||y.namespaceURI===ri&&!oa[T]?!1:!gu[g]&&(Ph[g]||!mu[g])},Uh=function(g){let y=z(g),T=jr(O(g)),S=w(g),P,F;return S&&C(S)===fe.element?(P={namespaceURI:z(S)},F=jr(O(S))):(P={namespaceURI:Mr},F="template"),na[y]?y===ni?Fh(T,P,F):y===ri?zh(T,P,F):y===nt?qh(T,P,F):!!(Sn==="application/xhtml+xml"&&na[y]):!1},Ot=function(g){zo(e.removed,{element:g});try{w(g).removeChild(g)}catch{if(h(g),!w(g))throw At("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},bu=function(g,y,T){try{p(g,y)}catch{try{g.removeAttribute(T)}catch{}}},aa=function(g){ca(g);let y=b(g);y&&St(lw(y),S=>{try{h(S)}catch{}});let T=C(g)===fe.element?v(g):null;if(T)for(let S=T.length-1;S>=0;--S){let P=T[S],F=P&&P.name;typeof F=="string"&&bu(g,P,F)}},Fr=function(g,y,T){if(!T)try{T=y.getAttributeNode(g)}catch{T=null}zo(e.removed,{attribute:T||null,from:y});try{T?p(y,T):y.removeAttribute(g)}catch{try{y.removeAttribute(g)}catch{}}if(g==="is")if(Pr||ei)try{Ot(y)}catch{}else try{y.setAttribute(g,"")}catch{}},wu=function(g){let y=v(g);if(y)for(let T=y.length-1;T>=0;--T){let S=y[T],P=S&&S.name;typeof P!="string"||se[ue(P)]||bu(g,S,P)}},la=function(g,y){let T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,S=[g];for(;S.length>0;){let P=S.pop();if(y(P)===!1)continue;if(T&&C(P)===fe.element){let W=_(P);$t(W)&&S.push(W)}let F=b(P);if(F)for(let W=F.length-1;W>=0;--W)S.push(F[W])}},ca=function(g){la(g,y=>{C(y)===fe.element&&wu(y)})},ua=function(g){let y=[];return la(g,T=>{y.push(T)},!0),y},Vh=function(g,y){let T=lc();St(ua(g),S=>{C(S)===fe.element&&cc(T,S)}),St(y,S=>{C(S)===fe.element&&!qo(T,S)&&wu(S)})},_u=function(g,y){let T=!1;return St(e.removed,S=>{S.element&&(T=T||S.element===g,ca(S.element))}),Vh(g,y),T},Wh=8,Gh=function(g,y){let T=sr,S=null,P=()=>(S||(S=lc(),St(y,F=>{cc(S,F)})),S);for(let F=0;;F++){let W=ua(g),he=[g],ot=!1;if(St(W,De=>{C(De)===fe.documentFragment?zo(he,De):!ot&&!qo(T,De)&&(ot=qo(P(),De))}),!ot)return;if(F>=Wh)throw At("the tree kept changing during in-place sanitization; refusing to return it");St(he,(De,$e)=>{Hh(De,$e>0,g,P())})}},Hh=function(g,y,T,S){let P=da(g),F;for(;F=P.nextNode();)!qo(S,F)||qo(sr,F)||(y&&We(oe.uponSanitizeShadowNode,F,null),ha(F,T),pa(F,T),$t(F.content)&&In(F.content))},Xh=function(g){sr&&cc(sr,g)},yu=function(g,y){return or?g==="patchsrc"?!0:g==="for"&&y!=="label"&&y!=="output":!1},Yh=function(g){or&&la(g,y=>{let T=C(y);if(T===fe.processingInstruction||T===fe.comment&&xe(sh,y.data)){try{h(y)}catch{}return!1}if(T===fe.element){let S=y,P=ue(O(y));try{S.hasAttribute&&S.hasAttribute("patchsrc")&&S.removeAttribute("patchsrc"),S.hasAttribute&&S.hasAttribute("for")&&yu("for",P)&&S.removeAttribute("for")}catch{}}return!0})},vu=function(g){let y=null,T=null;if(Qs)g="<remove></remove>"+g;else{let F=Kf(g,/^[\r\n\t ]+/);T=F&&F[0]}Sn==="application/xhtml+xml"&&Mr===nt&&(g='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+g+"</body></html>");let S=V?pt(g):g;if(Mr===nt)try{y=new c().parseFromString(S,Sn)}catch{}if(!y||!y.documentElement){y=nr.createDocument(Mr,"template",null);try{y.documentElement.innerHTML=ra?le:S}catch{}}let P=y.body||y.documentElement;return g&&T&&P.insertBefore(t.createTextNode(T),P.childNodes[0]||null),Mr===nt?Sh.call(y,ir?"html":"body")[0]:ir?y.documentElement:P},da=function(g){let y=k?k(g):g.ownerDocument;return Zo.call(y||g,g,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},oi=function(g){return g=Uo(g,Ih," "),g=Uo(g,Ch," "),g=Uo(g,Dh," "),g},fa=function(g){var y;xu(g);let T=(y=g.querySelectorAll)===null||y===void 0?void 0:y.call(g,"template");T&&St(T,S=>{$t(S.content)&&fa(S.content)})},xu=function(g){g.normalize();let y=k?k(g):g.ownerDocument,T=Zo.call(y||g,g,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),S=T.nextNode();for(;S;)S.data=oi(S.data),S=T.nextNode()},ii=function(g){let y=D?D(g):null;return typeof y!="string"||ue(y)!=="form"?!1:typeof g.nodeName!="string"||typeof g.textContent!="string"||typeof g.removeChild!="function"||g.attributes!==v(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!==E(g)||g.childNodes!==b(g)},$t=function(g){if(!E||typeof g!="object"||g===null)return!1;try{return E(g)===fe.documentFragment}catch{return!1}},An=function(g){if(!E||typeof g!="object"||g===null)return!1;try{return typeof E(g)=="number"}catch{return!1}};function We(I,g,y){I.length!==0&&St(I,T=>{T.call(e,g,y,Lr)})}let Zh=function(g,y){return!!(or&&g.hasChildNodes()&&!An(g.firstElementChild)&&xe(mc,g.textContent)&&xe(mc,g.innerHTML)||or&&Cw[y]&&C(g)===fe.element&&z(g)===nt&&(An(g.firstElementChild)||typeof g.textContent=="string"&&xe(mc,g.textContent))||g.nodeType===fe.processingInstruction||or&&g.nodeType===fe.comment&&xe(sh,g.data))},si=function(g,y){if(g instanceof RegExp)return xe(g,y);if(g instanceof Function){for(var T=arguments.length,S=new Array(T>2?T-2:0),P=2;P<T;P++)S[P-2]=arguments[P];return!!g(y,...S)}return!1},Kh=function(g,y,T){if(!Tn[y]&&Tu(y)&&si(rt.tagNameCheck,y))return!1;if(ea&&!ar[y]&&!ar[jr(y)]){let S=w(g),P=b(g);if(P&&S){let F=P.length;for(let W=F-1;W>=0;--W){let he=g===T?f(P[W],!0):P[W];S.insertBefore(he,m(g))}}}return Ot(g),!0},ku=function(g,y,T,S){return g.length===0?y:y===T||y===S?ze(y):y},zr=function(g,y){return g===y||w(g)!==null?!1:(ta&&ca(g),!0)},ha=function(g,y){if(Xh(g),We(oe.beforeSanitizeElements,g,null),zr(g,y))return!0;if(ii(g))return Ot(g),!0;let T=ue(O(g));if(ie=ku(oe.uponSanitizeElement,ie,Xs,Jo),We(oe.uponSanitizeElement,g,{tagName:T,allowedTags:ie}),zr(g,y))return!0;if(Zh(g,T))return Ot(g),!0;if(Tn[T]||!(Nt.tagCheck instanceof Function&&Nt.tagCheck(T))&&!ie[T]){let S=Kh(g,T,y);return S===!1&&(We(oe.afterSanitizeElements,g,null),zr(g,y))?!0:S}if(C(g)===fe.element&&!Uh(g)||(T==="noscript"||T==="noembed"||T==="noframes")&&xe(Iw,g.innerHTML))return Ot(g),!0;if(mt&&g.nodeType===fe.text){let S=oi(g.textContent);g.textContent!==S&&(zo(e.removed,{element:g.cloneNode()}),g.textContent=S)}return We(oe.afterSanitizeElements,g,null),zr(g,y)},Eu=function(g,y,T){if(tu[y]||yu(y,g)||ou&&(y==="id"||y==="name")&&(T in t||T in Lh))return!1;let S=se[y]||Nt.attributeCheck instanceof Function&&Nt.attributeCheck(y,g);return Zs&&xe(Nh,y)||ru&&xe(Oh,y)?!0:S?uu[y]||xe(eu,Uo(T,Qc,""))||(y==="src"||y==="xlink:href"||y==="href")&&g!=="script"&&Jf(T,"data:")===0&&lu[g]||nu&&!xe($h,Uo(T,Qc,""))?!0:!T:Tu(g)&&si(rt.tagNameCheck,g)&&si(rt.attributeNameCheck,y,g)||y==="is"&&rt.allowCustomizedBuiltInElements&&si(rt.tagNameCheck,T)},Jh=J({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Tu=function(g){return!Jh[jr(g)]&&xe(Rh,g)},Qh=function(g,y,T,S){if(V&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!T)switch(u.getAttributeType(g,y)){case"TrustedHTML":return pt(S);case"TrustedScriptURL":return Yo(S)}return S},ep=function(g,y,T,S){try{return T?g.setAttributeNS(T,y,S):g.setAttribute(y,S),ii(g)?(Ot(g),!1):!0}catch{return Fr(y,g),!1}},Su=function(g,y){return or&&xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,y)?!0:jr(g)==="attributename"&&Kf(y,"href")!==null},pa=function(g,y){if(We(oe.beforeSanitizeAttributes,g,null),zr(g,y))return;let T=g.attributes;if(!T||ii(g))return;se=ku(oe.uponSanitizeAttribute,se,Ys,Qo);let S={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:se,forceKeepAttr:void 0},P=T.length,F=ue(g.nodeName);for(;P--;){let W=T[P],he=W.name,ot=W.namespaceURI,De=W.value,$e=ue(he),qr=De,Re=he==="value"?qr:uw(qr),Au=!1;if(S.attrName=$e,S.attrValue=Re,S.keepAttr=!0,S.forceKeepAttr=void 0,We(oe.uponSanitizeAttribute,g,S),Re=S.attrValue,iu&&($e==="id"||$e==="name")&&Jf(Re,su)!==0&&(Fr(he,g,W),Re=su+Re,Au=!0),Su(he,Re)){Fr(he,g,W);continue}if(!S.forceKeepAttr){if(!S.keepAttr){Fr(he,g,W);continue}if(!Ks&&xe(ah,Re)){Fr(he,g,W);continue}if(mt&&(Re=oi(Re)),!Eu(F,$e,Re)){Fr(he,g,W);continue}Re=Qh(F,$e,ot,Re),Re!==qr&&ep(g,he,ot,Re)&&Au&&Zf(e.removed)}}We(oe.afterSanitizeAttributes,g,null),zr(g,y)},In=function(g){let y=null,T=da(g);for(We(oe.beforeSanitizeShadowDOM,g,null);y=T.nextNode();)if(We(oe.uponSanitizeShadowNode,y,null),ha(y,g),pa(y,g),$t(y.content)&&In(y.content),C(y)===fe.element){let S=_(y);$t(S)&&(ma(S),In(S))}mt&&xu(g),We(oe.afterSanitizeShadowDOM,g,null)},ma=function(g){let y=[{node:g,shadow:null}];for(;y.length>0;){let T=y.pop();if(T.shadow){In(T.shadow);continue}let S=T.node,P=C(S)===fe.element,F=b(S);if(F)for(let W=F.length-1;W>=0;--W)y.push({node:F[W],shadow:null});if(P){let W=D?D(S):null;if(typeof W=="string"&&ue(W)==="template"){let he=S.content;$t(he)&&y.push({node:he,shadow:null})}}if(P){let W=_(S);$t(W)&&y.push({node:null,shadow:W},{node:W,shadow:null})}}};return e.sanitize=function(I){let g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,T=null,S=null,P=null;if(ra=!I,ra&&(I="<!-->"),typeof I!="string"&&!An(I)&&(I=pw(I),typeof I!="string"))throw At("dirty is not a string, aborting");if(!e.isSupported)return I;Js?(ie=Jo,se=Qo):sa(g),(oe.uponSanitizeElement.length>0||oe.uponSanitizeAttribute.length>0)&&(ie=ze(ie)),oe.uponSanitizeAttribute.length>0&&(se=ze(se)),e.removed=[];let F=ta&&typeof I!="string"&&An(I),W=[],he=sr;if(F){Yh(I);let $e=O(I);if(typeof $e=="string"){let qr=ue($e);if(!ie[qr]||Tn[qr])throw aa(I),At("root node is forbidden and cannot be sanitized in-place")}if(ii(I))throw aa(I),At("root node is clobbered and cannot be sanitized in-place");W=ua(I),sr=lc()}else if(An(I))y=vu("<!---->"),T=y.ownerDocument.importNode(I,!0),T.nodeType===fe.element&&T.nodeName==="BODY"||T.nodeName==="HTML"?y=T:y.appendChild(T),ma(y);else{if(!Pr&&!mt&&!ir&&I.indexOf("<")===-1)return V&&ti?pt(I):I;if(y=vu(I),!y)return Pr?null:ti?le:""}y&&Qs&&Ot(y.firstChild);let ot=F?I:y;try{F&&ma(I);let $e=da(ot);for(;S=$e.nextNode();)ha(S,ot),pa(S,ot),$t(S.content)&&In(S.content);F&&Gh(I,W)}catch($e){throw F&&(aa(I),_u(I,W)),$e}finally{sr=he}if(F){if(_u(I,W))throw At("a node selected for removal could not be safely returned; refusing to sanitize in place");return mt&&fa(I),I}if(Pr){if(mt&&fa(y),ei)for(P=Ko.call(y.ownerDocument);y.firstChild;)P.appendChild(y.firstChild);else P=y;return(se.shadowroot||se.shadowrootmode)&&(P=Ah.call(r,P,!0)),P}let De=ir?y.outerHTML:y.innerHTML;return ir&&ie["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&xe(Sw,y.ownerDocument.doctype.name)&&(De="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
|
|
234
|
+
`+De),mt&&(De=oi(De)),V&&ti?pt(De):De},e.setConfig=function(){let I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};sa(I),Js=!0,Jo=ie,Qo=se},e.clearConfig=function(){Lr=null,Js=!1,Jo=null,Qo=null,V=_e,le=""},e.isValidAttribute=function(I,g,y){Lr||sa({});let T=ue(I),S=ue(g);return typeof y=="string"&&(Su(g,y)||!Ks&&xe(ah,y))?!1:Eu(T,S,y)},e.addHook=function(I,g){typeof g=="function"&&Me(oe,I)&&zo(oe[I],g)},e.removeHook=function(I,g){if(Me(oe,I)){if(g!==void 0){let y=aw(oe[I],g);return y===-1?void 0:cw(oe[I],y,1)[0]}return Zf(oe[I])}},e.removeHooks=function(I){Me(oe,I)&&(oe[I]=[])},e.removeAllHooks=function(){oe=lh()},e}var mh=ph();function Ow(){return import("@gramlot/gramlot/markdown")}var yc=class o extends et{static internalParams=new Set([...et.internalParams,"gramlot","method","params","onError"]);#e=!1;#t=null;constructor({gramlot:e,method:t,directory:r,onError:n}){super({cacheTime:-1,onError:n}),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:n}=e,i,s=new Promise((a,l)=>{i=()=>l(n.reason),n.addEventListener("abort",i,{once:!0})});try{let a=await Promise.race([this.gramlot.rpc.call("data",t,r,{signal:n}),s]);if(n.aborted)throw n.reason;return a}finally{n.removeEventListener("abort",i),this.#t===e&&(this.#t=null)}}prepareValue(e){if(!(e instanceof x))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 o({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()}};var vc={};ee(vc,{Labelbox:()=>js});function js(o){return class extends o{setLabelbox(e){let{box:t,labelBox:r,fieldLabel:n}=e;Object.assign(this,{box:t,labelBox:r,fieldLabel:n}),n.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:n,lbl_value:i,lbl_values:s}=this.parameters,a=s==null?n??"":to(gr(s),i,n);return a?this.control.setAttribute("aria-label",a):this.control.removeAttribute("aria-label"),r}}}js.labelbox=!0;js.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:Li}};var Ic={};ee(Ic,{FieldState:()=>Ac});var Sc={};ee(Sc,{validateInput:()=>Ms,validationParameters:()=>Tc});var Ec=["select","notnull","empty","case","len","min","max","email","regex","call","remote"],$w=["nodup","exist","gridnodup"],Ps=o=>o==null||o==="",xc=(o,e)=>o instanceof Promise?o.then(e):e(o);function Ms(o,e,t={}){let r={value:o,modified:!1,error:null,warnings:[],issues:[],datachanges:[]},n=Object.fromEntries(Object.entries(e).map(([c,u])=>[c.slice(9),u])),i=c=>Object.hasOwn(e,`validate_${c}`)&&e[`validate_${c}`]!=null;for(let c of $w)if(i(c))throw new Error(`validate_${c} requires the DB/grid integration.`);let s=(c,u,d=!1)=>t.invoke(c,e[c],{...n,value:u,result:r,validations:n,userChange:!0,signal:t.signal},d),a=(c,u)=>{if(u==null||u===!0)return;if(typeof u!="boolean"&&typeof u!="string"&&(typeof u!="object"||Array.isArray(u)))throw new TypeError("A validator returns true, false, null, an error code, or a result object/Bag.");let d=`validate_${c}`,f=u instanceof x?Object.fromEntries(u.getNodes().map(w=>[w.label,w.value])):typeof u=="object"?u:{errorcode:u===!1?"error":u};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=zt(p,w=>w?{...n,...f,value:r.value}[w]:r.value);if(m==null)throw new Error("A validation message references a missing value.");let b={rule:c,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=c=>{if(t.signal?.aborted)throw t.signal.reason;if(r.error||c===Ec.length)return r;let u=Ec[c],d=`validate_${u}`,f=e[d];if(!i(u)||f===!1&&u!=="empty")return l(c+1);let h=m=>{if(!m)return l(c+1);let b;return u==="remote"&&r.value==null?l(c+1):(u==="call"?b=s(d,r.value):u==="remote"?b=t.remote(f,{...Rw(e),value:r.value},t.signal):b=jw(u,f,r.value,t),xc(b,w=>{if(t.signal?.aborted)throw t.signal.reason;let _=()=>(a(u,w),l(c+1));return u==="remote"&&e.validate__onResult?xc(t.invoke("validate__onResult",e.validate__onResult,{result:w,value:r.value,validations:n,signal:t.signal}),_):_()}))},p=e[`${d}_if`];return xc(p==null?!0:typeof p=="boolean"?p:s(`${d}_if`,r.value,!0),h)};return l(0)}function Rw(o){let e=new Set(["if","error","warning","iswarning"]);return Object.fromEntries(Object.entries(o).filter(([t])=>t.startsWith("validate_remote_")&&!e.has(t.slice(16))).map(([t,r])=>[t.slice(16),r]))}function Wo(o,e,t={}){return{errorcode:o,message:e,...t}}function jw(o,e,t,r){if(o==="select")return r.selection(t,r.signal);if(o==="notnull")return Ps(t)&&e?Wo("notnull","A value is required.",{required:!0}):null;if(o==="empty")return Ps(t)?{value:e}:null;if(o==="len"){if(typeof e!="string"||!/^(?:\d+|\d+:\d*|:\d+)$/.test(e))throw new Error("Invalid validate_len: use a length or min:max.");let[n,i]=e.split(":"),s=Number(n||0),a=i===void 0?s:i===""?1/0:Number(i);if(s>a)throw new Error("Invalid validate_len: minimum exceeds maximum.");if(Ps(t))return;if(typeof t!="string")throw new TypeError("validate_len requires a text value.");return t.length<s||t.length>a?Wo(s===a?"wrong length":t.length<s?"too short":"too long",s===a?`Enter exactly ${s} characters.`:a===1/0?`Enter at least ${s} characters.`:s===0?`Enter no more than ${a} characters.`:`Enter between ${s} and ${a} characters.`):void 0}if(!Ps(t)){if(o==="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,n=>n[0].toUpperCase()+n.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(o==="min"||o==="max"){let n;if(r.isDecimal?.(t))n=t.comparedTo(e);else if(t instanceof Date&&e instanceof Date)n=t.getTime()-e.getTime();else if(typeof t=="number"&&Number.isFinite(t)&&typeof e=="number"&&Number.isFinite(e))n=t-e;else throw new TypeError(`validate_${o} requires matching numeric or date/time values.`);return(o==="min"?n<0:n>0)?Wo(o,`Value must be ${o==="min"?"at least":"at most"} ${e}.`):void 0}if(o==="email"){if(typeof t!="string")throw new TypeError("validate_email requires a text value.");return/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(t)?null:Wo("email","Check email format.",{iswarning:!0})}if(o==="regex"){if(typeof t!="string"||typeof e!="string")throw new TypeError("validate_regex requires text.");let n=e.trim(),i=n.startsWith("!");return new RegExp(i?n.slice(1):n,"u").test(t)!==i?null:Wo("regex","The value does not match the required pattern.")}}}var Go={dtype:"T",nullable:!0,binding:"read"},Bs={dtype:"B",nullable:!0,binding:"read"},kc={dtype:["T","L","N","R","B","D","H","DH","DHZ"],nullable:!0,binding:"read"},Tc={validate_select:Bs,validate_notnull:{...Bs,default:!1},validate_empty:kc,validate_case:{...Go,enum:["upper","lower","title","capitalize","u","l","t","c"]},validate_len:Go,validate_min:kc,validate_max:kc,validate_email:Bs,validate_regex:Go,validate_call:{dtype:"T",nullable:!0},validate_remote:Go,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(Ec.flatMap(o=>[[`validate_${o}_if`,{dtype:["T","B"],nullable:!0}],[`validate_${o}_iswarning`,Bs],...["error","warning"].map(e=>[`validate_${o}_${e}`,{...Go,qualification:"intl_str"}])]))};var Pw=1800,gh=200;function Ac(o){return class extends o{get supportsFormValidation(){return!0}static validationParameters(e){let t={...Fi(this.gramlotComponent,e),...e};return this.constrained&&t.validate_select==null&&(t.validate_select=!0),t}static get validationExecutor(){return Ms}get validationExecutor(){return this.constructor.validationExecutor}connectedCallback(){super.connectedCallback(),this.pageContext?.form&&this.pageContext.formValidate()}#e=!1;#t;#r;#n;#o=new kr;#i;#s={};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
235
|
input#control[aria-invalid="true"],textarea#control[aria-invalid="true"]{color:var(--gramlot-error,#8c1d18)}
|
|
240
236
|
#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
237
|
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 ${
|
|
238
|
+
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 ${gh}ms ease-out}
|
|
243
239
|
#field-message[data-severity="warning"]{color:var(--gramlot-warning,#805600);border-color:var(--gramlot-warning,#805600);background:var(--gramlot-warning-background,#fff8df)}
|
|
244
240
|
#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.#
|
|
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.#
|
|
241
|
+
@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.#a())})}#a(){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.#a();let e=this.ownerDocument.defaultView;this.message.hidden=!1,this.message.showPopover(),wr(this.message,this.control),this.#r=e.setTimeout(()=>{this.message.hidden||(this.message.setAttribute("data-fading",""),this.#r=e.setTimeout(()=>this.#a(),gh))},Pw),this.#n=new e.AbortController;let t={capture:!0,signal:this.#n.signal};e.addEventListener("scroll",()=>this.#a(),t),e.addEventListener("resize",()=>this.#a(),t)}releaseControl(){this.#o.cancel(),this.#a(),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.#a()}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(`
|
|
242
|
+
`),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.#s,{...this.pageContext,selection:r=>this.validateSelection(r)},Ms,r=>{if(this.#i=null,r.ok)try{t(r.value)}catch(n){r.ok=!1,r.result.error=n.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),n=Object.fromEntries(Object.entries(e).filter(([l])=>l.startsWith("validate_"))),i=new Set([...Object.keys(n),...Object.keys(this.#s)]);!this.pageContext?.form&&([...i].some(l=>!Object.is(n[l],this.#s[l]))||e.disabled||e.readonly)&&this.cancelValidation();let s=[...i].some(l=>!Object.is(n[l],this.#s[l]));this.#s=n,s&&this.pageContext?.form&&this.pageContext.formValidate();for(let l of Object.keys(n))delete r[l];let a=!!this.parameters.validate_notnull;return this.control.setAttribute("aria-required",String(a)),(this.control.localName==="textarea"||this.control.localName==="input"&&["text","password"].includes(this.control.type))&&(this.control.required=a),r}}}Ac.parameters=Tc;var En=new TextEncoder,bh=o=>`export {default} from "./collection.js";
|
|
247
243
|
export * from "./collection.js";
|
|
248
|
-
export const buildId = "${
|
|
249
|
-
`,
|
|
244
|
+
export const buildId = "${o}";
|
|
245
|
+
`,Cc=o=>typeof o=="string"&&o.length>0&&!/[\\\x00-\x1f:?#%]/.test(o)&&!o.split("/").some(e=>!e||e==="."||e==="..");function wh(o,e){if(!o||typeof o.name!="string"||!o.name||!["grammar","commands","module"].every(t=>Cc(o[t]))||!Array.isArray(o.css)||!o.css.every(Cc)||!Array.isArray(o.dependencies)||!o.dependencies.every(t=>typeof t=="string"&&t.length>0)||!Array.isArray(o.files)||!o.files.every(Cc)||new Set(o.files).size!==o.files.length||!(e instanceof Map)||e.size!==o.files.length||o.files.some(t=>!(e.get(t)instanceof Uint8Array))||[o.grammar,o.commands,o.module,...o.css].some(t=>!e.has(t)))throw new TypeError("Invalid collection artifact metadata or file inventory")}async function _h(o,e){wh(o,e);let t=[En.encode("gramlot-build-v1\0")],r=(l,c)=>{let u=typeof c=="string"?En.encode(c):c;t.push(En.encode(`${l}\0${u.length}\0`),u)};for(let l of["name","grammar","commands","module"])r(l,o[l]);for(let l of o.css)r("css",l);for(let l of o.dependencies)r("dependency",l);let n=(l,c)=>{let u=En.encode(l),d=En.encode(c);for(let f=0;f<Math.min(u.length,d.length);f++)if(u[f]!==d[f])return u[f]-d[f];return u.length-d.length};for(let l of[...o.files].sort(n))r("path",l),r("content",l===o.module?bh("__GRAMLOT_BUILD_ID__"):e.get(l));let i=new Uint8Array(t.reduce((l,c)=>l+c.length,0)),s=0;for(let l of t)i.set(l,s),s+=l.length;let a=await crypto.subtle.digest("SHA-256",i);return"sha256:"+[...new Uint8Array(a)].map(l=>l.toString(16).padStart(2,"0")).join("")}async function Bw(o,e){if(wh(o,e),typeof o.buildId!="string"||!/^sha256:[a-f0-9]{64}$/.test(o.buildId))throw new TypeError("Invalid collection buildId");let t=En.encode(bh(o.buildId)),r=e.get(o.module);if(r.length!==t.length||r.some((n,i)=>n!==t[i]))throw new Error("Invalid collection wrapper");if(await _h(o,e)!==o.buildId)throw new Error(`Collection fingerprint mismatch: ${o.name}`)}var Nc={};ee(Nc,{captureVideoFrame:()=>Dc});function Dc(o,e){if(!e.videoWidth||!e.videoHeight)throw new Error("Video image is not ready");let t=o.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 It(o,e,t){return Object.assign(new Error(e,t?{cause:t}:void 0),{code:o})}function Ls(o){return o.name==="NotAllowedError"||o.name==="SecurityError"?It("PERMISSION_DENIED","Camera permission was denied",o):o.name==="NotFoundError"||o.name==="OverconstrainedError"?It("UNAVAILABLE","Camera is unavailable",o):It("FAILED",o.message||"Camera failed",o)}var Fs=()=>It("CANCELLED","Photo capture cancelled"),Oc=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(Fs());if(!this.capabilities.includes("camera"))return Promise.reject(It("UNAVAILABLE","Camera is unavailable"));let t=this.document,r=t.defaultView;return new Promise((n,i)=>{let s=!1,a=null,l=new r.AbortController,c={signal:l.signal},u=t.createElement("dialog");u.className="gramlot-camera-dialog",u.setAttribute("aria-label","Take photo");let d=t.createElement("style");d.textContent=`
|
|
250
246
|
.gramlot-camera-dialog{max-width:calc(100vw - 2rem);max-height:calc(100vh - 2rem);border:1px solid var(--gramlot-border,#d5dde6);
|
|
251
247
|
border-radius:14px;padding:20px;color:var(--gramlot-ink,#202a35);background:var(--gramlot-surface,#fff);
|
|
252
248
|
box-shadow:0 24px 64px #14243a42;font:14px/1.4 system-ui,sans-serif}
|
|
@@ -256,8 +252,8 @@ export const buildId = "${n}";
|
|
|
256
252
|
.gramlot-camera-dialog .actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px}
|
|
257
253
|
.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
254
|
.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 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
|
|
255
|
+
`;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),u.append(d,f,h,p,m);let _=k=>{for(let C of k.getTracks())C.stop()},v=(k,C)=>{s||(s=!0,l.abort(),e.removeEventListener("abort",E),a&&(_(a),a=null),h.srcObject=null,u.open&&u.close(),u.remove(),k?i(k):n(C))},E=()=>v(Fs());e.addEventListener("abort",E,{once:!0}),b.addEventListener("click",E,c),u.addEventListener("cancel",k=>{k.preventDefault(),E()},c),u.addEventListener("close",()=>{s||E()},c);let D=()=>{!s&&h.videoWidth>0&&h.videoHeight>0&&(w.disabled=!1,p.textContent="")};h.addEventListener("loadedmetadata",D,c),w.addEventListener("click",()=>{try{let C=Dc(t,h).toDataURL("image/jpeg",.9);if(!C.startsWith("data:image/jpeg;"))throw new Error("Camera image encoding failed");v(null,{url:C,format:"jpeg"})}catch(k){v(Ls(k))}},c),t.body.append(u);try{u.showModal()}catch(k){v(Ls(k));return}if(e.aborted){E();return}Promise.resolve().then(()=>s?null:r.navigator.mediaDevices.getUserMedia({video:!0,audio:!1})).then(async k=>{if(k){if(s){_(k);return}a=k,h.srcObject=a;for(let C of a.getTracks())C.addEventListener("ended",()=>v(It("UNAVAILABLE","Camera stopped")),c);try{await h.play(),D()}catch(C){v(Ls(C))}}},k=>v(Ls(k)))})}choosePhoto(e){if(e.aborted)return Promise.reject(Fs());let t=this.document,r=t.defaultView;return new Promise((n,i)=>{let s=!1,a=null,l=new r.AbortController,c={signal:l.signal},u=t.createElement("input");u.type="file",u.accept="image/png,image/jpeg,image/webp",u.hidden=!0;let d=(h,p)=>{s||(s=!0,l.abort(),e.removeEventListener("abort",f),a&&a.readyState===1&&a.abort(),u.remove(),h?i(h):n(p))},f=()=>d(Fs());if(e.addEventListener("abort",f,{once:!0}),u.addEventListener("cancel",f,c),u.addEventListener("change",()=>{let h=u.files[0];if(!h||!["image/png","image/jpeg","image/webp"].includes(h.type)){d(It("FAILED","Select a PNG, JPEG or WebP image"));return}a=new r.FileReader,a.onload=()=>d(null,{url:a.result,format:h.type.slice(6)}),a.onerror=()=>d(It("FAILED","Photo could not be read",a.error)),a.readAsDataURL(h)},c),t.body.append(u),e.aborted){f();return}try{u.click()}catch(h){d(It("FAILED","Photo selection failed",h))}})}};var $c=new WeakMap,Mw=/^m_[a-f0-9]+$/;function jc(o,e,{messages:t}){if(!(t instanceof x)||t instanceof N)throw new TypeError("Chat messages require a Data Bag");let r=e.parentNode,n=o.dom.getDomNode(r);if(!n)return;let i=$c.get(r);i||(i={rows:new Map,active:!0},$c.set(r,i),o.src.renderer.onDispose(r,()=>{i.active=!1;for(let u of i.rows.keys())r.getRelativeData(".messageData").popNode(u);i.rows.clear(),$c.delete(r)}));let s=t.getNodes();for(let u of s)if(!Mw.test(u.label)||!["user","assistant"].includes(u.attr.role)||typeof u.attr.author!="string"||!(typeof u.staticValue=="string"||u.staticValue instanceof de))throw new TypeError("Chat messages require a stable label, role, author and string or Gramlot Source");let a=n.scrollHeight-n.clientHeight-n.scrollTop<48,l=[];for(let u of s){let d=i.rows.get(u.label);if(d&&d.value===u.staticValue&&d.role===u.attr.role&&d.author===u.attr.author)continue;let f=new me,h=f.root.article({node_label:u.label,datapath:r.absDatapath(".messageData."+u.label),"data-role":u.attr.role,"aria-label":u.attr.author}),p=Z(h.div());typeof u.staticValue=="string"?f.wrapSource(p).div("=="+JSON.stringify(u.staticValue),{white_space:"pre-wrap"}):p.setValue(o.src.prepareSource(u.staticValue.toTytx()));let m=o.src.prepareSource(f.source);o.src.renderer.validateCandidate(m),l.push({message:u,old:d,child:m.getNode(u.label)})}let c=new Set(s.map(u=>u.label));for(let[u]of i.rows)c.has(u)||(r.value.popNode(u),r.getRelativeData(".messageData").popNode(u),i.rows.delete(u));for(let{message:u,old:d,child:f}of l)d&&r.value.popNode(u.label),d||r.setRelativeData(".messageData."+u.label,new x),o.src.builder.setChild(r.value,f.nodeTag,f.value,{...f.attr,node_label:u.label}),i.rows.set(u.label,{value:u.staticValue,role:u.attr.role,author:u.attr.author});a&&queueMicrotask(()=>{i.active&&(n.scrollTop=n.scrollHeight)})}function vh(o,e,t=null){if(o.getRelativeData(".pending")||o.getRelativeData(".picking")||!o.getRelativeData(".conversation.ready"))return;let r=G();o.SET(".requestId",r),o.SET(".pending",!0),o.SET(".error",""),o.SET(".conversation.request",new x({id:r,action:e,text:t,attachments:j(R(o.getRelativeData(".attachments")))}))}function Pc(o,e){let t=e.getRelativeData(".draft");typeof t!="string"||!t.trim()&&!e.getRelativeData(".attachments").length||vh(e,"send",t)}function Bc(o,e){vh(e,"reset")}function Mc(o,e,{response:t}){if(t!==null){if(!(t instanceof x))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 x),e.SET(".pending",!1),e.SET(".error",t.getItem("error")))}}var Rc=new WeakMap;function Lc(o,e){let t=e.parentNode,r=Rc.get(t);if(!r){let n=o.dom.getDomNode(t);if(!n)return;let i=n.closest("[data-chat-composer]"),s=n.querySelector("textarea"),a=i.querySelector("[data-chat-top]"),l=i.querySelector("[data-chat-toolbar]"),c=n.ownerDocument.defaultView,u=0,d=!0,f=()=>{if(u=0,!d)return;s.style.height="0px";let m=c.getComputedStyle(s),b=parseFloat(m.borderTopWidth)+parseFloat(m.borderBottomWidth),w=Math.max(44,Math.min(180,s.scrollHeight+b));s.style.height=w+"px",s.style.overflowY=s.scrollHeight+b>w?"auto":"hidden";let _=Math.ceil(n.getBoundingClientRect().height+a.getBoundingClientRect().height+l.getBoundingClientRect().height+2);e.getRelativeData(".composerHeight")!==_&&e.SET(".composerHeight",_)},h=()=>{d&&!u&&(u=c.requestAnimationFrame(f))},p=new c.ResizeObserver(h);for(let m of[n,a,l])p.observe(m);o.src.renderer.onDispose(t,()=>{d=!1,p.disconnect(),u&&c.cancelAnimationFrame(u),Rc.delete(t)}),r={schedule:h},Rc.set(t,r)}r.schedule()}var Lw=["txt","md","csv","json","py","js","ts","jsx","tsx","html","css","sql","yaml","yml","xml","sh","toml","log"],yh={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",pdf:"application/pdf",...Object.fromEntries(Lw.map(o=>[o,"text/plain"]))};function Fw(o,e){return new Promise((t,r)=>{let n=new e.FileReader;n.onload=()=>t(n.result.slice(n.result.indexOf(",")+1)),n.onerror=()=>r(new Error("Could not read the selected file.")),n.readAsDataURL(o)})}async function Fc(o,e){if(e.getRelativeData(".pending")||e.getRelativeData(".picking"))return;let t=o.dom.getDomNode(e.parentNode).ownerDocument,r=t.createElement("input");r.type="file",r.multiple=!0,r.accept=Object.keys(yh).map(a=>"."+a).join(","),r.style.display="none",t.body.append(r);let n=!0,i,s=o.src.renderer.onDispose(e.parentNode,()=>{n=!1,r.remove(),i([])});e.SET(".picking",!0),e.SET(".error","");try{let a=await new Promise(u=>{i=u,r.addEventListener("cancel",()=>u([]),{once:!0}),r.addEventListener("change",()=>u([...r.files]),{once:!0}),r.click()});if(!n||!a.length)return;let l=j(R(e.getRelativeData(".attachments")));if(l.length+a.length>5)throw new Error("Choose at most 5 files.");let c=l.getNodes().reduce((u,d)=>u+d.staticValue.getItem("size"),0);for(let u of a){let d=yh[u.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(c+=u.size,!u.size||u.size>f||c>4*1024*1024)throw new Error("Limits: 2 MiB per file, 1 MiB for text, 4 MiB total.");let h=await Fw(u,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_"+G(),new x({name:u.name,mediaType:d,size:u.size,data:h}))}n&&e.SET(".attachments",l)}catch(a){n&&e.SET(".error",a.message)}finally{s(),r.remove(),n&&e.SET(".picking",!1)}}function zc(o,e){e.getRelativeData(".pending")||e.getRelativeData(".attachments").popNode(e.getAttr("attachment_id"))}function qc(o,e,{attachments:t}){let r=e.parentNode;for(let s of[...r.value.getNodes()])s.label.startsWith("a_")&&r.value.popNode(s.label);let n=new me;for(let s of t.getNodes()){let a=s.staticValue,l=n.root.div({node_label:s.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});a.getItem("mediaType").startsWith("image/")&&l.img({src:"data:"+a.getItem("mediaType")+";base64,"+a.getItem("data"),alt:"Attachment preview",width:"36px",height:"36px",object_fit:"cover",border_radius:"6px"}),l.span("=="+JSON.stringify(a.getItem("name")),{font_size:"12px",max_width:"180px",overflow:"hidden",text_overflow:"ellipsis",white_space:"nowrap"}),l.button({icon:"\xD7","aria-label":"Remove "+a.getItem("name"),disabled:"^.pending",class:"button--quiet"}).dataController({func:"chatRemoveAttachment",attachment_id:s.label})}let i=o.src.prepareSource(n.source);o.src.renderer.validateCandidate(i);for(let s of i.getNodes())o.src.builder.setChild(r.value,s.nodeTag,s.value,{...s.attr,node_label:s.label})}var zs=class{constructor({app:e,editor:t,design:r}){this.renderer=e.src.renderer,this.design=r;let n=this.renderer.records.get(r).presentation;this.frame=n.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",n.before(this.frame);let i=this.frame.contentDocument;e.registerDocument(i);let s=i.createElement("style");s.textContent="html,body{margin:0;min-height:100%;} .visual-editor-canvas{min-height:100vh;}",this.styles=i.createElement("style");let a=i.createElement("style");a.textContent=".gramlot-source-selected{outline:2px solid #8ab4f8!important;outline-offset:-2px!important;}",i.head.append(s,this.styles,a),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(`
|
|
256
|
+
`)}dispose(){this.release?.(),this.release=null,this.frame.remove()}};var xh=["string","number","integer","boolean","date","time","datetime","null"];function Uc(o){if(o===null)return"null";if(["string","boolean"].includes(typeof o))return typeof o;if(typeof o=="number"&&Number.isFinite(o))return Number.isSafeInteger(o)?"integer":"number";if(o instanceof Date&&Number.isFinite(o.getTime())){let e=o.toISOString();return e.slice(0,10)==="1970-01-01"?"time":e.endsWith("T00:00:00.000Z")?"date":"datetime"}return null}function qs(o,e){if(e==="null")return"";if(o instanceof Date){let t=o.toISOString();return e==="date"?t.slice(0,10):e==="time"?t.slice(11,23):t}return String(o)}function Vc(o,e){if(o==="string")return e;if(o==="null")return null;if(o==="boolean"&&["true","false"].includes(e))return e==="true";if((o==="number"||o==="integer")&&/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e.trim())){let t=Number(e);if(Number.isFinite(t)&&(o!=="integer"||Number.isSafeInteger(t)))return t}if(["date","time","datetime"].includes(o)&&(o==="date"?/^\d{4}-\d{2}-\d{2}$/:o==="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=o==="date"?`${e}T00:00:00Z`:o==="time"?`1970-01-01T${e}Z`:e,n=new Date(r);if(Number.isFinite(n.getTime())){let i=n.toISOString(),s=r.replace(/Z$/,"").split(/[T:.]/),a=i.replace(/Z$/,"").split(/[T:.]/);if(s.every((l,c)=>c===4?Number(l.padEnd(3,"0"))===Number(a[c]):l===a[c]))return n}}throw new Error(`Invalid ${o} value: ${e||"(empty)"}`)}var Ho=class{#e;#t;#r;#n;#o;#i=null;#s=null;#a=null;#l=!1;constructor({renderer:e,root:t,onSelect:r,canvas:n=e.records.get(t.parentNode)?.presentation}){if(!t?.parentNode||typeof r!="function")throw new TypeError("SourcePicker requires a mounted Source root and onSelect");if(!n||n.nodeType!==1)throw new TypeError("SourcePicker requires a mounted preview");this.#e=e,this.#t=t,this.#r=n,this.#n=r,n.addEventListener("pointerdown",this,!0),n.addEventListener("click",this,!0),this.#o=new n.ownerDocument.defaultView.MutationObserver(()=>this.#c()),this.#o.observe(n,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["class"]}),this.#a=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.#c()}}#c(){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.#s!==r&&(this.#s?.classList.remove("gramlot-source-selected"),this.#s=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.#s?.classList.remove("gramlot-source-selected"),this.#a?.(),this.#a=null,this.#s=null)}};var Wc={base:"",compact:`/* gramlot-compact: professional density profile; load after Base. */
|
|
261
257
|
@layer gramlot.tokens {
|
|
262
258
|
:root {
|
|
263
259
|
color-scheme: light;
|
|
@@ -1505,7 +1501,7 @@ export const buildId = "${n}";
|
|
|
1505
1501
|
:where([role="toolbar"]) { background:Canvas; color:CanvasText; backdrop-filter:none; }
|
|
1506
1502
|
}
|
|
1507
1503
|
}
|
|
1508
|
-
`},
|
|
1504
|
+
`},Gc={default:"",compact:`/* Color-only override: load after the chosen appearance profile. */
|
|
1509
1505
|
@layer gramlot.tokens {
|
|
1510
1506
|
:root {
|
|
1511
1507
|
color-scheme: light;
|
|
@@ -1781,8 +1777,8 @@ export const buildId = "${n}";
|
|
|
1781
1777
|
--gramlot-warning-background: #413820;
|
|
1782
1778
|
}
|
|
1783
1779
|
}
|
|
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};
|
|
1780
|
+
`};function Q(o){for(let e=o;e;e=e.parentNode)if(e.getAttr("visualEditorId"))return e;throw new Error("Operation requires a VisualEditor Source ancestor")}function te(o){return Q(o).fullpath.split(".").slice(1).join(".")+".layout.center.design"}function Oe(o){return Q(o).absDatapath(".")}function Us(o,e){return o.rootBuilder.binding.nodeIds.get(Q(o).getAttr("visualEditorId")+e)}var kh=[["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"]],zw={html:"HTML",components:"Gramlot","components.layout":"Layout","components.inputs":"Inputs"},Gs=Object.fromEntries(["class","style","width","height","padding","margin","color","background"].map(o=>[o,{dtype:"T",nullable:!0}])),Eh=Object.fromEntries(["lbl_","box_"].flatMap(o=>Object.entries(Gs).map(([e,t])=>[o+e,t]))),Hc=[["general","General"],["behaviour","Behaviour"],["validation","Validation"],["styles","Styles"],["container","Container"]],Vs=["T","B","L","R","N","D","H"];function Xc(o,e){return/^(lbl|box)(_|$)/.test(o)?"general":e.has(o)?"container":o.startsWith("validate_")?"validation":Object.hasOwn(Gs,o)||/^(icon|tab)/.test(o)||["design","labelPosition","switch_color","orientation"].includes(o)?"styles":/^(on[A-Z]|get[A-Z]|drag|drop)/.test(o)||["action","command","disabled","readonly","live","beforeClose","open","collapsed","closable","movable","resizable","collapsible","maximizable","maximized","persist","autoCollapse","openOnClick"].includes(o)?"behaviour":"general"}var Ct=(o,e,t=null)=>{let r=o.builder.schema[e];if(!r)throw new Error(`Unknown widget: ${e}`);let n=r._meta?.gramlot_component;return{...(!t||!(t.getValue(!0)instanceof t.builder.source.constructor))&&(!n||n.command&&!Object.hasOwn(n.parameters,"caption"))?{_text:{dtype:"T",nullable:!0}}:{},...Gs,...n?.labelbox?Eh:{},...n?.parameters??{},...o._getMeta("gramlot_component")?.childParameters??{}}},Ws=new WeakMap,Xo=new WeakMap,Yc=class{chatRender(e,t){return jc(this.page,e,t)}chatCompleted(e,t){Mc(this.page,e,t),e.GET(`${Oe(e)}.assistant.active`)&&e.SET(".pending",!0)}chatReset(e){return Bc(this.page,e)}chatResize(e){return Lc(this.page,e)}chatPickAttachments(e){return Fc(this.page,e)}chatRenderAttachments(e,t){return qc(this.page,e,t)}chatRemoveAttachment(e){return zc(this.page,e)}chatSend(e){if(e.GET(".pending")||!e.GET(".conversation.ready")||!e.GET(".draft")?.trim())return;let t=Q(e),r=t.GET(".editingMode"),n=e.builder.source.getNode(te(e)).value.toTytx(),i=r==="code"?t.GET(".codeDocument.content"):n;if(r==="code"&&!t.GET(".codeDocument.writable")){e.SET(".error","Page code editing is disabled by the host");return}let s=(t.GET(".assistantRun.run")??0)+1,a=t.GET(".catalogueScope"),l={commonParameters:Gs,labelboxParameters:Eh,widgets:{}};for(let[c,u]of Object.entries(e.builder.schema)){if(!vn(a,c,u._meta??{})||u._meta?.data_element||u._meta?.subbuilder||u._meta?.container)continue;let d=u._meta?.gramlot_component;l.widgets[c]={parameters:d?.parameters??{},labelbox:!!d?.labelbox,childParameters:d?.childParameters??{}}}return t.SET(".assistantRun",new x({run:s,mode:r,next:0,expected:i,blocked:!1})),t.SET(".assistantStatus","Waiting for editing instructions\u2026"),t.SET(".assistant.context",new x({run:s,mode:r,language:t.GET(".codeDocument.language")??null,codeWritable:t.GET(".codeDocument.writable")===!0,code:r==="code"?i:null,source:n,selected:t.GET(".selection"),schema:JSON.stringify(l)})),Pc(this.page,e)}assistantState(e,{active:t}){if(t===!1){e.SET(`${Oe(e)}.chat.pending`,!1);let r=Q(e);r.GET(".assistantRun.next")===0&&r.SET(".assistantStatus","")}}assistantApply(e,{operations:t}){if(!(t instanceof x))return;let r=Q(e);for(let n of t.getNodes()){if(n.attr.run!==r.GET(".assistantRun.run")||n.attr.index<r.GET(".assistantRun.next"))continue;let i=e.builder.source.getNode(te(e)).value,s=r.GET(".assistantRun.mode"),a=s==="code"?r.GET(".codeDocument.content"):i.toTytx(),l=!1,c=!1,u="";try{if(r.GET(".assistantRun.blocked"))throw c=!0,new Error("The document was replaced during editing");if(n.attr.index!==r.GET(".assistantRun.next"))throw c=!0,new Error("Editing sequence is incomplete");if(a!==r.GET(".assistantRun.expected"))throw c=!0,new Error("Source changed during the request. Remaining edits stopped; send a new instruction.");let d=JSON.parse(n.value);if(s==="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",s==="code"?r.GET(".codeDocument.content"):i.toTytx()),r.SET(".assistantStatus",`Applied ${n.attr.index+1}: ${s==="code"?"Page code draft":d.operation+" "+d.path}`)}catch(d){u=d.message,(s==="code"?r.GET(".codeDocument.content"):i.toTytx())!==a&&(c=!0),r.SET(".assistantRun.blocked",c),r.SET(".assistantStatus",`${c?"Editing stopped":"Rejected"}: ${u}`)}r.SET(".assistantRun.next",n.attr.index+1),r.SET(".assistant.ack",new x({run:n.attr.run,index:n.attr.index,applied:l,stop:c,error:u,mode:s,code:s==="code"?r.GET(".codeDocument.content"):null,source:i.toTytx(),selected:r.GET(".selection")}))}}applySourceEdit(e,t){let{operation:r,path:n,parent:i,tag:s,label:a,attributes:l={},text:c}=t,u=v=>typeof v=="string"&&/^pageRoot(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(v);if(!u(n)||r==="move"&&!u(i))throw new Error(`Use dot-separated paths inside pageRoot: ${JSON.stringify(n)}`);if(!["insert","update","remove","move"].includes(r))throw new Error("Unknown Source editing operation");if(["remove","move"].includes(r)&&n==="pageRoot")throw new Error("The page root is protected");if(r==="insert"&&(typeof a!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a)))throw new Error("Choose an explicit node label");if(!l||typeof l!="object"||Array.isArray(l))throw new Error("Expected scalar attributes");for(let[v,E]of Object.entries(l))if(v.startsWith("_")||/^(connect_|on[A-Z]|script$|formula$|action$|func$|remote_)/.test(v)||["constructor","prototype"].includes(v)||E!==null&&typeof E=="object"||typeof E=="string"&&(E.startsWith("==")||E.includes(":=")))throw new Error(`Unsupported generated attribute: ${v}`);if(c!==void 0&&typeof c!="string")throw new Error("Text must be literal text");let d=e.builder.source.getNode(te(e)),f=e.rootBuilder.binding.gramlot,h=f.src.prepareSource(d.value.toTytx(),d.builder),p=h.getNode(n);if(!p)throw new Error("The Source target no longer exists");let m=p;if(r==="insert"){if(!e.builder.schema[s]||["script","style","iframe","object","embed"].includes(s)||e.builder.schema[s]._meta?.data_element)throw new Error("Choose a visual widget from the catalogue");if(p.value instanceof h.constructor&&p.value.getNode(a))throw new Error("This node label is already in use");m=p.builder.commandOnNode(p,s,c??null,{...l,node_label:a})}else if(r==="update"){if(c!==void 0&&p.value instanceof h.constructor)throw new Error("Text cannot replace a populated container");let v={...p.getAttr()};for(let[E,D]of Object.entries(l))D===null?delete v[E]:v[E]=D;p.setAttr(v,!0,!1,!1),c!==void 0&&p.setValue(c)}else if(r==="remove")p.parentBag.popNode(p.label);else{if(Object.keys(l).length||c!==void 0)throw new Error("Move and property edits must be separate operations");if(i===n||i.startsWith(n+"."))throw new Error("Cannot move a node into itself");let v=h.getNode(i);if(!v)throw new Error("The destination no longer exists");if(v.value instanceof h.constructor&&v.value.getNode(p.label))throw new Error("The destination already contains this label");m=this.appendBranch(v,p,p.label)}let b=v=>{if(v.value instanceof h.constructor){v.builder.validateChildren(v.nodeTag,v.value.getNodes().map(E=>E.nodeTag));for(let E of v.value.getNodes()){for(let[D,k]of Object.entries(Ct(v,E.nodeTag,E)))this.validateParameter(v,E,D,k,E.getAttr(D));b(E)}}};h.getNodes().forEach(b),tt(Q(e).GET(".catalogueScope"),h),f.src.renderer.validateCandidate(h,{replacingNode:d});let w=e.builder.source.getNode(`${te(e)}.${n}`),_=n;r==="insert"?(this.appendBranch(w,m,a),_=`${n}.${a}`):r==="update"?(w.setAttr({...m.getAttr()},!0,!1,!1),c!==void 0&&w.setValue(c)):r==="remove"?(_=n.slice(0,n.lastIndexOf(".")),w.parentBag.popNode(w.label)):(this.applyDrop(e,{item:e.builder.source.getNode(`${te(e)}.${i}`),path:i,dropValues:{"app/source":{path:n}}}),_=`${i}.${w.label}`),e.SET(".sourceSearch",""),e.SET(".selection",_)}initializeCanvasSelection(e){let t=e.rootBuilder.binding.renderer,r=e.builder.source.getNode(te(e)),n=Q(e),i=n.GET(".canvasCss");i!=null&&this.applyCanvasCss(n,i);let s=Ws.get(r);s?.dispose();let a=new Ho({renderer:t,root:r,...Xo.has(r)?{canvas:Xo.get(r).body}:{},onSelect:l=>{e.SET(".sourceSearch",""),e.SET(".selection",l.fullpath.slice(r.fullpath.length+1))}});Ws.set(r,a),s||t.onDispose(r.parentNode,()=>{Ws.delete(r),Xo.delete(r)}),this.highlightSelection(e)}applyCanvasCss(e,t){if(!Array.isArray(t)||t.some(s=>typeof s!="string"))throw new TypeError("canvas CSS must be a list of CSS texts");let r=Q(e),n=r.builder.source.getNode(te(r)),i=Xo.get(n);i||(i=new zs({app:r.rootBuilder.binding.gramlot,editor:r,design:n}),Xo.set(n,i)),i.setCss(t)}setCanvasCss(e,t){let r=Q(e);this.applyCanvasCss(r,t),r.SET(".canvasCss",t),this.initializeCanvasSelection(r)}highlightSelection(e){let t=e.builder.source.getNode(te(e)),r=e.GET(".selection");Ws.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(),n=r==="f8"?"cutBranch":r==="f9"?"pasteBranch":null;!n||t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),this[n](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(te(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 s=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(s)};s(i);let a=new e.builder.source.constructor(null,i.builder);return i.parentBag.popNode(i.label),a.setItem(i.label,i.getValue(!0),{...i.getAttr()},">",!1,!1,"editor",!1,!0,null,i.nodeTag),a.toTytx()}beginClipboard(e,t,r){e.SET(".error","");try{if(!t||t==="pageRoot")throw new Error("Choose a branch below the page root");let n=e.builder.source.getNode(`${te(e)}.${t}`);if(!n)throw new Error("The Source branch no longer exists");let i=this.branchSnapshot(e,t);e.SET(".clipboardDraft",new x({path:t,copy:r,name:n.label,wire:i,parentTag:n.parentNode.nodeTag})),e.SET(".clipboardOpen",!0)}catch(n){e.SET(".error",n.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"),n=e.GET(".clipboardDraft.wire"),i=e.GET(".clipboardDraft.copy"),s=e.builder.source.getNode(`${te(e)}.${r}`);if(!i&&(!s||this.branchSnapshot(e,r)!==n))throw new Error("The branch changed; select it again before cutting");let a=e.GET(".clipboard"),l=1;for(;a.getNode(`branch_${l}`);)l++;let c=`branch_${l}`;a.setItem(c,n,{name:t,parentTag:e.GET(".clipboardDraft.parentTag")}),e.SET(".clipboardSelection",c),e.SET(".clipboardVisible",!0),i||(e.SET(".selection",r.slice(0,r.lastIndexOf("."))),s.parentBag.popNode(s.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 n=t?e.GET(".clipboard").getNode(t):null;if(!n)throw new Error("Choose a saved branch in the clipboard");let i=r?e.builder.source.getNode(`${te(e)}.${r}`):null;if(!i)throw new Error("Choose a destination in the Source tree");let s=e.rootBuilder.binding.gramlot.src.prepareSource(n.getValue(!0),i.builder);tt(Q(e).GET(".catalogueScope"),s);let a=s.getNodes()[0];i.builder.validateParent(a.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):[],a.nodeTag]);let c={...a.getAttr()},u=i.builder.schema[a.nodeTag]._meta?.gramlot_component?.parameters??{},d=i.builder.schema[n.getAttr("parentTag")]?._meta?.gramlot_component?.childParameters??{};for(let w of Object.keys(d))w in u||delete c[w];a.setAttr(c,!0,!1,!1),e.SET(".insertion",new x({parentPath:r,tag:a.nodeTag,clipboard:s.toTytx()}));let f=Ct(i,a.nodeTag),h=Object.entries(f).filter(([w,_])=>_.required&&(c[w]==null||c[w]===""||_.unique));if(!h.length){this.finishPaste(e);return}let p=Us(e,"InsertFields");p.getValue(!0).clear();let m=e.builder.wrapSource(p);m.p(`Paste ${n.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,a.nodeTag,w,_,"insertion",_.default);e.SET(".insertionOpen",!0)}appendBranch(e,t,r){let n=e.builder.source.constructor,i=e.getValue(!0);if(!(i instanceof n)){let s=i;i=new n(null,e.builder),e.builder.promoteNodeValue(e,s,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(`${te(e)}.${t}`);if(!r)throw new Error("The destination no longer exists");let n=e.rootBuilder.binding.gramlot,i=n.src.prepareSource(e.GET(".insertion.clipboard"),r.builder);tt(Q(e).GET(".catalogueScope"),i);let s=i.getNodes()[0],a={...s.getAttr()};for(let[b,w]of Object.entries(Ct(r,s.nodeTag))){if(!w.required)continue;let _=e.GET(`.insertion.types.${b}`),v=e.GET(`.insertion.parameters.${b}${w.enum?"":_?"."+_:""}`);v!=null&&(a[b]=v),this.validateParameter(r,null,b,w,a[b])}s.setAttr(a,!0,!1,!1);let l=r.getValue(!0),c=s.label,u=1;for(;l instanceof e.builder.source.constructor&&l.getNode(c);)c=`${s.label}_${u++}`;let d=e.builder.source.getNode(te(e)),f=n.src.prepareSource(d.getValue(!0).toTytx(),d.builder),h=f.getNode(t);h.builder.validateParent(s.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):[],s.nodeTag]);let m=this.appendBranch(h,s,c);tt(Q(e).GET(".catalogueScope"),f),n.src.renderer.validateCandidate(f,{replacingNode:d}),this.appendBranch(r,m,c),e.SET(".insertionOpen",!1),e.SET(".sourceSearch",""),e.SET(".selection",`${t}.${c}`),e.SET(".fileStatus","Branch pasted")}openCode(e){let t=Q(e);t.SET(".codeOpen",!0),t.SET(".editingMode","code")}async codeSave(e){let t=Q(e),r=t.GET(".codeDocument");if(r.getItem("busy")||!r.getItem("writable"))return;let n=r.getItem("content"),i=r.getItem("revision"),s=!1;if(n===r.getItem("saved"))return;let a=new AbortController,l=this.page.src.renderer.onDispose(t,()=>a.abort());r.setItem("busy",!0),r.setItem("status","Saving Page code\u2026");let c=t.value.getNode("layout.center.design"),u=c.value.toTytx();try{let d=await this.page.rpc.call("data","editor_document_save",{key:t.getAttr("codeDocumentKey"),content:n,revision:i},{signal:a.signal});if(a.signal.aborted)return;r.setItem("revision",d.revision),r.setItem("saved",n),s=!0,r.setItem("status","Page code saved"),u!==c.value.toTytx()?r.setItem("status","Page code saved; Source changed meanwhile. Use Preview saved to replace it."):await this.codeLoadPreview(t,a)}catch(d){a.signal.aborted||r.setItem("status",`${s?"Page code saved; preview failed":"Save failed"}: ${d.message}`)}finally{l(),a.signal.aborted||r.setItem("busy",!1)}}async codePreview(e){let t=Q(e),r=t.GET(".codeDocument");if(r.getItem("busy"))return;let n=new AbortController,i=this.page.src.renderer.onDispose(t,()=>n.abort());r.setItem("busy",!0);try{await this.codeLoadPreview(t,n)}catch(s){n.signal.aborted||r.setItem("status",`Preview failed: ${s.message}`)}finally{i(),n.signal.aborted||r.setItem("busy",!1)}}async codeLoadPreview(e,t){let r=e.GET(".codeDocument"),n=e.value.getNode("layout.center.design"),i=n.value.toTytx(),s=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(n.value.toTytx()!==i)throw new Error("Source changed while preparing preview; it was retained");let a=this.page.src.prepareSource(s,n.builder);tt(e.GET(".catalogueScope"),a),this.page.src.renderer.validateCandidate(a,{replacingNode:n}),e.GET(".assistantRun")&&e.SET(".assistantRun.blocked",!0),e.SET(".selection",null),n.setValue(a,!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(te(e));t.getValue(!0).clear();let r=e.GET(".dataRoot");if(r)e.SET(r,new x);else for(let n of e.rootBuilder.data.getNodes())n.label!=="__editor"&&e.rootBuilder.data.popNode(n.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(n){throw e.SET(".fileStatus",`Open failed: ${n.message}`),n}}initializeDocument(e){let t=Q(e),r=t.builder.source,n=te(t).split("."),i=`${t.getAttr("visualEditorId")}-document`;t.SET(".modified",!1),r.subscribe(i,{any:s=>{n.every((a,l)=>s.pathlist[l]===a)&&t.SET(".modified",!0)}}),t.rootBuilder.binding.renderer.onDispose(t,()=>r.unsubscribe(i,{any:!0}))}currentSource(e){let t=Q(e);return t.builder.source.getNode(te(t)).getValue(!0).toTytx()}markSaved(e){Q(e).SET(".modified",!1)}loadSource(e,{source:t,filename:r}){let n=Q(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=n.rootBuilder.binding.gramlot,s=n.builder.source.getNode(te(n)),a=i.src.prepareSource(t,s.builder),l=a.getNodes();if(l.length!==1||l[0].label!=="pageRoot")throw new Error("Expected one pageRoot Source");tt(n.GET(".catalogueScope"),a),i.src.renderer.validateCandidate(a,{replacingNode:s}),n.GET(".assistantRun")&&n.SET(".assistantRun.blocked",!0),n.SET(".selection",null),s.setValue(a,!0,{_text:null},!0),n.SET(".filename",r),n.SET(".insertionOpen",!1),n.SET(".sourceSearch",""),n.SET(".selection","pageRoot"),this.markSaved(n)}toggleNavigation(e){e.SET(".navigationOpen",e.GET(".navigationOpen")==="close"?!0:"close")}openCatalogue(e){e.SET(`${Oe(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=Q(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:n}){if(!t||!r||!n)return;if(!Object.hasOwn(Wc,t)||!Object.hasOwn(Gc,r)||!["light","dark"].includes(n))throw new Error("Choose a declared theme, palette and color mode");Q(e).SET(".appearanceCss",Wc[t]+`
|
|
1781
|
+
`+Gc[r]),e.rootBuilder.binding.renderer.destination.ownerDocument.documentElement.setAttribute("data-theme",n)}initializeEditor(e,{dataRoot:t}){let r=e.GET(".catalogueScope");if(yn(r),Array.isArray(r)){for(let a of r)if(!e.builder.schema[a])throw new Error(`Unknown catalogue tag: ${a}`)}if(e.SET(".editingMode","source"),e.SET(".clipboard",new x),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 x);else{let a=Oe(e),l=a.split(".").map(()=>"#parent").join(".");e.builder.source.getNode(te(e)).setAttr({datapath:`${a}.${l}`})}let n=new x,i=new Map([["",n]]),s=(a,l)=>{if(i.has(a))return i.get(a);let c=a.split("."),u=c.pop(),d=c.join("."),f=s(d,zw[d]),h=new x;return f.setItem(u,h,{caption:l}),i.set(a,h),h};for(let[a,l,c]of kh)c.split(" ").some(u=>e.builder.schema[u]&&vn(r,u,e.builder.schema[u]._meta??{}))&&s(a,l);for(let[a,l]of Object.entries(e.builder.schema).sort(([c],[u])=>c.localeCompare(u))){if(!vn(r,a,l._meta??{})||l._meta?.data_element||l._meta?.subbuilder||l._meta?.container)continue;let c=l._meta?.gramlot_component?"components":"html",u=kh.find(([f,,h])=>f.startsWith(c+".")&&h.split(" ").includes(a)),d=u?u[0]:`${c}.other`;s(d,u?u[1]:"Other elements").setItem(a,null,{caption:a,tag:a})}e.SET(".catalogue",n)}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:n}){if(n["app/clipboard"]){this.beginPaste(e,n["app/clipboard"].path,r);return}if(n["app/source"]){let f=`${te(e)}.${n["app/source"].path}`,h=`${te(e)}.${r}`,p=e.builder.source.getNode(f);if(!p||f===`${te(e)}.pageRoot`)throw new Error("The page root cannot be moved");if(tt(Q(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),v=_ instanceof w?_.getNodes().filter(D=>D!==p):[];if(_ instanceof w&&_!==b&&_.getNode(p.label))throw new Error("The target already contains this label");let E=m._getMeta("gramlot_component")?.childParameters??{};for(let[D,k]of Object.entries(E)){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&&v.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,[...v.map(D=>D.nodeTag),p.nodeTag]),_===b)b.move(b.getNodes().indexOf(p),v.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=n["app/widget"].tag;this.validateCatalogueTag(e,i),t.builder.validateParent(i,t.nodeTag);let s=t.getValue(!0);t.builder.validateChildren(t.nodeTag,[...s instanceof e.builder.source.constructor?s.getNodes().map(f=>f.nodeTag):[],i]);let a=Ct(t,i),l=Object.entries(a).filter(([,f])=>f.required);if(e.SET(".insertion",new x),e.SET(".insertion.parentPath",r),e.SET(".insertion.tag",i),!l.length){this.applyInsert(e);return}let c=Us(e,"InsertFields");c.getValue(!0).clear();let u=e.builder.wrapSource(c);u.p(`Insert ${i} into ${t.label} [${t.nodeTag}]`,{class:"visual-editor-hint"});let d=u.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=Us(e,"EditorFields");if(r.getValue(!0).clear(),e.SET(".propertyError",""),e.SET(".properties",new x),!t){e.SET(".propertiesOpen",!1);return}let n=e.builder.source.getNode(`${te(e)}.${t}`);if(!n){e.SET(".propertiesOpen",!1);return}let i=n.parentNode,s=Ct(i,n.nodeTag,n);e.SET(".properties.path",t),this.attributeRows(e,n),e.SET(".propertiesTitle",`${n.label} [${n.nodeTag}]`),e.SET(".propertiesHeight",`${Math.min(300,Math.max(180,80+Math.ceil(Object.keys(s).filter(f=>Xc(f,new Set)==="general").length/2)*38))}px`);let a=e.builder.wrapSource(r);t!=="pageRoot"&&a.p(t,{class:"visual-editor-destination"});let l=new Set(Object.keys(i._getMeta("gramlot_component")?.childParameters??{})),c=new Map(Hc.map(([f])=>[f,[]]));for(let f of Object.entries(s))c.get(Xc(f[0],l)).push(f);e.SET(".parameterTab",Hc.find(([f])=>c.get(f).length)[0]);let u=a.tabContainer({selectedPage:`^${Oe(e)}.parameterTab`,class:"visual-parameter-tabs",tabMode:"underline",height:"100%",min_height:0,flex:1});for(let[f,h]of Hc){if(!c.get(f).length)continue;let p=u.contentPane({pageName:f,title:h,overflow:"auto",padding:"4px",min_height:0,...f==="styles"?{nodeId:Q(e).getAttr("visualEditorId")+"StyleAttributes"}:{}});if(f==="styles"){this.attributeFields(e,p,n,"styles");continue}f==="container"&&p.p(`Child parameters of ${i.nodeTag}`,{class:"visual-editor-hint"}),f==="behaviour"&&Object.hasOwn(s,"action")&&p.p("action: use a named Logic method, for example openCatalogue.",{class:"visual-editor-hint"}),f==="behaviour"&&n.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"&&n._getMeta("gramlot_component")?.labelbox&&this.labelboxFields(e,m,n,s);let b,w=([,_])=>{let v=Array.isArray(_.dtype)?_.dtype:[_.dtype];return!_.enum&&!v.some(E=>Vs.includes(E))?2:_.dtype==="B"?1:0};for(let[_,v]of[...c.get(f)].sort((E,D)=>w(E)-w(D))){if(n._getMeta("gramlot_component")?.labelbox&&/^(lbl|box)(_|$)/.test(_))continue;let E=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"})}E=b}let D=_==="_text"?n.getValue(!0):n.getAttr(_);this.parameterField(e,E,n.nodeTag,_,v,"properties",D??v.default)}}let d=u.contentPane({nodeId:Q(e).getAttr("visualEditorId")+"MoreAttributes",pageName:"attributes",title:"More attributes",overflow:"auto",padding:"4px",min_height:0});this.attributeFields(e,d,n),e.SET(".propertiesOpen",!0)}attributeRows(e,t){let r=new x;for(let[n,i]of Object.entries(t.getAttr())){if(n==="_meta")continue;let s=Uc(i),a=s?qs(i,s):"[non-scalar value]";r.setItem(`r${r.length}`,new x({name:n,type:s??"readonly",text:a,original:a}))}e.SET(".properties.attributeRows",r),e.SET(".properties.attributeDraft",new x({name:"",type:"string",text:""})),e.SET(".properties.attributeDraftHidden",!0)}attributeFields(e,t,r,n="attributes"){let i=e.GET(".properties.path"),s=`${Oe(e)}.properties`,a=e.rootBuilder.binding.gramlot.src.renderer,l=new Set(Object.keys(r.parentNode._getMeta("gramlot_component")?.childParameters??{})),c=t.div({class:"visual-editor-attribute-list","aria-label":n==="styles"?"Style attributes":"Node attributes"}),u=c.div({class:"visual-editor-attribute-row visual-editor-attribute-heading"});u.span("Attribute",{class:"visual-editor-attribute-name"});let d=u.div({class:"visual-editor-attribute-value"});d.span("Value"),d.button("+",{action:"beginAttribute",editingPath:i,"aria-label":n==="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"),v=b.label;if(n==="styles"&&Xc(w,l)!=="styles"&&!a._isStyleContribution(w))continue;let E=_!=="readonly",D=c.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:`^${s}.attributeRows.${v}.text`,disabled:!E,"aria-label":`${w} attribute value`,title:E?_:"Non-scalar values are read-only"}),k.button("\xD7",{action:"removeAttribute",attributeRow:v,editingPath:i,disabled:!E,"aria-label":`Remove ${w} attribute`,title:`Remove ${w}`,class:"visual-editor-attribute-command"}),E&&n==="attributes"&&D.dataController({func:"changeAttribute",value:`^${s}.attributeRows.${v}.text`,attributeRow:v,editingPath:i,_userChanges:!0})}let f=c.div({class:"visual-editor-attribute-row",hidden:`^${s}.attributeDraftHidden`,connect_onkeydown:"attributeDraftKey"});f.div({class:"visual-editor-attribute-name"}).input({value:`^${s}.attributeDraft.name`,live:!0,"aria-label":"New attribute name",placeholder:"Attribute name"});let p=f.div({class:"visual-editor-attribute-value"});p.input({value:`^${s}.attributeDraft.text`,live:!0,"aria-label":"New attribute value",placeholder:"Value"});let m=p.select({value:`^${s}.attributeDraft.type`,"aria-label":"New attribute type"});for(let b of xh)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=Q(e);t===r.GET(".selection")&&(r.SET(".properties.attributeDraft",new x({name:"",type:"string",text:""})),r.SET(".properties.attributeDraftHidden",!1),r.SET(".propertyError",""))}cancelAttribute(e){Q(e).SET(".properties.attributeDraftHidden",!0)}attributeDraftKey(e,t){if(t.isComposing||!["Enter","Escape"].includes(t.key))return;t.preventDefault(),t.stopPropagation();let r=Q(e);t.key==="Escape"?this.cancelAttribute(r):this.addAttribute(r,{editingPath:r.GET(".properties.path")})}addAttribute(e,{editingPath:t}){let r=Q(e);if(t===r.GET(".selection")){r.SET(".propertyError","");try{let n=r.GET(".properties.attributeDraft"),i=n.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 s=r.builder.source.getNode(`${te(r)}.${t}`);if(!s)throw new Error("The selected Source node no longer exists");if(Object.hasOwn(s.getAttr(),i))throw new Error(`Duplicate attribute: ${i}`);let a=Vc(n.getItem("type"),String(n.getItem("text")??""));this.writeAttribute(r,s,t,i,a,!1)}catch(n){r.SET(".propertyError",n.message)}}}changeAttribute(e,{attributeRow:t,editingPath:r,value:n}){this.editAttribute(e,{attributeRow:t,editingPath:r,value:n,remove:!1})}removeAttribute(e,{attributeRow:t,editingPath:r}){this.editAttribute(e,{attributeRow:t,editingPath:r,remove:!0})}editAttribute(e,{attributeRow:t,editingPath:r,value:n,remove:i}){let s=Q(e);if(r===s.GET(".selection")){s.SET(".propertyError","");try{let a=s.GET(".properties.attributeRows").getItem(t);if(!a||a.getItem("type")==="readonly")throw new Error("This attribute is not editable");let l=a.getItem("name");if(["_meta","__proto__","constructor","prototype"].includes(l))throw new Error("Unsupported attribute name.");let c=s.builder.source.getNode(`${te(s)}.${r}`);if(!c)throw new Error("The selected Source node no longer exists");let u=c.getAttr(),d=Uc(u[l]);if(!Object.hasOwn(u,l)||d!==a.getItem("type")||qs(u[l],d)!==a.getItem("original"))throw new Error("Attribute changed; select the node again before editing.");let f=i?null:Vc(d,String(n??""));this.writeAttribute(s,c,r,l,f,i,a)}catch(a){s.SET(".propertyError",a.message)}}}writeAttribute(e,t,r,n,i,s,a=null){let l={...t.getAttr()};s?delete l[n]:l[n]=i;let c=Ct(t.parentNode,t.nodeTag,t);c[n]&&this.validateParameter(t.parentNode,t,n,c[n],s?null:i);let u=e.builder.source.getNode(te(e)),d=e.rootBuilder.binding.gramlot,f=d.src.prepareSource(u.getValue(!0).toTytx(),u.builder);if(f.getNode(r).setAttr(l,!0,!1,!1),tt(e.GET(".catalogueScope"),f),d.src.renderer.validateCandidate(f,{replacingNode:u}),t.setAttr(l,!0,!1,!1),a&&!s){let h=qs(i,a.getItem("type"));a.setItem("original",h),a.setItem("text",h);let p=e.GET(`.properties.types.${n}`);c[n]?.enum?e.SET(`.properties.parameters.${n}`,i):p&&e.SET(`.properties.parameters.${n}.${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,n){for(let i of["lbl","box"]){let s=i==="lbl"?"Label":"Box",a=t.div({class:"visual-labelbox-section",grid_column:"1 / -1"}),l=a.div({class:"visual-labelbox-heading"});i==="lbl"?this.parameterField(e,l,r.nodeTag,"lbl",n.lbl,"properties",r.getAttr("lbl")):l.span(s,{class:"visual-labelbox-title"}),l.button({iconSrc:Ce.properties,title:`Edit ${s.toLowerCase()} attributes`,"aria-label":`Edit ${s.toLowerCase()} attributes`,class:"button--quiet",action:"toggleLabelboxAttributes",prefix:i});let c=Object.entries(n).filter(([f])=>f.startsWith(i+"_"));e.SET(`.properties.${i}Hidden`,!0),e.SET(`.properties.${i}Attribute`,"");let u=a.div({class:"visual-labelbox-attribute",hidden:`^${Oe(e)}.properties.${i}Hidden`}),d=u.select({"aria-label":`${s} attribute`,value:`^${Oe(e)}.properties.${i}Attribute`});d.option("Which attribute?",{value:""});for(let[f]of c)d.option(f.slice(i.length+1),{value:f});u.div({node_label:"attributeValue"}).span(""),u.dataController({func:"renderLabelboxAttribute",_init:!0,parameterName:`^${Oe(e)}.properties.${i}Attribute`,editingPath:e.GET(".properties.path")})}}renderLabelboxAttribute(e,{parameterName:t,editingPath:r}){let n=e.parentBag.getNode("attributeValue");if(n.getValue(!0).clear(),!t||r!==e.GET(".selection"))return;let i=e.builder.source.getNode(`${te(e)}.${r}`),s=Ct(i.parentNode,i.nodeTag,i)[t];this.parameterField(e,e.builder.wrapSource(n),i.nodeTag,t,s,"properties",i.getAttr(t)??s.default,!0)}parameterField(e,t,r,n,i,s,a,l=!1){let c=n==="lbl"?"Label":n==="_text"&&e.builder.schema[r]._meta?.gramlot_component?.command?"caption":n==="_text"?"Text":n,u=`${Oe(e)}.${s}.parameters.${n}`;if(i.enum){e.SET(u,a??"");let b=t.select({lbl:l?null:c,lbl_position:"TL",value:`^${u}`,"aria-label":n});b.option("",{value:""});for(let w of i.enum)b.option(String(w),{value:w});s==="properties"&&t.dataController({func:"changeProperty",value:`^${u}`,_userChanges:!0,parameterName:n,editingPath:e.GET(".properties.path")});return}let d=Array.isArray(i.dtype)?i.dtype:i.dtype?[i.dtype]:[],f=d.filter(b=>Vs.includes(b));if(!f.length){t.p(`${c}: no editor is available for this declared type`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}let h="";if(a==null?h=f.length===1?f[0]:"":typeof a=="boolean"&&f.includes("B")?h="B":typeof a=="string"&&f.includes("T")?h="T":typeof a=="number"?h=f.find(b=>["L","R","N"].includes(b))??"":a instanceof Date?h=f.find(b=>["D","H"].includes(b))??"":f.length===1&&f[0]==="N"&&(h="N"),a!=null&&!h){t.p(`${c}: the current value is not editable with these scalar types`,{class:"visual-editor-hint",grid_column:"1 / -1"});return}e.SET(`${Oe(e)}.${s}.types.${n}`,h);for(let b of f)e.SET(`${u}.${b}`,b===h?a??null:null);let p=!l&&(d.length>1||/^(tooltip|_text|action|placeholder|value)$|(_error|_warning|_if)$/.test(n)),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:`${c} type`,lbl_position:"TL",value:`^${Oe(e)}.${s}.types.${n}`,"aria-label":`${n} type`});b.option("Not set",{value:""});for(let w of d)b.option(Vs.includes(w)?w:`${w} (unavailable)`,{value:w,disabled:!Vs.includes(w)});s==="properties"&&m.dataController({func:"changePropertyType",type:`^${Oe(e)}.${s}.types.${n}`,_userChanges:!0,parameterName:n,editingPath:e.GET(".properties.path")})}m.div({node_label:"input"}).span(""),m.dataController({func:"renderParameterInput",_init:!0,type:`^${Oe(e)}.${s}.types.${n}`,parameterName:n,parameterLabel:c,scope:s,compact:l,multiple:d.length>1})}renderParameterInput(e,{type:t,parameterName:r,parameterLabel:n,scope:i,multiple:s,compact:a}){let l=e.parentBag.getNode("input");if(l.getValue(!0).clear(),!t)return;let c=e.builder.wrapSource(l),u=s?`${n} (${t})`:n,d=`^${Oe(e)}.${i}.parameters.${r}.${t}`,f={lbl:a?null:u,lbl_position:"TL",value:d,"aria-label":u};if(t==="B")c.checkbox(f);else if(["L","R","N"].includes(t))c.numberTextBox({...f,dtype:t});else if(t==="D")c.dateTextBox(f);else if(t==="H")c.timeTextBox(f);else if(t==="T"&&/^(lbl|box)_color$/.test(r))c.colorpicker(f);else if(t==="T")c.textbox(f);else throw new Error(`No parameter editor for ${t}`);i==="properties"&&c.dataController({func:"changeProperty",value:d,_userChanges:!0,parameterName:r,editingPath:e.GET(".properties.path")})}changePropertyType(e,{type:t,parameterName:r,editingPath:n}){this.changeProperty(e,{parameterName:r,editingPath:n,value:t?e.GET(`.properties.parameters.${r}.${t}`):null})}changeProperty(e,{value:t,parameterName:r,editingPath:n}){if(n===e.GET(".selection")){e.SET(".propertyError","");try{let i=e.builder.source.getNode(`${te(e)}.${n}`);if(!i)throw new Error("The selected Source node no longer exists");if(r!=="_text"&&Object.is(i.getAttr(r),t))return;let a=Ct(i.parentNode,i.nodeTag,i)[r];if(!a)throw new Error(`Unknown parameter: ${r}`);if(this.validateParameter(i.parentNode,i,r,a,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,c]of[["MoreAttributes","attributes"],["StyleAttributes","styles"]]){let u=Us(e,l);u.getValue(!0).clear(),this.attributeFields(e,e.builder.wrapSource(u),i,c)}}catch(i){e.SET(".propertyError",i.message)}}}validateParameter(e,t,r,n,i){let s=i==null||i==="";if(n.required&&s)throw new Error(`Choose ${r}`);if(!s&&n.enum&&!n.enum.includes(i))throw new Error(`Invalid ${r}`);let a=e.getValue(!0);if(!s&&n.unique&&a instanceof e.builder.source.constructor&&a.getNodes().some(l=>l!==t&&l.getAttr(r)===i))throw new Error(`${r} is already in use`)}validateCatalogueTag(e,t){let r=Q(e).GET(".catalogueScope");if(!vn(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(`${te(e)}.${t}`);if(!r)throw new Error("The target Source node is no longer available");let n=e.GET(".insertion.tag");this.validateCatalogueTag(e,n);let i={};for(let[a,l]of Object.entries(Ct(r,n)).filter(([,c])=>c.required)){let c=e.GET(`.insertion.types.${a}`),u=e.GET(`.insertion.parameters.${a}${l.enum?"":c?"."+c:""}`);this.validateParameter(r,null,a,l,u),i[a]=u}let s=r.builder.commandOnNode(r,n,null,i);e.SET(".insertionOpen",!1),e.SET(".selection",`${t}.${s.label}`)}};var Kc={};ee(Kc,{libraries:()=>Hs,loadLibrary:()=>Th});var Zc=(o,e,t)=>`https://cdn.jsdelivr.net/npm/${o}@${e}/${t}`,Hs=Object.freeze({echarts:Object.freeze({packages:{echarts:"6.1.0"},local:"echarts/dist/echarts.esm.min.mjs",url:Zc("echarts","6.1.0","dist/echarts.esm.min.mjs"),integrity:"sha384-2svH5QplTeBKhRXWxXOJE2P6pRpgnqVq8l8U1dYXUBXvc2zJ/FMMardtnPnnCXnt",format:"module"}),echartsGl:Object.freeze({packages:{"echarts-gl":"2.1.0"},local:"echarts-gl/dist/echarts-gl.min.js",url:null,integrity:null,format:"script",global:"echarts-gl"}),uplot:Object.freeze({packages:{uplot:"1.6.32"},local:"uplot/dist/uPlot.esm.js",url:Zc("uplot","1.6.32","dist/uPlot.esm.js"),integrity:"sha384-iUdBlEO5qc07+gOz+3rq/Besyud+KVIxM+xJEuUBObxLG3C/Dlkz8OYuPUcPrCGP",format:"module"}),uplotStyle:Object.freeze({packages:{uplot:"1.6.32"},local:"uplot/dist/uPlot.min.css",url:Zc("uplot","1.6.32","dist/uPlot.min.css"),integrity:"sha384-IfV0B7MIOYuO95kO9G5ySKPz/85zqFNOAs8iy4tkK5zd9izhJAB8b7lHrwYqqmYE",format:"style"}),plotly:Object.freeze({packages:{"plotly.js-dist-min":"4.2.0"},local:"plotly.js-dist-min",url:null,integrity:null,format:"module"}),vega:Object.freeze({packages:{vega:"6.4.0"},local:"vega",url:null,integrity:null,format:"module"}),writeExcelFile:Object.freeze({packages:{"write-excel-file":"4.1.1"},local:"write-excel-file/browser",url:null,integrity:null,format:"module"}),jodit:Object.freeze({packages:{jodit:"4.18.10"},local:"./components/jodit-engine.js",url:null,integrity:null,format:"module"}),codemirror:Object.freeze({packages:{"@codemirror/autocomplete":"6.20.4","@codemirror/commands":"6.11.1","@codemirror/lang-css":"6.3.1","@codemirror/lang-html":"6.4.12","@codemirror/lang-javascript":"6.2.5","@codemirror/lang-json":"6.0.2","@codemirror/lang-markdown":"6.5.2","@codemirror/lang-python":"6.2.1","@codemirror/lang-sql":"6.10.0","@codemirror/lang-xml":"6.1.0","@codemirror/language":"6.13.1","@codemirror/lint":"6.9.7","@codemirror/search":"6.7.2","@codemirror/state":"6.7.6","@codemirror/view":"6.43.15","@lezer/highlight":"1.2.5","codemirror-lang-typst":"0.6.0"},local:"./components/code-mirror-engine.js",url:null,integrity:null,format:"module"}),prosemirror:Object.freeze({packages:{"prosemirror-commands":"1.6.2","prosemirror-history":"1.4.1","prosemirror-keymap":"1.2.2","prosemirror-markdown":"1.13.1","prosemirror-model":"1.25.12","prosemirror-state":"1.4.3","prosemirror-view":"1.42.6"},local:"./components/prose-mirror-engine.js",url:null,integrity:null,format:"module"}),typst:Object.freeze({packages:{"@myriaddreamin/typst.ts":"0.7.0","@myriaddreamin/typst-ts-web-compiler":"0.7.0","@myriaddreamin/typst-ts-renderer":"0.7.0"},local:"./components/typst-client.js",url:null,integrity:null,format:"module"})});async function Th(o,e,t){if(!Object.hasOwn(Hs,o))throw new Error(`Unknown third-party library: ${o}`);let r=Hs[o],n=r.url!==null&&e.documentElement.getAttribute("data-gramlot-library-source")==="cdn";if(r.format==="style"){if(!n)return(await t()).default;let s=await e.defaultView.fetch(r.url,{integrity:r.integrity});if(!s.ok)throw new Error(`${o}: ${r.url} answered ${s.status}`);return s.text()}let i=n?await import(r.url):await t();return r.format==="script"?e.defaultView[r.global]:i}var qw=Object.freeze({"@genrojs/bag":Za,"@genrojs/builders":rl,"@genrojs/toolbox":Ll,"@genrojs/tytx":Ua,"decimal.js":xa,"@msgpack/msgpack":Mn,dompurify:_c,"./random-id.js":nl,"./format.js":_l,"./libraries.js":Kc,"./media-frame.js":Nc,"./validation-run.js":kl,"./renderer/attributes.js":xl,"./view/labelbox.js":ll,"./stores/column-filter.js":Bl,"./stores/collection-filter.js":zl,"./stores/id-set.js":Wl,"./stores/bag-collection-store.js":Gl,"./stores/bag-collection-view.js":Xl,"./components/bases.js":gl,"./components/choices.js":ol,"./components/choice-field-styles.js":ul,"./components/field-state.js":Ic,"./components/grid-formulas.js":Ql,"./components/grid-structure.js":tc,"./components/labelbox.js":vc,"./components/parameters.js":hl,"./components/popup.js":bl,"./components/validation.js":Sc});export{x as Bag,qe as BagNode,Oc as BrowserCameraProvider,ml as ChoiceGroup,Dn as CommandRegistry,Xt as ComponentCollection,No as DeviceHandler,Mo as DirectoryResolver,Do as DomHandler,Es as Exposed,Ac as FieldState,Lo as FileSystemController,Rr as FileSystemLogic,wn as FramePage,Ro as Gramlot,me as GramlotBuilder,Sr as GramlotHtmlRenderer,Io as GramlotRenderer,uo as GramlotSvgRenderer,Ne as Handler,Nn as HttpTransport,Cs as IdeLogic,Oo as InOut,Ts as IndexLogic,Bo as IndexPage,js as Labelbox,Cn as MobileEnvironment,pl as NativeControl,yc as NavigationResolver,Po as Page,ic as PageBootstrap,Jn as References,pr as RpcError,Qn as RpcHandler,Rt as ServerAdapter,Co as SourceHandler,Os as SourceImport,Ho as SourcePicker,Fo as TreeStore,Ds as TreeStoreLogic,tr as TreeStoreResolver,_n as UploadTarget,$o as UtilitiesHandler,Ns as VisualEditor,Yc as VisualEditorLogic,Mc as chatCompleted,Fc as chatPickAttachments,zc as chatRemoveAttachment,jc as chatRender,qc as chatRenderAttachments,Bc as chatReset,Lc as chatResize,Pc as chatSend,Ss as codeMirrorWithOptions,_h as collectionBuildId,mh as createDOMPurify,Ye as createDecimal,fl as defineCollection,Yt as defineComponent,Hf as fileSystemTree,j as fromTytx,La as fromTytxIter,Hs as libraries,Th as loadLibrary,Ow as loadMarkdown,ac as mountIndexPage,wo as parseDateExpression,qw as sharedModules,Z as sourceTarget,R as toTytx,Bw as verifyCollectionArtifact,Q as visualEditorScope};
|
|
1786
1782
|
/*! Bundled license information:
|
|
1787
1783
|
|
|
1788
1784
|
decimal.js/decimal.mjs:
|