@mathzetta/qblur 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +58 -0
- package/LICENSE +21 -0
- package/README.md +152 -2
- package/dist/cpu-worker.js +2 -0
- package/dist/qblur-apply.js +2 -0
- package/dist/qblur-element.js +2 -0
- package/dist/qblur.core.js +2 -0
- package/dist/qblur.external.global.min.js +2 -0
- package/dist/qblur.external.js +2 -0
- package/dist/qblur.global.min.js +2 -0
- package/dist/qblur.js +2 -0
- package/docs/filters.md +841 -0
- package/docs/library.md +601 -0
- package/package.json +118 -4
- package/src/apply-filter.js +245 -0
- package/src/apply.d.ts +64 -0
- package/src/apply.js +14 -0
- package/src/auto.js +41 -0
- package/src/cpu-helpers.js +418 -0
- package/src/cpu-runner.js +282 -0
- package/src/cpu-worker.js +58 -0
- package/src/cpu.js +586 -0
- package/src/element.d.ts +16 -0
- package/src/element.js +142 -0
- package/src/format.js +614 -0
- package/src/graphics.js +305 -0
- package/src/index.d.ts +283 -0
- package/src/index.js +13 -0
- package/src/library.js +173 -0
- package/src/png.js +157 -0
- package/src/runtime.js +248 -0
- package/src/save.js +108 -0
- package/src/strokes.js +350 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* qblur 0.1.2 — Copyright (c) 2025-2026 Robert Wilcox — MIT licence — https://qblur.com — MathZetta inside: Copyright (c) 2025 Robert Wilcox, MIT licence */
|
|
2
|
+
const t=-1,e={"+":{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:n(1),abs:n(1),floor:n(1),ceil:n(1),det:n(1),ln:n(1),loglog:n(1),logloglog:n(1),expm1:n(1),sin:n(1),cos:n(1),tan:n(1),csc:n(1),sec:n(1),cot:n(1),sinh:n(1),cosh:n(1),tanh:n(1),arcsin:n(1),arccos:n(1),arctan:n(1),arcsinh:n(1),arccosh:n(1),arctanh:n(1),random:n(0),log:n(2),root:n(2),atan2:n(2),round:n(2),fixed:n(2),perm:n(2),comb:n(2),der:n(2),max:n(t),min:n(t),gcd:n(t),mean:n(t),sum:n(t),prod:n(t),int:n(t),lim:n(t),"\\sumidx":n(t),"\\prodidx":n(t),pmatrix:n(t),bmatrix:n(t),vmatrix:n(t),"()":s(),"[]":s(),"{}":s(),"(]":s(),"[)":s(),"=":{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"},"?:":{prec:10,assoc:"right",arity:3,fixity:"infix"}};function n(t){return{prec:100,assoc:"none",arity:t,fixity:"prefix"}}function s(){return{prec:5,assoc:"left",arity:t,fixity:"none",group:!0}}const r="\\:",i=t=>"string"==typeof t&&t.startsWith(r)&&t.length>2;function o(t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:i(t)?a:void 0}const a=n(t),l=100,c="",p="",u={[c]:"dot",[p]:"cross"},h="",$={ln:l,log:l,loglog:l,logloglog:l,sqrt:l,sqrtpow:l,pow:l,expm1:l,der:l,lim:l,int:l,round:l,fixed:l,floor:l,ceil:l,abs:l,random:l,sum:l,prod:l,"\\sumidx":l,"\\prodidx":l,perm:l,comb:l,"\\perm":l,"\\comb":l,"\\binom":l,max:l,min:l,gcd:l,mean:l,pmatrix:l,bmatrix:l,vmatrix:l,det:l,sin:l,cos:l,tan:l,csc:l,sec:l,cot:l,sinh:l,cosh:l,tanh:l,arcsin:l,arccos:l,arctan:l,arcsinh:l,arccosh:l,arctanh:l,atan2:l,_:l,"!":90,"\\not":85,"^":80,"*":70,"/":70,frac:70,[c]:70,[p]: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,"?:":10,"?":9,",":5},f=t=>Object.prototype.hasOwnProperty.call($,t),m=new Set(["^","?:","?","log"]),g=["(","{","["],d=[")","}","]"];function y(t,e=!1){if(!t)return!1;for(let n=0;n<t.length;n++)if(!("0123456789.".includes(t[n])||e&&0===n&&"-"===t[n]&&t.length>1))return!1;return!0}for(const t of[$])Object.setPrototypeOf(t,null);const x=t=>({type:"number",value:String(t)}),b=t=>({type:"symbol",value:t}),w=(t,e)=>({type:"op",op:t,args:e}),_=['"',"'","`"];function M(t){return y(t,!0)?x(t):_.includes(t[0])?{type:"string",value:t}:b(t)}const v={"0-":"neg",sqrtpow:"root",pow:"^","==":"=","!==":"≠="};function A(t,e,n=null){e(t,n),"op"===t.type&&t.args.forEach(n=>A(n,e,t))}function E(t){let e="";return A(t,t=>{!e&&"symbol"===t.type&&1===t.value.length&&/[a-zA-Zʹ-Ͽ]/.test(t.value)&&(e=t.value)}),e}for(const t of[v])Object.setPrototypeOf(t,null);function N(t){const e=new Map;for(const[n,s,r]of t)if(n&&""!==n.trim()&&(e.set(n,s),!r))for(const t of k(n))e.get(t)||e.set(t,s);const n=new Map;for(const t of e.keys()){let e=n;for(let n=0;n<t.length;n++)e.has(t[n])||e.set(t[n],new Map),e=e.get(t[n]);e.end=!0}return t=>{let s="",r=0;for(;r<t.length;){const i=O(n,t,r);i?(s+=e.get(t.slice(r,r+i)),r+=i):s+=t[r++]}return s}}function O(t,e,n){let s=t,r=0;for(let t=n;t<e.length&&(s=s.get(e[t]),s);t++)s.end&&(r=t-n+1);return r}function k(t){const e=new Set([t.toLowerCase(),t.toUpperCase(),I(t)]);return e.delete(t),e}function I(t){let e="",n=!1;for(const s of t){const t=s>="a"&&s<="z",r=s>="A"&&s<="Z";e+=!n&&t?s.toUpperCase():s,n=t||r}return e}const S=[["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("],["\\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",c],["\\times",p],["×",p],["·",c],["÷","/"],["->","→"],["\\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(t=>["(","{"].flatMap(e=>[2,3,4,5,6,7,8,9,10].map(n=>[`${t}log${n}${e}`,`log_{${n}}${e}`]))),["\\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 "],["\\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.",h],["\\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 "],["∞","∞"],["⋅",c],["−","-"],["\\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 j=t=>" "===t||"\t"===t||"\n"===t,q="({[",z=")}]";const R={__proto__:null},T={__proto__:null};[..."⁰¹²³⁴⁵⁶⁷⁸⁹"].forEach((t,e)=>{R[t]=String(e)}),[..."₀₁₂₃₄₅₆₇₈₉"].forEach((t,e)=>{T[t]=String(e)}),Object.assign(R,{"⁺":"+","⁻":"-","⁼":"=","⁽":"(","⁾":")","ᵃ":"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 C=new RegExp(`[${Object.keys(R).join("")}]+|[${Object.keys(T).join("")}]+`,"g");const P={__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"},Z=new RegExp(`(?<![\\w.,^_])(\\d+)[ \\t]?([${Object.keys(P).join("")}])`,"g"),F=/(?<![\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 U(t){const e=t.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(e)?"":e}function D(t,e){const n=[];let s=0,r=0;for(let i=0;i<t.length;i++)q.includes(t[i])?s++:z.includes(t[i])?s--:0===s&&t.startsWith(e,i)&&(n.push(t.slice(r,i)),i+=e.length-1,r=i+1);return n.push(t.slice(r)),n}function W(t,e,n){let s=0;const r=new RegExp(`\\b${n}\\b`,"iy");for(let n=e;n<t.length;n++)if(q.includes(t[n]))s++;else if(z.includes(t[n])){if(--s<0)return-1}else if(0===s&&(r.lastIndex=n,r.test(t)))return n;return-1}function H(t,e){let n=0;for(let s=e;s<t.length;s++)if(q.includes(t[s]))n++;else if(z.includes(t[s])&&--n<0)return s;return t.length}function G(t,e){let n=1;for(let s=e+1;s<t.length;s++)if("?"===t[s])n++;else if(":"===t[s]&&0===--n)return t.slice(0,e+1)+"("+t.slice(e+1,s)+")?:"+t.slice(s+1);return t}function B(t){for(let e=2;e<t.length;e++)if("g"===t[e]&&"log"===t.slice(e-2,e+1))if("_"===t[e+1]){if(q.includes(t[e+2]))continue;const n=/^(?:\d+(?:\.\d+)?|[A-Za-z\u0370-\u03FF])/.exec(t.slice(e+2))?.[0];if(!n)continue;const s=e+2+n.length;t=t.slice(0,e+2)+"{"+n+"}"+t.slice(s)}else if("("===t[e+1]){let n=1,s=0,r="",i="",o=0;for(let a=e+2;a<t.length;a++){if(")]".includes(t[a])?n--:"([".includes(t[a])&&n++,0===n){o=a;break}1===n&&","===t[a]?s++:0===s?r+=t[a]:i+=t[a]}1===s&&o>0&&(t=t.slice(0,e+1)+"_{"+i+"}("+r+")"+t.slice(o+1))}return t}function X(t){const e="⌈"===t[0]?"ceil":"floor";let n=1;for(let s=1;s<t.length;s++)if("⌊"===t[s]||"⌈"===t[s]?n++:"⌋"!==t[s]&&"⌉"!==t[s]||n--,0===n)return e+"("+t.slice(1,s)+")"+t.slice(s+1);return t}function Q(t){let e=1;for(let n=0;n<t.length;n++){if(")]".includes(t[n])?e--:"([".includes(t[n])&&e++,0!==e)continue;const s=t.slice(0,n),r=t[n+1];if("{"===r||"("===r)return r+s+","+t.slice(n+2);const i=/^[A-Za-z0-9.\u0370-\u03FF]+/.exec(t.slice(n+1))?.[0]??"";return"{"+s+","+i+"}"+t.slice(n+1+i.length)}return t}const V=new Set(["pmatrix","bmatrix","vmatrix"]);function Y(t){const e=t.indexOf("}"),n=t.indexOf("{");if(e<0||n>=0&&n<e)return!1;const s=t.slice(0,e);if(!s.includes("matrix"))return!1;const r=t.indexOf("\\end{"+s+"}"),i=t.indexOf("\\begin{"+s+"}",e+1);if(r<0||-1!==i&&i<r)return!1;const o=t.slice(e+1,r).trim().split("\\\\").map(t=>t.trim()).filter(t=>t.length).map(t=>"["+t.replace(/&/g,", ")+"]"),a=t.slice(r+6+s.length);return V.has(s)?s+"("+o.join(", ")+")"+a:"["+o.join(", ")+"]"+a}function K(t,e){if("{"!==t[e+1])return[t[e+1],e+2];let n=1,s="";for(let r=e+2;r<t.length;r++){if("{"===t[r])n++;else if("}"===t[r]&&0===--n)return[s,r+1];s+=t[r]}return[s,t.length]}function J(t){const{lower:e,upper:n,next:s}=function(t){let e="",n="",s=0;return"_"===t[0]&&([e,s]=K(t,0),"^"===t[s]&&([n,s]=K(t,s))),{lower:e,upper:n,next:s}}(t),r=t.slice(s),i=t=>t.replace(/\\,/g,"").replace(/\\!/g,"");let o,a="",l="",c=r.indexOf("\\mathrm{d}");if(c>=0){o=r.slice(0,c);const t=/^\{([^{}]*)\}/.exec(r.slice(c+10));a=t?t[1]:r[c+10],l=r.slice(c+10+(t?t[0].length:1))}else(c=function(t){let e=0;for(let n=0;n<t.length;n++)if(q.includes(t[n]))e++;else if(z.includes(t[n]))e--;else if(0===e&&"d"===t[n]&&/[A-Za-z\u0370-\u03FF]/.test(t[n+1]??"")&&!/[A-Za-z]/.test(t[n+2]??""))return n;return-1}(r))>=0?(o=r.slice(0,c),a=r[c+1],l=r.slice(c+2)):o=r;if(!a){const t=/frac\{d([A-Za-z])\}/.exec(o);t&&(a=t[1],o=o.replace(t[0],"frac{1}"))}if(!a&&/^[A-Za-z]$/.test(e)){a=[...i(o).matchAll(/(?<![A-Za-z\\])([A-Za-z])(?![A-Za-z(])/g)].map(t=>t[1]).find(t=>t!==e&&t!==n)??"x"}let p="int("+(i(o).trim()?i(o):"1");return a&&(p+=","+a),(e||n)&&(p+=","+e+","+n),p+")"+l}function tt(t){const e=t[0];if(!(e>="A"&&e<="Z"||e>="a"&&e<="z"||e>="α"&&e<="ω"))return!1;const n=t.slice(2);let s=1;for(let t=0;t<n.length;t++)if(z.includes(n[t])?s--:q.includes(n[t])&&s++,0===s)return"("+n.slice(0,t)+","+e+")"+n.slice(t+1);return!1}function et(t){return"{"===t[0]||t.length<2?t:"{"+t[0]+"}{"+t[1]+"}"+t.slice(2)}const nt=/[A-Za-z\u0370-\u03FF]/;function st(t,e){if("{"!==t[e])return null;let n=0;for(let s=e;s<t.length;s++)if("{"===t[s])n++;else if("}"===t[s]&&0===--n)return[t.slice(e+1,s),s+1];return null}function rt(t,e){const n=/^\^(?:\{(\d+)\}|(\d))/.exec(t.slice(e));return n?[Number(n[1]??n[2]),e+n[0].length]:[1,e]}function it(t,e){const n=t.replace(/\\mathrm\{d\}/g,"d"),s=e.replace(/\\mathrm\{d\}/g,"d"),r=/^d(?:\^\{?(\d+)\}?)?([A-Za-z\u0370-\u03FF]?)$/.exec(n),i=/^d([A-Za-z\u0370-\u03FF])(?:\^\{?(\d+)\}?)?$/.exec(s);return r&&i?{n:Number(r[1]??1),of:r[2],by:i[1]}:null}function ot(t,e){if(q.includes(t[e])){let n=0;for(let s=e;s<t.length;s++)if(q.includes(t[s]))n++;else if(z.includes(t[s])&&0===--n)return[t.slice(e,s+1),s+1];return[t.slice(e),t.length]}let n=0;for(let s=e;s<t.length;s++)if(q.includes(t[s]))n++;else{if(z.includes(t[s])&&--n<0)return[t.slice(e,s),s];if(0===n&&("="===t[s]||","===t[s]))return[t.slice(e,s),s]}return[t.slice(e),t.length]}const at=(t,e,n)=>`der(${t},${e}${n>1?","+n:""})`;const lt="strtktk",ct="ABCDEFGHIJ",pt=t=>lt+[...String(t)].map(t=>ct[t]).join(""),ut=new RegExp(`^${lt}[${ct}]+$`);function ht(t){let e="";for(let n=0;n<t.length;n++){const s=t[n];if('"'===s||"`"===s){const s=$t(t,n);e+=t.slice(n,s+1),n=s}else if("'"===s)if(/[A-Za-z0-9)\]′\u0370-\u03FF]/.test(e[e.length-1]??""))e+="′";else{const s=$t(t,n);e+=t.slice(n,s+1),n=s}else e+=s}return e}function $t(t,e){let n=!1;for(let s=e+1;s<t.length;s++)if(n)n=!1;else if("\\"===t[s])n=!0;else if(t[s]===t[e])return s;return t.length-1}const ft=new RegExp(`${lt}[${ct}]+|§\\d+§`,"g");function mt(t,e){return e&&0!==e.size?t.map(t=>"string"!=typeof t?t:t.replace(ft,t=>{const n=e.get(t);if(void 0!==n)return n;for(let n=t.length-1;n>7;n--){const s=e.get(t.slice(0,n));if(void 0!==s)return s+t.slice(n)}return t})):t}const gt={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.pow(-x, 1 / n) : Math.pow(x, 1 / n)))"};for(const t of[gt])Object.setPrototypeOf(t,null);const dt="([{",yt=")]}";function xt(t,e){let n=0;for(let s=e;s<t.length;s++)if(dt.includes(t[s]))n++;else if(yt.includes(t[s])&&0===--n)return s;return-1}function bt(t){if(!t.trim())return[];const e=[];let n=0,s=0;for(let r=0;r<t.length;r++)dt.includes(t[r])?n++:yt.includes(t[r])?n--:","===t[r]&&0===n&&(e.push(t.slice(s,r).trim()),s=r+1);return e.push(t.slice(s).trim()),e}function wt(t,e,n){const s=[...t.matchAll(e)];for(let e=s.length-1;e>=0;e--){const r=s[e],i=r.index+r[0].length-1,o=xt(t,i);if(o<0)continue;const a=n(bt(t.slice(i+1,o)),r,t.slice(o+1));if(null==a)continue;const[l,c=0]=Array.isArray(a)?a:[a];if((t=t.slice(0,r.index)+l+t.slice(o+1+c)).length>1e5)throw new Error("The expression expands too much when read")}return t}const _t=t=>new RegExp(`(?<![\\w.])(${t})\\s*\\(`,"g"),Mt=t=>`(${t})`,vt=t=>/^\[.*\]$/s.test(t.trim())?`{${t.trim().slice(1,-1)}}`:t;const At={IF:t=>t.length>=2&&`((${t[0]}) ? (${t[1]}) : (${t[2]??"false"}))`,AND:t=>t.length&&`(${t.map(Mt).join(" & ")})`,OR:t=>t.length&&`(${t.map(Mt).join(" ∨ ")})`,NOT:t=>1===t.length&&`(!(${t[0]}))`,XOR:t=>2===t.length&&`((${t[0]}) \\xor (${t[1]}))`,LOG:t=>2===t.length?`log_{${t[1]}}(${t[0]})`:1===t.length&&`log_{10}(${t[0]})`,ATAN2:t=>2===t.length&&`atan2(${t[1]}, ${t[0]})`,INT:t=>1===t.length&&`floor(${t[0]})`,FIXED:t=>(1===t.length||2===t.length)&&`fixed(${t[0]}, ${t[1]??2})`,"FLOOR.MATH":t=>1===t.length&&`floor(${t[0]})`,"CEILING.MATH":t=>1===t.length&&`ceil(${t[0]})`,FACT:t=>1===t.length&&`((${t[0]})!)`,COMBIN:t=>2===t.length&&`comb(${t.join(", ")})`,PERMUT:t=>2===t.length&&`perm(${t.join(", ")})`,AVERAGE:t=>`mean(${t.join(", ")})`,SUM:t=>`sum(${t.join(", ")})`,PRODUCT:t=>`prod(${t.join(", ")})`,MAX:t=>`max(${t.join(", ")})`,MIN:t=>`min(${t.join(", ")})`,MEDIAN:t=>`median(${t.join(", ")})`,"STDEV.P":t=>`stdev(${t.join(", ")})`,STDEVP:t=>`stdev(${t.join(", ")})`,CEILING:t=>(1===t.length||2===t.length&&"1"===t[1].trim())&&`ceil(${t[0]})`,RAND:t=>!t.length&&"random()",ISNUMBER:t=>1===t.length&&`((${t[0]}) ∈ ℝ)`,LOG10:t=>1===t.length&&`log_{10}(${t[0]})`};function Et(t,e){for(let n=e,s=0;n>=0;n--)if(")"===t[n])s++;else if("("===t[n]&&0===--s)return n;return-1}function Nt(t){const e="(?:[\\p{L}_][\\p{L}\\p{N}_.]*|\\d+(?:\\.\\d+)?|§\\d+§)";return t=function(t,e){const n=new RegExp(`^(?:${e})`,"u"),s=new RegExp(`(?:${e})$`,"u"),r=/[\p{L}_][\p{L}\p{N}_.]*$/u;for(let e=t.indexOf("^");e>=0;e=t.indexOf("^",e+1)){let i,o=e+1;for(;/\s/.test(t[o]??"");)o++;if("("===t[o])i=xt(t,o)+1;else{const e=n.exec(t.slice(o));i=e?o+e[0].length:0,e&&"("===t[i]&&(i=xt(t,i)+1)}if(i<=o||!/^\s*\^/.test(t.slice(i)))continue;let a,l=e;for(;l>0&&/\s/.test(t[l-1]);)l--;if(")"===t[l-1]){a=Et(t,l-1);const e=a>0&&r.exec(t.slice(Math.max(0,a-64),a));e&&(a-=e[0].length)}else{const e=s.exec(t.slice(Math.max(0,l-64),l));a=e?l-e[0].length:-1}a<0||(t=`${t.slice(0,a)}(${t.slice(a,i)})${t.slice(i)}`,e=i+1)}return t}(t=(t=(t=t.replace(/^\s*=/,"").replace(/(?<![\w.])_xlfn\./g,"")).replace(/&/g,"+")).replace(new RegExp(`(^|[(,=<>*/+^-]\\s*)-\\s*(${e})(?=\\s*\\^)`,"gu"),"$1(-$2)"),e),wt(t,/(?<![\w.])([A-Z][A-Z0-9]*(?:\.[A-Z]+)?)\s*\(/g,(t,e)=>At[e[1]]?.(t)||null)}const Ot={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"},kt="strtktk[A-J]+";function It(t){for(let e=!0;e;){const n=t;e=(t=t.replace(new RegExp(`(${kt})\\s*\\|\\|\\s*(${kt})`,"g"),"$1 + $2"))!==n}const e=new RegExp(`^\\(typeof\\(([^()]*)\\)\\s+IN\\s+\\(${kt},\\s*${kt}\\)\\s+AND\\s+(.*)\\)$`,"s");for(let n=t.lastIndexOf("(typeof(");n>=0;n=n>0?t.lastIndexOf("(typeof(",n-1):-1){const s=xt(t,n),r=s>0&&e.exec(t.slice(n,s+1));if(!r)continue;const[,i,o]=r,a=new Map([[`${i} = TRUNC(${i})`,"ℤ"],[`${i} = TRUNC(${i}) AND ${i} > 0`,"ℕ"],[`ABS(${i}) < ∞`,"ℝ"]]).get(o.trim());a&&(t=`${t.slice(0,n)}((${i}) ∈ ${a})${t.slice(s+1)}`)}t=wt(t,/(?<![\w.])CAST\s*\(/gi,t=>{const e=1===t.length&&/^(.*)\s+AS\s+(?:REAL|FLOAT|DOUBLE(?:\s+PRECISION)?|NUMERIC|DECIMAL|INTEGER|INT)\s*$/is.exec(t[0]);return e?`(${e[1]})`:null}),t=(t=(t=wt(t=function(t){for(let e=0;e<50;e++){const e=[...t.matchAll(/\bCASE\s+WHEN\b/gi)];if(!e.length)return t;const n=e[e.length-1].index,s=/\bEND\b/i.exec(t.slice(n));if(!s)return t;const r=t.slice(n+4,n+s.index).split(/\b(WHEN|THEN|ELSE)\b/i).map(t=>t.trim()),i=[];let o="null";for(let t=1;t<r.length;t+=2){const e=r[t].toUpperCase();"WHEN"===e?i.push([r[t+1],r[t+3]]):"ELSE"===e&&(o=r[t+1])}const a=i.reduceRight((t,[e,n])=>`((${e}) ? (${n}) : ${t})`,Mt(o));t=t.slice(0,n)+a+t.slice(n+s.index+3)}return t}(t=t.replace(/(?<![\w.])ARRAY\s*\[/g,"[")),/(?<![\w.])LOG\s*\(/g,t=>2===t.length?`log_{${t[0]}}(${t[1]})`:`log_{10}(${t[0]})`)).replace(/(?<![\w.])PI\s*\(\s*\)/g,"π")).replace(/(?<![\w.])([A-Z][A-Z0-9]*)(?=\s*\()/g,t=>Ot[t]??t);for(const[e,n]of[[/\bNOT\s+IN\s*\(/g,"∉"],[/\bIN\s*\(/g,"∈"]])for(let s=e.exec(t);s;s=e.exec(t)){const r=s.index+s[0].length-1,i=xt(t,r);if(i<0)break;t=`${t.slice(0,s.index)}${n} {${t.slice(r+1,i)}}${t.slice(i+1)}`,e.lastIndex=0}return t.replace(/<>/g," ≠ ")}const St={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"},jt={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 qt={inf:"∞",nan:"NaN"};function zt(t){return(t=(t=function(t){return t=t.replace(/(?<![\w.])sympy\.Interval\.(open|Lopen|Ropen)\s*\(/g,(t,e)=>`sympy_interval_${e}(`),t=t.replace(/(?<![\w.])sympy\.S\.(\w+)/g,(t,e)=>Tt[e]??t),t=t.replace(/(?<![\w.])sympy\.(Reals|Integers|Naturals0?|Rationals|Complexes)\b/g,(t,e)=>Tt[e]),t.replace(/(?<![\w.])sympy\.(\w+)/g,(t,e)=>Ct[e]??Rt[e]??t)}(t=(t=(t=(t=(t=(t=(t=t.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,(t,e)=>St[e]?`Math.${St[e]}`:jt[e]?jt[e]:qt[e]??t)).replace(/(?<![\w.])(?:math|Math)\.(factorial|isfinite|isclose|prod|inf|nan|abs|trunc)\b/g,(t,e)=>qt[e]??e)).replace(/(?<![\w.])Number\.(isInteger|isFinite)\b/g,(t,e)=>e.toLowerCase())).replace(/(?<![\w.])scipy\.(?:special|integrate)\.(\w+)/g,"$1"))).replace(/\bMZ_INFINITY\b/g,"∞")).replace(/(?<![\w.])mz_(?=\w+\s*\()/g,"")}const Rt={pi:"π",E:"e",oo:"∞",true:"true",false:"false",nan:"NaN",I:"i"},Tt={Reals:"ℝ",Integers:"ℤ",Naturals:"ℕ",Naturals0:"ℕ",Rationals:"ℚ",Complexes:"ℂ"},Ct={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",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:""},Pt={open:"()",Lopen:"(]",Ropen:"[)"};const Zt=t=>{const e=/^\((.*)\)$/s.exec(t.trim());return e?bt(e[1]):null},Ft=t=>e=>2===e.length&&`${t[0]}${e[0]}, ${e[1]}${t[1]}`,Lt=t=>Zt(t)??[t],Ut={where:t=>3===t.length&&`((${t[0]}) ? (${t[1]}) : (${t[2]}))`,logical_and:t=>2===t.length&&`((${t[0]}) & (${t[1]}))`,logical_or:t=>2===t.length&&`((${t[0]}) ∨ (${t[1]}))`,logical_xor:t=>2===t.length&&`((${t[0]}) \\xor (${t[1]}))`,logical_not:t=>1===t.length&&`(!(${t[0]}))`,isin:t=>2===t.length&&`((${t[0]}) ∈ ${vt(t[1])})`,contains:t=>2===t.length&&`((${t[1]}) ∈ ${vt(t[0])})`,isclose:t=>t.length>=2&&`((${t[0]}) ≈ (${t[1]}))`,isfinite:t=>1===t.length&&`((${t[0]}) ∈ ℝ)`,isinteger:t=>1===t.length&&`((${t[0]}) ∈ ℤ)`,factorial:t=>1===t.length&&`((${t[0]})!)`,union:t=>2===t.length&&`((${t[0]}) ∪ (${t[1]}))`,union_:t=>2===t.length&&`((${t[0]}) ∪ (${t[1]}))`,intersection:t=>2===t.length&&`((${t[0]}) ∩ (${t[1]}))`,sq:t=>1===t.length&&`((${t[0]})^2)`,cube:t=>1===t.length&&`((${t[0]})^3)`,fract:t=>1===t.length&&`((${t[0]}) - floor(${t[0]}))`,inversesqrt:t=>1===t.length&&`(1/sqrt(${t[0]}))`,mod:t=>2===t.length&&`((${t[0]}) \\mod (${t[1]}))`,atan:t=>2===t.length&&`atan2(${t[0]}, ${t[1]})`,exp2:t=>1===t.length&&`((2)^(${t[0]}))`,trunc:t=>1===t.length&&`((${t[0]}) < 0 ? (ceil(${t[0]})) : floor(${t[0]}))`,vec2:t=>`(${t.join(", ")})`,vec3:t=>`(${t.join(", ")})`,vec4:t=>`(${t.join(", ")})`,derivative:t=>t.length>=2&&`der(${t.join(", ")})`,sympy_rational:t=>2===t.length&&`((${t[0]})/(${t[1]}))`,sympy_value:t=>1===t.length&&`(${t[0]})`,sympy_eq:t=>2===t.length&&`((${t[0]}) = (${t[1]}))`,sympy_ne:t=>2===t.length&&`((${t[0]}) ≠ (${t[1]}))`,sympy_and:t=>t.length&&`(${t.map(Mt).join(" & ")})`,sympy_or:t=>t.length&&`(${t.map(Mt).join(" ∨ ")})`,sympy_not:t=>1===t.length&&`(!(${t[0]}))`,sympy_xor:t=>2===t.length&&`((${t[0]}) \\xor (${t[1]}))`,sympy_nand:t=>2===t.length&&`((${t[0]}) \\nand (${t[1]}))`,sympy_nor:t=>2===t.length&&`((${t[0]}) \\nor (${t[1]}))`,sympy_piecewise:t=>{const e=t.map(Zt);return!e.length||e.some(t=>!t||2!==t.length)?null:e.reduceRight((t,[e,n])=>null===t||/^True$|^true$/.test(n.trim())&&void 0===t?`(${e})`:`((${n}) ? (${e}) : ${t??"(null)"})`,void 0)},sympy_set:t=>`{${t.join(", ")}}`,sympy_interval:Ft("[]"),sympy_interval_open:Ft("()"),sympy_interval_Lopen:Ft("(]"),sympy_interval_Ropen:Ft("[)"),sympy_contains:t=>2===t.length&&`((${t[0]}) ∈ ${t[1]})`,sympy_list_gcd:t=>1===t.length&&`gcd(${t[0].trim().replace(/^\[|\]$/g,"")})`,sympy_root:t=>2===t.length&&`root(${t[1]}, ${t[0]})`,sympy_integrate:t=>{if(2!==t.length)return null;const e=Lt(t[1]);return 3===e.length?`int(${t[0]}, ${e.join(", ")})`:1===e.length?`int(${t[0]}, ${e[0]})`:null},sympy_limit:t=>t.length>=3&&`lim(${t.slice(0,3).join(", ")}${t[3]?`, ${t[3]}`:""})`,sympy_summation:t=>{if(3===t.length&&/^\s*[A-Za-z]\w*\s*==/.test(t[1]))return`sum(${t[0]}, ${t[1].replace("==","=")}, ${t[2]})`;const e=2===t.length&&Lt(t[1]);return 3===e?.length&&`(\\sum_{${e[0]}=${e[1]}}^{${e[2]}} (${t[0]}))`},sympy_product:t=>{if(3===t.length&&/^\s*[A-Za-z]\w*\s*==/.test(t[1]))return`prod(${t[0]}, ${t[1].replace("==","=")}, ${t[2]})`;const e=2===t.length&&Lt(t[1]);return 3===e?.length&&`(\\prod_{${e[0]}=${e[1]}}^{${e[2]}} (${t[0]}))`},limit:t=>t.length>=3&&`lim(${t.join(", ")})`,summation:t=>3===t.length&&/^\s*[A-Za-z]\w*\s*==/.test(t[1])&&`sum(${t[0]}, ${t[1].replace("==","=")}, ${t[2]})`,sum:Dt("sum"),prod:Dt("prod")};function Dt(t){return e=>{const n=1===e.length&&/^(.*?)\s+for\s+(\w+)\s+in\s+range\((.*)\)\s*$/s.exec(e[0]);if(!n)return null;const s=bt(n[3]),[r,i]=1===s.length?["0",s[0]]:s,o=/\s*\+\s*1$/.test(i)?i.replace(/\s*\+\s*1$/,""):`(${i}) - 1`;return`(\\${t}_{${n[2]}=${r}}^{${o}} (${n[1]}))`}}function Wt(t){t=function(t){for(let e=t.lastIndexOf("(lambda");e>=0;e=e>0?t.lastIndexOf("(lambda",e-1):-1){const n=xt(t,e);if(n<0||"("!==t[n+1])continue;const s=xt(t,n+1),r=/^\(lambda\s+([\w\s,]+?)\s*:\s*([\s\S]*)\)$/.exec(t.slice(e,n+1));if(s<0||!r)continue;const i=r[1].split(",").map(t=>t.trim()),o=bt(t.slice(n+2,s));if(o.length!==i.length||!i.every(t=>/^[A-Za-z_]\w*$/.test(t)))continue;const a=new Map(i.map((t,e)=>[t,o[e]])),l=r[2].replace(new RegExp(`(?<![\\w.])(${i.join("|")})(?!\\w)`,"g"),t=>`(${a.get(t)})`);if((t=t.slice(0,e)+`(${l})`+t.slice(s+1)).length>1e5)throw new Error("The expression expands too much when read")}return t}(t),t=wt(t,_t("quad"),(t,e,n)=>{const s=/^lambda\s+(\w+)\s*:\s*(.*)$/s.exec(t[0]??"");if(!s||3!==t.length)return null;const r=/^\s*\[\s*0\s*\]/.exec(n);return[`int(${s[2]}, ${s[1]}, ${t[1]}, ${t[2]})`,r?r[0].length:0]}),t=wt(t,_t(Object.keys(Ut).join("|")),(t,e)=>Ut[e[1]](t)||null);for(let e=(t=wt(t,_t("float"),(t,e,n)=>{const s=/^\s*\.is_integer\(\s*\)/.exec(n);return s&&1===t.length?[`((${t[0]}) ∈ ℤ)`,s[0].length]:null})).lastIndexOf(".includes(");e>=0;e=e>0?t.lastIndexOf(".includes(",e-1):-1){const n=e+9,s=xt(t,n);let r=e;if(yt.includes(t[e-1])){let n=0;for(r=e-1;r>=0;r--)if(yt.includes(t[r]))n++;else if(dt.includes(t[r])&&0===--n)break}else for(;r>0&&/[\w.]/.test(t[r-1]);)r--;s<0||r<0||r===e||(t=`${t.slice(0,r)}((${t.slice(n+1,s)}) ∈ ${vt(t.slice(r,e))})${t.slice(s+1)}`)}return t}for(const t of[At,Ot,St,jt,Rt,Tt,Ct,Pt,Ut,qt])Object.setPrototypeOf(t,null);const Ht=String.raw`(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}|(?<![\w.′^])[\w.′^]+)`,Gt=t=>t.trim().split(/\s+/).join(String.raw`\s+`),Bt=t=>new RegExp(String.raw`(?<![\w.])${Gt(t)}(?![\w.])`,"gi"),Xt=[["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","="]],Qt="[<>≤≥=≠≈]",Vt={second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10};Object.setPrototypeOf(Vt,null);const Yt=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","hyperbolic sine":"sinh","hyperbolic cosine":"cosh","hyperbolic tangent":"tanh",floor:"floor",ceiling:"ceil"}).sort((t,e)=>e[0].length-t[0].length),Kt=[["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","∈ ℚ"]],Jt=/(?<![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;Xt.map(([t])=>t),Kt.map(([t])=>t),Yt.map(([t])=>`${t} of`);const te=N([[" 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 ","→"],["===","=...="]]),ee=N([...S,...function(){const t=[],e=(e,n)=>{t.push([e,n],[e+"(",n+"("])};for(const n of["sin","cos","tan","cot","csc","sec"])if(t.push(["Math."+n+"(",n+"("],["\\"+n+"(",n+"("],["\\"+n,n]),["sin","cos","tan"].includes(n))for(const t of["","h"]){const s=n+t,r="arc"+n+t;t&&(e("Math."+s,s),e("\\"+s,s));for(const n of["^-1","^{-1}","-1"])e("\\"+s+n,r),e(s+n,r),t||e("Math."+s+n,r);t||e("\\a"+s,r),e("\\arc"+s,r),e("Math.a"+s,r),e("Math.arc"+s,r)}return t}()]),ne=[["code",function(t){return/^\s*=|[(.%^<_eE]|\|\||\bif\b|\b(?:True|False|None|TRUE|FALSE|NULL)\b/.test(t)?(/^\s*=(?!=)/.test(t)&&(t=Nt(t)),t=function(t){for(const[e,n]of Object.entries(gt))for(let s=t.lastIndexOf(n);s>=0;s=s>0?t.lastIndexOf(n,s-1):-1){const r=s+n.length,i="("===t[r]?xt(t,r):-1;if(i<0)continue;let o=t.slice(r+1,i);"gcd"===e&&(o=o.trim().replace(/^\[|\]$/g,""));const a="factorial"===e?`((${o})!)`:`${e}(${o})`;t=t.slice(0,s)+a+t.slice(i+1)}for(let e=t.lastIndexOf(").toFixed(");e>=0;e=e>0?t.lastIndexOf(").toFixed(",e-1):-1){const n=e+10-1,s=xt(t,n),r=t.lastIndexOf("Number(",e);s<0||r<0||xt(t,r+7-1)!==e||(t=t.slice(0,r)+`fixed(${t.slice(r+7,e)}, ${t.slice(n+1,s)})`+t.slice(s+1))}return t.replace(/\(\(\)=>\{let (sum|prod) = [01]; let loopCount = 0; for \(let (\w+)=(.*?);\2<=(.*?);\2\+\+\) \{if \(loopCount\+\+ > 1000000\)\{break\};\1 [+*]= (.*?);\}; return \1;\}\)\(\)/g,(t,e,n,s,r,i)=>`(\\${"sum"===e?"sum":"prod"}_{${n}=${s}}^{${r}} (${i}))`)}(t),t=function(t){for(let e=0;e<50;e++){let e=!0;for(const n of t.matchAll(/\bif\b/g)){const s=n.index;let r=0,i=-1,o=t.length;for(let e=s+2;e<t.length;e++)if(dt.includes(t[e]))r++;else{if(yt.includes(t[e])&&--r<0){o=e;break}if(0===r&&","===t[e]){o=e;break}if(0===r&&/^then\b/.test(t.slice(e))&&/\W/.test(t[e-1])){i=-2;break}0===r&&i<0&&/^else\b/.test(t.slice(e))&&/\W/.test(t[e-1])&&(i=e)}if(i<0)continue;r=0;let a=0;for(let e=s-1;e>=0;e--)if(yt.includes(t[e]))r++;else{if(dt.includes(t[e])&&--r<0){a=e+1;break}if(0===r&&","===t[e]){a=e+1;break}}const l=t.slice(a,s).trim();if(!l)continue;const c=`((${t.slice(s+2,i).trim()}) ? (${l}) : (${t.slice(i+4,o).trim()}))`;t=t.slice(0,a)+c+t.slice(o),e=!1;break}if(e)return t}return t}(t=Wt(t=function(t){return t.includes("sorted")?wt(t,/(?<![\w.])sorted\s*\(/g,t=>{if(1!==t.length)return null;const e=t[0];for(let t=0,n=0;t<e.length;t++)if("([{".includes(e[t]))n++;else if(")]}".includes(e[t]))n--;else if(0===n&&("|"===e[t]||"&"===e[t])){const n=t=>{const e=t.trim(),n=/^set\s*\(/.exec(e);return n&&xt(e,n[0].length-1)===e.length-1?e.slice(n[0].length,-1):null},[s,r]=[n(e.slice(0,t)),n(e.slice(t+1))];return null!==s&&null!==r?`((${s}) ${"|"===e[t]?"∪":"∩"} (${r}))`:null}return null}):t}(t=zt(t=It(t=(t=t.replace(/(?<![\w.])9e999\b/g,"∞")).replace(/(?<![\w.])(\d+(?:\.\d+)?)[eE]([+-]?\d+)(?![\w.])/g,"($1*10^{$2})")))))),(t=(t=t.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 ")):t}],["english",function(t){if(!Jt.test(t))return t;let e=t;const n=(t,n,s,r="∈")=>{e=e.replace(new RegExp(String.raw`(?<![\w.])${Gt(t)}\s+(${Ht})\s+(?:and|to)\s+(${Ht})(?:\s+(inclusive|exclusive))?(?![\w.])`,"gi"),(t,e,i,o)=>{const[a,l]="exclusive"===o?.toLowerCase()?["(",")"]:"inclusive"===o?.toLowerCase()?["[","]"]:[n,s];return` ${r} ${a}${e}, ${i}${l} `})};n("is not strictly between","(",")","∉"),n("is not between","[","]","∉"),n("is strictly between","(",")"),n("is between","[","]"),n("between","[","]"),e=e.replace(new RegExp(String.raw`(?<![\w.])is\s+(not\s+)?in\s+the\s+(open|closed|half-open)\s+interval\s+from\s+(${Ht})\s+to\s+(${Ht})`,"gi"),(t,e,n,s,r)=>{const[i,o]={open:["(",")"],closed:["[","]"],"half-open":["[",")"]}[n.toLowerCase()];return` ${e?"∉":"∈"} ${i}${s}, ${r}${o} `});const s=String.raw`(${Ht})\s+`;e=e.replace(new RegExp(s+String.raw`is\s+(not\s+)?within\s+(${Ht})\s*(%|\s+percent)?\s+of\s+(${Ht})`,"gi"),(t,e,n,s,r,i)=>`(abs((${e}) - (${i})) ${n?">":"≤"} ${r?`(${s})/100 * ${/^\d+(\.\d+)?$/.test(i)?i:`abs(${i})`}`:`(${s})`})`),e=e.replace(new RegExp(s+String.raw`is\s+(?:a\s+)?multiple\s+of\s+(${Ht})`,"gi"),"(($1) mod ($2) = 0)"),e=e.replace(new RegExp(s+String.raw`is\s+(not\s+)?divisible\s+by\s+(${Ht})`,"gi"),(t,e,n,s)=>`((${e}) mod (${s}) ${n?"≠":"="} 0)`),e=e.replace(new RegExp(String.raw`(${Ht})\s+divides\s+(${Ht})`,"gi"),"(($2) mod ($1) = 0)"),e=e.replace(new RegExp(s+String.raw`is\s+(not\s+)?(even|odd)(?![\w.])`,"gi"),(t,e,n,s)=>`((${e}) mod 2 ${"even"===s.toLowerCase()!==Boolean(n)?"=":"≠"} 0)`);for(const[t,n]of Kt)e=e.replace(Bt(t),` ${n} `);e=e.replace(Bt("is not in")," ∉ ").replace(Bt("is in")," ∈ ").replace(Bt("is an element of")," ∈ ");for(const[t,n]of Xt)e=e.replace(Bt(t),` ${n} `);e=e.replace(Bt("is not")," ≠ "),e=e.replace(/(?<=[\w.)\]}′]\s+)is(?=\s+[\w.(\[{-])/gi," = ");for(let t=!0;t;){const n=e;e=e.replace(new RegExp(String.raw`(${Ht})\s*(${Qt})\s*(${Ht})\s+(and|or)\s+(${Qt})`,"gi"),"$1 $2 $3 $4 $1 $5"),t=e!==n}e=e.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?absolute\s+value\s+of\s+(${Ht})`,"gi"),"abs($1)"),e=e.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?square\s+root\s+of\s+(${Ht})`,"gi"),"sqrt($1)"),e=e.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?cube\s+root\s+of\s+(${Ht})`,"gi"),"root(3, $1)"),e=e.replace(new RegExp(String.raw`(${Ht})\s+to\s+the\s+power\s+of\s+(${Ht})`,"gi"),"($1)^($2)"),e=e.replace(new RegExp(String.raw`(${Ht})\s+to\s+the\s+(${Object.keys(Vt).join("|")}|(\d+|n)(?:st|nd|rd|th))(?:\s+power)?(?![\w.])`,"gi"),(t,e,n,s)=>`(${e})^(${Vt[n.toLowerCase()]??s})`),e=e.replace(new RegExp(String.raw`(${Ht})\s+to\s+the\s+(${Ht})(?![\w.])`,"gi"),"($1)^($2)");for(const[t,n]of Yt)e=e.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?${Gt(t)}\s+of\s+(${Ht})`,"gi"),`${n}($1)`);e=e.replace(new RegExp(String.raw`(${Ht})\s+squared(?![\w.])`,"gi"),"($1)^2"),e=e.replace(new RegExp(String.raw`(${Ht})\s+cubed(?![\w.])`,"gi"),"($1)^3"),e=e.replace(new RegExp(String.raw`(?<![\w.])half\s+of\s+(${Ht})`,"gi"),"($1)/2"),e=e.replace(new RegExp(String.raw`(?<![\w.])twice\s+(${Ht})`,"gi"),"2*($1)"),e=e.replace(new RegExp(String.raw`(\d+(?:\.\d+)?)\s+percent(?![\w.])`,"gi"),"$1%");const r=t=>new RegExp(String.raw`(?<=[\w.′)\]}]\s+)${Gt(t)}(?=\s+[\w.(\[{-])`,"gi");for(const[t,n]of[["divided by","/"],["over","/"],["multiplied by","*"],["times","*"],["plus","+"],["minus","-"],["modulo","mod"]])e=e.replace(r(t),` ${n} `);return e}],["words",te],["spaced",function(t){t=function(t){for(let e=t.lastIndexOf("\\sqrt");e>=0;e=e>0?t.lastIndexOf("\\sqrt",e-1):-1){let n=e+5;if(/[A-Za-z]/.test(t[n]??""))continue;for(;j(t[n]);)n++;const s=t.slice(n);let r=/^(?:§\d+§|-?(?:\d+(?:\.\d+)?|\.\d+)|-?[A-Za-zͰ-Ͽ])/.exec(s)?.[0];if(!r&&/^\\[A-Za-z]/.test(s)&&!s.startsWith("\\left")){let t=/^\\[A-Za-z]+/.exec(s)[0].length;if(/^\d\d/.exec(s.slice(t))&&/frac$/.test(s.slice(0,t)))t+=2;else{const e=/^\s*\[[^\[\]{}]*\]/.exec(s.slice(t));for(e&&(t+=e[0].length);;){let e=t;for(;j(s[e]);)e++;if("{"!==s[e])break;let n=0,r=-1;for(let t=e;t<s.length;t++)if("{"===s[t])n++;else if("}"===s[t]&&0===--n){r=t;break}if(r<0)break;t=r+1}}r=s.slice(0,t)}r&&(t=`${t.slice(0,e)}\\sqrt{${r}}${t.slice(n+r.length)}`)}return t}(function(t){return t=t.replace(Z,(t,e,n)=>`(${e}+${P[n]})`),t=t.replace(F,(t,e,n,s)=>Number(n)<Number(s)&&3!==n.length?`(${e}+${n}/${s})`:t),t.replace(L,(t,e,n,s,r,i)=>{const[o,a]=[n??r,s??i];return Number(o)<Number(a)?`(${e}+\\frac{${o}}{${a}})`:t})}(function(t){return t.replace(C,t=>{const e=t[0]in R;return`${e?"^":"_"}{${[...t].map(t=>(e?R:T)[t]).join("")}}`})}(t))),t=B(t=function(t){for(let e=0;e<t.length;e++){const n=n=>t.slice(Math.max(0,e-n),e+1);if("t"===t[e]&&"\\text"===n(4)&&"{"===t[e+1]){let n=1,s=e+2,r="";for(;n>0&&s<t.length;)"{"===t[s]?n++:"}"===t[s]?n--:r+=t[s],s++;t=t.slice(0,e-4)+r+t.slice(s)}}return t}(t=(t=(t=function(t){for(let e=0;e<100;e++){const e=[...t.matchAll(/\bif\b/gi)];if(!e.length)return t;const n=e[e.length-1].index,s=W(t,n+2,"then");if(s<0)return t;const r=t.slice(n+2,s),i=W(t,s+4,"else"),o=H(t,i<0?s+4:i+4),a=t.slice(s+4,i<0?o:i),l=i<0?"unchanged":t.slice(i+4,o).trim();t=`${t.slice(0,n)}((${r.trim()}) ? (${a.trim()}) : (${l}))${t.slice(o)}`}return t}(t)).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 e=0;e<t.length-1;e++)if("?"===t[e]&&":"!==t[e+1])t=G(t,e);else if("_"===t[e]||"^"===t[e]){const n=/^§\d+§/.exec(t.slice(e+1));if(n){t=`${t.slice(0,e+1)}{${n[0]}}${t.slice(e+1+n[0].length)}`;continue}const s=("^"===t[e]||/[A-Za-z}]/.test(t[e-1]??""))&&/^\\[A-Za-z]+(?![A-Za-z{\d])/.exec(t.slice(e+1));if(s){t=`${t.slice(0,e+1)}{${s[0]}}${t.slice(e+1+s[0].length)}`;continue}let r=e+1;for("-"===t[r]&&r++;r<t.length&&".0123456789".includes(t[r]);)r++;if(r===e+2&&"-"===t[e+1]&&(r=e+1),"-"===t[e+1]&&/^\s*[\^!]/.test(t.slice(r,r+8)))continue;r>e+1&&(t=t.slice(0,e+1)+"{"+t.slice(e+1,r)+"}"+t.slice(r))}return t}],["squeeze",function(t){return t.replace(/\s+/g,(e,n)=>{const s=t[n-1]??"",r=t[n+e.length]??"";return"Δ"===s?"":/[A-Za-z\u0370-\u03FF′]/.test(s)&&/[A-Za-z\u0370-\u03FF]/.test(r)?" ":""})}],["symbols",ee],["bar",function(t){let e=0;for(let n=t.indexOf(h,e);n>=0;n=t.indexOf(h,e)){let s=0,r=-1;for(let e=n+1;e<t.length;e++)if("([{".includes(t[e]))s++;else if(")]}".includes(t[e]))s--;else if(0===s&&t.startsWith("|_",e)){r=e;break}r<0&&se(),t=`${t.slice(0,n+1)}(${t.slice(n+1,r)})${t.slice(r)}`,e=n+1}return t}],["compact",function(t){if(t=function(t){for(let e=0;e<t.length;e++){const n=e>0&&nt.test(t[e-1]);let s,r=null,i=e;if(t.startsWith("frac{",e)){const n=st(t,e+4),s=n&&st(t,n[1]);r=s&&it(n[0],s[0]),r&&(i=s[1])}else if("d"===t[e]&&!n){let[n,s]=rt(t,e+1),o="";if(nt.test(t[s]??"")&&"/"===t[s+1]&&(o=t[s++]),"/"===t[s]&&"d"===t[s+1]&&nt.test(t[s+2]??"")){const e=t[s+2],[,a]=rt(t,s+3);r={n:n,of:o,by:e},i=a}}if(r){if(r.of)s=at(r.of,r.by,r.n);else{const[e,n]=ot(t,i);if(!e)continue;s=at(e,r.by,r.n),i=n}t=t.slice(0,e)+s+t.slice(i),e+=3}}return t}(t=function(t){for(let e=t.indexOf(")′");e>=0;e=t.indexOf(")′",e+1)){let n=0,s=-1;for(let r=e;r>=0;r--)if(")"===t[r])n++;else if("("===t[r]&&0===--n){s=r;break}if(s<0)continue;for(;s>0&&/[A-Za-z\u0370-\u03FF′]/.test(t[s-1]);)s--;let r=0;for(;"′"===t[e+1+r];)r++;t=t.slice(0,s)+at(t.slice(s,e+1),"x",r)+t.slice(e+1+r),e=s}return t}(t=(t=B(t)).replace(/(?<![A-Za-z])frac(\d)(\d)/g,"frac{$1}{$2}"))),t.split("\\int").length>101)throw new Error("More than 100 integrals");for(let e=0;e<t.length;e++){const n=t[e],s=n=>t.slice(Math.max(0,e-n),e),r=n=>t.slice(Math.max(0,e-n),e+1);if("{"===n){if("\\begin"===s(6)){const n=Y(t.slice(e+1));n&&(t=t.slice(0,e-6)+n)}}else if("["===n)"\\sqrt"===s(5)?t=t.slice(0,e-5)+"sqrt"+Q(t.slice(e+1)):"sqrt"===s(4)&&(t=t.slice(0,e-4)+"sqrt"+Q(t.slice(e+1)));else if("⌊"===n||"⌈"===n)t=t.slice(0,e)+X(t.slice(e));else if("t"===n)"\\int"===r(3)&&(t=t.slice(0,e-3)+J(t.slice(e+1)));else if("m"===n)"\\binom"===r(5)&&(t=t.slice(0,e-5)+"\\binom"+et(t.slice(e+1)));else if("d"===n&&"dd"===r(1)&&"("===t[e+2]){const n=tt(t.slice(e+1));n&&(t=t.slice(0,e-1)+"der"+n)}}return(t=t.replace(/\\(?:text|textrm|textit|mathrm|mathit|mathbf|mathsf|operatorname)\{([A-Za-z])\}/g,"$1")).replace(/\\log/g,"log")}],["bars",function(t){for(let e=t.indexOf(h);e>=0;e=t.indexOf(h)){const n=se;t.startsWith("(der(",e+1)||n();const s=re(t,e+1,"(",")"),r=re(t,e+5,"(",")");(r<0||s!==r+1)&&n();const i=ie(t.slice(e+6,r));(i.length<2||i.length>3||!t.startsWith("|_",s+1))&&n();const o=s;let a,l;"{"===t[o+3]?(l=re(t,o+3,"{","}"),l<0&&n(),a=t.slice(o+4,l)):(l=o+3,a=t[l]??"");const[c,p,u]=i;a.trim()||n();const h=a.includes("=")?a:`${p}=${a}`;t=`${t.slice(0,e)}der(${c},${h}${u?`,${u}`:""})${t.slice(l+1)}`}return t}],["tidy",t=>t.replace(/ {2,}/g," ").trim()]],se=()=>{throw new Error("An evaluation bar (\\left. … \\right|_{x = a}) is read only after a derivative: \\left.\\frac{d}{dx} f\\right|_{x=a}")};function re(t,e,n,s){let r=0;for(let i=e;i<t.length;i++)if(t[i]===n)r++;else if(t[i]===s&&0===--r)return i;return-1}function ie(t){const e=[];let n=0,s=0;for(let r=0;r<t.length;r++)"([{".includes(t[r])?n++:")]}".includes(t[r])?n--:","===t[r]&&0===n&&(e.push(t.slice(s,r)),s=r+1);return e.push(t.slice(s)),e}function oe(t,e={}){if("string"!=typeof t)throw new Error("Expression must be a string");const{text:n,strings:s}=function(t){const e=new Map;let n="",s=0;for(;s<t.length;){const r=t[s];if('"'!==r&&"'"!==r&&"`"!==r){n+=t[s++];continue}let i=s+1,o="",a=!1;for(;i<t.length&&(a||t[i]!==r);)a=!a&&"\\"===t[i],o+=t[i++];const l=pt(e.size);e.set(l,r+o+r),n+=l,s=i+1}return{text:n,strings:e}}(ht(t));let r=n.replace(/\t/g," ");e.evaluate&&(r=function(t,e,n){const s=/\\[A-Za-z]/.test(t);let r=0;for(;;){let i=t.indexOf("{{",r);if(i<0)return t;let o=!1;const a=s&&ae.test(t.slice(0,i));if(le(t,i)||a&&"{"===t[i+2]?i+=1:o=a,!t.startsWith("{{",i)){r=i;continue}const l=ce(t,i);if(l<0)return t;let c=t.slice(i+2,l).trim();for(const[t,n]of e)c=c.split(t).join(n);try{let s=n(c);if(/^["'`]/.test(s)){const t=pt(e.size);e.set(t,s),s=t}const a=t.slice(0,i).trimEnd(),p=t.slice(l+2).trimStart();/^[\d.]/.test(s)&&(/[\d.]$/.test(a)||/^[\d.]/.test(p))&&(s=`(${s})`),o&&(s=`{${s}}`),t=t.slice(0,i)+" "+s+" "+t.slice(l+2),r=i+1+s.length}catch{r=l+2}}}(r,s,e.evaluate));const i=[["strings",r]];for(const[t,e]of ne){if(r=e(r),r.length>1e5)throw new Error("The expression expands too much when read");i.push([t,r])}return{cleaned:r,stringMap:s,steps:i}}const ae=/(?:\\[A-Za-z]+\*?|[\^_}\]])$/;function le(t,e){let n=0;for(;"\\"===t[e-1-n];)n++;return n%2==1}function ce(t,e){let n=0;for(let s=e+2;s<t.length;s++){if(t.startsWith("}}",s)&&0===n)return s;"{"===t[s]?n++:"}"===t[s]&&n--}return-1}const pe={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:"Ω"};for(const t of[pe])Object.setPrototypeOf(t,null);const ue=Object.keys($).filter(t=>100===$[t]&&/^[a-z]{2,}$/.test(t)),he=["frac"],$e=[...Object.keys(pe),"pi","tau","inf","infinity","exp"],fe="\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+/),me=new Set([...$e,...fe,"true","false","null","undefined","unchanged","deg","mod","pmod","NaN","Infinity"]),ge=/^[a-zA-ZͰ-Ͽ]$/,de=new Set(["f","g","h","u","v","F","G","H"]),ye=t=>ue.includes(t)||he.includes(t),xe=[...ue,...he,...$e].sort((t,e)=>e.length-t.length),be=[...ue,...he,"pi"].sort((t,e)=>e.length-t.length);function we(t,e=xe){const n=[];let s=0;for(;s<t.length;){const r=e.find(e=>t.startsWith(e,s))??t[s];n.push(r),s+=r.length}return n}function _e(t){if(ye(t))return!0;const e=we(t,be);return e.length>1&&ye(e[e.length-1])&&!me.has(t)}function Me(t,{mode:e="plain",followed:n=!0}={}){if(t.includes("′")&&/^[a-zA-Z′]+$/.test(t)&&!/^.′+$/.test(t))return t.match(/[a-zA-Z]′*/g);if(!((s=t).length>0&&[...s].every(t=>ge.test(t)))||1===t.length||me.has(t)||ye(t))return[t];var s;if("Δ"===t[0]&&2===t.length)return[t];if("latex"===e)return ve(we(t),n);if(t.length<=2)return[...t];const r=ve(we(t,be),n),i=r.findIndex(t=>t.length>1);if(i<0)return[t];if("pi"===r[i]&&!r.some(t=>ue.includes(t)))return 3===t.length?r:[t];const o=i;let a=0,l=0;for(const t of r.slice(i))a=1===t.length?a+1:0,l=Math.max(l,a);return o<=1&&l<=2?r:[t]}function ve(t,e){const n=t[t.length-1];return e||!ue.includes(n)?t:[...t.slice(0,-1),...n]}const Ae="§",Ee=/[A-Za-zͰ-Ͽ′]/,Ne=t=>/^[A-Za-zͰ-Ͽ][A-Za-zͰ-Ͽ′]*$/.test(t);function Oe(t,e="plain"){if("string"!=typeof t)throw new Error("Tokenizer input must be a string");const n=[];let s="";const i=t=>{s&&(Ne(s)?n.push(...function(t,e,n){if((t=>ut.test(t))(t))return[t];if(g.includes(e))return function(t,e){if(/^[a-zA-Z]′+$/.test(t))return[r+t];if("if"===t.toLowerCase())return["\\:if"];if(1===t.length)return de.has(t)?[r+t]:[t];if(f(t))return[t];const n=Me(t,{mode:e,followed:!0});return n.length>1?n:t.length<=2?[...t]:[r+t]}(t,n);const s=void 0!==e&&!/[+\-*/=<>),\]}|!≤≥≠]/.test(e);return Me(t,{mode:n,followed:s})}(s,t,e)):n.push(s),s="")};for(let e=0;e<t.length;e++){const o=t[e];if(o===Ae){i(o);const s=t.indexOf(Ae,e+1);if(s<0)throw new Error(`An unmatched ${Ae}`);const a=t.slice(e,s+1);n.push(g.includes(t[s+1])?r+a:a),e=s;continue}if(Ne(s)&&/[0-9]/.test(o)&&f(s+o)){const{op:r,end:i}=ke(t,e,s+o);n.push(r),s="",e=i;continue}if(Ee.test(o)&&"′"!==o&&y(s)&&(n.push(s),s=""),Ee.test(o)&&(""===s?"′"!==o:Ne(s)))s+=o;else if(/[0-9]/.test(o)&&Ne(s)&&!_e(s))s+=o;else if(Ne(s)&&i(" "===o?t[e+1]:o),"(){}[]".includes(o))s&&n.push(...Ie(s,o)),s="",n.push(o);else if("_"!==o&&" "!==o){if(f(s+o)){const{op:r,end:i}=ke(t,e,s+o);n.push(r),s="",e=i;continue}if(f(o)){i(o);const{op:s,end:r}=ke(t,e,o);n.push(s),e=r;continue}s+=o}else i(t[e+1]),"_"===o&&n.push("_")}if(i(void 0),n.some(t=>/^:/.test(t)))throw new Error("Unmatched ':'");return n}function ke(t,e,n){let s=e;for(;s+1<t.length&&f(n+t[s+1]);)n+=t[s+1],s++;return"!"===n&&"_"===t[s+1]&&s++,{op:n,end:s}}function Ie(t,e){if(!g.includes(e))return[t];if("\\"===t[0]){const e=t.slice(1);return[f(e)?e:r+e]}return y(t)?[t,"*"]:f(t)||ye(t)||y(t[0])?[t]:[r+t]}const Se=70,je=100,qe="%mod",ze=t=>g.includes(t),Re=t=>d.includes(t),Te=t=>i(t)||$[t]===je&&"_"!==t,Ce=new Set(["\\comb","\\perm","comb","perm"]),Pe={frac:"/","\\binom":"\\binom"},Ze=new Set(["<",">","≤","≥","=","==","===","≠","≠=","!=","!==","&","|","\\not","\\xor","∈","∉","true","false"]),Fe={"\\comb":"comb","\\perm":"perm",deg:"°","π":"pi","∨":"|"};class Le{constructor(t){this.tokens=t,this.pos=0,this.out=[],this.absDepth=0,this.frames=[]}peek(t=0){return this.tokens[this.pos+t]}next(){return this.tokens[this.pos++]}emit(...t){this.out.push(...t)}parseAll(){if(!this.tokens.length)throw new Error("Empty expression");this.parseExpression(0);const t=this.peek();if(void 0!==t)throw new Error(Re(t)?`Unmatched '${t}'`:`Unexpected '${t}'`);return this.out}parseExpression(t,e=!1){this.parseOperand(),this.absorb(t,e)}absorb(t,e=!1){for(;;){const n=this.peek();if(void 0===n||Re(n))return;const s=this.operatorAt(n,e);if(!s||s.lbp<=t)return;s.run()}}operatorAt(t,e){if("|"===t)return this.pipe();if(","===t)return{lbp:5,run:()=>{this.next(),this.frames.length&&(this.frames[this.frames.length-1].comma=!0),this.parseExpression(5),this.emit(",")}};if("?"===t)return{lbp:9,run:()=>this.ternary()};if("mod"===t)return{lbp:$.mod,run:()=>this.modulo()};if(t===qe)return{lbp:Se,run:()=>{this.next(),this.parseExpression(Se),this.emit("mod")}};if("pmod"===t)return{lbp:$.pmod,run:()=>{this.next(),this.parseScript(),this.emit("pmod")}};if("?:"===t)return{lbp:10,run:()=>{throw new Error("Unmatched ':'")}};if("!"===t)return{lbp:90,run:()=>{this.next(),this.emit("!")}};if("_"===t)return{lbp:je,run:()=>{this.next(),this.parseScript(),this.emit("_")}};if(Ce.has(t))return{lbp:je,run:()=>{this.next(),this.parseExpression(je),this.emit(t)}};const n=$[t];if("="===t&&void 0!==n)return{lbp:n,run:()=>this.equals(n)};if(void 0!==n&&!Te(t)&&"\\not"!==t&&!(t in Pe)){const e=m.has(t)?n-1:n;return{lbp:n,run:()=>{this.next(),this.parseExpression(e),this.emit(t)}}}return this.startsOperand(t)?this.implicit(t,e):null}implicit(t,e){return{lbp:e&&!Te(t)?71:Se,run:()=>{this.parseExpression(Se),this.emit("*")}}}startsOperand(t){return void 0===t||Re(t)||"|"===t?"|"===t:t!==qe&&(!!(ze(t)||Te(t)||t in Pe)||!f(t))}pipe(){if(this.absDepth>0)return null;let t=0;for(let e=this.pos;e<this.tokens.length;e++)"|"===this.tokens[e]&&t++;const e="|"===this.peek(1);return t%2==0&&!e&&this.startsOperand(this.peek(1))?this.implicit("|",!1):{lbp:$["|"],run:()=>{this.next(),e&&t%2==0&&this.next(),this.parseExpression($["|"]),this.emit("|")}}}modulo(){this.next(),this.parseExpression(Se,!0),this.emit("mod")}equals(t){this.next(),this.parseExpression(t),Ze.has(this.out[this.out.length-1])&&this.questionAhead()&&this.absorb(8),this.emit("=")}questionAhead(){let t=0;for(let e=this.pos;e<this.tokens.length;e++){const n=this.tokens[e];if(ze(n))t++;else if(Re(n)){if(0===t--)return!1}else{if(0===t&&","===n)return!1;if(0===t&&"?"===n)return!0}}return!1}ternary(){if(this.next(),this.parseExpression(10),"?:"!==this.next())throw new Error("Unmatched '?'");this.parseExpression(8),this.emit("?:")}parseOperand(){const t=this.next(),e=this.tokens[this.pos-2],n=this.peek();if(void 0===t)throw new Error("An operator is missing an operand at the end");if(ze(t))return this.bracket(t,"{"===t&&("∈"===e||"∉"===e));if("|"===t)return this.absolute();if("-"===t||"+"===t){return"^"===e&&(void 0===n||Re(n))||ze(e)&&Re(n)?this.emit("\\"+t):"+"===t?this.parseExpression(75):this.negate()}if("±"===t)return this.parseExpression(75),this.emit("pm");if("!"===t||"\\not"===t)return this.parseExpression(85),this.emit("\\not");if(t in Pe)return this.parseScript(),this.parseScript(),this.emit(Pe[t]);if("log"===t)return this.logarithm();if("lim"===t&&"_"===n)return this.limit();if(("\\sumidx"===t||"\\prodidx"===t)&&"_"===n)return this.bigOperator(t);if(Te(t))return this.functionCall(t);if(t===qe)throw new Error("'%' is missing an operand");if(Re(t)||f(t))throw new Error(`'${t}' is missing an operand`);this.emit(t)}negate(){const t=this.out.length;this.parseExpression(75);const e=this.out.slice(t);1!==e.length||!y(e[0])&&"∞"!==e[0]?this.emit("neg"):this.out[t]="-"+e[0]}bracket(t,e=!1){if(Re(this.peek()))return void this.emit("∅",t+this.next());this.frames.push({comma:!1}),this.parseExpression(0);const{comma:n}=this.frames.pop(),s=this.peek();Re(s)&&(this.next(),n?this.emit(t+s):e&&this.emit("{}"))}absolute(){this.absDepth++,this.parseExpression(0),this.absDepth--,"|"===this.peek()&&this.next(),this.emit("abs")}parseScript(){const t=this.peek();if(ze(t))return this.parseOperand();if("-"===t||"+"===t)return this.parseOperand();if(Te(t))return this.parseOperand();if(this.next(),void 0===t||Re(t)||f(t))throw new Error("Missing a sub- or superscript");this.emit(t)}logarithm(){"_"===this.peek()?(this.next(),this.parseScript()):this.emit("e"),this.argument(),this.emit("log")}limit(){this.next();const t=this.out.length;this.parseScript();const e=this.out.splice(t);this.parseExpression($["+"],!0),this.emit(...e,",","()","lim")}bigOperator(t){this.next();const e=this.out.length;this.parseScript();let n=this.out.splice(e);"^"===this.peek()&&(this.next(),this.parseScript(),n=[...n,...this.out.splice(e),","]),this.parseExpression($["+"],!0),this.emit(...n,",","()",t)}functionCall(t){if(void 0===this.peek())return this.emit(t);let e=null;if("^"===this.peek()){this.next();const t=this.out.length;this.parseScript(),e=this.out.splice(t)}if(0===o(t)?.arity&&!ze(this.peek()))return this.emit(t);this.argument(),this.emit(t),e&&this.emit(...e,"^")}argument(){const t=this.peek();if(ze(t))return this.next(),this.bracket(t);this.parseExpression(Se,!0)}}function Ue(t,e){t=function(t){const e=[];for(let n=0;n<t.length;n++){const s=t[n],i=t=>"string"==typeof t&&/^[a-zA-Z]$/.test(t);if(de.has(s)&&"^ { - 1 } ("===t.slice(n+1,n+7).join(" ")){e.push(r+s+"⁻¹"),n+=5;continue}const[o,a,l]=t.slice(n+1,n+4),c=i(a)?a!==s:y(a);i(s)&&"e"!==s&&"("===o&&c&&")"===l?e.push(r+s):e.push(s)}return e}(t);const n=[];for(const s of t)f(s)||ze(s)||Re(s)||"_"===s||i(s)||y(s)?n.push(s):n.push(...De(s,e));return n}function De(t,e){if("%"===t)return[qe];if(!t.includes("%"))return We(t,e);const n=t.split("%");n.length>1&&""===n[n.length-1]&&(n.pop(),n[n.length-1]+="%");const s=[];return n.forEach((t,n)=>{n>0&&s.push(qe),""!==t&&s.push(...We(t,e))}),s}function We(t,e){let n=0;for(;n<t.length&&y(t.slice(0,n+1));)n++;if(0===n||n===t.length)return[t];const s=t.slice(n);return"%"===s?[t]:[t.slice(0,n),...(r=s,Ue(Oe(r,e),e))];var r}for(const t of[Pe,Fe])Object.setPrototypeOf(t,null);const He=new Set(["()","[]","{}","(]","[)"]),Ge={pow:"^",sqrtpow:"root","\\binom":"comb","\\comb":"comb","\\perm":"perm",frac:"/","==":"=","!==":"≠=",...Object.fromEntries(Object.keys(u).map(t=>[t,"*"]))},Be=new Set(["round","fixed","der"]),Xe=t=>i(t)||100===$[t];function Qe(e){const n=[],s=t=>{if(!n.length)throw new Error(`'${t}' is missing an operand`);return n.pop()},r=t=>t.list?t.list:[t],i=(t,e)=>{if(t.list)throw new Error(`A list of values needs brackets around it (near '${e}')`);return t};if(e.forEach((a,l)=>{if("∅"===a)return void n.push({list:[]});if(","===a){const t=s(a),e=s(a);return void n.push({list:[...r(e),...r(t)]})}if(He.has(a)){const t=r(s(a));if(!t.length&&!Xe(e[l+1]))throw new Error("Empty brackets");return void n.push(w(a,t))}const c=Ge[a]??a,p=o(c);if(!p){if("?"===a||"abs("===a)throw new Error(`Unmatched '${a[0]}'`);return void n.push(M(a))}let h;if(Xe(a)&&He.has(e[l-1])&&n[n.length-1]?.op===e[l-1])h=n.pop().args;else{let e=p.arity===t||Be.has(c)?1:p.arity;if(n.length<e)throw new Error(`'${a}' needs ${e} operand${1===e?"":"s"}`);h=n.splice(n.length-e,e).map(t=>i(t,a))}const $=function(t,e){switch(t){case"sqrt":if(2===e.length)return w("root",e);break;case"round":if(1===e.length)return w("round",[e[0],x(0)]);break;case"sum":case"prod":{const n=e[1];if("op"===n?.type&&"symbol"===n.args[0]?.type&&(3===e.length&&"="===n.op||2===e.length&&"∈"===n.op))return w("sum"===t?"\\sumidx":"\\prodidx",e);break}case"det":if(e.length>1&&e.every(t=>"op"===t.type&&"[]"===t.op))return w("det",[w("[]",e)]);break;case"fixed":if(1===e.length)return w("fixed",[e[0],x(2)]);break;case"der":if(1===e.length)return w("der",[e[0],b("x")]);if(3===e.length)return function([t,e,n]){const s="number"===n.type?Number(n.value):NaN;if(!Number.isInteger(s)||s<1||s>20)throw new Error("der(f, x, n) needs n to be a whole number from 1 to 20");const r="op"===e.type&&"="===e.op?e:null,i=r?r.args[0]:e;let o=t;for(let t=0;t<s;t++)o=w("der",[o,r&&t===s-1?r:i]);return o}(e);break;case"log":if(2===e.length&&"symbol"===e[0].type&&"e"===e[0].value)return w("ln",[e[1]]);break;case"lim":return Ye(t,e),w("lim",function(t){const e=t=>"op"===t.type&&"^"===t.op&&"symbol"===t.args[1].type?Ve[t.args[1].value]:void 0,[n,s,r]=t;if(2===t.length&&"op"===s.type&&"→"===s.op&&e(s.args[1])){const[t,r]=s.args;return[n,t,r.args[0],b(e(r))]}return 3===t.length&&e(r)?[n,s,r.args[0],b(e(r))]:t}(e));case"\\:if":if(2===e.length||3===e.length)return w("?:",[e[0],e[1],e[2]??b("unchanged")]);throw new Error("if() takes a condition, a value, and optionally an alternative")}return Ye(t,e),w(t,e)}(c,h);u[a]&&"*"===$.op&&($.written=u[a]),n.push($)}),1!==n.length)throw new Error(n.length?"Some values are not connected by an operator":"Empty expression");return i(n[0],"end")}const Ve={"\\+":"r","\\-":"l"};function Ye(e,n){const{arity:s}=o(e);if(s!==t){if(n.length!==s){throw new Error(`'${e}' takes ${s} argument${1===s?"":"s"}, not ${n.length}`)}}else if(0===n.length&&!i(e))throw new Error(`'${e}' needs at least one argument`)}for(const t of[Ge,Ve])Object.setPrototypeOf(t,null);const Ke=new RegExp(`[${Object.keys(u).join("")}]`,"g"),Je=t=>t.replace(Ke,"*"),tn=/\\(?:text|textrm|textit|mathrm|mathit|operatorname)\{\s*([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\s*\}/g;const en=t=>/^[a-z][a-z0-9]*$/.test(t)&&f(t);function nn(t){return t.includes("\\")?(t=function(t){for(let e=0;e<50;e++){const e=t.lastIndexOf("\\begin{cases}"),n=e<0?-1:t.indexOf("\\end{cases}",e);if(n<0)return t;const s=D(t.slice(e+13,n),"\\\\").map(t=>D(t,"&")).filter(t=>t.join("").trim());let r=null;for(let t=s.length-1;t>=0;t--){const e=s[t][0].trim(),n=U(s[t].slice(1).join("&"));r=null!==r||n?`((${n||"true"}) ? (${e}) : ${r??"(unchanged)"})`:`(${e})`}t=t.slice(0,e)+(r??"")+t.slice(n+11)}return t}(t)).replace(/\{\}\^\{([^{}]*)\}\s*\\mathrm\{P\}\s*_\{([^{}]*)\}/g,"\\perm($1,$2)"):t}function sn(e,n={}){const s={original:e};try{if("string"!=typeof e)throw new Error("Expression must be a string");const r=n.maxLength??5e3;if(e.length>r)throw new Error(`Longer than ${r} 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(t,e,n){if(!t.includes(e))return t;const s=ht(t);let r="";for(let i=0;i<s.length;i++){const o=s[i];if('"'===o||"`"===o||"'"===o){const o=$t(s,i);r+=t.slice(i,o+1).replaceAll(e,n),i=o}else r+=t[i]}return r}(e,Ae,"")).includes(Ae))throw new Error(`The character ${Ae} can't be read: MathZetta uses it to mark names`);const a=/^\s*=(?!=)/.test(e);a&&(e=e.replace(/("(?:[^"]|"")*")|\$(?=[A-Za-z]{0,3}\d|[A-Za-z]{1,3}\$?\d)/g,(t,e)=>e??""));const l=a?[...new Set(e.replace(/"(?:[^"]|"")*"/g,"").match(/(?<![\w.])[A-Za-z]{1,3}\d+(?::[A-Za-z]{1,3}\d+)?(?![\w.(])/g)??[])]:[],{text:c,protectedNames:p}=function(t,e=[],n=[]){const s=new Map,r=new Map,i=t=>{let e=r.get(t);return void 0===e&&(e=`${Ae}${s.size}${Ae}`,s.set(e,t),r.set(t,e)),e};t=t.replace(tn,(t,e)=>en(e.trim())?` ${e.trim()}`:i(e.trim()));for(const n of[...e].sort((t,e)=>e.length-t.length)){const e=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp(`(?<![A-Za-z_])${e}(?![A-Za-z0-9_])`,"g"),()=>i(n))}for(const e of[...n].sort((t,e)=>e.length-t.length)){const n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp(`(?<![A-Za-z_])${n}(?![A-Za-z0-9_])(\\s*)(\\(?)`,"g"),(t,n,s)=>i(e)+(s?" * (":n))}return{text:t,protectedNames:s}}(nn(e),n.names,[...n.values??[],...l]),u=(t=>/\\[A-Za-z]/.test(t)?"latex":"plain")(c),{cleaned:h,stringMap:$,steps:f}=function(t,e={}){const n=void 0===e.blocks?null:e.blocks;return oe(t,{evaluate:n?t=>n(t,e.scope):void 0})}(c,{blocks:n.blocks,scope:n.scope}),m=t=>mt(mt(t,$),p).map(t=>"string"==typeof t?t.replaceAll("",Ae):t);s.mode=u,s.cleaned=Je(m([h])[0]),s.cleanSteps=f.map(([t,e])=>[t,Je(e)]);const g=Oe(h,u);s.tokens=g.map(Je);const d=m(function(t,e="plain"){return new Le(Ue(t,e)).parseAll().map(t=>Fe[t]??t)}(g,u));s.rawPostfix=d.map(Je);const y={},x=function(e,n){const s=[];return function e(r){"op"===r.type?(r.args.forEach(e),o(r.op)?.arity===t&&s.push(String(r.args.length)),n&&r.written&&(n[s.length]=r.written),s.push(r.op)):s.push(r.value)}(e),s}(Qe(d),y);s.postfix=x,s.written=y,s.tree=function(e){if(!Array.isArray(e)||0===e.length)throw new Error("Empty postfix");const n=[],s=[];if(e.forEach((e,r)=>{const a=v[e]??String(e),l=o(a);if(!l)return n.push({...M(a),id:r}),void s.push(1);let c=l.arity;if(c===t){const t=n.pop();if(s.pop(),c=t&&"number"===t.type?Number(t.value):NaN,!Number.isInteger(c)||c<0)throw new Error(`'${a}' takes a variable number of arguments, so it must follow a count`);if(0===c&&!l.group&&!i(a))throw new Error(`'${a}' needs at least one argument`)}if(n.length<c)throw new Error(`'${a}' needs ${c} operand${1===c?"":"s"}`);const p=1+Math.max(0,...s.splice(s.length-c,c));if(p>1e3)throw new Error("Nested too deeply (more than 1000 levels)");s.push(p),n.push({...w(a,n.splice(n.length-c,c)),id:r})}),1!==n.length)throw new Error(`Postfix leaves ${n.length} values instead of 1`);return n[0]}(x),Object.keys(y).length&&A(s.tree,t=>{y[t.id]&&(t.written=y[t.id])})}catch(t){s.error=t instanceof RangeError?"Nested too deeply":t.message}return s}class rn extends Error{}const on=new Set(Object.getOwnPropertyNames(Math)),an=new Set([...on,"isInteger","isFinite","includes","reduce","toFixed"]),ln={Math:on,Number:new Set(["isInteger","isFinite"])},cn=new Set(["Math","Number","Infinity","NaN","true","false","null"]),pn=new Set(["let","for","if","return"]),un=Object.values(gt).sort((t,e)=>e.length-t.length),hn=["===","!==","**=","...","=>","==","!=","<=",">=","&&","||","??","**","++","--","+=","-=","*=","/=","%=","(",")","[","]","{","}",",",";","?",":",".","+","-","*","/","%","!","=","<",">","&","|","^","~"],$n=new Set(["=","+=","-=","*=","/=","%=","**=","++","--"]);for(const t of[ln])Object.setPrototypeOf(t,null);const fn={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:t=>`Math.${t}`,abs:"Math.abs",max:"Math.max",min:"Math.min",random:"Math.random()",pow:(t,e)=>`Math.pow(${t}, ${e})`,both:(t,e)=>`(${t} && ${e})`,either:(t,e)=>`(${t} || ${e})`,not:t=>`!${t}`,xor:(t,e)=>`(!(${t}) !== !(${e}))`,oddRoot:(t,e)=>3===e?`Math.cbrt(${t})`:qn(t)?`(${t} < 0 ? -Math.pow(-${t}, 1 / ${e}) : Math.pow(${t}, 1 / ${e}))`:`${gt.root}(${e}, ${t})`,close:(t,e)=>`Math.abs((${t}) - (${e})) < 1e-9`,eq:{"=":"==","===":"===","≠":"!=","≠=":"!=="},ternary:(t,e,n)=>`(${t} ? ${e} : ${n})`,list:{"()":["[","]"],"[]":["[","]"],"{}":["[","]"],"(]":["[","]"],"[)":["[","]"]},contains:(t,e,n)=>`${n?"!":""}${t}.includes(${e})`,factorial:t=>`${gt.factorial}(${t})`,perm:(t,e)=>`${gt.perm}(${t}, ${e})`,comb:(t,e)=>`${gt.comb}(${t}, ${e})`,gcd:t=>`${gt.gcd}([${t}])`,round:(t,e)=>{const n=Tn(t)?t:`(${t})`;if(jn(t)&&qn(e))return"0"===e?`Math.round(${t})`:`Math.round(${t} * Math.pow(10, ${e})) / Math.pow(10, ${e})`;if(!qn(t)||!qn(e))return`${gt.round}(${t}, ${e})`;if("0"===e)return`(${n} < 0 ? -Math.round(-${n}) : Math.round(${n}))`;const s=`Math.pow(10, ${e})`;return`(${n} < 0 ? -Math.round(-${n} * ${s}) : Math.round(${n} * ${s})) / ${s}`},fixed:(t,e)=>`Number(${t}).toFixed(${e})`,matrix:t=>`[${t.map(t=>`[${t.join(", ")}]`).join(", ")}]`,det:t=>`${gt.det}(${t})`,union:(t,e)=>`${gt.union}(${t}, ${e})`,intersection:(t,e)=>`${gt.intersection}(${t}, ${e})`,indexed:(t,e,n,s,r)=>"sum"===t?`(()=>{let sum = 0; let loopCount = 0; for (let ${e}=${n};${s};${e}++) {if (loopCount++ > 1000000){break};sum += ${r};}; return sum;})()`:`(()=>{let prod = 1; let loopCount = 0; for (let ${e}=${n};${s};${e}++) {if (loopCount++ > 1000000){break};prod *= ${r};}; return prod;})()`},mn={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:t=>`math.${t}`,abs:"abs",max:"max",min:"min",random:"random.random()",pow:null,both:(t,e)=>`(${t} and ${e})`,either:(t,e)=>`(${t} or ${e})`,not:t=>`not ${t}`,xor:(t,e)=>`((not (${t})) != (not (${e})))`,oddRoot:(t,e)=>3===e?`math.cbrt(${t})`:Rn(t,t=>`(-(-${t}) ** (1 / ${e}) if ${t} < 0 else ${t} ** (1 / ${e}))`),close:(t,e)=>`abs((${t}) - (${e})) < 1e-9`,eq:{"=":"==","===":"==","≠":"!=","≠=":"!="},ternary:(t,e,n)=>`(${e} if ${t} else ${n})`,list:{"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(",")"],"[)":["(",")"]},contains:(t,e,n)=>`${e} ${n?"not in":"in"} ${t}`,factorial:t=>`math.factorial(${t})`,perm:(t,e)=>`math.perm(${t}, ${e})`,comb:(t,e)=>`math.comb(${t}, ${e})`,gcd:t=>`math.gcd(${t})`,round:(t,e)=>{if("0"===e)return jn(t)?`math.floor(${t} + 0.5)`:Rn(t,e=>zn(t,`(math.floor(${e} + 0.5) if ${e} >= 0 else -math.floor(-${e} + 0.5))`,e));const n=`10 ** ${Tn(e)?e:`(${e})`}`;if(jn(t)&&qn(e))return`math.floor(${t} * ${n} + 0.5) / ${n}`;const s=(e,n)=>zn(t,`(math.floor(${e} * ${n} + 0.5) if ${e} >= 0 else -math.floor(-${e} * ${n} + 0.5)) / ${n}`,e);return qn(t)&&qn(e)?s(Tn(t)?t:`(${t})`,n):`(lambda _v, _p: ${s("_v","_p")})(${t}, ${n})`},fixed:(t,e,n)=>null===n?`format(${mn.round(t,e)}, "." + str(${e}) + "f")`:`format(${mn.round(t,n)}, ".${n}f")`,matrix:t=>`[${t.map(t=>`[${t.join(", ")}]`).join(", ")}]`,det:t=>`np.linalg.det(${t})`,union:(t,e)=>`sorted(set(${t}) | set(${e}))`,intersection:(t,e)=>`sorted(set(${t}) & set(${e}))`,integral:(t,e,n,s)=>`scipy.integrate.quad(lambda ${n}: ${e}, ${s.join(", ")})[0]`,symbolic:"the SymPy flavour, { sympy: true }, has it",indexed:(t,e,n,s,r,i)=>"sum"===t?`sum(${r} for ${e} in range(${n}, ${i} + 1))`:`math.prod(${r} for ${e} in range(${n}, ${i} + 1))`},gn={asin:"arcsin",acos:"arccos",atan:"arctan",asinh:"arcsinh",acosh:"arccosh",atanh:"arctanh",atan2:"arctan2",pow:"power"},dn=(t,e)=>e.reduce((e,n)=>`${t}(${e}, ${n})`),yn={"<":"<",">":">","≤":"<=","≥":">=","=":"==","===":"==","≠":"!=","≠=":"!="},xn=([,t],e,n)=>{const[s,r]=e.args,i=(t,e)=>"op"===t.type&&Pn.has(t.op)?`(${e})`:e,o=n=>`${n} ${yn[e.op]} ${i(r,t)}`;return"op"===s.type&&yn[s.op]?`np.logical_and(${n(s)}, ${o(i(s.args[1],n(s.args[1])))})`:o(i(s,n(s)))},bn={...mn,name:"numpy",title:"numpy",union:(t,e)=>`np.union1d(${t}, ${e})`,intersection:(t,e)=>`np.intersect1d(${t}, ${e})`,pi:"np.pi",e:"np.e",tau:"(2 * np.pi)",inf:"np.inf",degree:"(np.pi/180)",math:t=>`np.${gn[t]??t}`,list:{...mn.list,"{}":["[","]"]},abs:"np.abs",random:"np.random.random()",matrix:t=>`np.array(${mn.matrix(t)})`,det:t=>`np.linalg.det(${t})`,both:(t,e)=>`np.logical_and(${t}, ${e})`,either:(t,e)=>`np.logical_or(${t}, ${e})`,not:t=>`np.logical_not(${t})`,close:(t,e)=>`np.isclose(${t}, ${e})`,ternary:(t,e,n)=>`np.where(${t}, ${e}, ${n})`,contains:(t,e,n)=>n?`np.logical_not(np.isin(${e}, ${t}))`:`np.isin(${e}, ${t})`,factorial:t=>`scipy.special.factorial(${t})`,perm:(t,e)=>`scipy.special.perm(${t}, ${e})`,comb:(t,e)=>`scipy.special.comb(${t}, ${e})`,round:(t,e)=>{if("0"===e)return Rn(t,t=>`np.where(${t} >= 0, np.floor(${t} + 0.5), -np.floor(-${t} + 0.5))`);const n=`10.0 ** ${Tn(e)?e:`(${e})`}`,s=(t,e)=>`np.where(${t} >= 0, np.floor(${t} * ${e} + 0.5), -np.floor(-${t} * ${e} + 0.5)) / ${e}`;return qn(t)&&qn(e)?s(Tn(t)?t:`(${t})`,n):`(lambda _v, _p: ${s("_v","_p")})(${t}, ${n})`},oddRoot:(t,e)=>3===e?`np.cbrt(${t})`:Rn(t,t=>`np.where(${t} < 0, -np.power(-${t}, 1 / ${e}), np.power(${t}, 1 / ${e}))`),fixed:(t,e,n)=>null===n?`np.char.mod("%." + str(${e}) + "f", ${bn.round(t,e)})`:`np.char.mod("%.${n}f", ${bn.round(t,n)})`,ops:{...Object.fromEntries(Object.keys(yn).map(t=>[t,xn])),max:t=>1===t.length?`np.nanmax(${t[0]})`:dn("np.maximum",t),min:t=>1===t.length?`np.nanmin(${t[0]})`:dn("np.minimum",t),sum:t=>1===t.length?`np.nansum(${t[0]})`:null,prod:t=>1===t.length?`np.nanprod(${t[0]})`:null,mean:t=>1===t.length?`np.nanmean(${t[0]})`:null,"\\:median":t=>1===t.length?`np.nanmedian(${t[0]})`:null,"\\:stdev":t=>1===t.length?`np.nanstd(${t[0]})`:null,"\\:std":t=>1===t.length?`np.nanstd(${t[0]})`:null,gcd:t=>dn("np.gcd",t),"\\xor":([t,e])=>`np.logical_xor(${t}, ${e})`,"\\nand":([t,e])=>`np.logical_not(np.logical_and(${t}, ${e}))`,"\\nor":([t,e])=>`np.logical_not(np.logical_or(${t}, ${e}))`}},wn=t=>`sympy.${t}`,_n=t=>"number"===t.type&&/^-?\d+$/.test(t.value)||"op"===t.type&&"neg"===t.op&&_n(t.args[0]),Mn={"ℝ":"sympy.S.Reals","ℤ":"sympy.S.Integers","ℕ":"sympy.S.Naturals","ℚ":"sympy.S.Rationals","ℂ":"sympy.S.Complexes"},vn={"[]":"sympy.Interval","()":"sympy.Interval.open","(]":"sympy.Interval.Lopen","[)":"sympy.Interval.Ropen"};function An(t,e){return"symbol"===t.type&&Mn[t.value]?Mn[t.value]:"op"===t.type&&vn[t.op]&&2===t.args.length?`${vn[t.op]}(${t.args.map(e).join(", ")})`:"op"===t.type&&o(t.op)?.group?`sympy.FiniteSet(${t.args.map(e).join(", ")})`:"number"===t.type||"neg"===t.op&&"number"===t.args[0].type?`sympy.FiniteSet(${e(t)})`:e(t)}function En(t,e,n,s){const r=[];return function e(s){"op"===s.type&&s.op===t?s.args.forEach(e):r.push(n(s))}(e),`${s}(${r.join(", ")})`}const Nn={...mn,name:"sympy",title:"SymPy",symbolic:null,noStrings:!0,pi:wn("pi"),e:wn("E"),tau:"(2*sympy.pi)",inf:wn("oo"),degree:"(sympy.pi/180)",true:wn("true"),false:wn("false"),null:"None",math:t=>wn({log:"log",asin:"asin",acos:"acos",atan:"atan",asinh:"asinh",acosh:"acosh",atanh:"atanh",atan2:"atan2",expm1:"expm1",ceil:"ceiling"}[t]??t),abs:wn("Abs"),random:"random.random()",matrix:t=>`sympy.Matrix(${mn.matrix(t)})`,det:t=>`sympy.det(${t})`,both:(t,e)=>`sympy.And(${t}, ${e})`,either:(t,e)=>`sympy.Or(${t}, ${e})`,not:t=>`sympy.Not(${t})`,close:(t,e)=>`sympy.Abs((${t}) - (${e})) < sympy.Rational(1, 10**9)`,exactNumber:t=>{const e=/^(\d*)\.(\d+)$/.exec(t);if(!e)return t;const n=10n**BigInt(e[2].length);let[s,r]=[BigInt(e[1]||"0")*n+BigInt(e[2]),n];const i=(t,e)=>e?i(e,t%e):t,o=i(s,r);return[s,r]=[s/o,r/o],1n===r?String(s):`sympy.Rational(${s}, ${r})`},factorial:t=>`sympy.factorial(${t})`,perm:(t,e)=>`sympy.ff(${t}, ${e})`,comb:(t,e)=>`sympy.binomial(${t}, ${e})`,ops:{"/":(t,e)=>_n(e.args[0])&&_n(e.args[1])?`sympy.Rational(${t[0]}, ${t[1]})`:null,"^":(t,e)=>"symbol"===e.args[0].type&&"e"===e.args[0].value?`sympy.exp(${t[1]})`:null,"=":t=>`sympy.Eq(${t[0]}, ${t[1]})`,"===":t=>`sympy.Eq(${t[0]}, ${t[1]})`,"≡":t=>`sympy.Eq(${t[0]}, ${t[1]})`,"≠":t=>`sympy.Ne(${t[0]}, ${t[1]})`,"≠=":t=>`sympy.Ne(${t[0]}, ${t[1]})`,mod:t=>`sympy.Mod(${t[0]}, ${t[1]})`,pmod:(t,e,n)=>{const[s]=e.args;return"op"===s.type&&["≡","="].includes(s.op)?`sympy.Eq(sympy.Mod((${n(s.args[0])}) - (${n(s.args[1])}), ${t[1]}), 0)`:`sympy.Mod(${t[0]}, ${t[1]})`},"!":t=>`sympy.factorial(${t[0]})`,perm:t=>`sympy.ff(${t[0]}, ${t[1]})`,comb:t=>`sympy.binomial(${t[0]}, ${t[1]})`,gcd:t=>2===t.length?`sympy.gcd(${t.join(", ")})`:`sympy.gcd_list([${t.join(", ")}])`,max:t=>`sympy.Max(${t.join(", ")})`,min:t=>`sympy.Min(${t.join(", ")})`,floor:t=>`sympy.floor(${t[0]})`,ceil:t=>`sympy.ceiling(${t[0]})`,csc:t=>`sympy.csc(${t[0]})`,sec:t=>`sympy.sec(${t[0]})`,cot:t=>`sympy.cot(${t[0]})`,ln:t=>`sympy.log(${t[0]})`,log:(t,e)=>"symbol"===e.args[0].type&&"e"===e.args[0].value?`sympy.log(${t[1]})`:`sympy.log(${t[1]}, ${t[0]})`,loglog:t=>`sympy.log(sympy.log(${t[0]}))`,logloglog:t=>`sympy.log(sympy.log(sympy.log(${t[0]})))`,expm1:t=>`(sympy.exp(${t[0]}) - 1)`,root:(t,e)=>"number"===e.args[0].type&&/^\d*[13579]$/.test(e.args[0].value)&&("number"===e.args[1].type||"neg"===e.args[1].op&&"number"===e.args[1].args[0].type)?`sympy.real_root(${t[1]}, ${t[0]})`:`sympy.root(${t[1]}, ${t[0]})`,round:(t,e)=>{const n="number"===e.args[1].type&&"0"===e.args[1].value,s=(t,e)=>{const s=n?`(${t})`:`(${t}) * 10**(${e})`,r=`sympy.Piecewise((${`sympy.floor(${s} + sympy.Rational(1, 2))`}, ${t} >= 0), (${`-sympy.floor(-${s} + sympy.Rational(1, 2))`}, True))`;return n?r:`${r} / 10**(${e})`};return n?Rn(t[0],t=>s(t)):qn(t[0])&&qn(t[1])?s(t[0],t[1]):`(lambda _v, _p: ${s("_v","_p")})(${t[0]}, ${t[1]})`},"&":(t,e,n)=>En("&",e,n,"sympy.And"),"|":(t,e,n)=>En("|",e,n,"sympy.Or"),"\\not":t=>`sympy.Not(${t[0]})`,"\\xor":t=>`sympy.Xor(${t.join(", ")})`,"\\nand":t=>`sympy.Nand(${t.join(", ")})`,"\\nor":t=>`sympy.Nor(${t.join(", ")})`,"?:":t=>`sympy.Piecewise((${t[1]}, ${t[0]}), (${t[2]}, True))`,"∈":(t,e,n)=>`sympy.Contains(${t[0]}, ${An(e.args[1],n)})`,"∉":(t,e,n)=>`sympy.Not(sympy.Contains(${t[0]}, ${An(e.args[1],n)}))`,"∪":(t,e,n)=>`sympy.Union(${e.args.map(t=>An(t,n)).join(", ")})`,"∩":(t,e,n)=>`sympy.Intersection(${e.args.map(t=>An(t,n)).join(", ")})`,"{}":t=>`sympy.FiniteSet(${t.join(", ")})`,der:(t,e,n)=>{const s=e.args[1];return"op"===s.type&&"="===s.op?`sympy.diff(${t[0]}, ${n(s.args[0])}).subs(${n(s.args[0])}, ${n(s.args[1])})`:`sympy.diff(${t.join(", ")})`},int:(t,e,n)=>{const[s,r,i,o]=e.args,a=e.args.length>=2&&(t=>"symbol"===t.type&&1===t.value.length&&/[a-zA-Zʹ-Ͽ]/.test(t.value))(r),l=a?n(r):E(s)||"x";let c=[];return 4===e.args.length?c=[i,o]:3===e.args.length?c=a?[i]:[r,i]:2!==e.args.length||a||(c=[r]),c=c.map(n),c.length?`sympy.integrate(${n(s)}, (${l}, ${c[0]}, ${c[1]??"sympy.oo"}))`:`sympy.integrate(${n(s)}, ${l})`},lim:(t,e,n)=>{const[s,r]=e.args,i="op"===r?.type&&"→"===r.op;if(e.args.length<2)throw new Error("A limit needs a point: lim(f, x → a)");const[o,a]=i?r.args.map(n):2===e.args.length?[E(s)||"x",t[1]]:[t[1],t[2]],l="symbol"===e.args[3]?.type?Cn[e.args[3].value]??"":"";return`sympy.limit(${t[0]}, ${o}, ${a}${l})`},"\\sumidx":(t,e,n)=>On("summation",e,n),"\\prodidx":(t,e,n)=>On("product",e,n)}};function On(t,e,n){const[s,r,i]=e.args;return e.args.length<3||"op"!==r.type||"="!==r.op||"symbol"!==r.args[0].type?null:`sympy.${t}(${n(s)}, (${n(r.args[0])}, ${n(r.args[1])}, ${n(i)}))`}const kn={javascript:fn,python:mn,numpy:bn,sympy:Nn},In={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"},Sn={csc:"sin",sec:"cos",cot:"tan"},jn=t=>/^\d+(\.\d+)?$/.test(t),qn=t=>t.length<=16&&!/[\w.$]\s*\(/.test(t),zn=(t,e,n)=>/[A-Za-z_]/.test(t)?`(${e} if abs(${n}) < math.inf else ${n})`:e,Rn=(t,e)=>qn(t)?e(Tn(t)?t:`(${t})`):`(lambda _v: ${e("_v")})(${t})`;function Tn(t){if(/^[\w.]+$/.test(t))return!0;const e=/^[\w.$]+\(/.exec(t);if(!e)return!1;for(let n=e[0].length-1,s=0;n<t.length;n++)if("("===t[n])s++;else if(")"===t[n]&&0===--s)return n===t.length-1;return!1}const Cn={r:', "+"',l:', "-"'},Pn=new Set(["<",">","≤","≥","=","===","≠","≠=","∈","∉"]),Zn={"ℝ":{javascript:t=>`Number.isFinite(${t})`,python:t=>`math.isfinite(${t})`,numpy:t=>`np.isfinite(${t})`},"ℤ":{javascript:t=>`Number.isInteger(${t})`,python:t=>`float(${t}).is_integer()`,numpy:t=>`(np.mod(${t}, 1) == 0)`},"ℕ":{javascript:t=>`(Number.isInteger(${t}) && ${t} > 0)`,python:t=>`(float(${t}).is_integer() and ${t} > 0)`,numpy:t=>`np.logical_and(np.mod(${t}, 1) == 0, ${t} > 0)`}};for(const t of[fn,mn,gn,yn,bn,Mn,vn,Nn,kn,In,Sn,Zn,Cn])Object.setPrototypeOf(t,null);const Fn=t=>e=>`<mover accent="true">${e}<mo>${t}</mo></mover>`,Ln={boxed:t=>`<menclose notation="box">${t}</menclose>`,cancel:t=>`<menclose notation="updiagonalstrike">${t}</menclose>`,overline:Fn("¯"),bar:Fn("¯"),underline:t=>`<munder accentunder="true">${t}<mo>_</mo></munder>`,vec:Fn("→"),hat:Fn("^"),widehat:Fn("^"),tilde:Fn("~"),dot:Fn("˙"),ddot:Fn("¨")};Object.setPrototypeOf(Ln,null);const Un={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"<",">":">","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","±":"±",mod:"mod","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},Dn={sin:"sin",cos:"cos",tan:"tan",csc:"csc",sec:"sec",cot:"cot",sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsin:"arcsin",arccos:"arccos",arctan:"arctan",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"},Wn={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};for(const t of[Un,Dn,Wn])Object.setPrototypeOf(t,null);const Hn={pi:"PI()","π":"PI()",e:"EXP(1)",tau:"(2 * PI())","τ":"(2 * PI())","∞":"'Infinity'","-∞":"'-Infinity'",true:"TRUE",false:"FALSE",null:"NULL"},Gn={...Hn,"∞":"9e999","-∞":"-9e999",tau:"(2 * PI())","τ":"(2 * PI())"},Bn={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"},Xn={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"},Qn={"+":"+","-":"-","*":"*","/":"/","=":"=","===":"=","≠":"<>","≠=":"<>","<":"<",">":">","≤":"<=","≥":">="},Vn={"()":["(",")"],"{}":["(",")"],"[]":["ARRAY[","]"],"(]":["(",")"],"[)":["(",")"]},Yn={"!":"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"},Kn={max:"MAX",min:"MIN"},Jn={csc:"SIN",sec:"COS",cot:"TAN"},ts={"ℝ":t=>`(ABS(${t}) < 'Infinity')`,"ℤ":t=>`(${t} = TRUNC(${t}))`,"ℕ":t=>`(${t} = TRUNC(${t}) AND ${t} > 0)`};for(const t of[Hn,Gn,Bn,Qn,Vn,Kn,Jn,ts,Xn,Yn])Object.setPrototypeOf(t,null);const es={pi:"PI()","π":"PI()",e:"EXP(1)",tau:"(2*PI())","τ":"(2*PI())","°":"(PI()/180)",true:"TRUE",false:"FALSE"},ns={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"},ss={csc:"SIN",sec:"COS",cot:"TAN"},rs={"=":"=","===":"=","≡":"=","≠":"<>","≠=":"<>","<":"<",">":">","≤":"<=","≥":">="},is={sum:"SUM",prod:"PRODUCT",mean:"AVERAGE",max:"MAX",min:"MIN","\\:median":"MEDIAN","\\:stdev":"STDEVP","\\:count":"COUNT"},os={der:"a derivative",int:"an integral",lim:"a limit","\\sumidx":"a sum to n","\\prodidx":"a product to n",pm:"±","±":"±","∪":"∪","∩":"∩","→":"→"};for(const t of[es,ns,ss,rs,is,os])Object.setPrototypeOf(t,null);const as="3.141592653589793",ls={pi:as,"π":as,e:"2.718281828459045",tau:"6.283185307179586","τ":"6.283185307179586","∞":"MZ_INFINITY","-∞":"(-MZ_INFINITY)",true:"true",false:"false"},cs={"α":"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"},ps={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"},us={sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",round:"round"},hs={csc:"sin",sec:"cos",cot:"tan"},$s={"=":"==","===":"==","≠":"!=","≠=":"!=","<":"<",">":">","≤":"<=","≥":">="},fs={"ℝ":t=>`(abs(${t}) < MZ_INFINITY)`,"ℤ":t=>`(fract(${t}) == 0.0)`,"ℕ":t=>`(fract(${t}) == 0.0 && ${t} > 0.0)`},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"},gs=["px","py","rgb","gray","unchanged","selected"],ds=["zoom","shift","rotate","crop","tile","flipx","flipy"],ys=["srgb","linear","hsv","hsl","lab","oklab","ycbcr"].filter(t=>"srgb"!==t).flatMap(t=>[`to${t}`,`from${t}`]),xs=["pixel","red","green","blue","alpha","luma","source","selection","width","height","blur","blurx","blury","gaussian","gaussianx","gaussiany","sobel","sobelx","sobely","laplacian","sharpen","emboss","dilate","erode","convolve",...ds,"fract","clamp","mix","smoothstep","step","distance","length","dot","normalize","cross","sign","exp2","log2","inversesqrt","radians","degrees",...ys],bs=["red","green","blue","alpha","luma"];function ws(t,e,{whole:n=!1}={}){const s=_s(t,e);return n?"symbol"===s.type&&e.has(s.value)?{...s,value:`mz_px_${s.value}`}:"op"===s.type&&s.op.startsWith(`${r}mz_at_`)?{...s,op:s.op.replace("mz_at_","mz_sample_")}:s:s}function _s(t,e){if("op"!==t.type)return t;const n=t.args.map(t=>_s(t,e)),s=t.op.startsWith(r)?t.op.slice(2):null,i=n.length&&"symbol"===n[0].type&&e.has(n[0].value)?n[0].value:null;if(s&&e.has(s))return{...t,op:`${r}mz_at_${s}`,args:n};if(s&&bs.includes(s)&&1===n.length&&i)return{...t,args:[{...n[0],value:`mz_px_${i}`}]};if(s&&bs.includes(s)&&1===n.length&&"op"===n[0].type&&n[0].op.startsWith(`${r}mz_at_`))return{...t,args:[{...n[0],op:n[0].op.replace("mz_at_","mz_sample_")}]};if(s&&ds.includes(s)){const t={type:"op",op:`${r}mz_${s}`,args:i?n.slice(1):n};return{type:"op",op:`${r}mz_at_${i??"image"}`,args:[t]}}return("width"===s||"height"===s)&&n.length<=1?i&&"source"!==i?{type:"op",op:`${r}mz_${s}_${i}`,args:[]}:{type:"symbol",value:"width"===s?"w":"h"}:{...t,args:n}}const Ms={square:8,line:24};for(const t of[ls,cs,ps,us,hs,$s,fs,Ms,ms])Object.setPrototypeOf(t,null);const vs={data:new Float32Array([1,1,1,1]),width:1,height:1},As={data:new Float32Array([0,0,0,0]),width:1,height:1},Es={cover:0,fit:1,stretch:2,tile:3};function Ns(t){return Es[t??"cover"]??0}function Os(t,e){return t-e*Math.floor(t/e)}const ks=(t,e)=>t<0?0:t>e?e:t;function Is(t,e,n,s,r,i){const o=Math.floor(s),a=Math.floor(r),l=s-o,c=r-a,p=ks(o,e-1),u=ks(o+1,e-1),h=ks(a,n-1),$=ks(a+1,n-1),f=4*(h*e+p),m=4*(h*e+u),g=4*($*e+p),d=4*($*e+u);for(let e=0;e<4;e++){const n=t[f+e]+(t[m+e]-t[f+e])*l,s=t[g+e]+(t[d+e]-t[g+e])*l;i[e]=n+(s-n)*c}return i}function Ss(t,e,n){const s=Math.min(Math.max(Math.ceil(t),0),e),r=[];for(let t=-s;t<=s;t++)n(t)&&r.push(t);return r}function js(t,e,n,s,r,i,o,a,l=0,c=s){const p=new Float32Array(n*s*3),u=i.length,h=Int32Array.from(i),$=Float64Array.from(o??i.map(()=>1)),f="x"===r?n:s,m=new Int32Array(u);for(let s=l;s<c;s++)for(let i=0;i<n;i++){const o="x"===r?i:s;for(let t=0;t<u;t++){let a=o+h[t];a=a<0?0:a>=f?f-1:a,m[t]=("x"===r?s*n+a:a*n+i)*e}let l=0,c=0,g=0;for(let e=0;e<u;e++){const n=m[e],s=$[e];l+=t[n]*s,c+=t[n+1]*s,g+=t[n+2]*s}const d=3*(s*n+i);p[d]=l/a,p[d+1]=c/a,p[d+2]=g/a}return p}function qs(t,e,n,s,r,i,o,a=0,l=s){const c=new Float32Array(n*s*3),p="x"===r?n:s,u="x"===r?s:n,h=o-i+1,$=(t,e)=>"x"===r?t*n+e:e*n+t,f=t=>t<0?0:t>=p?p-1:t,[m,g]="x"===r?[a,l]:[0,u],[d,y]="x"===r?[0,p]:[a,l];for(let n=m;n<g;n++){let s=0,r=0,a=0;for(let l=d+i;l<=d+o;l++){const i=$(n,f(l))*e;s+=t[i],r+=t[i+1],a+=t[i+2]}for(let l=d;l<y;l++){const p=3*$(n,l);c[p]=s/h,c[p+1]=r/h,c[p+2]=a/h;const u=$(n,f(l+i))*e,m=$(n,f(l+o+1))*e;s+=t[m]-t[u],r+=t[m+1]-t[u+1],a+=t[m+2]-t[u+2]}}return c}function zs(t,e,n,s,r,i,o,a,l=0,c=s){const p=new Float32Array(n*s*3),u="x"===r?n:s;for(let s=l;s<c;s++)for(let l=0;l<n;l++){const c="x"===r?l:s;let h=o,$=o,f=o;for(let o=0;o<i.length;o++){let p=c+i[o];p=p<0?0:p>=u?u-1:p;const m=("x"===r?s*n+p:p*n+l)*e;a?(t[m]>h&&(h=t[m]),t[m+1]>$&&($=t[m+1]),t[m+2]>f&&(f=t[m+2])):(t[m]<h&&(h=t[m]),t[m+1]<$&&($=t[m+1]),t[m+2]<f&&(f=t[m+2]))}const m=3*(s*n+l);p[m]=h,p[m+1]=$,p[m+2]=f}return p}const Rs=(t,e,n)=>t+e*n,Ts=(t,e)=>e>t?e:t,Cs=(t,e)=>e<t?e:t;function Ps(t,e,n,s=0,r=n){const i=new Float32Array(e*n*3);for(let n=s*e;n<r*e;n++)i[3*n]=t[4*n],i[3*n+1]=t[4*n+1],i[3*n+2]=t[4*n+2];return i}const Zs=(t,e,n,s)=>[Math.max(0,t-n),Math.min(s,e+n)];function Fs(t,e,n,s,r,i,o,a){const l=Ss(i,a,t=>Math.abs(t)<=i);if(!l.length)return Ps(t,e,n,s,r);const c=l[0],p=l[l.length-1];if(1===o.length)return qs(t,4,e,n,o[0],c,p,s,r);const[u,h]=Zs(s,r,p,n);return qs(qs(t,4,e,n,"x",c,p,u,h),3,e,n,"y",c,p,s,r)}function Ls(t,e,n,s,r,i,o,a){if(!(i>0))return Ps(t,e,n,s,r);const l=3*i,c=Ss(l,a,t=>Math.abs(t)<=l),p=c.map(t=>Math.exp(-t*t/(2*i*i))),u=p.reduce((t,e)=>t+e,0);if(1===o.length)return js(t,4,e,n,o[0],c,p,u,s,r);const[h,$]=Zs(s,r,c[c.length-1],n);return js(js(t,4,e,n,"x",c,p,u,h,$),3,e,n,"y",c,p,u,s,r)}function Us(t,e,n,s,r,i,o,a){const l=Ss(i,Ms.square,t=>Math.abs(t)<=i);if(!l.length)return new Float32Array(e*n*3).fill(o);const[c,p]=Zs(s,r,l[l.length-1],n);return zs(zs(t,4,e,n,"x",l,o,a,c,p),3,e,n,"y",l,o,a,s,r)}function Ds(t,e,n,s,r,i){const o=function(t,e,n){const s=new Float32Array(e*n);for(let r=0;r<e*n;r++)s[r]=.299*t[4*r]+.587*t[4*r+1]+.114*t[4*r+2];return s}(t,e,n),a=new Float32Array(e*n);for(let t=s;t<r;t++)for(let s=0;s<e;s++){const r=(r,i)=>o[ks(t+i,n-1)*e+ks(s+r,e-1)];a[t*e+s]=i(r)}return a}const Ws=t=>t(1,-1)+2*t(1,0)+t(1,1)-(t(-1,-1)+2*t(-1,0)+t(-1,1)),Hs=t=>t(-1,1)+2*t(0,1)+t(1,1)-(t(-1,-1)+2*t(0,-1)+t(1,-1)),Gs=t=>4*t(0,0)-t(-1,0)-t(1,0)-t(0,-1)-t(0,1),Bs=t=>.5+t(-1,-1)-t(1,1),Xs=t=>Math.hypot(Ws(t),Hs(t));function Qs(t,e,n,s,r,i,o,a,l,c,p){for(let u=0;u<3;u++){let h=a,$=0;for(const a of i)for(const c of i){const i=o?o(a,c):1;h=l(h,t[4*(ks(r+c,n-1)*e+ks(s+a,e-1))+u],i),$+=i}c[u]=p?p(h,$):h}return c}function Vs(t,e,n,s,r,i,o,a,l){for(let c=0;c<3;c++){let p=0,u=0;for(const l of o){const o=a?a(l):1,h="x"===i?ks(s+l,e-1):s;p+=t[4*(("y"===i?ks(r+l,n-1):r)*e+h)+c]*o,u+=o}l[c]=p/u}return l}const Ys=(t,e,n,s,r)=>{const i=4*(s*e+n);return r[0]=t[i],r[1]=t[i+1],r[2]=t[i+2],r};const Ks=t=>t<.04045?t/12.92:Math.pow((t+.055)/1.055,2.4),Js=t=>(t=Math.max(t,0))<.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,tr=(t,e,n,s,r)=>{const i=s===t?(e-n)/r:s===e?2+(n-t)/r:4+(t-e)/r;return i/6-Math.floor(i/6)},er=(t,e)=>{const n=Math.abs(6*(t+e-Math.floor(t+e))-3);return Math.min(Math.max(n-1,0),1)};const nr=t=>t<.008856?7.787*t+16/116:Math.cbrt(t),sr=t=>t<.206893?(t-16/116)/7.787:t*t*t;var rr=Object.freeze({__proto__:null,BLANK:vs,CLEAR:As,at:function(t,e,n){return Number(t[e][n])},at_blur:function(t,e,n,s,r,i,o){return Qs(t,e,n,s,r,Ss(i,Ms.square,t=>Math.abs(t)<=i),null,0,Rs,o,(t,e)=>t/e)},at_blurx:function(t,e,n,s,r,i,o){return Vs(t,e,n,s,r,"x",Ss(i,Ms.line,t=>Math.abs(t)<=i),null,o)},at_blury:function(t,e,n,s,r,i,o){return Vs(t,e,n,s,r,"y",Ss(i,Ms.line,t=>Math.abs(t)<=i),null,o)},at_dilate:function(t,e,n,s,r,i,o){return Qs(t,e,n,s,r,Ss(i,Ms.square,t=>Math.abs(t)<=i),null,0,Ts,o)},at_erode:function(t,e,n,s,r,i,o){return Qs(t,e,n,s,r,Ss(i,Ms.square,t=>Math.abs(t)<=i),null,1,Cs,o)},at_gaussian:function(t,e,n,s,r,i,o){if(!(i>0))return Ys(t,e,s,r,o);const a=3*i;return Qs(t,e,n,s,r,Ss(a,Ms.square,t=>Math.abs(t)<=a),(t,e)=>Math.exp(-(t*t+e*e)/(2*i*i)),0,Rs,o,(t,e)=>t/e)},at_gaussianx:function(t,e,n,s,r,i,o){if(!(i>0))return Ys(t,e,s,r,o);const a=3*i;return Vs(t,e,n,s,r,"x",Ss(a,Ms.line,t=>Math.abs(t)<=a),t=>Math.exp(-t*t/(2*i*i)),o)},at_gaussiany:function(t,e,n,s,r,i,o){if(!(i>0))return Ys(t,e,s,r,o);const a=3*i;return Vs(t,e,n,s,r,"y",Ss(a,Ms.line,t=>Math.abs(t)<=a),t=>Math.exp(-t*t/(2*i*i)),o)},at_sharpen:function(t,e,n,s,r,i,o){const a=(t,s)=>4*(ks(s,n-1)*e+ks(t,e-1)),l=a(s,r),c=a(s-1,r),p=a(s+1,r),u=a(s,r-1),h=a(s,r+1);for(let e=0;e<3;e++)o[e]=t[l+e]+i*(4*t[l+e]-t[c+e]-t[p+e]-t[u+e]-t[h+e]);return o},col_fromhsl:function(t,e,n,s){const r=(1-Math.abs(2*n-1))*e;return s[0]=n-.5*r+r*er(t,0),s[1]=n-.5*r+r*er(t,2/3),s[2]=n-.5*r+r*er(t,1/3),s},col_fromhsv:function(t,e,n,s){return s[0]=n*(1+(er(t,0)-1)*e),s[1]=n*(1+(er(t,2/3)-1)*e),s[2]=n*(1+(er(t,1/3)-1)*e),s},col_fromlab:function(t,e,n,s){const r=(100*t+16)/116,i=r-256*(n-.5)/200,o=.95047*sr(r+256*(e-.5)/500),a=sr(r),l=1.08883*sr(i),c=Math.min(Math.max(3.2404542*o-1.5371385*a-.4985314*l,0),1),p=Math.min(Math.max(-.969266*o+1.8760108*a+.041556*l,0),1),u=Math.min(Math.max(.0556434*o-.2040259*a+1.0572252*l,0),1);return s[0]=Js(c),s[1]=Js(p),s[2]=Js(u),s},col_fromlinear:function(t,e,n,s){return s[0]=Js(t),s[1]=Js(e),s[2]=Js(n),s},col_fromoklab:function(t,e,n,s){let r=t+.3963377774*(e-=.5)+.2158037573*(n-=.5),i=t-.1055613458*e-.0638541728*n,o=t-.0894841775*e-1.291485548*n;r*=r*r,i*=i*i,o*=o*o;const a=Math.min(Math.max(4.0767416621*r-3.3077115913*i+.2309699292*o,0),1),l=Math.min(Math.max(-1.2684380046*r+2.6097574011*i-.3413193965*o,0),1),c=Math.min(Math.max(-.0041960863*r-.7034186147*i+1.707614701*o,0),1);return s[0]=Js(a),s[1]=Js(l),s[2]=Js(c),s},col_fromycbcr:function(t,e,n,s){return e-=.5,n-=.5,s[0]=t+1.402*n,s[1]=t-.344136*e-.714136*n,s[2]=t+1.772*e,s},col_tohsl:function(t,e,n,s){const r=Math.max(t,e,n),i=Math.min(t,e,n),o=r-i,a=.5*(r+i);return s[0]=o>0?tr(t,e,n,r,o):0,s[1]=o>0?o/(1-Math.abs(2*a-1)):0,s[2]=a,s},col_tohsv:function(t,e,n,s){const r=Math.max(t,e,n),i=r-Math.min(t,e,n);return s[0]=i>0?tr(t,e,n,r,i):0,s[1]=r>0?i/r:0,s[2]=r,s},col_tolab:function(t,e,n,s){const r=Ks(t),i=Ks(e),o=Ks(n),a=nr((.4124564*r+.3575761*i+.1804375*o)/.95047),l=nr(.2126729*r+.7151522*i+.072175*o),c=nr((.0193339*r+.119192*i+.9503041*o)/1.08883);return s[0]=(116*l-16)/100,s[1]=.5+500*(a-l)/256,s[2]=.5+200*(l-c)/256,s},col_tolinear:function(t,e,n,s){return s[0]=Ks(t),s[1]=Ks(e),s[2]=Ks(n),s},col_tooklab:function(t,e,n,s){const r=Ks(t),i=Ks(e),o=Ks(n),a=Math.cbrt(.4122214708*r+.5363325363*i+.0514459929*o),l=Math.cbrt(.2119034982*r+.6806995451*i+.1073969566*o),c=Math.cbrt(.0883024619*r+.2817188376*i+.6299787005*o);return s[0]=.2104542553*a+.793617785*l-.0040720468*c,s[1]=.5+1.9779984951*a-2.428592205*l+.4505937099*c,s[2]=.5+.0259040371*a+.7827717662*l-.808675766*c,s},col_toycbcr:function(t,e,n,s){const r=.299*t+.587*e+.114*n;return s[0]=r,s[1]=.5+.5643*(n-r),s[2]=.5+.7132*(t-r),s},convolve:function(t,e,n,s,r,i,o,a,l,c,p,u,h,$,f){const m=(t,i)=>4*(ks(r+i,n-1)*e+ks(s+t,e-1)),g=[[i,-1,-1],[o,0,-1],[a,1,-1],[l,-1,0],[c,0,0],[p,1,0],[u,-1,1],[h,0,1],[$,1,1]];for(let e=0;e<3;e++){let n=0;for(const[s,r,i]of g)n+=s*t[m(r,i)+e];f[e]=n}return f},factorial:function(t){let e=1;for(let n=2;n<=170&&!(n>t);n++)e*=n;return e},fmod:Os,gcd:function(t,e){t=Math.abs(t),e=Math.abs(e);for(let n=0;n<64&&0!==e;n++){const n=Os(t,e);t=e,e=n}return t},perm:function(t,e){let n=1;for(let s=0;s<170&&!(s>=e);s++)n*=t-s;return n},picture:function(t,e,n,s,r,i,o,a,l,c,p,u,h){let $,f;0===c?$=f=Math.max(s/e,r/n):1===c?$=f=Math.min(s/e,r/n):2===c?($=s/e,f=r/n):$=f=1,$*=i,f*=i;const m=p+.5-o*s,g=u+.5-a*r,d=Math.cos(l),y=Math.sin(l);let x=(d*m+y*g)/$+.5*e,b=(d*g-y*m)/f+.5*n;if(3===c)x=Os(x,e),b=Os(b,n);else if(x<0||b<0||x>e||b>n)return h[0]=h[1]=h[2]=h[3]=0,h;return Is(t,e,n,x-.5,b-.5,h)},placeCode:Ns,plane_blur:function(t,e,n,s,r,i){return Fs(t,e,n,s,r,i,["x","y"],Ms.square)},plane_blurx:function(t,e,n,s,r,i){return Fs(t,e,n,s,r,i,["x"],Ms.line)},plane_blury:function(t,e,n,s,r,i){return Fs(t,e,n,s,r,i,["y"],Ms.line)},plane_dilate:function(t,e,n,s,r,i){return Us(t,e,n,s,r,i,0,!0)},plane_emboss:function(t,e,n,s,r){return Ds(t,e,n,s,r,Bs)},plane_erode:function(t,e,n,s,r,i){return Us(t,e,n,s,r,i,1,!1)},plane_gaussian:function(t,e,n,s,r,i){return Ls(t,e,n,s,r,i,["x","y"],Ms.square)},plane_gaussianx:function(t,e,n,s,r,i){return Ls(t,e,n,s,r,i,["x"],Ms.line)},plane_gaussiany:function(t,e,n,s,r,i){return Ls(t,e,n,s,r,i,["y"],Ms.line)},plane_laplacian:function(t,e,n,s,r){return Ds(t,e,n,s,r,Gs)},plane_sharpen:function(t,e,n,s,r,i){const o=new Float32Array(e*n*3);for(let a=s;a<r;a++)for(let s=0;s<e;s++){const r=(t,s)=>4*(ks(s,n-1)*e+ks(t,e-1)),l=r(s,a),c=r(s-1,a),p=r(s+1,a),u=r(s,a-1),h=r(s,a+1);for(let n=0;n<3;n++)o[3*(a*e+s)+n]=t[l+n]+i*(4*t[l+n]-t[c+n]-t[p+n]-t[u+n]-t[h+n])}return o},plane_sobel:function(t,e,n,s,r){return Ds(t,e,n,s,r,Xs)},plane_sobelx:function(t,e,n,s,r){return Ds(t,e,n,s,r,Ws)},plane_sobely:function(t,e,n,s,r){return Ds(t,e,n,s,r,Hs)},random:function(t,e,n,s){const r=43758.5453*Math.sin(12.9898*(t+.5)+78.233*(n-e-.5)+37.719*s);return r-Math.floor(r)},root:function(t,e){return 2===t?Math.sqrt(e):3===t?Math.sign(e)*Math.pow(Math.abs(e),1/3):Math.pow(e,1/t)},round:function(t,e){const n=Math.pow(10,e);return Math.sign(t)*Math.floor(Math.abs(t)*n+.5)/n},sample:Is,sampleOrZero:function(t,e,n,s,r,i){const o=s+.5,a=r+.5;return o<0||a<0||o>e||a>n?(i[0]=i[1]=i[2]=i[3]=0,i):Is(t,e,n,s,r,i)},scratch:function(){return new Float64Array(4)},smoothstep:function(t,e,n){const s=Math.min(Math.max((n-t)/(e-t),0),1);return s*s*(3-2*s)}});const ir="\\:",or=Object.keys(rr).filter(t=>"function"==typeof rr[t]),ar=t=>Object.assign(Object.create(null),t),lr=ar({r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"}),cr=ar({pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)"}),pr=ar({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:t=>`Math.pow(2, ${t})`,log2:1,expm1:t=>`(Math.exp(${t}) - 1)`,loglog:t=>`Math.log(Math.log(${t}))`,logloglog:t=>`Math.log(Math.log(Math.log(${t})))`,csc:t=>`(1 / Math.sin(${t}))`,sec:t=>`(1 / Math.cos(${t}))`,cot:t=>`(1 / Math.tan(${t}))`,fract:t=>`(${t} - Math.floor(${t}))`,radians:t=>`(${t} * 0.017453292519943295)`,degrees:t=>`(${t} * 57.29577951308232)`,inversesqrt:t=>`(1 / Math.sqrt(${t}))`,atan2:(t,e)=>`Math.atan2(${t}, ${e})`,pow:(t,e)=>`Math.pow(${t}, ${e})`,mod:(t,e)=>`(${t} - ${e} * Math.floor(${t} / ${e}))`,step:(t,e)=>`(${e} < ${t} ? 0 : 1)`,clamp:(t,e,n)=>`Math.min(Math.max(${t}, ${e}), ${n})`,mix:(t,e,n)=>`(${t} + (${e} - ${t}) * ${n})`,smoothstep:(t,e,n)=>`$h_smoothstep(${t}, ${e}, ${n})`}),ur=ar({atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3}),hr=ar({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}),$r=(t,e)=>({kind:t,c:e}),fr=t=>$r("f",[t]),mr=t=>$r("b",[t]),gr=t=>1===t.length?fr(t[0]):$r("v",t),dr=(t,e=0)=>"b"===t.kind?`(${t.c[0]} ? 1 : 0)`:"f"===t.kind?t.c[0]:t.c[e]??t.c[0],yr=t=>"v"===t.kind?t.c.length:1;class xr extends Error{}function br(t){if(t.blendKept)return{blend:!0,source:""};const e=t.params??{},n=new Set([...Object.keys(t.placements??{}),"source","selection"]),s=new wr(e,n,t.space??"srgb");s.graphics=new Set(Object.keys(t.graphics??{})),s.bind=ar(t.bind??{});const r="string"==typeof t.color?{rgba:t.color}:t.color,i=(s,r)=>ws(function(t,e={}){const n=sn(t,e);if(n.error)throw new Error(`Failed to parse expression "${s=t,"string"==typeof s&&s.length>80?`${s.slice(0,77)}…`:s}": ${n.error}`);var s;return n.tree}(s,{names:[...xs,...Object.keys(t.placements??{})],values:[...gs,...Object.keys(e)],blocks:null}),n,{whole:r});for(const t of["rgba","rgb","r","g","b","a"]){if(!r[t])continue;let e;try{e=i(r[t],"rgba"===t)}catch(t){throw new xr(t.message)}s.channel(t,e)}const o=s.source();!function(t,e={}){if("string"!=typeof t)throw new rn("generated code must be a string");const n=t;for(const e of un)t=t.split(e).join("Math.abs");const s=!1!==e.keywords,r=e.variables instanceof RegExp?e.variables:new Set(e.variables??[]),i=t=>r instanceof RegExp?r.test(t):r.has(t),o=e.indexable instanceof RegExp?e.indexable:null;let a=null,l=0;const c=t=>{throw new rn(`not allowed in a formula: ${t}`)},p=()=>a&&("id"===a.type||"num"===a.type||"str"===a.type||"p"===a.type&&(")"===a.value||"]"===a.value||"}"===a.value));for(;l<t.length;){const n=t.slice(l),r=/^\s+/.exec(n);if(r){l+=r[0].length;continue}(n.startsWith("/*")||n.startsWith("//")||n.startsWith("\x3c!--")||n.startsWith("--\x3e"))&&c("a comment");const u=/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(n);if(u&&(!a||"id"!==a.type||!/[\w$]$/.test(t[l-1]??""))){a={type:"num",value:u[0]},l+=u[0].length;continue}if('"'===n[0]){!1===e.strings&&c("a string");const t=/^"(?:[^"\\\n\r\u2028\u2029]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/.exec(n);t||c('a string that is not a plain "…" literal'),p()&&c("a string right after a value"),a={type:"str",value:t[0]},l+=t[0].length;continue}const h=/^[A-Za-z_$][\w$]*/.exec(n);if(h){const t=h[0];if(a&&"p"===a.type&&"."===a.value){const e=a.owner;(e&&ln[e]?ln[e].has(t):an.has(t)&&!on.has(t))||c(`.${t}`)}else cn.has(t)||s&&pn.has(t)||i(t)||c(`the name "${t}"`);a={type:"id",value:t,member:Boolean(a&&"p"===a.type&&"."===a.value)},l+=t.length;continue}const $=hn.find(t=>n.startsWith(t));$||c(`"${n[0]}"`),$n.has($)&&(s||c(`an assignment ("${$}")`),a&&"id"===a.type&&a.member&&c(`an assignment to .${a.value}`)),"["!==$||!p()||o&&"id"===a.type&&i(a.value)&&o.test(a.value)||c("indexing with [ ]");const f={type:"p",value:$};"."===$&&(p()||c('a "." here'),f.owner="id"===a.type&&ln[a.value]?a.value:null),a=f,l+=$.length}}(o,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const a=new Function(...s.parameters(),o);return{source:o,uses:s.uses,pictures:[...s.pictureNames],run(t){a(...s.arguments(t))}}}class wr{constructor(t,e,n="srgb"){this.params=t,this.pictures=e,this.space="srgb"===n?null:n,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(t,e=this.body){const n="$v"+this.n++;return e.push(`let ${n} = ${t};`),n}keep(t,e=this.body){return $r(t.kind,t.c.map(t=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(t)?t:this.temp(t,e)))}fail(t){throw new xr(t)}leaf(t){if("number"===t.type)return fr(`(${t.value.replace(/\.+$/,"")})`);"string"===t.type&&this.fail("a filter has no text: numbers and colours only");const e=t.value,n=/^(-?(?:\d+\.?\d*|\.\d+))%$/.exec(e);if(n)return fr(`(${n[1]} / 100)`);if("t"===e&&this.uses.add("t"),lr[e])return fr(lr[e]);if("rgb"===e)return gr(["$r","$g","$b"]);if("unchanged"===e)return fr("$u");if("selected"===e)return fr(this.pictureHere("selection").c[0]);if(cr[e])return fr(cr[e]);if("true"===e||"false"===e)return mr(e);if(Object.prototype.hasOwnProperty.call(this.params,e)){const t=`$p_${e}`;return"color"===this.params[e].type?gr([`${t}_0`,`${t}_1`,`${t}_2`]):fr(t)}if(this.pictures.has(e)){const t=this.pictureHere(e);return gr(t.c.slice(0,3))}if(e.startsWith("mz_px_")&&this.pictures.has(e.slice(6)))return this.pictureHere(e.slice(6));this.fail(`unknown name "${e}"`)}pictureHere(t){if(!this.perPixel.has(t)){const e=this.sampler(t,"$px","$py");this.perPixel.set(t,this.keep(e))}return this.perPixel.get(t)}sampler(t,e,n){const s=this.scratchArray();return"source"===t?(this.uses.add("source"),this.body.push(`$h_sample($S, $w, $h, ${e}, ${n}, ${s});`)):(this.pictureNames.add(t),this.body.push(`$h_picture($Q_${t}, $qw_${t}, $qh_${t}, $w, $h, $qz_${t}, $qx_${t}, $qy_${t}, $qa_${t}, $qm_${t}, ${e}, ${n}, ${s});`)),this.space&&"selection"!==t&&this.body.push(`$h_col_to${this.space}(${s}[0], ${s}[1], ${s}[2], ${s});`),gr([0,1,2,3].map(t=>`${s}[${t}]`))}scratchArray(){const t="$T"+this.scratch++;return this.pre.push(`let ${t} = $h_scratch();`),t}value(t){return"op"===t.type?this.op(t):this.leaf(t)}op(t){const{op:e,args:n}=t,s=e.startsWith(ir)?e.slice(2):null;if(null!==s)return this.call(s,n,t);const r=()=>n.map(t=>this.value(t));switch(e){case"+":case"-":case"*":case"/":{const[t,n]=r();return this.componentwise([t,n],(t,n)=>`(${t} ${e} ${n})`)}case"neg":return this.componentwise(r(),t=>`(-${t})`);case"^":return this.power(n);case"mod":return this.componentwise(r(),pr.mod);case"<":case">":case"≤":case"≥":{const[t,n]=r(),s={"≤":"<=","≥":">="}[e]??e;return mr(`(${dr(t)} ${s} ${dr(n)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[t,n]=r(),s=Math.max(yr(t),yr(n)),i=Array.from({length:s},(e,s)=>`${dr(t,s)} === ${dr(n,s)}`).join(" && ");return mr("≠"===e||"≠="===e?`!(${i})`:`(${i})`)}case"≈":{const[t,e]=r();return mr(`(Math.abs(${dr(t)} - ${dr(e)}) < 1e-5)`)}case"&":{const[t,e]=r();return mr(`(${this.truth(t)} && ${this.truth(e)})`)}case"|":{const[t,e]=r();return mr(`(${this.truth(t)} || ${this.truth(e)})`)}case"\\xor":{const[t,e]=r();return mr(`(${this.truth(t)} !== ${this.truth(e)})`)}case"\\nand":{const[t,e]=r();return mr(`!(${this.truth(t)} && ${this.truth(e)})`)}case"\\nor":{const[t,e]=r();return mr(`!(${this.truth(t)} || ${this.truth(e)})`)}case"\\not":{const[t]=r();return mr(`!${this.truth(t)}`)}case"?:":return this.ternary(n);case"max":case"min":return this.componentwise(r(),(...t)=>`Math.${e}(${t.join(", ")})`);case"sum":return this.componentwise(r(),(...t)=>`(${t.join(" + ")})`);case"prod":return this.componentwise(r(),(...t)=>`(${t.join(" * ")})`);case"mean":return this.componentwise(r(),(...t)=>`((${t.join(" + ")}) / ${t.length})`);case"()":case"[]":case"{}":case"(]":case"[)":{const t=r().flatMap(t=>"b"===t.kind?[dr(t)]:t.c.map((e,n)=>dr(t,n)));return t.length>4&&this.fail("a colour has at most 4 values (r, g, b, a)"),gr(t)}case"!":return this.componentwise(r(),t=>`$h_factorial(${t})`);case"perm":return this.componentwise(r(),(t,e)=>`$h_perm(${t}, ${e})`);case"comb":return this.componentwise(r(),(t,e)=>`($h_perm(${t}, ${e}) / $h_factorial(${e}))`);case"gcd":return this.componentwise(r(),(...t)=>t.reduce((t,e)=>`$h_gcd(${t}, ${e})`));case"round":{const[t,e]=r();return this.componentwise([t,e],(t,e)=>`$h_round(${t}, ${e})`)}case"log":{const[t,e]=r();return this.componentwise([t,e],(t,e)=>`(Math.log(${e}) / Math.log(${t}))`)}case"root":{const[t,e]=r();return this.componentwise([t,e],(t,e)=>`$h_root(${t}, ${e})`)}case"∈":case"∉":return this.membership(t);case"random":return this.random();case"_":{const[t,e]=n;if("symbol"===t.type&&("number"===e.type||"symbol"===e.type))return this.leaf({type:"symbol",value:`${t.value}_${e.value}`});break}}if(pr[e])return this.builtin(e,r());this.fail(`"${e}" isn't available in a filter`)}truth(t){return"b"===t.kind?t.c[0]:`(${dr(t)} !== 0)`}componentwise(t,e){const n=t.map(yr),s=Math.max(...n),r=new Set(n.filter(t=>t>1));r.size>1&&this.fail(`can't combine vectors of ${[...r].join(" and ")} values`);const i=Array.from({length:s},(n,s)=>e(...t.map(t=>dr(t,s))));return this.keep(gr(i))}builtin(t,e){const n=pr[t];if(ur[t]&&e.length!==ur[t]&&this.fail(`${t}() takes ${ur[t]} values`),"function"==typeof n)return this.componentwise(e,n);const s=1===n?t:n;return this.componentwise(e,(...t)=>`Math.${s}(${t.join(", ")})`)}power([t,e]){const n="number"===e.type&&/^-?\d+$/.test(e.value)?Number(e.value):null,s=this.keep(this.value(t)),r=t=>this.componentwise([s],e=>Array(t).fill(e).join(" * "));return 0===n?this.componentwise([s],()=>"1"):null!==n&&n>=1&&n<=4?r(n):null!==n&&n<=-1&&n>=-4?this.componentwise([r(-n)],t=>`(1 / ${t})`):"symbol"===t.type&&"e"===t.value?this.componentwise([this.value(e)],t=>`Math.exp(${t})`):"number"===t.type&&"2"===t.value?this.componentwise([this.value(e)],t=>`Math.pow(2, ${t})`):this.componentwise([s,this.value(e)],(t,e)=>`Math.pow(${t}, ${e})`)}ternary([t,e,n]){const s=this.truth(this.value(t)),r=t=>"symbol"===t.type&&"unchanged"===t.value;let i=r(e)?null:this.value(e),o=r(n)?null:this.value(n);const a=t=>"b"===t.kind?mr("($u > 0.5)"):"f"===t.kind?fr("$u"):gr(["$k0","$k1","$k2","$k3"].slice(0,4===t.c.length?4:3));if(!i&&!o)return fr("$u");if(i||(i=a(o)),o||(o=a(i)),"b"===i.kind&&"b"===o.kind)return mr(this.temp(`(${s} ? ${i.c[0]} : ${o.c[0]})`));const l=Math.max(yr(i),yr(o)),c=Array.from({length:l},(t,e)=>this.temp(`(${s} ? ${dr(i,e)} : ${dr(o,e)})`));return gr(c)}membership(t){const[e,n]=t.args,s=dr(this.value(e)),r="∉"===t.op;let i;if("op"===n.type&&["()","[]","(]","[)"].includes(n.op)&&2===n.args.length){const[t,e]=n.args.map(t=>dr(this.value(t)));i=`(${s} ${"["===n.op[0]?">=":">"} ${t} && ${s} ${"]"===n.op[1]?"<=":"<"} ${e})`}else"op"===n.type&&"{}"===n.op?i=`(${n.args.map(t=>`${s} === ${dr(this.value(t))}`).join(" || ")})`:"symbol"===n.type&&["ℝ","ℤ","ℕ"].includes(n.value)?i={"ℝ":`Number.isFinite(${s})`,"ℤ":`Number.isInteger(${s})`,"ℕ":`(Number.isInteger(${s}) && ${s} > 0)`}[n.value]:this.fail("∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ");return mr(r?`!${i}`:i)}random(){return this.uses.add("random"),fr(this.temp("$h_random($px, $py, $h, ++$seed)"))}call(t,e,n){const s=()=>e.map(t=>this.value(t));if(t.startsWith("mz_sample_")){const e=t.slice(10),[n,r]=s(),[i,o]=r?[dr(n),dr(r)]:[dr(n,0),dr(n,1)];if("image"===e){const t=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${i}, ${o}, ${t});`),this.keep(gr([0,1,2,3].map(e=>`${t}[${e}]`)))}return this.pictures.has(e)||this.fail(`unknown picture "${e}"`),this.keep(this.sampler(e,i,o))}if(t.startsWith("mz_at_")){const e=t.slice(6),[n,r]=s(),[i,o]=r?[dr(n),dr(r)]:[dr(n,0),dr(n,1)];if("image"===e){const t=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${i}, ${o}, ${t});`),gr([0,1,2].map(e=>`${t}[${e}]`))}return this.pictures.has(e)||this.fail(`unknown picture "${e}"`),this.keep(gr(this.sampler(e,i,o).c.slice(0,3)))}if(t.startsWith("mz_width_")||t.startsWith("mz_height_")){const e=t.replace(/^mz_(width|height)_/,"");return this.pictureNames.add(e),fr(t.startsWith("mz_width_")?`$qw_${e}`:`$qh_${e}`)}switch(t){case"pixel":{const[t,e]=s().map(t=>dr(t)),n=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${t}, ${e}, ${n});`),this.keep(gr([0,1,2,3].map(t=>`${n}[${t}]`)))}case"red":case"green":case"blue":case"alpha":case"luma":{let n;2===e.length?n=this.call("pixel",e):1===e.length?n=this.value(e[0]):this.fail(`${t}() takes a colour, or a position px, py`);const s={red:0,green:1,blue:2,alpha:3}[t];return"luma"===t?fr(`(${dr(n,0)} * 0.299 + ${dr(n,1)} * 0.587 + ${dr(n,2)} * 0.114)`):"alpha"===t&&3===yr(n)?fr("1"):fr(dr(n,s))}case"length":{const[t]=s();return fr(`Math.sqrt(${t.c.map((e,n)=>`${dr(t,n)} * ${dr(t,n)}`).join(" + ")})`)}case"distance":{const[t,e]=s(),n=this.componentwise([t,e],(t,e)=>`(${t} - ${e})`);return fr(`Math.sqrt(${n.c.map(t=>`${t} * ${t}`).join(" + ")})`)}case"dot":{const[t,e]=s(),n=Math.max(yr(t),yr(e));return fr(`(${Array.from({length:n},(n,s)=>`${dr(t,s)} * ${dr(e,s)}`).join(" + ")})`)}case"normalize":{const[t]=s(),e=this.temp(`Math.sqrt(${t.c.map((e,n)=>`${dr(t,n)} * ${dr(t,n)}`).join(" + ")})`);return this.componentwise([t],t=>`(${t} / ${e})`)}case"cross":{const[t,e]=s();3===yr(t)&&3===yr(e)||this.fail("cross() takes two colours (3 values each)");const[n,r,i]=t.c,[o,a,l]=e.c;return this.keep(gr([`(${r} * ${l} - ${i} * ${a})`,`(${i} * ${o} - ${n} * ${l})`,`(${n} * ${a} - ${r} * ${o})`]))}case"convolve":{const t=s().map(t=>dr(t));9!==t.length&&this.fail("convolve() takes 9 numbers: the 3×3 kernel, row by row");const e=this.scratchArray();return this.body.push(`$h_convolve($I, $w, $h, $px, $py, ${t.join(", ")}, ${e});`),gr([0,1,2].map(t=>`${e}[${t}]`))}case"mz_zoom":case"mz_shift":case"mz_rotate":case"mz_crop":case"mz_tile":case"mz_flipx":case"mz_flipy":return this.geometry(t.slice(3),s().map(t=>dr(t)));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 e=s(),n=3===e.length?e.map(t=>dr(t)):[0,1,2].map(t=>dr(e[0],t));1!==e.length&&3!==e.length&&this.fail(`${t}() takes a colour`);const r=this.scratchArray();return this.body.push(`$h_col_${t}(${n.join(", ")}, ${r});`),this.keep(gr([0,1,2].map(t=>`${r}[${t}]`)))}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(t,s());case"asin":return this.builtin("arcsin",s());case"acos":return this.builtin("arccos",s());case"atan":return 2===e.length?this.builtin("atan2",s()):this.builtin("arctan",s());case"log":return this.builtin("ln",s());case"max":case"min":return this.componentwise(s(),(...e)=>`Math.${t}(${e.join(", ")})`)}if(hr[t])return this.neighbourhood(t,e);this.fail(`unknown function "${t}"`)}geometry(t,e){const n=(t,e)=>this.keep(gr([t,e]));switch(t){case"zoom":{const[t,s="0.5",r="0.5"]=e,i=n(`(${s} * $w - 0.5)`,`(${r} * $h - 0.5)`);return n(`(${i.c[0]} + ($px - ${i.c[0]}) / ${t})`,`(${i.c[1]} + ($py - ${i.c[1]}) / ${t})`)}case"shift":{const[t,s]=e;return n(`($h_fmod($px - ${t} + 0.5, $w) - 0.5)`,`($h_fmod($py - ${s} + 0.5, $h) - 0.5)`)}case"rotate":{const[t,s="0.5",r="0.5"]=e,i=n(`(${s} * $w - 0.5)`,`(${r} * $h - 0.5)`),o=n(`($px - ${i.c[0]})`,`($py - ${i.c[1]})`),a=this.keep(gr([`Math.cos(${t})`,`Math.sin(${t})`]));return n(`(${i.c[0]} + ${a.c[0]} * ${o.c[0]} + ${a.c[1]} * ${o.c[1]})`,`(${i.c[1]} + ${a.c[0]} * ${o.c[1]} - ${a.c[1]} * ${o.c[0]})`)}case"crop":{const[t,s,r,i]=e;return n(`((${t} + (${r} - ${t}) * ($px + 0.5) / $w) * $w - 0.5)`,`((${s} + (${i} - ${s}) * ($py + 0.5) / $h) * $h - 0.5)`)}case"tile":{const[t,s=t]=e;return n(`($h_fmod(($px + 0.5) * ${t}, $w) - 0.5)`,`($h_fmod(($py + 0.5) * ${s}, $h) - 0.5)`)}case"flipx":return n("($w - 1 - $px)","$py");case"flipy":return n("$px","($h - 1 - $py)")}this.fail(`unknown geometry ${t}`)}neighbourhood(t,e){const n=hr[t];if(e.every(t=>this.isUniform(t))){const s=e.map(t=>dr(this.uniformValue(t))),r=`${t}(${s.join(",")})`;if(!this.planes.has(r)){const e=`$N${this.planes.size}`;this.pre.push(`let ${e} = $h_plane_${t}($I, $w, $h, $y0, $y1${s.map(t=>`, ${t}`).join("")});`),this.planes.set(r,e)}const i=this.planes.get(r);return 3===n?gr([0,1,2].map(t=>`${i}[$j3 + ${t}]`)):fr(`${i}[$j]`)}const s=e.map(t=>dr(this.value(t)));if(1===n)return fr(this.temp(`$h_at_${t}($I, $w, $h, $px, $py${s.map(t=>`, ${t}`).join("")})`));const r=this.scratchArray();return this.body.push(`$h_at_${t}($I, $w, $h, $px, $py${s.map(t=>`, ${t}`).join("")}, ${r});`),gr([0,1,2].map(t=>`${r}[${t}]`))}isUniform(t){return"number"===t.type||("symbol"===t.type?["w","h","t"].includes(t.value)||Boolean(cr[t.value])||Object.prototype.hasOwnProperty.call(this.params,t.value)&&"color"!==this.params[t.value].type:"op"===t.type&&!t.op.startsWith(ir)&&"random"!==t.op&&t.args.every(t=>this.isUniform(t)))}uniformValue(t){const e=this.body;this.body=this.pre;try{return this.value(t)}finally{this.body=e}}channel(t,e){const n="rgba"===t||"rgb"===t?"$gray":`$c${"rgba".indexOf(t)}`;this.body.push(`$u = ${n}; $k0 = $c0; $k1 = $c1; $k2 = $c2; $k3 = $c3;`);const s=this.value(e),r=yr(s),i=t=>dr(s,t);if("rgba"===t){2===r&&this.fail("a colour is one number (grey), three (r, g, b) or four (r, g, b, a) — not two");const t=1===r?[i(0),i(0),i(0),"1"]:3===r?[i(0),i(1),i(2),"1"]:[0,1,2,3].map(i);this.body.push(`$c0 = ${t[0]}; $c1 = ${t[1]}; $c2 = ${t[2]}; $c3 = ${t[3]};`)}else if("rgb"===t){2===r&&this.fail("a colour is one number (grey), three (r, g, b) or four — not two");const t=1===r?[i(0),i(0),i(0)]:[i(0),i(1),i(2)];this.body.push(`$c0 = ${t[0]}; $c1 = ${t[1]}; $c2 = ${t[2]};`)}else{const e="rgba".indexOf(t),n=1===r?i(0):3===r&&"a"===t?"1":i(e);this.body.push(`$c${e} = ${n};`)}}parameters(){return["$I","$O","$S","$w","$h","$t","$P","$op","$y0","$y1",...[...this.pictureNames].flatMap(t=>[`$Q_${t}`,`$qw_${t}`,`$qh_${t}`,`$qz_${t}`,`$qx_${t}`,`$qy_${t}`,`$qa_${t}`,`$qm_${t}`]),...or.map(t=>`$h_${t}`)]}arguments(t){const e=[...this.pictureNames];return[t.input,t.output,t.source,t.width,t.height,t.t,t.params,t.opacity,t.y0??0,t.y1??t.height,...e.flatMap(e=>{const n=t.pictures[this.bind?.[e]??e]??(this.graphics?.has(e)?As:vs),s=t.placements[e]??{};return[n.data,n.width,n.height,Number(s.zoom??1),Number(s.x??.5),Number(s.y??.5),Number(s.angle??0),Ns(s.place)]}),...or.map(t=>rr[t])]}source(){const t=Object.entries(this.params).map(([t,e],n)=>"color"===e.type?`let $p_${t}_0 = $P[${n}][0], $p_${t}_1 = $P[${n}][1], $p_${t}_2 = $P[${n}][2];`:`let $p_${t} = $P[${n}];`);return[...t.map(t=>t.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(t=>` ${t}`)," $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")}}const _r="undefined"!=typeof self&&"function"==typeof self.postMessage&&"undefined"==typeof window?{on:t=>{self.onmessage=e=>t(e.data)},post:(t,e)=>self.postMessage(t,e)}:await(async()=>{const{parentPort:t}=await(import("node:worker_threads"));return{on:e=>t.on("message",e),post:(e,n)=>t.postMessage(e,n)}})();let Mr=[];const vr={};let Ar=null,Er=null;_r.on(t=>{try{if("init"===t.type)Mr=t.passes.map(t=>br(t)),_r.post({id:t.id,ok:!0});else if("picture"===t.type)"source"===t.name?Ar=t.picture:vr[t.name]=t.picture,_r.post({id:t.id,ok:!0});else if("run"===t.type){const{width:e,height:n,y0:s,y1:r}=t,i=e*n*4,o=t.output??(Er&&Er.length===i?Er:Er=new Float32Array(i));Mr[t.pass].run({input:t.input,output:o,source:Ar.data,width:e,height:n,t:t.t,params:t.params,opacity:t.opacity,pictures:vr,placements:t.placements,y0:s,y1:r});const a=s*e*4,l=r*e*4;if(t.quantize)for(let t=a;t<l;t++){const e=o[t];o[t]=e>0?e<1?Math.round(255*e)/255:1:0}if(t.output)_r.post({id:t.id,ok:!0});else{const e=o.slice(a,l);_r.post({id:t.id,ok:!0,band:e},[e.buffer])}}}catch(e){_r.post({id:t.id,ok:!1,error:e.message})}});
|