@mathzetta/qblur 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- /* qblur 0.2.0 — Copyright (c) 2025-2026 Robert Wilcox — MIT license — https://qblur.com — MathZetta inside: Copyright (c) 2025 Robert Wilcox, MIT license */
2
- function e(e){const n=new Map;for(const[t,o,s]of e)if(t&&""!==t.trim()&&(n.set(t,o),!s))for(const e of r(t))n.get(e)||n.set(e,o);const o=new Map;for(const e of n.keys()){let t=o;for(let r=0;r<e.length;r++)t.has(e[r])||t.set(e[r],new Map),t=t.get(e[r]);t.end=!0}return e=>{let r="",s=0;for(;s<e.length;){const a=t(o,e,s);a?(r+=n.get(e.slice(s,s+a)),s+=a):r+=e[s++]}return r}}function t(e,t,r){let n=e,o=0;for(let e=r;e<t.length&&(n=n.get(t[e]),n);e++)n.end&&(o=e-r+1);return o}function r(e){const t=new Set([e.toLowerCase(),e.toUpperCase(),n(e)]);return t.delete(e),t}function n(e){let t="",r=!1;for(const n of e){const e=n>="a"&&n<="z",o=n>="A"&&n<="Z";t+=!r&&e?n.toUpperCase():n,r=e||o}return t}const o=100,s="",a="",i={[s]:"dot",[a]:"cross"},l="",c={ln:o,log:o,loglog:o,logloglog:o,sqrt:o,sqrtpow:o,pow:o,expm1:o,der:o,lim:o,int:o,round:o,fixed:o,floor:o,ceil:o,abs:o,random:o,sum:o,prod:o,"\\sumidx":o,"\\prodidx":o,perm:o,comb:o,"\\perm":o,"\\comb":o,"\\binom":o,max:o,min:o,gcd:o,mean:o,pmatrix:o,bmatrix:o,vmatrix:o,det:o,sin:o,cos:o,tan:o,csc:o,sec:o,cot:o,sinh:o,cosh:o,tanh:o,evaluated:o,setbuilder:o,arcsin:o,arccos:o,arctan:o,arcsec:o,arccsc:o,arccot:o,arcsinh:o,arccosh:o,arctanh:o,atan2:o,_:o,"!":90,"\\not":85,"^":80,"*":70,"/":70,frac:70,[s]:70,[a]:70,mod:45,"+":50,"-":50,"±":50,"→":38,"<":34,">":34,"≤":34,"≥":34,"∈":32,"∉":32,"∪":33,"∩":33,"=":30,"==":30,"===":30,"≠":30,"≠=":30,"!==":30,"≈":30,"≡":30,pmod:2,"&":20,"\\xor":19,"|":18,"∨":18,"\\nor":17,"\\nand":17,"\\implies":15,"\\iff":14,"?:":10,"?":9,",":5},u=e=>Object.prototype.hasOwnProperty.call(c,e),p=new Set(["^","?:","?","log"]),h=["(","{","["],f=[")","}","]"];function m(e,t=!1){if(!e)return!1;for(let r=0;r<e.length;r++)if(!("0123456789.".includes(e[r])||t&&0===r&&"-"===e[r]&&e.length>1))return!1;return!0}for(const e of[c])Object.setPrototypeOf(e,null);const g=[["Math.atan2","atan2"],["Math.atan2(","atan2("],["atan2","atan2"],["\\atan2","atan2"],["Math.random()","random(1)"],["random.random()","random(1)"],["Math.log2(","log_{2}("],["Math.log10(","log_{10}("],["Math.log_{","log_{"],["Math.log","log_{e}"],["Math.ln","log_{e}"],["Math.abs(","abs("],["Math.fabs(","abs("],["Math.gcd(","gcd("],["Math.comb(","comb("],["Math.perm(","perm("],["Math.fmod(","mod("],["Math.exp(","(e)^("],["Math.exp2(","(2)^("],["Math.expm1(","expm1("],["Math.pow(","pow("],["**","^"],["Math.floor(","floor("],["Math.ceil(","ceil("],["Math.round(","round("],["Math.max(","max("],["Math.min(","min("],["Math.pi","π"],["Math.PI","π"],["math.Pi","π"],["Math.e","e"],["math.E","e"],["Math.sqrt2","sqrt(2)"],["Math.sqrt(","sqrt("],["Math.SQRT1_2","sqrt(1/2)"],["Math.SQRT1_{2}","sqrt(1/2)"],["Math.SQRT2","sqrt(2)"],["cbrt","sqrt[3]"],["Math.cbrt","sqrt[3]"],["Sqrt","sqrt"],["Root","sqrt"],["\\sqrt{","sqrt{"],["\\frac","frac"],["\\dfrac","frac"],["\\tfrac","frac"],["\\cfrac","frac"],["\\lim","lim"],["\\sum","\\sumidx"],["\\prod","\\prodidx"],["\\displaystyle",""],["\\textstyle",""],["\\,",""],["\\;",""],["\\!",""],["\\quad",""],["\\qquad",""],["\\lvert","|"],["\\rvert","|"],["\\vert","|"],["^\\prime","′"],["^{\\prime}","′"],["^{\\prime\\prime}","′′"],["\\prime","′"],["\\approx","≈"],["\\varepsilon","ε"],["\\vartheta","θ"],["\\varphi","φ"],["\\cup","∪"],["\\mathbb{R}","ℝ",!0],["\\mathbb{N}","ℕ",!0],["\\mathbb{Z}","ℤ",!0],["\\mathbb{Q}","ℚ",!0],["\\mathbb{C}","ℂ",!0],["\\cap","∩"],["\\%","%"],["\\barwedge","\\nand"],["∧","&"],["¬","!"],["↑","\\nand"],["↓","\\nor"],["∫","\\int"],["∑","\\sum"],["∏","\\prod"],["asin(","arcsin("],["acos(","arccos("],["atan(","arctan("],["asinh(","arcsinh("],["acosh(","arccosh("],["atanh(","arctanh("],["asec(","arcsec("],["acsc(","arccsc("],["acot(","arccot("],["\\sqrt*","sqrt"],["Log","log"],["Max","max"],["Min","min"],["Floor","floor"],["Ceil","ceil"],["Round","round"],["Abs","abs"],["Sum","sum"],["Prod","prod"],["Mean","mean"],["Avg","mean"],["Average","mean"],["Gcd","gcd"],["Math.LOG2e","log_{2}(e)"],["Math.LOG10e","log_{10}(e)"],["Math.LN2","log_{e}(2)"],["Math.LN10","log_{e}(10)"],["Math.tau","τ"],["infinity","∞"],["\\infty","∞"],["\\cdot",s],["\\times",a],["×",a],["·",s],["÷","/"],["->","→"],["\\to","→"],["\\max","max"],["\\min","min"],["\\det","det"],["^{\\top}","^{T}",!0],["^\\top","^T",!0],["^{\\intercal}","^{T}",!0],["^\\intercal","^T",!0],["^{\\mathsf{T}}","^{T}",!0],["^{\\mathrm{T}}","^{T}",!0],["product(","prod("],["log[","log_["],["\\log[","log_["],["\\log_","log_"],["\\log","log_{e}"],["\\ln","log_{e}"],["log(","log_{e}("],["ln(","log_{e}("],...["","\\"].flatMap(e=>["(","{"].flatMap(t=>[2,3,4,5,6,7,8,9,10].map(r=>[`${e}log${r}${t}`,`log_{${r}}${t}`]))),["\\log_10","log_{10}"],["log_10","log_{10}"],["\\log\\log","\\loglog"],["\\log\\log\\log","\\logloglog"],["\\loglog","\\loglog"],["\\logloglog","\\logloglog"],["loglog(","loglog("],["\\exp","e^"],["exp(","e^("],["\\div","/"],["\\int","\\int"],["\\in","∈"],["\\not\\in","∉"],["\\notin","∉"],["\\nor"," \\nor "],["\\xor"," \\xor "],["\\nand"," \\nand "],["\\Longrightarrow"," \\implies "],["\\Rightarrow"," \\implies "],["\\implies"," \\implies "],["⇒"," \\implies "],["⟹"," \\implies "],["\\Longleftrightarrow"," \\iff "],["\\Leftrightarrow"," \\iff "],["\\iff"," \\iff "],["⇔"," \\iff "],["⟺"," \\iff "],["\\uparrow"," \\nand "],["\\downarrow"," \\nor "],["\\oplus"," \\xor "],["\\lor","∨"],["\\land","&"],["Not"," \\not "],["&&","&"],["\\neg"," \\not "],["\\not"," \\not "],["\\rightarrow","→"],["\\limits_","_"],["\\pmod"," pmod "],["\\equiv","≡"],["\\mod"," mod "],["\\bmod"," mod "],["\\pm","±"],["\\plusmn","±"],["\\neq","≠"],["\\ne","≠"],["!==","≠="],["==","="],["=...=","==="],["!=","≠"],["\\gt",">"],["\\lt","<"],["\\ge","≥"],["\\geq","≥"],[">=","≥"],["\\le","≤"],["\\leq","≤"],["<=","≤"],["<>","≠"],["\\lparen","("],["\\rparen",")"],["\\left(","("],["\\right)",")"],["\\left[","["],["\\right]","]"],["\\left{","{"],["\\right}","}"],["\\left\\{","{"],["\\{","{"],["\\}","}"],["\\right\\}","}"],["\\left.",l],["\\left|","|"],["\\right|","|"],["\\lfloor","⌊"],["\\rfloor","⌋"],["\\lceil","⌈"],["\\rceil","⌉"],["ceiling(","ceil("],["√","sqrt"],["²","^2"],["³","^3"],["⁴","^4"],["⁵","^5"],["⁶","^6"],["⁷","^7"],["⁸","^8"],["⁹","^9"],["⁰","^0"],["¹","^1"],["ⁿ","^n"],["⁻¹","^{-1}"],["⁻²","^{-2}"],["⁻³","^{-3}"],["∛","sqrt[3]"],["∜","sqrt[4]"],["½","(1/2)"],["⅓","(1/3)"],["⅔","(2/3)"],["¼","(1/4)"],["¾","(3/4)"],["⅛","(1/8)"],["⅜","(3/8)"],["⅝","(5/8)"],["⅞","(7/8)"],["⅕","(1/5)"],["⅖","(2/5)"],["⅗","(3/5)"],["⅘","(4/5)"],["⅙","(1/6)"],["⅚","(5/6)"],["⅐","(1/7)"],["⅑","(1/9)"],["⅒","(1/10)"],["⊕"," \\xor "],["∞","∞"],["⋅",s],["−","-"],["\\wedge","&"],["∨","∨"],["\\vee","∨"],["\\Pi","Π",!0],["\\Alpha","Α",!0],["\\Beta","Β",!0],["\\Gamma","Γ",!0],["\\Delta","Δ",!0],["\\Delta ","Δ",!0],["\\Epsilon","Ε",!0],["\\Zeta","Ζ",!0],["\\Eta","Η",!0],["\\Theta","Θ",!0],["\\Iota","Ι",!0],["\\Kappa","Κ",!0],["\\Lambda","Λ",!0],["\\Mu","Μ",!0],["\\Nu","Ν",!0],["\\Xi","Ξ",!0],["\\Omicron","Ο",!0],["\\Rho","Ρ",!0],["\\Sigma","Σ",!0],["\\Tau","Τ",!0],["\\Upsilon","Υ",!0],["\\Phi","Φ",!0],["\\Chi","Χ",!0],["\\Psi","Ψ",!0],["\\Omega","Ω",!0],["\\pi","π",!0],["\\alpha","α",!0],["\\beta","β",!0],["\\gamma","γ",!0],["\\delta","δ",!0],["\\epsilon","ε",!0],["\\zeta","ζ",!0],["\\eta","η",!0],["\\theta","θ",!0],["\\iota","ι",!0],["\\kappa","κ",!0],["\\lambda","λ",!0],["\\mu","μ",!0],["\\nu","ν",!0],["\\xi","ξ",!0],["\\omicron","ο",!0],["\\rho","ρ",!0],["\\sigma","σ",!0],["\\tau","τ",!0],["\\upsilon","υ",!0],["\\phi","φ",!0],["\\chi","χ",!0],["\\psi","ψ",!0],["\\omega","ω",!0]];const d=e=>" "===e||"\t"===e||"\n"===e,$="({[",y=")}]";const b="ⅆ",w=new RegExp(String.raw`(\\(?:mathrm|operatorname|text)\{d\}\s*|d)([A-Za-zα-ω](?![A-Za-z0-9])|\\(?:${"alpha|beta|gamma|delta|epsilon|varepsilon|zeta|eta|theta|vartheta|iota|kappa|lambda|mu|nu|xi|rho|sigma|tau|upsilon|phi|varphi|chi|psi|omega"})(?![A-Za-z]))`,"g");function x(e){const t=[String.raw`\left\{`,String.raw`\left\lbrace`,String.raw`\{`,String.raw`\lbrace`,"{"],r=[String.raw`\right\}`,String.raw`\right\rbrace`,String.raw`\}`,String.raw`\rbrace`,"}"],n=/\\[A-Za-z{]/.test(e);for(let o=0,s=0;o<50;o++){let o=-1,a="";for(let r=s;r<e.length&&o<0;r++){const s=t.find(t=>e.startsWith(t,r));s&&("{"===s&&(n||/[\\^_A-Za-z]$/.test(e.slice(0,r)))||("{"!==s||"{"!==e[r+1]?(o=r,a=s):r++))}if(o<0)return e;let i=0,l=null,c=null,u=-1,p=0;for(let t=o+a.length;t<e.length;t++){const o=r.find(r=>e.startsWith(r,t));if(0===i&&o&&("{"===a?"}"===o:"}"!==o)){u=t,a+="|"+o;break}if(!"([{".includes(e[t])||"{"===e[t]&&"\\"===e[t-1]?")]}".includes(e[t])&&"\\"!==e[t-1]&&i--:i++,0===i&&"?"===e[t]&&p++,0===i&&!l){const r=/^(?:\\middle\s*\||\\mid(?![A-Za-z])|:(?!=)|\|)/.exec(e.slice(t));r&&":"===r[0]&&p?p--:r&&"|"!==r[0]?l={at:t,length:r[0].length}:r&&n&&!c&&!/\\left\s*$|\\right\s*$|\\middle\s*$/.test(e.slice(0,t))&&(c={at:t,length:1})}}if(l??=c,u<0||!l){s=o+1;continue}const h=e.slice(o+a.split("|")[0].length,l.at).trim(),f=e.slice(l.at+l.length,u).trim();if(!h||!f){s=o+1;continue}const m=a.split("|")[1];e=`${e.slice(0,o)}setbuilder((${h}),(${f}))${e.slice(u+m.length)}`,s=o}return e}const v=String.raw`\\(?:[Bb]igg?|right)[lrm]?`,_=new RegExp(`(?:${v}\\s*([\\]|])|(\\]))\\s*(?=[_^])`,"g");function E(e,t){let r=t;for(;" "===e[r];)r++;if("{"===e[r]){let t=0;for(let n=r;n<e.length;n++)if("{"===e[n])t++;else if("}"===e[n]&&0===--t)return{value:e.slice(r+1,n).trim(),end:n+1};return null}const n=/^\\[A-Za-z]+/.exec(e.slice(r));return n?{value:n[0],end:r+n[0].length}:"-"===e[r]&&/\d/.test(e[r+1]??"")?{value:e.slice(r,r+2),end:r+2}:e[r]?{value:e[r],end:r+1}:null}function A(e,t){let r=t;for(;" "===e[r];)r++;const n=e[r];if("_"!==n&&"^"!==n)return null;const o=E(e,r+1);if(!o)return null;let s=o.end;for(;" "===e[s];)s++;const a="_"===n?"^":"_";if(e[s]!==a)return null;const i=E(e,s+1);return i?"_"===n?{lo:o.value,hi:i.value,end:i.end}:{lo:i.value,hi:o.value,end:i.end}:null}function z(e,t,r){let n=0;for(let o=t-1;o>=0;o--){if(r){if("]"===e[o])n++;else if("["===e[o]){if(0===n)return{start:o,end:o+1};n--}continue}const s=e.slice(0,o+1),a=/\\right\s*[\]|)}.]$|\\[Bb]igg?r?\s*[\]|]$/.exec(s),i=/\\left\s*(?:[[(.]|\\\{)$|\\[Bb]igg?l?\s*\[$/.exec(s);if(a&&o+1<t)n++,o-=a[0].length-1;else if(i){if(0===n)return{start:o+1-i[0].length,end:o+1};n--,o-=i[0].length-1}}return null}function M(e,t){let r=0;for(let n=t-1;n>=0;n--){const t=e[n];if(")]}".includes(t))r++;else if("([{".includes(t)){if(0===r)return n+1;r--}else{if(0===r&&/[=<>&,]/.test(t))return n+1;if(0===r&&/\\(?:approx|leq?|geq?|neq?|to|quad|qquad)$/.test(e.slice(0,n+1)))return n+1}}return 0}function k(e){for(let t=0;t<50;t++){_.lastIndex=0;let t=null;for(let r=_.exec(e);r;r=_.exec(e)){const n=A(e,r.index+r[0].length);if(!n)continue;const o=Boolean(r[2]),s="|"===(r[1]??r[2]),a=z(e,r.index,o);if((a||s&&!/^\\right/.test(r[0]))&&(!a||!/\\left\s*\|$/.test(e.slice(a.start,a.end)))){t={m:r,limits:n,opener:a};break}}if(!t)return e;const{m:r,limits:n,opener:o}=t,s=o?o.start:M(e,r.index),a=e.slice(o?o.end:s,r.index).trim(),i=/^\s*([A-Za-zα-ωΑ-Ω]|\\[A-Za-z]+)\s*=\s*([\s\S]+)$/.exec(n.lo),l=n.hi.replace(/^\s*(?:[A-Za-zα-ωΑ-Ω]|\\[A-Za-z]+)\s*=\s*/,""),c=i?`evaluated((${a}),${i[1]},${i[2]},${l})`:`evaluated((${a}),${n.lo},${l})`;e=`${e.slice(0,s)}${s>0&&/[^\s(=]/.test(e[s-1])?" ":""}${c}${e.slice(n.end)}`}return e}const O={__proto__:null,sine:"sin",cosine:"cos",tangent:"tan",secant:"sec",cosecant:"csc",cotangent:"cot"};const j={__proto__:null},S={__proto__:null};[..."⁰¹²³⁴⁵⁶⁷⁸⁹"].forEach((e,t)=>{j[e]=String(t)}),[..."₀₁₂₃₄₅₆₇₈₉"].forEach((e,t)=>{S[e]=String(t)}),Object.assign(j,{"⁺":"+","⁻":"-","⁼":"=","⁽":"(","⁾":")","ᵃ":"a","ᵇ":"b","ᶜ":"c","ᵈ":"d","ᵉ":"e","ᶠ":"f","ᵍ":"g","ʰ":"h","ⁱ":"i","ʲ":"j","ᵏ":"k","ˡ":"l","ᵐ":"m","ⁿ":"n","ᵒ":"o","ᵖ":"p","ʳ":"r","ˢ":"s","ᵗ":"t","ᵘ":"u","ᵛ":"v","ʷ":"w","ˣ":"x","ʸ":"y","ᶻ":"z"}),Object.assign(S,{"₊":"+","₋":"-","₌":"=","₍":"(","₎":")","ₐ":"a","ₑ":"e","ₕ":"h","ᵢ":"i","ⱼ":"j","ₖ":"k","ₗ":"l","ₘ":"m","ₙ":"n","ₒ":"o","ₚ":"p","ᵣ":"r","ₛ":"s","ₜ":"t","ᵤ":"u","ᵥ":"v","ₓ":"x"});const N=new RegExp(`[${Object.keys(j).join("")}]+|[${Object.keys(S).join("")}]+`,"g");const I={__proto__:null,"½":"1/2","⅓":"1/3","⅔":"2/3","¼":"1/4","¾":"3/4","⅕":"1/5","⅖":"2/5","⅗":"3/5","⅘":"4/5","⅙":"1/6","⅚":"5/6","⅐":"1/7","⅛":"1/8","⅜":"3/8","⅝":"5/8","⅞":"7/8","⅑":"1/9","⅒":"1/10"},T=new RegExp(`(?<![\\w.,^_])(\\d+)[ \\t]?([${Object.keys(I).join("")}])`,"g"),R=/(?<![\w.,^_/])(\d+)[ \t]+([1-9]\d*)\/(\d+)(?![\d./^!])/g,C=/(?<![\w.,^_])(\d+)\s*\\[dtc]?frac\s*(?:\{\s*(\d+)\s*\}\s*\{\s*(\d+)\s*\}|(\d)(\d)(?!\d))/g;function F(e){const t=e.replace(/^\s*(?:\\(?:text|textrm|mathrm)\s*\{\s*(?:if|for|when|where)\s*\}|\b(?:if|for|when|where)\b)\s*,?/,"").replace(/[\s,.;]+$/,"").trim();return/^(?:\\(?:text|textrm|mathrm)\s*\{\s*)?(?:otherwise|else)\s*\}?$/.test(t)?"":t}function q(e,t){const r=[];let n=0,o=0;for(let s=0;s<e.length;s++)$.includes(e[s])?n++:y.includes(e[s])?n--:0===n&&e.startsWith(t,s)&&(r.push(e.slice(o,s)),s+=t.length-1,o=s+1);return r.push(e.slice(o)),r}function P(e,t,r){let n=0;const o=new RegExp(`\\b${r}\\b`,"iy");for(let r=t;r<e.length;r++)if($.includes(e[r]))n++;else if(y.includes(e[r])){if(--n<0)return-1}else if(0===n&&(o.lastIndex=r,o.test(e)))return r;return-1}function U(e,t){let r=0;for(let n=t;n<e.length;n++)if($.includes(e[n]))r++;else if(y.includes(e[n])&&--r<0)return n;return e.length}function L(e,t){let r=1;for(let n=t+1;n<e.length;n++)if("?"===e[n])r++;else if(":"===e[n]&&0===--r)return e.slice(0,t+1)+"("+e.slice(t+1,n)+")?:"+e.slice(n+1);return e}function D(e){for(let t=2;t<e.length;t++)if("g"===e[t]&&"log"===e.slice(t-2,t+1))if("_"===e[t+1]){if($.includes(e[t+2]))continue;const r=/^(?:\d+(?:\.\d+)?|[A-Za-z\u0370-\u03FF])/.exec(e.slice(t+2))?.[0];if(!r)continue;const n=t+2+r.length;e=e.slice(0,t+2)+"{"+r+"}"+e.slice(n)}else if("("===e[t+1]){let r=1,n=0,o="",s="",a=0;for(let i=t+2;i<e.length;i++){if(")]".includes(e[i])?r--:"([".includes(e[i])&&r++,0===r){a=i;break}1===r&&","===e[i]?n++:0===n?o+=e[i]:s+=e[i]}1===n&&a>0&&(e=e.slice(0,t+1)+"_{"+s+"}("+o+")"+e.slice(a+1))}return e}function B(e){const t="⌈"===e[0]?"ceil":"floor";let r=1;for(let n=1;n<e.length;n++)if("⌊"===e[n]||"⌈"===e[n]?r++:"⌋"!==e[n]&&"⌉"!==e[n]||r--,0===r)return t+"("+e.slice(1,n)+")"+e.slice(n+1);return e}function Z(e){let t=1;for(let r=0;r<e.length;r++){if(")]".includes(e[r])?t--:"([".includes(e[r])&&t++,0!==t)continue;const n=e.slice(0,r),o=e[r+1];if("{"===o||"("===o)return o+n+","+e.slice(r+2);const s=/^[A-Za-z0-9.\u0370-\u03FF]+/.exec(e.slice(r+1))?.[0]??"";return"{"+n+","+s+"}"+e.slice(r+1+s.length)}return e}const G=new Set(["pmatrix","bmatrix","vmatrix"]);function W(e){const t=e.indexOf("}"),r=e.indexOf("{");if(t<0||r>=0&&r<t)return!1;const n=e.slice(0,t);if(!n.includes("matrix"))return!1;const o=e.indexOf("\\end{"+n+"}"),s=e.indexOf("\\begin{"+n+"}",t+1);if(o<0||-1!==s&&s<o)return!1;const a=e.slice(t+1,o).trim().split("\\\\").map(e=>e.trim()).filter(e=>e.length).map(e=>"["+e.replace(/&/g,", ")+"]"),i=e.slice(o+6+n.length);return G.has(n)?n+"("+a.join(", ")+")"+i:"["+a.join(", ")+"]"+i}function H(e,t){if("{"!==e[t+1])return[e[t+1],t+2];let r=1,n="";for(let o=t+2;o<e.length;o++){if("{"===e[o])r++;else if("}"===e[o]&&0===--r)return[n,o+1];n+=e[o]}return[n,e.length]}function X(e){const{lower:t,upper:r,next:n}=function(e){let t="",r="",n=0;return"_"===e[0]&&([t,n]=H(e,0),"^"===e[n]&&([r,n]=H(e,n))),{lower:t,upper:r,next:n}}(e),o=e.slice(n),s=e=>e.replace(/\\,/g,"").replace(/\\!/g,"");let a,i="",l="",c=o.indexOf("\\mathrm{d}");if(c>=0){a=o.slice(0,c);const e=/^\{([^{}]*)\}/.exec(o.slice(c+10));i=e?e[1]:o[c+10],l=o.slice(c+10+(e?e[0].length:1))}else(c=function(e){let t=0;for(let r=0;r<e.length;r++)if($.includes(e[r]))t++;else if(y.includes(e[r]))t--;else if(0===t&&"d"===e[r]&&/[A-Za-z\u0370-\u03FF]/.test(e[r+1]??"")&&!/[A-Za-z]/.test(e[r+2]??""))return r;return-1}(o))>=0?(a=o.slice(0,c),i=o[c+1],l=o.slice(c+2)):a=o;if(!i){const e=/frac\{d([A-Za-z])\}/.exec(a);e&&(i=e[1],a=a.replace(e[0],"frac{1}"))}if(!i&&/^[A-Za-z]$/.test(t)){i=[...s(a).matchAll(/(?<![A-Za-z\\])([A-Za-z])(?![A-Za-z(])/g)].map(e=>e[1]).find(e=>e!==t&&e!==r)??"x"}let u="int("+(s(a).trim()?s(a):"1");return i&&(u+=","+i),(t||r)&&(u+=","+t+","+r),u+")"+l}function V(e){const t=e[0];if(!(t>="A"&&t<="Z"||t>="a"&&t<="z"||t>="α"&&t<="ω"))return!1;const r=e.slice(2);let n=1;for(let e=0;e<r.length;e++)if(y.includes(r[e])?n--:$.includes(r[e])&&n++,0===n)return"("+r.slice(0,e)+","+t+")"+r.slice(e+1);return!1}function Y(e){return"{"===e[0]||e.length<2?e:"{"+e[0]+"}{"+e[1]+"}"+e.slice(2)}const J=/[A-Za-z\u0370-\u03FF]/;function K(e,t){if("{"!==e[t])return null;let r=0;for(let n=t;n<e.length;n++)if("{"===e[n])r++;else if("}"===e[n]&&0===--r)return[e.slice(t+1,n),n+1];return null}function Q(e,t){const r=/^\^(?:\{(\d+)\}|(\d))/.exec(e.slice(t));return r?[Number(r[1]??r[2]),t+r[0].length]:[1,t]}function ee(e,t){const r=e.replace(/\\mathrm\{d\}/g,"d"),n=t.replace(/\\mathrm\{d\}/g,"d"),o=/^d(?:\^\{?(\d+)\}?)?([A-Za-z\u0370-\u03FF]?)$/.exec(r),s=/^d([A-Za-z\u0370-\u03FF])(?:\^\{?(\d+)\}?)?$/.exec(n);return o&&s?{n:Number(o[1]??1),of:o[2],by:s[1]}:null}function te(e,t){if($.includes(e[t])){let r=0;for(let n=t;n<e.length;n++)if($.includes(e[n]))r++;else if(y.includes(e[n])&&0===--r)return[e.slice(t,n+1),n+1];return[e.slice(t),e.length]}let r=0;for(let n=t;n<e.length;n++)if($.includes(e[n]))r++;else{if(y.includes(e[n])&&--r<0)return[e.slice(t,n),n];if(0===r&&("="===e[n]||","===e[n]))return[e.slice(t,n),n]}return[e.slice(t),e.length]}const re=(e,t,r)=>`der(${e},${t}${r>1?","+r:""})`;const ne="strtktk",oe="ABCDEFGHIJ",se=e=>ne+[...String(e)].map(e=>oe[e]).join(""),ae=new RegExp(`^${ne}[${oe}]+$`);function ie(e){let t="";for(let r=0;r<e.length;r++){const n=e[r];if('"'===n||"`"===n){const n=le(e,r);t+=e.slice(r,n+1),r=n}else if("'"===n)if(/[A-Za-z0-9)\]′\u0370-\u03FF]/.test(t[t.length-1]??""))t+="′";else{const n=le(e,r);t+=e.slice(r,n+1),r=n}else t+=n}return t}function le(e,t){let r=!1;for(let n=t+1;n<e.length;n++)if(r)r=!1;else if("\\"===e[n])r=!0;else if(e[n]===e[t])return n;return e.length-1}const ce=new RegExp(`${ne}[${oe}]+|§\\d+§`,"g");function ue(e,t){return t&&0!==t.size?e.map(e=>"string"!=typeof e?e:e.replace(ce,e=>{const r=t.get(e);if(void 0!==r)return r;for(let r=e.length-1;r>7;r--){const n=t.get(e.slice(0,r));if(void 0!==n)return n+e.slice(r)}return e})):e}const pe={factorial:"((n) => { if (!Number.isInteger(n) || n < 0) return NaN; if (n > 170) return Infinity; let r = 1; for (let i = 2; i <= n; i++) r *= i; return r; })",perm:"((n, k) => { if (!Number.isInteger(n) || !Number.isInteger(k) || k < 0 || k > n) return NaN; let r = 1; for (let i = n - k + 1; i <= n && r !== Infinity; i++) r *= i; return r; })",comb:"((n, k) => { if (!Number.isInteger(n) || !Number.isInteger(k) || k < 0 || k > n) return NaN; k = Math.min(k, n - k); let r = 1; for (let i = 1; i <= k && r !== Infinity; i++) r = r * (n - k + i) / i; return Math.round(r); })",gcd:"((args)=>{let gcd = function(a,b) { return (!b)?a:gcd(b,a%b); }; return Math.abs(args.reduce(gcd));})",det:"((m) => { const a = m.map((r) => r.slice()); const n = a.length; let d = 1; for (let i = 0; i < n; i++) { let p = i; for (let r = i + 1; r < n; r++) if (Math.abs(a[r][i]) > Math.abs(a[p][i])) p = r; if (a[p][i] === 0) return 0; if (p !== i) { const t = a[p]; a[p] = a[i]; a[i] = t; d = -d; } d *= a[i][i]; for (let r = i + 1; r < n; r++) { const f = a[r][i] / a[i][i]; for (let c = i; c < n; c++) a[r][c] -= f * a[i][c]; } } return d; })",union:"((a, b) => [...new Set([].concat(a, b))])",intersection:"((a, b) => [].concat(a).filter((x) => [].concat(b).includes(x)))",round:"((x, d) => { const p = Math.pow(10, d); return (x < 0 ? -Math.round(-x * p) : Math.round(x * p)) / p; })",mod:"((a, n) => ((a % n) + n) % n)",root:"((n, x) => (x < 0 && Math.abs(n % 2) === 1 ? -Math.pow(-x, 1 / n) : Math.pow(x, 1 / n)))",contains:"((s, t) => { const f = (x) => (x == null ? String() : String(x)).replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32)); return f(s).includes(f(t)); })",startswith:"((s, t) => { const f = (x) => (x == null ? String() : String(x)).replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32)); return f(s).startsWith(f(t)); })"},he="lambda x: str().join(chr(ord(c) + 32) if 65 <= ord(c) <= 90 else c for c in (str() if x is None or x != x else str(int(x)) if isinstance(x, float) and x.is_integer() else str(x)))",fe=`lambda s, t, f=${he}: f(t) in f(s)`,me=`lambda s, t, f=${he}: f(s).startswith(f(t))`,ge={contains:`(${fe})`,startswith:`(${me})`},de={contains:`np.vectorize(${fe}, otypes=[bool])`,startswith:`np.vectorize(${me}, otypes=[bool])`};for(const e of[pe,ge,de])Object.setPrototypeOf(e,null);const $e="([{",ye=")]}";function be(e,t){let r=0;for(let n=t;n<e.length;n++)if($e.includes(e[n]))r++;else if(ye.includes(e[n])&&0===--r)return n;return-1}function we(e){if(!e.trim())return[];const t=[];let r=0,n=0;for(let o=0;o<e.length;o++)$e.includes(e[o])?r++:ye.includes(e[o])?r--:","===e[o]&&0===r&&(t.push(e.slice(n,o).trim()),n=o+1);return t.push(e.slice(n).trim()),t}function xe(e,t,r){const n=[...e.matchAll(t)];for(let t=n.length-1;t>=0;t--){const o=n[t],s=o.index+o[0].length-1,a=be(e,s);if(a<0)continue;const i=r(we(e.slice(s+1,a)),o,e.slice(a+1));if(null==i)continue;const[l,c=0]=Array.isArray(i)?i:[i];if((e=e.slice(0,o.index)+l+e.slice(a+1+c)).length>1e5)throw new Error("The expression expands too much when read")}return e}const ve=e=>new RegExp(`(?<![\\w.])(${e})\\s*\\(`,"g"),_e=e=>`(${e})`,Ee=e=>/^\[.*\]$/s.test(e.trim())?`{${e.trim().slice(1,-1)}}`:e,Ae=[...Object.entries(pe),...Object.entries(de),...Object.entries(ge)];const ze={IF:e=>e.length>=2&&`((${e[0]}) ? (${e[1]}) : (${e[2]??"false"}))`,AND:e=>e.length&&`(${e.map(_e).join(" & ")})`,OR:e=>e.length&&`(${e.map(_e).join(" ∨ ")})`,NOT:e=>1===e.length&&`(!(${e[0]}))`,XOR:e=>2===e.length&&`((${e[0]}) \\xor (${e[1]}))`,LOG:e=>2===e.length?`log_{${e[1]}}(${e[0]})`:1===e.length&&`log_{10}(${e[0]})`,ATAN2:e=>2===e.length&&`atan2(${e[1]}, ${e[0]})`,INT:e=>1===e.length&&`floor(${e[0]})`,FIXED:e=>(1===e.length||2===e.length)&&`fixed(${e[0]}, ${e[1]??2})`,"FLOOR.MATH":e=>1===e.length&&`floor(${e[0]})`,"CEILING.MATH":e=>1===e.length&&`ceil(${e[0]})`,FACT:e=>1===e.length&&`((${e[0]})!)`,COMBIN:e=>2===e.length&&`comb(${e.join(", ")})`,PERMUT:e=>2===e.length&&`perm(${e.join(", ")})`,AVERAGE:e=>`mean(${e.join(", ")})`,SUM:e=>`sum(${e.join(", ")})`,PRODUCT:e=>`prod(${e.join(", ")})`,MAX:e=>`max(${e.join(", ")})`,MIN:e=>`min(${e.join(", ")})`,MEDIAN:e=>`median(${e.join(", ")})`,"STDEV.P":e=>`stdev(${e.join(", ")})`,STDEVP:e=>`stdev(${e.join(", ")})`,CEILING:e=>(1===e.length||2===e.length&&"1"===e[1].trim())&&`ceil(${e[0]})`,RAND:e=>!e.length&&"random()",ISNUMBER:e=>1===e.length&&`((${e[0]}) ∈ ℝ)`,LOG10:e=>1===e.length&&`log_{10}(${e[0]})`};function Me(e,t){for(let r=t,n=0;r>=0;r--)if(")"===e[r])n++;else if("("===e[r]&&0===--n)return r;return-1}function ke(e){const t="(?:[\\p{L}_][\\p{L}\\p{N}_.]*|\\d+(?:\\.\\d+)?|§\\d+§)";return e=function(e,t){const r=new RegExp(`^(?:${t})`,"u"),n=new RegExp(`(?:${t})$`,"u"),o=/[\p{L}_][\p{L}\p{N}_.]*$/u;for(let t=e.indexOf("^");t>=0;t=e.indexOf("^",t+1)){let s,a=t+1;for(;/\s/.test(e[a]??"");)a++;if("("===e[a])s=be(e,a)+1;else{const t=r.exec(e.slice(a));s=t?a+t[0].length:0,t&&"("===e[s]&&(s=be(e,s)+1)}if(s<=a||!/^\s*\^/.test(e.slice(s)))continue;let i,l=t;for(;l>0&&/\s/.test(e[l-1]);)l--;if(")"===e[l-1]){i=Me(e,l-1);const t=i>0&&o.exec(e.slice(Math.max(0,i-64),i));t&&(i-=t[0].length)}else{const t=n.exec(e.slice(Math.max(0,l-64),l));i=t?l-t[0].length:-1}i<0||(e=`${e.slice(0,i)}(${e.slice(i,s)})${e.slice(s)}`,t=s+1)}return e}(e=(e=(e=e.replace(/^\s*=/,"").replace(/(?<![\w.])_xlfn\./g,"")).replace(/&/g,"+")).replace(new RegExp(`(^|[(,=<>*/+^-]\\s*)-\\s*(${t})(?=\\s*\\^)`,"gu"),"$1(-$2)"),t),xe(e,/(?<![\w.])([A-Z][A-Z0-9]*(?:\.[A-Z]+)?)\s*\(/g,(e,t)=>ze[t[1]]?.(e)||null)}const Oe={POWER:"pow",SQRT:"sqrt",ABS:"abs",LN:"ln",EXP:"exp",FLOOR:"floor",CEIL:"ceil",CEILING:"ceil",ROUND:"round",GREATEST:"max",LEAST:"min",MOD:"mod",ATAN2:"atan2",FACTORIAL:"factorial",SIN:"sin",COS:"cos",TAN:"tan",SEC:"sec",CSC:"csc",COT:"cot",ASIN:"asin",ACOS:"acos",ATAN:"atan",SINH:"sinh",COSH:"cosh",TANH:"tanh",ASINH:"asinh",ACOSH:"acosh",ATANH:"atanh",COMB:"comb",PERM:"perm",GCD:"gcd",DERIVATIVE:"derivative",LIMIT:"limit",UNION:"union",EXPM1:"expm1",TRUNC:"trunc",SUMMATION:"sum"},je="strtktk[A-J]+";function Se(e){for(let t=!0;t;){const r=e;t=(e=e.replace(new RegExp(`(${je})\\s*\\|\\|\\s*(${je})`,"g"),"$1 + $2"))!==r}const t=new RegExp(`^\\(typeof\\(([^()]*)\\)\\s+IN\\s+\\(${je},\\s*${je}\\)\\s+AND\\s+(.*)\\)$`,"s");for(let r=e.lastIndexOf("(typeof(");r>=0;r=r>0?e.lastIndexOf("(typeof(",r-1):-1){const n=be(e,r),o=n>0&&t.exec(e.slice(r,n+1));if(!o)continue;const[,s,a]=o,i=new Map([[`${s} = TRUNC(${s})`,"ℤ"],[`${s} = TRUNC(${s}) AND ${s} > 0`,"ℕ"],[`ABS(${s}) < ∞`,"ℝ"]]).get(a.trim());i&&(e=`${e.slice(0,r)}((${s}) ∈ ${i})${e.slice(n+1)}`)}e=xe(e,/(?<![\w.])CAST\s*\(/gi,e=>{const t=1===e.length&&/^(.*)\s+AS\s+(?:REAL|FLOAT|DOUBLE(?:\s+PRECISION)?|NUMERIC|DECIMAL|INTEGER|INT)\s*$/is.exec(e[0]);return t?`(${t[1]})`:null}),e=(e=(e=xe(e=function(e){for(let t=0;t<50;t++){const t=[...e.matchAll(/\bCASE\s+WHEN\b/gi)];if(!t.length)return e;const r=t[t.length-1].index,n=/\bEND\b/i.exec(e.slice(r));if(!n)return e;const o=e.slice(r+4,r+n.index).split(/\b(WHEN|THEN|ELSE)\b/i).map(e=>e.trim()),s=[];let a="null";for(let e=1;e<o.length;e+=2){const t=o[e].toUpperCase();"WHEN"===t?s.push([o[e+1],o[e+3]]):"ELSE"===t&&(a=o[e+1])}const i=s.reduceRight((e,[t,r])=>`((${t}) ? (${r}) : ${e})`,_e(a));e=e.slice(0,r)+i+e.slice(r+n.index+3)}return e}(e=e.replace(/(?<![\w.])ARRAY\s*\[/g,"[")),/(?<![\w.])LOG\s*\(/g,e=>2===e.length?`log_{${e[0]}}(${e[1]})`:`log_{10}(${e[0]})`)).replace(/(?<![\w.])PI\s*\(\s*\)/g,"π")).replace(/(?<![\w.])([A-Z][A-Z0-9]*)(?=\s*\()/g,e=>Oe[e]??e);for(const[t,r]of[[/\bNOT\s+IN\s*\(/g,"∉"],[/\bIN\s*\(/g,"∈"]])for(let n=t.exec(e);n;n=t.exec(e)){const o=n.index+n[0].length-1,s=be(e,o);if(s<0)break;e=`${e.slice(0,n.index)}${r} {${e.slice(o+1,s)}}${e.slice(s+1)}`,t.lastIndex=0}return e.replace(/<>/g," ≠ ")}const Ne={sin:"sin",cos:"cos",tan:"tan",sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsin:"asin",arccos:"acos",arctan:"atan",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",arctan2:"atan2",sqrt:"sqrt",cbrt:"cbrt",exp:"exp",expm1:"expm1",log:"log",log2:"log2",log10:"log10",floor:"floor",ceil:"ceil",round:"round",power:"pow",abs:"abs",absolute:"abs",fabs:"abs",pi:"PI",e:"E",gcd:"gcd"},Ie={maximum:"max",minimum:"min",nanmax:"max",nanmin:"min",nansum:"sum",nanprod:"prod",nanmean:"mean",nanmedian:"median",nanstd:"stdev",mod:"mod",fmod:"mod",where:"where",isin:"isin",isclose:"isclose",isfinite:"isfinite",logical_and:"logical_and",logical_or:"logical_or",logical_not:"logical_not",logical_xor:"logical_xor",prod:"prod",sum:"sum",trunc:"trunc",union1d:"union",intersect1d:"intersection"};const Te=e=>e.replace(/(?<![\w.])set\s*\(\s*\)/g,"∅"),Re={inf:"∞",nan:"NaN"};function Ce(e){return(e=(e=function(e){return e=e.replace(/(?<![\w.])sympy\.Interval\.(open|Lopen|Ropen)\s*\(/g,(e,t)=>`sympy_interval_${t}(`),e=e.replace(/(?<![\w.])sympy\.S\.(\w+)/g,(e,t)=>qe[t]??e),e=e.replace(/(?<![\w.])sympy\.(Reals|Integers|Naturals0?|Rationals|Complexes)\b/g,(e,t)=>qe[t]),e.replace(/(?<![\w.])sympy\.(\w+)/g,(e,t)=>Pe[t]??Fe[t]??e)}(e=(e=(e=(e=(e=(e=(e=e.replace(/(?<![\w.])(?:np|numpy)\.random\.random\(\s*\)|(?<![\w.])random\.random\(\s*\)/g,"Math.random()")).replace(/(?<![\w.])(?:np|numpy)\.linalg\.(det|inv)\b/g,"$1")).replace(/(?<![\w.])(?:np|numpy)\.array\s*\(/g,"(")).replace(/(?<![\w.])(?:np|numpy)\.(\w+)/g,(e,t)=>Ne[t]?`Math.${Ne[t]}`:Ie[t]?Ie[t]:Re[t]??e)).replace(/(?<![\w.])(?:math|Math)\.(factorial|isfinite|isclose|prod|inf|nan|abs|trunc)\b/g,(e,t)=>Re[t]??t)).replace(/(?<![\w.])Number\.(isInteger|isFinite)\b/g,(e,t)=>t.toLowerCase())).replace(/(?<![\w.])scipy\.(?:special|integrate)\.(\w+)/g,"$1"))).replace(/\bMZ_INFINITY\b/g,"∞")).replace(/(?<![\w.])mz_(?=\w+\s*\()/g,"")}const Fe={pi:"π",E:"e",oo:"∞",true:"true",false:"false",nan:"NaN",I:"i"},qe={Reals:"ℝ",Integers:"ℤ",Naturals:"ℕ",Naturals0:"ℕ",Rationals:"ℚ",Complexes:"ℂ"},Pe={sqrt:"Math.sqrt",exp:"Math.exp",sin:"Math.sin",cos:"Math.cos",tan:"Math.tan",sinh:"Math.sinh",cosh:"Math.cosh",tanh:"Math.tanh",asin:"Math.asin",acos:"Math.acos",atan:"Math.atan",asinh:"Math.asinh",acosh:"Math.acosh",atanh:"Math.atanh",atan2:"atan2",csc:"csc",sec:"sec",cot:"cot",log:"log",Abs:"abs",floor:"floor",ceiling:"ceil",Max:"max",Min:"min",factorial:"factorial",binomial:"comb",ff:"perm",gcd:"gcd",gcd_list:"sympy_list_gcd",Mod:"mod",root:"sympy_root",real_root:"sympy_root",det:"det",Rational:"sympy_rational",Integer:"sympy_value",Float:"sympy_value",Eq:"sympy_eq",Ne:"sympy_ne",And:"sympy_and",Or:"sympy_or",Not:"sympy_not",Xor:"sympy_xor",Nand:"sympy_nand",Nor:"sympy_nor",Implies:"sympy_implies",Equivalent:"sympy_iff",Piecewise:"sympy_piecewise",FiniteSet:"sympy_set",Interval:"sympy_interval",Contains:"sympy_contains",Union:"union",Intersection:"intersection",diff:"derivative",integrate:"sympy_integrate",limit:"sympy_limit",summation:"sympy_summation",product:"sympy_product",expm1:"expm1",Matrix:""},Ue={open:"()",Lopen:"(]",Ropen:"[)"};const Le=e=>{const t=/^\((.*)\)$/s.exec(e.trim());return t?we(t[1]):null},De=e=>t=>2===t.length&&`${e[0]}${t[0]}, ${t[1]}${e[1]}`,Be=e=>Le(e)??[e],Ze={where:e=>3===e.length&&`((${e[0]}) ? (${e[1]}) : (${e[2]}))`,logical_and:e=>2===e.length&&`((${e[0]}) & (${e[1]}))`,logical_or:e=>2===e.length&&`((${e[0]}) ∨ (${e[1]}))`,logical_xor:e=>2===e.length&&`((${e[0]}) \\xor (${e[1]}))`,logical_not:e=>1===e.length&&`(!(${e[0]}))`,isin:e=>2===e.length&&`((${e[0]}) ∈ ${Ee(e[1])})`,contains:e=>2===e.length&&`((${e[1]}) ∈ ${Ee(e[0])})`,isclose:e=>e.length>=2&&`((${e[0]}) ≈ (${e[1]}))`,isfinite:e=>1===e.length&&`((${e[0]}) ∈ ℝ)`,isinteger:e=>1===e.length&&`((${e[0]}) ∈ ℤ)`,factorial:e=>1===e.length&&`((${e[0]})!)`,union:e=>2===e.length&&`((${e[0]}) ∪ (${e[1]}))`,union_:e=>2===e.length&&`((${e[0]}) ∪ (${e[1]}))`,intersection:e=>2===e.length&&`((${e[0]}) ∩ (${e[1]}))`,sq:e=>1===e.length&&`((${e[0]})^2)`,cube:e=>1===e.length&&`((${e[0]})^3)`,fract:e=>1===e.length&&`((${e[0]}) - floor(${e[0]}))`,inversesqrt:e=>1===e.length&&`(1/sqrt(${e[0]}))`,radians:e=>1===e.length&&`((${e[0]})°)`,degrees:e=>1===e.length&&`((${e[0]})/°)`,mod:e=>2===e.length&&`((${e[0]}) \\mod (${e[1]}))`,atan:e=>2===e.length&&`atan2(${e[0]}, ${e[1]})`,exp2:e=>1===e.length&&`((2)^(${e[0]}))`,trunc:e=>1===e.length&&`((${e[0]}) < 0 ? (ceil(${e[0]})) : floor(${e[0]}))`,vec2:e=>`(${e.join(", ")})`,vec3:e=>`(${e.join(", ")})`,vec4:e=>`(${e.join(", ")})`,derivative:e=>e.length>=2&&`der(${e.join(", ")})`,sympy_rational:e=>2===e.length&&`((${e[0]})/(${e[1]}))`,sympy_value:e=>1===e.length&&`(${e[0]})`,sympy_eq:e=>2===e.length&&`((${e[0]}) = (${e[1]}))`,sympy_ne:e=>2===e.length&&`((${e[0]}) ≠ (${e[1]}))`,sympy_and:e=>e.length&&`(${e.map(_e).join(" & ")})`,sympy_or:e=>e.length&&`(${e.map(_e).join(" ∨ ")})`,sympy_not:e=>1===e.length&&`(!(${e[0]}))`,sympy_xor:e=>2===e.length&&`((${e[0]}) \\xor (${e[1]}))`,sympy_nand:e=>2===e.length&&`((${e[0]}) \\nand (${e[1]}))`,sympy_implies:e=>2===e.length&&`((${e[0]}) \\implies (${e[1]}))`,sympy_iff:e=>2===e.length&&`((${e[0]}) \\iff (${e[1]}))`,sympy_nor:e=>2===e.length&&`((${e[0]}) \\nor (${e[1]}))`,sympy_piecewise:e=>{const t=e.map(Le);return!t.length||t.some(e=>!e||2!==e.length)?null:t.reduceRight((e,[t,r])=>null===e||/^True$|^true$/.test(r.trim())&&void 0===e?`(${t})`:`((${r}) ? (${t}) : ${e??"(null)"})`,void 0)},sympy_set:e=>`{${e.join(", ")}}`,sympy_interval:De("[]"),sympy_interval_open:De("()"),sympy_interval_Lopen:De("(]"),sympy_interval_Ropen:De("[)"),sympy_contains:e=>2===e.length&&`((${e[0]}) ∈ ${e[1]})`,sympy_list_gcd:e=>1===e.length&&`gcd(${e[0].trim().replace(/^\[|\]$/g,"")})`,sympy_root:e=>2===e.length&&`root(${e[1]}, ${e[0]})`,sympy_integrate:e=>{if(2!==e.length)return null;const t=Be(e[1]);return 3===t.length?`int(${e[0]}, ${t.join(", ")})`:1===t.length?`int(${e[0]}, ${t[0]})`:null},sympy_limit:e=>e.length>=3&&`lim(${e.slice(0,3).join(", ")}${e[3]?`, ${e[3]}`:""})`,sympy_summation:e=>{if(3===e.length&&/^\s*[A-Za-z]\w*\s*==/.test(e[1]))return`sum(${e[0]}, ${e[1].replace("==","=")}, ${e[2]})`;const t=2===e.length&&Be(e[1]);return 3===t?.length&&`(\\sum_{${t[0]}=${t[1]}}^{${t[2]}} (${e[0]}))`},sympy_product:e=>{if(3===e.length&&/^\s*[A-Za-z]\w*\s*==/.test(e[1]))return`prod(${e[0]}, ${e[1].replace("==","=")}, ${e[2]})`;const t=2===e.length&&Be(e[1]);return 3===t?.length&&`(\\prod_{${t[0]}=${t[1]}}^{${t[2]}} (${e[0]}))`},limit:e=>e.length>=3&&`lim(${e.join(", ")})`,summation:e=>3===e.length&&/^\s*[A-Za-z]\w*\s*==/.test(e[1])&&`sum(${e[0]}, ${e[1].replace("==","=")}, ${e[2]})`,sum:Ge("sum"),prod:Ge("prod")};function Ge(e){return t=>{const r=1===t.length&&/^(.*?)\s+for\s+(\w+)\s+in\s+range\((.*)\)\s*$/s.exec(t[0]);if(!r)return null;const n=we(r[3]),[o,s]=1===n.length?["0",n[0]]:n,a=/\s*\+\s*1$/.test(s)?s.replace(/\s*\+\s*1$/,""):`(${s}) - 1`;return`(\\${e}_{${r[2]}=${o}}^{${a}} (${r[1]}))`}}function We(e){e=function(e){for(let t=e.lastIndexOf("(lambda");t>=0;t=t>0?e.lastIndexOf("(lambda",t-1):-1){const r=be(e,t);if(r<0||"("!==e[r+1])continue;const n=be(e,r+1),o=/^\(lambda\s+([\w\s,]+?)\s*:\s*([\s\S]*)\)$/.exec(e.slice(t,r+1));if(n<0||!o)continue;const s=o[1].split(",").map(e=>e.trim()),a=we(e.slice(r+2,n));if(a.length!==s.length||!s.every(e=>/^[A-Za-z_]\w*$/.test(e)))continue;const i=new Map(s.map((e,t)=>[e,a[t]])),l=o[2].replace(new RegExp(`(?<![\\w.])(${s.join("|")})(?!\\w)`,"g"),e=>`(${i.get(e)})`);if((e=e.slice(0,t)+`(${l})`+e.slice(n+1)).length>1e5)throw new Error("The expression expands too much when read")}return e}(e),e=xe(e,ve("quad"),(e,t,r)=>{const n=/^lambda\s+(\w+)\s*:\s*(.*)$/s.exec(e[0]??"");if(!n||3!==e.length)return null;const o=/^\s*\[\s*0\s*\]/.exec(r);return[`int(${n[2]}, ${n[1]}, ${e[1]}, ${e[2]})`,o?o[0].length:0]}),e=xe(e,ve(Object.keys(Ze).join("|")),(e,t)=>Ze[t[1]](e)||null);for(let t=(e=xe(e,ve("float"),(e,t,r)=>{const n=/^\s*\.is_integer\(\s*\)/.exec(r);return n&&1===e.length?[`((${e[0]}) ∈ ℤ)`,n[0].length]:null})).lastIndexOf(".includes(");t>=0;t=t>0?e.lastIndexOf(".includes(",t-1):-1){const r=t+9,n=be(e,r);let o=t;if(ye.includes(e[t-1])){let r=0;for(o=t-1;o>=0;o--)if(ye.includes(e[o]))r++;else if($e.includes(e[o])&&0===--r)break}else for(;o>0&&/[\w.]/.test(e[o-1]);)o--;n<0||o<0||o===t||(e=`${e.slice(0,o)}((${e.slice(r+1,n)}) ∈ ${Ee(e.slice(o,t))})${e.slice(n+1)}`)}return e}for(const e of[ze,Oe,Ne,Ie,Fe,qe,Pe,Ue,Ze,Re])Object.setPrototypeOf(e,null);const He=String.raw`(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}|(?<![\w.′^])[\w.′^]+)`,Xe=e=>e.trim().split(/\s+/).join(String.raw`\s+`),Ve=e=>new RegExp(String.raw`(?<![\w.])${Xe(e)}(?![\w.])`,"gi"),Ye=[["is greater than or equal to","≥"],["is more than or equal to","≥"],["is at least","≥"],["is no less than","≥"],["is not less than","≥"],["is less than or equal to","≤"],["is at most","≤"],["is no more than","≤"],["is not more than","≤"],["is not greater than","≤"],["is greater than",">"],["is more than",">"],["is bigger than",">"],["is larger than",">"],["is above",">"],["exceeds",">"],["is less than","<"],["is smaller than","<"],["is fewer than","<"],["is below","<"],["is not equal to","≠"],["does not equal","≠"],["doesn't equal","≠"],["is different from","≠"],["is approximately equal to","≈"],["is approximately","≈"],["is about","≈"],["is roughly","≈"],["is close to","≈"],["is equal to","="],["is the same as","="],["equals","="],["greater than or equal to","≥"],["less than or equal to","≤"],["at least","≥"],["at most","≤"],["greater than",">"],["more than",">"],["less than","<"],["not equal to","≠"],["equal to","="]],Je="[<>≤≥=≠≈]",Ke={second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10};Object.setPrototypeOf(Ke,null);const Qe=Object.entries({sine:"sin",cosine:"cos",tangent:"tan",secant:"sec",cosecant:"csc",cotangent:"cot","natural log":"ln","natural logarithm":"ln",arcsine:"arcsin",arccosine:"arccos",arctangent:"arctan",arcsecant:"arcsec",arccosecant:"arccsc",arccotangent:"arccot","hyperbolic sine":"sinh","hyperbolic cosine":"cosh","hyperbolic tangent":"tanh",floor:"floor",ceiling:"ceil"}).sort((e,t)=>t[0].length-e[0].length),et=[["is non-negative","≥ 0"],["is nonnegative","≥ 0"],["is not negative","≥ 0"],["is non-positive","≤ 0"],["is nonpositive","≤ 0"],["is not positive","≤ 0"],["is positive","> 0"],["is negative","< 0"],["is non-zero","≠ 0"],["is nonzero","≠ 0"],["is not zero","≠ 0"],["is zero","= 0"],["is a whole number","∈ ℤ"],["is an integer","∈ ℤ"],["is not an integer","∉ ℤ"],["is a natural number","∈ ℕ"],["is a real number","∈ ℝ"],["is real","∈ ℝ"],["is a rational number","∈ ℚ"],["is rational","∈ ℚ"]],tt=/(?<![A-Za-z])(?:is|between|exceeds|equals?|does|doesn't|least|most|than|divides|and|or|of|to|squared|cubed|twice|percent|by|over|times|plus|minus|modulo)(?![A-Za-z])/i;Ye.map(([e])=>e),et.map(([e])=>e),Qe.map(([e])=>`${e} of`);const rt=e([[" And "," & "],[" Or "," ∨ "],[" Not In "," ∉ "],[" Nor "," \\nor "],[" Xor "," \\xor "],[" Nand "," \\nand "],[" In "," ∈ "],[" Mod "," \\mod "],[" % ","%"],[" Perm ","\\perm "],[" P ","\\perm",!0],[" Comb ","\\comb "],[" C ","\\comb",!0],[" choose ","\\comb "],["! ","!_"],["\\in ","∈"],["\\notin ","∉"],["\\not\\in ","∉"],["\\to ","→"],["===","=...="]]),nt=e([...g,...function(){const e=[],t=(t,r)=>{e.push([t,r],[t+"(",r+"("])};for(const r of["sin","cos","tan","cot","csc","sec"]){e.push(["Math."+r+"(",r+"("],["\\"+r+"(",r+"("],["\\"+r,r]);for(const e of["sin","cos","tan"].includes(r)?["","h"]:[""]){const n=r+e,o="arc"+r+e;e&&(t("Math."+n,n),t("\\"+n,n));for(const r of["^-1","^{-1}","-1"])t("\\"+n+r,o),t(n+r,o),e||t("Math."+n+r,o);e||t("\\a"+n,o),t("\\arc"+n,o),t("Math.a"+n,o),t("Math.arc"+n,o)}}return e}()]),ot=[["code",function(e){return/^\s*=|[(.%^<_eE]|\|\||\bif\b|\b(?:True|False|None|TRUE|FALSE|NULL)\b/.test(e)?(/^\s*=(?!=)/.test(e)&&(e=ke(e)),e=function(e){for(const[t,r]of Ae)for(let n=e.lastIndexOf(r);n>=0;n=n>0?e.lastIndexOf(r,n-1):-1){const o=n+r.length,s="("===e[o]?be(e,o):-1;if(s<0)continue;let a=e.slice(o+1,s);"gcd"===t&&(a=a.trim().replace(/^\[|\]$/g,""));const i="factorial"===t?`((${a})!)`:`${t}(${a})`;e=e.slice(0,n)+i+e.slice(s+1)}for(let t=e.lastIndexOf(").toFixed(");t>=0;t=t>0?e.lastIndexOf(").toFixed(",t-1):-1){const r=t+10-1,n=be(e,r),o=e.lastIndexOf("Number(",t);n<0||o<0||be(e,o+7-1)!==t||(e=e.slice(0,o)+`fixed(${e.slice(o+7,t)}, ${e.slice(r+1,n)})`+e.slice(n+1))}return e.replace(/\(\(\)=>\{let (sum|prod) = [01]; let loopCount = 0; for \(let (\w+)=(.*?);\2<=(.*?);\2\+\+\) \{if \(loopCount\+\+ > 1000000\)\{break\};\1 [+*]= (.*?);\}; return \1;\}\)\(\)/g,(e,t,r,n,o,s)=>`(\\${"sum"===t?"sum":"prod"}_{${r}=${n}}^{${o}} (${s}))`)}(e),e=function(e){for(let t=0;t<50;t++){let t=!0;for(const r of e.matchAll(/\bif\b/g)){const n=r.index;let o=0,s=-1,a=e.length;for(let t=n+2;t<e.length;t++)if($e.includes(e[t]))o++;else{if(ye.includes(e[t])&&--o<0){a=t;break}if(0===o&&","===e[t]){a=t;break}if(0===o&&/^then\b/.test(e.slice(t))&&/\W/.test(e[t-1])){s=-2;break}0===o&&s<0&&/^else\b/.test(e.slice(t))&&/\W/.test(e[t-1])&&(s=t)}if(s<0)continue;o=0;let i=0;for(let t=n-1;t>=0;t--)if(ye.includes(e[t]))o++;else{if($e.includes(e[t])&&--o<0){i=t+1;break}if(0===o&&","===e[t]){i=t+1;break}}const l=e.slice(i,n).trim();if(!l)continue;const c=`((${e.slice(n+2,s).trim()}) ? (${l}) : (${e.slice(s+4,a).trim()}))`;e=e.slice(0,i)+c+e.slice(a),t=!1;break}if(t)return e}return e}(e=We(e=function(e){return e.includes("set")?Te(xe(e,/(?<![\w.])sorted\s*\(/g,e=>{if(1!==e.length)return null;const t=e[0];for(let e=0,r=0;e<t.length;e++)if("([{".includes(t[e]))r++;else if(")]}".includes(t[e]))r--;else if(0===r&&("|"===t[e]||"&"===t[e])){const r=e=>{const t=e.trim(),r=/^set\s*\(/.exec(t);return r&&be(t,r[0].length-1)===t.length-1?t.slice(r[0].length,-1):null},[n,o]=[r(t.slice(0,e)),r(t.slice(e+1))];return null!==n&&null!==o?`((${n}) ${"|"===t[e]?"∪":"∩"} (${o}))`:null}return null})):e}(e=Ce(e=Se(e=(e=e.replace(/(?<![\w.])9e999\b/g,"∞")).replace(/(?<![\w.])(\d+(?:\.\d+)?)[eE]([+-]?\d+)(?![\w.])/g,"($1*10^{$2})")))))),(e=(e=e.replace(/\b(?:True|TRUE)\b/g,"true").replace(/\b(?:False|FALSE)\b/g,"false").replace(/\b(?:None|NULL)\b/g,"null")).replace(/\^\^/g," \\xor ")).replace(/%(?=\s*(?:[(-]|[A-Za-z_][\w.]*\s*\())/g," \\mod ")):e}],["english",function(e){if(!tt.test(e))return e;let t=e;const r=(e,r,n,o="∈")=>{t=t.replace(new RegExp(String.raw`(?<![\w.])${Xe(e)}\s+(${He})\s+(?:and|to)\s+(${He})(?:\s+(inclusive|exclusive))?(?![\w.])`,"gi"),(e,t,s,a)=>{const[i,l]="exclusive"===a?.toLowerCase()?["(",")"]:"inclusive"===a?.toLowerCase()?["[","]"]:[r,n];return` ${o} ${i}${t}, ${s}${l} `})};r("is not strictly between","(",")","∉"),r("is not between","[","]","∉"),r("is strictly between","(",")"),r("is between","[","]"),r("between","[","]"),t=t.replace(new RegExp(String.raw`(?<![\w.])is\s+(not\s+)?in\s+the\s+(open|closed|half-open)\s+interval\s+from\s+(${He})\s+to\s+(${He})`,"gi"),(e,t,r,n,o)=>{const[s,a]={open:["(",")"],closed:["[","]"],"half-open":["[",")"]}[r.toLowerCase()];return` ${t?"∉":"∈"} ${s}${n}, ${o}${a} `});const n=String.raw`(${He})\s+`;t=t.replace(new RegExp(n+String.raw`is\s+(not\s+)?within\s+(${He})\s*(%|\s+percent)?\s+of\s+(${He})`,"gi"),(e,t,r,n,o,s)=>`(abs((${t}) - (${s})) ${r?">":"≤"} ${o?`(${n})/100 * ${/^\d+(\.\d+)?$/.test(s)?s:`abs(${s})`}`:`(${n})`})`),t=t.replace(new RegExp(n+String.raw`is\s+(?:a\s+)?multiple\s+of\s+(${He})`,"gi"),"(($1) mod ($2) = 0)"),t=t.replace(new RegExp(n+String.raw`is\s+(not\s+)?divisible\s+by\s+(${He})`,"gi"),(e,t,r,n)=>`((${t}) mod (${n}) ${r?"≠":"="} 0)`),t=t.replace(new RegExp(String.raw`(${He})\s+divides\s+(${He})`,"gi"),"(($2) mod ($1) = 0)"),t=t.replace(new RegExp(n+String.raw`is\s+(not\s+)?(even|odd)(?![\w.])`,"gi"),(e,t,r,n)=>`((${t}) mod 2 ${"even"===n.toLowerCase()!==Boolean(r)?"=":"≠"} 0)`);for(const[e,r]of et)t=t.replace(Ve(e),` ${r} `);t=t.replace(Ve("is not in")," ∉ ").replace(Ve("is in")," ∈ ").replace(Ve("is an element of")," ∈ ");for(const[e,r]of Ye)t=t.replace(Ve(e),` ${r} `);t=t.replace(Ve("is not")," ≠ "),t=t.replace(/(?<=[\w.)\]}′]\s+)is(?=\s+[\w.(\[{-])/gi," = ");for(let e=!0;e;){const r=t;t=t.replace(new RegExp(String.raw`(${He})\s*(${Je})\s*(${He})\s+(and|or)\s+(${Je})`,"gi"),"$1 $2 $3 $4 $1 $5"),e=t!==r}t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?absolute\s+value\s+of\s+(${He})`,"gi"),"abs($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?square\s+root\s+of\s+(${He})`,"gi"),"sqrt($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?cube\s+root\s+of\s+(${He})`,"gi"),"root(3, $1)"),t=t.replace(new RegExp(String.raw`(${He})\s+to\s+the\s+power\s+of\s+(${He})`,"gi"),"($1)^($2)"),t=t.replace(new RegExp(String.raw`(${He})\s+to\s+the\s+(${Object.keys(Ke).join("|")}|(\d+|n)(?:st|nd|rd|th))(?:\s+power)?(?![\w.])`,"gi"),(e,t,r,n)=>`(${t})^(${Ke[r.toLowerCase()]??n})`),t=t.replace(new RegExp(String.raw`(${He})\s+to\s+the\s+(${He})(?![\w.])`,"gi"),"($1)^($2)");for(const[e,r]of Qe)t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?${Xe(e)}\s+of\s+(${He})`,"gi"),`${r}($1)`);t=t.replace(new RegExp(String.raw`(${He})\s+squared(?![\w.])`,"gi"),"($1)^2"),t=t.replace(new RegExp(String.raw`(${He})\s+cubed(?![\w.])`,"gi"),"($1)^3"),t=t.replace(new RegExp(String.raw`(?<![\w.])half\s+of\s+(${He})`,"gi"),"($1)/2"),t=t.replace(new RegExp(String.raw`(?<![\w.])twice\s+(${He})`,"gi"),"2*($1)"),t=t.replace(new RegExp(String.raw`(\d+(?:\.\d+)?)\s+percent(?![\w.])`,"gi"),"$1%");const o=e=>new RegExp(String.raw`(?<=[\w.′)\]}]\s+)${Xe(e)}(?=\s+[\w.(\[{-])`,"gi");for(const[e,r]of[["divided by","/"],["over","/"],["multiplied by","*"],["times","*"],["plus","+"],["minus","-"],["modulo","mod"]])t=t.replace(o(e),` ${r} `);return t}],["words",rt],["spaced",function(e){e=function(e){for(let t=e.lastIndexOf("\\sqrt");t>=0;t=t>0?e.lastIndexOf("\\sqrt",t-1):-1){let r=t+5;if(/[A-Za-z]/.test(e[r]??""))continue;for(;d(e[r]);)r++;const n=e.slice(r);let o=/^(?:§\d+§|-?(?:\d+(?:\.\d+)?|\.\d+)|-?[A-Za-zͰ-Ͽ])/.exec(n)?.[0];if(!o&&/^\\[A-Za-z]/.test(n)&&!n.startsWith("\\left")){let e=/^\\[A-Za-z]+/.exec(n)[0].length;if(/^\d\d/.exec(n.slice(e))&&/frac$/.test(n.slice(0,e)))e+=2;else{const t=/^\s*\[[^\[\]{}]*\]/.exec(n.slice(e));for(t&&(e+=t[0].length);;){let t=e;for(;d(n[t]);)t++;if("{"!==n[t])break;let r=0,o=-1;for(let e=t;e<n.length;e++)if("{"===n[e])r++;else if("}"===n[e]&&0===--r){o=e;break}if(o<0)break;e=o+1}}o=n.slice(0,e)}o&&(e=`${e.slice(0,t)}\\sqrt{${o}}${e.slice(r+o.length)}`)}return e}(function(e){return e=e.replace(T,(e,t,r)=>`(${t}+${I[r]})`),e=e.replace(R,(e,t,r,n)=>Number(r)<Number(n)&&3!==r.length?`(${t}+${r}/${n})`:e),e.replace(C,(e,t,r,n,o,s)=>{const[a,i]=[r??o,n??s];return Number(a)<Number(i)?`(${t}+\\frac{${a}}{${i}})`:e})}(function(e){return e.replace(N,e=>{const t=e[0]in j;return`${t?"^":"_"}{${[...e].map(e=>(t?j:S)[e]).join("")}}`})}(e))),e=function(e){return e.replace(/(?:\{\s*\}|(?<![\w}\])′]))_\s*(?:\{\s*([^{}]+?)\s*\}|([A-Za-z0-9]+?))\s*(?:\\mathrm\{([CP])\}|([CP]))\s*_\s*(?:\{\s*([^{}]+?)\s*\}|([A-Za-z0-9]))/g,(e,t,r,n,o,s,a)=>`${"C"===(n??o)?"comb":"perm"}(${t??r},${s??a})`)}(function(e){return e.replace(/(?<![A-Za-z\\])([A-Za-z])\^\s*\{?\s*\(\s*([1-9])\s*\)\s*\}?(?=\s*\()/g,(e,t,r)=>t+"′".repeat(Number(r)))}(function(e){return e.replace(/(?<![A-Za-z\\])(arc)?(sine|cosine|tangent|secant|cosecant|cotangent)(?![A-Za-z])(?=\s*\(|\s+(?:[A-Za-z](?![A-Za-z])|\d|\\))/gi,(e,t,r)=>(t?"arc":"")+O[r.toLowerCase()])}(e))),e=function(e){if(/\\[io]*int|∫|(?<![A-Za-z])int\(|\\partial|∂|(?<![A-Za-z])d\s*\/\s*d|frac\s*\{\s*(?:\\mathrm\s*\{\s*d\s*\}|\\operatorname\s*\{\s*d\s*\}|d)/.test(e))return e;const t=[];for(const r of e.matchAll(w)){const n=e.slice(0,r.index),o=e.slice(r.index+r[0].length),s="d"!==r[1];if(!s&&(/[A-Za-z0-9\\^_/]$|frac\s*\{$/.test(n)||/^\s*[/}]/.test(o)&&!/\{\s*$/.test(n)))continue;const a=s||/\\[,;:! ]\s*$/.test(n);t.push({m:r,strong:a})}const r=t.length>=2?t:t.filter(e=>e.strong);for(const{m:t}of r.reverse())e=e.slice(0,t.index)+b+t[2]+e.slice(t.index+t[0].length);return e}(e),/\\/.test(e)||(e=x(e)),e=D(e=function(e){for(let t=0;t<e.length;t++){const r=r=>e.slice(Math.max(0,t-r),t+1);if("t"===e[t]&&"\\text"===r(4)&&"{"===e[t+1]){let r=1,n=t+2,o="";for(;r>0&&n<e.length;)"{"===e[n]?r++:"}"===e[n]?r--:o+=e[n],n++;e=e.slice(0,t-4)+o+e.slice(n)}}return e}(e=(e=(e=function(e){for(let t=0;t<100;t++){const t=[...e.matchAll(/\bif\b/gi)];if(!t.length)return e;const r=t[t.length-1].index,n=P(e,r+2,"then");if(n<0)return e;const o=e.slice(r+2,n),s=P(e,n+4,"else"),a=U(e,s<0?n+4:s+4),i=e.slice(n+4,s<0?a:s),l=s<0?"unchanged":e.slice(s+4,a).trim();e=`${e.slice(0,r)}((${o.trim()}) ? (${i.trim()}) : (${l}))${e.slice(a)}`}return e}(e=e.replace(/(?<![.\w=])\.\.\.(?![.\w=])/g,"⋯").replace(/∅/g,"\\{\\}"))).replace(/\(\s*\\?b?mod\s+([^()\s](?:[^()]*[^()\s])?)\s*\)/g," \\pmod{$1}")).replace(/(^|[^A-Za-z\\])lim\s+([^\s_{}]+?)\s*(->|→|\\to)\s*([^\s]+)\s+/g,"$1lim_{$2→$4} ")));for(let t=0;t<e.length-1;t++)if("?"===e[t]&&":"!==e[t+1])e=L(e,t);else if("_"===e[t]||"^"===e[t]){const r=/^§\d+§/.exec(e.slice(t+1));if(r){e=`${e.slice(0,t+1)}{${r[0]}}${e.slice(t+1+r[0].length)}`;continue}const n=("^"===e[t]||/[A-Za-z}]/.test(e[t-1]??""))&&/^\\[A-Za-z]+(?![A-Za-z{\d])/.exec(e.slice(t+1));if(n){e=`${e.slice(0,t+1)}{${n[0]}}${e.slice(t+1+n[0].length)}`;continue}let o=t+1;for("-"===e[o]&&o++;o<e.length&&".0123456789".includes(e[o]);)o++;if(o===t+2&&"-"===e[t+1]&&(o=t+1),"-"===e[t+1]&&/^\s*[\^!]/.test(e.slice(o,o+8)))continue;o>t+1&&(e=e.slice(0,t+1)+"{"+e.slice(t+1,o)+"}"+e.slice(o))}return e}],["squeeze",function(e){return e.replace(/\s+/g,(t,r)=>{const n=e[r-1]??"",o=e[r+t.length]??"";return"Δ"===n?"":/[A-Za-z\u0370-\u03FF′]/.test(n)&&/[A-Za-z\u0370-\u03FF]/.test(o)||/[A-Za-z\u0370-\u03FF′]/.test(n)&&/\d/.test(o)&&!/\\[A-Za-z]+$/.test(e.slice(0,r))?" ":""})}],["symbols",nt],["bar",function(e){let t=0;for(let r=e.indexOf(l,t);r>=0;r=e.indexOf(l,t)){let n=0,o=-1;for(let t=r+1;t<e.length;t++)if("([{".includes(e[t]))n++;else if(")]}".includes(e[t]))n--;else if(0===n&&e.startsWith("|_",t)){o=t;break}o<0&&st(),e=`${e.slice(0,r+1)}(${e.slice(r+1,o)})${e.slice(o)}`,t=r+1}return e}],["compact",function(e){if(e=function(e){for(let t=0;t<e.length;t++){const r=t>0&&J.test(e[t-1]);let n,o=null,s=t;if(e.startsWith("frac{",t)){const r=K(e,t+4),n=r&&K(e,r[1]);o=n&&ee(r[0],n[0]),o&&(s=n[1])}else if("d"===e[t]&&!r){let[r,n]=Q(e,t+1),a="";if(J.test(e[n]??"")&&"/"===e[n+1]&&(a=e[n++]),"/"===e[n]&&"d"===e[n+1]&&J.test(e[n+2]??"")){const t=e[n+2],[,i]=Q(e,n+3);o={n:r,of:a,by:t},s=i}}if(o){if(o.of)n=re(o.of,o.by,o.n);else{const[t,r]=te(e,s);if(!t)continue;n=re(t,o.by,o.n),s=r}e=e.slice(0,t)+n+e.slice(s),t+=3}}return e}(e=function(e){for(let t=e.indexOf(")′");t>=0;t=e.indexOf(")′",t+1)){let r=0,n=-1;for(let o=t;o>=0;o--)if(")"===e[o])r++;else if("("===e[o]&&0===--r){n=o;break}if(n<0)continue;for(;n>0&&/[A-Za-z\u0370-\u03FF′]/.test(e[n-1]);)n--;let o=0;for(;"′"===e[t+1+o];)o++;e=e.slice(0,n)+re(e.slice(n,t+1),"x",o)+e.slice(t+1+o),t=n}return e}(e=(e=D(e)).replace(/(?<![A-Za-z])frac(\d)(\d)/g,"frac{$1}{$2}"))),e.split("\\int").length>101)throw new Error("More than 100 integrals");for(let t=0;t<e.length;t++){const r=e[t],n=r=>e.slice(Math.max(0,t-r),t),o=r=>e.slice(Math.max(0,t-r),t+1);if("{"===r){if("\\begin"===n(6)){const r=W(e.slice(t+1));r&&(e=e.slice(0,t-6)+r)}}else if("["===r)"\\sqrt"===n(5)?e=e.slice(0,t-5)+"sqrt"+Z(e.slice(t+1)):"sqrt"===n(4)&&(e=e.slice(0,t-4)+"sqrt"+Z(e.slice(t+1)));else if("⌊"===r||"⌈"===r)e=e.slice(0,t)+B(e.slice(t));else if("t"===r)"\\int"===o(3)&&(e=e.slice(0,t-3)+X(e.slice(t+1)));else if("m"===r)"\\binom"===o(5)&&(e=e.slice(0,t-5)+"\\binom"+Y(e.slice(t+1)));else if("d"===r&&"dd"===o(1)&&"("===e[t+2]){const r=V(e.slice(t+1));r&&(e=e.slice(0,t-1)+"der"+r)}}return(e=e.replace(/\\(?:text|textrm|textit|mathrm|mathit|mathbf|mathsf|operatorname)\{([A-Za-z])\}/g,"$1")).replace(/\\log/g,"log")}],["bars",function(e){for(let t=e.indexOf(l);t>=0;t=e.indexOf(l)){const r=st;e.startsWith("(der(",t+1)||r();const n=at(e,t+1,"(",")"),o=at(e,t+5,"(",")");(o<0||n!==o+1)&&r();const s=it(e.slice(t+6,o));(s.length<2||s.length>3||!e.startsWith("|_",n+1))&&r();const a=n;let i,l;"{"===e[a+3]?(l=at(e,a+3,"{","}"),l<0&&r(),i=e.slice(a+4,l)):(l=a+3,i=e[l]??"");const[c,u,p]=s;i.trim()||r();const h=i.includes("=")?i:`${u}=${i}`;e=`${e.slice(0,t)}der(${c},${h}${p?`,${p}`:""})${e.slice(l+1)}`}return e}],["tidy",e=>e.replace(/ {2,}/g," ").trim()]],st=()=>{throw new Error("A bar with one limit (\\left. … \\right|_{x = a}) is read only after a derivative, \\left.\\frac{d}{dx} f\\right|_{x=a}; with two, \\left. F \\right|_a^b, it is F at b minus F at a")};function at(e,t,r,n){let o=0;for(let s=t;s<e.length;s++)if(e[s]===r)o++;else if(e[s]===n&&0===--o)return s;return-1}function it(e){const t=[];let r=0,n=0;for(let o=0;o<e.length;o++)"([{".includes(e[o])?r++:")]}".includes(e[o])?r--:","===e[o]&&0===r&&(t.push(e.slice(n,o)),n=o+1);return t.push(e.slice(n)),t}function lt(e,t={}){if("string"!=typeof e)throw new Error("Expression must be a string");const{text:r,strings:n}=function(e){const t=new Map;let r="",n=0;for(;n<e.length;){const o=e[n];if('"'!==o&&"'"!==o&&"`"!==o){r+=e[n++];continue}let s=n+1,a="",i=!1;for(;s<e.length&&(i||e[s]!==o);)i=!i&&"\\"===e[s],a+=e[s++];const l=se(t.size);t.set(l,o+a+o),r+=l,n=s+1}return{text:r,strings:t}}(ie(e));let o=r.replace(/\t/g," ");t.evaluate&&(o=function(e,t,r){const n=/\\[A-Za-z]/.test(e);let o=0;for(;;){let s=e.indexOf("{{",o);if(s<0)return e;let a=!1;const i=n&&ct.test(e.slice(0,s));if(ut(e,s)||i&&"{"===e[s+2]?s+=1:a=i,!e.startsWith("{{",s)){o=s;continue}const l=pt(e,s);if(l<0)return e;let c=e.slice(s+2,l).trim();for(const[e,r]of t)c=c.split(e).join(r);try{let n=r(c);if(/^["'`]/.test(n)){const e=se(t.size);t.set(e,n),n=e}const i=e.slice(0,s).trimEnd(),u=e.slice(l+2).trimStart();/^[\d.]/.test(n)&&(/[\d.]$/.test(i)||/^[\d.]/.test(u))&&(n=`(${n})`),a&&(n=`{${n}}`),e=e.slice(0,s)+" "+n+" "+e.slice(l+2),o=s+1+n.length}catch{o=l+2}}}(o,n,t.evaluate));const s=[["strings",o]];for(const[e,t]of ot){if(o=t(o),o.length>1e5)throw new Error("The expression expands too much when read");s.push([e,o])}return{cleaned:o,stringMap:n,steps:s}}const ct=/(?:\\[A-Za-z]+\*?|[\^_}\]])$/;function ut(e,t){let r=0;for(;"\\"===e[t-1-r];)r++;return r%2==1}function pt(e,t){let r=0;for(let n=t+2;n<e.length;n++){if(e.startsWith("}}",n)&&0===r)return n;"{"===e[n]?r++:"}"===e[n]&&r--}return-1}const ht=-1,ft={"+":{prec:50,assoc:"left",arity:2,fixity:"infix"},"-":{prec:50,assoc:"left",arity:2,fixity:"infix"},"±":{prec:50,assoc:"left",arity:2,fixity:"infix"},"*":{prec:70,assoc:"left",arity:2,fixity:"infix"},"/":{prec:70,assoc:"left",arity:2,fixity:"infix"},"^":{prec:80,assoc:"right",arity:2,fixity:"infix"},mod:{prec:45,assoc:"left",arity:2,fixity:"infix"},neg:{prec:75,assoc:"none",arity:1,fixity:"prefix"},pm:{prec:75,assoc:"none",arity:1,fixity:"prefix"},"!":{prec:90,assoc:"none",arity:1,fixity:"postfix"},_:{prec:100,assoc:"none",arity:2,fixity:"infix"},sqrt:mt(1),abs:mt(1),floor:mt(1),ceil:mt(1),det:mt(1),ln:mt(1),loglog:mt(1),logloglog:mt(1),expm1:mt(1),sin:mt(1),cos:mt(1),tan:mt(1),csc:mt(1),sec:mt(1),cot:mt(1),sinh:mt(1),cosh:mt(1),tanh:mt(1),arcsin:mt(1),arccos:mt(1),arctan:mt(1),arcsec:mt(1),arccsc:mt(1),arccot:mt(1),arcsinh:mt(1),arccosh:mt(1),arctanh:mt(1),random:mt(0),log:mt(2),root:mt(2),atan2:mt(2),round:mt(2),fixed:mt(2),perm:mt(2),comb:mt(2),der:mt(2),evaluated:mt(4),setbuilder:mt(2),max:mt(ht),min:mt(ht),gcd:mt(ht),mean:mt(ht),sum:mt(ht),prod:mt(ht),int:mt(ht),lim:mt(ht),"\\sumidx":mt(ht),"\\prodidx":mt(ht),pmatrix:mt(ht),bmatrix:mt(ht),vmatrix:mt(ht),"()":gt(),"[]":gt(),"{}":gt(),"(]":gt(),"[)":gt(),"=":{prec:30,assoc:"left",arity:2,fixity:"infix"},"===":{prec:30,assoc:"left",arity:2,fixity:"infix"},"≠":{prec:30,assoc:"left",arity:2,fixity:"infix"},"≠=":{prec:30,assoc:"left",arity:2,fixity:"infix"},"<":{prec:34,assoc:"left",arity:2,fixity:"infix"},">":{prec:34,assoc:"left",arity:2,fixity:"infix"},"≤":{prec:34,assoc:"left",arity:2,fixity:"infix"},"≥":{prec:34,assoc:"left",arity:2,fixity:"infix"},"∈":{prec:32,assoc:"left",arity:2,fixity:"infix"},"∉":{prec:32,assoc:"left",arity:2,fixity:"infix"},"∪":{prec:33,assoc:"left",arity:2,fixity:"infix"},"∩":{prec:33,assoc:"left",arity:2,fixity:"infix"},"≈":{prec:30,assoc:"left",arity:2,fixity:"infix"},"≡":{prec:30,assoc:"left",arity:2,fixity:"infix"},pmod:{prec:2,assoc:"left",arity:2,fixity:"infix"},"→":{prec:38,assoc:"left",arity:2,fixity:"infix"},"\\not":{prec:85,assoc:"none",arity:1,fixity:"prefix"},"&":{prec:20,assoc:"left",arity:2,fixity:"infix"},"\\xor":{prec:19,assoc:"left",arity:2,fixity:"infix"},"|":{prec:18,assoc:"left",arity:2,fixity:"infix"},"\\nor":{prec:17,assoc:"left",arity:2,fixity:"infix"},"\\nand":{prec:17,assoc:"left",arity:2,fixity:"infix"},"\\implies":{prec:15,assoc:"right",arity:2,fixity:"infix"},"\\iff":{prec:14,assoc:"left",arity:2,fixity:"infix"},"?:":{prec:10,assoc:"right",arity:3,fixity:"infix"}};function mt(e){return{prec:100,assoc:"none",arity:e,fixity:"prefix"}}function gt(){return{prec:5,assoc:"left",arity:ht,fixity:"none",group:!0}}const dt="\\:",$t=e=>"string"==typeof e&&e.startsWith(dt)&&e.length>2;function yt(e){return Object.prototype.hasOwnProperty.call(ft,e)?ft[e]:$t(e)?bt:void 0}const bt=mt(ht),wt=e=>yt(e)?.prec;function xt(e,t,r){if("mod"===e&&t)return wt(t)<=70;if("mod"===t&&["*","/"].includes(e))return!0;if("mod"===t&&["+","-","±"].includes(e))return"right"===r;const n=wt(e),o=wt(t);if(!n||!o)return!1;if(o!==n)return o<n;const s=yt(e).assoc;return"left"===s?"right"===r:"right"===s&&"left"===r}const vt={alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω"};function _t(e,t,r){const n=e=>"symbol"===e.type?e.value===t?r:e:"op"!==e.type||["der","int","lim","\\sumidx","\\prodidx","evaluated","setbuilder"].includes(e.op)&&function(e,t){if("setbuilder"===e.op){const r=e.args[0];return("symbol"===r.type?r.value:r.args?.[0]?.value)===t}const r=e.args[1];return"symbol"===r?.type?r.value===t:"op"===r?.type&&["=","→"].includes(r.op)&&"symbol"===r.args[0]?.type&&r.args[0].value===t}(e,t)?e:{...e,id:void 0,args:e.args.map(n)};return n(e)}function Et(e){if("*"!==e.op)return!1;const[t,r]=e.args;return"number"===t.type&&"-1"===t.value&&"-1"!==function(e){for(;"op"===e.type&&e.args.length;)e=e.args[0];return"op"===e.type?"":e.value}(r)}function At(e,t){if("number"!==e.type||!/^\d+$/.test(e.value))return NaN;const r=Number(e.value);return r<t?r:NaN}const zt=new Set(["<",">","≤","≥","=","===","≠","≠=","&","|","\\not","\\xor","\\nand","\\nor","\\implies","\\iff","∈","∉","≈","≡"]);function Mt(e){return"op"===e.type&&(!!("="===e.op&&(t=e.args[1],"op"===t.type&&zt.has(t.op)||"symbol"===t.type&&("true"===t.value||"false"===t.value)))||e.args.some(Mt));var t}const kt=new Set(["<",">","≤","≥","=","≠"]);function Ot(e){if("op"!==e.type||!kt.has(e.op)||2!==e.args.length)return null;const[t,r]=e.args;if("op"!==t.type||!kt.has(t.op)||2!==t.args.length)return null;return{type:"op",op:"&",args:[Ot(t)??t,{type:"op",op:e.op,args:[t.args[1],r]}]}}for(const e of[vt])Object.setPrototypeOf(e,null);const jt={pmatrix:["(",")"],bmatrix:["[","]"],vmatrix:["|","|"]};function St(e){if(!e||"op"!==e.type)return null;if(Object.prototype.hasOwnProperty.call(jt,e.op))return e.args.map(e=>"op"===e.type&&"[]"===e.op?e.args:[e]);if("[]"!==e.op||!e.args.length||!e.args.every(e=>"op"===e.type&&"[]"===e.op))return null;const t=e.args[0].args.length;return!t||!e.args.every(e=>e.args.length===t)||e.args.length<2&&t<2?null:e.args.map(e=>e.args)}const Nt=Object.keys(c).filter(e=>100===c[e]&&/^[a-z]{2,}$/.test(e)),It=["frac"],Tt=[...Object.keys(vt),"pi","tau","inf","infinity","exp"],Rt="\n cost costs coast cosine cosines cosy sine sines since sincere sinus single\n tank tanks tango stand stank\n point points print prints paint paints pint pints mint hint hints lint tint saint faint joint into\n spin spine pipe pipes pine pines pick picks pink pity pie pies pilot pivot pixel pizza piano\n order orders under wonder border render older elder ladder cider rider wider bidder\n logic logo logs blog clog login slog\n model models mode modes modal modest modern module modules\n limb limbs slim lime limo limit limits climb\n maxi minute minutes mince mind mine mines\n sums sumo summit rounds floors ceils means meant sect sects secs expo kiln\n meta metal metals taxi must mute muse nut nuts\n".trim().split(/\s+/),Ct=new Set([...Tt,...Rt,"simplify","expand","factor","cancel","diff","integrate","solve","approx","limit","true","false","null","undefined","unchanged","deg","mod","pmod","NaN","Infinity"]),Ft=/^[a-zA-ZͰ-Ͽ]$/,qt=new Set(["f","g","h","u","v","F","G","H"]),Pt=e=>Nt.includes(e)||It.includes(e),Ut=[...Nt,...It,...Tt].sort((e,t)=>t.length-e.length),Lt=[...Nt,...It,"pi"].sort((e,t)=>t.length-e.length);function Dt(e,t=Ut){const r=[];let n=0;for(;n<e.length;){const o=t.find(t=>e.startsWith(t,n))??e[n];r.push(o),n+=o.length}return r}function Bt(e){if(Pt(e))return!0;const t=Dt(e,Lt);return t.length>1&&Pt(t[t.length-1])&&!Ct.has(e)}function Zt(e,{mode:t="plain",followed:r=!0}={}){if(e.includes("′")&&/^[a-zA-Z′]+$/.test(e)&&!/^.′+$/.test(e))return e.match(/[a-zA-Z]′*/g);if(!((n=e).length>0&&[...n].every(e=>Ft.test(e)))||1===e.length||Ct.has(e)||Pt(e))return[e];var n;if("Δ"===e[0]&&2===e.length)return[e];if("latex"===t)return Gt(Dt(e),r);if(e.length<=2)return[...e];const o=Gt(Dt(e,Lt),r),s=o.findIndex(e=>e.length>1);if(s<0)return[e];if("pi"===o[s]&&!o.some(e=>Nt.includes(e)))return 3===e.length?o:[e];const a=s;let i=0,l=0;for(const e of o.slice(s))i=1===e.length?i+1:0,l=Math.max(l,i);return a<=1&&l<=2?o:[e]}function Gt(e,t){const r=e[e.length-1];return t||!Nt.includes(r)?e:[...e.slice(0,-1),...r]}const Wt="§",Ht=/[A-Za-zͰ-Ͽ′]/,Xt=e=>/^[A-Za-zͰ-Ͽ][A-Za-zͰ-Ͽ′]*$/.test(e);function Vt(e,t="plain"){if("string"!=typeof e)throw new Error("Tokenizer input must be a string");const r=[];let n="";const o=e=>{n&&(Xt(n)?r.push(...function(e,t,r){if((e=>ae.test(e))(e))return[e];if(h.includes(t))return function(e,t){if(/^[a-zA-Z]′+$/.test(e))return[dt+e];if("if"===e.toLowerCase())return["\\:if"];if(1===e.length)return qt.has(e)?[dt+e]:[e];if(u(e))return[e];const r=Zt(e,{mode:t,followed:!0});return r.length>1?r:e.length<=2?[...e]:[dt+e]}(e,r);const n=void 0!==t&&!/[+\-*/=<>),\]}|!≤≥≠]/.test(t);return Zt(e,{mode:r,followed:n})}(n,e,t)):r.push(n),n="")};for(let t=0;t<e.length;t++){const s=e[t];if(s===Wt){o(s);const n=e.indexOf(Wt,t+1);if(n<0)throw new Error(`An unmatched ${Wt}`);const a=e.slice(t,n+1);r.push(h.includes(e[n+1])?dt+a:a),t=n;continue}if("ⅆ"===s&&/[A-Za-z\u0370-\u03FF]/.test(e[t+1]??""))n&&o(s),n="",r.push("d"+e[t+1]),t+=1;else{if(Xt(n)&&/[0-9]/.test(s)&&u(n+s)){const{op:o,end:a}=Yt(e,t,n+s);r.push(o),n="",t=a;continue}if(Ht.test(s)&&"′"!==s&&m(n)&&(r.push(n),n=""),Ht.test(s)&&(""===n?"′"!==s:Xt(n)))n+=s;else if(/[0-9]/.test(s)&&Xt(n)&&!Bt(n))n+=s;else if(Xt(n)&&o(" "===s?e[t+1]:s),"(){}[]".includes(s))n&&r.push(...Jt(n,s)),n="",r.push(s);else if("_"!==s&&" "!==s){if(u(n+s)){const{op:o,end:a}=Yt(e,t,n+s);r.push(o),n="",t=a;continue}if(u(s)){o(s);const{op:n,end:a}=Yt(e,t,s);r.push(n),t=a;continue}n+=s}else o(e[t+1]),"_"===s&&r.push("_")}}if(o(void 0),r.some(e=>/^:/.test(e)))throw new Error("Unmatched ':'");return r}function Yt(e,t,r){let n=t;for(;n+1<e.length&&u(r+e[n+1]);)r+=e[n+1],n++;return"!"===r&&"_"===e[n+1]&&n++,{op:r,end:n}}function Jt(e,t){if(!h.includes(t))return[e];if("\\"===e[0]){const t=e.slice(1);return[u(t)?t:dt+t]}return m(e)?[e,"*"]:u(e)||Pt(e)||m(e[0])?[e]:[dt+e]}const Kt=70,Qt=100,er="%mod",tr=/^d[A-Za-z\u0370-\u03FF]$/,rr=e=>h.includes(e),nr=e=>f.includes(e),or=e=>$t(e)||c[e]===Qt&&"_"!==e,sr=new Set(["\\comb","\\perm","comb","perm"]),ar={frac:"/","\\binom":"\\binom"},ir=new Set(["<",">","≤","≥","=","==","===","≠","≠=","!=","!==","&","|","\\not","\\xor","\\implies","\\iff","∈","∉","true","false"]),lr={"\\comb":"comb","\\perm":"perm",deg:"°","π":"pi","∨":"|"};class cr{constructor(e){this.tokens=e,this.pos=0,this.out=[],this.absDepth=0,this.frames=[]}peek(e=0){return this.tokens[this.pos+e]}next(){return this.tokens[this.pos++]}emit(...e){this.out.push(...e)}parseAll(){if(!this.tokens.length)throw new Error("Empty expression");this.parseExpression(0);const e=this.peek();if(void 0!==e)throw new Error(nr(e)?`Unmatched '${e}'`:`Unexpected '${e}'`);return this.out}parseExpression(e,t=!1){this.parseOperand(),this.absorb(e,t)}absorb(e,t=!1){for(;;){const r=this.peek();if(void 0===r||nr(r))return;const n=this.operatorAt(r,t);if(!n||n.lbp<=e)return;n.run()}}operatorAt(e,t){if("|"===e)return this.pipe();if(","===e)return{lbp:5,run:()=>{this.next(),this.frames.length&&(this.frames[this.frames.length-1].comma=!0),this.parseExpression(5),this.emit(",")}};if("?"===e)return{lbp:9,run:()=>this.ternary()};if("mod"===e)return{lbp:c.mod,run:()=>this.modulo()};if(e===er)return{lbp:Kt,run:()=>{this.next(),this.parseExpression(Kt),this.emit("mod")}};if("pmod"===e)return{lbp:c.pmod,run:()=>{this.next(),this.parseScript(),this.emit("pmod")}};if("?:"===e)return{lbp:10,run:()=>{throw new Error("Unmatched ':'")}};if("!"===e)return{lbp:90,run:()=>{this.next(),this.emit("!")}};if("_"===e)return{lbp:Qt,run:()=>{this.next(),this.parseScript(),this.emit("_")}};if(sr.has(e))return{lbp:Qt,run:()=>{this.next(),this.parseExpression(Qt),this.emit(e)}};const r=c[e];if("="===e&&void 0!==r)return{lbp:r,run:()=>this.equals(r)};if(void 0!==r&&!or(e)&&"\\not"!==e&&!(e in ar)){const t=p.has(e)?r-1:r;return{lbp:r,run:()=>{this.next(),this.parseExpression(t),this.emit(e)}}}return this.startsOperand(e)?this.implicit(e,t):null}implicit(e,t){return{lbp:!t||or(e)||tr.test(e)?Kt:71,run:()=>{this.parseExpression(Kt),this.emit("*")}}}startsOperand(e){return void 0===e||nr(e)||"|"===e?"|"===e:e!==er&&(!!(rr(e)||or(e)||e in ar)||!u(e))}pipe(){if(this.absDepth>0)return null;let e=0;for(let t=this.pos;t<this.tokens.length;t++)"|"===this.tokens[t]&&e++;const t="|"===this.peek(1);return e%2==0&&!t&&this.startsOperand(this.peek(1))?this.implicit("|",!1):{lbp:c["|"],run:()=>{this.next(),t&&e%2==0&&this.next(),this.parseExpression(c["|"]),this.emit("|")}}}modulo(){this.next(),this.parseExpression(Kt,!0),this.emit("mod")}equals(e){this.next(),this.parseExpression(e),ir.has(this.out[this.out.length-1])&&this.questionAhead()&&this.absorb(8),this.emit("=")}questionAhead(){let e=0;for(let t=this.pos;t<this.tokens.length;t++){const r=this.tokens[t];if(rr(r))e++;else if(nr(r)){if(0===e--)return!1}else{if(0===e&&","===r)return!1;if(0===e&&"?"===r)return!0}}return!1}ternary(){if(this.next(),this.parseExpression(10),"?:"!==this.next())throw new Error("Unmatched '?'");this.parseExpression(8),this.emit("?:")}parseOperand(){const e=this.next(),t=this.tokens[this.pos-2],r=this.peek();if(void 0===e)throw new Error("An operator is missing an operand at the end");if(rr(e))return this.bracket(e,"{"===e&&("∈"===t||"∉"===t));if("|"===e)return this.absolute();if("-"===e||"+"===e){return"^"===t&&(void 0===r||nr(r))||rr(t)&&nr(r)?this.emit("\\"+e):"+"===e?this.parseExpression(75):this.negate()}if("±"===e)return this.parseExpression(75),this.emit("pm");if("!"===e||"\\not"===e)return this.parseExpression(85),this.emit("\\not");if(e in ar)return this.parseScript(),this.parseScript(),this.emit(ar[e]);if("log"===e)return this.logarithm();if("lim"===e&&"_"===r)return this.limit();if(("\\sumidx"===e||"\\prodidx"===e)&&"_"===r)return this.bigOperator(e);if(or(e))return this.functionCall(e);if(e===er)throw new Error("'%' is missing an operand");if(nr(e)||u(e))throw new Error(`'${e}' is missing an operand`);this.emit(e)}negate(){const e=this.out.length;this.parseExpression(75);const t=this.out.slice(e);1!==t.length||!m(t[0])&&"∞"!==t[0]?this.emit("neg"):this.out[e]="-"+t[0]}bracket(e,t=!1){if(nr(this.peek()))return void this.emit("∅",e+this.next());this.frames.push({comma:!1}),this.parseExpression(0);const{comma:r}=this.frames.pop(),n=this.peek();nr(n)&&(this.next(),r?this.emit(e+n):t&&this.emit("{}"))}absolute(){this.absDepth++,this.parseExpression(0),this.absDepth--,"|"===this.peek()&&this.next(),this.emit("abs")}parseScript(){const e=this.peek();if(rr(e))return this.parseOperand();if("-"===e||"+"===e)return this.parseOperand();if(or(e))return this.parseOperand();if(this.next(),void 0===e||nr(e)||u(e))throw new Error("Missing a sub- or superscript");this.emit(e)}logarithm(){"_"===this.peek()?(this.next(),this.parseScript()):this.emit("e"),this.argument(),this.emit("log")}limit(){this.next();const e=this.out.length;this.parseScript();const t=this.out.splice(e);this.parseExpression(c["+"],!0),this.emit(...t,",","()","lim")}bigOperator(e){this.next();const t=this.out.length;this.parseScript();let r=this.out.splice(t);"^"===this.peek()&&(this.next(),this.parseScript(),r=[...r,...this.out.splice(t),","]),this.parseExpression(c["+"],!0),this.emit(...r,",","()",e)}functionCall(e){if(void 0===this.peek())return this.emit(e);let t=null;if("^"===this.peek()){this.next();const e=this.out.length;this.parseScript(),t=this.out.splice(e)}if(0===yt(e)?.arity&&!rr(this.peek()))return this.emit(e);this.argument(),this.emit(e),t&&this.emit(...t,"^")}argument(){const e=this.peek();if(rr(e))return this.next(),this.bracket(e);this.parseExpression(Kt,!0)}}function ur(e,t){e=function(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r],o=e=>"string"==typeof e&&/^[a-zA-Z]$/.test(e);if(qt.has(n)&&"^ { - 1 } ("===e.slice(r+1,r+7).join(" ")){t.push(dt+n+"⁻¹"),r+=5;continue}const[s,a,i]=e.slice(r+1,r+4),l=o(a)?a!==n:m(a);o(n)&&"e"!==n&&"("===s&&l&&")"===i?t.push(dt+n):t.push(n)}return t}(e);const r=[];for(const n of e)u(n)||rr(n)||nr(n)||"_"===n||$t(n)||m(n)?r.push(n):r.push(...pr(n,t));return r}function pr(e,t){if("%"===e)return[er];if(!e.includes("%"))return hr(e,t);const r=e.split("%");r.length>1&&""===r[r.length-1]&&(r.pop(),r[r.length-1]+="%");const n=[];return r.forEach((e,r)=>{r>0&&n.push(er),""!==e&&n.push(...hr(e,t))}),n}function hr(e,t){let r=0;for(;r<e.length&&m(e.slice(0,r+1));)r++;if(0===r||r===e.length)return[e];const n=e.slice(r);return"%"===n?[e]:[e.slice(0,r),...(o=n,ur(Vt(o,t),t))];var o}for(const e of[ar,lr])Object.setPrototypeOf(e,null);const fr=e=>({type:"number",value:String(e)}),mr=e=>({type:"symbol",value:e}),gr=(e,t)=>({type:"op",op:e,args:t}),dr=['"',"'","`"];function $r(e){return m(e,!0)?fr(e):dr.includes(e[0])?{type:"string",value:e}:mr(e)}const yr={"0-":"neg",sqrtpow:"root",pow:"^","==":"=","!==":"≠="};function br(e,t,r=null){t(e,r),"op"===e.type&&e.args.forEach(r=>br(r,t,e))}function wr(e){let t="";return br(e,e=>{!t&&"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value)&&(t=e.value)}),t}for(const e of[yr])Object.setPrototypeOf(e,null);const xr=new Set(["()","[]","{}","(]","[)"]),vr={pow:"^",sqrtpow:"root","\\binom":"comb","\\comb":"comb","\\perm":"perm",frac:"/","==":"=","!==":"≠=",...Object.fromEntries(Object.keys(i).map(e=>[e,"*"]))},_r=new Set(["round","fixed","der"]),Er=e=>$t(e)||100===c[e];function Ar(e){const t=[],r=e=>{if(!t.length)throw new Error(`'${e}' is missing an operand`);return t.pop()},n=e=>e.list?e.list:[e],o=(e,t)=>{if(e.list)throw new Error(`A list of values needs brackets around it (near '${t}')`);return e};if(e.forEach((s,a)=>{if("∅"===s)return void t.push({list:[]});if(","===s){const e=r(s),o=r(s);return void t.push({list:[...n(o),...n(e)]})}if(xr.has(s)){const o=n(r(s));if(!o.length&&"{}"!==s&&!Er(e[a+1]))throw new Error("Empty brackets");return void t.push(gr(s,o))}const l=vr[s]??s,c=yt(l);if(!c){if("?"===s||"abs("===s)throw new Error(`Unmatched '${s[0]}'`);return void t.push($r(s))}let u;if(Er(s)&&xr.has(e[a-1])&&t[t.length-1]?.op===e[a-1])u=t.pop().args;else{let e=c.arity===ht||_r.has(l)?1:c.arity;if(t.length<e)throw new Error(`'${s}' needs ${e} operand${1===e?"":"s"}`);u=t.splice(t.length-e,e).map(e=>o(e,s))}const p=function(e,t){switch(e){case"sqrt":if(2===t.length)return gr("root",t);break;case"round":if(1===t.length)return gr("round",[t[0],fr(0)]);break;case"sum":case"prod":{const r=t[1];if("op"===r?.type&&"symbol"===r.args[0]?.type&&(3===t.length&&"="===r.op||2===t.length&&"∈"===r.op))return gr("sum"===e?"\\sumidx":"\\prodidx",t);break}case"evaluated":if(3===t.length)return gr("evaluated",[t[0],mr(wr(t[0])||"x"),t[1],t[2]]);break;case"det":if(t.length>1&&t.every(e=>"op"===e.type&&"[]"===e.op))return gr("det",[gr("[]",t)]);break;case"fixed":if(1===t.length)return gr("fixed",[t[0],fr(2)]);break;case"der":if(1===t.length)return gr("der",[t[0],mr("x")]);if(3===t.length)return function([e,t,r]){const n="number"===r.type?Number(r.value):NaN;if(!Number.isInteger(n)||n<1||n>20)throw new Error("der(f, x, n) needs n to be a whole number from 1 to 20");const o="op"===t.type&&"="===t.op?t:null,s=o?o.args[0]:t;let a=e;for(let e=0;e<n;e++)a=gr("der",[a,o&&e===n-1?o:s]);return a}(t);break;case"log":if(2===t.length&&"symbol"===t[0].type&&"e"===t[0].value)return gr("ln",[t[1]]);break;case"lim":return Mr(e,t),gr("lim",function(e){const t=e=>{if("op"!==e.type)return null;if("^"===e.op&&"symbol"===e.args[1].type&&zr[e.args[1].value])return{point:e.args[0],side:zr[e.args[1].value]};const r=e.args.length?t(e.args[e.args.length-1]):null;return r&&{point:{...e,args:[...e.args.slice(0,-1),r.point]},side:r.side}},[r,n,o]=e;if(2===e.length&&"op"===n.type&&"→"===n.op){const[e,o]=n.args,s=t(o);if(s)return[r,e,s.point,mr(s.side)]}const s=3===e.length&&t(o);return s?[r,n,s.point,mr(s.side)]:e}(t));case"\\:if":if(2===t.length||3===t.length)return gr("?:",[t[0],t[1],t[2]??mr("unchanged")]);throw new Error("if() takes a condition, a value, and optionally an alternative")}return Mr(e,t),gr(e,t)}(l,u);i[s]&&"*"===p.op&&(p.written=i[s]),t.push(p)}),1!==t.length)throw new Error(t.length?"Some values are not connected by an operator":"Empty expression");const s=["=","<",">","≤","≥","≠","≈","≡","∈","∉"],a=t[0];return a.list&&a.list.length>1&&a.list.every(e=>"op"===e.type&&s.includes(e.op))?a.list.reduce((e,t)=>gr("&",[e,t])):o(t[0],"end")}const zr={"\\+":"r","\\-":"l"};function Mr(e,t){const{arity:r}=yt(e);if(r!==ht){if(t.length!==r){throw new Error(`'${e}' takes ${r} argument${1===r?"":"s"}, not ${t.length}`)}}else if(0===t.length&&!$t(e))throw new Error(`'${e}' needs at least one argument`)}for(const e of[vr,zr])Object.setPrototypeOf(e,null);const kr=new RegExp(`[${Object.keys(i).join("")}]`,"g"),Or=e=>e.replace(kr,"*"),jr=/\\(?:text|textrm|textit|mathrm|mathit|operatorname)\{\s*([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\s*\}/g;const Sr=e=>/^[a-z][a-z0-9]*$/.test(e)&&u(e);function Nr(e){return e.includes("\\")?(e=function(e){return e=k(e),e=x(e),e=e.replace(/\\(?:[Bb]igg?)[lrm]?(?![A-Za-z])\s*/g,""),e=e.replace(/\^\s*(?:\\circ\b|\{\s*\\circ\s*\})|\\degree\b|\\textdegree\b/g,"°"),e=e.replace(/\\(?:cdots|ldots|dotsb|dotsc|dots)(?![A-Za-z])/g,"⋯"),e=e.replace(/(\d*)\.(\d*)\\overline\s*\{\s*(\d+)\s*\}/g,(e,t,r,n)=>`${t||"0"}.${r}${n}${n}..`),e=e.replace(/\\(?:emptyset|varnothing)(?![A-Za-z])/g,"\\{\\}"),e=e.replace(/\(\s*([A-Za-z])\s*\\circ\s*([A-Za-z])\s*\)\s*\(([^()]*)\)/g,"$1($2($3))"),e}(e=function(e){for(let t=0;t<50;t++){const t=e.lastIndexOf("\\begin{cases}"),r=t<0?-1:e.indexOf("\\end{cases}",t);if(r<0)return e;const n=q(e.slice(t+13,r),"\\\\").map(e=>q(e,"&")).filter(e=>e.join("").trim());let o=null;const s=/=|<|>|\\(?:le|ge|leq|geq|neq|ne|lt|gt)(?![A-Za-z])/;if(n.length>1&&n.every(e=>1===e.length&&s.test(e[0])))o=n.map(e=>`(${e[0].trim().replace(/\s*[,;.]$/,"")})`).join(" \\land "),e=e.slice(0,t)+`(${o})`+e.slice(r+11);else{for(let e=n.length-1;e>=0;e--){const t=n[e][0].trim().replace(/\s*[,;]$/,""),r=F(n[e].slice(1).join("&"));o=null!==o||r?`((${r||"true"}) ? (${t}) : ${o??"(unchanged)"})`:`(${t})`}e=e.slice(0,t)+(o??"")+e.slice(r+11)}}return e}(e))).replace(/\{\}\^\{([^{}]*)\}\s*\\mathrm\{P\}\s*_\{([^{}]*)\}/g,"\\perm($1,$2)"):/[\]|]\s*_/.test(e)?k(e):e}function Ir(e,t={}){const r={original:e};try{if("string"!=typeof e)throw new Error("Expression must be a string");const n=t.maxLength??5e3;if(e.length>n)throw new Error(`Longer than ${n} characters (options.maxLength)`);if(e.includes(""))throw new Error("The character U+E000 can't be read: MathZetta uses it to hold § in strings");if((e=function(e,t,r){if(!e.includes(t))return e;const n=ie(e);let o="";for(let s=0;s<n.length;s++){const a=n[s];if('"'===a||"`"===a||"'"===a){const a=le(n,s);o+=e.slice(s,a+1).replaceAll(t,r),s=a}else o+=e[s]}return o}(e,Wt,"")).includes(Wt))throw new Error(`The character ${Wt} can't be read: MathZetta uses it to mark names`);const o=/^\s*=(?!=)/.test(e);o&&(e=e.replace(/("(?:[^"]|"")*")|\$(?=[A-Za-z]{0,3}\d|[A-Za-z]{1,3}\$?\d)/g,(e,t)=>t??""));const s=o?[...new Set(e.replace(/"(?:[^"]|"")*"/g,"").match(/(?<![\w.])[A-Za-z]{1,3}\d+(?::[A-Za-z]{1,3}\d+)?(?![\w.(])/g)??[])]:[],{text:a,protectedNames:i}=function(e,t=[],r=[]){const n=new Map,o=new Map,s=e=>{let t=o.get(e);return void 0===t&&(t=`${Wt}${n.size}${Wt}`,n.set(t,e),o.set(e,t)),t};e=e.replace(jr,(e,t)=>Sr(t.trim())?` ${t.trim()}`:s(t.trim()));for(const r of[...t].sort((e,t)=>t.length-e.length)){const t=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp(`(?<![A-Za-z_])${t}(?![A-Za-z0-9_])`,"g"),()=>s(r))}for(const t of[...r].sort((e,t)=>t.length-e.length)){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp(`(?<![A-Za-z_])${r}(?![A-Za-z0-9_])(\\s*)(\\(?)`,"g"),(e,r,n)=>s(t)+(n?" * (":r))}return{text:e,protectedNames:n}}(Nr(e),t.names,[...t.values??[],...s]),l=(e=>/\\[A-Za-z]/.test(e)?"latex":"plain")(a),{cleaned:c,stringMap:u,steps:p}=function(e,t={}){const r=void 0===t.blocks?null:t.blocks;return lt(e,{evaluate:r?e=>r(e,t.scope):void 0})}(a,{blocks:t.blocks,scope:t.scope}),h=e=>ue(ue(e,u),i).map(e=>"string"==typeof e?e.replaceAll("",Wt):e);r.mode=l,r.cleaned=Or(h([c])[0]),r.cleanSteps=p.map(([e,t])=>[e,Or(t)]);const f=Vt(c,l);r.tokens=f.map(Or);const m=h(function(e,t="plain"){return new cr(ur(e,t)).parseAll().map(e=>lr[e]??e)}(f,l));r.rawPostfix=m.map(Or);const g={},d=function(e,t){const r=[];return function e(n){"op"===n.type?(n.args.forEach(e),yt(n.op)?.arity===ht&&r.push(String(n.args.length)),t&&n.written&&(t[r.length]=n.written),r.push(n.op)):r.push(n.value)}(e),r}(Ar(m),g);r.postfix=d,r.written=g,r.tree=function(e){if(!Array.isArray(e)||0===e.length)throw new Error("Empty postfix");const t=[],r=[];if(e.forEach((e,n)=>{const o=yr[e]??String(e),s=yt(o);if(!s)return t.push({...$r(o),id:n}),void r.push(1);let a=s.arity;if(a===ht){const e=t.pop();if(r.pop(),a=e&&"number"===e.type?Number(e.value):NaN,!Number.isInteger(a)||a<0)throw new Error(`'${o}' takes a variable number of arguments, so it must follow a count`);if(0===a&&!s.group&&!$t(o))throw new Error(`'${o}' needs at least one argument`)}if(t.length<a)throw new Error(`'${o}' needs ${a} operand${1===a?"":"s"}`);const i=1+Math.max(0,...r.splice(r.length-a,a));if(i>1e3)throw new Error("Nested too deeply (more than 1000 levels)");r.push(i),t.push({...gr(o,t.splice(t.length-a,a)),id:n})}),1!==t.length)throw new Error(`Postfix leaves ${t.length} values instead of 1`);return t[0]}(d),Object.keys(g).length&&br(r.tree,e=>{g[e.id]&&(e.written=g[e.id])})}catch(e){r.error=e instanceof RangeError?"Nested too deeply":e.message}return r}function Tr(e,t={}){const r=Ir(e,t);if(r.error)throw new Error(`Failed to parse expression "${n=e,"string"==typeof n&&n.length>80?`${n.slice(0,77)}…`:n}": ${r.error}`);var n;return r.tree}function Rr(e,t={}){const r=300===t.version,n=new Map,o=e=>{let s=n.get(e);if(void 0===s&&"op"===e.type&&"setbuilder"===e.op)throw new Error("No GLSL for a set described by a condition (only a test of membership in one)");const a=void 0===s?function(e){if("op"!==e.type||"∈"!==e.op&&"∉"!==e.op)return null;const[t,r]=e.args;if("op"!==r.type||"setbuilder"!==r.op)return null;let[n,o]=r.args,s=null;if("op"===n.type&&"∈"===n.op&&"symbol"===n.args[0].type&&([n,s]=n.args),"symbol"!==n.type)return null;const a=_t(o,n.value,t),i=s?{type:"op",op:"&",args:[{type:"op",op:"∈",args:[t,s]},a]}:a;return"∉"===e.op?{type:"op",op:"\\not",args:[i]}:i}(e):null;return a&&n.set(e,s=`(${o(a)})`),void 0===s&&n.set(e,s=function(e){if(e.length>1e6)throw new Error("The output would be too long");return e}("op"===e.type?Vr(e,o,r,t.filter):function(e){const t=e.value;if("number"===e.type)return qr(t);const r="symbol"===e.type&&function(e){const t="string"==typeof e&&/^(-?)(\d*)(?:\.(\d*))?%$/.exec(e);if(!t||!t[2]&&!t[3])return null;const r=(t[2]||"0").padStart(3,"0")+(t[3]??""),n=r.length-(t[3]??"").length-2,o=`${r.slice(0,n).replace(/^0+(?=\d)/,"")}.${r.slice(n)}`.replace(/\.?0+$/,"");return t[1]+(""===o?"0":o)}(t);if(r)return qr(r);if("string"===e.type)throw new Error("No GLSL for text: a shader has numbers and vectors only");if("⋯"===t)throw new Error('No GLSL for ⋯: a sum written out with "and so on" has no value to work out (write it with ∑)');return void 0!==Fr[t]?Fr[t]:"\\+"===t||"\\-"===t?t[1]:Ur(t)}(e))),s};return o(e)}const Cr="3.141592653589793",Fr={pi:Cr,"π":Cr,e:"2.718281828459045",tau:"6.283185307179586","τ":"6.283185307179586","∞":"MZ_INFINITY","-∞":"(-MZ_INFINITY)",true:"true",false:"false"};function qr(e){let t=e.endsWith("..")?function(e){const t=function(e){const t=/^(-?)(\d*)\.(\d+)\.\.$/.exec(e);if(!t)return null;const[,r,n,o]=t;let s=1;for(let e=1;2*e<=o.length;e++)if(o.slice(-e)===o.slice(-2*e,-e)){s=e;break}const a=o.slice(-s);let i=o;for(;i.endsWith(a);)i=i.slice(0,-s);return{sign:r,whole:n||"0",prefix:i,block:a}}(e);if(!t)return e.replace(/\.+$/,"");const{sign:r,whole:n,prefix:o,block:s}=t;return`${r}${n}.${(o+s.repeat(Math.ceil(20/s.length)+1)).slice(0,Math.max(o.length+s.length,17))}`}(e):e.replace(/\.+$/,"");return t.startsWith(".")&&(t="0"+t),t.startsWith("-.")&&(t="-0"+t.slice(1)),t.includes(".")||(t+=".0"),t}const Pr={"α":"alpha","β":"beta","γ":"gamma","δ":"delta","ε":"epsilon","ζ":"zeta","η":"eta","θ":"theta","ι":"iota","κ":"kappa","λ":"lambda","μ":"mu","ν":"nu","ξ":"xi","ρ":"rho","σ":"sigma","φ":"phi","χ":"chi","ψ":"psi","ω":"omega","Δ":"delta_","Σ":"sigma","Ω":"omega","Φ":"phi","Θ":"theta"},Ur=e=>e.replace(/′/g,"_prime").replace("⁻¹","_inverse").replace(/[^\x00-\x7F]/g,e=>Pr[e]??`_u${e.codePointAt(0).toString(16)}`).replace(/[^A-Za-z0-9_]/g,"_"),Lr={sqrt:"sqrt",abs:"abs",floor:"floor",ceil:"ceil",ln:"log",det:"determinant",sin:"sin",cos:"cos",tan:"tan",arcsin:"asin",arccos:"acos",arctan:"atan",atan2:"atan"},Dr={sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",round:"round"},Br={csc:"sin",sec:"cos",cot:"tan"},Zr={"=":"==","===":"==","≠":"!=","≠=":"!=","<":"<",">":">","≤":"<=","≥":">="},Gr=new Set(["&","|","\\xor","\\nand","\\nor","\\implies","\\iff","?:","mean","log","≈","∈","∉"]);function Wr(e){return"op"!==e.type?null:["!","perm"].includes(e.op)?"*":["comb","csc","sec","cot"].includes(e.op)?"/":"^"===e.op?function(e){const t=Xr(e.args[1]);return 1===t?Wr(e.args[0]):null!==t&&t<0&&t>=-4?"/":null}(e):Gr.has(e.op)?null:function(e){return"op"!==e.type||yt(e.op)?.group?null:"sum"===e.op?"+":"prod"===e.op?"*":Et(e)?"neg":e.op}(e)}const Hr=e=>Math.abs(e)>6?`1.0e${e}`:qr(String(10**e));function Xr(e){return"number"===e.type&&/^-?\d+$/.test(e.value)?Number(e.value):null}function Vr(e,t,r,n=!1){e=function(e,t){if(!["\\sumidx","\\prodidx"].includes(e.op)||3!==e.args.length)return e;const[r,n,o]=e.args;if("op"===n.type&&"="===n.op)return e;const s=t(r);return s?{...e,args:[r,{type:"op",op:"=",args:[{type:"symbol",value:s},n]},o]}:e}(e,wr);const o=Ot(e);if(o)return t(o);const{op:s,args:a}=e,[i,l]=a,c=(e,r,n=s)=>xt(n,Wr(e),r)?`(${t(e)})`:t(e),u=()=>a.map(t).join(", "),p=e=>`${c(i,"left")} ${e} ${c(l,"right")}`,h=e=>{const r=Wr(e),n=!!r&&xt("neg",r,"right"),o=t(e);return n||o.startsWith("-")||"op"===e.type&&["neg","pm"].includes(e.op)?`(${o})`:o};if("det"===s&&i&&St(i))return Vr({...e,op:"vmatrix",args:i.args},t,r,n);const f=function(e){if("op"!==e.type||!["arcsec","arccsc","arccot"].includes(e.op))return null;const[t]=e.args,r={type:"op",op:"/",args:[{type:"number",value:"1"},t]};return"arcsec"===e.op?{type:"op",op:"arccos",args:[r]}:"arccsc"===e.op?{type:"op",op:"arcsin",args:[r]}:{type:"op",op:"-",args:[{type:"op",op:"/",args:[{type:"symbol",value:"pi"},{type:"number",value:"2"}]},{type:"op",op:"arctan",args:[t]}]}}(e)??function(e){if("op"!==e.type||"evaluated"!==e.op)return null;const[t,r,n,o]=e.args;return{type:"op",op:"-",args:[_t(t,r.value,o),_t(t,r.value,n)]}}(e);if(f)return`(${t(f)})`;if(Lr[s])return`${Lr[s]}(${u()})`;if(Dr[s]&&"round"!==s)return`${r?Dr[s]:"mz_"+Dr[s]}(${u()})`;if(Br[s])return`1.0 / ${Br[s]}(${t(i)})`;if(Zr[s])return p(Zr[s]);if($t(s))return`${Ur((e=>e.slice(2))(s))}(${u()})`;switch(s){case"+":case"-":case"*":case"/":return"*"===s&&Et(e)?Vr({...e,op:"neg",args:[l]},t,r,n):"*"===s&&"symbol"===l.type&&"°"===l.value?`radians(${t(i)})`:p(s);case"mod":return`mod(${t(i)}, ${t(l)})`;case"^":return Yr(e,t);case"neg":return"-"+h(i);case"pm":return`vec2(${t(i)}, -${h(i)})`;case"±":return`vec2(${t(i)} + ${c(l,"right","+")}, ${t(i)} - ${c(l,"right","-")})`;case"!":{const e=At(i,13);return e<=1?"1.0":e?Array.from({length:e},(t,r)=>e-r+".0").join(" * "):`mz_factorial(${t(i)})`}case"perm":case"comb":{const e=At(i,21),r=At(l,21);if(e>=r){if(0===r)return"1.0";const t=Array.from({length:r},(t,r)=>e-r+".0").join(" * ");return"perm"===s?t:`(${t}) / (${Array.from({length:r},(e,t)=>`${t+1}.0`).join(" * ")})`}return`mz_${s}(${t(i)}, ${t(l)})`}case"root":{const e=Xr(i);return 2===e?`sqrt(${t(l)})`:3===e?`mz_cbrt(${t(l)})`:null===e||e%2!=0?`mz_root(${t(i)}, ${t(l)})`:`pow(${t(l)}, 1.0 / ${c(i,"right","/")})`}case"log":return"symbol"===i.type&&"e"===i.value?`log(${t(l)})`:"number"===i.type&&"2"===i.value?`log2(${t(l)})`:`(log(${t(l)}) / log(${t(i)}))`;case"loglog":return`log(log(${t(i)}))`;case"logloglog":return`log(log(log(${t(i)})))`;case"expm1":return`(exp(${t(i)}) - 1.0)`;case"round":case"fixed":{const e=Xr(l),r=`mz_round(${0===e||null===e?t(i):`${c(i,"left","*")} * ${Hr(e)}`})`;return 0===e||null===e?r:`${r} / ${Hr(e)}`}case"random":return"mz_random()";case"max":case"min":return 1===a.length?"op"===i.type?`(${t(i)})`:t(i):a.map(t).reduce((e,t)=>`${s}(${e}, ${t})`);case"gcd":return a.map(t).reduce((e,t)=>`mz_gcd(${e}, ${t})`);case"mean":return`((${a.map((e,t)=>c(e,t?"right":"left","+")).join(" + ")}) / ${a.length}.0)`;case"sum":return a.map((e,t)=>c(e,t?"right":"left","+")).join(" + ");case"prod":return a.map((e,t)=>c(e,t?"right":"left","*")).join(" * ");case"&":return`(${t(i)} && ${t(l)})`;case"|":return`(${t(i)} || ${t(l)})`;case"\\xor":return`(${t(i)} ^^ ${t(l)})`;case"\\nand":return`!(${t(i)} && ${t(l)})`;case"\\implies":return`(!(${t(i)}) || ${t(l)})`;case"\\iff":return`((${t(i)}) == (${t(l)}))`;case"\\nor":return`!(${t(i)} || ${t(l)})`;case"\\not":return"!"+h(i);case"?:":{const e=e=>n&&"symbol"===e.type&&"unchanged"===e.value,r=(r,n)=>e(r)&&!e(n)?`mz_unchanged(${t(n)})`:t(r);return`(${Mt(i)?`(${t(i)})`:t(i)} ? ${r(l,a[2])} : ${r(a[2],l)})`}case"≈":return`(abs(${t(i)} - ${c(l,"right","-")}) < 1e-5)`;case"≡":return p("==");case"pmod":return"op"===i.type&&["≡","="].includes(i.op)?`(mod(${t(i.args[0])} - ${c(i.args[1],"right","-")}, ${t(l)}) == 0.0)`:`mod(${t(i)}, ${t(l)})`;case"∈":case"∉":return function(e,t){const[r,n]=e.args,o=t(r),s="∉"===e.op;if("symbol"===n.type&&Jr[n.value]){const e=Jr[n.value](o);return s?`!${e}`:e}if("op"===n.type&&["()","[]","(]","[)"].includes(n.op)&&2===n.args.length){const[e,r]=n.args.map(t),a=`(${o} ${"["===n.op[0]?">=":">"} ${e} && ${o} ${"]"===n.op[1]?"<=":"<"} ${r})`;return s?`!${a}`:a}if("op"===n.type&&"{}"===n.op&&!n.args.length)return s?"true":"false";if("op"===n.type&&"{}"===n.op){const e=`(${n.args.map(e=>`${o} == ${t(e)}`).join(" || ")})`;return s?`!${e}`:e}throw new Error(`No GLSL for ∈ ${"symbol"===n.type?n.value:"this set"}: only intervals, {listed values}, ℝ, ℤ and ℕ`)}(e,t);case"pmatrix":case"bmatrix":case"vmatrix":{const r=St(e).map(e=>e.map(t)),n=r.length,o=r.every(e=>e.length===n);if("vmatrix"===s){if(!o||n>3)throw new Error("No GLSL for a determinant bigger than 3 by 3");if(1===n)return r[0][0];const e=r.map(e=>e.map(e=>`(${e})`));if(2===n)return`(${e[0][0]} * ${e[1][1]} - ${e[0][1]} * ${e[1][0]})`;const[[t,s,a],[i,l,c],[u,p,h]]=e;return`(${t} * (${l} * ${h} - ${c} * ${p}) - ${s} * (${i} * ${h} - ${c} * ${u}) + ${a} * (${i} * ${p} - ${l} * ${u}))`}if(o&&n>=2&&n<=4)return`mat${n}(${r[0].map((e,t)=>r.map(e=>e[t]).join(", ")).join(", ")})`;const a=r.flat();if((1===n||r.every(e=>1===e.length))&&a.length>=2&&a.length<=4)return`vec${a.length}(${a.join(", ")})`;throw new Error(`No GLSL for a ${n} by ${r[0].length} matrix`)}case"()":case"[]":case"{}":case"(]":case"[)":return a.length>=2&&a.length<=4?`vec${a.length}(${u()})`:`float[](${u()})`;case"→":return`${t(i)}, ${t(l)}`;case"_":return"number"===l.type&&/^\d+$/.test(l.value)?`${t(i)}_${l.value}`:"symbol"===l.type?`${t(i)}_${t(l)}`:`${t(i)}[int(${t(l)})]`}if(Kr[s])throw new Error(`No GLSL for ${Kr[s]}`);throw new Error(`No GLSL for '${s}'`)}function Yr(e,t,r){const[n,o]=e.args,s=Xr(o),a=t(n);if(0===s)return"1.0";if(1===s)return a;if(2===s)return`mz_sq(${a})`;if(3===s)return`mz_cube(${a})`;if(4===s)return`mz_sq(mz_sq(${a}))`;if(null!==s&&s<0&&s>=-4){const e=Yr({args:[n,{type:"number",value:String(-s)}]},t);return`1.0 / ${-1!==s||"op"!==n.type||function(e){const t=/^\w+\(/.exec(e)?.[0].length;if(!t)return!1;let r=0;for(let n=t-1;n<e.length;n++)if("("===e[n])r++;else if(")"===e[n]&&0===--r)return n===e.length-1;return!1}(e)?e:`(${e})`}`}return"symbol"===n.type&&"e"===n.value?`exp(${t(o)})`:"number"===n.type&&"2"===n.value?`exp2(${t(o)})`:"op"===o.type&&"/"===o.op&&"number"===o.args[0].type&&"1"===o.args[0].value&&"number"===o.args[1].type&&"2"===o.args[1].value?`sqrt(${a})`:`pow(${a}, ${t(o)})`}const Jr={"ℝ":e=>`(abs(${e}) < MZ_INFINITY)`,"ℤ":e=>`(fract(${e}) == 0.0)`,"ℕ":e=>`(fract(${e}) == 0.0 && ${e} > 0.0)`};const Kr={der:"a derivative",int:"an integral",lim:"a limit","\\sumidx":"a sum to n","\\prodidx":"a product to n","∪":"a union of sets","∩":"an intersection of sets"},Qr=["#define MZ_INFINITY (1.0 / 0.0)",...["float","vec2","vec3","vec4"].flatMap(e=>[`${e} mz_sq(${e} x) { return x * x; }`,`${e} mz_cube(${e} x) { return x * x * x; }`,`${e} mz_cbrt(${e} x) { return sign(x) * pow(abs(x), ${e}(1.0 / 3.0)); }`,`${e} mz_root(float n, ${e} x) { return mod(n, 2.0) == 1.0 ? sign(x) * pow(abs(x), ${e}(1.0 / n)) : pow(x, ${e}(1.0 / n)); }`,`${e} mz_round(${e} x) { return sign(x) * floor(abs(x) + 0.5); }`,`${e} mz_sinh(${e} x) { return (exp(x) - exp(-x)) / 2.0; }`,`${e} mz_cosh(${e} x) { return (exp(x) + exp(-x)) / 2.0; }`,`${e} mz_tanh(${e} x) { ${e} a = exp(2.0 * x); return (a - 1.0) / (a + 1.0); }`,`${e} mz_asinh(${e} x) { return log(x + sqrt(x * x + 1.0)); }`,`${e} mz_acosh(${e} x) { return log(x + sqrt(x * x - 1.0)); }`,`${e} mz_atanh(${e} x) { return 0.5 * log((1.0 + x) / (1.0 - x)); }`]),"float mz_factorial(float n) { float r = 1.0; for (int i = 2; i <= 170; i++) { if (float(i) > n) break; r *= float(i); } return r; }","float mz_perm(float n, float k) { float r = 1.0; for (int i = 0; i < 170; i++) { if (float(i) >= k) break; r *= n - float(i); } return r; }","float mz_comb(float n, float k) { return mz_perm(n, k) / mz_factorial(k); }","float mz_gcd(float a, float b) { a = abs(a); b = abs(b); for (int i = 0; i < 64; i++) { if (b == 0.0) break; float t = mod(a, b); a = b; b = t; } return a; }","float mz_seed = 0.0;","float mz_random() { mz_seed += 1.0; return fract(sin(dot(vec3(gl_FragCoord.xy, mz_seed), vec3(12.9898, 78.233, 37.719))) * 43758.5453); }"].join("\n"),en=["px","py","rgb","gray","unchanged","selected"],tn=["blur","blurx","blury","gaussian","gaussianx","gaussiany","sobel","sobelx","sobely","laplacian","sharpen","emboss","dilate","erode","convolve"],rn=["zoom","shift","rotate","crop","tile","flipx","flipy"],nn=["srgb","linear","hsv","hsl","lab","oklab","ycbcr"],on=nn.filter(e=>"srgb"!==e).flatMap(e=>[`to${e}`,`from${e}`]),sn=["pixel","red","green","blue","alpha","luma","source","selection","width","height",...tn,...rn,"fract","clamp","mix","smoothstep","step","distance","length","dot","normalize","cross","sign","exp2","log2","inversesqrt","radians","degrees",...on],an=["source","selection"];const ln=["cover","fit","stretch","tile"],cn=["red","green","blue","alpha","luma"];function un(e,t,{whole:r=!1}={}){const n=pn(e,t);return r?"symbol"===n.type&&t.has(n.value)?{...n,value:`mz_px_${n.value}`}:"op"===n.type&&n.op.startsWith(`${dt}mz_at_`)?{...n,op:n.op.replace("mz_at_","mz_sample_")}:n:n}function pn(e,t){if("op"!==e.type)return e;const r=e.args.map(e=>pn(e,t)),n=e.op.startsWith(dt)?e.op.slice(2):null,o=r.length&&"symbol"===r[0].type&&t.has(r[0].value)?r[0].value:null;if(n&&t.has(n))return{...e,op:`${dt}mz_at_${n}`,args:r};if(n&&cn.includes(n)&&1===r.length&&o)return{...e,args:[{...r[0],value:`mz_px_${o}`}]};if(n&&cn.includes(n)&&1===r.length&&"op"===r[0].type&&r[0].op.startsWith(`${dt}mz_at_`))return{...e,args:[{...r[0],op:r[0].op.replace("mz_at_","mz_sample_")}]};if(n&&rn.includes(n)){const e={type:"op",op:`${dt}mz_${n}`,args:o?r.slice(1):r};return{type:"op",op:`${dt}mz_at_${o??"image"}`,args:[e]}}return("width"===n||"height"===n)&&r.length<=1?o&&"source"!==o?{type:"op",op:`${dt}mz_${n}_${o}`,args:[]}:{type:"symbol",value:"width"===n?"w":"h"}:{...e,args:r}}const hn=[...en,...sn],fn={square:8,line:24};function mn(e){const t=(e,t)=>`\n float mz_r = min(max(ceil(${e}), 0.0), ${fn.square}.0);\n for (int i = 0; i <= ${2*fn.square}; i++) {\n float fi = float(i) - mz_r;\n if (fi > mz_r) break;\n for (int j = 0; j <= ${2*fn.square}; j++) {\n float fj = float(j) - mz_r;\n if (fj > mz_r) break;\n ${t}\n }\n }`,r=(e,t,r)=>`\n float mz_r = min(max(ceil(${t}), 0.0), ${fn.line}.0);\n for (int i = 0; i <= ${2*fn.line}; i++) {\n float fi = float(i) - mz_r;\n if (fi > mz_r) break;\n float dx = ${"x"===e?"fi":"0.0"}, dy = ${"y"===e?"fi":"0.0"};\n ${r}\n }`,n=e=>`vec3 blur${e}(float radius) {\n vec3 sum = vec3(0.0); float n = 0.0;${r(e,"radius","if (abs(fi) > radius) continue;\n sum += mz_tap(dx, dy).rgb; n += 1.0;")}\n return sum / n;\n}`,o=e=>`vec3 gaussian${e}(float sigma) {\n if (sigma <= 0.0) return mz_tap(0.0, 0.0).rgb;\n vec3 sum = vec3(0.0); float total = 0.0;${r(e,"3.0 * sigma","if (abs(fi) > 3.0 * sigma) continue;\n float w = mz_gauss(fi * fi, sigma);\n sum += w * mz_tap(dx, dy).rgb; total += w;")}\n return sum / total;\n}`;return`// ---- neighborhood: the pixels around this one (dy runs downwards, like py) ----\nvec4 mz_tap(float dx, float dy) { return ${e}(image, (gl_FragCoord.xy + vec2(dx, -dy)) / resolution); }\nfloat mz_luma_at(float dx, float dy) { return dot(mz_tap(dx, dy).rgb, vec3(0.299, 0.587, 0.114)); }\nfloat mz_gauss(float d2, float sigma) { return exp(-d2 / (2.0 * sigma * sigma)); }\nvec3 blur(float radius) {\n vec3 sum = vec3(0.0); float n = 0.0;${t("radius","if (abs(fi) > radius || abs(fj) > radius) continue;\n sum += mz_tap(fi, fj).rgb; n += 1.0;")}\n return sum / n;\n}\n${n("x")}\n${n("y")}\nvec3 gaussian(float sigma) {\n if (sigma <= 0.0) return mz_tap(0.0, 0.0).rgb;\n float limit = 3.0 * sigma;\n vec3 sum = vec3(0.0); float total = 0.0;${t("limit","if (abs(fi) > limit || abs(fj) > limit) continue;\n float w = mz_gauss(fi * fi + fj * fj, sigma);\n sum += w * mz_tap(fi, fj).rgb; total += w;")}\n return sum / total;\n}\n${o("x")}\n${o("y")}\nvec3 dilate(float radius) {\n vec3 best = vec3(0.0);${t("radius","if (abs(fi) > radius || abs(fj) > radius) continue;\n best = max(best, mz_tap(fi, fj).rgb);")}\n return best;\n}\nvec3 erode(float radius) {\n vec3 best = vec3(1.0);${t("radius","if (abs(fi) > radius || abs(fj) > radius) continue;\n best = min(best, mz_tap(fi, fj).rgb);")}\n return best;\n}\nfloat sobelx() {\n return (mz_luma_at(1.0, -1.0) + 2.0 * mz_luma_at(1.0, 0.0) + mz_luma_at(1.0, 1.0))\n - (mz_luma_at(-1.0, -1.0) + 2.0 * mz_luma_at(-1.0, 0.0) + mz_luma_at(-1.0, 1.0));\n}\nfloat sobely() {\n return (mz_luma_at(-1.0, 1.0) + 2.0 * mz_luma_at(0.0, 1.0) + mz_luma_at(1.0, 1.0))\n - (mz_luma_at(-1.0, -1.0) + 2.0 * mz_luma_at(0.0, -1.0) + mz_luma_at(1.0, -1.0));\n}\nfloat sobel() { return length(vec2(sobelx(), sobely())); }\nfloat laplacian() { return 4.0 * mz_luma_at(0.0, 0.0) - mz_luma_at(-1.0, 0.0) - mz_luma_at(1.0, 0.0) - mz_luma_at(0.0, -1.0) - mz_luma_at(0.0, 1.0); }\nfloat emboss() { return 0.5 + mz_luma_at(-1.0, -1.0) - mz_luma_at(1.0, 1.0); }\nvec3 sharpen(float amount) {\n vec3 c = mz_tap(0.0, 0.0).rgb;\n return c + amount * (4.0 * c - mz_tap(-1.0, 0.0).rgb - mz_tap(1.0, 0.0).rgb - mz_tap(0.0, -1.0).rgb - mz_tap(0.0, 1.0).rgb);\n}\nvec3 convolve(float k00, float k01, float k02, float k10, float k11, float k12, float k20, float k21, float k22) {\n return k00 * mz_tap(-1.0, -1.0).rgb + k01 * mz_tap(0.0, -1.0).rgb + k02 * mz_tap(1.0, -1.0).rgb\n + k10 * mz_tap(-1.0, 0.0).rgb + k11 * mz_tap(0.0, 0.0).rgb + k12 * mz_tap(1.0, 0.0).rgb\n + k20 * mz_tap(-1.0, 1.0).rgb + k21 * mz_tap(0.0, 1.0).rgb + k22 * mz_tap(1.0, 1.0).rgb;\n}`}function gn(e,t={}){const r=300===t.version,n=t.parse;if(!n)throw new Error("filterShader needs options.parse (use the one from src/index.js)");const o=t.space&&"srgb"!==t.space?t.space:null;if(o&&!nn.includes(o))throw new Error(`Unknown color space "${o}": ${nn.join(", ")}`);const s=Array.isArray(t.images)?Object.fromEntries(t.images.map(e=>[e,{}])):{...t.images??{}},a=Object.keys(s),i=/^[A-Za-z_][A-Za-z0-9_]*$/;for(const e of a)if(!i.test(e))throw new Error(`A picture's name must be a GLSL identifier, not ${JSON.stringify(e)}`);for(const[e,r]of Object.entries(t.uniforms??{}))if(!i.test(e)||!/^(?:float|int|bool|[biu]?vec[234]|mat[234]|sampler2D)$/.test(String(r)))throw new Error(`Uniform ${JSON.stringify(e)}: a GLSL name and type, not ${JSON.stringify(r)}`);const l=new Set([...a,...an]);let c=0;const u=(e,r=!1)=>{return Rr(un((function e(t){const r="op"===t.type?t.op.replace(/^\\:/,""):t.value;if(tn.includes(r)&&++c>24)throw new Error("At most 24 neighborhood functions (blur, gaussian, sobel …) in a filter pass");"op"===t.type&&t.args.forEach(e)}(o=n(e)),o),l,{whole:r}),{version:t.version,filter:!0});var o},p="string"==typeof e?{rgba:e}:e,h=[];p.rgba&&h.push(" mz_keep(gray, color);",` color = mz_rgba(${u(p.rgba,!0)});`),p.rgb&&h.push(" mz_keep(gray, color);",` color.rgb = mz_rgb(${u(p.rgb)});`);for(const e of["r","g","b","a"])p[e]&&h.push(` mz_keep(color.${e}, color);`,` color.${e} = mz_ch_${e}(${u(p[e])});`);if(!h.length)throw new Error("filterShader: give an expression, or an object with r, g, b, a, rgb or rgba");const f=r?"texture":"texture2D",m=Object.entries(t.uniforms??{}).map(([e,t])=>`uniform ${t} ${e};`),g=new RegExp(`\\b(${tn.join("|")})\\(`).test(h.join("\n"));!a.includes("source")&&/\b(source|mz_at_source|mz_px_source|mz_sample_source)\b/.test(h.join("\n"))&&a.push("source"),!a.includes("selection")&&/\b(selected|selection|mz_at_selection|mz_px_selection|mz_sample_selection)\b/.test(h.join("\n"))&&a.push("selection");const d=/\bmz_(zoom|shift|rotate|crop|tile|flipx|flipy|at_image|sample_image)\(/.test(h.join("\n")),$=o||new RegExp(`\\b(${on.join("|")})\\(`).test(h.join("\n")),y=e=>[`float mz_ch_${e}(float v) { return v; }`,`float mz_ch_${e}(bool v) { return v ? 1.0 : 0.0; }`,`float mz_ch_${e}(vec3 v) { return ${"a"===e?"1.0":`v.${e}`}; }`,`float mz_ch_${e}(vec4 v) { return v.${e}; }`];return[r?"#version 300 es":"","precision highp float;","uniform sampler2D image; // the frame","uniform vec2 resolution; // width, height in pixels","uniform float t; // frame index",t.blend?"uniform float mz_opacity; // how much of the result shows over the input, 0–1":"",...m,...a.map(e=>`uniform sampler2D mz_img_${e};`),...a.filter(e=>!an.includes(e)).flatMap(e=>[`uniform vec2 mz_size_${e}; // its own width and height`,`uniform vec4 mz_place_${e}; // zoom, x, y, angle`]),r?"out vec4 fragColor;":"",Qr,`vec4 pixel(float px, float py) { return ${f}(image, vec2((px + 0.5) / resolution.x, 1.0 - (py + 0.5) / resolution.y)); }`,"float red(float px, float py) { return pixel(px, py).r; }","float green(float px, float py) { return pixel(px, py).g; }","float blue(float px, float py) { return pixel(px, py).b; }","float alpha(float px, float py) { return pixel(px, py).a; }","float luma(float px, float py) { return dot(pixel(px, py).rgb, vec3(0.299, 0.587, 0.114)); }","float red(vec4 v) { return v.r; }","float red(vec3 v) { return v.r; }","float green(vec4 v) { return v.g; }","float green(vec3 v) { return v.g; }","float blue(vec4 v) { return v.b; }","float blue(vec3 v) { return v.b; }","float alpha(vec4 v) { return v.a; }","float alpha(vec3 v) { return 1.0; }","float luma(vec4 v) { return dot(v.rgb, vec3(0.299, 0.587, 0.114)); }","float luma(vec3 v) { return dot(v, vec3(0.299, 0.587, 0.114)); }","vec2 mz_p() { return vec2(gl_FragCoord.x - 0.5, resolution.y - gl_FragCoord.y - 0.5); } // (px, py)",...$?["// ---- color spaces: to<space>(c) and from<space>(c), sRGB on the other side ----","vec3 tolinear(vec3 c) { return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c)); }","vec3 fromlinear(vec3 c) { c = max(c, 0.0); return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c)); }","float mz_hue(vec3 c, float v, float d) { float h = v == c.r ? (c.g - c.b) / d : v == c.g ? 2.0 + (c.b - c.r) / d : 4.0 + (c.r - c.g) / d; return fract(h / 6.0); }","vec3 tohsv(vec3 c) { float v = max(c.r, max(c.g, c.b)); float d = v - min(c.r, min(c.g, c.b)); return vec3(d > 0.0 ? mz_hue(c, v, d) : 0.0, v > 0.0 ? d / v : 0.0, v); }","vec3 fromhsv(vec3 c) { vec3 k = abs(fract(c.x + vec3(0.0, 2.0 / 3.0, 1.0 / 3.0)) * 6.0 - 3.0); return c.z * mix(vec3(1.0), clamp(k - 1.0, 0.0, 1.0), c.y); }","vec3 tohsl(vec3 c) { float v = max(c.r, max(c.g, c.b)); float m = min(c.r, min(c.g, c.b)); float d = v - m; float l = (v + m) * 0.5; return vec3(d > 0.0 ? mz_hue(c, v, d) : 0.0, d > 0.0 ? d / (1.0 - abs(2.0 * l - 1.0)) : 0.0, l); }","vec3 fromhsl(vec3 c) { float C = (1.0 - abs(2.0 * c.z - 1.0)) * c.y; vec3 k = abs(fract(c.x + vec3(0.0, 2.0 / 3.0, 1.0 / 3.0)) * 6.0 - 3.0); return (c.z - C * 0.5) + C * clamp(k - 1.0, 0.0, 1.0); }","vec3 toycbcr(vec3 c) { float y = dot(c, vec3(0.299, 0.587, 0.114)); return vec3(y, 0.5 + (c.b - y) * 0.5643, 0.5 + (c.r - y) * 0.7132); }","vec3 fromycbcr(vec3 c) { float cb = c.y - 0.5; float cr = c.z - 0.5; return vec3(c.x + 1.402 * cr, c.x - 0.344136 * cb - 0.714136 * cr, c.x + 1.772 * cb); }","vec3 tolab(vec3 c) {"," vec3 l = tolinear(c);"," vec3 xyz = vec3(dot(l, vec3(0.4124564, 0.3575761, 0.1804375)), dot(l, vec3(0.2126729, 0.7151522, 0.0721750)), dot(l, vec3(0.0193339, 0.1191920, 0.9503041))) / vec3(0.95047, 1.0, 1.08883);"," vec3 f = mix(7.787 * xyz + 16.0 / 116.0, mz_cbrt(xyz), step(0.008856, xyz));"," return vec3((116.0 * f.y - 16.0) / 100.0, 0.5 + 500.0 * (f.x - f.y) / 256.0, 0.5 + 200.0 * (f.y - f.z) / 256.0);","}","vec3 fromlab(vec3 c) {"," float fy = (c.x * 100.0 + 16.0) / 116.0;"," vec3 f = vec3(fy + (c.y - 0.5) * 256.0 / 500.0, fy, fy - (c.z - 0.5) * 256.0 / 200.0);"," vec3 xyz = mix((f - 16.0 / 116.0) / 7.787, f * f * f, step(0.206893, f)) * vec3(0.95047, 1.0, 1.08883);"," vec3 l = vec3(dot(xyz, vec3(3.2404542, -1.5371385, -0.4985314)), dot(xyz, vec3(-0.9692660, 1.8760108, 0.0415560)), dot(xyz, vec3(0.0556434, -0.2040259, 1.0572252)));"," return fromlinear(clamp(l, 0.0, 1.0));","}","vec3 tooklab(vec3 c) {"," vec3 l = tolinear(c);"," vec3 lms = mz_cbrt(vec3(dot(l, vec3(0.4122214708, 0.5363325363, 0.0514459929)), dot(l, vec3(0.2119034982, 0.6806995451, 0.1073969566)), dot(l, vec3(0.0883024619, 0.2817188376, 0.6299787005))));"," return vec3(dot(lms, vec3(0.2104542553, 0.7936177850, -0.0040720468)), 0.5 + dot(lms, vec3(1.9779984951, -2.4285922050, 0.4505937099)), 0.5 + dot(lms, vec3(0.0259040371, 0.7827717662, -0.8086757660)));","}","vec3 fromoklab(vec3 c) {"," float A = c.y - 0.5; float B = c.z - 0.5;"," vec3 lms = vec3(c.x + 0.3963377774 * A + 0.2158037573 * B, c.x - 0.1055613458 * A - 0.0638541728 * B, c.x - 0.0894841775 * A - 1.2914855480 * B);"," lms = lms * lms * lms;"," vec3 l = vec3(dot(lms, vec3(4.0767416621, -3.3077115913, 0.2309699292)), dot(lms, vec3(-1.2684380046, 2.6097574011, -0.3413193965)), dot(lms, vec3(-0.0041960863, -0.7034186147, 1.7076147010)));"," return fromlinear(clamp(l, 0.0, 1.0));","}",...on.map(e=>`vec3 ${e}(float x, float y, float z) { return ${e}(vec3(x, y, z)); }`)]:[],...a.flatMap(e=>function(e,t,r,n=null){const o=n&&"selection"!==e,s=o?[`vec4 mz_sample_${e}(vec2 p) { vec4 v = mz_raw_${e}(p); v.rgb = to${n}(v.rgb); return v; }`]:[],a=o?`mz_raw_${e}`:`mz_sample_${e}`;if(an.includes(e))return[`vec4 ${a}(vec2 p) { vec2 q = p + 0.5; return ${r}(mz_img_${e}, vec2(q.x / resolution.x, 1.0 - q.y / resolution.y)); }`,...s,`vec3 mz_at_${e}(vec2 p) { return mz_sample_${e}(p).rgb; }`,`vec3 mz_at_${e}(float px, float py) { return mz_at_${e}(vec2(px, py)); }`];return[`vec4 ${a}(vec2 p) {`,` vec2 size = mz_size_${e};`,` vec2 scale = ${{cover:"vec2(max(resolution.x / size.x, resolution.y / size.y))",fit:"vec2(min(resolution.x / size.x, resolution.y / size.y))",stretch:"resolution / size",tile:"vec2(1.0)"}[t??"cover"]} * mz_place_${e}.x;`,` vec2 d = p + 0.5 - mz_place_${e}.yz * resolution;`,` float co = cos(mz_place_${e}.w), si = sin(mz_place_${e}.w);`," d = vec2(co * d.x + si * d.y, co * d.y - si * d.x);"," vec2 q = d / scale + size * 0.5;"," "+("tile"===t?"q = mod(q, size);":"if (q.x < 0.0 || q.y < 0.0 || q.x > size.x || q.y > size.y) return vec4(0.0);"),` return ${r}(mz_img_${e}, vec2(q.x / size.x, 1.0 - q.y / size.y));`,"}",...s,`vec3 mz_at_${e}(vec2 p) { return mz_sample_${e}(p).rgb; }`,`vec3 mz_at_${e}(float px, float py) { return mz_at_${e}(vec2(px, py)); }`,`float mz_width_${e}() { return mz_size_${e}.x; }`,`float mz_height_${e}() { return mz_size_${e}.y; }`]}(e,s[e]?.place,f,o)),...d?dn(f):[],g?mn(f):"",...y("r"),...y("g"),...y("b"),...y("a"),"vec3 mz_rgb(float v) { return vec3(v); }","vec3 mz_rgb(bool v) { return vec3(v ? 1.0 : 0.0); }","vec3 mz_rgb(vec3 v) { return v; }","vec3 mz_rgb(vec4 v) { return v.rgb; }","vec4 mz_rgba(float v) { return vec4(vec3(v), 1.0); }","vec4 mz_rgba(bool v) { return vec4(vec3(v ? 1.0 : 0.0), 1.0); }","vec4 mz_rgba(vec3 v) { return vec4(v, 1.0); }","vec4 mz_rgba(vec4 v) { return v; }","float unchanged = 0.0;","vec3 mz_unchanged_3 = vec3(0.0);","vec4 mz_unchanged_4 = vec4(0.0);","void mz_keep(float value, vec4 all) { unchanged = value; mz_unchanged_3 = all.rgb; mz_unchanged_4 = all; }","float mz_unchanged(float like) { return unchanged; }","bool mz_unchanged(bool like) { return unchanged > 0.5; }","vec3 mz_unchanged(vec3 like) { return mz_unchanged_3; }","vec4 mz_unchanged(vec4 like) { return mz_unchanged_4; }","void main() {"," float w = resolution.x;"," float h = resolution.y;"," float px = gl_FragCoord.x - 0.5;"," float py = h - gl_FragCoord.y - 0.5;"," float x = gl_FragCoord.x / w;"," float y = 1.0 - gl_FragCoord.y / h;",` vec4 c = ${f}(image, gl_FragCoord.xy / resolution);`," float r = c.r, g = c.g, b = c.b, a = c.a;"," vec3 rgb = c.rgb;",` float gray = dot(${o?`from${o}(rgb)`:"rgb"}, vec3(0.299, 0.587, 0.114)); // the brightness as seen`," vec4 color = c;"," mz_seed = t;",...a.flatMap(e=>[` vec4 mz_px_${e} = mz_sample_${e}(mz_p());`,` vec3 ${e} = mz_px_${e}.rgb;`]),a.includes("selection")?" float selected = mz_px_selection.r; // 1 inside the selection, 0 outside; 1 everywhere without one":"",...h,t.blend?" color = mix(c, color, mz_opacity);":"",` ${r?"fragColor":"gl_FragColor"} = color;`,"}"].filter(e=>""!==e).join("\n")}function dn(e){return["// ---- geometry: where to read the picture from, for this pixel ----","vec2 mz_zoom(float s, float cx, float cy) { vec2 c = vec2(cx, cy) * resolution - 0.5; return c + (mz_p() - c) / s; }","vec2 mz_zoom(float s) { return mz_zoom(s, 0.5, 0.5); }","vec2 mz_shift(float dx, float dy) { return mod(mz_p() - vec2(dx, dy) + 0.5, resolution) - 0.5; } // wraps around","vec2 mz_rotate(float a, float cx, float cy) { vec2 c = vec2(cx, cy) * resolution - 0.5; vec2 d = mz_p() - c; float co = cos(a), si = sin(a); return c + vec2(co * d.x + si * d.y, co * d.y - si * d.x); }","vec2 mz_rotate(float a) { return mz_rotate(a, 0.5, 0.5); }","vec2 mz_crop(float x0, float y0, float x1, float y1) { vec2 f = (mz_p() + 0.5) / resolution; return (vec2(x0, y0) + vec2(x1 - x0, y1 - y0) * f) * resolution - 0.5; }","vec2 mz_tile(float nx, float ny) { return mod((mz_p() + 0.5) * vec2(nx, ny), resolution) - 0.5; }","vec2 mz_tile(float n) { return mz_tile(n, n); }","vec2 mz_flipx() { vec2 p = mz_p(); return vec2(resolution.x - 1.0 - p.x, p.y); }","vec2 mz_flipy() { vec2 p = mz_p(); return vec2(p.x, resolution.y - 1.0 - p.y); }",`vec4 mz_sample_image(vec2 p) { vec2 q = p + 0.5; if (q.x < 0.0 || q.y < 0.0 || q.x > resolution.x || q.y > resolution.y) return vec4(0.0); return ${e}(image, vec2(q.x / resolution.x, 1.0 - q.y / resolution.y)); }`,"vec3 mz_at_image(vec2 p) { return mz_sample_image(p).rgb; }"]}for(const e of[Fr,Pr,Lr,Dr,Br,Zr,Jr,fn,Kr])Object.setPrototypeOf(e,null);const $n=["round","soft","marker","chalk","spray"],yn=["recorded","even","per-stroke"],bn=["pressure","speed","none"],wn=["none","inside","outside"],xn={type:"strokes",strokes:[],brush:"round",size:.03,flow:1,spacing:.2,taper:0,buildUp:!1,widthFrom:"pressure",timing:"recorded",speed:1,gap:6,start:0,fit:0,age:30,clip:"none",shadows:[]};function vn(e,t){throw new Error(`Graphic "${e}": ${t}`)}function _n(e,t,r,n,o){const s=Number(r);return(!Number.isFinite(s)||s<n||s>o)&&vn(e,`"${t}" is a number from ${n} to ${o}`),s}function En(e,t){let r=Math.imul(0|e,374761393)+Math.imul(0|t,668265263)|0;return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967296}const An=new Map;function zn(e,t,r,n=1/0,{mask:o=null}={}){const s=t*r,{alpha:a,passes:i,latest:l,cov:c,when:u,touched:p}=function(e){let t=An.get(e);return t||(t={alpha:new Float32Array(e),passes:new Float32Array(e),latest:new Float32Array(e),cov:new Float32Array(e),when:new Float32Array(e),touched:new Int32Array(e)},An.clear(),An.set(e,t)),t.alpha.fill(0),t.passes.fill(0),t.latest.fill(-1),t}(s),{strokes:h,total:f}=function(e,t=1){const r=[];let n=e.start;const o=30/e.speed,s=20/e.speed;for(const a of e.strokes){const i=a.points;if(!i.length)continue;const l=[0];for(let e=1;e<i.length;e++)l.push(l[e-1]+Math.hypot((i[e][0]-i[e-1][0])*t,i[e][1]-i[e-1][1]));const c=l[l.length-1]||1e-9,u=i[0][2],p=i.map((t,r)=>{let n;n="recorded"===e.timing?(t[2]-u)/1e3*30/e.speed:"even"===e.timing?l[r]*o:l[r]/c*s;let a=1;if("pressure"===e.widthFrom)a=.3+.7*t[3];else if("speed"===e.widthFrom&&r>0){const e=Math.max(1,t[2]-i[r-1][2]),n=(l[r]-l[r-1])/e*1e3;a=Math.min(1.3,Math.max(.35,1.3-.6*n))}return e.taper>0&&(a*=Math.max(.15,Math.min(1,l[r]/c/e.taper,(1-l[r]/c)/e.taper))),{x:t[0],y:t[1],f:n,wf:a}});"speed"===e.widthFrom&&p.length>1&&(p[0].wf=p[1].wf);const h=p[p.length-1].f;for(const e of p)e.f+=n;r.push({points:p,start:n,end:n+h}),n+=h+e.gap}let a=r.length?r[r.length-1].end:e.start;if(e.fit>0&&a>e.start){const t=e.fit/(a-e.start);for(const n of r){for(const r of n.points)r.f=e.start+(r.f-e.start)*t;n.start=e.start+(n.start-e.start)*t,n.end=e.start+(n.end-e.start)*t}a=e.start+e.fit}return{strokes:r,total:a}}(e,t/r),m=Number.isFinite(n)?n:f,g=Math.max(.5,e.size*r/2);let d=0,$=256*Math.max(s,65536);h.forEach(n=>{if(n.start>m||$<=0)return;let o=0;const s=(t,r,n,o)=>{const s=d++;if("spray"===e.brush){const e=Math.max(3,Math.round(.6*n)),a=Math.max(.6,.07*n);for(let i=0;i<e;i++){const e=En(s,2*i)*Math.PI*2,l=Math.sqrt(En(s,2*i+1))*n;h(t+Math.cos(e)*l,r+Math.sin(e)*l,a,o,"round")}}else h(t,r,n,o,e.brush)},h=(n,s,a,i,l)=>{const h="marker"===l?a:a+1,f=Math.max(0,Math.floor(n-h)),m=Math.min(t-1,Math.ceil(n+h)),g=Math.max(0,Math.floor(s-h)),d=Math.min(r-1,Math.ceil(s+h));$-=m>=f&&d>=g?(m-f+1)*(d-g+1):16;for(let r=g;r<=d;r++)for(let h=f;h<=m;h++){const f=h+.5-n,m=r+.5-s;let g;if("soft"===l){const e=Math.hypot(f,m)/a;if(e>=1)continue;const t=1-e;g=t*t*(3-2*t)}else if("marker"===l){const e=(f+m)*Math.SQRT1_2,t=(m-f)*Math.SQRT1_2,r=Math.hypot(e/a,t/(.33*a));g=Math.min(1,Math.max(0,(1-r)*a*.33+.5))}else g=Math.min(1,Math.max(0,a-Math.hypot(f,m)+.5)),"chalk"===l&&(g*=En(h,7919*r)>.42?1:.12);if(g<=0)continue;g*=e.flow;const d=r*t+h;g>c[d]&&(0===c[d]&&(p[o++]=d),c[d]=g),g>.02&&(u[d]=i)}},f=n.points;let y=0;const b=e=>[e.x*t,e.y*r];if(1===f.length||f.every(e=>e.x===f[0].x&&e.y===f[0].y)){const[e,t]=b(f[0]);s(e,t,g*f[0].wf,f[0].f)}for(let t=1;t<f.length;t++){const r=f[t-1],n=f[t];if(r.f>m)break;const[o,a]=b(r),[i,l]=b(n);let c=1;n.f>m&&(c=(m-r.f)/Math.max(1e-9,n.f-r.f));const u=Math.hypot(i-o,l-a);let p=1===t?0:y;for(;p<=u*c&&$>0;){const t=u?p/u:0,c=g*(r.wf+(n.wf-r.wf)*t);s(o+(i-o)*t,a+(l-a)*t,c,r.f+(n.f-r.f)*t),p+=Math.max(.5,2*e.spacing*c)}if(y=p-u,c<1||$<=0)break}for(let t=0;t<o;t++){const r=p[t],n=c[r];a[r]=e.buildUp?1-(1-a[r])*(1-n):Math.max(a[r],n),i[r]+=n,n>.02&&u[r]>l[r]&&(l[r]=u[r]),c[r]=0}});const y=new Uint8ClampedArray(4*s),b="inside"===e.clip,w="outside"===e.clip;for(let t=0;t<s;t++){let r=a[t];if(0===r)continue;let n=1;o&&(b||w)&&(n=b?o[t]:1-o[t]),r*=n;const s=4*t;y[s]=Math.round(255*Math.min(1,Math.max(0,(m-l[t])/e.age))),y[s+1]=Math.round(255*Math.min(1,i[t]*n/4)),y[s+2]=Math.round(255*Math.min(1,Math.max(0,l[t]/Math.max(1e-9,f)))),y[s+3]=Math.round(255*r)}return{data:y,width:t,height:r,total:f}}const Mn=["text","rect","ellipse","strokes"],kn={text:{type:"text",text:"Text",font:"sans-serif",weight:"bold",style:"normal",size:.08,x:.5,y:.85,align:"center",angle:0,lineHeight:1.2,color:"#ffffff",outline:null,shadow:{color:"rgba(0,0,0,0.6)",blur:.15,dx:.04,dy:.06},shadows:[]},rect:{type:"rect",x:.5,y:.85,w:.8,h:.18,radius:.15,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]},ellipse:{type:"ellipse",x:.5,y:.5,w:.4,h:.4,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]}},On=(e,t)=>(t.shadows??[]).map((t,r)=>`${e}_shadow${r+1}`),jn=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i,Sn=/^[\w\s,'"-]{1,80}$/,Nn=["normal","bold","100","200","300","400","500","600","700","800","900"];function In(e,t,r){if("string"!=typeof r||!jn.test(r.trim()))throw new Error(`Graphic "${e}": "${t}" is a color like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);return r.trim()}function Tn(e,t,r,n=-1/0,o=1/0){const s=Number(r);if(!Number.isFinite(s)||s<n||s>o)throw new Error(`Graphic "${e}": "${t}" is a number${Number.isFinite(n)?` from ${n} to ${o}`:""}`);return s}function Rn(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "outline" is { "color", "width" } or null`);return{color:In(e,"outline.color",t.color??"#000000"),width:Tn(e,"outline.width",t.width??.06,0,1)}}function Cn(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "shadow" is { "color", "blur", "dx", "dy" } or null`);return{color:In(e,"shadow.color",t.color??"rgba(0,0,0,0.6)"),blur:Tn(e,"shadow.blur",t.blur??.15,0,2),dx:Tn(e,"shadow.dx",t.dx??0,-2,2),dy:Tn(e,"shadow.dy",t.dy??0,-2,2)}}function Fn(e,t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Graphic "${e}": give { "type": "text" | "rect" | "ellipse", … }`);const r=t.type??"text";if(!Mn.includes(r))throw new Error(`Graphic "${e}": "type" is text, rect, ellipse or strokes — not "${r}"`);if("strokes"===r)return function(e,t){for(const r of Object.keys(t))r in xn||vn(e,`no such setting "${r}" for strokes`);const r={...xn,...t},n=(t,n)=>(n.includes(r[t])||vn(e,`"${t}" is ${n.join(", ")} — not "${r[t]}"`),r[t]),o={type:"strokes",brush:n("brush",$n),widthFrom:n("widthFrom",bn),timing:n("timing",yn),clip:n("clip",wn),size:_n(e,"size",r.size,.001,.5),flow:_n(e,"flow",r.flow,.01,1),spacing:_n(e,"spacing",r.spacing,.02,2),taper:_n(e,"taper",r.taper,0,.5),speed:_n(e,"speed",r.speed,.05,20),gap:_n(e,"gap",r.gap,0,600),start:_n(e,"start",r.start,0,1e4),fit:_n(e,"fit",r.fit,0,1e4),age:_n(e,"age",r.age,1,1e4),buildUp:Boolean(r.buildUp),shadows:[]};Array.isArray(r.strokes)||vn(e,'"strokes" is a list of { "points": [[x, y, ms, pressure], …] }');let s=0;return o.strokes=r.strokes.map((t,r)=>{const n=Array.isArray(t)?t:t?.points;return Array.isArray(n)||vn(e,`stroke ${r+1} is { "points": [[x, y, ms, pressure], …] }`),s+=n.length,s>6e4&&vn(e,"a drawing has at most 60000 points"),{points:n.map((t,n)=>((!Array.isArray(t)||t.length<2||!t.every(e=>Number.isFinite(Number(e))))&&vn(e,`stroke ${r+1}, point ${n+1} is [x, y, ms, pressure]`),[+Number(t[0]).toFixed(4),+Number(t[1]).toFixed(4),Math.round(Number(t[2]??16*n)),+Math.min(1,Math.max(0,Number(t[3]??1))).toFixed(2)]))}}),o}(e,t);const n=kn[r];for(const o of Object.keys(t))if(!(o in n)&&"fontUrl"!==o&&"onlyShadow"!==o)throw new Error(`Graphic "${e}": no such setting "${o}" for ${r}`);const o={type:r};for(const[r,s]of Object.entries(n)){if("type"===r)continue;const n=r in t&&void 0!==t[r]?t[r]:s;if("color"===r)o.color=In(e,r,n);else if("outline"===r)o.outline=Rn(e,n);else if("shadow"===r)o.shadow=Cn(e,n);else if("shadows"===r){if(!Array.isArray(n)||n.length>8)throw new Error(`Graphic "${e}": "shadows" is a list of up to 8 { "color", "blur", "dx", "dy" }`);o.shadows=n.map((t,r)=>{if(!t||"object"!=typeof t)throw new Error(`Graphic "${e}": shadow layer ${r+1} is { "color", "blur", "dx", "dy" }`);return Cn(e,t)})}else if("text"===r){if("string"!=typeof n||n.length>500)throw new Error(`Graphic "${e}": "text" is up to 500 characters`);o.text=n}else if("font"===r){if("string"!=typeof n||!Sn.test(n))throw new Error(`Graphic "${e}": "font" is a font family, like "Georgia" or "sans-serif"`);o.font=n}else if("weight"===r){if(!Nn.includes(String(n)))throw new Error(`Graphic "${e}": "weight" is normal, bold or 100–900`);o.weight=String(n)}else if("style"===r){if(!["normal","italic"].includes(n))throw new Error(`Graphic "${e}": "style" is normal or italic`);o.style=n}else if("align"===r){if(!["left","center","right"].includes(n))throw new Error(`Graphic "${e}": "align" is left, center or right`);o.align=n}else"size"===r?o.size=Tn(e,r,n,.005,2):"w"===r||"h"===r?o[r]=Tn(e,r,n,0,4):"radius"===r?o.radius=Tn(e,r,n,0,.5):"lineHeight"===r?o.lineHeight=Tn(e,r,n,.5,4):o[r]=Tn(e,r,n)}if(void 0!==t.fontUrl&&null!==t.fontUrl&&""!==t.fontUrl){if("text"!==r)throw new Error(`Graphic "${e}": "fontUrl" is for text`);let n;try{n=new URL(t.fontUrl)}catch{n=null}if(!n||"https:"!==n.protocol)throw new Error(`Graphic "${e}": "fontUrl" is an https:// address of a font file (.woff2, .woff, .ttf, .otf) or of a Google Fonts stylesheet`);o.fontUrl=n.href}return void 0!==t.onlyShadow&&(o.onlyShadow=Tn(e,"onlyShadow",t.onlyShadow,0,7)),o}function qn(e,t){const r=e.fontUrl?`"${Pn(e.fontUrl)}", ${e.font}`:e.font;return`${e.style} ${e.weight} ${Math.max(1,e.size*t)}px ${r}`}function Pn(e){let t=0;for(const r of e)t=31*t+r.charCodeAt(0)>>>0;return`mz-font-${t.toString(36)}`}const Un=new Map;async function Ln(e,t){try{let r=e.fontUrl;if(!/\.(woff2?|ttf|otf)(\?|$)/i.test(new URL(r).pathname)||function(e){try{const t=new URL(e);return"fonts.googleapis.com"!==t.hostname?null:(t.searchParams.get("family")??"").split(":")[0].replace(/\+/g," ")||null}catch{return null}}(r)){if(r=function(e,{weight:t="400",style:r="normal"}={}){const n=[...e.matchAll(/@font-face\s*{([^}]*)}/g)].map(e=>e[1]),o=(e,t)=>(new RegExp(`${t}\\s*:\\s*([^;]+);`).exec(e)?.[1]??"").trim(),s=String("bold"===t?700:"normal"===t?400:t),a=n.filter(e=>o(e,"font-weight")===s&&o(e,"font-style")===r),i=(a.length?a:n).at(-1);return i&&(/url\(([^)]+)\)/.exec(i)?.[1]??"").replace(/^['"]|['"]$/g,"")||null}(await(await fetch(r,{credentials:"omit",referrerPolicy:"no-referrer"})).text(),e),!r||!r.startsWith("https://"))return null}const n=new FontFace(Pn(e.fontUrl),`url(${JSON.stringify(r)})`,{weight:e.weight,style:e.style});return t.add(await n.load()),n}catch{return null}}function Dn(e,t,r,n){e.save();const o="text"===t.type?t.size*n:n,s=void 0!==t.onlyShadow?t.shadows[t.onlyShadow]:null,a=s?2*(r+n)+1e3:0,i=s??t.shadow;if(e.translate(t.x*r-a,t.y*n),t.angle&&e.rotate(t.angle),i&&(e.shadowColor=i.color,e.shadowBlur=i.blur*o,e.shadowOffsetX=i.dx*o+a,e.shadowOffsetY=i.dy*o),e.fillStyle=s?"#000000":t.color,t.outline&&(e.strokeStyle=t.outline.color,e.lineWidth=t.outline.width*o,e.lineJoin="round"),"text"===t.type){e.font=qn(t,n),e.textAlign=t.align,e.textBaseline="middle";const r=t.text.split("\n"),o=t.size*n*t.lineHeight;r.forEach((n,a)=>{const l=(a-(r.length-1)/2)*o;t.outline&&e.strokeText(n,0,l),t.outline&&i&&!s&&(e.shadowColor="transparent"),e.fillText(n,0,l),t.outline&&i&&!s&&(e.shadowColor=i.color)})}else{const o=t.w*r,a=t.h*n;if(e.beginPath(),"ellipse"===t.type)e.ellipse(0,0,o/2,a/2,0,0,2*Math.PI);else{const r=Math.min(o,a)*t.radius;e.roundRect?e.roundRect(-o/2,-a/2,o,a,r):e.rect(-o/2,-a/2,o,a)}e.fill(),t.outline&&(s||(e.shadowColor="transparent"),e.stroke())}e.restore()}async function Bn(e,t,r,{t:n=1/0,mask:o=null}={}){const s=e.graphics??{},a=await async function(e,t=100){if("undefined"==typeof document&&"undefined"==typeof self)return[];const r="undefined"!=typeof document?document.fonts:self.fonts;if(!r)return[];const n=[];for(const o of Object.values(e??{}))if("text"===o.type){if(o.fontUrl&&"undefined"!=typeof FontFace){const e=`${o.fontUrl} ${o.weight} ${o.style}`;Un.has(e)||Un.set(e,Ln(o,r)),await Un.get(e)||n.push(o.fontUrl)}try{await r.load(qn(o,t),o.text)}catch{}}return[...new Set(n)]}(s,r),i={};for(const[e,a]of Object.entries(s)){if("strokes"===a.type){const s=zn(a,t,r,n,{mask:o});i[e]="undefined"!=typeof ImageData?new ImageData(s.data,t,r):s;continue}const s="undefined"!=typeof OffscreenCanvas&&"undefined"==typeof document?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r});Dn(s.getContext("2d"),a,t,r),i[e]=s}return Object.defineProperty(i,"failedFonts",{value:a}),i}const Zn="mathzetta-filter/1",Gn=["r","g","b","a","rgb","rgba"],Wn=/^[A-Za-z][A-Za-z0-9_]*$/,Hn=new Set([...hn,"r","g","b","a","x","y","w","h","t","c","e","pi","color","image","resolution","base","position","main","in","out","inout","const","uniform","varying","attribute","void","float","int","bool","vec2","vec3","vec4","mat2","mat3","mat4","sampler2D","struct","precision","highp","mediump","lowp","if","else","for","while","do","return","break","continue","discard","true","false","texture2D","texture","mix","clamp","step","smoothstep","abs","sign","floor","ceil","fract","mod","min","max","sin","cos","tan","asin","acos","atan","pow","exp","log","exp2","log2","sqrt","inversesqrt","length","distance","dot","cross","normalize","radians","degrees"]),Xn=e=>Array.isArray(e)&&3===e.length&&e.every(e=>Number.isFinite(Number(e))),Vn=e=>e&&"object"==typeof e&&!Array.isArray(e),Yn={place:"cover",zoom:1,x:.5,y:.5,angle:0};function Jn(e){if("string"==typeof e){if(!e.trim())throw new Error("The filter is empty");return{format:Zn,color:e.trim()}}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A filter is an expression, or an object with "color" or "steps"');if(void 0!==e.format&&e.format!==Zn)throw new Error(`Unknown filter format "${e.format}" (this is ${Zn})`);const t={format:Zn};for(const r of["name","author","description"])void 0!==e[r]&&""!==e[r]&&(t[r]=String(e[r]));if(void 0!==e.steps){if(void 0!==e.color)throw new Error('A filter has either "color" or "steps", not both');if(!Array.isArray(e.steps)||!e.steps.length)throw new Error('"steps" must be a list with at least one step');return t.steps=e.steps.map(to),void 0!==e.notes&&(t.notes=Kn(e.notes,oo(t))),t}if(void 0===e.color)throw new Error('A filter needs "color" (an expression, or one per channel) or "steps"');const r=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"params" is an object of name → { default, min, max }');const t={};for(const[r,n]of Object.entries(e)){if(!Wn.test(r))throw new Error(`Parameter name "${r}" must be letters, digits and _, starting with a letter`);if(Hn.has(r))throw new Error(`"${r}" is already defined in every filter; pick another parameter name`);t[r]=ro(r,n)}return t}(e.params??{});Object.keys(r).length&&(t.params=r),void 0!==e.notes&&(t.notes=Kn(e.notes,r));const n=function(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,{}])):e;if(!r||"object"!=typeof r)throw new Error('"images" is a list of names, or an object of name → { description }');const n={};for(const[e,o]of Object.entries(r)){if(!Wn.test(e)||e.startsWith("mz_"))throw new Error(`Image name "${e}" must be letters, digits and _, starting with a letter`);if("source"===e)throw new Error('"source" is always available: the picture the chain started from');if(Hn.has(e))throw new Error(`"${e}" is already defined in every filter; pick another image name`);if(Object.hasOwn(t,e))throw new Error(`"${e}" is both a parameter and an image`);n[e]=eo(e,o)}return n}(e.images??{},r);Object.keys(n).length&&(t.images=n);const o=function(e,t,r){if(!Vn(e))throw new Error('"graphics" is an object of name → { "type": "text" | "rect" | "ellipse", … }');if(Object.keys(e).length>64)throw new Error("A filter has at most 64 graphics");const n={};for(const[o,s]of Object.entries(e)){if(!Wn.test(o)||o.startsWith("mz_"))throw new Error(`Graphic name "${o}" must be letters, digits and _, starting with a letter`);if(Hn.has(o)||"source"===o||"selection"===o)throw new Error(`"${o}" is already defined in every filter; pick another graphic name`);if(Object.hasOwn(t,o)||Object.hasOwn(r,o))throw new Error(`"${o}" is both a graphic and a parameter or picture`);n[o]=Fn(o,s)}const o=new Set(Object.keys(n).flatMap(e=>Array.from({length:8},(t,r)=>`${e}_shadow${r+1}`)));for(const e of[...Object.keys(n),...Object.keys(t),...Object.keys(r)])if(o.has(e))throw new Error(`"${e}" is the name of a shadow layer of another graphic; pick another name`);return n}(e.graphics??{},r,n);Object.keys(o).length&&(t.graphics=o);const s=function(e){if(null==e)return null;const t="string"==typeof e?{in:e,out:e}:e;if(!Vn(t))throw new Error(`"space" is a color space (${nn.join(", ")}) or { "in": …, "out": … }`);const r={in:t.in??"srgb",out:t.out??"srgb"};for(const e of["in","out"])if(!nn.includes(r[e]))throw new Error(`"space": "${r[e]}" is not a color space; they are ${nn.join(", ")}`);return"srgb"===r.in&&"srgb"===r.out?null:r}(e.space);return s&&(t.space=s),t.color=function(e){if("string"==typeof e){if(!e.trim())throw new Error('"color" is empty');return e.trim()}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"color" is an expression, or an object with r, g, b, a, rgb or rgba expressions');const t={};for(const[r,n]of Object.entries(e)){if(!Gn.includes(r))throw new Error(`"color" can set r, g, b, a, rgb or rgba — not "${r}"`);if("string"!=typeof n||!n.trim())throw new Error(`"color.${r}" must be an expression`);t[r]=n.trim()}if(!Object.keys(t).length)throw new Error('"color" sets no channels');return t}(e.color),t}function Kn(e,t){if(!Array.isArray(e))throw new Error('"notes" is a list of Markdown texts and { "param": name } entries');return e.map(e=>{if("string"==typeof e)return e;if(!Vn(e)||"string"!=typeof e.param||1!==Object.keys(e).length)throw new Error('"notes": each entry is a Markdown text or { "param": name }');if(!Object.hasOwn(t,e.param))throw new Error(`"notes" places "${e.param}", but there is no parameter called that`);return{param:e.param}})}function Qn(e){if(e.color)return{...e.graphics??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(Qn(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function eo(e,t){if(!Vn(t))throw new Error(`Image "${e}": give { description, place, zoom, x, y, angle }`);const r={};if(t.description&&(r.description=String(t.description)),void 0!==t.place){if(!ln.includes(t.place))throw new Error(`Image "${e}": "place" is ${ln.join(", ")} — not "${t.place}"`);r.place=t.place}for(const n of["zoom","x","y","angle"]){if(void 0===t[n])continue;const o=Number(t[n]);if(!Number.isFinite(o))throw new Error(`Image "${e}": "${n}" is a number`);r[n]=o}for(const r of Object.keys(t))if(!["description","place","zoom","x","y","angle"].includes(r))throw new Error(`Image "${e}": no such setting "${r}"`);return r}function to(e){if("string"==typeof e)return{filter:Jn(e),with:{},opacity:1,skip:!1};if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A step is an expression, a filter, or { "filter": …, "with": { … }, "opacity": … }');const{filter:t,with:r,opacity:n,skip:o,...s}=e,a={filter:Jn(void 0!==t?t:s),with:{},opacity:1,skip:Boolean(o)};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new Error('"with" is an object of parameter name → value');a.with={...r}}if(void 0!==n){const e=Number(n);if(!(e>=0&&e<=1))throw new Error('"opacity" is a number from 0 to 1');a.opacity=e}return a}function ro(e,t){if("number"==typeof t)t={default:t};else if(Array.isArray(t))t={type:"color",default:t};else if(!t||"object"!=typeof t)throw new Error(`Parameter "${e}" needs a default value`);const r=t.type??(Array.isArray(t.default)?"color":"number"),n={type:r};if(void 0!==t.label&&(n.label=String(t.label)),"color"===r){const r=t.default??[1,1,1];if(!Xn(r))throw new Error(`Color parameter "${e}" needs a default of three numbers, 0–1`);return n.default=r.map(Number),n}if("number"!==r)throw new Error(`Parameter "${e}": the type is "number" or "color", not "${r}"`);let o=null;if(void 0!==t.options){if(!Array.isArray(t.options)||!t.options.length||!t.options.every(e=>""!==e&&Number.isFinite(Number(e))))throw new Error(`Parameter "${e}": "options" is a list of numbers`);o=t.options.map(Number)}if(void 0!==t.input&&"slider"!==t.input&&"box"!==t.input)throw new Error(`Parameter "${e}": "input" is "slider" or "box", not "${t.input}"`);const s=Number(t.default??(o?o[0]:0));if(!Number.isFinite(s))throw new Error(`Parameter "${e}" needs a numeric default`);if(n.default=s,n.min=void 0!==t.min?Number(t.min):o?o.reduce((e,t)=>Math.min(e,t),s):Math.min(0,2*s),n.max=void 0!==t.max?Number(t.max):o?o.reduce((e,t)=>Math.max(e,t),s):Math.max(1,2*s),void 0!==t.step&&(n.step=Number(t.step)),o&&(n.options=o),"box"!==t.input||o||(n.input="box"),!(n.min<=s&&s<=n.max))throw new Error(`Parameter "${e}": the default ${s} is outside ${n.min} to ${n.max}`);return n}function no(e){if(e.color)return{...e.images??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(no(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function oo(e){if(e.color)return{...e.params??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(oo(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function so(e,t,r,n){const{filter:o}=e,s=ao(o,t),a=oo(o),i=no(o),l=Qn(o);for(const[t,n]of Object.entries(e.with)){if(Object.hasOwn(l,t)){if(Vn(n))try{Fn(t,{...l[t],...n})}catch(e){r.push(`${s}: ${e.message}`)}else r.push(`${s}: "with" for the graphic "${t}" is an object of its settings`);continue}if(Object.hasOwn(i,t)){try{eo(t,n)}catch(e){r.push(`${s}: ${e.message}`)}continue}const e=Object.hasOwn(a,t)?a[t]:null;e?("color"===e.type?Xn(n):Number.isFinite(Number(n)))||r.push(`${s}: "${t}" should be a ${"color"===e.type?"color: three numbers, 0–1":"number"}`):r.push(`${s}: "with" sets "${t}", but there is no parameter called that`)}o.steps&&o.steps.forEach((e,n)=>so(e,[...t,n],r))}function ao(e,t){return e.name?`"${e.name}"`:t.length?`step ${t.map(e=>e+1).join(".")}`:"the filter"}function io(e,t={}){const r=Jn(e),n=[];if(so({filter:r,with:{}},[],n),n.length)throw new Error(n.join("\n"));const o={passes:[],credits:[],problems:n,version:300===t.version?300:100,top:r,graphics:{}};if(lo({filter:r,with:{},opacity:1,skip:!1},[],{},o),n.length)throw new Error(n.join("\n"));return o.passes.length||o.passes.push(co(Jn("pixel(px, py)"),{},1,[],o.version)),{name:r.name??"",author:r.author??"",description:r.description??"",version:o.version,passes:o.passes,credits:o.credits,images:no(r),graphics:o.graphics}}function lo(e,t,r,n){if(e.skip)return;if(n.passes.length>256){const e="A filter has at most 256 passes";return void(n.problems.includes(e)||n.problems.push(e))}const o=function(e){if(!e.space||void 0===e.color)return null;const{space:t,name:r,author:n,description:o,...s}=e,a=e=>({filter:e,with:{},opacity:1,skip:!1}),i=[];"srgb"!==t.in&&i.push(a({format:Zn,color:{rgb:`to${t.in}(rgb)`}}));i.push(a({...s,_space:t.in})),"srgb"!==t.out&&i.push(a({format:Zn,color:{rgb:`from${t.out}(rgb)`}}));const l={format:Zn,steps:i};for(const[e,t]of Object.entries({name:r,author:n,description:o}))t&&(l[e]=t);return l}(e.filter)??function(e){if("string"!=typeof e.color)return null;const t=/^(gaussian|blur)\((.*)\)$/s.exec(e.color.trim());if(!t)return null;let r=0;for(const e of t[2])if("("===e)r++;else if(")"===e&&--r<0)return null;if(0!==r)return null;const{color:n,...o}=e,s=e=>{const r={format:Zn,color:`${t[1]}${e}(${t[2]})`};return o.params&&(r.params=o.params),o.images&&(r.images=o.images),o.graphics&&(r.graphics=o.graphics),{filter:r,with:{},opacity:1,skip:!1}};return{...o,steps:[s("x"),s("y")]}}(e.filter);if(o)return e.filter===n.top&&(n.top=o),void lo({...e,filter:o},t,r,n);const{filter:s}=e,a={...e.with,...r};for(const t of Object.keys(r))Vn(r[t])&&Vn(e.with[t])&&(a[t]={...e.with[t],...r[t]});if(s.name&&s!==n.top&&!n.credits.some(e=>e.name===s.name&&e.author===(s.author??""))&&n.credits.push({name:s.name,author:s.author??""}),s.color){try{n.passes.push(function(e,t){e.bind={};for(const[r,n]of Object.entries(e.graphics??{})){let o=r;for(let e=2;o in t&&JSON.stringify(t[o])!==JSON.stringify(n);e++)o=`${r}~${e}`;t[o]=n,e.bind[r]=o}return e}(co(s,a,e.opacity,t,n.version),n.graphics))}catch(e){n.problems.push(`${ao(s,t)}: ${e.message}`)}return}const i=n.passes.length;s.steps.forEach((e,r)=>lo(e,[...t,r],a,n)),e.opacity<1&&(n.passes.length-i===1?n.passes[i].opacity*=e.opacity:(n.passes[i].keepInput+=1,n.passes.push(function(e,t,r){const n=300===r,o=n?"texture":"texture2D",s=[n?"#version 300 es":"","precision highp float;","uniform sampler2D image;","uniform sampler2D base;","uniform vec2 resolution;","uniform float mz_opacity;",n?"out vec4 fragColor;":"","void main() {"," vec2 uv = gl_FragCoord.xy / resolution;",` ${n?"fragColor":"gl_FragColor"} = mix(${o}(base, uv), ${o}(image, uv), mz_opacity);`,"}"].filter(Boolean).join("\n");return{name:"blend",author:"",path:t,fragment:s,params:{},values:{},opacity:e,images:[],placements:{},graphics:{},keepInput:0,blendKept:!0}}(e.opacity,t,n.version))))}function co(e,t,r,n,o){const s=e.params??{},a={};for(const[e,r]of Object.entries(s))Object.hasOwn(t,e)?a[e]="color"===r.type?t[e].map(Number):Number(t[e]):a[e]=r.default;const i={};for(const[r,n]of Object.entries(e.images??{})){const{description:e,...o}=n;i[r]={...Yn,...o,...Vn(t[r])?t[r]:{}}}const l={};for(const[r,n]of Object.entries(e.graphics??{}))l[r]=Vn(t[r])?Fn(r,{...n,...t[r]}):n,i[r]={...Yn,place:"stretch"},On(r,l[r]).forEach((e,t)=>{l[e]={...l[r],onlyShadow:t},i[e]={...Yn,place:"stretch"}});const c=function(e,t,r=null){const n=e.params??{},o={};for(const[e,t]of Object.entries(n))o[e]="color"===t.type?"vec3":"float";const s={};for(const[t,n]of Object.entries(e.images??{}))s[t]={place:r?.[t]?.place??n.place??Yn.place};for(const[t,n]of Object.entries(e.graphics??{})){s[t]={place:"stretch"};const e=r?Object.keys(r).filter(e=>/_shadow\d+$/.test(e)&&e.startsWith(`${t}_shadow`)):On(t,n);for(const t of e)s[t]={place:"stretch"}}return function(e,t={}){const r=Array.isArray(t.images)?t.images:Object.keys(t.images??{}),n=[...sn,...t.names??[],...r],o=[...en,...t.values??[]];return gn(e,{...t,parse:e=>Tr(e,{...t,names:n,values:o})})}(e.color,{version:t,uniforms:o,values:Object.keys(n),images:s,blend:!0,space:e._space??e.space?.in??"srgb"})}(e,o,i),u=Object.keys(i);return c.includes("uniform sampler2D mz_img_source;")&&u.push("source"),c.includes("uniform sampler2D mz_img_selection;")&&u.push("selection"),{name:e.name??"",author:e.author??"",path:n,color:e.color,space:e._space??"srgb",fragment:c,params:s,values:a,opacity:r,images:u,placements:i,graphics:l,keepInput:0,blendKept:!1}}function uo(e){return JSON.stringify(fo(Jn(e),!0),null,2)}function po(e){const t=e.includes("#")?e.slice(e.lastIndexOf("#")+1):e;let r;try{r=JSON.parse(function(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/"));return(new TextDecoder).decode(Uint8Array.from(t,e=>e.charCodeAt(0)))}(t.trim()))}catch{throw new Error("Not a filter link")}return Jn(r)}function ho(e){const t=String(e??"").trim();if(!t)throw new Error("Nothing to read");if(t.startsWith("{"))return function(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Not valid JSON")}return Jn(t)}(t);if(!/\s/.test(t)){const e=t.includes("#")?t.slice(t.lastIndexOf("#")+1):t;if(/^[A-Za-z0-9_-]{8,}$/.test(e))try{return po(e)}catch(e){if(t.includes("#"))throw e}}return Jn(t)}function fo(e,t){const r={};t&&(r.format=Zn);for(const t of["name","author","description"])e[t]&&(r[t]=e[t]);return e.notes&&e.notes.length&&(r.notes=e.notes),e.steps?(r.steps=e.steps.map(e=>{const t=fo(e.filter,!1),r=1===Object.keys(t).length&&"string"==typeof t.color?t.color:t,n={};return Object.keys(e.with).length&&(n.with=e.with),1!==e.opacity&&(n.opacity=e.opacity),e.skip&&(n.skip=!0),Object.keys(n).length?{filter:r,...n}:r}),r):(e.params&&(r.params=e.params),e.images&&(r.images=e.images),e.graphics&&(r.graphics=e.graphics),e.space&&(r.space=e.space.in===e.space.out?e.space.in:e.space),r.color=e.color,r)}function mo(e,t,r={}){if(e.isContextLost())throw new Error("The WebGL context is lost");const n=$o(e,r.precision),o=function(e={}){return 300===e.version?"#version 300 es\nin vec2 position;\nvoid main() { gl_Position = vec4(position, 0.0, 1.0); }":"attribute vec2 position;\nvoid main() { gl_Position = vec4(position, 0.0, 1.0); }"}({version:t.version}),s=[];try{for(const r of t.passes)s.push(yo(e,o,r.fragment,r.name))}catch(t){for(const t of s)e.deleteProgram(t);throw t}const a=(e,t)=>e.bind&&Object.hasOwn(e.bind,t)?e.bind[t]:t,i=s.map(()=>new Map),l=(t,r)=>(i[t].has(r)||i[t].set(r,e.getUniformLocation(s[t],r)),i[t].get(r)),c=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,c),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),e.STATIC_DRAW);const u={texture:e.createTexture(),framebuffer:null};e.bindTexture(e.TEXTURE_2D,u.texture),go(e);const p=new Map,h=new Map,f=e.createTexture();e.bindTexture(e.TEXTURE_2D,f),go(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));const m=e.createTexture();e.bindTexture(e.TEXTURE_2D,m),go(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([0,0,0,0]));const g=[];let d=0,$=0;const y={passes:t.passes,get precision(){return n.name},setImage(t,r){if("string"!=typeof t&&(r=t,t=null),t&&"source"!==t&&null==r)return p.has(t)&&e.deleteTexture(p.get(t)),p.delete(t),h.delete(t),y;let n=u.texture;if(t&&"source"!==t&&(p.has(t)||(p.set(t,e.createTexture()),e.bindTexture(e.TEXTURE_2D,p.get(t)),go(e)),n=p.get(t)),r&&r.data&&r.width&&r.height&&"undefined"!=typeof ImageData&&!(r instanceof ImageData)){const e=r.data,t=e instanceof Float32Array||e instanceof Float64Array,n=e instanceof Uint8ClampedArray?e:Uint8ClampedArray.from(e,t?e=>255*e:void 0);r=new ImageData(n,r.width,r.height)}return e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r),t&&h.set(t,[r.naturalWidth||r.videoWidth||r.width||1,r.naturalHeight||r.videoHeight||r.height||1]),y},draw({t:r=0}={}){if(e.drawingBufferWidth!==d||e.drawingBufferHeight!==$){d=e.drawingBufferWidth,$=e.drawingBufferHeight;for(const t of g)e.bindTexture(e.TEXTURE_2D,t.texture),e.texImage2D(e.TEXTURE_2D,0,n.internal,d,$,0,e.RGBA,n.type,null)}let o=u;const i=[];return t.passes.forEach((y,b)=>{for(let e=0;e<y.keepInput;e++)i.push(o);const w=b===t.passes.length-1?null:function(t){let r=g.find(e=>!t.includes(e));return r||(r={texture:e.createTexture(),framebuffer:e.createFramebuffer()},e.bindTexture(e.TEXTURE_2D,r.texture),go(e,n.filter),e.texImage2D(e.TEXTURE_2D,0,n.internal,d,$,0,e.RGBA,n.type,null),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r.texture,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE&&"byte"!==n.name&&(Object.assign(n,$o(e,"byte")),e.bindTexture(e.TEXTURE_2D,r.texture),go(e,n.filter),e.texImage2D(e.TEXTURE_2D,0,n.internal,d,$,0,e.RGBA,n.type,null)),g.push(r)),r}([o,...i]);e.bindFramebuffer(e.FRAMEBUFFER,w?w.framebuffer:null),e.viewport(0,0,d,$);const x=s[b];e.useProgram(x);const v=e.getAttribLocation(x,"position");e.bindBuffer(e.ARRAY_BUFFER,c),e.enableVertexAttribArray(v),e.vertexAttribPointer(v,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,o.texture),e.uniform1i(l(b,"image"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,y.blendKept?i[i.length-1].texture:null),y.blendKept&&e.uniform1i(l(b,"base"),1),y.images.forEach((t,r)=>{if(e.activeTexture(e.TEXTURE2+r),e.bindTexture(e.TEXTURE_2D,"source"===t?u.texture:p.get(a(y,t))??(y.graphics?.[t]?m:f)),e.uniform1i(l(b,`mz_img_${t}`),2+r),!y.placements[t])return;const n=h.get(a(y,t))??[1,1],o=y.placements[t];e.uniform2f(l(b,`mz_size_${t}`),n[0],n[1]),e.uniform4f(l(b,`mz_place_${t}`),Number(o.zoom),Number(o.x),Number(o.y),Number(o.angle))}),e.uniform2f(l(b,"resolution"),d,$),e.uniform1f(l(b,"t"),r),e.uniform1f(l(b,"mz_opacity"),y.opacity);for(const[t,r]of Object.entries(y.params)){const n=y.values[t];"color"===r.type?e.uniform3fv(l(b,t),n.map(Number)):e.uniform1f(l(b,t),Number(n))}e.drawArrays(e.TRIANGLES,0,3),y.blendKept&&i.pop(),o=w}),y},dispose(){for(const t of s)e.deleteProgram(t);e.deleteTexture(u.texture),e.deleteTexture(f),e.deleteTexture(m);for(const t of p.values())e.deleteTexture(t);for(const t of g)e.deleteTexture(t.texture),e.deleteFramebuffer(t.framebuffer);e.deleteBuffer(c)}};return y}function go(e,t=e.LINEAR){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t)}function $o(e,t="byte"){const r={name:"byte",internal:e.RGBA,type:e.UNSIGNED_BYTE,filter:e.LINEAR};if("half"!==t&&"float"!==t)return r;if("undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext){if(!e.getExtension("EXT_color_buffer_float"))return r;const n=e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST;return"float"===t?{name:"float",internal:e.RGBA32F,type:e.FLOAT,filter:n}:{name:"half",internal:e.RGBA16F,type:e.HALF_FLOAT,filter:e.LINEAR}}if("float"===t&&e.getExtension("OES_texture_float")&&e.getExtension("WEBGL_color_buffer_float"))return{name:"float",internal:e.RGBA,type:e.FLOAT,filter:e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST};const n=e.getExtension("OES_texture_half_float");return n&&e.getExtension("EXT_color_buffer_half_float")?{name:"half",internal:e.RGBA,type:n.HALF_FLOAT_OES,filter:e.getExtension("OES_texture_half_float_linear")?e.LINEAR:e.NEAREST}:r}function yo(e,t,r,n){const o=e.createProgram(),s=[];let a=null;for(const[i,l]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);if(s.push(t),e.shaderSource(t,l),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS)){a=`${n||"The filter"} does not compile: ${(e.getShaderInfoLog(t)??"").trim()}`;break}e.attachShader(o,t)}a||(e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)||(a=`${n||"The filter"} does not link: ${(e.getProgramInfoLog(o)??"").trim()}`));for(const t of s)e.deleteShader(t);if(a)throw e.deleteProgram(o),new Error(a);return o}class bo extends Error{}const wo=new Set(Object.getOwnPropertyNames(Math)),xo=new Set([...wo,"isInteger","isFinite","includes","reduce","toFixed"]),vo={Math:wo,Number:new Set(["isInteger","isFinite"])},_o=new Set(["Math","Number","Infinity","NaN","true","false","null"]),Eo=new Set(["let","for","if","return"]),Ao=Object.values(pe).sort((e,t)=>t.length-e.length),zo=["===","!==","**=","...","=>","==","!=","<=",">=","&&","||","??","**","++","--","+=","-=","*=","/=","%=","(",")","[","]","{","}",",",";","?",":",".","+","-","*","/","%","!","=","<",">","&","|","^","~"],Mo=new Set(["=","+=","-=","*=","/=","%=","**=","++","--"]);for(const e of[vo])Object.setPrototypeOf(e,null);const ko={name:"javascript",title:"JavaScript",pi:"Math.PI",e:"Math.E",tau:"(2 * Math.PI)",inf:"Infinity",degree:"(Math.PI/180)",true:"true",false:"false",null:"null",math:e=>`Math.${e}`,abs:"Math.abs",max:"Math.max",min:"Math.min",random:"Math.random()",pow:(e,t)=>`Math.pow(${e}, ${t})`,both:(e,t)=>`(${e} && ${t})`,either:(e,t)=>`(${e} || ${t})`,not:e=>`!${e}`,xor:(e,t)=>`(!(${e}) !== !(${t}))`,oddRoot:(e,t)=>3===t?`Math.cbrt(${e})`:Ho(e)?`(${e} < 0 ? -Math.pow(-${e}, 1 / ${t}) : Math.pow(${e}, 1 / ${t}))`:`${pe.root}(${t}, ${e})`,realRoot:(e,t)=>`${pe.root}(${e}, ${t})`,close:(e,t)=>`Math.abs((${e}) - (${t})) < 1e-9`,eq:{"=":"==","===":"===","≠":"!=","≠=":"!=="},ternary:(e,t,r)=>`(${e} ? ${t} : ${r})`,list:{"()":["[","]"],"[]":["[","]"],"{}":["[","]"],"(]":["[","]"],"[)":["[","]"]},contains:(e,t,r)=>`${r?"!":""}${e}.includes(${t})`,substring:(e,t,r)=>`${r?"!":""}${pe.contains}(${e}, ${t})`,startsWith:(e,t)=>`${pe.startswith}(${e}, ${t})`,factorial:e=>`${pe.factorial}(${e})`,perm:(e,t)=>`${pe.perm}(${e}, ${t})`,comb:(e,t)=>`${pe.comb}(${e}, ${t})`,gcd:e=>`${pe.gcd}([${e}])`,round:(e,t)=>{const r=Jo(e)?e:`(${e})`;if(Wo(e)&&Ho(t))return"0"===t?`Math.round(${e})`:`Math.round(${e} * Math.pow(10, ${t})) / Math.pow(10, ${t})`;if(!Ho(e)||!Ho(t))return`${pe.round}(${e}, ${t})`;if("0"===t)return`(${r} < 0 ? -Math.round(-${r}) : Math.round(${r}))`;const n=`Math.pow(10, ${t})`;return`(${r} < 0 ? -Math.round(-${r} * ${n}) : Math.round(${r} * ${n})) / ${n}`},fixed:(e,t)=>`Number(${e}).toFixed(${t})`,matrix:e=>`[${e.map(e=>`[${e.join(", ")}]`).join(", ")}]`,det:e=>`${pe.det}(${e})`,union:(e,t)=>`${pe.union}(${e}, ${t})`,intersection:(e,t)=>`${pe.intersection}(${e}, ${t})`,indexed:(e,t,r,n,o)=>"sum"===e?`(()=>{let sum = 0; let loopCount = 0; for (let ${t}=${r};${n};${t}++) {if (loopCount++ > 1000000){break};sum += ${o};}; return sum;})()`:`(()=>{let prod = 1; let loopCount = 0; for (let ${t}=${r};${n};${t}++) {if (loopCount++ > 1000000){break};prod *= ${o};}; return prod;})()`},Oo={name:"python",title:"Python",python:!0,pi:"math.pi",e:"math.e",tau:"math.tau",inf:"math.inf",degree:"(math.pi/180)",true:"True",false:"False",null:"None",math:e=>`math.${e}`,abs:"abs",max:"max",min:"min",random:"random.random()",pow:null,both:(e,t)=>`(${e} and ${t})`,either:(e,t)=>`(${e} or ${t})`,not:e=>`not ${e}`,xor:(e,t)=>`((not (${e})) != (not (${t})))`,oddRoot:(e,t)=>3===t?`math.cbrt(${e})`:Vo(e,e=>`(-(-${e}) ** (1 / ${t}) if ${e} < 0 else ${e} ** (1 / ${t}))`),realRoot:(e,t)=>Vo(t,t=>`(-(-${t}) ** (1 / ${Yo(e)}) if ${t} < 0 and ${Yo(e)} % 2 == 1 else ${t} ** (1 / ${Yo(e)}))`),close:(e,t)=>`abs((${e}) - (${t})) < 1e-9`,eq:{"=":"==","===":"==","≠":"!=","≠=":"!="},ternary:(e,t,r)=>`(${t} if ${e} else ${r})`,list:{"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(",")"],"[)":["(",")"]},emptySet:"set()",contains:(e,t,r)=>`${t} ${r?"not in":"in"} ${e}`,substring:(e,t,r)=>r?`(not ${ge.contains}(${e}, ${t}))`:`${ge.contains}(${e}, ${t})`,startsWith:(e,t)=>`${ge.startswith}(${e}, ${t})`,factorial:e=>`math.factorial(${e})`,perm:(e,t)=>`math.perm(${e}, ${t})`,comb:(e,t)=>`math.comb(${e}, ${t})`,gcd:e=>`math.gcd(${e})`,round:(e,t)=>{if("0"===t)return Wo(e)?`math.floor(${e} + 0.5)`:Vo(e,t=>Xo(e,`(math.floor(${t} + 0.5) if ${t} >= 0 else -math.floor(-${t} + 0.5))`,t));const r=`10 ** ${Jo(t)?t:`(${t})`}`;if(Wo(e)&&Ho(t))return`math.floor(${e} * ${r} + 0.5) / ${r}`;const n=(t,r)=>Xo(e,`(math.floor(${t} * ${r} + 0.5) if ${t} >= 0 else -math.floor(-${t} * ${r} + 0.5)) / ${r}`,t);return Ho(e)&&Ho(t)?n(Jo(e)?e:`(${e})`,r):`(lambda _v, _p: ${n("_v","_p")})(${e}, ${r})`},fixed:(e,t,r)=>null===r?`format(${Oo.round(e,t)}, "." + str(${t}) + "f")`:`format(${Oo.round(e,r)}, ".${r}f")`,matrix:e=>`[${e.map(e=>`[${e.join(", ")}]`).join(", ")}]`,det:e=>`np.linalg.det(${e})`,union:(e,t)=>`sorted(set(${e}) | set(${t}))`,intersection:(e,t)=>`sorted(set(${e}) & set(${t}))`,integral:(e,t,r,n)=>`scipy.integrate.quad(lambda ${r}: ${t}, ${n.join(", ")})[0]`,symbolic:"the SymPy flavour, { sympy: true }, has it",indexed:(e,t,r,n,o,s)=>"sum"===e?`sum(${o} for ${t} in range(${r}, ${s} + 1))`:`math.prod(${o} for ${t} in range(${r}, ${s} + 1))`},jo={asin:"arcsin",acos:"arccos",atan:"arctan",asinh:"arcsinh",acosh:"arccosh",atanh:"arctanh",atan2:"arctan2",pow:"power"},So=(e,t)=>t.reduce((t,r)=>`${e}(${t}, ${r})`),No={"<":"<",">":">","≤":"<=","≥":">=","=":"==","===":"==","≠":"!=","≠=":"!="},Io=([,e],t,r)=>{const[n,o]=t.args,s=(e,t)=>"op"===e.type&&Qo.has(e.op)?`(${t})`:t,a=r=>`${r} ${No[t.op]} ${s(o,e)}`;return"op"===n.type&&No[n.op]?`np.logical_and(${r(n)}, ${a(s(n.args[1],r(n.args[1])))})`:a(s(n,r(n)))},To={...Oo,name:"numpy",title:"numpy",union:(e,t)=>`np.union1d(${e}, ${t})`,intersection:(e,t)=>`np.intersect1d(${e}, ${t})`,pi:"np.pi",e:"np.e",tau:"(2 * np.pi)",inf:"np.inf",degree:"(np.pi/180)",math:e=>`np.${jo[e]??e}`,list:{...Oo.list,"{}":["[","]"]},abs:"np.abs",random:"np.random.random()",matrix:e=>`np.array(${Oo.matrix(e)})`,det:e=>`np.linalg.det(${e})`,both:(e,t)=>`np.logical_and(${e}, ${t})`,either:(e,t)=>`np.logical_or(${e}, ${t})`,not:e=>`np.logical_not(${e})`,close:(e,t)=>`np.isclose(${e}, ${t})`,ternary:(e,t,r)=>`np.where(${e}, ${t}, ${r})`,contains:(e,t,r)=>r?`np.logical_not(np.isin(${t}, ${e}))`:`np.isin(${t}, ${e})`,substring:(e,t,r)=>r?`np.logical_not(${de.contains}(${e}, ${t}))`:`${de.contains}(${e}, ${t})`,startsWith:(e,t)=>`${de.startswith}(${e}, ${t})`,factorial:e=>`scipy.special.factorial(${e})`,perm:(e,t)=>`scipy.special.perm(${e}, ${t})`,comb:(e,t)=>`scipy.special.comb(${e}, ${t})`,round:(e,t)=>{if("0"===t)return Vo(e,e=>`np.where(${e} >= 0, np.floor(${e} + 0.5), -np.floor(-${e} + 0.5))`);const r=`10.0 ** ${Jo(t)?t:`(${t})`}`,n=(e,t)=>`np.where(${e} >= 0, np.floor(${e} * ${t} + 0.5), -np.floor(-${e} * ${t} + 0.5)) / ${t}`;return Ho(e)&&Ho(t)?n(Jo(e)?e:`(${e})`,r):`(lambda _v, _p: ${n("_v","_p")})(${e}, ${r})`},oddRoot:(e,t)=>3===t?`np.cbrt(${e})`:Vo(e,e=>`np.where(${e} < 0, -np.power(-${e}, 1 / ${t}), np.power(${e}, 1 / ${t}))`),realRoot:(e,t)=>Vo(t,t=>`np.where((${t} < 0) & (np.mod(${e}, 2) == 1), -np.power(-${t}, 1 / ${Yo(e)}), np.power(${t}, 1 / ${Yo(e)}))`),fixed:(e,t,r)=>null===r?`np.char.mod("%." + str(${t}) + "f", ${To.round(e,t)})`:`np.char.mod("%.${r}f", ${To.round(e,r)})`,ops:{...Object.fromEntries(Object.keys(No).map(e=>[e,Io])),max:e=>1===e.length?`np.nanmax(${e[0]})`:So("np.maximum",e),min:e=>1===e.length?`np.nanmin(${e[0]})`:So("np.minimum",e),sum:e=>1===e.length?`np.nansum(${e[0]})`:null,prod:e=>1===e.length?`np.nanprod(${e[0]})`:null,mean:e=>1===e.length?`np.nanmean(${e[0]})`:null,"\\:median":e=>1===e.length?`np.nanmedian(${e[0]})`:null,"\\:stdev":e=>1===e.length?`np.nanstd(${e[0]})`:null,"\\:std":e=>1===e.length?`np.nanstd(${e[0]})`:null,gcd:e=>So("np.gcd",e),"\\xor":([e,t])=>`np.logical_xor(${e}, ${t})`,"\\nand":([e,t])=>`np.logical_not(np.logical_and(${e}, ${t}))`,"\\implies":([e,t])=>`np.logical_or(np.logical_not(${e}), ${t})`,"\\iff":([e,t])=>`np.logical_not(np.logical_xor(${e}, ${t}))`,"\\nor":([e,t])=>`np.logical_not(np.logical_or(${e}, ${t}))`}},Ro=e=>`sympy.${e}`,Co=e=>"number"===e.type&&/^-?\d+$/.test(e.value)||"op"===e.type&&"neg"===e.op&&Co(e.args[0]),Fo={"ℝ":"sympy.S.Reals","ℤ":"sympy.S.Integers","ℕ":"sympy.S.Naturals","ℚ":"sympy.S.Rationals","ℂ":"sympy.S.Complexes"},qo={"[]":"sympy.Interval","()":"sympy.Interval.open","(]":"sympy.Interval.Lopen","[)":"sympy.Interval.Ropen"};function Po(e,t){return"symbol"===e.type&&Fo[e.value]?Fo[e.value]:"op"===e.type&&qo[e.op]&&2===e.args.length?`${qo[e.op]}(${e.args.map(t).join(", ")})`:"op"===e.type&&yt(e.op)?.group?`sympy.FiniteSet(${e.args.map(t).join(", ")})`:"number"===e.type||"neg"===e.op&&"number"===e.args[0].type?`sympy.FiniteSet(${t(e)})`:t(e)}function Uo(e,t,r,n){const o=[];return function t(n){"op"===n.type&&n.op===e?n.args.forEach(t):o.push(r(n))}(t),`${n}(${o.join(", ")})`}const Lo={...Oo,name:"sympy",title:"SymPy",symbolic:null,noStrings:!0,pi:Ro("pi"),e:Ro("E"),tau:"(2*sympy.pi)",inf:Ro("oo"),degree:"(sympy.pi/180)",true:Ro("true"),false:Ro("false"),null:"None",math:e=>Ro({log:"log",asin:"asin",acos:"acos",atan:"atan",asinh:"asinh",acosh:"acosh",atanh:"atanh",atan2:"atan2",expm1:"expm1",ceil:"ceiling"}[e]??e),abs:Ro("Abs"),random:"random.random()",matrix:e=>`sympy.Matrix(${Oo.matrix(e)})`,det:e=>`sympy.det(${e})`,both:(e,t)=>`sympy.And(${e}, ${t})`,either:(e,t)=>`sympy.Or(${e}, ${t})`,not:e=>`sympy.Not(${e})`,close:(e,t)=>`sympy.Abs((${e}) - (${t})) < sympy.Rational(1, 10**9)`,exactNumber:e=>{const t=/^(\d*)\.(\d+)$/.exec(e);if(!t)return e;const r=10n**BigInt(t[2].length);let[n,o]=[BigInt(t[1]||"0")*r+BigInt(t[2]),r];const s=(e,t)=>t?s(t,e%t):e,a=s(n,o);return[n,o]=[n/a,o/a],1n===o?String(n):`sympy.Rational(${n}, ${o})`},factorial:e=>`sympy.factorial(${e})`,perm:(e,t)=>`sympy.ff(${e}, ${t})`,comb:(e,t)=>`sympy.binomial(${e}, ${t})`,ops:{"/":(e,t)=>Co(t.args[0])&&Co(t.args[1])?`sympy.Rational(${e[0]}, ${e[1]})`:null,"^":(e,t)=>"symbol"===t.args[0].type&&"e"===t.args[0].value?`sympy.exp(${e[1]})`:null,"=":e=>`sympy.Eq(${e[0]}, ${e[1]})`,"===":e=>`sympy.Eq(${e[0]}, ${e[1]})`,"≡":e=>`sympy.Eq(${e[0]}, ${e[1]})`,"≠":e=>`sympy.Ne(${e[0]}, ${e[1]})`,"≠=":e=>`sympy.Ne(${e[0]}, ${e[1]})`,mod:e=>`sympy.Mod(${e[0]}, ${e[1]})`,pmod:(e,t,r)=>{const[n]=t.args;return"op"===n.type&&["≡","="].includes(n.op)?`sympy.Eq(sympy.Mod((${r(n.args[0])}) - (${r(n.args[1])}), ${e[1]}), 0)`:`sympy.Mod(${e[0]}, ${e[1]})`},"!":e=>`sympy.factorial(${e[0]})`,perm:e=>`sympy.ff(${e[0]}, ${e[1]})`,comb:e=>`sympy.binomial(${e[0]}, ${e[1]})`,gcd:e=>2===e.length?`sympy.gcd(${e.join(", ")})`:`sympy.gcd_list([${e.join(", ")}])`,max:e=>`sympy.Max(${e.join(", ")})`,min:e=>`sympy.Min(${e.join(", ")})`,floor:e=>`sympy.floor(${e[0]})`,ceil:e=>`sympy.ceiling(${e[0]})`,csc:e=>`sympy.csc(${e[0]})`,sec:e=>`sympy.sec(${e[0]})`,cot:e=>`sympy.cot(${e[0]})`,ln:e=>`sympy.log(${e[0]})`,log:(e,t)=>"symbol"===t.args[0].type&&"e"===t.args[0].value?`sympy.log(${e[1]})`:`sympy.log(${e[1]}, ${e[0]})`,loglog:e=>`sympy.log(sympy.log(${e[0]}))`,logloglog:e=>`sympy.log(sympy.log(sympy.log(${e[0]})))`,expm1:e=>`(sympy.exp(${e[0]}) - 1)`,root:(e,t)=>"number"===t.args[0].type&&/^\d*[13579]$/.test(t.args[0].value)&&("number"===t.args[1].type||"neg"===t.args[1].op&&"number"===t.args[1].args[0].type)?`sympy.real_root(${e[1]}, ${e[0]})`:`sympy.root(${e[1]}, ${e[0]})`,round:(e,t)=>{const r="number"===t.args[1].type&&"0"===t.args[1].value,n=(e,t)=>{const n=r?`(${e})`:`(${e}) * 10**(${t})`,o=`sympy.Piecewise((${`sympy.floor(${n} + sympy.Rational(1, 2))`}, ${e} >= 0), (${`-sympy.floor(-${n} + sympy.Rational(1, 2))`}, True))`;return r?o:`${o} / 10**(${t})`};return r?Vo(e[0],e=>n(e)):Ho(e[0])&&Ho(e[1])?n(e[0],e[1]):`(lambda _v, _p: ${n("_v","_p")})(${e[0]}, ${e[1]})`},"&":(e,t,r)=>Uo("&",t,r,"sympy.And"),"|":(e,t,r)=>Uo("|",t,r,"sympy.Or"),"\\not":e=>`sympy.Not(${e[0]})`,"\\xor":e=>`sympy.Xor(${e.join(", ")})`,"\\nand":e=>`sympy.Nand(${e.join(", ")})`,"\\implies":e=>`sympy.Implies(${e.join(", ")})`,"\\iff":e=>`sympy.Equivalent(${e.join(", ")})`,"\\nor":e=>`sympy.Nor(${e.join(", ")})`,"?:":e=>`sympy.Piecewise((${e[1]}, ${e[0]}), (${e[2]}, True))`,"∈":(e,t,r)=>`sympy.Contains(${e[0]}, ${Po(t.args[1],r)})`,"∉":(e,t,r)=>`sympy.Not(sympy.Contains(${e[0]}, ${Po(t.args[1],r)}))`,"∪":(e,t,r)=>`sympy.Union(${t.args.map(e=>Po(e,r)).join(", ")})`,"∩":(e,t,r)=>`sympy.Intersection(${t.args.map(e=>Po(e,r)).join(", ")})`,"{}":e=>`sympy.FiniteSet(${e.join(", ")})`,der:(e,t,r)=>{const n=t.args[1];return"op"===n.type&&"="===n.op?`sympy.diff(${e[0]}, ${r(n.args[0])}).subs(${r(n.args[0])}, ${r(n.args[1])})`:`sympy.diff(${e.join(", ")})`},int:(e,t,r)=>{const[n,o,s,a]=t.args,i=t.args.length>=2&&(e=>"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value))(o),l=i?r(o):wr(n)||"x";let c=[];return 4===t.args.length?c=[s,a]:3===t.args.length?c=i?[s]:[o,s]:2!==t.args.length||i||(c=[o]),c=c.map(r),c.length?`sympy.integrate(${r(n)}, (${l}, ${c[0]}, ${c[1]??"sympy.oo"}))`:`sympy.integrate(${r(n)}, ${l})`},lim:(e,t,r)=>{const[n,o]=t.args,s="op"===o?.type&&"→"===o.op;if(t.args.length<2)throw new Error("A limit needs a point: lim(f, x → a)");const[a,i]=s?o.args.map(r):2===t.args.length?[wr(n)||"x",e[1]]:[e[1],e[2]],l="symbol"===t.args[3]?.type?Ko[t.args[3].value]??"":"";return`sympy.limit(${e[0]}, ${a}, ${i}${l})`},"\\sumidx":(e,t,r)=>Do("summation",t,r),"\\prodidx":(e,t,r)=>Do("product",t,r)}};function Do(e,t,r){const[n,o,s]=t.args;return t.args.length<3||"op"!==o.type||"="!==o.op||"symbol"!==o.args[0].type?null:`sympy.${e}(${r(n)}, (${r(o.args[0])}, ${r(o.args[1])}, ${r(s)}))`}const Bo={javascript:ko,python:Oo,numpy:To,sympy:Lo},Zo={sqrt:"sqrt",floor:"floor",ceil:"ceil",ln:"log",expm1:"expm1",sin:"sin",cos:"cos",tan:"tan",sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsin:"asin",arccos:"acos",arctan:"atan",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",atan2:"atan2"},Go={csc:"sin",sec:"cos",cot:"tan"},Wo=e=>/^\d+(\.\d+)?$/.test(e),Ho=e=>e.length<=16&&!/[\w.$]\s*\(/.test(e),Xo=(e,t,r)=>/[A-Za-z_]/.test(e)?`(${t} if abs(${r}) < math.inf else ${r})`:t,Vo=(e,t)=>Ho(e)?t(Jo(e)?e:`(${e})`):`(lambda _v: ${t("_v")})(${e})`,Yo=e=>Jo(e)?e:`(${e})`;function Jo(e){if(/^[\w.]+$/.test(e))return!0;const t=/^[\w.$]+\(/.exec(e);if(!t)return!1;for(let r=t[0].length-1,n=0;r<e.length;r++)if("("===e[r])n++;else if(")"===e[r]&&0===--n)return r===e.length-1;return!1}const Ko={r:', "+"',l:', "-"'},Qo=new Set(["<",">","≤","≥","=","===","≠","≠=","∈","∉"]),es={"ℝ":{javascript:e=>`Number.isFinite(${e})`,python:e=>`math.isfinite(${e})`,numpy:e=>`np.isfinite(${e})`},"ℤ":{javascript:e=>`Number.isInteger(${e})`,python:e=>`float(${e}).is_integer()`,numpy:e=>`(np.mod(${e}, 1) == 0)`},"ℕ":{javascript:e=>`(Number.isInteger(${e}) && ${e} > 0)`,python:e=>`(float(${e}).is_integer() and ${e} > 0)`,numpy:e=>`np.logical_and(np.mod(${e}, 1) == 0, ${e} > 0)`}};for(const e of[ko,Oo,jo,No,To,Fo,qo,Lo,Bo,Zo,Go,es,Ko])Object.setPrototypeOf(e,null);const ts=e=>t=>`<mover accent="true">${t}<mo>${e}</mo></mover>`,rs={boxed:e=>`<menclose notation="box">${e}</menclose>`,cancel:e=>`<menclose notation="updiagonalstrike">${e}</menclose>`,overline:ts("¯"),bar:ts("¯"),underline:e=>`<munder accentunder="true">${e}<mo>_</mo></munder>`,vec:ts("→"),hat:ts("^"),widehat:ts("^"),tilde:ts("~"),dot:ts("˙"),ddot:ts("¨")};Object.setPrototypeOf(rs,null);const ns={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"&lt;",">":"&gt;","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","±":"±",mod:"mod","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},os={sin:"sin",cos:"cos",tan:"tan",csc:"csc",sec:"sec",cot:"cot",sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsin:"arcsin",arccos:"arccos",arctan:"arctan",arcsec:"arcsec",arccsc:"arccsc",arccot:"arccot",arcsinh:"arcsinh",arccosh:"arccosh",arctanh:"arctanh",atan2:"atan2",ln:"ln",max:"max",min:"min",gcd:"gcd",det:"det",mean:"mean",round:"round",fixed:"fixed",random:"random"},ss={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};for(const e of[ns,os,ss])Object.setPrototypeOf(e,null);const as={pi:"PI()","π":"PI()",e:"EXP(1)",tau:"(2 * PI())","τ":"(2 * PI())","∞":"'Infinity'","-∞":"'-Infinity'",true:"TRUE",false:"FALSE",null:"NULL"},is={...as,"∞":"9e999","-∞":"-9e999",tau:"(2 * PI())","τ":"(2 * PI())"},ls={sqrt:"SQRT",abs:"ABS",floor:"FLOOR",ceil:"CEIL",ln:"LN",sin:"SIN",cos:"COS",tan:"TAN",cot:"COT",sinh:"SINH",cosh:"COSH",tanh:"TANH",arcsin:"ASIN",arccos:"ACOS",arctan:"ATAN",arcsinh:"ASINH",arccosh:"ACOSH",arctanh:"ATANH",atan2:"ATAN2",max:"GREATEST",min:"LEAST",gcd:"GCD",random:"RANDOM","!":"FACTORIAL"},cs={der:"a derivative",int:"an integral",lim:"a limit","\\sumidx":"a sum to n","\\prodidx":"a product to n","∪":"a union of sets","∩":"an intersection of sets"},us={"+":"+","-":"-","*":"*","/":"/","=":"=","===":"=","≠":"<>","≠=":"<>","<":"<",">":">","≤":"<=","≥":">="},ps={"()":["(",")"],"{}":["(",")"],"[]":["ARRAY[","]"],"(]":["(",")"],"[)":["(",")"]},hs={"!":"a factorial",gcd:"gcd",perm:"permutations (perm)",comb:"combinations (comb)","±":"±",pm:"±",_:"an index into a list","→":"→",pmatrix:"a matrix",bmatrix:"a matrix",vmatrix:"a determinant",det:"a determinant"},fs={max:"MAX",min:"MIN"},ms={csc:"SIN",sec:"COS",cot:"TAN"},gs={"ℝ":e=>`(ABS(${e}) < 'Infinity')`,"ℤ":e=>`(${e} = TRUNC(${e}))`,"ℕ":e=>`(${e} = TRUNC(${e}) AND ${e} > 0)`};for(const e of[as,is,ls,us,ps,fs,ms,gs,cs,hs])Object.setPrototypeOf(e,null);const ds={pi:"PI()","π":"PI()",e:"EXP(1)",tau:"(2*PI())","τ":"(2*PI())","°":"(PI()/180)",true:"TRUE",false:"FALSE"},$s={sqrt:"SQRT",abs:"ABS",floor:"INT",ln:"LN",det:"MDETERM",sin:"SIN",cos:"COS",tan:"TAN",sinh:"SINH",cosh:"COSH",tanh:"TANH",arcsin:"ASIN",arccos:"ACOS",arctan:"ATAN",arcsinh:"ASINH",arccosh:"ACOSH",arctanh:"ATANH",round:"ROUND",fixed:"FIXED",perm:"PERMUT",comb:"COMBIN",gcd:"GCD","!":"FACT","\\not":"NOT","&":"AND","|":"OR"},ys={csc:"SIN",sec:"COS",cot:"TAN"},bs={"=":"=","===":"=","≡":"=","≠":"<>","≠=":"<>","<":"<",">":">","≤":"<=","≥":">="},ws={sum:"SUM",prod:"PRODUCT",mean:"AVERAGE",max:"MAX",min:"MIN","\\:median":"MEDIAN","\\:stdev":"STDEVP","\\:count":"COUNT"},xs={der:"a derivative",int:"an integral",lim:"a limit","\\sumidx":"a sum to n","\\prodidx":"a product to n",pm:"±","±":"±","∪":"∪","∩":"∩","→":"→"};for(const e of[ds,$s,ys,bs,ws,xs])Object.setPrototypeOf(e,null);const vs={data:new Float32Array([1,1,1,1]),width:1,height:1},_s={data:new Float32Array([0,0,0,0]),width:1,height:1},Es={cover:0,fit:1,stretch:2,tile:3};function As(e){return Es[e??"cover"]??0}function zs(e,t){return e-t*Math.floor(e/t)}const Ms=(e,t)=>e<0?0:e>t?t:e;function ks(e,t,r,n,o,s){const a=Math.floor(n),i=Math.floor(o),l=n-a,c=o-i,u=Ms(a,t-1),p=Ms(a+1,t-1),h=Ms(i,r-1),f=Ms(i+1,r-1),m=4*(h*t+u),g=4*(h*t+p),d=4*(f*t+u),$=4*(f*t+p);for(let t=0;t<4;t++){const r=e[m+t]+(e[g+t]-e[m+t])*l,n=e[d+t]+(e[$+t]-e[d+t])*l;s[t]=r+(n-r)*c}return s}function Os(e,t,r){const n=Math.min(Math.max(Math.ceil(e),0),t),o=[];for(let e=-n;e<=n;e++)r(e)&&o.push(e);return o}function js(e,t,r,n,o,s,a,i,l=0,c=n){const u=new Float32Array(r*n*3),p=s.length,h=Int32Array.from(s),f=Float64Array.from(a??s.map(()=>1)),m="x"===o?r:n,g=new Int32Array(p);for(let n=l;n<c;n++)for(let s=0;s<r;s++){const a="x"===o?s:n;for(let e=0;e<p;e++){let i=a+h[e];i=i<0?0:i>=m?m-1:i,g[e]=("x"===o?n*r+i:i*r+s)*t}let l=0,c=0,d=0;for(let t=0;t<p;t++){const r=g[t],n=f[t];l+=e[r]*n,c+=e[r+1]*n,d+=e[r+2]*n}const $=3*(n*r+s);u[$]=l/i,u[$+1]=c/i,u[$+2]=d/i}return u}function Ss(e,t,r,n,o,s,a,i=0,l=n){const c=new Float32Array(r*n*3),u="x"===o?r:n,p="x"===o?n:r,h=a-s+1,f=(e,t)=>"x"===o?e*r+t:t*r+e,m=e=>e<0?0:e>=u?u-1:e,[g,d]="x"===o?[i,l]:[0,p],[$,y]="x"===o?[0,u]:[i,l];for(let r=g;r<d;r++){let n=0,o=0,i=0;for(let l=$+s;l<=$+a;l++){const s=f(r,m(l))*t;n+=e[s],o+=e[s+1],i+=e[s+2]}for(let l=$;l<y;l++){const u=3*f(r,l);c[u]=n/h,c[u+1]=o/h,c[u+2]=i/h;const p=f(r,m(l+s))*t,g=f(r,m(l+a+1))*t;n+=e[g]-e[p],o+=e[g+1]-e[p+1],i+=e[g+2]-e[p+2]}}return c}function Ns(e,t,r,n,o,s,a,i,l=0,c=n){const u=new Float32Array(r*n*3),p="x"===o?r:n;for(let n=l;n<c;n++)for(let l=0;l<r;l++){const c="x"===o?l:n;let h=a,f=a,m=a;for(let a=0;a<s.length;a++){let u=c+s[a];u=u<0?0:u>=p?p-1:u;const g=("x"===o?n*r+u:u*r+l)*t;i?(e[g]>h&&(h=e[g]),e[g+1]>f&&(f=e[g+1]),e[g+2]>m&&(m=e[g+2])):(e[g]<h&&(h=e[g]),e[g+1]<f&&(f=e[g+1]),e[g+2]<m&&(m=e[g+2]))}const g=3*(n*r+l);u[g]=h,u[g+1]=f,u[g+2]=m}return u}const Is=(e,t,r)=>e+t*r,Ts=(e,t)=>t>e?t:e,Rs=(e,t)=>t<e?t:e;function Cs(e,t,r,n=0,o=r){const s=new Float32Array(t*r*3);for(let r=n*t;r<o*t;r++)s[3*r]=e[4*r],s[3*r+1]=e[4*r+1],s[3*r+2]=e[4*r+2];return s}const Fs=(e,t,r,n)=>[Math.max(0,e-r),Math.min(n,t+r)];function qs(e,t,r,n,o,s,a,i){const l=Os(s,i,e=>Math.abs(e)<=s);if(!l.length)return Cs(e,t,r,n,o);const c=l[0],u=l[l.length-1];if(1===a.length)return Ss(e,4,t,r,a[0],c,u,n,o);const[p,h]=Fs(n,o,u,r);return Ss(Ss(e,4,t,r,"x",c,u,p,h),3,t,r,"y",c,u,n,o)}function Ps(e,t,r,n,o,s,a,i){if(!(s>0))return Cs(e,t,r,n,o);const l=3*s,c=Os(l,i,e=>Math.abs(e)<=l),u=c.map(e=>Math.exp(-e*e/(2*s*s))),p=u.reduce((e,t)=>e+t,0);if(1===a.length)return js(e,4,t,r,a[0],c,u,p,n,o);const[h,f]=Fs(n,o,c[c.length-1],r);return js(js(e,4,t,r,"x",c,u,p,h,f),3,t,r,"y",c,u,p,n,o)}function Us(e,t,r,n,o,s,a,i){const l=Os(s,fn.square,e=>Math.abs(e)<=s);if(!l.length)return new Float32Array(t*r*3).fill(a);const[c,u]=Fs(n,o,l[l.length-1],r);return Ns(Ns(e,4,t,r,"x",l,a,i,c,u),3,t,r,"y",l,a,i,n,o)}function Ls(e,t,r,n,o,s){const a=function(e,t,r){const n=new Float32Array(t*r);for(let o=0;o<t*r;o++)n[o]=.299*e[4*o]+.587*e[4*o+1]+.114*e[4*o+2];return n}(e,t,r),i=new Float32Array(t*r);for(let e=n;e<o;e++)for(let n=0;n<t;n++){const o=(o,s)=>a[Ms(e+s,r-1)*t+Ms(n+o,t-1)];i[e*t+n]=s(o)}return i}const Ds=e=>e(1,-1)+2*e(1,0)+e(1,1)-(e(-1,-1)+2*e(-1,0)+e(-1,1)),Bs=e=>e(-1,1)+2*e(0,1)+e(1,1)-(e(-1,-1)+2*e(0,-1)+e(1,-1)),Zs=e=>4*e(0,0)-e(-1,0)-e(1,0)-e(0,-1)-e(0,1),Gs=e=>.5+e(-1,-1)-e(1,1),Ws=e=>Math.hypot(Ds(e),Bs(e));function Hs(e,t,r,n,o,s,a,i,l,c,u){for(let p=0;p<3;p++){let h=i,f=0;for(const i of s)for(const c of s){const s=a?a(i,c):1;h=l(h,e[4*(Ms(o+c,r-1)*t+Ms(n+i,t-1))+p],s),f+=s}c[p]=u?u(h,f):h}return c}function Xs(e,t,r,n,o,s,a,i,l){for(let c=0;c<3;c++){let u=0,p=0;for(const l of a){const a=i?i(l):1,h="x"===s?Ms(n+l,t-1):n;u+=e[4*(("y"===s?Ms(o+l,r-1):o)*t+h)+c]*a,p+=a}l[c]=u/p}return l}const Vs=(e,t,r,n,o)=>{const s=4*(n*t+r);return o[0]=e[s],o[1]=e[s+1],o[2]=e[s+2],o};const Ys=e=>e<.04045?e/12.92:Math.pow((e+.055)/1.055,2.4),Js=e=>(e=Math.max(e,0))<.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055,Ks=(e,t,r,n,o)=>{const s=n===e?(t-r)/o:n===t?2+(r-e)/o:4+(e-t)/o;return s/6-Math.floor(s/6)},Qs=(e,t)=>{const r=Math.abs(6*(e+t-Math.floor(e+t))-3);return Math.min(Math.max(r-1,0),1)};const ea=e=>e<.008856?7.787*e+16/116:Math.cbrt(e),ta=e=>e<.206893?(e-16/116)/7.787:e*e*e;var ra=Object.freeze({__proto__:null,BLANK:vs,CLEAR:_s,at:function(e,t,r){return Number(e[t][r])},at_blur:function(e,t,r,n,o,s,a){return Hs(e,t,r,n,o,Os(s,fn.square,e=>Math.abs(e)<=s),null,0,Is,a,(e,t)=>e/t)},at_blurx:function(e,t,r,n,o,s,a){return Xs(e,t,r,n,o,"x",Os(s,fn.line,e=>Math.abs(e)<=s),null,a)},at_blury:function(e,t,r,n,o,s,a){return Xs(e,t,r,n,o,"y",Os(s,fn.line,e=>Math.abs(e)<=s),null,a)},at_dilate:function(e,t,r,n,o,s,a){return Hs(e,t,r,n,o,Os(s,fn.square,e=>Math.abs(e)<=s),null,0,Ts,a)},at_erode:function(e,t,r,n,o,s,a){return Hs(e,t,r,n,o,Os(s,fn.square,e=>Math.abs(e)<=s),null,1,Rs,a)},at_gaussian:function(e,t,r,n,o,s,a){if(!(s>0))return Vs(e,t,n,o,a);const i=3*s;return Hs(e,t,r,n,o,Os(i,fn.square,e=>Math.abs(e)<=i),(e,t)=>Math.exp(-(e*e+t*t)/(2*s*s)),0,Is,a,(e,t)=>e/t)},at_gaussianx:function(e,t,r,n,o,s,a){if(!(s>0))return Vs(e,t,n,o,a);const i=3*s;return Xs(e,t,r,n,o,"x",Os(i,fn.line,e=>Math.abs(e)<=i),e=>Math.exp(-e*e/(2*s*s)),a)},at_gaussiany:function(e,t,r,n,o,s,a){if(!(s>0))return Vs(e,t,n,o,a);const i=3*s;return Xs(e,t,r,n,o,"y",Os(i,fn.line,e=>Math.abs(e)<=i),e=>Math.exp(-e*e/(2*s*s)),a)},at_sharpen:function(e,t,r,n,o,s,a){const i=(e,n)=>4*(Ms(n,r-1)*t+Ms(e,t-1)),l=i(n,o),c=i(n-1,o),u=i(n+1,o),p=i(n,o-1),h=i(n,o+1);for(let t=0;t<3;t++)a[t]=e[l+t]+s*(4*e[l+t]-e[c+t]-e[u+t]-e[p+t]-e[h+t]);return a},col_fromhsl:function(e,t,r,n){const o=(1-Math.abs(2*r-1))*t;return n[0]=r-.5*o+o*Qs(e,0),n[1]=r-.5*o+o*Qs(e,2/3),n[2]=r-.5*o+o*Qs(e,1/3),n},col_fromhsv:function(e,t,r,n){return n[0]=r*(1+(Qs(e,0)-1)*t),n[1]=r*(1+(Qs(e,2/3)-1)*t),n[2]=r*(1+(Qs(e,1/3)-1)*t),n},col_fromlab:function(e,t,r,n){const o=(100*e+16)/116,s=o-256*(r-.5)/200,a=.95047*ta(o+256*(t-.5)/500),i=ta(o),l=1.08883*ta(s),c=Math.min(Math.max(3.2404542*a-1.5371385*i-.4985314*l,0),1),u=Math.min(Math.max(-.969266*a+1.8760108*i+.041556*l,0),1),p=Math.min(Math.max(.0556434*a-.2040259*i+1.0572252*l,0),1);return n[0]=Js(c),n[1]=Js(u),n[2]=Js(p),n},col_fromlinear:function(e,t,r,n){return n[0]=Js(e),n[1]=Js(t),n[2]=Js(r),n},col_fromoklab:function(e,t,r,n){let o=e+.3963377774*(t-=.5)+.2158037573*(r-=.5),s=e-.1055613458*t-.0638541728*r,a=e-.0894841775*t-1.291485548*r;o*=o*o,s*=s*s,a*=a*a;const i=Math.min(Math.max(4.0767416621*o-3.3077115913*s+.2309699292*a,0),1),l=Math.min(Math.max(-1.2684380046*o+2.6097574011*s-.3413193965*a,0),1),c=Math.min(Math.max(-.0041960863*o-.7034186147*s+1.707614701*a,0),1);return n[0]=Js(i),n[1]=Js(l),n[2]=Js(c),n},col_fromycbcr:function(e,t,r,n){return t-=.5,r-=.5,n[0]=e+1.402*r,n[1]=e-.344136*t-.714136*r,n[2]=e+1.772*t,n},col_tohsl:function(e,t,r,n){const o=Math.max(e,t,r),s=Math.min(e,t,r),a=o-s,i=.5*(o+s);return n[0]=a>0?Ks(e,t,r,o,a):0,n[1]=a>0?a/(1-Math.abs(2*i-1)):0,n[2]=i,n},col_tohsv:function(e,t,r,n){const o=Math.max(e,t,r),s=o-Math.min(e,t,r);return n[0]=s>0?Ks(e,t,r,o,s):0,n[1]=o>0?s/o:0,n[2]=o,n},col_tolab:function(e,t,r,n){const o=Ys(e),s=Ys(t),a=Ys(r),i=ea((.4124564*o+.3575761*s+.1804375*a)/.95047),l=ea(.2126729*o+.7151522*s+.072175*a),c=ea((.0193339*o+.119192*s+.9503041*a)/1.08883);return n[0]=(116*l-16)/100,n[1]=.5+500*(i-l)/256,n[2]=.5+200*(l-c)/256,n},col_tolinear:function(e,t,r,n){return n[0]=Ys(e),n[1]=Ys(t),n[2]=Ys(r),n},col_tooklab:function(e,t,r,n){const o=Ys(e),s=Ys(t),a=Ys(r),i=Math.cbrt(.4122214708*o+.5363325363*s+.0514459929*a),l=Math.cbrt(.2119034982*o+.6806995451*s+.1073969566*a),c=Math.cbrt(.0883024619*o+.2817188376*s+.6299787005*a);return n[0]=.2104542553*i+.793617785*l-.0040720468*c,n[1]=.5+1.9779984951*i-2.428592205*l+.4505937099*c,n[2]=.5+.0259040371*i+.7827717662*l-.808675766*c,n},col_toycbcr:function(e,t,r,n){const o=.299*e+.587*t+.114*r;return n[0]=o,n[1]=.5+.5643*(r-o),n[2]=.5+.7132*(e-o),n},convolve:function(e,t,r,n,o,s,a,i,l,c,u,p,h,f,m){const g=(e,s)=>4*(Ms(o+s,r-1)*t+Ms(n+e,t-1)),d=[[s,-1,-1],[a,0,-1],[i,1,-1],[l,-1,0],[c,0,0],[u,1,0],[p,-1,1],[h,0,1],[f,1,1]];for(let t=0;t<3;t++){let r=0;for(const[n,o,s]of d)r+=n*e[g(o,s)+t];m[t]=r}return m},factorial:function(e){let t=1;for(let r=2;r<=170&&!(r>e);r++)t*=r;return t},fmod:zs,gcd:function(e,t){e=Math.abs(e),t=Math.abs(t);for(let r=0;r<64&&0!==t;r++){const r=zs(e,t);e=t,t=r}return e},perm:function(e,t){let r=1;for(let n=0;n<170&&!(n>=t);n++)r*=e-n;return r},picture:function(e,t,r,n,o,s,a,i,l,c,u,p,h){let f,m;0===c?f=m=Math.max(n/t,o/r):1===c?f=m=Math.min(n/t,o/r):2===c?(f=n/t,m=o/r):f=m=1,f*=s,m*=s;const g=u+.5-a*n,d=p+.5-i*o,$=Math.cos(l),y=Math.sin(l);let b=($*g+y*d)/f+.5*t,w=($*d-y*g)/m+.5*r;if(3===c)b=zs(b,t),w=zs(w,r);else if(b<0||w<0||b>t||w>r)return h[0]=h[1]=h[2]=h[3]=0,h;return ks(e,t,r,b-.5,w-.5,h)},placeCode:As,plane_blur:function(e,t,r,n,o,s){return qs(e,t,r,n,o,s,["x","y"],fn.square)},plane_blurx:function(e,t,r,n,o,s){return qs(e,t,r,n,o,s,["x"],fn.line)},plane_blury:function(e,t,r,n,o,s){return qs(e,t,r,n,o,s,["y"],fn.line)},plane_dilate:function(e,t,r,n,o,s){return Us(e,t,r,n,o,s,0,!0)},plane_emboss:function(e,t,r,n,o){return Ls(e,t,r,n,o,Gs)},plane_erode:function(e,t,r,n,o,s){return Us(e,t,r,n,o,s,1,!1)},plane_gaussian:function(e,t,r,n,o,s){return Ps(e,t,r,n,o,s,["x","y"],fn.square)},plane_gaussianx:function(e,t,r,n,o,s){return Ps(e,t,r,n,o,s,["x"],fn.line)},plane_gaussiany:function(e,t,r,n,o,s){return Ps(e,t,r,n,o,s,["y"],fn.line)},plane_laplacian:function(e,t,r,n,o){return Ls(e,t,r,n,o,Zs)},plane_sharpen:function(e,t,r,n,o,s){const a=new Float32Array(t*r*3);for(let i=n;i<o;i++)for(let n=0;n<t;n++){const o=(e,n)=>4*(Ms(n,r-1)*t+Ms(e,t-1)),l=o(n,i),c=o(n-1,i),u=o(n+1,i),p=o(n,i-1),h=o(n,i+1);for(let r=0;r<3;r++)a[3*(i*t+n)+r]=e[l+r]+s*(4*e[l+r]-e[c+r]-e[u+r]-e[p+r]-e[h+r])}return a},plane_sobel:function(e,t,r,n,o){return Ls(e,t,r,n,o,Ws)},plane_sobelx:function(e,t,r,n,o){return Ls(e,t,r,n,o,Ds)},plane_sobely:function(e,t,r,n,o){return Ls(e,t,r,n,o,Bs)},random:function(e,t,r,n){const o=43758.5453*Math.sin(12.9898*(e+.5)+78.233*(r-t-.5)+37.719*n);return o-Math.floor(o)},root:function(e,t){return 2===e?Math.sqrt(t):3===e?Math.sign(t)*Math.pow(Math.abs(t),1/3):Math.pow(t,1/e)},round:function(e,t){const r=Math.pow(10,t);return Math.sign(e)*Math.floor(Math.abs(e)*r+.5)/r},sample:ks,sampleOrZero:function(e,t,r,n,o,s){const a=n+.5,i=o+.5;return a<0||i<0||a>t||i>r?(s[0]=s[1]=s[2]=s[3]=0,s):ks(e,t,r,n,o,s)},scratch:function(){return new Float64Array(4)},smoothstep:function(e,t,r){const n=Math.min(Math.max((r-e)/(t-e),0),1);return n*n*(3-2*n)}});const na="\\:",oa=Object.keys(ra).filter(e=>"function"==typeof ra[e]),sa=e=>Object.assign(Object.create(null),e),aa=sa({r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"}),ia=sa({pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)","°":"(Math.PI / 180)"}),la=sa({sqrt:1,abs:1,floor:1,ceil:1,ln:"log",sin:1,cos:1,tan:1,arcsin:"asin",arccos:"acos",arctan:"atan",sinh:1,cosh:1,tanh:1,arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",sign:1,exp:1,exp2:e=>`Math.pow(2, ${e})`,log2:1,expm1:e=>`(Math.exp(${e}) - 1)`,loglog:e=>`Math.log(Math.log(${e}))`,logloglog:e=>`Math.log(Math.log(Math.log(${e})))`,csc:e=>`(1 / Math.sin(${e}))`,sec:e=>`(1 / Math.cos(${e}))`,cot:e=>`(1 / Math.tan(${e}))`,fract:e=>`(${e} - Math.floor(${e}))`,radians:e=>`(${e} * 0.017453292519943295)`,degrees:e=>`(${e} * 57.29577951308232)`,inversesqrt:e=>`(1 / Math.sqrt(${e}))`,arcsec:e=>`Math.acos(1 / ${e})`,arccsc:e=>`Math.asin(1 / ${e})`,arccot:e=>`(Math.PI / 2 - Math.atan(${e}))`,atan2:(e,t)=>`Math.atan2(${e}, ${t})`,pow:(e,t)=>`Math.pow(${e}, ${t})`,mod:(e,t)=>`(${e} - ${t} * Math.floor(${e} / ${t}))`,step:(e,t)=>`(${t} < ${e} ? 0 : 1)`,clamp:(e,t,r)=>`Math.min(Math.max(${e}, ${t}), ${r})`,mix:(e,t,r)=>`(${e} + (${t} - ${e}) * ${r})`,smoothstep:(e,t,r)=>`$h_smoothstep(${e}, ${t}, ${r})`}),ca=sa({atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3});const ua=sa({blur:3,blurx:3,blury:3,gaussian:3,gaussianx:3,gaussiany:3,dilate:3,erode:3,sharpen:3,sobel:1,sobelx:1,sobely:1,laplacian:1,emboss:1}),pa=(e,t)=>({kind:e,c:t}),ha=e=>pa("f",[e]),fa=e=>pa("b",[e]),ma=e=>1===e.length?ha(e[0]):pa("v",e),ga=(e,t=0)=>"b"===e.kind?`(${e.c[0]} ? 1 : 0)`:"f"===e.kind?e.c[0]:e.c[t]??e.c[0],da=e=>"v"===e.kind?e.c.length:1;class $a extends Error{}function ya(e){if(e.blendKept)return{blend:!0,source:""};const t=e.params??{},r=new Set([...Object.keys(e.placements??{}),"source","selection"]),n=new ba(t,r,e.space??"srgb");n.graphics=new Set(Object.keys(e.graphics??{})),n.bind=sa(e.bind??{});const o="string"==typeof e.color?{rgba:e.color}:e.color,s=(n,o)=>un(Tr(n,{names:[...sn,...Object.keys(e.placements??{})],values:[...en,...Object.keys(t)],blocks:null}),r,{whole:o});for(const e of["rgba","rgb","r","g","b","a"]){if(!o[e])continue;let t;try{t=s(o[e],"rgba"===e)}catch(e){throw new $a(e.message)}n.channel(e,t)}const a=n.source();!function(e,t={}){if("string"!=typeof e)throw new bo("generated code must be a string");const r=e;for(const t of Ao)e=e.split(t).join("Math.abs");const n=!1!==t.keywords,o=t.variables instanceof RegExp?t.variables:new Set(t.variables??[]),s=e=>o instanceof RegExp?o.test(e):o.has(e),a=t.indexable instanceof RegExp?t.indexable:null;let i=null,l=0;const c=e=>{throw new bo(`not allowed in a formula: ${e}`)},u=()=>i&&("id"===i.type||"num"===i.type||"str"===i.type||"p"===i.type&&(")"===i.value||"]"===i.value||"}"===i.value));for(;l<e.length;){const r=e.slice(l),o=/^\s+/.exec(r);if(o){l+=o[0].length;continue}(r.startsWith("/*")||r.startsWith("//")||r.startsWith("\x3c!--")||r.startsWith("--\x3e"))&&c("a comment");const p=/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(r);if(p&&(!i||"id"!==i.type||!/[\w$]$/.test(e[l-1]??""))){i={type:"num",value:p[0]},l+=p[0].length;continue}if('"'===r[0]){!1===t.strings&&c("a string");const e=/^"(?:[^"\\\n\r\u2028\u2029]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/.exec(r);e||c('a string that is not a plain "…" literal'),u()&&c("a string right after a value"),i={type:"str",value:e[0]},l+=e[0].length;continue}const h=/^[A-Za-z_$][\w$]*/.exec(r);if(h){const e=h[0];if(i&&"p"===i.type&&"."===i.value){const t=i.owner;(t&&vo[t]?vo[t].has(e):xo.has(e)&&!wo.has(e))||c(`.${e}`)}else _o.has(e)||n&&Eo.has(e)||s(e)||c(`the name "${e}"`);i={type:"id",value:e,member:Boolean(i&&"p"===i.type&&"."===i.value)},l+=e.length;continue}const f=zo.find(e=>r.startsWith(e));f||c(`"${r[0]}"`),Mo.has(f)&&(n||c(`an assignment ("${f}")`),i&&"id"===i.type&&i.member&&c(`an assignment to .${i.value}`)),"["!==f||!u()||a&&"id"===i.type&&s(i.value)&&a.test(i.value)||c("indexing with [ ]");const m={type:"p",value:f};"."===f&&(u()||c('a "." here'),m.owner="id"===i.type&&vo[i.value]?i.value:null),i=m,l+=f.length}}(a,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const i=new Function(...n.parameters(),a);return{source:a,uses:n.uses,pictures:[...n.pictureNames],run(e){i(...n.arguments(e))}}}class ba{constructor(e,t,r="srgb"){this.params=e,this.pictures=t,this.space="srgb"===r?null:r,this.pre=[],this.body=[],this.n=0,this.uses=new Set,this.pictureNames=new Set,this.perPixel=new Map,this.planes=new Map,this.scratch=0}temp(e,t=this.body){const r="$v"+this.n++;return t.push(`let ${r} = ${e};`),r}keep(e,t=this.body){return pa(e.kind,e.c.map(e=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(e)?e:this.temp(e,t)))}fail(e){throw new $a(e)}leaf(e){if("number"===e.type)return ha(`(${e.value.replace(/\.+$/,"")})`);"string"===e.type&&this.fail("a filter has no text: numbers and colors only");const t=e.value,r=/^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(t);if(r)return ha(`(${r[1]} / 100)`);if("t"===t&&this.uses.add("t"),aa[t])return ha(aa[t]);if("rgb"===t)return ma(["$r","$g","$b"]);if("unchanged"===t)return ha("$u");if("selected"===t)return ha(this.pictureHere("selection").c[0]);if(ia[t])return ha(ia[t]);if("true"===t||"false"===t)return fa(t);if(Object.prototype.hasOwnProperty.call(this.params,t)){const e=`$p_${t}`;return"color"===this.params[t].type?ma([`${e}_0`,`${e}_1`,`${e}_2`]):ha(e)}if(this.pictures.has(t)){const e=this.pictureHere(t);return ma(e.c.slice(0,3))}if(t.startsWith("mz_px_")&&this.pictures.has(t.slice(6)))return this.pictureHere(t.slice(6));this.fail(`unknown name "${t}"`)}pictureHere(e){if(!this.perPixel.has(e)){const t=this.sampler(e,"$px","$py");this.perPixel.set(e,this.keep(t))}return this.perPixel.get(e)}sampler(e,t,r){const n=this.scratchArray();return"source"===e?(this.uses.add("source"),this.body.push(`$h_sample($S, $w, $h, ${t}, ${r}, ${n});`)):(this.pictureNames.add(e),this.body.push(`$h_picture($Q_${e}, $qw_${e}, $qh_${e}, $w, $h, $qz_${e}, $qx_${e}, $qy_${e}, $qa_${e}, $qm_${e}, ${t}, ${r}, ${n});`)),this.space&&"selection"!==e&&this.body.push(`$h_col_to${this.space}(${n}[0], ${n}[1], ${n}[2], ${n});`),ma([0,1,2,3].map(e=>`${n}[${e}]`))}scratchArray(){const e="$T"+this.scratch++;return this.pre.push(`let ${e} = $h_scratch();`),e}value(e){return"op"===e.type?this.op(e):this.leaf(e)}op(e){const{op:t,args:r}=e,n=t.startsWith(na)?t.slice(2):null;if(null!==n)return this.call(n,r,e);const o=()=>r.map(e=>this.value(e));switch(t){case"+":case"-":case"*":case"/":{const[e,r]=o();return this.componentwise([e,r],(e,r)=>`(${e} ${t} ${r})`)}case"neg":return this.componentwise(o(),e=>`(-${e})`);case"^":return this.power(r);case"mod":return this.componentwise(o(),la.mod);case"<":case">":case"≤":case"≥":{const[e,r]=o(),n={"≤":"<=","≥":">="}[t]??t;return fa(`(${ga(e)} ${n} ${ga(r)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[e,r]=o(),n=Math.max(da(e),da(r)),s=Array.from({length:n},(t,n)=>`${ga(e,n)} === ${ga(r,n)}`).join(" && ");return fa("≠"===t||"≠="===t?`!(${s})`:`(${s})`)}case"≈":{const[e,t]=o();return fa(`(Math.abs(${ga(e)} - ${ga(t)}) < 1e-5)`)}case"&":{const[e,t]=o();return fa(`(${this.truth(e)} && ${this.truth(t)})`)}case"|":{const[e,t]=o();return fa(`(${this.truth(e)} || ${this.truth(t)})`)}case"\\xor":{const[e,t]=o();return fa(`(${this.truth(e)} !== ${this.truth(t)})`)}case"\\nand":{const[e,t]=o();return fa(`!(${this.truth(e)} && ${this.truth(t)})`)}case"\\nor":{const[e,t]=o();return fa(`!(${this.truth(e)} || ${this.truth(t)})`)}case"\\implies":{const[e,t]=o();return fa(`(!${this.truth(e)} || ${this.truth(t)})`)}case"\\iff":{const[e,t]=o();return fa(`(${this.truth(e)} === ${this.truth(t)})`)}case"\\not":{const[e]=o();return fa(`!${this.truth(e)}`)}case"?:":return this.ternary(r);case"max":case"min":return this.componentwise(o(),(...e)=>`Math.${t}(${e.join(", ")})`);case"sum":return this.componentwise(o(),(...e)=>`(${e.join(" + ")})`);case"prod":return this.componentwise(o(),(...e)=>`(${e.join(" * ")})`);case"mean":return this.componentwise(o(),(...e)=>`((${e.join(" + ")}) / ${e.length})`);case"()":case"[]":case"{}":case"(]":case"[)":{const e=o().flatMap(e=>"b"===e.kind?[ga(e)]:e.c.map((t,r)=>ga(e,r)));return e.length>4&&this.fail("a color has at most 4 values (r, g, b, a)"),ma(e)}case"!":return this.componentwise(o(),e=>`$h_factorial(${e})`);case"perm":return this.componentwise(o(),(e,t)=>`$h_perm(${e}, ${t})`);case"comb":return this.componentwise(o(),(e,t)=>`($h_perm(${e}, ${t}) / $h_factorial(${t}))`);case"gcd":return this.componentwise(o(),(...e)=>e.reduce((e,t)=>`$h_gcd(${e}, ${t})`));case"round":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`$h_round(${e}, ${t})`)}case"log":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`(Math.log(${t}) / Math.log(${e}))`)}case"root":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`$h_root(${e}, ${t})`)}case"∈":case"∉":{const t=function(e){const[t,r]=e.args;if("op"!==r.type||"setbuilder"!==r.op)return null;let[n,o]=r.args,s=null;"op"===n.type&&"∈"===n.op&&([n,s]=n.args);const a=e=>"symbol"===e.type&&e.value===n.value?t:"op"===e.type?{...e,args:e.args.map(a)}:e,i=s?{type:"op",op:"&",args:[{type:"op",op:"∈",args:[t,s]},a(o)]}:a(o);return"∉"===e.op?{type:"op",op:"\\not",args:[i]}:i}(e);return t?this.value(t):this.membership(e)}case"random":return this.random();case"evaluated":return this.value(function(e){const[t,r,n,o]=e.args,s=(e,t)=>"symbol"===e.type&&e.value===r.value?t:"op"===e.type?{...e,args:e.args.map(e=>s(e,t))}:e;return{type:"op",op:"-",args:[s(t,o),s(t,n)]}}(e));case"_":{const[e,t]=r;if("symbol"===e.type&&("number"===t.type||"symbol"===t.type))return this.leaf({type:"symbol",value:`${e.value}_${t.value}`});break}}if(la[t])return this.builtin(t,o());this.fail(`"${t}" isn't available in a filter`)}truth(e){return"b"===e.kind?e.c[0]:`(${ga(e)} !== 0)`}componentwise(e,t){const r=e.map(da),n=Math.max(...r),o=new Set(r.filter(e=>e>1));o.size>1&&this.fail(`can't combine vectors of ${[...o].join(" and ")} values`);const s=Array.from({length:n},(r,n)=>t(...e.map(e=>ga(e,n))));return this.keep(ma(s))}builtin(e,t){const r=la[e];if(ca[e]&&t.length!==ca[e]&&this.fail(`${e}() takes ${ca[e]} values`),"function"==typeof r)return this.componentwise(t,r);const n=1===r?e:r;return this.componentwise(t,(...e)=>`Math.${n}(${e.join(", ")})`)}power([e,t]){const r="number"===t.type&&/^-?\d+$/.test(t.value)?Number(t.value):null,n=this.keep(this.value(e)),o=e=>this.componentwise([n],t=>Array(e).fill(t).join(" * "));return 0===r?this.componentwise([n],()=>"1"):null!==r&&r>=1&&r<=4?o(r):null!==r&&r<=-1&&r>=-4?this.componentwise([o(-r)],e=>`(1 / ${e})`):"symbol"===e.type&&"e"===e.value?this.componentwise([this.value(t)],e=>`Math.exp(${e})`):"number"===e.type&&"2"===e.value?this.componentwise([this.value(t)],e=>`Math.pow(2, ${e})`):this.componentwise([n,this.value(t)],(e,t)=>`Math.pow(${e}, ${t})`)}ternary([e,t,r]){const n=this.truth(this.value(e)),o=e=>"symbol"===e.type&&"unchanged"===e.value;let s=o(t)?null:this.value(t),a=o(r)?null:this.value(r);const i=e=>"b"===e.kind?fa("($u > 0.5)"):"f"===e.kind?ha("$u"):ma(["$k0","$k1","$k2","$k3"].slice(0,4===e.c.length?4:3));if(!s&&!a)return ha("$u");if(s||(s=i(a)),a||(a=i(s)),"b"===s.kind&&"b"===a.kind)return fa(this.temp(`(${n} ? ${s.c[0]} : ${a.c[0]})`));const l=Math.max(da(s),da(a)),c=Array.from({length:l},(e,t)=>this.temp(`(${n} ? ${ga(s,t)} : ${ga(a,t)})`));return ma(c)}membership(e){const[t,r]=e.args,n=ga(this.value(t)),o="∉"===e.op;let s;if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,t]=r.args.map(e=>ga(this.value(e)));s=`(${n} ${"["===r.op[0]?">=":">"} ${e} && ${n} ${"]"===r.op[1]?"<=":"<"} ${t})`}else"op"===r.type&&"{}"===r.op?s=r.args.length?`(${r.args.map(e=>`${n} === ${ga(this.value(e))}`).join(" || ")})`:"false":"symbol"===r.type&&["ℝ","ℤ","ℕ"].includes(r.value)?s={"ℝ":`Number.isFinite(${n})`,"ℤ":`Number.isInteger(${n})`,"ℕ":`(Number.isInteger(${n}) && ${n} > 0)`}[r.value]:this.fail("∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ");return fa(o?`!${s}`:s)}random(){return this.uses.add("random"),ha(this.temp("$h_random($px, $py, $h, ++$seed)"))}call(e,t,r){const n=()=>t.map(e=>this.value(e));if(e.startsWith("mz_sample_")){const t=e.slice(10),[r,o]=n(),[s,a]=o?[ga(r),ga(o)]:[ga(r,0),ga(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${s}, ${a}, ${e});`),this.keep(ma([0,1,2,3].map(t=>`${e}[${t}]`)))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(this.sampler(t,s,a))}if(e.startsWith("mz_at_")){const t=e.slice(6),[r,o]=n(),[s,a]=o?[ga(r),ga(o)]:[ga(r,0),ga(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${s}, ${a}, ${e});`),ma([0,1,2].map(t=>`${e}[${t}]`))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(ma(this.sampler(t,s,a).c.slice(0,3)))}if(e.startsWith("mz_width_")||e.startsWith("mz_height_")){const t=e.replace(/^mz_(width|height)_/,"");return this.pictureNames.add(t),ha(e.startsWith("mz_width_")?`$qw_${t}`:`$qh_${t}`)}switch(e){case"pixel":{const[e,t]=n().map(e=>ga(e)),r=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${e}, ${t}, ${r});`),this.keep(ma([0,1,2,3].map(e=>`${r}[${e}]`)))}case"red":case"green":case"blue":case"alpha":case"luma":{let r;2===t.length?r=this.call("pixel",t):1===t.length?r=this.value(t[0]):this.fail(`${e}() takes a color, or a position px, py`);const n={red:0,green:1,blue:2,alpha:3}[e];return"luma"===e?ha(`(${ga(r,0)} * 0.299 + ${ga(r,1)} * 0.587 + ${ga(r,2)} * 0.114)`):"alpha"===e&&3===da(r)?ha("1"):ha(ga(r,n))}case"length":{const[e]=n();return ha(`Math.sqrt(${e.c.map((t,r)=>`${ga(e,r)} * ${ga(e,r)}`).join(" + ")})`)}case"distance":{const[e,t]=n(),r=this.componentwise([e,t],(e,t)=>`(${e} - ${t})`);return ha(`Math.sqrt(${r.c.map(e=>`${e} * ${e}`).join(" + ")})`)}case"dot":{const[e,t]=n(),r=Math.max(da(e),da(t));return ha(`(${Array.from({length:r},(r,n)=>`${ga(e,n)} * ${ga(t,n)}`).join(" + ")})`)}case"normalize":{const[e]=n(),t=this.temp(`Math.sqrt(${e.c.map((t,r)=>`${ga(e,r)} * ${ga(e,r)}`).join(" + ")})`);return this.componentwise([e],e=>`(${e} / ${t})`)}case"cross":{const[e,t]=n();3===da(e)&&3===da(t)||this.fail("cross() takes two colors (3 values each)");const[r,o,s]=e.c,[a,i,l]=t.c;return this.keep(ma([`(${o} * ${l} - ${s} * ${i})`,`(${s} * ${a} - ${r} * ${l})`,`(${r} * ${i} - ${o} * ${a})`]))}case"convolve":{const e=n().map(e=>ga(e));9!==e.length&&this.fail("convolve() takes 9 numbers: the 3×3 kernel, row by row");const t=this.scratchArray();return this.body.push(`$h_convolve($I, $w, $h, $px, $py, ${e.join(", ")}, ${t});`),ma([0,1,2].map(e=>`${t}[${e}]`))}case"mz_zoom":case"mz_shift":case"mz_rotate":case"mz_crop":case"mz_tile":case"mz_flipx":case"mz_flipy":return this.geometry(e.slice(3),n().map(e=>ga(e)));case"tolinear":case"fromlinear":case"tohsv":case"fromhsv":case"tohsl":case"fromhsl":case"tolab":case"fromlab":case"tooklab":case"fromoklab":case"toycbcr":case"fromycbcr":{const t=n(),r=3===t.length?t.map(e=>ga(e)):[0,1,2].map(e=>ga(t[0],e));1!==t.length&&3!==t.length&&this.fail(`${e}() takes a color`);const o=this.scratchArray();return this.body.push(`$h_col_${e}(${r.join(", ")}, ${o});`),this.keep(ma([0,1,2].map(e=>`${o}[${e}]`)))}case"random":return this.random();case"exp":case"exp2":case"log2":case"sign":case"fract":case"radians":case"degrees":case"inversesqrt":case"pow":case"mod":case"step":case"clamp":case"mix":case"smoothstep":case"abs":case"floor":case"ceil":case"sqrt":case"sin":case"cos":case"tan":return this.builtin(e,n());case"asin":return this.builtin("arcsin",n());case"acos":return this.builtin("arccos",n());case"atan":return 2===t.length?this.builtin("atan2",n()):this.builtin("arctan",n());case"log":return this.builtin("ln",n());case"max":case"min":return this.componentwise(n(),(...t)=>`Math.${e}(${t.join(", ")})`)}if(ua[e])return this.neighborhood(e,t);this.fail(`unknown function "${e}"`)}geometry(e,t){const r=(e,t)=>this.keep(ma([e,t]));switch(e){case"zoom":{const[e,n="0.5",o="0.5"]=t,s=r(`(${n} * $w - 0.5)`,`(${o} * $h - 0.5)`);return r(`(${s.c[0]} + ($px - ${s.c[0]}) / ${e})`,`(${s.c[1]} + ($py - ${s.c[1]}) / ${e})`)}case"shift":{const[e,n]=t;return r(`($h_fmod($px - ${e} + 0.5, $w) - 0.5)`,`($h_fmod($py - ${n} + 0.5, $h) - 0.5)`)}case"rotate":{const[e,n="0.5",o="0.5"]=t,s=r(`(${n} * $w - 0.5)`,`(${o} * $h - 0.5)`),a=r(`($px - ${s.c[0]})`,`($py - ${s.c[1]})`),i=this.keep(ma([`Math.cos(${e})`,`Math.sin(${e})`]));return r(`(${s.c[0]} + ${i.c[0]} * ${a.c[0]} + ${i.c[1]} * ${a.c[1]})`,`(${s.c[1]} + ${i.c[0]} * ${a.c[1]} - ${i.c[1]} * ${a.c[0]})`)}case"crop":{const[e,n,o,s]=t;return r(`((${e} + (${o} - ${e}) * ($px + 0.5) / $w) * $w - 0.5)`,`((${n} + (${s} - ${n}) * ($py + 0.5) / $h) * $h - 0.5)`)}case"tile":{const[e,n=e]=t;return r(`($h_fmod(($px + 0.5) * ${e}, $w) - 0.5)`,`($h_fmod(($py + 0.5) * ${n}, $h) - 0.5)`)}case"flipx":return r("($w - 1 - $px)","$py");case"flipy":return r("$px","($h - 1 - $py)")}this.fail(`unknown geometry ${e}`)}neighborhood(e,t){const r=ua[e];if(t.every(e=>this.isUniform(e))){const n=t.map(e=>ga(this.uniformValue(e))),o=`${e}(${n.join(",")})`;if(!this.planes.has(o)){const t=`$N${this.planes.size}`;this.pre.push(`let ${t} = $h_plane_${e}($I, $w, $h, $y0, $y1${n.map(e=>`, ${e}`).join("")});`),this.planes.set(o,t)}const s=this.planes.get(o);return 3===r?ma([0,1,2].map(e=>`${s}[$j3 + ${e}]`)):ha(`${s}[$j]`)}const n=t.map(e=>ga(this.value(e)));if(1===r)return ha(this.temp(`$h_at_${e}($I, $w, $h, $px, $py${n.map(e=>`, ${e}`).join("")})`));const o=this.scratchArray();return this.body.push(`$h_at_${e}($I, $w, $h, $px, $py${n.map(e=>`, ${e}`).join("")}, ${o});`),ma([0,1,2].map(e=>`${o}[${e}]`))}isUniform(e){return"number"===e.type||("symbol"===e.type?["w","h","t"].includes(e.value)||Boolean(ia[e.value])||Object.prototype.hasOwnProperty.call(this.params,e.value)&&"color"!==this.params[e.value].type:"op"===e.type&&!e.op.startsWith(na)&&"random"!==e.op&&e.args.every(e=>this.isUniform(e)))}uniformValue(e){const t=this.body;this.body=this.pre;try{return this.value(e)}finally{this.body=t}}channel(e,t){const r="rgba"===e||"rgb"===e?"$gray":`$c${"rgba".indexOf(e)}`;this.body.push(`$u = ${r}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);const n=this.value(t),o=da(n),s=e=>ga(n,e);if("rgba"===e){2===o&&this.fail("a color is one number (gray), three (r, g, b) or four (r, g, b, a) — not two");const e=1===o?[s(0),s(0),s(0),"1"]:3===o?[s(0),s(1),s(2),"1"]:[0,1,2,3].map(s);this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]}; $c3 = ${e[3]};`)}else if("rgb"===e){2===o&&this.fail("a color is one number (gray), three (r, g, b) or four — not two");const e=1===o?[s(0),s(0),s(0)]:[s(0),s(1),s(2)];this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]};`)}else{const t="rgba".indexOf(e),r=1===o?s(0):3===o&&"a"===e?"1":s(t);this.body.push(`$c${t} = ${r};`)}}parameters(){return["$I","$O","$S","$w","$h","$t","$P","$op","$y0","$y1",...[...this.pictureNames].flatMap(e=>[`$Q_${e}`,`$qw_${e}`,`$qh_${e}`,`$qz_${e}`,`$qx_${e}`,`$qy_${e}`,`$qa_${e}`,`$qm_${e}`]),...oa.map(e=>`$h_${e}`)]}arguments(e){const t=[...this.pictureNames];return[e.input,e.output,e.source,e.width,e.height,e.t,e.params,e.opacity,e.y0??0,e.y1??e.height,...t.flatMap(t=>{const r=e.pictures[this.bind?.[t]??t]??(this.graphics?.has(t)?_s:vs),n=e.placements[t]??{};return[r.data,r.width,r.height,Number(n.zoom??1),Number(n.x??.5),Number(n.y??.5),Number(n.angle??0),As(n.place)]}),...oa.map(e=>ra[e])]}source(){const e=Object.entries(this.params).map(([e,t],r)=>"color"===t.type?`let $p_${e}_0 = $P[${r}][0], $p_${e}_1 = $P[${r}][1], $p_${e}_2 = $P[${r}][2];`:`let $p_${e} = $P[${r}];`);return[...e.map(e=>e.replace(/\$P\[(\d+)\]\[(\d)\]/g,"$h_at($P, $1, $2)")),"let $u = 0, $k0 = 0, $k1 = 0, $k2 = 0, $k3 = 0, $seed = 0, $CS = $h_scratch();",...this.pre,"for (let $py = $y0; $py < $y1; $py++) {"," for (let $px = 0; $px < $w; $px++) {"," let $j = $py * $w + $px, $j3 = $j * 3, $j4 = $j * 4;"," let $r = $I[$j4], $g = $I[$j4 + 1], $b = $I[$j4 + 2], $a = $I[$j4 + 3];"," let $c0 = $r, $c1 = $g, $c2 = $b, $c3 = $a;"," let $x = ($px + 0.5) / $w, $y = ($py + 0.5) / $h;",this.space?` $h_col_from${this.space}($r, $g, $b, $CS); let $gray = $CS[0] * 0.299 + $CS[1] * 0.587 + $CS[2] * 0.114;`:" let $gray = $r * 0.299 + $g * 0.587 + $b * 0.114;"," $seed = $t;",...this.body.map(e=>` ${e}`)," $O[$j4] = $r + ($c0 - $r) * $op;"," $O[$j4 + 1] = $g + ($c1 - $g) * $op;"," $O[$j4 + 2] = $b + ($c2 - $b) * $op;"," $O[$j4 + 3] = $a + ($c3 - $a) * $op;"," }","}"].join("\n")}}function wa(e,t={}){const r="float"===t.precision||"half"===t.precision?"float":"byte",n=e.passes.map(e=>ya(e)),o={};let s=null;const a=t.parallelFrom??25e4,i=void 0===t.workers||"auto"===t.workers?function(){const e="undefined"!=typeof navigator&&navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(0,Math.min(8,e-1))}():Number(t.workers);let l=null,c=null,u=new Map;const p={passes:e.passes,get precision(){return r},sources:n.map(e=>e.source),setImage(e,t){"string"!=typeof e&&(t=e,e=null);const r=va(t);return e&&"source"!==e?o[e]=r:s=r,p},draw({t:t=0,canvas:a=null}={}){if(!s)throw new Error("setImage() first");const{width:i,height:l}=s,c=i*l*4;let u=s.data;const p=[];e.passes.forEach((e,a)=>{for(let t=0;t<e.keepInput;t++)p.push(u);const h=new Float32Array(c);if(e.blendKept){const t=p.pop(),r=e.opacity;for(let e=0;e<c;e++)h[e]=t[e]+(u[e]-t[e])*r}else n[a].run({input:u,output:h,source:s.data,width:i,height:l,t:t,params:Object.keys(e.params??{}).map(t=>e.values[t]),opacity:e.opacity,pictures:o,placements:e.placements??{}});"byte"===r&&xa(h),u=h});const h=new Uint8ClampedArray(c);for(let e=0;e<c;e++){const t=u[e];h[e]=t>0?t<1?Math.round(255*t):255:0}const f={data:h,width:i,height:l};return a&&(a.width=i,a.height=l,a.getContext("2d").putImageData(new ImageData(h,i,l),0,0)),f},async drawAsync({t:n=0,canvas:h=null}={}){if(!s)throw new Error("setImage() first");const{width:f,height:m}=s;if(i<2||f*m<a)return p.draw({t:n,canvas:h});c??=async function(e,t,r){const n=new URL(r??"./cpu-worker.js",import.meta.url);let o,s=()=>{};if("undefined"!=typeof Worker&&"undefined"!=typeof window){const e=n.origin===location.origin?n:URL.createObjectURL(new Blob([`import ${JSON.stringify(n.href)};`],{type:"text/javascript"}));e!==n&&(s=()=>URL.revokeObjectURL(e)),o=()=>{const t=new Worker(e,{type:"module"});return{send:e=>t.postMessage(e),on:e=>{t.onmessage=t=>e(t.data),t.onerror=t=>e({id:-1,ok:!1,error:t.message})},close:()=>t.terminate()}}}else try{const{Worker:e}=await(import("node:worker_threads"));o=()=>{const t=new e(n);return{send:e=>t.postMessage(e),on:e=>{t.on("message",e),t.on("error",t=>e({id:-1,ok:!1,error:t.message}))},close:()=>t.terminate()}}}catch{return null}const a=Array.from({length:e},o);let i=1;const l=a.map(()=>new Map);a.forEach((e,t)=>e.on(e=>{if(-1===e.id){for(const[,r]of l[t])r.reject(new Error(e.error));return void l[t].clear()}const r=l[t].get(e.id);r&&(l[t].delete(e.id),e.ok?r.resolve(e):r.reject(new Error(e.error)))}));const c=(e,t)=>new Promise((r,n)=>{const o=i++;l[e].set(o,{resolve:r,reject:n}),a[e].send({...t,id:o})}),u={size:e,shared:Ea(),ask:c,broadcast:e=>Promise.all(a.map((t,r)=>c(r,e))),close:()=>{a.forEach(e=>e.close());for(const e of l){for(const[,t]of e)t.reject(new Error("The runner was disposed of while drawing"));e.clear()}}};try{await u.broadcast({type:"init",passes:t.map(({fragment:e,...t})=>t)})}catch(e){throw u.close(),e}finally{s()}return u}(i,e.passes,t.workerUrl).catch(()=>!1);const g=c,d=await g;if(g!==c)throw new Error("The runner was disposed of while drawing");if(l=d,!d)return p.draw({t:n,canvas:h});const $=f*m*4,y=()=>d.shared?new Float32Array(new SharedArrayBuffer(4*$)):new Float32Array($);for(const[e,t]of[["source",s],...Object.entries(o)])u.get(e)!==t&&(await d.broadcast({type:"picture",name:e,picture:d.shared?Aa(t):t}),u.set(e,t));let b=d.shared?Aa(s).data:s.data;const w=[];for(let t=0;t<e.passes.length;t++){const o=e.passes[t];for(let e=0;e<o.keepInput;e++)w.push(b);const s=y();if(o.blendKept){const e=w.pop();for(let t=0;t<$;t++)s[t]=e[t]+(b[t]-e[t])*o.opacity;"byte"===r&&xa(s)}else{const e=Object.keys(o.params??{}).map(e=>o.values[e]),a=_a(m,d.size),i=await Promise.all(a.map(([a,i],l)=>d.ask(l,{type:"run",pass:t,input:b,output:d.shared?s:null,width:f,height:m,t:n,params:e,opacity:o.opacity,placements:o.placements??{},y0:a,y1:i,quantize:"byte"===r})));d.shared||i.forEach((e,t)=>s.set(e.band,a[t][0]*f*4))}b=s}const x=new Uint8ClampedArray($);for(let e=0;e<$;e++){const t=b[e];x[e]=t>0?t<1?Math.round(255*t):255:0}const v={data:x,width:f,height:m};return h&&(h.width=f,h.height=m,h.getContext("2d").putImageData(new ImageData(x,f,m),0,0)),v},get workers(){return l?l.size:0},dispose(){s=null;for(const e of Object.keys(o))delete o[e];c&&c.then(e=>e&&e.close()),c=null,l=null,u=new Map}};return p}function xa(e){for(let t=0;t<e.length;t++){const r=e[t];e[t]=r>0?r<1?Math.round(255*r)/255:1:0}}function va(e){if(e&&e.data&&e.width&&e.height){const t=e.data,r=t instanceof Float32Array||t instanceof Float64Array?1:1/255,n=new Float32Array(e.width*e.height*4);for(let e=0;e<n.length;e++)n[e]=t[e]*r;return{data:n,width:e.width,height:e.height}}if("undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas){const t=e.naturalWidth||e.videoWidth||e.width,r=e.naturalHeight||e.videoHeight||e.height;if(!t||!r)throw new Error("setImage: the picture has no size yet (not loaded?)");const n=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r})).getContext("2d",{willReadFrequently:!0});return n.drawImage(e,0,0,t,r),va(n.getImageData(0,0,t,r))}throw new Error("setImage: give ImageData or { data, width, height }")}function _a(e,t){const r=[];for(let n=0;n<t;n++){const o=Math.floor(e*n/t),s=Math.floor(e*(n+1)/t);s>o&&r.push([o,s])}return r}const Ea=()=>"undefined"!=typeof SharedArrayBuffer&&("undefined"==typeof crossOriginIsolated||!0===crossOriginIsolated);function Aa(e){if(e.data.buffer instanceof(globalThis.SharedArrayBuffer??Object))return e;if(e.shared)return e.shared;const t=new Float32Array(new SharedArrayBuffer(e.data.byteLength));return t.set(e.data),e.shared={data:t,width:e.width,height:e.height},e.shared}const za=[{name:"Wave",group:"Shape & motion",description:"Rows slide back and forth as t advances",params:{amplitude:{default:8,min:0,max:40},wavelength:{default:10,min:1,max:60},speed:{default:5,min:1,max:30}},color:"pixel(px + amplitude sin(py / wavelength + t / speed), py)"},{name:"Invert",group:"Color & tone",color:"(1 - r, 1 - g, 1 - b)"},{name:"Grayscale",group:"Color & tone",color:"gray"},{name:"Threshold",group:"Color & tone",params:{cutoff:.5},color:"if gray > cutoff then 1 else 0"},{name:"Posterize",group:"Color & tone",params:{levels:{default:4,min:2,max:16,step:1}},color:"min(floor(rgb * levels) / (levels - 1), 1)"},{name:"Brightness & contrast",group:"Color & tone",params:{brightness:{default:0,min:-.5,max:.5},contrast:{default:1,min:0,max:3}},color:"(rgb - 0.5) contrast + 0.5 + brightness"},{name:"Tint",group:"Color & tone",params:{tint:[1,.85,.7]},color:"rgb * tint"},{name:"Sepia",group:"Color & tone",color:"(0.393r + 0.769g + 0.189b, 0.349r + 0.686g + 0.168b, 0.272r + 0.534g + 0.131b)"},{name:"Color circle",group:"Color & tone",description:"Black and white, except a soft circle that keeps its color",params:{across:{default:.5,min:0,max:1,label:"where, across"},down:{default:.5,min:0,max:1,label:"where, down"},radius:{default:.3,min:0,max:1},softness:{default:.08,min:0,max:.5}},notes:["The color stays inside a circle and fades to gray over the softness. Sizes are parts of the picture's shorter side, so it stays round.",{param:"across"},{param:"down"},{param:"radius"},{param:"softness"}],color:"mix((gray, gray, gray), rgb, 1 - smoothstep(radius, radius + softness, distance((px, py), (across w, down h)) / min(w, h)))"},{name:"Vignette",group:"Color & tone",params:{strength:{default:1.6,min:0,max:4}},color:"rgb * (1 - strength ((x - 0.5)^2 + (y - 0.5)^2))"},{name:"Sobel edges",group:"Blur & edges",description:"How fast the brightness changes",params:{gain:{default:2,min:.2,max:10}},color:"gain sobel()"},{name:"Edge map",group:"Blur & edges",description:"White where an edge is stronger than the cutoff",params:{cutoff:{default:.3,min:0,max:2}},color:"if sobel() > cutoff then 1 else 0"},{name:"Outline",group:"Blur & edges",description:"Ink lines over the color",params:{gain:{default:3,min:0,max:10}},color:"rgb (1 - gain sobel())"},{name:"Box blur",group:"Blur & edges",params:{radius:{default:2,min:0,max:8,step:1}},color:"blur(radius)"},{name:"Gaussian blur",group:"Blur & edges",description:"Computed in two passes, across then down, so it can be wide",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Canny edges",group:"Blur & edges",description:"Thin, clean edge lines: smooth, gradient, thinning, two thresholds, hysteresis — a chain",steps:[{params:{sigma:{default:1.4,min:.5,max:4}},color:"gaussian(sigma)"},{color:"(min(sobel() / 4, 1), floor(fract((atan2(sobely(), sobelx()) + π/8) / π) 4) / 4, 0)"},{color:"if green(px, py) < 0.125 then (if r >= red(px - 1, py) & r >= red(px + 1, py) then r else 0) else if green(px, py) < 0.375 then (if r >= red(px + 1, py + 1) & r >= red(px - 1, py - 1) then r else 0) else if green(px, py) < 0.625 then (if r >= red(px, py - 1) & r >= red(px, py + 1) then r else 0) else (if r >= red(px - 1, py + 1) & r >= red(px + 1, py - 1) then r else 0)"},{params:{low:{default:.08,min:0,max:.5},high:{default:.2,min:0,max:1}},color:"if r > high then 1 else if r > low then 0.5 else 0"},"if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else 0"]},{name:"Sharpen",group:"Blur & edges",params:{amount:{default:.6,min:0,max:3}},color:"sharpen(amount)"},{name:"Unsharp mask",group:"Blur & edges",description:"The picture plus what a blur removes",params:{amount:{default:1.5,min:0,max:5},sigma:{default:2,min:.5,max:4}},color:"rgb + amount (rgb - gaussian(sigma))"},{name:"Bloom",group:"Blur & edges",description:"Bright parts glow",params:{amount:{default:.8,min:0,max:3},sigma:{default:3,min:.5,max:4},cutoff:{default:.6,min:0,max:1}},color:"rgb + amount max(gaussian(sigma) - cutoff, 0)"},{name:"Emboss",group:"Blur & edges",color:"emboss()"},{name:"Dilate",group:"Blur & edges",description:"Light areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"dilate(radius)"},{name:"Erode",group:"Blur & edges",description:"Dark areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"erode(radius)"},{name:"3×3 kernel",group:"Blur & edges",description:"Your own convolution; the default is a sharpen",params:{k1:{default:0,min:-8,max:8},k2:{default:-1,min:-8,max:8},k3:{default:0,min:-8,max:8},k4:{default:-1,min:-8,max:8},k5:{default:5,min:-8,max:8},k6:{default:-1,min:-8,max:8},k7:{default:0,min:-8,max:8},k8:{default:-1,min:-8,max:8},k9:{default:0,min:-8,max:8}},color:"convolve(k1, k2, k3, k4, k5, k6, k7, k8, k9)"},{name:"Pixelate",group:"Shape & motion",params:{size:{default:8,min:1,max:32,step:1}},color:"pixel(floor(px / size) size, floor(py / size) size)"},{name:"Mirror",group:"Shape & motion",color:"pixel(w - px, py)"},{name:"Scanlines",group:"Shape & motion",params:{period:{default:4,min:2,max:16,step:1}},color:"if py mod period < period / 2 then rgb else rgb * 0.6"},{name:"Pulse",group:"Shape & motion",description:"Brightness breathes with t",params:{speed:{default:6,min:1,max:30},depth:{default:.25,min:0,max:1}},color:"rgb (1 - depth + depth sin(t / speed))"},{name:"Chroma key",group:"Color & tone",description:"Replaces one color with another",params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1},background:[.1,.1,.4]},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Through a mask",group:"Other pictures",description:"Put this last: the steps above show only where the mask is light",images:{mask:{description:"light where the effect shows"}},color:"mix(source, rgb, luma(mask))"},{name:"Mix",group:"Other pictures",description:"Fade towards another picture",images:["overlay"],params:{amount:.5},color:"mix(rgb, overlay, amount)"},{name:"Masked mix",group:"Other pictures",images:{overlay:{},mask:{description:"light where the overlay shows"}},color:"mix(rgb, overlay, luma(mask))"},{name:"Multiply",group:"Other pictures",images:["overlay"],color:"rgb * overlay"},{name:"Screen",group:"Other pictures",images:["overlay"],color:"1 - (1 - rgb)(1 - overlay)"},{name:"Overlay blend",group:"Other pictures",images:["overlay"],color:"if gray < 0.5 then 2 rgb overlay else 1 - 2 (1 - rgb)(1 - overlay)"},{name:"Difference",group:"Other pictures",images:["overlay"],color:"abs(rgb - overlay)"},{name:"Alpha over",group:"Other pictures",description:"A picture with transparency laid on top",images:["overlay"],color:"mix(rgb, overlay, alpha(overlay))"},{name:"Chroma key onto a picture",group:"Other pictures",images:{background:{}},params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1}},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Only inside the selection",group:"Other pictures",description:"Put this last: the steps above show only inside what you selected on the picture (everywhere, without a selection)",color:"mix(source, rgb, selected)"},{name:"Only outside the selection",group:"Other pictures",description:"Put this last: the steps above show only outside what you selected",color:"mix(rgb, source, selected)"},{name:"Caption",group:"Text & shapes",description:"Words along the bottom, with a soft shadow; change them under the step",graphics:{title:{text:"Your caption here",y:.88}},color:"mix(rgb, title, alpha(title))"},{name:"Poster title",group:"Text & shapes",description:"Big outlined letters across the top",graphics:{title:{text:"BIG TITLE",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.16,y:.14,outline:{color:"#000000",width:.08},shadow:null}},color:"mix(rgb, title, alpha(title))"},{name:"Gradient text",group:"Text & shapes",description:"The letters colored by math: a sunset from left to right",graphics:{title:{text:"Golden hour",font:"Georgia, serif",size:.13,y:.5,shadow:{color:"rgba(0,0,0,0.5)",blur:.2,dx:0,dy:.05}}},color:"mix(rgb, mix((1, 0.35, 0.3), (1, 0.85, 0.25), x), alpha(title))"},{name:"Neon sign",group:"Text & shapes",description:"White letters with a colored glow",graphics:{title:{text:"OPEN",font:"Trebuchet MS, sans-serif",size:.18,y:.5,shadow:{color:"#00e5ff",blur:.45,dx:0,dy:0}}},color:"mix(rgb * 0.6, title, alpha(title))"},{name:"Layered shadow",group:"Text & shapes",description:"Two shadow layers, each with its own filter: a soft glow that darkens and breathes with t, and a hard offset colored by a gradient",graphics:{title:{text:"LAYERS",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.17,y:.5,shadow:null,shadows:[{color:"#000000",blur:.7,dx:0,dy:.08},{color:"#000000",blur:0,dx:.07,dy:.07}]}},color:"mix(mix(mix(rgb, rgb * 0.25, alpha(title_shadow1) (0.7 + 0.3 sin(t / 10))), mix((1, 0.2, 0.6), (0.2, 0.6, 1), x), alpha(title_shadow2)), title, alpha(title))"},{name:"Ink brush",group:"Brushes",description:'Paint in a color; draw on the picture with "draw" under the step',graphics:{brush:{type:"strokes",brush:"round",size:.025}},params:{ink:[.95,.2,.25]},color:"mix(rgb, ink, alpha(brush))"},{name:"Blur brush",group:"Brushes",description:"Paint a blur in — stronger every time a stroke goes over the same place",graphics:{brush:{type:"strokes",brush:"soft",size:.08}},color:"mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush))"},{name:"Darken brush",group:"Brushes",description:"Each pass darkens a little more, like layers of a wash",graphics:{brush:{type:"strokes",brush:"soft",size:.07,flow:.7}},color:"rgb (1 - 0.22 min(4 green(brush), 4))"},{name:"Color reveal brush",group:"Brushes",description:"The picture starts gray; the brush paints its color back",graphics:{brush:{type:"strokes",brush:"soft",size:.1}},color:"mix((gray, gray, gray), rgb, alpha(brush))"},{name:"Fuse brush",group:"Brushes",description:"Paint glows as it goes down, then cools to charcoal (red(brush) is its age)",graphics:{brush:{type:"strokes",brush:"round",size:.02,age:40}},color:"mix(rgb, mix((1, 0.9, 0.5), (0.1, 0.07, 0.06), red(brush)), alpha(brush)) + (1, 0.5, 0.1) alpha(brush) max(0, 1 - 3 red(brush)) 0.6"},{name:"Rainbow brush",group:"Brushes",description:"The color runs round the wheel along the drawing (blue(brush) is how far through it)",graphics:{brush:{type:"strokes",brush:"marker",size:.035}},color:"mix(rgb, fromhsv(blue(brush), 0.85, 1), alpha(brush))"},{name:"Chalk outline",group:"Brushes",description:'Chalk round an object: select it, then "outline the selection" under the step',graphics:{brush:{type:"strokes",brush:"chalk",size:.018,timing:"even",speed:2}},color:"mix(rgb, (0.97, 0.97, 0.92), alpha(brush))"},{name:"Frosted panel",group:"Text & shapes",description:"A rounded panel that blurs and darkens what is behind it — a shape with its own filter",graphics:{panel:{type:"rect",y:.86,w:.9,h:.2,radius:.25}},color:"mix(rgb, gaussian(5) * 0.7, alpha(panel))"},{name:"Spotlight oval",group:"Text & shapes",description:"Darkens everything but a soft oval",graphics:{spot:{type:"ellipse",x:.5,y:.45,w:.45,h:.55,shadow:{color:"#ffffff",blur:.12,dx:0,dy:0}}},color:"mix(rgb * 0.3, rgb, alpha(spot))"},{name:"Scrolling banner",group:"Text & shapes",description:"Text that slides across and wraps round (animated with t)",graphics:{title:{text:"Breaking news · scrolling text · ",size:.07,y:.92}},params:{speed:{default:3,min:-10,max:10}},color:"mix(rgb, shift(title, -speed t, 0), alpha(shift(title, -speed t, 0)))"},{name:"Pulsing title",group:"Text & shapes",description:"Text that grows and shrinks a little (animated with t)",graphics:{title:{text:"Hello!",size:.14,y:.5}},params:{amount:{default:.06,min:0,max:.3}},color:"mix(rgb, zoom(title, 1 + amount sin(t / 8)), alpha(zoom(title, 1 + amount sin(t / 8))))"},{name:"Fade-in title",group:"Text & shapes",description:"Text that fades in over the first frames (animated with t)",graphics:{title:{text:"Once upon a time",font:"Georgia, serif",style:"italic",weight:"normal",size:.09,y:.5}},params:{frames:{default:40,min:1,max:200}},color:"mix(rgb, title, alpha(title) clamp(t / frames, 0, 1))"},{name:"Zoom",group:"Shape & motion",params:{scale:{default:1.5,min:.25,max:4},cx:.5,cy:.5},color:"zoom(scale, cx, cy)"},{name:"Ken Burns",group:"Shape & motion",description:"A slow zoom that drifts across — a still picture that moves",params:{speed:{default:.002,min:0,max:.01},drift:{default:3e-4,min:-.001,max:.001}},color:"zoom(1 + speed t, 0.5 + drift t, 0.45)"},{name:"Scroll",group:"Shape & motion",description:"Slides and wraps around",params:{dx:{default:1,min:-5,max:5},dy:{default:0,min:-5,max:5}},color:"shift(dx t, dy t)"},{name:"Spin",group:"Shape & motion",params:{speed:{default:.01,min:-.05,max:.05}},color:"rotate(speed t)"},{name:"Tile",group:"Shape & motion",params:{n:{default:2,min:1,max:8,step:1}},color:"tile(n)"},{name:"Crop",group:"Shape & motion",description:"A part of the picture, filling the frame",params:{left:.1,top:.1,right:.9,bottom:.9},color:"crop(left, top, right, bottom)"},{name:"Flip",group:"Shape & motion",color:"flipx()"},{name:"Picture in picture",group:"Other pictures",description:"Another picture, fitted small in a corner",images:{inset:{description:"any size: it is fitted whole",place:"fit",zoom:.35,x:.8,y:.78}},color:"mix(rgb, inset, alpha(inset))"},{name:"Moving overlay",group:"Other pictures",description:"Another picture scrolling across at half strength",images:["overlay"],params:{speed:{default:2,min:-10,max:10}},color:"mix(rgb, shift(overlay, speed t, 0), 0.5)"},{name:"Hue shift",group:"Color & tone",description:"Turns every color around the hue wheel (in HSV)",space:"hsv",params:{amount:{default:.1,min:-.5,max:.5}},color:"(fract(r + amount), g, b)"},{name:"Saturation",group:"Color & tone",description:"More or less color (in HSV)",space:"hsv",params:{amount:{default:1.5,min:0,max:3}},color:"(r, clamp(g amount, 0, 1), b)"},{name:"Lightness",group:"Color & tone",description:"Lighter or darker without changing the colors (in Lab)",space:"lab",params:{amount:{default:1.15,min:.5,max:2}},color:"(clamp(r amount, 0, 1), g, b)"},{name:"Vivid",group:"Color & tone",description:"Colorfulness, perceptually even (in OKLab)",space:"oklab",params:{amount:{default:1.6,min:0,max:3}},color:"(r, 0.5 + (g - 0.5) amount, 0.5 + (b - 0.5) amount)"},{name:"Linear-light blur",group:"Blur & edges",description:"A Gaussian in linear light: bright spots stay bright, as a lens does",space:"linear",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Film grain",group:"Color & tone",description:"Noise that changes every frame",params:{amount:{default:.15,min:0,max:.6}},color:"rgb + amount (random() - 0.5)"},{name:"Swirl",group:"Shape & motion",params:{strength:{default:.02,min:0,max:.1}},color:"pixel(w/2 + (px - w/2) cos(strength t gray) - (py - h/2) sin(strength t gray), h/2 + (px - w/2) sin(strength t gray) + (py - h/2) cos(strength t gray))"}],Ma=e=>za.find(t=>t.name===e);za.push({name:"Old film",group:"Chains",description:"Sepia, a vignette and faint scanlines — a chain of three",steps:[Ma("Sepia"),{filter:Ma("Vignette"),with:{strength:1.2}},{filter:Ma("Scanlines"),opacity:.5}]},{name:"Comic",group:"Chains",description:"Bold flat colors with ink lines: a small blur first, so a photo's fine texture isn't inked — a chain of four",steps:[{filter:Ma("Gaussian blur"),with:{sigma:1.6}},{filter:Ma("Vivid"),with:{amount:1.5}},{filter:Ma("Posterize"),with:{levels:4}},{filter:Ma("Outline"),with:{gain:1.2}}]},{name:"Cartoon",group:"Chains",description:"Blur, then flatten the colors, then outline — a chain of three",steps:[{filter:Ma("Gaussian blur"),with:{sigma:1.5}},{filter:Ma("Posterize"),with:{levels:6}},{filter:Ma("Outline"),with:{gain:2}}]},{name:"Dreamy",group:"Chains",description:"A soft glow mixed over the picture",steps:[{filter:Ma("Bloom"),with:{amount:1.2}},{filter:Ma("Gaussian blur"),with:{sigma:2},opacity:.4}]},{name:"Tilt shift",group:"Chains",description:"Blurred where the mask is light — a chain",steps:[{filter:Ma("Gaussian blur"),with:{sigma:4}},Ma("Through a mask")]},{name:"Title card",group:"Chains",description:"A frosted panel with a caption on it — a chain of two",steps:[Ma("Frosted panel"),{filter:Ma("Caption"),with:{title:{text:"A title on a panel",y:.86}}}]},{name:"Color spotlight",group:"Chains",description:"Gray except where the mask is dark — a chain",steps:[Ma("Grayscale"),Ma("Through a mask")]});const ka=za,Oa=()=>"undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas,ja=(e,t)=>"undefined"!=typeof document?Object.assign(document.createElement("canvas"),{width:e,height:t}):new OffscreenCanvas(e,t);function Sa(e){if(e&&"object"==typeof e&&Array.isArray(e.passes))return e;if("string"==typeof e){const t=e.trim().toLowerCase(),r=ka.find(e=>e.name.toLowerCase()===t);return io(r??ho(e))}return io(e)}const Na=4096,Ia=2048;function Ta(e,t,r,n){const o=Math.min(1,n/Math.max(t,r));if(o>=1)return{image:e,width:t,height:r};const s=Math.max(1,Math.round(t*o)),a=Math.max(1,Math.round(r*o));if(Oa()){let n=e;((e=>Boolean(e&&e.data&&e.width&&e.height)&&!("undefined"!=typeof ImageData&&e instanceof ImageData))(e)||"undefined"!=typeof ImageData&&e instanceof ImageData)&&(n=ja(t,r),n.getContext("2d").putImageData((e=>"undefined"!=typeof ImageData&&e instanceof ImageData?e:new ImageData(e.data instanceof Uint8ClampedArray?e.data:Uint8ClampedArray.from(e.data,e.data instanceof Float32Array||e.data instanceof Float64Array?e=>255*e:void 0),e.width,e.height))(e),0,0));const o=ja(s,a),i=o.getContext("2d");return i.imageSmoothingEnabled=!0,i.imageSmoothingQuality="high",i.drawImage(n,0,0,s,a),{image:o,width:s,height:a}}const i=e.data,l=new i.constructor(s*a*4);for(let e=0;e<a;e++){const n=Math.floor(e*r/a),o=Math.max(n+1,Math.floor((e+1)*r/a));for(let r=0;r<s;r++){const a=Math.floor(r*t/s),c=Math.max(a+1,Math.floor((r+1)*t/s)),u=[0,0,0,0];for(let e=n;e<o;e++)for(let r=a;r<c;r++)for(let n=0;n<4;n++)u[n]+=i[4*(e*t+r)+n];const p=(o-n)*(c-a);for(let t=0;t<4;t++)l[4*(e*s+r)+t]=u[t]/p}}return{image:{data:l,width:s,height:a},width:s,height:a}}const Ra=e=>!(e=>"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)(e)||e.complete&&e.naturalWidth?[e.naturalWidth||e.videoWidth||e.displayWidth||e.width||0,e.naturalHeight||e.videoHeight||e.displayHeight||e.height||0]:[0,0],Ca=e=>Boolean(e)&&"object"==typeof e&&Array.isArray(e.passes),Fa=e=>(Array.isArray(e)||ArrayBuffer.isView(e))&&3===e.length&&[...e].every(e=>Number.isFinite(Number(e)));let qa=null;const Pa=new WeakMap;let Ua=0;function La(e){if("string"==typeof e)return`s:${e}`;if(Ca(e))return Pa.has(e)||Pa.set(e,"c:"+Ua++),Pa.get(e);if(e&&"object"==typeof e)try{return`d:${uo(e)}`}catch{return null}return null}const Da=e=>({...e,passes:e.passes.map(e=>({...e,values:{...e.values}}))});function Ba(e,t,r){const n=La(e)&&`${t}|${La(e)}`,o=qa?.runners;if(r&&n&&o?.has(n)){const e=o.get(n);return o.delete(n),o.set(n,e),e}const s=Sa(e),a=Da(s),i=function(e,t={}){const r=function({webgl:e=!1,prefer:t="auto"}={}){return"cpu"===t?{engine:"cpu",reason:"asked for the CPU"}:e?{engine:"gpu",reason:"gpu"===t?"asked for the GPU":"WebGL is here"}:{engine:"cpu",reason:"no WebGL here"}}({webgl:Boolean(t.gl),prefer:t.prefer});if("gpu"===r.engine)try{return{runner:mo(t.gl,e,{precision:t.precision}),...r}}catch(r){if("gpu"===t.prefer)throw r;return{runner:wa(e,t),engine:"cpu",reason:`the GPU refused the shader (${r.message.split("\n")[0]})`}}return{runner:wa(e,t),...r}}(a,{gl:r,prefer:t}),l={compiled:a,source:Ca(e)?s:Da(s),...i};if(r&&n&&"gpu"===i.engine&&(o.set(n,l),o.size>16)){const[e,t]=o.entries().next().value;o.delete(e),t.runner.dispose()}return l}let Za=Promise.resolve();function Ga(e,t,r={}){const n=Za.then(()=>async function(e,t,{params:r={},t:n=0,images:o={},engine:s="auto",canvas:a=null,maxSize:i=null}={}){if(!e)throw new Error("applyFilter: no picture");const[l,c]=Ra(e);if(!l||!c)throw new Error("applyFilter: the picture has no size yet (not loaded?)");if(null!==i&&!(Number(i)>=1))throw new Error(`applyFilter: maxSize is a number of pixels, not ${JSON.stringify(i)}`);if("auto"!==s&&"gpu"!==s&&"cpu"!==s)throw new Error(`applyFilter: engine is 'auto', 'gpu' or 'cpu', not "${s}"`);const u=a?a.getContext("2d"):null;if(a&&!u)throw new Error("applyFilter: `canvas` must be a 2D canvas (this one already has another kind of context)");const p="cpu"!==s?function(){if(qa&&!qa.gl.isContextLost())return qa;if(!Oa())return null;const e=ja(1,1),t=e.getContext("webgl",{preserveDrawingBuffer:!0,premultipliedAlpha:!1});return qa=t?{canvas:e,gl:t,runners:new Map}:null,qa}():null;if("gpu"===s&&!p)throw new Error('applyFilter: no WebGL here (use engine "auto" or "cpu")');const h=Ba(t,"gpu"===s?"gpu":p?"auto":"cpu",p?.gl),{compiled:f,source:m,runner:g}=h,d="gpu"===h.engine,$=d?Math.min(Number(i??Na),p.gl.getParameter(p.gl.MAX_TEXTURE_SIZE)||Na):Number(i??Ia),{image:y,width:b,height:w}=Ta(e,l,c,$);try{const e=new Map(f.passes.flatMap(e=>Object.entries(e.params??{})));for(const[t,n]of Object.entries(r)){if(!e.has(t))throw new Error(`applyFilter: the filter has no knob called "${t}" (it has ${[...e.keys()].join(", ")||"none"})`);if("color"===e.get(t).type?!Fa(n):!Number.isFinite(Number(n))||"object"==typeof n||""===n)throw new Error(`applyFilter: the knob "${t}" needs ${"color"===e.get(t).type?"a color, [r, g, b] with each 0–1":"a number"}, not ${JSON.stringify(n)}`)}const t=Object.entries(f.graphics??{});let s={};if(t.length){const e=t.filter(([,e])=>"strokes"!==e.type).map(([e])=>e);if(!Oa()&&e.length)throw new Error(`applyFilter: this filter draws ${e.join(", ")} (text or shapes), which needs a canvas — there is none here`);s=await Bn(f,b,w,{t:Number.isFinite(n)?n:1/0})}f.passes.forEach((e,t)=>{e.values={...m.passes[t].values},e.opacity=m.passes[t].opacity;for(const[t,n]of Object.entries(r))t in(e.params??{})&&(e.values[t]="color"===e.params[t].type?[...n].map(Number):Number(n))}),g.setImage(y);for(const e of h.given??[])e in o||g.setImage(e,null);h.given=Object.keys(o);for(const[e,t]of Object.entries(o)){const[r,n]=Ra(t);g.setImage(e,r&&n?Ta(t,r,n,$).image:t)}for(const[e,t]of Object.entries(s))g.setImage(e,t);if(d){p.canvas.width=b,p.canvas.height=w,g.draw({t:n});const e=a??ja(b,w);e.width=b,e.height=w;const t=u??e.getContext("2d");return t.clearRect(0,0,b,w),t.drawImage(p.canvas,0,0),e}const i=await g.drawAsync({t:n});if(!Oa()&&!a)return i;const l=a??ja(b,w);return l.width=b,l.height=w,(u??l.getContext("2d")).putImageData(new ImageData(i.data,b,w),0,0),l}finally{d||g.dispose()}}(e,t,r));return Za=n.catch(()=>{}),n}const Wa=new Int32Array(256);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?3988292384^t>>>1:t>>>1;Wa[e]=t}function Ha(e,t){const r=new Uint8Array(12+t.length),n=new DataView(r.buffer);n.setUint32(0,t.length);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);return r.set(t,8),n.setUint32(8+t.length,function(e){let t=-1;for(let r=0;r<e.length;r++)t=Wa[255&(t^e[r])]^t>>>8;return(-1^t)>>>0}(r.subarray(4,8+t.length))),r}function Xa(e,t,r){const n=e+t-r,o=Math.abs(n-e),s=Math.abs(n-t),a=Math.abs(n-r);return o<=s&&o<=a?e:s<=a?t:r}async function Va({width:e,height:t,data:r,palette:n="auto",colors:o=256,dither:s=!0,quantize:a=null}){if("undefined"==typeof CompressionStream)return null;if(!Number.isInteger(e)||!Number.isInteger(t)||e<1||t<1||!r||r.length<e*t*4)throw new Error("encodePng: width and height are whole numbers of pixels, and data holds 4 bytes for each");let i=null;if(("auto"===n||"force"===n)&&(i=function(e){const t=new Map,r=[],n=new Uint8Array(e.length/4);for(let o=0,s=0;o<e.length;o+=4,s++){const a=(e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])>>>0;let i=t.get(a);if(void 0===i){if(256===r.length)return null;i=r.length,t.set(a,i),r.push([e[o],e[o+1],e[o+2],e[o+3]])}n[s]=i}return{palette:r,indices:n}}(r),i&&i.palette.length>o&&(i=null),!i&&"force"===n)){if(!a)throw new Error('encodePng: palette "force" needs a quantize function (the picture has more than `colors` colors)');i=a(r,Math.min(256,Math.max(2,o)),{dither:s,width:e})}const l=[new Uint8Array([137,80,78,71,13,10,26,10])],c=new Uint8Array(13),u=new DataView(c.buffer);let p,h,f;if(u.setUint32(0,e),u.setUint32(4,t),i){const r=i.palette.length;f=r<=2?1:r<=4?2:r<=16?4:8,h="palette",c[8]=f,c[9]=3;const n=Math.ceil(e*f/8);p=new Uint8Array(t*(1+n));for(let r=0;r<t;r++){const t=r*(1+n)+1;for(let n=0;n<e;n++){const o=i.indices[r*e+n];8===f?p[t+n]=o:p[t+(n*f>>3)]|=o<<8-f-n*f%8}}const o=new Uint8Array(3*r),s=new Uint8Array(r);let a=!1;i.palette.forEach(([e,t,r,n],i)=>{o.set([e,t,r],3*i),s[i]=n,n<255&&(a=!0)}),l.push(Ha("IHDR",c),Ha("PLTE",o)),a&&l.push(Ha("tRNS",s))}else{let n=!0;for(let e=3;e<r.length;e+=4)if(r[e]<255){n=!1;break}const o=n?3:4;h=n?"rgb":"rgba",f=8,c[8]=8,c[9]=n?2:6;const s=e*o;p=new Uint8Array(t*(1+s));const a=new Uint8Array(s),i=new Uint8Array(s);for(let l=0;l<t;l++){for(let t=0,s=l*e*4,i=0;t<e;t++,s+=4,i+=o)a[i]=r[s],a[i+1]=r[s+1],a[i+2]=r[s+2],n||(a[i+3]=r[s+3]);const t=l*(1+s);p[t]=4;for(let e=0;e<s;e++)p[t+1+e]=a[e]-Xa(e>=o?a[e-o]:0,i[e],e>=o?i[e-o]:0);i.set(a)}l.push(Ha("IHDR",c))}l.push(Ha("IDAT",await async function(e){if("undefined"==typeof CompressionStream)return null;const t=new CompressionStream("deflate"),r=t.writable.getWriter();return r.write(e),r.close(),new Uint8Array(await new Response(t.readable).arrayBuffer())}(p)),Ha("IEND",new Uint8Array(0)));const m=i?i.palette.length:function(e,t=257){const r=new Set;for(let n=0;n<e.length;n+=4)if(r.add((e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0),r.size>=t)return r.size;return r.size}(r);return{blob:new Blob(l,{type:"image/png"}),kind:h,colors:m,bits:f}}const Ya=e=>e&&e.data&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&"function"!=typeof e.getContext;function Ja(e){if(Ya(e)){const{data:t,width:r,height:n}=e;if(t instanceof Uint8ClampedArray||t instanceof Uint8Array)return{data:t,width:r,height:n};const o=new Uint8ClampedArray(r*n*4),s=t instanceof Float32Array||t instanceof Float64Array?255:1;for(let e=0;e<o.length;e++)o[e]=Math.round(t[e]*s);return{data:o,width:r,height:n}}if(e&&"function"==typeof e.getContext){const t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("This canvas has a WebGL context: pass the 2D canvas applyFilter() returned, or copy it onto one first");return t.getImageData(0,0,e.width,e.height)}throw new Error("Give a canvas or a picture ({ data, width, height })")}async function Ka(e,{type:t="image/png",quality:r,palette:n="auto"}={}){if("image/png"===t){const t=await Va({...Ja(e),palette:n});if(t)return t.blob}const o=Ya(e)?function(e){const{width:t,height:r}=e;let n=null;return"undefined"!=typeof OffscreenCanvas?n=new OffscreenCanvas(t,r):"undefined"!=typeof document&&(n=Object.assign(document.createElement("canvas"),{width:t,height:r})),n?(n.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(e.data),t,r),0,0),n):null}(Ja(e)):e;if(!o)throw new Error(`Saving as ${t} needs a browser (a canvas encodes it); in Node, save as image/png`);return"function"==typeof o.convertToBlob?o.convertToBlob({type:t,quality:r}):new Promise((e,n)=>o.toBlob(r=>r?e(r):n(new Error(`The browser could not encode ${t}`)),t,r))}async function Qa(e,{gifenc:t,delay:r=1e3/30,repeat:n=0,colors:o=256}={}){const s=t&&(t.GIFEncoder?t:t.default);if(!s||"function"!=typeof s.GIFEncoder)throw new Error("encodeGif needs gifenc: import * as gifenc from 'gifenc' and pass { gifenc }");const a=s.GIFEncoder();let i=null,l=0;for await(const t of e){let{data:e,width:c,height:u}=Ja(t);if((e.byteOffset||e.byteLength!==e.buffer.byteLength)&&(e=e.slice()),i&&(i[0]!==c||i[1]!==u))throw new Error(`Frame ${l+1} is ${c} × ${u}; the first was ${i[0]} × ${i[1]}`);i=[c,u];const p=ei(e),h=p?"rgba4444":"rgb565",f=s.quantize(e,Math.max(2,Math.min(256,o)),{format:h,oneBitAlpha:p}),m=s.applyPalette(e,f,h),g={palette:f,delay:Math.round(r),repeat:n};if(p){const e=f.findIndex(e=>e.length>3&&0===e[3]);e>=0&&Object.assign(g,{transparent:!0,transparentIndex:e})}a.writeFrame(m,c,u,g),l++}if(!l)throw new Error("encodeGif: no frames");return a.finish(),new Blob([a.bytes()],{type:"image/gif"})}function ei(e){for(let t=3;t<e.length;t+=4)if(e[t]<255)return!0;return!1}export{Na as MAX_SIZE,Ia as MAX_SIZE_CPU,Ga as applyFilter,Qa as encodeGif,Va as encodePng,Ja as pictureData,Ka as toBlob,Sa as toCompiled};
1
+ /* qblur 0.3.0 — Copyright (c) 2025-2026 Robert Wilcox — MIT license — https://qblur.com — MathZetta inside: Copyright (c) 2025 Robert Wilcox, MIT license */
2
+ function e(e){const n=new Map;for(const[t,o,s]of e)if(t&&""!==t.trim()&&(n.set(t,o),!s))for(const e of r(t))n.get(e)||n.set(e,o);const o=new Map;for(const e of n.keys()){let t=o;for(let r=0;r<e.length;r++)t.has(e[r])||t.set(e[r],new Map),t=t.get(e[r]);t.end=!0}return e=>{let r="",s=0;for(;s<e.length;){const a=t(o,e,s);a?(r+=n.get(e.slice(s,s+a)),s+=a):r+=e[s++]}return r}}function t(e,t,r){let n=e,o=0;for(let e=r;e<t.length&&(n=n.get(t[e]),n);e++)n.end&&(o=e-r+1);return o}function r(e){const t=new Set([e.toLowerCase(),e.toUpperCase(),n(e)]);return t.delete(e),t}function n(e){let t="",r=!1;for(const n of e){const e=n>="a"&&n<="z",o=n>="A"&&n<="Z";t+=!r&&e?n.toUpperCase():n,r=e||o}return t}const o=100,s="",a="",i={[s]:"dot",[a]:"cross"},l="",c={ln:o,log:o,loglog:o,logloglog:o,sqrt:o,sqrtpow:o,pow:o,expm1:o,der:o,lim:o,int:o,round:o,fixed:o,floor:o,ceil:o,abs:o,random:o,sum:o,prod:o,"\\sumidx":o,"\\prodidx":o,perm:o,comb:o,"\\perm":o,"\\comb":o,"\\binom":o,max:o,min:o,gcd:o,mean:o,pmatrix:o,bmatrix:o,vmatrix:o,det:o,sin:o,cos:o,tan:o,csc:o,sec:o,cot:o,sinh:o,cosh:o,tanh:o,evaluated:o,setbuilder:o,arcsin:o,arccos:o,arctan:o,arcsec:o,arccsc:o,arccot:o,arcsinh:o,arccosh:o,arctanh:o,atan2:o,_:o,"!":90,"\\not":85,"^":80,"*":70,"/":70,frac:70,[s]:70,[a]:70,mod:45,"+":50,"-":50,"±":50,"→":38,"<":34,">":34,"≤":34,"≥":34,"∈":32,"∉":32,"∪":33,"∩":33,"=":30,"==":30,"===":30,"≠":30,"≠=":30,"!==":30,"≈":30,"≡":30,pmod:2,"&":20,"\\xor":19,"|":18,"∨":18,"\\nor":17,"\\nand":17,"\\implies":15,"\\iff":14,"?:":10,"?":9,",":5},u=e=>Object.prototype.hasOwnProperty.call(c,e),p=new Set(["^","?:","?","log"]),h=["(","{","["],f=[")","}","]"];function m(e,t=!1){return"string"==typeof e&&(t?d:g).test(e)}const g=/^(?:\d+\.?\d*|\.\d+|\d*\.\d+\.\.)$/,d=/^-?(?:\d+\.?\d*|\.\d+|\d*\.\d+\.\.)$/;for(const e of[c])Object.setPrototypeOf(e,null);const $=[["Math.atan2","atan2"],["Math.atan2(","atan2("],["atan2","atan2"],["\\atan2","atan2"],["Math.random()","random(1)"],["random.random()","random(1)"],["Math.log2(","log_{2}("],["Math.log10(","log_{10}("],["Math.log2","log_{2}"],["Math.log10","log_{10}"],["Math.log_{","log_{"],["Math.log","log_{e}"],["Math.ln","log_{e}"],["Math.abs(","abs("],["Math.fabs(","abs("],["Math.gcd(","gcd("],["Math.comb(","comb("],["Math.perm(","perm("],["Math.fmod(","mod("],["Math.exp(","(e)^("],["Math.exp2(","(2)^("],["Math.expm1(","expm1("],["Math.pow(","pow("],["**","^"],["Math.floor(","floor("],["Math.ceil(","ceil("],["Math.round(","round("],["Math.max(","max("],["Math.min(","min("],["Math.pi","π"],["Math.PI","π"],["math.Pi","π"],["Math.e","e"],["math.E","e"],["Math.sqrt2","sqrt(2)"],["Math.sqrt(","sqrt("],["Math.SQRT1_2","sqrt(1/2)"],["Math.SQRT1_{2}","sqrt(1/2)"],["Math.SQRT2","sqrt(2)"],["cbrt","sqrt[3]"],["Math.cbrt","sqrt[3]"],["Sqrt","sqrt"],["Root","sqrt"],["\\sqrt{","sqrt{"],["\\frac","frac"],["\\dfrac","frac"],["\\tfrac","frac"],["\\cfrac","frac"],["\\lim","lim"],["\\sum","\\sumidx"],["\\prod","\\prodidx"],["\\displaystyle",""],["\\textstyle",""],["\\,",""],["\\;",""],["\\!",""],["\\quad",""],["\\qquad",""],["\\lvert","|"],["\\rvert","|"],["\\vert","|"],["^\\prime","′"],["^{\\prime}","′"],["^{\\prime\\prime}","′′"],["\\prime","′"],["\\approx","≈"],["\\varepsilon","ε"],["\\vartheta","θ"],["\\varphi","φ"],["\\cup","∪"],["\\mathbb{R}","ℝ",!0],["\\mathbb{N}","ℕ",!0],["\\mathbb{Z}","ℤ",!0],["\\mathbb{Q}","ℚ",!0],["\\mathbb{C}","ℂ",!0],["\\cap","∩"],["\\%","%"],["\\barwedge","\\nand"],["∧","&"],["¬","!"],["↑","\\nand"],["↓","\\nor"],["∫","\\int"],["∑","\\sum"],["∏","\\prod"],["asin(","arcsin("],["acos(","arccos("],["atan(","arctan("],["asinh(","arcsinh("],["acosh(","arccosh("],["atanh(","arctanh("],["asec(","arcsec("],["acsc(","arccsc("],["acot(","arccot("],["\\sqrt*","sqrt"],["Log","log"],["Max","max"],["Min","min"],["Floor","floor"],["Ceil","ceil"],["Round","round"],["Abs","abs"],["Sum","sum"],["Prod","prod"],["Mean","mean"],["Avg","mean"],["Average","mean"],["Gcd","gcd"],["Math.LOG2e","log_{2}(e)"],["Math.LOG10e","log_{10}(e)"],["Math.LN2","log_{e}(2)"],["Math.LN10","log_{e}(10)"],["Math.tau","τ"],["infinity","∞"],["\\infty","∞"],["\\cdot",s],["\\times",a],["×",a],["·",s],["÷","/"],["->","→"],["\\to","→"],["\\max","max"],["\\min","min"],["\\det","det"],["^{\\top}","^{T}",!0],["^\\top","^T",!0],["^{\\intercal}","^{T}",!0],["^\\intercal","^T",!0],["^{\\mathsf{T}}","^{T}",!0],["^{\\mathrm{T}}","^{T}",!0],["product(","prod("],["log[","log_["],["\\log[","log_["],["\\log_","log_"],["\\log","log_{e}"],["\\ln","log_{e}"],["log(","log_{e}("],["ln(","log_{e}("],...["","\\"].flatMap(e=>["(","{"].flatMap(t=>[2,3,4,5,6,7,8,9,10].map(r=>[`${e}log${r}${t}`,`log_{${r}}${t}`]))),["\\log_10","log_{10}"],["log_10","log_{10}"],["\\log\\log","\\loglog"],["\\log\\log\\log","\\logloglog"],["\\loglog","\\loglog"],["\\logloglog","\\logloglog"],["loglog(","loglog("],["\\exp","e^"],["exp(","e^("],["\\div","/"],["\\int","\\int"],["\\in","∈"],["\\not\\in","∉"],["\\notin","∉"],["\\nor"," \\nor "],["\\xor"," \\xor "],["\\nand"," \\nand "],["\\Longrightarrow"," \\implies "],["\\Rightarrow"," \\implies "],["\\implies"," \\implies "],["⇒"," \\implies "],["⟹"," \\implies "],["\\Longleftrightarrow"," \\iff "],["\\Leftrightarrow"," \\iff "],["\\iff"," \\iff "],["⇔"," \\iff "],["⟺"," \\iff "],["\\uparrow"," \\nand "],["\\downarrow"," \\nor "],["\\oplus"," \\xor "],["\\lor","∨"],["\\land","&"],["Not"," \\not "],["&&","&"],["\\neg"," \\not "],["\\not"," \\not "],["\\rightarrow","→"],["\\limits_","_"],["\\pmod"," pmod "],["\\equiv","≡"],["\\mod"," mod "],["\\bmod"," mod "],["\\pm","±"],["\\plusmn","±"],["\\neq","≠"],["\\ne","≠"],["!==","≠="],["==","="],["=...=","==="],["!=","≠"],["\\gt",">"],["\\lt","<"],["\\ge","≥"],["\\geq","≥"],[">=","≥"],["\\le","≤"],["\\leq","≤"],["<=","≤"],["<>","≠"],["\\lparen","("],["\\rparen",")"],["\\left(","("],["\\right)",")"],["\\left[","["],["\\right]","]"],["\\left{","{"],["\\right}","}"],["\\left\\{","{"],["\\{","{"],["\\}","}"],["\\right\\}","}"],["\\left.",l],["\\left|","|"],["\\right|","|"],["\\lfloor","⌊"],["\\rfloor","⌋"],["\\lceil","⌈"],["\\rceil","⌉"],["ceiling(","ceil("],["√","sqrt"],["²","^2"],["³","^3"],["⁴","^4"],["⁵","^5"],["⁶","^6"],["⁷","^7"],["⁸","^8"],["⁹","^9"],["⁰","^0"],["¹","^1"],["ⁿ","^n"],["⁻¹","^{-1}"],["⁻²","^{-2}"],["⁻³","^{-3}"],["∛","sqrt[3]"],["∜","sqrt[4]"],["½","(1/2)"],["⅓","(1/3)"],["⅔","(2/3)"],["¼","(1/4)"],["¾","(3/4)"],["⅛","(1/8)"],["⅜","(3/8)"],["⅝","(5/8)"],["⅞","(7/8)"],["⅕","(1/5)"],["⅖","(2/5)"],["⅗","(3/5)"],["⅘","(4/5)"],["⅙","(1/6)"],["⅚","(5/6)"],["⅐","(1/7)"],["⅑","(1/9)"],["⅒","(1/10)"],["⊕"," \\xor "],["∞","∞"],["⋅",s],["−","-"],["\\wedge","&"],["∨","∨"],["\\vee","∨"],["\\Pi","Π",!0],["\\Alpha","Α",!0],["\\Beta","Β",!0],["\\Gamma","Γ",!0],["\\Delta","Δ",!0],["\\Delta ","Δ",!0],["\\Epsilon","Ε",!0],["\\Zeta","Ζ",!0],["\\Eta","Η",!0],["\\Theta","Θ",!0],["\\Iota","Ι",!0],["\\Kappa","Κ",!0],["\\Lambda","Λ",!0],["\\Mu","Μ",!0],["\\Nu","Ν",!0],["\\Xi","Ξ",!0],["\\Omicron","Ο",!0],["\\Rho","Ρ",!0],["\\Sigma","Σ",!0],["\\Tau","Τ",!0],["\\Upsilon","Υ",!0],["\\Phi","Φ",!0],["\\Chi","Χ",!0],["\\Psi","Ψ",!0],["\\Omega","Ω",!0],["\\pi","π",!0],["\\alpha","α",!0],["\\beta","β",!0],["\\gamma","γ",!0],["\\delta","δ",!0],["\\epsilon","ε",!0],["\\zeta","ζ",!0],["\\eta","η",!0],["\\theta","θ",!0],["\\iota","ι",!0],["\\kappa","κ",!0],["\\lambda","λ",!0],["\\mu","μ",!0],["\\nu","ν",!0],["\\xi","ξ",!0],["\\omicron","ο",!0],["\\rho","ρ",!0],["\\sigma","σ",!0],["\\tau","τ",!0],["\\upsilon","υ",!0],["\\phi","φ",!0],["\\chi","χ",!0],["\\psi","ψ",!0],["\\omega","ω",!0]];const y=e=>" "===e||"\t"===e||"\n"===e,b="({[",w=")}]";const x="ⅆ",v=new RegExp(String.raw`(\\(?:mathrm|operatorname|text)\{d\}\s*|d)([A-Za-zα-ω](?![A-Za-z0-9])|\\(?:${"alpha|beta|gamma|delta|epsilon|varepsilon|zeta|eta|theta|vartheta|iota|kappa|lambda|mu|nu|xi|rho|sigma|tau|upsilon|phi|varphi|chi|psi|omega"})(?![A-Za-z]))`,"g");function _(e){const t=[String.raw`\left\{`,String.raw`\left\lbrace`,String.raw`\{`,String.raw`\lbrace`,"{"],r=[String.raw`\right\}`,String.raw`\right\rbrace`,String.raw`\}`,String.raw`\rbrace`,"}"],n=/\\[A-Za-z{]/.test(e);for(let o=0,s=0;o<50;o++){let o=-1,a="";for(let r=s;r<e.length&&o<0;r++){const s=t.find(t=>e.startsWith(t,r));s&&("{"===s&&(n||/[\\^_A-Za-z]$/.test(e.slice(0,r)))||("{"!==s||"{"!==e[r+1]?(o=r,a=s):r++))}if(o<0)return e;let i=0,l=null,c=null,u=-1,p=0;for(let t=o+a.length;t<e.length;t++){const o=r.find(r=>e.startsWith(r,t));if(0===i&&o&&("{"===a?"}"===o:"}"!==o)){u=t,a+="|"+o;break}if(!"([{".includes(e[t])||"{"===e[t]&&"\\"===e[t-1]?")]}".includes(e[t])&&"\\"!==e[t-1]&&i--:i++,0===i&&"?"===e[t]&&p++,0===i&&!l){const r=/^(?:\\middle\s*\||\\mid(?![A-Za-z])|:(?!=)|\|)/.exec(e.slice(t));r&&":"===r[0]&&p?p--:r&&"|"!==r[0]?l={at:t,length:r[0].length}:r&&n&&!c&&!/\\left\s*$|\\right\s*$|\\middle\s*$/.test(e.slice(0,t))&&(c={at:t,length:1})}}if(l??=c,u<0||!l){s=o+1;continue}const h=e.slice(o+a.split("|")[0].length,l.at).trim(),f=e.slice(l.at+l.length,u).trim();if(!h||!f){s=o+1;continue}const m=a.split("|")[1];e=`${e.slice(0,o)}setbuilder((${h}),(${f}))${e.slice(u+m.length)}`,s=o}return e}const A=String.raw`\\(?:[Bb]igg?|right)[lrm]?`,E=new RegExp(`(?:${A}\\s*([\\]|])|(\\]))\\s*(?=[_^])`,"g");function z(e,t){let r=t;for(;" "===e[r];)r++;if("{"===e[r]){let t=0;for(let n=r;n<e.length;n++)if("{"===e[n])t++;else if("}"===e[n]&&0===--t)return{value:e.slice(r+1,n).trim(),end:n+1};return null}const n=/^\\[A-Za-z]+/.exec(e.slice(r));return n?{value:n[0],end:r+n[0].length}:"-"===e[r]&&/\d/.test(e[r+1]??"")?{value:e.slice(r,r+2),end:r+2}:e[r]?{value:e[r],end:r+1}:null}function M(e,t){let r=t;for(;" "===e[r];)r++;const n=e[r];if("_"!==n&&"^"!==n)return null;const o=z(e,r+1);if(!o)return null;let s=o.end;for(;" "===e[s];)s++;const a="_"===n?"^":"_";if(e[s]!==a)return null;const i=z(e,s+1);return i?"_"===n?{lo:o.value,hi:i.value,end:i.end}:{lo:i.value,hi:o.value,end:i.end}:null}function k(e,t,r){let n=0;for(let o=t-1;o>=0;o--){if(r){if("]"===e[o])n++;else if("["===e[o]){if(0===n)return{start:o,end:o+1};n--}continue}const s=e.slice(0,o+1),a=/\\right\s*[\]|)}.]$|\\[Bb]igg?r?\s*[\]|]$/.exec(s),i=/\\left\s*(?:[[(.]|\\\{)$|\\[Bb]igg?l?\s*\[$/.exec(s);if(a&&o+1<t)n++,o-=a[0].length-1;else if(i){if(0===n)return{start:o+1-i[0].length,end:o+1};n--,o-=i[0].length-1}}return null}function O(e,t){let r=0;for(let n=t-1;n>=0;n--){const t=e[n];if(")]}".includes(t))r++;else if("([{".includes(t)){if(0===r)return n+1;r--}else{if(0===r&&/[=<>&,]/.test(t))return n+1;if(0===r&&/\\(?:approx|leq?|geq?|neq?|to|quad|qquad)$/.test(e.slice(0,n+1)))return n+1}}return 0}function j(e){for(let t=0;t<50;t++){E.lastIndex=0;let t=null;for(let r=E.exec(e);r;r=E.exec(e)){const n=M(e,r.index+r[0].length);if(!n)continue;const o=Boolean(r[2]),s="|"===(r[1]??r[2]),a=k(e,r.index,o);if((a||s&&!/^\\right/.test(r[0]))&&(!a||!/\\left\s*\|$/.test(e.slice(a.start,a.end)))){t={m:r,limits:n,opener:a};break}}if(!t)return e;const{m:r,limits:n,opener:o}=t,s=o?o.start:O(e,r.index),a=e.slice(o?o.end:s,r.index).trim(),i=/^\s*([A-Za-zα-ωΑ-Ω]|\\[A-Za-z]+)\s*=\s*([\s\S]+)$/.exec(n.lo),l=n.hi.replace(/^\s*(?:[A-Za-zα-ωΑ-Ω]|\\[A-Za-z]+)\s*=\s*/,""),c=i?`evaluated((${a}),${i[1]},${i[2]},${l})`:`evaluated((${a}),${n.lo},${l})`;e=`${e.slice(0,s)}${s>0&&/[^\s(=]/.test(e[s-1])?" ":""}${c}${e.slice(n.end)}`}return e}const S={__proto__:null,sine:"sin",cosine:"cos",tangent:"tan",secant:"sec",cosecant:"csc",cotangent:"cot"};const N=100;const I={__proto__:null},T={__proto__:null};[..."⁰¹²³⁴⁵⁶⁷⁸⁹"].forEach((e,t)=>{I[e]=String(t)}),[..."₀₁₂₃₄₅₆₇₈₉"].forEach((e,t)=>{T[e]=String(t)}),Object.assign(I,{"⁺":"+","⁻":"-","⁼":"=","⁽":"(","⁾":")","ᵃ":"a","ᵇ":"b","ᶜ":"c","ᵈ":"d","ᵉ":"e","ᶠ":"f","ᵍ":"g","ʰ":"h","ⁱ":"i","ʲ":"j","ᵏ":"k","ˡ":"l","ᵐ":"m","ⁿ":"n","ᵒ":"o","ᵖ":"p","ʳ":"r","ˢ":"s","ᵗ":"t","ᵘ":"u","ᵛ":"v","ʷ":"w","ˣ":"x","ʸ":"y","ᶻ":"z"}),Object.assign(T,{"₊":"+","₋":"-","₌":"=","₍":"(","₎":")","ₐ":"a","ₑ":"e","ₕ":"h","ᵢ":"i","ⱼ":"j","ₖ":"k","ₗ":"l","ₘ":"m","ₙ":"n","ₒ":"o","ₚ":"p","ᵣ":"r","ₛ":"s","ₜ":"t","ᵤ":"u","ᵥ":"v","ₓ":"x"});const R=new RegExp(`[${Object.keys(I).join("")}]+|[${Object.keys(T).join("")}]+`,"g");const F={__proto__:null,"½":"1/2","⅓":"1/3","⅔":"2/3","¼":"1/4","¾":"3/4","⅕":"1/5","⅖":"2/5","⅗":"3/5","⅘":"4/5","⅙":"1/6","⅚":"5/6","⅐":"1/7","⅛":"1/8","⅜":"3/8","⅝":"5/8","⅞":"7/8","⅑":"1/9","⅒":"1/10"},C=new RegExp(`(?<![\\w.,^_])(\\d+)[ \\t]?([${Object.keys(F).join("")}])`,"g"),q=/(?<![\w.,^_/])(\d+)[ \t]+([1-9]\d*)\/(\d+)(?![\d./^!])/g,L=/(?<![\w.,^_])(\d+)\s*\\[dtc]?frac\s*(?:\{\s*(\d+)\s*\}\s*\{\s*(\d+)\s*\}|(\d)(\d)(?!\d))/g;function P(e){const t=e.replace(/^\s*(?:\\(?:text|textrm|mathrm)\s*\{\s*(?:if|for|when|where)\s*\}|\b(?:if|for|when|where)\b)\s*,?/,"").replace(/[\s,.;]+$/,"").trim();return/^(?:\\(?:text|textrm|mathrm)\s*\{\s*)?(?:otherwise|else)\s*\}?$/.test(t)?"":t}function U(e,t){const r=[];let n=0,o=0;for(let s=0;s<e.length;s++)b.includes(e[s])?n++:w.includes(e[s])?n--:0===n&&e.startsWith(t,s)&&(r.push(e.slice(o,s)),s+=t.length-1,o=s+1);return r.push(e.slice(o)),r}function B(e,t,r){let n=0;const o=new RegExp(`\\b${r}\\b`,"iy");for(let r=t;r<e.length;r++)if(b.includes(e[r]))n++;else if(w.includes(e[r])){if(--n<0)return-1}else if(0===n&&(o.lastIndex=r,o.test(e)))return r;return-1}function D(e,t){let r=0;for(let n=t;n<e.length;n++)if(b.includes(e[n]))r++;else if(w.includes(e[n])&&--r<0)return n;return e.length}function Z(e,t){let r=1;for(let n=t+1;n<e.length;n++)if("?"===e[n])r++;else if(":"===e[n]&&0===--r)return e.slice(0,t+1)+"("+e.slice(t+1,n)+")?:"+e.slice(n+1);return e}function G(e){for(let t=2;t<e.length;t++)if("g"===e[t]&&"log"===e.slice(t-2,t+1))if("_"===e[t+1]){if(b.includes(e[t+2]))continue;const r=/^(?:\d+(?:\.\d+)?|[A-Za-z\u0370-\u03FF])/.exec(e.slice(t+2))?.[0];if(!r)continue;const n=t+2+r.length;e=e.slice(0,t+2)+"{"+r+"}"+e.slice(n)}else if("("===e[t+1]){let r=1,n=0,o="",s="",a=0;for(let i=t+2;i<e.length;i++){if(")]".includes(e[i])?r--:"([".includes(e[i])&&r++,0===r){a=i;break}1===r&&","===e[i]?n++:0===n?o+=e[i]:s+=e[i]}1===n&&a>0&&(e=e.slice(0,t+1)+"_{"+s+"}("+o+")"+e.slice(a+1))}return e}function W(e){const t="⌈"===e[0]?"ceil":"floor";let r=1;for(let n=1;n<e.length;n++)if("⌊"===e[n]||"⌈"===e[n]?r++:"⌋"!==e[n]&&"⌉"!==e[n]||r--,0===r)return t+"("+e.slice(1,n)+")"+e.slice(n+1);return e}function H(e){let t=1;for(let r=0;r<e.length;r++){if(")]".includes(e[r])?t--:"([".includes(e[r])&&t++,0!==t)continue;const n=e.slice(0,r),o=e[r+1];if("{"===o||"("===o)return o+n+","+e.slice(r+2);const s=/^[A-Za-z0-9.\u0370-\u03FF]+/.exec(e.slice(r+1))?.[0]??"";return"{"+n+","+s+"}"+e.slice(r+1+s.length)}return e}const X=new Set(["pmatrix","bmatrix","vmatrix"]);function V(e){const t=e.indexOf("}"),r=e.indexOf("{");if(t<0||r>=0&&r<t)return!1;const n=e.slice(0,t);if(!n.includes("matrix"))return!1;const o=e.indexOf("\\end{"+n+"}"),s=e.indexOf("\\begin{"+n+"}",t+1);if(o<0||-1!==s&&s<o)return!1;const a=e.slice(t+1,o).trim().split("\\\\").map(e=>e.trim()).filter(e=>e.length).map(e=>"["+e.replace(/&/g,", ")+"]"),i=e.slice(o+6+n.length);return X.has(n)?n+"("+a.join(", ")+")"+i:"["+a.join(", ")+"]"+i}function Y(e,t){if("{"!==e[t+1])return[e[t+1],t+2];let r=1,n="";for(let o=t+2;o<e.length;o++){if("{"===e[o])r++;else if("}"===e[o]&&0===--r)return[n,o+1];n+=e[o]}return[n,e.length]}function J(e){const{lower:t,upper:r,next:n}=function(e){let t="",r="",n=0;return"_"===e[0]&&([t,n]=Y(e,0),"^"===e[n]&&([r,n]=Y(e,n))),{lower:t,upper:r,next:n}}(e),o=e.slice(n),s=e=>e.replace(/\\,/g,"").replace(/\\!/g,"");let a,i="",l="",c=o.indexOf("\\mathrm{d}");if(c>=0){a=o.slice(0,c);const e=/^\{([^{}]*)\}/.exec(o.slice(c+10));i=e?e[1]:o[c+10],l=o.slice(c+10+(e?e[0].length:1))}else(c=function(e){let t=0;for(let r=0;r<e.length;r++)if(b.includes(e[r]))t++;else if(w.includes(e[r]))t--;else if(0===t&&"d"===e[r]&&/[A-Za-z\u0370-\u03FF]/.test(e[r+1]??"")&&!/[A-Za-z]/.test(e[r+2]??""))return r;return-1}(o))>=0?(a=o.slice(0,c),i=o[c+1],l=o.slice(c+2)):a=o;if(!i){const e=/frac\{d([A-Za-z])\}/.exec(a);e&&(i=e[1],a=a.replace(e[0],"frac{1}"))}if(!i&&/^[A-Za-z]$/.test(t)){i=[...s(a).matchAll(/(?<![A-Za-z\\])([A-Za-z])(?![A-Za-z(])/g)].map(e=>e[1]).find(e=>e!==t&&e!==r)??"x"}let u="int("+(s(a).trim()?s(a):"1");return i&&(u+=","+i),(t||r)&&(u+=","+t+","+r),u+")"+l}function K(e){const t=e[0];if(!(t>="A"&&t<="Z"||t>="a"&&t<="z"||t>="α"&&t<="ω"))return!1;const r=e.slice(2);let n=1;for(let e=0;e<r.length;e++)if(w.includes(r[e])?n--:b.includes(r[e])&&n++,0===n)return"("+r.slice(0,e)+","+t+")"+r.slice(e+1);return!1}function Q(e){return"{"===e[0]||e.length<2?e:"{"+e[0]+"}{"+e[1]+"}"+e.slice(2)}const ee=/[A-Za-z\u0370-\u03FF]/;function te(e,t){if("{"!==e[t])return null;let r=0;for(let n=t;n<e.length;n++)if("{"===e[n])r++;else if("}"===e[n]&&0===--r)return[e.slice(t+1,n),n+1];return null}function re(e,t){const r=/^\^(?:\{(\d+)\}|(\d))/.exec(e.slice(t));return r?[Number(r[1]??r[2]),t+r[0].length]:[1,t]}function ne(e,t){const r=e.replace(/\\mathrm\{d\}/g,"d"),n=t.replace(/\\mathrm\{d\}/g,"d"),o=/^d(?:\^\{?(\d+)\}?)?([A-Za-z\u0370-\u03FF]?)$/.exec(r),s=/^d([A-Za-z\u0370-\u03FF])(?:\^\{?(\d+)\}?)?$/.exec(n);return o&&s?{n:Number(o[1]??1),of:o[2],by:s[1]}:null}function oe(e,t){if(b.includes(e[t])){let r=0;for(let n=t;n<e.length;n++)if(b.includes(e[n]))r++;else if(w.includes(e[n])&&0===--r)return[e.slice(t,n+1),n+1];return[e.slice(t),e.length]}let r=0;for(let n=t;n<e.length;n++)if(b.includes(e[n]))r++;else{if(w.includes(e[n])&&--r<0)return[e.slice(t,n),n];if(0===r&&("="===e[n]||","===e[n]))return[e.slice(t,n),n]}return[e.slice(t),e.length]}const se=(e,t,r)=>`der(${e},${t}${r>1?","+r:""})`;const ae="strtktk",ie="ABCDEFGHIJ",le=e=>ae+[...String(e)].map(e=>ie[e]).join(""),ce=new RegExp(`^${ae}[${ie}]+$`);function ue(e){let t="";for(let r=0;r<e.length;r++){const n=e[r];if('"'===n||"`"===n){const n=pe(e,r);t+=e.slice(r,n+1),r=n}else if("'"===n)if(/[A-Za-z0-9)\]′\u0370-\u03FF]/.test(t[t.length-1]??""))t+="′";else{const n=pe(e,r);t+=e.slice(r,n+1),r=n}else t+=n}return t}function pe(e,t){let r=!1;for(let n=t+1;n<e.length;n++)if(r)r=!1;else if("\\"===e[n])r=!0;else if(e[n]===e[t])return n;return e.length-1}const he=new RegExp(`${ae}[${ie}]+|§\\d+§`,"g");function fe(e,t){return t&&0!==t.size?e.map(e=>"string"!=typeof e?e:e.replace(he,e=>{const r=t.get(e);if(void 0!==r)return r;for(let r=e.length-1;r>7;r--){const n=t.get(e.slice(0,r));if(void 0!==n)return n+e.slice(r)}return e})):e}const me={factorial:"((n) => { if (!Number.isInteger(n) || n < 0) return NaN; if (n > 170) return Infinity; let r = 1; for (let i = 2; i <= n; i++) r *= i; return r; })",perm:"((n, k) => { if (!Number.isInteger(n) || !Number.isInteger(k) || k < 0 || k > n) return NaN; let r = 1; for (let i = n - k + 1; i <= n && r !== Infinity; i++) r *= i; return r; })",comb:"((n, k) => { if (!Number.isInteger(n) || !Number.isInteger(k) || k < 0 || k > n) return NaN; k = Math.min(k, n - k); let r = 1; for (let i = 1; i <= k && r !== Infinity; i++) r = r * (n - k + i) / i; return Math.round(r); })",gcd:"((args)=>{let gcd = function(a,b) { return (!b)?a:gcd(b,a%b); }; return Math.abs(args.reduce(gcd));})",det:"((m) => { const a = m.map((r) => r.slice()); const n = a.length; let d = 1; for (let i = 0; i < n; i++) { let p = i; for (let r = i + 1; r < n; r++) if (Math.abs(a[r][i]) > Math.abs(a[p][i])) p = r; if (a[p][i] === 0) return 0; if (p !== i) { const t = a[p]; a[p] = a[i]; a[i] = t; d = -d; } d *= a[i][i]; for (let r = i + 1; r < n; r++) { const f = a[r][i] / a[i][i]; for (let c = i; c < n; c++) a[r][c] -= f * a[i][c]; } } return d; })",times:"((a, b) => { const L = Array.isArray; const m = (v) => L(v) && v.length > 0 && v.every((r) => L(r) && r.length > 0 && r.length === v[0].length && !r.some(L)) && (v.length > 1 || v[0].length > 1); const l = (v) => L(v) && v.length > 0 && !v.some(L); const p = (A, B) => (A[0].length === B.length ? A.map((r) => B[0].map((_, j) => r.reduce((s, x, k) => s + x * B[k][j], 0))) : NaN); const e = (x, y) => (L(x) && L(y) ? (x.length === y.length ? x.map((t, i) => e(t, y[i])) : NaN) : L(x) ? x.map((t) => e(t, y)) : L(y) ? y.map((t) => e(x, t)) : x * y); if (m(a) && m(b)) return p(a, b); if (m(a) && l(b)) { const c = p(a, b.map((y) => [y])); return L(c) ? c.map((r) => r[0]) : c; } if (l(a) && m(b)) { const c = p([a], b); return L(c) ? c[0] : c; } return e(a, b); })",same:"((a, b) => { const s = (x, y) => (Array.isArray(x) && Array.isArray(y) ? x.length === y.length && x.every((v, i) => s(v, y[i])) : x == y); return s(a, b); })",union:"((a, b) => [...new Set([].concat(a, b))])",intersection:"((a, b) => [].concat(a).filter((x) => [].concat(b).includes(x)))",round:"((x, d) => { const p = Math.pow(10, d); return (x < 0 ? -Math.round(-x * p) : Math.round(x * p)) / p; })",mod:"((a, n) => ((a % n) + n) % n)",root:"((n, x) => (x < 0 && Math.abs(n % 2) === 1 ? -Math.pow(-x, 1 / n) : Math.pow(x, 1 / n)))",contains:"((s, t) => { const f = (x) => (x == null ? String() : String(x)).replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32)); return f(s).includes(f(t)); })",startswith:"((s, t) => { const f = (x) => (x == null ? String() : String(x)).replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32)); return f(s).startsWith(f(t)); })"},ge="lambda x: str().join(chr(ord(c) + 32) if 65 <= ord(c) <= 90 else c for c in (str() if x is None or x != x else str(int(x)) if isinstance(x, float) and x.is_integer() else str(x)))",de=`lambda s, t, f=${ge}: f(t) in f(s)`,$e=`lambda s, t, f=${ge}: f(s).startswith(f(t))`,ye={contains:`(${de})`,startswith:`(${$e})`},be={contains:`np.vectorize(${de}, otypes=[bool])`,startswith:`np.vectorize(${$e}, otypes=[bool])`};for(const e of[me,ye,be])Object.setPrototypeOf(e,null);const we="([{",xe=")]}";function ve(e,t){let r=0;for(let n=t;n<e.length;n++)if(we.includes(e[n]))r++;else if(xe.includes(e[n])&&0===--r)return n;return-1}function _e(e){if(!e.trim())return[];const t=[];let r=0,n=0;for(let o=0;o<e.length;o++)we.includes(e[o])?r++:xe.includes(e[o])?r--:","===e[o]&&0===r&&(t.push(e.slice(n,o).trim()),n=o+1);return t.push(e.slice(n).trim()),t}function Ae(e,t,r){const n=[...e.matchAll(t)];for(let t=n.length-1;t>=0;t--){const o=n[t],s=o.index+o[0].length-1,a=ve(e,s);if(a<0)continue;const i=r(_e(e.slice(s+1,a)),o,e.slice(a+1));if(null==i)continue;const[l,c=0]=Array.isArray(i)?i:[i];if((e=e.slice(0,o.index)+l+e.slice(a+1+c)).length>1e5)throw new Error("The expression expands too much when read")}return e}const Ee=e=>new RegExp(`(?<![\\w.])(${e})\\s*\\(`,"g"),ze=e=>`(${e})`,Me=e=>/^\[.*\]$/s.test(e.trim())?`{${e.trim().slice(1,-1)}}`:e,ke=[...Object.entries(me),...Object.entries(be),...Object.entries(ye)];const Oe={IF:e=>e.length>=2&&`((${e[0]}) ? (${e[1]}) : (${e[2]??"false"}))`,AND:e=>e.length&&`(${e.map(ze).join(" & ")})`,OR:e=>e.length&&`(${e.map(ze).join(" ∨ ")})`,NOT:e=>1===e.length&&`(!(${e[0]}))`,XOR:e=>2===e.length&&`((${e[0]}) \\xor (${e[1]}))`,LOG:e=>2===e.length?`log_{${e[1]}}(${e[0]})`:1===e.length&&`log_{10}(${e[0]})`,ATAN2:e=>2===e.length&&`atan2(${e[1]}, ${e[0]})`,INT:e=>1===e.length&&`floor(${e[0]})`,FIXED:e=>(1===e.length||2===e.length)&&`fixed(${e[0]}, ${e[1]??2})`,"FLOOR.MATH":e=>1===e.length&&`floor(${e[0]})`,"CEILING.MATH":e=>1===e.length&&`ceil(${e[0]})`,FACT:e=>1===e.length&&`((${e[0]})!)`,COMBIN:e=>2===e.length&&`comb(${e.join(", ")})`,PERMUT:e=>2===e.length&&`perm(${e.join(", ")})`,AVERAGE:e=>`mean(${e.join(", ")})`,SUM:e=>`sum(${e.join(", ")})`,PRODUCT:e=>`prod(${e.join(", ")})`,MAX:e=>`max(${e.join(", ")})`,MIN:e=>`min(${e.join(", ")})`,MEDIAN:e=>`median(${e.join(", ")})`,"STDEV.P":e=>`stdev(${e.join(", ")})`,STDEVP:e=>`stdev(${e.join(", ")})`,CEILING:e=>(1===e.length||2===e.length&&"1"===e[1].trim())&&`ceil(${e[0]})`,RAND:e=>!e.length&&"random()",ISNUMBER:e=>1===e.length&&`((${e[0]}) ∈ ℝ)`,LOG10:e=>1===e.length&&`log_{10}(${e[0]})`,MMULT:e=>2===e.length&&`((${e[0]}) * (${e[1]}))`};function je(e,t){for(let r=t,n=0;r>=0;r--)if(")"===e[r])n++;else if("("===e[r]&&0===--n)return r;return-1}function Se(e){const t="(?:[\\p{L}_][\\p{L}\\p{N}_.]*|\\d+(?:\\.\\d+)?|§\\d+§)";return e=function(e,t){const r=new RegExp(`^(?:${t})`,"u"),n=new RegExp(`(?:${t})$`,"u"),o=/[\p{L}_][\p{L}\p{N}_.]*$/u;for(let t=e.indexOf("^");t>=0;t=e.indexOf("^",t+1)){let s,a=t+1;for(;/\s/.test(e[a]??"");)a++;if("("===e[a])s=ve(e,a)+1;else{const t=r.exec(e.slice(a));s=t?a+t[0].length:0,t&&"("===e[s]&&(s=ve(e,s)+1)}if(s<=a||!/^\s*\^/.test(e.slice(s)))continue;let i,l=t;for(;l>0&&/\s/.test(e[l-1]);)l--;if(")"===e[l-1]){i=je(e,l-1);const t=i>0&&o.exec(e.slice(Math.max(0,i-64),i));t&&(i-=t[0].length)}else{const t=n.exec(e.slice(Math.max(0,l-64),l));i=t?l-t[0].length:-1}i<0||(e=`${e.slice(0,i)}(${e.slice(i,s)})${e.slice(s)}`,t=s+1)}return e}(e=(e=(e=e.replace(/^\s*=/,"").replace(/(?<![\w.])_xlfn\./g,"")).replace(/&/g,"+")).replace(new RegExp(`(^|[(,=<>*/+^-]\\s*)-\\s*(${t})(?=\\s*\\^)`,"gu"),"$1(-$2)"),t),Ae(e,/(?<![\w.])([A-Z][A-Z0-9]*(?:\.[A-Z]+)?)\s*\(/g,(e,t)=>Oe[t[1]]?.(e)||null)}const Ne={POWER:"pow",SQRT:"sqrt",ABS:"abs",LN:"ln",EXP:"exp",FLOOR:"floor",CEIL:"ceil",CEILING:"ceil",ROUND:"round",GREATEST:"max",LEAST:"min",MOD:"mod",ATAN2:"atan2",FACTORIAL:"factorial",SIN:"sin",COS:"cos",TAN:"tan",SEC:"sec",CSC:"csc",COT:"cot",ASIN:"asin",ACOS:"acos",ATAN:"atan",SINH:"sinh",COSH:"cosh",TANH:"tanh",ASINH:"asinh",ACOSH:"acosh",ATANH:"atanh",COMB:"comb",PERM:"perm",GCD:"gcd",DERIVATIVE:"derivative",LIMIT:"limit",UNION:"union",EXPM1:"expm1",TRUNC:"trunc",SUMMATION:"sum"},Ie="strtktk[A-J]+";function Te(e){for(let t=!0;t;){const r=e;t=(e=e.replace(new RegExp(`(${Ie})\\s*\\|\\|\\s*(${Ie})`,"g"),"$1 + $2"))!==r}const t=new RegExp(`^\\(typeof\\(([^()]*)\\)\\s+IN\\s+\\(${Ie},\\s*${Ie}\\)\\s+AND\\s+(.*)\\)$`,"s");for(let r=e.lastIndexOf("(typeof(");r>=0;r=r>0?e.lastIndexOf("(typeof(",r-1):-1){const n=ve(e,r),o=n>0&&t.exec(e.slice(r,n+1));if(!o)continue;const[,s,a]=o,i=new Map([[`${s} = TRUNC(${s})`,"ℤ"],[`${s} = TRUNC(${s}) AND ${s} > 0`,"ℕ"],[`ABS(${s}) < ∞`,"ℝ"]]).get(a.trim());i&&(e=`${e.slice(0,r)}((${s}) ∈ ${i})${e.slice(n+1)}`)}e=Ae(e,/(?<![\w.])CAST\s*\(/gi,e=>{const t=1===e.length&&/^(.*)\s+AS\s+(?:REAL|FLOAT|DOUBLE(?:\s+PRECISION)?|NUMERIC|DECIMAL|INTEGER|INT)\s*$/is.exec(e[0]);return t?`(${t[1]})`:null}),e=(e=(e=Ae(e=function(e){for(let t=0;t<50;t++){const t=[...e.matchAll(/\bCASE\s+WHEN\b/gi)];if(!t.length)return e;const r=t[t.length-1].index,n=/\bEND\b/i.exec(e.slice(r));if(!n)return e;const o=e.slice(r+4,r+n.index).split(/\b(WHEN|THEN|ELSE)\b/i).map(e=>e.trim()),s=[];let a="null";for(let e=1;e<o.length;e+=2){const t=o[e].toUpperCase();"WHEN"===t?s.push([o[e+1],o[e+3]]):"ELSE"===t&&(a=o[e+1])}const i=s.reduceRight((e,[t,r])=>`((${t}) ? (${r}) : ${e})`,ze(a));e=e.slice(0,r)+i+e.slice(r+n.index+3)}return e}(e=e.replace(/(?<![\w.])ARRAY\s*\[/g,"[")),/(?<![\w.])LOG\s*\(/g,e=>2===e.length?`log_{${e[0]}}(${e[1]})`:`log_{10}(${e[0]})`)).replace(/(?<![\w.])PI\s*\(\s*\)/g,"π")).replace(/(?<![\w.])([A-Z][A-Z0-9]*)(?=\s*\()/g,e=>Ne[e]??e);for(const[t,r]of[[/\bNOT\s+IN\s*\(/g,"∉"],[/\bIN\s*\(/g,"∈"]])for(let n=t.exec(e);n;n=t.exec(e)){const o=n.index+n[0].length-1,s=ve(e,o);if(s<0)break;e=`${e.slice(0,n.index)}${r} {${e.slice(o+1,s)}}${e.slice(s+1)}`,t.lastIndex=0}return e.replace(/<>/g," ≠ ")}const Re={sin:"sin",cos:"cos",tan:"tan",sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsin:"asin",arccos:"acos",arctan:"atan",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",arctan2:"atan2",sqrt:"sqrt",cbrt:"cbrt",exp:"exp",expm1:"expm1",log:"log",log2:"log2",log10:"log10",floor:"floor",ceil:"ceil",round:"round",power:"pow",abs:"abs",absolute:"abs",fabs:"abs",pi:"PI",e:"E",gcd:"gcd"},Fe={maximum:"max",minimum:"min",nanmax:"max",nanmin:"min",nansum:"sum",nanprod:"prod",nanmean:"mean",nanmedian:"median",nanstd:"stdev",mod:"mod",fmod:"mod",where:"where",isin:"isin",isclose:"isclose",isfinite:"isfinite",logical_and:"logical_and",logical_or:"logical_or",logical_not:"logical_not",logical_xor:"logical_xor",prod:"prod",sum:"sum",trunc:"trunc",union1d:"union",intersect1d:"intersection",dot:"np_times",matmul:"np_times",multiply:"np_times",array_equal:"np_equal"};const Ce=e=>e.replace(/(?<![\w.])set\s*\(\s*\)/g,"∅"),qe={inf:"∞",nan:"NaN"};function Le(e){return(e=(e=function(e){return e=e.replace(/(?<![\w.])sympy\.Interval\.(open|Lopen|Ropen)\s*\(/g,(e,t)=>`sympy_interval_${t}(`),e=e.replace(/(?<![\w.])sympy\.S\.(\w+)/g,(e,t)=>Ue[t]??e),e=e.replace(/(?<![\w.])sympy\.(Reals|Integers|Naturals0?|Rationals|Complexes)\b/g,(e,t)=>Ue[t]),e.replace(/(?<![\w.])sympy\.(\w+)/g,(e,t)=>Be[t]??Pe[t]??e)}(e=(e=(e=(e=(e=(e=(e=e.replace(/(?<![\w.])(?:np|numpy)\.random\.random\(\s*\)|(?<![\w.])random\.random\(\s*\)/g,"Math.random()")).replace(/(?<![\w.])(?:np|numpy)\.linalg\.(det|inv)\b/g,"$1")).replace(/(?<![\w.])(?:np|numpy)\.array\s*\(/g,"(")).replace(/(?<![\w.])(?:np|numpy)\.(\w+)/g,(e,t)=>Re[t]?`Math.${Re[t]}`:Fe[t]?Fe[t]:qe[t]??e)).replace(/(?<![\w.])(?:math|Math)\.(factorial|isfinite|isclose|prod|inf|nan|abs|trunc)\b/g,(e,t)=>qe[t]??t)).replace(/(?<![\w.])Number\.(isInteger|isFinite)\b/g,(e,t)=>t.toLowerCase())).replace(/(?<![\w.])scipy\.(?:special|integrate)\.(\w+)/g,"$1"))).replace(/\bMZ_INFINITY\b/g,"∞")).replace(/(?<![\w.])mz_(?=\w+\s*\()/g,"")}const Pe={pi:"π",E:"e",oo:"∞",true:"true",false:"false",nan:"NaN",I:"i"},Ue={Reals:"ℝ",Integers:"ℤ",Naturals:"ℕ",Naturals0:"ℕ",Rationals:"ℚ",Complexes:"ℂ"},Be={sqrt:"Math.sqrt",exp:"Math.exp",sin:"Math.sin",cos:"Math.cos",tan:"Math.tan",sinh:"Math.sinh",cosh:"Math.cosh",tanh:"Math.tanh",asin:"Math.asin",acos:"Math.acos",atan:"Math.atan",asinh:"Math.asinh",acosh:"Math.acosh",atanh:"Math.atanh",atan2:"atan2",csc:"csc",sec:"sec",cot:"cot",log:"log",Abs:"abs",floor:"floor",ceiling:"ceil",Max:"max",Min:"min",factorial:"factorial",binomial:"comb",ff:"perm",gcd:"gcd",gcd_list:"sympy_list_gcd",Mod:"mod",root:"sympy_root",real_root:"sympy_root",det:"det",Rational:"sympy_rational",Integer:"sympy_value",Float:"sympy_value",Eq:"sympy_eq",Ne:"sympy_ne",And:"sympy_and",Or:"sympy_or",Not:"sympy_not",Xor:"sympy_xor",Nand:"sympy_nand",Nor:"sympy_nor",Implies:"sympy_implies",Equivalent:"sympy_iff",Piecewise:"sympy_piecewise",FiniteSet:"sympy_set",Interval:"sympy_interval",Contains:"sympy_contains",Union:"union",Intersection:"intersection",diff:"derivative",integrate:"sympy_integrate",limit:"sympy_limit",summation:"sympy_summation",product:"sympy_product",expm1:"expm1",Matrix:""},De={open:"()",Lopen:"(]",Ropen:"[)"};const Ze=e=>{const t=/^\((.*)\)$/s.exec(e.trim());return t?_e(t[1]):null},Ge=e=>t=>2===t.length&&`${e[0]}${t[0]}, ${t[1]}${e[1]}`,We=e=>Ze(e)??[e],He={where:e=>3===e.length&&`((${e[0]}) ? (${e[1]}) : (${e[2]}))`,both:e=>2===e.length&&`((${e[0]}) & (${e[1]}))`,either:e=>2===e.length&&`((${e[0]}) ∨ (${e[1]}))`,np_times:e=>2===e.length&&`((${e[0]}) * (${e[1]}))`,np_equal:e=>2===e.length&&`((${e[0]}) = (${e[1]}))`,logical_and:e=>2===e.length&&`((${e[0]}) & (${e[1]}))`,logical_or:e=>2===e.length&&`((${e[0]}) ∨ (${e[1]}))`,logical_xor:e=>2===e.length&&`((${e[0]}) \\xor (${e[1]}))`,logical_not:e=>1===e.length&&`(!(${e[0]}))`,isin:e=>2===e.length&&`((${e[0]}) ∈ ${Me(e[1])})`,contains:e=>2===e.length&&`((${e[1]}) ∈ ${Me(e[0])})`,isclose:e=>e.length>=2&&`((${e[0]}) ≈ (${e[1]}))`,isfinite:e=>1===e.length&&`((${e[0]}) ∈ ℝ)`,isinteger:e=>1===e.length&&`((${e[0]}) ∈ ℤ)`,factorial:e=>1===e.length&&`((${e[0]})!)`,union:e=>2===e.length&&`((${e[0]}) ∪ (${e[1]}))`,union_:e=>2===e.length&&`((${e[0]}) ∪ (${e[1]}))`,intersection:e=>2===e.length&&`((${e[0]}) ∩ (${e[1]}))`,sq:e=>1===e.length&&`((${e[0]})^2)`,cube:e=>1===e.length&&`((${e[0]})^3)`,fract:e=>1===e.length&&`((${e[0]}) - floor(${e[0]}))`,inversesqrt:e=>1===e.length&&`(1/sqrt(${e[0]}))`,radians:e=>1===e.length&&`((${e[0]})°)`,degrees:e=>1===e.length&&`((${e[0]})/°)`,mod:e=>2===e.length&&`((${e[0]}) \\mod (${e[1]}))`,atan:e=>2===e.length&&`atan2(${e[0]}, ${e[1]})`,exp2:e=>1===e.length&&`((2)^(${e[0]}))`,trunc:e=>1===e.length&&`((${e[0]}) < 0 ? (ceil(${e[0]})) : floor(${e[0]}))`,...Object.fromEntries([2,3,4].map(e=>[`mat${e}`,t=>t.length===e*e&&`[${Array.from({length:e},(r,n)=>`[${Array.from({length:e},(r,o)=>t[o*e+n]).join(", ")}]`).join(", ")}]`])),vec2:e=>`(${e.join(", ")})`,vec3:e=>`(${e.join(", ")})`,vec4:e=>`(${e.join(", ")})`,derivative:e=>e.length>=2&&`der(${e.join(", ")})`,sympy_rational:e=>2===e.length&&`((${e[0]})/(${e[1]}))`,sympy_value:e=>1===e.length&&`(${e[0]})`,sympy_eq:e=>2===e.length&&`((${e[0]}) = (${e[1]}))`,sympy_ne:e=>2===e.length&&`((${e[0]}) ≠ (${e[1]}))`,sympy_and:e=>e.length&&`(${e.map(ze).join(" & ")})`,sympy_or:e=>e.length&&`(${e.map(ze).join(" ∨ ")})`,sympy_not:e=>1===e.length&&`(!(${e[0]}))`,sympy_xor:e=>2===e.length&&`((${e[0]}) \\xor (${e[1]}))`,sympy_nand:e=>2===e.length&&`((${e[0]}) \\nand (${e[1]}))`,sympy_implies:e=>2===e.length&&`((${e[0]}) \\implies (${e[1]}))`,sympy_iff:e=>2===e.length&&`((${e[0]}) \\iff (${e[1]}))`,sympy_nor:e=>2===e.length&&`((${e[0]}) \\nor (${e[1]}))`,sympy_piecewise:e=>{const t=e.map(Ze);return!t.length||t.some(e=>!e||2!==e.length)?null:t.reduceRight((e,[t,r])=>null===e||/^True$|^true$/.test(r.trim())&&void 0===e?`(${t})`:`((${r}) ? (${t}) : ${e??"(null)"})`,void 0)},sympy_set:e=>`{${e.join(", ")}}`,sympy_interval:Ge("[]"),sympy_interval_open:Ge("()"),sympy_interval_Lopen:Ge("(]"),sympy_interval_Ropen:Ge("[)"),sympy_contains:e=>2===e.length&&`((${e[0]}) ∈ ${e[1]})`,sympy_list_gcd:e=>1===e.length&&`gcd(${e[0].trim().replace(/^\[|\]$/g,"")})`,sympy_root:e=>2===e.length&&`root(${e[1]}, ${e[0]})`,sympy_integrate:e=>{if(2!==e.length)return null;const t=We(e[1]);return 3===t.length?`int(${e[0]}, ${t.join(", ")})`:1===t.length?`int(${e[0]}, ${t[0]})`:null},sympy_limit:e=>e.length>=3&&`lim(${e.slice(0,3).join(", ")}${e[3]?`, ${e[3]}`:""})`,sympy_summation:e=>{if(3===e.length&&/^\s*[A-Za-z]\w*\s*==/.test(e[1]))return`sum(${e[0]}, ${e[1].replace("==","=")}, ${e[2]})`;const t=2===e.length&&We(e[1]);return 3===t?.length&&`(\\sum_{${t[0]}=${t[1]}}^{${t[2]}} (${e[0]}))`},sympy_product:e=>{if(3===e.length&&/^\s*[A-Za-z]\w*\s*==/.test(e[1]))return`prod(${e[0]}, ${e[1].replace("==","=")}, ${e[2]})`;const t=2===e.length&&We(e[1]);return 3===t?.length&&`(\\prod_{${t[0]}=${t[1]}}^{${t[2]}} (${e[0]}))`},limit:e=>e.length>=3&&`lim(${e.join(", ")})`,summation:e=>3===e.length&&/^\s*[A-Za-z]\w*\s*==/.test(e[1])&&`sum(${e[0]}, ${e[1].replace("==","=")}, ${e[2]})`,sum:Xe("sum"),prod:Xe("prod")};function Xe(e){return t=>{const r=1===t.length&&/^(.*?)\s+for\s+(\w+)\s+in\s+range\((.*)\)\s*$/s.exec(t[0]);if(!r)return null;const n=_e(r[3]),[o,s]=1===n.length?["0",n[0]]:n,a=/\s*\+\s*1$/.test(s)?s.replace(/\s*\+\s*1$/,""):`(${s}) - 1`;return`(\\${e}_{${r[2]}=${o}}^{${a}} (${r[1]}))`}}function Ve(e){e=function(e){for(let t=e.lastIndexOf("(lambda");t>=0;t=t>0?e.lastIndexOf("(lambda",t-1):-1){const r=ve(e,t);if(r<0||"("!==e[r+1])continue;const n=ve(e,r+1),o=/^\(lambda\s+([\w\s,]+?)\s*:\s*([\s\S]*)\)$/.exec(e.slice(t,r+1));if(n<0||!o)continue;const s=o[1].split(",").map(e=>e.trim()),a=_e(e.slice(r+2,n));if(a.length!==s.length||!s.every(e=>/^[A-Za-z_]\w*$/.test(e)))continue;const i=new Map(s.map((e,t)=>[e,a[t]])),l=o[2].replace(new RegExp(`(?<![\\w.])(${s.join("|")})(?!\\w)`,"g"),e=>`(${i.get(e)})`);if((e=e.slice(0,t)+`(${l})`+e.slice(n+1)).length>1e5)throw new Error("The expression expands too much when read")}return e}(e),e=Ae(e,Ee("quad"),(e,t,r)=>{const n=/^lambda\s+(\w+)\s*:\s*(.*)$/s.exec(e[0]??"");if(!n||3!==e.length)return null;const o=/^\s*\[\s*0\s*\]/.exec(r);return[`int(${n[2]}, ${n[1]}, ${e[1]}, ${e[2]})`,o?o[0].length:0]}),e=Ae(e,Ee(Object.keys(He).join("|")),(e,t)=>He[t[1]](e)||null);for(let t=(e=Ae(e,Ee("float"),(e,t,r)=>{if(1!==e.length)return null;const n=/^\s*\.is_integer\(\s*\)/.exec(r);return n?[`((${e[0]}) ∈ ℤ)`,n[0].length]:`(${e[0]})`})).lastIndexOf(".includes(");t>=0;t=t>0?e.lastIndexOf(".includes(",t-1):-1){const r=t+9,n=ve(e,r);let o=t;if(xe.includes(e[t-1])){let r=0;for(o=t-1;o>=0;o--)if(xe.includes(e[o]))r++;else if(we.includes(e[o])&&0===--r)break}else for(;o>0&&/[\w.]/.test(e[o-1]);)o--;n<0||o<0||o===t||(e=`${e.slice(0,o)}((${e.slice(r+1,n)}) ∈ ${Me(e.slice(o,t))})${e.slice(n+1)}`)}return e}for(const e of[Oe,Ne,Re,Fe,Pe,Ue,Be,De,He,qe])Object.setPrototypeOf(e,null);const Ye=String.raw`(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}|(?<![\w.′^])[\w.′^]+)`,Je=e=>e.trim().split(/\s+/).join(String.raw`\s+`),Ke=e=>new RegExp(String.raw`(?<![\w.])${Je(e)}(?![\w.])`,"gi"),Qe=[["is greater than or equal to","≥"],["is more than or equal to","≥"],["is at least","≥"],["is no less than","≥"],["is not less than","≥"],["is less than or equal to","≤"],["is at most","≤"],["is no more than","≤"],["is not more than","≤"],["is not greater than","≤"],["is greater than",">"],["is more than",">"],["is bigger than",">"],["is larger than",">"],["is above",">"],["exceeds",">"],["is less than","<"],["is smaller than","<"],["is fewer than","<"],["is below","<"],["is not equal to","≠"],["does not equal","≠"],["doesn't equal","≠"],["is different from","≠"],["is approximately equal to","≈"],["is approximately","≈"],["is about","≈"],["is roughly","≈"],["is close to","≈"],["is equal to","="],["is the same as","="],["equals","="],["greater than or equal to","≥"],["less than or equal to","≤"],["at least","≥"],["at most","≤"],["greater than",">"],["more than",">"],["less than","<"],["not equal to","≠"],["equal to","="]],et="[<>≤≥=≠≈]",tt={second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10};Object.setPrototypeOf(tt,null);const rt=Object.entries({sine:"sin",cosine:"cos",tangent:"tan",secant:"sec",cosecant:"csc",cotangent:"cot","natural log":"ln","natural logarithm":"ln",arcsine:"arcsin",arccosine:"arccos",arctangent:"arctan",arcsecant:"arcsec",arccosecant:"arccsc",arccotangent:"arccot","hyperbolic sine":"sinh","hyperbolic cosine":"cosh","hyperbolic tangent":"tanh",floor:"floor",ceiling:"ceil"}).sort((e,t)=>t[0].length-e[0].length),nt=[["is non-negative","≥ 0"],["is nonnegative","≥ 0"],["is not negative","≥ 0"],["is non-positive","≤ 0"],["is nonpositive","≤ 0"],["is not positive","≤ 0"],["is positive","> 0"],["is negative","< 0"],["is non-zero","≠ 0"],["is nonzero","≠ 0"],["is not zero","≠ 0"],["is zero","= 0"],["is an integer","∈ ℤ"],["is not an integer","∉ ℤ"],["is a natural number","∈ ℕ"],["is a real number","∈ ℝ"],["is real","∈ ℝ"],["is a rational number","∈ ℚ"],["is rational","∈ ℚ"],...[["the integers","ℤ"],["the natural numbers","ℕ"],["the real numbers","ℝ"],["the rational numbers","ℚ"],["the complex numbers","ℂ"]].flatMap(([e,t])=>[[`is not in ${e}`,`∉ ${t}`],[`is in ${e}`,`∈ ${t}`]])],ot=/(?<![A-Za-z])(?:is|between|exceeds|equals?|does|doesn't|least|most|than|divides|and|or|of|to|squared|cubed|twice|percent|by|over|times|plus|minus|modulo)(?![A-Za-z])/i;Qe.map(([e])=>e),nt.map(([e])=>e),rt.map(([e])=>`${e} of`);const st=e([[" And "," & "],[" Or "," ∨ "],[" Not In "," ∉ "],[" Nor "," \\nor "],[" Xor "," \\xor "],[" Nand "," \\nand "],[" In "," ∈ "],[" Mod "," \\mod "],[" % ","%"],[" Perm ","\\perm "],[" P ","\\perm",!0],[" Comb ","\\comb "],[" C ","\\comb",!0],[" choose ","\\comb "],["! ","!_"],["\\in ","∈"],["\\notin ","∉"],["\\not\\in ","∉"],["\\to ","→"],["===","=...="]]),at=e([...$,...function(){const e=[],t=(t,r)=>{e.push([t,r],[t+"(",r+"("])};for(const r of["sin","cos","tan","cot","csc","sec"]){e.push(["Math."+r+"(",r+"("],["\\"+r+"(",r+"("],["\\"+r,r]);for(const e of["sin","cos","tan"].includes(r)?["","h"]:[""]){const n=r+e,o="arc"+r+e;e&&(t("Math."+n,n),t("\\"+n,n));for(const r of["^-1","^{-1}","-1"])t("\\"+n+r,o),t(n+r,o),e||t("Math."+n+r,o);e||t("\\a"+n,o),t("\\arc"+n,o),t("Math.a"+n,o),t("Math.arc"+n,o)}}return e}()]),it=[["code",function(e){return/^\s*=|[(.%^<_eE]|\|\||\bif\b|\b(?:True|False|None|TRUE|FALSE|NULL)\b/.test(e)?(/^\s*=(?!=)/.test(e)&&(e=Se(e)),e=function(e){for(const[t,r]of ke)for(let n=e.lastIndexOf(r);n>=0;n=n>0?e.lastIndexOf(r,n-1):-1){const o=n+r.length,s="("===e[o]?ve(e,o):-1;if(s<0)continue;let a=e.slice(o+1,s);"gcd"===t&&(a=a.trim().replace(/^\[|\]$/g,""));const i="times"===t||"same"===t?_e(a):null,l="factorial"===t?`((${a})!)`:2===i?.length?`((${i[0]}) ${"times"===t?"*":"="} (${i[1]}))`:`${t}(${a})`;e=e.slice(0,n)+l+e.slice(s+1)}for(let t=e.lastIndexOf(").toFixed(");t>=0;t=t>0?e.lastIndexOf(").toFixed(",t-1):-1){const r=t+10-1,n=ve(e,r),o=e.lastIndexOf("Number(",t);n<0||o<0||ve(e,o+7-1)!==t||(e=e.slice(0,o)+`fixed(${e.slice(o+7,t)}, ${e.slice(r+1,n)})`+e.slice(n+1))}return e.replace(/\(\(\)=>\{let (sum|prod) = [01]; let loopCount = 0; for \(let (\w+)=(.*?);\2<=(.*?);\2\+\+\) \{if \(loopCount\+\+ > 1000000\)\{break\};\1 [+*]= (.*?);\}; return \1;\}\)\(\)/g,(e,t,r,n,o,s)=>`(\\${"sum"===t?"sum":"prod"}_{${r}=${n}}^{${o}} (${s}))`)}(e),e=function(e){for(let t=0;t<50;t++){let t=!0;for(const r of e.matchAll(/\bif\b/g)){const n=r.index;let o=0,s=-1,a=e.length;for(let t=n+2;t<e.length;t++)if(we.includes(e[t]))o++;else{if(xe.includes(e[t])&&--o<0){a=t;break}if(0===o&&","===e[t]){a=t;break}if(0===o&&/^then\b/.test(e.slice(t))&&/\W/.test(e[t-1])){s=-2;break}0===o&&s<0&&/^else\b/.test(e.slice(t))&&/\W/.test(e[t-1])&&(s=t)}if(s<0)continue;o=0;let i=0;for(let t=n-1;t>=0;t--)if(xe.includes(e[t]))o++;else{if(we.includes(e[t])&&--o<0){i=t+1;break}if(0===o&&","===e[t]){i=t+1;break}}const l=e.slice(i,n).trim();if(!l)continue;const c=`((${e.slice(n+2,s).trim()}) ? (${l}) : (${e.slice(s+4,a).trim()}))`;e=e.slice(0,i)+c+e.slice(a),t=!1;break}if(t)return e}return e}(e=Ve(e=function(e){return e.includes("set")?Ce(Ae(e,/(?<![\w.])sorted\s*\(/g,e=>{if(1!==e.length)return null;const t=e[0];for(let e=0,r=0;e<t.length;e++)if("([{".includes(t[e]))r++;else if(")]}".includes(t[e]))r--;else if(0===r&&("|"===t[e]||"&"===t[e])){const r=e=>{const t=e.trim(),r=/^set\s*\(/.exec(t);return r&&ve(t,r[0].length-1)===t.length-1?t.slice(r[0].length,-1):null},[n,o]=[r(t.slice(0,e)),r(t.slice(e+1))];return null!==n&&null!==o?`((${n}) ${"|"===t[e]?"∪":"∩"} (${o}))`:null}return null})):e}(e=Le(e=Te(e=(e=e.replace(/(?<![\w.])9e999\b/g,"∞")).replace(/(?<![\w.])(\d+(?:\.\d+)?)[eE]([+-]?\d+)(?![\w.])/g,"($1*10^{$2})")))))),(e=(e=e.replace(/\b(?:True|TRUE)\b/g,"true").replace(/\b(?:False|FALSE)\b/g,"false").replace(/\b(?:None|NULL)\b/g,"null")).replace(/\^\^/g," \\xor ")).replace(/%(?=\s*(?:[(-]|[A-Za-z_][\w.]*\s*\())/g," \\mod ")):e}],["english",function(e){if(!ot.test(e))return e;let t=e;const r=(e,r,n,o="∈")=>{t=t.replace(new RegExp(String.raw`(?<![\w.])${Je(e)}\s+(${Ye})\s+(?:and|to)\s+(${Ye})(?:\s+(inclusive|exclusive))?(?![\w.])`,"gi"),(e,t,s,a)=>{const[i,l]="exclusive"===a?.toLowerCase()?["(",")"]:"inclusive"===a?.toLowerCase()?["[","]"]:[r,n];return` ${o} ${i}${t}, ${s}${l} `})};r("is not strictly between","(",")","∉"),r("is not between","[","]","∉"),r("is strictly between","(",")"),r("is between","[","]"),r("between","[","]"),t=t.replace(new RegExp(String.raw`(?<![\w.])is\s+(not\s+)?in\s+the\s+(open|closed|half-open)\s+interval\s+from\s+(${Ye})\s+to\s+(${Ye})`,"gi"),(e,t,r,n,o)=>{const[s,a]={open:["(",")"],closed:["[","]"],"half-open":["[",")"]}[r.toLowerCase()];return` ${t?"∉":"∈"} ${s}${n}, ${o}${a} `});const n=String.raw`(${Ye})\s+`;t=t.replace(new RegExp(n+String.raw`is\s+(not\s+)?within\s+(${Ye})\s*(%|\s+percent)?\s+of\s+(${Ye})`,"gi"),(e,t,r,n,o,s)=>`(abs((${t}) - (${s})) ${r?">":"≤"} ${o?`(${n})/100 * ${/^\d+(\.\d+)?$/.test(s)?s:`abs(${s})`}`:`(${n})`})`),t=t.replace(new RegExp(n+String.raw`is\s+(?:a\s+)?multiple\s+of\s+(${Ye})`,"gi"),"(($1) mod ($2) = 0)"),t=t.replace(new RegExp(n+String.raw`is\s+(not\s+)?divisible\s+by\s+(${Ye})`,"gi"),(e,t,r,n)=>`((${t}) mod (${n}) ${r?"≠":"="} 0)`),t=t.replace(new RegExp(String.raw`(${Ye})\s+divides\s+(${Ye})`,"gi"),"(($2) mod ($1) = 0)"),t=t.replace(new RegExp(n+String.raw`is\s+(not\s+)?(even|odd)(?![\w.])`,"gi"),(e,t,r,n)=>`((${t}) mod 2 ${"even"===n.toLowerCase()!==Boolean(r)?"=":"≠"} 0)`),t=t.replace(new RegExp(n+String.raw`is\s+(not\s+)?a\s+whole\s+number(?![\w.])`,"gi"),(e,t,r)=>r?`((${t}) ∉ ℤ ∨ (${t}) < 0)`:`((${t}) ∈ ℤ & (${t}) ≥ 0)`);for(const[e,r]of nt)t=t.replace(Ke(e),` ${r} `);t=t.replace(Ke("is not in")," ∉ ").replace(Ke("is in")," ∈ ").replace(Ke("is an element of")," ∈ ");for(const[e,r]of Qe)t=t.replace(Ke(e),` ${r} `);t=t.replace(Ke("is not")," ≠ "),t=t.replace(/(?<=[\w.)\]}′]\s+)is(?=\s+[\w.(\[{-])/gi," = ");for(let e=!0;e;){const r=t;t=t.replace(new RegExp(String.raw`(${Ye})\s*(${et})\s*(${Ye})\s+(and|or)\s+(${et})`,"gi"),"$1 $2 $3 $4 $1 $5"),e=t!==r}t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?absolute\s+value\s+of\s+(${Ye})`,"gi"),"abs($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?square\s+root\s+of\s+(${Ye})`,"gi"),"sqrt($1)"),t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?cube\s+root\s+of\s+(${Ye})`,"gi"),"root(3, $1)"),t=t.replace(new RegExp(String.raw`(${Ye})\s+to\s+the\s+power\s+of\s+(${Ye})`,"gi"),"($1)^($2)"),t=t.replace(new RegExp(String.raw`(${Ye})\s+to\s+the\s+(${Object.keys(tt).join("|")}|(\d+|n)(?:st|nd|rd|th))(?:\s+power)?(?![\w.])`,"gi"),(e,t,r,n)=>`(${t})^(${tt[r.toLowerCase()]??n})`),t=t.replace(new RegExp(String.raw`(${Ye})\s+to\s+the\s+(${Ye})(?![\w.])`,"gi"),"($1)^($2)");for(const[e,r]of rt)t=t.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?${Je(e)}\s+of\s+(${Ye})`,"gi"),`${r}($1)`);t=t.replace(new RegExp(String.raw`(${Ye})\s+squared(?![\w.])`,"gi"),"($1)^2"),t=t.replace(new RegExp(String.raw`(${Ye})\s+cubed(?![\w.])`,"gi"),"($1)^3"),t=t.replace(new RegExp(String.raw`(?<![\w.])half\s+of\s+(${Ye})`,"gi"),"($1)/2"),t=t.replace(new RegExp(String.raw`(?<![\w.])twice\s+(${Ye})`,"gi"),"2*($1)"),t=t.replace(new RegExp(String.raw`(\d+(?:\.\d+)?)\s+percent(?![\w.])`,"gi"),"$1%");const o=e=>new RegExp(String.raw`(?<=[\w.′)\]}]\s+)${Je(e)}(?=\s+[\w.(\[{-])`,"gi");for(const[e,r]of[["divided by","/"],["over","/"],["multiplied by","*"],["times","*"],["plus","+"],["minus","-"],["modulo","mod"]])t=t.replace(o(e),` ${r} `);return t}],["words",st],["spaced",function(e){e=function(e){for(let t=e.lastIndexOf("\\sqrt");t>=0;t=t>0?e.lastIndexOf("\\sqrt",t-1):-1){let r=t+5;if(/[A-Za-z]/.test(e[r]??""))continue;for(;y(e[r]);)r++;const n=e.slice(r);let o=/^(?:§\d+§|-?(?:\d+(?:\.\d+)?|\.\d+)|-?[A-Za-zͰ-Ͽ])/.exec(n)?.[0];if(!o&&/^\\[A-Za-z]/.test(n)&&!n.startsWith("\\left")){let e=/^\\[A-Za-z]+/.exec(n)[0].length;if(/^\d\d/.exec(n.slice(e))&&/frac$/.test(n.slice(0,e)))e+=2;else{const t=/^\s*\[[^\[\]{}]*\]/.exec(n.slice(e));for(t&&(e+=t[0].length);;){let t=e;for(;y(n[t]);)t++;if("{"!==n[t])break;let r=0,o=-1;for(let e=t;e<n.length;e++)if("{"===n[e])r++;else if("}"===n[e]&&0===--r){o=e;break}if(o<0)break;e=o+1}}o=n.slice(0,e)}o&&(e=`${e.slice(0,t)}\\sqrt{${o}}${e.slice(r+o.length)}`)}return e}(function(e){return e=e.replace(C,(e,t,r)=>`(${t}+${F[r]})`),e=e.replace(q,(e,t,r,n)=>Number(r)<Number(n)&&3!==r.length?`(${t}+${r}/${n})`:e),e.replace(L,(e,t,r,n,o,s)=>{const[a,i]=[r??o,n??s];return Number(a)<Number(i)?`(${t}+\\frac{${a}}{${i}})`:e})}(function(e){return e.replace(R,e=>{const t=e[0]in I;return`${t?"^":"_"}{${[...e].map(e=>(t?I:T)[e]).join("")}}`})}(e))),e=function(e){return e.replace(/(?:\{\s*\}|(?<![\w}\])′]))_\s*(?:\{\s*([^{}]+?)\s*\}|([A-Za-z0-9]+?))\s*(?:\\mathrm\{([CP])\}|([CP]))\s*_\s*(?:\{\s*([^{}]+?)\s*\}|([A-Za-z0-9]))/g,(e,t,r,n,o,s,a)=>`${"C"===(n??o)?"comb":"perm"}(${t??r},${s??a})`)}(function(e){return e.replace(/(?<![A-Za-z\\])([A-Za-z])\^\s*\{?\s*\(\s*([1-9]\d*)\s*\)\s*\}?(?=\s*\()/g,(e,t,r)=>{if(r.length>3||Number(r)>N)throw new Error(`A derivative f^{(n)} is read up to n = ${N}`);return t+"′".repeat(Number(r))})}(function(e){return e.replace(/(?<![A-Za-z\\])(arc)?(sine|cosine|tangent|secant|cosecant|cotangent)(?![A-Za-z])(?=\s*\(|\s+(?:[A-Za-z](?![A-Za-z])|\d|\\))/gi,(e,t,r)=>(t?"arc":"")+S[r.toLowerCase()])}(e))),e=function(e){if(/\\[io]*int|∫|(?<![A-Za-z])int\(|\\partial|∂|(?<![A-Za-z])d\s*\/\s*d|frac\s*\{\s*(?:\\mathrm\s*\{\s*d\s*\}|\\operatorname\s*\{\s*d\s*\}|d)/.test(e))return e;const t=[];for(const r of e.matchAll(v)){const n=e.slice(0,r.index),o=e.slice(r.index+r[0].length),s="d"!==r[1];if(!s&&(/[A-Za-z0-9\\^_/]$|frac\s*\{$/.test(n)||/^\s*[/}]/.test(o)&&!/\{\s*$/.test(n)))continue;const a=s||/\\[,;:! ]\s*$/.test(n);t.push({m:r,strong:a})}const r=t.length>=2?t:t.filter(e=>e.strong);for(const{m:t}of r.reverse())e=e.slice(0,t.index)+x+t[2]+e.slice(t.index+t[0].length);return e}(e),/\\/.test(e)||(e=_(e)),e=G(e=function(e){for(let t=0;t<e.length;t++){const r=r=>e.slice(Math.max(0,t-r),t+1);if("t"===e[t]&&"\\text"===r(4)&&"{"===e[t+1]){let r=1,n=t+2,o="";for(;r>0&&n<e.length;)"{"===e[n]?r++:"}"===e[n]?r--:o+=e[n],n++;e=e.slice(0,t-4)+o+e.slice(n)}}return e}(e=(e=(e=function(e){for(let t=0;t<100;t++){const t=[...e.matchAll(/\bif\b/gi)];if(!t.length)return e;const r=t[t.length-1].index,n=B(e,r+2,"then");if(n<0)return e;const o=e.slice(r+2,n),s=B(e,n+4,"else"),a=D(e,s<0?n+4:s+4),i=e.slice(n+4,s<0?a:s),l=s<0?"unchanged":e.slice(s+4,a).trim();e=`${e.slice(0,r)}((${o.trim()}) ? (${i.trim()}) : (${l}))${e.slice(a)}`}return e}(e=e.replace(/(?<![.\w=])\.\.\.(?![.\w=])/g,"⋯").replace(/∅/g,"\\{\\}"))).replace(/\(\s*\\?b?mod\s+([^()\s](?:[^()]*[^()\s])?)\s*\)/g," \\pmod{$1}")).replace(/(^|[^A-Za-z\\])lim\s+([^\s_{}]+?)\s*(->|→|\\to)\s*([^\s]+)\s+/g,"$1lim_{$2→$4} ")));for(let t=0;t<e.length-1;t++)if("?"===e[t]&&":"!==e[t+1])e=Z(e,t);else if("_"===e[t]||"^"===e[t]){const r=/^§\d+§/.exec(e.slice(t+1));if(r){e=`${e.slice(0,t+1)}{${r[0]}}${e.slice(t+1+r[0].length)}`;continue}const n=("^"===e[t]||/[A-Za-z}]/.test(e[t-1]??""))&&/^\\[A-Za-z]+(?![A-Za-z{\d])/.exec(e.slice(t+1));if(n){e=`${e.slice(0,t+1)}{${n[0]}}${e.slice(t+1+n[0].length)}`;continue}let o=t+1;for("-"===e[o]&&o++;o<e.length&&".0123456789".includes(e[o]);)o++;if(o===t+2&&"-"===e[t+1]&&(o=t+1),"-"===e[t+1]&&/^\s*[\^!]/.test(e.slice(o,o+8)))continue;o>t+1&&(e=e.slice(0,t+1)+"{"+e.slice(t+1,o)+"}"+e.slice(o))}return e}],["squeeze",function(e){return(e=e.replace(/(?<![\d.])\d{1,3}(?:[ \u00A0\u202F]\d{3})+(?![\d])/g,e=>e.replace(/[ \u00A0\u202F]/g,""))).replace(/\s+/g,(t,r)=>{const n=e[r-1]??"",o=e[r+t.length]??"";return"Δ"===n?"":/[A-Za-z\u0370-\u03FF′]/.test(n)&&/[A-Za-z\u0370-\u03FF]/.test(o)||/[A-Za-z\u0370-\u03FF′]/.test(n)&&/^\\[A-Za-z]/.test(e.slice(r+t.length,r+t.length+2))&&!/\\[A-Za-z]+$/.test(e.slice(0,r))||/[A-Za-z\u0370-\u03FF′]/.test(n)&&/\d/.test(o)&&!/\\[A-Za-z]+$/.test(e.slice(0,r))?" ":/\d/.test(n)&&/\d/.test(o)&&!/\\[A-Za-z]+\s*\d*$/.test(e.slice(0,r))?"*":""})}],["symbols",at],["bar",function(e){let t=0;for(let r=e.indexOf(l,t);r>=0;r=e.indexOf(l,t)){let n=0,o=-1;for(let t=r+1;t<e.length;t++)if("([{".includes(e[t]))n++;else if(")]}".includes(e[t]))n--;else if(0===n&&e.startsWith("|_",t)){o=t;break}o<0&&lt(),e=`${e.slice(0,r+1)}(${e.slice(r+1,o)})${e.slice(o)}`,t=r+1}return e}],["compact",function(e){if(e=function(e){for(let t=0;t<e.length;t++){const r=t>0&&ee.test(e[t-1]);let n,o=null,s=t;if(e.startsWith("frac{",t)){const r=te(e,t+4),n=r&&te(e,r[1]);o=n&&ne(r[0],n[0]),o&&(s=n[1])}else if("d"===e[t]&&!r){let[r,n]=re(e,t+1),a="";if(ee.test(e[n]??"")&&"/"===e[n+1]&&(a=e[n++]),"/"===e[n]&&"d"===e[n+1]&&ee.test(e[n+2]??"")){const t=e[n+2],[,i]=re(e,n+3);o={n:r,of:a,by:t},s=i}}if(o){if(o.of)n=se(o.of,o.by,o.n);else{const[t,r]=oe(e,s);if(!t)continue;n=se(t,o.by,o.n),s=r}e=e.slice(0,t)+n+e.slice(s),t+=3}}return e}(e=function(e){for(let t=e.indexOf(")′");t>=0;t=e.indexOf(")′",t+1)){let r=0,n=-1;for(let o=t;o>=0;o--)if(")"===e[o])r++;else if("("===e[o]&&0===--r){n=o;break}if(n<0)continue;for(;n>0&&/[A-Za-z\u0370-\u03FF′]/.test(e[n-1]);)n--;let o=0;for(;"′"===e[t+1+o];)o++;e=e.slice(0,n)+se(e.slice(n,t+1),"x",o)+e.slice(t+1+o),t=n}return e}(e=(e=G(e)).replace(/(?<![A-Za-z])frac(\d)(\d)/g,"frac{$1}{$2}"))),e.split("\\int").length>101)throw new Error("More than 100 integrals");for(let t=0;t<e.length;t++){const r=e[t],n=r=>e.slice(Math.max(0,t-r),t),o=r=>e.slice(Math.max(0,t-r),t+1);if("{"===r){if("\\begin"===n(6)){const r=V(e.slice(t+1));r&&(e=e.slice(0,t-6)+r)}}else if("["===r)"\\sqrt"===n(5)?e=e.slice(0,t-5)+"sqrt"+H(e.slice(t+1)):"sqrt"===n(4)&&(e=e.slice(0,t-4)+"sqrt"+H(e.slice(t+1)));else if("⌊"===r||"⌈"===r)e=e.slice(0,t)+W(e.slice(t));else if("t"===r)"\\int"===o(3)&&(e=e.slice(0,t-3)+J(e.slice(t+1)));else if("m"===r)"\\binom"===o(5)&&(e=e.slice(0,t-5)+"\\binom"+Q(e.slice(t+1)));else if("d"===r&&"dd"===o(1)&&"("===e[t+2]){const r=K(e.slice(t+1));r&&(e=e.slice(0,t-1)+"der"+r)}}return(e=e.replace(/\\(?:text|textrm|textit|mathrm|mathit|mathbf|mathsf|operatorname)\{([A-Za-z])\}/g,"$1")).replace(/\\log/g,"log")}],["bars",function(e){for(let t=e.indexOf(l);t>=0;t=e.indexOf(l)){const r=lt;e.startsWith("(der(",t+1)||r();const n=ct(e,t+1,"(",")"),o=ct(e,t+5,"(",")");(o<0||n!==o+1)&&r();const s=ut(e.slice(t+6,o));(s.length<2||s.length>3||!e.startsWith("|_",n+1))&&r();const a=n;let i,l;"{"===e[a+3]?(l=ct(e,a+3,"{","}"),l<0&&r(),i=e.slice(a+4,l)):(l=a+3,i=e[l]??"");const[c,u,p]=s;i.trim()||r();const h=i.includes("=")?i:`${u}=${i}`;e=`${e.slice(0,t)}der(${c},${h}${p?`,${p}`:""})${e.slice(l+1)}`}return e}],["tidy",e=>e.replace(/ {2,}/g," ").trim()]],lt=()=>{throw new Error("A bar with one limit (\\left. … \\right|_{x = a}) is read only after a derivative, \\left.\\frac{d}{dx} f\\right|_{x=a}; with two, \\left. F \\right|_a^b, it is F at b minus F at a")};function ct(e,t,r,n){let o=0;for(let s=t;s<e.length;s++)if(e[s]===r)o++;else if(e[s]===n&&0===--o)return s;return-1}function ut(e){const t=[];let r=0,n=0;for(let o=0;o<e.length;o++)"([{".includes(e[o])?r++:")]}".includes(e[o])?r--:","===e[o]&&0===r&&(t.push(e.slice(n,o)),n=o+1);return t.push(e.slice(n)),t}function pt(e,t={}){if("string"!=typeof e)throw new Error("Expression must be a string");const{text:r,strings:n}=function(e){const t=new Map;let r="",n=0;for(;n<e.length;){const o=e[n];if('"'!==o&&"'"!==o&&"`"!==o){r+=e[n++];continue}let s=n+1,a="",i=!1;for(;s<e.length&&(i||e[s]!==o);)i=!i&&"\\"===e[s],a+=e[s++];const l=le(t.size);t.set(l,o+a+o),r+=l,n=s+1}return{text:r,strings:t}}(ue(e));let o=r.replace(/\t/g," ");t.evaluate&&(o=function(e,t,r){const n=/\\[A-Za-z]/.test(e);let o=0;for(;;){let s=e.indexOf("{{",o);if(s<0)return e;let a=!1;const i=n&&ht.test(e.slice(0,s));if(ft(e,s)||i&&"{"===e[s+2]?s+=1:a=i,!e.startsWith("{{",s)){o=s;continue}const l=mt(e,s);if(l<0)return e;let c=e.slice(s+2,l).trim();for(const[e,r]of t)c=c.split(e).join(r);try{let n=r(c);if(/^["'`]/.test(n)){const e=le(t.size);t.set(e,n),n=e}const i=e.slice(0,s).trimEnd(),u=e.slice(l+2).trimStart();/^[\d.]/.test(n)&&(/[\d.]$/.test(i)||/^[\d.]/.test(u))&&(n=`(${n})`),a&&(n=`{${n}}`),e=e.slice(0,s)+" "+n+" "+e.slice(l+2),o=s+1+n.length}catch{o=l+2}}}(o,n,t.evaluate));const s=[["strings",o]];for(const[e,t]of it){if(o=t(o),o.length>1e5)throw new Error("The expression expands too much when read");s.push([e,o])}return{cleaned:o,stringMap:n,steps:s}}const ht=/(?:\\[A-Za-z]+\*?|[\^_}\]])$/;function ft(e,t){let r=0;for(;"\\"===e[t-1-r];)r++;return r%2==1}function mt(e,t){let r=0;for(let n=t+2;n<e.length;n++){if(e.startsWith("}}",n)&&0===r)return n;"{"===e[n]?r++:"}"===e[n]&&r--}return-1}const gt=-1,dt={"+":{prec:50,assoc:"left",arity:2,fixity:"infix"},"-":{prec:50,assoc:"left",arity:2,fixity:"infix"},"±":{prec:50,assoc:"left",arity:2,fixity:"infix"},"*":{prec:70,assoc:"left",arity:2,fixity:"infix"},"/":{prec:70,assoc:"left",arity:2,fixity:"infix"},"^":{prec:80,assoc:"right",arity:2,fixity:"infix"},mod:{prec:45,assoc:"left",arity:2,fixity:"infix"},neg:{prec:75,assoc:"none",arity:1,fixity:"prefix"},pm:{prec:75,assoc:"none",arity:1,fixity:"prefix"},"!":{prec:90,assoc:"none",arity:1,fixity:"postfix"},_:{prec:100,assoc:"none",arity:2,fixity:"infix"},sqrt:$t(1),abs:$t(1),floor:$t(1),ceil:$t(1),det:$t(1),ln:$t(1),loglog:$t(1),logloglog:$t(1),expm1:$t(1),sin:$t(1),cos:$t(1),tan:$t(1),csc:$t(1),sec:$t(1),cot:$t(1),sinh:$t(1),cosh:$t(1),tanh:$t(1),arcsin:$t(1),arccos:$t(1),arctan:$t(1),arcsec:$t(1),arccsc:$t(1),arccot:$t(1),arcsinh:$t(1),arccosh:$t(1),arctanh:$t(1),random:$t(0),log:$t(2),root:$t(2),atan2:$t(2),round:$t(2),fixed:$t(2),perm:$t(2),comb:$t(2),der:$t(2),evaluated:$t(4),setbuilder:$t(2),max:$t(gt),min:$t(gt),gcd:$t(gt),mean:$t(gt),sum:$t(gt),prod:$t(gt),int:$t(gt),lim:$t(gt),"\\sumidx":$t(gt),"\\prodidx":$t(gt),pmatrix:$t(gt),bmatrix:$t(gt),vmatrix:$t(gt),"()":yt(),"[]":yt(),"{}":yt(),"(]":yt(),"[)":yt(),"=":{prec:30,assoc:"left",arity:2,fixity:"infix"},"===":{prec:30,assoc:"left",arity:2,fixity:"infix"},"≠":{prec:30,assoc:"left",arity:2,fixity:"infix"},"≠=":{prec:30,assoc:"left",arity:2,fixity:"infix"},"<":{prec:34,assoc:"left",arity:2,fixity:"infix"},">":{prec:34,assoc:"left",arity:2,fixity:"infix"},"≤":{prec:34,assoc:"left",arity:2,fixity:"infix"},"≥":{prec:34,assoc:"left",arity:2,fixity:"infix"},"∈":{prec:32,assoc:"left",arity:2,fixity:"infix"},"∉":{prec:32,assoc:"left",arity:2,fixity:"infix"},"∪":{prec:33,assoc:"left",arity:2,fixity:"infix"},"∩":{prec:33,assoc:"left",arity:2,fixity:"infix"},"≈":{prec:30,assoc:"left",arity:2,fixity:"infix"},"≡":{prec:30,assoc:"left",arity:2,fixity:"infix"},pmod:{prec:2,assoc:"left",arity:2,fixity:"infix"},"→":{prec:38,assoc:"left",arity:2,fixity:"infix"},"\\not":{prec:85,assoc:"none",arity:1,fixity:"prefix"},"&":{prec:20,assoc:"left",arity:2,fixity:"infix"},"\\xor":{prec:19,assoc:"left",arity:2,fixity:"infix"},"|":{prec:18,assoc:"left",arity:2,fixity:"infix"},"\\nor":{prec:17,assoc:"left",arity:2,fixity:"infix"},"\\nand":{prec:17,assoc:"left",arity:2,fixity:"infix"},"\\implies":{prec:15,assoc:"right",arity:2,fixity:"infix"},"\\iff":{prec:14,assoc:"left",arity:2,fixity:"infix"},"?:":{prec:10,assoc:"right",arity:3,fixity:"infix"}};function $t(e){return{prec:100,assoc:"none",arity:e,fixity:"prefix"}}function yt(){return{prec:5,assoc:"left",arity:gt,fixity:"none",group:!0}}const bt="\\:",wt=e=>"string"==typeof e&&e.startsWith(bt)&&e.length>2;function xt(e){return Object.prototype.hasOwnProperty.call(dt,e)?dt[e]:wt(e)?vt:void 0}const vt=$t(gt),_t=e=>xt(e)?.prec;function At(e,t,r){if("mod"===e&&t)return _t(t)<=70;if("mod"===t&&["*","/"].includes(e))return!0;if("mod"===t&&["+","-","±"].includes(e))return"right"===r;const n=_t(e),o=_t(t);if(!n||!o)return!1;if(o!==n)return o<n;const s=xt(e).assoc;return"left"===s?"right"===r:"right"===s&&"left"===r}const Et={alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω"};function zt(e,t,r){const n=e=>"symbol"===e.type?e.value===t?r:e:"op"!==e.type?e:Mt.has(e.op)&&function(e,t){if("setbuilder"===e.op){const r=e.args[0];return("symbol"===r.type?r.value:r.args?.[0]?.value)===t}const r=e.args[1];return"symbol"===r?.type?r.value===t:"op"===r?.type&&["=","→"].includes(r.op)&&"symbol"===r.args[0]?.type&&r.args[0].value===t}(e,t)?{...e,id:void 0,args:e.args.map((t,r)=>function(e,t,r,n){if("setbuilder"===e)return 0===r&&"op"===t.type&&"∈"===t.op?{...t,id:void 0,args:[t.args[0],n(t.args[1])]}:t;if(0===r)return t;if(1===r)return"op"!==t.type||"="!==t.op&&"→"!==t.op?t:{...t,id:void 0,args:[t.args[0],...t.args.slice(1).map(n)]};return n(t)}(e.op,t,r,n))}:{...e,id:void 0,args:e.args.map(n)};return n(e)}const Mt=new Set(["der","int","lim","\\sumidx","\\prodidx","evaluated","setbuilder"]);function kt(e){if("*"!==e.op)return!1;const[t,r]=e.args;return"number"===t.type&&"-1"===t.value&&"-1"!==function(e){for(;"op"===e.type&&e.args.length;)e=e.args[0];return"op"===e.type?"":e.value}(r)}function Ot(e,t){if("number"!==e.type||!/^\d+$/.test(e.value))return NaN;const r=Number(e.value);return r<t?r:NaN}const jt=new Set(["<",">","≤","≥","=","===","≠","≠=","&","|","\\not","\\xor","\\nand","\\nor","\\implies","\\iff","∈","∉","≈","≡"]);function St(e){return"op"===e.type&&(!!("="===e.op&&(t=e.args[1],"op"===t.type&&jt.has(t.op)||"symbol"===t.type&&("true"===t.value||"false"===t.value)))||e.args.some(St));var t}const Nt=new Set(["<",">","≤","≥","=","≠"]);function It(e){if("op"!==e.type||!Nt.has(e.op)||2!==e.args.length)return null;const[t,r]=e.args;if("op"!==t.type||!Nt.has(t.op)||2!==t.args.length)return null;return{type:"op",op:"&",args:[It(t)??t,{type:"op",op:e.op,args:[t.args[1],r]}]}}for(const e of[Et])Object.setPrototypeOf(e,null);const Tt={pmatrix:["(",")"],bmatrix:["[","]"],vmatrix:["|","|"]};function Rt(e){return"number"===e.type||"op"===e.type&&"neg"===e.op&&"number"===e.args[0]?.type?"number":"symbol"!==e.type||"true"!==e.value&&"false"!==e.value?"string"===e.type?"text":null:"boolean"}const Ft={__proto__:null,number:"a number",boolean:"true or false",text:"text"};function Ct(e){if(!e||"op"!==e.type)return null;if(Object.prototype.hasOwnProperty.call(Tt,e.op))return e.args.map(e=>"op"===e.type&&"[]"===e.op?e.args:[e]);if("[]"!==e.op||!e.args.length||!e.args.every(e=>"op"===e.type&&"[]"===e.op))return null;const t=e.args[0].args.length;return!t||!e.args.every(e=>e.args.length===t)||e.args.length<2&&t<2?null:e.args.map(e=>e.args)}const qt=Object.keys(c).filter(e=>100===c[e]&&/^[a-z]{2,}$/.test(e)),Lt=["frac"],Pt=[...Object.keys(Et),"pi","tau","inf","infinity","exp"],Ut="\n cost costs coast cosine cosines cosy sine sines since sincere sinus single\n tank tanks tango stand stank\n point points print prints paint paints pint pints mint hint hints lint tint saint faint joint into\n spin spine pipe pipes pine pines pick picks pink pity pie pies pilot pivot pixel pizza piano\n order orders under wonder border render older elder ladder cider rider wider bidder\n logic logo logs blog clog login slog\n model models mode modes modal modest modern module modules\n limb limbs slim lime limo limit limits climb\n maxi minute minutes mince mind mine mines\n sums sumo summit rounds floors ceils means meant sect sects secs expo kiln\n meta metal metals taxi must mute muse nut nuts\n".trim().split(/\s+/),Bt=new Set([...Pt,...Ut,"simplify","expand","factor","cancel","diff","integrate","solve","approx","limit","true","false","null","undefined","unchanged","deg","mod","pmod","NaN","Infinity"]),Dt=/^[a-zA-ZͰ-Ͽ]$/,Zt=new Set(["f","g","h","u","v","F","G","H"]),Gt=e=>qt.includes(e)||Lt.includes(e),Wt=[...qt,...Lt,...Pt].sort((e,t)=>t.length-e.length),Ht=[...qt,...Lt,"pi"].sort((e,t)=>t.length-e.length);function Xt(e,t=Wt){const r=[];let n=0;for(;n<e.length;){const o=t.find(t=>e.startsWith(t,n))??e[n];r.push(o),n+=o.length}return r}function Vt(e){if(Gt(e))return!0;const t=Xt(e,Ht);return t.length>1&&Gt(t[t.length-1])&&!Bt.has(e)}function Yt(e,{mode:t="plain",followed:r=!0}={}){if(e.includes("′")&&/^[a-zA-Z′]+$/.test(e)&&!/^.′+$/.test(e))return e.match(/[a-zA-Z]′*/g);if(!((n=e).length>0&&[...n].every(e=>Dt.test(e)))||1===e.length||Bt.has(e)||Gt(e))return[e];var n;if("Δ"===e[0]&&2===e.length)return[e];if("latex"===t)return Jt(Xt(e),r);if(e.length<=2)return[...e];const o=Jt(Xt(e,Ht),r),s=o.findIndex(e=>e.length>1);if(s<0)return[e];if("pi"===o[s]&&!o.some(e=>qt.includes(e)))return 3===e.length?o:[e];const a=s;let i=0,l=0;for(const e of o.slice(s))i=1===e.length?i+1:0,l=Math.max(l,i);return a<=1&&l<=2?o:[e]}function Jt(e,t){const r=e[e.length-1];return t||!qt.includes(r)?e:[...e.slice(0,-1),...r]}const Kt="§",Qt=/[A-Za-zͰ-Ͽ′]/,er=e=>/^[A-Za-zͰ-Ͽ][A-Za-zͰ-Ͽ′]*$/.test(e);function tr(e,t="plain"){if("string"!=typeof e)throw new Error("Tokenizer input must be a string");const r=[];let n="";const o=e=>{n&&(er(n)?r.push(...function(e,t,r){if((e=>ce.test(e))(e))return[e];if(h.includes(t))return function(e,t){if(/^[a-zA-Z]′+$/.test(e))return[bt+e];if("if"===e.toLowerCase())return["\\:if"];if(1===e.length)return Zt.has(e)?[bt+e]:[e];if(u(e))return[e];const r=Yt(e,{mode:t,followed:!0});return r.length>1?r:e.length<=2?[...e]:[bt+e]}(e,r);const n=void 0!==t&&!/[+\-*/=<>),\]}|!≤≥≠]/.test(t);return Yt(e,{mode:r,followed:n})}(n,e,t)):r.push(n),n="")};for(let t=0;t<e.length;t++){const s=e[t];if(s===Kt){o(s);const n=e.indexOf(Kt,t+1);if(n<0)throw new Error(`An unmatched ${Kt}`);const a=e.slice(t,n+1);r.push(h.includes(e[n+1])?bt+a:a),t=n;continue}if("ⅆ"===s&&/[A-Za-z\u0370-\u03FF]/.test(e[t+1]??""))n&&o(s),n="",r.push("d"+e[t+1]),t+=1;else{if(er(n)&&/[0-9]/.test(s)&&u(n+s)){const{op:o,end:a}=rr(e,t,n+s);r.push(o),n="",t=a;continue}if(Qt.test(s)&&"′"!==s&&m(n)&&(r.push(n),n=""),Qt.test(s)&&(""===n?"′"!==s:er(n)))n+=s;else if(/[0-9]/.test(s)&&er(n)&&!Vt(n))n+=s;else if(er(n)&&o(" "===s?e[t+1]:s),"(){}[]".includes(s))n&&r.push(...nr(n,s)),n="",r.push(s);else if("_"!==s&&" "!==s){if(u(n+s)){const{op:o,end:a}=rr(e,t,n+s);r.push(o),n="",t=a;continue}if(u(s)){o(s);const{op:n,end:a}=rr(e,t,s);r.push(n),t=a;continue}n+=s}else o(e[t+1]),"_"===s&&r.push("_")}}if(o(void 0),r.some(e=>/^:/.test(e)))throw new Error("Unmatched ':'");return r}function rr(e,t,r){let n=t;for(;n+1<e.length&&u(r+e[n+1]);)r+=e[n+1],n++;return"!"===r&&"_"===e[n+1]&&n++,{op:r,end:n}}function nr(e,t){if(!h.includes(t))return[e];if("\\"===e[0]){const t=e.slice(1);return[u(t)?t:bt+t]}return m(e)?[e,"*"]:u(e)||Gt(e)||m(e[0])?[e]:[bt+e]}const or=70,sr=100,ar="%mod",ir=/^d[A-Za-z\u0370-\u03FF]$/,lr=e=>h.includes(e),cr=e=>f.includes(e),ur=e=>wt(e)||c[e]===sr&&"_"!==e,pr=new Set(["\\comb","\\perm","comb","perm"]),hr={frac:"/","\\binom":"\\binom"},fr=new Set(["<",">","≤","≥","=","==","===","≠","≠=","!=","!==","&","|","\\not","\\xor","\\implies","\\iff","∈","∉","true","false"]),mr={"\\comb":"comb","\\perm":"perm",deg:"°","π":"pi","∨":"|"};class gr{constructor(e){this.tokens=e,this.pos=0,this.out=[],this.absDepth=0,this.frames=[]}peek(e=0){return this.tokens[this.pos+e]}next(){return this.tokens[this.pos++]}emit(...e){this.out.push(...e)}parseAll(){if(!this.tokens.length)throw new Error("Empty expression");this.parseExpression(0);const e=this.peek();if(void 0!==e)throw new Error(cr(e)?`Unmatched '${e}'`:`Unexpected '${e}'`);return this.out}parseExpression(e,t=!1){this.parseOperand(),this.absorb(e,t)}absorb(e,t=!1){for(;;){const r=this.peek();if(void 0===r||cr(r))return;const n=this.operatorAt(r,t);if(!n||n.lbp<=e)return;n.run()}}operatorAt(e,t){if("|"===e)return this.pipe();if(","===e)return{lbp:5,run:()=>{this.next(),this.frames.length&&(this.frames[this.frames.length-1].comma=!0),this.parseExpression(5),this.emit(",")}};if("?"===e)return{lbp:9,run:()=>this.ternary()};if("mod"===e)return{lbp:c.mod,run:()=>this.modulo()};if(e===ar)return{lbp:or,run:()=>{this.next(),this.parseExpression(or),this.emit("mod")}};if("pmod"===e)return{lbp:c.pmod,run:()=>{this.next(),this.parseScript(),this.emit("pmod")}};if("?:"===e)return{lbp:10,run:()=>{throw new Error("Unmatched ':'")}};if("!"===e)return{lbp:90,run:()=>{this.next(),this.emit("!")}};if("_"===e)return{lbp:sr,run:()=>{this.next(),this.parseScript(),this.emit("_")}};if(pr.has(e))return{lbp:sr,run:()=>{this.next(),this.parseExpression(sr),this.emit(e)}};const r=c[e];if("="===e&&void 0!==r)return{lbp:r,run:()=>this.equals(r)};if(void 0!==r&&!ur(e)&&"\\not"!==e&&!(e in hr)){const t=p.has(e)?r-1:r;return{lbp:r,run:()=>{this.next(),this.parseExpression(t),this.emit(e)}}}return this.startsOperand(e)?this.implicit(e,t):null}implicit(e,t){return{lbp:!t||ur(e)||ir.test(e)?or:71,run:()=>{this.parseExpression(or),this.emit("*")}}}startsOperand(e){return void 0===e||cr(e)||"|"===e?"|"===e:e!==ar&&(!!(lr(e)||ur(e)||e in hr)||!u(e))}pipe(){if(this.absDepth>0)return null;let e=0;for(let t=this.pos;t<this.tokens.length;t++)"|"===this.tokens[t]&&e++;const t="|"===this.peek(1);return e%2==0&&!t&&this.startsOperand(this.peek(1))?this.implicit("|",!1):{lbp:c["|"],run:()=>{this.next(),t&&e%2==0&&this.next(),this.parseExpression(c["|"]),this.emit("|")}}}modulo(){this.next(),this.parseExpression(or,!0),this.emit("mod")}equals(e){this.next(),this.parseExpression(e),fr.has(this.out[this.out.length-1])&&this.questionAhead()&&this.absorb(8),this.emit("=")}questionAhead(){let e=0;for(let t=this.pos;t<this.tokens.length;t++){const r=this.tokens[t];if(lr(r))e++;else if(cr(r)){if(0===e--)return!1}else{if(0===e&&","===r)return!1;if(0===e&&"?"===r)return!0}}return!1}ternary(){if(this.next(),this.parseExpression(10),"?:"!==this.next())throw new Error("Unmatched '?'");this.parseExpression(8),this.emit("?:")}parseOperand(){const e=this.next(),t=this.tokens[this.pos-2],r=this.peek();if(void 0===e)throw new Error("An operator is missing an operand at the end");if(lr(e))return this.bracket(e,"{"===e&&("∈"===t||"∉"===t));if("|"===e)return this.absolute();if("-"===e||"+"===e){return"^"===t&&(void 0===r||cr(r))||lr(t)&&cr(r)?this.emit("\\"+e):"+"===e?this.parseExpression(75):this.negate()}if("±"===e)return this.parseExpression(75),this.emit("pm");if("!"===e||"\\not"===e)return this.parseExpression(85),this.emit("\\not");if(e in hr)return this.parseScript(),this.parseScript(),this.emit(hr[e]);if("log"===e)return this.logarithm();if("lim"===e&&"_"===r)return this.limit();if(("\\sumidx"===e||"\\prodidx"===e)&&"_"===r)return this.bigOperator(e);if(ur(e))return this.functionCall(e);if(e===ar)throw new Error("'%' is missing an operand");if(cr(e)||u(e))throw new Error(`'${e}' is missing an operand`);this.emit(e)}negate(){const e=this.out.length;this.parseExpression(75);const t=this.out.slice(e);1!==t.length||!m(t[0])&&"∞"!==t[0]?this.emit("neg"):this.out[e]="-"+t[0]}bracket(e,t=!1){if(cr(this.peek()))return void this.emit("∅",e+this.next());this.frames.push({comma:!1}),this.parseExpression(0);const{comma:r}=this.frames.pop(),n=this.peek();cr(n)&&(this.next(),r?this.emit(e+n):t&&this.emit("{}"))}absolute(){this.absDepth++,this.parseExpression(0),this.absDepth--,"|"===this.peek()&&this.next(),this.emit("abs")}parseScript(){const e=this.peek();if(lr(e))return this.parseOperand();if("-"===e||"+"===e)return this.parseOperand();if(ur(e))return this.parseOperand();if(this.next(),void 0===e||cr(e)||u(e))throw new Error("Missing a sub- or superscript");this.emit(e)}logarithm(){"_"===this.peek()?(this.next(),this.parseScript()):this.emit("e"),this.argument(),this.emit("log")}limit(){this.next();const e=this.out.length;this.parseScript();const t=this.out.splice(e);this.parseExpression(c["+"],!0),this.emit(...t,",","()","lim")}bigOperator(e){this.next();const t=this.out.length;this.parseScript();let r=this.out.splice(t);"^"===this.peek()&&(this.next(),this.parseScript(),r=[...r,...this.out.splice(t),","]),this.parseExpression(c["+"],!0),this.emit(...r,",","()",e)}functionCall(e){if(void 0===this.peek())return this.emit(e);let t=null;if("^"===this.peek()){this.next();const e=this.out.length;this.parseScript(),t=this.out.splice(e)}if(0===xt(e)?.arity&&!lr(this.peek()))return this.emit(e);this.argument(),this.emit(e),t&&this.emit(...t,"^")}argument(){const e=this.peek();if(lr(e))return this.next(),this.bracket(e);this.parseExpression(or,!0)}}function dr(e,t){e=function(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r],o=e=>"string"==typeof e&&/^[a-zA-Z]$/.test(e);if(Zt.has(n)&&"^ { - 1 } ("===e.slice(r+1,r+7).join(" ")){t.push(bt+n+"⁻¹"),r+=5;continue}const[s,a,i]=e.slice(r+1,r+4),l=o(a)?a!==n:m(a);o(n)&&"e"!==n&&"("===s&&l&&")"===i?t.push(bt+n):t.push(n)}return t}(e);const r=[];for(const n of e)u(n)||lr(n)||cr(n)||"_"===n||wt(n)||m(n)?r.push(n):r.push(...$r(n,t));return r}function $r(e,t){if("%"===e)return[ar];if(!e.includes("%"))return yr(e,t);const r=e.split("%");r.length>1&&""===r[r.length-1]&&(r.pop(),r[r.length-1]+="%");const n=[];return r.forEach((e,r)=>{r>0&&n.push(ar),""!==e&&n.push(...yr(e,t))}),n}function yr(e,t){let r=0;for(;r<e.length&&m(e.slice(0,r+1));)r++;if(0===r||r===e.length)return[e];const n=e.slice(r);return"%"===n?[e]:[e.slice(0,r),...(o=n,dr(tr(o,t),t))];var o}for(const e of[hr,mr])Object.setPrototypeOf(e,null);const br=e=>({type:"number",value:String(e)}),wr=e=>({type:"symbol",value:e}),xr=(e,t)=>({type:"op",op:e,args:t}),vr=['"',"'","`"];function _r(e){return m(e,!0)?br(e):vr.includes(e[0])?{type:"string",value:e}:wr(e)}const Ar={"0-":"neg",sqrtpow:"root",pow:"^","==":"=","!==":"≠="};function Er(e,t,r=null){t(e,r),"op"===e.type&&e.args.forEach(r=>Er(r,t,e))}function zr(e){let t="";return Er(e,e=>{!t&&"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value)&&(t=e.value)}),t}for(const e of[Ar])Object.setPrototypeOf(e,null);const Mr=new Set(["()","[]","{}","(]","[)"]),kr={pow:"^",sqrtpow:"root","\\binom":"comb","\\comb":"comb","\\perm":"perm",frac:"/","==":"=","!==":"≠=",...Object.fromEntries(Object.keys(i).map(e=>[e,"*"]))},Or=new Set(["round","fixed","der"]),jr=e=>wt(e)||100===c[e];function Sr(e){const t=[],r=e=>{if(!t.length)throw new Error(`'${e}' is missing an operand`);return t.pop()},n=e=>e.list?e.list:[e],o=(e,t)=>{if(e.list)throw new Error(`A list of values needs brackets around it (near '${t}')`);return e};if(e.forEach((s,a)=>{if("∅"===s)return void t.push({list:[]});if(","===s){const e=r(s),o=r(s);return void t.push({list:[...n(o),...n(e)]})}if(Mr.has(s)){const o=n(r(s));if(!o.length&&"{}"!==s&&!jr(e[a+1]))throw new Error("Empty brackets");return void t.push(xr(s,o))}const l=kr[s]??s,c=xt(l);if(!c){if("?"===s||"abs("===s)throw new Error(`Unmatched '${s[0]}'`);return void t.push(_r(s))}let u;if(jr(s)&&Mr.has(e[a-1])&&t[t.length-1]?.op===e[a-1])u=t.pop().args;else{let e=c.arity===gt||Or.has(l)?1:c.arity;if(t.length<e)throw new Error(`'${s}' needs ${e} operand${1===e?"":"s"}`);u=t.splice(t.length-e,e).map(e=>o(e,s))}const p=function(e,t){switch(e){case"sqrt":if(2===t.length)return xr("root",t);break;case"round":if(1===t.length)return xr("round",[t[0],br(0)]);break;case"sum":case"prod":{const r=t[1];if("op"===r?.type&&"symbol"===r.args[0]?.type&&(3===t.length&&"="===r.op||2===t.length&&"∈"===r.op))return xr("sum"===e?"\\sumidx":"\\prodidx",t);break}case"evaluated":if(3===t.length)return xr("evaluated",[t[0],wr(zr(t[0])||"x"),t[1],t[2]]);break;case"det":if(t.length>1&&t.every(e=>"op"===e.type&&"[]"===e.op))return xr("det",[xr("[]",t)]);break;case"fixed":if(1===t.length)return xr("fixed",[t[0],br(2)]);break;case"der":if(1===t.length)return xr("der",[t[0],wr("x")]);if(3===t.length)return function([e,t,r]){const n="number"===r.type?Number(r.value):NaN;if(!Number.isInteger(n)||n<1||n>20)throw new Error("der(f, x, n) needs n to be a whole number from 1 to 20");const o="op"===t.type&&"="===t.op?t:null,s=o?o.args[0]:t;let a=e;for(let e=0;e<n;e++)a=xr("der",[a,o&&e===n-1?o:s]);return a}(t);break;case"log":if(2===t.length&&"symbol"===t[0].type&&"e"===t[0].value)return xr("ln",[t[1]]);break;case"lim":return Ir(e,t),xr("lim",function(e){const t=e=>{if("op"!==e.type)return null;if("^"===e.op&&"symbol"===e.args[1].type&&Nr[e.args[1].value])return{point:e.args[0],side:Nr[e.args[1].value]};const r=e.args.length?t(e.args[e.args.length-1]):null;return r&&{point:{...e,args:[...e.args.slice(0,-1),r.point]},side:r.side}},[r,n,o]=e;if(2===e.length&&"op"===n.type&&"→"===n.op){const[e,o]=n.args,s=t(o);if(s)return[r,e,s.point,wr(s.side)]}const s=3===e.length&&t(o);return s?[r,n,s.point,wr(s.side)]:e}(t));case"\\:if":if(2===t.length||3===t.length)return xr("?:",[t[0],t[1],t[2]??wr("unchanged")]);throw new Error("if() takes a condition, a value, and optionally an alternative")}return Ir(e,t),xr(e,t)}(l,u);i[s]&&"*"===p.op&&(p.written=i[s]),t.push(p)}),1!==t.length)throw new Error(t.length?"Some values are not connected by an operator":"Empty expression");const s=["=","<",">","≤","≥","≠","≈","≡","∈","∉"],a=t[0];return a.list&&a.list.length>1&&a.list.every(e=>"op"===e.type&&s.includes(e.op))?a.list.reduce((e,t)=>xr("&",[e,t])):o(t[0],"end")}const Nr={"\\+":"r","\\-":"l"};function Ir(e,t){const{arity:r}=xt(e);if(r!==gt){if(t.length!==r){throw new Error(`'${e}' takes ${r} argument${1===r?"":"s"}, not ${t.length}`)}}else if(0===t.length&&!wt(e))throw new Error(`'${e}' needs at least one argument`)}for(const e of[kr,Nr])Object.setPrototypeOf(e,null);const Tr=new RegExp(`[${Object.keys(i).join("")}]`,"g"),Rr=e=>e.replace(Tr,"*"),Fr=/\\(?:text|textrm|textit|mathrm|mathit|operatorname)\{\s*([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\s*\}/g;const Cr=e=>/^[a-z][a-z0-9]*$/.test(e)&&u(e);function qr(e){return e.includes("\\")?(e=function(e){return e=j(e),e=_(e),e=e.replace(/\\(?:[Bb]igg?)[lrm]?(?![A-Za-z])\s*/g,""),e=e.replace(/\^\s*(?:\\circ\b|\{\s*\\circ\s*\})|\\degree\b|\\textdegree\b/g,"°"),e=e.replace(/\\(?:cdots|ldots|dotsb|dotsc|dots)(?![A-Za-z])/g,"⋯"),e=e.replace(/(\d*)\.(\d*)\\overline\s*\{\s*(\d+)\s*\}/g,(e,t,r,n)=>`${t||"0"}.${r}${n}${n}..`),e=e.replace(/\\(?:emptyset|varnothing)(?![A-Za-z])/g,"\\{\\}"),e=e.replace(/\(\s*([A-Za-z])\s*\\circ\s*([A-Za-z])\s*\)\s*\(([^()]*)\)/g,"$1($2($3))"),e}(e=function(e){for(let t=0;t<50;t++){const t=e.lastIndexOf("\\begin{cases}"),r=t<0?-1:e.indexOf("\\end{cases}",t);if(r<0)return e;const n=U(e.slice(t+13,r),"\\\\").map(e=>U(e,"&")).filter(e=>e.join("").trim());let o=null;const s=/=|<|>|\\(?:le|ge|leq|geq|neq|ne|lt|gt)(?![A-Za-z])/;if(n.length>1&&n.every(e=>1===e.length&&s.test(e[0])))o=n.map(e=>`(${e[0].trim().replace(/\s*[,;.]$/,"")})`).join(" \\land "),e=e.slice(0,t)+`(${o})`+e.slice(r+11);else{for(let e=n.length-1;e>=0;e--){const t=n[e][0].trim().replace(/\s*[,;]$/,""),r=P(n[e].slice(1).join("&"));o=null!==o||r?`((${r||"true"}) ? (${t}) : ${o??"(unchanged)"})`:`(${t})`}e=e.slice(0,t)+(o??"")+e.slice(r+11)}}return e}(e))).replace(/\{\}\^\{([^{}]*)\}\s*\\mathrm\{P\}\s*_\{([^{}]*)\}/g,"\\perm($1,$2)"):/[\]|]\s*_/.test(e)?j(e):e}function Lr(e,t={}){const r={original:e};try{if("string"!=typeof e)throw new Error("Expression must be a string");const n=t.maxLength??5e3;if(e.length>n)throw new Error(`Longer than ${n} characters (options.maxLength)`);if(e.includes(""))throw new Error("The character U+E000 can't be read: MathZetta uses it to hold § in strings");if((e=function(e,t,r){if(!e.includes(t))return e;const n=ue(e);let o="";for(let s=0;s<n.length;s++){const a=n[s];if('"'===a||"`"===a||"'"===a){const a=pe(n,s);o+=e.slice(s,a+1).replaceAll(t,r),s=a}else o+=e[s]}return o}(e,Kt,"")).includes(Kt))throw new Error(`The character ${Kt} can't be read: MathZetta uses it to mark names`);const o=/^\s*=(?!=)/.test(e);o&&(e=e.replace(/("(?:[^"]|"")*")|\$(?=[A-Za-z]{0,3}\d|[A-Za-z]{1,3}\$?\d)/g,(e,t)=>t??""));const s=o?[...new Set(e.replace(/"(?:[^"]|"")*"/g,"").match(/(?<![\w.])[A-Za-z]{1,3}\d+(?::[A-Za-z]{1,3}\d+)?(?![\w.(])/g)??[])]:[],{text:a,protectedNames:i}=function(e,t=[],r=[]){const n=new Map,o=new Map,s=e=>{let t=o.get(e);return void 0===t&&(t=`${Kt}${n.size}${Kt}`,n.set(t,e),o.set(e,t)),t};e=e.replace(Fr,(e,t)=>Cr(t.trim())?` ${t.trim()}`:s(t.trim()));for(const r of[...t].sort((e,t)=>t.length-e.length)){const t=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp(`(?<![A-Za-z_])${t}(?![A-Za-z0-9_])`,"g"),()=>s(r))}for(const t of[...r].sort((e,t)=>t.length-e.length)){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp(`(?<![A-Za-z_])${r}(?![A-Za-z0-9_])(\\s*)(\\(?)`,"g"),(e,r,n)=>s(t)+(n?" * (":r))}return{text:e,protectedNames:n}}(qr(e),t.names,[...t.values??[],...s]),l=(e=>/\\[A-Za-z]/.test(e)?"latex":"plain")(a),{cleaned:c,stringMap:u,steps:p}=function(e,t={}){const r=void 0===t.blocks?null:t.blocks;return pt(e,{evaluate:r?e=>r(e,t.scope):void 0})}(a,{blocks:t.blocks,scope:t.scope}),h=e=>fe(fe(e,u),i).map(e=>"string"==typeof e?e.replaceAll("",Kt):e);r.mode=l,r.cleaned=Rr(h([c])[0]),r.cleanSteps=p.map(([e,t])=>[e,Rr(t)]);const f=tr(c,l);r.tokens=f.map(Rr);const m=h(function(e,t="plain"){return new gr(dr(e,t)).parseAll().map(e=>mr[e]??e)}(f,l));r.rawPostfix=m.map(Rr);const g={},d=function(e,t){const r=[];return function e(n){"op"===n.type?(n.args.forEach(e),xt(n.op)?.arity===gt&&r.push(String(n.args.length)),t&&n.written&&(t[r.length]=n.written),r.push(n.op)):r.push(n.value)}(e),r}(Sr(m),g);r.postfix=d,r.written=g,r.tree=function(e){if(!Array.isArray(e)||0===e.length)throw new Error("Empty postfix");const t=[],r=[];if(e.forEach((e,n)=>{const o=Ar[e]??String(e),s=xt(o);if(!s)return t.push({..._r(o),id:n}),void r.push(1);let a=s.arity;if(a===gt){const e=t.pop();if(r.pop(),a=e&&"number"===e.type?Number(e.value):NaN,!Number.isInteger(a)||a<0)throw new Error(`'${o}' takes a variable number of arguments, so it must follow a count`);if(0===a&&!s.group&&!wt(o))throw new Error(`'${o}' needs at least one argument`)}if(t.length<a)throw new Error(`'${o}' needs ${a} operand${1===a?"":"s"}`);const i=1+Math.max(0,...r.splice(r.length-a,a));if(i>1e3)throw new Error("Nested too deeply (more than 1000 levels)");r.push(i),t.push({...xr(o,t.splice(t.length-a,a)),id:n})}),1!==t.length)throw new Error(`Postfix leaves ${t.length} values instead of 1`);return t[0]}(d),Object.keys(g).length&&Er(r.tree,e=>{g[e.id]&&(e.written=g[e.id])})}catch(e){r.error=e instanceof RangeError?"Nested too deeply":e.message}return r}function Pr(e,t={}){const r=Lr(e,t);if(r.error)throw new Error(`Failed to parse expression "${n=e,"string"==typeof n&&n.length>80?`${n.slice(0,77)}…`:n}": ${r.error}`);var n;return r.tree}function Ur(e,t={}){const r=300===t.version,n=new Map,o=e=>{let s=n.get(e);if(void 0===s&&"op"===e.type&&"setbuilder"===e.op)throw new Error("No GLSL for a set described by a condition (only a test of membership in one)");const a=void 0===s?function(e){if("op"!==e.type||"∈"!==e.op&&"∉"!==e.op)return null;const[t,r]=e.args;if("op"!==r.type||"setbuilder"!==r.op)return null;let[n,o]=r.args,s=null;if("op"===n.type&&"∈"===n.op&&"symbol"===n.args[0].type&&([n,s]=n.args),"symbol"!==n.type)return null;const a=zt(o,n.value,t),i=s?{type:"op",op:"&",args:[{type:"op",op:"∈",args:[t,s]},a]}:a;return"∉"===e.op?{type:"op",op:"\\not",args:[i]}:i}(e):null;return a&&n.set(e,s=`(${o(a)})`),void 0===s&&n.set(e,s=function(e){if(e.length>1e6)throw new Error("The output would be too long");return e}("op"===e.type?tn(e,o,r,t.filter):function(e){const t=e.value;if("number"===e.type)return Zr(t);const r="symbol"===e.type&&function(e){const t="string"==typeof e&&/^(-?)(\d*)(?:\.(\d*))?%$/.exec(e);if(!t||!t[2]&&!t[3])return null;const r=(t[2]||"0").padStart(3,"0")+(t[3]??""),n=r.length-(t[3]??"").length-2,o=`${r.slice(0,n).replace(/^0+(?=\d)/,"")}.${r.slice(n)}`.replace(/\.?0+$/,"");return t[1]+(""===o?"0":o)}(t);if(r)return Zr(r);if("string"===e.type)throw new Error("No GLSL for text: a shader has numbers and vectors only");if("⋯"===t)throw new Error('No GLSL for ⋯: a sum written out with "and so on" has no value to work out (write it with ∑)');return void 0!==Dr[t]?Dr[t]:"\\+"===t||"\\-"===t?t[1]:Wr(t)}(e))),s};return o(e)}const Br="3.141592653589793",Dr={pi:Br,"π":Br,e:"2.718281828459045",tau:"6.283185307179586","τ":"6.283185307179586","∞":"MZ_INFINITY","-∞":"(-MZ_INFINITY)",true:"true",false:"false"};function Zr(e){let t=e.endsWith("..")?function(e){const t=function(e){const t=/^(-?)(\d*)\.(\d+)\.\.$/.exec(e);if(!t)return null;const[,r,n,o]=t;let s=1;for(let e=1;2*e<=o.length;e++)if(o.slice(-e)===o.slice(-2*e,-e)){s=e;break}const a=o.slice(-s);let i=o;for(;i.endsWith(a);)i=i.slice(0,-s);return{sign:r,whole:n||"0",prefix:i,block:a}}(e);if(!t)return e.replace(/\.+$/,"");const{sign:r,whole:n,prefix:o,block:s}=t;return`${r}${n}.${(o+s.repeat(Math.ceil(20/s.length)+1)).slice(0,Math.max(o.length+s.length,17))}`}(e):e.replace(/\.+$/,"");return t.startsWith(".")&&(t="0"+t),t.startsWith("-.")&&(t="-0"+t.slice(1)),t.includes(".")||(t+=".0"),t}const Gr={"α":"alpha","β":"beta","γ":"gamma","δ":"delta","ε":"epsilon","ζ":"zeta","η":"eta","θ":"theta","ι":"iota","κ":"kappa","λ":"lambda","μ":"mu","ν":"nu","ξ":"xi","ρ":"rho","σ":"sigma","φ":"phi","χ":"chi","ψ":"psi","ω":"omega","Δ":"delta_","Σ":"sigma","Ω":"omega","Φ":"phi","Θ":"theta"},Wr=e=>e.replace(/′/g,"_prime").replace("⁻¹","_inverse").replace(/[^\x00-\x7F]/g,e=>Gr[e]??`_u${e.codePointAt(0).toString(16)}`).replace(/[^A-Za-z0-9_]/g,"_"),Hr={sqrt:"sqrt",abs:"abs",floor:"floor",ceil:"ceil",ln:"log",det:"determinant",sin:"sin",cos:"cos",tan:"tan",arcsin:"asin",arccos:"acos",arctan:"atan",atan2:"atan"},Xr={sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",round:"round"},Vr={csc:"sin",sec:"cos",cot:"tan"},Yr={"=":"==","===":"==","≠":"!=","≠=":"!=","<":"<",">":">","≤":"<=","≥":">="},Jr=new Set(["&","|","\\xor","\\nand","\\nor","\\implies","\\iff","?:","mean","log","≈","∈","∉"]);function Kr(e){return"op"!==e.type?null:["!","perm"].includes(e.op)?"*":["comb","csc","sec","cot"].includes(e.op)?"/":"^"===e.op?function(e){const t=en(e.args[1]);return 1===t?Kr(e.args[0]):null!==t&&t<0&&t>=-4?"/":null}(e):Jr.has(e.op)?null:function(e){return"op"!==e.type||xt(e.op)?.group?null:"sum"===e.op?"+":"prod"===e.op?"*":kt(e)?"neg":e.op}(e)}const Qr=e=>Math.abs(e)>6?`1.0e${e}`:Zr(String(10**e));function en(e){return"number"===e.type&&/^-?\d+$/.test(e.value)?Number(e.value):null}function tn(e,t,r,n=!1){e=function(e,t){if(!["\\sumidx","\\prodidx"].includes(e.op)||3!==e.args.length)return e;const[r,n,o]=e.args;if("op"===n.type&&"="===n.op)return e;const s=t(r);return s?{...e,args:[r,{type:"op",op:"=",args:[{type:"symbol",value:s},n]},o]}:e}(e,zr);const o=It(e);if(o)return t(o);const{op:s,args:a}=e,[i,l]=a,c=(e,r,n=s)=>At(n,Kr(e),r)?`(${t(e)})`:t(e),u=()=>a.map(t).join(", "),p=e=>`${c(i,"left")} ${e} ${c(l,"right")}`,h=e=>sn(e)?t(e):`${c(e,"left","≠")} != 0.0`,f=e=>sn(e)?`float(${t(e)})`:t(e),m=e=>{const r=Kr(e),n=!!r&&At("neg",r,"right"),o=t(e);return n||o.startsWith("-")||"op"===e.type&&["neg","pm"].includes(e.op)?`(${o})`:o},g=function(e){if("op"!==e.type||!["=","===","≠","≠="].includes(e.op)||2!==e.args.length)return null;const[t,r]=e.args.map(Rt);return t&&r&&t!==r?{strict:"==="===e.op||"≠="===e.op,answer:"≠="===e.op,refusal:`= between ${Ft[t]} and ${Ft[r]} (only JavaScript's loose == converts one to the other; === compares them strictly)`}:null}(e);if(g&&!g.strict)throw new Error(`No GLSL for ${g.refusal}`);if(g&&!a.some(e=>"string"===e.type))return g.answer?"true":"false";if("det"===s&&i&&Ct(i))return tn({...e,op:"vmatrix",args:i.args},t,r,n);const d=function(e){if("op"!==e.type||!["arcsec","arccsc","arccot"].includes(e.op))return null;const[t]=e.args,r={type:"op",op:"/",args:[{type:"number",value:"1"},t]};return"arcsec"===e.op?{type:"op",op:"arccos",args:[r]}:"arccsc"===e.op?{type:"op",op:"arcsin",args:[r]}:{type:"op",op:"-",args:[{type:"op",op:"/",args:[{type:"symbol",value:"pi"},{type:"number",value:"2"}]},{type:"op",op:"arctan",args:[t]}]}}(e)??function(e){if("op"!==e.type||"evaluated"!==e.op)return null;const[t,r,n,o]=e.args;return{type:"op",op:"-",args:[zt(t,r.value,o),zt(t,r.value,n)]}}(e);if(d)return`(${t(d)})`;if(Hr[s])return`${Hr[s]}(${u()})`;if(Xr[s]&&"round"!==s)return`${r?Xr[s]:"mz_"+Xr[s]}(${u()})`;if(Vr[s])return`1.0 / ${Vr[s]}(${t(i)})`;if(Yr[s])return p(Yr[s]);if(wt(s))return`${Wr((e=>e.slice(2))(s))}(${u()})`;switch(s){case"+":case"-":case"*":case"/":return"*"===s&&kt(e)?tn({...e,op:"neg",args:[l]},t,r,n):"*"===s&&"symbol"===l.type&&"°"===l.value?`radians(${t(i)})`:p(s);case"mod":return`mod(${t(i)}, ${t(l)})`;case"^":return rn(e,t);case"neg":return"-"+m(i);case"pm":return`vec2(${t(i)}, -${m(i)})`;case"±":return`vec2(${t(i)} + ${c(l,"right","+")}, ${t(i)} - ${c(l,"right","-")})`;case"!":{const e=Ot(i,13);return e<=1?"1.0":e?Array.from({length:e},(t,r)=>e-r+".0").join(" * "):`mz_factorial(${t(i)})`}case"perm":case"comb":{const e=Ot(i,21),r=Ot(l,21);if(e>=r){if(0===r)return"1.0";const t=Array.from({length:r},(t,r)=>e-r+".0").join(" * ");return"perm"===s?t:`(${t}) / (${Array.from({length:r},(e,t)=>`${t+1}.0`).join(" * ")})`}return`mz_${s}(${t(i)}, ${t(l)})`}case"root":{const e=en(i);return 2===e?`sqrt(${t(l)})`:3===e?`mz_cbrt(${t(l)})`:null===e||e%2!=0?`mz_root(${t(i)}, ${t(l)})`:`pow(${t(l)}, 1.0 / ${c(i,"right","/")})`}case"log":return"symbol"===i.type&&"e"===i.value?`log(${t(l)})`:"number"===i.type&&"2"===i.value?`log2(${t(l)})`:`(log(${t(l)}) / log(${t(i)}))`;case"loglog":return`log(log(${t(i)}))`;case"logloglog":return`log(log(log(${t(i)})))`;case"expm1":return`(exp(${t(i)}) - 1.0)`;case"round":case"fixed":{const e=en(l),r=`mz_round(${0===e||null===e?t(i):`${c(i,"left","*")} * ${Qr(e)}`})`;return 0===e||null===e?r:`${r} / ${Qr(e)}`}case"random":return"mz_random()";case"max":case"min":return 1===a.length?"op"===i.type?`(${t(i)})`:t(i):a.map(t).reduce((e,t)=>`${s}(${e}, ${t})`);case"gcd":return a.map(t).reduce((e,t)=>`mz_gcd(${e}, ${t})`);case"mean":return`((${a.map((e,t)=>c(e,t?"right":"left","+")).join(" + ")}) / ${a.length}.0)`;case"sum":return a.map((e,t)=>c(e,t?"right":"left","+")).join(" + ");case"prod":return a.map((e,t)=>c(e,t?"right":"left","*")).join(" * ");case"&":return sn(i)&&sn(l)?`(${t(i)} && ${t(l)})`:`mz_both(${f(i)}, ${f(l)})`;case"|":return sn(i)&&sn(l)?`(${t(i)} || ${t(l)})`:`mz_either(${f(i)}, ${f(l)})`;case"\\xor":return`(${h(i)} ^^ ${h(l)})`;case"\\nand":return`!(${h(i)} && ${h(l)})`;case"\\implies":return`(!(${h(i)}) || ${h(l)})`;case"\\iff":return`((${h(i)}) == (${h(l)}))`;case"\\nor":return`!(${h(i)} || ${h(l)})`;case"\\not":return sn(i)?"!"+m(i):`!(${h(i)})`;case"?:":{const e=e=>n&&"symbol"===e.type&&"unchanged"===e.value,r=(r,n)=>e(r)&&!e(n)?`mz_unchanged(${t(n)})`:t(r);return`(${sn(i)?St(i)?`(${t(i)})`:t(i):h(i)} ? ${r(l,a[2])} : ${r(a[2],l)})`}case"≈":return`(abs(${t(i)} - ${c(l,"right","-")}) < 1e-5)`;case"≡":return p("==");case"pmod":return"op"===i.type&&["≡","="].includes(i.op)?`(mod(${t(i.args[0])} - ${c(i.args[1],"right","-")}, ${t(l)}) == 0.0)`:`mod(${t(i)}, ${t(l)})`;case"∈":case"∉":return function(e,t){const[r,n]=e.args,o=t(r),s="∉"===e.op;if("symbol"===n.type&&an[n.value]){const e=an[n.value](o);return s?`!${e}`:e}if("op"===n.type&&["()","[]","(]","[)"].includes(n.op)&&2===n.args.length){const[e,r]=n.args.map(t),a=`(${o} ${"["===n.op[0]?">=":">"} ${e} && ${o} ${"]"===n.op[1]?"<=":"<"} ${r})`;return s?`!${a}`:a}if("op"===n.type&&"{}"===n.op&&!n.args.length)return s?"true":"false";if("op"===n.type&&"{}"===n.op){const e=`(${n.args.map(e=>`${o} == ${t(e)}`).join(" || ")})`;return s?`!${e}`:e}throw new Error(`No GLSL for ∈ ${"symbol"===n.type?n.value:"this set"}: only intervals, {listed values}, ℝ, ℤ and ℕ`)}(e,t);case"pmatrix":case"bmatrix":case"vmatrix":{const r=Ct(e).map(e=>e.map(t)),n=r.length,o=r.every(e=>e.length===n);if("vmatrix"===s){if(!o||n>3)throw new Error("No GLSL for a determinant bigger than 3 by 3");if(1===n)return r[0][0];const e=r.map(e=>e.map(e=>`(${e})`));if(2===n)return`(${e[0][0]} * ${e[1][1]} - ${e[0][1]} * ${e[1][0]})`;const[[t,s,a],[i,l,c],[u,p,h]]=e;return`(${t} * (${l} * ${h} - ${c} * ${p}) - ${s} * (${i} * ${h} - ${c} * ${u}) + ${a} * (${i} * ${p} - ${l} * ${u}))`}if(o&&n>=2&&n<=4)return`mat${n}(${r[0].map((e,t)=>r.map(e=>e[t]).join(", ")).join(", ")})`;const a=r.flat();if((1===n||r.every(e=>1===e.length))&&a.length>=2&&a.length<=4)return`vec${a.length}(${a.join(", ")})`;throw new Error(`No GLSL for a ${n} by ${r[0].length} matrix`)}case"()":case"[]":case"{}":case"(]":case"[)":if("[]"===s&&Ct(e))return tn({...e,op:"bmatrix"},t,r,n);if(a.some(e=>"op"===e.type&&nn.has(e.op)&&e.args.length>1))throw new Error("No GLSL for a list of lists (only a matrix: rows of one length, at most 4 by 4)");return a.length>=2&&a.length<=4?`vec${a.length}(${u()})`:`float[](${u()})`;case"→":return`${t(i)}, ${t(l)}`;case"_":return"number"===l.type&&/^\d+$/.test(l.value)?`${t(i)}_${l.value}`:"symbol"===l.type?`${t(i)}_${t(l)}`:`${t(i)}[int(${t(l)})]`}if(ln[s])throw new Error(`No GLSL for ${ln[s]}`);throw new Error(`No GLSL for '${s}'`)}function rn(e,t,r){const[n,o]=e.args,s=en(o),a=t(n);if(0===s)return"1.0";if(1===s)return a;if(2===s)return`mz_sq(${a})`;if(3===s)return`mz_cube(${a})`;if(4===s)return`mz_sq(mz_sq(${a}))`;if(null!==s&&s<0&&s>=-4){const e=rn({args:[n,{type:"number",value:String(-s)}]},t);return`1.0 / ${-1!==s||"op"!==n.type||function(e){const t=/^\w+\(/.exec(e)?.[0].length;if(!t)return!1;let r=0;for(let n=t-1;n<e.length;n++)if("("===e[n])r++;else if(")"===e[n]&&0===--r)return n===e.length-1;return!1}(e)?e:`(${e})`}`}return"symbol"===n.type&&"e"===n.value?`exp(${t(o)})`:"number"===n.type&&"2"===n.value?`exp2(${t(o)})`:"op"===o.type&&"/"===o.op&&"number"===o.args[0].type&&"1"===o.args[0].value&&"number"===o.args[1].type&&"2"===o.args[1].value?`sqrt(${a})`:`pow(${a}, ${t(o)})`}const nn=new Set(["()","[]","{}","(]","[)"]),on=new Set([...Object.keys(Yr),"&","|","\\xor","\\nand","\\nor","\\implies","\\iff","\\not","∈","∉","≈","≡"]);function sn(e){return"symbol"===e.type?"true"===e.value||"false"===e.value:"op"===e.type&&("&"===e.op||"|"===e.op?e.args.every(sn):!!on.has(e.op)||("pmod"===e.op?"op"===e.args[0].type&&["≡","="].includes(e.args[0].op):"?:"===e.op?sn(e.args[1])&&sn(e.args[2]):Boolean(It(e))))}const an={"ℝ":e=>`(abs(${e}) < MZ_INFINITY)`,"ℤ":e=>`(fract(${e}) == 0.0)`,"ℕ":e=>`(fract(${e}) == 0.0 && ${e} > 0.0)`};const ln={der:"a derivative",int:"an integral",lim:"a limit","\\sumidx":"a sum to n","\\prodidx":"a product to n","∪":"a union of sets","∩":"an intersection of sets"},cn=["#define MZ_INFINITY (1.0 / 0.0)",...["float","vec2","vec3","vec4"].flatMap(e=>[`${e} mz_sq(${e} x) { return x * x; }`,`${e} mz_cube(${e} x) { return x * x * x; }`,`${e} mz_cbrt(${e} x) { return sign(x) * pow(abs(x), ${e}(1.0 / 3.0)); }`,`${e} mz_root(float n, ${e} x) { return mod(n, 2.0) == 1.0 ? sign(x) * pow(abs(x), ${e}(1.0 / n)) : pow(x, ${e}(1.0 / n)); }`,`${e} mz_round(${e} x) { return sign(x) * floor(abs(x) + 0.5); }`,`${e} mz_sinh(${e} x) { return (exp(x) - exp(-x)) / 2.0; }`,`${e} mz_cosh(${e} x) { return (exp(x) + exp(-x)) / 2.0; }`,`${e} mz_tanh(${e} x) { ${e} a = exp(2.0 * x); return (a - 1.0) / (a + 1.0); }`,`${e} mz_asinh(${e} x) { return log(x + sqrt(x * x + 1.0)); }`,`${e} mz_acosh(${e} x) { return log(x + sqrt(x * x - 1.0)); }`,`${e} mz_atanh(${e} x) { return 0.5 * log((1.0 + x) / (1.0 - x)); }`]),"float mz_factorial(float n) { float r = 1.0; for (int i = 2; i <= 170; i++) { if (float(i) > n) break; r *= float(i); } return r; }","float mz_perm(float n, float k) { float r = 1.0; for (int i = 0; i < 170; i++) { if (float(i) >= k) break; r *= n - float(i); } return r; }","float mz_comb(float n, float k) { return mz_perm(n, k) / mz_factorial(k); }","float mz_both(float a, float b) { return a != 0.0 ? b : a; }","float mz_either(float a, float b) { return a != 0.0 ? a : b; }","float mz_gcd(float a, float b) { a = abs(a); b = abs(b); for (int i = 0; i < 64; i++) { if (b == 0.0) break; float t = mod(a, b); a = b; b = t; } return a; }","float mz_seed = 0.0;","float mz_random() { mz_seed += 1.0; return fract(sin(dot(vec3(gl_FragCoord.xy, mz_seed), vec3(12.9898, 78.233, 37.719))) * 43758.5453); }"].join("\n"),un=["px","py","rgb","gray","unchanged","selected","away"],pn=["blur","blurx","blury","gaussian","gaussianx","gaussiany","sobel","sobelx","sobely","laplacian","sharpen","emboss","dilate","erode","convolve"],hn=["zoom","shift","rotate","crop","tile","flipx","flipy"],fn=["srgb","linear","hsv","hsl","lab","oklab","ycbcr"],mn=fn.filter(e=>"srgb"!==e).flatMap(e=>[`to${e}`,`from${e}`]),gn=["pixel","red","green","blue","alpha","luma","source","selection","width","height",...pn,...hn,"fract","clamp","mix","smoothstep","step","distance","length","dot","normalize","cross","sign","exp2","log2","inversesqrt","radians","degrees",...mn],dn=["source","selection"],$n="away",yn="float mz_away(vec4 v) { return v.r > 0.0 ? 255.0 * (1.0 - v.r) : 1020.0 * (1.0 - v.g); }",bn=[...dn,$n];const wn=["cover","fit","stretch","tile"],xn=["red","green","blue","alpha","luma"];function vn(e,t,{whole:r=!1}={}){const n=_n(e,t);return r?"symbol"===n.type&&t.has(n.value)?{...n,value:`mz_px_${n.value}`}:"op"===n.type&&n.op.startsWith(`${bt}mz_at_`)?{...n,op:n.op.replace("mz_at_","mz_sample_")}:n:n}function _n(e,t){if("op"!==e.type)return e;const r=e.args.map(e=>_n(e,t)),n=e.op.startsWith(bt)?e.op.slice(2):null,o=r.length&&"symbol"===r[0].type&&t.has(r[0].value)?r[0].value:null;if(n&&t.has(n))return{...e,op:`${bt}mz_at_${n}`,args:r};if(n&&xn.includes(n)&&1===r.length&&o)return{...e,args:[{...r[0],value:`mz_px_${o}`}]};if(n&&xn.includes(n)&&1===r.length&&"op"===r[0].type&&r[0].op.startsWith(`${bt}mz_at_`))return{...e,args:[{...r[0],op:r[0].op.replace("mz_at_","mz_sample_")}]};if(n&&hn.includes(n)){const e={type:"op",op:`${bt}mz_${n}`,args:o?r.slice(1):r};return{type:"op",op:`${bt}mz_at_${o??"image"}`,args:[e]}}return("width"===n||"height"===n)&&r.length<=1?o&&"source"!==o?{type:"op",op:`${bt}mz_${n}_${o}`,args:[]}:{type:"symbol",value:"width"===n?"w":"h"}:{...e,args:r}}const An=[...un,...gn],En={square:8,line:24};function zn(e){const t=(e,t)=>`\n float mz_r = min(max(ceil(${e}), 0.0), ${En.square}.0);\n for (int i = 0; i <= ${2*En.square}; i++) {\n float fi = float(i) - mz_r;\n if (fi > mz_r) break;\n for (int j = 0; j <= ${2*En.square}; j++) {\n float fj = float(j) - mz_r;\n if (fj > mz_r) break;\n ${t}\n }\n }`,r=(e,t,r)=>`\n float mz_r = min(max(ceil(${t}), 0.0), ${En.line}.0);\n for (int i = 0; i <= ${2*En.line}; i++) {\n float fi = float(i) - mz_r;\n if (fi > mz_r) break;\n float dx = ${"x"===e?"fi":"0.0"}, dy = ${"y"===e?"fi":"0.0"};\n ${r}\n }`,n=e=>`vec3 blur${e}(float radius) {\n vec3 sum = vec3(0.0); float n = 0.0;${r(e,"radius","if (abs(fi) > radius) continue;\n sum += mz_tap(dx, dy).rgb; n += 1.0;")}\n return sum / n;\n}`,o=e=>`vec3 gaussian${e}(float sigma) {\n if (sigma <= 0.0) return mz_tap(0.0, 0.0).rgb;\n vec3 sum = vec3(0.0); float total = 0.0;${r(e,"3.0 * sigma","if (abs(fi) > 3.0 * sigma) continue;\n float w = mz_gauss(fi * fi, sigma);\n sum += w * mz_tap(dx, dy).rgb; total += w;")}\n return sum / total;\n}`;return`// ---- neighborhood: the pixels around this one (dy runs downwards, like py) ----\nvec4 mz_tap(float dx, float dy) { return ${e}(image, (gl_FragCoord.xy + vec2(dx, -dy)) / resolution); }\nfloat mz_luma_at(float dx, float dy) { return dot(mz_tap(dx, dy).rgb, vec3(0.299, 0.587, 0.114)); }\nfloat mz_gauss(float d2, float sigma) { return exp(-d2 / (2.0 * sigma * sigma)); }\nvec3 blur(float radius) {\n vec3 sum = vec3(0.0); float n = 0.0;${t("radius","if (abs(fi) > radius || abs(fj) > radius) continue;\n sum += mz_tap(fi, fj).rgb; n += 1.0;")}\n return sum / n;\n}\n${n("x")}\n${n("y")}\nvec3 gaussian(float sigma) {\n if (sigma <= 0.0) return mz_tap(0.0, 0.0).rgb;\n float limit = 3.0 * sigma;\n vec3 sum = vec3(0.0); float total = 0.0;${t("limit","if (abs(fi) > limit || abs(fj) > limit) continue;\n float w = mz_gauss(fi * fi + fj * fj, sigma);\n sum += w * mz_tap(fi, fj).rgb; total += w;")}\n return sum / total;\n}\n${o("x")}\n${o("y")}\nvec3 dilate(float radius) {\n vec3 best = vec3(0.0);${t("radius","if (abs(fi) > radius || abs(fj) > radius) continue;\n best = max(best, mz_tap(fi, fj).rgb);")}\n return best;\n}\nvec3 erode(float radius) {\n vec3 best = vec3(1.0);${t("radius","if (abs(fi) > radius || abs(fj) > radius) continue;\n best = min(best, mz_tap(fi, fj).rgb);")}\n return best;\n}\nfloat sobelx() {\n return (mz_luma_at(1.0, -1.0) + 2.0 * mz_luma_at(1.0, 0.0) + mz_luma_at(1.0, 1.0))\n - (mz_luma_at(-1.0, -1.0) + 2.0 * mz_luma_at(-1.0, 0.0) + mz_luma_at(-1.0, 1.0));\n}\nfloat sobely() {\n return (mz_luma_at(-1.0, 1.0) + 2.0 * mz_luma_at(0.0, 1.0) + mz_luma_at(1.0, 1.0))\n - (mz_luma_at(-1.0, -1.0) + 2.0 * mz_luma_at(0.0, -1.0) + mz_luma_at(1.0, -1.0));\n}\nfloat sobel() { return length(vec2(sobelx(), sobely())); }\nfloat laplacian() { return 4.0 * mz_luma_at(0.0, 0.0) - mz_luma_at(-1.0, 0.0) - mz_luma_at(1.0, 0.0) - mz_luma_at(0.0, -1.0) - mz_luma_at(0.0, 1.0); }\nfloat emboss() { return 0.5 + mz_luma_at(-1.0, -1.0) - mz_luma_at(1.0, 1.0); }\nvec3 sharpen(float amount) {\n vec3 c = mz_tap(0.0, 0.0).rgb;\n return c + amount * (4.0 * c - mz_tap(-1.0, 0.0).rgb - mz_tap(1.0, 0.0).rgb - mz_tap(0.0, -1.0).rgb - mz_tap(0.0, 1.0).rgb);\n}\nvec3 convolve(float k00, float k01, float k02, float k10, float k11, float k12, float k20, float k21, float k22) {\n return k00 * mz_tap(-1.0, -1.0).rgb + k01 * mz_tap(0.0, -1.0).rgb + k02 * mz_tap(1.0, -1.0).rgb\n + k10 * mz_tap(-1.0, 0.0).rgb + k11 * mz_tap(0.0, 0.0).rgb + k12 * mz_tap(1.0, 0.0).rgb\n + k20 * mz_tap(-1.0, 1.0).rgb + k21 * mz_tap(0.0, 1.0).rgb + k22 * mz_tap(1.0, 1.0).rgb;\n}`}function Mn(e,t={}){const r=300===t.version,n=t.parse;if(!n)throw new Error("filterShader needs options.parse (use the one from src/index.js)");const o=t.space&&"srgb"!==t.space?t.space:null;if(o&&!fn.includes(o))throw new Error(`Unknown color space "${o}": ${fn.join(", ")}`);const s=Array.isArray(t.images)?Object.fromEntries(t.images.map(e=>[e,{}])):{...t.images??{}},a=Object.keys(s),i=/^[A-Za-z_][A-Za-z0-9_]*$/;for(const e of a)if(!i.test(e))throw new Error(`A picture's name must be a GLSL identifier, not ${JSON.stringify(e)}`);for(const[e,r]of Object.entries(t.uniforms??{}))if(!i.test(e)||!/^(?:float|int|bool|[biu]?vec[234]|mat[234]|sampler2D)$/.test(String(r)))throw new Error(`Uniform ${JSON.stringify(e)}: a GLSL name and type, not ${JSON.stringify(r)}`);const l=new Set([...a,...dn]);let c=0;const u=(e,r=!1)=>{return Ur(vn((function e(t){const r="op"===t.type?t.op.replace(/^\\:/,""):t.value;if(pn.includes(r)&&++c>24)throw new Error("At most 24 neighborhood functions (blur, gaussian, sobel …) in a filter pass");"op"===t.type&&t.args.forEach(e)}(o=n(e)),o),l,{whole:r}),{version:t.version,filter:!0});var o},p="string"==typeof e?{rgba:e}:e,h=[];p.rgba&&h.push(" mz_keep(gray, color);",` color = mz_rgba(${u(p.rgba,!0)});`),p.rgb&&h.push(" mz_keep(gray, color);",` color.rgb = mz_rgb(${u(p.rgb)});`);for(const e of["r","g","b","a"])p[e]&&h.push(` mz_keep(color.${e}, color);`,` color.${e} = mz_ch_${e}(${u(p[e])});`);if(!h.length)throw new Error("filterShader: give an expression, or an object with r, g, b, a, rgb or rgba");const f=r?"texture":"texture2D",m=Object.entries(t.uniforms??{}).map(([e,t])=>`uniform ${t} ${e};`),g=new RegExp(`\\b(${pn.join("|")})\\(`).test(h.join("\n"));!a.includes("source")&&/\b(source|mz_at_source|mz_px_source|mz_sample_source)\b/.test(h.join("\n"))&&a.push("source"),!a.includes("selection")&&/\b(selected|selection|mz_at_selection|mz_px_selection|mz_sample_selection)\b/.test(h.join("\n"))&&a.push("selection"),!a.includes($n)&&/\baway\b/.test(h.join("\n"))&&a.push($n);const d=/\bmz_(zoom|shift|rotate|crop|tile|flipx|flipy|at_image|sample_image)\(/.test(h.join("\n")),$=o||new RegExp(`\\b(${mn.join("|")})\\(`).test(h.join("\n")),y=e=>[`float mz_ch_${e}(float v) { return v; }`,`float mz_ch_${e}(bool v) { return v ? 1.0 : 0.0; }`,`float mz_ch_${e}(vec3 v) { return ${"a"===e?"1.0":`v.${e}`}; }`,`float mz_ch_${e}(vec4 v) { return v.${e}; }`];return[r?"#version 300 es":"","precision highp float;","uniform sampler2D image; // the frame","uniform vec2 resolution; // width, height in pixels","uniform float t; // frame index",t.blend?"uniform float mz_opacity; // how much of the result shows over the input, 0–1":"",...m,...a.map(e=>`uniform sampler2D mz_img_${e};`),...a.filter(e=>!bn.includes(e)).flatMap(e=>[`uniform vec2 mz_size_${e}; // its own width and height`,`uniform vec4 mz_place_${e}; // zoom, x, y, angle`]),r?"out vec4 fragColor;":"",cn,`vec4 pixel(float px, float py) { return ${f}(image, vec2((px + 0.5) / resolution.x, 1.0 - (py + 0.5) / resolution.y)); }`,"float red(float px, float py) { return pixel(px, py).r; }","float green(float px, float py) { return pixel(px, py).g; }","float blue(float px, float py) { return pixel(px, py).b; }","float alpha(float px, float py) { return pixel(px, py).a; }","float luma(float px, float py) { return dot(pixel(px, py).rgb, vec3(0.299, 0.587, 0.114)); }","float red(vec4 v) { return v.r; }","float red(vec3 v) { return v.r; }","float green(vec4 v) { return v.g; }","float green(vec3 v) { return v.g; }","float blue(vec4 v) { return v.b; }","float blue(vec3 v) { return v.b; }","float alpha(vec4 v) { return v.a; }","float alpha(vec3 v) { return 1.0; }","float luma(vec4 v) { return dot(v.rgb, vec3(0.299, 0.587, 0.114)); }","float luma(vec3 v) { return dot(v, vec3(0.299, 0.587, 0.114)); }","vec2 mz_p() { return vec2(gl_FragCoord.x - 0.5, resolution.y - gl_FragCoord.y - 0.5); } // (px, py)",...$?["// ---- color spaces: to<space>(c) and from<space>(c), sRGB on the other side ----","vec3 tolinear(vec3 c) { return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c)); }","vec3 fromlinear(vec3 c) { c = max(c, 0.0); return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c)); }","float mz_hue(vec3 c, float v, float d) { float h = v == c.r ? (c.g - c.b) / d : v == c.g ? 2.0 + (c.b - c.r) / d : 4.0 + (c.r - c.g) / d; return fract(h / 6.0); }","vec3 tohsv(vec3 c) { float v = max(c.r, max(c.g, c.b)); float d = v - min(c.r, min(c.g, c.b)); return vec3(d > 0.0 ? mz_hue(c, v, d) : 0.0, v > 0.0 ? d / v : 0.0, v); }","vec3 fromhsv(vec3 c) { vec3 k = abs(fract(c.x + vec3(0.0, 2.0 / 3.0, 1.0 / 3.0)) * 6.0 - 3.0); return c.z * mix(vec3(1.0), clamp(k - 1.0, 0.0, 1.0), c.y); }","vec3 tohsl(vec3 c) { float v = max(c.r, max(c.g, c.b)); float m = min(c.r, min(c.g, c.b)); float d = v - m; float l = (v + m) * 0.5; return vec3(d > 0.0 ? mz_hue(c, v, d) : 0.0, d > 0.0 ? d / (1.0 - abs(2.0 * l - 1.0)) : 0.0, l); }","vec3 fromhsl(vec3 c) { float C = (1.0 - abs(2.0 * c.z - 1.0)) * c.y; vec3 k = abs(fract(c.x + vec3(0.0, 2.0 / 3.0, 1.0 / 3.0)) * 6.0 - 3.0); return (c.z - C * 0.5) + C * clamp(k - 1.0, 0.0, 1.0); }","vec3 toycbcr(vec3 c) { float y = dot(c, vec3(0.299, 0.587, 0.114)); return vec3(y, 0.5 + (c.b - y) * 0.5643, 0.5 + (c.r - y) * 0.7132); }","vec3 fromycbcr(vec3 c) { float cb = c.y - 0.5; float cr = c.z - 0.5; return vec3(c.x + 1.402 * cr, c.x - 0.344136 * cb - 0.714136 * cr, c.x + 1.772 * cb); }","vec3 tolab(vec3 c) {"," vec3 l = tolinear(c);"," vec3 xyz = vec3(dot(l, vec3(0.4124564, 0.3575761, 0.1804375)), dot(l, vec3(0.2126729, 0.7151522, 0.0721750)), dot(l, vec3(0.0193339, 0.1191920, 0.9503041))) / vec3(0.95047, 1.0, 1.08883);"," vec3 f = mix(7.787 * xyz + 16.0 / 116.0, mz_cbrt(xyz), step(0.008856, xyz));"," return vec3((116.0 * f.y - 16.0) / 100.0, 0.5 + 500.0 * (f.x - f.y) / 256.0, 0.5 + 200.0 * (f.y - f.z) / 256.0);","}","vec3 fromlab(vec3 c) {"," float fy = (c.x * 100.0 + 16.0) / 116.0;"," vec3 f = vec3(fy + (c.y - 0.5) * 256.0 / 500.0, fy, fy - (c.z - 0.5) * 256.0 / 200.0);"," vec3 xyz = mix((f - 16.0 / 116.0) / 7.787, f * f * f, step(0.206893, f)) * vec3(0.95047, 1.0, 1.08883);"," vec3 l = vec3(dot(xyz, vec3(3.2404542, -1.5371385, -0.4985314)), dot(xyz, vec3(-0.9692660, 1.8760108, 0.0415560)), dot(xyz, vec3(0.0556434, -0.2040259, 1.0572252)));"," return fromlinear(clamp(l, 0.0, 1.0));","}","vec3 tooklab(vec3 c) {"," vec3 l = tolinear(c);"," vec3 lms = mz_cbrt(vec3(dot(l, vec3(0.4122214708, 0.5363325363, 0.0514459929)), dot(l, vec3(0.2119034982, 0.6806995451, 0.1073969566)), dot(l, vec3(0.0883024619, 0.2817188376, 0.6299787005))));"," return vec3(dot(lms, vec3(0.2104542553, 0.7936177850, -0.0040720468)), 0.5 + dot(lms, vec3(1.9779984951, -2.4285922050, 0.4505937099)), 0.5 + dot(lms, vec3(0.0259040371, 0.7827717662, -0.8086757660)));","}","vec3 fromoklab(vec3 c) {"," float A = c.y - 0.5; float B = c.z - 0.5;"," vec3 lms = vec3(c.x + 0.3963377774 * A + 0.2158037573 * B, c.x - 0.1055613458 * A - 0.0638541728 * B, c.x - 0.0894841775 * A - 1.2914855480 * B);"," lms = lms * lms * lms;"," vec3 l = vec3(dot(lms, vec3(4.0767416621, -3.3077115913, 0.2309699292)), dot(lms, vec3(-1.2684380046, 2.6097574011, -0.3413193965)), dot(lms, vec3(-0.0041960863, -0.7034186147, 1.7076147010)));"," return fromlinear(clamp(l, 0.0, 1.0));","}",...mn.map(e=>`vec3 ${e}(float x, float y, float z) { return ${e}(vec3(x, y, z)); }`)]:[],...a.flatMap(e=>function(e,t,r,n=null){const o=n&&"selection"!==e&&e!==$n,s=o?[`vec4 mz_sample_${e}(vec2 p) { vec4 v = mz_raw_${e}(p); v.rgb = to${n}(v.rgb); return v; }`]:[],a=o?`mz_raw_${e}`:`mz_sample_${e}`;if(bn.includes(e))return[`vec4 ${a}(vec2 p) { vec2 q = p + 0.5; return ${r}(mz_img_${e}, vec2(q.x / resolution.x, 1.0 - q.y / resolution.y)); }`,...s,`vec3 mz_at_${e}(vec2 p) { return mz_sample_${e}(p).rgb; }`,`vec3 mz_at_${e}(float px, float py) { return mz_at_${e}(vec2(px, py)); }`];return[`vec4 ${a}(vec2 p) {`,` vec2 size = mz_size_${e};`,` vec2 scale = ${{cover:"vec2(max(resolution.x / size.x, resolution.y / size.y))",fit:"vec2(min(resolution.x / size.x, resolution.y / size.y))",stretch:"resolution / size",tile:"vec2(1.0)"}[t??"cover"]} * mz_place_${e}.x;`,` vec2 d = p + 0.5 - mz_place_${e}.yz * resolution;`,` float co = cos(mz_place_${e}.w), si = sin(mz_place_${e}.w);`," d = vec2(co * d.x + si * d.y, co * d.y - si * d.x);"," vec2 q = d / scale + size * 0.5;"," "+("tile"===t?"q = mod(q, size);":"if (q.x < 0.0 || q.y < 0.0 || q.x > size.x || q.y > size.y) return vec4(0.0);"),` return ${r}(mz_img_${e}, vec2(q.x / size.x, 1.0 - q.y / size.y));`,"}",...s,`vec3 mz_at_${e}(vec2 p) { return mz_sample_${e}(p).rgb; }`,`vec3 mz_at_${e}(float px, float py) { return mz_at_${e}(vec2(px, py)); }`,`float mz_width_${e}() { return mz_size_${e}.x; }`,`float mz_height_${e}() { return mz_size_${e}.y; }`]}(e,s[e]?.place,f,o)),a.includes($n)?yn:"",...d?kn(f):[],g?zn(f):"",...y("r"),...y("g"),...y("b"),...y("a"),"vec3 mz_rgb(float v) { return vec3(v); }","vec3 mz_rgb(bool v) { return vec3(v ? 1.0 : 0.0); }","vec3 mz_rgb(vec3 v) { return v; }","vec3 mz_rgb(vec4 v) { return v.rgb; }","vec4 mz_rgba(float v) { return vec4(vec3(v), 1.0); }","vec4 mz_rgba(bool v) { return vec4(vec3(v ? 1.0 : 0.0), 1.0); }","vec4 mz_rgba(vec3 v) { return vec4(v, 1.0); }","vec4 mz_rgba(vec4 v) { return v; }","float unchanged = 0.0;","vec3 mz_unchanged_3 = vec3(0.0);","vec4 mz_unchanged_4 = vec4(0.0);","void mz_keep(float value, vec4 all) { unchanged = value; mz_unchanged_3 = all.rgb; mz_unchanged_4 = all; }","float mz_unchanged(float like) { return unchanged; }","bool mz_unchanged(bool like) { return unchanged > 0.5; }","vec3 mz_unchanged(vec3 like) { return mz_unchanged_3; }","vec4 mz_unchanged(vec4 like) { return mz_unchanged_4; }","void main() {"," float w = resolution.x;"," float h = resolution.y;"," float px = gl_FragCoord.x - 0.5;"," float py = h - gl_FragCoord.y - 0.5;"," float x = gl_FragCoord.x / w;"," float y = 1.0 - gl_FragCoord.y / h;",` vec4 c = ${f}(image, gl_FragCoord.xy / resolution);`," float r = c.r, g = c.g, b = c.b, a = c.a;"," vec3 rgb = c.rgb;",` float gray = dot(${o?`from${o}(rgb)`:"rgb"}, vec3(0.299, 0.587, 0.114)); // the brightness as seen`," vec4 color = c;"," mz_seed = t;",...a.flatMap(e=>[` vec4 mz_px_${e} = mz_sample_${e}(mz_p());`,e===$n?"":` vec3 ${e} = mz_px_${e}.rgb;`]),a.includes("selection")?" float selected = mz_px_selection.r; // 1 inside the selection, 0 outside; 1 everywhere without one":"",a.includes($n)?" float away = mz_away(mz_px_away); // pixels from the selection; 0 inside it, and everywhere without one":"",...h,t.blend?" color = mix(c, color, mz_opacity);":"",` ${r?"fragColor":"gl_FragColor"} = color;`,"}"].filter(e=>""!==e).join("\n")}function kn(e){return["// ---- geometry: where to read the picture from, for this pixel ----","vec2 mz_zoom(float s, float cx, float cy) { vec2 c = vec2(cx, cy) * resolution - 0.5; return c + (mz_p() - c) / s; }","vec2 mz_zoom(float s) { return mz_zoom(s, 0.5, 0.5); }","vec2 mz_shift(float dx, float dy) { return mod(mz_p() - vec2(dx, dy) + 0.5, resolution) - 0.5; } // wraps around","vec2 mz_rotate(float a, float cx, float cy) { vec2 c = vec2(cx, cy) * resolution - 0.5; vec2 d = mz_p() - c; float co = cos(a), si = sin(a); return c + vec2(co * d.x + si * d.y, co * d.y - si * d.x); }","vec2 mz_rotate(float a) { return mz_rotate(a, 0.5, 0.5); }","vec2 mz_crop(float x0, float y0, float x1, float y1) { vec2 f = (mz_p() + 0.5) / resolution; return (vec2(x0, y0) + vec2(x1 - x0, y1 - y0) * f) * resolution - 0.5; }","vec2 mz_tile(float nx, float ny) { return mod((mz_p() + 0.5) * vec2(nx, ny), resolution) - 0.5; }","vec2 mz_tile(float n) { return mz_tile(n, n); }","vec2 mz_flipx() { vec2 p = mz_p(); return vec2(resolution.x - 1.0 - p.x, p.y); }","vec2 mz_flipy() { vec2 p = mz_p(); return vec2(p.x, resolution.y - 1.0 - p.y); }",`vec4 mz_sample_image(vec2 p) { vec2 q = p + 0.5; if (q.x < 0.0 || q.y < 0.0 || q.x > resolution.x || q.y > resolution.y) return vec4(0.0); return ${e}(image, vec2(q.x / resolution.x, 1.0 - q.y / resolution.y)); }`,"vec3 mz_at_image(vec2 p) { return mz_sample_image(p).rgb; }"]}for(const e of[Dr,Gr,Hr,Xr,Vr,Yr,an,En,ln])Object.setPrototypeOf(e,null);const On=["round","soft","marker","chalk","spray"],jn=["recorded","even","per-stroke"],Sn=["pressure","speed","none"],Nn=["none","inside","outside"],In={type:"strokes",strokes:[],brush:"round",size:.03,flow:1,spacing:.2,taper:0,buildUp:!1,widthFrom:"pressure",timing:"recorded",speed:1,gap:6,start:0,fit:0,age:30,clip:"none",shadows:[]};function Tn(e,t){throw new Error(`Graphic "${e}": ${t}`)}function Rn(e,t,r,n,o){const s=Number(r);return(!Number.isFinite(s)||s<n||s>o)&&Tn(e,`"${t}" is a number from ${n} to ${o}`),s}function Fn(e,t){let r=Math.imul(0|e,374761393)+Math.imul(0|t,668265263)|0;return r=Math.imul(r^r>>>13,1274126177),((r^r>>>16)>>>0)/4294967296}const Cn=new Map;function qn(e,t,r,n=1/0,{mask:o=null}={}){const s=t*r,{alpha:a,passes:i,latest:l,cov:c,when:u,touched:p}=function(e){let t=Cn.get(e);return t||(t={alpha:new Float32Array(e),passes:new Float32Array(e),latest:new Float32Array(e),cov:new Float32Array(e),when:new Float32Array(e),touched:new Int32Array(e)},Cn.clear(),Cn.set(e,t)),t.alpha.fill(0),t.passes.fill(0),t.latest.fill(-1),t}(s),{strokes:h,total:f}=function(e,t=1){const r=[];let n=e.start;const o=30/e.speed,s=20/e.speed;for(const a of e.strokes){const i=a.points;if(!i.length)continue;const l=[0];for(let e=1;e<i.length;e++)l.push(l[e-1]+Math.hypot((i[e][0]-i[e-1][0])*t,i[e][1]-i[e-1][1]));const c=l[l.length-1]||1e-9,u=i[0][2],p=i.map((t,r)=>{let n;n="recorded"===e.timing?(t[2]-u)/1e3*30/e.speed:"even"===e.timing?l[r]*o:l[r]/c*s;let a=1;if("pressure"===e.widthFrom)a=.3+.7*t[3];else if("speed"===e.widthFrom&&r>0){const e=Math.max(1,t[2]-i[r-1][2]),n=(l[r]-l[r-1])/e*1e3;a=Math.min(1.3,Math.max(.35,1.3-.6*n))}return e.taper>0&&(a*=Math.max(.15,Math.min(1,l[r]/c/e.taper,(1-l[r]/c)/e.taper))),{x:t[0],y:t[1],f:n,wf:a}});"speed"===e.widthFrom&&p.length>1&&(p[0].wf=p[1].wf);const h=p[p.length-1].f;for(const e of p)e.f+=n;r.push({points:p,start:n,end:n+h}),n+=h+e.gap}let a=r.length?r[r.length-1].end:e.start;if(e.fit>0&&a>e.start){const t=e.fit/(a-e.start);for(const n of r){for(const r of n.points)r.f=e.start+(r.f-e.start)*t;n.start=e.start+(n.start-e.start)*t,n.end=e.start+(n.end-e.start)*t}a=e.start+e.fit}return{strokes:r,total:a}}(e,t/r),m=Number.isFinite(n)?n:f,g=Math.max(.5,e.size*r/2);let d=0,$=256*Math.max(s,65536);h.forEach(n=>{if(n.start>m||$<=0)return;let o=0;const s=(t,r,n,o)=>{const s=d++;if("spray"===e.brush){const e=Math.max(3,Math.round(.6*n)),a=Math.max(.6,.07*n);for(let i=0;i<e;i++){const e=Fn(s,2*i)*Math.PI*2,l=Math.sqrt(Fn(s,2*i+1))*n;h(t+Math.cos(e)*l,r+Math.sin(e)*l,a,o,"round")}}else h(t,r,n,o,e.brush)},h=(n,s,a,i,l)=>{const h="marker"===l?a:a+1,f=Math.max(0,Math.floor(n-h)),m=Math.min(t-1,Math.ceil(n+h)),g=Math.max(0,Math.floor(s-h)),d=Math.min(r-1,Math.ceil(s+h));$-=m>=f&&d>=g?(m-f+1)*(d-g+1):16;for(let r=g;r<=d;r++)for(let h=f;h<=m;h++){const f=h+.5-n,m=r+.5-s;let g;if("soft"===l){const e=Math.hypot(f,m)/a;if(e>=1)continue;const t=1-e;g=t*t*(3-2*t)}else if("marker"===l){const e=(f+m)*Math.SQRT1_2,t=(m-f)*Math.SQRT1_2,r=Math.hypot(e/a,t/(.33*a));g=Math.min(1,Math.max(0,(1-r)*a*.33+.5))}else g=Math.min(1,Math.max(0,a-Math.hypot(f,m)+.5)),"chalk"===l&&(g*=Fn(h,7919*r)>.42?1:.12);if(g<=0)continue;g*=e.flow;const d=r*t+h;g>c[d]&&(0===c[d]&&(p[o++]=d),c[d]=g),g>.02&&(u[d]=i)}},f=n.points;let y=0;const b=e=>[e.x*t,e.y*r];if(1===f.length||f.every(e=>e.x===f[0].x&&e.y===f[0].y)){const[e,t]=b(f[0]);s(e,t,g*f[0].wf,f[0].f)}for(let t=1;t<f.length;t++){const r=f[t-1],n=f[t];if(r.f>m)break;const[o,a]=b(r),[i,l]=b(n);let c=1;n.f>m&&(c=(m-r.f)/Math.max(1e-9,n.f-r.f));const u=Math.hypot(i-o,l-a);let p=1===t?0:y;for(;p<=u*c&&$>0;){const t=u?p/u:0,c=g*(r.wf+(n.wf-r.wf)*t);s(o+(i-o)*t,a+(l-a)*t,c,r.f+(n.f-r.f)*t),p+=Math.max(.5,2*e.spacing*c)}if(y=p-u,c<1||$<=0)break}for(let t=0;t<o;t++){const r=p[t],n=c[r];a[r]=e.buildUp?1-(1-a[r])*(1-n):Math.max(a[r],n),i[r]+=n,n>.02&&u[r]>l[r]&&(l[r]=u[r]),c[r]=0}});const y=new Uint8ClampedArray(4*s),b="inside"===e.clip,w="outside"===e.clip;for(let t=0;t<s;t++){let r=a[t];if(0===r)continue;let n=1;o&&(b||w)&&(n=b?o[t]:1-o[t]),r*=n;const s=4*t;y[s]=Math.round(255*Math.min(1,Math.max(0,(m-l[t])/e.age))),y[s+1]=Math.round(255*Math.min(1,i[t]*n/4)),y[s+2]=Math.round(255*Math.min(1,Math.max(0,l[t]/Math.max(1e-9,f)))),y[s+3]=Math.round(255*r)}return{data:y,width:t,height:r,total:f}}const Ln=["text","rect","ellipse","strokes"],Pn={text:{type:"text",text:"Text",font:"sans-serif",weight:"bold",style:"normal",size:.08,x:.5,y:.85,align:"center",angle:0,lineHeight:1.2,color:"#ffffff",outline:null,shadow:{color:"rgba(0,0,0,0.6)",blur:.15,dx:.04,dy:.06},shadows:[]},rect:{type:"rect",x:.5,y:.85,w:.8,h:.18,radius:.15,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]},ellipse:{type:"ellipse",x:.5,y:.5,w:.4,h:.4,angle:0,color:"#ffffff",outline:null,shadow:null,shadows:[]}},Un=(e,t)=>(t.shadows??[]).map((t,r)=>`${e}_shadow${r+1}`),Bn=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([\d.,\s%deg/]+\)|[a-z]{3,20}|transparent)$/i,Dn=/^[\w\s,'"-]{1,80}$/,Zn=["normal","bold","100","200","300","400","500","600","700","800","900"];function Gn(e,t,r){if("string"!=typeof r||!Bn.test(r.trim()))throw new Error(`Graphic "${e}": "${t}" is a color like "#ffcc00", "rgba(0,0,0,0.5)" or "white"`);return r.trim()}function Wn(e,t,r,n=-1/0,o=1/0){const s=Number(r);if(!Number.isFinite(s)||s<n||s>o)throw new Error(`Graphic "${e}": "${t}" is a number${Number.isFinite(n)?` from ${n} to ${o}`:""}`);return s}function Hn(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "outline" is { "color", "width" } or null`);return{color:Gn(e,"outline.color",t.color??"#000000"),width:Wn(e,"outline.width",t.width??.06,0,1)}}function Xn(e,t){if(null===t||!1===t)return null;if("object"!=typeof t)throw new Error(`Graphic "${e}": "shadow" is { "color", "blur", "dx", "dy" } or null`);return{color:Gn(e,"shadow.color",t.color??"rgba(0,0,0,0.6)"),blur:Wn(e,"shadow.blur",t.blur??.15,0,2),dx:Wn(e,"shadow.dx",t.dx??0,-2,2),dy:Wn(e,"shadow.dy",t.dy??0,-2,2)}}function Vn(e,t){if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Graphic "${e}": give { "type": "text" | "rect" | "ellipse", … }`);const r=t.type??"text";if(!Ln.includes(r))throw new Error(`Graphic "${e}": "type" is text, rect, ellipse or strokes — not "${r}"`);if("strokes"===r)return function(e,t){for(const r of Object.keys(t))r in In||Tn(e,`no such setting "${r}" for strokes`);const r={...In,...t},n=(t,n)=>(n.includes(r[t])||Tn(e,`"${t}" is ${n.join(", ")} — not "${r[t]}"`),r[t]),o={type:"strokes",brush:n("brush",On),widthFrom:n("widthFrom",Sn),timing:n("timing",jn),clip:n("clip",Nn),size:Rn(e,"size",r.size,.001,.5),flow:Rn(e,"flow",r.flow,.01,1),spacing:Rn(e,"spacing",r.spacing,.02,2),taper:Rn(e,"taper",r.taper,0,.5),speed:Rn(e,"speed",r.speed,.05,20),gap:Rn(e,"gap",r.gap,0,600),start:Rn(e,"start",r.start,0,1e4),fit:Rn(e,"fit",r.fit,0,1e4),age:Rn(e,"age",r.age,1,1e4),buildUp:Boolean(r.buildUp),shadows:[]};Array.isArray(r.strokes)||Tn(e,'"strokes" is a list of { "points": [[x, y, ms, pressure], …] }');let s=0;return o.strokes=r.strokes.map((t,r)=>{const n=Array.isArray(t)?t:t?.points;return Array.isArray(n)||Tn(e,`stroke ${r+1} is { "points": [[x, y, ms, pressure], …] }`),s+=n.length,s>6e4&&Tn(e,"a drawing has at most 60000 points"),{points:n.map((t,n)=>((!Array.isArray(t)||t.length<2||!t.every(e=>Number.isFinite(Number(e))))&&Tn(e,`stroke ${r+1}, point ${n+1} is [x, y, ms, pressure]`),[+Number(t[0]).toFixed(4),+Number(t[1]).toFixed(4),Math.round(Number(t[2]??16*n)),+Math.min(1,Math.max(0,Number(t[3]??1))).toFixed(2)]))}}),o}(e,t);const n=Pn[r];for(const o of Object.keys(t))if(!(o in n)&&"fontUrl"!==o&&"onlyShadow"!==o)throw new Error(`Graphic "${e}": no such setting "${o}" for ${r}`);const o={type:r};for(const[r,s]of Object.entries(n)){if("type"===r)continue;const n=r in t&&void 0!==t[r]?t[r]:s;if("color"===r)o.color=Gn(e,r,n);else if("outline"===r)o.outline=Hn(e,n);else if("shadow"===r)o.shadow=Xn(e,n);else if("shadows"===r){if(!Array.isArray(n)||n.length>8)throw new Error(`Graphic "${e}": "shadows" is a list of up to 8 { "color", "blur", "dx", "dy" }`);o.shadows=n.map((t,r)=>{if(!t||"object"!=typeof t)throw new Error(`Graphic "${e}": shadow layer ${r+1} is { "color", "blur", "dx", "dy" }`);return Xn(e,t)})}else if("text"===r){if("string"!=typeof n||n.length>500)throw new Error(`Graphic "${e}": "text" is up to 500 characters`);o.text=n}else if("font"===r){if("string"!=typeof n||!Dn.test(n))throw new Error(`Graphic "${e}": "font" is a font family, like "Georgia" or "sans-serif"`);o.font=n}else if("weight"===r){if(!Zn.includes(String(n)))throw new Error(`Graphic "${e}": "weight" is normal, bold or 100–900`);o.weight=String(n)}else if("style"===r){if(!["normal","italic"].includes(n))throw new Error(`Graphic "${e}": "style" is normal or italic`);o.style=n}else if("align"===r){if(!["left","center","right"].includes(n))throw new Error(`Graphic "${e}": "align" is left, center or right`);o.align=n}else"size"===r?o.size=Wn(e,r,n,.005,2):"w"===r||"h"===r?o[r]=Wn(e,r,n,0,4):"radius"===r?o.radius=Wn(e,r,n,0,.5):"lineHeight"===r?o.lineHeight=Wn(e,r,n,.5,4):o[r]=Wn(e,r,n)}if(void 0!==t.fontUrl&&null!==t.fontUrl&&""!==t.fontUrl){if("text"!==r)throw new Error(`Graphic "${e}": "fontUrl" is for text`);let n;try{n=new URL(t.fontUrl)}catch{n=null}if(!n||"https:"!==n.protocol)throw new Error(`Graphic "${e}": "fontUrl" is an https:// address of a font file (.woff2, .woff, .ttf, .otf) or of a Google Fonts stylesheet`);o.fontUrl=n.href}return void 0!==t.onlyShadow&&(o.onlyShadow=Wn(e,"onlyShadow",t.onlyShadow,0,7)),o}function Yn(e,t){const r=e.fontUrl?`"${Jn(e.fontUrl)}", ${e.font}`:e.font;return`${e.style} ${e.weight} ${Math.max(1,e.size*t)}px ${r}`}function Jn(e){let t=0;for(const r of e)t=31*t+r.charCodeAt(0)>>>0;return`mz-font-${t.toString(36)}`}const Kn=new Map;async function Qn(e,t){try{let r=e.fontUrl;if(!/\.(woff2?|ttf|otf)(\?|$)/i.test(new URL(r).pathname)||function(e){try{const t=new URL(e);return"fonts.googleapis.com"!==t.hostname?null:(t.searchParams.get("family")??"").split(":")[0].replace(/\+/g," ")||null}catch{return null}}(r)){if(r=function(e,{weight:t="400",style:r="normal"}={}){const n=[...e.matchAll(/@font-face\s*{([^}]*)}/g)].map(e=>e[1]),o=(e,t)=>(new RegExp(`${t}\\s*:\\s*([^;]+);`).exec(e)?.[1]??"").trim(),s=String("bold"===t?700:"normal"===t?400:t),a=n.filter(e=>o(e,"font-weight")===s&&o(e,"font-style")===r),i=(a.length?a:n).at(-1);return i&&(/url\(([^)]+)\)/.exec(i)?.[1]??"").replace(/^['"]|['"]$/g,"")||null}(await(await fetch(r,{credentials:"omit",referrerPolicy:"no-referrer"})).text(),e),!r||!r.startsWith("https://"))return null}const n=new FontFace(Jn(e.fontUrl),`url(${JSON.stringify(r)})`,{weight:e.weight,style:e.style});return t.add(await n.load()),n}catch{return null}}function eo(e,t,r,n){e.save();const o="text"===t.type?t.size*n:n,s=void 0!==t.onlyShadow?t.shadows[t.onlyShadow]:null,a=s?2*(r+n)+1e3:0,i=s??t.shadow;if(e.translate(t.x*r-a,t.y*n),t.angle&&e.rotate(t.angle),i&&(e.shadowColor=i.color,e.shadowBlur=i.blur*o,e.shadowOffsetX=i.dx*o+a,e.shadowOffsetY=i.dy*o),e.fillStyle=s?"#000000":t.color,t.outline&&(e.strokeStyle=t.outline.color,e.lineWidth=t.outline.width*o,e.lineJoin="round"),"text"===t.type){e.font=Yn(t,n),e.textAlign=t.align,e.textBaseline="middle";const r=t.text.split("\n"),o=t.size*n*t.lineHeight;r.forEach((n,a)=>{const l=(a-(r.length-1)/2)*o;t.outline&&e.strokeText(n,0,l),t.outline&&i&&!s&&(e.shadowColor="transparent"),e.fillText(n,0,l),t.outline&&i&&!s&&(e.shadowColor=i.color)})}else{const o=t.w*r,a=t.h*n;if(e.beginPath(),"ellipse"===t.type)e.ellipse(0,0,o/2,a/2,0,0,2*Math.PI);else{const r=Math.min(o,a)*t.radius;e.roundRect?e.roundRect(-o/2,-a/2,o,a,r):e.rect(-o/2,-a/2,o,a)}e.fill(),t.outline&&(s||(e.shadowColor="transparent"),e.stroke())}e.restore()}async function to(e,t,r,{t:n=1/0,mask:o=null}={}){const s=e.graphics??{},a=await async function(e,t=100){if("undefined"==typeof document&&"undefined"==typeof self)return[];const r="undefined"!=typeof document?document.fonts:self.fonts;if(!r)return[];const n=[];for(const o of Object.values(e??{}))if("text"===o.type){if(o.fontUrl&&"undefined"!=typeof FontFace){const e=`${o.fontUrl} ${o.weight} ${o.style}`;Kn.has(e)||Kn.set(e,Qn(o,r)),await Kn.get(e)||n.push(o.fontUrl)}try{await r.load(Yn(o,t),o.text)}catch{}}return[...new Set(n)]}(s,r),i={};for(const[e,a]of Object.entries(s)){if("strokes"===a.type){const s=qn(a,t,r,n,{mask:o});i[e]="undefined"!=typeof ImageData?new ImageData(s.data,t,r):s;continue}const s="undefined"!=typeof OffscreenCanvas&&"undefined"==typeof document?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r});eo(s.getContext("2d"),a,t,r),i[e]=s}return Object.defineProperty(i,"failedFonts",{value:a}),i}const ro="mathzetta-filter/1",no=["r","g","b","a","rgb","rgba"],oo=/^[A-Za-z][A-Za-z0-9_]*$/,so=new Set([...An,"r","g","b","a","x","y","w","h","t","c","e","pi","color","image","resolution","base","position","main","in","out","inout","const","uniform","varying","attribute","void","float","int","bool","vec2","vec3","vec4","mat2","mat3","mat4","sampler2D","struct","precision","highp","mediump","lowp","if","else","for","while","do","return","break","continue","discard","true","false","texture2D","texture","mix","clamp","step","smoothstep","abs","sign","floor","ceil","fract","mod","min","max","sin","cos","tan","asin","acos","atan","pow","exp","log","exp2","log2","sqrt","inversesqrt","length","distance","dot","cross","normalize","radians","degrees"]),ao=e=>Array.isArray(e)&&3===e.length&&e.every(e=>Number.isFinite(Number(e))),io=e=>e&&"object"==typeof e&&!Array.isArray(e),lo={place:"cover",zoom:1,x:.5,y:.5,angle:0};function co(e){if("string"==typeof e){if(!e.trim())throw new Error("The filter is empty");return{format:ro,color:e.trim()}}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A filter is an expression, or an object with "color" or "steps"');if(void 0!==e.format&&e.format!==ro)throw new Error(`Unknown filter format "${e.format}" (this is ${ro})`);const t={format:ro};for(const r of["name","author","description"])void 0!==e[r]&&""!==e[r]&&(t[r]=String(e[r]));if(void 0!==e.steps){if(void 0!==e.color)throw new Error('A filter has either "color" or "steps", not both');if(!Array.isArray(e.steps)||!e.steps.length)throw new Error('"steps" must be a list with at least one step');return t.steps=e.steps.map(fo),void 0!==e.notes&&(t.notes=uo(e.notes,$o(t))),t}if(void 0===e.color)throw new Error('A filter needs "color" (an expression, or one per channel) or "steps"');const r=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"params" is an object of name → { default, min, max }');const t={};for(const[r,n]of Object.entries(e)){if(!oo.test(r))throw new Error(`Parameter name "${r}" must be letters, digits and _, starting with a letter`);if(so.has(r))throw new Error(`"${r}" is already defined in every filter; pick another parameter name`);t[r]=mo(r,n)}return t}(e.params??{});Object.keys(r).length&&(t.params=r),void 0!==e.notes&&(t.notes=uo(e.notes,r));const n=function(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,{}])):e;if(!r||"object"!=typeof r)throw new Error('"images" is a list of names, or an object of name → { description }');const n={};for(const[e,o]of Object.entries(r)){if(!oo.test(e)||e.startsWith("mz_"))throw new Error(`Image name "${e}" must be letters, digits and _, starting with a letter`);if("source"===e)throw new Error('"source" is always available: the picture the chain started from');if(so.has(e))throw new Error(`"${e}" is already defined in every filter; pick another image name`);if(Object.hasOwn(t,e))throw new Error(`"${e}" is both a parameter and an image`);n[e]=ho(e,o)}return n}(e.images??{},r);Object.keys(n).length&&(t.images=n);const o=function(e,t,r){if(!io(e))throw new Error('"graphics" is an object of name → { "type": "text" | "rect" | "ellipse", … }');if(Object.keys(e).length>64)throw new Error("A filter has at most 64 graphics");const n={};for(const[o,s]of Object.entries(e)){if(!oo.test(o)||o.startsWith("mz_"))throw new Error(`Graphic name "${o}" must be letters, digits and _, starting with a letter`);if(so.has(o)||"source"===o||"selection"===o)throw new Error(`"${o}" is already defined in every filter; pick another graphic name`);if(Object.hasOwn(t,o)||Object.hasOwn(r,o))throw new Error(`"${o}" is both a graphic and a parameter or picture`);n[o]=Vn(o,s)}const o=new Set(Object.keys(n).flatMap(e=>Array.from({length:8},(t,r)=>`${e}_shadow${r+1}`)));for(const e of[...Object.keys(n),...Object.keys(t),...Object.keys(r)])if(o.has(e))throw new Error(`"${e}" is the name of a shadow layer of another graphic; pick another name`);return n}(e.graphics??{},r,n);Object.keys(o).length&&(t.graphics=o);const s=function(e){if(null==e)return null;const t="string"==typeof e?{in:e,out:e}:e;if(!io(t))throw new Error(`"space" is a color space (${fn.join(", ")}) or { "in": …, "out": … }`);const r={in:t.in??"srgb",out:t.out??"srgb"};for(const e of["in","out"])if(!fn.includes(r[e]))throw new Error(`"space": "${r[e]}" is not a color space; they are ${fn.join(", ")}`);return"srgb"===r.in&&"srgb"===r.out?null:r}(e.space);return s&&(t.space=s),t.color=function(e){if("string"==typeof e){if(!e.trim())throw new Error('"color" is empty');return e.trim()}if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('"color" is an expression, or an object with r, g, b, a, rgb or rgba expressions');const t={};for(const[r,n]of Object.entries(e)){if(!no.includes(r))throw new Error(`"color" can set r, g, b, a, rgb or rgba — not "${r}"`);if("string"!=typeof n||!n.trim())throw new Error(`"color.${r}" must be an expression`);t[r]=n.trim()}if(!Object.keys(t).length)throw new Error('"color" sets no channels');return t}(e.color),t}function uo(e,t){if(!Array.isArray(e))throw new Error('"notes" is a list of Markdown texts and { "param": name } entries');return e.map(e=>{if("string"==typeof e)return e;if(!io(e)||"string"!=typeof e.param||1!==Object.keys(e).length)throw new Error('"notes": each entry is a Markdown text or { "param": name }');if(!Object.hasOwn(t,e.param))throw new Error(`"notes" places "${e.param}", but there is no parameter called that`);return{param:e.param}})}function po(e){if(e.color)return{...e.graphics??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(po(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function ho(e,t){if(!io(t))throw new Error(`Image "${e}": give { description, place, zoom, x, y, angle }`);const r={};if(t.description&&(r.description=String(t.description)),void 0!==t.place){if(!wn.includes(t.place))throw new Error(`Image "${e}": "place" is ${wn.join(", ")} — not "${t.place}"`);r.place=t.place}for(const n of["zoom","x","y","angle"]){if(void 0===t[n])continue;const o=Number(t[n]);if(!Number.isFinite(o))throw new Error(`Image "${e}": "${n}" is a number`);r[n]=o}for(const r of Object.keys(t))if(!["description","place","zoom","x","y","angle"].includes(r))throw new Error(`Image "${e}": no such setting "${r}"`);return r}function fo(e){if("string"==typeof e)return{filter:co(e),with:{},opacity:1,skip:!1};if(!e||"object"!=typeof e||Array.isArray(e))throw new Error('A step is an expression, a filter, or { "filter": …, "with": { … }, "opacity": … }');const{filter:t,with:r,opacity:n,skip:o,...s}=e,a={filter:co(void 0!==t?t:s),with:{},opacity:1,skip:Boolean(o)};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new Error('"with" is an object of parameter name → value');a.with={...r}}if(void 0!==n){const e=Number(n);if(!(e>=0&&e<=1))throw new Error('"opacity" is a number from 0 to 1');a.opacity=e}return a}function mo(e,t){if("number"==typeof t)t={default:t};else if(Array.isArray(t))t={type:"color",default:t};else if(!t||"object"!=typeof t)throw new Error(`Parameter "${e}" needs a default value`);const r=t.type??(Array.isArray(t.default)?"color":"number"),n={type:r};if(void 0!==t.label&&(n.label=String(t.label)),"color"===r){const r=t.default??[1,1,1];if(!ao(r))throw new Error(`Color parameter "${e}" needs a default of three numbers, 0–1`);return n.default=r.map(Number),n}if("number"!==r)throw new Error(`Parameter "${e}": the type is "number" or "color", not "${r}"`);let o=null;if(void 0!==t.options){if(!Array.isArray(t.options)||!t.options.length||!t.options.every(e=>""!==e&&Number.isFinite(Number(e))))throw new Error(`Parameter "${e}": "options" is a list of numbers`);o=t.options.map(Number)}if(void 0!==t.input&&"slider"!==t.input&&"box"!==t.input)throw new Error(`Parameter "${e}": "input" is "slider" or "box", not "${t.input}"`);const s=Number(t.default??(o?o[0]:0));if(!Number.isFinite(s))throw new Error(`Parameter "${e}" needs a numeric default`);if(n.default=s,n.min=void 0!==t.min?Number(t.min):o?o.reduce((e,t)=>Math.min(e,t),s):Math.min(0,2*s),n.max=void 0!==t.max?Number(t.max):o?o.reduce((e,t)=>Math.max(e,t),s):Math.max(1,2*s),void 0!==t.step&&(n.step=Number(t.step)),o&&(n.options=o),"box"!==t.input||o||(n.input="box"),!(n.min<=s&&s<=n.max))throw new Error(`Parameter "${e}": the default ${s} is outside ${n.min} to ${n.max}`);return n}function go(e){if(e.color)return{...e.images??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries(go(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function $o(e){if(e.color)return{...e.params??{}};const t={};for(const r of e.steps)for(const[e,n]of Object.entries($o(r.filter)))Object.hasOwn(t,e)||(t[e]=n);return t}function yo(e,t,r,n){const{filter:o}=e,s=bo(o,t),a=$o(o),i=go(o),l=po(o);for(const[t,n]of Object.entries(e.with)){if(Object.hasOwn(l,t)){if(io(n))try{Vn(t,{...l[t],...n})}catch(e){r.push(`${s}: ${e.message}`)}else r.push(`${s}: "with" for the graphic "${t}" is an object of its settings`);continue}if(Object.hasOwn(i,t)){try{ho(t,n)}catch(e){r.push(`${s}: ${e.message}`)}continue}const e=Object.hasOwn(a,t)?a[t]:null;e?("color"===e.type?ao(n):Number.isFinite(Number(n)))||r.push(`${s}: "${t}" should be a ${"color"===e.type?"color: three numbers, 0–1":"number"}`):r.push(`${s}: "with" sets "${t}", but there is no parameter called that`)}o.steps&&o.steps.forEach((e,n)=>yo(e,[...t,n],r))}function bo(e,t){return e.name?`"${e.name}"`:t.length?`step ${t.map(e=>e+1).join(".")}`:"the filter"}function wo(e,t={}){const r=co(e),n=[];if(yo({filter:r,with:{}},[],n),n.length)throw new Error(n.join("\n"));const o={passes:[],credits:[],problems:n,version:300===t.version?300:100,top:r,graphics:{}};if(xo({filter:r,with:{},opacity:1,skip:!1},[],{},o),n.length)throw new Error(n.join("\n"));return o.passes.length||o.passes.push(vo(co("pixel(px, py)"),{},1,[],o.version)),{name:r.name??"",author:r.author??"",description:r.description??"",version:o.version,passes:o.passes,credits:o.credits,images:go(r),graphics:o.graphics}}function xo(e,t,r,n){if(e.skip)return;if(n.passes.length>256){const e="A filter has at most 256 passes";return void(n.problems.includes(e)||n.problems.push(e))}const o=function(e){if(!e.space||void 0===e.color)return null;const{space:t,name:r,author:n,description:o,...s}=e,a=e=>({filter:e,with:{},opacity:1,skip:!1}),i=[];"srgb"!==t.in&&i.push(a({format:ro,color:{rgb:`to${t.in}(rgb)`}}));i.push(a({...s,_space:t.in})),"srgb"!==t.out&&i.push(a({format:ro,color:{rgb:`from${t.out}(rgb)`}}));const l={format:ro,steps:i};for(const[e,t]of Object.entries({name:r,author:n,description:o}))t&&(l[e]=t);return l}(e.filter)??function(e){if("string"!=typeof e.color)return null;const t=/^(gaussian|blur)\((.*)\)$/s.exec(e.color.trim());if(!t)return null;let r=0;for(const e of t[2])if("("===e)r++;else if(")"===e&&--r<0)return null;if(0!==r)return null;const{color:n,...o}=e,s=e=>{const r={format:ro,color:`${t[1]}${e}(${t[2]})`};return o.params&&(r.params=o.params),o.images&&(r.images=o.images),o.graphics&&(r.graphics=o.graphics),{filter:r,with:{},opacity:1,skip:!1}};return{...o,steps:[s("x"),s("y")]}}(e.filter);if(o)return e.filter===n.top&&(n.top=o),void xo({...e,filter:o},t,r,n);const{filter:s}=e,a={...e.with,...r};for(const t of Object.keys(r))io(r[t])&&io(e.with[t])&&(a[t]={...e.with[t],...r[t]});if(s.name&&s!==n.top&&!n.credits.some(e=>e.name===s.name&&e.author===(s.author??""))&&n.credits.push({name:s.name,author:s.author??""}),s.color){try{n.passes.push(function(e,t){e.bind={};for(const[r,n]of Object.entries(e.graphics??{})){let o=r;for(let e=2;o in t&&JSON.stringify(t[o])!==JSON.stringify(n);e++)o=`${r}~${e}`;t[o]=n,e.bind[r]=o}return e}(vo(s,a,e.opacity,t,n.version),n.graphics))}catch(e){n.problems.push(`${bo(s,t)}: ${e.message}`)}return}const i=n.passes.length;s.steps.forEach((e,r)=>xo(e,[...t,r],a,n)),e.opacity<1&&(n.passes.length-i===1?n.passes[i].opacity*=e.opacity:(n.passes[i].keepInput+=1,n.passes.push(function(e,t,r){const n=300===r,o=n?"texture":"texture2D",s=[n?"#version 300 es":"","precision highp float;","uniform sampler2D image;","uniform sampler2D base;","uniform vec2 resolution;","uniform float mz_opacity;",n?"out vec4 fragColor;":"","void main() {"," vec2 uv = gl_FragCoord.xy / resolution;",` ${n?"fragColor":"gl_FragColor"} = mix(${o}(base, uv), ${o}(image, uv), mz_opacity);`,"}"].filter(Boolean).join("\n");return{name:"blend",author:"",path:t,fragment:s,params:{},values:{},opacity:e,images:[],placements:{},graphics:{},keepInput:0,blendKept:!0}}(e.opacity,t,n.version))))}function vo(e,t,r,n,o){const s=e.params??{},a={};for(const[e,r]of Object.entries(s))Object.hasOwn(t,e)?a[e]="color"===r.type?t[e].map(Number):Number(t[e]):a[e]=r.default;const i={};for(const[r,n]of Object.entries(e.images??{})){const{description:e,...o}=n;i[r]={...lo,...o,...io(t[r])?t[r]:{}}}const l={};for(const[r,n]of Object.entries(e.graphics??{}))l[r]=io(t[r])?Vn(r,{...n,...t[r]}):n,i[r]={...lo,place:"stretch"},Un(r,l[r]).forEach((e,t)=>{l[e]={...l[r],onlyShadow:t},i[e]={...lo,place:"stretch"}});const c=function(e,t,r=null){const n=e.params??{},o={};for(const[e,t]of Object.entries(n))o[e]="color"===t.type?"vec3":"float";const s={};for(const[t,n]of Object.entries(e.images??{}))s[t]={place:r?.[t]?.place??n.place??lo.place};for(const[t,n]of Object.entries(e.graphics??{})){s[t]={place:"stretch"};const e=r?Object.keys(r).filter(e=>/_shadow\d+$/.test(e)&&e.startsWith(`${t}_shadow`)):Un(t,n);for(const t of e)s[t]={place:"stretch"}}return function(e,t={}){const r=Array.isArray(t.images)?t.images:Object.keys(t.images??{}),n=[...gn,...t.names??[],...r],o=[...un,...t.values??[]];return Mn(e,{...t,parse:e=>Pr(e,{...t,names:n,values:o})})}(e.color,{version:t,uniforms:o,values:Object.keys(n),images:s,blend:!0,space:e._space??e.space?.in??"srgb"})}(e,o,i),u=Object.keys(i);return c.includes("uniform sampler2D mz_img_source;")&&u.push("source"),c.includes("uniform sampler2D mz_img_selection;")&&u.push("selection"),c.includes("uniform sampler2D mz_img_away;")&&u.push("away"),{name:e.name??"",author:e.author??"",path:n,color:e.color,space:e._space??"srgb",fragment:c,params:s,values:a,opacity:r,images:u,placements:i,graphics:l,keepInput:0,blendKept:!1}}function _o(e){return JSON.stringify(zo(co(e),!0),null,2)}function Ao(e){const t=e.includes("#")?e.slice(e.lastIndexOf("#")+1):e;let r;try{r=JSON.parse(function(e){const t=atob(e.replace(/-/g,"+").replace(/_/g,"/"));return(new TextDecoder).decode(Uint8Array.from(t,e=>e.charCodeAt(0)))}(t.trim()))}catch{throw new Error("Not a filter link")}return co(r)}function Eo(e){const t=String(e??"").trim();if(!t)throw new Error("Nothing to read");if(t.startsWith("{"))return function(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Not valid JSON")}return co(t)}(t);if(!/\s/.test(t)){const e=t.includes("#")?t.slice(t.lastIndexOf("#")+1):t;if(/^[A-Za-z0-9_-]{8,}$/.test(e))try{return Ao(e)}catch(e){if(t.includes("#"))throw e}}return co(t)}function zo(e,t){const r={};t&&(r.format=ro);for(const t of["name","author","description"])e[t]&&(r[t]=e[t]);return e.notes&&e.notes.length&&(r.notes=e.notes),e.steps?(r.steps=e.steps.map(e=>{const t=zo(e.filter,!1),r=1===Object.keys(t).length&&"string"==typeof t.color?t.color:t,n={};return Object.keys(e.with).length&&(n.with=e.with),1!==e.opacity&&(n.opacity=e.opacity),e.skip&&(n.skip=!0),Object.keys(n).length?{filter:r,...n}:r}),r):(e.params&&(r.params=e.params),e.images&&(r.images=e.images),e.graphics&&(r.graphics=e.graphics),e.space&&(r.space=e.space.in===e.space.out?e.space.in:e.space),r.color=e.color,r)}const Mo=1e20;function ko(e,t,r,n,o){let s=0;n[0]=0,o[0]=-Mo,o[1]=Mo;for(let r=1;r<t;r++){const t=e[r]+r*r;let a=n[s],i=(t-(e[a]+a*a))/(2*(r-a));for(;i<=o[s];)s--,a=n[s],i=(t-(e[a]+a*a))/(2*(r-a));s++,n[s]=r,o[s]=i,o[s+1]=Mo}s=0;for(let a=0;a<t;a++){for(;o[s+1]<a;)s++;const t=n[s];r[a]=(a-t)*(a-t)+e[t]}}function Oo(e,t,r){const n="function"==typeof e?e:t=>0!==e[t],o=Math.max(t,r),s=new Float64Array(o),a=new Float64Array(o),i=new Int32Array(o),l=new Float64Array(o+1),c=new Float64Array(t*r);for(let e=0;e<c.length;e++)c[e]=n(e)?0:Mo;for(let e=0;e<t;e++){for(let n=0;n<r;n++)s[n]=c[n*t+e];ko(s,r,a,i,l);for(let n=0;n<r;n++)c[n*t+e]=a[n]}const u=new Float32Array(t*r);for(let e=0;e<r;e++){const r=e*t;for(let e=0;e<t;e++)s[e]=c[r+e];ko(s,t,a,i,l);for(let e=0;e<t;e++)u[r+e]=a[e]>=Mo/2?1/0:Math.sqrt(a[e])}return u}function jo(e,{size:t=512}={}){if(!e)return null;const r=e.naturalWidth||e.videoWidth||e.width,n=e.naturalHeight||e.videoHeight||e.height;if(!r||!n)return null;const o=Math.min(1,t/Math.max(r,n)),s=Math.max(1,Math.round(r*o)),a=Math.max(1,Math.round(n*o));let i;if(!e.data||"undefined"!=typeof HTMLElement&&e instanceof HTMLElement){const t=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(s,a):Object.assign(document.createElement("canvas"),{width:s,height:a})).getContext("2d",{willReadFrequently:!0});t.drawImage(e,0,0,s,a),i=t.getImageData(0,0,s,a).data}else if(i=e.data,s!==r||a!==n){const e=new i.constructor(s*a*4);for(let t=0;t<a;t++){const o=Math.min(n-1,Math.floor((t+.5)*n/a));for(let n=0;n<s;n++){const a=4*(o*r+Math.min(r-1,Math.floor((n+.5)*r/s))),l=4*(t*s+n);for(let t=0;t<4;t++)e[l+t]=i[a+t]}}i=e}return function(e,t,r,{channel:n=0,scale:o=1}={}){const s=e instanceof Float32Array||e instanceof Float64Array?.5:128,a=t=>e[4*t+n]>=s,i=Oo(a,t,r),l=Oo(e=>!a(e),t,r),c=new Uint8ClampedArray(t*r*4);for(let e=0,t=0;e<i.length;e++,t+=4){const r=i[e]*o,n=l[e]*o;c[t]=255-Math.min(r,255),c[t+1]=255-Math.min(r,1020)/4,c[t+2]=255-Math.min(n,255),c[t+3]=255}return{data:c,width:t,height:r}}(i,s,a,{scale:r/s})}function So(e,t){if(!(e=>e.passes.some(e=>e.images?.includes("away")))(t))return e;const r=e.setImage.bind(e);let n=!1,o=null;return e.setImage=(t,s)=>"away"===t?(n=null!=s,r("away",n?s:jo(o))):(r(t,s),"selection"===t&&(o=s??null,n||r("away",jo(o))),e),e}function No(e,t,r={}){if(e.isContextLost())throw new Error("The WebGL context is lost");const n=To(e,r.precision),o=function(e={}){return 300===e.version?"#version 300 es\nin vec2 position;\nvoid main() { gl_Position = vec4(position, 0.0, 1.0); }":"attribute vec2 position;\nvoid main() { gl_Position = vec4(position, 0.0, 1.0); }"}({version:t.version}),s=[];try{for(const r of t.passes)s.push(Ro(e,o,r.fragment,r.name))}catch(t){for(const t of s)e.deleteProgram(t);throw t}const a=(e,t)=>e.bind&&Object.hasOwn(e.bind,t)?e.bind[t]:t,i=s.map(()=>new Map),l=(t,r)=>(i[t].has(r)||i[t].set(r,e.getUniformLocation(s[t],r)),i[t].get(r)),c=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,c),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),e.STATIC_DRAW);const u={texture:e.createTexture(),framebuffer:null};e.bindTexture(e.TEXTURE_2D,u.texture),Io(e);const p=new Map,h=new Map,f=e.createTexture();e.bindTexture(e.TEXTURE_2D,f),Io(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([255,255,255,255]));const m=e.createTexture();e.bindTexture(e.TEXTURE_2D,m),Io(e),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,new Uint8Array([0,0,0,0]));const g=[];let d=0,$=0;const y={passes:t.passes,get precision(){return n.name},setImage(t,r){if("string"!=typeof t&&(r=t,t=null),t&&"source"!==t&&null==r)return p.has(t)&&e.deleteTexture(p.get(t)),p.delete(t),h.delete(t),y;let n=u.texture;if(t&&"source"!==t&&(p.has(t)||(p.set(t,e.createTexture()),e.bindTexture(e.TEXTURE_2D,p.get(t)),Io(e)),n=p.get(t)),r&&r.data&&r.width&&r.height&&"undefined"!=typeof ImageData&&!(r instanceof ImageData)){const e=r.data,t=e instanceof Float32Array||e instanceof Float64Array,n=e instanceof Uint8ClampedArray?e:Uint8ClampedArray.from(e,t?e=>255*e:void 0);r=new ImageData(n,r.width,r.height)}return e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r),t&&h.set(t,[r.naturalWidth||r.videoWidth||r.width||1,r.naturalHeight||r.videoHeight||r.height||1]),y},draw({t:r=0}={}){if(e.drawingBufferWidth!==d||e.drawingBufferHeight!==$){d=e.drawingBufferWidth,$=e.drawingBufferHeight;for(const t of g)e.bindTexture(e.TEXTURE_2D,t.texture),e.texImage2D(e.TEXTURE_2D,0,n.internal,d,$,0,e.RGBA,n.type,null)}let o=u;const i=[];return t.passes.forEach((y,b)=>{for(let e=0;e<y.keepInput;e++)i.push(o);const w=b===t.passes.length-1?null:function(t){let r=g.find(e=>!t.includes(e));return r||(r={texture:e.createTexture(),framebuffer:e.createFramebuffer()},e.bindTexture(e.TEXTURE_2D,r.texture),Io(e,n.filter),e.texImage2D(e.TEXTURE_2D,0,n.internal,d,$,0,e.RGBA,n.type,null),e.bindFramebuffer(e.FRAMEBUFFER,r.framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r.texture,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE&&"byte"!==n.name&&(Object.assign(n,To(e,"byte")),e.bindTexture(e.TEXTURE_2D,r.texture),Io(e,n.filter),e.texImage2D(e.TEXTURE_2D,0,n.internal,d,$,0,e.RGBA,n.type,null)),g.push(r)),r}([o,...i]);e.bindFramebuffer(e.FRAMEBUFFER,w?w.framebuffer:null),e.viewport(0,0,d,$);const x=s[b];e.useProgram(x);const v=e.getAttribLocation(x,"position");e.bindBuffer(e.ARRAY_BUFFER,c),e.enableVertexAttribArray(v),e.vertexAttribPointer(v,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,o.texture),e.uniform1i(l(b,"image"),0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,y.blendKept?i[i.length-1].texture:null),y.blendKept&&e.uniform1i(l(b,"base"),1),y.images.forEach((t,r)=>{if(e.activeTexture(e.TEXTURE2+r),e.bindTexture(e.TEXTURE_2D,"source"===t?u.texture:p.get(a(y,t))??(y.graphics?.[t]?m:f)),e.uniform1i(l(b,`mz_img_${t}`),2+r),!y.placements[t])return;const n=h.get(a(y,t))??[1,1],o=y.placements[t];e.uniform2f(l(b,`mz_size_${t}`),n[0],n[1]),e.uniform4f(l(b,`mz_place_${t}`),Number(o.zoom),Number(o.x),Number(o.y),Number(o.angle))}),e.uniform2f(l(b,"resolution"),d,$),e.uniform1f(l(b,"t"),r),e.uniform1f(l(b,"mz_opacity"),y.opacity);for(const[t,r]of Object.entries(y.params)){const n=y.values[t];"color"===r.type?e.uniform3fv(l(b,t),n.map(Number)):e.uniform1f(l(b,t),Number(n))}e.drawArrays(e.TRIANGLES,0,3),y.blendKept&&i.pop(),o=w}),y},dispose(){for(const t of s)e.deleteProgram(t);e.deleteTexture(u.texture),e.deleteTexture(f),e.deleteTexture(m);for(const t of p.values())e.deleteTexture(t);for(const t of g)e.deleteTexture(t.texture),e.deleteFramebuffer(t.framebuffer);e.deleteBuffer(c)}};return So(y,t)}function Io(e,t=e.LINEAR){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t)}function To(e,t="byte"){const r={name:"byte",internal:e.RGBA,type:e.UNSIGNED_BYTE,filter:e.LINEAR};if("half"!==t&&"float"!==t)return r;if("undefined"!=typeof WebGL2RenderingContext&&e instanceof WebGL2RenderingContext){if(!e.getExtension("EXT_color_buffer_float"))return r;const n=e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST;return"float"===t?{name:"float",internal:e.RGBA32F,type:e.FLOAT,filter:n}:{name:"half",internal:e.RGBA16F,type:e.HALF_FLOAT,filter:e.LINEAR}}if("float"===t&&e.getExtension("OES_texture_float")&&e.getExtension("WEBGL_color_buffer_float"))return{name:"float",internal:e.RGBA,type:e.FLOAT,filter:e.getExtension("OES_texture_float_linear")?e.LINEAR:e.NEAREST};const n=e.getExtension("OES_texture_half_float");return n&&e.getExtension("EXT_color_buffer_half_float")?{name:"half",internal:e.RGBA,type:n.HALF_FLOAT_OES,filter:e.getExtension("OES_texture_half_float_linear")?e.LINEAR:e.NEAREST}:r}function Ro(e,t,r,n){const o=e.createProgram(),s=[];let a=null;for(const[i,l]of[[e.VERTEX_SHADER,t],[e.FRAGMENT_SHADER,r]]){const t=e.createShader(i);if(s.push(t),e.shaderSource(t,l),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS)){a=`${n||"The filter"} does not compile: ${(e.getShaderInfoLog(t)??"").trim()}`;break}e.attachShader(o,t)}a||(e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS)||(a=`${n||"The filter"} does not link: ${(e.getProgramInfoLog(o)??"").trim()}`));for(const t of s)e.deleteShader(t);if(a)throw e.deleteProgram(o),new Error(a);return o}class Fo extends Error{}const Co=new Set(Object.getOwnPropertyNames(Math)),qo=new Set([...Co,"isInteger","isFinite","includes","reduce","toFixed"]),Lo={Math:Co,Number:new Set(["isInteger","isFinite"])},Po=new Set(["Math","Number","Infinity","NaN","true","false","null"]),Uo=new Set(["let","for","if","return"]),Bo=Object.values(me).sort((e,t)=>t.length-e.length),Do=["===","!==","**=","...","=>","==","!=","<=",">=","&&","||","??","**","++","--","+=","-=","*=","/=","%=","(",")","[","]","{","}",",",";","?",":",".","+","-","*","/","%","!","=","<",">","&","|","^","~"],Zo=new Set(["=","+=","-=","*=","/=","%=","**=","++","--"]);for(const e of[Lo])Object.setPrototypeOf(e,null);const Go={name:"javascript",title:"JavaScript",pi:"Math.PI",e:"Math.E",tau:"(2 * Math.PI)",inf:"Infinity",degree:"(Math.PI/180)",true:"true",false:"false",null:"null",math:e=>`Math.${e}`,abs:"Math.abs",max:"Math.max",min:"Math.min",random:"Math.random()",pow:(e,t)=>`Math.pow(${e}, ${t})`,both:(e,t)=>`(${e} && ${t})`,either:(e,t)=>`(${e} || ${t})`,not:e=>`!${e}`,xor:(e,t)=>`(!(${e}) !== !(${t}))`,oddRoot:(e,t)=>3===t?`Math.cbrt(${e})`:us(e)?`(${e} < 0 ? -Math.pow(-${e}, 1 / ${t}) : Math.pow(${e}, 1 / ${t}))`:`${me.root}(${t}, ${e})`,realRoot:(e,t)=>`${me.root}(${e}, ${t})`,close:(e,t)=>`Math.abs((${e}) - (${t})) < 1e-9`,eq:{"=":"==","===":"===","≠":"!=","≠=":"!=="},ternary:(e,t,r)=>`(${e} ? ${t} : ${r})`,list:{"()":["[","]"],"[]":["[","]"],"{}":["[","]"],"(]":["[","]"],"[)":["[","]"]},contains:(e,t,r)=>`${r?"!":""}${e}.includes(${t})`,substring:(e,t,r)=>`${r?"!":""}${me.contains}(${e}, ${t})`,startsWith:(e,t)=>`${me.startswith}(${e}, ${t})`,factorial:e=>`${me.factorial}(${e})`,perm:(e,t)=>`${me.perm}(${e}, ${t})`,comb:(e,t)=>`${me.comb}(${e}, ${t})`,gcd:e=>`${me.gcd}([${e}])`,round:(e,t)=>{const r=ms(e)?e:`(${e})`;if(cs(e)&&us(t))return"0"===t?`Math.round(${e})`:`Math.round(${e} * Math.pow(10, ${t})) / Math.pow(10, ${t})`;if(!us(e)||!us(t))return`${me.round}(${e}, ${t})`;if("0"===t)return`(${r} < 0 ? -Math.round(-${r}) : Math.round(${r}))`;const n=`Math.pow(10, ${t})`;return`(${r} < 0 ? -Math.round(-${r} * ${n}) : Math.round(${r} * ${n})) / ${n}`},fixed:(e,t)=>`Number(${e}).toFixed(${t})`,matrix:e=>`[${e.map(e=>`[${e.join(", ")}]`).join(", ")}]`,det:e=>`${me.det}(${e})`,union:(e,t)=>`${me.union}(${e}, ${t})`,intersection:(e,t)=>`${me.intersection}(${e}, ${t})`,indexed:(e,t,r,n,o)=>"sum"===e?`(()=>{let sum = 0; let loopCount = 0; for (let ${t}=${r};${n};${t}++) {if (loopCount++ > 1000000){break};sum += ${o};}; return sum;})()`:`(()=>{let prod = 1; let loopCount = 0; for (let ${t}=${r};${n};${t}++) {if (loopCount++ > 1000000){break};prod *= ${o};}; return prod;})()`},Wo={name:"python",title:"Python",python:!0,pi:"math.pi",e:"math.e",tau:"math.tau",inf:"math.inf",degree:"(math.pi/180)",true:"True",false:"False",null:"None",math:e=>`math.${e}`,abs:"abs",max:"max",min:"min",random:"random.random()",pow:null,both:(e,t)=>`(${e} and ${t})`,either:(e,t)=>`(${e} or ${t})`,not:e=>`not ${e}`,xor:(e,t)=>`((not (${e})) != (not (${t})))`,oddRoot:(e,t)=>3===t?`math.cbrt(${e})`:hs(e,e=>`(-(-${e}) ** (1 / ${t}) if ${e} < 0 else ${e} ** (1 / ${t}))`),realRoot:(e,t)=>hs(t,t=>`(-(-${t}) ** (1 / ${fs(e)}) if ${t} < 0 and ${fs(e)} % 2 == 1 else ${t} ** (1 / ${fs(e)}))`),close:(e,t)=>`abs((${e}) - (${t})) < 1e-9`,eq:{"=":"==","===":"==","≠":"!=","≠=":"!="},ternary:(e,t,r)=>`(${t} if ${e} else ${r})`,list:{"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(",")"],"[)":["(",")"]},emptySet:"set()",contains:(e,t,r)=>`${t} ${r?"not in":"in"} ${e}`,substring:(e,t,r)=>r?`(not ${ye.contains}(${e}, ${t}))`:`${ye.contains}(${e}, ${t})`,startsWith:(e,t)=>`${ye.startswith}(${e}, ${t})`,factorial:e=>`math.factorial(${e})`,perm:(e,t)=>`math.perm(${e}, ${t})`,comb:(e,t)=>`math.comb(${e}, ${t})`,gcd:e=>`math.gcd(${e})`,round:(e,t)=>{if("0"===t)return cs(e)?`math.floor(${e} + 0.5)`:hs(e,t=>ps(e,`(math.floor(${t} + 0.5) if ${t} >= 0 else -math.floor(-${t} + 0.5))`,t));const r=`10 ** ${ms(t)?t:`(${t})`}`;if(cs(e)&&us(t))return`math.floor(${e} * ${r} + 0.5) / ${r}`;const n=(t,r)=>ps(e,`(math.floor(${t} * ${r} + 0.5) if ${t} >= 0 else -math.floor(-${t} * ${r} + 0.5)) / ${r}`,t);return us(e)&&us(t)?n(ms(e)?e:`(${e})`,r):`(lambda _v, _p: ${n("_v","_p")})(${e}, ${r})`},fixed:(e,t,r)=>null===r?`format(${Wo.round(e,t)}, "." + str(${t}) + "f")`:`format(${Wo.round(e,r)}, ".${r}f")`,matrix:e=>`[${e.map(e=>`[${e.join(", ")}]`).join(", ")}]`,det:e=>`np.linalg.det(${e})`,union:(e,t)=>`sorted(set(${e}) | set(${t}))`,intersection:(e,t)=>`sorted(set(${e}) & set(${t}))`,integral:(e,t,r,n)=>`scipy.integrate.quad(lambda ${r}: ${t}, ${n.join(", ")})[0]`,symbolic:"the SymPy flavour, { sympy: true }, has it",indexed:(e,t,r,n,o,s)=>"sum"===e?`sum(${o} for ${t} in range(${r}, ${s} + 1))`:`math.prod(${o} for ${t} in range(${r}, ${s} + 1))`},Ho={asin:"arcsin",acos:"arccos",atan:"arctan",asinh:"arcsinh",acosh:"arccosh",atanh:"arctanh",atan2:"arctan2",pow:"power"},Xo=(e,t)=>t.reduce((t,r)=>`${e}(${t}, ${r})`),Vo={"<":"<",">":">","≤":"<=","≥":">=","=":"==","===":"==","≠":"!=","≠=":"!="},Yo=([,e],t,r)=>{const[n,o]=t.args,s=(e,t)=>"op"===e.type&&ds.has(e.op)?`(${t})`:t,a=r=>`${r} ${Vo[t.op]} ${s(o,e)}`;return"op"===n.type&&Vo[n.op]?`np.logical_and(${r(n)}, ${a(s(n.args[1],r(n.args[1])))})`:a(s(n,r(n)))},Jo={...Wo,name:"numpy",title:"numpy",union:(e,t)=>`np.union1d(${e}, ${t})`,intersection:(e,t)=>`np.intersect1d(${e}, ${t})`,pi:"np.pi",e:"np.e",tau:"(2 * np.pi)",inf:"np.inf",degree:"(np.pi/180)",math:e=>`np.${Ho[e]??e}`,list:{...Wo.list,"{}":["[","]"]},abs:"np.abs",random:"np.random.random()",matrix:e=>`np.array(${Wo.matrix(e)})`,det:e=>`np.linalg.det(${e})`,both:(e,t)=>`np.logical_and(${e}, ${t})`,either:(e,t)=>`np.logical_or(${e}, ${t})`,not:e=>`np.logical_not(${e})`,close:(e,t)=>`np.isclose(${e}, ${t})`,ternary:(e,t,r)=>`np.where(${e}, ${t}, ${r})`,contains:(e,t,r)=>r?`np.logical_not(np.isin(${t}, ${e}))`:`np.isin(${t}, ${e})`,substring:(e,t,r)=>r?`np.logical_not(${be.contains}(${e}, ${t}))`:`${be.contains}(${e}, ${t})`,startsWith:(e,t)=>`${be.startswith}(${e}, ${t})`,factorial:e=>`scipy.special.factorial(${e})`,perm:(e,t)=>`scipy.special.perm(${e}, ${t})`,comb:(e,t)=>`scipy.special.comb(${e}, ${t})`,round:(e,t)=>{if("0"===t)return hs(e,e=>`np.where(${e} >= 0, np.floor(${e} + 0.5), -np.floor(-${e} + 0.5))`);const r=`10.0 ** ${ms(t)?t:`(${t})`}`,n=(e,t)=>`np.where(${e} >= 0, np.floor(${e} * ${t} + 0.5), -np.floor(-${e} * ${t} + 0.5)) / ${t}`;return us(e)&&us(t)?n(ms(e)?e:`(${e})`,r):`(lambda _v, _p: ${n("_v","_p")})(${e}, ${r})`},oddRoot:(e,t)=>3===t?`np.cbrt(${e})`:hs(e,e=>`np.where(${e} < 0, -np.power(-${e}, 1 / ${t}), np.power(${e}, 1 / ${t}))`),realRoot:(e,t)=>hs(t,t=>`np.where((${t} < 0) & (np.mod(${e}, 2) == 1), -np.power(-${t}, 1 / ${fs(e)}), np.power(${t}, 1 / ${fs(e)}))`),fixed:(e,t,r)=>null===r?`np.char.mod("%." + str(${t}) + "f", ${Jo.round(e,t)})`:`np.char.mod("%.${r}f", ${Jo.round(e,r)})`,ops:{...Object.fromEntries(Object.keys(Vo).map(e=>[e,Yo])),max:e=>1===e.length?`np.nanmax(${e[0]})`:Xo("np.maximum",e),min:e=>1===e.length?`np.nanmin(${e[0]})`:Xo("np.minimum",e),sum:e=>1===e.length?`np.nansum(${e[0]})`:null,prod:e=>1===e.length?`np.nanprod(${e[0]})`:null,mean:e=>1===e.length?`np.nanmean(${e[0]})`:null,"\\:median":e=>1===e.length?`np.nanmedian(${e[0]})`:null,"\\:stdev":e=>1===e.length?`np.nanstd(${e[0]})`:null,"\\:std":e=>1===e.length?`np.nanstd(${e[0]})`:null,gcd:e=>Xo("np.gcd",e),"\\xor":([e,t])=>`np.logical_xor(${e}, ${t})`,"\\nand":([e,t])=>`np.logical_not(np.logical_and(${e}, ${t}))`,"\\implies":([e,t])=>`np.logical_or(np.logical_not(${e}), ${t})`,"\\iff":([e,t])=>`np.logical_not(np.logical_xor(${e}, ${t}))`,"\\nor":([e,t])=>`np.logical_not(np.logical_or(${e}, ${t}))`}},Ko=e=>`sympy.${e}`,Qo=e=>"number"===e.type&&/^-?\d+$/.test(e.value)||"op"===e.type&&"neg"===e.op&&Qo(e.args[0]),es={"ℝ":"sympy.S.Reals","ℤ":"sympy.S.Integers","ℕ":"sympy.S.Naturals","ℚ":"sympy.S.Rationals","ℂ":"sympy.S.Complexes"},ts={"[]":"sympy.Interval","()":"sympy.Interval.open","(]":"sympy.Interval.Lopen","[)":"sympy.Interval.Ropen"};function rs(e,t){return"symbol"===e.type&&es[e.value]?es[e.value]:"op"===e.type&&ts[e.op]&&2===e.args.length?`${ts[e.op]}(${e.args.map(t).join(", ")})`:"op"===e.type&&xt(e.op)?.group?`sympy.FiniteSet(${e.args.map(t).join(", ")})`:"number"===e.type||"neg"===e.op&&"number"===e.args[0].type?`sympy.FiniteSet(${t(e)})`:t(e)}function ns(e,t,r,n){const o=[];return function t(n){"op"===n.type&&n.op===e?n.args.forEach(t):o.push(r(n))}(t),`${n}(${o.join(", ")})`}const os={...Wo,name:"sympy",title:"SymPy",symbolic:null,noStrings:!0,pi:Ko("pi"),e:Ko("E"),tau:"(2*sympy.pi)",inf:Ko("oo"),degree:"(sympy.pi/180)",true:Ko("true"),false:Ko("false"),null:"None",math:e=>Ko({log:"log",asin:"asin",acos:"acos",atan:"atan",asinh:"asinh",acosh:"acosh",atanh:"atanh",atan2:"atan2",expm1:"expm1",ceil:"ceiling"}[e]??e),abs:Ko("Abs"),random:"random.random()",matrix:e=>`sympy.Matrix(${Wo.matrix(e)})`,det:e=>`sympy.det(${e})`,both:(e,t)=>`sympy.And(${e}, ${t})`,either:(e,t)=>`sympy.Or(${e}, ${t})`,not:e=>`sympy.Not(${e})`,close:(e,t)=>`sympy.Abs((${e}) - (${t})) < sympy.Rational(1, 10**9)`,exactNumber:e=>{const t=/^(\d*)\.(\d+)$/.exec(e);if(!t)return e;const r=10n**BigInt(t[2].length);let[n,o]=[BigInt(t[1]||"0")*r+BigInt(t[2]),r];const s=(e,t)=>t?s(t,e%t):e,a=s(n,o);return[n,o]=[n/a,o/a],1n===o?String(n):`sympy.Rational(${n}, ${o})`},factorial:e=>`sympy.factorial(${e})`,perm:(e,t)=>`sympy.ff(${e}, ${t})`,comb:(e,t)=>`sympy.binomial(${e}, ${t})`,ops:{"/":(e,t)=>Qo(t.args[0])&&Qo(t.args[1])?`sympy.Rational(${e[0]}, ${e[1]})`:null,"^":(e,t)=>"symbol"===t.args[0].type&&"e"===t.args[0].value?`sympy.exp(${e[1]})`:null,"=":e=>`sympy.Eq(${e[0]}, ${e[1]})`,"===":e=>`sympy.Eq(${e[0]}, ${e[1]})`,"≡":e=>`sympy.Eq(${e[0]}, ${e[1]})`,"≠":e=>`sympy.Ne(${e[0]}, ${e[1]})`,"≠=":e=>`sympy.Ne(${e[0]}, ${e[1]})`,mod:e=>`sympy.Mod(${e[0]}, ${e[1]})`,pmod:(e,t,r)=>{const[n]=t.args;return"op"===n.type&&["≡","="].includes(n.op)?`sympy.Eq(sympy.Mod((${r(n.args[0])}) - (${r(n.args[1])}), ${e[1]}), 0)`:`sympy.Mod(${e[0]}, ${e[1]})`},"!":e=>`sympy.factorial(${e[0]})`,perm:e=>`sympy.ff(${e[0]}, ${e[1]})`,comb:e=>`sympy.binomial(${e[0]}, ${e[1]})`,gcd:e=>2===e.length?`sympy.gcd(${e.join(", ")})`:`sympy.gcd_list([${e.join(", ")}])`,max:e=>`sympy.Max(${e.join(", ")})`,min:e=>`sympy.Min(${e.join(", ")})`,floor:e=>`sympy.floor(${e[0]})`,ceil:e=>`sympy.ceiling(${e[0]})`,csc:e=>`sympy.csc(${e[0]})`,sec:e=>`sympy.sec(${e[0]})`,cot:e=>`sympy.cot(${e[0]})`,ln:e=>`sympy.log(${e[0]})`,log:(e,t)=>"symbol"===t.args[0].type&&"e"===t.args[0].value?`sympy.log(${e[1]})`:`sympy.log(${e[1]}, ${e[0]})`,loglog:e=>`sympy.log(sympy.log(${e[0]}))`,logloglog:e=>`sympy.log(sympy.log(sympy.log(${e[0]})))`,expm1:e=>`(sympy.exp(${e[0]}) - 1)`,root:(e,t)=>"number"===t.args[0].type&&/^\d*[13579]$/.test(t.args[0].value)&&("number"===t.args[1].type||"neg"===t.args[1].op&&"number"===t.args[1].args[0].type)?`sympy.real_root(${e[1]}, ${e[0]})`:`sympy.root(${e[1]}, ${e[0]})`,round:(e,t)=>{const r="number"===t.args[1].type&&"0"===t.args[1].value,n=(e,t)=>{const n=r?`(${e})`:`(${e}) * 10**(${t})`,o=`sympy.Piecewise((${`sympy.floor(${n} + sympy.Rational(1, 2))`}, ${e} >= 0), (${`-sympy.floor(-${n} + sympy.Rational(1, 2))`}, True))`;return r?o:`${o} / 10**(${t})`};return r?hs(e[0],e=>n(e)):us(e[0])&&us(e[1])?n(e[0],e[1]):`(lambda _v, _p: ${n("_v","_p")})(${e[0]}, ${e[1]})`},"&":(e,t,r)=>ns("&",t,r,"sympy.And"),"|":(e,t,r)=>ns("|",t,r,"sympy.Or"),"\\not":e=>`sympy.Not(${e[0]})`,"\\xor":e=>`sympy.Xor(${e.join(", ")})`,"\\nand":e=>`sympy.Nand(${e.join(", ")})`,"\\implies":e=>`sympy.Implies(${e.join(", ")})`,"\\iff":e=>`sympy.Equivalent(${e.join(", ")})`,"\\nor":e=>`sympy.Nor(${e.join(", ")})`,"?:":e=>`sympy.Piecewise((${e[1]}, ${e[0]}), (${e[2]}, True))`,"∈":(e,t,r)=>`sympy.Contains(${e[0]}, ${rs(t.args[1],r)})`,"∉":(e,t,r)=>`sympy.Not(sympy.Contains(${e[0]}, ${rs(t.args[1],r)}))`,"∪":(e,t,r)=>`sympy.Union(${t.args.map(e=>rs(e,r)).join(", ")})`,"∩":(e,t,r)=>`sympy.Intersection(${t.args.map(e=>rs(e,r)).join(", ")})`,"{}":e=>`sympy.FiniteSet(${e.join(", ")})`,der:(e,t,r)=>{const n=t.args[1];return"op"===n.type&&"="===n.op?`sympy.diff(${e[0]}, ${r(n.args[0])}).subs(${r(n.args[0])}, ${r(n.args[1])})`:`sympy.diff(${e.join(", ")})`},int:(e,t,r)=>{const[n,o,s,a]=t.args,i=t.args.length>=2&&(e=>"symbol"===e.type&&1===e.value.length&&/[a-zA-Zʹ-Ͽ]/.test(e.value))(o),l=i?r(o):zr(n)||"x";let c=[];return 4===t.args.length?c=[s,a]:3===t.args.length?c=i?[s]:[o,s]:2!==t.args.length||i||(c=[o]),c=c.map(r),c.length?`sympy.integrate(${r(n)}, (${l}, ${c[0]}, ${c[1]??"sympy.oo"}))`:`sympy.integrate(${r(n)}, ${l})`},lim:(e,t,r)=>{const[n,o]=t.args,s="op"===o?.type&&"→"===o.op;if(t.args.length<2)throw new Error("A limit needs a point: lim(f, x → a)");const[a,i]=s?o.args.map(r):2===t.args.length?[zr(n)||"x",e[1]]:[e[1],e[2]],l="symbol"===t.args[3]?.type?gs[t.args[3].value]??"":"";return`sympy.limit(${e[0]}, ${a}, ${i}${l})`},"\\sumidx":(e,t,r)=>ss("summation",t,r),"\\prodidx":(e,t,r)=>ss("product",t,r)}};function ss(e,t,r){const[n,o,s]=t.args;return t.args.length<3||"op"!==o.type||"="!==o.op||"symbol"!==o.args[0].type?null:`sympy.${e}(${r(n)}, (${r(o.args[0])}, ${r(o.args[1])}, ${r(s)}))`}const as={javascript:Go,python:Wo,numpy:Jo,sympy:os},is={sqrt:"sqrt",floor:"floor",ceil:"ceil",ln:"log",expm1:"expm1",sin:"sin",cos:"cos",tan:"tan",sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsin:"asin",arccos:"acos",arctan:"atan",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",atan2:"atan2"},ls={csc:"sin",sec:"cos",cot:"tan"},cs=e=>/^\d+(\.\d+)?$/.test(e),us=e=>e.length<=16&&!/[\w.$]\s*\(/.test(e),ps=(e,t,r)=>/[A-Za-z_]/.test(e)?`(${t} if abs(${r}) < math.inf else ${r})`:t,hs=(e,t)=>us(e)?t(ms(e)?e:`(${e})`):`(lambda _v: ${t("_v")})(${e})`,fs=e=>ms(e)?e:`(${e})`;function ms(e){if(/^[\w.]+$/.test(e))return!0;const t=/^[\w.$]+\(/.exec(e);if(!t)return!1;for(let r=t[0].length-1,n=0;r<e.length;r++)if("("===e[r])n++;else if(")"===e[r]&&0===--n)return r===e.length-1;return!1}const gs={r:', "+"',l:', "-"'},ds=new Set(["<",">","≤","≥","=","===","≠","≠=","∈","∉"]),$s={"ℝ":{javascript:e=>`Number.isFinite(${e})`,python:e=>`math.isfinite(${e})`,numpy:e=>`np.isfinite(${e})`},"ℤ":{javascript:e=>`Number.isInteger(${e})`,python:e=>`float(${e}).is_integer()`,numpy:e=>`(np.mod(${e}, 1) == 0)`},"ℕ":{javascript:e=>`(Number.isInteger(${e}) && ${e} > 0)`,python:e=>`(float(${e}).is_integer() and ${e} > 0)`,numpy:e=>`np.logical_and(np.mod(${e}, 1) == 0, ${e} > 0)`}},ys={"ℚ":"a number in code is a double, always a fraction, so whether it is rational can't be told ({ sympy: true } can)","ℂ":"a number in code is never complex"};for(const e of[Go,Wo,Ho,Vo,Jo,es,ts,os,as,is,ls,$s,ys,gs])Object.setPrototypeOf(e,null);const bs=e=>t=>`<mover accent="true">${t}<mo>${e}</mo></mover>`,ws={boxed:e=>`<menclose notation="box">${e}</menclose>`,cancel:e=>`<menclose notation="updiagonalstrike">${e}</menclose>`,overline:bs("¯"),bar:bs("¯"),underline:e=>`<munder accentunder="true">${e}<mo>_</mo></munder>`,vec:bs("→"),hat:bs("^"),widehat:bs("^"),tilde:bs("~"),dot:bs("˙"),ddot:bs("¨")};Object.setPrototypeOf(ws,null);const xs={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"&lt;",">":"&gt;","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","±":"±",mod:"mod","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓","\\implies":"⇒","\\iff":"⇔"},vs={sin:"sin",cos:"cos",tan:"tan",csc:"csc",sec:"sec",cot:"cot",sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsin:"arcsin",arccos:"arccos",arctan:"arctan",arcsec:"arcsec",arccsc:"arccsc",arccot:"arccot",arcsinh:"arcsinh",arccosh:"arccosh",arctanh:"arctanh",atan2:"atan2",ln:"ln",max:"max",min:"min",gcd:"gcd",det:"det",mean:"mean",round:"round",fixed:"fixed",random:"random"},_s={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};for(const e of[xs,vs,_s])Object.setPrototypeOf(e,null);const As={pi:"PI()","π":"PI()",e:"EXP(1)",tau:"(2 * PI())","τ":"(2 * PI())","∞":"'Infinity'","-∞":"'-Infinity'",true:"TRUE",false:"FALSE",null:"NULL"},Es={...As,"∞":"9e999","-∞":"-9e999",tau:"(2 * PI())","τ":"(2 * PI())"},zs={sqrt:"SQRT",abs:"ABS",floor:"FLOOR",ceil:"CEIL",ln:"LN",sin:"SIN",cos:"COS",tan:"TAN",cot:"COT",sinh:"SINH",cosh:"COSH",tanh:"TANH",arcsin:"ASIN",arccos:"ACOS",arctan:"ATAN",arcsinh:"ASINH",arccosh:"ACOSH",arctanh:"ATANH",atan2:"ATAN2",max:"GREATEST",min:"LEAST",gcd:"GCD",random:"RANDOM","!":"FACTORIAL"},Ms={der:"a derivative",int:"an integral",lim:"a limit","\\sumidx":"a sum to n","\\prodidx":"a product to n","∪":"a union of sets","∩":"an intersection of sets"},ks={"+":"+","-":"-","*":"*","/":"/","=":"=","===":"=","≠":"<>","≠=":"<>","<":"<",">":">","≤":"<=","≥":">="},Os={"()":["(",")"],"{}":["(",")"],"[]":["ARRAY[","]"],"(]":["(",")"],"[)":["(",")"]},js={"!":"a factorial",gcd:"gcd",perm:"permutations (perm)",comb:"combinations (comb)","±":"±",pm:"±",_:"an index into a list","→":"→",pmatrix:"a matrix",bmatrix:"a matrix",vmatrix:"a determinant",det:"a determinant"},Ss={max:"MAX",min:"MIN"},Ns={csc:"SIN",sec:"COS",cot:"TAN"},Is={"ℝ":e=>`(ABS(${e}) < 'Infinity')`,"ℤ":e=>`(${e} = TRUNC(${e}))`,"ℕ":e=>`(${e} = TRUNC(${e}) AND ${e} > 0)`};for(const e of[As,Es,zs,ks,Os,Ss,Ns,Is,Ms,js])Object.setPrototypeOf(e,null);const Ts={pi:"PI()","π":"PI()",e:"EXP(1)",tau:"(2*PI())","τ":"(2*PI())","°":"(PI()/180)",true:"TRUE",false:"FALSE"},Rs={sqrt:"SQRT",abs:"ABS",floor:"INT",ln:"LN",det:"MDETERM",sin:"SIN",cos:"COS",tan:"TAN",sinh:"SINH",cosh:"COSH",tanh:"TANH",arcsin:"ASIN",arccos:"ACOS",arctan:"ATAN",arcsinh:"ASINH",arccosh:"ACOSH",arctanh:"ATANH",round:"ROUND",fixed:"FIXED",perm:"PERMUT",comb:"COMBIN",gcd:"GCD","!":"FACT","\\not":"NOT","&":"AND","|":"OR"},Fs={csc:"SIN",sec:"COS",cot:"TAN"},Cs={"=":"=","===":"=","≡":"=","≠":"<>","≠=":"<>","<":"<",">":">","≤":"<=","≥":">="},qs={sum:"SUM",prod:"PRODUCT",mean:"AVERAGE",max:"MAX",min:"MIN","\\:median":"MEDIAN","\\:stdev":"STDEVP","\\:count":"COUNT"},Ls={der:"a derivative",int:"an integral",lim:"a limit","\\sumidx":"a sum to n","\\prodidx":"a product to n",pm:"±","±":"±","∪":"∪","∩":"∩","→":"→"};for(const e of[Ts,Rs,Fs,Cs,qs,Ls])Object.setPrototypeOf(e,null);const Ps={data:new Float32Array([1,1,1,1]),width:1,height:1},Us={data:new Float32Array([0,0,0,0]),width:1,height:1},Bs={cover:0,fit:1,stretch:2,tile:3};function Ds(e){return Bs[e??"cover"]??0}function Zs(e,t){return e-t*Math.floor(e/t)}const Gs=(e,t)=>e<0?0:e>t?t:e;function Ws(e,t,r,n,o,s){const a=Math.floor(n),i=Math.floor(o),l=n-a,c=o-i,u=Gs(a,t-1),p=Gs(a+1,t-1),h=Gs(i,r-1),f=Gs(i+1,r-1),m=4*(h*t+u),g=4*(h*t+p),d=4*(f*t+u),$=4*(f*t+p);for(let t=0;t<4;t++){const r=e[m+t]+(e[g+t]-e[m+t])*l,n=e[d+t]+(e[$+t]-e[d+t])*l;s[t]=r+(n-r)*c}return s}function Hs(e,t,r){const n=Math.min(Math.max(Math.ceil(e),0),t),o=[];for(let e=-n;e<=n;e++)r(e)&&o.push(e);return o}function Xs(e,t,r,n,o,s,a,i,l=0,c=n){const u=new Float32Array(r*n*3),p=s.length,h=Int32Array.from(s),f=Float64Array.from(a??s.map(()=>1)),m="x"===o?r:n,g=new Int32Array(p);for(let n=l;n<c;n++)for(let s=0;s<r;s++){const a="x"===o?s:n;for(let e=0;e<p;e++){let i=a+h[e];i=i<0?0:i>=m?m-1:i,g[e]=("x"===o?n*r+i:i*r+s)*t}let l=0,c=0,d=0;for(let t=0;t<p;t++){const r=g[t],n=f[t];l+=e[r]*n,c+=e[r+1]*n,d+=e[r+2]*n}const $=3*(n*r+s);u[$]=l/i,u[$+1]=c/i,u[$+2]=d/i}return u}function Vs(e,t,r,n,o,s,a,i=0,l=n){const c=new Float32Array(r*n*3),u="x"===o?r:n,p="x"===o?n:r,h=a-s+1,f=(e,t)=>"x"===o?e*r+t:t*r+e,m=e=>e<0?0:e>=u?u-1:e,[g,d]="x"===o?[i,l]:[0,p],[$,y]="x"===o?[0,u]:[i,l];for(let r=g;r<d;r++){let n=0,o=0,i=0;for(let l=$+s;l<=$+a;l++){const s=f(r,m(l))*t;n+=e[s],o+=e[s+1],i+=e[s+2]}for(let l=$;l<y;l++){const u=3*f(r,l);c[u]=n/h,c[u+1]=o/h,c[u+2]=i/h;const p=f(r,m(l+s))*t,g=f(r,m(l+a+1))*t;n+=e[g]-e[p],o+=e[g+1]-e[p+1],i+=e[g+2]-e[p+2]}}return c}function Ys(e,t,r,n,o,s,a,i,l=0,c=n){const u=new Float32Array(r*n*3),p="x"===o?r:n;for(let n=l;n<c;n++)for(let l=0;l<r;l++){const c="x"===o?l:n;let h=a,f=a,m=a;for(let a=0;a<s.length;a++){let u=c+s[a];u=u<0?0:u>=p?p-1:u;const g=("x"===o?n*r+u:u*r+l)*t;i?(e[g]>h&&(h=e[g]),e[g+1]>f&&(f=e[g+1]),e[g+2]>m&&(m=e[g+2])):(e[g]<h&&(h=e[g]),e[g+1]<f&&(f=e[g+1]),e[g+2]<m&&(m=e[g+2]))}const g=3*(n*r+l);u[g]=h,u[g+1]=f,u[g+2]=m}return u}const Js=(e,t,r)=>e+t*r,Ks=(e,t)=>t>e?t:e,Qs=(e,t)=>t<e?t:e;function ea(e,t,r,n=0,o=r){const s=new Float32Array(t*r*3);for(let r=n*t;r<o*t;r++)s[3*r]=e[4*r],s[3*r+1]=e[4*r+1],s[3*r+2]=e[4*r+2];return s}const ta=(e,t,r,n)=>[Math.max(0,e-r),Math.min(n,t+r)];function ra(e,t,r,n,o,s,a,i){const l=Hs(s,i,e=>Math.abs(e)<=s);if(!l.length)return ea(e,t,r,n,o);const c=l[0],u=l[l.length-1];if(1===a.length)return Vs(e,4,t,r,a[0],c,u,n,o);const[p,h]=ta(n,o,u,r);return Vs(Vs(e,4,t,r,"x",c,u,p,h),3,t,r,"y",c,u,n,o)}function na(e,t,r,n,o,s,a,i){if(!(s>0))return ea(e,t,r,n,o);const l=3*s,c=Hs(l,i,e=>Math.abs(e)<=l),u=c.map(e=>Math.exp(-e*e/(2*s*s))),p=u.reduce((e,t)=>e+t,0);if(1===a.length)return Xs(e,4,t,r,a[0],c,u,p,n,o);const[h,f]=ta(n,o,c[c.length-1],r);return Xs(Xs(e,4,t,r,"x",c,u,p,h,f),3,t,r,"y",c,u,p,n,o)}function oa(e,t,r,n,o,s,a,i){const l=Hs(s,En.square,e=>Math.abs(e)<=s);if(!l.length)return new Float32Array(t*r*3).fill(a);const[c,u]=ta(n,o,l[l.length-1],r);return Ys(Ys(e,4,t,r,"x",l,a,i,c,u),3,t,r,"y",l,a,i,n,o)}function sa(e,t,r,n,o,s){const a=function(e,t,r){const n=new Float32Array(t*r);for(let o=0;o<t*r;o++)n[o]=.299*e[4*o]+.587*e[4*o+1]+.114*e[4*o+2];return n}(e,t,r),i=new Float32Array(t*r);for(let e=n;e<o;e++)for(let n=0;n<t;n++){const o=(o,s)=>a[Gs(e+s,r-1)*t+Gs(n+o,t-1)];i[e*t+n]=s(o)}return i}const aa=e=>e(1,-1)+2*e(1,0)+e(1,1)-(e(-1,-1)+2*e(-1,0)+e(-1,1)),ia=e=>e(-1,1)+2*e(0,1)+e(1,1)-(e(-1,-1)+2*e(0,-1)+e(1,-1)),la=e=>4*e(0,0)-e(-1,0)-e(1,0)-e(0,-1)-e(0,1),ca=e=>.5+e(-1,-1)-e(1,1),ua=e=>Math.hypot(aa(e),ia(e));function pa(e,t,r,n,o,s,a,i,l,c,u){for(let p=0;p<3;p++){let h=i,f=0;for(const i of s)for(const c of s){const s=a?a(i,c):1;h=l(h,e[4*(Gs(o+c,r-1)*t+Gs(n+i,t-1))+p],s),f+=s}c[p]=u?u(h,f):h}return c}function ha(e,t,r,n,o,s,a,i,l){for(let c=0;c<3;c++){let u=0,p=0;for(const l of a){const a=i?i(l):1,h="x"===s?Gs(n+l,t-1):n;u+=e[4*(("y"===s?Gs(o+l,r-1):o)*t+h)+c]*a,p+=a}l[c]=u/p}return l}const fa=(e,t,r,n,o)=>{const s=4*(n*t+r);return o[0]=e[s],o[1]=e[s+1],o[2]=e[s+2],o};const ma=e=>e<.04045?e/12.92:Math.pow((e+.055)/1.055,2.4),ga=e=>(e=Math.max(e,0))<.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055,da=(e,t,r,n,o)=>{const s=n===e?(t-r)/o:n===t?2+(r-e)/o:4+(e-t)/o;return s/6-Math.floor(s/6)},$a=(e,t)=>{const r=Math.abs(6*(e+t-Math.floor(e+t))-3);return Math.min(Math.max(r-1,0),1)};const ya=e=>e<.008856?7.787*e+16/116:Math.cbrt(e),ba=e=>e<.206893?(e-16/116)/7.787:e*e*e;var wa=Object.freeze({__proto__:null,BLANK:Ps,CLEAR:Us,at:function(e,t,r){return Number(e[t][r])},at_blur:function(e,t,r,n,o,s,a){return pa(e,t,r,n,o,Hs(s,En.square,e=>Math.abs(e)<=s),null,0,Js,a,(e,t)=>e/t)},at_blurx:function(e,t,r,n,o,s,a){return ha(e,t,r,n,o,"x",Hs(s,En.line,e=>Math.abs(e)<=s),null,a)},at_blury:function(e,t,r,n,o,s,a){return ha(e,t,r,n,o,"y",Hs(s,En.line,e=>Math.abs(e)<=s),null,a)},at_dilate:function(e,t,r,n,o,s,a){return pa(e,t,r,n,o,Hs(s,En.square,e=>Math.abs(e)<=s),null,0,Ks,a)},at_erode:function(e,t,r,n,o,s,a){return pa(e,t,r,n,o,Hs(s,En.square,e=>Math.abs(e)<=s),null,1,Qs,a)},at_gaussian:function(e,t,r,n,o,s,a){if(!(s>0))return fa(e,t,n,o,a);const i=3*s;return pa(e,t,r,n,o,Hs(i,En.square,e=>Math.abs(e)<=i),(e,t)=>Math.exp(-(e*e+t*t)/(2*s*s)),0,Js,a,(e,t)=>e/t)},at_gaussianx:function(e,t,r,n,o,s,a){if(!(s>0))return fa(e,t,n,o,a);const i=3*s;return ha(e,t,r,n,o,"x",Hs(i,En.line,e=>Math.abs(e)<=i),e=>Math.exp(-e*e/(2*s*s)),a)},at_gaussiany:function(e,t,r,n,o,s,a){if(!(s>0))return fa(e,t,n,o,a);const i=3*s;return ha(e,t,r,n,o,"y",Hs(i,En.line,e=>Math.abs(e)<=i),e=>Math.exp(-e*e/(2*s*s)),a)},at_sharpen:function(e,t,r,n,o,s,a){const i=(e,n)=>4*(Gs(n,r-1)*t+Gs(e,t-1)),l=i(n,o),c=i(n-1,o),u=i(n+1,o),p=i(n,o-1),h=i(n,o+1);for(let t=0;t<3;t++)a[t]=e[l+t]+s*(4*e[l+t]-e[c+t]-e[u+t]-e[p+t]-e[h+t]);return a},col_fromhsl:function(e,t,r,n){const o=(1-Math.abs(2*r-1))*t;return n[0]=r-.5*o+o*$a(e,0),n[1]=r-.5*o+o*$a(e,2/3),n[2]=r-.5*o+o*$a(e,1/3),n},col_fromhsv:function(e,t,r,n){return n[0]=r*(1+($a(e,0)-1)*t),n[1]=r*(1+($a(e,2/3)-1)*t),n[2]=r*(1+($a(e,1/3)-1)*t),n},col_fromlab:function(e,t,r,n){const o=(100*e+16)/116,s=o-256*(r-.5)/200,a=.95047*ba(o+256*(t-.5)/500),i=ba(o),l=1.08883*ba(s),c=Math.min(Math.max(3.2404542*a-1.5371385*i-.4985314*l,0),1),u=Math.min(Math.max(-.969266*a+1.8760108*i+.041556*l,0),1),p=Math.min(Math.max(.0556434*a-.2040259*i+1.0572252*l,0),1);return n[0]=ga(c),n[1]=ga(u),n[2]=ga(p),n},col_fromlinear:function(e,t,r,n){return n[0]=ga(e),n[1]=ga(t),n[2]=ga(r),n},col_fromoklab:function(e,t,r,n){let o=e+.3963377774*(t-=.5)+.2158037573*(r-=.5),s=e-.1055613458*t-.0638541728*r,a=e-.0894841775*t-1.291485548*r;o*=o*o,s*=s*s,a*=a*a;const i=Math.min(Math.max(4.0767416621*o-3.3077115913*s+.2309699292*a,0),1),l=Math.min(Math.max(-1.2684380046*o+2.6097574011*s-.3413193965*a,0),1),c=Math.min(Math.max(-.0041960863*o-.7034186147*s+1.707614701*a,0),1);return n[0]=ga(i),n[1]=ga(l),n[2]=ga(c),n},col_fromycbcr:function(e,t,r,n){return t-=.5,r-=.5,n[0]=e+1.402*r,n[1]=e-.344136*t-.714136*r,n[2]=e+1.772*t,n},col_tohsl:function(e,t,r,n){const o=Math.max(e,t,r),s=Math.min(e,t,r),a=o-s,i=.5*(o+s);return n[0]=a>0?da(e,t,r,o,a):0,n[1]=a>0?a/(1-Math.abs(2*i-1)):0,n[2]=i,n},col_tohsv:function(e,t,r,n){const o=Math.max(e,t,r),s=o-Math.min(e,t,r);return n[0]=s>0?da(e,t,r,o,s):0,n[1]=o>0?s/o:0,n[2]=o,n},col_tolab:function(e,t,r,n){const o=ma(e),s=ma(t),a=ma(r),i=ya((.4124564*o+.3575761*s+.1804375*a)/.95047),l=ya(.2126729*o+.7151522*s+.072175*a),c=ya((.0193339*o+.119192*s+.9503041*a)/1.08883);return n[0]=(116*l-16)/100,n[1]=.5+500*(i-l)/256,n[2]=.5+200*(l-c)/256,n},col_tolinear:function(e,t,r,n){return n[0]=ma(e),n[1]=ma(t),n[2]=ma(r),n},col_tooklab:function(e,t,r,n){const o=ma(e),s=ma(t),a=ma(r),i=Math.cbrt(.4122214708*o+.5363325363*s+.0514459929*a),l=Math.cbrt(.2119034982*o+.6806995451*s+.1073969566*a),c=Math.cbrt(.0883024619*o+.2817188376*s+.6299787005*a);return n[0]=.2104542553*i+.793617785*l-.0040720468*c,n[1]=.5+1.9779984951*i-2.428592205*l+.4505937099*c,n[2]=.5+.0259040371*i+.7827717662*l-.808675766*c,n},col_toycbcr:function(e,t,r,n){const o=.299*e+.587*t+.114*r;return n[0]=o,n[1]=.5+.5643*(r-o),n[2]=.5+.7132*(e-o),n},convolve:function(e,t,r,n,o,s,a,i,l,c,u,p,h,f,m){const g=(e,s)=>4*(Gs(o+s,r-1)*t+Gs(n+e,t-1)),d=[[s,-1,-1],[a,0,-1],[i,1,-1],[l,-1,0],[c,0,0],[u,1,0],[p,-1,1],[h,0,1],[f,1,1]];for(let t=0;t<3;t++){let r=0;for(const[n,o,s]of d)r+=n*e[g(o,s)+t];m[t]=r}return m},factorial:function(e){let t=1;for(let r=2;r<=170&&!(r>e);r++)t*=r;return t},fmod:Zs,gcd:function(e,t){e=Math.abs(e),t=Math.abs(t);for(let r=0;r<64&&0!==t;r++){const r=Zs(e,t);e=t,t=r}return e},perm:function(e,t){let r=1;for(let n=0;n<170&&!(n>=t);n++)r*=e-n;return r},picture:function(e,t,r,n,o,s,a,i,l,c,u,p,h){let f,m;0===c?f=m=Math.max(n/t,o/r):1===c?f=m=Math.min(n/t,o/r):2===c?(f=n/t,m=o/r):f=m=1,f*=s,m*=s;const g=u+.5-a*n,d=p+.5-i*o,$=Math.cos(l),y=Math.sin(l);let b=($*g+y*d)/f+.5*t,w=($*d-y*g)/m+.5*r;if(3===c)b=Zs(b,t),w=Zs(w,r);else if(b<0||w<0||b>t||w>r)return h[0]=h[1]=h[2]=h[3]=0,h;return Ws(e,t,r,b-.5,w-.5,h)},placeCode:Ds,plane_blur:function(e,t,r,n,o,s){return ra(e,t,r,n,o,s,["x","y"],En.square)},plane_blurx:function(e,t,r,n,o,s){return ra(e,t,r,n,o,s,["x"],En.line)},plane_blury:function(e,t,r,n,o,s){return ra(e,t,r,n,o,s,["y"],En.line)},plane_dilate:function(e,t,r,n,o,s){return oa(e,t,r,n,o,s,0,!0)},plane_emboss:function(e,t,r,n,o){return sa(e,t,r,n,o,ca)},plane_erode:function(e,t,r,n,o,s){return oa(e,t,r,n,o,s,1,!1)},plane_gaussian:function(e,t,r,n,o,s){return na(e,t,r,n,o,s,["x","y"],En.square)},plane_gaussianx:function(e,t,r,n,o,s){return na(e,t,r,n,o,s,["x"],En.line)},plane_gaussiany:function(e,t,r,n,o,s){return na(e,t,r,n,o,s,["y"],En.line)},plane_laplacian:function(e,t,r,n,o){return sa(e,t,r,n,o,la)},plane_sharpen:function(e,t,r,n,o,s){const a=new Float32Array(t*r*3);for(let i=n;i<o;i++)for(let n=0;n<t;n++){const o=(e,n)=>4*(Gs(n,r-1)*t+Gs(e,t-1)),l=o(n,i),c=o(n-1,i),u=o(n+1,i),p=o(n,i-1),h=o(n,i+1);for(let r=0;r<3;r++)a[3*(i*t+n)+r]=e[l+r]+s*(4*e[l+r]-e[c+r]-e[u+r]-e[p+r]-e[h+r])}return a},plane_sobel:function(e,t,r,n,o){return sa(e,t,r,n,o,ua)},plane_sobelx:function(e,t,r,n,o){return sa(e,t,r,n,o,aa)},plane_sobely:function(e,t,r,n,o){return sa(e,t,r,n,o,ia)},random:function(e,t,r,n){const o=43758.5453*Math.sin(12.9898*(e+.5)+78.233*(r-t-.5)+37.719*n);return o-Math.floor(o)},root:function(e,t){return 2===e?Math.sqrt(t):3===e?Math.sign(t)*Math.pow(Math.abs(t),1/3):Math.pow(t,1/e)},round:function(e,t){const r=Math.pow(10,t);return Math.sign(e)*Math.floor(Math.abs(e)*r+.5)/r},sample:Ws,sampleOrZero:function(e,t,r,n,o,s){const a=n+.5,i=o+.5;return a<0||i<0||a>t||i>r?(s[0]=s[1]=s[2]=s[3]=0,s):Ws(e,t,r,n,o,s)},scratch:function(){return new Float64Array(4)},smoothstep:function(e,t,r){const n=Math.min(Math.max((r-e)/(t-e),0),1);return n*n*(3-2*n)}});const xa="\\:",va=Object.keys(wa).filter(e=>"function"==typeof wa[e]),_a=e=>Object.assign(Object.create(null),e),Aa=_a({r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"}),Ea=_a({pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)","°":"(Math.PI / 180)"}),za=_a({sqrt:1,abs:1,floor:1,ceil:1,ln:"log",sin:1,cos:1,tan:1,arcsin:"asin",arccos:"acos",arctan:"atan",sinh:1,cosh:1,tanh:1,arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",sign:1,exp:1,exp2:e=>`Math.pow(2, ${e})`,log2:1,expm1:e=>`(Math.exp(${e}) - 1)`,loglog:e=>`Math.log(Math.log(${e}))`,logloglog:e=>`Math.log(Math.log(Math.log(${e})))`,csc:e=>`(1 / Math.sin(${e}))`,sec:e=>`(1 / Math.cos(${e}))`,cot:e=>`(1 / Math.tan(${e}))`,fract:e=>`(${e} - Math.floor(${e}))`,radians:e=>`(${e} * 0.017453292519943295)`,degrees:e=>`(${e} * 57.29577951308232)`,inversesqrt:e=>`(1 / Math.sqrt(${e}))`,arcsec:e=>`Math.acos(1 / ${e})`,arccsc:e=>`Math.asin(1 / ${e})`,arccot:e=>`(Math.PI / 2 - Math.atan(${e}))`,atan2:(e,t)=>`Math.atan2(${e}, ${t})`,pow:(e,t)=>`Math.pow(${e}, ${t})`,mod:(e,t)=>`(${e} - ${t} * Math.floor(${e} / ${t}))`,step:(e,t)=>`(${t} < ${e} ? 0 : 1)`,clamp:(e,t,r)=>`Math.min(Math.max(${e}, ${t}), ${r})`,mix:(e,t,r)=>`(${e} + (${t} - ${e}) * ${r})`,smoothstep:(e,t,r)=>`$h_smoothstep(${e}, ${t}, ${r})`}),Ma=_a({atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3});const ka=_a({blur:3,blurx:3,blury:3,gaussian:3,gaussianx:3,gaussiany:3,dilate:3,erode:3,sharpen:3,sobel:1,sobelx:1,sobely:1,laplacian:1,emboss:1}),Oa=(e,t)=>({kind:e,c:t}),ja=e=>Oa("f",[e]),Sa=e=>Oa("b",[e]),Na=e=>1===e.length?ja(e[0]):Oa("v",e),Ia=(e,t=0)=>"b"===e.kind?`(${e.c[0]} ? 1 : 0)`:"f"===e.kind?e.c[0]:e.c[t]??e.c[0],Ta=e=>"v"===e.kind?e.c.length:1;class Ra extends Error{}function Fa(e){if(e.blendKept)return{blend:!0,source:""};const t=e.params??{},r=new Set([...Object.keys(e.placements??{}),"source","selection"]),n=new Ca(t,r,e.space??"srgb");n.graphics=new Set(Object.keys(e.graphics??{})),n.bind=_a(e.bind??{});const o="string"==typeof e.color?{rgba:e.color}:e.color,s=(n,o)=>vn(Pr(n,{names:[...gn,...Object.keys(e.placements??{})],values:[...un,...Object.keys(t)],blocks:null}),r,{whole:o});for(const e of["rgba","rgb","r","g","b","a"]){if(!o[e])continue;let t;try{t=s(o[e],"rgba"===e)}catch(e){throw new Ra(e.message)}n.channel(e,t)}const a=n.source();!function(e,t={}){if("string"!=typeof e)throw new Fo("generated code must be a string");const r=e;for(const t of Bo)e=e.split(t).join("Math.abs");const n=!1!==t.keywords,o=t.variables instanceof RegExp?t.variables:new Set(t.variables??[]),s=e=>o instanceof RegExp?o.test(e):o.has(e),a=t.indexable instanceof RegExp?t.indexable:null;let i=null,l=0;const c=e=>{throw new Fo(`not allowed in a formula: ${e}`)},u=()=>i&&("id"===i.type||"num"===i.type||"str"===i.type||"p"===i.type&&(")"===i.value||"]"===i.value||"}"===i.value));for(;l<e.length;){const r=e.slice(l),o=/^\s+/.exec(r);if(o){l+=o[0].length;continue}(r.startsWith("/*")||r.startsWith("//")||r.startsWith("\x3c!--")||r.startsWith("--\x3e"))&&c("a comment");const p=/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(r);if(p&&(!i||"id"!==i.type||!/[\w$]$/.test(e[l-1]??""))){i={type:"num",value:p[0]},l+=p[0].length;continue}if('"'===r[0]){!1===t.strings&&c("a string");const e=/^"(?:[^"\\\n\r\u2028\u2029]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/.exec(r);e||c('a string that is not a plain "…" literal'),u()&&c("a string right after a value"),i={type:"str",value:e[0]},l+=e[0].length;continue}const h=/^[A-Za-z_$][\w$]*/.exec(r);if(h){const e=h[0];if(i&&"p"===i.type&&"."===i.value){const t=i.owner;(t&&Lo[t]?Lo[t].has(e):qo.has(e)&&!Co.has(e))||c(`.${e}`)}else Po.has(e)||n&&Uo.has(e)||s(e)||c(`the name "${e}"`);i={type:"id",value:e,member:Boolean(i&&"p"===i.type&&"."===i.value)},l+=e.length;continue}const f=Do.find(e=>r.startsWith(e));f||c(`"${r[0]}"`),Zo.has(f)&&(n||c(`an assignment ("${f}")`),i&&"id"===i.type&&i.member&&c(`an assignment to .${i.value}`)),"["!==f||!u()||a&&"id"===i.type&&s(i.value)&&a.test(i.value)||c("indexing with [ ]");const m={type:"p",value:f};"."===f&&(u()||c('a "." here'),m.owner="id"===i.type&&Lo[i.value]?i.value:null),i=m,l+=f.length}}(a,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const i=new Function(...n.parameters(),a);return{source:a,uses:n.uses,pictures:[...n.pictureNames],run(e){i(...n.arguments(e))}}}class Ca{constructor(e,t,r="srgb"){this.params=e,this.pictures=t,this.space="srgb"===r?null:r,this.pre=[],this.body=[],this.n=0,this.uses=new Set,this.pictureNames=new Set,this.perPixel=new Map,this.planes=new Map,this.scratch=0}temp(e,t=this.body){const r="$v"+this.n++;return t.push(`let ${r} = ${e};`),r}keep(e,t=this.body){return Oa(e.kind,e.c.map(e=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(e)?e:this.temp(e,t)))}fail(e){throw new Ra(e)}leaf(e){if("number"===e.type)return ja(`(${e.value.replace(/\.+$/,"")})`);"string"===e.type&&this.fail("a filter has no text: numbers and colors only");const t=e.value,r=/^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(t);if(r)return ja(`(${r[1]} / 100)`);if("t"===t&&this.uses.add("t"),Aa[t])return ja(Aa[t]);if("rgb"===t)return Na(["$r","$g","$b"]);if("unchanged"===t)return ja("$u");if("selected"===t)return ja(this.pictureHere("selection").c[0]);if("away"===t){const[e,t]=this.pictureHere("away").c;return ja(`(${e} > 0 ? 255 * (1 - ${e}) : 1020 * (1 - ${t}))`)}if(Ea[t])return ja(Ea[t]);if("true"===t||"false"===t)return Sa(t);if(Object.prototype.hasOwnProperty.call(this.params,t)){const e=`$p_${t}`;return"color"===this.params[t].type?Na([`${e}_0`,`${e}_1`,`${e}_2`]):ja(e)}if(this.pictures.has(t)){const e=this.pictureHere(t);return Na(e.c.slice(0,3))}if(t.startsWith("mz_px_")&&this.pictures.has(t.slice(6)))return this.pictureHere(t.slice(6));this.fail(`unknown name "${t}"`)}pictureHere(e){if(!this.perPixel.has(e)){const t=this.sampler(e,"$px","$py");this.perPixel.set(e,this.keep(t))}return this.perPixel.get(e)}sampler(e,t,r){const n=this.scratchArray();return"source"===e?(this.uses.add("source"),this.body.push(`$h_sample($S, $w, $h, ${t}, ${r}, ${n});`)):(this.pictureNames.add(e),this.body.push(`$h_picture($Q_${e}, $qw_${e}, $qh_${e}, $w, $h, $qz_${e}, $qx_${e}, $qy_${e}, $qa_${e}, $qm_${e}, ${t}, ${r}, ${n});`)),this.space&&"selection"!==e&&"away"!==e&&this.body.push(`$h_col_to${this.space}(${n}[0], ${n}[1], ${n}[2], ${n});`),Na([0,1,2,3].map(e=>`${n}[${e}]`))}scratchArray(){const e="$T"+this.scratch++;return this.pre.push(`let ${e} = $h_scratch();`),e}value(e){return"op"===e.type?this.op(e):this.leaf(e)}op(e){const{op:t,args:r}=e,n=t.startsWith(xa)?t.slice(2):null;if(null!==n)return this.call(n,r,e);const o=()=>r.map(e=>this.value(e));switch(t){case"+":case"-":case"*":case"/":{const[e,r]=o();return this.componentwise([e,r],(e,r)=>`(${e} ${t} ${r})`)}case"neg":return this.componentwise(o(),e=>`(-${e})`);case"^":return this.power(r);case"mod":return this.componentwise(o(),za.mod);case"<":case">":case"≤":case"≥":{const[e,r]=o(),n={"≤":"<=","≥":">="}[t]??t;return Sa(`(${Ia(e)} ${n} ${Ia(r)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[e,r]=o(),n=Math.max(Ta(e),Ta(r)),s=Array.from({length:n},(t,n)=>`${Ia(e,n)} === ${Ia(r,n)}`).join(" && ");return Sa("≠"===t||"≠="===t?`!(${s})`:`(${s})`)}case"≈":{const[e,t]=o();return Sa(`(Math.abs(${Ia(e)} - ${Ia(t)}) < 1e-5)`)}case"&":{const[e,t]=o();return Sa(`(${this.truth(e)} && ${this.truth(t)})`)}case"|":{const[e,t]=o();return Sa(`(${this.truth(e)} || ${this.truth(t)})`)}case"\\xor":{const[e,t]=o();return Sa(`(${this.truth(e)} !== ${this.truth(t)})`)}case"\\nand":{const[e,t]=o();return Sa(`!(${this.truth(e)} && ${this.truth(t)})`)}case"\\nor":{const[e,t]=o();return Sa(`!(${this.truth(e)} || ${this.truth(t)})`)}case"\\implies":{const[e,t]=o();return Sa(`(!${this.truth(e)} || ${this.truth(t)})`)}case"\\iff":{const[e,t]=o();return Sa(`(${this.truth(e)} === ${this.truth(t)})`)}case"\\not":{const[e]=o();return Sa(`!${this.truth(e)}`)}case"?:":return this.ternary(r);case"max":case"min":return this.componentwise(o(),(...e)=>`Math.${t}(${e.join(", ")})`);case"sum":return this.componentwise(o(),(...e)=>`(${e.join(" + ")})`);case"prod":return this.componentwise(o(),(...e)=>`(${e.join(" * ")})`);case"mean":return this.componentwise(o(),(...e)=>`((${e.join(" + ")}) / ${e.length})`);case"()":case"[]":case"{}":case"(]":case"[)":{const e=o().flatMap(e=>"b"===e.kind?[Ia(e)]:e.c.map((t,r)=>Ia(e,r)));return e.length>4&&this.fail("a color has at most 4 values (r, g, b, a)"),Na(e)}case"!":return this.componentwise(o(),e=>`$h_factorial(${e})`);case"perm":return this.componentwise(o(),(e,t)=>`$h_perm(${e}, ${t})`);case"comb":return this.componentwise(o(),(e,t)=>`($h_perm(${e}, ${t}) / $h_factorial(${t}))`);case"gcd":return this.componentwise(o(),(...e)=>e.reduce((e,t)=>`$h_gcd(${e}, ${t})`));case"round":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`$h_round(${e}, ${t})`)}case"log":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`(Math.log(${t}) / Math.log(${e}))`)}case"root":{const[e,t]=o();return this.componentwise([e,t],(e,t)=>`$h_root(${e}, ${t})`)}case"∈":case"∉":{const t=function(e){const[t,r]=e.args;if("op"!==r.type||"setbuilder"!==r.op)return null;let[n,o]=r.args,s=null;"op"===n.type&&"∈"===n.op&&([n,s]=n.args);const a=e=>"symbol"===e.type&&e.value===n.value?t:"op"===e.type?{...e,args:e.args.map(a)}:e,i=s?{type:"op",op:"&",args:[{type:"op",op:"∈",args:[t,s]},a(o)]}:a(o);return"∉"===e.op?{type:"op",op:"\\not",args:[i]}:i}(e);return t?this.value(t):this.membership(e)}case"random":return this.random();case"evaluated":return this.value(function(e){const[t,r,n,o]=e.args,s=(e,t)=>"symbol"===e.type&&e.value===r.value?t:"op"===e.type?{...e,args:e.args.map(e=>s(e,t))}:e;return{type:"op",op:"-",args:[s(t,o),s(t,n)]}}(e));case"_":{const[e,t]=r;if("symbol"===e.type&&("number"===t.type||"symbol"===t.type))return this.leaf({type:"symbol",value:`${e.value}_${t.value}`});break}}if(za[t])return this.builtin(t,o());this.fail(`"${t}" isn't available in a filter`)}truth(e){return"b"===e.kind?e.c[0]:`(${Ia(e)} !== 0)`}componentwise(e,t){const r=e.map(Ta),n=Math.max(...r),o=new Set(r.filter(e=>e>1));o.size>1&&this.fail(`can't combine vectors of ${[...o].join(" and ")} values`);const s=Array.from({length:n},(r,n)=>t(...e.map(e=>Ia(e,n))));return this.keep(Na(s))}builtin(e,t){const r=za[e];if(Ma[e]&&t.length!==Ma[e]&&this.fail(`${e}() takes ${Ma[e]} values`),"function"==typeof r)return this.componentwise(t,r);const n=1===r?e:r;return this.componentwise(t,(...e)=>`Math.${n}(${e.join(", ")})`)}power([e,t]){const r="number"===t.type&&/^-?\d+$/.test(t.value)?Number(t.value):null,n=this.keep(this.value(e)),o=e=>this.componentwise([n],t=>Array(e).fill(t).join(" * "));return 0===r?this.componentwise([n],()=>"1"):null!==r&&r>=1&&r<=4?o(r):null!==r&&r<=-1&&r>=-4?this.componentwise([o(-r)],e=>`(1 / ${e})`):"symbol"===e.type&&"e"===e.value?this.componentwise([this.value(t)],e=>`Math.exp(${e})`):"number"===e.type&&"2"===e.value?this.componentwise([this.value(t)],e=>`Math.pow(2, ${e})`):this.componentwise([n,this.value(t)],(e,t)=>`Math.pow(${e}, ${t})`)}ternary([e,t,r]){const n=this.truth(this.value(e)),o=e=>"symbol"===e.type&&"unchanged"===e.value;let s=o(t)?null:this.value(t),a=o(r)?null:this.value(r);const i=e=>"b"===e.kind?Sa("($u > 0.5)"):"f"===e.kind?ja("$u"):Na(["$k0","$k1","$k2","$k3"].slice(0,4===e.c.length?4:3));if(!s&&!a)return ja("$u");if(s||(s=i(a)),a||(a=i(s)),"b"===s.kind&&"b"===a.kind)return Sa(this.temp(`(${n} ? ${s.c[0]} : ${a.c[0]})`));const l=Math.max(Ta(s),Ta(a)),c=Array.from({length:l},(e,t)=>this.temp(`(${n} ? ${Ia(s,t)} : ${Ia(a,t)})`));return Na(c)}membership(e){const[t,r]=e.args,n=Ia(this.value(t)),o="∉"===e.op;let s;if("op"===r.type&&["()","[]","(]","[)"].includes(r.op)&&2===r.args.length){const[e,t]=r.args.map(e=>Ia(this.value(e)));s=`(${n} ${"["===r.op[0]?">=":">"} ${e} && ${n} ${"]"===r.op[1]?"<=":"<"} ${t})`}else"op"===r.type&&"{}"===r.op?s=r.args.length?`(${r.args.map(e=>`${n} === ${Ia(this.value(e))}`).join(" || ")})`:"false":"symbol"===r.type&&["ℝ","ℤ","ℕ"].includes(r.value)?s={"ℝ":`Number.isFinite(${n})`,"ℤ":`Number.isInteger(${n})`,"ℕ":`(Number.isInteger(${n}) && ${n} > 0)`}[r.value]:this.fail("∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ");return Sa(o?`!${s}`:s)}random(){return this.uses.add("random"),ja(this.temp("$h_random($px, $py, $h, ++$seed)"))}call(e,t,r){const n=()=>t.map(e=>this.value(e));if(e.startsWith("mz_sample_")){const t=e.slice(10),[r,o]=n(),[s,a]=o?[Ia(r),Ia(o)]:[Ia(r,0),Ia(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${s}, ${a}, ${e});`),this.keep(Na([0,1,2,3].map(t=>`${e}[${t}]`)))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(this.sampler(t,s,a))}if(e.startsWith("mz_at_")){const t=e.slice(6),[r,o]=n(),[s,a]=o?[Ia(r),Ia(o)]:[Ia(r,0),Ia(r,1)];if("image"===t){const e=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${s}, ${a}, ${e});`),Na([0,1,2].map(t=>`${e}[${t}]`))}return this.pictures.has(t)||this.fail(`unknown picture "${t}"`),this.keep(Na(this.sampler(t,s,a).c.slice(0,3)))}if(e.startsWith("mz_width_")||e.startsWith("mz_height_")){const t=e.replace(/^mz_(width|height)_/,"");return this.pictureNames.add(t),ja(e.startsWith("mz_width_")?`$qw_${t}`:`$qh_${t}`)}switch(e){case"pixel":{const[e,t]=n().map(e=>Ia(e)),r=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${e}, ${t}, ${r});`),this.keep(Na([0,1,2,3].map(e=>`${r}[${e}]`)))}case"red":case"green":case"blue":case"alpha":case"luma":{let r;2===t.length?r=this.call("pixel",t):1===t.length?r=this.value(t[0]):this.fail(`${e}() takes a color, or a position px, py`);const n={red:0,green:1,blue:2,alpha:3}[e];return"luma"===e?ja(`(${Ia(r,0)} * 0.299 + ${Ia(r,1)} * 0.587 + ${Ia(r,2)} * 0.114)`):"alpha"===e&&3===Ta(r)?ja("1"):ja(Ia(r,n))}case"length":{const[e]=n();return ja(`Math.sqrt(${e.c.map((t,r)=>`${Ia(e,r)} * ${Ia(e,r)}`).join(" + ")})`)}case"distance":{const[e,t]=n(),r=this.componentwise([e,t],(e,t)=>`(${e} - ${t})`);return ja(`Math.sqrt(${r.c.map(e=>`${e} * ${e}`).join(" + ")})`)}case"dot":{const[e,t]=n(),r=Math.max(Ta(e),Ta(t));return ja(`(${Array.from({length:r},(r,n)=>`${Ia(e,n)} * ${Ia(t,n)}`).join(" + ")})`)}case"normalize":{const[e]=n(),t=this.temp(`Math.sqrt(${e.c.map((t,r)=>`${Ia(e,r)} * ${Ia(e,r)}`).join(" + ")})`);return this.componentwise([e],e=>`(${e} / ${t})`)}case"cross":{const[e,t]=n();3===Ta(e)&&3===Ta(t)||this.fail("cross() takes two colors (3 values each)");const[r,o,s]=e.c,[a,i,l]=t.c;return this.keep(Na([`(${o} * ${l} - ${s} * ${i})`,`(${s} * ${a} - ${r} * ${l})`,`(${r} * ${i} - ${o} * ${a})`]))}case"convolve":{const e=n().map(e=>Ia(e));9!==e.length&&this.fail("convolve() takes 9 numbers: the 3×3 kernel, row by row");const t=this.scratchArray();return this.body.push(`$h_convolve($I, $w, $h, $px, $py, ${e.join(", ")}, ${t});`),Na([0,1,2].map(e=>`${t}[${e}]`))}case"mz_zoom":case"mz_shift":case"mz_rotate":case"mz_crop":case"mz_tile":case"mz_flipx":case"mz_flipy":return this.geometry(e.slice(3),n().map(e=>Ia(e)));case"tolinear":case"fromlinear":case"tohsv":case"fromhsv":case"tohsl":case"fromhsl":case"tolab":case"fromlab":case"tooklab":case"fromoklab":case"toycbcr":case"fromycbcr":{const t=n(),r=3===t.length?t.map(e=>Ia(e)):[0,1,2].map(e=>Ia(t[0],e));1!==t.length&&3!==t.length&&this.fail(`${e}() takes a color`);const o=this.scratchArray();return this.body.push(`$h_col_${e}(${r.join(", ")}, ${o});`),this.keep(Na([0,1,2].map(e=>`${o}[${e}]`)))}case"random":return this.random();case"exp":case"exp2":case"log2":case"sign":case"fract":case"radians":case"degrees":case"inversesqrt":case"pow":case"mod":case"step":case"clamp":case"mix":case"smoothstep":case"abs":case"floor":case"ceil":case"sqrt":case"sin":case"cos":case"tan":return this.builtin(e,n());case"asin":return this.builtin("arcsin",n());case"acos":return this.builtin("arccos",n());case"atan":return 2===t.length?this.builtin("atan2",n()):this.builtin("arctan",n());case"log":return this.builtin("ln",n());case"max":case"min":return this.componentwise(n(),(...t)=>`Math.${e}(${t.join(", ")})`)}if(ka[e])return this.neighborhood(e,t);this.fail(`unknown function "${e}"`)}geometry(e,t){const r=(e,t)=>this.keep(Na([e,t]));switch(e){case"zoom":{const[e,n="0.5",o="0.5"]=t,s=r(`(${n} * $w - 0.5)`,`(${o} * $h - 0.5)`);return r(`(${s.c[0]} + ($px - ${s.c[0]}) / ${e})`,`(${s.c[1]} + ($py - ${s.c[1]}) / ${e})`)}case"shift":{const[e,n]=t;return r(`($h_fmod($px - ${e} + 0.5, $w) - 0.5)`,`($h_fmod($py - ${n} + 0.5, $h) - 0.5)`)}case"rotate":{const[e,n="0.5",o="0.5"]=t,s=r(`(${n} * $w - 0.5)`,`(${o} * $h - 0.5)`),a=r(`($px - ${s.c[0]})`,`($py - ${s.c[1]})`),i=this.keep(Na([`Math.cos(${e})`,`Math.sin(${e})`]));return r(`(${s.c[0]} + ${i.c[0]} * ${a.c[0]} + ${i.c[1]} * ${a.c[1]})`,`(${s.c[1]} + ${i.c[0]} * ${a.c[1]} - ${i.c[1]} * ${a.c[0]})`)}case"crop":{const[e,n,o,s]=t;return r(`((${e} + (${o} - ${e}) * ($px + 0.5) / $w) * $w - 0.5)`,`((${n} + (${s} - ${n}) * ($py + 0.5) / $h) * $h - 0.5)`)}case"tile":{const[e,n=e]=t;return r(`($h_fmod(($px + 0.5) * ${e}, $w) - 0.5)`,`($h_fmod(($py + 0.5) * ${n}, $h) - 0.5)`)}case"flipx":return r("($w - 1 - $px)","$py");case"flipy":return r("$px","($h - 1 - $py)")}this.fail(`unknown geometry ${e}`)}neighborhood(e,t){const r=ka[e];if(t.every(e=>this.isUniform(e))){const n=t.map(e=>Ia(this.uniformValue(e))),o=`${e}(${n.join(",")})`;if(!this.planes.has(o)){const t=`$N${this.planes.size}`;this.pre.push(`let ${t} = $h_plane_${e}($I, $w, $h, $y0, $y1${n.map(e=>`, ${e}`).join("")});`),this.planes.set(o,t)}const s=this.planes.get(o);return 3===r?Na([0,1,2].map(e=>`${s}[$j3 + ${e}]`)):ja(`${s}[$j]`)}const n=t.map(e=>Ia(this.value(e)));if(1===r)return ja(this.temp(`$h_at_${e}($I, $w, $h, $px, $py${n.map(e=>`, ${e}`).join("")})`));const o=this.scratchArray();return this.body.push(`$h_at_${e}($I, $w, $h, $px, $py${n.map(e=>`, ${e}`).join("")}, ${o});`),Na([0,1,2].map(e=>`${o}[${e}]`))}isUniform(e){return"number"===e.type||("symbol"===e.type?["w","h","t"].includes(e.value)||Boolean(Ea[e.value])||Object.prototype.hasOwnProperty.call(this.params,e.value)&&"color"!==this.params[e.value].type:"op"===e.type&&!e.op.startsWith(xa)&&"random"!==e.op&&e.args.every(e=>this.isUniform(e)))}uniformValue(e){const t=this.body;this.body=this.pre;try{return this.value(e)}finally{this.body=t}}channel(e,t){const r="rgba"===e||"rgb"===e?"$gray":`$c${"rgba".indexOf(e)}`;this.body.push(`$u = ${r}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);const n=this.value(t),o=Ta(n),s=e=>Ia(n,e);if("rgba"===e){2===o&&this.fail("a color is one number (gray), three (r, g, b) or four (r, g, b, a) — not two");const e=1===o?[s(0),s(0),s(0),"1"]:3===o?[s(0),s(1),s(2),"1"]:[0,1,2,3].map(s);this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]}; $c3 = ${e[3]};`)}else if("rgb"===e){2===o&&this.fail("a color is one number (gray), three (r, g, b) or four — not two");const e=1===o?[s(0),s(0),s(0)]:[s(0),s(1),s(2)];this.body.push(`$c0 = ${e[0]}; $c1 = ${e[1]}; $c2 = ${e[2]};`)}else{const t="rgba".indexOf(e),r=1===o?s(0):3===o&&"a"===e?"1":s(t);this.body.push(`$c${t} = ${r};`)}}parameters(){return["$I","$O","$S","$w","$h","$t","$P","$op","$y0","$y1",...[...this.pictureNames].flatMap(e=>[`$Q_${e}`,`$qw_${e}`,`$qh_${e}`,`$qz_${e}`,`$qx_${e}`,`$qy_${e}`,`$qa_${e}`,`$qm_${e}`]),...va.map(e=>`$h_${e}`)]}arguments(e){const t=[...this.pictureNames];return[e.input,e.output,e.source,e.width,e.height,e.t,e.params,e.opacity,e.y0??0,e.y1??e.height,...t.flatMap(t=>{const r=e.pictures[this.bind?.[t]??t]??(this.graphics?.has(t)?Us:Ps),n=e.placements[t]??{};return[r.data,r.width,r.height,Number(n.zoom??1),Number(n.x??.5),Number(n.y??.5),Number(n.angle??0),Ds(n.place)]}),...va.map(e=>wa[e])]}source(){const e=Object.entries(this.params).map(([e,t],r)=>"color"===t.type?`let $p_${e}_0 = $P[${r}][0], $p_${e}_1 = $P[${r}][1], $p_${e}_2 = $P[${r}][2];`:`let $p_${e} = $P[${r}];`);return[...e.map(e=>e.replace(/\$P\[(\d+)\]\[(\d)\]/g,"$h_at($P, $1, $2)")),"let $u = 0, $k0 = 0, $k1 = 0, $k2 = 0, $k3 = 0, $seed = 0, $CS = $h_scratch();",...this.pre,"for (let $py = $y0; $py < $y1; $py++) {"," for (let $px = 0; $px < $w; $px++) {"," let $j = $py * $w + $px, $j3 = $j * 3, $j4 = $j * 4;"," let $r = $I[$j4], $g = $I[$j4 + 1], $b = $I[$j4 + 2], $a = $I[$j4 + 3];"," let $c0 = $r, $c1 = $g, $c2 = $b, $c3 = $a;"," let $x = ($px + 0.5) / $w, $y = ($py + 0.5) / $h;",this.space?` $h_col_from${this.space}($r, $g, $b, $CS); let $gray = $CS[0] * 0.299 + $CS[1] * 0.587 + $CS[2] * 0.114;`:" let $gray = $r * 0.299 + $g * 0.587 + $b * 0.114;"," $seed = $t;",...this.body.map(e=>` ${e}`)," $O[$j4] = $r + ($c0 - $r) * $op;"," $O[$j4 + 1] = $g + ($c1 - $g) * $op;"," $O[$j4 + 2] = $b + ($c2 - $b) * $op;"," $O[$j4 + 3] = $a + ($c3 - $a) * $op;"," }","}"].join("\n")}}function qa(e,t={}){const r="float"===t.precision||"half"===t.precision?"float":"byte",n=e.passes.map(e=>Fa(e)),o={};let s=null;const a=t.parallelFrom??25e4,i=void 0===t.workers||"auto"===t.workers?function(){const e="undefined"!=typeof navigator&&navigator.hardwareConcurrency?navigator.hardwareConcurrency:4;return Math.max(0,Math.min(8,e-1))}():Number(t.workers);let l=null,c=null,u=new Map;const p={passes:e.passes,get precision(){return r},sources:n.map(e=>e.source),setImage(e,t){if("string"!=typeof e&&(t=e,e=null),e&&"source"!==e&&null==t)return delete o[e],p;const r=Pa(t);return e&&"source"!==e?o[e]=r:s=r,p},draw({t:t=0,canvas:a=null}={}){if(!s)throw new Error("setImage() first");const{width:i,height:l}=s,c=i*l*4;let u=s.data;const p=[];e.passes.forEach((e,a)=>{for(let t=0;t<e.keepInput;t++)p.push(u);const h=new Float32Array(c);if(e.blendKept){const t=p.pop(),r=e.opacity;for(let e=0;e<c;e++)h[e]=t[e]+(u[e]-t[e])*r}else n[a].run({input:u,output:h,source:s.data,width:i,height:l,t:t,params:Object.keys(e.params??{}).map(t=>e.values[t]),opacity:e.opacity,pictures:o,placements:e.placements??{}});"byte"===r&&La(h),u=h});const h=new Uint8ClampedArray(c);for(let e=0;e<c;e++){const t=u[e];h[e]=t>0?t<1?Math.round(255*t):255:0}const f={data:h,width:i,height:l};return a&&(a.width=i,a.height=l,a.getContext("2d").putImageData(new ImageData(h,i,l),0,0)),f},async drawAsync({t:n=0,canvas:h=null}={}){if(!s)throw new Error("setImage() first");const{width:f,height:m}=s;if(i<2||f*m<a)return p.draw({t:n,canvas:h});c??=async function(e,t,r){const n=new URL(r??"./cpu-worker.js",import.meta.url);let o,s=()=>{};if("undefined"!=typeof Worker&&"undefined"!=typeof window){const e=n.origin===location.origin?n:URL.createObjectURL(new Blob([`import ${JSON.stringify(n.href)};`],{type:"text/javascript"}));e!==n&&(s=()=>URL.revokeObjectURL(e)),o=()=>{const t=new Worker(e,{type:"module"});return{send:e=>t.postMessage(e),on:e=>{t.onmessage=t=>e(t.data),t.onerror=t=>e({id:-1,ok:!1,error:t.message})},close:()=>t.terminate()}}}else try{const{Worker:e}=await(import("node:worker_threads"));o=()=>{const t=new e(n);return{send:e=>t.postMessage(e),on:e=>{t.on("message",e),t.on("error",t=>e({id:-1,ok:!1,error:t.message}))},close:()=>t.terminate()}}}catch{return null}const a=Array.from({length:e},o);let i=1;const l=a.map(()=>new Map);a.forEach((e,t)=>e.on(e=>{if(-1===e.id){for(const[,r]of l[t])r.reject(new Error(e.error));return void l[t].clear()}const r=l[t].get(e.id);r&&(l[t].delete(e.id),e.ok?r.resolve(e):r.reject(new Error(e.error)))}));const c=(e,t)=>new Promise((r,n)=>{const o=i++;l[e].set(o,{resolve:r,reject:n}),a[e].send({...t,id:o})}),u={size:e,shared:Ba(),ask:c,broadcast:e=>Promise.all(a.map((t,r)=>c(r,e))),close:()=>{a.forEach(e=>e.close());for(const e of l){for(const[,t]of e)t.reject(new Error("The runner was disposed of while drawing"));e.clear()}}};try{await u.broadcast({type:"init",passes:t.map(({fragment:e,...t})=>t)})}catch(e){throw u.close(),e}finally{s()}return u}(i,e.passes,t.workerUrl).catch(()=>!1);const g=c,d=await g;if(g!==c)throw new Error("The runner was disposed of while drawing");if(l=d,!d)return p.draw({t:n,canvas:h});const $=f*m*4,y=()=>d.shared?new Float32Array(new SharedArrayBuffer(4*$)):new Float32Array($);for(const[e,t]of[["source",s],...Object.entries(o)])u.get(e)!==t&&(await d.broadcast({type:"picture",name:e,picture:d.shared?Da(t):t}),u.set(e,t));let b=d.shared?Da(s).data:s.data;const w=[];for(let t=0;t<e.passes.length;t++){const o=e.passes[t];for(let e=0;e<o.keepInput;e++)w.push(b);const s=y();if(o.blendKept){const e=w.pop();for(let t=0;t<$;t++)s[t]=e[t]+(b[t]-e[t])*o.opacity;"byte"===r&&La(s)}else{const e=Object.keys(o.params??{}).map(e=>o.values[e]),a=Ua(m,d.size),i=await Promise.all(a.map(([a,i],l)=>d.ask(l,{type:"run",pass:t,input:b,output:d.shared?s:null,width:f,height:m,t:n,params:e,opacity:o.opacity,placements:o.placements??{},y0:a,y1:i,quantize:"byte"===r})));d.shared||i.forEach((e,t)=>s.set(e.band,a[t][0]*f*4))}b=s}const x=new Uint8ClampedArray($);for(let e=0;e<$;e++){const t=b[e];x[e]=t>0?t<1?Math.round(255*t):255:0}const v={data:x,width:f,height:m};return h&&(h.width=f,h.height=m,h.getContext("2d").putImageData(new ImageData(x,f,m),0,0)),v},get workers(){return l?l.size:0},dispose(){s=null;for(const e of Object.keys(o))delete o[e];c&&c.then(e=>e&&e.close()),c=null,l=null,u=new Map}};return So(p,e)}function La(e){for(let t=0;t<e.length;t++){const r=e[t];e[t]=r>0?r<1?Math.round(255*r)/255:1:0}}function Pa(e){if(e&&e.data&&e.width&&e.height){const t=e.data,r=t instanceof Float32Array||t instanceof Float64Array?1:1/255,n=new Float32Array(e.width*e.height*4);for(let e=0;e<n.length;e++)n[e]=t[e]*r;return{data:n,width:e.width,height:e.height}}if("undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas){const t=e.naturalWidth||e.videoWidth||e.width,r=e.naturalHeight||e.videoHeight||e.height;if(!t||!r)throw new Error("setImage: the picture has no size yet (not loaded?)");const n=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,r):Object.assign(document.createElement("canvas"),{width:t,height:r})).getContext("2d",{willReadFrequently:!0});return n.drawImage(e,0,0,t,r),Pa(n.getImageData(0,0,t,r))}throw new Error("setImage: give ImageData or { data, width, height }")}function Ua(e,t){const r=[];for(let n=0;n<t;n++){const o=Math.floor(e*n/t),s=Math.floor(e*(n+1)/t);s>o&&r.push([o,s])}return r}const Ba=()=>"undefined"!=typeof SharedArrayBuffer&&("undefined"==typeof crossOriginIsolated||!0===crossOriginIsolated);function Da(e){if(e.data.buffer instanceof(globalThis.SharedArrayBuffer??Object))return e;if(e.shared)return e.shared;const t=new Float32Array(new SharedArrayBuffer(e.data.byteLength));return t.set(e.data),e.shared={data:t,width:e.width,height:e.height},e.shared}const Za=[{name:"Wave",group:"Shape & motion",description:"Rows slide back and forth as t advances",params:{amplitude:{default:8,min:0,max:40},wavelength:{default:10,min:1,max:60},speed:{default:5,min:1,max:30}},color:"pixel(px + amplitude sin(py / wavelength + t / speed), py)"},{name:"Invert",group:"Color & tone",color:"(1 - r, 1 - g, 1 - b)"},{name:"Grayscale",group:"Color & tone",color:"gray"},{name:"Threshold",group:"Color & tone",params:{cutoff:.5},color:"if gray > cutoff then 1 else 0"},{name:"Posterize",group:"Color & tone",params:{levels:{default:4,min:2,max:16,step:1}},color:"min(floor(rgb * levels) / (levels - 1), 1)"},{name:"Brightness & contrast",group:"Color & tone",params:{brightness:{default:0,min:-.5,max:.5},contrast:{default:1,min:0,max:3}},color:"(rgb - 0.5) contrast + 0.5 + brightness"},{name:"Tint",group:"Color & tone",params:{tint:[1,.85,.7]},color:"rgb * tint"},{name:"Sepia",group:"Color & tone",color:"(0.393r + 0.769g + 0.189b, 0.349r + 0.686g + 0.168b, 0.272r + 0.534g + 0.131b)"},{name:"Color circle",group:"Color & tone",description:"Black and white, except a soft circle that keeps its color",params:{across:{default:.5,min:0,max:1,label:"where, across"},down:{default:.5,min:0,max:1,label:"where, down"},radius:{default:.3,min:0,max:1},softness:{default:.08,min:0,max:.5}},notes:["The color stays inside a circle and fades to gray over the softness. Sizes are parts of the picture's shorter side, so it stays round.",{param:"across"},{param:"down"},{param:"radius"},{param:"softness"}],color:"mix((gray, gray, gray), rgb, 1 - smoothstep(radius, radius + softness, distance((px, py), (across w, down h)) / min(w, h)))"},{name:"Vignette",group:"Color & tone",params:{strength:{default:1.6,min:0,max:4}},color:"rgb * (1 - strength ((x - 0.5)^2 + (y - 0.5)^2))"},{name:"Sobel edges",group:"Blur & edges",description:"How fast the brightness changes",params:{gain:{default:2,min:.2,max:10}},color:"gain sobel()"},{name:"Edge map",group:"Blur & edges",description:"White where an edge is stronger than the cutoff",params:{cutoff:{default:.3,min:0,max:2}},color:"if sobel() > cutoff then 1 else 0"},{name:"Outline",group:"Blur & edges",description:"Ink lines over the color",params:{gain:{default:3,min:0,max:10}},color:"rgb (1 - gain sobel())"},{name:"Box blur",group:"Blur & edges",params:{radius:{default:2,min:0,max:8,step:1}},color:"blur(radius)"},{name:"Gaussian blur",group:"Blur & edges",description:"Computed in two passes, across then down, so it can be wide",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Canny edges",group:"Blur & edges",description:"Thin, clean edge lines: smooth, gradient, thinning, two thresholds, hysteresis — a chain",steps:[{params:{sigma:{default:1.4,min:.5,max:4}},color:"gaussian(sigma)"},{color:"(min(sobel() / 4, 1), floor(fract((atan2(sobely(), sobelx()) + π/8) / π) 4) / 4, 0)"},{color:"if green(px, py) < 0.125 then (if r >= red(px - 1, py) & r >= red(px + 1, py) then r else 0) else if green(px, py) < 0.375 then (if r >= red(px + 1, py + 1) & r >= red(px - 1, py - 1) then r else 0) else if green(px, py) < 0.625 then (if r >= red(px, py - 1) & r >= red(px, py + 1) then r else 0) else (if r >= red(px - 1, py + 1) & r >= red(px + 1, py - 1) then r else 0)"},{params:{low:{default:.08,min:0,max:.5},high:{default:.2,min:0,max:1}},color:"if r > high then 1 else if r > low then 0.5 else 0"},"if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else if r > 0.4 then (if red(dilate(1)) > 0.9 then 1 else 0.5) else 0","if r > 0.9 then 1 else 0"]},{name:"Sharpen",group:"Blur & edges",params:{amount:{default:.6,min:0,max:3}},color:"sharpen(amount)"},{name:"Unsharp mask",group:"Blur & edges",description:"The picture plus what a blur removes",params:{amount:{default:1.5,min:0,max:5},sigma:{default:2,min:.5,max:4}},color:"rgb + amount (rgb - gaussian(sigma))"},{name:"Bloom",group:"Blur & edges",description:"Bright parts glow",params:{amount:{default:.8,min:0,max:3},sigma:{default:3,min:.5,max:4},cutoff:{default:.6,min:0,max:1}},color:"rgb + amount max(gaussian(sigma) - cutoff, 0)"},{name:"Emboss",group:"Blur & edges",color:"emboss()"},{name:"Dilate",group:"Blur & edges",description:"Light areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"dilate(radius)"},{name:"Erode",group:"Blur & edges",description:"Dark areas grow",params:{radius:{default:2,min:0,max:8,step:1}},color:"erode(radius)"},{name:"3×3 kernel",group:"Blur & edges",description:"Your own convolution; the default is a sharpen",params:{k1:{default:0,min:-8,max:8},k2:{default:-1,min:-8,max:8},k3:{default:0,min:-8,max:8},k4:{default:-1,min:-8,max:8},k5:{default:5,min:-8,max:8},k6:{default:-1,min:-8,max:8},k7:{default:0,min:-8,max:8},k8:{default:-1,min:-8,max:8},k9:{default:0,min:-8,max:8}},color:"convolve(k1, k2, k3, k4, k5, k6, k7, k8, k9)"},{name:"Pixelate",group:"Shape & motion",params:{size:{default:8,min:1,max:32,step:1}},color:"pixel(floor(px / size) size, floor(py / size) size)"},{name:"Mirror",group:"Shape & motion",color:"pixel(w - px, py)"},{name:"Scanlines",group:"Shape & motion",params:{period:{default:4,min:2,max:16,step:1}},color:"if py mod period < period / 2 then rgb else rgb * 0.6"},{name:"Pulse",group:"Shape & motion",description:"Brightness breathes with t",params:{speed:{default:6,min:1,max:30},depth:{default:.25,min:0,max:1}},color:"rgb (1 - depth + depth sin(t / speed))"},{name:"Chroma key",group:"Color & tone",description:"Replaces one color with another",params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1},background:[.1,.1,.4]},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Through a mask",group:"Other pictures",description:"Put this last: the steps above show only where the mask is light",images:{mask:{description:"light where the effect shows"}},color:"mix(source, rgb, luma(mask))"},{name:"Mix",group:"Other pictures",description:"Fade towards another picture",images:["overlay"],params:{amount:.5},color:"mix(rgb, overlay, amount)"},{name:"Masked mix",group:"Other pictures",images:{overlay:{},mask:{description:"light where the overlay shows"}},color:"mix(rgb, overlay, luma(mask))"},{name:"Multiply",group:"Other pictures",images:["overlay"],color:"rgb * overlay"},{name:"Screen",group:"Other pictures",images:["overlay"],color:"1 - (1 - rgb)(1 - overlay)"},{name:"Overlay blend",group:"Other pictures",images:["overlay"],color:"if gray < 0.5 then 2 rgb overlay else 1 - 2 (1 - rgb)(1 - overlay)"},{name:"Difference",group:"Other pictures",images:["overlay"],color:"abs(rgb - overlay)"},{name:"Alpha over",group:"Other pictures",description:"A picture with transparency laid on top",images:["overlay"],color:"mix(rgb, overlay, alpha(overlay))"},{name:"Chroma key onto a picture",group:"Other pictures",images:{background:{}},params:{key:[.22,.71,.29],tolerance:{default:.35,min:0,max:1}},color:"if distance(rgb, key) < tolerance then background else rgb"},{name:"Only inside the selection",group:"Other pictures",description:"Put this last: the steps above show only inside what you selected on the picture (everywhere, without a selection)",color:"mix(source, rgb, selected)"},{name:"Only outside the selection",group:"Other pictures",description:"Put this last: the steps above show only outside what you selected",color:"mix(rgb, source, selected)"},{name:"Glow round the selection",group:"Other pictures",description:"A colored halo round what you selected, fading over `reach` pixels (`away` is the distance from the selection)",params:{glow:[1,.8,.3],reach:{default:60,min:2,max:400},amount:{default:.9,min:0,max:1}},color:"mix(rgb, glow, amount (1 - smoothstep(0, reach, away)) step(0.5, away))"},{name:"Blur away from the selection",group:"Other pictures",description:"Sharp on what you selected, blurrier the farther a pixel is from it, all blurred `reach` pixels away",params:{sigma:{default:6,min:.5,max:8},reach:{default:200,min:1,max:1e3}},color:"mix(rgb, gaussian(sigma), min(1, away / reach))"},{name:"Caption",group:"Text & shapes",description:"Words along the bottom, with a soft shadow; change them under the step",graphics:{title:{text:"Your caption here",y:.88}},color:"mix(rgb, title, alpha(title))"},{name:"Poster title",group:"Text & shapes",description:"Big outlined letters across the top",graphics:{title:{text:"BIG TITLE",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.16,y:.14,outline:{color:"#000000",width:.08},shadow:null}},color:"mix(rgb, title, alpha(title))"},{name:"Gradient text",group:"Text & shapes",description:"The letters colored by math: a sunset from left to right",graphics:{title:{text:"Golden hour",font:"Georgia, serif",size:.13,y:.5,shadow:{color:"rgba(0,0,0,0.5)",blur:.2,dx:0,dy:.05}}},color:"mix(rgb, mix((1, 0.35, 0.3), (1, 0.85, 0.25), x), alpha(title))"},{name:"Neon sign",group:"Text & shapes",description:"White letters with a colored glow",graphics:{title:{text:"OPEN",font:"Trebuchet MS, sans-serif",size:.18,y:.5,shadow:{color:"#00e5ff",blur:.45,dx:0,dy:0}}},color:"mix(rgb * 0.6, title, alpha(title))"},{name:"Layered shadow",group:"Text & shapes",description:"Two shadow layers, each with its own filter: a soft glow that darkens and breathes with t, and a hard offset colored by a gradient",graphics:{title:{text:"LAYERS",font:"Impact, Haettenschweiler, sans-serif",weight:"normal",size:.17,y:.5,shadow:null,shadows:[{color:"#000000",blur:.7,dx:0,dy:.08},{color:"#000000",blur:0,dx:.07,dy:.07}]}},color:"mix(mix(mix(rgb, rgb * 0.25, alpha(title_shadow1) (0.7 + 0.3 sin(t / 10))), mix((1, 0.2, 0.6), (0.2, 0.6, 1), x), alpha(title_shadow2)), title, alpha(title))"},{name:"Ink brush",group:"Brushes",description:'Paint in a color; draw on the picture with "draw" under the step',graphics:{brush:{type:"strokes",brush:"round",size:.025}},params:{ink:[.95,.2,.25]},color:"mix(rgb, ink, alpha(brush))"},{name:"Blur brush",group:"Brushes",description:"Paint a blur in — stronger every time a stroke goes over the same place",graphics:{brush:{type:"strokes",brush:"soft",size:.08}},color:"mix(rgb, gaussian(2 + 3 min(4 green(brush), 3)), alpha(brush))"},{name:"Darken brush",group:"Brushes",description:"Each pass darkens a little more, like layers of a wash",graphics:{brush:{type:"strokes",brush:"soft",size:.07,flow:.7}},color:"rgb (1 - 0.22 min(4 green(brush), 4))"},{name:"Color reveal brush",group:"Brushes",description:"The picture starts gray; the brush paints its color back",graphics:{brush:{type:"strokes",brush:"soft",size:.1}},color:"mix((gray, gray, gray), rgb, alpha(brush))"},{name:"Fuse brush",group:"Brushes",description:"Paint glows as it goes down, then cools to charcoal (red(brush) is its age)",graphics:{brush:{type:"strokes",brush:"round",size:.02,age:40}},color:"mix(rgb, mix((1, 0.9, 0.5), (0.1, 0.07, 0.06), red(brush)), alpha(brush)) + (1, 0.5, 0.1) alpha(brush) max(0, 1 - 3 red(brush)) 0.6"},{name:"Rainbow brush",group:"Brushes",description:"The color runs round the wheel along the drawing (blue(brush) is how far through it)",graphics:{brush:{type:"strokes",brush:"marker",size:.035}},color:"mix(rgb, fromhsv(blue(brush), 0.85, 1), alpha(brush))"},{name:"Chalk outline",group:"Brushes",description:'Chalk round an object: select it, then "outline the selection" under the step',graphics:{brush:{type:"strokes",brush:"chalk",size:.018,timing:"even",speed:2}},color:"mix(rgb, (0.97, 0.97, 0.92), alpha(brush))"},{name:"Frosted panel",group:"Text & shapes",description:"A rounded panel that blurs and darkens what is behind it — a shape with its own filter",graphics:{panel:{type:"rect",y:.86,w:.9,h:.2,radius:.25}},color:"mix(rgb, gaussian(5) * 0.7, alpha(panel))"},{name:"Spotlight oval",group:"Text & shapes",description:"Darkens everything but a soft oval",graphics:{spot:{type:"ellipse",x:.5,y:.45,w:.45,h:.55,shadow:{color:"#ffffff",blur:.12,dx:0,dy:0}}},color:"mix(rgb * 0.3, rgb, alpha(spot))"},{name:"Scrolling banner",group:"Text & shapes",description:"Text that slides across and wraps round (animated with t)",graphics:{title:{text:"Breaking news · scrolling text · ",size:.07,y:.92}},params:{speed:{default:3,min:-10,max:10}},color:"mix(rgb, shift(title, -speed t, 0), alpha(shift(title, -speed t, 0)))"},{name:"Pulsing title",group:"Text & shapes",description:"Text that grows and shrinks a little (animated with t)",graphics:{title:{text:"Hello!",size:.14,y:.5}},params:{amount:{default:.06,min:0,max:.3}},color:"mix(rgb, zoom(title, 1 + amount sin(t / 8)), alpha(zoom(title, 1 + amount sin(t / 8))))"},{name:"Fade-in title",group:"Text & shapes",description:"Text that fades in over the first frames (animated with t)",graphics:{title:{text:"Once upon a time",font:"Georgia, serif",style:"italic",weight:"normal",size:.09,y:.5}},params:{frames:{default:40,min:1,max:200}},color:"mix(rgb, title, alpha(title) clamp(t / frames, 0, 1))"},{name:"Zoom",group:"Shape & motion",params:{scale:{default:1.5,min:.25,max:4},cx:.5,cy:.5},color:"zoom(scale, cx, cy)"},{name:"Ken Burns",group:"Shape & motion",description:"A slow zoom that drifts across — a still picture that moves",params:{speed:{default:.002,min:0,max:.01},drift:{default:3e-4,min:-.001,max:.001}},color:"zoom(1 + speed t, 0.5 + drift t, 0.45)"},{name:"Scroll",group:"Shape & motion",description:"Slides and wraps around",params:{dx:{default:1,min:-5,max:5},dy:{default:0,min:-5,max:5}},color:"shift(dx t, dy t)"},{name:"Spin",group:"Shape & motion",params:{speed:{default:.01,min:-.05,max:.05}},color:"rotate(speed t)"},{name:"Tile",group:"Shape & motion",params:{n:{default:2,min:1,max:8,step:1}},color:"tile(n)"},{name:"Crop",group:"Shape & motion",description:"A part of the picture, filling the frame",params:{left:.1,top:.1,right:.9,bottom:.9},color:"crop(left, top, right, bottom)"},{name:"Flip",group:"Shape & motion",color:"flipx()"},{name:"Picture in picture",group:"Other pictures",description:"Another picture, fitted small in a corner",images:{inset:{description:"any size: it is fitted whole",place:"fit",zoom:.35,x:.8,y:.78}},color:"mix(rgb, inset, alpha(inset))"},{name:"Moving overlay",group:"Other pictures",description:"Another picture scrolling across at half strength",images:["overlay"],params:{speed:{default:2,min:-10,max:10}},color:"mix(rgb, shift(overlay, speed t, 0), 0.5)"},{name:"Hue shift",group:"Color & tone",description:"Turns every color around the hue wheel (in HSV)",space:"hsv",params:{amount:{default:.1,min:-.5,max:.5}},color:"(fract(r + amount), g, b)"},{name:"Saturation",group:"Color & tone",description:"More or less color (in HSV)",space:"hsv",params:{amount:{default:1.5,min:0,max:3}},color:"(r, clamp(g amount, 0, 1), b)"},{name:"Lightness",group:"Color & tone",description:"Lighter or darker without changing the colors (in Lab)",space:"lab",params:{amount:{default:1.15,min:.5,max:2}},color:"(clamp(r amount, 0, 1), g, b)"},{name:"Vivid",group:"Color & tone",description:"Colorfulness, perceptually even (in OKLab)",space:"oklab",params:{amount:{default:1.6,min:0,max:3}},color:"(r, 0.5 + (g - 0.5) amount, 0.5 + (b - 0.5) amount)"},{name:"Linear-light blur",group:"Blur & edges",description:"A Gaussian in linear light: bright spots stay bright, as a lens does",space:"linear",params:{sigma:{default:3,min:0,max:8}},color:"gaussian(sigma)"},{name:"Film grain",group:"Color & tone",description:"Noise that changes every frame",params:{amount:{default:.15,min:0,max:.6}},color:"rgb + amount (random() - 0.5)"},{name:"Swirl",group:"Shape & motion",params:{strength:{default:.02,min:0,max:.1}},color:"pixel(w/2 + (px - w/2) cos(strength t gray) - (py - h/2) sin(strength t gray), h/2 + (px - w/2) sin(strength t gray) + (py - h/2) cos(strength t gray))"}],Ga=e=>Za.find(t=>t.name===e);Za.push({name:"Old film",group:"Chains",description:"Sepia, a vignette and faint scanlines — a chain of three",steps:[Ga("Sepia"),{filter:Ga("Vignette"),with:{strength:1.2}},{filter:Ga("Scanlines"),opacity:.5}]},{name:"Comic",group:"Chains",description:"Bold flat colors with ink lines: a small blur first, so a photo's fine texture isn't inked — a chain of four",steps:[{filter:Ga("Gaussian blur"),with:{sigma:1.6}},{filter:Ga("Vivid"),with:{amount:1.5}},{filter:Ga("Posterize"),with:{levels:4}},{filter:Ga("Outline"),with:{gain:1.2}}]},{name:"Cartoon",group:"Chains",description:"Blur, then flatten the colors, then outline — a chain of three",steps:[{filter:Ga("Gaussian blur"),with:{sigma:1.5}},{filter:Ga("Posterize"),with:{levels:6}},{filter:Ga("Outline"),with:{gain:2}}]},{name:"Dreamy",group:"Chains",description:"A soft glow mixed over the picture",steps:[{filter:Ga("Bloom"),with:{amount:1.2}},{filter:Ga("Gaussian blur"),with:{sigma:2},opacity:.4}]},{name:"Tilt shift",group:"Chains",description:"Blurred where the mask is light — a chain",steps:[{filter:Ga("Gaussian blur"),with:{sigma:4}},Ga("Through a mask")]},{name:"Title card",group:"Chains",description:"A frosted panel with a caption on it — a chain of two",steps:[Ga("Frosted panel"),{filter:Ga("Caption"),with:{title:{text:"A title on a panel",y:.86}}}]},{name:"Color spotlight",group:"Chains",description:"Gray except where the mask is dark — a chain",steps:[Ga("Grayscale"),Ga("Through a mask")]});const Wa=Za,Ha=()=>"undefined"!=typeof document||"undefined"!=typeof OffscreenCanvas,Xa=(e,t)=>"undefined"!=typeof document?Object.assign(document.createElement("canvas"),{width:e,height:t}):new OffscreenCanvas(e,t);function Va(e){if(e&&"object"==typeof e&&Array.isArray(e.passes))return e;if("string"==typeof e){const t=e.trim().toLowerCase(),r=Wa.find(e=>e.name.toLowerCase()===t);return wo(r??Eo(e))}return wo(e)}const Ya=4096,Ja=2048;function Ka(e,t,r,n){const o=Math.min(1,n/Math.max(t,r));if(o>=1)return{image:e,width:t,height:r};const s=Math.max(1,Math.round(t*o)),a=Math.max(1,Math.round(r*o));if(Ha()){let n=e;((e=>Boolean(e&&e.data&&e.width&&e.height)&&!("undefined"!=typeof ImageData&&e instanceof ImageData))(e)||"undefined"!=typeof ImageData&&e instanceof ImageData)&&(n=Xa(t,r),n.getContext("2d").putImageData((e=>"undefined"!=typeof ImageData&&e instanceof ImageData?e:new ImageData(e.data instanceof Uint8ClampedArray?e.data:Uint8ClampedArray.from(e.data,e.data instanceof Float32Array||e.data instanceof Float64Array?e=>255*e:void 0),e.width,e.height))(e),0,0));const o=Xa(s,a),i=o.getContext("2d");return i.imageSmoothingEnabled=!0,i.imageSmoothingQuality="high",i.drawImage(n,0,0,s,a),{image:o,width:s,height:a}}const i=e.data,l=new i.constructor(s*a*4);for(let e=0;e<a;e++){const n=Math.floor(e*r/a),o=Math.max(n+1,Math.floor((e+1)*r/a));for(let r=0;r<s;r++){const a=Math.floor(r*t/s),c=Math.max(a+1,Math.floor((r+1)*t/s)),u=[0,0,0,0];for(let e=n;e<o;e++)for(let r=a;r<c;r++)for(let n=0;n<4;n++)u[n]+=i[4*(e*t+r)+n];const p=(o-n)*(c-a);for(let t=0;t<4;t++)l[4*(e*s+r)+t]=u[t]/p}}return{image:{data:l,width:s,height:a},width:s,height:a}}const Qa=e=>!(e=>"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)(e)||e.complete&&e.naturalWidth?[e.naturalWidth||e.videoWidth||e.displayWidth||e.width||0,e.naturalHeight||e.videoHeight||e.displayHeight||e.height||0]:[0,0],ei=e=>Boolean(e)&&"object"==typeof e&&Array.isArray(e.passes),ti=e=>(Array.isArray(e)||ArrayBuffer.isView(e))&&3===e.length&&[...e].every(e=>Number.isFinite(Number(e)));let ri=null;const ni=new WeakMap;let oi=0;function si(e){if("string"==typeof e)return`s:${e}`;if(ei(e))return ni.has(e)||ni.set(e,"c:"+oi++),ni.get(e);if(e&&"object"==typeof e)try{return`d:${_o(e)}`}catch{return null}return null}const ai=e=>({...e,passes:e.passes.map(e=>({...e,values:{...e.values}}))});function ii(e,t,r){const n=si(e)&&`${t}|${si(e)}`,o=ri?.runners;if(r&&n&&o?.has(n)){const e=o.get(n);return o.delete(n),o.set(n,e),e}const s=Va(e),a=ai(s),i=function(e,t={}){const r=function({webgl:e=!1,prefer:t="auto"}={}){return"cpu"===t?{engine:"cpu",reason:"asked for the CPU"}:e?{engine:"gpu",reason:"gpu"===t?"asked for the GPU":"WebGL is here"}:{engine:"cpu",reason:"no WebGL here"}}({webgl:Boolean(t.gl),prefer:t.prefer});if("gpu"===r.engine)try{return{runner:No(t.gl,e,{precision:t.precision}),...r}}catch(r){if("gpu"===t.prefer)throw r;return{runner:qa(e,t),engine:"cpu",reason:`the GPU refused the shader (${r.message.split("\n")[0]})`}}return{runner:qa(e,t),...r}}(a,{gl:r,prefer:t}),l={compiled:a,source:ei(e)?s:ai(s),...i};if(r&&n&&"gpu"===i.engine&&(o.set(n,l),o.size>16)){const[e,t]=o.entries().next().value;o.delete(e),t.runner.dispose()}return l}let li=Promise.resolve();function ci(e,t,r={}){const n=li.then(()=>async function(e,t,{params:r={},t:n=0,images:o={},engine:s="auto",canvas:a=null,maxSize:i=null}={}){if(!e)throw new Error("applyFilter: no picture");const[l,c]=Qa(e);if(!l||!c)throw new Error("applyFilter: the picture has no size yet (not loaded?)");if(null!==i&&!(Number(i)>=1))throw new Error(`applyFilter: maxSize is a number of pixels, not ${JSON.stringify(i)}`);if("auto"!==s&&"gpu"!==s&&"cpu"!==s)throw new Error(`applyFilter: engine is 'auto', 'gpu' or 'cpu', not "${s}"`);const u=a?a.getContext("2d"):null;if(a&&!u)throw new Error("applyFilter: `canvas` must be a 2D canvas (this one already has another kind of context)");const p="cpu"!==s?function(){if(ri&&!ri.gl.isContextLost())return ri;if(!Ha())return null;const e=Xa(1,1),t=e.getContext("webgl",{preserveDrawingBuffer:!0,premultipliedAlpha:!1});return ri=t?{canvas:e,gl:t,runners:new Map}:null,ri}():null;if("gpu"===s&&!p)throw new Error('applyFilter: no WebGL here (use engine "auto" or "cpu")');const h=ii(t,"gpu"===s?"gpu":p?"auto":"cpu",p?.gl),{compiled:f,source:m,runner:g}=h,d="gpu"===h.engine,$=d?Math.min(Number(i??Ya),p.gl.getParameter(p.gl.MAX_TEXTURE_SIZE)||Ya):Number(i??Ja),{image:y,width:b,height:w}=Ka(e,l,c,$);try{const e=new Map(f.passes.flatMap(e=>Object.entries(e.params??{})));for(const[t,n]of Object.entries(r)){if(!e.has(t))throw new Error(`applyFilter: the filter has no knob called "${t}" (it has ${[...e.keys()].join(", ")||"none"})`);if("color"===e.get(t).type?!ti(n):!Number.isFinite(Number(n))||"object"==typeof n||""===n)throw new Error(`applyFilter: the knob "${t}" needs ${"color"===e.get(t).type?"a color, [r, g, b] with each 0–1":"a number"}, not ${JSON.stringify(n)}`)}const t=Object.entries(f.graphics??{});let s={};if(t.length){const e=t.filter(([,e])=>"strokes"!==e.type).map(([e])=>e);if(!Ha()&&e.length)throw new Error(`applyFilter: this filter draws ${e.join(", ")} (text or shapes), which needs a canvas — there is none here`);s=await to(f,b,w,{t:Number.isFinite(n)?n:1/0})}f.passes.forEach((e,t)=>{e.values={...m.passes[t].values},e.opacity=m.passes[t].opacity;for(const[t,n]of Object.entries(r))t in(e.params??{})&&(e.values[t]="color"===e.params[t].type?[...n].map(Number):Number(n))}),g.setImage(y);for(const e of h.given??[])e in o||g.setImage(e,null);h.given=Object.keys(o);for(const[e,t]of Object.entries(o)){const[r,n]=Qa(t);g.setImage(e,r&&n?Ka(t,r,n,$).image:t)}for(const[e,t]of Object.entries(s))g.setImage(e,t);if(d){p.canvas.width=b,p.canvas.height=w,g.draw({t:n});const e=a??Xa(b,w);e.width=b,e.height=w;const t=u??e.getContext("2d");return t.clearRect(0,0,b,w),t.drawImage(p.canvas,0,0),e}const i=await g.drawAsync({t:n});if(!Ha()&&!a)return i;const l=a??Xa(b,w);return l.width=b,l.height=w,(u??l.getContext("2d")).putImageData(new ImageData(i.data,b,w),0,0),l}finally{d||g.dispose()}}(e,t,r));return li=n.catch(()=>{}),n}const ui=new Int32Array(256);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?3988292384^t>>>1:t>>>1;ui[e]=t}function pi(e,t){const r=new Uint8Array(12+t.length),n=new DataView(r.buffer);n.setUint32(0,t.length);for(let t=0;t<4;t++)r[4+t]=e.charCodeAt(t);return r.set(t,8),n.setUint32(8+t.length,function(e){let t=-1;for(let r=0;r<e.length;r++)t=ui[255&(t^e[r])]^t>>>8;return(-1^t)>>>0}(r.subarray(4,8+t.length))),r}function hi(e,t,r){const n=e+t-r,o=Math.abs(n-e),s=Math.abs(n-t),a=Math.abs(n-r);return o<=s&&o<=a?e:s<=a?t:r}async function fi({width:e,height:t,data:r,palette:n="auto",colors:o=256,dither:s=!0,quantize:a=null}){if("undefined"==typeof CompressionStream)return null;if(!Number.isInteger(e)||!Number.isInteger(t)||e<1||t<1||!r||r.length<e*t*4)throw new Error("encodePng: width and height are whole numbers of pixels, and data holds 4 bytes for each");let i=null;if(("auto"===n||"force"===n)&&(i=function(e){const t=new Map,r=[],n=new Uint8Array(e.length/4);for(let o=0,s=0;o<e.length;o+=4,s++){const a=(e[o]<<24|e[o+1]<<16|e[o+2]<<8|e[o+3])>>>0;let i=t.get(a);if(void 0===i){if(256===r.length)return null;i=r.length,t.set(a,i),r.push([e[o],e[o+1],e[o+2],e[o+3]])}n[s]=i}return{palette:r,indices:n}}(r),i&&i.palette.length>o&&(i=null),!i&&"force"===n)){if(!a)throw new Error('encodePng: palette "force" needs a quantize function (the picture has more than `colors` colors)');i=a(r,Math.min(256,Math.max(2,o)),{dither:s,width:e})}const l=[new Uint8Array([137,80,78,71,13,10,26,10])],c=new Uint8Array(13),u=new DataView(c.buffer);let p,h,f;if(u.setUint32(0,e),u.setUint32(4,t),i){const r=i.palette.length;f=r<=2?1:r<=4?2:r<=16?4:8,h="palette",c[8]=f,c[9]=3;const n=Math.ceil(e*f/8);p=new Uint8Array(t*(1+n));for(let r=0;r<t;r++){const t=r*(1+n)+1;for(let n=0;n<e;n++){const o=i.indices[r*e+n];8===f?p[t+n]=o:p[t+(n*f>>3)]|=o<<8-f-n*f%8}}const o=new Uint8Array(3*r),s=new Uint8Array(r);let a=!1;i.palette.forEach(([e,t,r,n],i)=>{o.set([e,t,r],3*i),s[i]=n,n<255&&(a=!0)}),l.push(pi("IHDR",c),pi("PLTE",o)),a&&l.push(pi("tRNS",s))}else{let n=!0;for(let e=3;e<r.length;e+=4)if(r[e]<255){n=!1;break}const o=n?3:4;h=n?"rgb":"rgba",f=8,c[8]=8,c[9]=n?2:6;const s=e*o;p=new Uint8Array(t*(1+s));const a=new Uint8Array(s),i=new Uint8Array(s);for(let l=0;l<t;l++){for(let t=0,s=l*e*4,i=0;t<e;t++,s+=4,i+=o)a[i]=r[s],a[i+1]=r[s+1],a[i+2]=r[s+2],n||(a[i+3]=r[s+3]);const t=l*(1+s);p[t]=4;for(let e=0;e<s;e++)p[t+1+e]=a[e]-hi(e>=o?a[e-o]:0,i[e],e>=o?i[e-o]:0);i.set(a)}l.push(pi("IHDR",c))}l.push(pi("IDAT",await async function(e){if("undefined"==typeof CompressionStream)return null;const t=new CompressionStream("deflate"),r=t.writable.getWriter();return r.write(e),r.close(),new Uint8Array(await new Response(t.readable).arrayBuffer())}(p)),pi("IEND",new Uint8Array(0)));const m=i?i.palette.length:function(e,t=257){const r=new Set;for(let n=0;n<e.length;n+=4)if(r.add((e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0),r.size>=t)return r.size;return r.size}(r);return{blob:new Blob(l,{type:"image/png"}),kind:h,colors:m,bits:f}}const mi=e=>e&&e.data&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&"function"!=typeof e.getContext;function gi(e){if(mi(e)){const{data:t,width:r,height:n}=e;if(t instanceof Uint8ClampedArray||t instanceof Uint8Array)return{data:t,width:r,height:n};const o=new Uint8ClampedArray(r*n*4),s=t instanceof Float32Array||t instanceof Float64Array?255:1;for(let e=0;e<o.length;e++)o[e]=Math.round(t[e]*s);return{data:o,width:r,height:n}}if(e&&"function"==typeof e.getContext){const t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("This canvas has a WebGL context: pass the 2D canvas applyFilter() returned, or copy it onto one first");return t.getImageData(0,0,e.width,e.height)}throw new Error("Give a canvas or a picture ({ data, width, height })")}async function di(e,{type:t="image/png",quality:r,palette:n="auto"}={}){if("image/png"===t){const t=await fi({...gi(e),palette:n});if(t)return t.blob}const o=mi(e)?function(e){const{width:t,height:r}=e;let n=null;return"undefined"!=typeof OffscreenCanvas?n=new OffscreenCanvas(t,r):"undefined"!=typeof document&&(n=Object.assign(document.createElement("canvas"),{width:t,height:r})),n?(n.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(e.data),t,r),0,0),n):null}(gi(e)):e;if(!o)throw new Error(`Saving as ${t} needs a browser (a canvas encodes it); in Node, save as image/png`);return"function"==typeof o.convertToBlob?o.convertToBlob({type:t,quality:r}):new Promise((e,n)=>o.toBlob(r=>r?e(r):n(new Error(`The browser could not encode ${t}`)),t,r))}async function $i(e,{gifenc:t,delay:r=1e3/30,repeat:n=0,colors:o=256}={}){const s=t&&(t.GIFEncoder?t:t.default);if(!s||"function"!=typeof s.GIFEncoder)throw new Error("encodeGif needs gifenc: import * as gifenc from 'gifenc' and pass { gifenc }");const a=s.GIFEncoder();let i=null,l=0;for await(const t of e){let{data:e,width:c,height:u}=gi(t);if((e.byteOffset||e.byteLength!==e.buffer.byteLength)&&(e=e.slice()),i&&(i[0]!==c||i[1]!==u))throw new Error(`Frame ${l+1} is ${c} × ${u}; the first was ${i[0]} × ${i[1]}`);i=[c,u];const p=yi(e),h=p?"rgba4444":"rgb565",f=s.quantize(e,Math.max(2,Math.min(256,o)),{format:h,oneBitAlpha:p}),m=s.applyPalette(e,f,h),g={palette:f,delay:Math.round(r),repeat:n};if(p){const e=f.findIndex(e=>e.length>3&&0===e[3]);e>=0&&Object.assign(g,{transparent:!0,transparentIndex:e})}a.writeFrame(m,c,u,g),l++}if(!l)throw new Error("encodeGif: no frames");return a.finish(),new Blob([a.bytes()],{type:"image/gif"})}function yi(e){for(let t=3;t<e.length;t+=4)if(e[t]<255)return!0;return!1}export{Ya as MAX_SIZE,Ja as MAX_SIZE_CPU,ci as applyFilter,$i as encodeGif,fi as encodePng,gi as pictureData,di as toBlob,Va as toCompiled};