@mathzetta/qblur 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,29 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — first release
4
+
5
+ The filter format, its compiler and two runners that give the same pixels.
6
+
7
+ - **The format, `mathzetta-filter/1`** (frozen: later versions add, never change or remove): a filter is
8
+ maths over a pixel, or a JSON document with a name, an author, knobs (`params`: numbers, colours, menus,
9
+ boxes), notes, other pictures (`images`, each placed), text and shapes and brush strokes (`graphics`), a
10
+ colour space, or `steps` — a chain of other filters with their own settings and opacity, which nests and
11
+ keeps its authors' names. `normalizeFilter`, `validateFilter`, `compileFilter`; sharing as JSON or a link
12
+ (`filterToJSON`, `filterToLink`, `readFilter`). A filter is only maths: running someone else's is safe (a text's font, if it names one, is fetched).
13
+ - **`applyFilter(picture, filter, { params, t, images, engine, canvas, maxSize })`** (`@mathzetta/qblur/apply`, `dist/qblur-apply.js`): the one call — a filter in any
14
+ form (maths, a document, JSON, a link, a compiled filter, or a built-in filter's name) on an `<img>`,
15
+ `<video>`, canvas, ImageData or `{ data, width, height }`; a 2D canvas back in a page, the picture in Node. Pictures over 4096 px on the long side (2048 on the CPU)
16
+ are scaled down first; `maxSize` sets the limit.
17
+ - **`<qblur-image>`** (`@mathzetta/qblur/element`, `dist/qblur-element.js`): a picture with a filter on it as an HTML
18
+ element; attributes `src`, `filter`, `params`, `t`, `animate`, `engine`, `alt`, `crossorigin`.
19
+ - **Runners**: WebGL 1 and 2 (`createFilterRunner`; 8-bit, half or float textures between passes) and plain
20
+ JavaScript (`createCpuRunner`; browsers and Node, `drawAsync` over workers for big pictures, generated
21
+ code checked before it runs); `createRunner` picks the GPU when it can.
22
+ - **Saving**: `toBlob` (PNG written by the package — indexed when there are few colours — so it works in
23
+ Node; JPEG and WebP in a browser), `encodeGif` (with gifenc passed in), `encodePng` — in `@mathzetta/qblur/apply`.
24
+ - **79 built-in filters** in `LIBRARY`, in seven `GROUPS`.
25
+ - **Text, shapes and brush strokes** drawn into frame-sized pictures (`renderGraphics`, `rasterizeStrokes`),
26
+ with web fonts and separate shadow layers.
27
+ - **Builds** on jsDelivr/unpkg: an ES module and a classic script, each with MathZetta inside or without
28
+ it, a GPU-only core, the element, and the CPU worker. TypeScript declarations for the package and the
29
+ element. MIT; no dependencies (MathZetta 1.x is a peer).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MathZetta Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,144 @@
1
- # Temporary Holding Version
1
+ # qblur
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Image filters written as maths — the site is **qblur** (qblur.com). A filter is an expression over a pixel —
4
+ `1 - rgb`, `if gray > 0.5 then (1, 0, 0)`, `gaussian(3)`,
5
+ `mix(source, rgb, luma(mask))` — or a JSON document with parameters, extra
6
+ pictures (masks, overlays) and chains of other people's filters. The
7
+ package turns one into WebGL shaders (through MathZetta's GLSL output) and
8
+ runs it on a picture.
9
+
10
+ ```js
11
+ import { applyFilter, toBlob } from '@mathzetta/qblur/apply'; // one call, and saving: its own entry
12
+
13
+ const canvas = await applyFilter(img, 'Sepia'); // a built-in filter, by name
14
+ const sharp = await applyFilter(img, 'Threshold', { params: { cutoff: 0.3 } }); // …with a knob set
15
+ const mine = await applyFilter(img, 'if gray > 0.5 then (1, 0, 0) else rgb'); // or maths
16
+ const png = await toBlob(mine); // PNG (JPEG, WebP in a browser)
17
+ // pictures over 4096 px on the long side (2048 on the CPU) are scaled down first: { maxSize } changes it
18
+ ```
19
+
20
+ ```html
21
+ <qblur-image src="photo.jpg" filter="Vignette" params='{"strength": 2}' alt="…"></qblur-image>
22
+ <script type="module" src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur-element.js"></script>
23
+ ```
24
+
25
+ For live knobs and video, a runner of your own:
26
+
27
+ ```js
28
+ import { compileFilter, createRunner, filterToLink } from '@mathzetta/qblur';
29
+
30
+ const compiled = compileFilter({ name: 'Old film', params: { strength: 1 }, color: 'gray + strength * 0.1 * sin(py)' });
31
+ const { runner } = createRunner(compiled, { gl: canvas.getContext('webgl') });
32
+ runner.setImage(img).draw({ t: 0, canvas });
33
+ filterToLink(compiled); // a URL anyone can open
34
+ ```
35
+
36
+ Needs `mathzetta` 1.x (a peer dependency: `npm install @mathzetta/qblur mathzetta`). TypeScript types are included.
37
+ Three entries: `@mathzetta/qblur` (the filters, the runners, the library), `@mathzetta/qblur/apply` (`applyFilter` and saving) and
38
+ `@mathzetta/qblur/element` (`<qblur-image>`).
39
+ Saving: `toBlob` (PNG anywhere, JPEG/WebP in a browser) and `encodeGif` (bring
40
+ [gifenc](https://www.npmjs.com/package/gifenc): the package has no dependencies of its own). See [CHANGELOG.md](CHANGELOG.md). [docs/library.md](docs/library.md) is how to use the
41
+ library on your own pages — the CDN, the builds, the API, with examples that `npm run check:docs` runs.
42
+ [docs/filters.md](docs/filters.md) is the full guide to the maths: what an expression can use, animation, neighbourhoods,
43
+ geometry, several pictures, sharing and the API.
44
+
45
+ It runs on the GPU (WebGL) or the CPU (plain JavaScript, also in Node):
46
+ `createRunner(compiled, { gl })` uses the GPU whenever WebGL is there (a
47
+ filter's shaders compile once, then serve every picture and frame) and the
48
+ CPU without it — both give the same pixels. See "Running it" in the guide.
49
+
50
+ ```bash
51
+ npm install # links ../mathzetta/packages/mathzetta (the public repo, checked out beside this one) for development
52
+ npm test # format, compiler, sharing, the CPU runner (pixels, bands, workers, safety) — no browser
53
+ npm run serve # http://localhost:8016/demo/ — the editor and library ("runs on": auto / GPU / CPU)
54
+ npm run check # every library filter through real WebGL in headless Chrome
55
+ npm run check:cpu # …and the CPU runner on the same pictures, compared pixel by pixel
56
+ npm run check:nowebgl # Chrome without WebGL: the editor must fall back to the CPU
57
+ npm run build # site/ — the editor bundled for any static host (no node_modules, no import map)
58
+ npm run check:site # build, then run the checks against site/
59
+ ```
60
+
61
+ Before building for a real address, set `SITE_URL=https://…/` (or
62
+ `"homepage"` in package.json) so pages get absolute canonical, `og:url` and
63
+ `og:image` addresses; the preview cards are `demo/share/*.jpg` (`node tools/share-cards.mjs` remakes them).
64
+
65
+ `site/` is the deployable editor: `index.html`, `app.js` (the page with
66
+ MathZetta and this package bundled in), `cpu-worker.js`, `guide.html` (the
67
+ guide rendered, heading ids as on GitHub) and `photos/`. Default photos go
68
+ in `demo/photos/` with an `index.json` — see the README there.
69
+ Serve the folder from anywhere (GitHub Pages, S3, a CDN); share links are
70
+ `#…` fragments, so nothing else is needed.
71
+
72
+ ## From a CDN
73
+
74
+ > Not on npm yet: the addresses below are where releases will be (placeholders until the first one).
75
+ > Search for `cdn.jsdelivr.net/npm/@mathzetta/qblur` to find every place they are written: this README,
76
+ > docs/library.md (and the site's library.html built from it).
77
+
78
+ Every npm release's `dist/` is on jsDelivr (and unpkg), MathZetta's GLSL output bundled in —
79
+ [docs/library.md](docs/library.md) has working examples of each way in:
80
+
81
+ ```html
82
+ <script type="module">
83
+ import { compileFilter, createRunner } from 'https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.js';
84
+ </script>
85
+ <!-- or a classic script: window.QBlur -->
86
+ <script src="https://cdn.jsdelivr.net/npm/@mathzetta/qblur@0.1/dist/qblur.global.min.js"></script>
87
+ ```
88
+
89
+ Every build comes **with MathZetta inside or without it** (`*.external.*`). Sizes as the CDN sends them (compressed):
90
+
91
+ | | ES module | classic `<script>` (`window.QBlur`) |
92
+ |---|---|---|
93
+ | everything, MathZetta inside (the classic script: `@mathzetta/qblur/apply` too) | `qblur.js` 54 KB | `qblur.global.min.js` 58 KB |
94
+ | `@mathzetta/qblur/apply`: applyFilter and saving, MathZetta inside | `qblur-apply.js` 56 KB | |
95
+ | the `<qblur-image>` element (applyFilter and MathZetta inside) | `qblur-element.js` 56 KB | |
96
+ | everything, without MathZetta | `qblur.external.js` 26 KB | `qblur.external.global.min.js` 30 KB |
97
+ | compile + run on the GPU only (no CPU runner, strokes, graphics, library) | `qblur.core.js` 33 KB | |
98
+ | the CPU runner's worker (`drawAsync` on big pictures), found beside the bundle | `cpu-worker.js` 31 KB | |
99
+
100
+ MathZetta (its GLSL output and the parser) is about half of a full build. Without it, the page
101
+ loads MathZetta once itself: a classic page puts a MathZetta `<script>` first — `mathzetta.min.js`
102
+ or the `glsl` flavour (GLSL + formulas is what the filters use) — and the external classic build
103
+ reads `window.MathZetta`; a module page maps `mathzetta`, `mathzetta/glsl` and `mathzetta/formulas`
104
+ to MathZetta's bundle with an import map (every name can point at the one file). The object models and their runtimes (the site's
105
+ `models/`, `ort/`) are not in the package: they belong to the editor at qblur.com.
106
+ Publishing is `npm publish` (`prepublishOnly` runs the tests and the build).
107
+
108
+ ## Files
109
+
110
+ | | |
111
+ | --- | --- |
112
+ | `src/format.js` | the filter document: normalize, validate, compile to passes, JSON and share links |
113
+ | `src/runtime.js` | the WebGL runner: textures, passes, live parameters |
114
+ | `src/cpu.js` | filter expressions → typed, straight-line JavaScript per pass (through the whitelist gate) |
115
+ | `src/cpu-helpers.js` | what that code calls: texture-like sampling, neighbourhood planes (separable, by bands of rows) |
116
+ | `src/cpu-runner.js`, `src/cpu-worker.js` | the CPU runner (draw / drawAsync over workers) |
117
+ | `src/auto.js` | `createRunner` / `chooseEngine`: GPU or CPU, and why |
118
+ | `src/library.js` | `LIBRARY`: the built-in filters, each with a `group` (`GROUPS`); every one validated, compiled and round-tripped by `npm test`. Canny edges is a nine-pass chain of plain expressions |
119
+ | `demo/avatar/`, `demo/splash/`, `demo/move/`, `demo/text/` | the small apps: a profile picture (framed on the person, a style, the background blurred, replaced or removed; a circle, a square or a cut-out sticker), a colour splash (click colours to keep), a photo that moves (saved as a GIF or video), fancy text (letters and border each coloured by a formula — gold, chrome, fire, a picture, or your own — as a transparent PNG or a GIF) — a few choices each; `npm run check:apps` |
120
+ | `demo/kit.js`, `demo/apps.css` | what the small apps share: open a picture, the sample photos, a filter on the GPU or CPU (`createView`), download, GIF |
121
+ | `demo/gif.js` | a GIF decoder (all frames, delays, disposal) so GIFs play and filter frame by frame; `gifenc` (a dev dependency, bundled) writes "Save as GIF" |
122
+ | `demo/png.js` | a PNG writer for what the browser's cannot do: indexed (1/2/4/8-bit) when the picture has few colours, RGB when nothing is transparent, forced palettes with dithering |
123
+ | `demo/export.js` | the Export panel: format with estimated sizes (auto picks the smallest sensible), quality / colours, size, a crop dragged on the picture, background for JPEG |
124
+ | `demo/livewire.js` | selecting an object: intelligent scissors (a cost map from the gradient, Dijkstra once per clicked point, the wire to the cursor walked back in real time, snapping, path cooling) and a colour-fill wand; the mask is `selected` in the maths |
125
+ | `src/graphics.js` | text and shapes: `normalizeGraphic` (validation), `drawGraphic` onto any 2D canvas, `loadGraphicFonts`, `renderGraphics(compiled, w, h)` for the runner |
126
+ | `tools/shot.mjs` | a screenshot of a page of this repo after running some JavaScript in it (headless Chrome) |
127
+ | `src/strokes.js` | brushes: recorded strokes drawn again for every frame (round, soft, marker, chalk, spray; pressure or speed; timing; passes; clip to a mask) into a picture of coverage, age, passes and progress; `traceContours` for outlining a selection |
128
+ | `demo/tracker.js` | tracking an object through a clip: patch-matched outline points held to the group's move/scale/turn, a colour model per keyframe so the outline follows the object's edge, a confidence per frame, keyframes propagated both ways |
129
+ | `demo/examples.js` | the Examples tour at the top of the editor: each example's filter, picture, features and step-by-step explanation (tested to compile; the checker runs each) |
130
+ | `demo/ai.js` | finding objects: MobileSAM on the site (`SHIPPED_MODELS`, run by ONNX Runtime Web in `ort/`; every site file stays under 25 MiB for Cloudflare Pages); in development a menu also offers RF-DETR Small and Nano and MagicTouch 1 and 2 (`demo/models/`, Apache-2.0) to compare; nothing loads until asked |
131
+ | `demo/rfdetr.js` | the model's input (stretched, normalized) and its decoding (boxes, labels, outlines); used by the page and by Node (test/ai.test.js) |
132
+ | `demo/sam.js` | MobileSAM: the picture scaled for its encoder, the decoder's prompt (points, box), the surest of its masks; used by the page and by Node |
133
+ | `tools/export-model.py` | remakes the ONNX models in demo/models/ (RF-DETR Small and Nano, MobileSAM; Python `rfdetr`) |
134
+ | `tools/compare-ai.mjs` | every object model on the same things in a photo, drawn side by side with timings (built site, headless Chrome) |
135
+ | `demo/app.js` | the editor's script; `tools/build.mjs` bundles it (resolving the page's import map) into `site/` |
136
+ | `demo/help.js` | the in-page cheat sheet, and `explain()`: an error → a hint and the help section / guide heading for it |
137
+ | `demo/photos/` | default photos (`index.json` lists them); the editor opens on the first |
138
+ | `tools/markdown.mjs` | the small Markdown renderer behind `site/guide.html` |
139
+ | `demo/index.html` | editor, library, share links; what `npm run check` drives |
140
+ | `docs/filters.md` | the guide |
141
+
142
+ This was `src/filters/` and `demos/filters.html` in MathZetta until
143
+ 2026-10-16; the GLSL expression output (`toGLSL`, `filterShader`) stayed
144
+ there as `mathzetta/glsl`.
@@ -0,0 +1,2 @@
1
+ /* qblur 0.1.0 — MIT licence — https://qblur.com */
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="\\:",o=t=>"string"==typeof t&&t.startsWith(r)&&t.length>2;function i(t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:o(t)?a:void 0}const a=n(t),l=100,c={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,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},p=t=>Object.prototype.hasOwnProperty.call(c,t),h=new Set(["^","?:","?","log"]),u=["(","{","["],$=[")","}","]"];function m(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[c])Object.setPrototypeOf(t,null);const f=t=>({type:"number",value:String(t)}),g=t=>({type:"symbol",value:t}),d=(t,e)=>({type:"op",op:t,args:e}),y=['"',"'","`"];function x(t){return m(t,!0)?f(t):y.includes(t[0])?{type:"string",value:t}:g(t)}const b={"0-":"neg",sqrtpow:"root",pow:"^","==":"=","!==":"≠="};function w(t,e,n=null){e(t,n),"op"===t.type&&t.args.forEach(n=>w(n,e,t))}function _(t){let e="";return w(t,t=>{!e&&"symbol"===t.type&&1===t.value.length&&/[a-zA-Zʹ-Ͽ]/.test(t.value)&&(e=t.value)}),e}for(const t of[b])Object.setPrototypeOf(t,null);function M(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 A(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 o=v(n,t,r);o?(s+=e.get(t.slice(r,r+o)),r+=o):s+=t[r++]}return s}}function v(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 A(t){const e=new Set([t.toLowerCase(),t.toUpperCase(),E(t)]);return e.delete(t),e}function E(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 N="({[",O=")}]";function I(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 S(t,e){const n=[];let s=0,r=0;for(let o=0;o<t.length;o++)N.includes(t[o])?s++:O.includes(t[o])?s--:0===s&&t.startsWith(e,o)&&(n.push(t.slice(r,o)),o+=e.length-1,r=o+1);return n.push(t.slice(r)),n}function k(t,e,n){let s=0;const r=new RegExp(`\\b${n}\\b`,"iy");for(let n=e;n<t.length;n++)if(N.includes(t[n]))s++;else if(O.includes(t[n])){if(--s<0)return-1}else if(0===s&&(r.lastIndex=n,r.test(t)))return n;return-1}function j(t,e){let n=0;for(let s=e;s<t.length;s++)if(N.includes(t[s]))n++;else if(O.includes(t[s])&&--n<0)return s;return t.length}function q(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 R(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(N.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="",o="",i=0;for(let a=e+2;a<t.length;a++){if(")]".includes(t[a])?n--:"([".includes(t[a])&&n++,0===n){i=a;break}1===n&&","===t[a]?s++:0===s?r+=t[a]:o+=t[a]}1===s&&(t=t.slice(0,e+1)+"_{"+o+"}("+r+")"+t.slice(i+1))}return t}function z(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 T(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 o=/^[A-Za-z0-9.\u0370-\u03FF]+/.exec(t.slice(n+1))?.[0]??"";return"{"+s+","+o+"}"+t.slice(n+1+o.length)}return t}const C=new Set(["pmatrix","bmatrix","vmatrix"]);function P(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+"}"),o=t.indexOf("\\begin{"+s+"}",e+1);if(r<0||-1!==o&&o<r)return!1;const i=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 C.has(s)?s+"("+i.join(", ")+")"+a:"["+i.join(", ")+"]"+a}function F(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 Z(t){const{lower:e,upper:n,next:s}=function(t){let e="",n="",s=0;return"_"===t[0]&&([e,s]=F(t,0),"^"===t[s]&&([n,s]=F(t,s))),{lower:e,upper:n,next:s}}(t),r=t.slice(s),o=t=>t.replace(/\\,/g,"").replace(/\\!/g,"");let i,a="",l="",c=r.indexOf("\\mathrm{d}");if(c>=0){i=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(N.includes(t[n]))e++;else if(O.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?(i=r.slice(0,c),a=r[c+1],l=r.slice(c+2)):i=r;if(!a){const t=/frac\{d([A-Za-z])\}/.exec(i);t&&(a=t[1],i=i.replace(t[0],"frac{1}"))}if(!a&&/^[A-Za-z]$/.test(e)){a=[...o(i).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("+(o(i)||"1");return a&&(p+=","+a),(e||n)&&(p+=","+e+","+n),p+")"+l}function L(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(O.includes(n[t])?s--:N.includes(n[t])&&s++,0===s)return"("+n.slice(0,t)+","+e+")"+n.slice(t+1);return!1}function U(t){return"{"===t[0]||t.length<2?t:"{"+t[0]+"}{"+t[1]+"}"+t.slice(2)}const D=/[A-Za-z\u0370-\u03FF]/;function H(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 W(t,e){const n=/^\^(?:\{(\d+)\}|(\d))/.exec(t.slice(e));return n?[Number(n[1]??n[2]),e+n[0].length]:[1,e]}function G(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),o=/^d([A-Za-z\u0370-\u03FF])(?:\^\{?(\d+)\}?)?$/.exec(s);return r&&o?{n:Number(r[1]??1),of:r[2],by:o[1]}:null}function B(t,e){if(N.includes(t[e])){let n=0;for(let s=e;s<t.length;s++)if(N.includes(t[s]))n++;else if(O.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(N.includes(t[s]))n++;else{if(O.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 X=(t,e,n)=>`der(${t},${e}${n>1?","+n:""})`;const V="strtktk",Q="ABCDEFGHIJ",Y=t=>V+[...String(t)].map(t=>Q[t]).join("");function K(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}function J(t,e){if(!e||0===e.size)return t;const n=[...e].sort((t,e)=>e[0].length-t[0].length);return t.map(t=>{for(const[e,s]of n)t=t.split(e).join(s);return t})}const tt={factorial:"((n) => { if (!Number.isInteger(n) || n < 0) return NaN; let r = 1; for (let i = 2; i <= n; i++) r *= i; return r; })",perm:"((n, k) => { let r = 1; for (let i = n - k + 1; i <= n; i++) r *= i; return r; })",comb:"((n, k) => { let r = 1; for (let i = 1; i <= k; i++) r = r * (n - k + i) / i; return r; })",gcd:"((args)=>{let gcd = function(a,b) { return (!b)?a:gcd(b,a%b); }; return Math.abs(args.reduce(gcd));})"};for(const t of[tt])Object.setPrototypeOf(t,null);const et="([{",nt=")]}";function st(t,e){let n=0;for(let s=e;s<t.length;s++)if(et.includes(t[s]))n++;else if(nt.includes(t[s])&&0===--n)return s;return-1}function rt(t){if(!t.trim())return[];const e=[];let n=0,s=0;for(let r=0;r<t.length;r++)et.includes(t[r])?n++:nt.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 ot(t,e,n){const s=[...t.matchAll(e)];for(let e=s.length-1;e>=0;e--){const r=s[e],o=r.index+r[0].length-1,i=st(t,o);if(i<0)continue;const a=n(rt(t.slice(o+1,i)),r,t.slice(i+1));if(null==a)continue;const[l,c=0]=Array.isArray(a)?a:[a];if((t=t.slice(0,r.index)+l+t.slice(i+1+c)).length>1e5)throw new Error("The expression expands too much when read")}return t}const it=t=>new RegExp(`(?<![\\w.])(${t})\\s*\\(`,"g"),at=t=>`(${t})`,lt=t=>/^\[.*\]$/s.test(t.trim())?`{${t.trim().slice(1,-1)}}`:t;const ct={IF:t=>t.length>=2&&`((${t[0]}) ? (${t[1]}) : (${t[2]??"false"}))`,AND:t=>t.length&&`(${t.map(at).join(" & ")})`,OR:t=>t.length&&`(${t.map(at).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]})`};const pt={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"},ht="strtktk[A-J]+";function ut(t){for(let e=!0;e;){const n=t;e=(t=t.replace(new RegExp(`(${ht})\\s*\\|\\|\\s*(${ht})`,"g"),"$1 + $2"))!==n}const e=new RegExp(`^\\(typeof\\(([^()]*)\\)\\s+IN\\s+\\(${ht},\\s*${ht}\\)\\s+AND\\s+(.*)\\)$`,"s");for(let n=t.lastIndexOf("(typeof(");n>=0;n=n>0?t.lastIndexOf("(typeof(",n-1):-1){const s=st(t,n),r=s>0&&e.exec(t.slice(n,s+1));if(!r)continue;const[,o,i]=r,a={[`${o} = TRUNC(${o})`]:"ℤ",[`${o} = TRUNC(${o}) AND ${o} > 0`]:"ℕ",[`ABS(${o}) < ∞`]:"ℝ"}[i.trim()];a&&(t=`${t.slice(0,n)}((${o}) ∈ ${a})${t.slice(s+1)}`)}t=ot(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=ot(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()),o=[];let i="null";for(let t=1;t<r.length;t+=2){const e=r[t].toUpperCase();"WHEN"===e?o.push([r[t+1],r[t+3]]):"ELSE"===e&&(i=r[t+1])}const a=o.reduceRight((t,[e,n])=>`((${e}) ? (${n}) : ${t})`,at(i));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=>pt[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,o=st(t,r);if(o<0)break;t=`${t.slice(0,s.index)}${n} {${t.slice(r+1,o)}}${t.slice(o+1)}`,e.lastIndex=0}return t.replace(/<>/g," ≠ ")}const $t={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"},mt={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"};function ft(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)=>dt[e]??t),t=t.replace(/(?<![\w.])sympy\.(Reals|Integers|Naturals0?|Rationals|Complexes)\b/g,(t,e)=>dt[e]),t.replace(/(?<![\w.])sympy\.(\w+)/g,(t,e)=>yt[e]??gt[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)=>$t[e]?`Math.${$t[e]}`:mt[e]?mt[e]:{inf:"∞",nan:"NaN"}[e]??t)).replace(/(?<![\w.])(?:math|Math)\.(factorial|isfinite|isclose|prod|inf|nan|abs|trunc)\b/g,(t,e)=>({inf:"∞",nan:"NaN"}[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 gt={pi:"π",E:"e",oo:"∞",true:"true",false:"false",nan:"NaN",I:"i"},dt={Reals:"ℝ",Integers:"ℤ",Naturals:"ℕ",Naturals0:"ℕ",Rationals:"ℚ",Complexes:"ℂ"},yt={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",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:""},xt={open:"()",Lopen:"(]",Ropen:"[)"};const bt=t=>{const e=/^\((.*)\)$/s.exec(t.trim());return e?rt(e[1]):null},wt=t=>e=>2===e.length&&`${t[0]}${e[0]}, ${e[1]}${t[1]}`,_t=t=>bt(t)??[t],Mt={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]}) ∈ ${lt(t[1])})`,contains:t=>2===t.length&&`((${t[1]}) ∈ ${lt(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]}) - ((${t[0]}) \\mod 1))`,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(at).join(" & ")})`,sympy_or:t=>t.length&&`(${t.map(at).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(bt);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:wt("[]"),sympy_interval_open:wt("()"),sympy_interval_Lopen:wt("(]"),sympy_interval_Ropen:wt("[)"),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=_t(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&&_t(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&&_t(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:vt("sum"),prod:vt("prod")};function vt(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=rt(n[3]),[r,o]=1===s.length?["0",s[0]]:s,i=/\s*\+\s*1$/.test(o)?o.replace(/\s*\+\s*1$/,""):`(${o}) - 1`;return`(\\${t}_{${n[2]}=${r}}^{${i}} (${n[1]}))`}}for(const t of[ct,pt,$t,mt,gt,dt,yt,xt,Mt])Object.setPrototypeOf(t,null);const At=String.raw`(?:\([^()]*\)|\[[^\[\]]*\]|\{[^{}]*\}|(?<![\w.′^])[\w.′^]+)`,Et=t=>t.trim().split(/\s+/).join(String.raw`\s+`),Nt=t=>new RegExp(String.raw`(?<![\w.])${Et(t)}(?![\w.])`,"gi"),Ot=[["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","="]],It="[<>≤≥=≠≈]",St=[["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","∈ ℚ"]];const kt=M([[" 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 ","→"],["===","=...="]]),jt=M([["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"],["\\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"],["\\downarrow","\\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","*"],["\\times","*"],["×","*"],["·","*"],["÷","/"],["->","→"],["\\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}("],["log2(","log_{2}("],["log3(","log_{3}("],["log4(","log_{4}("],["log5(","log_{5}("],["log6(","log_{6}("],["log7(","log_{7}("],["log8(","log_{8}("],["log9(","log_{9}("],["log10(","log_{10}("],["log_10","log_{10}"],["\\log2(","log_{2}("],["\\log3(","log_{3}("],["\\log4(","log_{4}("],["\\log5(","log_{5}("],["\\log6(","log_{6}("],["\\log7(","log_{7}("],["\\log8(","log_{8}("],["\\log9(","log_{9}("],["\\log10(","log_{10}("],["\\log_10","log_{10}"],["log2{","log_{2}{"],["log3{","log_{3}{"],["log4{","log_{4}{"],["log5{","log_{5}{"],["log6{","log_{6}{"],["log7{","log_{7}{"],["log8{","log_{8}{"],["log9{","log_{9}{"],["log10{","log_{10}{"],["\\log2{","log_{2}{"],["\\log3{","log_{3}{"],["\\log4{","log_{4}{"],["\\log5{","log_{5}{"],["\\log6{","log_{6}{"],["\\log7{","log_{7}{"],["\\log8{","log_{8}{"],["\\log9{","log_{9}{"],["\\log10{","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|","|"],["\\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)"],["⊕"," \\xor "],["∞","∞"],["⋅","*"],["−","-"],["\\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],...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}()]),qt=[["code",function(t){return/^\s*=|[(.%^<_eE]|\|\||\bif\b|\b(?:True|False|None|TRUE|FALSE|NULL)\b/.test(t)?(/^\s*=(?!=)/.test(t)&&(t=function(t){const e="(?:[\\p{L}_][\\p{L}\\p{N}_.]*|\\d+(?:\\.\\d+)?|§\\d+§)";t=(t=(t=t.replace(/^\s*=/,"").replace(/(?<![\w.])_xlfn\./g,"")).replace(/&/g,"+")).replace(new RegExp(`(^|[(,=<>*/+^-]\\s*)-\\s*(${e})(?=\\s*\\^)`,"gu"),"$1(-$2)");for(let n=!0;n;){const s=t;n=(t=t.replace(new RegExp(`(^|[^\\p{L}\\p{N}_.)§])(${e}\\s*\\^\\s*${e})(?=\\s*\\^)`,"u"),"$1($2)"))!==s}return ot(t,/(?<![\w.])([A-Z][A-Z0-9]*(?:\.[A-Z]+)?)\s*\(/g,(t,e)=>ct[e[1]]?.(t)||null)}(t)),t=function(t){for(const[e,n]of Object.entries(tt))for(let s=t.lastIndexOf(n);s>=0;s=s>0?t.lastIndexOf(n,s-1):-1){const r=s+n.length,o="("===t[r]?st(t,r):-1;if(o<0)continue;let i=t.slice(r+1,o);"gcd"===e&&(i=i.trim().replace(/^\[|\]$/g,""));const a="factorial"===e?`((${i})!)`:`${e}(${i})`;t=t.slice(0,s)+a+t.slice(o+1)}for(let e=t.lastIndexOf(").toFixed(");e>=0;e=e>0?t.lastIndexOf(").toFixed(",e-1):-1){const n=e+10-1,s=st(t,n),r=t.lastIndexOf("Number(",e);s<0||r<0||st(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,o)=>`(\\${"sum"===e?"sum":"prod"}_{${n}=${s}}^{${r}} (${o}))`)}(t),t=function(t){t=ot(t,it("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=ot(t,it(Object.keys(Mt).join("|")),(t,e)=>Mt[e[1]](t)||null);for(let e=(t=ot(t,it("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=st(t,n);let r=e;if(nt.includes(t[e-1])){let n=0;for(r=e-1;r>=0;r--)if(nt.includes(t[r]))n++;else if(et.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)}) ∈ ${lt(t.slice(r,e))})${t.slice(s+1)}`)}return t}(t=ft(t=ut(t=(t=t.replace(/(?<![\w.])9e999\b/g,"∞")).replace(/(?<![\w.])(\d+(?:\.\d+)?)[eE]([+-]\d+)(?![\w.])/g,"($1*10^{$2})")))),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,o=-1,i=t.length;for(let e=s+2;e<t.length;e++)if(et.includes(t[e]))r++;else{if(nt.includes(t[e])&&--r<0){i=e;break}if(0===r&&","===t[e]){i=e;break}if(0===r&&/^then\b/.test(t.slice(e))&&/\W/.test(t[e-1])){o=-2;break}0===r&&o<0&&/^else\b/.test(t.slice(e))&&/\W/.test(t[e-1])&&(o=e)}if(o<0)continue;r=0;let a=0;for(let e=s-1;e>=0;e--)if(nt.includes(t[e]))r++;else{if(et.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,o).trim()}) ? (${l}) : (${t.slice(o+4,i).trim()}))`;t=t.slice(0,a)+c+t.slice(i),e=!1;break}if(e)return t}return t}(t),(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(!/[A-Za-z]{2}/.test(t))return t;let e=t;const n=(t,n,s,r="∈")=>{e=e.replace(new RegExp(String.raw`(?<![\w.])${Et(t)}\s+(${At})\s+(?:and|to)\s+(${At})(?:\s+(inclusive|exclusive))?(?![\w.])`,"gi"),(t,e,o,i)=>{const[a,l]="exclusive"===i?.toLowerCase()?["(",")"]:"inclusive"===i?.toLowerCase()?["[","]"]:[n,s];return` ${r} ${a}${e}, ${o}${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+(${At})\s+to\s+(${At})`,"gi"),(t,e,n,s,r)=>{const[o,i]={open:["(",")"],closed:["[","]"],"half-open":["[",")"]}[n.toLowerCase()];return` ${e?"∉":"∈"} ${o}${s}, ${r}${i} `});const s=String.raw`(${At})\s+`;e=e.replace(new RegExp(s+String.raw`is\s+(not\s+)?within\s+(${At})\s*(%|\s+percent)?\s+of\s+(${At})`,"gi"),(t,e,n,s,r,o)=>`(abs((${e}) - (${o})) ${n?">":"≤"} ${r?`(${s})/100 * ${/^\d+(\.\d+)?$/.test(o)?o:`abs(${o})`}`:`(${s})`})`),e=e.replace(new RegExp(s+String.raw`is\s+(?:a\s+)?multiple\s+of\s+(${At})`,"gi"),"(($1) mod ($2) = 0)"),e=e.replace(new RegExp(s+String.raw`is\s+(not\s+)?divisible\s+by\s+(${At})`,"gi"),(t,e,n,s)=>`((${e}) mod (${s}) ${n?"≠":"="} 0)`),e=e.replace(new RegExp(String.raw`(${At})\s+divides\s+(${At})`,"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 St)e=e.replace(Nt(t),` ${n} `);e=e.replace(Nt("is not in")," ∉ ").replace(Nt("is in")," ∈ ").replace(Nt("is an element of")," ∈ ");for(const[t,n]of Ot)e=e.replace(Nt(t),` ${n} `);e=e.replace(Nt("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`(${At})\s*(${It})\s*(${At})\s+(and|or)\s+(${It})`,"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+(${At})`,"gi"),"abs($1)"),e=e.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?square\s+root\s+of\s+(${At})`,"gi"),"sqrt($1)"),e=e.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?cube\s+root\s+of\s+(${At})`,"gi"),"root(3, $1)"),e=e.replace(new RegExp(String.raw`(${At})\s+to\s+the\s+power\s+of\s+(${At})`,"gi"),"($1)^($2)");const r={second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10};e=e.replace(new RegExp(String.raw`(${At})\s+to\s+the\s+(${Object.keys(r).join("|")}|(\d+|n)(?:st|nd|rd|th))(?:\s+power)?(?![\w.])`,"gi"),(t,e,n,s)=>`(${e})^(${r[n.toLowerCase()]??s})`),e=e.replace(new RegExp(String.raw`(${At})\s+to\s+the\s+(${At})(?![\w.])`,"gi"),"($1)^($2)");const o={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"};for(const[t,n]of Object.entries(o).sort((t,e)=>e[0].length-t[0].length))e=e.replace(new RegExp(String.raw`(?<![\w.])(?:the\s+)?${Et(t)}\s+of\s+(${At})`,"gi"),`${n}($1)`);e=e.replace(new RegExp(String.raw`(${At})\s+squared(?![\w.])`,"gi"),"($1)^2"),e=e.replace(new RegExp(String.raw`(${At})\s+cubed(?![\w.])`,"gi"),"($1)^3"),e=e.replace(new RegExp(String.raw`(?<![\w.])half\s+of\s+(${At})`,"gi"),"($1)/2"),e=e.replace(new RegExp(String.raw`(?<![\w.])twice\s+(${At})`,"gi"),"2*($1)"),e=e.replace(new RegExp(String.raw`(\d+(?:\.\d+)?)\s+percent(?![\w.])`,"gi"),"$1%");const i=t=>new RegExp(String.raw`(?<=[\w.′)\]}]\s+)${Et(t)}(?=\s+[\w.(\[{-])`,"gi");for(const[t,n]of[["divided by","/"],["over","/"],["multiplied by","*"],["times","*"],["plus","+"],["minus","-"],["modulo","mod"]])e=e.replace(i(t),` ${n} `);return e}],["words",kt],["spaced",function(t){t=R(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=k(t,n+2,"then");if(s<0)return t;const r=t.slice(n+2,s),o=k(t,s+4,"else"),i=j(t,o<0?s+4:o+4),a=t.slice(s+4,o<0?i:o),l=o<0?"unchanged":t.slice(o+4,i).trim();t=`${t.slice(0,n)}((${r.trim()}) ? (${a.trim()}) : (${l}))${t.slice(i)}`}return t}(t)).replace(/\(\s*\\?b?mod\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=q(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}let s=e+1;for("-"===t[s]&&s++;s<t.length&&".0123456789".includes(t[s]);)s++;s===e+2&&"-"===t[e+1]&&(s=e+1),s>e+1&&(t=t.slice(0,e+1)+"{"+t.slice(e+1,s)+"}"+t.slice(s))}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",jt],["compact",function(t){t=function(t){for(let e=0;e<t.length;e++){const n=e>0&&D.test(t[e-1]);let s,r=null,o=e;if(t.startsWith("frac{",e)){const n=H(t,e+4),s=n&&H(t,n[1]);r=s&&G(n[0],s[0]),r&&(o=s[1])}else if("d"===t[e]&&!n){let[n,s]=W(t,e+1),i="";if(D.test(t[s]??"")&&"/"===t[s+1]&&(i=t[s++]),"/"===t[s]&&"d"===t[s+1]&&D.test(t[s+2]??"")){const e=t[s+2],[,a]=W(t,s+3);r={n:n,of:i,by:e},o=a}}if(r){if(r.of)s=X(r.of,r.by,r.n);else{const[e,n]=B(t,o);if(!e)continue;s=X(e,r.by,r.n),o=n}t=t.slice(0,e)+s+t.slice(o),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)+X(t.slice(s,e+1),"x",r)+t.slice(e+1+r),e=s}return t}(t=(t=R(t)).replace(/(?<![A-Za-z])frac(\d)(\d)/g,"frac{$1}{$2}")));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=P(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"+T(t.slice(e+1)):"sqrt"===s(4)&&(t=t.slice(0,e-4)+"sqrt"+T(t.slice(e+1)));else if("⌊"===n||"⌈"===n)t=t.slice(0,e)+z(t.slice(e));else if("t"===n)"\\int"===r(3)&&(t=t.slice(0,e-3)+Z(t.slice(e+1)));else if("m"===n)"\\binom"===r(5)&&(t=t.slice(0,e-5)+"\\binom"+U(t.slice(e+1)));else if("d"===n&&"dd"===r(1)&&"("===t[e+2]){const n=L(t.slice(e+1));n&&(t=t.slice(0,e-1)+"der"+n)}}return t.replace(/\\log/g,"log")}],["tidy",t=>t.replace(/ {2,}/g," ").trim()]];function Rt(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 o=s+1,i="",a=!1;for(;o<t.length&&(a||t[o]!==r);)a=!a&&"\\"===t[o],i+=t[o++];const l=Y(e.size);e.set(l,r+i+r),n+=l,s=o+1}return{text:n,strings:e}}(function(t){let e="";for(let n=0;n<t.length;n++){const s=t[n];if('"'===s||"`"===s){const s=K(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=K(t,n);e+=t.slice(n,s+1),n=s}else e+=s}return e}(t));let r=n.replace(/\t/g," ");e.evaluate&&(r=function(t,e,n){let s=0;for(;;){const r=t.indexOf("{{",s);if(r<0)return t;const o=zt(t,r);if(o<0)return t;let i=t.slice(r+2,o).trim();for(const[t,n]of e)i=i.split(t).join(n);try{let a=n(i);if(/^["'`]/.test(a)){const t=Y(e.size);e.set(t,a),a=t}const l=t.slice(0,r).trimEnd(),c=t.slice(o+2).trimStart();/^[\d.]/.test(a)&&(/[\d.]$/.test(l)||/^[\d.]/.test(c))&&(a=`(${a})`),t=t.slice(0,r)+" "+a+" "+t.slice(o+2),s=0}catch{s=o+2}}}(r,s,e.evaluate));const o=[["strings",r]];for(const[t,e]of qt){if(r=e(r),r.length>1e5)throw new Error("The expression expands too much when read");o.push([t,r])}return{cleaned:r,stringMap:s,steps:o}}function zt(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 Tt={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[Tt])Object.setPrototypeOf(t,null);const Ct=Object.keys(c).filter(t=>100===c[t]&&/^[a-z]{2,}$/.test(t)),Pt=["frac"],Ft=[...Object.keys(Tt),"pi","tau","inf","infinity","exp"],Zt="\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+/),Lt=new Set([...Ft,...Zt,"true","false","null","undefined","unchanged","deg","mod","pmod","NaN","Infinity"]),Ut=/^[a-zA-ZͰ-Ͽ]$/,Dt=new Set(["f","g","h","u","v","F","G","H"]),Ht=t=>Ct.includes(t)||Pt.includes(t),Wt=[...Ct,...Pt,...Ft].sort((t,e)=>e.length-t.length),Gt=[...Ct,...Pt,"pi"].sort((t,e)=>e.length-t.length);function Bt(t,e=Wt){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 Xt(t){if(Ht(t))return!0;const e=Bt(t,Gt);return e.length>1&&Ht(e[e.length-1])&&!Lt.has(t)}function Vt(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=>Ut.test(t)))||1===t.length||Lt.has(t)||Ht(t))return[t];var s;if("Δ"===t[0]&&2===t.length)return[t];if("latex"===e)return Qt(Bt(t),n);if(t.length<=2)return[...t];const r=Qt(Bt(t,Gt),n),o=r.findIndex(t=>t.length>1);if(o<0)return[t];if("pi"===r[o]&&!r.some(t=>Ct.includes(t)))return 3===t.length?r:[t];const i=o;let a=0,l=0;for(const t of r.slice(o))a=1===t.length?a+1:0,l=Math.max(l,a);return i<=1&&l<=2?r:[t]}function Qt(t,e){const n=t[t.length-1];return e||!Ct.includes(n)?t:[...t.slice(0,-1),...n]}const Yt="§",Kt=/[A-Za-zͰ-Ͽ′]/,Jt=t=>/^[A-Za-zͰ-Ͽ][A-Za-zͰ-Ͽ′]*$/.test(t);function te(t,e="plain"){if("string"!=typeof t)throw new Error("Tokenizer input must be a string");const n=[];let s="";const o=t=>{s&&(Jt(s)?n.push(...function(t,e,n){if((t=>new RegExp(`^${V}[${Q}]+$`).test(t))(t))return[t];if(u.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 Dt.has(t)?[r+t]:[t];if(p(t))return[t];const n=Vt(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 Vt(t,{mode:n,followed:s})}(s,t,e)):n.push(s),s="")};for(let e=0;e<t.length;e++){const i=t[e];if(i===Yt){o(i);const s=t.indexOf(Yt,e+1),a=t.slice(e,s+1);n.push(u.includes(t[s+1])?r+a:a),e=s;continue}if(Jt(s)&&/[0-9]/.test(i)&&p(s+i)){const{op:r,end:o}=ee(t,e,s+i);n.push(r),s="",e=o;continue}if(Kt.test(i)&&"′"!==i&&m(s)&&(n.push(s),s=""),Kt.test(i)&&(""===s?"′"!==i:Jt(s)))s+=i;else if(/[0-9]/.test(i)&&Jt(s)&&!Xt(s))s+=i;else if(Jt(s)&&o(" "===i?t[e+1]:i),"(){}[]".includes(i))s&&n.push(...ne(s,i)),s="",n.push(i);else if("_"!==i&&" "!==i){if(p(s+i)){const{op:r,end:o}=ee(t,e,s+i);n.push(r),s="",e=o;continue}if(p(i)){o(i);const{op:s,end:r}=ee(t,e,i);n.push(s),e=r;continue}s+=i}else o(t[e+1]),"_"===i&&n.push("_")}if(o(void 0),n.some(t=>/^:/.test(t)))throw new Error("Unmatched ':'");return n}function ee(t,e,n){let s=e;for(;s+1<t.length&&p(n+t[s+1]);)n+=t[s+1],s++;return"!"===n&&"_"===t[s+1]&&s++,{op:n,end:s}}function ne(t,e){if(!u.includes(e))return[t];if("\\"===t[0]){const e=t.slice(1);return[p(e)?e:r+e]}return m(t)?[t,"*"]:p(t)||Ht(t)||m(t[0])?[t]:[r+t]}const se=70,re=100,oe="%mod",ie=t=>u.includes(t),ae=t=>$.includes(t),le=t=>o(t)||c[t]===re&&"_"!==t,ce=new Set(["\\comb","\\perm","comb","perm"]),pe={frac:"/","\\binom":"\\binom"},he={"\\comb":"comb","\\perm":"perm",deg:"°","π":"pi","∨":"|"};class ue{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(ae(t)?`Unmatched '${t}'`:`Unexpected '${t}'`);return this.out}parseExpression(t,e=!1){for(this.parseOperand();;){const n=this.peek();if(void 0===n||ae(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:c.mod,run:()=>this.modulo()};if(t===oe)return{lbp:se,run:()=>{this.next(),this.parseExpression(se),this.emit("mod")}};if("pmod"===t)return{lbp:c.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:re,run:()=>{this.next(),this.parseScript(),this.emit("_")}};if(ce.has(t))return{lbp:re,run:()=>{this.next(),this.parseExpression(re),this.emit(t)}};const n=c[t];if(void 0!==n&&!le(t)&&"\\not"!==t&&!(t in pe)){const e=h.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&&!le(t)?71:se,run:()=>{this.parseExpression(se),this.emit("*")}}}startsOperand(t){return void 0===t||ae(t)||"|"===t?"|"===t:t!==oe&&(!!(ie(t)||le(t)||t in pe)||!p(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:c["|"],run:()=>{this.next(),e&&t%2==0&&this.next(),this.parseExpression(c["|"]),this.emit("|")}}}modulo(){this.next(),this.parseExpression(se,!0),this.emit("mod")}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(ie(t))return this.bracket(t,"{"===t&&("∈"===e||"∉"===e));if("|"===t)return this.absolute();if("-"===t||"+"===t){return"^"===e&&(void 0===n||ae(n))||ie(e)&&ae(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(le(t))return this.functionCall(t);if(ae(t)||p(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||!m(e[0])&&"∞"!==e[0]?this.emit("neg"):this.out[t]="-"+e[0]}bracket(t,e=!1){if(ae(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();ae(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(ie(t))return this.parseOperand();if("-"===t||"+"===t)return this.parseOperand();if(le(t))return this.parseOperand();if(this.next(),void 0===t||ae(t)||p(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(c["+"],!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(c["+"],!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===i(t)?.arity&&!ie(this.peek()))return this.emit(t);this.argument(),this.emit(t),e&&this.emit(...e,"^")}argument(){const t=this.peek();if(ie(t))return this.next(),this.bracket(t);this.parseExpression(se,!0)}}function $e(t,e){t=function(t){const e=[];for(let n=0;n<t.length;n++){const s=t[n],o=t=>"string"==typeof t&&/^[a-zA-Z]$/.test(t);if(Dt.has(s)&&"^ { - 1 } ("===t.slice(n+1,n+7).join(" ")){e.push(r+s+"⁻¹"),n+=5;continue}const[i,a,l]=t.slice(n+1,n+4),c=o(a)?a!==s:m(a);o(s)&&"e"!==s&&"("===i&&c&&")"===l?e.push(r+s):e.push(s)}return e}(t);const n=[];for(const s of t)p(s)||ie(s)||ae(s)||"_"===s||o(s)||m(s)?n.push(s):n.push(...me(s,e));return n}function me(t,e){const n=t=>$e(te(t,e),e);let s=0;for(;s<t.length&&m(t.slice(0,s+1));)s++;if(0===s){if("%"===t[0])return[oe,...n(t.slice(1))];const s=t.indexOf("%");return s>0&&s<t.length-1?[...me(t.slice(0,s),e),oe,...n(t.slice(s+1))]:[t]}const r=t.slice(s);return"%"===r[0]?1===r.length?[t]:[t.slice(0,s),oe,...n(r.slice(1))]:[t.slice(0,s),...n(r)]}for(const t of[pe,he])Object.setPrototypeOf(t,null);const fe=new Set(["()","[]","{}","(]","[)"]),ge={pow:"^",sqrtpow:"root","\\binom":"comb","\\comb":"comb","\\perm":"perm",frac:"/","==":"=","!==":"≠="},de=new Set(["round","fixed","der"]),ye=t=>o(t)||100===c[t];function xe(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],a=(t,e)=>{if(t.list)throw new Error(`A list of values needs brackets around it (near '${e}')`);return t};if(e.forEach((l,c)=>{if("∅"===l)return void n.push({list:[]});if(","===l){const t=s(l),e=s(l);return void n.push({list:[...r(e),...r(t)]})}if(fe.has(l)){const t=r(s(l));if(!t.length&&!ye(e[c+1]))throw new Error("Empty brackets");return void n.push(d(l,t))}const p=ge[l]??l,h=i(p);if(!h){if("?"===l||"abs("===l)throw new Error(`Unmatched '${l[0]}'`);return void n.push(x(l))}let u;if(ye(l)&&fe.has(e[c-1])&&n[n.length-1]?.op===e[c-1])u=n.pop().args;else{let e=h.arity===t||de.has(p)?1:h.arity;if(n.length<e)throw new Error(`'${l}' needs ${e} operand${1===e?"":"s"}`);u=n.splice(n.length-e,e).map(t=>a(t,l))}n.push(function(e,n){switch(e){case"sqrt":if(2===n.length)return d("root",n);break;case"round":if(1===n.length)return d("round",[n[0],f(0)]);break;case"sum":case"prod":{const t=n[1];if("op"===t?.type&&"symbol"===t.args[0]?.type&&(3===n.length&&"="===t.op||2===n.length&&"∈"===t.op))return d("sum"===e?"\\sumidx":"\\prodidx",n);break}case"det":if(n.length>1&&n.every(t=>"op"===t.type&&"[]"===t.op))return d("det",[d("[]",n)]);break;case"fixed":if(1===n.length)return d("fixed",[n[0],f(2)]);break;case"der":if(1===n.length)return d("der",[n[0],g("x")]);if(3===n.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");let r=t;for(let t=0;t<s;t++)r=d("der",[r,e]);return r}(n);break;case"log":if("symbol"===n[0].type&&"e"===n[0].value)return d("ln",[n[1]]);break;case"lim":return d("lim",function(t){const e=t=>"op"===t.type&&"^"===t.op&&"symbol"===t.args[1].type?{"\\+":"r","\\-":"l"}[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],g(e(r))]}return 3===t.length&&e(r)?[n,s,r.args[0],g(e(r))]:t}(n));case"\\:if":if(2===n.length||3===n.length)return d("?:",[n[0],n[1],n[2]??g("unchanged")]);throw new Error("if() takes a condition, a value, and optionally an alternative")}return function(e,n){const{arity:s}=i(e);if(s===t){if(0===n.length&&!o(e))throw new Error(`'${e}' needs at least one argument`);return}if(n.length!==s){throw new Error(`'${e}' takes ${s} argument${1===s?"":"s"}, not ${n.length}`)}}(e,n),d(e,n)}(p,u))}),1!==n.length)throw new Error(n.length?"Some values are not connected by an operator":"Empty expression");return a(n[0],"end")}for(const t of[ge])Object.setPrototypeOf(t,null);const be=/\\(?:text|textrm|textit|mathrm|mathit|operatorname)\{\s*([A-Za-z][A-Za-z0-9 ]*[A-Za-z0-9])\s*\}/g;const we=t=>/^[a-z][a-z0-9]*$/.test(t)&&p(t);function _e(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=S(t.slice(e+13,n),"\\\\").map(t=>S(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=I(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 Me(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)`);const o=/^\s*=(?!=)/.test(e);o&&(e=e.replace(/("(?:[^"]|"")*")|\$(?=[A-Za-z]{0,3}\d|[A-Za-z]{1,3}\$?\d)/g,(t,e)=>e??""));const a=o?[...new Set(e.replace(/"(?:[^"]|"")*"/g,"").match(/(?<![\w.])[A-Za-z]{1,3}\d+(?::[A-Za-z]{1,3}\d+)?(?![\w.(])/g)??[])]:[],{text:l,protectedNames:c}=function(t,e=[],n=[]){const s=new Map,r=t=>{const e=`${Yt}${s.size}${Yt}`;return s.set(e,t),e};t=t.replace(be,(t,e)=>we(e.trim())?` ${e.trim()}`:r(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"),()=>r(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)=>r(e)+(s?" * (":n))}return{text:t,protectedNames:s}}(_e(e),n.names,[...n.values??[],...a]),p=(t=>/\\[A-Za-z]/.test(t)?"latex":"plain")(l),{cleaned:h,stringMap:u,steps:$}=((t,e={})=>{const n=void 0===e.blocks?null:e.blocks;return Rt(t,{evaluate:n?t=>n(t,e.scope):void 0})})(l,{blocks:n.blocks,scope:n.scope}),m=t=>J(J(t,u),c);s.mode=p,s.cleaned=m([h])[0],s.cleanSteps=$,s.tokens=te(h,p),s.rawPostfix=m(function(t,e="plain"){return new ue($e(t,e)).parseAll().map(t=>he[t]??t)}(s.tokens,p));const f=function(e){const n=[];return function e(s){"op"===s.type?(s.args.forEach(e),i(s.op)?.arity===t&&n.push(String(s.args.length)),n.push(s.op)):n.push(s.value)}(e),n}(xe(s.rawPostfix));s.postfix=f,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 o=b[e]??String(e),a=i(o);if(!a)return n.push({...x(o),id:r}),void s.push(1);let l=a.arity;if(l===t){const t=n.pop();if(s.pop(),l=t&&"number"===t.type?Number(t.value):NaN,!Number.isInteger(l)||l<0)throw new Error(`'${o}' takes a variable number of arguments, so it must follow a count`)}if(n.length<l)throw new Error(`'${o}' needs ${l} operand${1===l?"":"s"}`);const c=1+Math.max(0,...s.splice(s.length-l,l));if(c>1e3)throw new Error("Nested too deeply (more than 1000 levels)");s.push(c),n.push({...d(o,n.splice(n.length-l,l)),id:r})}),1!==n.length)throw new Error(`Postfix leaves ${n.length} values instead of 1`);return n[0]}(f)}catch(t){s.error=t instanceof RangeError?"Nested too deeply":t.message}return s}class ve extends Error{}const Ae=new Set(Object.getOwnPropertyNames(Math)),Ee=new Set([...Ae,"isInteger","isFinite","from","includes","reduce","toFixed"]),Ne={Math:Ae,Number:new Set(["isInteger","isFinite"]),Array:new Set(["from"])},Oe=new Set(["Math","Number","Infinity","NaN","true","false","null"]),Ie=new Set(["let","for","if","return"]),Se=Object.values(tt).sort((t,e)=>e.length-t.length),ke=["===","!==","**=","...","=>","==","!=","<=",">=","&&","||","??","**","++","--","+=","-=","*=","/=","%=","(",")","[","]","{","}",",",";","?",":",".","+","-","*","/","%","!","=","<",">","&","|","^","~"];for(const t of[Ne])Object.setPrototypeOf(t,null);const je={name:"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}`,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=>`${tt.factorial}(${t})`,perm:(t,e)=>`${tt.perm}(${t}, ${e})`,comb:(t,e)=>`${tt.comb}(${t}, ${e})`,gcd:t=>`${tt.gcd}([${t}])`,round:(t,e)=>"0"===e?`Math.round(${t})`:`Math.round(${t} * Math.pow(10, ${e})) / Math.pow(10, ${e})`,fixed:(t,e)=>`Number(${t}).toFixed(${e})`,derivative:(t,e)=>`derivative(${t}, ${e})`,matrix:t=>`[${t.map(t=>`[${t.join(", ")}]`).join(", ")}]`,det:t=>`det(${t})`,integral:t=>`integrate(${t.join(", ")})`,limit:t=>`limit(${t.join(", ")})`,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;})()`},qe={name:"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}`,close:(t,e)=>`math.isclose(${t}, ${e})`,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)=>`round(${t}, ${e})`,fixed:(t,e,n)=>null===n?`format(${t}, '.' + str(${e}) + 'f')`:`format(${t}, '.${n}f')`,derivative:(t,e)=>`sympy.diff(${t}, ${e})`,matrix:t=>`[${t.map(t=>`[${t.join(", ")}]`).join(", ")}]`,det:t=>`numpy.linalg.det(${t})`,integral:(t,e,n,s)=>s?`scipy.integrate.quad(lambda ${n}: ${e}, ${s.join(", ")})[0]`:`sympy.integrate(${e}, sympy.Symbol(${JSON.stringify(n)}))`,limit:t=>`sympy.limit(${t.join(", ")})`,indexed:(t,e,n,s,r,o)=>"sum"===t?`sum(${r} for ${e} in range(${n}, ${o} + 1))`:`math.prod(${r} for ${e} in range(${n}, ${o} + 1))`},Re={asin:"arcsin",acos:"arccos",atan:"arctan",asinh:"arcsinh",acosh:"arccosh",atanh:"arctanh",atan2:"arctan2",pow:"power"},ze=(t,e)=>e.reduce((e,n)=>`${t}(${e}, ${n})`),Te={"<":"<",">":">","≤":"<=","≥":">=","=":"==","===":"==","≠":"!=","≠=":"!="},Ce=([,t],e,n)=>{const[s,r]=e.args,o=n=>`${n} ${Te[e.op]} ${t}`;return"op"===s.type&&Te[s.op]?`np.logical_and(${n(s)}, ${o(n(s.args[1]))})`:o(n(s))},Pe={...qe,name:"numpy",pi:"np.pi",e:"np.e",tau:"(2 * np.pi)",inf:"np.inf",degree:"(np.pi/180)",math:t=>`np.${Re[t]??t}`,list:{...qe.list,"{}":["[","]"]},abs:"np.abs",random:"np.random.random()",matrix:t=>`np.array(${qe.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)=>`np.round(${t}, ${e})`,fixed:(t,e,n)=>null===n?`np.char.mod('%.' + str(${e}) + 'f', ${t})`:`np.char.mod('%.${n}f', ${t})`,ops:{...Object.fromEntries(Object.keys(Te).map(t=>[t,Ce])),max:t=>1===t.length?`np.nanmax(${t[0]})`:ze("np.maximum",t),min:t=>1===t.length?`np.nanmin(${t[0]})`:ze("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=>ze("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}))`}},Fe=t=>`sympy.${t}`,Ze=t=>"number"===t.type&&/^-?\d+$/.test(t.value)||"op"===t.type&&"neg"===t.op&&Ze(t.args[0]),Le={"ℝ":"sympy.S.Reals","ℤ":"sympy.S.Integers","ℕ":"sympy.S.Naturals","ℚ":"sympy.S.Rationals","ℂ":"sympy.S.Complexes"},Ue={"[]":"sympy.Interval","()":"sympy.Interval.open","(]":"sympy.Interval.Lopen","[)":"sympy.Interval.Ropen"};function De(t,e){return"symbol"===t.type&&Le[t.value]?Le[t.value]:"op"===t.type&&Ue[t.op]&&2===t.args.length?`${Ue[t.op]}(${t.args.map(e).join(", ")})`:"op"===t.type&&i(t.op)?.group?`sympy.FiniteSet(${t.args.map(e).join(", ")})`:e(t)}function He(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 We={...qe,name:"sympy",noStrings:!0,pi:Fe("pi"),e:Fe("E"),tau:"(2*sympy.pi)",inf:Fe("oo"),degree:"(sympy.pi/180)",true:Fe("true"),false:Fe("false"),null:"None",math:t=>Fe({log:"log",asin:"asin",acos:"acos",atan:"atan",asinh:"asinh",acosh:"acosh",atanh:"atanh",atan2:"atan2",expm1:"expm1",ceil:"ceiling"}[t]??t),abs:Fe("Abs"),random:"random.random()",matrix:t=>`sympy.Matrix(${qe.matrix(t)})`,det:t=>`${t}.det()`,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 o=(t,e)=>e?o(e,t%e):t,i=o(s,r);return[s,r]=[s/i,r/i],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)=>Ze(e.args[0])&&Ze(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=>`sympy.root(${t[1]}, ${t[0]})`,round:(t,e)=>"number"===e.args[1].type&&"0"===e.args[1].value?`sympy.floor(${t[0]} + sympy.Rational(1, 2))`:`sympy.floor((${t[0]}) * 10**(${t[1]}) + sympy.Rational(1, 2)) / 10**(${t[1]})`,"&":(t,e,n)=>He("&",e,n,"sympy.And"),"|":(t,e,n)=>He("|",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]}, ${De(e.args[1],n)})`,"∉":(t,e,n)=>`sympy.Not(sympy.Contains(${t[0]}, ${De(e.args[1],n)}))`,"∪":(t,e,n)=>`sympy.Union(${e.args.map(t=>De(t,n)).join(", ")})`,"∩":(t,e,n)=>`sympy.Intersection(${e.args.map(t=>De(t,n)).join(", ")})`,"{}":t=>`sympy.FiniteSet(${t.join(", ")})`,der:t=>`sympy.diff(${t.join(", ")})`,int:(t,e,n)=>{const[s,r,o,i]=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):_(s)||"x";let c=[];return 4===e.args.length?c=[o,i]:3===e.args.length?c=a?[o]:[r,o]: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,o="op"===r?.type&&"→"===r.op,[i,a]=o?r.args.map(n):2===e.args.length?[_(s)||"x",t[1]]:[t[1],t[2]],l="symbol"===e.args[3]?.type?{r:', "+"',l:', "-"'}[e.args[3].value]??"":"";return`sympy.limit(${t[0]}, ${i}, ${a}${l})`},"\\sumidx":(t,e,n)=>Ge("summation",e,n),"\\prodidx":(t,e,n)=>Ge("product",e,n)}};function Ge(t,e,n){const[s,r,o]=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(o)}))`}const Be={javascript:je,python:qe,numpy:Pe,sympy:We},Xe={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"},Ve={csc:"sin",sec:"cos",cot:"tan"},Qe={"ℝ":{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[je,qe,Re,Te,Pe,Le,Ue,We,Be,Xe,Ve,Qe])Object.setPrototypeOf(t,null);const Ye=t=>e=>`<mover accent="true">${e}<mo>${t}</mo></mover>`,Ke={boxed:t=>`<menclose notation="box">${t}</menclose>`,cancel:t=>`<menclose notation="updiagonalstrike">${t}</menclose>`,overline:Ye("¯"),bar:Ye("¯"),underline:t=>`<munder accentunder="true">${t}<mo>_</mo></munder>`,vec:Ye("→"),hat:Ye("^"),widehat:Ye("^"),tilde:Ye("~"),dot:Ye("˙"),ddot:Ye("¨")};Object.setPrototypeOf(Ke,null);const Je={"=":"=","===":"=","≠":"≠","≠=":"≠","<":"&lt;",">":"&gt;","≤":"≤","≥":"≥","∈":"∈","∉":"∉","→":"→","±":"±",mod:"mod","≈":"≈","∪":"∪","∩":"∩","≡":"≡","&":"∧","|":"∨","\\xor":"⊕","\\nand":"↑","\\nor":"↓"},tn={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"},en={"()":["(",")"],"[]":["[","]"],"{}":["{","}"],"(]":["(","]"],"[)":["[",")"]};for(const t of[Je,tn,en])Object.setPrototypeOf(t,null);const nn={pi:"PI()","π":"PI()",e:"EXP(1)","∞":"'Infinity'",true:"TRUE",false:"FALSE",null:"NULL"},sn={...nn,"∞":"9e999","-∞":"-9e999",tau:"(2 * PI())","τ":"(2 * PI())"},rn={sqrt:"SQRT",abs:"ABS",floor:"FLOOR",ceil:"CEIL",ln:"LN",expm1:"EXPM1",sin:"SIN",cos:"COS",tan:"TAN",csc:"CSC",sec:"SEC",cot:"COT",sinh:"SINH",cosh:"COSH",tanh:"TANH",arcsin:"ASIN",arccos:"ACOS",arctan:"ATAN",arcsinh:"ASINH",arccosh:"ACOSH",arctanh:"ATANH",atan2:"ATAN2",round:"ROUND",perm:"PERM",comb:"COMB",max:"GREATEST",min:"LEAST",gcd:"GCD",random:"RANDOM",der:"DERIVATIVE",int:"INTEGRATE",lim:"LIMIT","\\sumidx":"SUMMATION","\\prodidx":"PRODUCT","!":"FACTORIAL"},on={"+":"+","-":"-","*":"*","/":"/","=":"=","===":"=","≠":"<>","≠=":"<>","<":"<",">":">","≤":"<=","≥":">="},an={"()":["(",")"],"{}":["(",")"],"[]":["ARRAY[","]"],"(]":["(",")"],"[)":["(",")"]},ln={max:"MAX",min:"MIN"},cn={csc:"SIN",sec:"COS",cot:"TAN"},pn={"ℝ":t=>`(ABS(${t}) < 'Infinity')`,"ℤ":t=>`(${t} = TRUNC(${t}))`,"ℕ":t=>`(${t} = TRUNC(${t}) AND ${t} > 0)`};for(const t of[nn,sn,rn,on,an,ln,cn,pn])Object.setPrototypeOf(t,null);const hn={pi:"PI()","π":"PI()",e:"EXP(1)",tau:"(2*PI())","τ":"(2*PI())","°":"(PI()/180)",true:"TRUE",false:"FALSE"},un={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"},$n={csc:"SIN",sec:"COS",cot:"TAN"},mn={"=":"=","===":"=","≡":"=","≠":"<>","≠=":"<>","<":"<",">":">","≤":"<=","≥":">="},fn={sum:"SUM",prod:"PRODUCT",mean:"AVERAGE",max:"MAX",min:"MIN","\\:median":"MEDIAN","\\:stdev":"STDEVP","\\:count":"COUNT"},gn={der:"a derivative",int:"an integral",lim:"a limit","\\sumidx":"a sum to n","\\prodidx":"a product to n",pm:"±","±":"±","∪":"∪","∩":"∩","→":"→"};for(const t of[hn,un,$n,mn,fn,gn])Object.setPrototypeOf(t,null);const dn="3.141592653589793",yn={pi:dn,"π":dn,e:"2.718281828459045",tau:"6.283185307179586","τ":"6.283185307179586","∞":"MZ_INFINITY","-∞":"(-MZ_INFINITY)",true:"true",false:"false"},xn={"α":"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"},bn={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"},wn={sinh:"sinh",cosh:"cosh",tanh:"tanh",arcsinh:"asinh",arccosh:"acosh",arctanh:"atanh",round:"round"},_n={csc:"sin",sec:"cos",cot:"tan"},Mn={"=":"==","===":"==","≠":"!=","≠=":"!=","<":"<",">":">","≤":"<=","≥":">="},vn={"ℝ":t=>`(abs(${t}) < MZ_INFINITY)`,"ℤ":t=>`(fract(${t}) == 0.0)`,"ℕ":t=>`(fract(${t}) == 0.0 && ${t} > 0.0)`},An=["px","py","rgb","gray","unchanged","selected"],En=["zoom","shift","rotate","crop","tile","flipx","flipy"],Nn=["srgb","linear","hsv","hsl","lab","oklab","ycbcr"].filter(t=>"srgb"!==t).flatMap(t=>[`to${t}`,`from${t}`]),On=["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",...En,"fract","clamp","mix","smoothstep","step","distance","length","dot","normalize","cross","sign","exp2","log2","inversesqrt","radians","degrees",...Nn],In=["red","green","blue","alpha","luma"];function Sn(t,e,{whole:n=!1}={}){const s=kn(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 kn(t,e){if("op"!==t.type)return t;const n=t.args.map(t=>kn(t,e)),s=t.op.startsWith(r)?t.op.slice(2):null,o=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&&In.includes(s)&&1===n.length&&o)return{...t,args:[{...n[0],value:`mz_px_${o}`}]};if(s&&In.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&&En.includes(s)){const t={type:"op",op:`${r}mz_${s}`,args:o?n.slice(1):n};return{type:"op",op:`${r}mz_at_${o??"image"}`,args:[t]}}return("width"===s||"height"===s)&&n.length<=1?o&&"source"!==o?{type:"op",op:`${r}mz_${s}_${o}`,args:[]}:{type:"symbol",value:"width"===s?"w":"h"}:{...t,args:n}}const jn={square:8,line:24};for(const t of[yn,xn,bn,wn,_n,Mn,vn,jn])Object.setPrototypeOf(t,null);const qn={data:new Float32Array([1,1,1,1]),width:1,height:1},Rn={data:new Float32Array([0,0,0,0]),width:1,height:1},zn={cover:0,fit:1,stretch:2,tile:3};function Tn(t){return zn[t??"cover"]??0}function Cn(t,e){return t-e*Math.floor(t/e)}const Pn=(t,e)=>t<0?0:t>e?e:t;function Fn(t,e,n,s,r,o){const i=Math.floor(s),a=Math.floor(r),l=s-i,c=r-a,p=Pn(i,e-1),h=Pn(i+1,e-1),u=Pn(a,n-1),$=Pn(a+1,n-1),m=4*(u*e+p),f=4*(u*e+h),g=4*($*e+p),d=4*($*e+h);for(let e=0;e<4;e++){const n=t[m+e]+(t[f+e]-t[m+e])*l,s=t[g+e]+(t[d+e]-t[g+e])*l;o[e]=n+(s-n)*c}return o}function Zn(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 Ln(t,e,n,s,r,o,i,a,l=0,c=s){const p=new Float32Array(n*s*3),h=o.length,u=Int32Array.from(o),$=Float64Array.from(i??o.map(()=>1)),m="x"===r?n:s,f=new Int32Array(h);for(let s=l;s<c;s++)for(let o=0;o<n;o++){const i="x"===r?o:s;for(let t=0;t<h;t++){let a=i+u[t];a=a<0?0:a>=m?m-1:a,f[t]=("x"===r?s*n+a:a*n+o)*e}let l=0,c=0,g=0;for(let e=0;e<h;e++){const n=f[e],s=$[e];l+=t[n]*s,c+=t[n+1]*s,g+=t[n+2]*s}const d=3*(s*n+o);p[d]=l/a,p[d+1]=c/a,p[d+2]=g/a}return p}function Un(t,e,n,s,r,o,i,a=0,l=s){const c=new Float32Array(n*s*3),p="x"===r?n:s,h="x"===r?s:n,u=i-o+1,$=(t,e)=>"x"===r?t*n+e:e*n+t,m=t=>t<0?0:t>=p?p-1:t,[f,g]="x"===r?[a,l]:[0,h],[d,y]="x"===r?[0,p]:[a,l];for(let n=f;n<g;n++){let s=0,r=0,a=0;for(let l=d+o;l<=d+i;l++){const o=$(n,m(l))*e;s+=t[o],r+=t[o+1],a+=t[o+2]}for(let l=d;l<y;l++){const p=3*$(n,l);c[p]=s/u,c[p+1]=r/u,c[p+2]=a/u;const h=$(n,m(l+o))*e,f=$(n,m(l+i+1))*e;s+=t[f]-t[h],r+=t[f+1]-t[h+1],a+=t[f+2]-t[h+2]}}return c}function Dn(t,e,n,s,r,o,i,a,l=0,c=s){const p=new Float32Array(n*s*3),h="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 u=i,$=i,m=i;for(let i=0;i<o.length;i++){let p=c+o[i];p=p<0?0:p>=h?h-1:p;const f=("x"===r?s*n+p:p*n+l)*e;a?(t[f]>u&&(u=t[f]),t[f+1]>$&&($=t[f+1]),t[f+2]>m&&(m=t[f+2])):(t[f]<u&&(u=t[f]),t[f+1]<$&&($=t[f+1]),t[f+2]<m&&(m=t[f+2]))}const f=3*(s*n+l);p[f]=u,p[f+1]=$,p[f+2]=m}return p}const Hn=(t,e,n)=>t+e*n,Wn=(t,e)=>e>t?e:t,Gn=(t,e)=>e<t?e:t;function Bn(t,e,n,s=0,r=n){const o=new Float32Array(e*n*3);for(let n=s*e;n<r*e;n++)o[3*n]=t[4*n],o[3*n+1]=t[4*n+1],o[3*n+2]=t[4*n+2];return o}const Xn=(t,e,n,s)=>[Math.max(0,t-n),Math.min(s,e+n)];function Vn(t,e,n,s,r,o,i,a){const l=Zn(o,a,t=>Math.abs(t)<=o);if(!l.length)return Bn(t,e,n,s,r);const c=l[0],p=l[l.length-1];if(1===i.length)return Un(t,4,e,n,i[0],c,p,s,r);const[h,u]=Xn(s,r,p,n);return Un(Un(t,4,e,n,"x",c,p,h,u),3,e,n,"y",c,p,s,r)}function Qn(t,e,n,s,r,o,i,a){if(!(o>0))return Bn(t,e,n,s,r);const l=3*o,c=Zn(l,a,t=>Math.abs(t)<=l),p=c.map(t=>Math.exp(-t*t/(2*o*o))),h=p.reduce((t,e)=>t+e,0);if(1===i.length)return Ln(t,4,e,n,i[0],c,p,h,s,r);const[u,$]=Xn(s,r,c[c.length-1],n);return Ln(Ln(t,4,e,n,"x",c,p,h,u,$),3,e,n,"y",c,p,h,s,r)}function Yn(t,e,n,s,r,o,i,a){const l=Zn(o,jn.square,t=>Math.abs(t)<=o);if(!l.length)return new Float32Array(e*n*3).fill(i);const[c,p]=Xn(s,r,l[l.length-1],n);return Dn(Dn(t,4,e,n,"x",l,i,a,c,p),3,e,n,"y",l,i,a,s,r)}function Kn(t,e,n,s,r,o){const i=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,o)=>i[Pn(t+o,n-1)*e+Pn(s+r,e-1)];a[t*e+s]=o(r)}return a}const Jn=t=>t(1,-1)+2*t(1,0)+t(1,1)-(t(-1,-1)+2*t(-1,0)+t(-1,1)),ts=t=>t(-1,1)+2*t(0,1)+t(1,1)-(t(-1,-1)+2*t(0,-1)+t(1,-1)),es=t=>4*t(0,0)-t(-1,0)-t(1,0)-t(0,-1)-t(0,1),ns=t=>.5+t(-1,-1)-t(1,1),ss=t=>Math.hypot(Jn(t),ts(t));function rs(t,e,n,s,r,o,i,a,l,c,p){for(let h=0;h<3;h++){let u=a,$=0;for(const a of o)for(const c of o){const o=i?i(a,c):1;u=l(u,t[4*(Pn(r+c,n-1)*e+Pn(s+a,e-1))+h],o),$+=o}c[h]=p?p(u,$):u}return c}function os(t,e,n,s,r,o,i,a,l){for(let c=0;c<3;c++){let p=0,h=0;for(const l of i){const i=a?a(l):1,u="x"===o?Pn(s+l,e-1):s;p+=t[4*(("y"===o?Pn(r+l,n-1):r)*e+u)+c]*i,h+=i}l[c]=p/h}return l}const is=(t,e,n,s,r)=>{const o=4*(s*e+n);return r[0]=t[o],r[1]=t[o+1],r[2]=t[o+2],r};const as=t=>t<.04045?t/12.92:Math.pow((t+.055)/1.055,2.4),ls=t=>(t=Math.max(t,0))<.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,cs=(t,e,n,s,r)=>{const o=s===t?(e-n)/r:s===e?2+(n-t)/r:4+(t-e)/r;return o/6-Math.floor(o/6)},ps=(t,e)=>{const n=Math.abs(6*(t+e-Math.floor(t+e))-3);return Math.min(Math.max(n-1,0),1)};const hs=t=>t<.008856?7.787*t+16/116:Math.cbrt(t),us=t=>t<.206893?(t-16/116)/7.787:t*t*t;var $s=Object.freeze({__proto__:null,BLANK:qn,CLEAR:Rn,at:function(t,e,n){return Number(t[e][n])},at_blur:function(t,e,n,s,r,o,i){return rs(t,e,n,s,r,Zn(o,jn.square,t=>Math.abs(t)<=o),null,0,Hn,i,(t,e)=>t/e)},at_blurx:function(t,e,n,s,r,o,i){return os(t,e,n,s,r,"x",Zn(o,jn.line,t=>Math.abs(t)<=o),null,i)},at_blury:function(t,e,n,s,r,o,i){return os(t,e,n,s,r,"y",Zn(o,jn.line,t=>Math.abs(t)<=o),null,i)},at_dilate:function(t,e,n,s,r,o,i){return rs(t,e,n,s,r,Zn(o,jn.square,t=>Math.abs(t)<=o),null,0,Wn,i)},at_erode:function(t,e,n,s,r,o,i){return rs(t,e,n,s,r,Zn(o,jn.square,t=>Math.abs(t)<=o),null,1,Gn,i)},at_gaussian:function(t,e,n,s,r,o,i){if(!(o>0))return is(t,e,s,r,i);const a=3*o;return rs(t,e,n,s,r,Zn(a,jn.square,t=>Math.abs(t)<=a),(t,e)=>Math.exp(-(t*t+e*e)/(2*o*o)),0,Hn,i,(t,e)=>t/e)},at_gaussianx:function(t,e,n,s,r,o,i){if(!(o>0))return is(t,e,s,r,i);const a=3*o;return os(t,e,n,s,r,"x",Zn(a,jn.line,t=>Math.abs(t)<=a),t=>Math.exp(-t*t/(2*o*o)),i)},at_gaussiany:function(t,e,n,s,r,o,i){if(!(o>0))return is(t,e,s,r,i);const a=3*o;return os(t,e,n,s,r,"y",Zn(a,jn.line,t=>Math.abs(t)<=a),t=>Math.exp(-t*t/(2*o*o)),i)},at_sharpen:function(t,e,n,s,r,o,i){const a=(t,s)=>4*(Pn(s,n-1)*e+Pn(t,e-1)),l=a(s,r),c=a(s-1,r),p=a(s+1,r),h=a(s,r-1),u=a(s,r+1);for(let e=0;e<3;e++)i[e]=t[l+e]+o*(4*t[l+e]-t[c+e]-t[p+e]-t[h+e]-t[u+e]);return i},col_fromhsl:function(t,e,n,s){const r=(1-Math.abs(2*n-1))*e;return s[0]=n-.5*r+r*ps(t,0),s[1]=n-.5*r+r*ps(t,2/3),s[2]=n-.5*r+r*ps(t,1/3),s},col_fromhsv:function(t,e,n,s){return s[0]=n*(1+(ps(t,0)-1)*e),s[1]=n*(1+(ps(t,2/3)-1)*e),s[2]=n*(1+(ps(t,1/3)-1)*e),s},col_fromlab:function(t,e,n,s){const r=(100*t+16)/116,o=r-256*(n-.5)/200,i=.95047*us(r+256*(e-.5)/500),a=us(r),l=1.08883*us(o),c=Math.min(Math.max(3.2404542*i-1.5371385*a-.4985314*l,0),1),p=Math.min(Math.max(-.969266*i+1.8760108*a+.041556*l,0),1),h=Math.min(Math.max(.0556434*i-.2040259*a+1.0572252*l,0),1);return s[0]=ls(c),s[1]=ls(p),s[2]=ls(h),s},col_fromlinear:function(t,e,n,s){return s[0]=ls(t),s[1]=ls(e),s[2]=ls(n),s},col_fromoklab:function(t,e,n,s){let r=t+.3963377774*(e-=.5)+.2158037573*(n-=.5),o=t-.1055613458*e-.0638541728*n,i=t-.0894841775*e-1.291485548*n;r*=r*r,o*=o*o,i*=i*i;const a=Math.min(Math.max(4.0767416621*r-3.3077115913*o+.2309699292*i,0),1),l=Math.min(Math.max(-1.2684380046*r+2.6097574011*o-.3413193965*i,0),1),c=Math.min(Math.max(-.0041960863*r-.7034186147*o+1.707614701*i,0),1);return s[0]=ls(a),s[1]=ls(l),s[2]=ls(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),o=Math.min(t,e,n),i=r-o,a=.5*(r+o);return s[0]=i>0?cs(t,e,n,r,i):0,s[1]=i>0?i/(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),o=r-Math.min(t,e,n);return s[0]=o>0?cs(t,e,n,r,o):0,s[1]=r>0?o/r:0,s[2]=r,s},col_tolab:function(t,e,n,s){const r=as(t),o=as(e),i=as(n),a=hs((.4124564*r+.3575761*o+.1804375*i)/.95047),l=hs(.2126729*r+.7151522*o+.072175*i),c=hs((.0193339*r+.119192*o+.9503041*i)/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]=as(t),s[1]=as(e),s[2]=as(n),s},col_tooklab:function(t,e,n,s){const r=as(t),o=as(e),i=as(n),a=Math.cbrt(.4122214708*r+.5363325363*o+.0514459929*i),l=Math.cbrt(.2119034982*r+.6806995451*o+.1073969566*i),c=Math.cbrt(.0883024619*r+.2817188376*o+.6299787005*i);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,o,i,a,l,c,p,h,u,$,m){const f=(t,o)=>4*(Pn(r+o,n-1)*e+Pn(s+t,e-1)),g=[[o,-1,-1],[i,0,-1],[a,1,-1],[l,-1,0],[c,0,0],[p,1,0],[h,-1,1],[u,0,1],[$,1,1]];for(let e=0;e<3;e++){let n=0;for(const[s,r,o]of g)n+=s*t[f(r,o)+e];m[e]=n}return m},factorial:function(t){let e=1;for(let n=2;n<=170&&!(n>t);n++)e*=n;return e},fmod:Cn,gcd:function(t,e){t=Math.abs(t),e=Math.abs(e);for(let n=0;n<64&&0!==e;n++){const n=Cn(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,o,i,a,l,c,p,h,u){let $,m;0===c?$=m=Math.max(s/e,r/n):1===c?$=m=Math.min(s/e,r/n):2===c?($=s/e,m=r/n):$=m=1,$*=o,m*=o;const f=p+.5-i*s,g=h+.5-a*r,d=Math.cos(l),y=Math.sin(l);let x=(d*f+y*g)/$+.5*e,b=(d*g-y*f)/m+.5*n;if(3===c)x=Cn(x,e),b=Cn(b,n);else if(x<0||b<0||x>e||b>n)return u[0]=u[1]=u[2]=u[3]=0,u;return Fn(t,e,n,x-.5,b-.5,u)},placeCode:Tn,plane_blur:function(t,e,n,s,r,o){return Vn(t,e,n,s,r,o,["x","y"],jn.square)},plane_blurx:function(t,e,n,s,r,o){return Vn(t,e,n,s,r,o,["x"],jn.line)},plane_blury:function(t,e,n,s,r,o){return Vn(t,e,n,s,r,o,["y"],jn.line)},plane_dilate:function(t,e,n,s,r,o){return Yn(t,e,n,s,r,o,0,!0)},plane_emboss:function(t,e,n,s,r){return Kn(t,e,n,s,r,ns)},plane_erode:function(t,e,n,s,r,o){return Yn(t,e,n,s,r,o,1,!1)},plane_gaussian:function(t,e,n,s,r,o){return Qn(t,e,n,s,r,o,["x","y"],jn.square)},plane_gaussianx:function(t,e,n,s,r,o){return Qn(t,e,n,s,r,o,["x"],jn.line)},plane_gaussiany:function(t,e,n,s,r,o){return Qn(t,e,n,s,r,o,["y"],jn.line)},plane_laplacian:function(t,e,n,s,r){return Kn(t,e,n,s,r,es)},plane_sharpen:function(t,e,n,s,r,o){const i=new Float32Array(e*n*3);for(let a=s;a<r;a++)for(let s=0;s<e;s++){const r=(t,s)=>4*(Pn(s,n-1)*e+Pn(t,e-1)),l=r(s,a),c=r(s-1,a),p=r(s+1,a),h=r(s,a-1),u=r(s,a+1);for(let n=0;n<3;n++)i[3*(a*e+s)+n]=t[l+n]+o*(4*t[l+n]-t[c+n]-t[p+n]-t[h+n]-t[u+n])}return i},plane_sobel:function(t,e,n,s,r){return Kn(t,e,n,s,r,ss)},plane_sobelx:function(t,e,n,s,r){return Kn(t,e,n,s,r,Jn)},plane_sobely:function(t,e,n,s,r){return Kn(t,e,n,s,r,ts)},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)},sample:Fn,sampleOrZero:function(t,e,n,s,r,o){const i=s+.5,a=r+.5;return i<0||a<0||i>e||a>n?(o[0]=o[1]=o[2]=o[3]=0,o):Fn(t,e,n,s,r,o)},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 ms="\\:",fs=Object.keys($s).filter(t=>"function"==typeof $s[t]),gs={r:"$r",g:"$g",b:"$b",a:"$a",x:"$x",y:"$y",px:"$px",py:"$py",w:"$w",h:"$h",t:"$t",gray:"$gray"},ds={pi:"Math.PI","π":"Math.PI",e:"Math.E",tau:"(2 * Math.PI)","τ":"(2 * Math.PI)","∞":"Infinity","-∞":"(-Infinity)"},ys={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})`},xs={atan2:2,pow:2,mod:2,step:2,clamp:3,mix:3,smoothstep:3},bs={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},ws=(t,e)=>({kind:t,c:e}),_s=t=>ws("f",[t]),Ms=t=>ws("b",[t]),vs=t=>1===t.length?_s(t[0]):ws("v",t),As=(t,e=0)=>"b"===t.kind?`(${t.c[0]} ? 1 : 0)`:"f"===t.kind?t.c[0]:t.c[e]??t.c[0],Es=t=>"v"===t.kind?t.c.length:1;class Ns extends Error{}function Os(t){if(t.blendKept)return{blend:!0,source:""};const e=t.params??{},n=new Set([...Object.keys(t.placements??{}),"source","selection"]),s=new Is(e,n,t.space??"srgb");s.graphics=new Set(Object.keys(t.graphics??{})),s.bind=t.bind??{};const r="string"==typeof t.color?{rgba:t.color}:t.color,o=(s,r)=>Sn(function(t,e={}){const n=Me(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:[...On,...Object.keys(t.placements??{})],values:[...An,...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=o(r[t],"rgba"===t)}catch(t){throw new Ns(t.message)}s.channel(t,e)}const i=s.source();!function(t,e={}){if("string"!=typeof t)throw new ve("generated code must be a string");const n=t;for(const e of Se)t=t.split(e).join("Math.abs");const s=!1!==e.keywords,r=e.variables instanceof RegExp?e.variables:new Set(e.variables??[]),o=t=>r instanceof RegExp?r.test(t):r.has(t),i=e.indexable instanceof RegExp?e.indexable:null;let a=null,l=0;const c=t=>{throw new ve(`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}const h=/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(n);if(h&&(!a||"id"!==a.type||!/[\w$]$/.test(t[l-1]??""))){a={type:"num",value:h[0]},l+=h[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 u=/^[A-Za-z_$][\w$]*/.exec(n);if(u){const t=u[0];if(a&&"p"===a.type&&"."===a.value){const e=a.owner;(e&&Ne[e]?Ne[e].has(t):Ee.has(t)&&!Ae.has(t))||c(`.${t}`)}else Oe.has(t)||s&&Ie.has(t)||o(t)||c(`the name "${t}"`);a={type:"id",value:t},l+=t.length;continue}const $=ke.find(t=>n.startsWith(t));$||c(`"${n[0]}"`),"["!==$||!p()||i&&"id"===a.type&&o(a.value)&&i.test(a.value)||c("indexing with [ ]");const m={type:"p",value:$};"."===$&&(p()||c('a "." here'),m.owner="id"===a.type&&Ne[a.value]?a.value:null),a=m,l+=$.length}}(i,{variables:/^\$\w+$/,indexable:/^\$[A-Z]\w*$/,strings:!1});const a=new Function(...s.parameters(),i);return{source:i,uses:s.uses,pictures:[...s.pictureNames],run(t){a(...s.arguments(t))}}}class Is{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 ws(t.kind,t.c.map(t=>/^[\w$.]+$|^\(?-?[\d.e+]+\)?$/.test(t)?t:this.temp(t,e)))}fail(t){throw new Ns(t)}leaf(t){if("number"===t.type)return _s(`(${t.value.replace(/\.+$/,"")})`);"string"===t.type&&this.fail("a filter has no text: numbers and colours only");const e=t.value;if("t"===e&&this.uses.add("t"),gs[e])return _s(gs[e]);if("rgb"===e)return vs(["$r","$g","$b"]);if("unchanged"===e)return _s("$u");if("selected"===e)return _s(this.pictureHere("selection").c[0]);if(ds[e])return _s(ds[e]);if("true"===e||"false"===e)return Ms(e);if(Object.prototype.hasOwnProperty.call(this.params,e)){const t=`$p_${e}`;return"color"===this.params[e].type?vs([`${t}_0`,`${t}_1`,`${t}_2`]):_s(t)}if(this.pictures.has(e)){const t=this.pictureHere(e);return vs(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});`),vs([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(ms)?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(),ys.mod);case"<":case">":case"≤":case"≥":{const[t,n]=r(),s={"≤":"<=","≥":">="}[e]??e;return Ms(`(${As(t)} ${s} ${As(n)})`)}case"=":case"===":case"≠":case"≠=":case"≡":{const[t,n]=r(),s=Math.max(Es(t),Es(n)),o=Array.from({length:s},(e,s)=>`${As(t,s)} === ${As(n,s)}`).join(" && ");return Ms("≠"===e||"≠="===e?`!(${o})`:`(${o})`)}case"≈":{const[t,e]=r();return Ms(`(Math.abs(${As(t)} - ${As(e)}) < 1e-5)`)}case"&":{const[t,e]=r();return Ms(`(${this.truth(t)} && ${this.truth(e)})`)}case"|":{const[t,e]=r();return Ms(`(${this.truth(t)} || ${this.truth(e)})`)}case"\\xor":{const[t,e]=r();return Ms(`(${this.truth(t)} !== ${this.truth(e)})`)}case"\\nand":{const[t,e]=r();return Ms(`!(${this.truth(t)} && ${this.truth(e)})`)}case"\\nor":{const[t,e]=r();return Ms(`!(${this.truth(t)} || ${this.truth(e)})`)}case"\\not":{const[t]=r();return Ms(`!${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?[As(t)]:t.c.map((e,n)=>As(t,n)));return t.length>4&&this.fail("a colour has at most 4 values (r, g, b, a)"),vs(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)=>`(Math.floor(${t} * Math.pow(10, ${e}) + 0.5) / Math.pow(10, ${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(ys[e])return this.builtin(e,r());this.fail(`"${e}" isn't available in a filter`)}truth(t){return"b"===t.kind?t.c[0]:`(${As(t)} !== 0)`}componentwise(t,e){const n=t.map(Es),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 o=Array.from({length:s},(n,s)=>e(...t.map(t=>As(t,s))));return this.keep(vs(o))}builtin(t,e){const n=ys[t];if(xs[t]&&e.length!==xs[t]&&this.fail(`${t}() takes ${xs[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 o=r(e)?null:this.value(e),i=r(n)?null:this.value(n);const a=t=>"b"===t.kind?Ms("($u > 0.5)"):"f"===t.kind?_s("$u"):vs(["$k0","$k1","$k2","$k3"].slice(0,4===t.c.length?4:3));if(!o&&!i)return _s("$u");if(o||(o=a(i)),i||(i=a(o)),"b"===o.kind&&"b"===i.kind)return Ms(this.temp(`(${s} ? ${o.c[0]} : ${i.c[0]})`));const l=Math.max(Es(o),Es(i)),c=Array.from({length:l},(t,e)=>this.temp(`(${s} ? ${As(o,e)} : ${As(i,e)})`));return vs(c)}membership(t){const[e,n]=t.args,s=As(this.value(e)),r="∉"===t.op;let o;if("op"===n.type&&["()","[]","(]","[)"].includes(n.op)&&2===n.args.length){const[t,e]=n.args.map(t=>As(this.value(t)));o=`(${s} ${"["===n.op[0]?">=":">"} ${t} && ${s} ${"]"===n.op[1]?"<=":"<"} ${e})`}else"op"===n.type&&"{}"===n.op?o=`(${n.args.map(t=>`${s} === ${As(this.value(t))}`).join(" || ")})`:"symbol"===n.type&&["ℝ","ℤ","ℕ"].includes(n.value)?o={"ℝ":`Number.isFinite(${s})`,"ℤ":`Number.isInteger(${s})`,"ℕ":`(Number.isInteger(${s}) && ${s} > 0)`}[n.value]:this.fail("∈ needs an interval [a, b], a set {…}, ℝ, ℤ or ℕ");return Ms(r?`!${o}`:o)}random(){return this.uses.add("random"),_s(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(),[o,i]=r?[As(n),As(r)]:[As(n,0),As(n,1)];if("image"===e){const t=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${o}, ${i}, ${t});`),this.keep(vs([0,1,2,3].map(e=>`${t}[${e}]`)))}return this.pictures.has(e)||this.fail(`unknown picture "${e}"`),this.keep(this.sampler(e,o,i))}if(t.startsWith("mz_at_")){const e=t.slice(6),[n,r]=s(),[o,i]=r?[As(n),As(r)]:[As(n,0),As(n,1)];if("image"===e){const t=this.scratchArray();return this.body.push(`$h_sampleOrZero($I, $w, $h, ${o}, ${i}, ${t});`),vs([0,1,2].map(e=>`${t}[${e}]`))}return this.pictures.has(e)||this.fail(`unknown picture "${e}"`),this.keep(vs(this.sampler(e,o,i).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),_s(t.startsWith("mz_width_")?`$qw_${e}`:`$qh_${e}`)}switch(t){case"pixel":{const[t,e]=s().map(t=>As(t)),n=this.scratchArray();return this.body.push(`$h_sample($I, $w, $h, ${t}, ${e}, ${n});`),this.keep(vs([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?_s(`(${As(n,0)} * 0.299 + ${As(n,1)} * 0.587 + ${As(n,2)} * 0.114)`):"alpha"===t&&3===Es(n)?_s("1"):_s(As(n,s))}case"length":{const[t]=s();return _s(`Math.sqrt(${t.c.map((e,n)=>`${As(t,n)} * ${As(t,n)}`).join(" + ")})`)}case"distance":{const[t,e]=s(),n=this.componentwise([t,e],(t,e)=>`(${t} - ${e})`);return _s(`Math.sqrt(${n.c.map(t=>`${t} * ${t}`).join(" + ")})`)}case"dot":{const[t,e]=s(),n=Math.max(Es(t),Es(e));return _s(`(${Array.from({length:n},(n,s)=>`${As(t,s)} * ${As(e,s)}`).join(" + ")})`)}case"normalize":{const[t]=s(),e=this.temp(`Math.sqrt(${t.c.map((e,n)=>`${As(t,n)} * ${As(t,n)}`).join(" + ")})`);return this.componentwise([t],t=>`(${t} / ${e})`)}case"cross":{const[t,e]=s();3===Es(t)&&3===Es(e)||this.fail("cross() takes two colours (3 values each)");const[n,r,o]=t.c,[i,a,l]=e.c;return this.keep(vs([`(${r} * ${l} - ${o} * ${a})`,`(${o} * ${i} - ${n} * ${l})`,`(${n} * ${a} - ${r} * ${i})`]))}case"convolve":{const t=s().map(t=>As(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});`),vs([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=>As(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=>As(t)):[0,1,2].map(t=>As(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(vs([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(bs[t])return this.neighbourhood(t,e);this.fail(`unknown function "${t}"`)}geometry(t,e){const n=(t,e)=>this.keep(vs([t,e]));switch(t){case"zoom":{const[t,s="0.5",r="0.5"]=e,o=n(`(${s} * $w - 0.5)`,`(${r} * $h - 0.5)`);return n(`(${o.c[0]} + ($px - ${o.c[0]}) / ${t})`,`(${o.c[1]} + ($py - ${o.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,o=n(`(${s} * $w - 0.5)`,`(${r} * $h - 0.5)`),i=n(`($px - ${o.c[0]})`,`($py - ${o.c[1]})`),a=this.keep(vs([`Math.cos(${t})`,`Math.sin(${t})`]));return n(`(${o.c[0]} + ${a.c[0]} * ${i.c[0]} + ${a.c[1]} * ${i.c[1]})`,`(${o.c[1]} + ${a.c[0]} * ${i.c[1]} - ${a.c[1]} * ${i.c[0]})`)}case"crop":{const[t,s,r,o]=e;return n(`((${t} + (${r} - ${t}) * ($px + 0.5) / $w) * $w - 0.5)`,`((${s} + (${o} - ${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=bs[t];if(e.every(t=>this.isUniform(t))){const s=e.map(t=>As(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 o=this.planes.get(r);return 3===n?vs([0,1,2].map(t=>`${o}[$j3 + ${t}]`)):_s(`${o}[$j]`)}const s=e.map(t=>As(this.value(t)));if(1===n)return _s(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});`),vs([0,1,2].map(t=>`${r}[${t}]`))}isUniform(t){return"number"===t.type||("symbol"===t.type?["w","h","t"].includes(t.value)||Boolean(ds[t.value])||Object.prototype.hasOwnProperty.call(this.params,t.value)&&"color"!==this.params[t.value].type:"op"===t.type&&!t.op.startsWith(ms)&&"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=Es(s),o=t=>As(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?[o(0),o(0),o(0),"1"]:3===r?[o(0),o(1),o(2),"1"]:[0,1,2,3].map(o);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?[o(0),o(0),o(0)]:[o(0),o(1),o(2)];this.body.push(`$c0 = ${t[0]}; $c1 = ${t[1]}; $c2 = ${t[2]};`)}else{const e="rgba".indexOf(t),n=1===r?o(0):3===r&&"a"===t?"1":o(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}`]),...fs.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)?Rn:qn),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),Tn(s.place)]}),...fs.map(t=>$s[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 Ss="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 ks=[];const js={};let qs=null,Rs=null;Ss.on(t=>{try{if("init"===t.type)ks=t.passes.map(t=>Os(t)),Ss.post({id:t.id,ok:!0});else if("picture"===t.type)"source"===t.name?qs=t.picture:js[t.name]=t.picture,Ss.post({id:t.id,ok:!0});else if("run"===t.type){const{width:e,height:n,y0:s,y1:r}=t,o=e*n*4,i=t.output??(Rs&&Rs.length===o?Rs:Rs=new Float32Array(o));ks[t.pass].run({input:t.input,output:i,source:qs.data,width:e,height:n,t:t.t,params:t.params,opacity:t.opacity,pictures:js,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=i[t];i[t]=e>0?e<1?Math.round(255*e)/255:1:0}if(t.output)Ss.post({id:t.id,ok:!0});else{const e=i.slice(a,l);Ss.post({id:t.id,ok:!0,band:e},[e.buffer])}}}catch(e){Ss.post({id:t.id,ok:!1,error:e.message})}});