#!/usr/bin/env node var Oh=Object.create;var Ds=Object.defineProperty;var _h=Object.getOwnPropertyDescriptor;var Lh=Object.getOwnPropertyNames;var Fh=Object.getPrototypeOf,Bh=Object.prototype.hasOwnProperty;var a=(e,t)=>Ds(e,"name",{value:t,configurable:!0});var Uh=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Zt=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}};var qh=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Lh(t))!Bh.call(e,o)&&o!==n&&Ds(e,o,{get:()=>t[o],enumerable:!(r=_h(t,o))||r.enumerable});return e};var iu=(e,t,n)=>(n=e!=null?Oh(Fh(e)):{},qh(t||!e||!e.__esModule?Ds(n,"default",{value:e,enumerable:!0}):n,e));var $,x=Uh(()=>{$={environment:"production",baseUrl:"https://texconverter.com",licenseServerUrl:"https://api.texconverter.com",licensePublicKeys:{kNpTbvHCbVq:"kck_ebq5MSquxITgIhAeUaUnBZuGH8K3K-zTGun2t9c"},releasePublicKeys:{kCwvEyZ9WiI:"sKbcXBfaAwt9hWbZRW2-aBJUNCWq2hv9QR56clk4u7s"},isProduction:!0,debug:!1}});var Cn=Zt(Me=>{"use strict";x();function $b(e,t,n){if(n===void 0&&(n=Array.prototype),e&&typeof n.find=="function")return n.find.call(e,t);for(var r=0;r-1}a(Ub,"isValidMimeType");var qb=rr({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=Rb;Me.find=$b;Me.freeze=rr;Me.HTML_BOOLEAN_ATTRIBUTES=fd;Me.HTML_RAW_TEXT_ELEMENTS=ro;Me.HTML_VOID_ELEMENTS=md;Me.hasDefaultHTMLNamespace=Fb;Me.hasOwn=Tn;Me.isHTMLBooleanAttribute=Mb;Me.isHTMLRawTextElement=_b;Me.isHTMLEscapableRawTextElement=Lb;Me.isHTMLMimeType=hd;Me.isHTMLVoidElement=Ob;Me.isValidMimeType=Ub;Me.MIME_TYPE=oo;Me.NAMESPACE=qb});var uo=Zt(lo=>{"use strict";x();var Wb=Cn();function yd(e,t){e.prototype=Object.create(Error.prototype,{constructor:{value:e},name:{value:e.name,enumerable:!0,writable:t}})}a(yd,"extendError");var so=Wb.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"}),bd=Object.keys(so);function wd(e){return typeof e=="number"&&e>=1&&e<=25}a(wd,"isValidDomExceptionCode");function Hb(e){return typeof e=="string"&&e.substring(e.length-so.Error.length)===so.Error}a(Hb,"endsWithError");function ao(e,t){wd(e)?(this.name=bd[e],this.message=t||""):(this.message=e,this.name=Hb(t)?t:so.Error),Error.captureStackTrace&&Error.captureStackTrace(this,ao)}a(ao,"DOMException");yd(ao,!0);Object.defineProperties(ao.prototype,{code:{enumerable:!0,get:a(function(){var e=bd.indexOf(this.name);return wd(e)?e:0},"get")}});var xd={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},Da=Object.entries(xd);for(io=0;io{"use strict";x();function Dd(e){try{typeof e!="function"&&(e=RegExp);var t=new e("\u{1D306}","u").exec("\u{1D306}");return!!t&&t[0].length===2}catch{}return!1}a(Dd,"detectUnicodeSupport");var sr=Dd();function sn(e){if(e.source[0]!=="[")throw new Error(e+" can not be used with chars");return e.source.slice(1,e.source.lastIndexOf("]"))}a(sn,"chars");function or(e,t){if(e.source[0]!=="[")throw new Error("/"+e.source+"/ can not be used with chars_without");if(!t||typeof t!="string")throw new Error(JSON.stringify(t)+" is not a valid search");if(e.source.indexOf(t)===-1)throw new Error('"'+t+'" is not is /'+e.source+"/");if(t==="-"&&e.source.indexOf(t)!==1)throw new Error('"'+t+'" is not at the first postion of /'+e.source+"/");return new RegExp(e.source.replace(t,""),sr?"u":"")}a(or,"chars_without");function Z(e){var t=this;return new RegExp(Array.prototype.slice.call(arguments).map(function(n){var r=typeof n=="string";if(r&&t===void 0&&n==="|")throw new Error("use regg instead of reg to wrap expressions with `|`!");return r?n:n.source}).join(""),sr?"u":"")}a(Z,"reg");function q(e){if(arguments.length===0)throw new Error("no parameters provided");return Z.apply(q,["(?:"].concat(Array.prototype.slice.call(arguments),[")"]))}a(q,"regg");var Gb="\uFFFD",an=/[-\x09\x0A\x0D\x20-\x2C\x2E-\uD7FF\uE000-\uFFFD]/;sr&&(an=Z("[",sn(an),"\\u{10000}-\\u{10FFFF}","]"));var jb=new RegExp("[^"+sn(an)+"]",sr?"u":""),Si=/[\x20\x09\x0D\x0A]/,Xb=sn(Si),ue=Z(Si,"+"),ke=Z(Si,"*"),co=/[:_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;sr&&(co=Z("[",sn(co),"\\u{10000}-\\u{10FFFF}","]"));var zb=sn(co),Pa=Z("[",zb,sn(/[-.0-9\xB7]/),sn(/[\u0300-\u036F\u203F-\u2040]/),"]"),et=Z(co,Pa,"*"),Vb=Z("^",et,"$"),vd=Z(Pa,"+"),Yb=Z("&",et,";"),Kb=q(/&#[0-9]+;|&#x[0-9a-fA-F]+;/),po=q(Yb,"|",Kb),fo=Z("%",et,";"),Ia=q(Z('"',q(/[^%&"]/,"|",fo,"|",po),"*",'"'),"|",Z("'",q(/[^%&']/,"|",fo,"|",po),"*","'")),Zb=q('"',q(/[^<&"]/,"|",po),"*",'"',"|","'",q(/[^<&']/,"|",po),"*","'"),Jb=or(co,":"),Qb=or(Pa,":"),Ca=Z(Jb,Qb,"*"),e0=Z("^",Ca,"$"),mo=Z(Ca,q(":",Ca),"?"),t0=Z("^",mo,"$"),n0=Z("(",mo,")"),ir=q(/"[^"]*"|'[^']*'/),r0=Z(/^<\?/,"(",et,")",q(ue,"(?!",Si,")(",an,"*?)"),"?",/\?>/),kd=/[\x20\x0D\x0Aa-zA-Z0-9-'()+,./:=?;!*#@$_%]/,ho=q('"',kd,'*"',"|","'",or(kd,"'"),"*'"),Td="",o0=Z(Td,q(or(an,"-"),"|",Z("-",or(an,"-"))),"*",Cd),Ed="#PCDATA",i0=q(Z(/\(/,ke,Ed,q(ke,/\|/,ke,mo),"*",ke,/\)\*/),"|",Z(/\(/,ke,Ed,ke,/\)/)),s0=/[?*+]?/,a0=Z(/\([^>]+\)/,s0),l0=q("EMPTY","|","ANY","|",i0,"|",a0),u0=""),d0=Z("NOTATION",ue,/\(/,ke,et,q(ke,/\|/,ke,et),"*",ke,/\)/),p0=Z(/\(/,ke,vd,q(ke,/\|/,ke,vd),"*",ke,/\)/),f0=q(d0,"|",p0),m0=q(/CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS/,"|",f0),h0=q(/#REQUIRED|#IMPLIED/,"|",q(q("#FIXED",ue),"?",Zb)),g0=q(ue,et,ue,m0,ue,h0),y0=""),Na="about:legacy-compat",w0=q('"'+Na+'"',"|","'"+Na+"'"),$a="SYSTEM",Di="PUBLIC",Ti=q(q($a,ue,ir),"|",q(Di,ue,ho,ue,ir)),x0=Z("^",q(q($a,ue,"(?",ir,")"),"|",q(Di,ue,"(?",ho,")",ue,"(?",ir,")"))),v0=Z("^",ho,"$"),k0=Z("^",ir,"$"),E0=q(ue,"NDATA",ue,et),A0=q(Ia,"|",q(Ti,E0,"?")),Nd=""),D0=q(Ia,"|",Ti),T0=Z(Nd,ue,"%",ue,et,ue,D0,ke,">"),C0=q(S0,"|",T0),N0=Z(Di,ue,ho),P0=Z(""),Ra=Z(ke,"=",ke),Ad=/1[.]\d+/,I0=Z(ue,"version",Ra,q("'",Ad,"'","|",'"',Ad,'"')),Sd=/[A-Za-z][-A-Za-z0-9._]*/,$0=q(ue,"encoding",Ra,q('"',Sd,'"',"|","'",Sd,"'")),R0=q(ue,"standalone",Ra,q("'",q("yes","|","no"),"'","|",'"',q("yes","|","no"),'"')),M0=Z(/^<\?xml/,I0,$0,"?",R0,"?",ke,/\?>/),O0="",F0=//,U0=Z(an,"*?",B0),q0=Z(F0,U0);X.chars=sn;X.chars_without=or;X.detectUnicodeSupport=Dd;X.reg=Z;X.regg=q;X.ABOUT_LEGACY_COMPAT=Na;X.ABOUT_LEGACY_COMPAT_SystemLiteral=w0;X.AttlistDecl=b0;X.CDATA_START=_0;X.CDATA_END=L0;X.CDSect=q0;X.Char=an;X.Comment=o0;X.COMMENT_START=Td;X.COMMENT_END=Cd;X.DOCTYPE_DECL_START=O0;X.elementdecl=c0;X.EntityDecl=C0;X.EntityValue=Ia;X.ExternalID=Ti;X.ExternalID_match=x0;X.Name=et;X.Name_exact=Vb;X.NCName_exact=e0;X.NotationDecl=P0;X.Reference=po;X.PEReference=fo;X.PI=r0;X.PUBLIC=Di;X.PubidLiteral=ho;X.PubidLiteral_match=v0;X.QName=mo;X.QName_exact=t0;X.QName_group=n0;X.S=ue;X.SChar_s=Xb;X.S_OPT=ke;X.SYSTEM=$a;X.SystemLiteral=ir;X.SystemLiteral_match=k0;X.InvalidChar=jb;X.UNICODE_REPLACEMENT_CHARACTER=Gb;X.UNICODE_SUPPORT=sr;X.XMLDecl=M0});var Ga=Zt(Te=>{"use strict";x();var st=Cn(),St=st.find,W0=st.hasDefaultHTMLNamespace,lr=st.hasOwn,H0=st.isHTMLMimeType,G0=st.isHTMLRawTextElement,j0=st.isHTMLVoidElement,go=st.MIME_TYPE,Dt=st.NAMESPACE,We=Symbol(),_d=uo(),F=_d.DOMException,Le=_d.DOMExceptionName,De=Ma();function ze(e){if(e!==We)throw new TypeError("Illegal constructor")}a(ze,"checkSymbol");function X0(e){return e!==""}a(X0,"notEmptyString");function z0(e){return e?e.split(/[\t\n\f\r ]+/).filter(X0):[]}a(z0,"splitOnASCIIWhitespace");function V0(e,t){return lr(e,t)||(e[t]=!0),e}a(V0,"orderedSetReducer");function Pd(e){if(!e)return[];var t=z0(e);return Object.keys(t.reduce(V0,{}))}a(Pd,"toOrderedSet");function Y0(e){return function(t){return e&&e.indexOf(t)!==-1}}a(Y0,"arrayIncludes");function Ld(e){if(!De.QName_exact.test(e))throw new F(F.INVALID_CHARACTER_ERR,'invalid character in qualified name "'+e+'"')}a(Ld,"validateQualifiedName");function _a(e,t){Ld(t),e=e||null;var n=null,r=t;if(t.indexOf(":")>=0){var o=t.split(":");n=o[0],r=o[1]}if(n!==null&&e===null)throw new F(F.NAMESPACE_ERR,"prefix is non-null and namespace is null");if(n==="xml"&&e!==st.NAMESPACE.XML)throw new F(F.NAMESPACE_ERR,'prefix is "xml" and namespace is not the XML namespace');if((n==="xmlns"||t==="xmlns")&&e!==st.NAMESPACE.XMLNS)throw new F(F.NAMESPACE_ERR,'either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace');if(e===st.NAMESPACE.XMLNS&&n!=="xmlns"&&t!=="xmlns")throw new F(F.NAMESPACE_ERR,'namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"');return[e,n,r]}a(_a,"validateAndExtract");function dr(e,t){for(var n in e)lr(e,n)&&(t[n]=e[n])}a(dr,"copy");function Ve(e,t){var n=e.prototype;if(!(n instanceof t)){let r=function(){};a(r,"t"),r.prototype=t.prototype,r=new r,dr(n,r),e.prototype=n=r}n.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),n.constructor=e)}a(Ve,"_extends");var Ye={},it=Ye.ELEMENT_NODE=1,ur=Ye.ATTRIBUTE_NODE=2,yo=Ye.TEXT_NODE=3,Fd=Ye.CDATA_SECTION_NODE=4,Bd=Ye.ENTITY_REFERENCE_NODE=5,K0=Ye.ENTITY_NODE=6,La=Ye.PROCESSING_INSTRUCTION_NODE=7,Fa=Ye.COMMENT_NODE=8,ar=Ye.DOCUMENT_NODE=9,Ud=Ye.DOCUMENT_TYPE_NODE=10,ln=Ye.DOCUMENT_FRAGMENT_NODE=11,Z0=Ye.NOTATION_NODE=12,Se=st.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 qd(e,t){if(t.length=0&&e=0){for(var o=t.length-1;r<=o;)t[r]=t[++r];if(t.length=o,ew(t,n),e){var i=e.ownerDocument;i&&jd(i,e,n),n.ownerElement=null}}}a($d,"_removeNamedNode");cr.prototype={length:0,item:Pe.prototype.item,getNamedItem:a(function(e){this._ownerElement&&this._ownerElement._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase());for(var t=0;t0;){var n=t.pop(),r=n.node,o=n.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=0;i--)t.push({node:r.childNodes[i],other:o.childNodes[i]})}return!0},"isEqualNode"),isSameNode:a(function(e){return this===e},"isSameNode"),insertBefore:a(function(e,t){return Pi(this,e,t)},"insertBefore"),replaceChild:a(function(e,t){Pi(this,e,t,Vd),t&&this.removeChild(t)},"replaceChild"),removeChild:a(function(e){return Xd(this,e)},"removeChild"),appendChild:a(function(e){return this.insertBefore(e,null)},"appendChild"),hasChildNodes:a(function(){return this.firstChild!=null},"hasChildNodes"),cloneNode:a(function(e){return Zd(this.ownerDocument||this,this,e)},"cloneNode"),normalize:a(function(){Oe(this,null,{enter:a(function(e){for(var t=e.firstChild;t;){var n=t.nextSibling;if(n!==null&&n.nodeType===yo&&t.nodeType===yo){for(var r=[],o=n;o!==null&&o.nodeType===yo;)r.push(o.data),o=o.nextSibling;for(var i=t.nextSibling;i!==o;){var s=i.nextSibling;i.parentNode=null,i.previousSibling=null,i.nextSibling=null,i=s}t.nextSibling=o,o!==null?o.previousSibling=t:e.lastChild=t,t.appendData(r.join("")),Ua(e.ownerDocument,e),t=o}else t=n}return!0},"enter")})},"normalize"),isSupported:a(function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},"isSupported"),lookupPrefix:a(function(e){for(var t=this;t;){var n=t._nsMap;if(n){for(var r in n)if(lr(n,r)&&n[r]===e)return r}t=t.nodeType==ur?t.ownerDocument:t.parentNode}return null},"lookupPrefix"),lookupNamespaceURI:a(function(e){for(var t=this;t;){var n=t._nsMap;if(n&&lr(n,e))return n[e];t=t.nodeType==ur?t.ownerDocument:t.parentNode}return null},"lookupNamespaceURI"),isDefaultNamespace:a(function(e){var t=this.lookupPrefix(e);return t==null},"isDefaultNamespace"),compareDocumentPosition:a(function(e){if(this===e)return 0;var t=e,n=this,r=null,o=null;if(t instanceof Nn&&(r=t,t=r.ownerElement),n instanceof Nn&&(o=n,n=o.ownerElement,r&&t&&n===t))for(var i=0,s;s=n.attributes[i];i++){if(s===r)return Se.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+Se.DOCUMENT_POSITION_PRECEDING;if(s===o)return Se.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+Se.DOCUMENT_POSITION_FOLLOWING}if(!t||!n||n.ownerDocument!==t.ownerDocument)return Se.DOCUMENT_POSITION_DISCONNECTED+Se.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC+(Id(n.ownerDocument)>Id(t.ownerDocument)?Se.DOCUMENT_POSITION_FOLLOWING:Se.DOCUMENT_POSITION_PRECEDING);if(o&&t===n)return Se.DOCUMENT_POSITION_CONTAINS+Se.DOCUMENT_POSITION_PRECEDING;if(r&&t===n)return Se.DOCUMENT_POSITION_CONTAINED_BY+Se.DOCUMENT_POSITION_FOLLOWING;for(var l=[],u=t.parentNode;u;){if(!o&&u===n)return Se.DOCUMENT_POSITION_CONTAINED_BY+Se.DOCUMENT_POSITION_FOLLOWING;l.push(u),u=u.parentNode}l.reverse();for(var c=[],d=n.parentNode;d;){if(!r&&d===t)return Se.DOCUMENT_POSITION_CONTAINS+Se.DOCUMENT_POSITION_PRECEDING;c.push(d),d=d.parentNode}c.reverse();var p=qd(l,c);for(var f in p.childNodes){var m=p.childNodes[f];if(m===n)return Se.DOCUMENT_POSITION_FOLLOWING;if(m===t)return Se.DOCUMENT_POSITION_PRECEDING;if(c.indexOf(m)>=0)return Se.DOCUMENT_POSITION_FOLLOWING;if(l.indexOf(m)>=0)return Se.DOCUMENT_POSITION_PRECEDING}return 0},"compareDocumentPosition")};function Gd(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}a(Gd,"_xmlEncoder");dr(Ye,ee);dr(Ye,ee.prototype);dr(Se,ee);dr(Se,ee.prototype);function Ni(e,t){Oe(e,null,{enter:a(function(n){return t(n)?Oe.STOP:!0},"enter")})}a(Ni,"_visitNode");function Oe(e,t,n){for(var r=[{node:e,context:t,phase:Oe.ENTER}];r.length>0;){var o=r.pop();if(o.phase===Oe.ENTER){var i=n.enter(o.node,o.context);if(i===Oe.STOP)return Oe.STOP;if(r.push({node:o.node,context:i,phase:Oe.EXIT}),i==null)continue;for(var s=o.node.lastChild;s;)r.push({node:s,context:i,phase:Oe.ENTER}),s=s.previousSibling}else n.exit&&n.exit(o.node,o.context)}}a(Oe,"walkDOM");Oe.STOP=Symbol("walkDOM.STOP");Oe.ENTER=0;Oe.EXIT=1;function Ut(e,t){ze(e);var n=t||{};this.ownerDocument=this,this.contentType=n.contentType||go.XML_APPLICATION,this.type=H0(this.contentType)?"html":"xml"}a(Ut,"Document");function nw(e,t,n){e&&e._inc++;var r=n.namespaceURI;r===Dt.XMLNS&&(t._nsMap[n.prefix?n.localName:""]=n.value)}a(nw,"_onAddAttribute");function jd(e,t,n,r){e&&e._inc++;var o=n.namespaceURI;o===Dt.XMLNS&&delete t._nsMap[n.prefix?n.localName:""]}a(jd,"_onRemoveAttribute");function Ua(e,t,n){if(e&&e._inc){e._inc++;var r=t.childNodes;if(n&&!n.nextSibling)r[r.length++]=n;else{for(var o=t.firstChild,i=0;o;)r[i++]=o,o=o.nextSibling;r.length=i,delete r[r.length]}}}a(Ua,"_onUpdateChild");function Xd(e,t){if(e!==t.parentNode)throw new F(F.NOT_FOUND_ERR,"child's parent is not parent");var n=t.previousSibling,r=t.nextSibling;return n?n.nextSibling=r:e.firstChild=r,r?r.previousSibling=n:e.lastChild=n,Ua(e.ownerDocument,e),t.parentNode=null,t.previousSibling=null,t.nextSibling=null,t}a(Xd,"_removeChild");function rw(e){return e&&(e.nodeType===ee.DOCUMENT_NODE||e.nodeType===ee.DOCUMENT_FRAGMENT_NODE||e.nodeType===ee.ELEMENT_NODE)}a(rw,"hasValidParentNodeType");function ow(e){return e&&(e.nodeType===ee.CDATA_SECTION_NODE||e.nodeType===ee.COMMENT_NODE||e.nodeType===ee.DOCUMENT_FRAGMENT_NODE||e.nodeType===ee.DOCUMENT_TYPE_NODE||e.nodeType===ee.ELEMENT_NODE||e.nodeType===ee.PROCESSING_INSTRUCTION_NODE||e.nodeType===ee.TEXT_NODE)}a(ow,"hasInsertableNodeType");function un(e){return e&&e.nodeType===ee.DOCUMENT_TYPE_NODE}a(un,"isDocTypeNode");function Bt(e){return e&&e.nodeType===ee.ELEMENT_NODE}a(Bt,"isElementNode");function zd(e){return e&&e.nodeType===ee.TEXT_NODE}a(zd,"isTextNode");function Rd(e,t){var n=e.childNodes||[];if(St(n,Bt)||un(t))return!1;var r=St(n,un);return!(t&&r&&n.indexOf(r)>n.indexOf(t))}a(Rd,"isElementInsertionPossible");function Md(e,t){var n=e.childNodes||[];function r(i){return Bt(i)&&i!==t}if(a(r,"hasElementChildThatIsNotChild"),St(n,r))return!1;var o=St(n,un);return!(t&&o&&n.indexOf(o)>n.indexOf(t))}a(Md,"isElementReplacementPossible");function iw(e,t,n){if(!rw(e))throw new F(F.HIERARCHY_REQUEST_ERR,"Unexpected parent node type "+e.nodeType);if(n&&n.parentNode!==e)throw new F(F.NOT_FOUND_ERR,"child not in parent");if(!ow(t)||un(t)&&e.nodeType!==ee.DOCUMENT_NODE)throw new F(F.HIERARCHY_REQUEST_ERR,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}a(iw,"assertPreInsertionValidity1to5");function sw(e,t,n){var r=e.childNodes||[],o=t.childNodes||[];if(t.nodeType===ee.DOCUMENT_FRAGMENT_NODE){var i=o.filter(Bt);if(i.length>1||St(o,zd))throw new F(F.HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(i.length===1&&!Rd(e,n))throw new F(F.HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(Bt(t)&&!Rd(e,n))throw new F(F.HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(un(t)){if(St(r,un))throw new F(F.HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var s=St(r,Bt);if(n&&r.indexOf(s)1||St(o,zd))throw new F(F.HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(i.length===1&&!Md(e,n))throw new F(F.HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(Bt(t)&&!Md(e,n))throw new F(F.HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(un(t)){let l=function(u){return un(u)&&u!==n};if(a(l,"hasDoctypeChildThatIsNotChild"),St(r,l))throw new F(F.HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var s=St(r,Bt);if(n&&r.indexOf(s)")!==-1)throw new F(F.INVALID_CHARACTER_ERR,'data contains "]]>"');var t=new Ri(We);return t.ownerDocument=this,t.childNodes=new Pe,t.appendData(e),t},"createCDATASection"),createProcessingInstruction:a(function(e,t){var n=new _i(We);return n.ownerDocument=this,n.childNodes=new Pe,n.nodeName=n.target=e,n.nodeValue=n.data=t,n},"createProcessingInstruction"),createAttribute:a(function(e){if(!De.QName_exact.test(e))throw new F(F.INVALID_CHARACTER_ERR,'invalid character in name "'+e+'"');return this.type==="html"&&(e=e.toLowerCase()),this._createAttribute(e)},"createAttribute"),_createAttribute:a(function(e){var t=new Nn(We);return t.ownerDocument=this,t.childNodes=new Pe,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},"_createAttribute"),createEntityReference:a(function(e){if(!De.Name_exact.test(e))throw new F(F.INVALID_CHARACTER_ERR,'not a valid xml name "'+e+'"');if(this.type==="html")throw new F("document is an html document",Le.NotSupportedError);var t=new Oi(We);return t.ownerDocument=this,t.childNodes=new Pe,t.nodeName=e,t},"createEntityReference"),createElementNS:a(function(e,t){var n=_a(e,t),r=new qt(We),o=r.attributes=new cr;return r.childNodes=new Pe,r.ownerDocument=this,r.nodeName=t,r.tagName=t,r.namespaceURI=n[0],r.prefix=n[1],r.localName=n[2],o._ownerElement=r,r},"createElementNS"),createAttributeNS:a(function(e,t){var n=_a(e,t),r=new Nn(We);return r.ownerDocument=this,r.childNodes=new Pe,r.nodeName=t,r.name=t,r.specified=!0,r.namespaceURI=n[0],r.prefix=n[1],r.localName=n[2],r},"createAttributeNS")};Ve(Ut,ee);function qt(e){ze(e),this._nsMap=Object.create(null)}a(qt,"Element");qt.prototype={nodeType:it,attributes:null,getQualifiedName:a(function(){return this.prefix?this.prefix+":"+this.localName:this.localName},"getQualifiedName"),_isInHTMLDocumentAndNamespace:a(function(){return this.ownerDocument.type==="html"&&this.namespaceURI===Dt.HTML},"_isInHTMLDocumentAndNamespace"),hasAttributes:a(function(){return!!(this.attributes&&this.attributes.length)},"hasAttributes"),hasAttribute:a(function(e){return!!this.getAttributeNode(e)},"hasAttribute"),getAttribute:a(function(e){var t=this.getAttributeNode(e);return t?t.value:null},"getAttribute"),getAttributeNode:a(function(e){return this._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase()),this.attributes.getNamedItem(e)},"getAttributeNode"),setAttribute:a(function(e,t){this._isInHTMLDocumentAndNamespace()&&(e=e.toLowerCase());var n=this.getAttributeNode(e);n?n.value=n.nodeValue=""+t:(n=this.ownerDocument._createAttribute(e),n.value=n.nodeValue=""+t,this.setAttributeNode(n))},"setAttribute"),removeAttribute:a(function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},"removeAttribute"),setAttributeNode:a(function(e){return this.attributes.setNamedItem(e)},"setAttributeNode"),setAttributeNodeNS:a(function(e){return this.attributes.setNamedItemNS(e)},"setAttributeNodeNS"),removeAttributeNode:a(function(e){return this.attributes.removeNamedItem(e.nodeName)},"removeAttributeNode"),removeAttributeNS:a(function(e,t){var n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},"removeAttributeNS"),hasAttributeNS:a(function(e,t){return this.getAttributeNodeNS(e,t)!=null},"hasAttributeNS"),getAttributeNS:a(function(e,t){var n=this.getAttributeNodeNS(e,t);return n?n.value:null},"getAttributeNS"),setAttributeNS:a(function(e,t,n){var r=_a(e,t),o=r[2],i=this.getAttributeNodeNS(e,o);i?i.value=i.nodeValue=""+n:(i=this.ownerDocument.createAttributeNS(e,t),i.value=i.nodeValue=""+n,this.setAttributeNode(i))},"setAttributeNS"),getAttributeNodeNS:a(function(e,t){return this.attributes.getNamedItemNS(e,t)},"getAttributeNodeNS"),getElementsByClassName:a(function(e){var t=Pd(e);return new At(this,function(n){var r=[];return t.length>0&&Ni(n,function(o){if(o!==n&&o.nodeType===it){var i=o.getAttribute("class");if(i){var s=e===i;if(!s){var l=Pd(i);s=t.every(Y0(l))}s&&r.push(o)}}}),r})},"getElementsByClassName"),getElementsByTagName:a(function(e){var t=(this.nodeType===ar?this:this.ownerDocument).type==="html",n=e.toLowerCase();return new At(this,function(r){var o=[];return Ni(r,function(i){if(!(i===r||i.nodeType!==it))if(e==="*")o.push(i);else{var s=i.getQualifiedName(),l=t&&i.namespaceURI===Dt.HTML?n:e;s===l&&o.push(i)}}),o})},"getElementsByTagName"),getElementsByTagNameNS:a(function(e,t){return new At(this,function(n){var r=[];return Ni(n,function(o){o!==n&&o.nodeType===it&&(e==="*"||o.namespaceURI===e)&&(t==="*"||o.localName==t)&&r.push(o)}),r})},"getElementsByTagNameNS")};Ut.prototype.getElementsByClassName=qt.prototype.getElementsByClassName;Ut.prototype.getElementsByTagName=qt.prototype.getElementsByTagName;Ut.prototype.getElementsByTagNameNS=qt.prototype.getElementsByTagNameNS;Ve(qt,ee);function Nn(e){ze(e),this.namespaceURI=null,this.prefix=null,this.ownerElement=null}a(Nn,"Attr");Nn.prototype.nodeType=ur;Ve(Nn,ee);function cn(e){ze(e)}a(cn,"CharacterData");cn.prototype={data:"",substringData:a(function(e,t){return this.data.substring(e,e+t)},"substringData"),appendData:a(function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},"appendData"),insertData:a(function(e,t){this.replaceData(e,0,t)},"insertData"),deleteData:a(function(e,t){this.replaceData(e,t,"")},"deleteData"),replaceData:a(function(e,t,n){var r=this.data.substring(0,e),o=this.data.substring(e+t);n=r+n+o,this.nodeValue=this.data=n,this.length=n.length},"replaceData")};Ve(cn,ee);function bo(e){ze(e)}a(bo,"Text");bo.prototype={nodeName:"#text",nodeType:yo,splitText:a(function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var r=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r},"splitText")};Ve(bo,cn);function $i(e){ze(e)}a($i,"Comment");$i.prototype={nodeName:"#comment",nodeType:Fa};Ve($i,cn);function Ri(e){ze(e)}a(Ri,"CDATASection");Ri.prototype={nodeName:"#cdata-section",nodeType:Fd};Ve(Ri,bo);function Mi(e){ze(e)}a(Mi,"DocumentType");Mi.prototype.nodeType=Ud;Ve(Mi,ee);function qa(e){ze(e)}a(qa,"Notation");qa.prototype.nodeType=Z0;Ve(qa,ee);function Wa(e){ze(e)}a(Wa,"Entity");Wa.prototype.nodeType=K0;Ve(Wa,ee);function Oi(e){ze(e)}a(Oi,"EntityReference");Oi.prototype.nodeType=Bd;Ve(Oi,ee);function pr(e){ze(e)}a(pr,"DocumentFragment");pr.prototype.nodeName="#document-fragment";pr.prototype.nodeType=ln;Ve(pr,ee);function _i(e){ze(e)}a(_i,"ProcessingInstruction");_i.prototype.nodeType=La;Ve(_i,cn);function Yd(){}a(Yd,"XMLSerializer");Yd.prototype.serializeToString=function(e,t){return Kd.call(e,t)};ee.prototype.toString=Kd;function Kd(e){var t;typeof e=="function"?t={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:e}:e!=null?t={requireWellFormed:!!e.requireWellFormed,splitCDATASections:e.splitCDATASections!==!1,nodeFilter:e.nodeFilter||null}:t={requireWellFormed:!1,splitCDATASections:!0,nodeFilter:null};var n=[],r=this.nodeType===ar&&this.documentElement||this,o=r.prefix,i=r.namespaceURI;if(i&&o==null){var o=r.lookupPrefix(i);if(o==null)var s=[{namespace:i,prefix:null}]}return Ha(this,n,s,t),n.join("")}a(Kd,"nodeSerializeToString");function Od(e,t,n){var r=e.prefix||"",o=e.namespaceURI;if(!o||r==="xml"&&o===Dt.XML||o===Dt.XMLNS)return!1;for(var i=n.length;i--;){var s=n[i];if(s.prefix===r)return s.namespace!==o}return!0}a(Od,"needNamespaceDefine");function Ci(e,t,n,r){if(r&&!De.QName_exact.test(t))throw new F('The attribute name "'+t+'" is not a valid XML QName',Le.InvalidStateError);e.push(" ",t,'="',n.replace(/[<>&"\t\n\r]/g,Gd),'"')}a(Ci,"addSerializedAttribute");function Ha(e,t,n,r){n||(n=[]);var o=r.nodeFilter,i=r.requireWellFormed,s=r.splitCDATASections,l=e.nodeType===ar?e:e.ownerDocument,u=l.type==="html";Oe(e,{ns:n},{enter:a(function(c,d){var p=d.ns;if(o)if(c=o(c),c){if(typeof c=="string")return t.push(c),null}else return null;switch(c.nodeType){case it:var f=c.attributes,m=f.length,h=c.tagName,g=h;if(!u&&!c.prefix&&c.namespaceURI){for(var y,E=0;E=0;v--){var w=p[v];if(w.prefix===""&&w.namespace===c.namespaceURI){y=w.namespace;break}}if(y!==c.namespaceURI)for(var v=p.length-1;v>=0;v--){var w=p[v];if(w.namespace===c.namespaceURI){w.prefix&&(g=w.prefix+":"+h);break}}}if(i&&!De.QName_exact.test(g))throw new F('The element name "'+g+'" is not a valid XML QName',Le.InvalidStateError);t.push("<",g);for(var A=p.slice(),N=0;N"),null;if(t.push(">"),u&&G0(h)){for(var P=c.firstChild;P;)P.data?t.push(P.data):Ha(P,t,A.slice(),r),P=P.nextSibling;return t.push(""),null}return{ns:A,tag:g};case ar:case ln:if(i&&c.nodeType===ar&&c.documentElement==null)throw new F("The Document has no documentElement",Le.InvalidStateError);return{ns:p};case ur:return Ci(t,c.name,c.value,i),null;case yo:if(i&&De.InvalidChar.test(c.data))throw new F("The Text node data contains characters outside the XML Char production",Le.InvalidStateError);return t.push(c.data.replace(/[<&>]/g,Gd)),null;case Fd:if(i&&c.data.indexOf("]]>")!==-1)throw new F('The CDATASection data contains "]]>"',Le.InvalidStateError);return s?t.push(De.CDATA_START,c.data.replace(/]]>/g,"]]]]>"),De.CDATA_END):t.push(De.CDATA_START,c.data,De.CDATA_END),null;case Fa:if(i){if(De.InvalidChar.test(c.data))throw new F("The comment node data contains characters outside the XML Char production",Le.InvalidStateError);if(c.data.indexOf("--")!==-1||c.data[c.data.length-1]==="-")throw new F('The comment node data contains "--" or ends with "-"',Le.InvalidStateError)}return t.push(De.COMMENT_START,c.data,De.COMMENT_END),null;case Ud:var _=c.publicId,M=c.systemId;if(i){if(!De.Name_exact.test(c.name))throw new F('The doctype name "'+c.name+'" is not a valid XML Name',Le.InvalidStateError);if(_&&!De.PubidLiteral_match.test(_))throw new F("DocumentType publicId is not a valid PubidLiteral",Le.InvalidStateError);if(M&&M!=="."&&!De.SystemLiteral_match.test(M))throw new F("DocumentType systemId is not a valid SystemLiteral",Le.InvalidStateError);if(c.internalSubset&&c.internalSubset.indexOf("]>")!==-1)throw new F('DocumentType internalSubset contains "]>"',Le.InvalidStateError)}return t.push(De.DOCTYPE_DECL_START," ",c.name),_?(t.push(" ",De.PUBLIC," ",_),M&&M!=="."&&t.push(" ",M)):M&&M!=="."&&t.push(" ",De.SYSTEM," ",M),c.internalSubset&&t.push(" [",c.internalSubset,"]"),t.push(">"),null;case La:if(i){if(!De.NCName_exact.test(c.target)||c.target.toLowerCase()==="xml")throw new F('The processing instruction target "'+c.target+'" is not a valid XML NCName or is reserved',Le.InvalidStateError);if(De.InvalidChar.test(c.data))throw new F("The ProcessingInstruction data contains characters outside the XML Char production",Le.InvalidStateError);if(c.data.indexOf("?>")!==-1)throw new F('The ProcessingInstruction data contains "?>"',Le.InvalidStateError)}return t.push(""),null;case Bd:if(i&&!De.Name_exact.test(c.nodeName))throw new F('The entity reference name "'+c.nodeName+'" is not a valid XML Name',Le.InvalidStateError);return t.push("&",c.nodeName,";"),null;default:return t.push("??",c.nodeName),null}},"enter"),exit:a(function(c,d){d&&d.tag&&t.push("")},"exit")})}a(Ha,"serializeToString");function aw(e,t,n){var r;return Oe(t,null,{enter:a(function(o,i){var s=o.cloneNode(!1);s.ownerDocument=e,s.parentNode=null,i===null?r=s:i.appendChild(s);var l=o.nodeType===ur||n;return l?s:null},"enter")}),r}a(aw,"importNode");function Zd(e,t,n){var r;return Oe(t,null,{enter:a(function(o,i){var s=new o.constructor(We);for(var l in o)if(lr(o,l)){var u=o[l];typeof u!="object"&&u!=s[l]&&(s[l]=u)}o.childNodes&&(s.childNodes=new Pe),s.ownerDocument=e;var c=n;switch(s.nodeType){case it:var d=o.attributes,p=s.attributes=new cr,f=d.length;p._ownerElement=s;for(var m=0;m{"use strict";x();var Qd=Cn().freeze;wo.XML_ENTITIES=Qd({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});wo.HTML_ENTITIES=Qd({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:` `,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"});wo.entityMap=wo.HTML_ENTITIES});var up=Zt(Fi=>{"use strict";x();var yr=Cn(),V=Ma(),op=uo(),lw=yr.isHTMLEscapableRawTextElement,uw=yr.isHTMLMimeType,cw=yr.isHTMLRawTextElement,ko=yr.hasOwn,tp=yr.NAMESPACE,dw=op.ParseError,pw=op.DOMException,fr=0,dn=1,mr=2,xo=3,hr=4,gr=5,vo=6,Li=7;function ip(){}a(ip,"XMLReader");ip.prototype={parse:a(function(e,t,n){var r=this.domBuilder;r.startDocument(),gw(t,t=Object.create(null)),fw(e,t,n,r,this.errorHandler),r.endDocument()},"parse")};var ja=/&#?\w+;?/g;function fw(e,t,n,r,o){var i=uw(r.mimeType);e.indexOf(V.UNICODE_REPLACEMENT_CHARACTER)>=0&&o.warning("Unicode replacement character detected, source encoding issues?");function s(z){if(z>65535){z-=65536;var Ce=55296+(z>>10),Ln=56320+(z&1023);return String.fromCharCode(Ce,Ln)}else return String.fromCharCode(z)}a(s,"fixedFromCharCode");function l(z){var Ce=z[z.length-1]===";"?z:z+";";if(!i&&Ce!==z)return o.error("EntityRef: expecting ;"),z;var Ln=V.Reference.exec(Ce);if(!Ln||Ln[0].length!==Ce.length)return o.error("entity not matching Reference production: "+z),z;var Yt=Ce.slice(1,-1);return ko(n,Yt)?n[Yt]:Yt.charAt(0)==="#"?s(parseInt(Yt.substring(1).replace("x","0x"))):(o.error("entity not found:"+z),z)}a(l,"entityReplacer");function u(z){if(z>y){var Ce=e.substring(y,z).replace(ja,l);f&&m(y),r.characters(Ce,0,z-y),y=z}}a(u,"appendText");var c=0,d=0,p=/\r\n?|\n|$/g,f=r.locator;function m(z,Ce){for(;z>=d&&(Ce=p.exec(e));)c=d,d=Ce.index+Ce[0].length,f.lineNumber++;f.columnNumber=z-c+1}a(m,"position");for(var h=[{currentNSMap:t}],g=[],y=0;;){try{var E=e.indexOf("<",y);if(E<0){if(!i&&g.length>0)return o.fatalError("unclosed xml tag(s): "+g.join(", "));if(!e.substring(y).match(/^\s*$/)){var v=r.doc,w=v.createTextNode(e.substring(y));if(v.documentElement)return o.error("Extra content at the end of the document");v.appendChild(w),r.currentElement=w}return}if(E>y){var A=e.substring(y,E);!i&&g.length===0&&(A=A.replace(new RegExp(V.S_OPT.source,"g"),""),A&&o.error("Unexpected content outside root element: '"+A+"'")),u(E)}switch(e.charAt(E+1)){case"/":var j=e.indexOf(">",E+2),N=e.substring(E+2,j>0?j:void 0);if(!N)return o.fatalError("end tag name missing");var S=V.reg("^",V.QName_group,V.S_OPT,"$"),k=j>0&&S.exec(N);if(!k){var T=j>0&&V.reg("^",V.QName_group).exec(N);if(i&&T)o.warning('end tag name contains invalid trailing characters: "'+N+'"'),k=T;else if(T&&new RegExp(S.source,S.flags+"m").test(N))o.error('end tag name is followed by a line break and trailing content: "'+N+'"'),k=T;else return o.fatalError('end tag name contains invalid characters: "'+N+'"')}if(!r.currentElement&&!r.doc.documentElement)return;var O=g[g.length-1]||r.currentElement.tagName||r.doc.documentElement.tagName||"";if(O!==k[1]){var C=k[1].toLowerCase();if(!i||O.toLowerCase()!==C)return o.fatalError('Opening and ending tag mismatch: "'+O+'" != "'+N+'"')}var D=h.pop();g.pop();var P=D.localNSMap;if(r.endElement(D.uri,D.localName,O),P)for(var _ in P)ko(P,_)&&r.endPrefixMapping(_);j++;break;case"?":f&&m(E),j=bw(e,E,r,o);break;case"!":f&&m(E),j=ap(e,E,r,o,i);break;default:f&&m(E);var M=new lp,W=h[h.length-1].currentNSMap,j=mw(e,E,M,W,l,o,i),we=M.length;if(M.closed||(i&&yr.isHTMLVoidElement(M.tagName)?M.closed=!0:g.push(M.tagName)),f&&we){for(var re=np(f,{}),U=0;Uy?y=j:u(Math.max(E,y)+1)}}a(fw,"parse");function np(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}a(np,"copyLocator");function mw(e,t,n,r,o,i,s){function l(m,h,g){if(ko(n.attributeNames,m))return i.fatalError("Attribute "+m+" redefined");if(!s&&h.indexOf("<")>=0)return i.fatalError("Unescaped '<' not allowed in attributes values");n.addValue(m,h.replace(/[\t\n\r]/g," ").replace(ja,o),g)}a(l,"addAttribute");for(var u,c,d=++t,p=fr;;){var f=e.charAt(d);if(p===fr&&f==="<")throw new Error("unexpected < in tag name: "+e.slice(t,d));switch(f){case"=":if(p===dn)u=e.slice(t,d),p=xo;else if(p===mr)p=xo;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(p===xo||p===dn)if(p===dn&&(i.warning('attribute value must after "="'),u=e.slice(t,d)),t=d+1,d=e.indexOf(f,t),d>0)c=e.slice(t,d),l(u,c,t-1),p=gr;else throw new Error("attribute value no end '"+f+"' match");else if(p==hr)c=e.slice(t,d),l(u,c,t),i.warning('attribute "'+u+'" missed start quot('+f+")!!"),t=d+1,p=gr;else throw new Error('attribute value must after "="');break;case"/":switch(p){case fr:n.setTagName(e.slice(t,d));case gr:case vo:case Li:p=Li,n.closed=!0;case hr:case dn:break;case mr:n.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return i.error("unexpected end of input"),p==fr&&n.setTagName(e.slice(t,d)),d;case">":switch(p){case fr:n.setTagName(e.slice(t,d));case gr:case vo:case Li:break;case hr:case dn:c=e.slice(t,d),c.slice(-1)==="/"&&(n.closed=!0,c=c.slice(0,-1));case mr:p===mr&&(c=u),p==hr?(i.warning('attribute "'+c+'" missed quot(")!'),l(u,c,t)):(s||i.warning('attribute "'+c+'" missed value!! "'+c+'" instead!!'),l(c,c,t));break;case xo:if(!s)return i.fatalError(`AttValue: ' or " expected`)}return d;case"\x80":f=" ";default:if(f<=" ")switch(p){case fr:n.setTagName(e.slice(t,d)),p=vo;break;case dn:u=e.slice(t,d),p=mr;break;case hr:var c=e.slice(t,d);i.warning('attribute "'+c+'" missed quot(")!!'),l(u,c,t);case gr:p=vo;break}else switch(p){case mr:s||i.warning('attribute "'+u+'" missed value!! "'+u+'" instead2!!'),l(u,u,t),t=d,p=dn;break;case gr:i.warning('attribute space is required"'+u+'"!!');case vo:p=dn,t=d;break;case xo:p=hr,t=d;break;case Li:throw new Error("elements closed character '/' and '>' must be connected to")}}d++}}a(mw,"parseElementStartPart");function rp(e,t,n){for(var r=e.tagName,o=null,p=e.length;p--;){var i=e[p],s=i.qName,l=i.value,f=s.indexOf(":");if(f>0)var u=i.prefix=s.slice(0,f),c=s.slice(f+1),d=u==="xmlns"&&c;else c=s,u=null,d=s==="xmlns"&&"";i.localName=c,d!==!1&&(o==null&&(o=Object.create(null),n=Object.create(n)),n[d]=o[d]=l,i.uri=tp.XMLNS,t.startPrefixMapping(d,l))}for(var p=e.length;p--;)i=e[p],i.prefix&&(i.prefix==="xml"&&(i.uri=tp.XML),i.prefix!=="xmlns"&&(i.uri=n[i.prefix]));var f=r.indexOf(":");f>0?(u=e.prefix=r.slice(0,f),c=e.localName=r.slice(f+1)):(u=null,c=e.localName=r);var m=e.uri=n[u||""];if(t.startElement(m,c,r,e),e.closed){if(t.endElement(m,c,r),o)for(u in o)ko(o,u)&&t.endPrefixMapping(u)}else return e.currentNSMap=n,e.localNSMap=o,!0}a(rp,"appendElement");function hw(e,t,n,r,o){var i=lw(n);if(i||cw(n)){var s=new RegExp("","ig");s.lastIndex=t;var l=s.exec(e),u=l?l.index:-1;if(u<0)return t+1;var c=e.substring(t+1,u);return i&&(c=c.replace(ja,r)),o.characters(c,0,c.length),u}return t+1}a(hw,"parseHtmlSpecialContent");function gw(e,t){for(var n in e)ko(e,n)&&(t[n]=e[n])}a(gw,"_copy");function sp(e,t){var n=t;function r(d){return d=d||0,e.charAt(n+d)}a(r,"char");function o(d){d=d||1,n+=d}a(o,"skip");function i(){for(var d=0;n"?r.fatalError("doctype not terminated with > at position "+i.getIndex()):(i.skip(1),n.startDTD(u.name,u.publicId,u.systemId,u.internalSubset),n.endDTD(),i.getIndex())}default:return r.fatalError('Not well-formed XML starting with "0)return r.fatalError("processing instruction at position "+t+" is an xml declaration which is only at the start of the document");if(!V.XMLDecl.test(e.substring(t)))return r.fatalError("xml declaration is not well-formed")}return n.processingInstruction(o[1],o[2]),t+o[0].length}a(bw,"parseProcessingInstruction");function lp(){this.attributeNames=Object.create(null)}a(lp,"ElementAttributes");lp.prototype={setTagName:a(function(e){if(!V.QName_exact.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},"setTagName"),addValue:a(function(e,t,n){if(!V.QName_exact.test(e))throw new Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:n}},"addValue"),length:0,getLocalName:a(function(e){return this[e].localName},"getLocalName"),getLocator:a(function(e){return this[e].locator},"getLocator"),getQName:a(function(e){return this[e].qName},"getQName"),getURI:a(function(e){return this[e].uri},"getURI"),getValue:a(function(e){return this[e].value},"getValue")};Fi.XMLReader=ip;Fi.parseUtils=sp;Fi.parseDoctypeCommentOrCData=ap});var gp=Zt(wr=>{"use strict";x();var Pn=Cn(),ww=Ga(),xw=uo(),cp=ep(),vw=up(),kw=ww.DOMImplementation,Ew=Pn.hasDefaultHTMLNamespace,Aw=Pn.isHTMLMimeType,Sw=Pn.isValidMimeType,fp=Pn.MIME_TYPE,Xa=Pn.NAMESPACE,dp=xw.ParseError,Dw=vw.XMLReader;function mp(e){return e.replace(/\r[\n\u0085]/g,` `).replace(/[\r\u0085\u2028\u2029]/g,` `)}a(mp,"normalizeLineEndings");function hp(e){if(e=e||{},e.locator===void 0&&(e.locator=!0),this.assign=e.assign||Pn.assign,this.domHandler=e.domHandler||Ui,this.onError=e.onError||e.errorHandler,e.errorHandler&&typeof e.errorHandler!="function")throw new TypeError("errorHandler object is no longer supported, switch to onError!");e.errorHandler&&e.errorHandler("warning","The `errorHandler` option has been deprecated, use `onError` instead!",this),this.normalizeLineEndings=e.normalizeLineEndings||mp,this.locator=!!e.locator,this.xmlns=this.assign(Object.create(null),e.xmlns)}a(hp,"DOMParser");hp.prototype.parseFromString=function(e,t){if(!Sw(t))throw new TypeError('DOMParser.parseFromString: the provided mimeType "'+t+'" is not valid.');var n=this.assign(Object.create(null),this.xmlns),r=cp.XML_ENTITIES,o=n[""]||null;Ew(t)?(r=cp.HTML_ENTITIES,o=Xa.HTML):t===fp.XML_SVG_IMAGE&&(o=Xa.SVG),n[""]=o,n.xml=n.xml||Xa.XML;var i=new this.domHandler({mimeType:t,defaultNamespace:o,onError:this.onError}),s=this.locator?{}:void 0;this.locator&&i.setDocumentLocator(s);var l=new Dw;l.errorHandler=i,l.domBuilder=i;var u=!Pn.isHTMLMimeType(t);return u&&typeof e!="string"&&l.errorHandler.fatalError("source is not a string"),l.parse(this.normalizeLineEndings(String(e)),n,r),i.doc.documentElement||l.errorHandler.fatalError("missing root element"),i.doc};function Ui(e){var t=e||{};this.mimeType=t.mimeType||fp.XML_APPLICATION,this.defaultNamespace=t.defaultNamespace||null,this.cdata=!1,this.currentElement=void 0,this.doc=void 0,this.locator=void 0,this.onError=t.onError}a(Ui,"DOMHandler");function br(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}a(br,"position");Ui.prototype={startDocument:a(function(){var e=new kw;this.doc=Aw(this.mimeType)?e.createHTMLDocument(!1):e.createDocument(this.defaultNamespace,"")},"startDocument"),startElement:a(function(e,t,n,r){var o=this.doc,i=o.createElementNS(e,n||t),s=r.length;Bi(this,i),this.currentElement=i,this.locator&&br(this.locator,i);for(var l=0;l=t+n||t?new java.lang.String(e,t,n)+"":e}a(pp,"_toString");"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){Ui.prototype[e]=function(){return null}});function Bi(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}a(Bi,"appendElement");function Cw(e){if(e==="error")throw"onErrorStopParsing"}a(Cw,"onErrorStopParsing");function Nw(){throw"onWarningStopParsing"}a(Nw,"onWarningStopParsing");wr.__DOMHandler=Ui;wr.DOMParser=hp;wr.normalizeLineEndings=mp;wr.onErrorStopParsing=Cw;wr.onWarningStopParsing=Nw});var za=Zt(te=>{"use strict";x();var xr=Cn();te.assign=xr.assign;te.hasDefaultHTMLNamespace=xr.hasDefaultHTMLNamespace;te.isHTMLMimeType=xr.isHTMLMimeType;te.isValidMimeType=xr.isValidMimeType;te.MIME_TYPE=xr.MIME_TYPE;te.NAMESPACE=xr.NAMESPACE;var qi=uo();te.DOMException=qi.DOMException;te.DOMExceptionName=qi.DOMExceptionName;te.ExceptionCode=qi.ExceptionCode;te.ParseError=qi.ParseError;var Ie=Ga();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 Wi=gp();te.DOMParser=Wi.DOMParser;te.normalizeLineEndings=Wi.normalizeLineEndings;te.onErrorStopParsing=Wi.onErrorStopParsing;te.onWarningStopParsing=Wi.onWarningStopParsing});x();import{isSea as VE}from"node:sea";import{getCACertificates as Ch,setDefaultCACertificates as YE}from"node:tls";x();import{readFile as bh,writeFile as Kl,mkdir as Zl}from"node:fs/promises";import{readFileSync as BE}from"node:fs";import{dirname as Or,join as Jl,resolve as Fo,basename as Mr,extname as Ql,sep as UE}from"node:path";x();x();import{inflateRawSync as Hh,deflateRawSync as Gh}from"node:zlib";var It={async inflateRaw(e){return new Uint8Array(Hh(e))},async deflateRaw(e){return new Uint8Array(Gh(e,{level:9}))}};x();x();x();x();var su=/[A-Za-z]/,qo=/[0-9]/;function Wo(e){let t=[],n=0,r=e.length,o=a((i,s,l,u)=>{t.push({type:i,value:s,start:l,end:u})},"push");for(;n=r){o("command","",u,n);break}if(e[n]==="\\"){n++,o("newline","\\\\",u,n);continue}if(su.test(e[n])){let d=n;for(;d65535?2:1;o("char",e.slice(n,n+l),n,n+l),n+=l}return o("eof","",r,r),t}a(Wo,"tokenize");x();x();function au(e,t){let n=1,r=1,o=Math.max(0,Math.min(t,e.length));for(let i=0;i"}`),i&&s.push(`Suggested fix: ${i}`),s.join(` `)}};x();var jh={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",omicron:"\u03BF",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03C6",varphi:"\u03D5",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9"},Xh={Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9"},zh={pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\u22C5",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2219",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",setminus:"\u2216",wedge:"\u2227",vee:"\u2228",cup:"\u222A",cap:"\u2229",amalg:"\u2A3F"},Vh={leq:"\u2264",le:"\u2264",geq:"\u2265",ge:"\u2265",neq:"\u2260",ne:"\u2260",approx:"\u2248",equiv:"\u2261",sim:"\u223C",simeq:"\u2243",cong:"\u2245",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",subseteq:"\u2286",supset:"\u2283",supseteq:"\u2287",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",succ:"\u227B",ll:"\u226A",gg:"\u226B",asymp:"\u224D",doteq:"\u2250",leqslant:"\u2A7D",geqslant:"\u2A7E",nleq:"\u2270",ngeq:"\u2271",nless:"\u226E",ngtr:"\u226F",nsubseteq:"\u2288",nsupseteq:"\u2289",subsetneq:"\u228A",supsetneq:"\u228B",ncong:"\u2247",nsim:"\u2241",nparallel:"\u2226",nmid:"\u2224",nequiv:"\u2262",triangleq:"\u225C",backsim:"\u223D",approxeq:"\u224A",vdash:"\u22A2",models:"\u22A8"},Yh={rightarrow:"\u2192",to:"\u2192",leftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",Rightarrow:"\u21D2",Leftarrow:"\u21D0",Leftrightarrow:"\u21D4",mapsto:"\u21A6",longrightarrow:"\u27F6",longleftarrow:"\u27F5",rightleftharpoons:"\u21CC",rightharpoonup:"\u21C0",leftharpoondown:"\u21BD",leftharpoonup:"\u21BC",rightharpoondown:"\u21C1",leftrightharpoons:"\u21CB",uparrow:"\u2191",downarrow:"\u2193",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",implies:"\u27F9",impliedby:"\u27F8",iff:"\u27FA",Longrightarrow:"\u27F9",Longleftarrow:"\u27F8",Longleftrightarrow:"\u27FA",longleftrightarrow:"\u27F7",longmapsto:"\u27FC",hookrightarrow:"\u21AA",hookleftarrow:"\u21A9",twoheadrightarrow:"\u21A0",leadsto:"\u21DD",rightsquigarrow:"\u21DD",rightleftarrows:"\u21C4",leftrightarrows:"\u21C6",Uparrow:"\u21D1",Downarrow:"\u21D3",updownarrow:"\u2195",Updownarrow:"\u21D5"},Kh={infty:"\u221E",partial:"\u2202",nabla:"\u2207",forall:"\u2200",exists:"\u2203",nexists:"\u2204",emptyset:"\u2205",varnothing:"\u2205",ldots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",therefore:"\u2234",because:"\u2235",angle:"\u2220",top:"\u22A4",bot:"\u22A5",aleph:"\u2135",hbar:"\u210F",ell:"\u2113",Re:"\u211C",Im:"\u2111",wp:"\u2118",prime:"\u2032",surd:"\u221A",degree:"\xB0",hslash:"\u210F",imath:"\u0131",jmath:"\u0237",langle:"\u27E8",rangle:"\u27E9",lVert:"\u2016",rVert:"\u2016",Vert:"\u2016",vert:"|",mid:"\u2223",neg:"\xAC",lnot:"\xAC",checkmark:"\u2713",dagger:"\u2020",ddagger:"\u2021",Box:"\u25A1",triangle:"\u25B3",square:"\u25A1",blacksquare:"\u25A0",diamond:"\u22C4",measuredangle:"\u2221",sphericalangle:"\u2222",frown:"\u2322",smile:"\u2323",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",complement:"\u2201",mho:"\u2127",AA:"\xC5",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",dots:"\u2026"};function Fn(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]={text:o,class:t};return n}a(Fn,"toClass");var Jt={...Fn(jh,"greek"),...Fn(Xh,"greek"),...Fn(zh,"operator"),...Fn(Vh,"operator"),...Fn(Yh,"operator"),...Fn(Kh,"special")},lu={"=":"\u2260","<":"\u226E",">":"\u226F","\u2264":"\u2270","\u2265":"\u2271","\u2261":"\u2262","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2208":"\u2209","\u220B":"\u220C","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u2223":"\u2224","|":"\u2224","\u2225":"\u2226","\u22A2":"\u22AC","\u22A8":"\u22AD","\u227A":"\u2280","\u227B":"\u2281","\u2203":"\u2204","\u2192":"\u219B","\u2190":"\u219A","\u2194":"\u21AE","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE"},Bn={"%":"%",$:"$","#":"#","&":"&",_:"_","{":"{","}":"}"," ":" ",",":" ",";":" "};x();var Un=new Set(["sin","cos","tan","cot","sec","csc","arcsin","arccos","arctan","arccot","arcsec","arccsc","sinh","cosh","tanh","coth","sech","csch","arsinh","arcosh","artanh","log","ln","exp","lim","limsup","liminf","max","min","sup","inf","det","gcd","lcm","dim","ker","deg","arg","hom","Pr","mod"]),_r=new Set(["lim","limsup","liminf","max","min","sup","inf"]);x();var Lr={red:"FF0000",green:"00FF00",blue:"0000FF",cyan:"00FFFF",magenta:"FF00FF",yellow:"FFFF00",black:"000000",white:"FFFFFF",gray:"808080",darkgray:"404040",lightgray:"BFBFBF",brown:"BF8040",lime:"BFFF00",olive:"808000",orange:"FF8000",pink:"FFBFBF",purple:"BF0040",teal:"008080",violet:"800080"};function uu(e){let t=e.toUpperCase();return Object.keys(Lr).find(n=>Lr[n]===t)}a(uu,"xcolorName");var Zh={red:"FF0000",green:"008000",blue:"0000FF",black:"000000",white:"FFFFFF",gray:"808080",grey:"808080",silver:"C0C0C0",orange:"FFA500",purple:"800080",teal:"008080",navy:"000080",maroon:"800000",olive:"808000",yellow:"FFFF00",cyan:"00FFFF",aqua:"00FFFF",magenta:"FF00FF",fuchsia:"FF00FF",pink:"FFC0CB",brown:"A52A2A",violet:"EE82EE",lime:"00FF00"};function cu(e){let t=e.trim(),n=/^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])$/.exec(t);if(n)return`${n[1]}${n[1]}${n[2]}${n[2]}${n[3]}${n[3]}`.toUpperCase();let r=/^#([0-9a-fA-F]{6})$/.exec(t);return r?r[1].toUpperCase():Zh[t.toLowerCase()]??null}a(cu,"cssColorToHex");x();function du(e,t,n){let r=Wo(t).map(S=>({...S,start:S.start+n,end:S.end+n})),o=0,i=a((S=0)=>r[Math.min(o+S,r.length-1)],"peek"),s=a(()=>r[oi().type==="eof","atEnd");function u(S,k,T,O){throw new yn(e,S,k,T.start,T.value||void 0,O)}a(u,"fail");function c(S){return{kind:"symbol",class:"digit",text:S.value,source:S.value,start:S.start,end:S.end}}a(c,"digitNode");function d(S,k){let T=k?k.value:"",O=k?k.end:S.end,C=k?k.start:i().start,D=!1;for(;;){let _=i();if(_.type==="char"&&(_.value==="+"||_.value==="-")&&_.start===O){T+=_.value,O=_.end,D=!0,s();continue}break}return D?{kind:"supsub",base:S,sup:{kind:"symbol",class:"punct",text:T,source:T,start:C,end:O},start:S.start,end:O}:S}a(d,"attachCharge");function p(){if(i().type==="lbrace"){let k=s(),T="",O=k.end;for(;i().type!=="rbrace"&&!l();){let D=i();D.type==="number"||D.type==="char"&&(D.value==="+"||D.value==="-")?(T+=D.value,O=D.end,s()):u("unsupported-construct",`Only digits and +/- are supported inside an explicit ^{...} in \\ce{}, found "${D.value}".`,D,"Move anything else outside \\ce{}, or write the charge as plain digits/signs.")}i().type!=="rbrace"&&u("unclosed-brace","Missing closing '}' for ^{...} in \\ce{}.",i(),"Add a matching '}'.");let C=s();return{text:T,start:k.start,end:C.end}}let S=i();if(S.type==="number"||S.type==="char"&&(S.value==="+"||S.value==="-")){s();let k=S.value,T=S.end;for(;i().type==="char"&&(i().value==="+"||i().value==="-")&&i().start===T;){let O=s();k+=O.value,T=O.end}return{text:k,start:S.start,end:T}}u("wrong-argument-count","Expected a digit or +/- after ^ in \\ce{}.",S)}a(p,"readSignedArg");function f(S){let k=i(S),T=i(S+1);return k.type==="char"&&k.value==="-"&&T.start===k.end?T.type==="lbracket"||T.type==="char"&&/^[A-Za-z(]$/.test(T.value):!1}a(f,"isBond");function m(S){let k=S,T=i();if(T.start===k.end){if(T.type==="number"){let C=i(1);if(C.type==="char"&&(C.value==="+"||C.value==="-")&&C.start===T.end&&!f(1))return s(),d(k,T);s();let D=c(T);k={kind:"supsub",base:k,sub:D,start:k.start,end:T.end}}else if(T.type==="char"&&(T.value==="+"||T.value==="-")&&!f(0))return d(k,void 0)}let O=i();if(O.type==="caret"&&O.start===k.end){s();let{text:C,start:D,end:P}=p();k={kind:"supsub",base:k,sup:{kind:"symbol",class:"punct",text:C,source:C,start:D,end:P},start:k.start,end:P}}return k}a(m,"maybeSubscriptOrCharge");function h(){let S=s(),k=S.value,T=S.end;for(;i().type==="char"&&/[a-z]/.test(i().value)&&i().start===T;){let C=s();k+=C.value,T=C.end}let O={kind:"symbol",class:"letter",text:k,source:k,start:S.start,end:T};return m(O)}a(h,"parseLetterRun");function g(S){let k=s(),T=S==="("?")":"]",O=a(M=>S==="("?M.type==="char"&&M.value===")":M.type==="rbracket","isCloseTok"),C=[];for(;!O(i())&&!l();)C.push(A());O(i())||u("unclosed-brace",`Missing closing '${T}' in \\ce{}.`,i(),`Add a matching '${T}'.`);let D=s(),P={kind:"row",children:C,start:k.start,end:D.end},_={kind:"delimited",left:S,right:T,parts:[P],start:k.start,end:D.end};return m(_)}a(g,"parseGroup");function y(S){for(let k=0;k0&&i(k-1).end!==T.start)return!1}return!0}a(y,"matchesSeq");function E(S,k,T){let O=i().start,C=O;for(let W=0;Wre.end&&j.push({kind:"spacing",size:"medium",start:re.end,end:i().start}),j.push(A())}i().type!=="rbracket"&&u("unclosed-brace","Missing closing ']' for the reaction condition.",i(),"Add a matching ']', e.g. \\ce{A ->[cat.] B}.");let we=s();D.push({kind:"row",children:j,start:W.start,end:we.end}),C=we.end}let[P,_]=D;return{kind:"labeledarrow",arrow:T,chr:k,above:P,below:_,start:O,end:C}}a(E,"consumeArrow");function v(){if(y(["<","<","=",">"])&&u("unsupported-construct","Asymmetric equilibrium arrows (favoring the reverse direction) are not supported \u2014 no distinct OMML glyph is available for them.",i(),"Use a plain equilibrium arrow (<=>) instead."),y(["<","=",">",">"])&&u("unsupported-construct","Asymmetric equilibrium arrows (favoring the forward direction) are not supported \u2014 no distinct OMML glyph is available for them.",i(),"Use a plain equilibrium arrow (<=>) instead."),y(["<","=",">"]))return E(3,"\u21CC","xrightarrow");if(y(["-",">"]))return E(2,"\u2192","xrightarrow");if(y(["<","-"]))return E(2,"\u2190","xleftarrow")}a(v,"tryParseArrow");function w(){let S=i().start,k,T;for(;i().type==="caret"||i().type==="underscore";){let D=s(),P=p(),_={kind:"symbol",class:"digit",text:P.text,source:P.text,start:P.start,end:P.end};D.type==="caret"?(k&&u("wrong-argument-count","An isotope has one mass number: there are two ^ here.",D),k=_):(T&&u("wrong-argument-count","An isotope has one atomic number: there are two _ here.",D),T=_)}let O=i();O.type==="char"&&/[A-Za-z]/.test(O.value)||u("unsupported-construct","An isotope's ^{mass} and _{number} have to be followed by an element symbol inside \\ce{}.",O,"Write it as \\ce{^{14}_{6}C}: the numbers, then the element.");let C=h();return{kind:"prescript",base:C,presup:k,presub:T,start:S,end:C.end}}a(w,"parseIsotope");function A(){let S=v();if(S)return S;let k=i();if(k.type==="char"&&k.value==="(")return g("(");if(k.type==="lbracket")return g("[");if(k.type==="char"&&/[A-Za-z]/.test(k.value))return h();if(k.type==="number")return s(),c(k);if(k.type==="caret"||k.type==="underscore")return w();if(k.type==="char"&&(k.value==="+"||k.value==="-"))return s(),{kind:"symbol",class:"punct",text:k.value,source:k.value,start:k.start,end:k.end};if(k.type==="command"){if(s(),k.value in Jt){let T=Jt[k.value];return{kind:"symbol",class:T.class,text:T.text,source:`\\${k.value}`,start:k.start,end:k.end}}if(k.value in Bn)return{kind:"symbol",class:"punct",text:Bn[k.value],source:`\\${k.value}`,start:k.start,end:k.end};u("unknown-command",`Unknown command "\\${k.value}" inside \\ce{}.`,k,"Only simple named symbols (e.g. \\Delta, \\alpha) are supported inside \\ce{} \u2014 not compound commands like \\frac. Move those outside \\ce{}.")}if(k.type==="char")return s(),{kind:"symbol",class:"punct",text:k.value==="#"?"\u2261":k.value,source:k.value,start:k.start,end:k.end};u("unexpected-eof","Unexpected end of \\ce{} content.",k)}a(A,"parseAtomUnit");let N=[];for(;!l();)N.push(A());return N}a(du,"parseChemicalFormula");var pu={sum:"sum",prod:"prod",coprod:"coprod",int:"int",iint:"iint",iiint:"iiint",oint:"oint",iiiint:"iiiint",oiint:"oiint",oiiint:"oiiint",bigcup:"bigcup",bigcap:"bigcap",bigoplus:"bigoplus",bigotimes:"bigotimes",bigodot:"bigodot",biguplus:"biguplus",bigvee:"bigvee",bigwedge:"bigwedge",bigsqcup:"bigsqcup"},fu={vec:"vec",hat:"hat",widehat:"hat",bar:"bar",overline:"bar",dot:"dot",ddot:"ddot",tilde:"tilde",widetilde:"tilde",check:"check",breve:"breve",overrightarrow:"overrightarrow",overleftarrow:"overleftarrow",overleftrightarrow:"overleftrightarrow",underline:"underline"},mu={xrightarrow:"\u27F6",xleftarrow:"\u27F5",xleftrightarrow:"\u27F7",xRightarrow:"\u27F9",xLeftarrow:"\u27F8",xLeftrightarrow:"\u27FA",xrightleftharpoons:"\u21CC",xleftrightharpoons:"\u21CB",xmapsto:"\u27FC",xhookrightarrow:"\u21AA",xhookleftarrow:"\u21A9"},Jh=new Set(["displaystyle","textstyle","scriptstyle","scriptscriptstyle"]),hu={",":"thin",";":"medium",":":"medium","!":"thin",quad:"quad",qquad:"qquad"," ":"medium"},Qh=new Set(["hline","toprule","midrule","bottomrule"]),gu={matrix:"matrix",pmatrix:"pmatrix",bmatrix:"bmatrix",Bmatrix:"Bmatrix",vmatrix:"vmatrix",Vmatrix:"Vmatrix"},yu={aligned:!0,gathered:!1,align:!0,gather:!1,split:!0},bu={cancel:"forward",bcancel:"backward",xcancel:"cross"},wu={overbrace:{pos:"top",chr:"\u23DE"},underbrace:{pos:"bot",chr:"\u23DF"},overparen:{pos:"top",chr:"\u23DC"},overarc:{pos:"top",chr:"\u23DC"},underparen:{pos:"bot",chr:"\u23DD"}},xu={overset:"top",stackrel:"top",underset:"bot"},vu={abs:{left:"|",right:"|"},norm:{left:"\u2016",right:"\u2016"},ceil:{left:"\u2308",right:"\u2309"},floor:{left:"\u230A",right:"\u230B"}},eg={textbf:"mathbf",textit:"mathit",textsf:"mathsf",texttt:"mathtt"},ku={mathbb:"mathbb",Bbb:"mathbb",mathcal:"mathcal",mathscr:"mathcal",mathfrak:"mathfrak",mathsf:"mathsf",mathtt:"mathtt",mathbf:"mathbf",boldsymbol:"boldsymbol",bm:"boldsymbol",mathit:"mathit",si:"upright",unit:"upright"},Eu={"{":"{","}":"}",langle:"\u27E8",rangle:"\u27E9",vert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309"},Au=a((e,t)=>e.type==="command"&&e.value===t,"isCommand"),$t=a(e=>e.type==="command"&&e.value==="end","isEnd"),Ts=a(e=>e.type==="command"&&e.value==="right","isRight"),Su=a(e=>e.type==="command"&&e.value==="middle","isMiddle"),Cs=class e{constructor(t){this.source=t;this.pos=0;this.nestingDepth=0;this.tokens=Wo(t)}static{a(this,"Parser")}parse(){let t=this.parseRow(r=>r.type==="eof"),n=this.peek();if(n.type!=="eof")throw this.err("unexpected-token",`Unexpected ${n.type} "${n.value}"`,n,"Check for an unmatched closing brace or bracket.");return t}peek(t=0){let n=Math.min(this.pos+t,this.tokens.length-1);return this.tokens[n]}advance(){let t=this.tokens[this.pos];return this.pos0?o[o.length-1].end:n;return{kind:"row",children:o,start:n,end:i}}mergePrescripts(t){let n=a(o=>o.kind==="supsub"&&o.base.kind==="row"&&o.base.children.length===0,"isEmptyBaseSupSub"),r=[];for(let o=0;oo.type==="rbrace");if(this.peek().type!=="rbrace")throw this.err("unclosed-brace","Missing closing brace.",this.peek(),"Add a matching '}' \u2014 every '{' needs a corresponding '}'.");let r=this.advance();return{...n,start:t.start,end:r.end}}parseArgument(){let t=this.peek();if(t.type==="lbrace")return this.parseGroup();if(t.type==="eof")throw this.err("unexpected-eof","Expected an argument but reached the end of the input.",t,"Provide an argument, e.g. wrap it in braces: {...}");return t.type==="number"&&t.value.length>1&&this.tokens.splice(this.pos,1,{...t,value:t.value[0],end:t.start+1},{...t,value:t.value.slice(1),start:t.start+1}),this.parseAtomCore(n=>n.type==="eof")}parseOptionalArgument(){if(this.peek().type!=="lbracket")return;this.advance();let t=this.parseRow(n=>n.type==="rbracket");if(this.peek().type!=="rbracket")throw this.err("unclosed-brace","Missing closing ']' for optional argument.",this.peek(),"Add a matching ']'.");return this.advance(),t}readBracedIdentifier(t){this.expect("lbrace",`after ${t}`);let n="";for(;this.peek().type==="char"||this.peek().type==="number";)n+=this.advance().value;if(this.peek().type!=="rbrace")throw this.err("unclosed-brace",`Missing closing brace for ${t} name.`,this.peek(),"Environment/command names must be plain letters, e.g. {pmatrix}.");return this.advance(),n}static{this.MAX_NESTING_DEPTH=200}parseAtom(t){if(++this.nestingDepth>e.MAX_NESTING_DEPTH){let n=this.peek();throw this.nestingDepth--,this.err("too-deeply-nested",`This expression nests more than ${e.MAX_NESTING_DEPTH} levels deep (fractions, scripts, radicals, groups, etc. inside one another).`,n,"Break the expression into smaller pieces, or check for a runaway/accidentally-repeated pattern.")}try{let n=this.parseAtomCore(t);return this.attachScripts(n)}finally{this.nestingDepth--}}attachScripts(t){let n,r,o=[],i=0,s=0;for(;;){let u=this.peek();if(u.type==="char"&&u.value==="'"){if(n)throw this.err("wrong-argument-count","Double superscript: a prime (') after an explicit superscript is ambiguous. Write the prime first (x'^{2}) or group it, e.g. x^{2\\prime}.",u);for(o.length===0&&(i=u.start);this.peek().type==="char"&&this.peek().value==="'";){let c=this.advance();s=c.end,o.push({kind:"symbol",class:"special",text:"\u2032",source:"'",start:c.start,end:c.end})}continue}if(u.type==="caret"){if(n)throw this.err("wrong-argument-count","Double superscript: use braces to group, e.g. x^{a^b}.",u);this.advance(),n=this.parseArgument()}else if(u.type==="underscore"){if(r)throw this.err("wrong-argument-count","Double subscript: use braces to group, e.g. x_{a_b}.",u);this.advance(),r=this.parseArgument()}else break}if(o.length>0){let u=n?[...o,n]:o,c=n?n.end:s;n={kind:"row",children:u,start:i,end:c}}return!n&&!r?t:{kind:"supsub",base:t,sup:n,sub:r,start:t.start,end:(n??r).end}}parseAtomCore(t){let n=this.peek();if(n.type==="lbrace")return this.parseGroup();if(n.type==="number")return this.advance(),{kind:"symbol",class:"digit",text:n.value,source:n.value,start:n.start,end:n.end};if(n.type==="lbracket")return this.advance(),{kind:"symbol",class:"punct",text:"[",source:"[",start:n.start,end:n.end};if(n.type==="rbracket")return this.advance(),{kind:"symbol",class:"punct",text:"]",source:"]",start:n.start,end:n.end};if(n.type==="char")return this.advance(),{kind:"symbol",class:/[A-Za-z]/.test(n.value)?"letter":"punct",text:n.value,source:n.value,start:n.start,end:n.end};if(n.type==="caret"||n.type==="underscore")return{kind:"row",children:[],start:n.start,end:n.start};if(n.type==="command")return this.parseCommand(n,t);throw n.type==="ampersand"||n.type==="newline"?this.err("unexpected-token",`"${n.value}" is only valid inside a matrix or cases environment.`,n):this.err("unexpected-eof","Expected an expression but reached the end of the input.",n)}parseCommand(t,n){let r=t.value;if(this.advance(),Jh.has(r))return{kind:"row",children:[],start:t.start,end:t.end};switch(r){case"cfrac":if(this.peek().type==="lbracket")throw this.err("unsupported-construct","\\cfrac's [l]/[r] numerator alignment can't be shown in a Word equation.",this.peek(),"Write \\cfrac{...}{...} without the [l] or [r].");case"frac":case"dfrac":case"tfrac":{let o=this.parseArgument(),i=this.parseArgument();return{kind:"frac",numerator:o,denominator:i,start:t.start,end:i.end}}case"binom":case"dbinom":case"tbinom":{let o=this.parseArgument(),i=this.parseArgument();return{kind:"binom",top:o,bottom:i,start:t.start,end:i.end}}case"sqrt":{let o=this.parseOptionalArgument(),i=this.parseArgument();return{kind:"sqrt",radicand:i,index:o,start:t.start,end:i.end}}case"left":return this.parseLeftRight(t);case"right":throw this.err("unexpected-token",'"\\right" without a matching "\\left".',t,"Add a \\left before this delimiter.");case"middle":throw this.err("unexpected-token",'"\\middle" is only valid directly inside a \\left ... \\right pair.',t,"Move this \\middle| inside a \\left...\\right group, e.g. \\left(A\\middle|B\\right).");case"begin":return this.parseEnvironment(t);case"end":throw this.err("unexpected-token",'"\\end" without a matching "\\begin".',t);case"text":case"mathrm":case"textrm":case"textnormal":case"textup":case"operatorname":{let o=this.readRawGroup();return{kind:"text",text:o.text,start:t.start,end:o.end}}case"textbf":case"textit":case"textsf":case"texttt":{let o=this.readRawGroup(),i={kind:"text",text:o.text,start:t.start,end:o.end};return{kind:"fontvariant",variant:eg[r],content:i,start:t.start,end:o.end}}case"tag":{let o=this.readRawGroup();return{kind:"tag",label:o.text,start:t.start,end:o.end}}case"pmod":{let o=this.parseArgument();return{kind:"row",children:[{kind:"text",text:" (mod ",start:t.start,end:t.start},o,{kind:"symbol",class:"punct",text:")",source:")",start:o.end,end:o.end}],start:t.start,end:o.end}}case"bmod":return{kind:"text",text:" mod ",start:t.start,end:t.end};case"bra":{let o=this.parseArgument();return{kind:"delimited",left:"\u27E8",right:"|",parts:[o],start:t.start,end:o.end}}case"ket":{let o=this.parseArgument();return{kind:"delimited",left:"|",right:"\u27E9",parts:[o],start:t.start,end:o.end}}case"expval":{let o=this.parseArgument();return{kind:"delimited",left:"\u27E8",right:"\u27E9",parts:[o],start:t.start,end:o.end}}case"braket":case"ip":{let o=this.parseArgument(),i=this.parseArgument();return{kind:"delimited",left:"\u27E8",right:"\u27E9",parts:[o,i],sepChar:"|",start:t.start,end:i.end}}case"boxed":{let o=this.parseArgument();return{kind:"boxed",base:o,start:t.start,end:o.end}}case"textcolor":case"color":{let o=this.readColor(t),i=r==="textcolor"?this.parseArgument():this.parseRow(n);return{kind:"color",color:o,content:i,start:t.start,end:Math.max(i.end,t.end)}}case"not":{let o=this.parseAtomCore(n),i=o.kind==="symbol"?lu[o.text]:void 0;if(i===void 0)throw this.err("unsupported-construct","\\not can only negate a relation that has a crossed-out form, such as \\not=, \\not\\in or \\not\\subset.",t,"Word can't strike through an arbitrary symbol. Use the negated symbol itself, e.g. \\neq, \\notin, \\nleq.");return{kind:"symbol",class:"operator",text:i,source:`\\not${o.source}`,start:t.start,end:o.end}}case"limits":case"nolimits":throw this.err("unexpected-token",`\\${r} has to come straight after a large operator (\\sum, \\int) or a function name (\\lim, \\det).`,t);case"hline":case"toprule":case"midrule":case"bottomrule":throw this.err("unexpected-token",`\\${r} draws a line between the rows of an array or matrix, so it has to start a row.`,t,"Put it straight after \\\\ or \\begin{array}{...}, as in \\begin{array}{|c|c|} \\hline a & b \\\\ \\hline \\end{array}.");case"dv":case"pdv":return this.parseDerivative(t,r==="pdv");case"dd":{let o=this.parseOptionalArgument(),i=this.differential(!1,o,t);if(this.peek().type!=="lbrace")return i;let s=this.parseGroup();return{kind:"row",children:[i,s],start:t.start,end:s.end}}case"vb":case"va":{let o=this.peek().type==="char"&&this.peek().value==="*";o&&this.advance();let i=this.parseArgument();return r==="va"?{kind:"accent",accent:"vec",base:i,start:t.start,end:i.end}:{kind:"fontvariant",variant:o?"boldsymbol":"mathbf",content:i,start:t.start,end:i.end}}case"grad":case"curl":case"divergence":case"laplacian":{let o={kind:"symbol",class:"special",text:"\u2207",source:"\\nabla",start:t.start,end:t.end};if(r==="grad")return o;if(r==="laplacian"){let l={kind:"symbol",class:"digit",text:"2",source:"2",start:t.end,end:t.end};return{kind:"supsub",base:o,sup:l,start:t.start,end:t.end}}let i=r==="curl"?{kind:"symbol",class:"operator",text:"\xD7",source:"\\times",start:t.end,end:t.end}:{kind:"symbol",class:"operator",text:"\u22C5",source:"\\cdot",start:t.end,end:t.end};return{kind:"row",children:[o,i],start:t.start,end:t.end}}case"ev":{let o=this.parseArgument();return{kind:"delimited",left:"\u27E8",right:"\u27E9",parts:[o],start:t.start,end:o.end}}case"mel":{let o=this.parseArgument(),i=this.parseArgument(),s=this.parseArgument();return{kind:"delimited",left:"\u27E8",right:"\u27E9",parts:[o,i,s],sepChar:"|",start:t.start,end:s.end}}case"ketbra":{let o=this.parseArgument(),i=this.parseArgument(),s={kind:"delimited",left:"|",right:"\u27E9",parts:[o],start:t.start,end:o.end},l={kind:"delimited",left:"\u27E8",right:"|",parts:[i],start:o.end,end:i.end};return{kind:"row",children:[s,l],start:t.start,end:i.end}}default:break}if(r in ku){let o=this.parseArgument();return{kind:"fontvariant",variant:ku[r],content:o,start:t.start,end:o.end}}if(r in fu){let o=this.parseArgument();return{kind:"accent",accent:fu[r],base:o,start:t.start,end:o.end}}if(r==="cancelto")throw this.err("unsupported-construct","\\cancelto is not supported.",t,"OMML can strike a term through (\\cancel) but has no way to draw the arrow and target value \\cancelto adds. Write \\cancel{...} and put the value alongside.");if(r==="substack")return{kind:"matrix",matrixKind:"array",rows:this.parseSubstackRows(t),columns:["center"],start:t.start,end:this.tokens[Math.max(0,this.pos-1)].end};if(r in bu){let o=this.parseArgument();return{kind:"cancel",cancel:bu[r],base:o,start:t.start,end:o.end}}if(r in wu){let o=this.parseArgument(),{pos:i,chr:s}=wu[r];return{kind:"groupchar",pos:i,chr:s,base:o,start:t.start,end:o.end}}if(r in xu){let o=this.parseArgument(),i=this.parseArgument();return{kind:"stack",pos:xu[r],label:o,base:i,start:t.start,end:i.end}}if(r in vu){let o=vu[r];this.peek().type==="char"&&this.peek().value==="*"&&this.advance();let i=this.parseArgument();return{kind:"delimited",left:o.left,right:o.right,parts:[i],start:t.start,end:i.end}}if(r in pu)return this.parseNAry(t,r);if(r in hu)return{kind:"spacing",size:hu[r],start:t.start,end:t.end};if(r in mu){let o=this.parseOptionalArgument(),i=this.parseArgument(),s=i.kind==="row"&&i.children.length===0?void 0:i;return{kind:"labeledarrow",arrow:r,chr:mu[r],above:s,below:o,start:t.start,end:i.end}}if(r==="ce"){let o=this.readRawGroup();return{kind:"fontvariant",variant:"upright",content:{kind:"row",children:du(this.source,o.text,o.start),start:o.start,end:o.end},start:t.start,end:o.end}}if(r in Jt){let o=Jt[r];return{kind:"symbol",class:o.class,text:o.text,source:`\\${r}`,start:t.start,end:t.end}}if(r in Bn)return{kind:"symbol",class:"punct",text:Bn[r],source:`\\${r}`,start:t.start,end:t.end};if(Un.has(r)){let o=this.readLimitsModifier();return o===void 0?{kind:"func",name:r,start:t.start,end:t.end}:{kind:"func",name:r,limits:o,start:t.start,end:this.tokens[Math.max(0,this.pos-1)].end}}throw this.err("unknown-command",`Unknown command "\\${r}".`,t,"Check the spelling, or see SUPPORTED_LATEX.md for the list of supported commands.")}readLimitsModifier(){let t=this.peek();if(Au(t,"limits"))return this.advance(),!0;if(Au(t,"nolimits"))return this.advance(),!1}readColor(t){let n;if(this.peek().type==="lbracket"){let l=this.advance();for(n="";this.peek().type==="char"||this.peek().type==="number";)n+=this.advance().value;if(this.peek().type!=="rbracket")throw this.err("unclosed-brace","Missing ']' after the colour model.",this.peek());if(this.advance(),n.toUpperCase()!=="HTML")throw this.err("unsupported-construct",`The colour model "${n}" is not supported.`,l,"Use a colour name, e.g. \\textcolor{red}{x}, or [HTML]{FF0000}.")}let r=this.readRawGroup(),o=r.text.trim(),i={type:"char",value:o,start:r.start,end:r.end};if(n!==void 0){if(!/^[0-9A-Fa-f]{6}$/.test(o))throw this.err("unsupported-construct",`"${o}" is not a six-digit HTML colour.`,i,"Write it as six hex digits, e.g. [HTML]{1F77B4}.");return o.toUpperCase()}let s=Lr[o];if(s===void 0)throw this.err("unsupported-construct",`"${o}" is not a colour TeXConverter knows (after \\${t.value}).`,i,`Use one of ${Object.keys(Lr).join(", ")} \u2014 or [HTML]{RRGGBB}.`);return s}differential(t,n,r){let o=t?{kind:"symbol",class:"special",text:"\u2202",source:"\\partial",start:r.start,end:r.end}:{kind:"text",text:"d",start:r.start,end:r.end};return n?{kind:"supsub",base:o,sup:n,start:r.start,end:n.end}:o}parseDerivative(t,n){let r=this.parseOptionalArgument(),o=this.parseArgument(),i=this.peek().type==="lbrace"?this.parseArgument():void 0,s=n&&i&&this.peek().type==="lbrace"?this.parseArgument():void 0,l=(s??i??o).end,u=a(h=>this.differential(n,h,t),"d"),c=a(h=>({kind:"row",children:h,start:t.start,end:l}),"row"),d=a((h,g)=>g?{kind:"supsub",base:h,sup:g,start:h.start,end:g.end}:h,"raised"),p,f;if(s){if(r)throw this.err("unsupported-construct","A mixed partial derivative takes no [order]: \\pdv{f}{x}{y} is already second order.",t);let h={kind:"symbol",class:"digit",text:"2",source:"2",start:t.start,end:t.start};p=c([u(h),o]),f=c([u(),i,u(),s])}else i?(p=c([u(r),o]),f=c([u(),d(i,r)])):(p=u(r),f=c([u(),d(o,r)]));return{kind:"frac",numerator:p,denominator:f,start:t.start,end:l}}parseNAry(t,n){let r=pu[n],o=this.readLimitsModifier(),i,s;for(;;){let c=this.peek();if(c.type==="underscore"){if(i)throw this.err("wrong-argument-count","Double subscript on a large operator.",c);this.advance(),i=this.parseArgument()}else if(c.type==="caret"){if(s)throw this.err("wrong-argument-count","Double superscript on a large operator.",c);this.advance(),s=this.parseArgument()}else break}let l=this.parseRow(c=>c.type==="eof"||c.type==="rbrace"||c.type==="rbracket"||c.type==="ampersand"||c.type==="newline"||$t(c)||Ts(c));return o===void 0?{kind:"nary",op:r,sub:i,sup:s,operand:l,start:t.start,end:l.end}:{kind:"nary",op:r,sub:i,sup:s,operand:l,limits:o,start:t.start,end:l.end}}parseLeftRight(t){let n=this.parseDelimiterChar(),r=a(c=>Ts(c)||Su(c)||c.type==="eof","stop"),o=[this.parseRow(r)],i;for(;Su(this.peek());){let c=this.advance(),d=this.parseDelimiterChar();if(i===void 0)i=d;else if(i!==d)throw this.err("unsupported-construct",`Multiple \\middle delimiters with different characters ("${i}" and "${d}") in the same \\left...\\right are not supported.`,c,"OMML's delimiter object uses one separator character for the whole group \u2014 use the same delimiter for every \\middle here, e.g. \\middle| each time.");o.push(this.parseRow(r))}if(!Ts(this.peek()))throw this.err("unclosed-environment","Missing \\right to match this \\left.",this.peek(),"Add a \\right.");let s=this.advance(),l=this.parseDelimiterChar();return{kind:"delimited",left:n,right:l,parts:o,sepChar:i,start:t.start,end:s.end}}parseDelimiterChar(){let t=this.advance();if(t.type==="lbracket")return"[";if(t.type==="rbracket")return"]";if(t.type==="char"){if(t.value===".")return"";if("()[]|".includes(t.value))return t.value;throw this.err("invalid-delimiter",`"${t.value}" is not a valid \\left/\\right delimiter.`,t,"Use one of ( ) [ ] { } | \\langle \\rangle \\lfloor \\rfloor \\lceil \\rceil or . for none.")}if(t.type==="command"&&t.value in Eu)return Eu[t.value];throw this.err("invalid-delimiter",`Expected a delimiter after \\left/\\right, found "${t.value}".`,t)}parseEnvironment(t){let n=this.readBracedIdentifier("\\begin"),r=n.replace(/\*$/,"");if(r==="array"){let o=this.parseColumnSpec();return this.parseMatrixBody(t,"array",n,o.columns,o.rules)}if(r in gu)return this.parseMatrixBody(t,gu[r],n);if(r==="cases")return this.parseCasesBody(t,n);if(r==="equation"){let o=this.parseRow(i=>$t(i)||i.type==="eof");return this.consumeEnd(n),{...o,start:t.start}}if(r in yu)return this.parseAlignBody(t,n,yu[r]);throw r==="eqnarray"?this.err("unsupported-construct",`The \\begin{${n}} environment is not supported yet.`,t,"eqnarray is deprecated even in LaTeX itself \u2014 use \\begin{align} instead, which is supported."):this.err("unsupported-construct",`Unknown or unsupported environment "\\begin{${n}}".`,t)}parseSubstackRows(t){if(this.peek().type!=="lbrace")throw this.err("unexpected-token","\\substack needs a braced group, as in \\substack{io.type==="newline"||o.type==="rbrace"||o.type==="ampersand"||o.type==="eof","stop");for(;;){let o=this.parseRow(r);n.push([o]);let i=this.peek();if(i.type==="newline"){this.advance();continue}if(i.type==="ampersand")throw this.err("unexpected-token",'\\substack has a single column, so "&" has no meaning in it.',i,"Separate the lines with \\\\ instead.");if(i.type==="rbrace"){this.advance();break}throw this.err("unclosed-brace","Missing the closing brace of \\substack.",i)}return n}parseColumnSpec(){let t=this.readRawGroup(),n=[],r=[];for(let o=0;of.type==="ampersand"||f.type==="newline"||$t(f)||f.type==="eof","cellStop");for(;;){if(u.length===0)for(let h=this.peek();h.type==="command"&&Qh.has(h.value);h=this.peek())this.advance(),l[l.length-1]!==s.length&&l.push(s.length);let f=this.parseRow(c);u.push(f);let m=this.peek();if(m.type==="ampersand"){this.advance();continue}if(m.type==="newline"){this.advance(),s.push(u),u=[];continue}if($t(m)){let h=u.length===1?u[0]:null;h!==null&&h.kind==="row"&&h.children.length===0&&s.length>0&&l.includes(s.length)||s.push(u),this.consumeEnd(r);break}throw this.err("unclosed-environment",`Missing \\end{${r}}.`,m)}let d=this.tokens[Math.max(0,this.pos-1)].end,p=l.length===0?{}:{hlines:l};return o===void 0?{kind:"matrix",matrixKind:n,rows:s,...p,start:t.start,end:d}:i.length===0?{kind:"matrix",matrixKind:n,rows:s,columns:o,...p,start:t.start,end:d}:{kind:"matrix",matrixKind:n,rows:s,columns:o,rules:i,...p,start:t.start,end:d}}parseAlignBody(t,n,r){let o=[],i=[],s=a(l=>l.type==="ampersand"||l.type==="newline"||$t(l)||l.type==="eof","cellStop");for(;;){let l=this.parseRow(s);i.push(l);let u=this.peek();if(u.type==="ampersand"){if(!r)throw this.err("unexpected-token",`"&" is not valid in \\begin{${n}} \u2014 gather has no alignment points (that's what align is for).`,u);this.advance();continue}if(u.type==="newline"){this.advance(),o.push(i),i=[];continue}if($t(u)){o.push(i),this.consumeEnd(n);break}throw this.err("unclosed-environment",`Missing \\end{${n}}.`,u)}return{kind:"align",rows:o,alignPoints:r,start:t.start,end:this.tokens[Math.max(0,this.pos-1)].end}}parseCasesBody(t,n){let r=[],o=a(i=>i.type==="ampersand"||i.type==="newline"||$t(i)||i.type==="eof","cellStop");for(;;){let i=this.parseRow(o),s;this.peek().type==="ampersand"&&(this.advance(),s=this.parseRow(o)),r.push({expr:i,condition:s});let l=this.peek();if(l.type==="newline"){this.advance();continue}if($t(l)){this.consumeEnd(n);break}throw this.err("unclosed-environment",`Missing \\end{${n}}.`,l)}return{kind:"cases",rows:r,start:t.start,end:this.tokens[Math.max(0,this.pos-1)].end}}readRawGroup(){let t=this.expect("lbrace","after \\text"),n=1,r=t.end,o=this.source,i=r;for(;r0;){if(o[r]==="{")n++;else if(o[r]==="}"&&(n--,n===0))break;r++}if(n!==0)throw this.err("unclosed-brace","Missing closing brace.",this.peek(),"Add a matching '}'.");let s=o.slice(i,r),l=r+1;for(;this.posGo[e])),ng={hat:"\u0302",tilde:"\u0303",dot:"\u0307",ddot:"\u0308",check:"\u030C",breve:"\u0306",vec:"\u20D7",overrightarrow:"\u20D7",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1"},rg={xrightarrow:"\u27F6",xleftarrow:"\u27F5",xleftrightarrow:"\u27F7",xRightarrow:"\u27F9",xLeftarrow:"\u27F8",xLeftrightarrow:"\u27FA",xrightleftharpoons:"\u21CC",xleftrightharpoons:"\u21CB",xmapsto:"\u27FC",xhookrightarrow:"\u21AA",xhookleftarrow:"\u21A9"},og={thin:"\u2009",medium:"\u2005",thick:"\u2004",quad:"\u2003",qquad:"\u2003\u2003"},Br=null;function Pu(e,t){Br!==null&&t!==void 0&&!Br.has(e)&&Br.set(e,t)}a(Pu,"remember");function Ho(e){return{kind:"row",children:e}}a(Ho,"row");function ig(e){return{kind:"matrix",rows:e.rows.map(t=>t.condition?[H(t.expr),H(t.condition)]:[H(t.expr)]),columns:["left","left"]}}a(ig,"matrixFromCases");function sg(e,t,n,r){let o=r===void 0?{}:{hlines:r},i=t.length,l=[0,...[...new Set(n)].filter(p=>p>0&&pp-f),i],u=[];for(let p=0;pArray.from({length:m-f},(E,v)=>y[f+v]??Ho([]))),g=t.slice(f,m);u.push(g.every(y=>y==="center")?{kind:"matrix",rows:h,...o}:{kind:"matrix",rows:h,columns:g,...o})}let c=n.includes(0)?"|":"",d=n.includes(i)?"|":"";return u.length===1?{kind:"delimited",left:c,right:d,parts:u}:{kind:"delimited",left:c,right:d,parts:u,sepChar:"|"}}a(sg,"matrixWithRules");var ag={matrix:{left:"",right:""},pmatrix:{left:"(",right:")"},bmatrix:{left:"[",right:"]"},Bmatrix:{left:"{",right:"}"},vmatrix:{left:"|",right:"|"},Vmatrix:{left:"\u2016",right:"\u2016"},array:{left:"",right:""}};function oe(e,t){let n=lg(e,t);return Br!==null&&Pu(n,Br.get(e)),n}a(oe,"mapSymbols");function lg(e,t){switch(e.kind){case"symbol":return t(e);case"row":return{...e,children:e.children.map(n=>oe(n,t))};case"frac":return{...e,numerator:oe(e.numerator,t),denominator:oe(e.denominator,t)};case"radical":return{...e,radicand:oe(e.radicand,t),index:e.index?oe(e.index,t):void 0};case"supersub":return{...e,base:oe(e.base,t),sup:e.sup?oe(e.sup,t):void 0,sub:e.sub?oe(e.sub,t):void 0};case"limlow":return{...e,base:oe(e.base,t),lower:oe(e.lower,t)};case"nary":return{...e,sub:e.sub?oe(e.sub,t):void 0,sup:e.sup?oe(e.sup,t):void 0,operand:oe(e.operand,t)};case"delimited":return{...e,parts:e.parts.map(n=>oe(n,t))};case"matrix":return{...e,rows:e.rows.map(n=>n.map(r=>oe(r,t)))};case"accent":return{...e,base:oe(e.base,t)};case"borderbox":case"groupchar":return{...e,base:oe(e.base,t)};case"limupp":return{...e,base:oe(e.base,t),upper:oe(e.upper,t)};case"prescript":return{...e,base:oe(e.base,t),presup:e.presup?oe(e.presup,t):void 0,presub:e.presub?oe(e.presub,t):void 0};case"eqarr":return{...e,rows:e.rows.map(n=>oe(n,t))};case"labeledarrow":return{...e,above:e.above?oe(e.above,t):void 0,below:e.below?oe(e.below,t):void 0};default:{let n=e;throw new Error(`Unhandled IR node in mapSymbols: ${JSON.stringify(n)}`)}}}a(lg,"mapSymbolsOnce");function ug(e,t){return oe(e,n=>({kind:"symbol",text:Du(n.text,t),italic:!1,bold:n.bold}))}a(ug,"applyUnicodeVariant");function Tu(e){return oe(e,t=>({...t,bold:!0}))}a(Tu,"applyBold");function Ms(e,t){return oe(e,n=>n.color!==void 0?n:{...n,color:t})}a(Ms,"applyColor");function H(e){let t=cg(e);return Pu(t,{start:e.start,end:e.end}),t}a(H,"lower");function cg(e){switch(e.kind){case"row":return Ho(e.children.map(H));case"symbol":{let t=e.class==="letter"||e.class==="greek";return{kind:"symbol",text:e.text,italic:t}}case"text":return{kind:"symbol",text:e.text,italic:!1};case"spacing":return{kind:"symbol",text:og[e.size]??" ",italic:!1};case"func":return{kind:"symbol",text:e.name,italic:!1};case"frac":return{kind:"frac",numerator:H(e.numerator),denominator:H(e.denominator),noBar:!1};case"binom":return{kind:"delimited",left:"(",right:")",parts:[{kind:"frac",numerator:H(e.top),denominator:H(e.bottom),noBar:!0}]};case"sqrt":return{kind:"radical",radicand:H(e.radicand),index:e.index?H(e.index):void 0};case"supsub":{if(e.base.kind==="func"&&e.sub&&!e.sup&&(e.base.limits??_r.has(e.base.name)))return{kind:"limlow",base:H(e.base),lower:H(e.sub)};if(e.base.kind==="groupchar"){let t=H(e.base);if(e.base.pos==="top"&&e.sup&&!e.sub)return{kind:"limupp",base:t,upper:H(e.sup)};if(e.base.pos==="bot"&&e.sub&&!e.sup)return{kind:"limlow",base:t,lower:H(e.sub)}}return{kind:"supersub",base:H(e.base),sup:e.sup?H(e.sup):void 0,sub:e.sub?H(e.sub):void 0}}case"nary":return{kind:"nary",chr:Go[e.op]??"\u2211",sub:e.sub?H(e.sub):void 0,sup:e.sup?H(e.sup):void 0,operand:H(e.operand),limitLocation:e.limits??Cu.has(e.op)?"undOvr":"subSup"};case"delimited":{let t=e.parts.map(H);if(t.length===1&&e.sepChar===void 0){let n=t[0].kind==="row"&&t[0].children.length===1?t[0].children[0]:t[0];if(n.kind==="delimited"&&n.left===""&&n.right===""&&n.sepChar==="|")return{kind:"delimited",left:e.left,right:e.right,parts:n.parts,sepChar:"|"}}return{kind:"delimited",left:e.left,right:e.right,parts:t,sepChar:e.sepChar}}case"matrix":{let t=ag[e.matrixKind]??{left:"",right:""},n=e.rows.map(i=>i.map(H));if(e.rules&&e.rules.length>0&&e.columns)return sg(n,e.columns,e.rules,e.hlines);let r=e.hlines===void 0?{}:{hlines:e.hlines},o=e.columns===void 0?{kind:"matrix",rows:n,...r}:{kind:"matrix",rows:n,columns:e.columns,...r};return!t.left&&!t.right?o:{kind:"delimited",left:t.left,right:t.right,parts:[o]}}case"cases":return{kind:"delimited",left:"{",right:"",parts:[ig(e)]};case"cancel":return{kind:"borderbox",base:H(e.base),strikeBLTR:e.cancel==="forward"||e.cancel==="cross",strikeTLBR:e.cancel==="backward"||e.cancel==="cross"};case"groupchar":return{kind:"groupchar",chr:e.chr,pos:e.pos,base:H(e.base)};case"boxed":return{kind:"borderbox",base:H(e.base),boxed:!0};case"color":return Ms(H(e.content),e.color);case"stack":return e.pos==="top"?{kind:"limupp",base:H(e.base),upper:H(e.label)}:{kind:"limlow",base:H(e.base),lower:H(e.label)};case"accent":{let t=H(e.base);return e.accent==="bar"?{kind:"accent",base:t,bar:!0}:e.accent==="underline"?{kind:"accent",base:t,bar:!0,under:!0}:{kind:"accent",base:t,char:ng[e.accent]??"\u0302"}}case"unsupported":return{kind:"symbol",text:`[unsupported: ${e.construct}]`,italic:!1};case"fontvariant":{let t=H(e.content);return e.variant==="mathbf"?Tu(oe(t,n=>({...n,italic:!1}))):e.variant==="boldsymbol"?Tu(t):e.variant==="upright"?oe(t,n=>({...n,italic:!1})):e.variant==="mathit"?oe(t,n=>({...n,italic:!0})):ug(t,e.variant)}case"prescript":return{kind:"prescript",base:H(e.base),presup:e.presup?H(e.presup):void 0,presub:e.presub?H(e.presub):void 0};case"align":return{kind:"eqarr",rows:e.rows.map(n=>Ho(n.map(H))),justify:e.alignPoints?"left":"center"};case"tag":return Ho([]);case"labeledarrow":return{kind:"labeledarrow",chr:e.chr??rg[e.arrow]??"\u27F6",above:e.above?H(e.above):void 0,below:e.below?H(e.below):void 0};default:{let t=e;throw new Error(`Unhandled AST node: ${JSON.stringify(t)}`)}}}a(cg,"lowerNode");x();x();var qn=class extends Error{static{a(this,"GraphicsError")}constructor(t){super(t.message),this.name="GraphicsError",this.details=t}toDisplayString(){let t=[this.details.message];return this.details.suggestion&&t.push(this.details.suggestion),t.join(" ")}};function b(e,t,n,r,o){throw new qn({type:e,message:t,position:n,token:r,suggestion:o})}a(b,"fail");x();x();function vt(e,t,n,r){let o=0,i=t;for(;i({...o,end:n[i]}))}a(Os,"tokenizeGraphics");function dg(e,t){let n=t+8,r=/^([\s\S]*?)\bin\s*(?=\{)/.exec(e.slice(n));r||b("syntax","\\foreach needs \\x in {list}.",t,"foreach");let o=r[1],i="",s=o.indexOf("[");if(s>=0){let{raw:d}=vt(o,s,"[","]");i=d,o=o.slice(0,s)}n+=r[0].length;let l=vt(e,n,"{","}");for(n=l.end;n=e.length&&b("syntax",'The \\foreach body is missing its closing ";".',t,"foreach"),u=e.slice(n,p+1),n=p+1}return{token:{kind:"foreach",variables:o.trim(),options:i,list:l.raw,body:u,bodyAt:c,at:t},end:n}}a(dg,"readForeach");x();function Be(e,t=0){let n=[],r=0,o=0,i=a((s,l)=>{let u=s.trim();if(u.length===0)return;let c=l+(s.length-s.trimStart().length),d=pg(u,"=");if(d===null){n.push({key:u,at:t+c});return}n.push({key:d.before.trim(),value:d.after.trim(),at:t+c})},"push");for(let s=0;sn.key===t)?.at??0}a(se,"optionAt");function B(e){let t=e.trim();return t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t}a(B,"unbrace");function Wn(e,t,n){for(let r of e)t.has(r.key)||b("unsupported-option",`"${r.key}" is not an option this build understands on ${n}.`,r.at,r.key,`Supported here: ${[...t].sort().join(", ")}.`)}a(Wn,"rejectUnsupported");x();var _s={pi:Math.PI,e:Math.E},Rt=Math.PI/180,jo={sin:{arity:1,apply:a(([e])=>Math.sin(e*Rt),"apply")},cos:{arity:1,apply:a(([e])=>Math.cos(e*Rt),"apply")},tan:{arity:1,apply:a(([e])=>Math.tan(e*Rt),"apply")},asin:{arity:1,apply:a(([e])=>Math.asin(e)/Rt,"apply")},acos:{arity:1,apply:a(([e])=>Math.acos(e)/Rt,"apply")},atan:{arity:1,apply:a(([e])=>Math.atan(e)/Rt,"apply")},atan2:{arity:2,apply:a(([e,t])=>Math.atan2(e,t)/Rt,"apply")},sinh:{arity:1,apply:a(([e])=>Math.sinh(e),"apply")},cosh:{arity:1,apply:a(([e])=>Math.cosh(e),"apply")},tanh:{arity:1,apply:a(([e])=>Math.tanh(e),"apply")},exp:{arity:1,apply:a(([e])=>Math.exp(e),"apply")},ln:{arity:1,apply:a(([e])=>Math.log(e),"apply")},log10:{arity:1,apply:a(([e])=>Math.log10(e),"apply")},log2:{arity:1,apply:a(([e])=>Math.log2(e),"apply")},sqrt:{arity:1,apply:a(([e])=>Math.sqrt(e),"apply")},abs:{arity:1,apply:a(([e])=>Math.abs(e),"apply")},floor:{arity:1,apply:a(([e])=>Math.floor(e),"apply")},ceil:{arity:1,apply:a(([e])=>Math.ceil(e),"apply")},round:{arity:1,apply:a(([e])=>Math.round(e),"apply")},min:{arity:2,apply:a(([e,t])=>Math.min(e,t),"apply")},max:{arity:2,apply:a(([e,t])=>Math.max(e,t),"apply")},mod:{arity:2,apply:a(([e,t])=>e%t,"apply")},deg:{arity:1,apply:a(([e])=>e/Rt,"apply")},rad:{arity:1,apply:a(([e])=>e*Rt,"apply")}},fg=["x","y","z"];function mg(e,t){let n=[],r=0;for(;rZe(n,t)))}}a(Ze,"evaluate");function Ur(e,t={},n=0){return Ze(Mt(e,n),t)}a(Ur,"evaluateSource");var o1=Object.keys(jo).sort();var zo=new Set(["tikzpicture","tkzpicture","circuitikz"]),hg="tkz",Iu=[],Xo=class{constructor(t){this.toks=t;this.pos=0;this.lastEnd=0}static{a(this,"GraphicsParser")}peek(t=0){return this.toks[Math.min(this.pos+t,this.toks.length-1)]}advance(){let t=this.toks[this.pos];return this.posBs(s,i)));continue}if(r.kind==="command"&&(r.name==="usetikzlibrary"||r.name==="ctikzset")){this.advance(),this.peek().kind==="group"&&this.advance(),this.peek().kind==="semi"&&this.advance();continue}let o=this.parseStatement();n.push({...o,src:{start:r.at,end:this.lastEnd}})}}parseStatement(){let t=this.peek();if(t.kind!=="command"&&b("syntax",`Expected a command, found "${qr(t)}".`,t.at,qr(t)),t.name==="begin"){this.advance();let n=this.environmentName("begin",t.at);if(n==="axis")return this.parseAxis(t.at,2);if(n==="scope")return{kind:"scope",options:this.takeOptions(),body:this.parseStatements("scope"),at:t.at};(n==="axis3d"||n==="axis3D")&&b("unknown-command",`\\begin{${n}} is not a pgfplots environment; 3D plots use \\begin{axis} with \\addplot3.`,t.at,n),b("unknown-command",`\\begin{${n}} is not an environment this build draws.`,t.at,n,"Supported inside a picture: axis, scope.")}if(t.name==="coordinate")return this.parseCoordinate();if(t.name==="tikzset"){this.advance();let n=this.peek();return n.kind!=="group"&&b("syntax","\\tikzset needs its styles in braces.",t.at,"tikzset"),this.advance(),this.peek().kind==="semi"&&this.advance(),{kind:"tikzset",options:Be(n.raw,n.at+1),at:t.at}}if(t.name==="addplot")return this.parseAddPlot();if(t.name==="draw"||t.name==="path"||t.name==="fill"||t.name==="filldraw")return this.parseDraw();if(t.name==="node")return this.parseNode();if(t.name.startsWith(hg))return this.parseTkz();b("unknown-command",`\\${t.name} is not a drawing command this build implements.`,t.at,t.name,"Supported: \\draw, \\fill, \\filldraw, \\path, \\node, \\coordinate, \\foreach, \\tikzset, \\addplot, and scope and axis environments.")}parseAxis(t,n){let r=this.takeOptions(),o=this.parseStatements("axis"),i=[];for(let c of o)c.kind==="axis"&&b("unsupported-option","An axis cannot hold another axis.",c.at,"axis"),c.kind==="tkz"&&b("unknown-command",`\\${c.name} is a tkz-euclide command, which cannot be used inside an axis.`,c.at,c.name),(c.kind==="coordinate"||c.kind==="scope"||c.kind==="tikzset")&&b("unsupported-option",`${c.kind==="coordinate"?"\\coordinate":c.kind==="scope"?"A scope":"\\tikzset"} can't be used inside an axis in this build.`,c.at,c.kind,"Inside an axis, use \\addplot, \\draw and \\node."),i.push(c);let s=i.filter(c=>c.kind==="addplot"),l=s.some(c=>c.dimensions===3),u=s.some(c=>c.dimensions===2);return l&&u&&b("unsupported-option","An axis cannot mix \\addplot and \\addplot3 in this build \u2014 the two need different axis frames.",t),{kind:"axis",options:r,body:i,dimensions:l?3:n,at:t}}parseAddPlot(){let t=this.advance(),n=this.peek(),r=n.kind==="word"&&n.value==="3"?3:2;r===3&&this.advance();let o=r===3?"addplot3":t.name,i=this.takeOptions(),s,l=this.peek();if(l.kind==="word"&&l.value==="coordinates"){this.advance();let c=this.peek();c.kind!=="group"&&b("syntax","\\addplot coordinates must be followed by a braced list of points.",l.at,"coordinates"),this.advance(),s={kind:"coordinates",points:Ru(c.raw,c.at+1),at:c.at}}else l.kind==="group"?(this.advance(),s={kind:"expression",source:l.raw,at:l.at+1}):l.kind==="coord"?(this.advance(),s=$u(l.raw,l.at+1,o)):l.kind==="word"&&(l.value==="table"||l.value==="file")?b("unsupported-option",`\\addplot ${l.value} reads data from outside the document, which this build cannot do.`,l.at,l.value,"Write the points inline with \\addplot coordinates {...}."):b("syntax",`\\${o} needs {an expression}, ({x}, {y}), or coordinates {...}.`,l.at,qr(l));let u=this.isCommand("closedcycle");return u&&this.advance(),this.endStatement(o,t.at),{kind:"addplot",dimensions:r,options:i,data:s,closedCycle:u,at:t.at}}takeRelative(){let t=this.peek();return t.kind==="word"&&(t.value==="+"||t.value==="++")&&this.peek(1).kind==="coord"?(this.advance(),t.value):""}atCoordinate(){let t=this.peek();return t.kind==="coord"||t.kind==="word"&&(t.value==="+"||t.value==="++")&&this.peek(1).kind==="coord"}takeCoord(t,n){let r=this.takeRelative(),o=this.peek();return o.kind!=="coord"&&b("syntax",`${t} must be followed by a coordinate in brackets, like (1,2).`,n,t),this.advance(),{coord:{raw:o.raw,at:o.at+1},relative:r}}optionsHere(){return this.peek().kind==="options"?this.takeOptions():Iu}parseDraw(){let t=this.advance(),n=this.takeOptions(),r=[],o="move";for(;;){let i=this.peek();if(this.atCoordinate()){let{coord:s,relative:l}=this.takeCoord("A path",i.at);r.push({kind:"point",op:o,coord:s,relative:l}),o="move";continue}if(i.kind==="pathop"){if(this.advance(),i.value===".."){r.push(this.parseCurve(i.at)),o="move";continue}o!=="move"&&b("syntax",`Two path operators in a row ("${o}" then "${i.value}").`,i.at,i.value),o=i.value;continue}if(i.kind!=="word")break;if(i.value==="cycle"){this.advance(),r.push({kind:"cycle",at:i.at}),o="move";continue}if(i.value==="to"){this.advance();let s=this.optionsHere(),{coord:l,relative:u}=this.takeCoord("to",i.at);r.push({kind:"to",options:s,to:l,relative:u,at:i.at});continue}if(i.value==="rectangle"){this.advance();let{coord:s,relative:l}=this.takeCoord("rectangle",i.at);r.push({kind:"rectangle",to:s,relative:l});continue}if(i.value==="grid"){this.advance();let s=this.optionsHere(),{coord:l,relative:u}=this.takeCoord("grid",i.at);r.push({kind:"grid",options:s,to:l,relative:u,at:i.at});continue}if(i.value==="circle"||i.value==="ellipse"){this.advance();let s=this.optionsHere(),u=!s.some(c=>c.key==="radius"||c.key==="x radius"||c.key==="y radius")&&this.peek().kind==="coord"?this.advance():null;r.push(u?{kind:"circle",options:s,radius:u.raw,radiusAt:u.at+1,at:i.at}:{kind:"circle",options:s,radius:null,at:i.at});continue}if(i.value==="arc"){this.advance();let s=this.optionsHere(),l=s.length===0&&this.peek().kind==="coord"?this.advance():null;r.push(l?{kind:"arc",options:s,spec:l.raw,specAt:l.at+1,at:i.at}:{kind:"arc",options:s,spec:null,at:i.at});continue}if(i.value==="plot"){this.advance();let s=this.optionsHere(),l=this.peek();if(l.kind==="word"&&l.value==="coordinates"){this.advance();let u=this.peek();u.kind!=="group"&&b("syntax","plot coordinates must be followed by a braced list of points.",l.at,"coordinates"),this.advance(),r.push({kind:"plot",options:s,op:o==="move"?"move":"--",data:{coordinates:Ru(u.raw,u.at+1)},at:i.at})}else if(l.kind==="coord"){this.advance();let u=$u(l.raw,l.at+1,"plot");r.push({kind:"plot",options:s,op:o==="move"?"move":"--",data:{x:u.x.source,y:u.y.source},at:i.at})}else b("syntax","plot needs coordinates {\u2026} or ({x}, {y}).",i.at,"plot");o="move";continue}if(i.value==="node"){this.advance();let s=this.optionsHere(),l=null;this.peek().kind==="coord"&&(l=this.advance().raw.trim()),this.peek().kind==="options"&&(s=[...s,...this.takeOptions()]);let u=this.peek();u.kind!=="group"&&b("syntax","A node on a path needs its text in braces: node {text}.",i.at,"node"),this.advance(),r.push({kind:"node",options:s,name:l,text:u.raw,textAt:u.at+1,at:i.at});continue}if(i.value==="coordinate"){this.advance(),this.optionsHere();let s=this.peek();s.kind!=="coord"&&b("syntax","coordinate needs a name in brackets: coordinate (A).",i.at,"coordinate"),this.advance(),r.push({kind:"coordinate",name:s.raw.trim(),at:i.at});continue}i.value==="pic"&&b("unknown-command","pic is not something this build draws.",i.at,"pic","Mark an angle with an arc: (B) ++(0:0.5) arc (0:40:0.5).");break}return r.length===0&&b("syntax",`\\${t.name} has no coordinates.`,t.at,t.name),this.endStatement(t.name,t.at),{kind:"draw",command:t.name,options:n,parts:r,at:t.at}}parseCurve(t){let n=this.peek();n.kind==="word"&&n.value==="controls"||b("syntax",'A curve is written ".. controls (a) and (b) .. (c)".',t,".."),this.advance();let r=this.takeCoord("controls",t),o,i=this.peek();i.kind==="word"&&i.value==="and"&&(this.advance(),o=this.takeCoord("and",i.at));let s=this.peek();s.kind==="pathop"&&s.value===".."||b("syntax",`A curve's control points end with "..", then the end point.`,t,".."),this.advance();let l=this.takeCoord("..",s.at);return{kind:"curve",c1:r.coord,c1Relative:r.relative,...o?{c2:o.coord}:{},c2Relative:o?.relative??"",to:l.coord,relative:l.relative,at:t}}parseNode(){let t=this.advance(),n=this.takeOptions(),r=null;this.peek().kind==="coord"&&(r=this.advance().raw.trim()),this.peek().kind==="options"&&(n=[...n,...this.takeOptions()]);let o={raw:"0,0",at:t.at},i=!1,s=this.peek();if(s.kind==="word"&&s.value==="at"){this.advance();let u=this.peek();u.kind!=="coord"&&b("syntax","\\node at must be followed by a coordinate.",s.at,"at"),this.advance(),o={raw:u.raw,at:u.at+1},i=!0,this.peek().kind==="options"&&(n=[...n,...this.takeOptions()])}let l=this.peek();return l.kind!=="group"&&b("syntax","\\node needs its text in braces.",s.at,"node"),this.advance(),this.endStatement("node",t.at),{kind:"node",options:n,name:r,at_:o,placed:i,text:l.raw,textAt:l.at+1,at:t.at}}parseCoordinate(){let t=this.advance();this.takeOptions();let n=this.peek();n.kind!=="coord"&&b("syntax","\\coordinate needs a name: \\coordinate (A) at (1,2);",t.at,"coordinate"),this.advance();let r=this.peek();r.kind==="word"&&r.value==="at"||b("syntax","\\coordinate needs a position: \\coordinate (A) at (1,2);",n.at,"coordinate"),this.advance();let o=this.peek();return o.kind!=="coord"&&b("syntax","\\coordinate ... at must be followed by a coordinate.",r.at,"at"),this.advance(),this.endStatement("coordinate",t.at),{kind:"coordinate",name:n.raw.trim(),at_:{raw:o.raw,at:o.at+1},at:t.at}}parseTkz(){let t=this.advance(),n=this.takeOptions(),r=[];for(;;){let o=this.peek();if(o.kind==="coord"){this.advance(),r.push({kind:"coord",raw:o.raw,at:o.at+1});continue}if(o.kind==="group"){this.advance(),r.push({kind:"group",raw:o.raw,at:o.at+1});continue}break}return this.peek().kind==="semi"&&this.advance(),{kind:"tkz",name:t.name,options:n,args:r,at:t.at}}};function qr(e){switch(e.kind){case"command":return`\\${e.name}`;case"options":return`[${e.raw}]`;case"group":return`{${e.raw}}`;case"coord":return`(${e.raw})`;case"pathop":case"word":return e.value;case"semi":return";";case"eof":return"end of input";case"foreach":return"\\foreach"}}a(qr,"tokenText");function $u(e,t,n){let r=[],o=0,i=0;for(let s=0;s<=e.length;s++){let l=e[s];if(l==="{"||l==="(")o++;else if(l==="}"||l===")")o--;else if(l===","&&o===0||s===e.length){let u=e.slice(i,s),c=u.length-u.trimStart().length,d=u.trim(),p=d.startsWith("{")&&d.endsWith("}");r.push({source:p?d.slice(1,-1):d,at:t+i+c+(p?1:0)}),i=s+1}}return(r.length!==2||r.some(s=>s.source.trim()===""))&&b("syntax",`\\${n} (\u2026) is a parametric plot and needs exactly two expressions: ({x}, {y}).`,t,`(${e})`),{kind:"parametric",x:r[0],y:r[1],at:t-1}}a($u,"parseParametric");function Ru(e,t){let n=[],r=0;for(;r=2&&n[s-2]!==void 0&&Number.isFinite(Number(n[s-2]))?u-l:c>=u?1:-1;(d===0||Math.sign(d)!==Math.sign(c-u||d))&&b("syntax","This \\foreach range never reaches its end.",t,"...");for(let p=u+d;(d>0?pc+1e-9)&&(i.push(_u(p)),!(i.length>Fs));p+=d);}return i}a(gg,"foreachValues");function Mu(e,t,n){return e.replace(new RegExp(`\\\\${t}(?![A-Za-z@])`,"g"),n)}a(Mu,"substitute");function Bs(e,t){return e.kind==="scope"?{...e,src:t,fromLoop:!0,body:e.body.map(n=>Bs(n,t))}:e.kind==="axis"?{...e,src:t,fromLoop:!0,body:e.body.map(n=>Bs(n,t))}:{...e,src:t,fromLoop:!0}}a(Bs,"fromLoop");function yg(e){let t=e.variables.split("/").map(s=>s.trim().replace(/^\\/,""));t.some(s=>!/^[A-Za-z@]+$/.test(s))&&b("syntax","\\foreach variables are written \\x, or \\x/\\y.",e.at,e.variables);let n=Be(e.options,e.at),r=null,o=[];for(let s of n)if(s.key==="count"&&s.value){let l=/^\\([A-Za-z@]+)(?:\s+from\s+(-?\d+))?$/.exec(s.value.trim());l||b("syntax","count is written count=\\i (or count=\\i from 0).",s.at,s.value),r={name:l[1],from:l[2]===void 0?1:Number(l[2])}}else if(s.key==="evaluate"&&s.value){let l=/^\\([A-Za-z@]+)\s+as\s+\\([A-Za-z@]+)\s+using\s+([\s\S]+)$/.exec(s.value.trim());l||b("syntax","evaluate is written evaluate=\\x as \\y using \\x*2.",s.at,s.value),o.push({from:l[1],name:l[2],using:l[3].trim()})}else b("unsupported-option",`"${s.key}" is not a \\foreach option this build understands.`,s.at,s.key,"Supported: count, evaluate.");let i=[];return gg(e.list,e.at).forEach((s,l)=>{++Ou>Fs&&b("unsupported-option",`\\foreach would run more than ${Fs} times in one picture.`,e.at,"foreach");let u=s.split("/").map(f=>f.trim()),c=e.body,d=t.map((f,m)=>[f,u[Math.min(m,u.length-1)]]);r&&d.push([r.name,String(r.from+l)]);for(let f of o){let m=d.find(([h])=>h===f.from)?.[1]??"0";d.push([f.name,_u(Ur(Mu(f.using,f.from,`(${m})`).replace(/^\{|\}$/g,""),{},e.at))])}for(let[f,m]of[...d].sort((h,g)=>g[0].length-h[0].length))c=Mu(c,f,m);let p=Os(c).map(f=>({...f,at:f.at+e.bodyAt}));i.push(...new Xo(p).parseBody())}),i}a(yg,"expandForeach");function Lu(e){return Ou=0,new Xo(Os(e)).parsePicture()}a(Lu,"parseGraphics");x();function Fu(e){if(e.length===0)return{minX:0,minY:0,maxX:1,maxY:1};let t=1/0,n=1/0,r=-1/0,o=-1/0;for(let i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y);if(r-t<1){let i=(t+r)/2;t=i-.5,r=i+.5}if(o-n<1){let i=(n+o)/2;n=i-.5,o=i+.5}return{minX:t,minY:n,maxX:r,maxY:o}}a(Fu,"boundsOf");x();x();function bg(e){let t=[],n=0,r="";for(;n0&&(t.push({math:!1,text:r}),r=""),t.push({math:!0,text:e.slice(n+1,i)}),n=i+1;continue}r+=o,n++}return r.length>0&&t.push({math:!1,text:r}),t}a(bg,"segments");function Wr(e,t,n){switch(e.kind){case"row":return e.children.flatMap(r=>Wr(r,t,n));case"symbol":return e.text.length===0?[]:[{text:e.text,baseline:t,italic:e.italic}];case"supersub":{t!=="normal"&&b("unsupported-expression","A label can raise or lower text once, but not a script on a script.",n,void 0,"Simplify the label, or put the expression in the surrounding text instead.");let r=[...Wr(e.base,"normal",n)];return e.sub&&r.push(...Wr(e.sub,"sub",n)),e.sup&&r.push(...Wr(e.sup,"sup",n)),r}default:b("unsupported-expression",`A label cannot contain a ${wg(e.kind)} \u2014 a plot label is a single line of text.`,n,e.kind,"Use a simpler label, or place the expression in the document text near the figure.")}}a(Wr,"runsFromIr");function wg(e){switch(e){case"frac":return"fraction";case"radical":return"radical";case"matrix":return"matrix";case"nary":return"large operator";case"delimited":return"bracketed group";case"accent":return"accented symbol";default:return e}}a(wg,"describe");function Hn(e,t=0){let n=[];for(let r of bg(e)){if(!r.math){let o=/\\[A-Za-z]+/.exec(r.text);o&&b("unknown-command",`${o[0]} in a label's text is not drawn: only plain text and $...$ maths are.`,t,o[0],o[0]==="\\chemfig"?"Draw a structure with \\chemfig on its own, or a reaction with \\schemestart ... \\schemestop, not inside a TikZ node.":"Write plain text, or put maths between $...$."),r.text.length>0&&n.push({text:r.text,baseline:"normal",italic:!1});continue}r.text.trim().length!==0&&n.push(...Wr(H(Qt(r.text)),"normal",t))}return n}a(Hn,"labelRuns");function bn(e,t){let n={kind:"text",at:t.at,runs:Hn(e,t.offset??0),anchor:t.anchor,baseline:t.baseline,fontSize:t.fontSize,color:t.color};return t.rotate===void 0?n:{...n,rotate:t.rotate}}a(bn,"textItem");var Yo=360,qs=260,en={top:16,right:16,bottom:40,left:48},Ws=Yo+en.left+en.right,ei=qs+en.top+en.bottom,Vo=12,xg=22;function Hs(e,t){if(e==="box"||e==="left")return{margin:en,plotWidth:Yo,plotHeight:qs};let n={top:t?xg:Vo,right:Vo,bottom:Vo,left:Vo};return{margin:n,plotWidth:Ws-n.left-n.right,plotHeight:ei-n.top-n.bottom}}a(Hs,"axisLayout");var vg=Hs("box",!1),dt="#333333",kg="#cccccc",Gn=11,Us=10,Ot={color:dt,width:1},Ko={color:kg,width:.6},Eg=new Set(["xmin","xmax","ymin","ymax","zmin","zmax","xlabel","ylabel","zlabel","title","grid","xtick","ytick","ztick","width","height","view","scale only axis","axis lines","axis line style","enlargelimits","samples","domain"]);function Bu(e,t,n){let r=L(e,t);return r===void 0||r.trim()===""?n:Ur(B(r),{},0)}a(Bu,"numberOption");function Gs(e,t,n,r){let o=L(e,`${t}min`),i=L(e,`${t}max`);if(o===void 0||i===void 0){if(r)return r;b("unsupported-option",`The axis does not give ${t}min and ${t}max, and this build does not infer limits from the data.`,n,`${t}min`,`Add ${t}min and ${t}max to the axis options.`)}let s=Bu(e,`${t}min`,0),l=Bu(e,`${t}max`,1);return l>s||b("unsupported-option",`${t}max must be greater than ${t}min.`,n,`${t}max`),{min:s,max:l}}a(Gs,"readRange");function qu(e,t,n=vg){let{margin:r,plotWidth:o,plotHeight:i}=n,s=o/(e.max-e.min),l=i/(t.max-t.min),u=a((p,f)=>({x:r.left+(p-e.min)*s,y:r.top+i-(f-t.min)*l}),"toDevice"),c=a(p=>({x:e.min+(p.x-r.left)/s,y:t.min+(r.top+i-p.y)/l}),"toData"),d=Math.min(Math.max(0,t.min),t.max);return{x:e,y:t,layout:n,toDevice:u,toData:c,baselineY:u(e.min,d).y,baselineValue:d}}a(qu,"buildFrame");function Ag(e){let t=e.max-e.min,n=t/6,r=Math.pow(10,Math.floor(Math.log10(n))),o=[1,2,5,10].map(l=>l*r).find(l=>t/l<=8)??r*10,i=[],s=Math.ceil(e.min/o)*o;for(let l=s;l<=e.max+o*1e-9;l+=o)i.push(Number(l.toFixed(10)));return i}a(Ag,"defaultTicks");function Sg(e,t){let n=L(e,t);if(n===void 0)return null;let r=B(n).trim();return r===""||r==="\\empty"?[]:r.split(",").map(o=>Ur(o.trim()))}a(Sg,"explicitTicks");function Zo(e,t,n){return Sg(e,n)??Ag(t)}a(Zo,"ticksFor");function Jo(e){if(Object.is(e,-0))return"0";let t=Number(e.toFixed(6));return String(t)}a(Jo,"formatTick");function Dg(e,t){let n=L(e,"grid");if(n===void 0)return"none";let r=B(n).trim();if(r==="none"||r==="false")return"none";if(r==="major"||r===""||r==="true")return"major";if(r==="both"||r==="minor")return"both";b("unsupported-option",`grid=${r} is not supported; use none, major or both.`,t,r)}a(Dg,"readGrid");function Tg(e,t){let n=L(e,"axis lines");if(n===void 0)return"box";let r=B(n).trim();if(r==="box")return"box";if(r==="left")return"left";if(r==="middle"||r==="center")return"middle";if(r==="none")return"none";b("unsupported-option",`axis lines=${r} is not supported; use box, left, middle, center or none.`,t,r)}a(Tg,"readLines");function Wu(e,t){return Wn(e,Eg,"an axis"),{grid:Dg(e,t),lines:Tg(e,t)}}a(Wu,"readFrameOptions");function Hu(e,t,n,r){if(n.lines==="middle"||n.lines==="none")return Cg(e,t,n,r);let o=[],i=Zo(t,e.x,"xtick"),s=Zo(t,e.y,"ytick");if(n.grid!=="none"){for(let d of i){let p=e.toDevice(d,e.y.max),f=e.toDevice(d,e.y.min);o.push({kind:"path",points:[p,f],closed:!1,stroke:Ko})}for(let d of s){let p=e.toDevice(e.x.min,d),f=e.toDevice(e.x.max,d);o.push({kind:"path",points:[p,f],closed:!1,stroke:Ko})}}if(n.lines==="left"){let d=e.toDevice(e.x.min,e.y.min),p=e.toDevice(e.x.max,e.y.min),f=e.toDevice(e.x.min,e.y.max);o.push({kind:"path",points:[d,p],closed:!1,stroke:Ot}),o.push({kind:"path",points:[d,f],closed:!1,stroke:Ot}),o.push(Qo(d,p),Qo(d,f))}else{let d=[e.toDevice(e.x.min,e.y.min),e.toDevice(e.x.max,e.y.min),e.toDevice(e.x.max,e.y.max),e.toDevice(e.x.min,e.y.max)];o.push({kind:"path",points:d,closed:!0,stroke:Ot})}for(let d of i){let p=e.toDevice(d,e.y.min);o.push({kind:"path",points:[p,{x:p.x,y:p.y-4}],closed:!1,stroke:Ot}),o.push({kind:"text",at:{x:p.x,y:p.y+6},runs:[{text:Jo(d),baseline:"normal",italic:!1}],anchor:"middle",baseline:"top",fontSize:Us,color:dt})}for(let d of s){let p=e.toDevice(e.x.min,d);o.push({kind:"path",points:[p,{x:p.x+4,y:p.y}],closed:!1,stroke:Ot}),o.push({kind:"text",at:{x:p.x-6,y:p.y},runs:[{text:Jo(d),baseline:"normal",italic:!1}],anchor:"end",baseline:"middle",fontSize:Us,color:dt})}let l=L(t,"xlabel");l!==void 0&&o.push(bn(B(l),{at:{x:en.left+Yo/2,y:ei-6},anchor:"middle",baseline:"bottom",fontSize:Gn,color:dt,offset:r}));let u=L(t,"ylabel");u!==void 0&&o.push(bn(B(u),{at:{x:12,y:en.top+qs/2},anchor:"middle",baseline:"middle",fontSize:Gn,color:dt,rotate:-90,offset:r}));let c=L(t,"title");return c!==void 0&&o.push(bn(B(c),{at:{x:en.left+Yo/2,y:4},anchor:"middle",baseline:"top",fontSize:Gn+1,color:dt,offset:r})),o}a(Hu,"drawAxis");function Qo(e,t){let n=t.x-e.x,r=t.y-e.y,o=Math.hypot(n,r)||1,i=n/o,s=r/o,l=7,u=3;return{kind:"path",points:[{x:t.x+i*2,y:t.y+s*2},{x:t.x-i*l-s*u,y:t.y-s*l+i*u},{x:t.x-i*l+s*u,y:t.y-s*l-i*u}],closed:!0,fill:{color:dt,opacity:1}}}a(Qo,"axisArrow");function Uu(e){return Math.min(Math.max(0,e.min),e.max)}a(Uu,"crossing");function Cg(e,t,n,r){let o=[],i=Zo(t,e.x,"xtick"),s=Zo(t,e.y,"ytick"),{margin:l,plotWidth:u,plotHeight:c}=e.layout,d=l.left,p=l.top,f=d+u,m=p+c;if(n.grid!=="none"){for(let g of i)o.push({kind:"path",points:[e.toDevice(g,e.y.max),e.toDevice(g,e.y.min)],closed:!1,stroke:Ko});for(let g of s)o.push({kind:"path",points:[e.toDevice(e.x.min,g),e.toDevice(e.x.max,g)],closed:!1,stroke:Ko})}if(n.lines==="middle"){let g=Uu(e.x),y=Uu(e.y),E=e.toDevice(0,y).y,v=e.toDevice(g,0).x,w={x:d,y:E},A={x:f,y:E},N={x:v,y:m},S={x:v,y:p};o.push({kind:"path",points:[w,A],closed:!1,stroke:Ot}),o.push({kind:"path",points:[N,S],closed:!1,stroke:Ot}),o.push(Qo(w,A),Qo(N,S));let k=m-E>16,T=v-d>26,O=g===0&&y===0,C=a((_,M,W,j)=>({kind:"text",at:M,runs:[{text:_,baseline:"normal",italic:!1}],anchor:W,baseline:j,fontSize:Us,color:dt}),"label");for(let _ of i){let M=e.toDevice(_,y);M.x>f-10||M.xm-2||O&&_===0||(o.push({kind:"path",points:[{x:M.x-3,y:M.y},{x:M.x+3,y:M.y}],closed:!1,stroke:Ot}),o.push(C(Jo(_),{x:T?M.x-5:M.x+5,y:M.y},T?"end":"start","middle")))}O&&o.push(C("0",{x:v-4,y:E+4},"end","top"));let D=L(t,"xlabel");D!==void 0&&o.push(bn(B(D),{at:{x:f-4,y:E-6},anchor:"end",baseline:"bottom",fontSize:Gn,color:dt,offset:r}));let P=L(t,"ylabel");P!==void 0&&o.push(bn(B(P),{at:{x:v+8,y:p+2},anchor:"start",baseline:"top",fontSize:Gn,color:dt,offset:r}))}let h=L(t,"title");return h!==void 0&&o.push(bn(B(h),{at:{x:d+u/2,y:4},anchor:"middle",baseline:"top",fontSize:Gn+1,color:dt,offset:r})),o}a(Cg,"drawInnerAxis");x();x();x();var ti={red:[255,0,0],green:[0,255,0],blue:[0,0,255],cyan:[0,255,255],magenta:[255,0,255],yellow:[255,255,0],black:[0,0,0],gray:[128,128,128],grey:[128,128,128],white:[255,255,255],darkgray:[64,64,64],lightgray:[191,191,191],brown:[191,128,64],lime:[191,255,0],olive:[128,128,0],orange:[255,128,0],pink:[255,191,191],purple:[191,0,64],teal:[0,128,128],violet:[128,0,128]},_t=a(e=>Math.max(0,Math.min(255,Math.round(e))).toString(16).padStart(2,"0"),"hex");function Ng(e,t,n){let r=n/100;return`#${_t(e[0]*r+t[0]*(1-r))}${_t(e[1]*r+t[1]*(1-r))}${_t(e[2]*r+t[2]*(1-r))}`}a(Ng,"mix");function tn(e,t){let n=e.trim();if(n.length===0&&b("unsupported-option","A colour was given with no value.",t),/^#[0-9a-fA-F]{6}$/.test(n))return n.toLowerCase();let r=/^\{?\s*rgb\s*,\s*255\s*:\s*red\s*,\s*(\d+)\s*;\s*green\s*,\s*(\d+)\s*;\s*blue\s*,\s*(\d+)\s*\}?$/.exec(n);if(r)return`#${_t(Number(r[1]))}${_t(Number(r[2]))}${_t(Number(r[3]))}`;let o=n.split("!").map(c=>c.trim()),i=ti[o[0].toLowerCase()];if(i===void 0&&b("unsupported-option",`"${o[0]}" is not a colour this build knows.`,t,o[0],`Known colours: ${Object.keys(ti).sort().join(", ")}.`),o.length===1)return`#${_t(i[0])}${_t(i[1])}${_t(i[2])}`;let s=Number(o[1]);(!Number.isFinite(s)||s<0||s>100)&&b("unsupported-option",`"${o[1]}" is not a percentage between 0 and 100.`,t,o[1]);let l=o[2]??"white",u=ti[l.toLowerCase()];return u===void 0&&b("unsupported-option",`"${l}" is not a colour this build knows.`,t,l),o.length>3&&b("unsupported-option",`The colour expression "${n}" is more complex than this build supports.`,t,n),Ng(i,u,s)}a(tn,"resolveColor");var js=Object.keys(ti).sort();var Pg=new Set(js);function Ig(e){return e.value!==void 0?!1:/^#[0-9a-fA-F]{6}$/.test(e.key)?!0:Pg.has(e.key.split("!")[0].trim().toLowerCase())}a(Ig,"isColorExpression");function kt(e){let t,n=[];for(let r of e)Ig(r)?t=tn(r.key,r.at):n.push(r);return{color:t,rest:n}}a(kt,"currentColor");var Gu=[["ultra thin",.4],["very thin",.6],["thin",.8],["semithick",1],["thick",1.6],["very thick",2.4],["ultra thick",3.2]],$g=1.2,Lt=Gu.map(([e])=>e),nn=["solid","dashed","dotted","densely dashed","loosely dashed"];function Xs(e,t=$g){let n=t;for(let o of e){let i=Gu.find(([s])=>s===o.key);i&&(n=i[1])}let r=L(e,"line width");if(r!==void 0){let o=Number.parseFloat(B(r));(!Number.isFinite(o)||o<=0)&&b("unsupported-option",`line width="${r}" is not a positive length.`,se(e,"line width"),r),n=o}return n}a(Xs,"readLineWidth");function Rg(e){let t;for(let n of e)n.key==="solid"?t=void 0:n.key==="dashed"?t=[4,3]:n.key==="densely dashed"?t=[3,1.5]:n.key==="loosely dashed"?t=[6,4]:n.key==="dotted"&&(t=[1,2]);return t}a(Rg,"readDash");function wn(e,t,n=!0){let r=L(e,"draw")??L(e,"color");if(r!==void 0&&B(r).trim()==="none"||!n&&r===void 0)return;let o=r===void 0||r.trim()===""?t:tn(B(r),se(e,"draw")),i=Xs(e),s=Rg(e);return s===void 0?{color:o,width:i}:{color:o,width:i,dash:s}}a(wn,"readStroke");function jn(e,t){let n=L(e,t);if(n===void 0)return;let r=Number(B(n));return(!Number.isFinite(r)||r<0||r>1)&&b("unsupported-option",`${t} must be between 0 and 1, not "${n}".`,se(e,t),n),r}a(jn,"readOpacity");function ju(e){return jn(e,"fill opacity")??jn(e,"opacity")}a(ju,"fillOpacity");function Hr(e){let t=L(e,"fill");if(t===void 0)return;let n=B(t).trim();if(n==="none")return;let r=jn(e,"fill opacity")??jn(e,"opacity")??1;return{color:tn(n,se(e,"fill")),opacity:r}}a(Hr,"readFill");var Mg=.2;function Xu(e,t){let n=jn(e,"fill opacity")??jn(e,"opacity")??Mg;return{color:t,opacity:n}}a(Xu,"impliedFill");var Og=50,_g=3,zs="#1f4e9c",Lg=new Set(["domain","samples","fill","draw","color","opacity","fill opacity","line width","name path","smooth","only marks","mark","mark size","variable","unbounded coords","restrict x to domain","restrict y to domain",...Lt,...nn]);function zu(e,t){return Vs(e,"domain")??{from:t.x.min,to:t.x.max}}a(zu,"readDomain");function Vs(e,t){let n=L(e,t);if(n===void 0)return;let r=B(n).trim(),o=se(e,t),i=r.split(":");i.length!==2&&b("unsupported-option",`${t} must be written "from:to", not "${r}".`,o,r);let s=Number(i[0]),l=Number(i[1]);return(!Number.isFinite(s)||!Number.isFinite(l))&&b("unsupported-option",`${t}="${r}" is not a pair of numbers.`,o,r),l<=s&&b("unsupported-option",`${t}="${r}" ends at or before it starts.`,o,r),{from:s,to:l}}a(Vs,"readInterval");function Fg(e){let t=L(e,"variable");if(t===void 0)return"x";let n=B(t).trim();return/^\\?[A-Za-z]+$/.test(n)||b("unsupported-option",`variable must name a parameter, like \\t, not "${t}".`,se(e,"variable"),t),n}a(Fg,"readVariable");function Bg(e){let t=L(e,"unbounded coords");if(t===void 0)return!1;let n=B(t).trim();if(n==="jump")return!0;if(n==="discard")return!1;b("unsupported-option",`unbounded coords=${n} is not supported; use jump or discard.`,se(e,"unbounded coords"),n)}a(Bg,"readJump");function Ug(e){let t=L(e,"mark size");if(t===void 0)return _g;let n=Number.parseFloat(B(t));return(!Number.isFinite(n)||n<=0||n>20)&&b("unsupported-option",`mark size="${t}" is not a size between 0 and 20pt.`,se(e,"mark size"),t),n*4/3}a(Ug,"readMarkSize");function Vu(e){let t=L(e,"samples");if(t===void 0)return Og;let n=se(e,"samples"),r=Number(B(t).trim());return(!Number.isInteger(r)||r<2)&&b("unsupported-option",`samples must be a whole number of at least 2, not "${t}".`,n,t),r>5e3&&b("unsupported-option",`samples=${r} is beyond this build's limit of 5000.`,n,t),r}a(Vu,"readSamples");function qg(e,t){let{color:n,rest:r}=kt(e);Wn(r,Lg,"\\addplot");let o=r.some(u=>u.key==="only marks"),i=o?void 0:wn(r,n??zs),s=i?.color??n??zs,l=Hr(r)??(t?Xu(r,s):void 0);return{stroke:i,fill:l,markersOnly:o}}a(qg,"readStyle");function Wg(e,t,n,r){let o=[];for(let i=0;i{let n=t.raw.replace(/^\s*axis cs:/,"").split(",");n.length<2&&b("bad-coordinate",`"(${t.raw})" is not a coordinate pair.`,t.at,t.raw);let r=Number(n[0].trim()),o=Number(n[1].trim());return(!Number.isFinite(r)||!Number.isFinite(o))&&b("bad-coordinate",`"(${t.raw})" is not a pair of numbers.`,t.at,t.raw),{x:r,y:o}})}a(Gg,"readCoordinates");function jg(e){return e.filter(t=>Number.isFinite(t.x)&&Number.isFinite(t.y))}a(jg,"finitePoints");function Xg(e,t){let n=Vs(t,"restrict x to domain"),r=Vs(t,"restrict y to domain");return!n&&!r?e:e.map(o=>n&&(o.xn.to)||r&&(o.yr.to)?{x:o.x,y:NaN}:o)}a(Xg,"restrict");function zg(e,t){if(!t){let o=jg(e);return o.length===0?[]:[o]}let n=[],r=[];for(let o of e)Number.isFinite(o.x)&&Number.isFinite(o.y)?r.push(o):r.length>0&&(n.push(r),r=[]);return r.length>0&&n.push(r),n}a(zg,"runsOf");function Yu(e,t){e.dimensions!==2&&b("unsupported-option","\\addplot3 needs a 3-D axis; this plot is in a 2-D one.",e.at);let n=qg(e.options,e.closedCycle),r;if(e.data.kind==="expression"){let i=Mt(e.data.source,e.data.at),{from:s,to:l}=zu(e.options,t);r=Wg(i,s,l,Vu(e.options))}else e.data.kind==="parametric"?r=Hg(e,t):r=Gg(e);let o=zg(Xg(r,e.options),Bg(e.options));if(o.length===0&&b("unsupported-expression","The plot produced no drawable points \u2014 every sample was infinite or undefined.",e.at,void 0,"Check the domain: a function with an asymptote inside it has no value there."),n.markersOnly){let i=Ug(e.options),s=kt(e.options).color??n.fill?.color??zs;return o.flat().map(l=>({kind:"marker",at:t.toDevice(l.x,l.y),shape:"dot",size:i,fill:{color:s,opacity:1}}))}return o.map(i=>{let s=e.closedCycle?[{x:i[i.length-1].x,y:t.baselineValue},{x:i[0].x,y:t.baselineValue}]:[];return{kind:"path",points:[...i,...s].map(u=>t.toDevice(u.x,u.y)),closed:e.closedCycle,...n.stroke?{stroke:n.stroke}:{},...n.fill?{fill:n.fill}:{}}})}a(Yu,"drawPlot");x();function ni(e,t){return e.x>=t.left-1e-6&&e.x<=t.right+1e-6&&e.y>=t.top-1e-6&&e.y<=t.bottom+1e-6}a(ni,"inside");function Vg(e,t,n){let r=t.x-e.x,o=t.y-e.y,i=0,s=1,l=[[-r,e.x-n.left],[r,n.right-e.x],[-o,e.y-n.top],[o,n.bottom-e.y]];for(let[c,d]of l){if(Math.abs(c)<1e-12){if(d<-1e-6)return null;continue}let p=d/c;if(c<0){if(p>s)return null;p>i&&(i=p)}else{if(p({x:e.x+r*c,y:e.y+o*c}),"at");return[i===0?e:u(i),s===1?t:u(s)]}a(Vg,"clipSegment");function Ku(e,t){if(e.length===1)return ni(e[0],t)?[[e[0]]]:[];let n=[],r=[];for(let o=0;o+10&&n.push(r),r=[];continue}let[s,l]=i,u=r[r.length-1];(!u||u.x!==s.x||u.y!==s.y)&&(r.length>0&&n.push(r),r=[s]),r.push(l),l!==e[o+1]&&(n.push(r),r=[])}return r.length>0&&n.push(r),n.filter(o=>o.length>=2)}a(Ku,"clipPolyline");function Yg(e,t){let n=a((s,l,u)=>({x:u,y:s.y+(l.y-s.y)*(u-s.x)/(l.x-s.x)}),"lerpX"),r=a((s,l,u)=>({x:s.x+(l.x-s.x)*(u-s.y)/(l.y-s.y),y:u}),"lerpY"),o=[{keep:a(s=>s.x>=t.left-1e-6,"keep"),cross:a((s,l)=>n(s,l,t.left),"cross")},{keep:a(s=>s.x<=t.right+1e-6,"keep"),cross:a((s,l)=>n(s,l,t.right),"cross")},{keep:a(s=>s.y>=t.top-1e-6,"keep"),cross:a((s,l)=>r(s,l,t.top),"cross")},{keep:a(s=>s.y<=t.bottom+1e-6,"keep"),cross:a((s,l)=>r(s,l,t.bottom),"cross")}],i=[...e];for(let s of o){if(i.length===0)break;let l=i;i=[];for(let u=0;uni(r,t)))return[e];if(!e.closed)return Ku(e.points,t).map(r=>({...e,points:r}));let n=[];if(e.fill){let r=Yg(e.points,t);if(r.length>=3){let{stroke:o,...i}=e;n.push({...i,points:r})}}if(e.stroke){let r=[...e.points,e.points[0]];for(let o of Ku(r,t)){let{fill:i,...s}=e;n.push({...s,closed:!1,points:o})}}return n}a(Kg,"clipPath");function Zu(e,t){let n=[];for(let r of e)switch(r.kind){case"path":n.push(...Kg(r,t));break;case"marker":case"text":ni(r.at,t)&&n.push(r);break;case"circle":case"arc":ni(r.center,t)&&n.push(r);break}return n}a(Zu,"clipToRect");x();function G(e){if(!Number.isFinite(e))return"0";let t=Number(e.toFixed(3));return Object.is(t,-0)?"0":String(t)}a(G,"num");function Xn(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}a(Xn,"escapeXml");function Zg(e){return e.map(t=>`${G(t.x)},${G(t.y)}`).join(" ")}a(Zg,"pointsAttr");function xn(e){let t=[];return e.fill?(t.push(`fill="${Xn(e.fill.color)}"`),e.fill.opacity!==1&&t.push(`fill-opacity="${G(e.fill.opacity)}"`)):t.push('fill="none"'),e.stroke&&(t.push(`stroke="${Xn(e.stroke.color)}"`,`stroke-width="${G(e.stroke.width)}"`),e.stroke.dash&&e.stroke.dash.length>0&&t.push(`stroke-dasharray="${e.stroke.dash.map(G).join(" ")}"`)),t.join(" ")}a(xn,"paintAttrs");function Jg(e){return e.points.length===0?"":`<${e.closed?"polygon":"polyline"} points="${Zg(e.points)}" ${xn(e)}/>`}a(Jg,"pathElement");function Ju(e){return``}a(Ju,"circleElement");function Qg(e){let t=a(u=>({x:e.center.x+e.radius*Math.cos(u),y:e.center.y-e.radius*Math.sin(u)}),"at"),n=t(e.startAngle),r=t(e.endAngle),o=e.endAngle-e.startAngle,i=Math.abs(o)>Math.PI?1:0,s=o>0?0:1;return Math.abs(o)>=Math.PI*2-1e-9?Ju({...e,kind:"circle"}):``}a(Qg,"arcElement");function ey(e){let{x:t,y:n}=e.at,r=e.size;switch(e.shape){case"dot":return``;case"circle":return``;case"square":return``;case"cross":{let o=xn({stroke:e.stroke});return``}}}a(ey,"markerElement");function ty(e){switch(e.baseline){case"top":return e.at.y+e.fontSize*.8;case"middle":return e.at.y+e.fontSize*.32;case"bottom":return e.at.y}}a(ty,"baselineY");function ny(e){if(e.runs.length===0)return"";let t=G(e.at.x),n=G(ty(e)),r=0,o=e.runs.map(s=>{let l=s.baseline==="sup"?-.42:s.baseline==="sub"?.28:0,u=(l-r)*e.fontSize;r=l;let c=[`dy="${G(u)}"`];return s.baseline!=="normal"&&c.push(`font-size="${G(e.fontSize*.72)}"`),s.italic&&c.push('font-style="italic"'),`${Xn(s.text)}`}),i=[`x="${t}"`,`y="${n}"`,`font-size="${G(e.fontSize)}"`,`fill="${Xn(e.color)}"`,`text-anchor="${e.anchor}"`];return e.rotate!==void 0&&i.push(`transform="rotate(${G(e.rotate)} ${t} ${n})"`),`${o.join("")}`}a(ny,"textElement");function ry(e){switch(e.kind){case"path":return Jg(e);case"circle":return Ju(e);case"arc":return Qg(e);case"text":return ny(e);case"marker":return ey(e)}}a(ry,"itemElement");function Qu(e,t={}){let n=[];n.push(``),t.title!==void 0&&n.push(`${Xn(t.title)}`),e.background!==void 0&&n.push(``);for(let r of e.items){let o=ry(r);o.length>0&&n.push(o)}return n.push(""),n.join("")}a(Qu,"sceneToSvg");function Ys(e){return new TextEncoder().encode(e)}a(Ys,"svgToBytes");x();var Et=13,de=Et,Ks=3*de,oy=.2*de,pt=.25*de,iy=.65*de,sy=.3*de,Jn=1.1,ay=.75,wc=45,rn="#000000",ri=10,ly=3*de,oi=1*de,ii=.5*de,Xr=.3*de,uy=.85*Et,ec=.7*de,xc=.9*Et,ai=.55*de,ea=.22*de,vn=.18*de,vc=.72,li=.34,kc=.3,Ec=.25,cy=new Set(["-","=","~","<",">"]),tc=new Set(["-","=","~","<",">","(",")","*","[","]","?","!","@"]),dy=new Set(["draw","color","line width",...Lt,...nn]),ui={oplus:"\u2295",ominus:"\u2296",delta:"\u03B4",Delta:"\u0394",cdot:"\xB7",bullet:"\u2022",",":"\u2009"," ":" ","%":"%","&":"&","#":"#",textdegree:"\xB0",degree:"\xB0"},py={A:.7,B:.64,C:.66,D:.73,E:.6,F:.56,G:.72,H:.74,I:.34,J:.38,K:.7,L:.58,M:.88,N:.73,O:.75,P:.59,Q:.75,R:.66,S:.54,T:.62,U:.72,V:.7,W:.96,X:.7,Y:.68,Z:.6,a:.48,b:.53,c:.44,d:.53,e:.47,f:.32,g:.49,h:.55,i:.28,j:.28,k:.52,l:.28,m:.82,n:.55,o:.52,p:.53,q:.53,r:.38,s:.4,t:.33,u:.55,v:.5,w:.73,x:.5,y:.5,z:.44," ":.25,"\u2009":.17,".":.25,",":.25,":":.25,";":.25,"'":.22,"(":.33,")":.33,"[":.3,"]":.3,"-":.33,"\u2013":.5,"\u2014":1,"+":.6,"\u2212":.6,"=":.6,"/":.4,"\xB0":.4,"\xB7":.25};function fy(e){return py[e]??(/\d/.test(e)?.5:.6)}a(fy,"charWidth");function zr(e,t){let n=0;for(let r of e){let o=r.baseline==="normal"?1:vc;for(let i of r.text)n+=fy(i)*o}return n*t}a(zr,"runsWidth");var my={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};function zn(e,t,n){return{minX:Math.min(e.minX,t),minY:Math.min(e.minY,n),maxX:Math.max(e.maxX,t),maxY:Math.max(e.maxY,n)}}a(zn,"include");function di(e,t,n){return{kind:"text",at:t,runs:e,anchor:"middle",baseline:"middle",fontSize:n,color:rn}}a(di,"centredText");function oa(e){let t=zr(e.runs,e.fontSize),n=e.anchor==="start"?e.at.x:e.anchor==="end"?e.at.x-t:e.at.x-t/2,r=e.runs.some(u=>u.baseline==="sup"),o=e.runs.some(u=>u.baseline==="sub"),i=e.baseline==="top"?e.at.y+.8*e.fontSize:e.baseline==="middle"?e.at.y+.32*e.fontSize:e.at.y,s=i-(.82+(r?.2:0))*e.fontSize,l=i+(.1+(o?.18:0))*e.fontSize;return{minX:n,minY:s,maxX:n+t,maxY:l}}a(oa,"textBounds");function pi(e){let t=my;for(let n of e)switch(n.kind){case"path":for(let r of n.points)t=zn(t,r.x,r.y);break;case"circle":case"arc":t=zn(zn(t,n.center.x-n.radius,n.center.y-n.radius),n.center.x+n.radius,n.center.y+n.radius);break;case"text":{let r=oa(n);t=zn(zn(t,r.minX,r.minY),r.maxX,r.maxY);break}case"marker":t=zn(t,n.at.x,n.at.y);break}return t}a(pi,"boundsOfItems");function fi(e,t,n){let r=a(o=>({x:o.x+t,y:o.y+n}),"move");return e.map(o=>{let i=o.move?{...o,move:{...o.move,origin:r(o.move.origin)}}:o;switch(i.kind){case"path":return{...i,points:i.points.map(r)};case"circle":case"arc":return{...i,center:r(i.center)};case"text":case"marker":return{...i,at:r(i.at)}}})}a(fi,"shiftItems");function Ac(e,t){let n="",r=0;for(;r0&&t.push(r)}return t}a(ia,"mergeRuns");function Ae(e,t,n,r,o){e[t]!==n&&b("syntax",`Expected "${n}" here.`,o+t,e[t]);let i=0;for(let s=t;se*Math.PI/180,"rad"),sa=a(e=>(e%360+360)%360,"normalise"),rc=a((e,t,n)=>({x:e.x+n*Math.cos(Qn(t)),y:e.y-n*Math.sin(Qn(t))}),"step");function oc(e,t){let n=sa(t);return n<90||n>270?Math.max(0,e.atoms.length-1):0}a(oc,"departureAtom");function hy(e,t){let n=sa(t);return n>90&&n<270?Math.max(0,e-1):0}a(hy,"arrivalAtom");function Gr(e,t){return e.centers[t]??e.at}a(Gr,"atomPoint");function ic(e,t,n){if(e.length===0)return{atoms:e,centers:[],at:n};let r=new Array(e.length);r[t]=n;for(let o=t+1;o=0;o--){let i=r[o+1];r[o]={x:i.x-e[o+1].width/2-e[o].width/2,y:n.y}}return{atoms:e,centers:r,at:n}}a(ic,"placeGroup");function sc(e,t){if(!e)return 0;let n=(li+(e.sup?kc:0))*de,r=(li+(e.sub?Ec:0))*de,o=Math.abs(t.x)>1e-9?e.width/2/Math.abs(t.x):1/0,i=t.y<-1e-9?n/-t.y:t.y>1e-9?r/t.y:1/0;return Math.min(o,i)+oy}a(sc,"clearance");var Vn=.15*de,Yn=.09*de,gy=.32*de,Kn=.6*de,yy=vc*Et;function by(e,t,n,r=0){let o={x:Math.cos(Qn(n.angle)),y:-Math.sin(Qn(n.angle))},i={x:-o.y,y:o.x},s=(li+(e.sup?kc:0))*de,l=(li+(e.sub?Ec:0))*de,u=Math.abs(o.x)>1e-9?e.width/2/Math.abs(o.x):1/0,c=o.y<-1e-9?s/-o.y:o.y>1e-9?l/o.y:1/0,d=Math.min(u,c)+Vn+r,p=a((h,g=0)=>({x:t.x+o.x*(d+h)+i.x*g,y:t.y+o.y*(d+h)+i.y*g}),"out"),f={color:rn,opacity:1},m={color:rn,width:Jn};switch(n.kind){case"dot":return{items:[{kind:"circle",center:p(Yn),radius:Yn,fill:f}],reach:r+2*Yn+Vn};case"pair":return{items:[-1,1].map(h=>({kind:"circle",center:p(Yn,h*gy/2),radius:Yn,fill:f})),reach:r+2*Yn+Vn};case"bar":return{items:[Ue(p(0,-Kn/2),p(0,Kn/2),m)],reach:r+Vn};case"box":{let h=.22*de;return{items:[{kind:"path",points:[p(0,-Kn/2),p(0,Kn/2),p(h,Kn/2),p(h,-Kn/2)],closed:!0,stroke:m}],reach:r+h+Vn}}case"text":{let h=di(n.runs,{x:0,y:0},yy),g=oa(h),y=Math.abs(o.x)*((g.maxX-g.minX)/2)+Math.abs(o.y)*((g.maxY-g.minY)/2),E=p(y);return{items:[{...h,at:{x:E.x-(g.minX+g.maxX)/2,y:E.y-(g.minY+g.maxY)/2}}],reach:r+2*y+Vn}}}}a(by,"decorationItems");var wy={"-":{kind:"single",reversed:!1},"=":{kind:"double",reversed:!1},"~":{kind:"triple",reversed:!1},">":{kind:"wedge",reversed:!1},"<":{kind:"wedge",reversed:!0},">:":{kind:"hashed",reversed:!1},"<:":{kind:"hashed",reversed:!0},">|":{kind:"hollow",reversed:!1},"<|":{kind:"hollow",reversed:!0}},Ue=a((e,t,n)=>({kind:"path",points:[e,t],closed:!1,stroke:n}),"line");function ac(e,t,n,r,o,i){let s=e.stroke;if(!s)return[];let l=o.x-n.x,u=o.y-n.y,c=Math.hypot(l,u);if(c<1e-9)return[];let d={x:l/c,y:u/c},p=sc(t,d),f=sc(r,{x:-d.x,y:-d.y});if(p+f>=c)return[];let m={x:n.x+d.x*p,y:n.y+d.y*p},h={x:o.x-d.x*f,y:o.y-d.y*f},g={x:d.y,y:-d.x},y=a((E,v,w=0)=>({x:E.x+g.x*v+d.x*w,y:E.y+g.y*v+d.y*w}),"off");switch(e.kind){case"single":return[Ue(m,h,s)];case"triple":return[Ue(m,h,s),Ue(y(m,pt),y(h,pt),s),Ue(y(m,-pt),y(h,-pt),s)];case"double":{let E=e.side===0&&i!==null?1:e.side;if(E===0)return[Ue(y(m,pt/2),y(h,pt/2),s),Ue(y(m,-pt/2),y(h,-pt/2),s)];let v=E===1?pt:-pt,w=i===null?0:pt*Math.tan(Math.PI/i);return[Ue(m,h,s),Ue(y(m,v,t?0:w),y(h,v,r?0:-w),s)]}case"wedge":case"hashed":case"hollow":{let E=e.reversed?h:m,v=e.reversed?m:h,w=iy/2;if(e.kind==="wedge"){let k=s.width/2;return[{kind:"path",points:[y(E,k),y(v,w),y(v,-w),y(E,-k)],closed:!0,fill:{color:s.color,opacity:1}}]}if(e.kind==="hollow")return[{kind:"path",points:[E,y(v,w),y(v,-w)],closed:!0,stroke:s}];let A=Math.hypot(v.x-E.x,v.y-E.y),N=Math.max(2,Math.floor(A/sy)),S=[];for(let k=1;k<=N;k++){let T=k/N,O={x:E.x+(v.x-E.x)*T,y:E.y+(v.y-E.y)*T};S.push(Ue(y(O,w*T),y(O,-w*T),{...s,width:Math.min(s.width,1)}))}return S}}}a(ac,"bondItems");function lc(e,t){let n=Be(e,t),{color:r,rest:o}=kt(n);Wn(o,dy,"a chemfig bond");let i=wn(o,r??rn);if(!i)return;let s=o.some(l=>l.key==="line width"||Lt.includes(l.key))?i.width:Jn;return{...i,width:s}}a(lc,"bondStroke");function uc(e,t){b("syntax","Put only the atom inside \\charge or \\lewis, and its bonds after the closing brace: \\charge{90=$\\oplus$}{N}(-H)-H, not \\charge{90=$\\oplus$}{N(-H)-H}.",t,e.trim())}a(uc,"onlyAnAtom");function xy(e){let t="";for(let n of e){for(let r of ia(n.runs))t+=r.baseline==="normal"?r.text:`${r.baseline==="sub"?"_":"^"}{${r.text}}`;for(let r of n.decorations??[]){if(r.kind!=="text")continue;let o=r.runs.map(i=>i.text).join("");/[+⊕]/.test(o)?t+="^{+}":/[-−⊖]/.test(o)&&(t+="^{-}")}}return t}a(xy,"atomLabel");var ta=class e{constructor(t,n){this.src=t;this.base=n;this.i=0;this.items=[];this.graph={atoms:[],bonds:[]};this.pending=[];this.hooks=new Map;this.linked=new Set}static{a(this,"MoleculeReader")}here(){return this.base+this.i}skipSpace(){for(;this.i!this.linked.has(i));o!==void 0&&b("syntax",`The hook ?${o==="a"?"":`[${o}]`} is never closed: give the atom it bonds to the same hook.`,this.base,"?")}placeHooks(t){for(let n of this.pending){let r=n.atom<0?void 0:t.atoms[n.atom],o=n.atom<0?t.at:Gr(t,n.atom),i=this.hooks.get(n.name);if(i===void 0){this.hooks.set(n.name,{atom:r,at:o});continue}this.items.push(...ac(n.spec,i.atom,i.at,r,o,null)),this.graph.bonds.push({from:i.at,to:o,kind:n.spec.kind,reversed:n.spec.reversed}),this.linked.add(n.name)}this.pending=[]}hook(t){let n=this.here();this.i++;let r=[];if(this.src[this.i]==="["){let{content:c,end:d}=Ae(this.src,this.i,"[","]",this.base);this.i=d,r=pc(c,",")}let o=(r[0]??"").trim()||"a",i=(r[1]??"").trim()||"-",s=wy[i];s===void 0&&b("unsupported-option",`"${i}" is not a bond a hook can draw: use -, =, ~, >, <, >:, <:, >| or <|.`,n,i);let l=r.slice(2).join(","),u=l.trim()===""?{color:rn,width:Jn}:lc(l,n);this.pending.push({name:o,spec:{...s,side:0,stroke:u},atom:t,at:n})}leadingAngle(t){let n=this.i,{content:r,end:o}=Ae(this.src,this.i,"[","]",this.base);this.i=o;let i=fc(r);return i.slice(1).some(s=>s.trim()!=="")&&b("unsupported-option","Only an angle can be given at the start of a molecule here.",this.base+n,r),mc(i[0]??"",t,this.base+n)}drawAtoms(t,n=0){if(t.atoms.length===0)return;this.graph.atoms.push({at:t.centers[n]??t.centers[0],centers:t.centers,label:xy(t.atoms)});let r=ia(t.atoms.flatMap(u=>u.runs)),o=t.atoms.length-1,i=t.centers[0].y,s=n===o&&o>0,l=s?t.centers[o].x+t.atoms[o].width/2:t.centers[0].x-t.atoms[0].width/2;this.items.push({...di(r,{x:l,y:i},Et),anchor:s?"end":"start"}),t.atoms.forEach((u,c)=>{let d=new Map;for(let p of u.decorations??[]){let f=sa(p.angle),m=by(u,t.centers[c],p,d.get(f)??0);this.items.push(...m.items),d.set(f,m.reach)}})}sequence(t,n,r){for(;;){this.skipSpace();let o=this.src[this.i];if(o===void 0){r!==null&&b("syntax",'A "(" is never closed.',this.here(),"(");return}if(o===r){this.i++;return}if(o===")"&&b("syntax",'This ")" closes nothing.',this.here(),")"),cy.has(o))this.bond(t,n);else if(o==="(")this.i++,this.branch(t,n);else if(o==="*")this.ring(t,n);else if(o==="?")this.hook(t.group.atoms.length-1),this.placeHooks(t.group);else if(o==="!")b("unknown-command","Submolecules (!) are not supported.",this.here(),"!","Write the group out in full.");else if(o==="@")b("unknown-command","Named bonds and atoms (@{\u2026}) are not supported.",this.here(),"@");else{let i=/^[^-=~<>()*[\]?!@\s]+/.exec(this.src.slice(this.i))?.[0]??o,s=/\(\s*$/.test(this.src.slice(0,this.i))?`: a branch starts with its bond, as (-${i}), not (${i})`:"";b("syntax",`"${i}" needs a bond before it, such as -, = or ~${s}.`,this.here(),o)}}}bondSpec(){let t=this.here(),n=this.src[this.i++],r="single",o=0,i=!1;n==="="?(r="double",this.src[this.i]==="^"?(o=1,this.i++):this.src[this.i]==="_"&&(o=2,this.i++)):n==="~"?r="triple":(n===">"||n==="<")&&(i=n==="<",r="wedge",this.src[this.i]===":"?(r="hashed",this.i++):this.src[this.i]==="|"&&(r="hollow",this.i++)),this.src[this.i]==="#"&&b("unsupported-option","Bond offsets (#(\u2026)) are not supported.",this.here(),"#"),this.src[this.i]==="@"&&b("unknown-command","Named bonds (@{\u2026}) are not supported.",this.here(),"@");let s=null;if(this.src[this.i]==="["){let{content:l,end:u}=Ae(this.src,this.i,"[","]",this.base);s=l,this.i=u}return{spec:{kind:r,side:o,reversed:i,stroke:{color:rn,width:Jn}},options:s,at:t}}bond(t,n){let{spec:r,options:o,at:i}=this.bondSpec(),s=fc(o??""),l=s[4]!==void 0&&s[4].trim()!==""?{...r,stroke:lc(s[4],i)}:r,u,c=1;if(n)n.count++,n.count>n.n&&b("syntax",`A ring of ${n.n} has only ${n.n} bonds.`,i),u=t.prev+360/n.n+(n.count===1?n.init:0);else{u=mc(s[0]??"",t.prev,i)??t.defaultAngle;let h=(s[1]??"").trim();h!==""&&(c=Number(h),(!Number.isFinite(c)||c<=0)&&b("unsupported-option",`"${h}" is not a bond length.`,i,h))}let d=hc(s[2],t.group.atoms.length,i)??oc(t.group,u),p=Gr(t.group,d),f,m;if(n&&n.count===n.n)f=n.hook,m=n.hookAtom,this.skipSpace(),this.i12)&&b("unsupported-option",`A ring of ${s} can't be drawn; use 3 to 12.`,r,i),this.i+=i.length,this.skipSpace(),this.src[this.i]!=="("&&b("syntax",`A ring needs its bonds in brackets, as in *${s}(-=-=-=).`,this.here(),this.src[this.i]),this.i++;let l=n?.n??t.fromRing,u=t.atStart?180/s:0,c=l!==null?360/l-180:-180/s-90+u,d=oc(t.group,t.prev),p={n:s,hook:t.group,hookAtom:d,init:c,correction:u,count:0},f=rc(Gr(t.group,d),t.prev+c+180/s+90,Ks/(2*Math.sin(Math.PI/s)));this.sequence({...t,fromRing:null},p,")"),o&&this.items.push({kind:"circle",center:f,radius:ay*Ks/(2*Math.tan(Math.PI/s)),stroke:{color:rn,width:Jn}})}atoms(){let t=[],n=null,r=a(()=>{n&&n.length>0&&t.push(cc(n)),n=null},"push"),o=a((i,s)=>{n??=[];let l=n[n.length-1];l&&l.baseline===s?n[n.length-1]={...l,text:l.text+i}:n.push({text:i,baseline:s,italic:!1})},"append");for(;this.i0)&&uc(t,n),{...s[0],decorations:[...s[0].decorations??[],...r]}}[...t.replace(/[_^](\{[^}]*\}|\\[A-Za-z]+|.)/g,"")].some(i=>tc.has(i))&&uc(t,n);let o=dc(t.trim(),n);return o.length===0&&b("syntax","There is no atom here to put electrons or a charge on.",n),{...cc(o.map(i=>({text:i.text,baseline:i.baseline,italic:!1}))),decorations:r}}scriptToken(){let t=this.src[this.i];if(t===void 0&&b("syntax","A subscript or superscript is missing its text.",this.here()),t==="{"){let n=this.here(),{content:r,end:o}=Ae(this.src,this.i,"{","}",this.base);return this.i=o,na(r,n)}if(t==="\\"){let n=/^\\([A-Za-z]+|.)/.exec(this.src.slice(this.i))?.[1]??"",r=ui[n];return r===void 0&&b("unknown-command",`\\${n} can't be drawn in a chemfig atom.`,this.here(),n),this.i+=1+n.length,r}return this.i++,t==="-"?"\u2212":t}};function cc(e){return{runs:e,width:zr(e,Et),sub:e.some(t=>t.baseline==="sub"),sup:e.some(t=>t.baseline==="sup")}}a(cc,"makeAtom");function dc(e,t){let n=[],r=0;for(;ro.text.length>0)}a(dc,"scriptPieces");function na(e,t){let n="";for(let r=0;rMath.max(1,t))&&b("unsupported-option",`There is no atom ${r} in that group.`,n,r),Math.min(o,t)-1}a(hc,"atomIndex");function Sc(e,t){let n=new ta(e,t);return n.read(),{items:n.items,bounds:pi(n.items)}}a(Sc,"moleculeBox");function ci(e,t,n){let r=Ac(e,t);if(r.length===0)return{items:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}};let o=di(r,{x:0,y:0},n);return{items:[o],bounds:oa(o)}}a(ci,"textBox");var Ey=new Set(["->","<-","<->","<=>"]),Ay=/^\\(chemfig|chemname|arrow|schemestart|schemestop|\+)(?![A-Za-z])/,ra=class{constructor(t){this.src=t;this.i=0;this.items=[]}static{a(this,"SchemeReader")}skipSpace(){for(;this.i{t.trim()!==""&&this.items.push({kind:"compound",box:ci(t,n,Et)}),t=""},"flush");for(;this.i";Ey.has(r)||b("unsupported-option",`"${r}" is not an arrow this build draws.`,t,r,"Use ->, <-, <-> or <=>.");let o=[],i=n<0?e.length:n;for(;i=e.length)break;let u=Ae(e,i,"[","]",t);o.push({content:u.content,at:t+i+1}),i=u.end}o.length>2&&o.slice(2).some(u=>u.content.trim()!=="")&&b("unsupported-option","An arrow takes a label above and one below; label angles are not supported.",o[2].at);let s=o[0]?gc(o[0].content,o[0].at):void 0,l=o[1]?gc(o[1].content,o[1].at):void 0;return{type:r,...s?{above:s}:{},...l?{below:l}:{}}}a(Sy,"parseArrowSpec");var kn=a((e,t,n,r)=>({x:e.x+t.x*n+t.y*r,y:e.y+t.y*n-t.x*r}),"frame");function si(e,t,n){return{kind:"path",points:[e,kn(e,t,-ai,ea),kn(e,t,-ai,-ea)],closed:!0,fill:{color:n.color,opacity:1}}}a(si,"head");function yc(e,t,n){return{kind:"path",points:[e,kn(e,t,-ai,ea*1.4)],closed:!1,stroke:n}}a(yc,"harpoon");function Dy(e,t,n,r){let o={color:rn,width:Jn},i=a((u,c=0)=>kn(t,n,u,c),"at"),s={x:-n.x,y:-n.y},l=ai*.5;switch(e){case"->":return[Ue(i(0),i(r-l),o),si(i(r),n,o)];case"<-":return[Ue(i(l),i(r),o),si(i(0),s,o)];case"<->":return[Ue(i(l),i(r-l),o),si(i(0),s,o),si(i(r),n,o)];case"<=>":return[Ue(i(0,vn),i(r,vn),o),yc(i(r,vn),n,o),Ue(i(0,-vn),i(r,-vn),o),yc(i(0,-vn),s,o)]}}a(Dy,"arrowItems");function Zs(e,t,n){if(e.items.length===0)return[];let r=(e.bounds.minX+e.bounds.maxX)/2,o=(e.bounds.minY+e.bounds.maxY)/2;return fi(e.items,t-r,n-o)}a(Zs,"centreBox");var jr=a(e=>e&&e.items.length>0?e.bounds.maxX-e.bounds.minX:0,"widthOf"),Zn=a(e=>e&&e.items.length>0?e.bounds.maxY-e.bounds.minY:0,"heightOf"),bc=a((e,t,n)=>Math.abs(n.x)*e+Math.abs(n.y)*t,"reach");function Js(e,t){return Math.abs(t.x)>=.5?{x:Math.sign(t.x)*e.halfW,y:0}:{x:0,y:t.y>0?e.halfH+e.nameDepth:-e.halfH}}a(Js,"side");var Qs=a((e,t,n,r)=>({minX:e.x-t,maxX:e.x+t,minY:e.y-n,maxY:e.y+r}),"around"),Ty=a((e,t)=>e.minX{let{item:f,start:m,d:h,length:g}=l;l=null;let y=f.type==="<=>"?vn:0,E=[];f.above&&f.above.items.length>0&&E.push({box:f.above,side:1}),f.below&&f.below.items.length>0&&E.push({box:f.below,side:-1});let v=a(A=>{let N=E.map(({box:O,side:C})=>{let D=y+Xr+bc(jr(O)/2,Zn(O)/2,{x:h.y,y:h.x}),P=kn(m,h,A/2,C*D);return{box:O,at:P,bounds:Qs(P,jr(O)/2,Zn(O)/2,Zn(O)/2)}}),S=kn(m,h,A,0),k={x:S.x+h.x*oi,y:S.y+h.y*oi},T=N.map(O=>O.bounds);if(p){let O=Js(p,{x:-h.x,y:-h.y});k={x:k.x-O.x,y:k.y-O.y},T.push(Qs(k,p.halfW,p.halfH,p.halfH+p.nameDepth))}return{length:A,placedLabels:N,tip:S,centre:k,clear:!T.some(O=>o.some(C=>Ty(O,C)))}},"layout"),w=v(g);for(let A=de/2;!w.clear&&A<=20*de;A+=de/2){let N=v(g+A);N.clear&&(w=N)}w.clear||(w=v(g)),t.push(...Dy(f.type,m,h,w.length));for(let A of w.placedLabels)t.push(...Zs(A.box,A.at.x,A.at.y)),o.push(A.bounds);return s=w.tip,w.centre},"drawArrow");for(let p of e){if(p.kind!=="compound"&&l&&c(),p.kind==="compound"){let f=Math.max(jr(p.box),jr(p.name))/2,m=Zn(p.box)/2,h=p.name&&p.name.items.length>0?ec+Zn(p.name):0,g={halfW:f,halfH:m,nameDepth:h},y=l?.item.arrives,E=l?c(g):{x:s.x+(u==="compound"?ii*2:0)+f,y:s.y},v={cx:E.x,cy:E.y,...g};t.push(...Zs(p.box,v.cx,v.cy)),o.push(Qs(E,f,m,m+h)),r.push(p.name&&p.name.items.length>0?{at:v,name:p.name}:{at:v}),y&&n.set(y,v),i=v,s={x:v.cx+f,y:v.cy}}else if(p.kind==="plus"){let f=u==="arrow"?{x:s.x+oi,y:s.y}:s,m=[{text:"+",baseline:"normal",italic:!1}],h=zr(m,Et);t.push(di(m,{x:f.x+ii+h/2,y:f.y},Et)),s={x:f.x+ii+h+ii,y:f.y}}else{let f=i;p.from&&(f=n.get(p.from.name)??null,f||b("syntax",`No compound before this arrow is named "${p.from.name}".`,p.from.at,`@${p.from.name}`,"Name it on an arrow that leaves it, as \\arrow(a--b).")),p.names&&(f||b("syntax",`There is no compound before this arrow to name "${p.names.name}".`,p.names.at,p.names.name),n.set(p.names.name,f));let m={x:Math.cos(Qn(p.angle)),y:-Math.sin(Qn(p.angle))},h=f?{x:f.cx+Js(f,m).x,y:f.cy+Js(f,m).y}:s,g=a(E=>E&&E.items.length>0?bc(jr(E),Zn(E),m):0,"along"),y=Math.max(ly*p.coeff,g(p.above)+de,g(p.below)+de);l={item:p,start:kn(h,m,oi,0),d:m,length:y},i=null}u=p.kind}l&&c();let d=new Map;for(let p of r)d.set(Math.round(p.at.cy),[...d.get(Math.round(p.at.cy))??[],p]);for(let p of d.values()){let f=Math.max(...p.map(m=>m.at.cy+m.at.halfH))+ec+.5*xc;for(let m of p)m.name&&t.push(...Zs(m.name,m.at.cx,f))}return t}a(Cy,"layoutScheme");function aa(e){return/^\s*\\(chemfig|chemname|schemestart)(?![A-Za-z])/.test(e)}a(aa,"isChemistrySource");function Tc(e){let t=e,n=/^\s*\\schemestart(?![A-Za-z])/.exec(e);if(n){let s=e.lastIndexOf("\\schemestop");s<0&&b("syntax","\\schemestart has no \\schemestop.",n[0].length-12,"schemestart"),e.slice(s+11).trim()!==""&&b("syntax","Nothing can follow \\schemestop.",s+11),t=" ".repeat(n[0].length)+e.slice(n[0].length,s)}let r=new ra(t);r.read(),r.items.length===0&&b("syntax","There is no structure to draw.",0);let o=Cy(r.items),i=pi(o);return Number.isFinite(i.minX)||b("syntax","There is no structure to draw.",0),{width:i.maxX-i.minX+ri*2,height:i.maxY-i.minY+ri*2,items:fi(o,ri-i.minX,ri-i.minY)}}a(Tc,"chemistryToScene");x();x();var me=a((e,t=1)=>({points:e,closed:!1,fill:"none",weight:t}),"line"),ft=a((e,t)=>({points:e,closed:!0,fill:t,weight:1}),"shape"),R=a((e,t)=>({x:e,y:t}),"P");function tr(e,t,n,r=40){let o=[];for(let i=0;i2&&n.push({...me([R(-r+.16*1.5,0),R(r-.16*1.5,0)]),weight:1}),{half:r,reach:.35,shapes:n}}a(gi,"cells");function la(){let e=[];for(let t=0;t<=24;t++)e.push(R(-.2+.4*t/24,.1*Math.sin(2*Math.PI*t/24)));return me(e)}a(la,"sineInside");var Re={short:a(()=>"short","short"),open:a(()=>"open","open"),R:a(e=>e.has("european")?mi:En,"R"),resistor:a(e=>e.has("european")?mi:En,"resistor"),"american resistor":a(()=>En,"american resistor"),"european resistor":a(()=>mi,"european resistor"),generic:a(()=>mi,"generic"),vR:a(()=>({...En,reach:.35,shapes:[...En.shapes,me([R(-.4,-.3),R(.3,.24)]),er(R(.4,.32),.8,.62)]}),"vR"),"variable resistor":a(()=>Re.vR(new Set),"variable resistor"),rheostat:a(()=>Re.vR(new Set),"rheostat"),pR:a(()=>({...En,reach:.5,shapes:[...En.shapes,me([R(0,.55),R(0,.3)]),er(R(0,.17),0,-1)]}),"pR"),potentiometer:a(()=>Re.pR(new Set),"potentiometer"),C:a(()=>({half:.1,reach:.3,shapes:[me([R(-.1,-.3),R(-.1,.3)],1.4),me([R(.1,-.3),R(.1,.3)],1.4)]}),"C"),capacitor:a(()=>Re.C(new Set),"capacitor"),L:a(()=>hi(),"L"),inductor:a(()=>hi(),"inductor"),"american inductor":a(()=>hi(),"american inductor"),"cute inductor":a(()=>hi(),"cute inductor"),battery1:a(()=>gi(1),"battery1"),cell:a(()=>gi(1),"cell"),battery:a(()=>gi(2),"battery"),battery2:a(()=>gi(2),"battery2"),V:a(()=>Ft(.35,[],[{text:"+",at:R(.17,0)},{text:"\u2212",at:R(-.17,0)}]),"V"),"american voltage source":a(()=>Re.V(new Set),"american voltage source"),vsource:a(()=>Ft(.35,[me([R(-.35,0),R(.35,0)])]),"vsource"),sV:a(()=>Ft(.35,[la()]),"sV"),vsourcesin:a(()=>Ft(.35,[la()]),"vsourcesin"),"sinusoidal voltage source":a(()=>Ft(.35,[la()]),"sinusoidal voltage source"),I:a(()=>Ft(.35,[me([R(-.2,0),R(.12,0)]),er(R(.22,0),1,0)]),"I"),isource:a(()=>Re.I(new Set),"isource"),"american current source":a(()=>Re.I(new Set),"american current source"),lamp:a(()=>Ft(.3,[me([R(-.21,-.21),R(.21,.21)]),me([R(-.21,.21),R(.21,-.21)])]),"lamp"),bulb:a(()=>Ft(.3,[me([R(-.21,-.21),R(.21,.21)]),me([R(-.21,.21),R(.21,-.21)])]),"bulb"),ammeter:a(()=>Vr("A"),"ammeter"),voltmeter:a(()=>Vr("V"),"voltmeter"),ohmmeter:a(()=>Vr("\u03A9"),"ohmmeter"),galvanometer:a(()=>Vr("G"),"galvanometer"),wattmeter:a(()=>Vr("W"),"wattmeter"),switch:a(()=>({half:.3,reach:.25,shapes:[ft(tr(-.25,0,.05,12),"paper"),ft(tr(.25,0,.05,12),"paper"),me([R(-.25,0),R(.2,.25)])]}),"switch"),nos:a(()=>Re.switch(new Set),"nos"),spst:a(()=>Re.switch(new Set),"spst"),"opening switch":a(()=>Re.switch(new Set),"opening switch"),ncs:a(()=>({half:.3,reach:.12,shapes:[ft(tr(-.25,0,.05,12),"paper"),ft(tr(.25,0,.05,12),"paper"),me([R(-.25,0),R(.27,.06)])]}),"ncs"),"closing switch":a(()=>Re.ncs(new Set),"closing switch"),cspst:a(()=>Re.ncs(new Set),"cspst"),key:a(()=>Re.switch(new Set),"key"),D:a(()=>({half:.2,reach:.2,shapes:Yr(!1)}),"D"),diode:a(()=>({half:.2,reach:.2,shapes:Yr(!1)}),"diode"),"D*":a(()=>({half:.2,reach:.2,shapes:Yr(!0)}),"D*"),"full diode":a(()=>({half:.2,reach:.2,shapes:Yr(!0)}),"full diode"),led:a(()=>({half:.2,reach:.45,shapes:[...Yr(!1),me([R(-.02,.25),R(.12,.42)]),er(R(.17,.48),.14,.17,.09),me([R(.12,.22),R(.26,.39)]),er(R(.31,.45),.14,.17,.09)]}),"led"),zD:a(()=>({half:.2,reach:.2,shapes:[ft([R(-.2,-.2),R(-.2,.2),R(.2,0)],"paper"),me([R(.12,-.24),R(.2,-.2),R(.2,.2),R(.28,.24)])]}),"zD"),zener:a(()=>Re.zD(new Set),"zener"),fuse:a(()=>({half:.3,reach:.1,shapes:[ft([R(-.3,-.1),R(.3,-.1),R(.3,.1),R(-.3,.1)],"paper"),me([R(-.3,0),R(.3,0)])]}),"fuse")},dS=Object.keys(Re),Py=/^(l|a|v|i|i>|i<|i_|i\^|i>_|i>\^|i<_|i<\^|l_|l\^|a_|a\^|v_|v\^|v<|v>)$/;function Cc(e){let t=e.find(n=>n.key in Re);return t?{name:t.key,label:t.value===void 0||t.value===""?null:B(t.value),rest:e.filter(n=>n!==t)}:null}a(Cc,"componentIn");var Iy=new Set(["color","thick","very thick","thin","line width","invert","mirror","name","n"]);function Nc(e,t,n,r,o,i,s){let l=Re[e](i),u=o.x-r.x,c=o.y-r.y,d=Math.hypot(u,c),p=d===0?R(1,0):R(u/d,c/d),f=R(-p.y,p.x);n.some(P=>P.key==="mirror")&&(f=R(-f.x,-f.y));let m=n.some(P=>P.key==="invert"),h=R((r.x+o.x)/2,(r.y+o.y)/2);for(let P of n)!Py.test(P.key)&&!Iy.has(P.key)&&!s(P.key)&&b("unsupported-option",`"${P.key}" is not an option this build understands on a circuit component.`,P.at,P.key,"Supported: a label (R=$R$, l=\u2026, l_=\u2026, a=\u2026, v=\u2026, i=\u2026), terminals (*-*, o-o, -o), mirror, invert.");if(l==="open")return{open:!0,bodyStart:r,bodyEnd:o,shapes:[],labels:[],letters:[]};let g=l==="short"?{half:0,reach:0,shapes:[]}:l,y=g.half===0?1:Math.min(1,d*.9/(2*g.half)),E=m?-1:1,v=a(P=>{let _=P.x*y*E,M=P.y*y;return R(h.x+p.x*_+f.x*M,h.y+p.y*_+f.y*M)},"place"),w=g.shapes.map(P=>({...P,points:P.points.map(v)})),A=(g.letters??[]).map(P=>({text:P.text,at:v(P.at)})),N=[],S=Math.max(g.reach*y,.05)+.08,k=a(P=>P?R(-f.x,-f.y):f,"side"),T=a(P=>B(P),"text"),O=a((P,_)=>{let M=k(_);N.push({text:T(P),at:R(h.x+M.x*S,h.y+M.y*S),dir:M})},"add");t&&O(t,!1);for(let P of n)P.value!==void 0&&(P.key==="l"||P.key==="l^"?O(P.value,!1):P.key==="l_"||P.key==="a"||P.key==="a_"?O(P.value,!0):P.key==="a^"?O(P.value,!1):/^v/.test(P.key)&&O(P.value,P.key!=="v^"));let C=n.find(P=>/^i/.test(P.key)&&P.value!==void 0);if(C){let P=C.key.includes("<"),_=C.key.includes("_"),M=Math.max(0,d/2-g.half*y),W=g.half*y+(M>.3?M/2:.15),j=R(h.x+p.x*W,h.y+p.y*W);w.push(er(j,P?-p.x:p.x,P?-p.y:p.y,.16));let we=k(_);N.push({text:T(C.value),at:R(j.x+we.x*.12,j.y+we.y*.12),dir:we})}let D=g.half*y;return{open:!1,bodyStart:R(h.x-p.x*D,h.y-p.y*D),bodyEnd:R(h.x+p.x*D,h.y+p.y*D),shapes:w,labels:N,letters:A}}a(Nc,"drawComponent");function Pc(e){let t=e.y-.2;return[me([e,R(e.x,t)]),me([R(e.x-.22,t),R(e.x+.22,t)]),me([R(e.x-.14,t-.07),R(e.x+.14,t-.07)]),me([R(e.x-.06,t-.14),R(e.x+.06,t-.14)])]}a(Pc,"groundShapes");function yi(e,t){return ft(tr(e.x,e.y,.06,16),t?"paper":"ink")}a(yi,"terminalShape");var eo={a:1,b:0,c:0,d:1,e:0,f:0},mt=a((e,t)=>({x:e.a*t.x+e.c*t.y+e.e,y:e.b*t.x+e.d*t.y+e.f}),"apply"),ca=a((e,t)=>({x:e.a*t.x+e.c*t.y,y:e.b*t.x+e.d*t.y}),"applyLinear");function qe(e,t){return{a:e.a*t.a+e.c*t.b,b:e.b*t.a+e.d*t.b,c:e.a*t.c+e.c*t.d,d:e.b*t.c+e.d*t.d,e:e.a*t.e+e.c*t.f+e.e,f:e.b*t.e+e.d*t.f+e.f}}a(qe,"compose");function $y(e){let t=e.a*e.d-e.b*e.c;return Math.abs(t)<1e-12&&b("unsupported-option","A scale of 0 flattens the picture to nothing.",0,"scale"),{a:e.d/t,b:-e.b/t,c:-e.c/t,d:e.a/t,e:(e.c*e.f-e.d*e.e)/t,f:(e.b*e.e-e.a*e.f)/t}}a($y,"invert");var Kr=a((e,t)=>({...eo,e,f:t}),"translate"),Zr=a((e,t)=>({...eo,a:e,d:t}),"scaleBy");function Ic(e){let t=e*Math.PI/180;return{a:Math.cos(t),b:Math.sin(t),c:-Math.sin(t),d:Math.cos(t),e:0,f:0}}a(Ic,"rotateBy");var Ry=new Set(["shift","xshift","yshift","rotate","rotate around","scale","xscale","yscale","x","y"]);function ya(e){let t=eo,n=[];for(let r of e){if(!Ry.has(r.key)||r.value===void 0){n.push(r);continue}let o=B(r.value);switch(r.key){case"shift":{let i=Rc(o,r.at);t=qe(t,Kr(i.x,i.y));break}case"xshift":t=qe(t,Kr(le(o,r.at,"pt"),0));break;case"yshift":t=qe(t,Kr(0,le(o,r.at,"pt")));break;case"rotate":t=qe(t,Ic(be(o,r.at,r.key)));break;case"rotate around":{let i=/^([^:]+):\s*\((.*)\)$/.exec(o);i||b("unsupported-option","rotate around is written rotate around={30:(1,2)}.",r.at,r.key);let s=Rc(i[2],r.at);t=qe(t,qe(Kr(s.x,s.y),qe(Ic(be(i[1],r.at,r.key)),Kr(-s.x,-s.y))));break}case"scale":{let i=be(o,r.at,r.key);t=qe(t,Zr(i,i));break}case"xscale":t=qe(t,Zr(be(o,r.at,r.key),1));break;case"yscale":t=qe(t,Zr(1,be(o,r.at,r.key)));break;case"x":t=qe(t,Zr(le(o,r.at,"cm"),1));break;case"y":t=qe(t,Zr(1,le(o,r.at,"cm")));break}}return{transform:t,rest:n}}a(ya,"readTransform");var rt=1/28.4527559,$c={cm:1,mm:.1,pt:rt,bp:2.54/72,in:2.54,pc:12*rt,em:10*rt,ex:4.3*rt,px:2.54/96},nt=37.8;function Uc(e){return e.replace(/\s+r(?=\s*[)*/+\-,^]|\s*$)/g,"*57.29577951308232").replace(/\\pi\b/g,"pi")}a(Uc,"pgfmath");function be(e,t,n,r={},o=[]){let i=B(e).trim(),s=Number(i);if(i!==""&&Number.isFinite(s))return s;let l;try{l=Ze(Mt(Uc(i),t,o),r)}catch{b("bad-coordinate",`"${e.trim()}" is not a number this build can read for ${n}.`,t,e.trim())}return Number.isFinite(l)||b("bad-coordinate",`"${e.trim()}" has no value for ${n}.`,t,e.trim()),l}a(be,"number");function le(e,t,n){let r=B(e).trim(),o=/^([-+]?(?:\d+\.?\d*|\.\d+))\s*(cm|mm|pt|bp|in|pc|em|ex|px)$/.exec(r);if(o)return Number(o[1])*$c[o[2]];let i=/^(.*?)\s*\*?\s*(cm|mm|pt|bp|in|pc|em|ex|px)$/.exec(r);return i&&i[1]&&!/[A-Za-z]$/.test(i[1])?be(i[1],t,"a length")*$c[i[2]]:be(r,t,"a length")*(n==="pt"?rt:1)}a(le,"length");function Je(e,t=","){let n=[],r=0,o=0;for(let i=0;i{l="none",u=u&&f},"fixed"),d=a((f,m)=>{if(m!=="")return n=-1,c(!1),!0;let h=qc(f);return h&&t.push(h),n=t.length-1,h!==null},"take");for(let f of e){let m=!0;switch(f.kind){case"point":(f.op==="|-"||f.op==="-|")&&c(!0),m=d(f.coord,f.relative);break;case"curve":m=d(f.c1,f.c1Relative)&&(!f.c2||d(f.c2,f.c2Relative))&&d(f.to,f.relative);break;case"to":f.options.length>0&&c(!1),m=d(f.to,f.relative);break;case"rectangle":{let h=n;m=d(f.to,f.relative),m&&h>=0&&f.relative===""?s.push({from:h,to:t.length-1}):c(!1);break}case"grid":l==="free"&&(l="quarter"),m=d(f.to,f.relative);break;case"plot":m="coordinates"in f.data&&f.data.coordinates.every(h=>d(h,"")),n=-1;break;case"circle":o++,f.radius!==null&&f.radiusAt!==void 0&&n>=0&&Oy.test(f.radius)&&r.push({radius:{start:f.radiusAt,end:f.radiusAt+f.radius.length,raw:f.radius},center:n}),(f.radius?.includes("and")||f.options.some(h=>h.key==="x radius"||h.key==="y radius"))&&c(!0);break;case"arc":f.spec!==null&&f.specAt!==void 0&&_y.test(f.spec)?i.push({start:f.specAt,end:f.specAt+f.spec.length,raw:f.spec}):c(!1),n=-1;break;default:break}if(!m)return null}if(t.length===0)return null;let p={coords:t,turns:{rotate:l,flip:u},arcs:i,rectangles:s};return o===1&&r.length===1?{...p,circle:r[0]}:p}a(Ly,"pathCoords");function Wc(e,t,n,r,o){if(!t.src)return[...e];let i=n&&!t.fromLoop&&!o.axis?{...n,transform:r}:null;return e.map(s=>{let{textSrc:l,...u}=s;return{...u,src:t.src,...i?{move:i}:{},...l&&!t.fromLoop?{textSrc:l}:{}}})}a(Wc,"traced");function ba(e,t){return{store:new Map,nodes:new Map,styles:new Map([["help lines",Be("gray!70, very thin")]]),pxPerUnit:e,axis:t,flags:new Set}}a(ba,"newContext");function Sn(e,t,n=0){n>10&&b("unsupported-option","These styles refer to each other in a loop.",e[0]?.at??0,e[0]?.key);let r=[];for(let o of e){let i=o.value===void 0?t.styles.get(o.key):void 0;i?r.push(...Sn(i.map(s=>({...s,at:o.at})),t,n+1)):r.push(o)}return r}a(Sn,"expandStyles");var Fy=new Set(["font","text","color","inner sep"]),By=new Set(["american","european","american resistors","european resistors","american voltages","european voltages","american currents","european currents","american inductors","cute inductors","american ports","siunitx","straight voltages","nooldvoltagedirection","RPvoltages","EFvoltages"]),Uy=new Set(["baseline",">","line cap","line join","every picture/.style","transform shape"]);function bi(e,t,n){let r=[],o=[];for(let f of e){let m=/^(.*?)\/\.(style|append style)$/.exec(f.key);if(m&&f.value!==void 0){let h=m[1].trim(),g=Be(B(f.value),f.at+1);h==="every node"?r.push({key:"__every node",value:f.value,at:f.at}):n.styles.set(h,m[2]==="append style"?[...n.styles.get(h)??[],...g]:g);continue}o.push(f)}let i=Sn(o,n),{transform:s,rest:l}=ya(i),u=[],c=[];for(let f of r)c.push(...Sn(Be(B(f.value),f.at+1),n));let{color:d,rest:p}=kt(l);if(d!==void 0){let f={key:"color",value:d,at:l[0]?.at??0};u.push(f),c.push(f)}for(let f of p)if(!Uy.has(f.key)){if(By.has(f.key)){(f.key==="european"||f.key==="european resistors")&&n.flags.add("european"),(f.key==="american"||f.key==="american resistors")&&n.flags.delete("european");continue}!pa.has(f.key)&&!ha.has(f.key)&&!(f.value===void 0&&xi(f.key))&&b("unsupported-option",`"${f.key}" is not an option this build understands on a picture or scope.`,f.at,f.key,"Supported: scale, shift, rotate, xshift, yshift, styles (name/.style={\u2026}, every node/.style={\u2026}), and the options of \\draw."),Fy.has(f.key)&&c.push(f),f.key!=="font"&&f.key!=="inner sep"&&f.key!=="text"&&u.push(f)}return{transform:qe(t.transform,s),inherited:[...t.inherited,...u],nodeStyle:[...t.nodeStyle,...c]}}a(bi,"enterScope");var Hc={center:[0,0],base:[0,-.3],"base west":[-1,-.3],"base east":[1,-.3],mid:[0,0],text:[0,0],north:[0,1],south:[0,-1],east:[1,0],west:[-1,0],"north east":[1,1],"north west":[-1,1],"south east":[1,-1],"south west":[-1,-1]};function da(e,t,n){if(t===0&&n===0)return e.center;if(e.shape==="rectangle"){let o=Math.min(e.halfW/Math.abs(t||1e-12),e.halfH/Math.abs(n||1e-12));return{x:e.center.x+t*o,y:e.center.y+n*o}}let r=1/Math.sqrt((t/e.halfW)**2+(n/e.halfH)**2);return{x:e.center.x+t*r,y:e.center.y+n*r}}a(da,"borderPoint");function qy(e,t,n,r){let o=Hc[t];if(o){if(e.shape==="rectangle")return{x:e.center.x+o[0]*e.halfW,y:e.center.y+o[1]*e.halfH};let[s,l]=o,u=Math.hypot(s,l)||1;return da(e,s/u,l/u)}let i=Number(t);if(Number.isFinite(i))return da(e,Math.cos(i*Math.PI/180),Math.sin(i*Math.PI/180));b("bad-coordinate",`"${t}" is not an anchor of a node.`,n,r,"Anchors: north, south, east, west, north east, \u2026, center, or an angle like (A.30).")}a(qy,"anchorOf");var Qr=class{constructor(t,n){this.ctx=t;this.transform=n}static{a(this,"Resolver")}resolve(t,n,r){let o=t.raw.trim();if(this.ctx.axis&&(o=o.replace(/^axis cs:\s*/,"")),o===""&&b("bad-coordinate","An empty coordinate.",t.at,o),n){r||b("bad-coordinate",`"${n}(${o})" needs a point before it to start from.`,t.at,o);let i=this.local(o,t.at);return{p:Mc(r,ca(this.transform,i)),ref:null}}return o.startsWith("$")&&o.endsWith("$")?(this.ctx.axis&&b("bad-coordinate","Calculated coordinates ($\u2026$) can't be used inside an axis.",t.at,o),{p:this.calc(o.slice(1,-1),t.at),ref:null}):Je(o).length===2||Je(o,":").length===2?(this.ctx.axis&&Je(o).length!==2&&b("bad-coordinate",`"(${t.raw})" is not a point in the axis \u2014 write it as (axis cs:x,y).`,t.at,t.raw),{p:mt(this.transform,this.local(o,t.at)),ref:null}):(this.ctx.axis&&b("bad-coordinate",`"(${t.raw})" is not a point in the axis \u2014 write it as (axis cs:x,y).`,t.at,t.raw),/^[A-Za-z][A-Za-z0-9_' .-]*$/.test(o)||b("bad-coordinate",`"(${o})" is not a coordinate this build can read.`,t.at,o),this.named(o,t.at))}local(t,n){let r=Je(t);if(r.length===2)return{x:le(r[0],n,"cm"),y:le(r[1],n,"cm")};let o=Je(t,":");if(o.length===2){let i=be(o[0],n,"an angle")*Math.PI/180,s=Je(o[1]," and "),l=le(s[0],n,"cm"),u=s.length===2?le(s[1],n,"cm"):l;return{x:l*Math.cos(i),y:u*Math.sin(i)}}/^[A-Za-z]/.test(t)&&b("bad-coordinate",`"+(${t})" moves by an amount, which a name isn't.`,n,t),b("bad-coordinate",`"(${t})" is not a coordinate this build can read.`,n,t)}named(t,n){let r=this.ctx.nodes.get(t);if(r)return{p:r.center,ref:r};let o=this.ctx.store.get(t);if(o)return{p:o,ref:null};let i=t.indexOf(".");if(i>0){let l=this.ctx.nodes.get(t.slice(0,i));if(l)return{p:qy(l,t.slice(i+1).trim(),n,t),ref:null};let u=this.ctx.store.get(t.slice(0,i));if(u)return{p:u,ref:null}}let s=[...this.ctx.nodes.keys(),...this.ctx.store.keys()];b("undefined-point",`The point "${t}" has not been defined.`,n,t,s.length===0?"No points have been defined yet in this picture. Name one first: \\coordinate (A) at (1,2);":`Points defined so far: ${s.join(", ")}.`)}calc(t,n){let r=0,o=a(()=>{for(;r{o(),t[r]!=="("&&b("bad-coordinate","In $\u2026$, expected a coordinate in brackets.",n,t);let{raw:u,end:c}=vt(t,r,"(",")");r=c;let d=u.trim(),p=Je(d).length===2||Je(d,":").length===2?mt(this.transform,this.local(d,n)):this.named(d,n).p;if(o(),t[r]==="!"){let f=t.indexOf("!",r+1);f<0&&b("bad-coordinate","In $\u2026$, a partway point is written (A)!0.5!(B).",n,t);let m=t.slice(r+1,f).trim();r=f+1;let h=i(),g={x:h.x-p.x,y:h.y-p.y};if(/[a-z]$/.test(m)){let E=le(m,n,"cm"),v=Math.hypot(g.x,g.y)||1;return{x:p.x+g.x/v*E,y:p.y+g.y/v*E}}let y=be(m,n,"a partway amount");return{x:p.x+g.x*y,y:p.y+g.y*y}}return p},"coordinate"),s=a(()=>{o();let u=/^([-+]?(?:\d+\.?\d*|\.\d+))\s*\*/.exec(t.slice(r));if(u){r+=u[0].length;let c=i(),d=Number(u[1]);return{x:c.x*d,y:c.y*d}}return i()},"term"),l=s();for(;;){o();let u=t[r];if(u!=="+"&&u!=="-")break;r++;let c=s();l=u==="+"?Mc(l,c):{x:l.x-c.x,y:l.y-c.y}}return o(),r({x:e.x+t.x,y:e.y+t.y}),"add"),Oc=["latex'","latex","Latex","stealth'","stealth","Stealth","to","To","Triangle","triangle 45","triangle 60","triangle 90","Straight Barb","Classical TikZ Rightarrow","Kite","Computer Modern Rightarrow","Rays"],ua=["Circle","circle","o","*","Square","Diamond"];function _c(e){let t=e.trim();if(t==="")return null;let n=0,r=!1,o=!1,i=!1;for(;t.length>0;){if(t.startsWith("{")){let l;try{let c=vt(t,0,"{","}");l=c.raw,t=t.slice(c.end).trim()}catch{return}let u=l.split("[")[0].trim();if(Oc.includes(u)||u===">")n++;else if(u==="Bar"||u==="|")r=!0;else if(ua.includes(u))[o,i]=[!0,i||u==="o"];else return;continue}if(t.startsWith(">")||t.startsWith("<")){n++,t=t.slice(1);continue}if(t.startsWith("|")){r=!0,t=t.slice(1);continue}let s=[...Oc,...ua].sort((l,u)=>u.length-l.length).find(l=>t.startsWith(l));if(!s)return;ua.includes(s)?[o,i]=[!0,i||s==="o"]:n++,t=t.slice(s.length).trim()}return{arrows:n,bar:r,dot:o,open:i}}a(_c,"tipSpec");function xi(e){let t=0;for(let n=0;n","shorten <","decorate","decoration","postaction","domain","samples","smooth","smooth cycle","tension","variable","step","xstep","ystep","radius","x radius","y radius","start angle","end angle","delta angle",">","font","text","every node/.style","inner sep","__every node",...Lt,...nn]),Lc=["zigzag","coil","snake","brace","border","markings","saw","bumps"];function Wy(e,t){if(e===void 0)return null;let n=Be(B(e),t),r=n.find(s=>s.value===void 0&&Lc.includes(s.key))?.key;if(!r){let s=n.find(l=>l.value===void 0&&l.key!=="mirror");b("unsupported-option",`"${s?.key??e}" is not a decoration this build draws.`,t,s?.key,`Decorations: ${Lc.join(", ")}.`)}let o=a((s,l)=>{let u=L(n,s);return u===void 0?l:le(u,se(n,s),"pt")},"len"),i=[];for(let s of n){if(s.key!=="mark"||s.value===void 0)continue;let l=/^at position\s+([-+]?[\d.]+)\s*(cm|mm|pt)?\s+with\s*\{\s*\\(arrow|arrowreversed)\s*(?:\[[^\]]*\])?\s*\{([^}]*)\}\s*\}$/.exec(B(s.value).trim()),u=/^between positions\s+([-+]?[\d.]+)\s+and\s+([-+]?[\d.]+)\s+step\s+([\d.]+)\s+with\s*\{\s*\\(arrow|arrowreversed)\s*(?:\[[^\]]*\])?\s*\{([^}]*)\}\s*\}$/.exec(B(s.value).trim());if(l){let c=l[4].trim(),d=l[3]==="arrowreversed"!==(c.startsWith("<")||c==="latex reversed");i.push({at:l[2]?le(`${l[1]}${l[2]}`,s.at,"cm"):Number(l[1]),fixed:l[2]!==void 0,reversed:d})}else if(u){let c=u[4]==="arrowreversed"!==u[5].trim().startsWith("<");for(let d=Number(u[1]);d<=Number(u[2])+1e-9&&i.length<50;d+=Number(u[3])||1)i.push({at:d,fixed:!1,reversed:c})}else b("unsupported-option","A marking is written mark=at position 0.5 with {\\arrow{>}}.",s.at,"mark")}return{name:r,amplitude:o("amplitude",r==="brace"?5*rt:2.5*rt),segment:o("segment length",r==="border"?4*rt:10*rt),aspect:Number(L(n,"aspect")??.5),mirror:n.some(s=>s.key==="mirror"),raise:o("raise",0),pre:o("pre length",0),post:o("post length",0),angle:Number(B(L(n,"angle")??"45")),marks:i}}a(Wy,"readDecoration");function An(e,t,n,r,o=24){let i=[];for(let s=1;s<=o;s++){let l=s/o,u=1-l;i.push({x:u*u*u*e.x+3*u*u*l*t.x+3*u*l*l*n.x+l*l*l*r.x,y:u*u*u*e.y+3*u*u*l*t.y+3*u*l*l*n.y+l*l*l*r.y})}return i}a(An,"cubic");function Hy(e,t,n){if(e.length<3)return[...e];let r=e.length,o=a(u=>t?e[(u+r)%r]:e[Math.max(0,Math.min(r-1,u))],"at"),i=[e[0]],s=n/.55/3,l=t?r:r-1;for(let u=0;umt(this.transform,c));this.pieces.push({points:u,closed:!0,startRef:null,endRef:null}),this.piece=null,this.current=i,this.last=[o,i];break}case"grid":{let o=this.need("grid",r.at),i=this.resolver.resolve(r.to,r.relative,o).p;this.grid(this.local(o),this.local(i),[...this.options,...r.options],r.at),this.piece=null,this.current=i;break}case"circle":{let o=this.need((r.radius===null&&r.options.length===0,"circle"),r.at),[i,s]=this.radii(r.radius,[...this.options,...r.options],r.at),l=this.local(o),u=[],c=96;for(let d=0;di.key==="smooth cycle")&&this.piece&&(this.piece.closed=!0);break}case"node":this.node(r);break;case"coordinate":{let o=this.need("coordinate",r.at);this.ctx.store.set(r.name,o);break}case"cycle":if(this.piece||b("syntax","cycle has no path to close.",r.at,"cycle"),this.loopStart&&this.piece.points[0]!==this.loopStart){this.lineTo([this.loopStart],null),this.current=this.loopStart,this.piece=null;break}this.piece.closed=!0,this.piece.endRef=null,this.current=this.piece.points[0],this.last=[this.piece.points[this.piece.points.length-1],this.piece.points[0]],this.piece=null;break}this.pieces.length===0&&this.labels.length===0&&!this.current&&b("syntax","This path has no points.",n)}toCurve(t,n,r,o){let i=new Set(["out","in","bend left","bend right","looseness","relative"]);for(let y of r)i.has(y.key)||b("unsupported-option",`"${y.key}" is not a to-path option this build understands.`,y.at,y.key,"Supported: out, in, bend left, bend right, looseness; or a circuit symbol: R, C, L, battery1, battery, V, sV, I, switch, ncs, lamp, ammeter, voltmeter, galvanometer, D, led, zD, fuse, vR, pR, short.");let s=Math.atan2(n.y-t.y,n.x-t.x)*180/Math.PI,l=null,u=null,c=L(r,"bend left"),d=L(r,"bend right");if(c!==void 0){let y=c===""?30:be(c,o,"bend left");l=s+y,u=s+180-y}else if(d!==void 0){let y=d===""?30:be(d,o,"bend right");l=s-y,u=s+180+y}let p=L(r,"out"),f=L(r,"in");if(p!==void 0&&(l=be(p,o,"out")),f!==void 0&&(u=be(f,o,"in")),l===null&&u===null)return[n];l??=s,u??=s+180;let m=Number(L(r,"looseness")??1),h=Math.hypot(n.x-t.x,n.y-t.y)*.3915*m,g=Math.PI/180;return An(t,{x:t.x+h*Math.cos(l*g),y:t.y+h*Math.sin(l*g)},{x:n.x+h*Math.cos(u*g),y:n.y+h*Math.sin(u*g)},n)}radii(t,n,r){if(t!==null){let l=Je(t," and "),u=le(l[0],r,"cm");return[u,l.length===2?le(l[1],r,"cm"):u]}let o=L(n,"radius"),i=L(n,"x radius")??o,s=L(n,"y radius")??o;return(i===void 0||s===void 0)&&b("syntax","A circle needs a radius: circle (1) or circle[radius=1].",r,"circle"),[le(i,r,"cm"),le(s,r,"cm")]}arcSpec(t,n,r){if(t!==null){let p=Je(t,":");p.length!==3&&b("syntax","An arc is written arc (start:end:radius), e.g. arc (0:90:1).",r,"arc");let f=Je(p[2]," and "),m=le(f[0],r,"cm");return{start:be(p[0],r,"an arc"),end:be(p[1],r,"an arc"),rx:m,ry:f.length===2?le(f[1],r,"cm"):m}}let o=L(n,"start angle"),i=L(n,"end angle"),s=L(n,"delta angle");o===void 0&&i===void 0&&b("syntax","An arc needs its angles: arc (0:90:1) or arc[start angle=0, end angle=90, radius=1].",r,"arc");let l=o!==void 0?be(o,r,"start angle"):be(i,r,"end angle")-be(s??"0",r,"delta angle"),u=i!==void 0?be(i,r,"end angle"):l+be(s??"0",r,"delta angle"),[c,d]=this.radii(null,n,r);return{start:l,end:u,rx:c,ry:d}}grid(t,n,r,o){let i=L(r,"step"),s=le(L(r,"xstep")??i??"1",o,"cm"),l=le(L(r,"ystep")??i??"1",o,"cm");(s<=0||l<=0)&&b("unsupported-option","A grid step must be more than 0.",o,"step");let[u,c]=[Math.min(t.x,n.x),Math.max(t.x,n.x)],[d,p]=[Math.min(t.y,n.y),Math.max(t.y,n.y)];(c-u)/s+(p-d)/l>1e3&&b("unsupported-option","This grid would have more than 1000 lines.",o,"grid");let f=a((m,h)=>this.pieces.push({points:[mt(this.transform,m),mt(this.transform,h)],closed:!1,startRef:null,endRef:null}),"line");for(let m=Math.ceil(u/s-1e-9)*s;m<=c+1e-9;m+=s)f({x:m,y:d},{x:m,y:p});for(let m=Math.ceil(d/l-1e-9)*l;m<=p+1e-9;m+=l)f({x:u,y:m},{x:c,y:m})}plot(t){let n=[...this.options,...t.options],r;if("coordinates"in t.data)r=t.data.coordinates.map(s=>this.resolver.resolve(s,"",null).p);else{let s=(B(L(n,"variable")??"\\x").replace(/^\\/,"")||"x").trim(),l=B(L(n,"domain")??"-5:5").split(":");l.length!==2&&b("unsupported-option","domain is written domain=a:b.",se(n,"domain"),"domain");let u=be(l[0],t.at,"domain"),c=be(l[1],t.at,"domain"),d=Math.round(be(L(n,"samples")??"25",t.at,"samples"));(d<2||d>5e3)&&b("unsupported-option","samples must be from 2 to 5000.",se(n,"samples"),"samples");let p=[s],f=a(g=>Uc(B(g).replace(new RegExp(`\\\\${s}(?![A-Za-z])`,"g"),s)),"own"),m=Mt(f(t.data.x),t.at,p),h=Mt(f(t.data.y),t.at,p);r=[];for(let g=0;gs.key==="smooth"||s.key==="smooth cycle"))return r;let i=Number(L(n,"tension")??.55);return Hy(r,n.some(s=>s.key==="smooth cycle"),i)}component(t,n,r){let o=r.rest.filter(s=>s.value===void 0&&xi(s.key)?.start!==void 0&&/^[*o]?-[*o]?$/.test(s.key)),i=Nc(r.name,r.label,r.rest.filter(s=>!o.includes(s)),t,n,this.ctx.flags,s=>/^[*o]?-[*o]?$/.test(s));i.open?this.start(n,null,!1):((i.bodyStart.x!==t.x||i.bodyStart.y!==t.y)&&this.lineTo([i.bodyStart],null),this.symbols.push(...i.shapes),(i.bodyEnd.x!==i.bodyStart.x||i.bodyEnd.y!==i.bodyStart.y)&&this.start(i.bodyEnd,null,!1),this.lineTo([n],null)),this.last=[t,n];for(let s of o){let[l,u]=s.key.split("-");l&&this.symbols.push(yi(t,l==="o")),u&&this.symbols.push(yi(n,u==="o"))}for(let s of i.labels)this.labels.push(...Jr(s.text,[...this.nodeOptions,{key:Gy(s.dir),at:0}],s.at,null,0,this.ctx,null));for(let s of i.letters)this.labels.push(...Jr(s.text,[...this.nodeOptions,{key:"font",value:"\\small",at:0},{key:"inner sep",value:"0pt",at:0}],s.at,null,0,this.ctx,null))}node(t){let n=[...this.nodeOptions,...Sn(t.options,this.ctx)];if(n.some(u=>u.key==="ground"||u.key==="circ"||u.key==="ocirc")&&(this.symbols.push(...Gc(n,this.need("node",t.at))),!t.text.trim()))return;let r=jy(n),o,i=null;if(r===null||this.last.length<2)o=this.need("node",t.at);else{let u=Xy(this.last,r);o=u.p,i=u.dir}n.some(u=>u.key==="sloped")||(i=null);let[s,...l]=Jr(t.text,n,o,t.name,t.at,this.ctx,i);this.labels.push({...s,textSrc:{start:t.textAt,end:t.textAt+t.text.length}},...l)}};function Gy(e){let t=Math.atan2(e.y,e.x)*180/Math.PI;return["right","above right","above","above left","left","below left","below","below right"][(Math.round(t/45)%8+8)%8]}a(Gy,"placementToward");function Gc(e,t){return e.some(n=>n.key==="ground")?Pc(t):[yi(t,e.some(n=>n.key==="ocirc"))]}a(Gc,"circuitNode");function jy(e){let t=null;for(let n of e)n.key==="midway"?t=.5:n.key==="near start"?t=.25:n.key==="near end"?t=.75:n.key==="at start"||n.key==="very near start"?t=n.key==="at start"?0:.125:n.key==="at end"||n.key==="very near end"?t=n.key==="at end"?1:.875:n.key==="pos"&&n.value!==void 0&&(t=be(n.value,n.at,"pos"));return t}a(jy,"nodePosition");function Xy(e,t){let n=[0];for(let l=1;l=o-1e-12){let u=n[l]-n[l-1],c=u===0?0:(o-n[l-1])/u,d=e[l-1],p=e[l];return{p:{x:d.x+(p.x-d.x)*c,y:d.y+(p.y-d.y)*c},dir:{x:p.x-d.x,y:p.y-d.y}}}let i=e[e.length-2],s=e[e.length-1];return{p:s,dir:{x:s.x-i.x,y:s.y-i.y}}}a(Xy,"pointAlong");function zy(e){let t=a((r,o)=>{let i=(o.x-r.center.x)/(r.halfW||1e-9),s=(o.y-r.center.y)/(r.halfH||1e-9);return r.shape==="rectangle"?Math.abs(i)<=1&&Math.abs(s)<=1:i*i+s*s<=1},"inside"),n=a((r,o)=>{let i=1;for(;i=r.length)return r;let s=r[i-1],l=r[i];for(let u=0;u<30;u++){let c={x:(s.x+l.x)/2,y:(s.y+l.y)/2};t(o,c)?s=c:l=c}return[l,...r.slice(i)]},"trim");e.closed||e.points.length<2||(e.startRef&&(e.points=n(e.points,e.startRef)),e.endRef&&(e.points=n([...e.points].reverse(),e.endRef).reverse()))}a(zy,"clipToNodes");var wi=class{constructor(t){this.points=t;this.lengths=[0];for(let n=1;nt&&this.lengths[o]{let{p:v,t:w}=n.at(g),A={x:-w.y*l,y:w.x*l};return{x:v.x+w.x*y+A.x*(E+t.raise),y:v.y+w.y*y+A.y*(E+t.raise)}},"offset"),c=o>0?n.slice(0,o):[n.at(0).p],d=i[[...c,...g,...d]],"join"),f=Math.max(1,Math.round(s/t.segment)),m=s/f,h=t.amplitude;switch(t.name){case"zigzag":case"saw":{let g=[];for(let y=0;y({x:g.x+E.x*S+v.x*(k+t.raise),y:g.y+E.y*S+v.y*(k+t.raise)}),"at"),A=s/2,N=Math.min(h/2,A/2);return[[w(0,0),...An(w(0,0),w(0,N),w(N,h/2),w(N*1.5,h/2),8),w(A-N*1.5,h/2),...An(w(A-N*1.5,h/2),w(A-N/2,h/2),w(A,h/2),w(A,h),8),...An(w(A,h),w(A,h/2),w(A+N/2,h/2),w(A+N*1.5,h/2),8),w(s-N*1.5,h/2),...An(w(s-N*1.5,h/2),w(s-N,h/2),w(s,N),w(s,0),8)]]}case"border":{let g=[],y=t.angle*Math.PI/180,E=Math.max(1,Math.round(s/t.segment));for(let v=0;v<=E;v++){let w=o+s*v/E;g.push([u(w,0,0),u(w,h*Math.cos(y),h*Math.sin(y))])}return g}default:return[[...e]]}}a(Vy,"decoratePiece");function Yy(e,t,n,r){let{color:o,rest:i}=kt(e),s=null,l=null,u=[];for(let k of i){let T=k.value===void 0?xi(k.key):null;T?(s=T.start,l=T.end):u.push(k)}for(let k of u)pa.has(k.key)||b("unsupported-option",`"${k.key}" is not an option this build understands on \\${t}.`,k.at,k.key,`Supported here: arrow tips (->, <->, -latex, |<->|), ${[...pa].filter(T=>!T.startsWith("__")).sort().join(", ")}.`);let c=t==="draw"||t==="filldraw"||u.some(k=>k.key==="draw"&&B(k.value??"")!=="none"),d=wn(u,o??n,c),p=Hr(u),f=L(u,"pattern"),m=p??((t==="fill"||t==="filldraw")&&f===void 0?{color:o??n,opacity:ju(u)??1}:void 0),h=["north east lines","north west lines","horizontal lines","vertical lines","crosshatch","grid","dots","crosshatch dots"];f!==void 0&&!h.includes(B(f))&&b("unsupported-option",`pattern=${f} is not a pattern this build draws.`,se(u,"pattern"),f,`Patterns: ${h.join(", ")}.`);let g=L(u,"pattern color"),y=L(u,"rounded corners"),E=a(k=>{let T=L(u,k);return T===void 0?0:le(T,se(u,k),"pt")*nt},"shorten"),v=L(u,"decoration"),w=u.some(k=>k.key==="decorate"),A=L(u,"postaction");if(A!==void 0){let k=Be(B(A),se(u,"postaction")+1);for(let T of k)T.key!=="decorate"&&T.key!=="decoration"&&b("unsupported-option",`"${T.key}" can't be used in postaction in this build.`,T.at,T.key,"postaction={decorate} draws a decoration as well as the path.");k.some(T=>T.key==="decorate")&&(w=!1),v=L(k,"decoration")??v,k.some(T=>T.key==="decorate")||(v=void 0)}else w||(v=void 0);let N=Wy(v,se(u,"decoration")||r),S=N?.name==="markings"?N.marks:[];return{paint:{...d?{stroke:d}:{},...m?{fill:m}:{},...f!==void 0?{pattern:{kind:B(f),color:g?tn(B(g),se(u,"pattern color")):"#000000"}}:{},start:s,end:l,shortenStart:E("shorten <"),shortenEnd:E("shorten >"),rounded:y===void 0?0:(y===""?4*rt:le(y,se(u,"rounded corners"),"pt"))*nt,marks:S},decoration:N&&N.name!=="markings"?N:null,replace:N?.name==="markings"?!1:w}}a(Yy,"readPaint");var to="#000000",Ky="#333333",Zy=12;function Jy(e,t,n){let r=Sn(e.options,t),{transform:o,rest:i}=ya(r),s=[...n.inherited,...i],l=qe(n.transform,o),{color:u}=kt(s),c=[...n.nodeStyle];u!==void 0&&c.push({key:"color",value:u,at:e.at});for(let g of s)(g.key==="font"||g.key==="text")&&c.push(g);for(let g of s)(g.key==="__every node"||g.key==="every node/.style")&&c.push(...Be(B(g.value??""),g.at));let d=new fa(t,l,new Qr(t,l),s,c);d.run(e.parts,e.at);let{paint:p,decoration:f,replace:m}=Yy(s,e.command,to,e.at);for(let g of d.pieces)zy(g);let h=[];if(f){let y=d.pieces.flatMap(A=>Vy(A.closed?[...A.points,A.points[0]]:A.points,f)).map(A=>({points:A,closed:!1,startRef:null,endRef:null}));m||h.push({kind:"shape",pieces:d.pieces,paint:p});let{fill:E,pattern:v,...w}=p;h.push({kind:"shape",pieces:y,paint:m?w:{...w,start:null,end:null,marks:[]}})}else h.push({kind:"shape",pieces:d.pieces,paint:p});return h.push(...jc(d.symbols,p.stroke)),h.push(...d.labels),Wc(h,e,Ly(e.parts),l,t)}a(Jy,"drawPath");var ma={above:[0,1],below:[0,-1],left:[-1,0],right:[1,0],"above left":[-1,1],"above right":[1,1],"below left":[-1,-1],"below right":[1,-1]},Qy=[["tiny",6.5],["scriptsize",8],["footnotesize",9.5],["small",10.5],["normalsize",12],["large",14],["Large",16.5],["LARGE",19.5],["huge",23],["Huge",27]],ha=new Set([...Object.keys(ma),"anchor","color","text","draw","fill","opacity","fill opacity","draw opacity","text opacity","line width","circle","rectangle","ellipse","shape","minimum size","minimum width","minimum height","inner sep","inner xsep","inner ysep","outer sep","rounded corners","font","scale","rotate","xshift","yshift","align","text width","label","midway","near start","near end","at start","at end","very near start","very near end","pos","sloped","name","transform shape","text centered","fill opacity","ground","circ","ocirc",...Lt,...nn]);function eb(e){return e.replace(/\\(?:textbf|textit|textrm|textsf|texttt|emph|mbox|text)\s*\{([^{}]*)\}/g,"$1").replace(/\\(?:bfseries|itshape|centering|raggedright|raggedleft|small|footnotesize|scriptsize|tiny|large|Large|normalsize)\b\s*/g,"").replace(/~/g," ").split(/\\\\(?:\[[^\]]*\])?/).map(n=>n.trim())}a(eb,"nodeLines");function Jr(e,t,n,r,o,i,s){let{color:l,rest:u}=kt(t);for(let Q of u)!ha.has(Q.key)&&Q.key!=="__every node"&&Q.key!=="every node/.style"&&b("unsupported-option",`"${Q.key}" is not an option this build understands on a node.`,Q.at,Q.key,`Supported here: ${[...ha].sort().join(", ")}.`);let c=Number(B(L(u,"scale")??"1"))||1,d=L(u,"font")??"",p=Qy.filter(([Q])=>new RegExp(`\\\\${Q}(?![A-Za-z])`).test(d)).pop(),f=(p?p[1]:Zy)*c,m=e.trim()===""?[]:eb(e),h=0;for(let Q of m)h=Math.max(h,zr(Hn(Q,o),f));let g=m.length===0?0:(m.length-1)*f*1.2+f,y=a((Q,Kt)=>{let Bo=L(u,Q);return Bo===void 0?Kt:le(Bo,se(u,Q),"pt")*nt},"sep"),E=y("inner sep",3.33*rt*nt),v=h/2+y("inner xsep",E),w=g/2+y("inner ysep",E),A=L(u,"shape"),N=A!==void 0?["circle","ellipse","rectangle"].includes(B(A))?B(A):b("unsupported-option",`shape=${A} is not a node shape this build draws.`,se(u,"shape"),A,"Shapes: rectangle, circle, ellipse."):u.some(Q=>Q.key==="circle")?"circle":u.some(Q=>Q.key==="ellipse")?"ellipse":"rectangle",S=y("minimum size",0);v=Math.max(v,y("minimum width",S)/2),w=Math.max(w,y("minimum height",S)/2),N==="circle"&&(v=w=Math.max(Math.hypot(v,w),S/2)),N==="ellipse"&&(v*=Math.SQRT2,w*=Math.SQRT2);let k=[0,0],T=0;for(let Q of u){let Kt=ma[Q.key];Kt&&(k=Kt,Q.value!==void 0&&/\bof\b/.test(Q.value)&&b("unsupported-option",`${Q.key}=${Q.value} needs the positioning library, which this build doesn't have.`,Q.at,Q.key,"Give the node a position with at (x,y)."),T=Q.value===void 0||Q.value===""?2:le(Q.value,Q.at,"pt")*nt)}let O=L(u,"anchor");if(O!==void 0){let Q=Hc[B(O)];Q||b("unsupported-option",`anchor=${O} is not an anchor this build knows.`,se(u,"anchor"),O,"Anchors: north, south, east, west, north east, \u2026, center."),k=[-Q[0],-Q[1]],T=0}let C=Math.hypot(k[0],k[1])||1,D=k[0]===0?0:Math.sign(k[0])*(v+T/C),P=k[1]===0?0:Math.sign(k[1])*(w+T/C),_=L(u,"xshift"),M=L(u,"yshift");_!==void 0&&(D+=le(_,se(u,"xshift"),"pt")*nt),M!==void 0&&(P+=le(M,se(u,"yshift"),"pt")*nt);let W={x:n.x+D/i.pxPerUnit.x,y:n.y+P/i.pxPerUnit.y},j=L(u,"text")??L(u,"color"),we=j!==void 0&&j!==""?tn(B(j),se(u,"text")||se(u,"color")):l??Ky,re=L(u,"draw"),ie=re!==void 0&&B(re)!=="none"?wn(u,l??to,!0):void 0,z=Hr(u),Ce=B(L(u,"align")??"center"),Ln=Ce==="left"?"start":Ce==="right"?"end":"middle",Yt=L(u,"rounded corners"),eu=L(u,"name"),tu=r??(eu!==void 0?B(eu):null);tu&&i.nodes.set(tu,{center:W,halfW:v/i.pxPerUnit.x,halfH:w/i.pxPerUnit.y,shape:N});let nu=[{kind:"label",center:W,lines:m,align:Ln,fontSize:f,color:we,rotate:Number(B(L(u,"rotate")??"0"))||0,slope:s,textHalf:h/2,halfW:v,halfH:w,shape:N,rounded:Yt===void 0?0:(Yt===""?4*rt:le(Yt,se(u,"rounded corners"),"pt"))*nt,...ie?{stroke:ie}:{},...z?{fill:z}:{},at:o}],ru=L(u,"label");if(ru!==void 0){let Q=/^(?:\[([^\]]*)\])?\s*(?:(above left|above right|below left|below right|above|below|left|right|-?\d+(?:\.\d+)?)\s*:)?([\s\S]*)$/.exec(B(ru)),Kt=Q?.[2]??"above",Bo=Be(Q?.[1]??"",se(u,"label")),Uo=Number(Kt),xt=Number.isFinite(Uo)?[Math.cos(Uo*Math.PI/180),Math.sin(Uo*Math.PI/180)]:ma[Kt],$h={center:W,halfW:v/i.pxPerUnit.x,halfH:w/i.pxPerUnit.y,shape:N},ou=Math.hypot(xt[0],xt[1])||1,Rh=da($h,xt[0]/ou,xt[1]/ou),Mh=Number.isFinite(Uo)?Math.abs(xt[0])<.38?xt[1]>0?"above":"below":Math.abs(xt[1])<.38?xt[0]>0?"right":"left":`${xt[1]>0?"above":"below"} ${xt[0]>0?"right":"left"}`:Kt;nu.push(...Jr(Q?.[3]??"",[{key:Mh,at:o},...Bo],Rh,null,o,i,null))}return nu}a(Jr,"makeLabel");function vi(e,t,n){let r=[];for(let o of e)switch(o.kind){case"draw":r.push(...Jy(o,t,n));break;case"node":r.push(...tb(o,t,n));break;case"coordinate":{let i=new Qr(t,n.transform).resolve(o.at_,"",null).p;t.store.set(o.name,i);break}case"scope":r.push(...vi(o.body,t,bi(o.options,n,t)));break;case"tikzset":bi(o.options,n,t);for(let i of o.options)/\/\.(style|append style)$/.test(i.key)||b("unsupported-option",`\\tikzset only defines styles here ("${i.key}" isn't one).`,i.at,i.key,"Write name/.style={\u2026}, then use [name].");break;case"addplot":b("unknown-command","\\addplot only works inside \\begin{axis}.",o.at,"addplot","Wrap the plot in \\begin{axis}[xmin=\u2026,xmax=\u2026,ymin=\u2026,ymax=\u2026] \u2026 \\end{axis}.");break;case"tkz":b("unknown-command",`\\${o.name} is a tkz-euclide command, which this build does not draw.`,o.at,o.name,"Draw the construction with \\draw and \\node instead.");break;case"axis":b("unsupported-option","An axis cannot be combined with other drawing commands \u2014 they use different coordinate systems.",o.at)}return r}a(vi,"evaluateStatements");function jc(e,t){let n=t??{color:to,width:Xs([])};return e.map(r=>({kind:"shape",pieces:[{points:r.points,closed:r.closed,startRef:null,endRef:null}],paint:{stroke:{color:n.color,width:n.width*r.weight},...r.fill==="none"?{}:{fill:{color:r.fill==="ink"?n.color:"#ffffff",opacity:1}},start:null,end:null,shortenStart:0,shortenEnd:0,rounded:0,marks:[]}}))}a(jc,"symbolShapes");function tb(e,t,n){let r=Sn(e.options,t),{transform:o,rest:i}=ya(r.filter(y=>y.key!=="rotate")),s=r.filter(y=>y.key==="rotate"),l=qe(n.transform,o),u=new Qr(t,l).resolve(e.at_,"",null).p,c=n.inherited.filter(y=>y.key==="__every node").flatMap(y=>Be(B(y.value??""),y.at)),d=[...n.nodeStyle,...c,...i,...s],p=e.placed?qc(e.at_):null,f={start:e.textAt,end:e.textAt+e.text.length},m=a(y=>{let[E,...v]=Jr(e.text,y,u,e.name,e.at,t,null);return[{...E,textSrc:f},...v]},"labelled"),g=d.some(y=>y.key==="ground"||y.key==="circ"||y.key==="ocirc")?[...jc(Gc(d,u),void 0),...e.text.trim()?m(d.filter(y=>!["ground","circ","ocirc"].includes(y.key))):[]]:m(d);return Wc(g,e,p?{coords:[p],turns:{rotate:"free",flip:!0},arcs:[],rectangles:[]}:null,l,t)}a(tb,"drawNode");function Xc(e,t){let n=[];for(let r of e)if(r.kind==="shape")for(let o of r.pieces)n.push(...o.points);else{let o=r.halfW/t.pxPerUnit.x,i=r.halfH/t.pxPerUnit.y;n.push(r.center),(r.stroke||r.fill)&&n.push({x:r.center.x-o,y:r.center.y-i},{x:r.center.x+o,y:r.center.y+i})}return n}a(Xc,"drawnPoints");var nb=7;function zc(e){return Math.max(nb,(e?.width??1)*4.5)}a(zc,"arrowSize");function Vc(e,t,n,r,o){let i=r*.36;return{kind:"path",points:[e,{x:e.x-t*r-n*i,y:e.y-n*r+t*i},{x:e.x-t*r+n*i,y:e.y-n*r-t*i}],closed:!0,fill:{color:o,opacity:1}}}a(Vc,"triangle");function Yc(e,t,n,r=48){let o=[];for(let i=0;i=0&&(s=e[f],!(Math.hypot(i.x-s.x,i.y-s.y)>=o*.6));f--);let l=Math.hypot(i.x-s.x,i.y-s.y);if(l<1e-9)return{items:[],trim:0};let u=(i.x-s.x)/l,c=(i.y-s.y)/l,d=[],p=0;for(let f=0;f=n){let l=n/(s||1);return[{x:o.x+(i.x-o.x)*l,y:o.y+(i.y-o.y)*l},...e.slice(r)]}n-=s}return[e[e.length-1]]}a(ga,"trimStart");var Bc=a((e,t)=>ga([...e].reverse(),t).reverse(),"trimEnd");function Kc(e,t,n){if(n<=0||e.length<3)return[...e];let r=e.length,o=[];for(let i=0;im-h);for(let m=0;m+1({x:u.x*p+l.x*g,y:u.y*p+l.y*g}),"at");i.push({kind:"path",points:[h(f[m]),h(f[m+1])],closed:!1,stroke:o})}}}return i}a(rb,"patternItems");function ob(e,t){let n=!1;for(let r=0,o=e.length-1;rt.y!=s.y>t.y&&t.x<(s.x-i.x)*(t.y-i.y)/(s.y-i.y)+i.x&&(n=!n)}return n}a(ob,"insidePolygon");function ib(e,t,n){let r=e.flat();if(r.length<2)return[];let o=new wi(r),i=zc(n);return t.map(s=>{let l=s.fixed?s.at<0?o.total+s.at*nt:s.at*nt:s.at*o.total,{p:u,t:c}=o.at(l),[d,p]=s.reversed?[-c.x,-c.y]:[c.x,c.y];return Vc({x:u.x+d*i*.5,y:u.y+p*i*.5},d,p,i,n?.color??to)})}a(ib,"markItems");function wa(e,t){let n=[];for(let r of e){let o=n.length;if(ab(r,t,n),!r.src)continue;let i=r.move&&sb(r.move,t);for(let s=o;su.points.length>1).map(u=>({points:u.points.map(t),closed:u.closed}));if(o.length===0)return;let i=o[0],s=o[o.length-1],l=[];if(r.shortenStart>0&&!i.closed&&(i.points=ga(i.points,r.shortenStart)),r.shortenEnd>0&&!s.closed&&(s.points=Bc(s.points,r.shortenEnd)),r.end&&!s.closed&&s.points.length>=2){let{items:u,trim:c}=Fc(s.points,r.end,r.stroke);l.push(...u),s.points=Bc(s.points,c)}if(r.start&&!i.closed&&i.points.length>=2){let{items:u,trim:c}=Fc([...i.points].reverse(),r.start,r.stroke);l.push(...u),i.points=ga(i.points,c)}for(let u of o){let c=Kc(u.points,u.closed,r.rounded);r.pattern?(r.fill&&n.push({kind:"path",points:c,closed:!0,fill:r.fill}),n.push(...rb(c,r.pattern.kind,r.pattern.color)),r.stroke&&n.push({kind:"path",points:c,closed:u.closed,stroke:r.stroke})):(r.stroke||r.fill)&&n.push({kind:"path",points:c,closed:u.closed,...r.stroke?{stroke:r.stroke}:{},...r.fill?{fill:r.fill}:{}})}(r.stroke||r.fill)&&n.push(...l),r.marks.length>0&&n.push(...ib(o.map(u=>u.points),r.marks,r.stroke))}}a(ab,"renderOne");function lb(e,t){let n=t(e.center),r=[];if(e.stroke||e.fill){let l=e.shape==="rectangle"?Kc([{x:n.x-e.halfW,y:n.y-e.halfH},{x:n.x+e.halfW,y:n.y-e.halfH},{x:n.x+e.halfW,y:n.y+e.halfH},{x:n.x-e.halfW,y:n.y+e.halfH}],!0,e.rounded):Yc(n,e.halfW,e.halfH);r.push({kind:"path",points:l,closed:!0,...e.stroke?{stroke:e.stroke}:{},...e.fill?{fill:e.fill}:{}})}let o=-e.rotate;if(e.slope){let l=t(e.center),u=t({x:e.center.x+e.slope.x,y:e.center.y+e.slope.y});o=Math.atan2(u.y-l.y,u.x-l.x)*180/Math.PI,o>90&&(o-=180),o<-90&&(o+=180)}let i=e.fontSize*1.2,s=e.align==="start"?n.x-e.textHalf:e.align==="end"?n.x+e.textHalf:n.x;return e.lines.forEach((l,u)=>{if(l==="")return;let c={kind:"text",at:{x:s,y:n.y+(u-(e.lines.length-1)/2)*i},runs:Hn(l,e.at),anchor:e.align,baseline:"middle",fontSize:e.fontSize,color:e.color};r.push(Math.abs(o)>.01?{...c,rotate:o}:c)}),r}a(lb,"renderLabel");x();var TS=.025*37.8;var nr=nt,ot=14,Jc={transform:eo,inherited:[],nodeStyle:[]};function ub(e){e.dimensions===3&&b("unknown-command","\\addplot3 draws in three dimensions, which this build does not render.",e.at,"addplot3","Plot the section you need as a 2-D figure.");let t=Wu(e.options,e.at),n=Gs(e.options,"x",e.at),r=Gs(e.options,"y",e.at),o=Hs(t.lines,L(e.options,"title")!==void 0),i=qu(n,r,o),s=i.toDevice(0,0),l=ba({x:Math.abs(i.toDevice(1,0).x-s.x),y:Math.abs(i.toDevice(0,1).y-s.y)},!0),u=a(p=>i.toDevice(p.x,p.y),"place"),c=[];for(let p of e.body)p.kind==="addplot"?c.push(...Zc(Yu(p,i),p.src)):c.push(...wa(vi([p],l,Jc),u));let d={left:o.margin.left,top:o.margin.top,right:o.margin.left+o.plotWidth,bottom:o.margin.top+o.plotHeight};return{width:Ws,height:ei,items:[...Zc(Hu(i,e.options,t,e.at),e.src),...Zu(c,d)]}}a(ub,"axisScene");function Zc(e,t){return t?e.map(n=>({...n,src:t})):[...e]}a(Zc,"traceTo");function cb(e,t){let n=ba({x:nr,y:nr},!1),r=bi(t,Jc,n),o=vi(e,n,r),i=Fu(Xc(o,n)),s=(i.maxX-i.minX)*nr+ot*2,l=(i.maxY-i.minY)*nr+ot*2,u=a(c=>({x:ot+(c.x-i.minX)*nr,y:ot+(i.maxY-c.y)*nr}),"place");return db({width:s,height:l,items:wa(o,u),frame:xa(r.transform,u)})}a(cb,"pictureScene");function db(e){let t=pi(e.items);if(!Number.isFinite(t.minX))return e;let n=Math.min(ot,t.minX),r=Math.min(ot,t.minY),o=Math.max(e.width-ot,t.maxX),i=Math.max(e.height-ot,t.maxY),s=ot-n,l=ot-r;return{width:o-n+ot*2,height:i-r+ot*2,items:s===0&&l===0?e.items:fi(e.items,s,l),...e.frame?{frame:{...e.frame,origin:{x:e.frame.origin.x+s,y:e.frame.origin.y+l}}}:{}}}a(db,"fitToLabels");function pb(e){let t=Lu(e),n=t.statements.filter(r=>r.kind==="axis");if(n.length===0)return cb(t.statements,t.options);if(n.length>1&&b("unsupported-option","A picture with more than one axis is not supported.",n[1].at,"axis"),t.statements.length>1){let r=t.statements.find(o=>o.kind!=="axis");b("unsupported-option","An axis cannot be combined with other drawing commands \u2014 they use different coordinate systems.",r.at)}return ub(n[0])}a(pb,"tikzToScene");function fb(e){return aa(e)?Tc(e):pb(e)}a(fb,"figureToScene");function Qc(e,t){return Qu(fb(e),t===void 0?{}:{title:t})}a(Qc,"figureToSvg");function ed(e){let t=[],n=aa(e)||/\\(chemfig|schemestart)(?![A-Za-z])/.test(e),r=/\\begin\s*\{circuitikz\}|\bto\s*\[\s*(?:R|C|L|D\*?|V|I|sV|battery1?|battery2|cell|lamp|bulb|ammeter|voltmeter|galvanometer|ohmmeter|switch|nos|ncs|spst|cspst|led|zD|fuse|vR|pR|short|open|resistor|capacitor|inductor|diode|vsource|isource|key|rheostat|potentiometer)\b|node\s*\[\s*(?:ground|circ|ocirc)\b/.test(e);return/\\begin\s*\{axis\}|\\addplot/.test(e)?t.push("\\usepackage{pgfplots}","\\pgfplotsset{compat=1.18}"):r?t.push("\\usepackage{circuitikz}"):n||t.push("\\usepackage{tikz}"),/pattern\s*=/.test(e)&&t.push("\\usetikzlibrary{patterns}"),/decorat/.test(e)&&t.push("\\usetikzlibrary{decorations.pathmorphing,decorations.pathreplacing,decorations.markings}"),/\$\s*\(/.test(e)&&t.push("\\usetikzlibrary{calc}"),n&&t.push("\\usepackage{chemfig}"),/\\ce\s*\{/.test(e)&&t.push("\\usepackage{mhchem}"),t}a(ed,"figurePackages");x();function td(e){if(e.kind!=="paragraph")return!1;let t=e.children.filter(n=>n.kind!=="eqnumber"&&(n.kind!=="text"||n.text.trim()!==""));return t.length===1&&t[0].kind==="math"}a(td,"isDisplayMathParagraph");function*no(e){for(let t of e)if(yield t,t.kind==="list")for(let n of t.items)yield*no(n.blocks??[]);else if(t.kind==="table")for(let n of t.rows)for(let r of n.cells)yield*no(r.blocks)}a(no,"walkBlocks");function*ki(e){let t=a(function*(n){for(let r of n)yield r,r.kind==="link"&&(yield*t(r.children))},"fromInlines");for(let n of no(e))switch(n.kind){case"paragraph":case"heading":yield*t(n.children);break;case"list":for(let r of n.items)yield*t(r.children);break;case"table":break}}a(ki,"walkInlines");function sd(e){let t="",n=0;for(;n1&&t[t.length-1].trim()===""&&t.pop(),t}a(Aa,"topLevelLines");function bb(e){let t=Aa(e);return t.length<2?null:t.map(n=>{if(/\\(nonumber|notag)\b/.test(n))return null;let r=Array.from(n.matchAll(/\\label\s*\{([^}]*)\}/g),i=>i[1].trim()),o=/\\tag\*?\s*\{([^}]*)\}/.exec(n);return o===null?{labels:r}:{tag:o[1].trim(),labels:r}})}a(bb,"rowNumbers");function wb(e){return e.replace(/\\label\s*\{[^}]*\}/g,"").replace(/\\tag\*?\s*\{[^}]*\}/g,"").replace(/\\(nonumber|notag)\b/g,"")}a(wb,"withoutLineNumbering");function xb(e){let t=e.kind==="eqarr"?e:e.kind==="row"&&e.children.length===1&&e.children[0].kind==="eqarr"?e.children[0]:null;return t!==null&&t.kind==="eqarr"?t.rows.length:0}a(xb,"eqarrRows");var vb={part:1,chapter:1,section:1,subsection:2,subsubsection:3,paragraph:4,subparagraph:5},va=a(e=>vb[e.endsWith("*")?e.slice(0,-1):e],"sectionLevel"),ld={textbf:"bold",bf:"bold",textit:"italic",emph:"italic",textsl:"italic",it:"italic",underline:"underline",uline:"underline"},kb=new Set(["maketitle","tableofcontents","listoffigures","listoftables","newpage","clearpage","cleardoublepage","pagebreak","noindent","indent","centering","raggedright","raggedleft","small","footnotesize","large","Large","LARGE","huge","Huge","normalsize","hfill","vfill","hspace","vspace","bigskip","medskip","smallskip","printbibliography","bibliographystyle","hline","toprule","midrule","bottomrule","protect","linebreak","nolinebreak","sloppy","frenchspacing"]),Eb=new Set(["document","center","flushleft","flushright","figure","figure*","table","table*","minipage","small","footnotesize","abstract","quote","quotation","sloppypar"]);function Qe(e,t,n){if(e[t]!=="\\")return null;let r=/^\\([A-Za-z]+\*?|.)/.exec(e.slice(t));if(r===null)return null;let o=r[1],i=t+r[0].length,s=[],l=[];for(;;){let u=i,c=0;for(;u1)break;if(e[u]==="["&&s.length+l.length1&&e[e.length-2].kind==="break")e.pop();else return}}a(id,"trimBreaks");var Ea=class{constructor(t){this.options=t;this.warnings=[];this.citations=[];this.bibliographyFiles=[];this.footnotes=new Map;this.images=new Map;this.footnoteCounter=0;this.figureCounter=1;this.unknown=new Set}static{a(this,"TexParser")}note(t){this.warnings.length<200&&this.warnings.push(t)}inlines(t,n={}){let r=[],o="",i=a(()=>{if(o==="")return;let l=o.replace(/[ \t\r\n]+/g," ");l!==""&&r.push({kind:"text",text:l,...n}),o=""},"flush"),s=0;for(;s0){i(),r.push(...this.inlines(t.slice(s+1,u-1),n)),s=u;continue}}if(l==="\\"){let u=t[s+1];if(u!==void 0&&ad.has(u)){o+=u,s+=2;continue}if(u==="\\"){i(),r.push({kind:"break",variant:"line"}),s+=2;let d=t[s]==="["?Dn(t,s,"[","]"):-1;d>0&&(s=d);continue}let c=Qe(t,s,Sb(Qe(t,s,0)?.name??""));if(c!==null&&(c.name==="chemfig"||c.name==="chemname")){let d=t.slice(s,c.end),p=this.drawnFigure(d,`A \\${c.name}`);i(),r.push(p??{kind:"text",text:d}),s=c.end;continue}if(c!==null){let d=this.inlineCommand(c,n);if(d!==null){i(),r.push(...d),s=c.end;continue}let p=mb[c.name];if(p!==void 0){o+=p,s=c.end;continue}if(kb.has(c.name)){s=c.end;continue}this.unknown.has(c.name)||(this.unknown.add(c.name),this.note(`\\${c.name} is not a command TeXConverter converts; its text was kept and the command dropped.`)),i();for(let f of c.args)r.push(...this.inlines(f,n));s=c.end;continue}}if(l===` `&&this.keepLines){i();let u=r[r.length-1];u!==void 0&&u.kind!=="break"&&!(u.kind==="math"&&u.display)&&r.push({kind:"break",variant:"line"}),s+=1;continue}if(l==="~"){o+="\xA0",s+=1;continue}if(l==="-"&&t.startsWith("---",s)){o+="\u2014",s+=3;continue}if(l==="-"&&t.startsWith("--",s)){o+="\u2013",s+=2;continue}if(t.startsWith("``",s)){o+="\u201C",s+=2;continue}if(t.startsWith("''",s)){o+="\u201D",s+=2;continue}o+=l,s+=1}return i(),id(r),r}get keepLines(){return this.options.keepLineBreaks===!0}readInlineMath(t,n){let r=rd(t,n);if(r===null)return null;let o=od(t,n+r.open.length,r.close);if(o<0)return this.note(`An unclosed ${r.open} was left as text.`),null;let i=t.slice(n+r.open.length,o),s=this.math(i,r.display);return s===null?null:{node:s,end:o+r.close.length}}math(t,n){let r=t.trim();if(r==="")return null;try{return{kind:"math",ir:H(Qt(r)),display:n,source:r}}catch(o){return this.note(`An equation was left as text because it did not parse: ${o instanceof Error?o.message:String(o)}`),null}}inlineCommand(t,n){let{name:r,args:o,optionals:i}=t;if((r==="underline"||r==="uline")&&/^\s*\\hspace\*?\s*\{[^}]*\}\s*$/.test(o[0]??""))return[{kind:"blank",widthCm:ka(/\{([^}]*)\}/.exec(o[0])[1])??2.5}];let s=ld[r];if(s!==void 0)return this.inlines(o[0]??"",{...n,[s]:!0});switch(r){case"texttt":case"textrm":case"textsc":return this.inlines(o[0]??"",n);case"textsuperscript":case"textsubscript":{let l=r==="textsuperscript"?"super":"sub";return this.inlines(o[0]??"",n).map(u=>u.kind==="text"?{...u,script:l}:u)}case"href":return[{kind:"link",href:Ai(o[0]??""),children:this.inlines(o[1]??"",n)}];case"url":{let l=Ai(o[0]??"");return[{kind:"link",href:l,children:[{kind:"text",text:l}]}]}case"includegraphics":{let l=(o[0]??"").trim();if(l==="")return[];let u={kind:"image",part:l},c=this.widthFromOptions(i[0]??"");return c!==null&&(u.widthEmu=c),[u]}case"footnote":{let l=String(++this.footnoteCounter);return this.footnotes.set(l,[{kind:"paragraph",children:this.inlines(o[0]??"")}]),[{kind:"footnoteref",id:l}]}case"cite":case"citep":case"citet":{let l=(o[0]??"").split(",").map(u=>u.trim()).filter(u=>u!=="");for(let u of l)this.citations.includes(u)||this.citations.push(u);return[{kind:"citation",keys:l}]}case"label":return[{kind:"label",id:(o[0]??"").trim()}];case"textcircled":{let l=Ab(o[0]??"");return l===null?this.inlines(o[0]??"",n):[{kind:"text",text:l,...n}]}case"rule":{let l=(o[0]??"").trim();return/^(?:[0-9.]*\s*)?\\(?:textwidth|linewidth|columnwidth|hsize)$/.test(l)?[{kind:"rule"}]:[{kind:"blank",widthCm:ka(l)??2.5}]}case"hrule":return[{kind:"rule"}];case"hfill":return[{kind:"fill"}];case"newpage":case"clearpage":case"cleardoublepage":case"pagebreak":return[{kind:"break",variant:"page"}];case"ref":case"eqref":case"pageref":return[{kind:"ref",id:(o[0]??"").trim(),wrap:r==="eqref"?"parentheses":"none"}];case"input":case"include":case"bibliography":case"documentclass":case"usepackage":case"title":case"author":case"date":return[];default:return null}}widthFromOptions(t){let o=/width\s*=\s*([0-9.]+)\s*\\(?:textwidth|linewidth|columnwidth)/.exec(t);if(o!==null)return Math.round(Number(o[1])*6.5*914400);let i=/width\s*=\s*([0-9.]+)\s*(in|cm|mm|pt)\b/.exec(t);if(i!==null){let s=Number(i[1]),l={in:914400,cm:914400/2.54,mm:914400/25.4,pt:914400/72};return Math.round(s*l[i[2]])}return null}blocks(t,n=0){let r=[],o="",i=!1,s=a(()=>{let u=i;if(i=!1,o.trim()===""){o="";return}let c=this.inlines(o);c.length>0&&r.push(u?{kind:"paragraph",children:c,continues:!0}:{kind:"paragraph",children:c}),o=""},"flush"),l=0;for(;l=0&&!/\n[ \t]*\n/.test(t.slice(l,d))&&t.slice(l,d).includes("\\begin{");if(d>=0&&p){let f=d+c.close.length;o+=t.slice(l,f),l=f;continue}}if(t[l]==="\\"){let p=Qe(t,l,0)?.name??"";if(p==="begin"){let m=Qe(t,l,1)?.args[0]?.trim()??"",h=this.environmentRegion(t,l,m);if(h!==null){let g=i||o.trim()!=="";s();let y=this.environment(m,h.body,t.slice(l,h.end),n),E=y.length===1?y[0]:null,v=E!==null&&E.kind==="paragraph"&&td({...E,children:E.children.filter(w=>w.kind!=="label")})?E:null;v!==null&&v.kind==="paragraph"?(r.push(g?{...v,continues:!0}:v),i=!0):(r.push(...y),i=!1),l=h.end;continue}this.note(`\\begin{${m}} has no matching \\end, so the rest of the file was read as text.`)}if(va(p)!==void 0){let f=Qe(t,l,1);if(f!==null){s();let m=va(p);r.push(p.endsWith("*")?{kind:"heading",level:m,children:this.inlines(f.args[0]??""),numbered:!1}:{kind:"heading",level:m,children:this.inlines(f.args[0]??"")}),l=f.end;continue}}if(p==="caption"){let f=Qe(t,l,2);if(f!==null&&f.args.length>0){s(),r.push({kind:"paragraph",align:"center",children:this.inlines(f.args[f.args.length-1])}),l=f.end;continue}}if(p==="schemestart"){let f=this.scheme(t,l);if(f!==null){s(),r.push(...f.blocks),l=f.end;continue}this.note("\\schemestart has no matching \\schemestop, so it was read as text.")}if(p==="input"||p==="include"){let f=Qe(t,l,1);if(f!==null){s(),r.push(...this.includeFile(f.args[0]??"",n)),l=f.end;continue}}if(p==="bibliography"){let f=Qe(t,l,1);if(f!==null){for(let m of(f.args[0]??"").split(",")){let h=m.trim();h!==""&&this.bibliographyFiles.push(h)}l=f.end;continue}}}o+=t[l],l+=1}return s(),r}environmentRegion(t,n,r){let o=Qe(t,n,1);if(o===null)return null;let i=`\\begin{${r}}`,s=`\\end{${r}}`,l=1,u=o.end;for(;u(i.push({kind:"label",id:d.trim()}),"")),l=yb.has(t)?bb(n):null;if(l!==null){let c=this.math(wb(r),!0);if(c!==null&&c.kind==="math"&&xb(c.ir)===l.length)return[{kind:"paragraph",children:[c,{kind:"eqnumber",rows:l}]}]}let u=this.math(s,!0);return u===null?[{kind:"paragraph",children:this.inlines(n)}]:[{kind:"paragraph",children:[...i,u,...gb(t,n)]}]}if(t==="itemize"||t==="enumerate"||t==="description"){let i=this.list(n,t==="enumerate"),s=t==="enumerate"?/^\s*\[[^\]]*?\bstart\s*=\s*(\d+)/.exec(n):null,l=t==="enumerate"?Db(n):null,u=s!==null&&i.kind==="list"&&Number(s[1])!==1?{...i,start:Number(s[1])}:i;return l&&u.kind==="list"&&(u={...u,label:l}),[u]}if(t==="tabular"||t==="array"||t==="tabularx"||t==="longtable")return[this.table(n,t)];if(t==="verbatim"||t==="lstlisting"||t==="verbatim*")return n.split(/\n/).filter(i=>i.trim()!=="").map(i=>({kind:"paragraph",children:[{kind:"text",text:i}]}));if(zo.has(t))return this.figure(t,r);if(Eb.has(t)){let i=/^(figure|table)\*?$/.test(t)?n.replace(/^\s*\[[!htbpH]*\]/,""):n,s=this.blocks(i,o);return t==="center"?s.map(l=>l.kind==="paragraph"?{...l,align:"center"}:l.kind==="table"?{...l,align:"center"}:l):t==="flushright"?s.map(l=>l.kind==="paragraph"?{...l,align:"right"}:l):s}return this.note(`\\begin{${t}} is not an environment TeXConverter converts; its contents were kept as ordinary paragraphs.`),this.blocks(n,o)}figure(t,n){let r=this.drawnFigure(n,`A \\begin{${t}}`);return r===null?n.split(/\n/).filter(o=>o.trim()!=="").map(o=>({kind:"paragraph",children:[{kind:"text",text:o}]})):[{kind:"paragraph",children:[r]}]}drawnFigure(t,n){let r;try{r=Qc(t)}catch(i){let s=i instanceof qn?i.toDisplayString():i instanceof Error?i.message:String(i);return this.note(`${n} could not be drawn, so its source was kept as text: ${s}`),null}let o=`word/media/figure${this.figureCounter++}.svg`;return this.images.set(o,Ys(r)),{kind:"image",part:o,source:{language:"tikz",tex:t}}}scheme(t,n){let r=t.indexOf("\\schemestop",n);if(r<0)return null;let o=r+11,i=t.slice(n,o),s=this.drawnFigure(i,"A \\schemestart reaction");return{blocks:[{kind:"paragraph",align:"center",children:s===null?[{kind:"text",text:i}]:[s]}],end:o}}listItemContent(t){let n=[],r=[],o=!0,i=a(l=>{if(l.trim()==="")return;let u=this.inlines(l);u.length!==0&&(o?n.push(...u):r.push({kind:"paragraph",children:u}))},"appendText"),s=0;for(;s0||d.blocks.length>0||c.length===0)&&o.push({level:r,children:d.children,...d.blocks.length?{blocks:d.blocks}:{},...s!==null?{label:this.inlines(s)}:{}}),o.push(...c)}return{kind:"list",ordered:n,items:o}}findNestedList(t){for(let n of["itemize","enumerate","description"]){let r=t.indexOf(`\\begin{${n}}`);if(r>=0)return{index:r,name:n}}return null}splitItems(t){let n=[],r=0,o=-1,i=null,s=0;for(;s=0&&n.push({label:i,body:t.slice(o,s)}),s+=5,i=null,t[s]==="["){let l=Dn(t,s,"[","]");l>0&&(i=t.slice(s+1,l-1).trim(),s=l)}o=s;continue}s+=1}return o>=0&&n.push({label:i,body:t.slice(o)}),n}table(t,n){let r=t,o="";for(let u=0;u<(n==="tabularx"?2:1);u++){let c=r.indexOf("{");if(c<0)break;let d=Dn(r,c);if(d<0)break;o=r.slice(c+1,d-1),r=r.slice(d)}let i=o.includes("|"),s=/\\(?:toprule|bottomrule)\b/.test(r),l=[];for(let u of this.splitRows(r)){s&&l.length>0&&/^\s*(?:\[[^\]]*\])?\s*\\(?:midrule|cmidrule|hline)\b/.test(u)&&(l[l.length-1]={...l[l.length-1],ruleBelow:!0});let c=u.replace(/\\(?:hline|toprule|midrule|bottomrule)\b/g,"").replace(/^\s*\[[^\]]*\]/,"").trim();if(c==="")continue;let d=this.splitCells(c).map(p=>{let f=/^\s*\\multicolumn\s*\{(\d+)\}/.exec(p);if(f!==null){let m=Qe(p,p.indexOf("\\multicolumn"),3);return{span:Number(f[1]),blocks:[{kind:"paragraph",children:this.inlines(m?.args[2]??"")}]}}return{span:1,blocks:[{kind:"paragraph",children:this.inlines(p.trim())}]}});l.push({cells:d,header:!1})}return s?{kind:"table",rows:l,bordered:!1,booktabs:!0}:{kind:"table",rows:l,bordered:i}}splitRows(t){let n=[],r=0,o=0,i=0;for(;i0&&(i=l)}o=i;continue}if(s==="\\"){i+=2;continue}i+=1}return n.push(t.slice(o)),n}splitCells(t){let n=[],r=0,o=0,i=0;for(;i=r)return this.note(`\\input{${t}} was not followed \u2014 files are nested more than ${r} deep, which usually means a cycle.`),[];let o=this.options.resolveInput;if(o===void 0)return this.note(`\\input{${t}} was skipped \u2014 this converter was not given a way to read other files.`),[];let i=o(t);return i===null?(this.note(`\\input{${t}} was skipped \u2014 the file could not be read.`),[]):this.blocks(sd(i),n+1)}};function Db(e){let t=/^\s*\[([^\n]*?)\]/.exec(e)?.[1],n=t?/\blabel\s*=\s*(\{(?:[^{}]|\{[^{}]*\})*\}|[^,\]]+)/.exec(t)?.[1]:void 0;if(!n)return null;let r=n.trim().replace(/^\{([\s\S]*)\}$/,"$1").trim(),o=/^\\textbf\{([\s\S]*)\}$/.exec(r);o&&(r=o[1].trim());let i=/^([^\\{}]*)\\arabic\*([^\\{}]*)$/.exec(r);if(!i)return null;let s={prefix:i[1],suffix:i[2],bold:o!==null};return s.prefix===""&&s.suffix==="."&&!s.bold?null:s}a(Db,"listLabel");function Tb(e){let t={},n=/\\documentclass\s*\[([^\]]*)\]/.exec(e)?.[1]??"",r=/\\usepackage\s*\[([^\]]*)\]\s*\{geometry\}/.exec(e)?.[1]??"",o=/\b(a4|letter|legal)paper\b/.exec(`${n},${r}`)?.[1];o&&(t.size=o);let i=/\b(10|11|12)pt\b/.exec(n)?.[1];i&&(t.fontSizePt=Number(i));let s=/(?:^|,)\s*margin\s*=\s*([^,]+)/.exec(r)?.[1],l=s?/^\s*([0-9]*\.?[0-9]+)\s*cm\s*$/.exec(s):null,u=l?Number(l[1]):s?ka(s):null;if(u!==null&&(t.marginCm=u),/\\renewcommand\s*\{?\\familydefault\}?\s*\{\\sfdefault\}/.test(e)?t.font="sans":/\\usepackage\s*(?:\[[^\]]*\])?\s*\{(?:mathptmx|newtxtext|times|tgtermes)\b/.test(e)&&(t.font="serif"),/\\pagestyle\s*\{fancy\}/.test(e)){let c=e.search(/\\fancyfoot\s*\[L\]/),d=c<0?void 0:Qe(e,c,1)?.args[0],p=Ai((d??"").replace(/\\(?:small|footnotesize|scriptsize)\b\s*/g,"")).trim(),f=/\\fancyfoot\s*\[[RC]\]\s*\{[^}]*\\thepage/.test(e);(p||f)&&(t.footer={text:p,pageNumbers:f})}return Object.keys(t).length?t:void 0}a(Tb,"pageSetup");function Cb(e){let t=e.indexOf("\\begin{document}");if(t<0)return{preamble:"",body:e};let n=e.lastIndexOf("\\end{document}"),r=t+16;return{preamble:e.slice(0,t),body:n>r?e.slice(r,n):e.slice(r)}}a(Cb,"splitPreambleAndBody");function Ei(e,t){let n=e.indexOf(`\\${t}`);if(n<0)return;let o=Qe(e,n,1)?.args[0];return o===void 0||o.trim()===""?void 0:o.trim()}a(Ei,"preambleValue");function ud(e,t={}){let n=sd(e),{preamble:r,body:o}=Cb(n),i=!e.includes("\\begin{document}"),s=new Ea({...t,keepLineBreaks:t.keepLineBreaks??i}),l=s.blocks(o),u=Ei(r,"documentclass")??"article",c=Ei(r,"title"),d=Ei(r,"author"),p=Ei(r,"SetWatermarkText"),f=Tb(r),m={document:{blocks:l,footnotes:s.footnotes,images:s.images,...p===void 0?{}:{watermark:Ai(p)},...f?{page:f}:{}},documentClass:u,bibliographyFiles:s.bibliographyFiles,citations:s.citations,warnings:s.warnings};return c!==void 0&&(m.title=c),d!==void 0&&(m.author=d),m}a(ud,"parseTexDocument");x();function cd(e){let t=[],n=0;for(;nu){n=u;continue}let c=e.slice(s,l).trim();s=l+1;let d={};for(;so.trim()).filter(o=>o!=="");if(n.length===0)return"";let r=n.map(o=>{let i=o.indexOf(",");if(i<0)return o;let s=o.slice(0,i).trim(),l=o.slice(i+1).trim();return l===""?s:`${l} ${s}`});return t==="ieee"?r.length===1?r[0]:`${r.slice(0,-1).join(", ")} and ${r[r.length-1]}`:r.length===1?r[0]:r.length===2?`${r[0]} and ${r[1]}`:`${r.slice(0,-1).join(", ")}, and ${r[r.length-1]}`}a(Ib,"formatAuthors");function dd(e,t="plain"){let n=e.fields,r=[],o=Ib(n.author??n.editor??"",t);switch(o!==""&&r.push(o),n.title!==void 0&&r.push(t==="ieee"?`"${n.title}"`:n.title),e.type){case"article":n.journal!==void 0&&r.push(n.journal),n.volume!==void 0&&r.push(n.number===void 0?`vol. ${n.volume}`:`vol. ${n.volume}, no. ${n.number}`),n.pages!==void 0&&r.push(`pp. ${n.pages.replace(/--?/g,"\u2013")}`);break;case"book":n.publisher!==void 0&&r.push(n.publisher),n.edition!==void 0&&r.push(`${n.edition} ed.`);break;case"inproceedings":case"conference":n.booktitle!==void 0&&r.push(`in ${n.booktitle}`),n.pages!==void 0&&r.push(`pp. ${n.pages.replace(/--?/g,"\u2013")}`);break;case"phdthesis":r.push("Ph.D. thesis"),n.school!==void 0&&r.push(n.school);break;case"mastersthesis":r.push("Master's thesis"),n.school!==void 0&&r.push(n.school);break;default:n.howpublished!==void 0&&r.push(n.howpublished),n.publisher!==void 0&&r.push(n.publisher);break}n.year!==void 0&&r.push(n.year),n.doi!==void 0?r.push(`doi:${n.doi}`):n.url!==void 0&&r.push(n.url);let i=r.join(", ");return i.endsWith(".")?i:`${i}.`}a(dd,"formatEntry");function pd(e,t,n="plain"){let r=new Map(e.map(u=>[u.key,u])),o=[],i=[];for(let u of t){let c=r.get(u);c===void 0?o.push(u):i.includes(c)||i.push(c)}let s=n==="unsrt"?i:[...i].sort((u,c)=>{let d=`${u.fields.author??u.fields.editor??""}${u.fields.year??""}`.toLowerCase(),p=`${c.fields.author??c.fields.editor??""}${c.fields.year??""}`.toLowerCase();return d.localeCompare(p)||u.key.localeCompare(c.key)}),l=new Map;s.forEach((u,c)=>l.set(u.key,String(c+1)));for(let u of o)l.set(u,u);return{entries:s,labels:l,missing:o}}a(pd,"buildBibliography");x();x();x();function on(e){let t=Math.max(1,...e.rows.map(n=>n.length));return Array.from({length:t},(n,r)=>e.columns?.[r]??"center")}a(on,"matrixColumnAligns");x();var yp=iu(za(),1);var bp="http://schemas.openxmlformats.org/officeDocument/2006/math",Wt="http://schemas.openxmlformats.org/wordprocessingml/2006/main",tt=class extends Error{static{a(this,"OmmlConversionError")}constructor(t){super(t),this.name="OmmlConversionError"}};function ht(e){throw new tt(e)}a(ht,"fail");function wp(e){return e&&e.nodeType===1&&e.namespaceURI===bp}a(wp,"isMathElement");function He(e){let t=[];for(let n=0;nn.localName===t)??null}a(ne,"firstChild");function Ht(e,t){return He(e).filter(n=>n.localName===t)}a(Ht,"allChildren");function Tt(e,t){let n=e.attributes;if(!n)return null;for(let r=0;r0?r:null}a(Ct,"propVal");function pn(e,t,n){let r=e?ne(e,t):null;if(!r)return n;let o=Tt(r,"val");return o===null||o.length===0?!0:o==="1"||o==="true"||o==="on"}a(pn,"boolProp");function Ge(e,t){let n=ne(e,t);return n?_e(n):{kind:"row",children:[]}}a(Ge,"containerRow");function _e(e){return{kind:"row",children:He(e).filter(n=>n.localName!=="argPr"&&n.localName!=="ctrlPr").map(Ja)}}a(_e,"parseContainerAsRow");var Pw=/[Ͱ-Ͽἀ-῿]/;function Iw(e){return/[A-Za-z]/.test(e)||Pw.test(e)}a(Iw,"naturalItalic");function $w(e){let t=Ht(e,"t").map(u=>u.textContent??"").join(""),n=ne(e,"rPr"),r=Ct(n,"sty"),o,i=!1;if(n&&ne(n,"nor")){let u=Rw(e);i=u.has("b"),o=u.has("i")}else r?(i=r.includes("b"),o=r.includes("i")):o=[...t].every(u=>Iw(u))&&t.length>0;let s=Mw(e),l={kind:"symbol",text:t,italic:o,bold:i||void 0};return s!==void 0&&(l.color=s),l}a($w,"parseRun");function Rw(e){let t=new Set;for(let n=0;n0?_e(n):void 0;return{kind:"radical",radicand:Ge(e,"e"),index:r}}a(_w,"parseRadical");function Va(e,t){let n=ne(e,"sup"),r=ne(e,"sub");return{kind:"supersub",base:Ge(e,"e"),sup:n&&He(n).length>0?_e(n):void 0,sub:r&&He(r).length>0?_e(r):void 0}}a(Va,"parseSuperSub");var Lw="\u222B";function Fw(e){let t=ne(e,"naryPr"),n=Ct(t,"chr")??Lw,r=Ct(t,"limLoc")??"subSup",o=pn(t,"subHide",!1),i=pn(t,"supHide",!1),s=o?null:ne(e,"sub"),l=i?null:ne(e,"sup");return{kind:"nary",chr:n,sub:s&&He(s).length>0?_e(s):void 0,sup:l&&He(l).length>0?_e(l):void 0,operand:Ge(e,"e"),limitLocation:r==="undOvr"?"undOvr":"subSup"}}a(Fw,"parseNary");var Bw={"(":"(",")":")","[":"[","]":"]","|":"|","{":"\\{ ","}":"\\} ","\u27E8":"\\langle ","\u27E9":"\\rangle ","\u2016":"\\Vert ","\u230A":"\\lfloor ","\u230B":"\\rfloor ","\u2308":"\\lceil ","\u2309":"\\rceil ","":"."};function vr(e){let t=Bw[e];return t===void 0&&ht(`Cannot represent delimiter character "${e}" in LaTeX \\left...\\right.`),t}a(vr,"delimiterCharToLatex");function Uw(e){let t=ne(e,"dPr"),n=t?ne(t,"begChr"):null,r=t?ne(t,"endChr"):null,o=t?ne(t,"sepChr"):null,i=n?Tt(n,"val")??"":"(",s=r?Tt(r,"val")??"":")",l=o?Tt(o,"val")??void 0:void 0,u=Ht(e,"e"),c=u.length>0?u.map(_e):[{kind:"row",children:[]}];return{kind:"delimited",left:i,right:s,parts:c,sepChar:l}}a(Uw,"parseDelimited");function qw(e){return{kind:"row",children:[...Ge(e,"fName").children,...Ge(e,"e").children]}}a(qw,"parseFunc");function Ww(e){return Ge(e,"e")}a(Ww,"parseBox");function Hw(e){let t=Ht(e,"mr").map(r=>Ht(r,"e").map(_e)),n=Gw(e);return n===void 0?{kind:"matrix",rows:t}:{kind:"matrix",rows:t,columns:n}}a(Hw,"parseMatrix");function Gw(e){let t=ne(e,"mPr"),n=t?ne(t,"mcs"):null;if(!n)return;let r=[];for(let o of Ht(n,"mc")){let i=ne(o,"mcPr"),s=Ct(i,"mcJc")??"center";(s==="inside"||s==="outside")&&ht(`A matrix column justified "${s}" has no LaTeX array equivalent \u2014 only left, center and right do.`);let l=s==="left"?"left":s==="right"?"right":"center",u=Number.parseInt(Ct(i,"count")??"1",10);for(let c=0;c<(Number.isFinite(u)&&u>0?u:1);c++)r.push(l)}return r.some(o=>o!=="center")?r:void 0}a(Gw,"parseMatrixColumns");var jw="\u0302";function Xw(e){let t=Ct(ne(e,"accPr"),"chr")??jw;return{kind:"accent",base:Ge(e,"e"),char:t}}a(Xw,"parseAcc");function zw(e){return(Ct(ne(e,"barPr"),"pos")??"bot")==="bot"?{kind:"accent",base:Ge(e,"e"),bar:!0,under:!0}:{kind:"accent",base:Ge(e,"e"),bar:!0}}a(zw,"parseBar");function Vw(e){let t=Ge(e,"e"),n=ne(e,"sub"),r=ne(e,"sup"),o=n&&He(n).length>0?_e(n):void 0,i=r&&He(r).length>0?_e(r):void 0;return{kind:"prescript",base:t,presub:o,presup:i}}a(Vw,"parsePrescript");function Yw(e){let t=ne(e,"eqArrPr"),n=t?ne(t,"baseJc"):null,r=n?Tt(n,"val"):"left";return{kind:"eqarr",rows:Ht(e,"e").map(_e),justify:r==="center"?"center":"left"}}a(Yw,"parseEqArr");var Ya=new Set(["\u27F6","\u27F5","\u27F7","\u27F9","\u27F8","\u27FA","\u21CC","\u21CB","\u27FC","\u21AA","\u21A9"]);function Ka(e){let t=He(e);return t.length===0||!t.every(n=>n.localName==="r")?null:t.map(n=>Ht(n,"t").map(r=>r.textContent??"").join("")).join("")}a(Ka,"plainTextOf");function xp(e,t){let n=ne(e,"e"),r=ne(e,"lim");(!n||!r)&&ht("m:limLow is missing m:e or m:lim.");let o=Ka(n);if(o!==null&&Ya.has(o)){let i=t?Za(t.above):void 0;return{kind:"labeledarrow",chr:o,below:_e(r),above:i}}return t&&ht(`m:limUpp wraps m:limLow, but the inner base "${o??"(complex content)"}" is not a recognized arrow glyph \u2014 cannot tell whether this is a labeled arrow.`),{kind:"limlow",base:_e(n),lower:_e(r)}}a(xp,"parseLimLow");function Kw(e){let t=ne(e,"borderBoxPr"),n=["hideTop","hideBot","hideLeft","hideRight"].map(s=>pn(t,s,!1)),r=n.every(s=>!s);!r&&!n.every(s=>s)&&ht("m:borderBox with only some of its borders drawn has no LaTeX equivalent \u2014 \\boxed draws all four."),(pn(t,"strikeH",!1)||pn(t,"strikeV",!1))&&ht("m:borderBox with a horizontal or vertical strike has no \\cancel equivalent \u2014 \\cancel draws a diagonal.");let o=pn(t,"strikeBLTR",!1),i=pn(t,"strikeTLBR",!1);return r?{kind:"borderbox",base:Ge(e,"e"),strikeBLTR:o,strikeTLBR:i,boxed:!0}:{kind:"borderbox",base:Ge(e,"e"),strikeBLTR:o,strikeTLBR:i}}a(Kw,"parseBorderBox");var Zw={"\u23DE":"top","\u23DF":"bot","\u23DC":"top","\u23DD":"bot"};function Jw(e){let t=ne(e,"groupChrPr"),n=Ct(t,"chr")??"\u23DE",r=Zw[n];r===void 0&&ht(`m:groupChr with the character "${n}" has no LaTeX equivalent \u2014 only the braces \\overbrace (\u23DE), \\underbrace (\u23DF) and the arcs \\overparen (\u23DC), \\underparen (\u23DD) are supported.`);let o=Ct(t,"pos")??"top";return o!==r&&ht(`m:groupChr draws "${n}" but places it at "${o}" \u2014 LaTeX has no way to write a top brace underneath (or the reverse).`),{kind:"groupchar",chr:n,pos:r,base:Ge(e,"e")}}a(Jw,"parseGroupChar");function Za(e){return _e(e)}a(Za,"parseLimUppLabel");function Qw(e){let t=ne(e,"e"),n=ne(e,"lim");(!t||!n)&&ht("m:limUpp is missing m:e or m:lim.");let r=He(t);if(r.length===1&&r[0].localName==="limLow"){let i=r[0],s=ne(i,"e"),l=s?Ka(s):null;if(l!==null&&Ya.has(l))return xp(i,{above:n})}let o=Ka(t);return o!==null&&Ya.has(o)?{kind:"labeledarrow",chr:o,above:Za(n),below:void 0}:{kind:"limupp",base:_e(t),upper:Za(n)}}a(Qw,"parseLimUpp");function Ja(e){switch(e.localName){case"r":return $w(e);case"f":return Ow(e);case"rad":return _w(e);case"sSup":return Va(e,"sSup");case"sSub":return Va(e,"sSub");case"sSubSup":return Va(e,"sSubSup");case"nary":return Fw(e);case"d":return Uw(e);case"func":return qw(e);case"box":return Ww(e);case"m":return Hw(e);case"acc":return Xw(e);case"bar":return zw(e);case"sPre":return Vw(e);case"eqArr":return Yw(e);case"limLow":return xp(e,!1);case"limUpp":return Qw(e);case"borderBox":return Kw(e);case"groupChr":return Jw(e);default:return ht(`"m:${e.localName}" is not a construct TeXConverter can convert back to LaTeX yet.`)}}a(Ja,"parseNode");function In(e){let t=[],n=new yp.DOMParser({errorHandler:a((r,o)=>{(r==="error"||r==="fatalError")&&t.push(String(o))},"errorHandler")}).parseFromString(e,"text/xml");return t.length>0&&ht(`The provided OOXML is not well-formed XML: ${t.join("; ")}`),n}a(In,"parseOoxml");function vp(e){let t=e.parentNode;for(;t;){if(wp(t)&&t.localName==="oMathPara")return!0;t=t.parentNode}return!1}a(vp,"isDisplayEquation");function Qa(e){let t=He(e).filter(r=>r.localName!=="ctrlPr");if(t.length!==1||t[0].localName!=="eqArr")return null;let n=Ht(t[0],"e").map(r=>{let o=He(r).filter(s=>s.localName!=="argPr"&&s.localName!=="ctrlPr"),i=o.findIndex(s=>s.localName==="r"&&Ht(s,"t").map(l=>l.textContent??"").join("")==="#");return i<0?{body:o,number:null}:{body:o.slice(0,i),number:o.slice(i+1)}});return n.some(r=>r.number!==null)?n:null}a(Qa,"splitEquationRows");function kp(e){let t=!1,n=!1,r="",o=[],i=a(s=>{if(!(!s||s.nodeType!==1)){if(s.namespaceURI===Wt&&s.localName==="fldChar"){n=Tt(s,"fldCharType")==="begin";return}if(s.namespaceURI===Wt&&s.localName==="bookmarkStart"){let l=Tt(s,"name");l&&o.push(l);return}if(s.namespaceURI===bp&&s.localName==="t"||s.namespaceURI===Wt&&s.localName==="instrText"){let l=s.textContent??"";n?t||=/^\s*SEQ\b/i.test(l):r+=l;return}for(let l=0;ln.number===null?null:kp(n.number))}a(Ap,"equationRowNumbersOf");function Sp(e){let t=Qa(e);return t!==null&&t.length===1?{kind:"row",children:t[0].body.map(Ja)}:t!==null?{kind:"eqarr",rows:t.map(n=>({kind:"row",children:n.body.map(Ja)})),justify:"left"}:_e(e)}a(Sp,"oMathElementToIr");function Ao(e){throw new tt(e)}a(Ao,"fail");var ex={"\u2264":"leq","\u2265":"geq","\u2260":"neq","\u2192":"to","\u2190":"leftarrow","\u2205":"emptyset",\u210F:"hbar","\xAC":"neg","\u2016":"Vert","\u27F9":"implies","\u27F8":"impliedby","\u27FA":"iff","\u21DD":"leadsto","\u2026":"ldots"},Np=Object.fromEntries(Object.entries(Go).map(([e,t])=>[t,e])),tx={"\u27F6":"xrightarrow","\u27F5":"xleftarrow","\u27F7":"xleftrightarrow","\u27F9":"xRightarrow","\u27F8":"xLeftarrow","\u27FA":"xLeftrightarrow","\u21CC":"xrightleftharpoons","\u21CB":"xleftrightharpoons","\u27FC":"xmapsto","\u21AA":"xhookrightarrow","\u21A9":"xhookleftarrow"};function nx(){let e=new Map;for(let[t,n]of Object.entries(Jt))e.has(n.text)||e.set(n.text,t);for(let[t,n]of Object.entries(Np))e.set(t,n);for(let[t,n]of Object.entries(ex))e.set(t,n);return e}a(nx,"buildReverseSymbolMap");var nl=nx();function rx(e){let t=nl.get(e);return t!==void 0?`\\${t} `:e==="\\"||e==="{"||e==="}"||e==="%"||e==="$"||e==="#"||e==="&"||e==="_"?`\\${e}`:e}a(rx,"reverseChar");function Pp(e){return[...e].map(rx).join("")}a(Pp,"reverseText");function Eo(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(r,n);return t}a(Eo,"invert");var ox={mathbb:Eo(Ns),mathcal:Eo(Ps),mathfrak:Eo(Is),mathsf:Eo($s),mathtt:Eo(Rs)},ix=/[Ͱ-Ͽἀ-῿]/;function rl(e){return/[A-Za-z]/.test(e)||ix.test(e)}a(rl,"naturalItalic");function sx(e){return!rl(e)&&nl.has(e)}a(sx,"italicIsMeaningless");function ax(e,t){return e.length===0?!0:[...e].every(n=>rl(n)===t||sx(n))}a(ax,"matchesNaturalItalic");function lx(e){let t=[...e.text];if(t.length>0&&!e.bold)for(let r of["mathbb","mathcal","mathfrak","mathsf","mathtt"]){let o=ox[r];if(t.every(i=>o.has(i)))return{kind:"variant",variant:r,plainText:t.map(i=>o.get(i)).join("")}}let n=e.bold??!1;if(ax(e.text,e.italic)&&!/\s/.test(e.text))return n?{kind:"boldsymbol"}:{kind:"plain"};if(!e.italic)return n?{kind:"mathbf"}:{kind:"mathrm"};if(!n&&!/\s/.test(e.text))return{kind:"mathit"};Ao(`Cannot represent this run ("${e.text}", italic=${e.italic}, bold=${n}) in LaTeX \u2014 its styling doesn't match any of plain text, \\mathbf, \\boldsymbol, or \\mathrm.`)}a(lx,"classifySymbolStyle");function Dp(e){return e.kind==="variant"?`variant:${e.variant}`:e.kind}a(Dp,"styleSignature");function ux(e,t){switch(e.kind){case"variant":return`\\${e.variant}{${t}}`;case"mathbf":return/\s/.test(t)&&!/[\\{}^_$&%#~]/.test(t)?`\\textbf{${t}}`:`\\mathbf{${t}}`;case"boldsymbol":return`\\boldsymbol{${t}}`;case"mathrm":return`\\mathrm{${t}}`;case"mathit":return`\\mathit{${t}}`;case"plain":return t}}a(ux,"wrapStyle");function cx(e,t){if(e===void 0)return t;let n=uu(e);return n===void 0?`\\textcolor[HTML]{${e}}{${t}}`:`\\textcolor{${n}}{${t}}`}a(cx,"wrapColor");function dx(e,t){return t.kind==="variant"?t.plainText:t.kind==="mathrm"?e.text:Pp(e.text)}a(dx,"groupText");function px(e){return rl(e)||/\s/.test(e)}a(px,"mustStayWrapped");function fx(e){let t=[],n="",r=!1,o=a(()=>{n!==""&&(t.push(r?{style:{kind:"mathrm"},text:n}:{style:{kind:"plain"},text:Pp(n)}),n="")},"flush");for(let i of e){let s=px(i);n!==""&&s!==r&&o(),r=s,n+=i}return o(),t}a(fx,"splitUprightRun");function mx(e){let t=lx(e),n=t.kind!=="mathrm"?[{style:t,text:dx(e,t)}]:fx(e.text);return e.color===void 0?n:n.map(r=>({...r,color:e.color}))}a(mx,"symbolPieces");function hx(e,t){return e.kind==="plain"?t:e.kind==="mathrm"&&Un.has(t)?`\\${t} `:ux(e,t)}a(hx,"emitGroup");function Tp(e){let t=e.length-1,n="",r=null,o,i="",s=a(()=>{r!==null&&(n+=cx(o,hx(r,i)),r=null,o=void 0,i="")},"flush");for(let l=0;lr.kind==="symbol"&&!r.italic))return null;let n=t.map(r=>r.text).join("");return Un.has(n)?n:null}a(Cp,"uprightFunctionName");function bx(e){if(e.sepChar!=="|"||e.parts.length<2)return null;let t=e.parts.map(c=>Rp([c]));if(!t.every(c=>c!==null&&c.kind==="matrix"))return null;let n=t,r=n[0].rows.length;if(!n.every(c=>c.rows.length===r))return null;let o=n.map(c=>on(c).map(d=>Ip[d]).join("")).join("|"),i=[];for(let c=0;c{let p=on(d).length;return Array.from({length:p},(f,m)=>d.rows[c][m]?xe(d.rows[c][m]):"")}).join(" & "));let s=$p(i,n[0].hlines),l=(e.left===""||e.left==="|")&&(e.right===""||e.right==="|"),u=a((c,d)=>`\\begin{array}{${c}${o}${d}} ${s} \\end{array}`,"array");return l?u(e.left==="|"?"|":"",e.right==="|"?"|":""):`\\left${vr(e.left)}${u("","")}\\right${vr(e.right)}`}a(bx,"ruledArrayLatex");function $p(e,t){if(t===void 0||t.length===0)return e.join(" \\\\ ");let n=e.map((r,o)=>t.includes(o)?`\\hline ${r}`:r).join(" \\\\ ");return t.includes(e.length)?`${n} \\\\ \\hline`:n}a($p,"withRowRules");function ce(e){return`{${xe(e)}}`}a(ce,"braced");function Rp(e){if(e.length!==1)return null;let t=e[0];return t.kind==="row"?t.children.length===1?t.children[0]:null:t}a(Rp,"singleChild");function xe(e){switch(e.kind){case"row":return Tp(e.children);case"symbol":return Tp([e]);case"frac":return`\\${e.noBar?"binom":"frac"}${ce(e.numerator)}${ce(e.denominator)}`;case"radical":return e.index?`\\sqrt[${xe(e.index)}]${ce(e.radicand)}`:`\\sqrt${ce(e.radicand)}`;case"supersub":{let t=xe(e.base),n=t.length===0?"{}":t,r=e.sub&&!e.sup?Cp(e.base):null;return r!==null&&_r.has(r)&&(n=`\\${r}\\nolimits`),e.sub&&(n+=`_${ce(e.sub)}`),e.sup&&(n+=`^${ce(e.sup)}`),n}case"limlow":{if(e.base.kind==="groupchar"&&e.base.pos==="bot")return`\\${el(e.base.chr)}${ce(e.base.base)}_${ce(e.lower)}`;let t=Cp(e.base);return t===null?`\\underset${ce(e.lower)}${ce(e.base)}`:_r.has(t)?`\\${t}_${ce(e.lower)}`:`\\${t}\\limits_${ce(e.lower)}`}case"limupp":return e.base.kind==="groupchar"&&e.base.pos==="top"?`\\${el(e.base.chr)}${ce(e.base.base)}^${ce(e.upper)}`:`\\overset${ce(e.upper)}${ce(e.base)}`;case"groupchar":return`\\${el(e.chr)}${ce(e.base)}`;case"borderbox":{let t;return e.strikeBLTR&&e.strikeTLBR?t=`\\xcancel${ce(e.base)}`:e.strikeTLBR?t=`\\bcancel${ce(e.base)}`:e.strikeBLTR?t=`\\cancel${ce(e.base)}`:t=xe(e.base),e.boxed?`\\boxed{${t}}`:t}case"nary":{let t=Np[e.chr];t||Ao(`Cannot represent the operator "${e.chr}" as a LaTeX \\sum/\\int-style command.`);let n=`\\${t}`,r=e.limitLocation==="undOvr";return(e.sub||e.sup)&&r!==Nu.has(e.chr)&&(n+=r?"\\limits":"\\nolimits"),e.sub&&(n+=`_${ce(e.sub)}`),e.sup&&(n+=`^${ce(e.sup)}`),`${n} ${xe(e.operand)}`}case"delimited":{if(e.left==="("&&e.right===")"&&!e.sepChar){let t=Rp(e.parts);if(t&&t.kind==="frac"&&t.noBar)return xe(t)}tl++;try{let t=bx(e);if(t!==null)return t;let n=vr(e.left),r=vr(e.right);if(e.parts.length===1)return`\\left${n}${xe(e.parts[0])}\\right${r}`;e.sepChar||Ao("A multi-part delimited group must have a separator character (\\middle).");let o=vr(e.sepChar).trim(),i=e.parts.map(s=>xe(s)).join(`\\middle${o} `);return`\\left${n}${i}\\right${r}`}finally{tl--}}case"matrix":{let t=$p(e.rows.map(r=>r.map(o=>xe(o)).join(" & ")),e.hlines),n=on(e);return n.some(r=>r!=="center")||e.hlines!==void 0&&e.hlines.length>0?`\\begin{array}{${n.map(o=>Ip[o]).join("")}} ${t} \\end{array}`:`\\begin{matrix} ${t} \\end{matrix}`}case"accent":{if(e.bar)return e.under?`\\underline${ce(e.base)}`:`\\bar${ce(e.base)}`;let t=gx[e.char??""];return t||Ao(`Cannot represent the combining accent character "${e.char}" as a LaTeX accent command.`),`\\${t}${ce(e.base)}`}case"prescript":{let t=e.presub?`_{${xe(e.presub)}}`:"",n=e.presup?`^{${xe(e.presup)}}`:"";return`{}${t}${n}${xe(e.base)}`}case"eqarr":{let t=tl>0,n=e.justify==="left"?t?"aligned":"align*":t?"gathered":"gather*",r=e.rows.map(o=>xe(o)).join(" \\\\ ");return`\\begin{${n}} ${r} \\end{${n}}`}case"labeledarrow":{let t=tx[e.chr];if(t!==void 0){let i=t,s=e.below?`[${xe(e.below)}]`:"",l=e.above?ce(e.above):"{}";return`\\${i}${s}${l}`}let n=nl.get(e.chr),r=n===void 0?e.chr:`\\${n}`,o=e.below?`\\underset${ce(e.below)}{${r}}`:r;return e.above&&(o=`\\overset${ce(e.above)}{${o}}`),o}default:{let t=e;throw new tt(`Unhandled IR node in irToLatex: ${JSON.stringify(t)}`)}}}a(xe,"irToLatex");x();function Mp(){return{images:!1,links:!1,tables:!1,chemistry:!1,units:!1,unicode:!1,colouredTables:!1,tikz:!1,pgfplots:!1,chemfig:!1,enumitem:!1,booktabs:!1}}a(Mp,"emptyFeatures");function wx(e){let t=Math.max(.3,Math.min(1.2,7/Math.max(1,e.trim().length)));return["\\usepackage{draftwatermark}",`\\SetWatermarkText{${xx(e.trim())}}`,`\\SetWatermarkScale{${Math.round(t*100)/100}}`,"\\SetWatermarkLightness{0.88}"]}a(wx,"watermarkLines");function Op(e){let t=["section","subsection","subsubsection","paragraph","subparagraph"];return e==="article"?t:["chapter",...t]}a(Op,"sectioningCommands");function xx(e){return e.replace(/[\\{}]/g,"").replace(/([&%$#_])/g,"\\$1").replace(/[~^]/g,"")}a(xx,"escapeWatermark");function _p(e,t={}){if(t.customPreamble!==void 0)return t.customPreamble.trimEnd();let n=t.documentClass??"article",o=[`\\documentclass[${[`${t.fontSize??11}pt`,t.paper??"a4paper"].join(",")}]{${n}}`];return o.push("\\usepackage{amsmath}","\\usepackage{amssymb}"),e.unicode&&o.push("\\usepackage{iftex}","\\ifTUTeX\\usepackage{fontspec}\\fi"),e.chemistry&&o.push("\\usepackage{mhchem}"),e.units&&o.push("\\usepackage{siunitx}"),e.images&&o.push("\\usepackage{graphicx}"),e.tables&&o.push("\\usepackage{array}"),e.booktabs&&o.push("\\usepackage{booktabs}"),e.enumitem&&o.push("\\usepackage{enumitem}"),e.pgfplots?o.push("\\usepackage{pgfplots}","\\pgfplotsset{compat=1.18}"):e.tikz&&o.push("\\usepackage{tikz}"),e.chemfig&&o.push("\\usepackage{chemfig}"),e.colouredTables&&o.push("\\usepackage[table]{xcolor}"),t.watermark!==void 0&&t.watermark.trim()!==""&&o.push(...wx(t.watermark)),e.links&&o.push("\\usepackage{hyperref}"),o.join(` `)}a(_p,"buildPreamble");var vx={"\\":"\\textbackslash{}","&":"\\&","%":"\\%",$:"\\$","#":"\\#",_:"\\_","{":"\\{","}":"\\}","~":"\\textasciitilde{}","^":"\\textasciicircum{}"},kx=new Set(["-","'","`",",","<",">"]);function Fp(e){let t=e.codePointAt(0);if(t>=9398&&t<=9423)return`\\textcircled{${String.fromCharCode(65+t-9398)}}`;if(t>=9424&&t<=9449)return`\\textcircled{${String.fromCharCode(97+t-9424)}}`;if(t===9450)return"\\textcircled{0}";if(t>=9312&&t<=9320)return`\\textcircled{${t-9312+1}}`}a(Fp,"circledCommand");function Lp(e){let t="",n="";for(let r of e)r===n&&kx.has(r)&&(t+="{}"),t+=vx[r]??Fp(r)??r,n=r;return t}a(Lp,"escapeText");var Ex=/^\s*\\begin\{(equation|align|gather|displaymath|multline|eqnarray)\*?\}/;function Ax(e){return Ex.test(e)}a(Ax,"isDisplayEnvironment");function kr(e){return e.replace(/[\\{}%#$&~^]/g,"")}a(kr,"escapeLabel");function Sx(e){for(let t of e)if(t.codePointAt(0)>255&&Fp(t)===void 0)return!0;return!1}a(Sx,"hasNonLatin1");var ol=class{constructor(t,n){this.document=t;this.options=n;this.features=Mp();this.images=new Map;this.warnings=[];this.imageNames=new Map;this.imageCounter=n.imageStartIndex??1}static{a(this,"Emitter")}inline(t){return t.map(n=>this.inlineOne(n)).join("")}inlineOne(t){switch(t.kind){case"text":return this.text(t.text,t);case"math":return this.math(t.ir,t.display,t.source);case"link":{this.features.links=!0;let n=this.inline(t.children);return`\\href{${Lp(t.href)}}{${n}}`}case"image":return this.image(t);case"break":return t.variant==="page"?` \\newpage `:`\\\\ `;case"rule":return"\\noindent\\rule{\\textwidth}{0.4pt}";case"fill":return"\\hfill ";case"blank":return`\\underline{\\hspace{${t.widthCm}cm}}`;case"citation":return`\\cite{${t.keys.map(n=>kr(n)).join(",")}}`;case"label":return`\\label{${kr(t.id)}}`;case"eqnumber":return"";case"ref":return t.wrap==="parentheses"?`\\eqref{${kr(t.id)}}`:`\\ref{${kr(t.id)}}`;case"footnoteref":{let n=this.document.footnotes.get(t.id);return n===void 0?"":`\\footnote{${n.map(o=>this.block(o)).join(" ").trim()}}`}}}text(t,n){if(t==="")return"";Sx(t)&&(this.features.unicode=!0);let r=Lp(t).replace(/\t/g,"\\quad{}");return n.script==="sub"?r=`\\textsubscript{${r}}`:n.script==="super"&&(r=`\\textsuperscript{${r}}`),n.bold===!0&&(r=`\\textbf{${r}}`),n.italic===!0&&(r=`\\textit{${r}}`),n.underline===!0&&(r=`\\underline{${r}}`),r}math(t,n,r){let o;if(r!==void 0)o=r;else try{o=xe(t)}catch(i){let s=i instanceof Error?i.message:String(i);return this.warnings.push(`An equation could not be written as LaTeX and was left as a marker: ${s}`),"\\textbf{[equation not converted]}"}return o.includes("\\ce{")&&(this.features.chemistry=!0),/\\si\{|\\unit\{/.test(o)&&(this.features.units=!0),n?Ax(o)?o:`\\[${o}\\]`:`$${o}$`}image(t){if(t.source?.language==="tikz"){let i=ed(t.source.tex).join(` `);return i.includes("{pgfplots}")&&(this.features.pgfplots=!0),i.includes("{tikz}")&&(this.features.tikz=!0),i.includes("{chemfig}")&&(this.features.chemfig=!0),i.includes("{mhchem}")&&(this.features.chemistry=!0),t.source.tex}this.features.images=!0;let n=this.document.images.get(t.part);if(n===void 0)return this.warnings.push(`An image referenced ${t.part}, which is not in the document, and was skipped.`),"";let r=this.imageNames.get(t.part);if(r===void 0){let i=t.part.lastIndexOf("."),s=i<0?".png":t.part.slice(i);r=`${this.options.imageFolder??"images"}/image${this.imageCounter++}${s}`,this.imageNames.set(t.part,r),this.images.set(r,n)}return`\\includegraphics${t.widthEmu!==void 0?`[width=${(t.widthEmu/914400).toFixed(3)}in]`:""}{${r}}`}block(t){switch(t.kind){case"heading":return this.heading(t.level,this.inline(t.children),t.numbered!==!1);case"paragraph":{let n=this.labelledDisplayEquation(t.children);if(n!==null)return n;let r=this.inline(t.children).trim();return r===""?"":t.align==="center"?`\\begin{center} ${r} \\end{center}`:t.align==="right"?`\\begin{flushright} ${r} \\end{flushright}`:r}case"list":return this.list(t.items,t.ordered,0,t.start);case"table":return this.table(t)}}labelledDisplayEquation(t){let n=t.filter(d=>d.kind!=="text"||d.text.trim()!==""),r=n.filter(d=>d.kind==="label"),o=n.find(d=>d.kind==="eqnumber"),i=n.filter(d=>d.kind!=="label"&&d.kind!=="eqnumber");if(r.length===0&&o===void 0||i.length!==1)return null;let s=i[0];if(s.kind!=="math"||!s.display)return null;let l=s.source??(()=>{try{return xe(s.ir)}catch{return null}})();if(l===null)return null;if(o?.rows!==void 0){let d=this.lineNumberedEquation(l,o.rows);if(d!==null)return d}let u=r.map(d=>`\\label{${kr(d.id)}}`).join("");o?.tag!==void 0&&!/\\tag\b/.test(l)&&(u+=`\\tag{${o.tag}}`);let c=/^\s*\\begin\{(equation|align|gather|multline|eqnarray)(\*?)\}/.exec(l);if(c!==null){let d=c[1];return(c[2]===""?l:l.replace(`\\begin{${d}*}`,`\\begin{${d}}`).replace(`\\end{${d}*}`,`\\end{${d}}`)).replace(`\\begin{${d}}`,`\\begin{${d}}${u}`)}return`\\begin{equation}${u}${l}\\end{equation}`}lineNumberedEquation(t,n){let r=/^\s*\\begin\{(align|gather|eqnarray|aligned|gathered)\*?\}([\s\S]*)\\end\{\1\*?\}\s*$/.exec(t);if(r===null)return null;let o=Aa(r[2]);if(o.length!==n.length)return null;let i=r[1]==="aligned"?"align":r[1]==="gathered"?"gather":r[1],s=o.map((l,u)=>{let c=n[u],d=c===null?"\\nonumber":c.labels.map(p=>`\\label{${kr(p)}}`).join("")+(c.tag===void 0?"":`\\tag{${c.tag}}`);return`${l.trim()}${d?` ${d}`:""}`});return`\\begin{${i}} ${s.join(` \\\\ `)} \\end{${i}}`}heading(t,n,r=!0){let o=Op(this.options.documentClass??"article"),i=Math.min(t-1,o.length-1);return t-1>o.length-1&&this.warnings.push(`A Heading ${t} was written as \\${o[i]}, the deepest level this document class has.`),`\\${o[i]}${r?"":"*"}{${n}}`}list(t,n,r,o){let i=n?"enumerate":"itemize",s=" ".repeat(r),l=n&&o!==void 0&&o!==1?`[start=${o}]`:"";l&&(this.features.enumitem=!0);let u=[`${s}\\begin{${i}}${l}`];for(let c=0;cr){let p=c;for(;cr;)c++;u.push(this.list(t.slice(p,c),n,r+1)),c--;continue}u.push(`${s} \\item${d.label?`[${this.inline(d.label)}]`:""} ${this.inline(d.children)}`);for(let p of d.blocks??[])p.kind==="table"&&!p.bordered&&p.booktabs!==!0?u.push(`${d.children.length>0?`\\\\ `:""}${this.optionsTable(p)}`):u.push(this.block(p))}return u.push(`${s}\\end{${i}}`),u.join(` `)}table(t){let n=this.tabular(t);return t.align==="center"?`\\begin{center} ${n} \\end{center}`:n}tabular(t){this.features.tables=!0;let n=Math.max(1,...t.rows.map(s=>s.cells.reduce((l,u)=>l+u.span,0)));if(t.booktabs===!0&&this.options.tableBorders!==!0)return this.booktabs(t,n);let r=this.options.tableBorders??t.bordered,i=[`\\begin{tabular}{${r?`|${"l|".repeat(n)}`:"l".repeat(n)}}`];r&&i.push("\\hline");for(let s of t.rows){let l=s.cells.map(u=>{let c=u.blocks.map(d=>this.block(d)).join(" ").trim();return u.span>1?`\\multicolumn{${u.span}}{${r?"|l|":"l"}}{${c}}`:c});i.push(`${l.join(" & ")} \\\\`),r&&i.push("\\hline")}return i.push("\\end{tabular}"),i.join(` `)}optionsTable(t){this.features.tables=!0;let n=Math.max(1,...t.rows.map(i=>i.cells.reduce((s,l)=>s+l.span,0))),o=[`\\begin{tabular}{@{}${`p{${(Math.floor(96/n)/100).toFixed(2).replace(/^0/,"0")}\\linewidth}`.repeat(n)}@{}}`];for(let i of t.rows){let s=i.cells.map(l=>{let u=l.blocks.map(c=>this.block(c)).join(" ").trim();return l.span>1?`\\multicolumn{${l.span}}{l}{${u}}`:u});o.push(`${s.join(" & ")} \\\\`)}return o.push("\\end{tabular}"),o.join(` `)}booktabs(t,n){this.features.booktabs=!0;let r=[`\\begin{tabular}{${"l".repeat(n)}}`,"\\toprule"];return t.rows.forEach((o,i)=>{let s=o.cells.map(l=>{let u=l.blocks.map(c=>this.block(c)).join(" ").trim();return l.span>1?`\\multicolumn{${l.span}}{l}{${u}}`:u});r.push(`${s.join(" & ")} \\\\`),o.ruleBelow===!0&&i0?n[n.length-1]+=` ${l}`:n.push(l))}let r=this.document.watermark;return{tex:`${_p(this.features,r===void 0||this.options.watermark!==void 0?this.options:{...this.options,watermark:r})} \\begin{document} ${n.join(` `)} \\end{document} `,images:this.images,warnings:this.warnings}}};function Bp(e,t={}){return new ol(e,t).emit()}a(Bp,"emitTexDocument");x();x();var Dx={left:"left",center:"center",right:"right"},Tx="http://schemas.openxmlformats.org/officeDocument/2006/math",Cx="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function he(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}a(he,"escapeXml");var il='',Ee='';function Hi(e,t,n=!1,r){if(e.length===0)return"";let o=n?t?"bi":"b":t?"i":"p",i=r===void 0?il:il.replace("",``);return!t&&new RegExp("\\p{L}-\\p{L}","u").test(e)?`${n?i.replace("/>","/>"):i}${he(e)}`:`${i}${he(e)}`}a(Hi,"run");function Nx(e,t){let n=on(e).length,r=`${Ee}`,o=`${Ee}`,i=[];for(let s=0;s`${c[s]??""}`).join(""),u=`${Ee}${l}`;i.push(`${o}${r}${u}`)}return i.join("")}a(Nx,"matrixRuleCells");function Ke(e){switch(e.kind){case"row":return e.children.map(Ke).join("");case"symbol":return Hi(e.text,e.italic,e.bold??!1,e.color);case"frac":{let t=e.noBar?"noBar":"bar",n=$e(e.numerator),r=$e(e.denominator);return`${Ee}${n}${r}`}case"radical":{let t=e.index?"0":"1",n=e.index?Ke(e.index):"";return`${Ee}${n}${$e(e.radicand)}`}case"supersub":{let t=$e(e.base);return e.sup&&e.sub?`${Ee}${t}${Ke(e.sub)}${Ke(e.sup)}`:e.sup?`${Ee}${t}${Ke(e.sup)}`:e.sub?`${Ee}${t}${Ke(e.sub)}`:t}case"limlow":return`${Ee}${$e(e.base)}${$e(e.lower)}`;case"limupp":return`${Ee}${$e(e.base)}${$e(e.upper)}`;case"borderbox":{let t=(e.strikeBLTR?'':"")+(e.strikeTLBR?'':"");return`${`${e.boxed?"":''}${t}${Ee}`}${$e(e.base)}`}case"groupchar":{let t=e.pos==="top"?'':'',n=e.pos==="top"?'':'';return`${`${t}${n}${Ee}`}${$e(e.base)}`}case"nary":{let t=e.sub?"":'',n=e.sup?"":'',r=`${t}${n}${Ee}`,o=e.sub?`${Ke(e.sub)}`:"",i=e.sup?`${Ke(e.sup)}`:"";return`${r}${o}${i}${$e(e.operand)}`}case"delimited":{let t=e.sepChar!==void 0?``:"",n=`${t}${Ee}`,r=e.parts.map(o=>`${$e(o)}`).join("");return`${n}${r}`}case"matrix":{let t=e.rows.map(c=>c.map(d=>`${$e(d)}`)),n=e.hlines!==void 0&&e.hlines.length>0,r=n?`${Nx(e,t)}`:"",o=t.map((c,d)=>`${n&&e.hlines.includes(d)?r:""}${c.join("")}`).join("")+(n&&e.hlines.includes(t.length)?r:""),i=on(e),s=[];for(let c of i){let d=s[s.length-1];d&&d.align===c?d.count+=1:s.push({align:c,count:1})}return`${`${s.map(c=>``).join("")}${Ee}`}${o}`}case"accent":{let t=$e(e.base);return e.bar?`${Ee}${t}`:`${Ee}${t}`}case"prescript":{let t=e.presub?`${Ke(e.presub)}`:"",n=e.presup?`${Ke(e.presup)}`:"";return`${Ee}${t}${n}${$e(e.base)}`}case"eqarr":{let t=e.rows.map(r=>`${$e(r)}`).join("");return`${`${Ee}`}${t}`}case"labeledarrow":{let t=Hi(e.chr,!1);return e.below&&(t=`${Ee}${t}${$e(e.below)}`),e.above&&(t=`${Ee}${t}${$e(e.above)}`),t}default:{let t=e;throw new Error(`Unhandled IR node: ${JSON.stringify(t)}`)}}}a(Ke,"renderIr");function $e(e){let t=Ke(e);return t.length>0?t:''}a($e,"argOrPlaceholder");var sl=`xmlns:m="${Tx}" xmlns:w="${Cx}"`;function Gi(e,t={}){let r=`${Ke(e)}`;return(t.display?`${r}`:r).replace("",``).replace(/^/,``)}a(Gi,"renderEquation");var Px=" SEQ Equation \\* ARABIC ";function al(e,t){return qp([{body:Ke(e),number:t}])}a(al,"renderNumberedEquation");function Up(e,t){let n=e.kind==="eqarr"?e.rows:[e];return qp(n.map((r,o)=>({body:Ke(r),number:t[o]??null})))}a(Up,"renderRowNumberedEquation");function qp(e){let t=e.map(r=>`${r.body}${r.number?`${Hi("#",!1)}${Ix(r.number)}`:""}`).join(""),n=`${Ee}${t}`;return`${n}`}a(qp,"numberedRows");function Ix(e){let t=a(i=>`${il}${i}`,"fieldRun"),n=e.bookmarks??[],r=n.map(i=>``).join("")+Hi(e.shown,!1)+n.map(i=>``).join(""),o=e.seq?t('')+t(`${he(Px)}`)+t('')+r+t(''):r;return`${Ee}${o}`}a(Ix,"numberMarkup");function Wp(e,t,n){let r=e.indexOf(""),o=e.lastIndexOf("");if(r<0||o`+e.slice(i,o)+``+e.slice(o)}a(Wp,"bookmarkInsideEquation");function Hp(e,t,n){let r=a(i=>`${he(i)}`,"text"),o=` REF ${he(e)} \\h `+r(t)+'';return n?`${r("(")}${o}${r(")")}`:o}a(Hp,"renderEquationRef");x();var $x="latex2word-equation",Xp="latex2word-equation-display",zp="latex2word-eqn:";var ll="latex2word:",Vp="latex2word:(source too long to store)";function Yp(e,t){if(!t?.startsWith(e))return null;let n=t.slice(e.length),r=n.lastIndexOf(":");if(r<0)return null;let o=n.slice(0,r),i=n.slice(r+1);return o.startsWith("=")?{shown:o.slice(1),bookmark:i,fixed:!0}:{shown:o,bookmark:i}}a(Yp,"readNumberTag");function Kp(e){return e===$x||e===Xp||Yp(zp,e)!==null}a(Kp,"isOwnTag");function Zp(e){return e===Xp||Yp(zp,e)!==null}a(Zp,"isDisplayTag");var ul="urn:texconverter:equations:1",So="_TeXSrc";function Gp(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}a(Gp,"escapeXmlText");function jp(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&#x([0-9a-fA-F]+);/g,(t,n)=>String.fromCodePoint(parseInt(n,16))).replace(/&#(\d+);/g,(t,n)=>String.fromCodePoint(Number(n))).replace(/&/g,"&")}a(jp,"unescapeXmlText");function Jp(e){let t=[...e].map(([n,r])=>`${Gp(r.latex)}`);return`${t.join("")}`}a(Jp,"sourceStoreXml");function Qp(e){let t=new Map;for(let n of e.matchAll(/<(?:[\w.-]+:)?eq\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:[\w.-]+:)?eq>)/g)){let r=n[1]??"",o=/\bbookmark="([^"]*)"/.exec(r)?.[1];if(o===void 0||o==="")continue;let i=/\bdisplay="1"/.test(r);t.set(jp(o),{latex:jp(n[2]??""),display:i})}return t}a(Qp,"readSourceStore");function Do(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return(/^[A-Za-z]/.test(t)?t:`L${t}`).slice(0,40)}a(Do,"bookmarkName");x();var cl=class extends Error{static{a(this,"OpcError")}constructor(t){super(t),this.name="OpcError"}};function at(e){throw new cl(e)}a(at,"fail");var Co="[Content_Types].xml",Rx=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function tf(e){let t=4294967295;for(let n=0;n>>8;return(t^4294967295)>>>0}a(tf,"crc32");var nf=67324752,rf=33639248,of=101010256,Mx=117853008,dl=22,Ox=65535+dl,_x=1,sf=0,af=8,To=4294967295,Lx=65535;function Er(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}a(Er,"view");function Fx(e){let t=Er(e),n=Math.max(0,e.length-Ox);for(let r=e.length-dl;r>=n;r--)if(t.getUint32(r,!0)===of)return r;return at("This file is not a zip archive \u2014 no end-of-central-directory record was found. A .docx is a zip; a .doc from Word 97-2003 is not, and neither is a file that only has the extension.")}a(Fx,"findEocd");function Bx(e,t){return new TextDecoder("utf-8").decode(e)}a(Bx,"decodeName");function Ux(e,t){let n=Er(e);t>=20&&n.getUint32(t-20,!0)===Mx&&at("This .docx uses the zip64 format, which TeXConverter does not read. Zip64 appears in archives over 4 GB or with more than 65,535 parts \u2014 if this is an ordinary document, re-saving it from Word will produce a plain zip.");let r=n.getUint16(t+10,!0),o=n.getUint32(t+12,!0),i=n.getUint32(t+16,!0);(r===Lx||o===To||i===To)&&at("This .docx uses the zip64 format, which TeXConverter does not read."),i+o>e.length&&at("This .docx is truncated \u2014 its central directory extends past the end of the file.");let s=[],l=i;for(let u=0;ue.length||n.getUint32(l,!0)!==rf)&&at(`This .docx is damaged \u2014 its central directory ends after ${u} of ${r} entries.`);let c=n.getUint16(l+8,!0),d=n.getUint16(l+10,!0),p=n.getUint32(l+16,!0),f=n.getUint32(l+20,!0),m=n.getUint32(l+24,!0),h=n.getUint16(l+28,!0),g=n.getUint16(l+30,!0),y=n.getUint16(l+32,!0),E=n.getUint32(l+42,!0),v=Bx(e.subarray(l+46,l+46+h),(c&2048)!==0);(c&_x)!==0&&at(`"${v}" is encrypted. TeXConverter cannot open a password-protected document \u2014 remove the protection in Word first (File > Info > Protect Document).`),(f===To||m===To||E===To)&&at(`"${v}" stores its size in a zip64 record, which TeXConverter does not read.`),s.push({name:v,method:d,flags:c,crc:p,compressedSize:f,uncompressedSize:m,localOffset:E}),l+=46+h+g+y}return s}a(Ux,"readCentralDirectory");function qx(e,t){let n=Er(e);(t.localOffset+30>e.length||n.getUint32(t.localOffset,!0)!==nf)&&at(`This .docx is damaged \u2014 "${t.name}" has no local file header where its directory entry says it should.`);let r=n.getUint16(t.localOffset+26,!0),o=n.getUint16(t.localOffset+28,!0);return t.localOffset+30+r+o}a(qx,"dataOffset");async function ji(e,t){let n=Ux(e,Fx(e)),r=new Map;for(let o of n){if(o.name.endsWith("/"))continue;let i=qx(e,o),s=i+o.compressedSize;s>e.length&&at(`This .docx is truncated \u2014 "${o.name}" extends past the end of the file.`);let l=e.subarray(i,s),u;o.method===sf?u=l.slice():o.method===af?u=await t.inflateRaw(l):at(`"${o.name}" is compressed with method ${o.method}, which TeXConverter does not read \u2014 a .docx uses only stored (0) and deflate (8).`),(u.length!==o.uncompressedSize||tf(u)!==o.crc)&&at(`"${o.name}" failed its checksum \u2014 this .docx is corrupt.`),r.set(o.name,u)}return{parts:r}}a(ji,"readPackage");function Wx(e){let t=e.getHours()<<11|e.getMinutes()<<5|Math.floor(e.getSeconds()/2)&31,n=e.getFullYear()-1980<<9|e.getMonth()+1<<5|e.getDate();return{time:t,day:n}}a(Wx,"dosDateTime");function ef(e){let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}a(ef,"concat");async function lf(e,t,n=new Date){let{time:r,day:o}=Wx(n),i=[...e.parts.keys()],s=i.includes(Co)?[Co,...i.filter(m=>m!==Co)]:i,l=[],u=[],c=0;for(let m of s){let h=e.parts.get(m),g=new TextEncoder().encode(m),y=await t.deflateRaw(h),E=y.lengthn.startsWith(t))}a(cf,"partsUnder");var pl=914400,Hx=Math.round(6.5*pl);function Gx(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length>=24&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return{width:t.getUint32(16,!1),height:t.getUint32(20,!1)};if(e.length>10&&e[0]===71&&e[1]===73&&e[2]===70)return{width:t.getUint16(6,!0),height:t.getUint16(8,!0)};if(e.length>4&&e[0]===255&&e[1]===216){let n=2;for(;n+9=208&&r<=215){n+=2;continue}let o=t.getUint16(n+2,!1);if(r>=192&&r<=207&&r!==196&&r!==200&&r!==204)return{height:t.getUint16(n+5,!1),width:t.getUint16(n+7,!1)};if(o<2)return null;n+=2+o}}return null}a(Gx,"intrinsicSize");var df={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",bmp:"image/bmp",tif:"image/tiff",tiff:"image/tiff",svg:"image/svg+xml",emf:"image/x-emf",wmf:"image/x-wmf"};function pf(e){let t=e.lastIndexOf(".");return t<0?"":e.slice(t+1).toLowerCase()}a(pf,"extensionOf");var Nt="http://schemas.openxmlformats.org/officeDocument/2006/relationships",zi=`latex2word:tikz `,ff=8e3;function jx(e){return he(e).replace(/\r/g," ").replace(/\n/g," ").replace(/\t/g," ")}a(jx,"escapeXmlAttribute");var fl=class{constructor(t,n){this.document=t;this.options=n;this.warnings=[];this.relationships=[];this.media=new Map;this.imageRelIds=new Map;this.footnoteIds=new Map;this.nextRel=1;this.imageCounter=0;this.usedLists={ordered:!1,bullet:!1};this.orderedStarts=[];this.tableIndent=0;this.sources=new Map;this.numbers=new Map;this.labelNumbers=new Map;this.rowNumbers=new Map;this.nextId=n.firstId??1,this.storeSource=n.storeSourceMetadata??!0,this.countEquations()}static{a(this,"Writer")}citationLabels(t){let n=this.options.citationLabels;return`[${t.map(o=>n?.get(o)??o).join(", ")}]`}countEquations(){let t=0;for(let n of no(this.document.blocks)){if(n.kind!=="paragraph")continue;let r=mf(n.children);if(r===null)continue;let o=r.number.rows;if(o!==void 0){let s=o.map(l=>l===null?null:l.tag??String(++t));this.rowNumbers.set(r.number,s),o.forEach((l,u)=>l?.labels.forEach(c=>this.labelNumbers.set(c,s[u])));continue}let i=r.number.tag??String(++t);this.numbers.set(r.number,i);for(let s of r.labels)this.labelNumbers.set(s,i)}}displayEquationParagraph(t,n,r=""){let o=this.numberedParagraph(t,n,r);if(o!==null)return o;let i=t.filter(l=>l.kind!=="text"||l.text.trim()!==""),s=i[0];return i.length!==1||s?.kind!=="math"||!s.display?null:this.paragraph(r+this.withSource(Gi(s.ir,{display:!0}),s.source),n)}continuationMarker(){let t=this.nextId++;return``}withSource(t,n){if(!this.storeSource||n===void 0)return t;let r=this.nextId++,o=`${So}${r}`;return this.sources.set(o,{latex:n,display:!0}),Wp(t,r,o)}numberedParagraph(t,n,r=""){let o=mf(t);if(o===null)return null;let{math:i,number:s,labels:l}=o;if(s.rows!==void 0){let p=this.rowNumbers.get(s)??[],f=s.rows.map((h,g)=>{if(h===null)return null;let y=h.labels.map(E=>({id:this.nextId++,name:Do(E)}));return y.length===0&&y.push({id:this.nextId++,name:`_TeXEq${this.nextId}`}),{shown:p[g]??"?",seq:h.tag===void 0,bookmarks:y}}),m=i.ir.kind==="row"&&i.ir.children.length===1?i.ir.children[0]:i.ir;return this.paragraph(r+this.withSource(Up(m,f),i.source),n)}let u=l.map(p=>({id:this.nextId++,name:Do(p)}));u.length===0&&u.push({id:this.nextId++,name:`_TeXEq${this.nextId}`});let c=this.numbers.get(s)??"?",d=al(i.ir,{shown:c,seq:s.tag===void 0,bookmarks:u});return this.paragraph(r+this.withSource(d,i.source),n)}relId(t,n,r=!1){let o=`rId${this.nextRel++}`;return this.relationships.push(r?{id:o,type:t,target:n,external:r}:{id:o,type:t,target:n}),o}inlines(t){return t.map(n=>this.inlineOne(n)).join("")}inlineOne(t){switch(t.kind){case"text":return this.textRun(t);case"math":{let n=Gi(t.ir,{display:t.display});return this.storeSource?Xx(n,t.source,t.display):n}case"link":return`${this.inlines(t.children)}`;case"image":return this.image(t);case"break":return t.variant==="page"?'':"";case"footnoteref":{let n=this.footnoteIds.get(t.id);return n===void 0?"":``}case"citation":return this.textRun({kind:"text",text:this.citationLabels(t.keys)});case"label":{let n=this.nextId++;return``}case"ref":return this.refField(t.id,t.wrap==="parentheses");case"eqnumber":return"";case"rule":return"";case"fill":return'';case"blank":return`${"\xA0".repeat(Math.max(4,Math.round(t.widthCm*n2)))}`}}textRun(t){let n=[];t.bold===!0&&n.push(""),t.italic===!0&&n.push(""),t.underline===!0&&n.push(''),t.script==="sub"&&n.push(''),t.script==="super"&&n.push('');let r=n.length>0?`${n.join("")}`:"",i=t.text.split(" ").map((s,l)=>(l===0?"":"")+(s===""?"":`${he(s)}`)).join("");return`${r}${i}`}refField(t,n){return Hp(Do(t),this.labelNumbers.get(t)??t,n)}image(t){let n=this.document.images.get(t.part);if(n===void 0)return this.warnings.push(`The image "${t.part}" was referenced but its file was not available, so it was left out.`),"";let r=pf(t.part)||"png";if(df[r]===void 0)return this.warnings.push(`The image "${t.part}" is a .${r}, which Word cannot embed, so it was left out.`),"";r==="svg"&&this.warnings.push(`The image "${t.part}" is an SVG. It is embedded correctly for the package format, but Word needs a raster fallback alongside it, which this build does not yet write \u2014 expect a placeholder where the picture should be.`);let o=this.imageRelIds.get(t.part),i;o===void 0&&(i=`media/${`image${++this.imageCounter}.${r}`}`,this.media.set(`word/${i}`,n),o=this.relId(`${Nt}/image`,i),this.imageRelIds.set(t.part,o));let{cx:s,cy:l}=this.extentFor(t,n),u=this.nextId++,c=t.alt??"",d=this.figureSource(t);return``}figureSource(t){if(t.source===void 0)return null;let n=`${zi}${t.source.tex}`;return n.length>ff?(this.warnings.push(`A figure's source is ${n.length} characters, beyond the ${ff} an attribute can safely hold, so the picture was written without it and cannot be edited as LaTeX after a round trip.`),null):n}extentFor(t,n){let r=Gx(n),o=r===null||r.width===0?4/3:r.width/r.height;if(t.widthEmu!==void 0&&t.heightEmu!==void 0)return{cx:t.widthEmu,cy:t.heightEmu};if(t.widthEmu!==void 0)return{cx:t.widthEmu,cy:Math.round(t.widthEmu/o)};if(t.heightEmu!==void 0)return{cx:Math.round(t.heightEmu*o),cy:t.heightEmu};if(r!==null){let s=Math.min(Math.round(r.width/96*pl),Hx);return{cx:s,cy:Math.round(s/o)}}this.warnings.push("An image did not state its size and is not a format whose dimensions could be read; it was placed at four inches wide.");let i=4*pl;return{cx:i,cy:Math.round(i/o)}}blocks(t){return t.map(n=>this.block(n)).join("")}block(t){switch(t.kind){case"heading":{let n=Math.min(Math.max(t.level,1),9),r=t.numbered===!1?this.nextId++:0,o=t.numbered===!1?``:"";return this.paragraph(o+this.inlines(t.children),``)}case"paragraph":{if(t.children.some(r=>r.kind==="rule"))return this.ruledParagraphs(t);let n=[];return t.align!==void 0&&t.align!=="left"&&n.push(``),zx(t.children).map((r,o)=>{let i=o>0||t.continues===!0?this.continuationMarker():"";return this.displayEquationParagraph(r,n.join(""),i)??this.paragraph(i+this.inlines(r),n.join(""))}).join("")}case"list":return this.list(t.items,t.ordered,t.start,t.label);case"table":return this.table(t)}}ruledParagraphs(t){let n=t.align!==void 0&&t.align!=="left"?``:"",r='',o=[],i=[],s=a(u=>{let c=[...u];for(;c.length>0&&(c[c.length-1].kind==="break"||c[c.length-1].kind==="text"&&c[c.length-1].text.trim()==="");)c.pop();for(;c.length>0&&(c[0].kind==="break"||c[0].kind==="text"&&c[0].text.trim()==="");)c.shift();return c},"trimBreaks");for(let u of t.children){if(u.kind!=="rule"){i.push(u);continue}o.push(this.paragraph(this.inlines(s(i)),r+n)),i=[]}let l=s(i);return l.length>0&&o.push(this.paragraph(this.inlines(l),n)),o.join("")}paragraph(t,n=""){return`${n===""?"":`${n}`}${t}`}list(t,n,r,o){n?this.usedLists.ordered=!0:this.usedLists.bullet=!0;let i=1;return n&&(this.orderedStarts.push(o?{start:r??1,label:o}:{start:r??1}),i=2+this.orderedStarts.length),t.map(s=>{let l=Math.min(s.level,8),u=s.label?``:``,c=this.tableIndent;this.tableIndent=720*(l+1);let d=this.blocks(s.blocks??[]);if(this.tableIndent=c,s.label&&!s.label.length&&!s.children.length)return d;let p=s.label?.length?`${this.inlines(s.label)}`:"";return this.paragraph(p+this.inlines(s.children),u)+d}).join("")}table(t){let n=Math.max(1,...t.rows.map(c=>c.cells.reduce((d,p)=>d+p.span,0))),r=Math.floor(9360/n),o=t.booktabs===!0,i=a(c=>t.bordered?``:o&&(c==="top"||c==="bottom")?``:``,"border"),s=''+(t.align==="center"?'':"")+(this.tableIndent>0&&t.align!=="center"?``:"")+`${["top","left","bottom","right","insideH","insideV"].map(i).join("")}`,l=`${``.repeat(n)}`,u=t.rows.map(c=>{let d=c.header?"":"",p=c.cells.map(f=>{let m=f.span>1?``:"",h=f.blocks.length===0?this.paragraph(""):this.blocks(f.blocks),g=h.includes("")||h.includes("':"";return`${m}${y}${g}`}).join("");return`${d}${p}`}).join("");return`${s}${l}${u}${this.paragraph("")}`}documentPart(){let t=1;for(let p of this.document.footnotes.keys())this.footnoteIds.set(p,++t);let n=this.blocks(this.document.blocks),o=this.document.watermark?.trim()?``:"",i=this.document.page?.footer?``:"",s=this.document.page,[l,u]=bf[s?.size??"a4"],c=Math.round((s?.marginCm??2)*567),d=`${o}${i}`;return lt(`${n}${d}`)}footnotesPart(){if(this.document.footnotes.size===0)return null;let t='',n=[...this.document.footnotes].map(([r,o])=>{let i=this.footnoteIds.get(r),s=this.blocks(o)||this.paragraph("");return`${s}`}).join("");return lt(`${t}${n}`)}relationshipsPart(){let t=this.relationships.map(n=>``).join("");return lt(`${t}`)}contentTypesPart(t){let n=new Set(["rels","xml"]);for(let i of this.media.keys())n.add(pf(i));let r=[...n].map(i=>{let s=i==="rels"?"application/vnd.openxmlformats-package.relationships+xml":i==="xml"?"application/xml":df[i];return s===void 0?"":``}).join(""),o=['','',...t].join("");return lt(`${r}${o}`)}write(){let t=this.documentPart(),n=this.footnotesPart();this.relId(`${Nt}/styles`,"styles.xml");let r=[];(this.usedLists.ordered||this.usedLists.bullet)&&(this.relId(`${Nt}/numbering`,"numbering.xml"),r.push('')),n!==null&&(this.relId(`${Nt}/footnotes`,"footnotes.xml"),r.push(''));let o=this.document.watermark?.trim();o&&r.push('');let i=this.document.page?.footer;i&&r.push(''),this.sources.size>0&&(this.relId(`${Nt}/customXml`,"../customXml/item1.xml"),r.push(''));let s=new Map,l=a((u,c)=>{s.set(u,new TextEncoder().encode(c))},"put");l(Co,this.contentTypesPart(r)),l("_rels/.rels",e2),l("word/document.xml",t),l("word/_rels/document.xml.rels",this.relationshipsPart()),l("word/styles.xml",Yx(this.document.page)),(this.usedLists.ordered||this.usedLists.bullet)&&l("word/numbering.xml",r2(this.orderedStarts)),n!==null&&l("word/footnotes.xml",n),o&&l("word/header1.xml",Zx(o)),i&&l("word/footer1.xml",Kx(i,this.document.page)),this.sources.size>0&&(l("customXml/item1.xml",lt(Jp(this.sources))),l("customXml/itemProps1.xml",Jx),l("customXml/_rels/item1.xml.rels",Qx));for(let[u,c]of this.media)s.set(u,c);return{package:{parts:s},warnings:this.warnings}}};function Xx(e,t,n){return t===void 0||t.length>240?e:`${e}`}a(Xx,"wrapWithSource");var ml="_TeXCont",hl="_TeXStar";function zx(e){let t=a(i=>i.kind==="text"&&i.text.trim()==="","blank"),n=[],r=[],o=a(()=>{r.some(i=>!t(i))&&n.push(r),r=[]},"flush");for(let i=0;i0&&(r[l-1].kind==="label"||t(r[l-1]));)l--;let u=r.splice(l).filter(d=>d.kind==="label");o();let c=[...u,s];for(;i+1i.kind!=="text"||i.text.trim()!==""),n=t.find(i=>i.kind==="eqnumber");if(n===void 0)return null;let r=t.filter(i=>i.kind!=="eqnumber"&&i.kind!=="label");if(r.length!==1||r[0].kind!=="math"||!r[0].display)return null;let o=t.flatMap(i=>i.kind==="label"?[i.id]:[]);return{math:r[0],number:n,labels:o}}a(mf,"numberedEquation");var Xi=['xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"','xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"','xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"','xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"','xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"','xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"'].join(" "),bf={a4:[11906,16838],letter:[12240,15840],legal:[12240,20160]},Vx={serif:"Times New Roman",sans:"Arial"};function Yx(e){if(!e?.font&&!e?.fontSizePt)return hf;let t=e.font?Vx[e.font]:"Calibri",n=Math.round((e.fontSizePt??11)*2);return hf.replace('',``)}a(Yx,"stylesFor");function Kx(e,t){let[n]=bf[t?.size??"a4"],r=n-2*Math.round((t?.marginCm??2)*567),o=a(l=>`${he(l)}`,"run"),i=a(l=>`1`,"field"),s=e.pageNumbers?`${o("Page ")}${i("PAGE")}${o(" of ")}${i("NUMPAGES")}`:"";return lt(`${e.text?o(e.text):""}${s}`)}a(Kx,"pageFooter");var gl="PowerPlusWaterMarkObject";function Zx(e){let n=`${["sum #0 0 10800","prod #0 2 1","sum 21600 0 @1","sum 0 0 @2","sum 21600 0 @3","if @0 @3 0","if @0 21600 @1","if @0 0 @2","if @0 @4 21600","mid @5 @6","mid @8 @5","mid @7 @8","mid @6 @7","sum @6 0 @5"].map(s=>``).join("")}`,r=Math.round(Math.max(40,Math.min(120,900/Math.max(1,e.length)))),o=``,i=`${Xi} xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w10="urn:schemas-microsoft-com:office:word"`;return lt(`${n}${o}`)}a(Zx,"watermarkHeader");function lt(e){return` ${e}`}a(lt,"xmlDeclaration");var Jx=lt(''),Qx=lt(``),e2=lt(``),hf=lt(''+[1,2,3,4,5,6,7,8,9].map(e=>``).join("")+''),gf=[{text:"\uF0B7",font:"Symbol"},{text:"o",font:"Courier New"},{text:"\uF0A7",font:"Wingdings"}],yf=["decimal","lowerLetter","lowerRoman"],t2=lt(''+[{abstract:1,bullet:!0},{abstract:2,bullet:!1}].map(({abstract:e,bullet:t})=>``+Array.from({length:9},(n,r)=>{let o=720*(r+1),i=gf[r%gf.length];return``+(t?``:"")+""}).join("")+"").join("")+''),n2=11.3;function r2(e){let t=e.map(({start:n,label:r},o)=>{let i=r?`${r.bold?"":""}`:"";return`${i}`}).join("");return t2.replace("",`${t}`)}a(r2,"numbering");function wf(e,t={}){return new fl(e,t).write()}a(wf,"documentToDocx");x();var I="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Vi="http://schemas.openxmlformats.org/officeDocument/2006/math",kf="http://schemas.openxmlformats.org/officeDocument/2006/relationships",o2="http://schemas.openxmlformats.org/drawingml/2006/main";function Ef(e){return e&&e.nodeType===1}a(Ef,"isElement");function ge(e){let t=[];for(let n=0;nY(r,t,n))??null}a(pe,"firstChild");function No(e,t,n){for(let r of ge(e)){if(Y(r,t,n))return r;let o=No(r,t,n);if(o!==null)return o}return null}a(No,"firstDescendant");function J(e,t,n){if(e===null)return null;let r=e.attributes;if(!r)return null;for(let o=0;oY(c,I,"lvl")&&(J(c,I,"ilvl")??"0")==="0"),l=Number(s===void 0?"1":fn(s,"start")??"1"),u=J(i,I,"abstractNumId");u!==null&&Number.isFinite(l)&&o.set(u,l)}for(let i of ge(r)){if(!Y(i,I,"num"))continue;let s=J(i,I,"numId");if(s===null)continue;let l=o.get(J(pe(i,I,"abstractNumId"),I,"val")??"")??1;for(let u of ge(i)){if(!Y(u,I,"lvlOverride")||(J(u,I,"ilvl")??"0")!=="0")continue;let c=fn(u,"startOverride");c!==null&&Number.isFinite(Number(c))&&(l=Number(c))}t.set(s,l)}return t}a(s2,"numberingStarts");function a2(e){let t=new Map,n=Gt(e,"word/numbering.xml");if(n===null)return t;let r;try{r=In(n)}catch{return t}let o=r.documentElement;if(o===null)return t;let i=new Map,s=new Map;for(let l of ge(o))if(Y(l,I,"abstractNum")){let u=J(l,I,"abstractNumId");if(u===null)continue;let c=new Map;for(let d of ge(l)){if(!Y(d,I,"lvl"))continue;let p=Number(J(d,I,"ilvl")??"0");c.set(p,(fn(d,"numFmt")??"decimal")!=="bullet")}i.set(u,c)}else if(Y(l,I,"num")){let u=J(l,I,"numId"),c=J(pe(l,I,"abstractNumId"),I,"val");u!==null&&c!==null&&s.set(u,c)}for(let[l,u]of s){let c=i.get(u);c!==void 0&&t.set(l,c)}return t}a(a2,"numberingFormats");function l2(e,t){let n=new Map,r=t.lastIndexOf("/"),o=`${t.slice(0,r)}/_rels/${t.slice(r+1)}.rels`,i=Gt(e,o);if(i===null)return n;let s;try{s=In(i)}catch{return n}let l=s.documentElement;if(l===null)return n;for(let u of ge(l)){let c=J(u,null,"Id"),d=J(u,null,"Target");c!==null&&d!==null&&n.set(c,d)}return n}a(l2,"relationships");function Af(e,t){if(/^[a-z]+:/i.test(e))return e;if(e.startsWith("/"))return e.slice(1);let r=`${t.slice(0,t.lastIndexOf("/"))}/${e}`.split("/"),o=[];for(let i of r)i==="."||i===""||(i===".."?o.pop():o.push(i));return o.join("/")}a(Af,"resolveTarget");function u2(e){let t=new Map,n=new Set,r=null,o=!1,i=a((s,l)=>{for(let u of ge(s))if(Y(u,I,"bookmarkStart")){let c=J(u,I,"name")??"";c.startsWith(So)?r=c:c.startsWith(ml)&&(l!==null?n.add(l):o=!0)}else if(Y(u,Vi,"oMath")){let c=Sf(u)??r;c!==null&&t.set(u,c),r=null}else Y(u,I,"p")?(o&&n.add(u),o=!1,i(u,u),r=null):i(u,l)},"walk");return i(e,null),{sources:t,continuing:n}}a(u2,"markersIn");function c2(e){let t=new Map;for(let n of cf(e,"customXml/")){if(!/^customXml\/item\d+\.xml$/.test(n))continue;let r=Gt(e,n);if(!(r===null||!r.includes(ul)))for(let[o,i]of Qp(r))t.set(o,i)}return t}a(c2,"storedSources");function Sf(e){for(let t of ge(e)){if(Y(t,I,"bookmarkStart")){let r=J(t,I,"name");if(r!==null&&r.startsWith(So))return r}let n=Sf(t);if(n!==null)return n}return null}a(Sf,"sourceBookmarkOf");function d2(e){let t=new Set;for(let n of e.matchAll(/REF\s+([A-Za-z0-9_]+)/g))t.add(n[1]);return t}a(d2,"referencedBookmarks");function p2(e){let t=[];for(let n of e){let r=t[t.length-1];n.kind==="text"&&r!==void 0&&r.kind==="text"&&r.bold===n.bold&&r.italic===n.italic&&r.underline===n.underline&&r.script===n.script?t[t.length-1]={...r,text:r.text+n.text}:t.push(n)}return t.filter(n=>n.kind!=="text"||n.text!=="")}a(p2,"mergeText");function f2(e){let t=pe(e,I,"rPr"),n=Ki(t,"b"),r=Ki(t,"i"),o=t!==null&&pe(t,I,"u")!==null&&fn(t,"u")!=="none",i=J(t===null?null:pe(t,I,"vertAlign"),I,"val"),s=i==="subscript"?"sub":i==="superscript"?"super":void 0,l=a(c=>{let d={kind:"text",text:c};return n&&(d.bold=!0),r&&(d.italic=!0),o&&(d.underline=!0),s!==void 0&&(d.script=s),d},"style"),u=[];for(let c of ge(e))if(Y(c,I,"t"))u.push(...g2(yl(c),o,l));else if(Y(c,I,"ptab")&&J(c,I,"alignment")==="right")u.push({kind:"fill"});else if(Y(c,I,"tab"))u.push(l(" "));else if(Y(c,I,"noBreakHyphen"))u.push(l("-"));else if(Y(c,I,"br"))u.push({kind:"break",variant:J(c,I,"type")==="page"?"page":"line"});else if(Y(c,I,"footnoteReference")){let d=J(c,I,"id");d!==null&&u.push({kind:"footnoteref",id:d})}return u}a(f2,"readRun");var m2=11.3,h2=5.2,xf=a(e=>Math.max(.5,Math.round(e*2)/2),"halfCm");function g2(e,t,n){if(t&&e.length>=3&&/^[\s ]+$/.test(e))return[{kind:"blank",widthCm:xf(e.length/m2)}];if(!/_{4,}/.test(e))return[n(e)];let r=[],o=0;for(let i of e.matchAll(/_{4,}/g))i.index>o&&r.push(n(e.slice(o,i.index))),r.push({kind:"blank",widthCm:xf(i[0].length/h2)}),o=i.index+i[0].length;return oY(l,I,"sdt")),i=t.markers.sources.get(e)??null,s=(o===void 0?null:Df(o))??(i===null?void 0:t.sources.get(i))??n;try{let l=Sp(e),u=vp(e)||s?.display===!0,c={kind:"math",ir:l,display:u};s!==null&&(c.source=s.latex);let d=a(h=>h.filter(g=>!g.startsWith("_")||t.referencedBookmarks.has(g)),"kept"),p=Ap(e);if(p!==null&&p.length>1){let h=p.map(g=>g===null?null:g.seq?{labels:d(g.bookmarks)}:{tag:g.text,labels:d(g.bookmarks)});return[c,{kind:"eqnumber",rows:h}]}let f=Ep(e);return f===null?[c]:[...d(f.bookmarks).map(h=>({kind:"label",id:h})),c,f.seq?{kind:"eqnumber"}:{kind:"eqnumber",tag:f.text}]}catch(l){if(!(l instanceof tt)||t.onUnsupported==="throw")throw l;return t.skipped.push({index:r,reason:l.message}),[]}}a(vf,"readMath");function b2(e){for(let t=1;t+1t.kind!=="text"||t.text!=="")}a(b2,"joinEquationRefs");function w2(e,t){let n=a(o=>{for(let i of ge(o))if(Y(i,I,"fldChar"))return J(i,I,"fldCharType");return null},"fldChar");if(!Y(e[t],I,"r")||n(e[t])!=="begin")return null;let r="";for(let o=t+1;o=1)return{block:ge(e).some(h=>Y(h,I,"bookmarkStart")&&(J(h,I,"name")??"").startsWith(hl))?{kind:"heading",level:i,children:r,numbered:!1}:{kind:"heading",level:i,children:r}};let s=n===null?null:pe(n,I,"numPr");if(s!==null){let m=J(pe(s,I,"numId"),I,"val"),h=Number(J(pe(s,I,"ilvl"),I,"val")??"0");if(m!==null&&m!=="0"){let g=t.numbering.get(m)?.get(h)??!0;return{block:{kind:"paragraph",children:r},listKey:m,listLevel:h,listOrdered:g}}}let l=n===null?null:fn(n,"jc"),u=n===null?null:pe(n,I,"pBdr"),c=u===null?null:pe(u,I,"bottom"),d=c!==null&&!["none","nil"].includes(J(c,I,"val")??"none"),p=r.some(m=>m.kind!=="text"||m.text.trim()!==""),f={kind:"paragraph",children:d?p?[...r,{kind:"break",variant:"line"},{kind:"rule"}]:[{kind:"rule"}]:r};return(l==="center"||l==="right"||l==="left")&&(f.align=l),t.markers.continuing.has(e)&&(f.continues=!0),{block:f}}a(x2,"readParagraph");function v2(e,t){let n=pe(e,I,"tblPr"),r=n===null?null:pe(n,I,"tblBorders"),o=a(p=>p!==null&&!["none","nil"].includes(J(p,I,"val")??"none"),"drawn"),i=a(p=>o(r===null?null:pe(r,I,p)),"side"),s=i("top")&&i("bottom")&&!i("insideH")&&!i("insideV")&&!i("left")&&!i("right"),l=!s&&r!==null&&ge(r).some(p=>J(p,I,"val")!=="none"&&J(p,I,"val")!=="nil"),u=n!==null&&fn(n,"jc")==="center",c=[];for(let p of ge(e)){if(!Y(p,I,"tr"))continue;let f=[];for(let g of ge(p)){if(!Y(g,I,"tc"))continue;let y=pe(g,I,"tcPr"),E=Number(J(y===null?null:pe(y,I,"gridSpan"),I,"val")??"1");f.push({blocks:Zi(g,t),span:Number.isFinite(E)&&E>0?E:1})}let m=pe(p,I,"trPr"),h=ge(p).filter(g=>Y(g,I,"tc")).every(g=>{let y=No(pe(g,I,"tcPr")??g,I,"tcBorders");return o(y===null?null:pe(y,I,"bottom"))});c.push(s&&h&&f.length>0?{cells:f,header:Ki(m,"tblHeader"),ruleBelow:!0}:{cells:f,header:Ki(m,"tblHeader")})}let d={kind:"table",rows:c,bordered:l};return s&&(d.booktabs=!0),u&&(d.align="center"),d}a(v2,"readTable");function k2(e,t){let n=[],r=null,o=a(()=>{if(r===null)return;let i=t.listCounts.get(r.key)??0,s=(t.numberingStarts.get(r.key)??1)+i;t.listCounts.set(r.key,i+r.items.filter(l=>l.level===0).length),n.push(r.ordered&&s!==1?{kind:"list",ordered:!0,items:r.items,start:s}:{kind:"list",ordered:r.ordered,items:r.items}),r=null},"flush");for(let i=0;i0){let c=r.items.length-1,d=r.items[c];r.items[c]={...d,blocks:[...d.blocks??[],s.block]};continue}o(),n.push(s.block);continue}let u=s.block;r!==null&&r.key!==s.listKey&&o(),r===null&&(r={key:s.listKey,ordered:s.listOrdered===!0,items:[]}),r.items.push({level:s.listLevel??0,children:u.children})}return o(),n}a(k2,"gatherLists");function Zi(e,t){let n=[];for(let r of ge(e))if(Y(r,I,"p"))n.push(x2(r,t));else if(Y(r,I,"tbl"))n.push({block:v2(r,t)});else if(Y(r,I,"sdt")){let o=pe(r,I,"sdtContent");if(o!==null)for(let i of Zi(o,t))n.push({block:i})}return k2(n,t)}a(Zi,"readBlocks");function E2(e,t){let n=new Map,r=Gt(e,"word/footnotes.xml");if(r===null)return n;let o;try{o=In(r)}catch{return n}let i=o.documentElement;if(i===null)return n;for(let s of ge(i)){if(!Y(s,I,"footnote"))continue;let l=J(s,I,"id");l===null||Number(l)<=0||n.set(l,Zi(s,t))}return n}a(E2,"readFootnotes");function A2(e){for(let t of e.parts.keys()){if(!/^word\/header\d*\.xml$/.test(t))continue;let n=Gt(e,t)??"",r=new RegExp(`]*id="${gl}[^"]*"[\\s\\S]*?]*\\bstring="([^"]*)"`).exec(n);if(r!==null){let o=r[1].replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").trim();if(o!=="")return o}}return null}a(A2,"readWatermark");function Tf(e,t={}){let n="word/document.xml",r=uf(e,n),i=In(r).documentElement;if(i===null)throw new tt("word/document.xml is empty.");let s=pe(i,I,"body");if(s===null)throw new tt("word/document.xml has no , so there is nothing to convert.");let l={pkg:e,headings:i2(e),numbering:a2(e),numberingStarts:s2(e),listCounts:new Map,rels:l2(e,n),relsFrom:n,images:new Map,skipped:[],onUnsupported:t.onUnsupportedEquation??"skip",referencedBookmarks:d2(r),sources:c2(e),markers:u2(s),equationIndex:0},u=Zi(s,l),c=E2(e,l),d=A2(e);return{document:{blocks:u,footnotes:c,images:l.images,...d===null?{}:{watermark:d}},skipped:l.skipped}}a(Tf,"docxToDocument");x();x();x();x();var S2=["equation*","equation","align*","align","gather*","gather"];function D2(e,t){if(!e.startsWith("\\begin{",t))return null;for(let n of S2){let r=`\\begin{${n}}`;if(e.startsWith(r,t))return{opener:r,name:n}}return null}a(D2,"matchEnvOpener");function T2(e,t,n){let r=e.indexOf(t,n);for(;r!==-1&&e[r-1]==="\\";)r=e.indexOf(t,r+1);return r}a(T2,"indexOfUnescaped");function C2(e,t,n){let r=T2(e,"$",t+1);if(r===-1)return-1;let o=e.slice(t+1,r);if(o.length===0)return-1;if(n==="always")return r;let i=o[0],s=o[o.length-1];return/\s/.test(i)||/\s/.test(s)||/\d/.test(i)&&!/^\d+(?:\.\d+)?$/.test(o)&&!/\d[A-Za-z\\]|[=^_\\{}]/.test(o)?-1:r}a(C2,"findSingleDollarClose");function bl(e,t={}){let n=t.singleDollarMode??"smart",r=[],o=e.length,i=0;for(;i0){let c=l+2;r.push({start:i,end:c,matchedText:e.slice(i,c),latex:u.trim(),display:!0,delimiter:"$$"}),i=c;continue}}i+=2;continue}if(e.startsWith("\\[",i)){let l=e.indexOf("\\]",i+2);if(l!==-1){let u=e.slice(i+2,l);if(u.trim().length>0){let c=l+2;r.push({start:i,end:c,matchedText:e.slice(i,c),latex:u.trim(),display:!0,delimiter:"\\["}),i=c;continue}}i+=2;continue}if(e.startsWith("\\(",i)){let l=e.indexOf("\\)",i+2);if(l!==-1){let u=e.slice(i+2,l);if(u.trim().length>0){let c=l+2;r.push({start:i,end:c,matchedText:e.slice(i,c),latex:u.trim(),display:!1,delimiter:"\\("}),i=c;continue}}i+=2;continue}if(e[i]==="$"&&n!=="never"){let l=C2(e,i,n);if(l!==-1){let u=l+1,c=e.slice(i+1,l);r.push({start:i,end:u,matchedText:e.slice(i,u),latex:c.trim(),display:!1,delimiter:"$"}),i=u;continue}i+=1;continue}i+=1}return r}a(bl,"findLatexSpans");var wl=class{constructor(t){this.singleDollarMode=t;this.converted=0;this.skippedAsCurrency=0;this.rejected=[]}static{a(this,"Detector")}countCurrencySkips(t,n){if(this.singleDollarMode!=="smart")return 0;let r=new Set(n.map(i=>i.start)),o=0;for(let i of bl(t,{singleDollarMode:"always"}))if(!r.has(i.start))try{H(Qt(i.latex)),o++}catch{}return o}splitText(t){let n=bl(t.text,{singleDollarMode:this.singleDollarMode});if(this.skippedAsCurrency+=this.countCurrencySkips(t.text,n),n.length===0)return[t];let r=[],o=0;for(let i of n){let s;try{s=H(Qt(i.latex))}catch(l){this.rejected.push({latex:i.latex,reason:l instanceof Error?l.message:String(l)});continue}i.start>o&&r.push({...t,text:t.text.slice(o,i.start)}),r.push({kind:"math",ir:s,display:i.display,source:i.latex}),o=i.end,this.converted++}return o===0?[t]:(o{switch(n.kind){case"paragraph":case"heading":return{...n,children:this.inlines(n.children)};case"list":return{...n,items:n.items.map(r=>({...r,children:this.inlines(r.children),...r.blocks===void 0?{}:{blocks:this.blocks(r.blocks)}}))};case"table":return{...n,rows:n.rows.map(r=>({...r,cells:r.cells.map(o=>({...o,blocks:this.blocks(o.blocks)}))}))}}})}};function Cf(e,t={}){if(t.enabled===!1)return{document:e,converted:0,rejected:[],skippedAsCurrency:0};let n=new wl(t.singleDollarMode??"smart"),r=n.blocks(e.blocks),o=new Map;for(let[i,s]of e.footnotes)o.set(i,n.blocks(s));return{document:{...e,blocks:r,footnotes:o},converted:n.converted,rejected:n.rejected,skippedAsCurrency:n.skippedAsCurrency}}a(Cf,"detectLatexInText");async function Qi(e,t,n={}){let r=await ji(e,t),{document:o,skipped:i}=Tf(r),s=Cf(o,n.detectLatex),l=s.document,u=Bp(l,n);return{tex:u.tex,images:new Map(u.images),equationsConverted:[...ki(l.blocks)].filter(c=>c.kind==="math").length,equationsFromText:s.converted,equationsSkipped:i,rejectedText:s.rejected,skippedAsCurrency:s.skippedAsCurrency,warnings:u.warnings,blocks:l.blocks.length}}a(Qi,"docxToTex");var N2=["",".png",".jpg",".jpeg",".pdf",".eps",".gif",".svg"];function P2(e,t,n){if(t!==void 0)for(let r of ki(e.blocks)){if(r.kind!=="image"||e.images.has(r.part))continue;let o=null;for(let i of N2)if(o=t(r.part+i),o!==null)break;o===null?n.push(`The image "${r.part}" could not be found, so it was left out.`):e.images.set(r.part,o)}}a(P2,"attachImages");function I2(e,t,n){if(e.length===0)return[];let r=[{kind:"heading",level:1,children:[{kind:"text",text:n}]}];return e.forEach((o,i)=>{r.push({kind:"paragraph",children:[{kind:"text",text:`[${i+1}] ${dd(o,t)}`}]})}),r}a(I2,"bibliographyBlocks");function es(e){return[...e.matchAll(/\\(?:bibliography|addbibresource)\{([^}]*)\}/g)].flatMap(t=>t[1].split(",")).map(t=>t.trim()).filter(t=>t!=="")}a(es,"bibliographyNames");async function ts(e,t,n={}){let r=ud(e,n),o=[...r.warnings];P2(r.document,n.resolveImage,o);let i=(n.bibSources??[]).flatMap(d=>cd(d)),s=pd(i,r.citations,n.bibStyle??"plain");for(let d of s.missing)o.push(`The citation "${d}" has no entry in the bibliography, so its key was printed instead of a number.`);let l=n.mathAsLatex===!0,u={...r.document,footnotes:l?new Map([...r.document.footnotes].map(([d,p])=>[d,Ji(p)])):r.document.footnotes,blocks:[...l?Ji(r.document.blocks):r.document.blocks,...I2(s.entries,n.bibStyle??"plain",n.bibliographyTitle??"References")]},c=wf(u,{...n,citationLabels:s.labels});return o.push(...c.warnings),{bytes:await lf(c.package,t),blocks:u.blocks.length,equations:[...ki(u.blocks)].filter(d=>d.kind==="math").length,images:u.images.size,citations:r.citations.length,missingCitations:s.missing,warnings:o}}a(ts,"texToDocx");function Ji(e){let t=a(n=>n.flatMap(r=>{if(r.kind==="math"){let o=(r.source??xe(r.ir)).trim();return[{kind:"text",text:r.display?`$$${o}$$`:`$${o}$`}]}return r.kind==="eqnumber"?[]:r.kind==="link"?[{...r,children:t(r.children)}]:[r]}),"inlines");return e.map(n=>{switch(n.kind){case"paragraph":case"heading":return{...n,children:t(n.children)};case"list":return{...n,items:n.items.map(r=>({...r,children:t(r.children),...r.blocks?{blocks:Ji(r.blocks)}:{}}))};case"table":return{...n,rows:n.rows.map(r=>({...r,cells:r.cells.map(o=>({...o,blocks:Ji(o.blocks)}))}))}}})}a(Ji,"mathAsLatexText");function ns(e,t={}){return ts(e,It,t)}a(ns,"convertTex");x();import{spawn as zl,spawnSync as mE}from"node:child_process";import{existsSync as Rr,mkdirSync as Km,readFileSync as Zm,rmSync as hE,writeFileSync as Jm}from"node:fs";import{homedir as gE}from"node:os";import{basename as yE,dirname as _n,join as Vt,resolve as vs}from"node:path";x();var $2=Object.freeze({environment:"development",baseUrl:"https://localhost:3000",licenseServerUrl:null,licensePublicKeys:{},isProduction:!1,debug:!0}),fe=typeof $=="object"&&$!==null?Object.freeze($):$2;x();import{createServer as zv}from"node:http";import{createReadStream as Vv}from"node:fs";import{pipeline as Yv}from"node:stream/promises";import{randomBytes as Il,timingSafeEqual as Kv}from"node:crypto";import{mkdir as um,writeFile as cs,access as Zv}from"node:fs/promises";import{dirname as Jv,join as Mo,resolve as $l,sep as cm}from"node:path";x();import{posix as Po}from"node:path";function rs(e){let t=e.replace(/\\/g,"/").split("/").filter(n=>n!==""&&n!==".");return t.length===0||t.includes("..")?null:t.join("/")}a(rs,"normalizeDropPath");var R2=new TextDecoder("utf-8"),xl=a(e=>R2.decode(e),"decode"),Nf=a(e=>Po.basename(e).replace(/\.[^.]*$/,""),"stem"),mn=a((e,t)=>`${e} ${t}${e===1?"":"s"}`,"plural"),M2=/\.docx$/i,O2=/\.(tex|latex)$/i,Pf=/\.bib$/i,_2=a(e=>Po.basename(e).startsWith("~$"),"isLockFile");async function If(e,t={}){let n=new Map;for(let f of e){let m=rs(f.path);m!==null&&!_2(m)&&n.set(m,f.bytes)}let r=new Map([...n.keys()].map(f=>[f.toLowerCase(),f])),o=a((f,m)=>{let h=Po.normalize(Po.join(f,m.replace(/\\/g,"/")));return h.startsWith("../")||h===".."?null:r.get(h.toLowerCase())??null},"lookup"),i=[...n.keys()],s=i.filter(f=>M2.test(f)),l=i.filter(f=>O2.test(f)),u=[];if(s.length===0&&l.length===0)return[{input:"Dropped files",error:"Nothing to convert here: drop .docx or .tex files, or a folder that contains them."}];for(let f of s)try{let m=await Qi(n.get(f),It,{detectLatex:{singleDollarMode:t.singleDollarMode}}),h=Nf(f),g=`${h}.tex`,y=new Map,E=g;if(m.images.size===0)y.set(g,new TextEncoder().encode(m.tex));else{E=`${h}/${g}`,y.set(E,new TextEncoder().encode(m.tex));for(let[w,A]of m.images)y.set(`${h}/${w}`,A)}let v=[...m.equationsSkipped.map(w=>`Equation ${w.index} was left out: ${w.reason}`),...m.rejectedText.map(w=>`Left as text: ${w.latex} \u2014 ${w.reason}`),...m.skippedAsCurrency>0?[`${mn(m.skippedAsCurrency,"expression")} starting with a digit were read as currency and left as text.`]:[],...m.warnings];u.push({input:f,kind:"docx-to-tex",files:y,primary:E,summary:`${mn(m.blocks,"block")}, ${mn(m.equationsConverted,"equation")}`+(m.images.size>0?`, ${mn(m.images.size,"image")}`:""),notes:v})}catch(m){u.push({input:f,error:m instanceof Error?m.message:String(m)})}let c=new Map(l.map(f=>[f,xl(n.get(f))])),d=l.filter(f=>/\\documentclass\b/.test(c.get(f)));d.length===0&&l.length===1&&(d=l),d.length===0&&l.length>1&&u.push({input:l.join(", "),error:"None of these .tex files has \\documentclass, so there is no telling which is the document and which are its chapters."});let p=i.filter(f=>Pf.test(f));for(let f of d)try{let m=c.get(f),h=Po.dirname(f),g=es(m).map(w=>o(h,Pf.test(w)?w:`${w}.bib`)).filter(w=>w!==null),y=g.length>0?g:p,E=await ts(m,It,{bibStyle:t.bibStyle,bibSources:y.map(w=>xl(n.get(w))),resolveInput:a(w=>{let A=o(h,w)??o(h,`${w}.tex`);return A===null||A===f?null:xl(n.get(A))},"resolveInput"),resolveImage:a(w=>{let A=o(h,w);return A===null?null:n.get(A)},"resolveImage")}),v=`${Nf(f)}.docx`;u.push({input:f,kind:"tex-to-docx",files:new Map([[v,E.bytes]]),primary:v,summary:`${mn(E.blocks,"block")}, ${mn(E.equations,"equation")}`+(E.images>0?`, ${mn(E.images,"image")}`:"")+(E.citations>0?`, ${mn(E.citations,"work")} cited`:""),notes:E.warnings})}catch(m){u.push({input:f,error:m instanceof Error?m.message:String(m)})}return u}a(If,"convertBatch");x();x();var L2="0.6.0-alpha";var Io=typeof __APP_DISTRIBUTION__=="string"&&__APP_DISTRIBUTION__==="store"?"store":"direct";function os(e=L2,t=474){return t>0?`${e} (build ${t})`:e}a(os,"versionLabel");import{mkdir as K2,readFile as Z2,rename as J2,rm as Q2,writeFile as ev}from"node:fs/promises";import{homedir as Al}from"node:os";import{dirname as tv,join as $o}from"node:path";x();import{createHash as F2}from"node:crypto";import{execFile as B2}from"node:child_process";import{readFile as U2}from"node:fs/promises";function $f(e,t){return new Promise((n,r)=>{B2(e,t,{timeout:5e3,windowsHide:!0},(o,i)=>o?r(o):n(String(i)))})}a($f,"run");async function q2(e=process.platform){try{if(e==="win32"){let t=await $f("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"]);return/MachineGuid\s+REG_SZ\s+([0-9A-Fa-f-]{36})/.exec(t)?.[1]?.toLowerCase()??null}if(e==="darwin"){let t=await $f("ioreg",["-rd1","-c","IOPlatformExpertDevice"]);return/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]{36})"/.exec(t)?.[1]?.toLowerCase()??null}for(let t of["/etc/machine-id","/var/lib/dbus/machine-id"]){let n=(await U2(t,"utf8").catch(()=>"")).trim();if(/^[0-9a-f]{32}$/.test(n))return n}}catch{}return null}a(q2,"rawMachineId");function W2(e){return F2("sha256").update(`texconverter-machine:v1:${e}`).digest("hex")}a(W2,"machineHashOf");var Rf;function Mf(){return Rf??=q2().then(e=>e?W2(e):null),Rf}a(Mf,"machineHash");x();x();var H2="L2W1",G2=new TextEncoder;function gt(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((e.length+3)%4)),n=new Uint8Array(t.length);for(let r=0;rtypeof n=="string")&&Array.isArray(t.base)&&t.base.every(n=>typeof n=="string")&&typeof t.iat=="number"&&typeof t.exp=="number"}a(j2,"isClaims");function vl(e){let t=e.split(".");if(!(t.length!==3||t[0]!==H2))try{let n=JSON.parse(new TextDecoder().decode(gt(t[1])));return j2(n)?n:void 0}catch{return}}a(vl,"peekLicenseClaims");async function Of(e,t,n){if(typeof e!="string"||e.length>8192)return{ok:!1,reason:"malformed"};let r=e.split("."),o=vl(e);if(!o)return{ok:!1,reason:"malformed"};let i=Object.prototype.hasOwnProperty.call(t,o.kid)?t[o.kid]:void 0;if(!i)return{ok:!1,reason:"unknown_key"};let s;try{let l=await crypto.subtle.importKey("raw",gt(i),{name:"Ed25519"},!1,["verify"]);s=await crypto.subtle.verify({name:"Ed25519"},l,gt(r[2]),G2.encode(`${r[0]}.${r[1]}`))}catch(l){return l instanceof Error&&l.name==="NotSupportedError"?{ok:!1,reason:"unsupported"}:{ok:!1,reason:"bad_signature"}}return s?n>=o.exp?{ok:!1,reason:"expired",claims:o}:{ok:!0,claims:o}:{ok:!1,reason:"bad_signature"}}a(Of,"verifyLicense");x();var is=class extends Error{constructor(n,r,o){super(o);this.status=n;this.code=r;this.name="SyncHttpError"}static{a(this,"SyncHttpError")}};var GC=5*6e4;var _f="x-texconverter-machine",Lf=720*60*60*1e3,X2="core.";function z2(e){return e.startsWith(X2)}a(z2,"isAlwaysFree");var kl="latex2word.account.v1",Ff="latex2word.clientDeviceId.v1",hn=class extends Error{constructor(n,r,o){super(o);this.status=n;this.code=r;this.name="LicenseServerError"}static{a(this,"LicenseServerError")}},Ar=class extends Error{static{a(this,"LicenseNetworkError")}constructor(t="Couldn't reach the TeXConverter server. Check your connection and try again."){super(t),this.name="LicenseNetworkError"}},El={state:"signed_out",granted:new Set};function Bf(){let e=crypto.getRandomValues(new Uint8Array(16));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(Bf,"randomClientId");function V2(e){let t=e;return typeof t=="object"&&t!==null&&t.v===1&&typeof t.server=="string"&&typeof t.session=="string"&&typeof t.email=="string"&&typeof t.license=="string"&&typeof t.refreshAfter=="number"}a(V2,"isStoredAccount");var ss=class e{constructor(t){this.options=t;this.fresh=new Set;this.serverUrl=t.serverUrl.replace(/\/+$/,""),this.fetchImpl=t.fetch??((n,r)=>fetch(n,r)),this.now=t.now??Date.now,this.timeoutMs=t.timeoutMs??15e3}static{a(this,"LicenseClient")}machine(){return this.machineHash??=(async()=>{try{let t=await this.options.machine?.();return typeof t=="string"&&/^[0-9a-f]{64}$/.test(t)?t:null}catch{return null}})(),this.machineHash}async machineCheck(){let t=await this.machine();if(!t)return;let n=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`check:${t}`)));return Array.from(n,r=>r.toString(16).padStart(2,"0")).join("")}async account(){try{let t=await this.options.store.get(kl);if(!t)return;let n=JSON.parse(t);if(!V2(n)||n.server!==this.serverUrl)return;if(n.machineCheck){let r=await this.machineCheck();if(r&&r!==n.machineCheck)return}return n}catch{return}}async save(t){let n=t.machineCheck??await this.machineCheck();await this.options.store.set(kl,JSON.stringify(n?{...t,machineCheck:n}:t))}async forget(){try{await this.options.store.remove(kl)}catch{}}async clientDeviceId(){try{let t=await this.options.store.get(Ff);if(t&&/^[A-Za-z0-9_-]{8,100}$/.test(t))return t;let n=Bf();return await this.options.store.set(Ff,n),n}catch{return Bf()}}async request(t,n,r,o,i=this.timeoutMs){let s={};if(r!==void 0&&(s["content-type"]="application/json"),o){s.authorization=`Bearer ${o}`;let p=await this.machine();p&&(s[_f]=p)}let l=new AbortController,u=setTimeout(()=>l.abort(),i),c;try{c=await this.fetchImpl(`${this.serverUrl}${n}`,{method:t,headers:s,body:r===void 0?void 0:JSON.stringify(r),signal:l.signal})}catch{throw new Ar}finally{clearTimeout(u)}let d;try{d=await c.json()}catch{throw new Ar(`The TeXConverter server answered unexpectedly (HTTP ${c.status}).`)}return{status:c.status,body:d}}static fail(t){let n=typeof t.body?.code=="string"?t.body.code:"error",r=typeof t.body?.error=="string"?t.body.error:`Request failed (HTTP ${t.status}).`;return new hn(t.status,n,r)}async callAsDevice(t,n,r,o){let i=await this.account();if(!i)throw new hn(401,"unauthenticated","Sign in to your TeXConverter account first.");let s=await this.request(t,n,r,i.session,o);if(s.status===401&&await this.forgetIf(i),s.status>=400)throw e.fail(s);return s.body}async streamAsDevice(t,n){let r=await this.account();if(!r)throw new hn(401,"unauthenticated","Sign in to your TeXConverter account first.");let o;try{let i=await this.machine(),s={authorization:`Bearer ${r.session}`};i&&(s[_f]=i),o=await this.fetchImpl(`${this.serverUrl}${t}`,{headers:s,signal:n})}catch{throw new Ar}if(!o.ok||!o.body){let i=await o.json().catch(()=>({}));throw o.status===401&&await this.forgetIf(r),e.fail({status:o.status,body:i})}return o.body}syncTransport(){let t=a(n=>n instanceof hn?new is(n.status,n.code,n.message):n,"asSync");return{call:a(async(n,r,o)=>{try{return await this.callAsDevice(n,r,o)}catch(i){throw t(i)}},"call"),stream:a(async(n,r)=>{try{return await this.streamAsDevice(n,r)}catch(o){throw t(o)}},"stream")}}async signedInEmail(){return(await this.account())?.email||null}async forgetIf(t){(await this.account())?.session===t.session&&await this.forget()}async startLink(){let{app:t,name:n,platform:r}=this.options.device,o=await this.request("POST","/v1/devices/link/start",{clientDeviceId:await this.clientDeviceId(),app:t,...n?{name:n.slice(0,100)}:{},...r?{platform:r.slice(0,50)}:{}});if(o.status!==201)throw e.fail(o);let i=o.body;return{deviceCode:i.deviceCode,userCode:i.userCode,verificationUrl:i.verificationUrl,verificationUrlComplete:i.verificationUrlComplete,expiresAt:this.now()+i.expiresIn*1e3,interval:i.interval}}async pollLink(t){let n=await this.request("POST","/v1/devices/link/poll",{deviceCode:t.deviceCode}),r=n.body?.code;if(n.status===202)return"pending";if(n.status===429&&r==="slow_down")return"slow_down";if(n.status===410)return"expired";if(n.status===403&&r==="access_denied")return"denied";if(n.status!==200)throw e.fail(n);let o=n.body;return this.fresh.add(o.license.token),await this.save({v:1,server:this.serverUrl,session:o.token,email:o.user?.email??"",name:o.user?.name??null,license:o.license.token,planName:o.license.planName??null,refreshAfter:o.license.refreshAfter}),"approved"}async waitForLink(t,n={}){let r=n.sleep??Y2,o=Math.max(1,t.interval)*1e3;for(;;){if(n.signal?.aborted)return"cancelled";if(this.now()>=t.expiresAt)return"expired";if(await r(o,n.signal),n.signal?.aborted)return"cancelled";let i;try{i=await this.pollLink(t)}catch(s){if(s instanceof Ar)continue;throw s}if(i==="slow_down")o+=5e3;else if(i!=="pending")return i}}async signOut(){let t=await this.account();if(await this.forget(),!!t)try{await this.request("POST","/v1/auth/logout",{},t.session)}catch{}}async status(t={}){let n=t.refresh??"auto",r=await this.account();if(!r)return El;if(n==="force"){let i=await this.refresh(r);if(i===null)return El;i&&(r=i)}let o=await this.check(r);if(o.state!=="active"&&n==="auto"){let i=await this.refresh(r);if(i===null)return El;i&&(o=await this.check(i))}else n==="auto"&&this.now()>=r.refreshAfter&&this.refresh(r).catch(()=>{});return o}async check(t){let n=this.now(),r={email:t.email,name:t.name,planName:t.planName},o=await Of(t.license,this.options.publicKeys,n);if(o.ok)return{state:"active",granted:new Set(o.claims.ent),expiresAt:o.claims.exp,...r};let i;if(o.reason==="unsupported"){if(i=vl(t.license),i&&this.fresh.has(t.license)&&n{try{let{version:n}=this.options.device,r=await this.request("POST","/v1/license",n?{appVersion:n.slice(0,60)}:{},t.session);if(r.status===401)return await this.forget(),null;if(r.status!==200)return;let o=r.body.license;this.fresh.add(o.token);let i=r.body.user,s={...t,...i&&typeof i.email=="string"?{email:i.email,name:typeof i.name=="string"?i.name:null}:{},license:o.token,planName:o.planName??null,refreshAfter:o.refreshAfter};return await this.save(s),s}catch{return}finally{this.refreshing=void 0}})(),this.refreshing}};function Y2(e,t){return new Promise(n=>{let r=setTimeout(o,e);function o(){clearTimeout(r),t?.removeEventListener("abort",o),n()}a(o,"done"),t?.addEventListener("abort",o,{once:!0})})}a(Y2,"defaultSleep");var nv="pack.documents",rv="pack.diagrams",ov="pack.tables",iv="core.image",Uf="pack.ai",sv="pack.pdf";function as(e=process.env,t=process.platform){return t==="win32"?$o(e.APPDATA??$o(Al(),"AppData","Roaming"),"LaTeX2Word","account.json"):t==="darwin"?$o(Al(),"Library","Application Support","LaTeX2Word","account.json"):$o(e.XDG_CONFIG_HOME??$o(Al(),".config"),"latex2word","account.json")}a(as,"accountFile");function av(e){let t=a(async()=>{try{let r=JSON.parse(await Z2(e,"utf8"));return typeof r=="object"&&r!==null?r:{}}catch{return{}}},"load"),n=a(async r=>{await K2(tv(e),{recursive:!0});let o=`${e}.${process.pid}.tmp`;await ev(o,JSON.stringify(r),{mode:384}),await J2(o,e)},"store");return{async get(r){let o=(await t())[r];return typeof o=="string"?o:null},async set(r,o){await n({...await t(),[r]:o})},async remove(r){let o=await t();r in o&&(delete o[r],Object.keys(o).length===0?await Q2(e,{force:!0}):await n(o))}}}a(av,"fileStore");var lv={win32:"Windows",darwin:"macOS",linux:"Linux"};function uv(e,t=process.platform){let n=lv[t]??t;return{app:e,name:`TeXConverter ${e==="desktop"?"app":"command line"} on ${n}`,platform:t,version:os()}}a(uv,"clientApp");function ls(e,t={}){if(fe.licenseServerUrl)return new ss({serverUrl:fe.licenseServerUrl,publicKeys:fe.licensePublicKeys,store:av(t.path??as()),device:uv(e),fetch:t.fetch,machine:t.machine??Mf})}a(ls,"accountClient");function qf(e){return e.granted.has(rv)?null:e.state==="signed_out"?"Saving diagrams needs a TeXConverter account with a subject plan. Sign in first.":e.state==="limited"?"TeXConverter couldn't check your plan. Connect to the internet and try again.":"Saving diagrams is part of every subject plan, which your account doesn't have yet."}a(qf,"diagramsRefusal");function Wf(e){return e.granted.has(ov)?null:e.state==="signed_out"?"Saving statistics tables needs a TeXConverter account with a subject plan. Sign in first.":e.state==="limited"?"TeXConverter couldn't check your plan. Connect to the internet and try again.":"Saving statistics tables is part of every subject plan, which your account doesn't have yet."}a(Wf,"tablesRefusal");function Hf(e){return e.granted.has(iv)?null:e.state==="signed_out"?"Saving an equation as a picture needs a TeXConverter account. It's free: sign in first.":e.state==="limited"?"TeXConverter couldn't check your plan. Connect to the internet and try again.":"Saving an equation as a picture isn't included in your plan."}a(Hf,"imagesRefusal");function Gf(e){return e.granted.has(Uf)?null:e.state==="signed_out"?"Create with AI needs a TeXConverter account. Sign in first.":e.state==="limited"?"TeXConverter couldn't check your plan. Connect to the internet and try again.":"Create with AI in the app is part of every paid plan. On the free plan, it's on the TeXConverter website."}a(Gf,"aiRefusal");function Sl(e){return e.granted.has(sv)&&e.granted.has(Uf)?null:e.state==="signed_out"?"PDF to LaTeX needs a TeXConverter account with a subject plan. Sign in first.":e.state==="limited"?"TeXConverter couldn't check your plan. Connect to the internet and try again.":"PDF to LaTeX is part of every subject plan, which your account doesn't have yet."}a(Sl,"pdfRefusal");function $n(e){return e.granted.has(nv)?null:e.state==="signed_out"?"Converting whole files needs a TeXConverter account with the Documents pack. Sign in first.":e.state==="limited"?"TeXConverter couldn't check your plan. Connect to the internet and try again.":"Converting whole files is part of the Documents pack, which your plan doesn't include. Every paid plan has it."}a($n,"documentsRefusal");x();x();var Zf=iu(za(),1);x();var jf="http://www.w3.org/1998/Math/MathML";var Dl={"\u0302":"^","\u0303":"~","\u0307":"\u02D9","\u0308":"\xA8","\u030C":"\u02C7","\u0306":"\u02D8","\u20D7":"\u2192","\u20D6":"\u2190","\u20E1":"\u2194"},Xf="_";var cv=new Set(["=","\u2260","<",">","\u2264","\u2265","\u2248","\u2261","\u223C","\u2243","\u2245","\u221D","\u226A","\u226B","\u2254","\u2192","\u2190","\u2194","\u21D2","\u21D0","\u21D4","\u27F6","\u27F5","\u27F7","\u27F9","\u27F8","\u27FA","\u21A6","\u27FC","\u21CC","\u21CB","\u2208","\u2209","\u2282","\u2283","\u2286","\u2287"]),dv=new Set(["+","-","\u2212","\xB1","\u2213","\xD7","\xF7","\xB7","\u22C5","\u222A","\u2229","\u2295","\u2297","\u2227","\u2228"]),fN=new Set([...cv,...dv,","]);function ut(e){throw new tt(e)}a(ut,"fail");function Jf(e){if(!e||e.nodeType!==1)return!1;let t=e.namespaceURI;return t===jf||t===null||t===void 0}a(Jf,"isMathmlElement");function pv(e){return jt(e)==="mo"&&Dr(e).trim()==="\u2061"}a(pv,"isFunctionApplication");function gn(e){let t=[];for(let n=0;n[t,e])),mv=new Set(["\u203E","\u2015","\xAF","\u0304"]);function hv(e,t){let n=je(e,"mathvariant");if(n!==null)switch(n){case"italic":return{italic:!0,bold:!1};case"bold":return{italic:!1,bold:!0};case"bold-italic":return{italic:!0,bold:!0};case"normal":return{italic:!1,bold:!1};default:ut(`mathvariant="${n}" is not a style TeXConverter can represent \u2014 use the corresponding Unicode characters (as \\mathbb, \\mathcal and \\mathfrak produce) instead.`)}return{italic:jt(e)==="mi"&&[...t].length===1,bold:!1}}a(hv,"stylingOf");function gv(e){if(jt(e)==="mspace")return{kind:"symbol",text:" ",italic:!1};let n=Dr(e),{italic:r,bold:o}=hv(e,n),i=o?{kind:"symbol",text:n,italic:r,bold:o}:{kind:"symbol",text:n,italic:r},s=em(e);return s!==void 0&&(i.color=s),i}a(gv,"tokenToIr");function em(e){let t=je(e,"mathcolor");if(t===null)return;let n=cu(t);return n===null&&ut(`mathcolor="${t}" is not a colour TeXConverter can read \u2014 use a #RRGGBB value or a common colour name.`),n}a(em,"colorOf");function Rn(e){return Ro(gn(e).map(t=>ae(t)))}a(Rn,"contentOf");function Ro(e){return e.length===1?e[0]:{kind:"row",children:e}}a(Ro,"asRow");function Sr(e,t){let n=gn(e);return n.length!==t&&ut(`<${jt(e)}> requires exactly ${t} child elements but has ${n.length}.`),n}a(Sr,"expectChildren");function yt(e,t){return jt(e)===t}a(yt,"isToken");function ct(e){if(!Qf.has(jt(e)))return null;let t=[...Dr(e).trim()];return t.length===1?t[0]:null}a(ct,"singleChar");var yv=new Set(["\u2211","\u220F","\u2210","\u222B","\u222C","\u222D","\u222E","\u222F","\u2230","\u2A0C","\u22C3","\u22C2","\u2A01","\u2A02","\u2A00","\u2A04","\u22C1","\u22C0","\u2A06"]),bv=new Set(["\u27F6","\u27F5","\u2192","\u2190","\u21CC","\u21C0","\u21C1","\u21BD","\u21CB","\u27F7","\u27F9","\u27F8","\u27FA","\u27FC","\u21AA","\u21A9"]),wv=new Set([Xf,"\u0332"]);function Cl(e){if(!yt(e,"mo"))return!1;if(je(e,"largeop")==="true")return!0;let t=ct(e);return t!==null&&yv.has(t)}a(Cl,"isLargeOperator");function xv(e){if(!yt(e,"mo")||je(e,"stretchy")!=="true")return!1;let t=ct(e);return t!==null&&bv.has(t)}a(xv,"isArrowOperator");function vv(e){let t=ct(e);return t===null?null:zf[t]!==void 0?zf[t]:Dl[t]!==void 0?t:null}a(vv,"accentMarkOf");function kv(e){let t=ct(e);return t!==null&&mv.has(t)}a(kv,"isOverline");var Ev={"\u23DE":"top","\u23DF":"bot","\u23DC":"top","\u23DD":"bot"};function Vf(e){let t=ct(e);if(t===null)return null;let n=Ev[t];return n===void 0?null:{chr:t,pos:n}}a(Vf,"groupCharOf");function Tl(e,t,n){let o=gn(e)[0];if(Cl(o)){let i=ct(o)??Dr(o).trim();return tm(i,t,n,"undOvr",{kind:"row",children:[]})}if(xv(o)){let s={kind:"labeledarrow",chr:ct(o)??Dr(o).trim()};return n&&(s.above=ae(n)),t&&(s.below=ae(t)),s}if(n!==null&&t===null){let i=Vf(n);if(i!==null)return{kind:"groupchar",chr:i.chr,pos:i.pos,base:ae(o)};if(kv(n))return{kind:"accent",base:ae(o),bar:!0};let s=vv(n);return s!==null?{kind:"accent",base:ae(o),char:s}:{kind:"limupp",base:ae(o),upper:ae(n)}}if(t!==null&&n===null){let i=Vf(t);if(i!==null)return{kind:"groupchar",chr:i.chr,pos:i.pos,base:ae(o)};let s=ct(t);return s!==null&&wv.has(s)?{kind:"accent",base:ae(o),bar:!0,under:!0}:{kind:"limlow",base:ae(o),lower:ae(t)}}ut(` requires a large operator or an arrow as its base; found <${jt(o)}>.`)}a(Tl,"parseUnderOver");function tm(e,t,n,r,o){let i={kind:"nary",chr:e,operand:o,limitLocation:r};return t&&(i.sub=ae(t)),n&&(i.sup=ae(n)),i}a(tm,"naryFrom");var Av="([{\u27E8\u2308\u230A|\u2016\u2223",Sv=")]}\u27E9\u2309\u230B|\u2016\u2223";function Yf(e){return yt(e,"mo")&&je(e,"fence")==="true"}a(Yf,"isExplicitFence");function Kf(e,t){if(!yt(e,"mo"))return null;if(je(e,"fence")==="true"&&Dr(e).trim()==="")return"";let n=ct(e);return n===null?null:je(e,"fence")==="true"?n:je(e,"stretchy")==="false"?null:(t?Av:Sv).includes(n)?n:null}a(Kf,"fenceCharOf");function Dv(e){if(e.length<2)return null;let t=e[0],n=e[e.length-1],r=Kf(t,!0),o=Kf(n,!1),i;if(r!==null&&o!==null)i=e.slice(1,-1);else if(Yf(t)&&r!==null)o="",i=e.slice(1);else if(Yf(n)&&o!==null)r="",i=e.slice(0,-1);else return null;if(r===null||o===null)return null;let s=[],l=[[]];for(let c of i){let d=yt(c,"mo")&&je(c,"fence")==="true"?ct(c):null;d!==null?(s.push(d),l.push([])):l[l.length-1].push(ae(c))}if(s.length===0)return{kind:"delimited",left:r,right:o,parts:[Ro(l[0])]};let u=s[0];return s.every(c=>c===u)||ut("A delimited group divided by more than one kind of separator cannot be represented \u2014 OMML allows a single separator character per group."),{kind:"delimited",left:r,right:o,parts:l.map(c=>Ro(c)),sepChar:u}}a(Dv,"tryDelimited");function nm(e){if(e.length===0)return null;let t=e[0],n=jt(t),r=null,o=null,i=null,s="subSup";if(Cl(t))r=ct(t);else if(["msub","msup","msubsup","munder","mover","munderover"].includes(n)){let u=gn(t),c=u[0];if(c===void 0||!Cl(c))return null;r=ct(c),s=n.startsWith("mu")||n==="mover"?"undOvr":"subSup",n==="msub"||n==="munder"?o=u[1]??null:n==="msup"||n==="mover"?i=u[1]??null:(o=u[1]??null,i=u[2]??null)}else return null;if(r===null)return null;let l=Ro(e.slice(1).map(u=>ae(u)));return tm(r,o,i,s,l)}a(nm,"tryNary");function Tv(e){let t=Dv(e);if(t!==null)return t;let n=nm(e);return n!==null?n:Ro(e.map(r=>ae(r)))}a(Tv,"parseRow");function Cv(e){let n=gn(e).filter(i=>yt(i,"mtr")||yt(i,"mlabeledtr")).map(i=>gn(i).filter(s=>yt(s,"mtd")).map(s=>Rn(s))),r=je(e,"columnalign");if((r==="left"||r==="center")&&n.every(i=>i.length===1))return{kind:"eqarr",rows:n.map(i=>i[0]),justify:r};let o=Nv(r,Math.max(1,...n.map(i=>i.length)));return o===void 0?{kind:"matrix",rows:n}:{kind:"matrix",rows:n,columns:o}}a(Cv,"parseTable");function Nv(e,t){if(e==null)return;let n=e.trim().split(/\s+/).filter(o=>o.length>0);if(n.length===0)return;let r=[];for(let o=0;oo!=="center")?r:void 0}a(Nv,"columnAlignments");function Pv(e){let t=gn(e),n=t.findIndex(s=>yt(s,"mprescripts"));n<0&&ut(" without (postscript-style staggered indices) has no OMML equivalent \u2014 write the scripts as ordinary sub/superscripts.");let r=t[0];r===void 0&&ut(" has no base.");let o=t.slice(n+1);o.length!==2&&ut(` takes prescripts in (sub, sup) pairs; found ${o.length} after .`);let i={kind:"prescript",base:ae(r)};return yt(o[0],"none")||(i.presub=ae(o[0])),yt(o[1],"none")||(i.presup=ae(o[1])),i}a(Pv,"parseMultiscripts");function ae(e){let t=jt(e);if(Qf.has(t))return gv(e);if(fv.has(t)){let n=em(e);return n===void 0?Rn(e):Ms(Rn(e),n)}switch(t){case"math":case"mrow":return Tv(gn(e));case"mfrac":{let[n,r]=Sr(e,2),o=je(e,"linethickness"),i=o==="0"||o==="0px"||o==="0pt";return{kind:"frac",numerator:ae(n),denominator:ae(r),noBar:i}}case"msqrt":return{kind:"radical",radicand:Rn(e)};case"mroot":{let[n,r]=Sr(e,2);return{kind:"radical",radicand:ae(n),index:ae(r)}}case"msub":case"msup":case"msubsup":{let n=nm([e]);if(n!==null)return n;let r=Sr(e,t==="msubsup"?3:2),o=ae(r[0]);return t==="msub"?{kind:"supersub",base:o,sub:ae(r[1])}:t==="msup"?{kind:"supersub",base:o,sup:ae(r[1])}:{kind:"supersub",base:o,sub:ae(r[1]),sup:ae(r[2])}}case"munder":{let n=Sr(e,2);return Tl(e,n[1],null)}case"mover":{let n=Sr(e,2);return Tl(e,null,n[1])}case"munderover":{let n=Sr(e,3);return Tl(e,n[1],n[2])}case"mmultiscripts":return Pv(e);case"mtable":return Cv(e);case"menclose":{let n=(je(e,"notation")??"longdiv").trim().split(/\s+/).filter(l=>l.length>0),r=n.includes("updiagonalstrike"),o=n.includes("downdiagonalstrike"),i=n.includes("box"),s=n.filter(l=>l!=="updiagonalstrike"&&l!=="downdiagonalstrike"&&l!=="box");return s.length>0&&ut(` has no OMML equivalent \u2014 only box (\\boxed) and the diagonal strikes (the \\cancel family) are supported.`),i?{kind:"borderbox",base:Rn(e),strikeBLTR:r,strikeTLBR:o,boxed:!0}:{kind:"borderbox",base:Rn(e),strikeBLTR:r,strikeTLBR:o}}case"mfenced":{let n=je(e,"open")??"(",r=je(e,"close")??")";return{kind:"delimited",left:n,right:r,parts:[Rn(e)]}}default:return ut(`"<${t}>" is not a MathML element TeXConverter can convert.`)}}a(ae,"parseElement");function Iv(e){let t=[],n=new Zf.DOMParser({errorHandler:a((r,o)=>{(r==="error"||r==="fatalError")&&t.push(String(o))},"errorHandler")}).parseFromString(e,"text/xml");return t.length>0&&ut(`The provided MathML is not well-formed XML: ${t.join("; ")}`),n}a(Iv,"parseXml");function $v(e){let t=null,n=a(r=>{if(!(t!==null||!r)){if(Jf(r)&&r.localName==="math"){t=r;return}for(let o=0;o element found \u2014 this does not look like MathML."),{ir:ae(n),display:je(n,"display")==="block"}}a(Rv,"parseMathmlDetailed");function rm(e){return Rv(e).ir}a(rm,"parseMathml");var Xt=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="HandwritingError"}static{a(this,"HandwritingError")}};function us(e){let t;return{available:e!==void 0,async write(n){if(e===void 0)throw new Xt("unavailable","Online handwriting recognition isn't available in this build.");if(t)throw new Xt("busy","The handwriting panel is already open. Finish or close it first.");let r=new AbortController;t=r;let o=a(()=>r.abort(),"onCallerGone");n?.addEventListener("abort",o,{once:!0});let i;try{i=await e(r.signal)}finally{n?.removeEventListener("abort",o),t=void 0}if(i.kind==="cancelled")return{kind:"cancelled"};try{return{kind:"inserted",latex:xe(rm(i.mathml)),mathml:i.mathml}}catch(s){throw new Xt("unreadable",`Windows recognised the handwriting, but TeXConverter couldn't read its answer: ${s instanceof Error?s.message:String(s)}`)}},abort(){t?.abort()}}}a(us,"createHandwritingDesk");x();import{createHash as Fv}from"node:crypto";import{existsSync as Bv,renameSync as Uv,rmSync as qv,writeFileSync as Wv}from"node:fs";x();var om="TCR1",Ov=new TextEncoder;function _v(e){let t=e;return typeof t=="object"&&t!==null&&t.v===1&&typeof t.platform=="string"&&/^[a-z]{1,20}$/.test(t.platform)&&typeof t.version=="string"&&t.version.length<=40&&Number.isInteger(t.build)&&t.build>0&&Number.isInteger(t.bytes)&&t.bytes>0&&typeof t.sha256=="string"&&/^[0-9a-f]{64}$/.test(t.sha256)}a(_v,"isManifest");function Lv(e){if(typeof e!="string"||e.length>4096)return;let t=e.split(".");if(!(t.length!==4||t[0]!==om))try{let n=JSON.parse(new TextDecoder().decode(gt(t[2])));return _v(n)?n:void 0}catch{return}}a(Lv,"peekRelease");async function im(e,t){let n=Lv(e);if(!n)return{ok:!1,reason:"malformed"};let[,r,o,i]=e.split("."),s=Object.prototype.hasOwnProperty.call(t,r)?t[r]:void 0;if(!s)return{ok:!1,reason:"unknown_key"};let l;try{let u=await crypto.subtle.importKey("raw",gt(s),{name:"Ed25519"},!1,["verify"]);l=await crypto.subtle.verify({name:"Ed25519"},u,gt(i),Ov.encode(`${om}.${r}.${o}`))}catch(u){return u instanceof Error&&u.name==="NotSupportedError"?{ok:!1,reason:"unsupported"}:{ok:!1,reason:"bad_signature"}}return l?{ok:!0,manifest:n}:{ok:!1,reason:"bad_signature"}}a(im,"verifyRelease");var ve=class extends Error{static{a(this,"UpdateError")}};function sm(e,t){let n=t.windows;return e<=0||!n||n.build<=e?{available:!1,required:!1}:{available:!0,required:t.minimumBuild>e}}a(sm,"compareBuilds");async function Hv(e,t,n){let r;try{r=new URL(e.url)}catch{throw new ve("The update's address isn't valid, so it wasn't installed.")}if(r.origin!==new URL(n).origin)throw new ve("The update isn't on TeXConverter's server, so it wasn't installed.");if(Object.keys(t).length===0)return;let o=e.manifest?await im(e.manifest,t):{ok:!1,reason:"malformed"};if(!o.ok)throw new ve("The update isn't signed by TeXConverter, so it wasn't installed. Download the new version from the website.");let i=o.manifest;if(i.platform!=="windows"||i.build!==e.build||i.bytes!==e.bytes||i.sha256!==e.sha256.toLowerCase())throw new ve("The update doesn't match its signature, so it wasn't installed.")}a(Hv,"checkRelease");async function Gv(e,t){if(e.byteLength!==t.bytes)throw new ve(`The download was ${e.byteLength} bytes, not ${t.bytes}. Try again.`);if(Fv("sha256").update(e).digest("hex")!==t.sha256)throw new ve("The download didn't match its checksum, so it wasn't installed. Try again.");let r;try{r=(await ji(e,It)).parts}catch(u){throw new ve(`The download couldn't be opened (${u instanceof Error?u.message:String(u)}).`)}let o=[...r.keys()].find(u=>/(^|\/)TeXConverter\.exe$/i.test(u)),i=o===void 0?void 0:r.get(o);if(!i)throw new ve("The download has no TeXConverter.exe in it.");if(i.byteLength<2||i[0]!==77||i[1]!==90)throw new ve("The TeXConverter.exe in the download isn't a Windows program.");let s=[...r.keys()].find(u=>/(^|\/)TeXConverterHelper\.exe$/i.test(u)),l=s===void 0?void 0:r.get(s);return{exe:i,helper:l&&l.byteLength>=2&&l[0]===77&&l[1]===90?l:null}}a(Gv,"filesFromZip");var Pl={exists:Bv,rename:Uv,write:a((e,t)=>Wv(e,t),"write"),remove:a(e=>qv(e,{force:!0}),"remove")},Nl=a(e=>`${e}.old`,"oldExePath");function jv(e,t,n=Pl){let r=Nl(e);n.exists(r)&&n.remove(r);try{n.rename(e,r)}catch(o){throw new ve(`TeXConverter couldn't move itself aside to update (${o instanceof Error?o.message:String(o)}). Download the new version from the website instead.`)}try{n.write(e,t)}catch(o){try{n.remove(e)}catch{}try{n.rename(r,e)}catch{throw new ve(`The update couldn't be written, and the previous version is at ${r}. Rename it back to TeXConverter.exe, or download the app again.`)}throw new ve(`The update couldn't be written (${o instanceof Error?o.message:String(o)}); this version is still in place.`)}}a(jv,"replaceExe");function am(e,t=Pl){try{t.exists(Nl(e))&&t.remove(Nl(e))}catch{}}a(am,"removeOldExe");var Xv=36e5;function lm(e){let t=e.fetch??fetch,n=e.files??Pl,r=e.now??Date.now,o=os(e.version,e.build),i=null,s="idle",l=null,u=null,c=null,d,p=!1,f=null;function m(){let{available:w,required:A}=i?sm(e.build,i):{available:!1,required:!1},N=i?.windows??null;return{current:o,latest:N?{label:N.label,notes:N.notes,bytes:N.bytes,build:N.build}:null,available:w,required:A,canInstall:e.exe!==null&&e.build>0,state:s,progress:l,error:u,checkedAt:c}}a(m,"status");async function h(){let w=await t(`${e.serverUrl}/v1/downloads`,{signal:AbortSignal.timeout(15e3)});if(!w.ok)throw new ve(`TeXConverter's server answered ${w.status}.`);let A=await w.json(),N=A.windows;return{windows:N&&typeof N.url=="string"&&Number.isInteger(N.build)&&typeof N.sha256=="string"?N:null,minimumBuild:Number(A.minimumBuild)||0,updateCheckHours:Number(A.updateCheckHours)||6}}a(h,"fetchDownloads");function g(){return s==="downloading"||s==="installing"||s==="restarting"?Promise.resolve(m()):(f??=(async()=>{s="checking";try{i=await h(),c=r(),u=null}catch{}finally{s="idle",f=null}return m()})(),f)}a(g,"check");async function y(w){let A=await t(w.url,{signal:AbortSignal.timeout(18e5)});if(!A.ok||!A.body)throw new ve(`The download failed (${A.status}). Try again.`);let N=[],S=0,k=A.body.getReader();for(;;){let{done:C,value:D}=await k.read();if(C)break;if(N.push(D),S+=D.byteLength,S>w.bytes)throw k.cancel(),new ve("The download was bigger than it should be, so it wasn't installed.");l=w.bytes>0?S/w.bytes:null}let T=new Uint8Array(S),O=0;for(let C of N)T.set(C,O),O+=C.byteLength;return T}a(y,"download");async function E(){if(s==="downloading"||s==="installing"||s==="restarting")return m();if(e.exe===null||e.build<=0)throw new ve("This copy of TeXConverter can't update itself. Download the new version from the website.");await g();let w=i?.windows;if(!w||!sm(e.build,i).available)throw new ve("This is already the latest version.");u=null;try{await Hv(w,e.releaseKeys??{},e.serverUrl),s="downloading",l=0;let A=await Gv(await y(w),w);s="installing",l=null,jv(e.exe,A.exe,n);try{e.afterReplace?.(e.exe,w.label,A.helper)}catch{}return s="restarting",m()}catch(A){throw s="failed",l=null,u=A instanceof ve?A.message:`The update failed (${A instanceof Error?A.message:String(A)}). Try again.`,A instanceof ve?A:new ve(u)}}a(E,"install");function v(){if(!p)return;let w=Math.min(168,Math.max(1,i?.updateCheckHours??6));d=setTimeout(()=>{g().finally(v)},w*Xv),d.unref?.()}return a(v,"schedule"),{status:m,check:g,install:E,start(){p||(p=!0,g().finally(v))},stop(){p=!1,d&&clearTimeout(d),d=void 0}}}a(lm,"createUpdater");var Qv={unavailable:404,busy:409,unreadable:422},ek=256*1024*1024,tk=["diagram","equation","photo","figure","edit","page","equations","translate"],nk=12e4,ds="[A-Za-z0-9_-]{1,64}",rk=[["GET",/^\/sync$/],["GET",/^\/prefs$/],["PATCH",/^\/prefs$/],["GET",/^\/work$/],["POST",/^\/work$/],["PATCH",new RegExp(`^/work/${ds}$`)],["DELETE",new RegExp(`^/work/${ds}$`)],["GET",/^\/ai\/creations$/],["POST",/^\/ai\/creations$/],["GET",new RegExp(`^/ai/creations/${ds}/photo$`)],["POST",new RegExp(`^/ai/creations/${ds}/(pin|remove|source)$`)]];function ok(e,t){if(!t.startsWith("/api/"))return null;let n=t.slice(4);return rk.some(([r,o])=>r===e&&o.test(n))?`/v1${n}`:null}a(ok,"accountRoute");var K=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o}static{a(this,"HttpError")}};function pm(e,t,n,r,o={}){e.writeHead(t,{"Content-Type":n,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer",...o}),e.end(r)}a(pm,"send");var ye=a((e,t,n)=>pm(e,t,"application/json; charset=utf-8",JSON.stringify(n)),"sendJson");async function Pt(e){if(!(e.headers["content-type"]??"").startsWith("application/json"))throw new K(415,"Expected JSON.");let t=[],n=0;for await(let r of e){if(n+=r.length,n>ek)throw new K(413,"That is more than TeXConverter will take in one go. Convert fewer files at a time.");t.push(r)}try{return JSON.parse(Buffer.concat(t).toString("utf8"))}catch{throw new K(400,"The request was not valid JSON.")}}a(Pt,"readJson");function ik(e,t){if(typeof t!="string")return!1;let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&Kv(n,r)}a(ik,"sameToken");async function sk(e){try{return await Zv(e),!0}catch{return!1}}a(sk,"exists");async function dm(e,t){let n=t.lastIndexOf("."),[r,o]=n>0?[t.slice(0,n),t.slice(n)]:[t,""];for(let i=1;;i++){let s=i===1?t:`${r} (${i})${o}`;if(!await sk(Mo(e,s)))return s}}a(dm,"freeName");function ak(e){let t=e.replace(/\.pdf$/i,"").replace(/[<>:"/\\|?*\u0000-\u001f]/g," ").replace(/\s+/g," ").trim().replace(/^[. ]+|[. ]+$/g,"").slice(0,80).trim();return/^(con|prn|aux|nul|com\d|lpt\d)$/i.test(t)||t===""?"PDF":t}a(ak,"fileStem");var lk="default-src 'none'; script-src 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";async function fm(e){let t=e.token??Il(32).toString("hex"),n=$l(e.outputDir),r=new Map,o=Date.now(),i=0,s,l,u=e.desk??us(e.handwriting);async function c(C=!1){if(!e.account)return{enabled:!1};let D=await e.account.status(C?{refresh:"force"}:void 0);return{enabled:!0,state:D.state,email:D.email??null,planName:D.planName??null,documents:$n(D),diagrams:qf(D),tables:Wf(D),images:Hf(D),ai:Gf(D),pdf:Sl(D),signIn:s?{userCode:s.link.userCode,url:s.link.verificationUrlComplete}:null,lastSignIn:l??null}}a(c,"accountInfo");async function d(C,D,P,_=nk){let M=e.account;if(!M?.callAsDevice)throw new K(404,"This build of TeXConverter has no AI tools.");try{return await M.callAsDevice(C,D,P,_)}catch(W){throw p(W)}}a(d,"relayAi");function p(C){return C instanceof hn?new K(C.status,C.message,C.code):new K(502,"TeXConverter's server couldn't be reached. Check your internet connection and try again.")}a(p,"unreachable");async function f(C,D){let P=e.account;if(!P?.streamAsDevice)throw new K(404,"This build of TeXConverter has no account to follow.");let _=new AbortController;C.once("close",()=>_.abort());let M;try{M=await P.streamAsDevice(`/v1/sync/events${D}`,_.signal)}catch(j){throw p(j)}C.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),C.flushHeaders();let W=M.getReader();try{for(let j=await W.read();!j.done;j=await W.read())C.write(j.value)}catch{}finally{_.abort(),C.end()}}a(f,"relayEvents");async function m(C){if(!s){let D={link:await C.startLink(),abort:new AbortController};s=D,l=void 0,C.waitForLink(D.link,{signal:D.abort.signal}).then(P=>l=P,()=>l="failed").finally(()=>{s===D&&(s=void 0)}),e.openUrl?.(D.link.verificationUrlComplete)}return{userCode:s.link.userCode,url:s.link.verificationUrlComplete}}a(m,"startSignIn");let h=zv((C,D)=>{g(C,D).catch(P=>{P instanceof K?ye(D,P.status,P.code===void 0?{error:P.message}:{error:P.message,code:P.code}):ye(D,500,{error:P instanceof Error?P.message:String(P)})})});async function g(C,D){let P=[`127.0.0.1:${i}`,`localhost:${i}`];if(!P.includes(C.headers.host??""))throw new K(421,"Wrong host.");let _=new URL(C.url??"/",`http://${C.headers.host}`);if(_.pathname==="/"&&C.method==="GET"){pm(D,200,"text/html; charset=utf-8",e.html,{"Content-Security-Policy":lk});return}let M=C.method==="GET"?/^\/ocr\/reader\/([^/]{1,60})\/([^/]{1,80})$/.exec(_.pathname):null;if(M){let U=e.reader?.file(M[1],M[2]);if(!U)throw new K(404,"Not found.");D.writeHead(200,{"Content-Type":U.endsWith(".wasm")?"application/wasm":"application/octet-stream","Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":"same-origin"}),await Yv(Vv(U),D).catch(()=>{});return}if(!_.pathname.startsWith("/api/"))throw new K(404,"Not found.");let W=C.headers.origin;if(W!==void 0&&!P.some(U=>W===`http://${U}`))throw new K(403,"Wrong origin.");if(!ik(t,C.headers["x-l2w-token"]))throw new K(401,"Missing or wrong token.");o=Date.now();let j=C.method==="GET"?/^\/api\/ai\/jobs\/([A-Za-z0-9_-]{1,64})$/.exec(_.pathname):null;if(j){ye(D,200,await d("GET",`/v1/ai/jobs/${j[1]}`));return}let we=C.method??"GET",re=ok(we,_.pathname);if(re){let U=we==="POST"||we==="PATCH"?await Pt(C):void 0;ye(D,200,await d(we,re+_.search,U,3e4));return}switch(`${C.method} ${_.pathname}`){case"GET /api/status":ye(D,200,{version:e.version,environment:e.build?.environment??"production",server:e.build?.server??null,outputDir:n,shell:e.shell===void 0?"unavailable":e.shell.installed()?"installed":"not-installed",handwriting:u.available,help:Object.keys(e.help??{}),updates:e.updates!==void 0,account:await c(_.searchParams.get("fresh")==="1")});return;case"GET /api/sync/events":await f(D,_.search);return;case"GET /api/library":if(!e.library)throw new K(404,"This build of TeXConverter has no library to fetch.");ye(D,200,await e.library().catch(()=>{throw new K(502,"The library couldn't be fetched.")}));return;case"GET /api/ai":ye(D,200,await d("GET","/v1/ai"));return;case"GET /api/ocr/reader":if(!e.reader)throw new K(404,"This build of TeXConverter has no reader.");ye(D,200,_.searchParams.get("fresh")==="1"?await e.reader.refresh():e.reader.status());return;case"POST /api/ocr/reader/prepare":if(!e.reader)throw new K(404,"This build of TeXConverter has no reader.");e.reader.prepare(),ye(D,200,e.reader.status());return;case"GET /api/translator":if(!e.translator)throw new K(404,"This build of TeXConverter can't translate on the computer.");ye(D,200,await e.translator.status(_.searchParams.get("fresh")==="1"));return;case"POST /api/translator/prepare":if(!e.translator)throw new K(404,"This build of TeXConverter can't translate on the computer.");ye(D,200,e.translator.prepare());return;case"POST /api/translator/translate":{if(!e.translator)throw new K(404,"This build of TeXConverter can't translate on the computer.");let U=await Pt(C);if(!Array.isArray(U.texts)||!U.texts.every(ie=>typeof ie=="string")||typeof U.lang!="string")throw new K(400,"Send the paper's texts and the language.");try{ye(D,200,e.translator.start(U.texts,U.lang,typeof U.subject=="string"?U.subject:null))}catch(ie){throw new K(409,ie instanceof Error?ie.message:String(ie))}return}case"GET /api/translator/job":if(!e.translator)throw new K(404,"This build of TeXConverter can't translate on the computer.");ye(D,200,e.translator.job());return;case"POST /api/translator/stop":if(!e.translator)throw new K(404,"This build of TeXConverter can't translate on the computer.");e.translator.stop(),ye(D,200,e.translator.job());return;case"POST /api/ai/diagram":case"POST /api/ai/equation":case"POST /api/ai/photo":case"POST /api/ai/figure":case"POST /api/ai/edit":case"POST /api/ai/page":case"POST /api/ai/equations":case"POST /api/ai/translate":{let U=tk.find(ie=>_.pathname===`/api/ai/${ie}`);ye(D,200,await d("POST",`/v1/ai/${U}`,await Pt(C)));return}case"POST /api/ai/pages":ye(D,200,await d("POST","/v1/ai/pages",await Pt(C)));return;case"POST /api/ocr/report":ye(D,200,await d("POST","/v1/ocr/report",await Pt(C)));return;case"POST /api/ai/photo/qr":case"POST /api/ai/photo/qr/status":case"POST /api/ai/photo/qr/cancel":ye(D,200,await d("POST",_.pathname.replace(/^\/api\//,"/v1/"),await Pt(C),3e4));return;case"POST /api/account/signin":if(!e.account)throw new K(404,"This build of TeXConverter has no accounts.");ye(D,200,await m(e.account));return;case"POST /api/account/cancel":s?.abort.abort(),D.writeHead(204).end();return;case"POST /api/account/signout":if(!e.account)throw new K(404,"This build of TeXConverter has no accounts.");await e.account.signOut(),D.writeHead(204).end();return;case"POST /api/ping":D.writeHead(204).end();return;case"POST /api/convert":ye(D,200,await v(await Pt(C)));return;case"POST /api/pdf/save":ye(D,200,await w(await Pt(C)));return;case"POST /api/open":{let U=await Pt(C),ie=typeof U.id=="string"?r.get(U.id):void 0;if(ie===void 0)throw new K(404,"TeXConverter did not write that file in this session.");e.openPath?.(ie,U.reveal===!0),D.writeHead(204).end();return}case"POST /api/install":{if(e.shell===void 0)throw new K(404,"There is no shell integration on this system.");ye(D,200,{done:await e.shell.install()});return}case"POST /api/handwrite":ye(D,200,{latex:await E()});return;case"GET /api/update":ye(D,200,y().status());return;case"POST /api/update/check":ye(D,200,await y().check());return;case"POST /api/update/install":{let U;try{U=await y().install()}catch(ie){throw ie instanceof ve?new K(409,ie.message):ie}D.once("finish",()=>{T()}),ye(D,200,U);return}case"POST /api/help":{let U=await Pt(C),ie=e.help??{},z=typeof U.topic=="string"&&Object.prototype.hasOwnProperty.call(ie,U.topic)?ie[U.topic]:void 0;if(z===void 0)throw new K(404,"There is no such help page.");e.openUrl?.(typeof z=="string"?z:await z()),D.writeHead(204).end();return}case"POST /api/update/download":e.openUrl?.(y().downloadPage),D.writeHead(204).end();return;default:throw new K(404,"Not found.")}}a(g,"handle");function y(){if(!e.updates)throw new K(404,"This build of TeXConverter doesn't update itself.");return e.updates}a(y,"updates");async function E(){try{let C=await u.write();return C.kind==="inserted"?C.latex:null}catch(C){throw C instanceof Xt?new K(Qv[C.reason],C.message):C}}a(E,"handwrite");async function v(C){if(e.account){let W=$n(await e.account.status());if(W!==null)throw new K(403,W)}let D=C;if(!Array.isArray(D.files))throw new K(400,"Expected a list of files.");let P=D.files.map(W=>{if(typeof W?.path!="string"||typeof W?.data!="string")throw new K(400,"Each file needs a path and base64 data.");return{path:W.path,bytes:new Uint8Array(Buffer.from(W.data,"base64"))}}),_=await If(P,{bibStyle:D.options?.bibStyle,singleDollarMode:D.options?.singleDollarMode}),M=[];for(let W of _){if("error"in W){M.push({input:W.input,error:W.error});continue}let j=W.primary.split("/")[0],we=await dm(n,j),re="";for(let[ie,z]of W.files){let Ce=$l(n,we+ie.slice(j.length));if(!Ce.startsWith(n+cm))throw new Error(`Refusing to write outside the output folder: ${ie}`);await um(Jv(Ce),{recursive:!0}),await cs(Ce,z),ie===W.primary&&(re=Ce)}let U=Il(12).toString("hex");r.set(U,re),M.push({input:W.input,kind:W.kind,output:re.slice(n.length+1),id:U,summary:W.summary,notes:W.notes})}return{results:M}}a(v,"convert");async function w(C){if(e.account){let re=Sl(await e.account.status());if(re!==null)throw new K(403,re)}let D=C;if(typeof D.name!="string"||typeof D.tex!="string"||!Array.isArray(D.files))throw new K(400,"Expected a name, the LaTeX and its figures.");let P=new Map;for(let re of D.files){let U=typeof re?.path=="string"?rs(re.path):null;if(U===null||!U.startsWith("figures/")||typeof re.data!="string")throw new K(400,"Each figure needs a path under figures/ and base64 data.");P.set(U,new Uint8Array(Buffer.from(re.data,"base64")))}let _=ak(D.name),M=$l(n,await dm(n,_));if(!M.startsWith(n+cm))throw new K(400,"That name can't be used for a folder.");await um(Mo(M,"figures"),{recursive:!0});for(let[re,U]of P)await cs(Mo(M,...re.split("/")),U);let W=Mo(M,`${_}.tex`);await cs(W,D.tex,"utf8");let j=a(re=>{let U=Il(12).toString("hex");return r.set(U,re),{output:re.slice(n.length+1),id:U}},"saved"),we={tex:j(W),word:null,notes:[]};if(D.word===!0){let re=e.account?$n(await e.account.status()):null;if(re!==null)we.notes.push(`No Word copy: ${re}`);else try{let U=await ns(D.tex,{resolveImage:a(z=>P.get(rs(z)??"")??null,"resolveImage")}),ie=Mo(M,`${_}.docx`);await cs(ie,U.bytes),we.word=j(ie),we.notes.push(...U.warnings.slice(0,50))}catch(U){we.notes.push(`The Word copy couldn't be made: ${U instanceof Error?U.message:String(U)}`)}}return we}a(w,"savePdf"),await new Promise((C,D)=>{h.once("error",D),h.listen(e.port??0,"127.0.0.1",()=>{h.removeListener("error",D),C()})}),i=h.address().port;let A=`http://127.0.0.1:${i}`,N,S=new Promise(C=>N=C),k,T=a(async()=>{k&&clearInterval(k),u.abort(),await new Promise(C=>{h.close(()=>C()),h.closeAllConnections()}),N()},"close"),O=e.idleMs===void 0?6e4:e.idleMs;return O!==null&&(k=setInterval(()=>{Date.now()-o>O&&T()},Math.min(O,5e3))),{origin:A,url:`${A}/?t=${t}`,token:t,closed:S,close:T}}a(fm,"startService");x();import{createHash as yk}from"node:crypto";import{createWriteStream as bk}from"node:fs";import{mkdir as hm,readdir as wk,readFile as gm,rename as xk,rm as ym,stat as vk,utimes as kk,writeFile as bm}from"node:fs/promises";import{join as Xe}from"node:path";import{Readable as Ek}from"node:stream";import{pipeline as Ak}from"node:stream/promises";x();var mm="TCM1",uk=["reader","translator"],ck={reader:["own","p2t","pix2tex"],translator:["indictrans2"]};function dk(e,t){return typeof t=="string"&&ck[e].includes(t)}a(dk,"isModelKind");var Rl=/^[0-9A-Za-z][0-9A-Za-z.-]{0,59}$/,pk=/^[0-9A-Za-z][0-9A-Za-z._-]{0,79}$/,fk=/^[0-9a-f]{64}$/,mk=new TextEncoder;function hk(e){return typeof e=="string"&&uk.includes(e)}a(hk,"isModelEngine");function gk(e){let t=e;return typeof t=="object"&&t!==null&&t.v===1&&hk(t.engine)&&typeof t.version=="string"&&Rl.test(t.version)&&typeof t.label=="string"&&dk(t.engine,t.kind)&&typeof t.runtime=="string"&&typeof t.promotedAt=="number"&&Array.isArray(t.files)&&t.files.length>0&&t.files.every(n=>typeof n=="object"&&n!==null&&typeof n.name=="string"&&pk.test(n.name)&&Number.isInteger(n.bytes)&&n.bytes>0&&typeof n.sha256=="string"&&fk.test(n.sha256))&&new Set(t.files.map(n=>n.name)).size===t.files.length}a(gk,"isManifest");async function Ml(e,t){if(typeof e!="string"||e.length>64*1024)return{ok:!1,reason:"malformed"};let n=e.split(".");if(n.length!==4||n[0]!==mm)return{ok:!1,reason:"malformed"};let[,r,o,i]=n,s;try{s=JSON.parse(new TextDecoder().decode(gt(o)))}catch{return{ok:!1,reason:"malformed"}}if(!gk(s))return{ok:!1,reason:"malformed"};let l=Object.prototype.hasOwnProperty.call(t,r)?t[r]:void 0;if(!l)return{ok:!1,reason:"unknown_key"};let u;try{let c=await crypto.subtle.importKey("raw",gt(l),{name:"Ed25519"},!1,["verify"]);u=await crypto.subtle.verify({name:"Ed25519"},c,gt(i),mk.encode(`${mm}.${r}.${o}`))}catch(c){return c instanceof Error&&c.name==="NotSupportedError"?{ok:!1,reason:"unsupported"}:{ok:!1,reason:"bad_signature"}}return u?{ok:!0,manifest:s}:{ok:!1,reason:"bad_signature"}}a(Ml,"verifyManifest");var wm="offer.json",ps="ready.json",Sk=2;function Ol(e=process.env,t=process.platform,n="",r="reader"){return t==="win32"?Xe(e.LOCALAPPDATA??Xe(n||e.USERPROFILE||"","AppData","Local"),"LaTeX2Word","ocr-models",r):t==="darwin"?Xe(n||e.HOME||"","Library","Caches","LaTeX2Word","ocr-models",r):Xe(e.XDG_CACHE_HOME??Xe(n||e.HOME||"",".cache"),"latex2word","ocr-models",r)}a(Ol,"readerDir");async function _l(e){let t=e.fetch??fetch,n=e.dir,r=null,o=new Map,i=null,s=null,l=e.name??"reader",u=e.servePath??"/ocr/reader/";async function c(v){if(!v.model)return{offer:v,manifest:null};let w=await Ml(v.model.manifest,e.publicKeys);return{offer:v,manifest:w.ok?w.manifest:null}}a(c,"check");let d=a(v=>e.everyFile===!0||!v.name.startsWith("hand_"),"onDevice");async function p(){return(await wk(n,{withFileTypes:!0}).catch(()=>[])).filter(w=>w.isDirectory()&&Rl.test(w.name)).map(w=>w.name)}a(p,"versionFolders");try{r=await c(JSON.parse(await gm(Xe(n,wm),"utf8")))}catch{r=null}for(let v of await p())try{let w=await Ml(await gm(Xe(n,v,ps),"utf8"),e.publicKeys);w.ok&&w.manifest.version===v&&o.set(v,w.manifest)}catch{}function f(){let v=r?.offer,w=r?.manifest??null,A={offerAi:v?.offerAi??!1,unsureBelow:v?.unsureBelow??.7,...v?.beams!==void 0?{beams:v.beams}:{},...v?.batch!==void 0?{batch:v.batch}:{},version:w?.version??null,label:w?.label??null,kind:w?.kind??null,bytes:0,done:0,reason:null,files:null};if(!v)return{...A,state:"unavailable",reason:`TeXConverter hasn't been able to check for its ${l} yet. Connect to the internet once.`};if(!v.enabled)return{...A,state:"off"};if(!w)return{...A,state:"unavailable",reason:`This copy of TeXConverter couldn't check the ${l} it was offered, so it won't use it.`};if(w.runtime!==e.runtime)return{...A,state:"unavailable",reason:`The ${l} on offer needs a newer TeXConverter. Update the app to use it.`};let N=w.files.filter(d).reduce((S,k)=>S+k.bytes,0);return o.has(w.version)?{...A,state:"ready",bytes:N,done:N,files:`${u}${w.version}/`}:i?.version===w.version?{...A,state:"downloading",bytes:N,done:i.done}:s?.version===w.version?{...A,state:"failed",bytes:N,reason:s.reason}:{...A,state:"absent",bytes:N}}a(f,"status");async function m(){let v;try{let N=await t(e.offerUrl??`${e.serverUrl}/v1/ocr/reader`,{headers:e.headers,signal:AbortSignal.timeout(8e3)});if(!N.ok)return f();v=await N.json()}catch{return f()}let w=r?.manifest?.version;r=await c(v),await hm(n,{recursive:!0}),await bm(Xe(n,wm),JSON.stringify(v));let A=r.manifest?.version;return A&&A!==w&&o.has(A)&&await kk(Xe(n,A,ps),new Date,new Date).catch(()=>{}),f()}a(m,"refresh");async function h(v,w,A){let N=Xe(n,v.version);await hm(N,{recursive:!0});for(let S of v.files.filter(d)){let k=Xe(N,S.name),T=`${k}.partial`,O=await t(new URL(S.name,A).href,{signal:AbortSignal.timeout(30*6e4)});if(!O.ok||!O.body)throw new Error(`TeXConverter's server didn't send ${S.name} (${O.status}).`);let C=yk("sha256"),D=0,P=Ek.fromWeb(O.body).on("data",_=>{C.update(_),D+=_.length,i&&(i.done+=_.length)});if(await Ak(P,bk(T)),D!==S.bytes||C.digest("hex")!==S.sha256)throw await ym(T,{force:!0}),new Error(`${S.name} arrived damaged. Try again.`);await xk(T,k)}await bm(Xe(N,ps),w),o.set(v.version,v)}a(h,"download");async function g(v){let w=[];for(let A of await p()){if(A===v)continue;let N=await vk(Xe(n,A,ps)).then(S=>S.mtimeMs,()=>0);w.push({name:A,at:N})}w.sort((A,N)=>N.at-A.at);for(let A of w.filter((N,S)=>N.at===0||S>=Sk-1))o.delete(A.name),await ym(Xe(n,A.name),{recursive:!0,force:!0})}a(g,"prune");function y(){let v=f();if(v.state!=="absent"&&v.state!=="failed")return i?.promise??Promise.resolve(v);let w=r.manifest,A=r.offer.model;s=null;let N=h(w,A.manifest,A.files).then(()=>g(w.version)).catch(S=>{s={version:w.version,reason:S instanceof Error?S.message:String(S)}}).then(()=>(i=null,f()));return i={version:w.version,bytes:v.bytes,done:0,promise:N},N}a(y,"prepare");function E(v,w){return o.get(v)?.files.some(N=>N.name===w&&d(N))?Xe(n,v,w):null}return a(E,"file"),{status:f,refresh:m,prepare:y,file:E}}a(_l,"readerModels");x();import{createHash as Tk}from"node:crypto";import{existsSync as Ck}from"node:fs";import{mkdir as Nk,writeFile as Pk}from"node:fs/promises";import{availableParallelism as Ik}from"node:os";import{dirname as $k,join as Rk}from"node:path";import{Worker as Mk}from"node:worker_threads";import{randomBytes as Ok}from"node:crypto";x();var Ll={hi:{tag:"hin_Deva",iso:"hi"},mr:{tag:"mar_Deva",iso:"mr"},gu:{tag:"guj_Gujr",iso:"gu"},bn:{tag:"ben_Beng",iso:"bn"},pa:{tag:"pan_Guru",iso:"pa"},or:{tag:"ory_Orya",iso:"or"},ta:{tag:"tam_Taml",iso:"ta"},te:{tag:"tel_Telu",iso:"te"},kn:{tag:"kan_Knda",iso:"kn"},ml:{tag:"mal_Mlym",iso:"ml"}},yP=Object.fromEntries(Object.values(Ll).map(e=>[e.tag,e.iso])),bt=String.raw`\p{L}\p{M}\p{Nd}\p{Pc}`,Dk=String.raw`\p{Alphabetic}\p{Nd}\p{M}`,zt=String.raw`\p{Alphabetic}\p{M}`,Oo=String.raw`\p{N}`,Fe=a((e,t="gu")=>new RegExp(e,t),"re");var bP=Fe(String.raw`[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}`),wP=Fe(String.raw`(?Rt(e,"name",{value:t,configurable:!0});var $t=(e,t)=>{for(var r in t)Rt(e,r,{get:t[r],enumerable:!0})};import{parentPort as Zr}from"node:worker_threads";import{existsSync as At,readFileSync as Ne}from"node:fs";import{join as Ae}from"node:path";import{pathToFileURL as so}from"node:url";var ft={};$t(ft,{InferenceSession:()=>ve,TRACE:()=>We,TRACE_EVENT_BEGIN:()=>le,TRACE_EVENT_END:()=>ue,TRACE_FUNC_BEGIN:()=>ie,TRACE_FUNC_END:()=>ae,Tensor:()=>H,default:()=>fn,env:()=>C,registerBackend:()=>ge});import{createRequire as Jr}from"module";var ze={};$t(ze,{InferenceSession:()=>ve,TRACE:()=>We,TRACE_EVENT_BEGIN:()=>le,TRACE_EVENT_END:()=>ue,TRACE_FUNC_BEGIN:()=>ie,TRACE_FUNC_END:()=>ae,Tensor:()=>H,env:()=>C,registerBackend:()=>ge});var Le=new Map,fe=[],ge=u((e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let o=Le.get(e);if(o===void 0)Le.set(e,{backend:t,priority:r});else{if(o.priority>r)return;if(o.priority===r&&o.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let n=fe.indexOf(e);n!==-1&&fe.splice(n,1);for(let s=0;s{let t=Le.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(o){return r||(t.error=`${o}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},"tryResolveAndInitializeBackend"),vt=u(async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),o=r.length===0?fe:r,n,s=[],i=new Set;for(let l of o){let c=await Kr(l);typeof c=="string"?s.push({name:l,err:c}):(n||(n=c),n===c&&i.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${s.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of s)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let a=t.filter(l=>i.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:u((l,c)=>c==="executionProviders"?a:Reflect.get(l,c),"get")})]},"resolveBackendAndExecutionProviders");var xt="1.30.0";var St="warning",U={wasm:{},webgl:{},webgpu:{},versions:{common:xt},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);St=e}},get logLevel(){return St}};Object.defineProperty(U,"logLevel",{enumerable:!0});var C=U;var _t=u((e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let o=r.getContext("2d");if(o!=null){let n,s;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],s=e.dims[3]):(n=e.dims[3],s=e.dims[2]);let i=t?.format!==void 0?t.format:"RGB",a=t?.norm,l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));let p=s*n,f=0,d=p,m=p*2,w=-1;i==="RGBA"?(f=0,d=p,m=p*2,w=p*3):i==="RGB"?(f=0,d=p,m=p*2):i==="RBG"&&(f=0,m=p,d=p*2);for(let T=0;T{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),o;if(r!=null){let n,s,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],s=e.dims[1],i=e.dims[3]):(n=e.dims[3],s=e.dims[2],i=e.dims[1]);let a=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=s*n;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn\'t match input tensor dims");let d=4,m=0,w=1,T=2,y=3,g=0,h=f,E=f*2,A=-1;a==="RGBA"?(g=0,h=f,E=f*2,A=f*3):a==="RGB"?(g=0,h=f,E=f*2):a==="RBG"&&(g=0,E=f,h=f*2),o=r.createImageData(n,s);for(let $=0;${if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:o}=t,n=t.norm??{mean:255,bias:0},s,i;typeof n.mean=="number"?s=[n.mean,n.mean,n.mean,n.mean]:s=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let a=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*o,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,d=0,m=1,w=2,T=3,y=0,g=c,h=c*2,E=-1;a==="RGB"&&(f=3,d=0,m=1,w=2,T=-1),l==="RGBA"?E=c*3:l==="RBG"?(y=0,h=c,g=c*2):l==="BGR"&&(h=0,g=c,y=c*2);for(let $=0;${let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,o=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,s=typeof e=="string",i,a=t??{},l=u(()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},"createCanvas"),c=u(p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null,"createCanvasContext");if(r){let p=l();p.width=e.width,p.height=e.height;let f=c(p);if(f!=null){let d=e.height,m=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,m=t.resizedWidth),t!==void 0){if(a=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=d,a.width=m}else a.tensorFormat="RGBA",a.height=d,a.width=m;f.drawImage(e,0,0),i=f.getImageData(0,0,m,d).data}else throw new Error("Can not access image data")}else if(o){let p,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(p=t.resizedHeight,f=t.resizedWidth):(p=e.height,f=e.width),t!==void 0&&(a=t),a.format="RGBA",a.height=p,a.width=f,t!==void 0){let d=l();d.width=f,d.height=p;let m=c(d);if(m!=null)m.putImageData(e,0,0),i=m.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let f=c(p);if(f!=null){let d=e.height,m=e.width;return f.drawImage(e,0,0,m,d),i=f.getImageData(0,0,m,d).data,a.height=d,a.width=m,Ve(i,a)}else throw new Error("Can not access image data")}else{if(s)return new Promise((p,f)=>{let d=l(),m=c(d);if(!e||!m)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{d.width=w.width,d.height=w.height,m.drawImage(w,0,0,d.width,d.height);let T=m.getImageData(0,0,d.width,d.height);a.height=d.height,a.width=d.width,p(Ve(T.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ve(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},"tensorFromImage"),It=u((e,t)=>{let{width:r,height:o,download:n,dispose:s}=t,i=[1,o,r,4];return new G({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:s})},"tensorFromTexture"),Nt=u((e,t)=>{let{dataType:r,dims:o,download:n,dispose:s}=t;return new G({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:o,download:n,dispose:s})},"tensorFromGpuBuffer"),Lt=u((e,t)=>{let{dataType:r,dims:o,download:n,dispose:s}=t;return new G({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:o,download:n,dispose:s})},"tensorFromMLTensor"),Pt=u((e,t,r)=>new G({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),"tensorFromPinnedBuffer");var de=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),$e=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),kt=!1,Mt=u(()=>{if(!kt){kt=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,o=typeof r<"u"&&r.from;e&&(de.set("int64",BigInt64Array),$e.set(BigInt64Array,"int64")),t&&(de.set("uint64",BigUint64Array),$e.set(BigUint64Array,"uint64")),o?(de.set("float16",r),$e.set(r,"float16")):de.set("float16",Uint16Array)}},"checkTypedArray");var Ut=u(e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new G(e.type,e.data,t);case"cpu-pinned":return new G({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new G({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new G({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new G({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}},"tensorReshape");var G=class{static{u(this,"Tensor")}constructor(t,r,o){Mt();let n,s;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,s=t.dims,t.location){case"cpu-pinned":{let a=de.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location \'${this.dataLocation}\'`)}else{let a,l;if(typeof t=="string")if(n=t,l=o,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor\'s data must be a string array.");a=r}else{let c=de.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?a=c.from(r,BigInt):a=c.from(r)}else if(r instanceof c)a=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor\'s data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor\'s data must be type of ${c}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof t[0];if(c==="string")n="string",a=t;else if(c==="boolean")n="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(t);else{let c=$e.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=c,a=t}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor\'s dims must be a number array");s=l,this.cpuData=a,this.dataLocation="cpu"}let i=Ut(s);if(this.cpuData&&i!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor\'s size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=i}static async fromImage(t,r){return Ct(t,r)}static fromTexture(t,r){return It(t,r)}static fromGpuBuffer(t,r){return Nt(t,r)}static fromMLTensor(t,r){return Lt(t,r)}static fromPinnedBuffer(t,r,o){return Pt(t,r,o)}toDataURL(t){return _t(this,t)}toImageData(t){return Ot(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Dt(this,t)}};var H=G;var We=u((e,t)=>{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||console.timeStamp(`${e}::ORT::${t}`)},"TRACE"),Bt=u((e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],o=!1;for(let n=0;n{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||Bt("BEGIN",e)},"TRACE_FUNC_BEGIN"),ae=u(e=>{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||Bt("END",e)},"TRACE_FUNC_END"),le=u(e=>{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||console.time(`ORT::${e}`)},"TRACE_EVENT_BEGIN"),ue=u(e=>{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||console.timeEnd(`ORT::${e}`)},"TRACE_EVENT_END");var Pe=class e{static{u(this,"InferenceSession")}constructor(t){this.handler=t}async run(t,r,o){ie(),le("InferenceSession.run");let n={},s={};if(typeof t!="object"||t===null||t instanceof H||Array.isArray(t))throw new TypeError("\'feeds\' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof H)throw new TypeError("\'fetches\' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("\'fetches\' cannot be an empty array.");i=!1;for(let c of r){if(typeof c!="string")throw new TypeError("\'fetches\' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`\'fetches\' contains invalid output name: ${c}.`);n[c]=null}if(typeof o=="object"&&o!==null)s=o;else if(typeof o<"u")throw new TypeError("\'options\' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let d=r[f];(d===null||d instanceof H)&&(c=!0,i=!1,n[f]=d)}if(c){if(typeof o=="object"&&o!==null)s=o;else if(typeof o<"u")throw new TypeError("\'options\' must be an object.")}else s=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be \'fetches\' or \'options\'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input \'${c}\' is missing in \'feeds\'.`);if(i)for(let c of this.outputNames)n[c]=null;let a=await this.handler.run(t,n,s),l={};for(let c in a)if(Object.hasOwnProperty.call(a,c)){let p=a[c];p instanceof H?l[c]=p:l[c]=new H(p.type,p.data,p.dims)}return ue("InferenceSession.run"),ae(),l}async release(){return this.handler.dispose()}static async create(t,r,o,n){ie(),le("InferenceSession.create");let s,i={};if(typeof t=="string"){if(s=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("\'options\' must be an object.")}else if(t instanceof Uint8Array){if(s=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("\'options\' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let p=t,f=0,d=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("\'byteOffset\' must be an integer.");if(f<0||f>=p.byteLength)throw new RangeError(`\'byteOffset\' is out of range [0, ${p.byteLength}).`);if(d=t.byteLength-f,typeof o=="number"){if(d=o,!Number.isSafeInteger(d))throw new RangeError("\'byteLength\' must be an integer.");if(d<=0||f+d>p.byteLength)throw new RangeError(`\'byteLength\' is out of range (0, ${p.byteLength-f}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("\'options\' must be an object.")}else if(typeof o<"u")throw new TypeError("\'byteLength\' must be a number.")}else if(typeof r<"u")throw new TypeError("\'options\' must be an object.");s=new Uint8Array(p,f,d)}else throw new TypeError("Unexpected argument[0]: must be \'path\' or \'buffer\'.");let[a,l]=await vt(i),c=await a.createInferenceSessionHandler(s,l);return ue("InferenceSession.create"),ae(),new e(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}};var ve=Pe;var he=Jr(import.meta.url),it=Object.defineProperty,Xr=Object.getOwnPropertyDescriptor,Qr=Object.getOwnPropertyNames,en=Object.prototype.hasOwnProperty,rt=(e=>typeof he<"u"?he:typeof Proxy<"u"?new Proxy(e,{get:u((t,r)=>(typeof he<"u"?he:t)[r],"get")}):e)(function(e){if(typeof he<"u")return he.apply(this,arguments);throw Error(\'Dynamic require of "\'+e+\'" is not supported\')}),Z=u((e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(o){throw r=[o],o}},"C"),tn=u((e,t)=>{for(var r in t)it(e,r,{get:t[r],enumerable:!0})},"Ot"),rn=u((e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Qr(t))!en.call(e,n)&&n!==r&&it(e,n,{get:u(()=>t[n],"get"),enumerable:!(o=Xr(t,n))||o.enumerable});return e},"It"),nn=u(e=>rn(it({},"__esModule",{value:!0}),e),"Tt"),be,at=Z(()=>{"use strict";be=!!(typeof process<"u"&&process.versions&&process.versions.node)}),He,jt,Ft,ne,rr,Ze,Gt,Vt,Wt,zt,qe,nr,or=Z(()=>{"use strict";at(),He=be||typeof location>"u"?void 0:location.origin,jt=import.meta.url>"file:"&&import.meta.url<"file;",Ft=u(()=>{if(!be){if(jt){let e=URL;return new URL(new e("ort.node.min.mjs",import.meta.url).href,He).href}return import.meta.url}},"Bt"),ne=Ft(),rr=u(()=>{if(ne&&!ne.startsWith("blob:"))return ne.substring(0,ne.lastIndexOf("/")+1)},"xe"),Ze=u((e,t)=>{try{let r=t??ne;return(r?new URL(e,r):new URL(e)).origin===He}catch{return!1}},"ve"),Gt=u((e,t)=>{let r=t??ne;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},"_t"),Vt=u((e,t)=>`${t??"./"}${e}`,"Pt"),Wt=u(async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},"Dt"),zt=u(async e=>(await import(e)).default,"vt"),qe=void 0,nr=u(async(e,t,r,o)=>{let n=qe&&!(e||t);if(n)if(ne)n=Ze(ne)||o&&!r;else if(o&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,qe];{let s="ort-wasm-simd-threaded.mjs",i=e??Gt(s,t),a=!be&&r&&i&&!Ze(i,t),l=a?await Wt(i):i??Vt(s,t);return[a?l:void 0,await zt(l)]}},"Ce")}),Ye,ke,xe,Ke,Ht,Zt,qt,sr,I,Se=Z(()=>{"use strict";or(),ke=!1,xe=!1,Ke=!1,Ht=u(()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},"Ut"),Zt=u(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},"At"),qt=u(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},"xt"),sr=u(async e=>{if(ke)return Promise.resolve();if(xe)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Ke)throw new Error("previous call to \'initializeWebAssembly()\' failed.");xe=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!qt())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Zt())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let o=Ht();r>1&&!o&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let n=e.wasmPaths,s=typeof n=="string"?n:void 0,i=n?.mjs,a=i?.href??i,l=n?.wasm,c=l?.href??l,p=e.wasmBinary,[f,d]=await nr(a,s,r>1,!!p||!!c),m=!1,w=[];if(t>0&&w.push(new Promise(T=>{setTimeout(()=>{m=!0,T()},t)})),w.push(new Promise((T,y)=>{let g={numThreads:r};if(p)g.wasmBinary=p,g.locateFile=h=>h;else if(c||s)g.locateFile=h=>c??s+h;else if(a&&a.indexOf("blob:")!==0)g.locateFile=h=>new URL(h,a).href;else if(f){let h=rr();h&&(g.locateFile=E=>h+E)}d(g).then(h=>{xe=!1,ke=!0,Ye=h,T(),f&&URL.revokeObjectURL(f)},h=>{xe=!1,Ke=!0,y(h)})})),await Promise.race(w),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},"We"),I=u(()=>{if(ke&&Ye)return Ye;throw new Error("WebAssembly is not initialized yet.")},"E")}),q,De,S,lt=Z(()=>{"use strict";Se(),q=u((e,t)=>{let r=I(),o=r.lengthBytesUTF8(e)+1,n=r._malloc(o);return r.stringToUTF8(e,n,o),t.push(n),n},"A"),De=u((e,t,r,o)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,s])=>{let i=t?t+n:n;if(typeof s=="object")De(s,i+".",r,o);else if(typeof s=="string"||typeof s=="number")o(i,s.toString());else if(typeof s=="boolean")o(i,s?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof s}`)})},"Q"),S=u(e=>{let t=I(),r=t.stackSave();try{let o=t.PTR_SIZE,n=t.stackAlloc(2*o);t._OrtGetLastError(n,n+o);let s=Number(t.getValue(n,o===4?"i32":"i64")),i=t.getValue(n+o,"*"),a=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${s}, ERROR_MESSAGE: ${a}`)}finally{t.stackRestore(r)}},"g")}),ir,on=Z(()=>{"use strict";Se(),lt(),ir=u(e=>{let t=I(),r=0,o=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let s=0;return e?.tag!==void 0&&(s=q(e.tag,o)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&S("Can\'t create run options."),e?.extra!==void 0&&De(e.extra,"",new WeakSet,(i,a)=>{let l=q(i,o),c=q(a,o);t._OrtAddRunConfigEntry(r,l,c)!==0&&S(`Can\'t set a run config entry: ${i} - ${a}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseRunOptions(r),o.forEach(i=>t._free(i)),s}},"ke")}),Yt,Kt,Jt,pe,Xt,ar,sn=Z(()=>{"use strict";Se(),lt(),Yt=u(e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},"Ct"),Kt=u(e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},"Mt"),Jt=u(e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},"Wt"),pe=u((e,t,r,o)=>{let n=q(t,o),s=q(r,o);I()._OrtAddSessionConfigEntry(e,n,s)!==0&&S(`Can\'t set a session config entry: ${t} - ${r}.`)},"q"),Xt=u(async(e,t,r)=>{let o=t.executionProviders;for(let n of o){let s=typeof n=="string"?n:n.name,i=[];switch(s){case"webnn":if(s="WEBNN",pe(e,"session.disable_quant_qdq","1",r),pe(e,"session.disable_qdq_constant_folding","1",r),typeof n!="string"){let f=n?.deviceType;f&&pe(e,"deviceType",f,r)}break;case"webgpu":if(s="JS",typeof n!="string"){let f=n;if(f?.preferredLayout){if(f.preferredLayout!=="NCHW"&&f.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${f.preferredLayout}`);pe(e,"preferredLayout",f.preferredLayout,r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=q(s,r),l=i.length,c=0,p=0;if(l>0){c=I()._malloc(l*I().PTR_SIZE),r.push(c),p=I()._malloc(l*I().PTR_SIZE),r.push(p);for(let f=0;f{let t=I(),r=0,o=[],n=e||{};Jt(n);try{let s=Yt(n.graphOptimizationLevel??"all"),i=Kt(n.executionMode??"sequential"),a=typeof n.logId=="string"?q(n.logId,o):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?q(n.optimizedModelFilePath,o):0;if(r=t._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,i,!!n.enableProfiling,0,a,l,c,p),r===0&&S("Can\'t create session options."),n.executionProviders&&await Xt(r,n,o),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);pe(r,"enableGraphCapture",n.enableGraphCapture.toString(),o)}if(n.freeDimensionOverrides)for(let[f,d]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let m=q(f,o);t._OrtAddFreeDimensionOverride(r,m,d)!==0&&S(`Can\'t set a free dimension override: ${f} - ${d}.`)}return n.extra!==void 0&&De(n.extra,"",new WeakSet,(f,d)=>{pe(r,f,d,o)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&S("Can\'t release session options."),o.forEach(i=>t._free(i)),s}},"Re")}),ye,Ue,we,lr,ur,ut,ct,cr,fr=Z(()=>{"use strict";ye=u(e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},"J"),Ue=u(e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},"ae"),we=u((e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],o=typeof t=="number"?t:t.reduce((n,s)=>n*s,1);return r>0?Math.ceil(o*r):void 0},"Y"),lr=u(e=>{switch(e){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},"Ge"),ur=u(e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},"je"),ut=u(e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4","ie"),ct=u(e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4","ue"),cr=u(e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}},"$e")}),Be,dr=Z(()=>{"use strict";at(),Be=u(async e=>{if(typeof e=="string")if(be)try{let{readFile:t}=rt("node:fs/promises");return new Uint8Array(await t(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let{createReadStream:r}=rt("node:fs"),o=r(e),n=[];for await(let s of o)n.push(s);return new Uint8Array(Buffer.concat(n))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),o=r?parseInt(r,10):0;if(o<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),s;try{s=new ArrayBuffer(o)}catch(a){if(a instanceof RangeError){let l=Math.ceil(o/65536);s=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let i=0;for(;;){let{done:a,value:l}=await n.read();if(a)break;let c=l.byteLength;new Uint8Array(s,i,c).set(l),i+=c}return new Uint8Array(s,0,o)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)},"ee")}),Qt,pr,mr,me,er,Je,nt,gr,hr,Xe,yr,wr,an=Z(()=>{"use strict";on(),sn(),fr(),Se(),lt(),dr(),Qt=u((e,t)=>{I()._OrtInit(e,t)!==0&&S("Can\'t initialize onnxruntime.")},"Ft"),pr=u(async e=>{Qt(e.wasm.numThreads,ur(e.logLevel))},"Je"),mr=u(async(e,t)=>{I().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let n=e.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:n}),!r)throw new Error(\'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.\')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},"Ye"),me=new Map,er=u(e=>{let t=I(),r=t.stackSave();try{let o=t.PTR_SIZE,n=t.stackAlloc(2*o);t._OrtGetInputOutputCount(e,n,n+o)!==0&&S("Can\'t get session input/output count.");let s=o===4?"i32":"i64";return[Number(t.getValue(n,s)),Number(t.getValue(n+o,s))]}finally{t.stackRestore(r)}},"Rt"),Je=u((e,t)=>{let r=I(),o=r.stackSave(),n=0;try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetInputOutputMetadata(e,t,i,i+s)!==0&&S("Can\'t get session input/output metadata.");let a=Number(r.getValue(i,"*"));n=Number(r.getValue(i+s,"*"));let l=r.HEAP32[n/4];if(l===0)return[a,0];let c=r.HEAPU32[n/4+1],p=[];for(let f=0;f{let t=I(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},"Ee"),gr=u(async(e,t)=>{let r,o,n=I();Array.isArray(e)?[r,o]=e:e.buffer===n.HEAPU8.buffer?[r,o]=[e.byteOffset,e.byteLength]:[r,o]=nt(e);let s=0,i=0,a=0,l=[],c=[],p=[];try{if([i,l]=await ar(t),t?.externalData&&n.mountExternalData){let E=[];for(let A of t.externalData){let $=typeof A=="string"?A:A.path,_=typeof A=="string"?A:A.data;E.push(Be(_).then(N=>{n.mountExternalData($,N)}))}await Promise.all(E)}for(let E of t?.executionProviders??[])if((typeof E=="string"?E:E.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof E!="string"){let A=E,$=A?.context,_=A?.gpuDevice,N=A?.deviceType,F=A?.powerPreference;$?n.currentContext=$:_?n.currentContext=await n.webnnCreateMLContext(_):n.currentContext=await n.webnnCreateMLContext({deviceType:N,powerPreference:F})}else n.currentContext=await n.webnnCreateMLContext();break}s=await n._OrtCreateSession(r,o,i),n.webgpuOnCreateSession?.(s),s===0&&S("Can\'t create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(s,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,d]=er(s),m=!!t?.enableGraphCapture,w=[],T=[],y=[],g=[],h=[];for(let E=0;En._OrtFree(d)),p.forEach(d=>n._OrtFree(d)),a!==0&&n._OrtReleaseBinding(a)!==0&&S("Can\'t release IO binding."),s!==0&&n._OrtReleaseSession(s)!==0&&S("Can\'t release session."),f}finally{n._free(r),i!==0&&n._OrtReleaseSessionOptions(i)!==0&&S("Can\'t release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},"Ze"),hr=u(e=>{let t=I(),r=me.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,n,s,i,a]=r;i&&(a&&t._OrtClearBoundOutputs(i.handle)!==0&&S("Can\'t clear bound outputs."),t._OrtReleaseBinding(i.handle)!==0&&S("Can\'t release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),n.forEach(l=>t._OrtFree(l)),s.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(o)!==0&&S("Can\'t release session."),me.delete(e)},"Xe"),Xe=u(async(e,t,r,o,n,s,i=!1)=>{if(!e){t.push(0);return}let a=I(),l=a.PTR_SIZE,c=e[0],p=e[1],f=e[3],d=f,m,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let g=e[2].gpuBuffer;w=we(ye(c),p);{let h=a.jsepRegisterBuffer;if(!h)throw new Error(\'Tensor location "gpu-buffer" is not supported without using WebGPU.\');m=h(o,s,g,w)}}else if(f==="ml-tensor"){let g=e[2].mlTensor;w=we(ye(c),p);let h=a.webnnRegisterMLTensor;if(!h)throw new Error(\'Tensor location "ml-tensor" is not supported without using WebNN.\');m=h(o,g,ye(c),p)}else{let g=e[2];if(Array.isArray(g)){w=l*g.length,m=a._malloc(w),r.push(m);for(let h=0;ha.setValue(y+E*l,h,l===4?"i32":"i64"));let g=a._OrtCreateTensor(ye(c),m,w,y,p.length,cr(d));g===0&&S(`Can\'t create tensor for input/output. session=${o}, index=${s}.`),t.push(g)}finally{a.stackRestore(T)}},"qe"),yr=u(async(e,t,r,o,n,s)=>{let i=I(),a=i.PTR_SIZE,l=me.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],p=l[1],f=l[2],d=l[3],m=l[4],w=l[5],T=t.length,y=o.length,g=0,h=[],E=[],A=[],$=[],_=[],N=i.stackSave(),F=i.stackAlloc(T*a),J=i.stackAlloc(T*a),se=i.stackAlloc(y*a),ee=i.stackAlloc(y*a);try{[g,h]=ir(s),le("wasm prepareInputOutputTensor");for(let b=0;bB*L,1);R=Ue(P);let Re=d?.outputPreferredLocations[o[b]];if(R==="string"){if(Re==="gpu-buffer"||Re==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let B=[];for(let L=0;L0){let B=i.jsepGetBuffer;if(!B)throw new Error(\'preferredLocation "gpu-buffer" is not supported without using WebGPU.\');let L=B(M),re=we(P,Q);if(re===void 0||!ut(R))throw new Error(`Unsupported data type: ${R}`);z=!0,v.push([R,X,{gpuBuffer:L,download:i.jsepCreateDownloader(L,re,R),dispose:u(()=>{i._OrtReleaseTensor(x)!==0&&S("Can\'t release tensor.")},"dispose")},"gpu-buffer"])}else if(Re==="ml-tensor"&&Q>0){let B=i.webnnEnsureTensor,L=i.webnnIsGraphInputOutputTypeSupported;if(!B||!L)throw new Error(\'preferredLocation "ml-tensor" is not supported without using WebNN.\');if(we(P,Q)===void 0||!ct(R))throw new Error(`Unsupported data type: ${R}`);if(!L(e,R,!1))throw new Error(`preferredLocation "ml-tensor" for ${R} output is not supported by current WebNN Context.`);let re=await B(e,M,P,X,!1);z=!0,v.push([R,X,{mlTensor:re,download:i.webnnCreateMLTensorDownloader(M,R),dispose:u(()=>{i.webnnReleaseTensorId(M),i._OrtReleaseTensor(x)},"dispose")},"ml-tensor"])}else if(Re==="ml-tensor-cpu-output"&&Q>0){let B=i.webnnCreateMLTensorDownloader(M,R)(),L=v.length;z=!0,O.push((async()=>{let re=[L,await B];return i.webnnReleaseTensorId(M),i._OrtReleaseTensor(x),re})()),v.push([R,X,[],"cpu"])}else{let B=lr(R),L=new B(Q);new Uint8Array(L.buffer,L.byteOffset,L.byteLength).set(i.HEAPU8.subarray(M,M+L.byteLength)),v.push([R,X,L,"cpu"])}}finally{i.stackRestore(D),R==="string"&&M&&i._free(M),z||i._OrtReleaseTensor(x)}}d&&!m&&(i._OrtClearBoundOutputs(d.handle)!==0&&S("Can\'t clear bound outputs."),me.set(e,[c,p,f,d,m,!1]));for(let[b,x]of await Promise.all(O))v[b][2]=x;return ue("wasm ProcessOutputTensor"),v}finally{i.webnnOnRunEnd?.(c),i.stackRestore(N),E.forEach(W=>i._OrtReleaseTensor(W)),A.forEach(W=>i._OrtReleaseTensor(W)),$.forEach(W=>i._free(W)),g!==0&&i._OrtReleaseRunOptions(g),h.forEach(W=>i._free(W))}},"Ke"),wr=u(e=>{let t=I(),r=me.get(e);if(!r)throw new Error("invalid session id");let o=r[0],n=t._OrtEndProfiling(o);n===0&&S("Can\'t get an profile file name."),t._OrtFree(n)},"Qe")}),Me,Qe,et,br,Er,Tr,Ar,Rr,$r,vr,xr=Z(()=>{"use strict";an(),Se(),or(),Me=!1,Qe=!1,et=!1,br=u(async()=>{if(!Qe){if(Me)throw new Error("multiple calls to \'initWasm()\' detected.");if(et)throw new Error("previous call to \'initWasm()\' failed.");Me=!0;try{await sr(C.wasm),await pr(C),Qe=!0}catch(e){throw et=!0,e}finally{Me=!1}}},"nt"),Er=u(async e=>{await mr(C,e)},"ot"),Tr=u(async e=>nt(e),"st"),Ar=u(async(e,t)=>gr(e,t),"at"),Rr=u(async e=>{hr(e)},"it"),$r=u(async(e,t,r,o,n,s)=>yr(e,t,r,o,n,s),"ut"),vr=u(async e=>{wr(e)},"ct")}),tt,tr,Sr,ln=Z(()=>{"use strict";xr(),fr(),at(),dr(),tt=u((e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},"pt"),tr=u(e=>{switch(e[3]){case"cpu":return new H(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ut(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:o,dispose:n}=e[2];return H.fromGpuBuffer(r,{dataType:t,dims:e[1],download:o,dispose:n})}case"ml-tensor":{let t=e[0];if(!ct(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:o,dispose:n}=e[2];return H.fromMLTensor(r,{dataType:t,dims:e[1],download:o,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},"Gt"),Sr=class{static{u(this,"ce")}async fetchModelAndCopyToWasmMemory(e){return Tr(await Be(e))}async loadModel(e,t){ie();let r;typeof e=="string"?be?r=await Be(e):r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Ar(r,t),ae()}async dispose(){return Rr(this.sessionId)}async run(e,t,r){ie();let o=[],n=[];Object.entries(e).forEach(f=>{let d=f[0],m=f[1],w=this.inputNames.indexOf(d);if(w===-1)throw new Error(`invalid input \'${d}\'`);o.push(m),n.push(w)});let s=[],i=[];Object.entries(t).forEach(f=>{let d=f[0],m=f[1],w=this.outputNames.indexOf(d);if(w===-1)throw new Error(`invalid output \'${d}\'`);s.push(m),i.push(w)});let a=o.map((f,d)=>tt(f,()=>`input "${this.inputNames[n[d]]}"`)),l=s.map((f,d)=>f?tt(f,()=>`output "${this.outputNames[i[d]]}"`):null),c=await $r(this.sessionId,n,a,i,l,r),p={};for(let f=0;fst,"OnnxruntimeWebAssemblyBackend"),initializeFlags:u(()=>ot,"initializeFlags"),wasmBackend:u(()=>Or,"wasmBackend")});var ot,st,Or,un=Z(()=>{"use strict";xr(),ln(),ot=u(()=>{(typeof C.wasm.initTimeout!="number"||C.wasm.initTimeout<0)&&(C.wasm.initTimeout=0);let e=C.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \\`false\\` and ignore SIMD feature checking.`),C.wasm.simd=!1),typeof C.wasm.proxy!="boolean"&&(C.wasm.proxy=!1),typeof C.wasm.trace!="boolean"&&(C.wasm.trace=!1),typeof C.wasm.numThreads!="number"||!Number.isInteger(C.wasm.numThreads)||C.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)C.wasm.numThreads=1;else{let t=typeof navigator>"u"?rt("node:os").cpus().length:navigator.hardwareConcurrency;C.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},"mt"),st=class{static{u(this,"fe")}async init(e){ot(),await br(),await Er(e)}async createInferenceSessionHandler(e,t){let r=new Sr;return await r.loadModel(e,t),r}},Or=new st}),cn="1.30.0",fn=ze;{let e=(un(),nn(_r)).wasmBackend;ge("cpu",e,10),ge("wasm",e,10)}Object.defineProperty(C.versions,"web",{value:cn,enumerable:!0});var je={hi:{tag:"hin_Deva",iso:"hi"},mr:{tag:"mar_Deva",iso:"mr"},gu:{tag:"guj_Gujr",iso:"gu"},bn:{tag:"ben_Beng",iso:"bn"},pa:{tag:"pan_Guru",iso:"pa"},or:{tag:"ory_Orya",iso:"or"},ta:{tag:"tam_Taml",iso:"ta"},te:{tag:"tel_Telu",iso:"te"},kn:{tag:"kan_Knda",iso:"kn"},ml:{tag:"mal_Mlym",iso:"ml"}},dn=Object.fromEntries(Object.values(je).map(e=>[e.tag,e.iso])),Y=String.raw`\\p{L}\\p{M}\\p{Nd}\\p{Pc}`,pn=String.raw`\\p{Alphabetic}\\p{Nd}\\p{M}`,oe=String.raw`\\p{Alphabetic}\\p{M}`,_e=String.raw`\\p{N}`,j=u((e,t="gu")=>new RegExp(e,t),"re"),mn=[[/\\r/gu,""],[/\\(\\s*/gu,"("],[/\\s*\\)/gu,")"],[/\\s:\\s?/gu,":"],[/\\s;\\s?/gu,";"],[/[`\xB4\u2018\u201A\u2019]/gu,"\'"],[/[\u201E\u201C\u201D\xAB\xBB]/gu,\'"\'],[/[\u2013\u2014]/gu,"-"],[/\\.\\.\\./gu,"..."],[/ %/gu,"%"],[/n\xBA /gu,"n\\xBA "],[/ \xBAC/gu," \\xBAC"],[/ ([?!;])/gu,"$1"],[/, /gu,", "]];function gn(e){for(let[t,r]of mn)e=e.replace(t,r);return e=e.replace(/[ ]{2,}/gu," "),e=e.replace(/\\) ([.!:?;,])/gu,")$1"),e=e.replace(j(String.raw`(\\p{Nd}) %`),"$1%"),e=e.replace(/"([,.]+)/gu,\'"$1\'),e=e.replace(j(String.raw`(\\p{Nd}) (\\p{Nd})`),"$1.$2"),e.trim()}u(gn,"puncNorm");var hn=[2534,2790,3302,2406,1632,44016,2918,2662,7248,1776,3174];function yn(e){let t="";for(let r of e){let o=r.codePointAt(0),n=hn.find(s=>o>=s&&o<=s+9);t+=n!==void 0&&o!==3174?String(o-n):r}return t}u(yn,"asciiDigits");var wn=j(String.raw`[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}`),Cr=j(String.raw`(?`,`< ID${e} >`,`[ID${e}]`,`[ ID${e} ]`,`[ID ${e}]`,``,`< id${e} >`,`[id${e}]`,`[ id${e} ]`,`[id ${e}]`,``,`< ${r}${e} >`,`< ${r} ${e} >`,`<${r} ${e}]`,`< ${r} ${e} ]`,`[${r}${e}]`,`[${r} ${e}]`,`[ ${r}${e} ]`,`[ ${r} ${e} ]`,`${r} ${e}`,`${r}${e}`);return t}u(Tn,"placeholderForms");function An(e){let t=new Map,r=1;for(let o of[wn,Cr,Ir,bn]){let n=[...new Set([...e.matchAll(o)].map(s=>s[0]))];for(let s of n)if(!(o===Cr&&s.replace(/\\./g,"").length<4)&&!(o===Ir&&s.replace(/[ .:]/g,"").length<4)){for(let i of Tn(r))t.set(i,s);e=e.split(s).join(``),r++}}return e=e.replace(/\\s+/gu," ").replace(/>\\//g,">").replace(/\\]\\//g,"]"),{text:e,placeholders:[...t]}}u(An,"wrapPlaceholders");var Rn=[[/\\r/gu,""],[/\\(/gu," ("],[/\\)/gu,") "],[/ +/gu," "],[/\\) ([.!:?;,])/gu,")$1"],[/\\( /gu,"("],[/ \\)/gu,")"],[j(String.raw`(\\p{Nd}) %`),"$1%"],[/ :/gu,":"],[/ ;/gu,";"],[/`/gu,"\'"],[/\'\'/gu,\' " \'],[/\u201E/gu,\'"\'],[/\u201C/gu,\'"\'],[/\u201D/gu,\'"\'],[/\u2013/gu,"-"],[/\u2014/gu," - "],[/ +/gu," "],[/\xB4/gu,"\'"],[/([a-zA-Z])\u2018([a-zA-Z])/gu,"$1\'$2"],[/([a-zA-Z])\u2019([a-zA-Z])/gu,"$1\'$2"],[/\u2018/gu,"\'"],[/\u201A/gu,"\'"],[/\u2019/gu,"\'"],[/\'\'/gu,\'"\'],[/\xB4\xB4/gu,\'"\'],[/\u2026/gu,"..."],[/\\u00A0\xAB\\u00A0/gu,\'"\'],[/\xAB\\u00A0/gu,\'"\'],[/\xAB/gu,\'"\'],[/\\u00A0\xBB\\u00A0/gu,\'"\'],[/\\u00A0\xBB/gu,\'"\'],[/\xBB/gu,\'"\'],[/\\u00A0%/gu,"%"],[/n\xBA\\u00A0/gu,"n\\xBA "],[/\\u00A0:/gu,":"],[/\\u00A0\xBAC/gu," \\xBAC"],[/\\u00A0cm/gu," cm"],[/\\u00A0\\?/gu,"?"],[/\\u00A0!/gu,"!"],[/\\u00A0;/gu,";"],[/,\\u00A0/gu,", "],[/ +/gu," "],[/"([,.]+)/gu,\'$1"\'],[j(String.raw`(\\p{Nd})\\u00A0(\\p{Nd})`),"$1.$2"]];function $n(e){for(let[t,r]of Rn)e=e.replace(t,r);return e.trim()}u($n,"mosesNormalize");var vn=new Set(["A","Adj","Adm","Adv","Apr","Art #NUMERIC_ONLY#","Asst","Aug","B","Bart","Bldg","Brig","Bros","C","Capt","Cmdr","Col","Comdr","Con","Corp","Cpl","D","DR","Dec","Dr","Drs","E","Ens","F","Feb","G","Gen","Gov","H","Hon","Hosp","Hr","I","Insp","J","Jan","Jul","Jun","K","L","Lt","M","MM","MR","MRS","MS","Maj","Mar","Messrs","Mlle","Mme","Mr","Mrs","Ms","Msgr","N","No #NUMERIC_ONLY#","Nos","Nov","Nr","O","Oct","Op","Ord","P","Pfc","Ph","Prof","Pvt","Q","R","Rep","Reps","Res","Rev","Rs","Rt","S","Sen","Sens","Sep","Sfc","Sgt","Sr","St","Supt","Surg","T","U","V","W","X","Y","Z","e.g","i.e","pp #NUMERIC_ONLY#","rev","v","vs"]),Nr=new Set(["Art","No","pp"]),xn=j(String.raw`([^${pn}\\s.\'${"`"},\\-])`),Sn=[[j(String.raw`([^${_e}])[,]`),"$1 , "],[j(String.raw`[,]([^${_e}])`)," , $1"],[j(String.raw`([${_e}])[,]$`),"$1 , "]],_n=[[j(String.raw`([^${oe}])[\']([^${oe}])`),"$1 \' $2"],[j(String.raw`([^${oe}${_e}])[\']([${oe}])`),"$1 \' $2"],[j(String.raw`([${oe}])[\']([^${oe}])`),"$1 \' $2"],[j(String.raw`([${oe}])[\']([${oe}])`),"$1 \'$2"],[j(String.raw`([${_e}])[\']([s])`),"$1 \'$2"]],On=new RegExp("^\\\\p{Lowercase}$","u"),Cn=j(String.raw`[${oe}]`,"u");function In(e){return e.replace(/\\.{2,}/g,(t,r)=>{let o=" "+"DOT".repeat(t.length)+"MULTI";return r+t.length".".repeat((t.length-5)/3))}u(Nn,"restoreMultidots");function Lr(e,t){for(let[r,o]of t)e=e.replace(r,o);return e}u(Lr,"applyAll");function Ln(e){let t=e.split(/\\s+/u).filter(r=>r!=="");for(let r=0;rCn.test(i))||vn.has(n)&&!Nr.has(n)||r!==t.length-1&&s&&On.test([...s][0])||Nr.has(n)&&r+1n!=="").join(" ").trim(),{prepared:`eng_Latn ${je[t].tag} ${r}`,placeholders:o.placeholders}}u(kr,"prepareEnglish");var Pr={pa:2560,gu:2688,or:2816,ta:2944,te:3072,kn:3200,ml:3328,si:3456,hi:2304,mr:2304,kK:2304,sa:2304,ne:2304,sd:2304,bn:2432,as:2432};function kn(e){return e>=21&&e<=40&&e!==28&&!((e-21)%5===0||(e-21)%5===4)&&(e=21+5*Math.floor((e-21)/5)),(e===43||e===44||e===45)&&(e=42),e===54&&(e=55),e}u(kn,"tamilOffset");function Mn(e,t,r){let o=Pr[t],n=Pr[r];if(o===void 0||n===void 0)return e;let s="";for(let i of e){let a=i.codePointAt(0)-o;a>=0&&a<=111&&i!=="\\u0964"&&i!=="\\u0965"?(r==="ta"&&(a=kn(a)),s+=String.fromCodePoint(n+a)):s+=i}return s}u(Mn,"transliterate");var Un=/[ ]([!%)\\]},.:;>?\\u0964\\u0965])/gu,Dn=/([#$(\\[{<@])[ ]/gu,Bn=/[ ]([-/\\\\])[ ]/gu,jn=/([0-9]+ [,.:/] )+[0-9]+/gu;function Fn(e){let t=e,r="",o=0;for(let n of t.matchAll(jn)){let s=n.index,i=s+n[0].length;s>o&&(r+=t.slice(o,s)+t.slice(s,i).replace(/ /g,""),o=i)}t=r+t.slice(o),t=t.replace(Bn,"$1").replace(Un,"$1").replace(Dn,"$1");for(let n of["\'",\'"\',"`"]){let s=0,i="";for(let a of t)a===n?(i+=s%2===0?"@RA":"@LA",s++):i+=a;t=i.split("@RA ").join(n).split(" @LA").join(n).split("@RA").join(n).split("@LA").join(n)}return t}u(Fn,"detokenize");function Mr(e,t,r){t==="ory_Orya"&&(e=e.split("\\u0B2F\\u0B3C").join("\\u0B5F"));for(let[n,s]of r)e=e.split(n).join(s);let o=dn[t]??"hi";return Fn(Mn(e,"hi",o))}u(Mr,"finish");var Gn=new Set([0,1,2,3]);function Vn(e){return e.normalize("NFKC").replace(/\\s/gu," ").replace(/[\\u0000-\\u0008\\u000e-\\u001f\\u007f-\\u009f]/gu,"").replace(/ +/g," ").trim()}u(Vn,"normalize");var Oe=class{constructor(t,r){this.source=t;this.target=r;this.cache=new Map}static{u(this,"Pieces")}word(t){let r=this.cache.get(t);if(r)return r;let o=[...t];for(;;){let s=-1,i=-1/0;for(let a=0;ai&&(i=l[1],s=a)}if(s<0)break;o.splice(s,2,o[s]+o[s+1])}let n=o.map(s=>this.source.pieces[s]?.[0]??this.source.unk);return this.cache.size<5e4&&this.cache.set(t,n),n}encode(t){let[r,o,...n]=t.split(" "),s=u(l=>{let c=l===void 0?void 0:this.source.tags[l];if(c===void 0)throw new Error(`The translator doesn\'t know the language tag ${l}.`);return c},"tag"),i=[s(r),s(o)],a=Vn(n.join(" "));if(a)for(let l of("\\u2581"+a.replace(/ /g,"\\u2581")).split(new RegExp("(?=\\u2581)","u")))l&&i.push(...this.word(l));return i.push(this.source.eos),i}decode(t){return t.filter(o=>!Gn.has(o)).map(o=>this.target[o]??"").join("").split("\\u2581").join(" ").trim().split(" .").join(".").split(" ?").join("?").split(" !").join("!").split(" ,").join(",").split(" \' ").join("\'").split(" n\'t").join("n\'t").split(" \'m").join("\'m").split(" \'s").join("\'s").split(" \'ve").join("\'ve").split(" \'re").join("\'re")}};var Ce=u((e,t,r)=>new e.Tensor("int64",BigInt64Array.from(t,o=>BigInt(o)),r),"int64");function Wn(e,t,r,o){let n=[],s=-1/0;for(let i=t;i-1/0))continue;let l=n.length;for(;l>0&&n[l-1][1]o&&n.pop(),n.length===o&&(s=n[o-1][1])}return n}u(Wn,"topK");async function Ur(e,t,r,o){let{ort:n,encoder:s,decoder:i}=e,a=t.length,l=r,c=Math.max(...t.map(v=>v.length)),p=[],f=[];for(let v of t){for(let O=v.length;O{let O=v.data,b=y*c*g,x=new Float32Array(T*a*l*b);for(let D=0;DArray.from({length:l},()=>f.slice(O*c,(O+1)*c)).flat()),[a*l,c]),_=new n.Tensor("float32",new Float32Array(0),[T,a*l,y,0,g]),N=_,F=Array.from({length:a*l},()=>[2]),J=Array.from({length:a*l},(v,O)=>O%l===0?0:-1/0),se=Array.from({length:a*l},(v,O)=>O),ee=Array.from({length:a},()=>[]),W=new Array(a).fill(!1);for(let v=1;v<256;v++){if(o?.())throw new DOMException("Stopped.","AbortError");let O=await i.run({input_ids:Ce(n,F.map(R=>R[R.length-1]),[a*l,1]),attention_mask:$,self_k:_,self_v:N,beam_idx:Ce(n,se,[a*l]),cross_k:E,cross_v:A}),b=O.logprobs.data,x=O.logprobs.dims[1];_=O.new_self_k,N=O.new_self_v;let D=[],k=[],z=[];for(let R=0;R-1/0)for(let[X,Q]of Wn(b,V*x,(V+1)*x,2*l))M.push([P,X,te+Q])}M.sort((P,V)=>V[2]-P[2]||P[0]*x+P[1]-(V[0]*x+V[1]));let ce=0;for(let[P,V,te]of M.slice(0,2*l)){if(V===2){ee[R].push({score:te/(v+1),ids:[...F[R*l+P].slice(1),V]});continue}if(D.push(R*l+P),k.push(V),z.push(te),++ce===l)break}for(;ce=l&&(ee[R]=ee[R].sort((V,te)=>te.score-V.score).slice(0,l),Math.max(...z.slice(-l))/(v+1)<=ee[R][l-1].score&&(W[R]=!0))}if(W.every(Boolean))break;F=D.map((R,M)=>[...F[R],k[M]]),J=z,se=D}return ee.map((v,O)=>{if(v.length-1/0&&v.push({score:D/F[O*l+x].length,ids:F[O*l+x].slice(1)})}let b=v.sort((x,D)=>D.score-x.score).slice(0,l).map(x=>x.ids);for(b.length||b.push([2]);b.lengthe.replace(/[.*+?^${}()|[\\]\\\\/]/g,"\\\\$&"),"escape"),Dr=String.raw`\\p{L}\\p{N}_`;function mt(e){let t=[...e].sort((r,o)=>o.length-r.length);return new RegExp(String.raw`(?pt(r).replace(/ /g,String.raw`\\s+`)).join("|")+String.raw`)(?![${Dr}\\-])`,"giu")}u(mt,"termPattern");var Fe=/\\$\\$[\\s\\S]*?\\$\\$|\\$(?:\\\\.|[^$\\\\])+\\$|\\\\\\([\\s\\S]*?\\\\\\)|\\\\\\[[\\s\\S]*?\\\\\\]|\\\\[a-zA-Z]+\\*?|\\\\./g;function zn(e,t,r){let o=[...t].filter(([,s])=>s.has(r)).map(([s])=>s),n=new Map;if(!o.length)return n;for(let s of e.replace(Fe," ").matchAll(mt(o))){let i=s[0].toLowerCase().replace(/\\s+/gu," ");n.set(i,(n.get(i)??0)+1)}return n}u(zn,"termsIn");function Hn(e){return e.replace(/[\\p{Mn}\\p{Mc}]+$/u,"")}u(Hn,"stem");var Zn=u((e,t)=>t?e.split(t).length-1:0,"count");function qn(e){return new RegExp(String.raw`(?i+l)}return e}u(gt,"joinEndings");function ht(e,t,r,o){let n=new Map,s=[],i=t;for(let[a,l]of zn(e,r,o)){let c=r.get(a).get(o),p=i;for(let[d,m]of Object.entries(c.fix))i=i.replace(qn(d),()=>m);i=gt(i,[c],o);let f=Zn(i,Hn(c.term))>=l;i===p&&f?n.set(a,"model"):i!==p&&n.set(a,"fixed"),!f&&c.force!==!1&&s.push(a)}return{text:i,outcomes:n,missing:s}}u(ht,"checkAndFix");var Kn="(?:mL|L|M|N|mol|moles?|g|mg|kg|cm|mm|nm|km|m/s|km/h|m|s|K|atm|kcal|cal|kJ|J|Pa|W|V|A|Hz|%)",Te=String.raw`[\\p{L}\\p{N}_]`,Ee=String.raw`(?:(?<=${Te})(?!${Te})|(?\\[\\]\'\u2018\u2019]{1,8}\\s*){0,3}(1[0-9][0-9])\\s*[>\\]\'\u2019]/gu,zr=u(e=>``,"marker"),Fr=u(e=>new RegExp("\\\\p{L}{2,}","u").test(e.replace(Fe," ")),"hasWords");function yt(e){let t=[];return{masked:e.replace(Xn,o=>(t.push(o),zr(t.length))),kept:t}}u(yt,"mask");function Gr(e,t){let r=[...e.matchAll(bt)].map(n=>Number(n[1])-100).sort((n,s)=>n-s),o=r.length===t.length&&r.every((n,s)=>n===s+1);return{text:e.replace(bt,(n,s)=>t[Number(s)-101]??n),ok:o}}u(Gr,"unmask");var Qn=/(?<=[\\p{L}\\p{N}][\\p{L}\\p{N}_>][.?!])\\s+(?=[A-Z(\\[<])|(?<=>)\\s+(?=(?:Find|Show|Prove|Determine|Calculate|Evaluate|Hence)(?![\\p{L}\\p{N}_]))/u,wt=u(e=>e.split(Qn).filter(t=>t.trim()),"sentences"),eo=/(?<=\\S)[\u0903\u0983\u0A03\u0A83\u0B03\u0B83\u0C03\u0C83\u0D03](?=\\s|$)/gu;function Vr(e,t){let r=e.split(":").length-t.split(":").length;return r>0?t.replace(eo,o=>r-- >0?":":o):t}u(Vr,"fixColons");var to=/\\b(?:is|are|equals|equal to|be)\\s*[.:]?\\s*$/i,ro={hi:/(?:\u0939\u0948|\u0939\u0948\u0902|\u0925\u093E|\u0925\u0947|\u0925\u0940|\u0939\u094B\u0917\u093E|\u0939\u094B\u0917\u0940|\u0939\u094B\u0902\u0917\u0947|\u0939\u094B\u0924\u093E|\u0939\u094B\u0924\u0940|\u0915\u0940\u091C\u093F\u090F|\u0915\u0930\u0947\u0902)$/u,mr:/(?:\u0906\u0939\u0947|\u0906\u0939\u0947\u0924|\u0905\u0938\u0947\u0932|\u0905\u0938\u0924\u0940\u0932|\u0905\u0938\u0924\u0947|\u0905\u0938\u0924\u094B|\u0905\u0938\u0924\u093E\u0924|\u0939\u094B\u0908\u0932|\u0939\u094B\u0924\u0947|\u0939\u094B\u0924\u094B|\u0936\u094B\u0927\u093E|\u0915\u0930\u093E|\u0915\u093E\u0922\u093E|\u0926\u094D\u092F\u093E)$/u};function no(e,t,r){let o=ro[r];return!o||!to.test(e)||o.test(t.replace(/[ .:\u0964?!]+$/u,""))}u(no,"complete");var Wr=u((e,t,r)=>{let o=t.filter(n=>oo(e,n));return o.find(n=>no(e,n,r))??o[0]},"choose"),oo=u((e,t)=>{let r=[...e.matchAll(//g)].map(n=>n[1]).sort().join(),o=[...t.matchAll(bt)].map(n=>n[1]).sort().join();return r===o},"keepsMarkers"),Ge=class e{constructor(t,r){this.sessions=t;this.pieces=r}static{u(this,"PaperTranslator")}async sentences(t,r,o,n,s,i){let a=je[r].tag,l=t.map(d=>{let m=kr(d,r);return{...m,ids:this.pieces.encode(m.prepared).slice(-256)}}),c=t.map((d,m)=>m).sort((d,m)=>t[d].length-t[m].length),p=new Array(t.length),f=u(async(d,m)=>(await Ur(this.sessions,d.map(T=>l[T].ids),m,i)).map((T,y)=>T.map(g=>Mr(this.pieces.decode(g),a,l[d[y]].placeholders))),"candidatesOf");for(let d=0;d{let d=wt(f);return d.length?d:[f]}),l=a.flat(),c=await this.sentences(l,r,o,n,s,i),p=0;return a.map(f=>{let d=c.slice(p,p+f.length).join(" ");return p+=f.length,d})}static sentenceCount(t){return t.filter(Fr).reduce((r,o)=>r+Math.max(1,wt(yt(o).masked).length),0)}async translate(t,r,o={}){let n=o.beams??5,s=o.batch??8,i=o.glossary,a=t.map(y=>o.sentences?.get(dt(y))?.[r]),l=t.map((y,g)=>g).filter(y=>Fr(t[y])&&a[y]===void 0),c=e.sentenceCount(l.map(y=>t[y])),p=0,f=u(()=>o.progress?.(++p,c),"tick");o.progress?.(0,c);let d=l.map(y=>yt(t[y])),m=await this.pieces_(d.map(y=>y.masked),r,n,s,f,o.stop),w=t.map((y,g)=>({text:a[g]??y,kept:!0,terms:new Map})),T=[];for(let[y,g]of l.entries()){let h=t[g],{text:E,ok:A}=Gr(Vr(h,m[y]),d[y].kept),$=w[g];if($.text=E,$.kept=A,i){let _=ht(h,E,i,r);$.text=_.text,$.terms=_.outcomes,_.missing.length&&T.push({index:g,missing:_.missing})}}if(i&&T.length){let y=T.map(({index:h,missing:E})=>{let{masked:A,kept:$}=yt(t[h]);return{masked:A.replace(mt(E),N=>($.push(i.get(N.toLowerCase().replace(/\\s+/gu," ")).get(r).term),zr($.length))),kept:$}});c+=y.reduce((h,E)=>h+Math.max(1,wt(E.masked).length),0);let g=await this.pieces_(y.map(h=>h.masked),r,n,s,f,o.stop);for(let[h,{index:E,missing:A}]of T.entries()){let $=t[E],_=w[E],{text:N,ok:F}=Gr(Vr($,g[h]),y[h].kept);if(F){let J=ht($,gt(N,A.map(se=>i.get(se).get(r)),r),i,r);_.text=J.text,_.kept=!0}for(let J of A)_.terms.set(J,F?"forced":"missed")}}return w}};function Hr(e,t){let r=Ae(e,t);if(At(r))return Ne(r);let o=[];for(let n=0;At(Ae(e,`${t}.${String(n).padStart(3,"0")}`));n++)o.push(Ne(Ae(e,`${t}.${String(n).padStart(3,"0")}`)));if(!o.length)throw new Error(`The translator\'s ${t} is missing.`);return Buffer.concat(o)}u(Hr,"readModelFile");var Ie=null,Et=new Set;async function io(e,t){if(Ie?.folder===e)return Ie;Ie=null,C.wasm.wasmPaths=so(e).href+"/",C.wasm.numThreads=t;let r={ort:ft,encoder:await ve.create(Hr(e,"encoder.onnx")),decoder:await ve.create(Hr(e,"decoder.onnx"))},o=new Oe(JSON.parse(Ne(Ae(e,"source.json"),"utf8")),JSON.parse(Ne(Ae(e,"target.json"),"utf8"))),n=Ae(e,"glossary.json"),s=At(n)?JSON.parse(Ne(n,"utf8")):null;return Ie={folder:e,translator:new Ge(r,o),glossary:s},Ie}u(io,"load");var Tt=u(e=>Zr.postMessage(e),"reply");Zr?.on("message",e=>{if(e.type==="stop"){Et.add(e.id);return}(async()=>{try{let{translator:t,glossary:r}=await io(e.folder,e.threads),o=await t.translate(e.texts,e.lang,{beams:e.beams,batch:e.batch,glossary:r?Br(r,e.subject):void 0,sentences:r?jr(r):void 0,progress:u((n,s)=>Tt({type:"progress",id:e.id,done:n,of:s}),"progress"),stop:u(()=>Et.has(e.id),"stop")});Tt({type:"done",id:e.id,results:o.map(n=>({text:n.text,kept:n.kept,terms:Object.fromEntries(n.terms)}))})}catch(t){let r=t instanceof Error&&t.name==="AbortError";Tt({type:"failed",id:e.id,message:t instanceof Error?t.message:String(t),stopped:r})}finally{Et.delete(e.id)}})()});export{Hr as readModelFile};\n/*! Bundled license information:\n\nonnxruntime-web/dist/ort.node.min.mjs:\n (*!\n * ONNX Runtime Web v1.30.0\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n *)\n*/\n'){let r=null,o=null,i,s=a(c=>{o&&(o={...o,...c})},"update");async function l(){if(r)return r;if(!n)throw new Error("This build of TeXConverter can't translate on the computer.");let c=new Mk(await _k(t,n));return c.on("message",d=>{d.id===o?.id&&(d.type==="progress"?s({done:d.done,of:d.of}):d.type==="done"?s({state:"done",results:d.results,done:o.of}):s({state:d.stopped?"stopped":"failed",error:d.message}),d.type!=="progress"&&u())}),c.on("error",d=>{s({state:"failed",error:`The translator stopped: ${d.message}`}),r=null}),c.on("exit",()=>{o?.state==="running"&&s({state:"failed",error:"The translator stopped unexpectedly. The computer may be short of memory: close other programs and try again."}),r=null}),r=c,c}a(l,"startWorker");function u(){clearTimeout(i),i=setTimeout(()=>{r?.terminate()},10*6e4),i.unref()}return a(u,"scheduleIdle"),{async status(c){return c?e.refresh():e.status()},prepare(){return e.prepare(),e.status()},start(c,d,p){if(!(d in Ll))throw new Error(`The translator on this computer doesn't translate into ${d}.`);let f=e.status();if(f.state!=="ready"||!f.version)throw new Error(f.reason??"The translator isn't downloaded yet.");let m=e.file(f.version,"source.json");if(!m)throw new Error("The translator's files are missing. Download it again.");o?.state==="running"&&r?.postMessage({type:"stop",id:o.id});let h=Ok(8).toString("hex");o={id:h,state:"running",done:0,of:0},clearTimeout(i);let g={type:"translate",id:h,folder:$k(m),threads:Math.max(1,Math.min(4,Ik()-1)),texts:c,lang:d,subject:p,beams:f.beams??5,batch:f.batch??8};return l().then(y=>y.postMessage(g),y=>s({state:"failed",error:y instanceof Error?y.message:String(y)})),o},job:a(()=>o,"job"),stop(){o?.state==="running"&&r?.postMessage({type:"stop",id:o.id})},async close(){clearTimeout(i),await r?.terminate()}}}a(xm,"desktopTranslator");x();var Fl="1.30.0";x();import{spawnSync as Gk,spawn as Nm}from"node:child_process";import{copyFileSync as jk,existsSync as Cr,mkdirSync as Tm,readFileSync as Pm,renameSync as Xk,rmSync as ms,writeFileSync as zk}from"node:fs";import{dirname as hs,join as Tr,resolve as Pr}from"node:path";x();var GP=String.raw` $ErrorActionPreference = 'Stop' Add-Type -ReferencedAssemblies System.Windows.Forms, System.Drawing -TypeDefinition @' using System; using System.Drawing; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Windows.Forms; // _IMathInputControlEvents, from micaut.dll's type library. [ComImport, Guid("683336B5-A47D-4358-96F9-875A472AE70A"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IMathInputControlEvents { [DispId(0)] void Insert([MarshalAs(UnmanagedType.BStr)] string recoResult); [DispId(1)] void Close(); [DispId(2)] void Paint(IntPtr hdc, int left, int top, int right, int bottom); [DispId(3)] void Clear(); } [ComVisible(true), ClassInterface(ClassInterfaceType.None)] public class TeXConverterInk : IMathInputControlEvents { [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr FindWindow(string cls, string title); [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h); [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags); [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, IntPtr pid); [DllImport("user32.dll")] static extern bool AttachThreadInput(uint attach, uint to, bool on); [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId(); // Windows lets only the program in front give the foreground away. The // panel is opened from the background (the helper serving Word, or the // app's server behind its browser tab), so it joins the front window's // input for a moment to be handed the focus, and the pen goes straight to it. static void BringToFront(IntPtr window) { uint front = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero); uint self = GetCurrentThreadId(); bool joined = front != 0 && front != self && AttachThreadInput(self, front, true); try { SetForegroundWindow(window); } finally { if (joined) AttachThreadInput(self, front, false); } } string result; public void Insert(string recoResult) { result = recoResult; Application.ExitThread(); } public void Close() { Application.ExitThread(); } public void Paint(IntPtr hdc, int left, int top, int right, int bottom) { } public void Clear() { } static object Call(object target, string name, params object[] args) { return target.GetType().InvokeMember(name, BindingFlags.InvokeMethod, null, target, args); } public static string Run(string caption) { object mic = Activator.CreateInstance(Type.GetTypeFromProgID("micaut.MathInputControl", true)); var sink = new TeXConverterInk(); IConnectionPoint point; Guid events = typeof(IMathInputControlEvents).GUID; ((IConnectionPointContainer)mic).FindConnectionPoint(ref events, out point); int cookie; point.Advise(sink, out cookie); try { Call(mic, "SetCaptionText", caption); Call(mic, "EnableAutoGrow", true); // Word's size, centred on the screen the user is working on. Rectangle area = Screen.FromPoint(Cursor.Position).WorkingArea; int width = Math.Min(780, area.Width - 40), height = Math.Min(500, area.Height - 40); int left = area.Left + (area.Width - width) / 2, top = area.Top + (area.Height - height) / 2; Call(mic, "SetPosition", left, top, left + width, top + height); Call(mic, "Show"); // The window is looked for until it appears (for up to 10 s), and the // panel counts as closed only once it has been seen and then hidden. IntPtr window = IntPtr.Zero; bool seen = false; int waited = 0; var watch = new Timer { Interval = 250 }; watch.Tick += (s, e) => { if (window == IntPtr.Zero) { window = FindWindow(null, caption); if (window != IntPtr.Zero) { // Above the browser or Word it was opened from, which otherwise // keeps the foreground and leaves the panel behind it. SetWindowPos(window, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040); BringToFront(window); } } if (window != IntPtr.Zero && IsWindowVisible(window)) seen = true; else if (seen || ++waited > 40) Application.ExitThread(); }; watch.Start(); Application.Run(); watch.Stop(); Call(mic, "Hide"); } finally { point.Unadvise(cookie); } return sink.result; } } '@ $mathml = [TeXConverterInk]::Run($env:TEXCONVERTER_INK_CAPTION) if ($mathml) { [Console]::Out.Write('MATHML ' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($mathml))) } else { [Console]::Out.Write('CANCELLED') } `;function Mn(e){return Buffer.from(e,"utf16le").toString("base64")}a(Mn,"encodeCommand");x();import{spawn as Lk,spawnSync as Fk}from"node:child_process";var Bl="PureTechWithJoy.TeXConverter",Bk="TeXConverter",vm="TeXConverter",fs=String.raw` Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; using System.Text; public static class TeXConverterTaskbar { [StructLayout(LayoutKind.Sequential, Pack = 4)] struct PropertyKey { public Guid fmtid; public uint pid; } [StructLayout(LayoutKind.Explicit)] struct PropVariant { [FieldOffset(0)] public ushort vt; [FieldOffset(8)] public IntPtr p; } [ComImport, Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IPropertyStore { int GetCount(out uint count); int GetAt(uint index, out PropertyKey key); int GetValue(ref PropertyKey key, out PropVariant value); int SetValue(ref PropertyKey key, ref PropVariant value); int Commit(); } [DllImport("shell32.dll")] static extern int SHGetPropertyStoreForWindow(IntPtr hwnd, ref Guid iid, out IPropertyStore store); [DllImport("shell32.dll", CharSet = CharSet.Unicode)] static extern int SHGetPropertyStoreFromParsingName(string path, IntPtr bindContext, int flags, ref Guid iid, out IPropertyStore store); delegate bool EnumProc(IntPtr hwnd, IntPtr data); [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc proc, IntPtr data); [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr hwnd); [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr hwnd, StringBuilder text, int max); [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr hwnd, StringBuilder name, int max); [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint pid); [DllImport("user32.dll")] static extern bool IsIconic(IntPtr hwnd); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hwnd, int command); [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hwnd); [DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern int GetCurrentPackageFamilyName(ref uint length, StringBuilder name); // PKEY_AppUserModel_*: RelaunchCommand 2, RelaunchIconResource 3, RelaunchDisplayNameResource 4, ID 5. static readonly Guid AppUserModel = new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"); static void Set(IPropertyStore store, uint pid, string text) { PropertyKey key = new PropertyKey(); key.fmtid = AppUserModel; key.pid = pid; PropVariant value = new PropVariant(); value.vt = 31; // VT_LPWSTR value.p = Marshal.StringToCoTaskMemUni(text); try { Marshal.ThrowExceptionForHR(store.SetValue(ref key, ref value)); } finally { Marshal.FreeCoTaskMem(value.p); } } /** The Store package's ID for its app named app, when this runs inside the package (as the app's children do); null outside one. */ public static string PackageAppId(string app) { uint length = 256; StringBuilder name = new StringBuilder(256); return GetCurrentPackageFamilyName(ref length, name) == 0 ? name.ToString() + "!" + app : null; } static bool IsAppWindow(IntPtr hwnd, string title) { if (!IsWindowVisible(hwnd)) return false; StringBuilder text = new StringBuilder(256); GetWindowText(hwnd, text, text.Capacity); if (text.ToString() != title) return false; StringBuilder name = new StringBuilder(256); GetClassName(hwnd, name, name.Capacity); if (name.ToString() != "Chrome_WidgetWin_1") return false; uint pid; GetWindowThreadProcessId(hwnd, out pid); try { string process = System.Diagnostics.Process.GetProcessById((int)pid).ProcessName.ToLowerInvariant(); return process == "msedge" || process == "chrome"; } catch { return false; } } /** Gives every open app window the ID; how many there were. */ public static int TagWindows(string title, string id, string command, string icon) { int tagged = 0; EnumWindows(delegate (IntPtr hwnd, IntPtr data) { if (!IsAppWindow(hwnd, title)) return true; Guid iid = typeof(IPropertyStore).GUID; IPropertyStore store; if (SHGetPropertyStoreForWindow(hwnd, ref iid, out store) != 0) return true; try { // The relaunch values before the ID: Windows reads them as the ID changes. // None for a package's ID: Windows starts a package's app itself. if (!String.IsNullOrEmpty(command)) { Set(store, 2, command); Set(store, 3, icon); Set(store, 4, title); } Set(store, 5, id); store.Commit(); tagged++; } catch { } finally { Marshal.ReleaseComObject(store); } return true; }, IntPtr.Zero); return tagged; } /** Brings the open app window to the front, restored if it was minimised; false when there is none. */ public static bool FocusWindow(string title) { IntPtr found = IntPtr.Zero; EnumWindows(delegate (IntPtr hwnd, IntPtr data) { if (!IsAppWindow(hwnd, title)) return true; found = hwnd; return false; }, IntPtr.Zero); if (found == IntPtr.Zero) return false; if (IsIconic(found)) ShowWindow(found, 9); // SW_RESTORE if (!SetForegroundWindow(found)) { // Windows lets a window be brought forward only by the program in use; // a tap of Alt makes this one that, as the person did just open it. keybd_event(0x12, 0, 0, UIntPtr.Zero); keybd_event(0x12, 0, 2, UIntPtr.Zero); // KEYEVENTF_KEYUP SetForegroundWindow(found); } return true; } /** Gives a saved .lnk the ID. */ public static void TagShortcut(string path, string id) { Guid iid = typeof(IPropertyStore).GUID; IPropertyStore store; Marshal.ThrowExceptionForHR(SHGetPropertyStoreFromParsingName(path, IntPtr.Zero, 2, ref iid, out store)); // GPS_READWRITE try { Set(store, 5, id); Marshal.ThrowExceptionForHR(store.Commit()); } finally { Marshal.ReleaseComObject(store); } } } '@ `,Uk=String.raw`${fs} $id = [TeXConverterTaskbar]::PackageAppId($env:TEXCONVERTER_PACKAGE_APP) $relaunch = $null if (-not $id) { $id = $env:TEXCONVERTER_APP_ID; $relaunch = $env:TEXCONVERTER_RELAUNCH } $deadline = [DateTime]::UtcNow.AddSeconds(20) do { if ([TeXConverterTaskbar]::TagWindows($env:TEXCONVERTER_WINDOW_TITLE, $id, $relaunch, $env:TEXCONVERTER_ICON) -gt 0) { break } Start-Sleep -Milliseconds 100 } while ([DateTime]::UtcNow -lt $deadline) `;function qk(e,t=e){return{TEXCONVERTER_WINDOW_TITLE:vm,TEXCONVERTER_APP_ID:Bl,TEXCONVERTER_PACKAGE_APP:Bk,TEXCONVERTER_RELAUNCH:`"${t}"`,TEXCONVERTER_ICON:`${e},0`}}a(qk,"tagWindowEnv");var km=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];function Em(e,t=e,n=(r,o,i)=>Lk(r,[...o],{...i,detached:!0,stdio:"ignore"})){let r=n("powershell.exe",[...km,Mn(Uk)],{windowsHide:!0,env:{...process.env,...qk(e,t)}});r.on("error",()=>{}),r.unref()}a(Em,"tagAppWindow");var Wk=String.raw`${fs} if ([TeXConverterTaskbar]::FocusWindow($env:TEXCONVERTER_WINDOW_TITLE)) { exit 0 } else { exit 1 } `,Hk=a((e,t,n)=>Fk(e,[...t],{windowsHide:!0,stdio:"ignore",env:n,timeout:15e3}),"runFocus");function Am(e=Hk){return process.platform!=="win32"?!1:e("powershell.exe",[...km,Mn(Wk)],{...process.env,TEXCONVERTER_WINDOW_TITLE:vm}).status===0}a(Am,"focusAppWindow");x();function Sm(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.byteLength<64||t.getUint16(0,!0)!==23117)throw new Error("it is not a Windows executable (no MZ header)");let n=t.getUint32(60,!0);if(n+24+70>e.byteLength||t.getUint32(n,!0)!==17744)throw new Error("it is not a Windows executable (no PE header)");let r=n+24,o=t.getUint16(r,!0);if(o!==267&&o!==523)throw new Error("its PE header is of an unknown kind");return{view:t,at:r,plus:o===523}}a(Sm,"optionalHeader");function Ul(e){let{view:t,at:n}=Sm(e);return t.getUint16(n+68,!0)}a(Ul,"subsystemOf");function Dm(e){let t=Ul(e);if(t!==2&&t!==3)throw new Error(`it is for an unexpected Windows subsystem (${t})`);let{at:n}=Sm(e),r=e.slice();return new DataView(r.buffer,r.byteOffset,r.byteLength).setUint16(n+68,2,!0),r}a(Dm,"withoutConsole");var Nr="TeXConverter",Hl="TeXConverter.exe",ql="LaTeX2Word.Convert",Wl="HKCU\\Software\\Classes\\SystemFileAssociations",Gl="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\LaTeX2Word",Im="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",$m="TeXConverterHelper",_o="TeXConverterHelper.exe",Rm=`${Nr}.lnk`;function Mm(e){if(!e.LOCALAPPDATA||!e.APPDATA)throw new Error("LOCALAPPDATA and APPDATA are not set, so there is nowhere per-user to install to.");let t=Tr(e.LOCALAPPDATA,"Programs",Nr);return{installDir:t,exe:Tr(t,Hl),helperExe:Tr(t,_o),shortcut:Tr(e.APPDATA,"Microsoft","Windows","Start Menu","Programs",`${Nr}.lnk`),windowProfile:Tr(e.LOCALAPPDATA,Nr,"Window")}}a(Mm,"installPaths");function Vk(){return[`${Wl}\\.docx\\shell\\${ql}`,`${Wl}\\.tex\\shell\\${ql}`,Gl]}a(Vk,"registryKeys");function Yk(e,t){let n=[],r=[[".docx","Convert to LaTeX (.tex)"],[".tex","Convert to Word (.docx)"]];for(let[i,s]of r){let l=`${Wl}\\${i}\\shell\\${ql}`;n.push({key:l,name:null,type:"REG_SZ",data:s}),n.push({key:l,name:"Icon",type:"REG_SZ",data:`${e.exe},0`}),n.push({key:`${l}\\command`,name:null,type:"REG_SZ",data:`"${e.exe}" open "%1"`})}let o=[["DisplayName","REG_SZ",Nr],["DisplayVersion","REG_SZ",t],["Publisher","REG_SZ",Nr],["DisplayIcon","REG_SZ",`${e.exe},0`],["InstallLocation","REG_SZ",e.installDir],["UninstallString","REG_SZ",`"${e.exe}" uninstall`],["NoModify","REG_DWORD","1"],["NoRepair","REG_DWORD","1"]];for(let[i,s,l]of o)n.push({key:Gl,name:i,type:s,data:l});return n}a(Yk,"registryValues");function Om(e){return["add",e.key,...e.name===null?["/ve"]:["/v",e.name],"/t",e.type,"/d",e.data,"/f"]}a(Om,"regAddArgs");function Cm(e,t){return t===void 0?["delete",e,"/f"]:["delete",e,"/v",t,"/f"]}a(Cm,"regDeleteArgs");function Kk(e){return{key:Im,name:$m,type:"REG_SZ",data:`"${e.helperExe}" helper`}}a(Kk,"helperRunValue");function Zk(e,t,n=Jk){if(Pr(hs(t)).toLowerCase()===Pr(e.installDir).toLowerCase())return null;let r=n(Tr(hs(t),_o));return r!==null&&_m(r)?r:null}a(Zk,"shippedHelper");function _m(e){try{return Ul(e)===2}catch{return!1}}a(_m,"isWindowlessExe");function Jk(e){try{return Pm(e)}catch{return null}}a(Jk,"readIfThere");function Qk(e){return`Get-Process -Name 'TeXConverterHelper' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq ${wt(e.helperExe)} } | Stop-Process -Force -ErrorAction SilentlyContinue`}a(Qk,"stopHelperScript");function wt(e){return`'${e.replace(/'/g,"''")}'`}a(wt,"psQuote");function eE(e,t=e.exe){return["$ErrorActionPreference = 'Stop'",fs,`$links = @(${wt(e.shortcut)})`,"$desktop = [Environment]::GetFolderPath('Desktop')",`if ($desktop) { $links += Join-Path $desktop ${wt(Rm)} }`,"$pinned = Join-Path $env:APPDATA 'MicrosoftInternet ExplorerQuick LaunchUser PinnedTaskBar'",`try { if (Test-Path -LiteralPath $pinned) { foreach ($candidate in (Get-ChildItem -LiteralPath $pinned -Filter '*.lnk' -File)) { $existing = (New-Object -ComObject WScript.Shell).CreateShortcut($candidate.FullName); if ($existing.TargetPath -eq ${wt(e.exe)} -or $existing.TargetPath -eq ${wt(e.helperExe)}) { $links += $candidate.FullName } } } } catch { }`,"foreach ($link in $links) {"," $s = (New-Object -ComObject WScript.Shell).CreateShortcut($link)",` $s.TargetPath = ${wt(t)}`," $s.WindowStyle = 7",` $s.IconLocation = ${wt(`${e.exe},0`)}`," $s.Description = 'Convert between Word documents and LaTeX'"," $s.Save()",` try { [TeXConverterTaskbar]::TagShortcut($link, ${wt(Bl)}) } catch { }`,"}",`try { Add-Type -Namespace TeXConverter -Name ShellNotify -MemberDefinition '[System.Runtime.InteropServices.DllImport("shell32.dll")] public static extern void SHChangeNotify(int wEventId, uint uFlags, System.IntPtr dwItem1, System.IntPtr dwItem2);' -ErrorAction Stop; [TeXConverter.ShellNotify]::SHChangeNotify(0x08000000, 0, [IntPtr]::Zero, [IntPtr]::Zero) } catch { }`].join(` `)}a(eE,"shortcutScript");function tE(e){return["$desktop = [Environment]::GetFolderPath('Desktop')","if (-not $desktop) { exit 1 }",`$link = Join-Path $desktop ${wt(Rm)}`,"if (-not (Test-Path -LiteralPath $link)) { exit 1 }","$target = (New-Object -ComObject WScript.Shell).CreateShortcut($link).TargetPath",`if ($target -ne ${wt(e.exe)} -and $target -ne ${wt(e.helperExe)}) { exit 1 }`,"Remove-Item -LiteralPath $link -Force","exit 0"].join("; ")}a(tE,"removeDesktopShortcutScript");function Lm(e){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Mn(e)]}a(Lm,"powershellArgs");var gs=a((e,t)=>{let n=Gk(e,t,{encoding:"utf8",windowsHide:!0});return{status:n.status,stderr:n.stderr??""}},"defaultRunner"),ys=a((e,t)=>{Nm(e,t,{detached:!0,stdio:"ignore",windowsHide:!0}).on("error",()=>{}).unref()},"launchDetached");function Fm(e,t){t("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",Qk(e)])}a(Fm,"stopHelper");function nE(e,t=gs,n=ys,r=null){try{let o=r!==null&&_m(r)?r:Dm(Pm(e.exe));Fm(e,t),zk(e.helperExe,o);let i=t("reg",Om(Kk(e)));if(i.status!==0)throw new Error(i.stderr.trim()||"the registry refused");return n(e.helperExe,["helper"]),"Set up handwriting for the Word add-in: a small helper starts with Windows, so Handwrite in Word opens Windows' handwriting panel"}catch(o){return`Handwriting from Word couldn't be set up (${o instanceof Error?o.message:String(o)}); it works while this window is open, and everything else is in place.`}}a(nE,"setUpHelper");function Bm(){if(process.platform!=="win32")throw new Error("The right-click menu and Start Menu entry are Windows-only for now. Use `texconverter app` or `texconverter convert` instead.")}a(Bm,"requireWindows");function jl(e,t=gs){return process.platform!=="win32"||!Cr(e.exe)?!1:t("reg",["query",Gl]).status===0}a(jl,"isInstalled");var rE={copy:jk,exists:Cr,rename:Xk,remove:a(e=>ms(e,{force:!0}),"remove")};function oE(e,t,n=rE){try{n.copy(e,t);return}catch(o){if(!n.exists(t))throw o}let r=`${t}.old`;try{n.exists(r)&&n.remove(r)}catch{}n.rename(t,r);try{n.copy(e,t)}catch(o){try{n.rename(r,t)}catch{}throw o}}a(oE,"copyOverRunning");function bs(e,t,n,r=gs,o=ys,i=Zk(e,n)){Bm();let s=[];if(Pr(n).toLowerCase()!==Pr(e.exe).toLowerCase()){Tm(e.installDir,{recursive:!0});try{oE(n,e.exe)}catch(c){throw new Error(`Could not copy TeXConverter into ${e.installDir} (${c instanceof Error?c.message:String(c)}). If another copy is running, close it and try again.`)}s.push(`Installed to ${e.installDir}`)}for(let c of Yk(e,t)){let d=r("reg",Om(c));if(d.status!==0)throw new Error(`Could not write ${c.key}: ${d.stderr.trim()}`)}s.push("Added \u201CConvert to LaTeX\u201D to the right-click menu of .docx files, and \u201CConvert to Word\u201D to .tex files");let l=nE(e,r,o,i);Tm(hs(e.shortcut),{recursive:!0});let u=r("powershell.exe",Lm(eE(e,Cr(e.helperExe)?e.helperExe:e.exe)));return u.status===0?s.push("Added TeXConverter to the Start Menu and the desktop"):s.push(`The Start Menu and desktop icons could not be created (${u.stderr.trim()||"no reason given"}); everything else is in place.`),s.push(l),s}a(bs,"install");function Um(e,t,n=gs){Bm();let r=[];for(let o of Vk())n("reg",Cm(o));r.push("Removed the right-click menu entries"),n("reg",Cm(Im,$m)),Fm(e,n),Cr(e.helperExe)&&r.push("Stopped the handwriting helper and removed it from sign-in"),Cr(e.shortcut)&&(ms(e.shortcut,{force:!0}),r.push("Removed the Start Menu entry")),n("powershell.exe",Lm(tE(e))).status===0&&r.push("Removed the desktop icon");try{ms(e.windowProfile,{recursive:!0,force:!0})}catch{}return Cr(e.installDir)&&(Pr(hs(t)).toLowerCase()===Pr(e.installDir).toLowerCase()?Nm("cmd.exe",["/d","/c",`ping 127.0.0.1 -n 3 >nul & rmdir /s /q "${e.installDir}"`],{detached:!0,stdio:"ignore",windowsHide:!0,windowsVerbatimArguments:!0}).unref():ms(e.installDir,{recursive:!0,force:!0}),r.push(`Removed ${e.installDir}`)),r}a(Um,"uninstall");x();import{createServer as iE}from"node:http";x();var Xl=[47815,47816,47817],ws=1,Ir="X-TeXConverter-Bridge",qm="handwriting",Wm="sign-in",Hm=/^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/;function Gm(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.app==="texconverter"&&t.protocol===ws&&typeof t.version=="string"&&Array.isArray(t.capabilities)}a(Gm,"isCompatibleStatus");function jm(e){return[new URL(e).origin]}a(jm,"bridgeOrigins");var $r=class extends Error{constructor(n){super(n==="running"?"Another copy of TeXConverter is already serving the Word add-in.":`The ports ${Xl.join(", ")} are all in use by other programs.`);this.reason=n;this.name="BridgeUnavailable"}static{a(this,"BridgeUnavailable")}},sE={unavailable:404,busy:409,unreadable:422},aE=[Ir.toLowerCase(),"content-type"];function Ne(e,t,n,r={}){e.writeHead(t,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Referrer-Policy":"no-referrer",...r}),e.end(JSON.stringify(n))}a(Ne,"sendJson");function lE(e){return{"Access-Control-Allow-Origin":e,Vary:"Origin"}}a(lE,"corsFor");function uE(e,t){return e!=="GET"&&e!=="POST"?!1:(t??"").split(",").map(r=>r.trim().toLowerCase()).filter(r=>r!=="").every(r=>aE.includes(r))}a(uE,"preflightAllowed");async function cE(e,t=fetch){try{let n=await t(`http://127.0.0.1:${e}/v1/status`,{headers:{[Ir]:String(ws)},signal:AbortSignal.timeout(1500)});return n.ok&&Gm(await n.json())}catch{return!1}}a(cE,"isOurBridge");async function Xm(e){let t=new Set(e.allowedOrigins),n=0,r=a(()=>({app:"texconverter",protocol:ws,version:e.version,capabilities:[...e.desk.available?[qm]:[],...e.signIn?[Wm]:[]]}),"status"),o=!1;async function i(p,f,m){let h=e.signIn;if(f===null||!Hm.test(f))return Ne(p,400,{error:"That isn't a sign-in code."},m);if(o)return Ne(p,409,{error:"TeXConverter is already asking about a sign-in. Answer it first."},m);o=!0;try{let g=await h.email();if(g===null)return Ne(p,409,{error:"The TeXConverter app isn't signed in any more. Sign in on the website instead."},m);let y=new AbortController;if(p.on("close",()=>{p.writableFinished||y.abort()}),!await h.confirm(g,y.signal)){y.signal.aborted||Ne(p,403,{error:"The sign-in wasn't allowed on this computer."},m);return}try{await h.approve(f)}catch(E){return Ne(p,502,{error:E instanceof Error?E.message:String(E)},m)}Ne(p,200,{ok:!0},m)}finally{o=!1}}a(i,"signInWord");async function s(p,f){if(![`127.0.0.1:${n}`,`localhost:${n}`].includes(p.headers.host??""))return Ne(f,421,{error:"Wrong host."});let h=p.headers.origin,g=h!==void 0&&t.has(h);if(h!==void 0&&!g)return Ne(f,403,{error:"This origin may not use TeXConverter."});let y=g?lE(h):{},E=new URL(p.url??"/","http://127.0.0.1").pathname;if(p.method==="OPTIONS"){if(!g||!uE(p.headers["access-control-request-method"],p.headers["access-control-request-headers"]))return Ne(f,403,{error:"Not allowed."});f.writeHead(204,{...y,"Access-Control-Allow-Methods":"GET, POST","Access-Control-Allow-Headers":`${Ir}, Content-Type`,"Access-Control-Allow-Private-Network":"true","Access-Control-Max-Age":"600","Cache-Control":"no-store"}),f.end();return}if(p.headers[Ir.toLowerCase()]===void 0)return Ne(f,400,{error:`Missing ${Ir}.`},y);if(Number(p.headers["content-length"]??0)>0||p.headers["transfer-encoding"]!==void 0)return Ne(f,413,{error:"The bridge takes no request body."},y);switch(`${p.method} ${E}`){case"GET /v1/status":return Ne(f,200,r(),y);case"POST /v1/handwrite":{if(!g)return Ne(f,403,{error:"Handwriting is for the TeXConverter add-in."});let v=new AbortController;f.on("close",()=>{f.writableFinished||v.abort()});try{let A=await e.desk.write(v.signal);v.signal.aborted||Ne(f,200,A,y)}catch(w){if(w instanceof Xt)return Ne(f,sE[w.reason],{error:w.message},y);throw w}return}case"GET /v1/account":{if(!g||!e.signIn)return Ne(f,403,{error:"The account is for the TeXConverter add-in."},y);let v={email:await e.signIn.email()};return Ne(f,200,v,y)}case"POST /v1/sign-in":return!g||!e.signIn?Ne(f,403,{error:"Signing in is for the TeXConverter add-in."},y):i(f,new URL(p.url??"/","http://127.0.0.1").searchParams.get("code"),y);default:return Ne(f,404,{error:"Not found."},y)}}a(s,"handle");let l=iE((p,f)=>{s(p,f).catch(m=>{f.headersSent?f.end():Ne(f,500,{error:m instanceof Error?m.message:String(m)})})});l.headersTimeout=1e4,l.requestTimeout=15e3;let u=!1;for(let p of e.ports??Xl){if(await new Promise((m,h)=>{let g=a(E=>{l.removeListener("listening",y),E.code==="EADDRINUSE"||E.code==="EACCES"?m(!1):h(E)},"onError"),y=a(()=>{l.removeListener("error",g),m(!0)},"onListening");l.once("error",g),l.once("listening",y),l.listen(p,"127.0.0.1")})){n=l.address().port;break}if(await cE(p)){u=!0;break}}if(n===0)throw new $r(u?"running":"ports-taken");let c,d=new Promise(p=>c=p);return l.on("close",()=>c()),{port:n,closed:d,close:a(()=>new Promise(p=>{l.close(()=>p()),l.closeAllConnections()}),"close")}}a(Xm,"startBridge");x();import{spawn as dE}from"node:child_process";var pE=String.raw` Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.Application]::EnableVisualStyles() $owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; ShowInTaskbar = $false } $answer = [System.Windows.Forms.MessageBox]::Show($owner, $env:TEXCONVERTER_CONFIRM_TEXT, 'TeXConverter', 'YesNo', 'Question', 'Button2') $owner.Dispose() if ($answer -eq 'Yes') { [Console]::Out.Write('YES') } else { [Console]::Out.Write('NO') } `;function zm(e={}){let t=e.spawnFn??((r,o,i)=>dE(r,[...o],i)),n=e.timeoutMs??12e4;return(r,o)=>new Promise(i=>{if(process.platform!=="win32"&&e.spawnFn===void 0)return i(!1);let s=t("powershell.exe",["-NoProfile","-NonInteractive","-STA","-ExecutionPolicy","Bypass","-EncodedCommand",Mn(pE)],{windowsHide:!0,env:{...process.env,TEXCONVERTER_CONFIRM_TEXT:r}}),l="";s.stdout?.on("data",p=>l+=p.toString("utf8"));let u=a(()=>{s.kill()},"stop"),c=setTimeout(u,n);o?.addEventListener("abort",u,{once:!0});let d=a(p=>{clearTimeout(c),o?.removeEventListener("abort",u),i(p)},"done");s.on("error",()=>d(!1)),s.on("close",()=>d(!o?.aborted&&l.trim()==="YES"))})}a(zm,"windowsConfirm");x();var xs="support@texconverter.com",Vm=/^[^\s@<>"?&#]+@[^\s@<>"?&#]+\.[^\s@<>"?&#]+$/;function Vl(e,t,n,r=Rr){for(let o=1;;o++){let i=o===1?t:`${t} (${o})`;if(!n.some(s=>r(Vt(e,i+s))))return i}}a(Vl,"freeOutputStem");function On(e,t,n=!1){zl(e,t,{detached:!0,stdio:"ignore",windowsHide:!1,windowsVerbatimArguments:n}).on("error",()=>{}).unref()}a(On,"detached");function Es(e,t){process.platform==="win32"?On("explorer.exe",[t?`/select,"${e}"`:`"${e}"`],!0):process.platform==="darwin"?On("open",t?["-R",e]:[e]):On("xdg-open",[t?_n(e):e])}a(Es,"openPathWithSystem");function Lo(e){process.platform==="win32"?On("rundll32.exe",["url.dll,FileProtocolHandler",e]):process.platform==="darwin"?On("open",[e]):On("xdg-open",[e])}a(Lo,"openUrl");var As="TEXCONVERTER_WINDOWLESS";function bE(e=Rr,t=process.env,n=process.platform){if(n!=="win32")return null;let r=[t["ProgramFiles(x86)"],t.ProgramFiles,t.LOCALAPPDATA].filter(i=>typeof i=="string"&&i!=="");return[...r.map(i=>Vt(i,"Microsoft","Edge","Application","msedge.exe")),...r.map(i=>Vt(i,"Google","Chrome","Application","chrome.exe"))].find(i=>e(i))??null}a(bE,"appWindowBrowser");function wE(e,t=null,n=[1200,820]){let r=t===null?[]:[`--user-data-dir=${t}`,"--no-first-run","--no-default-browser-check","--disable-sync","--disable-features=msImplicitSignin"];return[`--app=${e}`,`--window-size=${n[0]},${n[1]}`,...r]}a(wE,"appWindowArgs");function Ym(e,t={}){let n=t.browser===void 0?bE():t.browser;if(!n)return Lo(e);t.taskbarExe!==void 0&&Em(t.taskbarExe,t.taskbarLauncher??t.taskbarExe),zl(n,wE(e,t.profile??null),{detached:!0,stdio:"ignore"}).on("error",()=>Lo(e)).unref()}a(Ym,"openAppWindow");function Qm(e,t=Rr){if(yE(e).toLowerCase()!==_o.toLowerCase())return e;let n=Vt(_n(e),Hl);return t(n)?n:e}a(Qm,"windowExe");function eh(e,t,n=!1){let r=zl(e,[...t],{detached:!0,windowsHide:!0,stdio:n?["ignore","ignore","ignore","ipc"]:"ignore",env:{...process.env,[As]:"1"}});return r.on("error",()=>{}),r}a(eh,"launchWindowless");function th(e,t=3e4,n=[]){let r=eh(e,n,!0);return new Promise(o=>{let i=!1,s=a((u,c)=>{if(!i){if(i=!0,clearTimeout(l),r.connected&&r.disconnect(),r.unref(),c===void 0)return o(u);console.error(`texconverter: ${c}`),Ss("TeXConverter couldn't start.").then(()=>o(u))}},"done"),l=setTimeout(()=>s(0),t);r.on("message",u=>"error"in u?s(1,u.error):s(0)),r.on("error",u=>s(1,u.message)),r.on("exit",u=>s(u??1,"it stopped while starting."))})}a(th,"relaunchWindowless");function ks(e){let t=process.send?.bind(process);!t||!process.connected||t(e,()=>{process.connected&&process.disconnect?.()})}a(ks,"tellLauncher");function xE(){if(process.platform==="win32"){let e=mE("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Personal"],{encoding:"utf8",windowsHide:!0}),t=/Personal\s+REG_SZ\s+(.+)/.exec(e.stdout??"");if(e.status===0&&t)return t[1].trim()}return Vt(gE(),"Documents")}a(xE,"documentsFolder");function Ss(e){return process.stdin.isTTY?(console.log(` ${e} Press Enter to close this window.`),new Promise(t=>{process.stdin.resume(),process.stdin.once("data",()=>{process.stdin.pause(),t()})})):Promise.resolve()}a(Ss,"waitForEnter");function Yl(){if(process.platform!=="win32")return null;try{return Mm(process.env)}catch{return null}}a(Yl,"windowsPaths");function vE(e){return async()=>{let t=await fetch(`${e}/v1/library`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)throw new Error(`The licence server answered ${t.status}.`);return t.json()}}a(vE,"libraryFrom");async function kE(e){if(!e)return xs;try{let t=await fetch(`${e}/v1/contact`,{signal:AbortSignal.timeout(5e3)}),{supportEmail:n}=t.ok?await t.json():{};return typeof n=="string"&&Vm.test(n)?n:xs}catch{return xs}}a(kE,"supportAddress");function EE(e,t,n){if(process.platform!=="win32"||!fe.licenseServerUrl)return;let r=t?process.execPath:null;return lm({serverUrl:fe.licenseServerUrl,version:e,build:474,exe:r,releaseKeys:fe.releasePublicKeys??{},afterReplace:a((o,i,s)=>{n!==null&&vs(o).toLowerCase()===vs(n.exe).toLowerCase()&&jl(n)&&bs(n,i,o,void 0,void 0,s)},"afterReplace")})}a(EE,"updaterFor");function AE(e=process.env,t=process.platform){return Vt(_n(as(e,t)),"ui.json")}a(AE,"uiStateFile");function SE(e){try{let t=JSON.parse(Zm(e,"utf8")).port;return typeof t=="number"&&Number.isInteger(t)&&t>=1024&&t<=65535?t:0}catch{return 0}}a(SE,"rememberedPort");function DE(e,t){try{Km(_n(e),{recursive:!0}),Jm(e,JSON.stringify({port:t}))}catch{}}a(DE,"rememberPort");async function TE(e,t,n=fm){let r=SE(t),o;try{o=await n({...e,port:r})}catch(s){if(r===0)throw s;o=await n({...e,port:0})}let i=Number(new URL(o.origin).port);return i!==r&&DE(t,i),o}a(TE,"startOnRememberedPort");function CE(e=process.env,t=process.platform){return Vt(_n(as(e,t)),"running.json")}a(CE,"runningAppFile");function nh(e){try{let t=new URL(String(JSON.parse(Zm(e,"utf8")).url));return t.protocol==="http:"&&t.hostname==="127.0.0.1"&&t.searchParams.has("t")?t:null}catch{return null}}a(nh,"readRunningApp");function NE(e,t){try{Km(_n(e),{recursive:!0}),Jm(e,JSON.stringify({url:t}))}catch{}}a(NE,"recordRunningApp");function PE(e,t){try{nh(e)?.href===new URL(t).href&&hE(e,{force:!0})}catch{}}a(PE,"clearRunningApp");async function IE(e,t=fetch,n){let r=nh(e);if(r===null)return null;try{let o=await t(`${r.origin}/api/status`,{headers:{"X-L2W-Token":r.searchParams.get("t")},signal:AbortSignal.timeout(3e3)});if(!o.ok)return null;let i=await o.json();return typeof i.version!="string"||n!==void 0&&((i.environment??"production")!==n.environment||(i.server??null)!==n.server)?null:r}catch{return null}}a(IE,"findRunningApp");function rh(){return us(void 0)}a(rh,"handwritingDesk");function $E(e){return`Sign in TeXConverter for Word as ${e}? Word asked to use the account this computer's TeXConverter app is signed in to. Choose Yes only if you just asked for this in Word.`}a($E,"signInQuestion");function oh(e=ls("desktop"),t=zm()){if(e)return{async email(){let n=await e.status({refresh:"never"});return n.state==="signed_out"?null:n.email??null},confirm:a((n,r)=>t($E(n),r),"confirm"),async approve(n){await e.callAsDevice("POST","/v1/devices/link/approve-from-desktop",{userCode:n})}}}a(oh,"bridgeSignIn");function ih(e,t,n){return Xm({version:e,allowedOrigins:jm(fe.baseUrl),desk:t,signIn:n})}a(ih,"bridgeFor");function sh(e,t){return process.platform==="win32"&&(e.available||t!==void 0)}a(sh,"bridgeUseful");function RE(e,t=Io,n=process.execPath,r=Rr){let o=t==="store"?Vt(_n(n),_o):e?.helperExe;return o!==void 0&&r(o)?o:null}a(RE,"backgroundHelper");var ah="TeXConverter came from the Microsoft Store, so Windows looks after it: it's on the Start Menu, in each .docx and .tex file's Open with menu, and starts its helper at sign-in. Remove it in Settings \u2192 Apps.";async function ME(e,t,n){let r=oh();if(sh(t,r)){if(n!==null){ys(n,["helper"]);return}try{return await ih(e,t,r)}catch(o){o instanceof $r||console.error(`The Word add-in can't reach this app: ${o instanceof Error?o.message:String(o)}`);return}}}a(ME,"serveWordAddIn");async function lh(e){let t=rh(),n=oh();if(!sh(t,n))return 0;let r;try{r=await ih(e,t,n)}catch(i){if(i instanceof $r)return 0;throw i}let o=a(()=>{r.close()},"stop");return process.once("SIGINT",o),process.once("SIGTERM",o),await r.closed,0}a(lh,"runHelper");async function uh(e,t,n,r){if(t===void 0)return console.error("texconverter: this build has no app window. Build it with `npm run build:cli` or `npm run build:desktop`."),1;let o=Yl(),i=Io==="store",s=n&&o!==null?!i&&Rr(o.exe)?o.exe:process.execPath:void 0,l={profile:o?.windowProfile??null,taskbarExe:s,taskbarLauncher:s!==void 0&&o!==null&&s===o.exe&&Rr(o.helperExe)?o.helperExe:s},u=CE(),c=await IE(u,fetch,{environment:fe.environment,server:fe.licenseServerUrl??null});if(c!==null)return Am()||Ym(c.href,l),console.log("TeXConverter is already open; its window has been brought to the front."),ks({ready:!0}),0;n&&!i&&am(process.execPath);let d=rh(),p=await ME(e,d,RE(o)),f=n&&o!==null&&!i?{installed:a(()=>jl(o)&&vs(process.execPath).toLowerCase()===vs(o.exe).toLowerCase(),"installed"),install:a(async()=>(await p?.close(),p=void 0,bs(o,e,process.execPath)),"install")}:void 0,m=Vt(xE(),"TeXConverter"),h=fe.licenseServerUrl?vE(fe.licenseServerUrl):void 0,g=i?void 0:EE(e,n,o),y=g&&{status:g.status,check:g.check,install:g.install,downloadPage:`${fe.baseUrl}/download.html#desktop`},E={environment:fe.environment,server:fe.licenseServerUrl},v={guide:`${fe.baseUrl}/docs/desktop-and-cli.html`,latex:`${fe.baseUrl}/docs/supported-latex.html`,faq:`${fe.baseUrl}/docs/faq.html`,support:a(async()=>`mailto:${await kE(fe.licenseServerUrl)}`,"support")},w=fe.licenseServerUrl?await _l({serverUrl:fe.licenseServerUrl,publicKeys:fe.licensePublicKeys,dir:Ol(),runtime:Fl}):void 0,A=Ol(process.env,process.platform,"","translator"),N=fe.licenseServerUrl?xm(await _l({serverUrl:fe.licenseServerUrl,publicKeys:fe.licensePublicKeys,dir:A,runtime:Fl,offerUrl:`${fe.licenseServerUrl}/v1/translate/offline`,name:"translator",servePath:"/translator/"}),A):void 0,S=await TE({html:t,version:e,outputDir:m,openPath:Es,shell:f,account:r,openUrl:Lo,desk:d,library:h,updates:y,build:E,help:v,reader:w,translator:N},AE());g?.start(),console.log(`TeXConverter ${e} is running, and should have opened in a window of its own.`),console.log(`If it did not, open this address: ${S.url} `),console.log(`Converted files are saved to ${m}`),console.log("Close this window, or the app's window, to quit."),NE(u,S.url),Ym(S.url,l),ks({ready:!0});let k=a(()=>{S.close()},"stop");return process.once("SIGINT",k),process.once("SIGTERM",k),await S.closed,PE(u,S.url),g?.stop(),await N?.close(),await p?.close(),g?.status().state==="restarting"&&(console.log("Updated. Starting the new version\u2026"),process.env[As]?eh(process.execPath,["app"]).unref():On(process.execPath,["app"])),0}a(uh,"runApp");function ch(e,t,n=Io){if(n==="store")return console.log(ah),0;if(!t)return console.error("texconverter: install puts TeXConverter.exe on the right-click menu, so it has to be run from TeXConverter.exe. Build it with `npm run build:desktop`."),1;let r=Yl();if(r===null)return console.error("texconverter: the right-click menu and Start Menu entry are Windows-only for now."),1;try{for(let o of bs(r,e,process.execPath))console.log(` ${o}`);return console.log(` Done. Right-click a .docx or .tex file to convert it, or open TeXConverter from the Start Menu or the desktop.`),0}catch(o){return console.error(`texconverter: ${o instanceof Error?o.message:String(o)}`),1}}a(ch,"runInstall");function dh(e=Io){if(e==="store")return console.log(ah),0;let t=Yl();if(t===null)return console.error("texconverter: there is nothing installed to remove on this system."),1;for(let n of Um(t,process.execPath))console.log(` ${n}`);return 0}a(dh,"runUninstall");x();x();var OE={equation:"Equation",graph:"Graph",table:"Table",diagram:"Diagram",document:"Document"};function _E(e){let t=/^\s*```[\w-]*[ \t]*\r?\n([\s\S]*?)\r?\n?```\s*$/.exec(e);return t?t[1]:e}a(_E,"withoutFence");function ph(e){let t=e.task==="diagram",n=_E(e.source),r=n.split(` `).map(o=>o.trim()).find(o=>o&&!o.startsWith("%")&&!o.startsWith("```")&&!/^\\(begin|end)\{/.test(o))??n.trim();return{id:e.id,from:"creation",kind:t?"diagram":"equation",title:(r.length>80?`${r.slice(0,79)}\u2026`:r)||(t?"Diagram":"Equation"),body:t?{source:n}:{latex:n},surface:"ai",at:e.updatedAt??e.createdAt,pinned:e.pinned}}a(ph,"creationEntry");function fh(e){return{id:e.id,from:"work",kind:e.kind,title:e.title||OE[e.kind],body:e.body,surface:e.surface,at:e.updatedAt,pinned:!1}}a(fh,"workEntry");async function mh(e){let t=[],n=await e("GET","/v1/work?limit=500");for(;;){for(let o of n.items){let i=t.findIndex(s=>s.id===o.id);i>=0&&t.splice(i,1),o.deleted||t.push(o)}if(!n.more)break;n=await e("GET",`/v1/work?since=${n.rev}&limit=500`)}let r=(await e("GET","/v1/ai/creations")).items;return[...t.map(fh),...r.map(ph)].sort((o,i)=>i.at-o.at)}a(mh,"accountWork");var LE={web:"website",word:"Word",desktop:"desktop app",ai:"Create with AI"};function hh(e,t=Date.now()){if(e.length===0)return"Nothing in Your work yet. What you make on the website, in Word or in the app, signed in, is kept here.";let n=Math.max(...e.map(o=>o.id.length));return[...e.map(o=>{let i=LE[o.surface]??o.surface,s=o.kind.padEnd(8);return`${o.id.padEnd(n)} ${s} ${o.pinned?"* ":""}${o.title} (${i}, ${FE(t-o.at)})`}),"",'Run "texconverter work get " to print one.'].join(` `)}a(hh,"formatWorkList");function FE(e){let t=Math.round(e/6e4);if(t<1)return"just now";if(t<60)return`${t} min ago`;let n=Math.round(t/60);return n<48?`${n} h ago`:`${Math.round(n/24)} days ago`}a(FE,"ago");function gh(e){let t=e.body??{};return e.kind==="equation"&&typeof t.latex=="string"?t.latex:e.kind==="diagram"&&typeof t.source=="string"?t.source:JSON.stringify(e.body,null,2)}a(gh,"workText");async function qE(e,t,n={}){let r=await Qi(e,It,n),o=Or(t),i=new Map;for(let[s,l]of r.images)i.set(Jl(o,s),l);return{...r,texPath:t,images:i}}a(qE,"convertDocx");async function wh(e,t={}){let n=Fo(t.output??xh(e,".tex")),r=await qE(new Uint8Array(await bh(e)),n,t);await Zl(Or(n),{recursive:!0}),await Kl(n,r.tex,"utf8");for(let[o,i]of r.images)await Zl(Or(o),{recursive:!0}),await Kl(o,i);return r}a(wh,"convertDocxFile");function xh(e,t){let n=Ql(e);return n===""?e+t:e.slice(0,-n.length)+t}a(xh,"swapExtension");async function vh(e,t={}){let n=await bh(e,"utf8"),r=Or(Fo(e)),o=Fo(t.output??xh(e,".docx")),i=a(c=>{try{return BE(WE(r,c))}catch{return null}},"readRelative"),s=[],l=t.bibFiles??es(n);for(let c of l){let d=i(c)??i(`${c}.bib`);d!==null&&s.push(d.toString("utf8"))}let u=await ns(n,{...t,bibSources:s,resolveInput:a(c=>{let d=i(c)??i(`${c}.tex`);return d===null?null:d.toString("utf8")},"resolveInput"),resolveImage:a(c=>{let d=i(c);return d===null?null:new Uint8Array(d)},"resolveImage")});return await Zl(Or(o),{recursive:!0}),await Kl(o,u.bytes),{...u,docxPath:o}}a(vh,"convertTexFile");function WE(e,t){let n=Fo(e,t);if(n!==e&&!n.startsWith(e+UE))throw new Error(`"${t}" is outside the document's folder.`);return n}a(WE,"resolveWithin");function kh(e){let t=Ql(e).toLowerCase();return t===".docx"?"docx-to-tex":t===".tex"||t===".latex"?"tex-to-docx":null}a(kh,"directionFor");function Eh(e){let t=[` ${e.docxPath}`,` ${e.blocks} blocks, ${e.equations} equations`+(e.images>0?`, ${e.images} images`:"")+(e.citations>0?`, ${e.citations} citations`:"")];for(let n of e.warnings.slice(0,10))t.push(` note: ${n}`);return e.warnings.length>10&&t.push(` ...and ${e.warnings.length-10} more notes`),t.join(` `)}a(Eh,"formatTexReport");var yh=new Set(["article","report","book"]);function HE(e){let t=[...e],n=[],r={};if(t.length===0)return{command:"help",inputs:n,options:r};let o=t[0];if(o==="--help"||o==="-h"||o==="help")return{command:"help",inputs:n,options:r};if(o==="--version"||o==="-v")return{command:"version",inputs:n,options:r};if(o==="app"||o==="install"||o==="uninstall"||o==="login"||o==="logout"||o==="account"||o==="helper")return{command:o,inputs:n,options:r};if(o==="open"){let l=t.slice(1);return l.length!==1?{command:"open",inputs:n,options:r,error:"open takes exactly one file."}:{command:"open",inputs:l,options:r}}if(o==="work"){let l=t.slice(1),u=l[0]??"list";return u==="list"&&l.length<=1?{command:"work",inputs:["list"],options:r}:u==="get"&&l.length===2?{command:"work",inputs:l,options:r}:{command:"work",inputs:n,options:r,error:'work takes "list", or "get" and an id from the list.'}}let i=0;o==="convert"&&(i=1);let s=a(l=>{let u=t[++i];return u===void 0||u.startsWith("-")?null:u},"need");for(;i1&&r.output!==void 0?{command:"convert",inputs:n,options:r,error:"--output names a single file, so it cannot be used with several inputs."}:{command:"convert",inputs:n,options:r}}a(HE,"parseArgs");var GE=`texconverter \u2014 convert between Word documents and LaTeX Usage: texconverter convert [more ...] [options] texconverter app Open the TeXConverter window and drag files into it texconverter install Install TeXConverter: icons on the Start Menu and desktop, and "Convert to LaTeX" / "Convert to Word" on the right-click menu (Windows, TeXConverter.exe only) texconverter uninstall Remove them again texconverter helper Serve handwriting to the Word add-in, with no window (what install starts at sign-in; Windows only) texconverter login Sign in to your TeXConverter account on this computer texconverter logout Sign out on this computer texconverter account Show who is signed in here, and their plan texconverter work List Your work: what you made on the website, in Word, in the app and with AI, kept on your account texconverter work get Print one: an equation's LaTeX, a diagram's source, a graph or table as JSON The direction follows the file: a .docx becomes a .tex, a .tex becomes a .docx. Converting whole files is part of the Documents pack, in every paid plan. Options: -o, --output Where to write the result (default: alongside the input) --images Folder for extracted images (default: images) --image-start First number used in image filenames (default: 1) --class article | report | book (default: article) --font-size 10 | 11 | 12 (default: 11) --no-table-borders Never draw table rules, whatever the source did --no-detect-latex Leave $...$ typed in the text as literal text --dollar smart | always | never - how bare $...$ is read (default: smart, which skips things that look like currency) Converting a .tex: --bib A bibliography to draw references from (repeatable) --bib-style plain | unsrt | ieee (default: plain) --class, --font-size Ignored - the .tex states its own -h, --help Show this -v, --version Show the version Equations TeXConverter cannot represent are listed in the report and left out of the output, rather than the whole document being refused.`;function Ah(e){let t=[` ${e.texPath}`,` ${e.blocks} blocks, ${e.equationsConverted} equations converted`+(e.equationsFromText>0?` (${e.equationsFromText} recognised in the text)`:"")+(e.images.size>0?`, ${e.images.size} images`:"")];if(e.equationsSkipped.length>0){t.push(` ${e.equationsSkipped.length} equations could not be converted:`);for(let n of e.equationsSkipped.slice(0,10))t.push(` equation ${n.index}: ${n.reason}`);e.equationsSkipped.length>10&&t.push(` ...and ${e.equationsSkipped.length-10} more`)}if(e.skippedAsCurrency>0&&t.push(` ${e.skippedAsCurrency} more expressions would convert with --dollar always; they were read as currency because they start with a digit`),e.rejectedText.length>0){t.push(` ${e.rejectedText.length} spans looked like LaTeX but did not parse, and were left as text:`);for(let n of e.rejectedText.slice(0,5))t.push(` ${n.latex.length>50?n.latex.slice(0,49)+"\u2026":n.latex}`);e.rejectedText.length>5&&t.push(` ...and ${e.rejectedText.length-5} more`)}for(let n of e.warnings.slice(0,10))t.push(` note: ${n}`);return t.join(` `)}a(Ah,"formatReport");async function Sh(e){if(!e)return!0;let t=$n(await e.status());return t===null?!0:(console.error(`texconverter: ${t}`),!1)}a(Sh,"documentsAllowed");async function jE(e,t){let n=await e.status();if(n.state!=="signed_out")return console.log(`Already signed in as ${n.email}. Run "texconverter logout" first to switch accounts.`),0;let r=await e.startLink();console.log(`To sign in, open this page in your browser: ${r.verificationUrl} `),console.log(`Sign in there, and check it shows this code: ${r.userCode} `),t(r.verificationUrlComplete),console.log("Waiting for you to approve it... (Ctrl+C to stop)");let o=new AbortController,i=a(()=>o.abort(),"cancel");process.once("SIGINT",i);let s;try{s=await e.waitForLink(r,{signal:o.signal})}finally{process.removeListener("SIGINT",i)}return s==="denied"&&console.error("texconverter: the sign-in was declined on the website."),s==="expired"&&console.error('texconverter: the code expired before it was approved. Run "texconverter login" again.'),s==="cancelled"&&console.error("texconverter: stopped; not signed in."),s!=="approved"?1:Dh(e)}a(jE,"runLogin");async function Dh(e){let t=await e.status();return t.state==="signed_out"?(console.log('Not signed in on this computer. Run "texconverter login".'),0):(console.log(`Signed in as ${t.email}${t.planName?`, ${t.planName} plan`:""}.`),t.state==="limited"&&console.log("Couldn't check the plan just now, so only free features are on until TeXConverter can reach its server."),console.log($n(t)??"Converting whole files: included."),0)}a(Dh,"runAccount");async function XE(e,t){if((await e.status()).state==="signed_out")return console.error('texconverter: Your work is kept on your account. Run "texconverter login" first.'),1;let n=await mh((o,i)=>e.callAsDevice(o,i));if(t[0]!=="get")return console.log(hh(n)),0;let r=n.find(o=>o.id===t[1]);return r?(console.log(gh(r)),0):(console.error(`texconverter: there is nothing in Your work with the id ${t[1]}. Run "texconverter work" for the list.`),1)}a(XE,"runWork");async function zE(e,t){let n=!0,r=0;if(!await Sh(t))return await Ss("Open TeXConverter from the Start Menu to sign in, or to see your plan."),1;try{let o=kh(e);if(o===null)throw new Error("not a .docx or a .tex, so there is no direction to convert it in.");let i=Or(Fo(e)),s=Mr(e,Ql(e));if(console.log(`${Mr(e)} ->`),o==="docx-to-tex"){let l=Vl(i,s,[".tex","-images"]),u=await wh(e,{output:Jl(i,`${l}.tex`),imageFolder:`${l}-images`});console.log(Ah(u)),r=u.warnings.length+u.equationsSkipped.length+u.rejectedText.length,Es(u.texPath,!0)}else{let l=Vl(i,s,[".docx"]),u=await vh(e,{output:Jl(i,`${l}.docx`)});console.log(Eh(u)),r=u.warnings.length,Es(u.docxPath,!1)}}catch(o){n=!1,console.error(`${Mr(e)}: ${o instanceof Error?o.message:String(o)}`)}return(!n||r>0)&&await Ss(n?"Converted, with the notes above.":"Nothing was converted."),n?0:1}a(zE,"runOpen");async function Th(e,t,n={}){let r=HE(e);if(r.command==="help")return console.log(GE),0;if(r.command==="version")return console.log(t),0;if(r.error!==void 0)return console.error(`texconverter: ${r.error}`),console.error('Run "texconverter --help" for usage.'),2;let o=n.account??ls;if(r.command==="app")return uh(t,n.uiHtml,n.isSea===!0,o("desktop"));if(r.command==="install")return ch(t,n.isSea===!0);if(r.command==="uninstall")return dh();if(r.command==="helper")return lh(t);let i=o("cli");if(r.command==="login"||r.command==="logout"||r.command==="account"||r.command==="work"){if(!i)return console.error("texconverter: this build of TeXConverter has no accounts; there is nothing to sign in to."),1;try{return r.command==="login"?await jE(i,n.openUrl??Lo):r.command==="logout"?(await i.signOut(),console.log("Signed out on this computer."),0):r.command==="work"?await XE(i,r.inputs):await Dh(i)}catch(l){return console.error(`texconverter: ${l instanceof Error?l.message:String(l)}`),1}}if(r.command==="open")return zE(r.inputs[0],i);if(!await Sh(i))return console.error('Run "texconverter login" to sign in.'),1;let s=0;for(let l of r.inputs){let u=kh(l);if(u===null){s++,console.error(`${Mr(l)}: not a .docx or a .tex, so there is no direction to convert it in.`);continue}try{console.log(`${Mr(l)} ->`),console.log(u==="docx-to-tex"?Ah(await wh(l,r.options)):Eh(await vh(l,r.options)))}catch(c){s++,console.error(`${Mr(l)}: ${c instanceof Error?c.message:String(c)}`)}}return s>0?1:0}a(Th,"main");var KE="0.6.0-alpha",ZE='\n\n\n\n\nTeXConverter\n\n\n\n\n\n\n\n\n
\n \n\n
\n
\n

Word \u21C4 LaTeX

\n

Turn a Word document into LaTeX you can compile, or a LaTeX file into a Word document whose equations you can click and edit.

\n
\n\n \n \n\n
\n \n
\n

Drop Word or LaTeX files here

\n

Or a whole folder: a .tex is converted together with the chapters, figures and .bib files beside it. Several files convert in one go.

\n
\n \n \n
\n \n \n
\n\n
\n Options\n
\n \n \n
\n
\n\n \n
    \n
    \n\n \n \n\n \n \n\n \n\n \n\n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n\n
    \n \n
    \n
    \n
    \n\n\n\n',Ph=VE();YE([...Ch("default"),...Ch("system")]);var Ih=process.argv.slice(2),Nh=Ph&&Ih.length===0,JE=Nh&&process.platform==="win32"&&!process.env[As]?th(Qm(process.execPath)):Th(Nh?["app"]:Ih,KE,{uiHtml:ZE,isSea:Ph});JE.then(e=>{process.exitCode=e}).catch(e=>{let t=e instanceof Error?e.message:String(e);console.error(`texconverter: ${t}`),ks({error:t}),process.exitCode=1});