UNPKG

ethercalc

Version:

Multi-User Spreadsheet Server — TypeScript rewrite (Cloudflare fullstack)

11 lines 50.9 kB
function e(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function t(e){if(Array.isArray(e))return e}function n(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function r(){throw TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function i(e,i){return t(e)||n(e,i)||a(e,i)||r()}function a(t,n){if(t){if(typeof t==`string`)return e(t,n);var r={}.toString.call(t).slice(8,-1);return r===`Object`&&t.constructor&&(r=t.constructor.name),r===`Map`||r===`Set`?Array.from(t):r===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var o=Object.entries,s=Object.setPrototypeOf,c=Object.isFrozen,l=Object.getPrototypeOf,u=Object.getOwnPropertyDescriptor,d=Object.freeze,f=Object.seal,p=Object.create,m=typeof Reflect<`u`&&Reflect,h=m.apply,g=m.construct;d||=function(e){return e},f||=function(e){return e},h||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},g||=function(e){return new e(...[...arguments].slice(1))};var _=O(Array.prototype.forEach),ee=O(Array.prototype.lastIndexOf),te=O(Array.prototype.pop),v=O(Array.prototype.push),ne=O(Array.prototype.splice),y=Array.isArray,b=O(String.prototype.toLowerCase),re=O(String.prototype.toString),ie=O(String.prototype.match),x=O(String.prototype.replace),ae=O(String.prototype.indexOf),oe=O(String.prototype.trim),se=O(Number.prototype.toString),S=O(Boolean.prototype.toString),C=typeof BigInt>`u`?null:O(BigInt.prototype.toString),ce=typeof Symbol>`u`?null:O(Symbol.prototype.toString),w=O(Object.prototype.hasOwnProperty),T=O(Object.prototype.toString),E=O(RegExp.prototype.test),D=k(TypeError);function O(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return h(e,t,n)}}function k(e){return function(){return g(e,[...arguments])}}function A(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:b;if(s&&s(e,null),!y(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(c(t)||(t[r]=e),i=e)}e[i]=!0}return e}function j(e){for(let t=0;t<e.length;t++)w(e,t)||(e[t]=null);return e}function M(e){let t=p(null);for(let r of o(e)){var n=i(r,2);let a=n[0],o=n[1];w(e,a)&&(y(o)?t[a]=j(o):o&&typeof o==`object`&&o.constructor===Object?t[a]=M(o):t[a]=o)}return t}function le(e){switch(typeof e){case`string`:return e;case`number`:return se(e);case`boolean`:return S(e);case`bigint`:return C?C(e):`0`;case`symbol`:return ce?ce(e):`Symbol()`;case`undefined`:return T(e);case`function`:case`object`:{if(e===null)return T(e);let t=e,n=N(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:T(e)}return T(e)}default:return T(e)}}function N(e,t){for(;e!==null;){let n=u(e,t);if(n){if(n.get)return O(n.get);if(typeof n.value==`function`)return O(n.value)}e=l(e)}function n(){return null}return n}function ue(e){try{return E(e,``),!0}catch{return!1}}var de=d(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),fe=d(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),pe=d([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),me=d([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),he=d(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),ge=d([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),_e=d([`#text`]),ve=d(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.command.commandfor.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns`.split(`.`)),ye=d(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),be=d(`accent.accentunder.align.bevelled.close.columnalign.columnlines.columnspacing.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lquote.lspace.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),xe=d([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),Se=f(/{{[\w\W]*|^[\w\W]*}}/g),Ce=f(/<%[\w\W]*|^[\w\W]*%>/g),we=f(/\${[\w\W]*/g),Te=f(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ee=f(/^aria-[\-\w]+$/),De=f(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Oe=f(/^(?:\w+script|data):/i),ke=f(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ae=f(/^html$/i),je=f(/^[a-z][.\w]*(-[.\w]+)+$/i),P={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Me=function(){return typeof window>`u`?null:window},Ne=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},Pe=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Fe(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Me(),t=e=>Fe(e);if(t.version=`3.4.9`,t.removed=[],!e||!e.document||e.document.nodeType!==P.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,s=e.Node,c=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let u=e.DOMParser,f=e.trustedTypes,m=c.prototype,h=N(m,`cloneNode`),g=N(m,`remove`),se=N(m,`nextSibling`),S=N(m,`childNodes`),C=N(m,`parentNode`),ce=N(m,`shadowRoot`),T=N(m,`attributes`),O=s&&s.prototype?N(s.prototype,`nodeType`):null,k=s&&s.prototype?N(s.prototype,`nodeName`):null;if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let j,F=``,Ie,Le=!1,I=0,Re=function(){if(I>0)throw D(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},L=function(e){Re(),I++;try{return j.createHTML(e)}finally{I--}},ze=function(e){Re(),I++;try{return j.createScriptURL(e)}finally{I--}},Be=function(){return Le||=(Ie=Ne(f,i),!0),Ie},Ve=n,He=Ve.implementation,Ue=Ve.createNodeIterator,We=Ve.createDocumentFragment,Ge=Ve.getElementsByTagName,Ke=r.importNode,R=Pe();t.isSupported=typeof o==`function`&&typeof C==`function`&&He&&He.createHTMLDocument!==void 0;let qe=Se,Je=Ce,Ye=we,Xe=Te,Ze=Ee,Qe=Oe,$e=ke,et=je,tt=De,z=null,nt=A({},[...de,...fe,...pe,...he,..._e]),B=null,rt=A({},[...ve,...ye,...be,...xe]),V=Object.seal(p(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),it=null,at=null,H=Object.seal(p(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ot=!0,st=!0,ct=!1,lt=!0,U=!1,W=!0,G=!1,ut=!1,dt=!1,K=!1,ft=!1,pt=!1,mt=!0,ht=!1,gt=`user-content-`,_t=!0,vt=!1,q={},J=null,yt=A({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),bt=null,xt=A({},[`audio`,`video`,`img`,`source`,`image`,`track`]),St=null,Ct=A({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),wt=`http://www.w3.org/1998/Math/MathML`,Tt=`http://www.w3.org/2000/svg`,Y=`http://www.w3.org/1999/xhtml`,Et=Y,Dt=!1,Ot=null,kt=A({},[wt,Tt,Y],re),At=A({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),jt=A({},[`annotation-xml`]),Mt=A({},[`title`,`style`,`font`,`a`,`script`]),Nt=null,Pt=[`application/xhtml+xml`,`text/html`],X=null,Ft=null,It=n.createElement(`form`),Lt=function(e){return e instanceof RegExp||e instanceof Function},Rt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Ft&&Ft===e)return;(!e||typeof e!=`object`)&&(e={}),e=M(e),Nt=Pt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,X=Nt===`application/xhtml+xml`?re:b,z=w(e,`ALLOWED_TAGS`)&&y(e.ALLOWED_TAGS)?A({},e.ALLOWED_TAGS,X):nt,B=w(e,`ALLOWED_ATTR`)&&y(e.ALLOWED_ATTR)?A({},e.ALLOWED_ATTR,X):rt,Ot=w(e,`ALLOWED_NAMESPACES`)&&y(e.ALLOWED_NAMESPACES)?A({},e.ALLOWED_NAMESPACES,re):kt,St=w(e,`ADD_URI_SAFE_ATTR`)&&y(e.ADD_URI_SAFE_ATTR)?A(M(Ct),e.ADD_URI_SAFE_ATTR,X):Ct,bt=w(e,`ADD_DATA_URI_TAGS`)&&y(e.ADD_DATA_URI_TAGS)?A(M(xt),e.ADD_DATA_URI_TAGS,X):xt,J=w(e,`FORBID_CONTENTS`)&&y(e.FORBID_CONTENTS)?A({},e.FORBID_CONTENTS,X):yt,it=w(e,`FORBID_TAGS`)&&y(e.FORBID_TAGS)?A({},e.FORBID_TAGS,X):M({}),at=w(e,`FORBID_ATTR`)&&y(e.FORBID_ATTR)?A({},e.FORBID_ATTR,X):M({}),q=w(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?M(e.USE_PROFILES):e.USE_PROFILES:!1,ot=e.ALLOW_ARIA_ATTR!==!1,st=e.ALLOW_DATA_ATTR!==!1,ct=e.ALLOW_UNKNOWN_PROTOCOLS||!1,lt=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,U=e.SAFE_FOR_TEMPLATES||!1,W=e.SAFE_FOR_XML!==!1,G=e.WHOLE_DOCUMENT||!1,K=e.RETURN_DOM||!1,ft=e.RETURN_DOM_FRAGMENT||!1,pt=e.RETURN_TRUSTED_TYPE||!1,dt=e.FORCE_BODY||!1,mt=e.SANITIZE_DOM!==!1,ht=e.SANITIZE_NAMED_PROPS||!1,_t=e.KEEP_CONTENT!==!1,vt=e.IN_PLACE||!1,tt=ue(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:De,Et=typeof e.NAMESPACE==`string`?e.NAMESPACE:Y,At=w(e,`MATHML_TEXT_INTEGRATION_POINTS`)&&e.MATHML_TEXT_INTEGRATION_POINTS&&typeof e.MATHML_TEXT_INTEGRATION_POINTS==`object`?M(e.MATHML_TEXT_INTEGRATION_POINTS):A({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),jt=w(e,`HTML_INTEGRATION_POINTS`)&&e.HTML_INTEGRATION_POINTS&&typeof e.HTML_INTEGRATION_POINTS==`object`?M(e.HTML_INTEGRATION_POINTS):A({},[`annotation-xml`]);let t=w(e,`CUSTOM_ELEMENT_HANDLING`)&&e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING==`object`?M(e.CUSTOM_ELEMENT_HANDLING):p(null);if(V=p(null),w(t,`tagNameCheck`)&&Lt(t.tagNameCheck)&&(V.tagNameCheck=t.tagNameCheck),w(t,`attributeNameCheck`)&&Lt(t.attributeNameCheck)&&(V.attributeNameCheck=t.attributeNameCheck),w(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(V.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),U&&(st=!1),ft&&(K=!0),q&&(z=A({},_e),B=p(null),q.html===!0&&(A(z,de),A(B,ve)),q.svg===!0&&(A(z,fe),A(B,ye),A(B,xe)),q.svgFilters===!0&&(A(z,pe),A(B,ye),A(B,xe)),q.mathMl===!0&&(A(z,he),A(B,be),A(B,xe))),H.tagCheck=null,H.attributeCheck=null,w(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?H.tagCheck=e.ADD_TAGS:y(e.ADD_TAGS)&&(z===nt&&(z=M(z)),A(z,e.ADD_TAGS,X))),w(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?H.attributeCheck=e.ADD_ATTR:y(e.ADD_ATTR)&&(B===rt&&(B=M(B)),A(B,e.ADD_ATTR,X))),w(e,`ADD_URI_SAFE_ATTR`)&&y(e.ADD_URI_SAFE_ATTR)&&A(St,e.ADD_URI_SAFE_ATTR,X),w(e,`FORBID_CONTENTS`)&&y(e.FORBID_CONTENTS)&&(J===yt&&(J=M(J)),A(J,e.FORBID_CONTENTS,X)),w(e,`ADD_FORBID_CONTENTS`)&&y(e.ADD_FORBID_CONTENTS)&&(J===yt&&(J=M(J)),A(J,e.ADD_FORBID_CONTENTS,X)),_t&&(z[`#text`]=!0),G&&A(z,[`html`,`head`,`body`]),z.table&&(A(z,[`tbody`]),delete it.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw D(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw D(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=j;j=e.TRUSTED_TYPES_POLICY;try{F=L(``)}catch(e){throw j=t,e}}else e.TRUSTED_TYPES_POLICY===null?(j=void 0,F=``):(j===void 0&&(j=Be()),j&&typeof F==`string`&&(F=L(``)));(R.uponSanitizeElement.length>0||R.uponSanitizeAttribute.length>0)&&z===nt&&(z=M(z)),R.uponSanitizeAttribute.length>0&&B===rt&&(B=M(B)),d&&d(e),Ft=e},zt=A({},[...fe,...pe,...me]),Bt=A({},[...he,...ge]),Vt=function(e){let t=C(e);(!t||!t.tagName)&&(t={namespaceURI:Et,tagName:`template`});let n=b(e.tagName),r=b(t.tagName);return Ot[e.namespaceURI]?e.namespaceURI===Tt?t.namespaceURI===Y?n===`svg`:t.namespaceURI===wt?n===`svg`&&(r===`annotation-xml`||At[r]):!!zt[n]:e.namespaceURI===wt?t.namespaceURI===Y?n===`math`:t.namespaceURI===Tt?n===`math`&&jt[r]:!!Bt[n]:e.namespaceURI===Y?t.namespaceURI===Tt&&!jt[r]||t.namespaceURI===wt&&!At[r]?!1:!Bt[n]&&(Mt[n]||!zt[n]):!!(Nt===`application/xhtml+xml`&&Ot[e.namespaceURI]):!1},Z=function(e){v(t.removed,{element:e});try{C(e).removeChild(e)}catch{if(g(e),!C(e))throw D(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},Ht=function(e){let t=S?S(e):e.childNodes;if(t){let e=[];_(t,t=>{v(e,t)}),_(e,e=>{try{g(e)}catch{}})}let n=T?T(e):null;if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;if(typeof i==`string`)try{e.removeAttribute(i)}catch{}}},Q=function(e,n){try{v(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{v(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(K||ft)try{Z(n)}catch{}else try{n.setAttribute(e,``)}catch{}},Ut=function(e){let t=T?T(e):e.attributes;if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;if(!(typeof i!=`string`||B[X(i)]))try{e.removeAttribute(i)}catch{}}},Wt=function(e){let t=[e];for(;t.length>0;){let e=t.pop();(O?O(e):e.nodeType)===P.element&&Ut(e);let n=S?S(e):e.childNodes;if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Gt=function(e){let t=null,r=null;if(dt)e=`<remove></remove>`+e;else{let t=ie(e,/^[\r\n\t ]+/);r=t&&t[0]}Nt===`application/xhtml+xml`&&Et===Y&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=j?L(e):e;if(Et===Y)try{t=new u().parseFromString(i,Nt)}catch{}if(!t||!t.documentElement){t=He.createDocument(Et,`template`,null);try{t.documentElement.innerHTML=Dt?F:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Et===Y?Ge.call(t,G?`html`:`body`)[0]:G?t.documentElement:a},Kt=function(e){return Ue.call(e.ownerDocument||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},qt=function(e){e.normalize();let t=Ue.call(e.ownerDocument||e,e,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),n=t.nextNode();for(;n;){let e=n.data;_([qe,Je,Ye],t=>{e=x(e,t,` `)}),n.data=e,n=t.nextNode()}let r=e.querySelectorAll?.call(e,`template`)??[];_(Array.from(r),e=>{Yt(e.content)&&qt(e.content)})},Jt=function(e){let t=k?k(e):null;return typeof t!=`string`||X(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==T(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==O(e)||e.childNodes!==S(e)},Yt=function(e){if(!O||typeof e!=`object`||!e)return!1;try{return O(e)===P.documentFragment}catch{return!1}},Xt=function(e){if(!O||typeof e!=`object`||!e)return!1;try{return typeof O(e)==`number`}catch{return!1}};function $(e,n,r){_(e,e=>{e.call(t,n,r,Ft)})}let Zt=function(e){let n=null;if($(R.beforeSanitizeElements,e,null),Jt(e))return Z(e),!0;let r=X(k?k(e):e.nodeName);if($(R.uponSanitizeElement,e,{tagName:r,allowedTags:z}),W&&e.hasChildNodes()&&!Xt(e.firstElementChild)&&E(/<[/\w!]/g,e.innerHTML)&&E(/<[/\w!]/g,e.textContent)||W&&e.namespaceURI===Y&&r===`style`&&Xt(e.firstElementChild)||e.nodeType===P.progressingInstruction||W&&e.nodeType===P.comment&&E(/<[/\w]/g,e.data))return Z(e),!0;if(it[r]||!(H.tagCheck instanceof Function&&H.tagCheck(r))&&!z[r]){if(!it[r]&&en(r)&&(V.tagNameCheck instanceof RegExp&&E(V.tagNameCheck,r)||V.tagNameCheck instanceof Function&&V.tagNameCheck(r)))return!1;if(_t&&!J[r]){let t=C(e),n=S(e);if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=vt?n[i]:h(n[i],!0);t.insertBefore(r,se(e))}}}return Z(e),!0}return(O?O(e):e.nodeType)===P.element&&!Vt(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&E(/<\/no(script|embed|frames)/i,e.innerHTML)?(Z(e),!0):(U&&e.nodeType===P.text&&(n=e.textContent,_([qe,Je,Ye],e=>{n=x(n,e,` `)}),e.textContent!==n&&(v(t.removed,{element:e.cloneNode()}),e.textContent=n)),$(R.afterSanitizeElements,e,null),!1)},Qt=function(e,t,r){if(at[t]||mt&&(t===`id`||t===`name`)&&(r in n||r in It))return!1;let i=B[t]||H.attributeCheck instanceof Function&&H.attributeCheck(t,e);if(!(st&&!at[t]&&E(Xe,t))&&!(ot&&E(Ze,t))){if(!i||at[t]){if(!(en(e)&&(V.tagNameCheck instanceof RegExp&&E(V.tagNameCheck,e)||V.tagNameCheck instanceof Function&&V.tagNameCheck(e))&&(V.attributeNameCheck instanceof RegExp&&E(V.attributeNameCheck,t)||V.attributeNameCheck instanceof Function&&V.attributeNameCheck(t,e))||t===`is`&&V.allowCustomizedBuiltInElements&&(V.tagNameCheck instanceof RegExp&&E(V.tagNameCheck,r)||V.tagNameCheck instanceof Function&&V.tagNameCheck(r))))return!1}else if(!St[t]&&!E(tt,x(r,$e,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&ae(r,`data:`)===0&&bt[e])&&!(ct&&!E(Qe,x(r,$e,``)))&&r)return!1}return!0},$t=A({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),en=function(e){return!$t[b(e)]&&E(et,e)},tn=function(e){$(R.beforeSanitizeAttributes,e,null);let n=e.attributes;if(!n||Jt(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:B,forceKeepAttr:void 0},i=n.length;for(;i--;){let a=n[i],o=a.name,s=a.namespaceURI,c=a.value,l=X(o),u=c,d=o===`value`?u:oe(u);if(r.attrName=l,r.attrValue=d,r.keepAttr=!0,r.forceKeepAttr=void 0,$(R.uponSanitizeAttribute,e,r),d=r.attrValue,ht&&(l===`id`||l===`name`)&&ae(d,gt)!==0&&(Q(o,e),d=gt+d),W&&E(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){Q(o,e);continue}if(l===`attributename`&&ie(d,`href`)){Q(o,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){Q(o,e);continue}if(!lt&&E(/\/>/i,d)){Q(o,e);continue}U&&_([qe,Je,Ye],e=>{d=x(d,e,` `)});let p=X(e.nodeName);if(!Qt(p,l,d)){Q(o,e);continue}if(j&&typeof f==`object`&&typeof f.getAttributeType==`function`&&!s)switch(f.getAttributeType(p,l)){case`TrustedHTML`:d=L(d);break;case`TrustedScriptURL`:d=ze(d);break}if(d!==u)try{s?e.setAttributeNS(s,o,d):e.setAttribute(o,d),Jt(e)?Z(e):te(t.removed)}catch{Q(o,e)}}$(R.afterSanitizeAttributes,e,null)},nn=function(e){let t=null,n=Kt(e);for($(R.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(R.uponSanitizeShadowNode,t,null),Zt(t),tn(t),Yt(t.content)&&nn(t.content),(O?O(t):t.nodeType)===P.element){let e=ce?ce(t):t.shadowRoot;Yt(e)&&(rn(e),nn(e))}$(R.afterSanitizeShadowDOM,e,null)},rn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){nn(e.shadow);continue}let n=e.node,r=(O?O(n):n.nodeType)===P.element,i=S?S(n):n.childNodes;if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=k?k(n):null;if(typeof e==`string`&&X(e)===`template`){let e=n.content;Yt(e)&&t.push({node:e,shadow:null})}}if(r){let e=ce?ce(n):n.shadowRoot;Yt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(Dt=!e,Dt&&(e=`<!-->`),typeof e!=`string`&&!Xt(e)&&(e=le(e),typeof e!=`string`))throw D(`dirty is not a string, aborting`);if(!t.isSupported)return e;ut||Rt(n),t.removed=[];let c=vt&&typeof e!=`string`&&Xt(e);if(c){let t=k?k(e):e.nodeName;if(typeof t==`string`){let e=X(t);if(!z[e]||it[e])throw D(`root node is forbidden and cannot be sanitized in-place`)}if(Jt(e))throw D(`root node is clobbered and cannot be sanitized in-place`);try{rn(e)}catch(t){throw Ht(e),t}}else if(Xt(e))i=Gt(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===P.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),rn(a);else{if(!K&&!U&&!G&&e.indexOf(`<`)===-1)return j&&pt?L(e):e;if(i=Gt(e),!i)return K?null:pt?F:``}i&&dt&&Z(i.firstChild);let l=Kt(c?e:i);try{for(;o=l.nextNode();)Zt(o),tn(o),Yt(o.content)&&nn(o.content)}catch(t){throw c&&Ht(e),t}if(c)return _(t.removed,e=>{e.element&&Wt(e.element)}),U&&qt(e),e;if(K){if(U&&qt(i),ft)for(s=We.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(B.shadowroot||B.shadowrootmode)&&(s=Ke.call(r,s,!0)),s}let u=G?i.outerHTML:i.innerHTML;return G&&z[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&E(Ae,i.ownerDocument.doctype.name)&&(u=`<!DOCTYPE `+i.ownerDocument.doctype.name+`> `+u),U&&_([qe,Je,Ye],e=>{u=x(u,e,` `)}),j&&pt?L(u):u},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rt(e),ut=!0},t.clearConfig=function(){Ft=null,ut=!1,j=Ie,F=``},t.isValidAttribute=function(e,t,n){Ft||Rt({});let r=X(e),i=X(t);return Qt(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&v(R[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=ee(R[e],t);return n===-1?void 0:ne(R[e],n,1)[0]}return te(R[e])},t.removeHooks=function(e){R[e]=[]},t.removeAllHooks=function(){R=Pe()},t}var F=Fe();function Ie(e){let t=e;t.charAt(0)===`?`&&(t=t.substr(1));let n={};if(!t)return n;let r=t.split(`&`);for(let e of r){let t=e.indexOf(`=`),r=t>=0?e.slice(0,t):e,i=t>=0?e.slice(t+1):``;r&&(n[decodeURIComponent(r)]=decodeURIComponent(i))}return n}function Le(e,t){if(e.OrigDoPositionCalculations)return!1;e.requestParams=Ie(t.search??``);let n=e.DoPositionCalculations;n&&(e.OrigDoPositionCalculations=n),e.DoPositionCalculations=function(...t){let r=n?.apply(e,t);return e.Callbacks.broadcast?.(`ask.ecell`),r};let r=t.win??{};if(r.CryptoJS){let t=e=>r.CryptoJS.MD5(e).toString();e.hadSnapshot=!0;let n=e.LoadEditorSettings;n&&(e.OrigLoadEditorSettings=n),e.LoadEditorSettings=(r,i,a)=>{r.SettingsCallbacks.ethercalc={save:()=>`ethercalc:${t(r.context.sheetobj.CreateSheetSave())}\n`,load:(n,r,i)=>{i.replace(/^\w+:/,``)===t(n.context.sheetobj.CreateSheetSave())?e.hadSnapshot=!1:e.hadSnapshot=!0}},n?e.LoadEditorSettings=n:delete e.LoadEditorSettings,n?.(r,i,a)}}else e.hadSnapshot=!1;let i=e.SizeSSDiv;i&&(e.OrigSizeSSDiv=i),e.SizeSSDiv=e=>{!e||!e.parentNode||i?.(e)},e.Sheet&&e.Sheet.prototype&&(e.Sheet.prototype.ScheduleSheetCommands=function(...t){e.ScheduleSheetCommands?.(this,t[0],t[1],t[2])});let a=e.ScheduleSheetCommands;return a&&(e.OrigScheduleSheetCommands=a),e.ScheduleSheetCommands=(n,r,i,o)=>{let s=r.replace(/\n\n+/g,` `);if(/\S/.test(s)){if(!o&&s!==`redisplay`&&s!==`recalc`){let r=t.win?.__MULTI__;if(r?.rows?.length&&/set \w+ formula /.test(s))for(let{link:e,title:t}of r.rows){let n=RegExp(`\\$${t}\\.([A-Z]+[1-9][0-9]*)`,`ig`);s=s.replace(n,`"${e.replace(`/`,``)}"!$1`)}e.Callbacks.broadcast?.(`execute`,{cmdstr:s,saveundo:i,room:n._room})}a?.(n,s,i,o)}},e.MoveECell=(t,n)=>{let r=t.context.highlights,i=n;if(t.ecell){if(t.ecell.coord===i)return i;e.Callbacks.broadcast?.(`ecell`,{original:t.ecell.coord,ecell:i});let n=e.GetEditorCellElement?.(t,t.ecell.row,t.ecell.col);delete r[t.ecell.coord];let a=t.range2;a.hasrange&&t.ecell.row>=a.top&&t.ecell.row<=a.bottom&&t.ecell.col>=a.left&&t.ecell.col<=a.right&&(r[t.ecell.coord]=`range2`),t.UpdateCellCSS(n,t.ecell.row,t.ecell.col),t.SetECellHeaders(``),t.cellhandles.ShowCellHandles(!1)}else e.Callbacks.broadcast?.(`ecell`,{ecell:i});i=t.context.cellskip[i]??i,t.ecell=e.coordToCr(i),t.ecell.coord=i;let a=e.GetEditorCellElement?.(t,t.ecell.row,t.ecell.col);r[i]=`cursor`;for(let e of Object.keys(t.MoveECellCallback))t.MoveECellCallback[e](t);t.UpdateCellCSS(a,t.ecell.row,t.ecell.col),t.SetECellHeaders(`selected`);for(let e of Object.keys(t.StatusCallback)){let n=t.StatusCallback[e];n.func(t,`moveecell`,i,n.params)}return t.busy?t.ensureecell=!0:(t.ensureecell=!1,t.EnsureECellVisible()),i},!0}function I(e,t){e.Callbacks=e.Callbacks??{},e.Callbacks.broadcast=t}function Re(e,t){e.RecalcInfo.LoadSheetCache={},e.RecalcInfo.LoadSheet=e=>{t(`ask.recalc`,{room:e.toLowerCase()})}}var L=[`log`,`recalc`,`snapshot`,`ecells`,`execute`,`chat`,`confirmemailsent`,`ignore`,`stopHuddle`,`ecell`,`my.ecell`,`ask.ecell`];function ze(e){return JSON.stringify(e)}function Be(e){return Ve(e,L)}function Ve(e,t){let n=He(e);if(typeof n!=`object`||!n||Array.isArray(n))return null;let r=n.type;return t.includes(r)?n:null}function He(e){try{return JSON.parse(e)}catch{return null}}var Ue=1;function We(e){let t=globalThis.WebSocket;if(!t)throw Error(`ws-adapter: no global WebSocket; pass wsFactory explicitly`);return new t(e)}function Ge(e,t){return globalThis.setTimeout(e,t)}function Ke(e){globalThis.clearTimeout(e)}function R(e){return e.startsWith(`http://`)?`ws://`+e.slice(7):e.startsWith(`https://`)?`wss://`+e.slice(8):e}function qe(e){let t=R(e.url.replace(/\/+$/,``)),n=new URLSearchParams;return n.set(`user`,e.user),e.auth!==void 0&&n.set(`auth`,e.auth),`${t}/_ws/${encodeURIComponent(e.room)}?${n.toString()}`}function Je(e,t,n){let r={...t};return r.type=e,r.user=n.user,r.room===void 0&&(r.room=n.room),n.auth!==void 0&&(r.auth=n.auth),r}function Ye(e){let t=e.reconnectDelayMs??500,n=e.maxReconnectAttempts??1800,r=e.wsFactory??We,i=e.setTimeoutFn??Ge,a=e.clearTimeoutFn??Ke,o=qe(e),s=new Set,c=[],l=null,u=!1,d=0,f=null;function p(t){e.onStatus?.(t)}function m(){let e;try{e=r(o)}catch{te();return}l=e,e.addEventListener(`open`,h),e.addEventListener(`close`,g),e.addEventListener(`error`,_),e.addEventListener(`message`,ee)}function h(){d=0,p({type:`open`}),v()}function g(e){p({type:`close`,code:e.code,reason:e.reason}),l=null,te()}function _(){p({type:`error`})}function ee(e){if(typeof e.data!=`string`)return;let t=Be(e.data);if(t)for(let e of s)e(t)}function te(){if(!u){if(d>=n){p({type:`reconnect_failed`});return}d++,p({type:`reconnecting`,attempt:d}),f=i(()=>{f=null,m()},t)}}function v(){for(;c.length>0;){let e=c.shift();l.send(e)}}function ne(t,n={}){if(u)return;let r=ze(Je(t,n,e));l&&l.readyState===Ue?l.send(r):c.push(r)}function y(e){return s.add(e),()=>{s.delete(e)}}function b(){if(u=!0,f!==null&&(a(f),f=null),l){try{l.close()}catch{}l=null}s.clear(),c.length=0}return m(),{broadcast:ne,onMessage:y,close:b,get queueLength(){return c.length},get connected(){return l!==null&&l.readyState===Ue},get reconnectAttempts(){return d}}}function Xe(){return Math.random().toString()}function Ze(e){return e.replace(/^_+/,``).replace(/\?.*/,``)}function Qe(e){let t=e.host,n=t.SocialCalc,r=e.randomUsername??Xe;n.requestParams=Ie(t.location.search),n._username=r(),n.isConnected=!0;let i=n.requestParams;i.auth!==void 0&&(n._auth=i.auth),i.app!==void 0&&(n._app=!0),i.view!==void 0&&(n._view=!0);let a=n._room;if(a||=t.EtherCalc?._room,a||=t.location.hash.replace(`#`,``),!a)return null;a=Ze(a),n._room=a;let o=n._app?`/app`:n._view?`/view`:n._auth===void 0?``:`/edit`;t.history.pushState({},``,`./${a}${o}`);let s=e.baseUrl??$e(t.location.pathname,a),c=Ye({room:a,user:n._username,auth:n._auth,url:s,reconnectDelayMs:e.reconnectDelayMs,maxReconnectAttempts:e.maxReconnectAttempts,wsFactory:e.wsFactory,setTimeoutFn:e.setTimeoutFn,clearTimeoutFn:e.clearTimeoutFn,onStatus:e.onStatus}),l=(e,t)=>{c.broadcast(e,t)};I(n,l),Le(n,{broadcast:l,search:t.location.search}),Re(n,l);let u=tt(t);return c.onMessage(u),{adapter:c,username:n._username,room:a,broadcast:l,stop(){c.close()}}}function $e(e,t){let n=e.replace(/\/(view|edit|app)$/,``).replace(RegExp(`/${et(t)}$`),``);return n===``?`/`:n}function et(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function tt(e){return function(t){let n=e.SocialCalc;if(!n.isConnected)return;let r=e.spreadsheet;if(!r)return;let i=t.room;if(t.user===n._username&&i===n._room)return;let a=t.to;if(a&&a!==n._username||i&&i!==n._room&&r.formDataViewer?._room!==i&&t.type===`log`)return;let o=r;if(i&&i!==n._room&&t.type!==`recalc`&&t.type!==`log`){if(r.formDataViewer?._room!==i)return;o=r.formDataViewer}switch(t.type){case`confirmemailsent`:n.EditorSheetStatusCallback?.(null,`confirmemailsent`,t.message,o.editor);return;case`chat`:e.addmsg?.(t.msg);return;case`ecells`:if(n._app)return;nt(n,o,t);return;case`ecell`:B(n,o,t);return;case`log`:rt(e,o,t);return;case`snapshot`:at(n,o,t);return;case`recalc`:H(n,o,t);return;case`execute`:ot(e,o,t);return;case`stopHuddle`:return;case`ask.ecell`:z(n,o,t);return;case`my.ecell`:case`ignore`:return}}}function z(e,t,n){if(e._app)return;let r=t.editor.ecell.coord;if(!r)return;let i={ecell:r};n.user!==void 0&&(i.to=n.user),e.Callbacks.broadcast?.(`ecell`,i)}function nt(e,t,n){let r=t.editor;for(let[t,i]of Object.entries(n.ecells)){if(t===e._username)continue;let n=` ${t} defaultPeer`,a=new RegExp(n,`g`),o=e.coordToCr?.(i);if(!o)continue;let s=e.GetEditorCellElement?.(r,o.row,o.col);s&&s.element.className.search(a)===-1&&(s.element.className+=n)}}function B(e,t,n){let r=t.editor,i=` ${n.user} defaultPeer`,a=new RegExp(i,`g`);if(n.original){let t=e.coordToCr?.(n.original);if(t){let n=e.GetEditorCellElement?.(r,t.row,t.col);n&&(n.element.className=n.element.className.replace(a,``))}(n.original===r.ecell.coord||n.ecell===r.ecell.coord)&&e.Callbacks.broadcast?.(`ecell`,{to:n.user,ecell:r.ecell.coord})}if(e._app)return;let o=e.coordToCr?.(n.ecell);if(!o)return;let s=e.GetEditorCellElement?.(r,o.row,o.col);s&&s.element.className.search(a)===-1&&(s.element.className+=i)}function rt(e,t,n){let r=e.SocialCalc,i=e.spreadsheet;if(i.formDataViewer?._room===n.room){V(i,n);return}if(r.hadSnapshot)return;r.hadSnapshot=!0;let a;n.snapshot&&(a=t.DecodeSpreadsheetSave(n.snapshot)),a&&(a.sheet&&(t.sheet.ResetSheet(),t.ParseSheetSave(n.snapshot.substring(a.sheet.start,a.sheet.end))),a.edit&&(t.editor.SettingsCallbacks,(r.LoadEditorSettings??(()=>{}))(t.editor,n.snapshot.substring(a.edit.start,a.edit.end),void 0))),e.addmsg?.(n.chat.join(` `),!0);let o=n.log.filter(e=>!/^re(calc|display)$/.test(e)).join(` `);o.length?t.context.sheetobj.ScheduleSheetCommands(`${o}\nrecalc\n`,!1,!0):t.context.sheetobj.ScheduleSheetCommands(`recalc `,!1,!0)}function V(e,t){let n;t.snapshot&&(n=e.DecodeSpreadsheetSave(t.snapshot));let r=e.formDataViewer;r.sheet.ResetSheet(),r.loaded=!0,e.editor,it(`ask.log`),n?.sheet&&(r.ParseSheetSave(t.snapshot.substring(n.sheet.start,n.sheet.end)),r.context.sheetobj.ScheduleSheetCommands(`recalc `,!1,!0))}function it(e,t){globalThis.SocialCalc?.Callbacks.broadcast?.(e,t)}function at(e,t,n){let r=e;r.hadSnapshot=!0;let i=n.snapshot?t.DecodeSpreadsheetSave(n.snapshot):void 0;i?.sheet&&(t.sheet.ResetSheet(),t.ParseSheetSave(n.snapshot.substring(i.sheet.start,i.sheet.end)),t.context.sheetobj.ScheduleSheetCommands(`recalc `,!1,!0))}function H(e,t,n){if(n.force){let r=e.Formula?.SheetCache?.sheets;r&&delete r[n.room],t.sheet.recalconce=!0}let r=n.snapshot?t.DecodeSpreadsheetSave(n.snapshot):void 0;if(r?.sheet){let i=n.snapshot.substring(r.sheet.start,r.sheet.end);e.RecalcLoadedSheet?.(n.room,i,!0);let a=e.RecalcInfo.LoadSheetCache;a&&a[n.room]!==i&&(a[n.room]=i,t.context.sheetobj.ScheduleSheetCommands(`recalc `,!1,!0))}else e.RecalcLoadedSheet?.(n.room,``,!0)}function ot(e,t,n){t.context.sheetobj.ScheduleSheetCommands(n.cmdstr,!1,!0);let r=e.spreadsheet,i=r?.tabnums?.graph;r&&i!==void 0&&r.currentTab===i&&e.setTimeout(()=>e.DoGraph?.(!1,!1),100)}var st=[`ff0`,`0ff`,`f0f`,`00f`,`f00`,`0f0`,`888`,`880`,`088`,`808`,`008`,`800`,`080`];function ct(e=Math.random){let t=0,n=()=>{let n=st[t++];if(n)return n;let r=``;for(let t=0;t<6;t++)r+=st[Math.round(e()*14)]??`0`;return r.slice(0,6)};return{getBarColor:n,getDrawColor:()=>`#${n()}`,reset:()=>{t=0}}}function lt(e){let{SocialCalc:t,win:n,doc:r}=e,i=ct();function a(e){let n=t.GetSpreadsheetControlObject?.();if(!n?.idPrefix)return;let i=r.getElementById(n.idPrefix+`graphlist`);!i||!i.options[0]||(e.range.hasrange?i.options[0].text=t.crToCoord(e.range.left,e.range.top)+`:`+t.crToCoord(e.range.right,e.range.bottom):i.options[0].text=t.LocalizeString?.(`[select range]`)??`[select range]`)}let o=e=>{i.reset();let n=t.LocalizeString??(e=>e),o=[],s=r.getElementById((e.idPrefix??``)+`graphlist`);e.editor.RangeChangeCallback.graph=a;for(let t of Object.keys(e.sheet.names??{}))o.push(t);if(o.sort(),!s)return;s.length=0,s.options[0]=new Option(n(`[select range]`));for(let t=0;t<o.length;t++){let n=o[t];s.options[t+1]=new Option(n,n),n===e.graphrange&&(s.options[t+1].selected=!0)}e.graphrange===``&&(s.options[0].selected=!0),a(e.editor);let l=r.getElementById((e.idPrefix??``)+`graphtype`);if(!l)return;l.length=0;let u=t.GraphTypesInfo;for(let t=0;t<u.displayorder.length;t++){let r=u.displayorder[t],i=u[r];l.options[t]=new Option(n(i.display),r),r===e.graphtype&&(l.options[t].selected=!0)}e.graphtype||=(l.options[0].selected=!0,l.options[0].value),c(!1,!0)};function s(){let e=t.GetSpreadsheetControlObject?.();if(!e?.idPrefix)return;let n=e.editor,i=r.getElementById(e.idPrefix+`graphlist`);if(!i)return;i.selectedIndex===0?n.range.hasrange?e.graphrange=t.crToCoord(n.range.left,n.range.top)+`:`+t.crToCoord(n.range.right,n.range.bottom):e.graphrange=n.ecell.coord+`:`+n.ecell.coord:e.graphrange=i.options[i.selectedIndex].value;let a=r.getElementById(e.idPrefix+`graphrange`);a&&(a.innerHTML=e.graphrange),c(!1,!1)}function c(e,n){i.reset();let r=t.GetSpreadsheetControlObject?.();if(!r?.graphtype)return;let a=r.views?.graph?.element;if(!a)return;let o=t.GraphTypesInfo[r.graphtype]?.func;if(!r.graphrange){o&&e?o(r,null,a,r.graphtype,e,n):a.innerHTML=`<div style="padding:30px;font-weight:bold;">${t.Constants.s_GraphRangeNotSelected??`Graph range not selected`}</div>`;return}let s=r.graphrange;if(s&&s.indexOf(`:`)===-1){let e=t.Formula?.LookupName?.(r.sheet,s);if(!e||e.type!==`range`){a.innerHTML=(t.LocalizeString?.(`Unknown range name`)??`Unknown range name`)+`: `+s;return}let n=/^(.*)\|(.*)\|$/.exec(e.value);if(!n)return;s=n[1]+`:`+n[2]}let c=t.ParseRange?.(s);if(!c)return;let l={left:Math.min(c.cr1.col,c.cr2.col),right:Math.max(c.cr1.col,c.cr2.col),top:Math.min(c.cr1.row,c.cr2.row),bottom:Math.max(c.cr1.row,c.cr2.row)};o?.(r,l,a,r.graphtype,e,n)}function l(e){let t=n.spreadsheet;t&&(t.graphtype=e.options[e.selectedIndex].value),c(!1,!1)}function u(e,t){let r=n.spreadsheet;if(r){switch(t){case 0:r.graphMinX=e.value;break;case 1:r.graphMaxX=e.value;break;case 2:r.graphMinY=e.value;break;case 3:r.graphMaxY=e.value;break}c(!1,!0)}}function d(){let e=t.GetSpreadsheetControlObject?.();if(!e)return``;let n=e.graphtype??``,r=t.encodeForSave??(e=>e),i=`graph:range:`+r(e.graphrange??``)+`:type:`+r(n);return i+=`:minmax:`+r(`${e.graphMinX??``},${e.graphMaxX??``},${e.graphMinY??``},${e.graphMaxY??``}`)+` `,i}function f(e,n,i){let a=t.GetSpreadsheetControlObject?.();if(!a)return!1;let o=t.decodeFromSave??(e=>e),s=i.split(`:`);for(let e=1;e<s.length;e+=2)switch(s[e]){case`type`:a.graphtype=o(s[e+1]??``);break;case`range`:a.graphrange=o(s[e+1]??``);break;case`minmax`:{let t=o(s[e+1]??``).split(`,`),n=[`SocialCalc-graphMinX`,`SocialCalc-graphMaxX`,`SocialCalc-graphMinY`,`SocialCalc-graphMaxY`],i=[`graphMinX`,`graphMaxX`,`graphMinY`,`graphMaxY`];for(let e=0;e<4;e++){a[i[e]]=t[e]??``;let o=r.getElementById(n[e]);o&&(o.value=t[e]??``)}break}}return!0}n.GraphOnClick=o,n.GraphSetCells=s,n.DoGraph=c,n.GraphChanged=l,n.MinMaxChanged=u,n.GraphSave=d,n.GraphLoad=f,t.GraphTypesInfo={displayorder:[`verticalbar`,`horizontalbar`,`piechart`,`linechart`,`scatterchart`],verticalbar:{display:t.Constants.s_loc_vertical_bar??`Vertical Bar`,func:G(e,i)},horizontalbar:{display:t.Constants.s_loc_horizontal_bar??`Horizontal Bar`,func:ut(e,i)},piechart:{display:t.Constants.s_loc_pie_chart??`Pie Chart`,func:dt(e,i)},linechart:{display:t.Constants.s_loc_line_chart??`Line Chart`,func:K(e,i)},scatterchart:{display:t.Constants.s_loc_scatter_chart??`Scatter Chart`,func:ft(e,i)}},U(t)}function U(e){let t=e.Constants;t.s_loc_horizontal_bar=`Horizontal Bar`,t.s_loc_vertical_bar=`Vertical Bar`,t.s_loc_pie_chart=`Pie Chart`,t.s_loc_line_chart=`Line Chart`,t.s_loc_scatter_chart=`Scatter Chart`,t.s_loc_hide_help=`Hide Help`;let n=`A6A6A6`,r=`FFF`;e.requestParams?.app!==void 0&&(n=`FFF`,r=`000`),t.SCToolbarbackground=`background-color:#404040;`,t.SCTabbackground=`background-color:#808080;`,t.SCTabselectedCSS=`font-size:small;padding:6px 30px 6px 8px;color:#FFF;background-color:#404040;cursor:default;border-right:1px solid #CCC;`,t.SCTabplainCSS=`font-size:small;padding:6px 30px 6px 8px;color:#FFF;background-color:#808080;cursor:default;border-right:1px solid #CCC;`,t.SCToolbartext=`font-size:x-small;font-weight:bold;color:#FFF;padding-bottom:4px;`,t.ISCButtonBorderNormal=`#404040`,t.ISCButtonBorderHover=`#999`,t.ISCButtonBorderDown=`#FFF`,t.ISCButtonDownBackground=`#888`,t.defaultImagePrefix=`images/sc_`,t.defaultColnameStyle=`overflow:visible;font-size:small;text-align:center;color:#`+r+`;background-color:#808080`,t.defaultSelectedColnameStyle=`overflow:visible;font-size:small;text-align:center;color:#`+r+`;background-color:#404040`,t.defaultRownameStyle=`position:relative;overflow:visible;font-size:small;text-align:center;vertical-align:middle;color:#`+r+`;background-color:#808080;direction:rtl;`,t.defaultSelectedRownameStyle=`position:relative;overflow:visible;font-size:small;text-align:center;vertical-align:middle;color:#`+r+`;background-color:#404040;`,t.defaultHighlightTypeCursorStyle=`color:#`+r+`;backgroundColor:#`+n+`;`}function W(e,t,n){let r=[],i=[],a,o;n.left===n.right?(o=n.bottom-n.top+1,a=!0):(o=n.right-n.left+1,a=!1);let s=e.SocialCalc.rcColname;for(let e=0;e<o;e++){let o=a?s(n.left)+(e+n.top):s(e+n.left)+n.top,c=a?s(n.left-1||1)+(e+n.top):s(e+n.left)+(n.top-1||1),l=t.sheet.GetAssuredCell(o);if(String(l.valuetype).charAt(0)===`n`){let e=Number(l.datavalue);r.push(e);let a=t.sheet.GetAssuredCell(c);(n.right===n.left||n.top===n.bottom)&&(String(a.valuetype).charAt(0)===`t`||String(a.valuetype).charAt(0)===`n`)?i.push(String(a.datavalue)):i.push(String(e))}}return{values:r,labels:i,byrow:a,nitems:o}}function G(e,t){return(n,r,i,a,o)=>{if(o||!r){i.innerHTML=`<input type="button" value="${e.SocialCalc.Constants.s_loc_hide_help??`Hide Help`}" onclick="DoGraph(false,false);"><br><br>This is the help text for graph type: ${e.SocialCalc.GraphTypesInfo[a].display}.`;return}let{values:s,labels:c}=W(e,n,r),l=null,u=null;for(let e of s)(l===null||e>l)&&(l=e),(u===null||e<u)&&(u=e);(l??0)<0&&(l=0),(u??0)>0&&(u=0),i.innerHTML=`<table><tr><td><canvas id="myBarCanvas" width="500px" height="400px" style="border:1px solid black;"></canvas></td><td><span id="googleBarChart"></span></td></tr></table>`;let d=e.doc.getElementById(`myBarCanvas`);if(!d)return;let f=d.getContext(`2d`);if(!f)return;f.font=`10pt bold Arial`;let p=d.height-60,m=d.width;t.reset();let h=Math.floor(m/(s.length||1))-4||1,g=p*((l??0)/((l??0)-(u??0)||1))+30,_=p/((l??0)-(u??0)||1);f.lineWidth=5,f.moveTo(0,g),f.lineTo(d.width,g),f.stroke();for(let e=0;e<s.length;e++)f.fillStyle=`#`+t.getBarColor(),f.fillRect(e*h,g-_*s[e],h,_*s[e]),f.fillText(c[e]??``,e*h+4,g+16)}}function ut(e,t){return(n,r,i,a,o)=>{if(o||!r){i.innerHTML=`<input type="button" value="${e.SocialCalc.Constants.s_loc_hide_help??`Hide Help`}" onclick="DoGraph(false,false);"><br><br>Horizontal bar help.`;return}let{values:s,labels:c}=W(e,n,r);i.innerHTML=`<canvas id="myBarCanvas" width="500px" height="400px" style="border:1px solid black;"></canvas>`;let l=e.doc.getElementById(`myBarCanvas`);if(!l)return;let u=l.getContext(`2d`);if(!u)return;u.font=`10pt bold Arial`,t.reset();let d=Math.floor(l.height/(s.length||1))-4||1,f=0;for(let e of s)e>f&&(f=e);for(let e=0;e<s.length;e++)u.fillStyle=`#`+t.getBarColor(),u.fillRect(0,e*d,s[e]/(f||1)*(l.width-50),d),u.fillStyle=`#000`,u.fillText(c[e]??``,4,e*d+d/2)}}function dt(e,t){return(n,r,i)=>{if(!r)return;let{values:a,labels:o}=W(e,n,r),s=a.reduce((e,t)=>e+t,0);i.innerHTML=`<canvas id="myCanvas" width="500px" height="400px"></canvas>`;let c=e.doc.getElementById(`myCanvas`);if(!c)return;let l=c.getContext(`2d`);if(!l)return;l.font=`10pt Arial`;let u=c.width/2,d=c.height/2,f=d-50,p=0;for(let e=0;e<a.length;e++){if(!Number(a[e]))continue;l.beginPath(),l.moveTo(u,d),l.fillStyle=t.getDrawColor();let n=2*Math.PI*(a[e]/(s||1));l.arc(u,d,f,p,p+n,!1),l.closePath(),l.fill(),l.fillStyle=`#000`,l.fillText(o[e]??``,u+Math.cos(p+n/2)*f,d+Math.sin(p+n/2)*f),p+=n}}}function K(e,t){return(n,r,i)=>{if(!r)return;let{values:a}=W(e,n,r);i.innerHTML=`<canvas id="myLineCanvas" width="500px" height="400px"></canvas>`;let o=e.doc.getElementById(`myLineCanvas`);if(!o)return;let s=o.getContext(`2d`);if(!s)return;s.strokeStyle=t.getDrawColor(),s.beginPath();let c=(o.width-40)/(a.length||1);for(let e=0;e<a.length;e++)e===0?s.moveTo(20,o.height-a[e]-20):s.lineTo(20+e*c,o.height-a[e]-20);s.stroke()}}function ft(e,t){return(n,r,i)=>{if(!r)return;let{values:a}=W(e,n,r);i.innerHTML=`<canvas id="myScatterCanvas" width="500px" height="400px"></canvas>`;let o=e.doc.getElementById(`myScatterCanvas`);if(!o)return;let s=o.getContext(`2d`);if(!s)return;s.fillStyle=t.getDrawColor();let c=(o.width-40)/(a.length||1);for(let e=0;e<a.length;e++)s.beginPath(),s.arc(20+e*c,o.height-a[e]-20,5,0,2*Math.PI,!1),s.fill()}}var pt={ALLOWED_TAGS:`a.abbr.b.blockquote.br.caption.code.col.colgroup.div.em.font.h1.h2.h3.h4.h5.h6.hr.i.img.li.ol.p.pre.s.small.span.strike.strong.sub.sup.table.tbody.td.tfoot.th.thead.tr.u.ul`.split(`.`),ALLOWED_ATTR:[`href`,`src`,`alt`,`title`,`target`,`rel`,`style`,`class`,`colspan`,`rowspan`,`align`,`valign`,`width`,`height`,`color`,`face`,`size`],ALLOWED_URI_REGEXP:/^(?:(?:https?|mailto|tel|ftp):|[^a-z]|[a-z+.-]+(?:[^a-z+.:-]|$))/i,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1};function mt(e,t){let n=e.Callbacks??={};if(n.untrustedContent)return!1;let r=e=>t.sanitize(e,pt);return n.untrustedContent=!0,n.securityPolicy=n.securityPolicy??{},n.securityPolicy.sanitizeHtml=r,e.sanitizeHTML||=r,!0}var ht=`.te_download tr:nth-child(2) td:first-child`,gt=`td[id$="_logo"]`,_t=`https://github.com/audreyt/socialcalc/blob/main/LEGAL.txt`;function vt(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.closest!=`function`)return null;let n=t.closest(ht);return n&&typeof n==`object`?n:null}function q(e,t,n){let r=/\/.*\/(?:view|edit)$/.test(n.parentPathname)?`..`:`.`;if((e===`xlsx`||e===`ods`)&&n.isMultiple){let i=n.parentHref?/(^.*\/=[^?/]+)/.exec(n.parentHref):null;return i?`${i[1]}.${e}`:`${r}/=${t.replace(/\.[1-9]\d*$/,``)}.${e}`}return`${r}/${t}.${e}`}function J(e){let t=e.SocialCalc._room??``;if(!t)return;let n=e.vex??(typeof window<`u`?window.vex:void 0);if(!n?.dialog?.open)return;let r=(()=>{if(e.parent?.location)return e.parent.location;if(!(typeof window>`u`))try{return window.parent.location}catch{return}})()??{pathname:e.location.pathname},i=((e.__MULTI__?.rows??(typeof window<`u`?window.__MULTI__?.rows:void 0))?.length??0)>0||/\.[1-9]\d*$/.test(t),a=(e,t)=>{let n=t&&/filename\*?="?([^";]+)"?/i.exec(t);return n?.[1]?n[1]:e.split(`?`)[0]?.split(`/`).pop()??`export`},o=e.__exportOpen??(typeof document<`u`&&typeof fetch<`u`?e=>{(async()=>{let t=await fetch(e),n=await t.blob(),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=a(e,t.headers.get(`Content-Disposition`)),i.rel=`noopener`,document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>URL.revokeObjectURL(r),1e3)})()}:void 0);if(!o)return;e.SocialCalc.Keyboard??={},e.SocialCalc.Keyboard.passThru=!0,n.defaultOptions&&(n.defaultOptions.className=`vex-theme-flat-attack`);let s=e=>{o(q(e,t,{isMultiple:i,parentHref:r.href,parentPathname:r.pathname}))},c=n.dialog.buttons?.YES??{},l=n.dialog.buttons?.NO??{};n.dialog.open({message:(e.SocialCalc.Constants.s_loc_export_format??`Please choose an export format.`)+(i?`<br><small>(ODS and EXCEL support multiple sheets.)</small>`:``),callback:()=>{e.SocialCalc.Keyboard&&(e.SocialCalc.Keyboard.passThru=!1)},buttons:[{...c,text:`Excel`,click:()=>s(`xlsx`)},{...c,text:`CSV`,click:()=>s(`csv`)},{...c,text:`HTML`,click:()=>s(`html`)},{...c,text:`ODS`,click:()=>s(`ods`)},{...l,text:e.SocialCalc.Constants.s_loc_cancel??`Cancel`}]})}function yt(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.closest==`function`?t.closest(gt):null}function bt(e){if(e.__ETHERCALC_LOGO_BOUND__)return;let t=e.document??(typeof document<`u`?document:void 0);t&&(e.__ETHERCALC_LOGO_BOUND__=!0,t.addEventListener(`click`,t=>{yt(t.target)&&(e.__logoOpen??(typeof document<`u`?e=>{let t=document.createElement(`a`);t.href=e,t.target=`_blank`,t.rel=`noopener noreferrer`,document.body.appendChild(t),t.click(),document.body.removeChild(t)}:void 0))?.(_t)}))}function xt(e){if(e.__ETHERCALC_EXPORT_BOUND__)return;let t=e.document??(typeof document<`u`?document:void 0);t&&(e.__ETHERCALC_EXPORT_BOUND__=!0,t.addEventListener(`mouseover`,t=>{let n=vt(t.target);!n||typeof n.setAttribute!=`function`||n.setAttribute(`title`,e.SocialCalc.Constants.s_loc_export??`Export`)}),t.addEventListener(`click`,t=>{vt(t.target)&&J(e)}))}function St(e){let t=e,{SocialCalc:n}=e;t.doresize=()=>{t.spreadsheet?.DoOnResize?.()};let r=n.CurrentSpreadsheetControlObject??(n._view||n._app?n.SpreadsheetViewer?new n.SpreadsheetViewer:void 0